blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
201
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 7
100
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 260
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 11.4k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 17
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 80
values | src_encoding
stringclasses 28
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 8
9.86M
| extension
stringclasses 52
values | content
stringlengths 8
9.86M
| authors
listlengths 1
1
| author
stringlengths 0
119
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d13703d753e8b4d43cccbd529f7fc0878c21b293 | fb9723dd49f6c3d08007607abb56aac46e914d52 | /mods/mod_cavebot/StdAfx.cpp | d1abdcc5c02766bc26559ceabe4015625678c673 | [] | no_license | zekoman/tibiaauto | 4b4a2c469e68bb3393a60ebd737866f0bcb90f2b | 9395d210fc3cb177f77f6421af37d3977cfb8e71 | refs/heads/master | 2020-04-12T22:45:14.424621 | 2012-07-14T17:29:21 | 2012-07-14T17:29:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 205 | cpp | // stdafx.cpp : source file that includes just the standard includes
// mod_cavebot.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
| [
"[email protected]"
] | |
60c74f63ba47df4782befb6113d5b3693e379bb7 | ec3184b57577effad1a982c903298c0e511b5a4b | /C/CProgramming/C3rdWeek/ConsoleColorChange.cpp | 067a599f5f19c434a74ff600b6f1d01a45740c56 | [] | no_license | BckLily/yeilGroupStudy | 6535c58922407e0256874bfade305f46541e1e09 | 3e30c19a771baab23636591f28e3d26bd51ae072 | refs/heads/main | 2023-07-17T23:03:55.500076 | 2021-08-29T08:18:39 | 2021-08-29T08:18:39 | 393,947,582 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 545 | cpp | #include "ConsoleColorChange.h"
// Console Font Change
void FontColorChange(unsigned short textColor, unsigned short backColor) {
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), textColor | (backColor << 4));
}
//"mode con cols=30 lines=30 | title ?쒕ぉ紐?
void ConsoleWindowSize(unsigned short cols, unsigned short lines)
{
// string variable ... std::to_string()
std::string s_format = "mode con cols=" + std::to_string(cols) + "lines=" + std::to_string(lines);
// string??char*濡?蹂寃?
system(s_format.c_str());
}
| [
"[email protected]"
] | |
32f266e25edad8c7a1dec51de1bff3bd6d248b48 | b312a8b60827cff6c7db3538785197c0ac643671 | /source/cortex-m4/test-rtos/application/hwtimer.h | b6492454b4d904f039864203bf787cc52a98ae71 | [] | no_license | sigmadrone/sigmadrone | 8a05f0d04612e82d5fd50d067e0aa86aa20b2d9f | 662c0fd5e09d3fcf9d5a9cd9fb147700161ad731 | refs/heads/master | 2021-01-23T20:43:45.388369 | 2018-10-07T23:32:41 | 2018-10-07T23:32:41 | 36,966,425 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,451 | h | /*
* HwTimer.h
*
* Created on: Jan 13, 2015
* Author: svetlio
*/
#ifndef TEST_PRINTF_HWTIMER_H_
#define TEST_PRINTF_HWTIMER_H_
#include "stm32f4xx_hal.h"
#include "functionptr.h"
#include <cassert>
#include <vector>
#include "units.h"
#include "gpiopin.h"
class HwTimer {
public:
enum Mode {
MODE_NOT_INITIALIZED,
MODE_BASIC,
MODE_PWM_DECODE,
MODE_PWM_ENCODE
};
enum Id {
TIMER_INVALID, TIMER_1, TIMER_2, TIMER_3, TIMER_4, TIMER_5, TIMER_6, TIMER_7, TIMER_8,
TIMER_9, TIMER_10, TIMER_11, TIMER_12, TIMER_13, TIMER_14, TIMER_LAST
};
static const uint32_t INVALID_CHANNEL_NO = 0xffffffff;
/** Constructs and initializes a timer instance
* @param timer_id Id of the timer to be used
* @param period Desired timer period
* @param timer_clock At what frequency the timer will be clocked
* @param interrupt_callback Callback to be invoked when timer event happens
*/
HwTimer(Id timer_id,
const TimeSpan& period,
const Frequency& timer_clock = Frequency::from_kilohertz(10),
const FunctionPointer& interruptCallback = FunctionPointer());
/** Initializes the timer to be used as a simple counter or in slave mode
* The period will be set to the max value
* @param timer_id Id of the timer to be used
* @param timer_clock At what frequency the timer will be clocked
* @param interrupt_callback Callback to be invoked when timer event happens
*/
HwTimer(Id timer_id,
const Frequency& timer_clock,
const FunctionPointer& interrupt_callback = FunctionPointer());
virtual ~HwTimer();
/** Starts the timer in basic mode. The routine will implicitly stop the timer if
* it is currently ticking. Upon successful execution the timer will be in
* MODE_PWM_BASIC
* @returns true - success, false - failure
*/
bool start();
/** Starts the timer in PWM decode/input/capture mode. Implicitly stop the timer if
* it is currently ticking. Upon successful execution the timer will be in
* MODE_PWM_DECODE
*
* @returns true - success, false - failure
*/
bool start_pwm_decode_mode();
/** Starts the timer in PWM encode mode. Implicitly stops the timer if
* it is currently ticking. Upon successful execution the timer will be in
* MODE_PWM_ENCODE
*
* @returns true - success, false - failure
*/
bool start_pwm_encode_mode(const std::vector<uint32_t>& channels);
/** Stops the timer. After this call the timer will be in MODE_NOT_INITIALIZED
*/
void stop();
/** Sets new timer period value. Note: do not call this routine if the timer is started
* @param period The new value will take effect after the timer was restarted.
*/
void set_period(const TimeSpan& period) { period_ = period; }
/** Sets the desired timer clock. Note: do not call this routine if the timer is started
* @param timer_clock The new value will take effect after the timer was restarted.
*/
void set_timer_clock(const Frequency& timer_clock);
/** Returns the elapsed interval since the timer was zeroed out
* @returns Elapsed time interval
*/
TimeSpan time_elapsed() const;
/** Returns the current timer counter value
* @returns Timer counter value
*/
uint32_t current_counter_value() const;
/** Returns the configured timer period
* @returns Timer period
*/
inline const TimeSpan& period() const { return period_; }
/** Returns the timer Id
* @returns Timer Id
*/
inline Id timerid() const { return timer_id_; }
/** Returns the current mode of operation
* @returns Mode of operation
*/
inline Mode mode() const { return mode_; }
/** Returns the timer input clock
* @returns The timer input clock, prior to pre-scaler and divider
*/
inline Frequency input_clock() { return get_timx_input_clock(timer_id_); }
/** Returns the captured value from the specified channel
* @param channel Channel number to be queried, value must be in the range [1..4]
* @returns The current captured value
*/
uint32_t read_captured_value(uint32_t channel);
/** Returns the actual timer clock
* @returns Returns the clock at which the timer ticks.
*/
Frequency timer_clock() const { return timer_clock_; }
/** Sets the duty cycle on the specified channel. Timer must be configured
* in MODE_PWM_ENCODE
* @param channel_no Channel number [1..4]
* @param pulse_period Lenght of the duty cycle, must be LEQ than the timer period
*/
bool set_pwm_duty_cycle(uint32_t channel_no, const TimeSpan& pulse_period);
inline uint64_t period_elapsed_count() const { return period_elapsed_cnt_; }
/** Returns the timer input clock for any of the timers
* @param timer_id Timer ID
* @returns Timer input clock, prior to pre-scaler and divider
*/
static Frequency get_timx_input_clock(Id timer_id);
/** Returns alternative function number for the specified timer id
* @param timer_id Timer ID
* @returns The corresponding alternative function number
*/
static uint32_t get_gpio_altfunc(Id timer_id);
private:
friend void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *handle);
friend void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *handle);
void on_period_elapsed();
TIM_HandleTypeDef* init_handle();
static uint32_t get_timx_channel(uint32_t channel_no);
private:
Id timer_id_;
TimeSpan period_;
Frequency timer_clock_;
FunctionPointer callback_;
Mode mode_;
std::vector<uint32_t> channels_;
volatile uint64_t period_elapsed_cnt_;
};
#endif /* TEST_PRINTF_HWTIMER_H_ */
| [
"[email protected]"
] | |
038a4de57c384634827e79c0a0b4422d9cb96bdd | 0a9034344f15e42b57a8ae8e50214a8ef4e3b6ab | /BattleOfFightWar/RangedWeapon.h | 3e237d0c972615bc78e95cbcf7fb5e56853f99bf | [] | no_license | thawhtaik/Battle-of-Fight-War | 27f19119f366a910cfe9dc05ee53d90ded035b82 | ef3db676f65b800d1da76c4abe8a9862f1ec99e6 | refs/heads/master | 2020-05-17T17:55:33.275032 | 2012-03-09T02:02:12 | 2012-03-09T02:02:12 | 3,347,737 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 447 | h | #ifndef _WEAPON_RANGED_
#define _WEAPON_RANGED_
#include "Weapon.h"
#include "Bullet.h"
#include "ProjectileList.h"
#define WEAPON_RANGED_WIND_UP_TIME_NORMAL 1
#define WEAPON_RANGED_MUZZLE_FLASH_OFFSET 0
extern ProjectileList GlobalProjectileList;
class RangedWeapon: public Weapon
{
public:
RangedWeapon(int newAttackPower, int newRange, int newCoolDown);
void attack(WorldObject* Attacker, MapCoordinates TargetPosition);
};
#endif | [
"[email protected]"
] | |
491e50e62555b444cc1edd1982b4b63435c80467 | 6c468d281898335a713f179509eb7f89310a0c14 | /Tower_Defense/TowerDefense/Source/Tile.cpp | 079ae5421f43c9f47ed6d5ea763012cf3c472684 | [] | no_license | Raymenes/Rui_Zeng_Portfolio | 1a258b07126dce6c9234fc3e96aa795bb9e30818 | 9738379f8af7fe3bfe2eefde082da64f418b03ce | refs/heads/master | 2021-01-10T16:11:58.115079 | 2015-12-17T06:02:52 | 2015-12-17T06:02:52 | 43,798,159 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 446 | cpp | //
// Tile.cpp
// Game-mac
//
// Created by Rui Zeng on 10/2/15.
// Copyright © 2015 Sanjay Madhav. All rights reserved.
//
#include "Tile.hpp"
#include "Game.h"
IMPL_ACTOR(Tile, Actor);
Tile::Tile(Game& game)
: Actor(game), isBlocked(false), isPath(false), isSpecial(false)
{
mMeshComponent = MeshComponent::Create(*this);
mMesh = game.GetAssetCache().Load<Mesh>("Meshes/Tile.itpmesh2");
mMeshComponent->SetMesh(mMesh);
} | [
"[email protected]"
] | |
9a132574d50e1a089ad8a777cf886bcc280d5e1f | 74aec8287f60eb75ae6f4dfcb82f7b1b24be8607 | /clangTool/IfInfo.h | 7a9e0518dbb280c38953462d114b47f7c7c646c4 | [
"BSD-2-Clause"
] | permissive | ayushmalikofficial/Hermes | 6849528ebb8d90750503538e918fe1b534fd84c2 | 4bf70ac70f331cb1dfb01be70dae85d4a3bcdf88 | refs/heads/master | 2020-10-01T18:56:42.142693 | 2019-07-26T05:07:33 | 2019-07-26T05:07:33 | 227,603,753 | 1 | 0 | NOASSERTION | 2019-12-12T12:38:42 | 2019-12-12T12:38:41 | null | UTF-8 | C++ | false | false | 974 | h | /*
* Dhriti Khanna ([email protected])
*
* Class for storing 'if' data. Whenever an'if' is encountered, an object of this class is created and
* pushed into the stack being maintained for storing such 'ifs'.
*/
#ifndef IFINFO_H
#define IFINFO_H
#include <vector>
#include <stdio.h>
#include <iostream>
#include <string.h>
#include "CommonUtils.h"
using namespace std;
class IfInfo
{
public:
int rank;
int pid;
std::vector<string> varNames;
int correspondingRecvLineno;
std::vector<Operator> ops;
std::vector<int> literals; // For now we are comparing with only integer values
std::vector<std::pair<int, int> > startEndPositions;
std::vector<int> sendsComingFromIfs;
IfInfo(string varName, Operator op, int dataVal, int start_line_no, int end_line_no, int correspondingRecvLineno, int sendLineNo=-1, int rank=-1, int pid=-1);
IfInfo(string varName, Operator op, int dataVal, int start_line_no, int end_line_no);
IfInfo();
};
#endif
| [
"[email protected]"
] | |
1b9d1d45f6dbdd5a35102be5eefbd7b08e437193 | 603ad7bb3df5a02d222acefec08ce4f94d75409b | /atcoder/sumiD.cpp | d9f4c45367a5a93d6bd41dd23649f474ef790160 | [] | no_license | MijaelTola/icpc | 6fc43aa49f97cf951a2b2fcbd0becd8c895abf36 | ee2629ba087fbe7303743c84b509959f8d3fc9a0 | refs/heads/master | 2023-07-09T00:47:42.812242 | 2021-08-08T00:44:10 | 2021-08-08T00:44:10 | 291,160,127 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 883 | cpp | #include <bits/stdc++.h>
using namespace std;
int n;
string s;
vector<int> v[11];
int main() {
cin >> n >> s;
for (int i = 0; i < n; ++i)
v[s[i] - '0'].push_back(i);
int ans = 0;
for (int i = 0; i < 100; ++i) {
string x = to_string(i);
while(x.size() < 2) x = "0" + x;
int a = 0, b = 0;
while(a < n and b < (int)x.size()) {
if(s[a] == x[b]) a++, b++;
else a++;
}
if(a == n) continue;
for (int i = 0; i < 10; ++i) {
if(!v[i].size()) continue;
int l = -1, r = v[i].size();
while(r - l > 1) {
int mid = (l + r) / 2;
if(v[i][mid] >= a) r = mid;
else l = mid;
}
ans += (r < (int)v[i].size());
}
}
cout << ans << "\n";
return 0;
}
| [
"[email protected]"
] | |
63d8c6de73fd35da1e4c63de6cd42b70578eca25 | 867748c43510579840e061f2fa23ce46f6d7c87c | /code/server/epoller.cpp | b97b026aa58ea310fd632b0980829b9b91fedf61 | [] | no_license | IceCream-jy/HTTPWebServer | 22c45689deab9b2517e0bae345ef6df3f8517cdb | 9b845b0958b3ade170f20ea6d729ad45c1d1a2ef | refs/heads/main | 2023-05-29T09:39:19.996463 | 2021-06-04T01:27:28 | 2021-06-04T01:27:28 | 346,352,459 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,137 | cpp | #include "epoller.hh"
Epoller::Epoller(int maxEvent):epollFd_(epoll_create(512)), events_(maxEvent){
assert(epollFd_ >= 0 && events_.size() > 0);
}
Epoller::~Epoller() {
close(epollFd_);
}
bool Epoller::AddFd(int fd, uint32_t events) {
if(fd < 0) return false;
epoll_event ev = {0};
ev.data.fd = fd;
ev.events = events;
return 0 == epoll_ctl(epollFd_, EPOLL_CTL_ADD, fd, &ev);
}
bool Epoller::ModFd(int fd, uint32_t events) {
if(fd < 0) return false;
epoll_event ev = {0};
ev.data.fd = fd;
ev.events = events;
return 0 == epoll_ctl(epollFd_, EPOLL_CTL_MOD, fd, &ev);
}
bool Epoller::DelFd(int fd) {
if(fd < 0) return false;
epoll_event ev = {0};
return 0 == epoll_ctl(epollFd_, EPOLL_CTL_DEL, fd, &ev);
}
int Epoller::Wait(int timeoutMs) {
return epoll_wait(epollFd_, &events_[0], static_cast<int>(events_.size()), timeoutMs);
}
int Epoller::GetEventFd(size_t i) const {
assert(i < events_.size() && i >= 0);
return events_[i].data.fd;
}
uint32_t Epoller::GetEvents(size_t i) const {
assert(i < events_.size() && i >= 0);
return events_[i].events;
} | [
"[email protected]"
] | |
7cc3015cd2b5956133dc26662e79c2b5886917df | 501591e4268ad9a5705012cd93d36bac884847b7 | /src/server/game/Grids/GridDefines.h | 4eef48579399f5bee0ad1c2c6c706f74ebc7e817 | [] | no_license | CryNet/MythCore | f550396de5f6e20c79b4aa0eb0a78e5fea9d86ed | ffc5fa1c898d25235cec68c76ac94c3279df6827 | refs/heads/master | 2020-07-11T10:09:31.244662 | 2013-06-29T19:06:43 | 2013-06-29T19:06:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,910 | h | /*
* Copyright (C) 2008 - 2011 Trinity <http://www.trinitycore.org/>
*
* Copyright (C) 2010 - 2012 Myth Project <http://mythprojectnetwork.blogspot.com/>
*
* Myth Project's source is based on the Trinity Project source, you can find the
* link to that easily in Trinity Copyrights. Myth Project is a private community.
* To get access, you either have to donate or pass a developer test.
* You may not share Myth Project's sources! For personal use only.
*/
#ifndef TRINITY_GRIDDEFINES_H
#define TRINITY_GRIDDEFINES_H
#include "Common.h"
#include "NGrid.h"
#include <cmath>
// Forward class definitions
class Corpse;
class Creature;
class DynamicObject;
class GameObject;
class Pet;
class Player;
#define MAX_NUMBER_OF_CELLS 8
#define MAX_NUMBER_OF_GRIDS 64
#define SIZE_OF_GRIDS 533.33333f
#define CENTER_GRID_ID (MAX_NUMBER_OF_GRIDS/2)
#define CENTER_GRID_OFFSET (SIZE_OF_GRIDS/2)
#define MIN_GRID_DELAY (MINUTE*IN_MILLISECONDS)
#define MIN_MAP_UPDATE_DELAY 50
#define SIZE_OF_GRID_CELL (SIZE_OF_GRIDS/MAX_NUMBER_OF_CELLS)
#define CENTER_GRID_CELL_ID (MAX_NUMBER_OF_CELLS*MAX_NUMBER_OF_GRIDS/2)
#define CENTER_GRID_CELL_OFFSET (SIZE_OF_GRID_CELL/2)
#define TOTAL_NUMBER_OF_CELLS_PER_MAP (MAX_NUMBER_OF_GRIDS*MAX_NUMBER_OF_CELLS)
#define MAP_RESOLUTION 128
#define MAP_SIZE (SIZE_OF_GRIDS*MAX_NUMBER_OF_GRIDS)
#define MAP_HALFSIZE (MAP_SIZE/2)
// Creature used instead pet to simplify *::Visit templates (not required duplicate code for Creature->Pet case)
typedef TYPELIST_4(Player, Creature/*pets*/, Corpse/*resurrectable*/, DynamicObject/*farsight target*/) AllWorldObjectTypes;
typedef TYPELIST_4(GameObject, Creature/*except pets*/, DynamicObject, Corpse/*Bones*/) AllGridObjectTypes;
typedef GridRefManager<Corpse> CorpseMapType;
typedef GridRefManager<Creature> CreatureMapType;
typedef GridRefManager<DynamicObject> DynamicObjectMapType;
typedef GridRefManager<GameObject> GameObjectMapType;
typedef GridRefManager<Player> PlayerMapType;
typedef Grid<Player, AllWorldObjectTypes, AllGridObjectTypes> GridType;
typedef NGrid<MAX_NUMBER_OF_CELLS, Player, AllWorldObjectTypes, AllGridObjectTypes> NGridType;
typedef TypeMapContainer<AllGridObjectTypes> GridTypeMapContainer;
typedef TypeMapContainer<AllWorldObjectTypes> WorldTypeMapContainer;
template<const unsigned int LIMIT>
struct CoordPair
{
CoordPair(uint32 x=0, uint32 y=0) : x_coord(x), y_coord(y) { }
CoordPair(const CoordPair<LIMIT> &obj) : x_coord(obj.x_coord), y_coord(obj.y_coord) { }
bool operator == (const CoordPair<LIMIT> &obj) const { return (obj.x_coord == x_coord && obj.y_coord == y_coord); }
bool operator != (const CoordPair<LIMIT> &obj) const { return !operator == (obj); }
CoordPair<LIMIT>& operator=(const CoordPair<LIMIT> &obj)
{
x_coord = obj.x_coord;
y_coord = obj.y_coord;
return *this;
}
void operator<<(const uint32 val)
{
if(x_coord > val)
x_coord -= val;
else
x_coord = 0;
}
void operator>>(const uint32 val)
{
if(x_coord+val < LIMIT)
x_coord += val;
else
x_coord = LIMIT - 1;
}
void operator-=(const uint32 val)
{
if(y_coord > val)
y_coord -= val;
else
y_coord = 0;
}
void operator+=(const uint32 val)
{
if(y_coord+val < LIMIT)
y_coord += val;
else
y_coord = LIMIT - 1;
}
uint32 x_coord;
uint32 y_coord;
};
typedef CoordPair<MAX_NUMBER_OF_GRIDS> GridPair;
typedef CoordPair<TOTAL_NUMBER_OF_CELLS_PER_MAP> CellPair;
namespace Trinity
{
template<class RET_TYPE, int CENTER_VAL>
inline RET_TYPE Compute(float x, float y, float center_offset, float size)
{
// calculate and store temporary values in double format for having same result as same mySQL calculations
double x_offset = (double(x) - center_offset)/size;
double y_offset = (double(y) - center_offset)/size;
int x_val = int(x_offset+CENTER_VAL + 0.5);
int y_val = int(y_offset+CENTER_VAL + 0.5);
return RET_TYPE(x_val, y_val);
}
inline GridPair ComputeGridPair(float x, float y)
{
return Compute<GridPair, CENTER_GRID_ID>(x, y, CENTER_GRID_OFFSET, SIZE_OF_GRIDS);
}
inline CellPair ComputeCellPair(float x, float y)
{
return Compute<CellPair, CENTER_GRID_CELL_ID>(x, y, CENTER_GRID_CELL_OFFSET, SIZE_OF_GRID_CELL);
}
inline CellPair ComputeCellPair(float x, float y, float &x_off, float &y_off)
{
double x_offset = (double(x) - CENTER_GRID_CELL_OFFSET)/SIZE_OF_GRID_CELL;
double y_offset = (double(y) - CENTER_GRID_CELL_OFFSET)/SIZE_OF_GRID_CELL;
int x_val = int(x_offset + CENTER_GRID_CELL_ID + 0.5);
int y_val = int(y_offset + CENTER_GRID_CELL_ID + 0.5);
x_off = (float(x_offset) - x_val + CENTER_GRID_CELL_ID) * SIZE_OF_GRID_CELL;
y_off = (float(y_offset) - y_val + CENTER_GRID_CELL_ID) * SIZE_OF_GRID_CELL;
return CellPair(x_val, y_val);
}
inline void NormalizeMapCoord(float &c)
{
if(c > MAP_HALFSIZE - 0.5)
c = MAP_HALFSIZE - 0.5;
else if(c < -(MAP_HALFSIZE - 0.5))
c = -(MAP_HALFSIZE - 0.5);
}
inline bool IsValidMapCoord(float c)
{
return finite(c) && (std::fabs(c) <= MAP_HALFSIZE - 0.5);
}
inline bool IsValidMapCoord(float x, float y)
{
return IsValidMapCoord(x) && IsValidMapCoord(y);
}
inline bool IsValidMapCoord(float x, float y, float z)
{
return IsValidMapCoord(x, y) && finite(z);
}
inline bool IsValidMapCoord(float x, float y, float z, float o)
{
return IsValidMapCoord(x, y, z) && finite(o);
}
}
#endif
| [
"[email protected]"
] | |
f72446aa7c13fd6262a06f20e418f8cdeed9f8b9 | dddc4c4446efe13ecf66216f94f03f61ca343a4d | /higan/hiro/gtk/widget/radio-button.hpp | f1e77ead71c1878f5956615afe076f955768ee66 | [] | no_license | RianKatoen/Higan-Core | 65fdda51b89f04b437373387e83d507c0b1de0d1 | 62e39877da4bba23356cb65bc7c6dc6f0925bdc3 | refs/heads/master | 2023-03-25T13:09:20.181034 | 2021-02-22T21:32:56 | 2021-02-22T21:32:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 456 | hpp | #if defined(Hiro_RadioButton)
namespace hiro {
struct pRadioButton : pWidget {
Declare(RadioButton, Widget)
auto minimumSize() const -> Size;
auto setBordered(bool bordered) -> void;
auto setChecked() -> void;
auto setGroup(sGroup group) -> void;
auto setImage(const Image& image) -> void;
auto setOrientation(Orientation orientation) -> void;
auto setText(const string& text) -> void;
auto groupLocked() const -> bool;
};
}
#endif
| [
"[email protected]"
] | |
e4a515c9465c9ad5331205b9b95b4d8095ceef27 | 92d32b057d2b9b94694c97eaefa4d9967b97265d | /Quartz Composer Interface /OSCMinuit/ip/UdpSocket.cpp | 48958f06abb33b24c04907567c0f76a11f80d624 | [
"Unlicense"
] | permissive | Minuit/minuit | 153db9cd216b54d30b0b43969e34a513448d0384 | 247dc9663b483434d0282423996c172669c3bb71 | refs/heads/master | 2020-12-09T14:59:16.544377 | 2017-02-24T17:14:44 | 2017-02-24T17:14:44 | 15,773,165 | 17 | 2 | null | 2014-11-04T14:37:05 | 2014-01-09T17:06:49 | Max | UTF-8 | C++ | false | false | 15,749 | cpp | /*
oscpack -- Open Sound Control packet manipulation library
http://www.audiomulch.com/~rossb/oscpack
Copyright (c) 2004-2005 Ross Bencina <[email protected]>
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.
Any person wishing to distribute modifications to the Software is
requested to send the modifications to the original developer so that
they can be incorporated into the canonical version.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "../ip/UdpSocket.h"
#include <vector>
#include <algorithm>
#include <stdexcept>
#include <assert.h>
#include <signal.h>
#include <math.h>
#include <errno.h>
#include <string.h> // for memset
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h> // for sockaddr_in
#include "../ip/PacketListener.h"
#include "../ip/TimerListener.h"
#if defined(__APPLE__) && !defined(_SOCKLEN_T)
// pre system 10.3 didn have socklen_t
typedef ssize_t socklen_t;
#endif
static void SockaddrFromIpEndpointName( struct sockaddr_in& sockAddr, const IpEndpointName& endpoint )
{
memset( (char *)&sockAddr, 0, sizeof(sockAddr ) );
sockAddr.sin_family = AF_INET;
sockAddr.sin_addr.s_addr =
(endpoint.address == IpEndpointName::ANY_ADDRESS)
? INADDR_ANY
: htonl( endpoint.address );
sockAddr.sin_port =
(endpoint.port == IpEndpointName::ANY_PORT)
? 0
: htons( endpoint.port );
}
static IpEndpointName IpEndpointNameFromSockaddr( const struct sockaddr_in& sockAddr )
{
return IpEndpointName(
(sockAddr.sin_addr.s_addr == INADDR_ANY)
? IpEndpointName::ANY_ADDRESS
: ntohl( sockAddr.sin_addr.s_addr ),
(sockAddr.sin_port == 0)
? IpEndpointName::ANY_PORT
: ntohs( sockAddr.sin_port )
);
}
class UdpSocket::Implementation{
bool isBound_;
bool isConnected_;
int socket_;
struct sockaddr_in connectedAddr_;
struct sockaddr_in sendToAddr_;
public:
Implementation()
: isBound_( false )
, isConnected_( false )
, socket_( -1 )
{
if( (socket_ = socket( AF_INET, SOCK_DGRAM, 0 )) == -1 ){
throw std::runtime_error("unable to create udp socket\n");
}
memset( &sendToAddr_, 0, sizeof(sendToAddr_) );
sendToAddr_.sin_family = AF_INET;
}
~Implementation()
{
if (socket_ != -1) close(socket_);
}
IpEndpointName LocalEndpointFor( const IpEndpointName& remoteEndpoint ) const
{
assert( isBound_ );
// first connect the socket to the remote server
struct sockaddr_in connectSockAddr;
SockaddrFromIpEndpointName( connectSockAddr, remoteEndpoint );
if (connect(socket_, (struct sockaddr *)&connectSockAddr, sizeof(connectSockAddr)) < 0) {
throw std::runtime_error("unable to connect udp socket\n");
}
// get the address
struct sockaddr_in sockAddr;
memset( (char *)&sockAddr, 0, sizeof(sockAddr ) );
socklen_t length = sizeof(sockAddr);
if (getsockname(socket_, (struct sockaddr *)&sockAddr, &length) < 0) {
throw std::runtime_error("unable to getsockname\n");
}
if( isConnected_ ){
// reconnect to the connected address
if (connect(socket_, (struct sockaddr *)&connectedAddr_, sizeof(connectedAddr_)) < 0) {
throw std::runtime_error("unable to connect udp socket\n");
}
}else{
// unconnect from the remote address
struct sockaddr_in unconnectSockAddr;
memset( (char *)&unconnectSockAddr, 0, sizeof(unconnectSockAddr ) );
unconnectSockAddr.sin_family = AF_UNSPEC;
// address fields are zero
int connectResult = connect(socket_, (struct sockaddr *)&unconnectSockAddr, sizeof(unconnectSockAddr));
if ( connectResult < 0 && errno != EAFNOSUPPORT ) {
throw std::runtime_error("unable to un-connect udp socket\n");
}
}
return IpEndpointNameFromSockaddr( sockAddr );
}
void Unconnect()
{
struct sockaddr_in unconnectSockAddr;
memset( (char *)&unconnectSockAddr, 0, sizeof(unconnectSockAddr ) );
unconnectSockAddr.sin_family = AF_UNSPEC;
// address fields are zero
int connectResult = connect(socket_, (struct sockaddr *)&unconnectSockAddr, sizeof(unconnectSockAddr));
if ( connectResult < 0 && errno != EAFNOSUPPORT ) {
throw std::runtime_error("unable to un-connect udp socket\n");
}
isConnected_ = false;
}
void Connect( const IpEndpointName& remoteEndpoint )
{
SockaddrFromIpEndpointName( connectedAddr_, remoteEndpoint );
if (connect(socket_, (struct sockaddr *)&connectedAddr_, sizeof(connectedAddr_)) < 0) {
throw std::runtime_error("unable to connect udp socket\n");
}
isConnected_ = true;
}
void Send( const char *data, int size )
{
assert( isConnected_ );
send( socket_, data, size, 0 );
}
void SendTo( const IpEndpointName& remoteEndpoint, const char *data, int size )
{
sendToAddr_.sin_addr.s_addr = htonl( remoteEndpoint.address );
sendToAddr_.sin_port = htons( remoteEndpoint.port );
sendto( socket_, data, size, 0, (sockaddr*)&sendToAddr_, sizeof(sendToAddr_) );
}
void Bind( const IpEndpointName& localEndpoint )
{
struct sockaddr_in bindSockAddr;
SockaddrFromIpEndpointName( bindSockAddr, localEndpoint );
if (bind(socket_, (struct sockaddr *)&bindSockAddr, sizeof(bindSockAddr)) < 0) {
throw std::runtime_error("unable to bind udp socket\n");
}
isBound_ = true;
}
bool IsBound() const { return isBound_; }
bool IsConnected() const { return isConnected_; }
int ReceiveFrom( IpEndpointName& remoteEndpoint, char *data, int size )
{
assert( isBound_ );
struct sockaddr_in fromAddr;
socklen_t fromAddrLen = sizeof(fromAddr);
int result = recvfrom(socket_, data, size, 0,
(struct sockaddr *) &fromAddr, (socklen_t*)&fromAddrLen);
if( result < 0 )
return 0;
remoteEndpoint.address = ntohl(fromAddr.sin_addr.s_addr);
remoteEndpoint.port = ntohs(fromAddr.sin_port);
return result;
}
int Socket() { return socket_; }
};
UdpSocket::UdpSocket()
{
impl_ = new Implementation();
}
UdpSocket::~UdpSocket()
{
delete impl_;
}
IpEndpointName UdpSocket::LocalEndpointFor( const IpEndpointName& remoteEndpoint ) const
{
return impl_->LocalEndpointFor( remoteEndpoint );
}
void UdpSocket::Connect( const IpEndpointName& remoteEndpoint )
{
impl_->Connect( remoteEndpoint );
}
void UdpSocket::Unconnect()
{
impl_->Unconnect( );
}
void UdpSocket::Send( const char *data, int size )
{
impl_->Send( data, size );
}
void UdpSocket::SendTo( const IpEndpointName& remoteEndpoint, const char *data, int size )
{
impl_->SendTo( remoteEndpoint, data, size );
}
void UdpSocket::Bind( const IpEndpointName& localEndpoint )
{
impl_->Bind( localEndpoint );
}
bool UdpSocket::IsBound() const
{
return impl_->IsBound();
}
bool UdpSocket::IsConnected() const
{
return impl_->IsConnected();
}
int UdpSocket::ReceiveFrom( IpEndpointName& remoteEndpoint, char *data, int size )
{
return impl_->ReceiveFrom( remoteEndpoint, data, size );
}
struct AttachedTimerListener{
AttachedTimerListener( int id, int p, TimerListener *tl )
: initialDelayMs( id )
, periodMs( p )
, listener( tl ) {}
int initialDelayMs;
int periodMs;
TimerListener *listener;
};
static bool CompareScheduledTimerCalls(
const std::pair< double, AttachedTimerListener > & lhs, const std::pair< double, AttachedTimerListener > & rhs )
{
return lhs.first < rhs.first;
}
SocketReceiveMultiplexer *multiplexerInstanceToAbortWithSigInt_ = 0;
extern "C" /*static*/ void InterruptSignalHandler( int );
/*static*/ void InterruptSignalHandler( int )
{
multiplexerInstanceToAbortWithSigInt_->AsynchronousBreak();
signal( SIGINT, SIG_DFL );
}
class SocketReceiveMultiplexer::Implementation{
std::vector< std::pair< PacketListener*, UdpSocket* > > socketListeners_;
std::vector< AttachedTimerListener > timerListeners_;
volatile bool break_;
int breakPipe_[2]; // [0] is the reader descriptor and [1] the writer
double GetCurrentTimeMs() const
{
struct timeval t;
gettimeofday( &t, 0 );
return ((double)t.tv_sec*1000.) + ((double)t.tv_usec / 1000.);
}
public:
Implementation()
{
if( pipe(breakPipe_) != 0 )
throw std::runtime_error( "creation of asynchronous break pipes failed\n" );
}
~Implementation()
{
close( breakPipe_[0] );
close( breakPipe_[1] );
}
void AttachSocketListener( UdpSocket *socket, PacketListener *listener )
{
assert( std::find( socketListeners_.begin(), socketListeners_.end(), std::make_pair(listener, socket) ) == socketListeners_.end() );
// we don't check that the same socket has been added multiple times, even though this is an error
socketListeners_.push_back( std::make_pair( listener, socket ) );
}
void DetachSocketListener( UdpSocket *socket, PacketListener *listener )
{
std::vector< std::pair< PacketListener*, UdpSocket* > >::iterator i =
std::find( socketListeners_.begin(), socketListeners_.end(), std::make_pair(listener, socket) );
assert( i != socketListeners_.end() );
socketListeners_.erase( i );
}
void AttachPeriodicTimerListener( int periodMilliseconds, TimerListener *listener )
{
timerListeners_.push_back( AttachedTimerListener( periodMilliseconds, periodMilliseconds, listener ) );
}
void AttachPeriodicTimerListener( int initialDelayMilliseconds, int periodMilliseconds, TimerListener *listener )
{
timerListeners_.push_back( AttachedTimerListener( initialDelayMilliseconds, periodMilliseconds, listener ) );
}
void DetachPeriodicTimerListener( TimerListener *listener )
{
std::vector< AttachedTimerListener >::iterator i = timerListeners_.begin();
while( i != timerListeners_.end() ){
if( i->listener == listener )
break;
++i;
}
assert( i != timerListeners_.end() );
timerListeners_.erase( i );
}
void Run()
{
break_ = false;
// configure the master fd_set for select()
fd_set masterfds, tempfds;
FD_ZERO( &masterfds );
FD_ZERO( &tempfds );
// in addition to listening to the inbound sockets we
// also listen to the asynchronous break pipe, so that AsynchronousBreak()
// can break us out of select() from another thread.
FD_SET( breakPipe_[0], &masterfds );
int fdmax = breakPipe_[0];
for( std::vector< std::pair< PacketListener*, UdpSocket* > >::iterator i = socketListeners_.begin();
i != socketListeners_.end(); ++i ){
if( fdmax < i->second->impl_->Socket() )
fdmax = i->second->impl_->Socket();
FD_SET( i->second->impl_->Socket(), &masterfds );
}
// configure the timer queue
double currentTimeMs = GetCurrentTimeMs();
// expiry time ms, listener
std::vector< std::pair< double, AttachedTimerListener > > timerQueue_;
for( std::vector< AttachedTimerListener >::iterator i = timerListeners_.begin();
i != timerListeners_.end(); ++i )
timerQueue_.push_back( std::make_pair( currentTimeMs + i->initialDelayMs, *i ) );
std::sort( timerQueue_.begin(), timerQueue_.end(), CompareScheduledTimerCalls );
const int MAX_BUFFER_SIZE = 4098;
char *data = new char[ MAX_BUFFER_SIZE ];
IpEndpointName remoteEndpoint;
struct timeval timeout;
while( !break_ ){
tempfds = masterfds;
struct timeval *timeoutPtr = 0;
if( !timerQueue_.empty() ){
double timeoutMs = timerQueue_.front().first - GetCurrentTimeMs();
if( timeoutMs < 0 )
timeoutMs = 0;
// 1000000 microseconds in a second
timeout.tv_sec = (long)(timeoutMs * .001);
timeout.tv_usec = (long)((timeoutMs - (timeout.tv_sec * 1000)) * 1000);
timeoutPtr = &timeout;
}
if( select( fdmax + 1, &tempfds, 0, 0, timeoutPtr ) < 0 && errno != EINTR ){
throw std::runtime_error("select failed\n");
}
if ( FD_ISSET( breakPipe_[0], &tempfds ) ){
// clear pending data from the asynchronous break pipe
char c;
read( breakPipe_[0], &c, 1 );
}
if( break_ )
break;
for( std::vector< std::pair< PacketListener*, UdpSocket* > >::iterator i = socketListeners_.begin();
i != socketListeners_.end(); ++i ){
if( FD_ISSET( i->second->impl_->Socket(), &tempfds ) ){
int size = i->second->ReceiveFrom( remoteEndpoint, data, MAX_BUFFER_SIZE );
if( size > 0 ){
i->first->ProcessPacket( data, size, remoteEndpoint );
if( break_ )
break;
}
}
}
// execute any expired timers
currentTimeMs = GetCurrentTimeMs();
bool resort = false;
for( std::vector< std::pair< double, AttachedTimerListener > >::iterator i = timerQueue_.begin();
i != timerQueue_.end() && i->first <= currentTimeMs; ++i ){
i->second.listener->TimerExpired();
if( break_ )
break;
i->first += i->second.periodMs;
resort = true;
}
if( resort )
std::sort( timerQueue_.begin(), timerQueue_.end(), CompareScheduledTimerCalls );
}
delete [] data;
}
void Break()
{
break_ = true;
}
void AsynchronousBreak()
{
break_ = true;
// Send a termination message to the asynchronous break pipe, so select() will return
write( breakPipe_[1], "!", 1 );
}
};
SocketReceiveMultiplexer::SocketReceiveMultiplexer()
{
impl_ = new Implementation();
}
SocketReceiveMultiplexer::~SocketReceiveMultiplexer()
{
delete impl_;
}
void SocketReceiveMultiplexer::AttachSocketListener( UdpSocket *socket, PacketListener *listener )
{
impl_->AttachSocketListener( socket, listener );
}
void SocketReceiveMultiplexer::DetachSocketListener( UdpSocket *socket, PacketListener *listener )
{
impl_->DetachSocketListener( socket, listener );
}
void SocketReceiveMultiplexer::AttachPeriodicTimerListener( int periodMilliseconds, TimerListener *listener )
{
impl_->AttachPeriodicTimerListener( periodMilliseconds, listener );
}
void SocketReceiveMultiplexer::AttachPeriodicTimerListener( int initialDelayMilliseconds, int periodMilliseconds, TimerListener *listener )
{
impl_->AttachPeriodicTimerListener( initialDelayMilliseconds, periodMilliseconds, listener );
}
void SocketReceiveMultiplexer::DetachPeriodicTimerListener( TimerListener *listener )
{
impl_->DetachPeriodicTimerListener( listener );
}
void SocketReceiveMultiplexer::Run()
{
impl_->Run();
}
void SocketReceiveMultiplexer::RunUntilSigInt()
{
assert( multiplexerInstanceToAbortWithSigInt_ == 0 ); /* at present we support only one multiplexer instance running until sig int */
multiplexerInstanceToAbortWithSigInt_ = this;
signal( SIGINT, InterruptSignalHandler );
impl_->Run();
signal( SIGINT, SIG_DFL );
multiplexerInstanceToAbortWithSigInt_ = 0;
}
void SocketReceiveMultiplexer::Break()
{
impl_->Break();
}
void SocketReceiveMultiplexer::AsynchronousBreak()
{
impl_->AsynchronousBreak();
}
| [
"[email protected]"
] | |
c5bdd57284863add5acb6e5fa35738990d4541b0 | b4ba3bc2725c8ff84cd80803c8b53afbe5e95e07 | /Test/Test/Dev/Game/Layer/3D/POD3DLayer.cpp | 05b46c378371796208c6f725d36dbaafbde06300 | [
"MIT"
] | permissive | xueliuxing28/Medusa | c4be1ed32c2914ff58bf02593f41cf16e42cc293 | 15b0a59d7ecc5ba839d66461f62d10d6dbafef7b | refs/heads/master | 2021-06-06T08:27:41.655517 | 2016-10-08T09:49:54 | 2016-10-08T09:49:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,436 | cpp | // Copyright (c) 2015 fjz13. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
#include "TestPreCompiled.h"
#include "POD3DLayer.h"
POD3DLayer::POD3DLayer(StringRef name/*=StringRef::Empty*/, const IEventArg& e/*=IEventArg::Empty*/) :BaseCaseLayer(name, e)
{
}
POD3DLayer::~POD3DLayer(void)
{
}
bool POD3DLayer::Initialize()
{
RETURN_FALSE_IF_FALSE(BaseCaseLayer::Initialize());
auto state = this->MutableRenderState().AllocState<RasterizerRenderState>();
state->SetCullMode(GraphicsFace::Back);
state->Enable(true);
auto depthState = this->MutableRenderState().AllocState<DepthStencilRenderState>();
depthState->EnableDepthTest(true);
auto* shape1 = NodeFactory::Instance().CreatePODSprite("Scene.pod");
//shape1->SetAnchor(0.5f, 0.5f);
//shape1->SetDock(DockPoint::MiddleCenter);
AddChild(shape1);
return true;
}
bool POD3DLayer::OnEnter()
{
return true;
/*auto winSize = ResolutionAdapter::Instance().WinSize();
auto camera = CameraFactory::Instance().CreateFromModel("Camera01", "Scene.pod", winSize, false);
IScene* scene = SceneManager::Instance().Current();
scene->SetCamera(camera);
return true;*/
}
bool POD3DLayer::OnExit()
{
IScene* scene = SceneManager::Instance().Current();
auto camera= ResolutionAdapter::Instance().DefaultCamera2D();
scene->SetCamera(camera);
return true;
}
MEDUSA_IMPLEMENT_NODE(POD3DLayer);
| [
"[email protected]"
] | |
db11432de161a30b42c1c1359a054ebac17826b6 | cb30423685deeed8f5720a287a32ce4cd1088563 | /gunrock/src/pr/pr_functor.hxx | 7b05aed514d5cb86b10796ebeb7a930f6908587e | [
"Apache-2.0"
] | permissive | YuxinxinChen/mini | d2dedc6ddb5e1fbc9a23d4b9ad42326147f84e7a | 5fd1a0eafe161ec91acdbeebca410f62edd82195 | refs/heads/master | 2020-12-01T15:35:51.658376 | 2019-12-27T11:29:38 | 2019-12-27T11:29:38 | 230,683,659 | 0 | 0 | Apache-2.0 | 2019-12-29T00:25:48 | 2019-12-29T00:25:47 | null | UTF-8 | C++ | false | false | 1,375 | hxx | #pragma once
#include "pr/pr_problem.hxx"
#include "intrinsics.hxx"
using namespace gunrock::util;
namespace gunrock {
namespace pr {
struct pr_functor_t {
static __device__ __forceinline__ bool cond_filter(int idx, pr_problem_t::data_slice_t *data, int iteration) {
float old_value = data->d_current_ranks[idx];
float new_value = 0.15f + 0.85f * data->d_reduced_ranks[idx];
if (data->d_degrees[idx] > 0)
new_value /= data->d_degrees[idx];
if (!isfinite(new_value)) new_value = 0;
data->d_current_ranks[idx] = new_value;
return (fabs(new_value-old_value) > (0.001f*old_value));
}
static __device__ __forceinline__ bool cond_advance(int src, int dst, int edge_id, int rank, int output_idx, pr_problem_t::data_slice_t *data, int iteration) {
return true;
}
static __device__ __forceinline__ bool apply_advance(int src, int dst, int edge_id, int rank, int output_idx, pr_problem_t::data_slice_t *data, int iteration) {
return true;
}
static __device__ __forceinline__ int get_value_to_reduce(int idx, pr_problem_t::data_slice_t *data, int iteration) {
return (isfinite(data->d_current_ranks[idx]) ? data->d_current_ranks[idx]:0);
}
};
}// end of pr
}// end of gunrock
| [
"[email protected]"
] | |
409b7e111389c82094d6a4bc321fd3d3dda1f101 | fe837dfcc6026d7d2ba7319108598988900c278b | /src/main.h | 0e3fc7b90351c38f715a45d5b5947d418e5b81b4 | [
"MIT"
] | permissive | Peppsycoin/Peppsycoin-Wallet | ebef4539a402c5a75015ef20e0784b31cdc6d450 | 3af7ca9b3625649921dc2c65ff37a204e304fd79 | refs/heads/master | 2016-09-06T10:52:19.805566 | 2016-02-02T19:16:16 | 2016-02-02T19:16:16 | 34,880,435 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 44,986 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Litecoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_MAIN_H
#define BITCOIN_MAIN_H
#include "bignum.h"
#include "net.h"
#include "key.h"
#include "script.h"
#include "db.h"
#include "scrypt.h"
#include <list>
class CWallet;
class CBlock;
class CBlockIndex;
class CKeyItem;
class CReserveKey;
class CAddress;
class CInv;
class CRequestTracker;
class CNode;
// This fix should give some protection agains sudden
// changes of the network hashrate.
// Thanks: https://bitcointalk.org/index.php?topic=182430.msg1904506#msg1904506
// activated: after block 15000 for all following diff retargeting events
#define COINFIX1_BLOCK (15000)
// for now, we leave the block size at 1 MB, meaning we support roughly 2400 transactions
// per block, which means about 160 tps
static const unsigned int MAX_BLOCK_SIZE = 1000000;
static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
static const int64 MIN_TX_FEE = 10000000;
static const int64 MIN_RELAY_TX_FEE = MIN_TX_FEE;
static const int64 MAX_MONEY = 159595959 * COIN; // maximum number of coins
inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
static const int COINBASE_MATURITY = 59;
// Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
#ifdef USE_UPNP
static const int fHaveUPnP = true;
#else
static const int fHaveUPnP = false;
#endif
extern CScript COINBASE_FLAGS;
extern CCriticalSection cs_main;
extern std::map<uint256, CBlockIndex*> mapBlockIndex;
extern uint256 hashGenesisBlock;
extern CBlockIndex* pindexGenesisBlock;
extern int nBestHeight;
extern CBigNum bnBestChainWork;
extern CBigNum bnBestInvalidWork;
extern uint256 hashBestChain;
extern CBlockIndex* pindexBest;
extern unsigned int nTransactionsUpdated;
extern uint64 nLastBlockTx;
extern uint64 nLastBlockSize;
extern const std::string strMessageMagic;
extern double dHashesPerSec;
extern int64 nHPSTimerStart;
extern int64 nTimeBestReceived;
extern CCriticalSection cs_setpwalletRegistered;
extern std::set<CWallet*> setpwalletRegistered;
extern unsigned char pchMessageStart[4];
// Settings
extern int64 nTransactionFee;
extern int64 nMinimumInputValue;
// Minimum disk space required - used in CheckDiskSpace()
static const uint64 nMinDiskSpace = 52428800;
class CReserveKey;
class CTxDB;
class CTxIndex;
void RegisterWallet(CWallet* pwalletIn);
void UnregisterWallet(CWallet* pwalletIn);
void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false);
bool ProcessBlock(CNode* pfrom, CBlock* pblock);
bool CheckDiskSpace(uint64 nAdditionalBytes=0);
FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
FILE* AppendBlockFile(unsigned int& nFileRet);
bool LoadBlockIndex(bool fAllowNew=true);
void PrintBlockTree();
bool ProcessMessages(CNode* pfrom);
bool SendMessages(CNode* pto, bool fSendTrickle);
bool LoadExternalBlockFile(FILE* fileIn);
void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
CBlock* CreateNewBlock(CReserveKey& reservekey);
void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
bool CheckProofOfWork(uint256 hash, unsigned int nBits);
unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
int GetNumBlocksOfPeers();
bool IsInitialBlockDownload();
std::string GetWarnings(std::string strFor);
bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock);
bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
/** Position on disk for a particular transaction. */
class CDiskTxPos
{
public:
unsigned int nFile;
unsigned int nBlockPos;
unsigned int nTxPos;
CDiskTxPos()
{
SetNull();
}
CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
{
nFile = nFileIn;
nBlockPos = nBlockPosIn;
nTxPos = nTxPosIn;
}
IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
void SetNull() { nFile = (unsigned int) -1; nBlockPos = 0; nTxPos = 0; }
bool IsNull() const { return (nFile == (unsigned int) -1); }
friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
{
return (a.nFile == b.nFile &&
a.nBlockPos == b.nBlockPos &&
a.nTxPos == b.nTxPos);
}
friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
{
return !(a == b);
}
std::string ToString() const
{
if (IsNull())
return "null";
else
return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
}
void print() const
{
printf("%s", ToString().c_str());
}
};
/** An inpoint - a combination of a transaction and an index n into its vin */
class CInPoint
{
public:
CTransaction* ptx;
unsigned int n;
CInPoint() { SetNull(); }
CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
void SetNull() { ptx = NULL; n = (unsigned int) -1; }
bool IsNull() const { return (ptx == NULL && n == (unsigned int) -1); }
};
/** An outpoint - a combination of a transaction hash and an index n into its vout */
class COutPoint
{
public:
uint256 hash;
unsigned int n;
COutPoint() { SetNull(); }
COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
void SetNull() { hash = 0; n = (unsigned int) -1; }
bool IsNull() const { return (hash == 0 && n == (unsigned int) -1); }
friend bool operator<(const COutPoint& a, const COutPoint& b)
{
return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
}
friend bool operator==(const COutPoint& a, const COutPoint& b)
{
return (a.hash == b.hash && a.n == b.n);
}
friend bool operator!=(const COutPoint& a, const COutPoint& b)
{
return !(a == b);
}
std::string ToString() const
{
return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
/** An input of a transaction. It contains the location of the previous
* transaction's output that it claims and a signature that matches the
* output's public key.
*/
class CTxIn
{
public:
COutPoint prevout;
CScript scriptSig;
unsigned int nSequence;
CTxIn()
{
nSequence = std::numeric_limits<unsigned int>::max();
}
explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
{
prevout = prevoutIn;
scriptSig = scriptSigIn;
nSequence = nSequenceIn;
}
CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
{
prevout = COutPoint(hashPrevTx, nOut);
scriptSig = scriptSigIn;
nSequence = nSequenceIn;
}
IMPLEMENT_SERIALIZE
(
READWRITE(prevout);
READWRITE(scriptSig);
READWRITE(nSequence);
)
bool IsFinal() const
{
return (nSequence == std::numeric_limits<unsigned int>::max());
}
friend bool operator==(const CTxIn& a, const CTxIn& b)
{
return (a.prevout == b.prevout &&
a.scriptSig == b.scriptSig &&
a.nSequence == b.nSequence);
}
friend bool operator!=(const CTxIn& a, const CTxIn& b)
{
return !(a == b);
}
std::string ToString() const
{
std::string str;
str += "CTxIn(";
str += prevout.ToString();
if (prevout.IsNull())
str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
else
str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
if (nSequence != std::numeric_limits<unsigned int>::max())
str += strprintf(", nSequence=%u", nSequence);
str += ")";
return str;
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
/** An output of a transaction. It contains the public key that the next input
* must be able to sign with to claim it.
*/
class CTxOut
{
public:
int64 nValue;
CScript scriptPubKey;
CTxOut()
{
SetNull();
}
CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
{
nValue = nValueIn;
scriptPubKey = scriptPubKeyIn;
}
IMPLEMENT_SERIALIZE
(
READWRITE(nValue);
READWRITE(scriptPubKey);
)
void SetNull()
{
nValue = -1;
scriptPubKey.clear();
}
bool IsNull()
{
return (nValue == -1);
}
uint256 GetHash() const
{
return SerializeHash(*this);
}
friend bool operator==(const CTxOut& a, const CTxOut& b)
{
return (a.nValue == b.nValue &&
a.scriptPubKey == b.scriptPubKey);
}
friend bool operator!=(const CTxOut& a, const CTxOut& b)
{
return !(a == b);
}
std::string ToString() const
{
if (scriptPubKey.size() < 6)
return "CTxOut(error)";
return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
enum GetMinFee_mode
{
GMF_BLOCK,
GMF_RELAY,
GMF_SEND,
};
typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
/** The basic transaction that is broadcasted on the network and contained in
* blocks. A transaction can contain multiple inputs and outputs.
*/
class CTransaction
{
public:
static const int CURRENT_VERSION=1;
int nVersion;
std::vector<CTxIn> vin;
std::vector<CTxOut> vout;
unsigned int nLockTime;
// Denial-of-service detection:
mutable int nDoS;
bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
CTransaction()
{
SetNull();
}
IMPLEMENT_SERIALIZE
(
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(vin);
READWRITE(vout);
READWRITE(nLockTime);
)
void SetNull()
{
nVersion = CTransaction::CURRENT_VERSION;
vin.clear();
vout.clear();
nLockTime = 0;
nDoS = 0; // Denial-of-service prevention
}
bool IsNull() const
{
return (vin.empty() && vout.empty());
}
uint256 GetHash() const
{
return SerializeHash(*this);
}
bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
{
// Time based nLockTime implemented in 0.1.6
if (nLockTime == 0)
return true;
if (nBlockHeight == 0)
nBlockHeight = nBestHeight;
if (nBlockTime == 0)
nBlockTime = GetAdjustedTime();
if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
return true;
BOOST_FOREACH(const CTxIn& txin, vin)
if (!txin.IsFinal())
return false;
return true;
}
bool IsNewerThan(const CTransaction& old) const
{
if (vin.size() != old.vin.size())
return false;
for (unsigned int i = 0; i < vin.size(); i++)
if (vin[i].prevout != old.vin[i].prevout)
return false;
bool fNewer = false;
unsigned int nLowest = std::numeric_limits<unsigned int>::max();
for (unsigned int i = 0; i < vin.size(); i++)
{
if (vin[i].nSequence != old.vin[i].nSequence)
{
if (vin[i].nSequence <= nLowest)
{
fNewer = false;
nLowest = vin[i].nSequence;
}
if (old.vin[i].nSequence < nLowest)
{
fNewer = true;
nLowest = old.vin[i].nSequence;
}
}
}
return fNewer;
}
bool IsCoinBase() const
{
return (vin.size() == 1 && vin[0].prevout.IsNull());
}
/** Check for standard transaction types
@return True if all outputs (scriptPubKeys) use only standard transaction forms
*/
bool IsStandard() const;
/** Check for standard transaction types
@param[in] mapInputs Map of previous transactions that have outputs we're spending
@return True if all inputs (scriptSigs) use only standard transaction forms
@see CTransaction::FetchInputs
*/
bool AreInputsStandard(const MapPrevTx& mapInputs) const;
/** Count ECDSA signature operations the old-fashioned (pre-0.6) way
@return number of sigops this transaction's outputs will produce when spent
@see CTransaction::FetchInputs
*/
unsigned int GetLegacySigOpCount() const;
/** Count ECDSA signature operations in pay-to-script-hash inputs.
@param[in] mapInputs Map of previous transactions that have outputs we're spending
@return maximum number of sigops required to validate this transaction's inputs
@see CTransaction::FetchInputs
*/
unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
/** Amount of bitcoins spent by this transaction.
@return sum of all outputs (note: does not include fees)
*/
int64 GetValueOut() const
{
int64 nValueOut = 0;
BOOST_FOREACH(const CTxOut& txout, vout)
{
nValueOut += txout.nValue;
if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
}
return nValueOut;
}
/** Amount of bitcoins coming in to this transaction
Note that lightweight clients may not know anything besides the hash of previous transactions,
so may not be able to calculate this.
@param[in] mapInputs Map of previous transactions that have outputs we're spending
@return Sum of value of all inputs (scriptSigs)
@see CTransaction::FetchInputs
*/
int64 GetValueIn(const MapPrevTx& mapInputs) const;
static bool AllowFree(double dPriority)
{
// Large (in bytes) low-priority (new, small-coin) transactions
// need a fee.
return dPriority > COIN * 2880 / 250; // 5760 blocks found a day. Priority cutoff is 1 SMC day / 250 bytes.
}
int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, enum GetMinFee_mode mode=GMF_BLOCK) const
{
// Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
unsigned int nNewBlockSize = nBlockSize + nBytes;
int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
if (fAllowFree)
{
if (nBlockSize == 1)
{
// Transactions under 10K are free
// (about 4500bc if made of 50bc inputs)
if (nBytes < 10000)
nMinFee = 0;
}
else
{
// Free transaction area
if (nNewBlockSize < 27000)
nMinFee = 0;
}
}
// To limit dust spam, add MIN_TX_FEE/MIN_RELAY_TX_FEE for any output that is less than 0.01
BOOST_FOREACH(const CTxOut& txout, vout)
if (txout.nValue < CENT)
nMinFee += nBaseFee;
// Raise the price as the block approaches full
if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
{
if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
return MAX_MONEY;
nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
}
if (!MoneyRange(nMinFee))
nMinFee = MAX_MONEY;
return nMinFee;
}
bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
{
CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
if (!filein)
return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
// Read transaction
if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
return error("CTransaction::ReadFromDisk() : fseek failed");
try {
filein >> *this;
}
catch (std::exception &e) {
return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
}
// Return file pointer
if (pfileRet)
{
if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
return error("CTransaction::ReadFromDisk() : second fseek failed");
*pfileRet = filein.release();
}
return true;
}
friend bool operator==(const CTransaction& a, const CTransaction& b)
{
return (a.nVersion == b.nVersion &&
a.vin == b.vin &&
a.vout == b.vout &&
a.nLockTime == b.nLockTime);
}
friend bool operator!=(const CTransaction& a, const CTransaction& b)
{
return !(a == b);
}
std::string ToString() const
{
std::string str;
str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
GetHash().ToString().substr(0,10).c_str(),
nVersion,
vin.size(),
vout.size(),
nLockTime);
for (unsigned int i = 0; i < vin.size(); i++)
str += " " + vin[i].ToString() + "\n";
for (unsigned int i = 0; i < vout.size(); i++)
str += " " + vout[i].ToString() + "\n";
return str;
}
void print() const
{
printf("%s", ToString().c_str());
}
bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
bool ReadFromDisk(COutPoint prevout);
bool DisconnectInputs(CTxDB& txdb);
/** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
@param[in] txdb Transaction database
@param[in] mapTestPool List of pending changes to the transaction index database
@param[in] fBlock True if being called to add a new best-block to the chain
@param[in] fMiner True if being called by CreateNewBlock
@param[out] inputsRet Pointers to this transaction's inputs
@param[out] fInvalid returns true if transaction is invalid
@return Returns true if all inputs are in txdb or mapTestPool
*/
bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
/** Sanity check previous transactions, then, if all checks succeed,
mark them as spent by this transaction.
@param[in] inputs Previous transactions (from FetchInputs)
@param[out] mapTestPool Keeps track of inputs that need to be updated on disk
@param[in] posThisTx Position of this transaction on disk
@param[in] pindexBlock
@param[in] fBlock true if called from ConnectBlock
@param[in] fMiner true if called from CreateNewBlock
@param[in] fStrictPayToScriptHash true if fully validating p2sh transactions
@return Returns true if all checks succeed
*/
bool ConnectInputs(MapPrevTx inputs,
std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
bool ClientConnectInputs();
bool CheckTransaction() const;
bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
protected:
const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
};
/** A transaction with a merkle branch linking it to the block chain. */
class CMerkleTx : public CTransaction
{
public:
uint256 hashBlock;
std::vector<uint256> vMerkleBranch;
int nIndex;
// memory only
mutable bool fMerkleVerified;
CMerkleTx()
{
Init();
}
CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
{
Init();
}
void Init()
{
hashBlock = 0;
nIndex = -1;
fMerkleVerified = false;
}
IMPLEMENT_SERIALIZE
(
nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
nVersion = this->nVersion;
READWRITE(hashBlock);
READWRITE(vMerkleBranch);
READWRITE(nIndex);
)
int SetMerkleBranch(const CBlock* pblock=NULL);
int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
int GetBlocksToMaturity() const;
bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
bool AcceptToMemoryPool();
};
/** A txdb record that contains the disk location of a transaction and the
* locations of transactions that spend its outputs. vSpent is really only
* used as a flag, but having the location is very helpful for debugging.
*/
class CTxIndex
{
public:
CDiskTxPos pos;
std::vector<CDiskTxPos> vSpent;
CTxIndex()
{
SetNull();
}
CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
{
pos = posIn;
vSpent.resize(nOutputs);
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(pos);
READWRITE(vSpent);
)
void SetNull()
{
pos.SetNull();
vSpent.clear();
}
bool IsNull()
{
return pos.IsNull();
}
friend bool operator==(const CTxIndex& a, const CTxIndex& b)
{
return (a.pos == b.pos &&
a.vSpent == b.vSpent);
}
friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
{
return !(a == b);
}
int GetDepthInMainChain() const;
};
/** Nodes collect new transactions into a block, hash them into a hash tree,
* and scan through nonce values to make the block's hash satisfy proof-of-work
* requirements. When they solve the proof-of-work, they broadcast the block
* to everyone and the block is added to the block chain. The first transaction
* in the block is a special one that creates a new coin owned by the creator
* of the block.
*
* Blocks are appended to blk0001.dat files on disk. Their location on disk
* is indexed by CBlockIndex objects in memory.
*/
class CBlock
{
public:
// header
static const int CURRENT_VERSION=1;
int nVersion;
uint256 hashPrevBlock;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
// network and disk
std::vector<CTransaction> vtx;
// memory only
mutable std::vector<uint256> vMerkleTree;
// Denial-of-service detection:
mutable int nDoS;
bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
CBlock()
{
SetNull();
}
IMPLEMENT_SERIALIZE
(
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(hashPrevBlock);
READWRITE(hashMerkleRoot);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
// ConnectBlock depends on vtx being last so it can calculate offset
if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
READWRITE(vtx);
else if (fRead)
const_cast<CBlock*>(this)->vtx.clear();
)
void SetNull()
{
nVersion = CBlock::CURRENT_VERSION;
hashPrevBlock = 0;
hashMerkleRoot = 0;
nTime = 0;
nBits = 0;
nNonce = 0;
vtx.clear();
vMerkleTree.clear();
nDoS = 0;
}
bool IsNull() const
{
return (nBits == 0);
}
uint256 GetHash() const
{
return Hash(BEGIN(nVersion), END(nNonce));
}
uint256 GetPoWHash() const
{
uint256 thash;
scrypt_1024_1_1_256(BEGIN(nVersion), BEGIN(thash));
return thash;
}
int64 GetBlockTime() const
{
return (int64)nTime;
}
void UpdateTime(const CBlockIndex* pindexPrev);
uint256 BuildMerkleTree() const
{
vMerkleTree.clear();
BOOST_FOREACH(const CTransaction& tx, vtx)
vMerkleTree.push_back(tx.GetHash());
int j = 0;
for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
{
for (int i = 0; i < nSize; i += 2)
{
int i2 = std::min(i+1, nSize-1);
vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
}
j += nSize;
}
return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
}
std::vector<uint256> GetMerkleBranch(int nIndex) const
{
if (vMerkleTree.empty())
BuildMerkleTree();
std::vector<uint256> vMerkleBranch;
int j = 0;
for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
{
int i = std::min(nIndex^1, nSize-1);
vMerkleBranch.push_back(vMerkleTree[j+i]);
nIndex >>= 1;
j += nSize;
}
return vMerkleBranch;
}
static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
{
if (nIndex == -1)
return 0;
BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
{
if (nIndex & 1)
hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
else
hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
nIndex >>= 1;
}
return hash;
}
bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
{
// Open history file to append
CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
if (!fileout)
return error("CBlock::WriteToDisk() : AppendBlockFile failed");
// Write index header
unsigned int nSize = fileout.GetSerializeSize(*this);
fileout << FLATDATA(pchMessageStart) << nSize;
// Write block
long fileOutPos = ftell(fileout);
if (fileOutPos < 0)
return error("CBlock::WriteToDisk() : ftell failed");
nBlockPosRet = fileOutPos;
fileout << *this;
// Flush stdio buffers and commit to disk before returning
fflush(fileout);
if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
FileCommit(fileout);
return true;
}
bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
{
SetNull();
// Open history file to read
CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
if (!filein)
return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
if (!fReadTransactions)
filein.nType |= SER_BLOCKHEADERONLY;
// Read block
try {
filein >> *this;
}
catch (std::exception &e) {
return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
}
// Check the header
if (!CheckProofOfWork(GetPoWHash(), nBits))
return error("CBlock::ReadFromDisk() : errors in block header");
return true;
}
void print() const
{
printf("CBlock(hash=%s, PoW=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
GetHash().ToString().substr(0,20).c_str(),
GetPoWHash().ToString().substr(0,20).c_str(),
nVersion,
hashPrevBlock.ToString().substr(0,20).c_str(),
hashMerkleRoot.ToString().substr(0,10).c_str(),
nTime, nBits, nNonce,
vtx.size());
for (unsigned int i = 0; i < vtx.size(); i++)
{
printf(" ");
vtx[i].print();
}
printf(" vMerkleTree: ");
for (unsigned int i = 0; i < vMerkleTree.size(); i++)
printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
printf("\n");
}
bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
bool CheckBlock() const;
bool AcceptBlock();
private:
bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
};
/** The block chain is a tree shaped structure starting with the
* genesis block at the root, with each block potentially having multiple
* candidates to be the next block. pprev and pnext link a path through the
* main/longest chain. A blockindex may have multiple pprev pointing back
* to it, but pnext will only point forward to the longest branch, or will
* be null if the block is not part of the longest chain.
*/
class CBlockIndex
{
public:
const uint256* phashBlock;
CBlockIndex* pprev;
CBlockIndex* pnext;
unsigned int nFile;
unsigned int nBlockPos;
int nHeight;
CBigNum bnChainWork;
// block header
int nVersion;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
CBlockIndex()
{
phashBlock = NULL;
pprev = NULL;
pnext = NULL;
nFile = 0;
nBlockPos = 0;
nHeight = 0;
bnChainWork = 0;
nVersion = 0;
hashMerkleRoot = 0;
nTime = 0;
nBits = 0;
nNonce = 0;
}
CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
{
phashBlock = NULL;
pprev = NULL;
pnext = NULL;
nFile = nFileIn;
nBlockPos = nBlockPosIn;
nHeight = 0;
bnChainWork = 0;
nVersion = block.nVersion;
hashMerkleRoot = block.hashMerkleRoot;
nTime = block.nTime;
nBits = block.nBits;
nNonce = block.nNonce;
}
CBlock GetBlockHeader() const
{
CBlock block;
block.nVersion = nVersion;
if (pprev)
block.hashPrevBlock = pprev->GetBlockHash();
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
return block;
}
uint256 GetBlockHash() const
{
return *phashBlock;
}
int64 GetBlockTime() const
{
return (int64)nTime;
}
CBigNum GetBlockWork() const
{
CBigNum bnTarget;
bnTarget.SetCompact(nBits);
if (bnTarget <= 0)
return 0;
return (CBigNum(1)<<256) / (bnTarget+1);
}
bool IsInMainChain() const
{
return (pnext || this == pindexBest);
}
bool CheckIndex() const
{
return true; // CheckProofOfWork(GetBlockHash(), nBits);
}
enum { nMedianTimeSpan=11 };
int64 GetMedianTimePast() const
{
int64 pmedian[nMedianTimeSpan];
int64* pbegin = &pmedian[nMedianTimeSpan];
int64* pend = &pmedian[nMedianTimeSpan];
const CBlockIndex* pindex = this;
for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
*(--pbegin) = pindex->GetBlockTime();
std::sort(pbegin, pend);
return pbegin[(pend - pbegin)/2];
}
int64 GetMedianTime() const
{
const CBlockIndex* pindex = this;
for (int i = 0; i < nMedianTimeSpan/2; i++)
{
if (!pindex->pnext)
return GetBlockTime();
pindex = pindex->pnext;
}
return pindex->GetMedianTimePast();
}
std::string ToString() const
{
return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
pprev, pnext, nFile, nBlockPos, nHeight,
hashMerkleRoot.ToString().substr(0,10).c_str(),
GetBlockHash().ToString().substr(0,20).c_str());
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
/** Used to marshal pointers into hashes for db storage. */
class CDiskBlockIndex : public CBlockIndex
{
public:
uint256 hashPrev;
uint256 hashNext;
CDiskBlockIndex()
{
hashPrev = 0;
hashNext = 0;
}
explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
{
hashPrev = (pprev ? pprev->GetBlockHash() : 0);
hashNext = (pnext ? pnext->GetBlockHash() : 0);
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(hashNext);
READWRITE(nFile);
READWRITE(nBlockPos);
READWRITE(nHeight);
// block header
READWRITE(this->nVersion);
READWRITE(hashPrev);
READWRITE(hashMerkleRoot);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
)
uint256 GetBlockHash() const
{
CBlock block;
block.nVersion = nVersion;
block.hashPrevBlock = hashPrev;
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
return block.GetHash();
}
std::string ToString() const
{
std::string str = "CDiskBlockIndex(";
str += CBlockIndex::ToString();
str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
GetBlockHash().ToString().c_str(),
hashPrev.ToString().substr(0,20).c_str(),
hashNext.ToString().substr(0,20).c_str());
return str;
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
/** Describes a place in the block chain to another node such that if the
* other node doesn't have the same branch, it can find a recent common trunk.
* The further back it is, the further before the fork it may be.
*/
class CBlockLocator
{
protected:
std::vector<uint256> vHave;
public:
CBlockLocator()
{
}
explicit CBlockLocator(const CBlockIndex* pindex)
{
Set(pindex);
}
explicit CBlockLocator(uint256 hashBlock)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end())
Set((*mi).second);
}
CBlockLocator(const std::vector<uint256>& vHaveIn)
{
vHave = vHaveIn;
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(vHave);
)
void SetNull()
{
vHave.clear();
}
bool IsNull()
{
return vHave.empty();
}
void Set(const CBlockIndex* pindex)
{
vHave.clear();
int nStep = 1;
while (pindex)
{
vHave.push_back(pindex->GetBlockHash());
// Exponentially larger steps back
for (int i = 0; pindex && i < nStep; i++)
pindex = pindex->pprev;
if (vHave.size() > 10)
nStep *= 2;
}
vHave.push_back(hashGenesisBlock);
}
int GetDistanceBack()
{
// Retrace how far back it was in the sender's branch
int nDistance = 0;
int nStep = 1;
BOOST_FOREACH(const uint256& hash, vHave)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
return nDistance;
}
nDistance += nStep;
if (nDistance > 10)
nStep *= 2;
}
return nDistance;
}
CBlockIndex* GetBlockIndex()
{
// Find the first block the caller has in the main chain
BOOST_FOREACH(const uint256& hash, vHave)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
return pindex;
}
}
return pindexGenesisBlock;
}
uint256 GetBlockHash()
{
// Find the first block the caller has in the main chain
BOOST_FOREACH(const uint256& hash, vHave)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
return hash;
}
}
return hashGenesisBlock;
}
int GetHeight()
{
CBlockIndex* pindex = GetBlockIndex();
if (!pindex)
return 0;
return pindex->nHeight;
}
};
/** Alerts are for notifying old versions if they become too obsolete and
* need to upgrade. The message is displayed in the status bar.
* Alert messages are broadcast as a vector of signed data. Unserializing may
* not read the entire buffer if the alert is for a newer version, but older
* versions can still relay the original data.
*/
class CUnsignedAlert
{
public:
int nVersion;
int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
int64 nExpiration;
int nID;
int nCancel;
std::set<int> setCancel;
int nMinVer; // lowest version inclusive
int nMaxVer; // highest version inclusive
std::set<std::string> setSubVer; // empty matches all
int nPriority;
// Actions
std::string strComment;
std::string strStatusBar;
std::string strReserved;
IMPLEMENT_SERIALIZE
(
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(nRelayUntil);
READWRITE(nExpiration);
READWRITE(nID);
READWRITE(nCancel);
READWRITE(setCancel);
READWRITE(nMinVer);
READWRITE(nMaxVer);
READWRITE(setSubVer);
READWRITE(nPriority);
READWRITE(strComment);
READWRITE(strStatusBar);
READWRITE(strReserved);
)
void SetNull()
{
nVersion = 1;
nRelayUntil = 0;
nExpiration = 0;
nID = 0;
nCancel = 0;
setCancel.clear();
nMinVer = 0;
nMaxVer = 0;
setSubVer.clear();
nPriority = 0;
strComment.clear();
strStatusBar.clear();
strReserved.clear();
}
std::string ToString() const
{
std::string strSetCancel;
BOOST_FOREACH(int n, setCancel)
strSetCancel += strprintf("%d ", n);
std::string strSetSubVer;
BOOST_FOREACH(std::string str, setSubVer)
strSetSubVer += "\"" + str + "\" ";
return strprintf(
"CAlert(\n"
" nVersion = %d\n"
" nRelayUntil = %"PRI64d"\n"
" nExpiration = %"PRI64d"\n"
" nID = %d\n"
" nCancel = %d\n"
" setCancel = %s\n"
" nMinVer = %d\n"
" nMaxVer = %d\n"
" setSubVer = %s\n"
" nPriority = %d\n"
" strComment = \"%s\"\n"
" strStatusBar = \"%s\"\n"
")\n",
nVersion,
nRelayUntil,
nExpiration,
nID,
nCancel,
strSetCancel.c_str(),
nMinVer,
nMaxVer,
strSetSubVer.c_str(),
nPriority,
strComment.c_str(),
strStatusBar.c_str());
}
void print() const
{
printf("%s", ToString().c_str());
}
};
/** An alert is a combination of a serialized CUnsignedAlert and a signature. */
class CAlert : public CUnsignedAlert
{
public:
std::vector<unsigned char> vchMsg;
std::vector<unsigned char> vchSig;
CAlert()
{
SetNull();
}
IMPLEMENT_SERIALIZE
(
READWRITE(vchMsg);
READWRITE(vchSig);
)
void SetNull()
{
CUnsignedAlert::SetNull();
vchMsg.clear();
vchSig.clear();
}
bool IsNull() const
{
return (nExpiration == 0);
}
uint256 GetHash() const
{
return SerializeHash(*this);
}
bool IsInEffect() const
{
return (GetAdjustedTime() < nExpiration);
}
bool Cancels(const CAlert& alert) const
{
if (!IsInEffect())
return false; // this was a no-op before 31403
return (alert.nID <= nCancel || setCancel.count(alert.nID));
}
bool AppliesTo(int nVersion, std::string strSubVerIn) const
{
// TODO: rework for client-version-embedded-in-strSubVer ?
return (IsInEffect() &&
nMinVer <= nVersion && nVersion <= nMaxVer &&
(setSubVer.empty() || setSubVer.count(strSubVerIn)));
}
bool AppliesToMe() const
{
return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
}
bool RelayTo(CNode* pnode) const
{
if (!IsInEffect())
return false;
// returns true if wasn't already contained in the set
if (pnode->setKnown.insert(GetHash()).second)
{
if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
AppliesToMe() ||
GetAdjustedTime() < nRelayUntil)
{
pnode->PushMessage("alert", *this);
return true;
}
}
return false;
}
bool CheckSignature()
{
CKey key;
if (!key.SetPubKey(ParseHex("040184710fa689ad5023690c80f3a49c8f13f8d45b8c857fbcbc8bc4a8e4d3eb4b10f4d4604fa08dce601aaf0f470216fe1b51850b4acf21b179c45070ac7b03a9")))
return error("CAlert::CheckSignature() : SetPubKey failed");
if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
return error("CAlert::CheckSignature() : verify signature failed");
// Now unserialize the data
CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
sMsg >> *(CUnsignedAlert*)this;
return true;
}
bool ProcessAlert();
/*
* Get copy of (active) alert object by hash. Returns a null alert if it is not found.
*/
static CAlert getAlertByHash(const uint256 &hash);
};
class CTxMemPool
{
public:
mutable CCriticalSection cs;
std::map<uint256, CTransaction> mapTx;
std::map<COutPoint, CInPoint> mapNextTx;
bool accept(CTxDB& txdb, CTransaction &tx,
bool fCheckInputs, bool* pfMissingInputs);
bool addUnchecked(const uint256& hash, CTransaction &tx);
bool remove(CTransaction &tx);
void queryHashes(std::vector<uint256>& vtxid);
unsigned long size()
{
LOCK(cs);
return mapTx.size();
}
bool exists(uint256 hash)
{
return (mapTx.count(hash) != 0);
}
CTransaction& lookup(uint256 hash)
{
return mapTx[hash];
}
};
extern CTxMemPool mempool;
#endif
| [
"[email protected]"
] | |
68e29d55ac1ed372a0b96b6c374d13987052fee5 | 999ca2f4259c1ca9de722f70f77c434a8d839bac | /DirectX11_Starter/Camera.h | d0319f8526c60fc0e51fb19e287ffb6b090b913b | [] | no_license | KevinMGranger/discs | 02eaffb8f8b1902fd261ad4c19d54f9a7ce81920 | 5e03ee3823ce8399fbf22bdad1361b89ee2741fe | refs/heads/master | 2020-12-26T04:15:35.443469 | 2015-10-15T06:55:06 | 2015-10-15T06:55:06 | 45,007,476 | 0 | 0 | null | 2015-10-27T00:50:30 | 2015-10-27T00:50:30 | null | UTF-8 | C++ | false | false | 842 | h | #pragma once
#include <DirectXMath.h>
#include <Windows.h>
#include "SimpleShader.h"
using namespace DirectX;
/// <summary>
/// Basic camera.
/// </summary>
class Camera
{
private:
bool viewMatIsDirty;
XMFLOAT4X4 viewMat;
XMFLOAT4X4 projMat;
XMFLOAT3 position;
XMFLOAT3 direction;
float rotX;
float rotY;
public:
Camera(XMFLOAT3 position, XMFLOAT3 direction, float aspectRatio);
XMFLOAT3 GetPosition();
XMFLOAT3 GetDirection();
float GetXRotation();
float GetYRotation();
virtual void CreateProjMatrix(float aspectRatio);
void SetViewAndProjMatrices(SimpleVertexShader* vertexShader);
void SetPosition(XMFLOAT3 position);
void SetDirection(XMFLOAT3 direction);
void SetRotationX(float rotX);
void SetRotationY(float rotY);
void Rotate(float x, float y);
virtual void Update(float deltaTime);
~Camera();
};
| [
"[email protected]"
] | |
ebfe1b720078f2c32a0ecd42fbb387c6bef1abf6 | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /components/services/storage/public/mojom/buckets/bucket_id_mojom_traits.cc | 62ea3c93ad282c00578ac68888c12d8803a7da1c | [
"BSD-3-Clause"
] | permissive | chromium/chromium | aaa9eda10115b50b0616d2f1aed5ef35d1d779d6 | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | refs/heads/main | 2023-08-24T00:35:12.585945 | 2023-08-23T22:01:11 | 2023-08-23T22:01:11 | 120,360,765 | 17,408 | 7,102 | BSD-3-Clause | 2023-09-10T23:44:27 | 2018-02-05T20:55:32 | null | UTF-8 | C++ | false | false | 490 | cc | // Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/services/storage/public/mojom/buckets/bucket_id_mojom_traits.h"
namespace mojo {
// static
bool StructTraits<storage::mojom::BucketIdDataView, storage::BucketId>::Read(
storage::mojom::BucketIdDataView data,
storage::BucketId* out) {
*out = storage::BucketId(data.value());
return true;
}
} // namespace mojo
| [
"[email protected]"
] | |
916bc105c18dca122b1ba854dcd11e8a125ae157 | b7913eb4849ffd4c60bdab08853bbaa7b38ff415 | /1034.cpp | 537192bd1782a7587cb7d1f45d48ae987d954a72 | [] | no_license | BismarckDD/HihoCoder | 21776854895183a56a16959a6229d4bd2094094a | 73e181d0002720ea5404ae9974df5d30e3be17f1 | refs/heads/master | 2021-01-13T00:59:22.293004 | 2017-01-24T13:54:43 | 2017-01-24T13:54:43 | 55,900,245 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,984 | cpp | #include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
#define maxn 100010
#define max(a, b) (a>b?a:b)
#define min(a, b) (a<b?a:b)
#define LL long long
#define ULL unsigned long long
#define UInt unsigned int
const ULL ULLMIN = 0;
const ULL ULLMAX = ~(ULL)(1<<63);
int n, m, l, r, t;
struct OP1 { UInt s, m, r; } op1[maxn];
struct OP2 { UInt t, l, r; } op2[maxn];
vector<UInt> st[maxn], et[maxn];
int oprcmp(const OP2 &a, const OP2 &b)
{
if (a.l == b.l) return a.r < b.r;
return a.l < b.l;
}
struct NodeTimeSeg
{
NodeTimeSeg *ch[2], *fa;
ULL value, totalSeg, numberSeg, totalVal; // Seg length of current node,
//seg number in total, seg number of current length, seg length in total;
// NodeTimeSeg() :value(0), totalSeg(0), numberSeg(0), totalVal(0) {};
};
struct NodeTime
{
NodeTime *ch[2], *fa;
ULL value;
// NodeTime() :value(0) {};
};
template<typename NODETYPE, size_t BUFFSIZE>
class SplayTree
{
public:
bool Init()
{
_buffsize = 0;
memset(_buff, 0, sizeof(_buff));
nil = _buff + _buffsize++;
nil->fa = nil->ch[0] = nil->ch[1] = nil;
root = GetNode(ULLMIN, nil);
root->ch[1] = GetNode(ULLMAX, root);
UpdateInternal(root->ch[1]);
UpdateInternal(root);
return true;
}
inline void FindValue(ULL value, NODETYPE *&p, NODETYPE *&q)
{
while (p != nil)
{
if (p->value == value) break;
else if (p->value > value) { q = p; p = p->ch[0]; }
else if (p->value < value) { q = p; p = p->ch[1]; }
else continue;
}
}
inline NODETYPE* FindPrev(ULL value)
{
NODETYPE *p = root, *q = NULL;
while (p != nil)
{
if (p->value < value) q = p, p = p->ch[1];
else p = p->ch[0];
}
return q;
}
inline NODETYPE* FindNext(ULL value)
{
NODETYPE *p = root, *q = NULL;
while (p != nil)
{
if (p->value > value) q = p, p = p->ch[0];
else p = p->ch[1];
}
return q;
}
bool Insert(ULL value)
{
if (value == 0) return false;
NODETYPE *p = root, *q = NULL;
FindValue(value, p, q);
return InsertInternal(p, q, value);
}
bool Delete(ULL value)
{
if (value == 0) return false;
NODETYPE *p = root, *q = NULL;
FindValue(value, p, q);
return DeleteInternal(p, value);
}
protected:
NODETYPE _buff[BUFFSIZE], *root = NULL, *nil = NULL;
ULL _buffsize;
virtual void GetNodeInternal(ULL value, NODETYPE* x, NODETYPE* fa) = 0;
virtual void UpdateInternal(NODETYPE* x) = 0;
virtual bool InsertInternal(NODETYPE* p, NODETYPE* q, ULL value) = 0;
virtual bool DeleteInternal(NODETYPE* p, ULL value) = 0;
NODETYPE* GetNode(ULL value, NODETYPE* fa)
{
NODETYPE* x = NULL;
x = _buff + _buffsize++;
x->ch[0] = x->ch[1] = nil;
x->value = value;
x->fa = fa;
GetNodeInternal(value, x, fa);
return x;
}
inline void Rotate(NODETYPE* x, bool isRightRotate)
{
NODETYPE* xfa = x->fa;
xfa->ch[!isRightRotate] = x->ch[isRightRotate];
xfa->ch[!isRightRotate]->fa = xfa;
x->fa = xfa->fa;
xfa->fa->ch[0] == xfa ? x->fa->ch[0] = x : x->fa->ch[1] = x;
xfa->fa = x; x->ch[isRightRotate] = xfa;
UpdateInternal(xfa);
if (xfa == root) root = x;
}
bool Splay(NODETYPE* x, NODETYPE *fa)
{
while (x->fa != fa)
{
if (x->fa->fa == fa) {
x->fa->ch[0] == x ? Rotate(x, true) : Rotate(x, false);
} else {
if (x->fa->fa->ch[0] == x->fa) {
if (x->fa->ch[0] == x) Rotate(x->fa, true), Rotate(x, true);
else Rotate(x, false), Rotate(x, true);
} else {
if (x->fa->ch[0] == x) Rotate(x, true), Rotate(x, false);
else Rotate(x->fa, false), Rotate(x, false);
}
}
}
UpdateInternal(x);
return true;
}
};
class SplayTreeTimeSeg : public SplayTree<NodeTimeSeg, maxn << 2>
{
public:
void Select(ULL value, ULL &size1, ULL &size2)
{
NodeTimeSeg *p = root, *q = NULL;
FindValue(value, p, q);
if (p == nil) p = FindNext(value);
Splay(p, nil);
size1 = root->ch[0]->totalVal;
size2 = root->totalSeg - root->ch[0]->totalSeg - 1; // there exists a minimum number 0.
}
protected:
virtual void UpdateInternal(NodeTimeSeg* p)
{
if (p->numberSeg < 0) p->numberSeg = 0;
p->totalSeg = p->ch[0]->totalSeg + p->ch[1]->totalSeg + p->numberSeg;
p->totalVal = p->ch[0]->totalVal + p->ch[1]->totalVal + p->numberSeg * p->value;
}
virtual void GetNodeInternal(ULL value, NodeTimeSeg* x, NodeTimeSeg* fa)
{
x->totalVal = value;
x->totalSeg = x->numberSeg = 1;
}
virtual bool InsertInternal(NodeTimeSeg* p, NodeTimeSeg* q, ULL value)
{
if (p != nil)
{
p->numberSeg += 1;
p->totalSeg += 1;
p->totalVal += value;
}
else
{
p = GetNode(value, q);
value < q->value ? q->ch[0] = p : q->ch[1] = p;
}
Splay(p, nil);
return true;
}
virtual bool DeleteInternal(NodeTimeSeg* p, ULL value)
{
if (p == nil) return false;
p->numberSeg -= 1;
p->totalSeg -= 1;
p->totalVal -= value;
Splay(p, nil);
return false;
}
};
class SplayTreeTime : public SplayTree<NodeTime, maxn << 2>
{
public:
ULL m_a, m_b, m_c;
protected:
virtual void GetNodeInternal(ULL value, NodeTime* x, NodeTime* fa) { return; }
virtual void UpdateInternal(NodeTime* x) { return; }
virtual bool InsertInternal(NodeTime* p, NodeTime* q, ULL value)
{
if (p == nil)
{
p = GetNode(value, q);
value > q->value ? q->ch[1] = p : q->ch[0] = p;
Splay(p, nil);
NodeTime *p1 = root->ch[0]; while (p1->ch[1] != nil) p1 = p1->ch[1];
NodeTime *p2 = root->ch[1]; while (p2->ch[0] != nil) p2 = p2->ch[0];
m_b = value; m_a = p1->value; m_c = p2->value;
return true;
}
return false;
}
virtual bool DeleteInternal(NodeTime* p, ULL value)
{
if (p != nil)
{
Splay(p, nil);
NodeTime *p1 = root->ch[0]; while (p1->ch[1] != nil) p1 = p1->ch[1];
NodeTime *p2 = root->ch[1]; while (p2->ch[0] != nil) p2 = p2->ch[0];
Splay(p1, nil); Splay(p2, root);
m_a = p1->value; m_b = value; m_c = p2->value;
p2->ch[0] = nil;
return true;
}
return false;
}
public:
ULL GetMin() { return FindNext(ULLMIN)->value; }
ULL GetMax() { return FindPrev(ULLMAX)->value; }
};
SplayTreeTime t2;
SplayTreeTimeSeg t1;
int main()
{
int tst = 1, ted = 1, sst, sed;
scanf("%d", &n);
for (int i = 1; i <= n; ++i) scanf("%u %u %u", &op1[i].s, &op1[i].m, &op1[i].r);
scanf("%d", &m);
scanf("%u %u %u", &op2[1].t, &op2[1].l, &op2[1].r);
for (int i = 1, j = 2; i <= m; ++i)
{ // combine two querys like (1, 1, 4) & (1, 4, 7) into one query (1, 1, 7)
i == m ? op2[j].t = ULLMAX, op2[j].l = ULLMIN, op2[j].r = ULLMAX : scanf("%u %u %u", &op2[j].t, &op2[j].l, &op2[j].r);
if (op2[j].t != op2[j - 1].t)
{
if (ted > tst)
{
sort(op2 + tst, op2 + ted + 1, oprcmp);
for (sst = tst, sed = tst + 1; sed <= ted; ++sed)
{
if (op2[sed].l <= op2[sst].r + 1) op2[sst].r = max(op2[sst].r, op2[sed].r);
else op2[++sst] = op2[sed];
}
op2[++sst] = op2[j]; j = sst;
}
tst = ted = j++;
}
else
ted = j++;
}
for (int i = 1; i < ted; ++i)
{
st[op2[i].l].push_back(op2[i].t);
et[op2[i].r].push_back(op2[i].t);
}
t1.Init(), t2.Init();
ULL a, b, c, cover = 0;
ULL ans = 0, size1, size2;
bool ret = 0, flag = false;
for (int i = 1; i <= n; ++i) // Deal with each magic unit.
{
for (int j = 0; j < st[i].size(); ++j)
{
if (st[i][j] == 0) flag = true;
++cover;
ret = t2.Insert(st[i][j]);
// printf("insert: %d %d %d\n", a, b, c);
if (!ret) continue;
a = t2.m_a, b = t2.m_b, c = t2.m_c;
// printf("insert: %d %d %d\n", a, b, c);
if (c != ULLMAX) t1.Delete(c - a), t1.Insert(c - b);
t1.Insert(b - a);
}
// printf("T1 Sum: %d\n", t1.totalVal);
if (cover > 0 && op1[i].m > 0)
if (op1[i].r > 0)
{
ULL mint = flag ? 0 : t2.GetMin();
ULL tmp = (op1[i].m + op1[i].r - 1) / op1[i].r;
t1.Select(tmp, size1, size2);
mint < tmp ? size1 -= mint : --size2;
ans += size1 * (ULL)op1[i].r + size2 * (ULL)op1[i].m; // most value.
tmp = (op1[i].m - op1[i].s + op1[i].r - 1) / op1[i].r;
ans += mint < tmp ? mint * (ULL)op1[i].r + op1[i].s : op1[i].m; // initial value.
}
else
ans += (ULL)op1[i].s;
for (int j = 0; j < et[i].size(); ++j)
{
if(et[i][j] == 0) flag = false;
--cover;
ret = t2.Delete(et[i][j]);
if (!ret) continue;
a = t2.m_a, b = t2.m_b, c = t2.m_c;
t1.Delete(b - a);
if (c != ULLMAX) t1.Delete(c - b), t1.Insert(c - a);
}
}
printf("%llu\n", ans);
return 0;
}
| [
"[email protected]"
] | |
998bf72dcf017dfa24acd8a262f8dd4b6a83f3af | dc6f3df2c3fde15d5c157e58251cdf9401d58db8 | /CS148/HW/hw4/submit/HW4-starter-code/include/Shape.h | 9d870d0c1df3b8e48340f77379b03ce527857a58 | [] | no_license | xavi1989/cs231n | 1888a642dc912623f33afaa69172839c93a6cd86 | be23c07888d0dc4d2b0549985f1fa5f31b725c78 | refs/heads/master | 2020-04-15T14:36:12.594198 | 2018-01-24T19:21:50 | 2018-01-24T19:21:50 | 55,452,259 | 0 | 6 | null | 2016-04-25T21:17:37 | 2016-04-04T23:17:56 | Jupyter Notebook | UTF-8 | C++ | false | false | 367 | h | #ifndef SHAPE_H
#define SHAPE_H
#include <Eigen/Dense>
#include <Materials.h>
namespace Raytracer148 {
struct Ray {
Eigen::Vector3d origin, direction;
};
class Shape;
struct HitRecord {
Eigen::Vector3d position, normal;
double t;
Materials m;
};
class Shape {
public:
virtual ~Shape(){}
virtual HitRecord intersect(const Ray &ray) = 0;
};
}
#endif
| [
"[email protected]"
] | |
d69c9e8cf49670817aa379a471ed42e112d2e75e | d18c4464af78f715ffc5d5addb1e005d018ca68d | /Voj/小希的迷宫 .cpp | 423167d2cbef9a89ef629bb8f32365fef4c9344a | [] | no_license | xiaoshidefeng/ACM | 508f71ba7da6e603e8c6fbbccfa9d68d497f15a9 | b646ae0a624fc5db2d7ac46b7baef9a2779fef7b | refs/heads/master | 2021-01-19T22:05:47.518409 | 2018-05-14T14:09:51 | 2018-05-14T14:09:51 | 82,564,505 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,142 | cpp | #include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<algorithm>
#include<map>
#include<set>
#include<queue>
#include<string>
#include<iostream>
using namespace std;
#define MID(x,y) ((x+y)>>1)
#define CLR(arr,val) memset(arr,val,sizeof(arr))
#define FAST_IO ios::sync_with_stdio(false);cin.tie(0);
const double PI = acos(-1.0);
const int INF = 0x3f3f3f3f;
const int N=2e5+7;
bool f;
int cnt;
int pre[100001];
bool vis[100001];
int finds(int x)
{
return x==pre[x]?pre[x]:pre[x]=finds(pre[x]);
}
void join(int x,int y)
{
x=finds(x);
y=finds(y);
if(x==y) { f=false; return;}
pre[y]=x;
++cnt;
}
int main()
{
//freopen("f:/input.txt", "r", stdin);
int i,j,k,a,b;
while(1)
{
set<int>s;
CLR(vis,false);
f=true;
cnt=0;
for(i=0;i<100000;i++)
pre[i]=i;
while(scanf("%d%d",&a,&b)!=EOF&&((a!=0||b!=0)&&(a!=-1||b!=-1)))
{
vis[a]=true;
vis[b]=true;
s.insert(a);
s.insert(b);
join(a,b);
}
if(a==-1&&b==-1)
break;
if(((s.size()-1)!=cnt)&&cnt!=0)
{
printf("No\n");
continue;
}
if(f)
{
printf("Yes\n");
continue;
}
else
printf("No\n");
}
} | [
"[email protected]"
] | |
e1b7e12e8ee093cb4cacb88c4922da3b2cbae449 | d6f231aa64df78689776dde56ea7afb8cbd215f3 | /CodeForces/268A/12436915_AC_30ms_1860kB.cpp | 37762ea5e591aece11ccdecab2d89e1cdcc25c10 | [] | no_license | Linzecong/My-ACM-Code | 18de33b786d51fd0729b601349f0db0f8ff22141 | d5487590d400510f387d352cd0748e9224f7acdd | refs/heads/master | 2021-01-24T04:28:53.268943 | 2018-11-30T08:36:40 | 2018-11-30T08:36:40 | 122,939,894 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 386 | cpp | #include<iostream>
#include<algorithm>
using namespace std;
int h[100];
int g[100];
int main(){
int a;
cin>>a;
for(int i=0;i<a;i++){
cin>>h[i]>>g[i];
}
int ans=0;
for(int i=0;i<a;i++){
for(int j=0;j<a;j++){
if(i!=j)
if(h[i]==g[j])
ans++;
}
}
cout<<ans<<endl;
return 0;
} | [
"[email protected]"
] | |
8b16765dbcdf9433426e7c4deb37778c42de2fd8 | c0526eb4f180b3502acdb83ddc4835ad9bf876be | /Code/Engine/Core/Utility/ErrorWarningAssert.hpp | 0dd8ef17cec05ced9cba822865dab1168f649be7 | [] | no_license | achasedev/Engine | 502fb98b276962047ee27f0a2fb0b42be3d8f81d | 55ed183af05a7511b10e685e2d64b977bbfd5603 | refs/heads/master | 2022-05-22T06:38:40.721915 | 2019-05-07T22:09:39 | 2019-05-07T22:09:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,146 | hpp | #pragma once
//-----------------------------------------------------------------------------------------------
// ErrorWarningAssert.hpp
//
// Summary of error and assertion macros:
// #define ERROR_AND_DIE( errorText ) // "MUST not reach this point"; Show error dialogue, then shut down the app
// #define ERROR_RECOVERABLE( errorText ) // "SHOULD not reach this point"; Show warning dialogue, then proceed
// #define GUARANTEE_OR_DIE( condition, errorText ) // "MUST be true"; If condition is false, show error dialogue then shut down the app
// #define GUARANTEE_RECOVERABLE( condition, errorText ) // "SHOULD be true"; If condition is false, show warning dialogue then proceed
// #define ASSERT_OR_DIE( condition, errorText ) // Same as GUARANTEE_OR_DIE, but removed if DISABLE_ASSERTS is #defined
// #define ASSERT_RECOVERABLE( condition, errorText ) // Same as GUARANTEE_RECOVERABLE, but removed if DISABLE_ASSERTS is #defined
//
//-----------------------------------------------------------------------------------------------
#include <string>
//-----------------------------------------------------------------------------------------------
enum SeverityLevel
{
SEVERITY_INFORMATION,
SEVERITY_QUESTION,
SEVERITY_WARNING,
SEVERITY_FATAL
};
//-----------------------------------------------------------------------------------------------
void DebuggerPrintf( const char* messageFormat, ... );
bool IsDebuggerAvailable();
__declspec( noreturn ) void FatalError( const char* filePath, const char* functionName, int lineNum, const std::string& reasonForError, const char* conditionText=nullptr );
void RecoverableWarning( const char* filePath, const char* functionName, int lineNum, const std::string& reasonForWarning, const char* conditionText=nullptr );
void SystemDialogue_Okay( const std::string& messageTitle, const std::string& messageText, SeverityLevel severity );
bool SystemDialogue_OkayCancel( const std::string& messageTitle, const std::string& messageText, SeverityLevel severity );
bool SystemDialogue_YesNo( const std::string& messageTitle, const std::string& messageText, SeverityLevel severity );
int SystemDialogue_YesNoCancel( const std::string& messageTitle, const std::string& messageText, SeverityLevel severity );
//-----------------------------------------------------------------------------------------------
// ERROR_AND_DIE
//
// Present in all builds.
// No condition; always triggers if reached.
// Depending on the platform, this typically:
// - Logs an error message to the console and/or log file
// - Opens an error/message dialogue box
// - Triggers a debug breakpoint (if appropriate development suite is present)
// - Shuts down the app
//
// Use this when reaching a certain line of code should never happen under any circumstances,
// and continued execution is dangerous or impossible.
//
#define ERROR_AND_DIE( errorMessageText ) \
{ \
FatalError( __FILE__, __FUNCTION__, __LINE__, errorMessageText ); \
}
//-----------------------------------------------------------------------------------------------
// ERROR_RECOVERABLE
//
// Present in all builds.
// No condition; always triggers if reached.
// Depending on the platform, this typically:
// - Logs a warning message to the console and/or log file
// - Opens an warning/message dialogue box
// - Triggers a debug breakpoint (if appropriate development suite is present)
// - Continues execution
//
#define ERROR_RECOVERABLE( errorMessageText ) \
{ \
RecoverableWarning( __FILE__, __FUNCTION__, __LINE__, errorMessageText ); \
}
//-----------------------------------------------------------------------------------------------
// GUARANTEE_OR_DIE
//
// Present in all builds.
// Triggers if condition is false.
// Depending on the platform, this typically:
// - Logs an error message to the console and/or log file
// - Opens an error/message dialogue box
// - Triggers a debug breakpoint (if appropriate development suite is present)
// - Shuts down the app
//
#define GUARANTEE_OR_DIE( condition, errorMessageText ) \
{ \
if( !(condition) ) \
{ \
const char* conditionText = #condition; \
FatalError( __FILE__, __FUNCTION__, __LINE__, errorMessageText, conditionText ); \
} \
}
//-----------------------------------------------------------------------------------------------
// GUARANTEE_RECOVERABLE
//
// Present in all builds.
// Triggers if condition is false.
// Depending on the platform, this typically:
// - Logs a warning message to the console and/or log file
// - Opens an warning/message dialogue box
// - Triggers a debug breakpoint (if appropriate development suite is present)
// - Continues execution
//
#define GUARANTEE_RECOVERABLE( condition, errorMessageText ) \
{ \
if( !(condition) ) \
{ \
const char* conditionText = #condition; \
RecoverableWarning( __FILE__, __FUNCTION__, __LINE__, errorMessageText, conditionText ); \
} \
}
//-----------------------------------------------------------------------------------------------
// ASSERT_OR_DIE
//
// Removed if DISABLE_ASSERTS is defined, typically in a Final build configuration.
// Triggers if condition is false.
// Depending on the platform, this typically:
// - Logs an error message to the console and/or log file
// - Opens an error/message dialogue box
// - Triggers a debug breakpoint (if appropriate development suite is present)
// - Shuts down the app
//
#if defined( DISABLE_ASSERTS )
#define ASSERT_OR_DIE( condition, errorMessageText ) { (void)( condition ); }
#else
#define ASSERT_OR_DIE( condition, errorMessageText ) \
{ \
if( !(condition) ) \
{ \
const char* conditionText = #condition; \
FatalError( __FILE__, __FUNCTION__, __LINE__, errorMessageText, conditionText ); \
} \
}
#endif
//-----------------------------------------------------------------------------------------------
// ASSERT_RECOVERABLE
//
// Removed if DISABLE_ASSERTS is defined, typically in a Final build configuration.
// Triggers if condition is false.
// Depending on the platform, this typically:
// - Logs a warning message to the console and/or log file
// - Opens an warning/message dialogue box
// - Triggers a debug breakpoint (if appropriate development suite is present)
// - Continues execution
//
#if defined( DISABLE_ASSERTS )
#define ASSERT_RECOVERABLE( condition, errorMessageText ) { (void)( condition ); }
#else
#define ASSERT_RECOVERABLE( condition, errorMessageText ) \
{ \
if( !(condition) ) \
{ \
const char* conditionText = #condition; \
RecoverableWarning( __FILE__, __FUNCTION__, __LINE__, errorMessageText, conditionText ); \
} \
}
#endif
| [
"[email protected]"
] | |
b79837dd5696da721741ed91ead3e23044964b54 | 08b8c25f7fea9970647f31469e4be3bc48e5b86d | /uva-online-judge/accepted-solutions/725 - Division.cpp | 3bdfe6f91049554c05075dd75f31d723bf7db1e2 | [] | no_license | SharifulCSECoU/competitive-programming | ab55e458055c816877b16044a728af5a35af2565 | f7d4bb0cb156cc6044fe61e7ed508d5bdcf68a07 | refs/heads/master | 2020-04-05T03:05:10.770413 | 2018-11-07T06:59:28 | 2018-11-07T06:59:28 | 156,500,818 | 0 | 0 | null | 2018-11-07T06:30:40 | 2018-11-07T06:30:40 | null | UTF-8 | C++ | false | false | 1,210 | cpp | //725 - Division
#include <iostream>
using namespace std;
char a[32350][7], temp[7];
int N=0, n;
bool exist, Free[15];
void Generate(int n) {
if (n==5) {
strcpy(a[N++], temp);
return;
}
for (int i=0; i<=9; i++)
if (Free[i]) {
Free[i] = false;
temp[n] = i+'0';
Generate(n+1);
Free[i] = true;
}
}
void Check(char snd[], int mul) {
int i;
char fir[7]; fir[5] = '\0';
memset(Free, true, 10);
for (i=0; i<5; i++) {
Free[snd[i]-48] = false;
fir[4-i] = char(mul%10)+'0'; mul/=10;
}
for (i=0; i<5; i++) {
int k = fir[i]-48;
if (Free[k]) Free[k] = false;
else return;
}
exist = true;
printf("%s / %s = %d\n", fir, snd, n);
}
main() {
bool End = false;
memset(Free, true, 10);
temp[5] = '\0';
Generate(0);
while (cin >> n && n) {
if (End) cout << endl; End = true;
exist = false;
for (int i=0; i<N; i++) {
int num = n*atoi(a[i]);
if (num<98766)
Check(a[i], num);
}
if (!exist) printf("There are no solutions for %d.\n", n);
}
}
| [
"[email protected]"
] | |
1602a9af0f37ffef18f93b6f260210d3475fa6d9 | fe94f2d2bfe9993c0c3c23be2e59fcb5d9cf1290 | /autotune/services/include/Sqlite3TuningDatabase.h | d6c23b66468a8dc270c0e7171782a63311ea4f55 | [
"BSD-3-Clause"
] | permissive | readex-eu/readex-ptf | 43f213d1bf8663a1e2790c49cce125bd817cef08 | 011ef4bf133476a10482c8c248027bcb651d4d57 | refs/heads/master | 2022-11-29T04:18:47.400222 | 2018-09-01T18:53:41 | 2018-09-01T18:53:41 | 139,039,087 | 1 | 2 | BSD-3-Clause | 2022-11-26T01:05:10 | 2018-06-28T15:48:19 | C++ | UTF-8 | C++ | false | false | 1,521 | h | #ifndef SQLITE3TUNINGDATABASE_H_
#define SQLITE3TUNINGDATABASE_H_
#include "config.h"
#include "TuningDatabase.h"
#ifdef PSC_SQLITE3_ENABLED
#include <sqlite3.h>
class sqlite3_error : public std::runtime_error {
public:
explicit sqlite3_error( const string& arg ) : runtime_error( arg ) {
}
};
class Sqlite3TuningDatabase : public TuningDatabase {
public:
explicit Sqlite3TuningDatabase( std::string filename );
~Sqlite3TuningDatabase();
Iterator<int>* queryPrograms();
ProgramSignature querySignature( int id );
Iterator<TuningCase>* queryCases( int id );
void saveSignature( ProgramID const& id,
ProgramSignature const& signature );
void saveTuningCase( ProgramID const& id,
TuningCase const& tc );
void commit();
private:
sqlite3* db; ///< SQLite3 database connection
void disableAutocommit();
int queryIdByText( ProgramID const& text );
boost::optional<int>selectBenchmark( ProgramID const& text );
int insertBenchmark( ProgramID const& text );
void insertCountersEntry( int id,
std::string feature,
INT64 value );
int insertMeasurementEntry( int bid,
double execTime );
void insertTuningValueEntry( int mid,
TuningValue const& tv );
};
#endif /* PSC_SQLITE3_ENABLED */
#endif /* SQLITE3TUNINGDATABASE_H_ */
| [
"[email protected]"
] | |
71032fe4b88da052606c48092b0e3d9fcf722ef9 | f879bf08c5ea4ae33d58010fda3af17126ab4389 | /src/Choreographer.cpp | 8593bdc1d996fe143af3b1daeadabcb1e9cee483 | [] | no_license | oturpe/fog-mover | e83c95c090425f84d05fd390cb91c9bbd59cd3cb | 69b21cd951c230fa299d87343b6532f665ad19cc | refs/heads/master | 2021-01-17T12:50:32.580124 | 2016-07-03T11:45:32 | 2016-07-03T11:45:32 | 57,836,738 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,953 | cpp | #include <avr/io.h>
#include "Choreographer.h"
#include "FogGeneratorController.h"
#include "PololuStepperController.h"
#include "ValveController.h"
Choreographer::Choreographer(
FogGeneratorController & fogMachine,
PololuStepperController & bellow,
ValveController & exitValve,
ValveController & topValve,
ValveController & bottomValve
) :
fogMachine(fogMachine),
bellow(bellow),
exitValve(exitValve),
topValve(topValve),
bottomValve(bottomValve),
counter(0) {
/*
for(uint8_t index = 0; index < CHOREOGRAPHY_LENGTH; index++) {
instants[index] = 0;
events[index] = NONE;
}
*/
}
void Choreographer::registerEvent(uint64_t instant, Event event) {
uint8_t index = 0;
while (instants[index]) {
index++;
}
instants[index] = instant;
events[index] = event;
}
void Choreographer::run() {
counter++;
uint8_t index = 0;
uint32_t instant = instants[index];
while(instant) {
if (counter == instant) {
runEvent(events[index]);
}
instant = instants[++index];
}
fogMachine.run();
bellow.run();
exitValve.run();
topValve.run();
bottomValve.run();
}
void Choreographer::runEvent(Event event) {
switch (event) {
case NONE:
return;
case BLOW_FOG:
fogMachine.blow();
return;
case PULL_FOG:
bellow.setDirection(true);
bellow.setEnable(true);
exitValve.setOpen(true, 0);
topValve.setOpen(true, 2 * SERVO_MOVE_PERIOD);
bottomValve.setOpen(false, 3 * SERVO_MOVE_PERIOD);
return;
case LOWER_BELLOW:
bellow.setDirection(false);
bellow.setEnable(false);
exitValve.setOpen(false,0);
topValve.setOpen(true, 2 * SERVO_MOVE_PERIOD);
bottomValve.setOpen(false, 3 * SERVO_MOVE_PERIOD);
return;
case END:
counter = 0;
return;
}
} | [
"[email protected]"
] | |
a38fc8a0599f00dab9c88db520d1a35f4598b682 | 7f255c8e466ecc172830323c4b2268ae428a8563 | /LINKED LIST.cpp | bb8589d8ce087528cdd50bd35c01051c9781443f | [] | no_license | hitechgaurav/Data-Structure-Using-C-and-C- | 03a2be83e77289f4ed61a30fc80d8ea3a684212b | 10454f254e7b52eb2f545883e69c77e51665aad3 | refs/heads/master | 2020-12-19T02:19:49.086895 | 2020-01-22T14:38:15 | 2020-01-22T14:38:15 | 235,591,754 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,645 | cpp | //Program to illustrate LINKED LIST
#include<iostream>
#include<conio.h>
using namespace std;
class node
{
public:
int data;
node *next;
};
class l_list
{
private:
node *top,*head;
public:
l_list();
void create();
void append(node*);
node *getnode();
void display();
void insert_beg();
void insert_des(int);
void delete_l(int pos);
};
l_list::l_list()
{
top=NULL;
}
void l_list::create()
{
node *newnode;
char ch;
while(ch!='n')
{
newnode=getnode();
if(top==NULL)
{
top=head=newnode;
}
else
append(newnode);
cout<<"\nPress n to break or else to continue: ";
cin>>ch;
}
}
void l_list::append(node *newnode)
{
if(top==NULL)
{
top=head=newnode;
}
else
{
top->next=newnode;
top=top->next;
}
}
node* l_list::getnode()
{
node *newnode;
newnode=new node;
cout<<"\nEnter data of node:- ";
cin>>newnode->data;
newnode->next=NULL;
return newnode;
}
void l_list::insert_beg()
{
node *newnode;
newnode=getnode();
newnode->next=head;
head=newnode;
}
void l_list::insert_des(int pos)
{
node *newnode;
newnode=getnode();
node *tmp=head;
int flag=1,count=1;
if(pos==1)
{
newnode->next=head;
head=newnode;
return;
}
while(count!=pos-1)
{
tmp=tmp->next;
if(tmp==NULL)
{
flag=0;
break;
}
count++;
}
if(flag==1)
{
newnode->next=tmp->next;
tmp->next=newnode;
}
else
cout<<"\nPosition not found.";
}
void l_list::delete_l(int pos)
{
if(pos==1)
{
node *temp=head;
head=head->next;
delete temp;
}
else
{
node *curr=head;
curr=curr->next;
node *temp=head;
int count=1,flag=1;
while(count!=pos-1)
{
curr=curr->next;
temp=temp->next;
if(curr==NULL)
{
flag=0;
break;
}
count++;
}
if(flag==1)
{
temp->next=curr->next;
delete curr;
return;
}
else
cout<<"\nPosition not found.";
}
}
void l_list::display()
{
cout<<"\nLinked List are: "<<endl;
node *temp=head;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
}
int main()
{
int pos;
l_list list1;
list1.create();
list1.display();
l_list list2;
list2.create();
cout<<"list created";
list2.display();
//list.insert_beg();
//list.display();
//cout<<"\nYou have called desired postion list entry system. please enter position where new node to be inserted."<<endl;
//cin>>pos;
//list.insert_des(pos);
//list.display();
//cout<<"\nEnter position to delete node: ";
//cin>>pos;
//list.delete_l(pos);
//list.display();
return 0;
}
| [
"[email protected]"
] | |
5bb707f331a3ee866cf36e7911421203332a5d90 | fcf0b03a0528eae28f91435eaa5166c06823ba39 | /FableMod.Gfx.Integration/ExtendedFrame.h | 7aaeba0c767e99e94e3e37883070d694117c5db4 | [] | no_license | DeanHnter/chocolate-box | 27f9ebe4fb8a4bc315fd60e737de5176faac0091 | df92d975d60c02cea1b0af1b4a8a6d797e7fbbad | refs/heads/master | 2022-05-01T20:42:34.919891 | 2019-07-19T14:41:58 | 2019-07-19T14:41:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 587 | h | #pragma once
#include <windows.h>
#include <memory.h>
#include <d3d9.h>
#include <d3dx9math.h>
using namespace System;
namespace FableMod
{
namespace Gfx
{
namespace Integration
{
struct D3DXEXTENDEDFRAME : public D3DXFRAME
{
ID3DXMesh* pSkinnedMesh;
FableMod::Gfx::TexturePtr spTexture;
FableMod::Gfx::TexturePtr spBumpMap;
FableMod::Gfx::TexturePtr spReflectMap;
bool bAlpha;
D3DXMATRIX* BoneMatrices;
D3DXEXTENDEDFRAME()
{
memset(this, 0, sizeof(*this));
}
~D3DXEXTENDEDFRAME()
{
Destroy();
}
void Destroy();
};
}
}
} | [
"[email protected]"
] | |
d00c44dc974685581933e0a286235c9e0aab565c | a603e9d52853ae836ec34102105b6920c7aad9f6 | /flow/cpp/magical_flow/src/db/DesignDB.cpp | 0e7f9298bfaf7a688e2b6b991972d255acc833f4 | [
"BSD-3-Clause"
] | permissive | magical-eda/MAGICAL | a8225e66653c411a5b1ec422233ef3f8d60dafff | 199ab0719f85f74c79bf85a556118b132988a5fe | refs/heads/master | 2022-11-19T04:36:36.542986 | 2021-09-10T22:14:57 | 2021-09-10T22:14:57 | 174,222,055 | 176 | 44 | BSD-3-Clause | 2021-09-10T22:14:58 | 2019-03-06T21:12:55 | C++ | UTF-8 | C++ | false | false | 1,692 | cpp | /*
* @file DesignDB.cpp
* @author Keren Zhu
* @date 06/26/2019
*/
#include "db/DesignDB.h"
#include <unordered_map>
PROJECT_NAMESPACE_BEGIN
bool DesignDB::findRootCkt()
{
if (this->numCkts() == 0) { return true; }
std::stack<IndexType> sortStack; //< Store the sorted indices here
std::vector<IntType> visited; //< Mark whether one sub circuit has been visited
std::stack<IndexType> stack; //< for DFS
// Initialize the variables
visited.resize(this->numCkts(), 0);
// DFS
for (IndexType startIdx = 0; startIdx < this->numCkts(); ++startIdx)
{
if (visited[startIdx] == 1)
{
continue;
}
stack.push(startIdx);
std::stack<IndexType> innerStack; //< Store the sorting of the current DFS
while (!stack.empty())
{
auto nodeIdx = stack.top();
stack.pop();
visited.at(nodeIdx) = 1;
for (const auto & childNode : _ckts.at(nodeIdx).nodeArray())
{
if (childNode.isLeaf())
{
continue;
}
IndexType graphIdx = childNode.subgraphIdx();
if (visited[graphIdx] == 1)
{
continue;
}
stack.push(graphIdx);
}
innerStack.push(nodeIdx); // Add to the vector (used as stack)
}
// Add the DFS result to the overall order
while (!innerStack.empty())
{
sortStack.push(innerStack.top());
innerStack.pop();
}
}
_rootCkt = sortStack.top();
return true;
}
PROJECT_NAMESPACE_END
| [
"[email protected]"
] | |
6088a9357710017d61c6d8d2e965f7e9fbb0975b | cfd07462c76839287112e7a1b5e7b8d3156e9ffa | /New Ping/New Ping.ino | b7474b9996408eeb0821044816d7221d27fff6b1 | [] | no_license | wbrown97a/Basic-Arduino | c845bd73fadfecf6888c01d661c9f7b992d3720e | b4d33dffdac912e1ef5568cbf9ab9de386a64eb7 | refs/heads/master | 2021-01-03T01:21:45.190589 | 2020-03-13T19:43:21 | 2020-03-13T19:43:21 | 239,855,188 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 384 | ino | #include <NewPing.h>
#define TRIGGER_PIN 2
#define ECHO_PIN 4
#define MAX_DISTANCE 200
NewPing myHCSR04(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
void setup() {
Serial.begin(9600);
pinMode(13,OUTPUT);
}
void loop() {Serial.println(myHCSR04.ping_cm());
delay(50);
if (myHCSR04.ping_cm() > 5)
digitalWrite(13, HIGH);
else
digitalWrite(13, LOW);
}
| [
"[email protected]"
] | |
e72c8b0cf00043968179187c28d41213144ddb4a | 9a488a219a4f73086dc704c163d0c4b23aabfc1f | /tags/Release-0_9_2/src/RootTheme.hh | e848e66c5c6bad7c8a87fba405ee80b5be692a32 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | BackupTheBerlios/fluxbox-svn | 47b8844b562f56d02b211fd4323c2a761b473d5b | 3ac62418ccf8ffaddbf3c181f28d2f652543f83f | refs/heads/master | 2016-09-05T14:55:27.249504 | 2007-12-14T23:27:57 | 2007-12-14T23:27:57 | 40,667,038 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,375 | hh | // RootTheme.hh
// Copyright (c) 2003 Henrik Kinnunen (fluxgen(at)users.sourceforge.net)
//
// 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.
// $Id: RootTheme.hh,v 1.1 2003/04/25 10:14:54 fluxgen Exp $
#ifndef ROOTTHEME_HH
#define ROOTTHEME_HH
#include "FbTk/Theme.hh"
#include "Color.hh"
#include <X11/Xlib.h>
#include <string>
/**
Contains border color, border size, bevel width and opGC for objects like
geometry window in BScreen
*/
class RootTheme: public FbTk::Theme {
public:
/// constructor
/// @param screen_num the screen number
/// @param screen_root_command the string to be executed override theme rootCommand
RootTheme(int screen_num, std::string &screen_root_command);
~RootTheme();
void reconfigTheme();
const FbTk::Color &borderColor() const { return *m_border_color; }
int borderWidth() const { return *m_border_width; }
int bevelWidth() const { return *m_bevel_width; }
int handleWidth() const { return *m_handle_width; }
GC opGC() const { return m_opgc; }
private:
FbTk::ThemeItem<std::string> m_root_command;
FbTk::ThemeItem<int> m_border_width, m_bevel_width, m_handle_width;
FbTk::ThemeItem<FbTk::Color> m_border_color;
std::string &m_screen_root_command; ///< string to execute and override theme rootCommand
GC m_opgc;
};
#endif // ROOTTHEME_HH
| [
"(no author)@54ec5f11-9ae8-0310-9a2b-99d706b22625"
] | (no author)@54ec5f11-9ae8-0310-9a2b-99d706b22625 |
d9bb2e8333c781126e4e85160bae3e92fd2d579f | e071a601b9cb597511ed637800f000b428bf8491 | /ext/soui/soui/UIEngine/UIEngine.h | 845448669ebc8da5e9317ebaa3062fb3ad843520 | [
"MIT"
] | permissive | radtek/oIM | 7964ed39421f8dab37d75c1b252f517bbed747fd | 0a439b34bee703c50772ce1029e126f1da624576 | refs/heads/master | 2020-05-25T10:54:16.054941 | 2018-01-12T13:44:23 | 2018-01-12T13:44:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 486 | h | //SOUI组件配置
#pragma once
#include <com-def.h>
#include <com-loaderex.hpp>
#include <interface\szip-i.h>
# define UIENGINE_DLL _T("UIEngine.dll")
class SUIEngine
{
public:
SUIEngine()
{
}
BOOL CreateZip(IObjRef **ppObj)
{
return UIEngine.CreateInstance(UIENGINE_DLL, ppObj, INAME_ZIP);
}
BOOL Create7Zip(IObjRef **ppObj)
{
return UIEngine.CreateInstance(UIENGINE_DLL, ppObj, INAME_7ZIP);
}
protected:
SComLoaderEx UIEngine;
};
| [
"lwq@2015"
] | lwq@2015 |
74b8af949547774a9ce0ba374709c0fdc642ebb2 | 502acfbf60879aaeb4f5bae4fe5ebe84accec734 | /src/picacoin-wallet.cpp | d0613eecec5d530acc6c492973ccfe096d8206a0 | [
"MIT"
] | permissive | picacoin/picacoin | 43415691bb84be2b26d897b11ee66b7e289ca5b4 | a6b6c1053d796fac077d1c4ce63e09014002b364 | refs/heads/main | 2022-07-28T10:53:15.869086 | 2021-06-24T02:31:01 | 2021-06-24T02:31:01 | 367,504,237 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,360 | cpp | // Copyright (c) 2016-2020 The Picacoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/picacoin-config.h>
#endif
#include <chainparams.h>
#include <chainparamsbase.h>
#include <logging.h>
#include <util/system.h>
#include <util/translation.h>
#include <util/url.h>
#include <wallet/wallettool.h>
#include <functional>
const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr;
UrlDecodeFn* const URL_DECODE = nullptr;
static void SetupWalletToolArgs(ArgsManager& argsman)
{
SetupHelpOptions(argsman);
SetupChainParamsBaseOptions(argsman);
argsman.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
argsman.AddArg("-datadir=<dir>", "Specify data directory", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
argsman.AddArg("-wallet=<wallet-name>", "Specify wallet name", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::OPTIONS);
argsman.AddArg("-dumpfile=<file name>", "When used with 'dump', writes out the records to this file. When used with 'createfromdump', loads the records into a new wallet.", ArgsManager::ALLOW_STRING, OptionsCategory::OPTIONS);
argsman.AddArg("-debug=<category>", "Output debugging information (default: 0).", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
argsman.AddArg("-descriptors", "Create descriptors wallet. Only for 'create'", ArgsManager::ALLOW_BOOL, OptionsCategory::OPTIONS);
argsman.AddArg("-format=<format>", "The format of the wallet file to create. Either \"bdb\" or \"sqlite\". Only used with 'createfromdump'", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
argsman.AddArg("-printtoconsole", "Send trace/debug info to console (default: 1 when no -debug is true, 0 otherwise).", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
argsman.AddCommand("info", "Get wallet info", OptionsCategory::COMMANDS);
argsman.AddCommand("create", "Create new wallet file", OptionsCategory::COMMANDS);
argsman.AddCommand("salvage", "Attempt to recover private keys from a corrupt wallet. Warning: 'salvage' is experimental.", OptionsCategory::COMMANDS);
argsman.AddCommand("dump", "Print out all of the wallet key-value records", OptionsCategory::COMMANDS);
argsman.AddCommand("createfromdump", "Create new wallet file from dumped records", OptionsCategory::COMMANDS);
}
static bool WalletAppInit(ArgsManager& args, int argc, char* argv[])
{
SetupWalletToolArgs(args);
std::string error_message;
if (!args.ParseParameters(argc, argv, error_message)) {
tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error_message);
return false;
}
if (argc < 2 || HelpRequested(args) || args.IsArgSet("-version")) {
std::string strUsage = strprintf("%s picacoin-wallet version", PACKAGE_NAME) + " " + FormatFullVersion() + "\n";
if (!args.IsArgSet("-version")) {
strUsage += "\n"
"picacoin-wallet is an offline tool for creating and interacting with " PACKAGE_NAME " wallet files.\n"
"By default picacoin-wallet will act on wallets in the default mainnet wallet directory in the datadir.\n"
"To change the target wallet, use the -datadir, -wallet and -testnet/-regtest arguments.\n\n"
"Usage:\n"
" picacoin-wallet [options] <command>\n";
strUsage += "\n" + args.GetHelpMessage();
}
tfm::format(std::cout, "%s", strUsage);
return false;
}
// check for printtoconsole, allow -debug
LogInstance().m_print_to_console = args.GetBoolArg("-printtoconsole", args.GetBoolArg("-debug", false));
if (!CheckDataDirOption()) {
tfm::format(std::cerr, "Error: Specified data directory \"%s\" does not exist.\n", args.GetArg("-datadir", ""));
return false;
}
// Check for chain settings (Params() calls are only valid after this clause)
SelectParams(args.GetChainName());
return true;
}
int main(int argc, char* argv[])
{
ArgsManager& args = gArgs;
#ifdef WIN32
util::WinCmdLineArgs winArgs;
std::tie(argc, argv) = winArgs.get();
#endif
SetupEnvironment();
RandomInit();
try {
if (!WalletAppInit(args, argc, argv)) return EXIT_FAILURE;
} catch (const std::exception& e) {
PrintExceptionContinue(&e, "WalletAppInit()");
return EXIT_FAILURE;
} catch (...) {
PrintExceptionContinue(nullptr, "WalletAppInit()");
return EXIT_FAILURE;
}
const auto command = args.GetCommand();
if (!command) {
tfm::format(std::cerr, "No method provided. Run `picacoin-wallet -help` for valid methods.\n");
return EXIT_FAILURE;
}
if (command->args.size() != 0) {
tfm::format(std::cerr, "Error: Additional arguments provided (%s). Methods do not take arguments. Please refer to `-help`.\n", Join(command->args, ", "));
return EXIT_FAILURE;
}
ECCVerifyHandle globalVerifyHandle;
ECC_Start();
if (!WalletTool::ExecuteWalletToolFunc(args, command->command)) {
return EXIT_FAILURE;
}
ECC_Stop();
return EXIT_SUCCESS;
}
| [
"[email protected]"
] | |
01d68840b4c26560d0b17e675c614a082443c2d4 | d4f2df282ef9a8ad104f93799995c24c4fd9554e | /kumite_projects/date-event-base.cpp | 1c08a9d0c42b88c1b1e4d5dc76beb6b33e424760 | [
"BSD-3-Clause"
] | permissive | Pythonimous/learning-cpp | d1f0a50e09e43df027f593a9ab986b9ad898768e | d4a32ebbf9ca28aace619746de5b2580a8debd93 | refs/heads/main | 2023-08-27T04:32:50.637949 | 2021-11-11T13:29:58 | 2021-11-11T13:29:58 | 339,829,084 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,467 | cpp | #include <iostream>
#include <sstream>
#include <iomanip>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <exception>
/*
Final project of the 1 / 5 course of the specialization.
A simple Date-Event database.
Supports dates of format yyyy-mm-dd. 1 <= mm <= 12; 1 <= dd <= 31.
Months, leap years and complex (i.e. multiline) requests to be added later.
Processes an istream of commands until over.
*/
using namespace std;
class Date {
public:
Date() {}
Date(int y, int m, int d) {
year_ = y;
if (m < 1 || m > 12) { // if month not in [1: 12]
throw range_error("Month value is invalid: " + to_string(m));
} else if (d < 1 || d > 31) { // if day not in [1: 31]
throw range_error("Day value is invalid: " + to_string(d));
} else { // if everything else is okay
year_ = y;
month_ = m;
day_ = d;
}
}
int GetYear() const {
return year_;
}
int GetMonth() const {
return month_;
}
int GetDay() const {
return day_;
}
private:
int year_ = 0;
int month_ = 1;
int day_ = 1;
};
istream& operator >> (istream& input, Date& date) {
// Overloads an >> operator for a date string to a Date object.
// Correct string format: y-m-d, no extra symbols before y and after d are allowed.
string to_parse;
input >> to_parse;
if (!to_parse.empty()) {
int year, month, day;
char sep1, sep2;
istringstream ss(to_parse);
ss >> year >> sep1 >> month >> sep2;
if (!(ss >> day)) { throw runtime_error("Wrong date format: " + to_parse); }
if (!ss.eof()) { throw runtime_error("Wrong date format: " + to_parse); }
if (sep1 == '-' && sep2 == '-') {
date = Date(year, month, day);
}
else {
throw runtime_error("Wrong date format: " + to_parse);
}
}
return input;
}
ostream& operator << (ostream& output, Date date) {
output << setw(4) << setfill('0') << date.GetYear() << '-'
<< setw(2) << setfill('0') << date.GetMonth() << '-'
<< setw(2) << setfill('0') << date.GetDay();
return output;
}
bool operator < (const Date& ld, const Date& hd) {
return vector<int>{ld.GetYear(), ld.GetMonth(), ld.GetDay()} <
vector<int>{hd.GetYear(), hd.GetMonth(), hd.GetDay()};
}
class Database {
public:
void AddEvent(const Date& date, const string& event) {
// cin Add date event
// Adds an event for a given date in a database.
db[date].insert(event);
}
bool DeleteEvent(const Date& date, const string& event) {
// cin Delete date event
// Deletes an event from a given date in a database.
if (db[date].count(event) == 1) {
db[date].erase(event);
return true;
} else { // no events for a given date
return false;
}
}
int DeleteDate(const Date& date) {
// cin Delete date
// Deletes all the events for a given date in a database
int n = db[date].size();
db.erase(date);
return n;
}
void Find(const Date& date) const {
// cin Find date
// Prints all the events for a given date in an alphabet order
if (db.count(date) == 1) {
for (auto event : db.at(date)) {
cout << event << endl;
}
}
}
void Print() const {
// cin Print
// Prints all (date - event) pairs in a table in chronological -> alphabetic order.
for (auto item : db) {
for (string event : item.second) {
cout << item.first << ' ' << event << endl;
}
}
}
private:
map<Date, set<string>> db;
};
int main() {
try {
Database db;
string command;
while (getline(cin, command)) {
istringstream ss(command);
string cmd;
ss >> cmd;
if (cmd == "Print") {
db.Print();
} else if (set<string>{"Add", "Del", "Find"}.count(cmd) == 1) {
string event;
Date date;
ss >> date >> event;
if (cmd == "Find") {
db.Find(date);
} else if (cmd == "Add") {
db.AddEvent(date, event);
} else { // if command == "Del"
if (event.empty()) {
int n = db.DeleteDate(date);
cout << "Deleted " << n << " events" << endl;
} else {
bool deleted = db.DeleteEvent(date, event);
if (deleted) { cout << "Deleted successfully" << endl;
} else { cout << "Event not found" << endl; }
}
}
} else if (command.empty()) {
} else { // if command is not recognized
throw runtime_error("Unknown command: " + cmd);
}
}
} catch (runtime_error& err) {
cout << err.what() << endl;
}
return 0;
}
| [
"[email protected]"
] | |
1d0264ab584313aa5f374b80def97ea34f170280 | 78918391a7809832dc486f68b90455c72e95cdda | /boost_lib/boost/type_traits/is_float.hpp | 0f0b1519bc081c8e8d6c82f4d977c7e3289a6d70 | [
"MIT"
] | permissive | kyx0r/FA_Patcher | 50681e3e8bb04745bba44a71b5fd04e1004c3845 | 3f539686955249004b4483001a9e49e63c4856ff | refs/heads/master | 2022-03-28T10:03:28.419352 | 2020-01-02T09:16:30 | 2020-01-02T09:16:30 | 141,066,396 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 786 | hpp | // (C) Copyright Steve Cleary, Beman Dawes, Howard Hinnant & John Maddock 2000.
// Use, modification and distribution are subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt).
//
// See http://www.boost.org/libs/type_traits for most recent version including documentation.
#ifndef BOOST_TYPE_TRAITS_IS_FLOAT_HPP_INCLUDED
#define BOOST_TYPE_TRAITS_IS_FLOAT_HPP_INCLUDED
// should be the last #include
#include <boost/type_traits/is_floating_point.hpp>
namespace boost
{
//* is a type T a floating-point type described in the standard (3.9.1p8)
template <class T> struct is_float : public is_floating_point<T> {};
} // namespace boost
#endif // BOOST_TYPE_TRAITS_IS_FLOAT_HPP_INCLUDED
| [
"[email protected]"
] | |
e16daf535294dfe272aae44b3852f5711c67c713 | 2373e540b14b2b4fb105ab4ed48f5decaa4aa2fc | /vanhove/main_vhove.cpp | e0d7b0764b5dea9c9db5848411207359a1b10a3f | [] | no_license | hiddevuijk/abp_simulation | a853f806ab51b4701865b01c53f5e645a5767335 | 1dacb28ded034a2bff8528edeea395db6b030d73 | refs/heads/master | 2020-04-05T14:09:42.764262 | 2017-10-30T15:08:01 | 2017-10-30T15:08:01 | 94,788,092 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,827 | cpp |
#include <iostream>
#include <vector>
#include <string>
#include <random>
#include "read.h"
#include "deriv.h"
#include "integrate.h"
#include "pair_distribution.h"
#include "diffconst.h"
#include "fcc_lattice.h"
#include "vanHove.h"
#include "orientation.h"
using namespace std;
int main(int argc, char *argv[])
{
// number of particles
int N;
//density
double rho;
// size of the box
double L;
// diff consts
double Dt,Dr;
// swim speed
double v0;
//porential parameters
double gamma, beta, sigma,eps;
// Van Hove parameters
double dt_vh,tm,dr_vh,rm;
int Nt_vh,Nr_vh;
// inital time used to equilibrate
double teq;
// integration time step
double dt;
// average over navg vanHove functions
int navg;
// seed for the random number generator
int seed;
// name of the output file
string name;
// name of the input file
// default is input.txt, otherwise commandline input
string input_name = "input.txt";
if(argc == 2) {
input_name = argv[1];
input_name += ".txt";
}
// read variables from input file
read_variables_vhove(N,rho,Dt,Dr,v0,gamma,beta,eps,sigma,dt,dt_vh,tm,dr_vh,rm,teq,navg,seed,name,input_name);
L = pow(N/rho,1./3);
Nt_vh = tm/dt_vh+1;
Nr_vh = rm/dr_vh+1;
vector<double> t_vh(Nt_vh,0.0);
vector<double> r_vh(Nr_vh,0.0);
for(int i=0;i<Nt_vh;++i)
t_vh[i] = (i+1)*dt_vh;
// r_vh contains the right values of the bins
for(int i=0;i<Nr_vh;++i)
r_vh[i] = (i+1)*dr_vh;
// omega = -1 -> v0 = v
Deriv deriv(N,L,Dt,Dr,v0,-1,gamma,beta,eps,sigma,seed);
default_random_engine gen(seed);
vector<vector<double> > r(N,vector<double>(3));
vector<vector<double> > dr(N,vector<double>(3));
vector<vector<double> > p(N,vector<double>(3,1.));
vector<vector<double> > dp(N,vector<double>(3,1.));
// start with random p(t=0)
rand_vecs(p,N,3,-.5*L,.5*L,gen,1.);
// start with particles on fcc lattic
// with largest possible lattice spacing
init_r_fcc(r,N,sigma,L);
// integrate until teq in order to equilibrate
integrate(r,dr,p,dp,deriv,0,teq,dt);
// initial position vectors
vector<vector<double> > r0 = r;
// Van Hove result
vector<vector<double> > vhove(Nt_vh,vector<double>(Nr_vh,0.0));
// van Hove single measurement
vector<vector<double> > vhove_temp(Nt_vh,vector<double>(Nr_vh,0.0));
for(int avgi = 0;avgi<navg;++avgi) {
r0 = r;
for( int ti =0;ti<Nt_vh;ti++) {
integrate(r,dr,p,dp,deriv,0,dt_vh,dt);
get_vhove(vhove_temp[ti],r,r0,dr_vh,Nr_vh);
}
add2result(vhove,vhove_temp,navg);
}
// shift r_vh with -0.5*dr_vh to get mid points of the bins
for(int i=0;i<r_vh.size();++i)
r_vh[i] -= 0.5*dr_vh;
// devide vhove by 4*pi*dr*r^2
normalize_vh(vhove,r_vh);
if(name != "") name += '_';
write_vec(r_vh,name+"r.dat");
write_vec(t_vh,name+"t.dat");
write_mat(vhove,Nt_vh,Nr_vh,name+"vhove.dat");
return 0;
}
| [
"[email protected]"
] | |
0310c9d688c16067263467fafd9ee721030dbd6e | 05087ffdddfe3f13a8e5f3bd3ca10c6212220bdb | /HW.DS2.C3/HW.DS2.C3/HW.DS2.C3.cpp | 43657811c4388957765cf08a4bacb37260cf8cf7 | [
"MIT"
] | permissive | LeeInJae/Algorithm | d2397c44f6d7c1b516981f6269b7e8c6ada59d4e | ec9d539a96fd87c3c0fdd4067e10900f7cddbaf9 | refs/heads/master | 2021-07-09T14:39:44.035975 | 2016-10-30T15:38:55 | 2016-10-30T15:38:55 | 22,943,693 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,353 | cpp | // HW.DS2.C3.cpp : 콘솔 응용 프로그램에 대한 진입점을 정의합니다.
//
#include "stdafx.h"
#include <string.h>
#define TRUE 1
#define FALSE 0
typedef struct human{
char * name;
int age;
float salary;
}human_t;
void setPerson(human_t * person, char * name, int age, float salary){
person->name = name;
person->age = age;
person->salary = salary;
}
int humansEqualvalue(human_t person1, human_t person2){
if (strcmp(person1.name, person2.name)){
return FALSE;
}
else if (person1.age != person2.age){
return FALSE;
}
else if (person1.salary != person2.salary)
{
return FALSE;
}
return TRUE;
}
int humansEqualReference(human_t * person1, human_t * person2){
if (strcmp(person1->name, person2->name)){
return FALSE;
}
else if (person1->age != person2->age){
return FALSE;
}
else if (person1->salary != person2->salary)
{
return FALSE;
}
return TRUE;
}
int _tmain(int argc, _TCHAR* argv[])
{
human_t person1, person2;
setPerson(&person1, "LeeInJae", 26, 1000000000);
setPerson(&person2, "LeeInJae", 22, 1000000000);
printf("CallByValue Check Person1, Person2 = %d\n", humansEqualvalue(person1, person2));
printf("CallByReference Check Person1, Person2 = %d\n", humansEqualReference(&person1, &person2));
getchar();
return 0;
}
| [
"[email protected]"
] | |
e472ee60877a1913c5cfe113c4a11134a7b395cf | d72c583f762925436cc05ef548414e7d316d84bd | /Github/Source/moc_fill.cpp | 5fd0df2b9f94de1707700cd399dbba746dde7dd6 | [] | no_license | MaksSmagin999/Source-Mini-Graphics-Editor.-Qt5-C- | 6db2d69f09f7e1d42bc73548cf13af13e1095488 | 8ca55e114b7d2b8a643b002c748b364d095490ae | refs/heads/master | 2022-04-11T15:09:29.407974 | 2020-04-04T10:55:30 | 2020-04-04T10:55:30 | 251,317,492 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,750 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'fill.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.14.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include <memory>
#include "GraphicDisplay/fill.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'fill.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.14.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_ToolFill_t {
QByteArrayData data[1];
char stringdata0[9];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_ToolFill_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_ToolFill_t qt_meta_stringdata_ToolFill = {
{
QT_MOC_LITERAL(0, 0, 8) // "ToolFill"
},
"ToolFill"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_ToolFill[] = {
// content:
8, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
void ToolFill::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
QT_INIT_METAOBJECT const QMetaObject ToolFill::staticMetaObject = { {
QMetaObject::SuperData::link<ToolCore::staticMetaObject>(),
qt_meta_stringdata_ToolFill.data,
qt_meta_data_ToolFill,
qt_static_metacall,
nullptr,
nullptr
} };
const QMetaObject *ToolFill::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *ToolFill::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_ToolFill.stringdata0))
return static_cast<void*>(this);
return ToolCore::qt_metacast(_clname);
}
int ToolFill::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = ToolCore::qt_metacall(_c, _id, _a);
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| [
"[email protected]"
] | |
f2ab6b23c20f3ba14df952720e0c33c4e076367d | cbea49eecad8f9e13d7c6170b496ca5db4147cb2 | /Programming-Techniques/T6/Z1/main.cpp | 1a91603d6a35aeb0ab8a05365632dfcd279ae969 | [] | no_license | amsiljak/c9-Projects | ea53221a9d83f955d8225797950783db8ae7be8f | 60a8242cd6dbf8edefc47bde3b0daa0f15993cdc | refs/heads/main | 2023-04-21T03:05:41.851590 | 2021-05-02T23:02:57 | 2021-05-02T23:02:57 | 363,766,433 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,449 | cpp | /*
TP 16/17 (Tutorijal 6, Zadatak 1)
Autotestovi by Kerim Hodzic. Prijave gresaka, pitanja
i sugestije saljite na mail: [email protected]
Napomene: testovi su konacni tek pred tutorijal
za krsenje zabrana dobiva se 0 bodova za zadatak
*/
#include <iostream>
#include <cmath>
#include <new>
#include <stdexcept>
#include <limits>
template <typename TipNiza>
TipNiza *GenerirajStepeneDvojke(int n)
{
try {
TipNiza *p;
if(n<=0) throw std::domain_error("Broj elemenata mora biti pozitivan");
p=new TipNiza[n];
for(int i=0;i<n;i++)
{
if(powl(2,i)>(std::numeric_limits<TipNiza>::max()))
{
delete[] p;
throw std::overflow_error("Prekoracen dozvoljeni opseg");
}
p[i]=powl(2,i);
}
return p;
}
catch (std::bad_alloc) {
throw std::runtime_error("Alokacija nije uspjela");
}
catch(std::domain_error)
{
throw;
}
catch(std::overflow_error)
{
throw;
}
}
int main ()
{
try{
int n;
std::cout<<"Koliko zelite elemenata: ";
std::cin>>n;
if(n<=0) throw std::domain_error("Broj elemenata mora biti pozitivan");
auto a=GenerirajStepeneDvojke<int>(n);
for(int i=0;i<n;i++)
{
std::cout<<a[i]<<" ";
}
delete[] a;
}
catch(std::domain_error e)
{
std::cout<<"Izuzetak: "<<e.what()<<std::endl;
}
catch(std::overflow_error e)
{
std::cout<<"Izuzetak: "<<e.what()<<std::endl;
}
catch(std::bad_alloc e)
{
std::cout<<"Izuzetak: "<<e.what()<<std::endl;
}
return 0;
} | [
"[email protected]"
] | |
545ac2dc1fc4aecbd9ccb2e97ffbc5928da412b8 | 711c4e7bea9c3a656605ba1ed0d6f7bd1935ccc0 | /ShaderManager.h | 50588d2abd0eaf1f98ac7d2cbc45423242b1cab3 | [] | no_license | Cuteposter/Witchgame | 74f12be45cf6d35497ad9defa31d63f19ec19c8e | d6e79914e036d86080740d6723422e66cb5ca069 | refs/heads/master | 2021-01-21T04:35:20.673187 | 2016-07-04T04:53:08 | 2016-07-04T04:53:08 | 55,560,818 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,335 | h | /**
Copyright (c) 2012 - Luu Gia Thuy
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.
*/
#pragma once
#ifndef SHADER_MANAGER_H
#define SHADER_MANAGER_H
#include <string>
#include <map>
// Forward declaration
class CShader;
class CShaderManager
{
////////////////////////////////////////////////////////////
// Types
////////////////////////////////////////////////////////////
protected:
typedef std::map<std::string, CShader*> TShaderMap;
////////////////////////////////////////////////////////////
// Fields
////////////////////////////////////////////////////////////
protected:
/// Map of shader name and shader obj pointer
TShaderMap m_ShaderMap;
/// Default shader string
static const char* DEFAULT_SHADER;
/// The unique instance of this class
static CShaderManager* s_Instance;
////////////////////////////////////////////////////////////
// Methods
////////////////////////////////////////////////////////////
public:
/// Destructor
~CShaderManager();
// Get the unique instance of this class
static CShaderManager* GetInstance();
/**
* Get shader object pointer
* @return if successful load/link, the loaded/linked shader object point is return, otherwise return the default shader
*/
CShader* GetShader(const char* inVertFileName, const char* inFragFileName, const char* inGeomFileName);
protected:
/// Default constructor (protected)
CShaderManager();
/**
* Load, compile and create a vertex/fragment/geometric shader program and link the program
* @return CShader object pointer if all shaders are loaded successfully, NULL otherwise
*/
CShader* Load(const char* inVertexFilename
, const char* inFragmentFilename
, const char* inGeometryFilename);
/** Releases all resources */
void Dispose(CShader* inShader);
/**
* Load and compile a shader
* @param inShaderType type of shader: GL_VERTEX_SHADER, GL_GEOMETRY_SHADER_EXT or GL_FRAGMENT_SHADER
* @param inFileName shader file name
* @param inOutShader the pointer to shader
* @return true if successfully loaded, false otherwise
*/
bool LoadShader(unsigned int inShaderType, const std::string& inFileName, unsigned int & inOutShader);
/**
* Load a shader source code from a file.
* @return the pointer to the source
*/
char** LoadSource(int& outLineCount, const std::string& inFileName);
}; // end class ShaderManager
#endif | [
"[email protected]"
] | |
a8fef47f8ef716d61296938883514d53c331c5fd | dc38a39ddaa88b01353d28daecf133e77b04a6be | /codeforces/div3_555/p4.cpp | f7849022dae7cdb17e1e1c141118bc01d3a616e2 | [] | no_license | alexriderspy/Competitive-Programming | de57a7a5af617f979063d528ca0ae12c22f29036 | 30c1809800411a361d557a4e98921c6fdc0eb7b2 | refs/heads/main | 2023-06-01T02:12:19.587635 | 2021-07-09T04:06:21 | 2021-07-09T04:06:21 | 384,316,770 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,780 | cpp | #include<bits/stdc++.h>
using namespace std;
typedef vector<int> VI;
typedef vector<vector<int>> VVI;
typedef vector<string> VS;
typedef vector<vector<string>> VVS;
typedef signed long long i64;
typedef unsigned long long u64;
#define pi pair<int, int>
#define mod 1000000007
#define ll long long
#define ld long double
#define fu(i, m, n) for (ll i = (m); i < (n); ++i)
#define fr(i, S, E) for (typeof(E) i = (S); i != (E); ++i)
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define YES cout<<"YES"<<endl;
#define NO cout<<"NO"<<endl;
ll fact(ll n){
ll p=1;
for(ll k=1;k<=n;k++){
p*=k;
p=p%mod;
}
p=p%mod;
return p;
}
ll power(ll n, ll k){
ll p=1;
while(k--){
p*=n;
}
return p;
}
bool cmp(pair<ll, ll> a, pair<ll, ll> b) {return a.second < b.second;}
void solve(){
int n,f=0;
cin>>n;
vector<int>a,cl,cr;
vector<char>dl,dr;
for(int i=0;i<n;i++){
int tmp;
cin>>tmp;
a.push_back(tmp);
}
cl.push_back(0);
cr.push_back(0);
//vector<int>b(a.rbegin(),a.rend());
// fu(i,0,n) cout<<b[i]<<" ";
int i=0,j=n-1;
while(i<=j){
if(max(a[i],a[j])<=cl.back()) break;
if(a[j]<a[i]){
if(a[j]>cl.back()){
dl.push_back('R');
dr.push_back('R');
cr.push_back(a[j]);
cl.push_back(a[j]);j--;
}else{
dl.push_back('L');
cl.push_back(a[i]);
dr.push_back('L');
//dl.push_back('L');
cr.push_back(a[i]);i++;
}
}
else if(a[i]<a[j]){
if(a[i]>cr.back()){
dr.push_back('L');
cl.push_back(a[i]);
dl.push_back('L');
cr.push_back(a[i]);i++;
}else{
dl.push_back('R');
dr.push_back('R');
cl.push_back(a[j]);
cr.push_back(a[j]);j--;
}
}
else{
f=1;break;
}
}
int si=i,sj=j;
//considering l
if(f==1){
while(si<=sj){
if(a[si]<=cl.back()) break;
if(a[si]>cl.back()){
cl.push_back(a[si]);dl.push_back('L');si++;
}
}
while(i<=j){
if(a[j]<=cr.back()) break;
if(a[j]>cr.back()){
cr.push_back(a[j]);dr.push_back('R');j--;
}
}
}
if(dr.size()>dl.size()){
int h=dr.size();
cout<<h<<"\n";
for(char ch:dr){
cout<<ch; }
cout<<"\n";
}else{
int h=dl.size();
cout<<h<<"\n";
for(char ch:dl){
cout<<ch; }
cout<<"\n";
}
}
int main()
{
ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
//ll t;cin>>t;
solve();
}
| [
"[email protected]"
] | |
0842966219719ee98fb8d963d9145100a500ccf1 | fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd | /third_party/crashpad/crashpad/snapshot/test/test_process_snapshot.h | 7dd312475c490d0b3c08723a07567c0eb82b90c0 | [
"Apache-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT"
] | permissive | wzyy2/chromium-browser | 2644b0daf58f8b3caee8a6c09a2b448b2dfe059c | eb905f00a0f7e141e8d6c89be8fb26192a88c4b7 | refs/heads/master | 2022-11-23T20:25:08.120045 | 2018-01-16T06:41:26 | 2018-01-16T06:41:26 | 117,618,467 | 3 | 2 | BSD-3-Clause | 2022-11-20T22:03:57 | 2018-01-16T02:09:10 | null | UTF-8 | C++ | false | false | 6,896 | h | // Copyright 2014 The Crashpad Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef CRASHPAD_SNAPSHOT_TEST_TEST_PROCESS_SNAPSHOT_H_
#define CRASHPAD_SNAPSHOT_TEST_TEST_PROCESS_SNAPSHOT_H_
#include <stdint.h>
#include <sys/time.h>
#include <sys/types.h>
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/macros.h"
#include "snapshot/exception_snapshot.h"
#include "snapshot/memory_map_region_snapshot.h"
#include "snapshot/memory_snapshot.h"
#include "snapshot/module_snapshot.h"
#include "snapshot/process_snapshot.h"
#include "snapshot/system_snapshot.h"
#include "snapshot/thread_snapshot.h"
#include "snapshot/unloaded_module_snapshot.h"
#include "util/misc/uuid.h"
#include "util/stdlib/pointer_container.h"
namespace crashpad {
namespace test {
//! \brief A test ProcessSnapshot that can carry arbitrary data for testing
//! purposes.
class TestProcessSnapshot final : public ProcessSnapshot {
public:
TestProcessSnapshot();
~TestProcessSnapshot() override;
void SetProcessID(pid_t process_id) { process_id_ = process_id; }
void SetParentProcessID(pid_t parent_process_id) {
parent_process_id_ = parent_process_id;
}
void SetSnapshotTime(const timeval& snapshot_time) {
snapshot_time_ = snapshot_time;
}
void SetProcessStartTime(const timeval& start_time) {
process_start_time_ = start_time;
}
void SetProcessCPUTimes(const timeval& user_time,
const timeval& system_time) {
process_cpu_user_time_ = user_time;
process_cpu_system_time_ = system_time;
}
void SetReportID(const UUID& report_id) { report_id_ = report_id; }
void SetClientID(const UUID& client_id) { client_id_ = client_id; }
void SetAnnotationsSimpleMap(
const std::map<std::string, std::string>& annotations_simple_map) {
annotations_simple_map_ = annotations_simple_map;
}
//! \brief Sets the system snapshot to be returned by System().
//!
//! \param[in] system The system snapshot that System() will return. The
//! TestProcessSnapshot object takes ownership of \a system.
void SetSystem(std::unique_ptr<SystemSnapshot> system) {
system_ = std::move(system);
}
//! \brief Adds a thread snapshot to be returned by Threads().
//!
//! \param[in] thread The thread snapshot that will be included in Threads().
//! The TestProcessSnapshot object takes ownership of \a thread.
void AddThread(std::unique_ptr<ThreadSnapshot> thread) {
threads_.push_back(thread.release());
}
//! \brief Adds a module snapshot to be returned by Modules().
//!
//! \param[in] module The module snapshot that will be included in Modules().
//! The TestProcessSnapshot object takes ownership of \a module.
void AddModule(std::unique_ptr<ModuleSnapshot> module) {
modules_.push_back(module.release());
}
//! \brief Adds an unloaded module snapshot to be returned by
//! UnloadedModules().
//!
//! \param[in] unloaded_module The unloaded module snapshot that will be
//! included in UnloadedModules().
void AddModule(const UnloadedModuleSnapshot& unloaded_module) {
unloaded_modules_.push_back(unloaded_module);
}
//! \brief Sets the exception snapshot to be returned by Exception().
//!
//! \param[in] exception The exception snapshot that Exception() will return.
//! The TestProcessSnapshot object takes ownership of \a exception.
void SetException(std::unique_ptr<ExceptionSnapshot> exception) {
exception_ = std::move(exception);
}
//! \brief Adds a memory map region snapshot to be returned by MemoryMap().
//!
//! \param[in] region The memory map region snapshot that will be included in
//! MemoryMap(). The TestProcessSnapshot object takes ownership of \a
//! region.
void AddMemoryMapRegion(std::unique_ptr<MemoryMapRegionSnapshot> region) {
memory_map_.push_back(region.release());
}
//! \brief Adds a handle snapshot to be returned by Handles().
//!
//! \param[in] handle The handle snapshot that will be included in Handles().
void AddHandle(const HandleSnapshot& handle) {
handles_.push_back(handle);
}
//! \brief Add a memory snapshot to be returned by ExtraMemory().
//!
//! \param[in] extra_memory The memory snapshot that will be included in
//! ExtraMemory(). The TestProcessSnapshot object takes ownership of \a
//! extra_memory.
void AddExtraMemory(std::unique_ptr<MemorySnapshot> extra_memory) {
extra_memory_.push_back(extra_memory.release());
}
// ProcessSnapshot:
pid_t ProcessID() const override;
pid_t ParentProcessID() const override;
void SnapshotTime(timeval* snapshot_time) const override;
void ProcessStartTime(timeval* start_time) const override;
void ProcessCPUTimes(timeval* user_time, timeval* system_time) const override;
void ReportID(UUID* report_id) const override;
void ClientID(UUID* client_id) const override;
const std::map<std::string, std::string>& AnnotationsSimpleMap()
const override;
const SystemSnapshot* System() const override;
std::vector<const ThreadSnapshot*> Threads() const override;
std::vector<const ModuleSnapshot*> Modules() const override;
std::vector<UnloadedModuleSnapshot> UnloadedModules() const override;
const ExceptionSnapshot* Exception() const override;
std::vector<const MemoryMapRegionSnapshot*> MemoryMap() const override;
std::vector<HandleSnapshot> Handles() const override;
std::vector<const MemorySnapshot*> ExtraMemory() const override;
private:
pid_t process_id_;
pid_t parent_process_id_;
timeval snapshot_time_;
timeval process_start_time_;
timeval process_cpu_user_time_;
timeval process_cpu_system_time_;
UUID report_id_;
UUID client_id_;
std::map<std::string, std::string> annotations_simple_map_;
std::unique_ptr<SystemSnapshot> system_;
PointerVector<ThreadSnapshot> threads_;
PointerVector<ModuleSnapshot> modules_;
std::vector<UnloadedModuleSnapshot> unloaded_modules_;
std::unique_ptr<ExceptionSnapshot> exception_;
PointerVector<MemoryMapRegionSnapshot> memory_map_;
std::vector<HandleSnapshot> handles_;
PointerVector<MemorySnapshot> extra_memory_;
DISALLOW_COPY_AND_ASSIGN(TestProcessSnapshot);
};
} // namespace test
} // namespace crashpad
#endif // CRASHPAD_SNAPSHOT_TEST_TEST_PROCESS_SNAPSHOT_H_
| [
"[email protected]"
] | |
c799a74c4306ad9d12b87b02f5c3064cb702d8f3 | f2ec2c68ba7791a4db8838a24dd6d1b7f054b18f | /important/codesinC/practice/feb_farewell.cpp | 5ade9dd65e68cc23dfa53134dc63ebe4b05cca96 | [] | no_license | captain59/importantCodes | de56d241635d1129ae980cb6449407b24bb20992 | e1a80e45796fcb060d0b906f2cabc87cab73b67f | refs/heads/master | 2021-01-01T17:08:05.201104 | 2017-07-24T11:52:19 | 2017-07-24T11:52:19 | 98,005,629 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 284 | cpp | #include <stdio.h>
#include <iostream>
#include <string>
#include <algorithm>
#include <math.h>
#include <vector>
using namespace std;
int main()
{
int n,m;
scanf("%d%d",&n,&m);
int a[n];
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
sort(a,a+n);
printf("%d\n",a[n-m]);
return 0;
} | [
"[email protected]"
] | |
238a662afc5546139b3d10d7e37b8222d6631e4e | 19a8bdb4fac11ea31b8b4f642d209e0a9f075d1b | /coder/CodeB/Code/n!/x/xchian!.cpp | 6316d93d91249229cf9f5f2119aa1b150784b967 | [] | no_license | HuyKhoi-code/C- | 049727c5ba792a9e24f945522f8e2aaed7360650 | 57ea096681fc8db7470445f46c317c325900e9cb | refs/heads/master | 2023-06-02T03:11:03.793539 | 2021-06-17T07:50:22 | 2021-06-17T07:50:22 | 377,746,797 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 279 | cpp | #include <iostream>
using namespace std ;
int x,n;
int main ()
{
cin >>x;
cin >>n;
float s=0;
int t=1;
int d=1;
for (int i=1;i<=n;i++)
{
t=t*i;
d=d*x;
s=s+d/t;
}
cout <<s;
return 0;
}
| [
"[email protected]"
] | |
5ff9d4d664ee0b2dbe6e035ccf7384044816217c | 8aad555c3c3a47b66b08b353ddd7ce4b0c6c06e3 | /NvEncoder/EncoderCUDA.h | 4080099604e5cc68d874fc8a482b2a529e3f2604 | [] | no_license | TamedTornado/nvenc | 2b02f69b5964c292b952d039f4ad6327c0484ceb | 87094365c2e2a1d8abb01a579acdc414e1f2847e | refs/heads/master | 2021-07-09T01:54:15.585450 | 2017-10-07T14:14:24 | 2017-10-07T14:14:24 | 106,089,460 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,298 | h | #pragma once
#include <cuda_runtime_api.h>
#include <cuda.h>
#include <vector_types.h>
#include "nvEncodeAPI.h"
#include "encoder.h"
/**
* @brief Encoder for CUDA device memory and array input (uses current CUDA context in constructor).
*/
class EncoderCUDA : public Encoder
{
public:
EncoderCUDA();
EncoderCUDA(uint32_t width, uint32_t height, bool hevc, uint32_t bitrate);
virtual ~EncoderCUDA();
void Encode(CUdeviceptr bufferRGBA, uint32_t width, uint32_t height, bool iFrame, std::vector<uint8_t>& buffer);
void EncodeArray(CUarray arrayRGBA, uint32_t width, uint32_t height, bool iFrame, std::vector<uint8_t>& buffer);
std::shared_ptr<NV_ENC_LOCK_BITSTREAM> EncodeFrame(CUdeviceptr bufferRGBA, uint32_t width, uint32_t height, bool iFrame);
virtual void Init(NV_ENC_DEVICE_TYPE deviceType, void* device, uint32_t width, uint32_t height, bool hevc, uint32_t bitrate) override;
protected:
// void ResizeNV12Buffer(uint32_t width, uint32_t height);
private:
CUcontext m_CUDAContext;
// CUmodule m_colorConversionModule = nullptr;
// CUfunction m_RGBAToNV12Kernel = nullptr;
// CUfunction m_RGBASurfaceToNV12Kernel = nullptr;
// struct
// {
// CUdeviceptr pointer = 0;
// uint32_t pitch = 0;
// uint32_t width = 0;
// uint32_t height = 0;
// } m_bufferNV12;
}; | [
"[email protected]"
] | |
0f6a730393edd4b40eb86667e6513c5bc1e3f8ac | a939af9df16d2aca0dfb8970ed5f241db911574f | /Vertex.h | aee00991b250c01a640c715c6ba1ef4661c2cba3 | [] | no_license | multixd/Lab10 | 1fdb056d678c166103c0840271b33d878aa87e6c | 386bcebc4c8e79d67ea965d43321af06bf690123 | refs/heads/master | 2020-09-25T06:12:24.795490 | 2019-12-04T18:51:54 | 2019-12-04T18:51:54 | 225,935,480 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 373 | h | #ifndef VERTEX_H_
#define VERTEX_H_
#include <string>
#include <list>
#include <map>
#include <climits>
using namespace std;
class Vertex {
public:
list<pair<int, int> > neighbors;
string label;
int distance;
string color;
Vertex* prev;
Vertex(string label):label(label),distance(INT_MAX),color("WHITE"),prev(0){}
~Vertex(){}
};
#endif /* VERTEX_H_ */
| [
"[email protected]"
] | |
54861377296ef379c12d5e3c4137531db5669370 | 320c93e4bea7b5f44499b11564f36883a2e5eb2f | /src/RcppExports.cpp | 85f457bcd48f61731e817e1bdd47d3ec2a34b9cd | [] | no_license | krishnapsrinivasan/quanteda.textmodels | da62a8e6745190d8bbd885f41f7cc5fb39dc96df | 7430c1e8575f30b54e1504a83e710ca5c0f55f80 | refs/heads/master | 2022-11-28T18:20:26.727683 | 2020-06-16T14:40:06 | 2020-06-16T14:40:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,103 | cpp | // Generated by using Rcpp::compileAttributes() -> do not edit by hand
// Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
#include <RcppArmadillo.h>
#include <Rcpp.h>
using namespace Rcpp;
// qatd_cpp_ca
S4 qatd_cpp_ca(const arma::sp_mat& dfm, const double residual_floor);
RcppExport SEXP _quanteda_textmodels_qatd_cpp_ca(SEXP dfmSEXP, SEXP residual_floorSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< const arma::sp_mat& >::type dfm(dfmSEXP);
Rcpp::traits::input_parameter< const double >::type residual_floor(residual_floorSEXP);
rcpp_result_gen = Rcpp::wrap(qatd_cpp_ca(dfm, residual_floor));
return rcpp_result_gen;
END_RCPP
}
// qatd_cpp_tbb_enabled
bool qatd_cpp_tbb_enabled();
RcppExport SEXP _quanteda_textmodels_qatd_cpp_tbb_enabled() {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
rcpp_result_gen = Rcpp::wrap(qatd_cpp_tbb_enabled());
return rcpp_result_gen;
END_RCPP
}
// qatd_cpp_wordfish_dense
Rcpp::List qatd_cpp_wordfish_dense(SEXP wfm, SEXP dir, SEXP priors, SEXP tol, SEXP disp, SEXP dispfloor, bool abs_err);
RcppExport SEXP _quanteda_textmodels_qatd_cpp_wordfish_dense(SEXP wfmSEXP, SEXP dirSEXP, SEXP priorsSEXP, SEXP tolSEXP, SEXP dispSEXP, SEXP dispfloorSEXP, SEXP abs_errSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< SEXP >::type wfm(wfmSEXP);
Rcpp::traits::input_parameter< SEXP >::type dir(dirSEXP);
Rcpp::traits::input_parameter< SEXP >::type priors(priorsSEXP);
Rcpp::traits::input_parameter< SEXP >::type tol(tolSEXP);
Rcpp::traits::input_parameter< SEXP >::type disp(dispSEXP);
Rcpp::traits::input_parameter< SEXP >::type dispfloor(dispfloorSEXP);
Rcpp::traits::input_parameter< bool >::type abs_err(abs_errSEXP);
rcpp_result_gen = Rcpp::wrap(qatd_cpp_wordfish_dense(wfm, dir, priors, tol, disp, dispfloor, abs_err));
return rcpp_result_gen;
END_RCPP
}
// qatd_cpp_wordfish
Rcpp::List qatd_cpp_wordfish(arma::sp_mat& wfm, IntegerVector& dirvec, NumericVector& priorvec, NumericVector& tolvec, IntegerVector& disptype, NumericVector& dispmin, bool ABS, bool svd_sparse, double residual_floor);
RcppExport SEXP _quanteda_textmodels_qatd_cpp_wordfish(SEXP wfmSEXP, SEXP dirvecSEXP, SEXP priorvecSEXP, SEXP tolvecSEXP, SEXP disptypeSEXP, SEXP dispminSEXP, SEXP ABSSEXP, SEXP svd_sparseSEXP, SEXP residual_floorSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< arma::sp_mat& >::type wfm(wfmSEXP);
Rcpp::traits::input_parameter< IntegerVector& >::type dirvec(dirvecSEXP);
Rcpp::traits::input_parameter< NumericVector& >::type priorvec(priorvecSEXP);
Rcpp::traits::input_parameter< NumericVector& >::type tolvec(tolvecSEXP);
Rcpp::traits::input_parameter< IntegerVector& >::type disptype(disptypeSEXP);
Rcpp::traits::input_parameter< NumericVector& >::type dispmin(dispminSEXP);
Rcpp::traits::input_parameter< bool >::type ABS(ABSSEXP);
Rcpp::traits::input_parameter< bool >::type svd_sparse(svd_sparseSEXP);
Rcpp::traits::input_parameter< double >::type residual_floor(residual_floorSEXP);
rcpp_result_gen = Rcpp::wrap(qatd_cpp_wordfish(wfm, dirvec, priorvec, tolvec, disptype, dispmin, ABS, svd_sparse, residual_floor));
return rcpp_result_gen;
END_RCPP
}
static const R_CallMethodDef CallEntries[] = {
{"_quanteda_textmodels_qatd_cpp_ca", (DL_FUNC) &_quanteda_textmodels_qatd_cpp_ca, 2},
{"_quanteda_textmodels_qatd_cpp_tbb_enabled", (DL_FUNC) &_quanteda_textmodels_qatd_cpp_tbb_enabled, 0},
{"_quanteda_textmodels_qatd_cpp_wordfish_dense", (DL_FUNC) &_quanteda_textmodels_qatd_cpp_wordfish_dense, 7},
{"_quanteda_textmodels_qatd_cpp_wordfish", (DL_FUNC) &_quanteda_textmodels_qatd_cpp_wordfish, 9},
{NULL, NULL, 0}
};
RcppExport void R_init_quanteda_textmodels(DllInfo *dll) {
R_registerRoutines(dll, NULL, CallEntries, NULL, NULL);
R_useDynamicSymbols(dll, FALSE);
}
| [
"[email protected]"
] | |
c31650fd6cf1f9737efea3dfe24c2e2e7e59958d | f0fed75abcf38c92193362b36d1fbf3aa30f0e73 | /android/frameworks/av/media/libstagefright/include/MPEG4Extractor.h | 27dcae4d66e998f620a2b7114185f7a9efc52357 | [
"LicenseRef-scancode-unicode",
"Apache-2.0"
] | permissive | jannson/BPI-1296-Android7 | b8229d0e7fa0da6e7cafd5bfe3ba18f5ec3c7867 | d377aa6e73ed42f125603961da0f009604c0754e | refs/heads/master | 2023-04-28T08:46:02.016267 | 2020-07-27T11:47:47 | 2020-07-27T11:47:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,909 | h | /*
* Copyright (C) 2009 The Android Open Source Project
*
* 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 MPEG4_EXTRACTOR_H_
#define MPEG4_EXTRACTOR_H_
#include <arpa/inet.h>
#include <media/stagefright/DataSource.h>
#include <media/stagefright/MediaExtractor.h>
#include <media/stagefright/Utils.h>
#include <utils/List.h>
#include <utils/Vector.h>
#include <utils/String8.h>
#include "RTK/RTKAudioALAC.h"
namespace android {
struct AMessage;
class DataSource;
class SampleTable;
class String8;
struct SidxEntry {
size_t mSize;
uint32_t mDurationUs;
};
struct Trex {
uint32_t track_ID;
uint32_t default_sample_description_index;
uint32_t default_sample_duration;
uint32_t default_sample_size;
uint32_t default_sample_flags;
};
class MPEG4Extractor : public MediaExtractor {
public:
// Extractor assumes ownership of "source".
MPEG4Extractor(const sp<DataSource> &source);
virtual size_t countTracks();
virtual sp<IMediaSource> getTrack(size_t index);
virtual sp<MetaData> getTrackMetaData(size_t index, uint32_t flags);
virtual sp<MetaData> getMetaData();
virtual uint32_t flags() const;
virtual const char * name() { return "MPEG4Extractor"; }
// for DRM
virtual char* getDrmTrackInfo(size_t trackID, int *len);
#ifdef RTK_PLATFORM
uint32_t *mTWOSChunkOffsets;
uint32_t *mTWOSChunkSizes;
uint32_t mTWOSMaxPacketSize;
uint32_t mTWOSNumChunk;
uint32_t mTWOSsamplesPerChunk;
uint32_t *mSOWTChunkOffsets;
uint32_t *mSOWTChunkSizes;
uint32_t mSOWTMaxPacketSize;
uint32_t mSOWTNumChunk;
uint32_t mSOWTsamplesPerChunk;
uint32_t mCurrcts;
uint32_t audio_ver1_header_present_flag;
uint32_t audio_samples_per_packet;
uint32_t audio_bytes_per_frame;
uint32_t mWouldBlockCount;
int64_t mNextVideoOffset;
int64_t mNextAudioOffset;
ALACSpecificConfig mALACConfig;
#endif
protected:
virtual ~MPEG4Extractor();
private:
struct PsshInfo {
uint8_t uuid[16];
uint32_t datalen;
uint8_t *data;
};
struct Track {
Track *next;
sp<MetaData> meta;
uint32_t timescale;
sp<SampleTable> sampleTable;
bool includes_expensive_metadata;
bool skipTrack;
#ifdef RTK_PLATFORM
bool mIsMLAWAudio;
bool mIsTWOSAudio; // PCM, Big endian
uint32_t mIsSOWTAudio; // PCM, Little endian, 0:none, 1:sowt, 2:raw , 3:lpcm
#endif
};
Vector<SidxEntry> mSidxEntries;
off64_t mMoofOffset;
bool mMoofFound;
bool mMdatFound;
Vector<PsshInfo> mPssh;
Vector<Trex> mTrex;
sp<DataSource> mDataSource;
status_t mInitCheck;
uint32_t mHeaderTimescale;
bool mIsQT;
Track *mFirstTrack, *mLastTrack;
sp<MetaData> mFileMetaData;
Vector<uint32_t> mPath;
String8 mLastCommentMean;
String8 mLastCommentName;
String8 mLastCommentData;
KeyedVector<uint32_t, AString> mMetaKeyMap;
status_t readMetaData();
status_t parseChunk(off64_t *offset, int depth);
status_t parseITunesMetaData(off64_t offset, size_t size);
status_t parseColorInfo(off64_t offset, size_t size);
status_t parse3GPPMetaData(off64_t offset, size_t size, int depth);
void parseID3v2MetaData(off64_t offset);
status_t parseQTMetaKey(off64_t data_offset, size_t data_size);
status_t parseQTMetaVal(int32_t keyId, off64_t data_offset, size_t data_size);
status_t updateAudioTrackInfoFromESDS_MPEG4Audio(
const void *esds_data, size_t esds_size);
static status_t verifyTrack(Track *track);
struct SINF {
SINF *next;
uint16_t trackID;
uint8_t IPMPDescriptorID;
ssize_t len;
char *IPMPData;
};
SINF *mFirstSINF;
#ifdef RTK_PLATFORM
bool mMetaFoundAfterTrak;
#endif
bool mIsDrm;
status_t parseDrmSINF(off64_t *offset, off64_t data_offset);
status_t parseTrackHeader(off64_t data_offset, off64_t data_size);
status_t parseSegmentIndex(off64_t data_offset, size_t data_size);
Track *findTrackByMimePrefix(const char *mimePrefix);
MPEG4Extractor(const MPEG4Extractor &);
MPEG4Extractor &operator=(const MPEG4Extractor &);
};
bool SniffMPEG4(
const sp<DataSource> &source, String8 *mimeType, float *confidence,
sp<AMessage> *);
} // namespace android
#endif // MPEG4_EXTRACTOR_H_
| [
"[email protected]"
] | |
2900d32b8c3844f4a270e957b7e8f92f6420eaf7 | c6339883d5c3e5c3c73f20c9c3a9bf7c0101893a | /HomeWork2/Person.h | 20895af9e533fb08b83b1273d7c52146ed27cfde | [] | no_license | TexHexx/HomeWork2 | ac1811c3b6e674502ac9ef5fd50b303afb0f8107 | 05bc385fe1b714c76e00d620663d3691ce516acf | refs/heads/master | 2023-07-23T19:32:16.247579 | 2021-08-30T10:20:03 | 2021-08-30T10:20:03 | 400,783,804 | 0 | 0 | null | 2021-08-29T07:05:47 | 2021-08-28T12:11:31 | C++ | UTF-8 | C++ | false | false | 650 | h | #pragma once
#include <string>
enum class sex { man, woman };
class Person {
private:
std::string* _personName;
int _personAge;
sex _personSex;
int _personWeight;
public:
explicit Person(std::string* personName, int personAge = 0, sex personSex = sex::man, int personWeight = 0) : _personName(personName), _personAge(personAge), _personSex(personSex), _personWeight(personWeight) {};
void setName(std::string* name);
void setAge(int age);
void setWeigth(int weight);
std::string* getName() { return _personName; };
int getAge() { return _personAge; };
sex getSex() { return _personSex; };
int getWeight() { return _personWeight; };
};
| [
"[email protected]"
] | |
061a12e2a778a7a7996b41b59bc19d85c2e094ca | f90de00314d0a7fda3a9a2a9577a0e6a1469d88b | /cpp_primer/13/13_08.h | ecaa603938cc14b6c4fd577af5151739b1a5b199 | [] | no_license | 1iuyzh/exercise | fdb4c6c34c47e512c5474c4b90c7533f81c1177f | 95f0b9e91dd8fb7fd9c51566fd47eff4f033d1be | refs/heads/master | 2020-05-20T12:59:51.518359 | 2018-10-25T03:36:11 | 2018-10-25T03:36:11 | 80,420,443 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 378 | h | #include<string>
using std::string;
class HasPtr {
public:
HasPtr(const string &s = string()) : ps(new string(s)), i(0) { }
HasPtr(const HasPtr &hp) : ps(new string(*hp.ps)), i(hp.i) { }
HasPtr& operator=(const HasPtr &rhs) {
delete ps;
ps = new string(*rhs.ps);
i = rhs.i;
return *this;
}
private:
string *ps;
int i;
}; | [
"[email protected]"
] | |
b5961d8e0b53afb907b6cc02414fc858e3e3fdc4 | d387c3750d6ee7481df3b30a621a1f1f67a097f2 | /codeforces/1433/C.cpp | 931e7e133d8bca0baa94cea5e8f1dfc4fbadb985 | [] | no_license | sahilkhan03/CF-Solutions | 54b7c4858d0c810ea47768f975f4503bd83fff8b | 67e9e9581d547229b44bee271b4844423fff3a29 | refs/heads/master | 2023-04-22T01:37:43.022110 | 2021-04-19T13:34:00 | 2021-05-10T05:00:23 | 333,403,802 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,151 | cpp | #pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define fast ios_base::sync_with_stdio(false); cin.tie(nullptr);
#define all(x) x.begin(), x.end()
#define F first
#define S second
#define pb push_back
#define pl pair<ll, ll>
#define vl vector<ll>
#define vi vector<int>
#define endl '\n'
template <typename T, typename TT>
inline ostream &operator<<(ostream &os, const pair<T, TT> &t) {
return os << t.first << " " << t.second;
}
template <typename T>
inline ostream &operator<<(ostream &os, const vector<T> &t) {
for (auto i : t) os << i << " ";
return os;
}
template <typename T>
inline ostream &operator<<(ostream &os, const set<T> &t) {
for (auto i : t) os << i << " ";
return os;
}
template <typename T1, typename T2>
inline ostream &operator<<(ostream &os, const map<T1, T2> &t) {
for (auto i : t) os << i.first << " : " << i.second << endl;
return os;
}
template <typename T>
inline istream &operator>>(istream &is, vector<T> &v) {
for (T &t : v) is >> t;
return is;
}
template <typename T1, typename T2>
inline istream &operator>>(istream &is, vector<pair<T1, T2>> &v) {
for (pair<T1, T2> &t : v) is >> t.first >> t.second;
return is;
}
#ifdef LOCAL
#define debug(args...) (Debugger()), args
class Debugger {
public:
bool first;
string separator;
Debugger(const string &_separator = ", ") : first(true), separator(_separator) {}
template <typename ObjectType>
Debugger &operator, (const ObjectType &v) {
if (!first) cerr << separator;
cerr << v;
first = false;
return *this;
}
~Debugger() { cerr << endl; }
};
#else
#define debug(args...)
#endif
const ll mod = 1e9 + 7;
void solve() {
ll n; cin >> n;
vl v(n); cin >> v;
ll mx = *max_element(all(v)), mn = *min_element(all(v));
if (mx == mn) {
cout << -1 << endl;
return;
}
for (int i = 0; i < n; i++) {
if (v[i] == mx) {
if (i + 1 < n and v[i + 1] < mx) {
cout << i + 1 << endl;
return;
}
if (i - 1 >= 0 and v[i - 1] < mx) {
cout << i + 1 << endl;
return;
}
}
}
cout << -1 << endl;
}
int main()
{
fast;
ll T = 1;
cin >> T;
while (T--) {
solve();
}
return 0;
}
| [
"[email protected]"
] | |
0be7267c1db0d9e42599ab3d85f495f5c4ca5266 | 5a0ce4bb19201fea53aa676d68737e1ed4cf3f67 | /Turtles/build-turtles-Desktop_Qt_5_11_1_MinGW_32bit-Debug/debug/moc_mainwindow.cpp | 22c9734407673384696f4bbd2fa5a6e8efdb9e20 | [] | no_license | diegoramillamx/Turtles | ceff6049fc8015b2a44836f58020fcf85f57d565 | dd35f07a54e5f3e46206f2272dda0166ed51ec2d | refs/heads/master | 2020-03-30T06:42:54.880006 | 2019-09-13T23:52:32 | 2019-09-13T23:52:32 | 150,883,615 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,079 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'mainwindow.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.11.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../turtles/mainwindow.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'mainwindow.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.11.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_MainWindow_t {
QByteArrayData data[6];
char stringdata0[116];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_MainWindow_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_MainWindow_t qt_meta_stringdata_MainWindow = {
{
QT_MOC_LITERAL(0, 0, 10), // "MainWindow"
QT_MOC_LITERAL(1, 11, 20), // "on_psbEntrar_clicked"
QT_MOC_LITERAL(2, 32, 0), // ""
QT_MOC_LITERAL(3, 33, 25), // "on_psbRegistrarse_clicked"
QT_MOC_LITERAL(4, 59, 28), // "on_ledPassword_returnPressed"
QT_MOC_LITERAL(5, 88, 27) // "on_ledUsuario_returnPressed"
},
"MainWindow\0on_psbEntrar_clicked\0\0"
"on_psbRegistrarse_clicked\0"
"on_ledPassword_returnPressed\0"
"on_ledUsuario_returnPressed"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_MainWindow[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
4, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 34, 2, 0x08 /* Private */,
3, 0, 35, 2, 0x08 /* Private */,
4, 0, 36, 2, 0x08 /* Private */,
5, 0, 37, 2, 0x08 /* Private */,
// slots: parameters
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
0 // eod
};
void MainWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
MainWindow *_t = static_cast<MainWindow *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->on_psbEntrar_clicked(); break;
case 1: _t->on_psbRegistrarse_clicked(); break;
case 2: _t->on_ledPassword_returnPressed(); break;
case 3: _t->on_ledUsuario_returnPressed(); break;
default: ;
}
}
Q_UNUSED(_a);
}
QT_INIT_METAOBJECT const QMetaObject MainWindow::staticMetaObject = {
{ &QMainWindow::staticMetaObject, qt_meta_stringdata_MainWindow.data,
qt_meta_data_MainWindow, qt_static_metacall, nullptr, nullptr}
};
const QMetaObject *MainWindow::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *MainWindow::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_MainWindow.stringdata0))
return static_cast<void*>(this);
return QMainWindow::qt_metacast(_clname);
}
int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QMainWindow::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 4)
qt_static_metacall(this, _c, _id, _a);
_id -= 4;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 4)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 4;
}
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| [
"[email protected]"
] | |
cdeaa1c56b081c3f0bd35ab1ce68db545561c78e | a3917f60c106698a5cd245a73ff2c5bb767e3e13 | /src/layer/rnn.h | 0372dc9a283a7c9842c24916954278f8b7e2f6d7 | [
"BSD-3-Clause",
"Zlib",
"BSD-2-Clause"
] | permissive | sunbinbin1991/ncnn-bin | 85e7a43258c488b9b6cbf8a83c9875fd7e7889e9 | fc74404af642bc4729532fd39f8e9446eb7b0dcd | refs/heads/master | 2021-05-05T11:13:10.553624 | 2018-03-07T08:03:08 | 2018-03-07T08:03:08 | 118,119,521 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,433 | h | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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 LAYER_RNN_H
#define LAYER_RNN_H
#include "layer.h"
namespace ncnn {
class RNN : public Layer
{
public:
RNN();
virtual ~RNN();
virtual int load_param(const ParamDict& pd);
#if NCNN_STDIO
virtual int load_model(FILE* binfp);
#endif // NCNN_STDIO
virtual int load_model(const unsigned char*& mem);
virtual int forward(const std::vector<Mat>& bottom_blobs, std::vector<Mat>& top_blobs) const;
public:
// param
int num_output;
int weight_data_size;
// model
Mat weight_hh_data;
Mat weight_xh_data;
Mat weight_ho_data;
Mat bias_h_data;
Mat bias_o_data;
};
} // namespace ncnn
#endif // LAYER_RNN_H
| [
"[email protected]"
] | |
db30f1248dc5e25abc2b53e85284890694b60e21 | 9fc9581e07ea2cf1b2a8588f230cff93c02743a5 | /probleme/vectori/cautare_binara/2443.cpp | 3224d55a20d74609f1a0ef4b80f6b370f829ac24 | [] | no_license | UncleKhab/cpp-probleme | 4b47a9a8dc4939c05d916865842df29e2538956c | 9960cb67361b39b94625c228d609d5fdc9fc40c5 | refs/heads/main | 2023-05-08T03:34:35.803000 | 2021-05-26T12:18:55 | 2021-05-26T12:18:55 | 330,030,311 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 781 | cpp | #include <bits/stdc++.h>
using namespace std;
int a[100001],b[100001];
int n,m,x,s;
int cautare_binara(int x)
{
int st = 1, dr = n;
int mij;
while(st <= dr)
{
mij = (st+dr)/2;
if(b[mij] == x)
{
return mij;
}
if(b[mij] > x)
{
dr = mij - 1;
}
else
{
st = mij + 1;
}
}
return dr;
}
int main()
{
cin >> n;
b[0] = 0;
for(int i = 1; i <= n;i++)
{
cin >> a[i];
b[i] = b[i-1] + a[i];
}
cin >> m;
for(int i = 0; i < m;i++)
{
cin >> x >> s;
int p = cautare_binara(s);
while(a[p] > x && p>=0)
{
p--;
}
cout << p << '\n';
}
}
| [
"[email protected]"
] | |
8e98e3a49c2f58a5d8611090feeb0b0cc9eb1125 | 050ebbbc7d5f89d340fd9f2aa534eac42d9babb7 | /grupa2/irebas/p1/pro.cpp | a2b89f9f39c891f1539c3a180c0bae82491c9105 | [] | no_license | anagorko/zpk2015 | 83461a25831fa4358366ec15ab915a0d9b6acdf5 | 0553ec55d2617f7bea588d650b94828b5f434915 | refs/heads/master | 2020-04-05T23:47:55.299547 | 2016-09-14T11:01:46 | 2016-09-14T11:01:46 | 52,429,626 | 0 | 13 | null | 2016-03-22T09:35:25 | 2016-02-24T09:19:07 | C++ | UTF-8 | C++ | false | false | 198 | cpp | #include <iostream>
using namespace std;
int main() {
unsigned int a,b,c;
cin >> a >> b >> c;
cout << "Objętosc: " << a*b*c << endl;
cout << "Pole: " << 2*(a*b)+2*(a*c)+2*(b*c) << endl;
}
| [
"[email protected]"
] | |
6a1eb9fb564d93169389105e52f5bda5dc9eb3a5 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5658571765186560_0/C++/BananaTree/D.cpp | 4f018b6481e1213d1dffb9797dd50ec9136d3163 | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,285 | cpp | #include <bits/stdc++.h>
#define FOR(i, n) for (int i = 0; i < n; ++i)
using namespace std;
const string ALLOK = "GABRIEL";
const string NOTOK = "RICHARD";
int main() {
int T, area, row, col;
cin >> T;
FOR(tt, T) {
cout << "Case #" << tt + 1 << ": ";
cin >> area >> row >> col;
if (row < col) swap(row, col);
if ((row * col) % area) {
cout << NOTOK << endl;
continue;
}
if (area <= 2) cout << ALLOK << endl;
if (area == 3) {
assert(col != 4);
if (col == 1) cout << NOTOK << endl;
if (col == 2) {
assert(row == 3);
cout << ALLOK << endl;
}
if (col == 3) {
if (row == 3) cout << NOTOK << endl;
if (row == 4) cout << ALLOK << endl;
}
}
if (area == 4) {
if (row < 4 || col == 1) cout << NOTOK << endl;
else {
assert(row == 4 && col > 1);
if (col == 2) cout << ALLOK << endl;
if (col == 3) cout << NOTOK << endl;
if (col == 4) cout << ALLOK << endl;
}
}
}
return 0;
}
| [
"[email protected]"
] | |
56f95b8e85ca1994a7cbe1677aecffc4f5cc2ff9 | d27c4ca7fd96a62363e555677d9d41e0b649f704 | /saber/funcs/impl/cuda/saber_box_coder.h | 049397a35239cd28272291d18901871e1a3f4660 | [
"Apache-2.0"
] | permissive | imharrywu/Anakin-1 | 26e69bb2ec38d66d279cb3b1003501cbf0f8b729 | ffabcf1bd4b19cc6c682ba8a9e68b8ef976d9da7 | refs/heads/master | 2020-09-21T12:53:29.055278 | 2019-11-29T09:37:52 | 2019-11-29T09:37:52 | 224,795,082 | 0 | 0 | Apache-2.0 | 2019-11-29T06:56:16 | 2019-11-29T06:56:16 | null | UTF-8 | C++ | false | false | 1,994 | h | /* Copyright (c) 2019 Anakin Authors, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef ANAKIN_SABER_FUNCS_IMPL_CUDA_SABER_BOX_CODER_H
#define ANAKIN_SABER_FUNCS_IMPL_CUDA_SABER_BOX_CODER_H
#include "anakin_config.h"
#include "saber/funcs/impl/impl_box_coder.h"
#include "saber/core/tensor.h"
namespace anakin {
namespace saber {
template <DataType OpDtype>
class SaberBoxCoder<NV, OpDtype> : \
public ImplBase <
NV,
OpDtype,
BoxCoderParam<NV> > {
public:
typedef typename DataTrait<NV, OpDtype>::Dtype OpDataType;
SaberBoxCoder() = default;
~SaberBoxCoder() {}
virtual SaberStatus init(const std::vector<Tensor<NV>*>& inputs,
std::vector<Tensor<NV>*>& outputs,
BoxCoderParam<NV>& param, Context<NV>& ctx) {
//get context
this->_ctx = &ctx;
return create(inputs, outputs, param, ctx);
}
virtual SaberStatus create(const std::vector<Tensor<NV>*>& inputs,
std::vector<Tensor<NV>*>& outputs,
BoxCoderParam<NV>& param, Context<NV>& ctx) {
return SaberSuccess;
}
virtual SaberStatus dispatch(const std::vector<Tensor<NV>*>& inputs,
std::vector<Tensor<NV>*>& outputs,
BoxCoderParam<NV>& param)override;
private:
};
} //namespace saber
} //namespace anakin
#endif //ANAKIN_SABER_BOX_CODER_H
| [
"[email protected]"
] | |
fd371ea4f645e3ead78231a4dc7dfdad781b8bc4 | 7041d863026248d007963cb0fcdd6c505f6eb0d1 | /process2/myecho.cc | c54b2e0c998bf43f709e3f4296c7bdec97fbf06e | [] | no_license | Firebird1029/cs61-lectures | 8d64a4fd1490e38b651c3cb061e95acac54ef4b0 | 59923921a5243af491c204f0ed8bfaaa3b9790d4 | refs/heads/main | 2023-01-19T00:54:00.615636 | 2020-12-03T14:22:04 | 2020-12-03T14:22:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 235 | cc | #include "helpers.hh"
int main(int argc, char* argv[]) {
fprintf(stderr, "Myecho running in pid %d\n", getpid());
for (int i = 0; i != argc; ++i) {
fprintf(stderr, "Arg %d @%p: \"%s\"\n", i, argv[i], argv[i]);
}
}
| [
"[email protected]"
] | |
cdc9f81d395a3f9c39fe0538516f3aa0d8337025 | 32ede53a77c76deb095cf4609f3a301550a2bf35 | /PickStructure.h | 34a5981c7ccc596c8fae665d9df52a67f2a30534 | [] | no_license | justtookoff/FlyingDuckChart | 9492fa2e1083139102f592ea887c78fa074370a7 | 8b551285e97b14cb6c959473c89ab6c2ab82ff50 | refs/heads/master | 2021-07-03T03:25:18.942558 | 2017-09-23T09:13:15 | 2017-09-23T09:13:15 | 104,552,351 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 666 | h | //PickStructure.h
#ifndef _PICKSTRUCTURE_H
#define _PICKSTRUCTURE_H
#include "MouseLButtonAction.h"
class Structure;
class SelectedStructure;
class GroupSelectedStructure;
class Group;
class PickStructure : public MouseLButtonAction {
public :
PickStructure();
PickStructure(const PickStructure& source);
~PickStructure();
PickStructure& operator=(const PickStructure& source);
virtual void Pick(NSChart *nsChart, SelectedStructure *selectedStructure, Structure* *pickStructure);
virtual void PickGroup(NSChart *nsChart, GroupSelectedStructure *groupSelectedStructure, Group * *pickGroupStructure);
};
#endif // !_PICKSTRUCTURE_H
| [
"[email protected]"
] | |
c69ce11beb35702e7ddd3b36ae78d2a9e1d7f909 | 10f3c3497a8e005382f839205220261c2ec6053d | /main.cpp | a53cd8708635ea5780cd8305c3a2ee3d912eadbd | [] | no_license | WorkhorsyTest/cpp_sdl2_opengl | d0060295a301abf4ed1a2ff294a09e40630a35b3 | e679e930a11322b97c6f9e8e990f0352eef2c7f2 | refs/heads/master | 2021-07-08T11:27:59.213730 | 2017-10-01T16:27:35 | 2017-10-01T16:27:35 | 74,003,387 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,924 | cpp |
#include <stdbool.h>
#include <string>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <GL/glew.h>
#include <SDL/SDL.h>
#include <SDL/SDL_image.h>
#include "SDL_opengl.h"
#ifdef EMSCRIPTEN
#include <emscripten.h>
#include <math.h>
void gluPerspective(GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar) {
GLdouble xmin, xmax, ymin, ymax;
ymax = zNear * tan(fovy * M_PI / 360.0);
ymin = -ymax;
xmin = ymin * aspect;
xmax = ymax * aspect;
glFrustum(xmin, xmax, ymin, ymax, zNear, zFar);
}
#endif
using namespace std;
float width = 200, height = 200;
float bpp = 0;
float near = 10.0, far = 100000.0, fovy = 45.0;
float position[3] = {0,0,-40};
const float triangle[9] = {
0, 10, 0, // top point
-10, -10, 0, // bottom left
10, -10, 0 // bottom right
};
float rotate_degrees = 90;
float rotate_axis[3] = {0,1,0};
SDL_Surface* screen = nullptr;
bool IsSurfaceRGBA8888(const SDL_Surface* surface) {
return (surface->format->Rmask == 0xFF000000 &&
surface->format->Gmask == 0x00FF0000 &&
surface->format->Bmask == 0x0000FF00 &&
surface->format->Amask == 0x000000FF);
}
/*
SDL_Surface* EnsureSurfaceRGBA8888(SDL_Surface* surface) {
// Just return if it is already RGBA8888
if (IsSurfaceRGBA8888(surface)) {
return surface;
}
// Convert the surface into a new one that is RGBA8888
//std::cout << "Converting surface to RGBA8888 format." << std::endl;
SDL_Surface* new_surface = SDL_ConvertSurfaceFormat(surface, SDL_PIXELFORMAT_RGBA8888, 0);
if (new_surface == nullptr) {
stringstream ss;
ss << "Failed to convert surface to RGBA8888 format" <<
" at " << __FILE__ << ":" << __LINE__;
throw std::runtime_error(ss.str());
}
SDL_FreeSurface(surface);
// Make sure the new surface is RGBA8888
if (! IsSurfaceRGBA8888(new_surface)) {
stringstream ss;
ss << "Failed to convert surface to RGBA8888 format" <<
" at " << __FILE__ << ":" << __LINE__;
throw std::runtime_error(ss.str());
}
return new_surface;
}
*/
SDL_Surface* LoadSurface(std::string file_name) {
SDL_Surface* surface = IMG_Load(file_name.c_str());
if (surface == nullptr) {
stringstream ss;
ss << "Failed to load surface \"" << file_name << "\"" <<
" at " << __FILE__ << ":" << __LINE__;
throw std::runtime_error(ss.str());
}
//surface = EnsureSurfaceRGBA8888(surface);
return surface;
}
void render() {
SDL_Event event;
while ( SDL_PollEvent( &event ) ) {
#ifdef EMSCRIPTEN
if ( event.type == SDL_KEYDOWN || event.type == SDL_KEYUP ) {
emscripten_cancel_main_loop();
SDL_Quit();
} else if (event.type == SDL_QUIT) {
emscripten_cancel_main_loop();
SDL_Quit();
}
#endif
}
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
glTranslatef(position[0], position[1], position[2]);
{
static Uint32 last = 0;
static float angle = 0;
Uint32 now = SDL_GetTicks();
float delta = (now - last) / 1000.0f; // in seconds
last = now;
angle += rotate_degrees * delta;
// c modulo operator only supports ints as arguments
#define MOD( n, d ) (n - (d * (int) ( n / d )))
angle = MOD( angle, 360 );
glRotatef( angle, rotate_axis[0], rotate_axis[1], rotate_axis[2] );
}
glBegin(GL_TRIANGLES);
for (int i=0; i<=6; i+=3) {
glColor3f(i==0, i==3, i==6); // adding some color
glVertex3fv(&triangle[i]);
}
glEnd();
SDL_GL_SwapBuffers();
}
int main() {
// Initialize SDL
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
fprintf(stderr, "Could not initialize SDL: %s\n", SDL_GetError());
return 1;
}
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1 );
screen = SDL_SetVideoMode(
width, height, bpp,
SDL_ANYFORMAT | SDL_OPENGL );
glViewport(0, 0, width, height);
glPolygonMode( GL_FRONT, GL_FILL );
glPolygonMode( GL_BACK, GL_LINE );
glMatrixMode(GL_PROJECTION);
gluPerspective(fovy,width/height,near,far);
glMatrixMode(GL_MODELVIEW);
// ===================
// Texture 2
// ===================
GLuint texture2;
glGenTextures(1, &texture2);
glBindTexture(GL_TEXTURE_2D, texture2);
// Set our texture parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// Set texture filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// Load, create texture and generate mipmaps
SDL_Surface* surface = nullptr;
try {
//LoadSurface("awesomeface.png");
} catch (const std::runtime_error &err) {
//std::exception_ptr err = std::current_exception();
cout << "!!!" << err.what() << endl;
return 1;
}
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, surface->w, surface->h, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, surface->pixels);
glGenerateMipmap(GL_TEXTURE_2D);
SDL_FreeSurface(surface);
glBindTexture(GL_TEXTURE_2D, 0);
#ifdef EMSCRIPTEN
emscripten_set_main_loop(render, 0, true);
#else
while (true) {
render();
}
#endif
return 0;
}
| [
"[email protected]"
] | |
4a0a5a0d9ee2da46b6fa85b97cf3fe234893e53c | a3ae02601fac3a51f6ed2eca50322cd50f9711e2 | /source/sziFancyLogger.h | 48663bc211d55cf54187644d9eb12760e8752392 | [] | no_license | bbsun/AutomaticTuningOfSysParams | e66ca7881de7373aac12126c8592eb9eb899cd49 | 6593b706f3600cf83375fb05d9d641e01821b6ad | refs/heads/master | 2021-05-27T04:52:42.192043 | 2013-05-25T21:22:17 | 2013-05-25T21:22:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,471 | h | #ifndef _sziFancyLogger_h_
#define _sziFancyLogger_h_
#include <itkLogger.h>
#include <itkStdStreamLogOutput.h>
#include <fstream>
#include <itkFancyString.h>
namespace szi
{
/**
A logger implementation that always logs incoming messages to a file.
It also includes some minor revisions to the original implementation for easier use.
*/
class FancyLogger : public itk::Logger
{
public:
/** Standard class typedefs. */
typedef FancyLogger Self;
typedef itk::Logger Superclass;
typedef itk::SmartPointer< Self > Pointer;
typedef itk::SmartPointer< const Self > ConstPointer;
/** Method for object creation without using the object factory. */
itkFactorylessNewMacro( Self );
/** Run-time type information (and related methods). */
itkTypeMacro( szi::FancyLogger, Logger );
void AddOutput( std::ostream& os )
{
itk::StdStreamLogOutput::Pointer output = itk::StdStreamLogOutput::New();
output->SetStream( os );
this->AddLogOutput( (itk::StdStreamLogOutput*)output );
}
void StartLogging( const char * name )
{
this->EndLogging();
std::string fn( name );
fn.append( ".log" );
this->m_FileStream.open( fn.c_str() );
if ( !this->m_FileStream.is_open() )
{
this->Warning( "Not able to create the log file!" );
}
}
void EndLogging()
{
if ( this->m_FileStream.is_open() )
{
this->m_FileStream.close();
}
}
virtual void Write( PriorityLevelType level, std::string const & content )
{
std::string message( content + "\n" );
Superclass::Write( level, message );
if ( level == FATAL )
{
this->EndLogging();
throw "Fatal error was encountered!";
}
}
void StartLine( PriorityLevelType level )
{
if ( this->m_LineText.size() )
{
this->EndLine();
}
this->m_LinePriority = level;
}
void EndLine()
{
this->Write( this->m_LinePriority, this->m_LineText );
this->m_LineText.clear();
}
virtual ~FancyLogger()
{
this->EndLogging();
}
/*
template < typename T >
FancyLogger& operator<<( T const & data ) { this->m_LineText << data; return (*this); }
/*/
FancyLogger& operator<<( char const & data ) { this->m_LineText << data; return (*this); }
FancyLogger& operator<<( unsigned char const & data ) { this->m_LineText << data; return (*this); }
FancyLogger& operator<<( short const & data ) { this->m_LineText << data; return (*this); }
FancyLogger& operator<<( unsigned short const & data ) { this->m_LineText << data; return (*this); }
FancyLogger& operator<<( int const & data ) { this->m_LineText << data; return (*this); }
FancyLogger& operator<<( unsigned int const & data ) { this->m_LineText << data; return (*this); }
FancyLogger& operator<<( long const & data ) { this->m_LineText << data; return (*this); }
FancyLogger& operator<<( unsigned long const & data ) { this->m_LineText << data; return (*this); }
FancyLogger& operator<<( float const & data ) { this->m_LineText << data; return (*this); }
FancyLogger& operator<<( double const & data ) { this->m_LineText << data; return (*this); }
FancyLogger& operator<<( std::string const & data ) { this->m_LineText << data; return (*this); }
FancyLogger& operator<<( char const * data ) { this->m_LineText << data; return (*this); }
template < typename T > FancyLogger& operator<<( std::vector<T> const & data ) { this->m_LineText << data; return (*this); }
template < typename T > FancyLogger& operator<<( itk::Array<T> const & data ) { this->m_LineText << data; return (*this); }
//*/
FancyLogger& operator<<( void (*mf)(FancyLogger&) )
{
(*mf)(*this);
return (*this);
}
class Manipulator
{
public:
typedef FancyLogger ObjectType;
typedef std::string ArgumentType;
Manipulator( const ArgumentType& a ) : m_Argument( a ) {}
virtual void mf( ObjectType&, const ArgumentType& ) const = 0;
ArgumentType m_Argument;
};
//
FancyLogger& operator<<( const Manipulator& manip )
{
manip.mf( (*this), manip.m_Argument );
return (*this);
}
protected:
FancyLogger() : m_LinePriority( NOTSET )
{
this->SetPriorityLevel( NOTSET );
this->SetLevelForFlushing( INFO );
this->SetTimeStampFormat( HUMANREADABLE );
this->SetHumanReadableFormat( "%Y-%b-%d %H:%M:%S" );
this->SetName( this->GetNameOfClass() );
// add the default file output
this->AddOutput( this->m_FileStream );
}
private:
FancyLogger( const Self & ); // purposely not implemented
FancyLogger& operator=( const Self & ); // purposely not implemented
std::ofstream m_FileStream;
PriorityLevelType m_LinePriority;
itk::FancyString m_LineText;
};
// some manipulators for FancyLogger
class StartFatal : public FancyLogger::Manipulator
{
public:
typedef FancyLogger::Manipulator SuperClass;
StartFatal( const ArgumentType& a = "" ) : SuperClass( a ) {}
virtual void mf( ObjectType& logger, const ArgumentType& name ) const
{
if ( name.size() )
{
logger.SetName( name.c_str() );
}
logger.StartLine( FancyLogger::FATAL );
}
};
class StartCritical : public FancyLogger::Manipulator
{
public:
typedef FancyLogger::Manipulator SuperClass;
StartCritical( const ArgumentType& a = "" ) : SuperClass( a ) {}
virtual void mf( ObjectType& logger, const ArgumentType& name ) const
{
if ( name.size() )
{
logger.SetName( name.c_str() );
}
logger.StartLine( FancyLogger::CRITICAL );
}
};
class StartWarning : public FancyLogger::Manipulator
{
public:
typedef FancyLogger::Manipulator SuperClass;
StartWarning( const ArgumentType& a = "" ) : SuperClass( a ) {}
virtual void mf( ObjectType& logger, const ArgumentType& name ) const
{
if ( name.size() )
{
logger.SetName( name.c_str() );
}
logger.StartLine( FancyLogger::WARNING );
}
};
class StartInfo : public FancyLogger::Manipulator
{
public:
typedef FancyLogger::Manipulator SuperClass;
StartInfo( const ArgumentType& a = "" ) : SuperClass( a ) {}
virtual void mf( ObjectType& logger, const ArgumentType& name ) const
{
if ( name.size() )
{
logger.SetName( name.c_str() );
}
logger.StartLine( FancyLogger::INFO );
}
};
class StartDebug : public FancyLogger::Manipulator
{
public:
typedef FancyLogger::Manipulator SuperClass;
StartDebug( const ArgumentType& a = "" ) : SuperClass( a ) {}
virtual void mf( ObjectType& logger, const ArgumentType& name ) const
{
if ( name.size() )
{
logger.SetName( name.c_str() );
}
logger.StartLine( FancyLogger::DEBUG );
}
};
inline void Fatal( FancyLogger& logger )
{
logger.StartLine( FancyLogger::FATAL );
}
inline void Critical( FancyLogger& logger )
{
logger.StartLine( FancyLogger::CRITICAL );
}
inline void Warning( FancyLogger& logger )
{
logger.StartLine( FancyLogger::WARNING );
}
inline void Info( FancyLogger& logger )
{
logger.StartLine( FancyLogger::INFO );
}
inline void Debug( FancyLogger& logger )
{
logger.StartLine( FancyLogger::DEBUG );
}
inline void End( FancyLogger& logger )
{
logger.EndLine();
}
} // namespace szi
#endif // _sziFancyLogger_h_
| [
"[email protected]"
] | |
e0312d07630033447e7bedfed01ef128ef7f1563 | 0d3e7bb4c93eef383bff1f0ff6e7e46296634364 | /versions/v10/Instance.cpp | 0f5d8f8880dfcba83fb1d7c62eebf6bbaa34c583 | [] | no_license | mlomb/halite2-bot | ff7982067a15392379f279754d87f1116c66e796 | 3b1ed0fbce4c16268590ebedec4db2c7ed773630 | refs/heads/master | 2021-05-10T15:53:16.422027 | 2019-01-29T17:16:50 | 2019-01-29T17:16:50 | 118,563,037 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 18,908 | cpp | #include "Instance.hpp"
#include "hlt/constants.hpp"
#include "Input.hpp"
#include "Log.hpp"
#include "Navigation.hpp"
#include "Image.hpp"
#include <queue>
#include <chrono>
#include <string.h>
#include <algorithm>
Instance* Instance::s_Instance = nullptr;
Instance::Instance()
{
s_Instance = this;
}
void Instance::Initialize(const std::string& bot_name)
{
std::cout.sync_with_stdio(false);
in::GetSString() >> player_id;
in::GetSString() >> map_width >> map_height;
Log::Get()->Open(std::to_string(player_id) + "_" + bot_name + ".log");
Log::log() << "-- " << bot_name << " --" << std::endl;
Log::log() << "Our player id: " << player_id << std::endl;
Log::log() << "Map size: " << map_width << "x" << map_height << std::endl;
turn = 0;
NextTurn();
Log::log() << "Players: " << num_players << std::endl
<< "Planets: " << planets.size() << std::endl;
std::cout << bot_name << std::endl;
}
void Instance::Play()
{
rush_phase = num_players == 2;
game_over = false;
while (true) {
NextTurn();
auto start = std::chrono::high_resolution_clock::now();
std::vector<Move> moves = Frame();
auto finish = std::chrono::high_resolution_clock::now();
auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(finish - start);
Log::log("Turn took: " + std::to_string(millis.count()) + "ms");
// generate moves string
std::ostringstream oss;
for (const Move& move : moves) {
switch (move.type) {
case MoveType::Noop:
continue;
case MoveType::Undock:
oss << "u " << move.ship_id << " ";
break;
case MoveType::Dock:
oss << "d " << move.ship_id << " "
<< move.dock_to << " ";
break;
case MoveType::Thrust:
oss << "t " << move.ship_id << " "
<< move.move_thrust << " "
<< move.move_angle_deg << " ";
break;
}
}
std::cout << oss.str() << std::endl;
if (!std::cout.good()) {
Log::log("Error sending movements, aborting");
std::exit(0);
}
}
}
void Instance::NextTurn()
{
const std::string input = in::GetString();
if (!std::cin.good()) {
// This is needed on Windows to detect that game engine is done.
std::exit(0);
}
if (turn == 0)
Log::log("--- PRE-GAME ---");
else
Log::log() << "--- TURN " << turn << " ---" << std::endl;
// process the map
ParseMap(input);
++turn;
}
void Instance::ParseMap(const std::string& input) {
std::stringstream iss(input);
iss >> num_players;
EntityId entity_id;
// mark all the entities as dead
for (auto& kv : ships) { kv.second->alive = false; kv.second->task_id = -1; kv.second->task_priority = 0; kv.second->frozen = true; }
for (auto& kv : planets) { kv.second->alive = false; }
shipsCount.clear();
for (int i = 0; i < num_players; ++i) {
PlayerId player_id;
unsigned int num_ships;
iss >> player_id >> num_ships;
shipsCount.insert(std::make_pair(player_id, num_ships));
for (int j = 0; j < num_ships; j++) {
iss >> entity_id;
Ship* ship = GetShip(entity_id);
if (ship == nullptr) {
ship = new Ship(entity_id);
ships.insert(std::make_pair(entity_id, ship));
}
ship->alive = true;
iss >> ship->location.x;
iss >> ship->location.y;
iss >> ship->health;
double vel_x_deprecated, vel_y_deprecated;
iss >> vel_x_deprecated >> vel_y_deprecated;
int docking_status;
iss >> docking_status;
ship->docking_status = static_cast<ShipDockingStatus>(docking_status);
iss >> ship->docked_planet;
iss >> ship->docking_progress;
iss >> ship->weapon_cooldown;
ship->owner_id = player_id;
ship->radius = hlt::constants::SHIP_RADIUS;
}
}
unsigned int num_planets;
iss >> num_planets;
for (unsigned int i = 0; i < num_planets; ++i) {
iss >> entity_id;
Planet* planet = GetPlanet(entity_id);
if (planet == nullptr) {
planet = new Planet(entity_id);
planets.insert(std::make_pair(entity_id, planet));
}
planet->alive = true;
iss >> planet->location.x;
iss >> planet->location.y;
iss >> planet->health;
iss >> planet->radius;
iss >> planet->docking_spots;
iss >> planet->current_production;
iss >> planet->remaining_production;
int owned;
iss >> owned;
iss >> planet->owner_id;
if (owned != 1)
planet->owner_id = -1;
unsigned int num_docked_ships;
iss >> num_docked_ships;
planet->docked_ships.reserve(num_docked_ships);
for (unsigned int i = 0; i < num_docked_ships; ++i) {
iss >> entity_id;
planet->docked_ships.push_back(GetShip(entity_id));
}
}
Log::log() << "Map parsed -- ships: " << ships.size() << " planets: " << planets.size() << std::endl;
}
Instance* Instance::Get()
{
return s_Instance;
}
Ship* Instance::GetShip(EntityId shipId) {
auto it = ships.find(shipId);
if (it != ships.end())
return (*it).second;
return nullptr;
}
Planet* Instance::GetPlanet(EntityId planetId) {
auto it = planets.find(planetId);
if (it != planets.end())
return (*it).second;
return nullptr;
}
Task* Instance::CreateTask(TaskType type)
{
Task* task = new Task(current_task++);
task->type = type;
tasks.push_back(task);
return task;
}
Task* Instance::GetTask(unsigned int task_id)
{
return tasks.at(task_id);
}
void Instance::UpdateMap()
{
// clear the map
memset(&map[0][0], 0, MAP_HEIGHT * MAP_WIDTH * sizeof(MapCell));
for (int i = 0; i < MAP_HEIGHT * MAP_WIDTH; i++) {
int y = (i / MAP_WIDTH);
int x = (i % MAP_WIDTH);
if (x < 0 || y < 0 || x >= MAP_WIDTH || y >= MAP_HEIGHT)
continue;
MapCell& cell = map[y][x];
cell.location = { (double)x / MAP_DEFINITION, (double)y / MAP_DEFINITION };
cell.astar_F = INF;
cell.astar_G = INF;
}
// mark the planets as solids
for (auto&kv : planets) {
Planet* planet = kv.second;
if (!planet->alive) continue;
IterateMap(planet->location, planet->radius + hlt::constants::SHIP_RADIUS, [&](Vector2 position, MapCell& cell, double distance) {
cell.solid = true;
});
}
// mark ships
for (auto&kv : ships) {
Ship* ship = kv.second;
if (!ship->alive) continue;
double radius;
if (ship->IsOur()) {
if (!ship->IsCommandable()) continue; // we can't control this ship
radius = ship->radius * 2 + hlt::constants::MAX_SPEED;
}
else {
if (ship->IsCommandable())
radius = ship->radius * 2 + hlt::constants::MAX_SPEED + hlt::constants::WEAPON_RADIUS + 1;
else
radius = ship->radius * 2 + hlt::constants::WEAPON_RADIUS;
}
IterateMap(ship->location, radius, [&](Vector2 position, MapCell& cell, double distance) {
if (distance < ship->radius)
cell.ship = true;
if (ship->IsOur())
cell.friendlyShipsThatCanReachThere++;
else {
cell.nextTurnEnemyShipsTakingDamage++;
if (ship->IsCommandable())
cell.nextTurnEnemyShipsAttackInRange++;
}
});
}
/*
Image::WriteImage(std::string("turns/turn_") + std::to_string(turn) + "_map.bmp", MAP_WIDTH, MAP_HEIGHT, [&](int x, int y) -> std::tuple<unsigned char, unsigned char, unsigned char> {
y = MAP_HEIGHT - y - 1;
if (map[y][x].ship)
return std::make_tuple(0, 0, 255);
if (map[y][x].solid)
return std::make_tuple(0, 0, 0);
int d1 = 200 - map[y][x].nextTurnEnemyShipsAttackInRange * 15;
auto enemyColor = std::make_tuple(255, d1, d1);
int d2 = 200 - map[y][x].friendlyShipsThatCanReachThere * 15;
auto friendColor = std::make_tuple(d2, 255, d2);
if (d1 == 200 && d2 == 200)
return std::make_tuple(255, 255, 255);
else if (d1 != 200 && d2 == 200)
return enemyColor;
else if (d1 == 200 && d2 != 200)
return friendColor;
else
return Image::Interpolate(enemyColor, friendColor);
});
*/
}
MapCell& Instance::GetCell(const Vector2& location)
{
int x = location.x * MAP_DEFINITION;
int y = location.y * MAP_DEFINITION;
if (x < 0 || y < 0 || x >= MAP_WIDTH || y >= MAP_HEIGHT)
return map[0][0]; // strange
return map[y][x];
}
void Instance::IterateMap(Vector2 location, double radius, std::function<void(Vector2, MapCell&, double)> action) {
if (!action) return;
Vector2 startPoint = location - radius;
Vector2 endPoint = location + radius;
const double borderSeparation = 1;
startPoint.x = std::fmin(std::fmax(startPoint.x, borderSeparation), map_width - borderSeparation);
startPoint.y = std::fmin(std::fmax(startPoint.y, borderSeparation), map_height - borderSeparation);
endPoint.x = std::fmin(std::fmax(endPoint.x, borderSeparation), map_width - borderSeparation);
endPoint.y = std::fmin(std::fmax(endPoint.y, borderSeparation), map_height - borderSeparation);
const double step = 1.0 / MAP_DEFINITION;
for (double ix = startPoint.x; ix < endPoint.x; ix += step) {
for (double iy = startPoint.y; iy < endPoint.y; iy += step) {
Vector2 position = { (double)ix, (double)iy };
double d = location.DistanceTo(position);
if (d < radius) {
action(position, GetCell(position), d);
}
}
}
}
std::vector<Move> Instance::Frame()
{
shipTrajectories.clear();
if (num_players == 4) {
rush_phase = false;
// check for a game over
if (!game_over) {
// we are not in game over yet
int myShips = shipsCount.at(player_id);
int players = 1;
int maxEnemyShipsFromOnePlayer = 0;
for (auto& kv : shipsCount) {
if (kv.first == player_id) continue;
if (kv.second > 0) {
int planets_owned = 0;
for (auto& kv : planets) {
if (kv.second->owner_id == kv.first)
planets_owned++;
}
if (planets_owned > 0) {
players++;
maxEnemyShipsFromOnePlayer = std::max(maxEnemyShipsFromOnePlayer, kv.second);
}
}
}
if (players >= 4) { // we only give up if we need to fight the 3rd place
if (maxEnemyShipsFromOnePlayer > myShips + (maxEnemyShipsFromOnePlayer * 0.5 /* 50% of the ships */))
game_over = true;
}
}
}
else { // num_player == 2
if (rush_phase) { // we check if the rush phase should end
Log::log("We're in rush phase!");
bool threatsFound = false;
for (auto& kv : ships) {
if (!kv.second->alive) continue;
if (kv.second->owner_id == player_id) continue;
if (kv.second->docking_status == ShipDockingStatus::Undocked) {
threatsFound = true;
break;
}
}
if (!threatsFound) {
if (shipsCount.at(player_id) > 6 || turn > 30) {
// just end the rushing detection phase if we generated at least 6 ships
Log::log("Ending the rush phase because we have at least 6 ships or turn > 30");
threatsFound = false;
}
}
rush_phase = threatsFound;
Log::log() << "Rushing detection: " << (rush_phase ? "Continues" : "Ended") << std::endl;
}
}
// Generate all the tasks
GenerateTasks();
// detect rushers
// Organize ships; assign tasks
AssignTasks();
// Execute the tasks assigned by priority
std::vector<Ship*> requireComputeShips;
for (auto&kv : ships) {
Ship* ship = kv.second;
if (!ship->alive) continue;
if (!ship->IsOur()) continue;
requireComputeShips.push_back(ship);
}
// sort by priority
std::sort(requireComputeShips.begin(), requireComputeShips.end(), [](const Ship* shipPtrA, const Ship* shipPtrB) {
return shipPtrA->task_priority < shipPtrB->task_priority;
});
std::vector<Move> moves;
std::vector<NavigationRequest> navigationRequests;
for (Ship* ship : requireComputeShips) {
auto action = ship->ComputeAction();
if (action.second.second) {
ship->frozen = false;
navigationRequests.push_back(action.second.first);
}
else {
if (action.first.second) {
moves.push_back(action.first.first);
}
}
}
//UpdateMap();
std::vector<Move> navMoves = Navigation::NavigateShips(navigationRequests);
Log::log() << "Navigation requests: " << navigationRequests.size() << " Navigation moves: " << navMoves.size() << std::endl;
for (Move navMove : navMoves) {
// Add a message in the angle
//navMove.move_angle_deg += ((GetTask(GetShip(navMove.ship_id)->task_id)->target + 1) * 360);
moves.push_back(navMove);
}
return moves;
}
void Instance::GenerateTasks()
{
// Clear old tasks
current_task = 0;
for (Task* task : tasks)
delete task;
tasks.clear();
// Generate new tasks
for (auto& kv : planets) {
Planet* planet = kv.second;
if (!planet->alive) continue; // if the planet was destroyed 'it doesnt exist'
if (planet->owner_id == -1 || planet->IsOur()) { // the planet is not owned or it's owned by us
// Task DOCK
Task* taskDock = CreateTask(TaskType::DOCK);
taskDock->target = planet->entity_id;
taskDock->location = planet->location;
taskDock->radius = planet->radius;
taskDock->max_ships = game_over ? 0 : planet->docking_spots;
}
}
if (!game_over) {
// Ship tasks
for (auto& kv : ships) {
Ship* ship = kv.second;
if (!ship->alive) continue;
if (ship->IsOur()) continue;
// every enemy ship alive
Task* taskAttack = CreateTask(TaskType::ATTACK);
taskAttack->target = ship->entity_id;
taskAttack->location = ship->location;
taskAttack->radius = 0;
taskAttack->indefense = ship->docking_status != ShipDockingStatus::Undocked;
taskAttack->max_ships = 6;// TODO See
}
}
else { // game_over
// we've lost
// try to get 3rd place
for (int i = 0; i < 4; i++) {
Task* taskEscape = CreateTask(TaskType::ESCAPE);
taskEscape->target = -1;
taskEscape->location = { i % 2 == 0 ? 0 : (double)map_width, (int)(i / 2.0) == 0 ? 0 : (double)map_height };
taskEscape->radius = 0;
taskEscape->max_ships = -1; // All ships must escape
}
}
Log::log() << "Generated " << tasks.size() << " tasks" << std::endl;
}
void Instance::AssignTasks()
{
std::queue<Ship*> qShips;
std::set<Task*> dockTasksWithShips;
// non undocked ships have a fixed task
for (auto& kv : ships) {
Ship* ship = kv.second;
if (!ship->alive) continue;
if (!ship->IsOur()) continue;
if (!ship->IsCommandable()) {
// ship is docking, docked or undocking
Task* dockTask = 0;
// we're docked to a planet, find the task that match
for (Task* task : tasks) {
if (task->type == TaskType::DOCK && task->target == ship->docked_planet) {
dockTask = task;
break;
}
}
if (dockTask == 0) {
Log::log("Dock task for ship " + std::to_string(ship->entity_id) + " not found.");
qShips.push(ship);
}
else {
std::string status_name = "UNKNOWN";
switch (ship->docking_status)
{
case ShipDockingStatus::Docking: status_name = "DOCKING"; break;
case ShipDockingStatus::Docked: status_name = "DOCKED"; break;
case ShipDockingStatus::Undocking: status_name = "UNDOCKING"; break;
}
Log::log("Ship " + std::to_string(ship->entity_id) + " continues " + status_name + " to planet " + std::to_string(dockTask->target) + " -- docking progress: " + std::to_string(ship->docking_progress));
ship->task_id = dockTask->task_id;
ship->task_priority = INF; // docked ships cant be relevated
dockTask->ships.insert(ship);
dockTasksWithShips.insert(dockTask);
}
} else
qShips.push(ship);
}
// for the rest of the ships (which are now on qShips)
while (!qShips.empty()) {
Ship* ship = qShips.front();
qShips.pop();
Task* priorizedTask = 0;
double maxPriority = -INF;
Ship* otherShipPtrOverriding = 0;
for (Task* task : tasks) {
if (task->max_ships == 0) continue;
// this is a priority relative to the ship, aka how important this task is for this ship
Vector2 target = task->location;
if (task->radius != 0)
target = ship->location.ClosestPointTo(task->location, task->radius);
double distance = ship->location.DistanceTo(task->location);
/* PRIORITY CALCULATION */
double d = distance;
switch (task->type)
{
case DOCK:
d += 8;
break;
case ATTACK:
if (task->indefense) {
d -= 9;
double arriveDist = ship->location.DistanceTo(target);
int enemiesWhenArrive = CountNearbyShips(target, ship->radius, arriveDist, false);
int friendsWhenArrive = CountNearbyShips(target, ship->radius, arriveDist, true);
if (friendsWhenArrive >= enemiesWhenArrive) {
d -= 13;
}
}
// if we are in early game, we even priorize this more
/*
if (!rush_phase && turn < 30) {
d -= 35;
}
*/
break;
}
double distancePriority = 100 - d / 100;
double priority = distancePriority;
/* PRIORITY CALCULATION */
if (task->type == ATTACK) {
Log::log() << "Ship " << ship->entity_id << " with task " << task->task_id << " priority " << priority << std::endl;
}
Ship* otherShipPtrWithLessPriority = 0;
if (task->IsFull()) { // task is full, no other ship can help
// but we check if we have a higher priority than one of the ships already assigned to this task
double otherShipPtrMinPriority = INF; // less is better
for (Ship* otherShipPtr : task->ships) {
double otherShipPtrPriority = otherShipPtr->task_priority;
if (priority > otherShipPtrPriority) {
if (otherShipPtrPriority < otherShipPtrMinPriority) {
otherShipPtrWithLessPriority = otherShipPtr;
otherShipPtrMinPriority = otherShipPtrPriority;
}
}
}
if (!otherShipPtrWithLessPriority)
continue;
}
if (priority > maxPriority) {
maxPriority = priority;
priorizedTask = task;
otherShipPtrOverriding = otherShipPtrWithLessPriority;
}
}
if (priorizedTask == 0) {
Log::log("Ship " + std::to_string(ship->entity_id) + " couldn't find a suitable task!");
}
else {
Log::log("Ship " + std::to_string(ship->entity_id) + " assigned to task " + std::to_string(priorizedTask->task_id) + " (" + priorizedTask->Info() + ") with priority " + std::to_string(maxPriority));
if (otherShipPtrOverriding) {
Log::log("... while overriding ship " + std::to_string(otherShipPtrOverriding->entity_id) + " in task " + std::to_string(otherShipPtrOverriding->task_id));
priorizedTask->ships.erase(otherShipPtrOverriding);
qShips.push(otherShipPtrOverriding);
otherShipPtrOverriding->task_id = -1;
otherShipPtrOverriding->task_priority = 0;
}
ship->task_id = priorizedTask->task_id;
ship->task_priority = maxPriority;
priorizedTask->ships.insert(ship);
}
}
Log::log() << "Tasks have been assigned" << std::endl;
}
int Instance::CountNearbyShips(Vector2 location, double radius, double range, bool friends)
{
int count = 0;
for (auto& kv : ships) {
Ship* ship = kv.second;
if (!ship->alive) continue;
if (ship->IsOur() == friends) {
if (ship->IsCommandable()) {
if (ship->location.DistanceTo(location) - radius < range) {
count++;
}
}
}
}
return count;
}
Ship* Instance::FindClosestShip(Vector2 location, bool indefense)
{
double minDistance = INF;
Ship* result;
for (auto& kv : ships) {
Ship* ship = kv.second;
if (!ship->alive) continue;
if (ship->IsOur()) continue;
if (!ship->IsCommandable() == indefense) {
double distance = ship->location.DistanceTo(location);
if (distance < minDistance) {
minDistance = distance;
result = ship;
}
}
}
return result;
}
| [
"[email protected]"
] | |
9cf7bb2823358fa498f68cf8288d12e6720cc1ed | 7849554c268311afab49d919d68a0deed784c221 | /src/SimulatorApp/org.alljoyn.Notification.Producer/ProducerConsumer.h | 022eaaa63c0c7e8c82ee63691e7a9ce06cf0059b | [
"MIT"
] | permissive | dotMorten/AllJoynDeviceSimulator | aa30a73e188c738daa7ba5cc143e7af72c65d005 | b5a7e7198983c0aad02f78d1868a083940f7c57f | refs/heads/master | 2020-12-29T00:30:27.844468 | 2016-08-16T04:13:28 | 2016-08-16T04:13:28 | 49,626,641 | 8 | 5 | null | 2016-08-08T19:45:35 | 2016-01-14T06:08:58 | C++ | UTF-8 | C++ | false | false | 9,557 | h | //-----------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//
// Tool: AllJoynCodeGenerator.exe
//
// This tool is located in the Windows 10 SDK and the Windows 10 AllJoyn
// Visual Studio Extension in the Visual Studio Gallery.
//
// The generated code should be packaged in a Windows 10 C++/CX Runtime
// Component which can be consumed in any UWP-supported language using
// APIs that are available in Windows.Devices.AllJoyn.
//
// Using AllJoynCodeGenerator - Invoke the following command with a valid
// Introspection XML file and a writable output directory:
// AllJoynCodeGenerator -i <INPUT XML FILE> -o <OUTPUT DIRECTORY>
// </auto-generated>
//-----------------------------------------------------------------------------
#pragma once
namespace org { namespace alljoyn { namespace Notification { namespace Producer {
public interface class IProducerConsumer
{
event Windows::Foundation::TypedEventHandler<ProducerConsumer^, Windows::Devices::AllJoyn::AllJoynSessionLostEventArgs^>^ SessionLost;
event Windows::Foundation::TypedEventHandler<ProducerConsumer^, Windows::Devices::AllJoyn::AllJoynSessionMemberAddedEventArgs^>^ SessionMemberAdded;
event Windows::Foundation::TypedEventHandler<ProducerConsumer^, Windows::Devices::AllJoyn::AllJoynSessionMemberRemovedEventArgs^>^ SessionMemberRemoved;
};
public ref class ProducerConsumer sealed : [Windows::Foundation::Metadata::Default] IProducerConsumer
{
public:
ProducerConsumer(Windows::Devices::AllJoyn::AllJoynBusAttachment^ busAttachment);
virtual ~ProducerConsumer();
// Join the AllJoyn session specified by sessionName.
//
// This will usually be called after the unique name of a producer has been reported
// in the Added callback on the Watcher.
static Windows::Foundation::IAsyncOperation<ProducerJoinSessionResult^>^ JoinSessionAsync(_In_ Windows::Devices::AllJoyn::AllJoynServiceInfo^ serviceInfo, _Inout_ ProducerWatcher^ watcher);
// Call the Dismiss method
Windows::Foundation::IAsyncOperation<ProducerDismissResult^>^ DismissAsync(_In_ int32 interfaceMemberInputArg);
// Get the value of the Version property.
Windows::Foundation::IAsyncOperation<ProducerGetVersionResult^>^ GetVersionAsync();
// Used to send signals or register functions to handle received signals.
property ProducerSignals^ Signals
{
ProducerSignals^ get() { return m_signals; }
}
// This event will fire whenever the consumer loses the session that it is a member of.
virtual event Windows::Foundation::TypedEventHandler<ProducerConsumer^, Windows::Devices::AllJoyn::AllJoynSessionLostEventArgs^>^ SessionLost
{
Windows::Foundation::EventRegistrationToken add(Windows::Foundation::TypedEventHandler<ProducerConsumer^, Windows::Devices::AllJoyn::AllJoynSessionLostEventArgs^>^ handler)
{
return _SessionLost += ref new Windows::Foundation::EventHandler<Platform::Object^>
([handler](Platform::Object^ sender, Platform::Object^ args)
{
handler->Invoke(safe_cast<ProducerConsumer^>(sender), safe_cast<Windows::Devices::AllJoyn::AllJoynSessionLostEventArgs^>(args));
}, Platform::CallbackContext::Same);
}
void remove(Windows::Foundation::EventRegistrationToken token)
{
_SessionLost -= token;
}
internal:
void raise(ProducerConsumer^ sender, Windows::Devices::AllJoyn::AllJoynSessionLostEventArgs^ args)
{
_SessionLost(sender, args);
}
}
// This event will fire whenever a member joins the session.
virtual event Windows::Foundation::TypedEventHandler<ProducerConsumer^, Windows::Devices::AllJoyn::AllJoynSessionMemberAddedEventArgs^>^ SessionMemberAdded
{
Windows::Foundation::EventRegistrationToken add(Windows::Foundation::TypedEventHandler<ProducerConsumer^, Windows::Devices::AllJoyn::AllJoynSessionMemberAddedEventArgs^>^ handler)
{
return _SessionMemberAdded += ref new Windows::Foundation::EventHandler<Platform::Object^>
([handler](Platform::Object^ sender, Platform::Object^ args)
{
handler->Invoke(safe_cast<ProducerConsumer^>(sender), safe_cast<Windows::Devices::AllJoyn::AllJoynSessionMemberAddedEventArgs^>(args));
}, Platform::CallbackContext::Same);
}
void remove(Windows::Foundation::EventRegistrationToken token)
{
_SessionMemberAdded -= token;
}
internal:
void raise(ProducerConsumer^ sender, Windows::Devices::AllJoyn::AllJoynSessionMemberAddedEventArgs^ args)
{
_SessionMemberAdded(sender, args);
}
}
// This event will fire whenever a member leaves the session.
virtual event Windows::Foundation::TypedEventHandler<ProducerConsumer^, Windows::Devices::AllJoyn::AllJoynSessionMemberRemovedEventArgs^>^ SessionMemberRemoved
{
Windows::Foundation::EventRegistrationToken add(Windows::Foundation::TypedEventHandler<ProducerConsumer^, Windows::Devices::AllJoyn::AllJoynSessionMemberRemovedEventArgs^>^ handler)
{
return _SessionMemberRemoved += ref new Windows::Foundation::EventHandler<Platform::Object^>
([handler](Platform::Object^ sender, Platform::Object^ args)
{
handler->Invoke(safe_cast<ProducerConsumer^>(sender), safe_cast<Windows::Devices::AllJoyn::AllJoynSessionMemberRemovedEventArgs^>(args));
}, Platform::CallbackContext::Same);
}
void remove(Windows::Foundation::EventRegistrationToken token)
{
_SessionMemberRemoved -= token;
}
internal:
void raise(ProducerConsumer^ sender, Windows::Devices::AllJoyn::AllJoynSessionMemberRemovedEventArgs^ args)
{
_SessionMemberRemoved(sender, args);
}
}
internal:
// Consumers do not support property get.
QStatus OnPropertyGet(_In_ PCSTR interfaceName, _In_ PCSTR propertyName, _Inout_ alljoyn_msgarg val)
{
UNREFERENCED_PARAMETER(interfaceName); UNREFERENCED_PARAMETER(propertyName); UNREFERENCED_PARAMETER(val);
return ER_NOT_IMPLEMENTED;
}
// Consumers do not support property set.
QStatus OnPropertySet(_In_ PCSTR interfaceName, _In_ PCSTR propertyName, _In_ alljoyn_msgarg val)
{
UNREFERENCED_PARAMETER(interfaceName); UNREFERENCED_PARAMETER(propertyName); UNREFERENCED_PARAMETER(val);
return ER_NOT_IMPLEMENTED;
}
void OnSessionLost(_In_ alljoyn_sessionid sessionId, _In_ alljoyn_sessionlostreason reason);
void OnSessionMemberAdded(_In_ alljoyn_sessionid sessionId, _In_ PCSTR uniqueName);
void OnSessionMemberRemoved(_In_ alljoyn_sessionid sessionId, _In_ PCSTR uniqueName);
void OnPropertyChanged(_In_ alljoyn_proxybusobject obj, _In_ PCSTR interfaceName, _In_ const alljoyn_msgarg changed, _In_ const alljoyn_msgarg invalidated);
property Platform::String^ ServiceObjectPath
{
Platform::String^ get() { return m_ServiceObjectPath; }
void set(Platform::String^ value) { m_ServiceObjectPath = value; }
}
property alljoyn_proxybusobject ProxyBusObject
{
alljoyn_proxybusobject get() { return m_proxyBusObject; }
void set(alljoyn_proxybusobject value) { m_proxyBusObject = value; }
}
property alljoyn_busobject BusObject
{
alljoyn_busobject get() { return m_busObject; }
void set(alljoyn_busobject value) { m_busObject = value; }
}
property alljoyn_sessionlistener SessionListener
{
alljoyn_sessionlistener get() { return m_sessionListener; }
void set(alljoyn_sessionlistener value) { m_sessionListener = value; }
}
property alljoyn_sessionid SessionId
{
alljoyn_sessionid get() { return m_sessionId; }
}
private:
virtual event Windows::Foundation::EventHandler<Platform::Object^>^ _SessionLost;
virtual event Windows::Foundation::EventHandler<Platform::Object^>^ _SessionMemberAdded;
virtual event Windows::Foundation::EventHandler<Platform::Object^>^ _SessionMemberRemoved;
int32 JoinSession(_In_ Windows::Devices::AllJoyn::AllJoynServiceInfo^ serviceInfo);
// Register a callback function to handle incoming signals.
QStatus AddSignalHandler(_In_ alljoyn_busattachment busAttachment, _In_ alljoyn_interfacedescription interfaceDescription, _In_ PCSTR methodName, _In_ alljoyn_messagereceiver_signalhandler_ptr handler);
Windows::Devices::AllJoyn::AllJoynBusAttachment^ m_busAttachment;
ProducerSignals^ m_signals;
Platform::String^ m_ServiceObjectPath;
alljoyn_proxybusobject m_proxyBusObject;
alljoyn_busobject m_busObject;
alljoyn_sessionlistener m_sessionListener;
alljoyn_sessionid m_sessionId;
alljoyn_busattachment m_nativeBusAttachment;
// Used to pass a pointer to this class to callbacks
Platform::WeakReference* m_weak;
// This map is required because we need a way to pass the consumer to the signal
// handlers, but the current AllJoyn C API does not allow passing a context to these
// callbacks.
static std::map<alljoyn_interfacedescription, Platform::WeakReference*> SourceInterfaces;
};
} } } }
| [
"[email protected]"
] | |
42131c11f0ac8992b971668fe82712c62dc966d7 | 39100b66c5359c5fa7ce2dc3e0bba754f70d73f7 | /CaioRB L2E2/DarkPriest.cpp | 2dd072711b3ee35bcafc8966fcf8036076e8bd50 | [] | no_license | raphaellc/AlgEDCPP | 74db9cf0b2a27239c7b44b585e436637aa522151 | f37fca39d16aa8b11572603ba173e7bc2e0e870a | refs/heads/master | 2020-03-25T21:11:30.969638 | 2018-11-29T14:24:06 | 2018-11-29T14:24:06 | 144,163,894 | 0 | 0 | null | 2018-12-11T22:08:25 | 2018-08-09T14:28:14 | C++ | UTF-8 | C++ | false | false | 194 | cpp | #include "DarkPriest.h"
#include <iostream>
DarkPriest::DarkPriest()
{
}
DarkPriest::~DarkPriest()
{
}
void DarkPriest::charm()
{
std::cout << "You follow me now./n";
}
| [
"[email protected]"
] | |
662f734dd95f0aa3d89f583a6b0c116020432d84 | 348929c1b3bbcf91de71f52c8d34c5c37160eda2 | /StrukturePodataka/SP-Stablo-LV(fax)/SP-LV(fax)/Main.cpp | 7b6de4d944c4619ceb65a2cadb987842b1964334 | [] | no_license | pavle-doby/Elfak_lab_vezbe | 385c9592d9e23fa3d4d70e4cb7251387d40f3099 | 262ac7c75e719b82ac61e3f80b8608c4b401e966 | refs/heads/master | 2021-10-14T04:32:42.956300 | 2018-10-24T00:41:58 | 2018-10-24T00:41:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 422 | cpp | #include <iostream>
#include "Tree.h"
#include "Node.h"
using namespace std;
void main()
{
Tree drvo;
drvo.insert(7);
drvo.insert(11);
drvo.insert(9);
drvo.insert(12);
drvo.insert(3);
drvo.insert(5);
drvo.insert(2);
drvo.insert(1);
cout << "drvo:" << endl;
drvo.printAll();
int br=drvo.atLevel(drvo.getRoot(), 3, 0);
cout <<endl<< "U "<<3 <<". redu " << "ima " << br << " cvora"<<endl;
system("Pause");
} | [
"[email protected]"
] | |
b6c1bf76f6fcde201e7eeaa7e70bf73adefb3955 | e4d400c65be7fe8d44e6d0534fb705b89a0a7901 | /CQuiz/CQuiz.cpp | 741abae5c6040f43a23662e5e6846ea6d1278c77 | [] | no_license | JBudiman00/CQuiz | d690a8e59decec0abb33cdd683e3c8968d062cd6 | 78b822d3f2989b7da8370f134fa15946ccb5e655 | refs/heads/master | 2022-11-21T13:16:38.873353 | 2020-07-24T14:46:23 | 2020-07-24T14:46:23 | 282,243,403 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,479 | cpp | // CQuiz.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int random(int, int);
int answer(char[]);
int getQuestions();
void getMax();
int checkUsed(int);
int max;
int* usedQ;
int main()
{
char choice[10];
getMax();
#define SIZE max
//Description
printf("Welcome to Nathan's quiz. This is a random quiz program\n");
printf("Choose the # of questions on the quiz (At least 1, at most %d)\n", max/2);
scanf("%s", choice);
srand(time(NULL));
usedQ = (int*) malloc(max * sizeof(int));
usedQ[0] = -1;
printf("Searhing... \n");
printf("Questions ready\n");
int count = 0;
int a = atoi(choice);
for (int x = 0; x < a; x++) {
count += getQuestions();
}
free(usedQ);
printf("You answered %d out of %d correctly", count, a);
return 0;
}
//Pull questions from .txt bank
int getQuestions() {
FILE* fp;
int ans = 0;
fp = fopen("C:\\Temp\\tmp\\quiz.txt", "r");
if (fp == NULL) {
printf("Error opening file");
exit(EXIT_FAILURE);
}
else {
char line[256];
int count = 0;
int lineNumber;
for(;;){
lineNumber = random(0, max);
if (checkUsed(lineNumber) == 0) {
break;
}
}
while (fgets(line, sizeof line, fp) != NULL) {
if (count == lineNumber) {
printf("Question: %s", line);
fgets(line, sizeof line, fp);
ans = answer(line);
break;
}
count++;
}
}
fclose(fp);
return ans;
}
int checkUsed(int lineNumber) { //int is bool. 1 = true (has been used), 0 = false (hasn't been used)
int test;
for (int x = 0; x < max; x++)
{
if (usedQ[x] == lineNumber) {
return 1;
}
if (usedQ[x] == -1) {
usedQ[x] = lineNumber;
usedQ[x + 1] = -1;
return 0;
}
}
//Should never reach this point
return 0;
}
int answer(char ans[]) { //int is bool. 1 = true, 0 = false
char input[50];
ans[strlen(ans) - 1] = '\0';
scanf("%s", input);
if (strcmp(input, ans) == 0) {
printf("Correct!\n");
return 1;
}
printf("Boo, incorrect smh\n");
return 0;
}
int random(int min, int max) {
int randNum;
for (;;) {
randNum = rand() % max;
if (randNum % 2 == 0) {
break;
}
}
return randNum;
}
void getMax() {
FILE* fp;
fp = fopen("C:\\Temp\\tmp\\quiz.txt", "r");
char line[256];
max = 0;
while (fgets(line, sizeof line, fp) != NULL) {
max++;
}
fclose(fp);
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
| [
"[email protected]"
] | |
64e2ded0ad1c4b037754f2005d7d7843003d5fb0 | c54b4353e2a813ba522877293df14d4591261787 | /xcode/script_object.cpp | 8611f37608b4d1fffe55cc7a832bea24aee2881b | [] | no_license | joemcalister/A.M.I | 47895ef5d5ebc39224a48eae599423ccfb27e911 | 09b81640e40de56675fa1d717a1197359e6af115 | refs/heads/master | 2021-01-19T21:13:29.266062 | 2017-05-08T14:55:47 | 2017-05-08T14:55:47 | 88,628,584 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 114 | cpp | //
// script_object.cpp
// ami_proto_2
//
// Created by Joe on 11/02/2017.
//
//
#include "script_object.hpp"
| [
"[email protected]"
] | |
525964768846afee855a92d2415bb5df3c2da2d0 | 9922edafddb080ccefb36858e5ffd1a106beae95 | /Server/LoginServer/main/LDBTaskCharDelete.h | 609f6c98128e28d28fcb48d7fe55514b50ad1023 | [] | no_license | saerich/RaiderZ-Evolved-Develop | ee93f46d866ed0310107a07ad0a4a2db3a2fd529 | b2a20e2a5b058a330b2e18a3f0a45a10f71f2cb0 | refs/heads/master | 2023-02-25T15:43:26.276331 | 2021-02-04T01:37:25 | 2021-02-04T01:37:25 | 281,212,532 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 904 | h | #ifndef _LDBTASK_DELETECHARACTER_H
#define _LDBTASK_DELETECHARACTER_H
#include "LDBAsyncTask.h"
#include "MMemPool.h"
class SAccountCharList;
class LDBTaskCharDelete : public LDBAsyncTask, public MMemPool<LDBTaskCharDelete>
{
public :
LDBTaskCharDelete();
~LDBTaskCharDelete();
enum
{
CHAR_DELETE = 0,
};
enum RETURN
{
FAIL_GUILDMASTER = -1,
SUCCESS = 0,
};
void Input(const MUID& uidPlayer, const int nIndex);
void OnExecute(mdb::MDatabase& rfDB);
mdb::MDB_THRTASK_RESULT _OnCompleted();
private :
struct _DATA
{
MUID uidPlayer;
int nIndex;
int nReturn;
};
class Completer
{
public :
Completer(_DATA& Data, int& nReturn);
void Do();
private :
void RebuildCharList(const int nIndex, SAccountCharList& CharList);
void RouteResult(CCommandResultTable nCRT, int nIndex);
private :
_DATA& m_Data;
};
protected :
_DATA m_Data;
};
#endif | [
"[email protected]"
] | |
711788c880c730b69b49ab3a116d7a0c944c2651 | a864edfee8f42d67157ef8091b2a10c5803bbe6c | /Source/Samples/18_CharacterDemo/PhotoCamera.h | 57fd95aeacfe1384a8becc86a1b7dbf574b5a4e6 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | MynachMelyn/U3DGame | 16be918351adef75d57aace1df66cce34b285bdd | 19517880318ef7c676184d60377a3fa752e8804e | refs/heads/master | 2022-03-11T04:50:44.011403 | 2019-07-03T23:52:21 | 2019-07-03T23:52:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,031 | h | #pragma once
#include <Urho3D/Scene/LogicComponent.h>
#include <Urho3D/Graphics/AnimatedModel.h>
#include <Urho3D/Graphics/RenderPath.h>
using namespace Urho3D;
class PhotoCamera : public LogicComponent {
URHO3D_OBJECT(PhotoCamera, LogicComponent);
public:
///Construct.
explicit PhotoCamera(Context* context);
/// Register object factory and attributes.
static void RegisterObject(Context* context);
/// Handle startup. Called by LogicComponent base class.
void Start() override;
/// Handle physics world update. Called by LogicComponent base class.
void FixedUpdate(float timeStep) override;
void snapAPhoto();
void changeFocus(float valuePerSecond, float timeStep);
void MakeViewport();
void Setup();
Node* rttCameraNode;
AnimatedModel* cameraModel;
Node* cameraNode;
Scene* scene;
SharedPtr<Texture2D> renderTexture;
SharedPtr<RenderPath> cameraRenderPath;
SharedPtr<RenderPath> cameraRenderPathDebug;
int focusChange = 0;
bool changeAperture = false;
}; | [
"[email protected]"
] | |
c958a59c193603a15febc1773d3627888303d9b8 | 6c0f8abb26f9832eb7ab00901f470d001be4af32 | /util/Test/tNoiseBias.cc | 55455e776337f8b48df96ea0916a0b682bd81a94 | [
"MIT"
] | permissive | erikleitch/climax | 146a6bf69b04f0df8879e77ea4529b4c269015a5 | 66ce64b0ab9f3a3722d3177cc5215ccf59369e88 | refs/heads/master | 2021-07-19T17:17:22.524714 | 2021-02-02T17:17:35 | 2021-02-02T17:17:35 | 57,599,379 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 14,294 | cc | #include <iostream>
#include <iomanip>
#include <cmath>
#include "gcp/program/Program.h"
#include "gcp/util/Angle.h"
#include "gcp/util/HourAngle.h"
#include "gcp/util/Declination.h"
#include "gcp/util/Mass.h"
#include "gcp/util/Sampler.h"
#include "gcp/util/Stats.h"
#include "gcp/pgutil/PgUtil.h"
#include "cpgplot.h"
using namespace std;
using namespace gcp::util;
using namespace gcp::program;
KeyTabEntry Program::keywords[] = {
{ "rad", "0", "d", "Radians"},
{ "nsamp", "1000", "i", "nsamp"},
{ "niter", "1000", "i", "niter"},
{ "npt", "1000", "i", "npt"},
{ "sigma", "1.0", "d", "sigma"},
{ "snrtrue", "3.0", "d", "true SNR"},
{ "snrmin", "0.0", "d", "min SNR"},
{ "snrmax", "4.0", "d", "max SNR"},
{ "expmax", "2.7", "d", "explicit max SNR"},
{ "expn", "9", "i", "number of independent samples to assume"},
{ END_OF_KEYWORDS}
};
void Program::initializeUsage() {};
void makeMadcowsPlot(std::string dev, unsigned npt, double snrMinTrue, double snrMaxTrue);
void makeFullPlot(std::string dev, unsigned npt, double snrMax, double snrMinTrue, double snrMaxTrue);
double psFull(unsigned nsamp, double snrMax, double snrTrue);
double plotPsFull(unsigned npt, unsigned nsamp, double snrMax, double snrTrueMin, double snrTrueMax);
void printRatio(unsigned nsamp, double snrMax, double snrTrue);
void plotRatio(unsigned npt, unsigned nsamp, double snrMin, double snrMax, double snrTrue, bool write);
void plotPsNoise(unsigned npt, unsigned nsamp, double snrMin, double snrMax, double norm);
void plotPsTrue(unsigned npt, unsigned nsamp, double xmin, double xmax, double norm, double snrTrue);
void makeNoisePlot(unsigned npt, double snrmin, double snrmax);
void makeRatioPlot(unsigned npt, double snrmin, double snrmax);
void makeRatioPlotSub(unsigned npt, double snrmin, double snrmax, double snrTrue);
void simNoiseOnly(unsigned nsamp, unsigned niter)
{
std::vector<double> maxs(niter);
for(unsigned i=0; i < niter; i++) {
std::vector<double> samps = Sampler::generateGaussianSamples(1.0, nsamp);
maxs[i] = Stats::max(samps);
}
PgUtil::histogram(&maxs, 100);
}
double simWithSignal(unsigned nsamp, unsigned niter, double snrTrue,
double& snrMin, double& snrMax, double& norm)
{
std::vector<double> maxs(niter);
std::vector<double> snrVals(niter);
for(unsigned i=0; i < niter; i++) {
std::vector<double> samps = Sampler::generateGaussianSamples(1.0, nsamp);
unsigned ind = (unsigned)Sampler::generateUniformSample(0, nsamp-1);
samps[ind] += snrTrue;
maxs[i] = Stats::max(samps);
}
PgUtil::histogram(&maxs, 100);
std::vector<double> x;
std::vector<double> y;
Stats::histogram(maxs, 100, x, y);
norm = Stats::max(y);
snrMin = Stats::min(x);
snrMax = Stats::max(x);
}
int Program::main()
{
unsigned nsamp = Program::getIntegerParameter("nsamp");
unsigned niter = Program::getIntegerParameter("niter");
unsigned npt = Program::getIntegerParameter("npt");
double snrMin = Program::getDoubleParameter("snrmin");
double snrMax = Program::getDoubleParameter("snrmax");
double snrTrue = Program::getDoubleParameter("snrtrue");
double explicitMax = Program::getDoubleParameter("expmax");
unsigned expn = Program::getIntegerParameter("expn");
#if 0
makeNoisePlot(npt, snrMin, snrMax);
return 0;
#endif
#if 0
double norm, xmin, xmax;
xmin = snrMin;
xmax = snrMax;
simWithSignal(nsamp, niter, snrTrue, xmin, xmax, norm);
plotPsTrue(npt, nsamp, xmin, xmax, norm, snrTrue);
makeRatioPlot(npt, snrMin, snrMax);
// return;
std::vector<double> maxs(niter);
for(unsigned i=0; i < niter; i++) {
std::vector<double> samps = Sampler::generateGaussianSamples(1.0, nsamp);
maxs[i] = Stats::max(samps);
}
PgUtil::histogram(&maxs, 100);
double mode = Stats::mode(maxs, 100);
COUT("cdf of " << mode << " = " << Sampler::gaussCdf(mode, 0.0, 1.0));
std::vector<double> x;
std::vector<double> y;
Stats::histogram(maxs, 100, x, y);
PgUtil::setOverplot(true);
PgUtil::setWin(false);
plotPsNoise(npt, nsamp, Stats::min(x), Stats::max(x), Stats::max(y));
#endif
makeFullPlot("full2.ps/cps", npt, 2.0, snrMin, snrMax);
makeFullPlot("full3.ps/cps", npt, 3.0, snrMin, snrMax);
makeMadcowsPlot("madcows.ps/cps", npt, snrMin, snrMax);
PgUtil::open("/xs");
PgUtil::setUsedefs(false);
PgUtil::setOverplot(false);
PgUtil::setTraceColor(6);
PgUtil::setWin(true);
double estStrue = plotPsFull(npt, expn, explicitMax, snrMin, snrMax);
printRatio(expn, explicitMax, estStrue);
return 0;
}
/**.......................................................................
* Plot the noise only probability distribution
*/
void plotPsNoise(unsigned npt, unsigned nsamp, double snrMin, double snrMax, double norm)
{
std::vector<double> x(npt);
std::vector<double> y(npt);
double dx = (snrMax - snrMin)/(npt-1);
for(unsigned i=0; i < npt; i++) {
x[i] = snrMin + dx*i;
y[i] = Sampler::gaussPdf(x[i], 0.0, 1.0);
double cdf = Sampler::gaussCdf(x[i], 0.0, 1.0);
for(unsigned iSamp=0; iSamp < nsamp-1; iSamp++) {
y[i] *= cdf;
}
}
unsigned iMax;
double normCalc = Stats::max(y, iMax);
for(unsigned i=0; i < npt; i++) {
y[i] *= norm/normCalc;
}
PgUtil::linePlot(x, y, "S\\dmax\\u", "p(S\\dmax\\u| 0, H\\dn\\u)");
}
void plotPsTrue(unsigned npt, unsigned nsamp, double snrMin, double snrMax, double norm, double snrTrue)
{
std::vector<double> x(npt);
std::vector<double> ynmax(npt);
std::vector<double> ysmax(npt);
std::vector<double> y(npt);
std::vector<double> r(npt);
double dx = (snrMax - snrMin)/(npt-1);
for(unsigned i=0; i < npt; i++) {
x[i] = snrMin + dx*i;
ynmax[i] = Sampler::gaussPdf(x[i], 0.0, 1.0);
ysmax[i] = Sampler::gaussPdf(x[i], snrTrue, 1.0);
double ncdf = Sampler::gaussCdf(x[i], 0.0, 1.0);
double scdf = Sampler::gaussCdf(x[i], snrTrue, 1.0);
if(nsamp > 1) {
for(unsigned iSamp=0; iSamp < nsamp-1; iSamp++) {
ysmax[i] *= ncdf;
}
}
if(nsamp > 1) {
ynmax[i] *= scdf;
}
if(nsamp > 2) {
for(unsigned iSamp=0; iSamp < nsamp-2; iSamp++) {
ynmax[i] *= ncdf;
}
}
y[i] = ysmax[i] + (nsamp-1)*ynmax[i];
r[i] = log10(ysmax[i] / ((nsamp-1)*ynmax[i]));
}
unsigned iMax;
double normCalc = Stats::max(y, iMax);
COUT("PLotting norm = " << norm << " calc = " << normCalc);
for(unsigned i=0; i < npt; i++) {
y[i] *= norm/normCalc;
}
COUT("PLotting norm = " << norm);
PgUtil::setOverplot(true);
PgUtil::setWin(false);
PgUtil::linePlot(x, y);
COUT("PLotting ratio");
PgUtil::setOverplot(false);
PgUtil::setWin(true);
PgUtil::linePlot(x, r);
}
void makeNoisePlot(unsigned npt, double snrmin, double snrmax)
{
PgUtil::open("psnoise.ps/cps");
PgUtil::setCharacterHeight(2);
PgUtil::setOverplot(false);
PgUtil::setTraceColor(2);
PgUtil::setWin(true);
COUT("Calling plotpsnoise");
plotPsNoise(npt, 1, snrmin, snrmax, 1.0);
PgUtil::setOverplot(true);
PgUtil::setTraceColor(8);
PgUtil::setWin(false);
plotPsNoise(npt, 5, snrmin, snrmax, 1.0);
PgUtil::setOverplot(true);
PgUtil::setTraceColor(6);
PgUtil::setWin(false);
plotPsNoise(npt, 20, snrmin, snrmax, 1.0);
}
void printRatio(unsigned nsamp, double snrMax, double snrTrue)
{
double x;
double ynmax;
double ysmax;
double y;
double r;
x = snrMax;
ynmax = Sampler::gaussPdf(x, 0.0, 1.0);
ysmax = Sampler::gaussPdf(x, snrTrue, 1.0);
double ncdf = Sampler::gaussCdf(x, 0.0, 1.0);
double scdf = Sampler::gaussCdf(x, snrTrue, 1.0);
if(nsamp > 1) {
for(unsigned iSamp=0; iSamp < nsamp-1; iSamp++) {
ysmax *= ncdf;
}
}
if(nsamp > 1) {
ynmax *= scdf;
}
if(nsamp > 2) {
for(unsigned iSamp=0; iSamp < nsamp-2; iSamp++) {
ynmax *= ncdf;
}
}
r = ysmax / ((nsamp-1)*ynmax);
double lr = log10(ysmax / ((nsamp-1)*ynmax));
COUT("ps = " << ysmax << " pn = " << (nsamp-1)*ynmax << " r = " << r << " log10(r) = " << lr << " for n = " << nsamp << " smax = " << snrMax << " strue = " << snrTrue);
}
void plotRatio(unsigned npt, unsigned nsamp, double snrMin, double snrMax, double snrTrue, bool write)
{
std::vector<double> x(npt);
std::vector<double> ynmax(npt);
std::vector<double> ysmax(npt);
std::vector<double> y(npt);
std::vector<double> r(npt);
double dx = (snrMax - snrMin)/(npt-1);
COUT("snr ranges from " << snrMin << " to " << snrMax);
for(unsigned i=0; i < npt; i++) {
x[i] = snrMin + dx*i;
ynmax[i] = Sampler::gaussPdf(x[i], 0.0, 1.0);
ysmax[i] = Sampler::gaussPdf(x[i], snrTrue, 1.0);
double ncdf = Sampler::gaussCdf(x[i], 0.0, 1.0);
double scdf = Sampler::gaussCdf(x[i], snrTrue, 1.0);
if(nsamp > 1) {
for(unsigned iSamp=0; iSamp < nsamp-1; iSamp++) {
ysmax[i] *= ncdf;
}
}
if(nsamp > 1) {
ynmax[i] *= scdf;
}
if(nsamp > 2) {
for(unsigned iSamp=0; iSamp < nsamp-2; iSamp++) {
ynmax[i] *= ncdf;
}
}
y[i] = ysmax[i] + (nsamp-1)*ynmax[i];
r[i] = log10(ysmax[i] / ((nsamp-1)*ynmax[i]));
}
double ymax = Stats::max(r);
double ymin = Stats::min(r);
std::ostringstream os;
os << "S\\dtrue\\u = " << snrTrue;
PgUtil::linePlot(x, r, "S\\dmax\\u", "log\\d10\\u(r)");
if(write) {
os.str("");
COUT("ymax = " << ymax);
os << "N = " << nsamp;
float ch;
cpgqch(&ch);
cpgsch(1.0);
PgUtil::text(os.str(), snrMin, ymin + 0.05*(ymax-ymin), Angle(Angle::Degrees(), 0.0), PgUtil::JUST_LEFT);
cpgsch(ch);
}
}
double plotPsFull(unsigned npt, unsigned nsamp, double snrMax, double snrTrueMin, double snrTrueMax)
{
std::vector<double> x(npt);
std::vector<double> y(npt);
COUT("min = " << snrTrueMin << " max = " << snrTrueMax);
double dx = (snrTrueMax - snrTrueMin)/(npt-1);
for(unsigned i=0; i < npt; i++) {
x[i] = snrTrueMin + dx*i;
y[i] = psFull(nsamp, snrMax, x[i]);
}
unsigned iMax;
Stats::max(y, iMax);
COUT("Max occurs at: " << x[iMax] << " for N = " << nsamp << " snrMax = " << snrMax << " bias = " << 100*fabs((snrMax - x[iMax])/snrMax) << " %");
std::ostringstream os;
os.str("");
// os << "S\\dmax\\u = " << snrMax;
PgUtil::linePlot(x, y, "S\\dtrue\\u", "p(S\\dtrue\\u| S\\dmax\\u)", os.str());
os.str("");
os << "N = " << nsamp;
double ymin = y[0];
#if 0
float ch;
cpgqch(&ch);
cpgsch(1.0);
PgUtil::text(os.str(), snrTrueMin, ymin-0.05, Angle(Angle::Degrees(), 0.0), PgUtil::JUST_LEFT);
cpgsch(ch);
#endif
return x[iMax];
}
double psFull(unsigned nsamp, double snrMax, double snrTrue)
{
double ynmax = Sampler::gaussPdf(snrMax, 0.0, 1.0);
double ysmax = Sampler::gaussPdf(snrMax, snrTrue, 1.0);
double ncdf = Sampler::gaussCdf(snrMax, 0.0, 1.0);
double scdf = Sampler::gaussCdf(snrMax, snrTrue, 1.0);
if(nsamp > 1) {
for(unsigned iSamp=0; iSamp < nsamp-1; iSamp++) {
ysmax *= ncdf;
}
}
if(nsamp > 1) {
ynmax *= scdf;
}
if(nsamp > 2) {
for(unsigned iSamp=0; iSamp < nsamp-2; iSamp++) {
ynmax *= ncdf;
}
}
return ysmax + (nsamp-1)*ynmax;
}
void makeRatioPlot(unsigned npt, double snrmin, double snrmax)
{
PgUtil::open("ratio.ps/cps");
// PgUtil::open("/xs");
// PgUtil::subplot(2,1);
makeRatioPlotSub(npt, snrmin, snrmax, 2.0);
PgUtil::close();
}
void makeRatioPlotSub(unsigned npt, double snrmin, double snrmax, double snrTrue)
{
double range = snrmax-snrmin;
PgUtil::setXmin(snrmin - 0.1*range);
PgUtil::setXmax(snrmax + 0.1*range);
PgUtil::setYmin(-1.0);
PgUtil::setYmax(4.5);
PgUtil::setUsedefs(true);
PgUtil::setCharacterHeight(2);
PgUtil::setOverplot(false);
PgUtil::setTraceColor(2);
PgUtil::setWin(true);
plotRatio(npt, 2, snrmin, snrmax, 2.0, false);
PgUtil::setOverplot(true);
PgUtil::setWin(false);
cpgsls(2);
plotRatio(npt, 2, snrmin, snrmax, 3.0, true);
cpgsls(1);
PgUtil::setTraceColor(1);
cpgsls(2);
cpgmove(0.0, 0);
cpgdraw(snrmax, 0.0);
cpgsls(1);
PgUtil::setOverplot(true);
PgUtil::setTraceColor(8);
PgUtil::setWin(false);
plotRatio(npt, 5, snrmin, snrmax, 2.0, false);
cpgsls(2);
plotRatio(npt, 5, snrmin, snrmax, 3.0, true);
cpgsls(1);
PgUtil::setOverplot(true);
PgUtil::setTraceColor(6);
PgUtil::setWin(false);
plotRatio(npt, 20, snrmin, snrmax, 2.0, false);
cpgsls(2);
plotRatio(npt, 20, snrmin, snrmax, 3.0, true);
cpgsls(1);
}
void makeFullPlot(std::string dev, unsigned npt, double snrMax, double snrMinTrue, double snrMaxTrue)
{
double range = snrMaxTrue-snrMinTrue;
PgUtil::setXmin(snrMinTrue - 0.1*range);
PgUtil::setXmax(snrMaxTrue + 0.1*range);
PgUtil::setYmin(-1.0);
PgUtil::setYmax(4.5);
PgUtil::setUsedefs(false);
PgUtil::open(dev);
PgUtil::setCharacterHeight(2);
PgUtil::setOverplot(false);
PgUtil::setTraceColor(6);
PgUtil::setWin(true);
plotPsFull(npt, 20, snrMax, snrMinTrue, snrMaxTrue);
PgUtil::setTraceColor(1);
PgUtil::setOverplot(true);
PgUtil::setTraceColor(8);
PgUtil::setWin(false);
plotPsFull(npt, 5, snrMax, snrMinTrue, snrMaxTrue);
PgUtil::setOverplot(true);
PgUtil::setTraceColor(2);
PgUtil::setWin(false);
plotPsFull(npt, 1, snrMax, snrMinTrue, snrMaxTrue);
PgUtil::close();
}
void makeMadcowsPlot(std::string dev, unsigned npt, double snrMinTrue, double snrMaxTrue)
{
COUT("Madcows");
double snrTrueRange = snrMaxTrue-snrMinTrue;
double snrMaxMin = 2.0;
double snrMaxMax = 3.0;
unsigned nCurve = 5;
double dSnrMax = (snrMaxMax - snrMaxMin)/(nCurve - 1);
PgUtil::setXmin(snrMinTrue - 0.1*snrTrueRange);
PgUtil::setXmax(snrMaxTrue + 0.1*snrTrueRange);
PgUtil::setYmin(0.0);
PgUtil::setYmax(0.6);
PgUtil::setUsedefs(true);
PgUtil::open(dev);
PgUtil::setCharacterHeight(2);
PgUtil::setOverplot(false);
PgUtil::setTraceColor(6);
PgUtil::setWin(true);
for(unsigned iCurve = 0; iCurve < nCurve; iCurve++) {
double snrMax = snrMaxMin + dSnrMax * iCurve;
plotPsFull(npt, 9, snrMax, snrMinTrue, snrMaxTrue);
PgUtil::setOverplot(true);
PgUtil::setTraceColor(6);
PgUtil::setWin(false);
}
cpgsch(1.0);
PgUtil::text("N = 9, S\\dmax\\u = 2-3", 4, 0.5);
PgUtil::close();
}
| [
"[email protected]"
] | |
a52a15998beb185a242b082ec4d8ab875e4f9f1d | 1d506a4d22a61f66de9019bf3795d10297ef9e4a | /HTTPServer/Sources/VHTTPWebsocketHandler.cpp | fdc6bf8ad4f4038792b0350975805c5750c99cd9 | [] | no_license | sanyaade-teachings/core-Components | b439c37bbe0e5d896645848d8db183e40f40b9e7 | a93d30e32da6f5fd58c76dfed430093746906ed1 | refs/heads/master | 2021-01-18T10:56:50.349393 | 2013-05-16T15:04:40 | 2013-05-16T15:04:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,635 | cpp | /*
* This file is part of Wakanda software, licensed by 4D under
* (i) the GNU General Public License version 3 (GNU GPL v3), or
* (ii) the Affero General Public License version 3 (AGPL v3) or
* (iii) a commercial license.
* This file remains the exclusive property of 4D and/or its licensors
* and is protected by national and international legislations.
* In any event, Licensee's compliance with the terms and conditions
* of the applicable license constitutes a prerequisite to any use of this file.
* Except as otherwise expressly stated in the applicable license,
* such license does not include any other license or rights on this file,
* 4D's and/or its licensors' trademarks and/or other proprietary rights.
* Consequently, no title, copyright or other proprietary rights
* other than those specified in the applicable license is granted.
*/
#include "HTTPServer.h"
#include "VHTTPWebsocketHandler.h"
const XBOX::VString K_UPGRADE("Upgrade");
const XBOX::VString K_WEBSOCKET("websocket");
const XBOX::VString K_WBSCK_KEY("Sec-WebSocket-Key");
const XBOX::VString K_WBSCK_VERS("Sec-WebSocket-Version");
const XBOX::VString K_WBSCK_ACCEPT("Sec-WebSocket-Accept");
const XBOX::VString K_WBSCK_EXT("Sec-WebSocket-Extensions");
const XBOX::VString K_CONNECTION("Connection:");
XBOX::VError IHTTPWebsocketHandler::ReadBytes(void* inData, XBOX::VSize& ioLength, bool inExactly)
{
XBOX::VError err;
if (!fEndpt)
{
xbox_assert((fEndpt != NULL));
return XBOX::VE_INVALID_PARAMETER;
}
if (ioLength < 0)
{
err = XBOX::VE_INVALID_PARAMETER;
}
else
{
uLONG length;
XBOX::StErrorContextInstaller errorContext( true /*we keep errors*/, true /*from now on, popups are forbidden*/);
length = ioLength;
err = fEndpt->Read(inData,&length);
if (err == XBOX::VE_SRVR_RESOURCE_TEMPORARILY_UNAVAILABLE)
{
if (length)
{
XBOX::DebugMsg("NON-NULL LENGTH SHOULD NOT HAPPEN!!!!!\n");
}
else
{
ioLength = 0;
err = XBOX::VE_OK;//'cos non blocking
}
}
else
{
if (!err)
{
// when exactly, the TIMEOUT_ERR is returned if the exact length is not get
if (inExactly && (length < ioLength))
{
uLONG exactLength;
exactLength = ioLength - length;
err = fEndpt->ReadExactly((char*)inData+length,exactLength,2000);
}
else
{
ioLength = length;
}
}
}
}
if (err)
{
XBOX::DebugMsg("ReadBytes ERR=%d\n",err);
XBOX::DebugMsg("ERRCODE_FROM_VERROR=%d\n",ERRCODE_FROM_VERROR(err));
XBOX::DebugMsg("NATIVE_ERRCODE_FROM_VERROR=%d\n",( (XBOX::VNativeError)(err & 0xFFFFFFFF) ));
//xbox_assert(!l_err);
}
return err;
}
#define K_WEBSOCKET_NB_MAX_TRIES (10)
XBOX::VError IHTTPWebsocketHandler::WriteBytes(const void* inData, XBOX::VSize inLength)
{
int nbTries;
sLONG len;
XBOX::VError err;
char* tmpData = (char*)inData;
err = XBOX::VE_OK;
nbTries = K_WEBSOCKET_NB_MAX_TRIES;
if (!fEndpt)
{
xbox_assert((fEndpt != NULL));
return XBOX::VE_INVALID_PARAMETER;
}
while(!err && inLength)
{
XBOX::StErrorContextInstaller errorContext( true /*we keep errors*/, true /*from now on, popups are forbidden*/);
len = ( inLength > 4096 ? 4096 : (sLONG)inLength );
//DebugMsg("WriteBytes trying to write %d bytes at %x\n",l_len,l_tmp);
err = fEndpt->Write(tmpData,(uLONG*)&len);
if (err == XBOX::VE_SRVR_RESOURCE_TEMPORARILY_UNAVAILABLE)
{
nbTries--;
if (!nbTries)
{
err = XBOX::VE_SRVR_WRITE_FAILED;
}
else
{
err = XBOX::VE_OK;
XBOX::VTask::Sleep(100);
continue;
}
}
if (!err)
{
nbTries = K_WEBSOCKET_NB_MAX_TRIES;
inLength -= len;
tmpData += len;
}
else
{
XBOX::DebugMsg("WriteBytes ERR=%d tries left%d\n",err,nbTries);
XBOX::DebugMsg("ERRCODE_FROM_VERROR=%d\n",ERRCODE_FROM_VERROR(err));
}
}
return err;
}
void IHTTPWebsocketHandler::CreateAcceptString(const XBOX::VString& key, XBOX::VString& outAcceptString)
{
XBOX::SHA1 sha1sum;
outAcceptString = key;
outAcceptString.AppendCString("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
XBOX::VStringConvertBuffer buffer( outAcceptString, XBOX::VTC_UTF_8);
XBOX::VChecksumSHA1::GetChecksumFromBytes(buffer.GetCPointer(),buffer.GetLength(),sha1sum);
XBOX::VChecksumSHA1::EncodeChecksumBase64(sha1sum,outAcceptString);
}
VHTTPWebsocketClientHandler::WsState VHTTPWebsocketClientHandler::GetState() const
{
return fState;
}
VHTTPWebsocketClientHandler::VHTTPWebsocketClientHandler()
{
fState = CLOSED_STATE;
fEndpt = NULL;
fBytesToRead = XBOX_LONG8(0);
fCurt = XBOX_LONG8(0);
fOutputIsTerminated = true;
}
VHTTPWebsocketClientHandler::~VHTTPWebsocketClientHandler()
{
testAssert(fEndpt == NULL);
fState = (WsState)-1;
}
XBOX::VError VHTTPWebsocketClientHandler::SendHandshake(const VString& inHost, const VString& inPath)
{
XBOX::VError err = VE_OK;
VString message("GET ");
message += inPath;
message += CVSTR(" HTTP/1.1\r\n");
message += K_UPGRADE;
message += CVSTR(": ");
message += K_WEBSOCKET;
message += "\r\n";
message += "Connection: Upgrade\r\n";
message += "Host: ";
message += inHost;
message += "\r\n";
message += K_WBSCK_KEY;
message += ": ";
message += fKey;
message += "\r\n";
message += K_WBSCK_VERS;
message += ": 13\r\n\r\n";
VStringConvertBuffer buffer( message, VTC_UTF_8);
uLONG len = (sLONG)buffer.GetLength();
err = fEndpt->WriteWithTimeout((void*)buffer.GetCPointer(),&len,1000);
return err;
}
XBOX::VError VHTTPWebsocketClientHandler::TreatHandshakeResponse(sLONG& ioLen)
{
XBOX::VError err = VE_INVALID_PARAMETER;
bool upgradeToWS = false;
bool connectionUpgrade = false;
bool acceptOK = false;
sBYTE *inData = fInBuffer;
const sBYTE K_HTTP_EOL[2] = { '\r','\n' };
for( int idx=0; idx<ioLen; idx++ )
{
if (!memcmp(inData+idx,K_HTTP_EOL,2))
{
inData[idx] = 0;
if (strstr(inData,"HTTP") && strstr(inData,"101"))
{
err = VE_OK;
}
ioLen -= (idx + 2);
inData += idx + 2;
break;
}
}
while( (ioLen > 0) && !err )
{
if (!memcmp(inData,K_HTTP_EOL,2))
{
ioLen -= 2;
inData += 2;
break;
}
for( int idx=0; idx<ioLen; idx++ )
{
if (!memcmp(inData+idx,K_HTTP_EOL,2))
{
inData[idx] = 0;
VString curtLine((const char*)inData);
ioLen -= (idx + 2);
VIndex upgradeIndex = curtLine.Find(K_UPGRADE);
if ( upgradeIndex == 1 )
{
upgradeToWS = curtLine.Find(K_WEBSOCKET,upgradeIndex+1) > 0;
}
VIndex connectionIndex = curtLine.Find(K_CONNECTION);
if ( connectionIndex == 1 )
{
connectionUpgrade = curtLine.Find(K_UPGRADE,connectionIndex+1) > 0;
}
VIndex acceptIndex = curtLine.Find(K_WBSCK_ACCEPT);
if ( acceptIndex == 1 )
{
VIndex acceptKeyLen = curtLine.GetLength() - K_WBSCK_ACCEPT.GetLength() - 2;
VString acceptKey;
curtLine.GetSubString( K_WBSCK_ACCEPT.GetLength() + 3, acceptKeyLen, acceptKey);
VString awaitedAcceptKey;
CreateAcceptString(fKey,awaitedAcceptKey);
//DebugMsg("VHTTPWebsocketClientHandler::TreatHandshakeResponse '%S' vs '%S'\n",&awaitedAcceptKey,&acceptKey);
acceptOK = ( awaitedAcceptKey.CompareToString(acceptKey,true) == CR_EQUAL );
}
inData += idx + 2;
break;
}
}
}
if (!connectionUpgrade || !upgradeToWS || !acceptOK)
{
err = VE_INVALID_PARAMETER;
}
return err;
}
const char K_BASE64_ARRAY[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
XBOX::VError VHTTPWebsocketClientHandler::CreateKey()
{
fKey = CVSTR("");
for( int idx=0; idx<11; idx++ )
{
sLONG rnd = VSystem::Random();
fKey += K_BASE64_ARRAY[rnd % 64];
rnd = (rnd / 64) % 64;
fKey += K_BASE64_ARRAY[rnd];
}
fKey += "==";
//fKey = "M/1qGPeVFygnm55eBj8YZA==";
return VE_OK;
}
XBOX::VError VHTTPWebsocketClientHandler::ConnectToServer(const XBOX::VURL& inUrl)
{
XBOX::VError err = VE_OK;
VString tmpStr;
VString host;
VString params;
VString query;
sLONG portNumber;
if (!testAssert(fState == CLOSED_STATE))
{
return VE_INVALID_PARAMETER;
}
inUrl.GetScheme(tmpStr);
if (!tmpStr.EqualToString(CVSTR("ws"),true))
{
err = VE_INVALID_PARAMETER;
}
if (!err)
{
inUrl.GetPortNumber( tmpStr, false );
portNumber = tmpStr.GetLong();
if (!portNumber)
{
portNumber = 80;
}
inUrl.GetRelativeURL(tmpStr,false);
inUrl.GetHostName( host, false );
inUrl.GetPath( tmpStr );
inUrl.GetRelativePath( tmpStr );
inUrl.GetParameters( params, false );
inUrl.GetQuery( query, false );
}
if (!err)
{
fState = CONNECTING_STATE;
XBOX::XTCPSock* tcpSck = XTCPSock::NewClientConnectedSock(host,portNumber,1000);
params += "?";
params += query;
tmpStr = "/";
tmpStr += params;
err = ConnectToServer(tcpSck,host,tmpStr);
}
if (err)
{
if (fEndpt)
{
Close();
}
fState = CLOSED_STATE;
}
else
{
fState = OPENED_STATE;
}
return err;
}
XBOX::VError VHTTPWebsocketClientHandler::ConnectToServer(XBOX::XTCPSock* inTcpSck, const VString& inHost, const VString& inData)
{
XBOX::VError err = VE_INVALID_PARAMETER;
if (inTcpSck)
{
fEndpt = new VTCPEndPoint(inTcpSck);
fEndpt->SetIsBlocking(true);
err = CreateKey();
if (!err)
{
err = SendHandshake(inHost,inData);
}
if (testAssert(err == VE_OK))
{
sLONG len = K_WEBSOCKET_HANDLER_MAX_SIZE;
err = fEndpt->Read((void*)fInBuffer,(uLONG*)&len);
if (testAssert(err == VE_OK))
{
err = TreatHandshakeResponse(len);
if (testAssert(err == VE_OK))
{
if (len > 0)
{
xbox_assert(false);
}
}
}
}
}
return err;
}
XBOX::VError VHTTPWebsocketClientHandler::ReadHeader(bool& outFound)
{
VError err;
memset(&fReadFrame,0,sizeof(ws_frame_t));
outFound = false;
fReadFrame.buf_len = 2;
// see if there's frame start
err = ReadBytes((void *)fReadFrame.header, fReadFrame.buf_len, true);
if (!err && fReadFrame.buf_len)
{
// extensions not handled
if (fReadFrame.header[0] & 0x70)
{
DebugMsg("VHTTPWebsocketClientHandler::ReadHeader RFC6455 EXTENSIONS NOT HANDLED!!!!\n");
err = VE_INVALID_PARAMETER;
}
if (!err)
{
fReadFrame.opcode = (ws_opcode_t)(fReadFrame.header[0] & 0x0F);
fReadFrame.masked = (fReadFrame.header[1] & 0x80);
if (testAssert(fReadFrame.masked == 0))
{
fReadFrame.len = (sLONG8)(fReadFrame.header[1] & 0x7F);
if (fReadFrame.len == 127)
{
fReadFrame.buf_len = 8;
err = ReadBytes((void *)(fReadFrame.header+2), fReadFrame.buf_len, true);
if ( err || !fReadFrame.buf_len)
{
err = VE_STREAM_CANNOT_READ;
}
if (!err)
{
fReadFrame.len = 0;
for(int l_i=0;l_i<8;l_i+=2)
{
fReadFrame.len = 65536*fReadFrame.len + (256*fReadFrame.header[2+l_i]+fReadFrame.header[3+l_i]);
}
DebugMsg("ReadHeader frame.len1=%lld, msk=%d\n",fReadFrame.len,fReadFrame.masked);
}
}
else
{
if (fReadFrame.len == 126)
{
fReadFrame.buf_len = 2;
err = ReadBytes((void *)(fReadFrame.header+2), fReadFrame.buf_len, true);
if ( err || !fReadFrame.buf_len)
{
err = VE_STREAM_CANNOT_READ;
}
if (!err)
{
fReadFrame.len = 256*fReadFrame.header[2]+fReadFrame.header[3];
DebugMsg("ReadHeader frame.len2=%d, msk=%d\n",fReadFrame.len,fReadFrame.masked);
}
}
else
{
DebugMsg("ReadHeader frame.len3=%d, msk=%d\n",fReadFrame.len,fReadFrame.masked);
}
}
}
else
{
DebugMsg("VHTTPWebsocketClientHandler::ReadHeader header shoud not be masked!!!!\n");
err = VE_INVALID_PARAMETER;
}
if (!err)
{
outFound = true;
}
}
}
return err;
}
XBOX::VError VHTTPWebsocketClientHandler::ReadMessage( void* inData, VSize& ioLength, bool& outIsTerminated )
{
bool headerFound;
VError err;
if (!testAssert(fState == OPENED_STATE))
{
return VE_INVALID_PARAMETER;
}
if (ioLength < 0)
{
return VE_INVALID_PARAMETER;
}
if (fEndpt == NULL)
{
return VE_INVALID_PARAMETER;
}
err = VE_OK;
if (!fBytesToRead)
{
err = ReadHeader(headerFound);
if (err)
{
DebugMsg("ERR2\n");
}
if (!err && !headerFound)
{
ioLength = 0;
}
// not fragmented ?
if (!err && ioLength && (fReadFrame.header[0] & 0x80))
{
fBytesToRead = fReadFrame.len;
fCurt = XBOX_LONG8(0);
switch(fReadFrame.opcode)
{
case CONTINUATION_FRAME:
DebugMsg("ERR3\n");
err = VE_UNIMPLEMENTED;
break;
case CONNEXION_CLOSE:
if (fReadFrame.len >= 126)
{
DebugMsg("ERR4\n");
err = VE_INVALID_PARAMETER;
}
else
{
err = VE_STREAM_EOF;
}
break;
case TEXT_FRAME:
case BIN_FRAME:
break;
default:
break;
}
}
else
{
if (!err && ioLength )
{
DebugMsg("Fragmentation not handled ERR6\n");
err = VE_INVALID_PARAMETER;
}
}
}
//DebugMsg("ReadMessage req_len=%d ToRead=%lld\n",*ioLength,fBytesToRead);
if (!err && fBytesToRead)
{
//printf("...... bef ReadMessage req_len=%d ToRead=%lld\n",*ioLength,fBytesToRead);
ioLength = ( ioLength >= fBytesToRead ? ((VSize)fBytesToRead) : ioLength);
//printf("...... aft ReadMessage req_len=%d ToRead=%lld\n",*ioLength,fBytesToRead);
err = ReadBytes(inData,ioLength,true);
if (err)
{
DebugMsg("ERR1\n");
}
else
{
fBytesToRead -= ioLength;
//printf("...... ....... aft ReadMessage read_len=%d ToRead=%lld\n",*ioLength,fBytesToRead);
/*if (fFrame.masked)
{
for(VSize l_i=0; l_i<*ioLength; l_i++)
{
((unsigned char *)inData)[l_i] ^= fFrame.msk[fCurt % 4];
fCurt++;
}
}*/
outIsTerminated = !(fBytesToRead);
}
}
if (err)
{
/*fEndpt = NULL;*/
Close();
}
return err;
}
XBOX::VError VHTTPWebsocketClientHandler::WriteHeader(VSize inLength)
{
VError err;
memset(&fFrame,0,sizeof(ws_frame_t));
fFrame.buf_len = 2;
if (fOutputIsTerminated)
{
fFrame.header[0] = 0x81;
}
else
{
fFrame.header[0] = 0x01;
}
if (inLength <= 125)
{
fFrame.header[1] = inLength;
fFrame.buf_len = 2;
}
else
{
if (inLength < 65536)
{
fFrame.header[1] = 126;
fFrame.header[2] = inLength / 256;
fFrame.header[3] = inLength % 256;
fFrame.buf_len = 4;
}
else
{
fFrame.header[1] = 127;
fFrame.buf_len = 10;
xbox_assert(false);
// TBC GH
}
}
//set mask indicator
fFrame.header[1] |= 0x80;
memcpy( fFrame.header+fFrame.buf_len, fMask, 4);
fFrame.buf_len += 4;
err = WriteBytes((void *)fFrame.header, fFrame.buf_len);
return err;
}
XBOX::VError VHTTPWebsocketClientHandler::WriteMessage( const void* inData, VSize inLength, bool inIsTerminated )
{
XBOX::VError err;
if (!testAssert(fState == OPENED_STATE))
{
return VE_INVALID_PARAMETER;
}
if (inLength < 0)
{
return VE_INVALID_PARAMETER;
}
if (fEndpt == NULL)
{
return VE_INVALID_PARAMETER;
}
err = VE_OK;
sLONG randomMask = VSystem::Random();
memcpy( fMask, &randomMask, 4 );
fOutputIsTerminated = inIsTerminated;
{
err = WriteHeader(inLength);
if (err)
{
DebugMsg("VHTTPWebsocketClientHandler::WriteHeader ERR2\n");
}
else
{
// mask bytes before sending
sLONG nbLoops;
VIndex curtIdx;
curtIdx = 0;
nbLoops = inLength / K_WEBSOCKET_HANDLER_MAX_SIZE;
while( !err && nbLoops )
{
for(VSize idx=0; idx<K_WEBSOCKET_HANDLER_MAX_SIZE; idx++)
{
fOutBuffer[idx] = ((unsigned char *)inData)[curtIdx] ^ fMask[curtIdx % 4];
curtIdx++;
}
err = WriteBytes( fOutBuffer, K_WEBSOCKET_HANDLER_MAX_SIZE);
nbLoops--;
}
if (!err)
{
VIndex remainder = inLength % K_WEBSOCKET_HANDLER_MAX_SIZE;
for(VSize idx=0; idx<remainder; idx++)
{
fOutBuffer[idx] = ((unsigned char *)inData)[curtIdx] ^ fMask[curtIdx % 4];
curtIdx++;
}
err = WriteBytes( fOutBuffer, remainder);
}
}
}
if (err)
{
Close();
}
return err;
}
XBOX::VError VHTTPWebsocketClientHandler::Close()
{
if (!fEndpt)
{
return VE_INVALID_PARAMETER;
}
fEndpt->Close();
fState = CLOSED_STATE;
ReleaseRefCountable(&fEndpt);
}
VHTTPWebsocketServerHandler::VHTTPWebsocketServerHandler()
{
//_IsClosed = true;
fEndpt = NULL;
//_ReadInProgress = false;
fBytesToRead = XBOX_LONG8(0);
fCurt = XBOX_LONG8(0);
fOutputIsTerminated = true;
fState = CLOSED_STATE;
}
VHTTPWebsocketServerHandler::~VHTTPWebsocketServerHandler()
{
testAssert(fEndpt == NULL);
fState = (WsState)-1;
}
VHTTPWebsocketServerHandler::WsState VHTTPWebsocketServerHandler::GetState() const
{
return fState;
}
XBOX::VError VHTTPWebsocketServerHandler::ValidateHeader(const XBOX::VHTTPHeader& hdr,XBOX::VString & outKey)
{
XBOX::VError l_err;
XBOX::VString l_hdrstr;
XBOX::VString l_tmp;
l_err = VE_OK;
hdr.ToString(l_hdrstr);
if ( !hdr.GetHeaderValue(K_UPGRADE,l_tmp) || !l_tmp.EqualToString(K_WEBSOCKET,true) )
{
l_err = VE_INVALID_PARAMETER;
}
if ( !l_err && ( !hdr.GetHeaderValue(HEADER_CONNECTION,l_tmp) || (l_tmp.Find(K_UPGRADE) < 1 ) ) )
{
l_err = VE_INVALID_PARAMETER;
}
if ( !l_err && ( !hdr.GetHeaderValue(K_WBSCK_VERS,l_tmp) || (l_tmp.GetWord() < 13) ) )
{
l_err = VE_INVALID_PARAMETER;
}
if ( !l_err && !hdr.GetHeaderValue(K_WBSCK_KEY,outKey) )
{
l_err = VE_INVALID_PARAMETER;
}
return l_err;
}
#define K_ACCEPT_MAX_LEN (256)
XBOX::VError VHTTPWebsocketServerHandler::SendHandshake(IHTTPResponse* resp,const XBOX::VString & key)
{
XBOX::VError err;
//XBOX::SHA1 sha1sum;
XBOX::VString acceptStr; //ex (from rfc6455)"dGhlIHNhbXBsZSBub25jZQ==");
err = VE_OK;
/*acceptStr.AppendCString("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
VStringConvertBuffer buffer( acceptStr, VTC_UTF_8);
VChecksumSHA1::GetChecksumFromBytes(buffer.GetCPointer(),buffer.GetLength(),sha1sum);
VChecksumSHA1::EncodeChecksumBase64(sha1sum,acceptStr);*/
CreateAcceptString(key,acceptStr);
resp->SetResponseStatusCode(HTTP_SWITCHING_PROTOCOLS);
if (!resp->AddResponseHeader(HEADER_CONNECTION,K_UPGRADE))
{
err = VE_STREAM_CANNOT_WRITE;
}
if (!err && !resp->AddResponseHeader(K_UPGRADE,K_WEBSOCKET))
{
err = VE_STREAM_CANNOT_WRITE;
}
if (!err && !resp->AddResponseHeader(K_WBSCK_ACCEPT,acceptStr))
{
err = VE_STREAM_CANNOT_WRITE;
}
resp->AllowCompression(false);
if (!err)
{
err = resp->SendResponseHeader();
}
return err;
}
XBOX::VError VHTTPWebsocketServerHandler::ReadHeader(bool& found)
{
VError err;
memset(&fFrame,0,sizeof(ws_frame_t));
found = false;
fFrame.buf_len = 2;
// see if there's frame start
err = ReadBytes((void *)fFrame.header, fFrame.buf_len, true);
if (!err && fFrame.buf_len)
{
// extensions not handled
if (fFrame.header[0] & 0x70)
{
DebugMsg("VHTTPWebsocketServerHandler::ReadHeader RFC6455 EXTENSIONS NOT HANDLED!!!!\n");
err = VE_INVALID_PARAMETER;
}
if (!err)
{
fFrame.opcode = (ws_opcode_t)(fFrame.header[0] & 0x0F);
fFrame.masked = (fFrame.header[1] & 0x80);
fFrame.len = (sLONG8)(fFrame.header[1] & 0x7F);
if (fFrame.len == 127)
{
fFrame.buf_len = 8;
err = ReadBytes((void *)(fFrame.header+2), fFrame.buf_len, true);
if ( err || !fFrame.buf_len)
{
err = VE_STREAM_CANNOT_READ;
}
if (!err)
{
fFrame.len = 0;
for(int l_i=0;l_i<8;l_i+=2)
{
fFrame.len = 65536*fFrame.len + (256*fFrame.header[2+l_i]+fFrame.header[3+l_i]);
}
DebugMsg("ReadHeader frame.len1=%lld, msk=%d\n",fFrame.len,fFrame.masked);
}
}
else
{
if (fFrame.len == 126)
{
fFrame.buf_len = 2;
err = ReadBytes((void *)(fFrame.header+2), fFrame.buf_len, true);
if ( err || !fFrame.buf_len)
{
err = VE_STREAM_CANNOT_READ;
}
if (!err)
{
fFrame.len = 256*fFrame.header[2]+fFrame.header[3];
DebugMsg("ReadHeader frame.len2=%d, msk=%d\n",fFrame.len,fFrame.masked);
}
}
else
{
DebugMsg("ReadHeader frame.len3=%d, msk=%d\n",fFrame.len,fFrame.masked);
}
}
if (!err && fFrame.masked)
{
fFrame.buf_len = 4;
err = ReadBytes((void *)fFrame.msk, fFrame.buf_len, true);
if ( err || !fFrame.buf_len)
{
err = VE_STREAM_CANNOT_READ;
}
}
found = true;
}
}
return err;
}
XBOX::VError VHTTPWebsocketServerHandler::ReadMessage( void* inData, VSize& ioLength, bool& outIsTerminated )
{
bool headerFound;
VError err;
if (ioLength < 0)
{
return VE_INVALID_PARAMETER;
}
if (fEndpt == NULL)
{
return VE_INVALID_PARAMETER;
}
err = VE_OK;
if (!fBytesToRead)
{
err = ReadHeader(headerFound);
if (err)
{
DebugMsg("ERR2\n");
}
if (!err && !headerFound)
{
ioLength = 0;
}
// not fragmented ?
if (!err && (ioLength) && (fFrame.header[0] & 0x80))
{
fBytesToRead = fFrame.len;
fCurt = XBOX_LONG8(0);
switch(fFrame.opcode)
{
case CONTINUATION_FRAME:
DebugMsg("ERR3\n");
err = VE_UNIMPLEMENTED;
break;
case CONNEXION_CLOSE:
if (fFrame.len >= 126)
{
DebugMsg("ERR4\n");
err = VE_INVALID_PARAMETER;
}
else
{
err = VE_STREAM_EOF;
}
break;
case TEXT_FRAME:
case BIN_FRAME:
break;
default:
break;
}
}
else
{
if (!err && ioLength )
{
DebugMsg("Fragmentation not handled ERR6\n");
err = VE_INVALID_PARAMETER;
}
}
}
//DebugMsg("ReadMessage req_len=%d ToRead=%lld\n",*ioLength,fBytesToRead);
if (!err && fBytesToRead)
{
//printf("...... bef ReadMessage req_len=%d ToRead=%lld\n",*ioLength,fBytesToRead);
ioLength = ( ioLength >= fBytesToRead ? ((VSize)fBytesToRead) : ioLength);
//printf("...... aft ReadMessage req_len=%d ToRead=%lld\n",*ioLength,fBytesToRead);
err = ReadBytes(inData,ioLength);
if (err)
{
DebugMsg("ERR1\n");
}
else
{
fBytesToRead -= ioLength;
//printf("...... ....... aft ReadMessage read_len=%d ToRead=%lld\n",*ioLength,fBytesToRead);
if (fFrame.masked)
{
for(VSize l_i=0; l_i<ioLength; l_i++)
{
((unsigned char *)inData)[l_i] ^= fFrame.msk[fCurt % 4];
fCurt++;
}
}
outIsTerminated = !(fBytesToRead);
}
}
if (err)
{
Close();
}
return err;
}
XBOX::VError VHTTPWebsocketServerHandler::WriteMessage( const void* inData, VSize inLength, bool inIsTerminated )
{
XBOX::VError err;
unsigned char header[10];
if (fEndpt == NULL)
{
return VE_INVALID_PARAMETER;
}
err = VE_OK;
if (fOutputIsTerminated)
{
fOutputIsTerminated = inIsTerminated;
if (inIsTerminated)
{
header[0] = 0x81;
}
else
{
header[0] = 0x01;
}
}
else
{
fOutputIsTerminated = inIsTerminated;
header[0] = (inIsTerminated ? 0x80 : 0x00 );
}
err = ( inLength >= 0 ? VE_OK : VE_INVALID_PARAMETER);
testAssert( err == VE_OK );
//SEND_COMPLETE_FRAME:
if (!err)
{
if (inLength <= 125)
{
header[1] = (unsigned char)inLength;
err = WriteBytes(header,2);
if (err)
{
DebugMsg("WriteBytes ERR\n");
}
}
else
{
if (inLength < 65536)
{
header[1] = 126;
header[2] = inLength / 256;
header[3] = inLength % 256;
err = WriteBytes(header,4);
if (err)
{
DebugMsg("Write3 ERR\n");
}
}
else
{
DebugMsg("WriteMessage ERR\n");
err = VE_INVALID_PARAMETER;
}
}
//SEND_ALL_DATA:
if (!err)
{
err = WriteBytes(inData,inLength);
if (err)
{
DebugMsg("WriteBytes ERR\n");
}
}
}
if (err)
{
/*fEndpt = NULL;*/
Close();
}
return err;
}
XBOX::VError VHTTPWebsocketServerHandler::Close()
{
if (!fEndpt)
{
return VE_INVALID_PARAMETER;
}
fEndpt->Close();
fEndpt = NULL;
return VE_OK;
}
XBOX::VError VHTTPWebsocketServerHandler::TreatNewConnection( IHTTPResponse* inResponse)
{
XBOX::VString l_key;
VError l_err;
if (!testAssert(fEndpt == NULL))
{
DebugMsg("TreatNewConnection previous connection still active\n");
return VE_INVALID_PARAMETER;
}
l_err = VE_OK;
if (inResponse->GetRequestHTTPVersion() != VERSION_1_1)
{
DebugMsg("Version HTTP 1.1 required for websockets\n");
l_err = VE_INVALID_PARAMETER;
}
if (!l_err && (inResponse->GetRequestMethod() != HTTP_GET))
{
l_err = VE_INVALID_PARAMETER;
}
const XBOX::VHTTPHeader &l_rqst_hdr = inResponse->GetRequestHeader();
if (!l_err)
{
l_err = ValidateHeader(l_rqst_hdr,l_key);
}
if (!l_err)
{
l_err = SendHandshake(inResponse,l_key);
}
if (!l_err)
{
fEndpt = inResponse->GetEndPoint();
if (!fEndpt)
{
DebugMsg("TreatNewConnection invalid ENDPOINT\n");
l_err = VE_INVALID_PARAMETER;
}
else
{
// make socket non-blocking for the moment (the user should POLL by using ReadMessage)
fEndpt->SetIsBlocking(false);
fCurt = XBOX_LONG8(0);
fOutputIsTerminated = true;
}
}
if (l_err)
{
inResponse->ReplyWithStatusCode( HTTP_BAD_REQUEST);
}
return l_err;
}
| [
"[email protected]"
] | |
044288fd94c6007420c4f7797fdb7977898c5744 | a386d4c4dcec9fc39cedc3d820b5cdee0b0aa6b7 | /src/shared/opl3/opl3_operator.h | a0d581e59e0f09a8c8b2181a00fe33dadbf7a2fb | [
"MIT"
] | permissive | francescosacco/tinyXT | 0e5a2e41affad813dfcbac651b18382c799570ce | d0beb4d5d3c8ad37bc0de0d89cbe522a4deb0aa5 | refs/heads/master | 2021-03-04T21:15:58.800056 | 2018-02-13T19:51:08 | 2017-12-27T19:52:11 | 108,322,541 | 14 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 11,417 | h |
#include "opl3_envelope_gen.h"
//
// Phase Generator
//
class OPL3_PhaseGenerator_t
{
public:
double phase, phaseIncrement;
OPL3_PhaseGenerator_t()
{
phase = phaseIncrement = 0;
}
inline void setFrequency(int f_number, int block, int mult)
{
// This frequency formula is derived from the following equation:
// f_number = baseFrequency * pow(2,19) / sampleRate / pow(2,block-1);
double baseFrequency =
f_number * pow(2, block-1) * OPL3Data::sampleRate / pow(2, 19);
double operatorFrequency = baseFrequency * OperatorData::multTable[mult];
// phase goes from 0 to 1 at
// period = (1/frequency) seconds ->
// Samples in each period is (1/frequency)*sampleRate =
// = sampleRate/frequency ->
// So the increment in each sample, to go from 0 to 1, is:
// increment = (1-0) / samples in the period ->
// increment = 1 / (OPL3Data.sampleRate/operatorFrequency) ->
phaseIncrement = operatorFrequency / OPL3Data::sampleRate;
}
inline double getPhase(int vib)
{
if (vib == 1)
{
// phaseIncrement = (operatorFrequency * vibrato) / sampleRate
phase += phaseIncrement * OPL3Data::vibratoTable[OPL3.dvb][OPL3.vibratoIndex];
}
else
{
// phaseIncrement = operatorFrequency / sampleRate
phase += phaseIncrement;
}
phase -= floor(phase);
return phase;
}
inline void keyOn(void)
{
phase = 0.0;
}
};
class OPL3_Operator_t
{
OPL3_PhaseGenerator_t phaseGenerator;
OPL3_EnvelopeGenerator_t envelopeGenerator;
double envelope, phase;
int operatorBaseAddress;
int am, vib, ksr, egt, mult, ksl, tl, ar, dr, sl, rr, ws;
int keyScaleNumber, f_number, block;
const double noModulator = 0.0;
OPL3_Operator_t(int baseAddress)
{
operatorBaseAddress = baseAddress;
envelope = 0;
am = vib = ksr = egt = mult = ksl = tl = ar = dr = sl = rr = ws = 0;
keyScaleNumber = f_number = block = 0;
}
inline void update_AM1_VIB1_EGT1_KSR1_MULT4(void)
{
int am1_vib1_egt1_ksr1_mult4 = OPL3.registers[operatorBaseAddress + OperatorData::AM1_VIB1_EGT1_KSR1_MULT4_Offset];
// Amplitude Modulation. This register is used int EnvelopeGenerator.getEnvelope();
am = (am1_vib1_egt1_ksr1_mult4 & 0x80) >> 7;
// Vibrato. This register is used in PhaseGenerator.getPhase();
vib = (am1_vib1_egt1_ksr1_mult4 & 0x40) >> 6;
// Envelope Generator Type. This register is used in EnvelopeGenerator.getEnvelope();
egt = (am1_vib1_egt1_ksr1_mult4 & 0x20) >> 5;
// Key Scale Rate. Sets the actual envelope rate together with rate and keyScaleNumber.
// This register os used in EnvelopeGenerator.setActualAttackRate().
ksr = (am1_vib1_egt1_ksr1_mult4 & 0x10) >> 4;
// Multiple. Multiplies the Channel.baseFrequency to get the Operator.operatorFrequency.
// This register is used in PhaseGenerator.setFrequency().
mult = am1_vib1_egt1_ksr1_mult4 & 0x0F;
phaseGenerator.setFrequency(f_number, block, mult);
envelopeGenerator.setActualAttackRate(ar, ksr, keyScaleNumber);
envelopeGenerator.setActualDecayRate(dr, ksr, keyScaleNumber);
envelopeGenerator.setActualReleaseRate(rr, ksr, keyScaleNumber);
}
inline void update_KSL2_TL6(void)
{
int ksl2_tl6 = OPL3.registers[operatorBaseAddress + OperatorData::KSL2_TL6_Offset];
// Key Scale Level. Sets the attenuation in accordance with the octave.
ksl = (ksl2_tl6 & 0xC0) >> 6;
// Total Level. Sets the overall damping for the envelope.
tl = ksl2_tl6 & 0x3F;
envelopeGenerator.setAtennuation(f_number, block, ksl);
envelopeGenerator.setTotalLevel(tl);
}
inline void update_AR4_DR4()
{
int ar4_dr4 = OPL3.registers[operatorBaseAddress+OperatorData.AR4_DR4_Offset];
// Attack Rate.
ar = (ar4_dr4 & 0xF0) >> 4;
// Decay Rate.
dr = ar4_dr4 & 0x0F;
envelopeGenerator.setActualAttackRate(ar, ksr, keyScaleNumber);
envelopeGenerator.setActualDecayRate(dr, ksr, keyScaleNumber);
}
inline void update_SL4_RR4()
{
int sl4_rr4 = OPL3.registers[operatorBaseAddress+OperatorData.SL4_RR4_Offset];
// Sustain Level.
sl = (sl4_rr4 & 0xF0) >> 4;
// Release Rate.
rr = sl4_rr4 & 0x0F;
envelopeGenerator.setActualSustainLevel(sl);
envelopeGenerator.setActualReleaseRate(rr, ksr, keyScaleNumber);
}
inline void update_5_WS3()
{
int _5_ws3 = OPL3.registers[operatorBaseAddress+OperatorData._5_WS3_Offset];
ws = _5_ws3 & 0x07;
}
inline double getOperatorOutput(double modulator)
{
if(envelopeGenerator.stage == EnvelopeGenerator.Stage.OFF) return 0;
double envelopeInDB = envelopeGenerator.getEnvelope(egt, am);
envelope = Math.pow(10, envelopeInDB/10.0);
// If it is in OPL2 mode, use first four waveforms only:
ws &= ((OPL3._new<<2) + 3);
double[] waveform = OperatorData.waveforms[ws];
phase = phaseGenerator.getPhase(vib);
double operatorOutput = getOutput(modulator, phase, waveform);
return operatorOutput;
}
protected:
inline double getOutput(double modulator, double outputPhase, double *waveform)
{
outputPhase = (outputPhase + modulator) % 1;
if (outputPhase < 0)
{
outputPhase++;
// If the double could not afford to be less than 1:
outputPhase %= 1;
}
int sampleIndex = (int) (outputPhase * OperatorData.waveLength);
return waveform[sampleIndex] * envelope;
}
inline void keyOn(void)
{
if (ar > 0)
{
envelopeGenerator.keyOn();
phaseGenerator.keyOn();
}
else
{
envelopeGenerator.stage = EnvelopeGenerator.Stage.OFF;
}
}
inline void keyOff(void)
{
envelopeGenerator.keyOff();
}
inline void updateOperator(int ksn, int f_num, int blk)
{
keyScaleNumber = ksn;
f_number = f_num;
block = blk;
update_AM1_VIB1_EGT1_KSR1_MULT4();
update_KSL2_TL6();
update_AR4_DR4();
update_SL4_RR4();
update_5_WS3();
}
}
//
// Rhythm
//
// The getOperatorOutput() method in TopCymbalOperator, HighHatOperator and SnareDrumOperator
// were made through purely empyrical reverse engineering of the OPL3 output.
class OPL3_RhythmChannel_t :public OPL3_Channel2op_t
{
public:
RhythmChannel(int baseAddress, Operator o1, Operator o2) {
super(baseAddress, o1, o2);
}
double[] getChannelOutput() {
double channelOutput = 0, op1Output = 0, op2Output = 0;
double[] output;
// Note that, different from the common channel,
// we do not check to see if the Operator's envelopes are Off.
// Instead, we always do the calculations,
// to update the publicly available phase.
op1Output = op1.getOperatorOutput(Operator.noModulator);
op2Output = op2.getOperatorOutput(Operator.noModulator);
channelOutput = (op1Output + op2Output) / 2;
output = getInFourChannels(channelOutput);
return output;
};
// Rhythm channels are always running,
// only the envelope is activated by the user.
protected void keyOn() { };
protected void keyOff() { };
}
class HighHatSnareDrumChannel extends RhythmChannel {
final static int highHatSnareDrumChannelBaseAddress = 7;
HighHatSnareDrumChannel() {
super(highHatSnareDrumChannelBaseAddress,
OPL3.highHatOperator,
OPL3.snareDrumOperator);
}
}
class TomTomTopCymbalChannel extends RhythmChannel {
final static int tomTomTopCymbalChannelBaseAddress = 8;
TomTomTopCymbalChannel() {
super(tomTomTopCymbalChannelBaseAddress,
OPL3.tomTomOperator,
OPL3.topCymbalOperator);
}
}
class TopCymbalOperator extends Operator {
final static int topCymbalOperatorBaseAddress = 0x15;
TopCymbalOperator(int baseAddress) {
super(baseAddress);
}
TopCymbalOperator() {
this(topCymbalOperatorBaseAddress);
}
double getOperatorOutput(double modulator) {
double highHatOperatorPhase =
OPL3.highHatOperator.phase * OperatorData.multTable[OPL3.highHatOperator.mult];
// The Top Cymbal operator uses his own phase together with the High Hat phase.
return getOperatorOutput(modulator, highHatOperatorPhase);
}
// This method is used here with the HighHatOperator phase
// as the externalPhase.
// Conversely, this method is also used through inheritance by the HighHatOperator,
// now with the TopCymbalOperator phase as the externalPhase.
protected double getOperatorOutput(double modulator, double externalPhase) {
double envelopeInDB = envelopeGenerator.getEnvelope(egt, am);
envelope = Math.pow(10, envelopeInDB/10.0);
phase = phaseGenerator.getPhase(vib);
int waveIndex = ws & ((OPL3._new<<2) + 3);
double[] waveform = OperatorData.waveforms[waveIndex];
// Empirically tested multiplied phase for the Top Cymbal:
double carrierPhase = (8 * phase)%1;
double modulatorPhase = externalPhase;
double modulatorOutput = getOutput(Operator.noModulator,modulatorPhase, waveform);
double carrierOutput = getOutput(modulatorOutput,carrierPhase, waveform);
int cycles = 4;
if( (carrierPhase*cycles)%cycles > 0.1) carrierOutput = 0;
return carrierOutput*2;
}
}
class HighHatOperator extends TopCymbalOperator {
final static int highHatOperatorBaseAddress = 0x11;
HighHatOperator() {
super(highHatOperatorBaseAddress);
}
double getOperatorOutput(double modulator) {
double topCymbalOperatorPhase =
OPL3.topCymbalOperator.phase * OperatorData.multTable[OPL3.topCymbalOperator.mult];
// The sound output from the High Hat resembles the one from
// Top Cymbal, so we use the parent method and modifies his output
// accordingly afterwards.
double operatorOutput = super.getOperatorOutput(modulator, topCymbalOperatorPhase);
if(operatorOutput == 0) operatorOutput = Math.random()*envelope;
return operatorOutput;
}
}
class SnareDrumOperator extends Operator {
final static int snareDrumOperatorBaseAddress = 0x14;
SnareDrumOperator() {
super(snareDrumOperatorBaseAddress);
}
double getOperatorOutput(double modulator) {
if(envelopeGenerator.stage == EnvelopeGenerator.Stage.OFF) return 0;
double envelopeInDB = envelopeGenerator.getEnvelope(egt, am);
envelope = Math.pow(10, envelopeInDB/10.0);
// If it is in OPL2 mode, use first four waveforms only:
int waveIndex = ws & ((OPL3._new<<2) + 3);
double[] waveform = OperatorData.waveforms[waveIndex];
phase = OPL3.highHatOperator.phase * 2;
double operatorOutput = getOutput(modulator, phase, waveform);
double noise = Math.random() * envelope;
if(operatorOutput/envelope != 1 && operatorOutput/envelope != -1) {
if(operatorOutput > 0) operatorOutput = noise;
else if(operatorOutput < 0) operatorOutput = -noise;
else operatorOutput = 0;
}
return operatorOutput*2;
}
}
class TomTomOperator extends Operator {
final static int tomTomOperatorBaseAddress = 0x12;
TomTomOperator() {
super(tomTomOperatorBaseAddress);
}
}
| [
"[email protected]"
] | |
7bafc675b4e2d99bbc5f20749f7ab1641bea00eb | 9e0d3a88bbec553403c16d947d3eb8ab610936b0 | /my_controller_pkg/src/dummy_app.cpp | 6481f4700d4b8beaa19b26dcb7dbfd4abb9d625d | [] | no_license | FatihKaanAkkus/mobile_robot | 45c9eb5e38260966cd7e8ba719178bcf9d412161 | c14c0723eef20b8609516b2dd7ceffaddef03946 | refs/heads/master | 2020-03-11T19:37:08.427339 | 2018-05-26T00:04:42 | 2018-05-26T00:04:42 | 130,212,743 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 554 | cpp | #include <ros/ros.h>
#include <controller_manager/controller_manager.h>
#include <my_controller_pkg/my_robot_hw.h>
using namespace my_controller_pkg;
int main(int argc, char** argv)
{
ros::init(argc, argv, "DummyApp");
ros::AsyncSpinner spinner(1);
spinner.start();
MyRobotHW hw;
ros::NodeHandle nh;
controller_manager::ControllerManager cm(&hw, nh);
ros::Duration period(1.0);
while (ros::ok())
{
ROS_INFO("loop");
hw.read();
cm.update(ros::Time::now(), period);
hw.write();
period.sleep();
}
return 0;
}
| [
"[email protected]"
] | |
83457e225aec7801eb9ce6831795f9b507bb2eea | 7d4ff4ea6b306a07fc13a8fa3d120fb62df94726 | /photoresistor/Photoresistor.cpp | 77871ba1750dfe5477932fa630d26f7ccb78e424 | [] | no_license | oshurmamadov/ArduinoSamples | af34e14f88b3c807146fc652d2ee5304891e5a0d | 0b1a8bdf6241b886e0cba0b37f5ca4c1f5635b2e | refs/heads/master | 2023-04-21T15:29:07.466356 | 2021-05-05T07:36:48 | 2021-05-05T07:36:48 | 356,362,023 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 795 | cpp | /*
* Photoresistor.cpp
*
* Created on: 11 Apr 2021
* Author: parviz.oshurmamadov
*/
#include "Photoresistor.h"
#include "Arduino.h"
#include "../utils/VoltTransformer.h"
int BIT_RATE = 28800;
int photoresistorReadPin = A5;
int redPin = 4;
int greenPin = 2;
VoltTransformer transformer;
void Photoresistor::setup() {
Serial.begin(BIT_RATE);
pinMode(photoresistorReadPin, INPUT);
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
}
void Photoresistor::loop() {
int photoresistorVolt = analogRead(photoresistorReadPin);
float voltage = transformer.toVold(photoresistorVolt);
Serial.println(voltage);
if (voltage <= 0.8) {
digitalWrite(redPin, HIGH);
digitalWrite(greenPin, LOW);
} else {
digitalWrite(redPin, LOW);
digitalWrite(greenPin, HIGH);
}
delay(500);
}
| [
"[email protected]"
] | |
5e042f4982474cab891a338f2450193257a76bb0 | a80f9892194bb0a4e2262e116f6c81df1149ab4d | /libraries/Led_Dragon/Led_Dragon.h | ce2ee8bf7cc72ac0684a74eebc2e5d88310f21ae | [] | no_license | stevedudek/Arduino | f4bfe975c5da7148d67a20f3103d9de01fec6ae7 | 9025714324190f7b8b352185d3455f8b88636419 | refs/heads/master | 2023-01-08T00:14:57.236175 | 2022-12-27T00:40:37 | 2022-12-27T00:40:37 | 29,985,600 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,636 | h | //
// Led.h
//
#ifndef Led_h
#define Led_h
class Led
{
public:
Led(uint16_t i);
uint16_t
getNumLeds(void);
void
fill(CHSV color),
fillHue(uint8_t hue),
fillBlack(void);
void
setPixelColor(uint16_t i, CHSV color), setPixelHue(uint16_t i, uint8_t hue),
increasePixelHue(uint16_t i, uint8_t increase), flipPixel(uint16_t i),
setPixelBlack(uint16_t i);
void
dimPixel(uint16_t i, uint8_t amount),
dimAllPixels(uint8_t amount);
// void morph_frame(uint8_t morph, uint8_t total_frames);
void morph_frame(uint8_t fract);
void push_frame(void);
void
setBlur(uint8_t b), turnOffBlur(void);
bool
hasBlur(void);
void
addPixelColor(uint16_t i, CHSV c2), addPixelColorNoMap(uint16_t i, CHSV c2);
CHSV
getCurrFrameColor(uint16_t i),
getNextFrameColor(uint16_t i),
getInterpFrameColor(uint16_t i);
uint8_t
getInterpFrameHue(uint16_t i),
getInterpFrameSat(uint16_t i),
getInterpFrameVal(uint16_t i);
void
setInterpFrame(uint16_t i, CHSV color),
setInterpFrameHue(uint16_t i, uint8_t hue),
setInterpFrameSat(uint16_t i, uint8_t sat),
setInterpFrameVal(uint16_t i, uint8_t val);
CHSV
wheel(uint8_t hue),
gradient_wheel(uint8_t hue, uint8_t intensity);
CHSV rgb_to_hsv( CRGB color);
CHSV
getInterpHSV(CHSV c1, CHSV c2, uint8_t fract),
getInterpHSV(CHSV c1, CHSV c2, CHSV old_color, uint8_t fract),
getInterpHSVthruRGB(CHSV c1, CHSV c2, uint8_t fract),
smooth_color(CHSV old_color, CHSV new_color, uint8_t max_change);
CRGB
getInterpRGB(CRGB c1, CRGB c2, uint8_t fract),
smooth_rgb_color(CRGB old_color, CRGB new_color, uint8_t max_change);
CHSV getInterpRGBthruHSV(CRGB c1, CRGB c2, uint8_t fract);
void RGBtoHSV(uint8_t red, uint8_t green, uint8_t blue, float *h, float *s, float *v );
void rgb2hsv_new(uint8_t src_r, uint8_t src_g, uint8_t src_b, uint8_t *dst_h, uint8_t *dst_s, uint8_t *dst_v);
bool
is_black(CHSV color);
uint8_t
interpolate(uint8_t a, uint8_t b, uint8_t fract),
interpolate_wrap(uint8_t a, uint8_t b, uint8_t fract),
interpolate_wrap(uint8_t a, uint8_t b, uint8_t old_value, uint8_t fract),
smooth(uint8_t old_value, uint8_t new_value, uint8_t max_change),
smooth_wrap(uint8_t old_value, uint8_t new_value, uint8_t max_change);
private:
// variables
uint16_t numLeds;
CHSV *current_frame;
CHSV *next_frame;
CHSV *interp_frame;
uint8_t blur_amount;
// private functions
};
#endif
| [
"[email protected]"
] | |
7d08490fa64e30ff3d03ff84c15692897de3d725 | 6300038dd6b7d7251afa52bdfee980c8bbcf7669 | /src/compositor/texture_delegate.h | ad735bf56b96ea8b59f062b691f71b350701d3b2 | [
"BSD-3-Clause"
] | permissive | kkspeed/NaiveWM | 06740316336a425b95456dd8f1bb3fede0d0947d | 5da1e816ae3b9ec7a5a8c0b73b569615e231a215 | refs/heads/master | 2020-12-10T03:19:51.709491 | 2017-09-28T02:35:47 | 2017-09-28T02:35:47 | 95,508,262 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 493 | h | #ifndef COMPOSITOR_TEXTUREDELEGATE_H_
#define COMPOSITOR_TEXTUREDELEGATE_H_
#include <memory>
namespace naive {
namespace compositor {
class TextureDelegate {
public:
virtual void Draw(int x,
int y,
int patch_x,
int patch_y,
int width,
int height) = 0;
virtual ~TextureDelegate() = default;
};
} // namespace compositor
} // namespace naive
#endif // COMPOSITOR_TEXTURE_DELEGATE_
| [
"[email protected]"
] | |
fea24f6a05e55b6172baef5cb50885af9ea27f3d | f359d190dd0fa43dc21772a0faccec89013e0e99 | /export/windows/obj/include/flixel/system/debug/_Window/GraphicWindowHandle.h | dcf766073c60c36944da533e2feaa54517687018 | [] | no_license | pedrohpe/terminal | 0da838959f09c50550e629fa8c592dc364b1fa1f | 49fdf9fd10a075ae083e9b31850788fbb814fea5 | refs/heads/master | 2020-03-25T09:18:50.578453 | 2018-08-05T21:42:33 | 2018-08-05T21:42:33 | 143,659,093 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 2,329 | h | // Generated by Haxe 3.4.4
#ifndef INCLUDED_flixel_system_debug__Window_GraphicWindowHandle
#define INCLUDED_flixel_system_debug__Window_GraphicWindowHandle
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
#ifndef INCLUDED_openfl_display_BitmapData
#include <openfl/display/BitmapData.h>
#endif
HX_DECLARE_CLASS4(flixel,_hx_system,debug,_Window,GraphicWindowHandle)
HX_DECLARE_CLASS2(openfl,display,BitmapData)
HX_DECLARE_CLASS2(openfl,display,IBitmapDrawable)
namespace flixel{
namespace _hx_system{
namespace debug{
namespace _Window{
class HXCPP_CLASS_ATTRIBUTES GraphicWindowHandle_obj : public ::openfl::display::BitmapData_obj
{
public:
typedef ::openfl::display::BitmapData_obj super;
typedef GraphicWindowHandle_obj OBJ_;
GraphicWindowHandle_obj();
public:
enum { _hx_ClassId = 0x6915d971 };
void __construct(int width,int height, ::Dynamic __o_transparent, ::Dynamic __o_fillRGBA);
inline void *operator new(size_t inSize, bool inContainer=true,const char *inName="flixel.system.debug._Window.GraphicWindowHandle")
{ return hx::Object::operator new(inSize,inContainer,inName); }
inline void *operator new(size_t inSize, int extra)
{ return hx::Object::operator new(inSize+extra,true,"flixel.system.debug._Window.GraphicWindowHandle"); }
static hx::ObjectPtr< GraphicWindowHandle_obj > __new(int width,int height, ::Dynamic __o_transparent, ::Dynamic __o_fillRGBA);
static hx::ObjectPtr< GraphicWindowHandle_obj > __alloc(hx::Ctx *_hx_ctx,int width,int height, ::Dynamic __o_transparent, ::Dynamic __o_fillRGBA);
static void * _hx_vtable;
static Dynamic __CreateEmpty();
static Dynamic __Create(hx::DynamicArray inArgs);
//~GraphicWindowHandle_obj();
HX_DO_RTTI_ALL;
static bool __GetStatic(const ::String &inString, Dynamic &outValue, hx::PropertyAccess inCallProp);
static bool __SetStatic(const ::String &inString, Dynamic &ioValue, hx::PropertyAccess inCallProp);
static void __register();
bool _hx_isInstanceOf(int inClassId);
::String __ToString() const { return HX_HCSTRING("GraphicWindowHandle","\x60","\x9a","\xd6","\xfa"); }
static void __boot();
static ::String resourceName;
};
} // end namespace flixel
} // end namespace system
} // end namespace debug
} // end namespace _Window
#endif /* INCLUDED_flixel_system_debug__Window_GraphicWindowHandle */
| [
"[email protected]"
] | |
778584d71bc37f92d61b1a4c79dd3dea4ca1e06a | 1af49694004c6fbc31deada5618dae37255ce978 | /chrome/browser/chromeos/child_accounts/time_limits/web_time_limit_navigation_throttle.cc | 4404363f7692b33f34559f20f8328bac31369252 | [
"BSD-3-Clause"
] | permissive | sadrulhc/chromium | 59682b173a00269ed036eee5ebfa317ba3a770cc | a4b950c23db47a0fdd63549cccf9ac8acd8e2c41 | refs/heads/master | 2023-02-02T07:59:20.295144 | 2020-12-01T21:32:32 | 2020-12-01T21:32:32 | 317,678,056 | 3 | 0 | BSD-3-Clause | 2020-12-01T21:56:26 | 2020-12-01T21:56:25 | null | UTF-8 | C++ | false | false | 8,031 | cc | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/child_accounts/time_limits/web_time_limit_navigation_throttle.h"
#include <string>
#include "base/feature_list.h"
#include "base/memory/ptr_util.h"
#include "base/optional.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/child_accounts/child_user_service.h"
#include "chrome/browser/chromeos/child_accounts/child_user_service_factory.h"
#include "chrome/browser/chromeos/child_accounts/time_limits/app_types.h"
#include "chrome/browser/chromeos/child_accounts/time_limits/web_time_limit_enforcer.h"
#include "chrome/browser/chromeos/child_accounts/time_limits/web_time_limit_error_page/web_time_limit_error_page.h"
#include "chrome/browser/chromeos/child_accounts/time_limits/web_time_navigation_observer.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/web_applications/app_browser_controller.h"
#include "chrome/browser/web_applications/components/app_registrar.h"
#include "chrome/browser/web_applications/components/web_app_id.h"
#include "chrome/browser/web_applications/components/web_app_tab_helper_base.h"
#include "chrome/browser/web_applications/web_app_provider.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/web_contents.h"
#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
namespace chromeos {
namespace {
bool IsWebBlocked(content::BrowserContext* context) {
auto* child_user_service =
ChildUserServiceFactory::GetForBrowserContext(context);
DCHECK(child_user_service);
return child_user_service->WebTimeLimitReached();
}
bool IsURLAllowlisted(const GURL& url, content::BrowserContext* context) {
auto* child_user_service =
ChildUserServiceFactory::GetForBrowserContext(context);
if (!child_user_service)
return false;
return child_user_service->WebTimeLimitAllowlistedURL(url);
}
bool IsWebAppAllowlisted(const std::string& app_id_string,
content::BrowserContext* context) {
const chromeos::app_time::AppId app_id(apps::mojom::AppType::kWeb,
app_id_string);
auto* child_user_service =
ChildUserServiceFactory::GetForBrowserContext(context);
DCHECK(child_user_service);
return child_user_service->AppTimeLimitAllowlistedApp(app_id);
}
base::TimeDelta GetWebTimeLimit(content::BrowserContext* context) {
auto* child_user_service =
ChildUserServiceFactory::GetForBrowserContext(context);
DCHECK(child_user_service);
return child_user_service->GetWebTimeLimit();
}
Browser* FindBrowserForWebContents(content::WebContents* web_contents) {
BrowserList* browser_list = BrowserList::GetInstance();
for (Browser* browser : *browser_list) {
TabStripModel* tab_strip_model = browser->tab_strip_model();
for (int i = 0; i < tab_strip_model->count(); i++) {
if (web_contents == tab_strip_model->GetWebContentsAt(i))
return browser;
}
}
return nullptr;
}
} // namespace
using ThrottleCheckResult = content::NavigationThrottle::ThrottleCheckResult;
// static
std::unique_ptr<WebTimeLimitNavigationThrottle>
WebTimeLimitNavigationThrottle::MaybeCreateThrottleFor(
content::NavigationHandle* navigation_handle) {
content::BrowserContext* browser_context =
navigation_handle->GetWebContents()->GetBrowserContext();
if (!Profile::FromBrowserContext(browser_context)->IsChild())
return nullptr;
if (!app_time::WebTimeLimitEnforcer::IsEnabled())
return nullptr;
if (!navigation_handle->IsInMainFrame())
return nullptr;
// Creating a throttle for both the main frame and sub frames. This prevents
// kids from circumventing the app restrictions by using iframes in a local
// html file.
return IsWebBlocked(browser_context)
? base::WrapUnique(
new WebTimeLimitNavigationThrottle(navigation_handle))
: nullptr;
}
WebTimeLimitNavigationThrottle::~WebTimeLimitNavigationThrottle() = default;
ThrottleCheckResult WebTimeLimitNavigationThrottle::WillStartRequest() {
return WillStartOrRedirectRequest();
}
ThrottleCheckResult WebTimeLimitNavigationThrottle::WillRedirectRequest() {
return WillStartOrRedirectRequest();
}
ThrottleCheckResult WebTimeLimitNavigationThrottle::WillProcessResponse() {
return WillStartOrRedirectRequest();
}
const char* WebTimeLimitNavigationThrottle::GetNameForLogging() {
return "WebTimeLimitNavigationThrottle";
}
WebTimeLimitNavigationThrottle::WebTimeLimitNavigationThrottle(
content::NavigationHandle* navigation_handle)
: NavigationThrottle(navigation_handle) {}
ThrottleCheckResult
WebTimeLimitNavigationThrottle::WillStartOrRedirectRequest() {
content::BrowserContext* browser_context =
navigation_handle()->GetWebContents()->GetBrowserContext();
if (!IsWebBlocked(browser_context) ||
IsURLAllowlisted(navigation_handle()->GetURL(), browser_context)) {
return NavigationThrottle::PROCEED;
}
// Let's get the browser instance from the navigation handle.
content::WebContents* web_contents = navigation_handle()->GetWebContents();
// Proceed if the |web_contents| is embedded in another WebContents or if it
// is doing background work for another user facing WebContents.
if (web_contents->GetOutermostWebContents() != web_contents ||
web_contents->GetResponsibleWebContents() != web_contents) {
return PROCEED;
}
Browser* browser = FindBrowserForWebContents(web_contents);
if (!browser)
return PROCEED;
bool is_windowed = false;
if (browser) {
Browser::Type type = browser->type();
is_windowed = (type == Browser::Type::TYPE_APP_POPUP) ||
(type == Browser::Type::TYPE_APP) ||
(type == Browser::Type::TYPE_POPUP);
}
web_app::WebAppTabHelperBase* web_app_helper =
web_app::WebAppTabHelperBase::FromWebContents(web_contents);
bool is_app = web_app_helper && !web_app_helper->GetAppId().empty();
base::TimeDelta time_limit = GetWebTimeLimit(browser_context);
const std::string& app_locale = g_browser_process->GetApplicationLocale();
if (!is_app) {
const GURL& url = navigation_handle()->GetURL();
std::string domain = net::registry_controlled_domains::GetDomainAndRegistry(
url, net::registry_controlled_domains::PrivateRegistryFilter::
INCLUDE_PRIVATE_REGISTRIES);
if (domain.empty())
domain = url.has_host() ? url.host() : url.spec();
app_time::WebTimeNavigationObserver* observer =
app_time::WebTimeNavigationObserver::FromWebContents(web_contents);
const base::Optional<base::string16>& prev_title =
observer ? observer->previous_title() : base::nullopt;
return NavigationThrottle::ThrottleCheckResult(
CANCEL, net::ERR_BLOCKED_BY_CLIENT,
GetWebTimeLimitChromeErrorPage(domain, prev_title, time_limit,
app_locale));
}
// Don't throttle windowed applications. We show a notification and close
// them.
if (is_windowed)
return PROCEED;
// Don't throttle allowlisted applications.
if (IsWebAppAllowlisted(web_app_helper->GetAppId(), browser_context))
return PROCEED;
Profile* profile = Profile::FromBrowserContext(browser_context);
web_app::WebAppProvider* web_app_provider =
web_app::WebAppProvider::Get(profile);
const web_app::AppRegistrar& registrar = web_app_provider->registrar();
const std::string& app_name =
registrar.GetAppShortName(web_app_helper->GetAppId());
return NavigationThrottle::ThrottleCheckResult(
CANCEL, net::ERR_BLOCKED_BY_CLIENT,
GetWebTimeLimitAppErrorPage(time_limit, app_locale, app_name));
}
} // namespace chromeos
| [
"[email protected]"
] | |
44622f4287c3d9dd208817612d2951a76ecc90aa | bbece7213a837ae2650bd7f881f42a143f3b5464 | /Homework_2/Asteroids_SSE.cpp | 8e57f5d3e9170235cca98883d4230d04d26df27e | [] | no_license | sjgeorge2/CS441_Homework | b225ad597e6386a59f9882e88cebf6adfededbce | dcf69029a442d6beeb019c2508b6dbc44ab7da9c | refs/heads/master | 2021-01-18T04:09:02.762373 | 2017-03-23T23:52:46 | 2017-03-23T23:52:46 | 85,760,209 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,774 | cpp | // Samuel George
// CS441 Homework Assignemnt 2
// This code was modified to work with the SSE instruction set
// Original code provided from class
#include <iostream>
#include <fstream>
using std::fstream;
using std::ios;
#include <chrono> //c++11 Timing functions
#include <cmath>
//#include "lib/inc.c" // netrun timing functions
#include "xmmintrin.h"
// Make up a random 3D vector in this range.
// NOT ACTUALLY RANDOM, just pseudorandom via linear congruence.
void randomize(int index, float range, float &x, float &y, float &z) {
index = index ^ (index << 24); // fold index (improve whitening)
x = (((index * 1234567) % 1039) / 1000.0 - 0.5)*range;
y = (((index * 7654321) % 1021) / 1000.0 - 0.5)*range;
z = (((index * 1726354) % 1027) / 1000.0 - 0.5)*range;
}
class position {
public:
float px, py, pz; // position's X, Y, Z components (meters)
// Return distance to another position
float distance(const position &p) const {
float dx = p.px - px;
float dy = p.py - py;
float dz = p.pz - pz;
return sqrt(dx*dx + dy*dy + dz*dz);
}
};
class body : public position {
public:
float m; // mass (Kg)
};
class asteroid : public body {
public:
float vx, vy, vz; // velocity (m)
float fx, fy, fz; // net force vector (N)
void setup(void) {
fx = fy = fz = 0.0;
}
// Add the gravitational force on us due to this body
void add_force(const body &b) {
// Newton's law of gravitation:
// length of F = G m1 m2 / r^2
// direction of F = R/r
float dx = b.px - px;
float dy = b.py - py;
float dz = b.pz - pz;
float r = sqrt(dx*dx + dy*dy + dz*dz);
float G = 6.67408e-11; // gravitational constant
float scale = G*b.m*m / (r*r*r);
fx += dx*scale;
fy += dy*scale;
fz += dz*scale;
}
// Use known net force values to advance by one timestep
void step(float dt) {
float ax = fx / m, ay = fy / m, az = fz / m;
vx += ax*dt; vy += ay*dt; vz += az*dt;
px += vx*dt; py += vy*dt; pz += vz*dt;
}
};
// A simple fixed-size image
class image {
public:
enum { pixels = 500 };
unsigned char pixel[pixels][pixels];
void clear(void) {
for (int y = 0; y<pixels; y++)
for (int x = 0; x<pixels; x++)
pixel[y][x] = 0;
}
void draw(float fx, float fy) {
int y = (int)(fx*pixels);
int x = (int)(fy*pixels);
if (y >= 0 && y<pixels && x >= 0 && x<pixels)
if (pixel[y][x]<200) pixel[y][x] += 10;
}
void write(const char *filename) {
std::ofstream f("out.ppm", std::ios_base::binary);
f << "P5 " << pixels << " " << pixels << "\n";
f << "255\n";
for (int y = 0; y<pixels; y++)
for (int x = 0; x<pixels; x++)
f.write((char *)&pixel[y][x], 1);
}
};
//////////////////////////////////////////////////
/* SSE Operations Wrapper */
//////////////////////////////////////////////////
// Copied from class notes + added needed functionality //
// copied from class notes + additions
class fourfloats; /* forward declaration */
/* Wrapper around four bitmasks: 0 if false, all-ones (NAN) if true.
This class is used to implement comparisons on SSE registers. */
class fourmasks {
__m128 mask;
public:
fourmasks(__m128 m) { mask = m; }
__m128 if_then_else(fourfloats dthen, fourfloats delse);
};
/* Nice wrapper around __m128:
it represents four floating point values. */
class fourfloats {
__m128 v;
public:
fourfloats(float onevalue) { v = _mm_load1_ps(&onevalue); }
fourfloats(float onevalue, float twovalue, float threevalue, float fourvalue) { v = _mm_setr_ps(onevalue, twovalue, threevalue, fourvalue); }
fourfloats(__m128 ssevalue) { v = ssevalue; } // put in an SSE value
operator __m128 () const { return v; } // take out an SSE value
fourfloats(const float *fourvalues) { v = _mm_load_ps(fourvalues); }
void store(float *fourvalues) { _mm_store_ps(fourvalues, v); }
/* arithmetic operations return blocks of floats */
fourfloats operator+(const fourfloats &right) {
return _mm_add_ps(v, right.v);
}
fourfloats operator*(const fourfloats &right) {
return _mm_mul_ps(v, right.v);
}
/* comparison operations return blocks of masks (bools) */
fourmasks operator<(const fourfloats &right) {
return _mm_cmplt_ps(v, right.v);
}
};
int main(void) {
image img;
fstream myfile;
myfile.open("resultfileSSE.txt", ios::out);
enum { n_asteroids = 8192 };
float range = 500e6;
float p2v = 3.0e-6; // position (meters) to velocity (meters/sec)
body terra;
terra.px = 0.0; terra.py = 0.0; terra.pz = 0.0;
terra.m = 5.972e24;
body luna;
luna.px = 384.4e6; luna.py = 0.0; luna.pz = 0.0;
luna.m = 7.34767309e22;
///////////////////////////////////////////////////////////////////////
/* the SSE timing code */
//////////////////////////////////////////////////////////////////////
myfile << "SSE Altered time:\n";
std::chrono::time_point<std::chrono::high_resolution_clock> start, end;
for (int test = 0; test < 5; test++) {
float closest_approach = 1.0e100;
img.clear(); // black out the image
start = std::chrono::high_resolution_clock::now();
//double start=time_in_seconds();
/* performance critical part here */
for (int ai = 0; ai < n_asteroids; ai = ai+4)
{
asteroid a;
int run = 0;
do {
// run randomize on each SSE
randomize(ai * 100 + run, range, a.px, a.py, a.pz);
run++;
} while (a.distance(terra) < 10000e3);
//a.m = 1.0;
//a.vx = -a.py*p2v;
//a.vy = a.px*p2v;
//a.vz = 0.0;
// load one SSE register full of p2v
// load second SSE register full of components of an asteroid, to be put in a vector to set each component with
fourfloats src(1.0, -a.py, a.px, 0.0);
fourfloats d = (src, src*p2v, src*p2v, src);
float dest[4];
d.store(dest);
a.m = dest[0];
a.vx = dest[1];
a.vy = dest[2];
a.vz = dest[3];
for (int i = 0; i < 1000; i++)
{
a.setup();
a.add_force(terra);
a.add_force(luna);
a.step(1000.0);
// Draw current location of asteroid
img.draw(
a.px*(1.0 / range) + 0.5,
a.py*(1.0 / range) + 0.5);
// Check distance
float d = terra.distance(a);
if (closest_approach > d) closest_approach = d;
}
}
end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
myfile << "Took " << elapsed_seconds.count() << " seconds, " << elapsed_seconds.count()*1.0e9 / n_asteroids << " ns/asteroid\n";
myfile << " closest approach: " << closest_approach << "\n";
myfile << test;
/*if (myfile.is_open())
{
myfile << "SSE Altered time:\n";
myfile << "Took " << elapsed_seconds.count() << " seconds, " << elapsed_seconds.count()*1.0e9 / n_asteroids << " ns/asteroid\n";
myfile << " closest approach: " << closest_approach << "\n";
}*/
myfile.close();
}
img.write("out.ppm"); // netrun shows "out.ppm" by default
} | [
"[email protected]"
] | |
2ce3606a9991717375288144c15eb9944452456f | 21a221c20313339ac7380f8d92f8006e5435ef1d | /src/arcemu-world/LfgHandler.cpp | 8dda031f6cf5ba01c2db81b3bc7860d70a370a91 | [] | no_license | AwkwardDev/Descent-core-scripts-3.3.5 | a947a98d0fdedae36a488c542642fcf61472c3d7 | d773b1a41ed3f9f970d81962235e858d0848103f | refs/heads/master | 2021-01-18T10:16:03.750112 | 2014-08-12T16:28:15 | 2014-08-12T16:28:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 120,228 | cpp | /*
* ArcEmu MMORPG Server
* Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2008 <http://www.ArcEmu.org/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "StdAfx.h"
void WorldSession::HandleLFGJoin(WorldPacket& recvPacket)
{
sLog.outDebug("CMSG_LFG_JOIN");
uint8 map_count,unk_count;
uint8 unk1,unk2,unk3;
recvPacket >> GetPlayer()->LFG_roles;
recvPacket >> unk1;
recvPacket >> unk2;
recvPacket >> map_count;
if ( map_count == 0 ) //maybe this is also used to leave the search ?
return;
//clear old list
GetPlayer()->LFG_dungeons.BeginLoop();
GetPlayer()->LFG_dungeons.SafeClear();
for (int8 i = 0 ; i < map_count; ++i)
{
LFG_store *tstore = new LFG_store;
uint32 tval;
recvPacket >> tval;
tstore->type = tval >> 24;
tstore->map_id = tval & 0x00FFFFFF;
GetPlayer()->LFG_dungeons.push_front( tstore );
}
GetPlayer()->LFG_dungeons.EndLoopAndCommit();
recvPacket >> unk_count;
for (int8 i = 0 ; i < unk_count; ++i)
recvPacket >> unk3;
recvPacket >> GetPlayer()->LFG_comment;
//!! hack, include gear score in comment !!!
// GetPlayer()->LFG_comment = GetPlayer()->LFG_GetGearScore( ) + ":" + GetPlayer()->LFG_comment;
sLfgMgr.LFGDungeonJoin( GetPlayer() );
}
void WorldSession::HandleLFGLeave(WorldPacket& recvPacket)
{
sLog.outDebug("CMSG_LFG_LEAVE");
sLfgMgr.LFGDungeonLeave( GetPlayer() );
}
void WorldSession::HandleLFGAnswerJoin(WorldPacket& recvPacket)
{
}
void WorldSession::HandleLFGSetFilterRoles(WorldPacket& recvPacket)
{
sLog.outDebug("CMSG_LFG_SET_ROLES");
recvPacket >> GetPlayer()->LFG_roles;
}
void WorldSession::HandleLFGSetComment(WorldPacket& recvPacket)
{
sLog.outDebug("CMSG_SET_LFG_COMMENT");
recvPacket >> GetPlayer()->LFG_comment;
//!! hack, include gear score in comment !!!
// GetPlayer()->LFG_comment = GetPlayer()->LFG_GetGearScore( ) + ":" + GetPlayer()->LFG_comment;
}
void WorldSession::HandleLFGKickVote(WorldPacket& recvPacket)
{
}
void WorldSession::HandleLFGTeleport(WorldPacket& recvPacket)
{
}
//from DBC fetch all possible dungeons and send a list that we may join
void WorldSession::HandleLFGPlayerListRequest(WorldPacket& recvPacket)
{
sLog.outDebug("CMSG_LFG_PLAYER_LOCK_INFO_REQUEST");
uint32 counter_pos,counter_val;
sStackWolrdPacket( data, SMSG_LFG_PLAYER_INFO, 5000 );
//build up random dungeon list
counter_pos = data.GetSize();
counter_val = 0;
data << uint8( 0 ); //-> holder for the number of random dungeons available
/* for (uint32 i = 0; i < dbcLFGDungeonStore.GetNumRows(); ++i)
{
LFGDungeonEntry *de = dbcLFGDungeonStore.LookupRow(i);
if ( de->type == LFG_TYPE_RANDOM && de->minlevel <= GetPlayer()->getLevel() && GetPlayer()->getLevel() <= de->maxlevel )
{
uint32 combined_data = de->map_id | (de->type << 24);
data << uint32( combined_data );
data << uint8( 0 ); //done ?
//these are the reward details, need to implement these later
data << uint32(0); //base money
data << uint32(0); //basexp
data << uint32(0); //rand money
data << uint32(0); //rand xp
data << uint8(0); //has item rewards
counter_val++;
}
}
data.WriteAtPos( (uint8)counter_val, counter_pos );*/
//this is needed or custom realms will not be able to use RB
uint32 mylevel = GetPlayer()->getLevel();
if( mylevel > PLAYER_LEVEL_CAP_BLIZZLIKE )
mylevel = PLAYER_LEVEL_CAP_BLIZZLIKE;
//these are available dungeons without special rewards
counter_pos = data.GetSize();
counter_val = 0;
data << uint32( 0 ); //-> holder for the number of random dungeons available
for (uint32 i = 0; i < dbcLFGDungeonStore.GetNumRows(); ++i)
{
LFGDungeonEntry *de = dbcLFGDungeonStore.LookupRow(i);
if( de->type == LFG_TYPE_RANDOM || de->type == LFG_TYPE_ZONE || de->type == LFG_TYPE_QUEST )
continue;
LfgStatusCode sc = LFG_LOCKSTATUS_OK;
if (de->minlevel > mylevel )
sc = LFG_LOCKSTATUS_TOO_LOW_LEVEL;
else if (de->maxlevel < mylevel )
sc = LFG_LOCKSTATUS_TOO_HIGH_LEVEL;
if( sc == LFG_LOCKSTATUS_OK )
{
MapInfo * pMapInfo = WorldMapInfoStorage.LookupEntry( de->map_id );
if( pMapInfo == NULL )
sc = LFG_LOCKSTATUS_RAID_LOCKED;
}
uint32 combined_data = de->map_id | (de->type << 24);
data << uint32( combined_data );
data << uint32( sc );
counter_val++;
}
data.WriteAtPos( counter_val, counter_pos );
SendPacket(&data);
}
//from DBC fetch all possible dungeons and send a list that we may join as group
void WorldSession::HandleLFGGroupListRequest(WorldPacket& recvPacket)
{
sLog.outDebug("CMSG_LFD_PARTY_LOCK_INFO_REQUEST");
/*
01 - 1 guid
1E 7D 81 02 00 00 00 07 guid
5C 00 00 00 number of entries for this guid
F1 00 00 05 02 00 00 00
F2 00 00 05 02 00 00 00
DD 00 00 05 02 00 00 00 D1 00 00 01 02 00 00 00 D3 00 00 05 02 00 00 00 C9 00 00 05 03 00 00 00 B9 00 00 05 03 00 00 00 89 00 00 01 03 00 00 00 0A 00 00 01 03 00 00 00 08 00 00 01 03 00 00 00 10 00 00 01 03 00 00 00 AC 00 00 01 03 00 00 00 B4 00 00 05 03 00 00 00 BC 00 00 05 03 00 00 00 0C 00 00 01 03 00 00 00 0E 00 00 01 03 00 00 00 14 00 00 01 03 00 00 00 CE 00 00 01 02 00 00 00 CF 00 00 01 02 00 00 00 D2 00 00 05 02 00 00 00 D4 00 00 05 02 00 00 00 D5 00 00 05 02 00 00 00 CD 00 00 05 02 00 00 00 16 00 00 01 03 00 00 00 FC 00 00 05 02 00 00 00 D7 00 00 05 02 00 00 00 D9 00 00 05 02 00 00 00 DB 00 00 05 02 00 00 00 8A 00 00 01 03 00 00 00 1C 00 00 01 03 00 00 00 01 00 00 01 03 00 00 00 20 00 00 01 03 00 00 00 97 00 00 01 03 00 00 00 B6 00 00 05 03 00 00 00 BE 00 00 05 03 00 00 00 88 00 00 01 03 00 00 00 A4 00 00 01 03 00 00 00 AD 00 00 01 03 00 00 00 AE 00 00 01 03 00 00 00 AB 00 00 01 03 00 00 00 B2 00 00 05 03 00 00 00 B3 00 00 05 03 00 00 00 B5 00 00 05 03 00 00 00 B7 00 00 05 03 00 00 00 B8 00 00 05 03 00 00 00 BA 00 00 05 03 00 00 00 BB 00 00 05 03 00 00 00 BD 00 00 05 03 00 00 00 BF 00 00 05 03 00 00 00 C0 00 00 05 03 00 00 00 C6 00 00 01 03 00 00 00 E2 00 00 05 02 00 00 00 CB 00 00 01 02 00 00 00 12 00 00 01 03 00 00 00 AA 00 00 01 03 00 00 00 93 00 00 01 03 00 00 00 A3 00 00 01 03 00 00 00 1E 00 00 01 03 00 00 00 26 00 00 01 03 00 00 00 02 00 00 01 03 00 00 00 04 00 00 01 03 00 00 00 06 00 00 01 03 00 00 00 92 00 00 01 03 00 00 00 94 00 00 01 03 00 00 00 95 00 00 01 03 00 00 00 96 00 00 01 03 00 00 00 8C 00 00 01 03 00 00 00 FB 00 00 01 02 00 00 00 FD 00 00 01 02 00 00 00 FE 00 00 05 02 00 00 00 FF 00 00 01 02 00 00 00 00 01 00 05 02 00 00 00 10 01 00 01 03 00 00 00 11 01 00 01 03 00 00 00 1D 01 00 01 02 00 00 00 06 01 00 06 02 00 00 00 1E 01 00 01 02 00 00 00 12 01 00 01 03 00 00 00 14 01 00 01 03 00 00 00 1F 01 00 01 02 00 00 00 20 01 00 01 02 00 00 00 02 01 00 06 03 00 00 00 03 01 00 06 03 00 00 00 04 01 00 06 03 00 00 00 A5 00 00 01 03 00 00 00 F5 00 00 01 02 00 00 00 F9 00 00 05 02 00 00 00 28 00 00 01 03 00 00 00 18 00 00 01 03 00 00 00 1A 00 00 01 03 00 00 00 22 00 00 01 03 00 00 00 24 00 00 01 03 00 00 00
*/
if( GetPlayer() == NULL )
return; // noway
if( GetPlayer()->GetGroup() == NULL )
return; // hmm client never asked this unless you had a group
//get raid min and max level
uint32 raid_minlevel = GetPlayer()->getLevel();
uint32 raid_maxlevel = GetPlayer()->getLevel();
uint8 player_count = 0;
Group * group = GetPlayer()->GetGroup();
// Loop through each raid group.
for( uint8 k = 0; k < group->GetSubGroupCount(); k++ )
{
SubGroup * subgroup = group->GetSubGroup( k );
if( subgroup )
{
group->Lock();
for( GroupMembersSet::iterator itr = subgroup->GetGroupMembersBegin(); itr != subgroup->GetGroupMembersEnd(); ++itr )
{
if( (*itr)->m_loggedInPlayer == NULL )
continue;
if( (*itr)->m_loggedInPlayer->getLevel() < raid_minlevel )
raid_minlevel = (*itr)->m_loggedInPlayer->getLevel();
if( (*itr)->m_loggedInPlayer->getLevel() > raid_maxlevel )
raid_maxlevel = (*itr)->m_loggedInPlayer->getLevel();
player_count++;
}
group->Unlock();
}
}
if( raid_minlevel > PLAYER_LEVEL_CAP_BLIZZLIKE )
raid_minlevel = PLAYER_LEVEL_CAP_BLIZZLIKE;
if( raid_maxlevel > PLAYER_LEVEL_CAP_BLIZZLIKE )
raid_maxlevel = PLAYER_LEVEL_CAP_BLIZZLIKE;
uint32 counter_pos,counter_val;
sStackWolrdPacket( data, SMSG_LFG_PARTY_INFO, 5000 );
data << uint8( 1 ); //1 player count = leader
data << uint64( GetPlayer()->GetGUID() );
//build up random dungeon list
counter_pos = data.GetSize();
counter_val = 0;
data << uint32( 0 ); //-> holder for the number of random dungeons available
for (uint32 i = 0; i < dbcLFGDungeonStore.GetNumRows(); ++i)
{
LFGDungeonEntry *de = dbcLFGDungeonStore.LookupRow(i);
if( de->type == LFG_TYPE_RANDOM || de->type == LFG_TYPE_ZONE )
continue;
LfgStatusCode sc = LFG_LOCKSTATUS_OK;
if (de->minlevel > raid_minlevel)
sc = LFG_LOCKSTATUS_TOO_LOW_LEVEL;
else if (de->maxlevel < raid_maxlevel)
sc = LFG_LOCKSTATUS_TOO_HIGH_LEVEL;
if( sc == LFG_LOCKSTATUS_OK )
{
MapInfo * pMapInfo = WorldMapInfoStorage.LookupEntry( de->map_id );
if( pMapInfo == NULL )
sc = LFG_LOCKSTATUS_RAID_LOCKED;
}
data << uint32( de->ID );
data << uint32( sc );
counter_val++;
}
data.WriteAtPos( counter_val, counter_pos );
SendPacket(&data);
}
void WorldSession::HandleLFGQueueInstanceJoin(WorldPacket& recvPacket)
{
sLog.outDebug("CMSG_SEARCH_LFG_JOIN");
uint32 combined_data;
recvPacket >> combined_data;
GetPlayer()->RB_map_id = combined_data & 0x00FFFFFF;
GetPlayer()->RB_type = combined_data >> 24;
sLfgMgr.RBSendLookingPlayerList( GetPlayer() );
}
void WorldSession::HandleLFGQueueInstanceLeave(WorldPacket& recvPacket)
{
GetPlayer()->RB_map_id = 0;
GetPlayer()->RB_type = 0;
}
#if 0
/*
void WorldSession::HandleLfgProposalResultOpcode(WorldPacket &recv_data)
{
sLog.outDebug("CMSG_LFG_PROPOSAL_RESULT");
uint32 lfgGroupID; // Internal lfgGroupID
bool accept; // Accept to join?
recv_data >> lfgGroupID;
recv_data >> accept;
sLFGMgr.UpdateProposal(lfgGroupID, GetPlayer()->GetGUIDLow(), accept);
}
void WorldSession::HandleLfgSetBootVoteOpcode(WorldPacket &recv_data)
{
sLog.outDebug("CMSG_LFG_SET_BOOT_VOTE");
bool agree; // Agree to kick player
recv_data >> agree;
sLFGMgr.UpdateBoot(GetPlayer(), agree);
}
void WorldSession::HandleLfgTeleportOpcode(WorldPacket &recv_data)
{
sLog.outDebug("CMSG_LFG_TELEPORT");
bool out;
recv_data >> out;
sLFGMgr.TeleportPlayer(GetPlayer(), out);
}
void WorldSession::SendLfgUpdateParty(uint8 updateType)
{
bool join = false;
bool extrainfo = false;
bool queued = false;
switch(updateType)
{
case LFG_UPDATETYPE_JOIN_PROPOSAL:
extrainfo = true;
break;
case LFG_UPDATETYPE_ADDED_TO_QUEUE:
extrainfo = true;
join = true;
queued = true;
break;
case LFG_UPDATETYPE_CLEAR_LOCK_LIST:
// join = true; // TODO: Sometimes queued and extrainfo - Check ocurrences...
queued = true;
break;
case LFG_UPDATETYPE_PROPOSAL_BEGIN:
extrainfo = true;
join = true;
break;
}
LfgDungeonSet *dungeons = GetPlayer()->GetLfgDungeons();
uint8 size = dungeons->size();
std::string comment = GetPlayer()->GetLfgComment();
sLog.outDebug("SMSG_LFG_UPDATE_PARTY");
WorldPacket data(SMSG_LFG_UPDATE_PARTY, 1 + 1 + (extrainfo ? 1 : 0) * (1 + 1 + 1 + 1 + 1 + size * 4 + comment.length()));
data << uint8(updateType); // Lfg Update type
data << uint8(extrainfo); // Extra info
if (extrainfo)
{
data << uint8(join); // LFG Join
data << uint8(queued); // Join the queue
data << uint8(0); // unk - Always 0
data << uint8(0); // unk - Always 0
for (uint8 i = 0; i < 3; ++i)
data << uint8(0); // unk - Always 0
data << uint8(size);
for (LfgDungeonSet::const_iterator it = dungeons->begin(); it != dungeons->end(); ++it)
data << uint32(*it);
data << comment;
}
SendPacket(&data);
}
void WorldSession::SendLfgRoleChosen(uint64 guid, uint8 roles)
{
sLog.outDebug("SMSG_LFG_ROLE_CHOSEN");
WorldPacket data(SMSG_LFG_ROLE_CHOSEN, 8 + 1 + 4);
data << uint64(guid); // Guid
data << uint8(roles > 0); // Ready
data << uint32(roles); // Roles
SendPacket(&data);
}
void WorldSession::SendLfgQueueStatus(uint32 dungeon, int32 waitTime, int32 avgWaitTime, int32 waitTimeTanks, int32 waitTimeHealer, int32 waitTimeDps, uint32 queuedTime, uint8 tanks, uint8 healers, uint8 dps)
{
sLog.outDebug("SMSG_LFG_QUEUE_STATUS");
WorldPacket data(SMSG_LFG_QUEUE_STATUS, 4 + 4 + 4 + 4 + 4 +4 + 1 + 1 + 1 + 4);
data << uint32(dungeon); // Dungeon
data << uint32(avgWaitTime); // Average Wait time
data << uint32(waitTime); // Wait Time
data << uint32(waitTimeTanks); // Wait Tanks
data << uint32(waitTimeHealer); // Wait Healers
data << uint32(waitTimeDps); // Wait Dps
data << uint8(tanks); // Tanks needed
data << uint8(healers); // Healers needed
data << uint8(dps); // Dps needed
data << uint32(queuedTime); // Player wait time in queue
SendPacket(&data);
}
void WorldSession::SendLfgPlayerReward(uint32 rdungeonEntry, uint32 sdungeonEntry, uint8 done, const LfgReward *reward, const Quest *qRew)
{
if (!rdungeonEntry || !sdungeonEntry || !qRew)
return;
uint8 itemNum = qRew ? qRew->GetRewItemsCount() : 0;
sLog.outDebug("SMSG_LFG_PLAYER_REWARD");
WorldPacket data(SMSG_LFG_PLAYER_REWARD, 4 + 4 + 1 + 4 + 4 + 4 + 4 + 4 + 1 + itemNum * (4 + 4 + 4));
data << uint32(rdungeonEntry); // Random Dungeon Finished
data << uint32(sdungeonEntry); // Dungeon Finished
data << uint8(done);
data << uint32(1);
data << uint32(qRew->GetRewOrReqMoney());
data << uint32(qRew->XPValue(GetPlayer()));
data << uint32(reward->reward[done].variableMoney);
data << uint32(reward->reward[done].variableXP);
data << uint8(itemNum);
if (itemNum)
{
ItemPrototype const* iProto = NULL;
for (uint8 i = 0; i < QUEST_REWARDS_COUNT; ++i)
{
if (!qRew->RewItemId[i])
continue;
iProto = ObjectMgr::GetItemPrototype(qRew->RewItemId[i]);
data << uint32(qRew->RewItemId[i]);
data << uint32(iProto ? iProto->DisplayInfoID : 0);
data << uint32(qRew->RewItemCount[i]);
}
}
SendPacket(&data);
}
void WorldSession::SendLfgBootPlayer(LfgPlayerBoot *pBoot)
{
sLog.outDebug("SMSG_LFG_BOOT_PLAYER");
int8 playerVote = pBoot->votes[GetPlayer()->GetGUIDLow()];
uint8 votesNum = 0;
uint8 agreeNum = 0;
uint32 secsleft = uint8((pBoot->cancelTime - time(NULL)) / 1000);
for (LfgAnswerMap::const_iterator it = pBoot->votes.begin(); it != pBoot->votes.end(); ++it)
{
if (it->second != LFG_ANSWER_PENDING)
{
++votesNum;
if (it->second == LFG_ANSWER_AGREE)
++agreeNum;
}
}
WorldPacket data(SMSG_LFG_BOOT_PLAYER, 1 + 1 + 1 + 8 + 4 + 4 + 4 + 4 + pBoot->reason.length());
data << uint8(pBoot->inProgress); // Vote in progress
data << uint8(playerVote != -1); // Did Vote
data << uint8(playerVote == 1); // Agree
data << uint64(MAKE_NEW_GUID(pBoot->victimLowGuid, 0, HIGHGUID_PLAYER)); // Victim GUID
data << uint32(votesNum); // Total Votes
data << uint32(agreeNum); // Agree Count
data << uint32(secsleft); // Time Left
data << uint32(pBoot->votedNeeded); // Needed Votes
data << pBoot->reason.c_str(); // Kick reason
SendPacket(&data);
}
void WorldSession::SendUpdateProposal(uint32 proposalId, LfgProposal *pProp)
{
if (!pProp)
return;
uint32 pLogGuid = GetPlayer()->GetGUIDLow();
LfgProposalPlayerMap::const_iterator itPlayer = pProp->players.find(pLogGuid);
if (itPlayer == pProp->players.end()) // Player MUST be in the proposal
return;
LfgProposalPlayer *ppPlayer = itPlayer->second;
uint32 pLowGroupGuid = ppPlayer->groupLowGuid;
uint32 dLowGuid = pProp->groupLowGuid;
uint32 dungeonId = pProp->dungeonId;
uint32 isSameDungeon = GetPlayer()->GetGroup() && GetPlayer()->GetGroup()->GetLfgDungeonEntry() == dungeonId;
sLog.outDebug("SMSG_LFG_PROPOSAL_UPDATE");
WorldPacket data(SMSG_LFG_PROPOSAL_UPDATE, 4 + 1 + 4 + 4 + 1 + 1 + pProp->players.size() * (4 + 1 + 1 + 1 + 1 +1));
if (!dLowGuid && GetPlayer()->GetLfgDungeons()->size() == 1) // New group - select the dungeon the player selected
dungeonId = *GetPlayer()->GetLfgDungeons()->begin();
if (LFGDungeonEntry const *dungeon = sLFGDungeonStore.LookupEntry(dungeonId))
dungeonId = dungeon->Entry();
data << uint32(dungeonId); // Dungeon
data << uint8(pProp->state); // Result state
data << uint32(proposalId); // Internal Proposal ID
data << uint32(0); // Bosses killed - FIXME
data << uint8(isSameDungeon); // Silent (show client window)
data << uint8(pProp->players.size()); // Group size
for (itPlayer = pProp->players.begin(); itPlayer != pProp->players.end(); ++itPlayer)
{
ppPlayer = itPlayer->second;
data << uint32(ppPlayer->role); // Role
data << uint8(itPlayer->first == pLogGuid); // Self player
if (!ppPlayer->groupLowGuid) // Player not it a group
{
data << uint8(0); // Not in dungeon
data << uint8(0); // Not same group
}
else
{
data << uint8(ppPlayer->groupLowGuid == dLowGuid); // In dungeon (silent)
data << uint8(ppPlayer->groupLowGuid == pLowGroupGuid); // Same Group than player
}
data << uint8(ppPlayer->accept != LFG_ANSWER_PENDING); // Answered
data << uint8(ppPlayer->accept == LFG_ANSWER_AGREE); // Accepted
}
SendPacket(&data);
}
void WorldSession::SendLfgUpdateSearch(bool update)
{
sLog.outDebug("SMSG_LFG_UPDATE_SEARCH");
WorldPacket data(SMSG_LFG_UPDATE_SEARCH, 1);
data << uint8(update); // In Lfg Queue?
SendPacket(&data);
}
void WorldSession::SendLfgDisabled()
{
sLog.outDebug("SMSG_LFG_DISABLED");
WorldPacket data(SMSG_LFG_DISABLED, 0);
SendPacket(&data);
}
void WorldSession::SendLfgOfferContinue(uint32 dungeonEntry)
{
sLog.outDebug("SMSG_LFG_OFFER_CONTINUE");
WorldPacket data(SMSG_LFG_OFFER_CONTINUE, 4);
data << uint32(dungeonEntry);
SendPacket(&data);
}
void WorldSession::SendLfgTeleportError(uint8 err)
{
sLog.outDebug("SMSG_LFG_TELEPORT_DENIED");
WorldPacket data(SMSG_LFG_TELEPORT_DENIED, 4);
data << uint32(err); // Error
SendPacket(&data);
}
LFGMgr::LFGMgr()
{
m_QueueTimer = 0;
m_WaitTimeAvg = -1;
m_WaitTimeTank = -1;
m_WaitTimeHealer = -1;
m_WaitTimeDps = -1;
m_NumWaitTimeAvg = 0;
m_NumWaitTimeTank = 0;
m_NumWaitTimeHealer = 0;
m_NumWaitTimeDps = 0;
m_update = true;
m_lfgProposalId = 1;
GetAllDungeons();
}
LFGMgr::~LFGMgr()
{
for (LfgRewardMap::iterator itr = m_RewardMap.begin(); itr != m_RewardMap.end(); ++itr)
delete itr->second;
m_RewardMap.clear();
m_EncountersByAchievement.clear();
for (LfgQueueInfoMap::iterator it = m_QueueInfoMap.begin(); it != m_QueueInfoMap.end(); ++it)
delete it->second;
m_QueueInfoMap.clear();
for (LfgProposalMap::iterator it = m_Proposals.begin(); it != m_Proposals.end(); ++it)
delete it->second;
m_Proposals.clear();
for (LfgPlayerBootMap::iterator it = m_Boots.begin(); it != m_Boots.end(); ++it)
delete it->second;
m_Boots.clear();
for (LfgRoleCheckMap::iterator it = m_RoleChecks.begin(); it != m_RoleChecks.end(); ++it)
delete it->second;
m_RoleChecks.clear();
for (LfgDungeonMap::iterator it = m_CachedDungeonMap.begin(); it != m_CachedDungeonMap.end(); ++it)
delete it->second;
m_CachedDungeonMap.clear();
m_CompatibleMap.clear();
m_QueueInfoMap.clear();
m_currentQueue.clear();
m_newToQueue.clear();
}
/// <summary>
/// Load achievement <-> encounter associations
/// </summary>
void LFGMgr::LoadDungeonEncounters()
{
m_EncountersByAchievement.clear();
uint32 count = 0;
QueryResult_AutoPtr result = WorldDatabase.Query("SELECT achievementId, dungeonId FROM lfg_dungeon_encounters");
if (!result)
{
barGoLink bar(1);
bar.step();
sLog.outString();
sLog.outErrorDb(">> Loaded 0 dungeon encounter lfg associations. DB table `lfg_dungeon_encounters` is empty!");
return;
}
barGoLink bar(result->GetRowCount());
Field* fields = NULL;
do
{
bar.step();
fields = result->Fetch();
uint32 achievementId = fields[0].GetUInt32();
uint32 dungeonId = fields[1].GetUInt32();
if (AchievementEntry const* achievement = sAchievementStore.LookupEntry(achievementId))
{
if (!(achievement->flags & ACHIEVEMENT_FLAG_COUNTER))
{
sLog.outErrorDb("Achievement %u specified in table `lfg_dungeon_encounters` is not a statistic!", achievementId);
continue;
}
}
else
{
sLog.outErrorDb("Achievement %u specified in table `lfg_dungeon_encounters` does not exist!", achievementId);
continue;
}
if (!sLFGDungeonStore.LookupEntry(dungeonId))
{
sLog.outErrorDb("Dungeon %u specified in table `lfg_dungeon_encounters` does not exist!", dungeonId);
continue;
}
m_EncountersByAchievement[achievementId] = dungeonId;
++count;
} while (result->NextRow());
sLog.outString();
sLog.outString(">> Loaded %u dungeon encounter lfg associations.", count);
}
/// <summary>
/// Load rewards for completing dungeons
/// </summary>
void LFGMgr::LoadRewards()
{
for (LfgRewardMap::iterator itr = m_RewardMap.begin(); itr != m_RewardMap.end(); ++itr)
delete itr->second;
m_RewardMap.clear();
uint32 count = 0;
// ORDER BY is very important for GetRandomDungeonReward!
QueryResult_AutoPtr result = WorldDatabase.Query("SELECT dungeonId, maxLevel, firstQuestId, firstMoneyVar, firstXPVar, otherQuestId, otherMoneyVar, otherXPVar FROM lfg_dungeon_rewards ORDER BY dungeonId, maxLevel ASC");
if (!result)
{
barGoLink bar(1);
bar.step();
sLog.outString();
sLog.outErrorDb(">> Loaded 0 lfg dungeon rewards. DB table `lfg_dungeon_rewards` is empty!");
return;
}
barGoLink bar(result->GetRowCount());
Field* fields = NULL;
do
{
bar.step();
fields = result->Fetch();
uint32 dungeonId = fields[0].GetUInt32();
uint32 maxLevel = fields[1].GetUInt8();
uint32 firstQuestId = fields[2].GetUInt32();
uint32 firstMoneyVar = fields[3].GetUInt32();
uint32 firstXPVar = fields[4].GetUInt32();
uint32 otherQuestId = fields[5].GetUInt32();
uint32 otherMoneyVar = fields[6].GetUInt32();
uint32 otherXPVar = fields[7].GetUInt32();
if (!sLFGDungeonStore.LookupEntry(dungeonId))
{
sLog.outErrorDb("Dungeon %u specified in table `lfg_dungeon_rewards` does not exist!", dungeonId);
continue;
}
if (!maxLevel || maxLevel > sWorld.getIntConfig(CONFIG_MAX_PLAYER_LEVEL))
{
sLog.outErrorDb("Level %u specified for dungeon %u in table `lfg_dungeon_rewards` can never be reached!", maxLevel, dungeonId);
maxLevel = sWorld.getIntConfig(CONFIG_MAX_PLAYER_LEVEL);
}
if (firstQuestId && !sObjectMgr.GetQuestTemplate(firstQuestId))
{
sLog.outErrorDb("First quest %u specified for dungeon %u in table `lfg_dungeon_rewards` does not exist!", firstQuestId, dungeonId);
firstQuestId = 0;
}
if (otherQuestId && !sObjectMgr.GetQuestTemplate(otherQuestId))
{
sLog.outErrorDb("Other quest %u specified for dungeon %u in table `lfg_dungeon_rewards` does not exist!", otherQuestId, dungeonId);
otherQuestId = 0;
}
m_RewardMap.insert(LfgRewardMap::value_type(dungeonId, new LfgReward(maxLevel, firstQuestId, firstMoneyVar, firstXPVar, otherQuestId, otherMoneyVar, otherXPVar)));
++count;
} while (result->NextRow());
sLog.outString();
sLog.outString(">> Loaded %u lfg dungeon rewards.", count);
}
// Temporal add to try to find bugs that leaves data inconsistent
void LFGMgr::Cleaner()
{
LfgQueueInfoMap::iterator itQueue;
LfgGuidList::iterator itGuidListRemove;
LfgGuidList eraseList;
for (LfgQueueInfoMap::iterator it = m_QueueInfoMap.begin(); it != m_QueueInfoMap.end();)
{
itQueue = it++;
// Remove empty queues
if (!itQueue->second)
{
sLog.outError("LFGMgr::Cleaner: removing " UI64FMTD " from QueueInfoMap, data is null", itQueue->first);
m_QueueInfoMap.erase(itQueue);
}
// Remove queue with empty players
else if(!itQueue->second->roles.size())
{
sLog.outError("LFGMgr::Cleaner: removing " UI64FMTD " from QueueInfoMap, no players in queue!", itQueue->first);
m_QueueInfoMap.erase(itQueue);
}
}
// Remove from NewToQueue those guids that do not exist in queueMap
for (LfgGuidList::iterator it = m_newToQueue.begin(); it != m_newToQueue.end();)
{
itGuidListRemove = it++;
if (m_QueueInfoMap.find(*itGuidListRemove) == m_QueueInfoMap.end())
{
eraseList.push_back(*itGuidListRemove);
m_newToQueue.erase(itGuidListRemove);
sLog.outError("LFGMgr::Cleaner: removing " UI64FMTD " from newToQueue, no queue info with that guid", *itGuidListRemove);
}
}
// Remove from currentQueue those guids that do not exist in queueMap
for (LfgGuidList::iterator it = m_currentQueue.begin(); it != m_currentQueue.end();)
{
itGuidListRemove = it++;
if (m_QueueInfoMap.find(*itGuidListRemove) == m_QueueInfoMap.end())
{
eraseList.push_back(*itGuidListRemove);
m_newToQueue.erase(itGuidListRemove);
sLog.outError("LFGMgr::Cleaner: removing " UI64FMTD " from currentQueue, no queue info with that guid", *itGuidListRemove);
}
}
for (LfgGuidList::iterator it = eraseList.begin(); it != eraseList.end(); ++it)
{
if (IS_GROUP(*it))
{
if (Group *grp = sObjectMgr.GetGroupByGUID(GUID_LOPART(*it)))
for (GroupReference *itr = grp->GetFirstMember(); itr != NULL; itr = itr->next())
if (Player *plr = itr->getSource())
plr->GetSession()->SendLfgUpdateParty(LFG_UPDATETYPE_REMOVED_FROM_QUEUE);
}
else
if (Player *plr = sObjectMgr.GetPlayer(*it))
plr->GetSession()->SendLfgUpdatePlayer(LFG_UPDATETYPE_REMOVED_FROM_QUEUE);
}
}
void LFGMgr::Update(uint32 diff)
{
if (!m_update || !sWorld.getBoolConfig(CONFIG_DUNGEON_FINDER_ENABLE))
return;
m_update = false;
time_t currTime = time(NULL);
// Remove obsolete role checks
LfgRoleCheckMap::iterator itRoleCheck;
LfgRoleCheck *pRoleCheck;
for (LfgRoleCheckMap::iterator it = m_RoleChecks.begin(); it != m_RoleChecks.end();)
{
itRoleCheck = it++;
pRoleCheck = itRoleCheck->second;
if (currTime < pRoleCheck->cancelTime)
continue;
pRoleCheck->result = LFG_ROLECHECK_MISSING_ROLE;
WorldPacket data(SMSG_LFG_ROLE_CHECK_UPDATE, 4 + 1 + 1 + pRoleCheck->dungeons.size() * 4 + 1 + pRoleCheck->roles.size() * (8 + 1 + 4 + 1));
sLog.outDebug("SMSG_LFG_ROLE_CHECK_UPDATE");
BuildLfgRoleCheck(data, pRoleCheck);
Player *plr = NULL;
for (LfgRolesMap::const_iterator itRoles = pRoleCheck->roles.begin(); itRoles != pRoleCheck->roles.end(); ++itRoles)
{
plr = sObjectMgr.GetPlayer(itRoles->first);
if (!plr)
continue;
plr->GetSession()->SendPacket(&data);
plr->GetLfgDungeons()->clear();
plr->SetLfgRoles(ROLE_NONE);
if (itRoles->first == pRoleCheck->leader)
plr->GetSession()->SendLfgJoinResult(LFG_JOIN_FAILED, pRoleCheck->result);
}
delete pRoleCheck;
m_RoleChecks.erase(itRoleCheck);
}
// Remove obsolete proposals
LfgProposalMap::iterator itRemove;
for (LfgProposalMap::iterator it = m_Proposals.begin(); it != m_Proposals.end();)
{
itRemove = it++;
if (itRemove->second->cancelTime < currTime)
RemoveProposal(itRemove, LFG_UPDATETYPE_PROPOSAL_FAILED);
}
// Remove obsolete kicks
LfgPlayerBootMap::iterator itBoot;
LfgPlayerBoot *pBoot;
for (LfgPlayerBootMap::iterator it = m_Boots.begin(); it != m_Boots.end();)
{
itBoot = it++;
pBoot = itBoot->second;
if (pBoot->cancelTime < currTime)
{
Group *grp = sObjectMgr.GetGroupByGUID(itBoot->first);
pBoot->inProgress = false;
for (LfgAnswerMap::const_iterator itVotes = pBoot->votes.begin(); itVotes != pBoot->votes.end(); ++itVotes)
if (Player *plrg = sObjectMgr.GetPlayer(itVotes->first))
if (plrg->GetGUIDLow() != pBoot->victimLowGuid)
plrg->GetSession()->SendLfgBootPlayer(pBoot);
if (grp)
grp->SetLfgKickActive(false);
delete pBoot;
m_Boots.erase(itBoot);
}
}
// Consistency cleaner
Cleaner();
// Check if a proposal can be formed with the new groups being added
LfgProposalList proposals;
LfgGuidList firstNew;
while (!m_newToQueue.empty())
{
firstNew.push_back(m_newToQueue.front());
if (IS_GROUP(firstNew.front()))
CheckCompatibility(firstNew, &proposals); // Check if the group itself match
if (!proposals.size())
FindNewGroups(firstNew, m_currentQueue, &proposals);
if (proposals.size()) // Group found!
{
LfgProposal *pProposal = *proposals.begin();
// TODO: Create algorithm to select better group based on GS (uses to be good tank with bad healer and viceversa)
// Remove groups in the proposal from new and current queues (not from queue map)
for (LfgGuidList::const_iterator it = pProposal->queues.begin(); it != pProposal->queues.end(); ++it)
{
m_currentQueue.remove(*it);
m_newToQueue.remove(*it);
}
m_Proposals[++m_lfgProposalId] = pProposal;
uint32 lowGuid = 0;
for (LfgProposalPlayerMap::const_iterator itPlayers = pProposal->players.begin(); itPlayers != pProposal->players.end(); ++itPlayers)
{
lowGuid = itPlayers->first;
if (Player *plr = sObjectMgr.GetPlayer(itPlayers->first))
{
if (plr->GetGroup())
plr->GetSession()->SendLfgUpdateParty(LFG_UPDATETYPE_PROPOSAL_BEGIN);
else
plr->GetSession()->SendLfgUpdatePlayer(LFG_UPDATETYPE_PROPOSAL_BEGIN);
plr->GetSession()->SendUpdateProposal(m_lfgProposalId, pProposal);
}
}
if (pProposal->state == LFG_PROPOSAL_SUCCESS)
UpdateProposal(m_lfgProposalId, lowGuid, true);
// Clean up
for (LfgProposalList::iterator it = proposals.begin(); it != proposals.end(); ++it)
{
if ((*it) == pProposal) // Do not remove the selected proposal;
continue;
(*it)->queues.clear();
for (LfgProposalPlayerMap::iterator itPlayers = (*it)->players.begin(); itPlayers != (*it)->players.end(); ++itPlayers)
delete itPlayers->second;
(*it)->players.clear();
delete (*it);
}
proposals.clear();
}
else
{
m_currentQueue.push_back(m_newToQueue.front()); // Group not found, add this group to the queue.
m_newToQueue.pop_front();
}
firstNew.clear();
}
// Update all players status queue info
if (m_QueueTimer > LFG_QUEUEUPDATE_INTERVAL)
{
m_QueueTimer = 0;
time_t currTime = time(NULL);
int32 waitTime;
LfgQueueInfo *queue;
uint32 dungeonId;
uint32 queuedTime;
uint8 role;
for (LfgQueueInfoMap::const_iterator itQueue = m_QueueInfoMap.begin(); itQueue != m_QueueInfoMap.end(); ++itQueue)
{
queue = itQueue->second;
if (!queue)
{
sLog.outError("LFGMgr::Update: %s (lowguid: %u) queued with null queue info!", IS_GROUP(itQueue->first) ? "group" : "player", GUID_LOPART(itQueue->first));
continue;
}
dungeonId = *queue->dungeons.begin();
queuedTime = uint32(currTime - queue->joinTime);
role = ROLE_NONE;
for (LfgRolesMap::const_iterator itPlayer = queue->roles.begin(); itPlayer != queue->roles.end(); ++itPlayer)
role |= itPlayer->second;
waitTime = -1;
if (role & ROLE_TANK)
{
if (role & ROLE_HEALER || role & ROLE_DAMAGE)
waitTime = m_WaitTimeAvg;
else
waitTime = m_WaitTimeTank;
}
else if (role & ROLE_HEALER)
{
if (role & ROLE_DAMAGE)
waitTime = m_WaitTimeAvg;
else
waitTime = m_WaitTimeHealer;
}
else if (role & ROLE_DAMAGE)
waitTime = m_WaitTimeDps;
for (LfgRolesMap::const_iterator itPlayer = queue->roles.begin(); itPlayer != queue->roles.end(); ++itPlayer)
if (Player * plr = sObjectMgr.GetPlayer(itPlayer->first))
plr->GetSession()->SendLfgQueueStatus(dungeonId, waitTime, m_WaitTimeAvg, m_WaitTimeTank, m_WaitTimeHealer, m_WaitTimeDps, queuedTime, queue->tanks, queue->healers, queue->dps);
}
}
else
m_QueueTimer += diff;
m_update = true;
}
/// <summary>
/// Add a guid to new queue, checks consistency
/// </summary>
/// <param name="uint64">Player or group guid</param>
void LFGMgr::AddGuidToNewQueue(uint64 guid)
{
// Consistency check
LfgGuidList::const_iterator it;
for (it = m_newToQueue.begin(); it != m_newToQueue.end(); ++it)
{
if (*it == guid)
{
sLog.outError("LFGMgr::AddGuidToNewQueue: " UI64FMTD " being added to queue and it was already added. ignoring", guid);
break;
}
}
if (it == m_newToQueue.end())
{
LfgGuidList::iterator itRemove;
for (LfgGuidList::iterator it = m_currentQueue.begin(); it != m_currentQueue.end() && *it != guid;)
{
itRemove = it++;
if (*itRemove == guid)
{
sLog.outError("LFGMgr::AddGuidToNewQueue: " UI64FMTD " being added to queue and already in current queue (removing to readd)", guid);
m_currentQueue.erase(itRemove);
break;
}
}
// Add to queue
m_newToQueue.push_back(guid);
sLog.outDebug("LFGMgr::AddGuidToNewQueue: %u added to m_newToQueue (size: %u)", GUID_LOPART(guid), m_newToQueue.size());
}
}
/// <summary>
/// Creates a QueueInfo and adds it to the queue. Tries to match a group before joining.
/// </summary>
/// <param name="uint64">Player or group guid</param>
/// <param name="LfgRolesMap *">Player roles</param>
/// <param name="LfgDungeonSet *">Selected dungeons</param>
void LFGMgr::AddToQueue(uint64 guid, LfgRolesMap *roles, LfgDungeonSet *dungeons)
{
if (!roles || !roles->size() || !dungeons)
{
sLog.outError("LFGMgr::AddToQueue: " UI64FMTD " has no roles or no dungeons", guid);
return;
}
LfgQueueInfo *pqInfo = new LfgQueueInfo();
pqInfo->joinTime = time_t(time(NULL));
for (LfgRolesMap::const_iterator it = roles->begin(); it != roles->end(); ++it)
{
if (pqInfo->tanks && it->second & ROLE_TANK)
--pqInfo->tanks;
else if (pqInfo->healers && it->second & ROLE_HEALER)
--pqInfo->healers;
else
--pqInfo->dps;
}
for (LfgRolesMap::const_iterator itRoles = roles->begin(); itRoles != roles->end(); ++itRoles)
pqInfo->roles[itRoles->first] = itRoles->second;
LfgDungeonSet *expandedDungeons = dungeons;
if (isRandomDungeon(*dungeons->begin())) // Expand random dungeons
{
LfgDungeonMap dungeonMap;
dungeonMap[guid] = GetDungeonsByRandom(*dungeons->begin());
PlayerSet players;
Player *plr;
for (LfgRolesMap::const_iterator it = roles->begin(); it != roles->end(); ++it)
{
plr = sObjectMgr.GetPlayer(it->first);
if (plr)
players.insert(plr);
}
if (players.size() != roles->size())
{
sLog.outError("LFGMgr::AddToQueue: " UI64FMTD " has players %d offline. Can't join queue", guid, uint8(roles->size() - players.size()));
pqInfo->dungeons.clear();
pqInfo->roles.clear();
players.clear();
delete pqInfo;
return;
}
// Check restrictions
expandedDungeons = CheckCompatibleDungeons(&dungeonMap, &players);
players.clear();
}
for (LfgDungeonSet::const_iterator it = expandedDungeons->begin(); it != expandedDungeons->end(); ++it)
pqInfo->dungeons.insert(*it);
sLog.outDebug("LFGMgr::AddToQueue: " UI64FMTD " joining with %u members", guid, pqInfo->roles.size());
m_QueueInfoMap[guid] = pqInfo;
AddGuidToNewQueue(guid);
}
/// <summary>
/// Removes the player/group from all queues
/// </summary>
/// <param name="uint64">Player or group guid</param>
/// <returns>bool</returns>
bool LFGMgr::RemoveFromQueue(uint64 guid)
{
bool ret = false;
uint32 before = m_QueueInfoMap.size();
m_currentQueue.remove(guid);
m_newToQueue.remove(guid);
RemoveFromCompatibles(guid);
LfgQueueInfoMap::iterator it = m_QueueInfoMap.find(guid);
if (it != m_QueueInfoMap.end())
{
delete it->second;
m_QueueInfoMap.erase(it);
ret = true;
}
sLog.outDebug("LFGMgr::RemoveFromQueue: " UI64FMTD " %s - Queue(%u)", guid, before != m_QueueInfoMap.size() ? "Removed": "Not in queue", m_QueueInfoMap.size());
return ret;
}
/// <summary>
/// Adds the player/group to lfg queue
/// </summary>
/// <param name="Player *">Player</param>
void LFGMgr::Join(Player *plr)
{
Group *grp = plr->GetGroup();
if (grp && grp->GetLeaderGUID() != plr->GetGUID())
return;
uint64 guid = grp ? grp->GetGUID() : plr->GetGUID();
sLog.outDebug("LFGMgr::Join: %u joining with %u members", GUID_LOPART(guid), grp ? grp->GetMembersCount() : 1);
LfgJoinResult result = LFG_JOIN_OK;
// Previous checks before joining
LfgQueueInfoMap::iterator itQueue = m_QueueInfoMap.find(guid);
if (itQueue != m_QueueInfoMap.end())
{
result = LFG_JOIN_INTERNAL_ERROR;
sLog.outError("LFGMgr::Join: %s (lowguid: %u) trying to join but is already in queue!", grp ? "group" : "player", GUID_LOPART(guid));
}
else if (plr->InBattleground() || plr->InArena())
result = LFG_JOIN_USING_BG_SYSTEM;
else if (plr->HasAura(LFG_SPELL_DESERTER))
result = LFG_JOIN_DESERTER;
else if (plr->HasAura(LFG_SPELL_COOLDOWN))
result = LFG_JOIN_RANDOM_COOLDOWN;
else
{
// Check if all dungeons are valid
for (LfgDungeonSet::const_iterator it = plr->GetLfgDungeons()->begin(); it != plr->GetLfgDungeons()->end(); ++it)
{
if (!GetDungeonGroupType(*it))
{
result = LFG_JOIN_DUNGEON_INVALID;
break;
}
}
}
// Group checks
if (grp && result == LFG_JOIN_OK)
{
if (grp->GetMembersCount() > MAXGROUPSIZE)
result = LFG_JOIN_TOO_MUCH_MEMBERS;
else
{
Player *plrg;
uint8 memberCount = 0;
for (GroupReference *itr = grp->GetFirstMember(); itr != NULL && result == LFG_JOIN_OK; itr = itr->next())
{
plrg = itr->getSource();
if (plrg)
{
if (plrg->HasAura(LFG_SPELL_DESERTER))
result = LFG_JOIN_PARTY_DESERTER;
else if (plrg->HasAura(LFG_SPELL_COOLDOWN))
result = LFG_JOIN_PARTY_RANDOM_COOLDOWN;
++memberCount;
}
}
if (memberCount != grp->GetMembersCount())
result = LFG_JOIN_DISCONNECTED;
}
}
if (result != LFG_JOIN_OK) // Someone can't join. Clear all stuf
{
plr->GetLfgDungeons()->clear();
plr->SetLfgRoles(ROLE_NONE);
plr->GetSession()->SendLfgJoinResult(result, 0);
plr->GetSession()->SendLfgUpdateParty(LFG_UPDATETYPE_ROLECHECK_FAILED);
return;
}
if (grp)
{
Player *plrg = NULL;
LfgDungeonSet *dungeons;
for (GroupReference *itr = plr->GetGroup()->GetFirstMember(); itr != NULL; itr = itr->next())
{
plrg = itr->getSource(); // Not null, checked earlier
if (plrg != plr)
{
dungeons = plrg->GetLfgDungeons();
dungeons->clear();
for (LfgDungeonSet::const_iterator itDungeon = plr->GetLfgDungeons()->begin(); itDungeon != plr->GetLfgDungeons()->end(); ++itDungeon)
dungeons->insert(*itDungeon);
}
plrg->GetSession()->SendLfgUpdateParty(LFG_UPDATETYPE_JOIN_PROPOSAL);
}
UpdateRoleCheck(grp, plr);
}
else
{
plr->GetSession()->SendLfgJoinResult(LFG_JOIN_OK, 0);
plr->GetSession()->SendLfgUpdatePlayer(LFG_UPDATETYPE_JOIN_PROPOSAL);
LfgRolesMap roles;
roles[plr->GetGUIDLow()] = plr->GetLfgRoles();
AddToQueue(plr->GetGUID(), &roles, plr->GetLfgDungeons());
roles.clear();
}
}
/// <summary>
/// Leave the lfg queue
/// </summary>
/// <param name="Player *">Player (could be NULL)</param>
/// <param name="Group *">Group (could be NULL)</param>
void LFGMgr::Leave(Player *plr, Group *grp )
{
if (plr && !plr->GetLfgUpdate())
return;
uint64 guid = grp ? grp->GetGUID() : plr ? plr->GetGUID() : 0;
// Remove from Role Checks
if (grp)
{
grp->SetLfgQueued(false);
LfgRoleCheckMap::const_iterator itRoleCheck = m_RoleChecks.find(GUID_LOPART(guid));
if (itRoleCheck != m_RoleChecks.end())
{
UpdateRoleCheck(grp); // No player to update role = LFG_ROLECHECK_ABORTED
return;
}
}
// Remove from queue
RemoveFromQueue(guid);
// Remove from Proposals
for (LfgProposalMap::iterator it = m_Proposals.begin(); it != m_Proposals.end(); ++it)
{
// Mark the player/leader of group who left as didn't accept the proposal
for (LfgProposalPlayerMap::iterator itPlayer = it->second->players.begin(); itPlayer != it->second->players.end(); ++itPlayer)
if ((plr && itPlayer->first == plr->GetGUIDLow()) || (grp && itPlayer->first == GUID_LOPART(grp->GetLeaderGUID())))
itPlayer->second->accept = LFG_ANSWER_DENY;
}
if (grp)
{
for (GroupReference *itr = grp->GetFirstMember(); itr != NULL; itr = itr->next())
if (Player *plrg = itr->getSource())
{
plrg->GetSession()->SendLfgUpdateParty(LFG_UPDATETYPE_REMOVED_FROM_QUEUE);
plrg->GetLfgDungeons()->clear();
plrg->SetLfgRoles(ROLE_NONE);
}
}
else
{
plr->GetSession()->SendLfgUpdatePlayer(LFG_UPDATETYPE_REMOVED_FROM_QUEUE);
plr->GetLfgDungeons()->clear();
plr->SetLfgRoles(ROLE_NONE);
}
}
/// <summary>
/// Given a Lfg group checks if leader needs to be show the popup to select more players
/// </summary>
/// <param name="Group *">Group than needs new players</param>
void LFGMgr::OfferContinue(Group *grp)
{
if (grp && grp->GetLfgStatus() != LFG_STATUS_COMPLETE)
if (Player *leader = sObjectMgr.GetPlayer(grp->GetLeaderGUID()))
leader->GetSession()->SendLfgOfferContinue(grp->GetLfgDungeonEntry(false));
}
/// <summary>
/// Check the queue to try to match groups. Returns all the posible matches
/// </summary>
/// <param name="LfgGuidList &">Guids we trying to match with the rest of groups</param>
/// <param name="LfgGuidList">All guids in queue</param>
/// <param name="LfgProposalList *">Proposals found.</param>
void LFGMgr::FindNewGroups(LfgGuidList &check, LfgGuidList all, LfgProposalList *proposals)
{
ASSERT(proposals);
if (!check.size() || check.size() > MAXGROUPSIZE)
return;
sLog.outDebug("LFGMgr::FindNewGroup: (%s) - all(%s)", ConcatenateGuids(check).c_str(), ConcatenateGuids(all).c_str());
LfgGuidList compatibles;
// Check individual compatibilities
for (LfgGuidList::iterator it = all.begin(); it != all.end(); ++it)
{
check.push_back(*it);
if (CheckCompatibility(check, proposals))
compatibles.push_back(*it);
check.pop_back();
}
while (compatibles.size() > 1)
{
check.push_back(compatibles.front());
compatibles.pop_front();
FindNewGroups(check, compatibles, proposals);
check.pop_back();
}
}
/// <summary>
/// Check compatibilities between groups.
/// </summary>
/// <param name="LfgGuidList &">Guids we checking compatibility</param>
/// <returns>bool</returns>
/// <param name="LfgProposalList *">Proposals found.</param>
bool LFGMgr::CheckCompatibility(LfgGuidList check, LfgProposalList *proposals)
{
std::string strGuids = ConcatenateGuids(check);
if (check.size() > MAXGROUPSIZE || !check.size())
{
sLog.outDebug("LFGMgr::CheckCompatibility: (%s): Size wrong - Not compatibles", strGuids.c_str());
return false;
}
// No previous check have been done, do it now
uint8 numPlayers = 0;
uint8 numLfgGroups = 0;
uint32 groupLowGuid = 0;
LfgQueueInfoMap pqInfoMap;
LfgQueueInfoMap::iterator itQueue;
for (LfgGuidList::const_iterator it = check.begin(); it != check.end() && numLfgGroups < 2 && numPlayers <= MAXGROUPSIZE; ++it)
{
itQueue = m_QueueInfoMap.find(*it);
if (itQueue == m_QueueInfoMap.end())
{
sLog.outError("LFGMgr::CheckCompatibility: " UI64FMTD " is not queued but listed as queued!", *it);
return false;
}
pqInfoMap[*it] = itQueue->second;
numPlayers += itQueue->second->roles.size();
if (IS_GROUP(*it))
{
uint32 lowGuid = GUID_LOPART(*it);
if (Group *grp = sObjectMgr.GetGroupByGUID(lowGuid))
if (grp->isLFGGroup())
{
if (!numLfgGroups)
groupLowGuid = lowGuid;
++numLfgGroups;
}
}
}
if (check.size() == 1 && numPlayers != MAXGROUPSIZE) // Single group with less than MAXGROUPSIZE - Compatibles
return true;
if (check.size() > 1)
{
// Previously cached?
LfgAnswer answer = GetCompatibles(strGuids);
if (answer != LFG_ANSWER_PENDING)
{
if (numPlayers != MAXGROUPSIZE || answer == LFG_ANSWER_DENY)
{
sLog.outDebug("LFGMgr::CheckCompatibility: (%s) compatibles (cached): %d", strGuids.c_str(), answer);
return bool(answer);
}
// MAXGROUPSIZE + LFG_ANSWER_AGREE = Match - we don't have it cached so do calcs again
}
else if (check.size() > 2)
{
uint64 frontGuid = check.front();
check.pop_front();
// Check all-but-new compatibilities (New,A,B,C,D) --> check(A,B,C,D)
if (!CheckCompatibility(check, proposals)) // Group not compatible
{
sLog.outDebug("LFGMgr::CheckCompatibility: (%s) no compatibles (%s not compatibles)", strGuids.c_str(), ConcatenateGuids(check).c_str());
SetCompatibles(strGuids, false);
return false;
}
check.push_front(frontGuid);
// all-but-new compatibles, now check with new
}
}
// Do not match - groups already in a lfgDungeon or too much players
if (numLfgGroups > 1 || numPlayers > MAXGROUPSIZE)
{
pqInfoMap.clear();
SetCompatibles(strGuids, false);
if (numLfgGroups > 1)
sLog.outDebug("LFGMgr::CheckCompatibility: (%s) More than one Lfggroup (%u)", strGuids.c_str(), numLfgGroups);
else
sLog.outDebug("LFGMgr::CheckCompatibility: (%s) Too much players (%u)", strGuids.c_str(), numPlayers);
return false;
}
// ----- Player checks -----
LfgRolesMap rolesMap;
uint32 newLeaderLowGuid = 0;
for (LfgQueueInfoMap::const_iterator it = pqInfoMap.begin(); it != pqInfoMap.end(); ++it)
{
for (LfgRolesMap::const_iterator itRoles = it->second->roles.begin(); itRoles != it->second->roles.end(); ++itRoles)
{
// Assign new leader
if (itRoles->second & ROLE_LEADER && (!newLeaderLowGuid || urand(0, 1)))
newLeaderLowGuid = itRoles->first;
rolesMap[itRoles->first] = itRoles->second;
}
}
if (rolesMap.size() != numPlayers)
{
sLog.outError("LFGMgr::CheckCompatibility: There is a player multiple times in queue.");
pqInfoMap.clear();
rolesMap.clear();
return false;
}
Player *plr;
PlayerSet players;
for (LfgRolesMap::const_iterator it = rolesMap.begin(); it != rolesMap.end(); ++it)
{
plr = sObjectMgr.GetPlayer(it->first);
if (!plr)
sLog.outDebug("LFGMgr::CheckCompatibility: (%s) Warning! %u offline!", strGuids.c_str(), it->first);
for (PlayerSet::const_iterator itPlayer = players.begin(); itPlayer != players.end() && plr; ++itPlayer)
{
// Do not form a group with ignoring candidates
if (plr->GetSocial()->HasIgnore((*itPlayer)->GetGUIDLow()) || (*itPlayer)->GetSocial()->HasIgnore(plr->GetGUIDLow()))
plr = NULL;
// neither with diferent faction if it's not a mixed faction server
else if (plr->GetTeam() != (*itPlayer)->GetTeam() && !sWorld.getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP))
plr = NULL;
}
if (plr)
players.insert(plr);
}
// if we dont have the same ammount of players then we have self ignoring candidates or different faction groups
// otherwise check if roles are compatible
if (players.size() != numPlayers || !CheckGroupRoles(rolesMap))
{
if (players.size() != numPlayers)
sLog.outDebug("LFGMgr::CheckCompatibility: (%s) Player offline, ignoring or diff teams", strGuids.c_str());
else
sLog.outDebug("LFGMgr::CheckCompatibility: (%s) Roles not compatible", strGuids.c_str());
pqInfoMap.clear();
rolesMap.clear();
players.clear();
SetCompatibles(strGuids, false);
return false;
}
// ----- Selected Dungeon checks -----
// Check if there are any compatible dungeon from the selected dungeons
LfgDungeonMap dungeonMap;
for (LfgQueueInfoMap::const_iterator it = pqInfoMap.begin(); it != pqInfoMap.end(); ++it)
dungeonMap[it->first] = &it->second->dungeons;
LfgDungeonSet *compatibleDungeons = CheckCompatibleDungeons(&dungeonMap, &players);
dungeonMap.clear();
pqInfoMap.clear();
if (!compatibleDungeons || !compatibleDungeons->size())
{
if (compatibleDungeons)
delete compatibleDungeons;
players.clear();
rolesMap.clear();
SetCompatibles(strGuids, false);
return false;
}
SetCompatibles(strGuids, true);
// ----- Group is compatible, if we have MAXGROUPSIZE members then match is found
if (numPlayers != MAXGROUPSIZE)
{
players.clear();
rolesMap.clear();
sLog.outDebug("LFGMgr::CheckCompatibility: (%s) Compatibles but not match. Players(%u)", strGuids.c_str(), numPlayers);
return true;
}
sLog.outDebug("LFGMgr::CheckCompatibility: (%s) MATCH! Group formed", strGuids.c_str());
// Select a random dungeon from the compatible list
LfgDungeonSet::iterator itDungeon = compatibleDungeons->begin();
uint32 selectedDungeon = urand(0, compatibleDungeons->size() - 1);
while (selectedDungeon > 0)
{
++itDungeon;
--selectedDungeon;
}
selectedDungeon = *itDungeon;
compatibleDungeons->clear();
delete compatibleDungeons;
// Create a new proposal
LfgProposal *pProposal = new LfgProposal(selectedDungeon);
pProposal->cancelTime = time_t(time(NULL)) + LFG_TIME_PROPOSAL;
pProposal->queues = check;
pProposal->groupLowGuid = groupLowGuid;
// Assign new roles to players and assign new leader
LfgProposalPlayer *ppPlayer;
uint32 lowGuid;
PlayerSet::const_iterator itPlayers = players.begin();
if (!newLeaderLowGuid)
{
uint8 pos = urand(0, players.size() - 1);
for (uint8 i = 0; i < pos; ++i)
++itPlayers;
newLeaderLowGuid = (*itPlayers)->GetGUIDLow();
}
pProposal->leaderLowGuid = newLeaderLowGuid;
uint8 numAccept = 0;
for (itPlayers = players.begin(); itPlayers != players.end(); ++itPlayers)
{
lowGuid = (*itPlayers)->GetGUIDLow();
ppPlayer = new LfgProposalPlayer();
Group *grp = (*itPlayers)->GetGroup();
if (grp)
{
ppPlayer->groupLowGuid = grp->GetLowGUID();
if (grp->GetLfgDungeonEntry() == selectedDungeon && ppPlayer->groupLowGuid == pProposal->groupLowGuid) // Player from existing group, autoaccept
{
ppPlayer->accept = LFG_ANSWER_AGREE;
++numAccept;
}
}
ppPlayer->role = rolesMap[lowGuid];
pProposal->players[lowGuid] = ppPlayer;
}
if (numAccept == MAXGROUPSIZE)
pProposal->state = LFG_PROPOSAL_SUCCESS;
if (!proposals)
proposals = new LfgProposalList();
proposals->push_back(pProposal);
rolesMap.clear();
players.clear();
return true;
}
/// <summary>
/// Update the Role check info with the player selected role.
/// </summary>
/// <param name="Group *">Group</param>
/// <param name="Player *">Player (optional, default NULL)</param>
void LFGMgr::UpdateRoleCheck(Group *grp, Player *plr )
{
if (!grp)
return;
uint32 rolecheckId = grp->GetLowGUID();
LfgRoleCheck *pRoleCheck = NULL;
LfgRolesMap check_roles;
LfgRoleCheckMap::iterator itRoleCheck = m_RoleChecks.find(rolecheckId);
LfgDungeonSet *dungeons = plr->GetLfgDungeons();
bool newRoleCheck = itRoleCheck == m_RoleChecks.end();
if (newRoleCheck)
{
if (grp->GetLeaderGUID() != plr->GetGUID())
return;
pRoleCheck = new LfgRoleCheck();
pRoleCheck->cancelTime = time_t(time(NULL)) + LFG_TIME_ROLECHECK;
pRoleCheck->result = LFG_ROLECHECK_INITIALITING;
pRoleCheck->leader = plr->GetGUIDLow();
for (GroupReference *itr = grp->GetFirstMember(); itr != NULL; itr = itr->next())
if (Player *plrg = itr->getSource())
pRoleCheck->roles[plrg->GetGUIDLow()] = 0;
// Check if it's offer continue or trying to find a new instance after a random assigned (Join Random + LfgGroup)
if (grp->isLFGGroup() && dungeons->size() == 1 && isRandomDungeon(*dungeons->begin()) && grp->GetLfgDungeonEntry())
pRoleCheck->dungeons.insert(grp->GetLfgDungeonEntry());
else
for (LfgDungeonSet::const_iterator itDungeon = dungeons->begin(); itDungeon != dungeons->end(); ++itDungeon)
pRoleCheck->dungeons.insert(*itDungeon);
}
else
pRoleCheck = itRoleCheck->second;
LfgLockStatusMap *playersLockMap = NULL;
if (plr)
{
// Player selected no role.
if (plr->GetLfgRoles() < ROLE_TANK)
pRoleCheck->result = LFG_ROLECHECK_NO_ROLE;
else
{
// Check if all players have selected a role
pRoleCheck->roles[plr->GetGUIDLow()] = plr->GetLfgRoles();
uint8 size = 0;
for (LfgRolesMap::const_iterator itRoles = pRoleCheck->roles.begin(); itRoles != pRoleCheck->roles.end() && itRoles->second != ROLE_NONE; ++itRoles)
++size;
if (pRoleCheck->roles.size() == size)
{
// use temporal var to check roles, CheckGroupRoles modifies the roles
check_roles = pRoleCheck->roles;
if (!CheckGroupRoles(check_roles)) // Group is not posible
pRoleCheck->result = LFG_ROLECHECK_WRONG_ROLES;
else
{
// Check if we can find a dungeon for that group
pRoleCheck->result = LFG_ROLECHECK_FINISHED;
if (pRoleCheck->dungeons.size() > 1)
playersLockMap = GetPartyLockStatusDungeons(plr, &pRoleCheck->dungeons);
else
{
LfgDungeonSet::const_iterator it = pRoleCheck->dungeons.begin();
LFGDungeonEntry const *dungeon = sLFGDungeonStore.LookupEntry(*it);
if (dungeon && dungeon->type == LFG_TYPE_RANDOM)
playersLockMap = GetPartyLockStatusDungeons(plr, GetDungeonsByRandom(*it));
else
playersLockMap = GetPartyLockStatusDungeons(plr, &pRoleCheck->dungeons);
}
}
}
}
}
else
pRoleCheck->result = LFG_ROLECHECK_ABORTED;
WorldSession *session;
WorldPacket data(SMSG_LFG_ROLE_CHECK_UPDATE, 4 + 1 + 1 + pRoleCheck->dungeons.size() * 4 + 1 + pRoleCheck->roles.size() * (8 + 1 + 4 + 1));
sLog.outDebug("SMSG_LFG_ROLE_CHECK_UPDATE");
BuildLfgRoleCheck(data, pRoleCheck);
Player *plrg = NULL;
for (GroupReference *itr = grp->GetFirstMember(); itr != NULL; itr = itr->next())
{
plrg = itr->getSource();
if (!plrg)
continue;
session = plrg->GetSession();
if (!newRoleCheck && plr)
session->SendLfgRoleChosen(plr->GetGUID(), plr->GetLfgRoles());
session->SendPacket(&data);
switch(pRoleCheck->result)
{
case LFG_ROLECHECK_INITIALITING:
continue;
case LFG_ROLECHECK_FINISHED:
if (!playersLockMap)
session->SendLfgUpdateParty(LFG_UPDATETYPE_ADDED_TO_QUEUE);
else
{
if (grp->GetLeaderGUID() == plrg->GetGUID())
{
uint32 size = 0;
for (LfgLockStatusMap::const_iterator it = playersLockMap->begin(); it != playersLockMap->end(); ++it)
size += 8 + 4 + it->second->size() * (4 + 4);
WorldPacket data(SMSG_LFG_JOIN_RESULT, 4 + 4 + size);
sLog.outDebug("SMSG_LFG_JOIN_RESULT");
data << uint32(LFG_JOIN_PARTY_NOT_MEET_REQS); // Check Result
data << uint32(0); // Check Value (always 0 when PartyNotMeetReqs
BuildPartyLockDungeonBlock(data, playersLockMap);
session->SendPacket(&data);
}
session->SendLfgUpdateParty(LFG_UPDATETYPE_ROLECHECK_FAILED);
plrg->GetLfgDungeons()->clear();
plrg->SetLfgRoles(ROLE_NONE);
}
break;
default:
if (grp->GetLeaderGUID() == plrg->GetGUID())
session->SendLfgJoinResult(LFG_JOIN_FAILED, pRoleCheck->result);
session->SendLfgUpdateParty(LFG_UPDATETYPE_ROLECHECK_FAILED);
plrg->GetLfgDungeons()->clear();
plrg->SetLfgRoles(ROLE_NONE);
break;
}
}
if (pRoleCheck->result == LFG_ROLECHECK_FINISHED)
{
grp->SetLfgQueued(true);
AddToQueue(grp->GetGUID(), &pRoleCheck->roles, &pRoleCheck->dungeons);
}
if (pRoleCheck->result != LFG_ROLECHECK_INITIALITING)
{
pRoleCheck->dungeons.clear();
pRoleCheck->roles.clear();
delete pRoleCheck;
if (!newRoleCheck)
m_RoleChecks.erase(itRoleCheck);
}
else if (newRoleCheck)
m_RoleChecks[rolecheckId] = pRoleCheck;
}
/// <summary>
/// Remove from cached compatible dungeons any entry that contains the given guid
/// </summary>
/// <param name="uint64">guid to remove from any list</param>
void LFGMgr::RemoveFromCompatibles(uint64 guid)
{
LfgGuidList lista;
lista.push_back(guid);
std::string strGuid = ConcatenateGuids(lista);
lista.clear();
LfgCompatibleMap::iterator it;
for (LfgCompatibleMap::iterator itNext = m_CompatibleMap.begin(); itNext != m_CompatibleMap.end();)
{
it = itNext++;
if (it->first.find(strGuid) != std::string::npos) // Found, remove it
{
sLog.outDebug("LFGMgr::RemoveFromCompatibles: Removing " UI64FMTD " from (%s)", guid, it->first.c_str());
m_CompatibleMap.erase(it);
}
}
}
/// <summary>
/// Set the compatibility of a list of guids
/// </summary>
/// <param name="std::string">list of guids concatenated by |</param>
/// <param name="bool">compatibles or not</param>
void LFGMgr::SetCompatibles(std::string key, bool compatibles)
{
sLog.outDebug("LFGMgr::SetCompatibles: (%s): %d", key.c_str(), LfgAnswer(compatibles));
m_CompatibleMap[key] = LfgAnswer(compatibles);
}
/// <summary>
/// Get the compatible dungeons between two groups from cache
/// </summary>
/// <param name="std::string">list of guids concatenated by |</param>
/// <returns>LfgAnswer,
LfgAnswer LFGMgr::GetCompatibles(std::string key)
{
LfgAnswer answer = LFG_ANSWER_PENDING;
LfgCompatibleMap::iterator it = m_CompatibleMap.find(key);
if (it != m_CompatibleMap.end())
answer = it->second;
sLog.outDebug("LFGMgr::GetCompatibles: (%s): %d", key.c_str(), answer);
return answer;
}
/// <summary>
/// Given a list of groups checks the compatible dungeons. If players is not null also check restictions
/// </summary>
/// <param name="LfgDungeonMap *">dungeons to check</param>
/// <param name="PlayerSet *">Players to check restrictions</param>
/// <returns>LfgDungeonSet*</returns>
LfgDungeonSet* LFGMgr::CheckCompatibleDungeons(LfgDungeonMap *dungeonsMap, PlayerSet *players)
{
if (!dungeonsMap || dungeonsMap->empty())
return NULL;
LfgDungeonMap::const_iterator itMap = ++dungeonsMap->begin();
LfgDungeonSet *compatibleDungeons = new LfgDungeonSet();
bool compatibleDungeon;
// Get the first group and compare with the others to select all common dungeons
for (LfgDungeonSet::const_iterator itDungeon = dungeonsMap->begin()->second->begin(); itDungeon != dungeonsMap->begin()->second->end(); ++itDungeon)
{
compatibleDungeon = true;
for (LfgDungeonMap::const_iterator it = itMap; it != dungeonsMap->end() && compatibleDungeon; ++it)
if (it->second->find(*itDungeon) == it->second->end())
compatibleDungeon = false;
if (compatibleDungeon)
compatibleDungeons->insert(*itDungeon);
}
if (players && !players->empty())
{
// now remove those with restrictions
LfgLockStatusMap *pLockDungeons = GetGroupLockStatusDungeons(players, compatibleDungeons, false);
if (pLockDungeons) // Found dungeons not compatible, remove them from the set
{
LfgLockStatusSet *pLockSet = NULL;
LfgDungeonSet::iterator itDungeon;
for (LfgLockStatusMap::const_iterator itLockMap = pLockDungeons->begin(); itLockMap != pLockDungeons->end() && compatibleDungeons->size(); ++itLockMap)
{
pLockSet = itLockMap->second;
for(LfgLockStatusSet::const_iterator itLockSet = pLockSet->begin(); itLockSet != pLockSet->end(); ++itLockSet)
{
itDungeon = compatibleDungeons->find((*itLockSet)->dungeon);
if (itDungeon != compatibleDungeons->end())
compatibleDungeons->erase(itDungeon);
}
pLockSet->clear();
delete pLockSet;
}
pLockDungeons->clear();
delete pLockDungeons;
}
}
// Any compatible dungeon after checking restrictions?
if (!compatibleDungeons->size())
{
delete compatibleDungeons;
compatibleDungeons = NULL;
}
return compatibleDungeons;
}
/// <summary>
/// Check if a group can be formed with the given group
/// </summary>
/// <param name="LfgRolesMap &">Roles to check</param>
/// <param name="bool">Used to remove ROLE_LEADER</param>
/// <returns>bool</returns>
bool LFGMgr::CheckGroupRoles(LfgRolesMap &groles, bool removeLeaderFlag )
{
if (!groles.size())
return false;
uint8 damage = 0;
uint8 tank = 0;
uint8 healer = 0;
if (removeLeaderFlag)
for (LfgRolesMap::iterator it = groles.begin(); it != groles.end(); ++it)
it->second &= ~ROLE_LEADER;
for (LfgRolesMap::iterator it = groles.begin(); it != groles.end(); ++it)
{
switch(it->second)
{
case ROLE_NONE:
return false;
case ROLE_TANK:
if (tank == LFG_TANKS_NEEDED)
return false;
tank++;
break;
case ROLE_HEALER:
if (healer == LFG_HEALERS_NEEDED)
return false;
healer++;
break;
case ROLE_DAMAGE:
if (damage == LFG_DPS_NEEDED)
return false;
damage++;
break;
default:
if (it->second & ROLE_TANK)
{
it->second -= ROLE_TANK;
if (CheckGroupRoles(groles, false))
return true;
it->second += ROLE_TANK;
}
if (it->second & ROLE_HEALER)
{
it->second -= ROLE_HEALER;
if (CheckGroupRoles(groles, false))
return true;
it->second += ROLE_HEALER;
}
if (it->second & ROLE_DAMAGE)
{
it->second -= ROLE_DAMAGE;
return CheckGroupRoles(groles, false);
}
break;
}
}
return true;
}
/// <summary>
/// Update Proposal info with player answer
/// </summary>
/// <param name="uint32">Id of the proposal</param>
/// <param name="uint32">Player low guid</param>
/// <param name="bool">Player answer</param>
void LFGMgr::UpdateProposal(uint32 proposalId, uint32 lowGuid, bool accept)
{
// Check if the proposal exists
LfgProposalMap::iterator itProposal = m_Proposals.find(proposalId);
if (itProposal == m_Proposals.end())
return;
LfgProposal *pProposal = itProposal->second;
// Check if proposal have the current player
LfgProposalPlayerMap::iterator itProposalPlayer = pProposal->players.find(lowGuid);
if (itProposalPlayer == pProposal->players.end())
return;
LfgProposalPlayer *ppPlayer = itProposalPlayer->second;
ppPlayer->accept = LfgAnswer(accept);
if (!accept)
{
RemoveProposal(itProposal, LFG_UPDATETYPE_PROPOSAL_DECLINED);
return;
}
LfgPlayerList players;
Player *plr;
// check if all have answered and reorder players (leader first)
bool allAnswered = true;
for (LfgProposalPlayerMap::const_iterator itPlayers = pProposal->players.begin(); itPlayers != pProposal->players.end(); ++itPlayers)
{
plr = sObjectMgr.GetPlayer(itPlayers->first);
if (plr)
{
if (itPlayers->first == pProposal->leaderLowGuid)
players.push_front(plr);
else
players.push_back(plr);
}
if (itPlayers->second->accept != LFG_ANSWER_AGREE) // No answer (-1) or not accepted (0)
allAnswered = false;
}
if (!allAnswered)
{
for (LfgPlayerList::const_iterator it = players.begin(); it != players.end(); ++it)
(*it)->GetSession()->SendUpdateProposal(proposalId, pProposal);
}
else
{
bool sendUpdate = pProposal->state != LFG_PROPOSAL_SUCCESS;
pProposal->state = LFG_PROPOSAL_SUCCESS;
time_t joinTime = time_t(time(NULL));
uint8 role = 0;
int32 waitTime = -1;
LfgQueueInfoMap::iterator itQueue;
uint64 guid = 0;
// Create a new group (if needed)
Group *grp = sObjectMgr.GetGroupByGUID(pProposal->groupLowGuid);
for (LfgPlayerList::const_iterator it = players.begin(); it != players.end(); ++it)
{
plr = *it;
if (sendUpdate)
plr->GetSession()->SendUpdateProposal(proposalId, pProposal);
plr->SetLfgUpdate(false);
if (plr->GetGroup())
{
guid = plr->GetGroup()->GetGUID();
plr->GetSession()->SendLfgUpdateParty(LFG_UPDATETYPE_GROUP_FOUND);
if (plr->GetGroup() != grp)
plr->RemoveFromGroup();
}
else
{
guid = plr->GetGUID();
plr->GetSession()->SendLfgUpdatePlayer(LFG_UPDATETYPE_GROUP_FOUND);
}
if (!grp)
{
grp = new Group();
grp->Create(plr->GetGUID(), plr->GetName());
grp->ConvertToLFG();
sObjectMgr.AddGroup(grp);
}
else if (plr->GetGroup() != grp)
{
grp->SetLfgQueued(false);
grp->AddMember(plr->GetGUID(), plr->GetName());
}
plr->SetLfgUpdate(true);
// Update timers
role = plr->GetLfgRoles();
itQueue = m_QueueInfoMap.find(guid);
if (itQueue == m_QueueInfoMap.end())
{
sLog.outError("LFGMgr::UpdateProposal: Queue info for guid " UI64FMTD " not found!", guid);
waitTime = -1;
}
else
{
waitTime = int32(joinTime - itQueue->second->joinTime);
if (role & ROLE_TANK)
{
if (role & ROLE_HEALER || role & ROLE_DAMAGE)
m_WaitTimeAvg = int32((m_WaitTimeAvg * m_NumWaitTimeAvg + waitTime) / ++m_NumWaitTimeAvg);
else
m_WaitTimeTank = int32((m_WaitTimeTank * m_NumWaitTimeTank + waitTime) / ++m_NumWaitTimeTank);
}
else if (role & ROLE_HEALER)
{
if (role & ROLE_DAMAGE)
m_WaitTimeAvg = int32((m_WaitTimeAvg * m_NumWaitTimeAvg + waitTime) / ++m_NumWaitTimeAvg);
else
m_WaitTimeHealer = int32((m_WaitTimeHealer * m_NumWaitTimeHealer + waitTime) / ++m_NumWaitTimeHealer);
}
else if (role & ROLE_DAMAGE)
m_WaitTimeDps = int32((m_WaitTimeDps * m_NumWaitTimeDps + waitTime) / ++m_NumWaitTimeDps);
}
grp->SetLfgRoles(plr->GetGUID(), pProposal->players[plr->GetGUIDLow()]->role);
}
// Set the dungeon difficulty
LFGDungeonEntry const *dungeon = sLFGDungeonStore.LookupEntry(pProposal->dungeonId);
ASSERT(dungeon);
grp->SetDungeonDifficulty(Difficulty(dungeon->difficulty));
grp->SetLfgDungeonEntry(dungeon->Entry());
grp->SetLfgStatus(LFG_STATUS_NOT_SAVED);
grp->SendUpdate();
// Remove players/groups from Queue
for (LfgGuidList::const_iterator it = pProposal->queues.begin(); it != pProposal->queues.end(); ++it)
RemoveFromQueue(*it);
// Teleport Player
for (LfgPlayerList::const_iterator it = players.begin(); it != players.end(); ++it)
TeleportPlayer(*it, false);
for (LfgProposalPlayerMap::const_iterator it = pProposal->players.begin(); it != pProposal->players.end(); ++it)
delete it->second;
pProposal->players.clear();
pProposal->queues.clear();
delete pProposal;
m_Proposals.erase(itProposal);
}
players.clear();
}
/// <summary>
/// Remove a proposal from the pool, remove the group that didn't accept (if needed) and readd the other members to the queue
/// </summary>
/// <param name="LfgProposalMap::iterator">Proposal to remove</param>
/// <param name="LfgUpdateType">Type of removal (LFG_UPDATETYPE_PROPOSAL_FAILED, LFG_UPDATETYPE_PROPOSAL_DECLINED)</param>
void LFGMgr::RemoveProposal(LfgProposalMap::iterator itProposal, LfgUpdateType type)
{
Player *plr;
uint64 guid;
LfgUpdateType updateType;
LfgQueueInfoMap::iterator itQueue;
LfgProposal *pProposal = itProposal->second;
pProposal->state = LFG_PROPOSAL_FAILED;
// Mark all people that didn't answered as no accept
if (type == LFG_UPDATETYPE_PROPOSAL_FAILED)
for (LfgProposalPlayerMap::const_iterator it = pProposal->players.begin(); it != pProposal->players.end(); ++it)
if (it->second->accept != LFG_ANSWER_AGREE)
it->second->accept = LFG_ANSWER_DENY;
// Inform players
for (LfgProposalPlayerMap::const_iterator it = pProposal->players.begin(); it != pProposal->players.end(); ++it)
{
plr = sObjectMgr.GetPlayer(it->first);
if (!plr)
continue;
guid = plr->GetGroup() ? plr->GetGroup()->GetGUID(): plr->GetGUID();
plr->GetSession()->SendUpdateProposal(itProposal->first, pProposal);
// Remove members that didn't accept
itQueue = m_QueueInfoMap.find(guid);
if (it->second->accept == LFG_ANSWER_DENY)
{
updateType = type;
plr->GetLfgDungeons()->clear();
plr->SetLfgRoles(ROLE_NONE);
if (itQueue != m_QueueInfoMap.end())
m_QueueInfoMap.erase(itQueue);
RemoveFromCompatibles(guid);
}
else // Readd to queue
{
if (itQueue == m_QueueInfoMap.end()) // Can't readd! misssing queue info!
updateType = LFG_UPDATETYPE_REMOVED_FROM_QUEUE;
else
{
itQueue->second->joinTime = time_t(time(NULL));
AddGuidToNewQueue(guid);
updateType = LFG_UPDATETYPE_ADDED_TO_QUEUE;
}
}
if (plr->GetGroup())
plr->GetSession()->SendLfgUpdateParty(updateType);
else
plr->GetSession()->SendLfgUpdatePlayer(updateType);
}
for (LfgProposalPlayerMap::const_iterator it = pProposal->players.begin(); it != pProposal->players.end(); ++it)
delete it->second;
pProposal->players.clear();
pProposal->queues.clear();
delete pProposal;
m_Proposals.erase(itProposal);
}
/// <summary>
/// Initialize a boot kick vote
/// </summary>
/// <param name="Group *">Group</param>
/// <param name="uint32">Player low guid who inits the vote kick</param>
/// <param name="uint32">Player low guid to be kicked </param>
/// <param name="std::string">kick reason</param>
void LFGMgr::InitBoot(Group *grp, uint32 iLowGuid, uint32 vLowguid, std::string reason)
{
if (!grp)
return;
LfgPlayerBoot *pBoot = new LfgPlayerBoot();
pBoot->inProgress = true;
pBoot->cancelTime = time_t(time(NULL)) + LFG_TIME_BOOT;
pBoot->reason = reason;
pBoot->victimLowGuid = vLowguid;
pBoot->votedNeeded = GROUP_LFG_KICK_VOTES_NEEDED;
PlayerSet players;
uint32 pLowGuid = 0;
for (GroupReference *itr = grp->GetFirstMember(); itr != NULL; itr = itr->next())
{
if (Player *plrg = itr->getSource())
{
pLowGuid = plrg->GetGUIDLow();
if (pLowGuid == vLowguid)
pBoot->votes[pLowGuid] = LFG_ANSWER_DENY; // Victim auto vote NO
else if (pLowGuid == iLowGuid)
pBoot->votes[pLowGuid] = LFG_ANSWER_AGREE; // Kicker auto vote YES
else
{
pBoot->votes[pLowGuid] = LFG_ANSWER_PENDING;// Other members need to vote
players.insert(plrg);
}
}
}
for (PlayerSet::const_iterator it = players.begin(); it != players.end(); ++it)
(*it)->GetSession()->SendLfgBootPlayer(pBoot);
grp->SetLfgKickActive(true);
m_Boots[grp->GetLowGUID()] = pBoot;
}
/// <summary>
/// Update Boot info with player answer
/// </summary>
/// <param name="Player *">Player guid</param>
/// <param name="bool">Player answer</param>
void LFGMgr::UpdateBoot(Player *plr, bool accept)
{
Group *grp = plr ? plr->GetGroup() : NULL;
if (!grp)
return;
uint32 bootId = grp->GetLowGUID();
uint32 lowGuid = plr->GetGUIDLow();
LfgPlayerBootMap::iterator itBoot = m_Boots.find(bootId);
if (itBoot == m_Boots.end())
return;
LfgPlayerBoot *pBoot = itBoot->second;
if (!pBoot)
return;
if (pBoot->votes[lowGuid] != LFG_ANSWER_PENDING) // Cheat check: Player can't vote twice
return;
pBoot->votes[lowGuid] = LfgAnswer(accept);
uint8 votesNum = 0;
uint8 agreeNum = 0;
for (LfgAnswerMap::const_iterator itVotes = pBoot->votes.begin(); itVotes != pBoot->votes.end(); ++itVotes)
{
if (itVotes->second != LFG_ANSWER_PENDING)
{
++votesNum;
if (itVotes->second == LFG_ANSWER_AGREE)
++agreeNum;
}
}
if (agreeNum == pBoot->votedNeeded || // Vote passed
votesNum == pBoot->votes.size() || // All voted but not passed
(pBoot->votes.size() - votesNum + agreeNum) < pBoot->votedNeeded) // Vote didnt passed
{
// Send update info to all players
pBoot->inProgress = false;
for (LfgAnswerMap::const_iterator itVotes = pBoot->votes.begin(); itVotes != pBoot->votes.end(); ++itVotes)
if (Player *plrg = sObjectMgr.GetPlayer(itVotes->first))
if (plrg->GetGUIDLow() != pBoot->victimLowGuid)
plrg->GetSession()->SendLfgBootPlayer(pBoot);
if (agreeNum == pBoot->votedNeeded) // Vote passed - Kick player
{
Player::RemoveFromGroup(grp, MAKE_NEW_GUID(pBoot->victimLowGuid, 0, HIGHGUID_PLAYER));
if (Player *victim = sObjectMgr.GetPlayer(pBoot->victimLowGuid))
victim->TeleportToBGEntryPoint();
OfferContinue(grp);
grp->SetLfgKicks(grp->GetLfgKicks() + 1);
}
grp->SetLfgKickActive(false);
delete pBoot;
m_Boots.erase(itBoot);
}
}
/// <summary>
/// Teleports the player in or out the dungeon
/// </summary>
/// <param name="Player *">Player</param>
/// <param name="bool">Teleport out</param>
void LFGMgr::TeleportPlayer(Player *plr, bool out)
{
if (out)
{
plr->TeleportToBGEntryPoint();
return;
}
if (!plr->isAlive())
{
plr->GetSession()->SendLfgTeleportError(LFG_TELEPORTERROR_PLAYER_DEAD);
return;
}
if (plr->IsFalling() || plr->hasUnitState(UNIT_STAT_JUMPING))
{
plr->GetSession()->SendLfgTeleportError(LFG_TELEPORTERROR_FALLING);
return;
}
// TODO Add support for LFG_TELEPORTERROR_FATIGUE and LFG_TELEPORTERROR_INVALID_LOCATION
if (Group *grp = plr->GetGroup())
if (LFGDungeonEntry const *dungeon = sLFGDungeonStore.LookupEntry(grp->GetLfgDungeonEntry()))
if (AreaTrigger const* at = sObjectMgr.GetMapEntranceTrigger(dungeon->map))
{
if (!plr->GetMap()->IsDungeon() && !plr->GetMap()->IsRaid())
plr->SetBattlegroundEntryPoint();
plr->RemoveAurasByType(SPELL_AURA_MOUNTED);
// TODO: Teleport to group
plr->TeleportTo(at->target_mapId, at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
}
}
/// <summary>
/// Give completion reward to player
/// </summary>
/// <param name="const uint32">dungeonId</param>
/// <param name="Player *">player</param>
void LFGMgr::RewardDungeonDoneFor(const uint32 dungeonId, Player *player)
{
Group* group = player->GetGroup();
if (!group || !group->isLFGGroup())
return;
// Mark dungeon as finished
if (!group->isLfgDungeonComplete())
group->SetLfgStatus(LFG_STATUS_COMPLETE);
// Clear player related lfg stuff
uint32 rDungeonId = *player->GetLfgDungeons()->begin();
player->GetLfgDungeons()->clear();
player->SetLfgRoles(ROLE_NONE);
// Give rewards only if its a random dungeon
LFGDungeonEntry const *dungeon = sLFGDungeonStore.LookupEntry(dungeonId);
if (!dungeon || dungeon->type != LFG_TYPE_RANDOM)
return;
// Mark random dungeon as complete
uint8 index = player->isLfgDungeonDone(rDungeonId) ? 1 : 0;
if (!index)
player->SetLfgDungeonDone(rDungeonId);
// Update achievements
if (dungeon->difficulty == DUNGEON_DIFFICULTY_HEROIC)
player->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_USE_LFD_TO_GROUP_WITH_PLAYERS, 1);
LfgReward const* reward = GetRandomDungeonReward(rDungeonId, player->getLevel());
if (!reward)
return;
Quest const* qReward = sObjectMgr.GetQuestTemplate(reward->reward[index].questId);
if (!qReward)
return;
// Give rewards
player->GetSession()->SendLfgPlayerReward(dungeon->Entry(), group->GetLfgDungeonEntry(false), index, reward, qReward);
if (qReward->GetRewItemsCount() > 0)
{
for (uint32 i = 0; i < QUEST_REWARDS_COUNT; ++i)
{
if (uint32 itemId = qReward->RewItemId[i])
{
ItemPosCountVec dest;
if (player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, itemId, qReward->RewItemCount[i]) == EQUIP_ERR_OK)
{
Item* item = player->StoreNewItem(dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
player->SendNewItem(item, qReward->RewItemCount[i], true, false);
}
}
}
}
// Not give XP in case already completed once repeatable quest
uint32 XP = uint32(qReward->XPValue(player) * sWorld.getRate(RATE_XP_QUEST));
XP += (MAXGROUPSIZE - group->GetMembersCount()) * reward->reward[index].variableXP;
// Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
int32 moneyRew = qReward->GetRewOrReqMoney();
if (player->getLevel() < sWorld.getIntConfig(CONFIG_MAX_PLAYER_LEVEL))
player->GiveXP(XP, NULL);
else
moneyRew += int32(qReward->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY));
moneyRew += (MAXGROUPSIZE - group->GetMembersCount()) * reward->reward[index].variableMoney;
if (moneyRew)
player->ModifyMoney(moneyRew);
}
// --------------------------------------------------------------------------//
// Packet Functions
// --------------------------------------------------------------------------//
/// <summary>
/// Build lfgRolecheck packet
/// </summary>
/// <param name="WorldPacket &">WorldPacket</param>
/// <param name="LfgRoleCheck *">RoleCheck info</param>
void LFGMgr::BuildLfgRoleCheck(WorldPacket &data, LfgRoleCheck *pRoleCheck)
{
ASSERT(pRoleCheck);
Player *plr;
uint8 roles;
data << uint32(pRoleCheck->result); // Check result
data << uint8(pRoleCheck->result == LFG_ROLECHECK_INITIALITING);
data << uint8(pRoleCheck->dungeons.size()); // Number of dungeons
LFGDungeonEntry const *dungeon;
for (LfgDungeonSet::iterator it = pRoleCheck->dungeons.begin(); it != pRoleCheck->dungeons.end(); ++it)
{
dungeon = sLFGDungeonStore.LookupEntry(*it); // not null - been checked at join time
if (!dungeon)
{
sLog.outError("LFGMgr::BuildLfgRoleCheck: Dungeon %u does not exist in dbcs", *it);
data << uint32(0);
}
else
data << uint32(dungeon->Entry()); // Dungeon
}
data << uint8(pRoleCheck->roles.size()); // Players in group
// Leader info MUST be sent 1st :S
roles = pRoleCheck->roles[pRoleCheck->leader];
uint64 guid = MAKE_NEW_GUID(pRoleCheck->leader, 0, HIGHGUID_PLAYER);
data << uint64(guid); // Guid
data << uint8(roles > 0); // Ready
data << uint32(roles); // Roles
plr = sObjectMgr.GetPlayer(guid);
data << uint8(plr ? plr->getLevel() : 0); // Level
for (LfgRolesMap::const_iterator itPlayers = pRoleCheck->roles.begin(); itPlayers != pRoleCheck->roles.end(); ++itPlayers)
{
if (itPlayers->first == pRoleCheck->leader)
continue;
roles = itPlayers->second;
guid = MAKE_NEW_GUID(itPlayers->first, 0, HIGHGUID_PLAYER);
data << uint64(guid); // Guid
data << uint8(roles > 0); // Ready
data << uint32(roles); // Roles
plr = sObjectMgr.GetPlayer(guid);
data << uint8(plr ? plr->getLevel() : 0); // Level
}
}
/// <summary>
/// Build Party Dungeon lock status packet
/// </summary>
/// <param name="WorldPacket &">WorldPacket</param>
/// <param name="LfgLockStatusMap *">lock status map</param>
void LFGMgr::BuildPartyLockDungeonBlock(WorldPacket &data, LfgLockStatusMap *lockMap)
{
if (!lockMap || !lockMap->size())
{
data << uint8(0);
return;
}
data << uint8(lockMap->size());
for (LfgLockStatusMap::const_iterator it = lockMap->begin(); it != lockMap->end(); ++it)
{
data << uint64(MAKE_NEW_GUID(it->first, 0, HIGHGUID_PLAYER)); // Player guid
BuildPlayerLockDungeonBlock(data, it->second);
}
lockMap->clear();
delete lockMap;
}
/// <summary>
/// Build Player Dungeon lock status packet
/// </summary>
/// <param name="WorldPacket &">WorldPacket</param>
/// <param name="LfgLockStatusSet *">lock status list</param>
void LFGMgr::BuildPlayerLockDungeonBlock(WorldPacket &data, LfgLockStatusSet *lockSet)
{
if (!lockSet || !lockSet->size())
{
data << uint8(0);
return;
}
data << uint32(lockSet->size()); // Size of lock dungeons
for (LfgLockStatusSet::iterator it = lockSet->begin(); it != lockSet->end(); ++it)
{
data << uint32((*it)->dungeon); // Dungeon entry + type
data << uint32((*it)->lockstatus); // Lock status
delete (*it);
}
lockSet->clear();
delete lockSet;
}
// --------------------------------------------------------------------------//
// Auxiliar Functions
// --------------------------------------------------------------------------//
/// <summary>
/// Given a group get the dungeons that can't be done and reason
/// </summary>
/// <param name="PlayerSet *">Players to check lock status</param>
/// <param name="LfgDungeonSet *">Dungeons to check</param>
/// <param name="bool">Use dungeon entry (true) or id (false)</param>
/// <returns>LfgLockStatusMap*</returns>
LfgLockStatusMap* LFGMgr::GetGroupLockStatusDungeons(PlayerSet *pPlayers, LfgDungeonSet *dungeons, bool useEntry )
{
if (!pPlayers || !dungeons)
return NULL;
LfgLockStatusSet *dungeonSet = NULL;
LfgLockStatusMap *dungeonMap = new LfgLockStatusMap();
for (PlayerSet::const_iterator itr = pPlayers->begin(); itr != pPlayers->end(); ++itr)
{
dungeonSet = GetPlayerLockStatusDungeons(*itr, dungeons, useEntry);
if (dungeonSet)
(*dungeonMap)[(*itr)->GetGUIDLow()] = dungeonSet;
}
if (!dungeonMap->size())
{
delete dungeonMap;
dungeonMap = NULL;
}
return dungeonMap;
}
/// <summary>
/// Get all Group members list of dungeons that can't be done and reason
/// leader excluded as the list given is he list he can do
/// </summary>
/// <param name="Player *">Player to get Party Lock info</param>
/// <param name="LfgDungeonSet *">Dungeons to check</param>
/// <returns>LfgLockStatusMap*</returns>
LfgLockStatusMap* LFGMgr::GetPartyLockStatusDungeons(Player *plr, LfgDungeonSet *dungeons )
{
if (!plr)
return NULL;
if (!dungeons)
dungeons = GetAllDungeons();
Group *grp = plr->GetGroup();
if (!grp)
return NULL;
PlayerSet *pPlayers = new PlayerSet();
Player *plrg;
for (GroupReference *itr = grp->GetFirstMember(); itr != NULL; itr = itr->next())
{
plrg = itr->getSource();
if (plrg && plrg != plr)
pPlayers->insert(plrg);
}
LfgLockStatusMap *dungeonMap = GetGroupLockStatusDungeons(pPlayers, dungeons);
pPlayers->clear();
delete pPlayers;
return dungeonMap;
}
/// <summary>
/// Get list of dungeons player can't do and reasons
/// </summary>
/// <param name="Player *">Player to check lock status</param>
/// <param name="LfgDungeonSet *">Dungeons to check</param>
/// <param name="bool">Use dungeon entry (true) or id (false)</param>
/// <returns>LfgLockStatusSet*</returns>
LfgLockStatusSet* LFGMgr::GetPlayerLockStatusDungeons(Player *plr, LfgDungeonSet *dungeons , bool useEntry )
{
LfgLockStatusSet *list = new LfgLockStatusSet();
LfgLockStatus *lockstatus = NULL;
LFGDungeonEntry const *dungeon;
LfgLockStatusType locktype;
uint8 level = plr->getLevel();
uint8 expansion = plr->GetSession()->Expansion();
AccessRequirement const* ar;
if (!dungeons)
dungeons = GetAllDungeons();
for (LfgDungeonSet::const_iterator it = dungeons->begin(); it != dungeons->end(); ++it)
{
dungeon = sLFGDungeonStore.LookupEntry(*it);
if (!dungeon) // should never happen - We provide a list from sLFGDungeonStore
continue;
ar = sObjectMgr.GetAccessRequirement(dungeon->map, Difficulty(dungeon->difficulty));
locktype = LFG_LOCKSTATUS_OK;
if (dungeon->expansion > expansion)
locktype = LFG_LOCKSTATUS_INSUFFICIENT_EXPANSION;
else if (sDisableMgr.IsDisabledFor(DISABLE_TYPE_MAP, dungeon->map, plr))
locktype = LFG_LOCKSTATUS_RAID_LOCKED;
else if (dungeon->difficulty > DUNGEON_DIFFICULTY_NORMAL && plr->GetBoundInstance(dungeon->map, Difficulty(dungeon->difficulty)))
locktype = LFG_LOCKSTATUS_RAID_LOCKED;
else if (dungeon->minlevel > level)
locktype = LFG_LOCKSTATUS_TOO_LOW_LEVEL;
else if (dungeon->maxlevel < level)
locktype = LFG_LOCKSTATUS_TOO_HIGH_LEVEL;
else if (locktype == LFG_LOCKSTATUS_OK && ar)
{
if (ar->achievement && !plr->GetAchievementMgr().HasAchieved(sAchievementStore.LookupEntry(ar->achievement)))
locktype = LFG_LOCKSTATUS_RAID_LOCKED; // FIXME: Check the correct lock value
else if (plr->GetTeam() == ALLIANCE && ar->quest_A && !plr->GetQuestRewardStatus(ar->quest_A))
locktype = LFG_LOCKSTATUS_QUEST_NOT_COMPLETED;
else if (plr->GetTeam() == HORDE && ar->quest_H && !plr->GetQuestRewardStatus(ar->quest_H))
locktype = LFG_LOCKSTATUS_QUEST_NOT_COMPLETED;
else
if (ar->item)
{
if (!plr->HasItemCount(ar->item, 1) && (!ar->item2 || !plr->HasItemCount(ar->item2, 1)))
locktype = LFG_LOCKSTATUS_MISSING_ITEM;
}
else if (ar->item2 && !plr->HasItemCount(ar->item2, 1))
locktype = LFG_LOCKSTATUS_MISSING_ITEM;
}
if (locktype != LFG_LOCKSTATUS_OK)
{
lockstatus = new LfgLockStatus();
lockstatus->dungeon = useEntry ? dungeon->Entry(): dungeon->ID;
lockstatus->lockstatus = locktype;
list->insert(lockstatus);
}
}
if (!list->size())
{
delete list;
list = NULL;
}
return list;
}
/// <summary>
/// Get the dungeon list that can be done.
/// </summary>
/// <returns>LfgDungeonSet*</returns>
LfgDungeonSet* LFGMgr::GetAllDungeons()
{
LfgDungeonSet *alldungeons = m_CachedDungeonMap[0];
if (alldungeons)
return alldungeons;
LfgDungeonSet *dungeons;
LFGDungeonEntry const *dungeon;
alldungeons = new LfgDungeonSet();
m_CachedDungeonMap[0] = alldungeons;
for (uint32 i = 0; i < sLFGDungeonStore.GetNumRows(); ++i)
{
dungeon = sLFGDungeonStore.LookupEntry(i);
if (!dungeon || dungeon->type == LFG_TYPE_ZONE)
continue;
dungeons = m_CachedDungeonMap[dungeon->grouptype];
if (!dungeons)
{
dungeons = new LfgDungeonSet();
m_CachedDungeonMap[dungeon->grouptype] = dungeons;
}
if (dungeon->type != LFG_TYPE_RANDOM)
dungeons->insert(dungeon->ID);
alldungeons->insert(dungeon->ID);
}
return alldungeons;
}
/// <summary>
/// Get the dungeon list that can be done given a random dungeon entry.
/// Special case: randomdungeon == 0 then will return all dungeons
/// </summary>
/// <param name="uint32">Random dungeon entry</param>
/// <returns>LfgDungeonSet*</returns>
LfgDungeonSet* LFGMgr::GetDungeonsByRandom(uint32 randomdungeon)
{
uint8 groupType = 0;
if (LFGDungeonEntry const *dungeon = sLFGDungeonStore.LookupEntry(randomdungeon))
groupType = dungeon->grouptype;
return m_CachedDungeonMap[groupType];
}
/// <summary>
/// Get the random dungeon list that can be done at a certain level and expansion.
/// </summary>
/// <param name="uint8">Player level</param>
/// <param name="uint8">Player account expansion</param>
/// <returns>LfgDungeonSet*</returns>
LfgDungeonSet* LFGMgr::GetRandomDungeons(uint8 level, uint8 expansion)
{
LfgDungeonSet *list = new LfgDungeonSet();
LFGDungeonEntry const *dungeon;
for (uint32 i = 0; i < sLFGDungeonStore.GetNumRows(); ++i)
{
dungeon = sLFGDungeonStore.LookupEntry(i);
if (dungeon && dungeon->expansion <= expansion && dungeon->type == LFG_TYPE_RANDOM &&
dungeon->minlevel <= level && level <= dungeon->maxlevel)
list->insert(dungeon->Entry());
}
return list;
}
/// <summary>
/// Get the reward of a given random dungeon at a certain level
/// </summary>
/// <param name="uint32">random dungeon id</param>
/// <param name="uint8">Player level</param>
/// <returns>LfgReward const*</returns>
LfgReward const* LFGMgr::GetRandomDungeonReward(uint32 dungeon, uint8 level)
{
LfgReward const* rew = NULL;
LfgRewardMapBounds bounds = m_RewardMap.equal_range(dungeon & 0x00FFFFFF);
for (LfgRewardMap::const_iterator itr = bounds.first; itr != bounds.second; ++itr)
{
rew = itr->second;
// ordered properly at loading
if (itr->second->maxLevel >= level)
break;
}
return rew;
}
/// <summary>
/// Given a Dungeon id returns the dungeon Group Type
/// </summary>
/// <param name="uint32">Dungeon id</param>
/// <returns>uint8: GroupType</returns>
uint8 LFGMgr::GetDungeonGroupType(uint32 dungeonId)
{
LFGDungeonEntry const *dungeon = sLFGDungeonStore.LookupEntry(dungeonId);
if (!dungeon)
return 0;
return dungeon->grouptype;
}
/// <summary>
/// Given a Dungeon id returns if it's random
/// </summary>
/// <param name="uint32">Dungeon id</param>
/// <returns>bool</returns>
bool LFGMgr::isRandomDungeon(uint32 dungeonId)
{
LFGDungeonEntry const *dungeon = sLFGDungeonStore.LookupEntry(dungeonId);
if (!dungeon)
return false;
return dungeon->type == LFG_TYPE_RANDOM;
}
/// <summary>
/// Given a list of guids returns the concatenation using | as delimiter
/// </summary>
/// <param name="LfgGuidList ">list of guids</param>
/// <returns>std::string</returns>
std::string LFGMgr::ConcatenateGuids(LfgGuidList check)
{
if (check.empty())
return "";
LfgGuidSet guidSet;
while (!check.empty())
{
guidSet.insert(check.front());
check.pop_front();
}
std::ostringstream o;
LfgGuidSet::iterator it = guidSet.begin();
o << *it;
for (++it; it != guidSet.end(); ++it)
o << "|" << *it;
guidSet.clear();
return o.str();
}
enum LFGenum
{
LFG_TIME_ROLECHECK = 2*MINUTE,
LFG_TIME_BOOT = 2*MINUTE,
LFG_TIME_PROPOSAL = 2*MINUTE,
LFG_TANKS_NEEDED = 1,
LFG_HEALERS_NEEDED = 1,
LFG_DPS_NEEDED = 3,
LFG_QUEUEUPDATE_INTERVAL = 15000,
LFG_SPELL_COOLDOWN = 71328,
LFG_SPELL_DESERTER = 71041,
LFG_MAX_KICKS = 3,
};
enum LfgType
{
LFG_TYPE_DUNGEON = 1,
LFG_TYPE_RAID = 2,
LFG_TYPE_QUEST = 3,
LFG_TYPE_ZONE = 4,
LFG_TYPE_HEROIC = 5,
LFG_TYPE_RANDOM = 6,
};
enum LfgProposalState
{
LFG_PROPOSAL_INITIATING = 0,
LFG_PROPOSAL_FAILED = 1,
LFG_PROPOSAL_SUCCESS = 2,
};
enum LfgGroupType
{
LFG_GROUPTYPE_ALL = 0, // Internal use, represents all groups.
LFG_GROUPTYPE_CLASSIC = 1,
LFG_GROUPTYPE_BC_NORMAL = 2,
LFG_GROUPTYPE_BC_HEROIC = 3,
LFG_GROUPTYPE_WTLK_NORMAL = 4,
LFG_GROUPTYPE_WTLK_HEROIC = 5,
LFG_GROUPTYPE_CLASSIC_RAID = 6,
LFG_GROUPTYPE_BC_RAID = 7,
LFG_GROUPTYPE_WTLK_RAID_10 = 8,
LFG_GROUPTYPE_WTLK_RAID_25 = 9,
};
enum LfgLockStatusType
{
LFG_LOCKSTATUS_OK = 0, // Internal use only
LFG_LOCKSTATUS_INSUFFICIENT_EXPANSION = 1,
LFG_LOCKSTATUS_TOO_LOW_LEVEL = 2,
LFG_LOCKSTATUS_TOO_HIGH_LEVEL = 3,
LFG_LOCKSTATUS_TOO_LOW_GEAR_SCORE = 4,
LFG_LOCKSTATUS_TOO_HIGH_GEAR_SCORE = 5,
LFG_LOCKSTATUS_RAID_LOCKED = 6,
LFG_LOCKSTATUS_ATTUNEMENT_TOO_LOW_LEVEL = 1001,
LFG_LOCKSTATUS_ATTUNEMENT_TOO_HIGH_LEVEL = 1002,
LFG_LOCKSTATUS_QUEST_NOT_COMPLETED = 1022,
LFG_LOCKSTATUS_MISSING_ITEM = 1025,
LFG_LOCKSTATUS_NOT_IN_SEASON = 1031,
};
enum LfgTeleportError
{
//LFG_TELEPORTERROR_UNK1 = 0, // No reaction
LFG_TELEPORTERROR_PLAYER_DEAD = 1,
LFG_TELEPORTERROR_FALLING = 2,
//LFG_TELEPORTERROR_UNK2 = 3, // You can't do that right now
LFG_TELEPORTERROR_FATIGUE = 4,
//LFG_TELEPORTERROR_UNK3 = 5, // No reaction
LFG_TELEPORTERROR_INVALID_LOCATION = 6,
//LFG_TELEPORTERROR_UNK4 = 7, // You can't do that right now
//LFG_TELEPORTERROR_UNK5 = 8, // You can't do that right now
};
enum LfgJoinResult
{
LFG_JOIN_OK = 0, // Joined (no client msg)
LFG_JOIN_FAILED = 1, // RoleCheck Failed
LFG_JOIN_GROUPFULL = 2, // Your group is full
LFG_JOIN_UNK3 = 3, // No client reaction
LFG_JOIN_INTERNAL_ERROR = 4, // Internal LFG Error
LFG_JOIN_NOT_MEET_REQS = 5, // You do not meet the requirements for the chosen dungeons
LFG_JOIN_PARTY_NOT_MEET_REQS = 6, // One or more party members do not meet the requirements for the chosen dungeons
LFG_JOIN_MIXED_RAID_DUNGEON = 7, // You cannot mix dungeons, raids, and random when picking dungeons
LFG_JOIN_MULTI_REALM = 8, // The dungeon you chose does not support players from multiple realms
LFG_JOIN_DISCONNECTED = 9, // One or more party members are pending invites or disconnected
LFG_JOIN_PARTY_INFO_FAILED = 10, // Could not retrieve information about some party members
LFG_JOIN_DUNGEON_INVALID = 11, // One or more dungeons was not valid
LFG_JOIN_DESERTER = 12, // You can not queue for dungeons until your deserter debuff wears off
LFG_JOIN_PARTY_DESERTER = 13, // One or more party members has a deserter debuff
LFG_JOIN_RANDOM_COOLDOWN = 14, // You can not queue for random dungeons while on random dungeon cooldown
LFG_JOIN_PARTY_RANDOM_COOLDOWN = 15, // One or more party members are on random dungeon cooldown
LFG_JOIN_TOO_MUCH_MEMBERS = 16, // You can not enter dungeons with more that 5 party members
LFG_JOIN_USING_BG_SYSTEM = 17, // You can not use the dungeon system while in BG or arenas
LFG_JOIN_FAILED2 = 18, // RoleCheck Failed
};
enum LfgRoleCheckResult
{
LFG_ROLECHECK_FINISHED = 1, // Role check finished
LFG_ROLECHECK_INITIALITING = 2, // Role check begins
LFG_ROLECHECK_MISSING_ROLE = 3, // Someone didn't selected a role after 2 mins
LFG_ROLECHECK_WRONG_ROLES = 4, // Can't form a group with that role selection
LFG_ROLECHECK_ABORTED = 5, // Someone leave the group
LFG_ROLECHECK_NO_ROLE = 6, // Someone selected no role
};
enum LfgAnswer
{
LFG_ANSWER_PENDING = -1,
LFG_ANSWER_DENY = 0,
LFG_ANSWER_AGREE = 1,
};
// Dungeon and reason why player can't join
struct LfgLockStatus
{
uint32 dungeon;
LfgLockStatusType lockstatus;
};
// Reward info
struct LfgReward
{
uint32 maxLevel;
struct
{
uint32 questId;
uint32 variableMoney;
uint32 variableXP;
} reward[2];
LfgReward(uint32 _maxLevel, uint32 firstQuest, uint32 firstVarMoney, uint32 firstVarXp, uint32 otherQuest, uint32 otherVarMoney, uint32 otherVarXp)
: maxLevel(_maxLevel)
{
reward[0].questId = firstQuest;
reward[0].variableMoney = firstVarMoney;
reward[0].variableXP = firstVarXp;
reward[1].questId = otherQuest;
reward[1].variableMoney = otherVarMoney;
reward[1].variableXP = otherVarXp;
}
};
typedef std::map<uint32, uint8> LfgRolesMap;
typedef std::map<uint32, LfgAnswer> LfgAnswerMap;
typedef std::list<uint64> LfgGuidList;
typedef std::map<uint64, LfgDungeonSet*> LfgDungeonMap;
// Stores player or group queue info
struct LfgQueueInfo
{
LfgQueueInfo(): tanks(LFG_TANKS_NEEDED), healers(LFG_HEALERS_NEEDED), dps(LFG_DPS_NEEDED) {};
time_t joinTime; // Player queue join time (to calculate wait times)
uint8 tanks; // Tanks needed
uint8 healers; // Healers needed
uint8 dps; // Dps needed
LfgDungeonSet dungeons; // Selected Player/Group Dungeon/s
LfgRolesMap roles; // Selected Player Role/s
};
struct LfgProposalPlayer
{
LfgProposalPlayer(): role(0), accept(LFG_ANSWER_PENDING), groupLowGuid(0) {};
uint8 role; // Proposed role
LfgAnswer accept; // Accept status (-1 not answer | 0 Not agree | 1 agree)
uint32 groupLowGuid; // Original group guid (Low guid) 0 if no original group
};
typedef std::map<uint32, LfgProposalPlayer*> LfgProposalPlayerMap;
// Stores all Dungeon Proposal after matching candidates
struct LfgProposal
{
LfgProposal(uint32 dungeon): dungeonId(dungeon), state(LFG_PROPOSAL_INITIATING), groupLowGuid(0), leaderLowGuid(0) {}
~LfgProposal()
{
for (LfgProposalPlayerMap::iterator it = players.begin(); it != players.end(); ++it)
delete it->second;
players.clear();
queues.clear();
};
uint32 dungeonId; // Dungeon to join
LfgProposalState state; // State of the proposal
uint32 groupLowGuid; // Proposal group (0 if new)
uint32 leaderLowGuid; // Leader guid.
time_t cancelTime; // Time when we will cancel this proposal
LfgGuidList queues; // Queue Ids to remove/readd
LfgProposalPlayerMap players; // Player current groupId
};
// Stores all rolecheck info of a group that wants to join LFG
struct LfgRoleCheck
{
time_t cancelTime;
LfgRolesMap roles;
LfgRoleCheckResult result;
LfgDungeonSet dungeons;
uint32 leader;
};
// Stores information of a current vote to kick someone from a group
struct LfgPlayerBoot
{
time_t cancelTime; // Time left to vote
bool inProgress; // Vote in progress
LfgAnswerMap votes; // Player votes (-1 not answer | 0 Not agree | 1 agree)
uint32 victimLowGuid; // Player guid to be kicked (can't vote)
uint8 votedNeeded; // Votes needed to kick the player
std::string reason; // kick reason
};
typedef std::set<Player*> PlayerSet;
typedef std::set<LfgLockStatus*> LfgLockStatusSet;
typedef std::vector<LfgProposal*> LfgProposalList;
typedef std::map<uint32, LfgLockStatusSet*> LfgLockStatusMap;
typedef std::map<uint64, LfgQueueInfo*> LfgQueueInfoMap;
typedef std::map<uint32, LfgRoleCheck*> LfgRoleCheckMap;
typedef std::map<uint32, LfgProposal*> LfgProposalMap;
typedef std::map<uint32, LfgPlayerBoot*> LfgPlayerBootMap;
typedef std::multimap<uint32, LfgReward const*> LfgRewardMap;
typedef std::pair<LfgRewardMap::const_iterator, LfgRewardMap::const_iterator> LfgRewardMapBounds;
typedef std::list<Player *> LfgPlayerList;
typedef std::set<uint64> LfgGuidSet;
typedef std::map<std::string, LfgAnswer> LfgCompatibleMap;
class LFGMgr
{
friend class ACE_Singleton<LFGMgr, ACE_Null_Mutex>;
public:
LFGMgr();
~LFGMgr();
void Join(Player *plr);
void Leave(Player *plr, Group *grp = NULL);
void OfferContinue(Group *grp);
void TeleportPlayer(Player *plr, bool out);
void UpdateProposal(uint32 proposalId, uint32 lowGuid, bool accept);
void UpdateBoot(Player *plr, bool accept);
void UpdateRoleCheck(Group *grp, Player *plr = NULL);
void Update(uint32 diff);
bool isRandomDungeon(uint32 dungeonId);
void InitBoot(Group *grp, uint32 plowGuid, uint32 vlowGuid, std::string reason);
void LoadDungeonEncounters();
void LoadRewards();
void RewardDungeonDoneFor(const uint32 dungeonId, Player* player);
uint32 GetDungeonIdForAchievement(uint32 achievementId)
{
std::map<uint32, uint32>::iterator itr = m_EncountersByAchievement.find(achievementId);
if (itr != m_EncountersByAchievement.end())
return itr->second;
return 0;
};
LfgLockStatusMap* GetPartyLockStatusDungeons(Player *plr, LfgDungeonSet *dungeons = NULL);
LfgDungeonSet* GetRandomDungeons(uint8 level, uint8 expansion);
LfgLockStatusSet* GetPlayerLockStatusDungeons(Player *plr, LfgDungeonSet *dungeons = NULL, bool useEntry = true);
LfgReward const* GetRandomDungeonReward(uint32 dungeon, uint8 level);
void BuildPlayerLockDungeonBlock(WorldPacket &data, LfgLockStatusSet *lockSet);
void BuildPartyLockDungeonBlock(WorldPacket &data, LfgLockStatusMap *lockMap);
private:
void Cleaner();
void AddGuidToNewQueue(uint64 guid);
void AddToQueue(uint64 guid, LfgRolesMap *roles, LfgDungeonSet *dungeons);
bool RemoveFromQueue(uint64 guid);
void RemoveProposal(LfgProposalMap::iterator itProposal, LfgUpdateType type);
void FindNewGroups(LfgGuidList &check, LfgGuidList all, LfgProposalList *proposals);
bool CheckGroupRoles(LfgRolesMap &groles, bool removeLeaderFlag = true);
bool CheckCompatibility(LfgGuidList check, LfgProposalList *proposals);
LfgDungeonSet* CheckCompatibleDungeons(LfgDungeonMap *dungeonsMap, PlayerSet *players);
void SetCompatibles(std::string concatenatedGuids, bool compatibles);
LfgAnswer GetCompatibles(std::string concatenatedGuids);
void RemoveFromCompatibles(uint64 guid);
std::string ConcatenateGuids(LfgGuidList check);
void BuildLfgRoleCheck(WorldPacket &data, LfgRoleCheck *pRoleCheck);
void BuildAvailableRandomDungeonList(WorldPacket &data, Player *plr);
void BuildBootPlayerBlock(WorldPacket &data, LfgPlayerBoot *pBoot, uint32 lowGuid);
LfgLockStatusMap* GetGroupLockStatusDungeons(PlayerSet *pPlayers, LfgDungeonSet *dungeons, bool useEntry = true);
LfgDungeonSet* GetDungeonsByRandom(uint32 randomdungeon);
LfgDungeonSet* GetAllDungeons();
uint8 GetDungeonGroupType(uint32 dungeon);
LfgRewardMap m_RewardMap; // Stores rewards for random dungeons
std::map<uint32, uint32> m_EncountersByAchievement; // Stores dungeon ids associated with achievements (for rewards)
LfgDungeonMap m_CachedDungeonMap; // Stores all dungeons by groupType
LfgQueueInfoMap m_QueueInfoMap; // Queued groups
LfgGuidList m_currentQueue; // Ordered list. Used to find groups
LfgGuidList m_newToQueue; // New groups to add to queue
LfgCompatibleMap m_CompatibleMap; // Compatible dungeons
LfgProposalMap m_Proposals; // Current Proposals
LfgPlayerBootMap m_Boots; // Current player kicks
LfgRoleCheckMap m_RoleChecks; // Current Role checks
uint32 m_QueueTimer; // used to check interval of update
uint32 m_lfgProposalId; // used as internal counter for proposals
int32 m_WaitTimeAvg;
int32 m_WaitTimeTank;
int32 m_WaitTimeHealer;
int32 m_WaitTimeDps;
uint32 m_NumWaitTimeAvg;
uint32 m_NumWaitTimeTank;
uint32 m_NumWaitTimeHealer;
uint32 m_NumWaitTimeDps;
bool m_update;
};
*/
#endif
/*
void WorldSession::HandleSetLookingForGroupComment(WorldPacket& recvPacket)
{
std::string comment;
recvPacket >> comment;
GetPlayer()->Lfgcomment = comment;
}
void WorldSession::HandleEnableAutoJoin(WorldPacket& recvPacket)
{
uint32 i;
// make sure they're not queued in any invalid cases
for(i = 0; i < MAX_LFG_QUEUE_ID; ++i)
{
if(_player->LfgDungeonId[i] != 0)
{
if(LfgDungeonTypes[_player->LfgDungeonId[i]] == LFG_TYPE_NONE
|| LfgDungeonTypes[_player->LfgDungeonId[i]] == LFG_TYPE_QUEST
|| LfgDungeonTypes[_player->LfgDungeonId[i]] == LFG_TYPE_ZONE
|| LfgDungeonTypes[_player->LfgDungeonId[i]] >= LFG_MAX_TYPES
)
{
return;
}
}
}
// enable autojoin, join any groups if possible.
_player->m_Autojoin = true;
for(i = 0; i < MAX_LFG_QUEUE_ID; ++i)
{
if(_player->LfgDungeonId[i] != 0)
{
_player->SendMeetingStoneQueue(_player->LfgDungeonId[i], 1);
sLfgMgr.UpdateLfgQueue(_player->LfgDungeonId[i]);
}
}
}
void WorldSession::HandleDisableAutoJoin(WorldPacket& recvPacket)
{
uint32 i;
_player->m_Autojoin = false;
for(i = 0; i < MAX_LFG_QUEUE_ID; ++i)
{
if(_player->LfgDungeonId[i] != 0)
{
if( LfgDungeonTypes[_player->LfgDungeonId[i]] == LFG_TYPE_DUNGEON
|| LfgDungeonTypes[_player->LfgDungeonId[i]] == LFG_TYPE_RAID
|| LfgDungeonTypes[_player->LfgDungeonId[i]] == LFG_TYPE_HEROIC_DUNGEON
|| LfgDungeonTypes[_player->LfgDungeonId[i]] == LFG_TYPE_ANY_DUNGEON
|| LfgDungeonTypes[_player->LfgDungeonId[i]] == LFG_TYPE_ANY_HEROIC_DUNGEON
|| LfgDungeonTypes[_player->LfgDungeonId[i]] == LFG_TYPE_DAILY_DUNGEON
|| LfgDungeonTypes[_player->LfgDungeonId[i]] == LFG_TYPE_DAILY_HEROIC_DUNGEON
)
_player->SendMeetingStoneQueue(_player->LfgDungeonId[i], 0);
}
}
}
void WorldSession::HandleEnableAutoAddMembers(WorldPacket& recvPacket)
{
uint32 i;
_player->m_AutoAddMem = true;
for(i = 0; i < MAX_LFG_QUEUE_ID; ++i)
{
if(_player->LfgDungeonId[i] != 0)
{
sLfgMgr.UpdateLfgQueue(_player->LfgDungeonId[i]);
}
}
}
void WorldSession::HandleDisableAutoAddMembers(WorldPacket& recvPacket)
{
_player->m_AutoAddMem = false;
}
void WorldSession::HandleMsgLookingForGroup(WorldPacket& recvPacket)
{
// this is looking for more
uint32 LfgType,LfgDungeonId,unk1;
recvPacket >> LfgType >> LfgDungeonId >> unk1;
if(LfgDungeonId > MAX_DUNGEONS)
{
return;
}
if(LfgDungeonId)
sLfgMgr.SendLfgList(_player, LfgDungeonId);
}
void WorldSession::HandleSetLookingForGroup(WorldPacket& recvPacket)
{
uint32 LfgQueueId;
uint16 LfgDungeonId;
uint8 LfgType,unk1;
uint32 i;
recvPacket >> LfgQueueId >> LfgDungeonId >> unk1 >> LfgType;
if(LfgDungeonId >= MAX_DUNGEONS || LfgQueueId >= MAX_LFG_QUEUE_ID || LfgType != LfgDungeonTypes[LfgDungeonId]) // last one is for cheaters
{
return;
}
if(_player->LfgDungeonId[LfgQueueId] != 0)
sLfgMgr.RemovePlayerFromLfgQueue(_player, _player->LfgDungeonId[LfgQueueId]);
_player->LfgDungeonId[LfgQueueId]=LfgDungeonId;
_player->LfgType[LfgQueueId]=LfgType;
if(LfgDungeonId)
{
sLfgMgr.SetPlayerInLFGqueue(_player, LfgDungeonId);
if( LfgType != LFG_TYPE_NONE && LfgType != LFG_TYPE_QUEST && LfgType != LFG_TYPE_ZONE && LfgType < LFG_MAX_TYPES )
{
sLfgMgr.UpdateLfgQueue(LfgDungeonId);
if(_player->m_Autojoin)
_player->SendMeetingStoneQueue(LfgDungeonId, 1);
}
}
else
{
for(i = 0; i < MAX_LFG_QUEUE_ID; ++i)
{
if(_player->LfgDungeonId[i] != 0)
break;
}
if( i == MAX_LFG_QUEUE_ID )
_player->PartLFGChannel();
}
}
void WorldSession::HandleSetLookingForMore(WorldPacket& recvPacket)
{
uint16 LfgDungeonId;
uint8 LfgType,unk1;
recvPacket >> LfgDungeonId >> unk1 >> LfgType;
if( LfgDungeonId >= MAX_DUNGEONS )
{
return;
}
// remove from an existing queue
if(LfgDungeonId != _player->LfmDungeonId && _player->LfmDungeonId)
sLfgMgr.RemovePlayerFromLfmList(_player, _player->LfmDungeonId);
_player->LfmDungeonId = LfgDungeonId;
_player->LfmType = LfgType;
if(LfgDungeonId)
sLfgMgr.SetPlayerInLfmList(_player, LfgDungeonId);
}
void WorldSession::HandleLfgClear(WorldPacket & recvPacket)
{
sLfgMgr.RemovePlayerFromLfgQueues(_player);
}
void WorldSession::HandleLfgInviteAccept(WorldPacket & recvPacket)
{
CHECK_INWORLD_RETURN
_player->PartLFGChannel();
if(
// _player->m_lfgMatch == NULL &&
_player->m_lfgInviterGuid == 0
)
{
// if(_player->m_lfgMatch == NULL)
// OutPacket(SMSG_LFG_MATCHMAKING_AUTOJOIN_FAILED_NO_PLAYER); // Matched Player(s) have gone offline.
// else
// OutPacket(SMSG_LFG_MATCHMAKING_AUTOJOIN_FAILED); // Group no longer available.
return;
}
/* if( _player->m_lfgMatch != NULL )
{
// move into accepted players
_player->m_lfgMatch->lock.Acquire();
_player->m_lfgMatch->PendingPlayers.erase(_player);
if( !_player->GetGroup() )
{
_player->m_lfgMatch->AcceptedPlayers.insert(_player);
if(!_player->m_lfgMatch->PendingPlayers.size())
{
// all players have accepted
Group * pGroup = new Group(true);
for(set<Player*>::iterator itr = _player->m_lfgMatch->AcceptedPlayers.begin(); itr != _player->m_lfgMatch->AcceptedPlayers.end(); ++itr)
pGroup->AddMember((*itr)->m_playerInfo);
_player->m_lfgMatch->pGroup = pGroup;
}
}
_player->m_lfgMatch->lock.Release();
}
else */
/* {
Player * pPlayer = objmgr.GetPlayer(_player->m_lfgInviterGuid);
if( pPlayer == NULL )
{
// OutPacket(SMSG_LFG_MATCHMAKING_AUTOJOIN_FAILED_NO_PLAYER); // Matched Player(s) have gone offline.
return;
}
if( pPlayer->GetGroup() == NULL || pPlayer->GetGroup()->IsFull() || pPlayer->GetGroup()->GetLeader() != pPlayer->m_playerInfo )
{
// OutPacket(SMSG_LFG_MATCHMAKING_AUTOJOIN_FAILED);
return;
}
pPlayer->GetGroup()->AddMember(_player->m_playerInfo);
}
_player->m_lfgInviterGuid = 0;
// _player->m_lfgMatch = NULL;
}
*/ | [
"[email protected]"
] | |
c4d4f5d4f38fcf0ad6bf548c620476a97adc36ed | 6fa78aa110e4eae26418a5104690135599344f31 | /gravitypotential.hpp | 53cf372988402cd6c915b9e9933e43f054e79339 | [] | no_license | jusperino/md_2017 | b27c6454b9afa43022e38e5120d2935de9b43336 | 2a469d71bbacb6fd035735f130c64cafd9dd2613 | refs/heads/master | 2021-09-05T03:44:45.311965 | 2018-01-21T00:37:01 | 2018-01-21T00:37:01 | 109,430,725 | 0 | 4 | null | 2018-01-09T12:15:19 | 2017-11-03T18:40:04 | C++ | UTF-8 | C++ | false | false | 501 | hpp | #ifndef _GRAVITYPOTENTIAL_HPP
#define _GRAVITYPOTENTIAL_HPP
#include "potential.hpp"
/**
* @brief TODO add the documentation
*/
class GravityPotential : public Potential {
public:
/**
* @brief calculate the force between the two particles and add it to p
*
* @param p particle p
* @param q particl q
*
* @return potential energy
*/
virtual real force(Particle &p, Particle &q);
};
#endif // _GRAVITYPOTENTIAL_HPP
// vim:set et sts=4 ts=4 sw=4 ai ci cin:
| [
"[email protected]"
] | |
e78ea861d7e0a0ba7b4391d82cedeefb1953c1d4 | 8c8820fb84dea70d31c1e31dd57d295bd08dd644 | /WebBrowserTexture/Public/WebBrowserTextureModule.h | ac19aac5072a3ee72a3310c6cfc571766d1e5abb | [] | no_license | redisread/UE-Runtime | e1a56df95a4591e12c0fd0e884ac6e54f69d0a57 | 48b9e72b1ad04458039c6ddeb7578e4fc68a7bac | refs/heads/master | 2022-11-15T08:30:24.570998 | 2020-06-20T06:37:55 | 2020-06-20T06:37:55 | 274,085,558 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 271 | h | // Copyright Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Modules/ModuleInterface.h"
#include "Modules/ModuleManager.h"
/**
* WebBrowserTextureModule interface
*/
class IWebBrowserTextureModule : public IModuleInterface
{
};
| [
"[email protected]"
] | |
3469de2552984b2f009c3971dec9145c5b71ada2 | 6c94f958f52b0c451bba629906900e23086d62e2 | /Client/Source/Info.h | 8e3062f9de79f31e8068aee21e1d3542219a4c24 | [] | no_license | JulienDuf/Server | 8967cf4737ad0df986fb93542f2b45dc5f4ca455 | 55285b16a9b3a6bbe9e2a2001370ff4a321db5c4 | refs/heads/master | 2021-01-19T18:51:58.869448 | 2016-01-24T07:07:34 | 2016-01-24T07:07:34 | 44,824,162 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,577 | h | #pragma once
#include <string>
enum server_message_type {NEW_CLIENT, NEW_MESSAGE, CLIENT_DISCONNECTED, CLIENTS_CONNECTED};
class ServerInfo {
public:
server_message_type message_type;
int clientID;
std::string clientName;
std::string* message;
ServerInfo() {
message = nullptr;
}
ServerInfo(char* info) {
std::string* values = new std::string(info);
int letter = 0;
int begin = 0;
std::string tmp;
for (int i = 0; i < 4; ++i) {
while (values->at(letter) != '\n') ++letter;
for (int k = begin; k < letter; ++k)
tmp.push_back(values->at(k));
begin = ++letter;
switch (i) {
case 0:
message_type = server_message_type(SDL_atoi(tmp.c_str()));
break;
case 1:
clientID = SDL_atoi(tmp.c_str());
break;
case 2:
clientName = std::string(tmp);
break;
case 3:
if (tmp == "NULL")
message = nullptr;
else
message = new std::string(tmp);
break;
}
tmp.clear();
}
delete values;
}
~ServerInfo() {
delete message;
}
virtual void convertToString(std::string &returnValue) {
char chr[10];
returnValue += SDL_itoa(message_type, chr, 10);
returnValue.push_back('\n');
returnValue += SDL_itoa(clientID, chr, 10);
returnValue.push_back('\n');
returnValue += clientName;
returnValue.push_back('\n');
if (message != nullptr)
returnValue += *message;
else
returnValue.append("NULL");
returnValue.push_back('\n');
}
};
class ClientInfo {
public:
int ID;
std::string name;
std::string* message;
ClientInfo() {
message = nullptr;
}
ClientInfo(char* info) {
std::string* values = new std::string(info);
int letter = 0;
int begin = 0;
std::string tmp;
for (int i = 0; i < 3; ++i) {
while (values->at(letter) != '\n') ++letter;
for (int k = begin; k < letter; ++k)
tmp.push_back(values->at(k));
begin = ++letter;
switch (i) {
case 0:
ID = SDL_atoi(tmp.c_str());
break;
case 1:
name = std::string(tmp);
break;
case 2:
if (tmp == "NULL")
message = nullptr;
else
message = new std::string(tmp);
break;
}
tmp.clear();
}
delete values;
}
~ClientInfo() {
delete message;
}
virtual void convertToString(std::string &returnValue) {
char chr[10];
returnValue += SDL_itoa(ID, chr, 10);
returnValue.push_back('\n');
returnValue += name;
returnValue.push_back('\n');
if (message != nullptr)
returnValue += *message;
else
returnValue.append("NULL");
returnValue.push_back('\n');
}
}; | [
"[email protected]"
] | |
5915eb6ee70df0ce3265eefa9afe19138f9326c5 | e4c3c428c5944a75a7444f65247e27aee29a3813 | /bindings/python/flashlight/lib/text/_decoder.cpp | 5606686f824694413f51499321a57465b3f34c08 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | wesbz/flashlight | 844f12f2e3d69c014c05d616062aaab6229eb8e6 | e692a941e902f9e207a1a4ee226c0ad0f8dbdc5e | refs/heads/master | 2022-12-17T22:29:19.146569 | 2020-09-22T21:41:17 | 2020-09-22T21:42:32 | 297,592,328 | 0 | 0 | NOASSERTION | 2020-09-23T14:31:37 | 2020-09-22T08:58:20 | null | UTF-8 | C++ | false | false | 9,448 | cpp | /**
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include "flashlight/lib/text/decoder/LexiconDecoder.h"
#include "flashlight/lib/text/decoder/LexiconFreeDecoder.h"
#ifdef FL_LIBRARIES_USE_KENLM
#include "flashlight/lib/text/decoder/lm/KenLM.h"
#endif // FL_LIBRARIES_USE_KENLM
namespace py = pybind11;
using namespace fl::lib::text;
using namespace py::literals;
/**
* Some hackery that lets pybind11 handle shared_ptr<void> (for old LMStatePtr).
* See: https://github.com/pybind/pybind11/issues/820
* PYBIND11_MAKE_OPAQUE(std::shared_ptr<void>);
* and inside PYBIND11_MODULE
* py::class_<std::shared_ptr<void>>(m, "encapsulated_data");
*/
namespace {
/**
* A pybind11 "alias type" for abstract class LM, allowing one to subclass LM
* with a custom LM defined purely in Python. For those who don't want to build
* with KenLM, or have their own custom LM implementation.
* See: https://pybind11.readthedocs.io/en/stable/advanced/classes.html
*
* TODO: ensure this works. Last time Jeff tried this there were slicing issues,
* see https://github.com/pybind/pybind11/issues/1546 for workarounds.
* This is low-pri since we assume most people can just build with KenLM.
*/
class PyLM : public LM {
using LM::LM;
// needed for pybind11 or else it won't compile
using LMOutput = std::pair<LMStatePtr, float>;
LMStatePtr start(bool startWithNothing) override {
PYBIND11_OVERLOAD_PURE(LMStatePtr, LM, start, startWithNothing);
}
LMOutput score(const LMStatePtr& state, const int usrTokenIdx) override {
PYBIND11_OVERLOAD_PURE(LMOutput, LM, score, state, usrTokenIdx);
}
LMOutput finish(const LMStatePtr& state) override {
PYBIND11_OVERLOAD_PURE(LMOutput, LM, finish, state);
}
};
/**
* Using custom python LMState derived from LMState is not working with
* custom python LM (derived from PyLM) because we need to to custing of LMState
* in score and finish functions to the derived class
* (for example vie obj.__class__ = CustomPyLMSTate) which cause the error
* "TypeError: __class__ assignment: 'CustomPyLMState' deallocator differs
* from 'flashlight.text.decoder._decoder.LMState'"
* details see in https://github.com/pybind/pybind11/issues/1640
* To define custom LM you can introduce map inside LM which maps LMstate to
* additional state info (shared pointers pointing to the same underlying object
* will have the same id in python in functions score and finish)
*
* ```python
* from flashlight.lib.text.decoder import LM
* class MyPyLM(LM):
* mapping_states = dict() # store simple additional int for each state
*
* def __init__(self):
* LM.__init__(self)
*
* def start(self, start_with_nothing):
* state = LMState()
* self.mapping_states[state] = 0
* return state
*
* def score(self, state, index):
* outstate = state.child(index)
* if outstate not in self.mapping_states:
* self.mapping_states[outstate] = self.mapping_states[state] + 1
* return (outstate, -numpy.random.random())
*
* def finish(self, state):
* outstate = state.child(-1)
* if outstate not in self.mapping_states:
* self.mapping_states[outstate] = self.mapping_states[state] + 1
* return (outstate, -1)
*```
*/
void LexiconDecoder_decodeStep(
LexiconDecoder& decoder,
uintptr_t emissions,
int T,
int N) {
decoder.decodeStep(reinterpret_cast<const float*>(emissions), T, N);
}
std::vector<DecodeResult> LexiconDecoder_decode(
LexiconDecoder& decoder,
uintptr_t emissions,
int T,
int N) {
return decoder.decode(reinterpret_cast<const float*>(emissions), T, N);
}
void LexiconFreeDecoder_decodeStep(
LexiconFreeDecoder& decoder,
uintptr_t emissions,
int T,
int N) {
decoder.decodeStep(reinterpret_cast<const float*>(emissions), T, N);
}
std::vector<DecodeResult> LexiconFreeDecoder_decode(
LexiconFreeDecoder& decoder,
uintptr_t emissions,
int T,
int N) {
return decoder.decode(reinterpret_cast<const float*>(emissions), T, N);
}
} // namespace
PYBIND11_MODULE(_lib_text_decoder, m) {
py::enum_<SmearingMode>(m, "SmearingMode")
.value("NONE", SmearingMode::NONE)
.value("MAX", SmearingMode::MAX)
.value("LOGADD", SmearingMode::LOGADD);
py::class_<TrieNode, TrieNodePtr>(m, "TrieNode")
.def(py::init<int>(), "idx"_a)
.def_readwrite("children", &TrieNode::children)
.def_readwrite("idx", &TrieNode::idx)
.def_readwrite("labels", &TrieNode::labels)
.def_readwrite("scores", &TrieNode::scores)
.def_readwrite("max_score", &TrieNode::maxScore);
py::class_<Trie, TriePtr>(m, "Trie")
.def(py::init<int, int>(), "max_children"_a, "root_idx"_a)
.def("get_root", &Trie::getRoot)
.def("insert", &Trie::insert, "indices"_a, "label"_a, "score"_a)
.def("search", &Trie::search, "indices"_a)
.def("smear", &Trie::smear, "smear_mode"_a);
py::class_<LM, LMPtr, PyLM>(m, "LM")
.def(py::init<>())
.def("start", &LM::start, "start_with_nothing"_a)
.def("score", &LM::score, "state"_a, "usr_token_idx"_a)
.def("finish", &LM::finish, "state"_a);
py::class_<LMState, LMStatePtr>(m, "LMState")
.def(py::init<>())
.def_readwrite("children", &LMState::children)
.def("compare", &LMState::compare, "state"_a)
.def("child", &LMState::child<LMState>, "usr_index"_a);
#ifdef FL_LIBRARIES_USE_KENLM
py::class_<KenLM, KenLMPtr, LM>(m, "KenLM")
.def(
py::init<const std::string&, const Dictionary&>(),
"path"_a,
"usr_token_dict"_a);
#endif
py::enum_<CriterionType>(m, "CriterionType")
.value("ASG", CriterionType::ASG)
.value("CTC", CriterionType::CTC);
py::class_<DecoderOptions>(m, "DecoderOptions")
.def(
py::init<
const int,
const int,
const double,
const double,
const double,
const double,
const double,
const double,
const bool,
const CriterionType>(),
"beam_size"_a,
"beam_size_token"_a,
"beam_threshold"_a,
"lm_weight"_a,
"word_score"_a,
"unk_score"_a,
"sil_score"_a,
"eos_score"_a,
"log_add"_a,
"criterion_type"_a)
.def_readwrite("beam_size", &DecoderOptions::beamSize)
.def_readwrite("beam_size_token", &DecoderOptions::beamSizeToken)
.def_readwrite("beam_threshold", &DecoderOptions::beamThreshold)
.def_readwrite("lm_weight", &DecoderOptions::lmWeight)
.def_readwrite("word_score", &DecoderOptions::wordScore)
.def_readwrite("unk_score", &DecoderOptions::unkScore)
.def_readwrite("sil_score", &DecoderOptions::silScore)
.def_readwrite("eos_score", &DecoderOptions::silScore)
.def_readwrite("log_add", &DecoderOptions::logAdd)
.def_readwrite("criterion_type", &DecoderOptions::criterionType);
py::class_<DecodeResult>(m, "DecodeResult")
.def(py::init<int>(), "length"_a)
.def_readwrite("score", &DecodeResult::score)
.def_readwrite("amScore", &DecodeResult::amScore)
.def_readwrite("lmScore", &DecodeResult::lmScore)
.def_readwrite("words", &DecodeResult::words)
.def_readwrite("tokens", &DecodeResult::tokens);
// NB: `decode` and `decodeStep` expect raw emissions pointers.
py::class_<LexiconDecoder>(m, "LexiconDecoder")
.def(py::init<
const DecoderOptions&,
const TriePtr,
const LMPtr,
const int,
const int,
const int,
const std::vector<float>&,
const bool>())
.def("decode_begin", &LexiconDecoder::decodeBegin)
.def(
"decode_step",
&LexiconDecoder_decodeStep,
"emissions"_a,
"T"_a,
"N"_a)
.def("decode_end", &LexiconDecoder::decodeEnd)
.def("decode", &LexiconDecoder_decode, "emissions"_a, "T"_a, "N"_a)
.def("prune", &LexiconDecoder::prune, "look_back"_a = 0)
.def(
"get_best_hypothesis",
&LexiconDecoder::getBestHypothesis,
"look_back"_a = 0)
.def("get_all_final_hypothesis", &LexiconDecoder::getAllFinalHypothesis);
py::class_<LexiconFreeDecoder>(m, "LexiconFreeDecoder")
.def(py::init<
const DecoderOptions&,
const LMPtr,
const int,
const int,
const std::vector<float>&>())
.def("decode_begin", &LexiconFreeDecoder::decodeBegin)
.def(
"decode_step",
&LexiconFreeDecoder_decodeStep,
"emissions"_a,
"T"_a,
"N"_a)
.def("decode_end", &LexiconFreeDecoder::decodeEnd)
.def("decode", &LexiconFreeDecoder_decode, "emissions"_a, "T"_a, "N"_a)
.def("prune", &LexiconFreeDecoder::prune, "look_back"_a = 0)
.def(
"get_best_hypothesis",
&LexiconFreeDecoder::getBestHypothesis,
"look_back"_a = 0)
.def(
"get_all_final_hypothesis",
&LexiconFreeDecoder::getAllFinalHypothesis);
}
| [
"[email protected]"
] | |
c7cbde244a8505bca05d63086fc8a18fd1fd0c1f | 5ec06dab1409d790496ce082dacb321392b32fe9 | /clients/cpp-qt5/generated/client/OAIComDayCqWcmDesignimporterImplCanvasBuilderImplInfo.cpp | 69075eeccfc125a1d7badebbbe7c0004fc86fa29 | [
"Apache-2.0"
] | permissive | shinesolutions/swagger-aem-osgi | e9d2385f44bee70e5bbdc0d577e99a9f2525266f | c2f6e076971d2592c1cbd3f70695c679e807396b | refs/heads/master | 2022-10-29T13:07:40.422092 | 2021-04-09T07:46:03 | 2021-04-09T07:46:03 | 190,217,155 | 3 | 3 | Apache-2.0 | 2022-10-05T03:26:20 | 2019-06-04T14:23:28 | null | UTF-8 | C++ | false | false | 5,196 | cpp | /**
* Adobe Experience Manager OSGI config (AEM) API
* Swagger AEM OSGI is an OpenAPI specification for Adobe Experience Manager (AEM) OSGI Configurations API
*
* OpenAPI spec version: 1.0.0-pre.0
* Contact: [email protected]
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "OAIComDayCqWcmDesignimporterImplCanvasBuilderImplInfo.h"
#include "OAIHelpers.h"
#include <QJsonDocument>
#include <QJsonArray>
#include <QObject>
#include <QDebug>
namespace OpenAPI {
OAIComDayCqWcmDesignimporterImplCanvasBuilderImplInfo::OAIComDayCqWcmDesignimporterImplCanvasBuilderImplInfo(QString json) {
init();
this->fromJson(json);
}
OAIComDayCqWcmDesignimporterImplCanvasBuilderImplInfo::OAIComDayCqWcmDesignimporterImplCanvasBuilderImplInfo() {
init();
}
OAIComDayCqWcmDesignimporterImplCanvasBuilderImplInfo::~OAIComDayCqWcmDesignimporterImplCanvasBuilderImplInfo() {
this->cleanup();
}
void
OAIComDayCqWcmDesignimporterImplCanvasBuilderImplInfo::init() {
pid = new QString("");
m_pid_isSet = false;
title = new QString("");
m_title_isSet = false;
description = new QString("");
m_description_isSet = false;
properties = new OAIComDayCqWcmDesignimporterImplCanvasBuilderImplProperties();
m_properties_isSet = false;
}
void
OAIComDayCqWcmDesignimporterImplCanvasBuilderImplInfo::cleanup() {
if(pid != nullptr) {
delete pid;
}
if(title != nullptr) {
delete title;
}
if(description != nullptr) {
delete description;
}
if(properties != nullptr) {
delete properties;
}
}
OAIComDayCqWcmDesignimporterImplCanvasBuilderImplInfo*
OAIComDayCqWcmDesignimporterImplCanvasBuilderImplInfo::fromJson(QString json) {
QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject jsonObject = doc.object();
this->fromJsonObject(jsonObject);
return this;
}
void
OAIComDayCqWcmDesignimporterImplCanvasBuilderImplInfo::fromJsonObject(QJsonObject pJson) {
::OpenAPI::setValue(&pid, pJson["pid"], "QString", "QString");
::OpenAPI::setValue(&title, pJson["title"], "QString", "QString");
::OpenAPI::setValue(&description, pJson["description"], "QString", "QString");
::OpenAPI::setValue(&properties, pJson["properties"], "OAIComDayCqWcmDesignimporterImplCanvasBuilderImplProperties", "OAIComDayCqWcmDesignimporterImplCanvasBuilderImplProperties");
}
QString
OAIComDayCqWcmDesignimporterImplCanvasBuilderImplInfo::asJson ()
{
QJsonObject obj = this->asJsonObject();
QJsonDocument doc(obj);
QByteArray bytes = doc.toJson();
return QString(bytes);
}
QJsonObject
OAIComDayCqWcmDesignimporterImplCanvasBuilderImplInfo::asJsonObject() {
QJsonObject obj;
if(pid != nullptr && *pid != QString("")){
toJsonValue(QString("pid"), pid, obj, QString("QString"));
}
if(title != nullptr && *title != QString("")){
toJsonValue(QString("title"), title, obj, QString("QString"));
}
if(description != nullptr && *description != QString("")){
toJsonValue(QString("description"), description, obj, QString("QString"));
}
if((properties != nullptr) && (properties->isSet())){
toJsonValue(QString("properties"), properties, obj, QString("OAIComDayCqWcmDesignimporterImplCanvasBuilderImplProperties"));
}
return obj;
}
QString*
OAIComDayCqWcmDesignimporterImplCanvasBuilderImplInfo::getPid() {
return pid;
}
void
OAIComDayCqWcmDesignimporterImplCanvasBuilderImplInfo::setPid(QString* pid) {
this->pid = pid;
this->m_pid_isSet = true;
}
QString*
OAIComDayCqWcmDesignimporterImplCanvasBuilderImplInfo::getTitle() {
return title;
}
void
OAIComDayCqWcmDesignimporterImplCanvasBuilderImplInfo::setTitle(QString* title) {
this->title = title;
this->m_title_isSet = true;
}
QString*
OAIComDayCqWcmDesignimporterImplCanvasBuilderImplInfo::getDescription() {
return description;
}
void
OAIComDayCqWcmDesignimporterImplCanvasBuilderImplInfo::setDescription(QString* description) {
this->description = description;
this->m_description_isSet = true;
}
OAIComDayCqWcmDesignimporterImplCanvasBuilderImplProperties*
OAIComDayCqWcmDesignimporterImplCanvasBuilderImplInfo::getProperties() {
return properties;
}
void
OAIComDayCqWcmDesignimporterImplCanvasBuilderImplInfo::setProperties(OAIComDayCqWcmDesignimporterImplCanvasBuilderImplProperties* properties) {
this->properties = properties;
this->m_properties_isSet = true;
}
bool
OAIComDayCqWcmDesignimporterImplCanvasBuilderImplInfo::isSet(){
bool isObjectUpdated = false;
do{
if(pid != nullptr && *pid != QString("")){ isObjectUpdated = true; break;}
if(title != nullptr && *title != QString("")){ isObjectUpdated = true; break;}
if(description != nullptr && *description != QString("")){ isObjectUpdated = true; break;}
if(properties != nullptr && properties->isSet()){ isObjectUpdated = true; break;}
}while(false);
return isObjectUpdated;
}
}
| [
"[email protected]"
] | |
9725f06117ea50fda953a975efd3293ec1d6faa0 | 8a2d3bba659ceffdb260c5e0cf3a064aa67f132d | /zestaw 6/zad6.cpp | e62e05b80fda28744acdf941315fe1168ac08924 | [] | no_license | maciejsikora2302/WDI--Introduction-to-Computer-Science | 7c1a96effe975be7192d22ca929166ba44ab0f0c | 7e557f2c664adb8bb42b1cc664b74a9768cf38a1 | refs/heads/master | 2020-05-03T23:43:46.941672 | 2019-04-01T13:58:59 | 2019-04-01T13:58:59 | 178,871,156 | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 1,117 | cpp | // ConsoleApplication2.cpp : Ten plik zawiera funkcję „main”. W nim rozpoczyna się i kończy wykonywanie programu.
//
#include<iostream>
#include <cmath>
using namespace std;
const int N = 6;
int liczba(int t[N], int pocz, int kon) {
int l = 0, pod = 1;
for (int i = kon; i >= pocz; i--) {
l += pod * t[i];
pod *= 2;
}
return l;
}
bool pierwsza(int a) {
if (a < 2) return false;
if (a == 2) return true;
if (a%2 == 0) return false;
for (int i = 3; i <= sqrt(a); i += 2) {
if (a%i == 0) return false;
}
return true;
}
void zad6(int t[N], int start, bool &odp) {
for (int i = start; i < N; i++) {
int l = liczba(t, start, i);
if(i-start==30){
cout << "nie da sie" << endl;
odp=true;
}
if (i + 1 < N and pierwsza(l)) {
zad6(t, i + 1, odp);
}
}
if (start == 0 and !odp) {
cout << "nie da sie" << endl;
}
if (pierwsza(liczba(t, start, N - 1)) and !odp) {
cout << "da sie " << endl;
odp = true;
}
}
void zad6_main(int t[N]){
bool superzmienna = false;
zad6(t, 0, superzmienna);
}
int main() {
int tab[N] = { 1,1,0,1,0,0 };
zad6_main(tab);
}
| [
"[email protected]"
] | |
f18ca7801703570671b4e9817172776908dda53b | 948f4e13af6b3014582909cc6d762606f2a43365 | /testcases/juliet_test_suite/testcases/CWE190_Integer_Overflow/s05/CWE190_Integer_Overflow__unsigned_int_max_square_81.h | 0fc55589d5c6ef60f98d357d7ad4ff7f397163c2 | [] | no_license | junxzm1990/ASAN-- | 0056a341b8537142e10373c8417f27d7825ad89b | ca96e46422407a55bed4aa551a6ad28ec1eeef4e | refs/heads/master | 2022-08-02T15:38:56.286555 | 2022-06-16T22:19:54 | 2022-06-16T22:19:54 | 408,238,453 | 74 | 13 | null | 2022-06-16T22:19:55 | 2021-09-19T21:14:59 | null | UTF-8 | C++ | false | false | 1,578 | h | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE190_Integer_Overflow__unsigned_int_max_square_81.h
Label Definition File: CWE190_Integer_Overflow.label.xml
Template File: sources-sinks-81.tmpl.h
*/
/*
* @description
* CWE: 190 Integer Overflow
* BadSource: max Set data to the max value for unsigned int
* GoodSource: Set data to a small, non-zero number (two)
* Sinks: square
* GoodSink: Ensure there will not be an overflow before squaring data
* BadSink : Square data, which can lead to overflow
* Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference
*
* */
#include "std_testcase.h"
namespace CWE190_Integer_Overflow__unsigned_int_max_square_81
{
class CWE190_Integer_Overflow__unsigned_int_max_square_81_base
{
public:
/* pure virtual function */
virtual void action(unsigned int data) const = 0;
};
#ifndef OMITBAD
class CWE190_Integer_Overflow__unsigned_int_max_square_81_bad : public CWE190_Integer_Overflow__unsigned_int_max_square_81_base
{
public:
void action(unsigned int data) const;
};
#endif /* OMITBAD */
#ifndef OMITGOOD
class CWE190_Integer_Overflow__unsigned_int_max_square_81_goodG2B : public CWE190_Integer_Overflow__unsigned_int_max_square_81_base
{
public:
void action(unsigned int data) const;
};
class CWE190_Integer_Overflow__unsigned_int_max_square_81_goodB2G : public CWE190_Integer_Overflow__unsigned_int_max_square_81_base
{
public:
void action(unsigned int data) const;
};
#endif /* OMITGOOD */
}
| [
"[email protected]"
] | |
313b709cad4eb37e451c3731feba07fa19e47723 | aefe0e674b19382754d4df1fc1d35e2570a7d259 | /Source/FurryTest/FurryTestGameMode.cpp | e0aabf235fe2c3341908399551599f114359f2b6 | [] | no_license | Auseng/FurryTest | 8f8bed55de62e9515edc14749281db16151d2694 | 55f3c7dd9b9666bea1fa3db11db545618a135c96 | refs/heads/master | 2020-03-17T22:08:41.748841 | 2018-05-18T23:56:49 | 2018-05-18T23:56:49 | 133,989,711 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 486 | cpp | // Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
#include "FurryTestGameMode.h"
#include "FurryTestCharacter.h"
#include "UObject/ConstructorHelpers.h"
AFurryTestGameMode::AFurryTestGameMode()
{
// set default pawn class to our Blueprinted character
static ConstructorHelpers::FClassFinder<APawn> PlayerPawnBPClass(TEXT("/Game/ThirdPersonCPP/Blueprints/ThirdPersonCharacter"));
if (PlayerPawnBPClass.Class != NULL)
{
DefaultPawnClass = PlayerPawnBPClass.Class;
}
}
| [
"[email protected]"
] | |
dfd88f0d75a78db9d3480364c3eaf9af5c5cdf04 | 3314307a5199fdc855c70970682345a1ac85c61d | /src/Core/PCM/PCMManager.cpp | 8f26a2aed6e419ea025a4ec12ac375f14f2967ca | [] | no_license | Botbusters4635/2020RobotCode | 546b5c82cd41dc39a779c8c59ab6558b0eb4cc94 | 2d4880df4aab45b0c5ce47f3c02fe66bb0bbe532 | refs/heads/master | 2023-02-20T10:40:25.212929 | 2021-01-19T02:11:46 | 2021-01-19T02:11:46 | 329,182,159 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,344 | cpp | //
// Created by abiel on 8/22/19.
//
#include "PCMManager.h"
PCMManager::PCMManager() : Manager("PCMManager") {
log->info("Initializing PCMManager...");
pistonsConfig = settings->getAllOfGroup("Pistons");
initializePistons();
}
void PCMManager::initializePistons() {
for (auto const &configEntry : pistonsConfig) {
size_t propertySeparator = configEntry.first.find('.');
std::string pistonName = configEntry.first.substr(0, propertySeparator);
std::string propertyName = configEntry.first.substr(propertySeparator + 1);
auto pistonIt = pistons.find(pistonName);
if (pistonIt == pistons.end()) {
pistonIt = pistons.emplace(pistonName, EctoPiston()).first;
}
if (propertyName == EctoPCMPropertyNames::id) {
std::stringstream ss(configEntry.second);
std::string token;
std::vector<int> ids;
while (std::getline(ss, token, ' ')) {
ids.emplace_back(std::stoi(token));
}
if (ids.size() > 1) {
pistonIt->second.isSingleSolenoid = false;
pistonIt->second.aSolenoid = std::make_shared<frc::Solenoid>(ids.front());
pistonIt->second.bSolenoid = std::make_shared<frc::Solenoid>(ids.at(1));
} else if (!ids.empty()) {
pistonIt->second.isSingleSolenoid = true;
pistonIt->second.aSolenoid = std::make_shared<frc::Solenoid>(ids.front());
} else {
throw std::invalid_argument("No valid ID given for piston: " + pistonName);
}
}
log->info("Added piston {}", pistonName);
}
}
EctoPiston &PCMManager::getPiston(const std::string &pistonName) {
auto piston = pistons.find(pistonName);
if (piston == pistons.end()) {
log->error("Invalid piston name: {}", pistonName);
throw std::runtime_error(fmt::format("Invalid piston name: {}", pistonName));
}
return piston->second;
}
void PCMManager::setPistonState(EctoPiston &piston, bool newState) {
piston.aSolenoid->Set(newState);
piston.bSolenoid->Set(!newState);
piston.currentState = newState;
}
void PCMManager::setPistonState(const std::string &pistonName, bool newState) {
setPistonState(getPiston(pistonName), newState);
}
void PCMManager::togglePistonState(EctoPiston &piston) {
setPistonState(piston, !piston.currentState);
}
void PCMManager::togglePistonState(const std::string &pistonName) {
togglePistonState(getPiston(pistonName));
}
void PCMManager::update() {
;
} | [
"[email protected]"
] | |
414b7fb687a6a1af20add0dfbb1493e52c7c1d1a | 51e8abe780348857f5023fe97810d6f1fdd5f690 | /opengl7/filters/AberrationFilter.cpp | 77c3a92dd3204311dbbaeb3716e97dafff2d0e7d | [] | no_license | rbaygildin/learn-graphics | 959a0182d7a81a7a3c33349e337aa5adea0ff32c | b6b88659b4028a6e3b5c05c68954503afd3e1c97 | refs/heads/master | 2021-09-15T03:08:58.803772 | 2018-05-24T19:00:44 | 2018-05-24T19:00:44 | 109,318,622 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 363 | cpp | //
// Created by Max Heartfield on 15.03.18.
//
#include "AberrationFilter.h"
AberrationFilter::AberrationFilter() {
addShaderFromSourceCode(QOpenGLShader::Vertex, readFile(VERT_PATH));
addShaderFromSourceCode(QOpenGLShader::Fragment, readFile(FRAG_PATH));
bindAttributeLocation("vertex", 0);
bindAttributeLocation("texCoord", 1);
link();
}
| [
"[email protected]"
] | |
fa9a2965b179ebf73bfd20aa5ec4d5eacdea26e8 | 7c7ca9efe5869a805a3c5238425be185758a71ce | /marsksim/boost/mpl/aux_/preprocessed/no_ctps/reverse_iter_fold_impl.hpp | f6e39aff07ff9d2cd2fd003ba2e66979d0fbd381 | [] | no_license | cansou/MyCustomMars | f332e6a1332eed9184838200d21cd36f5b57d3c9 | fb62f268a1913a70c39df329ef39df6034baac60 | refs/heads/master | 2022-10-20T18:53:22.220235 | 2020-06-12T08:46:25 | 2020-06-12T08:46:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,624 | hpp |
// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Preprocessed version of "boost/mpl/aux_/reverse_iter_fold_impl.hpp" header
// -- DO NOT modify by hand!
namespace mars_boost_ksim {} namespace boost_ksim = mars_boost_ksim; namespace mars_boost_ksim { namespace mpl { namespace aux {
/// forward declaration
template<
long N
, typename First
, typename Last
, typename State
, typename BackwardOp
, typename ForwardOp
>
struct reverse_iter_fold_impl;
template< long N >
struct reverse_iter_fold_chunk;
template<> struct reverse_iter_fold_chunk<0>
{
template<
typename First
, typename Last
, typename State
, typename BackwardOp
, typename ForwardOp
>
struct result_
{
typedef First iter0;
typedef State fwd_state0;
typedef fwd_state0 bkwd_state0;
typedef bkwd_state0 state;
typedef iter0 iterator;
};
};
template<> struct reverse_iter_fold_chunk<1>
{
template<
typename First
, typename Last
, typename State
, typename BackwardOp
, typename ForwardOp
>
struct result_
{
typedef First iter0;
typedef State fwd_state0;
typedef typename apply2< ForwardOp,fwd_state0,iter0 >::type fwd_state1;
typedef typename mpl::next<iter0>::type iter1;
typedef fwd_state1 bkwd_state1;
typedef typename apply2< BackwardOp,bkwd_state1,iter0 >::type bkwd_state0;
typedef bkwd_state0 state;
typedef iter1 iterator;
};
};
template<> struct reverse_iter_fold_chunk<2>
{
template<
typename First
, typename Last
, typename State
, typename BackwardOp
, typename ForwardOp
>
struct result_
{
typedef First iter0;
typedef State fwd_state0;
typedef typename apply2< ForwardOp,fwd_state0,iter0 >::type fwd_state1;
typedef typename mpl::next<iter0>::type iter1;
typedef typename apply2< ForwardOp,fwd_state1,iter1 >::type fwd_state2;
typedef typename mpl::next<iter1>::type iter2;
typedef fwd_state2 bkwd_state2;
typedef typename apply2< BackwardOp,bkwd_state2,iter1 >::type bkwd_state1;
typedef typename apply2< BackwardOp,bkwd_state1,iter0 >::type bkwd_state0;
typedef bkwd_state0 state;
typedef iter2 iterator;
};
};
template<> struct reverse_iter_fold_chunk<3>
{
template<
typename First
, typename Last
, typename State
, typename BackwardOp
, typename ForwardOp
>
struct result_
{
typedef First iter0;
typedef State fwd_state0;
typedef typename apply2< ForwardOp,fwd_state0,iter0 >::type fwd_state1;
typedef typename mpl::next<iter0>::type iter1;
typedef typename apply2< ForwardOp,fwd_state1,iter1 >::type fwd_state2;
typedef typename mpl::next<iter1>::type iter2;
typedef typename apply2< ForwardOp,fwd_state2,iter2 >::type fwd_state3;
typedef typename mpl::next<iter2>::type iter3;
typedef fwd_state3 bkwd_state3;
typedef typename apply2< BackwardOp,bkwd_state3,iter2 >::type bkwd_state2;
typedef typename apply2< BackwardOp,bkwd_state2,iter1 >::type bkwd_state1;
typedef typename apply2< BackwardOp,bkwd_state1,iter0 >::type bkwd_state0;
typedef bkwd_state0 state;
typedef iter3 iterator;
};
};
template<> struct reverse_iter_fold_chunk<4>
{
template<
typename First
, typename Last
, typename State
, typename BackwardOp
, typename ForwardOp
>
struct result_
{
typedef First iter0;
typedef State fwd_state0;
typedef typename apply2< ForwardOp,fwd_state0,iter0 >::type fwd_state1;
typedef typename mpl::next<iter0>::type iter1;
typedef typename apply2< ForwardOp,fwd_state1,iter1 >::type fwd_state2;
typedef typename mpl::next<iter1>::type iter2;
typedef typename apply2< ForwardOp,fwd_state2,iter2 >::type fwd_state3;
typedef typename mpl::next<iter2>::type iter3;
typedef typename apply2< ForwardOp,fwd_state3,iter3 >::type fwd_state4;
typedef typename mpl::next<iter3>::type iter4;
typedef fwd_state4 bkwd_state4;
typedef typename apply2< BackwardOp,bkwd_state4,iter3 >::type bkwd_state3;
typedef typename apply2< BackwardOp,bkwd_state3,iter2 >::type bkwd_state2;
typedef typename apply2< BackwardOp,bkwd_state2,iter1 >::type bkwd_state1;
typedef typename apply2< BackwardOp,bkwd_state1,iter0 >::type bkwd_state0;
typedef bkwd_state0 state;
typedef iter4 iterator;
};
};
template< long N >
struct reverse_iter_fold_chunk
{
template<
typename First
, typename Last
, typename State
, typename BackwardOp
, typename ForwardOp
>
struct result_
{
typedef First iter0;
typedef State fwd_state0;
typedef typename apply2< ForwardOp,fwd_state0,iter0 >::type fwd_state1;
typedef typename mpl::next<iter0>::type iter1;
typedef typename apply2< ForwardOp,fwd_state1,iter1 >::type fwd_state2;
typedef typename mpl::next<iter1>::type iter2;
typedef typename apply2< ForwardOp,fwd_state2,iter2 >::type fwd_state3;
typedef typename mpl::next<iter2>::type iter3;
typedef typename apply2< ForwardOp,fwd_state3,iter3 >::type fwd_state4;
typedef typename mpl::next<iter3>::type iter4;
typedef reverse_iter_fold_impl<
( (N - 4) < 0 ? 0 : N - 4 )
, iter4
, Last
, fwd_state4
, BackwardOp
, ForwardOp
> nested_chunk;
typedef typename nested_chunk::state bkwd_state4;
typedef typename apply2< BackwardOp,bkwd_state4,iter3 >::type bkwd_state3;
typedef typename apply2< BackwardOp,bkwd_state3,iter2 >::type bkwd_state2;
typedef typename apply2< BackwardOp,bkwd_state2,iter1 >::type bkwd_state1;
typedef typename apply2< BackwardOp,bkwd_state1,iter0 >::type bkwd_state0;
typedef bkwd_state0 state;
typedef typename nested_chunk::iterator iterator;
};
};
template<
typename First
, typename Last
, typename State
, typename BackwardOp
, typename ForwardOp
>
struct reverse_iter_fold_step;
template<
typename Last
, typename State
>
struct reverse_iter_fold_null_step
{
typedef Last iterator;
typedef State state;
};
template<>
struct reverse_iter_fold_chunk< -1 >
{
template<
typename First
, typename Last
, typename State
, typename BackwardOp
, typename ForwardOp
>
struct result_
{
typedef typename if_<
typename is_same< First,Last >::type
, reverse_iter_fold_null_step< Last,State >
, reverse_iter_fold_step< First,Last,State,BackwardOp,ForwardOp >
>::type res_;
typedef typename res_::state state;
typedef typename res_::iterator iterator;
};
};
template<
typename First
, typename Last
, typename State
, typename BackwardOp
, typename ForwardOp
>
struct reverse_iter_fold_step
{
typedef reverse_iter_fold_chunk< -1 >::template result_<
typename mpl::next<First>::type
, Last
, typename apply2< ForwardOp,State,First >::type
, BackwardOp
, ForwardOp
> nested_step;
typedef typename apply2<
BackwardOp
, typename nested_step::state
, First
>::type state;
typedef typename nested_step::iterator iterator;
};
template<
long N
, typename First
, typename Last
, typename State
, typename BackwardOp
, typename ForwardOp
>
struct reverse_iter_fold_impl
: reverse_iter_fold_chunk<N>
::template result_< First,Last,State,BackwardOp,ForwardOp >
{
};
}}}
| [
""
] | |
097f338633370b41fff291e5e855f3eff16a9941 | be4952850ad6a8b0abe50de671c495c6add9fae7 | /codeforce/CF_841A.cpp | 461dccea773d04fac1718874d908a38b17641daf | [] | no_license | ss5ssmi/OJ | 296cb936ecf7ef292e91f24178c9c08bd2d241b5 | 267184cef5f1bc1f222950a71fe705bbc5f0bb3e | refs/heads/master | 2022-10-29T18:15:14.290028 | 2022-10-12T04:42:47 | 2022-10-12T04:42:47 | 103,818,651 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 314 | cpp | #include<bits/stdc++.h>
using namespace std;
int main() {
int n,k,t[26]={0},sum=0,maxt=-1;
char s[100];
scanf("%d%d",&n,&k);
scanf("%s",s);
for(int i=0;i<n;i++){
t[s[i]-'a']++;
}
sort(t,t+26);
for(int i=1;i<26;i++){
sum=max(sum,t[i]);
}
if(sum<=k) printf("YES\n");
else printf("NO\n");
return 0;
}
| [
"[email protected]"
] | |
827fd0640d571670a0fe31509395bad903ea24b4 | 0e4a14372d86ed9d008f394bd3a1b9fd58ea2b68 | /cpp-course/chapter9/chapter9.cpp | 432d47e3f7e88fdf3509032abd4e0543dfa33ebe | [
"MIT"
] | permissive | jacekplocharczyk/cpp-course | 8e0f2492182bd7c13293cae191b010c2f211c415 | 1653c1001041efb02a56a6eda3ffceefd8b0b67d | refs/heads/master | 2021-06-08T17:26:00.489156 | 2018-08-06T11:09:47 | 2018-08-06T11:09:47 | 141,833,629 | 0 | 0 | MIT | 2021-04-23T07:57:44 | 2018-07-21T17:38:37 | C++ | UTF-8 | C++ | false | false | 113 | cpp | #include "drill.h"
int main() {
//drill1();
//drill2();
//drill3();
//drill4();
drill5();
return 0;
} | [
"[email protected]"
] | |
b49ba4ff33eb3729809928eb84133519a6108c29 | 131e65509db2c7e34b6ac41717fe8cf19c4fe726 | /dp2.cpp | 133e9b55ce49ad2257df80077cc6d40cdf5a35eb | [] | no_license | Keepen/DP | 167335346587f70abb28f6209392c4c12b1e39df | c1e05dda155c38ccd903a8e42c3f30c75caab0cd | refs/heads/master | 2022-12-03T09:11:49.906024 | 2020-08-03T15:14:45 | 2020-08-03T15:14:45 | 281,422,314 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,098 | cpp | //问题描述:
// 在一个数组中,给定一个目标数字S,求在该数组中能否找到几个数的和刚好等于目标数字
// 能:true;不能:false
//思路:
// 还是要与不要的原则
// 如果要当前数字 :就看前i - 1个数字能否拼成 S - v[i]
// 如果不要当前数字:就看前 i - 1个数字能否拼成 S
#include <iostream>
#include <vector>
using namespace std;
//递归版本
bool isOK(vector<int>& v, int i, int s){
if(s == 0){
return true;
}
else if(i == 0){
return v[0] == s;
}
else if (v[i] > s){
return isOK(v, i - 1, s);
}
else{
//要当前数字
bool a = isOK(v, i - 1, s - v[i]);
//不要当前数字
bool b = isOK(v, i - 1, s);
return a || b;
}
}
//非递归版本
//利用二维数组:v.size() * s --- v.size()行,s列的数组
// ret[i][j]表示,前i个数字能否拼成和为数字j
bool unrec_isOK(vector<int>& v, int s){
vector<vector<bool>> ret(v.size(), vector<bool>(s + 1, false));
ret[0][v[0]] = true; //初始化了第一行的值
for(int i = 1;i < v.size();++i){
for(int j = 0;j <= s;++j){
if(j == 0){
ret[i][j] = true;
}
//如果出现比目标数字大的就不要选
if(v[i] > j){
ret[i][j] = ret[i - 1][j];
}
//等于目标数字就是true
else if(v[i] == j){
ret[i][j] = true;
}
else{
// 选 不选
ret[i][j] = ret[i - 1][j - v[i]] || ret[i - 1][j];
}
}
}
return ret[v.size() - 1][s];
}
void solu(){
vector<int> v = {3,34,4,12,5,2};
int s = 9;
while(cin >> s){
//bool key = isOK(v, v.size() - 1, s);
bool key = unrec_isOK(v, s);
if(key){
cout << "true" << endl;
}
else{
cout << "false" << endl;
}
}
}
int main(){
solu();
return 0;
} | [
"[email protected]"
] | |
9274fd5f94c83f43abc296b1a253773ce3dfa70d | 4f0a96aa4642a735f71704c360beb2a5d4dd9a9e | /apps/OpenVizEarth/UIFacade.h | ae2ad468076c63f21eb47d54ad56747c850eee12 | [] | no_license | longyangzz/OpenVizEarth | 79f3f2873329d92b5749500c0dfbde128e0cfb13 | e8477ba4c7a48be37e6246cd98836895b086ae7d | refs/heads/master | 2022-09-18T19:58:33.747036 | 2022-08-07T07:05:52 | 2022-08-07T07:05:52 | 192,552,174 | 33 | 19 | null | 2019-10-06T11:37:56 | 2019-06-18T14:05:21 | C++ | UTF-8 | C++ | false | false | 1,765 | h | #ifndef ATLAS_H
#define ATLAS_H
#include <MainWindow.h>
#include "../NameSpace.h"
#include <osg/Object>
#include <osg/Node>
#include <osg/BoundingSphere>
namespace osg
{
class Group;
class PositionAttitudeTransform;
}
namespace osgSim
{
class OverlayNode;
}
namespace osgText
{
class Font;
}
namespace osgEarth
{
class Map;
class MapNode;
}
class UIFacade: public MainWindow
{
Q_OBJECT
public:
UIFacade(QWidget *parent = nullptr, Qt::WindowFlags flags = 0);
~UIFacade();
void initAll();
private:
// 加载语言文件
void LoadLanguages();
void initView();
void initDCUIVar();
void InitManager();
void initDataManagerAndScene();
void initPlugins();
void initLog();
void setupUi();
void collectInitInfo();
//UI style
void initUiStyles();
public slots:
// View related slots
void resetCamera();
void HandlingEntitiesChanged(const QVector<osg::Node*>& nodes);
void printToLogConsole(const QString & mess);
void printToLogConsole(const QStringList & mess);
signals:
// For splash screen
void sendTotalInitSteps(int);
void sendNowInitName(const QString&);
private:
std::ofstream *_log;
// Root for all
osg::ref_ptr<osg::Group> _root;
// Root for all data that can be projected on
osg::ref_ptr<osgSim::OverlayNode> _dataOverlay;
// Node that is projected to the _dataOverlay
osg::ref_ptr<osg::Group> _overlaySubgraph;
// Root for all drawings
osg::ref_ptr<osg::Group> _drawRoot;
// Root for osgEarth maps
osg::ref_ptr<osg::Group> _mapRoot;
// Root for osg format data
osg::ref_ptr<osg::Group> _dataRoot;
osg::ref_ptr<osgEarth::MapNode> _mapNode[MAX_SUBVIEW];
osg::ref_ptr<osgEarth::Map> _mainMap[MAX_SUBVIEW];
};
#endif
| [
"[email protected]"
] | |
9136b2387e0e8aaa2cc49f679d0a63b95790108f | 2678798b354051ec740e0cd9a8cad6797a2ab9f1 | /src/test/transaction_tests.cpp | 9310b1cfd7eae54f7cc70f556d95d5cf62614568 | [
"MIT"
] | permissive | klauson/Corvus | 17f7a5c7eec0b13cc93fb1859a9a37a27b1585d0 | 69f8371131dd1b2f77a3f5f6f7022a7ed6b26674 | refs/heads/master | 2020-03-14T03:02:04.163437 | 2018-04-28T14:34:14 | 2018-04-28T14:34:14 | 131,411,768 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,466 | cpp | // Copyright (c) 2011-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "data/tx_invalid.json.h"
#include "data/tx_valid.json.h"
#include "test/test_corvus.h"
#include "clientversion.h"
#include "consensus/validation.h"
#include "core_io.h"
#include "key.h"
#include "keystore.h"
#include "validation.h" // For CheckTransaction
#include "policy/policy.h"
#include "script/script.h"
#include "script/script_error.h"
#include "utilstrencodings.h"
#include <map>
#include <string>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/assign/list_of.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/assign/list_of.hpp>
#include <univalue.h>
using namespace std;
// In script_tests.cpp
extern UniValue read_json(const std::string& jsondata);
static std::map<string, unsigned int> mapFlagNames = boost::assign::map_list_of
(string("NONE"), (unsigned int)SCRIPT_VERIFY_NONE)
(string("P2SH"), (unsigned int)SCRIPT_VERIFY_P2SH)
(string("STRICTENC"), (unsigned int)SCRIPT_VERIFY_STRICTENC)
(string("DERSIG"), (unsigned int)SCRIPT_VERIFY_DERSIG)
(string("LOW_S"), (unsigned int)SCRIPT_VERIFY_LOW_S)
(string("SIGPUSHONLY"), (unsigned int)SCRIPT_VERIFY_SIGPUSHONLY)
(string("MINIMALDATA"), (unsigned int)SCRIPT_VERIFY_MINIMALDATA)
(string("NULLDUMMY"), (unsigned int)SCRIPT_VERIFY_NULLDUMMY)
(string("DISCOURAGE_UPGRADABLE_NOPS"), (unsigned int)SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)
(string("CLEANSTACK"), (unsigned int)SCRIPT_VERIFY_CLEANSTACK)
(string("CHECKLOCKTIMEVERIFY"), (unsigned int)SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)
(string("CHECKSEQUENCEVERIFY"), (unsigned int)SCRIPT_VERIFY_CHECKSEQUENCEVERIFY);
unsigned int ParseScriptFlags(string strFlags)
{
if (strFlags.empty()) {
return 0;
}
unsigned int flags = 0;
vector<string> words;
boost::algorithm::split(words, strFlags, boost::algorithm::is_any_of(","));
BOOST_FOREACH(string word, words)
{
if (!mapFlagNames.count(word))
BOOST_ERROR("Bad test: unknown verification flag '" << word << "'");
flags |= mapFlagNames[word];
}
return flags;
}
string FormatScriptFlags(unsigned int flags)
{
if (flags == 0) {
return "";
}
string ret;
std::map<string, unsigned int>::const_iterator it = mapFlagNames.begin();
while (it != mapFlagNames.end()) {
if (flags & it->second) {
ret += it->first + ",";
}
it++;
}
return ret.substr(0, ret.size() - 1);
}
BOOST_FIXTURE_TEST_SUITE(transaction_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(tx_valid)
{
// Read tests from test/data/tx_valid.json
// Format is an array of arrays
// Inner arrays are either [ "comment" ]
// or [[[prevout hash, prevout index, prevout scriptPubKey], [input 2], ...],"], serializedTransaction, verifyFlags
// ... where all scripts are stringified scripts.
//
// verifyFlags is a comma separated list of script verification flags to apply, or "NONE"
UniValue tests = read_json(std::string(json_tests::tx_valid, json_tests::tx_valid + sizeof(json_tests::tx_valid)));
ScriptError err;
for (unsigned int idx = 0; idx < tests.size(); idx++) {
UniValue test = tests[idx];
string strTest = test.write();
if (test[0].isArray())
{
if (test.size() != 3 || !test[1].isStr() || !test[2].isStr())
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
map<COutPoint, CScript> mapprevOutScriptPubKeys;
UniValue inputs = test[0].get_array();
bool fValid = true;
for (unsigned int inpIdx = 0; inpIdx < inputs.size(); inpIdx++) {
const UniValue& input = inputs[inpIdx];
if (!input.isArray())
{
fValid = false;
break;
}
UniValue vinput = input.get_array();
if (vinput.size() != 3)
{
fValid = false;
break;
}
mapprevOutScriptPubKeys[COutPoint(uint256S(vinput[0].get_str()), vinput[1].get_int())] = ParseScript(vinput[2].get_str());
}
if (!fValid)
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
string transaction = test[1].get_str();
CDataStream stream(ParseHex(transaction), SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
stream >> tx;
CValidationState state;
BOOST_CHECK_MESSAGE(CheckTransaction(tx, state), strTest);
BOOST_CHECK(state.IsValid());
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
if (!mapprevOutScriptPubKeys.count(tx.vin[i].prevout))
{
BOOST_ERROR("Bad test: " << strTest);
break;
}
unsigned int verify_flags = ParseScriptFlags(test[2].get_str());
BOOST_CHECK_MESSAGE(VerifyScript(tx.vin[i].scriptSig, mapprevOutScriptPubKeys[tx.vin[i].prevout],
verify_flags, TransactionSignatureChecker(&tx, i), &err),
strTest);
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
}
}
}
}
BOOST_AUTO_TEST_CASE(tx_invalid)
{
// Read tests from test/data/tx_invalid.json
// Format is an array of arrays
// Inner arrays are either [ "comment" ]
// or [[[prevout hash, prevout index, prevout scriptPubKey], [input 2], ...],"], serializedTransaction, verifyFlags
// ... where all scripts are stringified scripts.
//
// verifyFlags is a comma separated list of script verification flags to apply, or "NONE"
UniValue tests = read_json(std::string(json_tests::tx_invalid, json_tests::tx_invalid + sizeof(json_tests::tx_invalid)));
ScriptError err;
for (unsigned int idx = 0; idx < tests.size(); idx++) {
UniValue test = tests[idx];
string strTest = test.write();
if (test[0].isArray())
{
if (test.size() != 3 || !test[1].isStr() || !test[2].isStr())
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
map<COutPoint, CScript> mapprevOutScriptPubKeys;
UniValue inputs = test[0].get_array();
bool fValid = true;
for (unsigned int inpIdx = 0; inpIdx < inputs.size(); inpIdx++) {
const UniValue& input = inputs[inpIdx];
if (!input.isArray())
{
fValid = false;
break;
}
UniValue vinput = input.get_array();
if (vinput.size() != 3)
{
fValid = false;
break;
}
mapprevOutScriptPubKeys[COutPoint(uint256S(vinput[0].get_str()), vinput[1].get_int())] = ParseScript(vinput[2].get_str());
}
if (!fValid)
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
string transaction = test[1].get_str();
CDataStream stream(ParseHex(transaction), SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
stream >> tx;
CValidationState state;
fValid = CheckTransaction(tx, state) && state.IsValid();
for (unsigned int i = 0; i < tx.vin.size() && fValid; i++)
{
if (!mapprevOutScriptPubKeys.count(tx.vin[i].prevout))
{
BOOST_ERROR("Bad test: " << strTest);
break;
}
unsigned int verify_flags = ParseScriptFlags(test[2].get_str());
fValid = VerifyScript(tx.vin[i].scriptSig, mapprevOutScriptPubKeys[tx.vin[i].prevout],
verify_flags, TransactionSignatureChecker(&tx, i), &err);
}
BOOST_CHECK_MESSAGE(!fValid, strTest);
BOOST_CHECK_MESSAGE(err != SCRIPT_ERR_OK, ScriptErrorString(err));
}
}
}
BOOST_AUTO_TEST_CASE(basic_transaction_tests)
{
// Random real transaction (e2769b09e784f32f62ef849763d4f45b98e07ba658647343b915ff832b110436)
unsigned char ch[] = {0x01, 0x00, 0x00, 0x00, 0x01, 0x6b, 0xff, 0x7f, 0xcd, 0x4f, 0x85, 0x65, 0xef, 0x40, 0x6d, 0xd5, 0xd6, 0x3d, 0x4f, 0xf9, 0x4f, 0x31, 0x8f, 0xe8, 0x20, 0x27, 0xfd, 0x4d, 0xc4, 0x51, 0xb0, 0x44, 0x74, 0x01, 0x9f, 0x74, 0xb4, 0x00, 0x00, 0x00, 0x00, 0x8c, 0x49, 0x30, 0x46, 0x02, 0x21, 0x00, 0xda, 0x0d, 0xc6, 0xae, 0xce, 0xfe, 0x1e, 0x06, 0xef, 0xdf, 0x05, 0x77, 0x37, 0x57, 0xde, 0xb1, 0x68, 0x82, 0x09, 0x30, 0xe3, 0xb0, 0xd0, 0x3f, 0x46, 0xf5, 0xfc, 0xf1, 0x50, 0xbf, 0x99, 0x0c, 0x02, 0x21, 0x00, 0xd2, 0x5b, 0x5c, 0x87, 0x04, 0x00, 0x76, 0xe4, 0xf2, 0x53, 0xf8, 0x26, 0x2e, 0x76, 0x3e, 0x2d, 0xd5, 0x1e, 0x7f, 0xf0, 0xbe, 0x15, 0x77, 0x27, 0xc4, 0xbc, 0x42, 0x80, 0x7f, 0x17, 0xbd, 0x39, 0x01, 0x41, 0x04, 0xe6, 0xc2, 0x6e, 0xf6, 0x7d, 0xc6, 0x10, 0xd2, 0xcd, 0x19, 0x24, 0x84, 0x78, 0x9a, 0x6c, 0xf9, 0xae, 0xa9, 0x93, 0x0b, 0x94, 0x4b, 0x7e, 0x2d, 0xb5, 0x34, 0x2b, 0x9d, 0x9e, 0x5b, 0x9f, 0xf7, 0x9a, 0xff, 0x9a, 0x2e, 0xe1, 0x97, 0x8d, 0xd7, 0xfd, 0x01, 0xdf, 0xc5, 0x22, 0xee, 0x02, 0x28, 0x3d, 0x3b, 0x06, 0xa9, 0xd0, 0x3a, 0xcf, 0x80, 0x96, 0x96, 0x8d, 0x7d, 0xbb, 0x0f, 0x91, 0x78, 0xff, 0xff, 0xff, 0xff, 0x02, 0x8b, 0xa7, 0x94, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x19, 0x76, 0xa9, 0x14, 0xba, 0xde, 0xec, 0xfd, 0xef, 0x05, 0x07, 0x24, 0x7f, 0xc8, 0xf7, 0x42, 0x41, 0xd7, 0x3b, 0xc0, 0x39, 0x97, 0x2d, 0x7b, 0x88, 0xac, 0x40, 0x94, 0xa8, 0x02, 0x00, 0x00, 0x00, 0x00, 0x19, 0x76, 0xa9, 0x14, 0xc1, 0x09, 0x32, 0x48, 0x3f, 0xec, 0x93, 0xed, 0x51, 0xf5, 0xfe, 0x95, 0xe7, 0x25, 0x59, 0xf2, 0xcc, 0x70, 0x43, 0xf9, 0x88, 0xac, 0x00, 0x00, 0x00, 0x00, 0x00};
vector<unsigned char> vch(ch, ch + sizeof(ch) -1);
CDataStream stream(vch, SER_DISK, CLIENT_VERSION);
CMutableTransaction tx;
stream >> tx;
CValidationState state;
BOOST_CHECK_MESSAGE(CheckTransaction(tx, state) && state.IsValid(), "Simple deserialized transaction should be valid.");
// Check that duplicate txins fail
tx.vin.push_back(tx.vin[0]);
BOOST_CHECK_MESSAGE(!CheckTransaction(tx, state) || !state.IsValid(), "Transaction with duplicate txins should be invalid.");
}
//
// Helper: create two dummy transactions, each with
// two outputs. The first has 11 and 50 CENT outputs
// paid to a TX_PUBKEY, the second 21 and 22 CENT outputs
// paid to a TX_PUBKEYHASH.
//
static std::vector<CMutableTransaction>
SetupDummyInputs(CBasicKeyStore& keystoreRet, CCoinsViewCache& coinsRet)
{
std::vector<CMutableTransaction> dummyTransactions;
dummyTransactions.resize(2);
// Add some keys to the keystore:
CKey key[4];
for (int i = 0; i < 4; i++)
{
key[i].MakeNewKey(i % 2);
keystoreRet.AddKey(key[i]);
}
// Create some dummy input transactions
dummyTransactions[0].vout.resize(2);
dummyTransactions[0].vout[0].nValue = 11*CENT;
dummyTransactions[0].vout[0].scriptPubKey << ToByteVector(key[0].GetPubKey()) << OP_CHECKSIG;
dummyTransactions[0].vout[1].nValue = 50*CENT;
dummyTransactions[0].vout[1].scriptPubKey << ToByteVector(key[1].GetPubKey()) << OP_CHECKSIG;
AddCoins(coinsRet, dummyTransactions[0], 0);
dummyTransactions[1].vout.resize(2);
dummyTransactions[1].vout[0].nValue = 21*CENT;
dummyTransactions[1].vout[0].scriptPubKey = GetScriptForDestination(key[2].GetPubKey().GetID());
dummyTransactions[1].vout[1].nValue = 22*CENT;
dummyTransactions[1].vout[1].scriptPubKey = GetScriptForDestination(key[3].GetPubKey().GetID());
AddCoins(coinsRet, dummyTransactions[1], 0);
return dummyTransactions;
}
BOOST_AUTO_TEST_CASE(test_Get)
{
CBasicKeyStore keystore;
CCoinsView coinsDummy;
CCoinsViewCache coins(&coinsDummy);
std::vector<CMutableTransaction> dummyTransactions = SetupDummyInputs(keystore, coins);
CMutableTransaction t1;
t1.vin.resize(3);
t1.vin[0].prevout.hash = dummyTransactions[0].GetHash();
t1.vin[0].prevout.n = 1;
t1.vin[0].scriptSig << std::vector<unsigned char>(65, 0);
t1.vin[1].prevout.hash = dummyTransactions[1].GetHash();
t1.vin[1].prevout.n = 0;
t1.vin[1].scriptSig << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4);
t1.vin[2].prevout.hash = dummyTransactions[1].GetHash();
t1.vin[2].prevout.n = 1;
t1.vin[2].scriptSig << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4);
t1.vout.resize(2);
t1.vout[0].nValue = 90*CENT;
t1.vout[0].scriptPubKey << OP_1;
BOOST_CHECK(AreInputsStandard(t1, coins));
BOOST_CHECK_EQUAL(coins.GetValueIn(t1), (50+21+22)*CENT);
}
BOOST_AUTO_TEST_CASE(test_IsStandard)
{
LOCK(cs_main);
CBasicKeyStore keystore;
CCoinsView coinsDummy;
CCoinsViewCache coins(&coinsDummy);
std::vector<CMutableTransaction> dummyTransactions = SetupDummyInputs(keystore, coins);
CMutableTransaction t;
t.vin.resize(1);
t.vin[0].prevout.hash = dummyTransactions[0].GetHash();
t.vin[0].prevout.n = 1;
t.vin[0].scriptSig << std::vector<unsigned char>(65, 0);
t.vout.resize(1);
t.vout[0].nValue = 90*CENT;
CKey key;
key.MakeNewKey(true);
t.vout[0].scriptPubKey = GetScriptForDestination(key.GetPubKey().GetID());
string reason;
BOOST_CHECK(IsStandardTx(t, reason));
// Check dust with default relay fee:
CAmount nDustThreshold = 182 * minRelayTxFee.GetFeePerK()/1000 * 3;
BOOST_CHECK_EQUAL(nDustThreshold, 546);
// dust:
t.vout[0].nValue = nDustThreshold - 1;
BOOST_CHECK(!IsStandardTx(t, reason));
// not dust:
t.vout[0].nValue = nDustThreshold;
BOOST_CHECK(IsStandardTx(t, reason));
// Check dust with odd relay fee to verify rounding:
// nDustThreshold = 182 * 1234 / 1000 * 3
minRelayTxFee = CFeeRate(1234);
// dust:
t.vout[0].nValue = 672 - 1;
BOOST_CHECK(!IsStandardTx(t, reason));
// not dust:
t.vout[0].nValue = 672;
BOOST_CHECK(IsStandardTx(t, reason));
minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
t.vout[0].scriptPubKey = CScript() << OP_1;
BOOST_CHECK(!IsStandardTx(t, reason));
// MAX_OP_RETURN_RELAY-byte TX_NULL_DATA (standard)
t.vout[0].scriptPubKey = CScript() << OP_RETURN << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef3804678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38");
BOOST_CHECK_EQUAL(MAX_OP_RETURN_RELAY, t.vout[0].scriptPubKey.size());
BOOST_CHECK(IsStandardTx(t, reason));
// MAX_OP_RETURN_RELAY+1-byte TX_NULL_DATA (non-standard)
t.vout[0].scriptPubKey = CScript() << OP_RETURN << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef3804678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef3800");
BOOST_CHECK_EQUAL(MAX_OP_RETURN_RELAY + 1, t.vout[0].scriptPubKey.size());
BOOST_CHECK(!IsStandardTx(t, reason));
// Data payload can be encoded in any way...
t.vout[0].scriptPubKey = CScript() << OP_RETURN << ParseHex("");
BOOST_CHECK(IsStandardTx(t, reason));
t.vout[0].scriptPubKey = CScript() << OP_RETURN << ParseHex("00") << ParseHex("01");
BOOST_CHECK(IsStandardTx(t, reason));
// OP_RESERVED *is* considered to be a PUSHDATA type opcode by IsPushOnly()!
t.vout[0].scriptPubKey = CScript() << OP_RETURN << OP_RESERVED << -1 << 0 << ParseHex("01") << 2 << 3 << 4 << 5 << 6 << 7 << 8 << 9 << 10 << 11 << 12 << 13 << 14 << 15 << 16;
BOOST_CHECK(IsStandardTx(t, reason));
t.vout[0].scriptPubKey = CScript() << OP_RETURN << 0 << ParseHex("01") << 2 << ParseHex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
BOOST_CHECK(IsStandardTx(t, reason));
// ...so long as it only contains PUSHDATA's
t.vout[0].scriptPubKey = CScript() << OP_RETURN << OP_RETURN;
BOOST_CHECK(!IsStandardTx(t, reason));
// TX_NULL_DATA w/o PUSHDATA
t.vout.resize(1);
t.vout[0].scriptPubKey = CScript() << OP_RETURN;
BOOST_CHECK(IsStandardTx(t, reason));
// Only one TX_NULL_DATA permitted in all cases
t.vout.resize(2);
t.vout[0].scriptPubKey = CScript() << OP_RETURN << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38");
t.vout[1].scriptPubKey = CScript() << OP_RETURN << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38");
BOOST_CHECK(!IsStandardTx(t, reason));
t.vout[0].scriptPubKey = CScript() << OP_RETURN << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38");
t.vout[1].scriptPubKey = CScript() << OP_RETURN;
BOOST_CHECK(!IsStandardTx(t, reason));
t.vout[0].scriptPubKey = CScript() << OP_RETURN;
t.vout[1].scriptPubKey = CScript() << OP_RETURN;
BOOST_CHECK(!IsStandardTx(t, reason));
}
BOOST_AUTO_TEST_SUITE_END()
| [
"[email protected]"
] | |
0e9d3a2cdbfc85da178b7ceadaa155d8bc8407f4 | 53b95dfec4ca824d1929dc9f03989e32c21e98b0 | /src/1671 - Shortest Routes I.cpp | 59e4a8ab5599aa80d03daed2fee57fc7ce571b6d | [] | no_license | fuad7161/CSES-Solutions | 612e81975c653c9bd1339fa65a56c28ea61d7a7a | cf324f66365ff2ce375e169bc22e69c18f86ca62 | refs/heads/master | 2023-08-24T16:43:20.772743 | 2021-09-23T03:40:18 | 2021-09-23T03:40:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,559 | cpp | /*
Problem Name: Shortest Routes I
Problem Link: https://cses.fi/problemset/task/1671
Author: Sachin Srivastava (mrsac7)
*/
#include<bits/stdc++.h>
using namespace std;
template<typename... T>
void see(T&... args) { ((cin >> args), ...);}
template<typename... T>
void put(T&&... args) { ((cout << args << " "), ...);}
template<typename... T>
void putl(T&&... args) { ((cout << args << " "), ...); cout<<'\n';}
#define error(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); }
void err(istream_iterator<string> it) {}
template<typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {cerr << *it << "=" << a << ", "; err(++it, args...);}
#define int long long
#define pb push_back
#define F first
#define S second
#define ll long long
#define ull unsigned long long
#define ld long double
#define pii pair<int,int>
#define vi vector<int>
#define vii vector<pii>
#define vc vector
#define L cout<<'\n';
#define E cerr<<'\n';
#define all(x) x.begin(),x.end()
#define rep(i,a,b) for (int i=a; i<b; ++i)
#define rev(i,a,b) for (int i=a; i>b; --i)
#define IOS ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define setpr(x) cout<<setprecision(x)<<fixed
#define sz size()
#define seea(a,x,y) for(int i=x;i<y;i++){cin>>a[i];}
#define seev(v,n) for(int i=0;i<n;i++){int x; cin>>x; v.push_back(x);}
#define sees(s,n) for(int i=0;i<n;i++){int x; cin>>x; s.insert(x);}
const ll inf = LLONG_MAX;
const ld ep = 0.0000001;
const ld pi = acos(-1.0);
const ll md = 1000000007;
int vis[100005], dis[100005];
vii adj[100005];
void solve(){
int n,m; see(n,m);
rep(i,0,m){
int u,v,w; see(u,v,w);
adj[u].pb({v,w});
}
//dijkstra
rep(i,2,n+1) dis[i]=inf;
priority_queue<pii,vii,greater<pii>> q;
q.push({0,1});
while(!q.empty()){
int u = q.top().S; q.pop();
if (vis[u]) continue;
vis[u]=1;
for (auto [v,w] : adj[u]){
if (dis[v]>dis[u]+w){
dis[v] = dis[u]+w;
q.push({dis[v],v});
}
}
}
rep(i,1,n+1) put(dis[i]);
}
signed main(){
IOS;
#ifdef LOCAL
freopen("input.txt", "r" , stdin);
freopen("output.txt", "w", stdout);
#endif
int t=1;
//cin>>t;
while(t--){
solve();
//cout<<'\n';
}
#ifdef LOCAL
clock_t tStart = clock();
cerr<<fixed<<setprecision(10)<<"\nTime Taken: "<<(double)(clock()- tStart)/CLOCKS_PER_SEC<<endl;
#endif
} | [
"[email protected]"
] | |
2583d37de31028267cd5c0003ec319e629a5843f | 45c884678c2077542ee5bcdbf1791f06a6ce2a9c | /AABB2D/Model.h | af1bce216055359bbfdddc5d1f73be992d4e134b | [] | no_license | IGME-RIT/physics-AABB2D-VisualStudio | a523620fe99178baa238c7290a54ff4057097c5e | af2d5f4b1b6f439b6667a9513bd372ba32ab94b6 | refs/heads/master | 2020-06-07T07:56:36.676317 | 2019-06-30T15:03:41 | 2019-06-30T15:03:41 | 192,967,046 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 6,220 | h | /*
Title: AABB-2D
File Name: Model.h
Copyright © 2015
Original authors: Brockton Roth
Written under the supervision of David I. Schwartz, Ph.D., and
supported by a professional development seed grant from the B. Thomas
Golisano College of Computing & Information Sciences
(https://www.rit.edu/gccis) at the Rochester Institute of Technology.
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/>.
Description:
This is an Axis-Aligned Bounding Box collision test. This is in 2D.
Contains two squares, one that is stationary and one that is moving. They are bounded by
AABBs (Axis-Aligned Bounding Boxes) and when these AABBs collide, the moving object
"bounces" on the X-axis (because that is the only direction the object is moving). The
algorithm will detect collision along any axis, but will not be able to output the axis
of collision because it doesn't know. Thus, we assume X and hardcode in the X-axis bounce.
If you would like to know the axis of collision, try out the Swept AABB collision.
There is a physics timestep such that every update runs at the same delta time, regardless
of how fast or slow the computer is running. The squares should be the exact same as their
AABBs, since they are aligned on the X-Y axes but should you wish to see how the AABB
recalculates when the object's orientation changes, simply uncomment the rotate lines
(obj1->Rotate, obj2->Rotate).
*/
#ifndef _MODEL_H
#define _MODEL_H
#include "GLIncludes.h"
class Model
{
private:
int numVertices;
VertexFormat* vertices;
int numIndices;
GLuint* indices;
GLuint vbo;
GLuint ebo;
//GLuint shaderProgram;
//GLuint m_Buffer;
public:
Model(int numVerts = 0, VertexFormat* verts = nullptr, int numInds = 0, GLuint* inds = nullptr);
~Model();
GLuint AddVertex(VertexFormat*);
void AddIndex(GLuint);
void InitBuffer();
void UpdateBuffer();
void Draw();
// Our get variables.
int NumVertices()
{
return numVertices;
}
int NumIndices()
{
return numIndices;
}
VertexFormat* Vertices()
{
return vertices;
}
GLuint* Indices()
{
return indices;
}
/*Model(int p_nVertices = 3, float _size = 1.0f, float _originX = 0.0f, float _originY = 0.0f, float _originZ = 0.0f)
{
if (p_nVertices < 3)
p_nVertices = 3;
m_ShaderProgram = 0;
m_Buffer = 0;
m_nVertices = p_nVertices;
m_pPoint = new Point3D[p_nVertices];
SetOrigin(_originX, _originY, _originZ);
GeneratePoints(_size);
}*/
// ~Figure(void)
// {
// Release();
// }
//
// void Release(void)
// {
// m_nVertices = 0;
// if (m_pPoint != nullptr)
// {
// delete[] m_pPoint;
// m_pPoint = nullptr;
// }
// }
//
// void SetPoint(int nIndex, float x, float y, float z = 0.0f)
// {
// if (nIndex < 0 || nIndex >= m_nVertices || m_pPoint == nullptr)
// return;
//
// m_pPoint[nIndex].x = x;
// m_pPoint[nIndex].y = y;
// m_pPoint[nIndex].z = z;
// }
//
// void SetPoint(int nIndex, Point3D p_Point)
// {
// if (nIndex < 0 || nIndex >= m_nVertices || m_pPoint == nullptr)
// return;
//
// m_pPoint[nIndex] = p_Point;
// }
//
// void operator()(int nIndex, float x, float y, float z = 0.0f)
// {
// if (nIndex < 0 || nIndex >= m_nVertices || m_pPoint == nullptr)
// return;
//
// m_pPoint[nIndex].x = x;
// m_pPoint[nIndex].y = y;
// m_pPoint[nIndex].z = z;
// }
//
// void operator()(int nIndex, Point3D p_Point)
// {
// if (nIndex < 0 || nIndex >= m_nVertices || m_pPoint == nullptr)
// return;
//
// m_pPoint[nIndex] = p_Point;
// }
//
// Point3D& operator[](int nIndex)
// {
// if (nIndex < 0 || nIndex >= m_nVertices || m_pPoint == nullptr)
// assert(false);
//
// return m_pPoint[nIndex];
// }
//
// void SetOrigin(float x, float y, float z)
// {
// m_Origin.x = x;
// m_Origin.y = y;
// m_Origin.z = z;
// }
//
// void CompileFigure(void)
// {
// for (int i = 0; i < m_nVertices; i++)
// {
// m_pPoint[i].x += m_Origin.x;
// m_pPoint[i].y += m_Origin.y;
// m_pPoint[i].z += m_Origin.z;
// }
// InitBuffer();
// }
//
// friend std::ostream& operator<<(std::ostream os, Figure& other)
// {
// other.PrintContent();
// return os;
// }
//
// void Render(void)
// {
// // Use the buffer and shader for each circle.
// glUseProgram(m_ShaderProgram);
// glBindBuffer(GL_ARRAY_BUFFER, m_Buffer);
//
// // Initialize the vertex position attribute from the vertex shader.
// GLuint loc = glGetAttribLocation(m_ShaderProgram, "vPosition");
// glEnableVertexAttribArray(loc);
// glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
//
// // Draw the array of this figure
// glDrawArrays(GL_TRIANGLE_FAN, 0, m_nVertices);
// }
//
//private:
// void InitBuffer(void)
// {
// // Create a vertex array object
// GLuint vao;
// glGenVertexArrays(1, &vao);
// glBindVertexArray(vao);
//
// // Create and initialize a buffer object for each circle.
// glGenBuffers(1, &m_Buffer);
// glBindBuffer(GL_ARRAY_BUFFER, m_Buffer);
// glBufferData(GL_ARRAY_BUFFER, m_nVertices * sizeof(Point3D), m_pPoint, GL_STATIC_DRAW);
//
// // Load shaders and use the resulting shader program
// m_ShaderProgram = InitShader("Shaders\\vshader.glsl", "Shaders\\fshader.glsl");
// }
//
// void GeneratePoints(float fSize = 1.0f)
// {
// GLfloat theta = 0;
// for (int i = 0; i < m_nVertices; i++)
// {
// theta += static_cast<GLfloat>(2 * M_PI / m_nVertices);
// m_pPoint[i].x = static_cast<GLfloat>(cos(theta)) * fSize;
// m_pPoint[i].y = static_cast<GLfloat>(sin(theta)) * fSize;
// }
// CompileFigure();
// }
//
// void PrintContent(void)
// {
// std::cout << "Content:" << std::endl;
// for (int i = 0; i < m_nVertices; i++)
// {
// std::cout << m_pPoint[i] << std::endl;
// }
// }
};
#endif //_MODEL_H
| [
"[email protected]"
] | |
6520bfb8672411cc2d7efedaecedf793b34078c6 | ae9ffe2cf2ed611de03a54df50efbb66efa0f3c5 | /cocos/2d/CCComponent.cpp | 4e0a228ae2e9d20d044fd0d0bb021d0c82b2b183 | [
"MIT"
] | permissive | jinsuoliu/cocos2d-bgfx | 3d02cdf31493ee6c43ab5f0e1ccf16303138b816 | 8d4a5cfd525e94b941f333170f747222745713b9 | refs/heads/master | 2020-06-26T20:03:34.338951 | 2019-05-16T08:28:03 | 2019-05-16T08:28:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,658 | cpp | /****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "ccHeader.h"
#include "2d/CCComponent.h"
#include "base/CCScriptSupport.h"
NS_CC_BEGIN
Component::Component()
: _owner(nullptr)
, _enabled(true)
{
#if CC_ENABLE_SCRIPT_BINDING
ScriptEngineProtocol* engine = ScriptEngineManager::getInstance()->getScriptEngine();
_scriptType = engine != nullptr ? engine->getScriptType() : ccScriptType::kScriptTypeNone;
#endif
}
Component::~Component()
{
}
bool Component::init()
{
return true;
}
#if CC_ENABLE_SCRIPT_BINDING
static bool sendComponentEventToJS(Component* node, int action)
{
auto scriptEngine = ScriptEngineManager::getInstance()->getScriptEngine();
if (scriptEngine->isCalledFromScript())
{
scriptEngine->setCalledFromScript(false);
}
else
{
BasicScriptData data(node,(void*)&action);
ScriptEvent scriptEvent(kComponentEvent,(void*)&data);
if (scriptEngine->sendEvent(&scriptEvent))
return true;
}
return false;
}
#endif
void Component::onEnter()
{
#if CC_ENABLE_SCRIPT_BINDING
if (_scriptType == ccScriptType::kScriptTypeJavascript)
{
sendComponentEventToJS(this, kComponentOnEnter);
}
#endif
}
void Component::onExit()
{
#if CC_ENABLE_SCRIPT_BINDING
if (_scriptType == ccScriptType::kScriptTypeJavascript)
{
sendComponentEventToJS(this, kComponentOnExit);
}
#endif
}
void Component::onAdd()
{
#if CC_ENABLE_SCRIPT_BINDING
if (_scriptType == ccScriptType::kScriptTypeJavascript)
{
sendComponentEventToJS(this, kComponentOnAdd);
}
#endif
}
void Component::onRemove()
{
#if CC_ENABLE_SCRIPT_BINDING
if (_scriptType == ccScriptType::kScriptTypeJavascript)
{
sendComponentEventToJS(this, kComponentOnRemove);
}
#endif
}
void Component::update(float delta)
{
#if CC_ENABLE_SCRIPT_BINDING
if (_scriptType == ccScriptType::kScriptTypeJavascript)
{
sendComponentEventToJS(this, kComponentOnUpdate);
}
#endif
}
bool Component::serialize(void *ar)
{
return true;
}
Component* Component::create()
{
Component * ret = new (std::nothrow) Component();
if (ret && ret->init())
{
ret->autorelease();
}
else
{
CC_SAFE_DELETE(ret);
}
return ret;
}
void Component::setOwner(Node *owner)
{
_owner = owner;
}
void Component::setEnabled(bool enabled)
{
_enabled = enabled;
}
NS_CC_END
| [
"[email protected]"
] | |
623e24cfe4024dfac339c7dc1efe69e731a50b47 | a3f8e3d964d09d1b6895f8dd9e27a160fd385ff8 | /Assignment_1/Assignment_5/FilterByName.cpp | 3f61b86ffd98149013b310f01dc326dea7018202 | [] | no_license | NaxxoBG/SAR_repo | ca08445d0919f4af5da366f5afd83754dfa69074 | 56c6f9606eed8bf47d7092b631ea4e49f0bc3782 | refs/heads/master | 2020-12-28T09:21:29.486105 | 2020-05-05T17:04:11 | 2020-05-05T17:04:11 | 238,264,581 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 468 | cpp | #include "FilterByName.h"
#include <algorithm>
FilterByName::FilterByName(std::unordered_set<std::string> &names)
{
this->names = names;
}
std::vector<Monkeyy> FilterByName::filter(std::vector<Monkeyy> ms)
{
std::vector<Monkeyy> filtered;
std::copy_if(ms.begin(), ms.end(), std::back_inserter(filtered), [this](Monkeyy &i) {return find(names.begin(), names.end(), i.getName()) != names.end(); });
return next != nullptr ? next->filter(filtered) : filtered;
}
| [
"[email protected]"
] | |
a1cf681c32d94c9669389d71da2f884262cba504 | 5bf031203768b81b48dd6550f5ded7f6a6e91cbf | /dbms/src/Formats/MySQLWireBlockOutputStream.cpp | 621a624fb0e8690939e5cc8170799646b079bfde | [
"Apache-2.0"
] | permissive | MyXOF/ClickHouse | e687e45eacb4891a4253f3d43e2dcdf2ce4a2675 | b8faf69b3f894254d77741fb8e04e391bd1fab41 | refs/heads/master | 2020-06-19T01:05:13.526951 | 2019-07-28T09:45:25 | 2019-07-28T09:45:25 | 196,508,548 | 0 | 0 | null | 2019-07-12T04:27:17 | 2019-07-12T04:27:16 | null | UTF-8 | C++ | false | false | 2,880 | cpp | #include "MySQLWireBlockOutputStream.h"
#include <Core/MySQLProtocol.h>
#include <Interpreters/ProcessList.h>
#include <iomanip>
#include <sstream>
namespace DB
{
using namespace MySQLProtocol;
MySQLWireBlockOutputStream::MySQLWireBlockOutputStream(WriteBuffer & buf, const Block & header, Context & context)
: header(header)
, context(context)
, packet_sender(std::make_shared<PacketSender>(buf, context.mysql.sequence_id))
{
packet_sender->max_packet_size = context.mysql.max_packet_size;
}
void MySQLWireBlockOutputStream::writePrefix()
{
if (header.columns() == 0)
return;
packet_sender->sendPacket(LengthEncodedNumber(header.columns()));
for (const ColumnWithTypeAndName & column : header.getColumnsWithTypeAndName())
{
ColumnDefinition column_definition(column.name, CharacterSet::binary, 0, ColumnType::MYSQL_TYPE_STRING, 0, 0);
packet_sender->sendPacket(column_definition);
}
if (!(context.mysql.client_capabilities & Capability::CLIENT_DEPRECATE_EOF))
{
packet_sender->sendPacket(EOF_Packet(0, 0));
}
}
void MySQLWireBlockOutputStream::write(const Block & block)
{
size_t rows = block.rows();
for (size_t i = 0; i < rows; i++)
{
ResultsetRow row_packet;
for (const ColumnWithTypeAndName & column : block)
{
WriteBufferFromOwnString ostr;
column.type->serializeAsText(*column.column.get(), i, ostr, format_settings);
row_packet.appendColumn(std::move(ostr.str()));
}
packet_sender->sendPacket(row_packet);
}
}
void MySQLWireBlockOutputStream::writeSuffix()
{
QueryStatus * process_list_elem = context.getProcessListElement();
CurrentThread::finalizePerformanceCounters();
QueryStatusInfo info = process_list_elem->getInfo();
size_t affected_rows = info.written_rows;
std::stringstream human_readable_info;
human_readable_info << std::fixed << std::setprecision(3)
<< "Read " << info.read_rows << " rows, " << formatReadableSizeWithBinarySuffix(info.read_bytes) << " in " << info.elapsed_seconds << " sec., "
<< static_cast<size_t>(info.read_rows / info.elapsed_seconds) << " rows/sec., "
<< formatReadableSizeWithBinarySuffix(info.read_bytes / info.elapsed_seconds) << "/sec.";
if (header.columns() == 0)
packet_sender->sendPacket(OK_Packet(0x0, context.mysql.client_capabilities, affected_rows, 0, 0, "", human_readable_info.str()), true);
else
if (context.mysql.client_capabilities & CLIENT_DEPRECATE_EOF)
packet_sender->sendPacket(OK_Packet(0xfe, context.mysql.client_capabilities, affected_rows, 0, 0, "", human_readable_info.str()), true);
else
packet_sender->sendPacket(EOF_Packet(0, 0), true);
}
void MySQLWireBlockOutputStream::flush()
{
packet_sender->out->next();
}
}
| [
"[email protected]"
] | |
86d2249f40b08c1fce1b7af7e9c4c704075c11f3 | 0a99e7c3abed0f4bc5f0e5abf7b6fede80622a5b | /SFML_Template/SFML_Template/SFML_Template/src/Barriers.cpp | 1735697a9ba220d6f81e0c65473f79a404ea458e | [] | no_license | mrjai24/Code-Samples--C-- | 2ac4faa62663f011a16554dfd0cfd03fc2b2f34c | 0dbfc8990c5e54870a20fe3d05548301fc824fda | refs/heads/main | 2023-01-23T21:35:35.011998 | 2020-11-27T21:36:05 | 2020-11-27T21:36:05 | 316,598,448 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,061 | cpp | //Adding in additional libraries.
#include "../include/Barriers.h"
//Defining a variable for the scale of the barriers.
float fScale = 0.75f;
//Private functions.
void Barriers::initTextures()
{
//Initialising all the barrier textures.
//Full barriers.
this->textures["BarrierFull"] = new Texture();
this->textures["BarrierFull"]->loadFromFile("Textures/Barrier.png");
//Partial barriers.
this->textures["BarrierPhase1"] = new Texture();
this->textures["BarrierPhase1"]->loadFromFile("Textures/Barrier_Destroyed_Phase_1.png");
//Almost destroyed barriers.
this->textures["BarrierPhase2"] = new Texture();
this->textures["BarrierPhase2"]->loadFromFile("Textures/Barrier_Destroyed_Phase_2.png");
}
void Barriers::initVariables()
{
//Initialises all the variables.
iNoOfHitsMax = 9;
iNoOfHitsBarrier1 = iNoOfHitsMax;
iNoOfHitsBarrier2 = iNoOfHitsMax;
iNoOfHitsBarrier3 = iNoOfHitsMax;
iNoOfHitsBarrier4 = iNoOfHitsMax;
}
void Barriers::initBarriers()
{
//Sets up the barriers with textures, scale and their positions.
//Barrier 1 set up.
this->barrier1.setTexture(*textures["BarrierFull"]);
this->barrier1.setScale(fScale, fScale);
this->barrier1.setPosition(50.f, 750.f);
//Barrier 2 set up.
this->barrier2.setTexture(*textures["BarrierFull"]);
this->barrier2.setScale(fScale, fScale);
this->barrier2.setPosition(310.f, 750.f);
//Barrier 3 set up.
this->barrier3.setTexture(*textures["BarrierFull"]);
this->barrier3.setScale(fScale, fScale);
this->barrier3.setPosition(570.f, 750.f);
//Barrier 4 set up.
this->barrier4.setTexture(*textures["BarrierFull"]);
this->barrier4.setScale(fScale, fScale);
this->barrier4.setPosition(830.f, 750.f);
}
//Constructor.
Barriers::Barriers()
{
//Calls the void functions to set up the barriers.
this->initTextures();
this->initVariables();
this->initBarriers();
}
//Accessors.
const FloatRect Barriers::getBounds(int iBarrierNo) const
{
//Gets the bounds of each barrier using a switch.
switch (iBarrierNo)
{
//Barrier 1.
case 1:
return this->barrier1.getGlobalBounds();
break;
//Barrier 2.
case 2:
return this->barrier2.getGlobalBounds();
break;
//Barrier 3.
case 3:
return this->barrier3.getGlobalBounds();
break;
//Barrier 4.
case 4:
return this->barrier4.getGlobalBounds();
break;
}
}
//Functions.
void Barriers::barrierHit(int iBarrierNo)
{
//Decreases the value of the hit variable for each barrier using a switch.
switch (iBarrierNo)
{
//Barrier 1.
case 1:
this->iNoOfHitsBarrier1--;
//TEST cout << iNoOfHitsBarrier1 << endl;
break;
//Barrier 2.
case 2:
this->iNoOfHitsBarrier2--;
//TEST cout << iNoOfHitsBarrier2 << endl;
break;
//Barrier 3.
case 3:
this->iNoOfHitsBarrier3--;
//TEST cout << iNoOfHitsBarrier3 << endl;
break;
//Barrier 4.
case 4:
this->iNoOfHitsBarrier4--;
//TEST cout << iNoOfHitsBarrier4 << endl;
break;
}
}
void Barriers::update(RenderTarget* target)
{
//Updates each barrier giving them a different sprites depended of their hit variable.
//Barrier 1 update.
//Phase 1.
if (iNoOfHitsBarrier1 == 6)
{
this->barrier1.setTexture(*textures["BarrierPhase1"]);
this->barrier1.setScale(fScale, fScale);
}
//Phase 2.
else if (iNoOfHitsBarrier1 == 3)
{
this->barrier1.setTexture(*textures["BarrierPhase2"]);
this->barrier1.setScale(fScale, fScale);
}
//Disappear.
else if (iNoOfHitsBarrier1 == 0)
{
//Moves the barrier off screen.
this->barrier1.setPosition(1100.f, 1100.f);
}
//Barrier 2 update.
//Phase 1.
if (iNoOfHitsBarrier2 == 6)
{
this->barrier2.setTexture(*textures["BarrierPhase1"]);
this->barrier2.setScale(fScale, fScale);
}
//Phase 2.
else if (iNoOfHitsBarrier2 == 3)
{
this->barrier2.setTexture(*textures["BarrierPhase2"]);
this->barrier2.setScale(fScale, fScale);
}
//Disappear.
else if (iNoOfHitsBarrier2 == 0)
{
//Moves the barrier off screen.
this->barrier2.setPosition(1100.f, 1100.f);
}
//Barrier 3 update.
//Phase 1.
if (iNoOfHitsBarrier3 == 6)
{
this->barrier3.setTexture(*textures["BarrierPhase1"]);
this->barrier3.setScale(fScale, fScale);
}
//Phase 2.
else if (iNoOfHitsBarrier3 == 3)
{
this->barrier3.setTexture(*textures["BarrierPhase2"]);
this->barrier3.setScale(fScale, fScale);
}
//Disappear.
else if (iNoOfHitsBarrier3 == 0)
{
//Moves the barrier off screen.
this->barrier3.setPosition(1100.f, 1100.f);
}
//Barrier 4 update.
//Phase 1.
if (iNoOfHitsBarrier4 == 6)
{
this->barrier4.setTexture(*textures["BarrierPhase1"]);
this->barrier4.setScale(fScale, fScale);
}
//Phase 2.
else if (iNoOfHitsBarrier4 == 3)
{
this->barrier4.setTexture(*textures["BarrierPhase2"]);
this->barrier4.setScale(fScale, fScale);
}
//Disappear.
else if (iNoOfHitsBarrier4 == 0)
{
//Moves the barrier off screen.
this->barrier4.setPosition(1100.f, 1100.f);
}
}
void Barriers::render(RenderTarget& target)
{
//Draws all the barriers to the screen.
target.draw(this->barrier1);
target.draw(this->barrier2);
target.draw(this->barrier3);
target.draw(this->barrier4);
} | [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.