text
stringlengths 8
6.88M
|
|---|
/*
Expression Evaluator Library (NS-EEL) v2
Copyright (C) 2004-2008 Cockos Incorporated
Copyright (C) 1999-2003 Nullsoft, Inc.
nseel-lextab.c
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "script-lextab.h"
#include "script-yycontext.h"
#include "script-compiler.h"
namespace Script { namespace mdpx {
//------------------------------------------------------------------------------
ExpressionPtr nseel_parse_string(yycontext *ctx,const char *name, int type)
{
auto compiler = ctx->compiler;
switch (type)
{
case INTCONST:
{
auto v = atol(name);
return compiler->CreateCompiledConstantExpression((ValueType)v);
}
case DBLCONST:
{
auto v = atof(name);
return compiler->CreateCompiledConstantExpression((ValueType)v);
}
case HEXCONST:
{
int v=0;
int n=0;
while (1)
{
int a=name[n++];
if (a >= '0' && a <= '9') v=(v<<4)+a-'0';
else if (a >= 'A' && a <= 'F') v=(v<<4)+10+a-'A';
else if (a >= 'a' && a <= 'f') v=(v<<4)+10+a-'a';
else break;
}
return compiler->CreateCompiledConstantExpression((ValueType)v);
}
default:
assert(0);
return nullptr;
}
}
//------------------------------------------------------------------------------
YYSTYPE nseel_translate(yycontext *ctx, int type)
{
char name[4096];
nseel_gettoken(ctx, name, sizeof(name));
ExpressionPtr e = nseel_parse_string(ctx, name, type);
return (YYSTYPE)e;
}
//------------------------------------------------------------------------------
INT_PTR nseel_lookup(yycontext *ctx, TokenType *typeOfObject)
{
char name[4096];
nseel_gettoken(ctx, name, sizeof(name));
auto *compiler = ctx->compiler;
ExpressionPtr cv = compiler->LookupVariable(name);
if (cv)
{
*typeOfObject = IDENTIFIER;
return (INT_PTR)cv;
}
FuncType ftype;
if (LookupFunction(name, &ftype, typeOfObject))
{
return (INT_PTR)ftype;
}
*typeOfObject = IDENTIFIER;
cv = compiler->AddVariable(name);
return (INT_PTR)cv;
}
#define LEXSKIP (-1)
static int _lmovb(const lextab *lp, int c, int st)
{
int base;
while ((base = lp->llbase[st]+c) > lp->llnxtmax ||
(lp->llcheck[base] & 0377) != st) {
if (st != lp->llendst) {
base = lp->lldefault[st] & 0377;
st = base;
}
else
return(-1);
}
return(lp->llnext[base]&0377);
}
#define INTCONST 1
#define DBLCONST 2
#define HEXCONST 3
#define VARIABLE 4
#define OTHER 5
static int _Alextab(yycontext *ctx, int __na__)
{
// fucko: JF> 17 -> 19?
if (__na__ >= 0 && __na__ <= 17)
{
//?
char tname[4096];
nseel_gettoken(ctx, tname, sizeof(tname));
}
switch (__na__)
{
case 0:
{
char name[4096];
nseel_gettoken(ctx, name, sizeof(name));
if (name[0] < '0' || name[0] > '9') // not really a hex value, lame
{
TokenType ttype;
ctx->yylval = nseel_lookup(ctx, &ttype);
return ttype;
}
ctx->yylval = nseel_translate(ctx,HEXCONST);
return VALUE;
}
case 1: ctx->yylval = nseel_translate(ctx,INTCONST); return VALUE;
case 2: ctx->yylval = nseel_translate(ctx,INTCONST); return VALUE;
case 3: ctx->yylval = nseel_translate(ctx,DBLCONST); return VALUE;
case 4:
case 5:
{
TokenType ttype;
ctx->yylval = nseel_lookup(ctx,&ttype);
return ttype;
}
case 6: return '+';
case 7: return '-';
case 8: return '*';
case 9: return '/';
case 10: return '%';
case 11: return '&';
case 12: return '|';
case 13: return '(';
case 14: return ')';
case 15: return '=';
case 16: return ',';
case 17: return ';';
}
return (LEXSKIP);
}
static const char _Flextab[] =
{
1, 18, 17, 16, 15, 14, 13, 12,
11, 10, 9, 8, 7, 6, 4, 5,
5, 4, 4, 3, 3, 3, 3, 4,
0, 4, 5, 0, 5, 4, 1, 3,
0, 2, -1, 1, -1,
};
static const char _Nlextab[] =
{
36, 36, 36, 36, 36, 36, 36, 36,
36, 1, 36, 36, 36, 36, 36, 36,
36, 36, 36, 36, 36, 36, 36, 36,
36, 36, 36, 36, 36, 36, 36, 36,
1, 36, 36, 36, 36, 9, 8, 36,
6, 5, 11, 13, 3, 12, 19, 10,
30, 30, 30, 30, 30, 30, 30, 30,
30, 30, 36, 2, 36, 4, 36, 36,
36, 29, 29, 29, 29, 29, 29, 18,
18, 18, 18, 18, 18, 18, 18, 18,
18, 18, 18, 18, 18, 18, 18, 18,
18, 18, 18, 36, 36, 36, 36, 18,
36, 29, 29, 29, 29, 29, 23, 18,
18, 18, 18, 18, 18, 18, 18, 18,
18, 18, 18, 18, 18, 18, 14, 18,
18, 18, 18, 36, 7, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 36,
36, 36, 36, 36, 36, 36, 17, 17,
17, 17, 17, 17, 17, 17, 17, 17,
17, 17, 17, 17, 17, 17, 17, 17,
17, 17, 17, 17, 17, 17, 17, 17,
36, 36, 36, 36, 17, 36, 17, 17,
17, 17, 17, 17, 17, 17, 17, 17,
17, 17, 17, 17, 17, 17, 17, 17,
17, 17, 17, 17, 17, 17, 17, 17,
15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 36, 36, 36, 36, 36, 36,
36, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 36, 36, 36, 36, 16,
36, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 22, 22, 22, 22, 22,
22, 22, 22, 22, 22, 21, 21, 21,
21, 21, 21, 21, 21, 21, 21, 36,
20, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 36, 36, 36, 36, 36,
36, 36, 25, 25, 25, 25, 25, 25,
36, 24, 36, 36, 36, 36, 36, 36,
20, 36, 36, 36, 36, 36, 36, 36,
36, 36, 36, 36, 36, 36, 36, 36,
36, 36, 25, 25, 25, 25, 25, 25,
36, 24, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 36, 36, 36, 36,
36, 36, 36, 28, 28, 28, 28, 28,
28, 36, 27, 36, 36, 36, 36, 36,
36, 36, 36, 36, 36, 36, 36, 36,
36, 36, 36, 36, 36, 36, 36, 36,
36, 36, 36, 28, 28, 28, 28, 28,
28, 31, 27, 35, 35, 35, 35, 35,
35, 35, 35, 35, 35, 36, 36, 36,
36, 36, 36, 36, 34, 34, 34, 33,
34, 34, 36, 32, 36, 36, 36, 36,
36, 36, 36, 36, 36, 36, 36, 36,
36, 36, 36, 36, 36, 36, 36, 36,
36, 36, 36, 36, 34, 34, 34, 33,
34, 34, 36, 32, 34, 34, 34, 34,
34, 34, 34, 34, 34, 34, 36, 36,
36, 36, 36, 36, 36, 34, 34, 34,
34, 34, 34, 36, 32, 36, 36, 36,
36, 36, 36, 36, 36, 36, 36, 36,
36, 36, 36, 36, 36, 36, 36, 36,
36, 36, 36, 36, 36, 34, 34, 34,
34, 34, 34, 36, 32,
};
static const char _Clextab[] =
{
-1, -1, -1, -1, -1, -1, -1, -1,
-1, 0, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
0, -1, -1, -1, -1, 0, 0, -1,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, -1, 0, -1, 0, -1, -1,
-1, 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, -1, -1, -1, -1, 0,
-1, 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, -1, 0, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, -1,
-1, -1, -1, -1, -1, -1, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14,
-1, -1, -1, -1, 14, -1, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14,
15, 15, 15, 15, 15, 15, 15, 15,
15, 15, -1, -1, -1, -1, -1, -1,
-1, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, -1, -1, -1, -1, 15,
-1, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 19, 19, 19, 19, 19,
19, 19, 19, 19, 19, 20, 20, 20,
20, 20, 20, 20, 20, 20, 20, -1,
19, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, -1, -1, -1, -1, -1,
-1, -1, 23, 23, 23, 23, 23, 23,
-1, 23, -1, -1, -1, -1, -1, -1,
19, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, 23, 23, 23, 23, 23, 23,
-1, 23, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, -1, -1, -1, -1,
-1, -1, -1, 26, 26, 26, 26, 26,
26, -1, 26, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 26, 26, 26, 26, 26,
26, 30, 26, 30, 30, 30, 30, 30,
30, 30, 30, 30, 30, -1, -1, -1,
-1, -1, -1, -1, 30, 30, 30, 30,
30, 30, -1, 30, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, 30, 30, 30, 30,
30, 30, -1, 30, 33, 33, 33, 33,
33, 33, 33, 33, 33, 33, -1, -1,
-1, -1, -1, -1, -1, 33, 33, 33,
33, 33, 33, -1, 33, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 33, 33, 33,
33, 33, 33, -1, 33,
};
static const char _Dlextab[] =
{
36, 36, 36, 36, 36, 36, 36, 36,
36, 36, 36, 36, 36, 36, 36, 36,
15, 14, 14, 36, 36, 20, 19, 14,
14, 23, 15, 15, 26, 23, 36, 19,
36, 36, 33, 30,
};
static const int _Blextab[] =
{
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 77, 152,
0, 0, 0, 227, 237, 0, 0, 249,
0, 0, 306, 0, 0, 0, 363, 0,
0, 420, 0, 0, 0,
};
static const lextab nseel_lextab = {
36,
_Dlextab,
_Nlextab,
_Clextab,
_Blextab,
524,
_lmovb,
_Flextab,
_Alextab,
0,
0,
0,
0,
};
const lextab *GetDefaultLexTab() {return &nseel_lextab;}
}} // namespace
|
#include<stdio.h>
int main()
{
int i,m[5],n[5],c[5];
//clrscr();
printf("\nReading the 1st array\n");
for (i=0;i<5;i++)
{
printf("Enter the value");
scanf("%d",&m[i]);
}
printf("\nReading the 2nd array\n");
for (i=0;i<5;i++)
{
printf("Enter the value");
scanf("%d",&n[i]);
}
printf("\nThe output of addition of 2 array is\n");
for(i=0;i<5;i++)
{
c[i]=m[i]+n[i];
printf("\nthe sum of %d & %d is %d",m[i],n[i],c[i]);
}
return 0;
}
|
//================================================================//
// //
//$Id:$ //
// //
// stdafx.h : //
// Include file for standard system include files,or project //
// specific include files that are used frequently, but are //
// changed infrequently. //
// //
// Copyright 2005 Network Appliance, Inc. All rights //
// reserved. Specifications subject to change without notice. //
// //
// This SDK sample code is provided AS IS, with no support or //
// warranties of any kind, including but not limited to //
// warranties of merchantability or fitness of any kind, //
// expressed or implied. This code is subject to the license //
// agreement that accompanies the SDK. //
// //
//================================================================//
#pragma once
#include <iostream>
#include <tchar.h>
// TODO: reference additional headers your program requires here
|
/*************************************************
Copyright:CFSC
Author: Souleep
Date:2020-06-02
Description:通过CAS/Memory_Order分别实现无锁消息队列
**************************************************/
/*todo:linux kernel的kfifo机制好像更优雅*/
#ifndef __LFQUEUE_H__
#define __LFQUEUE_H__
#include <thread>
#include <iostream>
#include <atomic>
#include <stdint.h>
#define CAS2(obj, expected, desired) std::atomic::atomic_compare_exchange_weak(obj, expected, desired);
#ifdef WIN32
#define CAS(ptr, oldvalue, newvalue) InterlockedCompareExchange(ptr, newvalue, oldvalue)
#else
#define CAS(ptr, oldvalue, newvalue) __sync_val_compare_and_swap(ptr , oldvalue , newvalue)
#endif
#include<mutex>
template<typename ELEM_TYPE>
class LockFreeQueue
{
public:
LockFreeQueue(int capicity) : capicity_(capicity), header_(0), tailer_(0), guard_(0)
{
if (capicity_ < 4) { capicity_ = 4; }
lf_queue_ = new ELEM_TYPE * [capicity_];
for (int i = 0; i < capicity_; i++)
lf_queue_[i] = NULL;
}
~LockFreeQueue() { if (lf_queue_) { delete[] lf_queue_; } }
public:
enum QStatus {
Empty,
Full,
Normal,
Unknown
};
bool isempty() { return header_ == guard_; }
bool isfull() { return (internal_index(tailer_ + 1)) == header_; }
int internal_index(int v) { return (v % capicity_); }
bool enqueue(ELEM_TYPE* item)
{
int temp, guard;
ASSERT(item);
do
{
// fetch tailer_ first and then judge isfull, else encounter concurrent problem
temp = tailer_;
guard = guard_;
if (isfull())
{
return false;
}
// cross operate
if (CAS(&tailer_, temp, internal_index(temp + 1)) == temp)
{
lf_queue_[temp] = item;
// update the guard_ for the max dequeue item
CAS(&guard_, guard, internal_index(guard + 1));
break;
}
else
{
//std::cout << "enqueue Cas failure one times" << std::endl;
}
} while (true);
return true;
}
template<typename ELEM_TYPE>
bool dequeue(ELEM_TYPE** item)
{
int temp;
do
{
// fetch header first and then judge isempty, else encounter concurrent problem
temp = header_;
*item = NULL;
if (isempty())
{
return false;
}
// cross operate CAS failure
*item = lf_queue_[temp];
if (CAS(&header_, temp, internal_index(temp + 1)) == temp)
{
// some producer lock one slot, but doesn't push back
// while (!lf_queue_[temp])
// {
// std::this_thread::yield();
// }
//*item = lf_queue_[temp];
lf_queue_[temp] = NULL;
break;
}
else
{
//std::cout << "dequeue Cas failure one times" << std::endl;
}
} while (true);
return true;
}
private:
ELEM_TYPE** lf_queue_;
int capicity_;
#ifdef WIN32
long header_;
long tailer_;
long guard_;
// header <= guard <= tailer
#else
int header_;
int tailer_;
int guard_;
// int header_;
// int tailer_;
// int guard_; // header <= guard <= tailer
#endif
};
//空锁
struct NullMutex
{
void lock() {}
void unlock() {}
};
#define XIXI_CACHELINE_SIZE 64
//通过内存序实现双锁链表:类似于原子变量但要强于原子变量
//双锁链表(头尾锁):如果单进单出,使用空锁实现无锁队列
template<typename VALUE_TYPE, typename PUSH_MUTEX_TYPE = std::mutex, typename POP_MUTEX_TYPE = std::mutex>
class NonBlockingQueue
{
public:
NonBlockingQueue(const NonBlockingQueue&) = delete;
NonBlockingQueue& operator= (const NonBlockingQueue&) = delete;
typedef VALUE_TYPE value_type;
private:
struct Node
{
//value_type data;
char data[sizeof(value_type)];
Node* next;
};
Node* m_head; //队列头
Node* m_freeTail;
char padding1[XIXI_CACHELINE_SIZE - sizeof(Node*) * 2];
Node* m_tail; //队列尾
Node* m_free; //
PUSH_MUTEX_TYPE m_push_mutex;
POP_MUTEX_TYPE m_pop_mutex;
public:
NonBlockingQueue(int init_node_num = UINT16_MAX)
{
Node* pNode = allocNode();
if (pNode)
{
pNode->next = NULL;
}
m_head = m_tail = pNode;
pNode = allocNode();
if (pNode)
{
pNode->next = NULL;
}
m_free = m_freeTail = pNode;
for (int i = 0; i < init_node_num; i++)
{
pushNode(allocNode());
}
}
~NonBlockingQueue()
{
Node* pNode = NULL;
while (m_head)
{
pNode = m_head;
m_head = m_head->next;
VALUE_TYPE* obj = (VALUE_TYPE*)pNode->data;
obj->~VALUE_TYPE();
freeNode(pNode);
}
m_tail = NULL;
while (m_free)
{
pNode = m_free;
m_free = m_free->next;
freeNode(pNode);
}
}
bool push(const VALUE_TYPE& value)
{
m_push_mutex.lock();
Node* pNode = popNode();
if (pNode)
{
new (pNode->data) VALUE_TYPE(value);
pNode->next = NULL;
Node* new_tail = m_tail;
this->m_tail = pNode;
std::atomic_thread_fence(std::memory_order_release);
new_tail->next = pNode;
m_push_mutex.unlock();
return true;
}
m_push_mutex.unlock();
return false;
}
bool pop(VALUE_TYPE& value)
{
m_pop_mutex.lock();
Node* pNode = m_head;
Node* new_head = pNode->next;
if (new_head)
{
std::atomic_thread_fence(std::memory_order_acquire);
VALUE_TYPE* obj = (VALUE_TYPE*)new_head->data;
value = *obj;
obj->~VALUE_TYPE();
m_head = new_head;
pushNode(pNode);
m_pop_mutex.unlock();
return true;
}
m_pop_mutex.unlock();
return false;
}
private:
//内存分配一个节点
Node* allocNode()
{
return new Node();
}
//归还节点内存
void freeNode(Node* pNode)
{
delete pNode;
}
//从空闲节点池获取一个节点
Node* popNode()
{
Node* pNode = m_free;
Node* new_head = pNode->next;
if (new_head)
{
std::atomic_thread_fence(std::memory_order_acquire);
m_free = new_head;
}
else
{
pNode = allocNode();
}
return pNode;
}
//把一个节点放回空闲列表
void pushNode(Node* pNode)
{
Node* new_tail = m_freeTail;
pNode->next = NULL;
m_freeTail = pNode;
std::atomic_thread_fence(std::memory_order_release);
new_tail->next = pNode;
}
};
#endif
|
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Name: Braydon Hampton
// File: main.cpp
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#include <iostream>
#include <limits>
#include "mystring.h"
const int MAX_BUF = 1024;
void test_str_cmp()
{
char s[MAX_BUF];
char t[MAX_BUF];
std::cin.getline(s, MAX_BUF);
std::cin.getline(t, MAX_BUF);
std::cout << str_cmp(s, t) << std::endl;
}
int main()
{
int i = 0;
std::cin >> i;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
switch (i)
{
case 0:
test_str_cmp();
break;
}
return 0;
}
|
#include<vector>
using std::vector;
class test
{
public:
int max_output(vector<int> &prices)
{
int final_cost = 0;
for(auto i = prices.begin();i!= prices.end();++i)
{
if(i+1 != prices.end() && *(i+1) > *i)
{
final_cost += *(i+1) - *i;
}
}
return final_cost;
}
};
//直接采用指针的方式调用迭代器实现,较为巧妙
//有没有其他更加直接的写法?
|
#include<bits/stdc++.h>
using namespace std;
int main(){
int a,b,c,d,e,f,i,m,maxi,mm,n,j,p;
cin>>n;
while(n--){
cin>>a;
for(i=0;i<a-1;i++){ {cin>>b>>c; p=-100;
d=b; c=e; f=d-e; m=f; if(m>p) {maxi=m;} else maxi=p;
e=f+m; if(maxi>e) {mm=maxi ;} else mm=e;
}}
printf("case %d: %d",i+1,mm);
}
return 0;
}
|
#include "DXUT.h"
#include "cVirus.h"
cVirus::cVirus(void)
:m_nCount( 0 )
{
}
cVirus::~cVirus(void)
{
}
void cVirus::Init()
{
m_vScale *= 0.4f;
cMonster::Init();
m_fOriMoveSpeed = 10.0f;
m_fHp = 500.0f;
m_fBulletSpeed = 25.0f;
m_pResourceFile = _GETSINGLE( cResourceMgr )->GetResourceFile( "virus" );
m_pResBullet = _GETSINGLE( cResourceMgr )->GetResourceFile( "bullet_pill" );
m_vOriScale = m_vScale;
m_IsCanShot = false;
this->AddChild( (cBaseObject*)
_GETSINGLE( cSystemMgr )->SetTimer( this, 1.0f, TT_SHOT ) );
}
void cVirus::Update()
{
m_vRotation.y += 0.25f * D3DX_PI * _GETSINGLE( cSystemMgr )->GetDeltaTime();
cMonster::Update();
m_IsGrow = false;
if( m_vPos.z < 125.0f && m_vPos.z > 10.0f )
{
m_vDirection.z = -1.0f;
VirusShot();
m_vDirection.z = 0.0f;
}
else
{
m_vDirection.z = -1.0f;
}
}
void cVirus::VirusShot()
{
if( m_IsCanShot )
{
D3DXVECTOR3 vPos = m_vPos;
m_IsGrow = true;
switch ( rand() % 3 )
{
case 0:
m_fShotRot = 0.5f;
m_fShotCoolTime = 0.3f;
m_vPos.x -= 0.3f;
Shot( OI_PLAYER, 1, true);
m_vPos.x += 0.6f;
Shot( OI_PLAYER, 1, false);
m_vPos = vPos;
break;
case 1:
m_fShotRot = 1.0f;
m_fShotCoolTime = 4.0f;
Shot( OI_PLAYER, 20, true );
break;
case 2:
m_fShotCoolTime = 0.6f;
m_fShotRot = 0.3f;
Shot( OI_PLAYER, 4, true );
break;
}
}
}
void cVirus::Render()
{
_GETSINGLE( cObjMgr )->m_fLighting = 0.75f;
cMonster::Render();
_GETSINGLE( cObjMgr )->m_fLighting = 1.0f;
}
|
//------------------------------------------------------------------------------
// ConicalSensor
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool.
//
// Copyright (c) 2002 - 2015 United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration.
// All Other Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
// http://www.apache.org/licenses/LICENSE-2.0.
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language
// governing permissions and limitations under the License.
//
// Author: Wendy Shoan, NASA/GSFC
// Created: 2016.05.03
//
/**
* Definition of the Conical Sensor class. This class modles a conical sensor.
*/
//------------------------------------------------------------------------------
#ifndef ConicalSensor_hpp
#define ConicalSensor_hpp
#include "gmatdefs.hpp"
#include "OrbitState.hpp"
#include "AbsoluteDate.hpp"
class ConicalSensor
{
public:
// class methods
ConicalSensor(Real fov);
ConicalSensor( const ConicalSensor ©);
ConicalSensor& operator=(const ConicalSensor ©);
virtual ~ConicalSensor();
virtual void SetFieldOfView(Real fov);
virtual Real GetFieldOfView();
protected:
/// Field-of-View (radians)
Real fieldOfView;
};
#endif // ConicalSensor_hpp
|
#pragma once
#include <array>
#include "../exceptions.hpp"
#include "DomainBase.hpp"
#include "PointSet.hpp"
#include "types.hpp"
namespace fantom
{
template < size_t Dim >
DomainBase::Bounds computeBounds( const ValueArray< Tensor< double, Dim > >& points )
{
if( auto p = dynamic_cast< const PointSetRectilinear< Dim >* >( &points ) )
{
return p->getBounds();
}
if( auto p = dynamic_cast< const PointSetUniform< Dim >* >( &points ) )
{
return p->getBounds();
}
Tensor< double, Dim > pMin, pMax;
for( size_t d = 0; d != Dim; ++d )
{
pMin[d] = std::numeric_limits< double >::max();
pMax[d] = -pMin[d];
}
for( size_t i = 0; i < points.size(); ++i )
{
Tensor< double, Dim > value = points[i];
for( size_t d = 0; d != Dim; ++d )
{
pMin[d] = std::min( pMin[d], value[d] );
pMax[d] = std::max( pMax[d], value[d] );
}
}
std::vector< std::pair< double, double > > bounds;
for( size_t d = 0; d != Dim; ++d )
{
bounds.push_back( std::make_pair( pMin[d], pMax[d] ) );
}
return DomainBase::Bounds( std::move( bounds ) );
}
//----------------------------------- DiscreteDomain -------------------------------------
/// representation of a discrete domain \ingroup commit
/**
* The purpose of this class is to store a point set.
* It also holds meta information about the structuring of the point set.
* \tparam D geometric dimension of the domain.
* \throw fantom::out_of_range when accessing invalid indices (only in debug build)
* \note All members are thread-safe.
*/
template < size_t D >
class DiscreteDomain : public DomainBase
{
typedef RTTI_Info< DiscreteDomain< D >, DomainBase, All_DiscreteDomain > TypeInfo;
TYPE_INFORMATION( "Discrete " + types::DimensionName< D >() + " Domain" )
friend class DomainFactory;
public:
/// control point type
typedef Tensor< double, D > Point;
/// Creates discrete domain
/**
* \param numExtents number of structuring dimensions
* \param extents the extent of every structuring dimension
* \param points the point set
* \pre The positions in \a points are ordered by structuring dimensions (if any).
* The first dimension is incremented first, then the second, then the third and so on.
*/
DiscreteDomain( size_t numExtents, const size_t extents[], std::unique_ptr< ValueArray< Point > > points )
: DomainBase()
, mExtents( extents, &extents[numExtents] )
, mPoints( std::move( points ) )
, mBounds( computeBounds( *mPoints ) )
{
}
/// Creates a subdomain
/**
* \param parent the parent of this dataset.
* \param indices the indices of the parent domain to keep in the subset.
* \pre No entry in \a indices is larger
* than the number of points in the parent domain.
* \post Parent domain indices have been replaced by subset domain
* indices in \a indices.
*
* Note: \a indices do not need to be duplicate free. Therefore, it is possible to pass the index list of a cell
*complex
* into this function. The vertex indices corresponding to indices of the parent domain
* will then be converted to vertex indices corresponding to the equivalent indices of the sub domain.
*/
DiscreteDomain( std::shared_ptr< const DiscreteDomain< D > > parent, std::vector< size_t >& indices )
: DomainBase()
, mPoints( new SubValueArrayMaster< Point >( parent->mPoints, makeLookup( indices ) ) )
, mBounds( computeBounds( *mPoints ) )
{
}
virtual const Bounds& getBounds() const override
{
return mBounds;
}
/// Determines the number of structuring dimensions, 0 if unstructured.
virtual size_t numStructuringDimensions() const
{
return mExtents.size();
}
/// Determines the extent of the given structuring dimension
/**
* \param dimension the extent's index.
* \pre 0 <= \a i < \c numExtents().
*/
size_t structuringDimensionExtent( size_t dimension ) const
{
#ifndef NDEBUG
if( dimension >= numStructuringDimensions() )
throw fantom::out_of_range( "Unknown structuring dimension: "
+ lexical_cast< std::string >( dimension ) );
#endif
return mExtents[dimension];
}
virtual bool isBounded() const override
{
return true;
}
/// Determines the number of control points.
virtual size_t numPoints() const
{
return mPoints->size();
}
/// Determines the control points.
/// The positions in the ValueArray are ordered by structuring dimensions (if any).
/// The first dimension is incremented first, then the second, then the third and so on.
virtual const ValueArray< Point >& points() const
{
return *mPoints;
}
/// Converts structured coordinates into an index useable in the points() ValueArray
template < size_t SD >
size_t indexFromCoordinates( const std::array< size_t, SD >& coordinates ) const
{
if( SD != numStructuringDimensions() )
throw fantom::out_of_range( "Wrong number of coordinates!" );
size_t result = 0;
for( size_t i = SD; i > 0; --i )
{
result *= mExtents[i - 1];
result += coordinates[i - 1];
}
return result;
}
virtual StructuringType structuringType() const
{
if( numStructuringDimensions() == 0 )
return StructuringType::UNSTRUCTURED;
if( dynamic_cast< const PointSetUniform< D >* >( mPoints.get() ) )
return StructuringType::UNIFORM;
else if( dynamic_cast< const PointSetRectilinear< D >* >( mPoints.get() ) )
return StructuringType::RECTILINEAR;
else
return StructuringType::CURVILINEAR;
}
/**
* @copydoc DataObject::getInfoStrings()
*/
virtual std::vector< std::pair< std::string, std::string > > getInfoStrings() const override
{
std::vector< std::pair< std::string, std::string > > infoStrings = DomainBase::getInfoStrings();
infoStrings.emplace_back( "structuring", structuringTypeNames[(unsigned char)this->structuringType()] );
infoStrings.emplace_back( "numStructuringDimensions",
lexical_cast< std::string >( numStructuringDimensions() ) );
for( size_t d = 0; d < numStructuringDimensions(); ++d )
{
infoStrings.emplace_back( "extent[" + lexical_cast< std::string >( d ) + "]",
lexical_cast< std::string >( structuringDimensionExtent( d ) ) );
}
infoStrings.emplace_back( "numPoints", lexical_cast< std::string >( numPoints() ) );
return infoStrings;
}
protected:
/**
* Copy constructor.
* Internal use only!
*
* \internal
*/
DiscreteDomain( const DiscreteDomain< D >& rhs )
: DomainBase()
, mExtents( rhs.mExtents )
, mPoints( rhs.mPoints )
, mBounds( rhs.mBounds )
{
}
// metadata about the structuring of the points
const std::vector< size_t > mExtents;
private:
// value array of the points
std::shared_ptr< const ValueArray< Point > > mPoints;
Bounds mBounds;
};
extern template class DiscreteDomain< 2 >;
extern template class DiscreteDomain< 3 >;
}
|
#pragma once
#include "Unit.h"
/**Class that derives from Unit. It has special abilites for cavalry. */
class Cavalry :
public Unit
{
public:
/*Constructor for Cavalry*/
Cavalry();
/*Destructor for Cavalry*/
~Cavalry();
/*The method returns the unit type as the first character of the unit name*/
char type_of_unit();
/*The metods calculates and returns the power of unit*/
int battle_value();
};
|
#pragma once
#include "ArgumentForwardIter.hpp"
#include <iterator>
#include <vector>
#include <cstring>
class Arguments
{
public:
Arguments(int argc, char** argv)
{
for(int i = 0; i < argc; i++)
{
m_argv.emplace_back(argv[i]);
}
}
ArgumentForwardIter Begin() const
{
return m_argv.data();
}
ArgumentForwardIter End() const
{
return m_argv.data() + m_argv.size();
}
unsigned Count() const { return m_argv.size(); }
private:
std::vector<std::string> m_argv;
};
inline bool ArgCmp(const std::string& arg, const std::string& longName, const std::string& shortName = "")
{
return std::strcmp(arg.c_str(), longName.c_str()) == 0 || std::strcmp(arg.c_str(), shortName.c_str()) == 0;
}
|
#include "Bit_Field.h"
void main()
{
ExampleFile();
}
|
//
// Created by 梁栋 on 2019-11-22.
//
#include <string>
#include <iostream>
using namespace std;
class Solution {
public:
int lengthOfLastWord(string s) {
int len = s.length();
if(len == 0)
return 0;
while(s[len-1] == ' '){
s = s.substr(0, len-1);
len = len-1;
}
int countSpace = 0;
for(auto c: s){
if(c == ' ')
countSpace += 1;
}
if(countSpace == len)
return 0;
int result = len;
cout<<"result init is "<<result<<endl;
cout<<len<<endl;
for(int i=0;i<len;i++){
if(countSpace == 0){
break;
}
if(s[i] == ' '){
countSpace --;
result --;
}else{
result--;
}
}
return result;
}
static void solution(){
Solution solution1;
cout<<solution1.lengthOfLastWord("a ");
}
};
|
#ifndef ASSIGN_H
#define ASSIGN_H
#include <iostream>
#include <string>
#include "statement.h"
#include "expression.h"
#include "lexp.h"
#include "../visitors/treevisitor.h"
using namespace std;
class Assignment: public Statement {
public:
Assignment(LExpression* target, Expression* exp):
target_(target),exp_(exp) { }
virtual ~Assignment();
virtual ostream& prettyPrint(ostream& os = cout,int indent=0) const;
virtual string toString() const;
virtual void accept(TreeVisitor* v) {
v->visitAssignment(this);
}
//accessors
LExpression* target() const { return target_; }
Expression* expression() const { return exp_; }
//mutators
void setTarget(LExpression* newTarget);
void setExpression(Expression* newExpression);
private:
LExpression* target_; /**< variable of array to be assigned to */
Expression* exp_; /**< expression to evaluate and assign */
};
#endif
|
/*************************************************************
* > File Name : CF1248A.cpp
* > Author : Tony
* > Created Time : 2019/10/21 16:43:01
* > Algorithm :
**************************************************************/
#include <bits/stdc++.h>
using namespace std;
inline long long read() {
long long x = 0; long long 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;
}
int main() {
long long T = read();
while (T--) {
long long n = read(), p0 = 0, p1 = 0, q0 = 0, q1 = 0;
for (long long i = 1; i <= n; ++i) {
long long p = read();
if (p % 2 == 0) p0++;
else p1++;
}
long long m = read();
for (long long i = 1; i <= m; ++i) {
long long q = read();
if (q % 2 == 0) q0++;
else q1++;
}
printf("%lld\n", p0 * q0 + p1 * q1);
}
return 0;
}
|
/*
pxCore Copyright 2005-2021 John Robinson
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// pxSharedContextNative.cpp
#include "rtLog.h"
#include "rtMutex.h"
#include "pxSharedContext.h"
#include "windows.h"
#include "pxSharedContextNative.h"
void pxSharedContext::makeCurrent(bool f) {
pxSharedContextNative::makeCurrent(f);
}
pxSharedContextNative::pxSharedContextNative() {
mHDC = wglGetCurrentDC();
mOriginalGLContext = wglGetCurrentContext();
mGLContext = wglCreateContext(mHDC);
wglShareLists(mOriginalGLContext, mGLContext);
}
pxSharedContextNative::~pxSharedContextNative() {
if (mGLContext)
wglDeleteContext(mGLContext);
}
void pxSharedContextNative::makeCurrent(bool f) {
wglMakeCurrent(mHDC, f?mGLContext:mOriginalGLContext);
}
|
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include "globals.h"
#include "mc68328.h"
#include ".obj/stubs/getsp_stub.h"
void cmd_getsp(char** argv)
{
if (argv[0])
error("syntax error: getsp");
Bytes stub(_obj_stubs_getsp_bin, _obj_stubs_getsp_bin_len);
pad_with_nops(stub);
brecord_write(0xffffffc0, stub.size(), &stub[0]);
brecord_execute(0xffffffc0);
Bytes data;
data.resize(8);
for (int i=0; i<8; i++)
data[i] = recvbyte();
printf("SP = %08x\n", readbe32(&data[0]));
printf("USP = %08x\n", readbe32(&data[4]));
}
|
#include <bits/stdc++.h>
using namespace std;
class RLEIterator
{
public:
RLEIterator(vector<int> &A)
{
evector.assign(A.begin(), A.end());
}
int next(int n)
{
int count = 0, ssize = evector.size(), i = 0, minus = 0, ret = -1;
for (; i < ssize - 1; i = i + 2)
{
if (evector[i] == 0)
continue;
if (n - count > evector[i])
{
count += evector[i];
continue;
}
else if (n - count == evector[i])
{
count += evector[i];
ret = evector[i + 1];
i = i + 2;
break;
}
else if (n - count < evector[i])
{
minus = n - count;
count = n;
ret = evector[i + 1];
break;
}
}
if (count != n)
{
evector.clear();
return ret;
}
evector.erase(evector.begin(), evector.begin() + i);
evector[0] -= minus;
cout << "nums: " << evector[0] << " now: " << evector[1] << endl;
return ret;
}
private:
vector<int> evector;
};
/**
* Your RLEIterator object will be instantiated and called as such:
* RLEIterator* obj = new RLEIterator(A);
* int param_1 = obj->next(n);
*/
|
#include "randomizer_world.hpp"
#include "world_teleport_tree.hpp"
#include "spawn_location.hpp"
#include <landstalker-lib/model/world.hpp>
#include <landstalker-lib/tools/game_text.hpp>
#include <landstalker-lib/exceptions.hpp>
#include "world_node.hpp"
#include "world_path.hpp"
#include "world_region.hpp"
#include "hint_source.hpp"
// Include headers automatically generated from model json files
#include "data/item.json.hxx"
#include "data/item_source.json.hxx"
#include "data/world_node.json.hxx"
#include "data/world_path.json.hxx"
#include "data/world_region.json.hxx"
#include "data/spawn_location.json.hxx"
#include "data/hint_source.json.hxx"
#include "data/world_teleport_tree.json.hxx"
#include "landstalker-lib/tools/stringtools.hpp"
#include <iostream>
RandomizerWorld::RandomizerWorld() :
World()
{
// Add "standard" gold items which can be used through item distribution
this->add_item(new ItemGolds(ITEM_1_GOLD, 1));
this->add_item(new ItemGolds(ITEM_20_GOLDS, 20));
this->add_item(new ItemGolds(ITEM_50_GOLDS, 50));
this->add_item(new ItemGolds(ITEM_100_GOLDS, 100));
this->add_item(new ItemGolds(ITEM_200_GOLDS, 200));
}
RandomizerWorld::~RandomizerWorld()
{
for (ItemSource* source : _item_sources)
delete source;
for (auto& [key, node] : _nodes)
delete node;
for (WorldPath* path : _paths)
delete path;
for (WorldRegion* region : _regions)
delete region;
for (HintSource* hint_source : _hint_sources)
delete hint_source;
for (auto& [key, spawn_loc] : _available_spawn_locations)
delete spawn_loc;
for (auto& [tree_1, tree_2] : _teleport_tree_pairs)
{
delete tree_1;
delete tree_2;
}
for(Item* item : _archipelago_items)
delete item;
}
ItemSource* RandomizerWorld::item_source(const std::string& name) const
{
for (ItemSource* source : _item_sources)
if (source->name() == name)
return source;
throw std::out_of_range("No source with given name");
}
std::vector<ItemSource*> RandomizerWorld::item_sources_with_item(Item* item)
{
std::vector<ItemSource*> sources_with_item;
for (ItemSource* source : _item_sources)
if (source->item() == item)
sources_with_item.emplace_back(source);
return sources_with_item;
}
std::array<std::string, ITEM_COUNT> RandomizerWorld::item_names() const
{
std::array<std::string, ITEM_COUNT> item_names;
for(uint8_t i=0 ; i<ITEM_COUNT ; ++i)
{
try
{
item_names[i] = this->item(i)->name();
}
catch(std::out_of_range&)
{
item_names[i] = "No" + std::to_string(i);
}
}
return item_names;
}
void RandomizerWorld::load_item_sources()
{
Json item_sources_json = Json::parse(ITEM_SOURCES_JSON);
for(const Json& source_json : item_sources_json)
{
_item_sources.emplace_back(ItemSource::from_json(source_json, *this));
}
#ifdef DEBUG
std::cout << _item_sources.size() << " item sources loaded." << std::endl;
#endif
// The following chests are absent from the game on release or modded out of the game for the rando, and their IDs are therefore free:
// 0x0E (14): Mercator Kitchen (variant?)
// 0x1E (30): King Nole's Cave spiral staircase (variant with enemies?) ---> 29 is the one used in rando
// 0x20 (32): Boulder chase hallway (variant with enemies?) ---> 31 is the one used in rando
// 0x25 (37): Thieves Hideout entrance (variant with water)
// 0x27 (39): Thieves Hideout entrance (waterless variant)
// 0x28 (40): Thieves Hideout entrance (waterless variant)
// 0x33 (51): Thieves Hideout second room (waterless variant)
// 0x3D (61): Thieves Hideout reward room (Kayla cutscene variant)
// 0x3E (62): Thieves Hideout reward room (Kayla cutscene variant)
// 0x3F (63): Thieves Hideout reward room (Kayla cutscene variant)
// 0x40 (64): Thieves Hideout reward room (Kayla cutscene variant)
// 0x41 (65): Thieves Hideout reward room (Kayla cutscene variant)
// 0xBB (187): Crypt (Larson. E room)
// 0xBC (188): Crypt (Larson. E room)
// 0xBD (189): Crypt (Larson. E room)
// 0xBE (190): Crypt (Larson. E room)
// 0xC3 (195): Map 712 / 0x2C8 ???
}
WorldPath* RandomizerWorld::path(WorldNode* origin, WorldNode* destination)
{
for(WorldPath* path : _paths)
if(path->origin() == origin && path->destination() == destination)
return path;
return nullptr;
}
WorldPath* RandomizerWorld::path(const std::string& origin_name, const std::string& destination_name)
{
WorldNode* origin = _nodes.at(origin_name);
WorldNode* destination = _nodes.at(destination_name);
return this->path(origin, destination);
}
void RandomizerWorld::add_path(WorldPath* path)
{
_paths.emplace_back(path);
}
WorldRegion* RandomizerWorld::region(const std::string& name) const
{
for(WorldRegion* region : _regions)
if(region->name() == name)
return region;
return nullptr;
}
std::vector<std::string> RandomizerWorld::spawn_location_names() const
{
std::vector<std::string> ret;
for(auto& [name, _] : _available_spawn_locations)
ret.emplace_back(name);
return ret;
}
void RandomizerWorld::add_spawn_location(SpawnLocation* spawn)
{
_available_spawn_locations[spawn->id()] = spawn;
}
void RandomizerWorld::dark_region(WorldRegion* region)
{
_dark_region = region;
this->dark_maps(region->dark_map_ids());
for(WorldNode* node : region->nodes())
{
for (WorldPath* path : node->ingoing_paths())
if(path->origin()->region() != region)
path->add_required_item(this->item(ITEM_LANTERN));
node->add_hint("in a very dark place");
}
}
void RandomizerWorld::add_custom_dialogue(Entity* entity, const std::string& text)
{
_custom_dialogues[entity] = GameText(text).get_output();
}
void RandomizerWorld::add_custom_dialogue_raw(Entity* entity, const std::string& text)
{
_custom_dialogues[entity] = text;
}
void RandomizerWorld::add_paths_for_tree_connections(bool require_tibor_access)
{
std::vector<WorldNode*> required_nodes;
if(require_tibor_access)
required_nodes = { this->node("tibor") };
for(auto& pair : _teleport_tree_pairs)
{
WorldNode* first_node = this->node(pair.first->node_id());
WorldNode* second_node = this->node(pair.second->node_id());
this->add_path(new WorldPath(first_node, second_node, 1, {}, required_nodes));
this->add_path(new WorldPath(second_node, first_node, 1, {}, required_nodes));
}
}
Item* RandomizerWorld::add_archipelago_item(const std::string& name, const std::string& player_name, bool use_shop_naming)
{
constexpr size_t MAX_PLAYER_NAME_SIZE = 10;
const std::set<char> VOWELS = { 'a', 'e', 'i', 'o', 'u', 'y', 'A', 'E', 'I', 'O', 'U', 'Y' };
size_t max_full_string_size = (use_shop_naming) ? 30 : 38;
// Shorten player name if needed
std::string shortened_player_name = player_name;
if(shortened_player_name.size() > MAX_PLAYER_NAME_SIZE)
shortened_player_name = player_name.substr(0, MAX_PLAYER_NAME_SIZE-1) + ".";
// Use all the remaining space for item name
size_t max_item_name_size = max_full_string_size - shortened_player_name.size();
// If the item name is too long, try truncating individual words to keep the global meaning
std::string shortened_item_name = name;
std::vector<std::string> words = stringtools::split_with_delims(shortened_item_name, { ' ', '-', '(', ')' });
size_t current_word_index = 0;
while(shortened_item_name.size() > max_item_name_size && current_word_index < words.size())
{
std::string& current_word = words[current_word_index];
if(current_word.size() > 4)
{
for(size_t i = 1 ; i < current_word.size() - 3 ; ++i)
{
if(VOWELS.contains(current_word[i]) && !VOWELS.contains(current_word[i + 1]))
{
current_word = current_word.substr(0, i+2) + ".";
if(current_word_index + 1 < words.size() && words[current_word_index + 1] == " ")
words.erase(words.begin() + ((int)current_word_index + 1));
break;
}
}
}
++current_word_index;
shortened_item_name = stringtools::join(words, "");
}
// If after shortening individual words, the global name is still too long, just truncate it
if(shortened_item_name.size() > max_item_name_size)
shortened_item_name = shortened_item_name.substr(0, max_item_name_size-1) + ".";
std::string formatted_name;
if(use_shop_naming)
formatted_name = shortened_player_name + "'s " + shortened_item_name;
else
formatted_name = shortened_item_name + " to " + shortened_player_name;
for(Item* item : _archipelago_items)
if(item->name() == formatted_name)
return item;
Item* new_item = new Item(ITEM_ARCHIPELAGO, formatted_name, 0, 0, 0, 0);
_archipelago_items.emplace_back(new_item);
return new_item;
}
void RandomizerWorld::spawn_location(const SpawnLocation* spawn)
{
_spawn_location = spawn;
this->spawn_map_id(spawn->map_id());
this->spawn_position_x(spawn->position_x());
this->spawn_position_y(spawn->position_y());
this->spawn_orientation(spawn->orientation());
if(this->starting_life() == 0)
this->starting_life(spawn->starting_life());
}
HintSource* RandomizerWorld::hint_source(const std::string& name) const
{
for(HintSource* source : _hint_sources)
if(source->description() == name)
return source;
throw LandstalkerException("Could not find hint source '" + name + "' as requested");
}
void RandomizerWorld::load_model_from_json()
{
this->load_additional_item_data();
this->load_item_sources();
this->load_nodes();
this->load_paths();
this->load_regions();
this->load_spawn_locations();
this->load_hint_sources();
this->load_teleport_trees();
}
void RandomizerWorld::load_nodes()
{
Json nodes_json = Json::parse(WORLD_NODES_JSON);
for(auto& [node_id, node_json] : nodes_json.items())
{
WorldNode* new_node = WorldNode::from_json(node_id, node_json);
_nodes[node_id] = new_node;
}
for(ItemSource* source : this->item_sources())
{
const std::string& node_id = source->node_id();
try {
_nodes.at(node_id)->add_item_source(source);
} catch(std::out_of_range&) {
throw LandstalkerException("Could not find node '" + node_id + "' referenced by item source '" + source->name() + "'");
}
}
#ifdef DEBUG
std::cout << _nodes.size() << " nodes loaded." << std::endl;
#endif
}
void RandomizerWorld::load_paths()
{
Json paths_json = Json::parse(WORLD_PATHS_JSON);
for(const Json& path_json : paths_json)
{
this->add_path(WorldPath::from_json(path_json, _nodes, this->items()));
if(path_json.contains("twoWay") && path_json.at("twoWay"))
{
Json inverted_json = path_json;
inverted_json["fromId"] = path_json.at("toId");
inverted_json["toId"] = path_json.at("fromId");
this->add_path(WorldPath::from_json(inverted_json, _nodes, this->items()));
}
}
#ifdef DEBUG
std::cout << _paths.size() << " paths loaded." << std::endl;
#endif
}
void RandomizerWorld::load_regions()
{
Json regions_json = Json::parse(WORLD_REGIONS_JSON);
for(const Json& region_json : regions_json)
_regions.emplace_back(WorldRegion::from_json(region_json, _nodes));
#ifdef DEBUG
std::cout << _regions.size() << " regions loaded." << std::endl;
#endif
for(auto& [id, node] : _nodes)
if(node->region() == nullptr)
throw LandstalkerException("Node '" + node->id() + "' doesn't belong to any region");
}
void RandomizerWorld::load_spawn_locations()
{
// Load base model
Json spawns_json = Json::parse(SPAWN_LOCATIONS_JSON);
for(auto& [id, spawn_json] : spawns_json.items())
this->add_spawn_location(SpawnLocation::from_json(id, spawn_json));
#ifdef DEBUG
std::cout << _available_spawn_locations.size() << " spawn locations loaded." << std::endl;
#endif
}
void RandomizerWorld::load_hint_sources()
{
Json hint_sources_json = Json::parse(HINT_SOURCES_JSON, nullptr, true, true);
for(const Json& hint_source_json : hint_sources_json)
{
HintSource* new_source = HintSource::from_json(hint_source_json, _nodes);
_hint_sources.emplace_back(new_source);
}
#ifdef DEBUG
std::cout << _hint_sources.size() << " hint sources loaded." << std::endl;
#endif
}
void RandomizerWorld::load_teleport_trees()
{
Json trees_json = Json::parse(WORLD_TELEPORT_TREES_JSON);
for(const Json& tree_pair_json : trees_json)
{
WorldTeleportTree* tree_1 = WorldTeleportTree::from_json(tree_pair_json[0]);
WorldTeleportTree* tree_2 = WorldTeleportTree::from_json(tree_pair_json[1]);
tree_1->paired_map_id(tree_2->map_id());
tree_2->paired_map_id(tree_1->map_id());
_teleport_tree_pairs.emplace_back(std::make_pair(tree_1, tree_2));
}
#ifdef DEBUG
std::cout << _teleport_tree_pairs.size() << " teleport tree pairs loaded." << std::endl;
#endif
}
void RandomizerWorld::load_additional_item_data()
{
Json items_json = Json::parse(ITEMS_JSON);
for(auto& [id_string, item_json] : items_json.items())
{
uint8_t id = std::stoi(id_string);
this->item(id)->apply_json(item_json);
}
}
|
/**
* Prevents object from implementing copy operations.
* class foo : public noncopyable {
* };
*
*/
#ifndef FISHY_NON_COPYABLE_H
#define FISHY_NON_COPYABLE_H
namespace core {
namespace util {
/**
* Classes inheriting from this will result in compile errors
* if they are attempted to be copied.
*/
class noncopyable {
public:
noncopyable() {}
private:
noncopyable(const noncopyable &) {}
noncopyable &operator=(const noncopyable &) { return *this; }
};
} // namespace util
} // namespace core
#endif
|
#ifndef Plane_h
#define Plane_h
#include "Geometry.hpp"
class Plane : public Geometry {
public:
Plane(float size) {
this->size = size;
indicesNum = 0;
boundingBoxLength = size;
}
void createVBOs() {
int vertexBufferLen, indexBufferLen;
getPlaneVbIbLen(vertexBufferLen, indexBufferLen);
std::vector<Vertex> vtx(vertexBufferLen);
std::vector<unsigned short> idx(indexBufferLen);
makePlane(size, vtx.begin(), idx.begin());
Geometry::createVBOs(vtx, idx);
}
protected:
float size;
};
#endif /* Plane_h */
|
// clang-format off
/* =============================================================================
* BEGIN Template file SIMPLModuleCodeTemplate.in.cpp
* ========================================================================== */
#include <pybind11/numpy.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl_bind.h>
#include <pybind11/stl.h>
PYBIND11_MAKE_OPAQUE(std::vector<int8_t>);
PYBIND11_MAKE_OPAQUE(std::vector<uint8_t>);
PYBIND11_MAKE_OPAQUE(std::vector<int16_t>);
PYBIND11_MAKE_OPAQUE(std::vector<uint16_t>);
PYBIND11_MAKE_OPAQUE(std::vector<int32_t>);
PYBIND11_MAKE_OPAQUE(std::vector<uint32_t>);
PYBIND11_MAKE_OPAQUE(std::vector<int64_t>);
PYBIND11_MAKE_OPAQUE(std::vector<uint64_t>);
PYBIND11_MAKE_OPAQUE(std::vector<float>);
PYBIND11_MAKE_OPAQUE(std::vector<double>);
/*
* Linux does not like the below line because unsigned long int and size_t are
* the same thing. Apple (clang) and Windows (MSVC) do not seem to have a problem
* with the line.
*/
#if defined(__APPLE__)
PYBIND11_MAKE_OPAQUE(std::vector<size_t>);
#endif
#include <utility>
#include <QtCore/QDateTime>
#include <QtCore/QString>
#include "SIMPLib/Common/PhaseType.h"
#include "SIMPLib/Common/ShapeType.h"
#include "SIMPLib/CoreFilters/ArrayCalculator.h"
#include "SIMPLib/CoreFilters/ImportHDF5Dataset.h"
#include "SIMPLib/FilterParameters/AxisAngleInput.h"
#include "SIMPLib/FilterParameters/FileListInfo.h"
#include "SIMPLib/FilterParameters/ThirdOrderPolynomial.h"
namespace py = pybind11;
PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>);
//PYBIND11_MAKE_OPAQUE(DataContainersMap)
//PYBIND11_MAKE_OPAQUE(AttributeMatricesMap)
#include "Templates/Pybind11CustomTypeCasts.in.h"
#ifndef PySharedPtrClass_TEMPLATE
#define PySharedPtrClass_TEMPLATE
template <typename T> using PySharedPtrClass = py::class_<T, std::shared_ptr<T>>;
#endif
/******************************************************************************
* This is a list of all the SIMPL headers that are needed/wrapped by Pybind11
******************************************************************************/
@HEADER_PATH@
/******************************************************************************
*
******************************************************************************/
#include "SIMPLib/DataArrays/DataArray.hpp"
#include "SIMPLib/Common/SIMPLArray.hpp"
/**
* @brief Initializes a template specialization of DataArray<T>
* @param T The Type
* @param NAME The name of the Variable
*/
#define PYB11_DEFINE_DATAARRAY_INIT(T, NAME) \
PySharedPtrClass<DataArray<T>> declare##NAME(py::module& m, PySharedPtrClass<IDataArray>& parent) \
{ \
using DataArrayType = DataArray<T>; \
PySharedPtrClass<DataArrayType> instance(m, #NAME, parent, py::buffer_protocol()); \
instance.def(py::init([](size_t numElements, QString name, T initValue) { return std::shared_ptr<DataArrayType>(new DataArrayType(numElements, name, initValue)); })) \
.def(py::init([](T* ptr, size_t numElements, std::vector<size_t> cDims, QString name, bool ownsData) { \
return DataArrayType::WrapPointer(ptr, numElements, cDims, name, ownsData); \
})) \
.def(py::init([](py::array_t<T, py::array::c_style> b, std::vector<size_t> cDims, QString name, bool ownsData) { \
ssize_t numElements = 1; \
ssize_t nDims = b.ndim(); \
for(ssize_t e = 0; e < nDims; e++) \
{ \
numElements *= b.shape(e); \
} \
numElements /= cDims[0]; \
return DataArrayType::WrapPointer(reinterpret_cast<T*>(b.mutable_data(0)), static_cast<size_t>(numElements), cDims, name, ownsData); \
})) /* Class instance method setValue */ \
.def("setValue", &DataArrayType::setValue, py::arg("index"), py::arg("value")) \
.def("getValue", &DataArrayType::getValue, py::arg("index")) \
.def_property("Data", &DataArrayType::getArray, &DataArrayType::setArray, py::return_value_policy::reference) \
.def_property("Name", &DataArrayType::getName, &DataArrayType::setName) \
.def("Cleanup", []() { return DataArrayType::NullPointer(); }); \
; \
return instance; \
}
PYB11_DEFINE_DATAARRAY_INIT(int8_t, Int8ArrayType);
PYB11_DEFINE_DATAARRAY_INIT(uint8_t, UInt8ArrayType);
PYB11_DEFINE_DATAARRAY_INIT(int16_t, Int16ArrayType);
PYB11_DEFINE_DATAARRAY_INIT(uint16_t, UInt16ArrayType);
PYB11_DEFINE_DATAARRAY_INIT(int32_t, Int32ArrayType);
PYB11_DEFINE_DATAARRAY_INIT(uint32_t, UInt32ArrayType);
PYB11_DEFINE_DATAARRAY_INIT(int64_t, Int64ArrayType);
PYB11_DEFINE_DATAARRAY_INIT(uint64_t, UInt64ArrayType);
PYB11_DEFINE_DATAARRAY_INIT(float, FloatArrayType);
PYB11_DEFINE_DATAARRAY_INIT(double, DoubleArrayType);
#define PYB11_DEFINE_SIMPLARRAY_2_INIT(T, NAME)\
py::class_<NAME>(mod, #NAME)\
.def(py::init<>([](py::list values) {\
NAME vec = NAME(py::cast<T>(values[0]), py::cast<T>(values[1]));\
return vec;\
}))\
.def("__repr__", [](const NAME &inValues) {\
py::list outValues;\
for (T value : inValues) { outValues.append(value); }\
return outValues;\
})\
.def("__str__", [](const NAME &inValues) {\
py::list outValues;\
for (T value : inValues) { outValues.append(value); }\
return py::str(outValues);\
})\
.def("__getitem__", [](const NAME &values, int index) {\
return values[index];\
})\
;
#define PYB11_DEFINE_SIMPLARRAY_3_INIT(T, NAME)\
py::class_<NAME>(mod, #NAME)\
.def(py::init<>([](py::list values) {\
NAME vec = NAME(py::cast<T>(values[0]), py::cast<T>(values[1]), py::cast<T>(values[2]));\
return vec;\
}))\
.def("__repr__", [](const NAME &inValues) {\
py::list outValues;\
for (T value : inValues) { outValues.append(value); }\
return outValues;\
})\
.def("__str__", [](const NAME &inValues) {\
py::list outValues;\
for (T value : inValues) { outValues.append(value); }\
return py::str(outValues);\
})\
.def("__getitem__", [](const NAME &values, int index) {\
return values[index];\
})\
;
#define PYB11_DEFINE_SIMPLARRAY_4_INIT(T, NAME)\
py::class_<NAME>(mod, #NAME)\
.def(py::init<>([](py::list values) {\
NAME vec = NAME(py::cast<T>(values[0]), py::cast<T>(values[1]), py::cast<T>(values[2]), py::cast<T>(values[3]));\
return vec;\
}))\
.def("__repr__", [](const NAME &inValues) {\
py::list outValues;\
for (T value : inValues) { outValues.append(value); }\
return outValues;\
})\
.def("__str__", [](const NAME &inValues) {\
py::list outValues;\
for (T value : inValues) { outValues.append(value); }\
return py::str(outValues);\
})\
.def("__getitem__", [](const NAME &values, int index) {\
return values[index];\
})\
;
#define PYB11_DEFINE_SIMPLARRAY_6_INIT(T, NAME)\
py::class_<NAME>(mod, #NAME)\
.def(py::init<>([](py::list values) {\
NAME vec = NAME(py::cast<T>(values[0]), py::cast<T>(values[1]), py::cast<T>(values[2]), py::cast<T>(values[3]), py::cast<T>(values[4]), py::cast<T>(values[5]));\
return vec;\
}))\
.def("__repr__", [](const NAME &inValues) {\
py::list outValues;\
for (T value : inValues) { outValues.append(value); }\
return outValues;\
})\
.def("__str__", [](const NAME &inValues) {\
py::list outValues;\
for (T value : inValues) { outValues.append(value); }\
return py::str(outValues);\
})\
.def("__getitem__", [](const NAME &values, int index) {\
return values[index];\
})\
;
//------------------------------------------------------------------------------
// This header file is auto-generated and contains include directives for each
// cxx file that contains a specific plugins init code.
//------------------------------------------------------------------------------
#include "DREAM3D_SubmoduleHeaders.h"
/**
* @brief PYBIND11_MODULE This section declares our python module, its name and
* what classes are available within the module.
*
*/
PYBIND11_MODULE(dream3d, m)
{
m.doc() = "Python wrapping for dream3d";
/* Define a python submodule for SIMPL */
py::module mod = m.def_submodule("simpl", " Python wrapping for SIMPL");
// SIMPLArray declarations/definitions
PYB11_DEFINE_SIMPLARRAY_2_INIT(float, FloatVec2Type)
PYB11_DEFINE_SIMPLARRAY_2_INIT(int32_t, IntVec2Type)
PYB11_DEFINE_SIMPLARRAY_2_INIT(size_t, SizeVec2Type)
PYB11_DEFINE_SIMPLARRAY_3_INIT(float, FloatVec3Type)
PYB11_DEFINE_SIMPLARRAY_3_INIT(int, IntVec3Type)
PYB11_DEFINE_SIMPLARRAY_3_INIT(size_t, SizeVec3Type)
PYB11_DEFINE_SIMPLARRAY_4_INIT(float, FloatVec4Type)
PYB11_DEFINE_SIMPLARRAY_4_INIT(int, IntVec4Type)
PYB11_DEFINE_SIMPLARRAY_4_INIT(size_t, SizeVec4Type)
PYB11_DEFINE_SIMPLARRAY_6_INIT(float, FloatVec6Type)
PYB11_DEFINE_SIMPLARRAY_6_INIT(int32_t, IntVec6Type)
py::class_<AxisAngleInput_t>(mod, "AxisAngleInput")
.def(py::init< const float &, const float &, const float &, const float &>())
;
py::class_<FileListInfo_t>(mod, "FileListInfo")
.def(py::init <> ([] ( const int & paddingDigits, const unsigned int & ordering, const int & startIndex,
const int & endIndex, const int & incrementIndex, const py::str & inputPath, const py::str & filePrefix,
const py::str & fileSuffix, const py::str &fileExtension)
{
FileListInfo_t fileListInfo;
fileListInfo.PaddingDigits = paddingDigits;
fileListInfo.Ordering = ordering;
fileListInfo.StartIndex = startIndex;
fileListInfo.EndIndex = endIndex;
fileListInfo.IncrementIndex = incrementIndex;
QString InputPath = QString::fromStdString(py::cast<std::string>(inputPath));
QString FilePrefix = QString::fromStdString(py::cast<std::string>(filePrefix));
QString FileSuffix = QString::fromStdString(py::cast<std::string>(fileSuffix));
QString FileExtension = QString::fromStdString(py::cast<std::string>(fileExtension));
fileListInfo.InputPath = InputPath;
fileListInfo.FilePrefix = FilePrefix;
fileListInfo.FileSuffix = FileSuffix;
fileListInfo.FileExtension = FileExtension;
return fileListInfo;
}))
;
#if 0
// Handle QVector of size_t
py::class_<std::vector<size_t>>(mod, "Dims")
.def(py::init<>([](py::list dimensions) {
std::vector<size_t> dims = std::vector<size_t>();
for (auto dimension : dimensions)
{
dims.push_back(py::cast<size_t>(dimension));
}
return dims;
}))
.def("__repr__", [](const std::vector<size_t> &dims) {
py::list dimensions;
for (size_t dim : dims)
{
dimensions.append(dim);
}
return dimensions;
})
.def("__str__", [](const std::vector<size_t> &dims) {
py::list dimensions;
for (size_t dim : dims)
{
dimensions.append(dim);
}
return py::str(dimensions);
})
.def("__getitem__", [](const std::vector<size_t> &dims, int key) {
return dims[key];
})
;
#endif
// Handle QSet of QString
py::class_<QSet<QString>>(mod, "StringSet")
.def(py::init<>([](py::set stringSet) {
QSet<QString> newQStringSet = QSet<QString>();
for (auto newString : stringSet)
{
newQStringSet.insert(py::cast<QString>(newString));
}
return newQStringSet;
}))
;
// Handle QDateTime
py::class_<QDateTime>(mod, "DateTime")
.def(py::init<>([](int year, int month, int day, int seconds) {
QDateTime dateTime(QDate(year, month, day));
dateTime.setTime_t(seconds);
return dateTime;
}))
;
// Handle QJsonArray
py::class_<QJsonArray>(mod, "JsonArray")
.def(py::init<>([](py::list values) {
QJsonArray qJsonArray;
for (auto value : values) {
QJsonValue qJsonValue(py::cast<double>(value));
qJsonArray.push_back(qJsonValue);
}
return qJsonArray;
}))
;
py::class_<QList<ImportHDF5Dataset::DatasetImportInfo>>(mod, "DatasetImportInfoList")
.def(py::init<>([](py::list values) {
QList<ImportHDF5Dataset::DatasetImportInfo> datasetImportInfoList;
for (auto value : values) {
py::list valueAsList = py::cast<py::list>(value);
ImportHDF5Dataset::DatasetImportInfo datasetImportInfo;
datasetImportInfo.dataSetPath = py::cast<QString>(valueAsList[0]);
datasetImportInfo.componentDimensions = py::cast<QString>(valueAsList[1]);
datasetImportInfoList.push_back(datasetImportInfo);
}
return datasetImportInfoList;
}));
/* STL Binding code */
py::bind_vector<std::vector<int8_t>>(mod, "VectorInt8");
py::bind_vector<std::vector<uint8_t>>(mod, "VectorUInt8");
py::bind_vector<std::vector<int16_t>>(mod, "VectorInt16");
py::bind_vector<std::vector<uint16_t>>(mod, "VectorUInt16");
py::bind_vector<std::vector<int32_t>>(mod, "VectorInt32");
py::bind_vector<std::vector<uint32_t>>(mod, "VectorUInt32");
py::bind_vector<std::vector<int64_t>>(mod, "VectorInt64");
py::bind_vector<std::vector<uint64_t>>(mod, "VectorUInt64");
py::bind_vector<std::vector<float>>(mod, "VectorFloat");
py::bind_vector<std::vector<double>>(mod, "VectorDouble");
if(py::detail::get_type_info(typeid(std::vector<size_t>)))
{
mod.attr("VectorSizeT") = mod.attr("VectorUInt64");
}
else
{
py::bind_vector<std::vector<size_t>>(mod, "VectorSizeT");
}
/* Enumeration code for Comparison Operators */
py::enum_<SIMPL::Comparison::Enumeration>(mod, "ComparisonOperators")
.value("LessThan", SIMPL::Comparison::Enumeration::Operator_LessThan)
.value("GreaterThan", SIMPL::Comparison::Enumeration::Operator_GreaterThan)
.value("Equal", SIMPL::Comparison::Enumeration::Operator_Equal)
.value("NotEqual", SIMPL::Comparison::Enumeration::Operator_NotEqual)
.value("Unknown", SIMPL::Comparison::Enumeration::Operator_Unknown)
.export_values();
/* Enumeration code for Delimiter types */
py::enum_<SIMPL::DelimiterTypes::Type>(mod, "DelimiterTypes")
.value("Comma", SIMPL::DelimiterTypes::Type::Comma)
.value("Semicolon", SIMPL::DelimiterTypes::Type::Semicolon)
.value("Colon", SIMPL::DelimiterTypes::Type::Colon)
.value("Tab", SIMPL::DelimiterTypes::Type::Tab)
.value("Space", SIMPL::DelimiterTypes::Type::Space)
.export_values();
/* Enumeration code for PhaseType */
py::enum_<PhaseType::Type>(mod, "PhaseType")
.value("Primary", PhaseType::Type::Primary)
.value("Precipitate", PhaseType::Type::Precipitate)
.value("Transformation", PhaseType::Type::Transformation)
.value("Matrix", PhaseType::Type::Matrix)
.value("Boundary", PhaseType::Type::Boundary)
.value("Unknown", PhaseType::Type::Unknown)
.value("Any", PhaseType::Type::Any)
.export_values();
/* Enumeration code for ShapeType */
py::enum_<ShapeType::Type>(mod, "ShapeType")
.value("Ellipsoid", ShapeType::Type::Ellipsoid)
.value("SuperEllipsoid", ShapeType::Type::SuperEllipsoid)
.value("CubeOctahedron", ShapeType::Type::CubeOctahedron)
.value("CylinderA", ShapeType::Type::CylinderA)
.value("CylinderB", ShapeType::Type::CylinderB)
.value("CylinderC", ShapeType::Type::CylinderC)
.value("ShapeTypeEnd", ShapeType::Type::ShapeTypeEnd)
.value("Unknown", ShapeType::Type::Unknown)
.value("Any", ShapeType::Type::Any)
.export_values();
/* Enumeration code for Crystal Structures */
py::enum_<EnsembleInfo::CrystalStructure>(mod, "CrystalStructure")
.value("Hexagonal_High", EnsembleInfo::CrystalStructure::Hexagonal_High)
.value("Cubic_High", EnsembleInfo::CrystalStructure::Cubic_High)
.value("Hexagonal_Low", EnsembleInfo::CrystalStructure::Hexagonal_Low)
.value("Cubic_Low", EnsembleInfo::CrystalStructure::Cubic_Low)
.value("Triclinic", EnsembleInfo::CrystalStructure::Triclinic)
.value("Monoclinic", EnsembleInfo::CrystalStructure::Monoclinic)
.value("OrthoRhombic", EnsembleInfo::CrystalStructure::OrthoRhombic)
.value("Tetragonal_Low", EnsembleInfo::CrystalStructure::Tetragonal_Low)
.value("Tetragonal_High", EnsembleInfo::CrystalStructure::Tetragonal_High)
.value("Trigonal_Low", EnsembleInfo::CrystalStructure::Trigonal_Low)
.value("Trigonal_High", EnsembleInfo::CrystalStructure::Trigonal_High)
.value("UnknownCrystalStructure", EnsembleInfo::CrystalStructure::UnknownCrystalStructure)
.export_values();
/* Enumeration code for Data types ******************/
py::enum_<SIMPL::ScalarTypes::Type>(mod, "ScalarTypes")
.value("Int8", SIMPL::ScalarTypes::Type::Int8)
.value("UInt8", SIMPL::ScalarTypes::Type::UInt8)
.value("Int16", SIMPL::ScalarTypes::Type::Int16)
.value("UInt16", SIMPL::ScalarTypes::Type::UInt16)
.value("Int32", SIMPL::ScalarTypes::Type::Int32)
.value("UInt32", SIMPL::ScalarTypes::Type::UInt32)
.value("Int64", SIMPL::ScalarTypes::Type::Int64)
.value("UInt64", SIMPL::ScalarTypes::Type::UInt64)
.value("Float", SIMPL::ScalarTypes::Type::Float)
.value("Double", SIMPL::ScalarTypes::Type::Double)
.value("Bool", SIMPL::ScalarTypes::Type::Bool)
.export_values();
/* Enumeration code for Initialization Choices */
py::enum_<CreateDataArray::InitializationChoices>(mod, "InitializationType")
.value("Manual", CreateDataArray::InitializationChoices::Manual)
.value("RandomWithRange", CreateDataArray::InitializationChoices::RandomWithRange)
.export_values();
/* Enumeration code for AngleUnits */
py::enum_<ArrayCalculator::AngleUnits>(mod, "AngleUnits")
.value("Radians", ArrayCalculator::AngleUnits::Radians)
.value("Degrees", ArrayCalculator::AngleUnits::Degrees)
.export_values();
py::enum_<SIMPL::NumericTypes::Type>(mod, "NumericTypes")
.value("Int8", SIMPL::NumericTypes::Type::Int8)
.value("UInt8", SIMPL::NumericTypes::Type::UInt8)
.value("Int16", SIMPL::NumericTypes::Type::Int16)
.value("UInt16", SIMPL::NumericTypes::Type::UInt16)
.value("Int32", SIMPL::NumericTypes::Type::Int32)
.value("UInt32", SIMPL::NumericTypes::Type::UInt32)
.value("Int64", SIMPL::NumericTypes::Type::Int64)
.value("UInt64", SIMPL::NumericTypes::Type::UInt64)
.value("Float", SIMPL::NumericTypes::Type::Float)
.value("Double", SIMPL::NumericTypes::Type::Double)
.value("Bool", SIMPL::NumericTypes::Type::Bool)
.value("SizeT", SIMPL::NumericTypes::Type::SizeT)
.value("UnknownNumType", SIMPL::NumericTypes::Type::UnknownNumType)
.export_values();
/* Init codes for classes in the Module */
@MODULE_INIT_CODE@
/* Init codes for the DataArray<T> classes */
PySharedPtrClass<Int8ArrayType> @LIB_NAME@_Int8ArrayType = declareInt8ArrayType(mod, @LIB_NAME@_IDataArray);
PySharedPtrClass<UInt8ArrayType> @LIB_NAME@_UInt8ArrayType = declareUInt8ArrayType(mod, @LIB_NAME@_IDataArray);
PySharedPtrClass<Int16ArrayType> @LIB_NAME@_Int16ArrayType = declareInt16ArrayType(mod, @LIB_NAME@_IDataArray);
PySharedPtrClass<UInt16ArrayType> @LIB_NAME@_UInt16ArrayType = declareUInt16ArrayType(mod, @LIB_NAME@_IDataArray);
PySharedPtrClass<Int32ArrayType> @LIB_NAME@_Int32ArrayType = declareInt32ArrayType(mod, @LIB_NAME@_IDataArray);
PySharedPtrClass<UInt32ArrayType> @LIB_NAME@_UInt32ArrayType = declareUInt32ArrayType(mod, @LIB_NAME@_IDataArray);
PySharedPtrClass<Int64ArrayType> @LIB_NAME@_Int64ArrayType = declareInt64ArrayType(mod, @LIB_NAME@_IDataArray);
PySharedPtrClass<UInt64ArrayType> @LIB_NAME@_UInt64ArrayType = declareUInt64ArrayType(mod, @LIB_NAME@_IDataArray);
PySharedPtrClass<FloatArrayType> @LIB_NAME@_FloatArrayType = declareFloatArrayType(mod, @LIB_NAME@_IDataArray);
PySharedPtrClass<DoubleArrayType> @LIB_NAME@_DoubleArrayType = declareDoubleArrayType(mod, @LIB_NAME@_IDataArray);
py::enum_<SIMPL::InfoStringFormat>(mod, "InfoStringFormat").value("HtmlFormat", SIMPL::InfoStringFormat::HtmlFormat).value("UnknownFormat", SIMPL::InfoStringFormat::UnknownFormat).export_values();
//--------------------------------------------------------------------------
// This header file is auto-generated and contains some C++ code to create
// a submodule for each dream3d plugin
//--------------------------------------------------------------------------
#include "DREAM3D_SubmoduleInit.hpp"
}
/* =============================================================================
* END Template file SIMPLModuleCodeTemplate.in.cpp
* ========================================================================== */
// clang-format on
|
#include <iostream>
#include <cstring>
int main()
{
char stra[] = "Hello,";
char strb[] = " world!";
char strc[50];
std::strcpy(strc, stra);
std::strcat(strc, strb);
std::cout << strc << std::endl;
return 0;
}
|
#include <iostream>
#include <string>
using namespace std;
int main (){
//cout << "Hello world" << endl;
// string s1;
// cout << s1 << endl;
// string s2 {"Frank"};
// cout << s2 << endl;
// string s3 {s2};
// cout << s3<< endl;
// string s4 {"Frank" , 3};
// cout << s4<< endl;
// string s5 {s3 , 0, 1};
// cout << s5<< endl;
// string s6 (7, '%');
// cout << s6<< endl;
//
// string s1; cout << s1 << endl;
// s1 = "C++ Rocks!"; cout << s1 << endl;
//
// string s2 {"Hello"}; cout << s2 << endl;
// s2 = s1;cout << s2 << endl;
//
// cout << "-------------------------------" << endl;
//
// string part1 {"C++"};
// string part2 {"is a powerful"};
//
// string sentence;
//
// sentence = part1 + " " + part2 + " language!";
// cout << sentence << endl;
//
//
// cout << "-------------------------------" << endl;
//
// string s3 {"Frank"};
//
// for (int c : s3)
// cout << c << endl;
string s0;
cout << s0 << endl;
cout << s0.length() << endl;
string s1 {"Apple"};
cout << s1 << endl;
cout << s1.length() << endl;
string s2 {"Banana"};
cout << s2 << endl;
cout << s2.length() << endl;
string s3 {"Kiwi"};
cout << s3 << endl;
cout << s3.length() << endl;
string s4 {"apple"};
cout << s4 << endl;
cout << s4.length() << endl;
string s5 {s1};
cout << s5 << endl;
cout << s5.length() << endl;
string s6 {s1, 0, 3};
cout << s6 << endl;
cout << s6.length() << endl;
string s7 (10, 'X');
cout << s7 << endl;
cout << s7.length() << endl;
return 0;
}
|
#if !defined(ATBASH_CIPHER_H)
#define ATBASH_CIPHER_H
#include <string>
#include <cctype>
#include <algorithm>
namespace atbash_cipher {
std::string encode(std::string);
std::string decode(std::string);
} // namespace atbash_cipher
#endif // ATBASH_CIPHER_H
|
#include "Reader.h"
namespace screenDNS {
Reader::Reader(int id, DBManager* db_manager) {
m_db_manager = db_manager;
m_id = id;
}
void Reader::operator () () {
while (true)
{
try {
sleep(3); // sleep 3s before each read
// Read the content of DB by invoking DBManager.readDB() method
struct cdb c;
if (!m_db_manager->readDB(c))
continue; // Failed to obtain pointer to DB in memory. Skip the rest of the code
// Open a log file for this thread
std::ostringstream oss;
oss << m_id;
std::string fileName = oss.str() + "_";
boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();
fileName += boost::posix_time::to_iso_extended_string(now);
ofstream myfile;
myfile.open (fileName.c_str());
myfile << m_id << " Pass cdb_init...\n";
// Test hard-coded loading DB
/*
std::cout << m_id << " Start test...\n" << std::endl;
std::string dbFileName = "/usr/home/dvv/F1.cdb";
int fd = open(dbFileName.c_str(), O_RDONLY);
struct cdb c;
if (fd > 0) {
std::cout << m_id << " Before cdb_free...\n" << std::endl;
//cdb_free(&c); // Free old cdb if it was allocated. Otherwise, leave it alone. CRASHED
std::cout << m_id << " Past cdb_free...\n" << std::endl;
cdb_init(&c, fd);
std::cout << m_id << " Pass cdb_init...\n" << std::endl;
close(fd);
std::cout << m_id << " Pass close...\n" << std::endl;
}
struct cdb *cdbp = &c; // cdb_datalen(&c) equiv. cdb_datalen(cdbp)
std::cout << m_id << " End test...\n" << std::endl;
*/
// End test loading DB
// Do the query on key. Return either: Found/Not_Found Value Or List_Of_Values. The list will be pushed back into a vector
// Ref: http://www.corpit.ru/mjt/tinycdb.html
std::string key;
char *val;
unsigned vlen, vpos;
// Simulate the test. With different URLs. Those URLs should exist on F1
if(m_id == 1)
key = "4t6nhh.6600.org";
else if(m_id == 2)
key = "4tag16ag100.com";
else if(m_id == 3)
key = "4root.net";
else
key = "3uxyctrlmiqeo.cn";
// Version 1: Check existence of key only. And return std::string format of value if need. OK
if (cdb_find(&c, key.c_str(), key.size()) > 0) { // if search successeful
vpos = cdb_datapos(&c); // position of data in a file
vlen = cdb_datalen(&c); // length of data
val = (char*)malloc(vlen * sizeof(char*)); // allocate memory
cdb_read(&c, val, vlen, vpos); // read the value into buffer
// handle the value
val[vlen] = '\0';
std::string str_val(val); // This will be the std::string format of value
free(val);
// Debug
std::cout << m_id << " Found key " << key << std::endl;
myfile << "Value_" << str_val << "_Key_" << key << "_Found by Thread_" << m_id << "\n";
} else {
// Debug
std::cout << m_id << " Found no key " << key << std::endl;
myfile << "Found no Key_" << key << "_by Thread_" << m_id << "\n";
}
// Version 2: Check ALL occurences of key. Push all the found values into a vector. OK. Need to check vector
/*
std::vector<std::string> unified_resp;
struct cdb_find cdbf; // structure to hold current find position
cdb_findinit(&cdbf, &c, key.c_str(), key.size()); // initialize search of key
std::cout << m_id << " Searching for key " << key << "_" << std::endl;
while(cdb_findnext(&cdbf) > 0) {
vpos = cdb_datapos(&c);
vlen = cdb_datalen(&c);
val = (char*)malloc(vlen * sizeof(char*)); // allocate memory
cdb_read(&c, val, vlen, vpos);
// handle the value
val[vlen] = '\0';
std::string str_val(val); // This will be the std::string format of value
std::cout << m_id << " Found 1 value " << str_val << " for key " << key << std::endl;
myfile << m_id << " Found 1 value " << str_val << " for key " << key << std::endl;
// Push it into an answer vector
unified_resp.push_back(str_val);
free(val);
}
std::cout << m_id << " End searching for key " << key << "_" << std::endl;
*/
myfile.close();
// Check if this thread is interrupted by main
boost::this_thread::interruption_point();
}
catch (const boost::thread_interrupted&)
{
std::cout << "Get signal thread interrupted. Exiting reader thread" << std::endl;
break;
}
}
}
}
|
/*
* Pinhole.h
*
*
*/
#ifndef PINHOLE_H_
#define PINHOLE_H_
#include "core/Camera.h"
namespace rt {
class Pinhole : public Camera {
public:
//
// Constructors
//
Pinhole();
Pinhole(int width, int height, int fov);
//
// Destructor
//
~Pinhole() {};
//
// print function (implementing abstract function of base class)
//
void printCamera();
};
} // namespace rt
#endif /* PINHOLE_H_ */
|
//
// Copyright Jason Rice 2017
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef NBDL_DETAIL_DEFAULT_CONSTRUCTIBLE_LAMBDA_HPP
#define NBDL_DETAIL_DEFAULT_CONSTRUCTIBLE_LAMBDA_HPP
#include <type_traits>
namespace nbdl::detail
{
// Thanks, Paul Fultz II
template <typename Lambda>
struct default_constructible_lambda
{
static_assert(
std::is_empty<Lambda>::value
, "Default constructible lambda must not capture."
);
template <typename ...Xs>
constexpr auto operator()(Xs&& ...xs) const
{
return reinterpret_cast<const Lambda&>(*this)(
std::forward<Xs>(xs)...
);
}
};
}
#endif
|
// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.
#include "core/CompileConfig.h"
#if OUZEL_SUPPORTS_OPENGL
#include "TextureResourceOGL.h"
#include "core/Engine.h"
#include "RendererOGL.h"
#include "utils/Log.h"
namespace ouzel
{
namespace graphics
{
static GLint getOGLInternalPixelFormat(PixelFormat pixelFormat)
{
#if OUZEL_SUPPORTS_OPENGLES
uint32_t openGLVersion = sharedEngine->getRenderer()->getAPIMajorVersion();
if (openGLVersion >= 3)
{
switch (pixelFormat)
{
case PixelFormat::A8_UNORM: return GL_ALPHA8_OES;
case PixelFormat::R8_UNORM: return GL_R8;
case PixelFormat::R8_SNORM: return GL_R8_SNORM;
case PixelFormat::R8_UINT: return GL_R8UI;
case PixelFormat::R8_SINT: return GL_R8I;
case PixelFormat::R16_UNORM: return GL_NONE;
case PixelFormat::R16_SNORM: return GL_NONE;
case PixelFormat::R16_UINT: return GL_R16UI;
case PixelFormat::R16_SINT: return GL_R16I;
case PixelFormat::R16_FLOAT: return GL_R16F;
case PixelFormat::R32_UINT: return GL_R32UI;
case PixelFormat::R32_SINT: return GL_R32I;
case PixelFormat::R32_FLOAT: return GL_R32F;
case PixelFormat::RG8_UNORM: return GL_RG8;
case PixelFormat::RG8_SNORM: return GL_RG8_SNORM;
case PixelFormat::RG8_UINT: return GL_RG8UI;
case PixelFormat::RG8_SINT: return GL_RG8I;
case PixelFormat::RGBA8_UNORM: return GL_RGBA8;
case PixelFormat::RGBA8_SNORM: return GL_RGBA8_SNORM;
case PixelFormat::RGBA8_UINT: return GL_RGBA8UI;
case PixelFormat::RGBA8_SINT: return GL_RGBA8I;
case PixelFormat::RGBA16_UNORM: return GL_NONE;
case PixelFormat::RGBA16_SNORM: return GL_NONE;
case PixelFormat::RGBA16_UINT: return GL_RGBA16UI;
case PixelFormat::RGBA16_SINT: return GL_RGBA16I;
case PixelFormat::RGBA16_FLOAT: return GL_RGBA16F;
case PixelFormat::RGBA32_UINT: return GL_RGBA32UI;
case PixelFormat::RGBA32_SINT: return GL_RGBA32I;
case PixelFormat::RGBA32_FLOAT: return GL_RGBA32F;
default: return GL_NONE;
}
}
else
{
switch (pixelFormat)
{
case PixelFormat::A8_UNORM: return GL_ALPHA;
case PixelFormat::RGBA8_UNORM: return GL_RGBA;
default: return GL_NONE;
}
}
#else
switch (pixelFormat)
{
case PixelFormat::A8_UNORM: return GL_ALPHA8_EXT;
case PixelFormat::R8_UNORM: return GL_R8;
case PixelFormat::R8_SNORM: return GL_R8_SNORM;
case PixelFormat::R8_UINT: return GL_R8UI;
case PixelFormat::R8_SINT: return GL_R8I;
case PixelFormat::R16_UNORM: return GL_R16;
case PixelFormat::R16_SNORM: return GL_R16_SNORM;
case PixelFormat::R16_UINT: return GL_R16UI;
case PixelFormat::R16_SINT: return GL_R16I;
case PixelFormat::R16_FLOAT: return GL_R16F;
case PixelFormat::R32_UINT: return GL_R32UI;
case PixelFormat::R32_SINT: return GL_R32I;
case PixelFormat::R32_FLOAT: return GL_R32F;
case PixelFormat::RG8_UNORM: return GL_RG8;
case PixelFormat::RG8_SNORM: return GL_RG8_SNORM;
case PixelFormat::RG8_UINT: return GL_RG8UI;
case PixelFormat::RG8_SINT: return GL_RG8I;
case PixelFormat::RGBA8_UNORM: return GL_RGBA8;
case PixelFormat::RGBA8_SNORM: return GL_RGBA8_SNORM;
case PixelFormat::RGBA8_UINT: return GL_RGBA8UI;
case PixelFormat::RGBA8_SINT: return GL_RGBA8I;
case PixelFormat::RGBA16_UNORM: return GL_RGBA16;
case PixelFormat::RGBA16_SNORM: return GL_RGBA16_SNORM;
case PixelFormat::RGBA16_UINT: return GL_RGBA16UI;
case PixelFormat::RGBA16_SINT: return GL_RGBA16I;
case PixelFormat::RGBA16_FLOAT: return GL_RGBA16F;
case PixelFormat::RGBA32_UINT: return GL_RGBA32UI;
case PixelFormat::RGBA32_SINT: return GL_RGBA32I;
case PixelFormat::RGBA32_FLOAT: return GL_RGBA32F;
default: return GL_NONE;
}
#endif
}
static GLenum getOGLPixelFormat(PixelFormat pixelFormat)
{
switch (pixelFormat)
{
case PixelFormat::A8_UNORM:
return GL_ALPHA;
case PixelFormat::R8_UNORM:
case PixelFormat::R8_SNORM:
case PixelFormat::R16_UNORM:
case PixelFormat::R16_SNORM:
case PixelFormat::R16_FLOAT:
case PixelFormat::R32_FLOAT:
return GL_RED;
case PixelFormat::R8_UINT:
case PixelFormat::R8_SINT:
case PixelFormat::R16_UINT:
case PixelFormat::R16_SINT:
case PixelFormat::R32_UINT:
case PixelFormat::R32_SINT:
return GL_RED_INTEGER;
case PixelFormat::RG8_UNORM:
case PixelFormat::RG8_SNORM:
return GL_RG;
case PixelFormat::RG8_UINT:
case PixelFormat::RG8_SINT:
return GL_RG_INTEGER;
case PixelFormat::RGBA8_UNORM:
case PixelFormat::RGBA8_SNORM:
case PixelFormat::RGBA16_UNORM:
case PixelFormat::RGBA16_SNORM:
case PixelFormat::RGBA16_FLOAT:
case PixelFormat::RGBA32_FLOAT:
return GL_RGBA;
case PixelFormat::RGBA8_UINT:
case PixelFormat::RGBA8_SINT:
case PixelFormat::RGBA16_UINT:
case PixelFormat::RGBA16_SINT:
case PixelFormat::RGBA32_UINT:
case PixelFormat::RGBA32_SINT:
return GL_RGBA_INTEGER;
default:
return 0;
}
}
static GLenum getOGLPixelType(PixelFormat pixelFormat)
{
switch (pixelFormat)
{
case PixelFormat::A8_UNORM:
case PixelFormat::R8_UNORM:
case PixelFormat::R16_UNORM:
case PixelFormat::RG8_UNORM:
case PixelFormat::RGBA8_UNORM:
case PixelFormat::RGBA16_UNORM:
return GL_UNSIGNED_BYTE;
case PixelFormat::R8_SNORM:
case PixelFormat::R16_SNORM:
case PixelFormat::RG8_SNORM:
case PixelFormat::RGBA8_SNORM:
case PixelFormat::RGBA16_SNORM:
return GL_BYTE;
case PixelFormat::R8_UINT:
case PixelFormat::R16_UINT:
case PixelFormat::R32_UINT:
case PixelFormat::RG8_UINT:
case PixelFormat::RGBA8_UINT:
case PixelFormat::RGBA16_UINT:
case PixelFormat::RGBA32_UINT:
return GL_UNSIGNED_INT;
case PixelFormat::R8_SINT:
case PixelFormat::R16_SINT:
case PixelFormat::R32_SINT:
case PixelFormat::RG8_SINT:
case PixelFormat::RGBA8_SINT:
case PixelFormat::RGBA16_SINT:
case PixelFormat::RGBA32_SINT:
return GL_INT;
case PixelFormat::R16_FLOAT:
case PixelFormat::R32_FLOAT:
case PixelFormat::RGBA16_FLOAT:
case PixelFormat::RGBA32_FLOAT:
return GL_FLOAT;
default:
return 0;
}
}
TextureResourceOGL::TextureResourceOGL()
{
}
TextureResourceOGL::~TextureResourceOGL()
{
if (depthBufferId)
{
RendererOGL::deleteRenderBuffer(depthBufferId);
}
if (frameBufferId)
{
RendererOGL::deleteFrameBuffer(frameBufferId);
}
if (textureId)
{
RendererOGL::deleteTexture(textureId);
}
}
bool TextureResourceOGL::upload()
{
std::lock_guard<std::mutex> lock(uploadMutex);
if (dirty)
{
if (!textureId)
{
glGenTextures(1, &textureId);
if (RendererOGL::checkOpenGLError())
{
Log(Log::Level::ERR) << "Failed to create texture";
return false;
}
}
RendererOGL::bindTexture(textureId, 0);
RendererOGL* rendererOGL = static_cast<RendererOGL*>(sharedEngine->getRenderer());
if (dirty & DIRTY_DATA ||
dirty & DIRTY_SIZE)
{
GLint oglInternalPixelFormat = getOGLInternalPixelFormat(pixelFormat);
if (oglInternalPixelFormat == GL_NONE)
{
Log(Log::Level::ERR) << "Invalid pixel format";
return false;
}
if (dirty & DIRTY_SIZE)
{
width = static_cast<GLsizei>(size.v[0]);
height = static_cast<GLsizei>(size.v[1]);
if (!renderTarget)
{
for (size_t level = 0; level < levels.size(); ++level)
{
if (!levels[level].data.empty())
{
glTexImage2D(GL_TEXTURE_2D, static_cast<GLint>(level), oglInternalPixelFormat,
static_cast<GLsizei>(levels[level].size.v[0]),
static_cast<GLsizei>(levels[level].size.v[1]), 0,
getOGLPixelFormat(pixelFormat), getOGLPixelType(pixelFormat),
levels[level].data.data());
}
}
}
if (renderTarget && rendererOGL->isRenderTargetsSupported())
{
if (!frameBufferId)
{
glGenFramebuffersProc(1, &frameBufferId);
if (RendererOGL::checkOpenGLError())
{
Log(Log::Level::ERR) << "Failed to create frame buffer";
return false;
}
}
RendererOGL::bindFrameBuffer(frameBufferId);
if (glCheckFramebufferStatusProc(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
{
RendererOGL::bindTexture(textureId, 0);
glTexImage2D(GL_TEXTURE_2D, 0, oglInternalPixelFormat,
static_cast<GLsizei>(size.v[0]),
static_cast<GLsizei>(size.v[1]), 0,
getOGLPixelFormat(pixelFormat), getOGLPixelType(pixelFormat), 0);
// TODO: blit multisample render buffer to texture
glFramebufferTexture2DProc(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureId, 0);
if (depth)
{
glGenRenderbuffersProc(1, &depthBufferId);
glBindRenderbufferProc(GL_RENDERBUFFER, depthBufferId);
if (sampleCount > 1 && rendererOGL->isMultisamplingSupported())
{
glRenderbufferStorageMultisampleProc(GL_RENDERBUFFER,
static_cast<GLsizei>(sampleCount),
GL_DEPTH_COMPONENT,
static_cast<GLsizei>(size.v[0]),
static_cast<GLsizei>(size.v[1]));
}
else
{
glRenderbufferStorageProc(GL_RENDERBUFFER, GL_DEPTH_COMPONENT,
static_cast<GLsizei>(size.v[0]),
static_cast<GLsizei>(size.v[1]));
}
glFramebufferRenderbufferProc(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthBufferId);
}
if (glCheckFramebufferStatusProc(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
{
Log(Log::Level::ERR) << "Failed to create frame buffer";
return false;
}
}
}
}
else if (!renderTarget)
{
for (size_t level = 0; level < levels.size(); ++level)
{
if (!levels[level].data.empty())
{
glTexSubImage2D(GL_TEXTURE_2D, static_cast<GLint>(level), 0, 0,
static_cast<GLsizei>(levels[level].size.v[0]),
static_cast<GLsizei>(levels[level].size.v[1]),
getOGLPixelFormat(pixelFormat), getOGLPixelType(pixelFormat),
levels[level].data.data());
if (RendererOGL::checkOpenGLError())
{
Log(Log::Level::ERR) << "Failed to upload texture data";
return false;
}
}
}
}
}
if (dirty & DIRTY_PARAMETERS)
{
clearMask = 0;
if (clearColorBuffer) clearMask |= GL_COLOR_BUFFER_BIT;
if (clearDepthBuffer) clearMask |= GL_DEPTH_BUFFER_BIT;
frameBufferClearColor[0] = clearColor.normR();
frameBufferClearColor[1] = clearColor.normG();
frameBufferClearColor[2] = clearColor.normB();
frameBufferClearColor[3] = clearColor.normA();
Texture::Filter finalFilter = (filter == Texture::Filter::DEFAULT) ? rendererOGL->getTextureFilter() : filter;
switch (finalFilter)
{
case Texture::Filter::DEFAULT:
case Texture::Filter::POINT:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (levels.size() > 1) ? GL_NEAREST_MIPMAP_NEAREST : GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
break;
case Texture::Filter::LINEAR:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (levels.size() > 1) ? GL_LINEAR_MIPMAP_NEAREST : GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
break;
case Texture::Filter::BILINEAR:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (levels.size() > 1) ? GL_LINEAR_MIPMAP_NEAREST : GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
break;
case Texture::Filter::TRILINEAR:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (levels.size() > 1) ? GL_LINEAR_MIPMAP_LINEAR : GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
break;
}
switch (addressX)
{
case Texture::Address::CLAMP:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
break;
case Texture::Address::REPEAT:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
break;
case Texture::Address::MIRROR_REPEAT:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
break;
}
switch (addressY)
{
case Texture::Address::CLAMP:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
break;
case Texture::Address::REPEAT:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
break;
case Texture::Address::MIRROR_REPEAT:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);
break;
}
uint32_t finalMaxAnisotropy = (maxAnisotropy == 0) ? rendererOGL->getMaxAnisotropy() : maxAnisotropy;
if (finalMaxAnisotropy > 1 && rendererOGL->isAnisotropicFilteringSupported())
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, static_cast<GLint>(finalMaxAnisotropy));
}
if (RendererOGL::checkOpenGLError())
{
Log(Log::Level::ERR) << "Failed to set texture parameters";
return false;
}
}
dirty = 0;
}
return true;
}
} // namespace graphics
} // namespace ouzel
#endif
|
#include <memory>
#include <string>
#include <gtest/gtest.h>
#include <Expected.h>
#include <Errors.h>
#include <ForceAllErrors.h>
#include "Common.h"
#include "CustomError.h"
#ifndef NDEBUG
static int ForceAllErrors_sideEffects0_value = 0;
static int ForceAllErrors_sideEffects1_value = 0;
// -----------------------------------------------------------------------------
// Example function under test:
llvm::Expected<int> ForceAllErrors_sideEffects0(bool returnInt) {
// Non-error code path. Error sanitizer will break the instance created in
// the return, not capturing the below side effect for regular error cases.
// >>> No ideas so far.
if (returnInt)
return 0;
ForceAllErrors_sideEffects0_value = 1;
return llvm::make_error<llvm::StringError>("Message",
llvm::inconvertibleErrorCode());
}
// Example invocation:
TEST(ForceAllErrors, sideEffects0_RegularError)
{
// Reset side effect value and call function that modifies it in error cases.
// Invoke function in a way that it returns an error.
ForceAllErrors_sideEffects0_value = 0;
auto expected = ForceAllErrors_sideEffects0(false);
// Instance broken via regular execution path
EXPECT_FALSE(isInSuccessState(expected));
// Side effect captured: consistent state
EXPECT_EQ(1, ForceAllErrors_sideEffects0_value);
llvm::consumeError(expected.takeError());
}
// Challenge for ESan:
TEST(ForceAllErrors, sideEffects0_ESanChallenge)
{
int breakInstance = 1;
llvm::ForceAllErrorsInScope FAE(breakInstance);
// Reset side effect value and call function that modifies it in error cases.
// Invoke function in a way it would usually return NO error
ForceAllErrors_sideEffects0_value = 0;
auto expected = ForceAllErrors_sideEffects0(true);
// Instance broken with mocked error by error sanitizer
EXPECT_FALSE(isInSuccessState(expected));
// Side effect not captured: INCONSISTENT state
EXPECT_EQ(0, ForceAllErrors_sideEffects0_value);
llvm::consumeError(expected.takeError());
}
// -----------------------------------------------------------------------------
// Example function under test:
llvm::Expected<int> ForceAllErrors_sideEffects1(bool returnInt) {
std::unique_ptr<llvm::Error> err;
if (!returnInt)
err = std::make_unique<llvm::Error>(
llvm::make_error<llvm::StringError>("Message",
llvm::inconvertibleErrorCode()));
if (err) {
ForceAllErrors_sideEffects1_value = 1;
}
// ... more code ...
if (!returnInt)
return std::move(*err);
// Error sanitizer will break this instance, not capturing above side effect.
// >>> Instrumentation of llvm::Error may help?!
return 0;
}
// Example invocation:
TEST(ForceAllErrors, sideEffects1_RegularError)
{
// Reset side effect value and call function that modifies it in error cases.
// Invoke function in a way that it returns an error.
ForceAllErrors_sideEffects1_value = 0;
auto expected = ForceAllErrors_sideEffects1(false);
// Instance broken via regular execution path
EXPECT_FALSE(isInSuccessState(expected));
// Side effect captured: consistent state
EXPECT_EQ(1, ForceAllErrors_sideEffects1_value);
llvm::consumeError(expected.takeError());
}
// Challenge for ESan:
TEST(ForceAllErrors, sideEffects1_ESanChallenge)
{
// Setup ESan to break first instance of llvm::Expected<T>
int breakInstance = 1;
llvm::ForceAllErrorsInScope FAE(breakInstance);
// Reset side effect value and call function that modifies it in error cases.
// Invoke function in a way it would usually return NO error.
ForceAllErrors_sideEffects1_value = 0;
auto expected = ForceAllErrors_sideEffects1(true);
// Instance broken with mocked error by error sanitizer
EXPECT_FALSE(isInSuccessState(expected));
// Side effect not captured: INCONSISTENT state
EXPECT_EQ(0, ForceAllErrors_sideEffects1_value);
llvm::consumeError(expected.takeError());
}
// -----------------------------------------------------------------------------
// Example function under test:
llvm::Expected<int> ForceAllErrors_mockedErrorType0(bool returnInt) {
// Non-error code path. Error sanitizer will break the instance created in
// the return. How to determine the correct error type is CustomError?
// >>> Static analysis can do this: remember which functions emit which errors
if (returnInt)
return 0;
return llvm::make_error<CustomError>(__FILE__, __LINE__);
}
// Example invocation:
TEST(ForceAllErrors, mockedErrorType0_RegularError)
{
// Invoke function in a way that it returns an error
auto expected = ForceAllErrors_mockedErrorType0(false);
EXPECT_FALSE(isInSuccessState(expected));
// The expected error type is CustomError, not llvm::StringError
llvm::Error err = expected.takeError();
EXPECT_TRUE(err.isA<CustomError>());
llvm::consumeError(std::move(err));
}
// Challenge for ESan:
TEST(ForceAllErrors, mockedErrorType0_ESanChallenge)
{
// Setup ESan to break first instance of llvm::Expected<T>
int breakInstance = 1;
llvm::ForceAllErrorsInScope FAE(breakInstance);
// Invoke function in a way it would usually return NO error
auto expected = ForceAllErrors_mockedErrorType0(true);
EXPECT_FALSE(isInSuccessState(expected));
// The expected error type is CustomError. However, it's a mocked error type
// actually (currently llvm::StringError).
llvm::Error err = expected.takeError();
EXPECT_TRUE(err.isA<llvm::StringError>());
llvm::consumeError(std::move(err));
}
// -----------------------------------------------------------------------------
// Example function under test:
llvm::Expected<int> ForceAllErrors_mockedErrorType1(bool returnInt, bool errTypeCustom) {
if (!returnInt) {
if (errTypeCustom)
return llvm::make_error<CustomError>(__FILE__, __LINE__);
else
return llvm::make_error<llvm::StringError>(
"Message", llvm::inconvertibleErrorCode());
}
// Non-error code path. Error sanitizer will break this instance. How to
// determine the possible error types?
// >>> Static analysis can help here too.
// >>> Add feature so that error can be forced twice. Once with each type.
return 0;
}
// Example invocation:
TEST(ForceAllErrors, mockedErrorType1_RegularError)
{
// Invoke function in a way that it returns a CustomError
auto expected1 = ForceAllErrors_mockedErrorType1(false, true);
EXPECT_FALSE(isInSuccessState(expected1));
llvm::Error err1 = expected1.takeError();
EXPECT_TRUE(err1.isA<CustomError>());
// Invoke function in a way that it returns a llvm::StringError
auto expected2 = ForceAllErrors_mockedErrorType1(false, false);
EXPECT_FALSE(isInSuccessState(expected2));
llvm::Error err2 = expected2.takeError();
EXPECT_TRUE(err2.isA<llvm::StringError>());
llvm::consumeError(std::move(err1));
llvm::consumeError(std::move(err2));
}
// Challenge for ESan:
TEST(ForceAllErrors, mockedErrorType1_ESanChallenge)
{
// Setup ESan to break first instance of llvm::Expected<T>.
// >>> Add feature to break one and the same instance multiple times
// >>> mocking all possible error types.
int breakInstance = 1;
llvm::ForceAllErrorsInScope FAE(breakInstance);
// Invoke function in a way it would usually return NO error
auto expected = ForceAllErrors_mockedErrorType1(true, true);
EXPECT_FALSE(isInSuccessState(expected));
llvm::Error err = expected.takeError();
EXPECT_TRUE(err.isA<llvm::StringError>());
llvm::consumeError(std::move(err));
}
// -----------------------------------------------------------------------------
// Example function under test:
llvm::Expected<int> ForceAllErrors_mockedErrorType2(std::function<llvm::Error()> f) {
if (f)
return f();
// Non-error code path. Error sanitizer will break this instance. How to
// determine the possible error types?
// >>> Dynamic parameter determines actual error type.
// >>> Static analysis CANNOT help.
// >>> Add runtime-feature to record execution path dynamically.
// >>> Use static analysis data to determine possible error types.
return 0;
}
// Example invocation:
TEST(ForceAllErrors, mockedErrorType2_RegularError)
{
// Invoke function in a way that it returns a CustomError
auto expected = ForceAllErrors_mockedErrorType2([]() {
return llvm::make_error<CustomError>(__FILE__, __LINE__);
});
EXPECT_FALSE(isInSuccessState(expected));
llvm::Error err = expected.takeError();
EXPECT_TRUE(err.isA<CustomError>());
llvm::consumeError(std::move(err));
}
// Challenge for ESan:
TEST(ForceAllErrors, mockedErrorType2_ESanChallenge)
{
// Setup ESan to break first instance of llvm::Expected<T>
int breakInstance = 1;
llvm::ForceAllErrorsInScope FAE(breakInstance);
// Invoke function in a way it would usually return NO error AT ALL
auto expected = ForceAllErrors_mockedErrorType2(nullptr);
EXPECT_FALSE(isInSuccessState(expected));
// We get the mocked error type again (currently llvm::StringError)
llvm::Error err = expected.takeError();
EXPECT_TRUE(err.isA<llvm::StringError>());
llvm::consumeError(std::move(err));
}
// -----------------------------------------------------------------------------
// Example function under test:
llvm::Expected<int> ForceAllErrors_innerLoopError(bool intOrErr) {
if (intOrErr)
return 0;
return llvm::make_error<llvm::StringError>(
"Message", llvm::inconvertibleErrorCode());
}
// Example invocation:
TEST(ForceAllErrors, innerLoopError_RegularError)
{
for (int i = 0; i < 3; ++i) {
// Invoke function in a way it returns an error
auto expected = ForceAllErrors_innerLoopError(false);
EXPECT_FALSE(isInSuccessState(expected));
llvm::consumeError(expected.takeError());
}
}
// Challenge for ESan:
TEST(ForceAllErrors, innerLoopError_ESanChallenge)
{
// Setup ESan to break the respective instance of llvm::Expected<T> created
// in the inner loop. This adds a lot of cases and has little use as it tests
// the same error paths again and again.
// >>> Additionally collect code locations for instances
// >>> Avoid breaking instances at same locations over and over again
for (int breakInstance = 1; breakInstance <= 3; ++breakInstance) {
llvm::ForceAllErrorsInScope FAE(breakInstance);
for (int i = 1; i <= 3; ++i) {
// Invoke function in a way it would usually return no error
auto expected = ForceAllErrors_innerLoopError(true);
bool instanceBroken = (breakInstance == i);
EXPECT_EQ(!instanceBroken, isInSuccessState(expected));
llvm::consumeError(expected.takeError());
}
}
}
// -----------------------------------------------------------------------------
// Example functions under test:
llvm::Expected<int> ForceAllErrors_nestedError(bool intOrErr) {
if (intOrErr)
return 0;
return llvm::make_error<llvm::StringError>(
"Message", llvm::inconvertibleErrorCode());
}
llvm::Expected<int> ForceAllErrors_recoverFromNestedError(llvm::Error err) {
llvm::consumeError(std::move(err));
// Currently this instance of llvm::Expected<T> will not be recognized by
// ESan, as it only exists in an error path.
// >>> Add feature to rerun cases that encounter new llvm::Expected<T>
// >>> instances after an error was forced.
// >>> Worst case up to 2^N reruns to capture all combinatons of subsequent
// >>> errors.
return 0;
}
llvm::Expected<int> ForceAllErrors_cascadingError(bool intOrErr) {
auto expected = ForceAllErrors_nestedError(intOrErr);
if (!expected)
return ForceAllErrors_recoverFromNestedError(expected.takeError());
return 0;
}
// Example invocation:
TEST(ForceAllErrors, cascadingError_RegularError)
{
// Invoke function in a way it returns no error
auto expected1 = ForceAllErrors_cascadingError(true);
EXPECT_TRUE(isInSuccessState(expected1));
llvm::consumeError(expected1.takeError());
// Invoke function in a way the error gets handled in recoverFromNestedError
auto expected2 = ForceAllErrors_cascadingError(false);
EXPECT_TRUE(isInSuccessState(expected2));
llvm::consumeError(expected2.takeError());
}
// Challenge for ESan:
TEST(ForceAllErrors, cascadingError_ESanChallenge)
{
{
// Setup ESan to break the first instance of llvm::Expected<T>.
// It's the one created in the nestedError function.
int breakInstance = 1;
llvm::ForceAllErrorsInScope FAE(breakInstance);
// Invoke function in a way it would usually return no error
auto expected = ForceAllErrors_cascadingError(true);
// Handled in recoverFromNestedError
EXPECT_TRUE(isInSuccessState(expected));
llvm::consumeError(expected.takeError());
}
{
// Setup ESan to break the second instance of llvm::Expected<T>
int breakInstance = 2;
llvm::ForceAllErrorsInScope FAE(breakInstance);
// Invoke function in a way it would usually return no error
auto expected = ForceAllErrors_cascadingError(true);
// Second forced error is NOT the one in created at the end of the
// recoverFromNestedError function, as it's not entered in this case.
// Instead it's be the one returned from the cascadingError function.
EXPECT_FALSE(isInSuccessState(expected));
llvm::consumeError(expected.takeError());
}
{
// Setup ESan to break the third instance of llvm::Expected<T>.
// However, there won't be a third instance, as again the
// recoverFromNestedError function is not entered.
int breakInstance = 3;
llvm::ForceAllErrorsInScope FAE(breakInstance);
// Invoke function in a way it would usually return no error
auto expected = ForceAllErrors_cascadingError(true);
// No forced error
EXPECT_TRUE(isInSuccessState(expected));
llvm::consumeError(expected.takeError());
}
}
#endif
|
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
const int N = 10000, K = 100;
struct Table {
int time = 8 * 3600, sum = 0;
bool isVip = false;
};
struct Player {
int atime, stime = -1, p;
Player(int at, int _p)
{
atime = at; p = _p;
}
};
Table tables[K];
vector<Player> players;
vector<Player> vplayers;
int pos = 0, vpos = 0;
bool cmp(Player a, Player b)
{
return a.atime < b.atime;
}
int main()
{
int n, k, m;
cin >> n;
for (int i = 0; i < n; i++)
{
int hour, minute, second, p, type;
scanf("%d:%d:%d %d %d", &hour, &minute, &second, &p, &type);
Player player(hour * 3600 + minute * 60 + second, p * 60);
if (type == 1)
vplayers.push_back(player);
else
players.push_back(player);
}
sort(vplayers.begin(), vplayers.end(), cmp);
/*for (int i = 0; i < players.size(); i++)
cout << players[i].atime << endl;*/
sort(players.begin(), players.end(), cmp);
/*for (int i = 0; i < players.size(); i++)
cout << players[i].atime << endl;*/
cin >> k >> m;
for (int i = 0; i < m; i++)
{
int index;
scanf("%d", &index);
tables[index - 1].isVip = true;
}
vector<Player> served;
for (int i = 0; i < n; i++)
{
int min = 21 * 3600 + 1, minI = 0;
bool isvip = false;
for (int j = 0; j < k; j++)
{
if (tables[j].time < min || (!isvip && tables[j].time == min && tables[j].isVip))
{
min = tables[j].time;
minI = j;
isvip = tables[j].isVip;
}
}
if (tables[minI].time > 21 * 3600) break;
if ((vpos < vplayers.size()) &&
((isvip && vplayers[vpos].atime <= tables[minI].time && players[vpos].atime <= tables[minI].time) ||
(vplayers[vpos].atime <= players[vpos].atime) ||
pos >= players.size()))
{
vplayers[vpos].stime = max(tables[minI].time, vplayers[vpos].atime);
if (vplayers[vpos].p > 2 * 3600)
tables[minI].time = vplayers[vpos].stime + 2 * 3600;
else
tables[minI].time = vplayers[vpos].stime + vplayers[vpos].p;
served.push_back(vplayers[vpos++]);
}
else
{
players[pos].stime = max(tables[minI].time, players[pos].atime);
if (players[pos].p > 2 * 3600)
tables[minI].time = players[pos].stime + 2 * 3600;
else
tables[minI].time = players[pos].stime + players[pos].p;
served.push_back(players[pos++]);
}
tables[minI].sum++;
}
int size = served.size();
for (int i = 0; i < size; i++)
{
int ah = served[i].atime / 3600,
am = (served[i].atime - ah * 3600) / 60,
as = served[i].atime % 60,
sh = served[i].stime / 3600,
sm = (served[i].stime - sh * 3600) / 60,
ss = served[i].stime % 60;
printf("%02d:%02d:%02d %02d:%02d:%02d %d\n", ah, am, as, sh, sm, ss, (served[i].stime - served[i].atime) / 60);
}
for (int i = 0; i < k; i++)
{
if (i == 0)
printf("%d", tables[i].sum);
else
printf(" %d", tables[i].sum);
}
return 0;
}
|
#include "include/materialdata.h"
#include "json/json.h"
#include <fstream>
using namespace cilender;
MaterialData::MaterialData()
{
}
MaterialData* MaterialData::loadJSON(std::string fileName)
{
MaterialData* mat = new MaterialData();
Json::Value root;
Json::Reader reader;
std::ifstream file( fileName.c_str() );
bool parsingSuccessful = reader.parse( file, root );
if ( !parsingSuccessful )
{
// report to the user the failure and their locations in the document.
std::cout << "Failed to parse material"
<< reader.getFormattedErrorMessages();
return mat;
}
std::string name = root.get("name", "").asString();
ci::ColorA diffuseColor(
root["diffuseColor"].get("r",0.0).asFloat(),
root["diffuseColor"].get("g",0.0).asFloat(),
root["diffuseColor"].get("b",0.0).asFloat(),
root["diffuseColor"].get("a",0.0).asFloat()
);
float diffuseIntensity = root.get("diffuseIntensity",1.0).asFloat();
ci::ColorA specularColor(
root["specularColor"].get("r",0.0).asFloat(),
root["specularColor"].get("g",0.0).asFloat(),
root["specularColor"].get("b",0.0).asFloat(),
root["specularColor"].get("a",0.0).asFloat()
);
float specularIntensity = root.get("specularIntensity",1.0).asFloat();
float ambientIntensity = root.get("ambient",1.0).asFloat();
float emissionIntensity = root.get("emissionIntensity",0.0).asFloat();
mat->name = name;
mat->diffuseColor = diffuseColor;
mat->diffuseIntensity = diffuseIntensity;
mat->specularColor = specularColor;
mat->specularIntensity = specularIntensity;
mat->ambientIntensity = ambientIntensity;
mat->emissionIntensity = emissionIntensity;
mat->material = ci::gl::Material(
ci::ColorA::white() * mat->ambientIntensity,
mat->diffuseColor * mat->diffuseIntensity,
mat->specularColor,
mat->specularIntensity,
ci::ColorA(
mat->diffuseColor.r,
mat->diffuseColor.g,
mat->diffuseColor.b,
mat->emissionIntensity
),
GL_FRONT
);
if(root["textures"].size() > 0)
{
std::vector< std::string > textures;
for(int i=0; i<root["textures"].size(); i++)
{
textures.push_back(root["textures"][i].asString());
}
mat->textures = textures;
}
return mat;
}
|
//
// UIHomeLayer.cpp
// Boids
//
// Created by Yanjie Chen on 3/3/15.
//
//
#include "UIHomeLayer.h"
#include "../Utils.h"
#include "../manager/SceneManager.h"
#include "../manager/ResourceManager.h"
#include "../data/PlayerInfo.h"
#include "UIHeroManageLayer.h"
#include "UITeamTalentLayer.h"
#include "../util/CocosUtils.h"
#include "../manager/AudioManager.h"
#define MAIN_CSB_FILE "ui/page/ui_home_page.csb"
#define LEVEL_CSB_FILE "ui/page/ui_home_detail.csb"
using namespace cocos2d;
using namespace cocostudio::timeline;
UIHomeLayer::UIHomeLayer() :
_map_data( nullptr )
{
}
UIHomeLayer::~UIHomeLayer() {
CC_SAFE_RELEASE( _map_data );
ActionTimelineCache::getInstance()->removeAction( MAIN_CSB_FILE );
}
UIHomeLayer* UIHomeLayer::create() {
UIHomeLayer* ret = new UIHomeLayer();
if( ret && ret->init() ) {
ret->autorelease();
return ret;
}
else {
CC_SAFE_DELETE( ret );
return nullptr;
}
}
bool UIHomeLayer::init() {
//detail
std::string level_csb_file = FileUtils::getInstance()->fullPathForFilename( LEVEL_CSB_FILE );
_level_node = cocos2d::CSLoader::getInstance()->createNode( level_csb_file );
this->addChild( _level_node );
_level_node->setName( "level_node" );
_background_node = dynamic_cast<Sprite*>( _level_node->getChildByName( "background" ) );
ui::Button* btn_back = dynamic_cast<ui::Button*>( _level_node->getChildByName( "backButton" ) );
btn_back->addTouchEventListener( CC_CALLBACK_2( UIHomeLayer::onBackButtonTouched, this ) );
ui::Button* btn_start = dynamic_cast<ui::Button*>( _level_node->getChildByName( "battleButton" ) );
btn_start->addTouchEventListener( CC_CALLBACK_2( UIHomeLayer::onStartButtonTouched, this ) );
ui::Text* mission_label_1 = dynamic_cast<ui::Text*>( _level_node->getChildByName( "lb_mission_1" ) );
ui::Text* mission_label_2 = dynamic_cast<ui::Text*>( _level_node->getChildByName( "lb_mission_2" ) );
ui::Text* mission_label_3 = dynamic_cast<ui::Text*>( _level_node->getChildByName( "lb_mission_3" ) );
_mission_labels.pushBack( mission_label_1 );
_mission_labels.pushBack( mission_label_2 );
_mission_labels.pushBack( mission_label_3 );
Sprite* sp_star_1 = dynamic_cast<Sprite*>( _level_node->getChildByName( "sp_star_1" ) );
Sprite* sp_star_2 = dynamic_cast<Sprite*>( _level_node->getChildByName( "sp_star_2" ) );
Sprite* sp_star_3 = dynamic_cast<Sprite*>( _level_node->getChildByName( "sp_star_3" ) );
_stars.pushBack( sp_star_1 );
_stars.pushBack( sp_star_2 );
_stars.pushBack( sp_star_3 );
_level_node->setVisible( false );
_lb_title = dynamic_cast<ui::Text*>( _level_node->getChildByName( "lb_title" ) );
_lb_title->setAdditionalKerning( -4.0f );
_lb_level_desc = dynamic_cast<ui::Text*>( _level_node->getChildByName( "lb_level_desc" ) );
_sp_boss_frame = dynamic_cast<Sprite*>( _level_node->getChildByName( "sp_boss_frame" ) );
_nd_diff = _level_node->getChildByName( "nd_diff" );
//main
std::string main_csb_file = FileUtils::getInstance()->fullPathForFilename( MAIN_CSB_FILE );
_main_node = cocos2d::CSLoader::getInstance()->createNode( main_csb_file );
this->addChild( _main_node );
_main_node->setName( "main_node" );
_panel_action = ActionTimelineCache::getInstance()->loadAnimationActionWithFlatBuffersFile( main_csb_file );
_lb_player_name = dynamic_cast<ui::Text*>( _main_node->getChildByName( "lb_player_name" ) );
_lb_player_name->setAdditionalKerning( -5.0f );
_lb_team_level = dynamic_cast<ui::Text*>( _main_node->getChildByName( "lb_team_lv" ) );
ui::Layout* pn_wheel = dynamic_cast<ui::Layout*>( _main_node->getChildByName( "pn_wheel" ) );
pn_wheel->addTouchEventListener( CC_CALLBACK_2( UIHomeLayer::onDifficultyTouched, this ) );
_scrollview = dynamic_cast<ui::ScrollView*>( _main_node->getChildByName( "mapScrollView" ) );
ui::Button* btn_store = dynamic_cast<ui::Button*>( _main_node->getChildByName( "btn_store" ) );
btn_store->addTouchEventListener( CC_CALLBACK_2( UIHomeLayer::onStoreTouched, this ) );
ui::Button* btn_team_skill = dynamic_cast<ui::Button*>( _main_node->getChildByName( "btn_team_skill" ) );
btn_team_skill->addTouchEventListener( CC_CALLBACK_2( UIHomeLayer::onTeamSkillTouched, this ) );
ui::Button* btn_hero = dynamic_cast<ui::Button*>( _main_node->getChildByName( "btn_hero" ) );
btn_hero->addTouchEventListener( CC_CALLBACK_2( UIHomeLayer::onHeroTouched, this ) );
this->loadMapOfDifficulty( 1 );
this->loadDeployedHeros();
for( auto node : _scrollview->getChildren() ) {
ui::Button* btn = dynamic_cast<ui::Button*>( node );
if( btn ) {
btn->addTouchEventListener( CC_CALLBACK_2( UIHomeLayer::onLevelTouched, this ) );
}
}
_currency_layer = UICurrencyLayer::create();
this->addChild( _currency_layer, 1000 );
_difficulty = eLevelDifficulty::LevelDiffEasy;
this->updatePlayerInfo( PlayerInfo::getInstance() );
if( PlayerInfo::getInstance()->isNewUser() ) {
UIHeroManageLayer* hero_layer = UIHeroManageLayer::create();
this->addChild( hero_layer, 2 );
hero_layer->setVisible( false );
}
return true;
}
void UIHomeLayer::onEnterTransitionDidFinish() {
Layer::onEnterTransitionDidFinish();
PlayerInfo::getInstance()->registerListener( PLAYER_INFO_BASE_INFO, this );
this->updatePlayerInfo( PlayerInfo::getInstance() );
AudioManager::getInstance()->playMusic( "audio/common/bg_home.mp3", true );
}
void UIHomeLayer::onExitTransitionDidStart() {
Layer::onExitTransitionDidStart();
PlayerInfo::getInstance()->unregisterListener( PLAYER_INFO_BASE_INFO, this );
AudioManager::getInstance()->stopMusic( "audio/common/bg_home.mp3" );
}
void UIHomeLayer::updatePlayerInfo( PlayerInfo* player_info ) {
_lb_player_name->setString( player_info->getPlayerName() );
_lb_team_level->setString( Utils::toStr( player_info->getTeamLevel() ) );
}
void UIHomeLayer::onStartButtonTouched( cocos2d::Ref* sender, cocos2d::ui::Widget::TouchEventType type ) {
if( type == cocos2d::ui::Widget::TouchEventType::ENDED ) {
CocosUtils::playTouchEffect();
cocos2d::Vector<cocos2d::Ref*> a_ref_params;
a_ref_params.pushBack( _map_data );
cocos2d::ValueMap a_value_params;
a_value_params["is_pvp"] = Value( _is_pvp );
a_value_params["level_id"] = Value( _level_id );
SceneConfig* scene_config = SceneConfig::create( a_ref_params, a_value_params );
SceneManager::getInstance()->transitToScene( eSceneName::SceneBattle, scene_config );
}
}
void UIHomeLayer::onBackButtonTouched( cocos2d::Ref* sender, cocos2d::ui::Widget::TouchEventType type ) {
if( type == cocos2d::ui::Widget::TouchEventType::ENDED ) {
CocosUtils::playTouchEffect();
_level_node->setVisible( false );
_main_node->setVisible( true );
_currency_layer->setVisible( true );
}
}
void UIHomeLayer::onLevelTouched( cocos2d::Ref* sender, cocos2d::ui::Widget::TouchEventType type ) {
if( type == cocos2d::ui::Widget::TouchEventType::ENDED ) {
CocosUtils::playTouchEffect();
_main_node->setVisible( false );
_level_node->setVisible( true );
_currency_layer->setVisible( false );
auto node = dynamic_cast<Node*>( sender );
int tag = node->getTag();
_level_id = Utils::stringFormat( "%d%03d", (int)_difficulty, tag );
const ValueMap& all_level_config = ResourceManager::getInstance()->getLevelConfig();
const ValueMap& level_config = all_level_config.at( _level_id ).asValueMap();
MapData* new_map_data = MapData::create( level_config.at( "map_res" ).asString(), level_config.at( "map_meta" ).asString() );
this->setMapData( new_map_data );
_is_pvp = false;
auto itr = level_config.find( "is_pvp" );
if( itr != level_config.end() ) {
_is_pvp = itr->second.asBool();
}
const ValueMap& meta_json = _map_data->getMetaJson();
itr = meta_json.find( "tasks" );
if( itr != meta_json.end() ) {
const ValueVector& task_array = itr->second.asValueVector();
int task_count = (int)task_array.size();
for( int i = 0; i < _mission_labels.size(); i++ ) {
if( i < task_count ) {
_mission_labels.at( i )->setString( task_array.at( i ).asValueMap().at( "desc" ).asString() );
}
else {
_mission_labels.at( i )->setString( "" );
}
}
}
int star = PlayerInfo::getInstance()->getLevelStar( Utils::toInt( _level_id ) );
for( int i = 0; i < star; i++ ) {
_stars.at( i )->setVisible( true );
}
if( star < 3 ) {
for( int i = star; i < 3; i++ ) {
_stars.at( i )->setVisible( false );
}
}
const ValueMap& level_conf = ResourceManager::getInstance()->getLevelConfig().at( _level_id ).asValueMap();
_lb_title->setString( level_conf.at( "name" ).asString() );
_lb_level_desc->setString( level_conf.at( "desc" ).asString() );
_nd_diff->removeAllChildren();
if( _difficulty == eLevelDifficulty::LevelDiffEasy ) {
Sprite* sp_diff = Sprite::createWithSpriteFrameName( "ui_home_detail_putong.png" );
_nd_diff->addChild( sp_diff );
}
else if( _difficulty == eLevelDifficulty::LevelDiffMedium ) {
Sprite* sp_diff = Sprite::createWithSpriteFrameName( "ui_home_detail_jingying.png" );
_nd_diff->addChild( sp_diff );
}
}
}
void UIHomeLayer::onStoreTouched( cocos2d::Ref* sender, cocos2d::ui::Widget::TouchEventType type ) {
if( type == cocos2d::ui::Widget::TouchEventType::ENDED ) {
CocosUtils::playTouchEffect();
}
}
void UIHomeLayer::onHeroTouched( cocos2d::Ref* sender, cocos2d::ui::Widget::TouchEventType type ) {
if( type == cocos2d::ui::Widget::TouchEventType::ENDED ) {
CocosUtils::playTouchEffect();
UIHeroManageLayer* hero_layer = dynamic_cast<UIHeroManageLayer*>( this->getChildByName( "hero_layer" ) );
if( hero_layer ) {
hero_layer->setVisible( true );
}
else {
hero_layer = UIHeroManageLayer::create();
this->addChild( hero_layer, 2 );
}
}
}
void UIHomeLayer::onTeamSkillTouched( cocos2d::Ref* sender, cocos2d::ui::Widget::TouchEventType type ){
if( type == cocos2d::ui::Widget::TouchEventType::ENDED ) {
CocosUtils::playTouchEffect();
UITeamTalentLayer* talent_layer = UITeamTalentLayer::create();
this->addChild( talent_layer, 2 );
}
}
eLevelDifficulty UIHomeLayer::getDifficulty() {
return _difficulty;
}
void UIHomeLayer::setDifficulty( eLevelDifficulty diff ) {
if( _difficulty != diff ) {
_difficulty = diff;
this->stopAction( _panel_action );
this->runAction( _panel_action );
switch( _difficulty ) {
case eLevelDifficulty::LevelDiffEasy:
_panel_action->play( "to_easy", false );
break;
case eLevelDifficulty::LevelDiffMedium:
_panel_action->play( "to_medium", false );
break;
case eLevelDifficulty::LevelDiffHard:
_panel_action->play( "to_hard", false );
break;
default:
break;
}
}
}
void UIHomeLayer::onDifficultyTouched( cocos2d::Ref* sender, cocos2d::ui::Widget::TouchEventType type ) {
if( type == cocos2d::ui::Widget::TouchEventType::ENDED ) {
CocosUtils::playTouchEffect();
int old_diff = (int)_difficulty;
int new_diff = old_diff % 2 + 1;
this->setDifficulty( (eLevelDifficulty)( new_diff ) );
this->loadMapOfDifficulty( new_diff );
}
}
void UIHomeLayer::setMapData( MapData* map_data ) {
CC_SAFE_RETAIN( map_data );
CC_SAFE_RELEASE( _map_data );
_map_data = map_data;
}
void UIHomeLayer::loadDeployedHeros() {
ValueVector deployed_units = PlayerInfo::getInstance()->getPlayerDeployedUnitsInfo();
for( int i = 0; i < 5; i++ ) {
Sprite* shadow = dynamic_cast<Sprite*>( _main_node->getChildByName( Utils::stringFormat( "hero_%d", i + 1 ) ) );
if( shadow ) {
shadow->removeAllChildren();
if( i < deployed_units.size() ) {
shadow->setVisible( true );
const ValueMap& info = deployed_units.at( i ).asValueMap();
std::string name = info.at( "name" ).asString();
std::string resource = ResourceManager::getInstance()->getPathForResource( name, eResourceType::Character_Front );
spine::SkeletonAnimation* skeleton = ArmatureManager::getInstance()->createArmature( resource );
skeleton->setAnimation( 0, "Idle", true );
skeleton->setPosition( Point( shadow->getContentSize().width / 2, shadow->getContentSize().height / 2 ) );
shadow->addChild( skeleton );
const ValueMap& unit_config = ResourceManager::getInstance()->getUnitData( name );
skeleton->setScale( unit_config.at( "scale" ).asFloat() * 1.2f );
}
else {
shadow->setVisible( false );
}
}
}
}
void UIHomeLayer::becomeTopLayer() {
this->loadDeployedHeros();
}
void UIHomeLayer::loadMapOfDifficulty( int diff ) {
PlayerInfo* player_info = PlayerInfo::getInstance();
const ValueMap& all_level_config = ResourceManager::getInstance()->getLevelConfig();
int count = (int)all_level_config.size() / 2;
for( int i = 1; i <= count; i++ ) {
int level_id = diff * 1000 + i;
std::string btn_name = Utils::stringFormat( "btn_level_%d", i );
ui::Button* btn = dynamic_cast<ui::Button*>( _scrollview->getChildByName( btn_name ) );
ui::Layout* pn_star = dynamic_cast<ui::Layout*>( _scrollview->getChildByName( Utils::stringFormat( "pn_level_%d", i ) ) );
switch( diff ) {
case 1:
{
//easy difficulty
if( player_info->isLevelCompleted( level_id ) ) {
pn_star->setVisible( true );
int level_star = player_info->getLevelStar( level_id );
int j;
for( j = 1; j <= level_star; j++ ) {
Sprite* sp_star = dynamic_cast<Sprite*>( pn_star->getChildByName( Utils::stringFormat( "star_%d", j ) ) );
sp_star->setVisible( true );
}
for( int k = j; k <= 3; k++ ) {
Sprite* sp_star = dynamic_cast<Sprite*>( pn_star->getChildByName( Utils::stringFormat( "star_%d", k ) ) );
sp_star->setVisible( false );
}
btn->setVisible( true );
btn->loadTextureNormal( "ui_home_cp_completed.png", ui::Widget::TextureResType::PLIST );
btn->loadTexturePressed( "ui_home_cp_completed.png", ui::Widget::TextureResType::PLIST );
}
else {
pn_star->setVisible( false );
if( ( i == 1 ) || player_info->isLevelCompleted( level_id - 1 ) ) {
btn->setVisible( true );
btn->loadTextureNormal( "ui_home_cp_opened.png", ui::Widget::TextureResType::PLIST );
btn->loadTexturePressed( "ui_home_cp_opened.png", ui::Widget::TextureResType::PLIST );
}
else {
btn->setVisible( false );
}
}
}
break;
case 2:
{
//medium difficulty
if( player_info->isLevelCompleted( level_id ) ) {
pn_star->setVisible( true );
int level_star = player_info->getLevelStar( level_id );
int j;
for( j = 1; j <= level_star; j++ ) {
Sprite* sp_star = dynamic_cast<Sprite*>( pn_star->getChildByName( Utils::stringFormat( "star_%d", j ) ) );
sp_star->setVisible( true );
}
for( int k = j; k <= 3; k++ ) {
Sprite* sp_star = dynamic_cast<Sprite*>( pn_star->getChildByName( Utils::stringFormat( "star_%d", k ) ) );
sp_star->setVisible( false );
}
btn->setVisible( true );
btn->loadTextureNormal( "ui_home_cp_completed.png", ui::Widget::TextureResType::PLIST );
btn->loadTexturePressed( "ui_home_cp_completed.png", ui::Widget::TextureResType::PLIST );
}
else {
pn_star->setVisible( false );
if( player_info->getLevelStar( level_id - 1000 ) == 3 ) {
btn->setVisible( true );
btn->loadTextureNormal( "ui_home_cp_opened.png", ui::Widget::TextureResType::PLIST );
btn->loadTexturePressed( "ui_home_cp_opened.png", ui::Widget::TextureResType::PLIST );
}
else {
btn->setVisible( false );
}
}
}
break;
case 3:
btn->setVisible( false );
break;
default:
break;
}
}
}
|
//
// request_parser.hpp
// ~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2017 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef HTTP_REQUEST_PARSER_H
#define HTTP_REQUEST_PARSER_H
#include <tuple>
#include <string>
#include <vector>
#include "request.h"
/// Parser for incoming requests.
class request_parser
{
public:
/// Construct ready to parse the request method.
request_parser();
/// Reset to initial parser state.
void reset();
/// Result of parse.
enum result_type { good, bad, indeterminate };
template <typename InputIterator>
void parse(Request& request_, InputIterator begin, InputIterator end) {
request req_struct;
result_type result;
InputIterator bodyStart;
std::tie(result, bodyStart) = parse_request(req_struct, begin, end);
//if result type is good then set request_ fields
if(result == good) {
request_.setProper(true);
request_.setIndeterminate(false);
request_.setMethod(req_struct.method);
request_.setUri(req_struct.uri);
request_.setVersion("HTTP/" + std::to_string(req_struct.http_version_major) + "." + std::to_string(req_struct.http_version_minor));
for(const auto header_ : req_struct.headers) {
request_.pushHeader(header_.name, header_.value);
}
parse_body(req_struct, bodyStart, end);
request_.setBody(req_struct.body);
}
else if(result == bad) {
request_.setIndeterminate(false);
request_.setProper(false);
} else {
request_.setIndeterminate(true);
}
}
private:
// header structure
struct header
{
std::string name;
std::string value;
};
// request structure
struct request
{
std::string method;
std::string uri;
int http_version_major;
int http_version_minor;
std::vector<header> headers;
std::string body;
};
/// Parse some data. The enum return value is good when a complete request has
/// been parsed, bad if the data is invalid, indeterminate when more data is
/// required. The InputIterator return value indicates how much of the input
/// has been consumed.
template <typename InputIterator>
std::tuple<result_type, InputIterator> parse_request(request& req,
InputIterator begin, InputIterator end)
{
while (begin != end)
{
result_type result = consume(req, *begin++);
if (result == good || result == bad)
return std::make_tuple(result, begin);
}
return std::make_tuple(indeterminate, begin);
}
template <typename InputIterator>
void parse_body(request& req,
InputIterator begin, InputIterator end)
{
while (begin != end)
{
consumeBody(req, *begin++);
}
}
void consumeBody(request& req, char input);
/// Handle the next character of input.
result_type consume(request& req, char input);
/// Check if a byte is an HTTP character.
static bool is_char(int c);
/// Check if a byte is an HTTP control character.
static bool is_ctl(int c);
/// Check if a byte is defined as an HTTP tspecial character.
static bool is_tspecial(int c);
/// Check if a byte is a digit.
static bool is_digit(int c);
/// The current state of the parser.
enum state
{
method_start,
method,
uri,
http_version_h,
http_version_t_1,
http_version_t_2,
http_version_p,
http_version_slash,
http_version_major_start,
http_version_major,
http_version_minor_start,
http_version_minor,
expecting_newline_1,
header_line_start,
header_lws,
header_name,
space_before_header_value,
header_value,
expecting_newline_2,
expecting_newline_3
} state_;
};
#endif // HTTP_REQUEST_PARSER_HPP
|
#include "../Include/Factory_Btn_Line.h"
#include "../Include/Botton.h"
Botton * Factory_Btn_Line::generate()
{
Botton* tmp = new Botton;
tmp = new Botton;
tmp->setSize(60, 30);
tmp->setPos(1170, 600);
tmp->loadTexture("Textures/Line.bmp");
tmp->setKey(7);
return tmp;
}
|
#define LED_GREEN 9
#define SWITCH 8
void setup() {
pinMode(LED_GREEN, OUTPUT);
pinMode(SWITCH, INPUT);
Serial.begin(9600);
Serial.println("start");
}
void loop() {
if(digitalRead(SWITCH) == LOW){
Serial.println("Switch ON.");
digitalWrite(LED_GREEN, HIGH);
}
else{
Serial.println("Switch OFF");
digitalWrite(LED_GREEN, LOW);
}
delay(100);
}
|
#include <iostream>
#include <cstdio>
#include <string.h>
#include <stack>
#include <string>
#include <vector>
using namespace std;
int m,n,f;
char *str;
int A[4010][4010];
long long int findla(int hist[],int n)
{
stack<int> height;
stack<int> index;
long long lA=0;
int li,lh;
for(int i=0;i<n;i++)
{
if(height.empty()||hist[i]>height.top())
{
height.push(hist[i]);
index.push(i);
}
else if(hist[i]<height.top())
{
while(1)
{
if(height.empty()||hist[i]>=height.top()) break;
li=index.top();
lh=height.top();
index.pop();
height.pop();
long long tA=lh*(i-li)*1LL;
if(tA>lA)
lA=tA;
}
height.push(hist[i]);
index.push(li);
}
}
while(!height.empty())
{
li=index.top();
lh=height.top();
index.pop();
height.pop();
//cout<<lh<<li<<endl;
long long tA=lh*(n-li)*1LL;
if(tA>lA)
lA=tA;
}
return lA;
}
int main()
{
str = new char[4010];
while(1){
scanf("%d%d",&n,&m);
if(m==0 && n==0)
return 0;
scanf("%d",&f);
// memset(str,'\0',sizeof(str));
for(int i=0;i<n;i++){
scanf("%s",str);
// int l = strlen(str);
for(int j=0;j<m;j++){
if(str[j]=='H')
A[i][j] = 1;
else
A[i][j] = 0;
}
}
long long int ans=0;
int tarr[4010];
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(i==0)
tarr[j]=A[i][j];
else
{
if(A[i][j]==1)
A[i][j]=tarr[j]=1+A[i-1][j];
else
tarr[j]=0;
}
}
long long int t=findla(tarr,m);
if(t>ans)
ans=t;
}
printf("%lld\n",(f*ans));
}
//system("pause");
return 0;
}
|
/* --- CYCLE DETECTION --- */
#include <bits/stdc++.h>
using namespace std;
/*
Given ADJ LIST as graph representation, find if the graph
is acyclic or not.
We can use DFS. Once we initialize DFS, and maintain a "cycle
stack". If we visit a node that has already been pushed to the stack,
it means we found a cycle.
*/
#define all(x) x.begin(), x.end()
#define found(i, x) find(all(x), i) != x.end()
const int MAXN = 5;
vector<vector<int>> adj(MAXN);
vector<bool> visited(MAXN);
bool cycle_detect(vector<int> cs, int n) {
if (found(n, cs)) {
return true;
} else if (visited[n]) {
return false;
} else {
bool exist = false;
for (int i : adj[n]) {
exist = true;
break;
}
if (exist) {
cs.push_back(n);
visited[n] = true;
for (int i : adj[n])
if (cycle_detect(cs, i)) return true;
}
}
return false;
}
int main() {
adj[1].push_back(2);
adj[2].push_back(3);
adj[3].push_back(1);
printf("%s\n", cycle_detect({}, 1) ? "Cycle" : "No Cycle");
}
|
#include "Node.h"
Node::Node(int v)
{
value = v;
left = NULL;
right = NULL;
next = NULL;
prev = NULL;
parent = NULL;
}
// Recursively delete all child nodes
Node::~Node()
{
if(left)
delete left;
if(right)
delete right;
}
// This function will remove a node from its parent
void Node::removeFromParent()
{
Node* parent = this->parent;
if(parent == NULL)
return;
if(parent->left == this)
parent->left = NULL;
else if(parent->right == this)
parent->right = NULL;
this->parent = NULL;
}
|
//
// MapData.h
// Boids
//
// Created by Xin Xu on 11/18/14.
//
//
#ifndef __Boids__MapData__
#define __Boids__MapData__
#include "cocos2d.h"
enum class TMXObjectLayerFlag {
Background = 1,
OnGround = 2,
Object = 4
};
class MapData : public cocos2d::Ref {
public:
MapData();
virtual ~MapData();
static MapData* create( const std::string& map_path, const std::string& meta_path );
virtual bool init( const std::string& map_path, const std::string& meta_path );
const std::string& getMetaData();
void dumpMetaData(const std::string& content);
const std::string& getMapData();
cocos2d::TMXTiledMap *generateTiledMapWithFlags(int flags);
const cocos2d::ValueMap& getMapJson() { return _map_json; }
const cocos2d::ValueMap& getMetaJson() { return _meta_json; }
cocos2d::ValueMap getAreaMapByName( const std::string& name );
cocos2d::ValueVector getAreasVectorByTag( const std::string& tag_name );
cocos2d::ValueMap getAreaMapByPosition( const cocos2d::Point& pos );
cocos2d::Sprite* spriteFromObject( cocos2d::TMXTiledMap* map, const cocos2d::Value& o, bool createFromCache );
private:
cocos2d::ValueMap _map_json;
cocos2d::ValueMap _meta_json;
std::string _mapData;
std::string _metaData;
std::string _map_path;
std::string _meta_path;
void preprocessMapData();
};
#endif /* defined(__Boids__MapData__) */
|
#include "sa_lcp.hpp"
#include <unordered_set>
#include <cassert>
#include <divsufsort.h>
#include <divsufsort64.h>
namespace stool
{
uint64_t intervalTotalCount = 0;
uint64_t rlcpCounter = 0;
void constructSA(string &text, vector<uint64_t> &sa)
{
uint64_t n = text.size();
sa.resize(n);
int64_t *SA = (int64_t *)malloc(n * sizeof(int64_t));
divsufsort64((const unsigned char *)&text[0], SA, n);
for (uint64_t i = 0; i < text.size(); ++i)
{
sa[i] = SA[i];
}
free(SA);
}
void constructISA(string &text, vector<uint64_t> &sa, vector<uint64_t> &isa)
{
uint64_t n = text.size();
isa.resize(n);
for (uint64_t i = 0; i < text.size(); ++i)
{
isa[sa[i]] = i;
}
}
void constructSA(string &text, vector<uint64_t> &sa, vector<uint64_t> &isa)
{
std::cout << "constructing Suffix Array...";
uint64_t n = text.size();
isa.resize(n);
sa.resize(n);
int64_t *SA = (int64_t *)malloc(n * sizeof(int64_t));
divsufsort64((const unsigned char *)&text[0], SA, n);
for (uint64_t i = 0; i < text.size(); ++i)
{
sa[i] = SA[i];
isa[SA[i]] = i;
}
free(SA);
std::cout << "[END]" << std::endl;
}
void constructLCP(string &text, vector<uint64_t> &lcp, vector<uint64_t> &sa, vector<uint64_t> &isa)
{
lcp.resize(text.size(), 0);
uint64_t n = text.size();
uint64_t k = 0;
if (text.size() > 1000000)
std::cout << "Constructing LCP Array" << std::flush;
for (uint64_t i = 0; i < n; i++)
{
assert(i < n);
uint64_t x = isa[i];
assert(x < n);
if (x == 0)
{
lcp[x] = 0;
}
else
{
while (sa[x] + k < n && sa[x - 1] + k < n && text[sa[x] + k] == text[sa[x - 1] + k])
{
assert(sa[x] + k < n);
assert(sa[x - 1] + k < n);
k++;
}
}
lcp[x] = k;
assert(x == 0 || (x > 0 && ((n - sa[x - 1]) >= k)));
if (k > 0)
k--;
}
if (n > 1000000)
std::cout << "[END]" << std::endl;
}
namespace StringFunctions
{
uint64_t LCE(string &text, uint64_t i, uint64_t j)
{
if (i > j)
return LCE(text, j, i);
uint64_t max = text.size() - j;
uint64_t x = 0;
for (x = 0; x < max; x++)
{
if (text[i + x] != text[j + x])
{
break;
}
}
return x;
}
void reverse(string &text)
{
string tmp = text;
for (uint64_t i = 0; i < text.size(); i++)
{
text[i] = tmp[text.size() - 1 - i];
}
}
} // namespace StringFunctions
} // namespace stool
|
#include "dialog.h"
#include "ui_dialog.h"
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QDebug>
#include <QtWidgets>
#include <cstdint>
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
dotrgb_is_available = false;
dotrgb_port_name = "";
dotrgb = new QSerialPort;
/*
qDebug() << "Number of available serial ports: " << QSerialPortInfo::availablePorts().length();
foreach (const QSerialPortInfo &serialPortInfo, QSerialPortInfo::availablePorts()) {
qDebug() << "Has vendor ID: " << serialPortInfo.hasVendorIdentifier();
if(serialPortInfo.hasVendorIdentifier()){
qDebug() << "Vendor ID: " << serialPortInfo.vendorIdentifier();
}
qDebug() << "Has product ID: " << serialPortInfo.hasProductIdentifier();
if(serialPortInfo.hasProductIdentifier()){
qDebug() << "Product ID: " << serialPortInfo.productIdentifier();
}
}
*/
foreach (const QSerialPortInfo &serialPortInfo, QSerialPortInfo::availablePorts()) {
if(serialPortInfo.hasVendorIdentifier() && serialPortInfo.hasProductIdentifier()){
if(serialPortInfo.vendorIdentifier() == dotrgb_vendor_id){
if(serialPortInfo.productIdentifier() == dotrgb_product_id){
dotrgb_port_name = serialPortInfo.portName();
dotrgb_is_available = true;
}
}
}
}
if(dotrgb_is_available){
dotrgb->setPortName(dotrgb_port_name);
dotrgb->open(QSerialPort::WriteOnly);
dotrgb->setBaudRate(QSerialPort::Baud9600);
dotrgb->setDataBits(QSerialPort::Data8);
dotrgb->setParity(QSerialPort::NoParity);
dotrgb->setStopBits(QSerialPort::OneStop);
dotrgb->setFlowControl(QSerialPort::NoFlowControl);
}else{
QMessageBox::warning(this, "Port Error", "Couldn't find the dotrgb!");
}
dotrgb_values.append('#');
}
Dialog::~Dialog()
{
if(dotrgb->isOpen()){
dotrgb->close();
}
delete ui;
}
void Dialog::on_RED_stateChanged(int arg1){
Dialog::updateDotRGB(QString("#r0%1").arg(arg1));
qDebug() << arg1;
/*
//dotrgb_values.append('a');
dotrgb_values[1] = arg1;
qDebug() << arg1;
qDebug() << dotrgb_values;
*/
/*
dotrgb_values[1] = '1';
dotrgb_values[2] = '#';
//dotrgb_values[3] = "\0";
//dotrgb_values[3] = 1;
qDebug() << arg1;
qDebug() << dotrgb_values;
//dotrgb_values[4] = '#';
Dialog::updateDotRGB(dotrgb_values);
*/
}
void Dialog::on_RED_2_stateChanged(int arg1){
Dialog::updateDotRGB(QString("#r1%1").arg(arg1));
qDebug() << arg1;
}
void Dialog::on_RED_3_stateChanged(int arg1){
Dialog::updateDotRGB(QString("#r2%1").arg(arg1));
qDebug() << arg1;
}
void Dialog::on_RED_4_stateChanged(int arg1){
Dialog::updateDotRGB(QString("#r3%1").arg(arg1));
qDebug() << arg1;
}
void Dialog::on_RED_5_stateChanged(int arg1){
Dialog::updateDotRGB(QString("#r4%1").arg(arg1));
qDebug() << arg1;
}
void Dialog::on_RED_6_stateChanged(int arg1){
Dialog::updateDotRGB(QString("#r5%1").arg(arg1));
qDebug() << arg1;
}
void Dialog::on_RED_7_stateChanged(int arg1){
Dialog::updateDotRGB(QString("#r6%1").arg(arg1));
qDebug() << arg1;
}
void Dialog::on_RED_8_stateChanged(int arg1){
Dialog::updateDotRGB(QString("#r7%1").arg(arg1));
qDebug() << arg1;
}
void Dialog::on_RED_9_stateChanged(int arg1){
Dialog::updateDotRGB(QString("#r8%1").arg(arg1));
qDebug() << arg1;
}
void Dialog::on_GREEN_stateChanged(int arg1){
Dialog::updateDotRGB(QString("#g0%1").arg(arg1));
qDebug() << arg1;
}
void Dialog::on_GREEN_2_stateChanged(int arg1){
Dialog::updateDotRGB(QString("#g1%1").arg(arg1));
qDebug() << arg1;
}
void Dialog::on_GREEN_3_stateChanged(int arg1){
Dialog::updateDotRGB(QString("#g2%1").arg(arg1));
qDebug() << arg1;
}
void Dialog::on_GREEN_4_stateChanged(int arg1){
Dialog::updateDotRGB(QString("#g3%1").arg(arg1));
qDebug() << arg1;
}
void Dialog::on_GREEN_5_stateChanged(int arg1){
Dialog::updateDotRGB(QString("#g4%1").arg(arg1));
qDebug() << arg1;
}
void Dialog::on_GREEN_6_stateChanged(int arg1){
Dialog::updateDotRGB(QString("#g5%1").arg(arg1));
qDebug() << arg1;
}
void Dialog::on_GREEN_7_stateChanged(int arg1){
Dialog::updateDotRGB(QString("#g6%1").arg(arg1));
qDebug() << arg1;
}
void Dialog::on_GREEN_8_stateChanged(int arg1){
Dialog::updateDotRGB(QString("#g7%1").arg(arg1));
qDebug() << arg1;
}
void Dialog::on_GREEN_9_stateChanged(int arg1){
Dialog::updateDotRGB(QString("#g8%1").arg(arg1));
qDebug() << arg1;
}
void Dialog::on_BLUE_stateChanged(int arg1){
Dialog::updateDotRGB(QString("#b0%1").arg(arg1));
qDebug() << arg1;
}
void Dialog::on_BLUE_2_stateChanged(int arg1){
Dialog::updateDotRGB(QString("#b1%1").arg(arg1));
qDebug() << arg1;
}
void Dialog::on_BLUE_3_stateChanged(int arg1){
Dialog::updateDotRGB(QString("#b2%1").arg(arg1));
qDebug() << arg1;
}
void Dialog::on_BLUE_4_stateChanged(int arg1){
Dialog::updateDotRGB(QString("#b3%1").arg(arg1));
qDebug() << arg1;
}
void Dialog::on_BLUE_5_stateChanged(int arg1){
Dialog::updateDotRGB(QString("#b4%1").arg(arg1));
qDebug() << arg1;
}
void Dialog::on_BLUE_6_stateChanged(int arg1){
Dialog::updateDotRGB(QString("#b5%1").arg(arg1));
qDebug() << arg1;
}
void Dialog::on_BLUE_7_stateChanged(int arg1){
Dialog::updateDotRGB(QString("#b6%1").arg(arg1));
qDebug() << arg1;
}
void Dialog::on_BLUE_8_stateChanged(int arg1){
Dialog::updateDotRGB(QString("#b7%1").arg(arg1));
qDebug() << arg1;
}
void Dialog::on_BLUE_9_stateChanged(int arg1){
Dialog::updateDotRGB(QString("#b8%1").arg(arg1));
qDebug() << arg1;
}
void Dialog::updateDotRGB(QString command){
if(dotrgb->isWritable()){
dotrgb->write(command.toStdString().c_str());
}else{
qDebug() << "Couldn't write to serial!";
}
}
|
#ifndef __DUI_RES_LOADER_H__
#define __DUI_RES_LOADER_H__
#include "DUIImage.h"
#include "DUICursor.h"
DUI_BGN_NAMESPCE
class DUILIB_API CResLoader
{
public:
CResLoader();
~CResLoader();
void CResLoader::ToAbsolutePath(CDUIString& lpszFileName);
CRefPtr<CImageList> LoadImageFromFile(const CDUIString& strFileName);
CRefPtr<CImageList> LoadImageFromDll(const CDUIString& lpszDllName, const CDUIString& strResID, const CDUIString& strResType);
CRefPtr<CImageList> LoadImageFromExe(const CDUIString& strResID, const CDUIString& strResType);
CRefPtr<CCursorObject> LoadCursorFromFile(const CDUIString& strFileName);
CRefPtr<CCursorObject> LoadCursorFromDll(const CDUIString& lpszDllName, const CDUIString& strResID, const CDUIString& strResType);
CRefPtr<CCursorObject> LoadCursorFromExe(const CDUIString& strResID, const CDUIString& strResType);
BOOL LoadXMLFromFile(const CDUIString& lpszFileName, CDUIString& pContent);
BOOL LoadXMLFromDll(const CDUIString& lpszDllName, const CDUIString& lpszResID, const CDUIString& lpszResType, CDUIString& pContent);
BOOL LoadXMLFromExe(const CDUIString& lpszResID, const CDUIString& lpszResType, CDUIString& pContent);
HINSTANCE LoadLibrary(const CDUIString& strFileName);
protected:
VOID FreeResDll();
HINSTANCE GetResInstance(const CDUIString& strDllName);
BOOL LoadStringFromResource(HINSTANCE hRes, const CDUIString& lpszResID, const CDUIString& lpszResType, CDUIString& pContent);
CRefPtr<CImageList> LoadImageFromResource(HINSTANCE hRes, const CDUIString& strResID, const CDUIString& strResType);
CRefPtr<CCursorObject> LoadCursorFromResource(HINSTANCE hRes, const CDUIString& strResID, const CDUIString& strResType);
protected:
HINSTANCE m_hResInstance;
};
DUI_END_NAMESPCE
#endif //__DUI_RES_LOADER_H__
|
#ifndef _MYEXCEPTION_H_
#define _MYEXCEPTION_H_
#include <iostream>
#include <cstring>
class MyException
{
public:
std::string message;
int type;
MyException()
{
message.clear();
type = 0;
}
MyException(const char* s, int e)
{
message = s;
type = e;
}
};
#endif
|
/*Manager.cpp
* Created by Chris Marques, Ryan Cox, and Nikolay Radaev
*/
#include <iostream>
#include <thread>
#include <chrono>
#include <string>
#include <vector>
#include <sstream>
#include <fstream>
#include <cstring>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <time.h>
#include <algorithm>
#include "project3.h"
using namespace std;
vector<Link> allLinks;
vector<SrcDest> packets;
ofstream file;
int nodes;
string thisIP;
int thisPort = 7000;
vector<int> fd_vector;
vector<int> ac_vector;
void error(char const *msg) {
perror(msg);
exit(1);
}
string getTime() {
time_t now = time(NULL);
tm * ptm = localtime(&now);
char buffer[32];
strftime(buffer, 32, "%a, %d.%m.%Y %H:%M:%S", ptm);
return buffer;
}
Link::Link(int src, int dest, int cost) {
Link::src = src;
Link::dest = dest;
Link::cost = cost;
}
void parseFile(string filename) {
ifstream inputFile(filename);
if (!inputFile.is_open()) {
cout << "Error opening the input file" << '\n';
exit(1);
}
cout << "Parsing File..." << endl;
file << getTime() << ": " << "Parsing a file" << '\n';
string line = "";
file << "\n-----PARSING FINISHED-----\n" << endl;
file << "\n-----LINKS PARSED-----\n" << endl;
int i = 0;
while (getline(inputFile, line)) {
if (i == 0) {
nodes = stoi(line);
file << getTime() << ": " << "\nNODES: " << nodes << endl;
getline(inputFile, line);
}
if (line.at(0) != '-') {
stringstream ss(line); // Turn the string into a stream.
string token;
vector<int> numbers;
while (getline(ss, token, ' ')) {
numbers.push_back(stoi(token));
}
allLinks.push_back(Link(numbers[0], numbers[1], numbers[2]));
file << "Src: " << allLinks[i].src << " | ";
file << "Dest: " << allLinks[i].dest << " | ";
file << "Cost: " << allLinks[i].cost << '\n';
i++;
} else {
int i = -1; //counter
file << "\n-----PACKETS PARSED-----\n" << endl;
while (getline(inputFile, line)) {
if (stoi(line) != -1) {
i++;
stringstream ss(line); // Turn the string into a stream.
string token;
vector<int> numbers;
while (getline(ss, token, ' ')) {
numbers.push_back(stoi(token));
}
packets.push_back(SrcDest { numbers[0], numbers[1] });
file << "Source: " << packets[i].src << " | ";
file << "Destination: " << packets[i].dest << '\n';
}
}
file << getTime() << ": " << "-----------------\n";
}
}
}
int acceptAny(int fds[], unsigned int count, struct sockaddr *addr, socklen_t *addrlen) {
fd_set readfds;
int maxfd, fd;
unsigned int i;
int status;
FD_ZERO(&readfds);
maxfd = -1;
for (i = 0; i < count; i++) {
FD_SET(fds[i], &readfds);
if (fds[i] > maxfd)
maxfd = fds[i];
}
status = select(maxfd + 1, &readfds, NULL, NULL, NULL);
if (status < 0)
return -1;
fd = -1;
for (i = 0; i < count; i++)
if (FD_ISSET(fds[i], &readfds)) {
fd = fds[i];
break;
}
if (fd == -1)
return -1;
else
return accept(fd, addr, addrlen);
}
/**
* These methods are for TCP connections.
* There are 2 methods for creating sockets: One for manager -> router and One for router -> manager
* There are methods for sending and receiving which work via FD and work on both router and manager
**/
//Create a router side TCP socket for connecting to the manager.
int createTCPSocket(string port) {
//Various variables for setting up socket and getting IP from socket, address info, etc.
int sockfd, bindErr, lisErr;
struct protoent *protoptr;
//Get protocol "name"
protoptr = getprotobyname("tcp");
//Create a TCP socket
sockfd = socket(AF_INET, SOCK_STREAM, protoptr->p_proto);
//Avoid "address already in use" error because machine(?) still waiting to send ack and keeps getting sent into TIMEWAIT.
int optval = 1;
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval);
if (sockfd < 0) {
char const *p = "ERROR creating socket";
error(p);
}
//Get/set addr info
struct addrinfo hints, *res;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
getaddrinfo(NULL, port.c_str(), &hints, &res);
//Bind the TCP socket
bindErr = bind(sockfd, res->ai_addr, res->ai_addrlen);
if (bindErr < 0) {
char const *p = "ERROR binding socket";
error(p);
}
//Listen on the TCP socket
lisErr = listen(sockfd, 25);
if (lisErr < 0) {
char const *p = "ERROR listening to socket";
error(p);
}
//Get the server IP (this was a lot harder than you would think... used beej's guide on gethostbyname)
char hostname[128];
struct hostent *he;
struct in_addr **addr_list;
gethostname(hostname, sizeof hostname);
he = gethostbyname(hostname);
addr_list = (struct in_addr **) he->h_addr_list;
//Print out important info
thisIP = inet_ntoa(*addr_list[0]);
file << getTime() << ": " << "Listening on: <" << thisIP << ", " << port << ">" << "\n\n";
return sockfd;
}
//Send to a TCP connection
void sendTCP(int fd, string message) {
//Sending
char buffer[9999];
//Writing a message to buffer + handling for too many characters.
memset(&buffer, 0, sizeof(buffer));
strcpy(buffer, message.c_str());
//Send message
send(fd, (char*) &buffer, strlen(buffer), 0);
file << getTime() << ": " << "Message sent." << endl;
}
//Try receiving from this TCP connection.
string receiveTCP(int fd) {
char buffer[9999];
memset(&buffer, 0, sizeof(buffer));
//receive file size
file << getTime() << ": " << "Waiting for message." << endl;
while (strlen(buffer) == 0) {
recv(fd, (char*) &buffer, sizeof(buffer), 0);
}
file << getTime() << ": " << "Received a message." << endl;
string str(buffer);
file << getTime() << ": " << str << endl;
return str;
}
string getRouterNeighbors(int routerID) {
string nd = to_string(nodes);
string ret = "*" + nd + "*";
vector<Link> neighbors;
for (size_t i = 0; i < allLinks.size(); i++) {
if ((allLinks[i].src == routerID) || allLinks[i].dest == routerID) {
neighbors.push_back(allLinks[i]);
}
}
if (neighbors.size() == 0) {
return "*None";
}
for (size_t i = 0; i < neighbors.size(); i++) {
ret = ret + to_string(neighbors[i].src) + "," + to_string(neighbors[i].dest) + "," + to_string(neighbors[i].cost) + ":";
}
ret = ret.substr(0, ret.length() - 1);
file << getTime() << ": " << "MESSAGE TO SEND TO ROUTER:" << ret << "" << endl;
return ret;
}
//This will call a router task; ie. building a router and running router class tashs
void buildRouter(int tid) {
//Create the router object
file << getTime() << ": " << "Router" << tid << " thread created and starting!" << '\n';
Router router(tid);
//Create the socket for the manager talking to a router
string routerPort = "" + (thisPort + tid);
router.setIP(thisIP);
router.setPort(thisPort + tid);
router.run(thisPort + tid - 1000);
file << getTime() << ": " << "Router" << tid << " created and given TCP info." << '\n';
//Once it reaches this point, the thread will quit.
file << getTime() << ": " << "Router" << tid << " quitting!" << '\n';
}
//THis is for running manager based tasks (ie. Sending and receiving packets)
void runManager(int num_threads) {
bool linksSent = false, tablesDone = false, broadcast = false, table = false, sent = false, quitting = false;
int waitingOn = num_threads, waitingOnFWD = num_threads, waitingOnBroad = num_threads, waitingOnTable = num_threads, waitingOnSent = packets.size(), waitingOnQuit = num_threads;
cout << "Creating Routers..." << endl;
for (int i = 0; i < num_threads; i++) {
file << "\n-----ROUTER " << i << " SOCKET CREATION-----\n";
file << getTime() << ": " << "Creating socket on port: " << (thisPort + i) << '\n';
fd_vector.push_back(createTCPSocket(to_string(thisPort + i)));
}
int accepted;
int* fds = &fd_vector[0];
struct sockaddr_storage their_addr;
socklen_t addr_size;
addr_size = sizeof their_addr;
//Send and receive link information
cout << "Linking TCP To Routers..." << endl;
while (!linksSent) {
//Accept initial connections
accepted = acceptAny(fds, num_threads, (struct sockaddr *) &their_addr, &addr_size);
//Solidify connections for later
ac_vector.push_back(accepted);
//Assuming all is well, start sending and receiving
if (accepted != -1) {
//Get port number from accepted
struct sockaddr_in sin;
socklen_t addrlen = sizeof(sin);
int local_port;
if (getsockname(accepted, (struct sockaddr *) &sin, &addrlen) == 0 && sin.sin_family == AF_INET && addrlen == sizeof(sin)) {
local_port = ntohs(sin.sin_port);
}
file << "\n-----ROUTER " << to_string(local_port - 7000) << " TCP LINK MESSAGING-----\n";
file << getTime() << ": " << "Accepted a connection on port: " << local_port << endl;
sendTCP(accepted, getRouterNeighbors(local_port - 7000));
string newMessage = receiveTCP(accepted);
if (newMessage == "Ready!") {
waitingOn--;
if (waitingOn <= 0) {
linksSent = true;
}
} else {
newMessage == "";
}
}
}
file << "\n-----SETUP COMPLETED, STARTING LINK ESTABLISHMENT-----\n";
cout << "Linking UDP Routers..." << endl;
while (!tablesDone) {
file << getTime() << ": " << "Sending Start Messages" << endl;
for (size_t i = 0; i < ac_vector.size(); i++) {
//sleep(1);
sendTCP(ac_vector[i], "$START");
if (receiveTCP(ac_vector[i]) == "DONE") {
waitingOnFWD--;
if (waitingOnFWD == 0) {
tablesDone = true;
break;
}
}
}
}
file << "\n-----LINK ESTABLISHMENT COMPLETED, STARTING BROADCAST-----\n";
cout << "Broadcasting LSPs..." << endl;
while (!broadcast) {
file << getTime() << ": " << "Sending Broadcast Messages" << endl;
for (size_t i = 0; i < ac_vector.size(); i++) {
//sleep(1);
sendTCP(ac_vector[i], "#BROADCAST");
if (receiveTCP(ac_vector[i]) == "READY") {
waitingOnBroad--;
if (waitingOnBroad == 0) {
broadcast = true;
break;
}
}
}
}
cout << "Creating Routing Tables..." << endl;
while (!table) {
file << "\n-----BROADCASTING COMPLETED, STARTING ROUTING TABLE CREATION-----\n" << endl;
for (size_t i = 0; i < ac_vector.size(); i++) {
//sleep(1);
sendTCP(ac_vector[i], "!Table");
if (receiveTCP(ac_vector[i]) == "RTDone") {
waitingOnTable--;
if (waitingOnTable == 0) {
table = true;
break;
}
}
}
}
//sleep(5);
cout << "Sending Packets..." << endl;
while (!sent) {
file << "\n-----ROUTING TABLES CREATED, SENDING PACKETS-----\n" << endl;
for (size_t i = 0; i < packets.size(); i++) {
sleep(1);
string mess = "~" + to_string(packets[i].dest);
sendTCP(ac_vector[packets[i].src], mess);
file << getTime() << ": " << "Sent Packet: " << i+1 << endl;
if (receiveTCP(ac_vector[packets[i].src]) == "PackSent") {
waitingOnSent--;
if (waitingOnSent == 0) {
sent = true;
break;
}
}
}
}
//sleep(5);
cout << "Quitting..." << endl;
while (!quitting) {
file << "\n-----PACKETS HAVE BEEN SENT, SENDING QUITs TO ROUTERS-----\n" << endl;
for (size_t i = 0; i < ac_vector.size(); i++) {
sendTCP(ac_vector[i], "^quit");
if (receiveTCP(ac_vector[i]) == "QUITACK") {
waitingOnQuit--;
if (waitingOnQuit == 0) {
quitting = true;
break;
}
}
}
}
for (size_t i = 0; i < ac_vector.size(); i++) {
close(ac_vector[i]);
}
}
//Create threads, num_threads passed via input file
void createRouterThreads(int num_threads) {
thread t[num_threads];
//Launch threads
for (int i = 0; i < num_threads; i++) {
t[i] = thread(buildRouter, i);
}
//Do manager related tasks (not sure about the placement here, but it should be correct because once the threads are created we want to do something with them)
runManager(num_threads);
file << "\n-----ROUTERS HAVE QUIT, QUITTING-----\n" << endl;
file << getTime() << ": " << "DONE";
//Join finished threads
for (int i = 0; i < num_threads; ++i) {
t[i].join();
}
exit(0);
}
//Will parse command line arguments and start processes
int main(int argc, const char * argv[]) {
file.open("Manager.log");
if (argc >= 2) {
file << "\n-----STARTING-----\n" << endl;
file << getTime() << ": " << "Opening the Filename: " << argv[1] << '\n';
parseFile(argv[1]);
}
else
cout << "incorrect number of arguments" << '\n';
//Hardcoded for testing, this will be pulled from the input file.
int numberOfThreads = nodes;
// nodes is how it is named in header file, check for more data structure
//Start the process, I dont think anything should be below this call
file << "\n-----CREATING " << numberOfThreads << " THREADS-----\n" << endl;
createRouterThreads(numberOfThreads);
return 0;
}
|
#pragma once
#include "SecureFixedLengthArray.h"
template<unsigned int arraySize>
class SecureArray
{
public:
SecureArray() : data(arraySize) {}
void Zero()
{
data.Zero();
}
unsigned int Size() const
{
return arraySize;
}
uint8_t& operator[](unsigned int i)
{
return data[i];
}
uint8_t* Get()
{
return data.Get();
}
const uint8_t* GetConst() const
{
return data.GetConst();
}
private:
SecureFixedLengthArray data;
};
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "Windows.Media.Ocr.1.h"
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::Foundation {
#ifndef WINRT_GENERIC_2f2d6c29_5473_5f3e_92e7_96572bb990e2
#define WINRT_GENERIC_2f2d6c29_5473_5f3e_92e7_96572bb990e2
template <> struct __declspec(uuid("2f2d6c29-5473-5f3e-92e7-96572bb990e2")) __declspec(novtable) IReference<double> : impl_IReference<double> {};
#endif
}
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_144b0f3d_2d59_5dd2_b012_908ec3e06435
#define WINRT_GENERIC_144b0f3d_2d59_5dd2_b012_908ec3e06435
template <> struct __declspec(uuid("144b0f3d-2d59-5dd2-b012-908ec3e06435")) __declspec(novtable) IVectorView<Windows::Globalization::Language> : impl_IVectorView<Windows::Globalization::Language> {};
#endif
#ifndef WINRT_GENERIC_805a60c7_df4f_527c_86b2_e29e439a83d2
#define WINRT_GENERIC_805a60c7_df4f_527c_86b2_e29e439a83d2
template <> struct __declspec(uuid("805a60c7-df4f-527c-86b2-e29e439a83d2")) __declspec(novtable) IVectorView<Windows::Media::Ocr::OcrWord> : impl_IVectorView<Windows::Media::Ocr::OcrWord> {};
#endif
#ifndef WINRT_GENERIC_60c76eac_8875_5ddb_a19b_65a3936279ea
#define WINRT_GENERIC_60c76eac_8875_5ddb_a19b_65a3936279ea
template <> struct __declspec(uuid("60c76eac-8875-5ddb-a19b-65a3936279ea")) __declspec(novtable) IVectorView<Windows::Media::Ocr::OcrLine> : impl_IVectorView<Windows::Media::Ocr::OcrLine> {};
#endif
}
namespace ABI::Windows::Foundation {
#ifndef WINRT_GENERIC_c7d7118e_ae36_59c0_ac76_7badee711c8b
#define WINRT_GENERIC_c7d7118e_ae36_59c0_ac76_7badee711c8b
template <> struct __declspec(uuid("c7d7118e-ae36-59c0-ac76-7badee711c8b")) __declspec(novtable) IAsyncOperation<Windows::Media::Ocr::OcrResult> : impl_IAsyncOperation<Windows::Media::Ocr::OcrResult> {};
#endif
}
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_dcf2525a_42c0_501d_9fcb_471fae060396
#define WINRT_GENERIC_dcf2525a_42c0_501d_9fcb_471fae060396
template <> struct __declspec(uuid("dcf2525a-42c0-501d-9fcb-471fae060396")) __declspec(novtable) IVector<Windows::Globalization::Language> : impl_IVector<Windows::Globalization::Language> {};
#endif
#ifndef WINRT_GENERIC_48409a10_61b6_5db1_a69d_8abc46ac608a
#define WINRT_GENERIC_48409a10_61b6_5db1_a69d_8abc46ac608a
template <> struct __declspec(uuid("48409a10-61b6-5db1-a69d-8abc46ac608a")) __declspec(novtable) IIterable<Windows::Globalization::Language> : impl_IIterable<Windows::Globalization::Language> {};
#endif
#ifndef WINRT_GENERIC_30e99ae6_f414_5243_8db2_aab38ea3f1f1
#define WINRT_GENERIC_30e99ae6_f414_5243_8db2_aab38ea3f1f1
template <> struct __declspec(uuid("30e99ae6-f414-5243-8db2-aab38ea3f1f1")) __declspec(novtable) IIterator<Windows::Globalization::Language> : impl_IIterator<Windows::Globalization::Language> {};
#endif
#ifndef WINRT_GENERIC_816ce87f_11b3_5e2b_ba1d_b251fe265b99
#define WINRT_GENERIC_816ce87f_11b3_5e2b_ba1d_b251fe265b99
template <> struct __declspec(uuid("816ce87f-11b3-5e2b-ba1d-b251fe265b99")) __declspec(novtable) IVector<Windows::Media::Ocr::OcrWord> : impl_IVector<Windows::Media::Ocr::OcrWord> {};
#endif
#ifndef WINRT_GENERIC_0ed4317a_9964_51c6_acbe_02512a069082
#define WINRT_GENERIC_0ed4317a_9964_51c6_acbe_02512a069082
template <> struct __declspec(uuid("0ed4317a-9964-51c6-acbe-02512a069082")) __declspec(novtable) IIterator<Windows::Media::Ocr::OcrWord> : impl_IIterator<Windows::Media::Ocr::OcrWord> {};
#endif
#ifndef WINRT_GENERIC_a0ce663a_46d0_55e5_928e_251eb67a1e99
#define WINRT_GENERIC_a0ce663a_46d0_55e5_928e_251eb67a1e99
template <> struct __declspec(uuid("a0ce663a-46d0-55e5-928e-251eb67a1e99")) __declspec(novtable) IIterable<Windows::Media::Ocr::OcrWord> : impl_IIterable<Windows::Media::Ocr::OcrWord> {};
#endif
#ifndef WINRT_GENERIC_87a2feca_2afa_5da6_9e14_6f5d47877923
#define WINRT_GENERIC_87a2feca_2afa_5da6_9e14_6f5d47877923
template <> struct __declspec(uuid("87a2feca-2afa-5da6-9e14-6f5d47877923")) __declspec(novtable) IVector<Windows::Media::Ocr::OcrLine> : impl_IVector<Windows::Media::Ocr::OcrLine> {};
#endif
#ifndef WINRT_GENERIC_52ca0f8a_5788_5695_b905_46b8d8171d88
#define WINRT_GENERIC_52ca0f8a_5788_5695_b905_46b8d8171d88
template <> struct __declspec(uuid("52ca0f8a-5788-5695-b905-46b8d8171d88")) __declspec(novtable) IIterator<Windows::Media::Ocr::OcrLine> : impl_IIterator<Windows::Media::Ocr::OcrLine> {};
#endif
#ifndef WINRT_GENERIC_6afa94a2_60d7_5dbe_942d_81aa3929c85e
#define WINRT_GENERIC_6afa94a2_60d7_5dbe_942d_81aa3929c85e
template <> struct __declspec(uuid("6afa94a2-60d7-5dbe-942d-81aa3929c85e")) __declspec(novtable) IIterable<Windows::Media::Ocr::OcrLine> : impl_IIterable<Windows::Media::Ocr::OcrLine> {};
#endif
}
namespace ABI::Windows::Foundation {
#ifndef WINRT_GENERIC_989c1371_444a_5e7e_b197_9eaaf9d2829a
#define WINRT_GENERIC_989c1371_444a_5e7e_b197_9eaaf9d2829a
template <> struct __declspec(uuid("989c1371-444a-5e7e-b197-9eaaf9d2829a")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Media::Ocr::OcrResult> : impl_AsyncOperationCompletedHandler<Windows::Media::Ocr::OcrResult> {};
#endif
}
namespace Windows::Media::Ocr {
struct IOcrEngine :
Windows::Foundation::IInspectable,
impl::consume<IOcrEngine>
{
IOcrEngine(std::nullptr_t = nullptr) noexcept {}
};
struct IOcrEngineStatics :
Windows::Foundation::IInspectable,
impl::consume<IOcrEngineStatics>
{
IOcrEngineStatics(std::nullptr_t = nullptr) noexcept {}
};
struct IOcrLine :
Windows::Foundation::IInspectable,
impl::consume<IOcrLine>
{
IOcrLine(std::nullptr_t = nullptr) noexcept {}
};
struct IOcrResult :
Windows::Foundation::IInspectable,
impl::consume<IOcrResult>
{
IOcrResult(std::nullptr_t = nullptr) noexcept {}
};
struct IOcrWord :
Windows::Foundation::IInspectable,
impl::consume<IOcrWord>
{
IOcrWord(std::nullptr_t = nullptr) noexcept {}
};
}
}
|
/***************************************************************************
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 "Message.h"
#include "Text.h"
#include "ResourceEntity.h"
#include "format.h"
#include "NounsAndCases.h"
#include "ResourceSourceFlags.h"
using namespace std;
void ResolveReferences(TextComponent &messageComponent)
{
int messageCount = messageComponent.Texts.size();
for (int i = 0; i < messageCount; i++)
{
TextEntry message = messageComponent.Texts[i];
uint8_t refN = (message.Reference >> 0) & 0xFF;
uint8_t refV = (message.Reference >> 8) & 0xFF;
uint8_t refC = (message.Reference >> 16) & 0xFF;
uint8_t refS = (message.Reference >> 24) & 0xFF;
if (refN + refV + refC != 0 && refS > 0)
{
messageComponent.Texts[i].Text = fmt::format("[REF {0:d}, {1:d}, {2:d}, {3:d}]", refN, refV, refC, refS);
for (int j = 0; j < messageCount; j++)
{
TextEntry other = messageComponent.Texts[j];
if (other.Noun == refN && other.Verb == refV && other.Condition == refC && other.Sequence == refS)
{
messageComponent.Texts[i].Text += fmt::format(" {0}", other.Text);
break;
}
}
}
}
}
void UnresolveReferences(TextComponent &messageComponent)
{
for (size_t i = 0; i < messageComponent.Texts.size(); i++)
{
TextEntry entry = messageComponent.Texts[i];
messageComponent.Texts[i].Reference = 0; //assume it is not!
if (entry.Text.substr(0, 5) == "[REF ")
{
char* lol = (char*)(entry.Text.c_str()) + 5;
int refN = strtol(lol, &lol, 10);
int refV = strtol(lol + 1, &lol, 10);
int refC = strtol(lol + 1, &lol, 10);
int refS = strtol(lol + 1, &lol, 10);
uint32_t ref = (refN << 0) | (refV << 8) | (refC << 16) | (refS << 24);
messageComponent.Texts[i].Reference = ref;
messageComponent.Texts[i].Text = "";
}
}
}
void MessageReadFrom_2102(TextComponent &messageComponent, sci::istream &byteStream)
{
uint16_t messageCount;
byteStream >> messageCount;
for (int i = 0; i < messageCount; i++)
{
TextEntry message = { 0 };
byteStream >> message.Noun;
byteStream >> message.Verb;
uint16_t textOffset;
byteStream >> textOffset;
sci::istream textStream = byteStream;
textStream.seekg(textOffset);
textStream >> message.Text;
message.Text = Dos2Win(message.Text);
messageComponent.Texts.push_back(message);
}
}
void MessageReadFrom_3411(TextComponent &messageComponent, sci::istream &byteStream)
{
byteStream.skip(2); // ptr to first byte past text data (?)
uint16_t messageCount;
byteStream >> messageCount;
for (int i = 0; i < messageCount; i++)
{
TextEntry message = { 0 };
byteStream >> message.Noun;
byteStream >> message.Verb;
byteStream >> message.Condition;
byteStream >> message.Sequence;
byteStream >> message.Talker;
uint16_t textOffset;
byteStream >> textOffset;
byteStream.skip(3); // Unknown?
sci::istream textStream = byteStream;
textStream.seekg(textOffset);
textStream >> message.Text;
message.Text = Dos2Win(message.Text);
messageComponent.Texts.push_back(message);
}
}
void MessageReadFrom_4000(TextComponent &messageComponent, sci::istream &byteStream)
{
uint16_t offsetToAfterResource;
byteStream >> offsetToAfterResource;
byteStream >> messageComponent.MysteryNumber;
uint16_t messageCount;
byteStream >> messageCount;
// "MysteryNumber" is a number that is roughly the number of messages, but sometimes a little more. Occasionally a lot more.
// Sometimes its zero (KQ6, 95 and 916)
for (int i = 0; i < messageCount; i++)
{
TextEntry message = { 0 };
byteStream >> message.Noun;
byteStream >> message.Verb;
byteStream >> message.Condition;
byteStream >> message.Sequence;
byteStream >> message.Talker;
uint16_t textOffset;
byteStream >> textOffset;
byteStream >> message.Reference;
sci::istream textStream = byteStream;
textStream.seekg(textOffset);
textStream >> message.Text;
message.Text = Dos2Win(message.Text);
messageComponent.Texts.push_back(message);
}
ResolveReferences(messageComponent);
}
void MessageWriteTo_2102(const TextComponent &messageComponent, sci::ostream &byteStream)
{
//UNTESTED
byteStream.WriteWord((uint16_t)messageComponent.Texts.size());
uint16_t textOffset = (uint16_t)(byteStream.tellp() + (4) * messageComponent.Texts.size());
for (const TextEntry &entry : messageComponent.Texts)
{
byteStream << entry.Noun;
byteStream << entry.Verb;
byteStream << textOffset;
textOffset += (uint16_t)(entry.Text.length() + 1);
}
for (const TextEntry &entry : messageComponent.Texts)
{
byteStream << Win2Dos(entry.Text);
}
uint16_t totalSize = (uint16_t)byteStream.tellp();
}
void MessageWriteTo_3411(const TextComponent &messageComponent, sci::ostream &byteStream)
{
uint32_t fillThisIn = byteStream.tellp();
byteStream.WriteWord(0); // We'll fill this in later
uint32_t startCount = byteStream.tellp();
byteStream.WriteWord((uint16_t)messageComponent.Texts.size());
uint16_t textOffset = (uint16_t)(byteStream.tellp() + (5 + 2 + 3) * messageComponent.Texts.size());
for (const TextEntry &entry : messageComponent.Texts)
{
byteStream << entry.Noun;
byteStream << entry.Verb;
byteStream << entry.Condition;
byteStream << entry.Sequence;
byteStream << entry.Talker;
byteStream << textOffset;
//Come back to check these later.
byteStream << (byte)0;
byteStream << (byte)0;
byteStream << (byte)0;
textOffset += (uint16_t)(entry.Text.length() + 1);
}
for (const TextEntry &entry : messageComponent.Texts)
{
byteStream << Win2Dos(entry.Text);
}
uint16_t totalSize = (uint16_t)byteStream.tellp();
uint16_t offsetToEnd = (uint16_t)(byteStream.tellp() - startCount);
*(reinterpret_cast<uint16_t*>(byteStream.GetInternalPointer() + fillThisIn)) = offsetToEnd;
// NOTE: This may need to be padded to WORD boundary
}
void MessageWriteTo_4000(const TextComponent &messageComponent, sci::ostream &byteStream)
{
uint32_t fillThisIn = byteStream.tellp();
byteStream.WriteWord(0); // We'll fill this in later
uint32_t startCount = byteStream.tellp();
byteStream << messageComponent.MysteryNumber;
UnresolveReferences((TextComponent&)messageComponent);
byteStream.WriteWord((uint16_t)messageComponent.Texts.size());
uint16_t textOffset = (uint16_t)(byteStream.tellp() + (5 + 2 + 4) * messageComponent.Texts.size());
for (const TextEntry &entry : messageComponent.Texts)
{
byteStream << entry.Noun;
byteStream << entry.Verb;
byteStream << entry.Condition;
byteStream << entry.Sequence;
byteStream << entry.Talker;
byteStream << textOffset;
byteStream << entry.Reference;
textOffset += (uint16_t)(entry.Text.length() + 1);
}
for (const TextEntry &entry : messageComponent.Texts)
{
byteStream << Win2Dos(entry.Text);
}
uint16_t totalSize = (uint16_t)byteStream.tellp();
uint16_t offsetToEnd = (uint16_t)(byteStream.tellp() - startCount);
*(reinterpret_cast<uint16_t*>(byteStream.GetInternalPointer() + fillThisIn)) = offsetToEnd;
// NOTE: This may need to be padded to WORD boundary
ResolveReferences((TextComponent&)messageComponent);
}
uint16_t CheckMessageVersion(sci::istream &byteStream)
{
uint16_t msgVersion;
byteStream >> msgVersion;
return msgVersion;
}
void MessageReadFrom(ResourceEntity &resource, sci::istream &byteStream, const std::map<BlobKey, uint32_t> &propertyBag)
{
TextComponent &message = resource.GetComponent<TextComponent>();
byteStream >> message.msgVersion;
byteStream.skip(2);
if (message.msgVersion <= 0x835) // 2101
{
message.Flags = MessagePropertyFlags::Noun | MessagePropertyFlags::Verb;
MessageReadFrom_2102(message, byteStream);
}
else if (message.msgVersion <= 0xd53) // 3411
{
message.Flags = MessagePropertyFlags::Noun | MessagePropertyFlags::Verb | MessagePropertyFlags::Condition | MessagePropertyFlags::Sequence | MessagePropertyFlags::Talker;
MessageReadFrom_3411(message, byteStream);
}
else
{
message.Flags = MessagePropertyFlags::Noun | MessagePropertyFlags::Verb | MessagePropertyFlags::Condition | MessagePropertyFlags::Sequence | MessagePropertyFlags::Talker;
MessageReadFrom_4000(message, byteStream);
}
}
void MessageWriteTo(const ResourceEntity &resource, sci::ostream &byteStream, std::map<BlobKey, uint32_t> &propertyBag)
{
const TextComponent &message = resource.GetComponent<TextComponent>();
byteStream << message.msgVersion;
byteStream.WriteWord(0); // Unknown
if (message.msgVersion <= 0x835)
{
MessageWriteTo_2102(message, byteStream);
}
else if (message.msgVersion <= 0xd53)
{
MessageWriteTo_3411(message, byteStream);
}
else
{
MessageWriteTo_4000(message, byteStream);
}
}
std::vector<std::string> split(const std::string& value, char separator)
{
std::vector<std::string> result;
std::string::size_type p = 0;
std::string::size_type q;
while ((q = value.find(separator, p)) != std::string::npos)
{
result.emplace_back(value, p, q - p);
p = q + 1;
}
result.emplace_back(value, p);
return result;
}
void ExportMessageToFile(const TextComponent &message, const std::string &filename)
{
ofstream file;
file.open(filename, ios_base::out | ios_base::trunc);
if (file.is_open())
{
for (const auto &entry : message.Texts)
{
string firstPart = fmt::format("{0}\t{1}\t{2}\t{3}\t{4}\t", (int)entry.Noun, (int)entry.Verb, (int)entry.Condition, (int)entry.Sequence, (int)entry.Talker);
file << firstPart;
// Split by line to match SV.exe's output
vector<string> lines = split(entry.Text, '\n');
int lineNumber = 0;
for (const string &line : lines)
{
if (lineNumber > 0)
{
file << "\t\t\t\t\t"; // "Empty stuff" before next line (matches SV.exe's output)
}
file << line;
file << endl;
lineNumber++;
}
}
}
}
void ConcatWithTabs(const vector<string> &pieces, size_t pos, string &text)
{
while (pos < pieces.size())
{
text += "\t";
text += pieces[pos];
pos++;
}
}
void ImportMessageFromFile(TextComponent &message, const std::string &filename)
{
ifstream file;
file.open(filename, ios_base::in);
if (file.is_open())
{
string line;
while (std::getline(file, line))
{
vector<string> linePieces = split(line, '\t');
if (linePieces.size() >= 6)
{
// If the first 5 are empty, then it's an extension of the previous line
bool empty = true;
for (int i = 0; empty && (i < 5); i++)
{
empty = linePieces[i].empty();
}
if (!empty)
{
TextEntry entry = {};
entry.Noun = (uint8_t)stoi(linePieces[0]);
entry.Verb = (uint8_t)stoi(linePieces[1]);
entry.Condition = (uint8_t)stoi(linePieces[2]);
entry.Sequence = (uint8_t)stoi(linePieces[3]);
entry.Talker = (uint8_t)stoi(linePieces[4]);
entry.Text = linePieces[5];
ConcatWithTabs(linePieces, 6, entry.Text);
message.Texts.push_back(entry);
}
else if (!message.Texts.empty())
{
// Append to previous
message.Texts.back().Text += "\n";
message.Texts.back().Text += linePieces[5];
ConcatWithTabs(linePieces, 6, message.Texts.back().Text);
}
}
}
}
}
bool ValidateMessage(const ResourceEntity &resource)
{
// Check for duplicate tuples
const TextComponent &text = resource.GetComponent<TextComponent>();
unordered_map<uint32_t, const TextEntry *> tuples;
for (const auto &entry : text.Texts)
{
uint32_t tuple = GetMessageTuple(entry);
if (tuples.find(tuple) != tuples.end())
{
string message = fmt::format("Entries must be distinct. The following entries have the same noun/verb/condition/sequence:\n{0}\n{1}",
entry.Text,
tuples[tuple]->Text
);
AfxMessageBox(message.c_str(), MB_OK | MB_ICONWARNING);
return false;
}
else
{
tuples[tuple] = &entry;
}
}
// Check for sequences beginning with something other than 1.
std::map<uint32_t, bool> tuplesHaveSeq;
for (auto &entry : text.Texts)
{
uint32_t tuple = entry.Noun + (entry.Verb << 8) + (entry.Condition << 16);
tuplesHaveSeq[tuple] = tuplesHaveSeq[tuple] || (entry.Sequence == 1);
}
for (auto &pair : tuplesHaveSeq)
{
if (!pair.second)
{
string message = fmt::format("The following mesaage: (noun:{0}, verb:{1}, cond:{2}) has a sequence that doesn't begin at 1. Save anyway?", (pair.first & 0xff), (pair.first >> 8) & 0xff, (pair.first >> 16) & 0xff);
if (IDNO == AfxMessageBox(message.c_str(), MB_YESNO | MB_ICONWARNING))
{
return false;
}
break;
}
}
return true;
}
void MessageWriteNounsAndCases(const ResourceEntity &resource, int resourceNumber)
{
NounsAndCasesComponent *nounsAndCases = const_cast<NounsAndCasesComponent*>(resource.TryGetComponent<NounsAndCasesComponent>());
if (nounsAndCases)
{
// Use the provided resource number instead of that in the ResourceEntity, since it may
// be -1
nounsAndCases->Commit(resourceNumber);
}
}
ResourceTraits messageTraits =
{
ResourceType::Message,
&MessageReadFrom,
&MessageWriteTo,
&ValidateMessage,
&MessageWriteNounsAndCases,
};
ResourceEntity *CreateMessageResource(SCIVersion version)
{
std::unique_ptr<ResourceEntity> pResource = std::make_unique<ResourceEntity>(messageTraits);
pResource->AddComponent(move(make_unique<TextComponent>()));
switch (version.MessageMapSource)
{
case MessageMapSource::Included:
pResource->SourceFlags = ResourceSourceFlags::ResourceMap;
break;
case MessageMapSource::MessageMap:
pResource->SourceFlags = ResourceSourceFlags::MessageMap;
break;
case MessageMapSource::AltResMap:
pResource->SourceFlags = ResourceSourceFlags::AltMap;
break;
default:
assert(false);
break;
}
return pResource.release();
}
ResourceEntity *CreateDefaultMessageResource(SCIVersion version)
{
// Nothing different.
return CreateMessageResource(version);
}
ResourceEntity *CreateNewMessageResource(SCIVersion version, uint16_t msgVersion)
{
ResourceEntity *resource = CreateMessageResource(version);
TextComponent &text = resource->GetComponent<TextComponent>();
text.msgVersion = msgVersion;
text.Flags = MessagePropertyFlags::Noun | MessagePropertyFlags::Verb;
if (msgVersion > 0x835)
{
text.Flags |= MessagePropertyFlags::Condition | MessagePropertyFlags::Sequence | MessagePropertyFlags::Talker;
}
return resource;
}
|
#pragma once
#include "value.h"
class cBaseShader;
class IObj;
class cResourceFile
{
public:
_SYNTHESIZE_INHER( char*, m_pKey, Key );
public:
virtual void Render( IObj* pObj, bool IsAni = false,
cBaseShader* pShader = NULL ) PURE;
public:
cResourceFile(void);
virtual ~cResourceFile(void);
};
|
//
// Item.cpp
// cocos2d_samples
//
// Created by 龚畅优 on 14-6-21.
//
//
#include "Item.h"
Item::Item(){
m_pic = NULL;
m_b2fixture = NULL;
m_type = 0;
m_tmpBox2dPos = Point::ZERO;
m_originPoint = Point::ZERO;
m_isLocked = false;
}
Item::~Item(){
CC_SAFE_RELEASE(m_pic);
}
bool Item::init(){
return true;
}
|
// -*- C++ -*-
//
// Copyright (C) 1998, 1999, 2000, 2002 Los Alamos National Laboratory,
// Copyright (C) 1998, 1999, 2000, 2002 CodeSourcery, LLC
//
// This file is part of FreePOOMA.
//
// FreePOOMA is free software; you can redistribute it and/or modify it
// under the terms of the Expat license.
//
// 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 Expat
// license for more details.
//
// You should have received a copy of the Expat license along with
// FreePOOMA; see the file LICENSE.
//
// ----------------------------------------------------------------------
// Functions supporting relation groups.
//-----------------------------------------------------------------------------
#include "Field/Relations/RelationGroups.h"
#include "Pooma/Pooma.h"
namespace Pooma {
namespace {
unsigned int activeGroups_g = 1;
unsigned int numGroups_g = 1;
} // anonymous namespace
unsigned int activeRelationGroups()
{
return activeGroups_g;
}
bool isRelationGroupActive(unsigned int groups)
{
return (groups & activeGroups_g) != 0;
}
void activateRelationGroup(unsigned int group)
{
blockAndEvaluate();
activeGroups_g |= group;
}
void deactivateRelationGroup(unsigned int group)
{
blockAndEvaluate();
activeGroups_g &= ~group;
}
unsigned int newRelationGroup()
{
unsigned int n = (1 << numGroups_g++);
activateRelationGroup(n);
return n;
}
} // namespace Pooma
// ACL:rcsinfo
// ----------------------------------------------------------------------
// $RCSfile: RelationGroups.cmpl.cpp,v $ $Author: richard $
// $Revision: 1.2 $ $Date: 2004/11/01 18:16:47 $
// ----------------------------------------------------------------------
// ACL:rcsinfo
|
#ifndef PMMAP_H
#define PMMAP_H
#include <Structs/Arrays/packedMemoryArray.h>
template <typename KeyType, typename DataType>
class PMMapItem;
/**
* @class PMDictionary
*
* @brief
*
* @author Panos Michail
*
*/
template <typename KeyType, typename DataType>
class PMMap
{
public:
typedef PMMapItem<KeyType,DataType> MapItem;
typedef typename PackedMemoryArray<MapItem>::Iterator Iterator;
typedef typename PackedMemoryArray<MapItem>::SizeType SizeType;
PMMap()
{
}
Iterator begin()
{
return m_pool.begin();
}
void clear()
{
m_pool.clear();
}
Iterator end()
{
return m_pool.end();
}
void erase( const Iterator& it)
{
m_pool.erase(it);
}
Iterator find( const KeyType& key)
{
MapItem item(key,DataType());
return m_pool.find( item);
}
DataType& operator[]( const KeyType& key)
{
Iterator it = find(key);
if( it == m_pool.end())
{
it = unmanagedInsert( MapItem(key, DataType()));
}
return it->m_data;
}
SizeType size()
{
return m_pool.size();
}
private:
PackedMemoryArray<MapItem> m_pool;
Iterator unmanagedInsert( const MapItem& newItem)
{
Iterator it = m_pool.lower_bound(newItem);
return m_pool.insert( it, newItem);
}
};
template <typename KeyType, typename DataType>
class PMMapItem
{
public:
PMMapItem( unsigned int init = 0):m_key(),m_data(0)
{
}
PMMapItem( const KeyType& key, const DataType& data):m_key(key),m_data(data)
{
}
bool operator < ( const PMMapItem& other) const
{
return m_key < other.m_key;
}
bool operator > ( const PMMapItem& other) const
{
return m_key > other.m_key;
}
bool operator == ( const PMMapItem& other) const
{
return (m_key == other.m_key);
}
bool operator != ( const PMMapItem& other) const
{
return (m_key != other.m_key);
}
KeyType m_key;
DataType m_data;
};
#endif //PMMAP_H
|
/* stl map */
#include<algorithm>
#include<map>
#include<string.h>
#include<string>
#include<unordered_map>
using namespace std;
#define MAXLEN (5)
struct Character {
int sid, uid, point;
map<int, int>::iterator pos;
}cha[100003];
int ucnt, scnt;
unordered_map<string, int> utab, stab;
map<int, int> user[30003]; // first: priority , second: character id
// priority는 default tick*2, reciever의 경우 tick*2+1
// reciever와 giver의 차이를 두기 위해
void userInit() {
for (int i = 1; i <= ucnt; i++) user[i].clear();
ucnt = 0;
memset(cha, 0, sizeof(cha));
utab.clear(), stab.clear();
}
void create(int tick, char userName[MAXLEN], char serverName[MAXLEN], int charID, int point) {
int uid = utab[userName];
if (!uid) utab[userName] = uid = ++ucnt;
int sid = stab[serverName];
if (!sid) stab[serverName] = sid = ++scnt;
cha[charID] = { sid, uid, point };
cha[charID].pos = user[uid].insert({ tick * 2, charID }).first;
}
int destroy(int tick, int charID) {
auto& p = cha[charID].pos;
user[cha[charID].uid].erase(p);
cha[charID].uid = 0;
return cha[charID].point;
}
int exchange(int src, int dest, int point, int tick) {
if (!cha[src].uid || !cha[dest].uid || cha[src].point < point) return -1;
cha[src].point -= point;
cha[dest].point += point;
user[cha[src].uid].erase(cha[src].pos);
user[cha[dest].uid].erase(cha[dest].pos);
cha[src].pos = user[cha[src].uid].insert({ tick * 2, src }).first;
cha[dest].pos = user[cha[dest].uid].insert({ tick * 2 + 1, dest }).first;
return cha[dest].point;
}
int numToNum(int tick, int giverID, int recieverID, int point) {
return exchange(giverID, recieverID, point, tick);
}
int numToName(int tick, int giverID, char recieverName[MAXLEN], int point) {
int uid = utab[recieverName];
if (!uid || user[uid].empty()) return -1;
return exchange(giverID, user[uid].rbegin()->second, point, tick);
}
void payBonusPoint(int tick, char serverName[MAXLEN], int point) {
int sid = stab[serverName];
for (int i = 1; i <= ucnt; i++) {
for (auto it = user[i].rbegin(); it != user[i].rend(); ++it) {
int cid = it->second;
if (cha[cid].sid == sid) {
cha[cid].point += point;
user[i].erase(cha[cid].pos);
cha[cid].pos = user[i].insert({ tick * 2, cid }).first;
break;
}
}
}
}
|
#include "wmaskeditwindow.h"
WMaskEditWindow::WMaskEditWindow(QWidget *parent) : QMainWindow(parent)
{
}
|
#include <iostream>
#include <utility>
#include "graph.h"
using namespace std;
int main(){
Graph g(10);
pair<int,int> a(0,1);
pair<int,int> b(2,1);
g.addline(a);
g.addline(b);
g.addline(pair<int,int>(1,4));
g.addline(pair<int,int>(2,4));
g.addline(pair<int,int>(2,5));
g.addline(pair<int,int>(1,6));
g.addline(pair<int,int>(3,6));
g.display();
g.deleteline(pair<int,int>(3,6));
g.deleteline(pair<int,int>(1,6));
cout<<"删除边操作后:"<<endl;
g.display();
system("pause");
return 0;
}
|
//
// Created by Steven Smith on 2020-04-04.
// A class created to help and simplify the main driver into something more simple
// and easier to manage.
//
#ifndef INC_371PROCEDURALFOREST_WINDOWMANAGER_H
#define INC_371PROCEDURALFOREST_WINDOWMANAGER_H
#include "GLFW/glfw3.h"
#include <string>
class WindowManager {
public:
static void Initialize(std::string, int, int);
static void Shutdown();
static void Update();
static void EnableMouseCursor();
static void DisableMouseCursor();
static float GetMouseMotionX();
static float GetMouseMotionY();
static GLFWwindow* getWindow();
static float GetFrameTime();
static bool ExitWindow();
private:
static double sLastFrameTime;
static float sFrameTime;
static double sLastMousePositionX;
static float sMouseDeltaX;
static double sLastMousePositionY;
static float sMouseDeltaY;
static GLFWwindow* window;
};
#endif //INC_371PROCEDURALFOREST_WINDOWMANAGER_H
|
#include <iostream>
using namespace std;
class Box
{
public:
// Constructor definition
Box()
{
cout <<"Constructor called." << endl;
}
double Volume()
{
return length * breadth * height;
}
int value()
{
return this->Volume();
}
int compare(Box box)
{
cout<<"\n"<<this->Volume();
cout<<"\n"<<box.Volume();
return this->Volume() > box.Volume();
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main(void)
{
Box Box1(3.0,3.0,3.0); // Declare box1
Box Box2(8.0, 8.0, 8.0); // Declare box2
Box Box3(5.0,5.0,5.0);
int volume = Box3.value();
cout<<"volume is : "<<volume;
int doubt = Box2.compare(Box1);
//cout<<"\n"<<doubt;
/*if(Box1.compare(Box2))
{
cout << "\nBox2 is smaller than Box1" <<endl;
}
else
{
cout << "\nBox2 is equal to or larger than Box1" <<endl;
}*/
return 0;
}
|
// ASMloadcameras.cpp
// Load in Configure parameters
// Bai, Gang.
// March 22ed, 2010.
#include <stdafx.h>
#include <cstdio>
#include <tinyxml.h>
#include "ASModeling.h"
namespace
{
#define TXFloatValue( p, v ) (p)->QueryFloatAttribute("value", (v));
#define TXIntValue( p, v ) (p)->QueryIntAttribute("value", (v));
} // unnamed namespace
namespace as_modeling
{
bool ASModeling::load_configure_file(const char *filename)
{
// File open
TiXmlDocument doc(filename);
if (!doc.LoadFile())
return false;
TiXmlHandle hDoc(&doc);
TiXmlElement * pElem;
TiXmlHandle hRoot(0);
//////////////////////////
// load items
//////////////////////////
pElem = hDoc.FirstChildElement().Element();
if (!pElem)
return false;
hRoot = TiXmlHandle(pElem);
// Participating media parameters
TiXmlHandle * hPmedia = & (hRoot.FirstChild("PMedia"));
pElem = hPmedia->FirstChild("extinction").Element();
if (!pElem)
return false;
TXFloatValue(pElem, &extinction_);
pElem = hPmedia->FirstChild("scattering").Element();
if (!pElem)
return false;
TXFloatValue(pElem, &scattering_);
pElem = hPmedia->FirstChild("alpha").Element();
if (!pElem)
return false;
TXFloatValue(pElem, &alpha_);
// Render parameters
TiXmlHandle * hRender = & (hRoot.FirstChild("Render"));
pElem = hRender->FirstChild("CurrentView").Element();
if (!pElem)
return false;
TXIntValue(pElem, ¤t_view_ );
pElem = hRender->FirstChild("width").Element();
if (!pElem)
return false;
TXIntValue(pElem, &width_ );
pElem = hRender->FirstChild("height").Element();
if (!pElem)
return false;
TXIntValue(pElem, &height_ );
TiXmlHandle* hRInterval = &(hRender->FirstChild("RenderInterval"));
if (!hRInterval)
return false;
pElem = hRInterval->FirstChild("Level5").Element();
if (!pElem)
return false;
TXIntValue(pElem, &(render_interval_array_[5]));
pElem = hRInterval->FirstChild("Level6").Element();
if (!pElem)
return false;
TXIntValue(pElem, &(render_interval_array_[6]));
pElem = hRInterval->FirstChild("Level7").Element();
if (!pElem)
return false;
TXIntValue(pElem, &(render_interval_array_[7]));
pElem = hRInterval->FirstChild("Level8").Element();
if (!pElem)
return false;
TXIntValue(pElem, &(render_interval_array_[8]));
pElem = hRender->FirstChild("RotAngle").Element();
if (!pElem)
return false;
TXIntValue(pElem, &rot_angles_ );
// Light parameters
TiXmlHandle * hLight = & (hRoot.FirstChild("Light"));
pElem = hLight->FirstChild("LightType").Element();
if (!pElem)
return false;
TXIntValue(pElem, &light_type_);
pElem = hLight->FirstChild("LightIntensityR").Element();
if (!pElem)
return false;
TXFloatValue(pElem, &light_intensity_);
pElem = hLight->FirstChild("LightX").Element();
if (!pElem)
return false;
TXFloatValue(pElem, &light_x_);
pElem = hLight->FirstChild("LightY").Element();
if (!pElem)
return false;
TXFloatValue(pElem, &light_y_);
pElem = hLight->FirstChild("LightZ").Element();
if (!pElem)
return false;
TXFloatValue(pElem, &light_z_);
// Volume parameters
TiXmlHandle * hVolume = & (hRoot.FirstChild("Volume"));
pElem = hVolume->FirstChild("BoxSize").Element();
if (!pElem)
return false;
TXFloatValue(pElem, &box_size_);
pElem = hVolume->FirstChild("VolumeInitialLevel").Element();
if (!pElem)
return false;
TXIntValue(pElem, &initial_vol_level_);
initial_vol_size_ = 1 << initial_vol_level_;
pElem = hVolume->FirstChild("VolumeMaxLevel").Element();
if (!pElem)
return false;
TXIntValue(pElem, &max_vol_level_);
max_vol_size_ = 1 << max_vol_level_;
pElem = hVolume->FirstChild("TransX").Element();
if (!pElem)
return false;
TXFloatValue(pElem, &trans_x_);
pElem = hVolume->FirstChild("TransY").Element();
if (!pElem)
return false;
TXFloatValue(pElem, &trans_y_);
pElem = hVolume->FirstChild("TransZ").Element();
if (!pElem)
return false;
TXFloatValue(pElem, &trans_z_);
TiXmlHandle* hVInterval = &(hVolume->FirstChild("VolInterval"));
if (!hVInterval)
return false;
pElem = hVInterval->FirstChild("Level5").Element();
if (!pElem)
return false;
TXIntValue(pElem, &volume_interval_array_[5]);
pElem = hVInterval->FirstChild("Level6").Element();
if (!pElem)
return false;
TXIntValue(pElem, &volume_interval_array_[6]);
pElem = hVInterval->FirstChild("Level7").Element();
if (!pElem)
return false;
TXIntValue(pElem, &volume_interval_array_[7]);
pElem = hVInterval->FirstChild("Level8").Element();
if (!pElem)
return false;
TXIntValue(pElem, &volume_interval_array_[8]);
// L-BFGS-B parameters
TiXmlHandle * hLbfgsb = & (hRoot.FirstChild("LBFGSB"));
pElem = hLbfgsb->FirstChild("disturb").Element();
if (!pElem)
return false;
TXFloatValue(pElem, &disturb_);
pElem = hLbfgsb->FirstChild("EpsG").Element();
if (!pElem)
return false;
TXFloatValue(pElem, &eps_g_);
pElem = hLbfgsb->FirstChild("EpsF").Element();
if (!pElem)
return false;
TXFloatValue(pElem, &eps_f_);
pElem = hLbfgsb->FirstChild("EpsX").Element();
if (!pElem)
return false;
TXFloatValue(pElem, &eps_x_);
pElem = hLbfgsb->FirstChild("MaxIts").Element();
if (!pElem)
return false;
TXIntValue(pElem, &max_iter_);
pElem = hLbfgsb->FirstChild("m").Element();
if (!pElem)
return false;
TXIntValue(pElem, &lbfgs_m_);
pElem = hLbfgsb->FirstChild("ConstrainType").Element();
if (!pElem)
return false;
TXIntValue(pElem, &constrain_type_);
pElem = hLbfgsb->FirstChild("LowerBound").Element();
if (!pElem)
return false;
TXFloatValue(pElem, &lower_boundary_);
pElem = hLbfgsb->FirstChild("UpperBound").Element();
if (!pElem)
return false;
TXFloatValue(pElem, &upper_boundary_);
// CUDA parameters
TiXmlHandle * hCuda = &(hRoot.FirstChild("CUDA"));
return true;
}
} // namespace as_modeling
|
/*
* Copyright 2016-2017 Flatiron Institute, Simons Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mvmergecontrol.h"
#include <QToolButton>
#include <flowlayout.h>
#include <mvcontext.h>
class MVMergeControlPrivate {
public:
MVMergeControl* q;
void do_merge_or_unmerge(bool merge);
};
MVMergeControl::MVMergeControl(MVAbstractContext* context, MVMainWindow* mw)
: MVAbstractControl(context, mw)
{
d = new MVMergeControlPrivate;
d->q = this;
QHBoxLayout* layout1 = new QHBoxLayout;
{
QToolButton* B = this->createToolButtonControl("merge_selected", "Merge selected", this, SLOT(slot_merge_selected()));
layout1->addWidget(B);
}
{
QToolButton* B = this->createToolButtonControl("unmerge_selected", "Unmerge selected", this, SLOT(slot_unmerge_selected()));
layout1->addWidget(B);
}
layout1->addStretch();
QHBoxLayout* layout2 = new QHBoxLayout;
{
QCheckBox* CB = this->createCheckBoxControl("view_merged", "View merged");
layout2->addWidget(CB);
}
layout2->addStretch();
QVBoxLayout* vlayout = new QVBoxLayout;
vlayout->addLayout(layout1);
vlayout->addLayout(layout2);
this->setLayout(vlayout);
this->updateControlsOn(context, SIGNAL(viewMergedChanged()));
this->updateControlsOn(context, SIGNAL(selectedClusterPairsChanged()));
this->updateControlsOn(context, SIGNAL(selectedClustersChanged()));
}
MVMergeControl::~MVMergeControl()
{
delete d;
}
QString MVMergeControl::title() const
{
return "Merge";
}
void MVMergeControl::updateContext()
{
MVContext* c = qobject_cast<MVContext*>(mvContext());
Q_ASSERT(c);
c->setViewMerged(this->controlValue("view_merged").toBool());
}
void MVMergeControl::updateControls()
{
MVContext* c = qobject_cast<MVContext*>(mvContext());
Q_ASSERT(c);
bool can_merge_or_unmerge = false;
if (!c->selectedClusterPairs().isEmpty()) {
can_merge_or_unmerge = true;
}
if (c->selectedClusters().count() >= 2) {
can_merge_or_unmerge = true;
}
this->setControlEnabled("merge_selected", can_merge_or_unmerge);
this->setControlEnabled("unmerge_selected", can_merge_or_unmerge);
this->setControlValue("view_merged", c->viewMerged());
}
void MVMergeControl::slot_merge_selected()
{
MVContext* c = qobject_cast<MVContext*>(mvContext());
Q_ASSERT(c);
d->do_merge_or_unmerge(true);
c->setViewMerged(true);
}
void MVMergeControl::slot_unmerge_selected()
{
d->do_merge_or_unmerge(false);
}
void MVMergeControlPrivate::do_merge_or_unmerge(bool merge)
{
MVContext* c = qobject_cast<MVContext*>(q->mvContext());
Q_ASSERT(c);
QSet<ClusterPair> selected_cluster_pairs = c->selectedClusterPairs();
if (selected_cluster_pairs.count() >= 1) {
foreach (ClusterPair pair, selected_cluster_pairs) {
QSet<QString> tags = c->clusterPairTags(pair);
if (merge)
tags.insert("merged");
else
tags.remove("merged");
c->setClusterPairTags(pair, tags);
}
}
else {
QList<int> selected_clusters = c->selectedClusters();
//we need to do something special since it is overkill to merge every pair -- and expensive for large # clusters
if (merge) {
ClusterMerge CM = c->clusterMerge();
for (int i1 = 0; i1 < selected_clusters.count() - 1; i1++) {
int i2 = i1 + 1;
ClusterPair pair(selected_clusters[i1], selected_clusters[i2]);
if (CM.representativeLabel(pair.k1()) != CM.representativeLabel(pair.k2())) {
//not already merged
QSet<QString> tags = c->clusterPairTags(pair);
tags.insert("merged");
c->setClusterPairTags(pair, tags);
QSet<int> tmp;
tmp.insert(pair.k1());
tmp.insert(pair.k2());
CM.merge(tmp);
}
}
}
else {
QSet<int> selected_clusters_set = selected_clusters.toSet();
QList<ClusterPair> keys = c->clusterPairAttributesKeys();
foreach (ClusterPair pair, keys) {
if ((selected_clusters_set.contains(pair.k1())) || (selected_clusters_set.contains(pair.k2()))) {
QSet<QString> tags = c->clusterPairTags(pair);
tags.remove("merged");
c->setClusterPairTags(pair, tags);
}
}
}
}
}
|
#ifndef PCB_H
#define PCB_H
#include <string>
#include "global_variables.h"
#include <iostream>
using namespace std;
/*
* This document describe the node of a process
* the action taken here as well as criteria for determining
* each situation is before the tick
*/
class PCB{
public:
int priority; // priotity
int cpu_time; // ticks since process established
int need_time; // ticks still needed
int count; // exact time used by the process
int timelet_count; // ticks run in a timelet_count
// bool CurRunning; // whether PCB is processed by CPU right now
int round; // Which round should the process be pushed in ready
string name; // process name
char state; // process state enum{'r = ready'. 'p = processing', 'f = finish'}
PCB * next_node; // ptr of next process
// PCB();
PCB(string name, int priority, int need_time, int round);
~PCB();
bool operator < (PCB p)const{
return (this -> round) < (p.round);
}
bool tick();
bool tick_fcfs();
bool run_the_process();
bool run_in_timelet();
bool yield_resouce();
char get_state();
bool append(PCB * next_node);
// short cmp_round(const PCB * a, const PCB * b);
string ToString();
};
PCB::PCB(string name, int priority, int need_time, int round){
this -> name = name;
this -> priority = priority;
this -> need_time = need_time;
this -> next_node = NULL;
this -> round = round;
this -> cpu_time = 0;
this -> timelet_count = 0;
this -> count = 0;
this -> state = 'r';
}
PCB::~PCB(){
delete & (this -> name);
delete &(this -> priority);
delete &(this -> need_time);
delete &(this -> next_node);
delete &(this -> cpu_time);
delete &(this -> timelet_count);
delete &(this -> count);
delete &(this -> state);
}
bool PCB::run_the_process(){
if(this -> state == 'f'){
return false;
}
else{
this -> state = 'p';
// cout << this -> name << " is processing." << endl;
return true;
}
}
bool PCB::yield_resouce(){
if(this -> state == 'p'){
// timelet up
if(this -> need_time != 0) {
if (this->timelet_count == 0) {
this->state = 'r';
return true;
}
else{
cerr << "Called yield_resource() when still have need_time";
return false;
}
}
else{
this -> state = 'f';
return true;
}
}
else{
cerr << "The process is not running when required to yield timelet" << endl;
return false;
}
}
bool PCB::tick(){
if(this -> state != 'f'){
/* cpu_time increase in 'p' and in 'r'
* increase cpu_time does not alter any locks */
this -> cpu_time ++;
if(this -> state == 'p'){
this -> count++;
if(this -> timelet_count < get_timelet()){
this -> timelet_count ++;
this -> need_time --;
/* when timelet is used up*/
if(this -> timelet_count == get_timelet()){
this -> timelet_count = 0;
yield_resouce();
return true;
}
if(this -> need_time == 0){
yield_resouce();
return true;
}
}
else{
cerr << "timelet error occur" << endl;
return false;
}
}
return true;
}
else{
return true;
}
}
bool PCB::tick_fcfs(){
if(this -> state != 'f'){
this -> cpu_time ++;
if(this -> state == 'p'){
this -> count ++;
this -> timelet_count = (this -> timelet_count + 1) % get_timelet();
this -> need_time --;
if(this -> need_time == 0){
this -> state = 'f';
}
}
/* next state of 'r' process is realised outside
* after tick() */
}
}
char PCB::get_state(){
return this -> state;
}
bool PCB :: append(PCB * next_node){
this -> next_node = next_node;
return true;
}
string PCB::ToString(){
string str = "";
str = this -> name + "\t" + to_string(this -> state)
+ "\t" + to_string(this -> priority) + "\t" + to_string(this -> round)
+ "\t" + to_string(this -> count) + "\t" + to_string(this -> need_time)
+ "\n";
return str;
}
#endif
|
#include "MainMenu.h"
#include "../Game.h"
#include "../entity/Player.h"
#include <QApplication>
extern Game *game;
MainMenu::MainMenu(QGraphicsView *parent) : QGraphicsSceneSized(parent)
{
title = new QGraphicsTextItem(QString("YASRL"));
title->setFont(QFont("Perfect DOS VGA 437", 80));
title->setPos((parent->width() - 283) / 2, 100);
this->addItem(title);
character0 = new QGraphicsTextItem(QString("0 > Play Mr. Nobody"));
character0->setFont(QFont("Perfect DOS VGA 437", 40));
character0->setPos((parent->width() - 562) / 2, 290);
this->addItem(character0);
quit = new QGraphicsTextItem(QString("Q > Quit"));
quit->setFont(QFont("Perfect DOS VGA 437", 40));
quit->setPos((parent->width() - 233) / 2, 600);
this->addItem(quit);
}
void MainMenu::keyPressEvent(QKeyEvent *event)
{
switch (event->key())
{
case Qt::Key_Q:
// Q: quits the game
QApplication::instance()->quit();
break;
case Qt::Key_0:
// 0: starts exploration with Mr. Nobody
game->player = new Player(MR_NOBODY);
game->displayExploration();
break;
default:
qDebug() << "MainMenu::keyPressEvent unknown key :" << event->key();
}
}
|
#ifndef BIDIRECTIONALDIJKSTRA_H
#define BIDIRECTIONALDIJKSTRA_H
#include <Structs/Trees/priorityQueue.h>
/**
* @class BidirectionalDijkstra
*
* @brief Bidirectional Dijkstra algorithm implementation
*
* This class supports running queries between source and target nodes by building two search trees, one starting at the source node and one ending at the target node.
*
* @tparam GraphType The type of the graph to run the algorithm on
* @author Panos Michail
*
*/
template<class GraphType>
class BidirectionalDijkstra
{
public:
typedef typename GraphType::NodeIterator NodeIterator;
typedef typename GraphType::NodeDescriptor NodeDescriptor;
typedef typename GraphType::EdgeIterator EdgeIterator;
typedef typename GraphType::InEdgeIterator InEdgeIterator;
typedef typename GraphType::SizeType SizeType;
typedef unsigned int WeightType;
typedef PriorityQueue< WeightType, NodeIterator, HeapStorage> PriorityQueueType;
/**
* @brief Constructor
*
* @param graph The graph to run the algorithm on
* @param timestamp An address containing a timestamp. A timestamp must be given in order to check whether a node is visited or not
*/
BidirectionalDijkstra( GraphType& graph, unsigned int* timestamp):G(graph),m_timestamp(timestamp)
{
}
const unsigned int& getSettledNodes()
{
return m_settled;
}
/**
* @brief Runs a shortest path query between a source node s and a target node t
*
* @param s The source node
* @param t The target node
* @return The distance of the target node
*/
WeightType runQuery( const typename GraphType::NodeIterator& s, const typename GraphType::NodeIterator& t)
{
NodeIterator u,v,lastNode;
EdgeIterator e,lastEdge;
pqFront.clear();
pqBack.clear();
++(*m_timestamp);
minDistance = std::numeric_limits<WeightType>::max();
m_settled = 2;
s->dist = 0;
s->distBack = std::numeric_limits<WeightType>::max();//<//
s->timestamp = (*m_timestamp);
s->pred = G.nilNodeDescriptor();
t->dist = std::numeric_limits<WeightType>::max(); //<//
t->distBack = 0;
t->timestamp = (*m_timestamp);
t->succ = G.nilNodeDescriptor();
pqFront.insert( s->dist, s, &(s->pqitem));
pqBack.insert( t->distBack, t, &(t->pqitemBack));
while( ! ( pqFront.empty() && pqBack.empty()))
{
curMin = 0;
if( !pqFront.empty()) curMin += pqFront.minKey();
if( !pqBack.empty()) curMin += pqBack.minKey();
if( curMin > minDistance)
{
break;
}
searchForward();
searchBackward();
}
u = viaNode;
t->dist = u->dist;
while( u->succ != G.nilNodeDescriptor())
{
v = G.getNodeIterator(u->succ);
v->pred = G.getNodeDescriptor( u);
e = G.getEdgeIterator( u, v);
t->dist += e->weight;
u = v;
}
return t->dist;
}
private:
GraphType& G;
unsigned int* m_timestamp;
PriorityQueueType pqFront, pqBack;
NodeIterator viaNode;
WeightType curMin, minDistance;
unsigned int m_settled;
bool isBackwardFound( const NodeIterator& u)
{
return (u->timestamp == (*m_timestamp)) && (u->distBack != std::numeric_limits<WeightType>::max());
}
bool isBackwardSettled( const NodeIterator& u)
{
return isBackwardFound(u) && (!isInBackQueue(u));
}
bool isForwardFound( const NodeIterator& u)
{
return (u->timestamp == (*m_timestamp)) && (u->dist != std::numeric_limits<WeightType>::max());
}
bool isForwardSettled( const NodeIterator& u)
{
return isForwardFound(u) && (!isInFrontQueue(u));
}
bool isInBackQueue( const NodeIterator& u)
{
return pqBack.contains( &(u->pqitemBack));
}
bool isInFrontQueue( const NodeIterator& u)
{
return pqFront.contains( &(u->pqitem));
}
void searchForward()
{
EdgeIterator e,lastEdge;
NodeIterator u,v;
if( !pqFront.empty())
{
u = pqFront.minItem();
pqFront.popMin();
++m_settled;
for( e = G.beginEdges(u), lastEdge = G.endEdges(u); e != lastEdge; ++e)
{
v = G.target(e);
if( v->timestamp < (*m_timestamp))
{
v->pred = u->getDescriptor();
v->dist = u->dist + e->weight;
v->timestamp = (*m_timestamp);
v->distBack = std::numeric_limits<WeightType>::max();
pqFront.insert( v->dist, v, &(v->pqitem));
}
else if( v->dist == std::numeric_limits<WeightType>::max())
{
v->pred = u->getDescriptor();
v->dist = u->dist + e->weight;
pqFront.insert( v->dist, v, &(v->pqitem));
}
else if( v->dist > u->dist + e->weight )
{
v->pred = u->getDescriptor();
v->dist = u->dist + e->weight;
pqFront.decrease( v->dist, &(v->pqitem));
}
if( isBackwardFound(v) && ( u->dist + e->weight + v->distBack < minDistance))
{
minDistance = u->dist +e->weight + v->distBack;
//std::cout << "Settled " << G.getId(v) << " from front with " << minDistance << " (" << u->dist << "+" << v->distBack << ")!\n";
viaNode = v;
}
}
}
}
void searchBackward()
{
InEdgeIterator k,lastInEdge;
NodeIterator u,v;
if( !pqBack.empty())
{
u = pqBack.minItem();
pqBack.popMin();
++m_settled;
for( k = G.beginInEdges(u), lastInEdge = G.endInEdges(u); k != lastInEdge; ++k)
{
v = G.source(k);
if( v->timestamp < (*m_timestamp))
{
v->succ = u->getDescriptor();
v->distBack = u->distBack + k->weight;
v->timestamp = (*m_timestamp);
v->dist = std::numeric_limits<WeightType>::max();
pqBack.insert( v->distBack, v, &(v->pqitemBack));
}
else if( v->distBack == std::numeric_limits<WeightType>::max())
{
v->succ = u->getDescriptor();
v->distBack = u->distBack + k->weight;
pqBack.insert( v->distBack, v, &(v->pqitemBack));
}
else if( v->distBack > u->distBack + k->weight )
{
v->succ = u->getDescriptor();
v->distBack = u->distBack + k->weight;
pqBack.decrease( v->distBack, &(v->pqitemBack));
}
if( isForwardFound(v) && ( v->dist + k->weight + u->distBack < minDistance))
{
minDistance = v->dist +k->weight + u->distBack;
//std::cout << "Settled " << G.getId(v) << " from back with " << minDistance << " (" << v->dist << "+" << u->distBack << ")!\n";
viaNode = v;
}
}
}
}
};
#endif//BIDIRECTIONALDIJKSTRA_H
|
/*****************************************************************************/
/*! \file option.hh
* \author AV
* \date 2010-03
*
* \brief A simple template to mimic ML's option/None/Some
*****************************************************************************/
#ifndef OPTION_HH
#define OPTION_HH
class OptionNoValueExc {};
template <typename T>
class Option
{
T stored;
bool isSome;
public:
/*! \brief Default constructor, similar to None in ML */
Option()
{
isSome = false;
}
/*! \brief Constructor with a value, similar to Some in ML */
Option(T val)
{
stored = val;
isSome = true;
}
/*! \brief Copy constructor */
Option(const Option &other) :
stored(other.stored),
isSome(other.isSome)
{};
/*! \brief Check if a value is stored */
bool hasValue() const
{
return isSome;
}
/*! \brief Get the value if present, throw a dirty exception otherwise */
T getValue() const
{
if (!isSome)
throw OptionNoValueExc();
return stored;
}
/*! \brief Get the address of the value if present, throw a dirty exception
* otherwise */
T * getValueAddr(bool force = false)
{
if(force) isSome = true;
if (!isSome)
throw OptionNoValueExc();
return & stored;
}
void clear()
{
isSome = false;
}
};
#endif /* OPTION_HH */
|
/***************************************************************************
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.
***************************************************************************/
//
// ResourcePicListView.h
//
#pragma once
#include "ResourceListView.h"
#include "QueueItems.h"
#include "ResourceBlob.h"
// This is created by the UI thread, and deleted by the worker thread.
class PICWORKITEM
{
public:
ResourceBlob blob;
};
// This is created by the worker thread, posted to the UI thread.
// Well, actually just the message "check for results" is posted to the
// UI thread.
class PICWORKRESULT
{
public:
PICWORKRESULT() { hbmp = NULL; nID= 0; }
~PICWORKRESULT() { DeleteObject(hbmp); }
HBITMAP hbmp;
UINT nID;
int iResourceNumber;
int iPackageNumber;
static PICWORKRESULT *CreateFromWorkItem(PICWORKITEM *pWorkItem);
};
class CResourcePicListCtrl : public CResourceListCtrl
{
protected: // create from serialization only
CResourcePicListCtrl();
DECLARE_DYNCREATE(CResourcePicListCtrl)
// Attributes
public:
virtual ResourceType GetType() { return ResourceType::Pic; }
virtual DWORD GetDefaultViewMode() { return LVS_ICON; }
// Operations
public:
// Implementation
public:
virtual ~CResourcePicListCtrl();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
void OnGetDispInfo(NMHDR* pNMHDR, LRESULT* pResult);
void OnItemChanged(NMHDR* pNMHDR, LRESULT* pResult);
protected:
virtual void _PrepareLVITEM(LVITEM *pItem);
virtual void _OnInitListView(int cItems);
void _RegenerateImages() override;
// Generated message map functions
protected:
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
LRESULT OnPicReady(WPARAM wParam, LPARAM lParam);
BOOL SetItemImage(int nItem , int nImageIndex);
DECLARE_MESSAGE_MAP()
private:
HIMAGELIST _himlPics;
int _iTokenImageIndex;
std::shared_ptr<QueueItems<PICWORKITEM, PICWORKRESULT>> _pQueue;
};
|
/***************************************************************************
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.
***************************************************************************/
// ChooseColorDialog.cpp : implementation file
//
#include "stdafx.h"
#include "AppState.h"
#include "ChooseColorDialogVGA.h"
#include "PaletteOperations.h"
// CChooseColorDialogVGA dialog
CChooseColorDialogVGA::CChooseColorDialogVGA(const PaletteComponent &palette, CWnd* pParent)
: CBaseColorDialog(CChooseColorDialogVGA::IDD, pParent), _palette(palette)
{
_bChoice = 0;
// 256 things here.
m_wndStatic.SetPalette(16, 16, reinterpret_cast<const EGACOLOR*>(palette.Mapping), ARRAYSIZE(palette.Mapping), palette.Colors, false);
m_wndStatic.ShowSelection(TRUE);
}
void CChooseColorDialogVGA::DoDataExchange(CDataExchange* pDX)
{
CBaseColorDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_CHOOSECOLORSTATIC, m_wndStatic);
m_wndStatic.SetCallback(this);
// Visuals
DDX_Control(pDX, IDC_DIALOGDESCRIPTION, m_wndDescription);
DDX_Control(pDX, IDCANCEL, m_wndCancel);
}
BEGIN_MESSAGE_MAP(CChooseColorDialogVGA, CBaseColorDialog)
ON_WM_KEYDOWN()
ON_WM_KILLFOCUS()
ON_WM_ACTIVATE()
END_MESSAGE_MAP()
void CChooseColorDialogVGA::OnColorClick(BYTE bIndex, int nID, BOOL fLeftClick)
{
if (fLeftClick)
{
// We only have one child - it must have been it.
SetColor(bIndex);
_fEnded = TRUE;
EndDialog(IDOK);
}
}
|
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
#include <QTimer>
#include <QDataStream>
#include <QTextStream>
#include <QtNetwork/QUdpSocket>
#include <QQueue>
#include "qcustomplot.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
const int Channel_Number = 9;
private slots:
void on_pushButton_open_clicked();
void on_pushButton_close_clicked();
void processSerialRec();
void timerUpdate();
void timerUpdate_indicators();
void selectionChanged();
void on_pushButton_autoscale_clicked();
void on_pushButton_ShowHide_clicked();
private:
const int PIC_WIDTH=1000;
QVector<double> x;
//初始化画布
void qcp_init(void);
Ui::MainWindow *ui;
//串口
QSerialPort *serialport;
//接收数据缓冲
QVector<double> rec[9];
QQueue<char> rec_fifo;
//绘图
QTimer *timer;
//显示更新
QTimer *timer_indicators;
//错误帧计数
int bad_frame_counter;
void dataParser(QString &s, float (&AccGyroRaw)[9]);
};
#endif // MAINWINDOW_H
|
// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.
#include "Sound.h"
#include "SoundResource.h"
#include "core/Engine.h"
namespace ouzel
{
namespace audio
{
Sound::Sound()
{
resource = sharedEngine->getAudio()->createSound();
}
Sound::~Sound()
{
if (sharedEngine) sharedEngine->getAudio()->deleteResource(resource);
}
bool Sound::init(const std::shared_ptr<SoundData>& newSoundData, bool relativePosition)
{
soundData = newSoundData;
return resource->init(newSoundData, relativePosition);
}
void Sound::setPosition(const Vector3& newPosition)
{
return resource->setPosition(newPosition);
}
void Sound::setPitch(float newPitch)
{
return resource->setPitch(newPitch);
}
void Sound::setGain(float newGain)
{
return resource->setGain(newGain);
}
bool Sound::play(bool repeatSound)
{
return resource->play(repeatSound);
}
bool Sound::pause()
{
return resource->pause();
}
bool Sound::stop()
{
return resource->stop();
}
bool Sound::isRepeating() const
{
return resource->isRepeating();
}
} // namespace audio
} // namespace ouzel
|
/* @brief G2.cpp
* Programa que contiene las implementaciones
* de las funciones contenidas en GF2.h
*/
#include <bits/stdc++.h>
#include "defs.h"
using namespace std;
void getPolynomial( int n, string *polynomialString ){
ifstream filetoOpen;
string read;
register int contador = 0;
filetoOpen.open( FILELIST, ios::in );
if( filetoOpen.fail() ){
cout<< "Error opening file";
exit(EXIT_FAILURE);
}
while( getline( filetoOpen, read ) ) {
if( contador == ( n - 3 ) )
*polynomialString = read;
contador++;
}
filetoOpen.close();
}
void getPowers( string polynomialString, bitset<9> *polynomialBits ){
string auxString = "";
for( register int i = 1; i < polynomialString.size() - 1; i++ )
if( polynomialString[i] != ',' ){
auxString = polynomialString[i];
(*polynomialBits).set( stoi( auxString, nullptr, 10 ) );
auxString = "";
}
}
bitset<9> calMultiplication( int row, int column, int n, bitset<9> polynomialBits ){
bitset<9> rowBits(row), columnBits(column);
bitset<9> result;
if( columnBits[0] == 1 )
result = rowBits;
for( register int i = 1; i < n; i++ ){
rowBits = rowBits << 1;
if( rowBits[n] == 1 )
rowBits ^= polynomialBits;
if( columnBits[i] == 1 )
result ^= rowBits;
}
return result;
}
|
#include "pch.h"
#include "PhoneBookDB.h"
//-Считывает данные с файла
//-Создает и заполняет хэш-таблицы
DATABASE_API void __cdecl CreateDB()
{
InitializeCriticalSection(&criticalSection);
surnameHashTable = new HashTable(BY_SURNAME);
streetHashTable = new HashTable(BY_STREET);
phoneHashTable = new HashTable(BY_PHONENUM);
pathToDB = "..\\jija.txt";
EnterCriticalSection(&criticalSection);
records = LoadDB(pathToDB);//читаем с файла и формируем вектор записей
LeaveCriticalSection(&criticalSection);
CreateHashTablesByVector();
}
//-Записывает вектор записей в файл
DATABASE_API void __cdecl DestroyDB()
{
EnterCriticalSection(&criticalSection);
WriteToFile();
LeaveCriticalSection(&criticalSection);
DeleteCriticalSection(&criticalSection);
}
//Добавление новой записи
DATABASE_API void __cdecl AddRecord(PhoneBookRecord* newRecord)
{
records.push_back(newRecord);
surnameHashTable->Add(newRecord);
phoneHashTable->Add(newRecord);
streetHashTable->Add(newRecord);
}
//Запись в файл данных из вектора записей
void WriteToFile()
{
ofstream fout;
fout.open(pathToDB);
if (fout.is_open()) {
fout.clear();
string line;
for (int i = 0;i < records.size();i++)
{
line = "";
line += records[i]->name + "*";
line += records[i]->surname + "*";
line += records[i]->patronymic + "*";
line += records[i]->phoneNum + "*";
line += records[i]->street + "*";
line += to_string(records[i]->houseNum) + "*";
line += to_string(records[i]->blockNum) + "*";
line += to_string(records[i]->flatNum) + "\n";
fout << line;
}
fout.close();
}
}
//Получаем вектор строк что-бы заполнить структуру
std::vector<string> getFields(string line)
{
vector<string> fields;
int startPos = 0;
int endPos = line.find("*");
while (endPos != -1) {
fields.push_back(line.substr(startPos, endPos - startPos));
startPos = endPos + 1;
endPos = line.find("*", startPos);
}
fields.push_back(line.substr(startPos, line.length() - startPos));
return fields;
}
//Выгружаем данные с файла и формируем вектор
std::vector<PhoneBookRecord*> LoadDB(string path)
{
ifstream dataFile;
vector<PhoneBookRecord*> records;
dataFile.open(path);
if (dataFile.is_open()) {
string line;
while (getline(dataFile, line)) {
vector<string> fileRecord = getFields(line);
PhoneBookRecord* record = new PhoneBookRecord();
record->name = fileRecord[0];
record->surname = fileRecord[1];
record->patronymic = fileRecord[2];
record->phoneNum = fileRecord[3];
record->street = fileRecord[4];
record->houseNum = stoi(fileRecord[5]);
record->blockNum = stoi(fileRecord[6]);
record->flatNum = stoi(fileRecord[7]);
records.push_back(record);
}
dataFile.close();
}
return records;
}
//Создание хэш-таблиц
void CreateHashTablesByVector()
{
for (int i = 0;i < records.size();i++)
{
surnameHashTable->Add(records[i]); //внутри метода оно само берет нужное поле
phoneHashTable->Add(records[i]);
streetHashTable->Add(records[i]);
}
}
//Возврат всех записей
DATABASE_API std::vector<PhoneBookRecord*> __cdecl GetAllRecords()
{
return records;
}
//Возврат записей по значению: ФАМИЛИИ или УЛИЦЫ или НОМЕРА
DATABASE_API std::vector<PhoneBookRecord*> __cdecl GetRecordsByValue(string value, int indexingType)
{
vector<PhoneBookRecord*> result;
if (indexingType == BY_SURNAME) { result = surnameHashTable->Find(value); }
if (indexingType == BY_PHONENUM) { result = phoneHashTable->Find(value); }
if (indexingType == BY_STREET) { result = streetHashTable->Find(value); }
return result;
}
DATABASE_API void __cdecl DeleteRecord(PhoneBookRecord* Record)
{
for (int i = 0;i < records.size();i++) {
if (records[i]->blockNum == Record->blockNum &&
records[i]->name == Record->name &&
records[i]->surname == Record->surname &&
records[i]->patronymic == Record->patronymic &&
records[i]->street == Record->street &&
records[i]->houseNum == Record->houseNum &&
records[i]->blockNum == Record->blockNum &&
records[i]->flatNum == Record->flatNum)
{ records.erase(records.begin() + i); }
}
phoneHashTable->Delete(Record);
surnameHashTable->Delete(Record);
streetHashTable->Delete(Record);
}
DATABASE_API void __cdecl ChangeRecord(PhoneBookRecord* oldRecord, PhoneBookRecord* newRecord)
{
for (int i = 0;i < records.size();i++) {
if( records[i]->blockNum== oldRecord->blockNum &&
records[i]->name == oldRecord->name &&
records[i]->surname == oldRecord->surname &&
records[i]->patronymic == oldRecord->patronymic &&
records[i]->street == oldRecord->street &&
records[i]->houseNum == oldRecord->houseNum &&
records[i]->blockNum == oldRecord->blockNum &&
records[i]->flatNum == oldRecord->flatNum)
{
records[i]=newRecord;
}
}
phoneHashTable->Change(oldRecord,newRecord);
surnameHashTable->Change(oldRecord, newRecord);
streetHashTable->Change(oldRecord, newRecord);
}
|
#pragma once
#include "event_system.hpp"
#include "../Renderer/Shader.hpp"
#include "audio_system.hpp"
#include <iostream>
const static int NUM_SCORES = 10;
namespace sf
{
class Window;
};
struct lua_State;
class GraphicsSystem;
class Camera;
struct State
{
lua_State* luaState;
GraphicsSystem* graphicsSystem;
AudioSystem* audioSystem;
};
struct ShaderStruct
{
Shader basic;
Shader shader2d;
Shader amazing;
Shader particle;
Shader trash; // Basic passthrough shader
Shader billboard;
Shader mouseEffect;
Shader postProcessing;
Shader text;
};
typedef std::vector<State> LuaVector;
class Game
{
private:
sf::Window* window;
EventSystem eventSystem;
Camera* camera;
State currentState;
ShaderStruct shaders;
std::string stateName;
sf::Clock highscoreClock;
sf::Music music;
bool fullscreen;
float highscoreList[NUM_SCORES];
public:
Game();
~Game();
void run();
sf::Time timePerFrame;
void changeResolution(int width, int height);
private:
void handleEvents();
void update(float deltaTime);
void updateState();
void initWindow();
//Lua stuff
void addLuaLibraries(lua_State* luaState);
static int newState(lua_State* luaState);
static int deleteState(lua_State* luaState);
static int setFramerate(lua_State* luaState);
static int setResolution(lua_State* luaState);
static int getCameraPosition(lua_State* luaState);
static int newMusic(lua_State* luaState);
};
|
// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.
#pragma once
#include <cstddef>
#include "core/CompileConfig.h"
#if OUZEL_SUPPORTS_SSE
#include <xmmintrin.h>
#endif
namespace ouzel
{
class Vector2;
class Vector3;
class Color;
class Vector4
{
public:
static const Vector4 ZERO;
static const Vector4 ONE;
static const Vector4 UNIT_X;
static const Vector4 UNIT_Y;
static const Vector4 UNIT_Z;
static const Vector4 NEGATIVE_UNIT_X;
static const Vector4 NEGATIVE_UNIT_Y;
static const Vector4 NEGATIVE_UNIT_Z;
#if OUZEL_SUPPORTS_SSE
union
{
__m128 s;
float v[4];
};
#else
float v[4];
#endif
Vector4()
{
v[0] = 0.0f;
v[1] = 0.0f;
v[2] = 0.0f;
v[3] = 0.0f;
}
Vector4(float aX, float aY, float aZ, float aW)
{
v[0] = aX;
v[1] = aY;
v[2] = aZ;
v[3] = aW;
}
Vector4(const Vector4& p1, const Vector4& p2);
Vector4(const Vector4& copy)
{
v[0] = copy.v[0];
v[1] = copy.v[1];
v[2] = copy.v[2];
v[3] = copy.v[3];
}
Vector4(const Vector2& v);
Vector4& operator=(const Vector2& v);
Vector4(const Vector3& v);
Vector4& operator=(const Vector3& v);
Vector4(const Color& color);
Vector4& operator=(const Color& color);
float& x() { return v[0]; }
float& y() { return v[1]; }
float& z() { return v[2]; }
float& w() { return v[3]; }
float x() const { return v[0]; }
float y() const { return v[1]; }
float z() const { return v[2]; }
float w() const { return v[3]; }
float& operator[](size_t index) { return v[index]; }
float operator[](size_t index) const { return v[index]; }
bool isZero() const
{
return v[0] == 0.0f && v[1] == 0.0f && v[2] == 0.0f && v[3] == 0.0f;
}
bool isOne() const
{
return v[0] == 1.0f && v[1] == 1.0f && v[2] == 1.0f && v[3] == 1.0f;
}
static float angle(const Vector4& v1, const Vector4& v2);
void add(const Vector4& vec)
{
v[0] += vec.v[0];
v[1] += vec.v[1];
v[2] += vec.v[2];
v[3] += vec.v[3];
}
static void add(const Vector4& v1, const Vector4& v2, Vector4& dst)
{
dst.v[0] = v1.v[0] + v2.v[0];
dst.v[1] = v1.v[1] + v2.v[1];
dst.v[2] = v1.v[2] + v2.v[2];
dst.v[3] = v1.v[3] + v2.v[3];
}
void clamp(const Vector4& min, const Vector4& max);
static void clamp(const Vector4& vec, const Vector4& min, const Vector4& max, Vector4& dst);
float distance(const Vector4& vec) const;
float distanceSquared(const Vector4& vec) const
{
float dx = vec.v[0] - v[0];
float dy = vec.v[1] - v[1];
float dz = vec.v[2] - v[2];
float dw = vec.v[3] - v[3];
return dx * dx + dy * dy + dz * dz + dw * dw;
}
float dot(const Vector4& vec) const
{
return v[0] * vec.v[0] + v[1] * vec.v[1] + v[2] * vec.v[2] + v[3] * vec.v[3];
}
static float dot(const Vector4& v1, const Vector4& v2)
{
return v1.v[0] * v2.v[0] + v1.v[1] * v2.v[1] + v1.v[2] * v2.v[2] + v1.v[3] * v2.v[3];
}
float length() const;
float lengthSquared() const
{
return v[0] * v[0] + v[1] * v[1] + v[2] * v[2] + v[3] * v[3];
}
void negate()
{
v[0] = -v[0];
v[1] = -v[1];
v[2] = -v[2];
v[3] = -v[3];
}
void normalize();
void scale(float scalar)
{
v[0] *= scalar;
v[1] *= scalar;
v[2] *= scalar;
v[3] *= scalar;
}
void scale(const Vector4& scale)
{
v[0] *= scale.v[0];
v[1] *= scale.v[1];
v[2] *= scale.v[2];
v[3] *= scale.v[3];
}
void set(float newX, float newY, float newZ, float newW)
{
v[0] = newX;
v[1] = newY;
v[2] = newZ;
v[3] = newW;
}
void set(const Vector4& p1, const Vector4& p2)
{
v[0] = p2.v[0] - p1.v[0];
v[1] = p2.v[1] - p1.v[1];
v[2] = p2.v[2] - p1.v[2];
v[3] = p2.v[3] - p1.v[3];
}
void subtract(const Vector4& vec)
{
v[0] -= vec.v[0];
v[1] -= vec.v[1];
v[2] -= vec.v[2];
v[3] -= vec.v[3];
}
static void subtract(const Vector4& v1, const Vector4& v2, Vector4& dst)
{
dst.v[0] = v1.v[0] - v2.v[0];
dst.v[1] = v1.v[1] - v2.v[1];
dst.v[2] = v1.v[2] - v2.v[2];
dst.v[3] = v1.v[3] - v2.v[3];
}
void smooth(const Vector4& target, float elapsedTime, float responseTime);
float getMin() const;
float getMax() const;
inline Vector4 operator+(const Vector4& vec) const
{
Vector4 result(*this);
result.add(vec);
return result;
}
inline Vector4& operator+=(const Vector4& vec)
{
add(vec);
return *this;
}
inline Vector4 operator-(const Vector4& vec) const
{
Vector4 result(*this);
result.subtract(vec);
return result;
}
inline Vector4& operator-=(const Vector4& vec)
{
subtract(vec);
return *this;
}
inline Vector4 operator-() const
{
return Vector4(-v[0], -v[1], -v[2], -v[3]);
}
inline Vector4 operator*(float scalar) const
{
Vector4 result(*this);
result.scale(scalar);
return result;
}
inline Vector4& operator*=(float scalar)
{
scale(scalar);
return *this;
}
inline Vector4 operator/(float scalar) const
{
return Vector4(v[0] / scalar, v[1] / scalar, v[2] / scalar, v[3] / scalar);
}
inline Vector4& operator/=(float scalar)
{
v[0] /= scalar;
v[1] /= scalar;
v[2] /= scalar;
v[3] /= scalar;
return *this;
}
inline bool operator<(const Vector4& vec) const
{
if (v[0] == vec.v[0])
{
if (v[1] == vec.v[1])
{
if (v[2] == vec.v[2])
{
return v[3] < vec.v[3];
}
return v[2] < vec.v[2];
}
return v[1] < vec.v[1];
}
return v[0] < vec.v[0];
}
inline bool operator==(const Vector4& vec) const
{
return v[0] == vec.v[0] && v[1] == vec.v[1] && v[2] == vec.v[2] && v[3] == vec.v[3];
}
inline bool operator!=(const Vector4& vec) const
{
return v[0] != vec.v[0] || v[1] != vec.v[1] || v[2] != vec.v[2] || v[3] != vec.v[3];
}
};
inline Vector4 operator*(float x, const Vector4& vec)
{
Vector4 result(vec);
result.scale(x);
return result;
}
}
|
#include <iostream>
using namespace std;
class Queue
{
private:
int size;
int front;
int rear;
int *arr;
public:
Queue();
Queue(int);
void enQueue(int);
int deQueue();
void display();
};
Queue::Queue()
{
size = 10;
front = rear = -1;
arr = new int[size];
}
Queue::Queue(int size)
{
this->size = size;
front = rear = -1;
arr = new int[this->size];
}
void Queue::enQueue(int x)
{
if (rear == size - 1)
{
cout << "Queue is Full\n";
}
else
{
rear++;
arr[rear] = x;
}
}
int Queue::deQueue()
{
int x = -1;
if (rear == front)
{
cout << "Queue is Empty!\n";
}
else
{
front++;
x = arr[front];
arr[front]=NULL;
}
return x;
}
void Queue::display()
{
for (int i = 0; i < size; i++)
{
cout << arr[i] << endl;
}
}
|
#include <cstdio>
// 送分 print frequency
// 9 8 5 1 7 2 8 2 9 10 1 7 8 9 5 6 9 0 1 9
const int num = 20;
int main() {
int arr[20] = {0};
int tmp;
for(int i = 0; i < num; i++) {
scanf("%d", &tmp);
arr[tmp]++;
}
for(int i = 0; i < 11; i++) {
printf("%d:%d\n", i, arr[i]);
}
return 0;
}
|
#include<iostream>
#include<stack>
using namespace std;
bool is_correct(string);
int main(){
cout<<"Enter parenthesis"<<endl;
string s;
cin>>s;
cout<<endl<<is_correct(s);
return 0;
}
bool is_correct(string s){
stack<char> estack;
int i=0;
while(s[i]!='\0'){
if( s[i]=='[' || s[i]=='{' || s[i]=='(' ){
estack.push(s[i]);
}else if( s[i]==']' || s[i]=='}' || s[i]==')' ){
if( estack.empty() ){
return false;
}else if(estack.top()=='{' && s[i]=='}'){
estack.pop();
}else if(estack.top()=='[' && s[i]==']'){
estack.pop();
}else if(estack.top()=='(' && s[i]==')'){
estack.pop();
}
}
i++;
}
return estack.empty() ? true:false;
}
|
#include <iostream>
using namespace std;
int main()
{
int a;
cout << "입력: ";
cin >>hex>> a;
cout << "10진수: " <<dec<<a << endl;
cout << "8진수: " << oct << a << endl;
}
|
#pragma once
/*
문제:
1 부터 N 까지 차례대로 수를 쓰내려갈 때 특정수의 빈도수를 구하는 것이 문제이다.
예를 들어, N = 11 이고 조사할 수가 1 인 경우
1234567891011
빈도 수는 4 이다.
입력:
N 과 한 자리 수(0 ~ 9)가 주어진다. N 은 100 000 000 이하의 자연수이다.
출력:
빈도 수를 출력한다. 답은 32 비트 정수 범위를 넘어가지 않는다.
예제 입력 1:
11 1
예제 출력 1:
4
나의 방법:
1)
1~9와 0은 계산법이 약간 다르다.
2)
스터디 풀이 방법들:
1.
2.
3.
*/
namespace BG0814 {
struct InputData {
int N, findN;
};
using INPUT = InputData;
using OUTPUT = int;
using SOLUTION = OUTPUT(*)(INPUT);
using INPUT_PROCESS = OUTPUT(*)(INPUT&);
OUTPUT inputProcess(INPUT&);
OUTPUT solution_1(INPUT);
OUTPUT solution_2(INPUT);
OUTPUT solution_3(INPUT);
/** 사용할 값*/
#define VALID_INPUT 1
#define INVALID_INPUT -1
int f(int n);
/** Test Case */
void SetTestCase(INPUT& input);
}
|
#include <objects/health_potion.h>
using namespace lab3::objects;
Health_Potion::Health_Potion(const std::string &name, int extra_points, int price, int weight, int volume)
: Potion(name, "You recover some life points", extra_points, price, weight, volume)
{}
Health_Potion::~Health_Potion()
{}
ActionResult Health_Potion::use(Character &c)
{
c.add_life(this->extra_points_);
std::stringstream ss;
ss << "You have use a "<<this->name()<<", which gives you "<<extra_points_<<" life points. "<<
"Now you have "<<c.getLifePoints()<< " life points";
lab3::utils_io::print_newline(ss.str());
return true;
}
|
#include <bits/stdc++.h>
using namespace std;
#define REP(i, init, n) for(int i = (int)(init); i < (int)(n); i++)
#define vi vector<int>
#define vl vector<long>
#define vvi vector<vector<int>>
#define vvl vector<vector<long>>
#define pint pair<int, int>
#define plong pair<long, long>
int main() {
double n, m, d;
cin>>n>>m>>d;
double ans = 0;
if(d == 0) ans = (m-1)/n;
else ans = (m-1)* 2*(n-d)/(n*n);
cout << setprecision(10) << ans << endl;
}
|
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
unordered_map<int, int> table;
int sum = 0;
int count = 0;
for (int i = 0; i < nums.size(); i++) {
sum += nums[i];
if (sum == k)
count++;
if (table.find(sum - k) != table.end()) {
count += table[sum - k];
}
table[sum]++;
}
return count;
}
};
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::Globalization::PhoneNumberFormatting {
struct IPhoneNumberFormatter;
struct IPhoneNumberFormatterStatics;
struct IPhoneNumberInfo;
struct IPhoneNumberInfoFactory;
struct IPhoneNumberInfoStatics;
struct PhoneNumberFormatter;
struct PhoneNumberInfo;
}
namespace Windows::Globalization::PhoneNumberFormatting {
struct IPhoneNumberFormatter;
struct IPhoneNumberFormatterStatics;
struct IPhoneNumberInfo;
struct IPhoneNumberInfoFactory;
struct IPhoneNumberInfoStatics;
struct PhoneNumberFormatter;
struct PhoneNumberInfo;
}
namespace Windows::Globalization::PhoneNumberFormatting {
template <typename T> struct impl_IPhoneNumberFormatter;
template <typename T> struct impl_IPhoneNumberFormatterStatics;
template <typename T> struct impl_IPhoneNumberInfo;
template <typename T> struct impl_IPhoneNumberInfoFactory;
template <typename T> struct impl_IPhoneNumberInfoStatics;
}
namespace Windows::Globalization::PhoneNumberFormatting {
enum class PhoneNumberFormat
{
E164 = 0,
International = 1,
National = 2,
Rfc3966 = 3,
};
enum class PhoneNumberMatchResult
{
NoMatch = 0,
ShortNationalSignificantNumberMatch = 1,
NationalSignificantNumberMatch = 2,
ExactMatch = 3,
};
enum class PhoneNumberParseResult
{
Valid = 0,
NotANumber = 1,
InvalidCountryCode = 2,
TooShort = 3,
TooLong = 4,
};
enum class PredictedPhoneNumberKind
{
FixedLine = 0,
Mobile = 1,
FixedLineOrMobile = 2,
TollFree = 3,
PremiumRate = 4,
SharedCost = 5,
Voip = 6,
PersonalNumber = 7,
Pager = 8,
UniversalAccountNumber = 9,
Voicemail = 10,
Unknown = 11,
};
}
}
|
//----------------------------- Problem 4
#include <iostream>
using namespace std;
int main(){
char first,second,third,fourth,fifth;
cout << "Enter first char of your name ";
cin >> first;
cout << "Enter second char of your name ";
cin >> second;
cout << "Enter third char of your name ";
cin >> third;
cout << "Enter fourth char of your name ";
cin >> fourth;
cout << "Enter fifth char of your name ";
cin >> fifth;
cout << "name is : " << first << second << third << fourth << fifth;
return 0;
}
|
#include <bits/stdc++.h>
using namespace std;
// LCS,Longest Common Sequence,最长公共子序列
// 还是序列的问题,所以状态还是跟序列最末元素有关,但是有两个字符串
// 动态规划的好处就是你可以屏蔽掉其他的一些细节,
// 专注于两个状态切换时的动作,把这个用递推式表达出来,加上初始状态,我们就得到这个问题的解
// 所以这题很自然能够想到的状态切换时的样子,
// 第一个是 if A[i]==B[j], dp[i][j] = dp[i - 1][j - 1] + 1, else dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
// 想着想着发现递归式就已经出来了
// 然后我们再想应该填什么初始状态,你可以把dp[i][j]看成是一个二维矩阵,所以它的状态在矩阵上是怎么蔓延的?
// 就是要知道 左上&左&上 的状态,所以我可以想象初始状态就是把矩阵的左宽和上长填好,之后就可以一直蔓延
// 同时也要注意到不把这两条边填好dp的状态转移方程也会越界
// for i, dp[i][0] = 0, for j, dp[0][j] = 0
// 我们要的答案就是dp[i][j]
int main()
{
string A, B;
while (cin >> A >> B)
{
int lenA = A.length();
int lenB = B.length();
int dp[105][105] = {};
// for (int i = 0; i <= lenA; i++)
// dp[i][0] = 0;
// for (int j = 0; j <= lenB; j++)
// dp[0][j] = 0;
// 比较易错的点,就是lenA要取等号,因为起始从1开始才比较字符
for (int i = 1; i <= lenA; i++)
{
for (int j = 1; j <= lenB; j++)
{
// A[i - 1] == B[j - 1] 也很易错,事实上dp的状态跟字符的下标没有对应上
// 当然算法笔记是通过scanf输入前移一位把A和B的第一位置空,但这里已经熟练就没必要
dp[i][j] = (A[i - 1] == B[j - 1] ? dp[i - 1][j - 1] + 1 : max(dp[i - 1][j], dp[i][j - 1]));
}
}
// 这里也是,不要写成dp[lenA - 1][lenB - 1]
printf("%d\n", dp[lenA][lenB]);
}
}
|
/*
* File: File.h
* Author: gmena
*
* Created on 23 de agosto de 2014, 02:51 PM
*/
#include <string>
#include <sstream>
#include <iostream>
#include <cstring>
#include <fstream>
#include <unistd.h>
#include <sys/stat.h>
#ifndef FILE_H
#define FILE_H
using namespace std;
class File {
public:
string readAt (const char *dir);
void make (string dir);
void rm (string dir);
bool isFile (string path);
bool isDir (string path);
private:
};
#endif /* FILE_H */
|
#include "pch.h"
#include "DependencyInjector.h"
#include "Renderer.h"
#include "Window.h"
#include "Camera.h"
DependencyInjector* DependencyInjector::m_pInstance = nullptr;
DependencyInjector::~DependencyInjector()
{
delete m_pWindow;
delete m_pCamera;
m_pInstance = nullptr;
}
Renderer* DependencyInjector::InjectRenderer()
{
return new Renderer(InjectCamera());
}
Window* DependencyInjector::InjectWindow(const int width, const int height)
{
if (!m_pWindow)
{
m_pWindow = new Window("Renderer", width, height);
}
return m_pWindow;
}
Camera* DependencyInjector::InjectCamera()
{
if (!m_pCamera)
{
m_pCamera = new Camera();
}
return m_pCamera;
}
void DependencyInjector::SetCamera(Camera* pCam)
{
if (m_pCamera)
{
delete m_pCamera;
}
m_pCamera = pCam;
}
|
#include <ros/ros.h>
#include <std_msgs/String.h>
#include <std_msgs/Int16.h>
#include <std_msgs/Float32.h>
#include "white_ticket/Distance.h"
#include <stdio.h>
#include <string>
#include <vector>
#include <time.h>
#include <iostream>
using namespace std;
const int LIMIT = 3;
const int ALL = 6;
const int SAME = 3;
const int DISTANCE_THRESHOLD = 5;
float distance_val = 100;
string ticket_id = "0";
string decode_ticket = "0";
string seed="-1";
string decode="-1";
vector<string> seeds(ALL, "-1");
vector<string> decodes(ALL, "-1");
string seed_now, decode_now;
int seed_cnt, decode_cnt;
int dp[ALL+1][ALL+1];
ros::Publisher pub;
std_msgs::Int16 display_mode;
void distanceCallback(const std_msgs::Float32::ConstPtr& msg)
{
distance_val = msg->data;
return;
}
void seedCallback(const std_msgs::String::ConstPtr& msg)
{
seed = msg->data;
return;
}
void decodeCallback(const std_msgs::String::ConstPtr& msg)
{
string content = msg->data;
string tmp = "";
int idx = 0;
while(content[idx]!=','){
tmp += content[idx];
idx++;
}
decode = tmp;
decode_ticket = content[idx+1];
return;
}
void ticketCallback(const std_msgs::String::ConstPtr& msg)
{
ticket_id = msg->data;
}
void seed_chk(){
if(seed_now == seed){
seed_cnt++;
if(seed_cnt == LIMIT){
for(int i=ALL-1; i>=1; i--)
seeds[i] = seeds[i-1];
seeds[0] = seed_now;
}
} else{
seed_now = seed;
seed_cnt = 1;
}
}
void decode_chk(){
if(decode_now == decode){
decode_cnt++;
if(decode_cnt == LIMIT){
for(int i=ALL-1;i>=1;i--)
decodes[i] = decodes[i-1];
decodes[0] = decode;
}
} else{
decode_now = decode;
decode_cnt = 1;
}
}
void buf_print(){
printf("seeds : ");
for(int i=0;i<ALL;i++)
printf("%s ", seeds[i].c_str());
printf("\n");
printf("decodes : ");
for(int i=0;i<ALL;i++)
printf("%s ", decodes[i].c_str());
printf("\n");
}
void count(){
for(int i=1;i<=ALL;i++){
for(int j=1;j<=ALL;j++){
if(seeds[i-1] != "-1" && decodes[j-1] != "-1" && seeds[i-1]==decodes[j-1])
dp[i][j] = dp[i-1][j-1]+1;
else
dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
}
}
}
bool pass_chk(){
if((decode != "-1") && (decode_ticket != ticket_id))
return false;
if(dp[ALL][ALL] >= SAME)
return true;
else
return false;
}
void pass_action(){
display_mode.data = 0;
printf("PASS!!!\n");
pub.publish(display_mode);
}
void not_pass_action(){
display_mode.data = 1;
printf("NOT PASS!!!\n");
pub.publish(display_mode);
}
void take_away_action(){
//display_mode.data = "take_away";
printf("TAKE AWAY PHONE!\n");
//pub.publish(display_mode);
}
void not_in_action(){
display_mode.data = 4;
printf("please in your phone\n");
pub.publish(display_mode);
}
void in_action(){
display_mode.data = 3;
printf("IN\n");
pub.publish(display_mode);
}
void out_of_range_action(){
display_mode.data = 2;
printf("your phone is out of range\n");
printf("please in your phone\n");
pub.publish(display_mode);
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "main_node");
ros::NodeHandle nh;
pub = nh.advertise<std_msgs::Int16>("display",100);
ros::Subscriber distance_sub = nh.subscribe("distance",20,distanceCallback);
ros::Subscriber seed_sub = nh.subscribe("seed",20,seedCallback);
ros::Subscriber decode_sub = nh.subscribe("decode",20,decodeCallback);
ros::Subscriber ticket_sub = nh.subscribe("ticket",20,ticketCallback);
ros::Rate loop_rate(10);
bool pass = false;
int in_cnt = 0;
while(ros::ok())
{
//ROS_INFO("distance: %.2fcm", distance_val)lt target tutorial_generate_messages_py
ROS_INFO("seed %s / decode %s",seed.c_str(), decode.c_str());
//printf("in_cnt : %d distance : %f \n", in_cnt, distance_val);
if(distance_val < DISTANCE_THRESHOLD){
in_cnt++;
}
else{
not_in_action();
in_cnt = 0;
}
if(in_cnt >= 5){
in_action();
clock_t in_time = clock();
int out_cnt = 0;
while(1){
//printf("in_cnt : %d distance : %f \n", in_cnt, distance_val);
seed_chk();
decode_chk();
buf_print();
count();
if(!pass) pass = pass_chk();
if(pass){
pass_action();
if(out_cnt > 5){
printf("BYE!\n");
pass = false;
in_cnt = 0;
decodes.assign(ALL,"-1");
break;
}else{
take_away_action();
}
}else{
double time = clock() - in_time;
printf("time : %lf in_time : %lf\n",time,in_time);
if(time > 100000){
printf("time : %d\n",time);
while(1){
if(out_cnt > 5){
not_pass_action();
break;
}else{
not_pass_action();
take_away_action();
}
if(distance_val >= DISTANCE_THRESHOLD) out_cnt++;
else out_cnt = 0;
loop_rate.sleep();
ros::spinOnce();
}
decodes.assign(ALL,"-1");
break;
}else{
if(out_cnt > 5){
out_of_range_action();
pass = false;
in_cnt = 0;
decodes.assign(ALL,"-1");
in_time = clock();
//break;
}else{
in_action();
}
}
}
if(distance_val >= DISTANCE_THRESHOLD) out_cnt++;
else out_cnt = 0;
loop_rate.sleep();
ros::spinOnce();
}
}
loop_rate.sleep();
ros::spinOnce();
}
return 0;
}
|
class Solution {
public:
int getFood(vector<vector<char>>& grid) {
int m = grid.size(), n = grid[0].size();
queue<vector<int>> q; // <i, j>
vector<vector<int>> dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == '*') { // starting position
q.push({i, j});
break;
}
}
}
int step = 0;
while (!q.empty()) {
step++;
for (int i = q.size(); i > 0; i--) {
auto cur = q.front(); q.pop();
for (auto dir : dirs) {
int x = cur[0] + dir[0], y = cur[1] + dir[1];
if (x < 0 || x >= m || y < 0 || y >= n || grid[x][y] == 'X') continue;
if (grid[x][y] == '#') return step; // found the target
grid[x][y] = 'X'; // [x][y] has been visited
q.push({x, y});
}
}
}
return -1;
}
};
|
// github.com/andy489
// https://www.hackerrank.com/contests/practice-3-sda/challenges/balloons-and-candy
#include <cstdio>
#include <utility>
#include <algorithm>
typedef long long ll;
using namespace std;
const int mxN = 100005;
ll n, m, l, r = 1e18, mid, s;
pair<ll, ll> A[mxN];
int main() {
scanf("%lld%lld", &n, &m);
int i(i);
for (; i < n; ++i)
scanf("%lld", &A[i].first);
for (i = 0; i < n; ++i)
scanf("%lld", &A[i].second);
while (l < r) {
mid = l + (r - l) / 2, s = 0;
for (i = 0; i < n; ++i)
s += max(0ll, A[i].first - mid / A[i].second);
if (s <= m)
r = mid;
else
l = mid + 1;
}
return printf("%lld", l), 0;
}
|
#ifndef RECTANGLE_H
#define RECTANGLE_H
class Rectangle{
public:
Rectangle();
int getWidth();
void setWidth(int);
double getHeight();
void setHeight(double);
private:
int width;
double height;
};
#endif
|
#include "stdafx.h"
#include "Reader.h"
#include "Data.h"
using namespace std;
namespace
{
istringstream getLineStrm(istream & in)
{
string str;
getline(in, str);
return istringstream(str);
}
void readLine(istream && in, Data & d, size_t y)
{
char ch;
size_t x = 0;
while (x < d.width() && !in.eof() && (in >> ch))
{
auto type = Type(ch);
auto currPoint = Point(x, y);
if (type == Type::King)
{
d.start = currPoint;
type = Type::Free;
}
d(currPoint.x, currPoint.y) = { type, 0 };
if (isEnemy(type))
{
d(currPoint.x, currPoint.y).id = d.enemies.size();
d.enemies.push_back({ type, currPoint });
}
++x;
}
if (x != d.width())
{
throw invalid_argument("not enougth data on row " + to_string(y + 1));
}
}
};
namespace Reader
{
Data readData(istream & in)
{
size_t rows, columns;
auto strm = getLineStrm(in);
if (!(strm >> rows >> columns) || rows <= 0 || columns <= 0)
{
throw invalid_argument("invalid data size");
}
auto d = Data(columns, rows);
for (size_t i = 0; i < rows && !in.eof(); ++i)
{
readLine(getLineStrm(in), d, i);
}
return d;
}
}
|
/*
* SPDX-FileCopyrightText: (C) 2018 Daniel Nicoletti <dantti12@gmail.com>
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef PROTOCOLHTTP2_H
#define PROTOCOLHTTP2_H
#include "hpack.h"
#include "protocol.h"
#include "socket.h"
#include <context.h>
#include <enginerequest.h>
#include <QObject>
// namespace Cutelyst {
// class Headers;
// }
class QEventLoop;
namespace Cutelyst {
class H2Frame
{
public:
quint32 len;
quint32 streamId;
quint8 type;
quint8 flags;
};
class ProtoRequestHttp2;
class H2Stream final : public Cutelyst::EngineRequest
{
public:
enum State {
Idle,
Open,
HalfClosed,
Closed
};
H2Stream(quint32 streamId, qint32 initialWindowSize, ProtoRequestHttp2 *protoRequestH2);
~H2Stream() override;
virtual qint64 doWrite(const char *data, qint64 len) override final;
virtual bool writeHeaders(quint16 status, const Cutelyst::Headers &headers) override final;
virtual void processingFinished() override final;
void windowUpdated();
QEventLoop *loop = nullptr;
QString scheme;
ProtoRequestHttp2 *protoRequest;
quint32 streamId;
qint32 windowSize = 65535;
qint64 contentLength = -1;
qint32 dataSent = 0;
qint64 consumedData = 0;
quint8 state = Idle;
bool gotPath = false;
};
class ProtoRequestHttp2 final : public ProtocolData
{
Q_GADGET
public:
ProtoRequestHttp2(Cutelyst::Socket *sock, int bufferSize);
~ProtoRequestHttp2() override;
void setupNewConnection(Cutelyst::Socket *sock) override final;
inline void resetData() override final
{
ProtocolData::resetData();
stream_id = 0;
pktsize = 0;
delete hpack;
hpack = nullptr;
auto it = streams.constBegin();
while (it != streams.constEnd()) {
// If we deleteLater the context, there might
// be an event that tries to finalize the request
// and it will encounter a null context pointer
delete it.value()->context;
delete it.value();
++it;
}
streams.clear();
headersBuffer.clear();
maxStreamId = 0;
streamForContinuation = 0;
dataSent = 0;
windowSize = 65535;
settingsInitialWindowSize = 65535;
canPush = false;
}
quint32 stream_id = 0;
quint32 pktsize = 0;
QByteArray headersBuffer;
HPack *hpack = nullptr;
quint64 streamForContinuation = 0;
quint32 maxStreamId = 0;
qint32 dataSent = 0;
qint32 windowSize = 65535;
qint32 settingsInitialWindowSize = 65535;
quint32 settingsMaxFrameSize = 16384;
quint8 processing = 0;
bool canPush = true;
QHash<quint32, H2Stream *> streams;
};
class ProtocolHttp2 final : public Protocol
{
public:
explicit ProtocolHttp2(Server *wsgi);
~ProtocolHttp2() override;
Type type() const override;
void parse(Cutelyst::Socket *sock, QIODevice *io) const override final;
ProtocolData *createData(Cutelyst::Socket *sock) const override final;
int parseSettings(ProtoRequestHttp2 *request, QIODevice *io, const H2Frame &fr) const;
int parseData(ProtoRequestHttp2 *request, QIODevice *io, const H2Frame &fr) const;
int parseHeaders(ProtoRequestHttp2 *request, QIODevice *io, const H2Frame &fr) const;
int parsePriority(ProtoRequestHttp2 *request, QIODevice *io, const H2Frame &fr) const;
int parsePing(ProtoRequestHttp2 *request, QIODevice *io, const H2Frame &fr) const;
int parseRstStream(ProtoRequestHttp2 *request, QIODevice *io, const H2Frame &fr) const;
int parseWindowUpdate(ProtoRequestHttp2 *request, QIODevice *io, const H2Frame &fr) const;
int sendGoAway(QIODevice *io, quint32 lastStreamId, quint32 error) const;
int sendRstStream(QIODevice *io, quint32 streamId, quint32 error) const;
int sendSettings(QIODevice *io, const std::vector<std::pair<quint16, quint32>> &settings) const;
int sendSettingsAck(QIODevice *io) const;
int sendPing(QIODevice *io, quint8 flags, const char *data = nullptr, qint32 dataLen = 0) const;
int sendData(QIODevice *io, quint32 streamId, qint32 flags, const char *data, qint32 dataLen) const;
int sendFrame(QIODevice *io, quint8 type, quint8 flags = 0, quint32 streamId = 0, const char *data = nullptr, qint32 dataLen = 0) const;
void queueStream(Cutelyst::Socket *socket, H2Stream *stream) const;
bool upgradeH2C(Cutelyst::Socket *socket, QIODevice *io, const Cutelyst::EngineRequest &request);
public:
quint32 m_maxFrameSize;
qint32 m_headerTableSize;
};
} // namespace Cutelyst
#endif // PROTOCOLHTTP2_H
|
#ifndef PROGRESS_H
#define PROGRESS_H
#include <QDialog>
#include <QString>
#include <QSerialPortInfo>
#include <QWidget>
#include <QProgressBar>
#include "ui_progress.h"
class Progress : public QDialog, protected Ui::Progress
{
Q_OBJECT
public:
Progress(QString info, QSerialPortInfo portInfo, QWidget *parent=nullptr);
~Progress();
QProgressBar *getProgressBar();
};
#endif //PROGRESS_H
|
#pragma once
//////////////////////////////////////////////////////////////////////////
#include "geometry.h"
#include "wgeometry.h"
#include "operators.h"
#include "TVView.h"
//////////////////////////////////////////////////////////////////////////
enum _TVN
{
TVFN_LAST = 0u-100u,
TVFN_FIRST = 0u-200u,
TVFN_WINDOWADDED,
TVFN_WINDOWREMOVED,
TVFN_WINDOWRESIZED,
};
struct TVFNMHDR : NMHDR
{
TVFNMHDR(HWND hwnd, UINT c)
{
hwndFrom=hwnd;
idFrom=GetWindowLong(hwnd, GWL_ID);
code=c;
};
LRESULT SendMessage()
{
return ::SendMessage(
GetParent(hwndFrom),
WM_NOTIFY,
(WPARAM)idFrom,
(LPARAM)this);
}
};
struct CBmp
{
CBmp()
: bitmap_(new CBitmap())
{
}
CBmp(HBITMAP hbmp, CSize sz=CSize())
: bitmap_(new CBitmap(hbmp)),
size_(sz)
{
}
CBmp(const CBmp &bmp)
: bitmap_(bmp.bitmap_),
size_(bmp.size_)
{}
CBmp &operator=(CBmp bmp)
{
swap(bmp);
return *this;
}
void swap(CBmp &bmp)
{
bitmap_.swap(bmp.bitmap_);
std::swap(size_, bmp.size_);
}
operator CBitmapHandle() const
{
return CBitmapHandle( *bitmap_ );
}
CSize GetSize() const
{
return size_;
}
private:
shared_ptr<CBitmap> bitmap_;
CSize size_;
};
/////////////////////////////////////////////////////////////////////////
void ShowCopyClipDlg(HWND window);
class CTileViewFrame
: public CWindowImpl<CTileViewFrame>
{
public:
DECLARE_WND_CLASS(NULL)
BOOL PreTranslateMessage(MSG *pMsg);
BEGIN_MSG_MAP_EX(CTileViewView)
MESSAGE_HANDLER(WM_PAINT, OnPaint);
MSG_WM_CREATE(OnCreate);
MSG_WM_DESTROY(OnDestroy);
MSG_WM_SIZE(OnSize);
MESSAGE_HANDLER_EX(WM_SHOWWINDOW, OnShowWindow);
MESSAGE_HANDLER_EX(WM_WINDOWPOSCHANGED, OnShowWindow);
MSG_WM_SETFOCUS(OnSetFocus);
MSG_WM_KILLFOCUS(OnFocus);
MSG_WM_ERASEBKGND(OnEraseBackground);
MSG_WM_MOUSEMOVE(OnMouseMove);
MSG_WM_LBUTTONDOWN(OnLButtonDown);
MSG_WM_LBUTTONUP(OnLButtonUp);
MSG_WM_MBUTTONDOWN(OnMButtonDown);
MSG_WM_SETCURSOR(OnSetCursor);
MESSAGE_HANDLER(TVFM_CHILDLBUTTONDOWN, OnChildLButtonDown);
MESSAGE_HANDLER(TVFM_DELETECHILD, OnDeleteChild);
MESSAGE_HANDLER(TVFM_UPDATELAYOUT, OnUpdateLayout);
MESSAGE_HANDLER(TVFM_REPLACECHILD, OnReplaceChild);
MESSAGE_HANDLER(TVFM_ARRANGEWINDOWS, OnArrangeWindows);
MESSAGE_HANDLER(TVFM_STARTDRAG, OnStartDrag);
MESSAGE_HANDLER(TVFM_ISINDRAGMODE, OnIsInDragMode);
MESSAGE_HANDLER_EX(TVVM_COPYCLIP, OnCopyClip);
COMMAND_ID_HANDLER_EX(ID_FILE_OPEN, OnFileOpen);
COMMAND_ID_HANDLER_EX(ID_FILE_SAVE, OnFileSave);
REFLECT_NOTIFICATIONS();
END_MSG_MAP()
// Handler prototypes (uncomment arguments if needed):
// LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
// LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
// LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/)
CTileViewFrame(bool autodelete=false);
private:
LRESULT OnCreate(LPCREATESTRUCT);
LRESULT OnDestroy();
LRESULT OnSize(UINT, CSize);
LRESULT OnShowWindow(UINT, WPARAM, LPARAM);
LRESULT OnSetFocus(HWND);
LRESULT OnPaint(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL & /*bHandled*/);
LRESULT OnFocus(HWND);
LRESULT OnEraseBackground(HDC);
LRESULT OnSetCursor(HWND=0, UINT=0, UINT=0);
LRESULT OnMouseMove(UINT, CPoint);
LRESULT OnLButtonDown(UINT, CPoint);
LRESULT OnLButtonUp(UINT, CPoint);
LRESULT OnMButtonDown(UINT, CPoint);
LRESULT OnChildLButtonDown(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL & /*bHandled*/);
LRESULT OnDeleteChild(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL & /*bHandled*/);
LRESULT OnReplaceChild(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL & /*bHandled*/);
LRESULT OnUpdateLayout(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL & /*bHandled*/);
LRESULT OnStartDrag(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL & /*bHandled*/);
LRESULT OnIsInDragMode(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL & /*bHandled*/);
LRESULT SetFocusNext(UINT, WPARAM, LPARAM, BOOL &);
LRESULT OnArrangeWindows(UINT, WPARAM, LPARAM, BOOL &);
LRESULT OnCopyClip(UINT, WPARAM, LPARAM);
public:
void ReceiveSubWindows(std::vector<pwindow_t> &);
void UpdateLayout();
void HideAll();
void ShowAll();
void FocusNext();
CRect GetChildRect(pwindow_t) const;
void AppendWindows(int);
void SetCreateWindowCallback(boost::function1<HWND, HWND> func);
void serialization(serl::archiver &ar);
LRESULT OnFileOpen(UINT, int, HWND);
LRESULT OnFileSave(UINT, int, HWND);
void OnFinalMessage(HWND);
void ShowArrangeWindow();
void AddArrangeWindow();
private:
HWND CreateNewWindow();
private:
boost::function1<HWND, HWND> do_create_window_;
std::string serialization_buffer_;
CToolTipCtrl tooltip_;
TOOLINFO tool_;
//! Autodeletes CTVFrame object in ONFinalMessage handler.
bool autodelete_;
//! Hides subwindows while moving splitter
//! to increase perfomance
bool hide_while_moving_;
bool dragging_;
pwindow_t drag_window_;
CImageList drag_list_;
CPoint drag_start_point_;
// painting
std::map<int, CBmp> bitmaps_;
//! member to perform resize operation
shared_ptr<XSlideLine> mobil_zone_;
//! member to perform insert operation
shared_ptr<Inserter> inserter_;
//! members for select operations
bool settingselection_;
point selectionpoint_;
shared_ptr<SelectionRect> selection_;
//! window container
Page page_;
//! subwindow having keyboard focus
pwindow_t focus_;
friend class CArrangeWnd;
};
|
//
// Created by utec on 12/11/19.
//
#ifndef AVA_PREGADRO_H
#define AVA_PREGADRO_H
#include <iostream>
#include <string>
#include "CAlumno.h"
using namespace std;
class Pregrado : public Alumno{
private:
int practica;
public:
Pregrado(int ,string , int , string ,int, int);
void mostrarPregrado();
};
Pregrado::Pregrado(int codigo, string nombre, int dni, string carrera, int credAcum, int practica) : Alumno(codigo ,nombre,dni,carrera ,credAcum) {
this->practica=practica;
}
void Pregrado::mostrarPregrado() {
mostrarAlumno();
cout<<practica<<endl;
}
#endif //AVA_PREGADRO_H
|
#include <cmath>
#include <functional>
#include <future>
#include <iostream>
#include <thread>
#include <random>
using namespace std;
int fun(int a, int b)
{
// std::default_random_engine dre;
return std::pow(a, b);
}
void task_lambda()
{
std::packaged_task<int(int, int)> p([](int a, int b) {
return std::pow(a, b);
});
std::future<int> f = p.get_future();
p(3, 3);
cout << f.get() << endl;
}
void task_bind()
{
std::packaged_task<int()> p(std::bind(fun, 3, 3));
std::future<int> f = p.get_future();
p();
f.wait();
std::cout << f.get() << std::endl;
}
void task_fun()
{
std::packaged_task<int(int, int)> p(fun);
std::future<int> f = p.get_future();
std::thread t(std::move(p), 3, 4);
t.join();
std::cout << f.get() << std::endl;
}
int main(int argc, char *argv[])
{
// task_fun();
// task_bind();
task_lambda();
int a{10};
return 0;
}
|
#include <iostream>
int main()
{
/**
* Commas act as separators in this line, not as an operator.
* Results: a=1, b=2, c=3, i=0
*/
int a = 1, b = 2, c = 3, i = 0;
/**
* Assigns value of b into i.
* Results: a=1, b=2, c=3, i=2
*/
int a = 1, b = 2, c = 3;
int i = (a, b);
/**
* Assigns value of a into i. Equivalent to (i = a), b;
* Results: a=1, b=2, c=3, i=1
* (The curly braces on the second line are needed to
* avoid a compiler error. The second 'b' declared
* is given no initial value.)
*/
int a = 1, b = 2, c = 3;
{
int i = a, b;
}
/**
* Increases value of a by 2, then assigns value of resulting operation a+b into i .
* Results: a=3, b=2, c=3, i=5
*/
int a = 1, b = 2, c = 3;
int i = (a += 2, a + b);
/**
* Increases value of a by 2, then stores value of a to i, and discards unused
* values of resulting operation a + b . Equivalent to (i = (a += 2)), a + b;
* Results: a=3, b=2, c=3, i=3
*/
int a = 1, b = 2, c = 3;
int i;
i = a += 2, a + b;
/**
* Assigns value of a into i; the following 'b' and 'c'
* are not part of the initializer but declarators for
* second instances of those variables.
* Results: a=1, b=2, c=3, i=1
* (The curly braces on the second line are needed to
* avoid a compiler error. The second 'b' and second
* 'c' declared are given no initial value.)
*/
int a = 1, b = 2, c = 3;
{
int i = a, b, c;
}
/**
* Assigns value of c into i, discarding the unused a and b values.
* Results: a=1, b=2, c=3, i=3
*/
int a = 1, b = 2, c = 3;
int i = (a, b, c);
/**
* Returns 6, not 4, since comma operator sequence points following the keyword
* 'return' are considered a single expression evaluating to rvalue of final
* subexpression c=6 .
*/
return a = 4, b = 5, c = 6;
/**
* Returns 3, not 1, for same reason as previous example.
*/
return 1, 2, 3;
/**
* Returns 3, not 1, still for same reason as above. This example works as it does
* because return is a keyword, not a function call. Even though compilers will
* allow for the construct return(value), the parentheses are only relative to "value"
* and have no special effect on the return keyword.
* Return simply gets an expression and here the expression is "(1), 2, 3".
*/
return (1), 2, 3;
}
|
#include "Complex.h"
#include<iostream>
using namespace std;
Complex::Complex(float x, float y): re(x), im(y)
{
cout<<"Complex\n";
}
Complex::~Complex()
{
cout<<"Distruge complex\n";
}
Complex::Complex(const Complex& other)
{
this->re=other.re;
this->im=other.im;
cout<<"Copiaza Complex\n";
}
void Complex::setReal(float x)
{
re=x;
}
void Complex::setImaginar(float y)
{
im=y;
}
float Complex::getReal()
{
return re;
}
float Complex::getImaginar()
{
return im;
}
istream& operator>>(istream&in, Complex a)
{
in>>a.re;
in>>a.im;
return in;
}
ostream& operator<<(ostream&out, const Complex &a)
{
if(a.re==0)
{
if (a.im>0)
out<<"i*"<<a.im;
else if(a.im<0)
out<<"-i*"<<-a.im;
else
out<<"0";
}
else
{
if(a.im==0)
out<<a.re;
else
{
if(a.im>0)
out<<a.re<<"+i*"<<a.im;
else
out<<a.re<<"-i*"<<-a.im;
}
}
out<<"\n";
}
Complex& Complex::operator=(const Complex &z)
{
if ( this != &z)
{
re=z.re;
im=z.im;
}
cout<<"Atribuie Complex\n";
return *this;
}
bool Complex::operator==(const Complex& z) const
{
if(re==z.re && im==z.im)
return true;
else
return false;
}
bool Complex::pur_imaginar()
{
if(re==0)
return true;
else
return false;
}
|
#include <cstdio>
#include <iostream>
using namespace std;
typedef long long ll;
struct Node {
char c;
Node *lc, *rc;
Node() { lc = rc = NULL; }
};
Node node[30];
// 出现过则+1,为孩子则-1
int root[30] = { 0 }, n;
void preOrder(Node* r) {
if (r == NULL)
return;
cout << r->c;
preOrder(r->lc);
preOrder(r->rc);
}
int main() {
// #define DEBUG
#ifdef DEBUG
freopen("d:\\.in", "r", stdin);
freopen("d:\\.out", "w", stdout);
#endif
cin >> n;
char g, l, r;
for (int i = 0; i < n; ++i) {
cin.ignore();
cin >> g >> l >> r;
root[g - 'a']++;
node[g - 'a'].c = g;
if (l != '*') {
root[l - 'a']--;
node[g - 'a'].lc = &node[l - 'a'];
}
if (r != '*') {
root[r - 'a']--;
node[g - 'a'].rc = &node[r - 'a'];
}
}
for (int i = 0; i < 30; ++i)
if (root[i])
preOrder(&node[i]);
return 0;
}
|
#ifndef SIMMETHODS_SEMIIMPLICITEULER_HEADER
#define SIMMETHODS_SEMIIMPLICITEULER_HEADER
#include "SimMethod.h"
#include "Source/Common/Timing.h"
#include <fstream>
namespace solar
{
//Simulates data using semi-implicit Euler integration method
//Expects data to be in following units:
// -pos in AU units
// -vel in AU/Earth year
// -mass in multiples of Sun's masses
class SemiImplicitEuler :public SimMethod
{
public:
void operator()(double step) override final;
};
}
#endif
|
#include <iostream>
#include <string>
#include <cstring>
#include <sstream>
#include <list>
#include <cassert>
class CNode
{
CNode * next_[27]; //\0, a - z
public:
CNode(){
memset(next_, 0, sizeof next_);
}
CNode * next(char c){
if(!c)
return next_[0];
if('a' <= c && c <= 'z')
return next_[c - 'a' + 1];
if('A' <= c && c <= 'Z')
return next_[c - 'A' + 'a' + 1];
return NULL;
}
const CNode * next(char c) const{
if(!c)
return next_[0];
if('a' <= c && c <= 'z')
return next_[c - 'a' + 1];
if('A' <= c && c <= 'Z')
return next_[c - 'A' + 'a' + 1];
return NULL;
}
void next(char c, CNode * n){
assert(n);
if(c){
assert('a' <= c && c <= 'z');
next_[c - 'a' + 1] = n;
}else
next_[0] = n;
}
bool findWord(const char * w) const{
assert(w);
const CNode * n = next(*w);
if(!n)
return false;
if(!*w)
return true;
return n->findWord(w + 1);
}
};
class CTrie
{
std::list<CNode> nodes_;
CNode head_;
public:
void addWord(const std::string & w){
if(w.empty())
return;
CNode * cur = &head_;
for(size_t i = 0;i < w.size();++i){
CNode * n = cur->next(w[i]);
if(!n){
nodes_.push_back(CNode());
n = &nodes_.back();
cur->next(w[i], n);
}
cur = n;
}
nodes_.push_back(CNode());
cur->next(0, &nodes_.back());
}
bool findWord(const std::string & w) const{
if(w.empty())
return false;
return head_.findWord(w.c_str());
}
};
void prepare(CTrie & t, const std::list<std::string> words)
{
for(std::list<std::string>::const_iterator i = words.begin();i != words.end();++i)
t.addWord(*i);
}
bool isValid(const CTrie & t, const std::string & str)
{
std::istringstream iss(str);
for(std::string w;(iss>>w);)
if(!t.findWord(w))
return false;
return true;
}
int main()
{
const char * words[] = {"this", "is", "what", "i", "say"};
const char * strings[] = {
"this is what i say",
"this is not what i say",
"this is th say"
};
std::list<std::string> w(words, words + sizeof words / sizeof words[0]);
CTrie t;
prepare(t, w);
for(size_t i = 0;i < sizeof strings / sizeof strings[0];++i)
std::cout<<isValid(t, strings[i])<<"\n";
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.