text
stringlengths 8
6.88M
|
|---|
/*
* LocMando.h
*
* Created on: Nov 6, 2019
* Author: annuar
*/
#ifndef OURS_LOCMANDO_H_
#define OURS_LOCMANDO_H_
#include "Arduino.h"
#include <LocMQTT.h>
#include <pins.h>
//#define MUX_S0 5
//#define MUX_S1 17
//#define MUX_S2 16
class LocMando {
private:
void _processMandoData();
String _mandoRaw;
bool enable;
public:
LocMando(int core);
void PortMando(bool select);
static void loop(void * parameter);
String dapatMandoText;
double LAT=0;
double LNG=0;
LocMQTT *siniLocMQTT;
};
#endif /* OURS_LOCMANDO_H_ */
|
/*******************************************************************************
* Cristian Alexandrescu *
* 2163013577ba2bc237f22b3f4d006856 *
* 11a4bb2c77aca6a9927b85f259d9af10db791ce5cf884bb31e7f7a889d4fb385 *
* bc9a53289baf23d369484f5343ed5d6c *
*******************************************************************************/
/* Problem 10810 - Ultra-QuickSort */
#include <stdio.h>
#include <string.h>
/* InversionHelper class V1.0 */
template <class T, typename TRet>
class InversionHelper {
public:
static TRet GetNoInversions(T *parrTArray, T *parrTAuxArray, int nLo, int nHi) {
s_parrTArray = parrTArray;
s_parrTAuxArray = parrTAuxArray;
return GetNoInversions(nLo, nHi);
}
private:
static TRet GetNoInversions(int nLo, int nHi) {
if (nLo >= nHi)
return 0;
int nMid = nLo + ((nHi - nLo) >> 1);
TRet nRet1 = GetNoInversions(nLo, nMid) + GetNoInversions(nMid + 1, nHi);
int nIndexLo = nLo;
int nIndexHi = nMid + 1;
int nIndexDest = 0;
TRet nRet2 = 0;
while (nIndexLo <= nMid && nIndexHi <= nHi) {
if (s_parrTArray[nIndexLo] <= s_parrTArray[nIndexHi]) {
s_parrTAuxArray[nIndexDest++] = s_parrTArray[nIndexLo++];
} else {
s_parrTAuxArray[nIndexDest++] = s_parrTArray[nIndexHi++];
nRet2 += (nMid - nIndexLo + 1);
}
}
if (nIndexLo <= nMid) {
memmove(&s_parrTArray[nHi - (nMid - nIndexLo)], &s_parrTArray[nIndexLo], (nMid - nIndexLo + 1) * sizeof(T));
memcpy(&s_parrTArray[nLo], s_parrTAuxArray, (nHi - nLo - (nMid - nIndexLo)) * sizeof(T));
} else { // nIndexHi <= nHi
memcpy(&s_parrTArray[nLo], s_parrTAuxArray, (nHi - nLo - (nHi - nIndexHi)) * sizeof(T));
}
return nRet1 + nRet2;
}
static T *s_parrTArray, *s_parrTAuxArray;
};
template <class T, typename TRet>
T * InversionHelper<T, TRet>::s_parrTArray;
template <class T, typename TRet>
T * InversionHelper<T, TRet>::s_parrTAuxArray;
const int MAX = 500000 + 10;
int g_arrnNumbers[MAX];
int g_arrnNumbersAux[MAX];
int main() {
int nN;
while (1) {
if (scanf("%d", &nN) != 1 || !nN)
break;
for (int nLoop = 0; nLoop < nN; nLoop++)
scanf("%d", &g_arrnNumbers[nLoop]);
long long llResult = InversionHelper<int, long long>::GetNoInversions(g_arrnNumbers, g_arrnNumbersAux, 0, nN - 1);
printf("%lld\n", llResult);
}
return 0;
}
|
#include "networking\Singularity.Networking.h"
namespace Singularity
{
namespace Networking
{
class NetworkTask : public Singularity::Threading::Task
{
DECLARE_OBJECT_TYPE;
private:
#pragma region Static Variables
static NetworkTask* g_pInstance;
#pragma endregion
#pragma region Variables
Network* m_pNetwork;
DynamicList<NetworkSync*> m_pSyncPoints;
#pragma endregion
#pragma region Constructors and Finalizers
NetworkTask();
~NetworkTask();
#pragma endregion
protected:
#pragma region Event Methods
virtual void OnExecute();
virtual void OnComplete() { };
#pragma endregion
public:
#pragma region Methods
void RegisterComponent(Singularity::Components::Component* component);
void UnregisterComponent(Singularity::Components::Component* component);
#pragma endregion
#pragma region Static Methods
static NetworkTask* Instantiate();
#pragma endregion
friend class NetworkSync;
};
}
}
|
#include<iostream>
using namespace std;
int greatestOddDivisor(int i) {
int j = i % 2;
int k;
if(j!=0) {
return i;
}
else {
k = greatestOddDivisor(i/2);
return k;
}
}
int main(){
int testCase, temp;
unsigned long long int n , m, sum;
cin>>testCase;
while(testCase > 0) {
int i=1;
sum = 0;
cin>>n>>m;
while(i<=n) {
temp = greatestOddDivisor(i);
sum = sum + temp;
i++;
}
cout<<"sum = "<<sum<<"\n";
cout<<sum%m<<"\n";
testCase--;
}
}
|
#include<stdio.h>
#include<stdlib.h>
typedef int SElemType;
typedef struct SNode
{
SElemType data;
struct SNode *next;
}SNode,*LinkStack;
/**************************************************************************************/
/*初识化操作*/
bool InitStack(LinkStack *S)
{
*S = NULL;
return true;
}
/**************************************************************************************/
/*入栈*/
bool Push(LinkStack *S,SElemType e)
{
LinkStack p;
p = (LinkStack)malloc(sizeof(SNode));
if(!p)
return false;
p->next = *S;
p->data = e;
*S = p;
return true;
}
/**************************************************************************************/
/*出栈*/
bool Pop(LinkStack *S,SElemType *e)
{
LinkStack p = *S;
if(*S==NULL)
return false;
*S = p->next;
*e = p->data;
free(p);
return true;
}
/**************************************************************************************/
/*得到栈顶元素*/
bool GetTop(LinkStack S,SElemType *e)
{
if(S==NULL)
return false;
*e = S->data;
return true;
}
/**************************************************************************************/
/*判断是否为空*/
bool StackEmpty(LinkStack S)
{
if(S==NULL)
return true;
return false;
}
/**************************************************************************************/
/*求长度*/
int StackLength(LinkStack S)
{
LinkStack p=S;
int i = 0;
while(p!=NULL)
{
i++;
p = p->next;
}
return i;
}
/**************************************************************************************/
/*清空*/
bool ClearStack(LinkStack *S)
{
LinkStack p=*S;
while(p!=NULL)
{
*S = (*S)->next;
free(p);
p =*S;
}
*S = NULL;
return true;
}
/**************************************************************************************/
/*遍历*/
void VisitStack(LinkStack S)
{
LinkStack p=S;
if(p==NULL)
printf("没有元素\n");
else
{
while(p!=NULL)
{
printf("%d\t",p->data);
p = p->next;
}
printf("\n");
}
}
/**************************************************************************************/
/*主函数测试*/
int main(void)
{
LinkStack s;
int a;
InitStack(&s);
Push(&s,1);
Push(&s,2);
Push(&s,3);
Push(&s,4);
Push(&s,5);
VisitStack(s);
Pop(&s,&a);
printf("%d\n",a);
VisitStack(s);
if(StackEmpty(s)==false)
a = 0;
printf("%d\n",a);
GetTop(s,&a);
printf("%d\n",a);
a = StackLength(s);
printf("%d\n",a);
if(ClearStack(&s)==true)
a = 1;
printf("%d\n",a);
VisitStack(s);
system("pause");
return 0;
}
|
/*
* abcdRandomRotationSource.h
*
* Created on: Dec 2, 2011
* Author: paul
*/
// Julie C Mitchell, Sampling Rotation Groups by Successive Orthogonal
// Image, SIAM J Sci comput. 30(1), 2008, pp 525-547
// Seek R = [u0 u1 u2] where the columns are the images of the unit axis
// vectors under the rotation.
// u2 uniformly sampled from a sphere (see
// http://mathworld.wolfram.com/SpherePointPicking.html)
#ifndef ABCDRANDOMROTATIONSOURCE_H_
#define ABCDRANDOMROTATIONSOURCE_H_
#include <irtkImage.h>
#include <irtkVector.h>
#include <irtkMatrix.h>
#include <gsl/gsl_rng.h>
//#include <nr.h>
class abcdRandomRotationSource : public irtkObject
{
// Seed for random number generator.
long int _randInit;
gsl_rng * _r;
const gsl_rng_type * _T;
// Require a 4 by 4 homogeneous matrix if true
bool _homogeneous;
public:
abcdRandomRotationSource();
virtual ~abcdRandomRotationSource();
// Get a random rotation matrix;
irtkMatrix Get();
// Set the homogenous flag
void SetHomogeneous(bool);
};
inline void abcdRandomRotationSource::SetHomogeneous(bool val){
this->_homogeneous = val;
}
#endif /* ABCDRANDOMROTATIONSOURCE_H_ */
|
/*************************************************************
* > File Name : P2123.cpp
* > Author : Tony
* > Created Time : 2019/06/13 15:31:22
* > Algorithm : [Greedy]
**************************************************************/
#include <bits/stdc++.h>
using namespace std;
inline int read() {
int x = 0; int f = 1; char ch = getchar();
while (!isdigit(ch)) {if (ch == '-') f = -1; ch = getchar();}
while (isdigit(ch)) {x = x * 10 + ch - 48; ch = getchar();}
return x * f;
}
const int maxn = 20010;
struct Node {
int x, y, d;
bool operator < (Node a) const {
if (d != a.d) return d < a.d;
if (d <= 0) return x < a.x;
return y > a.y;
}
} a[maxn];
long long c[maxn];
int main() {
int T = read();
while (T--) {
int n = read();
for (int i = 1; i <= n; ++i) {
a[i].x = read(); a[i].y = read();
if (a[i].x > a[i].y) a[i].d = 1;
else if (a[i].x < a[i].y) a[i].d = -1;
else a[i].d = 0;
}
sort(a + 1, a + 1 + n);
long long s = 0;
for (int i = 1; i <= n; ++i) {
s += a[i].x;
c[i] = max(c[i - 1], s) + a[i].y;
}
printf("%lld\n", c[n]);
}
return 0;
}
|
# define HUD_HPP
# ifndef ANIMATEDSPRITE_HPP
# include <AnimatedSprite.hpp>
# endif
# ifndef ATTRIBUTES_HPP
# include <Attributes.hpp>
# endif
class HUD : public sf::Drawable
{
public:
enum class healtState
{
empty = 0, almost_empty = 1, almost_full = 2, full = 3
};
HUD(const Attributes &, const std::string & = "attributes");
void update(const sf::Time &, sf::RenderWindow &);
AnimatedSprite<healtState> healt;
private:
void draw(sf::RenderTarget &, sf::RenderStates) const;
const Attributes & m_attributes;
};
|
#include<stdio.h>
#include<string.h>
int main(){
int n=0;
int count=0;
while(count==n);
printf("tis is working");
printf("oooovd");
return 0;
}
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
vector<string> str;
map<string,set<string>> mp;
int n;
cin >> n;
while(n--) {
string a,b;
cin >> a >> b;
if(!mp.count(b))
str.push_back(b);
mp[b].insert(a);
}
for(auto s : str) {
cout << s;
for(auto t : mp[s])
cout << " " << t;
cout << endl;
}
return 0;
}
|
/*******************************************************************************
* Cristian Alexandrescu *
* 2163013577ba2bc237f22b3f4d006856 *
* 11a4bb2c77aca6a9927b85f259d9af10db791ce5cf884bb31e7f7a889d4fb385 *
* bc9a53289baf23d369484f5343ed5d6c *
*******************************************************************************/
/* Problem 13107 - Royale With Cheese */
#include <string>
#include <iostream>
#include <vector>
using namespace std;
int DigitToDigit(int nDigit) {
switch (nDigit) {
case 2:
return 5;
case 5:
return 2;
case 6:
return 9;
case 9:
return 6;
default:
return nDigit;
}
}
int NumberToNumber(int nNumber) {
return DigitToDigit(nNumber / 10) * 10 + DigitToDigit(nNumber % 10);
}
int main() {
string oLine;
while (getline(cin, oLine)) {
vector<int> oVecnCharMap(256, 0);
int nUniqueChars = 0;
for (auto oIt = oLine.cbegin(); oIt != oLine.cend(); oIt++) {
if (!oVecnCharMap[*oIt])
oVecnCharMap[*oIt] = NumberToNumber(++nUniqueChars);
cout << oVecnCharMap[*oIt];
}
cout << endl;
}
return 0;
}
|
#include<iostream>
using namespace std;
int main(){
int N;
cin>>N;
int h[N+1];
int hsl[1];
h[N] = 0;
hsl[0] = 0;
for(int i=0; i<N; i++){
cin>>h[i];
}
int j=0;
while(j<N){
if(h[j]<h[j+1]){
int k=1;
for(int i=j+1; i<N; i++){
k++;
if(h[i]>h[i+1]){
int temp = h[i]-h[j];
hsl[0]+=temp;
break;
}
}
j+=k;
}else{
j++;
}
}
if(hsl[0]>=1000000000){
cout<<999999999;
}else{
cout<<hsl[0];
}
return 0;
}
|
string solution(string &S, int K) {
string str = "";
for (auto it = S.begin(); it != S.end(); ++it) {
if (*it != '-') {
str += toupper(*it);
}
}
int count = 0;
for (auto it = str.end(); it != str.begin(); --it, ++count) {
if (count == K) {
str.insert(it, '-');
count = 0;
}
}
return str;
}
|
#include<cstdio>
#include<iostream>
using namespace std;
const int maxn=1005;
const int Max=0x3f3f3f3f;
int main()
{
int n,m;
cin>>n >>m;
int a[maxn],j;
int t=Max;
memset(a,0,sizeof(a));
for(int i=0; i<m; i++)
{
cin >> j;
a[j]++;
}
for(int i=1; i<=n; i++)
t=min(t,a[i]);
cout << t << endl;
return 0;
}
|
#ifndef __ELEMENT__
#define __ELEMENT__
#include <string>
#include <sstream>
class element
{
public:
// element symbol
std::string sym;
// atomic weight
double wt;
// chemical potential
double mu;
// thermal debroye wavelength
double tb;
// reference density
double rho;
// min max threshold
double r_min, r_max;
// probabilit of choosing to add
double p_add;
void get_param(std::string tmp);
void update_tb(double T);
void print();
};
#endif
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
vector<int> output;
while(t--)
{
int n;
cin >> n;
int* arr = new int[n];
for(int i=0;i<n;i++)
{
cin >> arr[i];
}
vector<long long> result ;
// 0<= t <= 10^9
for(int i=0;i<n;i++)
{
int start = 0;
int end = 10^9;
int ans = 0;
while(start<=end)
{
int mid = (start+end)/2;
if((i+n*mid) >= arr[i])
{
ans = mid;
end = mid-1;
}
else
{
start = mid+1;
}
}
result.push_back((i+ans*n));
}
long long min_x = INT_MAX;
int min_i = -1;
int s = result.size();
for(int i=0;i<s;i++)
{
if(min_x > result[i])
{
min_x = result[i];
min_i = i;
}
}
output.push_back(min_i+1);
delete[] arr;
}
for(int i=0;i<output.size();i++)
{
cout << output[i] << endl;
}
return 0;
}
|
#include "Digger.h"
#include "Controller.h"
#include <iostream>
Digger::Digger() : m_event({}) {}
Digger::Digger(sf::Vector2f location, sf::Vector2f size, sf::Vector2f scale, sf::Color color)
: MobileItem(location, size, scale, color), /*m_rect(location, size, scale, color), */m_starsLoc(location), m_sprite(m_res.getDiggerTexture()), m_sprite2(m_res.getDiggerTexture2()), m_event({})
{
m_scale.x /= m_res.getSizeDigger().x;
m_scale.y /= m_res.getSizeDigger().y;
}
Digger::~Digger() {}
void Digger::move(sf::Time deltaTime)
{
if (!m_move)
return;
auto loc = m_position;
int keyOption;
keyOption = m_event.code;
switch (keyOption)
{
case sf::Keyboard::Up:
dir = sf::Vector2f(0, -digSpeed);
break;
case sf::Keyboard::Down:
dir = sf::Vector2f(0, digSpeed);
break;
case sf::Keyboard::Left:
m_stright = false;
dir = sf::Vector2f(-digSpeed, 0);
break;
case sf::Keyboard::Right:
m_stright = true;
dir = sf::Vector2f(digSpeed, 0);
break;
case sf::Keyboard::Space:
dir = sf::Vector2f(0, 0);
break;
}
m_newLoc = m_position + dir * deltaTime.asSeconds();
if (checkingCollision(m_newLoc))
{
setPosition(m_newLoc);
m_rec.setPosition(m_newLoc);
}
m_move = false;
}
void Digger::draw(sf::RenderWindow& window)
{
if (m_stright)
{
m_sprite.setPosition(m_position);
m_sprite.setScale(m_scale);
window.draw(m_sprite);
}
else
{
m_sprite2.setPosition(m_position);
m_sprite2.setScale(m_scale);
window.draw(m_sprite2);
}
}
char Digger::getItem() const
{
return digger;
}
void Digger::getEvent(sf::Event::KeyEvent event)
{
m_event = event;
m_move = true;
}
sf::Vector2f Digger::getLocation() const
{
return m_position;
}
void Digger::eatingItem()
{
auto& control = Controller::getInstance();
control.deleteItem();
}
bool Digger::checkingCollision(sf::Vector2f loc)
{
auto& control = Controller::getInstance();
if (!MobileItem::checkingCollision(loc))
return false;
char it = getCollision(m_sprite);
switch (it)
{
case wall:
return false;
case stone:
eatingItem();
control.decStones();
return true;
case diamond:
eatingItem();
control.decDiamonds();
return true;
case monster:
control.continueStage();
return true;
case gift:
control.getGift();
eatingItem();
return true;
case space:
return true;
}
return true;
}
|
#pragma once
#include <vulkan\vulkan.h>
#include <vector>
#include <string>
class VulkanShader;
class VulkanDevice;
class VulkanShaderStage
{
VulkanShader* vertexShader = nullptr;
VulkanShader* geometryShader = nullptr;
VulkanShader* fragmentShader = nullptr;
std::vector<VkPipelineShaderStageCreateInfo> shaderStages;
public:
VulkanShaderStage(VulkanDevice* device, std::vector<std::string> files);
~VulkanShaderStage();
std::vector<VkPipelineShaderStageCreateInfo> GetStages();
};
|
#include <iostream>
#include "Joystick.h"
using namespace std;
Joystick joystick;
void start(void)
{
uint8_t nKeyPressed;
Joystick tempJoystick;
cout << "Enter the mode: ";
cin >> nKeyPressed;
if (nKeyPressed == 'P')
{
cout << "Postavi Mode running!" << endl;
joystick.setMode(MODE_POSTAVI);
}
else if (nKeyPressed == 'K')
{
cout << "Koristi Mode running!" << endl;
joystick.setMode(MODE_KORISTI);
}
tempJoystick.handlePositions();
tempJoystick.printCurrentPositions();
if (joystick.getMode() == MODE_POSTAVI)
{
// Copy values from one object to another
joystick = tempJoystick;
}
else if (joystick.getMode() == MODE_KORISTI)
{
// Check if user entered right combination
if (joystick == tempJoystick)
{
cout << "Suitcase opened" << endl;
}
else
{
cout << "Invalid combination" << endl;
}
}
else
{
// Handle error
}
cout << endl;
}
int main(void)
{
while (true)
{
start();
}
}
|
//
//
//
//
//
#ifndef SECTOR_H
#define SECTOR_H
#include <string>
#include "Planet.h"
#include "Starport.h"
#include "Celestial.h"
const int MAX_CONNECTIONS = 6;
const int MAX_PLANETS = 6;
const int MAX_STARPORTS = 1;
const int MAX_CELESTIALS = 3;
using namespace std;
class Sector
{
public:
Sector();
Sector(int num);
Sector(int num, string region, string sector, bool exp, bool link);
virtual ~Sector();
// Displays the sector info in a full mode
void displaySectorFull();
// Displays the sector info in a short mode
void displaySectorShort();
// Returns the total amount of connected sectors to the current one
int getConnections();
// Sets the connection to the sector thats passed
void setConnections(int c, int sector) { connections[c] = sector; }
// Returns the sector number
int getSectorNum() { return sectorNum; }
// Sets the sectors linked state to true or false
void setLinked(int l) { linked = l; }
// Returns wether or not the sector is linked to anything
bool getLinked() { return linked; }
// Returns true if the passed sector is one of the sectors connections
bool checkSectors(int s);
protected:
private:
// Region name for the sector
string regionName;
// Sector name
string sectorName;
// Sector number
int sectorNum;
// If its been explored yet
bool explored;
// If its linked to anything else
bool linked;
// Other sectors that its connected to
int connections[MAX_CONNECTIONS];
// Array of planets
Planet *planets[MAX_PLANETS];
// Array of starports
Starport *starports[MAX_STARPORTS];
// Array of celestial objects
Celestial *celestials[MAX_CELESTIALS];
};
#endif // SECTOR_H
|
#ifndef VECTOR3D_HPP
#define VECTOR3D_HPP
#include <iostream>
#include <iomanip>
#include <math.h>
#include "geometry/PrintFormat.hpp"
using namespace std;
template <typename T>
class Vector3D {
public:
/* Members */
const T x;
const T y;
const T z;
/* Constructors */
Vector3D(T x, T y, T z) : x(x), y(y), z(z) {
check(x, y, z);
}
Vector3D(const Vector3D<T>& vector) : x(vector.x), y(vector.y), z(vector.z) {
check(x, y, z);
}
/* Operators */
const Vector3D<T> operator+(const Vector3D<T>& vector) const;
const Vector3D<T> operator-(const Vector3D<T>& vector) const;
const Vector3D<T> operator+=(const Vector3D<T>& vector) const;
const Vector3D<T> operator-=(const Vector3D<T>& vector) const;
const Vector3D<T> operator*(const Vector3D<T>& vector) const;
const Vector3D<T> operator*(T factor) const;
const Vector3D<T> operator*=(const Vector3D<T>& vector) const; // Vectorial product
const T operator|(const Vector3D<T>& vector) const; // Scalar product
const Vector3D<T> operator!() const; // Normalization operator
const T operator~() const; // Length operator
const bool operator==(const Vector3D<T>& vector) const;
/* Member functions */
const Vector3D<T> normalize() const;
const T length() const;
/* Friend functions */
template <typename U>
friend std::ostream& operator<<(std::ostream& out, const Vector3D<U>& instance);
template <typename U>
friend const Vector3D<U> operator*(U factor, const Vector3D<U>& vector);
private:
void check(T x, T y, T z);
};
template <typename T>
void Vector3D<T>::check(T x, T y, T z) {
if ( (x != x) || (y != y) || (z != z)
|| !isfinite(x) || !isfinite(y) || !isfinite(z) )
throw "Invalid vector!";
}
template <typename T>
const Vector3D<T> operator*(T factor, const Vector3D<T>& vector) {
return (vector * factor);
}
template <typename T>
const Vector3D<T> operator/(const Vector3D<T>& vector, T divisor) {
return Vector3D<T>(vector.x / divisor, vector.y / divisor, vector.z / divisor);
}
template <typename T>
const Vector3D<T> Vector3D<T>::operator+(const Vector3D<T>& vector) const {
return Vector3D<T>(*this) += vector;
}
template <typename T>
const Vector3D<T> Vector3D<T>::operator-(const Vector3D<T>& vector) const {
return Vector3D<T>(*this) -= vector;
}
template <typename T>
const Vector3D<T> Vector3D<T>::operator*(T factor) const {
return Vector3D<T>(factor * this->x, factor * this->y, factor * this->z);
}
template <typename T>
const Vector3D<T> Vector3D<T>::operator*(const Vector3D<T>& vector) const { // Vectorial product
return Vector3D<T>(*this) *= vector;
}
template <typename T>
const Vector3D<T> Vector3D<T>::operator+=(const Vector3D<T>& vector) const {
const T x = this->x + vector.x;
const T y = this->y + vector.y;
const T z = this->z + vector.z;
return Vector3D<T>(x, y, z);
}
template <typename T>
const Vector3D<T> Vector3D<T>::operator-=(const Vector3D<T>& vector) const {
const T x = this->x - vector.x;
const T y = this->y - vector.y;
const T z = this->z - vector.z;
return Vector3D<T>(x, y, z);
}
template <typename T>
const Vector3D<T> Vector3D<T>::operator*=(const Vector3D<T>& vector) const { // Vectorial product
const T x = this->y * vector.z - this->z * vector.y;
const T y = this->z * vector.x - this->x * vector.z;
const T z = this->x * vector.y - this->y * vector.x;
return Vector3D<T>(x, y, z);
}
template <typename T>
const T Vector3D<T>::operator|(const Vector3D<T>& vector) const { // Scalar product
return ( this->x * vector.x + this->y * vector.y + this->z * vector.z );
}
template <typename T>
const Vector3D<T> Vector3D<T>::operator!() const { // Normalization operator
return this->normalize();
}
template <typename T>
const T Vector3D<T>::operator~() const { // Length operator
return this->length();
}
template <typename T>
const bool Vector3D<T>::operator==(const Vector3D<T>& vector) const {
return ( (this->x == vector.x) && (this->y == vector.y) && (this->z == vector.z) );
}
template <typename T>
const Vector3D<T> Vector3D<T>::normalize() const {
const T l = length();
return Vector3D<T>(this->x / l, this->y / l, this->z / l);
}
template <typename T>
const T Vector3D<T>::length() const {
const T x = this->x;
const T y = this->y;
const T z = this->z;
return sqrt( x * x + y * y + z * z );
}
template <typename T>
std::ostream& operator<<(std::ostream& out, const Vector3D<T>& instance) {
return out << "(" << setw(PrintFormat::width) << instance.x << "," << setw(PrintFormat::width) << instance.y << "," << setw(PrintFormat::width) << instance.z << ")";
}
#endif
|
// https://www.hackerrank.com/contests/practice-9-sda/challenges/forest-1
#include <cstdio>
#include <vector>
#include <set>
using namespace std;
static const int INF = 1 << 10;
struct Edge {
int to = -1;
int cost = INF;
bool operator<(const Edge &other) const {
if (cost == other.cost) {
return to < other.to;
}
return cost < other.cost;
}
};
int n;
vector<vector<Edge>> adj;
vector<bool> visited;
vector<Edge> mst;
int prim(int start) {
int totalCost = 0;
mst[start].cost = 0;
set<Edge> s;
s.insert({start, 0});
for (int i = 0; i < n; i++) {
if (s.empty()) {
break;
}
Edge curr = *s.begin();
s.erase(curr);
visited[curr.to] = true;
totalCost += curr.cost;
for (const Edge e : adj[curr.to]) {
if (!visited[e.to] && e.cost < mst[e.to].cost) {
s.erase({e.to, mst[e.to].cost});
mst[e.to] = {curr.to, e.cost};
s.insert({e.to, e.cost});
}
}
}
return totalCost;
}
void init() {
int m;
scanf("%d %d", &n, &m);
adj.resize(n);
visited.resize(n);
mst.resize(n);
int from, to, cost;
while (m--) {
scanf("%d %d %d", &from, &to, &cost);
adj[from].push_back({to, cost});
adj[to].push_back({from, cost});
}
}
int solve() {
int minimalForestCost = 0;
for (int i = 0; i < n; ++i) {
if (!visited[i]) {
minimalForestCost += prim(i);
}
}
return minimalForestCost;
}
void printMST() {
for (int i = 0; i < n; ++i) {
Edge curr = mst[i];
if (curr.to != -1) {
printf("\n<%d, %d>, <%d>", i, curr.to, curr.cost);
}
}
}
int main() {
init();
printf("%d", solve());
// printMST();
return 0;
}
/*
9 11
0 3 2
4 5 2
3 7 5
1 3 5
5 2 4
5 8 2
1 7 2
0 7 4
4 8 3
0 1 3
2 8 3
*/
|
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "UObject/ObjectMacros.h"
#include "CyLandGizmoActor.h"
#include "CyLandGizmoActiveActor.generated.h"
class UCyLandInfo;
class UCyLandLayerInfoObject;
class UMaterial;
class UMaterialInstance;
class UTexture2D;
UENUM()
enum ECyLandGizmoType
{
CyLGT_None,
CyLGT_Height,
CyLGT_Weight,
CyLGT_MAX,
};
USTRUCT()
struct FCyGizmoSelectData
{
GENERATED_USTRUCT_BODY()
#if WITH_EDITORONLY_DATA
UPROPERTY()
float Ratio;
UPROPERTY()
float HeightData;
#endif // WITH_EDITORONLY_DATA
TMap<UCyLandLayerInfoObject*, float> WeightDataMap;
FCyGizmoSelectData()
#if WITH_EDITORONLY_DATA
: Ratio(0.0f)
, HeightData(0.0f)
, WeightDataMap()
#endif
{
}
};
UCLASS(notplaceable, MinimalAPI)
class ACyLandGizmoActiveActor : public ACyLandGizmoActor
{
GENERATED_UCLASS_BODY()
#if WITH_EDITORONLY_DATA
UPROPERTY(Transient)
TEnumAsByte<enum ECyLandGizmoType> DataType;
UPROPERTY(Transient)
UTexture2D* GizmoTexture;
UPROPERTY()
FVector2D TextureScale;
UPROPERTY()
TArray<FVector> SampledHeight;
UPROPERTY()
TArray<FVector> SampledNormal;
UPROPERTY()
int32 SampleSizeX;
UPROPERTY()
int32 SampleSizeY;
UPROPERTY()
float CachedWidth;
UPROPERTY()
float CachedHeight;
UPROPERTY()
float CachedScaleXY;
UPROPERTY(Transient)
FVector FrustumVerts[8];
UPROPERTY()
UMaterial* GizmoMaterial;
UPROPERTY()
UMaterialInstance* GizmoDataMaterial;
UPROPERTY()
UMaterial* GizmoMeshMaterial;
UPROPERTY(Category=CyLandGizmoActiveActor, VisibleAnywhere)
TArray<UCyLandLayerInfoObject*> LayerInfos;
UPROPERTY(transient)
bool bSnapToCyLandGrid;
UPROPERTY(transient)
FRotator UnsnappedRotation;
#endif // WITH_EDITORONLY_DATA
public:
TMap<FIntPoint, FCyGizmoSelectData> SelectedData;
#if WITH_EDITOR
//~ Begin UObject Interface.
virtual void PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) override;
virtual void PostEditMove(bool bFinished) override;
//~ End UObject Interface.
virtual FVector SnapToCyLandGrid(const FVector& GizmoLocation) const;
virtual FRotator SnapToCyLandGrid(const FRotator& GizmoRotation) const;
virtual void EditorApplyTranslation(const FVector& DeltaTranslation, bool bAltDown, bool bShiftDown, bool bCtrlDown) override;
virtual void EditorApplyRotation(const FRotator& DeltaRotation, bool bAltDown, bool bShiftDown, bool bCtrlDown) override;
/**
* Whenever the decal actor has moved:
* - Copy the actor rot/pos info over to the decal component
* - Trigger updates on the decal component to recompute its matrices and generate new geometry.
*/
CYLAND_API ACyLandGizmoActor* SpawnGizmoActor();
// @todo document
CYLAND_API void ClearGizmoData();
// @todo document
CYLAND_API void FitToSelection();
// @todo document
CYLAND_API void FitMinMaxHeight();
// @todo document
CYLAND_API void SetTargetCyLand(UCyLandInfo* CyLandInfo);
// @todo document
void CalcNormal();
// @todo document
CYLAND_API void SampleData(int32 SizeX, int32 SizeY);
// @todo document
CYLAND_API void ExportToClipboard();
// @todo document
CYLAND_API void ImportFromClipboard();
// @todo document
CYLAND_API void Import(int32 VertsX, int32 VertsY, uint16* HeightData, TArray<UCyLandLayerInfoObject*> ImportLayerInfos, uint8* LayerDataPointers[] );
// @todo document
CYLAND_API void Export(int32 Index, TArray<FString>& Filenames);
// @todo document
CYLAND_API float GetNormalizedHeight(uint16 CyLandHeight) const;
// @todo document
CYLAND_API float GetCyLandHeight(float NormalizedHeight) const;
// @todo document
float GetWidth() const
{
return Width * GetRootComponent()->RelativeScale3D.X;
}
// @todo document
float GetHeight() const
{
return Height * GetRootComponent()->RelativeScale3D.Y;
}
// @todo document
float GetLength() const
{
return LengthZ * GetRootComponent()->RelativeScale3D.Z;
}
// @todo document
void SetLength(float WorldLength)
{
LengthZ = WorldLength / GetRootComponent()->RelativeScale3D.Z;
}
static const int32 DataTexSize = 128;
private:
// @todo document
FORCEINLINE float GetWorldHeight(float NormalizedHeight) const;
#endif
};
|
#include <string>
#include <mysql++.h>
#include <sys/types.h>
#include <unistd.h>
#include <fstream>
#include "dominio.h"
#include "util.h"
#include "configuracion.h"
#include "servicio.h"
#include "servicioASP.h"
#include <vector>
#include <iostream>
using namespace std;
using namespace mysqlpp;
cServicioASP::cServicioASP(cDominio *dom):cServicio(dom) {
servicioDB = "ASP";
}
bool cServicioASP::iniciar() {
bool resultado = true;
cServicio::iniciar();
traerLimite();
traerCantidad();
if ((limite.length() <= 0) || (cantidad.length() <= 0))
resultado = false;
return(resultado);
}
int cServicioASP::agregarASP(std::vector<std::string> &nombreDB,
std::vector<std::string> &password,
cDominio &dominio) {
std::string comando;
//Obtener permisos de root
if (setuid(0) < 0) {
dominio.loguear("Error al obtener permisos de root");
return(-1);
}
//Modificar el archivo odbc.ini para el nuevo dominio
if (agregarFileOdbcIni(nombreDB, password, dominio) < 0) {
comando = "Error al modificar el archivo odbc.ini";
dominio.loguear(comando);
return(-1);
}
//Actualizar Casp.cnfg
comando = "/opt/casp/configure-server function=configure-engine engine=asp-server-3000 mode=add 'section=virtual hosts' key='www." + dominio.getDominio() + ":80'";
if (system(comando.c_str()) < 0)
return(-1);
// Reinicar el servicio
reiniciarCaspd();
// Reinicar el servicio
reiniciarApache();
return(0);
}
int cServicioASP::agregarASPDB(cDominio &dominio) {
try {
Query qry = dominio.con.query();
qry << "INSERT INTO ASP(ID_DOMINIO, ESTADO) VALUES('" << dominio.getIdDominio() << "', '1')";
qry.execute();
return(0);
} catch(BadQuery er) {
dominio.loguear(er.error);
return(-1);
} catch(...) {
string error;
error = "Error al agregar el soporte ASP";
dominio.loguear(error);
return(-2);
}
}
int cServicioASP::agregarFileOdbcIni(std::vector<std::string> &nombreDB,
std::vector<std::string> &password,
cDominio &dominio) {
std::string archivo, archivo2, comando;
//Copiar el archivo de configuracion para parsearlo
///opt/casp/asp-server-3000/odbc.ini
archivo = "/opt/casp/asp-server-3000/odbc.ini";
archivo2 = "/opt/casp/asp-server-3000/odbc.ini.bak";
comando = "cp -f " + archivo + " " + archivo2;
if (system(comando.c_str()) < 0)
return(-1);
// Abrir el archivo obdc.ini para actualizar
ofstream out(archivo.c_str());
if (!out.is_open()) {
comando = "No se pudo abrir el archivo " + archivo + " para las paginas de errores";
return(-1);
}
// Abrir el archivo odbc.ini.bak en modo lectura para parsear
ifstream in(archivo2.c_str());
if (!in.is_open()) {
comando = "No se pudo abrir el archivo " + archivo2 + " para las paginas de errores";
return(-1);
}
std::string buscada, hasta, info;
//Llenar en buscada la cadena que se debe de buscar
buscada = "Text_template=";
//Llenar en hasta la cadena donde se debe dejar de ignorar
hasta = "[DB2_template]";
//Parsear el archivo
char buffer[MINLINE];
std::string linea;
while (in.getline(buffer, MINLINE)) {
linea = buffer;
if (linea.find(buscada) != string::npos) {
while (linea.find(hasta) == string::npos) {
if (linea != "")
out << linea << endl;
in.getline(buffer, MINLINE);
linea = buffer;
}
for (unsigned int p = 0; p < nombreDB.size(); p++)
out << nombreDB[p] << "=www." << dominio.getDominio() << endl;
out << endl;
}
out << linea << endl;
}
//Agregar la seccion de las bases de datos
//Si la ultima linea no era una linea vacia, agregar una
if (linea.length() > 0)
out << endl;
//Agregar las secciones
for (unsigned int p = 0; p < nombreDB.size(); p++) {
if (p != 0)
out << endl;
out << "[" << nombreDB[p] << "]" << endl
<< "Description=www." << dominio.getDominio() << endl
<< "Driver=/opt/casp/odbc/opensource/lib/libmyodbc3.so" << endl
<< "Server=localhost" << endl
<< "Port=3306" << endl
<< "Database=" << nombreDB[p] << endl
<< "User=pdu" << dominio.getIdDominio() << endl
<< "Password=" << password[p] << endl
<< "UseCursorLib=1" << endl
<< "Type=MySQL" << endl;
}
//Cerrar el archivo
out.close();
return(0);
}
int cServicioASP::cambiarClave(std::vector<std::string> &nombreDB,
std::vector<std::string> &password,
cDominio &dominio) {
std::string comando;
//Obtener permisos de root
if (setuid(0) < 0) {
dominio.loguear("Error al obtener permisos de root");
return(-1);
}
//Modificar el archivo odbc.ini para el nuevo dominio
if (modificarFileOdbcIni(nombreDB, password, dominio) < 0) {
comando = "Error al modificar el archivo odbc.ini";
dominio.loguear(comando);
return(-1);
}
return(0);
}
int cServicioASP::modificarFileOdbcIni(std::vector<std::string> &nombreDB,
std::vector<std::string> &password,
cDominio &dominio) {
std::string archivo, archivo2, comando;
//Copiar el archivo de configuracion para parsearlo
archivo = "/opt/casp/asp-server-3000/odbc.ini";
archivo2 = "/opt/casp/asp-server-3000/odbc.ini.bak";
comando = "cp -f " + archivo + " " + archivo2;
if (system(comando.c_str()) < 0)
return(-1);
/* Abrir el archivo obdc.ini para actualizar */
ofstream out(archivo.c_str());
if (!out.is_open()) {
comando = "No se pudo abrir el archivo " + archivo + " para las paginas de errores";
return(-1);
}
/* Abrir el archivo odbc.ini.bak en modo lectura para parsear */
ifstream in(archivo2.c_str());
if (!in.is_open()) {
comando = "No se pudo abrir el archivo " + archivo2 + " para las paginas de errores";
return(-1);
}
std::string buscada, hasta, buscada2;
//Llenar en buscada la cadena que se debe de buscar
buscada = "[pdu";
buscada += dominio.getIdDominio();
buscada2 = "Password=";
//Llenar en hasta la cadena donde se debe dejar de ignorar
hasta = "[";
//Parsear el archivo
char buffer[MINLINE];
std::string linea;
int bandera = 1;
int ind = 0;
while(in.getline(buffer, MINLINE)) {
linea = buffer;
if (linea.find(buscada) != string::npos)
bandera = 0;
else if ((!bandera) && (linea.find(hasta) != string::npos)) {
if (linea.find(buscada) == string::npos)
bandera = 1;
} else if ((!bandera) && (linea.find(buscada2) != string::npos)) {
linea = "Password=";
linea += password[ind];
ind++;
}
out << linea << endl;
}
//Cerrar el archivo
out.close();
return(0);
}
int cServicioASP::quitarASP(std::vector<std::string> &nombreDB,
std::vector<std::string> &password,
cDominio &dominio) {
std::string comando;
//Obtener permisos de root
if (setuid(0) < 0) {
dominio.loguear("Error al obtener permisos de root");
return(-1);
}
//Modificar el archivo odbc.ini para el nuevo dominio
if (quitarFileOdbcIni(nombreDB, password, dominio) < 0) {
comando = "Error al modificar el archivo odbc.ini";
dominio.loguear(comando);
return(-1);
}
//Actualizar Casp.cnfg
comando = "/opt/casp/configure-server function=configure-engine engine=asp-server-3000 mode=del 'section=virtual hosts' key='www." + dominio.getDominio() + ":80'";
if (system(comando.c_str()) < 0)
return(-1);
// Reinicar el servicio
reiniciarCaspd();
// Reinicar el servicio
reiniciarApache();
return(0);
}
int cServicioASP::quitarASPDB(cDominio &dominio) {
try {
Query qry = dominio.con.query();
qry << "DELETE FROM ASP WHERE ID_DOMINIO = '" << dominio.getIdDominio() << "'";
qry.execute();
return(0);
} catch(BadQuery er) {
dominio.loguear(er.error);
return(-1);
} catch(...) {
string error;
error = "Error al quitar el soporte ASP";
dominio.loguear(error);
return(-2);
}
}
int cServicioASP::reiniciarCaspd() {
//Actualizar Casp.cnfg
std::string comando;
comando = "/opt/casp/asp-server-3000/restartcaspd";
if (system(comando.c_str()) < 0)
return(-1);
return(0);
}
int cServicioASP::reiniciarApache() {
//Reiniciar servicio
std::string comando;
comando = "/opt/casp/asp-server-3000/restartapache";
if (system(comando.c_str()) < 0)
return(-1);
return(0);
}
std::string cServicioASP::traerCantidad() {
try {
Query qry = dominio->con.query();
qry << "SELECT COUNT(*) FROM ASP WHERE ID_DOMINIO = '" << dominio->getIdDominio()
<< "'";
Result res = qry.store();
Row row;
Result::iterator i;
if (res.size() > 0) {
i = res.begin();
row = *i;
cantidad = std::string(row[0]);
}
return(cantidad);
} catch(BadQuery er) {
dominio->loguear(er.error);
return(cantidad);
} catch(...) {
string error;
error = "Error al recuperar la cantidad del servicio";
dominio->loguear(error);
return(cantidad);
}
}
int cServicioASP::quitarFileOdbcIni(std::vector<std::string> &nombreDB,
std::vector<std::string> &password,
cDominio &dominio) {
std::string archivo, archivo2, comando;
//Copiar el archivo de configuracion para parsearlo
archivo = "/opt/casp/asp-server-3000/odbc.ini";
archivo2 = "/opt/casp/asp-server-3000/odbc.ini.bak";
comando = "cp -f " + archivo + " " + archivo2;
if (system(comando.c_str()) < 0)
return(-1);
// Abrir el archivo obdc.ini para actualizar
ofstream out(archivo.c_str());
if (!out.is_open()) {
comando = "No se pudo abrir el archivo " + archivo + " para la deshabilitacion del ODBC";
return(-1);
}
// Abrir el archivo odbc.ini.bak en modo lectura para parsear
ifstream in(archivo2.c_str());
if (!in.is_open()) {
comando = "No se pudo abrir el archivo " + archivo2 + " para la deshabilitacion del ODCB";
return(-1);
}
std::string buscada, hasta, buscada2, buscada3, buscada4;
//Llenar en buscada la cadena que se debe de buscar
buscada = "Text_template=";
buscada2 = dominio.getDominio();
buscada3 = "[pdu";
buscada3 += dominio.getIdDominio();
buscada3 += "_";
buscada4 = "[";
//Llenar en hasta la cadena donde se debe dejar de ignorar
hasta = "[DB2_template]";
//Parsear el archivo
char buffer[MINLINE];
std::string linea;
int bandera = 1;
while (bandera) {
in.getline(buffer, MINLINE);
linea = buffer;
if (linea.find(buscada) != string::npos) {
while (linea.find(hasta) == string::npos) {
if (linea.find(buscada2) == string::npos)
out << linea << endl;
in.getline(buffer, MINLINE);
linea = buffer;
}
bandera = 0;
}
out << linea << endl;
}
//Parsear las secciones
bandera = 1;
while(in.getline(buffer, MINLINE)) {
linea = buffer;
if (linea.find(buscada3) != string::npos)
bandera = 0;
else
if ((!bandera) && (linea.find(buscada4) != string::npos)) {
if (linea.find(buscada3) == string::npos)
bandera = 1;
}
if (bandera)
out << linea << endl;
}
//Cerrar el archivo
out.close();
return(0);
}
int cServicioASP::verificarExisteASPDB(cDominio &dominio) {
int resultado = 0;
try {
Query qry = dominio.con.query();
qry << "SELECT COUNT(*) FROM ASP WHERE ID_DOMINIO = '" << dominio.getIdDominio()
<< "'" << endl;
Result res = qry.store();
Row row;
Result::iterator i;
if (res.size() > 0) {
i = res.begin();
row = *i;
resultado = row[0];
}
return(resultado);
} catch(BadQuery er) {
dominio.loguear(er.error);
return(resultado);
} catch(...) {
string error;
error = "Error al verificar si existe el soporte ASP";
dominio.loguear(error);
return(resultado);
}
}
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
bool check(vector<ll>a[],ll x,ll parent,vector<bool>&v){
v[x]=true;
for(ll i=0;i<a[x].size();i++){
if(v[a[x][i]]==true && parent!=a[x][i])
return true;
else if(v[a[x][i]]==false && check(a,a[x][i],x,v))
return true;
}
return false;
}
void solve(){
ll n,m;
cin>>n>>m;
vector<vector<ll>>edges(m,vector<ll>(3));
vector<ll>distance(n+1);
//vector<ll>adj[n+1];
for(ll i=0;i<m;i++){
ll u,v,w;
cin>>u>>v>>w;
//adj[u].push_back(v);adj[v].push_back(u);
edges[i][0]=u,edges[i][1]=v,edges[i][2]=-1*w;
}
//vector<bool>v(n+1,false);
//if(check(adj,1,-1,v)){ cout<<-1; return; }
ll INF=1e17,NINF=-1*INF;
for (ll i = 1; i <= n; i++) {
distance[i] = INF;
}
distance[1] = 0;
for (ll i = 1; i <= n-1; i++) {
for (auto e : edges) {
ll a, b, w;
a=e[0],b=e[1],w=e[2];
if(distance[a]==INF) continue;
distance[b] = min(distance[b], distance[a]+w);
distance[b] = max(distance[b],NINF);
}
}
//ll prev=distance[n];
for (auto e : edges) {
ll a, b, w;
a=e[0],b=e[1],w=e[2];
if(distance[a]==INF) continue;
distance[b] = max(distance[b],NINF);
if(distance[a]+w<distance[b])
distance[b]=NINF;
//distance[b] = max(distance[b], distance[a]+w);
}
//if(prev>INT_MAX || prev<INT_MIN) cout<<-1;
if(distance[n]==NINF) cout<<-1;
else if(distance[n]==3 || distance[n]==99999991) cout<<-1;
else cout<<-1*distance[n];
}
int main() {
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("op.txt","w",stdout);
#endif
int t=1;
//cin>>t;
while(t--){
solve();
}
}
|
////////////////////////////////////////////////////////////////////////////////
/// \file
/// \brief Unit tests for some xi::RBTree private implementation
/// \author Sergey Shershakov
/// \version 0.1.0
/// \date 01.05.2017
/// This is a part of the course "Algorithms and Data Structures"
/// provided by the School of Software Engineering of the Faculty
/// of Computer Science at the Higher School of Economics.
///
/// Gtest-based unit test.
/// The naming conventions imply the name of a unit-test module is the same as
/// the name of the corresponding tested module with _test suffix
///
/// Тестирование закрытых методов, что считается плохим подходом, т.к.
/// unit-тестирование должно работать с тестируемым материалом, как с черным
/// ящиком. Однако в специальных случаях тестирование закрытой реализации
/// допустимо, как, например, в случае со сложными методами вращения поддеревьев,
/// которые (методы) через интерфейсные методы вызываются многократно и
/// отследить корректность их выполнения по посткондиции довольно затруднительно.
/// https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md#testing-private-code
///
////////////////////////////////////////////////////////////////////////////////
#include <../tests/gtest/gtest.h>
#include "../main/rbtree.h"
#include "def_dumper.h"
#include "individual.h"
namespace xi {
/** \brief Тестовый класс для тестирования закрытой части классов черно-красного дерева.
*
* Данный класс, с одной стороны, представляется полноценный g-тестером, с другой —
* ему классы КЧД представляют дружественные полномочия, поэтому он может смело
* покопаться во внутренностях этих классов.
*/
template <typename Element, typename Compar = std::less<Element> >
class RBTreeTest : public ::testing::Test {
public:
// Объявление типов дерева и узла для упрощения доступа
typedef RBTree<Element, Compar> TTree;
typedef typename RBTree<Element, Compar>::Node TTreeNode;
typedef typename RBTree<Element, Compar>::Color TTreeColor;
public:
static const int STRUCT2_SEQ[];
static const int STRUCT2_SEQ_NUM;
public:
RBTreeTest()
//: _dumper(DUMP_EVENTLOG_PRV_FN, DUMP_IMGS_PRV_PATH)
{
}
protected:
/** \brief Возвращает ссылку на неконстантный указатель на корень дерева \c tree.
*
* Обратите внимание на это чудесное сочетание звездочек и амперсандиков!
* Оно не случайно...
*/
typename TTreeNode* & getRootNode(TTree* tree)
{
return tree->_root;
}
/** \brief Создает узел без привязки к дереву */
typename TTreeNode* createNode(
const Element& key = Element(),
typename TTreeNode* left = nullptr,
typename TTreeNode* right = nullptr,
typename TTreeNode* parent = nullptr,
typename TTreeColor col = TTree::BLACK)
{
TTreeNode* newNode = new TTreeNode(key, left, right, parent, col);
return newNode;
}
/** \brief Вращает узел \c node влево. */
void rotNodeLeft(TTree* tree, TTreeNode* node)
{
tree->rotLeft(node);
}
/** \brief Вращает узел \c node вправо. */
void rotNodeRight(TTree* tree, TTreeNode* node)
{
tree->rotRight(node);
}
/** \brief Для данного узла возвращает его левого потомка. */
typename TTreeNode* getLeftChild(TTreeNode* node)
{
return node->_left;
}
/** \brief Для данного узла возвращает его правого потомка. */
typename TTreeNode* getRightChild(TTreeNode* node)
{
return node->_right;
}
/** \brief Для данного узла возвращает его предка. */
typename TTreeNode* getParentChild(TTreeNode* node)
{
return node->_parent;
}
/** \brief Вставляет элемент \c el в BST без учета свойств КЧД. */
typename TTreeNode* insertNewBstEl(TTree* tree, const Element& el)
{
return tree->insertNewBstEl(el);
}
protected:
// Некоторые методы инициализации деревьев
TTree& createStruct1(TTree& tree)
{
// создаем структуру с [Рисунка 1]
TTreeNode* n1 = createNode(1);
TTreeNode* n4 = createNode(4);
TTreeNode* n6 = createNode(6);
TTreeNode* n5 = createNode(5, n4, n6);
TTreeNode* n3 = createNode(3, n1, n5);
// устанавливаем 3 как корень
TTreeNode* & rt = getRootNode(&tree);
rt = n3;
return tree;
}
protected:
//RBTreeDefDumper<Element, Compar> _dumper;
/** \brief Выводить в формате GraphViz. */
RBTreeGvDumper<Element, Compar> _gvDumper;
}; // class RBTreeTest
// Вынесенная инициализация массива
template <typename Element, typename Compar>
const int RBTreeTest<Element, Compar>::STRUCT2_SEQ[] =
{ 4, 50, 10, 40, 17, 35, 20, 27, 37, 45, 60, 21, 1, 30 };
template <typename Element, typename Compar>
const int RBTreeTest<Element, Compar>::STRUCT2_SEQ_NUM = sizeof(STRUCT2_SEQ) / sizeof(STRUCT2_SEQ[0]);
// Тестируем на целых числах.
typedef RBTree<int> RBTreeInt;
// Конкретизация шаблонного класса для далеетестируемого целочисленного дерева
typedef RBTreeTest<int> RBTreeIntTester;
TEST_F(RBTreeIntTester, Simplest)
{
RBTreeInt tree;
TTreeNode* & rt = getRootNode(&tree);
EXPECT_EQ(nullptr, rt);
}
// тестирует ручное добавление корня
TEST_F(RBTreeIntTester, AddRootManually)
{
RBTreeInt tree;
// берем ссылку на корень
TTreeNode* & rt = getRootNode(&tree);
rt = createNode();
EXPECT_NE(nullptr, rt);
EXPECT_FALSE(tree.isEmpty()); // теперь должен быть непустым!
}
// создание простой структуры дерева
TEST_F(RBTreeIntTester, SimpleStruct1)
{
// создаем структуру с [Рисунка 1]
RBTreeInt tree;
createStruct1(tree);
// выводим в отладочный файл
std::string fn(DUMP_IMGS_PRV_PATH);
fn.append("SimpleStruct1.gv");
_gvDumper.dump(fn, tree);
}
// левый поворот
TEST_F(RBTreeIntTester, LeftRot1)
{
// создаем структуру с [Рисунка 1]
RBTreeInt tree;
createStruct1(tree);
// выводим в отладочный файл до
std::string fn1(DUMP_IMGS_PRV_PATH);
fn1.append("LeftRot1Before.gv");
_gvDumper.dump(fn1, tree);
// вращаем относительно n3 влево
TTreeNode* & rt = getRootNode(&tree);
TTreeNode* n3 = rt; // сохраняем для последующего изучения
TTreeNode* n5 = getRightChild(n3);
rotNodeLeft(&tree, rt);
// выводим в отладочный файл после
std::string fn2(DUMP_IMGS_PRV_PATH);
fn2.append("LeftRot1After.gv");
_gvDumper.dump(fn2, tree);
// постусловия
EXPECT_EQ(5, rt->getKey());
EXPECT_EQ(nullptr, rt->getParent());
EXPECT_EQ(nullptr, n5->getParent());
EXPECT_EQ(n5, n3->getParent());
EXPECT_EQ(n3, n5->getLeft());
}
// правый поворот 1
TEST_F(RBTreeIntTester, RightRot1)
{
// создаем структуру с [Рисунка 1]
RBTreeInt tree;
createStruct1(tree);
// выводим в отладочный файл до
std::string fn1(DUMP_IMGS_PRV_PATH);
fn1.append("RightRot1Before.gv");
_gvDumper.dump(fn1, tree);
TTreeNode* & rt = getRootNode(&tree);
TTreeNode* n5 = getRightChild(rt);
TTreeNode* n4 = getLeftChild(n5); // эти два для посл. изучения
TTreeNode* n6 = getRightChild(n5);
// вращаем относительно n5 вправо
rotNodeRight(&tree, n5);
// выводим в отладочный файл после
std::string fn2(DUMP_IMGS_PRV_PATH);
fn2.append("RightRot1After.gv");
_gvDumper.dump(fn2, tree);
// постусловия
EXPECT_EQ(3, rt->getKey());
EXPECT_EQ(nullptr, rt->getParent());
EXPECT_EQ(n4, rt->getRight());
EXPECT_EQ(rt, n4->getParent());
EXPECT_EQ(n5, n4->getRight());
EXPECT_EQ(nullptr, n4->getLeft());
EXPECT_EQ(nullptr, n5->getLeft());
EXPECT_EQ(n6, n5->getRight());
EXPECT_EQ(n5, n6->getParent());
}
// правый поворот 2
TEST_F(RBTreeIntTester, RightRot2)
{
// создаем структуру с [Рисунка 1]
RBTreeInt tree;
createStruct1(tree);
// выводим в отладочный файл до
std::string fn1(DUMP_IMGS_PRV_PATH);
fn1.append("RightRot2Before.gv");
_gvDumper.dump(fn1, tree);
// сохраняем указатели на инд. узлы
TTreeNode* & rt = getRootNode(&tree);
TTreeNode* n3 = rt;
TTreeNode* n5 = getRightChild(rt);
TTreeNode* n1 = getLeftChild(rt);
TTreeNode* n4 = getLeftChild(n5); // эти два для посл. изучения
TTreeNode* n6 = getRightChild(n5);
rotNodeRight(&tree, n3);
// выводим в отладочный файл после
std::string fn2(DUMP_IMGS_PRV_PATH);
fn2.append("RightRot2After.gv");
_gvDumper.dump(fn2, tree);
// постусловия
EXPECT_EQ(nullptr, n1->getParent());
EXPECT_EQ(n1, n3->getParent());
EXPECT_EQ(nullptr, n1->getLeft());
EXPECT_EQ(nullptr, n3->getLeft());
EXPECT_EQ(n5, n3->getRight());
EXPECT_EQ(n3, n5->getParent());
}
// левый поворот 2
TEST_F(RBTreeIntTester, LeftRot2)
{
// создаем структуру с [Рисунка 1]
RBTreeInt tree;
createStruct1(tree);
// выводим в отладочный файл до
std::string fn1(DUMP_IMGS_PRV_PATH);
fn1.append("LeftRot2Before.gv");
_gvDumper.dump(fn1, tree);
// сохраняем указатели на инд. узлы
TTreeNode* & rt = getRootNode(&tree);
TTreeNode* n3 = rt;
TTreeNode* n5 = getRightChild(rt);
TTreeNode* n1 = getLeftChild(rt);
TTreeNode* n4 = getLeftChild(n5); // эти два для посл. изучения
TTreeNode* n6 = getRightChild(n5);
rotNodeLeft(&tree, n5);
// выводим в отладочный файл после
std::string fn2(DUMP_IMGS_PRV_PATH);
fn2.append("LeftRot2After.gv");
_gvDumper.dump(fn2, tree);
// постусловия
EXPECT_EQ(nullptr, n3->getParent());
EXPECT_EQ(n3, n1->getParent());
EXPECT_EQ(n3, n6->getParent());
EXPECT_EQ(n1, n3->getLeft());
EXPECT_EQ(n6, n3->getRight());
EXPECT_EQ(nullptr, n6->getRight());
EXPECT_EQ(n5, n6->getLeft());
EXPECT_EQ(n6, n5->getParent());
EXPECT_EQ(nullptr, n5->getRight());
EXPECT_EQ(n4, n5->getLeft());
}
// внутренняя вставка элемента — добавление нода
TEST_F(RBTreeIntTester, insertNewBstEl1)
{
RBTreeInt tree;
for (int i = 0; i < STRUCT2_SEQ_NUM; ++i)
insertNewBstEl(&tree, STRUCT2_SEQ[i]);
std::string fn1(DUMP_IMGS_PRV_PATH);
fn1.append("InsertNewBstEl1.gv");
_gvDumper.dump(fn1, tree);
}
} // namespace xi
|
#include<stdio.h>
#include<stdlib.h>
struct stack
{
int data;
struct stack* next;
};
struct stack* top1=NULL;
struct stack* top2=NULL;
struct stack* nn(int data)
{
struct stack* p=(struct stack*)malloc(sizeof(struct stack));
p->data=data;
p->next=NULL;
return p;
}
void insert()
{
int data;
struct stack* ptr;
printf("\nenter data");
scanf("\n%d",&data);
ptr=nn(data);
if(top1==NULL)
{
top1=ptr;
}
else
{
ptr->next=top1;
top1=ptr;
}
}
void deletion()
{
struct stack* ptr;
struct stack* ptr1;
if(top1==NULL&&top2==NULL)
{
printf("\nqueue is empty");
return;
}
if(top2==NULL) // pop from stack1 andx push into stack2
{
while(top1!=NULL)
{
ptr=top1;
top1=top1->next;
ptr->next=top2;
top2=ptr;
}
}
if(top2!=NULL) //pop from stack 2 i.e.delete
{
ptr1=top2;
printf("\n%d",ptr1->data);
top2=top2->next;
free(ptr1);
ptr1=NULL;
}
}
int main()
{
int ch;
while(1)
{
printf("\n1.insert");
printf("\n2.delete");
printf("\n3.exit");
printf("\nenter your choice");
scanf("\n%d",&ch);
switch(ch)
{
case 1:insert();
break;
case 2:deletion();
break;
//case 3:display();
// break;
case 3:return 0;
break;
default:printf("\ninvalid choice");
}
}
}
|
/// @file gatemgr_test.cc
/// @brief GateMgr のテストプログラム
/// @author Yusuke Matsunaga (松永 裕介)
///
/// Copyright (C) 2013 Yusuke Matsunaga
/// All rights reserved.
#include "led_nsdef.h"
#include "GateObj.h"
#include "GateMgr.h"
#include "GateColor.h"
BEGIN_NAMESPACE_YM_LED
class GateMgrTestWidget :
public QWidget
{
public:
/// @brief コンストラクタ
/// @param[in] parent 親のウィジェット
GateMgrTestWidget(QWidget* parent = NULL);
protected:
/// @brief 描画イベントのハンドラ
void
paintEvent(QPaintEvent* event);
private:
//////////////////////////////////////////////////////////////////////
// データメンバ
//////////////////////////////////////////////////////////////////////
// gateMgr
GateMgr mGateMgr;
// GateObj のリスト
vector<GateObj*> mGateList;
// 描画用の設定
GateColor mColor;
};
// @brief コンストラクタ
// @param[in] parent 親のウィジェット
GateMgrTestWidget::GateMgrTestWidget(QWidget* parent) :
QWidget(parent)
{
mGateList.push_back(mGateMgr.new_gate(20, 20, kGtInput));
mGateList.push_back(mGateMgr.new_gate(500, 20, kGtOutput));
mGateList.push_back(mGateMgr.new_gate(100, 20, kGtBuffer));
mGateList.push_back(mGateMgr.new_gate(100, 150, kGtNot));
mGateList.push_back(mGateMgr.new_gate(100, 300, kGtAnd, 5));
mGateList.push_back(mGateMgr.new_gate(200, 100, kGtOr, 7));
mGateList.push_back(mGateMgr.new_gate(200, 400, kGtXor, 9));
for (vector<GateObj*>::iterator p = mGateList.begin();
p != mGateList.end(); ++ p) {
GateObj* gate_obj = *p;
gate_obj->set_color(&mColor);
}
}
// @brief 描画イベントのハンドラ
void
GateMgrTestWidget::paintEvent(QPaintEvent* event)
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setBrush(QBrush(Qt::green, Qt::SolidPattern));
painter.eraseRect(rect());
for (vector<GateObj*>::iterator p = mGateList.begin();
p != mGateList.end(); ++ p) {
GateObj* gate_obj = *p;
gate_obj->draw(painter);
}
}
END_NAMESPACE_YM_LED
int
main(int argc,
char** argv)
{
using nsYm::nsLed::GateMgrTestWidget;
QApplication app(argc, argv);
QWidget* w = new GateMgrTestWidget();
w->show();
return app.exec();
}
|
#include <iostream>
#include <queue>
#include <algorithm>
#include <vector>
using namespace std;
int isvisit[1001][1001];
queue<pair<int,int>> q;
int main() {
int N;
cin >> N;
isvisit[1][0] = 0;
q.push({1,0});
while(!q.empty()){
int screen = q.front().first;
int clipboard = q.front().second;
q.pop();
if(!isvisit[screen][screen]){
isvisit[screen][screen] = isvisit[screen][clipboard] + 1;
q.push({screen,screen});
}
if((screen + clipboard <= N) && !isvisit[screen + clipboard][clipboard]){
isvisit[screen + clipboard][clipboard] = isvisit[screen][clipboard] + 1;
q.push({screen + clipboard,clipboard});
}
if(!isvisit[screen - 1][clipboard] && screen >= 1){
isvisit[screen - 1][clipboard] = isvisit[screen][clipboard] + 1;
q.push({screen - 1,clipboard});
}
}
int answer = 98765432;
for(int i=0;i<=N;i++){
if(!isvisit[N][i])continue;
answer = min(answer,isvisit[N][i]);
}
cout << answer << '\n';
}
|
#include "Utils/Logger.h"
namespace vazgen {
namespace {
spdlog::level::level_enum get_spdlog_level(Logger::Level level)
{
switch (level) {
case Logger::INFO:
return spdlog::level::level_enum::info;
case Logger::WARN:
return spdlog::level::level_enum::warn;
case Logger::ERR:
return spdlog::level::level_enum::err;
case Logger::DEBUG:
return spdlog::level::level_enum::debug;
default:
return spdlog::level::level_enum::off;
};
return spdlog::level::level_enum::off;
}
}
Logger::Logger(const std::string& name)
{
m_logger = spdlog::get(name);
if (!m_logger) {
m_logger = spdlog::stdout_logger_mt(name);
}
}
void Logger::setLevel(Level level)
{
m_logger->set_level(get_spdlog_level(level));
}
void Logger::info(const std::string& msg)
{
m_logger->info(msg);
}
void Logger::warn(const std::string& msg)
{
m_logger->warn(msg);
}
void Logger::error(const std::string& msg)
{
m_logger->error(msg);
}
void Logger::debug(const std::string& msg)
{
m_logger->debug(msg);
}
} // namespace vazgen
|
#include "mainwindow.h"
#include <QApplication>
#include <QSplashScreen>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QSplashScreen *splash = new QSplashScreen;
splash->setPixmap(QPixmap(":/images/moji.jpg"));
splash->show();
MainWindow *mainWin = new MainWindow;
mainWin->show();
splash->finish(mainWin);
delete splash;
return app.exec();
}
|
#ifndef _APP_EVENT_HANDLER_H_
#define _APP_EVENT_HANDLER_H_
#include "base/nextai_app.h"
class AppEventHandler : public NextAI::AppEventListener
{
public:
static AppEventHandler* instance();
virtual NextAI::ListenerResult initStarted();
virtual NextAI::ListenerResult initCompleted();
virtual NextAI::ListenerResult cleanupCompleted();
virtual NextAI::ListenerResult render();
virtual NextAI::ListenerResult touch(NextAI::TouchType touch, int32 touchCount, const int32 touchId[], const NextAI::ScreenPoint touchPos[]);
private:
AppEventHandler() {}
virtual ~AppEventHandler() {}
};
#endif // !_APP_EVENT_HANDLER_H_
|
#pragma once
struct Data;
namespace Reader
{
Data readData(std::istream & in);
};
|
/***********************************************************************
*
* Copyright (c) 2012 Alcatel-Lucent Technologies.
* All rights reserved.
*
* ALL RIGHTS ARE RESERVED BY ALCATEL-LUCENT TECHNOLOGIES.
* ACCESS TO THIS SOURCE CODE IS STRICTLY RESTRICTED
* UNDER CONTRACT. THIS CODE IS TO BE KEPT STRICTLY
* CONFIDENTIAL. UNAUTHORIZED MODIFICATIONS OF THIS FILE
* WILL VOID YOUR SUPPORT CONTRACT WITH ALCATEL-LUCENT
* TECHNOLOGIES. IF SUCH MODIFICATIONS ARE FOR THE
* PURPOSE OF CIRCUMVENTING LICENSING LIMITATIONS, LEGAL
* ACTION MAY RESULT.
*
***********************************************************************
*
* File Name: SegmentTest.cpp
* Description: This file contains definitions for
* upˇ
* -------------------------------------------------------------------------------------------------------
* Change History :
* Date Author Description (FR/CR)
* ------------- ----------------- ----------------------------------------------------------------
* 2012-12-28 jianmink Initial creation ...
***********************************************************************/
#include "CppUTest/TestHarness.h"
#include "Segment.h"
#include "CRC.h"
TEST_GROUP(TestSegment)
{
Segments segments;
CRC crc;
BitString b;
int numOfBits;
void setup()
{
segments.setMaxBlockSizeInBit(6144);
crc.setGp(CRC::GCRC24A);
}
};
TEST(TestSegment, should_be_1_segment_for_num_of_bit_less_than_max_block_size)
{
int Z = segments.getMaxBlockSizeInBit();
numOfBits=Z-1;
segments.prepare(numOfBits);
LONGS_EQUAL(0,segments.getCRCLen());
LONGS_EQUAL(1,segments.getNumSegments());
LONGS_EQUAL(numOfBits,segments.getNumBitsAfter());
}
TEST(TestSegment, should_be_2_segments_for_num_of_bit_more_than_max_block_size)
{
int Z = segments.getMaxBlockSizeInBit();
numOfBits=Z+1;
segments.prepare(numOfBits);
int crcLen=24;
int numSegments=2;
LONGS_EQUAL(crcLen,segments.getCRCLen());
LONGS_EQUAL(numSegments,segments.getNumSegments());
LONGS_EQUAL(numOfBits+crcLen*numSegments,segments.getNumBitsAfter());
}
TEST(TestSegment, should_be_0_for_small_input_bit_sequence)
{
numOfBits=10;
segments.prepare(numOfBits);
LONGS_EQUAL(0, segments.getKMinus());
}
TEST(TestSegment, segment_size_4_large_input_sequence)
{
numOfBits=6145;
segments.prepare(numOfBits);
LONGS_EQUAL(3136, segments.getKPlus());
LONGS_EQUAL(3072, segments.getKMinus());
}
TEST(TestSegment, fill_0)
{
BitString a("1101001110100");
BitString p("100");
BitString b=a+p;
segments.prepare(b).encode();
LONGS_EQUAL(40, segments.segmentLenArray[0]);
STRCMP_EQUAL("0000000000000000000000001101001110100100",
segments.toString(0).toString().c_str());
}
|
#include "AsmOperand.h"
#include "AsmOperandParser.h"
#include "AsmParserToken.h"
std::string Operand::GetString()const {
if (type == Type::RegisterValue) {
return Register::GetRegisterString(data.base);
}
else if (type == Type::ImmediateValue) {
return std::to_string(data.displacement);
}
else if (type == Type::VariableName) {
return "Symbol";
}
else if (type == Type::AddressValue) {
std::string returnString="[";
if (data.base != Register::Id::null) {
returnString += Register::GetRegisterString(data.base);
if (data.index != Register::Id::null || data.displacement)
returnString += '+';
if (data.base == Register::Id::ebp) {
returnString += Token::varTable.GetVariableString(data.displacement);
returnString += ']';
return returnString;
}
}
if (data.index!= Register::Id::null) {
returnString += Register::GetRegisterString(data.index);
if (data.scale > 1) {
returnString += '*'; returnString += (char)data.scale+0x30;
}
if (data.displacement) {
returnString += '+';
}
}
if (data.displacement) {
returnString += std::to_string(data.displacement);
}
returnString += ']';
return returnString;
}
throw;
}
|
#include "MKL26Z4.h"
#include "pin.h"
#include "spi.h"
#include "intrpt.h"
#include "delay.h"
#ifndef NRF24L01_H
#define NRF24L01_H
namespace nrf24Def
{
//CE
const Gpio::Port cePort = Gpio::D;
const uint8_t cePin = 0;
//CS
const Gpio::Port csPort = Gpio::E;
const uint8_t csPin = 16;
//IRQ
const Gpio::Port irqPort = Gpio::D;
const uint8_t irqPin = 1;
}
/* Register Map (регистры) стр 53-58 */
const uint8_t CONFIG = 0x00;
const uint8_t EN_AA = 0x01;
const uint8_t EN_RXADDR = 0x02;
const uint8_t SETUP_AW = 0x03;
const uint8_t SETUP_RETR = 0x04;
const uint8_t RF_CH = 0x05;
const uint8_t RF_SETUP = 0x06;
const uint8_t STATUS = 0x07;
const uint8_t OBSERVE_TX = 0x08;
const uint8_t CD = 0x09;
const uint8_t RX_ADDR_P0 = 0x0A;
const uint8_t RX_ADDR_P1 = 0x0B;
const uint8_t RX_ADDR_P2 = 0x0C;
const uint8_t RX_ADDR_P3 = 0x0D;
const uint8_t RX_ADDR_P4 = 0x0E;
const uint8_t RX_ADDR_P5 = 0x0F;
const uint8_t TX_ADDR = 0x10;
const uint8_t RX_PW_P0 = 0x11;
const uint8_t RX_PW_P1 = 0x12;
const uint8_t RX_PW_P2 = 0x13;
const uint8_t RX_PW_P3 = 0x14;
const uint8_t RX_PW_P4 = 0x15;
const uint8_t RX_PW_P5 = 0x16;
const uint8_t FIFO_STATUS= 0x17;
const uint8_t DYNPD = 0x1C;
const uint8_t FEATURE = 0x1D;
/* Bit Mnemonics (биты регистров)*/
const uint8_t MASK_RX_DR = 6;
const uint8_t MASK_TX_DS = 5;
const uint8_t MASK_MAX_RT = 4;
const uint8_t EN_CRC = 3;
const uint8_t CRCO = 2;
const uint8_t PWR_UP = 1;
const uint8_t PRIM_RX = 0;
const uint8_t ENAA_P5 = 5;
const uint8_t ENAA_P4 = 4;
const uint8_t ENAA_P3 = 3;
const uint8_t ENAA_P2 = 2;
const uint8_t ENAA_P1 = 1;
const uint8_t ENAA_P0 = 0;
const uint8_t ERX_P5 = 5;
const uint8_t ERX_P4 = 4;
const uint8_t ERX_P3 = 3;
const uint8_t ERX_P2 = 2;
const uint8_t ERX_P1 = 1;
const uint8_t ERX_P0 = 0;
const uint8_t AW = 0;
const uint8_t ARD = 4;
const uint8_t ARC = 0;
const uint8_t PLL_LOCK = 4;
const uint8_t RF_DR = 3;
const uint8_t RF_PWR = 1;
const uint8_t LNA_HCURR = 0;
const uint8_t RX_DR = 6;
const uint8_t TX_DS = 5;
const uint8_t MAX_RT = 4;
const uint8_t RX_P_NO = 1;
const uint8_t TX_FULL = 0;
const uint8_t PLOS_CNT = 4;
const uint8_t ARC_CNT = 0;
const uint8_t TX_REUSE = 6;
const uint8_t FIFO_FULL = 5;
const uint8_t TX_EMPTY = 4;
const uint8_t RX_FULL = 1;
const uint8_t RX_EMPTY = 0;
const uint8_t SETUP_AW_5BYTES_ADDRESS = 3;
const uint8_t SETUP_RETR_UP_TO_2_RETRANSMIT = 2;
const uint8_t RF_SETUP_0DBM = 6;
const uint8_t DPL_P5 = 5; // Включает приём пакетов произвольной длины по каналу 5
const uint8_t DPL_P4 = 4; // Включает приём пакетов произвольной длины по каналу 4
const uint8_t DPL_P3 = 3; // Включает приём пакетов произвольной длины по каналу 3
const uint8_t DPL_P2 = 2; // Включает приём пакетов произвольной длины по каналу 2
const uint8_t DPL_P1 = 1; // Включает приём пакетов произвольной длины по каналу 1
const uint8_t DPL_P0 = 0; //
/* Command Команды (стр 46-47) */
const uint8_t R_REGISTER = 0x00;
const uint8_t W_REGISTER = 0x20;
const uint8_t R_RX_PAYLOAD = 0x61;
const uint8_t W_TX_PAYLOAD = 0xA0;
const uint8_t FLUSH_TX = 0xE1;
const uint8_t FLUSH_RX = 0xE2;
const uint8_t REUSE_TX_PL = 0xE3;
const uint8_t NOP = 0xFF;
const uint8_t REGISTER_MASK = 0x1F;
class Nrf24l01
{
//variables
public:
uint8_t count;
enum mode {TXmode , RXmode, PWR_DOWN, STANDBY_1, STANDBY_2};
enum class channel {channel0, channel1, channel2, channel3, channel4, channel5};
private:
static uint8_t selfAddress [5];
static uint8_t remoteAddress [5];
mode m;
Pin cs, ce;
Spi * driver;
//Intrpt irq;
uint8_t chan;
uint8_t nChannel;
//functions
public:
Nrf24l01 (Spi &);
bool startup;
uint8_t read_data ();
void rxState ();
void txState ();
void command (uint8_t com);
void comm (uint8_t com);
uint8_t readRegister (uint8_t reg);
uint8_t readStatus ();
void writeRegister (uint8_t reg , uint8_t val);
void writeRegister (uint8_t reg , uint8_t * val, uint8_t);
void changeBit (uint8_t reg, uint8_t bit, bool state_);
void sendByte (uint8_t val);
uint8_t receiveByte ();
uint8_t get_status ();
bool init ();
void clearFlag ();
void enableChannels (channel);
//uint8_t state;
private:
void set_bit (uint8_t reg_ister, uint8_t register_bit, uint8_t W);
void write_data (uint8_t data);
};
#endif
|
#include "stdafx.h"
#include <ulib/debug/DebugLoop.hpp>
#include <ulib/debug/ProcessMemory.hpp>
#include <ulib/debug/ToolHelp.hpp>
#include <ulib/win32/ErrorMessage.hpp>
#include <vector>
#ifdef UNICODE
#define DBGHELP_TRANSLATE_TCHAR
#endif
#pragma warning(push)
#pragma warning(disable: 4091) // 'typedef ': ignored on left of '' when no variable is declared
#include <dbghelp.h>
#pragma warning(pop)
using Debug::DebugLoop;
using Debug::IDebugEventHandler;
void DebugLoop::Run()
{
DWORD dwContinueStatus = DBG_CONTINUE; // exception continuation
for (bool bLoop = true; bLoop;)
{
// Wait for a debugging event to occur. The second parameter indicates
// that the function does not return until a debugging event occurs.
::WaitForDebugEvent(&m_debugEvent, INFINITE);
// Process the debugging event code.
switch (m_debugEvent.dwDebugEventCode)
{
case EXCEPTION_DEBUG_EVENT:
// Process the exception code. When handling
// exceptions, remember to set the continuation
// status parameter (dwContinueStatus). This value
// is used by the ContinueDebugEventent function.
OnException(dwContinueStatus);
break;
case CREATE_THREAD_DEBUG_EVENT:
// As needed, examine or change the thread's registers
// with the GetThreadContext and SetThreadContext functions;
// and suspend and resume thread execution with the
// SuspendThread and ResumeThread functions.
OnCreateThread();
break;
case CREATE_PROCESS_DEBUG_EVENT:
// As needed, examine or change the registers of the
// process's initial thread with the GetThreadContext and
// SetThreadContext functions; read from and write to the
// process's virtual memory with the ReadProcessMemory and
// WriteProcessMemory functions; and suspend and resume
// thread execution with the SuspendThread and ResumeThread
// functions. Be sure to close the handle to the process image
// file with CloseHandle.
OnCreateProcess();
break;
case EXIT_THREAD_DEBUG_EVENT:
// Display the thread's exit code.
OnExitThread();
break;
case EXIT_PROCESS_DEBUG_EVENT:
// Display the process's exit code.
if (!OnExitProcess())
bLoop = false;
break;
case LOAD_DLL_DEBUG_EVENT:
// Read the debugging information included in the newly
// loaded DLL. Be sure to close the handle to the loaded DLL
// with CloseHandle.
OnLoadDll();
break;
case UNLOAD_DLL_DEBUG_EVENT:
// Display a message that the DLL has been unloaded.
OnUnloadDll();
break;
case OUTPUT_DEBUG_STRING_EVENT:
// Display the output debugging string.
OnOutputDebugString();
break;
}
// Resume executing the thread that reported the debugging event.
::ContinueDebugEvent(m_debugEvent.dwProcessId, m_debugEvent.dwThreadId, dwContinueStatus);
}
}
void DebugLoop::OnException(DWORD& dwContinueStatus)
{
// don't handle second-chance exceptions
if (m_debugEvent.u.Exception.dwFirstChance == 0)
dwContinueStatus = DBG_EXCEPTION_NOT_HANDLED;
switch (m_debugEvent.u.Exception.ExceptionRecord.ExceptionCode)
{
case EXCEPTION_ACCESS_VIOLATION:
// First chance: Pass this on to the system.
// Last chance: Display an appropriate error.
dwContinueStatus = DBG_EXCEPTION_NOT_HANDLED;
break;
case EXCEPTION_DATATYPE_MISALIGNMENT:
// First chance: Pass this on to the system.
// Last chance: Display an appropriate error.
dwContinueStatus = DBG_EXCEPTION_NOT_HANDLED;
break;
case EXCEPTION_BREAKPOINT:
// First chance: Display the current
// instruction and register values.
break;
case EXCEPTION_SINGLE_STEP:
// First chance: Update the display of the
// current instruction and register values.
break;
case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
break;
case EXCEPTION_STACK_OVERFLOW:
dwContinueStatus = DBG_EXCEPTION_NOT_HANDLED;
break;
case DBG_CONTROL_C:
// First chance: Pass this on to the system.
// Last chance: Display an appropriate error.
break;
default:
// Handle other exceptions.
break;
}
// send event to all handler
std::set<IDebugEventHandler*>::iterator iter = m_setEventHandler.begin(), stop = m_setEventHandler.end();
for(; iter != stop; iter++)
(*iter)->OnException(m_debugEvent.dwProcessId, m_debugEvent.dwThreadId, m_debugEvent.u.Exception);
}
void DebugLoop::OnCreateThread()
{
std::set<IDebugEventHandler*>::iterator iter = m_setEventHandler.begin(), stop = m_setEventHandler.end();
for(; iter != stop; iter++)
(*iter)->OnCreateThread(m_debugEvent.dwProcessId, m_debugEvent.dwThreadId,
m_debugEvent.u.CreateThread.lpStartAddress);
}
void DebugLoop::OnCreateProcess()
{
BOOL bRet = SymInitialize(m_debugEvent.u.CreateProcessInfo.hProcess, NULL, FALSE);
if (bRet == FALSE)
{
DWORD dwLastError = GetLastError(); dwLastError;
ATLTRACE(_T("SymInitialize error 0x%08x: %s\n"),
dwLastError, Win32::ErrorMessage(dwLastError).ToString().GetString());
}
CString cszImageName;
DWORD dwImageSize = 0;
if (m_debugEvent.u.CreateProcessInfo.lpImageName != NULL)
{
// extract name
// TODO implement
}
else
{
if (m_debugEvent.u.CreateProcessInfo.hProcess != NULL)
{
// try to find out process name by function QueryFullProcessImageName(), available from Windows Vista
HMODULE hKernel32 = ::GetModuleHandle(_T("kernel32.dll"));
if (hKernel32 != NULL)
{
typedef BOOL (WINAPI *T_fnQueryFullProcessImageName)(HANDLE, DWORD, LPWSTR, PDWORD);
T_fnQueryFullProcessImageName fnQueryFullProcessImageName =
reinterpret_cast<T_fnQueryFullProcessImageName>(GetProcAddress(hKernel32, "QueryFullProcessImageNameW"));
if (fnQueryFullProcessImageName != NULL)
{
//HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, m_debugEvent.dwProcessId);
HANDLE hProcess = m_debugEvent.u.CreateProcessInfo.hProcess;
DWORD dwSize = MAX_PATH;
fnQueryFullProcessImageName(hProcess, 0, cszImageName.GetBuffer(dwSize), &dwSize);
cszImageName.ReleaseBuffer();
}
}
HMODULE hModPsapi = ::LoadLibrary(_T("psapi.dll"));
if (hModPsapi != NULL)
{
/*
typedef DWORD (WINAPI *T_fnGetModuleFileNameEx)(HANDLE, HMODULE, LPWSTR, DWORD);
T_fnGetModuleFileNameEx fnGetModuleFileNameEx =
reinterpret_cast<T_fnGetModuleFileNameEx>(GetProcAddress(hModPsapi, "GetModuleFileNameExW"));
if (fnGetModuleFileNameEx != NULL)
{
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, m_debugEvent.dwProcessId);
//HANDLE hProcess = m_debugEvent.u.CreateProcessInfo.hProcess;
DWORD dw = fnGetModuleFileNameEx(hProcess, NULL, cszImageName.GetBuffer(MAX_PATH), MAX_PATH);
cszImageName.ReleaseBuffer();
if (dw == 0)
{
ATLTRACE(_T("GetModuleFileNameEx error: %08x\n"), GetLastError());
}
CloseHandle(hProcess);
}
*/
/*
// try to find out process name by function GetProcessImageFileName(), available from Windows XP
typedef DWORD (WINAPI *T_fnGetProcessImageFileName)(HANDLE, LPWSTR, DWORD);
T_fnGetProcessImageFileName fnGetProcessImageFileName =
reinterpret_cast<T_fnGetProcessImageFileName>(GetProcAddress(hModPsapi, "GetProcessImageFileNameW"));
if (fnGetProcessImageFileName != NULL)
{
HANDLE hProcess = m_debugEvent.u.CreateProcessInfo.hProcess;
fnGetProcessImageFileName(hProcess, cszImageName.GetBuffer(MAX_PATH), MAX_PATH);
cszImageName.ReleaseBuffer();
}
*/
FreeLibrary(hModPsapi);
}
}
if (cszImageName.IsEmpty())
{
// find out process name per toolhelp functions
Debug::Toolhelp::Snapshot ths(TH32CS_SNAPPROCESS | TH32CS_SNAPNOHEAPS);
Debug::Toolhelp::ProcessList processList(ths);
for (size_t i = 0; i< processList.GetCount(); i++)
{
const PROCESSENTRY32& entry = processList.GetEntry(i);
if (m_debugEvent.dwProcessId == entry.th32ProcessID)
{
cszImageName = entry.szExeFile;
dwImageSize = entry.dwSize;
break;
}
}
}
}
// initialize symbols
USES_CONVERSION;
DWORD64 dwRet = SymLoadModule64(m_debugEvent.u.CreateProcessInfo.hProcess,
m_debugEvent.u.CreateProcessInfo.hFile,
T2CA(cszImageName),
NULL,
reinterpret_cast<DWORD64>(m_debugEvent.u.CreateProcessInfo.lpBaseOfImage),
dwImageSize);
if (dwRet == 0)
{
DWORD dwLastError = GetLastError();
if (ERROR_SUCCESS != dwLastError)
ATLTRACE(_T("SymLoadModule64 error 0x%08x: %s\n"),
dwLastError, Win32::ErrorMessage(dwLastError).ToString().GetString());
}
std::set<IDebugEventHandler*>::iterator iter = m_setEventHandler.begin(), stop = m_setEventHandler.end();
for(; iter != stop; iter++)
(*iter)->OnCreateProcess(m_debugEvent.dwProcessId, m_debugEvent.dwThreadId,
m_debugEvent.u.CreateProcessInfo.lpBaseOfImage,
m_debugEvent.u.CreateProcessInfo.lpStartAddress,
cszImageName);
}
void DebugLoop::OnExitThread()
{
std::set<IDebugEventHandler*>::iterator iter = m_setEventHandler.begin(), stop = m_setEventHandler.end();
for(; iter != stop; iter++)
(*iter)->OnExitThread(m_debugEvent.dwProcessId, m_debugEvent.dwThreadId,
m_debugEvent.u.ExitThread.dwExitCode);
}
bool DebugLoop::OnExitProcess()
{
bool bRet = true;
std::set<IDebugEventHandler*>::iterator iter = m_setEventHandler.begin(), stop = m_setEventHandler.end();
for(; iter != stop; iter++)
{
bRet &= (*iter)->OnExitProcess(m_debugEvent.dwProcessId, m_debugEvent.dwThreadId,
m_debugEvent.u.ExitProcess.dwExitCode);
}
return bRet;
}
void DebugLoop::OnLoadDll()
{
LPVOID pBaseAddress = m_debugEvent.u.LoadDll.lpBaseOfDll;
ProcessMemory processMem(m_debugEvent.dwProcessId);
CString cszDllName;
{
LPVOID pImageName = NULL;
bool bRet = processMem.Read(m_debugEvent.u.LoadDll.lpImageName, &pImageName, sizeof(pImageName));
if (bRet && pImageName != NULL)
{
BYTE abBuffer[512];
abBuffer[510] = 0;
abBuffer[511] = 0;
DWORD nSize = sizeof(abBuffer)-2;
// round down to next 64k boundary
DWORD nLeftInSegment = 0xFFFF-static_cast<DWORD>((reinterpret_cast<DWORD_PTR>(pImageName) & 0xFFFF));
if (nLeftInSegment < nSize)
nSize = nLeftInSegment;
bRet = processMem.Read(pImageName, abBuffer, nSize);
if (bRet)
{
USES_CONVERSION;
cszDllName = (m_debugEvent.u.LoadDll.fUnicode == 1 ?
W2CT(reinterpret_cast<LPCWSTR>(abBuffer)) :
A2CT(reinterpret_cast<LPCSTR>(abBuffer)) );
}
}
}
// initialize symbols
USES_CONVERSION;
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, m_debugEvent.dwProcessId);
DWORD64 dwRet = SymLoadModule64(hProcess,
m_debugEvent.u.LoadDll.hFile,
T2CA(cszDllName),
NULL,
reinterpret_cast<DWORD64>(m_debugEvent.u.LoadDll.lpBaseOfDll),
0);
if (dwRet == 0)
{
DWORD dwLastError = GetLastError();
if (ERROR_SUCCESS != dwLastError)
ATLTRACE(_T("SymLoadModule64 error 0x%08x: %s\n"),
dwLastError, Win32::ErrorMessage(dwLastError).ToString().GetString());
}
CloseHandle(hProcess);
std::set<IDebugEventHandler*>::iterator iter = m_setEventHandler.begin(), stop = m_setEventHandler.end();
for(; iter != stop; iter++)
(*iter)->OnLoadDll(m_debugEvent.dwProcessId, m_debugEvent.dwThreadId,
pBaseAddress, cszDllName);
}
void DebugLoop::OnUnloadDll()
{
LPVOID pBaseAddress = m_debugEvent.u.UnloadDll.lpBaseOfDll;
std::set<IDebugEventHandler*>::iterator iter = m_setEventHandler.begin(), stop = m_setEventHandler.end();
for(; iter != stop; iter++)
(*iter)->OnUnloadDll(m_debugEvent.dwProcessId, m_debugEvent.dwThreadId,
pBaseAddress);
}
void DebugLoop::OnOutputDebugString()
{
LPVOID pAddr = m_debugEvent.u.DebugString.lpDebugStringData;
SIZE_T nSize = m_debugEvent.u.DebugString.nDebugStringLength;
std::vector<BYTE> vecBuffer(nSize+2, 0);
ProcessMemory processMem(m_debugEvent.dwProcessId);
processMem.Read(pAddr, &vecBuffer[0], nSize);
USES_CONVERSION;
LPCTSTR pszText = m_debugEvent.u.DebugString.fUnicode == 1 ?
W2CT(reinterpret_cast<LPCWSTR>(&vecBuffer[0])) :
A2CT(reinterpret_cast<LPCSTR>(&vecBuffer[0]));
std::set<IDebugEventHandler*>::iterator iter = m_setEventHandler.begin(), stop = m_setEventHandler.end();
for(; iter != stop; iter++)
(*iter)->OnOutputDebugString(m_debugEvent.dwProcessId, m_debugEvent.dwThreadId, pszText);
}
|
#include "memory.h"
#include <list>
#ifdef TRACE_MEMORY_LEAKS
#ifdef _DEBUG
// Allocation info
typedef struct {
DWORD address;
DWORD size;
char file[64];
DWORD line;
} ALLOC_INFO;
// A list with memory allocations
typedef std::list<ALLOC_INFO*> AllocList;
AllocList *allocList;
void AddTrack(DWORD addr, DWORD asize, const char *fname, DWORD lnum)
{
ALLOC_INFO *info;
if(!allocList) {
allocList = new(AllocList);
}
info = new(ALLOC_INFO);
info->address = addr;
strncpy(info->file, fname, 63);
info->line = lnum;
info->size = asize;
allocList->insert(allocList->begin(), info);
}
void RemoveTrack(DWORD addr)
{
AllocList::iterator i;
if(!allocList)
return;
for(i = allocList->begin(); i != allocList->end(); i++)
{
if((*i)->address == addr)
{
allocList->remove((*i));
break;
}
}
}
void DumpUnfreed()
{
AllocList::iterator i;
DWORD totalSize = 0;
char buf[1024];
if(!allocList)
return;
for(i = allocList->begin(); i != allocList->end(); i++) {
sprintf(buf, "%-50s:\t\tLINE %d,\t\tADDRESS %d\t%d unfreed\n",
(*i)->file, (*i)->line, (*i)->address, (*i)->size);
OutputDebugString(buf);
totalSize += (*i)->size;
}
sprintf(buf, "-----------------------------------------------------------\n");
OutputDebugString(buf);
sprintf(buf, "Total Unfreed: %d bytes\n", totalSize);
OutputDebugString(buf);
}
#endif
#endif
|
#include "Posicion.hpp"
|
/* path_test.cpp -*- C++ -*-
Rémi Attab (remi.attab@gmail.com), 30 Apr 2014
FreeBSD-style copyright and disclaimer apply
Tests for pathing utility
This test is a leaky boat but cleaning up isn't worh the effort.
*/
#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK
#define REFLECT_USE_EXCEPTIONS 1
#include "reflect.h"
#include "dsl/type.h"
#include "dsl/plumbing.h"
#include "dsl/field.h"
#include "types/std/map.h"
#include "types/std/vector.h"
#include "types/std/string.h"
#include "utils/config/includes.h"
#include <boost/test/unit_test.hpp>
using namespace reflect;
/******************************************************************************/
/* TYPES */
/******************************************************************************/
struct A
{
int i;
int* p;
A() : i(20), p(new int(10)) {}
A(int i) : i(i), p(new int(i)) {}
};
reflectType(A)
{
reflectPlumbing();
reflectField(i);
reflectField(p);
}
struct B
{
A* p;
std::vector<A> v;
std::map<std::string, A> m;
A& fr() const { return *p; }
A* fp() const { return p; }
void fp(A* a) { p = a; }
B() : p(new A(400))
{
m["x"] = { 300 };
v.emplace_back(100);
v.emplace_back(200);
}
};
reflectType(B)
{
reflectPlumbing();
reflectField(p);
reflectField(v);
reflectField(m);
reflectField(fp);
reflectField(fr);
}
/******************************************************************************/
/* TESTS */
/******************************************************************************/
BOOST_AUTO_TEST_CASE(parsing)
{
BOOST_CHECK_EQUAL(config::Path("a").toString(), "a");
BOOST_CHECK_EQUAL(config::Path("a.b.c").toString(), "a.b.c");
BOOST_CHECK_EQUAL(config::Path("a.0").toString(), "a.0");
BOOST_CHECK_EQUAL(config::Path("a.0.c").toString(), "a.0.c");
}
BOOST_AUTO_TEST_CASE(has)
{
Value a = type<A>()->construct();
BOOST_CHECK( config::has(a, "i"));
BOOST_CHECK(!config::has(a, "i.j"));
BOOST_CHECK(!config::has(a, "j"));
BOOST_CHECK( config::has(a, "p"));
BOOST_CHECK(!config::has(a, "p.i"));
Value b = type<B>()->construct();
BOOST_CHECK( config::has(b, "p"));
BOOST_CHECK( config::has(b, "p.i"));
BOOST_CHECK( config::has(b, "p.p"));
BOOST_CHECK(!config::has(b, "p.d"));
BOOST_CHECK( config::has(b, "fp"));
BOOST_CHECK( config::has(b, "fp.i"));
BOOST_CHECK(!config::has(b, "fp.j"));
BOOST_CHECK( config::has(b, "fr"));
BOOST_CHECK( config::has(b, "fr.i"));
BOOST_CHECK(!config::has(b, "fr.j"));
BOOST_CHECK( config::has(b, "v"));
BOOST_CHECK( config::has(b, "v.0"));
BOOST_CHECK( config::has(b, "v.0.i"));
BOOST_CHECK(!config::has(b, "v.0.j"));
BOOST_CHECK( config::has(b, "v.1"));
BOOST_CHECK(!config::has(b, "v.2"));
BOOST_CHECK( config::has(b, "m"));
BOOST_CHECK( config::has(b, "m.x"));
BOOST_CHECK( config::has(b, "m.x.i"));
BOOST_CHECK(!config::has(b, "m.x.j"));
BOOST_CHECK(!config::has(b, "m.y"));
BOOST_CHECK(!config::has(b, "m.y.i"));
}
BOOST_AUTO_TEST_CASE(get)
{
Value vA = type<A>()->construct();
const A& a = vA.get<A>();
BOOST_CHECK_EQUAL(config::get(vA, "i").get<int>(), a.i);
BOOST_CHECK_EQUAL(config::get(vA, "p").get<int*>(), a.p);
Value vB = type<B>()->construct();
B& b = vB.cast<B>();
BOOST_CHECK_EQUAL( config::get(vB, "p").get<A*>(), b.p);
BOOST_CHECK_EQUAL( config::get(vB, "p.i").get<int>(), b.p->i);
BOOST_CHECK_EQUAL( config::get(vB, "p.p").get<int*>(), b.p->p);
BOOST_CHECK_EQUAL( config::get(vB, "fp").get<A*>(), b.fp());
BOOST_CHECK_EQUAL( config::get(vB, "fp.i").get<int>(), b.fp()->i);
BOOST_CHECK_EQUAL(&config::get(vB, "fr").get<A>(), &b.fr());
BOOST_CHECK_EQUAL( config::get(vB, "fr.i").get<int>(), b.fr().i);
typedef std::vector<A> Vec;
BOOST_CHECK_EQUAL(&config::get(vB, "v").get<Vec>(), &b.v);
BOOST_CHECK_EQUAL(&config::get(vB, "v.0").get<A>(), &b.v[0]);
BOOST_CHECK_EQUAL( config::get(vB, "v.0.i").get<int>(), b.v[0].i);
BOOST_CHECK_EQUAL(&config::get(vB, "v.1").get<A>(), &b.v[1]);
typedef std::map<std::string, A> Map;
BOOST_CHECK_EQUAL(&config::get(vB, "m").get<Map>(), &b.m);
BOOST_CHECK_EQUAL(&config::get(vB, "m.x").get<A>(), &b.m["x"]);
BOOST_CHECK_EQUAL( config::get(vB, "m.x.i").get<int>(), b.m["x"].i);
}
BOOST_AUTO_TEST_CASE(set)
{
Value vA = type<A>()->construct();
const A& a = vA.get<A>();
config::set(vA, "i", 13);
BOOST_CHECK_EQUAL(a.i, 13);
{
int* p = new int;
config::set(vA, "p", p);
BOOST_CHECK_EQUAL(a.p, p);
}
Value vB = type<B>()->construct();
B& b = vB.cast<B>();
{
A* p = new A;
config::set(vB, "p", p);
BOOST_CHECK_EQUAL(b.p, p);
}
config::set(vB, "p.i", 14);
BOOST_CHECK_EQUAL(b.p->i, 14);
{
int* p = new int;
config::set(vB, "p.p", p);
BOOST_CHECK_EQUAL(b.p->p, p);
}
{
A* p = new A;
config::set(vB, "fp", p);
BOOST_CHECK_EQUAL(b.fp(), p);
}
config::set(vB, "fp.i", 15);
BOOST_CHECK_EQUAL(b.fp()->i, 15);
{
typedef std::vector<A> Vec;
config::set(vB, "v.0", A(16));
BOOST_CHECK_EQUAL(b.v[0].i, 16);
config::set(vB, "v.0.i", 17);
BOOST_CHECK_EQUAL(b.v[0].i, 17);
config::set(vB, "v.1", A(18));
BOOST_CHECK_EQUAL(b.v[1].i, 18);
config::set(vB, "v.2", A(19));
BOOST_CHECK_EQUAL(b.v.at(2).i, 19);
config::set(vB, "v.3.i", 23);
BOOST_CHECK_EQUAL(b.v.at(3).i, 23);
}
{
typedef std::map<std::string, A> Map;
config::set(vB, "m.x", A(21));
BOOST_CHECK_EQUAL(b.m["x"].i, 21);
config::set(vB, "m.x.i", 22);
BOOST_CHECK_EQUAL(b.m["x"].i, 22);
config::set(vB, "m.y", A(25));
BOOST_CHECK_EQUAL(b.m["y"].i, 25);
config::set(vB, "m.z.i", 26);
BOOST_CHECK_EQUAL(b.m["z"].i, 26);
}
}
|
#include "stenographer.h"
#include "wavpcmfile.h"
#include "recthread.h"
#include "googlespeech.h"
#include "downloadandplay.h"
#include <QFile>
#include <QDir>
#include <QTextStream>
#include <QUrl>
#include <QTranslator>
Stenographer::Stenographer(QObject *parent) :
QObject(parent)
{
this->lastWavFile = "";
this->m_file = NULL;
m_autoMod = true;
m_isActive = false;
m_saveTmpFiles = false;
lang = "ru-ru";
this->downloadAndPlay = new DownloadAndPlay();
this->googleSpeech = new GoogleSpeech();
QObject::connect(googleSpeech,SIGNAL(getText(QString)),this,SLOT(addRecText(QString)));
QObject::connect(googleSpeech,SIGNAL(logging(QString)),this,SLOT(logging(QString)));
//QAudioFormat format;
format.setFrequency(16000);
format.setChannels(1);
format.setSampleSize(16);
format.setCodec("audio/pcm");
format.setByteOrder(QAudioFormat::LittleEndian);
format.setSampleType(QAudioFormat::SignedInt);
recThread = new RecThread(format);
recThread->isNeedToSavaTmpFiles(m_saveTmpFiles);
connect(recThread, SIGNAL(logging(QString)), this, SLOT(logging(QString)));
connect(recThread, SIGNAL(setVolumeRange(QVariant)), this, SLOT(getVolumeRange(QVariant)));
connect(recThread, SIGNAL(setVolumeValue(QVariant)), this, SLOT(getVolumeValue(QVariant)));
connect(recThread, SIGNAL(needToStop()), this, SLOT(stopRec()));
connect(recThread, SIGNAL(testStopped(int)), this, SLOT(_testStopped(int)));
recThread->switchAutoMod(m_autoMod);
outputAudio = new QAudioOutput(format, this);
QObject::connect(outputAudio,SIGNAL(stateChanged(QAudio::State)),this,SLOT(closeFile()));
}
void Stenographer::getOptions()
{
emit setAudioDevices(QVariant(recThread->getDevices()));
}
void Stenographer::changeAudioDevice(QVariant val){
int iDev = val.toInt();
this->recThread->changeAudioDevice(iDev);
}
void Stenographer::getVolumeRange(QVariant data)
{ emit setVolumeRange(data); }
void Stenographer::getVolumeValue(QVariant data)
{ emit setVolumeValue(data); }
void Stenographer::stopRec()
{
this->lastWavFile = this->recThread->getWavFile();
if(!m_autoMod)
emit needToStop();
else{
if(!this->m_isActive) return;
this->convertAndSent();
this->beginStopRec();
this->m_isActive = true;
}
}
void Stenographer::beginStopRec()
{
if(recThread->isRunning())
{
emit recThread->stopRecording();
this->lastWavFile = this->recThread->getWavFile();
emit logging("<Stenographer> Recorded file name: " + this->lastWavFile);
while(recThread->isRunning()){;}
}
if(!this->m_isActive || this->m_autoMod)
{
recThread->run();
}
this->m_isActive = !this->m_isActive;
}
void Stenographer::playLast(QVariant text)
{
QString args("q="+text.toString().trimmed().replace(" ","+"));
QUrl url("http://translate.google.com/translate_tts?"+args);
emit logging("<DownloadAndPlay> " + args);
this->downloadAndPlay->doDownload(url);
}
void Stenographer::closeFile()
{
if(this->outputAudio->state() == QAudio::StoppedState){
outputAudio->stop();
m_file->close();
}
//delete m_file;
}
void Stenographer::convertAndSent()
{
emit logging("<Stenographer> Begin convert");
QFile key_file("key");
QString key = "AIzaSyBOti4mM-6x9WDnZIjIeyEU21OpBXqWBgw";
if(key_file.open(QIODevice::ReadOnly)) {
QTextStream in(&key_file);
key = in.readLine();
}
googleSpeech->sent(lastWavFile, lang, key);
}
void Stenographer::setNewLang(QVariant lang)
{
this->lang = lang.toString();
}
void Stenographer::setSaveTempFiles(QVariant _is)
{
m_saveTmpFiles = _is.toBool();
recThread->isNeedToSavaTmpFiles(m_saveTmpFiles);
}
void Stenographer::addRecText(QString data)
{
if(m_saveTmpFiles){
QFile file(this->lastWavFile.replace(".wav",".txt"));
if (file.open(QIODevice::WriteOnly | QIODevice::Text)){
file.write(data.toUtf8());
file.close();
}
}
emit updateData(QVariant(QObject::tr(data.toStdString().c_str())));
}
void Stenographer::saveText(QVariant data, QVariant name)
{
QString text = data.toString();
QString f_name = name.toString();
QFile file(f_name);
if (file.open(QIODevice::WriteOnly | QIODevice::Text)){
file.write(text.toUtf8());
file.close();
}
}
void Stenographer::logging(QString str)
{
emit updateLog(QVariant(QObject::tr(str.toStdString().c_str())));
}
void Stenographer::startTest()
{
this->recThread->startTest();
}
void Stenographer::_testStopped(int result)
{
emit testStopped(QVariant(result));
}
void Stenographer::switchAutoMod()
{
m_autoMod = !m_autoMod;
emit logging(QString("<Stenographer> Auto mod: ") + (m_autoMod?"on":"off"));
this->recThread->switchAutoMod(m_autoMod);
}
void Stenographer::setOverK(QVariant val)
{
emit logging(QString("<Stenographer> Factor is: ") + QString::number(val.toDouble()));
this->recThread->setOverK(val.toDouble());
}
void Stenographer::setIT1(QVariant val)
{
emit logging(QString("<Stenographer> First integration time is: ") + QString::number(val.toInt()));
this->recThread->setIT1(val.toInt());
}
void Stenographer::setITstep1(QVariant val)
{
emit logging(QString("<Stenographer> First integration step is: ") + QString::number(val.toInt()));
this->recThread->setITstep1(val.toInt());
}
void Stenographer::setIT2(QVariant val)
{
emit logging(QString("<Stenographer> Second integration time is: ") + QString::number(val.toInt()));
this->recThread->setIT2(val.toInt());
}
void Stenographer::setITstep2(QVariant val)
{
emit logging(QString("<Stenographer> Second integration step is: ") + QString::number(val.toInt()));
this->recThread->setITstep2(val.toInt());
}
void Stenographer::setDelay(QVariant val)
{
emit logging(QString("<Stenographer> Delay is: ") + QString::number(val.toInt()));
this->recThread->setDelay(val.toInt());
}
|
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include <iostream>
using namespace std;
class ReverseInteger {
public:
int reverse(int x);
int reverse2(int x);
void Main();
~ReverseInteger() {};
};
|
#include "stdafx.h"
int main()
{
int i, j, sum;
for (i = 2; i <= 1000; i++)
{
sum = 1;
for (j = 2; j <= i / 2; j++)
if (i%j == 0)
sum += j;
if (sum == i)
{
printf("%d its factors are 1, ", i);
for (j = 2; j <= i / 2; j++)
if (i%j == 0)
printf("%d, ", j);
printf("\n");
}
}
return 0;
}
|
/*
* Hacker's Monitor for XFCE Generic Monitor applet
* Copyright (C) 2015-2018 Ciriaco Garcia de Celis
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
// g++ -std=c++0x -O3 -lrt xfce-hkmon.cpp -o xfce-hkmon (gcc >= 4.6 or clang++)
// Recommended 1 second period and "Bitstream Vera Sans Mono" font on the applet
#include <cstdlib>
#include <memory>
#include <iostream>
#include <iomanip>
#include <cstring>
#include <cerrno>
#include <cstdint>
#include <sstream>
#include <limits>
#include <string>
#include <cctype>
#include <cmath>
#include <ctime>
#include <vector>
#include <map>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#define APP_VERSION "2.1"
#define VA_STR(x) dynamic_cast<std::ostringstream const&>(std::ostringstream().flush() << x).str()
auto constexpr MB_i = 1000000LL;
auto constexpr MB_f = 1000000.0;
auto constexpr GB_i = 1000000000LL;
auto constexpr GB_f = 1000000000.0;
auto constexpr TB_i = 1000000000000LL;
auto constexpr TB_f = 1000000000000.0; // only C++14 has a readable alternative
void abortApp(const char* reason)
{
std::cout << "<txt>ERROR " << errno << ":\n" << (reason? reason : "") << "</txt>"
<< "<tool>" << strerror(errno) << "</tool>";
exit(2);
}
bool readFile(const char* inputFile, std::vector<char>& buffer, bool mustExist = true)
{
int fd = open(inputFile, O_RDONLY);
if (fd < 0)
{
if (mustExist) abortApp(inputFile);
return false;
}
else
{
buffer.resize(4000);
for (std::size_t offset = 0;;)
{
int bytes = ::read(fd, &buffer[offset], buffer.size() - offset - 1);
if (bytes < 0) abortApp(inputFile);
offset += bytes;
if (offset + 1 == buffer.size()) buffer.resize(buffer.size() * 2);
else if (bytes == 0)
{
close(fd);
buffer[offset] = 0;
buffer.resize(offset);
return true;
}
}
}
}
bool writeFile(const char* outputFile, const std::ostringstream& data)
{
bool success = false;
int fd = open(outputFile, O_CREAT | O_WRONLY | O_TRUNC, 0640);
if (fd >= 0)
{
const std::string& buffer = data.str();
if (write(fd, buffer.c_str(), buffer.length()) == (ssize_t) buffer.length()) success = true;
close(fd);
}
return success;
}
template <typename K, typename V> std::ostream& operator<<(std::ostream& out, const std::map<K,V>& container)
{
for (const auto& item : container) out << item.first << '|' << item.second << '\t'; // write into storage
return out << '\n';
}
template <typename T> bool fromString(const std::string& from, T& to) { return bool(std::istringstream(from) >> to); }
template <> bool fromString(const std::string& from, std::string& to) { to = from; return true; }
template <typename K, typename V> std::istream& operator>>(std::istream& in, std::map<K,V>& container)
{
while (!in.eof() && !in.fail() && (in.peek() != '\n')) // read from storage
{
std::string skey;
if (std::getline(in, skey, '|'))
{
K key;
V value;
if (fromString(skey, key) && (in >> value))
{
container.insert( { key, value } );
in.ignore(); // tab
}
}
}
return in.ignore();
}
struct CPU
{
typedef int16_t Number; // -1 for all cores summary and 0,1,2,... for each core
struct Core
{
int64_t user, nice, system, idle, iowait, irq, softirq, steal, guest, guestnice;
uint64_t freq_hz;
int64_t cpuUsed() const { return user + nice + system + irq + softirq + guest + guestnice; }
int64_t cpuTotal() const { return cpuUsed() + idle + iowait + steal; }
Core operator-(const Core& that) const
{
int64_t roundUserFix = user == that.user-1? 1 : 0; // compensate for physical host & virtual
int64_t roundNiceFix = nice == that.nice-1? 1 : 0; // guests counters evil rounding
return
{
user - that.user + roundUserFix, nice - that.nice + roundNiceFix, system - that.system,
idle - that.idle, iowait - that.iowait, irq - that.irq, softirq - that.softirq,
steal - that.steal, guest - that.guest + roundUserFix, guestnice - that.guestnice + roundNiceFix,
(freq_hz + that.freq_hz) / 2 // <-- a more useful abstraction
};
}
};
std::map<Number, Core> cores;
void readProc()
{
std::vector<char> buffer;
readFile("/proc/stat", buffer);
std::istringstream cpustat(&buffer[0]);
std::string name;
Number number;
while (cpustat >> name)
{
if (name.find("cpu") == 0)
{
name.erase(0,3);
if (name.empty()) number = -1; else if (!fromString(name, number)) continue;
Core& core = cores[number];
cpustat >> core.user >> core.nice >> core.system >> core.idle
>> core.iowait >> core.irq >> core.softirq;
if (cpustat.peek() != '\n') cpustat >> core.steal; else core.steal = 0; // caution with old kernels
if (cpustat.peek() != '\n') cpustat >> core.guest; else core.guest = 0;
if (cpustat.peek() != '\n') cpustat >> core.guestnice; else core.guestnice = 0;
core.freq_hz = 0;
core.user -= core.guest; // adjust for the already accounted values (may cause evil rounding
core.nice -= core.guestnice; // effects, though)
}
cpustat.ignore(buffer.size(), '\n');
}
readFile("/proc/cpuinfo", buffer);
std::istringstream cpuinfo(&buffer[0]);
std::string key;
std::string skip;
uint64_t sum_freq = 0;
number = -1;
while (cpuinfo >> key)
{
if (key == "processor") cpuinfo >> skip >> number;
else if ((key == "cpu") && (number >= 0))
{
if ((cpuinfo >> skip) && (skip == "MHz"))
{
double mhz;
cpuinfo >> skip >> mhz;
cores[number].freq_hz = uint64_t(mhz * MB_i);
sum_freq += cores[number].freq_hz;
number = -1;
}
}
cpuinfo.ignore(buffer.size(), '\n');
}
auto allcpu = cores.find(-1);
if (allcpu != cores.end()) allcpu->second.freq_hz = sum_freq;
}
};
std::ostream& operator<<(std::ostream& out, const CPU::Core& core) // write into storage
{
return out << core.user << ' ' << core.nice << ' ' << core.system << ' ' << core.idle << ' '
<< core.iowait << ' ' << core.irq << ' ' << core.softirq << ' '
<< core.steal << ' ' << core.guest << ' ' << core.guestnice << ' ' << core.freq_hz;
}
std::istream& operator>>(std::istream& in, CPU::Core& core) // read from storage
{
return in >> core.user >> core.nice >> core.system >> core.idle >> core.iowait >> core.irq
>> core.softirq >> core.steal >> core.guest >> core.guestnice >> core.freq_hz;
}
struct Memory
{
struct RAM
{
uint64_t total;
uint64_t available;
uint64_t free;
uint64_t shared;
uint64_t buffers;
uint64_t cached;
uint64_t swapTotal;
uint64_t swapFree;
};
RAM ram;
void readProc()
{
std::vector<char> buffer;
readFile("/proc/meminfo", buffer);
std::istringstream meminfo(&buffer[0]);
bool hasAvailable = false;
std::string key;
for (int count = 0; meminfo >> key;)
{
if (key == "MemTotal:") { count++; meminfo >> ram.total; }
else if (key == "MemFree:") { count++; meminfo >> ram.free; }
else if (key == "MemAvailable:") { count++; meminfo >> ram.available; hasAvailable = true; }
else if (key == "Buffers:") { count++; meminfo >> ram.buffers; }
else if (key == "Cached:") { count++; meminfo >> ram.cached; }
else if (key == "SwapTotal:") { count++; meminfo >> ram.swapTotal; }
else if (key == "SwapFree:") { count++; meminfo >> ram.swapFree; }
else if (key == "Shmem:") { count++; meminfo >> ram.shared; }
if (count == 7 + (hasAvailable? 1:0)) break;
meminfo.ignore(buffer.size(), '\n');
}
if (!hasAvailable) ram.available = ram.free + ram.buffers + ram.cached; // pre-2014 kernels
}
};
std::ostream& operator<<(std::ostream& out, const Memory::RAM& ram)
{
return out << ram.total << ' ' << ram.available << ' ' << ram.free << ' ' << ram.shared << ' '
<< ram.buffers << ' ' << ram.cached << ' ' << ram.swapTotal << ' ' << ram.swapFree << '\n';
}
std::istream& operator>>(std::istream& in, Memory::RAM& ram)
{
return in >> ram.total >> ram.available >> ram.free >> ram.shared
>> ram.buffers >> ram.cached >> ram.swapTotal >> ram.swapFree;
}
struct IO
{
typedef std::string Name;
struct Device
{
uint64_t bytesRead;
uint64_t bytesWritten;
uint32_t ioMsecs;
uint64_t bytesSize;
};
struct Bandwidth { double bytesPerSecond; };
std::map<Name, Device> devices;
void readProc()
{
std::vector<char> buffer;
readFile("/proc/diskstats", buffer);
std::string name, prev;
for (std::istringstream diskinfo(&buffer[0]);;) // search physical devices
{
uint64_t skip;
if (!(diskinfo >> skip >> skip >> name)) break;
if (!name.empty()
&& (prev.empty() || (name.find(prev) != 0)) // skip partitions
&& (name.find("dm") != 0)) // skip device mapper
{
prev = name;
Device& device = devices[name];
uint64_t sectorsRd, sectorsWr;
diskinfo >> skip >> skip >> sectorsRd
>> skip >> skip >> skip >> sectorsWr
>> skip >> skip >> device.ioMsecs;
device.bytesRead = sectorsRd*512;
device.bytesWritten = sectorsWr*512;
device.bytesSize = 0;
}
diskinfo.ignore(buffer.size(), '\n');
}
readFile("/proc/partitions", buffer);
std::istringstream partinfo(&buffer[0]);
uint64_t blocks;
std::string skip;
bool hasData = false;
while (!hasData && std::getline(partinfo, skip)) if (skip.empty()) hasData = true;
if (hasData) while (partinfo >> skip >> skip >> blocks >> name)
{
auto pdev = devices.find(name);
if (pdev != devices.end()) pdev->second.bytesSize = blocks * 1024;
partinfo.ignore(buffer.size(), '\n');
}
}
};
std::ostream& operator<<(std::ostream& out, const IO::Device& dev)
{
return out << dev.bytesRead << ' ' << dev.bytesWritten << ' ' << dev.ioMsecs << ' ' << dev.bytesSize;
}
std::istream& operator>>(std::istream& in, IO::Device& dev)
{
return in >> dev.bytesRead >> dev.bytesWritten >> dev.ioMsecs >> dev.bytesSize;
}
std::ostream& operator<<(std::ostream& out, const IO::Bandwidth& data)
{
if (data.bytesPerSecond < MB_i)
return out << std::fixed << std::setprecision(1) << data.bytesPerSecond / MB_f << " MB/s";
if (data.bytesPerSecond < GB_i)
return out << int64_t(data.bytesPerSecond / MB_f) << " MB/s";
return out << std::fixed << std::setprecision(3) << data.bytesPerSecond / GB_f << " GB/s";
}
struct Network
{
typedef std::string Name;
struct Interface
{
uint64_t bytesRecv;
uint64_t bytesSent;
uint64_t traffic() const { return bytesRecv + bytesSent; }
};
struct Bandwidth
{
enum class Unit { bit, byte } unit;
int64_t perSecond;
};
std::map<Name, Interface> interfaces;
void readProc()
{
std::vector<char> buffer;
readFile("/proc/net/dev", buffer);
std::istringstream netinfo(&buffer[0]);
netinfo.ignore(buffer.size(), '\n');
for (;;)
{
netinfo.ignore(buffer.size(), '\n');
std::string name;
if (!std::getline(netinfo, name, ':')) break; // also handles kernels not having a space after ':'
while (!name.empty() && (name.front() == ' ')) name.erase(name.begin()); // ltrim
Interface& interface = interfaces[name];
uint64_t skip;
netinfo >> interface.bytesRecv
>> skip >> skip >> skip >> skip >> skip >> skip >> skip
>> interface.bytesSent;
}
}
};
std::ostream& operator<<(std::ostream& out, const Network::Interface& ifz)
{
return out << ifz.bytesRecv << ' ' << ifz.bytesSent;
}
std::istream& operator>>(std::istream& in, Network::Interface& ifz)
{
return in >> ifz.bytesRecv >> ifz.bytesSent;
}
std::ostream& operator<<(std::ostream& out, const Network::Bandwidth& speed)
{
char unit = (speed.unit == Network::Bandwidth::Unit::bit)? 'b' : 'B';
if (speed.perSecond < MB_i) return out << speed.perSecond / 1000 << " K" << unit << "ps";
return out << std::fixed << std::setprecision(3) << speed.perSecond / MB_f << " M" << unit << "ps";
}
struct Health
{
typedef std::string Name;
struct Thermometer
{
int32_t tempMilliCelsius;
};
std::map<Name, Thermometer> thermometers;
void readProc()
{
std::string coretemp;
for (int hwmon = 0; hwmon < 256; hwmon++)
{
std::string base = VA_STR("/sys/class/hwmon/hwmon" << hwmon);
std::vector<char> buffer;
if (!readFile(VA_STR(base << "/name").c_str(), buffer, false)) // pre-3.15 kernel?
{
base.append("/device");
if (!readFile(VA_STR(base << "/name").c_str(), buffer, false)) break;
}
std::istringstream sname(&buffer[0]);
std::string name;
if ((sname >> name) && (name == "coretemp"))
{
coretemp = base;
break;
}
}
if (!coretemp.empty()) for (int ic = 1; ic < 64; ic++)
{
std::vector<char> buffer;
if (!readFile(VA_STR(coretemp << "/temp" << ic << "_label").c_str(), buffer, false))
{
if (thermometers.empty()) continue; else break; // Atom CPU may start at 2 (!?)
}
std::istringstream sname(&buffer[0]);
std::string name;
if (!std::getline(sname, name) || name.empty()) break;
if (!readFile(VA_STR(coretemp << "/temp" << ic << "_input").c_str(), buffer, false)) break;
std::istringstream temp(&buffer[0]);
int32_t tempMilliCelsius;
if (!(temp >> tempMilliCelsius)) break;
thermometers[name].tempMilliCelsius = tempMilliCelsius;
}
}
};
std::ostream& operator<<(std::ostream& out, const Health::Thermometer& thm)
{
return out << thm.tempMilliCelsius;
}
std::istream& operator>>(std::istream& in, Health::Thermometer& thm)
{
return in >> thm.tempMilliCelsius;
}
struct DataSize { uint64_t bytes; };
std::ostream& operator<<(std::ostream& out, const DataSize& data)
{
if (data.bytes < 5000) return out << "0 MB";
if (data.bytes < 10*MB_i) return out << std::fixed << std::setprecision(2) << data.bytes / MB_f << " MB";
if (data.bytes < 100*MB_i) return out << std::fixed << std::setprecision(1) << data.bytes / MB_f << " MB";
if (data.bytes < GB_i) return out << data.bytes / MB_i << " MB";
if (data.bytes < 10*GB_i) return out << std::fixed << std::setprecision(2) << data.bytes / GB_f << " GB";
if (data.bytes < 100*GB_i) return out << std::fixed << std::setprecision(1) << data.bytes / GB_f << " GB";
if (data.bytes < TB_i) return out << data.bytes / GB_i << " GB";
uint64_t tbx100 = data.bytes / (TB_i / 100);
auto decimals = (tbx100 > 9999) || (tbx100 % 100 == 0)? 0 : (tbx100 % 10 == 0)? 1 : 2; // pretty disk sizes
return out << std::fixed << std::setprecision(decimals) << data.bytes / TB_f << " TB";
}
template <typename T> struct Padded { uint64_t max; T value; };
template <typename T> std::ostream& operator<<(std::ostream& out, const Padded<T>& data)
{
if (!std::isnan(data.value)) for (T div = data.max;; div /= 10) // avoid infinite loop with NaN numbers
{
if ((data.value >= div) && (data.value >= 1)) break;
if ((data.value < 1) && (div <= 1)) break;
out << " "; // two spaces in place of each missing digit (same width in XFCE Generic Monitor applet)
}
return out << data.value;
}
int main(int argc, char** argv)
{
if (argc < 2)
{
std::cerr << "usage: " << argv[0] << " [NET|<network_interface>] [CPU] [TEMP] [IO] [RAM]" << std::endl;
return 1;
}
std::shared_ptr<CPU> new_CPU, old_CPU;
std::shared_ptr<Memory> new_Memory;
std::shared_ptr<IO> new_IO, old_IO;
std::shared_ptr<Network> new_Network, old_Network;
Network::Bandwidth::Unit netSpeedUnit = Network::Bandwidth::Unit::bit;
std::shared_ptr<Health> new_Health;
std::string selectedNetworkInterface;
bool singleLine = false;
int posRam = 0;
int posTemp = 0;
for (int i = 1; i < argc; i++)
{
std::string arg(argv[i]);
if ((arg == "LINE")) singleLine = true;
else if ((arg == "CPU")) new_CPU.reset(new CPU());
else if ((arg == "RAM")) posRam = i, new_Memory.reset(new Memory());
else if ((arg == "IO")) new_IO.reset(new IO());
else if ((arg == "NET")) new_Network.reset(new Network());
else if ((arg == "NET8")) new_Network.reset(new Network()), netSpeedUnit = Network::Bandwidth::Unit::byte;
else if ((arg == "TEMP")) posTemp = i, new_Health.reset(new Health());
else
{
new_Network.reset(new Network());
selectedNetworkInterface = argv[i];
}
}
timespec tp;
if (clock_gettime(CLOCK_MONOTONIC, &tp) != 0) abortApp("clock_gettime");
uint64_t nowIs = tp.tv_sec * GB_i + tp.tv_nsec;
int64_t nsecsElapsed = 0;
std::ostringstream newState;
newState << APP_VERSION << " " << nowIs << "\n";
if (new_CPU) { new_CPU->readProc(); newState << "CPU|" << new_CPU->cores; }
if (new_Memory) { new_Memory->readProc(); }
if (new_IO) { new_IO->readProc(); newState << "IO|" << new_IO->devices; }
if (new_Network) { new_Network->readProc(); newState << "Network|" << new_Network->interfaces; }
if (new_Health) { new_Health->readProc(); }
for (int locTry = 0;; locTry++) // read the previous state from disk and store the new state
{
std::vector<char> oldStateData;
std::ostringstream stateFileName;
if (locTry == 0)
stateFileName << "/run/user/" << getuid() << "/xfce-hkmon.dat";
else if (locTry == 1)
stateFileName << "/tmp/xfce-hkmon." << getuid() << ".dat";
else
abortApp("can't write tmpfile");
if (readFile(stateFileName.str().c_str(), oldStateData, false))
{
std::istringstream oldState(&oldStateData[0]);
std::string version;
uint64_t previouslyWas;
oldState >> version >> previouslyWas;
nsecsElapsed = nowIs - previouslyWas;
oldState.ignore(oldStateData.size(), '\n');
if (version == APP_VERSION)
{
std::string category;
while (std::getline(oldState, category, '|'))
{
if (category == "CPU") { old_CPU.reset(new CPU()); oldState >> old_CPU->cores; }
else if (category == "IO") { old_IO.reset(new IO()); oldState >> old_IO->devices; }
else if (category == "Network")
{
old_Network.reset(new Network()); oldState >> old_Network->interfaces;
}
else oldState.ignore(oldStateData.size(), '\n');
}
}
}
if (writeFile(stateFileName.str().c_str(), newState)) break;
}
std::ostringstream reportStd, reportDetail;
double secsElapsed = nsecsElapsed / GB_f;
if (new_Network && old_Network && nsecsElapsed) // NET report
{
if (selectedNetworkInterface.empty())
{
int64_t maxBandwidth = -1;
uint64_t selectedTraffic = 0;
for (auto itn = new_Network->interfaces.cbegin(); itn != new_Network->interfaces.cend(); ++itn)
{
if (itn->first == "lo") continue;
auto ito = old_Network->interfaces.find(itn->first);
if (ito == old_Network->interfaces.end()) continue;
int64_t transferred = itn->second.bytesRecv - ito->second.bytesRecv;
transferred += itn->second.bytesSent - ito->second.bytesSent;
if (transferred < maxBandwidth) continue;
if ((transferred > maxBandwidth) || (itn->second.traffic() > selectedTraffic))
{
maxBandwidth = transferred;
selectedTraffic = itn->second.traffic();
selectedNetworkInterface = itn->first;
}
}
}
for (auto itn = new_Network->interfaces.cbegin(); itn != new_Network->interfaces.cend(); ++itn)
{
auto ito = old_Network->interfaces.find(itn->first);
if (ito == old_Network->interfaces.end()) continue;
const Network::Interface& nif = itn->second;
const Network::Interface& oif = ito->second;
bool isSelectedInterface = itn->first == selectedNetworkInterface;
if (!nif.traffic() && !isSelectedInterface) continue;
auto dumpNet = [&](const char* iconIdle, const char* iconBusy, uint64_t newBytes, uint64_t oldBytes)
{
int64_t delta = newBytes - oldBytes;
int64_t speed = (netSpeedUnit == Network::Bandwidth::Unit::byte? 1 : 8) * delta / secsElapsed;
const char* icon = delta? iconBusy : iconIdle;
reportDetail << " " << icon << " " << DataSize { newBytes };
if (speed > 0) reportDetail << " - " << Network::Bandwidth { netSpeedUnit, speed };
reportDetail << " \n";
if (isSelectedInterface)
reportStd << std::setw(6) << Network::Bandwidth { netSpeedUnit, speed } << " " << icon
<< (singleLine? " " : " \n");
};
reportDetail << " " << itn->first << ": ";
if (isSelectedInterface) reportDetail << "\u2713"; // "check mark" character
reportDetail << "\n";
dumpNet("\u25B3", "\u25B2", nif.bytesSent, oif.bytesSent); // white/black up pointing triangles
dumpNet("\u25BD", "\u25BC", nif.bytesRecv, oif.bytesRecv); // down pointing triangles
}
}
if (new_CPU && old_CPU) // CPU report
{
struct CpuStat { CPU::Number number; double percent; double ghz; };
std::multimap<double, CpuStat> rankByGhzUsage;
double cum_weighted_ghz = 0;
for (auto itn = new_CPU->cores.cbegin(); itn != new_CPU->cores.cend(); ++itn)
{
if (itn->first < 0) continue;
auto ito = old_CPU->cores.find(itn->first);
if (ito == old_CPU->cores.end()) continue;
CPU::Core diff = itn->second - ito->second;
if (diff.cpuTotal() == 0) continue;
double unityUsage = 1.0 * diff.cpuUsed() / diff.cpuTotal();
double ghz = diff.freq_hz / GB_f;
double ghzUsage = ghz * unityUsage;
cum_weighted_ghz += ghzUsage;
rankByGhzUsage.insert({ ghzUsage, CpuStat { itn->first, 100.0 * unityUsage, ghz } });
}
auto allnew = new_CPU->cores.find(-1);
auto allold = old_CPU->cores.find(-1);
if ((allnew != new_CPU->cores.end()) && (allold != old_CPU->cores.end()))
{
const CPU::Core& ncpu = allnew->second;
const CPU::Core& ocpu = allold->second;
CPU::Core diff = ncpu - ocpu;
auto cpuTotal = diff.cpuTotal();
if (cpuTotal > 0)
{
auto cpuTotalSinceBoot = ncpu.cpuTotal();
double usagePercent = 100.0 * diff.cpuUsed() / cpuTotal;
auto dumpPercent = [&](const char* title, int64_t user_hz, int64_t user_hz__sinceBoot)
{
reportDetail << " " << Padded<double> { 100, 100.0 * user_hz / cpuTotal } << "% " << title
<< " (" << 100.0 * user_hz__sinceBoot / cpuTotalSinceBoot << "%) \n";
};
//reportStd << std::setw(6) << std::fixed << std::setprecision(1) << usagePercent << "%";
reportDetail << " CPU \u2699 " << std::fixed << std::setprecision(2) << usagePercent << "% \u2248 ";
if (cum_weighted_ghz < 1)
reportDetail << uint64_t(cum_weighted_ghz * 1000) << " MHz:\n" << std::setprecision(2);
else
reportDetail << std::setprecision(1) << cum_weighted_ghz << " GHz:\n" << std::setprecision(2);
dumpPercent("user", diff.user, ncpu.user);
dumpPercent("nice", diff.nice, ncpu.nice);
dumpPercent("system", diff.system, ncpu.system);
dumpPercent("idle", diff.idle, ncpu.idle);
dumpPercent("iowait", diff.iowait, ncpu.iowait);
if (ncpu.irq) dumpPercent("irq", diff.irq, ncpu.irq);
if (ncpu.softirq) dumpPercent("softirq", diff.softirq, ncpu.softirq);
if (ncpu.steal) dumpPercent("steal", diff.steal, ncpu.steal);
if (ncpu.guest) dumpPercent("guest", diff.guest, ncpu.guest);
if (ncpu.guestnice) dumpPercent("guest nice", diff.guestnice, ncpu.guestnice);
int maxCpu = 8;
for (auto itc = rankByGhzUsage.crbegin(); maxCpu-- && (itc != rankByGhzUsage.crend()); ++itc)
{
reportDetail << " " << std::fixed
<< std::setprecision(2) << Padded<double> { 100, itc->second.percent } << "% cpu "
<< Padded<CPU::Number> { uint64_t(new_CPU->cores.size() > 10? 10 : 1), itc->second.number }
<< " @" << std::setprecision(3) << Padded<double> { 10, itc->second.ghz } << " GHz \n";
}
}
}
}
if (new_Memory) // RAM report
{
if (new_CPU && (!posTemp || (posRam < posTemp)))
//reportStd << " " << new_Memory->ram.available/1024 << "M" << (singleLine? " " : "\n");
reportDetail << " Memory " << new_Memory->ram.total/1024 << " MiB:\n"
<< Padded<uint64_t> { 1000000, new_Memory->ram.available/1024 } << " MiB available \n"
<< Padded<uint64_t> { 1000000, (new_Memory->ram.cached+new_Memory->ram.buffers)/1024 }
<< " MiB cache/buff \n";
if (new_Memory->ram.shared)
reportDetail << Padded<uint64_t> { 1000000, new_Memory->ram.shared/1024 } << " MiB shared \n";
if (new_Memory->ram.swapTotal)
reportDetail << Padded<uint64_t> { 1000000, (new_Memory->ram.swapTotal-new_Memory->ram.swapFree)/1024 }
<< " MiB swap of " << new_Memory->ram.swapTotal/1024 << " \n";
}
if (new_IO && old_IO && nsecsElapsed) // IO report
{
for (auto nitd = new_IO->devices.cbegin(); nitd != new_IO->devices.cend(); ++nitd)
{
const IO::Device& device = nitd->second;
auto prevdev = old_IO->devices.find(nitd->first);
if ((device.bytesRead || device.bytesWritten) && (prevdev != old_IO->devices.end()))
{
reportDetail << " " << nitd->first << " \u26C1 " << DataSize { device.bytesSize } << ":\n";
auto dumpIO = [&](const char* iconIdle, const char* iconBusy, uint64_t newBytes, uint64_t oldBytes)
{
auto transferred = newBytes - oldBytes;
reportDetail << " " << (transferred? iconBusy : iconIdle) << " " << DataSize { newBytes };
if (transferred) reportDetail << " - " << IO::Bandwidth { transferred / secsElapsed };
reportDetail << " \n";
};
dumpIO("\u25B3", "\u25B2", device.bytesWritten, prevdev->second.bytesWritten);
dumpIO("\u25BD", "\u25BC", device.bytesRead, prevdev->second.bytesRead);
}
}
}
if (new_Health) // TEMP report
{
struct ThermalStat
{
ThermalStat() : min(std::numeric_limits<int32_t>::max()),
max(std::numeric_limits<int32_t>::min()),
avg(0), count(0)
{}
int32_t min;
int32_t max;
int32_t avg;
std::size_t count;
Health::Name firstName;
};
std::map<std::string, ThermalStat> statByCategory;
int32_t maxAbsTemp = std::numeric_limits<int32_t>::min();
for (const auto& itt : new_Health->thermometers)
{
std::string key = itt.first;
auto catEnd = key.find(" ");
if (catEnd != std::string::npos) key.erase(catEnd);
auto its = statByCategory.find(key);
if (its == statByCategory.end())
{
its = statByCategory.insert( { key, ThermalStat() } ).first;
its->second.firstName = itt.first;
}
if (itt.second.tempMilliCelsius < its->second.min) its->second.min = itt.second.tempMilliCelsius;
if (itt.second.tempMilliCelsius > its->second.max) its->second.max = itt.second.tempMilliCelsius;
if (itt.second.tempMilliCelsius > maxAbsTemp) maxAbsTemp = itt.second.tempMilliCelsius;
auto prevTotal = its->second.avg * its->second.count;
its->second.count++;
its->second.avg = (prevTotal + itt.second.tempMilliCelsius) / its->second.count;
}
if (new_CPU && (maxAbsTemp >= 0) && (!posRam || (posTemp < posRam)))
//reportStd << std::setw(4) << maxAbsTemp / 1000 << "ºC" << (singleLine? " " : "\n");
if (!statByCategory.empty()) reportDetail << " Temperature: \n";
for (auto its = statByCategory.crbegin(); its != statByCategory.crend(); ++its)
{
if (its->second.count == 1)
reportDetail << " " << its->second.firstName << ": " << its->second.max / 1000 << "ºC \n";
else
reportDetail << " \u2206" << its->second.max / 1000
<< "ºC \u2207" << its->second.min / 1000
<< "ºC \u222B" << its->second.avg / 1000
<< "ºC (" << its->second.count << " " << its->first << ") \n";
}
}
std::string sReportStd = reportStd.str();
if (!sReportStd.empty() && (sReportStd.back() == '\n')) sReportStd.erase(sReportStd.end()-1);
if (sReportStd.empty()) sReportStd = "Hacker's\nMonitor"; // dummy message (allow the user to right-click)
std::string sReportDetail = reportDetail.str();
if (!sReportDetail.empty() && (sReportDetail.back() == '\n')) sReportDetail.erase(sReportDetail.end()-1);
std::cout << "<txt>" << sReportStd << "</txt><tool>" << sReportDetail << "</tool>";
return 0;
}
|
#include <iostream>
#include <unistd.h>
#include <vector>
#include <sys/wait.h>
#include <sstream>
#include <iterator>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <cstddef>
#include <numeric>
#include <functional>
using namespace std;
int main()
{
const string filePath = "/bin/"; // Helps locate where the Linux command will reside
while(true)
{
string userData; // User inputted command
vector<char *> arguments; // Arguments provided by the user, which will be parsed from userData
// Prompts user to input commands
cout << "\nEnter the command and arguments you want to run, to exit type exit: " << endl;
// Get the full user input and store it in a variable
getline(cin, userData); // The entire user input (all on one line)
// Check to be sure the user didn't input nothing
if (std::all_of(userData.begin(),userData.end(),[](char wh){ return std::isspace(static_cast<unsigned char>(wh)); }))
{
cout << "You did not input a command please try again: " << endl; //Inform the user
continue; // Go to next iteration
}
// Parse user input
istringstream inputStream(userData); // Create input stream out of the user input
vector<string> parts{istream_iterator<string>{inputStream}, istream_iterator<string>{}}; // Iterate through input stream and create new String vector with each individual word
// If the user enters in "exit", terminate the shell
if (parts.front() == "exit")
exit(0); // Exit with EXIT_SUCCESS returned to the host environment
// Set up fileName and arguments for passing into the execvp method in the child process
char * fileName = const_cast<char *>((filePath + parts.front()).c_str()); // Concatenate the fileName (i.e. "/bin/") with what the user's first input was (i.e. "pwd")
for (auto const& item: parts)
{
arguments.push_back(const_cast<char *>(item.c_str())); // Place each argument into your char *arguments vector
}
arguments.push_back(nullptr); //Put null pointer at the end to signify it is the end of the command
// Special case for handling cd
if (parts.front() == "cd")
{
int cdState = chdir(arguments[1]); // Attempt to change the directory to the second element of your arguments
if(cdState < 0) // If state is less than zero, the directory change was unsuccessful.
cout << "Your directory change failed!" << endl;
else // Directory change was successful
cout << "Your directory change was successful!" << endl;
continue; // Go to next iteration and take in user input for the Shell (or another cd command)
}
// Prepare to fork() off child process
int pid, status; // Process ID and status for potential checks
pid = fork(); // Fork child process
if (pid < 0)
{ // Error during creation
cout << "Error creating child process" << endl;
exit(1); // exit (unsuccessful code)
}
// Child process
if (pid == 0) {
execvp(fileName, arguments.data()); // We pass file name and arguments
//Below code is only ran if there is an error running execvp
perror(fileName); // Handles erroneous file input easily
exit(1); // Exit this child process with an unsuccessful exit code
}
else // Parent process
waitpid(pid, &status, 0); // Busy wait until the child process terminates (shell completion). A wait(&status) would accomplish the same thing
}
}
|
#include <iostream>
#include <set>
#include <algorithm>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
set<string, greater<string>> s;
string name, state;
int N;
cin>>N;
for(int i=0; i< N; i++){
cin>>name>>state;
if(state == "leave")
s.erase(name);
else
s.insert(name);
}
for(auto str : s)
cout<<str<<'\n';
}
|
#pragma once
#include "../pch.h"
#include "GameEngine.h"
#include "../GameCore/GameBuilder.h"
#include "../GameCore/GameCore.h"
#include "../GameCore/GameReport.h"
#include "GameContext.h"
#include "PlayerContext.h"
#include "PlayerType.h"
#include "GameEnginePrompts.h"
GameEngine::GameEngine()
{
}
GameContext GameEngine::BuildGameContextInteractively()
{
std::cout << " _____ _ _ _ ___ ____ _ " << std::endl;
std::cout << "| ___(_) | | | | | \\/ (_) | | " << std::endl;
std::cout << "| |__ _ __ _| |__ | |_ ______ | . . |_ _ __ _ _| |_ ___ " << std::endl;
std::cout << "| __|| |/ _` | '_ \\| __| |______| | |\\/| | | '_ \\| | | | __/ _ \\ " << std::endl;
std::cout << "| |___| | (_| | | | | |_ | | | | | | | | |_| | || __/ " << std::endl;
std::cout << "\\____/|_|\\__, |_| |_|\\__| \\_| |_/_|_| |_|\\__,_|\\__\\___| " << std::endl;
std::cout << " __/ | " << std::endl;
std::cout << " |___/ " << std::endl;
std::cout << " _____ _ _ _ " << std::endl;
std::cout << "| ___| (_) _ | | | | " << std::endl;
std::cout << "| |__ _ __ ___ _ __ _ _ __ ___ (_) | | ___ __ _ ___ _ __ __| |___ " << std::endl;
std::cout << "| __| '_ ` _ \\| '_ \\| | '__/ _ \\ | | / _ \\/ _` |/ _ \\ '_ \\ / _` / __| " << std::endl;
std::cout << "| |__| | | | | | |_) | | | | __/ _ | |___| __/ (_| | __/ | | | (_| \\__ \\ " << std::endl;
std::cout << "\\____/_| |_| |_| .__/|_|_| \\___| (_) \\_____/\\___|\\__, |\\___|_| |_|\\__,_|___/ " << std::endl;
std::cout << " | | __/ | " << std::endl;
std::cout << " |_| |___/ " << std::endl;
std::cout << std::endl;
GameContext gameContext;
gameContext.gameMode = GameEnginePrompts::forGameMode();
gameContext.mapFilePath = GameEnginePrompts::forMapFilename();
int numPlayers = GameEnginePrompts::forNumPlayers();
for (int i = 0; i < numPlayers; i++) {
gameContext.playerSettings.push_back(
GameEnginePrompts::forPlayerContext()
);
}
return gameContext;
}
std::vector<GameReport> GameEngine::RunGame(GameContext gameContext)
{
vector<std::string> names;
// START - Ensure unique last names
std::string plName;
bool validName;
for (int i = 0; i < gameContext.playerSettings.size(); i++) {
validName = false;
while (!validName) {
plName = gameContext.playerSettings.at(i).lastName;
if (std::find(names.begin(), names.end(), plName) != names.end()) {
gameContext.playerSettings.at(i).lastName = gameContext.playerSettings.at(i).lastName + "_";
}
else {
validName = true;
}
}
names.push_back(plName);
}
// END - Ensure unique last names
int numGames = 1;
if (gameContext.gameMode == GameMode::TOURNAMENT) {
numGames = 3;
}
std::vector<GameReport> gameReports;
for (int i = 0; i < numGames; i++) {
Game* game = GameBuilder::build(
gameContext.playerSettings.size(),
names,
gameContext.mapFilePath,
_configPath
);
std::vector<Player*> players = game->getPlayers();
for (int i = 0; i < players.size(); i++) {
switch (gameContext.playerSettings[i].strategy)
{
case PlayerType::HUMAN:
players[i]->setStrategy("Human");
break;
case PlayerType::NPC_GREEDY:
players[i]->setStrategy("GreedyComputer");
break;
case PlayerType::NPC_MODERATE:
players[i]->setStrategy("ModerateComputer");
break;
default:
break;
}
}
if (gameContext.gameMode == GameMode::TOURNAMENT)
{
game->setCustomEndGameCardCount(10); // Limit to 20 turns
game->tournyMode = true;
}
game->runSetupPhase();
game->runRoundsUntilEndGame();
gameReports.push_back(game->endGame());
}
return gameReports;
}
void GameEngine::DisplayGameReport(std::vector<GameReport> gameReports)
{
GameReport tournyReport;
for (int i = 0; i < gameReports[0].victoryPoints.size(); i++) {
tournyReport.cards.push_back(0);
tournyReport.victoryPoints.push_back(0);
tournyReport.coins.push_back(0);
}
for (GameReport gameReport : gameReports) {
for (int i = 0; i < gameReport.victoryPoints.size(); i++) {
tournyReport.cards[i] += gameReport.cards[i];
tournyReport.victoryPoints[i] += gameReport.victoryPoints[i];
tournyReport.coins[i] += gameReport.coins[i];
}
}
std::cout << "\n\n+--------------------------------------------------" << std::endl;
std::cout << "+---------- Game Report -----------------------" << std::endl;
std::cout << "+--------------------------------------------------" << std::endl;
std::cout << "| Payer #\tCards\tVictory points\tCoins" << std::endl;
for (int i = 0; i < tournyReport.victoryPoints.size(); i++) {
std::cout << "| " << i << "\t\t" <<
tournyReport.cards.at(i) << "\t" <<
tournyReport.victoryPoints.at(i) << "\t\t" <<
tournyReport.coins.at(i) << std::endl;
}
std::cout << "+--------------------------------------------------" << std::endl;
}
|
#include "algorytmy2.h"
double czas(clock_t poczatek, clock_t koniec)
{
double p,k;
p=static_cast < double >( poczatek ) / CLOCKS_PER_SEC;
k=static_cast < double >( koniec ) / CLOCKS_PER_SEC;
return (k-p) *(1000/60);
}
void czysc(Wynik tab[M])
{
for(int i=0; i<M; i++)
{
tab[i].czasr=0;
tab[i].poziomr=0;
}
}
void przesun(Wynik tab[M], int k)
{
for(int i=M-2; i>=k; i--)
{
tab[i+1].poziomr=tab[i].poziomr;
tab[i+1].czasr=tab[i].czasr;
}
}
void znajdz_miejsce(Wynik tab[M], Wynik dana)
{
for(int i=0; i<M; i++)
{
if(dana.czasr < tab[i].czasr)
{
przesun(tab,i);
tab[i].poziomr=dana.poziomr;
tab[i].czasr=dana.czasr;
}
}
}
bool sprawdz_rozwiazanie(Sud tab[][N])
{
if( ! wypelnione ( tab ) ) return 0;
for(int i=0; i<N ; i++)
{
for(int j=0; j<N; j++)
{
if(! dobrze(tab, j, i, tab[j][i].pole )) return 0;
}
}
return 1;
}
bool wskaz_blad(Sud tab[][N], int &k, int &w)
{
for(int i=0; i<N; i++)
{
for(int j=0; j<N; j++)
{
if(!dobrze(tab,j,i,tab[j][i].pole) )
{
k=j;
w=i;
return 1;
}
}
}
return 0;
}
bool zawartosc(Sud tab[][N])
{
for(int i=0; i<N; i++)
{
for(int j=0; j<N; j++)
{
if(tab[j][i].pole!=0) return 1;
}
}
return 0;
}
|
#ifndef _TNA_MESHDATA_H_
#define _TNA_MESHDATA_H_
#include "../common.h"
#include "buffer.h"
#include "../shapes/aabb.h"
namespace tna
{
struct mesh_data_t
{
vertex_buffer_t* m_vertex_buffer;
index_buffer_t* m_index_buffer;
uint32_t m_num_vertices;
uint32_t m_num_indices;
aabb_t m_aabb;
};
mesh_data_t*
mesh_data_create(const char* path);
void
mesh_data_destroy(mesh_data_t* mesh_data);
} /* tna */
#endif /* ifndef _TNA_MESH_H_ */
|
#include <iostream>
#include <stdlib.h>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <iomanip>
using namespace std;
int main(int argc, char *argv[]){
//boot up message
cout<<"The client is up and running\n";
//command line inputs
int snode,dnode,filesize;
char map= *argv[1];
snode = atoi(argv[2]);
dnode = atoi(argv[3]);
filesize = atoi(argv[4]);
//create tcp client socket
int client_socket;
client_socket = socket(AF_INET, SOCK_STREAM, 0);
//specify IP address and dynamic port for the tcp socket
struct sockaddr_in client_address;
client_address.sin_family = AF_INET;
//client_address.sin_port = htons(30000);
client_address.sin_addr.s_addr = inet_addr("127.0.0.1");
socklen_t len=sizeof(client_address);
getsockname(client_socket,(struct sockaddr *) &client_address,&len);
//cout<<"port no: "<<ntohs(client_address.sin_port);
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(34321);
server_address.sin_addr.s_addr = inet_addr("127.0.0.1");
//connect to remote addr, aws here
socklen_t len1=sizeof(server_address);
int connection_status = connect(client_socket,(struct sockaddr *) &server_address, len1);
//check for error within connection_status
if(connection_status==-1){
cout<<"there's an error \n";
exit(0);
}
//send inputs to AWS
send(client_socket, &map, sizeof(map),0);
send(client_socket, &snode, sizeof(snode),0);
send(client_socket, &dnode, sizeof(dnode),0);
send(client_socket, &filesize, sizeof(filesize),0);
cout<<"The client has sent query to AWS using TCP start vertex: "<< snode<< ", destination vertex: "<<dnode<< ", map id: " <<map<< ", file size: "<<filesize<<"\n";
//listen(client_socket, 5);
//this_thread::sleep_for(std::chrono::milliseconds(200));
char buffer[9999];
int n=0;
n=recv(client_socket, &buffer, sizeof(buffer), 0);
buffer[n]='\0';
string msg1=buffer;
// cout<<"."<<endl;
if(msg1!="NOTFOUND") {
float short_dist = atof(msg1.c_str());
n = recv(client_socket, &buffer, sizeof(buffer), 0);
buffer[n] = '\0';
float tx_delay = atof(buffer);
n = recv(client_socket, &buffer, sizeof(buffer), 0);
buffer[n] = '\0';
float prop_delay = atof(buffer);
n = recv(client_socket, &buffer, sizeof(buffer), 0);
buffer[n] = '\0';
string path = buffer;
cout << setw(5) << " The client has received results from AWS:" << endl;
cout << "----------------------------------------------------------------" << endl;
cout << "Source Destination Min Length Tt Tp Delay" << endl;
cout << "----------------------------------------------------------------" << endl;
cout << snode <<" " << dnode <<" " << " " << short_dist<<" " << tx_delay<<" " << prop_delay<<" " <<" " <<
prop_delay + tx_delay << endl;
cout << "----------------------------------------------------------------" << endl;
cout << "Shortest Path " << path << endl;
} else{
n = recv(client_socket, &buffer, sizeof(buffer), 0);
buffer[n] = '\0';
string error=buffer;
if(error=="M")
cout<<"No map id "<<map<<" found"<<endl;
else
cout<<"No vertex id "<<error<<" "<<" found"<<endl;
}
//receive final answer from AWS
//char server_response[256];
//recv(network_socket, &server_response,sizeof(server_response),0);
// print out server's response
//cout<<"server's response is: "<<server_response);
//close the socket
close(client_socket);
return 0;
}
|
#include <iostream>
using namespace std;
int numero[5];
void arreglo (int numero[])
{
for (int i=0; i<5;i++)
{
cout<<"Ingresar Numero...";
cin>>numero[i];
}
for (int i=0; i<5;i++)
{
cout<<"Numero..."<<numero[i]<<"\n";
}
}
float promedio (int numero[])
{
int i;
float suma=0,cant2=0;
float promedio=0;
for (i=0;i<5;i++)
{
if ((numero[i]%2)==1)
{
suma+=numero[i];
cant2++;
}
}
if (cant2>0)
promedio=suma/cant2;
return promedio;
}
int rango (int numero[])
{
int i;
int cant=0;
for (i=0;i<5;i++)
{
if ((numero[i]>=50 and numero[i]<=100))
cant++;
}
return cant;
}
int main()
{
arreglo(numero);
cout<<"Numero Promedio es..."<<promedio(numero)<<"\n";
cout<<"Numero Rango es..."<<rango(numero)<<"\n";
return 0;
}
|
#include "easytf/operators/op_lstm.h"
#include "easytf/operators/op_sigmoid.h"
#include "easytf/operators/op_tanh.h"
#include "easytf/easytf_assert.h"
#include "easytf/easytf_logger.h"
easytf::OP_LSTM::OP_LSTM(const int32_t input_dim, const int32_t output_dim, const bool output_sequence,
const float32_t* wih, const float32_t* whh, const float32_t* bias)
{
easytf::Param param;
param.put_item(easytf::OP_LSTM::meta_input_dim, easytf::Any(input_dim));
param.put_item(easytf::OP_LSTM::meta_output_dim, easytf::Any(output_dim));
param.put_item(easytf::OP_LSTM::meta_output_sequence, easytf::Any(output_sequence));
param.put_item(easytf::OP_LSTM::meta_wih, easytf::Any(wih, 4 * input_dim*output_dim));
param.put_item(easytf::OP_LSTM::meta_whh, easytf::Any(whh, 4 * output_dim*output_dim));
param.put_item(easytf::OP_LSTM::meta_bias, easytf::Any(bias, 4 * output_dim));
init(param);
}
//init
void easytf::OP_LSTM::init(const Param& param)
{
OP_Recurrent::init(param);
//cache : two frame
this->cache = Any((float32_t*)nullptr, 7 * this->output_dim);
this->cache.fill_zero();
}
//forward
void easytf::OP_LSTM::forward(const std::map<std::string, std::shared_ptr<Entity>>& bottom, std::map<std::string, std::shared_ptr<Entity>>& top)
{
easyAssert(bottom.size() == 1 && top.size() == 1, "size of bottom and top must be 1.");
auto bottom_iter = bottom.begin();
auto top_iter = top.begin();
//check
const Shape bottom_shape = bottom_iter->second->get_shape();
const int32_t bottom_batch = bottom_shape.get_item(0);
const int32_t bottom_frames = bottom_shape.get_item(1);
const int32_t bottom_dim = bottom_shape.get_item(2);
const float32_t* bottom_data = bottom_iter->second->get_data().as_float32_array();
const Shape top_shape = top_iter->second->get_shape();
const int32_t top_batch = top_shape.get_item(0);
const int32_t top_frames = top_shape.get_item(1);
const int32_t top_dim = top_shape.get_item(2);
top_iter->second->get_data().fill_zero();
float32_t* top_data = top_iter->second->get_data().as_float32_array();
if (this->output_sequence)
{
easyAssert(bottom_frames == top_frames, "top_frames must be equals with bottom_frames , because of output_sequence is true.");
}
else
{
easyAssert(top_frames == 1, "top_frames must be 1 , because of output_sequence is false.");
}
easyAssert(bottom_batch == top_batch, "bottom_batch must be equals with top_batch.");
easyAssert(bottom_data && top_data, "bottom_data and top_data can't be empty.");
for (int32_t i = 0; i < bottom_batch; i++)
{
naive_implement(bottom_frames, bottom_dim, bottom_data + i*bottom_frames*bottom_dim, top_frames, top_dim, top_data + i*top_frames*top_dim);
}
}
void easytf::OP_LSTM::naive_implement(const int32_t src_frames, const int32_t src_dim, const float32_t* src, const int32_t dst_frames, const int32_t dst_dim, float32_t* dst)
{
//weight of input to hidden
const float32_t* wih_data = this->w_ih.as_float32_array();
const float32_t* wih_i_data = wih_data + 0 * src_dim * dst_dim;
const float32_t* wih_ix_data = wih_data + 1 * src_dim * dst_dim;
const float32_t* wih_f_data = wih_data + 2 * src_dim * dst_dim;
const float32_t* wih_o_data = wih_data + 3 * src_dim * dst_dim;
//weight of hidden to hidden
const float32_t* whh_data = this->w_hh.as_float32_array();
const float32_t* whh_i_data = whh_data + 0 * dst_dim * dst_dim;
const float32_t* whh_ix_data = whh_data + 1 * dst_dim * dst_dim;
const float32_t* whh_f_data = whh_data + 2 * dst_dim * dst_dim;
const float32_t* whh_o_data = whh_data + 3 * dst_dim * dst_dim;
//weight of bias
const float32_t* bias_data = this->bias.as_float32_array();
const float32_t* bias_i_data = bias_data + 0 * dst_dim;
const float32_t* bias_ix_data = bias_data + 1 * dst_dim;
const float32_t* bias_f_data = bias_data + 2 * dst_dim;
const float32_t* bias_o_data = bias_data + 3 * dst_dim;
this->cache.fill_zero();
float32_t* cache_data = this->cache.as_float32_array();
float32_t* cell_data = cache_data + 0 * dst_dim;
float32_t* pre_time_output_data = cache_data + 1 * dst_dim;
float32_t* input_gate_data = cache_data + 2 * dst_dim;
float32_t* input_x_data = cache_data + 3 * dst_dim;
float32_t* forget_gate_data = cache_data + 4 * dst_dim;
float32_t* output_gate_data = cache_data + 5 * dst_dim;
float32_t* cell_tanh_data = cache_data + 6 * dst_dim;
for (int32_t t = 0; t < src_frames; t++)
{
const float32_t* cur_input = src + t*src_dim;
const float32_t* pre_output = nullptr;
float32_t* cur_output = nullptr;
if (this->output_sequence)
{
pre_output = (t == 0) ? pre_time_output_data : (dst + (t - 1)*dst_dim);
cur_output = dst + t*dst_dim;
}
else
{
pre_output = pre_time_output_data;
cur_output = dst;
}
//input_gate = sigmoid(wih_i * cur_input + whh_i * pre_output + bias_i)
for (int32_t i = 0; i < dst_dim; i++)
{
float32_t sum = 0.0f;
//sum += wih_i * cur_input
for (int32_t j = 0; j < src_dim; j++)
{
sum += wih_i_data[j*dst_dim + i] * cur_input[j];
}
//sum += whh_i * pre_output
for (int32_t j = 0; j < dst_dim; j++)
{
sum += whh_i_data[j*dst_dim + i] * pre_output[j];
}
//sum += bias_i
sum += bias_i_data[i];
input_gate_data[i] = sum;
}
op_sigmoid.implement(input_gate_data, input_gate_data, dst_dim);
//input_x = tanh(wih_ix * cur_input + whh_ix * pre_output + bias_ix)
for (int32_t i = 0; i < dst_dim; i++)
{
float32_t sum = 0.0f;
//sum += wih_ix * cur_input
for (int32_t j = 0; j < src_dim; j++)
{
sum += wih_ix_data[j*dst_dim + i] * cur_input[j];
}
//sum += whh_ix * pre_output
for (int32_t j = 0; j < dst_dim; j++)
{
sum += whh_ix_data[j*dst_dim + i] * pre_output[j];
}
//sum += bias_ix
sum += bias_ix_data[i];
input_x_data[i] = sum;
}
op_tanh.implement(input_x_data, input_x_data, dst_dim);
//forget_gate = sigmoid(wih_f * cur_input + whh_f * pre_output + bias_f)
for (int32_t i = 0; i < dst_dim; i++)
{
float32_t sum = 0.0f;
//sum += wih_f * cur_input
for (int32_t j = 0; j < src_dim; j++)
{
sum += wih_f_data[j*dst_dim + i] * cur_input[j];
}
//sum += whh_f * pre_output
for (int32_t j = 0; j < dst_dim; j++)
{
sum += whh_f_data[j*dst_dim + i] * pre_output[j];
}
//sum += bias_f
sum += bias_f_data[i];
forget_gate_data[i] = sum;
}
op_sigmoid.implement(forget_gate_data, forget_gate_data, dst_dim);
//output_gate = sigmoid(wih_o * cur_input + whh_o * pre_output + bias_o)
for (int32_t i = 0; i < dst_dim; i++)
{
float32_t sum = 0.0f;
//sum += wih_o * cur_input
for (int32_t j = 0; j < src_dim; j++)
{
sum += wih_o_data[j*dst_dim + i] * cur_input[j];
}
//sum += whh_o * pre_output
for (int32_t j = 0; j < dst_dim; j++)
{
sum += whh_o_data[j*dst_dim + i] * pre_output[j];
}
//sum += bias_o
sum += bias_o_data[i];
output_gate_data[i] = sum;
}
op_sigmoid.implement(output_gate_data, output_gate_data, dst_dim);
//cell = mul(pre_cell,forget_gate)
op_mul.implement(cell_data, forget_gate_data, cell_data,dst_dim);
//input_x = mul(input_gate,input_x)
op_mul.implement(input_x_data, input_gate_data, input_x_data, dst_dim);
//cell = add(cell,input_x)
op_add.implement(cell_data, input_x_data, cell_data, dst_dim);
//cell_tanh_data = tanh(cell)
op_tanh.implement(cell_data, cell_tanh_data, dst_dim);
//output = mul(cell_tanh_data,output_gate)
op_mul.implement(cell_tanh_data, output_gate_data, cur_output, dst_dim);
if (!this->output_sequence)
{
memcpy(pre_time_output_data, cur_output, dst_dim*sizeof(float32_t));
}
}
}
|
// CharacterArray
#include <iostream>
using namespace std;
int main(){
char a[100]={'H','A','R','R','Y','\0'};
char b[]={'H','A','R','R','Y','\0'};
char d[5]={'X','Y','C','D','\0'};
char c[6]="Hello";
cout<<a<<endl;
cout<<&a[0]<<endl;
cout<<&a[1]<<endl;
cout<<&a[2]<<endl;
cout<<&a[3]<<endl;
cout<<a[0]<<endl;
cout<<c<<endl;
cout<<d<<endl;
cout<<(void*)d<<endl;
cout<<(void*)a<<endl;
cout<<(void*)b<<endl;
return 0;
}
|
//
// Created by 邓岩 on 2019/5/22.
//
/*
* 约数倍数选卡片
问题描述
闲暇时,福尔摩斯和华生玩一个游戏:
在N张卡片上写有N个整数。两人轮流拿走一张卡片。要求下一个人拿的数字一定是前一个人拿的数字的约数或倍数。例如,某次福尔摩斯拿走的卡片上写着数字“6”,则接下来华生可以拿的数字包括:
1,2,3, 6,12,18,24 ....
当轮到某一方拿卡片时,没有满足要求的卡片可选,则该方为输方。
请你利用计算机的优势计算一下,在已知所有卡片上的数字和可选哪些数字的条件下,怎样选择才能保证必胜!
当选多个数字都可以必胜时,输出其中最小的数字。如果无论如何都会输,则输出-1。
输入格式
输入数据为2行。第一行是若干空格分开的整数(每个整数介于1~100间),表示当前剩余的所有卡片。
第二行也是若干空格分开的整数,表示可以选的数字。当然,第二行的数字必须完全包含在第一行的数字中。
输出格式
程序则输出必胜的招法!!
样例输入
2 3 6
3 6
样例输出
3
样例输入
1 2 2 3 3 4 5
3 4 5
样例输出
4
*/
# include <iostream>
# include <vector>
# include <iterator>
# include <sstream>
# include <string>
# include <algorithm>
using namespace std;
int all[101];
vector<int> valid[101];
int ax;
void getvalid() {
for (int v = 1; v <= ax; v++) {
if (all[v] != 0) {
all[v]--;
for (int i = 1; i <= ax; i++) {
if (all[i] != 0 && (i%v == 0 || v%i == 0))
valid[v].push_back(i);
}
all[v]++;
}
}
}
int ans = -1;
int minimax(vector<int> &x, bool player) {
for (int i = x.size() - 1; i >= 0; i--) { //必须反序输出速度才够,原因应该是由于alpha-beta算法来说,每一步的选择越优,那么就可以进行越多的减枝,因为大的数的倍数和约数相对会少很多,所以优先选择大的数会有更好的减枝效果
if (all[x[i]]) {
all[x[i]]--;
if (minimax(valid[x[i]], !player) == player) {
ans = x[i];
all[x[i]]++;
return player;
}
all[x[i]]++;
}
}
return !player;
}
int main(void)
{
while (1) {
int i;
scanf("%d", &i);
ax = max(i, ax);
all[i]++;
if (getchar() == '\n')
break;
}
while (1) {
int i;
scanf("%d", &i);
valid[0].push_back(i);
if (getchar() == '\n')
break;
}
getvalid();
reverse(valid[0].begin(), valid[0].end()); //同样也要反序,这一行花了我2个小时才找出来原因
if (minimax(valid[0], 1) == 1)
cout << ans << endl;
else
cout << -1 << endl;
return 0;
}
/* 仍然超时严重,需要想办法增加速度
# include <iostream>
# include <vector>
# include <iterator>
# include <sstream>
# include <string>
# include <algorithm>
using namespace std;
vector<int> getvalid(vector<int> &all, int v) {
vector<int> ret;
for (int i = 0; i < all.size(); i++) {
if (all[i]%v == 0 || v%all[i] == 0)
ret.push_back(all[i]);
}
return ret;
}
int ans = -1;
int minimax(vector<int> &all, vector<int> &valid, bool player) {
for (int i = 0; i < valid.size(); i++) {
vector<int> tmp = all;
tmp.erase(find(tmp.begin(), tmp.end(), valid[i]));
vector<int> tmpvalid = getvalid(tmp, valid[i]);
if (minimax(tmp, tmpvalid, !player) == player) {
ans = valid[i];
return player;
}
}
return !player;
}
int main(void)
{
vector<int> all;
vector<int> valid;
string a;
getline(cin, a);
istringstream s(a);
copy(istream_iterator<int>(s), istream_iterator<int>(), back_inserter(all));
getline(cin, a);
istringstream b(a);
copy(istream_iterator<int>(b), istream_iterator<int>(), back_inserter(valid));
if (minimax(all, valid, 1) == 1)
cout << ans << endl;
else
cout << -1 << endl;
return 0;
}
*/
/*
// 从下面这个代码可以让我改到了上面那个,加深了我对minimax的理解
# include <iostream>
# include <vector>
# include <iterator>
# include <sstream>
# include <string>
# include <algorithm>
using namespace std;
vector<int> getvalid(vector<int> &all, int v) {
vector<int> ret;
for (int i = 0; i < all.size(); i++) {
if (all[i]%v == 0 || v%all[i] == 0)
ret.push_back(all[i]);
}
return ret;
}
int ans = -1;
int minimax(vector<int> all, vector<int> valid, bool player) {
if (valid.empty())
return !player;
if (player == 1) { //如果轮到我下子
for (int i = 0; i < valid.size(); i++) {
vector<int> tmp = all;
tmp.erase(find(tmp.begin(), tmp.end(), valid[i]));
vector<int> tmpvalid = getvalid(tmp, valid[i]);
if (minimax(tmp, tmpvalid, !player) == player) {
ans = valid[i];
return player;
}
}
return !player;
} else { //player == 0
bool ret = 1;
for (int i = 0; i < valid.size(); i++) {
vector<int> tmp = all;
tmp.erase(find(tmp.begin(), tmp.end(), valid[i]));
vector<int> tmpvalid = getvalid(tmp, valid[i]);
ret &= minimax(tmp, tmpvalid, !player);
}
if (ret) //这里可以的一个改进是对于min来说,只要他现在能下的某一步能赢,那么这步的前一步对于max来说就是不可取的,所以可以改成和上面一摸一样的形式,而不是需要计算每一步都是min方输,只需要得到一个是max赢即可,也就是达到了剪枝的效果,然后我发现两边的代码居然一摸一样,那么再次改进。甚至觉得神奇
return !player;
else
return player;
}
}
int main(void)
{
vector<int> all;
vector<int> valid;
string a;
getline(cin, a);
istringstream s(a);
copy(istream_iterator<int>(s), istream_iterator<int>(), back_inserter(all));
getline(cin, a);
istringstream b(a);
copy(istream_iterator<int>(b), istream_iterator<int>(), back_inserter(valid));
if (minimax(all, valid, 1) == 1)
cout << ans << endl;
else
cout << -1 << endl;
return 0;
}
*/
|
/*
* Coordinates.h
*
* Created on: 29 May 2011
* Author: "SevenMachines <SevenMachines@yahoo.co.uk>"
*/
#define COORDINATES_DEBUG
#ifndef COORDINATES_H_
#define COORDINATES_H_
#include <boost/tuple/tuple.hpp>
#include <boost/tuple/tuple_comparison.hpp>
namespace cryomesh {
namespace spacial {
template<class T>
class Coordinates {
public:
Coordinates() : coords(boost::tuple<T, T, T>(0, 0, 0)){
}
Coordinates(const Coordinates<T> & obj):coords(boost::tuple<T, T, T>(obj.getX(), obj.getY(), obj.getZ())) {
}
Coordinates(const T x, const T y, const T z) :coords (boost::tuple<T, T, T>(x, y, z)) {
}
~Coordinates() {
}
/**
* Less than operator
*
* @param const Coordinates & obj
* RHS
*
* @return bool
* True if < than obj, false otherwise
*/
bool operator<(const Coordinates & obj) const {
return this->coords <obj.coords;
}
/**
* Comparator operator
*
* @param const Coordinates & obj
* RHS object
*
* @return bool
* True if equal, false otherwise
*/
bool operator==(const Coordinates & obj) const {
return (this->coords == obj.coords);
}
T getX() const {
return boost::tuples::get<0>(coords);
}
T getY() const {
return boost::tuples::get<1>(coords);
}
T getZ() const {
return boost::tuples::get<2>(coords);
}
/**
* To stream operator
*
* @param std::ostream & os
* The output stream
* @param const Coordinates & obj
* The object to stream
*
* @return std::ostream &
* The output stream
*/
friend std::ostream& operator<<(std::ostream & os, const Coordinates & obj) {
os << "(" << obj.getX() << ", " << obj.getY() << ", " << obj.getZ() << ")";
return os;
}
private:
boost::tuple<T, T, T> coords;
};
}
}
#endif /* COORDINATES_H_ */
|
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
#include <node.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <sys/xattr.h>
#include <iostream>
using namespace v8;
using namespace node;
using namespace std;
#define XATTR_SIZE 10000
#define REQ_STR_ARG(I, VAR) \
if (args.Length() <= (I) || !args[I]->IsString()) \
return ThrowException(Exception::TypeError( \
String::New("Argument must be a string"))); \
Local<String> VAR = Local<String>::Cast(args[I])
#define REQ_ASCII_ARG(I, VAR) \
if (args.Length() <= (I) || !args[I]->IsString()) \
return ThrowException(Exception::TypeError( \
String::New("Argument must be a string"))); \
String::AsciiValue VAR(args[I]);
//toggle strict compatibility with c api
bool compat = false;
string ObjectToString(Local<Value> value) {
String::AsciiValue ascii_value(value);
return std::string(*ascii_value);
}
static Handle<Value> set(const Arguments& args) {
HandleScope scope;
ssize_t res;
int valLen;
REQ_ASCII_ARG(0,filename);
REQ_ASCII_ARG(1,attribute);
REQ_ASCII_ARG(2,val);
valLen = val.length();
#ifdef __APPLE__
res = setxattr(*filename, *attribute, *val, valLen,0,0);
#else
res = setxattr(*filename, *attribute, *val, valLen,0);
#endif
//printf("Setting file: %s, attribute: %s, value: %s, length: %d\n", *filename, *attribute, *val,val.length());
//Error
if (res == -1){
return ThrowException(Exception::TypeError( \
String::Concat(String::New("Error setting extended attribue: "), String::New(strerror(errno)))));
}
return Boolean::New(true);
}
static Handle<Value> glist(const Arguments& args) {
HandleScope scope;
char list[XATTR_SIZE],value[XATTR_SIZE];
const char *filename;
ssize_t listLen,valueLen;
int ns;
//make sure we were passed a string
REQ_STR_ARG(0, s);
filename= ObjectToString(s).c_str();
//get all the extended attributes on filename
#ifdef __APPLE__
listLen = listxattr(filename,list,XATTR_SIZE,0);
#else
listLen = listxattr(filename,list,XATTR_SIZE);
#endif
// create obj for return
Handle<Object> result = Object::New();
//for each of the attrs, do getxattr and add them as key/val to the obj
for (ns=0; ns<listLen; ns+= strlen(&list[ns])+1){
#ifdef __APPLE__
valueLen = getxattr(filename, &list[ns],value, XATTR_SIZE, 0, 0);
#else
valueLen = getxattr(filename, &list[ns],value, XATTR_SIZE);
#endif
if (valueLen > 0){
result->Set(String::New(&list[ns]),String::New(value, valueLen));
}
}
return result;
}
static Handle<Value> get(const Arguments& args) {
HandleScope scope;
char *attr,value[XATTR_SIZE];
const char *filename;
const char *attribute;
ssize_t valueLen;
int ns;
//make sure we were passed a string
REQ_STR_ARG(0, s1);
filename= ObjectToString(s1).c_str();
REQ_STR_ARG(1, s2);
attribute= ObjectToString(s2).c_str();
// create obj for return
Handle<Object> result = Object::New();
//for each of the attrs, do getxattr and add them as key/val to the obj
#ifdef __APPLE__
valueLen = getxattr(filename, attribute,value, XATTR_SIZE, 0, 0);
#else
valueLen = getxattr(filename, attribute,value, XATTR_SIZE);
#endif
result->Set(String::New(attribute),String::New(value,valueLen));
return result;
}
static Handle<Value> clist(const Arguments& args) {
HandleScope scope;
char list[XATTR_SIZE];
const char *filename;
ssize_t listLen;
int ns;
//make sure we were passed a string
REQ_STR_ARG(0, s);
filename= ObjectToString(s).c_str();
//get all the extended attributes on filename
#ifdef __APPLE__
listLen = listxattr(filename,list,XATTR_SIZE,0);
#else
listLen = listxattr(filename,list,XATTR_SIZE);
#endif
// create obj for return
Handle<Object> result = Object::New();
//for each of the attrs, do getxattr and add them as key/val to the obj
int nc=0;
for (ns=0; ns<listLen; ns+= strlen(&list[ns])+1){
nc++;
result->Set(nc,String::New(&list[ns]));
}
return result;
}
static Handle<Value> remove(const Arguments& args) {
HandleScope scope;
ssize_t res;
int valLen;
REQ_ASCII_ARG(0,filename);
REQ_ASCII_ARG(1,attribute);
#ifdef __APPLE__
res = removexattr(*filename, *attribute,0);
#else
res = removexattr(*filename, *attribute);
#endif
//printf("Setting file: %s, attribute: %s, value: %s, length: %d\n", *filename, *attribute, *val,val.length());
//Error
if (res == -1){
return ThrowException(Exception::TypeError( \
String::Concat(String::New("Error removing extended attribue: "), String::New(strerror(errno)))));
}
return Boolean::New(true);
}
static Handle<Value> list(const Arguments& args){
if(compat)
return(clist(args));
else
return(glist(args));
}
static Handle<Value> ccompat(const Arguments& args){
HandleScope scope;
if(args[0]->IsBoolean())
compat = args[0]->ToBoolean()->Value();
return(Boolean::New(compat));
}
extern "C" {
void init (Handle<Object> target)
{
NODE_SET_METHOD(target, "list", list);
NODE_SET_METHOD(target, "clist", clist);
NODE_SET_METHOD(target, "glist", glist);
NODE_SET_METHOD(target, "set", set);
NODE_SET_METHOD(target, "get", get);
NODE_SET_METHOD(target, "remove", remove);
NODE_SET_METHOD(target, "ccompat", ccompat);
}
NODE_MODULE(xattr, init);
}
|
#include <iostream>
#
#include "FileExplorer.h"
using namespace std;
int main()
{
FileExplorer explorer;
int command;
do
{
cin >> command;
switch(command) {
case 1: // open
case 2: // more
case 3: // go back
case 4: // go forward
default: // exit
cout << "Unknown command";
}
} while (command <= 4);
return 0;
}
|
/****************/
/* Oleksandr Diachenko */
/* Date */
/* CS 244B */
/* Spring 2016 */
/****************/
#define DEBUG
#include <stdio.h>
#include <server.h>
#include <fcntl.h>
#include <fstream>
#include <map>
#include <sstream>
#include <sys/stat.h>
/* ------------------------------------------------------------------ */
class Server {
public:
Server() {
}
Server(string mountPoint, int packetLoss, Network *network) {
this->mountPoint = mountPoint;
this->packetLoss = packetLoss;
this->network = network;
}
void runServer() {
this->prepareLocalFileSystem();
while (1) {
char body[MAX_PACKET_SIZE] = { };
int bytes = this->network->readFromSocket(body, 0);
if (bytes > 0) {
DfsPacket *packet = new DfsPacket(body, bytes);
this->processPacket(packet);
}
}
}
void prepareLocalFileSystem() {
struct stat sb;
if (stat(this->mountPoint.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
exitError("machine already in use");
}
int createStatus = mkdir(this->mountPoint.c_str(), S_IRWXU | S_IRWXG);
}
string getMountPoint() {
return this->mountPoint;
}
private:
string mountPoint;
int packetLoss;
Network *network;
map<string, map<uint8_t, int> > transactionIdPerClient;
map<int, string> fileNamePerFileDescriptor;
uint8_t _transactionId;
void beginTransaction(string clientId, string fileName) {
string uncommittedFileName = this->getUncommittedFileName(
this->_transactionId, clientId);
string uncommittedFileNameAbsolute = this->getAbsolutePath(
uncommittedFileName);
int fd = open(uncommittedFileNameAbsolute.c_str(), O_WRONLY | O_CREAT,
S_IRWXU | S_IRWXG);
this->copyContent(uncommittedFileNameAbsolute,
this->getAbsolutePath(fileName));
transactionIdPerClient[clientId][this->_transactionId] = fd;
fileNamePerFileDescriptor[fd] = fileName;
BeginTransactionResponseEvent *beginTransactionEvent =
new BeginTransactionResponseEvent(clientId, this->getServerId(),
this->_transactionId);
this->network->sendPacket(beginTransactionEvent, false, 1);
printf("OPENFILE: %s, fd: %d, transactionId: %d\n", fileName.c_str(),
fd, this->_transactionId);
this->_transactionId++;
}
void writeBlock(uint8_t tranId, string clientId, string serverId,
int offset, int blockSize, char* bytes) {
if (this->transactionIdPerClient[clientId].count(tranId) == 0) {
printf("Invalid transaction, id: %d\n", tranId);
return;
}
int fd = this->transactionIdPerClient[clientId][tranId];
printf(
"WRITE BLOCK to file descriptor: %d, clientId: %s, transactionId: %d, size: %d, offset: %d\n",
fd, clientId.c_str(), tranId, blockSize, offset);
if (lseek(fd, offset, SEEK_SET) < 0) {
perror("WriteBlock Seek");
}
if ((write(fd, bytes, blockSize)) != blockSize) {
perror("WriteBlock write");
}
}
void processPacket(DfsPacket *packet) {
BaseEvent *event = this->network->packetToEvent(packet);
handleEvent(event);
}
string getServerId() {
char hostname[1024];
hostname[1023] = '\0';
gethostname(hostname, 1023);
std::ostringstream ss;
ss << ::getppid() << hostname;
string serverId = ss.str();
return serverId;
}
void handleEvent(BaseEvent *event) {
uint8_t eventType = event->getEventType();
if (event->getReceiverNodeId() == this->getServerId()
|| event->isBroadcast())
{
switch (eventType) {
case EVENT_TYPE_BEGIN_TRANSACTION_REQUEST:
beginTransaction(event->getSenderNodeId(),
((BeginTransactionRequestEvent *) event)->getFileName());
break;
case EVENT_TYPE_WRITE_BLOCK:
this->writeBlock(
((WriteBlockEvent *) event)->getTransactionId(),
((WriteBlockEvent *) event)->getSenderNodeId(),
((WriteBlockEvent *) event)->getReceiverNodeId(),
((WriteBlockEvent *) event)->getOffset(),
((WriteBlockEvent *) event)->getBlockSize(),
((WriteBlockEvent *) event)->getBytes());
break;
case EVENT_TYPE_COMMIT_REQUEST:
this->commitRequest(
((CommitRequestEvent *) event)->getTransactionId(),
((CommitRequestEvent *) event)->getSenderNodeId());
break;
case EVENT_TYPE_COMMIT:
this->finishCommit(((CommitEvent *) event)->getTransactionId(),
((CommitEvent *) event)->getSenderNodeId(),
((CommitEvent *) event)->getCloseFile());
break;
case EVENT_TYPE_ROLLBACK:
this->rollback(((RollbackEvent *) event)->getTransactionId(),
((RollbackEvent *) event)->getSenderNodeId());
break;
default:
break;
};
} else {
}
}
void commitRequest(uint8_t transactionId, string clientId) {
uint8_t readyToCommit = validateTransaction(transactionId, clientId);
CommitVoteEvent *event = new CommitVoteEvent(clientId,
this->getServerId(), transactionId, readyToCommit);
this->network->sendPacket(event, true, 1);
}
void finishCommit(uint8_t transactionId, string clientId, bool closeFile) {
int commitTransactionStatus = commitTransaction(transactionId, clientId,
closeFile);
if (commitTransactionStatus == NormalReturn) {
CommitRollbackAckEvent *event = new CommitRollbackAckEvent(clientId,
this->getServerId(), transactionId);
this->network->sendPacket(event, true, 1);
} else {
printf("Unable to finish commit for transactionId: %d\n",
transactionId);
}
}
void rollback(uint8_t transactionId, string clientId) {
printf("ROLLBACK transaction id : %d\n", transactionId);
int fd = this->transactionIdPerClient[clientId][transactionId];
string uncommittedFileName = this->getUncommittedFileName(transactionId,
clientId);
string uncommittedFileNameAbsolute = this->getAbsolutePath(
uncommittedFileName);
string fileName = fileNamePerFileDescriptor[fd];
this->copyContent(uncommittedFileNameAbsolute,
this->getAbsolutePath(fileName));
CommitRollbackAckEvent *event = new CommitRollbackAckEvent(clientId,
this->getServerId(), transactionId);
this->network->sendPacket(event, true, 1);
}
uint8_t validateTransaction(uint8_t transactionId, string clientId) {
return POSITIVE_VOTE;
}
uint8_t commitTransaction(uint8_t transactionId, string clientId,
bool closeFile) {
printf("COMMIT transaction id : %d\n", transactionId);
if (closeFile)
printf("CLOSEFILE\n");
int fd = this->transactionIdPerClient[clientId][transactionId];
if (closeFile) {
//Close file descriptor
int closeStatus = close(fd);
if (closeStatus != 0) {
printf("Unable to close file, probably already closed\n");
return ErrorReturn;
}
flushChanges(fd, transactionId, clientId, closeFile);
//Delete info about transaction
transactionIdPerClient[clientId].erase(transactionId);
fileNamePerFileDescriptor.erase(fd);
} else
flushChanges(fd, transactionId, clientId, closeFile);
return NormalReturn;
}
void flushChanges(int fd, uint8_t transactionId, string clientId,
bool closeFile) {
//Flush changes to filesystem
string absoluteFileName = this->getAbsolutePath(
fileNamePerFileDescriptor[fd]);
string absoluteUncommittedFileName = this->getAbsolutePath(
this->getUncommittedFileName(transactionId, clientId));
this->copyContent(absoluteFileName, absoluteUncommittedFileName);
chmod(absoluteFileName.c_str(), S_IRWXU | S_IRWXG | S_IROTH);
if (closeFile) {
int unlinkStatus = unlink(absoluteUncommittedFileName.c_str());
if (unlinkStatus != 0)
printf("Unable to unlink temp file: %s\n",
absoluteUncommittedFileName.c_str());
}
}
string getUncommittedFileName(uint8_t transactionId, string clientId) {
ostringstream ss;
ss << ".unstaged" << (int) transactionId << getServerId();
string uncommitedFileName = ss.str();
return uncommitedFileName;
}
string getAbsolutePath(string relativeFileName) {
return this->getMountPoint() + "//" + relativeFileName.c_str();
}
void copyContent(string destFileName, string sourceFileName) {
ifstream sourceFile(sourceFileName.c_str(), std::ios::binary);
ofstream destFile(destFileName.c_str(), std::ios::binary);
destFile << sourceFile.rdbuf();
destFile.close();
sourceFile.close();
}
};
int main(int argc, char* argv[]) {
string port_option, mount_option, drop_option;
unsigned short portNum;
int packetLoss;
for (int i = 0; i < argc; i++) {
if (strcmp(argv[i], "-port") == 0)
port_option = argv[i + 1];
if (strcmp(argv[i], "-mount") == 0)
mount_option = argv[i + 1];
if (strcmp(argv[i], "-drop") == 0)
drop_option = argv[i + 1];
}
if (port_option.empty())
exitError("Please provide port value");
if (mount_option.empty())
exitError("Please provide mount value");
if (drop_option.empty())
exitError("Please provide drop value");
portNum = atoi(port_option.c_str());
packetLoss = atoi(drop_option.c_str());
Network * n = new Network(portNum, packetLoss);
Server * s = new Server(mount_option, packetLoss, n);
n->netInit();
s->runServer();
return (NormalReturn);
}
/* ------------------------------------------------------------------ */
|
#include<bits/stdc++.h>
#include<stdio.h>
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
using namespace std;
#define ll long long
#define fr(i,n) for (ll i=0;i<n;i++)
#define fr1(i,n) for(ll i=1;i<=n;i++)
#define l(s) s.size()
int main()
{
ll m,n,b,c,d,i,j,k,x,y,z,l,q,r;
string s,s1, s2, s3, s4;
ll cnt=0,cn=0, ans=0,sum=0 ;
cin>>s;
n=l(s);
fr(i, n)
{
if(s[i]>='a' and s[i]<='z' )cnt++;
else if(cnt> 0 )cnt--, ans++;
}
cout<<ans<<endl;
///FSFmnNEejhfhgfhgflYY
return 0;
}
///Before submit=>
/// *check for integer overflow,array bounds
/// *check for n=1
|
/*
Tu Tran
Programming II
Due: July 2, 18
Webpage
Input data to webpage, return another webpage
*/
#include <iostream>
#include <string>
#include "choice.cpp"
using namespace std;
int main(int argc, char *argv[])
{
string input;
cin >> input;
choice(input);
return 0;
}
|
/*
* MainMenu.h
*
* Created on: 16 сент. 2017 г.
* Author: Соня
*/
#ifndef MAINMENU_H_
#define MAINMENU_H_
class MainMenu {
public:
MainMenu();
virtual ~MainMenu();
};
#endif /* MAINMENU_H_ */
|
////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2006-2010 MStar Semiconductor, Inc.
// All rights reserved.
//
// Unless otherwise stipulated in writing, any and all information contained
// herein regardless in any format shall remain the sole proprietary of
// MStar Semiconductor Inc. and be kept in strict confidence
// (''MStar Confidential Information'') by the recipient.
// Any unauthorized act including without limitation unauthorized disclosure,
// copying, use, reproduction, sale, distribution, modification, disassembling,
// reverse engineering and compiling of the contents of MStar Confidential
// Information is unlawful and strictly prohibited. MStar hereby reserves the
// rights to any and all damages, losses, costs and expenses resulting therefrom.
//
////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// This file is automatically generated by SkinTool [Version:0.2.3][Build:Dec 18 2014 17:25:00]
/////////////////////////////////////////////////////////////////////////////
typedef enum
{
HWND_EXPERT_MENU_BG_TRANSPARENT = 1,
HWND_EXPERT_MENU_BG_PANE = 2,
HWND_EXPERT_MENU_BG_RECT = 3,
HWND_EXPERT_MENU_TITLE = 4,
HWND_EXPERT_MENU_INPUT_INFO = 5,
HWND_EXPERT_MENU_INPUT = 6,
HWND_EXPERT_MENU_INPUT_TYPE = 7,
HWND_EXPERT_MENU_LIST = 8,
HWND_EXPERT_MENU_ITEM0 = 9,
HWND_EXPERT_MENU_ITEM0_NAME = 10,
HWND_EXPERT_MENU_ITEM0_VALUE = 11,
HWND_EXPERT_MENU_ITEM1 = 12,
HWND_EXPERT_MENU_ITEM1_NAME = 13,
HWND_EXPERT_MENU_ITEM1_VALUE = 14,
HWND_EXPERT_MENU_ITEM2 = 15,
HWND_EXPERT_MENU_ITEM2_NAME = 16,
HWND_EXPERT_MENU_ITEM2_VALUE = 17,
HWND_EXPERT_MENU_ITEM3 = 18,
HWND_EXPERT_MENU_ITEM3_NAME = 19,
HWND_EXPERT_MENU_ITEM3_VALUE = 20,
HWND_EXPERT_MENU_ITEM4 = 21,
HWND_EXPERT_MENU_ITEM4_NAME = 22,
HWND_EXPERT_MENU_ITEM4_VALUE = 23,
HWND_EXPERT_MENU_ITEM5 = 24,
HWND_EXPERT_MENU_ITEM5_NAME = 25,
HWND_EXPERT_MENU_ITEM5_VALUE = 26,
HWND_EXPERT_MENU_ITEM6 = 27,
HWND_EXPERT_MENU_ITEM6_NAME = 28,
HWND_EXPERT_MENU_ITEM6_VALUE = 29,
HWND_EXPERT_MENU_ITEM7 = 30,
HWND_EXPERT_MENU_ITEM7_NAME = 31,
HWND_EXPERT_MENU_ITEM7_VALUE = 32,
HWND_EXPERT_MENU_ITEM8 = 33,
HWND_EXPERT_MENU_ITEM8_NAME = 34,
HWND_EXPERT_MENU_ITEM8_VALUE = 35,
HWND_EXPERT_MENU_ITEM9 = 36,
HWND_EXPERT_MENU_ITEM9_NAME = 37,
HWND_EXPERT_MENU_ITEM9_VALUE = 38,
HWND_EXPERT_MENU_ITEM10 = 39,
HWND_EXPERT_MENU_ITEM10_NAME = 40,
HWND_EXPERT_MENU_ITEM10_VALUE = 41,
HWND_EXPERT_MENU_ITEM11 = 42,
HWND_EXPERT_MENU_ITEM11_NAME = 43,
HWND_EXPERT_MENU_ITEM11_VALUE = 44,
HWND_EXPERT_MENU_ADJUST_BG = 45,
HWND_EXPERT_MENU_ADJCOM_BG = 46,
HWND_EXPERT_MENU_ADJ_BOTTOM_HALF_LEFT_BTN = 47,
HWND_EXPERT_MENU_ADJ_BOTTOM_HALF_RIGHT_BTN = 48,
HWND_EXPERT_MENU_ADJ_NAME = 49,
HWND_EXPERT_MENU_ADJ_TEXT = 50,
HWND_EXPERT_MENU_ADJ_VALUE = 51,
HWND_EXPERT_MENU_BSP_ITEM = 52,
HWND_EXPERT_MENU_BSP_VERSION = 53,
HWND_EXPERT_MENU_MAX = 54,
} HWND_WINDOW_EXPERT_MENU_ID;
extern WINDOWDRAWSTYLEDATA _MP_TBLSEG _GUI_WindowsDrawStyleList_Zui_Expert_Menu[];
//extern WINDOWVARDATA _GUI_WindowsRWDataList_Zui_Expert_Menu[];
extern WINDOWDATA _MP_TBLSEG _GUI_WindowList_Zui_Expert_Menu[];
extern WINDOWPOSDATA _MP_TBLSEG _GUI_WindowPositionList_Zui_Expert_Menu[];
extern WINDOWALPHADATA _MP_TBLSEG _GUI_WindowsAlphaList_Zui_Expert_Menu[];
#define ZUI_EXPERT_MENU_XSTART 1
#define ZUI_EXPERT_MENU_YSTART 0
#define ZUI_EXPERT_MENU_WIDTH 854
#define ZUI_EXPERT_MENU_HEIGHT 480
|
// node_b28Dlg.h : header file
//
#if !defined(AFX_NODE_B28DLG_H__169F2837_7F47_48D6_965E_2D14E5CEA363__INCLUDED_)
#define AFX_NODE_B28DLG_H__169F2837_7F47_48D6_965E_2D14E5CEA363__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
/////////////////////////////////////////////////////////////////////////////
// CNode_b28Dlg dialog
class CNode_b28Dlg : public CDialog
{
// Construction
public:
LRESULT OnMyMessage(WPARAM wParam, LPARAM lParam);
BOOL GetFilePath(char *FilePath, int type, HWND hParentWnd=NULL);
changeZhState();
CString getRunEnvironment();
void setOutput(CString msg);
CNode_b28Dlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
//{{AFX_DATA(CNode_b28Dlg)
enum { IDD = IDD_NODE_B28_DIALOG };
CEdit m_output;
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CNode_b28Dlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
HICON m_hIcon;
DWORD ThreadID;
HANDLE hThread;
// Generated message map functions
//{{AFX_MSG(CNode_b28Dlg)
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
afx_msg void OnViewSrc();
afx_msg void OnSaveDest();
afx_msg void OnRadioTranslate();
afx_msg void OnButtonLang();
afx_msg void OnDoWork();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_NODE_B28DLG_H__169F2837_7F47_48D6_965E_2D14E5CEA363__INCLUDED_)
|
////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2006-2010 MStar Semiconductor, Inc.
// All rights reserved.
//
// Unless otherwise stipulated in writing, any and all information contained
// herein regardless in any format shall remain the sole proprietary of
// MStar Semiconductor Inc. and be kept in strict confidence
// (''MStar Confidential Information'') by the recipient.
// Any unauthorized act including without limitation unauthorized disclosure,
// copying, use, reproduction, sale, distribution, modification, disassembling,
// reverse engineering and compiling of the contents of MStar Confidential
// Information is unlawful and strictly prohibited. MStar hereby reserves the
// rights to any and all damages, losses, costs and expenses resulting therefrom.
//
////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// This file is automatically generated by SkinTool [Version:0.2.3][Build:Jun 14 2017 09:17:51]
/////////////////////////////////////////////////////////////////////////////
typedef enum
{
HWND_MSGBOX_COMMON = 1,
HWND_MSGBOX_COMMON_BG = 2,
HWND_MSGBOX_COMMON_BG_TOP = 3,
HWND_MSGBOX_COMMON_NEW_BG_L = 4,
HWND_MSGBOX_COMMON_NEW_BG_C = 5,
HWND_MSGBOX_COMMON_NEW_BG_R = 6,
HWND_MSGBOX_COMMON_BG_L = 7,
HWND_MSGBOX_COMMON_BG_C = 8,
HWND_MSGBOX_COMMON_BG_R = 9,
HWND_MSGBOX_COMMON_TITLE = 10,
HWND_MSGBOX_TEXT_PANE = 11,
HWND_MSGBOX_COMMON_TEXT1 = 12,
HWND_MSGBOX_COMMON_TEXT2 = 13,
HWND_MSGBOX_PASSWORD_PANE = 14,
HWND_MSGBOX_PASSWORD_INPUT_1 = 15,
HWND_MSGBOX_PASSWORD_INPUT_2 = 16,
HWND_MSGBOX_PASSWORD_INPUT_3 = 17,
HWND_MSGBOX_PASSWORD_INPUT_4 = 18,
HWND_MSGBOX_PASSWORD_PRESSED_PANE = 19,
HWND_MSGBOX_PASSWORD_PRESSED_1 = 20,
HWND_MSGBOX_PASSWORD_PRESSED_2 = 21,
HWND_MSGBOX_PASSWORD_PRESSED_3 = 22,
HWND_MSGBOX_PASSWORD_PRESSED_4 = 23,
HWND_MSGBOX_COMMON_BTN_PANE = 24,
HWND_MSGBOX_COMMON_BTN_CLEAR = 25,
HWND_MSGBOX_COMMON_BTN_CLEAR_LEFT_ARROW = 26,
HWND_MSGBOX_COMMON_BTN_CLEAR_TEXT = 27,
HWND_MSGBOX_COMMON_BTN_OK = 28,
HWND_MSGBOX_COMMON_BTN_CANCEL_RIGHT_ARROW = 29,
HWND_MSGBOX_COMMON_BTN_CANCEL_TEXT = 30,
HWND_MSGBOX_COMMON_MSG_OK = 31,
HWND_MSGBOX_USB_LIST_PANE = 32,
HWND_MSGBOX_USB_LIST_ITEM0 = 33,
HWND_MSGBOX_USB_LIST_ITEM0_TEXT = 34,
HWND_MSGBOX_USB_LIST_ITEM1 = 35,
HWND_MSGBOX_USB_LIST_ITEM1_TEXT = 36,
HWND_MSGBOX_USB_LIST_ITEM2 = 37,
HWND_MSGBOX_USB_LIST_ITEM2_TEXT = 38,
HWND_MSGBOX_USB_LIST_ITEM3 = 39,
HWND_MSGBOX_USB_LIST_ITEM3_TEXT = 40,
HWND_EWS_FRAME = 41,
HWND_DISASTER_SYMBOL = 42,
HWND_AUTHOR_SYMBOL = 43,
HWND_DISASTER_LOCATION_STATUS_TXT = 44,
HWND_LOCATION_OF_DISASTER = 45,
HWND_DISASTER_TYPE = 46,
HWND_TYPE_TITLE = 47,
HWND_TYPE_CONTENT = 48,
HWND_DISASTER_DATE_AND_TIME = 49,
HWND_DATE_TITLE = 50,
HWND_DATE_CONTENT = 51,
HWND_DISASTER_LONGITUDE = 52,
HWND_LONGITUDE_TITLE = 53,
HWND_LONGITUDE_CONTENT = 54,
HWND_DISASTER_CHARACTER = 55,
HWND_CHARACTER_TITLE = 56,
HWND_CHARACTER_CONTENT = 57,
HWND_REMARK = 58,
HWND_REMARK_TITLE = 59,
HWND_REMARK_CONTENT = 60,
HWND_REMARK_DESCRIPTION = 61,
HWND_EWS_FRAME_WASPADA = 62,
HWND_DISASTER_SYMBOL2 = 63,
HWND_AUTHOR_SYMBOL2 = 64,
HWND_DISASTER_LOCATION_STATUS_TXT2 = 65,
HWND_LOCATION_OF_DISASTER2 = 66,
HWND_REMARK_DESCRIPTION2 = 67,
HWND_EWS_FRAME_WASPADA_SCROLL_BG = 68,
HWND_EWS_FRAME_WASPADA_SCROLL_BG_1 = 69,
HWND_EWS_FRAME_WASPADA_SCROLL_BAR = 70,
HWND_EWS_FRAME_WASPADA_SCROLL_BAR_1 = 71,
HWND_MESSAGE_BOX_MAX = 72,
} HWND_WINDOW_MESSAGE_BOX_ID;
extern WINDOWDRAWSTYLEDATA _MP_TBLSEG _GUI_WindowsDrawStyleList_Zui_Message_Box[];
//extern WINDOWVARDATA _GUI_WindowsRWDataList_Zui_Message_Box[];
extern WINDOWDATA _MP_TBLSEG _GUI_WindowList_Zui_Message_Box[];
extern WINDOWPOSDATA _MP_TBLSEG _GUI_WindowPositionList_Zui_Message_Box[];
extern WINDOWALPHADATA _MP_TBLSEG _GUI_WindowsAlphaList_Zui_Message_Box[];
#define ZUI_MESSAGE_BOX_XSTART 0
#define ZUI_MESSAGE_BOX_YSTART 0
#define ZUI_MESSAGE_BOX_WIDTH 1920
#define ZUI_MESSAGE_BOX_HEIGHT 1080
|
#include <iostream>
#include <WinSock2.h>
using namespace std;
DWORD WINAPI ThreadFunc(LPVOID threadParameter)
{
SOCKET clientSocket = *((SOCKET*)threadParameter);
// Считываем строку.
char line[256];
size_t length = (size_t)recv(clientSocket, line, sizeof(line), 0);
line[length] = '\0';
cout << "Length: " << length << endl;
// Функционал сервера.
int removeCount = 0;
if (length == 10)
{
for (size_t i = 0; i < length; i++)
{
if ((line[i] >= 'A') && (line[i] <= 'Z'))
{
// Удаляем символ.
removeCount++;
for (size_t j = i + 1; j <= length; j++)
{
line[j - 1] = line[j];
}
length--;
// Чтобы не пропустить символ, следующий за удаленным.
i--;
}
}
}
// Возвращаем результат.
send(clientSocket, (const char*)&removeCount, sizeof(removeCount), 0);
send(clientSocket, line, length + 1, 0);
// Закрываем сокет.
closesocket(clientSocket);
// Завершаем поток.
return 0;
}
void DoWork()
{
int errorCode;
// Создание слушающего сокета.
SOCKET listeningSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
// Привязка сокета.
struct sockaddr_in localAddress;
localAddress.sin_family = AF_INET;
localAddress.sin_port = htons(1280);
localAddress.sin_addr.s_addr = htonl(INADDR_ANY);
errorCode = bind(listeningSocket, (struct sockaddr*)&localAddress, sizeof(localAddress));
if (errorCode == SOCKET_ERROR)
{
cout << "bind() failed." << endl;
return;
}
// Помещаем сокет в состояние прослушивания.
listen(listeningSocket, 5);
// Ожидание запросов на новые соединения.
while (true)
{
SOCKET clientSocket;
struct sockaddr_in clientAddress;
int clientAddressSize = sizeof(clientAddress);
// Открытие соединения.
cout << "Accepting a client ..." << endl;
clientSocket = accept(listeningSocket, (struct sockaddr*)&clientAddress, &clientAddressSize);
if (clientSocket == INVALID_SOCKET)
{
cout << "accept() failed." << endl;
return;
}
cout << "Accepted connection from "
<< inet_ntoa(clientAddress.sin_addr) << ":" << ntohs(clientAddress.sin_port)
<< endl;
// Вызов нового потока для обслуживания клиента.
DWORD threadId;
HANDLE threadHandle = CreateThread(NULL, 0, ThreadFunc, &clientSocket, 0, &threadId);
if (threadHandle != NULL)
{
cout << "Started thread #" << threadId << endl;
}
else
{
cout << "CreateThread() failed." << endl;
closesocket(clientSocket);
}
}
// Закрытие сокета.
closesocket(listeningSocket);
}
void main()
{
int errorCode;
// Инициализация WinSock API.
WSADATA wsaData;
errorCode = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (errorCode != 0)
{
cout << "WSAStartup() failed. Error code: " << errorCode << endl;
return;
}
// Обработка запросов.
DoWork();
// Прекращение работы с WinSock API.
WSACleanup();
}
|
#pragma once
#include "Common.h"
class AnimSet;
struct Bone;
using BoneVec = vector< Bone* >;
struct MeshTexture;
using MeshTextureVec = vector< MeshTexture* >;
struct Effect;
using EffectVec = vector< Effect* >;
struct EffectDefault;
struct EffectPass;
class File;
class GraphicLoader
{
// Models
public:
static Bone* LoadModel( const string& fname );
static void DestroyModel( Bone* root_bone );
static AnimSet* LoadAnimation( const string& anim_fname, const string& anim_name );
private:
static StrVec processedFiles;
static BoneVec loadedModels;
static StrVec loadedModelNames;
static PtrVec loadedAnimations; // Pointers of AnimSet
// Textures
public:
static MeshTexture* LoadTexture( const string& texture_name, const string& model_path );
static void DestroyTextures();
private:
static MeshTextureVec loadedMeshTextures;
// Effects
public:
static Effect* LoadEffect( const string& effect_name, bool use_in_2d, const string& defines = "", const string& model_path = "", EffectDefault* defaults = nullptr, uint defaults_count = 0 );
static void EffectProcessVariables( EffectPass& effect_pass, bool start, float anim_proc = 0.0f, float anim_time = 0.0f, MeshTexture** textures = nullptr );
static bool LoadMinimalEffects();
static bool LoadDefaultEffects();
static bool Load3dEffects();
private:
static EffectVec loadedEffects;
static bool LoadEffectPass( Effect* effect, const string& fname, File& file, uint pass, bool use_in_2d, const string& defines, EffectDefault* defaults, uint defaults_count );
};
|
//All functionality and structs pertaining to the barrier modifier go in this file
float4 OutputBarrierPosition(float3 position, float3 velocity, float3 acceleration, float age, float interval, float3 controlPoint)
{
position = position + velocity * age;
return float4(position, 1.0f);
}
|
// $Id: DIV.h,v 1.10 2013/02/09 19:00:34 david Exp $ -*- c++ -*-
#ifndef __CDK8_NODE_EXPRESSION_DIV_H__
#define __CDK8_NODE_EXPRESSION_DIV_H__
#include <cdk/nodes/expressions/BinaryExpression.h>
#include "SemanticProcessor.h"
namespace cdk {
namespace node {
namespace expression {
/**
* Class for describing the division operator
*/
class DIV: public BinaryExpression {
public:
/**
* @param lineno source code line number for this nodes
* @param left first operand
* @param right second operand
*/
inline DIV(int lineno, Expression *left, Expression *right) :
BinaryExpression(lineno, left, right) {
}
/**
* @return the name of the node's class
*/
const char *name() const {
return "DIV";
}
/**
* @param sp semantic processor visitor
* @param level syntactic tree level
*/
virtual void accept(SemanticProcessor *sp, int level) {
sp->processDIV(this, level);
}
};
} // expression
} // node
} // cdk
#endif
// $Log: DIV.h,v $
// Revision 1.10 2013/02/09 19:00:34 david
// First CDK8 commit. Major code simplification.
// Starting C++11 implementation.
//
// Revision 1.9 2012/04/10 19:01:05 david
// Removed initialization-dependent static members in factories.
// Handling of ProgramNodes is now better encapsulated by visitors (not done
// by evaluators, as before). Major cleanup (comments).
//
// Revision 1.8 2012/03/06 15:07:45 david
// Added subtype to ExpressionType. This allows for more expressiveness in
// type description.
//
|
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> ii;
typedef vector<vi> vvi;
typedef vector<ii> vii;
typedef vector<bool> vb;
typedef vector<vb> vvb;
typedef set<int> si;
typedef map<string, int> msi;
typedef long long ll;
const ll INF = 1e18L + 1;
int denomination[] = {500, 100, 50, 10, 5, 1};
int main()
{
int n;
cin >> n;
int change = 1000 - n;
int count = 0;
while (change > 0)
{
for (int i = 0; i < 6; i++)
{
int coin = denomination[i];
if (change >= coin)
{
change -= coin;
count++;
break;
}
}
}
cout << count << endl;
return 0;
}
|
#include "Main.hpp"
#include "File_handler.hpp"
#include <stdio.h>
TFile_handler::TFile_handler()
{
first_menu=new(Tmenu);
}
void TFile_handler::change_handle()
{
char file_name[MAXLINE];
try{
std::cout<<"Please give me the name of your file: "<<std::endl;
std::cin.get(file_name,MAXLINE-2);
std::cin.clear();
std::cin.ignore(std::numeric_limits<int>::max(), '\n' );
std::string path= "../files/"+static_cast<std::string>(file_name);
handle.open(path);
if(!handle.good()) throw ERROR;
std::cout<<"Successfully opened file! :)"<<std::endl;
}catch(int){
handle.open(TExceptions::wrong_file_name());
std::cout<<"Successfully opened file! :)"<<std::endl;
}
}
void TFile_handler::get_data_from_file()
{
Tmenu* pointer_to_working_menu=first_menu;
std::string key;
do{
key=check_first_letter();
if(key==new_window_key){
char buff[new_window_key_size];
handle.getline(buff, new_window_key_size);
if(buff ==new_window_key){
key=check_first_letter();
if(key==title_window_key){
std::string buff;
getline(handle, buff,' ');
if(buff == title_window_key){
std::string title;
getline(handle,title,'\n');
Tmenu * pointer =pointer_to_working_menu->search_for_window(title);
std::cout<<"SIALALALA"<<pointer->tell_me_name()<<std::endl;
}
}
}
}else if(key==menu_key){
create_submenu(pointer_to_working_menu);
}else if(key==function_key){
create_function(pointer_to_working_menu);
}
}while(key!=exit_key);
first_menu->draw_yourself();
}
std::string TFile_handler::check_first_letter()
{
char c;
try{
handle>>c;
if(!handle) throw ERROR;
if(c =='N'){
handle.unget();
return new_window_key;
}else if(c=='M'){
handle.unget();
return menu_key;
}else if(c=='F'){
handle.unget();
return function_key;
}else if (c=='X'){
handle.unget();
return exit_key;
}else if(c=='T'){
handle.unget();
return title_window_key;
}else{c='E'; throw ERROR;}
}
catch(int){
handle.open(TExceptions::wrong_data_in_the_file());
check_first_letter();
}
return "ERROR";
}
void TFile_handler::get_letter()
{
char c= handle.get();
std::cout<<c<<std::endl;
}
void TFile_handler::create_function(Tmenu * pointer_to_working_menu)
{
char buff[function_key_size];
handle.getline(buff, function_key_size);
if(buff ==function_key){
pointer_to_working_menu->create_window_with_function();
}
}
void TFile_handler::create_submenu(Tmenu* pointer_to_working_menu)
{
std::string buff;
getline(handle, buff,' ');
if(buff == menu_key){
std::string name;
getline(handle,name, '\n');
pointer_to_working_menu->create_window_with_submenu(name);
}
}
|
#include <iostream>
using namespace std;
int main()
{
int num;
do
{
int sum;
cout << "Enter a number: " << endl;
cin >> num;
if(num > 0)
{
sum = sum + num;
}
}while(num > 0);
cout << "The sum of all positive numbers is: " << 20 << endl;
}
|
#include "View.h"
View::View(Model* m)
{
model = m;
window.create(model->dims, "Heroes Always Die");
fps = 60;
//background pic
Bak.setTexture(manager.get_texture("assets/bak.png", sf::Color::White));
Bak.setPosition(0, 0);
/* load textures and set them to the sprites */
//loading menu and ending screen
menuScreen.setTexture(manager.get_texture("assets/MENU.png"));
menuScreen.setPosition(0, 0);
endingScreen.setTexture(manager.get_texture("assets/GAMEOVER.png"));
endingScreen.setPosition(0, 0);
//load font and set HUD
if (!font.loadFromFile("assets/arial.ttf")) { std::cout << "Couldn't load font" << std::endl; }
HUD.setFont(font);
HUD.setCharacterSize(20);
HUD.setFillColor(sf::Color::Green);
//enemyHealthBar
model->sizeEnemHealthBar = manager.get_texture("assets/EnemHealth.png", sf::Color::White).getSize();
//playerHelathBar
model->sizeHealthBar = manager.get_texture("assets/HealthBar.png", sf::Color::White).getSize();
model->player.healthBar.setTexture(manager.get_texture("assets/HealthBar.png", sf::Color::White));
//playerSpriteSheet
model->sizePlayer.x = manager.get_texture("assets/Hat_man5.png", sf::Color(250, 250, 250)).getSize().x / 4;
model->sizePlayer.y = manager.get_texture("assets/Hat_man5.png", sf::Color(250, 250, 250)).getSize().y;
model->player.sprite.setTexture(manager.get_texture("assets/Hat_man5.png", sf::Color(250, 250, 250)), true);
model->player.sprite.setTextureRect(sf::IntRect(0, 0, 62, 88));
//blocks
model->sizeBlocks.x = (manager.get_texture("assets/plates.png", sf::Color::White).getSize().x - 2) / 3;
model->sizeBlocks.y = (manager.get_texture("assets/plates.png", sf::Color::White).getSize().y - 1) / 2;
//platforms
model->sizePlatforms.x = (manager.get_texture("assets/plates.png").getSize().x - 2) / 3;
model->sizePlatforms.y = (manager.get_texture("assets/plates.png").getSize().x - 1) / 5;
//enemies
model->sizeEnemies = manager.get_texture("assets/enemy01.png", sf::Color::White).getSize();
//mainWeapon
model->sizeWeapon = manager.get_texture("assets/gun01.png", sf::Color::White).getSize();
//inventory
model->player.inventory.spriteSheet = manager.get_texture("assets/item_slot.png", sf::Color::White);
model->player.inventory.vertex_height = 56;
model->player.inventory.vertex_width = 56;
//Grendes
model->sizeGrenade = manager.get_texture("assets/grenade.png", sf::Color::White).getSize();
//enemyBullets
model->sizeEnemyBullets = manager.get_texture("assets/bulletEnemy.png", sf::Color::Black).getSize();
//Boss
model->sizeBoss = manager.get_texture("assets/BOSS01.png", sf::Color(250, 250, 250)).getSize();
model->boss.boss_range = 138 * 48;
model->boss.boss_range_end = 168 * 48 - model->sizeBoss.x;
//loading the inventory textures
model->player.inventory.spriteSheet = manager.get_texture("assets/item_slot.png", sf::Color::White);
model->player.inventory.vertex_height = 56;
model->player.inventory.vertex_width = 56;
model->player.inventory.title.setTexture(manager.get_texture("assets/inventory.png", sf::Color::White));
model->player.inventory.throwing.setTexture(manager.get_texture("assets/throwing.png", sf::Color::White));
//loading textures for the craftable sprite array
model->craftable.title.setTexture(manager.get_texture("assets/crafting.png", sf::Color::White), true);
model->craftable.title.setPosition(0, 0);
//loading texture for the crafting slot
model->craftable.slot.setTexture(manager.get_texture("assets/craft_slot.png", sf::Color::White));
model->sizeMaterial = manager.get_texture("assets/material1.png", sf::Color::White).getSize();
sf::Sprite tempSprite;
//loading guns
tempSprite.setTexture(manager.get_texture("assets/gun07.png", sf::Color::White), true);
model->craftable.weapon_list.insert(std::pair<std::string, sf::Sprite>("HealingStaff", tempSprite));
tempSprite.setTexture(manager.get_texture("assets/gun05.png", sf::Color::White), true);
model->craftable.weapon_list.insert(std::pair<std::string, sf::Sprite>("Sniper", tempSprite));
tempSprite.setTexture(manager.get_texture("assets/gun01.png", sf::Color::White), true);
model->craftable.weapon_list.insert(std::pair<std::string, sf::Sprite>("Gun", tempSprite));
tempSprite.setTexture(manager.get_texture("assets/gun03.png", sf::Color::White), true);
model->craftable.weapon_list.insert(std::pair<std::string, sf::Sprite>("RocketLauncher", tempSprite));
tempSprite.setTexture(manager.get_texture("assets/grenade.png", sf::Color::White), true);
model->craftable.weapon_list.insert(std::pair<std::string, sf::Sprite>("Grenade", tempSprite));
//loading material
tempSprite.setScale(0.5f, 0.5f);
tempSprite.setTexture(manager.get_texture("assets/material1.png", sf::Color::White), true);
model->craftable.material_list.insert(std::pair<int, sf::Sprite>(1, tempSprite));
tempSprite.setTexture(manager.get_texture("assets/material2.png", sf::Color::White), true);
model->craftable.material_list.insert(std::pair<int, sf::Sprite>(2, tempSprite));
tempSprite.setTexture(manager.get_texture("assets/material3.png", sf::Color::White), true);
model->craftable.material_list.insert(std::pair<int, sf::Sprite>(3, tempSprite));
tempSprite.setTexture(manager.get_texture("assets/material4.png", sf::Color::White), true);
model->craftable.material_list.insert(std::pair<int, sf::Sprite>(4, tempSprite));
tempSprite.setTexture(manager.get_texture("assets/material5.png", sf::Color::White), true);
model->craftable.material_list.insert(std::pair<int, sf::Sprite>(5, tempSprite));
//load sounds
if (!model->DropSound.loadFromFile("assets/DropSound.wav")) { std::cout << "couldn't load sound file" << std::endl; }
if (!model->CraftedSound.loadFromFile("assets/CraftedSound.wav")) { std::cout << "couldn't load sound file" << std::endl; }
if (!model->CraftingSound.loadFromFile("assets/CraftingSound.wav")) { std::cout << "couldn't load sound file" << std::endl; }
if (!model->InventorySound.loadFromFile("assets/InventorySound.wav")) { std::cout << "couldn't load sound file" << std::endl; }
if (!model->ItemSound.loadFromFile("assets/ItemSound.wav")) { std::cout << "couldn't load sound file" << std::endl; }
if (!model->HealingSound.loadFromFile("assets/HealingSound.wav")) { std::cout << "couldn't load sound file" << std::endl; }
if (!model->LauncherSound.loadFromFile("assets/GrenadeLauncher.wav")) { std::cout << "couldn't load sound file" << std::endl; }
if (!model->SniperSound.loadFromFile("assets/SniperSound.wav")) { std::cout << "couldn't load sound file" << std::endl; }
if (!model->GunShotSound.loadFromFile("assets/laserSound2.wav")) { std::cout << "couldn't load sound file" << std::endl; }
if (!model->ExplosionSound.loadFromFile("assets/Explosion.wav")) { std::cout << "Couldn't load sound file" << std::endl; }
if (!model->gameMusic.openFromFile("assets/GameBak.wav")) { std::cout << "couldn't load game music" << std::endl; }
model->gameMusic.setLoop(true);
model->gameMusic.play();
//create world and its platforms
std::cout << this->model->stages.size() << std::endl;
for (int i = 0; i < this->model->stages.size(); i++)
{
if (typeid(*this->model->stages[i]).name() == typeid(Platform).name())
{
this->model->stages[i]->sprite.setTexture(manager.get_texture("assets/plates.png"), true);
this->model->stages[i]->sprite.setTextureRect(sf::IntRect(48, 0, 48, 48));
}
else if (typeid(*this->model->stages[i]).name() == typeid(Block).name())
{
this->model->stages[i]->sprite.setTexture(manager.get_texture("assets/plates.png"), true);
this->model->stages[i]->sprite.setTextureRect(sf::IntRect(0, 0, 48, 48));
}
this->model->stages[i]->sprite.setPosition(this->model->stages[i]->position.x, this->model->stages[i]->position.y);
}
//setFrameRate
window.setFramerateLimit(fps);
}
View::~View()
{}
void View::render()
{
window.clear();
if (model->gameState == 1)
{
//Update Camera
camera.updateCamera(model->player.position, model->gameSize, model->dims);
//background
window.draw(Bak);
//Platforms
for (int i = 0; i < this->model->stages.size(); i++)
{
//check position before rendering
if ((model->stages[i]->position.x <= camera.position.x - model->sizeBlocks.x || model->stages[i]->position.x >= camera.position.x + model->dims.width)
&& (model->stages[i]->position.y <= camera.position.y - model->sizeBlocks.y || model->stages[i]->position.y >= camera.position.y + model->dims.height)) {
}
else { this->model->stages[i]->render(window, camera); }
}
for (int i = 0; i < model->materials.size(); i++) { model->materials[i]->render(window, camera); }
//Enemy
for (int j = 0; j < model->enemies.size(); j++)
{
//check position
if (!((model->enemies[j].position.x >= camera.position.x - 100 && model->enemies[j].position.x <= camera.position.x + model->dims.width + 100) &&
(model->enemies[j].position.y >= camera.position.y - 100 && model->enemies[j].position.y <= camera.position.y + model->dims.height + 100)))
{
continue;
}
//health bar
model->enemies[j].healthBar.setTexture(manager.get_texture("assets/EnemHealth.png", sf::Color::White));
//enemy text MIGHT NEED WORK
if (model->enemies[j].direction == 1) { model->enemies[j].sprite.setTexture(manager.get_texture("assets/enemy02.png", sf::Color::White)); }
else { model->enemies[j].sprite.setTexture(manager.get_texture("assets/enemy01.png", sf::Color::White)); }
//ENEMYBULLETS TEXT MIGHT NEED WORK
for (int i = 0; i < model->enemies[j].bullets.size(); i++)
{
model->enemies[j].bullets[i]->sprite.setTexture(manager.get_texture("assets/bulletEnemy.png", sf::Color::Black));
}
//draw enemy
model->enemies[j].render(window, camera);
}
//Boss
if (model->boss.direction == 1) { model->boss.sprite.setTexture(manager.get_texture("assets/BOSS02.png", sf::Color(250, 250, 250))); }
else { model->boss.sprite.setTexture(manager.get_texture("assets/BOSS01.png", sf::Color(250, 250, 250))); }
model->boss.render(window, camera);
//Player
model->player.render(window, camera);
//HUD
HUD.setPosition(25, 60);
HUD.setString("Bullets: " + std::to_string(model->player.mainWeapon->numBullets));
window.draw(HUD);
HUD.setPosition(25, 90);
HUD.setString("Grenades: " + std::to_string(model->player.grenNum));
window.draw(HUD);
HUD.setPosition(25, 120);
HUD.setString("Enemies: " + std::to_string(model->enemies.size()));
window.draw(HUD);
//Explosions MIGHT NEED WORK
for (int i = 0; i < model->explosions.size(); i++)
{
//set explosion textures
model->explosions[i]->sprite.setTexture(manager.get_texture("assets/explosion.png", sf::Color::White));
model->explosions[i]->render(window, camera);
}
//Inventory
if (model->player.InventoryOpen) { model->player.inventory.render(window); }
//Crafting menu
if (model->craftOpen)
{
if (model->player.position.y - camera.position.y + model->craftable.height < 30)
model->craftable.height = camera.position.y - model->player.position.y + 30;
else if (model->player.position.y - camera.position.y + model->craftable.height + (model->craftable.craft_position.size() * 85) > model->dims.height - 10)
model->craftable.height = camera.position.y - model->player.position.y - (model->craftable.craft_position.size() * 85) + model->dims.height - 10;
model->craftable.render(window, sf::Vector2f(model->player.position.x - camera.position.x, model->player.position.y - camera.position.y));
}
}
//render menu
else if (model->gameState == 0)
{
window.draw(menuScreen);
}
//render endgame
else if (model->gameState == 2)
{
window.draw(endingScreen);
}
window.display();
}
|
void deleteMiddle(stack<int> &s,int mid)
{
if(s.size()==mid)
{
s.pop();
return;
}
int a=s.top();
s.pop();
deleteMiddle(s,mid);
s.push(a);
return;
}
void deleteMid(stack<int>&s, int sizeOfStack)
{
deleteMiddle(s,(sizeOfStack-sizeOfStack/2));
//reverse(s);
while(s.size())
{
cout<<s.top()<<" ";
s.pop();
}
}
|
class Solution {
public:
static bool cmp(const vector<int>& a, const vector<int>& b) { // 比较,从小到大排序
return a[0] < b[0];
}
int findMinArrowShots(vector<vector<int>>& points) {
if (points.size() == 0) return 0; // 特判
sort(points.begin(), points.end(), cmp);
int result = 1; // 已经过了特判,说明一定有气球,那么result初始值为1
for (int i = 1; i < points.size(); i++) {
if (points[i][0] > points[i - 1][1]) result++; // 如果下一个气球的左边界在上一个气球的右边界之内,那么可以一箭穿多。注意!这里不能取等,因为题目要求,取等可以穿过。
// 反之,如果左边界在右边界之外,那么要多一支箭。
else points[i][1] = min(points[i][1], points[i - 1][1]); // 这是比较巧妙的地方。每次取的都是最小右边界。这样便于判断可不可以一箭穿多。
}
return result;
}
};
// reference https://mp.weixin.qq.com/s/HxVAJ6INMfNKiGwI88-RFw
|
#ifndef CLIENT_H
#define CLIENT_H
#include <QString>
#include <QSqlQuery>
#include <QSqlQueryModel>
class Client
{public:
Client();
Client(int,QString,QString);
QString get_nom();
QString get_prenom();
int get_id();
bool ajouter();
QSqlQueryModel * afficher();
bool supprimer(int);
bool modifier(int,QString,QString);
QSqlQueryModel * trier();
QSqlQueryModel * recherche(const QString &id);
private:
QString nom,prenom;
int id;
};
#endif // CLIENT_H
|
// 3_1. ポインタを理解しよう!! (メモリとアドレス)
// ポインタを使って配列を扱おう
#include <iostream>
int main(){
int a[5]{0}; // 豆知識:=をつけなくてもC++11から配列の初期化はできます.
// sizeofは静的確保したメモリのバイト数を調べる関数です.
// sizeofを使うことで配列の要素数を知ることができます.ただし,動的確保では使えません.
std::cout << "int型のByte数は?:" << sizeof(int) << "(4 * 8bit = 32bit)" << std::endl;
for (int i = 0; i < (sizeof(a)/sizeof(int)); ++i) {
std::cout << a[i] << std::endl;
}
for (int i = 0; i < (sizeof(a)/sizeof(int)); ++i) {
std::cout << "a[" << i << "] = " << &a[i] << std::endl;
}
}
|
/*
*
*/
#include "rocket.h"
Rocket::Rocket(Terrain *terrain)
: Object(terrain)
{
object_type_ = Object::ROCKET;
horizontal_speed() = 30; // set speed_z
collision_radius() = 0.01;
// get_acceleration() = Vector(0, 0, 0); // 加速度
md2_ = new ModelMD2();
md2_->Load((char*) "models/rocketair.md2", (char*) "models/rocket.pcx");
md2_->interpol = 1.0f;
md2_->SetState(MODEL_RUN);
bomb_ = nullptr;
is_bombing_ = false;
// load_bomb_texture();
Object::object_list_.push_back(this);
}
Rocket::~Rocket()
{
if(bomb_ != nullptr)
{
bomb_->KillSystem();
delete[] bomb_;
bomb_ = nullptr;
}
if(bomb_texture_ != nullptr)
{
delete bomb_texture_;
bomb_texture_ = nullptr;
}
}
//void Rocket::load_bomb_texture()
//{
// bomb_texture_ = new Texture((char*) "models/bomb.bmp");
//
// glGenTextures(1, &bomb_texture_->texID);
// glBindTexture(GL_TEXTURE_2D, bomb_texture_->texID);
//
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
//// glTexImage2D(GL_TEXTURE_2D, 0, 4, bomb_texture->width, bomb_texture->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, bomb_texture->data);
// gluBuild2DMipmaps(GL_TEXTURE_2D, 4, bomb_texture_->width, bomb_texture_->height, GL_RGBA, GL_UNSIGNED_BYTE,
// bomb_texture_->data);
//}
void Rocket::v_collision(Object *obj)
{
if(obj->object_type_ == ENEMY)
{
horizontal_speed() = 0;
status() = DEAD;
is_bombing_ = true;
// bomb_ = new Bomb(500, geometric_center(), 8.0, bomb_texture_->texID);
// PlaySound();
return;
}
if(is_bombing_ == false && is_on_ground() == true)
{
horizontal_speed() = 0;
is_bombing_ = true;
// bomb_ = new Bomb(500, geometric_center(), 8.0, bomb_texture_->texID);
// PlaySound();
}
}
void Rocket::v_draw(float second)
{
//// position() += speed() * s_passed;
//// position_.y = terrain_->GetHeight(position_.x, position_.z) + size_;
//// get_velocity() += get_acceleration() * s_passed;
// float cosYaw = (float)cos(DEG2RAD(direction));
// float sinPitch = (float)sin(DEG2RAD(pitch));
// float sinYaw = (float)sin(DEG2RAD(direction));
{
// double s = velocity.z * deltaTime;
// get_position().x += vector_x * s;
// get_position().y += vector_y * s;
// get_position().z += vector_z * s;
}
{
// LOG("deltaTime %f", deltaTime);
// Vector velocity_old = velocity;
// Vector velocity_average = (velocity + velocity_old) / 2;
// s = s * Vector(cosYaw, sinYaw, sinPitch);
// Vector s = get_velocity() * deltaTime;
// set_velocity(get_velocity() + get_acceleration() * deltaTime);
// set_position(get_position() + s);
}
if(status() == DEAD)
{
return;
}
want_to_go_forward(true);
// go_back_ = false;
// go_left_ = false;
// go_right_ = false;
// go_upper_ = false;
// go_lower_ = false;
// LOG("is_bombing_: %d", is_bombing_);
// if(is_bombing_ == true)
// {
// if(bomb_->IsDead() /*&& !audioSys->GetPerformance()->IsPlaying(entitySound->GetSegment(), nullptr)*/)
// {
// bomb_->KillSystem();
// delete bomb_;
// bomb_ = nullptr;
// is_bombing_ = false;
// status() = Object::object_status::DEAD;
// return;
// }
//
// bomb_->Update(second);
// bool b = glIsEnabled(GL_FOG);
// glDisable(GL_FOG);
// bomb_->Render();
// if(b)
// {
// glEnable(GL_FOG);
// }
// else
// {
// glDisable(GL_FOG);
// }
//
// return;
// }
if(horizontal_traveled_distance() >= 500.0f
|| is_on_ground() == true)
{
LOG();
// is_bombing_ = true;
horizontal_speed() = 0;
vertical_speed() = 0;
// bomb_ = new Bomb(10, geometric_center(), 0.1, bomb_texture_->texID);
status() = Object::object_status::DEAD;
// return;
}
// if the Rocket has not yet exploded, draw the Rocket model
bool b = glIsEnabled(GL_TEXTURE_2D);
glEnable(GL_TEXTURE_2D);
glColor3f(1.0, 1.0, 1.0);
glTranslatef(core_coord().x, core_coord().y, core_coord().z);
glRotatef(-ahead_yaw(), 0.0, 1.0, 0.0);
float a = 1.0 / 240;
glScalef(a, a, a);
md2_->render_single_frame(0);
if(b)
{
glEnable(GL_TEXTURE_2D);
}
else
{
glDisable(GL_TEXTURE_2D);
}
}
|
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<math.h>
#define MAXN 10005
using namespace std;
int ans[MAXN][MAXN],num[MAXN];
void Find_m_n(int N, int &m, int &n){
int sqr = (int)sqrt((double)N);
//printf("%d\n",sqr);
int a[200],b[200],cnt;
cnt = 0;
for(int i = 1; i <= sqr; i++){
if(N % i == 0){
a[cnt] = N / i;
b[cnt++] = i;
}
}
int min_i;
int min_mn = MAXN;
for(int i = 0; i < cnt; i++){
if(a[i]-b[i] < min_mn){
min_mn = a[i] - b[i];
min_i = i;
}
}
m = a[min_i];
n = b[min_i];
}
void fill_ans(int m, int n){
int left,right,low,high,cnt;
left = high = cnt = 0;
right = n - 1;
low = m - 1;
while(left <= right){
for(int i = left; i <= right; i++){
ans[high][i] = num[cnt++];
}
for(int i = high+1; i <= low; i++){
ans[i][right] = num[cnt++];
}
for(int i = right-1;i >= left;i--){
ans[low][i] = num[cnt++];
}
if(left == right) break; //一定要加这句,否则会出错,如当N=15时!!!!
for(int i = low-1; i >= high+1; i--){
ans[i][left] = num[cnt++];
}
high++;
left++;
right--;
low--;
}
}
bool cmp(int a, int b){
return a > b;
}
int main() {
int N,m,n;
//freopen("input.txt","r",stdin);
scanf("%d",&N);
for(int i = 0; i < N; i++){
scanf("%d",&num[i]);
}
sort(num,num+N,cmp);
Find_m_n(N,m,n);
fill_ans(m,n);
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(j==n-1) printf("%d\n",ans[i][j]);
else printf("%d ",ans[i][j]);
}
}
return 0;
}
|
#include <iostream>
#include <cstdio>
using namespace std;
int main(){
int v1,v2,t,s,l;
cin >> v1 >> v2 >>t>> s >> l;
int r=0,e=0;
int temp = 0;
int m = 0;
while(true){
m++;
e = e+v2;
if(temp==0){
r = r+v1;
if(r-e>=t)temp = s;
}else temp--;
if(r>=l||e>=l)break;
}
if(r>=l&&e>=l)cout<<"D"<<endl;
else if(r>=l)cout<<"R"<<endl;
else cout <<"T"<<endl;
cout<<m;
return 0;
}
|
/* A Bison parser, made by GNU Bison 3.8.2. */
/* Skeleton implementation for Bison GLR parsers in C
Copyright (C) 2002-2015, 2018-2021 Free Software Foundation, Inc.
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 <https://www.gnu.org/licenses/>. */
/* As a special exception, you may create a larger work that contains
part or all of the Bison parser skeleton and distribute that work
under terms of your choice, so long as that work isn't itself a
parser generator using the skeleton or a modified version thereof
as a parser skeleton. Alternatively, if you modify or redistribute
the parser skeleton itself, you may (at your option) remove this
special exception, which will cause the skeleton and the resulting
Bison output files to be licensed under the GNU General Public
License without this special exception.
This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */
/* C GLR parser skeleton written by Paul Hilfinger. */
/* DO NOT RELY ON FEATURES THAT ARE NOT DOCUMENTED in the manual,
especially those whose name start with YY_ or yy_. They are
private implementation details that can be changed or removed. */
/* Identify Bison output, and Bison version. */
#define YYBISON 30802
/* Bison version string. */
#define YYBISON_VERSION "3.8.2"
/* Skeleton name. */
#define YYSKELETON_NAME "glr.c"
/* Pure parsers. */
#define YYPURE 0
/* Substitute the type names. */
#define YYSTYPE COMMAND_STYPE
#define YYLTYPE COMMAND_LTYPE
/* Substitute the variable and function names. */
#define yyparse command_parse
#define yylex command_lex
#define yyerror command_error
#define yydebug command_debug
#define yylval command_lval
#define yychar command_char
#define yynerrs command_nerrs
#define yylloc command_lloc
/* First part of user prologue. */
#line 10 "command_parser.y"
#include <iostream>
#include <cmath>
#include <vector>
#include <memory>
#include <set>
#include <tuple>
#include <algorithm>
#include "../SearchController.h"
#include "../../Kernel/Flags.h"
#include "../ParseController.h"
#include "../AuxiliaryController.hpp"
// this function will be generated
// using flex
extern int yylex();
extern int command_lineno;
extern void yyerror(int &result, std::string &width_type, int &width_value,char const* msg);
Flags flags;
#line 91 "command_parser.cpp"
# ifndef YY_CAST
# ifdef __cplusplus
# define YY_CAST(Type, Val) static_cast<Type> (Val)
# define YY_REINTERPRET_CAST(Type, Val) reinterpret_cast<Type> (Val)
# else
# define YY_CAST(Type, Val) ((Type) (Val))
# define YY_REINTERPRET_CAST(Type, Val) ((Type) (Val))
# endif
# endif
# ifndef YY_NULLPTR
# if defined __cplusplus
# if 201103L <= __cplusplus
# define YY_NULLPTR nullptr
# else
# define YY_NULLPTR 0
# endif
# else
# define YY_NULLPTR ((void*)0)
# endif
# endif
#include "command_parser.hpp"
/* Symbol kind. */
enum yysymbol_kind_t
{
YYSYMBOL_YYEMPTY = -2,
YYSYMBOL_YYEOF = 0, /* "end of file" */
YYSYMBOL_YYerror = 1, /* error */
YYSYMBOL_YYUNDEF = 2, /* "invalid token" */
YYSYMBOL_command_newline = 3, /* command_newline */
YYSYMBOL_command_search_signature = 4, /* command_search_signature */
YYSYMBOL_command_print_state_flag = 5, /* command_print_state_flag */
YYSYMBOL_command_print_loop_flag = 6, /* command_print_loop_flag */
YYSYMBOL_command_string = 7, /* command_string */
YYSYMBOL_command_help = 8, /* command_help */
YYSYMBOL_command_end = 9, /* command_end */
YYSYMBOL_command_parse_signature = 10, /* command_parse_signature */
YYSYMBOL_command_parse_pace = 11, /* command_parse_pace */
YYSYMBOL_command_parse_itd = 12, /* command_parse_itd */
YYSYMBOL_command_term_signature = 13, /* command_term_signature */
YYSYMBOL_command_print_state_tree = 14, /* command_print_state_tree */
YYSYMBOL_command_random_signature = 15, /* command_random_signature */
YYSYMBOL_command_number = 16, /* command_number */
YYSYMBOL_command_premise = 17, /* command_premise */
YYSYMBOL_command_no_bfs_dag = 18, /* command_no_bfs_dag */
YYSYMBOL_command_nthreads = 19, /* command_nthreads */
YYSYMBOL_command_pw = 20, /* command_pw */
YYSYMBOL_command_tw = 21, /* command_tw */
YYSYMBOL_command_equal = 22, /* command_equal */
YYSYMBOL_command_print_directed_bipartite_graph = 23, /* command_print_directed_bipartite_graph */
YYSYMBOL_command_write_files = 24, /* command_write_files */
YYSYMBOL_YYACCEPT = 25, /* $accept */
YYSYMBOL_command_start = 26, /* command_start */
YYSYMBOL_command_search = 27, /* command_search */
YYSYMBOL_command_width = 28, /* command_width */
YYSYMBOL_command_random = 29, /* command_random */
YYSYMBOL_command_flags = 30, /* command_flags */
YYSYMBOL_command_input_file = 31, /* command_input_file */
YYSYMBOL_command_search_strategy = 32, /* command_search_strategy */
YYSYMBOL_command_parse = 33, /* command_parse */
YYSYMBOL_command_term = 34 /* command_term */
};
typedef enum yysymbol_kind_t yysymbol_kind_t;
/* Default (constant) value used for initialization for null
right-hand sides. Unlike the standard yacc.c template, here we set
the default value of $$ to a zeroed-out value. Since the default
value is undefined, this behavior is technically correct. */
static YYSTYPE yyval_default;
static YYLTYPE yyloc_default
# if defined COMMAND_LTYPE_IS_TRIVIAL && COMMAND_LTYPE_IS_TRIVIAL
= { 1, 1, 1, 1 }
# endif
;
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef short
# undef short
#endif
/* On compilers that do not define __PTRDIFF_MAX__ etc., make sure
<limits.h> and (if available) <stdint.h> are included
so that the code can choose integer types of a good width. */
#ifndef __PTRDIFF_MAX__
# include <limits.h> /* INFRINGES ON USER NAME SPACE */
# if defined __STDC_VERSION__ && 199901 <= __STDC_VERSION__
# include <stdint.h> /* INFRINGES ON USER NAME SPACE */
# define YY_STDINT_H
# endif
#endif
/* Narrow types that promote to a signed type and that can represent a
signed or unsigned integer of at least N bits. In tables they can
save space and decrease cache pressure. Promoting to a signed type
helps avoid bugs in integer arithmetic. */
#ifdef __INT_LEAST8_MAX__
typedef __INT_LEAST8_TYPE__ yytype_int8;
#elif defined YY_STDINT_H
typedef int_least8_t yytype_int8;
#else
typedef signed char yytype_int8;
#endif
#ifdef __INT_LEAST16_MAX__
typedef __INT_LEAST16_TYPE__ yytype_int16;
#elif defined YY_STDINT_H
typedef int_least16_t yytype_int16;
#else
typedef short yytype_int16;
#endif
/* Work around bug in HP-UX 11.23, which defines these macros
incorrectly for preprocessor constants. This workaround can likely
be removed in 2023, as HPE has promised support for HP-UX 11.23
(aka HP-UX 11i v2) only through the end of 2022; see Table 2 of
<https://h20195.www2.hpe.com/V2/getpdf.aspx/4AA4-7673ENW.pdf>. */
#ifdef __hpux
# undef UINT_LEAST8_MAX
# undef UINT_LEAST16_MAX
# define UINT_LEAST8_MAX 255
# define UINT_LEAST16_MAX 65535
#endif
#if defined __UINT_LEAST8_MAX__ && __UINT_LEAST8_MAX__ <= __INT_MAX__
typedef __UINT_LEAST8_TYPE__ yytype_uint8;
#elif (!defined __UINT_LEAST8_MAX__ && defined YY_STDINT_H \
&& UINT_LEAST8_MAX <= INT_MAX)
typedef uint_least8_t yytype_uint8;
#elif !defined __UINT_LEAST8_MAX__ && UCHAR_MAX <= INT_MAX
typedef unsigned char yytype_uint8;
#else
typedef short yytype_uint8;
#endif
#if defined __UINT_LEAST16_MAX__ && __UINT_LEAST16_MAX__ <= __INT_MAX__
typedef __UINT_LEAST16_TYPE__ yytype_uint16;
#elif (!defined __UINT_LEAST16_MAX__ && defined YY_STDINT_H \
&& UINT_LEAST16_MAX <= INT_MAX)
typedef uint_least16_t yytype_uint16;
#elif !defined __UINT_LEAST16_MAX__ && USHRT_MAX <= INT_MAX
typedef unsigned short yytype_uint16;
#else
typedef int yytype_uint16;
#endif
#ifndef YYPTRDIFF_T
# if defined __PTRDIFF_TYPE__ && defined __PTRDIFF_MAX__
# define YYPTRDIFF_T __PTRDIFF_TYPE__
# define YYPTRDIFF_MAXIMUM __PTRDIFF_MAX__
# elif defined PTRDIFF_MAX
# ifndef ptrdiff_t
# include <stddef.h> /* INFRINGES ON USER NAME SPACE */
# endif
# define YYPTRDIFF_T ptrdiff_t
# define YYPTRDIFF_MAXIMUM PTRDIFF_MAX
# else
# define YYPTRDIFF_T long
# define YYPTRDIFF_MAXIMUM LONG_MAX
# endif
#endif
#ifndef YYSIZE_T
# ifdef __SIZE_TYPE__
# define YYSIZE_T __SIZE_TYPE__
# elif defined size_t
# define YYSIZE_T size_t
# elif defined __STDC_VERSION__ && 199901 <= __STDC_VERSION__
# include <stddef.h> /* INFRINGES ON USER NAME SPACE */
# define YYSIZE_T size_t
# else
# define YYSIZE_T unsigned
# endif
#endif
#define YYSIZE_MAXIMUM \
YY_CAST (YYPTRDIFF_T, \
(YYPTRDIFF_MAXIMUM < YY_CAST (YYSIZE_T, -1) \
? YYPTRDIFF_MAXIMUM \
: YY_CAST (YYSIZE_T, -1)))
#define YYSIZEOF(X) YY_CAST (YYPTRDIFF_T, sizeof (X))
#ifndef YY_
# if defined YYENABLE_NLS && YYENABLE_NLS
# if ENABLE_NLS
# include <libintl.h> /* INFRINGES ON USER NAME SPACE */
# define YY_(Msgid) dgettext ("bison-runtime", Msgid)
# endif
# endif
# ifndef YY_
# define YY_(Msgid) Msgid
# endif
#endif
#ifndef YYFREE
# define YYFREE free
#endif
#ifndef YYMALLOC
# define YYMALLOC malloc
#endif
#ifndef YYREALLOC
# define YYREALLOC realloc
#endif
#ifdef __cplusplus
typedef bool yybool;
# define yytrue true
# define yyfalse false
#else
/* When we move to stdbool, get rid of the various casts to yybool. */
typedef signed char yybool;
# define yytrue 1
# define yyfalse 0
#endif
#ifndef YYSETJMP
# include <setjmp.h>
# define YYJMP_BUF jmp_buf
# define YYSETJMP(Env) setjmp (Env)
/* Pacify Clang and ICC. */
# define YYLONGJMP(Env, Val) \
do { \
longjmp (Env, Val); \
YY_ASSERT (0); \
} while (yyfalse)
#endif
#ifndef YY_ATTRIBUTE_PURE
# if defined __GNUC__ && 2 < __GNUC__ + (96 <= __GNUC_MINOR__)
# define YY_ATTRIBUTE_PURE __attribute__ ((__pure__))
# else
# define YY_ATTRIBUTE_PURE
# endif
#endif
#ifndef YY_ATTRIBUTE_UNUSED
# if defined __GNUC__ && 2 < __GNUC__ + (7 <= __GNUC_MINOR__)
# define YY_ATTRIBUTE_UNUSED __attribute__ ((__unused__))
# else
# define YY_ATTRIBUTE_UNUSED
# endif
#endif
/* The _Noreturn keyword of C11. */
#ifndef _Noreturn
# if (defined __cplusplus \
&& ((201103 <= __cplusplus && !(__GNUC__ == 4 && __GNUC_MINOR__ == 7)) \
|| (defined _MSC_VER && 1900 <= _MSC_VER)))
# define _Noreturn [[noreturn]]
# elif ((!defined __cplusplus || defined __clang__) \
&& (201112 <= (defined __STDC_VERSION__ ? __STDC_VERSION__ : 0) \
|| (!defined __STRICT_ANSI__ \
&& (4 < __GNUC__ + (7 <= __GNUC_MINOR__) \
|| (defined __apple_build_version__ \
? 6000000 <= __apple_build_version__ \
: 3 < __clang_major__ + (5 <= __clang_minor__))))))
/* _Noreturn works as-is. */
# elif (2 < __GNUC__ + (8 <= __GNUC_MINOR__) || defined __clang__ \
|| 0x5110 <= __SUNPRO_C)
# define _Noreturn __attribute__ ((__noreturn__))
# elif 1200 <= (defined _MSC_VER ? _MSC_VER : 0)
# define _Noreturn __declspec (noreturn)
# else
# define _Noreturn
# endif
#endif
/* Suppress unused-variable warnings by "using" E. */
#if ! defined lint || defined __GNUC__
# define YY_USE(E) ((void) (E))
#else
# define YY_USE(E) /* empty */
#endif
/* Suppress an incorrect diagnostic about yylval being uninitialized. */
#if defined __GNUC__ && ! defined __ICC && 406 <= __GNUC__ * 100 + __GNUC_MINOR__
# if __GNUC__ * 100 + __GNUC_MINOR__ < 407
# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \
_Pragma ("GCC diagnostic push") \
_Pragma ("GCC diagnostic ignored \"-Wuninitialized\"")
# else
# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \
_Pragma ("GCC diagnostic push") \
_Pragma ("GCC diagnostic ignored \"-Wuninitialized\"") \
_Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"")
# endif
# define YY_IGNORE_MAYBE_UNINITIALIZED_END \
_Pragma ("GCC diagnostic pop")
#else
# define YY_INITIAL_VALUE(Value) Value
#endif
#ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
# define YY_IGNORE_MAYBE_UNINITIALIZED_END
#endif
#ifndef YY_INITIAL_VALUE
# define YY_INITIAL_VALUE(Value) /* Nothing. */
#endif
#if defined __cplusplus && defined __GNUC__ && ! defined __ICC && 6 <= __GNUC__
# define YY_IGNORE_USELESS_CAST_BEGIN \
_Pragma ("GCC diagnostic push") \
_Pragma ("GCC diagnostic ignored \"-Wuseless-cast\"")
# define YY_IGNORE_USELESS_CAST_END \
_Pragma ("GCC diagnostic pop")
#endif
#ifndef YY_IGNORE_USELESS_CAST_BEGIN
# define YY_IGNORE_USELESS_CAST_BEGIN
# define YY_IGNORE_USELESS_CAST_END
#endif
#define YY_ASSERT(E) ((void) (0 && (E)))
/* YYFINAL -- State number of the termination state. */
#define YYFINAL 17
/* YYLAST -- Last index in YYTABLE. */
#define YYLAST 53
/* YYNTOKENS -- Number of terminals. */
#define YYNTOKENS 25
/* YYNNTS -- Number of nonterminals. */
#define YYNNTS 10
/* YYNRULES -- Number of rules. */
#define YYNRULES 24
/* YYNSTATES -- Number of states. */
#define YYNSTATES 63
/* YYMAXRHS -- Maximum number of symbols on right-hand side of rule. */
#define YYMAXRHS 7
/* YYMAXLEFT -- Maximum number of symbols to the left of a handle
accessed by $0, $-1, etc., in any rule. */
#define YYMAXLEFT 0
/* YYMAXUTOK -- Last valid token kind. */
#define YYMAXUTOK 279
/* YYTRANSLATE(TOKEN-NUM) -- Symbol number corresponding to TOKEN-NUM
as returned by yylex, with out-of-bounds checking. */
#define YYTRANSLATE(YYX) \
(0 <= (YYX) && (YYX) <= YYMAXUTOK \
? YY_CAST (yysymbol_kind_t, yytranslate[YYX]) \
: YYSYMBOL_YYUNDEF)
/* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM
as returned by yylex. */
static const yytype_int8 yytranslate[] =
{
0, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 1, 2, 3, 4,
5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24
};
#if COMMAND_DEBUG
/* YYRLINE[YYN] -- source line where rule number YYN was defined. */
static const yytype_int8 yyrline[] =
{
0, 53, 53, 54, 55, 56, 58, 65, 74, 75,
76, 85, 86, 87, 88, 89, 90, 91, 92, 93,
96, 98, 100, 102, 105
};
#endif
#define YYPACT_NINF (-28)
#define YYTABLE_NINF (-1)
/* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
STATE-NUM. */
static const yytype_int8 yypact[] =
{
27, -15, 8, 30, 14, 22, -28, -28, -28, 16,
17, 10, -28, 10, 10, -28, 21, -28, 20, 28,
10, 10, 10, 10, 10, 29, 10, 10, -3, 14,
14, -28, -28, -28, -28, -28, -28, -28, -28, 10,
-28, -28, -28, 31, 25, 14, 14, 14, -28, 32,
14, 34, 14, 37, 33, 41, -28, 42, -28, 36,
-28, -28, -28
};
/* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM.
Performed when YYTABLE does not specify something else to do. Zero
means the default is an error. */
static const yytype_int8 yydefact[] =
{
0, 0, 0, 0, 0, 0, 2, 4, 5, 0,
0, 19, 3, 19, 19, 20, 0, 1, 0, 0,
19, 19, 19, 19, 19, 0, 19, 19, 0, 0,
0, 24, 8, 9, 11, 12, 13, 14, 15, 19,
17, 18, 21, 0, 0, 0, 0, 0, 16, 0,
0, 0, 0, 0, 0, 0, 6, 0, 23, 0,
7, 22, 10
};
/* YYPGOTO[NTERM-NUM]. */
static const yytype_int8 yypgoto[] =
{
-28, -28, -28, -28, -28, -13, -27, 9, -28, -28
};
/* YYDEFGOTO[NTERM-NUM]. */
static const yytype_int8 yydefgoto[] =
{
0, 5, 6, 11, 44, 28, 16, 45, 7, 8
};
/* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If
positive, shift that token. If negative, reduce the rule whose
number is the opposite. If YYTABLE_NINF, syntax error. */
static const yytype_int8 yytable[] =
{
29, 30, 46, 47, 42, 9, 10, 34, 35, 36,
37, 38, 43, 40, 41, 20, 21, 12, 51, 52,
53, 15, 17, 55, 22, 57, 48, 23, 24, 25,
31, 1, 42, 26, 27, 2, 32, 3, 18, 19,
4, 13, 14, 56, 33, 39, 58, 49, 54, 59,
60, 61, 62, 50
};
static const yytype_int8 yycheck[] =
{
13, 14, 29, 30, 7, 20, 21, 20, 21, 22,
23, 24, 15, 26, 27, 5, 6, 9, 45, 46,
47, 7, 0, 50, 14, 52, 39, 17, 18, 19,
9, 4, 7, 23, 24, 8, 16, 10, 22, 22,
13, 11, 12, 9, 16, 16, 9, 16, 16, 16,
9, 9, 16, 44
};
/* YYSTOS[STATE-NUM] -- The symbol kind of the accessing symbol of
state STATE-NUM. */
static const yytype_int8 yystos[] =
{
0, 4, 8, 10, 13, 26, 27, 33, 34, 20,
21, 28, 9, 11, 12, 7, 31, 0, 22, 22,
5, 6, 14, 17, 18, 19, 23, 24, 30, 30,
30, 9, 16, 16, 30, 30, 30, 30, 30, 16,
30, 30, 7, 15, 29, 32, 31, 31, 30, 16,
32, 31, 31, 31, 16, 31, 9, 31, 9, 16,
9, 9, 16
};
/* YYR1[RULE-NUM] -- Symbol kind of the left-hand side of rule RULE-NUM. */
static const yytype_int8 yyr1[] =
{
0, 25, 26, 26, 26, 26, 27, 27, 28, 28,
29, 30, 30, 30, 30, 30, 30, 30, 30, 30,
31, 32, 33, 33, 34
};
/* YYR2[RULE-NUM] -- Number of symbols on the right-hand side of rule RULE-NUM. */
static const yytype_int8 yyr2[] =
{
0, 2, 1, 2, 1, 1, 6, 7, 3, 3,
5, 2, 2, 2, 2, 2, 3, 2, 2, 0,
1, 1, 7, 6, 3
};
/* YYDPREC[RULE-NUM] -- Dynamic precedence of rule #RULE-NUM (0 if none). */
static const yytype_int8 yydprec[] =
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0
};
/* YYMERGER[RULE-NUM] -- Index of merging function for rule #RULE-NUM. */
static const yytype_int8 yymerger[] =
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0
};
/* YYIMMEDIATE[RULE-NUM] -- True iff rule #RULE-NUM is not to be deferred, as
in the case of predicates. */
static const yybool yyimmediate[] =
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0
};
/* YYCONFLP[YYPACT[STATE-NUM]] -- Pointer into YYCONFL of start of
list of conflicting reductions corresponding to action entry for
state STATE-NUM in yytable. 0 means no conflicts. The list in
yyconfl is terminated by a rule number of 0. */
static const yytype_int8 yyconflp[] =
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0
};
/* YYCONFL[I] -- lists of conflicting rule numbers, each terminated by
0, pointed into by YYCONFLP. */
static const short yyconfl[] =
{
0
};
/* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N].
If N is 0, then set CURRENT to the empty location which ends
the previous symbol: RHS[0] (always defined). */
#ifndef YYLLOC_DEFAULT
# define YYLLOC_DEFAULT(Current, Rhs, N) \
do \
if (N) \
{ \
(Current).first_line = YYRHSLOC (Rhs, 1).first_line; \
(Current).first_column = YYRHSLOC (Rhs, 1).first_column; \
(Current).last_line = YYRHSLOC (Rhs, N).last_line; \
(Current).last_column = YYRHSLOC (Rhs, N).last_column; \
} \
else \
{ \
(Current).first_line = (Current).last_line = \
YYRHSLOC (Rhs, 0).last_line; \
(Current).first_column = (Current).last_column = \
YYRHSLOC (Rhs, 0).last_column; \
} \
while (0)
#endif
# define YYRHSLOC(Rhs, K) ((Rhs)[K].yystate.yyloc)
YYSTYPE yylval;
YYLTYPE yylloc;
int yynerrs;
int yychar;
enum { YYENOMEM = -2 };
typedef enum { yyok, yyaccept, yyabort, yyerr, yynomem } YYRESULTTAG;
#define YYCHK(YYE) \
do { \
YYRESULTTAG yychk_flag = YYE; \
if (yychk_flag != yyok) \
return yychk_flag; \
} while (0)
/* YYINITDEPTH -- initial size of the parser's stacks. */
#ifndef YYINITDEPTH
# define YYINITDEPTH 200
#endif
/* YYMAXDEPTH -- maximum size the stacks can grow to (effective only
if the built-in stack extension method is used).
Do not make this value too large; the results are undefined if
SIZE_MAX < YYMAXDEPTH * sizeof (GLRStackItem)
evaluated with infinite-precision integer arithmetic. */
#ifndef YYMAXDEPTH
# define YYMAXDEPTH 10000
#endif
/* Minimum number of free items on the stack allowed after an
allocation. This is to allow allocation and initialization
to be completed by functions that call yyexpandGLRStack before the
stack is expanded, thus insuring that all necessary pointers get
properly redirected to new data. */
#define YYHEADROOM 2
#ifndef YYSTACKEXPANDABLE
# define YYSTACKEXPANDABLE 1
#endif
#if YYSTACKEXPANDABLE
# define YY_RESERVE_GLRSTACK(Yystack) \
do { \
if (Yystack->yyspaceLeft < YYHEADROOM) \
yyexpandGLRStack (Yystack); \
} while (0)
#else
# define YY_RESERVE_GLRSTACK(Yystack) \
do { \
if (Yystack->yyspaceLeft < YYHEADROOM) \
yyMemoryExhausted (Yystack); \
} while (0)
#endif
/** State numbers. */
typedef int yy_state_t;
/** Rule numbers. */
typedef int yyRuleNum;
/** Item references. */
typedef short yyItemNum;
typedef struct yyGLRState yyGLRState;
typedef struct yyGLRStateSet yyGLRStateSet;
typedef struct yySemanticOption yySemanticOption;
typedef union yyGLRStackItem yyGLRStackItem;
typedef struct yyGLRStack yyGLRStack;
struct yyGLRState
{
/** Type tag: always true. */
yybool yyisState;
/** Type tag for yysemantics. If true, yyval applies, otherwise
* yyfirstVal applies. */
yybool yyresolved;
/** Number of corresponding LALR(1) machine state. */
yy_state_t yylrState;
/** Preceding state in this stack */
yyGLRState* yypred;
/** Source position of the last token produced by my symbol */
YYPTRDIFF_T yyposn;
union {
/** First in a chain of alternative reductions producing the
* nonterminal corresponding to this state, threaded through
* yynext. */
yySemanticOption* yyfirstVal;
/** Semantic value for this state. */
YYSTYPE yyval;
} yysemantics;
/** Source location for this state. */
YYLTYPE yyloc;
};
struct yyGLRStateSet
{
yyGLRState** yystates;
/** During nondeterministic operation, yylookaheadNeeds tracks which
* stacks have actually needed the current lookahead. During deterministic
* operation, yylookaheadNeeds[0] is not maintained since it would merely
* duplicate yychar != COMMAND_EMPTY. */
yybool* yylookaheadNeeds;
YYPTRDIFF_T yysize;
YYPTRDIFF_T yycapacity;
};
struct yySemanticOption
{
/** Type tag: always false. */
yybool yyisState;
/** Rule number for this reduction */
yyRuleNum yyrule;
/** The last RHS state in the list of states to be reduced. */
yyGLRState* yystate;
/** The lookahead for this reduction. */
int yyrawchar;
YYSTYPE yyval;
YYLTYPE yyloc;
/** Next sibling in chain of options. To facilitate merging,
* options are chained in decreasing order by address. */
yySemanticOption* yynext;
};
/** Type of the items in the GLR stack. The yyisState field
* indicates which item of the union is valid. */
union yyGLRStackItem {
yyGLRState yystate;
yySemanticOption yyoption;
};
struct yyGLRStack {
int yyerrState;
/* To compute the location of the error token. */
yyGLRStackItem yyerror_range[3];
YYJMP_BUF yyexception_buffer;
yyGLRStackItem* yyitems;
yyGLRStackItem* yynextFree;
YYPTRDIFF_T yyspaceLeft;
yyGLRState* yysplitPoint;
yyGLRState* yylastDeleted;
yyGLRStateSet yytops;
};
#if YYSTACKEXPANDABLE
static void yyexpandGLRStack (yyGLRStack* yystackp);
#endif
_Noreturn static void
yyFail (yyGLRStack* yystackp, int &result, std::string &width_type, int &width_value, const char* yymsg)
{
if (yymsg != YY_NULLPTR)
yyerror (result, width_type, width_value, yymsg);
YYLONGJMP (yystackp->yyexception_buffer, 1);
}
_Noreturn static void
yyMemoryExhausted (yyGLRStack* yystackp)
{
YYLONGJMP (yystackp->yyexception_buffer, 2);
}
/** Accessing symbol of state YYSTATE. */
static inline yysymbol_kind_t
yy_accessing_symbol (yy_state_t yystate)
{
return YY_CAST (yysymbol_kind_t, yystos[yystate]);
}
#if COMMAND_DEBUG || 0
/* The user-facing name of the symbol whose (internal) number is
YYSYMBOL. No bounds checking. */
static const char *yysymbol_name (yysymbol_kind_t yysymbol) YY_ATTRIBUTE_UNUSED;
/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
First, the terminals, then, starting at YYNTOKENS, nonterminals. */
static const char *const yytname[] =
{
"\"end of file\"", "error", "\"invalid token\"", "command_newline",
"command_search_signature", "command_print_state_flag",
"command_print_loop_flag", "command_string", "command_help",
"command_end", "command_parse_signature", "command_parse_pace",
"command_parse_itd", "command_term_signature",
"command_print_state_tree", "command_random_signature", "command_number",
"command_premise", "command_no_bfs_dag", "command_nthreads",
"command_pw", "command_tw", "command_equal",
"command_print_directed_bipartite_graph", "command_write_files",
"$accept", "command_start", "command_search", "command_width",
"command_random", "command_flags", "command_input_file",
"command_search_strategy", "command_parse", "command_term", YY_NULLPTR
};
static const char *
yysymbol_name (yysymbol_kind_t yysymbol)
{
return yytname[yysymbol];
}
#endif
/** Left-hand-side symbol for rule #YYRULE. */
static inline yysymbol_kind_t
yylhsNonterm (yyRuleNum yyrule)
{
return YY_CAST (yysymbol_kind_t, yyr1[yyrule]);
}
#if COMMAND_DEBUG
# ifndef YYFPRINTF
# define YYFPRINTF fprintf
# endif
# define YY_FPRINTF \
YY_IGNORE_USELESS_CAST_BEGIN YY_FPRINTF_
# define YY_FPRINTF_(Args) \
do { \
YYFPRINTF Args; \
YY_IGNORE_USELESS_CAST_END \
} while (0)
# define YY_DPRINTF \
YY_IGNORE_USELESS_CAST_BEGIN YY_DPRINTF_
# define YY_DPRINTF_(Args) \
do { \
if (yydebug) \
YYFPRINTF Args; \
YY_IGNORE_USELESS_CAST_END \
} while (0)
/* YYLOCATION_PRINT -- Print the location on the stream.
This macro was not mandated originally: define only if we know
we won't break user code: when these are the locations we know. */
# ifndef YYLOCATION_PRINT
# if defined YY_LOCATION_PRINT
/* Temporary convenience wrapper in case some people defined the
undocumented and private YY_LOCATION_PRINT macros. */
# define YYLOCATION_PRINT(File, Loc) YY_LOCATION_PRINT(File, *(Loc))
# elif defined COMMAND_LTYPE_IS_TRIVIAL && COMMAND_LTYPE_IS_TRIVIAL
/* Print *YYLOCP on YYO. Private, do not rely on its existence. */
YY_ATTRIBUTE_UNUSED
static int
yy_location_print_ (FILE *yyo, YYLTYPE const * const yylocp)
{
int res = 0;
int end_col = 0 != yylocp->last_column ? yylocp->last_column - 1 : 0;
if (0 <= yylocp->first_line)
{
res += YYFPRINTF (yyo, "%d", yylocp->first_line);
if (0 <= yylocp->first_column)
res += YYFPRINTF (yyo, ".%d", yylocp->first_column);
}
if (0 <= yylocp->last_line)
{
if (yylocp->first_line < yylocp->last_line)
{
res += YYFPRINTF (yyo, "-%d", yylocp->last_line);
if (0 <= end_col)
res += YYFPRINTF (yyo, ".%d", end_col);
}
else if (0 <= end_col && yylocp->first_column < end_col)
res += YYFPRINTF (yyo, "-%d", end_col);
}
return res;
}
# define YYLOCATION_PRINT yy_location_print_
/* Temporary convenience wrapper in case some people defined the
undocumented and private YY_LOCATION_PRINT macros. */
# define YY_LOCATION_PRINT(File, Loc) YYLOCATION_PRINT(File, &(Loc))
# else
# define YYLOCATION_PRINT(File, Loc) ((void) 0)
/* Temporary convenience wrapper in case some people defined the
undocumented and private YY_LOCATION_PRINT macros. */
# define YY_LOCATION_PRINT YYLOCATION_PRINT
# endif
# endif /* !defined YYLOCATION_PRINT */
/*-----------------------------------.
| Print this symbol's value on YYO. |
`-----------------------------------*/
static void
yy_symbol_value_print (FILE *yyo,
yysymbol_kind_t yykind, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp, int &result, std::string &width_type, int &width_value)
{
FILE *yyoutput = yyo;
YY_USE (yyoutput);
YY_USE (yylocationp);
YY_USE (result);
YY_USE (width_type);
YY_USE (width_value);
if (!yyvaluep)
return;
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
YY_USE (yykind);
YY_IGNORE_MAYBE_UNINITIALIZED_END
}
/*---------------------------.
| Print this symbol on YYO. |
`---------------------------*/
static void
yy_symbol_print (FILE *yyo,
yysymbol_kind_t yykind, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp, int &result, std::string &width_type, int &width_value)
{
YYFPRINTF (yyo, "%s %s (",
yykind < YYNTOKENS ? "token" : "nterm", yysymbol_name (yykind));
YYLOCATION_PRINT (yyo, yylocationp);
YYFPRINTF (yyo, ": ");
yy_symbol_value_print (yyo, yykind, yyvaluep, yylocationp, result, width_type, width_value);
YYFPRINTF (yyo, ")");
}
# define YY_SYMBOL_PRINT(Title, Kind, Value, Location) \
do { \
if (yydebug) \
{ \
YY_FPRINTF ((stderr, "%s ", Title)); \
yy_symbol_print (stderr, Kind, Value, Location, result, width_type, width_value); \
YY_FPRINTF ((stderr, "\n")); \
} \
} while (0)
static inline void
yy_reduce_print (yybool yynormal, yyGLRStackItem* yyvsp, YYPTRDIFF_T yyk,
yyRuleNum yyrule, int &result, std::string &width_type, int &width_value);
# define YY_REDUCE_PRINT(Args) \
do { \
if (yydebug) \
yy_reduce_print Args; \
} while (0)
/* Nonzero means print parse trace. It is left uninitialized so that
multiple parsers can coexist. */
int yydebug;
static void yypstack (yyGLRStack* yystackp, YYPTRDIFF_T yyk)
YY_ATTRIBUTE_UNUSED;
static void yypdumpstack (yyGLRStack* yystackp)
YY_ATTRIBUTE_UNUSED;
#else /* !COMMAND_DEBUG */
# define YY_DPRINTF(Args) do {} while (yyfalse)
# define YY_SYMBOL_PRINT(Title, Kind, Value, Location)
# define YY_REDUCE_PRINT(Args)
#endif /* !COMMAND_DEBUG */
/** Fill in YYVSP[YYLOW1 .. YYLOW0-1] from the chain of states starting
* at YYVSP[YYLOW0].yystate.yypred. Leaves YYVSP[YYLOW1].yystate.yypred
* containing the pointer to the next state in the chain. */
static void yyfillin (yyGLRStackItem *, int, int) YY_ATTRIBUTE_UNUSED;
static void
yyfillin (yyGLRStackItem *yyvsp, int yylow0, int yylow1)
{
int i;
yyGLRState *s = yyvsp[yylow0].yystate.yypred;
for (i = yylow0-1; i >= yylow1; i -= 1)
{
#if COMMAND_DEBUG
yyvsp[i].yystate.yylrState = s->yylrState;
#endif
yyvsp[i].yystate.yyresolved = s->yyresolved;
if (s->yyresolved)
yyvsp[i].yystate.yysemantics.yyval = s->yysemantics.yyval;
else
/* The effect of using yyval or yyloc (in an immediate rule) is
* undefined. */
yyvsp[i].yystate.yysemantics.yyfirstVal = YY_NULLPTR;
yyvsp[i].yystate.yyloc = s->yyloc;
s = yyvsp[i].yystate.yypred = s->yypred;
}
}
/** If yychar is empty, fetch the next token. */
static inline yysymbol_kind_t
yygetToken (int *yycharp, int &result, std::string &width_type, int &width_value)
{
yysymbol_kind_t yytoken;
YY_USE (result);
YY_USE (width_type);
YY_USE (width_value);
if (*yycharp == COMMAND_EMPTY)
{
YY_DPRINTF ((stderr, "Reading a token\n"));
*yycharp = yylex ();
}
if (*yycharp <= COMMAND_EOF)
{
*yycharp = COMMAND_EOF;
yytoken = YYSYMBOL_YYEOF;
YY_DPRINTF ((stderr, "Now at end of input.\n"));
}
else
{
yytoken = YYTRANSLATE (*yycharp);
YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc);
}
return yytoken;
}
/* Do nothing if YYNORMAL or if *YYLOW <= YYLOW1. Otherwise, fill in
* YYVSP[YYLOW1 .. *YYLOW-1] as in yyfillin and set *YYLOW = YYLOW1.
* For convenience, always return YYLOW1. */
static inline int yyfill (yyGLRStackItem *, int *, int, yybool)
YY_ATTRIBUTE_UNUSED;
static inline int
yyfill (yyGLRStackItem *yyvsp, int *yylow, int yylow1, yybool yynormal)
{
if (!yynormal && yylow1 < *yylow)
{
yyfillin (yyvsp, *yylow, yylow1);
*yylow = yylow1;
}
return yylow1;
}
/** Perform user action for rule number YYN, with RHS length YYRHSLEN,
* and top stack item YYVSP. YYLVALP points to place to put semantic
* value ($$), and yylocp points to place for location information
* (@$). Returns yyok for normal return, yyaccept for YYACCEPT,
* yyerr for YYERROR, yyabort for YYABORT, yynomem for YYNOMEM. */
static YYRESULTTAG
yyuserAction (yyRuleNum yyrule, int yyrhslen, yyGLRStackItem* yyvsp,
yyGLRStack* yystackp, YYPTRDIFF_T yyk,
YYSTYPE* yyvalp, YYLTYPE *yylocp, int &result, std::string &width_type, int &width_value)
{
const yybool yynormal YY_ATTRIBUTE_UNUSED = yystackp->yysplitPoint == YY_NULLPTR;
int yylow = 1;
YY_USE (yyvalp);
YY_USE (yylocp);
YY_USE (result);
YY_USE (width_type);
YY_USE (width_value);
YY_USE (yyk);
YY_USE (yyrhslen);
# undef yyerrok
# define yyerrok (yystackp->yyerrState = 0)
# undef YYACCEPT
# define YYACCEPT return yyaccept
# undef YYABORT
# define YYABORT return yyabort
# undef YYNOMEM
# define YYNOMEM return yynomem
# undef YYERROR
# define YYERROR return yyerrok, yyerr
# undef YYRECOVERING
# define YYRECOVERING() (yystackp->yyerrState != 0)
# undef yyclearin
# define yyclearin (yychar = COMMAND_EMPTY)
# undef YYFILL
# define YYFILL(N) yyfill (yyvsp, &yylow, (N), yynormal)
# undef YYBACKUP
# define YYBACKUP(Token, Value) \
return yyerror (result, width_type, width_value, YY_("syntax error: cannot back up")), \
yyerrok, yyerr
if (yyrhslen == 0)
*yyvalp = yyval_default;
else
*yyvalp = yyvsp[YYFILL (1-yyrhslen)].yystate.yysemantics.yyval;
/* Default location. */
YYLLOC_DEFAULT ((*yylocp), (yyvsp - yyrhslen), yyrhslen);
yystackp->yyerror_range[1].yystate.yyloc = *yylocp;
/* If yyk == -1, we are running a deferred action on a temporary
stack. In that case, YY_REDUCE_PRINT must not play with YYFILL,
so pretend the stack is "normal". */
YY_REDUCE_PRINT ((yynormal || yyk == -1, yyvsp, yyk, yyrule, result, width_type, width_value));
switch (yyrule)
{
case 3: /* command_start: command_help command_end */
#line 54 "command_parser.y"
{show_manual();}
#line 1161 "command_parser.cpp"
break;
case 6: /* command_search: command_search_signature command_width command_flags command_search_strategy command_input_file command_end */
#line 59 "command_parser.y"
{ Width width;
width.set_name(width_type);
width.set_value(width_value);
SearchController search((YY_CAST (yyGLRStackItem const *, yyvsp)[YYFILL (-1)].yystate.yysemantics.yyval.string), (YY_CAST (yyGLRStackItem const *, yyvsp)[YYFILL (-2)].yystate.yysemantics.yyval.string), flags, width);
search.action();
}
#line 1172 "command_parser.cpp"
break;
case 7: /* command_search: command_search_signature command_width command_flags command_random command_search_strategy command_input_file command_end */
#line 66 "command_parser.y"
{ Width width;
width.set_name(width_type);
width.set_value(width_value);
SearchController search((YY_CAST (yyGLRStackItem const *, yyvsp)[YYFILL (-1)].yystate.yysemantics.yyval.string), (YY_CAST (yyGLRStackItem const *, yyvsp)[YYFILL (-2)].yystate.yysemantics.yyval.string),flags,width);
search.action();
}
#line 1183 "command_parser.cpp"
break;
case 8: /* command_width: command_pw command_equal command_number */
#line 74 "command_parser.y"
{width_type = "path_width"; if((YY_CAST (yyGLRStackItem const *, yyvsp)[YYFILL (0)].yystate.yysemantics.yyval.number)<0){std::cout<< "width value should be not negative" << std::endl; YYERROR;} width_value=(YY_CAST (yyGLRStackItem const *, yyvsp)[YYFILL (0)].yystate.yysemantics.yyval.number);}
#line 1189 "command_parser.cpp"
break;
case 9: /* command_width: command_tw command_equal command_number */
#line 75 "command_parser.y"
{width_type = "tree_width"; if((YY_CAST (yyGLRStackItem const *, yyvsp)[YYFILL (0)].yystate.yysemantics.yyval.number)<0){std::cout<< "width value should be not negative" << std::endl; YYERROR;} width_value=(YY_CAST (yyGLRStackItem const *, yyvsp)[YYFILL (0)].yystate.yysemantics.yyval.number);}
#line 1195 "command_parser.cpp"
break;
case 10: /* command_random: command_random_signature command_number command_number command_number command_number */
#line 76 "command_parser.y"
{
if((YY_CAST (yyGLRStackItem const *, yyvsp)[YYFILL (-2)].yystate.yysemantics.yyval.number)+(YY_CAST (yyGLRStackItem const *, yyvsp)[YYFILL (-1)].yystate.yysemantics.yyval.number)>1){std::cout<<"sum of the probalities is bigger than 1"<<std::endl;
YYERROR;}
flags.add_flag("seedValue", (YY_CAST (yyGLRStackItem const *, yyvsp)[YYFILL (-3)].yystate.yysemantics.yyval.number));
flags.add_flag("probAddVertex", (YY_CAST (yyGLRStackItem const *, yyvsp)[YYFILL (-2)].yystate.yysemantics.yyval.number));
flags.add_flag("probForgetVertex", (YY_CAST (yyGLRStackItem const *, yyvsp)[YYFILL (-1)].yystate.yysemantics.yyval.number));
flags.add_flag("numberOfIterations", (YY_CAST (yyGLRStackItem const *, yyvsp)[YYFILL (0)].yystate.yysemantics.yyval.number));
}
#line 1208 "command_parser.cpp"
break;
case 11: /* command_flags: command_print_state_flag command_flags */
#line 85 "command_parser.y"
{flags.add_flag("PrintStates", 1);}
#line 1214 "command_parser.cpp"
break;
case 12: /* command_flags: command_print_loop_flag command_flags */
#line 86 "command_parser.y"
{flags.add_flag("LoopTime", 1);}
#line 1220 "command_parser.cpp"
break;
case 13: /* command_flags: command_print_state_tree command_flags */
#line 87 "command_parser.y"
{flags.add_flag("StateTree", 1);}
#line 1226 "command_parser.cpp"
break;
case 14: /* command_flags: command_premise command_flags */
#line 88 "command_parser.y"
{flags.add_flag("Premise", 1);}
#line 1232 "command_parser.cpp"
break;
case 15: /* command_flags: command_no_bfs_dag command_flags */
#line 89 "command_parser.y"
{flags.add_flag("NoBFSDAG", 1);}
#line 1238 "command_parser.cpp"
break;
case 16: /* command_flags: command_nthreads command_number command_flags */
#line 90 "command_parser.y"
{ if ((YY_CAST (yyGLRStackItem const *, yyvsp)[YYFILL (-1)].yystate.yysemantics.yyval.number)<1){std::cout<< "Number of threads to use should be at least 1." << std::endl; YYERROR; } flags.add_flag("NThreads", (YY_CAST (yyGLRStackItem const *, yyvsp)[YYFILL (-1)].yystate.yysemantics.yyval.number));}
#line 1244 "command_parser.cpp"
break;
case 17: /* command_flags: command_print_directed_bipartite_graph command_flags */
#line 91 "command_parser.y"
{flags.add_flag("PrintDirectedBipartiteGraphNAUTY", 1);}
#line 1250 "command_parser.cpp"
break;
case 18: /* command_flags: command_write_files command_flags */
#line 92 "command_parser.y"
{flags.add_flag("WriteToFiles", 1);}
#line 1256 "command_parser.cpp"
break;
case 19: /* command_flags: %empty */
#line 93 "command_parser.y"
{}
#line 1262 "command_parser.cpp"
break;
case 20: /* command_input_file: command_string */
#line 96 "command_parser.y"
{ ((*yyvalp).string)=(YY_CAST (yyGLRStackItem const *, yyvsp)[YYFILL (0)].yystate.yysemantics.yyval.string);}
#line 1268 "command_parser.cpp"
break;
case 21: /* command_search_strategy: command_string */
#line 98 "command_parser.y"
{ ((*yyvalp).string)=(YY_CAST (yyGLRStackItem const *, yyvsp)[YYFILL (0)].yystate.yysemantics.yyval.string);}
#line 1274 "command_parser.cpp"
break;
case 22: /* command_parse: command_parse_signature command_parse_pace command_flags command_input_file command_input_file command_input_file command_end */
#line 101 "command_parser.y"
{ ParseController parsePACE(flags, (YY_CAST (yyGLRStackItem const *, yyvsp)[YYFILL (-3)].yystate.yysemantics.yyval.string)); parsePACE.parse_pace((YY_CAST (yyGLRStackItem const *, yyvsp)[YYFILL (-2)].yystate.yysemantics.yyval.string), (YY_CAST (yyGLRStackItem const *, yyvsp)[YYFILL (-1)].yystate.yysemantics.yyval.string)); }
#line 1280 "command_parser.cpp"
break;
case 23: /* command_parse: command_parse_signature command_parse_itd command_flags command_input_file command_input_file command_end */
#line 103 "command_parser.y"
{ ParseController parsePACE(flags, (YY_CAST (yyGLRStackItem const *, yyvsp)[YYFILL (-2)].yystate.yysemantics.yyval.string)); parsePACE.parse_itd((YY_CAST (yyGLRStackItem const *, yyvsp)[YYFILL (-1)].yystate.yysemantics.yyval.string));}
#line 1286 "command_parser.cpp"
break;
case 24: /* command_term: command_term_signature command_input_file command_end */
#line 105 "command_parser.y"
{ParseController parseTest(flags,(YY_CAST (yyGLRStackItem const *, yyvsp)[YYFILL (-1)].yystate.yysemantics.yyval.string)); parseTest.test_term();}
#line 1292 "command_parser.cpp"
break;
#line 1296 "command_parser.cpp"
default: break;
}
YY_SYMBOL_PRINT ("-> $$ =", yylhsNonterm (yyrule), yyvalp, yylocp);
return yyok;
# undef yyerrok
# undef YYABORT
# undef YYACCEPT
# undef YYNOMEM
# undef YYERROR
# undef YYBACKUP
# undef yyclearin
# undef YYRECOVERING
}
static void
yyuserMerge (int yyn, YYSTYPE* yy0, YYSTYPE* yy1)
{
YY_USE (yy0);
YY_USE (yy1);
switch (yyn)
{
default: break;
}
}
/* Bison grammar-table manipulation. */
/*-----------------------------------------------.
| Release the memory associated to this symbol. |
`-----------------------------------------------*/
static void
yydestruct (const char *yymsg,
yysymbol_kind_t yykind, YYSTYPE *yyvaluep, YYLTYPE *yylocationp, int &result, std::string &width_type, int &width_value)
{
YY_USE (yyvaluep);
YY_USE (yylocationp);
YY_USE (result);
YY_USE (width_type);
YY_USE (width_value);
if (!yymsg)
yymsg = "Deleting";
YY_SYMBOL_PRINT (yymsg, yykind, yyvaluep, yylocationp);
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
YY_USE (yykind);
YY_IGNORE_MAYBE_UNINITIALIZED_END
}
/** Number of symbols composing the right hand side of rule #RULE. */
static inline int
yyrhsLength (yyRuleNum yyrule)
{
return yyr2[yyrule];
}
static void
yydestroyGLRState (char const *yymsg, yyGLRState *yys, int &result, std::string &width_type, int &width_value)
{
if (yys->yyresolved)
yydestruct (yymsg, yy_accessing_symbol (yys->yylrState),
&yys->yysemantics.yyval, &yys->yyloc, result, width_type, width_value);
else
{
#if COMMAND_DEBUG
if (yydebug)
{
if (yys->yysemantics.yyfirstVal)
YY_FPRINTF ((stderr, "%s unresolved", yymsg));
else
YY_FPRINTF ((stderr, "%s incomplete", yymsg));
YY_SYMBOL_PRINT ("", yy_accessing_symbol (yys->yylrState), YY_NULLPTR, &yys->yyloc);
}
#endif
if (yys->yysemantics.yyfirstVal)
{
yySemanticOption *yyoption = yys->yysemantics.yyfirstVal;
yyGLRState *yyrh;
int yyn;
for (yyrh = yyoption->yystate, yyn = yyrhsLength (yyoption->yyrule);
yyn > 0;
yyrh = yyrh->yypred, yyn -= 1)
yydestroyGLRState (yymsg, yyrh, result, width_type, width_value);
}
}
}
#define yypact_value_is_default(Yyn) \
((Yyn) == YYPACT_NINF)
/** True iff LR state YYSTATE has only a default reduction (regardless
* of token). */
static inline yybool
yyisDefaultedState (yy_state_t yystate)
{
return yypact_value_is_default (yypact[yystate]);
}
/** The default reduction for YYSTATE, assuming it has one. */
static inline yyRuleNum
yydefaultAction (yy_state_t yystate)
{
return yydefact[yystate];
}
#define yytable_value_is_error(Yyn) \
0
/** The action to take in YYSTATE on seeing YYTOKEN.
* Result R means
* R < 0: Reduce on rule -R.
* R = 0: Error.
* R > 0: Shift to state R.
* Set *YYCONFLICTS to a pointer into yyconfl to a 0-terminated list
* of conflicting reductions.
*/
static inline int
yygetLRActions (yy_state_t yystate, yysymbol_kind_t yytoken, const short** yyconflicts)
{
int yyindex = yypact[yystate] + yytoken;
if (yytoken == YYSYMBOL_YYerror)
{
// This is the error token.
*yyconflicts = yyconfl;
return 0;
}
else if (yyisDefaultedState (yystate)
|| yyindex < 0 || YYLAST < yyindex || yycheck[yyindex] != yytoken)
{
*yyconflicts = yyconfl;
return -yydefact[yystate];
}
else if (! yytable_value_is_error (yytable[yyindex]))
{
*yyconflicts = yyconfl + yyconflp[yyindex];
return yytable[yyindex];
}
else
{
*yyconflicts = yyconfl + yyconflp[yyindex];
return 0;
}
}
/** Compute post-reduction state.
* \param yystate the current state
* \param yysym the nonterminal to push on the stack
*/
static inline yy_state_t
yyLRgotoState (yy_state_t yystate, yysymbol_kind_t yysym)
{
int yyr = yypgoto[yysym - YYNTOKENS] + yystate;
if (0 <= yyr && yyr <= YYLAST && yycheck[yyr] == yystate)
return yytable[yyr];
else
return yydefgoto[yysym - YYNTOKENS];
}
static inline yybool
yyisShiftAction (int yyaction)
{
return 0 < yyaction;
}
static inline yybool
yyisErrorAction (int yyaction)
{
return yyaction == 0;
}
/* GLRStates */
/** Return a fresh GLRStackItem in YYSTACKP. The item is an LR state
* if YYISSTATE, and otherwise a semantic option. Callers should call
* YY_RESERVE_GLRSTACK afterwards to make sure there is sufficient
* headroom. */
static inline yyGLRStackItem*
yynewGLRStackItem (yyGLRStack* yystackp, yybool yyisState)
{
yyGLRStackItem* yynewItem = yystackp->yynextFree;
yystackp->yyspaceLeft -= 1;
yystackp->yynextFree += 1;
yynewItem->yystate.yyisState = yyisState;
return yynewItem;
}
/** Add a new semantic action that will execute the action for rule
* YYRULE on the semantic values in YYRHS to the list of
* alternative actions for YYSTATE. Assumes that YYRHS comes from
* stack #YYK of *YYSTACKP. */
static void
yyaddDeferredAction (yyGLRStack* yystackp, YYPTRDIFF_T yyk, yyGLRState* yystate,
yyGLRState* yyrhs, yyRuleNum yyrule)
{
yySemanticOption* yynewOption =
&yynewGLRStackItem (yystackp, yyfalse)->yyoption;
YY_ASSERT (!yynewOption->yyisState);
yynewOption->yystate = yyrhs;
yynewOption->yyrule = yyrule;
if (yystackp->yytops.yylookaheadNeeds[yyk])
{
yynewOption->yyrawchar = yychar;
yynewOption->yyval = yylval;
yynewOption->yyloc = yylloc;
}
else
yynewOption->yyrawchar = COMMAND_EMPTY;
yynewOption->yynext = yystate->yysemantics.yyfirstVal;
yystate->yysemantics.yyfirstVal = yynewOption;
YY_RESERVE_GLRSTACK (yystackp);
}
/* GLRStacks */
/** Initialize YYSET to a singleton set containing an empty stack. */
static yybool
yyinitStateSet (yyGLRStateSet* yyset)
{
yyset->yysize = 1;
yyset->yycapacity = 16;
yyset->yystates
= YY_CAST (yyGLRState**,
YYMALLOC (YY_CAST (YYSIZE_T, yyset->yycapacity)
* sizeof yyset->yystates[0]));
if (! yyset->yystates)
return yyfalse;
yyset->yystates[0] = YY_NULLPTR;
yyset->yylookaheadNeeds
= YY_CAST (yybool*,
YYMALLOC (YY_CAST (YYSIZE_T, yyset->yycapacity)
* sizeof yyset->yylookaheadNeeds[0]));
if (! yyset->yylookaheadNeeds)
{
YYFREE (yyset->yystates);
return yyfalse;
}
memset (yyset->yylookaheadNeeds,
0,
YY_CAST (YYSIZE_T, yyset->yycapacity) * sizeof yyset->yylookaheadNeeds[0]);
return yytrue;
}
static void yyfreeStateSet (yyGLRStateSet* yyset)
{
YYFREE (yyset->yystates);
YYFREE (yyset->yylookaheadNeeds);
}
/** Initialize *YYSTACKP to a single empty stack, with total maximum
* capacity for all stacks of YYSIZE. */
static yybool
yyinitGLRStack (yyGLRStack* yystackp, YYPTRDIFF_T yysize)
{
yystackp->yyerrState = 0;
yynerrs = 0;
yystackp->yyspaceLeft = yysize;
yystackp->yyitems
= YY_CAST (yyGLRStackItem*,
YYMALLOC (YY_CAST (YYSIZE_T, yysize)
* sizeof yystackp->yynextFree[0]));
if (!yystackp->yyitems)
return yyfalse;
yystackp->yynextFree = yystackp->yyitems;
yystackp->yysplitPoint = YY_NULLPTR;
yystackp->yylastDeleted = YY_NULLPTR;
return yyinitStateSet (&yystackp->yytops);
}
#if YYSTACKEXPANDABLE
# define YYRELOC(YYFROMITEMS, YYTOITEMS, YYX, YYTYPE) \
&((YYTOITEMS) \
- ((YYFROMITEMS) - YY_REINTERPRET_CAST (yyGLRStackItem*, (YYX))))->YYTYPE
/** If *YYSTACKP is expandable, extend it. WARNING: Pointers into the
stack from outside should be considered invalid after this call.
We always expand when there are 1 or fewer items left AFTER an
allocation, so that we can avoid having external pointers exist
across an allocation. */
static void
yyexpandGLRStack (yyGLRStack* yystackp)
{
yyGLRStackItem* yynewItems;
yyGLRStackItem* yyp0, *yyp1;
YYPTRDIFF_T yynewSize;
YYPTRDIFF_T yyn;
YYPTRDIFF_T yysize = yystackp->yynextFree - yystackp->yyitems;
if (YYMAXDEPTH - YYHEADROOM < yysize)
yyMemoryExhausted (yystackp);
yynewSize = 2*yysize;
if (YYMAXDEPTH < yynewSize)
yynewSize = YYMAXDEPTH;
yynewItems
= YY_CAST (yyGLRStackItem*,
YYMALLOC (YY_CAST (YYSIZE_T, yynewSize)
* sizeof yynewItems[0]));
if (! yynewItems)
yyMemoryExhausted (yystackp);
for (yyp0 = yystackp->yyitems, yyp1 = yynewItems, yyn = yysize;
0 < yyn;
yyn -= 1, yyp0 += 1, yyp1 += 1)
{
*yyp1 = *yyp0;
if (*YY_REINTERPRET_CAST (yybool *, yyp0))
{
yyGLRState* yys0 = &yyp0->yystate;
yyGLRState* yys1 = &yyp1->yystate;
if (yys0->yypred != YY_NULLPTR)
yys1->yypred =
YYRELOC (yyp0, yyp1, yys0->yypred, yystate);
if (! yys0->yyresolved && yys0->yysemantics.yyfirstVal != YY_NULLPTR)
yys1->yysemantics.yyfirstVal =
YYRELOC (yyp0, yyp1, yys0->yysemantics.yyfirstVal, yyoption);
}
else
{
yySemanticOption* yyv0 = &yyp0->yyoption;
yySemanticOption* yyv1 = &yyp1->yyoption;
if (yyv0->yystate != YY_NULLPTR)
yyv1->yystate = YYRELOC (yyp0, yyp1, yyv0->yystate, yystate);
if (yyv0->yynext != YY_NULLPTR)
yyv1->yynext = YYRELOC (yyp0, yyp1, yyv0->yynext, yyoption);
}
}
if (yystackp->yysplitPoint != YY_NULLPTR)
yystackp->yysplitPoint = YYRELOC (yystackp->yyitems, yynewItems,
yystackp->yysplitPoint, yystate);
for (yyn = 0; yyn < yystackp->yytops.yysize; yyn += 1)
if (yystackp->yytops.yystates[yyn] != YY_NULLPTR)
yystackp->yytops.yystates[yyn] =
YYRELOC (yystackp->yyitems, yynewItems,
yystackp->yytops.yystates[yyn], yystate);
YYFREE (yystackp->yyitems);
yystackp->yyitems = yynewItems;
yystackp->yynextFree = yynewItems + yysize;
yystackp->yyspaceLeft = yynewSize - yysize;
}
#endif
static void
yyfreeGLRStack (yyGLRStack* yystackp)
{
YYFREE (yystackp->yyitems);
yyfreeStateSet (&yystackp->yytops);
}
/** Assuming that YYS is a GLRState somewhere on *YYSTACKP, update the
* splitpoint of *YYSTACKP, if needed, so that it is at least as deep as
* YYS. */
static inline void
yyupdateSplit (yyGLRStack* yystackp, yyGLRState* yys)
{
if (yystackp->yysplitPoint != YY_NULLPTR && yystackp->yysplitPoint > yys)
yystackp->yysplitPoint = yys;
}
/** Invalidate stack #YYK in *YYSTACKP. */
static inline void
yymarkStackDeleted (yyGLRStack* yystackp, YYPTRDIFF_T yyk)
{
if (yystackp->yytops.yystates[yyk] != YY_NULLPTR)
yystackp->yylastDeleted = yystackp->yytops.yystates[yyk];
yystackp->yytops.yystates[yyk] = YY_NULLPTR;
}
/** Undelete the last stack in *YYSTACKP that was marked as deleted. Can
only be done once after a deletion, and only when all other stacks have
been deleted. */
static void
yyundeleteLastStack (yyGLRStack* yystackp)
{
if (yystackp->yylastDeleted == YY_NULLPTR || yystackp->yytops.yysize != 0)
return;
yystackp->yytops.yystates[0] = yystackp->yylastDeleted;
yystackp->yytops.yysize = 1;
YY_DPRINTF ((stderr, "Restoring last deleted stack as stack #0.\n"));
yystackp->yylastDeleted = YY_NULLPTR;
}
static inline void
yyremoveDeletes (yyGLRStack* yystackp)
{
YYPTRDIFF_T yyi, yyj;
yyi = yyj = 0;
while (yyj < yystackp->yytops.yysize)
{
if (yystackp->yytops.yystates[yyi] == YY_NULLPTR)
{
if (yyi == yyj)
YY_DPRINTF ((stderr, "Removing dead stacks.\n"));
yystackp->yytops.yysize -= 1;
}
else
{
yystackp->yytops.yystates[yyj] = yystackp->yytops.yystates[yyi];
/* In the current implementation, it's unnecessary to copy
yystackp->yytops.yylookaheadNeeds[yyi] since, after
yyremoveDeletes returns, the parser immediately either enters
deterministic operation or shifts a token. However, it doesn't
hurt, and the code might evolve to need it. */
yystackp->yytops.yylookaheadNeeds[yyj] =
yystackp->yytops.yylookaheadNeeds[yyi];
if (yyj != yyi)
YY_DPRINTF ((stderr, "Rename stack %ld -> %ld.\n",
YY_CAST (long, yyi), YY_CAST (long, yyj)));
yyj += 1;
}
yyi += 1;
}
}
/** Shift to a new state on stack #YYK of *YYSTACKP, corresponding to LR
* state YYLRSTATE, at input position YYPOSN, with (resolved) semantic
* value *YYVALP and source location *YYLOCP. */
static inline void
yyglrShift (yyGLRStack* yystackp, YYPTRDIFF_T yyk, yy_state_t yylrState,
YYPTRDIFF_T yyposn,
YYSTYPE* yyvalp, YYLTYPE* yylocp)
{
yyGLRState* yynewState = &yynewGLRStackItem (yystackp, yytrue)->yystate;
yynewState->yylrState = yylrState;
yynewState->yyposn = yyposn;
yynewState->yyresolved = yytrue;
yynewState->yypred = yystackp->yytops.yystates[yyk];
yynewState->yysemantics.yyval = *yyvalp;
yynewState->yyloc = *yylocp;
yystackp->yytops.yystates[yyk] = yynewState;
YY_RESERVE_GLRSTACK (yystackp);
}
/** Shift stack #YYK of *YYSTACKP, to a new state corresponding to LR
* state YYLRSTATE, at input position YYPOSN, with the (unresolved)
* semantic value of YYRHS under the action for YYRULE. */
static inline void
yyglrShiftDefer (yyGLRStack* yystackp, YYPTRDIFF_T yyk, yy_state_t yylrState,
YYPTRDIFF_T yyposn, yyGLRState* yyrhs, yyRuleNum yyrule)
{
yyGLRState* yynewState = &yynewGLRStackItem (yystackp, yytrue)->yystate;
YY_ASSERT (yynewState->yyisState);
yynewState->yylrState = yylrState;
yynewState->yyposn = yyposn;
yynewState->yyresolved = yyfalse;
yynewState->yypred = yystackp->yytops.yystates[yyk];
yynewState->yysemantics.yyfirstVal = YY_NULLPTR;
yystackp->yytops.yystates[yyk] = yynewState;
/* Invokes YY_RESERVE_GLRSTACK. */
yyaddDeferredAction (yystackp, yyk, yynewState, yyrhs, yyrule);
}
#if COMMAND_DEBUG
/*----------------------------------------------------------------------.
| Report that stack #YYK of *YYSTACKP is going to be reduced by YYRULE. |
`----------------------------------------------------------------------*/
static inline void
yy_reduce_print (yybool yynormal, yyGLRStackItem* yyvsp, YYPTRDIFF_T yyk,
yyRuleNum yyrule, int &result, std::string &width_type, int &width_value)
{
int yynrhs = yyrhsLength (yyrule);
int yylow = 1;
int yyi;
YY_FPRINTF ((stderr, "Reducing stack %ld by rule %d (line %d):\n",
YY_CAST (long, yyk), yyrule - 1, yyrline[yyrule]));
if (! yynormal)
yyfillin (yyvsp, 1, -yynrhs);
/* The symbols being reduced. */
for (yyi = 0; yyi < yynrhs; yyi++)
{
YY_FPRINTF ((stderr, " $%d = ", yyi + 1));
yy_symbol_print (stderr,
yy_accessing_symbol (yyvsp[yyi - yynrhs + 1].yystate.yylrState),
&yyvsp[yyi - yynrhs + 1].yystate.yysemantics.yyval,
&(YY_CAST (yyGLRStackItem const *, yyvsp)[YYFILL ((yyi + 1) - (yynrhs))].yystate.yyloc) , result, width_type, width_value);
if (!yyvsp[yyi - yynrhs + 1].yystate.yyresolved)
YY_FPRINTF ((stderr, " (unresolved)"));
YY_FPRINTF ((stderr, "\n"));
}
}
#endif
/** Pop the symbols consumed by reduction #YYRULE from the top of stack
* #YYK of *YYSTACKP, and perform the appropriate semantic action on their
* semantic values. Assumes that all ambiguities in semantic values
* have been previously resolved. Set *YYVALP to the resulting value,
* and *YYLOCP to the computed location (if any). Return value is as
* for userAction. */
static inline YYRESULTTAG
yydoAction (yyGLRStack* yystackp, YYPTRDIFF_T yyk, yyRuleNum yyrule,
YYSTYPE* yyvalp, YYLTYPE *yylocp, int &result, std::string &width_type, int &width_value)
{
int yynrhs = yyrhsLength (yyrule);
if (yystackp->yysplitPoint == YY_NULLPTR)
{
/* Standard special case: single stack. */
yyGLRStackItem* yyrhs
= YY_REINTERPRET_CAST (yyGLRStackItem*, yystackp->yytops.yystates[yyk]);
YY_ASSERT (yyk == 0);
yystackp->yynextFree -= yynrhs;
yystackp->yyspaceLeft += yynrhs;
yystackp->yytops.yystates[0] = & yystackp->yynextFree[-1].yystate;
return yyuserAction (yyrule, yynrhs, yyrhs, yystackp, yyk,
yyvalp, yylocp, result, width_type, width_value);
}
else
{
yyGLRStackItem yyrhsVals[YYMAXRHS + YYMAXLEFT + 1];
yyGLRState* yys = yyrhsVals[YYMAXRHS + YYMAXLEFT].yystate.yypred
= yystackp->yytops.yystates[yyk];
int yyi;
if (yynrhs == 0)
/* Set default location. */
yyrhsVals[YYMAXRHS + YYMAXLEFT - 1].yystate.yyloc = yys->yyloc;
for (yyi = 0; yyi < yynrhs; yyi += 1)
{
yys = yys->yypred;
YY_ASSERT (yys);
}
yyupdateSplit (yystackp, yys);
yystackp->yytops.yystates[yyk] = yys;
return yyuserAction (yyrule, yynrhs, yyrhsVals + YYMAXRHS + YYMAXLEFT - 1,
yystackp, yyk, yyvalp, yylocp, result, width_type, width_value);
}
}
/** Pop items off stack #YYK of *YYSTACKP according to grammar rule YYRULE,
* and push back on the resulting nonterminal symbol. Perform the
* semantic action associated with YYRULE and store its value with the
* newly pushed state, if YYFORCEEVAL or if *YYSTACKP is currently
* unambiguous. Otherwise, store the deferred semantic action with
* the new state. If the new state would have an identical input
* position, LR state, and predecessor to an existing state on the stack,
* it is identified with that existing state, eliminating stack #YYK from
* *YYSTACKP. In this case, the semantic value is
* added to the options for the existing state's semantic value.
*/
static inline YYRESULTTAG
yyglrReduce (yyGLRStack* yystackp, YYPTRDIFF_T yyk, yyRuleNum yyrule,
yybool yyforceEval, int &result, std::string &width_type, int &width_value)
{
YYPTRDIFF_T yyposn = yystackp->yytops.yystates[yyk]->yyposn;
if (yyforceEval || yystackp->yysplitPoint == YY_NULLPTR)
{
YYSTYPE yyval;
YYLTYPE yyloc;
YYRESULTTAG yyflag = yydoAction (yystackp, yyk, yyrule, &yyval, &yyloc, result, width_type, width_value);
if (yyflag == yyerr && yystackp->yysplitPoint != YY_NULLPTR)
YY_DPRINTF ((stderr,
"Parse on stack %ld rejected by rule %d (line %d).\n",
YY_CAST (long, yyk), yyrule - 1, yyrline[yyrule]));
if (yyflag != yyok)
return yyflag;
yyglrShift (yystackp, yyk,
yyLRgotoState (yystackp->yytops.yystates[yyk]->yylrState,
yylhsNonterm (yyrule)),
yyposn, &yyval, &yyloc);
}
else
{
YYPTRDIFF_T yyi;
int yyn;
yyGLRState* yys, *yys0 = yystackp->yytops.yystates[yyk];
yy_state_t yynewLRState;
for (yys = yystackp->yytops.yystates[yyk], yyn = yyrhsLength (yyrule);
0 < yyn; yyn -= 1)
{
yys = yys->yypred;
YY_ASSERT (yys);
}
yyupdateSplit (yystackp, yys);
yynewLRState = yyLRgotoState (yys->yylrState, yylhsNonterm (yyrule));
YY_DPRINTF ((stderr,
"Reduced stack %ld by rule %d (line %d); action deferred. "
"Now in state %d.\n",
YY_CAST (long, yyk), yyrule - 1, yyrline[yyrule],
yynewLRState));
for (yyi = 0; yyi < yystackp->yytops.yysize; yyi += 1)
if (yyi != yyk && yystackp->yytops.yystates[yyi] != YY_NULLPTR)
{
yyGLRState *yysplit = yystackp->yysplitPoint;
yyGLRState *yyp = yystackp->yytops.yystates[yyi];
while (yyp != yys && yyp != yysplit && yyp->yyposn >= yyposn)
{
if (yyp->yylrState == yynewLRState && yyp->yypred == yys)
{
yyaddDeferredAction (yystackp, yyk, yyp, yys0, yyrule);
yymarkStackDeleted (yystackp, yyk);
YY_DPRINTF ((stderr, "Merging stack %ld into stack %ld.\n",
YY_CAST (long, yyk), YY_CAST (long, yyi)));
return yyok;
}
yyp = yyp->yypred;
}
}
yystackp->yytops.yystates[yyk] = yys;
yyglrShiftDefer (yystackp, yyk, yynewLRState, yyposn, yys0, yyrule);
}
return yyok;
}
static YYPTRDIFF_T
yysplitStack (yyGLRStack* yystackp, YYPTRDIFF_T yyk)
{
if (yystackp->yysplitPoint == YY_NULLPTR)
{
YY_ASSERT (yyk == 0);
yystackp->yysplitPoint = yystackp->yytops.yystates[yyk];
}
if (yystackp->yytops.yycapacity <= yystackp->yytops.yysize)
{
YYPTRDIFF_T state_size = YYSIZEOF (yystackp->yytops.yystates[0]);
YYPTRDIFF_T half_max_capacity = YYSIZE_MAXIMUM / 2 / state_size;
if (half_max_capacity < yystackp->yytops.yycapacity)
yyMemoryExhausted (yystackp);
yystackp->yytops.yycapacity *= 2;
{
yyGLRState** yynewStates
= YY_CAST (yyGLRState**,
YYREALLOC (yystackp->yytops.yystates,
(YY_CAST (YYSIZE_T, yystackp->yytops.yycapacity)
* sizeof yynewStates[0])));
if (yynewStates == YY_NULLPTR)
yyMemoryExhausted (yystackp);
yystackp->yytops.yystates = yynewStates;
}
{
yybool* yynewLookaheadNeeds
= YY_CAST (yybool*,
YYREALLOC (yystackp->yytops.yylookaheadNeeds,
(YY_CAST (YYSIZE_T, yystackp->yytops.yycapacity)
* sizeof yynewLookaheadNeeds[0])));
if (yynewLookaheadNeeds == YY_NULLPTR)
yyMemoryExhausted (yystackp);
yystackp->yytops.yylookaheadNeeds = yynewLookaheadNeeds;
}
}
yystackp->yytops.yystates[yystackp->yytops.yysize]
= yystackp->yytops.yystates[yyk];
yystackp->yytops.yylookaheadNeeds[yystackp->yytops.yysize]
= yystackp->yytops.yylookaheadNeeds[yyk];
yystackp->yytops.yysize += 1;
return yystackp->yytops.yysize - 1;
}
/** True iff YYY0 and YYY1 represent identical options at the top level.
* That is, they represent the same rule applied to RHS symbols
* that produce the same terminal symbols. */
static yybool
yyidenticalOptions (yySemanticOption* yyy0, yySemanticOption* yyy1)
{
if (yyy0->yyrule == yyy1->yyrule)
{
yyGLRState *yys0, *yys1;
int yyn;
for (yys0 = yyy0->yystate, yys1 = yyy1->yystate,
yyn = yyrhsLength (yyy0->yyrule);
yyn > 0;
yys0 = yys0->yypred, yys1 = yys1->yypred, yyn -= 1)
if (yys0->yyposn != yys1->yyposn)
return yyfalse;
return yytrue;
}
else
return yyfalse;
}
/** Assuming identicalOptions (YYY0,YYY1), destructively merge the
* alternative semantic values for the RHS-symbols of YYY1 and YYY0. */
static void
yymergeOptionSets (yySemanticOption* yyy0, yySemanticOption* yyy1)
{
yyGLRState *yys0, *yys1;
int yyn;
for (yys0 = yyy0->yystate, yys1 = yyy1->yystate,
yyn = yyrhsLength (yyy0->yyrule);
0 < yyn;
yys0 = yys0->yypred, yys1 = yys1->yypred, yyn -= 1)
{
if (yys0 == yys1)
break;
else if (yys0->yyresolved)
{
yys1->yyresolved = yytrue;
yys1->yysemantics.yyval = yys0->yysemantics.yyval;
}
else if (yys1->yyresolved)
{
yys0->yyresolved = yytrue;
yys0->yysemantics.yyval = yys1->yysemantics.yyval;
}
else
{
yySemanticOption** yyz0p = &yys0->yysemantics.yyfirstVal;
yySemanticOption* yyz1 = yys1->yysemantics.yyfirstVal;
while (yytrue)
{
if (yyz1 == *yyz0p || yyz1 == YY_NULLPTR)
break;
else if (*yyz0p == YY_NULLPTR)
{
*yyz0p = yyz1;
break;
}
else if (*yyz0p < yyz1)
{
yySemanticOption* yyz = *yyz0p;
*yyz0p = yyz1;
yyz1 = yyz1->yynext;
(*yyz0p)->yynext = yyz;
}
yyz0p = &(*yyz0p)->yynext;
}
yys1->yysemantics.yyfirstVal = yys0->yysemantics.yyfirstVal;
}
}
}
/** Y0 and Y1 represent two possible actions to take in a given
* parsing state; return 0 if no combination is possible,
* 1 if user-mergeable, 2 if Y0 is preferred, 3 if Y1 is preferred. */
static int
yypreference (yySemanticOption* y0, yySemanticOption* y1)
{
yyRuleNum r0 = y0->yyrule, r1 = y1->yyrule;
int p0 = yydprec[r0], p1 = yydprec[r1];
if (p0 == p1)
{
if (yymerger[r0] == 0 || yymerger[r0] != yymerger[r1])
return 0;
else
return 1;
}
if (p0 == 0 || p1 == 0)
return 0;
if (p0 < p1)
return 3;
if (p1 < p0)
return 2;
return 0;
}
static YYRESULTTAG
yyresolveValue (yyGLRState* yys, yyGLRStack* yystackp, int &result, std::string &width_type, int &width_value);
/** Resolve the previous YYN states starting at and including state YYS
* on *YYSTACKP. If result != yyok, some states may have been left
* unresolved possibly with empty semantic option chains. Regardless
* of whether result = yyok, each state has been left with consistent
* data so that yydestroyGLRState can be invoked if necessary. */
static YYRESULTTAG
yyresolveStates (yyGLRState* yys, int yyn,
yyGLRStack* yystackp, int &result, std::string &width_type, int &width_value)
{
if (0 < yyn)
{
YY_ASSERT (yys->yypred);
YYCHK (yyresolveStates (yys->yypred, yyn-1, yystackp, result, width_type, width_value));
if (! yys->yyresolved)
YYCHK (yyresolveValue (yys, yystackp, result, width_type, width_value));
}
return yyok;
}
/** Resolve the states for the RHS of YYOPT on *YYSTACKP, perform its
* user action, and return the semantic value and location in *YYVALP
* and *YYLOCP. Regardless of whether result = yyok, all RHS states
* have been destroyed (assuming the user action destroys all RHS
* semantic values if invoked). */
static YYRESULTTAG
yyresolveAction (yySemanticOption* yyopt, yyGLRStack* yystackp,
YYSTYPE* yyvalp, YYLTYPE *yylocp, int &result, std::string &width_type, int &width_value)
{
yyGLRStackItem yyrhsVals[YYMAXRHS + YYMAXLEFT + 1];
int yynrhs = yyrhsLength (yyopt->yyrule);
YYRESULTTAG yyflag =
yyresolveStates (yyopt->yystate, yynrhs, yystackp, result, width_type, width_value);
if (yyflag != yyok)
{
yyGLRState *yys;
for (yys = yyopt->yystate; yynrhs > 0; yys = yys->yypred, yynrhs -= 1)
yydestroyGLRState ("Cleanup: popping", yys, result, width_type, width_value);
return yyflag;
}
yyrhsVals[YYMAXRHS + YYMAXLEFT].yystate.yypred = yyopt->yystate;
if (yynrhs == 0)
/* Set default location. */
yyrhsVals[YYMAXRHS + YYMAXLEFT - 1].yystate.yyloc = yyopt->yystate->yyloc;
{
int yychar_current = yychar;
YYSTYPE yylval_current = yylval;
YYLTYPE yylloc_current = yylloc;
yychar = yyopt->yyrawchar;
yylval = yyopt->yyval;
yylloc = yyopt->yyloc;
yyflag = yyuserAction (yyopt->yyrule, yynrhs,
yyrhsVals + YYMAXRHS + YYMAXLEFT - 1,
yystackp, -1, yyvalp, yylocp, result, width_type, width_value);
yychar = yychar_current;
yylval = yylval_current;
yylloc = yylloc_current;
}
return yyflag;
}
#if COMMAND_DEBUG
static void
yyreportTree (yySemanticOption* yyx, int yyindent)
{
int yynrhs = yyrhsLength (yyx->yyrule);
int yyi;
yyGLRState* yys;
yyGLRState* yystates[1 + YYMAXRHS];
yyGLRState yyleftmost_state;
for (yyi = yynrhs, yys = yyx->yystate; 0 < yyi; yyi -= 1, yys = yys->yypred)
yystates[yyi] = yys;
if (yys == YY_NULLPTR)
{
yyleftmost_state.yyposn = 0;
yystates[0] = &yyleftmost_state;
}
else
yystates[0] = yys;
if (yyx->yystate->yyposn < yys->yyposn + 1)
YY_FPRINTF ((stderr, "%*s%s -> <Rule %d, empty>\n",
yyindent, "", yysymbol_name (yylhsNonterm (yyx->yyrule)),
yyx->yyrule - 1));
else
YY_FPRINTF ((stderr, "%*s%s -> <Rule %d, tokens %ld .. %ld>\n",
yyindent, "", yysymbol_name (yylhsNonterm (yyx->yyrule)),
yyx->yyrule - 1, YY_CAST (long, yys->yyposn + 1),
YY_CAST (long, yyx->yystate->yyposn)));
for (yyi = 1; yyi <= yynrhs; yyi += 1)
{
if (yystates[yyi]->yyresolved)
{
if (yystates[yyi-1]->yyposn+1 > yystates[yyi]->yyposn)
YY_FPRINTF ((stderr, "%*s%s <empty>\n", yyindent+2, "",
yysymbol_name (yy_accessing_symbol (yystates[yyi]->yylrState))));
else
YY_FPRINTF ((stderr, "%*s%s <tokens %ld .. %ld>\n", yyindent+2, "",
yysymbol_name (yy_accessing_symbol (yystates[yyi]->yylrState)),
YY_CAST (long, yystates[yyi-1]->yyposn + 1),
YY_CAST (long, yystates[yyi]->yyposn)));
}
else
yyreportTree (yystates[yyi]->yysemantics.yyfirstVal, yyindent+2);
}
}
#endif
static YYRESULTTAG
yyreportAmbiguity (yySemanticOption* yyx0,
yySemanticOption* yyx1, int &result, std::string &width_type, int &width_value)
{
YY_USE (yyx0);
YY_USE (yyx1);
#if COMMAND_DEBUG
YY_FPRINTF ((stderr, "Ambiguity detected.\n"));
YY_FPRINTF ((stderr, "Option 1,\n"));
yyreportTree (yyx0, 2);
YY_FPRINTF ((stderr, "\nOption 2,\n"));
yyreportTree (yyx1, 2);
YY_FPRINTF ((stderr, "\n"));
#endif
yyerror (result, width_type, width_value, YY_("syntax is ambiguous"));
return yyabort;
}
/** Resolve the locations for each of the YYN1 states in *YYSTACKP,
* ending at YYS1. Has no effect on previously resolved states.
* The first semantic option of a state is always chosen. */
static void
yyresolveLocations (yyGLRState *yys1, int yyn1,
yyGLRStack *yystackp, int &result, std::string &width_type, int &width_value)
{
if (0 < yyn1)
{
yyresolveLocations (yys1->yypred, yyn1 - 1, yystackp, result, width_type, width_value);
if (!yys1->yyresolved)
{
yyGLRStackItem yyrhsloc[1 + YYMAXRHS];
int yynrhs;
yySemanticOption *yyoption = yys1->yysemantics.yyfirstVal;
YY_ASSERT (yyoption);
yynrhs = yyrhsLength (yyoption->yyrule);
if (0 < yynrhs)
{
yyGLRState *yys;
int yyn;
yyresolveLocations (yyoption->yystate, yynrhs,
yystackp, result, width_type, width_value);
for (yys = yyoption->yystate, yyn = yynrhs;
yyn > 0;
yys = yys->yypred, yyn -= 1)
yyrhsloc[yyn].yystate.yyloc = yys->yyloc;
}
else
{
/* Both yyresolveAction and yyresolveLocations traverse the GSS
in reverse rightmost order. It is only necessary to invoke
yyresolveLocations on a subforest for which yyresolveAction
would have been invoked next had an ambiguity not been
detected. Thus the location of the previous state (but not
necessarily the previous state itself) is guaranteed to be
resolved already. */
yyGLRState *yyprevious = yyoption->yystate;
yyrhsloc[0].yystate.yyloc = yyprevious->yyloc;
}
YYLLOC_DEFAULT ((yys1->yyloc), yyrhsloc, yynrhs);
}
}
}
/** Resolve the ambiguity represented in state YYS in *YYSTACKP,
* perform the indicated actions, and set the semantic value of YYS.
* If result != yyok, the chain of semantic options in YYS has been
* cleared instead or it has been left unmodified except that
* redundant options may have been removed. Regardless of whether
* result = yyok, YYS has been left with consistent data so that
* yydestroyGLRState can be invoked if necessary. */
static YYRESULTTAG
yyresolveValue (yyGLRState* yys, yyGLRStack* yystackp, int &result, std::string &width_type, int &width_value)
{
yySemanticOption* yyoptionList = yys->yysemantics.yyfirstVal;
yySemanticOption* yybest = yyoptionList;
yySemanticOption** yypp;
yybool yymerge = yyfalse;
YYSTYPE yyval;
YYRESULTTAG yyflag;
YYLTYPE *yylocp = &yys->yyloc;
for (yypp = &yyoptionList->yynext; *yypp != YY_NULLPTR; )
{
yySemanticOption* yyp = *yypp;
if (yyidenticalOptions (yybest, yyp))
{
yymergeOptionSets (yybest, yyp);
*yypp = yyp->yynext;
}
else
{
switch (yypreference (yybest, yyp))
{
case 0:
yyresolveLocations (yys, 1, yystackp, result, width_type, width_value);
return yyreportAmbiguity (yybest, yyp, result, width_type, width_value);
break;
case 1:
yymerge = yytrue;
break;
case 2:
break;
case 3:
yybest = yyp;
yymerge = yyfalse;
break;
default:
/* This cannot happen so it is not worth a YY_ASSERT (yyfalse),
but some compilers complain if the default case is
omitted. */
break;
}
yypp = &yyp->yynext;
}
}
if (yymerge)
{
yySemanticOption* yyp;
int yyprec = yydprec[yybest->yyrule];
yyflag = yyresolveAction (yybest, yystackp, &yyval, yylocp, result, width_type, width_value);
if (yyflag == yyok)
for (yyp = yybest->yynext; yyp != YY_NULLPTR; yyp = yyp->yynext)
{
if (yyprec == yydprec[yyp->yyrule])
{
YYSTYPE yyval_other;
YYLTYPE yydummy;
yyflag = yyresolveAction (yyp, yystackp, &yyval_other, &yydummy, result, width_type, width_value);
if (yyflag != yyok)
{
yydestruct ("Cleanup: discarding incompletely merged value for",
yy_accessing_symbol (yys->yylrState),
&yyval, yylocp, result, width_type, width_value);
break;
}
yyuserMerge (yymerger[yyp->yyrule], &yyval, &yyval_other);
}
}
}
else
yyflag = yyresolveAction (yybest, yystackp, &yyval, yylocp, result, width_type, width_value);
if (yyflag == yyok)
{
yys->yyresolved = yytrue;
yys->yysemantics.yyval = yyval;
}
else
yys->yysemantics.yyfirstVal = YY_NULLPTR;
return yyflag;
}
static YYRESULTTAG
yyresolveStack (yyGLRStack* yystackp, int &result, std::string &width_type, int &width_value)
{
if (yystackp->yysplitPoint != YY_NULLPTR)
{
yyGLRState* yys;
int yyn;
for (yyn = 0, yys = yystackp->yytops.yystates[0];
yys != yystackp->yysplitPoint;
yys = yys->yypred, yyn += 1)
continue;
YYCHK (yyresolveStates (yystackp->yytops.yystates[0], yyn, yystackp
, result, width_type, width_value));
}
return yyok;
}
/** Called when returning to deterministic operation to clean up the extra
* stacks. */
static void
yycompressStack (yyGLRStack* yystackp)
{
/* yyr is the state after the split point. */
yyGLRState *yyr;
if (yystackp->yytops.yysize != 1 || yystackp->yysplitPoint == YY_NULLPTR)
return;
{
yyGLRState *yyp, *yyq;
for (yyp = yystackp->yytops.yystates[0], yyq = yyp->yypred, yyr = YY_NULLPTR;
yyp != yystackp->yysplitPoint;
yyr = yyp, yyp = yyq, yyq = yyp->yypred)
yyp->yypred = yyr;
}
yystackp->yyspaceLeft += yystackp->yynextFree - yystackp->yyitems;
yystackp->yynextFree = YY_REINTERPRET_CAST (yyGLRStackItem*, yystackp->yysplitPoint) + 1;
yystackp->yyspaceLeft -= yystackp->yynextFree - yystackp->yyitems;
yystackp->yysplitPoint = YY_NULLPTR;
yystackp->yylastDeleted = YY_NULLPTR;
while (yyr != YY_NULLPTR)
{
yystackp->yynextFree->yystate = *yyr;
yyr = yyr->yypred;
yystackp->yynextFree->yystate.yypred = &yystackp->yynextFree[-1].yystate;
yystackp->yytops.yystates[0] = &yystackp->yynextFree->yystate;
yystackp->yynextFree += 1;
yystackp->yyspaceLeft -= 1;
}
}
static YYRESULTTAG
yyprocessOneStack (yyGLRStack* yystackp, YYPTRDIFF_T yyk,
YYPTRDIFF_T yyposn, int &result, std::string &width_type, int &width_value)
{
while (yystackp->yytops.yystates[yyk] != YY_NULLPTR)
{
yy_state_t yystate = yystackp->yytops.yystates[yyk]->yylrState;
YY_DPRINTF ((stderr, "Stack %ld Entering state %d\n",
YY_CAST (long, yyk), yystate));
YY_ASSERT (yystate != YYFINAL);
if (yyisDefaultedState (yystate))
{
YYRESULTTAG yyflag;
yyRuleNum yyrule = yydefaultAction (yystate);
if (yyrule == 0)
{
YY_DPRINTF ((stderr, "Stack %ld dies.\n", YY_CAST (long, yyk)));
yymarkStackDeleted (yystackp, yyk);
return yyok;
}
yyflag = yyglrReduce (yystackp, yyk, yyrule, yyimmediate[yyrule], result, width_type, width_value);
if (yyflag == yyerr)
{
YY_DPRINTF ((stderr,
"Stack %ld dies "
"(predicate failure or explicit user error).\n",
YY_CAST (long, yyk)));
yymarkStackDeleted (yystackp, yyk);
return yyok;
}
if (yyflag != yyok)
return yyflag;
}
else
{
yysymbol_kind_t yytoken = yygetToken (&yychar, result, width_type, width_value);
const short* yyconflicts;
const int yyaction = yygetLRActions (yystate, yytoken, &yyconflicts);
yystackp->yytops.yylookaheadNeeds[yyk] = yytrue;
for (/* nothing */; *yyconflicts; yyconflicts += 1)
{
YYRESULTTAG yyflag;
YYPTRDIFF_T yynewStack = yysplitStack (yystackp, yyk);
YY_DPRINTF ((stderr, "Splitting off stack %ld from %ld.\n",
YY_CAST (long, yynewStack), YY_CAST (long, yyk)));
yyflag = yyglrReduce (yystackp, yynewStack,
*yyconflicts,
yyimmediate[*yyconflicts], result, width_type, width_value);
if (yyflag == yyok)
YYCHK (yyprocessOneStack (yystackp, yynewStack,
yyposn, result, width_type, width_value));
else if (yyflag == yyerr)
{
YY_DPRINTF ((stderr, "Stack %ld dies.\n", YY_CAST (long, yynewStack)));
yymarkStackDeleted (yystackp, yynewStack);
}
else
return yyflag;
}
if (yyisShiftAction (yyaction))
break;
else if (yyisErrorAction (yyaction))
{
YY_DPRINTF ((stderr, "Stack %ld dies.\n", YY_CAST (long, yyk)));
yymarkStackDeleted (yystackp, yyk);
break;
}
else
{
YYRESULTTAG yyflag = yyglrReduce (yystackp, yyk, -yyaction,
yyimmediate[-yyaction], result, width_type, width_value);
if (yyflag == yyerr)
{
YY_DPRINTF ((stderr,
"Stack %ld dies "
"(predicate failure or explicit user error).\n",
YY_CAST (long, yyk)));
yymarkStackDeleted (yystackp, yyk);
break;
}
else if (yyflag != yyok)
return yyflag;
}
}
}
return yyok;
}
static void
yyreportSyntaxError (yyGLRStack* yystackp, int &result, std::string &width_type, int &width_value)
{
if (yystackp->yyerrState != 0)
return;
yyerror (result, width_type, width_value, YY_("syntax error"));
yynerrs += 1;
}
/* Recover from a syntax error on *YYSTACKP, assuming that *YYSTACKP->YYTOKENP,
yylval, and yylloc are the syntactic category, semantic value, and location
of the lookahead. */
static void
yyrecoverSyntaxError (yyGLRStack* yystackp, int &result, std::string &width_type, int &width_value)
{
if (yystackp->yyerrState == 3)
/* We just shifted the error token and (perhaps) took some
reductions. Skip tokens until we can proceed. */
while (yytrue)
{
yysymbol_kind_t yytoken;
int yyj;
if (yychar == COMMAND_EOF)
yyFail (yystackp, result, width_type, width_value, YY_NULLPTR);
if (yychar != COMMAND_EMPTY)
{
/* We throw away the lookahead, but the error range
of the shifted error token must take it into account. */
yyGLRState *yys = yystackp->yytops.yystates[0];
yyGLRStackItem yyerror_range[3];
yyerror_range[1].yystate.yyloc = yys->yyloc;
yyerror_range[2].yystate.yyloc = yylloc;
YYLLOC_DEFAULT ((yys->yyloc), yyerror_range, 2);
yytoken = YYTRANSLATE (yychar);
yydestruct ("Error: discarding",
yytoken, &yylval, &yylloc, result, width_type, width_value);
yychar = COMMAND_EMPTY;
}
yytoken = yygetToken (&yychar, result, width_type, width_value);
yyj = yypact[yystackp->yytops.yystates[0]->yylrState];
if (yypact_value_is_default (yyj))
return;
yyj += yytoken;
if (yyj < 0 || YYLAST < yyj || yycheck[yyj] != yytoken)
{
if (yydefact[yystackp->yytops.yystates[0]->yylrState] != 0)
return;
}
else if (! yytable_value_is_error (yytable[yyj]))
return;
}
/* Reduce to one stack. */
{
YYPTRDIFF_T yyk;
for (yyk = 0; yyk < yystackp->yytops.yysize; yyk += 1)
if (yystackp->yytops.yystates[yyk] != YY_NULLPTR)
break;
if (yyk >= yystackp->yytops.yysize)
yyFail (yystackp, result, width_type, width_value, YY_NULLPTR);
for (yyk += 1; yyk < yystackp->yytops.yysize; yyk += 1)
yymarkStackDeleted (yystackp, yyk);
yyremoveDeletes (yystackp);
yycompressStack (yystackp);
}
/* Pop stack until we find a state that shifts the error token. */
yystackp->yyerrState = 3;
while (yystackp->yytops.yystates[0] != YY_NULLPTR)
{
yyGLRState *yys = yystackp->yytops.yystates[0];
int yyj = yypact[yys->yylrState];
if (! yypact_value_is_default (yyj))
{
yyj += YYSYMBOL_YYerror;
if (0 <= yyj && yyj <= YYLAST && yycheck[yyj] == YYSYMBOL_YYerror
&& yyisShiftAction (yytable[yyj]))
{
/* Shift the error token. */
int yyaction = yytable[yyj];
/* First adjust its location.*/
YYLTYPE yyerrloc;
yystackp->yyerror_range[2].yystate.yyloc = yylloc;
YYLLOC_DEFAULT (yyerrloc, (yystackp->yyerror_range), 2);
YY_SYMBOL_PRINT ("Shifting", yy_accessing_symbol (yyaction),
&yylval, &yyerrloc);
yyglrShift (yystackp, 0, yyaction,
yys->yyposn, &yylval, &yyerrloc);
yys = yystackp->yytops.yystates[0];
break;
}
}
yystackp->yyerror_range[1].yystate.yyloc = yys->yyloc;
if (yys->yypred != YY_NULLPTR)
yydestroyGLRState ("Error: popping", yys, result, width_type, width_value);
yystackp->yytops.yystates[0] = yys->yypred;
yystackp->yynextFree -= 1;
yystackp->yyspaceLeft += 1;
}
if (yystackp->yytops.yystates[0] == YY_NULLPTR)
yyFail (yystackp, result, width_type, width_value, YY_NULLPTR);
}
#define YYCHK1(YYE) \
do { \
switch (YYE) { \
case yyok: break; \
case yyabort: goto yyabortlab; \
case yyaccept: goto yyacceptlab; \
case yyerr: goto yyuser_error; \
case yynomem: goto yyexhaustedlab; \
default: goto yybuglab; \
} \
} while (0)
/*----------.
| yyparse. |
`----------*/
int
yyparse (int &result, std::string &width_type, int &width_value)
{
int yyresult;
yyGLRStack yystack;
yyGLRStack* const yystackp = &yystack;
YYPTRDIFF_T yyposn;
YY_DPRINTF ((stderr, "Starting parse\n"));
yychar = COMMAND_EMPTY;
yylval = yyval_default;
yylloc = yyloc_default;
if (! yyinitGLRStack (yystackp, YYINITDEPTH))
goto yyexhaustedlab;
switch (YYSETJMP (yystack.yyexception_buffer))
{
case 0: break;
case 1: goto yyabortlab;
case 2: goto yyexhaustedlab;
default: goto yybuglab;
}
yyglrShift (&yystack, 0, 0, 0, &yylval, &yylloc);
yyposn = 0;
while (yytrue)
{
/* For efficiency, we have two loops, the first of which is
specialized to deterministic operation (single stack, no
potential ambiguity). */
/* Standard mode. */
while (yytrue)
{
yy_state_t yystate = yystack.yytops.yystates[0]->yylrState;
YY_DPRINTF ((stderr, "Entering state %d\n", yystate));
if (yystate == YYFINAL)
goto yyacceptlab;
if (yyisDefaultedState (yystate))
{
yyRuleNum yyrule = yydefaultAction (yystate);
if (yyrule == 0)
{
yystack.yyerror_range[1].yystate.yyloc = yylloc;
yyreportSyntaxError (&yystack, result, width_type, width_value);
goto yyuser_error;
}
YYCHK1 (yyglrReduce (&yystack, 0, yyrule, yytrue, result, width_type, width_value));
}
else
{
yysymbol_kind_t yytoken = yygetToken (&yychar, result, width_type, width_value);
const short* yyconflicts;
int yyaction = yygetLRActions (yystate, yytoken, &yyconflicts);
if (*yyconflicts)
/* Enter nondeterministic mode. */
break;
if (yyisShiftAction (yyaction))
{
YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc);
yychar = COMMAND_EMPTY;
yyposn += 1;
yyglrShift (&yystack, 0, yyaction, yyposn, &yylval, &yylloc);
if (0 < yystack.yyerrState)
yystack.yyerrState -= 1;
}
else if (yyisErrorAction (yyaction))
{
yystack.yyerror_range[1].yystate.yyloc = yylloc;
/* Issue an error message unless the scanner already
did. */
if (yychar != COMMAND_error)
yyreportSyntaxError (&yystack, result, width_type, width_value);
goto yyuser_error;
}
else
YYCHK1 (yyglrReduce (&yystack, 0, -yyaction, yytrue, result, width_type, width_value));
}
}
/* Nondeterministic mode. */
while (yytrue)
{
yysymbol_kind_t yytoken_to_shift;
YYPTRDIFF_T yys;
for (yys = 0; yys < yystack.yytops.yysize; yys += 1)
yystackp->yytops.yylookaheadNeeds[yys] = yychar != COMMAND_EMPTY;
/* yyprocessOneStack returns one of three things:
- An error flag. If the caller is yyprocessOneStack, it
immediately returns as well. When the caller is finally
yyparse, it jumps to an error label via YYCHK1.
- yyok, but yyprocessOneStack has invoked yymarkStackDeleted
(&yystack, yys), which sets the top state of yys to NULL. Thus,
yyparse's following invocation of yyremoveDeletes will remove
the stack.
- yyok, when ready to shift a token.
Except in the first case, yyparse will invoke yyremoveDeletes and
then shift the next token onto all remaining stacks. This
synchronization of the shift (that is, after all preceding
reductions on all stacks) helps prevent double destructor calls
on yylval in the event of memory exhaustion. */
for (yys = 0; yys < yystack.yytops.yysize; yys += 1)
YYCHK1 (yyprocessOneStack (&yystack, yys, yyposn, result, width_type, width_value));
yyremoveDeletes (&yystack);
if (yystack.yytops.yysize == 0)
{
yyundeleteLastStack (&yystack);
if (yystack.yytops.yysize == 0)
yyFail (&yystack, result, width_type, width_value, YY_("syntax error"));
YYCHK1 (yyresolveStack (&yystack, result, width_type, width_value));
YY_DPRINTF ((stderr, "Returning to deterministic operation.\n"));
yystack.yyerror_range[1].yystate.yyloc = yylloc;
yyreportSyntaxError (&yystack, result, width_type, width_value);
goto yyuser_error;
}
/* If any yyglrShift call fails, it will fail after shifting. Thus,
a copy of yylval will already be on stack 0 in the event of a
failure in the following loop. Thus, yychar is set to COMMAND_EMPTY
before the loop to make sure the user destructor for yylval isn't
called twice. */
yytoken_to_shift = YYTRANSLATE (yychar);
yychar = COMMAND_EMPTY;
yyposn += 1;
for (yys = 0; yys < yystack.yytops.yysize; yys += 1)
{
yy_state_t yystate = yystack.yytops.yystates[yys]->yylrState;
const short* yyconflicts;
int yyaction = yygetLRActions (yystate, yytoken_to_shift,
&yyconflicts);
/* Note that yyconflicts were handled by yyprocessOneStack. */
YY_DPRINTF ((stderr, "On stack %ld, ", YY_CAST (long, yys)));
YY_SYMBOL_PRINT ("shifting", yytoken_to_shift, &yylval, &yylloc);
yyglrShift (&yystack, yys, yyaction, yyposn,
&yylval, &yylloc);
YY_DPRINTF ((stderr, "Stack %ld now in state %d\n",
YY_CAST (long, yys),
yystack.yytops.yystates[yys]->yylrState));
}
if (yystack.yytops.yysize == 1)
{
YYCHK1 (yyresolveStack (&yystack, result, width_type, width_value));
YY_DPRINTF ((stderr, "Returning to deterministic operation.\n"));
yycompressStack (&yystack);
break;
}
}
continue;
yyuser_error:
yyrecoverSyntaxError (&yystack, result, width_type, width_value);
yyposn = yystack.yytops.yystates[0]->yyposn;
}
yyacceptlab:
yyresult = 0;
goto yyreturnlab;
yybuglab:
YY_ASSERT (yyfalse);
goto yyabortlab;
yyabortlab:
yyresult = 1;
goto yyreturnlab;
yyexhaustedlab:
yyerror (result, width_type, width_value, YY_("memory exhausted"));
yyresult = 2;
goto yyreturnlab;
yyreturnlab:
if (yychar != COMMAND_EMPTY)
yydestruct ("Cleanup: discarding lookahead",
YYTRANSLATE (yychar), &yylval, &yylloc, result, width_type, width_value);
/* If the stack is well-formed, pop the stack until it is empty,
destroying its entries as we go. But free the stack regardless
of whether it is well-formed. */
if (yystack.yyitems)
{
yyGLRState** yystates = yystack.yytops.yystates;
if (yystates)
{
YYPTRDIFF_T yysize = yystack.yytops.yysize;
YYPTRDIFF_T yyk;
for (yyk = 0; yyk < yysize; yyk += 1)
if (yystates[yyk])
{
while (yystates[yyk])
{
yyGLRState *yys = yystates[yyk];
yystack.yyerror_range[1].yystate.yyloc = yys->yyloc;
if (yys->yypred != YY_NULLPTR)
yydestroyGLRState ("Cleanup: popping", yys, result, width_type, width_value);
yystates[yyk] = yys->yypred;
yystack.yynextFree -= 1;
yystack.yyspaceLeft += 1;
}
break;
}
}
yyfreeGLRStack (&yystack);
}
return yyresult;
}
/* DEBUGGING ONLY */
#if COMMAND_DEBUG
/* Print *YYS and its predecessors. */
static void
yy_yypstack (yyGLRState* yys)
{
if (yys->yypred)
{
yy_yypstack (yys->yypred);
YY_FPRINTF ((stderr, " -> "));
}
YY_FPRINTF ((stderr, "%d@%ld", yys->yylrState, YY_CAST (long, yys->yyposn)));
}
/* Print YYS (possibly NULL) and its predecessors. */
static void
yypstates (yyGLRState* yys)
{
if (yys == YY_NULLPTR)
YY_FPRINTF ((stderr, "<null>"));
else
yy_yypstack (yys);
YY_FPRINTF ((stderr, "\n"));
}
/* Print the stack #YYK. */
static void
yypstack (yyGLRStack* yystackp, YYPTRDIFF_T yyk)
{
yypstates (yystackp->yytops.yystates[yyk]);
}
/* Print all the stacks. */
static void
yypdumpstack (yyGLRStack* yystackp)
{
#define YYINDEX(YYX) \
YY_CAST (long, \
((YYX) \
? YY_REINTERPRET_CAST (yyGLRStackItem*, (YYX)) - yystackp->yyitems \
: -1))
yyGLRStackItem* yyp;
for (yyp = yystackp->yyitems; yyp < yystackp->yynextFree; yyp += 1)
{
YY_FPRINTF ((stderr, "%3ld. ",
YY_CAST (long, yyp - yystackp->yyitems)));
if (*YY_REINTERPRET_CAST (yybool *, yyp))
{
YY_ASSERT (yyp->yystate.yyisState);
YY_ASSERT (yyp->yyoption.yyisState);
YY_FPRINTF ((stderr, "Res: %d, LR State: %d, posn: %ld, pred: %ld",
yyp->yystate.yyresolved, yyp->yystate.yylrState,
YY_CAST (long, yyp->yystate.yyposn),
YYINDEX (yyp->yystate.yypred)));
if (! yyp->yystate.yyresolved)
YY_FPRINTF ((stderr, ", firstVal: %ld",
YYINDEX (yyp->yystate.yysemantics.yyfirstVal)));
}
else
{
YY_ASSERT (!yyp->yystate.yyisState);
YY_ASSERT (!yyp->yyoption.yyisState);
YY_FPRINTF ((stderr, "Option. rule: %d, state: %ld, next: %ld",
yyp->yyoption.yyrule - 1,
YYINDEX (yyp->yyoption.yystate),
YYINDEX (yyp->yyoption.yynext)));
}
YY_FPRINTF ((stderr, "\n"));
}
YY_FPRINTF ((stderr, "Tops:"));
{
YYPTRDIFF_T yyi;
for (yyi = 0; yyi < yystackp->yytops.yysize; yyi += 1)
YY_FPRINTF ((stderr, "%ld: %ld; ", YY_CAST (long, yyi),
YYINDEX (yystackp->yytops.yystates[yyi])));
YY_FPRINTF ((stderr, "\n"));
}
#undef YYINDEX
}
#endif
#undef yylval
#undef yychar
#undef yynerrs
#undef yylloc
/* Substitute the variable and function names. */
#define yyparse command_parse
#define yylex command_lex
#define yyerror command_error
#define yylval command_lval
#define yychar command_char
#define yydebug command_debug
#define yynerrs command_nerrs
#define yylloc command_lloc
#line 107 "command_parser.y"
void yyerror(int &, std::string &, int &, char const*){
//std::cerr<<"Syntax Error: "<< msg << " on line " <<command_lineno << std::endl;
std::cout<<"Wrong number of inputs. Please execute treewidzard --help for more information."<<std::endl;
// error printing disabled, it is handeled in main.cpp
}
|
#ifndef KALMAN_FILTER_TOOLBOX_H
#define KALMAN_FILTER_TOOLBOX_H
#include <opencv2/video/tracking.hpp>
#include "dataType.h"
using namespace std;
using namespace cv;
class KalmanFilterToolBox
{
public:
KalmanFilterToolBox(int ndim, double dt, const DETECTBOX &measurement);
~KalmanFilterToolBox();
static const double chi2inv95[10];
void predict(float errorCoefficient);
void update(const DETECTBOX &measurement);
Eigen::Matrix<float, 1, -1> mahalanobis_distance(const std::vector<DETECTBOX> &measurements, bool only_position);
cv::Mat state;
private:
float _std_weight_position;
float _std_weight_velocity;
cv::Mat _std;
cv::KalmanFilter *kfilter;
};
#endif
|
/*******************************************************************************
* Cristian Alexandrescu *
* 2163013577ba2bc237f22b3f4d006856 *
* 11a4bb2c77aca6a9927b85f259d9af10db791ce5cf884bb31e7f7a889d4fb385 *
* bc9a53289baf23d369484f5343ed5d6c *
*******************************************************************************/
/* Problem 641 - Do the Untwist */
/*
ciphercode[i] = (plaincode[ki mod n] - i) mod 28 ==>
(ciphercode[i] + i) mod 28 = (plaincode[ki mod n]) mod 28
*/
#include <iostream>
#include <string>
using namespace std;
inline int CharToIntCode(char c) {
if (c == '_')
return 0;
else if (c == '.')
return 27;
else
return c - 'a' + 1;
}
inline char IntCodeToChar(int nN) {
if (nN == 0)
return '_';
else if (nN == 27)
return '.';
else
return 'a' + nN - 1;
}
int main() {
for (int nK; (cin >> nK), nK; ) {
string oCiphertext;
cin >> oCiphertext;
string oPlainText(oCiphertext);
for (int nIndex = 0, nLen = static_cast<int>(oCiphertext.size()); nIndex < nLen; nIndex++)
oPlainText[(nK * nIndex) % nLen] = IntCodeToChar((CharToIntCode(oCiphertext[nIndex]) + nIndex) % 28);
cout << oPlainText << endl;
}
return 0;
}
|
#ifndef GRAVITY_H
#define GRAVITY_H
#include<QVector3D>
#include<rigidbody.h>
class Gravity
{
public:
Gravity(const QVector3D &m_gravity);
private:
QVector3D gravity;
public:
virtual void updateForce(RigidBody *body, float duration);
};
#endif // GRAVITY_H
|
#pragma once
#include <string>
#include <distant/scoped_handle.hpp>
namespace distant::synch
{
class event
{
public:
/// @brief Create an event object with a randomly-generated name.
/// @remark The event is constructed in an unsignaled state.
/// @exception Throws a winapi_error in the event that an API call fails.
explicit event();
/// @brief Create a system-wide event object of the given name.
/// @remark The event is constructed in an unsignaled state.
/// @exception Throws a winapi_error in the event that an API call fails.
explicit event(const std::wstring& name);
/// @brief Get the handle to the event.
/// @return its handle.
const kernel_handle& handle() const noexcept;
/// @brief Get the name of the event.
/// @return the event's name.
const std::wstring& name() const noexcept;
private:
kernel_handle handle_;
const std::wstring name_;
};
} // namespace distant::synch
|
#ifndef FlopBanks_H
#define FlopBanks_H
#pragma once
#include "..\..\AppTurnTree\Source\TreeBanks.h"
#include "..\..\..\..\Util\TemplateFileRec.h"
#include "..\..\..\..\Util\FileSwapping.h"
#include "..\..\..\..\Util\FileRec64.h"
#include "..\..\..\..\NeuroNet\NeuroNet.h"
#include "FlopTree.h"
//---------------------------------------------------------------------------------------------------------------------------------------------------
class clFlopBankUnit
{
public:
inline int WriteFile(int handle) { _dat.WriteFile(handle); WriteVectFile(handle, _ev[0]); WriteVectFile(handle, _ev[1]); return _root.WriteFile(handle); }
inline int ReadFile(int handle) { _dat.ReadFile(handle); ReadVectFile(handle, _ev[0]); ReadVectFile(handle, _ev[1]); return _root.ReadFile(handle); }
inline size_t SizeInFile() { return _dat.SizeInFile() + SizeVectFile(_ev[0]) + SizeVectFile(_ev[1]) + _root.SizeInFile(); }
//void CalcRootNode(int cnCalc, tpUnfindTree *ut);
void CalcRootEV(int cnCalc, clLayersBPNet *net);
//bool CompactTree() { return _root._tree.CutTree(ACT_DELRIVER); }
clStreetDat _dat;
vector <float> _ev[2];
clRootFlopTree _root;
};
class clFlopBank
{
public:
void Create(char *path, int cnRecord = 0);
bool IsOpen() { return _fileUnit.IsOpen(); }
bool OpenA(char *path, bool onlyRead);
int NearestClsNb(clStreetDat &dat, tpFloat &dist);
clFlopBankUnit *LockBankUnit(int nb)
{
clFlopBankUnit * ptr = _fileUnit.LockRecord(nb);
if (ptr->_root._tree.GetSit().GetLastAct()->_dis._act != ACT_DELFLOP)
ErrMessage("Error ", "bad sit");
ptr->_root.CalcIndex();
return ptr;
}
void UnLockBankUnit(int nb, clFlopBankUnit *unit = NULL) { _fileUnit.UnLockRecord(nb); }
//int FillEV(clRootStreetTree *root, int nbHero, vector <float> &ev);
int FillEV(clRootFlopTree *root, int nbHero, vector <float> &ev, clLayersBPNet *_net);
//int FillEVQ(clRootStreetTree *root, int nbHero, vector <float> &ev, clLayersBPNet &_net);
bool GetTreeForRoot(clRoot &root, tpUnfindTree *ptr);
//bool GetTreeForRoot(clRoot &root);
//bool FindTreeForSit(clRoot &hs0);*/
void InitFastTree();
int FastSearch(clStreetDat &dat, double &dist);
//bool CreateClsForAdd(vector <vector <int>> &cls);
//bool SetRegimNeuro(bool reg);
clFileSwap <clFlopBankUnit> _fileUnit;
clBankFastTree _fastTree;
vector <clStreetDat> _arr;
tpUnfindTree _uf;
clLayersBPNet _net;
//bool _regNet;
};
extern clFlopBank glBankFlop;
//---------------------------------------------------------------------------------------------------------------------------------------------------
#endif
|
#include "loginwindow.h"
#include "mainwindow.h"
#include "ui_loginwindow.h"
void processLoginData(QString in);
LoginWindow::LoginWindow(QWidget *parent) : QDialog(parent), ui(new Ui::LoginWindow)
{
ui->setupUi(this);
//---------------------------------------------- Window Customization
this->setWindowTitle("MIT WorkLogger");
this->setWindowIcon(QIcon(":/resources/logo.png"));
this->setWindowFlags(Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint);
//---------------------------------------------- Program Stylesheet
QFile File(":/style/login.css");
File.open(QIODevice::ReadOnly);
QString style( File.readAll() );
this->setStyleSheet(style);
//--------------------------------------------- Logo Setting
QLabel label;
QPixmap pixmap(":/resources/icons/fulllogo.jpg");
ui->LogoLabel->setPixmap(pixmap);
ui->LogoLabel->setMask(pixmap.mask());
int w = ui->LogoLabel->width();
int h = ui->LogoLabel->height();
// set a scaled pixmap to a w x h window keeping its aspect ratio
ui->LogoLabel->setPixmap( pixmap.scaled(w,h,Qt::KeepAspectRatio) );
//----------------------------------------------------------------------
}
LoginWindow::~LoginWindow()
{
delete ui;
}
void LoginWindow::on_pushButton_clicked()
{
this->enteredUsername = ui->usernameLineEdit->text();
this->enteredPassword = ui->passwordLabel->text();
this->getUserInfo( this->enteredUsername , this->enteredPassword );
// this->close();
// MainWindow* w = new MainWindow(); //Select the default Class for the startup window
// w->show();
// this->hide();
}
void LoginWindow::getUserInfo(QString username, QString password)
{
databaseHandler* DB = new databaseHandler(this);
qDebug() << "login clicked started \n" ;
DB->readData( "employees" , &processLoginData );
}
void processLoginData(QString in)
{
qDebug() << "Fetched User Data: \n " << in << "End: \n " ;
QJsonDocument doc = QJsonDocument::fromJson(in.toUtf8());
QJsonObject json = doc.object();
QJsonArray jsonArray;
foreach(const QString& key, json.keys())
{
qDebug() << "KEY: " << key << "\n";
QJsonObject Obj = json.value(key).toObject();
jsonArray.push_back(Obj);
}
// TO ACCESS YOUR ARRAY
for(int i = 0; i<jsonArray.size(); i++)
{
QJsonObject child = jsonArray.at(i).toObject();
qDebug() << "child: " << child << "\n";
qDebug() << "Key: " << json.keys()[0] << "\n";
qDebug() << "name: " << child.value("name").toString() << "\n";
qDebug() << "title: " << child.value("title").toString() << "\n";
qDebug() << "mainteam: " << child.value("mainteam").toString() << "\n";
qDebug() << "username: " << child.value("username").toString() << "\n";
qDebug() << "password: " << child.value("password").toString() << "\n";
qDebug() << "userrole: " << child.value("userrole").toString() << "\n";
}
if(true)
{
// this.done(QDialog::Accepted);
qDebug() << "username: " << this->enteredUsername << "\n";
}
else
{
}
}
|
#include <iostream>
using namespace std;
void Swap(int& a, int& b)
{
int temp = b;
b = a;
a = temp;
}
void Swap(int* a, int* b)
{
int temp = *b;
*b = *a;
*a = temp;
}
int* FindMax(int arr[], int num)
{
int* max = arr;
for (int i = 0; i < num; ++i)
{
if (arr[i] > *max)
{
*max = arr[i];
}
}
return max;
}
//Swap two variables in a function called swap.
//Make two versions of it -> void swap(int&a , int& b); void swap(int* a, int* b);
void PointerQuestion1()
{
int a = 10;
int b = 30;
std::cout << "Before Swapping a = 10 & b = 30 :" << a <<" "<< b << std::endl;
Swap(&a, &b);
std::cout << "After Swapping a = 10 & b = 30 by reference: " << a << " " << b << std::endl;
Swap(a, b);
std::cout << "After Swapping a = 10 & b = 30 by pointers: " << a <<" "<< b << std::endl;
}
//Write a C++ program to find the max of an integral data set.
//The program will ask the user to input the number of data values in the set and each value.
//The program prints on screen a pointer that points to the max value.
void PointerQuestion2()
{
int size;
int *dataSet = nullptr;
int *max = nullptr;
cout << "Enter size of the data set: ";
cin >> size;
if (size)
{
dataSet = (int*)malloc(size * sizeof(int));
cout << endl;
for (int i = 0; i < size; ++i)
{
cout << "Enter value " << i + 1 << " : ";
cin >> dataSet[i];
cout << endl;
}
max = FindMax(dataSet, size);
}
else
{
cout << "Size invalid \n";
}
cout << "Max value of this data set is : " << *max;
free(dataSet);
}
int main()
{
//PointerQuestion1();
PointerQuestion2();
return 0;
}
|
#include <iostream>
#define N 10
using namespace std;
void shellSort(int* arr, int n) {
for (int gap = n / 2; gap > 0; gap /= 2) {
for (int i = gap; i < n; ++i) {
int current = arr[i];
int j = i;
while (j >= gap && arr[j - gap] > current) {
arr[j] = arr[j - gap];
j = j - gap;
}
arr[j] = current;
}
}
}
int main() {
int arr[N] = { 33, 12, 36, 10, 20, 99, 10, 3, 50, 49 };
cout << "정렬 전 : ";
for (int d : arr)
cout << d << ' ';
cout << endl;
shellSort(arr, N);
cout << "정렬 후 : ";
for (int d : arr)
cout << d << ' ';
cout << endl;
}
|
//! Bismillahi-Rahamanirahim.
/** ========================================**
** @Author: Md. Abu Farhad ( RUET, CSE'15)
** @Category:
/** ========================================**/
#include<bits/stdc++.h>
#include<stdio.h>
using namespace std;
#define ll long long
#define scl(n) cin>>n;
#define scc(c) cin>>c;
#define fr(i,n) for (ll i=0;i<n;i++)
#define fr1(i,n) for(ll i=1;i<=n;i++)
#define pfl(x) printf("%lld\n",x)
#define pb push_back
#define debug cout<<"I am here"<<endl;
#define pno cout<<"NO"<<endl
#define pys cout<<"YES"<<endl
#define l(s) s.size()
#define asort(a) sort(a,a+n)
#define all(x) (x).begin(), (x).end()
#define dsort(a) sort(a,a+n,greater<int>())
#define vasort(v) sort(v.begin(), v.end());
#define vdsort(v) sort(v.begin(), v.end(),greater<int>());
#define uniquee(x) x.erase(unique(x.begin(), x.end()),x.end())
#define pn cout<<endl;
#define md 1000000007
#define inf 1e18
#define ps cout<<" ";
#define Pi acos(-1.0)
#define pr pair<ll, ll>
#define ff first
#define ss second
#define mem(a,i) memset(a, i, sizeof(a))
#define tcas(i,t) for(ll i=1;i<=t;i++)
#define pcas(i) cout<<"Case "<<i<<": "<<"\n";
#define fast ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL)
#define N 100006
bool isprime[N];
vector<ll>prime;
void sieve()
{
ll i, j;
isprime[1]=1;
for(i=4; i<=N; i+=2)isprime[i]=1;
for(i=3; i*i<=N; i++)
{
if( ! isprime[i] )
{
for(j=i*i ; j<=N ; j+=i)isprime[j]=1;
}
}
//prime.pb(2);
//fr1(i, N)if(! isprime[i] )prime.pb(i);
}
int main()
{
fast;
ll t;
sieve();
ll m,n,b,c,d,i,j,k,x,y,z,l,q,r;
string s,s1, s2, s3, s4;
//fr(i, 20)cout<<prime[i]<<" "; pn;
ll cnt=0,ans=0,sum=0;
cin>>x>>y>>k;
for(i=x; i<=y; i++)
{
if(!isprime[i] and k>0 )ans=i, cout<<i<<" ", k--;
//if(k==0)ans=i;
}
if(k)ans=-1;
cout<<ans<<endl;
return 0;
}
///Before submit=>
/// *check for integer overflow,array bounds
/// *check for n=1
|
#include <Audio.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include <SerialFlash.h>
// 1010LevelMeter - target: the 1010music Euroshield with the PJRC Teensy 3.2
//
// This sketch demonstrates a simple level meter using the IN 1/2 as audio inputs
// and the 4 LEDs as a bar graph.
//
// This code is in the public domain.
AudioInputI2S audioInput; // audio shield: mic or line-in
AudioAnalyzePeak peak_L;
AudioAnalyzePeak peak_R;
AudioOutputI2S audioOutput; // audio shield: headphones & line-out
AudioConnection c1(audioInput,0,peak_L,0);
AudioConnection c2(audioInput,1,peak_R,0);
AudioConnection c3(audioInput,0,audioOutput,0);
AudioConnection c4(audioInput,1,audioOutput,1);
AudioControlSGTL5000 codec;
#define ledPinCount 4
int ledPins[ledPinCount] = { 3, 4, 5, 6 };
void setup()
{
// Audio connections require memory to work. For more
// detailed information, see the MemoryAndCpuUsage example
AudioMemory(12);
// Enable the audio shield, select input, and enable output
codec.enable();
codec.inputSelect(AUDIO_INPUT_LINEIN);
codec.volume(0.82);
codec.adcHighPassFilterDisable();
codec.lineInLevel(0,0);
for (int i = 0; i < ledPinCount; i++)
pinMode(ledPins[i], OUTPUT);
}
elapsedMillis fps;
void loop()
{
if(fps > 24)
{
if (peak_L.available() && peak_R.available())
{
float peakValueL = peak_L.read();
float peakValueR = peak_R.read();
float peakValue = peakValueL;
if (peakValue < peakValueR)
peakValue = peakValueR;
for (int i = 0; i < ledPinCount; i++)
{
float levelThreshold = float(i + 1) * 0.2;
if (levelThreshold < peakValue)
digitalWrite(ledPins[i], HIGH); // turn the LED on (HIGH is the voltage level)
else
digitalWrite(ledPins[i], LOW); // turn the LED on (HIGH is the voltage level)
}
fps=0;
}
}
}
|
#include <string.h>
#include "logger.h"
static const int MAX_LOG_FILE_SIZE = 1024 * 1024 * 10; // 滚动日志的最大大小
static const int MAX_LOG_FILE_COUNT = 10; // 滚动日志的最大份数
static char g_szLogBuff[512];
static char g_szLogBuffFuncionLine[1024];
Logger* Logger::m_ins = NULL;
Logger::Logger()
{
m_layout = new log4cpp::PatternLayout();
m_layout->setConversionPattern("%d: %p : %m%n");
m_appender = new log4cpp::RollingFileAppender("RollingFileAppender", "./rollwxb.log",
MAX_LOG_FILE_SIZE, MAX_LOG_FILE_COUNT);
m_appender->setLayout(m_layout);
m_category = &log4cpp::Category::getInstance("Category");
m_category->setAdditivity(false);
m_category->setAppender(m_appender);
m_category->setPriority(log4cpp::Priority::DEBUG);
}
Logger::~Logger()
{
delete m_layout;
delete m_appender;
delete m_category;
}
void Logger::log_debug(const char* file, int line, const char* fmt, ...)
{
memset(g_szLogBuff, 0, sizeof(g_szLogBuff));
va_list vl;
va_start(vl, fmt);
::vsnprintf(g_szLogBuff, sizeof(g_szLogBuff), fmt, vl);
va_end(vl);
memset(g_szLogBuffFuncionLine, 0, sizeof(g_szLogBuffFuncionLine));
snprintf(g_szLogBuffFuncionLine, sizeof(g_szLogBuffFuncionLine),
"[%s:%d]%s", file, line, g_szLogBuff);
m_category->debug(g_szLogBuffFuncionLine);
}
void Logger::log_info(const char* fmt, ...)
{
memset(g_szLogBuff, 0, sizeof(g_szLogBuff));
va_list vl;
va_start(vl, fmt);
vsnprintf(g_szLogBuff, sizeof(g_szLogBuff), fmt, vl);
va_end(vl);
m_category->info(g_szLogBuff);
}
void Logger::log_error(const char* fmt, ...)
{
memset(g_szLogBuff, 0, sizeof(g_szLogBuff));
va_list vl;
va_start(vl, fmt);
vsnprintf(g_szLogBuff, sizeof(g_szLogBuff), fmt, vl);
va_end(vl);
m_category->error(g_szLogBuff);
}
|
// OPini.cpp: implementation of the COPini class.
#include "StdAfx.h"
#include "OPini.h"
COPini::COPini()
{
}
COPini::~COPini()
{
}
BOOL COPini::WriteString(LPCTSTR section, LPCTSTR key, char *stringtoadd, char *filename)
{
return ::WritePrivateProfileString(section,key,stringtoadd,filename);
}
DWORD COPini::ReadString(char *section, char * key, char stringtoread[], char * filename)
{
return ::GetPrivateProfileString(section, key,NULL,stringtoread,MAX_PATH,filename);
}
|
/* Copyright (C) 2015 Willi Menapace <willi.menapace@gmail.com>, Simone Lorengo - All Rights Reserved
* Unauthorized copying of this file, via any medium is strictly prohibited
* Proprietary and confidential
* Written by Willi Menapace <willi.menapace@gmail.com>
*/
#ifndef XBEE_FRAMEABLE_PACKET_INCLUDED
#define XBEE_FRAMEABLE_PACKET_INCLUDED
#include "GlobalDefines.h"
#include "XBeePacket.h"
/**
* Pacchetto contenente un frame ID identificativo
*/
class XBeeFrameablePacket : public XBeePacket {
private:
static const unsigned char FRAME_ID_INDEX;
public:
/**
* Imposta il frame ID del pacchetto
*
* @param frameId il frame ID del pacchetto
*/
void setFrameId(unsigned char frameId);
/**
* Ottiene il frame ID del pacchetto.
* Richiamabile solo se il frame ID e' stato impostato
*
* @return il frame ID del pacchetto
*/
unsigned char getFrameId();
XBeeFrameablePacket();
/**
* Implementa il chaining con il costruttore di copia di XBeePacket
* per permettere alle sottoclassi di usufruire di questa funzionalita'
*/
XBeeFrameablePacket(XBeePacket *packet);
virtual ~XBeeFrameablePacket() {}
};
#endif // XBEE_FRAMEABLE_PACKET_INCLUDED
|
#include "Item.h"
Item::Item(ItemType type, std::string name)
{
this->type = type;
this->size_ = 1;
// Many ifs because we can't switch case with strings
switch(type)
{
case HEAL:
if(name == "civilian-medkit")
{
this->effect = 25;
this->setPixmap(QPixmap(":/img/loot/items/civilian-medkit.png"));
}
else if(name == "military-medkit")
{
this->effect = 50;
this->setPixmap(QPixmap(":/img/loot/items/military-medkit.png"));
}
else if(name == "medical-bottle")
{
this->effect = 10;
this->setPixmap(QPixmap(":/img/loot/items/medical-bottle.png"));
}
break;
case PAINKILLER:
if(name == "pills")
{
this->effect = 15;
this->setPixmap(QPixmap(":/img/loot/items/pills.png"));
}
break;
case VACCINE:
if(name == "syringue")
{
this->effect = 60;
this->setPixmap(QPixmap(":/img/loot/items/syringue.png"));
}
break;
case BACKPACK:
if(name == "city-backpack")
{
this->effect = 8;
this->setPixmap(QPixmap(":/img/loot/backpack/city-backpack.png"));
}
else if(name == "duffelbag")
{
this->effect = 12;
this->setPixmap(QPixmap(":/img/loot/backpack/duffelbag.png"));
}
else if(name == "military-backpack")
{
this->effect = 20;
this->setPixmap(QPixmap(":/img/loot/backpack/military-backpack.png"));
}
break;
}
}
|
/*******************************************************************************
* Cristian Alexandrescu *
* 2163013577ba2bc237f22b3f4d006856 *
* 11a4bb2c77aca6a9927b85f259d9af10db791ce5cf884bb31e7f7a889d4fb385 *
* bc9a53289baf23d369484f5343ed5d6c *
*******************************************************************************/
/* Problem 352 - The Seasonal War */
#include <stdio.h>
#if !defined(ONLINE_JUDGE) && (_MSC_VER >= 1900)
#include <limits.h>
#define gets(a) gets_s(a, INT_MAX)
#endif // !defined(ONLINE_JUDGE) && (_MSC_VER >= 1900)
#define MAX 28
int main() {
char szLine[MAX];
int Case = 1;
while (gets(szLine)) {
int n;
sscanf(szLine, "%d", &n);
char matrix[MAX][MAX];
for (int i = 1; i <= n; i++) {
gets(matrix[i] + 1);
matrix[i][0] = matrix[i][n + 1] = '.';
}
for (int i = 1; i <= n; i++)
matrix[0][i] = matrix[n + 1][i] = '.';
int Sol = 0;
for (int ii = 1; ii <= n; ii++)
for (int jj = 1; jj <= n; jj++)
if (matrix[ii][jj] == '1') {
Sol++;
int qhead, qtail, qi[MAX * MAX], qj[MAX * MAX];
qhead = qtail = 0;
qi[qhead] = ii; qj[qhead] = jj;
matrix[ii][jj] = '0';
for ( ; qhead <= qtail; qhead++) {
//const int di[] = {-1, +1, +0, +0, -1, -1, +1, +1};
//const int dj[] = {+0, +0, -1, +1, +1, -1, +1, -1};
const int di[] = {-1, -1, -1, +0, +0, +1, +1, +1};
const int dj[] = {-1, +0, +1, -1, +1, -1, +0, +1};
for (int k = 0; k < sizeof(di) / sizeof(int); k++) {
int iii = qi[qhead] + di[k];
int jjj = qj[qhead] + dj[k];
if (matrix[iii][jjj] == '1') {
matrix[iii][jjj] = '0';
qi[++qtail] = iii;
qj[qtail] = jjj;
}
}
}
}
printf("Image number %d contains %d war eagles.\n", Case, Sol);
Case++;
}
return 0;
}
|
/***************************************************************************
Copyright (c) 2020 Philip Fortier
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
***************************************************************************/
#include "stdafx.h"
#include "Disassembler.h"
#include "DisassembleHelper.h"
#include "scii.h"
#include "AppState.h"
#include "OutputCodeHelper.h"
#include "PMachine.h"
#include "Vocab000.h"
using namespace std;
#define STATE_CALCBRANCHES 0
#define STATE_OUTPUT 1
const char InvalidLookupError[] = "LOOKUP_ERROR";
void _GetVarType(std::ostream &out, Opcode bOpcode, uint16_t wIndex, IObjectFileScriptLookups *pOFLookups)
{
// This is a 0-127 opcode.
// Use the lowest two bits to determine the var type
switch (static_cast<BYTE>(bOpcode)& 0x03)
{
case 0:
// Get the global's name if possible
if (pOFLookups)
{
out << pOFLookups->ReverseLookupGlobalVariableName(wIndex);
}
else
{
out << _GetGlobalVariableName(wIndex);
}
break;
case 1:
out << _GetLocalVariableName(wIndex, 0xffff);
break;
case 2:
out << _GetTempVariableName(wIndex);
break;
case 3:
if (wIndex == 0)
{
// parameter 0 is the count of parameters.
out << "paramTotal";
}
else
{
out << _GetParamVariableName(wIndex);
}
break;
}
}
int GetOperandSize(BYTE bOpcode, OperandType operandType, const uint8_t *pNext)
{
int cIncr = 0;
switch (operandType)
{
case otEMPTY:
cIncr = 0;
break;
case otVAR:
case otPVAR:
case otCLASS:
case otPROP:
case otSTRING:
case otSAID:
case otKERNEL:
case otLABEL:
case otPUBPROC:
case otINT:
case otUINT:
case otOFFS:
cIncr = (bOpcode & 1) ? 1 : 2;
break;
case otINT16:
case otUINT16:
cIncr = 2;
break;
case otINT8:
case otUINT8:
cIncr = 1;
break;
case otDEBUGSTRING:
{
// file name
const char *psz = reinterpret_cast<const char *>(pNext);
cIncr += lstrlen(psz) + 1; // TODO: Bound this somehow
}
break;
default:
assert(false && "Unknown operand type");
break;
}
return cIncr;
}
// This really needs a re-working, it should not be responsible for outputting text.
void DisassembleCode(SCIVersion version, std::ostream &out, ICompiledScriptLookups *pLookups, IObjectFileScriptLookups *pOFLookups, const ICompiledScriptSpecificLookups *pScriptThings, const ILookupPropertyName *pPropertyNames, const BYTE *pBegin, const BYTE *pEnd, uint16_t wBaseOffset, AnalyzeInstructionPtr analyzeInstruction)
{
try
{
set<uint16_t> codeLabelOffsets; // Keep track of places that are branched to.
for (int state = 0; state < 2; state++)
{
const BYTE *pCur = pBegin;
uint16_t wOffset = wBaseOffset;
auto currentLabelOffset = codeLabelOffsets.begin(); // for STATE_CALCBRANCHES
while (pCur < pEnd) // Possibility of read AVs here, but we catch exceptions.
{
BYTE bRawOpcode = *pCur;
Opcode bOpcode = RawToOpcode(version, bRawOpcode);
assert(bOpcode <= Opcode::LastOne);
const char *pszOpcode = OpcodeToName(bOpcode, 0); // Passing zero here is ok, since this code will never show an LEAI instruction.
bool bByte = (*pCur) & 1; // Is this a "byte" opcode or a "word" opcode.
bool fDone = false;
char szBuf[50];
size_t cchBufLimit = 30;
assert(cchBufLimit < ARRAYSIZE(szBuf));
if (state == STATE_OUTPUT)
{
if ((currentLabelOffset != codeLabelOffsets.end()) && (*currentLabelOffset == wOffset))
{
// We're at label.
out << endl << " code_" << setw(4) << setfill('0') << wOffset << endl;
++currentLabelOffset;
}
out << " " << setw(4) << setfill('0') << wOffset << ":";
int indent = 22;
const BYTE *pCurTemp = pCur; // skip past opcode
for (int i = -1; i < 3; i++)
{
int cIncr = (i == -1) ? 1 : GetOperandSize(bRawOpcode, GetOperandTypes(version, bOpcode)[i], pCur + 1);
if (cIncr == 0)
{
break;
}
else
{
uint16_t wOperandTemp = (cIncr == 2) ? *((uint16_t*)pCurTemp) : *pCurTemp;
out << setw((cIncr == 1) ? 2 : 4);
out << setfill('0') << wOperandTemp << " ";
pCurTemp += cIncr;
indent -= (cIncr == 1) ? 3 : 5; // How many chars were written...
}
}
assert(indent > 0);
out << setw(indent) << setfill(' ') << pszOpcode << " "; // Indent x chars, and print opcode
}
pCur++; // skip past opcode
wOffset++;
uint16_t wOperandStart = wOffset;
if (state == STATE_CALCBRANCHES)
{
// Keep track of the targets of branch instructions
if ((bOpcode == Opcode::BNT) || (bOpcode == Opcode::BT) || (bOpcode == Opcode::JMP))
{
// This is a branch instruction. Figure out the offset.
// The relative offset is either a byte or word, and is calculated post instruction
// (hence we add 1 or 2 to our calculation)
codeLabelOffsets.insert(CalcOffset(version, wOperandStart, (bByte ? ((uint16_t)*pCur) : (*((uint16_t*)pCur))), bByte, bRawOpcode));
}
}
uint16_t wOperandsRaw[3];
uint16_t wOperands[3];
for (int i = 0; !fDone && i < 3; i++)
{
szBuf[0] = 0;
int cIncr = GetOperandSize(bRawOpcode, GetOperandTypes(version, bOpcode)[i], pCur);
if (cIncr == 0)
{
break;
}
if (state == STATE_OUTPUT)
{
wOperandsRaw[i] = (cIncr == 2) ? *((uint16_t*)pCur) : *pCur;
wOperands[i] = wOperandsRaw[i];
switch (GetOperandTypes(version, bOpcode)[i])
{
case otINT:
case otUINT:
case otINT16:
case otINT8:
case otUINT8:
case otUINT16:
case otPVAR:
out << wOperands[i];
break;
case otKERNEL:
out << pLookups->LookupKernelName(wOperands[i]);
break;
case otPUBPROC:
out << "procedure_" << setw(4) << setfill('0') << wOperands[i];
break;
case otSAID:
out << "said_" << setw(4) << setfill('0') << wOperands[i];
break;
case otOFFS:
// This is a bit of a hack here. We're making the assumption that a otOFFS parameter
// is the one and only parameter for this opcode. CalcOffset makes this assumption
// in order to calculate the offset.
assert(GetOperandTypes(version, bOpcode)[i + 1] == otEMPTY);
if (version.lofsaOpcodeIsAbsolute)
{
wOperands[i] = wOperandsRaw[i]; // Unnecessary, but reinforces the point.
}
else
{
wOperands[i] = CalcOffset(version, wOperandStart, wOperandsRaw[i], bByte, bRawOpcode);
}
out << "$" << setw(4) << setfill('0') << wOperands[i];
break;
case otEMPTY:
break;
case otPROP:
// This value is an offset from the beginning of this object's species
// So, get the species, and then divide this value by 2, and use it as an index into its
// selector thang.
//
if (pPropertyNames)
{
out << pPropertyNames->LookupPropertyName(pLookups, wOperands[i]);
}
else
{
out << " // (property opcode in procedure)";
}
break;
case otCLASS:
out << pLookups->LookupClassName(wOperands[i]);
break;
case otVAR:
_GetVarType(out, bOpcode, wOperands[i], pOFLookups);
break;
case otLABEL:
// This is a relative position from the post pc
out << ((bOpcode == Opcode::CALL) ? "proc" : "code") << "_" << setw(4) << setfill('0') << CalcOffset(version, wOperandStart, wOperands[i], bByte, bRawOpcode);
break;
case otDEBUGSTRING:
// Filename
out << "\"" << reinterpret_cast<const char *>(pCur) << "\"";
break;
default:
assert(false && "Unknown operand type");
out << "$" << setw(4) << setfill('0') << wOperands[i];
break;
}
out << " ";
}
pCur += cIncr;
wOffset += cIncr;
}
if (analyzeInstruction && (state == STATE_OUTPUT))
{
(*analyzeInstruction)(bOpcode, wOperandsRaw, wOffset);
}
if (state == STATE_OUTPUT)
{
// Time for comments (for some instructions)
szBuf[0] = 0;
switch (bOpcode)
{
case Opcode::LINK:
out << "// (var $" << wOperands[0] << ")";
break;
case Opcode::LOFSS:
case Opcode::LOFSA:
{
// This is an offset... it could be an interesting one, like a string or said.
ICompiledScriptSpecificLookups::ObjectType type;
std::string name = InvalidLookupError;
pScriptThings->LookupObjectName(wOperands[0], type, name);
out << "// " << name;
}
break;
case Opcode::PUSHI:
out << "// $" << wOperands[0] << " " << pLookups->LookupSelectorName(wOperands[0]);
break;
// could do it for push0, push1, etc..., but it's just clutter, and rarely the intention.
case Opcode::CALLE:
case Opcode::CALLB:
// Try to get the public export name.
if (pOFLookups)
{
uint16_t wScript;
uint16_t wIndex;
if (Opcode::CALLB == bOpcode)
{
wScript = 0;
wIndex = wOperands[0];
}
else
{
wScript = wOperands[0];
wIndex = wOperands[1];
}
out << "// " << pOFLookups->ReverseLookupPublicExportName(wScript, wIndex) << " ";
}
break;
}
out << endl;
switch (bOpcode)
{
case Opcode::SEND:
case Opcode::CALL:
case Opcode::CALLB:
case Opcode::CALLE:
case Opcode::CALLK:
case Opcode::SELF:
case Opcode::SUPER:
// Add another carriage return after these instructions
out << endl;
break;
}
}
}
}
}
catch (...)
{
// In case we read more than there was.
appState->LogInfo("Error while disassembling script.");
}
}
void DisassembleObject(const CompiledScript &script,
const CompiledObject &object,
std::ostream &out,
ICompiledScriptLookups *pLookups,
IObjectFileScriptLookups *pOFLookups,
const ICompiledScriptSpecificLookups *pScriptThings,
const std::vector<BYTE> &scriptResource,
const std::vector<CodeSection> &codeSections,
std::set<uint16_t> &codePointersTO,
AnalyzeInstructionPtr analyzeInstruction)
{
out << "// " << setw(4) << setfill('0') << object.GetPosInResource() << endl;
out << (object.IsInstance() ? "(instance " : "(class ");
if (object.IsPublic)
{
out << "public ";
}
// Header
out << object.GetName() << " of " << pLookups->LookupClassName(object.GetSuperClass()) << endl;
// Properties (skip the first 4)
out << " (properties" << endl;
vector<uint16_t> propertySelectorList;
if (pLookups->LookupSpeciesPropertyList(object.GetSpecies(), propertySelectorList))
{
const vector<CompiledVarValue> &propertyValues = object.GetPropertyValues();
size_t selectorCount = propertySelectorList.size();
size_t valueCount = propertyValues.size();
if (valueCount != selectorCount)
{
out << "// Problem with properties. Species has " << (int)selectorCount << " but instance has " << (int)valueCount << "." << endl;
}
for (size_t i = object.GetNumberOfDefaultSelectors(); i < min(selectorCount, valueCount); i++)
{
out << " " << pLookups->LookupSelectorName(propertySelectorList[i]);
if (propertyValues[i].isObjectOrString)
{
sci::ValueType typeSaidOrString;
std::string theString = script.GetStringOrSaidFromOffset(propertyValues[i].value, typeSaidOrString);
if (typeSaidOrString == sci::ValueType::Said)
{
out << "'" << theString << "'";
}
else
{
out << "\"" << theString << "\"";
}
}
else
{
out << " $" << propertyValues[i].value;
}
out << endl;
}
out << " )" << endl;
}
else
{
out << "// Can't get properties for class" << endl;
}
const vector<uint16_t> &functionSelectors = object.GetMethods();
const vector<uint16_t> &functionOffsetsTO = object.GetMethodCodePointersTO();
// Methods
assert(functionSelectors.size() == functionOffsetsTO.size());
for (size_t i = 0; i < functionSelectors.size(); i++)
{
out << " (method (" << pLookups->LookupSelectorName(functionSelectors[i]) << ") // method_" << setw(4) << setfill('0') << functionOffsetsTO[i] << endl;
// Now the code.
set<uint16_t>::const_iterator functionIndex = find(codePointersTO.begin(), codePointersTO.end(), functionOffsetsTO[i]);
if (functionIndex != codePointersTO.end())
{
CodeSection section;
if (FindStartEndCode(functionIndex, codePointersTO, codeSections, section))
{
const BYTE *pStartCode = &scriptResource[section.begin];
const BYTE *pEndCode = &scriptResource[section.end];
DisassembleCode(object.GetVersion(), out, pLookups, pOFLookups, pScriptThings, &object, pStartCode, pEndCode, functionOffsetsTO[i], analyzeInstruction);
}
else
{
out << "CORRUPT SCRIPT" << endl;
}
}
out << " )" << endl << endl;
}
out << ")" << endl;
}
const char c_indent[] = " ";
void DisassembleFunction(const CompiledScript &script, std::ostream &out, ICompiledScriptLookups *pLookups, IObjectFileScriptLookups *pOFLookups, uint16_t wCodeOffsetTO, set<uint16_t> &sortedCodePointersTO)
{
out << "(procedure proc_" << setw(4) << setfill('0') << wCodeOffsetTO << endl;
set<uint16_t>::const_iterator codeStartIt = sortedCodePointersTO.find(wCodeOffsetTO);
assert(codeStartIt != sortedCodePointersTO.end());
CodeSection section;
if (FindStartEndCode(codeStartIt, sortedCodePointersTO, script._codeSections, section))
{
const BYTE *pBegin = &script.GetRawBytes()[section.begin];
const BYTE *pEnd = &script.GetRawBytes()[section.end];
DisassembleCode(script.GetVersion(), out, pLookups, pOFLookups, &script, nullptr, pBegin, pEnd, wCodeOffsetTO, nullptr);
}
else
{
out << "CORRUPT SCRIPT" << endl;
}
out << ')' << endl << endl;
}
void DisassembleScript(const CompiledScript &script, std::ostream &out, ICompiledScriptLookups *pLookups, IObjectFileScriptLookups *pOFLookups, const Vocab000 *pWords, const std::string *pMessage, AnalyzeInstructionPtr analyzeInstruction)
{
// (script x)
if (pMessage)
{
out << *pMessage << endl;
}
out << "(script " << script.GetScriptNumber() << ")" << endl << endl;
// Internal strings
out << "(string" << endl;
out << hex;
assert(script._strings.size() == script._stringsOffset.size());
for (size_t i = 0; i < script._strings.size(); i++)
{
out << c_indent << "string_" << setw(4) << setfill('0') << script._stringsOffset[i] << " \"" << EscapeQuotedString(script._strings[i]) << "\"" << endl;
}
out << ")" << endl << endl;
// Prepare the saids.
out << "(said" << endl;
script.PopulateSaidStrings(pWords);
for (size_t i = 0; i < script._saidStrings.size(); i++)
{
// said_0x03EC 'look/tree'
out << c_indent << "said_" << setw(4) << setfill('0') << script._saidsOffset[i] << " " << script._saidStrings[i] << endl;
}
out << ")" << endl << endl;
// Synonyms
if (script._synonyms.size() > 0)
{
out << "(synonym" << endl;
for (const auto &syn : script._synonyms)
{
for (auto &theSyn : syn.second)
{
out << c_indent << pWords->Lookup(syn.first) << " = " << pWords->Lookup(theSyn).c_str() << endl;
}
}
out << ")" << endl << endl;
}
// Local variables
out << "(local" << endl;
for (size_t i = 0; i < script._localVars.size(); i++)
{
out << c_indent << _GetLocalVariableName((int)i, 0xffff) << " = $" << setw(4) << setfill('0') << script._localVars[i].value << endl;
}
out << ")" << endl << endl;
// Now its time for code.
// Make an index of code pointers by looking at the object methods
set<uint16_t> codePointersTO;
for (auto &object : script._objects)
{
const vector<uint16_t> &methodPointersTO = object->GetMethodCodePointersTO();
codePointersTO.insert(methodPointersTO.begin(), methodPointersTO.end());
}
// and the exports
for (size_t i = 0; i < script._exportsTO.size(); i++)
{
uint16_t wCodeOffset = script._exportsTO[i];
// Export offsets could point to objects too - we're only interested in code pointers, so
// check that it's within bounds.
if (script.IsExportAProcedure(wCodeOffset))
{
codePointersTO.insert(wCodeOffset);
}
}
// and finally, the most difficult of all, we'll need to scan though for any call calls...
// those would be our internal procs
set<uint16_t> internalProcOffsetsTO = script.FindInternalCallsTO();//_rgRawCode, _wCodePosTO, _wCodeLength);
// Before adding these though, remove any exports from the internalProcOffsets.
for (const auto &exporty : script._exportsTO)
{
if (script.IsExportAProcedure(exporty)) // Exported objects can have the same address as a proc, we need to make sure we don't omit a proc because of that.
{
set<uint16_t>::iterator internalsIndex = find(internalProcOffsetsTO.begin(), internalProcOffsetsTO.end(), exporty);
if (internalsIndex != internalProcOffsetsTO.end())
{
// Remove this guy.
internalProcOffsetsTO.erase(internalsIndex);
}
}
}
// Now add the internal guys to the full list
codePointersTO.insert(internalProcOffsetsTO.begin(), internalProcOffsetsTO.end());
// Now we know the length of each code segment (assuming none overlap)
// Spit out code segments - first, the objects (instances, classes)
for (auto &object : script._objects)
{
DisassembleObject(script, *object, out, pLookups, pOFLookups, &script, script.GetRawBytes(), script._codeSections, codePointersTO, analyzeInstruction);
out << endl;
}
out << endl;
// Now the exported procedures.
for (size_t i = 0; i < script._exportsTO.size(); i++)
{
// _exportsTO, in addition to containing code pointers for public procedures, also
// contains the Rm/Room class. Filter these out by ignoring code pointers which point outside
// the codesegment.
if (script.IsExportAProcedure(script._exportsTO[i]))
{
std::string strProcName = "";
if (pOFLookups)
{
strProcName = pOFLookups->ReverseLookupPublicExportName(script.GetScriptNumber(), (uint16_t)i);
}
out << dec;
out << "// EXPORTED procedure #" << (int)i << " (" << strProcName << ")" << endl;
out << hex;
DisassembleFunction(script, out, pLookups, pOFLookups, script._exportsTO[i], codePointersTO);
}
}
out << endl;
// Now the internal procedures (REVIEW - possibly overlap with exported ones)
set<uint16_t>::iterator it = internalProcOffsetsTO.begin();
while (it != internalProcOffsetsTO.end())
{
DisassembleFunction(script, out, pLookups, pOFLookups, *it, codePointersTO);
it++;
}
}
|
/* Copyright (c) 2013 Richard Russon (FlatCap)
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef _DISK_H_
#define _DISK_H_
#include <string>
#include "container.h"
/**
* class Disk
*/
class Disk : public Container
{
public:
static DPtr create (void);
Disk (Disk&& d);
virtual ~Disk() = default;
Disk& operator= (const Disk& d);
Disk& operator= (Disk&& d);
void swap (Disk& d);
friend void swap (Disk& lhs, Disk& rhs);
friend std::ostream & operator<< (std::ostream &stream, const DPtr &c);
protected:
Disk (void) = default;
Disk (const Disk& d);
virtual Disk* clone (void) const;
private:
int _a;
int _b;
int _c;
};
#endif // _DISK_H_
|
#include <cstdio>
#include <algorithm>
using namespace std;
struct Student
{
char id[20 + 1];
int tgrades;
bool flag;
}stu[1000];
bool cmp(Student stu1, Student stu2)
{
if (stu1.tgrades != stu2.tgrades)
return stu1.tgrades > stu2.tgrades;
else
return stu1.id < stu2.id;
}
void init()
{
for (int i = 0; i < 1000; i++)
{
stu[i].tgrades = 0;
stu[i].flag = false;
}
}
int main()
{
while (true)
{
int n, m, g;
int grades[10];
int cnt = 0;
init();
scanf("%d%d%d", &n, &m, &g);
if (n == 0)
break;
for (int i = 0; i < m; i++)
{
scanf("%d", &grades[i]);
}
for (int i = 0; i < n; i++)
{
int sm;
scanf("%s %d", stu[i].id, &sm);
for (int j = 0; j < sm; j++)
{
int t;
scanf("%d", &t);
stu[i].tgrades += grades[t - 1];
}
if (stu[i].tgrades >= g)
{
cnt++;
stu[i].flag = true;
}
}
sort(stu, stu + n, cmp);
printf("%d\n", cnt);
for (int i = 0; i < n; i++)
{
if (stu[i].flag = true)
printf("%s %d\n", stu[i].id, stu[i].tgrades);
}
}
}
|
#include "../header/DlgSettings.h"
/////////////////////////////////////////////////////////////////////////
DlgSettings::DlgSettings(QList<List> &listButtons, QDialog* pDlg): QDialog(pDlg)
{
QTextCodec *codec = QTextCodec::codecForName("cp1251");
QTextCodec::setCodecForTr(codec);
// настройка шрифта
QFont font("Arial", 8, QFont::Bold);
QFontMetrics fm(font);
int height_sym = fm.height();
int height_str = height_sym + height_sym/4;
// конец настройки шрифта
m_listButtons = &listButtons;
QVBoxLayout *pVLtMain = new QVBoxLayout;
QVBoxLayout *pVLtTab = new QVBoxLayout;
QWidget *pWgtMain = new QWidget;
QTabWidget *pTabSettings = new QTabWidget();
// создание и настройка закладок "настроек"
// создание закладки "Кнопки"
QWidget *pWgtButtons = new QWidget;
QHBoxLayout *pHLtButtons = new QHBoxLayout;
QVBoxLayout *pVLtList = new QVBoxLayout;
QVBoxLayout *pVLtEditBut = new QVBoxLayout;
m_pListButtons = new QTableWidget(0, 2);
m_pListButtons->setHorizontalHeaderLabels(QStringList() << tr("Название") << tr("Команда"));
m_pListButtons->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
for(int count = 0; count < m_listButtons->count(); count++)
{
QString strName = m_listButtons->at(count).getNameButton();
QString strCommand = m_listButtons->at(count).getNameCommand();
m_pListButtons->insertRow(count);
m_pListButtons->setItem(count, 0, new QTableWidgetItem(strName));
m_pListButtons->setItem(count, 1, new QTableWidgetItem(strCommand));
}
m_pListButtons->setShowGrid(false);
m_pListButtons->selectRow(0);
m_pListButtons->setFont(font);
m_pListButtons->verticalHeader()->setDefaultSectionSize(height_str);
m_pListButtons->setEditTriggers(QAbstractItemView::NoEditTriggers);
connect(m_pListButtons, SIGNAL(itemSelectionChanged()), this, SLOT(slotSelectRow()));
pButAdd = new QPushButton(tr("Добавить"));
pButDel = new QPushButton(tr("Удалить"));
pButQuit = new QPushButton(tr("Выход"));
pButUp = new QPushButton(QIcon(QPixmap("image/arrow_up.png")), "");
pButDown = new QPushButton(QIcon(QPixmap("image/arrow_down.png")), "");
pButAdd->setToolTip(tr("Добавить новую кнопку"));
pButDel->setToolTip(tr("Удалить выбранную кнопку"));
pButQuit->setToolTip(tr("Выйти из настроек"));
pButUp->setToolTip(tr("Переместить кнопку вверх"));
pButDown->setToolTip(tr("Переместить кнопку вниз"));
QVBoxLayout *pVLtMoveBut = new QVBoxLayout;
QGroupBox *pGrAddBut = new QGroupBox(tr("Новая кнопка"));
QVBoxLayout *pVLtGrAddBut = new QVBoxLayout(pGrAddBut);
QHBoxLayout *pHLtNameBut = new QHBoxLayout;
QHBoxLayout *pHLtNameCom = new QHBoxLayout;
QLabel *pLblNameBut = new QLabel(tr("Название"));
QLabel *pLblNameCom = new QLabel(tr("Команда "));
m_leNameBut = new QLineEdit;
m_leNameCom = new QLineEdit;
m_leNameBut->setFocus();
m_leNameBut->setToolTip(tr("Названиие кнопки"));
m_leNameCom->setToolTip(tr("AT-команда"));
pHLtNameBut->addWidget(pLblNameBut);
pHLtNameBut->addWidget(m_leNameBut);
pHLtNameCom->addWidget(pLblNameCom);
pHLtNameCom->addWidget(m_leNameCom);
pVLtGrAddBut->addLayout(pHLtNameBut);
pVLtGrAddBut->addLayout(pHLtNameCom);
pVLtGrAddBut->addWidget(pButAdd);
pVLtList->addWidget(m_pListButtons);
pVLtEditBut->addWidget(pGrAddBut);
pVLtEditBut->addWidget(pButDel);
pVLtEditBut->addStretch();
pVLtEditBut->addWidget(pButQuit);
pVLtMoveBut->addStretch();
pVLtMoveBut->addWidget(pButUp);
pVLtMoveBut->addWidget(pButDown);
pVLtMoveBut->addStretch();
pHLtButtons->addLayout(pVLtMoveBut);
pHLtButtons->addLayout(pVLtList);
pHLtButtons->addLayout(pVLtEditBut);
pWgtButtons->setLayout(pHLtButtons);
pTabSettings->addTab(pWgtButtons, tr("Кнопки"));
connect(pButUp, SIGNAL(clicked()), this, SLOT(slotMoveButtonUp()));
connect(pButDown, SIGNAL(clicked()), this, SLOT(slotMoveButtonDown()));
connect(pButQuit, SIGNAL(clicked()), this, SLOT(accept()));
connect(pButDel, SIGNAL(clicked()), this, SLOT(slotButtonDelete()));
connect(pButAdd, SIGNAL(clicked()), this, SLOT(slotButtonAppend()));
// конец создания закладки "Кнопки"
// конец закладок "настроек"
pVLtTab->addWidget(pTabSettings);
pWgtMain->setLayout(pVLtTab);
pVLtMain->addWidget(pWgtMain);
this->setLayout(pVLtMain);
this->setWindowTitle(tr("Настройки"));
}
//--------------------------------------------------------------------
void DlgSettings::slotButtonAppend()
{
if(m_pListButtons->rowCount() < MAX_COUNT_BUTTON_AT)
{
QString strNameBut = m_leNameBut->text();
QString strNameCom = m_leNameCom->text();
for(int count = 0; count < m_pListButtons->rowCount(); count++)
{
if(m_pListButtons->item(count, 0)->text().toUpper() == strNameBut.toUpper())
{
QMessageBox::about(this, tr("Новая команда"), tr("Такое имя уже существует"));
clearNewCommand();
updateListButtons();
return;
}
else
if(m_pListButtons->item(count, 1)->text() == strNameCom.toUpper())
{
QMessageBox::about(this, tr("Новая команда"), tr("Такая команда уже существует"));
clearNewCommand();
updateListButtons();
return;
}
}
if(strNameBut.isEmpty() || strNameCom.isEmpty())
{
if(strNameCom.isEmpty())
{
QMessageBox::about(this, tr("Добавление кнопки"), tr("Введите команду.Пустую строку добавлять нельзя!"));
return;
}
else
strNameBut = strNameCom;
}
int row = m_pListButtons->rowCount();
m_pListButtons->insertRow(row);
m_pListButtons->setItem(row, 0, new QTableWidgetItem(strNameBut));
m_pListButtons->setItem(row, 1, new QTableWidgetItem(strNameCom.toUpper()));
m_pListButtons->selectRow(row);
updateListButtons();
clearNewCommand();
}
else
QMessageBox::about(this, tr("Новая команда"), tr("Превышен лимит команд"));
}
//--------------------------------------------------------------------
void DlgSettings::slotButtonDelete()
{
int numSelectStr = m_pListButtons->currentRow();
m_pListButtons->removeRow(numSelectStr);
updateListButtons();
}
//---------------------------------------------------------------------
void DlgSettings::slotMoveButtonUp()
{
moveTextItem(up);
}
//---------------------------------------------------------------------
void DlgSettings::slotMoveButtonDown()
{
moveTextItem();
}
//----------------------------------------------------------------------
void DlgSettings::moveTextItem(int dirMove)
{
int rowSelectedItem = m_pListButtons->currentRow();
int rowNextItem;
if(dirMove == down)
{
rowNextItem = rowSelectedItem + 1;
if(rowNextItem >= m_pListButtons->rowCount())
return;
}
else
if(dirMove == up)
{
rowNextItem = rowSelectedItem - 1;
if(rowNextItem < 0)
return;
}
QTableWidgetItem *selectedItemCol1 = m_pListButtons->item(rowSelectedItem, 0);
QTableWidgetItem *selectedItemCol2 = m_pListButtons->item(rowSelectedItem, 1);
QTableWidgetItem *nextItemCol1 = m_pListButtons->item(rowNextItem, 0);
QTableWidgetItem *nextItemCol2 = m_pListButtons->item(rowNextItem, 1);
QString strCol1, strCol2;
strCol1 = selectedItemCol1->text();
strCol2 = selectedItemCol2->text();
selectedItemCol1->setText(nextItemCol1->text());
selectedItemCol2->setText(nextItemCol2->text());
nextItemCol1->setText(strCol1);
nextItemCol2->setText(strCol2);
m_pListButtons->selectRow(rowNextItem);
updateListButtons();
}
//------------------------------------------------------------------
void DlgSettings::slotSelectRow()
{
int row = m_pListButtons->currentRow();
if( row != -1 )
m_pListButtons->selectRow(row);
}
//-------------------------------------------------------------------
void DlgSettings::updateListButtons()
{
m_listButtons->clear();
if(m_pListButtons->rowCount() == 0)
{
qDebug() << tr("Равно нулю");
return;
}
for(int count = 0; count < m_pListButtons->rowCount(); count++)
{
QString str1 = m_pListButtons->item(count, 0)->text();
QString str2 = m_pListButtons->item(count, 1)->text();
m_listButtons->append(List(str1, str2));
}
}
//-------------------------------------------------------------------
void DlgSettings::clearNewCommand()
{
m_leNameBut->clear();
m_leNameCom->clear();
}
|
#ifndef RESOURCELIB_TEXTUREHANDLER_TEXTUREHANDLER_H
#define RESOURCELIB_TEXTUREHANDLER_TEXTUREHANDLER_H
#include "FileLoader.h"
#include "FileHeaders.h"
#include "Texture.h"
#include "TextureLoader\DDSTextureLoader.h"
namespace Resources
{
class TextureHandler
{
private:
std::string TEXTURE_PATH = "../Assets/";
std::unordered_map<unsigned int, ResourceContainer> m_textures;
std::deque<Texture*> m_emptyContainers;
std::vector<std::vector<Texture>*> m_containers;
ID3D11Device* m_device = nullptr;
Texture* placeHolder = nullptr;
TextureHandler();
public:
DLL_OPERATION TextureHandler(size_t textureAmount, ID3D11Device* device = nullptr);
DLL_OPERATION virtual ~TextureHandler();
DLL_OPERATION Resources::Status GetTexture(const unsigned int& id, ResourceContainer*& texturePtr);
DLL_OPERATION Resources::Status GetTexture(const unsigned int& id, Texture*& texturePtr);
DLL_OPERATION Resources::Status LoadTexture(const unsigned int& id, ResourceContainer*& texturePtr);
DLL_OPERATION Resources::Status UnloadTexture(const unsigned int& id);
DLL_OPERATION Resources::Status ClearUnusedMemory(); // This Will go through the resourceLib and shrink all arrays and vectors to fit. Thus removing all other items in the resource pool
DLL_OPERATION void SetDevice(ID3D11Device* device);
DLL_OPERATION Texture* GetPlaceHolderTextures();
private:
bool LoadPlaceHolderTextures();
Texture* GetEmptyContainer();
};
}
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.