text
stringlengths 8
6.88M
|
|---|
#include "Clyde.h"
Clyde::Clyde()
{
points = 10;
dead = false;
lastAnimationPowerUP = POWER_UP_INFO::X_GREY_2_SPRITE;
direction = CLYDE_INITIAL_INFO::DIRECTION;
lastTime = clock();
timeDown = 0.15f;
}
void Clyde::Update(bool* _keys)
{
if (!dead)
{
//input control
if (_keys[(int)InputKey::K_LEFT])
{
direction = 1;
}
else if (_keys[(int)InputKey::K_RIGHT])
{
direction = 0;
}
else if (_keys[(int)InputKey::K_UP])
{
direction = 3;
}
else if (_keys[(int)InputKey::K_DOWN])
{
direction = 2;
}
//update
deltaTime = (clock() - lastTime);
lastTime = clock();
deltaTime /= CLOCKS_PER_SEC;
timeDown -= deltaTime;
}
else
{
deltaTimeRespawn = (clock() - lastTimeRespawn);
lastTimeRespawn = clock();
deltaTimeRespawn /= CLOCKS_PER_SEC;
timeDownRespawn -= deltaTimeRespawn;
if (timeDownRespawn <= 0)
{
direction = CLYDE_INITIAL_INFO::DIRECTION;
dead = false;
}
}
}
void Clyde::Move(int _velocity)
{
switch (direction)
{
case 0:
objectRect.x -= _velocity;
if (objectRect.x <= 0) objectRect.x = SIZE * 19;
break;
case 1:
objectRect.x += _velocity;
if (objectRect.x >= SIZE * 19) objectRect.x = 0;
break;
case 2:
objectRect.y -= _velocity;
if (objectRect.y <= 0) objectRect.y = SIZE * 19;
break;
case 3:
objectRect.y += _velocity;
if (objectRect.y >= SIZE * 19) objectRect.y = 0;
break;
default:
break;
}
}
void Clyde::Animate()
{
switch (direction)
{
case 0:
if (lastAnimation == CLYDE::X_LEFT_CLOSE_SPRITE && timeDown <= 0)
{
SetNewAnimation(CLYDE::X_LEFT_OPEN_SPRITE);
}
else if (lastAnimation == CLYDE::X_LEFT_OPEN_SPRITE && timeDown <= 0)
{
SetNewAnimation(CLYDE::X_LEFT_CLOSE_SPRITE);
}
else if (lastAnimation != CLYDE::X_LEFT_CLOSE_SPRITE && lastAnimation != CLYDE::X_LEFT_OPEN_SPRITE)
{
SetNewAnimation(CLYDE::X_LEFT_CLOSE_SPRITE);
}
break;
case 1:
if (lastAnimation == CLYDE::X_RIGHT_CLOSE_SPRITE && timeDown <= 0)
{
SetNewAnimation(CLYDE::X_RIGHT_OPEN_SPRITE);
}
else if (lastAnimation == CLYDE::X_RIGHT_OPEN_SPRITE && timeDown <= 0)
{
SetNewAnimation(CLYDE::X_RIGHT_CLOSE_SPRITE);
}
else if (lastAnimation != CLYDE::X_RIGHT_CLOSE_SPRITE && lastAnimation != CLYDE::X_RIGHT_OPEN_SPRITE)
{
SetNewAnimation(CLYDE::X_RIGHT_CLOSE_SPRITE);
}
break;
case 2:
if (lastAnimation == CLYDE::X_UP_CLOSE_SPRITE && timeDown <= 0)
{
SetNewAnimation(CLYDE::X_UP_OPEN_SPRITE);
}
else if (lastAnimation == CLYDE::X_UP_OPEN_SPRITE && timeDown <= 0)
{
SetNewAnimation(CLYDE::X_UP_CLOSE_SPRITE);
}
else if (lastAnimation != CLYDE::X_UP_CLOSE_SPRITE && lastAnimation != CLYDE::X_UP_OPEN_SPRITE)
{
SetNewAnimation(CLYDE::X_UP_CLOSE_SPRITE);
}
break;
case 3:
if (lastAnimation == CLYDE::X_DOWN_CLOSE_SPRITE && timeDown <= 0)
{
SetNewAnimation(CLYDE::X_DOWN_OPEN_SPRITE);
}
else if (lastAnimation == CLYDE::X_DOWN_OPEN_SPRITE && timeDown <= 0)
{
SetNewAnimation(CLYDE::X_DOWN_CLOSE_SPRITE);
}
else if (lastAnimation != CLYDE::X_DOWN_CLOSE_SPRITE && lastAnimation != CLYDE::X_DOWN_OPEN_SPRITE)
{
SetNewAnimation(CLYDE::X_DOWN_CLOSE_SPRITE);
}
break;
default:
break;
}
}
void Clyde::AnimatePowerUp()
{
if (lastAnimationPowerUP == POWER_UP_INFO::X_GREY_2_SPRITE && timeDown <= 0)
{
SetNewAnimationPowerUp(POWER_UP_INFO::X_BLUE_1_SPRITE);
}
else if (lastAnimationPowerUP == POWER_UP_INFO::X_BLUE_1_SPRITE && timeDown <= 0)
{
SetNewAnimationPowerUp(POWER_UP_INFO::X_BLUE_2_SPRITE);
}
else if (lastAnimationPowerUP == POWER_UP_INFO::X_BLUE_2_SPRITE && timeDown <= 0)
{
SetNewAnimationPowerUp(POWER_UP_INFO::X_GREY_1_SPRITE);
}
else if (lastAnimationPowerUP == POWER_UP_INFO::X_GREY_1_SPRITE && timeDown <= 0)
{
SetNewAnimationPowerUp(POWER_UP_INFO::X_GREY_2_SPRITE);
}
}
void Clyde::SetInitialPosition(int _x, int _y)
{
initialPosition.x = _x;
initialPosition.y = _y;
}
void Clyde::SetNewAnimation(int _animation)
{
objectSpriteRect.x = (Renderer::Instance()->GetTextureSize(PACMAN_SPRITESHEET::ID).x / 8) * _animation;
objectSpriteRect.y = (Renderer::Instance()->GetTextureSize(PACMAN_SPRITESHEET::ID).x / 8) * CLYDE::Y_SPRITE_POSITION;
lastAnimation = _animation;
timeDown = 0.15f;
}
void Clyde::SetNewAnimationPowerUp(int _animation)
{
objectSpriteRect.x = (Renderer::Instance()->GetTextureSize(PACMAN_SPRITESHEET::ID).x / 8) * _animation;
objectSpriteRect.y = (Renderer::Instance()->GetTextureSize(PACMAN_SPRITESHEET::ID).x / 8) * POWER_UP_INFO::Y_SPRITE_POSITION;
lastAnimationPowerUP = _animation;
timeDown = 0.15f;
}
void Clyde::Respawn()
{
objectRect.x = initialPosition.x * SIZE;
objectRect.y = initialPosition.y * SIZE;
actualPosition.x = initialPosition.x;
actualPosition.y = initialPosition.y;
direction = -1;
dead = true;
timeDownRespawn = 2.0f;
lastTimeRespawn = clock();
SetNewAnimation(CLYDE::X_LEFT_OPEN_SPRITE);
}
void Clyde::Draw()
{
Renderer::Instance()->PushSprite(objectId, objectSpriteRect, objectRect);
}
Clyde::~Clyde()
{
}
|
#pragma once
#include "utils/ptts.hpp"
#include "proto/config_child.pb.h"
using namespace std;
namespace pc = proto::config;
namespace nora {
namespace config {
using child_phase_ptts = ptts<pc::child_phase>;
child_phase_ptts& child_phase_ptts_instance();
void child_phase_ptts_set_funcs();
using child_logic_ptts = ptts<pc::child_logic>;
child_logic_ptts& child_logic_ptts_instance();
void child_logic_ptts_set_funcs();
using child_value_ptts = ptts<pc::child_value>;
child_value_ptts& child_value_ptts_instance();
void child_value_ptts_set_funcs();
using child_raise_ptts = ptts<pc::child_raise>;
child_raise_ptts& child_raise_ptts_instance();
void child_raise_ptts_set_funcs();
using child_study_ptts = ptts<pc::child_study>;
child_study_ptts& child_study_ptts_instance();
void child_study_ptts_set_funcs();
using child_study_item_ptts = ptts<pc::child_study_item>;
child_study_item_ptts& child_study_item_ptts_instance();
void child_study_item_ptts_set_funcs();
using child_skill_ptts = ptts<pc::child_skill>;
child_skill_ptts& child_skill_ptts_instance();
void child_skill_ptts_set_funcs();
using child_learn_skill_actor_ptts = ptts<pc::child_learn_skill_actor>;
child_learn_skill_actor_ptts& child_learn_skill_actor_ptts_instance();
void child_learn_skill_actor_ptts_set_funcs();
using child_add_skill_exp_item_ptts = ptts<pc::child_add_skill_exp_item>;
child_add_skill_exp_item_ptts& child_add_skill_exp_item_ptts_instance();
void child_add_skill_exp_item_ptts_set_funcs();
using child_drop_ptts = ptts<pc::child_drop>;
child_drop_ptts& child_drop_ptts_instance();
void child_drop_ptts_set_funcs();
using child_buff_ptts = ptts<pc::child_buff>;
child_buff_ptts& child_buff_ptts_instance();
void child_buff_ptts_set_funcs();
}
}
|
#ifndef MUD_H
#define MUD_H
#include <QByteArray>
class MUD
{
public:
MUD();
~MUD();
virtual bool onClientInput(QByteArray aInput) = 0;
virtual bool onLineReceived(QByteArray aLine) = 0;
virtual bool onColorFragment(QByteArray aColor, QByteArray aText) = 0;
};
#endif // MUD_H
|
#include "stdafx.h"
#include "Tree.h"
size_t GetHeight(Node *node)
{
size_t size = 0;
if (node != nullptr)
{
size = node->m_height;
}
return size;
}
size_t CheckBalanceFactor(Node *node)
{
size_t leftValue = ((node->m_leftLink != nullptr) ? GetHeight(node->m_leftLink) : 0);
size_t rightValue = ((node->m_rightLink != nullptr) ? GetHeight(node->m_rightLink) : 0);
return rightValue - leftValue;
}
void ResetHeight(Node *node)
{
if (node->m_leftLink != nullptr)
{
ResetHeight(node->m_leftLink);
}
if (node->m_rightLink != nullptr)
{
ResetHeight(node->m_rightLink);
}
size_t leftBalanceFactor = ((node->m_leftLink != nullptr) ? GetHeight(node->m_leftLink) : 0);
size_t rightBalanceFactor = ((node->m_rightLink != nullptr) ? GetHeight(node->m_rightLink) : 0);
node->m_height = ((leftBalanceFactor > rightBalanceFactor) ? leftBalanceFactor : rightBalanceFactor) + 1;
}
Node* BalanceTree(Node *node)
{
ResetHeight(node);
if (CheckBalanceFactor(node) == 2)
{
if (CheckBalanceFactor(node->m_rightLink) < 0)
{
node->m_rightLink = RightRotation(node->m_rightLink);
}
return LeftRotation(node);
}
if (CheckBalanceFactor(node) == -2)
{
if (CheckBalanceFactor(node->m_leftLink) > 0)
{
node->m_leftLink = LeftRotation(node->m_leftLink);
}
return RightRotation(node);
}
return node;
}
Node* LeftRotation(Node *node)
{
Node *tmp = node->m_rightLink;
node->m_rightLink = tmp->m_leftLink;
tmp->m_leftLink = node;
ResetHeight(node);
ResetHeight(tmp);
return BalanceTree(tmp);
}
Node* RightRotation(Node *node)
{
Node *tmp = node->m_leftLink;
node->m_leftLink = tmp->m_rightLink;
tmp->m_rightLink = node;
ResetHeight(node);
ResetHeight(tmp);
return BalanceTree(tmp);
}
Node* Insert(Node *node, int key)
{
if (node == nullptr)
{
Node *tmp = new Node;
tmp->m_key = key;
return tmp;
}
else if (key < node->m_key)
{
node->m_leftLink = Insert(node->m_leftLink, key);
}
else
{
node->m_rightLink = Insert(node->m_rightLink, key);
}
return BalanceTree(node);
}
Node* MinElement(Node *node)
{
Node *tmp = node;
if (node->m_leftLink != nullptr)
{
tmp = MinElement(node->m_leftLink);
}
return tmp;
}
Node* RemoveMin(Node *node)
{
if (node->m_leftLink == nullptr)
{
return node->m_rightLink;
}
node->m_leftLink = RemoveMin(node->m_leftLink);
return BalanceTree(node);
}
Node* RemoveByKey(Node *node, int key)
{
if (node == nullptr)
{
return nullptr;
}
if (key < node->m_key)
{
node->m_leftLink = RemoveByKey(node->m_leftLink, key);
}
else if (key > node->m_key)
{
node->m_rightLink = RemoveByKey(node->m_rightLink, key);
}
else
{
Node *left = node->m_leftLink;
Node *right = node->m_rightLink;
delete node;
if (right == nullptr)
{
return left;
}
Node *min = MinElement(right);
min->m_rightLink = RemoveMin(right);
min->m_leftLink = left;
return BalanceTree(min);
}
return BalanceTree(node);
}
|
int outpin = 8;
float kiloh;
long period;
bool ones = false;
long lastTime = 0;
long now;
// Timer output
const byte CLOCKOUT = 9; // Only for Arduino Uno
#define NOP __asm__ __volatile__ ("nop\n\t")
// Output strings
//String bitstring = "0110100001100101011011000110110001101111"; // Hello
//String bitstring = "01001000";// 0110100100100001"; // Hi!
String bitstring = "11010011";// 0110100100100001"; // I dunno
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(outpin,OUTPUT);
lastTime = micros();
period = 20000; // 20ms
// Timer setup
// set up 8 MHz timer on CLOCKOUT (OC1A)
// pinMode (CLOCKOUT, OUTPUT);
// // set up Timer 1
// TCCR1A = bit (COM1A0); // toggle OC1A on Compare Match
// TCCR1B = bit (WGM12) | bit (CS10); // CTC, no prescaling
// OCR1A = 7; // output every cycle
}
void loop() {
Serial.println();
lastTime = millis();
// Starting header of 1010
for (int i = 0; i < 2; i++) {
sendBit((1+i) % 2);
}
// Other bits
for (int i = 0; i < bitstring.length(); i++) {
if (bitstring[i] == '1'){
sendBit(true);
// PORTB = B00000001;
// delayMicroseconds(period);
// Serial.print("1 ");
} else {
sendBit(false);
// PORTB = B00000000;
// delayMicroseconds(period);
// Serial.print("0 ");
}
// Serial.println(millis()-lastTime);
}
PORTB = B00000000;
delay(1000);
}
void sendBit(bool singleBit){
long startTime = micros();
if (singleBit){
while (micros() - startTime < period){
PORTB = B00000001;
NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP;
PORTB = B00000000;
NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP;
PORTB = B00000001;
NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP;
PORTB = B00000000;
NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP;
// PORTB = B00000001;
// NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP;
// PORTB = B00000000;
// NOP;NOP;NOP;NOP;NOP;NOP;NOP;NOP;
}
} else {
while (micros() - startTime < period){
PORTB = B00000000;
}
}
}
|
#include <iostream>
using namespace std;
using ll = long long;
int main() {
ll N, M;
cin >> N >> M;
ll mi = max(0LL, N - M * 2);
ll ma = N;
while (true) {
ll c = N - ma;
if (M <= c * (c - 1) / 2) break;
--ma;
}
cout << mi << " " << ma << endl;
return 0;
}
|
#include "hydroponics/hydroponicsai.hpp"
#include "hydroponics/hydroponics_table.hpp"
#include "hydroponics/hydroponicsjobs.hpp"
#include "components/room.hpp"
#include "job/jobprovider.hpp"
#include "utilities/assert_cast.hpp"
using namespace ai;
using namespace ecs;
namespace hydroponics {
AI::timer_t HydroponicsAI::start(AI*) {
return 1000;
}
void HydroponicsAI::update_tables(Room* r) {
// Copy the furniture pointers into a vector
std::vector<Furniture*> base_tables = r->find_furniture(hydroponics_table_properties);
auto& tables = assert_cast<HydroponicsTable>(base_tables);
// Update the table state listing
std::sort(tables.begin(), tables.end());
std::swap(tables, m_tables);
}
AI::timer_t HydroponicsAI::update(AI* ai) {
Ent* room = ai->parent;
auto jobprov = room->assert_get<job::JobProvider>();
Room* r = room->assert_get<Room>();
update_tables(r);
if (m_tables.size() == 0) {
return 1000;
}
// Add the jobs and update the growth stages
for (auto table : m_tables) {
switch (table->stage) {
case HydroponicsTable::not_planted:
jobprov->to_provide_jobs.emplace_back(make_plant_job(table));
table->stage = HydroponicsTable::plant_requested;
break;
case HydroponicsTable::planted:
if (rand() % 5 == 0) {
table->stage = HydroponicsTable::stage1;
}
break;
case HydroponicsTable::stage1:
if (rand() % 5 == 0) {
table->stage = HydroponicsTable::stage2;
}
break;
case HydroponicsTable::stage2:
if (rand() % 5 == 0) {
table->stage = HydroponicsTable::stage3;
}
break;
case HydroponicsTable::stage3:
if (rand() % 5 == 0) {
jobprov->to_provide_jobs.emplace_back(make_harvest_job(table));
table->stage = HydroponicsTable::ready;
}
break;
default:
break;
}
}
return 1000;
}
std::string HydroponicsAI::desc = "Harvesting";
}
|
#include <bits/stdc++.h>
using namespace std;
const int inf=2012345678;
long long dist[10][10];
char b[2010101];
int main(){
scanf("%s",b);
int n=strlen(b);
for(int x=0;x<10;x++)for(int y=0;y<10;y++){
for(int i=0;i<10;i++)for(int j=0;j<10;j++)dist[i][j]=inf;
for(int i=0;i<10;i++)dist[i][(i+x)%10]=dist[i][(i+y)%10]=1;
for(int i=0;i<10;i++)for(int j=0;j<10;j++)for(int k=0;k<10;k++){
dist[j][k]=min(dist[j][k],dist[j][i]+dist[i][k]);
}
//for(int i=0;i<10;i++)for(int j=0;j<10;j++)printf("%d %d %d %d %d\n",x,y,i,j,dist[i][j]);
bool bad=false;
long long ans=0;
for(int i=0;i<n-1;i++){
int s=b[i]-'0',e=b[i+1]-'0';
if(dist[s][e]==inf){
bad=true;break;
}
ans+=dist[s][e]-1;
}
printf("%lld ",bad?-1LL:ans);
if(y==9)puts("");
}
}
|
#include <bits/stdc++.h>
using namespace std;
string ltrim(const string &);
string rtrim(const string &);
vector<string> split(const string &);
/*
* Complete the 'distanceTraversed' function below.
*
* The function is expected to return an INTEGER.
* The function accepts 2D_INTEGER_ARRAY lot as parameter.
*/
vector<pair<int, int>> dir={{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
int distanceTraversed(vector<vector<int>> lot) {
int row, col;
queue<pair<pair<int, int>, int>> q;
q.push({{0, 0}, 0});
row=lot.size();
col=lot[0].size();
int minDistance=-1;
while(!q.empty()) {
int x=q.front().first.first;
int y=q.front().first.second;
int dis=q.front().second;
q.pop();
if(lot[x][y]==9) {
minDistance=dis;
break;
}
lot[x][y]=-1;
for(auto itr=dir.begin(); itr!=dir.end(); itr++) {
int xCoordinate=x+itr->first;
int yCoordinate=y+itr->second;
if(xCoordinate<0 || xCoordinate>=row || yCoordinate<0 || yCoordinate>=col || lot[xCoordinate][yCoordinate]==0 || lot[xCoordinate][yCoordinate]==-1)
continue;
q.push({{xCoordinate, yCoordinate}, dis+1});
}
}
return minDistance;
}
int main()
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup" -*-
*
* Copyright (C) Opera Software ASA 1999-2004
*/
#include "core/pch.h"
#include "modules/ecmascript/carakan/src/es_pch.h"
#include "modules/ecmascript/carakan/src/builtins/es_regexp_builtins.h"
#include "modules/ecmascript/carakan/src/object/es_regexp_object.h"
#include "modules/ecmascript/carakan/src/object/es_global_object.h"
#include "modules/regexp/include/regexp_advanced_api.h"
static JString *
CreateEscapedSource(ES_Context *context, JString *source)
{
const uni_char *storage = Storage(context, source);
unsigned length = Length(source), additional = 0, index;
BOOL in_class = FALSE;
for (index = 0; index < length; ++index)
switch (storage[index])
{
case '[':
in_class = TRUE;
break;
case ']':
in_class = FALSE;
break;
case '\\':
++index;
break;
case '/':
if (!in_class)
++additional;
}
if (additional == 0)
return source;
else
{
JString *escaped = JString::Make(context, length + additional);
uni_char *ptr = Storage(context, escaped);
for (index = 0; index < length; ++index)
{
switch (storage[index])
{
case '[':
in_class = TRUE;
break;
case ']':
in_class = FALSE;
break;
case '\\':
*ptr++ = storage[index++];
*ptr++ = storage[index];
continue;
case '/':
if (!in_class)
*ptr++ = '\\';
}
*ptr++ = storage[index];
}
return escaped;
}
}
class ES_RegExpSuspension
: public RegExpSuspension,
public ES_StackGCRoot
{
public:
ES_RegExpSuspension(ES_Execution_Context *context)
: ES_StackGCRoot(context),
context(context),
memory(NULL)
{
}
~ES_RegExpSuspension();
virtual void Yield();
virtual void *AllocateL(unsigned nbytes);
virtual void GCTrace();
private:
ES_Execution_Context *context;
ES_Box *memory;
BOOL allocating;
};
ES_RegExpSuspension::~ES_RegExpSuspension()
{
ES_Box *box = memory;
while (box)
{
ES_Box *next = *reinterpret_cast<ES_Box **>(box->Unbox());
context->heap->Free(box);
box = next;
}
}
/* virtual */ void
ES_RegExpSuspension::Yield()
{
context->CheckOutOfTime();
}
/* virtual */ void *
ES_RegExpSuspension::AllocateL(unsigned nbytes)
{
ES_Box *box = ES_Box::Make(context, sizeof(void *) + nbytes);
*reinterpret_cast<ES_Box **>(box->Unbox()) = memory;
memory = box;
return box->Unbox() + sizeof(void *);
}
/* virtual */ void
ES_RegExpSuspension::GCTrace()
{
ES_Box *box = memory;
while (box)
{
GC_PUSH_BOXED(context->heap, box);
box = *reinterpret_cast<ES_Box **>(box->Unbox());
}
}
/* static */ BOOL
ES_RegExp_Object::ParseFlags(ES_Context *context, RegExpFlags &flags, unsigned &flagbits, JString *source)
{
flags.ignore_case = NO;
flags.multi_line = NO;
flags.ignore_whitespace = FALSE;
flags.searching = TRUE;
flagbits = 0;
if (source)
{
const uni_char *storage = Storage(context, source);
unsigned length = Length(source);
for (unsigned index = 0; index < length; ++index)
switch (storage[index])
{
case 'g': if (flagbits & REGEXP_FLAG_GLOBAL) goto return_false; else flagbits |= REGEXP_FLAG_GLOBAL; break;
case 'i': if (flagbits & REGEXP_FLAG_IGNORECASE) goto return_false; else { flagbits |= REGEXP_FLAG_IGNORECASE; flags.ignore_case = YES; } break;
case 'm': if (flagbits & REGEXP_FLAG_MULTILINE) goto return_false; else { flagbits |= REGEXP_FLAG_MULTILINE; flags.multi_line = YES; } break;
#ifdef ES_NON_STANDARD_REGEXP_FEATURES
case 'x': if (flagbits & REGEXP_FLAG_EXTENDED) goto return_false; else { flagbits |= REGEXP_FLAG_EXTENDED; flags.ignore_whitespace = TRUE; } break;
case 'y': if (flagbits & REGEXP_FLAG_NOSEARCH) goto return_false; else { flagbits |= REGEXP_FLAG_NOSEARCH; flags.searching = FALSE; } break;
#endif // ES_NON_STANDARD_REGEXP_FEATURES
default:
goto return_false;
}
}
return TRUE;
return_false:
if (ES_Execution_Context *exec_context = context->GetExecutionContext())
exec_context->ThrowSyntaxError("Invalid RegExp flags");
return FALSE;
}
/* static */ ES_RegExp_Object *
ES_RegExp_Object::Make(ES_Context *context, ES_Global_Object *global_object, JString *source, RegExpFlags &flags, unsigned flagbits, BOOL escape_source)
{
ES_SuspendedCreateRegExp suspended(Storage(context, source), Length(source), &flags);
suspended.Execute(context);
if (OpStatus::IsError(suspended.status))
if (OpStatus::IsMemoryError(suspended.status))
context->AbortOutOfMemory();
else
return NULL;
ES_RegExp_Information info;
info.regexp = suspended.regexp;
info.flags = flagbits;
ES_RegExp_Object *regexp;
// FIXME: OOM handling.
unsigned ncaptures = info.regexp->GetNumberOfCaptures();
unsigned extra = ncaptures * sizeof(RegExpMatch);
GC_ALLOCATE_WITH_EXTRA(context, regexp, extra, ES_RegExp_Object, (regexp, global_object->GetRegExpClass(), global_object, info));
info.regexp->DecRef();
ES_CollectorLock gclock(context);
regexp->SetProperties(context, escape_source ? CreateEscapedSource(context, source) : source);
return regexp;
}
/* static */ ES_RegExp_Object *
ES_RegExp_Object::Make(ES_Context *context, ES_Global_Object *global_object, const ES_RegExp_Information &info, JString *source)
{
ES_RegExp_Object *regexp;
unsigned ncaptures = info.regexp->GetNumberOfCaptures();
unsigned extra = ncaptures * sizeof(RegExpMatch);
GC_ALLOCATE_WITH_EXTRA(context, regexp, extra, ES_RegExp_Object, (regexp, global_object->GetRegExpClass(), global_object, info));
ES_CollectorLock gclock(context);
regexp->flags = info.flags;
regexp->SetProperties(context, source);
#ifdef ES_NATIVE_SUPPORT
/* Regular expression literals are JIT:ed immediately by the lexer, unless
they're not supported, or JIT was disabled when the script was compiled.
If the latter happens, and JIT is enabled, we can't dynamically JIT the
regexp, because we'd then use the wrong allocator for executable memory
and the cleanup would be wrong. */
if (!regexp->native_matcher)
regexp->calls = UINT_MAX;
#endif // ES_NATIVE_SUPPORT
return regexp;
}
/* static */ ES_RegExp_Object *
ES_RegExp_Object::MakePrototypeObject(ES_Context *context, ES_Global_Object *global_object, ES_Class *&instance)
{
JString **idents = context->rt_data->idents;
ES_Class_Singleton *prototype_class = ES_Class::MakeSingleton(context, global_object->GetObjectPrototype(), "RegExp", idents[ESID_RegExp], ES_RegExpBuiltins::ES_RegExpBuiltinsCount);
prototype_class->Prototype()->AddInstance(context, prototype_class, TRUE);
ES_RegExpBuiltins::PopulatePrototypeClass(context, prototype_class);
RegExpFlags re_flags;
re_flags.ignore_case = NO;
re_flags.multi_line = NO;
ES_SuspendedCreateRegExp suspended(UNI_L("(?:)"), 4, &re_flags);
suspended.Execute(context);
if (OpStatus::IsError(suspended.status))
if (OpStatus::IsMemoryError(suspended.status))
context->AbortOutOfMemory();
else
return NULL;
ES_RegExp_Information re_info;
re_info.regexp = suspended.regexp;
re_info.flags = 0;
re_info.source = UINT_MAX;
ES_RegExp_Object *prototype_object;
unsigned ncaptures = re_info.regexp->GetNumberOfCaptures();
unsigned extra = ncaptures * sizeof(RegExpMatch);
GC_ALLOCATE_WITH_EXTRA(context, prototype_object, extra, ES_RegExp_Object, (prototype_object, prototype_class, global_object, re_info));
re_info.regexp->DecRef();
ES_CollectorLock gclock(context);
prototype_class->AddInstance(context, prototype_object);
prototype_object->flags = re_info.flags;
prototype_object->AllocateProperties(context);
ES_RegExpBuiltins::PopulatePrototype(context, global_object, prototype_object);
ES_Class *sub_object_class = ES_Class::MakeRoot(context, prototype_object, "RegExp", idents[ESID_RegExp], TRUE);
prototype_object->SetSubObjectClass(context, sub_object_class);
sub_object_class = ES_Class::ExtendWithL(context, sub_object_class, idents[ESID_lastIndex], ES_Property_Info(DE|DD), ES_STORAGE_WHATEVER);
sub_object_class = ES_Class::ExtendWithL(context, sub_object_class, idents[ESID_source], ES_Property_Info(RO|DE|DD), ES_STORAGE_WHATEVER);
sub_object_class = ES_Class::ExtendWithL(context, sub_object_class, idents[ESID_global], ES_Property_Info(RO|DE|DD), ES_STORAGE_WHATEVER);
sub_object_class = ES_Class::ExtendWithL(context, sub_object_class, idents[ESID_ignoreCase], ES_Property_Info(RO|DE|DD), ES_STORAGE_WHATEVER);
instance = ES_Class::ExtendWithL(context, sub_object_class, idents[ESID_multiline], ES_Property_Info(RO|DE|DD), ES_STORAGE_WHATEVER);
return prototype_object;
}
JString *
ES_RegExp_Object::GetFlags(ES_Context *context)
{
char buffer[5], *ptr = buffer; /* ARRAY OK jl 2011-02-26 */
if (flags & REGEXP_FLAG_GLOBAL)
*ptr++ = 'g';
if (flags & REGEXP_FLAG_IGNORECASE)
*ptr++ = 'i';
if (flags & REGEXP_FLAG_MULTILINE)
*ptr++ = 'm';
#ifdef ES_NON_STANDARD_REGEXP_FEATURES
if (flags & REGEXP_FLAG_EXTENDED)
*ptr++ = 'x';
if (flags & REGEXP_FLAG_NOSEARCH)
*ptr++ = 'y';
#endif // ES_NON_STANDARD_REGEXP_FEATURES
return JString::Make(context, buffer, ptr - buffer);
}
void
ES_RegExp_Object::GetFlags(RegExpFlags &flags, unsigned &flagbits)
{
flagbits = this->flags;
flags.ignore_case = ((flagbits & REGEXP_FLAG_IGNORECASE) != 0) ? YES : NO;
flags.multi_line = ((flagbits & REGEXP_FLAG_MULTILINE) != 0) ? YES : NO;
#ifdef ES_NON_STANDARD_REGEXP_FEATURES
flags.ignore_whitespace = (flagbits & REGEXP_FLAG_EXTENDED) != 0;
flags.searching = (flagbits & REGEXP_FLAG_NOSEARCH) == 0;
#else
flags.ignore_whitespace = FALSE;
flags.searching = TRUE;
#endif // ES_NON_STANDARD_REGEXP_FEATURES
}
RegExpMatch *
ES_RegExp_Object::Exec(ES_Execution_Context *context, JString *string, unsigned index)
{
BOOL matched;
if (string == previous_string_positive && index == previous_index_positive)
matched = TRUE;
else if (string == previous_string_negative[0] && index == previous_index_negative[0] ||
string == previous_string_negative[1] && index == previous_index_negative[1])
matched = FALSE;
else
{
if (last_ctor)
last_ctor->BeforeMatch(this);
const uni_char *storage = Storage(context, string);
unsigned length = Length(string);
#ifdef ES_NATIVE_SUPPORT
if (native_matcher)
use_native_matcher: matched = native_matcher(GetMatchArray(), storage, index, length - index);
else if (calls != UINT_MAX && context->UseNativeDispatcher() &&
(++calls > ES_REGEXP_JIT_CALLS_THRESHOLD || length > ES_REGEXP_JIT_LENGTH_THRESHOLD) &&
CreateNativeMatcher(context))
goto use_native_matcher;
else
#endif // ES_NATIVE_SUPPORT
{
ES_RegExpSuspension suspend(context);
#ifdef ES_NON_STANDARD_REGEXP_FEATURES
matched = value->ExecL(storage, length, index, GetMatchArray(), &suspend, (flags & REGEXP_FLAG_NOSEARCH) == 0);
#else // ES_NON_STANDARD_REGEXP_FEATURES
matched = value->ExecL(storage, length, index, GetMatchArray(), &suspend);
#endif // ES_NON_STANDARD_REGEXP_FEATURES
}
if (matched)
{
previous_string_positive = string;
previous_index_positive = index;
}
else
{
previous_string_negative[1] = previous_string_negative[0];
previous_index_negative[1] = previous_index_negative[0];
previous_string_negative[0] = string;
previous_index_negative[0] = index;
/* A failed match still tramples 'match_array', so a cache of a
positive previous match must be invalidated. */
previous_string_positive = NULL;
}
}
if (matched)
{
last_ctor = GetRegExpConstructor(context);
last_ctor->SetCaptures(this, string);
return GetMatchArray();
}
else
return NULL;
}
unsigned
ES_RegExp_Object::GetNumberOfCaptures()
{
return value->GetNumberOfCaptures();
}
#ifdef ES_NATIVE_SUPPORT
class ES_SuspendedCreateNativeDispatcher
: public ES_SuspendedCall
{
public:
ES_SuspendedCreateNativeDispatcher(ES_Execution_Context *context, RegExp *regexp)
: context(context),
regexp(regexp)
{
context->SuspendedCall(this);
}
virtual void DoCall(ES_Execution_Context *context)
{
status = regexp->CreateNativeMatcher(context->heap->GetExecutableMemory());
}
OP_STATUS status;
private:
ES_Execution_Context *context;
RegExp *regexp;
};
RegExpNativeMatcher *
ES_RegExp_Object::CreateNativeMatcher(ES_Execution_Context *context)
{
if (calls != UINT_MAX)
{
ES_SuspendedCreateNativeDispatcher call(context, value);
if (call.status == OpStatus::OK)
return native_matcher = value->GetNativeMatcher();
else if (call.status == OpStatus::ERR)
calls = UINT_MAX;
else
context->AbortOutOfMemory();
}
return NULL;
}
#endif // ES_NATIVE_SUPPORT
ES_RegExp_Constructor *
ES_RegExp_Object::GetRegExpConstructor(ES_Execution_Context *context)
{
return context->GetGlobalObject()->GetRegExpConstructor();
}
void
ES_RegExp_Object::Update(ES_Context *context, RegExp *new_value, JString *new_source, unsigned new_flags)
{
if (last_ctor)
last_ctor->BeforeMatch(this);
/* Update the matches array -- if new_value has fewer captures, continue using. If not, flag it as invalid
and use new_value's match array. Which should be fine, as it is not shared. */
bool valid_matches = false;
if (value && new_value && value->GetNumberOfCaptures() > new_value->GetNumberOfCaptures())
valid_matches = true;
RegExpMatch *matches = GetMatchArray();
for (unsigned index = 0; index < static_cast<unsigned>(value->GetNumberOfCaptures()) + 1; ++index)
{
matches[index].start = 0;
matches[index].length = UINT_MAX;
}
if (!valid_matches)
{
unsigned ncaptures = 1 + new_value->GetNumberOfCaptures();
dynamic_match_array = ES_Box::Make(context, ncaptures * sizeof(RegExpMatch));
RegExpMatch *matches = reinterpret_cast<RegExpMatch *>(dynamic_match_array->Unbox());
for (unsigned index = 0; index < ncaptures; index++)
matches[index].length = UINT_MAX;
}
value->DecRef();
value = new_value;
flags = new_flags;
#ifdef ES_NATIVE_SUPPORT
native_matcher = value->GetNativeMatcher();
calls = 0;
#endif // ES_NATIVE_SUPPORT
SetProperties(context, new_source);
previous_string_positive = previous_string_negative[0] = previous_string_negative[1] = NULL;
}
/* static */ void
ES_RegExp_Object::Initialize(ES_RegExp_Object *regexp, ES_Class *klass, ES_Global_Object *global_object, const ES_RegExp_Information &info)
{
#ifdef ES_REGEXP_IS_CALLABLE
ES_Function::Initialize(regexp, klass, global_object, NULL, ES_RegExpBuiltins::exec, NULL);
#else
ES_Function::Initialize(regexp, klass, global_object, NULL, NULL, NULL);
#endif // ES_REGEXP_IS_CALLABLE
regexp->ChangeGCTag(GCTAG_ES_Object_RegExp);
regexp->last_ctor = NULL;
regexp->value = info.regexp;
regexp->flags = info.flags;
#ifdef ES_NATIVE_SUPPORT
regexp->native_matcher = regexp->value->GetNativeMatcher();
regexp->calls = 0;
#endif // ES_NATIVE_SUPPORT
unsigned ncaptures = 1 + regexp->value->GetNumberOfCaptures();
for (unsigned index = 0; index < ncaptures; ++index)
regexp->match_array[index].length = UINT_MAX;
regexp->dynamic_match_array = 0;
regexp->previous_string_positive = NULL;
regexp->previous_string_negative[0] = NULL;
regexp->previous_string_negative[1] = NULL;
regexp->SetNeedDestroy();
info.regexp->IncRef();
}
/* static */ void
ES_RegExp_Information::Destroy(ES_RegExp_Information *re_info)
{
if (re_info && re_info->regexp)
re_info->regexp->DecRef();
}
/* static */ void
ES_RegExp_Object::Destroy(ES_RegExp_Object *regexp)
{
regexp->value->DecRef();
}
void
ES_RegExp_Object::SetProperties(ES_Context *context, JString *source)
{
if (!properties)
AllocateProperties(context);
PutCachedAtIndex(ES_PropertyIndex(LASTINDEX), 0); // lastIndex
PutCachedAtIndex(ES_PropertyIndex(SOURCE), source); // source
ES_Value_Internal value;
value.SetBoolean((flags & REGEXP_FLAG_GLOBAL) != 0);
PutCachedAtIndex(ES_PropertyIndex(GLOBAL), value); // global
value.SetBoolean((flags & REGEXP_FLAG_IGNORECASE) != 0);
PutCachedAtIndex(ES_PropertyIndex(IGNORECASE), value); // ignoreCase
value.SetBoolean((flags & REGEXP_FLAG_MULTILINE) != 0);
PutCachedAtIndex(ES_PropertyIndex(MULTILINE), value); // multiline
}
static ES_Special_RegExp_Capture *
ES_Special_RegExp_Capture_Make(ES_Context *context, ES_RegExp_Constructor::IndexType index)
{
return ES_Special_RegExp_Capture::Make(context, static_cast<unsigned>(index));
}
/* static */ ES_RegExp_Constructor *
ES_RegExp_Constructor::Make(ES_Context *context, ES_Global_Object *global_object)
{
ES_RegExp_Constructor *ctor;
GC_ALLOCATE(context, ctor, ES_RegExp_Constructor, (ctor, global_object));
ctor->AllocateProperties(context);
ctor->data.builtin.information = ESID_RegExp | (2 << 16);
ctor->PutCachedAtIndex(ES_PropertyIndex(ES_Function::LENGTH), 2);
ctor->PutCachedAtIndex(ES_PropertyIndex(ES_Function::NAME), context->rt_data->idents[ESID_RegExp]);
ctor->PutCachedAtIndex(ES_PropertyIndex(ES_Function::PROTOTYPE), global_object->GetRegExpPrototype());
ctor->PutCachedAtIndex(ES_PropertyIndex(ES_RegExp_Constructor::INPUT), ES_Value_Internal());
unsigned index = 1;
for (index = 1; index <= 9; ++index)
{
ES_Value_Internal capture;
capture.SetBoxed(ES_Special_RegExp_Capture::Make(context, index));
ctor->PutCachedAtIndex(ES_PropertyIndex(ES_RegExp_Constructor::INPUT + index), capture);
}
ES_Value_Internal value;
value.SetBoxed(ES_Special_RegExp_Capture_Make(context, INDEX_INPUT));
index += ES_RegExp_Constructor::INPUT;
ctor->PutCachedAtIndex(ES_PropertyIndex(index), value);
value.SetBoxed(ES_Special_RegExp_Capture_Make(context, INDEX_LASTMATCH));
ctor->PutCachedAtIndex(ES_PropertyIndex(++index), value);
ctor->PutCachedAtIndex(ES_PropertyIndex(++index), value);
value.SetBoxed(ES_Special_RegExp_Capture_Make(context, INDEX_LASTPAREN));
ctor->PutCachedAtIndex(ES_PropertyIndex(++index), value);
ctor->PutCachedAtIndex(ES_PropertyIndex(++index), value);
value.SetBoxed(ES_Special_RegExp_Capture_Make(context, INDEX_LEFTCONTEXT));
ctor->PutCachedAtIndex(ES_PropertyIndex(++index), value);
ctor->PutCachedAtIndex(ES_PropertyIndex(++index), value);
value.SetBoxed(ES_Special_RegExp_Capture_Make(context, INDEX_RIGHTCONTEXT));
ctor->PutCachedAtIndex(ES_PropertyIndex(++index), value);
ctor->PutCachedAtIndex(ES_PropertyIndex(++index), value);
value.SetBoxed(ES_Special_RegExp_Capture_Make(context, INDEX_MULTILINE));
ctor->PutCachedAtIndex(ES_PropertyIndex(++index), value);
ctor->PutCachedAtIndex(ES_PropertyIndex(++index), value);
return ctor;
}
/* static */ void
ES_RegExp_Constructor::Initialize(ES_RegExp_Constructor *self, ES_Global_Object *global_object)
{
ES_Function::Initialize(self, global_object->GetRegExpConstructorClass(), global_object, NULL, ES_RegExpBuiltins::constructor_call, ES_RegExpBuiltins::constructor_construct);
self->ChangeGCTag(GCTAG_ES_Object_RegExp_CTOR);
self->object = NULL;
self->string = NULL;
self->multiline = FALSE;
self->use_backup = FALSE;
}
void
ES_RegExp_Constructor::GetCapture(ES_Context *context, ES_Value_Internal &value, unsigned index)
{
JString *result;
if (object && index - 1 < object->GetNumberOfCaptures() && (use_backup ? backup_matches : object->GetMatchArray())[index].length != UINT_MAX)
{
if (use_backup)
result = JString::Make(context, string, backup_matches[index].start, backup_matches[index].length);
else
result = JString::Make(context, string, object->GetMatchArray()[index].start, object->GetMatchArray()[index].length);
}
else
result = context->rt_data->strings[STRING_empty];
value.SetString(result);
}
void
ES_RegExp_Constructor::GetLastMatch(ES_Context *context, ES_Value_Internal &value)
{
JString *result;
if (object)
{
if (use_backup)
result = JString::Make(context, string, backup_matches[0].start, backup_matches[0].length);
else
result = JString::Make(context, string, matches[0].start, matches[0].length);
}
else
result = context->rt_data->strings[STRING_empty];
value.SetString(result);
}
void
ES_RegExp_Constructor::GetLastParen(ES_Context *context, ES_Value_Internal &value)
{
if (object)
GetCapture(context, value, es_minu(object->GetNumberOfCaptures(), 10));
else
value.SetString(context->rt_data->strings[STRING_empty]);
}
void
ES_RegExp_Constructor::GetLeftContext(ES_Context *context, ES_Value_Internal &value)
{
JString *result;
if (object)
{
if (use_backup)
result = JString::Make(context, string, 0, backup_matches[0].start);
else
result = JString::Make(context, string, 0, matches[0].start);
}
else
result = context->rt_data->strings[STRING_empty];
value.SetString(result);
}
void
ES_RegExp_Constructor::GetRightContext(ES_Context *context, ES_Value_Internal &value)
{
JString *result;
if (object)
{
unsigned offset = use_backup ? (backup_matches[0].start + backup_matches[0].length) : (matches[0].start + matches[0].length);
result = JString::Make(context, string, offset, Length(string) - offset);
}
else
result = context->rt_data->strings[STRING_empty];
value.SetString(result);
}
void
ES_RegExp_Constructor::BackupMatches()
{
if (matches != backup_matches && !use_backup)
{
backup_matches[0] = matches[0];
unsigned ncaptures = object->GetNumberOfCaptures();
for (unsigned index = 1, count = es_minu(ncaptures, 9); index <= count; ++index)
backup_matches[index] = matches[index];
if (ncaptures > 9)
backup_matches[10] = matches[ncaptures];
use_backup = TRUE;
}
}
/* virtual */ void
ES_SuspendedCreateRegExp::DoCall(ES_Execution_Context *context)
{
regexp = OP_NEW(RegExp, ());
if (!regexp)
status = OpStatus::ERR_NO_MEMORY;
else
{
status = regexp->Init(pattern, length, NULL, flags);
if (OpStatus::IsError(status))
regexp->DecRef();
}
}
void
ES_SuspendedCreateRegExp::Execute(ES_Context *context)
{
if (!context->IsUsingStandardStack())
static_cast<ES_Execution_Context *>(context)->SuspendedCall(this);
else
DoCall(static_cast<ES_Execution_Context *>(context));
}
/* virtual */ void
ES_SuspendedUpdateRegExp::DoCall(ES_Execution_Context *context)
{
RegExp *regexp = OP_NEW(RegExp, ());
if (!regexp)
status = OpStatus::ERR_NO_MEMORY;
else
{
status = regexp->Init(Storage(context, source), Length(source), NULL, flags);
if (OpStatus::IsError(status))
regexp->DecRef();
else
update_object->Update(context, regexp, source, flagbits);
}
}
|
#pragma once
#include <nlohmann/json.hpp>
#include <string>
using namespace std;
using json = nlohmann::json;
double toDouble(const json &);
|
/*
Copyright (c) 2018-2019, tevador <tevador@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "crypto/randomx/common.hpp"
#include "crypto/randomx/randomx.h"
#include "crypto/randomx/dataset.hpp"
#include "crypto/randomx/vm_interpreted.hpp"
#include "crypto/randomx/vm_interpreted_light.hpp"
#include "crypto/randomx/vm_compiled.hpp"
#include "crypto/randomx/vm_compiled_light.hpp"
#include "crypto/randomx/blake2/blake2.h"
#if defined(_M_X64) || defined(__x86_64__)
#include "crypto/randomx/jit_compiler_x86_static.hpp"
#elif defined(XMRIG_ARMv8)
#include "crypto/randomx/jit_compiler_a64_static.hpp"
#endif
#include "backend/cpu/Cpu.h"
#include "crypto/common/VirtualMemory.h"
#include <mutex>
#include <cassert>
extern "C" {
#include "crypto/randomx/panthera/yespower.h"
#include "crypto/randomx/panthera/KangarooTwelve.h"
}
#include "crypto/rx/Profiler.h"
RandomX_ConfigurationWownero::RandomX_ConfigurationWownero()
{
ArgonSalt = "RandomWOW\x01";
ProgramIterations = 1024;
ProgramCount = 16;
ScratchpadL2_Size = 131072;
ScratchpadL3_Size = 1048576;
RANDOMX_FREQ_IADD_RS = 25;
RANDOMX_FREQ_IROR_R = 10;
RANDOMX_FREQ_IROL_R = 0;
RANDOMX_FREQ_FSWAP_R = 8;
RANDOMX_FREQ_FADD_R = 20;
RANDOMX_FREQ_FSUB_R = 20;
RANDOMX_FREQ_FMUL_R = 20;
RANDOMX_FREQ_CBRANCH = 16;
fillAes4Rx4_Key[0] = rx_set_int_vec_i128(0xcf359e95, 0x141f82b7, 0x7ffbe4a6, 0xf890465d);
fillAes4Rx4_Key[1] = rx_set_int_vec_i128(0x6741ffdc, 0xbd5c5ac3, 0xfee8278a, 0x6a55c450);
fillAes4Rx4_Key[2] = rx_set_int_vec_i128(0x3d324aac, 0xa7279ad2, 0xd524fde4, 0x114c47a4);
fillAes4Rx4_Key[3] = rx_set_int_vec_i128(0x76f6db08, 0x42d3dbd9, 0x99a9aeff, 0x810c3a2a);
fillAes4Rx4_Key[4] = fillAes4Rx4_Key[0];
fillAes4Rx4_Key[5] = fillAes4Rx4_Key[1];
fillAes4Rx4_Key[6] = fillAes4Rx4_Key[2];
fillAes4Rx4_Key[7] = fillAes4Rx4_Key[3];
}
RandomX_ConfigurationArqma::RandomX_ConfigurationArqma()
{
ArgonIterations = 1;
ArgonSalt = "RandomARQ\x01";
ProgramIterations = 1024;
ProgramCount = 4;
ScratchpadL2_Size = 131072;
ScratchpadL3_Size = 262144;
}
RandomX_ConfigurationSafex::RandomX_ConfigurationSafex()
{
ArgonSalt = "RandomSFX\x01";
}
RandomX_ConfigurationKeva::RandomX_ConfigurationKeva()
{
ArgonSalt = "RandomKV\x01";
ScratchpadL2_Size = 131072;
ScratchpadL3_Size = 1048576;
}
RandomX_ConfigurationScala::RandomX_ConfigurationScala()
{
ArgonMemory = 131072;
ArgonIterations = 2;
ArgonSalt = "DefyXScala\x13";
CacheAccesses = 2;
DatasetBaseSize = 33554432;
ScratchpadL1_Size = 65536;
ScratchpadL2_Size = 131072;
ScratchpadL3_Size = 262144;
ProgramSize = 64;
ProgramIterations = 1024;
ProgramCount = 4;
RANDOMX_FREQ_IADD_RS = 25;
RANDOMX_FREQ_CBRANCH = 16;
}
RandomX_ConfigurationBase::RandomX_ConfigurationBase()
: ArgonMemory(262144)
, CacheAccesses(8)
, DatasetBaseSize(2147483648)
, ArgonIterations(3)
, ArgonLanes(1)
, ArgonSalt("RandomX\x03")
, ScratchpadL1_Size(16384)
, ScratchpadL2_Size(262144)
, ScratchpadL3_Size(2097152)
, ProgramSize(256)
, ProgramIterations(2048)
, ProgramCount(8)
, RANDOMX_FREQ_IADD_RS(16)
, RANDOMX_FREQ_IADD_M(7)
, RANDOMX_FREQ_ISUB_R(16)
, RANDOMX_FREQ_ISUB_M(7)
, RANDOMX_FREQ_IMUL_R(16)
, RANDOMX_FREQ_IMUL_M(4)
, RANDOMX_FREQ_IMULH_R(4)
, RANDOMX_FREQ_IMULH_M(1)
, RANDOMX_FREQ_ISMULH_R(4)
, RANDOMX_FREQ_ISMULH_M(1)
, RANDOMX_FREQ_IMUL_RCP(8)
, RANDOMX_FREQ_INEG_R(2)
, RANDOMX_FREQ_IXOR_R(15)
, RANDOMX_FREQ_IXOR_M(5)
, RANDOMX_FREQ_IROR_R(8)
, RANDOMX_FREQ_IROL_R(2)
, RANDOMX_FREQ_ISWAP_R(4)
, RANDOMX_FREQ_FSWAP_R(4)
, RANDOMX_FREQ_FADD_R(16)
, RANDOMX_FREQ_FADD_M(5)
, RANDOMX_FREQ_FSUB_R(16)
, RANDOMX_FREQ_FSUB_M(5)
, RANDOMX_FREQ_FSCAL_R(6)
, RANDOMX_FREQ_FMUL_R(32)
, RANDOMX_FREQ_FDIV_M(4)
, RANDOMX_FREQ_FSQRT_R(6)
, RANDOMX_FREQ_CBRANCH(25)
, RANDOMX_FREQ_CFROUND(1)
, RANDOMX_FREQ_ISTORE(16)
, RANDOMX_FREQ_NOP(0)
{
fillAes4Rx4_Key[0] = rx_set_int_vec_i128(0x99e5d23f, 0x2f546d2b, 0xd1833ddb, 0x6421aadd);
fillAes4Rx4_Key[1] = rx_set_int_vec_i128(0xa5dfcde5, 0x06f79d53, 0xb6913f55, 0xb20e3450);
fillAes4Rx4_Key[2] = rx_set_int_vec_i128(0x171c02bf, 0x0aa4679f, 0x515e7baf, 0x5c3ed904);
fillAes4Rx4_Key[3] = rx_set_int_vec_i128(0xd8ded291, 0xcd673785, 0xe78f5d08, 0x85623763);
fillAes4Rx4_Key[4] = rx_set_int_vec_i128(0x229effb4, 0x3d518b6d, 0xe3d6a7a6, 0xb5826f73);
fillAes4Rx4_Key[5] = rx_set_int_vec_i128(0xb272b7d2, 0xe9024d4e, 0x9c10b3d9, 0xc7566bf3);
fillAes4Rx4_Key[6] = rx_set_int_vec_i128(0xf63befa7, 0x2ba9660a, 0xf765a38b, 0xf273c9e7);
fillAes4Rx4_Key[7] = rx_set_int_vec_i128(0xc0b0762d, 0x0c06d1fd, 0x915839de, 0x7a7cd609);
# if defined(XMRIG_FEATURE_ASM) && (defined(_M_X64) || defined(__x86_64__))
// Workaround for Visual Studio placing trampoline in debug builds.
auto addr = [](void (*func)()) {
const uint8_t* p = reinterpret_cast<const uint8_t*>(func);
# if defined(_MSC_VER)
if (p[0] == 0xE9) {
p += *(const int32_t*)(p + 1) + 5;
}
# endif
return p;
};
{
const uint8_t* a = addr(randomx_sshash_prefetch);
const uint8_t* b = addr(randomx_sshash_end);
memcpy(codeShhPrefetchTweaked, a, b - a);
}
{
const uint8_t* a = addr(randomx_program_read_dataset);
const uint8_t* b = addr(randomx_program_read_dataset_ryzen);
memcpy(codeReadDatasetTweaked, a, b - a);
codeReadDatasetTweakedSize = b - a;
}
{
const uint8_t* a = addr(randomx_program_read_dataset_ryzen);
const uint8_t* b = addr(randomx_program_read_dataset_sshash_init);
memcpy(codeReadDatasetRyzenTweaked, a, b - a);
codeReadDatasetRyzenTweakedSize = b - a;
}
if (xmrig::Cpu::info()->hasBMI2()) {
const uint8_t* a = addr(randomx_prefetch_scratchpad_bmi2);
const uint8_t* b = addr(randomx_prefetch_scratchpad_end);
memcpy(codePrefetchScratchpadTweaked, a, b - a);
codePrefetchScratchpadTweakedSize = b - a;
}
else {
const uint8_t* a = addr(randomx_prefetch_scratchpad);
const uint8_t* b = addr(randomx_prefetch_scratchpad_bmi2);
memcpy(codePrefetchScratchpadTweaked, a, b - a);
codePrefetchScratchpadTweakedSize = b - a;
}
# endif
}
#ifdef XMRIG_ARMv8
static uint32_t Log2(size_t value) { return (value > 1) ? (Log2(value / 2) + 1) : 0; }
#endif
static int scratchpadPrefetchMode = 1;
void randomx_set_scratchpad_prefetch_mode(int mode)
{
scratchpadPrefetchMode = mode;
}
void RandomX_ConfigurationBase::Apply()
{
const uint32_t ScratchpadL1Mask_Calculated = (ScratchpadL1_Size / sizeof(uint64_t) - 1) * 8;
const uint32_t ScratchpadL2Mask_Calculated = (ScratchpadL2_Size / sizeof(uint64_t) - 1) * 8;
AddressMask_Calculated[0] = ScratchpadL2Mask_Calculated;
AddressMask_Calculated[1] = ScratchpadL1Mask_Calculated;
AddressMask_Calculated[2] = ScratchpadL1Mask_Calculated;
AddressMask_Calculated[3] = ScratchpadL1Mask_Calculated;
ScratchpadL3Mask_Calculated = (((ScratchpadL3_Size / sizeof(uint64_t)) - 1) * 8);
ScratchpadL3Mask64_Calculated = ((ScratchpadL3_Size / sizeof(uint64_t)) / 8 - 1) * 64;
CacheLineAlignMask_Calculated = (DatasetBaseSize - 1) & ~(RANDOMX_DATASET_ITEM_SIZE - 1);
#if defined(XMRIG_FEATURE_ASM) && (defined(_M_X64) || defined(__x86_64__))
*(uint32_t*)(codeShhPrefetchTweaked + 3) = ArgonMemory * 16 - 1;
const uint32_t DatasetBaseMask = DatasetBaseSize - RANDOMX_DATASET_ITEM_SIZE;
*(uint32_t*)(codeReadDatasetRyzenTweaked + 9) = DatasetBaseMask;
*(uint32_t*)(codeReadDatasetRyzenTweaked + 24) = DatasetBaseMask;
*(uint32_t*)(codeReadDatasetTweaked + 7) = DatasetBaseMask;
*(uint32_t*)(codeReadDatasetTweaked + 23) = DatasetBaseMask;
//*(uint32_t*)(codeReadDatasetLightSshInitTweaked + 59) = DatasetBaseMask;
const bool hasBMI2 = xmrig::Cpu::info()->hasBMI2();
*(uint32_t*)(codePrefetchScratchpadTweaked + (hasBMI2 ? 7 : 4)) = ScratchpadL3Mask64_Calculated;
*(uint32_t*)(codePrefetchScratchpadTweaked + (hasBMI2 ? 17 : 18)) = ScratchpadL3Mask64_Calculated;
// Apply scratchpad prefetch mode
{
uint32_t* a = (uint32_t*)(codePrefetchScratchpadTweaked + (hasBMI2 ? 11 : 8));
uint32_t* b = (uint32_t*)(codePrefetchScratchpadTweaked + (hasBMI2 ? 21 : 22));
switch (scratchpadPrefetchMode)
{
case 0:
*a = 0x00401F0FUL; // 4-byte nop
*b = 0x00401F0FUL; // 4-byte nop
break;
case 1:
default:
*a = 0x060C180FUL; // prefetcht0 [rsi+rax]
*b = 0x160C180FUL; // prefetcht0 [rsi+rdx]
break;
case 2:
*a = 0x0604180FUL; // prefetchnta [rsi+rax]
*b = 0x1604180FUL; // prefetchnta [rsi+rdx]
break;
case 3:
*a = 0x060C8B48UL; // mov rcx, [rsi+rax]
*b = 0x160C8B48UL; // mov rcx, [rsi+rdx]
break;
}
}
typedef void(randomx::JitCompilerX86::* InstructionGeneratorX86_2)(const randomx::Instruction&);
#define JIT_HANDLE(x, prev) do { \
const InstructionGeneratorX86_2 p = &randomx::JitCompilerX86::h_##x; \
memcpy(randomx::JitCompilerX86::engine + k, &p, sizeof(p)); \
} while (0)
#elif defined(XMRIG_ARMv8)
Log2_ScratchpadL1 = Log2(ScratchpadL1_Size);
Log2_ScratchpadL2 = Log2(ScratchpadL2_Size);
Log2_ScratchpadL3 = Log2(ScratchpadL3_Size);
Log2_DatasetBaseSize = Log2(DatasetBaseSize);
Log2_CacheSize = Log2((ArgonMemory * randomx::ArgonBlockSize) / randomx::CacheLineSize);
#define JIT_HANDLE(x, prev) randomx::JitCompilerA64::engine[k] = &randomx::JitCompilerA64::h_##x
#else
#define JIT_HANDLE(x, prev)
#endif
uint32_t k = 0;
uint32_t freq_sum = 0;
#define INST_HANDLE(x, prev) \
freq_sum += RANDOMX_FREQ_##x; \
for (; k < freq_sum; ++k) { JIT_HANDLE(x, prev); }
#define INST_HANDLE2(x, func_name, prev) \
freq_sum += RANDOMX_FREQ_##x; \
for (; k < freq_sum; ++k) { JIT_HANDLE(func_name, prev); }
INST_HANDLE(IADD_RS, NULL);
INST_HANDLE(IADD_M, IADD_RS);
INST_HANDLE(ISUB_R, IADD_M);
INST_HANDLE(ISUB_M, ISUB_R);
INST_HANDLE(IMUL_R, ISUB_M);
INST_HANDLE(IMUL_M, IMUL_R);
#if defined(_M_X64) || defined(__x86_64__)
if (hasBMI2) {
INST_HANDLE2(IMULH_R, IMULH_R_BMI2, IMUL_M);
INST_HANDLE2(IMULH_M, IMULH_M_BMI2, IMULH_R);
}
else
#endif
{
INST_HANDLE(IMULH_R, IMUL_M);
INST_HANDLE(IMULH_M, IMULH_R);
}
INST_HANDLE(ISMULH_R, IMULH_M);
INST_HANDLE(ISMULH_M, ISMULH_R);
INST_HANDLE(IMUL_RCP, ISMULH_M);
INST_HANDLE(INEG_R, IMUL_RCP);
INST_HANDLE(IXOR_R, INEG_R);
INST_HANDLE(IXOR_M, IXOR_R);
INST_HANDLE(IROR_R, IXOR_M);
INST_HANDLE(IROL_R, IROR_R);
INST_HANDLE(ISWAP_R, IROL_R);
INST_HANDLE(FSWAP_R, ISWAP_R);
INST_HANDLE(FADD_R, FSWAP_R);
INST_HANDLE(FADD_M, FADD_R);
INST_HANDLE(FSUB_R, FADD_M);
INST_HANDLE(FSUB_M, FSUB_R);
INST_HANDLE(FSCAL_R, FSUB_M);
INST_HANDLE(FMUL_R, FSCAL_R);
INST_HANDLE(FDIV_M, FMUL_R);
INST_HANDLE(FSQRT_R, FDIV_M);
#if defined(_M_X64) || defined(__x86_64__)
if (xmrig::Cpu::info()->jccErratum()) {
INST_HANDLE2(CBRANCH, CBRANCH<true>, FSQRT_R);
}
else {
INST_HANDLE2(CBRANCH, CBRANCH<false>, FSQRT_R);
}
#else
INST_HANDLE(CBRANCH, FSQRT_R);
#endif
#if defined(_M_X64) || defined(__x86_64__)
if (hasBMI2) {
INST_HANDLE2(CFROUND, CFROUND_BMI2, CBRANCH);
}
else
#endif
{
INST_HANDLE(CFROUND, CBRANCH);
}
INST_HANDLE(ISTORE, CFROUND);
INST_HANDLE(NOP, ISTORE);
#undef INST_HANDLE
}
RandomX_ConfigurationMonero RandomX_MoneroConfig;
RandomX_ConfigurationWownero RandomX_WowneroConfig;
RandomX_ConfigurationArqma RandomX_ArqmaConfig;
RandomX_ConfigurationSafex RandomX_SafexConfig;
RandomX_ConfigurationKeva RandomX_KevaConfig;
RandomX_ConfigurationScala RandomX_ScalaConfig;
alignas(64) RandomX_ConfigurationBase RandomX_CurrentConfig;
static std::mutex vm_pool_mutex;
int rx_yespower_k12(void *out, size_t outlen, const void *in, size_t inlen)
{
rx_blake2b_wrapper::run(out, outlen, in, inlen);
yespower_params_t params = { YESPOWER_1_0, 2048, 8, NULL };
if (yespower_tls((const uint8_t *)out, outlen, ¶ms, (yespower_binary_t *)out)) return -1;
return KangarooTwelve((const unsigned char *)out, outlen, (unsigned char *)out, 32, 0, 0);
}
extern "C" {
randomx_cache *randomx_create_cache(randomx_flags flags, uint8_t *memory) {
if (!memory) {
return nullptr;
}
randomx_cache *cache = nullptr;
try {
cache = new randomx_cache();
switch (flags & RANDOMX_FLAG_JIT) {
case RANDOMX_FLAG_DEFAULT:
cache->jit = nullptr;
cache->initialize = &randomx::initCache;
cache->datasetInit = &randomx::initDataset;
cache->memory = memory;
break;
case RANDOMX_FLAG_JIT:
cache->jit = new randomx::JitCompiler(false, true);
cache->initialize = &randomx::initCacheCompile;
cache->datasetInit = nullptr;
cache->memory = memory;
break;
default:
UNREACHABLE;
}
}
catch (std::exception &ex) {
if (cache != nullptr) {
randomx_release_cache(cache);
cache = nullptr;
}
}
return cache;
}
void randomx_init_cache(randomx_cache *cache, const void *key, size_t keySize) {
assert(cache != nullptr);
assert(keySize == 0 || key != nullptr);
cache->initialize(cache, key, keySize);
}
void randomx_release_cache(randomx_cache* cache) {
delete cache;
}
randomx_dataset *randomx_create_dataset(uint8_t *memory) {
if (!memory) {
return nullptr;
}
auto dataset = new randomx_dataset();
dataset->memory = memory;
return dataset;
}
#define DatasetItemCount ((RandomX_CurrentConfig.DatasetBaseSize + RandomX_CurrentConfig.DatasetExtraSize) / RANDOMX_DATASET_ITEM_SIZE)
unsigned long randomx_dataset_item_count() {
return DatasetItemCount;
}
void randomx_init_dataset(randomx_dataset *dataset, randomx_cache *cache, unsigned long startItem, unsigned long itemCount) {
assert(dataset != nullptr);
assert(cache != nullptr);
assert(startItem < DatasetItemCount && itemCount <= DatasetItemCount);
assert(startItem + itemCount <= DatasetItemCount);
cache->datasetInit(cache, dataset->memory + startItem * randomx::CacheLineSize, startItem, startItem + itemCount);
}
void *randomx_get_dataset_memory(randomx_dataset *dataset) {
assert(dataset != nullptr);
return dataset->memory;
}
void randomx_release_dataset(randomx_dataset *dataset) {
delete dataset;
}
randomx_vm* randomx_create_vm(randomx_flags flags, randomx_cache* cache, randomx_dataset* dataset, uint8_t* scratchpad, uint32_t node) {
assert(cache != nullptr || (flags & RANDOMX_FLAG_FULL_MEM));
assert(cache == nullptr || cache->isInitialized());
assert(dataset != nullptr || !(flags & RANDOMX_FLAG_FULL_MEM));
randomx_vm* vm = nullptr;
std::lock_guard<std::mutex> lock(vm_pool_mutex);
static uint8_t* vm_pool[64] = {};
static size_t vm_pool_offset[64] = {};
constexpr size_t VM_POOL_SIZE = 2 * 1024 * 1024;
if (node >= 64) {
node = 0;
}
if (!vm_pool[node]) {
vm_pool[node] = (uint8_t*) xmrig::VirtualMemory::allocateLargePagesMemory(VM_POOL_SIZE);
if (!vm_pool[node]) {
vm_pool[node] = (uint8_t*) rx_aligned_alloc(VM_POOL_SIZE, 4096);
}
}
void* p = vm_pool[node] + vm_pool_offset[node];
size_t vm_size = 0;
try {
switch (flags & (RANDOMX_FLAG_FULL_MEM | RANDOMX_FLAG_JIT | RANDOMX_FLAG_HARD_AES)) {
case RANDOMX_FLAG_DEFAULT:
vm = new(p) randomx::InterpretedLightVmDefault();
vm_size = sizeof(randomx::InterpretedLightVmDefault);
break;
case RANDOMX_FLAG_FULL_MEM:
vm = new(p) randomx::InterpretedVmDefault();
vm_size = sizeof(randomx::InterpretedVmDefault);
break;
case RANDOMX_FLAG_JIT:
vm = new(p) randomx::CompiledLightVmDefault();
vm_size = sizeof(randomx::CompiledLightVmDefault);
break;
case RANDOMX_FLAG_FULL_MEM | RANDOMX_FLAG_JIT:
vm = new(p) randomx::CompiledVmDefault();
vm_size = sizeof(randomx::CompiledVmDefault);
break;
case RANDOMX_FLAG_HARD_AES:
vm = new(p) randomx::InterpretedLightVmHardAes();
vm_size = sizeof(randomx::InterpretedLightVmHardAes);
break;
case RANDOMX_FLAG_FULL_MEM | RANDOMX_FLAG_HARD_AES:
vm = new(p) randomx::InterpretedVmHardAes();
vm_size = sizeof(randomx::InterpretedVmHardAes);
break;
case RANDOMX_FLAG_JIT | RANDOMX_FLAG_HARD_AES:
vm = new(p) randomx::CompiledLightVmHardAes();
vm_size = sizeof(randomx::CompiledLightVmHardAes);
break;
case RANDOMX_FLAG_FULL_MEM | RANDOMX_FLAG_JIT | RANDOMX_FLAG_HARD_AES:
vm = new(p) randomx::CompiledVmHardAes();
vm_size = sizeof(randomx::CompiledVmHardAes);
break;
default:
UNREACHABLE;
}
if (cache != nullptr) {
vm->setCache(cache);
}
if (dataset != nullptr) {
vm->setDataset(dataset);
}
vm->setScratchpad(scratchpad);
vm->setFlags(flags);
}
catch (std::exception &ex) {
vm = nullptr;
}
if (vm) {
vm_pool_offset[node] += vm_size;
if (vm_pool_offset[node] + 4096 > VM_POOL_SIZE) {
vm_pool_offset[node] = 0;
}
}
return vm;
}
void randomx_vm_set_cache(randomx_vm *machine, randomx_cache* cache) {
assert(machine != nullptr);
assert(cache != nullptr && cache->isInitialized());
machine->setCache(cache);
}
void randomx_vm_set_dataset(randomx_vm *machine, randomx_dataset *dataset) {
assert(machine != nullptr);
assert(dataset != nullptr);
machine->setDataset(dataset);
}
void randomx_destroy_vm(randomx_vm* vm) {
vm->~randomx_vm();
}
void randomx_calculate_hash(randomx_vm *machine, const void *input, size_t inputSize, void *output, const xmrig::Algorithm algo) {
assert(machine != nullptr);
assert(inputSize == 0 || input != nullptr);
assert(output != nullptr);
alignas(16) uint64_t tempHash[8];
switch (algo) {
case xmrig::Algorithm::RX_XLA: rx_yespower_k12(tempHash, sizeof(tempHash), input, inputSize); break;
default: rx_blake2b_wrapper::run(tempHash, sizeof(tempHash), input, inputSize);
}
machine->initScratchpad(&tempHash);
machine->resetRoundingMode();
for (uint32_t chain = 0; chain < RandomX_CurrentConfig.ProgramCount - 1; ++chain) {
machine->run(&tempHash);
rx_blake2b_wrapper::run(tempHash, sizeof(tempHash), machine->getRegisterFile(), sizeof(randomx::RegisterFile));
}
machine->run(&tempHash);
machine->getFinalResult(output);
}
void randomx_calculate_hash_first(randomx_vm* machine, uint64_t (&tempHash)[8], const void* input, size_t inputSize, const xmrig::Algorithm algo) {
switch (algo) {
case xmrig::Algorithm::RX_XLA: rx_yespower_k12(tempHash, sizeof(tempHash), input, inputSize); break;
default: rx_blake2b_wrapper::run(tempHash, sizeof(tempHash), input, inputSize);
}
machine->initScratchpad(tempHash);
}
void randomx_calculate_hash_next(randomx_vm* machine, uint64_t (&tempHash)[8], const void* nextInput, size_t nextInputSize, void* output, const xmrig::Algorithm algo) {
PROFILE_SCOPE(RandomX_hash);
machine->resetRoundingMode();
for (uint32_t chain = 0; chain < RandomX_CurrentConfig.ProgramCount - 1; ++chain) {
machine->run(&tempHash);
rx_blake2b_wrapper::run(tempHash, sizeof(tempHash), machine->getRegisterFile(), sizeof(randomx::RegisterFile));
}
machine->run(&tempHash);
// Finish current hash and fill the scratchpad for the next hash at the same time
switch (algo) {
case xmrig::Algorithm::RX_XLA: rx_yespower_k12(tempHash, sizeof(tempHash), nextInput, nextInputSize); break;
default: rx_blake2b_wrapper::run(tempHash, sizeof(tempHash), nextInput, nextInputSize);
}
machine->hashAndFill(output, tempHash);
}
}
|
// Created on: 1995-10-17
// Created by: Laurent BOURESCHE
// Copyright (c) 1995-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _GeomFill_Boundary_HeaderFile
#define _GeomFill_Boundary_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <Standard_Real.hxx>
#include <Standard_Transient.hxx>
class gp_Pnt;
class gp_Vec;
class GeomFill_Boundary;
DEFINE_STANDARD_HANDLE(GeomFill_Boundary, Standard_Transient)
//! Root class to define a boundary which will form part of a
//! contour around a gap requiring filling.
//! Any new type of constrained boundary must inherit this class.
//! The GeomFill package provides two classes to define constrained boundaries:
//! - GeomFill_SimpleBound to define an unattached boundary
//! - GeomFill_BoundWithSurf to define a boundary attached to a surface.
//! These objects are used to define the boundaries for a
//! GeomFill_ConstrainedFilling framework.
class GeomFill_Boundary : public Standard_Transient
{
public:
Standard_EXPORT virtual gp_Pnt Value (const Standard_Real U) const = 0;
Standard_EXPORT virtual void D1 (const Standard_Real U, gp_Pnt& P, gp_Vec& V) const = 0;
Standard_EXPORT virtual Standard_Boolean HasNormals() const;
Standard_EXPORT virtual gp_Vec Norm (const Standard_Real U) const;
Standard_EXPORT virtual void D1Norm (const Standard_Real U, gp_Vec& N, gp_Vec& DN) const;
Standard_EXPORT virtual void Reparametrize (const Standard_Real First, const Standard_Real Last, const Standard_Boolean HasDF, const Standard_Boolean HasDL, const Standard_Real DF, const Standard_Real DL, const Standard_Boolean Rev) = 0;
Standard_EXPORT void Points (gp_Pnt& PFirst, gp_Pnt& PLast) const;
Standard_EXPORT virtual void Bounds (Standard_Real& First, Standard_Real& Last) const = 0;
Standard_EXPORT virtual Standard_Boolean IsDegenerated() const = 0;
Standard_EXPORT Standard_Real Tol3d() const;
Standard_EXPORT void Tol3d (const Standard_Real Tol);
Standard_EXPORT Standard_Real Tolang() const;
Standard_EXPORT void Tolang (const Standard_Real Tol);
DEFINE_STANDARD_RTTIEXT(GeomFill_Boundary,Standard_Transient)
protected:
Standard_EXPORT GeomFill_Boundary(const Standard_Real Tol3d, const Standard_Real Tolang);
private:
Standard_Real myT3d;
Standard_Real myTang;
};
#endif // _GeomFill_Boundary_HeaderFile
|
#ifndef APPLICATION_BASECMD_H
#define APPLICATION_BASECMD_H
#include <utility>
#include "CallbacksHolder/CallbacksHolder.h"
// Abstract command
class BaseCmd {
public:
virtual ~BaseCmd() = default;
BaseCmd(int numRequest, const std::optional<std::string>& error,
const std::string& body);
// Execute command
virtual void execute(std::shared_ptr<CallbacksHolder> holder) = 0;
protected:
int numRequest;
std::optional<std::string> error;
const std::string body;
};
#endif //APPLICATION_BASECMD_H
|
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <unistd.h>
#include "odb/client/db-client-impl-data.hh"
#include "odb/client/tcp-data-client.hh"
#include "odb/mess/db-client.hh"
#include "odb/mess/simple-cli-client.hh"
void wait_stop(odb::DBClient &db_client) {
while (1) {
db_client.check_stopped();
auto state = db_client.state();
if (state != odb::DBClient::State::VM_RUNNING)
break;
auto sl_dur = std::chrono::milliseconds(10);
std::this_thread::sleep_for(sl_dur);
}
}
int main(int argc, char **argv) {
if (argc < 3) {
std::cerr << "Usage: odb-client-simple-cli <hostname> <port>\n";
return 1;
}
auto hostname = argv[1];
auto port = std::atoi(argv[2]);
auto tcp_cli = std::make_unique<odb::TCPDataClient>(hostname, port);
auto tcp_impl = std::make_unique<odb::DBClientImplData>(std::move(tcp_cli));
odb::DBClient db_client(std::move(tcp_impl));
odb::SimpleCLIClient cli(db_client);
bool is_tty = isatty(fileno(stdin));
db_client.connect();
bool print_state = true;
while (1) {
// Check if still connected
auto state = db_client.state();
if (state != odb::DBClient::State::VM_STOPPED &&
state != odb::DBClient::State::VM_RUNNING)
break;
// If VM running, wait for it to stop (need to sends requests at interval
// to know if still running)
if (state == odb::DBClient::State::VM_RUNNING) {
wait_stop(db_client);
print_state = true;
}
if (print_state)
std::cout << cli.exec("state");
if (is_tty) {
std::cout << "> ";
std::cout.flush();
}
std::string cmd;
std::getline(std::cin, cmd);
if (cmd.empty())
break;
#ifdef ODB_COMM_LOGS
auto t1 = std::chrono::high_resolution_clock::now();
#endif
std::string out = cli.exec(cmd);
#ifdef ODB_COMM_LOGS
auto t2 = std::chrono::high_resolution_clock::now();
#endif
std::cout << out;
if (!out.empty() && out.back() != '\n')
std::cout << std::endl;
print_state = false;
#ifdef ODB_COMM_LOGS
auto cmd_ms =
std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count();
std::cout << "Command executed in " << cmd_ms << "ms.\n";
#endif
}
return 0;
}
|
/*
* drinkmachine.h
*
*/
#ifndef DRINKMACHINE_H_
#define DRINKMACHINE_H_
// put any includes here
#include <iostream>
#include <fstream>
#include <iomanip>
//put constant structures
const unsigned int MAX_DRINKS = 20;
// put your structures here
struct DrinkItem
{
unsigned int id;
std::string name;
double price;
unsigned int numOfDrinks;
unsigned int drinksPurchased;
unsigned int quantityOffset;
unsigned int soldOffset;
};
struct DrinkMachine
{
unsigned int versionNum;
unsigned int drinkItem;
DrinkItem drinks[MAX_DRINKS];
std::fstream fileName;
};
// put function prototypes here
bool create(DrinkMachine &drinkMachine); //create function COMPLETED
void destroy(DrinkMachine &drinkMachine); // destroy function COMPLETED
DrinkItem& drink(DrinkMachine &drinkMachine, unsigned int drinkId); //drink function COMPLETED
unsigned int size(DrinkMachine &drinkMachine); //size function COMPLETED
bool available(DrinkMachine &drinkMachine, unsigned int drinkId); //available function COMPLETED
double price(DrinkMachine &drinkMachine, unsigned int drinkId); //price function COMPLETED
std::string name(DrinkMachine &drinkMachine, unsigned int drinkId); //name function COMPLETED
unsigned int quantity(DrinkMachine &drinkMachine, unsigned int drinkId); //quantity function COMPLETED
unsigned int sold(DrinkMachine &drinkMachine, unsigned int drinkId); //sold function COMPLETED
bool purchase(DrinkMachine &drinkMachine, int unsigned drinkId, double amount, double &change); //purchase function
void dumpDrinkMachine(const DrinkMachine &drinkMachine); //dumpDrinkMachine function*/
void bubbleSort(DrinkMachine &drinkMachine, int size);
// put all of your includes, structures and prototypes before this comment
#endif /* DRINKMACHINE_H_ */
|
#include <iostream>
using namespace std;
int n;
int main(){
cout<<"masukan angka : ";
cin>>n;
for(int i = 1; i <= n; i++){
if((i%3!=0) && (i%5!=0))
{
cout<<i<<endl;
}
if(i%3==0)
{
cout<<"upin"<<endl;
}
if(i%5==0)
{
cout<<"ipin"<<endl;
}
}
return 0;
}
|
/*
C --> C++ 변경, 개선점
<Data 정의 값 추가>
#define TRUE 1 --> true
#define FALSE 0 --> false
0 --> NULL
(void *)0 --> NULL(C) --> nullptr(C++)
<Data Type 추가>
bool : 논리 타입 --> true / false 명령어 를 저장하는 타입
<참조 타입 추가>
type * --> 동적 할당 / C style string 에 사용(char [])에 사용
배열형 --> type var[]
변수 참조형 --> reference type ---> ( type & )
<기본타입, 구조체 등의 초기화>
C style : int a = 10; // 대입을 이용한 초기화
CPP style : int a(10);// ()를 이용한 초기화 --> ex) 초기화 리스트
<연산자 추가>
new : malloc(sizeof(type)*1)
new [] : malloc(sizeof(type)*n)
delete : free( variable );
delete [] : free(dynamic array);
<사용자 정의 데이터 타입>
typedef struct _Node{}node; --> (C)
struct node{}; ---------------> (CPP)
class 명령어의 추가
객체지향 프로그래밍 지원
ㄴ 일반화 프로그래밍 지원
함수를 구분하는 기준 이름 ===> 이름 + 매개변수 ( 오버로딩 : Overloading)
C언어 : printf()의 매개변수에 "hello world"를 입력해서 < [출력동작]의 요소로 "hello world" 를 사용한다.>
C++ : console 출력을 담당하는 객체에 "hello world"를 전달한다. < [출력 객체]가 출력 동작을 처리한다.>
단일 책임 원칙 : XX를 담당하는 객체는 XX 만 처리한다.
*/
#include <iostream>
#include "myNode.h"
using namespace std;
/*
객체지향 3원칙
1. 정보은닉 : 데이터에 접근할 수있는 권한을 확인한다.
접근지정(제어)자 : 캡슐화
- private : 클래스 외부의 접근은 모두 차단
- protected :
- public : 외부에 공개하는 데이터
2. 상속성
3. 다형성
*/
int main(void) {
myNode * n1 = new myNode(10); // default Constructor
myNode * n2 = new myNode(20);
myNode* n3 = new myNode(30);
myNode* n4 = new myNode(40);
myNode n5 = myNode(11);
n1->setNext(n2);
n2->setNext(n3);
n3->setNext(n4);
myNode* cursor = nullptr;
cursor = n1;
cout << cursor->getData() << endl;
cursor = cursor->getNext();
cout << cursor->getData() << endl;
cursor = cursor->getNext();
cout << cursor->getData() << endl;
cursor = cursor->getNext();
cout << cursor->getData() << endl;
return 0;
}
|
//****************************************************************************
//
// Copyright (C) 1997-2007 3DV SYSTEMS LTD.
// All rights reserved.
//
// Module Name: DepthCamera.cpp
// Date: 1-9-2007
// Description: Implementation file for CDepthCamera class, which uses
// the DMachine SDK to control the camera.
// Updated By:
// Last Updated:
// Version: 1.00
//****************************************************************************
#include "DepthCamera.h"
#include "tdvcamerainterface.h"
// video callback function
void videoCallBack(unsigned char * pDepthBuf, unsigned char * pRgbBuf,
int bufIndex, void* pObject)
{
CDepthCamera *pDepthCamera = (CDepthCamera*)pObject;
if (!pDepthCamera)
return;
TDVCameraInterfaceBase *pCamera = pDepthCamera->GetCameraInterface();
if (!pCamera)
return;
unsigned char* pRGBFullRes = NULL;
unsigned char* pPrimary = NULL;
unsigned char* pSecondary = NULL;
if (pDepthCamera->IsRGBFullResolutionEnabled())
pCamera->getVideoBuffer(BUFFER_TYPE_RGB_FULL_RES, pRGBFullRes);
if (pDepthCamera->IsIRVideoTransferEnabled())
{
pCamera->getVideoBuffer(BUFFER_TYPE_PRIMARY, pPrimary);
pCamera->getVideoBuffer(BUFFER_TYPE_SECONDARY, pSecondary);
}
// there might be a small delay between the request for full res RGB\IR and the actual
// time the transfer is started. Let's skip frames not synced
if (pDepthCamera->IsRGBFullResolutionEnabled() && !pRGBFullRes)
return;
if (pDepthCamera->IsIRVideoTransferEnabled() && (!pPrimary || !pSecondary))
return;
pDepthCamera->SetFrames(pDepthBuf, pRgbBuf, pRGBFullRes, pPrimary, pSecondary);
}
// Command callback function
void cmdCallBack(int cmd, void* pObject)
{
/*
we only receive command if they value parameter is
different than currently set value
only when the main DMachine application sends a message, we can
be sure the value was set in the camera. for example, when turning on the
illumincation, only when CMD_ILLUMINCATION_ON is returned, the value
was set in the camera.
*/
CDepthCamera *pDepthCamera = (CDepthCamera*)pObject;
TDVCameraInterfaceBase *pCamera = pDepthCamera->GetCameraInterface();
// at first run, or when the resolution has changed, we need to
// re-initialize the videos that we want to be processed
if (cmd == CMD_CAMERA_RESOLUTION)
{
// might need to re-enable options that may have chenged to default after resolution change
pDepthCamera->EnableRGBFullResolution(pDepthCamera->IsRGBFullResolutionEnabled()?1:0);
pDepthCamera->EnableIRVideoTransfer(pDepthCamera->IsIRVideoTransferEnabled()?1:0);
pDepthCamera->EnableWideDepthMode(pDepthCamera->IsWideDepthModeEnabled()?true:false);
}
}
CDepthCamera::CDepthCamera(void)
{
m_pCameraInterfaceBase = NULL;
m_bEnableRGBFullResoltion = false;
m_bEnableIRVideoTransfer = false;
m_bEnableLargeDepthMode = false;
m_hNewFrameReady = 0;
m_hCriticalSection = 0;
m_pDepthFrame = NULL;
m_pRGBFrame = NULL;
m_pRGBFullResFrame = NULL;
m_pPrimary = NULL;
m_pSecondary = NULL;
m_bIsInitialized = false;
}
CDepthCamera::~CDepthCamera(void)
{
if (m_bIsInitialized)
{
EnableRGBFullResolution(false); // save on processing time...
UnInitialize();
}
}
// initialize the TDVCameraInterfaceBase object, and the callbacks
// in case the camera is not connected or DMachine is not running,
// it will wait the specified time until returning, to prevent program blocking.
// by default, it will wait indefinitely
bool CDepthCamera::Initialize(int timeout)
{
if (m_bIsInitialized) // already initialized
return true;
m_bEnableRGBFullResoltion = false;
m_pDepthFrame = m_pRGBFrame = m_pRGBFullResFrame = NULL;
m_hCriticalSection = CreateEvent(NULL, false, true, NULL);
m_hNewFrameReady = CreateEvent(NULL, false, false, NULL);
m_pCameraInterfaceBase = new TDVCameraInterfaceBase();
m_pCameraInterfaceBase->setCommandCallBack(cmdCallBack, this);
m_pCameraInterfaceBase->setVideoCallBack(videoCallBack, this);
int waitTime = timeout;
const int waitResolution = 20; // wait in constant quantities, to save processing
// wait for camera to get initialized
// by gaecha
// infinite check
while (!m_pCameraInterfaceBase->isCommActive() && waitTime != 0)
{
if (waitTime != INFINITE && waitTime > 0)
{
Sleep(waitResolution);
waitTime -= waitResolution;
if (waitTime < 0)
waitTime = 0;
}
}
if (waitTime == 0) // timeout occured
{
UnInitialize();
return false;
}
while (!m_pCameraInterfaceBase->isVideoActive() && waitTime != 0)
{
if (waitTime != INFINITE && waitTime > 0)
{
Sleep(waitResolution);
waitTime -= waitResolution;
if (waitTime < 0)
waitTime = 0;
}
}
if (waitTime == 0) // timeout occured
{
UnInitialize();
return false;
}
// camera is now ready for use. Lets set some default values
m_pCameraInterfaceBase->setCameraCommand(CMD_PROCESSING_MODE, 1); // make sure we are in depth mode...
m_pCameraInterfaceBase->setCameraCommand(CMD_ILLUMINATION_ON, 1); // make sure ilumination is on
m_pCameraInterfaceBase->setCameraCommand(CMD_AUTO_DEPTH_POSITION, 1);
m_pCameraInterfaceBase->setCameraCommand(CMD_MEDIAN, 1);
m_pCameraInterfaceBase->setCameraCommand(CMD_TEMPORAL_FILTER, 0);
SetDepthWindowPosition(100, 160);
m_bIsInitialized = true;
return true;
}
// uninitialize all internal objects.
void CDepthCamera::UnInitialize()
{
if (m_pCameraInterfaceBase)
{
delete m_pCameraInterfaceBase;
m_pCameraInterfaceBase = NULL;
}
if (m_hCriticalSection)
{
CloseHandle(m_hCriticalSection);
m_hCriticalSection = 0;
}
if (m_hNewFrameReady)
{
CloseHandle(m_hNewFrameReady);
m_hNewFrameReady = 0;
}
m_bIsInitialized = false;
}
// currently the supported resolutions are:
// - RESOLUTION_320X240_30FPS
// - RESOLUTION_160X120_60FPS
// this function blocks until the resolution has been changed.
void CDepthCamera::ChangeResolution(int resolutionMode)
{
int resolusion = 0;
m_pCameraInterfaceBase->getCameraCommandVal(CMD_CAMERA_RESOLUTION, resolusion);
if (resolusion == resolutionMode)
{ // nothing to change - resolution already valid
return;
}
if (resolutionMode == RESOLUTION_320X240_30FPS || resolutionMode == RESOLUTION_160X120_60FPS)
{
m_pCameraInterfaceBase->setCameraCommand(CMD_CAMERA_RESOLUTION, resolutionMode);
}
// wait until new resolusion is set
while (resolusion != resolutionMode)
m_pCameraInterfaceBase->getCameraCommandVal(CMD_CAMERA_RESOLUTION, resolusion);
// make sure all the videos and comm are valid again
while (!m_pCameraInterfaceBase->isCommActive())
{
Sleep(500);
}
while (!m_pCameraInterfaceBase->isVideoActive())
{
Sleep(500);
}
}
// get video frame parameters.
bool CDepthCamera::GetVideoSize(int& width, int& height,
int& rgbFullResWidth, int& rgbFullResHeight,
int& depthPixelSize, int& rgbPixelSize) const
{
if (!m_pCameraInterfaceBase->isVideoActive())
return false;
m_pCameraInterfaceBase->getVideoSize(width, height, rgbPixelSize, depthPixelSize);
m_pCameraInterfaceBase->getRGBFullResSize(rgbFullResWidth, rgbFullResHeight, rgbPixelSize);
return true;
}
// returns the maximal width possible for setting depth range, measured in centemeters
int CDepthCamera::GetMaxAllowedWidth() const
{
int min, max;
m_pCameraInterfaceBase->getCameraCommandLimits(CMD_PRIMARY_WIDTH, min, max);
return max;
}
// set the depth range manually. This function chooses default settings
// that will best fit the distance\width specified
// the depth range will be between distance and distance+width, measured in centemeters
void CDepthCamera::SetDepthWindowPosition(int distance, int width)
{
if (IsWideDepthModeEnabled())
width = GetMaxAllowedWidth();
m_pCameraInterfaceBase->setCameraCommand(CMD_AUTO_BRIGHTNESS, 0);
m_pCameraInterfaceBase->setCameraCommand(CMD_PRIMARY_DISTANCE, distance);
if (!m_bEnableLargeDepthMode) // in large depth mode the width is fixed to 300cm
m_pCameraInterfaceBase->setCameraCommand(CMD_PRIMARY_WIDTH, width);
// here we set default values for other settings when using this specified width
int resolution;
m_pCameraInterfaceBase->getCameraCommandVal(CMD_CAMERA_RESOLUTION, resolution);
int gain=0;
int clean=2;
int minBrightness;
int maxBrightness;
m_pCameraInterfaceBase->getCameraCommandLimits(CMD_PRIMARY_BRIGHTNESS, minBrightness, maxBrightness);
int primaryBrightness = maxBrightness;
int secondaryBrightness = maxBrightness;
int maxGain;
int minGain;
m_pCameraInterfaceBase->getCameraCommandLimits(CMD_GAIN, minGain, maxGain);
// assume we want not to saturate the video at the close range
if (distance < 60)
{
primaryBrightness = int(0.5+.75*maxBrightness);
}
else if (distance < 100)
{
}
else if (distance < 150)
{
gain = int(0.4*maxGain);
clean = 3;
if (m_bEnableLargeDepthMode)
{
gain = int(0.6*maxGain);
}
}
else if (distance < 200)
{
gain = int(0.5*maxGain);
clean = 4;
}
else
{
gain = maxGain;
clean = 4;
}
switch (resolution)
{
case RESOLUTION_320X240_30FPS:
break;
case RESOLUTION_160X120_60FPS:
if (distance < 200 && !m_bEnableLargeDepthMode)
{
gain -= 40;
if (gain < minGain)
{
primaryBrightness = int(0.6*primaryBrightness);
gain = minGain;
}
}
clean += 1;
break;
default:
break;
}
m_pCameraInterfaceBase->setCameraCommand(CMD_GAIN, gain);
m_pCameraInterfaceBase->setCameraCommand(CMD_CLEAN_VAL, clean);
m_pCameraInterfaceBase->setCameraCommand(CMD_PRIMARY_BRIGHTNESS, primaryBrightness);
m_pCameraInterfaceBase->setCameraCommand(CMD_SECONDARY_BRIGHTNESS, secondaryBrightness);
}
// get the depth range distance\width
// the depth range will be between distance and distance+width, measured in centemeters
void CDepthCamera::GetDepthWindowPosition(int &distance, int &width) const
{
m_pCameraInterfaceBase->getCameraCommandVal(CMD_PRIMARY_WIDTH, width);
m_pCameraInterfaceBase->getCameraCommandVal(CMD_PRIMARY_DISTANCE, distance);
}
// set the width specified, and positions the depth window
// around the closest object to the camera
// the function blocks until object is found
void CDepthCamera::FindObjectUsingWidth(int depthWidth)
{
m_pCameraInterfaceBase->setCameraCommand(CMD_PRIMARY_WIDTH, depthWidth);
m_pCameraInterfaceBase->setCameraCommand(CMD_AUTO_FIND, 1);
int value = 0;
// wait for object to be found
while (value==0)
{
Sleep(100);
m_pCameraInterfaceBase->getCameraCommandVal(CMD_AUTO_FIND_COMPLETED, value);
}
int distance;
m_pCameraInterfaceBase->getCameraCommandVal(CMD_PRIMARY_DISTANCE, distance);
SetDepthWindowPosition(distance, depthWidth); // set default settings for the found range
}
// enable\disable the transfer of RGB in 640x480 resolution.
// When enabled, this consumes more CPU
void CDepthCamera::EnableRGBFullResolution(bool enable)
{
m_bEnableRGBFullResoltion = enable;
m_pCameraInterfaceBase->setCameraCommand(CMD_RGB_FULL_RES, m_bEnableRGBFullResoltion?1:0);
}
// check whether the RGB in full resolution is also transfered
bool CDepthCamera::IsRGBFullResolutionEnabled() const
{
return m_bEnableRGBFullResoltion;
}
// enable\disable the transfer of IR Video (Primary and secondary IR).
// When enabled, this consumes more CPU
void CDepthCamera::EnableIRVideoTransfer(bool enable)
{
m_bEnableIRVideoTransfer = enable;
m_pCameraInterfaceBase->setCameraCommand(CMD_USING_IR_INPUT, m_bEnableIRVideoTransfer?1:0);
}
// check whether the IR video (primary and secondary) is also transfered
bool CDepthCamera::IsIRVideoTransferEnabled() const
{
return m_bEnableIRVideoTransfer;
}
// when the user needs a 300cm depth window range, enable this mode.
// It will automatically place the depth range to support depth range starting
// from 100cm and ending at 400cm (distance from the camera).
void CDepthCamera::EnableWideDepthMode(bool enable)
{
m_bEnableLargeDepthMode = enable;
m_pCameraInterfaceBase->setCameraCommand(CMD_WIDE_DEPTH_MODE, m_bEnableLargeDepthMode?1:0);
// set proper window settings for the wide depth mode
SetDepthWindowPosition(100, GetMaxAllowedWidth());
}
// is the large depth mode enabled?
bool CDepthCamera::IsWideDepthModeEnabled() const
{
return m_bEnableLargeDepthMode;
}
// enable\disable the "smooth" filter. also set the filter's intensity
void CDepthCamera::EnableDepthFilter(bool enable, int intensity)
{
m_pCameraInterfaceBase->setCameraCommand(CMD_SMOOTH, enable?1:0);
m_pCameraInterfaceBase->setCameraCommand(CMD_TEMPORAL_FILTER, enable?1:0);
int min, max;
m_pCameraInterfaceBase->getCameraCommandLimits(CMD_SOFTNESS_VAL, min, max);
if (intensity > max) // make sure we do not set higher than allowed intensity value
intensity = max;
m_pCameraInterfaceBase->setCameraCommand(CMD_SOFTNESS_VAL, intensity);
}
// check if the depth filter is enabled, and if so, what is it's intensity
bool CDepthCamera::IsDepthFilterEnabled() const
{
int iEnable;
m_pCameraInterfaceBase->getCameraCommandVal(CMD_SMOOTH, iEnable);
return iEnable?true:false;
}
// returns the next frames data. If RGB full resolution is not enabled,
// the pRGBFullResFrame will be NULL.
// This function will block until the next frame is ready, or until timeout
// is reached. If timeout occurs, the function returns false, otherwize true.
bool CDepthCamera::GetNextFrame(unsigned char* &pDepthFrame,
unsigned char* &pRGBFrame,
unsigned char* &pRGBFullResFrame,
unsigned char* &pPrimary,
unsigned char* &pSecondary,
int timeout)
{
if (WaitForSingleObject(m_hNewFrameReady, timeout) == WAIT_OBJECT_0)
{
// lock critical section while returning the frames, to make sure
// RGB and depth are synced
if (Lock())
{
pDepthFrame = m_pDepthFrame;
pRGBFrame = m_pRGBFrame;
pRGBFullResFrame = m_pRGBFullResFrame;
pPrimary = m_pPrimary;
pSecondary = m_pSecondary;
Unlock();
return true;
}
}
return false;
}
// when you wish to get full control over other parameters, you can get the
// internal TDVCameraInterfaceBase object and handle things by yourself
TDVCameraInterfaceBase* CDepthCamera::GetCameraInterface()
{
return m_pCameraInterfaceBase;
}
void CDepthCamera::SetFrames(unsigned char* pDepthFrame,
unsigned char* pRGBFrame,
unsigned char* pRGBFullResFrame,
unsigned char* pPrimary,
unsigned char* pSecondary)
{
if (Lock())
{
m_pDepthFrame = pDepthFrame;
m_pRGBFrame = pRGBFrame;
m_pRGBFullResFrame = pRGBFullResFrame;
m_pPrimary = pPrimary;
m_pSecondary = pSecondary;
Unlock();
// signal that a new frame is ready
SetEvent(m_hNewFrameReady);
}
}
bool CDepthCamera::Lock()
{
if (WaitForSingleObject(m_hCriticalSection, INFINITE) == WAIT_OBJECT_0)
return true;
return false;
}
void CDepthCamera::Unlock()
{
SetEvent(m_hCriticalSection);
}
void CDepthCamera::EnableTrack(bool enable)
{
m_pCameraInterfaceBase->setCameraCommand(CMD_AUTO_TRACK, enable);
}
void CDepthCamera::EnableSmoothing(bool enable, double smoothVal)
{
m_pCameraInterfaceBase->setCameraCommand(CMD_SMOOTH, enable);
m_pCameraInterfaceBase->setCameraCommand(CMD_SOFTNESS_VAL, (int)smoothVal);
}
void CDepthCamera::SetCleanVal(double cleanVal)
{
m_pCameraInterfaceBase->setCameraCommand(CMD_CLEAN_VAL, (int)cleanVal);
}
void CDepthCamera::EnableMedian(bool enable)
{
m_pCameraInterfaceBase->setCameraCommand(CMD_MEDIAN, enable);
}
void CDepthCamera::FreezeVideo(bool freeze)
{
m_pCameraInterfaceBase->setCameraCommand(CMD_FREEZE_VIDEO, freeze);
}
|
#include<cstdio>
#include<cstring>
#define MAXN 10010
using namespace std;
/*
函数extend[i] = |T与T(i,m)的最长公共前缀|,这里2<=i<=m。
函数Bi = |T与S(i,n)的最长公共前缀|,这里1<=i<=n。
*/
struct ExtKmp{ //start from 1
const char *t, *s;
int *b;
int extend[MAXN];
int m,n;
void cal(char *_t, int _m, char *_s, int _n, int *_b) //len_t = m
{
t = _t;
n = _n;
s = _s;
m = _m;
b = _b;
count_extend();
count_b();
}
void count_extend()
{
int j=0,len,l,k;
while(j<=m-2&&t[1+j]==t[2+j]) ++j;
extend[1]=m;
extend[2]=j;
k=2;
for(int i=3;i<=m;++i)
{
len=k+extend[k]-1;
l=extend[i-k+1];
if(l<len-i+1) extend[i]=l;
else{
j=max(0,len-i+1);
while(i+j<=m&&t[1+j]==t[i+j]) ++j;
extend[i]=j;
k=i;
}
}
}
void count_b()
{
int j=0,len,l,k;
while(j<m&&t[1+j]==s[1+j]) ++j;
b[1]=j;
k=1;
for(int i=2;i<=n;++i)
{
len=k+b[k]-1;
l=extend[i-k+1];
if(l<len-i+1) b[i]=l;
else {
j=max(0,len-i+1);
while(j<m&&i+j<=n&&t[1+j]==s[i+j]) ++j;
b[i]=j;
k=i;
}
}
}
};
|
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <queue>
#include <set>
using namespace std;
struct ListNode{
int val;
ListNode* next;
ListNode(int x):val(x),next(NULL){}
};
void printLL(ListNode* head){
ListNode* temp = head;
while(temp!=NULL){
cout<<temp->val<<"->";
temp = temp->next;
}
}
ListNode* addNode(ListNode* head, int val){
if(head==NULL){
head = new ListNode(val);
}
else{
ListNode* temp = head;
while(temp->next!=NULL){
temp = temp->next;
}
temp->next = new ListNode(val);
}
return head;
}ListNode* partition(ListNode* A, int B){
int l =0;
vector<int> v1,v2;
ListNode* t = A;
while(t!=NULL){
if(t->val<B){
v1.push_back(t->val);
}
else{
v2.push_back(t->val);
}
t = t->next;
l++;
}
ListNode* head = (ListNode*)malloc(sizeof(ListNode)); ;
ListNode* curr = head;
if(v1.size()&&v2.size()){
head->val = v1[0];
for(int i =1;i<v1.size();i++){
ListNode* temp = (ListNode*)malloc(sizeof(ListNode));
temp->val = v1[i];
curr->next = temp;
curr = temp;
}
for(int i =0;i<v2.size();i++){
ListNode* temp = (ListNode*)malloc(sizeof(ListNode));
temp->val = v2[i];
curr->next = temp;
curr = temp;
}
curr->next = NULL;
}
else if(v1.size()==0&&v2.size()!=0){
head->val = v2[0];
for(int i =1;i<v2.size();i++){
ListNode* temp = (ListNode*)malloc(sizeof(ListNode));
temp->val = v2[i];
curr->next = temp;
curr = temp;
}
curr->next = NULL;
}
return head;
}
int main(){
ListNode *head = NULL;
// = new ListNode();
int n,x;
cin>>n>>x;
for(int i =0;i<n;i++){
int val;
cin>>val;
head = addNode(head,val);
}
// printLL(head);
head = partition(head,x);
printLL(head);
}
|
/*
* The Deploy Implementation
* Nana C++ Library(http://www.nanapro.org)
* Copyright(C) 2003-2016 Jinhao(cnjinhao@hotmail.com)
*
* 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)
*
* @file: _/Deploy.hpp
*
* What follow are dependented on what defined in _/Config.h
*/
#pragma once
#include <_/Config.h>
#if defined(VERBOSE_PREPROCESSOR)
#include <_/VerbosePreprocessor.h>
#endif
#include <stdexcept>
#include <_/CharSet.h>
//Implement workarounds for GCC/MinGW which version is below 4.8.2
#if defined(STD_NUMERIC_CONVERSIONS_NOT_SUPPORTED)
namespace std
{
//Workaround for no implemenation of std::stoi in MinGW.
int stoi(const std::string&, std::size_t * pos = nullptr, int base = 10);
int stoi(const std::wstring&, std::size_t* pos = nullptr, int base = 10);
//Workaround for no implemenation of std::stof in MinGW.
float stof(const std::string&, std::size_t * pos = nullptr);
float stof(const std::wstring&, std::size_t* pos = nullptr);
//Workaround for no implemenation of std::stod in MinGW.
double stod(const std::string&, std::size_t * pos = nullptr);
double stod(const std::wstring&, std::size_t* pos = nullptr);
//Workaround for no implemenation of std::stold in MinGW.
long double stold(const std::string&, std::size_t * pos = nullptr);
long double stold(const std::wstring&, std::size_t* pos = nullptr);
//Workaround for no implemenation of std::stol in MinGW.
long stol(const std::string&, std::size_t* pos = nullptr, int base = 10);
long stol(const std::wstring&, std::size_t* pos = nullptr, int base = 10);
//Workaround for no implemenation of std::stoll in MinGW.
long long stoll(const std::string&, std::size_t* pos = nullptr, int base = 10);
long long stoll(const std::wstring&, std::size_t* pos = nullptr, int base = 10);
//Workaround for no implemenation of std::stoul in MinGW.
unsigned long stoul(const std::string&, std::size_t* pos = nullptr, int base = 10);
unsigned long stoul(const std::wstring&, std::size_t* pos = nullptr, int base = 10);
//Workaround for no implemenation of std::stoull in MinGW.
unsigned long long stoull(const std::string&, std::size_t* pos = nullptr, int base = 10);
unsigned long long stoull(const std::wstring&, std::size_t* pos = nullptr, int base = 10);
}
#endif //STD_NUMERIC_CONVERSIONS_NOT_SUPPORTED
#ifdef STD_TO_STRING_NOT_SUPPORTED
namespace std
{
//Workaround for no implemenation of std::to_string/std::to_wstring in MinGW.
std::string to_string(long double);
std::string to_string(double);
std::string to_string(unsigned);
std::string to_string(int);
std::string to_string(long);
std::string to_string(unsigned long);
std::string to_string(long long);
std::string to_string(unsigned long long);
std::string to_string(float);
}
#endif
#ifdef STD_TO_WSTRING_NOT_SUPPORTED
namespace std
{
std::wstring to_wstring(long double);
std::wstring to_wstring(double);
std::wstring to_wstring(unsigned);
std::wstring to_wstring(int);
std::wstring to_wstring(long);
std::wstring to_wstring(unsigned long);
std::wstring to_wstring(long long);
std::wstring to_wstring(unsigned long long);
std::wstring to_wstring(float);
}
#endif
namespace _ {
/// Checks whether a specified text is UTF8 encoding
bool is_UTF8 (const char* str, unsigned len);
void throw_not_UTF8 (const std::string& text);
void throw_not_UTF8 (const char*, unsigned len);
void throw_not_UTF8 (const char*);
const std::string& to_UTF8 (const std::string&);
std::string to_UTF8 (const std::wstring&);
std::wstring to_wstring (const std::string& UTF8_str);
const std::wstring& to_wstring (const std::wstring& wstr);
std::wstring&& to_wstring (std::wstring&& wstr);
#if defined(NANA_WINDOWS)
std::string to_osmbstr (const std::string& text_UTF8);
#else
std::string to_osmbstr(std::string text_UTF8);
#endif
#if defined(NANA_WINDOWS)
using native_string_type = std::wstring;
#else //POSIX
using native_string_type = std::string;
#endif
}
#if defined(NANA_WINDOWS)
const native_string_type to_nstring (const std::string&);
const native_string_type& to_nstring (const std::wstring&);
native_string_type to_nstring (std::string&&);
native_string_type&& to_nstring (std::wstring&&);
#else //POSIX
const native_string_type& to_nstring(const std::string&);
const native_string_type to_nstring(const std::wstring&);
native_string_type&& to_nstring(std::string&&);
native_string_type to_nstring(std::wstring&&);
#endif
native_string_type to_nstring (int);
native_string_type to_nstring (double);
native_string_type to_nstring (std::size_t);
}
namespace _ {
inline unsigned make_rgb (unsigned char red, unsigned char green, unsigned char blue)
{
return ((unsigned (red) << 16) | ((unsigned (green) << 8)) | blue);
}
}
#define NANA_RGB(a) (((DWORD)(a) & 0xFF)<<16) | ((DWORD)(a) & 0xFF00) | (((DWORD)(a) & 0xFF0000) >> 16 )
#ifdef STD_MAKE_UNIQUE_NOT_SUPPORTED
// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3656.htm
#include <cstddef>
#include <memory>
#include <type_traits>
#include <utility>
namespace std {
template<class T> struct _Unique_if {
typedef unique_ptr<T> _Single_object;
};
template<class T> struct _Unique_if<T[]> {
typedef unique_ptr<T[]> _Unknown_bound;
};
template<class T, size_t N> struct _Unique_if<T[N]> {
typedef void _Known_bound;
};
template<class T, class... Args>
typename _Unique_if<T>::_Single_object
make_unique(Args&&... args) {
return unique_ptr<T>(new T(std::forward<Args>(args)...));
}
template<class T>
typename _Unique_if<T>::_Unknown_bound
make_unique(size_t n) {
typedef typename remove_extent<T>::type U;
return unique_ptr<T>(new U[n]());
}
template<class T, class... Args>
typename _Unique_if<T>::_Known_bound
make_unique(Args&&...) = delete;
}
#endif //STD_make_unique_NOT_SUPPORTED
|
#include <cmath> //for log, sqrt and erf
#include <iostream>
#include "EuropeanOption.h"
#include "MarketData.h"
#include "Payoff.h"
#include "Pricer.h"
class SimpleMarketData : public MarketData{
double discountFactorTo(double time) const override {
double rate = 0.03;
return exp(-rate*time);
}
double equityPrice() const override {return 100;}
double equityVolatility() const override {return 0.2;}
};
void printResults(const Results& r){
std::cout<<"Price: "<<r.m_price<<", SD: "<<r.m_standardDeviation
<<", Delta: "<<r.m_delta<<", Gamma: "<<r.m_gamma<<"\n";
}
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
SimpleMarketData m;
EuropeanOption call(false, 102.,0.2);
EuropeanOption put(true, 102,0.2);
Pricer p(10000);
std::cout<<"Call:\n";
std::cout<<"Analytic:\n";
printResults(call.analyticPrice(m));
std::cout<<"Monte Carlo:\n";
printResults(p.go(m,call));
std::cout<<"\nPut:\n";
std::cout<<"Analytic:\n";
printResults(put.analyticPrice(m));
std::cout<<"Monte Carlo:\n";
printResults(p.go(m,put));
return 0;
}
|
#pragma once
/*
* Lanq(Lan Quick)
* Solodov A. N. (hotSAN)
* 2016
* LqIpRaw - .
*/
#include "LqOs.h"
#include "LqPtdArr.hpp"
#include "LqSbuf.h"
#pragma pack(push)
#pragma pack(1)
template<typename NumT, bool ByteOrderBigEndiean>
class LqByteOrderNum {
NumT val;
public:
typedef NumT Type;
operator NumT() const {
NumT v;
if(ByteOrderBigEndiean) {
for(intptr_t i = 0; i < sizeof(NumT); i++)
v = (v << 8) | ((uint8_t*)&val)[i];
} else {
for(intptr_t i = sizeof(NumT) - 1; i >= 0; i--)
v = (v << 8) | ((uint8_t*)&val)[i];
}
return v;
}
NumT operator=(NumT n) {
NumT v = n;
if(ByteOrderBigEndiean) {
for(intptr_t i = sizeof(NumT) - 1; i >= 0; i--, v >>= 8)
((uint8_t*)&val)[i] = v & 0xff;
} else {
for(intptr_t i = 0; i < sizeof(NumT); i++, v >>= 8)
((uint8_t*)&val)[i] = v & 0xff;
}
return n;
}
};
template<typename NumT, size_t BitOff, size_t BitLen>
class LqBitField {
NumT val;
static const NumT Filt1 = (NumT(-1) >> BitOff) & (NumT(-1) << ((sizeof(NumT) * 8) - (BitOff + BitLen)));
static const NumT Filt2 = ~Filt1;
static const NumT ShrB = (sizeof(NumT) * 8) - (BitOff + BitLen);
public:
operator NumT() { return (val & Filt1) >> ShrB; }
NumT operator=(NumT n) { val = (val & Filt2) | (Filt1 & (n << ShrB)); return n; }
};
template<typename T, bool ByteOrderBigEndiean, size_t BitOff, size_t BitLen>
class LqBitField<LqByteOrderNum<T, ByteOrderBigEndiean>, BitOff, BitLen> {
LqByteOrderNum<T, ByteOrderBigEndiean> val;
static const T Filt1 = (T(-1) >> BitOff) & (T(-1) << ((sizeof(T) * 8) - (BitOff + BitLen)));
static const T Filt2 = ~Filt1;
static const T ShrB = (sizeof(T) * 8) - (BitOff + BitLen);
public:
operator T() { return (val & Filt1) >> ShrB; }
T operator=(T n) { val = (val & Filt2) | (Filt1 & (n << ShrB)); return n; }
};
/* This is POD structures !*/
struct ipheader {
union {
LqBitField<LqByteOrderNum<uint8_t, true>, 0, 4> version;
LqBitField<LqByteOrderNum<uint8_t, true>, 4, 4> ihl;
};
union {
LqBitField<LqByteOrderNum<uint8_t, true>, 0, 6> dscp;
LqBitField<LqByteOrderNum<uint8_t, true>, 6, 2> ecn;
};
LqByteOrderNum<uint16_t, true> len;
LqByteOrderNum<uint16_t, true> id;
union {
LqBitField<LqByteOrderNum<uint16_t, true>, 0, 1> reserv;
LqBitField<LqByteOrderNum<uint16_t, true>, 1, 1> nofr;
LqBitField<LqByteOrderNum<uint16_t, true>, 2, 1> hasfr;
LqBitField<LqByteOrderNum<uint16_t, true>, 3, 13> offset;
};
uint8_t ttl;
uint8_t protocol;
LqByteOrderNum<uint16_t, true> check;
LqByteOrderNum<uint32_t, true> saddr;
LqByteOrderNum<uint32_t, true> daddr;
int ToString(char* DestBuf, size_t DestBufSize) {
return LqFbuf_snprintf(
DestBuf,
DestBufSize,
"version: %u\n"
"hdr_len: %u\n"
"dscp: %u\n"
"ecn: %u\n"
"len: %u\n"
"id: %u\n"
"flags: nofr=%u, hasfr=%u\n"
"offset: %u\n"
"ttl: %u\n"
"protocol: %u\n"
"check: %u\n"
"saddr: %u.%u.%u.%u\n"
"daddr: %u.%u.%u.%u\n",
(unsigned)version,
(unsigned)ihl,
(unsigned)dscp,
(unsigned)ecn,
(unsigned)len,
(unsigned)id,
(unsigned)nofr,
(unsigned)hasfr,
(unsigned)offset,
(unsigned)ttl,
(unsigned)protocol,
(unsigned)check,
(unsigned)(((uint8_t*)&saddr)[0]),
(unsigned)(((uint8_t*)&saddr)[1]),
(unsigned)(((uint8_t*)&saddr)[2]),
(unsigned)(((uint8_t*)&saddr)[3]),
(unsigned)(((uint8_t*)&daddr)[0]),
(unsigned)(((uint8_t*)&daddr)[1]),
(unsigned)(((uint8_t*)&daddr)[2]),
(unsigned)(((uint8_t*)&daddr)[3])
);
}
void ComputeChecksum() {
check = 0;
unsigned long sum = 0;
size_t count = ihl * 4;
uint16_t* addr = (uint16_t*)this;
for(sum = 0; count > 1; count -= 2)
sum += *addr++;
if(count == 1)
sum += (char)*addr;
sum = (sum >> 16) + (sum & 0xFFFF);
sum += (sum >> 16);
*(uint16_t*)&check = ~sum;
}
};
struct tcphdr {
LqByteOrderNum<uint16_t, true> source;
LqByteOrderNum<uint16_t, true> dest;
LqByteOrderNum<uint32_t, true> seq;
LqByteOrderNum<uint32_t, true> ack_seq;
union {
LqBitField<LqByteOrderNum<uint16_t, true>, 0, 4> thl;
LqBitField<LqByteOrderNum<uint16_t, true>, 4, 3> res1;
LqBitField<LqByteOrderNum<uint16_t, true>, 7, 1> ns;
LqBitField<LqByteOrderNum<uint16_t, true>, 8, 1> cwr;
LqBitField<LqByteOrderNum<uint16_t, true>, 9, 1> ece;
LqBitField<LqByteOrderNum<uint16_t, true>, 10, 1> urg;
LqBitField<LqByteOrderNum<uint16_t, true>, 11, 1> ack;
LqBitField<LqByteOrderNum<uint16_t, true>, 12, 1> psh;
LqBitField<LqByteOrderNum<uint16_t, true>, 13, 1> rst;
LqBitField<LqByteOrderNum<uint16_t, true>, 14, 1> syn;
LqBitField<LqByteOrderNum<uint16_t, true>, 15, 1> fin;
};
LqByteOrderNum<uint16_t, true> window;
LqByteOrderNum<uint16_t, true> check;
LqByteOrderNum<uint16_t, true> urg_ptr;
int ToString(char* DestBuf, size_t DestBufSize) {
return LqFbuf_snprintf(
DestBuf,
DestBufSize,
"source: %u\n"
"dest: %u\n"
"seq: %u\n"
"ack_seq: %u\n"
"thl: %u\n"
"res1: %u\n"
"flags: cwr=%u, ece=%u, urg=%u, ack=%u, psh=%u, rst=%u, syn=%u, fin=%u\n"
"window: %u\n"
"check: %u\n"
"urg_ptr: %u\n",
(unsigned)source,
(unsigned)dest,
(unsigned)seq,
(unsigned)ack_seq,
(unsigned)thl,
(unsigned)res1,
(unsigned)cwr,
(unsigned)ece,
(unsigned)urg,
(unsigned)ack,
(unsigned)psh,
(unsigned)rst,
(unsigned)syn,
(unsigned)fin,
(unsigned)window,
(unsigned)check,
(unsigned)urg_ptr
);
}
void ComputeChecksum(ipheader *iph, size_t DataLen = 0, void* Data = nullptr) {
const uint16_t *buf = (uint16_t*)this;
uint32_t sum = 0;
int len = thl * 4;
*(uint16_t*)&check = 0;
for(; len > 1; len -= 2)
sum += *(buf++);
if(Data == nullptr) {
len = DataLen;
for(; len > 1; len -= 2)
sum += *(buf++);
} else {
if(len == 1)
sum += *((uint8_t *)(buf++));
len = DataLen;
buf = (uint16_t*)Data;
for(; len > 1; len -= 2)
sum += *(buf++);
}
if(len == 1)
sum += *((uint8_t *)buf);
sum += (*((uint32_t*)&iph->saddr) >> 16) & 0xffff;
sum += (*((uint32_t*)&iph->saddr) & 0xffff);
sum += (*((uint32_t*)&iph->daddr) >> 16) & 0xffff;
sum += (*((uint32_t*)&iph->daddr) & 0xffff);
sum += htons(iph->protocol);
sum += htons(thl * 4 + DataLen);
while(sum >> 16)
sum = (sum & 0xFFFF) + (sum >> 16);
*(uint16_t*)&check = (uint16_t)(~sum);
}
void ComputeChecksum(size_t DataLen = 0, void* Data = nullptr) {
const uint16_t *buf = (uint16_t*)this;
uint32_t sum = 0;
int len = thl * 4;
*(uint16_t*)&check = 0;
for(; len > 1; len -= 2)
sum += *(buf++);
len = DataLen;
if(Data == nullptr) {
for(; len > 1; len -= 2)
sum += *(buf++);
} else {
if(len == 1)
sum += *((uint8_t *)(buf++));
buf = (uint16_t*)Data;
for(; len > 1; len -= 2)
sum += *(buf++);
}
if(len == 1)
sum += *((uint8_t *)buf);
sum += htons(thl * 4 + DataLen);
while(sum >> 16)
sum = (sum & 0xFFFF) + (sum >> 16);
*(uint16_t*)&check = (uint16_t)(~sum);
}
};
struct udphdr {
LqByteOrderNum<uint16_t, true> source;
LqByteOrderNum<uint16_t, true> dest;
LqByteOrderNum<uint16_t, true> len;
LqByteOrderNum<uint16_t, true> check;
int ToString(char* DestBuf, size_t DestBufSize) {
return LqFbuf_snprintf(
DestBuf,
DestBufSize,
"source: %u\n"
"dest: %u\n"
"len: %u\n"
"check: %u\n",
(unsigned)source,
(unsigned)dest,
(unsigned)len,
(unsigned)check
);
}
void ComputeChecksum(ipheader *iph, size_t DataLen = 0, void* Data = nullptr) {
const uint16_t *buf = (uint16_t*)this;
uint32_t sum = 0;
int len = sizeof(udphdr);
*(uint16_t*)&check = 0;
for(; len > 1; len -= 2)
sum += *(buf++);
if(Data == nullptr) {
len = DataLen;
for(; len > 1; len -= 2)
sum += *(buf++);
} else {
if(len == 1)
sum += *((uint8_t *)(buf++));
len = DataLen;
buf = (uint16_t*)Data;
for(; len > 1; len -= 2)
sum += *(buf++);
}
if(len == 1)
sum += *((uint8_t *)buf);
sum += (*((uint32_t*)&iph->saddr) >> 16) & 0xffff;
sum += (*((uint32_t*)&iph->saddr) & 0xffff);
sum += (*((uint32_t*)&iph->daddr) >> 16) & 0xffff;
sum += (*((uint32_t*)&iph->daddr) & 0xffff);
sum += htons(iph->protocol);
sum += htons(sizeof(udphdr) + DataLen);
while(sum >> 16)
sum = (sum & 0xFFFF) + (sum >> 16);
*(uint16_t*)&check = (uint16_t)(~sum);
}
void ComputeChecksum(size_t DataLen = 0, void* Data = nullptr) {
const uint16_t *buf = (uint16_t*)this;
uint32_t sum = 0;
int len = sizeof(udphdr);
*(uint16_t*)&check = 0;
for(; len > 1; len -= 2)
sum += *(buf++);
len = DataLen;
if(Data == nullptr) {
for(; len > 1; len -= 2)
sum += *(buf++);
} else {
if(len == 1)
sum += *((uint8_t *)(buf++));
buf = (uint16_t*)Data;
for(; len > 1; len -= 2)
sum += *(buf++);
}
if(len == 1)
sum += *((uint8_t *)buf);
sum += htons(sizeof(udphdr) + DataLen);
while(sum >> 16)
sum = (sum & 0xFFFF) + (sum >> 16);
*(uint16_t*)&check = (uint16_t)(~sum);
}
};
struct icmphdr {
uint8_t type;
uint8_t code;
LqByteOrderNum<uint16_t, true> check;
struct {
LqByteOrderNum<uint16_t, true> id;
LqByteOrderNum<uint16_t, true> seq;
char data[1];
} echo;
void ComputeChecksum(size_t CommonLen) {
*(uint16_t*)&check = 0;
int sum = 0;
size_t count = CommonLen;
uint16_t* addr = (uint16_t*)this;
for(sum = 0; count > 1; count -= 2)
sum += *addr++;
if(count == 1)
sum += (char)*addr;
sum = (sum >> 16) + (sum & 0xFFFF);
sum += (sum >> 16);
*(uint16_t*)&check = ~sum;
}
};
#pragma pack(pop)
|
#include <math.h>
#include "GameInfo.h"
#include "glut.h"
#include "Bullet.h"
#include "Player.h"
#include "MouseClicked.h"
MouseClicked* Bullet::getmouse()
{
return MouseClicked::Instance();
}
void Bullet::drawBullet()
{
//마우스 좌측 버튼 클릭시
if (getmouse()->getisShot())
{
isShotStart = true;
shotPowerZ = 0;
shotPowerX = 0;
isShotEnd = false;
}
else
{
isShotStart = false;
}
if (isShotStart)
{
int val = (int)Player::Instance()->getYaw() % 360; //yaw 360 나머지
saveYaw = Player::Instance()->getYaw(); //isShotStart일 때 yaw 저장
val < 0 ? val *= -1 : val; //양의 정수 만들어주기
// printf("%d\n", val);
if ((val >= 0 && val <= 90) || (val >= 270 && val <= 360)) //shotPowerZ가 양수가 되는 부분
isbiggerZ = true;
else
isbiggerZ = false; //shotPowerZ가 음수가 되는 부분
if ((val >= 0 && val <= 180)) //shotPowerX가 양수가 되는 부분
isbiggerX = true;
else
isbiggerX = false; //shotPowerX가 음수가 되는 부분
isShotEnd = true;
}
if (isShotEnd)
{
if (isbiggerZ)
{
shotPowerZ += sin((saveYaw + 90) * TO_RADIANS);;
}
else
{
shotPowerZ += sin((saveYaw + 90) * TO_RADIANS);;
}
if (isbiggerX)
{
shotPowerX -= cos((saveYaw + 90) * TO_RADIANS);
}
else
{
shotPowerX -= cos((saveYaw + 90) * TO_RADIANS);
}
}
glPushMatrix();
glMatrixMode(GL_MODELVIEW); //모델뷰 행렬 스택
glTranslatef(Player::Instance()->getcamX() - shotPowerX, //총알 그리기
Player::Instance()->getcamY() + (Player::Instance()->getPlayerPitch() / 200),
Player::Instance()->getcamZ() - shotPowerZ);
glutWireSphere(0.05f, 50.0f, 50.0f);
glPopMatrix();
}
|
#include <iostream>
#include <cstring>
using namespace std;
long long arr[21];
long long check[21];
long long a,b,count=0;
void dfs(long long t,long long total){
if(total==b-arr[0]){
count++;
}
for(long long i=t;i<a;i++){
if(check[i]) continue;
check[i]=1;
dfs(i,total+arr[i]);
check[i]=0;
}
}
int main(){
cin>>a>>b;
for(int i=0;i<a;i++){
cin>>arr[i];
}
dfs(1,0);
cout<<count;
}
|
#pragma once
#include "GameNode.h"
// 에너미 부모 클래스
#define FIRECOUNT 1000
enum Direction {
DIRECTION_LEFT,
DIRECTION_RIGHT,
DIRECTION_DOWN,
};
class Enemy : public GameNode
{
private:
Image * _image;
RECT _rc;
POINT _pos;
float _speed;
// 프레임 이미지를 돌리기 위한 변수
int _count;
int _currentFrameX;
int _currentFrameY;
// 계속해서 주기적으로 증가
int _fireCount;
// 랜덤한 값을 가지고 있다가 fireCount가 쌓이게 되면 발사하는 형식으로
int _rndFireCount;
POINT _initPos;
bool _isLive;
public:
Enemy();
~Enemy();
virtual HRESULT Init();
virtual HRESULT Init(const char* imageName, POINT position);
virtual void Release();
virtual void Update();
virtual void Render();
virtual void Move(Direction dir);
virtual void Draw();
virtual void Animation();
bool BulletCountFire();
bool CheckCollision(Direction dir);
void SetPosition(POINT pos);
RECT GetRect() { return _rc; }
};
|
#include "SomeOfEverything.h"
#include "PxPhysicsAPI.h"
#include "NvBounds3.h"
#include <vector>
#include <stdint.h>
#include <stdlib.h>
#include <math.h>
#pragma warning(disable:4100)
#define NUMBER_OF_MATERIALS 2
#define NUMBER_OF_SHAPES 2
typedef std::vector< physx::PxMaterial *> MaterialVector;
typedef std::vector< physx::PxShape *> ShapeVector;
typedef std::vector< physx::PxConvexMesh *> ConvexMeshVector;
typedef std::vector< physx::PxTriangleMesh * > TriangleMeshVector;
typedef std::vector< physx::PxRigidStatic *> RigidStaticVector;
typedef std::vector< physx::PxRigidDynamic *> RigidDynamicVector;
typedef std::vector< physx::PxHeightField *> HeightFieldVector;
typedef std::vector< physx::PxJoint *> JointVector;
typedef std::vector< physx::PxArticulation *> ArticulationVector;
typedef std::vector< physx::PxArticulationLink * > ArticulationLinkVector;
using namespace physx;
namespace SOME_OF_EVERYTHING
{
// All of the different joint types
enum JointType
{
JT_FIXED,
JT_REVOLUTE,
JT_PRISMATIC,
JT_SPHERICAL,
JT_D6,
JT_DISTANCE,
JT_ARTICULATION,
JT_LAST
};
#define HEIGHT_FIELD_SIZE 16
// Mesh: 32 vertices 64 triangles
#define VERTEX_COUNT 32
#define TRIANGLE_COUNT 64
float gVertices[VERTEX_COUNT * 3] = {
-0.200678006,-6.840312958,6.840312958,
-0.200678006,-4.724764824,6.840312958,
-0.200678006,-4.724764824,4.439278126,
-0.200678006,-0.649251997,2.597712994,
-0.200678006,-0.649251997,-2.021457911,
-0.200678006,5.880214214,-2.021457911,
-0.200678006,6.840312958,-6.840312958,
-0.200678006,1.902750969,-6.840312958,
-0.200678006,1.902750969,-3.969496965,
-0.200678006,-4.626715183,-3.969496965,
-0.200678006,-4.626715183,-6.840312958,
-0.200678006,-6.840312958,-6.840312958,
-0.200678006,6.840312958,6.840312958,
-0.200678006,5.880214214,2.597712994,
-0.200678006,1.804700971,4.439278126,
-0.200678006,1.804700971,6.840312958,
0.200678006,-6.840312958,-6.840312958,
0.200678006,-6.840312958,6.840312958,
0.200678006,-4.724764824,6.840312958,
0.200678006,1.804700971,6.840312958,
0.200678006,6.840312958,6.840312958,
0.200678006,6.840312958,-6.840312958,
0.200678006,1.902750969,-6.840312958,
0.200678006,-4.626715183,-6.840312958,
0.200678006,1.804700971,4.439278126,
0.200678006,-4.724764824,4.439278126,
0.200678006,-0.649251997,2.597712994,
0.200678006,5.880214214,2.597712994,
0.200678006,5.880214214,-2.021457911,
0.200678006,-4.626715183,-3.969496965,
0.200678006,1.902750969,-3.969496965,
0.200678006,-0.649251997,-2.021457911,
};
uint32_t gIndices[TRIANGLE_COUNT * 3] = {
4,8,9,
12,13,14,
16,0,11,
18,0,17,
20,15,19,
6,20,21,
6,22,7,
10,16,11,
20,24,27,
16,29,17,
29,8,30,
7,30,8,
23,9,29,
2,24,14,
19,14,24,
1,25,2,
4,28,5,
27,5,28,
3,31,4,
26,13,27,
11,0,9,
2,3,4,
0,1,2,
9,10,11,
6,7,8,
9,0,2,
5,6,8,
9,2,4,
4,5,8,
12,6,5,
13,3,14,
12,5,13,
14,15,12,
3,2,14,
16,17,0,
18,1,0,
20,12,15,
6,12,20,
6,21,22,
10,23,16,
20,19,24,
24,25,26,
27,28,20,
24,26,27,
28,21,20,
18,17,25,
16,23,29,
30,22,21,
30,21,28,
31,26,25,
30,28,31,
29,30,31,
25,17,29,
29,31,25,
29,9,8,
7,22,30,
23,10,9,
2,25,24,
19,15,14,
1,18,25,
4,31,28,
27,13,5,
3,26,31,
26,3,13,
};
static float ranf(void)
{
uint32_t v = rand();
return float(v) / float(RAND_MAX);
}
class SomeOfEverythingImpl : public SomeOfEverything
{
public:
SomeOfEverythingImpl(physx::PxPhysics *physics, physx::PxCooking *cooking,physx::PxScene *scene) : mScene(scene), mPhysics(physics),mCooking(cooking)
{
for (uint32_t y = 0; y < HEIGHT_FIELD_SIZE; y++)
{
for (uint32_t x = 0; x < HEIGHT_FIELD_SIZE; x++)
{
mHeightFieldData[y*HEIGHT_FIELD_SIZE + x] = x;
}
}
for (uint32_t i = 0; i < NUMBER_OF_MATERIALS; i++)
{
float staticFriction = ranf();
float dynamicFriction = ranf();
float restitution = ranf();
physx::PxMaterial *m = physics->createMaterial(staticFriction, dynamicFriction, restitution);
mMaterials.push_back(m);
}
for (uint32_t i = 0; i < NUMBER_OF_SHAPES; i++)
{
physx::PxMaterial *m = getRandomMaterial();
// Create a box shape
{
physx::PxVec3 dimensions;
dimensions.x = ranf();
dimensions.y = ranf();
dimensions.z = ranf();
physx::PxBoxGeometry box(dimensions);
physx::PxShape *s = physics->createShape(box, *m);
s->setName("@boxShape");
mShapes.push_back(s);
}
// Create a sphere shape
{
physx::PxSphereGeometry sphere(ranf());
physx::PxShape *s = physics->createShape(sphere, *m);
s->setName("@sphereShape");
mShapes.push_back(s);
}
// Create a capsule shape
{
physx::PxCapsuleGeometry capsule(ranf(), ranf());
physx::PxShape *s = physics->createShape(capsule, *m);
s->setName("@capsuleShape");
mShapes.push_back(s);
}
// Create convex hull and convex hull shape
{
#define HULL_POINTS 16
physx::PxVec3 points[HULL_POINTS];
// Create a random point cloud for the convex hull
for (auto &j : points)
{
j.x = ranf();
j.y = ranf();
j.z = ranf();
}
physx::PxConvexMeshDesc desc;
desc.points.data = points;
desc.points.count = HULL_POINTS;
desc.points.stride = sizeof(float) * 3;
desc.flags = physx::PxConvexFlag::eCOMPUTE_CONVEX;
physx::PxConvexMesh *c = mCooking->createConvexMesh(desc, mPhysics->getPhysicsInsertionCallback());
mConvexMeshes.push_back(c);
float scale = ranf() + 1.0f;
physx::PxVec3 sc(scale, scale, scale);
physx::PxConvexMeshGeometry convex(c,sc);
physx::PxShape *s = physics->createShape(convex, *m);
s->setName("@convexShape");
mShapes.push_back(s);
}
// Create triangle mesh and triangle mesh shape
{
physx::PxTriangleMeshDesc desc;
desc.points.data = gVertices;
desc.points.count = VERTEX_COUNT;
desc.points.stride = sizeof(float) * 3;
desc.triangles.data = gIndices;
desc.triangles.count = TRIANGLE_COUNT;
desc.triangles.stride = sizeof(uint32_t) * 3;
if (mMaterialIndices == nullptr)
{
mMaterialIndices = new uint16_t[TRIANGLE_COUNT];
for (uint32_t j = 0; j < TRIANGLE_COUNT; j++)
{
mMaterialIndices[j] = j & 3;
}
}
desc.materialIndices.data = mMaterialIndices;
desc.materialIndices.stride = sizeof(uint16_t);
physx::PxTriangleMesh *mesh = mCooking->createTriangleMesh(desc, mPhysics->getPhysicsInsertionCallback());
mTriangleMeshes.push_back(mesh);
float scale = ranf() + 1.0f;
physx::PxVec3 sc(scale, scale, scale);
physx::PxTriangleMeshGeometry tmesh(mesh, physx::PxMeshScale(sc));
physx::PxShape *s = physics->createShape(tmesh, *m);
s->setName("@triangleShape");
mShapes.push_back(s);
}
}
{
physx::PxMaterial *m = getRandomMaterial();
physx::PxHeightFieldDesc desc;
desc.samples.data = mHeightFieldData;
desc.samples.stride = sizeof(uint32_t);
desc.nbRows = HEIGHT_FIELD_SIZE;
desc.nbColumns = HEIGHT_FIELD_SIZE;
physx::PxHeightField *hf = mCooking->createHeightField(desc, mPhysics->getPhysicsInsertionCallback());
mHeightFields.push_back(hf);
float scale = ranf() + 1.0f;
physx::PxHeightFieldGeometry hfg(hf, physx::PxMeshGeometryFlag::eDOUBLE_SIDED, scale, scale, scale);
physx::PxShape *s = physics->createShape(hfg, *m);
s->setName("@heightFieldShape");
mShapes.push_back(s);
}
for (auto &i : mShapes)
{
physx::PxTransform t(physx::PxIdentity);
t.p.x = ranf() * 10 - 5;
t.p.z = ranf() * 10 - 5;
physx::PxRigidStatic *rd = physx::PxCreateStatic(*mPhysics, t, *i);
if (rd)
{
rd->setName("@rigidStatic");
mScene->addActor(*rd);
mRigidStatics.push_back(rd);
}
}
for (auto &i : mShapes)
{
bool isValid = false;
switch (i->getGeometryType())
{
case physx::PxGeometryType::eBOX:
case physx::PxGeometryType::eSPHERE:
case physx::PxGeometryType::eCONVEXMESH:
case physx::PxGeometryType::eCAPSULE:
isValid = true;
break;
}
if (isValid)
{
physx::PxTransform t(physx::PxIdentity);
t.p.x = ranf() * 10 - 5;
t.p.z = ranf() * 10 - 5;
t.p.y = ranf() * 4 + 1.0f;
physx::PxRigidDynamic *rd = physx::PxCreateDynamic(*mPhysics, t, *i, 1.0f);
if (rd)
{
rd->setName("@rigidDynamic");
if ((rand() & 3) == 0)
{
uint32_t index = rand() % mShapes.size();
physx::PxShape *s = mShapes[index];
switch (s->getGeometryType())
{
case physx::PxGeometryType::eBOX:
case physx::PxGeometryType::eSPHERE:
case physx::PxGeometryType::eCONVEXMESH:
case physx::PxGeometryType::eCAPSULE:
rd->attachShape(*s);
break;
}
}
mScene->addActor(*rd);
mRigidDynamics.push_back(rd);
}
}
}
mAggregate = mPhysics->createAggregate(32, true);
for (auto &i : mShapes)
{
bool isValid = false;
switch (i->getGeometryType())
{
case physx::PxGeometryType::eBOX:
case physx::PxGeometryType::eSPHERE:
case physx::PxGeometryType::eCONVEXMESH:
case physx::PxGeometryType::eCAPSULE:
isValid = true;
break;
}
if (isValid)
{
physx::PxTransform t(physx::PxIdentity);
t.p.x = ranf() * 10 - 5;
t.p.z = ranf() * 10 - 5;
t.p.y = ranf() * 4 + 1.0f;
physx::PxRigidDynamic *rd = physx::PxCreateDynamic(*mPhysics, t, *i, 1.0f);
if (rd)
{
rd->setName("@rigidDynamic");
if ((rand() & 3) == 0)
{
uint32_t index = rand() % mShapes.size();
physx::PxShape *s = mShapes[index];
switch (s->getGeometryType())
{
case physx::PxGeometryType::eBOX:
case physx::PxGeometryType::eSPHERE:
case physx::PxGeometryType::eCONVEXMESH:
case physx::PxGeometryType::eCAPSULE:
rd->attachShape(*s);
break;
}
}
mAggregate->addActor(*rd);
mRigidDynamics.push_back(rd);
}
}
}
{
PxArticulation *a = mPhysics->createArticulation();
physx::PxTransform linkPose(physx::PxIdentity);
PxArticulationLink* link = a->createLink(nullptr, linkPose);
physx::PxMaterial *m = getRandomMaterial();
PxSphereGeometry sphere(1.0f);
PxRigidActorExt::createExclusiveShape(*link, sphere, *m);
PxRigidBodyExt::updateMassAndInertia(*link, 1.0f);
{
PxArticulationLink* childLink = a->createLink(link, linkPose);
PxRigidActorExt::createExclusiveShape(*childLink, sphere, *m);
PxRigidBodyExt::updateMassAndInertia(*childLink, 1.0f);
}
mAggregate->addArticulation(*a);
mArticulations.push_back(a);
}
mScene->addAggregate(*mAggregate);
{
PxArticulation *a = mPhysics->createArticulation();
mScene->addArticulation(*a);
mArticulations.push_back(a);
}
createJoint(JT_FIXED);
createJoint(JT_D6);
createJoint(JT_SPHERICAL);
createJoint(JT_DISTANCE);
createJoint(JT_REVOLUTE);
createJoint(JT_PRISMATIC);
}
physx::PxMaterial *getRandomMaterial(void) const
{
uint32_t index = rand() % mMaterials.size();
return mMaterials[index];
}
virtual ~SomeOfEverythingImpl(void)
{
for (auto &i : mArticulationLinks)
{
i->release();
}
for (auto &i : mArticulations)
{
i->release();
}
for (auto &i : mJoints)
{
i->release();
}
for (auto &i : mRigidStatics)
{
i->release();
}
for (auto &i : mRigidDynamics)
{
i->release();
}
if (mAggregate)
{
mAggregate->release();
}
for (auto &i : mMaterials)
{
i->release();
}
for (auto &i : mShapes)
{
i->release();
}
for (auto &i : mConvexMeshes)
{
i->release();
}
for (auto &i : mTriangleMeshes)
{
i->release();
}
for (auto &i : mHeightFields)
{
i->release();
}
delete[]mMaterialIndices;
}
virtual void release(void) final
{
delete this;
}
PxRigidDynamic *findActor(PxRigidDynamic *exclude)
{
PxRigidDynamic *ret = nullptr;
for (;;)
{
uint32_t index = rand() % mRigidDynamics.size();
ret = mRigidDynamics[index];
if (ret != exclude)
{
break;
}
}
return ret;
}
void createJoint(JointType type)
{
PxRigidDynamic *a1 = findActor(nullptr);
PxRigidDynamic *a2 = findActor(a1);
physx::PxTransform t = a1->getGlobalPose();
float worldPos[3];
float worldOrientation[4];
worldPos[0] = t.p.x;
worldPos[1] = t.p.y;
worldPos[2] = t.p.z;
worldOrientation[0] = t.q.x;
worldOrientation[1] = t.q.y;
worldOrientation[2] = t.q.z;
worldOrientation[3] = t.q.w;
createConstraint(a1, a2, worldPos, worldOrientation, type, ranf(), 5, 15, 15);
}
// Prismatic Joint
PxJoint* createPrismaticJoint(PxRigidActor* a0, const PxTransform& t0, PxRigidActor* a1, const PxTransform& t1)
{
PxPrismaticJoint* j = PxPrismaticJointCreate(*mPhysics, a0, t0, a1, t1);
j->setConstraintFlag(PxConstraintFlag::eVISUALIZATION, true); // enable visualization!!
j->setConstraintFlag(PxConstraintFlag::eDISABLE_PREPROCESSING, true);
j->setName("@prismaticJoint");
return j;
}
// Distance Joint
PxJoint* createDistanceJoint(PxRigidActor* a0, const PxTransform& t0, PxRigidActor* a1, const PxTransform& t1)
{
PxDistanceJoint* j = PxDistanceJointCreate(*mPhysics, a0, t0, a1, t1);
j->setConstraintFlag(PxConstraintFlag::eVISUALIZATION, true); // enable visualization!!
j->setConstraintFlag(PxConstraintFlag::eDISABLE_PREPROCESSING, true);
j->setName("@prismaticJoint");
return j;
}
// Revolute Joint
PxJoint* createRevoluteJoint(PxRigidActor* a0, const PxTransform& t0, PxRigidActor* a1, const PxTransform& t1)
{
PxRevoluteJoint* j = PxRevoluteJointCreate(*mPhysics, a0, t0, a1, t1);
j->setConstraintFlag(PxConstraintFlag::eVISUALIZATION, true); // enable visualization!!
j->setConstraintFlag(PxConstraintFlag::eDISABLE_PREPROCESSING, true);
j->setName("@prismaticJoint");
return j;
}
// fixed joint
PxJoint* createFixedJoint(PxRigidActor* a0, const PxTransform& t0, PxRigidActor* a1, const PxTransform& t1)
{
PxFixedJoint* j = PxFixedJointCreate(*mPhysics, a0, t0, a1, t1);
j->setConstraintFlag(PxConstraintFlag::eVISUALIZATION, true); // enable visualization!!
j->setConstraintFlag(PxConstraintFlag::eDISABLE_PREPROCESSING, true);
j->setName("@fixedJoint");
return j;
}
// spherical joint limited to an angle of at most pi/4 radians (45 degrees)
PxJoint* createLimitedSpherical(PxRigidActor* a0, const PxTransform& t0, PxRigidActor* a1, const PxTransform& t1, uint32_t swing1Limit, uint32_t swing2Limit)
{
PxSphericalJoint* j = PxSphericalJointCreate(*mPhysics, a0, t0, a1, t1);
float lrange1 = (PxPi * 2) * (float(swing1Limit) / 360.0f);
float lrange2 = (PxPi * 2) * (float(swing2Limit) / 360.0f);
j->setLimitCone(PxJointLimitCone(lrange1, lrange2));
j->setSphericalJointFlag(PxSphericalJointFlag::eLIMIT_ENABLED, true);
j->setConstraintFlag(PxConstraintFlag::eVISUALIZATION, true); // enable visualization!!
j->setConstraintFlag(PxConstraintFlag::eDISABLE_PREPROCESSING, true);
j->setName("@sphericalJoint");
return j;
}
// D6 joint with a spring maintaining its position
PxJoint* createHingeJoint(PxRigidActor* a0, const PxTransform& t0, PxRigidActor* a1, const PxTransform& t1, uint32_t limitRangeDegrees)
{
PxD6Joint* j = PxD6JointCreate(*mPhysics, a0, t0, a1, t1);
j->setMotion(PxD6Axis::eSWING1, PxD6Motion::eLOCKED);
j->setMotion(PxD6Axis::eSWING2, PxD6Motion::eLOCKED);
j->setMotion(PxD6Axis::eTWIST, PxD6Motion::eLIMITED);
j->setConstraintFlag(PxConstraintFlag::eDISABLE_PREPROCESSING, true);
float lrange = (PxPi * 2) * (float(limitRangeDegrees) / 360.0f);
PxJointAngularLimitPair limit(-lrange, lrange);
j->setTwistLimit(limit);
j->setDrive(PxD6Drive::eSLERP, PxD6JointDrive(0, 1000, FLT_MAX, true));
j->setConstraintFlag(PxConstraintFlag::eVISUALIZATION, true); // enable visualization!!
j->setName("@hingJoint");
return j;
}
// Creates a fixed constraint between these two bodies
virtual void createConstraint(
PxRigidDynamic *a1,PxRigidDynamic *a2, const float worldPos[3], // World position of the constraint location
const float worldOrientation[4],
JointType type, // Type of constraint to use
float distanceLimit,
uint32_t twistLimit, // Twist limit in degrees (if used)
uint32_t swing1Limit, // Swing 1 limit in degrees (if used)
uint32_t swing2Limit) final // Swing 2 limit in degrees (if used)
{
{
PxTransform constraintWorld;
constraintWorld.p.x = worldPos[0];
constraintWorld.p.y = worldPos[1];
constraintWorld.p.z = worldPos[2];
constraintWorld.q.x = worldOrientation[0];
constraintWorld.q.y = worldOrientation[1];
constraintWorld.q.z = worldOrientation[2];
constraintWorld.q.w = worldOrientation[3];
PxTransform inverse1 = a1->getGlobalPose().getInverse();
PxTransform other1 = inverse1 * constraintWorld;
PxTransform inverse2 = a2->getGlobalPose().getInverse();
PxTransform other2 = inverse2 * constraintWorld;
PxJoint *joint = nullptr;
switch (type)
{
case JT_FIXED:
joint = createFixedJoint(a1, other1, a2, other2);
break;
case JT_D6:
joint = createHingeJoint(a1, other1, a2, other2, twistLimit);
break;
case JT_SPHERICAL:
joint = createLimitedSpherical(a1, other1, a2, other2, swing1Limit, swing2Limit);
break;
case JT_DISTANCE:
joint = createDistanceJoint(a1, other1, a2, other2);
break;
case JT_REVOLUTE:
joint = createRevoluteJoint(a1, other1, a2, other2);
break;
case JT_PRISMATIC:
joint = createPrismaticJoint(a1, other1, a2, other2);
break;
}
if (joint)
{
mJoints.push_back(joint);
}
}
}
physx::PxScene *mScene{ nullptr };
physx::PxPhysics *mPhysics{ nullptr };
physx::PxCooking *mCooking{ nullptr };
MaterialVector mMaterials;
ShapeVector mShapes;
ConvexMeshVector mConvexMeshes;
TriangleMeshVector mTriangleMeshes;
RigidStaticVector mRigidStatics;
RigidDynamicVector mRigidDynamics;
HeightFieldVector mHeightFields;
JointVector mJoints;
uint16_t *mMaterialIndices{ nullptr };
uint32_t mHeightFieldData[HEIGHT_FIELD_SIZE*HEIGHT_FIELD_SIZE];
PxAggregate *mAggregate{ nullptr };
ArticulationVector mArticulations;
ArticulationLinkVector mArticulationLinks;
};
SomeOfEverything *SomeOfEverything::create(physx::PxPhysics *physics, physx::PxCooking *cooking,physx::PxScene *scene)
{
SomeOfEverythingImpl *ret = new SomeOfEverythingImpl(physics, cooking,scene);
return static_cast<SomeOfEverything *>(ret);
}
}
|
#include "CppUnitTest.h"
#include "CppUnitTestAssert.h"
#include "../3XD_Lib/geometry/computus.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace Z_3D_LIB_FOR_EGE;
namespace My3D_Lib_for_ege_UnitTest
{
TEST_CLASS(_computus_test)
{
typedef _affine_vector DOT;
typedef _line LINE;
typedef _plane PLANE;
public:
TEST_METHOD(computus_parallel) {
Assert::IsTrue(computus::parallel({ 1.0, 2.0, 3.0, 0 }, { 10.0, 20.0, 30.0, 0 }));
LINE l1({ 34, -5, 0.02, 1 }, { 3.0, 4.0, 6.0, 0 });
LINE l2({ 223, -5, 23, 1 }, { 3.8411063979868792102277324929963, 5.1214751973158389469703099906617, 7.6822127959737584204554649859926, 0 });
Assert::IsTrue(computus::parallel(l1, l2));
}
TEST_METHOD(computus_dist) {
// distances for point-to-point
Assert::AreEqual(5.1961524227066318805823390245176, computus::dist({ 0, 1, 2, 1 }, { 3, 4, 5, 1 }));
// distances for point-to-line
DOT d{ 23, 4, 55, 1 };
LINE l1({ -34, -5, 23, 1 }, { -6, 3, 24, 0 });
Assert::AreEqual(63.431464783951519, computus::dist(d, l1));
// distances for line-to-line
LINE l2({ 1, 2, 3, 1 }, { -3, 5, 22, 0 });
LINE l3({ -5, -23, -9, 1 }, { -32, 4, 213, 0 });
Assert::AreEqual(6.0720091322390459, computus::dist(l2, l3));
// distances for point-to-plane whether both parallel or not;
DOT d1{ 23, 4, 55, 1 };
PLANE p({ -24, 5, -2, 1 }, { 5, 2, -15, 0 });
Assert::AreEqual(45.047397520698730, computus::dist(d1, p));
}
};
}
|
/*
* Copyright 2016 Freeman Zhang <zhanggyb@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "xdg-toplevel-meta.hpp"
#include <skland/wayland/xdg-toplevel.hpp>
#include <skland/core/numeric.hpp>
namespace skland {
namespace wayland {
const struct zxdg_toplevel_v6_listener XdgToplevelMeta::kListener = {
OnConfigure,
OnClose
};
void XdgToplevelMeta::OnConfigure(void *data,
struct zxdg_toplevel_v6 * /* zxdg_toplevel_v6 */,
int32_t width,
int32_t height,
struct wl_array *states) {
XdgToplevel *_this = static_cast<XdgToplevel *>(data);
if (!_this->configure_) return;
void *p = nullptr;
int value = 0;
wl_array_for_each(p, states) {
uint32_t state = *((uint32_t *) p);
switch (state) {
case ZXDG_TOPLEVEL_V6_STATE_MAXIMIZED: {
Bit::Set<int>(value, XdgToplevel::kStateMaskMaximized);
break;
}
case ZXDG_TOPLEVEL_V6_STATE_FULLSCREEN: {
Bit::Set<int>(value, XdgToplevel::kStateMaskFullscreen);
break;
}
case ZXDG_TOPLEVEL_V6_STATE_RESIZING: {
Bit::Set<int>(value, XdgToplevel::kStateMaskResizing);
break;
}
case ZXDG_TOPLEVEL_V6_STATE_ACTIVATED: {
Bit::Set<int>(value, XdgToplevel::kStateMaskActivated);
break;
}
default:
/* Unknown state */
break;
}
}
_this->configure_(width, height, value);
}
void XdgToplevelMeta::OnClose(void *data, struct zxdg_toplevel_v6 * /* zxdg_toplevel_v6 */) {
XdgToplevel *_this = static_cast<XdgToplevel *>(data);
if (_this->close_)
_this->close_();
}
}
}
|
#include <string>
#include "../headers/FormalNode.hpp"
#include "../headers/ClassNode.hpp"
#include "../headers/AstNode.hpp"
using namespace std;
FormalNode::FormalNode() = default;
string FormalNode::getType() { return type; }
void FormalNode::setName(string name) {
this->name = name;
this->value = name;
}
void FormalNode::setType(string type) {
this->type = type;
}
void FormalNode::printTree() {
printf("%s : %s", name.c_str(), type.c_str());
}
string FormalNode::printCheck(ClassNode *classNode) {
if (!classNode->getAstNode()->isParentExist(this->type) and this->type != "int32" and this->type != "bool" and
this->type != "string" and this->type != "Object" and this->type != "IO" and this->type != "unit")
return "ErrorSemanticOneTime:" + to_string(this->nbLine - 2) + ":" + to_string(this->nbColumn + 3) +
": semantic error : use of undefined type " + this->type + ".";
if (this->name == "self")
return "ErrorSemanticOneTime:" + to_string(this->getNbLine() - 3) + ":" + to_string(this->getNbColumn() - 4) +
": semantic error : cannot use self as an argument name.";
classNode->getVariableTable()->addVariable(this->name, this->type);
string retString = this->name + " : " + this->type;
return retString;
}
|
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
void deleteNode(struct ListNode* node)
{
if (node->next->next != NULL)
{
node->next = node->next->next;
}
else if(node->next->next == NULL)
{
node->next = NULL;
}
else if(node->next == NULL)
{
node = NULL;
}
}
ListNode* deleteUnique(ListNode* head) {
bool bRepeat = false;
ListNode *curr1, *curr2, *prev;
prev = head;
curr1 = head;
curr2 = head;
if(head->next == NULL)
{
head = NULL;
return head;
}
while(curr1->next != NULL)
{
if(curr1->val != curr1->next->val && curr1 == head)
{
curr1 = curr1->next;
curr2 = curr1;
prev = curr1;
head = curr1;
}
if(curr1->next->next != NULL)
{
if(curr1->val != curr1->next->val && curr1->next->next->val != curr1->next->val )
{
curr1->next = curr1->next->next;
}
}
}
delete prev, curr1, curr2;
return head;
}
int main()
{
return 0;
}
|
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of Intel Corporation may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "test_precomp.hpp"
using namespace cv;
using namespace std;
CV_AMLTest::CV_AMLTest( const char* _modelName ) : CV_MLBaseTest( _modelName )
{
validationFN = "avalidation.xml";
}
int CV_AMLTest::run_test_case( int testCaseIdx )
{
CV_TRACE_FUNCTION();
int code = cvtest::TS::OK;
code = prepare_test_case( testCaseIdx );
if (code == cvtest::TS::OK)
{
//#define GET_STAT
#ifdef GET_STAT
const char* data_name = ((CvFileNode*)cvGetSeqElem( dataSetNames, testCaseIdx ))->data.str.ptr;
printf("%s, %s ", name, data_name);
const int icount = 100;
float res[icount];
for (int k = 0; k < icount; k++)
{
#endif
data->shuffleTrainTest();
code = train( testCaseIdx );
#ifdef GET_STAT
float case_result = get_error();
res[k] = case_result;
}
float mean = 0, sigma = 0;
for (int k = 0; k < icount; k++)
{
mean += res[k];
}
mean = mean /icount;
for (int k = 0; k < icount; k++)
{
sigma += (res[k] - mean)*(res[k] - mean);
}
sigma = sqrt(sigma/icount);
printf("%f, %f\n", mean, sigma);
#endif
}
return code;
}
int CV_AMLTest::validate_test_results( int testCaseIdx )
{
CV_TRACE_FUNCTION();
int iters;
float mean, sigma;
// read validation params
FileNode resultNode =
validationFS.getFirstTopLevelNode()["validation"][modelName][dataSetNames[testCaseIdx]]["result"];
resultNode["iter_count"] >> iters;
if ( iters > 0)
{
resultNode["mean"] >> mean;
resultNode["sigma"] >> sigma;
model->save(format("/Users/vp/tmp/dtree/testcase_%02d.cur.yml", testCaseIdx));
float curErr = get_test_error( testCaseIdx );
const int coeff = 4;
ts->printf( cvtest::TS::LOG, "Test case = %d; test error = %f; mean error = %f (diff=%f), %d*sigma = %f\n",
testCaseIdx, curErr, mean, abs( curErr - mean), coeff, coeff*sigma );
if ( abs( curErr - mean) > coeff*sigma )
{
ts->printf( cvtest::TS::LOG, "abs(%f - %f) > %f - OUT OF RANGE!\n", curErr, mean, coeff*sigma, coeff );
return cvtest::TS::FAIL_BAD_ACCURACY;
}
else
ts->printf( cvtest::TS::LOG, ".\n" );
}
else
{
ts->printf( cvtest::TS::LOG, "validation info is not suitable" );
return cvtest::TS::FAIL_INVALID_TEST_DATA;
}
return cvtest::TS::OK;
}
TEST(ML_DTree, regression) { CV_AMLTest test( CV_DTREE ); test.safe_run(); }
TEST(ML_Boost, regression) { CV_AMLTest test( CV_BOOST ); test.safe_run(); }
TEST(ML_RTrees, regression) { CV_AMLTest test( CV_RTREES ); test.safe_run(); }
TEST(DISABLED_ML_ERTrees, regression) { CV_AMLTest test( CV_ERTREES ); test.safe_run(); }
TEST(ML_NBAYES, regression_5911)
{
int N=12;
Ptr<ml::NormalBayesClassifier> nb = cv::ml::NormalBayesClassifier::create();
// data:
Mat_<float> X(N,4);
X << 1,2,3,4, 1,2,3,4, 1,2,3,4, 1,2,3,4,
5,5,5,5, 5,5,5,5, 5,5,5,5, 5,5,5,5,
4,3,2,1, 4,3,2,1, 4,3,2,1, 4,3,2,1;
// labels:
Mat_<int> Y(N,1);
Y << 0,0,0,0, 1,1,1,1, 2,2,2,2;
nb->train(X, ml::ROW_SAMPLE, Y);
// single prediction:
Mat R1,P1;
for (int i=0; i<N; i++)
{
Mat r,p;
nb->predictProb(X.row(i), r, p);
R1.push_back(r);
P1.push_back(p);
}
// bulk prediction (continuous memory):
Mat R2,P2;
nb->predictProb(X, R2, P2);
EXPECT_EQ(sum(R1 == R2)[0], 255 * R2.total());
EXPECT_EQ(sum(P1 == P2)[0], 255 * P2.total());
// bulk prediction, with non-continuous memory storage
Mat R3_(N, 1+1, CV_32S),
P3_(N, 3+1, CV_32F);
nb->predictProb(X, R3_.col(0), P3_.colRange(0,3));
Mat R3 = R3_.col(0).clone(),
P3 = P3_.colRange(0,3).clone();
EXPECT_EQ(sum(R1 == R3)[0], 255 * R3.total());
EXPECT_EQ(sum(P1 == P3)[0], 255 * P3.total());
}
TEST(ML_RTrees, getVotes)
{
int n = 12;
int count, i;
int label_size = 3;
int predicted_class = 0;
int max_votes = -1;
int val;
// RTrees for classification
Ptr<ml::RTrees> rt = cv::ml::RTrees::create();
//data
Mat data(n, 4, CV_32F);
randu(data, 0, 10);
//labels
Mat labels = (Mat_<int>(n,1) << 0,0,0,0, 1,1,1,1, 2,2,2,2);
rt->train(data, ml::ROW_SAMPLE, labels);
//run function
Mat test(1, 4, CV_32F);
Mat result;
randu(test, 0, 10);
rt->getVotes(test, result, 0);
//count vote amount and find highest vote
count = 0;
const int* result_row = result.ptr<int>(1);
for( i = 0; i < label_size; i++ )
{
val = result_row[i];
//predicted_class = max_votes < val? i;
if( max_votes < val )
{
max_votes = val;
predicted_class = i;
}
count += val;
}
EXPECT_EQ(count, (int)rt->getRoots().size());
EXPECT_EQ(result.at<float>(0, predicted_class), rt->predict(test));
}
/* End of file. */
|
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <list>
#include <algorithm>
#include <sstream>
#include <set>
#include <cmath>
#include <map>
#include <stack>
#include <queue>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <numeric>
#include <bitset>
#include <deque>
const long long LINF = (5e18);
const int INF = (1<<30);
#define EPS 1e-6
const int MOD = 1000000007;
using namespace std;
class LampsGrid {
public:
int count(string &s) {
int res = 0;
for (char ch : s)
if (ch == '0')
++res;
return res;
}
int mostLit(vector <string> initial, int K) {
map<string, int> m;
for (string s : initial)
m[s]++;
int ans = 0;
for (pair<string, int> p : m) {
int c = K - count(p.first);
if (c >= 0 && (c&1)==0 ) {
ans = max(ans, p.second);
}
}
return ans;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { string Arr0[] = {"01",
"10",
"10"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; int Arg2 = 2; verify_case(0, Arg2, mostLit(Arg0, Arg1)); }
void test_case_1() { string Arr0[] = {"101010"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2; int Arg2 = 0; verify_case(1, Arg2, mostLit(Arg0, Arg1)); }
void test_case_2() { string Arr0[] = {"00", "11"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 999; int Arg2 = 0; verify_case(2, Arg2, mostLit(Arg0, Arg1)); }
void test_case_3() { string Arr0[] = {"0", "1", "0", "1", "0"}
; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1000; int Arg2 = 2; verify_case(3, Arg2, mostLit(Arg0, Arg1)); }
void test_case_4() { string Arr0[] = {
"001",
"101",
"001",
"000",
"111",
"001",
"101",
"111",
"110",
"000",
"111",
"010",
"110",
"001"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 6; int Arg2 = 4; verify_case(4, Arg2, mostLit(Arg0, Arg1)); }
void test_case_5() { string Arr0[] = {"01", "10", "01", "01", "10"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; int Arg2 = 3; verify_case(5, Arg2, mostLit(Arg0, Arg1)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main() {
LampsGrid ___test;
___test.run_test(-1);
}
// END CUT HERE
|
#include "ast_node.h"
#include "parser.hpp"
#include <iostream>
#include <map>
#include <list>
extern AST_Expression *root;
extern int yyparse();
// Maps identifier-names to a list of nodes where they occur.
typedef std::map<std::string, std::list<AST_Identifier*> > IdMap;
// Maps identifier-names to boolean values, for evaluation.
typedef std::map<std::string, bool> ValueMap;
// Do a depth-first search for identifiers, adds them to the identifier map.
void find_identifiers(AST_Expression &exp, IdMap &idmap);
void find_identifiers(AST_BinaryExpression &exp, IdMap &idmap);
void find_identifiers(AST_UnaryExpression &exp, IdMap &idmap);
void find_identifiers(AST_Identifier &exp, IdMap &idmap);
// Evaluate a (sub-)expression given a map of boolean values for the identifiers.
bool evaluate(AST_Expression &exp, ValueMap &valmap);
bool evaluate(AST_BinaryExpression &exp, ValueMap &valmap);
bool evaluate(AST_UnaryExpression &exp, ValueMap &valmap);
bool evaluate(AST_Identifier &exp, ValueMap &valmap);
// Bind values to a valuemap.
ValueMap valmap_bind(IdMap &id, unsigned int code);
int main(int argc, char **argv)
{
IdMap idmap;
ValueMap valmap;
int permutations_size = 0;
// Call the parser
yyparse();
if (root == NULL) {
return 1;
}
// Find and print some information about identifiers
std::cout << root->prettyPrint() << std::endl;
find_identifiers(*root, idmap);
std::cout << "Found " << idmap.size() << " unique identifiers" << std::endl;
for (auto it = idmap.begin(); it != idmap.end(); ++it) {
std::cout << it->first << ": " << it->second.size() << " occurrences" << std::endl;
}
// Check how many boolean permutations we need to generate
if (idmap.size() <= 2) {
permutations_size = 2;
} else if (idmap.size() <= 4) {
permutations_size = 4;
} else {
std::cout << "More than 4 identifiers not supported yet." << std::endl;
return 2;
}
std::cout << "Generating a lut" << permutations_size << "." << std::endl;
// Bind each possible permutation and evaluate the function
std::cout << "0";
for(unsigned int i = 0; i < permutations_size * permutations_size; ++i) {
valmap = valmap_bind(idmap, i);
std::cout << evaluate(*root, valmap);
}
std::cout << std::endl;
return 0;
}
void find_identifiers(AST_Expression &exp, IdMap &idmap) {
switch(exp.getType()) {
case AST_BEXP: find_identifiers((AST_BinaryExpression&)exp, idmap); break;
case AST_UEXP: find_identifiers((AST_UnaryExpression&)exp, idmap); break;
case AST_ID: find_identifiers((AST_Identifier&)exp, idmap); break;
default: std::cout << "Error?" << std::endl;
}
}
void find_identifiers(AST_BinaryExpression &exp, IdMap &idmap) {
find_identifiers(exp.lhs, idmap);
find_identifiers(exp.rhs, idmap);
}
void find_identifiers(AST_UnaryExpression &exp, IdMap &idmap) {
find_identifiers(exp.child, idmap);
}
void find_identifiers(AST_Identifier &exp, IdMap &idmap) {
idmap[exp.name].push_back(&exp);
}
bool evaluate(AST_Expression &exp, ValueMap &valmap) {
switch(exp.getType()) {
case AST_BEXP: return evaluate((AST_BinaryExpression&)exp, valmap);
case AST_UEXP: return evaluate((AST_UnaryExpression&)exp, valmap);
case AST_ID: return evaluate((AST_Identifier&)exp, valmap);
default: std::cout << "Error?" << std::endl;
}
return false;
}
bool evaluate(AST_BinaryExpression &exp, ValueMap &valmap) {
switch(exp.op) {
case TCEQ: return evaluate(exp.lhs, valmap) == evaluate(exp.rhs, valmap);
case TCNE: return evaluate(exp.lhs, valmap) != evaluate(exp.rhs, valmap);
case TCAND: return evaluate(exp.lhs, valmap) && evaluate(exp.rhs, valmap);
case TCOR: return evaluate(exp.lhs, valmap) || evaluate(exp.rhs, valmap);
default: std::cout << "Error?" << std::endl;
}
return false;
}
bool evaluate(AST_UnaryExpression &exp, ValueMap &valmap) {
switch(exp.op) {
case TCNOT: return !evaluate(exp.child, valmap);
default: std::cout << "Error?" << std::endl;
}
return false;
}
bool evaluate(AST_Identifier &exp, ValueMap &valmap) {
if (valmap.find(exp.name) != valmap.end()) {
return valmap[exp.name];
}
return false;
}
/**
* Bind an integer-coded representation to each identifier by using the binary representation.
* Some examples:
* 0 will bind all zero's
* 1 will bind 1 to the first.
* 3 will bind 1 to the first and second identifiers.
* etc.
*/
ValueMap valmap_bind(IdMap &id, unsigned int code) {
ValueMap valmap;
unsigned int mask = 1;
for (auto it = id.begin(); it != id.end(); ++it, mask <<= 1) {
valmap[it->first] = (code & mask) == mask;
}
return valmap;
}
|
//
// Created by tudom on 2019-12-28.
//
#ifdef _WIN32
# define DUMMY_API __declspec(dllexport)
# define DUMMY_LOCAL
#else
# define DUMMY_API __attribute__((visibility("default")))
# define DUMMY_LOCAL __attribute__((visibility("hidden")))
#endif
int DUMMY_API square(int i) {
return i * i;
}
void DUMMY_API param_sqr(int* ret, int i) {
*ret = square(i);
}
void DUMMY_LOCAL fix_all_the_worlds_problems(void*) {}
|
#include <ionir/passes/type_system/type_check_pass.h>
#include <ionir/misc/bootstrap.h>
#include <ionir/syntax/ast_builder.h>
#include <ionir/test/const.h>
#include "../pch.h"
using namespace ionir;
// TODO: Separate into multiple tests.
TEST(TypeCheckPassTest, Run) {
PassManager passManager = PassManager();
ionshared::Ptr<ionshared::PassContext> passContext =
std::make_shared<ionshared::PassContext>();
passManager.registerPass(std::make_shared<TypeCheckPass>(passContext));
Ast ast = Bootstrap::functionAst(test::constant::foobar);
ionshared::OptPtr<Function> function = ast[0]->dynamicCast<Module>()->lookupFunction(test::constant::foobar);
EXPECT_TRUE(ionshared::util::hasValue(function));
ionshared::Ptr<Prototype> prototype = function->get()->prototype;
prototype->returnType = TypeFactory::typeInteger(IntegerKind::Int32);
// TODO: For now it's throwing, but soon instead check for produced semantic error.
/**
* The bootstrapped function's entry section does not contain
* any instructions. Since at least a single terminal instruction
* is required, the pass should report a semantic error.
*/
// EXPECT_THROW(passManager.run(ast), std::runtime_error);
passManager.run(ast);
EXPECT_EQ(passContext->diagnostics->getSize(), 1);
ionshared::Diagnostic functionReturnValueMissingDiagnostic =
(*passContext->diagnostics.get())[0];
EXPECT_EQ(
functionReturnValueMissingDiagnostic.code.value(),
diagnostic::functionReturnValueMissing.code.value()
);
prototype->returnType = TypeFactory::typeVoid();
ionshared::Ptr<BasicBlock> entrySection = *function->get()->body->findEntryBasicBlock();
InstBuilder instBuilder = InstBuilder(entrySection);
instBuilder.createReturn();
// TODO: Compare diagnostics instead.
/**
* After setting the bootstrapped function's prototype's return
* type to void and inserting a return instruction, the pass
* should no longer complain.
*/
EXPECT_NO_THROW(passManager.run(ast));
}
TEST(TypeCheckPassTast, FunctionReturnTypeValueMismatch) {
ionshared::Ptr<ionshared::PassContext> passContext =
std::make_shared<ionshared::PassContext>();
ionshared::Ptr<TypeCheckPass> typeCheckPass = std::make_shared<TypeCheckPass>(passContext);
Ast ast = Bootstrap::functionAst(test::constant::foobar);
ionshared::OptPtr<Function> function = ast[0]->dynamicCast<Module>()->lookupFunction(test::constant::foobar);
EXPECT_TRUE(function.has_value());
ionshared::Ptr<Prototype> prototype = function->get()->prototype;
prototype->returnType = TypeFactory::typeInteger(IntegerKind::Int32);
ionshared::Ptr<BasicBlock> entrySection = *function->get()->body->findEntryBasicBlock();
InstBuilder instBuilder = InstBuilder(entrySection);
ionshared::Ptr<ReturnInst> returnInst = instBuilder.createReturn(
std::make_shared<IntegerLiteral>(
std::make_shared<IntegerType>(IntegerKind::Int8),
2
)
);
/**
* When the return instruction is visited, a
*/
EXPECT_THROW(
typeCheckPass->visitReturnInst(returnInst),
std::runtime_error
);
}
|
#include "GMOnlineImp.h"
#include <sys/time.h>
#include <sys/resource.h>
#include "util/tc_http.h"
#include "sig_check.h"
#include "util/tc_md5.h"
#include "util/tc_logger.h"
#include "util/tc_base64.h"
#include "CommLogic.h"
using namespace MINIAPR;
//const string g_appKey = "KfvpPibrLiA4sj41&";
taf::Servant* g_pMainServant = NULL;
extern TC_HttpAsync g_httpAsync;
map<int , ServerEngine::GamePrx> m_worldList;
string error_Response(string cmd, string reason)
{
JsonValueObjPtr objPrt = taf::TC_AutoPtr<JsonValueObj> (new JsonValueObj());
JsonValueStringPtr stringReason = taf::TC_AutoPtr<JsonValueString> (new JsonValueString(reason));
JsonValueStringPtr stringCmd = taf::TC_AutoPtr<JsonValueString> (new JsonValueString(cmd));
objPrt->value.insert(make_pair("cmd" ,stringCmd));
objPrt->value.insert(make_pair("reason" ,stringReason));
return TC_Json::writeValue(JsonValuePtr::dynamicCast(objPrt));
}
GMOnlineImp::GMOnlineImp()
{
}
GMOnlineImp::~GMOnlineImp()
{
}
void GMOnlineImp::initialize()
{
g_pMainServant = this;
string strConfigFile = ServerConfig::ServerName + ".conf";
TC_Config tmpCfg;
tmpCfg.parseFile(strConfigFile);
//m_strAPPID = tmpCfg.get("/LJSDKServer<productCode>", "");
//m_strProductSecretKey = tmpCfg.get("/LJSDKServer<productSecret>", "");
//FDLOG("LJSDKImp")<<"ReadArgs|"<<m_strAPPID<<endl;
vector<string> gameNameList;
if(!tmpCfg.getDomainVector("/GMOnlineServer/OuterObj/GameServerlist", gameNameList) )
{
throw runtime_error("invalid config /GMOnlineServer/OuterObj/GameServerlist");
return;
}
for(size_t i = 0; i < gameNameList.size(); i++)
{
string strTmpServerName = gameNameList[i];
string strSection = string("/GMOnlineServer/OuterObj/GameServerlist/") + strTmpServerName;
int iWorldID = TC_Common::strto<int>(tmpCfg.get(strSection + "<WorldID>", "-1") );
if(iWorldID < 0) continue;
string strObject = tmpCfg.get(strSection + "<GameObj>", "");
ServerEngine::GamePrx gamePrx = Application::getCommunicator()->stringToProxy<ServerEngine::GamePrx>(strObject);
std::pair<map<int , ServerEngine::GamePrx>::iterator,bool> ret = m_worldList.insert(make_pair(iWorldID,gamePrx));
assert(ret.second);
}
string strNameObj = tmpCfg.get("/GMOnlineServer<NameServer>", "");
assert(strNameObj.size() > 0);
m_namePrx = Application::getCommunicator()->stringToProxy<ServerEngine::NamePrx>(strNameObj);
//string strLegionNameObj = tmpCfg.get("/GMOnlineServer<LegionNameObject>", "");
//assert(strLegionNameObj.size() > 0);
//m_LegionNamePrx = Application::getCommunicator()->stringToProxy<ServerEngine::NamePrx>(strLegionNameObj);
}
class GetRoleBaseDataCBPtr : public ServerEngine::GamePrxCallback
{
public:
GetRoleBaseDataCBPtr(taf::JceCurrentPtr current)
:m_current(current)
{
}
virtual void callback_getRoleBaseData(taf::Int32 ret, const std::string& strJson)
{
cout<<strJson.c_str()<<endl;
m_current->sendResponse(strJson.c_str(),strJson.length());
}
virtual void callback_getRoleBaseData_exception(taf::Int32 ret)
{
string strJson = error_Response("rolebase","Server Exception");
m_current->sendResponse(strJson.c_str(),strJson.length());
//cout<<strJson.c_str()<<endl;
}
virtual void callback_getRoleBagData(taf::Int32 ret, const std::string& strJson)
{
cout<<strJson.c_str()<<endl;
m_current->sendResponse(strJson.c_str(),strJson.length());
}
virtual void callback_getRoleBagData_exception(taf::Int32 ret)
{
string strJson = error_Response("rolebag","Server Exception");
m_current->sendResponse(strJson.c_str(),strJson.length());
}
virtual void callback_getRoleHeroData(taf::Int32 ret, const std::string& strJson)
{
cout<<strJson.c_str()<<endl;
m_current->sendResponse(strJson.c_str(),strJson.length());
}
virtual void callback_getRoleHeroData_exception(taf::Int32 ret)
{
string strJson = error_Response("rolebag","Server Exception");
m_current->sendResponse(strJson.c_str(),strJson.length());
}
virtual void callback_sendRoleMail(taf::Int32 ret)
{
if(ret == 1)
{
string strJson = "{\"cmd\":\"rolemail\",\"status\":\"success\"}";
m_current->sendResponse(strJson.c_str(),strJson.length());
}
else if(ret == -1)
{
string strJson = error_Response("rolemail","Param Error");
m_current->sendResponse(strJson.c_str(),strJson.length());
}
else if(ret == -2)
{
string strJson = error_Response("rolemail","drop error");
m_current->sendResponse(strJson.c_str(),strJson.length());
}
}
virtual void callback_sendRoleMail_exception(taf::Int32 ret)
{
string strJson = error_Response("rolemail","Server Exception");
m_current->sendResponse(strJson.c_str(),strJson.length());
}
virtual void callback_getLegionMember(taf::Int32 ret, const std::string& strJson)
{
cout<<strJson<<endl;
m_current->sendResponse(strJson.c_str(),strJson.length());
}
virtual void callback_getLegionMember_exception(taf::Int32 ret)
{
string strJson = error_Response("legionmember","Server Exception");
m_current->sendResponse(strJson.c_str(),strJson.length());
}
virtual void callback_GMOnlneRollMessage(taf::Int32 ret)
{
string strJson="{\"cmd\":\"rollmsg\",\"status\":\"scuess\"}";
m_current->sendResponse(strJson.c_str(),strJson.length());
}
virtual void callback_GMOnlneRollMessage_exception(taf::Int32 ret)
{
string strJson = error_Response("rollmsg","Server Exception");
m_current->sendResponse(strJson.c_str(),strJson.length());
}
private:
taf::JceCurrentPtr m_current;
};
class RoleNameDescCallback : public ServerEngine::NamePrxCallback
{
public:
RoleNameDescCallback(taf::JceCurrentPtr current, string strCmd)
:m_current(current),
m_strCmd(strCmd)
{}
virtual void callback_getNameDesc(taf::Int32 ret, const ServerEngine::NameDesc& descInfo)
{
//ServerEngine::NameDesc namedesc = descInfo;
//m_cb(ret,namedesc);
if(ret != ServerEngine::en_NameRet_OK )
{
string strJson = error_Response(m_strCmd.c_str(),"Name Error");
m_current->sendResponse(strJson.c_str(),strJson.length());
}
else
{
int iWorldId = descInfo.wWolrdID;
string strAccount = descInfo.sAccount;
string str = TC_Common::TC_I2S(iWorldId) + strAccount;
string strJson = error_Response(m_strCmd.c_str(),str.c_str());
//m_current->sendResponse(strJson.c_str(),strJson.length());
//去服务器拿数据
map<int , ServerEngine::GamePrx>::iterator iter = m_worldList.find(iWorldId );
if( iter != m_worldList.end())
{
const ServerEngine::GamePrx gamePrt = iter->second;
if(m_strCmd == "rolebase")
{
ServerEngine::PKRole rolekey;
rolekey.worldID = descInfo.wWolrdID;
rolekey.rolePos = descInfo.iRolePos;
rolekey.strAccount = descInfo.sAccount;
gamePrt->async_getRoleBaseData( new GetRoleBaseDataCBPtr(m_current), rolekey);
}
else if(m_strCmd == "rolebag")
{
ServerEngine::PKRole rolekey;
rolekey.worldID = descInfo.wWolrdID;
rolekey.rolePos = descInfo.iRolePos;
rolekey.strAccount = descInfo.sAccount;
gamePrt->async_getRoleBagData( new GetRoleBaseDataCBPtr(m_current), rolekey);
}
else if(m_strCmd == "rolehero")
{
ServerEngine::PKRole rolekey;
rolekey.worldID = descInfo.wWolrdID;
rolekey.rolePos = descInfo.iRolePos;
rolekey.strAccount = descInfo.sAccount;
gamePrt->async_getRoleHeroData( new GetRoleBaseDataCBPtr(m_current), rolekey);
}
}
else
{
string strJson = error_Response(m_strCmd.c_str(),"Server Config Error");
m_current->sendResponse(strJson.c_str(),strJson.length());
}
}
}
virtual void callback_getNameDesc_exception(taf::Int32 ret)
{
//ServerEngine::NameDesc nullDesc;
//m_cb(ret,nullDesc);
string strJson = error_Response(m_strCmd.c_str(),"Server Exception");
m_current->sendResponse(strJson.c_str(),strJson.length());
}
private:
//DelegateName m_cb;
taf::JceCurrentPtr m_current;
string m_strCmd;
};
int GMOnlineImp::doRequest(taf::JceCurrentPtr current, vector<char>& response)
{
/*
请求内容为
{"cmd":" ", "data":{ } }
*/
const vector<char>& requestBuffer = current->getRequestBuffer();
if(requestBuffer.size() < 2)
{
current->close();
return 0;
}
string strMsg = string(&requestBuffer[0], requestBuffer.size() );
FDLOG("GMRequest")<<strMsg <<endl;
TC_HttpRequest stHttpRep;
stHttpRep.decode(&requestBuffer[0], requestBuffer.size() );
string strContent = stHttpRep.getContent();
FDLOG("GMRequestContent")<<strContent<<endl;
JsonValuePtr retValue = TC_Json::getValue(strContent);
JsonValueObjPtr pObj=JsonValueObjPtr::dynamicCast(retValue);
string strCmd = JsonValueStringPtr::dynamicCast(pObj->value["cmd"])->value;
if(strCmd == "rolebase")
{
onGetRoleBase(current, pObj);
}
else if(strCmd=="rolebag")
{
onGetRoleBag(current, pObj);
}
else if(strCmd=="rolehero")
{
onGetRoleHero(current, pObj);
}
else if(strCmd=="rolemail")
{
onSendRoleMail(current, pObj);
}
else if(strCmd=="legionmember")
{
onGetLegionMemberName(current, pObj);
}
else if(strCmd=="rollmsg")
{
onSendRollMessage(current, pObj);
}
else
{
string strJson = error_Response(strCmd.c_str(),"Param Error");
current->sendResponse(strJson.c_str(),strJson.length());
}
return -1;
}
void GMOnlineImp::onSendRollMessage(taf::JceCurrentPtr current, JsonValueObjPtr& objPtr)
{
string strCmd = JsonValueStringPtr::dynamicCast(objPtr->value["cmd"])->value;
JsonValueObjPtr pDataObj = JsonValueObjPtr::dynamicCast(objPtr->value["data"]);
if( pDataObj->value.find("msg") == pDataObj->value.end() )
{
string strJson = error_Response(strCmd.c_str(),"Param Error");
current->sendResponse(strJson.c_str(),strJson.length());
return;
}
string strMsg = JsonValueStringPtr::dynamicCast(pDataObj->value["msg"])->value;
if(strMsg.size()>60)
{
string strJson = error_Response("rollmsg","Message Too LONG");
current->sendResponse(strJson.c_str(),strJson.length());
return;
}
string strZoneId = JsonValueStringPtr::dynamicCast(pDataObj->value["zoneid"])->value;
int iZoneId = TC_S2I(strZoneId);
map<int , ServerEngine::GamePrx>::iterator iter = m_worldList.find(iZoneId );
if( iter != m_worldList.end())
{
const ServerEngine::GamePrx gamePrt = iter->second;
gamePrt->async_GMOnlneRollMessage( new GetRoleBaseDataCBPtr(current), strMsg);
}
else if(-1 == iZoneId)
{
map<int , ServerEngine::GamePrx>::iterator iter = m_worldList.begin();
for(;iter!= m_worldList.end();++iter)
{
const ServerEngine::GamePrx gamePrt = iter->second;
gamePrt->async_GMOnlneRollMessage( new GetRoleBaseDataCBPtr(current), strMsg);
}
}
else
{
string strJson = error_Response("legionmember","Server Config Error");
current->sendResponse(strJson.c_str(),strJson.length());
}
}
class SendRoleMailGetNameCallback : public ServerEngine::NamePrxCallback
{
public:
SendRoleMailGetNameCallback(taf::JceCurrentPtr current, string strCmd, map<string,string>& mailMap)
:m_current(current),
m_strCmd(strCmd),
m_MailMap(mailMap)
{}
virtual void callback_getNameDesc(taf::Int32 ret, const ServerEngine::NameDesc& descInfo)
{
if(ret != ServerEngine::en_NameRet_OK )
{
string strJson = error_Response(m_strCmd.c_str(),"Name Error");
m_current->sendResponse(strJson.c_str(),strJson.length());
}
else
{
int iWorldId = descInfo.wWolrdID;
string strAccount = descInfo.sAccount;
string str = TC_Common::TC_I2S(iWorldId) + strAccount;
string strJson = error_Response(m_strCmd.c_str(),str.c_str());
//去服务器拿数据
map<int , ServerEngine::GamePrx>::iterator iter = m_worldList.find(iWorldId );
if( iter != m_worldList.end())
{
const ServerEngine::GamePrx gamePrt = iter->second;
ServerEngine::PKRole rolekey;
rolekey.worldID = descInfo.wWolrdID;
rolekey.rolePos = descInfo.iRolePos;
rolekey.strAccount = descInfo.sAccount;
gamePrt->async_sendRoleMail( new GetRoleBaseDataCBPtr(m_current), rolekey,m_MailMap);
}
else
{
string strJson = error_Response(m_strCmd.c_str(),"Server Config Error");
m_current->sendResponse(strJson.c_str(),strJson.length());
}
}
}
virtual void callback_getNameDesc_exception(taf::Int32 ret)
{
//ServerEngine::NameDesc nullDesc;
//m_cb(ret,nullDesc);
string strJson = error_Response(m_strCmd.c_str(),"Server Exception");
m_current->sendResponse(strJson.c_str(),strJson.length());
}
private:
//DelegateName m_cb;
taf::JceCurrentPtr m_current;
string m_strCmd;
map<string,string> m_MailMap;
};
void GMOnlineImp::onGetLegionMemberName(taf::JceCurrentPtr current, JsonValueObjPtr& objPtr)
{
string strCmd = JsonValueStringPtr::dynamicCast(objPtr->value["cmd"])->value;
JsonValueObjPtr pDataObj = JsonValueObjPtr::dynamicCast(objPtr->value["data"]);
if( pDataObj->value.find("name") == pDataObj->value.end() )
{
string strJson = error_Response(strCmd.c_str(),"Param Error");
current->sendResponse(strJson.c_str(),strJson.length());
return;
}
string strName = JsonValueStringPtr::dynamicCast(pDataObj->value["name"])->value;
string strZoneId = JsonValueStringPtr::dynamicCast(pDataObj->value["zoneid"])->value;
int iZoneId = TC_S2I(strZoneId);
map<int , ServerEngine::GamePrx>::iterator iter = m_worldList.find(iZoneId );
if( iter != m_worldList.end())
{
const ServerEngine::GamePrx gamePrt = iter->second;
gamePrt->async_getLegionMember( new GetRoleBaseDataCBPtr(current), strName);
}
else
{
string strJson = error_Response("legionmember","Server Config Error");
current->sendResponse(strJson.c_str(),strJson.length());
}
}
void GMOnlineImp::onSendRoleMail(taf::JceCurrentPtr current, JsonValueObjPtr& objPtr)
{
string strCmd = JsonValueStringPtr::dynamicCast(objPtr->value["cmd"])->value;
JsonValueObjPtr pDataObj = JsonValueObjPtr::dynamicCast(objPtr->value["data"]);
if( pDataObj->value.find("name") == pDataObj->value.end() )
{
string strJson = error_Response(strCmd.c_str(),"Param Error");
current->sendResponse(strJson.c_str(),strJson.length());
return;
}
string strName = JsonValueStringPtr::dynamicCast(pDataObj->value["name"])->value;
string strTitle = JsonValueStringPtr::dynamicCast(pDataObj->value["title"])->value;
string strContext = JsonValueStringPtr::dynamicCast(pDataObj->value["context"])->value;
string strSender = JsonValueStringPtr::dynamicCast(pDataObj->value["sender"])->value;
JsonValueObjPtr pRewardObj = JsonValueObjPtr::dynamicCast(pDataObj->value["reward"]);
string strRewardLifeatt = JsonValueStringPtr::dynamicCast(pRewardObj->value["lifeatt"])->value;
string strRewardItem = JsonValueStringPtr::dynamicCast(pRewardObj->value["item"])->value;
string strRewardPay;
if(pRewardObj->value.find("pay") != pRewardObj->value.end())
{
strRewardPay = JsonValueStringPtr::dynamicCast(pRewardObj->value["pay"])->value;
}
if( pDataObj->value.find("title") == pDataObj->value.end() ||
pDataObj->value.find("context") == pDataObj->value.end()||
pDataObj->value.find("sender") == pDataObj->value.end() )
{
string strJson = error_Response(strCmd.c_str(),"Param Error");
current->sendResponse(strJson.c_str(),strJson.length());
return;
}
cout<<"reward pay:"<<strRewardPay<<endl;
map<string ,string> mailMap;
mailMap.insert(make_pair("title",strTitle) );
mailMap.insert(make_pair("context",strContext) );
mailMap.insert(make_pair("sender",strSender) );
mailMap.insert(make_pair("lifeatt",strRewardLifeatt) );
mailMap.insert(make_pair("item",strRewardItem) );
mailMap.insert(make_pair("pay", strRewardPay));
m_namePrx->async_getNameDesc(new SendRoleMailGetNameCallback(current,strCmd,mailMap), strName);
}
void GMOnlineImp::onGetRoleHero(taf::JceCurrentPtr current, JsonValueObjPtr& objPtr)
{
string strCmd = JsonValueStringPtr::dynamicCast(objPtr->value["cmd"])->value;
JsonValueObjPtr pDataObj = JsonValueObjPtr::dynamicCast(objPtr->value["data"]);
if( pDataObj->value.find("name") == pDataObj->value.end() )
{
string strJson = error_Response(strCmd.c_str(),"Param Error");
current->sendResponse(strJson.c_str(),strJson.length());
return;
}
string strName = JsonValueStringPtr::dynamicCast(pDataObj->value["name"])->value;
//去名字服务器拉取数据
m_namePrx->async_getNameDesc(new RoleNameDescCallback(current,strCmd), strName);
}
void GMOnlineImp::onGetRoleBag(taf::JceCurrentPtr current, JsonValueObjPtr& objPtr)
{
string strCmd = JsonValueStringPtr::dynamicCast(objPtr->value["cmd"])->value;
JsonValueObjPtr pDataObj = JsonValueObjPtr::dynamicCast(objPtr->value["data"]);
if( pDataObj->value.find("name") == pDataObj->value.end() )
{
string strJson = error_Response(strCmd.c_str(),"Param Error");
current->sendResponse(strJson.c_str(),strJson.length());
return;
}
string strName = JsonValueStringPtr::dynamicCast(pDataObj->value["name"])->value;
//去名字服务器拉取数据
m_namePrx->async_getNameDesc(new RoleNameDescCallback(current,strCmd), strName);
}
void GMOnlineImp::onGetRoleBase(taf::JceCurrentPtr current, JsonValueObjPtr& objPtr)
{
/*
{"cmd":"rolebase", "data":{"name":"XXX" } }
*/
string strCmd = JsonValueStringPtr::dynamicCast(objPtr->value["cmd"])->value;
JsonValueObjPtr pDataObj = JsonValueObjPtr::dynamicCast(objPtr->value["data"]);
if( pDataObj->value.find("name") == pDataObj->value.end() )
{
string strJson = error_Response(strCmd.c_str(),"Param Error");
current->sendResponse(strJson.c_str(),strJson.length());
return;
}
string strName = JsonValueStringPtr::dynamicCast(pDataObj->value["name"])->value;
//去名字服务器拉取数据
m_namePrx->async_getNameDesc(new RoleNameDescCallback(current,strCmd),strName);
//AsyncGetNameDesc(,);
//current->sendResponse(strJson.c_str(),strJson.length());
}
/*
int GMOnlineImp::doResponse(ReqMessagePtr resp)
{
cout<<"doResponse"<<endl;
return -1;
}
int GMOnlineImp::doResponseException(ReqMessagePtr resp)
{
cout<<"doResponseException"<<endl;
return -1;
}
int GMOnlineImp::doResponseNoRequest(ReqMessagePtr resp)
{
cout<<"doResponseNoRequest"<<endl;
return -1;
}*/
void GMOnlineImp::destroy()
{
}
|
#include <ranges>
#include <vector>
#include <algorithm>
#include <iostream>
export module range_exam;
namespace fibo::ranges
{
struct Foo
{
std::pmr::string name;
unsigned age;
};
export void exam1()
{
std::pmr::vector<Foo> vec{ {"a", 1}, {"b", 2}, {"c", 3} };
std::ranges::sort(vec, std::greater{}, &Foo::age);
for (auto& e : vec) std::cout << e.age << ' ';
std::cout << std::endl;
}
}
|
/*
* TimerManager.h
*
* Created on: Jun 11, 2017
* Author: root
*/
#ifndef TIMER_TIMERMANAGER_H_
#define TIMER_TIMERMANAGER_H_
#include "Timer.h"
#include <list>
#include "../Common.h"
#include "../Thread/Task.h"
#include "TimerBase.h"
using namespace std;
namespace CommBaseOut
{
class Slot
{
public:
void SetIndex(int i) { m_index = i; }
int AddTimer(Safe_Smart_Ptr<Timer> &timer);
list<Safe_Smart_Ptr<Timer> > OnTick(int64 tick);
private:
CSimLock m_lock;
map<DWORD, Safe_Smart_Ptr<Timer> > m_mapTimer;
int m_index;
};
class TimerManager : public Task, public TimerBase
{
public:
TimerManager();
~TimerManager();
virtual int svr();
void OnTick(int64 tick);
virtual int AddTimer(Safe_Smart_Ptr<Timer> &timer, int isNewTimer = 1);
virtual int AddTimer(Safe_Smart_Ptr<Timer> &timer, DWORD slot);
private:
void AttachTimer( Safe_Smart_Ptr<Timer> &timer, int64 tick, int isNewTimer );
private:
Slot m_slots[SLOT_COUNT];
DWORD m_currSlot;
CSimLock m_curlock;
DWORD m_lastTimerID;
CSimLock m_lock;
};
}
#endif /* TIMER_TIMERMANAGER_H_ */
|
//#ifndef INT_LINKED_LIST
//#define INT_LINKED_LIST
class IntNode {
public:
int info;
IntNode *next;
/*
IntNode() {
next = 0;
}
*/
IntNode(int el, IntNode *ptr = 0) {
info = el;
next = ptr;
}
};
class IntSLList {
public:
IntSLList() {
head = tail = 0;
}
~IntSLList();
int isEmpty() {
return head == 0;
}
//void addToHead(int);
void addToHead(int el) {
head = new IntNode(el, head);
// ^
// Right side: create new node with datum, el.
// Left side: set head to it.
// If from an empty list, new head is the new tail as well.
if (tail == 0)
tail = head;
// Example adding to list of 3 nodes
// tail old head new head
// node0 node2 node3 node4
}
void addToTail(int el) {
if (tail != 0) {
// ^ check if list is empty
// if not:
tail->next = new IntNode(el);
// ^what is currently the tail had next=0
// set next to a new IntNode with the datum specified,
// now tail is no longer the tail, the new datum created
// has next=0, and should be the new tail.
tail = tail->next;
// ^the new tail we should set is the new datum node
// created (the tail->next set above)
}
else
// if its a empty list, head and tail are the node created
// with the specified datum
head = tail = new IntNode(el);
}
// void addToTail(int);
int deleteFromHead();
int deleteFromTail();
void deleteNode(int);
bool isInList(int) const;
private:
IntNode *head, *tail;
};
IntSLList::~IntSLList() {
for (IntNode *p; !isEmpty();) {
p = head->next;
delete head;
head = p;
}
}
/*
void IntSLList::addToHead(int el) {
head = new IntNode(el, head);
if (tail == 0)
tail = head;
}
*/
//#endif
|
/* XMRig
* Copyright (c) 2018-2021 SChernykh <https://github.com/SChernykh>
* Copyright (c) 2016-2021 XMRig <https://github.com/xmrig>, <support@xmrig.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "hw/msr/Msr.h"
#include "3rdparty/fmt/core.h"
#include "backend/cpu/Cpu.h"
#include "base/io/log/Log.h"
#include <array>
#include <cctype>
#include <cinttypes>
#include <cstdio>
#include <dirent.h>
#include <fcntl.h>
#include <fstream>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
namespace xmrig {
static int msr_open(int32_t cpu, int flags)
{
const auto name = fmt::format("/dev/cpu/{}/msr", cpu < 0 ? Cpu::info()->units().front() : cpu);
return open(name.c_str(), flags);
}
class MsrPrivate
{
public:
inline MsrPrivate() : m_available(msr_allow_writes() || msr_modprobe()) {}
inline bool isAvailable() const { return m_available; }
private:
inline bool msr_allow_writes()
{
std::ofstream file("/sys/module/msr/parameters/allow_writes", std::ios::out | std::ios::binary | std::ios::trunc);
if (file.is_open()) {
file << "on";
}
return file.good();
}
inline bool msr_modprobe()
{
return system("/sbin/modprobe msr allow_writes=on > /dev/null 2>&1") == 0;
}
const bool m_available;
};
} // namespace xmrig
xmrig::Msr::Msr() : d_ptr(new MsrPrivate())
{
if (!isAvailable()) {
LOG_WARN("%s " YELLOW_BOLD("msr kernel module is not available"), tag());
}
}
xmrig::Msr::~Msr()
{
delete d_ptr;
}
bool xmrig::Msr::isAvailable() const
{
return d_ptr->isAvailable();
}
bool xmrig::Msr::write(Callback &&callback)
{
const auto &units = Cpu::info()->units();
for (int32_t pu : units) {
if (!callback(pu)) {
return false;
}
}
return true;
}
bool xmrig::Msr::rdmsr(uint32_t reg, int32_t cpu, uint64_t &value) const
{
const int fd = msr_open(cpu, O_RDONLY);
if (fd < 0) {
return false;
}
const bool success = pread(fd, &value, sizeof value, reg) == sizeof value;
close(fd);
return success;
}
bool xmrig::Msr::wrmsr(uint32_t reg, uint64_t value, int32_t cpu)
{
const int fd = msr_open(cpu, O_WRONLY);
if (fd < 0) {
return false;
}
const bool success = pwrite(fd, &value, sizeof value, reg) == sizeof value;
close(fd);
return success;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Magnus Gasslander
*/
#include "core/pch.h"
#if defined SUPPORT_TEXT_DIRECTION
#include "modules/unicode/unicode_bidiutils.h"
#include "modules/style/css.h"
// BidiLevelStack
BidiCategory BidiLevelStack::GetOverrideStatus() const
{
OP_ASSERT(stack_top >= 0 && static_cast<size_t>(stack_top) < ARRAY_SIZE(stack));
if (SlotOverride(stack[stack_top]))
{
if (SlotLevel(stack[stack_top]) % 2 == 0)
return BIDI_L;
return BIDI_R;
}
return BIDI_UNDEFINED;
}
int BidiLevelStack::GetResolvedLevel(BidiCategory type) const
{
int current_level = GetCurrentLevel();
if (type == BIDI_AN || type == BIDI_EN)
{
if (current_level % 2 == 0)
return current_level + 2;
else
return current_level + 1;
}
if ((type == BIDI_L && current_level % 2 == 1) ||
(type == BIDI_R && current_level % 2 == 0))
return current_level + 1;
return current_level;
}
BidiCategory BidiLevelStack::GetEmbeddingDir() const
{
int current_level = GetCurrentLevel();
if (current_level % 2 == 0)
return BIDI_L;
else
return BIDI_R;
}
void BidiLevelStack::PushLevel(int direction, bool is_override)
{
// Check for maximum explicit depth level according to standard.
if (stack_top >= MaximumDepth)
return;
// X2 - X5
stack_top++;
int previous_level = SlotLevel(stack[stack_top - 1]);
OP_ASSERT(direction == CSS_VALUE_rtl || direction == CSS_VALUE_ltr);
bool prev_level_is_even = (previous_level % 2) == 0;
int level_increment;
if (direction == CSS_VALUE_rtl)
{
// X2 & X4
if (prev_level_is_even)
level_increment = 1;
else
level_increment = 2;
}
else /* direction == CSS_VALUE_ltr */
{
// X3 & X5
if (!prev_level_is_even)
level_increment = 1;
else
level_increment = 2;
}
stack[stack_top] = EncodeSlot(previous_level + level_increment, is_override);
}
// BidiCalculation
OP_STATUS
BidiCalculation::PushLevel(int direction, BOOL is_override)
{
previous_embedding_level = level_stack.GetCurrentLevel();
level_stack.PushLevel(direction, !!is_override);
// eor is calculated after the push - the highest value.
eor_level = level_stack.GetCurrentLevel();
eor_type = (eor_level % 2 == 0) ? BIDI_L : BIDI_R;
OP_STATUS status = HandleNeutralsAtRunChange();
if (status != OpStatus::OK)
return status;
last_segment_type = last_strong_type = last_type = W1_last_type = W2_last_strong_type = W7_last_strong_type = eor_type;
return OpStatus::OK;
}
OP_STATUS BidiCalculation::PopLevel()
{
previous_embedding_level = level_stack.GetCurrentLevel();
// eor is calculated before the pop. It should always be based on the highest value.
eor_level = level_stack.GetCurrentLevel();
eor_type = (eor_level % 2 == 0) ? BIDI_L : BIDI_R;
level_stack.PopLevel();
OP_STATUS status = HandleNeutralsAtRunChange();
if (status != OpStatus::OK)
return status;
last_segment_type = last_strong_type = last_type = W1_last_type = W2_last_strong_type = W7_last_strong_type = eor_type;
return OpStatus::OK;
}
/**
* Set the paragraph level.
*
* We _don't_ set it according to the first strong type as per the
* BiDi spec. Instead we only look at the direction property in the
* tag, to be compatible with browsers.
*/
void BidiCalculation::SetParagraphLevel(BidiCategory type, BOOL override)
{
level_stack.SetParagraphLevel(type, !!override);
W1_last_type = W2_last_strong_type = W7_last_strong_type = last_strong_type = paragraph_type = type;
}
/**
* This is the basic method used to create a new segment
*/
OP_STATUS BidiCalculation::CreateSegment(long width, HTML_Element* start_element, unsigned short level, long virtual_position)
{
ParagraphBidiSegment* seg = OP_NEW(ParagraphBidiSegment, (width, start_element, level, virtual_position));
if (!seg)
return OpStatus::ERR_NO_MEMORY;
OP_ASSERT(segments);
seg->Into(segments);
previous_segment_level = level;
return OpStatus::OK;
}
void BidiCalculation::ExpandCurrentSegment(int width)
{
GetCurrentSegment()->width += width;
}
/**
* Will expand the current segment.
*
* If this is the very first segment or if the embedding level has changed,
* and this is the first segment of the new level, we will create a new segment.
*
*/
OP_STATUS BidiCalculation::ExpandCurrentSegmentOrCreateFirst(BidiCategory type, int width, HTML_Element* start_element, long virtual_position)
{
if (segments->Empty() ||
GetCurrentSegment()->level == 63 ||
previous_embedding_level != level_stack.GetCurrentLevel() ||
last_segment_type != type)
{
// We are at the first run or at a (embedding level ||
// resolved level) that differs from the last.
OP_STATUS status = CreateSegment(width, start_element, level_stack.GetResolvedLevel(type), virtual_position);
if (status != OpStatus::OK)
return status;
previous_embedding_level = level_stack.GetCurrentLevel();
}
else
{
ExpandCurrentSegment(width);
}
last_segment_type = type;
return OpStatus::OK;
}
/**
* Will create a brand new segment, using the type and the current embedding level.
*/
OP_STATUS BidiCalculation::CreateBidiSegment(BidiCategory type, int width, HTML_Element* start_element, long virtual_position)
{
OP_STATUS status = CreateSegment(width, start_element, level_stack.GetResolvedLevel(type), virtual_position);
if (status != OpStatus::OK)
return status;
previous_embedding_level = level_stack.GetCurrentLevel();
last_segment_type = type;
return OpStatus::OK;
}
/**
* previous_embedding_level is the level before the push/pop. This is where the segment actually belongs
* eor_type is the type of the eor that was determined by the push/pop
* previous_segment_level is the level of the last vreated segment. This is used to determine if we can just add
* to the last segment or if we need to create a new segment.
*
* FIXME too complicated!!
*/
OP_STATUS BidiCalculation::HandleNeutralsAtRunChange()
{
if (W4_pending_type != BIDI_UNDEFINED)
{
neutral_width = W4_width;
neutral_start_element = W4_start_element;
neutral_virtual_position_start = W4_virtual_position;
W4_pending_type = BIDI_UNDEFINED;
}
if (W5_type_before != BIDI_UNDEFINED)
{
if (IsNeutral(W5_type_before))
neutral_width += W5_width;
else
{
neutral_width = W5_width;
neutral_start_element = W5_start_element;
neutral_virtual_position_start = W5_virtual_position;
}
W5_type_before = BIDI_UNDEFINED;
}
if (!IsNeutral(last_type) && last_type != BIDI_CS && last_type != BIDI_ES && last_type != BIDI_ET)
return OpStatus::OK;
if (last_segment_type == BIDI_EN || last_segment_type == BIDI_AN)
{
// make the a BIDI_R segment from the neutral
int level_to_create = previous_embedding_level;
if (eor_type == BIDI_R && previous_embedding_level % 2 == 0) // two "R's (or EN/AN)" in a row should not follow the embedding level
level_to_create++;
OP_STATUS status = CreateSegment(neutral_width, neutral_start_element, level_to_create, neutral_virtual_position_start);
if (status != OpStatus::OK)
return status;
last_segment_type = (previous_embedding_level % 2 == 0) ? BIDI_L : BIDI_R;
}
/* either eor_type is the same as the last strong type or the
embedding direction is the same as the segment created last.
Note: this will not be triggered if the last strong type is
BIDI_UNDEFINED. That is good. */
else
if (( (eor_type == last_strong_type && previous_segment_level == eor_level) ||
previous_embedding_level == previous_segment_level) &&
!segments->Empty() &&
GetCurrentSegment()->level != 63)
{
ExpandCurrentSegment(neutral_width);
}
else
{
// make a segment with the previous embedding direction/level
int segment_level;
if (eor_type == last_strong_type)
{
if (previous_embedding_level % 2 == 0 && eor_type == BIDI_L || previous_embedding_level % 2 == 1 && eor_type == BIDI_R)
segment_level = previous_embedding_level;
else
segment_level = previous_embedding_level + 1;
}
else
segment_level = previous_embedding_level;
OP_STATUS status = CreateSegment(neutral_width, neutral_start_element, segment_level, neutral_virtual_position_start);
if (status != OpStatus::OK)
return status;
last_segment_type = (previous_embedding_level % 2 == 0) ? BIDI_L : BIDI_R;
}
return OpStatus::OK;
}
long
BidiCalculation::AppendStretch(BidiCategory initial_bidi_type, int width, HTML_Element* element, long virtual_position)
{
BOOL word_handled = FALSE;
OP_STATUS status = OpStatus::OK;
BidiCategory bidi_type = initial_bidi_type; // needed to record some states
long retval = LONG_MAX - 1;
if (bidi_type != BIDI_RLO &&
bidi_type != BIDI_RLE &&
bidi_type != BIDI_LRO &&
bidi_type != BIDI_LRE &&
bidi_type != BIDI_PDF)
{
BidiCategory override = level_stack.GetOverrideStatus();
if (override != BIDI_UNDEFINED)
bidi_type = override;
}
while (!word_handled)
{
word_handled = TRUE; // by default all words are handled in the first run
switch (bidi_type)
{
case BIDI_UNDEFINED:
// OP_ASSERT(0); // dont really fancy undefined types
if (last_type != BIDI_UNDEFINED)
bidi_type = last_type;
else
bidi_type = BIDI_L;
word_handled = FALSE;
break;
// strong types
case BIDI_RLO:
PushLevel(CSS_VALUE_rtl, TRUE);
break;
case BIDI_RLE:
PushLevel(CSS_VALUE_rtl, FALSE);
break;
case BIDI_LRO:
PushLevel(CSS_VALUE_ltr, TRUE);
break;
case BIDI_LRE:
PushLevel(CSS_VALUE_ltr, FALSE);
break;
case BIDI_L:
if (paragraph_type == BIDI_UNDEFINED)
SetParagraphLevel(BIDI_L, FALSE);
switch (last_type)
{
case BIDI_ET: // any pending W4 & W5 stretches should be converted to neutrals
case BIDI_CS:
case BIDI_ES:
if (last_type == BIDI_ET)
{
if (IsNeutral(W5_type_before))
neutral_width += W5_width;
else
{
neutral_width = W5_width;
neutral_start_element = W5_start_element;
neutral_virtual_position_start = W5_virtual_position;
}
}
else
if (W4_pending_type != BIDI_UNDEFINED)
{
neutral_width = W4_width;
neutral_start_element = W4_start_element;
neutral_virtual_position_start = W4_virtual_position;
last_type = BIDI_ON;
}
// fall through
case BIDI_S:
case BIDI_WS:
case BIDI_B:
case BIDI_ON:
if (level_stack.GetEmbeddingDir() != last_strong_type)
retval = neutral_virtual_position_start;
if (last_strong_type == BIDI_L)
{
status = ExpandCurrentSegmentOrCreateFirst(BIDI_L, width + neutral_width, neutral_start_element, neutral_virtual_position_start);
if (status != OpStatus::OK)
return LONG_MAX;
}
else
if (last_strong_type == BIDI_R)
{
if (level_stack.GetEmbeddingDir() == BIDI_L)
{
status = CreateBidiSegment(BIDI_L, width + neutral_width, neutral_start_element, neutral_virtual_position_start);
if (status != OpStatus::OK)
return LONG_MAX;
}
else
{
status = ExpandCurrentSegmentOrCreateFirst(BIDI_R, neutral_width, neutral_start_element, neutral_virtual_position_start);
if (status == OpStatus::OK)
status = CreateBidiSegment(BIDI_L, width, element, virtual_position);
if (status != OpStatus::OK)
return LONG_MAX;
}
}
else
OP_ASSERT(0); // this means that last_strong_type is undefined. or worse...
break;
case BIDI_UNDEFINED:
case BIDI_L:
// add to the current segment
status = ExpandCurrentSegmentOrCreateFirst(BIDI_L, width, element, virtual_position);
if (status != OpStatus::OK)
return LONG_MAX;
break;
case BIDI_EN:
case BIDI_AN:
case BIDI_R:
// create a new segment
status = CreateBidiSegment(BIDI_L, width, element, virtual_position);
if (status != OpStatus::OK)
return LONG_MAX;
break;
default:
break;
}
W2_last_strong_type = last_strong_type = BIDI_L;
last_type = BIDI_L;
break;
case BIDI_AL:
// W3
bidi_type = BIDI_R;
word_handled = FALSE;
break;
case BIDI_R:
if (paragraph_type == BIDI_UNDEFINED)
SetParagraphLevel(BIDI_R, FALSE); //FIXME mg should this be allowed ?
switch (last_type)
{
case BIDI_ES: // any pending W4 & W5 stretches should be converted to neutrals
case BIDI_CS:
case BIDI_ET:
if (last_type == BIDI_ET)
{
if (IsNeutral(W5_type_before))
neutral_width += W5_width;
else
{
neutral_width = W5_width;
neutral_start_element = W5_start_element;
neutral_virtual_position_start = W5_virtual_position;
}
}
else
if (W4_pending_type != BIDI_UNDEFINED) // which means that the word before this was a
{
neutral_width = W4_width;
neutral_start_element = W4_start_element;
neutral_virtual_position_start = W4_virtual_position;
last_type = BIDI_ON;
}
// fall through (W4 & W5)
case BIDI_S:
case BIDI_WS:
case BIDI_B:
case BIDI_ON:
if(level_stack.GetEmbeddingDir() != last_strong_type)
retval = neutral_virtual_position_start;
if (last_strong_type == BIDI_R)
{
status = ExpandCurrentSegmentOrCreateFirst(BIDI_R, width + neutral_width, neutral_start_element, neutral_virtual_position_start);
if (status != OpStatus::OK)
return LONG_MAX;
}
else
if (last_strong_type == BIDI_L)
{
if (level_stack.GetEmbeddingDir() == BIDI_R)
{
status = CreateBidiSegment(BIDI_R, width + neutral_width, neutral_start_element, neutral_virtual_position_start);
if (status != OpStatus::OK)
return LONG_MAX;
}
else
{
status = ExpandCurrentSegmentOrCreateFirst(BIDI_L, neutral_width, neutral_start_element, neutral_virtual_position_start);
if (status == OpStatus::OK)
status = CreateBidiSegment(BIDI_R, width, element, virtual_position);
if (status != OpStatus::OK)
return LONG_MAX;
}
}
else
OP_ASSERT(0); // this means that last strong type is undefined (or worse...)
// resolve the neutral
break;
case BIDI_EN:
case BIDI_AN:
case BIDI_L:
status = CreateBidiSegment(BIDI_R, width, element, virtual_position);
if (status != OpStatus::OK)
return LONG_MAX;
// create a new segment
break;
case BIDI_UNDEFINED:
// fall through
case BIDI_R:
// add to the current segment
status = ExpandCurrentSegmentOrCreateFirst(BIDI_R, width, element, virtual_position);
if (status != OpStatus::OK)
return LONG_MAX;
break;
default:
break;
}
last_strong_type = BIDI_R;
last_type = BIDI_R;
break;
// weak
case BIDI_PDF:
//PopLevel();
break;
case BIDI_EN:
if (W2_last_strong_type == BIDI_AL)
{
bidi_type = BIDI_AN;
word_handled = FALSE;
}
else
if (W7_last_strong_type == BIDI_L)
{
// W7
bidi_type = BIDI_L;
word_handled = FALSE;
}
else
{
switch (last_type)
{
case BIDI_ET:
width += W5_width;
element = W5_start_element;
virtual_position = W5_virtual_position;
if (IsNeutral(W5_type_before))
{
if (last_strong_type == BIDI_R || level_stack.GetEmbeddingDir() == BIDI_R)
{
// FIXME mg maybe make sure this only creates a segment when necessary
status = CreateBidiSegment(BIDI_R, neutral_width, neutral_start_element, neutral_virtual_position_start);
if (status == OpStatus::OK)
status = CreateBidiSegment(BIDI_EN, width, element, virtual_position);
if (status != OpStatus::OK)
return LONG_MAX;
}
else
{
// FIXME mg maybe make sure this only creates a segment when necessary
status = CreateBidiSegment(BIDI_L, neutral_width, neutral_start_element, neutral_virtual_position_start);
if (status == OpStatus::OK)
status = CreateBidiSegment(BIDI_EN, width, element, virtual_position);
if (status != OpStatus::OK)
return LONG_MAX;
}
}
else
{
// AN, L or R (can be no EN here)
status = CreateBidiSegment(BIDI_EN, width, element, virtual_position);
if (status != OpStatus::OK)
return LONG_MAX;
}
break;
case BIDI_ES:
case BIDI_CS:
if (W4_pending_type == BIDI_EN)
{
status = ExpandCurrentSegmentOrCreateFirst(BIDI_EN, W4_width + width, W4_start_element, W4_virtual_position);
if (status != OpStatus::OK)
return LONG_MAX;
}
else
{
OP_ASSERT(W4_pending_type == BIDI_AN);
if (last_strong_type == BIDI_R || level_stack.GetEmbeddingDir() == BIDI_R)
{
// FIXME mg maybe make sure this only creates a segment when necessary
status = CreateBidiSegment(BIDI_R, W4_width, W4_start_element, W4_virtual_position);
if (status == OpStatus::OK)
status = CreateBidiSegment(BIDI_EN, width, element, virtual_position);
if (status != OpStatus::OK)
return LONG_MAX;
}
else
{
// FIXME mg maybe make sure this only creates a segment when necessary
status = CreateBidiSegment(BIDI_L, W4_width, W4_start_element, W4_virtual_position);
if (status == OpStatus::OK)
status = CreateBidiSegment(BIDI_EN, width, element, virtual_position);
if (status != OpStatus::OK)
return LONG_MAX;
}
}
break;
case BIDI_S:
case BIDI_WS:
case BIDI_B:
case BIDI_ON:
if (level_stack.GetEmbeddingDir() != last_strong_type)
retval = neutral_virtual_position_start;
if (last_strong_type == BIDI_R || level_stack.GetEmbeddingDir() == BIDI_R)
{
// FIXME mg maybe make sure this only creates a segment when necessary
status = CreateBidiSegment(BIDI_R, neutral_width, neutral_start_element, neutral_virtual_position_start);
if (status == OpStatus::OK)
status = CreateBidiSegment(BIDI_EN, width, element, virtual_position);
if (status != OpStatus::OK)
return LONG_MAX;
}
else
{
// FIXME mg maybe make sure this only creates a segment when necessary
status = CreateBidiSegment(BIDI_L, neutral_width, neutral_start_element, neutral_virtual_position_start);
if (status == OpStatus::OK)
status = CreateBidiSegment(BIDI_EN, width, element, virtual_position);
if (status != OpStatus::OK)
return LONG_MAX;
}
break;
case BIDI_L:
status = CreateBidiSegment(BIDI_EN, width, element, virtual_position);
if (status != OpStatus::OK)
return LONG_MAX;
// create a new segment
break;
case BIDI_EN:
// add to the current segment
status = ExpandCurrentSegmentOrCreateFirst(BIDI_EN, width, element, virtual_position);
if (status != OpStatus::OK)
return LONG_MAX;
break;
case BIDI_UNDEFINED:
// fall through
case BIDI_AN:
case BIDI_R:
status = CreateBidiSegment(BIDI_EN, width, element, virtual_position);
if (status != OpStatus::OK)
return LONG_MAX;
break;
default:
break;
}
last_strong_type = BIDI_R;
last_type = BIDI_EN;
}
// W2 & W7
break;
case BIDI_ES:
if (last_type == BIDI_EN)
{
W4_width = width;
W4_start_element = element;
W4_virtual_position = virtual_position;
W4_pending_type = last_type;
last_type = BIDI_ES;
}
else
{
bidi_type = BIDI_ON;
word_handled = FALSE;
} // W4
break;
case BIDI_ET:
if (W2_last_strong_type == BIDI_L) // W7 in effect - there can be no W5
{
if (W5_last_type == BIDI_EN)
bidi_type = BIDI_EN;
else
bidi_type = BIDI_ON;
word_handled = FALSE;
}
else
{
switch (last_type)
{
case BIDI_EN:
bidi_type = BIDI_EN;
word_handled = FALSE;
break;
case BIDI_ET:
W5_width += width;
break;
case BIDI_ES:
case BIDI_CS: // cancel W4 rule here
if (W4_pending_type != BIDI_UNDEFINED)
{
neutral_width = W4_width;
neutral_start_element = W4_start_element;
neutral_virtual_position_start = W4_virtual_position;
W5_type_before = BIDI_ON;
W5_width = width;
W5_start_element = element;
W5_virtual_position = virtual_position;
}
last_type = BIDI_ET;
break;
default:
W5_type_before = last_type;
W5_width = width;
W5_start_element = element;
W5_virtual_position = virtual_position;
last_type = BIDI_ET;
break;
}
}
break;
case BIDI_AN:
switch (last_type)
{
case BIDI_ES:
if (last_strong_type == BIDI_R || level_stack.GetEmbeddingDir() == BIDI_R)
{
// FIXME mg maybe make sure this only creates a segment when necessary
status = CreateBidiSegment(BIDI_R, W4_width, W4_start_element, W4_virtual_position);
if (status == OpStatus::OK)
status = CreateBidiSegment(BIDI_AN, width, element, virtual_position);
if (status != OpStatus::OK)
return LONG_MAX;
}
else
{
// FIXME mg maybe make sure this only creates a segment when necessary
status = CreateBidiSegment(BIDI_L, W4_width, W4_start_element, W4_virtual_position);
if (status == OpStatus::OK)
status = CreateBidiSegment(BIDI_AN, width, element, virtual_position);
if (status != OpStatus::OK)
return LONG_MAX;
}
break;
case BIDI_CS:
if (W4_pending_type == BIDI_AN)
{
status = ExpandCurrentSegmentOrCreateFirst(BIDI_AN, W4_width + width, W4_start_element, W4_virtual_position);
if (status != OpStatus::OK)
return LONG_MAX;
}
else
{
OP_ASSERT(W4_pending_type == BIDI_EN);
if (last_strong_type == BIDI_R || level_stack.GetEmbeddingDir() == BIDI_R)
{
// FIXME mg maybe make sure this only creates a segment when necessary
status = CreateBidiSegment(BIDI_R, W4_width, W4_start_element, W4_virtual_position);
if (status == OpStatus::OK)
status = CreateBidiSegment(BIDI_AN, width, element, virtual_position);
if (status != OpStatus::OK)
return LONG_MAX;
}
else
{
// FIXME mg maybe make sure this only creates a segment when necessary
status = CreateBidiSegment(BIDI_L, W4_width, W4_start_element, W4_virtual_position);
if (status == OpStatus::OK)
status = CreateBidiSegment(BIDI_AN, width, element, virtual_position);
if (status != OpStatus::OK)
return LONG_MAX;
}
}
break;
case BIDI_ET:
// convert pending W5 stretches to neutrals
if (IsNeutral(W5_type_before))
neutral_width += W5_width;
else
{
neutral_width = W5_width;
neutral_start_element = W5_start_element;
neutral_virtual_position_start = W5_virtual_position;
}
// fall through
case BIDI_S:
case BIDI_WS:
case BIDI_B:
case BIDI_ON:
if (level_stack.GetEmbeddingDir() != last_strong_type)
retval = neutral_virtual_position_start;
if (last_strong_type == BIDI_R || level_stack.GetEmbeddingDir() == BIDI_R)
{
// FIXME mg maybe make sure this only creates a segment when necessary
status = CreateBidiSegment(BIDI_R, neutral_width, neutral_start_element, neutral_virtual_position_start);
if (status == OpStatus::OK)
status = CreateBidiSegment(BIDI_AN, width, element, virtual_position);
if (status != OpStatus::OK)
return LONG_MAX;
}
else
{
// FIXME mg maybe make sure this only creates a segment when necessary
status = CreateBidiSegment(BIDI_L, neutral_width, neutral_start_element, neutral_virtual_position_start);
if (status == OpStatus::OK)
status = CreateBidiSegment(BIDI_AN, width, element, virtual_position);
if (status != OpStatus::OK)
return LONG_MAX;
}
break;
case BIDI_L:
status = CreateBidiSegment(BIDI_AN,width, element, virtual_position);
if (status != OpStatus::OK)
return LONG_MAX;
// create a new segment
break;
case BIDI_AN:
// add to the current segment
status = ExpandCurrentSegmentOrCreateFirst(BIDI_AN, width, element, virtual_position);
if (status != OpStatus::OK)
return LONG_MAX;
break;
case BIDI_UNDEFINED:
// fall through
case BIDI_EN:
case BIDI_R:
status = CreateBidiSegment(BIDI_AN, width, element, virtual_position);
if (status != OpStatus::OK)
return LONG_MAX;
break;
default:
break;
}
last_strong_type = BIDI_R;
last_type = BIDI_AN;
break;
case BIDI_CS:
if (last_type == BIDI_EN || last_type == BIDI_AN)
{
W4_width = width;
W4_start_element = element;
W4_virtual_position = virtual_position;
W4_pending_type = last_type; // need to save this here to match the types
last_type = BIDI_CS;
}
else
{
bidi_type = BIDI_ON;
word_handled = FALSE; //FIXME
} // W4
break;
case BIDI_NSM:
bidi_type = W1_last_type;
word_handled = FALSE;
break;
case BIDI_BN:
bidi_type = last_strong_type; //FIXME
word_handled = FALSE;
break;
//neutrals
case BIDI_S:
case BIDI_WS:
case BIDI_B:
case BIDI_ON:
switch (last_type)
{
case BIDI_S: //L1
case BIDI_WS:
case BIDI_B:
case BIDI_ON:
neutral_width += width;
break;
case BIDI_ET: //W5
if (IsNeutral(W5_type_before))
neutral_width += W5_width + width;
else
{
neutral_width = W5_width + width;
neutral_start_element = W5_start_element;
neutral_virtual_position_start = W5_virtual_position;
}
break;
case BIDI_ES:
case BIDI_CS:
if (W4_pending_type != BIDI_UNDEFINED)
{
neutral_width = W4_width + width;
neutral_start_element = W4_start_element;
neutral_virtual_position_start = W4_virtual_position;
}
break;
case BIDI_UNDEFINED:
case BIDI_L:
case BIDI_R:
case BIDI_AN:
case BIDI_EN:
neutral_width = width;
neutral_start_element = element;
neutral_virtual_position_start = virtual_position;
break;
default:
break;
}
last_type = bidi_type;
break;
default:
OP_ASSERT(0);
break;
}
}
if (initial_bidi_type == BIDI_PDF)
PopLevel();
/* set the states of some variables needed for weak types */
// W1
if (initial_bidi_type != BIDI_NSM)
W1_last_type = initial_bidi_type;
// W2
if (initial_bidi_type == BIDI_R || initial_bidi_type == BIDI_L || initial_bidi_type == BIDI_AL)
W2_last_strong_type = initial_bidi_type;
// W4
// reset this here so I dont have to do it for every type
if (bidi_type != BIDI_CS && bidi_type != BIDI_ES)
W4_pending_type = BIDI_UNDEFINED;
// W5
if (bidi_type != BIDI_ET)
W5_type_before = BIDI_UNDEFINED;
if (initial_bidi_type == BIDI_EN)
W5_last_type = BIDI_EN;
else
W5_last_type = BIDI_UNDEFINED;
// W7
if (initial_bidi_type == BIDI_R || initial_bidi_type == BIDI_AL)
W7_last_strong_type = BIDI_R;
else
if (initial_bidi_type == BIDI_L)
W7_last_strong_type = BIDI_L;
return retval;
}
/** Reset the calculation object for reuse. */
void
BidiCalculation::Reset()
{
previous_embedding_level = -1;
last_type = BIDI_UNDEFINED;
paragraph_type = BIDI_UNDEFINED;
last_strong_type = BIDI_UNDEFINED;
neutral_width = 0;
neutral_start_element = NULL;
neutral_virtual_position_start = 0;
last_appended_element = NULL;
previous_segment_level = -1;
last_segment_type = BIDI_UNDEFINED;
eor_type = BIDI_UNDEFINED;
eor_level = -1;
W1_last_type = BIDI_UNDEFINED;
W2_last_strong_type = BIDI_UNDEFINED;
W4_pending_type = BIDI_UNDEFINED;
W4_virtual_position = 0;
W4_width = 0;
W4_start_element = NULL;
W5_type_before = BIDI_UNDEFINED;
W5_virtual_position = 0;
W5_width = 0;
W5_start_element = NULL;
W5_last_type = BIDI_UNDEFINED;
W7_last_strong_type = BIDI_UNDEFINED;
level_stack.Reset();
}
// end of BidiStatus
#endif //SUPPORT_TEXT_DIRECTION
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2008 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#include "core/pch.h"
#ifdef _EXTERNAL_SSL_SUPPORT_
#include "modules/externalssl/externalssl_com.h"
#include "modules/dochand/win.h"
#include "modules/dochand/winman.h"
#include "modules/externalssl/externalssl_displaycontext.h"
#include "modules/externalssl/extssl.h"
#include "modules/externalssl/src/OpSSLSocket.h"
#include "modules/windowcommander/OpWindowCommander.h"
#include "modules/windowcommander/OpWindowCommanderManager.h"
#include "modules/windowcommander/src/WindowCommander.h"
External_SSL_Comm::External_SSL_Comm(MessageHandler* msg_handler, ServerName* hostname, unsigned short portnumber, BOOL connect_only, BOOL secure)
: Comm(msg_handler, hostname, portnumber, connect_only)
, m_real_server_name(0)
, m_security_state(SECURITY_STATE_UNKNOWN)
, m_security_problems(FALSE)
, m_display_context(NULL) /* Owned by External_SSL_DisplayContextManager */
, m_server_certificate(NULL)
, m_server_certificate_chain(NULL)
{
}
External_SSL_Comm::~External_SSL_Comm()
{
OP_DELETE(m_server_certificate_chain);
OP_DELETE(m_server_certificate);
if (m_display_context)
{
m_display_context->CommDeleted();
g_ssl_display_context_manager->DeleteDisplayContext(m_display_context); // Will only delete if m_display_context->OnCertificateBrowsingDone() has been called
}
OP_DELETE(m_real_server_name);
}
void External_SSL_Comm::OnSocketConnectError(OpSocket* aSocket, OpSocket::Error aError)
{
if (!info.is_secure)
{
Comm::OnSocketConnectError(aSocket, aError);
return;
}
m_security_problems = TRUE;
if (m_display_context && m_display_context->GetCertificateBrowsingDone())
{
g_ssl_display_context_manager->DeleteDisplayContext(m_display_context);
m_display_context = NULL;
}
OP_ASSERT(m_display_context == NULL);
AnchoredCallCount blocker(this);
if( aError == OpSocket::SECURE_CONNECTION_FAILED)
{
// Extra check. Moved from outside of the loop to allow
// Comm::OnSocketConnectError() to be called.
if (m_display_context)
return;
OpWindow *opwin = 0;
Window* window = NULL;
SetProgressInformation(GET_ORIGINATING_WINDOW, 0, &opwin);
if (opwin)
{
for(window = g_windowManager->FirstWindow(); window; window = window->Suc())
{
if (window->GetOpWindow() == opwin)
{
break;
}
}
}
int errors = m_Socket->GetSSLConnectErrors();
if (!(errors & OpSocket::CERT_BAD_CERTIFICATE) && (m_server_certificate = m_Socket->ExtractCertificate()) != NULL)
{
if (m_server_certificate && m_Host->IsCertificateAccepted(m_server_certificate))
{
m_Socket->AcceptInsecureCertificate(m_server_certificate);
OP_DELETE(m_server_certificate);
m_server_certificate = NULL;
return;
}
WindowCommander *windowCommander = NULL;
if (window && (windowCommander = window->GetWindowCommander()))
{
OP_STATUS status;
m_display_context = g_ssl_display_context_manager->OpenCertificateDialog(status, this, windowCommander, errors, OpSSLListener::SSL_CERT_OPTION_NONE);
if (m_display_context)
return;
else if (OpStatus::IsMemoryError(status) && mh && (window = mh->GetWindow()))
window->RaiseCondition(status);
}
}
}
OP_DELETE(m_server_certificate);
m_server_certificate = NULL;
Comm::OnSocketConnectError(aSocket, aError);
}
void External_SSL_Comm::OnSocketConnected(OpSocket* aSocket)
{
if(info.is_secure)
{
OP_STATUS status;
if(OpStatus::IsError(status = GetSSLSecurityDescription(m_security_state, m_securitytext)))
{
if (status == OpStatus::ERR_NO_MEMORY && mh)
mh->GetWindow()->RaiseCondition(status);
m_security_state = SECURITY_STATE_NONE;
m_securitytext.Empty();
}
}
Comm::OnSocketConnected(aSocket);
}
OP_STATUS External_SSL_Comm::SetSSLSocketOptions()
{
if (!m_Socket)
return OpStatus::ERR;
const ServerName* server_name = GetRealServerName();
OP_ASSERT(server_name);
const uni_char* uni_name = server_name->UniName();
OP_STATUS status = m_Socket->SetServerName(uni_name);
RETURN_IF_ERROR(status);
UINT32 cipher_count = 0;
const cipherentry_st* ciphers = g_external_ssl_options->GetCipherArray(cipher_count);
if (!ciphers)
return OpStatus::ERR;
status = m_Socket->SetSecureCiphers(ciphers, cipher_count);
return status;
}
CommState External_SSL_Comm::ServerCertificateAccepted()
{
if (OpStatus::IsSuccess(m_Host->AddAcceptedCertificate(m_server_certificate)) && OpStatus::IsSuccess(m_Socket->AcceptInsecureCertificate(m_server_certificate)))
return COMM_LOADING;
else
return COMM_REQUEST_FAILED;
}
CommState External_SSL_Comm::Connect()
{
m_securitytext.Empty();
if (info.is_secure)
{
m_security_state = SECURITY_STATE_UNKNOWN;
if (OpStatus::IsError(SetSSLSocketOptions()))
return COMM_REQUEST_FAILED;
}
else
{
m_security_state = SECURITY_STATE_NONE;
}
return Comm::Connect();
}
const ServerName* External_SSL_Comm::GetRealServerName() const
{
return m_real_server_name ? m_real_server_name : static_cast <const ServerName*> (m_Host);
}
OpCertificate* External_SSL_Comm::ExtractCertificate()
{
return m_Socket->ExtractCertificate();
}
void External_SSL_Comm::SignalConnectionClosed()
{
Comm::OnSocketConnectError(m_Socket, OpSocket::SECURE_CONNECTION_FAILED);
}
OP_STATUS External_SSL_Comm::GetSSLSecurityDescription(int &sec_state, OpString &description)
{
sec_state = SECURITY_STATE_NONE;
description.Empty();
if (!m_Socket)
return OpStatus::OK;
cipherentry_st used_cipher;
BOOL TLS_v1_used = FALSE;
UINT32 PK_keylength = 0;
RETURN_IF_ERROR(m_Socket->GetCurrentCipher(&used_cipher, &TLS_v1_used, &PK_keylength));
const uni_char *fullname_format = g_external_ssl_options->GetCipher(used_cipher.id, sec_state);
if(sec_state > 1)
{
#ifdef DIA_PK_KEYLENGTH_SUPPORTED
if(PK_keylength< 646)
sec_state = 1;
else if(PK_keylength <838)
sec_state--;
#endif
}
if (m_security_problems)
sec_state = 0;
const uni_char *prot = (TLS_v1_used ? UNI_L("TLS v1.0") : UNI_L("SSL v3.0"));
if (fullname_format)
{
OpString temp_var;
RETURN_IF_ERROR(temp_var.AppendFormat(fullname_format, PK_keylength));
RETURN_IF_ERROR(description.SetConcat(prot, UNI_L(" "), temp_var));
}
return OpStatus::OK;
}
BOOL External_SSL_Comm::InsertTLSConnection(ServerName *host, unsigned short port)
{
info.is_secure = TRUE;
m_security_state = SECURITY_STATE_UNKNOWN;
m_securitytext.Empty();
if (m_Socket)
{
OP_STATUS status = OpStatus::OK;
m_real_server_name = ServerName::Create(host->Name(), status);
OP_ASSERT(OpStatus::IsSuccess(status) || !m_real_server_name);
if(SetSSLSocketOptions() != OpStatus::OK)
return FALSE;
return m_Socket->UpgradeToSecure();
}
return TRUE;
}
OP_STATUS External_SSL_Comm::CreateSocket(OpSocket** aSocket, BOOL secure)
{
return OpSSLSocket::Create(aSocket, this, secure);
}
#endif // _EXTERNAL_SSL_SUPPORT_
|
#include <bits/stdc++.h>
using namespace std;
ofstream fout ("blocks.out");
ifstream fin ("blocks.in");
#define For(x) for(int i = 0; i < x; i++)
#define Forv(vector) for(auto& j : vector)
int count(string s, char c) {
int count = 0;
for (int i = 0; i < s.size(); i++)
if (s[i] == c) count++;
return count;
}
int main(){
int n;
fin>>n;
auto letters = "abcdefghijklmnopqrstuvwxyz";
vector<pair<string,string> > blocks;
For(n){
string s,t;
fin>>s>>t;
pair<string,string> p(s,t);
blocks.push_back(p);
}
For(26){
int total = 0;
Forv(blocks){
total+=max(count(j.first,letters[i]),count(j.second,letters[i]));
}
fout<<total<<"\n";
}
}
|
#include<iostream>
#include<cstring>
#define FOR0(i,n) for(i=0;i<n;i++)
#define FOR(i,j,n) for(i=j;i<n;i++)
#define FORD(i,j,k) for(i=j;i>=k;i--)
#define MAX(a,b) (a)>(b)?(a):(b)
#define MIN(a,b) (a)<(b)?(a):(b)
#define num 1000000
using namespace std;
long dp[105][105];
long count(int K,int N)
{
if(K==0&&N==0)return 1;
if(K==0&&N!=0)return 0;
if(N<0||K<0)return 0;
if(dp[K][N]!=-1)return dp[K][N];
int i;
long ans=0;
FOR0(i,N+1)
{
ans=(ans+(count(K-1,N-i)%num))%num;
}
return dp[K][N]=ans;
}
int main()
{
int N,K;
while(1)
{
memset(dp,-1,sizeof dp);
scanf("%d%d",&N,&K);
if(!N)break;
cout<<count(K,N)<<endl;
}
}
|
#ifndef MAINUI_H
#define MAINUI_H
#include <TaskerUIMainWindowQWidget.h>
#include <memory>
/**
* @brief The MainUI class
*/
class MainUI {
private:
MainUI();
static CommStatsQWidget *Instance;
public:
static CommStatsQWidget *getInstance();
~MainUI();
public slots:
static void saveTaskerStateSlot();
};
#endif // MAINUI_H
|
#include "gamemanager.h"
#include "logincontroller.h"
RRG::GameManager::GameManager() {
}
RRG::GameManager::~GameManager() {
}
bool RRG::GameManager::Initialize() {
if (!_initialized) {
_initialized = true;
}
return _initialized;
}
void RRG::GameManager::Update(double time) {
//RRG::LoginController _currentController;
//_currentController.Render();
}
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2010 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* Espen Sand
*/
#include "core/pch.h"
#include "ipcmessageparser.h"
#include "modules/pi/OpWindow.h"
#include "modules/prefs/prefsmanager/collections/pc_ui.h"
#include "platforms/quix/commandline/quix_commandlineargumenthandler.h"
#include "platforms/unix/base/x11/x11_globals.h"
#include "platforms/unix/base/x11/x11_windowwidget.h"
#include "platforms/unix/base/x11/x11utils.h"
#include "adjunct/quick/Application.h"
#include "adjunct/quick/managers/CommandLineManager.h"
#include "adjunct/quick/WindowCommanderProxy.h"
#include "adjunct/quick/windows/BrowserDesktopWindow.h"
#include "adjunct/quick_toolkit/windows/DesktopWindow.h"
#ifdef _DEBUG
# define DEBUG_IPC_PARSING
#endif
namespace IPCMessageParser
{
void RaiseWindow(DesktopWindow* dw)
{
dw->Activate(TRUE);
dw->GetOpWindow()->Raise();
}
void LowerWindow(DesktopWindow* dw)
{
dw->Lower();
}
#if defined(DEBUG_IPC_PARSING)
void DumpParsedData(const ParsedData& pd)
{
OpString8 tmp;
tmp.Set(pd.address);
printf("address: %s\n", tmp.CStr());
tmp.Set(pd.window_name);
printf("window name: %s\n", tmp.CStr());
printf("rect: %d %d %d %d\n", pd.window_rect.x, pd.window_rect.y, pd.window_rect.width, pd.window_rect.height);
printf("new window: %d\n", pd.new_window);
printf("new tab: %d\n", pd.new_tab);
printf("privacy mode: %d\n", pd.privacy_mode);
printf("in background: %d\n", pd.in_background);
printf("noraise: %d\n", pd.noraise);
}
#endif
BOOL ParseCommand(BrowserDesktopWindow* bw, const OpString& cmd)
{
#if defined(DEBUG_IPC_PARSING)
OpString8 tmp;
tmp.Set(cmd);
printf("target: %p, cmd: %s\n", bw, tmp.CStr());
#endif
if (!bw)
{
return FALSE;
}
ParsedData pd;
if (cmd.Find("openURL") == 0)
{
if (ParseOpenUrlCommand(cmd, pd))
{
#if defined(DEBUG_IPC_PARSING)
DumpParsedData(pd);
#endif
if (pd.address.IsEmpty())
{
RaiseWindow(bw);
g_input_manager->InvokeAction(OpInputAction::ACTION_GO_TO_PAGE);
}
else
{
/* Not all combinations of values in pd are
* sensible. And only some combinations have
* actually been tested. In particular, setting
* both new_page and new_window to TRUE may not
* work as expected. And the same for setting
* in_background to TRUE but new_page to FALSE.
*/
// Set up the url opening parameters
OpenURLSetting url_setting;
url_setting.m_address.Set(pd.address);
url_setting.m_new_page = MAYBE;
url_setting.m_new_window = MAYBE;
url_setting.m_in_background = MAYBE;
url_setting.m_ignore_modifier_keys = TRUE;
url_setting.m_is_privacy_mode = pd.privacy_mode;
url_setting.m_is_remote_command = TRUE;
if (pd.new_window)
{
url_setting.m_new_page = NO;
url_setting.m_new_window = YES;
url_setting.m_in_background = NO;
}
if (pd.new_tab)
url_setting.m_new_page = YES;
if (pd.in_background)
url_setting.m_in_background = YES;
if (!pd.new_window)
{
url_setting.m_target_window = bw;
#if 0
/* This code sets url_setting.m_src_window.
* It used to happen as a side effect of
* calling g_application->GoToPage(), and I
* copied it in here when I rewrote the code
* to use the single-parameter OpenURL()
* instead.
*
* It is probably not needed. Most likely it
* does more harm than good. I expect
* m_src_window indicates which window
* initiated the loading. It seems obvious to
* me that when loading is initiated by an
* external application, no opera window
* should be set as opener.
*
* I chose to ifdef out the code rather than
* delete it in order to more easily test if
* removing this code is the cause of any
* strange regression we might run into.
*/
BrowserDesktopWindow* browser = g_application->GetActiveBrowserDesktopWindow();
if (browser)
{
DesktopWindow *active_win = browser->GetActiveDesktopWindow();
if (active_win)
{
OpWindowCommander *win_com = active_win->GetWindowCommander();
if (win_com)
{
// This sets setting.m_src_window to win_com's window
WindowCommanderProxy::InitOpenURLSetting(url_setting, win_com);
}
}
}
#endif
}
// Ok, URL opening parameters are set up, now do the work
if (!pd.noraise && !pd.new_window)
RaiseWindow(bw);
if (pd.new_window)
{
// I suspect this block is here just to be able to set the geometry.
Application::StartupSetting setting;
setting.open_in_background = FALSE;
setting.open_in_new_page = FALSE;
setting.open_in_new_window = TRUE;
setting.fullscreen = FALSE;
setting.iconic = FALSE;
setting.geometry = pd.window_rect;
g_application->SetStartupSetting(setting);
}
g_application->OpenURL(url_setting);
}
}
}
else if (cmd.Find("newInstance") == 0)
{
if (ParseDestinationCommand(cmd, pd))
{
#if defined(DEBUG_IPC_PARSING)
DumpParsedData(pd);
#endif
if (pd.in_background)
{
if (!pd.noraise)
RaiseWindow(bw);
g_application->CreateDocumentDesktopWindow(bw->GetWorkspace(), NULL, 0, 0, TRUE, FALSE, TRUE, FALSE, NULL, pd.privacy_mode);
}
else if (pd.new_tab)
{
if (!pd.noraise)
RaiseWindow(bw);
g_application->CreateDocumentDesktopWindow(bw->GetWorkspace(), NULL, 0, 0, TRUE, FALSE, FALSE, FALSE, NULL, pd.privacy_mode);
}
else if (pd.new_window)
{
Application::StartupSetting setting;
setting.open_in_background = FALSE;
setting.open_in_new_page = FALSE;
setting.open_in_new_window = TRUE;
setting.fullscreen = FALSE;
setting.iconic = FALSE;
setting.geometry = pd.window_rect;
g_application->SetStartupSetting(setting);
g_application->GetBrowserDesktopWindow(TRUE,FALSE,TRUE);
}
else
{
if (!pd.noraise)
RaiseWindow(bw);
g_application->CreateDocumentDesktopWindow(bw->GetWorkspace(), NULL, 0, 0, TRUE, FALSE, FALSE, FALSE, NULL, pd.privacy_mode);
}
}
}
else if (cmd.Find("openM2") == 0)
{
if (ParseDestinationCommand(cmd, pd))
{
#if defined(DEBUG_IPC_PARSING)
DumpParsedData(pd);
#endif
if (pd.new_window)
{
g_application->GetBrowserDesktopWindow(TRUE,FALSE,FALSE);
}
else if (pd.new_tab || pd.in_background)
{
return TRUE;
}
else
{
if (!pd.noraise)
RaiseWindow(bw);
}
g_input_manager->InvokeAction(OpInputAction::ACTION_READ_MAIL);
}
}
else if (cmd.Find("openComposer") == 0)
{
if (ParseDestinationCommand(cmd, pd))
{
#if defined(DEBUG_IPC_PARSING)
DumpParsedData(pd);
#endif
if (pd.new_window)
{
g_application->GetBrowserDesktopWindow(TRUE,FALSE,FALSE);
}
else if (pd.new_tab || pd.in_background)
{
return TRUE;
}
else
{
if (!pd.noraise)
RaiseWindow(bw);
}
g_input_manager->InvokeAction(OpInputAction::ACTION_COMPOSE_MAIL);
}
}
else if (cmd.Find("openFile") == 0)
{
if (ParseDestinationCommand(cmd, pd))
{
#if defined(DEBUG_IPC_PARSING)
DumpParsedData(pd);
#endif
if (pd.new_window)
{
g_application->GetBrowserDesktopWindow(TRUE,FALSE,FALSE);
}
else if (pd.new_tab)
{
if (!pd.noraise)
RaiseWindow(bw);
g_application->GetBrowserDesktopWindow(FALSE,FALSE,TRUE);
}
else if (pd.in_background)
{
return TRUE;
}
else
{
if (!pd.noraise)
RaiseWindow(bw);
}
g_input_manager->InvokeAction(OpInputAction::ACTION_OPEN_DOCUMENT);
}
}
else if (cmd.Find("addBookmark") == 0)
{
if (ParseOpenUrlCommand(cmd, pd))
{
#if defined(DEBUG_IPC_PARSING)
DumpParsedData(pd);
#endif
RaiseWindow(bw);
/*
HotlistManager::ItemData item_data;
INT32 id = -1;
BrowserDesktopWindow* bw = g_application->GetActiveBrowserDesktopWindow();
if (bw)
{
id = bw->GetSelectedHotlistItemId(OpTypedObject::PANEL_TYPE_BOOKMARKS);
}
item_data.url.Set( address );
item_data.name.Set( item_data.url.CStr() );
g_hotlist_manager->NewBookmark( item_data, id, NULL, TRUE );
*/
}
}
else if (cmd.Find("version") == 0)
{
X11Globals::ShowOperaVersion(TRUE, TRUE, bw);
}
else
{
return ParseWindowCommand(bw,cmd);
}
return TRUE;
}
BOOL ParseWindowCommand(DesktopWindow* dw, const OpString& cmd)
{
#if defined(DEBUG_IPC_PARSING)
OpString8 tmp;
tmp.Set(cmd);
printf("window target: %p, cmd: %s\n", dw, tmp.CStr());
#endif
if (!dw)
{
return FALSE;
}
if (cmd.Compare("raise()") == 0)
{
int p1 = cmd.FindFirstOf('(');
int p2 = cmd.FindLastOf(')');
if (p1 >= 0 && p1 < p2)
{
RaiseWindow(dw);
}
}
else if (cmd.Compare("lower()") == 0 )
{
int p1 = cmd.FindFirstOf('(');
int p2 = cmd.FindLastOf(')');
if (p1 >= 0 && p1 < p2)
{
LowerWindow(dw);
}
}
return TRUE;
}
BOOL ParseDestinationCommand(const OpString& cmd, ParsedData& pd)
{
int p1 = cmd.FindFirstOf('(');
int p2 = cmd.FindLastOf(')');
if (p1 == KNotFound || p2 == KNotFound || p1 > p2)
{
return FALSE;
}
OpString argument;
argument.Set(cmd.SubString(p1+1), p2-p1-1);
if (argument.IsEmpty())
{
return TRUE;
}
BOOL ok = FALSE;
const char* commands[] = { "new-window", "new-page", "new-tab", "new-private-tab", "background-page", "background-tab", 0 };
for (int i=0; commands[i]; i++)
{
int p4 = argument.Find(commands[i]);
if (p4 != KNotFound)
{
pd.new_window = i==0;
pd.new_tab = i==1 || i==2 || i==3 || i==4 || i==5;
pd.privacy_mode = i==3;
pd.in_background = i==4 || i==5;
if (i == 1 || i == 4)
printf("opera: 'new-page' and 'background-page' commands are deprecated and will stop working in a future version of opera. Use 'new-tab' or 'background-tab' instead.\n");
if (pd.new_window)
{
int p5 = argument.Find(UNI_L(",N="), p4);
if (p5 != KNotFound)
{
int p7 = argument.FindFirstOf(UNI_L(","), p5+3);
if( p7 == KNotFound)
p7 = argument.Length();
pd.window_name.Set(argument.SubString(p5+3),p7-p5-3);
pd.window_name.Strip();
}
int p6 = argument.Find(UNI_L(",G="), p4);
if (p6 != KNotFound)
{
int p7 = argument.FindFirstOf(UNI_L(","), p6+3);
if (p7 == KNotFound)
p7 = argument.Length();
OpString8 tmp;
tmp.Set(argument.SubString(p6+3),p7-p6-3);
pd.window_rect = X11Utils::ParseGeometry(tmp);
}
}
ok = TRUE;
break;
}
}
int p8 = argument.Find(UNI_L(",noraise"));
if (p8 != KNotFound)
{
pd.noraise = TRUE;
ok = TRUE;
}
return ok;
}
BOOL ParseOpenUrlCommand(const OpString& cmd, ParsedData& pd)
{
int p1 = cmd.FindFirstOf('(');
int p2 = cmd.FindLastOf(')');
if (p1 == KNotFound && p2 == KNotFound && p1 > p2)
{
return FALSE;
}
OpString argument;
argument.Set(cmd.SubString(p1+1), p2-p1-1);
if( argument.IsEmpty() )
{
return TRUE;
}
// Format openURL([url][,destnation][,N=name][,G=geometry][,noraise])
// Name and geometry have only meaning with new-window
int p4 = KNotFound;
const char* commands[] = { "new-window", "new-page", "new-tab", "new-private-tab", "background-page", "background-tab", 0 };
for (int i=0; commands[i]; i++)
{
p4 = argument.Find(commands[i]);
if (p4 != KNotFound)
{
pd.new_window = i==0;
pd.new_tab = i==1 || i==2 || i==3 || i==4 || i==5;
pd.privacy_mode = i==3;
pd.in_background = i==4 || i==5;
if (i == 1 || i == 4)
printf("opera: 'new-page' and 'background-page' commands are deprecated and will stop working in a future version of opera. Use 'new-tab' or 'background-tab' instead.\n");
if (pd.new_window)
{
int p5 = argument.Find(UNI_L(",N="), p4);
if (p5 != KNotFound)
{
int p7 = argument.FindFirstOf(UNI_L(","), p5+3);
if( p7 == KNotFound)
p7 = argument.Length();
pd.window_name.Set(argument.SubString(p5+3),p7-p5-3);
pd.window_name.Strip();
}
int p6 = argument.Find(UNI_L(",G="), p4);
if (p6 != KNotFound)
{
int p7 = argument.FindFirstOf(UNI_L(","), p6+3);
if( p7 == KNotFound)
p7 = argument.Length();
OpString8 tmp;
tmp.Set(argument.SubString(p6+3),p7-p6-3);
pd.window_rect = X11Utils::ParseGeometry(tmp);
}
}
break; // We are done
}
}
int p8 = argument.Find(UNI_L(",noraise"));
if (p8 != KNotFound)
{
pd.noraise = TRUE;
if (p4 == KNotFound)
p4 = p8;
}
if (p4 != KNotFound)
{
OpString tmp;
tmp.Set(argument.SubString(0),p4);
int p5 = tmp.FindLastOf(',');
if (p5 == KNotFound)
{
p5 = p4;
}
pd.address.Set(tmp.SubString(0),p5);
pd.address.Strip();
}
else
{
pd.address.Set(argument);
}
// resolve local files and convert from locale encoding
QuixCommandLineArgumentHandler::DecodeURL(pd.address);
return TRUE;
}
}
|
//======================================================================
#include <upl/st_code.hpp>
//======================================================================
namespace UPL {
namespace Type {
//======================================================================
#define TAG_INFO_STRUCT(v,e,s,b0,b1,b2,b3,b4) {Tag::e, s, b0, b1, b2, b3, b4},
static TagInfo_t const gsc_TagInfo [TagCount] = { UPL_PRIVATE__TYPE_TAGS(TAG_INFO_STRUCT) };
#undef TAG_INFO_STRUCT
#define TAG_CHECK_VALUE(v,e,s,b0,b1,b2,b3,b4) static_assert (int(gsc_TagInfo[v].tag) == v, "");
// :((
// Why can't I do this?!
//UPL_PRIVATE__TYPE_TAGS(TAG_CHECK_VALUE)
#undef TAG_CHECK_VALUE
//----------------------------------------------------------------------
TagInfo_t TagInfo (Tag tag)
{
assert (TagToInt(tag) < TagCount);
return gsc_TagInfo[TagToInt(tag)];
}
//======================================================================
PackedST Unpacked::pack () const
{
switch (tag)
{
case Tag::INVALID: return {};
case Tag::Nil: return STCode::Pack(STCode::MakeNil());
case Tag::Bool: return STCode::Pack(STCode::MakeBool(is_const));
case Tag::Byte: return STCode::Pack(STCode::MakeByte(is_const));
case Tag::Char: return STCode::Pack(STCode::MakeChar(is_const));
case Tag::Int: return STCode::Pack(STCode::MakeInt(is_const));
case Tag::Real: return STCode::Pack(STCode::MakeReal(is_const));
case Tag::String: return STCode::Pack(STCode::MakeString(is_const));
case Tag::Any: return STCode::Pack(STCode::MakeAny(is_const));
case Tag::Variant: return STCode::Pack(STCode::MakeVariant(is_const, {type_list.begin(), type_list.end()}));
case Tag::Array: return STCode::Pack(STCode::MakeArray(is_const, size, type1));
case Tag::Vector: return STCode::Pack(STCode::MakeVector(is_const, type1));
case Tag::Map: return STCode::Pack(STCode::MakeMap(is_const, type1, type2));
case Tag::Tuple: return STCode::Pack(STCode::MakeTuple(is_const, type_list));
case Tag::Package: return STCode::Pack(STCode::MakePackage(is_const, type_list));
case Tag::Function: return STCode::Pack(STCode::MakeFuction(is_const, type1, type_list));
default: assert(false); return {};
}
}
//======================================================================
STContainer::STContainer ()
: m_types ()
, m_stash ()
, m_lookup ()
{
m_stash.reserve (10000);
// Make the invalid entry
m_types.push_back ({});
m_types.back().bytes[0] = 0;
m_types.back().bytes[1] = 0;
m_types.back().bytes[2] = 0;
m_types.back().bytes[3] = 0;
// Make the rest of the default entries
auto t01 = createType(STCode::Pack(STCode::MakeNil())); assert ( 1 == t01);
auto t02 = createType(STCode::Pack(STCode::MakeBool(false))); assert ( 2 == t02);
auto t03 = createType(STCode::Pack(STCode::MakeBool(true))); assert ( 3 == t03);
auto t04 = createType(STCode::Pack(STCode::MakeByte(false))); assert ( 4 == t04);
auto t05 = createType(STCode::Pack(STCode::MakeByte(true))); assert ( 5 == t05);
auto t06 = createType(STCode::Pack(STCode::MakeChar(false))); assert ( 6 == t06);
auto t07 = createType(STCode::Pack(STCode::MakeChar(true))); assert ( 7 == t07);
auto t08 = createType(STCode::Pack(STCode::MakeInt(false))); assert ( 8 == t08);
auto t09 = createType(STCode::Pack(STCode::MakeInt(true))); assert ( 9 == t09);
auto t10 = createType(STCode::Pack(STCode::MakeReal(false))); assert (10 == t10);
auto t11 = createType(STCode::Pack(STCode::MakeReal(true))); assert (11 == t11);
auto t12 = createType(STCode::Pack(STCode::MakeString(false))); assert (12 == t12);
auto t13 = createType(STCode::Pack(STCode::MakeString(true))); assert (13 == t13);
auto t14 = createType(STCode::Pack(STCode::MakeAny(false))); assert (14 == t14);
auto t15 = createType(STCode::Pack(STCode::MakeAny(true))); assert (15 == t15);
}
//----------------------------------------------------------------------
STContainer::~STContainer ()
{
}
//----------------------------------------------------------------------
ID STContainer::createType (PackedST const & packed_st)
{
if (!STCode::IsValid(packed_st))
return InvalidID;
auto id = lookupType(packed_st);
if (InvalidID != id)
return id;
m_types.push_back ({});
ID cur_id = ID(m_types.size()) - 1;
auto & cur = m_types.back();
m_lookup[packed_st] = cur_id;
if (packed_st.size() <= sizeof(Entry)) // Put it in-line
{
cur.bytes[3] = cur.bytes[2] = cur.bytes[1] = cur.bytes[0] = 0;
for (size_t i = 0; i < packed_st.size() && i < 4; ++i)
cur.bytes[i] = packed_st[i];
setInlineEntry (cur_id, true);
}
else // Put it in the stash
{
auto stash_index = stashCurPos();
m_stash += packed_st;
assert (m_stash.size() == stash_index + packed_st.size());
setStashIndex (cur_id, stash_index);
}
return cur_id;
}
//----------------------------------------------------------------------
ID STContainer::createType (Unpacked const & unpacked)
{
return createType(unpacked.pack());
}
//----------------------------------------------------------------------
ID STContainer::lookupType (PackedST const & packed_st) const
{
auto i = m_lookup.find(packed_st);
if (m_lookup.end() != i)
return i->second;
else
return InvalidID;
}
//----------------------------------------------------------------------
ID STContainer::byTag (Tag tag) const
{
auto const i = TagToInt(tag);
if (i > 0 && i < TagToInt(Tag::Variant))
return ID(i);
else
return InvalidID;
}
//----------------------------------------------------------------------
Unpacked STContainer::unpack (ID id) const
{
auto t = tag(id);
auto c = isConst(id);
Unpacked ret (t, c);
switch (t)
{
case Tag::Variant:
ret.type_list = getVariantTypes(id);
break;
case Tag::Array:
ret.size = getArraySize(id);
ret.type1 = getArrayType(id);
break;
case Tag::Vector:
ret.type1 = getVectorType(id);
break;
case Tag::Map:
ret.type1 = getMapKeyType(id);
ret.type2 = getMapValueType(id);
break;
case Tag::Tuple:
ret.type_list = getTupleTypes(id);
break;
case Tag::Package:
ret.type_list = getPackageTypes(id);
break;
case Tag::Function:
ret.type1 = getFunctionReturnType(id);
ret.type_list = getFunctionParamTypes(id);
break;
case Tag::Nil:
/* TODO */
break;
case Tag::Bool:
/* TODO */
break;
case Tag::Byte:
/* TODO */
break;
case Tag::Char:
/* TODO */
break;
case Tag::Int:
/* TODO */
break;
case Tag::Real:
/* TODO */
break;
case Tag::String:
/* TODO */
break;
case Tag::Any:
/* TODO */
break;
case Tag::INVALID:
/* TODO */
break;
};
return ret;
}
//----------------------------------------------------------------------
//----------------------------------------------------------------------
std::vector<ID> STContainer::getTypeList (ID id) const
{
assert (tag(id) == Tag::Variant || tag(id) == Tag::Tuple || tag(id) == Tag::Package);
auto qfetch = [this, id](int q){return this->getQuartet(id, q);};
int q = 0;
size_t cnt = STCode::DeserializeInt (qfetch, q);
std::vector<ID> ret (cnt);
for (size_t i = 0; i < cnt; ++i)
ret[i] = STCode::DeserializeInt (qfetch, q);
return ret;
}
//----------------------------------------------------------------------
std::vector<ID> STContainer::getParamTypeList (ID id) const
{
assert (tag(id) == Tag::Function);
auto qfetch = [this, id](int q){return this->getQuartet(id, q);};
int q = 0;
STCode::DeserializeInt (qfetch, q);
size_t cnt = STCode::DeserializeInt (qfetch, q);
std::vector<ID> ret (cnt);
for (size_t i = 0; i < cnt; ++i)
ret[i] = STCode::DeserializeInt (qfetch, q);
return ret;
}
//----------------------------------------------------------------------
ID STContainer::getFirstType (ID id) const
{
assert (tag(id) == Tag::Vector || tag(id) == Tag::Map || tag(id) == Tag::Function);
auto qfetch = [this, id](int q){return this->getQuartet(id, q);};
int q = 0;
return STCode::DeserializeInt (qfetch, q);
}
//----------------------------------------------------------------------
ID STContainer::getSecondType (ID id) const
{
assert (tag(id) == Tag::Array || tag(id) == Tag::Map);
auto qfetch = [this, id](int q){return this->getQuartet(id, q);};
int q = 0;
STCode::DeserializeInt (qfetch, q);
return STCode::DeserializeInt (qfetch, q);
}
//----------------------------------------------------------------------
Size STContainer::getSize (ID id) const
{
assert (tag(id) == Tag::Array);
auto qfetch = [this, id](int q){return this->getQuartet(id, q);};
int q = 0;
return STCode::DeserializeInt (qfetch, q);
}
//----------------------------------------------------------------------
//======================================================================
} // namespace Type
} // namespace UPL
//======================================================================
|
#include <bits/stdc++.h>
using namespace std;
#define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0)
#define MAXN 100
int main(int argc, char const *argv[])
{
string str;
while( getline(cin,str) ){
list <char> text;
auto Iter = text.begin();
for(int i = 0 ; i < str.size() ; i++ ){
if( str[i] == '[' )
Iter = text.begin();
else if( str[i] == ']' )
Iter = text.end();
else
text.insert(Iter, str[i]);
}
for(auto i: text)
cout << i;
printf("\n");
}
return 0;
}
|
#include "msg_0x11_usebed_stc.h"
namespace MC
{
namespace Protocol
{
namespace Msg
{
UseBed::UseBed()
{
_pf_packetId = static_cast<int8_t>(0x11);
_pf_initialized = false;
}
UseBed::UseBed(int32_t _entityId, int8_t _unknown, int32_t _x, int8_t _y, int32_t _z)
: _pf_entityId(_entityId)
, _pf_unknown(_unknown)
, _pf_x(_x)
, _pf_y(_y)
, _pf_z(_z)
{
_pf_packetId = static_cast<int8_t>(0x11);
_pf_initialized = true;
}
size_t UseBed::serialize(Buffer& _dst, size_t _offset)
{
_pm_checkInit();
if(_offset == 0) _dst.clear();
_offset = WriteInt8(_dst, _offset, _pf_packetId);
_offset = WriteInt32(_dst, _offset, _pf_entityId);
_offset = WriteInt8(_dst, _offset, _pf_unknown);
_offset = WriteInt32(_dst, _offset, _pf_x);
_offset = WriteInt8(_dst, _offset, _pf_y);
_offset = WriteInt32(_dst, _offset, _pf_z);
return _offset;
}
size_t UseBed::deserialize(const Buffer& _src, size_t _offset)
{
_offset = _pm_checkPacketId(_src, _offset);
_offset = ReadInt32(_src, _offset, _pf_entityId);
_offset = ReadInt8(_src, _offset, _pf_unknown);
_offset = ReadInt32(_src, _offset, _pf_x);
_offset = ReadInt8(_src, _offset, _pf_y);
_offset = ReadInt32(_src, _offset, _pf_z);
_pf_initialized = true;
return _offset;
}
int32_t UseBed::getEntityId() const { return _pf_entityId; }
int8_t UseBed::getUnknown() const { return _pf_unknown; }
int32_t UseBed::getX() const { return _pf_x; }
int8_t UseBed::getY() const { return _pf_y; }
int32_t UseBed::getZ() const { return _pf_z; }
void UseBed::setEntityId(int32_t _val) { _pf_entityId = _val; }
void UseBed::setUnknown(int8_t _val) { _pf_unknown = _val; }
void UseBed::setX(int32_t _val) { _pf_x = _val; }
void UseBed::setY(int8_t _val) { _pf_y = _val; }
void UseBed::setZ(int32_t _val) { _pf_z = _val; }
} // namespace Msg
} // namespace Protocol
} // namespace MC
|
// Parses a sequence of texts into separate lines. Client defines
// the delimiter. Parsed output is returned as a vector of strings.
#ifndef UTILS_FILE_FILEWRITER_H_
#define UTILS_FILE_FILEWRITER_H_
#include <string>
#include "utils/error_handling/status.h"
namespace utils {
namespace file {
namespace filewriter {
using utils::error_handling::Status;
class FileWriter {
public:
static Status Open(const std::string& filepath);
static void OpenOrDie(const std::string& filepath);
static void WriteTo(const std::string& filepath);
};
} // namespace filewriter
} // namespace file
} // namespace utils
#endif
|
#ifndef _TRANSITION_
#define _TRANSITION_
#include <SFML/Graphics.hpp>
class State;
typedef struct TransitionState
{
sf::Time time = sf::Time::Zero;
sf::Vector2f position = sf::Vector2f(0, 0);
//sf::Vector2f scale = sf::Vector2f( 0, 0 );
//sf::Vector2f rotation = sf::Vector2f( 0, 0 );
sf::Color color = sf::Color::Transparent;
} TransitionState;
class Transition
{
public :
Transition( const std::string &path );
~Transition();
void start() { m_isStarted = true; }
bool isStarted() { return m_isStarted; }
bool isEnded() { return m_isEnded; }
virtual void draw( State * s, sf::RenderTarget& target, sf::RenderStates states ) const;
virtual void update();
private:
bool m_isStarted;
bool m_isEnded;
sf::Time m_timer;
std::vector< TransitionState > m_states;
};
#endif // _TRANSITION_
|
#include <iostream>
#pragma comment(linker, "/entry:print")
int print()
{
printf("hello world\n");
return 0;
}
int main(void)
{
return 0;
}
|
/* ***** BEGIN LICENSE BLOCK *****
* FW4SPL - Copyright (C) IRCAD, 2012-2013.
* Distributed under the terms of the GNU Lesser General Public License (LGPL) as
* published by the Free Software Foundation.
* ****** END LICENSE BLOCK ****** */
#ifndef _GDCMIO_DICOMDISTANCE_HPP_
#define _GDCMIO_DICOMDISTANCE_HPP_
#include <string>
#include <vector>
#include <fwData/Image.hpp>
#include <fwData/macros.hpp>
#include "gdcmIO/config.hpp"
#include "gdcmIO/DicomSCoord.hpp"
namespace gdcmIO
{
/**
* @brief This class define a container of distances to translate
* in DICOM/FW4SPL form.
* @class DicomDistance
* @author IRCAD (Research and Development Team).
* @date 2011.
*/
class GDCMIO_CLASS_API DicomDistance
{
public :
GDCMIO_API DicomDistance();
GDCMIO_API ~DicomDistance();
/**
* @brief Set distances data in an image.
*
* @param a_image Image where distances could be inserted.
*/
GDCMIO_API void convertToData(::fwData::Image::sptr a_image);
/**
* @brief Get distances data from an image and convert it to a closed DICOM form.
*
* @param a_image Image which can contain distances.
*/
GDCMIO_API void setFromData(::fwData::Image::csptr a_image) throw (::fwTools::Failed);
GDCMIO_API fwGettersSettersDocMacro(SCoords, SCoords, std::vector<SCoord>, Spatial coordinates container (eg : coordinates on x, y axis));
GDCMIO_API fwGettersSettersDocMacro(Dists, dists, std::vector<std::string>, Distance values container (e.g: distance value for each distance: "301.256"));
GDCMIO_API fwGettersSettersDocMacro(RefFrames, refFrames, std::vector<std::string>, SSlice numbers container (equal to coordinates on z axis of 2 points));
/**
* @brief Add a distance value in the container.
*
* @param a_dist Distance value.
*/
GDCMIO_API void addDist(const std::string & a_dist);
/**
* @brief Add coordinates for one distance in the container.
*
* @param a_coord Coordinates of 2 points.
*/
GDCMIO_API void addSCoord(const SCoord & a_scoord);
/**
* @brief Add slice numbers for one distance in the container.
*
* @param a_refFrame Slice numbers of 2 points.
*/
GDCMIO_API void addRefFrame(const std::string & a_refFrame);
private :
std::vector<SCoord> m_SCoords; ///< Coordinates container (equal to coordinates on x, y axis of 2 points).
///< (e.g: coordinates for each distance : "x1\y1\x2\y2").
std::vector<std::string> m_dists; ///< Distance values container (e.g: distance value for each distance: "301.256").
std::vector<std::string> m_refFrames; ///< Slice numbers container (equal to coordinates on z axis of 2 points).
///< (e.g: Slice numbers for each distance: "4\205").
};
} // namespace gdcmIO
#endif /* _GDCMIO_DICOMDISTANCE_HPP_ */
|
/*====================================================================
Copyright(c) 2018 Adam Rankin
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
// Local includes
#include "IEngineComponent.h"
// STL includes
#include <mutex>
namespace HoloIntervention
{
namespace Input
{
class SpatialSourceHandler;
class SpatialInput : public IEngineComponent
{
public:
typedef std::function<void(uint32)> SourceCallbackFunc;
public:
SpatialInput();
~SpatialInput();
void Update(Windows::Perception::Spatial::SpatialCoordinateSystem^ coordinateSystem);
uint64 RegisterSourceObserver(SourceCallbackFunc detectedCallback, SourceCallbackFunc lostCallback, SourceCallbackFunc genericPressCallback);
bool UnregisterSourceObserver(uint64 observerId);
std::shared_ptr<SpatialSourceHandler> GetSourceHandlerById(uint32 sourceId);
protected:
void OnSourceDetected(Windows::UI::Input::Spatial::SpatialInteractionManager^ sender, Windows::UI::Input::Spatial::SpatialInteractionSourceEventArgs^ args);
void OnSourceLost(Windows::UI::Input::Spatial::SpatialInteractionManager^ sender, Windows::UI::Input::Spatial::SpatialInteractionSourceEventArgs^ args);
void OnSourcePressed(Windows::UI::Input::Spatial::SpatialInteractionManager^ sender, Windows::UI::Input::Spatial::SpatialInteractionSourceEventArgs^ args);
void OnSourceUpdated(Windows::UI::Input::Spatial::SpatialInteractionManager^ sender, Windows::UI::Input::Spatial::SpatialInteractionSourceEventArgs^ args);
std::shared_ptr<SpatialSourceHandler> GetFirstSourceHandlerByKind(Windows::UI::Input::Spatial::SpatialInteractionSourceKind kind);
protected:
Windows::UI::Input::Spatial::SpatialInteractionManager^ m_interactionManager = nullptr;
Windows::Perception::Spatial::SpatialCoordinateSystem^ m_referenceFrame = nullptr;
Windows::Foundation::EventRegistrationToken m_sourceLostEventToken;
Windows::Foundation::EventRegistrationToken m_sourceDetectedEventToken;
Windows::Foundation::EventRegistrationToken m_sourcePressedEventToken;
Windows::Foundation::EventRegistrationToken m_sourceUpdatedEventToken;
std::mutex m_sourceMutex;
std::map<uint32, std::shared_ptr<SpatialSourceHandler>> m_sourceMap;
std::map<uint64, SourceCallbackFunc> m_sourceDetectedObservers;
std::map<uint64, SourceCallbackFunc> m_sourceLostObservers;
std::map<uint64, SourceCallbackFunc> m_genericPressObservers;
uint64 m_nextSourceObserverId = INVALID_TOKEN + 1;
};
}
}
|
#ifndef RSA_H_INCLUDED
#define RSA_H_INCLUDED
#include <iostream>
using namespace std;
class RSA
{
private:
int clavePrivada1;
public:
int clavePublica1;
int nyYa;
void generadorClaves();
RSA();
void mostrarDatos();
int cifrado(int, int, string);
string descifrado(int);
string descifrado2();
};
#endif // RSA_H_INCLUDED
|
/*
* Copyright 2017, Victor van der Veen
*
* 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 __DYNINST_CFG_CONSTRUCTION__
#define __DYNINST_CFG_CONSTRUCTION__
class ArmsFunctionWithAddress;
class DICFG : public CFG {
static Expression::Ptr the_pc;
public:
DICFG(const char *module_name) : CFG(module_name) {}
// ParseAPI based
void insert_functions_and_bbs(const CodeObject::funclist& funcs);
void insert_edges(const CodeObject::funclist& funcs);
//
// BPatch_API based
void insert_functions(std::vector<BPatch_function *> *funcs);
void insert_plt_entries(Symtab *symtab);
void insert_interprocedural_edges(std::vector<BPatch_function *> *funcs);
void analyze_unresolved_control_transfers(std::vector<BPatch_function *> *funcs);
BPatch_addressSpace *handle;
BPatch_image *image;
//
private:
// ParseAPI based
void copy_edge_type(ArmsEdge *arms_edge, ParseAPI::Edge *edge, bool indirect);
//
// BPatch_API based
void insert_intraprocedural_function_flow_graph(BPatch_function *fun);
void copy_edge_type(ArmsEdge *arms_edge, BPatch_edge *bp_edge, bool intra);
void set_entry_and_exit_points_of_function(BPatch_function *fun);
void insert_interprocedural_edge(ArmsFunction *arms_fun, BPatch_point *call_point);
//
};
void dyninst_analyze_address_taken_deprecated(const char *bin, const char **argv, DICFG *cfg);
DICFG* dyninst_build_cfg_deprecated(const char *bin, const char **argv);
void dyninst_analyze_address_taken(BPatch_addressSpace *handle, DICFG *cfg);
DICFG* dyninst_build_cfg(BPatch_addressSpace *handle, int index);
#endif
|
// Problem No. 2 => Find the repeating and the missing
#include <bits/stdc++.h>
using namespace std;
void printTwoElements(int arr[], int size)
{
int i;
cout << " The repeating element is ";
for (i = 0; i < size; i++) {
if (arr[abs(arr[i]) - 1] > 0)
arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1];
else
cout << abs(arr[i]) << "\n";
}
cout << "and the missing element is ";
for (i = 0; i < size; i++) {
if (arr[i] > 0)
cout << (i + 1);
}
}
int main()
{
int arr[] = { 7, 3, 4, 5, 5, 6, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
printTwoElements(arr, n);
}
/*
1. In the first approach we will initialize a frequency array of size 7. (Suppose we are given an array of size 6 in question)
@Let us consider the array given in question as A1 and frequency array that we created as A2. A1 = {4,3,6,2,1,1,}
and A2 = {0,0,0,0,0,0,0}
@ What we will do we will traves the array A1 and we will find the number 4, so we will update the value in A2 array at location 4 by one.
And follow this step and continue to traverse the array A1.
@ Than after traversing the whole A1 array, what will happen at some index point in A2 array value will be 1 at some index value will be 2 and at
some index value will be 0.
@ So where the value is 2 we can say that location is repeating in array A1, similarly the index with 0 value is missing from array A1.
@ Time complexity of this will be O(2n) and space complexity will be O(n)
2. The code here that I have writte use this approach "Use elements as Index and mark the visited places."
@ Traverse the array. While traversing, use the absolute value of every element as index and make the value at this
index as negative to mark it visited. If something is already marked negative then this is the repeating element.
To find missing, traverse the array again and look for a positive value.
*/
|
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
ShowWindow(GetConsoleWindow(), SW_HIDE); //Скроем консоль на всякий случай
QApplication a(argc, argv);
MainWindow w;
system("chcp 1251");
w.show();
auto g = std::async(MainWindow::Change); //Запускаем функцию Change(которая в бесконечном цикле чекает какая клавиша сейчас нажата)
//Но не просто запускаем, а запускаем асинхронно, то есть мы не будем ждать её выполнения (а она не выполнится, т.к. цикл бесконечный) и будем работать с визуальной менюшкой
return a.exec();
}
|
// Created on: 1998-08-26
// Created by: Julia GERASIMOVA
// Copyright (c) 1998-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _BRepOffsetAPI_MakeFilling_HeaderFile
#define _BRepOffsetAPI_MakeFilling_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <BRepFill_Filling.hxx>
#include <BRepBuilderAPI_MakeShape.hxx>
#include <Standard_Boolean.hxx>
#include <Standard_Real.hxx>
#include <GeomAbs_Shape.hxx>
#include <TopTools_ListOfShape.hxx>
class TopoDS_Face;
class TopoDS_Edge;
class gp_Pnt;
class TopoDS_Shape;
//! N-Side Filling
//! This algorithm avoids to build a face from:
//! * a set of edges defining the bounds of the face and some
//! constraints the surface of the face has to satisfy
//! * a set of edges and points defining some constraints
//! the support surface has to satisfy
//! * an initial surface to deform for satisfying the constraints
//! * a set of parameters to control the constraints.
//!
//! The support surface of the face is computed by deformation
//! of the initial surface in order to satisfy the given constraints.
//! The set of bounding edges defines the wire of the face.
//!
//! If no initial surface is given, the algorithm computes it
//! automatically.
//! If the set of edges is not connected (Free constraint)
//! missing edges are automatically computed.
//!
//! Limitations:
//! * If some constraints are not compatible
//! The algorithm does not take them into account.
//! So the constraints will not be satisfyed in an area containing
//! the incompatibilitries.
//! * The constraints defining the bound of the face have to be
//! entered in order to have a continuous wire.
//!
//! Other Applications:
//! * Deformation of a face to satisfy internal constraints
//! * Deformation of a face to improve Gi continuity with
//! connected faces
class BRepOffsetAPI_MakeFilling : public BRepBuilderAPI_MakeShape
{
public:
DEFINE_STANDARD_ALLOC
//! Constructs a wire filling object defined by
//! - the energy minimizing criterion Degree
//! - the number of points on the curve NbPntsOnCur
//! - the number of iterations NbIter
//! - the Boolean Anisotropie
//! - the 2D tolerance Tol2d
//! - the 3D tolerance Tol3d
//! - the angular tolerance TolAng
//! - the tolerance for curvature TolCur
//! - the highest polynomial degree MaxDeg
//! - the greatest number of segments MaxSeg.
//! If the Boolean Anistropie is true, the algorithm's
//! performance is better in cases where the ratio of the
//! length U and the length V indicate a great difference
//! between the two. In other words, when the surface is, for
//! example, extremely long.
Standard_EXPORT BRepOffsetAPI_MakeFilling(const Standard_Integer Degree = 3, const Standard_Integer NbPtsOnCur = 15, const Standard_Integer NbIter = 2, const Standard_Boolean Anisotropie = Standard_False, const Standard_Real Tol2d = 0.00001, const Standard_Real Tol3d = 0.0001, const Standard_Real TolAng = 0.01, const Standard_Real TolCurv = 0.1, const Standard_Integer MaxDeg = 8, const Standard_Integer MaxSegments = 9);
//! Sets the values of Tolerances used to control the constraint.
//! Tol2d:
//! Tol3d: it is the maximum distance allowed between the support surface
//! and the constraints
//! TolAng: it is the maximum angle allowed between the normal of the surface
//! and the constraints
//! TolCurv: it is the maximum difference of curvature allowed between
//! the surface and the constraint
Standard_EXPORT void SetConstrParam (const Standard_Real Tol2d = 0.00001, const Standard_Real Tol3d = 0.0001, const Standard_Real TolAng = 0.01, const Standard_Real TolCurv = 0.1);
//! Sets the parameters used for resolution.
//! The default values of these parameters have been chosen for a good
//! ratio quality/performance.
//! Degree: it is the order of energy criterion to minimize for computing
//! the deformation of the surface.
//! The default value is 3
//! The recommended value is i+2 where i is the maximum order of the
//! constraints.
//! NbPtsOnCur: it is the average number of points for discretisation
//! of the edges.
//! NbIter: it is the maximum number of iterations of the process.
//! For each iteration the number of discretisation points is
//! increased.
//! Anisotropie:
Standard_EXPORT void SetResolParam (const Standard_Integer Degree = 3, const Standard_Integer NbPtsOnCur = 15, const Standard_Integer NbIter = 2, const Standard_Boolean Anisotropie = Standard_False);
//! Sets the parameters used to approximate the filling
//! surface. These include:
//! - MaxDeg - the highest degree which the polynomial
//! defining the filling surface can have
//! - MaxSegments - the greatest number of segments
//! which the filling surface can have.
Standard_EXPORT void SetApproxParam (const Standard_Integer MaxDeg = 8, const Standard_Integer MaxSegments = 9);
//! Loads the initial surface Surf to
//! begin the construction of the surface.
//! This optional function is useful if the surface resulting from
//! construction for the algorithm is likely to be complex.
//! The support surface of the face under construction is computed by a
//! deformation of Surf which satisfies the given constraints.
//! The set of bounding edges defines the wire of the face.
//! If no initial surface is given, the algorithm computes it
//! automatically. If the set of edges is not connected (Free constraint),
//! missing edges are automatically computed.
//! Important: the initial surface must have orthogonal local coordinates,
//! i.e. partial derivatives dS/du and dS/dv must be orthogonal
//! at each point of surface.
//! If this condition breaks, distortions of resulting surface
//! are possible.
Standard_EXPORT void LoadInitSurface (const TopoDS_Face& Surf);
//! Adds a new constraint which also defines an edge of the wire
//! of the face
//! Order: Order of the constraint:
//! GeomAbs_C0 : the surface has to pass by 3D representation
//! of the edge
//! GeomAbs_G1 : the surface has to pass by 3D representation
//! of the edge and to respect tangency with the first
//! face of the edge
//! GeomAbs_G2 : the surface has to pass by 3D representation
//! of the edge and to respect tangency and curvature
//! with the first face of the edge.
//! Raises ConstructionError if the edge has no representation on a face and Order is
//! GeomAbs_G1 or GeomAbs_G2.
Standard_EXPORT Standard_Integer Add (const TopoDS_Edge& Constr, const GeomAbs_Shape Order, const Standard_Boolean IsBound = Standard_True);
//! Adds a new constraint which also defines an edge of the wire
//! of the face
//! Order: Order of the constraint:
//! GeomAbs_C0 : the surface has to pass by 3D representation
//! of the edge
//! GeomAbs_G1 : the surface has to pass by 3D representation
//! of the edge and to respect tangency with the
//! given face
//! GeomAbs_G2 : the surface has to pass by 3D representation
//! of the edge and to respect tangency and curvature
//! with the given face.
//! Raises ConstructionError if the edge has no 2d representation on the given face
Standard_EXPORT Standard_Integer Add (const TopoDS_Edge& Constr, const TopoDS_Face& Support, const GeomAbs_Shape Order, const Standard_Boolean IsBound = Standard_True);
//! Adds a free constraint on a face. The corresponding edge has to
//! be automatically recomputed. It is always a bound.
Standard_EXPORT Standard_Integer Add (const TopoDS_Face& Support, const GeomAbs_Shape Order);
//! Adds a punctual constraint.
Standard_EXPORT Standard_Integer Add (const gp_Pnt& Point);
//! Adds a punctual constraint.
Standard_EXPORT Standard_Integer Add (const Standard_Real U, const Standard_Real V, const TopoDS_Face& Support, const GeomAbs_Shape Order);
//! Builds the resulting faces
Standard_EXPORT virtual void Build(const Message_ProgressRange& theRange = Message_ProgressRange()) Standard_OVERRIDE;
//! Tests whether computation of the filling plate has been completed.
Standard_EXPORT virtual Standard_Boolean IsDone() const Standard_OVERRIDE;
//! Returns the list of shapes generated from the
//! shape <S>.
Standard_EXPORT virtual const TopTools_ListOfShape& Generated (const TopoDS_Shape& S) Standard_OVERRIDE;
//! Returns the maximum distance between the result and
//! the constraints. This is set at construction time.
Standard_EXPORT Standard_Real G0Error() const;
//! Returns the maximum angle between the result and the
//! constraints. This is set at construction time.
Standard_EXPORT Standard_Real G1Error() const;
//! Returns the maximum angle between the result and the
//! constraints. This is set at construction time.
Standard_EXPORT Standard_Real G2Error() const;
//! Returns the maximum distance attained between the
//! result and the constraint Index. This is set at construction time.
Standard_EXPORT Standard_Real G0Error (const Standard_Integer Index);
//! Returns the maximum angle between the result and the
//! constraints. This is set at construction time.
Standard_EXPORT Standard_Real G1Error (const Standard_Integer Index);
//! Returns the greatest difference in curvature found
//! between the result and the constraint Index.
Standard_EXPORT Standard_Real G2Error (const Standard_Integer Index);
protected:
private:
BRepFill_Filling myFilling;
};
#endif // _BRepOffsetAPI_MakeFilling_HeaderFile
|
#ifndef ROUTE_H
#define ROUTE_H
#include <QString>
namespace wpp
{
namespace qt
{
class Route
{
private:
QString m_name;
QString m_method;
QString m_host;
QString m_pattern;
public:
Route() {} //default-constructor needed by QMap, create an INVALID Route
Route(const QString& name, const QString method, const QString& host, const QString& pattern)
: m_name(name), m_method(method), m_host(host), m_pattern(pattern)
{
}
Route(const Route& route)//copy-constructor needed by QMap
//: Route(route.m_name, route.m_method, route.m_pattern)
: m_name(route.m_name), m_method(route.m_method), m_host(route.m_host), m_pattern(route.m_pattern)
{
}
const QString& name() const { return m_name; }
const QString& method() const { return m_method; }
const QString& host() const { return m_host; }
const QString& pattern() const { return m_pattern; }
bool isValid() const { return !m_host.isEmpty() && !m_pattern.isEmpty() && !m_method.isEmpty(); }
};
}//namespace qt
}//namespace wpp
#endif
|
#ifndef ARISTA_H
#define ARISTA_H
#include <QString>
#include <QDebug>
class Arista{
public:
QString origen;
QString destino;
double costo, km, min;
bool activo;
Arista(QString pOrigen, QString pDestino, bool pActivo, double pCosto, double pKm, double pMin){
this->origen = pOrigen;
this->destino = pDestino;
this->activo = pActivo;
this->costo = pCosto;
this->km = pKm;
this->min = pMin;
}
void imprimir(){
qDebug()<<"Destino: "+this->destino<<"Costo: "+QString::number(this->costo)+
", KM: "+QString::number(this->km)+", Min: "+QString::number(this->min);
}
};
#endif // ARISTA_H
|
/*
Name:
Copyright:
Author: Xiaodong Xiao
Date: 2019/10/30 21:31:55
Description:
*/
#include <bits/stdc++.h>
using namespace std;
int main() {
return 0;
}
|
#include "object\\DiffObject.h"
#include "Reference.h"
DiffObject::DiffObject(Vector2 vec) : Object(vec), accel(Ref::VectorZero) {
alpha = 0, fade = 24;
shouldRender = true;
}
Vector2 DiffObject::GetAccel() const {
return accel;
}
void DiffObject::SetAlpha(int alphaIn) {
alpha = alphaIn;
}
void DiffObject::Update() {
Object::Update();
if (accel.x <= -1.0f) {
accel.x += 1.0f;
offset.x += accel.x;
}
else if (accel.x >= 1.0f) {
accel.x -= 1.0f;
offset.x += accel.x;
}
if (accel.y <= -1.0f) {
accel.y += 1.0f;
offset.y += accel.y;
}
else if (accel.y >= 1.0f) {
accel.y -= 1.0f;
offset.y += accel.y;
}
}
void DiffObject::Draw() const {
Object::Draw();
}
|
#include"stdio.h"
#include"conio.h"
void main(void)
{
int a,b;
clrscr();
for(a=1; b<=50; b++)
{
b=a*a;
printf("%d %d\n",a,b);
}
getch();
}
|
void f() {
throw 1;
}
|
/*
==========================================
Copyright (c) 2016-2018 Dynamic_Static
Patrick Purcell
Licensed under the MIT license
http://opensource.org/licenses/MIT
==========================================
*/
#pragma once
#include "Dynamic_Static/Core/Defines.hpp"
#include "Dynamic_Static/Core/StringView.hpp"
#include <fstream>
#include <vector>
namespace dst {
namespace File {
/*!
Reads all lines in the file at the given file path.
@param [in] filePath The path to the file to read
@param [in] lines An std::vector<std::string> to populate with the lines read from the file
*/
inline void read_all_lines(
StringView filePath,
std::vector<std::string>& lines
)
{
lines.clear();
std::ifstream file(filePath.data());
if (file.is_open()) {
std::string line;
while (std::getline(file, line)) {
lines.push_back(line);
}
}
}
/*!
Reads all lines in the file at the given file path.
@param [in] filePath The path to the file to read
@param [in] lines An std::vector<std::string> populated with the lines read from the file
*/
inline std::vector<std::string> read_all_lines(StringView filePath)
{
std::vector<std::string> lines;
read_all_lines(filePath, lines);
return lines;
}
/*!
Reads all bytes in the file at the given file path.
@param [in] filePath The path to the file to read
@param [in] lines An std::vector<std::byte> to populate with the bytes read from the file
*/
inline void read_all_bytes(
StringView filePath,
std::vector<std::byte>& bytes
)
{
bytes.clear();
std::ifstream file(filePath.data(), std::ios::binary | std::ios::ate);
if (file.is_open()) {
auto size = file.tellg();
bytes.resize((size_t)size);
file.seekg(0, std::ios::beg);
file.read((char*)bytes.data(), size);
}
}
/*!
Reads all bytes in the file at the given file path.
@param [in] filePath The path to the file to read
@param [in] lines An std::vector<std::byte> populated with the bytes read from the file
*/
inline std::vector<std::byte> read_all_bytes(StringView filePath)
{
std::vector<std::byte> bytes;
read_all_bytes(filePath, bytes);
return bytes;
}
} // namespace File
} // namespace dst
|
#ifndef UTILS_H
#define UTILS_H
#include "../includes.h"
#include <QFileInfo>
void showColorModel(uchar* &C1,uchar* &C2,uchar* &C3,int rows,int cols,cv::String name);
void showColorImage(uchar* &R,uchar* &G,uchar* &B,int rows,int cols,cv::String name);
void abrir_imagen (uchar* &R,uchar* &G,uchar* &B,int &rows, int &cols, const std::string &pathTo);
void rgb2mat(uchar* &R,uchar* &G,uchar* &B,int &rows, int &cols, cv::Mat &image);
bool check_BMP_format(const std::string &pathTo);
bool checkImageformat(const std::string &pathTo);
bool checkVideoformat(const std::string &pathTo);
#endif // UTILS_H
|
/* -*-mode:c++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
#include "engine_gg.hh"
#include <stdexcept>
#include "response.hh"
#include "net/http_response.hh"
#include "thunk/ggutils.hh"
#include "util/optional.hh"
#include "util/system_runner.hh"
#include "util/units.hh"
#include "util/base64.hh"
#include "util/iterator.hh"
using namespace std;
using namespace gg;
using namespace gg::thunk;
HTTPRequest GGExecutionEngine::generate_request( const Thunk & thunk )
{
string payload = Thunk::execution_payload( thunk );
HTTPRequest request;
request.set_first_line( "POST / HTTP/1.1" );
request.add_header( HTTPHeader{ "Content-Length", to_string( payload.size() ) } );
request.add_header( HTTPHeader{ "Host", "gg-run-server" } );
request.done_with_headers();
request.read_in_body( payload );
assert( request.state() == COMPLETE );
return request;
}
void GGExecutionEngine::force_thunk( const Thunk & thunk,
ExecutionLoop & exec_loop )
{
/* Add dependencies to cache! */
cache_.access(thunk.hash(), true);
for (auto & item : join_containers(thunk.values(), thunk.executables())) {
cache_.access(item.first, true);
}
HTTPRequest request = generate_request( thunk );
exec_loop.make_http_request<TCPConnection>( thunk.hash(),
address_, request,
[this, thunk] ( const uint64_t, const string & thunk_hash,
const HTTPResponse & http_response ) -> bool
{
running_jobs_--;
if ( http_response.status_code() != "200" ) {
failure_callback_( thunk_hash, JobStatus::InvocationFailure );
return false;
}
ExecutionResponse response = ExecutionResponse::parse_message( http_response.body() );
/* print the output, if there's any */
if ( response.stdout.length() ) {
cerr << response.stdout << endl;
}
switch ( response.status ) {
case JobStatus::Success:
{
if ( response.thunk_hash != thunk_hash ) {
cerr << http_response.str() << endl;
throw runtime_error( "expected output for " +
thunk_hash + ", got output for " +
response.thunk_hash );
}
for ( const auto & output : response.outputs ) {
gg::cache::insert( gg::hash::for_output( response.thunk_hash, output.tag ), output.hash );
if ( output.data.length() ) {
roost::atomic_create( base64::decode( output.data ),
gg::paths::blob( output.hash ) );
}
}
gg::cache::insert( response.thunk_hash, response.outputs.at( 0 ).hash );
/* Unpin dependencies from cache! */
cache_.unpin(thunk.hash());
for (auto & item : join_containers(thunk.values(), thunk.executables())) {
cache_.unpin(item.first);
}
vector<ThunkOutput> thunk_outputs;
for ( auto & output : response.outputs ) {
cache_.access(output.hash, false);
thunk_outputs.emplace_back( move( output.hash ), move( output.tag ) );
}
success_callback_( response.thunk_hash, move( thunk_outputs ), 0 );
cache_.cleanup();
break;
}
default: /* in case of any other failure */
failure_callback_( thunk_hash, response.status );
}
return false;
},
[this] ( const uint64_t, const string & thunk_hash )
{
failure_callback_( thunk_hash, JobStatus::SocketFailure );
}
);
running_jobs_++;
}
size_t GGExecutionEngine::job_count() const
{
return running_jobs_;
}
bool GGExecutionEngine::in_cache(const std::string& key) const
{
return cache_.find(key);
}
|
#include <corridor_navigation/corridor_navigation.h>
#include <ros/ros.h>
CorridorNavigation::CorridorNavigation():desired_direction_(0), recovery_direction_threshold_(1.0),
correction_direction_threshold_(0.06), desired_distance_(0), goal_type_(-1)
{
}
CorridorNavigation::~CorridorNavigation()
{
}
void CorridorNavigation::setRecoveryDirectionThreshold(double recovery_direction_threshold)
{
recovery_direction_threshold_ = recovery_direction_threshold;
}
void CorridorNavigation::setCorrectionDirectionThreshold(double correction_direction_threshold)
{
correction_direction_threshold_ = correction_direction_threshold;
}
void CorridorNavigation::setNominalVelocity(double nominal_velocity)
{
nominal_velocity_ = nominal_velocity;
}
double CorridorNavigation::getDesiredDirection()
{
return desired_direction_;
}
bool CorridorNavigation::determineDirection(double &computed_direction, double curr_direction, double left_ref_direction,
double left_ref_range, double right_ref_direction, double right_ref_range)
{
if (fabs(desired_direction_ - curr_direction) < recovery_direction_threshold_)
{
// NOTE: both the ranges greater then 0 indicates both are valid ref angles
if(left_ref_range > 0 && right_ref_range > 0)
computed_direction = (left_ref_direction + right_ref_direction)/2.0;
else if (left_ref_range > 0)
computed_direction = curr_direction + left_ref_direction;
else if (right_ref_range > 0)
computed_direction = curr_direction + right_ref_direction;
return true;
}
else
return false;
// enable recovery behaviour i.e stop the monitors until robot comes back in valid direction range
}
bool CorridorNavigation::isCorrectDirection(double left_ref_direction, double left_ref_range,
double right_ref_direction, double right_ref_range)
{
if(left_ref_range > 0 && right_ref_range > 0)
{
if (fabs(left_ref_direction - right_ref_direction) < correction_direction_threshold_)
return true;
}
return false;
}
bool CorridorNavigation::isGoalReached(Gateways detected_gateways, double monitored_distance, double monitored_heading)
{
if( monitored_distance > (0.8 * desired_distance_) && monitored_distance < (1.2 * desired_distance_))
{
if (monitored_heading > (desired_direction_ - 0.4) && monitored_heading < (desired_direction_ + 0.4))
{
if (goal_type_ == 0 && (fabs(detected_gateways.t_junction.left_turn_range) > 0 || fabs(detected_gateways.t_junction.right_turn_range) > 0 || fabs(detected_gateways.t_junction.front_range) > 0))
return true;
else if (goal_type_ == 1 && fabs(detected_gateways.x_junction.left_turn_range) > 0 && fabs(detected_gateways.x_junction.right_turn_range) > 0)
return true;
else if (goal_type_ == 2 && fabs(detected_gateways.left_door.range_x) > 0 && fabs(detected_gateways.left_door.range_y) > 0)
return true;
else if (goal_type_ == 3 && fabs(detected_gateways.right_door.range_x) > 0 && fabs(detected_gateways.right_door.range_y) > 0)
return true;
// TODO: implement front navigation goal
}
}
return false;
}
double CorridorNavigation::computeVelocity(double monitored_distance, double monitored_heading)
{
double velocity = nominal_velocity_;
if( monitored_distance > (0.8 * desired_distance_) && monitored_distance < (1.2 * desired_distance_))
{
velocity = 0.7 * nominal_velocity_;
}
if (monitored_heading < (desired_direction_ - 0.4) || monitored_heading > (desired_direction_ + 0.4))
{
velocity = 0.5 * nominal_velocity_;
}
return velocity;
}
void CorridorNavigation::setGoal(int goal, double direction, double distance)
{
goal_type_ = goal;
desired_direction_ = direction;
desired_distance_ = distance;
}
void CorridorNavigation::reset()
{
desired_direction_ = 0;
desired_distance_ = 0;
goal_type_ = -1;
}
|
//////////////////////////////////////////////////////////////////////
///Copyright (C) 2011-2012 Benjamin Quach
//
//This file is part of the "Lost Horizons" video game demo
//
//"Lost Horizons" 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/>.
//
///////////////////////////////////////////////////////////////////////
//int.h
//Manages the graphics rendering loop
//main menu
//and config file loading
#ifndef INIT_H
#define INIT_H
#include "irrlicht.h"
#include "irrklang.h"
#include "gameloop.h"
#include "keylistener.h"
#include "mainmenu.h"
#include "optionmenu.h"
#include "fader.h"
#include "screenquad.h"
#include "iostream"
#include "fstream"
using namespace irr;
using namespace std;
using namespace irrklang;
using namespace io;
//used by main.cpp for command line arguments
//implent everything later
struct commandParams
{
bool cFullscreen;
bool cDisableAI;
};
class CInit
{
public:
//Initializer, setup variables and such
CInit();
//destructor
~CInit();
//Set up the game
void StartMenu();
void StartGame();
//if need to generate new config cause of changed settings
void createNewVideoConfig(int x,int y, bool windowed, bool vsync, bool quality);
void readVideoConfig();
friend class Game; //legacy
float time;
//used to nuke everything and ensure there are no memory leaks
void drop();
//important event objects
irrklang::ISoundEngine *sound;
KeyListener *receiver;
irr::IrrlichtDevice *graphics;
//new cursor
gui::IGUIImage *cursor;
GameLoop *Game;
bool load;
private:
//used if exiting game to the main menu
bool exit;
//used for special fx only
CFader *fader;
};
#endif
|
#include "stdafx.h"
#include "Monster.h"
#include "MonsterAction.h"
#include "MonsterEffect.h"
#include "../PythonBridge/PythonBridge.h"
#include "../../Engine/character/CharacterController.h"
#include "../GameData.h"
//#include "MonsterAI.h"
#include "MonsterActionList.h"
#include "MonsterMarker.h"
#include "Action/ACTEffect.h"
Monster::~Monster()
{
DeleteGO(m_smr);
ReleaseMAL();
ReleaseMark();
for (auto a : m_actions)
DeleteGO(a);
delete[] m_UseAction;
delete m_pyFile;
delete m_visualAI;
}
void Monster::OnDestroy() {
printf("Destroy %d monster\n", Getnum());
}
void Monster::ReleaseMAL()
{
if (!m_dmal)
{
DeleteGO(m_MAL);
m_dmal = true;
}
}
void Monster::ReleaseMark()
{
if (m_marker != nullptr)
{
DeleteGO(m_marker);
m_marker = nullptr;
}
}
void Monster::init(MonsterInitParam param) {
init(
param.HP,
param.MP,
param.DefencePow,
param.ExDefensePow,
param.AttackPow,
param.ExAttackPow,
param.Speed,
param.Radius,
param.Height,
param.ModelRender,
param.NumAnimation
);
}
void Monster::init(float HP, float MP,float Defense,float ExDefense, float Attack, float ExAttack, float speed, float radius, float height, SkinModelRender * smr, int animnum)
{
m_HP = HP;
m_maxHP = HP;
m_MP = MP;
m_maxMP = MP;
m_Defense = Defense;
m_ExDefense = ExDefense;
m_Attack = Attack;
m_ExAttack = ExAttack;
m_speed = speed;
m_radius = radius;
m_height = height;
m_smr = smr;
m_AnimNum = animnum;
}
void Monster::SetUseAction(ActionID* ua,int size)
{
m_UseAction = ua;
m_useActionSize = size;
}
void Monster::SuddenDeath()
{
float hp = m_HP * 0.3f;
m_HP = hp;
m_maxHP = hp;
}
void Monster::ClearAllAbnormalState() {
printf("clear all monster abnormal state\n");
for (auto abs : m_abnormalStates)
abs->Clense();
m_abnormalStates.clear();
}
void Monster::ClearAbnormalState(ACTEffectGrant* abn) {
auto it = std::find(m_abnormalStates.begin(), m_abnormalStates.end(), abn);
if(it != m_abnormalStates.end())
m_abnormalStates.erase(it);
printf("id is %d : abnormal state num is %d\n", Getnum(),m_abnormalStates.size());
}
bool Monster::Start()
{
m_smr->SetPosition(m_pos);
m_cc.Init(m_radius, m_height, m_pos,enFbxUpAxisY);
anim_idle();
m_MAL = NewGO<MonsterActionList>(0, "mal");
m_MAL->init(this);
m_marker = NewGO<MonsterMarker>(0, "mark");
m_marker->init(this);
if (m_team == 0)
{
CQuaternion q = CQuaternion::Identity();
q.SetRotationDeg(CVector3::Up(), 180);
m_smr->SetRotation(q);
}
return true;
}
void Monster::Update()
{
if (m_end)
return;
if (m_HP <= 0)
{
CEffect* eff = NewGO<CEffect>(0, "ef");
CVector3 efp = m_pos;
efp.y += m_height/2;
eff->SetPosition(efp);
eff->SetScale({ 3,3,3 });
eff->Play(L"Assets/effect/PONG.efk",2);
Sound* se = NewGO<Sound>(0, "se");
se->Init(L"Assets/sound/ani_fa_mon07.wav");
se->Play();
m_state = en_Dead;
for (auto a : m_abnormalStates)
a->SetTargetAliveFlag(false);
GameData::deletemons(this);
DeleteGO(this);
}
switch (m_state)
{
case en_NowLoading:
if (m_actionTime > 2)
{
//m_PB->py_exe(m_num, m_team, m_pyFile);
if (!isLoading)
{
if (!m_isUseVSAI)
PythonBridge::py_exe(m_num, m_team, m_pyFile->c_str());
else
m_visualAI->Run();
//m_PB->py_exeEX(m_num, m_team, m_pyFile);
//isLoading = true;
}
if (m_actions.size() >= 1)
{
m_state = en_Execute;
isLoading = false;
}
m_actionTime = 0;
if (!m_smr->IsPlayingAnimation())
{
anim_idle();
}
}
break;
case en_Execute:
{
bool isAbnormal = true;
for (auto as : m_abnormalStates)
{
if (as->GetAbnormalState() == abStan)
{
isAbnormal = false;
m_movespeed = CVector3::Zero();
break;
}
}
if (!m_isKnockback && isAbnormal)
execute();
}
break;
case en_Dead:
break;
}
receiveDamage();
Move();
if (m_MPRecvTime >= m_MPrecov)
{
if (m_MP < m_maxMP)
{
m_MP += 1;
m_MPRecvTime = 0;
}
}
m_actionTime += IGameTime().GetFrameDeltaTime();
m_MPRecvTime += IGameTime().GetFrameDeltaTime();
}
void Monster::execute()
{
if (m_actions.size() == 0)
{
m_state = en_NowLoading;
m_actionTime = 0;
return;
}
if (m_actions[0]->Action(this))
{
DeleteGO(m_actions[0]);
m_actions.erase(m_actions.begin());
}
}
void Monster::Move()
{
CVector3 oldPos = m_pos;
CVector3 move = m_movespeed + m_vKnockback;
move *= m_speed;
CVector3 v = m_pos + move * IGameTime().GetFrameDeltaTime();
if (v.Length() > m_limitDist)
{
v.Normalize();
m_pos = v * m_limitDist;
m_cc.SetPosition(m_pos);
}
else
m_pos = m_cc.Execute(IGameTime().GetFrameDeltaTime(), move);
m_smr->SetPosition(m_pos);
if (m_isKnockback)
{
Knockback();
}
else
{
Turn();
//TurnEx();
}
}
void Monster::Turn()
{
if (m_turncount > 0)
return;
if (m_movespeed.Length() < 0.0001f)
return;
float angle = atan2(m_movespeed.x, m_movespeed.z);
//m_turncount = 5;
//m_rotangle = angle / m_turncount;
m_rot.SetRotation(CVector3::AxisY(), angle);
m_smr->SetRotation(m_rot);
}
void Monster::TurnEx()
{
if (m_turncount <= 0)
return;
CQuaternion addrot = CQuaternion::Identity();
addrot.SetRotation(CVector3::AxisY(),m_rotangle);
m_rot.Multiply(addrot);
m_smr->SetRotation(m_rot);
m_turncount--;
}
void Monster::receiveDamage()
{
bool isdam = false;
if (m_Damage > 0)
{
float dm = m_Damage - m_Defense;
if (dm <= 0)
dm = m_Damage / m_Defense;
if (dm > 0)
m_HP -= dm;
m_Damage = 0;
isdam = true;
}
if (m_DamageEx > 0)
{
float dm = m_DamageEx - m_ExDefense;
if(dm <= 0)
dm = m_DamageEx / m_ExDefense;
if (dm > 0)
m_HP -= dm;
m_DamageEx = 0;
isdam = true;
}
if (isdam)
{
Sound* se = NewGO<Sound>(0, "se");
se->Init(L"Assets/sound/ani_fa_mon03.wav");
se->Play();
}
}
void Monster::StartKnockback(CVector3 v)
{
m_vKnockback = v;
m_vSubKnock = v / 3;
m_isKnockback = true;
}
void Monster::SetKnockback(CVector3 v)
{
m_vKnockback = v;
m_vSubKnock = v;
if (v.Length() < 1.f)
{
m_isKnockback = false;
}
}
void Monster::Knockback()
{
if (m_vKnockback.Length() < 0.001f)
{
if (m_vSubKnock.Length() < 0.05f)
{
m_vKnockback = CVector3::Zero();
m_vSubKnock = CVector3::Zero();
m_isKnockback = false;
}
}
else
{
m_vKnockback -= m_vSubKnock;
m_vSubKnock /= 1.5f;
}
}
void Monster::Setpos(CVector3 v)
{
m_pos = v;
m_smr->SetPosition(v);
m_cc.SetPosition(v);
}
void Monster::SetRotation(CQuaternion rot)
{
m_rot = rot;
m_smr->SetRotation(rot);
}
void Monster::AddAction(MonsterAction * ma)
{
bool isNOPushed = true;
if (ma != nullptr && m_actions.size() < 3)
{
for (int i = 0; i < m_useActionSize; i++)
{
if (m_UseAction[i] == ma->GetactionID())
{
isNOPushed = false;
m_actions.push_back(ma);
break;
}
}
}
if (isNOPushed)
DeleteGO(ma);
}
void Monster::anim_idle()
{
if (en_idle > m_AnimNum - 1)
return;
m_smr->PlayAnimation(en_idle);
}
void Monster::anim_walk()
{
if (en_walk > m_AnimNum - 1)
return;
m_smr->PlayAnimation(en_walk);
}
void Monster::anim_atack()
{
if (en_atack > m_AnimNum - 1)
return;
m_smr->PlayAnimation(en_atack);
}
void Monster::anim_defenseF()
{
if (en_defenseF > m_AnimNum - 1)
return;
m_smr->PlayAnimation(en_defenseF);
}
void Monster::anim_defenseM()
{
if (en_defenseM > m_AnimNum - 1)
return;
m_smr->PlayAnimation(en_defenseM);
}
void Monster::anim_defenseE()
{
if (en_defenseM > m_AnimNum - 1)
return;
m_smr->PlayAnimation(en_defenseE);
}
void Monster::anim_extra1()
{
if (en_extra1 > m_AnimNum - 1)
return;
m_smr->PlayAnimation(en_extra1);
}
bool Monster::isAnimPlay()
{
return m_smr->IsPlayingAnimation();
}
int Monster::GetAbnormalStateID(int num)
{
return m_abnormalStates[num]->GetAbnormalState();
}
|
#include <iostream>
#include <queue>
#include <climits>
using namespace std;
// STACK USING 2 QUEUES
class StackUsingDoubleQueue
{
queue<int> q1, q2;
int top;
public:
void push(int);
int pop();
int peek()
{
return top;
}
};
void StackUsingDoubleQueue ::push(int x)
{ // Complexity : O(n)
q2.push(x);
top = x;
while (!q1.empty())
{
q2.push(q1.front());
q1.pop();
}
queue<int> temp = q1;
q1 = q2;
q2 = temp;
}
int StackUsingDoubleQueue ::pop()
{ // Complexity : O(1)
int x = top;
q1.pop();
top = q1.front();
return x;
}
//STACK USING SINGLE QUEUE
class StackUsingSingleQueue
{
queue<int> q;
int top;
public:
void push(int);
int pop();
int peek()
{
return top;
}
};
void StackUsingSingleQueue ::push(int x)
{
int s = q.size();
q.push(x);
top = x;
for (int i = 0; i < s; i++)
{
q.push(q.front());
q.pop();
}
}
int StackUsingSingleQueue ::pop()
{
if (!q.empty())
{
int x = q.front();
q.pop();
top = q.front();
return x;
}
else
{
return INT_MIN;
}
}
// MAIN DRIVER CODE
int main()
{
//STACK USING DOUBLE QUEUE
StackUsingDoubleQueue q;
q.push(10);
q.push(20);
q.push(30);
cout << q.pop() << endl;
cout << q.peek() << endl;
//STACK USING SINGLE QUEUE
StackUsingSingleQueue q1;
q1.push(10);
q1.push(20);
q1.push(30);
cout << q1.pop() << endl;
cout << q1.peek() << endl;
return 0;
}
|
#include "msg_0x69_updatewindowproperty_stc.h"
namespace MC
{
namespace Protocol
{
namespace Msg
{
UpdateWindowProperty::UpdateWindowProperty()
{
_pf_packetId = static_cast<int8_t>(0x69);
_pf_initialized = false;
}
UpdateWindowProperty::UpdateWindowProperty(int8_t _windowId, int16_t _property, int16_t _value)
: _pf_windowId(_windowId)
, _pf_property(_property)
, _pf_value(_value)
{
_pf_packetId = static_cast<int8_t>(0x69);
_pf_initialized = true;
}
size_t UpdateWindowProperty::serialize(Buffer& _dst, size_t _offset)
{
_pm_checkInit();
if(_offset == 0) _dst.clear();
_offset = WriteInt8(_dst, _offset, _pf_packetId);
_offset = WriteInt8(_dst, _offset, _pf_windowId);
_offset = WriteInt16(_dst, _offset, _pf_property);
_offset = WriteInt16(_dst, _offset, _pf_value);
return _offset;
}
size_t UpdateWindowProperty::deserialize(const Buffer& _src, size_t _offset)
{
_offset = _pm_checkPacketId(_src, _offset);
_offset = ReadInt8(_src, _offset, _pf_windowId);
_offset = ReadInt16(_src, _offset, _pf_property);
_offset = ReadInt16(_src, _offset, _pf_value);
_pf_initialized = true;
return _offset;
}
int8_t UpdateWindowProperty::getWindowId() const { return _pf_windowId; }
int16_t UpdateWindowProperty::getProperty() const { return _pf_property; }
int16_t UpdateWindowProperty::getValue() const { return _pf_value; }
void UpdateWindowProperty::setWindowId(int8_t _val) { _pf_windowId = _val; }
void UpdateWindowProperty::setProperty(int16_t _val) { _pf_property = _val; }
void UpdateWindowProperty::setValue(int16_t _val) { _pf_value = _val; }
} // namespace Msg
} // namespace Protocol
} // namespace MC
|
#ifndef __ARRAY2D_H__
#define __ARRAY2D_H__
#include <Array.h>
template <class T>
class Array2D
{
protected:
unsigned int numberOfRows;
unsigned int numberOfColumns;
Array<T> array;
public:
class Row
{
Array2D& array2D;
unsigned int const row;
public:
Row (Array2D& _array2D, unsigned int _row) :
array2D (_array2D), row (_row)
{}
T& operator [] (unsigned int column) const
{
return array2D.Select (row, column);
}
};
Array2D (unsigned int, unsigned int);
T& Select (unsigned int, unsigned int);
Row operator [] (unsigned int);
};
template <class T>
Array2D<T>::Array2D (unsigned int m, unsigned int n) :
numberOfRows (m),
numberOfColumns (n),
array (m * n)
{}
template <class T>
T& Array2D<T>::Select (unsigned int i, unsigned int j)
{
if (i >= numberOfRows)
throw out_of_range ("invalid row");
if (j >= numberOfColumns)
throw out_of_range ("invalid column");
return array [i * numberOfColumns + j];
}
template<class T>
typename Array2D<T>:: Row
Array2D<T>::operator [] (unsigned int row)
{
return Row (*this, row);
}
#endif
|
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
/* Expects a SORTED vector */
int calcUnfairness(int K, vector<int> &test){
int min = -1;
vector<int>::iterator iter;
for(iter = test.begin(); iter != test.end()-K; iter++) {
// cout << *iter << endl;
int temp = *(iter+K-1) - *iter;
if (temp < min || min == -1)
min = temp;
// cout << min << endl;
}
return min;
}
int main() {
vector<int> candyList;
int N, K, temp, unfairness;
cin >> N >> K;
for (int i = 0; i < N; i++) {
cin >> temp;
candyList.push_back(temp);
}
sort(candyList.begin(), candyList.end());
cout << calcUnfairness(K, candyList) << "\n";
return 0;
}
|
#include "LISW_MPI.hpp"
#include "wignerSymbols.h"
#include "Integrator.hpp"
#include "Log.hpp"
#include <fstream>
#include <math.h>
#include <cmath>
Bispectrum_LISW::Bispectrum_LISW(AnalysisInterface* analysis)
:
interpolate_large(false),
ql_interpolated(false)
{
log<LOG_BASIC>("... Beginning LISW constructor ...");
this->analysis = analysis;
SN_calculation = false;
if (analysis->model->give_fiducial_params("interp_Cls") == 1)
{
double numin = analysis->model->give_fiducial_params("Bispectrum_numin");
double numax = analysis->model->give_fiducial_params("Bispectrum_numax");
make_Ql_interps((int)analysis->model->give_fiducial_params("lmax_Fisher_Bispectrum"),\
numin, numax);
}
// Preparing the Cls container
// I create a vector with length lmax that is filled with -1's.
// Then later on I'll fill them in later, as required.
for (int i = 0; i <= (int)analysis->model->give_fiducial_params("lmax_Fisher_Bispectrum"); i++)
{
Cls.push_back(-1);
Qls.push_back(-1);
Cls_noise.push_back(-1);
}
log<LOG_BASIC>("... LISW Class initialized ...");
}
Bispectrum_LISW::Bispectrum_LISW(AnalysisInterface* analysis, int num_params, MPI_Comm communicator)
:
interpolate_large(false),
ql_interpolated(false)
{
MPI_Comm_rank(communicator, &rank);
if (rank == 0)
log<LOG_BASIC>("... Beginning LISW constructor ...");
this->analysis = analysis;
SN_calculation = false;
this->lmax_CLASS = (int)analysis->model->give_fiducial_params("lmax_Fisher_Bispectrum");
this->num_params = num_params;
// num_deriv is the number of non_fiducial points calculated for the fisher derivative.
int num_deriv = 1;
int num_indecies = num_params * num_deriv + 1;
for (int l = 0; l < this->lmax_CLASS+1; l++)
{
vector<vector<vector<Interpol>>> subvec3;
for (int i = 0; i < num_indecies; i++)
{
vector<vector<Interpol>> subvec2;
for (int j = 0; j < num_indecies; j++)
{
vector<Interpol> subvec1;
for (int k = 0; k < num_indecies; k++)
{
Interpol I;
real_1d_array x;
real_1d_array y;
x.setlength(2);
y.setlength(2);
x[0] = 0;
x[1] = 1;
y[0] = 0;
y[1] = 1;
spline1dinterpolant interpol;
spline1dbuildlinear(x, y, 2, interpol);
I.computed = false;
I.interpolator = interpol;
subvec1.push_back(I);
}
subvec2.push_back(subvec1);
}
subvec3.push_back(subvec2);
}
Qls_interpolators_large.push_back(subvec3);
}
if (analysis->model->give_fiducial_params("interp_Cls") == 1)
{
numin_CLASS = analysis->model->give_fiducial_params("Bispectrum_numin");
numax_CLASS = analysis->model->give_fiducial_params("Bispectrum_numax");
make_Ql_interps(lmax_CLASS, numin_CLASS, numax_CLASS, 0,0,0);
}
for (int i = 0; i <= (int)analysis->model->give_fiducial_params("lmax_Fisher_Bispectrum"); i++)
{
Cls_noise.push_back(-1);
}
if (rank == 0)
log<LOG_BASIC>("... LISW Class initialized ...");
}
Bispectrum_LISW::~Bispectrum_LISW()
{
//delete Qls_interpolators_large;
}
///////////////////////////////////////
/** Public Functions **/
///////////////////////////////////////
double Bispectrum_LISW::calc_angular_Blll_all_config(int l1, int l2, int l3, double z1,\
double z2, double z3, int Pk_index, int Tb_index, int q_index)
{
//At the same redshift
if (z1 == z2 and z1 == z3)
{
double term1, term2, term3, term4, term5, term6;
double W3J = WignerSymbols::wigner3j(l1,l2,l3,0,0,0);
if (W3J == 0)
{
return 0;
}
else
{
double pre = 0.5 * sqrt((2.0*l1+1.0)*(2.0*l2+1.0)*(2.0*l3+1.0)/(4.0*pi)) * W3J;
// careful with Cl's, here Santos is used so we need to change from redshift to
// frequency.
double nu1 = 1420.0/(1.0+z1);
// TODO: Check the nu's and whether they are in the right position.
// This obviously doesn't matter if all z's are the same...
double Q1,Q2,Q3,Q4,Q5,Q6;
Q1 = Ql(l3, z1, Pk_index, Tb_index, q_index);
Q4 = Q1;
Q2 = Ql(l2, z1, Pk_index, Tb_index, q_index);
Q5 = Q2;
Q3 = Ql(l1, z1, Pk_index, Tb_index, q_index);
Q6 = Q3;
double Cl1,Cl2,Cl3;
// DO NOT include the Noise here!
// this should be the pure signal bispectrum.
// The only place the Noise is included is the SNR calculation.
Cl1 = Cl(l1, nu1, nu1, Pk_index, Tb_index, q_index);
Cl2 = Cl(l2, nu1, nu1, Pk_index, Tb_index, q_index);
Cl3 = Cl(l3, nu1, nu1, Pk_index, Tb_index, q_index);
term1 = Cl2 * Q1;
term2 = Cl3 * Q2;
term3 = Cl3 * Q3;
term4 = Cl1 * Q4;
term5 = Cl1 * Q5;
term6 = Cl2 * Q6;
double result = pre * (L_lll(l1,l2,l3)*(term1+term2)+\
L_lll(l2,l3,l1)*(term3+term4)+\
L_lll(l3,l1,l2)*(term5+term6));
//cout << "B = " << result << ", l1 = " << l1 << ", l2 = " << l2 << ", l3 = " << l3 << endl;
return result;
}
}
else
{
double min_z1z2, min_z1z3, min_z2z3;
min_z1z2 = z1;
min_z1z3 = z1;
min_z2z3 = z2;
if (z2 < z1)
min_z1z2 = z2;
if (z3 < z1)
min_z1z3 = z3;
if (z3 < z2)
min_z2z3 = z3;
double term1, term2, term3, term4, term5, term6;
double W3J = WignerSymbols::wigner3j(l1,l2,l3,0,0,0);
if (W3J == 0)
return 0;
else
{
double pre = 0.5 * sqrt((2.0*l1+1.0)*(2.0*l2+1.0)*(2.0*l3+1.0)/(4.0*pi)) * W3J;
// careful with Cl's, here Santos is used so we need to change from redshift to
// frequency.
double nu1 = 1420.0/(1.0+z1);
double nu2 = 1420.0/(1.0+z2);
double nu3 = 1420.0/(1.0+z3);
// TODO: Check the nu's and whether they are in the right position.
// This obviously doesn't matter if all z's are the same...
double Q1,Q2,Q3,Q4,Q5,Q6;
Q1 = Ql(l3, min_z1z3, Pk_index, Tb_index, q_index);
if (min_z1z3 == min_z1z2)
Q4 = Q1;
else
Q4 = Ql(l3, min_z1z2, Pk_index, Tb_index, q_index);
Q2 = Ql(l2, min_z1z2, Pk_index, Tb_index, q_index);
if (min_z1z2 == min_z2z3)
Q5 = Q2;
else
Q5 = Ql(l2, min_z2z3, Pk_index, Tb_index, q_index);
Q3 = Ql(l1, min_z2z3, Pk_index, Tb_index, q_index);
if (min_z2z3 == min_z1z3)
Q6 = Q3;
else
Q6 = Ql(l1, min_z1z3, Pk_index, Tb_index, q_index);
term1 = Cl(l2, nu1, nu2, Pk_index, Tb_index, q_index) * Q1;
term2 = Cl(l3, nu2, nu3, Pk_index, Tb_index, q_index) * Q2;
term3 = Cl(l3, nu3, nu1, Pk_index, Tb_index, q_index) * Q3;
term4 = Cl(l1, nu1, nu3, Pk_index, Tb_index, q_index) * Q4;
term5 = Cl(l1, nu2, nu1, Pk_index, Tb_index, q_index) * Q5;
term6 = Cl(l2, nu3, nu2, Pk_index, Tb_index, q_index) * Q6;
double result = pre * (L_lll(l1,l2,l3)*(term1+term2)+\
L_lll(l2,l3,l1)*(term3+term4)+\
L_lll(l3,l1,l2)*(term5+term6));
//cout << "B = " << result << ", l1 = " << l1 << ", l2 = " << l2 << ", l3 = " << l3 << endl;
return result;
}
}
}
double Bispectrum_LISW::calc_Blll(int l1, int l2, int l3, double z1, double z2, double z3)
{
//At the same redshift
if (z1 == z2 and z1 == z3)
{
double term1, term2, term3, term4, term5, term6;
double W3J = WignerSymbols::wigner3j(l1,l2,l3,0,0,0);
if (W3J == 0)
{
return 0;
}
else
{
double pre = 0.5 * sqrt((2.0*l1+1.0)*(2.0*l2+1.0)*(2.0*l3+1.0)/(4.0*pi)) * W3J;
// careful with Cl's, here Santos is used so we need to change from redshift to
// frequency.
double nu1 = 1420.0/(1.0+z1);
// TODO: Check the nu's and whether they are in the right position.
// This obviously doesn't matter if all z's are the same...
double Q1,Q2,Q3,Q4,Q5,Q6;
Q1 = Ql(l3, z1);
Q4 = Q1;
Q2 = Ql(l2, z1);
Q5 = Q2;
Q3 = Ql(l1, z1);
Q6 = Q3;
double Cl1,Cl2,Cl3;
// DO NOT include the Noise here!
// this should be the pure signal bispectrum.
// The only place the Noise is included is the SNR calculation.
Cl1 = Cl(l1, nu1, nu1);
Cl2 = Cl(l2, nu1, nu1);
Cl3 = Cl(l3, nu1, nu1);
term1 = Cl2 * Q1;
term2 = Cl3 * Q2;
term3 = Cl3 * Q3;
term4 = Cl1 * Q4;
term5 = Cl1 * Q5;
term6 = Cl2 * Q6;
double result = pre * (L_lll(l1,l2,l3)*(term1+term2)+\
L_lll(l2,l3,l1)*(term3+term4)+\
L_lll(l3,l1,l2)*(term5+term6));
//cout << "B = " << result << ", l1 = " << l1 << ", l2 = " << l2 << ", l3 = " << l3 << endl;
return result;
}
}
else
{
double min_z1z2, min_z1z3, min_z2z3;
min_z1z2 = z1;
min_z1z3 = z1;
min_z2z3 = z2;
if (z2 < z1)
min_z1z2 = z2;
if (z3 < z1)
min_z1z3 = z3;
if (z3 < z2)
min_z2z3 = z3;
double term1, term2, term3, term4, term5, term6;
double W3J = WignerSymbols::wigner3j(l1,l2,l3,0,0,0);
if (W3J == 0)
return 0;
else
{
double pre = 0.5 * sqrt((2.0*l1+1.0)*(2.0*l2+1.0)*(2.0*l3+1.0)/(4.0*pi)) * W3J;
// careful with Cl's, here Santos is used so we need to change from redshift to
// frequency.
double nu1 = 1420.0/(1.0+z1);
double nu2 = 1420.0/(1.0+z2);
double nu3 = 1420.0/(1.0+z3);
// TODO: Check the nu's and whether they are in the right position.
// This obviously doesn't matter if all z's are the same...
double Q1,Q2,Q3,Q4,Q5,Q6;
Q1 = Ql(l3, min_z1z3);
if (min_z1z3 == min_z1z2)
Q4 = Q1;
else
Q4 = Ql(l3, min_z1z2);
Q2 = Ql(l2, min_z1z2);
if (min_z1z2 == min_z2z3)
Q5 = Q2;
else
Q5 = Ql(l2, min_z2z3);
Q3 = Ql(l1, min_z2z3);
if (min_z2z3 == min_z1z3)
Q6 = Q3;
else
Q6 = Ql(l1, min_z1z3);
term1 = Cl(l2, nu1, nu2) * Q1;
term2 = Cl(l3, nu2, nu3) * Q2;
term3 = Cl(l3, nu3, nu1) * Q3;
term4 = Cl(l1, nu1, nu3) * Q4;
term5 = Cl(l1, nu2, nu1) * Q5;
term6 = Cl(l2, nu3, nu2) * Q6;
double result = pre * (L_lll(l1,l2,l3)*(term1+term2)+\
L_lll(l2,l3,l1)*(term3+term4)+\
L_lll(l3,l1,l2)*(term5+term6));
//cout << "B = " << result << ", l1 = " << l1 << ", l2 = " << l2 << ", l3 = " << l3 << endl;
return result;
}
}
}
double Bispectrum_LISW::Ql(int l, double z, int Pk_index, int Tb_index, int q_index)
{
if (ql_interpolated && interpolate_large)
{
if (Qls_interpolators_large[l][Pk_index][Tb_index][q_index].computed == false)
make_Ql_interps(lmax_CLASS,numin_CLASS,numax_CLASS,Pk_index,Tb_index,q_index);
return interp_Ql(l, z, Pk_index, Tb_index, q_index);
}
else if (ql_interpolated && Pk_index == 0 && Tb_index == 0 && q_index == 0)
{
return interp_Ql(l,z);
}
else
{
log<LOG_DEBUG>("No interpolation possible, Ql is computed from scratch.");
return Ql_calc(l,z,Pk_index,Tb_index,q_index);
}
}
/* TODO: I belive this function is pretty useless. */
double Bispectrum_LISW::Ql(int l, double z)
{
if (SN_calculation)
{
if (Qls[l] == -1)
{
Qls[l] = Ql_calc(l, z, 0,0,0);
return Qls[l];
}
else
{
return Qls[l];
}
}
else
{
return Ql_calc(l,z,0,0,0);
}
}
double Bispectrum_LISW::Cl(int l, double nu1, double nu2)
{
//cout << "Calculating Cl" << endl;
// We'll only compute each one of these once and then store them
if (SN_calculation)
{
if (Cls[l] == -1)
{
//cout << "Calculating Cl for l = " << l << endl;
Cls[l] = analysis->Cl(l,nu1,nu2,0,0,0);
return Cls[l];
}
else
{
return Cls[l];
}
}
else
{
return analysis->Cl(l,nu1,nu2,0,0,0);
}
}
double Bispectrum_LISW::Cl(int l, double nu1, double nu2, int Pk_index, int Tb_index, int q_index)
{
double res = analysis->Cl(l,nu1,nu2,Pk_index,Tb_index,q_index);
return res;
}
double Bispectrum_LISW::Cl_noise(int l, double nu1, double nu2)
{
// We'll only compute each one of these once and then store them
if (SN_calculation)
{
if (Cls_noise[l] == -1)
{
Cls_noise[l] = analysis->Cl_noise(l, nu1, nu2);
return Cls_noise[l];
}
else
{
return Cls_noise[l];
}
}
else
{
return analysis->Cl_noise(l,nu1,nu2);
}
}
double Bispectrum_LISW::integrand_Ql(int l, double z, double z_fixed)
{
double r = analysis->model->r_interp(z_fixed);
double rzp = analysis->model->r_interp(z);
double pre = (r - rzp)/(r*pow(rzp,3));
double k = l/analysis->model->r_interp(z);
double Omega_M = analysis->model->Omega_M(0);
double H_0 = analysis->model->give_fiducial_params()["hubble"]*1000.0;
double pre2 = pow(3.0 * Omega_M/2.0,2) * pow(H_0/(k* analysis->model->c),4);
double h = 0.01;
double P0 = analysis->model->Pkz_interp(k,z,0);
double P1 = analysis->model->Pkz_interp(k,z+h,0);
double deriv = pre2 * (2*(1.0+z) * P0+ pow(1.0+z,2) * (P1-P0)/h);
return pre*deriv;
}
//////////////////////////////////////
/** Private Functions **/
///////////////////////////////////////
void Bispectrum_LISW::make_Ql_interps(int lmax, double numin, double numax)
{
// I could make this use parallellism...
double z_min, z_max, z_stepsize;
int z_steps;
z_min = 1420.4/numax - 1.0;
z_max = 1420.4/numin - 1.0;
z_steps = 10;
z_stepsize = abs(z_max - z_min)/(double)z_steps;
for (int l = 0; l <= lmax; l++)
{
vector<double> vz, vQl;
for (int i = 0; i <= z_steps; i++)
{
double z = z_min + i*z_stepsize;
vQl.push_back(this->Ql(l,z,0,0,0));
vz.push_back(z);
}
real_1d_array z_arr, Ql_arr;
z_arr.setlength(vz.size());
Ql_arr.setlength(vQl.size());
for (unsigned int i = 0; i < vz.size(); i++){
z_arr[i] = vz[i];
}
for (unsigned int i = 0; i < vQl.size(); i++){
Ql_arr[i] = vQl[i];
}
spline1dinterpolant interpolator;
spline1dbuildcubic(z_arr, Ql_arr, interpolator);
Qls_interpolators.push_back(interpolator);
if (rank == 0)
log<LOG_BASIC>("Ql for l = %1% is interpolated.") % l;
}
ql_interpolated = true;
}
double Bispectrum_LISW::interp_Ql(int l, double z)
{
return spline1dcalc(Qls_interpolators[l],z);
}
void Bispectrum_LISW::make_Ql_interps(int lmax, double numin, double numax,\
int Pk_index, int Tb_index, int q_index)
{
if (Qls_interpolators_large[lmax][Pk_index][Tb_index][q_index].computed == false)
{
// I could make this use parallellism...
double z_min, z_max, z_stepsize;
int z_steps;
z_min = 1420.4/numax - 1.0;
z_max = 1420.4/numin - 1.0;
z_steps = 100;
z_stepsize = abs(z_max - z_min)/(double)z_steps;
for (int l = 0; l <= lmax; l++)
{
vector<double> vz, vQl;
for (int i = 0; i <= z_steps; i++)
{
double z = z_min + i*z_stepsize;
vQl.push_back(this->Ql_calc(l,z,Pk_index,Tb_index,q_index));
vz.push_back(z);
}
real_1d_array z_arr, Ql_arr;
z_arr.setlength(vz.size());
Ql_arr.setlength(vQl.size());
for (unsigned int i = 0; i < vz.size(); i++){
z_arr[i] = vz[i];
}
for (unsigned int i = 0; i < vQl.size(); i++){
Ql_arr[i] = vQl[i];
}
spline1dinterpolant interpolator;
spline1dbuildcubic(z_arr, Ql_arr, interpolator);
Qls_interpolators_large[l][Pk_index][Tb_index][q_index].interpolator = interpolator;
Qls_interpolators_large[l][Pk_index][Tb_index][q_index].computed = true;
}
ql_interpolated = true;
interpolate_large = true;
}
}
double Bispectrum_LISW::interp_Ql(int l, double z, int Pk_index, int Tb_index, int q_index)
{
return spline1dcalc(Qls_interpolators_large[l][Pk_index][Tb_index][q_index].interpolator,z);
}
double Bispectrum_LISW::W_lll_mmm(int l1, int l2, int l3, int m1, int m2, int m3)
{
double W3J1 = WignerSymbols::wigner3j(l1,l2,l3,0,0,0);
double W3J2 = WignerSymbols::wigner3j(l1,l2,l3,m1,m2,m3);
double Gaunt_integral = sqrt((2.0*l1+1.0)*(2.0*l2+1.0)*(2.0*l3+1.0)/(4.0*pi)) * W3J1 * W3J2;
return 0.5 * pow(-1.0, m1+m2+m3) * (l3*(l3+1.0) + l2*(l2+1.0) - l1*(l1+1.0)) * Gaunt_integral;
}
double Bispectrum_LISW::L_lll(int l1, int l2, int l3)
{
return (-l1*(l1+1.0) + l2*(l2+1.0) + l3*(l3+1.0));
}
double Bispectrum_LISW::Ql_calc(int l, double z, int Pk_index, int Tb_index, int q_index)
{
if (l == 0)
{
return 0;
}
else
{
double r = analysis->model->q_interp(z, q_index);
double h = 0.001;
double dTbdz = analysis->model->T21_interp(z+h,Tb_index) -\
analysis->model->T21_interp(z,Tb_index);
dTbdz /= h;
//TODO: is this supposed to be 1?
double eta =-(1.0+z) * dTbdz;
auto integrand = [&](double zp)
{
double rzp = analysis->model->q_interp(zp, q_index);
double pre = (r - rzp)/(r*pow(rzp,3));
/*double h = 0.01;
double deriv = (P_phi(l/rzp,z + h) - P_phi(l/rzp, z))/h;
*/
double k = l/rzp;
//TODO: need to use current params...
double Omega_M = analysis->model->Omega_M(0);
double H_0 = analysis->model->give_fiducial_params()["hubble"]*1000.0;
double pre2 = pow(3.0 * Omega_M/2.0,2) * pow(H_0/(k* analysis->model->c),4);
double h2 = 0.01;
double P0 = analysis->model->Pkz_interp(k,zp,Pk_index);
double P1 = analysis->model->Pkz_interp(k,zp+h2,Pk_index);
double deriv = pre2 * (2.0 * (1.0+zp) * P0 + pow(1.0+zp,2) * (P1-P0)/h2);
//if (z < 0.5)
// cout << k << endl;
return pre*deriv;//analysis->model->Pkz_interp(k, z,0);//*pre;
};
double integral = integrate(integrand, 0.001, z, 100, simpson());
return 2.0*eta*integral;
}
}
|
#ifndef TREEFACE_VISUAL_OBJECT_H
#define TREEFACE_VISUAL_OBJECT_H
#include "treeface/scene/SceneObject.h"
#include <treecore/HashMap.h>
#include <treecore/RefCountObject.h>
namespace treecore {
class Identifier;
class Result;
class var;
} // namespace treecore
class TestFramework;
namespace treeface {
class SceneGraphMaterial;
class Geometry;
class UniversalValue;
class VertexArray;
class VisualObject: public SceneObject
{
friend class ::TestFramework;
friend class SceneRenderer;
friend class Geometry;
public:
VisualObject( Geometry* geom, SceneGraphMaterial* mat );
virtual ~VisualObject();
TREECORE_DECLARE_NON_COPYABLE( VisualObject )
TREECORE_DECLARE_NON_MOVABLE( VisualObject )
void set_uniform_value( const treecore::Identifier& name, const UniversalValue& value );
bool get_uniform_value( const treecore::Identifier& name, UniversalValue& result ) const noexcept;
bool has_uniform( const treecore::Identifier& name ) const noexcept;
SceneGraphMaterial* get_material() const noexcept;
Geometry* get_geometry() const noexcept;
VertexArray* get_vertex_array() const noexcept;
void render() noexcept;
protected:
struct Impl;
Impl* m_impl = nullptr;
};
} // namespace treeface
#endif // TREEFACE_VISUAL_OBJECT_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-file-style: "stroustrup" -*-
*
* Copyright (C) 1995-2005 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#ifndef LOGDOC_OPELEMENTCALLBACK_H
#define LOGDOC_OPELEMENTCALLBACK_H
#ifdef OPELEMENTCALLBACK_SUPPORT
class XMLTokenHandler;
class LogicalDocument;
/** Utility interface for parsing an XML document and creating
HTML_Element objects but without putting them together in a tree.
To use this functionality, one must create an object that
implements this interface, and from it create an XMLTokenHandler
object using the MakeTokenHandler function. This token handler
object is then used as the argument to XMLParser::Make to create
an XMLParser object. This XMLParser object is then used to parse
the XML document (see the documentation for XMLParser for more
details on how to do that.) Any extra information about the XML
document or parse errors encountered must be fetched directly from
the XMLParser object. If parsing fails, none of the functions in
this interface will be called again.
If the URL passed to XMLParser::Make contains a fragment
identifier, only the element with a matching ID attribute and its
descendants will be created and signalled by calls to AddElement()
and EndElement(). If no such element is found, no calls at all
are made. If more than one such element is found in the document,
all but the first are ignored. */
class OpElementCallback
{
public:
static OP_STATUS MakeTokenHandler(XMLTokenHandler *&tokenhandler, LogicalDocument *logdoc, OpElementCallback *callback);
/**< Create an XMLTokenHandler that will create a tree of HTML
elements and notify the supplied OpTreeCallback when
finished. If the URL parsed by the XMLParser that the token
handler is used with contains a fragment identifier, only the
sub-tree rooted by an element with an id that matches the
fragment identifier is created.
@param tokenhandler Set to the created token handler on
success. The token handler must be freed
by the caller.
@param logdoc The logical document to which the created
elements will belong. Can not be NULL.
@param callback OpTreeCallback implementation. Can not be
NULL.
@return OpStatus::OK or OpStatus::ERR_NO_MEMORY. */
virtual ~OpElementCallback();
/**< Destructor. */
virtual OP_STATUS AddElement(HTML_Element *element) = 0;
/**< Called when an element starts. The element is owned by
the OpTreeCallback implementation, and must be freed by
doing something like
if (element->Clean(frames_doc))
element->Free(frames_doc);
where 'frames_doc' is the FramesDocument returned by
logdoc->GetFramesDocument()
on the LogicalDocument object passed to MakeTokenHandler.
If the element is of one of the types HE_TEXT, HE_TEXTGROUP,
HE_COMMENT, HE_PROCINST or HE_DOCTYPE no corresponding
EndElement call will be made. Otherwise, EndElement() will
be called at some point, including for elements created for
empty element tags.
@param element The element that started.
@return OpStatus::OK or OpStatus::ERR_NO_MEMORY. */
virtual OP_STATUS EndElement() = 0;
/**< Called when an element ends. Only called for regular
elements. That is, not called to end HE_TEXT, HE_TEXTGROUP,
HE_COMMENT, HE_PROCINST or HE_DOCTYPE elements; they are
ended implicitly since they cannot have children.
@return OpStatus::OK or OpStatus::ERR_NO_MEMORY. */
};
#endif // OPELEMENTCALLBACK_SUPPORT
#endif // LOGDOC_OPELEMENTCALLBACK_H
|
/*
Given a sorted integer array A of size n, which contains all unique elements. You need to construct a balanced BST from
this input array. Return the root of constructed BST.
Note: If array size is even, take first mid as root.
Input format:
The first line of input contains an integer, which denotes the value of n. The following line contains n space separated
integers, that denote the values of array.
Output Format:
The first and only line of output contains values of BST nodes, printed in pre order traversal.
Constraints:
Time Limit: 1 second
Sample Input 1:
7
1 2 3 4 5 6 7
Sample Output 1:
4 2 1 3 6 5 7
*/
#include<bits/stdc++.h>
using namespace std;
class BinaryTreeNode{
public:
int data;
BinaryTreeNode* left;
BinaryTreeNode* right;
BinaryTreeNode(int data){
this -> data = data;
this -> left = NULL;
this -> right = NULL;
}
};
BinaryTreeNode* helper(int *input,int startIndex,int endIndex){
if(startIndex > endIndex){
return NULL;
}
int mid = (startIndex + endIndex) / 2;
BinaryTreeNode* root = new BinaryTreeNode(input[mid]);
root -> left = helper(input,startIndex,mid - 1);
root -> right = helper(input,mid + 1,endIndex);
return root;
}
BinaryTreeNode* constructTree(int *input,int n){
int startIndex = 0;
int endIndex = n - 1;
return helper(input,startIndex,endIndex);
}
void preOrder(BinaryTreeNode* root){
if(root == NULL){
return;
}
cout << root -> data << " ";
preOrder(root -> left);
preOrder(root -> right);
}
int main(){
int n;
cin >> n;
int *input = new int[n];
for(int i=0;i<n;i++){
cin >> input[i];
}
BinaryTreeNode* root = constructTree(input,n);
preOrder(root);
cout << endl;
return 0;
}
|
//HeapDate.cpp
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include "HeapDate.h"
using namespace std;
//HeapDate constructor
HeapDate::HeapDate(){
HeapDate::day = "1";
HeapDate::month = "1";
HeapDate::year = "2000";
};
void HeapDate::dateChange(string date){
stringstream ss;
ss << date;
string element;
int i = 0;
string datInfo[3];
while(getline(ss, element, '/')){
datInfo[i] = element;
i++;
};
HeapDate::setMonth(datInfo[0]);
HeapDate::setDay(datInfo[1]);
HeapDate::setYear(datInfo[2]);
};
//day functions
void HeapDate::setDay(string day){
HeapDate::day = day;
}// end setday
string HeapDate::getDay(){
return day;
}//end getday
//month functions
void HeapDate::setMonth(string month){
HeapDate::month = month;
}//end setmonth
string HeapDate::getMonth(){
return month;
}//end getmonth
//year functions
void HeapDate::setYear(string year){
HeapDate::year = year;
}//end setyear
string HeapDate::getYear(){
return year;
}//end getyear
string HeapDate::printDate(){
return month + " " + day + ", " + year;
};
//HeapDate::~HeapDate(){
//};
|
#include <iostream>
#include <list>
#include <map>
using namespace std;
class Graf{
private:
int vertexcount;
list <int> *adj;
public:
Graf(int V){
this->vertexcount = V;
adj = new list<int>[V];
}
void add(int v, int h){
adj[v].push_back(h);
adj[h].push_back(v);
}
list<int> sort(list<int>unmarkt, map<const int, int> hodnota){
map <const int, int> sort;
while (!unmarkt.empty()){
sort[unmarkt.back()] = hodnota.find(unmarkt.back())->second;
unmarkt.pop_back();
}
int a = sort.size();
map<const int, int>::iterator it = sort.begin();
while (a!=0)
{
it = sort.begin();
for (map<const int, int>::iterator ix = sort.begin(); ix != sort.end();ix++){
if (it->second < 0){
if (ix->second > 0)
it = ix;
}
else if (it->second > ix->second && ix->second > 0){
it = ix;
}
}
unmarkt.push_back(it->first);
sort.erase(it);
a--;
}
return unmarkt;
}
int dijkstra(const int v)
{
int tmp;
list<int>unmarkt;
map<const int, int> hodnota;
for (int i = 0; i < vertexcount;i++)
{
unmarkt.push_back(i);
hodnota[i] = -1;
}
map<const int, int>::iterator it = hodnota.find(v);
map<const int, int>::iterator is;
it->second = 0;
while (!unmarkt.empty())
{
unmarkt = sort(unmarkt,hodnota);
tmp = unmarkt.front();
unmarkt.pop_front();
it = hodnota.find(tmp);
for (list<int>::iterator ix = adj[tmp].begin(); ix != adj[tmp].end(); ix++){
is = hodnota.find(*ix);
if (is->second == -1) is->second = it->second + 1;
else if (is->second > it->second + 1){
is->second = it->second + 1;
}
}
}
int najdlhsia = 0;
for (map<const int, int>::iterator ik = hodnota.begin(); ik != hodnota.end();ik++){
if (ik->second > najdlhsia)
najdlhsia = ik->second;
}
return najdlhsia;
}
int priemer(){
int priemer = 0, cp = 0;
for (int i = 0; i < vertexcount; i++){
priemer = dijkstra(i);
if (priemer>cp) cp = priemer;
}
return cp;
}
};
int main()
{
Graf g(5);
g.add(0, 2);
g.add(0, 3);
g.add(2, 1);
g.add(3, 4);
g.add(1, 4);
int a = g.priemer();
return 0;
}
|
#ifndef __COMMON_HPP__
#define __COMMON_HPP__
#include <cuda.h>
#include <cuda_runtime.h>
enum Side {
WHITE, BLACK
};
#define OTHER(x) (x == WHITE? BLACK:WHITE)
#define MAX_NUM_MOVES 32
class Move {
public:
int x, y;
__host__ __device__ Move() {
this->x = -1;
this->y = -1;
}
__host__ __device__ Move(int x, int y) {
this->x = x;
this->y = y;
}
__host__ __device__ Move(const Move &m) {
this->x = m.x;
this->y = m.y;
}
__host__ __device__ bool operator==(const Move &other) const {
return this->x == other.x && this->y == other.y;
}
__host__ __device__ bool operator!=(const Move &other) const {
return !(*this == other);
}
__host__ __device__ ~Move() {}
};
#endif
|
#include "scrollinterface.h"
#include "scroll.h"
ScrollInterface::ScrollInterface()
{}
ScrollInterface::~ScrollInterface()
{}
|
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cmath>
using namespace std;
/*
*** Function : 逻辑回归Logistic Regression的c++实现
*** Author : TheDetial
*** Platform : Windows10+VS2013
*** Time : 2021/08/03
*** Result : 结果已通过。
***
*/
/*
相关知识点:线性回归、sigmoid()、梯度下降(上升)
1.//方法1:随机梯度下降
2.参数w初始化为1.0:
3. //开始迭代
4. 迭代次数N()
5. {
6. 每次取一组训练数据,直到所有数据取完结束本次迭代()
7. {
8. 更新参数w
9. }
10. }
11. 迭代结束,返回参数w
12.
13.//方法2:批量梯度下降
14.参数w初始化为1.0:
15. //开始迭代
16. 迭代次数N()
17. {
18. 每次使用所有训练数据一次性计算:
19. 更新参数w
20. }
21. 迭代结束,返回参数w
1.//方法3、小批量梯度下降
2.参数w初始化为1.0:
3. //开始迭代
4. 迭代次数N()
5. {
6. 每次随机抽取一个Batch的数据计算:
7. 更新参数w
8. }
9. 迭代结束,返回参数w
*/
struct point
{
float x0;
float x1;
float x2;
int label;
};
class Logistic
{
public:
void dataLoad(vector<point> &, string filepath);//载入数据
void stoGradDescent(int iters, float steps);//方法1:随机梯度下降
void plotFilters();//画出散点图和logistic回归曲线
void logTest(string);//测试逻辑回归模型好坏
vector<point> dataTrain;//存储训练数据:特征+label
vector<point> dataTest;//存储测试数据
private:
float sigmoid(float);//sigmoid函数定义
vector<float> weights;//训练:权重向量
void add_vector(vector<float> &vec_w, vector<float>& vec_wdelt, float steps);//向量对应位相加
};
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int n;
ll func(vector<ll> a, int fugo)
{
ll ans = 0;
ll offset = 0; //蓄積する修正量
for (int i = 0; i < n; i++)
{
if (i % 2 == fugo){
if (a[i] <= offset){
ans += offset - (a[i] - 1);
offset = a[i] - 1;
}
} else {
if (a[i] >= offset){
ans += (a[i] + 1) - offset;
offset = a[i] + 1;
}
}
//printf("[%d]", offset);
}
//printf("%d ",ans);
return ans;
}
int main()
{
cin >> n;
vector<ll> a;
ll sum_tmp = 0;
for (int i = 0; i < n; i++)
{
int tmp; cin >> tmp;
sum_tmp += tmp;
a.push_back(sum_tmp);
}
ll ans = min(func(a, 0), func(a, 1));
cout << ans << endl;
}
|
#include "GamePCH.h"
#include "GStateScene.h"
#include "GStateBGLayer.h"
#include "GStateUILayer.h"
#include "GAbilityListCtrlItem.h"
#include "GItemListCtrlItem.h"
#include "GStateListCtrlItem.h"
#include "GnIListCtrl.h"
#include "GPlayingDataManager.h"
#include "GItemInfo.h"
#include "GUnitViewer.h"
#include "GnITabCtrl.h"
GStateScene::GStateScene() : mOtherInputEvent( this, &GStateScene::OtherInputEvent )
, mUnitInputEvent( this, &GStateScene::UnitInputEvent ), mShopInputEvent( this, &GStateScene::ShopInputEvent )
, mAbilityInputEvent( this, &GStateScene::AbilityInputEvent ), mpCurrentStetItem( NULL )
, mpCurrentShopItem( NULL ), mpCurrentInvenItem( NULL), mpCurrentEquipItem( NULL ), mCurrentControllerIndex( -1 )
{
}
GStateScene::~GStateScene()
{
}
GStateScene* GStateScene::CreateScene()
{
GStateScene* scene = new GStateScene();
if( scene->CreateInterface() == false || scene->CreateBackground() == false )
{
delete scene;
return NULL;
}
return scene;
}
bool GStateScene::CreateInterface()
{
GStateUILayer* interfaceLayer = new GStateUILayer();
mpOtherUIGroup = interfaceLayer->CreateInterface( GInterfaceLayer::UI_STATE_OTHERUI, &mOtherInputEvent );
if( mpOtherUIGroup == NULL
|| interfaceLayer->CreateInterface( GInterfaceLayer::UI_STATE_UNITTAB, &mUnitInputEvent ) == NULL
|| interfaceLayer->CreateInterface( GInterfaceLayer::UI_STATE_ABILITYTAB, &mAbilityInputEvent ) == NULL
|| interfaceLayer->CreateInterface( GInterfaceLayer::UI_STATE_SHOPTAB, &mShopInputEvent ) == NULL )
{
delete interfaceLayer;
return false;
}
mpInterfaceLayer = interfaceLayer;
addChild( interfaceLayer, INTERFACE_ZORDER );
interfaceLayer->release();
GnList<GUserHaveItem::Item> haveUnits;
GPlayingDataManager* dataMng = GPlayingDataManager::GetSingleton();
GUserHaveItem* haveItem = dataMng->GetPlayingHaveItem();
GPlayingData* playingData = dataMng->GetPlayingPlayerData();
haveItem->OpenPlayerItem( playingData->GetPlayerName() );
haveItem->GetItems( eUnit, haveUnits );
haveItem->Close();
mpsUnitViewer = GUnitViewer::CreateUnitViewer( haveUnits );
GnITabPage* tabPage = interfaceLayer->GetTabCtrl()->GetTabPage( GStateUILayer::UNIT_TAB );
tabPage->AddChild( mpsUnitViewer, INTERFACE_ZORDER + 10 );
return true;
}
bool GStateScene::CreateBackground()
{
GStateBGLayer* backLayer = GStateBGLayer::CreateBackground();
if( backLayer == NULL )
{
return false;
}
mpBackgroundLayer = backLayer;
addChild( backLayer );
backLayer->release();
return true;
}
void GStateScene::Update(float fTime)
{
mpInterfaceLayer->Update( fTime );
//mpsUnitViewer->Update( fTime );
}
const gchar* GStateScene::GetSceneName()
{
return SCENENAME_STATE;
}
void GStateScene::OtherInputEvent(GnInterface* pInterface, GnIInputEvent* pEvent)
{
if( pEvent->GetEventType() == GnIInputEvent::PUSHUP )
{
if( mpOtherUIGroup->GetChild( GInterfaceLayer::BT_STATE_FRONT ) == pInterface )
{
GScene::SetChangeSceneName( GScene::SCENENAME_SELECTSTAGE );
}
else if( mpOtherUIGroup->GetChild( GInterfaceLayer::BT_STATE_BACK ) == pInterface )
{
GScene::SetChangeSceneName( GScene::SCENENAME_START );
}
}
}
void GStateScene::UnitInputEvent(GnInterface* pInterface, GnIInputEvent* pEvent)
{
if( pEvent->GetEventType() == GnIInputEvent::PUSH )
{
if( pInterface->GetTegID() > -1 )
{
GStateUILayer* interfaceLayer = (GStateUILayer*)mpInterfaceLayer;
SelectUnit( (guint32)pInterface->GetTegID(), interfaceLayer->GetUnitMoneyLabel() );
}
}
else if( pEvent->GetEventType() == GnIInputEvent::PUSHUP )
{
GStateUILayer* interfaceLayer = (GStateUILayer*)mpInterfaceLayer;
switch( pInterface->GetTegID() )
{
case GInterfaceLayer::BT_UNIT_UPGRADE:
UpgradeUnit( mCurrentControllerIndex, interfaceLayer->GetMoneyLabel()
, interfaceLayer->GetUnitMoneyLabel() );
break;
}
}
}
void GStateScene::ShopInputEvent(GnInterface* pInterface, GnIInputEvent* pEvent)
{
if( pEvent->GetEventType() == GnIInputEvent::PUSH )
{
if( pInterface->GetTegID() == GInterfaceLayer::LISTITEM_SHOP )
{
if( ViewItemExplain( mpCurrentShopItem, pInterface ) )
{
if( mpCurrentInvenItem )
mpCurrentInvenItem->SetVisibleExplain( false );
if( mpCurrentEquipItem )
mpCurrentEquipItem->SetVisibleExplain( false );
}
}
else if( pInterface->GetTegID() == GInterfaceLayer::LISTITEM_INVEN )
{
if( ViewItemExplain( mpCurrentInvenItem, pInterface ) )
{
if( mpCurrentShopItem )
mpCurrentShopItem->SetVisibleExplain( false );
if( mpCurrentEquipItem )
mpCurrentEquipItem->SetVisibleExplain( false );
}
}
else
{
if( ViewItemExplain( mpCurrentEquipItem, pInterface ) )
{
if( mpCurrentShopItem )
mpCurrentShopItem->SetVisibleExplain( false );
if( mpCurrentInvenItem )
mpCurrentInvenItem->SetVisibleExplain( false );
}
}
}
else if( pEvent->GetEventType() == GnIInputEvent::PUSHUP )
{
GStateUILayer* interfaceLayer = (GStateUILayer*)mpInterfaceLayer;
switch( pInterface->GetTegID() )
{
case GInterfaceLayer::BT_BUY_ITEM:
BuyItem( interfaceLayer->GetInventoryListCtrl(), interfaceLayer->GetEquipListCtrl()
, interfaceLayer->GetMoneyLabel(), mpCurrentShopItem );
break;
case GInterfaceLayer::BT_SELL_ITEM:
if( SellItem( interfaceLayer->GetInventoryListCtrl(), interfaceLayer->GetEquipListCtrl()
, interfaceLayer->GetMoneyLabel(), mpCurrentInvenItem ) == 0 )
{
if( mpCurrentInvenItem )
{
mpCurrentInvenItem->SetVisibleExplain( false );
mpCurrentInvenItem = NULL;
}
}
break;
case GInterfaceLayer::BT_EQUIP_ITEM:
EquipItem( interfaceLayer->GetInventoryListCtrl(), interfaceLayer->GetEquipListCtrl()
, mpCurrentInvenItem );
// if( mpCurrentInvenItem )
// {
// mpCurrentInvenItem->SetVisibleExplain( false );
// mpCurrentInvenItem = NULL;
// }
break;
case GInterfaceLayer::BT_UNEQUIP_ITEM:
UnEquipItem( interfaceLayer->GetInventoryListCtrl(), interfaceLayer->GetEquipListCtrl()
, mpCurrentEquipItem );
if( mpCurrentEquipItem )
{
mpCurrentEquipItem->SetVisibleExplain( false );
mpCurrentEquipItem = NULL;
}
break;
}
}
}
void GStateScene::AbilityInputEvent(GnInterface* pInterface, GnIInputEvent* pEvent)
{
if( pEvent->GetEventType() == GnIInputEvent::PUSH )
{
ViewItemExplain( mpCurrentStetItem, pInterface );
}
else if( pEvent->GetEventType() == GnIInputEvent::PUSHUP )
{
GStateUILayer* interfaceLayer = (GStateUILayer*)mpInterfaceLayer;
switch( pInterface->GetTegID() )
{
case GInterfaceLayer::BT_ABILITY_UPGRADE:
UpgradeAbility( interfaceLayer->GetStarLabel(), mpCurrentStetItem );
break;
}
}
}
bool GStateScene::ViewItemExplain(GStateListCtrlItem*& pCurrentItem, GnInterface* pInterface)
{
GStateListCtrlItem* stetItem = GnDynamicCast( GStateListCtrlItem, pInterface );
if( stetItem )
{
if( pCurrentItem )
pCurrentItem->SetVisibleExplain( false );
pCurrentItem = stetItem;
stetItem->SetVisibleExplain( true );
return true;
}
return false;
}
guint32 GStateScene::SellItem(GnIListCtrl* pInvenList, GnIListCtrl* pEquipList, GnINumberLabel* pMoneyLabel
, GStateListCtrlItem* pItem)
{
if( pItem == NULL )
return 0;
GPlayingDataManager* dataMng = GPlayingDataManager::GetSingleton();
GUserHaveItem* haveItem = dataMng->GetPlayingHaveItem();
GPlayingData* playingData = dataMng->GetPlayingPlayerData();
haveItem->OpenPlayerItem( playingData->GetPlayerName() );
guint32 itemIndex = pItem->GetItemIndex();
// delete item
guint32 itemCount = haveItem->GetItemCount( itemIndex ) - 1;
if( itemCount < 1 )
{
GItemListCtrlItem* existItem = GetListCtrlItemFromIndex( pInvenList, itemIndex );
if( existItem )
{
haveItem->DeleteItem( itemIndex, eItem );
pInvenList->RemoveItem( pItem );
}
existItem = GetListCtrlItemFromIndex( pEquipList, itemIndex );
if( existItem )
{
haveItem->DeleteItem( itemIndex, eEquip );
pEquipList->RemoveItem( pItem );
}
}
else
{
UpdateItemCount( haveItem, pInvenList, pEquipList, itemIndex, itemCount );
}
// set money
guint32 sellMoney = GetItemInfo()->GetSellPrice( itemIndex, 0 );
guint32 money = sellMoney + playingData->GetMoneyCount();
playingData->SetMoneyCount( money );
pMoneyLabel->SetNumber( money );
haveItem->Close();
dataMng->SaveData();
return itemCount;
}
void GStateScene::BuyItem(GnIListCtrl* pInvenList, GnIListCtrl* pEquipList, GnINumberLabel* pMoneyLabel
, GStateListCtrlItem* pItem)
{
if( pItem == NULL )
return;
gtuint itemIndex = pItem->GetItemIndex();
GPlayingDataManager* dataMng = GPlayingDataManager::GetSingleton();
GPlayingData* playingData = dataMng->GetPlayingPlayerData();
guint32 buyMoney = GetItemInfo()->GetBuyPrice( itemIndex, 0 );
if( playingData->GetMoneyCount() < buyMoney )
return;
GUserHaveItem* haveItem = dataMng->GetPlayingHaveItem();
haveItem->OpenPlayerItem( playingData->GetPlayerName() );
GItemListCtrlItem* equipItem = NULL;
guint32 itemCount = haveItem->GetItemCount( pItem->GetItemIndex() ) + 1;
if( itemCount == 1 )
{
// add item to haveitem
haveItem->AddItem( itemIndex, eItem );
// add item to list
GStateUILayer* interfaceLayer = (GStateUILayer*)mpInterfaceLayer;
equipItem = interfaceLayer->CreateItemCtrlItem( itemIndex );
pInvenList->AddItem( equipItem );
equipItem->SetTegID( GInterfaceLayer::LISTITEM_INVEN );
equipItem->SetItemIndex( itemIndex );
equipItem->SetItemCount( itemCount );
}
else
{
UpdateItemCount( haveItem, pInvenList, pEquipList, itemIndex, itemCount );
}
haveItem->Close();
// set money
guint32 money = playingData->GetMoneyCount() - buyMoney;
playingData->SetMoneyCount( money );
pMoneyLabel->SetNumber( money );
dataMng->SaveData();
}
void GStateScene::EquipItem(GnIListCtrl* pInvenList, GnIListCtrl* pEquipList, GStateListCtrlItem* pItem)
{
if( pItem == NULL )
return;
if( pEquipList->GetItemCount() >= ENABLE_MAX_EQUIP )
return;
gtuint itemIndex = pItem->GetItemIndex();
GPlayingDataManager* dataMng = GPlayingDataManager::GetSingleton();
GPlayingData* playingData = dataMng->GetPlayingPlayerData();
if( GetListCtrlItemFromIndex(pEquipList, pItem->GetItemIndex() ) == NULL )
{
GUserHaveItem* haveItem = dataMng->GetPlayingHaveItem();
haveItem->OpenPlayerItem( playingData->GetPlayerName() );
guint32 itemCount = haveItem->GetItemCount( itemIndex );
// add equip item to haveitem
haveItem->AddItem( itemIndex, eEquip, 0, itemCount );
// add equip
GStateUILayer* interfaceLayer = (GStateUILayer*)mpInterfaceLayer;
GItemListCtrlItem* newItem = interfaceLayer->CreateEquipCtrlItem( itemIndex );
newItem->SetTegID( GInterfaceLayer::LISTITEM_EQUIP );
newItem->SetItemIndex( itemIndex );
newItem->SetItemCount( itemCount );
pEquipList->AddItem( newItem );
haveItem->Close();
}
}
void GStateScene::UnEquipItem(GnIListCtrl* pInvenList, GnIListCtrl* pEquipList, GStateListCtrlItem* pItem)
{
if( pItem == NULL )
return;
GPlayingDataManager* dataMng = GPlayingDataManager::GetSingleton();
GPlayingData* playingData = dataMng->GetPlayingPlayerData();
// delete equip item to haveitem
GUserHaveItem* haveItem = dataMng->GetPlayingHaveItem();
haveItem->OpenPlayerItem( playingData->GetPlayerName() );
haveItem->DeleteItem( pItem->GetItemIndex(), eEquip );
haveItem->Close();
// remove invenitem
pEquipList->RemoveItem( pItem );
}
void GStateScene::UpgradeAbility(GnINumberLabel* pStartLabel, GStateListCtrlItem*& pCurrentItem)
{
GAbilityListCtrlItem* ablityItem = GnDynamicCast(GAbilityListCtrlItem, pCurrentItem);
if( ablityItem == NULL )
return;
GPlayingDataManager* dataMng = GPlayingDataManager::GetSingleton();
GPlayingData* playingData = dataMng->GetPlayingPlayerData();
if( playingData->GetStarCount() < 1 )
return;
GUserHaveItem* haveItem = dataMng->GetPlayingHaveItem();
haveItem->OpenPlayerItem( playingData->GetPlayerName() );
guint32 level = haveItem->GetItemLevel( ablityItem->GetItemIndex() );
if( MAX_ABILITY_LEVEL <= level )
{
haveItem->Close();
return;
}
// update label level
ablityItem->SetCurrentLevel( ablityItem->GetCurrentLevel() + 1 );
// update have item level
haveItem->UpdateLevel( ablityItem->GetItemIndex(), ablityItem->GetCurrentLevel() );
haveItem->Close();
// set money
guint32 star = playingData->GetStarCount() - 1;
playingData->SetStarCount( star );
pStartLabel->SetNumber( star );
dataMng->SaveData();
}
void GStateScene::SelectUnit(guint32 uiUnitIndex, GnINumberLabel* pUnitMoneyLabel)
{
// view unit
GActorController* ctrl = mpsUnitViewer->GetActorCtrlFromUnitIndex( uiUnitIndex );
if( ctrl )
{
if( mCurrentControllerIndex != -1 )
mpsUnitViewer->SetVisibleActorCtlr( (guint32)mCurrentControllerIndex, false );
mpsUnitViewer->SetVisibleActorCtlr( uiUnitIndex, true );
mCurrentControllerIndex = uiUnitIndex;
}
if( eIndexC1 <= uiUnitIndex && eMaxIndexUnit > uiUnitIndex )
{
GUserHaveItem* haveItem = GetCurrentHaveItem();
// set upgrade money
guint32 itemLevel = haveItem->GetItemLevel( uiUnitIndex );
guint32 price = GetItemInfo()->GetBuyPrice( uiUnitIndex, itemLevel );
pUnitMoneyLabel->SetNumber( price );
haveItem->Close();
}
}
void GStateScene::UpgradeUnit(gtuint uiUnitIndex, GnINumberLabel* pTotalMoneyLabel, GnINumberLabel* pUnitMoneyLabel)
{
if( uiUnitIndex == -1 )
return;
GUserHaveItem* haveItem = GetCurrentHaveItem();
GPlayingDataManager* dataMng = GPlayingDataManager::GetSingleton();
GPlayingData* playingData = dataMng->GetPlayingPlayerData();
// check upgrade money
guint32 itemLevel = haveItem->GetItemLevel( uiUnitIndex );
if( MAX_UNIT_LEVEL <= itemLevel )
{
haveItem->Close();
return;
}
guint32 buyMoney = GetItemInfo()->GetBuyPrice( uiUnitIndex, itemLevel );
if( playingData->GetMoneyCount() < buyMoney )
{
haveItem->Close();
return;
}
itemLevel += 1;
// update level
haveItem->UpdateLevel( uiUnitIndex, itemLevel );
// set money data
guint32 money = playingData->GetMoneyCount() - buyMoney;
playingData->SetMoneyCount( money );
pTotalMoneyLabel->SetNumber( money );
dataMng->SaveData();
// set unit money label
buyMoney = GetItemInfo()->GetBuyPrice( uiUnitIndex, itemLevel );
pUnitMoneyLabel->SetNumber( buyMoney );
haveItem->Close();
}
void GStateScene::UpdateItemCount(GUserHaveItem* pHaveItem, GnIListCtrl* pInvenList, GnIListCtrl* pEquipList
, guint32 uiItemIndex, guint32 uiItemCount)
{
pHaveItem->UpdateCount( uiItemIndex, uiItemCount );
GItemListCtrlItem* item = GetListCtrlItemFromIndex( pInvenList, uiItemIndex );
if( item )
item->SetItemCount( uiItemCount );
item = GetListCtrlItemFromIndex( pEquipList, uiItemIndex );
if( item )
item->SetItemCount( uiItemCount );
}
GItemListCtrlItem* GStateScene::GetListCtrlItemFromIndex(GnIListCtrl* pList, guint32 uiIndex)
{
for( gtuint i = 0 ; i < pList->GetColumnSize() ; i++ )
{
for( gtuint j = 0 ; j < pList->GetRowSize() ; j++ )
{
GItemListCtrlItem* item = (GItemListCtrlItem*)pList->GetItem( i , j );
if( item && item->GetItemIndex() == uiIndex )
{
return item;
}
}
}
return NULL;
}
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "BehaviorTree/BTTaskNode.h"
#include "BTTask_StartAttack.generated.h"
/**
*
*/
UCLASS()
class ANIMATIONTEST_API UBTTask_StartAttack : public UBTTaskNode
{
GENERATED_BODY()
public:
UBTTask_StartAttack();
virtual void OnGameplayTaskActivated(UGameplayTask& Task) override;
virtual EBTNodeResult::Type ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory) override;
UPROPERTY(EditAnywhere, Category = "Jump")
bool bIsJumpAttack;
};
|
#pragma once
#include "shaders\Shader.h"
#include "SolarSystem.h"
#include "Camera.h"
#include "Skybox.h"
class RenderingManager {
private:
GLFWwindow* m_window;
Camera * m_camera;
GLfloat m_deltaTime;
Shader * m_default_shader = nullptr,
*m_light_shader = nullptr,
*m_skybox_shader = nullptr;
Skybox * m_skybox = nullptr;
SolarSystem * m_solar_system = nullptr;
public:
RenderingManager(Camera * camera, SolarSystem * solar_system){
m_camera = camera;
m_solar_system = solar_system;
}
inline GLFWwindow * get_window() { return m_window; }
inline void init() {
init_window();
init_openGL_flags();
init_shaders();
init_skybox();
}
inline void terminate() {
glfwTerminate();
}
void render(const float delta_time) {
m_deltaTime = delta_time;
glfwPollEvents();
clear_buffers();
// m_light.Use();
// m_camera->SetProjectionMatrix(&m_light);
//m_camera->SetViewMatrix(&m_light);
//solar_system->m_star->draw(m_light);
m_default_shader->Use();
m_camera->SetProjectionMatrix(*m_default_shader);
m_camera->SetViewMatrix(*m_default_shader);
for (auto& planet : m_solar_system->m_planets) {
planet->draw(*m_default_shader);
}
m_skybox->draw(*m_skybox_shader);
glfwSwapBuffers(m_window);
}
private:
void init_window() {
// Init GLFW
glfwInit();
// Set all the required options for GLFW
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
glfwWindowHint(GLFW_SAMPLES, 4);
// Create a GLFWwindow object that we can use for GLFW's functions
m_window = glfwCreateWindow(m_camera->m_width, m_camera->m_height, "solar-system", nullptr, nullptr);
glfwMakeContextCurrent(m_window);
// Options
glfwSetInputMode(m_window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
// Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions
glewExperimental = GL_TRUE;
glewInit();
// Define the viewport dimensions
glViewport(0, 0, m_camera->m_width, m_camera->m_height);
}
inline void init_openGL_flags() {
glEnable(GL_DEPTH_TEST);
//glEnable(GL_CULL_FACE);
glDepthFunc(GL_LEQUAL);
glEnable(GL_MULTISAMPLE);
}
inline void init_shaders() {
m_default_shader = new Shader("src/shaders/default.vs", "src/shaders/default.fs");
m_light_shader = new Shader("src/shaders/light_shader.vs", "src/shaders/light_shader.fs");
m_skybox_shader = new Shader("src/shaders/skybox.vs", "src/shaders/skybox.fs");
}
inline void init_skybox() {
m_skybox = new Skybox(m_camera, "assets/skybox/");
m_skybox->init();
}
inline void clear_buffers() {
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
}
};
|
// Copyright 2020 Fuji-Iot 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 FUJI_AC_PROTOCOL_HANDLER_H_
#define FUJI_AC_PROTOCOL_HANDLER_H_
#include <gtest/gtest_prod.h>
#include <memory>
#include "absl/types/optional.h"
#include "fuji_ac_state.h"
#include "fuji_frame.h"
namespace fuji_iot {
// This class is entry point for protocol handling. It is virtual equivalent of
// wired controller. AC unit communicates with the wired controller via serial
// interface. On hardware layer it is implemented using single wire connection
// that is shared for Tx/Rx.
//
// [master_frame -- wired_ctrl_frame(opt) -------]
//
// Single communication cycle is started with single master frame sent. Wired
// controller process it and (optionally) responds with wire_ctrl_frame.
// Remainder of the cycle is silent. The process resumes with next master_frame
// and is periodic. Main unit will repeat master_frame indefinately (even if
// there is not state change) and will treat lack of responses as an error.
class FujiAcProtocolHandler {
public:
// Takes ownership of state object, but caller should keep it reference to
// read and modify AC unit state.
FujiAcProtocolHandler(std::unique_ptr<FujiAcState> state);
// Processes data from main unit, updates state object with master_frame data
// and optionally returns a controller frame that should be sent back to main
// unit. If state was modified in between the calls (for example to change AC
// unit parameters), it will take precendece and that modification will be
// reflected in returned controller frame.
absl::optional<FujiControllerFrame> HandleMasterFrame(
const FujiMasterFrame &master_frame);
private:
FujiControllerFrame SendLoginFrame();
FujiControllerFrame SendErrorQueryFrame();
FujiControllerFrame SendStatusFrame();
FujiControllerFrame SendLoggedInFrame();
void UpdateFromMasterStatusRegister(const FujiMasterFrame &master_frame);
void UpdateFromMasterErrorRegister(const FujiMasterFrame &master_frame);
std::unique_ptr<FujiAcState> ac_state_;
bool error_read_ = false;
bool login_read_ = true;
FRIEND_TEST(FujiAcProtocolHandlerTest, RemoteTurnOnTurnOff);
FRIEND_TEST(FujiAcProtocolHandlerTest, TestGolden);
FRIEND_TEST(FujiAcProtocolHandlerTest, TurnOn);
FRIEND_TEST(FujiAcProtocolHandlerTest, WiredControlGolden);
};
} // namespace fuji_iot
#endif
|
//
// Persona.h
//
//
// Created by Daniel on 14/08/14.
//
//
#ifndef ____Persona__
#define ____Persona__
#include <iostream>
class Persona{
private:
int hambre;
int edad;
int energia;
int altura;
int peso;
public:
void comer() = 0;
void dormir() = 0;
void crecer() = 0;
void respirar() = 0;
void vivir() = 0;
};
#endif /* defined(____Persona__) */
|
#include <iostream>
#include <vector>
#include <map>
#include <stack>
using namespace std;
/**********************************************************************************
*
* Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
* determine if the input string is valid.
*
* The brackets must close in the correct order, "()" and "()[]{}" are all valid
* but "(]" and "([)]" are not.
*
*
**********************************************************************************/
class Solution {
public:
bool isValid(string s) {
string stack;
int n = s.size();
int i = 0;
while (i < n) {
char c = s[i];
if (c == '[' || c == '{' || c == '(') {
stack.push_back(c);
} else if (c == ']' || c == '}' || c == ')') {
if (stack.size() <= 0) return false;
char rch = stack.back();
if ((rch == '[' && c == ']') || (rch == '{' && c == '}') ||
(rch == '(' && c == ')')) {
stack.pop_back();
} else {
// not a match
return false;
}
} else {
return false;
}
i++;
}
return stack.empty();
}
};
int main() {
Solution s;
cout << s.isValid("{[()]}") << endl;
cout << true << endl;
return 0;
}
|
// Copyright (c) 2017 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _StdObjMgt_WriteData_HeaderFile
#define _StdObjMgt_WriteData_HeaderFile
#include <Standard.hxx>
#include <Storage_BaseDriver.hxx>
class StdObjMgt_Persistent;
class Standard_GUID;
//! Auxiliary data used to write persistent objects to a file.
class StdObjMgt_WriteData
{
public:
//! Auxiliary class used to automate begin and end of
//! writing object (adding opening and closing parenthesis)
//! at constructor and destructor
class ObjectSentry
{
public:
explicit ObjectSentry (StdObjMgt_WriteData& theData) : myWriteData(&theData)
{ myWriteData->myDriver->BeginWriteObjectData(); }
~ObjectSentry()
{ myWriteData->myDriver->EndWriteObjectData(); }
private:
StdObjMgt_WriteData* myWriteData;
ObjectSentry (const ObjectSentry&);
ObjectSentry& operator = (const ObjectSentry&);
};
Standard_EXPORT StdObjMgt_WriteData (const Handle(Storage_BaseDriver)& theDriver);
Standard_EXPORT void WritePersistentObject (const Handle(StdObjMgt_Persistent)& thePersistent);
template <class Persistent>
StdObjMgt_WriteData& operator << (const Handle(Persistent)& thePersistent)
{
myDriver->PutReference(thePersistent ? thePersistent->RefNum() : 0);
return *this;
}
Standard_EXPORT StdObjMgt_WriteData& operator << (const Handle(StdObjMgt_Persistent)& thePersistent);
template <class Type>
StdObjMgt_WriteData& WriteValue(const Type& theValue)
{
*myDriver << theValue;
return *this;
}
StdObjMgt_WriteData& operator << (const Standard_Character& theValue)
{ return WriteValue(theValue); }
StdObjMgt_WriteData& operator << (const Standard_ExtCharacter& theValue)
{ return WriteValue(theValue); }
StdObjMgt_WriteData& operator << (const Standard_Integer& theValue)
{ return WriteValue(theValue); }
StdObjMgt_WriteData& operator << (const Standard_Boolean& theValue)
{ return WriteValue(theValue); }
StdObjMgt_WriteData& operator << (const Standard_Real& theValue)
{ return WriteValue(theValue); }
StdObjMgt_WriteData& operator << (const Standard_ShortReal& theValue)
{ return WriteValue(theValue); }
private:
Handle(Storage_BaseDriver) myDriver;
};
Standard_EXPORT StdObjMgt_WriteData& operator <<
(StdObjMgt_WriteData& theWriteData, const Standard_GUID& theGUID);
#endif // _StdObjMgt_WriteData_HeaderFile
|
#include "Cloud.h"
#include "Platy.Game.Core/Util/Util.h"
#include <Util/Util.h>
namespace Platy
{
namespace Game
{
Cloud::Cloud(
const float& aParticleMaxSize,
const sf::Vector2f& aPosition,
const sf::Color& aColor,
const size_t& aParticleCount,
const float& anIntensity,
const float& aLifeTime,
const float& aLength,
const float& someGravity,
const bool& shouldFade)
: ParticleEmitter(
aParticleMaxSize,
EOrientation(),
aPosition,
aColor,
aParticleCount,
anIntensity,
aLifeTime,
aLength,
0,
someGravity,
INTENSITY_MODULATION_DIVIDER_SHOWER,
shouldFade,
false)
{
for (size_t i = 0; i < myParticles.size(); i++)
{
ResetParticle(i);
}
}
void Cloud::ResetParticle(const size_t& anIndex)
{
myParticles[anIndex].velocity =
Util::DegToVec2(Core::Util::RandFloat(0, 360));
myParticleVertices[anIndex * 4].position = GetCloudPosition();
myParticleVertices[anIndex * 4].position += sf::Vector2f(0, Core::Util::RandFloat(-20, 20));
ParticleEmitter::ResetParticle(anIndex);
}
sf::Vector2f Cloud::GetCloudPosition() const
{
return {myPosition.x + Core::Util::RandFloat(0, myLength), myPosition.y};
}
}
}
|
#include<iostream>
#include<vector>
#include<cstdlib>
#include<cstdio>
#include<cmath>
#define ull1 long long
using namespace std;
int modulo(int a,int b,int c){
long long x=1,y=a; // long long is taken to avoid overflow of intermediate results
while(b > 0){
if(b%2 == 1){
x=(x*y);
if(x>=c)
x%=c;
}
y = (y*y);
if(y>=c)
y%=c; // squaring the base
b /= 2;
}
return x;
}
long long mulmod(long long a,long long b,long long c){
long long x = 0,y=a%c;
while(b > 0){
if(b%2 == 1){
x = (x+y);
if(x>=c)
x%=c;
}
y = (y*2);
if(y>=c)
y%=c;
b /= 2;
}
return x;
}
bool Miller(long long p,int iteration=30){
if(p<2){
return false;
}
if(p!=2 && p%2==0){
return false;
}
long long s=p-1;
while(s%2==0){
s/=2;
}
for(int i=0;i<iteration;i++){
long long a=rand()%(p-1)+1,temp=s;
long long mod=modulo(a,temp,p);
while(temp!=p-1 && mod!=1 && mod!=p-1){
mod=mulmod(mod,mod,p);
temp *= 2;
}
if(mod!=p-1 && temp%2==0){
return false;
}
}
return true;
}
int main()
{
ull1 n,j;
int t;
scanf("%d",&t);
for(int i=0;i<t;i++)
{
scanf("%lld",&n);
n-=((n%2)==0);
for(j=n;j>1;j--)
{
if(j==2 || j==3 || j==5 || j==7 || j==11)
{
printf("%lld\n",j);
break;
}
if(j%2==0 ||j%3==0 ||j%5==0 ||j%7==0 ||j%11==0)
continue;
if(Miller(j))
{
printf("%lld\n",j);
break;
}
}
}
return 0;
}
|
#include "../include/Transfer.h"
Transfer::Transfer(){
}
void Transfer::convert(std::string filename){
std::string command = ("cd data && libreoffice --convert-to 'pdf' " + filename);
system(command.c_str());
}
std::string Transfer::upload(){
std::string filename = "./logs.pdf";
std::string command = ("cd data && curl --upload-file " + filename + " https://transfer.sh/" + filename +
" >> upload.txt");
system(command.c_str());
//system("cd ..");
std::ifstream file("data/upload.txt");
std::string fileUrl;
file >> fileUrl;
system("rm -f data/upload.txt");
system("rm -f data/logs.pdf");
return fileUrl;
}
|
#include<iostream>
using namespace std;
int sum_digi(int n,int sum)
{
if(n<10)
return sum+n;
return sum_digi(n/10,(n%10)+sum);
} //tail recursive
int main(int argc,char* argv[])
{
int n;
cin>>n;
cout<<sum_digi(n,0);
}
|
#include<bits/stdc++.h>
using namespace std;
main()
{
int n,m;
while(cin>>n>>m)
{
int ans;
ans = n+(floor((n-1)/(m-1)));
cout<<ans<<endl;
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.