text
stringlengths 8
6.88M
|
|---|
#ifndef TRANSFERT_H
#define TRANSFERT_H
#include "clientele.h"
#include "personne.h"
#include"QString"
#include "QSqlQueryModel"
#include "QDate"
#include <QPalette>
#include <QDesktopWidget>
#include <QtGui>
#include "personne.h"
class Transfert
{private:
int ID_client_t;
QString Type;
QString Position ;
QString Date_T;
QString Equipe;
public:
Transfert();
Transfert(int ID_client_t,QString Type,QString Position,QString Date_T,QString Equipe);
int getID_client_t() {return ID_client_t;};
QString getType() {return Type;};
QString getPosition() {return Position;};
QString getDate_T(){return Date_T;};
QString getEquipe(){return Equipe;};
bool AjoutTransfert(Transfert *TR);
virtual QSqlQueryModel * AfficherTransfert();
QSqlQueryModel * RechercherTransfert(int ID_client_t);
bool SupprimerTransfert(int ID_client);
bool ModifierTransfert(Transfert *TR);
};
#endif // TRANSFERT_H
|
#ifndef VINO_H
#define VINO_H
#include <string>
#include <iostream>
#include <iomanip>
#include <sstream>
using std::string;
class Vino {
private:
string nome;
string nazione;
string regione;
string produttore;
string aggettivo;
string colore;
string img64;
double prezzo;
double gradazioneAlcolica;
int temperaturaSuggerita;
int mlBottiglia;
int annata;
public:
//costruttori,operatori,metodi virtuali
Vino(string nome, string nazione, string regione, string produttore, string aggettivo, string colore, string img64,
double prezzo, double gradazioneAlcolica, int temperaturaSuggerita, int mlBottiglia, int annata);
Vino(const Vino&);
virtual Vino& operator=(const Vino&) = delete; //rompo la regola dei 3 non permettendo assegnazione, ma permetto Vino* x=y.clone();
virtual Vino* clone() const =0;
virtual bool operator==(const Vino&) const;
virtual bool operator!=(const Vino&) const;
virtual ~Vino() =default;
virtual string getTipo() const =0;
virtual string getInfo() const;
//getters
string getNome() const;
string getNazione() const;
string getRegione() const;
string getProduttore() const;
string getAggettivo() const;
string getColore() const;
string getImg64() const;
double getPrezzo() const;
double getGradazioneAlcolica() const;
int getTemperaturaSuggerita() const;
int getMlBottiglia() const;
int getAnnata() const;
//setters
void setNome(string nome);
void setNazione(string nazione);
void setRegione(string regione);
void setProduttore(string produttore);
void setAggettivo(string aggettivo);
void setColore(string colore);
void setImg64(string img64);
void setPrezzo(double prezzo);
void setGradazioneAlcolica(double gradazioneAlcolica);
void setTemperaturaSuggerita(int temperaturaSuggerita);
void setMlBottiglia(int mlBottiglia);
void setAnnata(int annata);
};
//Non-astratta
class VinoBarricato: public Vino{
private:
string legno; //tipo di legno usato
public:
//costruttori
VinoBarricato(string nome="No name" ,string nazione="No name", string regione="No name", string produttore="No name", string aggettivo="No name", string colore="No name", string img64="No name",
double prezzo=0, double gradazioneAlcolica=0, int temperaturaSuggerita=0, int mlBottiglia=0, int annata=0, string legno="No name");
VinoBarricato(const VinoBarricato& vb);
//get e set
string getLegno() const;
void setLegno(string legno);
//virtual stuff
VinoBarricato* clone() const;
bool operator==(const Vino&) const;
bool operator!=(const Vino&) const;
string getTipo() const;
string getInfo() const;
};
//Non-astratta
class VinoAromatizzato: public Vino{
private:
string elementoAggiunto;
public:
//costruttori
VinoAromatizzato(string nome="No name" ,string nazione="No name" , string regione="No name", string produttore="No name", string aggettivo="No name", string colore="No name", string img64="No name",
double prezzo=0, double gradazioneAlcolica=0, int temperaturaSuggerita=0, int mlBottiglia=0, int annata=0, string elementoAggiunto="No name");
VinoAromatizzato(const VinoAromatizzato& va);
//get e set
string getElementoAggiunto() const;
void setElementoAggiunto(string elementoAggiunto);
//virtual stuff
VinoAromatizzato* clone() const;
bool operator==(const Vino&) const;
bool operator!=(const Vino&) const;
string getTipo() const;
string getInfo() const;
};
//Non-astratta
class VinoLiquoroso: public Vino{
string liquoreAggiunto;
public:
//costruttori
VinoLiquoroso(string nome="No name" ,string nazione="No name", string regione="No name", string produttore="No name", string aggettivo="No name", string colore="No name", string img64="No name",
double prezzo=0, double gradazioneAlcolica=0, int temperaturaSuggerita=0, int mlBottiglia=0, int annata=0, string liquoreAggiunto="No name");
VinoLiquoroso(const VinoLiquoroso& vl);
//get e set
string getLiquoreAggiunto() const;
void setLiquoreAggiunto(string liquoreAggiunto);
//virtual stuff
VinoLiquoroso* clone() const;
bool operator==(const Vino&) const;
bool operator!=(const Vino&) const;
string getTipo() const;
string getInfo() const;
};
//Non-astratta
class VinoFrizzante: public Vino{
private:
double pressione; //espressa in BAR (tra 1 e 2,5 per i frizzanti, maggiore di 3 per gli spuamanti)
public:
//costruttori
VinoFrizzante(string nome="No name" ,string nazione="No name", string regione="No name", string produttore="No name", string aggettivo="No name", string colore="No name", string img64="No name",
double prezzo=0, double gradazioneAlcolica=0, int temperaturaSuggerita=0, int mlBottiglia=0,
int annata=0, double pressione=0);
VinoFrizzante(const VinoFrizzante& vf);
//get e set
double getPressione() const;
void setPressione(double pressione);
//virtual stuff
VinoFrizzante* clone() const;
bool operator==(const Vino&) const;
bool operator!=(const Vino&) const;
string getTipo() const;
string getInfo() const;
};
//Non-astratta
class Spumante: public VinoFrizzante{
private:
double residuoZuccherino; //espresso in percentuale; 1=100%, quindi è un numero compreso tra 0 e 1
public:
//costruttori
Spumante(string nome="No name" ,string nazione="No name", string regione="No name", string produttore="No name", string aggettivo="No name", string colore="No name", string img64="No name",
double prezzo=0, double gradazioneAlcolica=0, int temperaturaSuggerita=0, int mlBottiglia=0,
int annata=0, double pressione=0, double residuoZuccherino=0);
Spumante(const Spumante& sp);
//get e set
double getResiduoZuccherino() const;
void setResiduoZuccherino(double residuoZuccherino);
//virtual stuff
Spumante* clone() const;
bool operator==(const Vino&) const;
bool operator!=(const Vino&) const;
string getTipo() const;
string getInfo() const;
};
#endif // VINO_H
|
/*
* Operation System Shared Linkage Library Wrapper Implementation
* Copyright(C) 2003-2016 Jinhao
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* @file: _/SharedWrapper.hpp
* @description:
*/
#pragma once
#include <_/Deploy.hpp>
#include <type_traits>
#include <stdexcept>
namespace _ {
namespace system
{
namespace shared_helper
{
typedef void* module_t;
void* symbols (module_t handle, const char* symbol);
}; //< struct shared_helper
class shared_wrapper
{
typedef shared_helper::module_t module_t;
template<typename Function>
struct function_ptr
{
typedef typename std::conditional<std::is_function<Function>::value,
Function*,
typename std::conditional<std::is_function<Function>::value && std::is_pointer<Function>::value, Function, int>::type
>::type type;
};
struct impl_type
{
module_t handle;
std::string symbol;
void* proc_address;
impl_type ();
};
public:
shared_wrapper ();
shared_wrapper (const char* filename);
~shared_wrapper ();
bool open (const char* filename);
void close ();
bool empty () const;
template<typename Function>
typename function_ptr<Function>::type symbols (const char* symbol)
{
typedef typename function_ptr<Function>::type fptr_type;
//if(_::traits::is_function_pointer<fptr_type>::value == false)
if (std::is_function<typename std::remove_pointer<fptr_type>::type>::value == false) throw std::invalid_argument ("shared_wrapper::symbols, template<_Function> is not a function type or a function pointer type");
if (symbol == 0) throw std::invalid_argument ("shared_wrapper::symbols, symbol is null string");
if (impl_.handle == 0) throw std::logic_error ("shared_wrapper::symbols, empty handle");
if (impl_.symbol != symbol)
{
void* result = shared_helper::symbols (impl_.handle, symbol);
if (result == 0) throw std::logic_error ("shared_wrapper::symbols, empty proc address");
impl_.proc_address = result;
impl_.symbol = symbol;
}
return (fptr_type)(this->impl_.proc_address);
}
public:
impl_type impl_;
};
} //< namespace system
} //< namespace _
|
#include <iostream>
#include <cmath>
using namespace std;
bool isPrime(int x) {
//Check if a number is prime
if(x <= 1) return false;
if(x == 2 || x == 3) return true;
else if (x % 2 == 0) return false;
else {
for (int i = 3; i < (int)sqrt((float)x)+1; i++) {
if (x % i == 0) return false;
}
}
return true;
}
bool truncatableCheck(int x) {
if (x<=0) return false;
//Get the length of the number
int len = 0;
int tmp = x;
while (tmp !=0)
{
len ++;
tmp /= 10;
}
//Truncate from right and check if is prime
tmp = x;
while (tmp != 0) {
if (isPrime(tmp) != true) {
return false;
}
tmp /= 10;
}
//Truncate from left and check if is prime
tmp = x;
while(len > 1 ) {
int y = tmp % (int)pow((float)10, len-1);
if (isPrime(y) != true) {
return false;
}
len--;
}
return true;
}
int main() {
int numbers = 0;
int sum = 0;
int i = 8;
while(numbers < 11) {
if (truncatableCheck(i)) {
sum += i;
numbers ++;
cout << i << endl;
}
i++;
}
cout << "Sum "<< sum << endl;
return 0;
}
|
//#include<bits/stdc++.h>
#include<iostream>
#include<vector>
using namespace std;
int main(){
vector<int> haha;
int num;
for(int i=0;i<10;i++){
cin>>num;
haha.push_back(num);
}
for(int i=0;i<10;i++){
cout<<haha[i];
}
return 0;
}
|
#pragma once
#include <utility>
#include <iostream>
#include "../JuceLibraryCode/JuceHeader.h"
#include "Global.h"
#include "AddFood.h"
#include "AddNote.h"
#include "SceneManager.h"
#include <boost/any.hpp>
#include <memory> // std::unique_ptr
#include <vector> // std::vector
#include "DailyPlanImpl.h"
#include "DBConnectionManager.h"
namespace fa {
namespace gui {
class FoodPlanPanel final : public juce::Component {
public:
explicit FoodPlanPanel(SceneManager &, DBConnectionManager &);
virtual void resized() override;
void addEntry(FoodWithAmount);
void addEntry(NoteImpl);
private:
// #######################################################
// private classes
// #######################################################
class TopPanel final : public Component {
public:
TopPanel(DailyPlanImpl &);
virtual void paint(juce::Graphics&) override;
virtual void resized() override;
private:
juce::ProgressBar macroBar_;
juce::ProgressBar microBar_;
juce::ProgressBar kcalBar_;
juce::ProgressBar overallBar_;
double macroValue_ = 0.0;
double microValue_ = 0.0;
double kcalValue_ = 0.0;
double overallValue_ = 0.0;
juce::String macroText_{ "Macro: " };
juce::String microText_{ "Micro: " };
juce::String kcalText_{ "Kcal: " };
juce::String overallText_{ "Overall: " };
juce::ComboBox profile_;
juce::TextEditor date_;
juce::TextButton recommendation_;
DailyPlanImpl &dailyPlan_;
}; // END of class TopPanel
// --------------------------------------------------------
// FoodTable
// --------------------------------------------------------
class FoodList final : public juce::ListBox, public juce::ListBoxModel {
private:
class Entry;
public:
using SmartPointer = std::unique_ptr<Entry>;
using container_type = std::vector<SmartPointer>;
explicit FoodList(DailyPlanImpl &);
void addEntry(FoodWithAmount);
void addEntry(NoteImpl);
//virtual void resized() override;
virtual int getNumRows() override;
virtual void paintListBoxItem(int, juce::Graphics&, int, int, bool) override; // TO BE CHANGED
Component *refreshComponentForRow(int, bool, Component *) override;
virtual void listBoxItemClicked(int, juce::MouseEvent const &) override;
private:
// #######################################################
// FoodList - private classes
// #######################################################
class Entry {
public:
virtual void paint(juce::Graphics &, int, int) = 0;
virtual void openEditDialog() = 0;
virtual ~Entry() = default;
}; // END of class Entry
class FoodEntry final : public Entry {
public:
explicit FoodEntry(FoodWithAmount);
virtual void paint(juce::Graphics &, int, int) override;
virtual void openEditDialog() override;
private:
FoodWithAmount food_;
}; // END of class FoodEntry
class NoteEntry final : public Entry {
public:
explicit NoteEntry(NoteImpl);
virtual void paint(juce::Graphics &, int, int) override;
virtual void openEditDialog() override;
private:
NoteImpl note_;
}; // END of class NoteEntry
DailyPlanImpl &dailyPlan_;
container_type entries_;
juce::PopupMenu popupMenu_;
}; // END of class FoodList
// --------------------------------------------------------
// End FoodTable
// --------------------------------------------------------
class MiddlePanel final : public Component {
public:
explicit MiddlePanel(DailyPlanImpl &);
void addEntry(FoodWithAmount);
void addEntry(NoteImpl);
virtual void resized() override;
private:
FoodList foodList_;
}; // END of class MiddlePanel
class BottomPanel : public Component, public juce::Button::Listener {
public:
explicit BottomPanel(SceneManager &, DBConnectionManager &);
virtual void resized() override;
virtual void buttonClicked(juce::Button *) override;
private:
void startDialogWindow();
juce::ToggleButton noteVisibility_;
juce::TextButton addNote_;
juce::TextButton addFood_;
SceneManager &sceneManager_;
DBConnectionManager &dbManager_;
std::unique_ptr<juce::Component> p_;
}; // END of class BottomPanel
// #######################################################
// vars
// #######################################################
TopPanel topPanel_;
MiddlePanel middlePanel_;
BottomPanel bottomPanel_;
DailyPlanImpl dailyPlan_;
}; // END of class FoodPlanPanel
} // END of namespace gui
} // END of namespace fa
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2011 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#ifdef GADGET_SUPPORT
#include "modules/gadgets/OpGadgetClassProxy.h"
#include "modules/gadgets/OpGadgetClass.h"
#include "modules/gadgets/OpGadgetUpdate.h"
OpGadgetClassProxy::OpGadgetClassProxy(OpGadgetClass* gadget_class)
: m_gadget_class(gadget_class),
m_update_description_document_url(NULL),
m_user_data(NULL)
{}
OpGadgetClassProxy::OpGadgetClassProxy(const uni_char* update_description_document_url,
const void* const user_data)
: m_gadget_class(NULL),
m_update_description_document_url(update_description_document_url),
m_user_data(user_data)
{}
const uni_char* OpGadgetClassProxy::GetUpdateDescriptionDocumentUrl() const
{
return m_gadget_class ? m_gadget_class->GetGadgetUpdateUrl() :
m_update_description_document_url;
}
OpGadgetUpdateInfo* OpGadgetClassProxy::GetUpdateInfo() const
{
return m_gadget_class ? m_gadget_class->GetUpdateInfo() : m_update_info.get();
}
void OpGadgetClassProxy::SetUpdateInfo(OpGadgetUpdateInfo* update_info)
{
if(m_gadget_class)
m_gadget_class->SetUpdateInfo(update_info);
else
m_update_info = OpAutoPtr<OpGadgetUpdateInfo>(update_info);
}
#endif // GADGET_SUPPORT
|
#include<bits/stdc++.h>
using namespace std;
#define pi 3.141592653589793
main()
{
double a,b,c,s,area_of_triangle,r,area_of_circle,sunflower,radious_of_incr;
double area_of_incr,red,violets;
while(scanf("%lf %lf %lf",&a,&b,&c)==3)
{
if(a<=b&&b<=c&&c<=1000){
s = (a+b+c)/2.00;
area_of_triangle = sqrt(s*(s-a)*(s-b)*(s-c));
r=(a*b*c)/(4*area_of_triangle);
area_of_circle = pi*r*r;
sunflower = area_of_circle - area_of_triangle;
radious_of_incr = area_of_triangle/s;
area_of_incr = pi*radious_of_incr*radious_of_incr;
red = area_of_incr;
violets = area_of_triangle - red;
printf("%0.4lf %0.4lf %0.4lf\n",sunflower,violets,red);
}
}
return 0;
}
|
#ifndef Q06_H
#define Q06_H
#include<iostream>
using namespace std;
/** 串
* 存储结构:定长顺序存储(数组)、堆(动态)分配存储(链表)
*
* 字符串匹配
* 1. 暴力匹配
* 2. KMP算法
*/
// 1. 暴力匹配
int hardMatch(string haystack, string needle);
// 2. KMP算法
void cal_next(char *str, int *next, int len);
int KMP(char *str, int slen, char *ptr, int plen);
#endif
|
#include <stdio.h>
int main(void) {
char title[13] = "Cloud Atlas";
int year = 2012;
float budget = 128.5;
float income = 130.5;
printf("-----------------------------------Random film-----------------------------\n");
printf("|%-12s | %13s | %15s | %20s ) |\n", "Title", "Released year", "Budget (million)", "Box office, (million");
printf("|%-12s | %-13d | %16.2f | %23.2f| \n", title, year, budget, income);
printf("--------------------------------This is the end----------------------------\n");
return 0;
}
|
#include "BaseObject.h"
BaseObject::BaseObject()
{
position = glm::vec3(0);
direction = glm::vec3(1.0f, 0.0f, 0.0f);
directionAngle = 0;
modelMatrix = glm::mat4(1);
isDestroyed = false;
}
BaseObject::BaseObject(glm::vec3 fposition, glm::vec3 fdirection)
{
position = fposition;
direction = fdirection;
isDestroyed = false;
if (direction.x != 0.0f)
directionAngle = glm::atan(direction.z/direction.x);
else { directionAngle = 0.0f; }
modelMatrix = glm::translate(position)*glm::rotate(directionAngle, 0.0f, 1.0f, 0.0f);
}
glm::mat4 BaseObject::GetModelMatrix()
{
return modelMatrix;
}
glm::mat4 BaseObject::GetModelMatrixGun()
{
return T*R*S;
}
glm::vec3 BaseObject::GetPosition()
{
return position;
}
glm::vec3 BaseObject::GetDirection() {
return direction;
}
void BaseObject::SetModelMatrix(glm::mat4 fModelMatrix)
{
modelMatrix = fModelMatrix;
}
void BaseObject::UpdateModelMatrix()
{
modelMatrix = T*R*S;
}
void BaseObject::UpdateModelMatrixForBullet() {
if (direction.x != 0.0f)
directionAngle = glm::atan(direction.z / direction.x);
else { directionAngle = 0.0f; }
modelMatrix = glm::translate(position)*glm::rotate(directionAngle, 0.0f, 1.0f, 0.0f);
}
void BaseObject::SetPosition(glm::vec3 fposition) {
position = fposition;
}
void BaseObject::SetDestroyed(bool b) {
isDestroyed = b;
}
bool BaseObject::Destroyed() {
return isDestroyed;
}
BaseObject::~BaseObject()
{
}
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <functional>
#include <queue>
#include <string>
#include <cstring>
#include <numeric>
#include <cstdlib>
#include <cmath>
using namespace std;
typedef long long ll;
#define INF 10e17 // 4倍しても(4回足しても)long longを溢れない
#define rep(i,n) for(int i=0; i<n; i++)
#define rep_r(i,n,m) for(int i=m; i<n; i++)
#define END cout << endl
#define MOD 1000000007
#define pb push_back
#define sorti(x) sort(x.begin(), x.end())
#define sortd(x) sort(x.begin(), x.end(), std::greater<int>())
#define dubug(x) std::cout << (x) << std::endl;
#define roll(x) for (auto itr : x) { debug(itr); }
typedef pair< pair<int,int>, pair<int,int> > pdi;
int main() {
int h,w;
cin >> h >> w;
vector< vector<ll> > a(h + 1, vector<ll>(w + 1));
vector<pdi> ans;
rep(i,h) rep(j,w) {
cin >> a[i][j];
}
auto count_from_left = [&](int high) {
for (int now = 0; now < w; ++now) {
pair<int,int> p1, p2;
if (a[high][now] % 2) {
if (now == w - 1 and high < h - 1) {
p1.first = high;
p1.second = now;
p2.first = high + 1;
p2.second = now;
a[high + 1][now] += 1;
} else {
if (high == h - 1 and now == w - 1) {
break;
} else {
p1.first = high;
p1.second = now;
p2.first = high;
p2.second = now + 1;
a[high][now + 1] += 1;
}
}
ans.push_back(make_pair(p1,p2));
}
}
};
auto count_from_right = [&](int high) {
for (int now = w - 1; now >= 0; --now) {
pair<int,int> p1, p2;
if (a[high][now] % 2) {
if (now == 0 and high < h - 1) {
p1.first = high;
p1.second = now;
p2.first = high + 1;
p2.second = now;
a[high + 1][now] += 1;
} else {
p1.first = high;
p1.second = now;
p2.first = high;
p2.second = now - 1;
a[high][now - 1] += 1;
}
ans.push_back(make_pair(p1,p2));
}
}
};
rep(i, h) {
if (i % 2)
count_from_right(i);
else
count_from_left(i);
}
ll cnt = 0;
if (!ans.empty()) {
cnt = ans.size();
cout << cnt << endl;
for (auto itr : ans) {
pair<int,int> p1 = itr.first, p2 = itr.second;
cout << p1.first+1 << " " << p1.second+1 << " " << p2.first+1 << " " << p2.second+1 << endl;
}
} else {
cout << cnt << endl;
}
}
|
#pragma once
#include "IServer.h"
#include "IOCompletionContext.h"
class _SERVERAPI_EXPORT_ IOCompletionServer
{
public:
IOCompletionServer(void);
virtual ~IOCompletionServer(void);
protected:
//---------------------------------------------------------------------------
//创建完成端口
//---------------------------------------------------------------------------
//新建一个完成端口
HANDLE CreateNewIOCompletionPort(DWORD dwNumOfConcurrentThreads);
//---------------------------------------------------------------------------
//绑定完成端口
//---------------------------------------------------------------------------
//将一个设备句柄与完成端口绑定(关联在一起) 可以关联多个设备
//hDevice设备句柄包括 SOCKET,文件,油槽,管道等
//dwCompletionKey 自定义 参数 在线程里取出使用
bool BindIOCompletionPort(HANDLE hDevice, HANDLE hIOCompletionPort, DWORD dwCompletionKey);
//将套接字与完成端口绑定
bool BindSocketToIOCompletionPort(SOCKET &socket, HANDLE hIOCompletionPort, DWORD dwCompletionKey);
protected:
HANDLE m_hIOCompletionPort; //完成端口的句柄
HANDLE* m_phWorkerThreads; //工作者线程的句柄指针
};
|
#include <unistd.h>
#include <pool_keeper.hpp>
#include <worker.hpp>
#include <algorithm>
#include <iostream>
#include <thread>
namespace thread_pool {
pool_keeper::pool_keeper(int pool_size, int socket_fd)
: socket_fd_(socket_fd) {
int i;
pool_size_ = pool_size;
for (i=0; i<pool_size_; i++) {
workers_.push_back(std::thread(worker(*this, socket_fd_)));
}
sleep(120);
}
}
|
#include <cstdarg>
#include <cstdint>
#include <cstdlib>
#include <new>
struct Foo;
struct FooRef {
Foo *ptr;
};
extern "C" {
FooRef FooRef_create();
void FooRef_sayHello(FooRef self, uint8_t times) /*a comment!*/;
void rust_print_hello_world();
} // extern "C"
|
class equip_lever : CA_Magazine
{
scope = 2;
count = 1;
type = 256;
picture = "\dayz_equip\textures\equip_lever.paa";
model = "\z\addons\dayz_epoch_w\magazine\dze_handle.p3d";
descriptionShort = $STR_EQUIP_DESC_LEVER;
displayName = $STR_EQUIP_NAME_LEVER;
};
class ItemSledgeHead : CA_Magazine
{
scope = 2;
count = 1;
type = 256;
displayName = $STR_EPOCH_SLEDGEHAMMERHEAD;
model = "\z\addons\dayz_epoch\models\sledge_head.p3d";
picture = "\z\addons\dayz_epoch\pictures\equip_sledge_head_ca.paa";
descriptionShort = $STR_EPOCH_SLEDGEHAMMERHEAD_DESC;
class ItemActions
{
class Crafting
{
text = $STR_EPOCH_PLAYER_275;
script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;";
neednearby[] = {"workshop"};
requiretools[] = {"ItemToolbox"};
output[] = {};
outputweapons[] = {"ItemSledge"};
input[] = {{"ItemSledgeHead",1},{"ItemSledgeHandle",1}};
};
};
};
class ItemSledgeHandle : CA_Magazine
{
scope = 2;
count = 1;
type = 256;
displayName = $STR_EPOCH_SLEDGEHAMMERHANDLE;
model = "\z\addons\dayz_epoch\models\sledge_handle.p3d";
picture = "\z\addons\dayz_epoch\pictures\equip_sledge_handle_ca.paa";
descriptionShort = $STR_EPOCH_SLEDGEHAMMERHANDLE_DESC;
class ItemActions
{
class Crafting
{
text = $STR_EPOCH_PLAYER_275;
script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;";
neednearby[] = {"workshop"};
requiretools[] = {"ItemToolbox"};
output[] = {};
outputweapons[] = {"ItemSledge"};
input[] = {{"ItemSledgeHead",1},{"ItemSledgeHandle",1}};
};
};
};
class equip_Crossbow_Kit : CA_Magazine
{
scope = 2;
count = 1;
displayName = $STR_ITEM_NAME_CROSSBOW_KIT;
descriptionShort = $STR_ITEM_DESC_CROSSBOW_KIT;
model = "\z\addons\community_crossbow\models\Crossbow_kit.p3d";
picture = "\z\addons\community_crossbow\textures\Crossbow_kit.paa";
type = 256;
class ItemActions
{
class Crafting
{
text = $STR_CRAFTING_CROSSBOW;
script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;";
neednearby[] = {"workshop"};
requiretools[] = {"ItemToolbox","ItemKnife"};
output[] = {};
outputweapons[] = {"Crossbow_DZ"};
input[] = {{"equip_Crossbow_Kit",1},{"equip_crossbow_stock",1}};
};
};
};
class equip_crossbow_stock : CA_Magazine
{
scope = 2;
count = 1;
displayName = $STR_ITEM_NAME_CROSSBOW_STOCK;
descriptionShort = $STR_ITEM_DESC_CROSSBOW_STOCK;
model = "z\addons\community_crossbow\models\crossbow_stock.p3d";
picture = "\z\addons\community_crossbow\icons\crossbow_stock.paa";
type = 256;
class ItemActions
{
class Crafting
{
text = $STR_CRAFTING_CROSSBOW;
script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;";
neednearby[] = {"workshop"};
requiretools[] = {"ItemToolbox","ItemKnife"};
output[] = {};
outputweapons[] = {"Crossbow_DZ"};
input[] = {{"equip_Crossbow_Kit",1},{"equip_crossbow_stock",1}};
};
};
};
|
#pragma once
#include "utils/ptts.hpp"
#include "proto/config_mirror.pb.h"
using namespace std;
namespace pc = proto::config;
namespace nora {
namespace config {
using mirror_ptts = ptts<pc::mirror>;
mirror_ptts& mirror_ptts_instance();
void mirror_ptts_set_funcs();
}
}
|
///////////////////////////////////////////////////////////////////////////////
// bench.cpp - Compare speed of different parsers
//
///////////////////////////////////////////////////////////////////////////////
#define EXPAT 1
#ifdef WIN32 // Because I couldn't compile xerces on Linux
#define XERCES 1
#endif
#ifdef WIN32
#include <windows.h>
#include <io.h>
#else
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/time.h>
#endif
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include "asm-xml.h"
#ifdef EXPAT
#include "expat.h"
#endif
#ifdef XERCES
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/parsers/SAXParser.hpp>
#include <xercesc/framework/MemBufInputSource.hpp>
#include <xercesc/sax/DocumentHandler.hpp>
#include <xercesc/sax/HandlerBase.hpp>
#endif
//[of]:getTicks
long getTicks()
{
#ifdef WIN32
return GetTickCount();
#else
struct timeval tv;
struct timezone tz;
gettimeofday(&tv, &tz);
return tv.tv_sec * 1000 + tv.tv_usec / 1000;
#endif
}
//[cf]
//[of]:readFile
static char* readFile(const char* filename)
{
FILE* f = fopen(filename, "rb");
if( !f )
{
fprintf(stderr, "Can't open file '%s'\n", filename);
return NULL;
}
#ifdef WIN32
HANDLE hFile = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if( hFile == INVALID_HANDLE_VALUE )
return NULL;
unsigned int size = GetFileSize(hFile, NULL);
CloseHandle(hFile);
#else
struct stat st;
#ifdef MACOS
fstat(f->_file, &st);
#else
fstat(f->_fileno, &st);
#endif
unsigned int size = st.st_size;
#endif
char* buf = (char*)malloc(size+1);
size = fread(buf,1, size, f);
fclose(f);
buf[size] = 0;
return buf;
}
//[cf]
//[of]:AsmXml
//[c]
static const int chunkSize = 16*1024*1024; // 16M
//[c]
class BenchApplication
{
public:
AXClassContext classContext;
AXElementClass* docClass;
//[c]
//[of]: initializeAsmXml
int initializeAsmXml(const char* schemaFilename)
{
// Initialize the AsmXml library
ax_initialize((void*)malloc, (void*)free);
// Initialize the class context
int res = ax_initializeClassParser(&classContext);
if( res != 0 )
return 1;
// Read the schema and compile it
char* buf = readFile(schemaFilename);
if( !buf )
return 1;
docClass = ax_classFromString(buf, &classContext);
free(buf);
if( docClass == NULL )
return 1;
return 0;
}
//[cf]
//[of]: releaseAsmXml
void releaseAsmXml()
{
ax_releaseClassParser(&classContext);
}
//[cf]
//[of]: parseAsmXml
//[c]Parses an XML string
//[c]
//[of]: printAsmXmlError
void printAsmXmlError(AXParseContext* context)
{
fprintf(stderr, "Error (%d,%d): %d\n",
context->line,
context->column,
context->errorCode);
}
//[cf]
//[c]
int parseAsmXml(const char* buf)
{
AXParseContext parseContext;
// Initialize the parser
int res = ax_initializeParser(&parseContext, chunkSize);
if( res != 0 )
return 1;
AXElement* root = ax_parse(&parseContext, buf, docClass, 1);
if( root == NULL )
{
printAsmXmlError(&parseContext);
return 1;
}
ax_releaseParser(&parseContext);
return 0;
}
//[cf]
//[c]
};
//[c]
//[cf]
//[of]:Expat
#ifdef EXPAT
void starttag(void *UserData, const XML_Char *name, const XML_Char **attrs)
{
}
void endtag(void *UserData, const XML_Char *name)
{
}
void texttag(void *UserData, const XML_Char *data, int len)
{
}
XML_Parser doc;
static int initializeExpat()
{
doc = XML_ParserCreate(NULL);
XML_SetStartElementHandler(doc,&starttag);
XML_SetEndElementHandler(doc,&endtag);
XML_SetCharacterDataHandler(doc,&texttag);
return 0;
}
static void releaseExpat()
{
XML_ParserFree(doc);
}
static int parseExpat(const char* buf, unsigned int len)
{
XML_Status status = XML_Parse(doc, buf, len, 1);
if( status != XML_STATUS_OK )
return 1;
if( XML_ParserReset(doc, NULL) == XML_FALSE )
return 1;
return 0;
}
#endif
//[cf]
//[of]:Xerces
#ifdef XERCES
#if defined(XERCES_HAS_CPP_NAMESPACE)
XERCES_CPP_NAMESPACE_USE
#endif
class DocHandlers : public HandlerBase
{
public:
void startElement(const XMLCh* const name, AttributeList& attributes);
void endElement(const XMLCh* const name);
void characters(const XMLCh* const text, const unsigned int len);
void resetDocument();
};
void DocHandlers::startElement(const XMLCh* const name, AttributeList& attributes)
{
}
void DocHandlers::endElement(const XMLCh* const name)
{
}
void DocHandlers::characters(const XMLCh* const text, const unsigned int len)
{
}
void DocHandlers::resetDocument()
{
}
SAXParser* parser;
DocHandlers* handler;
void initializeXerces()
{
XMLPlatformUtils::Initialize();
parser = new SAXParser;
handler = new DocHandlers;
parser->setDocumentHandler(handler);
}
void releaseXerces()
{
delete handler;
delete parser;
XMLPlatformUtils::Terminate();
}
void parseXerces(const char* buf, unsigned long len)
{
const char id[5]="ID1\0";
MemBufInputSource* buffer;
buffer = new MemBufInputSource((XMLByte*)buf, len, (const char*)&id);
buffer->setCopyBufToStream(false);
parser->parse(*buffer);
delete buffer;
}
#endif
//[cf]
//[of]:main
int main(int argc, char *argv[])
{
int repeat = atoi(argv[1]);
printf("Iterations = %d \n", repeat);
// Read the file
char* buf = readFile(argv[3]);
if( !buf )
return 1;
unsigned int size = strlen(buf);
BenchApplication bench;
if( bench.initializeAsmXml(argv[2]) )
return 1;
int i = repeat;
long t1 = getTicks();
do
{
if( bench.parseAsmXml(buf) )
return 1;
} while( --i > 0 );
long t2 = getTicks();
printf("AsmXml....: %ld ms\n", t2 - t1);
bench.releaseAsmXml();
#ifdef EXPAT
initializeExpat();
i = repeat;
t1 = getTicks();
do
{
if( parseExpat(buf, size) )
return 1;
} while( --i > 0 );
t2 = getTicks();
printf("Expat.....: %ld ms\n", t2 - t1);
releaseExpat();
#endif
#ifdef XERCES
initializeXerces();
i = repeat;
t1 = getTicks();
do
{
parseXerces(buf, size);
} while( --i > 0 );
t2 = getTicks();
printf("Xerces.....: %ld ms\n", t2 - t1);
releaseXerces();
#endif
return 0;
}
//[cf]
|
#ifndef DUMMYCLASSIFIER_HPP
#define DUMMYCLASSIFIER_HPP
#include "Classifier.hpp"
/**
* @brief Example Classifier class. Extends Classifier class and
* implements basic methods
*/
class DummyClassifier: public Classifier {
public:
DummyClassifier(int, Conf &);
ClassificationResult *Classify(DetectionResult *);
void PlotResults(cv::Mat frame);
};
#endif
|
//
// Created by 钟奇龙 on 2019-05-10.
//
#include <string>
#include <vector>
#include <iostream>
using namespace std;
bool compare(string a,string b){
return a + b < b + a;
}
string lowestString(vector<string> arr){
if(arr.size() == 0) return "";
sort(arr.begin(),arr.end(),compare);
string res = "";
for(int i=0; i<arr.size(); ++i){
res += arr[i];
}
return res;
}
int main(){
vector<string> arr = {"b","ba"};
cout<<lowestString(arr)<<endl;
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 2012 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#ifndef MODULES_OTL_MAP_H
#define MODULES_OTL_MAP_H
#include "modules/otl/pair.h"
#include "modules/otl/src/red_black_tree.h"
/**
* Comparator for OtlMap that takes only the key into consideration.
*
* This comparator ensures uniqueness and proper ordering of keys within the
* map.
*
* @tparam KeyValuePair Pair of key and value types. Key is first, value is
* second.
* @tparam KeyComparator Comparison functor. Takes two arguments of key's type
* and returns a boolean: true if the first argument is to
* be placed at an earlier position than the second in a
* strict weak ordering operation, false otherwise. This
* defaults to the Less comparator which calls the key's
* < operator.
*/
template<typename KeyValuePair, typename KeyComparator>
struct OtlMapComparator
{
OtlMapComparator(const KeyComparator& keyComparator)
: keyComparator(keyComparator) {}
bool operator()(const KeyValuePair& o1, const KeyValuePair& o2) const
{
return keyComparator(o1.first, o2.first);
}
private:
KeyComparator keyComparator;
}; // OtlMapComparator
/**
* Associative map.
*
* Associative mapping of keys to values. Each key must be unique and have
* a defined ordering relation (by default operator <). Guarantees O(log(n))
* time complexity for insertion, removal and search operations.
*
* @tparam Key Type of the key. Must be copy-constructible.
* @tparam Value Type of the value. Must be copy-constructible and
* default-constructible.
* @tparam KeyComparator Comparison functor. Takes two arguments of type
* const Key& and returns a boolean: true if the first
* argument is to be placed at an earlier position than
* the second in a strict weak ordering operation, false
* otherwise. This defaults to the Less comparator which
* calls the key's < operator.
*/
template<typename Key, typename Value, typename KeyComparator = Less<const Key> >
class OtlMap
: public OtlRedBlackTree< OtlPair<const Key, Value>
, OtlMapComparator<OtlPair<const Key, Value>, KeyComparator> >
{
public:
typedef OtlPair<const Key, Value> KeyValuePair;
typedef OtlMapComparator<KeyValuePair, KeyComparator> Comparator;
typedef OtlRedBlackTree<KeyValuePair, Comparator> RBTree;
typedef typename RBTree::Iterator Iterator;
typedef typename RBTree::ConstIterator ConstIterator;
typedef typename RBTree::ReverseIterator ReverseIterator;
typedef typename RBTree::ReverseConstIterator ReverseConstIterator;
OtlMap(const KeyComparator& keyComparator = KeyComparator())
: RBTree(Comparator(keyComparator)) {}
Iterator Find(const Key& key) { return RBTree::Find(fromKey(key)); }
ConstIterator Find(const Key& key) const { return RBTree::Find(fromKey(key)); }
OP_STATUS Insert(const Key& key,
const Value& value,
Iterator* insertionPositionOut = NULL)
{
return RBTree::Insert(OtlMakePair(key, value), insertionPositionOut);
}
size_t Erase(const Key& key) { return RBTree::Erase(fromKey(key)); }
size_t Count(const Key& key) const { return RBTree::Count(fromKey(key)); }
using RBTree::Count;
using RBTree::Insert;
using RBTree::Erase;
private:
static KeyValuePair fromKey(const Key& key)
{
return OtlMakePair(key, Value());
}
}; // OtlMap
#endif // MODULES_OTL_MAP_H
|
//
// Packet.cpp
// SAD
//
// Created by Marquez, Richard A on 4/11/15.
// Copyright (c) 2015 Richard Marquez. All rights reserved.
//
#include "Packet.h"
Packet::Packet(float heading, vector<Range> RFData) {
this->heading = heading;
this->RFData = RFData;
}
|
#include "SLAM.hpp"
using namespace std;
using namespace cv;
Mat imdisp_debug(0,0, CV_32F);
void SLAM::waitForInit() {
do {
mongoose.FetchMongoose();
} while (!mongoose.isInit);
}
matf SLAM::CameraState::getLocalCoordinatesPoint(const matf & p2d) const {
matf out(3,3);
matf a0 = out.col(0), a1 = out.col(1), a2 = out.col(2);
a2 = p2d(0) * KRinv.col(0) + p2d(1) * KRinv.col(1) + KRinv.col(2);
a2 /= norm(a2);
a2.cross(-R.col(1)).copyTo(a0);
a2.cross(a0).copyTo(a1);
return out;
}
matf SLAM::CameraState::getLocalCoordinatesPoint(const Point2f & pt2d) const {
matf out(3,3);
matf a0 = out.col(0), a1 = out.col(1), a2 = out.col(2);
a2 = pt2d.x * KRinv.col(0) + pt2d.y * KRinv.col(1) + KRinv.col(2);
a2 /= norm(a2);
a2.cross(-R.col(1)).copyTo(a0);
a2.cross(a0).copyTo(a1);
return out;
}
matf SLAM::CameraState::getLocalCoordinatesPoint(const Point2i & pt2d) const {
matf out(3,3);
matf a0 = out.col(0), a1 = out.col(1), a2 = out.col(2);
a2 = (float)pt2d.x * KRinv.col(0) + (float)pt2d.y * KRinv.col(1) + KRinv.col(2);
a2 /= norm(a2);
a2.cross(-R.col(1)).copyTo(a0);
a2.cross(a0).copyTo(a1);
return out;
}
|
#pragma once
#include <functional>
#include "integration.hpp"
#include "sparse_vector.hpp"
namespace Time {
template <typename Basis>
class LinearFunctional {
public:
virtual ~LinearFunctional<Basis>() {}
SparseVector<Basis> Eval(const SparseIndices<Basis> &indices) const {
SparseVector<Basis> out;
out.reserve(indices.size());
for (auto phi : indices) out.emplace_back(phi, Eval(phi));
return out;
}
virtual double Eval(Basis *phi) const = 0;
};
template <typename Basis>
class QuadratureFunctional : public LinearFunctional<Basis> {
public:
using LinearFunctional<Basis>::Eval;
QuadratureFunctional(std::function<double(double)> f, size_t order)
: f_(f), order_(order) {}
double Eval(Basis *phi) const {
double cell = 0.0;
for (auto elem : phi->support())
cell += Integrate([&](double t) { return f_(t) * phi->Eval(t); }, *elem,
order_ + 1);
return cell;
}
protected:
std::function<double(double)> f_;
size_t order_;
};
template <typename Basis>
class ZeroEvalFunctional : public LinearFunctional<Basis> {
public:
using LinearFunctional<Basis>::Eval;
double Eval(Basis *phi) const { return phi->Eval(0.0); }
};
}; // namespace Time
|
#include "menu.h"
#include "visitor.h"
#include "sort_by_price_visitor.h"
#include <string>
Menu::Menu(){}
Menu::Menu(std::string newName, std::string newDescription)
:_name(newName), _description(newDescription)
{}
std::string Menu::GetName() {
return _name;
}
std::string Menu::GetDescription() {
return _description;
}
void Menu::SetName(std::string newName) {
_name = newName;
}
void Menu::SetDescription(std::string newDescription) {
_description = newDescription;
}
void Menu::update(std::string itemName){
}
void Menu::accept(Visitor &v){
//do nothing
}
// private:
// std::string _name;
// std::string _description;
|
// Created on: 1993-07-09
// Created by: Isabelle GRIGNON
// Copyright (c) 1993-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _BndLib_Add2dCurve_HeaderFile
#define _BndLib_Add2dCurve_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
class Adaptor2d_Curve2d;
class Bnd_Box2d;
class Geom2d_Curve;
//! Computes the bounding box for a curve in 2d .
//! Functions to add a 2D curve to a bounding box.
//! The 2D curve is defined from a Geom2d curve.
class BndLib_Add2dCurve
{
public:
DEFINE_STANDARD_ALLOC
//! Adds to the bounding box B the curve C
//! B is then enlarged by the tolerance value Tol.
//! Note: depending on the type of curve, one of the following
//! representations of the curve C is used to include it in the bounding box B:
//! - an exact representation if C is built from a line, a circle or a conic curve,
//! - the poles of the curve if C is built from a Bezier curve or a BSpline curve,
//! - if not, the points of an approximation of the curve C.
//! Warning
//! C is an adapted curve, that is, an object which is an interface between:
//! - the services provided by a 2D curve from the package Geom2d
//! - and those required of the curve by the computation algorithm.
//! The adapted curve is created in the following way:
//! Handle(Geom2d_Curve) mycurve = ...
//! ;
//! Geom2dAdaptor_Curve C(mycurve);
//! The bounding box B is then enlarged by adding it:
//! Bnd_Box2d B;
//! // ...
//! Standard_Real Tol = ... ;
//! Add2dCurve::Add ( C, Tol, B );
//! Exceptions
//! Standard_Failure if the curve is built from:
//! - a Geom_Line, or
//! - a Geom_Parabola, or
//! - a Geom_Hyperbola,
//! and P1 and P2 are either two negative infinite real
//! numbers, or two positive infinite real numbers.
Standard_EXPORT static void Add (const Adaptor2d_Curve2d& C, const Standard_Real Tol, Bnd_Box2d& B);
//! Adds to the bounding box Bthe arc of the curve C limited by the two parameter
//! values P1 and P2.
//! B is then enlarged by the tolerance value Tol.
//! Note: depending on the type of curve, one of the following
//! representations of the curve C is used to include it in the bounding box B:
//! - an exact representation if C is built from a line, a circle or a conic curve,
//! - the poles of the curve if C is built from a Bezier curve or a BSpline curve,
//! - if not, the points of an approximation of the curve C.
//! Warning
//! C is an adapted curve, that is, an object which is an interface between:
//! - the services provided by a 2D curve from the package Geom2d
//! - and those required of the curve by the computation algorithm.
//! The adapted curve is created in the following way:
//! Handle(Geom2d_Curve) mycurve = ...
//! ;
//! Geom2dAdaptor_Curve C(mycurve);
//! The bounding box B is then enlarged by adding it:
//! Bnd_Box2d B;
//! // ...
//! Standard_Real Tol = ... ;
//! Add2dCurve::Add ( C, Tol, B );
//! Exceptions
//! Standard_Failure if the curve is built from:
//! - a Geom_Line, or
//! - a Geom_Parabola, or
//! - a Geom_Hyperbola,
//! and P1 and P2 are either two negative infinite real
//! numbers, or two positive infinite real numbers.
Standard_EXPORT static void Add (const Adaptor2d_Curve2d& C, const Standard_Real U1, const Standard_Real U2, const Standard_Real Tol, Bnd_Box2d& B);
//! Adds to the bounding box B the curve C
//! B is then enlarged by the tolerance value Tol.
//! Note: depending on the type of curve, one of the following
//! representations of the curve C is used to include it in the bounding box B:
//! - an exact representation if C is built from a line, a circle or a conic curve,
//! - the poles of the curve if C is built from a Bezier curve or a BSpline curve,
//! - if not, the points of an approximation of the curve C.
Standard_EXPORT static void Add (const Handle(Geom2d_Curve)& C, const Standard_Real Tol, Bnd_Box2d& Box);
//! Adds to the bounding box B the part of curve C
//! B is then enlarged by the tolerance value Tol.
//! U1, U2 - the parametric range to compute the bounding box;
//! Note: depending on the type of curve, one of the following
//! representations of the curve C is used to include it in the bounding box B:
//! - an exact representation if C is built from a line, a circle or a conic curve,
//! - the poles of the curve if C is built from a Bezier curve or a BSpline curve,
//! - if not, the points of an approximation of the curve C.
Standard_EXPORT static void Add (const Handle(Geom2d_Curve)& C, const Standard_Real U1, const Standard_Real U2, const Standard_Real Tol, Bnd_Box2d& B);
//! Adds to the bounding box B the part of curve C
//! B is then enlarged by the tolerance value Tol.
//! U1, U2 - the parametric range to compute the bounding box;
//! Note: depending on the type of curve, one of the following
//! algorithms is used to include it in the bounding box B:
//! - an exact analytical if C is built from a line, a circle or a conic curve,
//! - numerical calculation of bounding box sizes, based on minimization algorithm, for other types of curve
//! If Tol = < Precision::PConfusion(), Precision::PConfusion is used as tolerance for calculation
Standard_EXPORT static void AddOptimal(const Handle(Geom2d_Curve)& C,
const Standard_Real U1,
const Standard_Real U2,
const Standard_Real Tol,
Bnd_Box2d& B);
protected:
private:
};
#endif // _BndLib_Add2dCurve_HeaderFile
|
/**
Copyright (c) 2015 Eric Bruneton
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "atmosphere/color.h"
#include "atmosphere/atmosphere.h"
#include "math/matrix.h"
using dimensional::Matrix3;
using dimensional::Vector3;
using dimensional::Scalar;
using dimensional::vec3;
namespace {
// The 3 sample wavelengths used when simulating RGB rendering. All the models
// are run spectrally, but we can simulate RGB rendering by simply dropping the
// values at all wavelengths but 3.
constexpr Wavelength lambda_r = 680.0 * nm;
constexpr Wavelength lambda_g = 550.0 * nm;
constexpr Wavelength lambda_b = 440.0 * nm;
} // namespace
Color GetSrgbColorNaive(const RadianceSpectrum& spectrum) {
// Extract 3 samples of the given spectrum, to be used as RGB components. Note
// that 'spectrum' is proportional to the input solar spectrum, whereas the
// original O'Neal and Bruneton model implementations implicitly use a
// wavelength independent solar spectrum. To simulate this, we need to cancel
// the effect of the input solar spectrum when extracting the RGB values:
static const RadianceSpectrum solar_spectrum = SolarSpectrum() * (1.0 / sr);
Number r = spectrum(lambda_r) / solar_spectrum(lambda_r);
Number g = spectrum(lambda_g) / solar_spectrum(lambda_g);
Number b = spectrum(lambda_b) / solar_spectrum(lambda_b);
// Scale the resulting color with a constant factor such that the result can
// be compared quantitatively with the correct way of converting 'spectrum' to
// a color, as in GetSrgbColor().
static const auto k =
dot(GetSrgbColor(solar_spectrum), vec3(1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0));
return Color(k * r, k * g, k * b);
}
Color GetSrgbColorFrom3SpectrumSamples(const RadianceSpectrum& spectrum) {
// Compute the normalization vector to properly convert 3 spectrum samples to
// a perceptual, linear sRGB color.
static const auto k = []() {
WavelengthFunction<0, -3, 0, 0, 0> f;
for (unsigned int i = 0; i < f.size(); ++i) {
Wavelength lambda = f.GetSample(i);
f[i] = 1.0 / (lambda * lambda * lambda);
}
const auto RGB = XYZ_to_sRGB * Vector3<Scalar<-2, -3, 0, 1, 0>>(
Integral(cie_x_bar_function() * SolarSpectrum() * f),
Integral(cie_y_bar_function() * SolarSpectrum() * f),
Integral(cie_z_bar_function() * SolarSpectrum() * f)) *
MaxLuminousEfficacy;
return Vector3<Scalar<0, 1, 0, -1, 1>>(
RGB.x / SolarSpectrum()(lambda_r) * (lambda_r * lambda_r * lambda_r),
RGB.y / SolarSpectrum()(lambda_g) * (lambda_g * lambda_g * lambda_g),
RGB.z / SolarSpectrum()(lambda_b) * (lambda_b * lambda_b * lambda_b));
}();
return Color(k.x * spectrum(lambda_r), k.y * spectrum(lambda_g),
k.z * spectrum(lambda_b));
}
// Returns an approximate version of the given spectrum, reconstructed from 3 of
// its samples with the CIE S0, S1 and S2 components.
RadianceSpectrum GetApproximateSpectrumFrom3SpectrumSamples(
const RadianceSpectrum& spectrum) {
static const Matrix3<Number> sRGB_to_XYZ = inverse(XYZ_to_sRGB);
Color XYZ = sRGB_to_XYZ * GetSrgbColorFrom3SpectrumSamples(spectrum);
Number x = XYZ.x / (XYZ.x + XYZ.y + XYZ.z);
Number y = XYZ.y / (XYZ.x + XYZ.y + XYZ.z);
Radiance Y = XYZ.y / MaxLuminousEfficacy;
Number M1 = (-1.3515 - 1.7703 * x + 5.9114 * y) /
(0.0241 + 0.2562 * x - 0.7341 * y);
Number M2 = (0.0300 - 31.4424 * x + 30.0717 * y) /
(0.0241 + 0.2562 * x - 0.7341 * y);
DimensionlessSpectrum S =
S0_function() + S1_function() * M1 + S2_function() * M2;
static const auto Y_S0 = Integral(S0_function() * cie_y_bar_function());
static const auto Y_S1 = Integral(S1_function() * cie_y_bar_function());
static const auto Y_S2 = Integral(S2_function() * cie_y_bar_function());
SpectralRadiance k = Y / (Y_S0 + Y_S1 * M1 + Y_S2 * M2);
return S * k;
}
Color WhiteBalanceNaive(const Color& c) {
const Color sun_color = GetSrgbColor(SolarSpectrum() * (1.0 / sr));
const Luminance sun_luminance =
dot(sun_color, vec3(1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0));
const auto white_point = sun_color / sun_luminance;
return Color(c.x / white_point.x, c.y / white_point.y, c.z / white_point.z);
}
|
/*
* video.cpp
*
* Created on: Apr 14, 2012
* Author: edge87
*/
|
/*
* loadsave.h
*/
#ifndef LOADSAVE_H
#define LOADSAVE_H
#include <QFile>
#include <QTextStream>
using namespace std;
class LoadSave
{
static LoadSave* loadsave;
LoadSave() {}
public:
static LoadSave& instance();
// loads a save state and configures objects
void load(QString filename);
// configures objects from a file <in>
// called at beginning of series of objects in a save file
void loadObjects(QTextStream& in, size_t &num);
// reads object data and saves a save state file
void save(QString filename);
static void teardown();
};
#endif // LOADSAVE_H
|
#include <iostream>
#include <vector>
using namespace std;
//暴力法
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
int i, j, k, row, col;
//基本思想:两次循环对9*9的数独每一个数字遍历一遍,然后比较该数字在每一行、每一列、每一宫是否有重复数字,有则返回false
for (i = 0; i < 9; i++)
{
for (j = 0; j < 9; j++)
{
if (board[i][j] != '.')
{
if (board[i][j] > '9' || board[i][j] < '1')
return false;
for (k = 0; k < 9; k++)
{
//对数字board[i][j]所在同一行判断是否有重复
if (k != j && board[i][k] == board[i][j])
return false;
//对数字board[i][j]所在同一列判断是否有重复
if (k != i && board[k][j] == board[i][j])
return false;
}
//对数字board[i][j]所在同一宫判断是否有重复
for (row = i / 3 * 3; row < i / 3 * 3 + 3; row++)
{
for (col = j / 3 * 3; col < j / 3 * 3 + 3; col++)
{
if (row != i && col != j && board[i][j] == board[row][col])
return false;
}
}
}
}
}
return true;
}
};
//HashMap法
class Solution1 {
public:
bool isValidSudoku(vector<vector<char>>& board) {
int i, j, k;
//数独必须每一行只能出现一次、每一列只能出现一次、每一个分隔的 3x3 宫内只能出现一次数字1-9
int row[9][10] = { 0 }; //row[i][curent]表示第i行出现数字curent,curent从1-9所以下标到10
int col[9][10] = { 0 }; //col[j][curent]表示第j列出现数字curent
int box[9][10] = { 0 }; //box[i/3*3+j/3][curent]表示第i/3*3+j/3宫出现数字curent
for (i = 0; i < 9; i++)
{
for (j = 0; j < 9; j++)
{
if (board[i][j] != '.')
{
if (board[i][j] > '9' || board[i][j] < '1')
return false;
int curent = board[i][j] - '0';
//如果之前已经出现了数字curent,则返回false
if (row[i][curent] == 1)
return false;
if (col[j][curent] == 1)
return false;
if (box[i/3*3+j/3][curent] == 1)
return false;
//之前没有出现数字curent,在每一行、每一列、每一宫标记数字curent出现
row[i][curent] = 1;
col[j][curent] = 1;
box[i / 3 * 3 + j / 3][curent] = 1;
}
}
}
return true;
}
};
int main()
{
Solution solute;
vector<vector<char>> board = {
{ '5','3','.','.','7','.','.','.','.' },
{ '6','.','.','1','9','5','.','.','.' },
{ '.','9','8','.','.','.','.','6','.' },
{ '8','.','.','.','6','.','.','.','3' },
{ '4','.','.','8','.','3','.','.','1' },
{ '7','.','.','.','2','.','.','.','6' },
{ '.','6','.','.','.','.','2','8','.' },
{ '.','.','.','4','1','9','.','.','5' },
{ '.','.','.','.','8','.','.','7','9' } };
cout << solute.isValidSudoku(board) << endl;
return 0;
}
|
#include "add_observation_noise.h"
#include "linalg.h"
#include <cstdlib>
#include <cmath>
/*****************************************************************************
* IMPLEMENTATION STATUS
* Done: Base implementation, unit test
* ToDo: Start optimizing
*****************************************************************************/
//! Adds random measurement noise. We assume R is diagnoal matrix.
//! TOCHECK: vector<Vector2d> z -> Storage choice for z, ROW-WISE for now
void add_observation_noise(Vector2d z[], const size_t zlen, cMatrix2d R, const int addnoise) {
add_observation_noise_base(z, zlen, R, addnoise);
}
double add_observation_noise_flops(Vector2d z[], const size_t zlen, cMatrix2d R, const int addnoise) {
return add_observation_noise_base_flops(z, zlen, R, addnoise);
}
double add_observation_noise_memory(Vector2d z[], const size_t zlen, cMatrix2d R, const int addnoise) {
return add_observation_noise_base_memory(z, zlen, R, addnoise);
}
/*****************************************************************************
* PERFORMANCE STATUS
* Work: 2*zlen rand + 2 sqrt + 2*zlen adds + 2*zlen mults = 6*zlen + 2
* Memory moved: TBD
* Cycles: 350
* Performance: TBD
* Optimal: TBD
* Status: TBD
*****************************************************************************/
void add_observation_noise_base(Vector2d z[], const size_t zlen, cMatrix2d R, const int addnoise)
{
if ( addnoise == 1 && zlen > 0 ){
double *randM1 = (double*)malloc(zlen*sizeof(double));
double *randM2 = (double*)malloc(zlen*sizeof(double));
fill_rand(randM1, zlen, -1.0, 1.0);
fill_rand(randM2, zlen, -1.0, 1.0);
const double sqrtR00 = sqrt(R[0]);
const double sqrtR11 = sqrt(R[3]);
for (int i = 0; i < zlen; i++) {
z[i][0] += randM1[i]*sqrtR00; // z[i][0] = z[i][0] + randM1[i]*sqrtR00;
z[i][1] += randM2[i]*sqrtR11; // z[i][1] = z[i][1] + randM2[i]*sqrtR11;
}
free(randM1);
free(randM2);
}
}
double add_observation_noise_base_flops(Vector2d z[], const size_t zlen, cMatrix2d R, const int addnoise) {
if( addnoise == 1 && zlen > 0 ) {
double* _m1;
return 2*fill_rand_flops(_m1, zlen, -1, 1) + 2 * tp.sqrt + zlen * 2 * ( tp.mul + tp.add );
}
else return 0;
}
double add_observation_noise_base_memory(Vector2d z[], const size_t zlen, cMatrix2d R, const int addnoise) {
if( addnoise == 1 && zlen > 0 ) {
double* _m1;
return 2*fill_rand_memory(_m1, zlen, -1, 1) + 2 + zlen * (2 + 2*2);
}
else return 0;
}
|
#include "stdafx.h"
#include "UIAnimator.h"
void UIAnimator::OnDestroy()
{
for (auto sp : m_Sprits)
DeleteGO(sp);
for (auto o : m_anims)
delete o;
}
void UIAnimator::loadUI(const wchar_t* path, std::function<SpriteRender* (sUI* ui,bool &isfook)> func)
{
FILE* file = nullptr;
_wfopen_s(&file, path, L"rb");
char uip[3] = { 0 };
fread(&uip, sizeof(uip), 1, file);
int cnt = 0;
fread(&cnt, sizeof(int), 1, file);
std::vector<sUI*> UIs;
for (int i = 0; i < cnt; i++)
{
sUI* ui = new sUI;
int len = 0;
fread(&len, sizeof(int), 1, file);
char* name = new char[len];
fread(name, len,1, file);
CVector2 dim = { 0,0 };
fread(&dim, sizeof(dim), 1, file);
CVector3 pos = { 0,0,0 };
fread(&pos, sizeof(pos), 1, file);
CVector3 sca = { 0,0,0 };
fread(&sca, sizeof(sca), 1, file);
CQuaternion rot = { 0,0,0,0 };
fread(&rot, sizeof(rot), 1, file);
wchar_t boneName[256];
mbstowcs(boneName, name, 256);
wcscpy(ui->name, boneName);
ui->dimensions = dim;
ui->pos = pos;
ui->scale = sca;
ui->rot = rot;
UIs.push_back(ui);
delete[] name;
}
fclose(file);
for (auto UI : UIs)
{
bool isfook = false;
int prio = 0;
SpriteRender* sp = func(UI, isfook);
if (!isfook)
{
std::wstring path = L"Assets/sprite/";
path += UI->name;
path += L".dds";
sp->Init(path.c_str(), UI->dimensions.x, UI->dimensions.y);
UI->pos.z = 0;
sp->SetPosition(UI->pos);
sp->SetScale(UI->scale);
sp->SetRotation(UI->rot);
}
m_Sprits.push_back(sp);
delete UI;
}
}
void UIAnimator::playAnim(const wchar_t* path)
{
for (auto an : m_anims)
{
delete(an);
}
m_anims.clear();
m_anims.shrink_to_fit();
FILE* file = nullptr;
_wfopen_s(&file, path, L"rb");
char uip[3] = { 0 };
fread(&uip, sizeof(uip), 1, file);
int cnt = 0;
fread(&cnt, sizeof(int), 1, file);
m_frameCount = cnt / m_Sprits.size();
for (int j = 0; j < m_Sprits.size(); j++)
{
UIAnim* ua = new UIAnim;
m_anims.push_back(ua);
}
for (int i = 0; i < cnt/ m_Sprits.size(); i++)
{
float time = 0;
fread(&time, sizeof(time), 1, file);
for (int j = 0; j < m_Sprits.size(); j++)
{
int num = 0;
fread(&num, sizeof(num), 1, file);
CVector3 pos = { 0,0,0 };
fread(&pos, sizeof(pos), 1, file);
CVector3 sca = { 0,0,0 };
fread(&sca, sizeof(sca), 1, file);
CQuaternion rot = { 0,0,0,0 };
fread(&rot, sizeof(rot), 1, file);
UIkeyFrame key;
key.num = j;
key.pos = pos;
key.scale = sca;
key.rot = rot;
m_anims[j]->frames.push_back(key);
}
}
m_isAnimation = true;
}
void UIAnimator::Update()
{
if (!m_isAnimation)
return;
int spsize = m_Sprits.size();
if(m_frame < m_frameCount)
{
m_frame += IGameTime().GetFrameDeltaTime() * m_speed;
if (m_frame >= m_frameCount)
{
m_frame = 0;
if(!m_isLoop)
m_isAnimation = false;
return;
}
for (int i = 0; i < spsize; i++)
{
CVector3 pos = m_anims[i]->frames[(int)m_frame].pos + m_pos;
pos.z = m_Sprits[i]->GetPosition().z;
m_Sprits[i]->SetPosition(pos);
m_Sprits[i]->SetScale(m_anims[i]->frames[(int)m_frame].scale);
m_Sprits[i]->SetRotation(m_anims[i]->frames[(int)m_frame].rot);
}
}
}
|
//
// Player.h
// GLWF
//
// Created by Rodrigo Castro Ramos on 1/29/19.
// Copyright © 2019 Rodrigo Castro Ramos. All rights reserved.
//
#ifndef Player_h
#define Player_h
#include <vector>
// GL Includes
#define GLEW_STATIC
#include <GL/glew.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include "Knife.h"
using namespace std;
// Defines several possible options for camera movement. Used as abstraction to stay away from window-system specific input methods
enum Player_Movement
{
IZQUIERDA,
SALTO,
DERECHA,
PROTECCION
};
class Player {
public:
glm::vec3 playerPosition;
GLfloat movementSpeed;
GLfloat movementJump;
glm::vec3 lefth;
glm::vec3 up;
glm::vec3 right;
glm::vec3 jump;
glm::vec3 front;
bool jumpPresed;
Player(){
playerPosition = glm::vec3 (0.0f, 0.0f, 0.0f);
lefth = glm::vec3 (-1.0f, 0.0f, 0.0f);
right = glm::vec3 ( 1.0f, 0.0f, 0.0f );
jump = glm::vec3 ( 0.0f, 0.05f, 0.0f );
movementSpeed = 6.0f;
movementJump = 4.0f;
jumpPresed = false;
front = glm::vec3 ( 0.0f, 0.0f, -1.0f );
}
void DropKnife(GLint modelLoc, GLint viewLoc, GLint projLoc, Shader shader, Model ourModel, glm::mat4 view, glm::mat4 projection, glm::mat4 model, GLfloat deltaTime){
Knife knife;
knife.movement(modelLoc, viewLoc, projLoc, shader, ourModel, view, projection, model, deltaTime);
}
void ProcessKeyboard( Player_Movement direction, GLfloat deltaTime )
{
GLfloat velocity = this->movementSpeed * deltaTime;
GLfloat velocityJump = this->movementJump * deltaTime;
if ( direction == DERECHA )
{
this->playerPosition += this->right * velocity;
}
if ( direction == IZQUIERDA )
{
this->playerPosition += this->lefth * velocity;
}
if ( direction == SALTO && playerPosition.y == 0.0f )
{
// jumpPresed = true;
cout<< "entre al loop"<<endl;
movementJump = 4.0f;
jumpPresed = true;
jump = glm::vec3 (0.0f,1.0f,0.0f);
}
// cout<<this->playerPosition.y<< " ";
if ( direction == PROTECCION )
{
cout<<"me tengo que proteger"<<endl;
cout<< jumpPresed;
}
}
void jumper( GLfloat deltaTime ){
GLfloat velocityJump = this->movementJump * deltaTime;
if ( jumpPresed == true ) {
if ( this->playerPosition.y <= 3.0f && jumpPresed == true ){
this->playerPosition += this->jump * velocityJump;
if (this->playerPosition.y > 2.6f ){
jumpPresed = false;
}
}
}
if ( jumpPresed == false ) {
if ( this->playerPosition.y != 0.0f && jumpPresed == false ){
this->playerPosition -= this->jump * velocityJump;
if ( this->playerPosition.y <= 0.0f){
jumpPresed = true;
this->playerPosition.y = 0.0f;
jump = glm::vec3 (0.0f,0.0f,0.0f);
}
}
}
}
glm::vec3 GetPosition( )
{
return this->playerPosition;
}
glm::vec3 GetFront( )
{
return this->front;
}
};
#endif /* Player_h */
|
//
// Created by Lee on 2019-04-23.
//
#include "ImageFileManager.h"
#include <QFileInfo>
#include <QFileDialog>
#include <QDir>
#include <QDebug>
#include <QProcess>
Photo ImageFileManager::uploadPhotoFileToGithub(QWidget * parent) {
QString fileName = QFileDialog::getOpenFileName(parent, ("Open File"),
QDir::homePath(),
("All files (*.*)"));
qDebug() << fileName;
if (fileName == "") {
Photo tmp;
tmp.setId(-1);
return tmp;
}
QFileInfo fileInfo(fileName);
QString mimeType = fileInfo.suffix();
QString name = fileInfo.fileName();
QString node = "node";
QStringList arguments;
arguments << "../github-uploader-binary/lib/cli.js" << fileName;
auto *process = new QProcess(parent);
process->start(node, arguments);
process->waitForFinished();
QByteArray url = process->readAll();
QString uri(url);
Photo photo(0, uri, mimeType, name);
return photo;
}
|
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <memory.h>
#include <math.h>
#include <string>
#include <string.h>
#include <queue>
#include <vector>
#include <set>
#include <deque>
#include <map>
#include <functional>
#include <numeric>
typedef long double LD;
typedef long long LL;
typedef unsigned long long ULL;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
#define MOD 7340033
int g[4300][4300];
int n, k;
int main() {
// freopen(".in", "r", stdin);
// freopen(".out", "w", stdout);
cin >> n >> k;
if (k > n) {
cout << 0 << endl;
return 0;
}
g[0][0] = 1;
for (int j = 1; j <= n; ++j) {
g[0][j] = 0;
for (int i = 1; i <= n; ++i) {
g[i][j] = (g[i - 1][j] + g[i - 1][j - 1]) % MOD;
}
}
int ans = 0;
for (int st = 1; st * k <= n; ++st) {
ans = (ans + g[n][st * k]) % MOD;
}
cout << ans << endl;
return 0;
}
|
#ifndef CDT_CORE_STRINGUTILS_HPP
#define CDT_CORE_STRINGUTILS_HPP
#include <string>
#include <vector>
#include "includes/libexport.h"
namespace cdt {
class CDT_API StringUtils {
public:
static std::string padLeft(const std::string& str, const char c, size_t length);
static std::string padRight(const std::string& str, const char c, size_t length);
static std::string center(const std::string& str, const char c, size_t length);
static std::vector<std::string> split(const std::string &str, const std::string& delim);
static std::string join(const std::vector<std::string> &list, const std::string& glue);
static bool startsWith(const std::string& str, const std::string& needle);
static bool endsWith(const std::string& str, const std::string& needle);
static bool contains(const std::string& str, const std::string& needle);
static std::string makeString(const std::string& format, ...);
private:
static std::string getPadding(const std::string& str, const char c, size_t length);
StringUtils() {};
~StringUtils() {};
StringUtils(const StringUtils& other);
StringUtils& operator=(const StringUtils& other);
};
} // cdt
#endif // CDT_CORE_STRINGUTILS_HPP
|
#pragma once
#include "utils.hpp"
#include "utils/ptts.hpp"
#include "proto/config_relation.pb.h"
using namespace std;
namespace pc = proto::config;
namespace nora {
namespace config {
using relation_logic_ptts = ptts<pc::relation_logic>;
relation_logic_ptts& relation_logic_ptts_instance();
void relation_logic_ptts_set_funcs();
using relation_suggestion_ptts = ptts<pc::relation_suggestion>;
relation_suggestion_ptts& relation_suggestion_ptts_instance();
void relation_suggestion_ptts_set_funcs();
using relation_gift_ptts = ptts<pc::relation_gift>;
relation_gift_ptts& relation_gift_ptts_instance();
void relation_gift_ptts_set_funcs();
}
}
|
#include "fixedp.h"
#include "Globals.h"
#include "rrrandom.h"
#include "rrrus_function.h"
#include "rrrus_hsv2rgb.h"
#include "Stripes.h"
// 0 bits int, 8 bits fraction.
typedef fixedp<false, 0, 8> ufixdot8;
void Stripes::setup() {
// Start at 0 speed, hold for 5 seconds.
_speedAnim.animate(0, 0, 5_s);
_speedAnim.setOnIdle([](Animatorf &anim) {
anim.animate(randfRange(-15, 15),
randiRange(0.5_s, 5_s),
randiRange(1_s, 30_s));
});
_widthAnim.animate(3, 0, 10_s);
_widthAnim.setOnIdle([](Animatorf &anim) {
// Have to sqrt the min range since so that squaring it later gives
// the right min range val.
constexpr float minRange = sqrtf(4.0f / NUM_LEDS);
float width = randfRange(minRange, 1);
width = width * width;
anim.animate(width * NUM_LEDS,
randiRange(5_s, 10_s),
randiRange(10_s, 20_s));
});
_crossoverAnim.animate(2, 0, 15_s);
_crossoverAnim.setOnIdle([](Animatorf &anim) {
// Min crossover of 2 leds gives enough blur to hide the discrete lights.
anim.animate(randfRange(2, NUM_LEDS/2),
randiRange(1_s, 5_s),
randiRange(10_s, 30_s));
});
_color1.set(CRGB::Black);
_color2.set(CRGB::Black);
AnimatorRGB::OnIdle colorOnIdle = [](AnimatorRGB &anim) {
CRGB color = CRGB::Black;
// 80% of the time, make a color. 20% of the time, use black.
if (randi(100) > 20) {
ufixdot8 s = (ufixdot8::ValType)randi(255);
// Cube s to make it tend more towards 0, which is then (1-s),
// so that we end up with more saturation than not.
s = s * s * s;
rrrus::hsv2rgb(CHSV(randi(255), (255 - s.fract()), 255), color);
}
anim.animate(color,
randiRange(1_s, 10_s),
randiRange(10_s, 30_s));
};
_color1.setOnIdle(colorOnIdle);
_color2.setOnIdle(colorOnIdle);
}
void Stripes::render() {
const uint32_t now = millis();
const float deltaTime = (float)(now - _lastTime)/1000.0f;
_lastTime = now;
const float stripeWidth = _widthAnim.value();
_fpos += (_speedAnim.value() * deltaTime);
if (stripeWidth > 0) {
while (_fpos > stripeWidth) {
_fpos -= stripeWidth*2;
}
while (_fpos < -stripeWidth) {
_fpos += stripeWidth*2;
}
}
const float halfWidth = stripeWidth/2;
const float crossover = min(_crossoverAnim.value(), halfWidth);
const CRGB c1 = _color1.value();
const CRGB c2 = _color2.value();
constexpr auto midStrip = NUM_LEDS / 2;
for (int i=0; i<NUM_LEDS; i++) {
const float ploc = fabs(fmod(_fpos + i - midStrip + stripeWidth*1000.5, stripeWidth*2) - stripeWidth) - halfWidth;
const float interp = min(0.5, max(-0.5, ploc / crossover)) + 0.5;
gLeds[i] = gGamma.apply( c1.lerp8(c2, 255 * interp));
}
}
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "SLRangedBasicProjectile.h"
#include "SMITElabs/Public/SLGod.h"
// Sets default values
ASLRangedBasicProjectile::ASLRangedBasicProjectile()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
SceneComponent = CreateDefaultSubobject<USceneComponent>(TEXT("SceneComponent"));
RootComponent = SceneComponent;
StaticMeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("StaticMeshComponent"));
StaticMeshComponent->SetupAttachment(RootComponent);
CleaveCollisionComponent = CreateDefaultSubobject<USphereComponent>(TEXT("CleaveCollisionComponent"));
CleaveCollisionComponent->SetupAttachment(RootComponent);
WallCollisionComponent = CreateDefaultSubobject<UBoxComponent>(TEXT("WallCollisionComponent"));
WallCollisionComponent->SetupAttachment(RootComponent);
ArrowComponent = CreateDefaultSubobject<UArrowComponent>(TEXT("ArrowComponent"));
ArrowComponent->SetupAttachment(RootComponent);
StaticMeshComponent->OnComponentBeginOverlap.AddDynamic(this, &ASLRangedBasicProjectile::OnOverlapBegin);
WallCollisionComponent->OnComponentBeginOverlap.AddDynamic(this, &ASLRangedBasicProjectile::OnWallHit);
}
float ASLRangedBasicProjectile::GetProjectileLength() { return ProjectileLength; }
// Called when the game starts or when spawned
void ASLRangedBasicProjectile::BeginPlay()
{
Super::BeginPlay();
SetActorLocation((GetActorLocation() + SceneComponent->GetForwardVector() * BasicAttackDisjoints[0] + SceneComponent->GetRightVector() * BasicAttackDisjoints[1]));
StartingLocation = GetActorLocation();
}
void ASLRangedBasicProjectile::SetBasicAttackDisjoints(TArray<float> Val)
{
BasicAttackDisjoints[0] = Val[0];
BasicAttackDisjoints[1] = Val[1];
}
void ASLRangedBasicProjectile::SetOrigin(ISLDangerous* Val) { Origin = Val; }
void ASLRangedBasicProjectile::SetDamageProgressionMultiplier(float Val) { DamageProgressionMultiplier = Val; }
void ASLRangedBasicProjectile::SetProjectileSpeed(float Val) { ProjectileSpeed = Val; }
void ASLRangedBasicProjectile::SetProjectileRange(float Val) { ProjectileRange = Val; }
void ASLRangedBasicProjectile::SetProjectileSize(float Val) { ProjectileSize = Val; StaticMeshComponent->SetRelativeScale3D(FVector(ProjectileHeight, ProjectileSize, ProjectileLength)); WallCollisionComponent->SetBoxExtent(FVector(ProjectileLength * 50, 25, 25)); }
void ASLRangedBasicProjectile::SetCleave(bool Val) { bCleave = Val; }
void ASLRangedBasicProjectile::SetCleaveDamage(float Val) { CleaveDamage = Val; }
void ASLRangedBasicProjectile::SetCleaveRange(float Val) { CleaveRange = Val; CleaveCollisionComponent->SetSphereRadius(CleaveRange * 100); }
void ASLRangedBasicProjectile::OnOverlapBegin(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& Hit)
{
// TODO Clean up this ugly if/else if
if (!OtherActor->Implements<USLVulnerable>() || Cast<ASLRangedBasicProjectile>(OtherActor)) return;
else if (OtherActor != Cast<AActor>(Origin) && Cast<ISLIdentifiable>(Origin)->GetBIsOrder() != Cast<ISLIdentifiable>(OtherActor)->GetBIsOrder())
{
ISLVulnerable* DamagedTarget = Cast<ISLVulnerable>(OtherActor);
if (Origin->GetIsPhysicalDamage())
{
float TotalProtections = (DamagedTarget->GetPhysicalProtections()) * (1 - Origin->GetPercentagePhysicalPenetration()) - Origin->GetFlatPhysicalPenetration() > 0 ? (DamagedTarget->GetPhysicalProtections()) * (1 - Origin->GetPercentagePhysicalPenetration()) - Origin->GetFlatPhysicalPenetration() : 0;
DamagedTarget->TakeHealthDamage(((Origin->GetCurrentBasicAttackDamage() + Origin->GetPhysicalPower() * Origin->GetBasicAttackPowerScaling()) * DamageProgressionMultiplier) * (100 / (TotalProtections + 100)), Origin);
}
else
{
float TotalProtections = (DamagedTarget->GetMagicalProtections()) * (1 - Origin->GetPercentageMagicalPenetration()) - Origin->GetFlatMagicalPenetration() > 0 ? (DamagedTarget->GetMagicalProtections()) * (1 - Origin->GetPercentageMagicalPenetration()) - Origin->GetFlatMagicalPenetration() : 0;
DamagedTarget->TakeHealthDamage(((Origin->GetCurrentBasicAttackDamage() + Origin->GetMagicalPower() * Origin->GetBasicAttackPowerScaling()) * DamageProgressionMultiplier) * (100 / (TotalProtections + 100)), Origin);
}
TArray<ISLVulnerable*> Targets{ DamagedTarget };
if (bCleave)
{
CleaveCollisionComponent->SetWorldLocation(OtherActor->GetActorLocation());
TArray<AActor*> OverlappingActors;
CleaveCollisionComponent->GetOverlappingActors(OverlappingActors);
for (AActor* var : OverlappingActors)
{
if (Cast<ISLVulnerable>(var) && var != OtherActor && var != Cast<AActor>(Origin))
{
FHitResult HitResult;
if (!GetWorld()->LineTraceSingleByChannel(HitResult, OtherActor->GetActorLocation(), var->GetActorLocation(), ECollisionChannel::ECC_GameTraceChannel1))
{
DamagedTarget = Cast<ISLVulnerable>(var);
if (Origin->GetIsPhysicalDamage())
{
float TotalProtections = (DamagedTarget->GetPhysicalProtections()) * (1 - Origin->GetPercentagePhysicalPenetration()) - Origin->GetFlatPhysicalPenetration() > 0 ? (DamagedTarget->GetPhysicalProtections()) * (1 - Origin->GetPercentagePhysicalPenetration()) - Origin->GetFlatPhysicalPenetration() : 0;
DamagedTarget->TakeHealthDamage(((Origin->GetCurrentBasicAttackDamage() + Origin->GetPhysicalPower() * Origin->GetBasicAttackPowerScaling()) * DamageProgressionMultiplier * CleaveDamage) * (100 / (TotalProtections + 100)), Origin);
}
else
{
float TotalProtections = (DamagedTarget->GetMagicalProtections()) * (1 - Origin->GetPercentageMagicalPenetration()) - Origin->GetFlatMagicalPenetration() > 0 ? (DamagedTarget->GetMagicalProtections()) * (1 - Origin->GetPercentageMagicalPenetration()) - Origin->GetFlatMagicalPenetration() : 0;
DamagedTarget->TakeHealthDamage(((Origin->GetCurrentBasicAttackDamage() + Origin->GetMagicalPower() * Origin->GetBasicAttackPowerScaling()) * DamageProgressionMultiplier * CleaveDamage) * (100 / (TotalProtections + 100)), Origin);
}
Targets.Add(DamagedTarget);
}
}
}
}
Origin->OnBasicAttackHit(Targets);
Destroy();
}
}
void ASLRangedBasicProjectile::OnWallHit(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& Hit)
{
if (!OtherActor->Implements<USLVulnerable>() && OtherActor != this) Destroy();
}
// Called every frame
void ASLRangedBasicProjectile::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
int NumberOfMovements{ (int)(DeltaTime * 100) };
if (NumberOfMovements == 0) ++NumberOfMovements;
for (int i = 0; i < NumberOfMovements; i++)
{
if (FVector::Dist(StartingLocation, GetActorLocation() + SceneComponent->GetForwardVector() * ProjectileSpeed * 100 * (DeltaTime / NumberOfMovements)) >= (ProjectileRange - ProjectileLength) * 100)
{
SetActorLocation(StartingLocation + SceneComponent->GetForwardVector() * (ProjectileRange - ProjectileLength) * 100);
Destroy();
}
SetActorLocation(GetActorLocation() + SceneComponent->GetForwardVector() * ProjectileSpeed * 100 * (DeltaTime / NumberOfMovements));
}
}
|
#include <iostream>
#include "Vector2D.h"
#include "Vector3D.h"
#include "Matrix.h"
using namespace std;
int main() {
return 0;
}
|
// WhitewoodEncryptionRandNumProvider.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include "WhitewoodEncryptionRandNumProvider.h"
// This is an example of an exported variable
WHITEWOODENCRYPTIONRANDNUMPROVIDER_API int nWhitewoodEncryptionRandNumProvider=0;
// This is an example of an exported function.
WHITEWOODENCRYPTIONRANDNUMPROVIDER_API int fnWhitewoodEncryptionRandNumProvider(void)
{
return 42;
}
// This is the constructor of a class that has been exported.
// see WhitewoodEncryptionRandNumProvider.h for the class definition
//CWhitewoodEncryptionRandNumProvider::CWhitewoodEncryptionRandNumProvider()
//{
// return;
//}
// CNGProvider.cpp : Defines the exported functions for the DLL application.
// Windows 8 : Beginning with Windows 8, the RNG algorithm supports FIPS 186 - 3.
// Keys less than or equal to 1024 bits adhere to FIPS 186 - 2
// and keys greater than 1024 to FIPS 186 - 3
//
#include "stdafx.h"
#define WIN32_NO_STATUS
#include <windows.h>
#undef WIN32_NO_STATUS
#include <windows.h>
#include <strsafe.h>
#include <setupapi.h>
#include <spapidef.h>
#include <windows.h>
#include <bcrypt.h>
#include "../Include/bcrypt_provider.h"
#include <setupapi.h>
#include <tchar.h>
#include <stdio.h>
#include "WhitewoodEncryptionRandNumProvider.h"
//#include "NetRandomProvider.h"
#include <winternl.h>
#include <winerror.h>
#include <stdio.h>
#include <bcrypt.h>
#include "..\include\dllhelper.h"
#ifdef __cplusplus
extern "C"
{
#endif
#include <malloc.h>
#include <windows.h>
//helper macros
#define MALLOC(X) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (X));
#define FREE(X) { if(X) { HeapFree(GetProcessHeap(), 0, X); X = NULL ; } }
#include <bcrypt.h>
#include "..\include\bcrypt_provider.h"
}
//
#define WERNG_PROVIDER_NAME L"NetRand RNG Provider"
#include ".\..\Include\bcrypt_provider.h"
#include <sal.h>
#define WERNG_IMAGE_NAME L"WhitewoodRandom.dll"
PWSTR WERngAlgorithmNames[1] = {
BCRYPT_RNG_ALGORITHM
};
CRYPT_INTERFACE_REG WERngInterface = {
BCRYPT_RNG_INTERFACE, CRYPT_LOCAL, 1, WERngAlgorithmNames
};
PCRYPT_INTERFACE_REG WERngInterfaces[1] = {
&WERngInterface
};
CRYPT_IMAGE_REG WERngImage = {
WERNG_IMAGE_NAME, 1, WERngInterfaces
};
CRYPT_PROVIDER_REG WERngProvider = {
0, NULL, &WERngImage, NULL
};
typedef ULONG(WINAPI* RtlNtStatusToDosErrorFunc)(IN NTSTATUS status);
static DWORD ToDosError(NTSTATUS status)
{
DWORD error = NO_ERROR;
HMODULE ntdll;
RtlNtStatusToDosErrorFunc RtlNtStatusToDosError;
ntdll = LoadLibrary(L"Ntdll.dll");
if (ntdll != NULL)
{
RtlNtStatusToDosError = (RtlNtStatusToDosErrorFunc)
GetProcAddress(ntdll, "RtlNtStatusToDosError");
if (RtlNtStatusToDosError != NULL)
{
error = RtlNtStatusToDosError(status);
}
else
{
error = GetLastError();
SetupWriteTextLogError(SetupGetThreadLogToken(),
TXTLOG_INSTALLER,
TXTLOG_ERROR,
error,
"RtlNtStatusToDosError function not found.");
}
}
else
{
error = GetLastError();
SetupWriteTextLogError(SetupGetThreadLogToken(),
TXTLOG_INSTALLER,
TXTLOG_ERROR,
error,
"Failed to load ntdll.dll.");
}
return error;
}
// This is an example of an exported variable
WHITEWOODENCRYPTIONRANDNUMPROVIDER_API int nCNGProvider = 0;
WHITEWOODENCRYPTIONRANDNUMPROVIDER_API NTSTATUS WINAPI GetInterface(
_In_ LPCWSTR pszProviderName,
_Out_ BCRYPT_RNG_FUNCTION_TABLE **ppFunctionTable,
_In_ ULONG dwFlags
);
/* visual aid for dev
typedef struct _BCRYPT_RNG_FUNCTION_TABLE {
BCRYPT_INTERFACE_VERSION Version;
BCryptOpenAlgorithmProviderFn OpenAlgorithmProvider;
BCryptGetPropertyFn GetProperty;
BCryptSetPropertyFn SetProperty;
BCryptCloseAlgorithmProviderFn CloseAlgorithmProvider;
BCryptGenRandomFn GenRandom;
} BCRYPT_RNG_FUNCTION_TABLE;
*/
BCRYPT_RNG_FUNCTION_TABLE RngFunctionTable;
typedef NTSTATUS(WINAPI *BCryptOpenAlgorithmProviderFn)(
_Out_ BCRYPT_ALG_HANDLE *phAlgorithm,
_In_ LPCWSTR pszAlgId,
_In_ ULONG dwFlags
);
typedef NTSTATUS(WINAPI *BCryptGetPropertyFn)(
_In_ BCRYPT_HANDLE hObject,
_In_ LPCWSTR pszProperty,
_Out_ PUCHAR pbOutput,
_In_ ULONG cbOutput,
_Out_ ULONG *pcbResult,
_In_ ULONG dwFlags
);
typedef NTSTATUS(WINAPI *BCryptSetPropertyFn)(
_Inout_ BCRYPT_HANDLE hObject,
_In_ LPCWSTR pszProperty,
_In_ PUCHAR pbInput,
_In_ ULONG cbInput,
_In_ ULONG dwFlags
);
typedef NTSTATUS(WINAPI *BCryptGenRandomFn)(
_Inout_ BCRYPT_ALG_HANDLE hAlgorithm,
_Inout_ PUCHAR pbBuffer,
_In_ ULONG cbBuffer,
_In_ ULONG dwFlags
);
typedef NTSTATUS(WINAPI *BCryptCloseAlgorithmProviderFn)(
_Inout_ BCRYPT_ALG_HANDLE hAlgorithm,
_In_ ULONG dwFlags
);
/* This is an example of an exported function.
CNGPROVIDER_API int fnCNGProvider(void)
{
return 42;
}
*/
// This is the constructor of a class that has been exported.
// see CNGProvider.h for the class definition
//CCNGProvider::CCNGProvider()
//{
// return;
//}
NTSTATUS(WINAPI OpenProvider)(
_Out_ BCRYPT_ALG_HANDLE *phAlgorithm,
_In_ LPCWSTR pszAlgId,
_In_ ULONG dwFlags
)
{
/*
open up the network source and start the entropy fetch engine
we will leave the entropy fetch status to fetch
*/
return STATUS_NOT_IMPLEMENTED;
}
_Must_inspect_result_ NTSTATUS(WINAPI CloseProvider)(
_Inout_ BCRYPT_ALG_HANDLE hAlgorithm,
_In_ ULONG dwFlags)
{
return STATUS_NOT_IMPLEMENTED;
}
NTSTATUS(WINAPI GetProperty)(
_In_ BCRYPT_HANDLE hObject,
_In_ LPCWSTR pszProperty,
_Out_ PUCHAR pbOutput,
_In_ ULONG cbOutput,
_Out_ ULONG *pcbResult,
_In_ ULONG dwFlags
)
{
return STATUS_NOT_IMPLEMENTED;
}
NTSTATUS(WINAPI SetProperty)(
_Inout_ BCRYPT_HANDLE hObject,
_In_ LPCWSTR pszProperty,
_In_ PUCHAR pbInput,
_In_ ULONG cbInput,
_In_ ULONG dwFlags
)
{
return STATUS_NOT_IMPLEMENTED;
}
NTSTATUS(WINAPI GetRandom)(
_Inout_ BCRYPT_ALG_HANDLE hAlgorithm,
_Inout_ PUCHAR pbBuffer,
_In_ ULONG cbBuffer,
_In_ ULONG dwFlags
)
{
return STATUS_NOT_IMPLEMENTED;
}
WHITEWOODENCRYPTIONRANDNUMPROVIDER_API NTSTATUS WINAPI GetInterface(LPCWSTR pszProviderName, BCRYPT_RNG_FUNCTION_TABLE ** ppFunctionTable, ULONG dwFlags)
{
// Let's initialize the function table
RngFunctionTable.OpenAlgorithmProvider = OpenProvider;
RngFunctionTable.GetProperty = GetProperty;
RngFunctionTable.SetProperty = SetProperty;
RngFunctionTable.GenRandom = GetRandom;
RngFunctionTable.CloseAlgorithmProvider = CloseProvider;
RngFunctionTable.Version = BCRYPT_RNG_INTERFACE_VERSION_1;
return NTSTATUS();
}// provider.cpp : Defines the entry point for the DLL application.
//
#include "stdafx.h"
//#include "NetRandomProvider.h"
#ifdef _MANAGED
#pragma managed(push, off)
#endif
///////////////////////////////////////////////////////////////////////////////
//
// Local definitions...
//
///////////////////////////////////////////////////////////////////////////////
//
// These NTSTATUS items are not currently defined in BCRYPT.H. Unitl this is
// corrected, the easiest way to make them available is to cut and paste them
// from NTSTATUS.H...
//
#ifndef NTSTATUS
typedef LONG NTSTATUS, *PNSTATUS;
#endif
#ifndef NT_SUCCESS
#define NT_SUCCESS(status) (status >= 0)
#endif
#ifndef STATUS_SUCCESS
#define STATUS_SUCCESS ((NTSTATUS)0x00000000L)
#define STATUS_NOT_SUPPORTED ((NTSTATUS)0xC00000BBL)
#define STATUS_UNSUCCESSFUL ((NTSTATUS)0xC0000001L)
#define STATUS_HMAC_NOT_SUPPORTED ((NTSTATUS)0xC000A001L)
#define STATUS_BUFFER_TOO_SMALL ((NTSTATUS)0xC0000023L)
#define STATUS_NOT_IMPLEMENTED ((NTSTATUS)0xC0000002L)
#endif
//#define STRICT
#include <windows.h>
#include <bcrypt.h>
#include "..\include\bcrypt_provider.h"
#include <setupapi.h>
#include <tchar.h>
#include <stdio.h>
/*
PWSTR WERngAlgorithmNames[1] = {
BCRYPT_RNG_ALGORITHM
};
CRYPT_INTERFACE_REG WERngInterface = {
BCRYPT_RNG_INTERFACE, CRYPT_LOCAL, 1, WERngAlgorithmNames
};
PCRYPT_INTERFACE_REG WERngInterfaces[1] = {
&WERngInterface
};
*/
/*CRYPT_IMAGE_REG WERngImage = {
WERNG_IMAGE_NAME, 1, WERngInterfaces
};
CRYPT_PROVIDER_REG WERngProvider = {
0, NULL, &WERngImage, NULL
};
typedef DWORD(WINAPI* RtlNtStatusToDosErrorFunc)(IN NTSTATUS status);
static DWORD ToDosError(IN NTSTATUS status)
{
DWORD error = NO_ERROR;
HMODULE ntdll;
RtlNtStatusToDosErrorFunc RtlNtStatusToDosError;
ntdll = LoadLibrary(L"Ntdll.dll");
if (ntdll != NULL)
{
RtlNtStatusToDosError = (RtlNtStatusToDosErrorFunc)
GetProcAddress(ntdll, "RtlNtStatusToDosError");
if (RtlNtStatusToDosError != NULL)
{
error = RtlNtStatusToDosError(status);
}
else
{
error = GetLastError();
SetupWriteTextLogError(SetupGetThreadLogToken(),
TXTLOG_INSTALLER,
TXTLOG_ERROR,
error,
"RtlNtStatusToDosError function not found.");
}
}
else
{
error = GetLastError();
SetupWriteTextLogError(SetupGetThreadLogToken(),
TXTLOG_INSTALLER,
TXTLOG_ERROR,
error,
"Failed to load ntdll.dll.");
}
return error;
}
*/
NTSTATUS WINAPI RegisterProvider(BOOLEAN KernelMode)
{
NTSTATUS status;
UNREFERENCED_PARAMETER(KernelMode);
status = BCryptRegisterProvider(WERNG_PROVIDER_NAME, CRYPT_OVERWRITE,
&WERngProvider);
if (!NT_SUCCESS(status))
{
SetupWriteTextLogError(SetupGetThreadLogToken(),
TXTLOG_INSTALLER,
TXTLOG_ERROR,
ToDosError(status),
"Failed to register as a CNG provider.");
return status;
}
status = BCryptAddContextFunctionProvider(CRYPT_LOCAL, NULL,
BCRYPT_RNG_INTERFACE, BCRYPT_RNG_ALGORITHM, WERNG_PROVIDER_NAME,
CRYPT_PRIORITY_BOTTOM);
if (!NT_SUCCESS(status))
{
SetupWriteTextLogError(SetupGetThreadLogToken(),
TXTLOG_INSTALLER,
TXTLOG_ERROR,
ToDosError(status),
"Failed to add cryptographic function.");
}
return status;
}
NTSTATUS WINAPI UnregisterProvider()
{
NTSTATUS status;
status = BCryptRemoveContextFunctionProvider(CRYPT_LOCAL, NULL,
BCRYPT_RNG_INTERFACE, BCRYPT_RNG_ALGORITHM, WERNG_PROVIDER_NAME);
if (!NT_SUCCESS(status))
{
SetupWriteTextLogError(SetupGetThreadLogToken(),
TXTLOG_INSTALLER,
TXTLOG_WARNING,
ToDosError(status),
"Failed to remove cryptographic function.");
}
status = BCryptUnregisterProvider(WERNG_PROVIDER_NAME);
if (!NT_SUCCESS(status))
{
SetupWriteTextLogError(SetupGetThreadLogToken(),
TXTLOG_INSTALLER,
TXTLOG_WARNING,
ToDosError(status),
"Failed to unregister as a CNG provider.");
}
return STATUS_SUCCESS;
}
DWORD CALLBACK WERngCoInstaller(IN DI_FUNCTION InstallFunction,
IN HDEVINFO DeviceInfoSet,
IN PSP_DEVINFO_DATA DeviceInfoData OPTIONAL,
IN OUT PCOINSTALLER_CONTEXT_DATA Context)
{
NTSTATUS status;
DWORD error = NO_ERROR;
UNREFERENCED_PARAMETER(DeviceInfoSet);
UNREFERENCED_PARAMETER(DeviceInfoData);
UNREFERENCED_PARAMETER(Context);
switch (InstallFunction)
{
case DIF_INSTALLDEVICE:
status = RegisterProvider(FALSE);
if (!NT_SUCCESS(status))
{
error = ToDosError(status);
}
break;
case DIF_REMOVE:
status = UnregisterProvider();
if (!NT_SUCCESS(status))
{
error = ToDosError(status);
}
break;
default:
break;
}
return error;
}
#ifdef _MANAGED
#pragma managed(pop)
#endif
|
/*
** EPITECH PROJECT, 2019
** tek3
** File description:
** Codec
*/
#include "Codec.hpp"
#include <stdexcept>
babel::Codec::Codec()
{
_encoder = opus_encoder_create(SAMPLE_RATE, NUM_CHANNELS, APPLICATION, &_error);
if (_error != OPUS_OK)
throw std::runtime_error("error");
_error = opus_encoder_ctl(_encoder, OPUS_SET_BITRATE(BITRATE));
if (_error != OPUS_OK)
throw std::runtime_error("error");
_decoder = opus_decoder_create(SAMPLE_RATE, NUM_CHANNELS, &_error);
if (_error != OPUS_OK)
throw std::runtime_error("error");
}
babel::Codec::~Codec()
{
opus_decoder_destroy(_decoder);
opus_encoder_destroy(_encoder);
}
int babel::Codec::encode(unsigned char * cbits, char * dataInput)
{
return (opus_encode(_encoder, reinterpret_cast<opus_int16 *>(dataInput), FRAME_SIZE, cbits, MAX_PACKET_SIZE));
}
int babel::Codec::decode(unsigned char * cbits, char * dataOutput, int nbBytes)
{
return (opus_decode(_decoder, cbits, nbBytes, reinterpret_cast<opus_int16 *>(dataOutput), MAX_FRAME_SIZE, 0));
}
|
/**
* @Author Vladimir Hardy
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstring>
#include <vector>
// To access members of a structure, use the dot operator. To access members of a structure through a pointer, use the arrow operator.
struct node {
std::string data;
node *next;
node *prev;
};
struct pointer_node {
void *data_pointer;
pointer_node *next;
pointer_node *prev;
};
#include "Prototypes.h"
#include "tree.cpp"
#include "mapquest.cpp"
/**
* @brief calls all linked list functions, this is where the test cases are.
* @definition Linked List: A collection of nodes that together form a linear ordering. Each node stores a pointer,
* called next, to the next node of the list.
*/
int main() {
std::vector<std::string> file_vector_for_tree;
std::vector<std::string> sorted_vector;
node *front, *rear = new node;
front = rear = nullptr;
auto *p_front = new pointer_node; //if you condense this declaration, it messes up addresses (set to 0)
auto *p_rear = new pointer_node;
// Homework 2 stuff: Read File
/*std::string my_file = "test_file.txt";
read_file(&front, &rear, my_file);
make_alphanumeric(&front, &rear);
navigate_list_backwards(&rear);
//create AVL tree from the words
tree AVL_tree;
tree_node *root = nullptr;
for(std::string i : file_vector_for_tree) { // Trying to call the AVL insert tree for each index in the vector
//AVL_tree.insert_tree(&root,i); // Causes weird errors where I cannot run the program, accessing something i have no control over, when I edit the test_file?
//It seems that the 1 height nodes are being replaced with new data instead of percolating up (occurs when given this error in degubber: -var-create: unable to create variable object)
}*/
// Homework 3 stuff:
map_quest mq;
int test_array[] = {30, 29, 11, 38, 42, 19, 8};
mq.merge_sort(test_array, 7);
read_file(&front, &rear, "mapcampus.txt");
navigate_list_forward(&rear);
}
/**
* @brief Navigates through a linked list and prints its data starting from the front
* @param front: a pointer that points to the first node in the list
*/
void navigate_list_forward(node **front) {
std::cout << "Navigating linked list forwards: " << std::endl;
if (empty(front, false)) {
std::cout << "---" << std::endl;
} else {
node *p_data = new node;
p_data = *front;
while (p_data != nullptr) {
std::cout << p_data->data << std::endl;
p_data = p_data->next;
}
}
}
/**
* @brief Navigates through a linked list and prints its data starting from the rear
* @param rear: a pointer that points to the last node in the list
*/
void navigate_list_backwards(node **rear) {
std::cout << "Navigating linked list backwards: " << std::endl;
node *p_data;
p_data = *rear;
while (p_data != nullptr) {
std::cout << p_data->data << std::endl;
p_data = p_data->prev;
}
}
int get_list_size(node **front) {
node *p_data = new node;
p_data = *front;
int size = 0;
while (p_data != nullptr) {
p_data = p_data->next;
size++;
}
return size;
}
/**
* @brief adds a new node to the front of a linked list with data (data gets moved to the left of the most recent node).
* @param front: a pointer that points to the first node in the list
* @param rear: a pointer that points to the last node in the list
* @param data: an integer that will be held in the node
*/
void insert_front(node **front, node **rear, std::string data) {
node *p_data = new node;
p_data->data = data;
//std::cout << "Front " << *front << std::endl; //Proof that front is null at the beginning
if (*front == nullptr) { // Special case
*front = *rear = p_data;
//std::cout << "Front: " << front << std::endl; //Prints what the variable front is storing
//std::cout << "Front&: " << &front << std::endl; //Gets the address of &front
//std::cout << "Front*: " << *front << std::endl; //gets the value *Front is pointing to
p_data->next = nullptr;
p_data->prev = nullptr;
} else { // One or more nodes (general case)
p_data->next = *front; //This moves the link of the new node to the next node
(*front)->prev = p_data; //The -> is happening before the *, so the compiler is trying to use -> get_data on a Node<NODETYPE> ** which doesn't work.
*front = p_data; //The value front is pointing to is assigned p_data
}
}
void insert_front_p(pointer_node **p_front, pointer_node **p_rear, void *void_data) {
pointer_node *p_data;
p_data->data_pointer = void_data;
if (*p_front == nullptr) {
*p_front = *p_rear = p_data;
p_data->next = nullptr;
p_data->prev = nullptr;
} else {
p_data->next = *p_front;
(*p_front)->prev = p_data;
*p_front = p_data;
}
}
/**
* @brief adds a new node to the end of a linked list (data gets moved to the right of the most recent node).
* @param front: a pointer that points to the first node in the list
* @param rear: a pointer that points to the last node in the list
* @param data: an integer that will be held in the node
*/
void insert_rear(node **front, node **rear, std::string data) {
node *p_data = new node;
p_data->data = data;
p_data->next = nullptr;
if (*front == nullptr) {
*front = *rear = p_data;
p_data->next = p_data->prev = nullptr;
} else {
p_data->prev = *rear;
(*rear)->next = p_data;
*rear = (*rear)->next;
}
}
void insert_rear_p(pointer_node **p_front, pointer_node **p_rear, void *void_data) {
}
/**
* @brief Removes the front node of a linked list and returns the integer value it stored. pointers pointing to the
* previous node are deleted
* @param front: a pointer that points to the first node in the list
* @param rear: a pointer that points to the last node in the list
* @return an integer that was stored in the node being deleted
*/
std::string remove_front_i(node **front, node **rear) {
node *p_data = new node;
std::string hold = "";
if (*front == nullptr) {
std::cout << "Linked List is already empty" << std::endl;
} else if (*front == *rear) {
hold = (*front)->data; //not p_data->data because it gives garbage
p_data = *front;
delete p_data;
*front = p_data = nullptr;
} else {
hold = (*front)->data;
*front = (*front)->next;
(*front)->prev = nullptr;
p_data = nullptr; //Just in case we try to access p_data
//delete p_data->prev;
delete p_data;
}
return hold;
}
/**
* @brief Removes the front address of data that a pointer points to A void* does not mean anything. It is a pointer, but the type that it points to is not known.
* @param p_front: a pointer that points to the first node in the list
* @param p_rear: a pointer that points to the last node in the list
* @return It returns a pointer to storage that contains an object of a known type
*/
void *remove_front_p(pointer_node **p_front, pointer_node **p_rear) {
pointer_node *p_data;
void *void_data = nullptr;
if (*p_front == nullptr) {
std::cout << "Linked List is already empty" << std::endl;
} else if (*p_front == *p_rear) {
void_data = (*p_front)->data_pointer; //not p_data->data because it gives garbage
p_data = *p_front;
delete p_data;
*p_front = p_data = nullptr;
} else {
void_data = (*p_front)->data_pointer;
*p_front = (*p_front)->next;
//delete (*p_front)->prev;
//(*p_front)->prev = nullptr;
}
return void_data;
}
/**
* @brief Removes the last node in the linked list and returns its integer value. pointers pointing to the next node
* are deleted and set to null
* @param front: a pointer that points to the first node in the list
* @param rear: a pointer that points to the last node in the list
* @return An integer that was stored in the node being deleted
*/
std::string remove_rear_i(node **front, node **rear) {
std::string hold = "";
node *p_data = new node;
if (*front == nullptr) {
std::cout << "Empty linked list" << std::endl;
} else if (*front == *rear) {
hold = (*rear)->data;
delete p_data;
*front = *rear = nullptr;
} else {
hold = (*rear)->data;
*rear = (*rear)->prev;
delete (*rear)->next;
(*rear)->next = nullptr;
//size--;
}
return hold;
}
/**
* @brief Removes the rear address a pointer points to
* @param p_front: a pointer that points to the first node in the list
* @param p_rear: a pointer that points to the last node in the list
* @return It returns a pointer to storage that contains an object of a known type
*/
void *remove_rear_p(pointer_node **p_front, pointer_node **p_rear) {
pointer_node *p_data;
void *void_data = nullptr;
if (*p_front == nullptr) {
std::cout << "Linked List is already empty" << std::endl;
} else if (*p_front == *p_rear) {
void_data = (*p_rear)->data_pointer; //not p_data->data because it gives garbage
p_data = *p_rear;
delete p_data;
*p_front = p_data = nullptr;
} else {
void_data = (*p_rear)->data_pointer;
*p_front = (*p_rear)->prev;
delete (*p_rear)->next;
(*p_rear)->next = nullptr;
}
return void_data;
}
/**
* @brief checks to see if a linked list is empty by using the front pointer
* @param front: a pointer that points to the first node in a linked list (if it exists)
* @return true or false, depending on whether the node is empty or not
*/
bool empty(node **front, bool output_text) {
if (*front == nullptr) { //If the front pointer doesnt point to anything, there isn't data anywhere else
if (output_text) {
std::cout << "Linked list is empty" << std::endl;
}
return true;
} else {
if (output_text) {
std::cout << "Linked list is not empty" << std::endl;
}
return false;
}
}
/**
* @brief Removes all nodes in a linked list
* @param front: a pointer that points to the first node in the list
* @param rear: a pointer that points to the last node in the list
*/
void empty_the_list(node **front, node **rear) {
while (*front != nullptr) {
std::cout << remove_front_i(front, rear) << std::endl; //Test case 2: no elements
}
//std::cout << "cleared" << std::endl; //Test case 2: no elements
}
/**
* @brief supposed to reverse the order of a list, but only prints 1 value
* @param front
* @param rear
*/
void reverse_list(node **front, node **rear) {
node *p_data, *q_data, *r_data = new node;
p_data = *front;
q_data = p_data->next;
r_data = q_data->next;
(*front)->next = nullptr;
while(q_data->next != nullptr) {
q_data->next = p_data;
p_data = q_data, q_data = r_data, r_data = r_data->next;
}
std::cout << "List reversed" << std::endl;
}
void read_file(node **front, node **rear, const std::string& file_name) {
std::ifstream file_to_be_read; //REMEMBER: Files are stored in cmake-build-debug
file_to_be_read.open(file_name, std::ios_base::app);
if(file_to_be_read.is_open()) {
std::string line;
while (std::getline(file_to_be_read,line)) { // fixes the issue where \n would be read
std::stringstream ss(line);
while (std::getline(ss, line, ' ')) {
insert_front(front, rear, line);
}
}
}
else {
std::cout << "Unable to open file " << file_name << std::endl;
}
file_to_be_read.close();
}
void make_alphanumeric(node **front, node **rear) { //bubble sort
node *p_data = new node;
std::string temp_val;
bool unsorted = true;
p_data = *rear;
while (unsorted) {
int swaps = 0;
while (p_data != *front) {
if (p_data->data /* d */ > p_data->prev->data /* a */) {
temp_val = p_data->data; //d
p_data->data = p_data->prev->data;
p_data->prev->data = temp_val;
swaps++;
}
if (p_data->prev == nullptr) {
break;
}
p_data = p_data->prev;
}
if(swaps == 0) {
unsorted = false;
}
}
}
|
/*
* Copyright 2020 OmniSci, Inc.
*
* 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.
*/
/**
* @file ForeignStorageCache.h
* @author Misiu Godfrey <misiu.godfrey@omnisci.com>
*
* This file includes the class specification for the cache used by the Foreign Storage
* Interface (FSI). This cache is used by FSI to cache data and metadata locally on disc
* to avoid repeated loads from foreign storage.
*/
#pragma once
#include <gtest/gtest.h>
#include "../Shared/mapd_shared_mutex.h"
#include "CacheEvictionAlgorithms/CacheEvictionAlgorithm.h"
#include "CacheEvictionAlgorithms/LRUEvictionAlgorithm.h"
#include "DataMgr/AbstractBufferMgr.h"
#include "DataMgr/FileMgr/GlobalFileMgr.h"
#include "ForeignDataWrapper.h"
struct DiskCacheConfig {
std::string path;
bool is_enabled = false;
size_t entry_limit = 1024;
size_t num_reader_threads = 0;
DiskCacheConfig() {}
DiskCacheConfig(std::string p,
bool enabled = true,
size_t limit = 1024,
size_t readers = 0)
: path(p), is_enabled(enabled), entry_limit(limit), num_reader_threads(readers) {}
};
using namespace Data_Namespace;
namespace foreign_storage {
class ForeignStorageCache {
public:
ForeignStorageCache(const std::string& cache_dir,
const size_t num_reader_threads,
const size_t limit);
/**
* Caches the chunks for the given chunk keys. Chunk buffers
* for chunks to be cached are expected to have already been
* populated before calling this method. This method also
* expects all provided chunk keys to be for the same table.
*
* @param chunk_keys - keys of chunks to be cached
*/
void cacheTableChunks(const std::vector<ChunkKey>& chunk_keys);
AbstractBuffer* getCachedChunkIfExists(const ChunkKey&);
bool isMetadataCached(const ChunkKey&);
void cacheMetadataVec(const ChunkMetadataVector&);
void getCachedMetadataVecForKeyPrefix(ChunkMetadataVector&, const ChunkKey&);
bool hasCachedMetadataForKeyPrefix(const ChunkKey&);
void clearForTablePrefix(const ChunkKey&);
void clear();
void setLimit(size_t limit);
std::vector<ChunkKey> getCachedChunksForKeyPrefix(const ChunkKey&);
bool recoverCacheForTable(ChunkMetadataVector&, const ChunkKey&);
std::map<ChunkKey, AbstractBuffer*> getChunkBuffersForCaching(
const std::vector<ChunkKey>& chunk_keys);
// Exists for testing purposes.
size_t getLimit() const { return entry_limit_; }
size_t getNumCachedChunks() const { return cached_chunks_.size(); }
size_t getNumCachedMetadata() const { return cached_metadata_.size(); }
// Useful for debugging.
std::string dumpCachedChunkEntries() const;
std::string dumpCachedMetadataEntries() const;
std::string dumpEvictionQueue() const;
File_Namespace::GlobalFileMgr* getGlobalFileMgr() { return global_file_mgr_.get(); }
private:
// These methods are private and assume locks are already acquired when called.
std::set<ChunkKey>::iterator eraseChunk(const std::set<ChunkKey>::iterator&);
void eraseChunk(const ChunkKey&);
void evictThenEraseChunk(const ChunkKey&);
void evictChunkByAlg();
bool isCacheFull() const;
void validatePath(const std::string&);
// We can swap out different eviction algorithms here.
std::unique_ptr<CacheEvictionAlgorithm> eviction_alg_ =
std::make_unique<LRUEvictionAlgorithm>();
// Underlying storage is handled by a GlobalFileMgr unique to the cache.
std::unique_ptr<File_Namespace::GlobalFileMgr> global_file_mgr_;
// Keeps tracks of which Chunks/ChunkMetadata are cached.
std::set<ChunkKey> cached_chunks_;
std::set<ChunkKey> cached_metadata_;
// Separate mutexes for chunks/metadata.
mapd_shared_mutex chunks_mutex_;
mapd_shared_mutex metadata_mutex_;
// Maximum number of Chunks that can be in the cache before eviction.
size_t entry_limit_;
}; // ForeignStorageCache
} // namespace foreign_storage
|
#ifndef SOPNET_GROUND_TRUTH_EXTRACTOR_H__
#define SOPNET_GROUND_TRUTH_EXTRACTOR_H__
#include <vector>
#include <boost/shared_ptr.hpp>
#include <pipeline/all.h>
#include <imageprocessing/ImageStack.h>
#include <sopnet/segments/Segments.h>
// forward declarations
class ImageExtractor;
class SliceExtractor;
class GroundTruthSegmentExtractor;
class GroundTruthExtractor : public pipeline::ProcessNode {
public:
GroundTruthExtractor(int firstSection = -1, int lastSection = -1);
private:
class SegmentsAssembler : public pipeline::SimpleProcessNode<> {
public:
SegmentsAssembler();
private:
void updateOutputs();
pipeline::Inputs<Segments> _segments;
pipeline::Output<Segments> _allSegments;
};
void onInputSet(const pipeline::InputSet<ImageStack>& signal);
void createPipeline();
// the ground truth images
pipeline::Input<ImageStack> _groundTruthSections;
// update signal slot to explicitly update inputs
signals::Slot<pipeline::Update> _update;
// ground truth sections to image converter
boost::shared_ptr<ImageExtractor> _sectionExtractor;
// slice extractors to get the slices per section
std::vector<boost::shared_ptr<SliceExtractor> > _sliceExtractors;
// extract segments from the components found by the sliceExtractors
std::vector<boost::shared_ptr<GroundTruthSegmentExtractor> > _segmentExtractors;
// collects all segments
boost::shared_ptr<SegmentsAssembler> _segmentsAssembler;
int _firstSection;
int _lastSection;
};
#endif // SOPNET_GROUND_TRUTH_EXTRACTOR_H__
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/SaveGame.h"
#include "NameScore.generated.h"
USTRUCT()
struct FSingle
{
GENERATED_BODY()
public:
UPROPERTY(VisibleAnywhere, Category = Basic)
FString PlayerName;
UPROPERTY(VisibleAnywhere, Category = Basic)
float PlayerScore;
};
/**
*
*/
UCLASS()
class PROJECT_API UNameScore : public USaveGame
{
GENERATED_BODY()
public:
UPROPERTY(VisibleAnywhere, Category = Basic)
TArray<FSingle> Saves;
};
|
#ifndef _RaseProcess_H_
#define _RaseProcess_H_
#include "BaseProcess.h"
class Table;
class Player;
class RaseProcess : public BaseProcess
{
public:
RaseProcess();
virtual ~RaseProcess();
int doRequest(CDLSocketHandler* clientHandler, InputPacket* inputPacket, Context* pt);
int doResponse(CDLSocketHandler* clientHandler, InputPacket* inputPacket, Context* pt);
private:
int sendRaseInfoToPlayers(Player* player, int cmd, Table* table, Player* betcallplayer,int64_t betmoney,Player* nextplayer,short seq);
};
#endif
|
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
int a[10010],f[10010];
int main()
{
int n;
scanf("%d",&n);
f[0] = 0;
int loc = 0;
for (int i = 1;i <= n; i++)
{
scanf("%d",&a[i]);
f[i] = max(f[i-1],0) + a[i];
if (f[i] > f[loc] || !(f[i] || f[loc])) loc = i;
}
int la = loc,fi = la-1;
if (!loc)
{
la = n;
fi = 1;
}
else
{
while (fi && f[fi] + a[fi+1] == f[fi+1]) fi--;
fi++;
}
printf("%d %d %d\n",f[loc],a[fi],a[la]);
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2010 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#ifndef OP_LINKS_VIEW_H
#define OP_LINKS_VIEW_H
#include "adjunct/desktop_pi/desktop_file_chooser.h"
#include "modules/widgets/OpWidget.h"
#include "adjunct/quick/windows/DocumentDesktopWindow.h"
#include "adjunct/quick_toolkit/widgets/OpTreeView/OpTreeView.h"
#include "adjunct/quick_toolkit/windows/DesktopWindow.h"
class LinksModel;
/***********************************************************************************
**
** OpLinksView
**
***********************************************************************************/
class OpLinksView : public OpWidget, public DesktopWindowSpy, public DesktopFileChooserListener
{
private:
struct LinkData
{
OpString address;
OpString title;
};
protected:
OpLinksView();
public:
static OP_STATUS Construct(OpLinksView** obj);
void SetDetailed(BOOL detailed, BOOL force = FALSE);
virtual void OnResize(INT32* new_w, INT32* new_h) {m_links_view->SetRect(GetBounds());}
virtual void OnShow(BOOL show);
virtual void OnAdded() {UpdateTargetDesktopWindow(); UpdateLinks(FALSE);}
BOOL IsSingleClick();
BOOL SetPanelLocked(BOOL locked);
virtual Type GetType() {return WIDGET_TYPE_LINKS_VIEW;}
BOOL ShowContextMenu(const OpPoint &point, BOOL center, BOOL use_keyboard_context);
// subclassing OpWidget
virtual void SetAction(OpInputAction* action) {m_links_view->SetAction(action); }
virtual void OnSettingsChanged(DesktopSettings* settings);
virtual void OnDeleted();
// DesktopFileChooserListener
virtual void OnFileChoosingDone(DesktopFileChooser* chooser, const DesktopFileChooserResult& result);
// OpWidgetListener
virtual void OnMouseEvent(OpWidget *widget, INT32 pos, INT32 x, INT32 y, MouseButton button, BOOL down, UINT8 nclicks);
virtual void OnDragStart(OpWidget* widget, INT32 pos, INT32 x, INT32 y);
virtual void OnTimer() {UpdateLinks(FALSE);}
// == OpInputContext ======================
virtual BOOL OnInputAction(OpInputAction* action);
virtual const char* GetInputContextName() {return "Links Widget";}
// DesktopWindowSpy hooks
virtual void OnTargetDesktopWindowChanged(DesktopWindow* target_window) {UpdateLinks(TRUE);}
virtual void OnPageStartLoading(OpWindowCommander* commander) {UpdateLinks(TRUE);}
virtual void OnPageLoadingFinished(OpWindowCommander* commander, OpLoadingListener::LoadingFinishStatus status) {UpdateLinks(FALSE);}
OpTreeView* GetTree() const { return m_links_view; }
private:
void DoAllSelected(OpInputAction::Action action);
void UpdateLinks(BOOL restart);
private:
DesktopFileChooser* m_chooser;
DesktopFileChooserRequest m_request;
LinksModel* m_links_model;
OpTreeView* m_links_view;
BOOL m_locked;
BOOL m_needs_update;
BOOL m_detailed;
BOOL m_private_mode;
};
#endif // OP_LINKS_VIEW_H
|
#include<iostream>
using namespace std;
typedef struct node
{
int a;
struct node *next;
}Node;
node *head, *end1;
void create(){
node *temp = new Node;
cin>>temp->a;
temp->next=NULL;
if(head == NULL)
{
head = temp;
end1 = temp;
}
else
{
end1->next = temp;
end1 = temp;
}
}
void traverse()
{
node *temp = head;
while(temp!=NULL)
{
cout<<temp->a;
temp=temp->next;
}
}
void swaplist(int x1, int y1)
{
node *temp,*prev1,*prev2, *x, *y;
prev1 = NULL;
prev2 = NULL;
temp=head;
int flag1 = 1, flag2 = 1;
while(temp!=NULL)
{
if(temp->a!=x1 && temp->a!=y1)
{
//both not found.
if(flag1 == 1 && flag2 == 1)
{
prev1 = temp;
prev2 = temp;
temp=temp->next;
}
if(flag1 == 0 && flag2 == 1)
{
prev2 = temp;
temp=temp->next;
}
if(flag1 == 1 && flag2 == 0)
{
prev1 = temp;
temp=temp->next;
}
}
if(temp->a == x1)
{
flag1 = 0;
x = temp;
//y yet not found.
if(flag2 == 1)
{
prev2 = temp;
temp=temp->next;
}
else
{
break;
}
}
if(temp->a == y1)
{
flag2 = 0;
y = temp;
//x yet not found.
if(flag1 == 1)
{
prev1 = temp;
temp=temp->next;
}
else
{
break;
}
}
}
//now prev1 and prev2 are previous nodes to x and y.
if(x != head && y!=head)
{
prev1->next = y;
node *temp1 = y->next;
y->next = x->next;
prev2->next = x;
x->next = temp1;
}
if( x == head)
{
node *y1 = y;
node *temp1 = y->next;
y->next = x->next;
prev2->next = x;
x->next = temp1;
head = y1;
}
if( y == head)
{
node *x1 = x;
node *temp1 = x->next;
x->next = y->next;
prev1->next = y;
y->next = temp1;
head = x1;
}
}
int main()
{
head = NULL;
int n;
cin>>n;
while(n--)
{
create();
}
swaplist(1,4);
traverse();
}
|
#ifndef DEFINE_H
#define DEFINE_H
#include <QString>
#include <optional>
namespace hls {
class Define {
public:
std::optional<QString> name() const;
void setName(const std::optional<QString> &name);
std::optional<QString> value() const;
void setValue(const std::optional<QString> &value);
std::optional<QString> import() const;
void setImport(const std::optional<QString> &import);
private:
std::optional<QString> mName;
std::optional<QString> mValue;
std::optional<QString> mImport;
};
}
#endif // DEFINE_H
|
#include <iostream>
#include <vector>
bool isPrime(int n)
{
for(int i = 2; i * i <= n;i++)
{
if(n % i == 0)
return false;
}
return true;
}
int countPrimes(int n)
{
vector<bool> isPrim(n,true);
for(int i = 2;i * i < n; i++)
{
if(isPrim[i])
for(int j = i * i; j < n; j+=i)
isPrim[j] = false;
}
int count = 0;
for(int i = 2; i < n; i++)
if(isPrim[i])
count++;
return count;
}
|
#include <iostream>
using namespace std;
class {
public:
void fun(){
cout<<"Hello World";
}
}a;
int main(){
a.fun();
return 0;
}
|
#include <iostream>
#include <vector>
using namespace std;
string soliMensaje() ;
int soliCantidadMensaje() ;
vector<string> matriz() ;
template <typename T>
void mostrarMatriz( vector<T> ) ;
int main()
{
vector<string> mensaje ;
mensaje = matriz() ;
cout << "Mostrar contenido de la matriz" << endl ;
mostrarMatriz( mensaje ) ;
return 0 ;
}
string soliMensaje()
{
string frase = "" ;
while( true )
{
cout << "Ingrese un mensaje de 10 caracteres como maximo." << endl ;
cout << "Ingrese mensaje: " ; cin >> frase ;
if( frase.size() < 0 && frase.size() > 10 ) cout << "Mensaje excede largo permitido." << endl ;
else break ;
}
return frase ;
} // fin soliMensaje
int soliCantidadMensaje()
{
int valor = 0 ;
while( true )
{
cout << "Ingrese la cantidad de mensajes que desea ingresar: " ; cin >> valor ;
if( valor < 0 ) cout << "Valor ingresado no valido." << endl ;
else break ;
}
return valor ;
}
vector<string> matriz()
{
vector<string> mensaje ;
int cantidad = 0 ;
cantidad = soliCantidadMensaje() ;
while( cantidad != 0 )
{
mensaje.push_back( soliMensaje() ) ;
cantidad-- ;
}
return mensaje ;
} // fin matriz
template <typename T>
void mostrarMatriz( vector<T> matriz )
{
for( int i = 0 ; i < matriz.size() ; i++ )
{
if( i == matriz.size() - 1 ) cout << matriz.at(i) << endl ;
else cout << matriz.at(i) << " " ;
}
} // fin mostrarMatriz
|
#ifndef DIALOGFILTER_H
#define DIALOGFILTER_H
// Qt
#include <QDialog>
#include <QList>
#include <QToolBar>
#include <QAction>
#include <QActionGroup>
#include <QThreadPool>
#include <QMessageBox>
#include <QProgressBar>
#include <QStackedWidget>
#include <QTreeWidget>
#include <QTreeWidgetItem>
// Grids
#include "../Grids/Grid.h"
#include "../Grids/RegularGrid.h"
// Filters
#include "../Filters/Filter.h"
#include "../Filters/AverageDeviation.h"
#include "../Filters/StandardDeviation.h"
// Forms
#include "../Forms/FormAverageDeviation.h"
#include "../Forms/FormStandardDeviation.h"
#include "../Forms/FormRegularGrid.h"
// Point Cloud
#include "../DataTypes.h"
namespace Ui {
class DialogFilter;
}
class DialogFilter : public QDialog
{
Q_OBJECT
public:
explicit DialogFilter(QWidget *parent = 0);
~DialogFilter();
void SetCloud(PointCloudT *newCloud);
private:
Ui::DialogFilter *ui;
QToolBar *toolbar;
QActionGroup *actiongroup;
PointCloudT *cloud;
QList<Filter*> filterList;
QList<Grid*> gridList;
QList<QObject*> itemList;
QList<QAction*> actionList;
QList<QWidget*> formList;
QTreeWidgetItem *filterParent;
QTreeWidgetItem *gridParent;
int currentStep;
void Initialize();
void AddAverageDeviationFilter();
void AddStandardDeviationFilter();
void AddRegularGrid();
protected slots:
void itemSelected(QTreeWidgetItem* item, int);
void moveFilterRight();
void moveFilterLeft();
void removeFilter();
void selectFilter(QAction *action);
void startFilter();
void filterError(QString error);
void filterStarted();
void filterProgress(int val);
void filterFinished(PointCloudT *filterCloud);
void gridError(QString error);
void gridStarted();
void gridProgress(int val);
void gridFinished(Grid *grid);
signals:
void filterComplete(PointCloudT*);
void filterComplete(Grid*);
};
#endif // DIALOGFILTER_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2012 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*
* Code in this file has been copied from adjunct/quick/managers/DesktopExtensionsManager.cpp
* For history prior to 20th Dec 2010, see there...
*
*/
#include "core/pch.h"
#ifdef EXTENSION_SUPPORT
#include "adjunct/quick/extensions/ExtensionUIListener.h"
#include "adjunct/quick/managers/DesktopExtensionsManager.h"
void ExtensionUIListener::OnExtensionSpeedDialInfoUpdated(OpWindowCommander* commander)
{
OpGadget* gadget = commander->GetGadget();
if (!gadget)
return;
g_desktop_extensions_manager->ExtensionDataUpdated(gadget->GetIdentifier());
}
void ExtensionUIListener::OnExtensionUIItemAddRequest(OpWindowCommander* commander, ExtensionUIItem* item)
{
OP_ASSERT(commander && item && item->callbacks);
if (!item || !item->callbacks) return; // should not happen, but not much we could do here
if (BlockedByPolicy(commander, item))
{
item->callbacks->ItemAdded(item->id, ItemAddedNotSupported);
return;
}
OP_STATUS status = OpStatus::ERR;
switch (item->parent_id)
{
case CONTEXT_TOOLBAR:
{
ExtensionButtonComposite *button = g_desktop_extensions_manager->GetButtonFromModel(item->id);
if (button)
status = UpdateExtensionButton(item);
else
status = CreateExtensionButton(item, commander->GetGadget());
break;
}
case CONTEXT_NONE:
case CONTEXT_PAGE:
case CONTEXT_SELECTION:
case CONTEXT_LINK:
case CONTEXT_EDITABLE:
case CONTEXT_IMAGE:
case CONTEXT_VIDEO:
case CONTEXT_AUDIO:
case CONTEXT_LAST_BUILTIN:
default:
item->callbacks->ItemAdded(item->id, ItemAddedContextNotSupported);
return;
}
if (OpStatus::IsSuccess(status))
item->callbacks->ItemAdded(item->id, ItemAddedSuccess);
else if (OpStatus::IsMemoryError(status))
item->callbacks->ItemAdded(item->id, ItemAddedResourceExceeded);
else
item->callbacks->ItemAdded(item->id, ItemAddedFailed);
}
void ExtensionUIListener::OnExtensionUIItemRemoveRequest(OpWindowCommander* commander,
ExtensionUIItem* item)
{
OP_ASSERT(item);
if (!item) return;
OP_STATUS status = DeleteExtensionButton(item);
// item->callbacks is null when opera is closing and core is cleaning up
if (!item->callbacks) return; //not much we could do here
if (OpStatus::IsSuccess(status))
item->callbacks->ItemRemoved(item->id, ItemRemovedSuccess);
else
item->callbacks->ItemRemoved(item->id, ItemRemovedFailed);
}
OP_STATUS ExtensionUIListener::CreateExtensionButton(ExtensionUIItem* item,
OpGadget *gadget)
{
OP_ASSERT(!g_desktop_extensions_manager->GetButtonFromModel(item->id));
RETURN_IF_ERROR(g_desktop_extensions_manager->CreateButtonInModel(item->id));
ExtensionButtonComposite *button = g_desktop_extensions_manager->GetButtonFromModel(item->id);
button->SetGadgetId(gadget->GetIdentifier());
button->UpdateUIItem(item);
RETURN_IF_ERROR(button->CreateOpExtensionButton(item->id));
return OpStatus::OK;
}
OP_STATUS ExtensionUIListener::UpdateExtensionButton(ExtensionUIItem* item)
{
ExtensionButtonComposite *button = g_desktop_extensions_manager->GetButtonFromModel(item->id);
OP_ASSERT(button);
RETURN_IF_ERROR(button->UpdateUIItem(item));
return OpStatus::OK;
}
OP_STATUS ExtensionUIListener::DeleteExtensionButton(ExtensionUIItem* item)
{
ExtensionButtonComposite *button = g_desktop_extensions_manager->GetButtonFromModel(item->id);
OP_ASSERT(button);
RETURN_IF_ERROR(button->RemoveOpExtensionButton(item->id));
RETURN_IF_ERROR(g_desktop_extensions_manager->DeleteButtonInModel(item->id));
return OpStatus::OK;
}
BOOL ExtensionUIListener::BlockedByPolicy(OpWindowCommander* commander, ExtensionUIItem* item)
{
OP_ASSERT(commander->GetGadget() && item);
switch (item->parent_id)
{
case CONTEXT_TOOLBAR:
{
if (commander->GetGadget()->IsFeatureRequested("opera:speeddial"))
return TRUE;
break;
}
case CONTEXT_NONE:
case CONTEXT_PAGE:
case CONTEXT_SELECTION:
case CONTEXT_LINK:
case CONTEXT_EDITABLE:
case CONTEXT_IMAGE:
case CONTEXT_VIDEO:
case CONTEXT_AUDIO:
case CONTEXT_LAST_BUILTIN:
default:
return FALSE;
}
return FALSE;
}
#endif //EXTENSION_SUPPORT
|
#pragma once
#include <string>
using namespace std;
class Sportsman
{
public:
Sportsman() = default;
Sportsman(string FIO, double height, double weight);
double GetHeight() const;
double GetWeight() const;
string GetFIO() const;
private:
string m_FIO;
double m_height;
double m_weight;
};
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#ifndef SAVEWITHINLINE_H
#define SAVEWITHINLINE_H
#ifdef SAVE_SUPPORT
#include "modules/url/url2.h"
#include "modules/upload/upload.h"
class Window;
#define FILENAME_BUF_SIZE 1024
BOOL SafeTypeToSave(Markup::Type element_type, URL content);
class SavedUrlCache
{
private:
struct url_and_filename {
URL url;
uni_char name[14]; /* ARRAY OK 2009-02-05 stighal */
} m_array[1024]; /* ARRAY OK 2009-02-05 stighal */
int m_used;
uni_char m_filename_buf[FILENAME_BUF_SIZE]; /* ARRAY OK 2009-05-11 stighal */
// Points to the end of the relative directory, i.e. where the filename should go
uni_char* m_filename_start;
// Points to the base directory
uni_char* m_reldir_start;
public:
SavedUrlCache(const uni_char* fname);
const uni_char* GetSavedFilename(const URL& url, BOOL& new_filename);
const uni_char* GetPathname() const { return m_filename_buf; }
const uni_char* GetFilenameStart() const { return m_filename_start;}
const uni_char* GetReldirStart() const { return m_reldir_start; }
};
class SaveWithInlineHelper
{
public:
/**
* Save a document and its sub-resources to disk.
* @param url The URL of the document to save.
* @param displayed_doc Pointer to the FramesDocument representing the
* document we are about to save, or NULL if not available.
* @param force_encoding Force document to be written using a specific
* encoding, NULL if you want to use the document encoding.
* @param fname File name to save the parent document to.
* @param window The window that requested the document to be saved.
* Any errors are reported to its associated WindowCommander.
* @param frames_only Only save linked frames if set to TRUE.
*/
static OP_STATUS Save(URL& url, FramesDocument *displayed_doc, const uni_char* fname, const char *force_encoding, Window *window, BOOL frames_only = FALSE);
/** @overload */
static void SaveL(URL& url, FramesDocument *displayed_doc, const uni_char* fname, const char *force_encoding, Window *window, BOOL frames_only);
/** @overload */
static OP_STATUS Save(URL& url, FramesDocument *displayed_doc, const uni_char* fname, const char *force_encoding, SavedUrlCache* su_cache, Window *window, BOOL frames_only = FALSE);
/** @overload */
static void SaveL(URL& url, FramesDocument *displayed_doc, const uni_char* fname, const char *force_encoding, SavedUrlCache* su_cache, Window *window, BOOL frames_only = FALSE, BOOL main_page = TRUE);
};
#ifdef MHTML_ARCHIVE_SAVE_SUPPORT
class SaveAsArchiveHelper
{
public:
/** Save the URL including all inline files (images, CSS, scripts etc.)
* in one MHTML (MIME multipart encoded) file. Links to other documents
* however are not followed or included.
*
* @param url URL of the top document to save
* @param fname Filename to save the file as. Must be a full path.
* @return OP_STATUS
*/
static OP_STATUS Save(URL& url, const uni_char* fname, Window *window);
/** Save the URL including all inline files (images, CSS, scripts etc.)
* in one MHTML (MIME multipart encoded) file. Links to other documents
* however are not followed or included. Return original page size and
* page size after saving.
*
* @param url URL of the top document to save
* @param fname Filename to save the file as. Must be a full path.
* @param max_size The maximum size in bytes that the saved page is allowed
* to use. 0 for no limit. If the page would exceed the limit,
* Opera will try to reduce its size, by ommiting parts of the
* document, or fail to save it the page can't be reduced to a
* sufficiently small size.
* @param page_size Pointer to a variable that'll get original page size
* @param saved_size Pointer to a variable that'll get saved page size
* @return OP_STATUS
*/
static OP_STATUS SaveAndReturnSize(URL& url, const uni_char* fname, Window *window,
unsigned int max_size = 0, unsigned int* page_size = NULL, unsigned int* saved_size = NULL);
/** Save the URL including all inline files (images, CSS, scripts etc.)
* in one MHTML (MIME multipart encoded) file. Links to other documents
* however are not followed or included.
*
* @param url URL of the top document to save
* @param fname Filename to save the file as. Must be a full path.
* @param max_size See Save()
* @param page_size Pointer to a variable that'll get original page size
* @param saved_size Pointer to a variable that'll get saved page size
*/
static void SaveL(URL& url, const uni_char* fname, Window *window,
unsigned int max_size = 0,
unsigned int* page_size = NULL,
unsigned int* saved_size = NULL);
/** Save the URL including all inline files (images, CSS, scripts etc.)
* in one MHTML (MIME multipart encoded) Upload_Multipart archive. Links to other documents
* however are not followed or included.
*
* @param url URL of the top document to save
* @param archive Upload_Multipart where to save the document.
* @param mail_message Whether the URL is a mail message or not
*/
static void GetArchiveL(URL& top_url, Upload_Multipart& archive, Window *window, BOOL mail_message = FALSE);
private:
/** Reorder the files so that the root page comes first, followed by any other
* html/xhtml/xml file, then svg files, then css files, and finaly images,
* scripts, and other files in no specific order. The root page is assumed to
* be the first item in the received parameter.
*
* @param archive The multipart document that should be reordered
*/
static void SortArchive(Upload_Multipart &archive);
};
#endif // MHTML_ARCHIVE_SAVE_SUPPORT
#endif // SAVE_SUPPORT
#endif // SAVEWITHINLINE_H
|
/*!
* \file mpost.h
* \author Simon Coakley
* \date 2012
* \copyright Copyright (c) 2012 University of Sheffield
* \brief Header file for mpost
*/
#ifndef MPOST_H_
#define MPOST_H_
#include <QMetaType>
#include <QPainter>
#include "./variable.h"
#include "./memorymodel.h"
struct statement {
QString lhs;
QString op;
QString rhs;
double drhs;
bool isVariable;
bool isValid;
};
typedef statement statement;
class Mpost {
public:
enum EditMode { Editable, ReadOnly };
Mpost(QString n = "", QString op = "", int v = 0, bool enabled = false);
void paint(QPainter *painter, const QRect &rect,
const QPalette &palette, EditMode mode) const;
QString name() const { return myName; }
QString name2() const { return myName2; }
int value() const { return myValue; }
void setName(QString n) { myName = n; }
void setName2(QString n) { myName2 = n; }
void setValue(int v) { myValue = v; }
bool enabled() const { return myEnabled; }
void setEnabled(bool enabled) { myEnabled = enabled; }
QString op() const { return myOp; }
void setOp(QString o) { myOp = o; }
int value2() const { return myValue2; }
void setValue2(int v) { myValue2 = v; }
QString getText();
void setText(QString t);
void setMemory(MemoryModel * m) { memory = m; }
QList<statement> getStatements() { return statements; }
private:
bool myEnabled;
QString myName;
QString myName2;
int myValue;
QString myOp;
int myValue2;
QString text;
QList<statement> statements;
MemoryModel * memory;
};
Q_DECLARE_METATYPE(Mpost)
#endif // MPOST_H_
|
//
// Created by Dawid Szymański on 2019-06-01.
//
#include <iostream>
int exercise07() {
int length, temporary = -1, sum = 0;
std::cout << "Podaj wielkosc tablicy : ";
std::cin >> length;
int table[length];
if (length <=0) {
std::cout << "Unprocessable Entity";
return 422;
}
for (int i = 0; i < length; i++) {
std::cout << "Podaj " << i << " element tablicy: ";
std::cin >> table[i];
sum += table[i];
}
std::cout << "Pierwszy element: " << table[0] << std::endl;
std::cout << "Cala tablica: [";
for (int i = 0; i < length; i++) {
if (i != 0) std::cout << ", ";
std::cout << table[i];
}
std::cout << "]" << std::endl;
std::cout << "Miedzy ostatnim a pierszym: " << table[length] - table[0] << std::endl;
std::cout << "Suma elementow: " << sum << std::endl;
while (temporary < 0 || temporary > length) {
std::cout << "Ktory element chcesz zbadac?" << std::endl;
std::cin >> temporary;
if (temporary < 0 || temporary > length) {
std::cout << "Index poza tablica :( Elementow jest " << length << std::endl;
}
}
std::cout << temporary << " element tablicy to: " << table[temporary - 1] << std::endl;
return 0;
}
|
#include<iostream>
#include"graph-parser-utilities.h"
using namespace std;
int main()
{
graph *A = new graph();
string inp;
while(true)
{
A->currentState();
cout<<"\nWhere to next? ";
if(inp=="stop")
break;
cin>>inp;
A->moveTo(inp);
}
}
|
#ifndef BATTLE_SYSTEM_H
#define BATTLE_SYSTEM_H
#include <map>
#include "../Internal/SingletonTemplate.h"
#include "../AI/AIBase.h"
#include "../Objects/Characters/CharacterEntity.h"
#include "../Objects/Characters/Player.h"
using std::map;
class BattleSystem : public SingletonTemplate<BattleSystem>
{
map<size_t, CharacterEntity*> PlayerTroops;
map<size_t, CharacterEntity*> AITroops;
map<size_t, map<size_t, Skill*>> PlayerTroopSkills;
CharacterEntity* SelectedTroop;
CharacterEntity* SelectedEnemyTroop;
Skill* SelectedSkill;
size_t DisplaySkillNum;
size_t TurnCost;
size_t PlayerStatus;
int PlayerWon;
bool PlayerTurn;
public:
BattleSystem();
~BattleSystem();
// Initialising
void Init();
// Setters
void SetPlayerTroops(size_t position, CharacterEntity* Troop);
void SetAITroops(size_t position, CharacterEntity* Troop);
void SetPlayerTroopSkills(size_t playerPosition, size_t skillPosition);
void SetPlayerTurn(bool newPlayerTurn);
void SetSelectedTroop(CharacterEntity* newSelectedTroop);
inline void SetSelectedEnemyTroop(CharacterEntity* newSelectedEnemyTroop){ SelectedEnemyTroop = newSelectedEnemyTroop; };
inline void SetSelectedSkill(Skill* newSelectedskill){ SelectedSkill = newSelectedskill; };
inline void SetDisplaySkillNum(size_t newDisplaySkillNum){ DisplaySkillNum = newDisplaySkillNum; };
inline void SetTurnCost(size_t newTurnCost) { TurnCost = newTurnCost; };
inline void SetPlayerWon(int newPlayerWon) { PlayerWon = newPlayerWon; };
// Getters
size_t GetSelectedTroopPosition();
size_t GetNumberOfAITroopAlive();
size_t GetNumberOfPlayerTroopAlive();
size_t GetSelectedEnemyTroopPosition();
CharacterEntity* GetPlayerTroopAttacking(size_t position);
Skill* GetSelectedSkill(size_t position);
inline map<size_t, CharacterEntity*>& GetPlayerTroops() { return PlayerTroops; };
inline map<size_t, CharacterEntity*>& GetAITroops() { return AITroops; };
inline map<size_t, Skill*>& GetPlayerTroopSkills(size_t position) { return PlayerTroopSkills.at(position); };
inline CharacterEntity* GetAITroopAttacking(size_t position) { return AITroops.find(position)->second; };
inline CharacterEntity* GetSelectedTroop() { return SelectedTroop; };
inline CharacterEntity* GetSelectedEnemyTroop() { return SelectedEnemyTroop; };
inline Skill* GetSkillInMap(size_t Character, size_t Skill_Pos) { return PlayerTroopSkills.at(Character).at(Skill_Pos); };
inline Skill* GetSelectedSkill() { return SelectedSkill; };
inline size_t GetDisplaySkillNum(){ return DisplaySkillNum; };
inline size_t GetTurnCost(){ if (TurnCost <= 0) TurnCost = 0; return TurnCost; };
inline int GetPlayerWon(){ return PlayerWon; };
inline bool GetPlayerTurn(){ return PlayerTurn; };
// Use this at every start of scene battles
void CheckTroopPositions();
// Switching Spots
void SwitchSpots(map<size_t, CharacterEntity*>& TroopMap, size_t FirstPosition, size_t SecondPosition);
void MoveTroopBackByOne(map<size_t, CharacterEntity*>& TroopMap);
void MoveTroopBackByTwo(map<size_t, CharacterEntity*>& TroopMap);
void MoveTroopFrontByOne(map<size_t, CharacterEntity*>& TroopMap);
void MoveTroopFrontByTwo(map<size_t, CharacterEntity*>& TroopMap);
// Damage Calculations all here
size_t DamageCalculation(size_t target, Skill* AttackerSkill);
// Buffing or Healing goes here
void ApplyFriendlyEffect(size_t TargettedTeammate, Skill* SkillUsed);
// Status Effect Calculations all here
void SetStatusEffect(size_t target, Skill* skillUsed);
// Checking if Skill can be activated
bool CanActivateSkill(CharacterEntity* Attacker, size_t Target, Skill* AttackerSkill);
void Reset();
void ClearWave();
void Debugging();
};
#endif
|
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
string a;
string b;
string c;
cin >> a;
cin >> b;
cin >> c;
vector<int> aCount(26);
vector<int> bCount(26);
vector<int> cCount(26);
for(int i = 0; i < a.size(); ++i) {
++aCount[a[i] - 'a'];
}
for(int i = 0; i < b.size(); ++i) {
++bCount[b[i] - 'a'];
}
for(int i = 0; i < c.size(); ++i) {
++cCount[c[i] - 'a'];
}
int max = 0;
int num = 0;
bool poss = true;
for(int i = 0; poss; ++i) {
int minC = 99999999;
for(int j = 0; j < aCount.size(); ++j) {
int total = aCount[j];
total -= bCount[j] * i;
if(total < 0) {
poss = false;
} else if(cCount[j] != 0){
total /= cCount[j];
if(total < minC) {
minC = total;
}
}
}
if(poss && max < i + minC) {
max = i + minC;
num = i;
}
}
string result = "";
int accC = max - num;
for(int i = 0; i < num; ++i) {
result += b;
}
for(int i = 0; i < accC; ++i) {
result += c;
}
for(int i = 0; i < aCount.size(); ++i) {
aCount[i] -= num * bCount[i];
aCount[i] -= accC * cCount[i];
for(; 0 < aCount[i]; --aCount[i]) {
result += (char)('a' + i);
}
}
cout << result << endl;
}
|
#include <QDate>
#include <QStringList>
#include <iostream>
using std::cout;
using std::endl;
static const unsigned int grades[4] = { 1, 2, 5, 8 };
static const QStringList kids = QStringList() << "A" << "E" << "K" << "S";
static const QStringList gradeNames = QStringList() << "Kindergarten"
<< "First Grade"
<< "Second Grade"
<< "Third Grade"
<< "Fourth Grade"
<< "Fifth Grade"
<< "Sixth Grade"
<< "Seventh Grade"
<< "Eighth Grade"
<< "Freshman High School"
<< "Sophomore High School"
<< "Junior High School"
<< "Senior High School"
<< "Freshman College"
<< "Sophomore College"
<< "Junior College"
<< "Senior College"
<< "Graduated";
int main(int, char**)
{
QDate today; //(2030, 10,1);
QDate startOfSchool( 2017, 9, 1 );
QDate startOfSummer( 2018, 6, 7 );
unsigned int addYears = 0;
while( today > startOfSummer ) {
addYears++;
startOfSchool = startOfSchool.addYears(1);
startOfSummer = startOfSummer.addYears(1);
}
if (startOfSchool > today) {
cout << "In September, kids will be entering:" << endl;
} else {
cout << "Kids are in:" << endl;
}
for (int i = 0; i < 4; i++) {
unsigned int gradeIdx = grades[i]+addYears;
if (gradeIdx >= gradeNames.size()) gradeIdx = gradeNames.size()-1;
cout << gradeNames[gradeIdx].toStdString()
<< " for " << kids[i].toStdString() << endl;
}
return 0;
}
|
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
OpenGLDrv.h: Public OpenGL RHI definitions.
=============================================================================*/
#pragma once
// Dependencies.
//#include "Core.h"
#include "RHI.h"
#include "DynamicRHI.h"
#include "OPENGL_Include.h"
// OpenGL RHI public headers.
#include "OpenGLUtil.h"
#include "OpenGLState.h"
#include "OpenGLResources.h"
class EGLService;
/** The interface which is implemented by the dynamically bound RHI. */
class FOpenGLDynamicRHI : public FDynamicRHI, public IRHICommandContext
{
public:
friend class FOpenGLViewport;
/** Initialization constructor. */
FOpenGLDynamicRHI();
/** Destructor */
~FOpenGLDynamicRHI() {}
// FDynamicRHI interface.
virtual void Init();
virtual void Shutdown();
template<typename TRHIType>
static FORCEINLINE typename TOpenGLResourceTraits<TRHIType>::TConcreteType* ResourceCast(TRHIType* Resource)
{
return static_cast<typename TOpenGLResourceTraits<TRHIType>::TConcreteType*>(Resource);
}
virtual FSamplerStateRHIRef RHICreateSamplerState(const FSamplerStateInitializerRHI& Initializer) final override;
virtual FRasterizerStateRHIRef RHICreateRasterizerState(const FRasterizerStateInitializerRHI& Initializer) final override;
virtual FDepthStencilStateRHIRef RHICreateDepthStencilState(const FDepthStencilStateInitializerRHI& Initializer) final override;
virtual FBlendStateRHIRef RHICreateBlendState(const FBlendStateInitializerRHI& Initializer) final override;
virtual FVertexDeclarationRHIRef RHICreateVertexDeclaration(const FVertexDeclarationElementList& Elements) final override;
virtual FPixelShaderRHIRef RHICreatePixelShader(const char* Code) final override;
virtual FVertexShaderRHIRef RHICreateVertexShader(const char* Code) final override;
virtual FBoundShaderStateRHIRef RHICreateBoundShaderState(FVertexDeclarationRHIParamRef VertexDeclaration, FVertexShaderRHIParamRef VertexShader, FPixelShaderRHIParamRef PixelShader) final override;
virtual FBoundBufferStateRHIRef RHICreateBoundBufferState(const FBoundBufferDesc& Desc, FRHIVertexDeclaration* VertexDeclaration) final override;
virtual FUniformBufferRHIRef RHICreateUniformBuffer(const void* Contents, const FRHIUniformBufferLayout& Layout, EUniformBufferUsage Usage) final override;
virtual FIndexBufferRHIRef RHICreateIndexBuffer(uint32 Stride, uint32 Size, uint32 InUsage, FRHIResourceCreateInfo& CreateInfo) final override;
virtual FVertexBufferRHIRef RHICreateVertexBuffer(uint32 Size, uint32 InUsage, FRHIResourceCreateInfo& CreateInfo) final override;
virtual FTexture2DRHIRef RHICreateTexture2D(uint32 SizeX, uint32 SizeY, uint8 Format, uint32 NumMips, uint32 NumSamples, uint32 Flags, FRHIResourceCreateInfo& CreateInfo) final override;
//virtual FShaderResourceViewRHIRef RHICreateShaderResourceView(FTexture2DRHIParamRef Texture2DRHI, uint8 MipLevel) final override;
//virtual FShaderResourceViewRHIRef RHICreateShaderResourceView(FTexture2DRHIParamRef Texture2DRHI, uint8 MipLevel, uint8 NumMipLevels, uint8 Format) final override;
//virtual FShaderResourceViewRHIRef RHICreateShaderResourceView(FTexture3DRHIParamRef Texture3DRHI, uint8 MipLevel) final override;
//virtual FShaderResourceViewRHIRef RHICreateShaderResourceView(FTexture2DArrayRHIParamRef Texture2DArrayRHI, uint8 MipLevel) final override;
//virtual FShaderResourceViewRHIRef RHICreateShaderResourceView(FTextureCubeRHIParamRef TextureCubeRHI, uint8 MipLevel) final override;
virtual void RHIGenerateMips(FTextureRHIParamRef Texture) final override;
virtual FTextureCubeRHIRef RHICreateTextureCube(uint32 Size, uint8 Format, uint32 NumMips, uint32 Flags, FRHIResourceCreateInfo& CreateInfo) final override;
//virtual FViewportRHIRef RHICreateViewport(void* WindowHandle, uint32 SizeX, uint32 SizeY, bool bIsFullscreen, EPixelFormat PreferredPixelFormat) final override;
//virtual void RHIResizeViewport(FViewportRHIParamRef Viewport, uint32 SizeX, uint32 SizeY, bool bIsFullscreen) final override;
virtual FRHIRenderTarget* RHICreateRenderTarget(const FRHISetRenderTargetsInfo& Info) final override;
virtual void RHISetRasterizerState(FRasterizerStateRHIParamRef NewState) final override;
virtual void RHISetViewport(uint32 MinX, uint32 MinY, float MinZ, uint32 MaxX, uint32 MaxY, float MaxZ) final override;
virtual void RHISetScissorRect(bool bEnable, uint32 MinX, uint32 MinY, uint32 MaxX, uint32 MaxY) final override;
virtual void RHISetBoundShaderState(FBoundShaderStateRHIParamRef BoundShaderState) final override;
virtual void RHISetBoundBufferState(FBoundBufferStateRHIParamRef BoundBufferState) final override;
virtual void RHISetShaderTexture(FVertexShaderRHIParamRef VertexShader, uint32 TextureIndex, FTextureRHIParamRef NewTexture) final override;
virtual void RHISetShaderTexture(FPixelShaderRHIParamRef PixelShader, uint32 TextureIndex, FTextureRHIParamRef NewTexture) final override;
virtual void RHISetShaderSampler(FVertexShaderRHIParamRef VertexShader, uint32 SamplerIndex, FSamplerStateRHIParamRef NewState) final override;
virtual void RHISetShaderSampler(FPixelShaderRHIParamRef PixelShader, uint32 SamplerIndex, FSamplerStateRHIParamRef NewState) final override;
//virtual void RHISetShaderUniformBuffer(FVertexShaderRHIParamRef VertexShader, uint32 BufferIndex, FUniformBufferRHIParamRef Buffer) final override;
//virtual void RHISetShaderUniformBuffer(FPixelShaderRHIParamRef PixelShader, uint32 BufferIndex, FUniformBufferRHIParamRef Buffer) final override;
//virtual void RHISetShaderParameter(FVertexShaderRHIParamRef VertexShader, uint32 BufferIndex, uint32 BaseIndex, uint32 NumBytes, const void* NewValue) final override;
//virtual void RHISetShaderParameter(FPixelShaderRHIParamRef PixelShader, uint32 BufferIndex, uint32 BaseIndex, uint32 NumBytes, const void* NewValue) final override;
virtual void RHISetDepthStencilState(FDepthStencilStateRHIParamRef NewState, uint32 StencilRef) final override;
//virtual void RHISetBlendState(FBlendStateRHIParamRef NewState, const FLinearColor& BlendFactor) final override;
//virtual void RHISetRenderTargets(uint32 NumSimultaneousRenderTargets, const FRHIRenderTargetView* NewRenderTargets, const FRHIDepthRenderTargetView* NewDepthStencilTarget, uint32 NumUAVs, const FUnorderedAccessViewRHIParamRef* UAVs) final override;
//virtual void RHISetRenderTargetsAndClear(const FRHISetRenderTargetsInfo& RenderTargetsInfo) final override;
virtual void RHISetRenderTarget(FRHIRenderTarget* RenderTarget) final override;
virtual void RHIDrawPrimitive(uint32 PrimitiveType, uint32 BaseVertexIndex, uint32 NumPrimitives, uint32 NumInstances) final override;
virtual void RHIDrawIndexedPrimitive(FIndexBufferRHIParamRef IndexBuffer, uint32 PrimitiveType, int32 BaseVertexIndex, uint32 FirstInstance, uint32 NumVertices, uint32 StartIndex, uint32 NumPrimitives, uint32 NumInstances) final override;
virtual void RHIClear(bool bClearColor, const FLinearColor& Color, bool bClearDepth, float Depth, bool bClearStencil, uint32 Stencil, FIntRect ExcludeRect) final override;
virtual void RHIClearMRT(bool bClearColor, int32 NumClearColors, const FLinearColor* ColorArray, bool bClearDepth, float Depth, bool bClearStencil, uint32 Stencil, FIntRect ExcludeRect) final override;
// virtual void RHIEnableDepthBoundsTest(bool bEnable, float MinDepth, float MaxDepth) final override;
void CachedSetupTextureStage(FOpenGLContextState& ContextState, GLint TextureIndex, GLenum Target, GLuint Resource, GLint BaseMip, GLint NumMips);
FOpenGLContextState& GetContextStateForCurrentContext();
void CachedBindArrayBuffer( FOpenGLContextState& ContextState, GLuint Buffer )
{
VERIFY_GL_SCOPE();
if( ContextState.ArrayBufferBound != Buffer )
{
glBindBuffer( GL_ARRAY_BUFFER, Buffer );
ContextState.ArrayBufferBound = Buffer;
}
}
void CachedBindElementArrayBuffer( FOpenGLContextState& ContextState, GLuint Buffer )
{
VERIFY_GL_SCOPE();
if( ContextState.ElementArrayBufferBound != Buffer )
{
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, Buffer );
ContextState.ElementArrayBufferBound = Buffer;
}
}
void CachedBindPixelUnpackBuffer( FOpenGLContextState& ContextState, GLuint Buffer )
{
VERIFY_GL_SCOPE();
if( ContextState.PixelUnpackBufferBound != Buffer )
{
glBindBuffer( GL_PIXEL_UNPACK_BUFFER, Buffer );
ContextState.PixelUnpackBufferBound = Buffer;
}
}
void CachedBindUniformBuffer( FOpenGLContextState& ContextState, GLuint Buffer )
{
VERIFY_GL_SCOPE();
if( ContextState.UniformBufferBound != Buffer )
{
glBindBuffer( GL_UNIFORM_BUFFER, Buffer );
ContextState.UniformBufferBound = Buffer;
}
}
bool IsUniformBufferBound( FOpenGLContextState& ContextState, GLuint Buffer ) const
{
return ( ContextState.UniformBufferBound == Buffer );
}
/** Add query to Queries list upon its creation. */
//void RegisterQuery( FOpenGLRenderQuery* Query );
///** Remove query from Queries list upon its deletion. */
//void UnregisterQuery( FOpenGLRenderQuery* Query );
/** Inform all queries about the need to recreate themselves after OpenGL context they're in gets deleted. */
void InvalidateQueries();
FOpenGLSamplerState* GetPointSamplerState() const { return (FOpenGLSamplerState*)PointSamplerState.get(); }
FRHITexture* CreateOpenGLTexture(uint32 SizeX, uint32 SizeY, bool CubeTexture, bool ArrayTexture, uint8 Format, uint32 NumMips, uint32 NumSamples, uint32 ArraySize, uint32 Flags, const FClearValueBinding& InClearValue, vector<void*> BulkData);
void SetCustomPresent(class FRHICustomPresent* InCustomPresent);
private:
/** Counter incremented each time RHIBeginScene is called. */
uint32 SceneFrameCounter;
/** Value used to detect when resource tables need to be recached. INDEX_NONE means always recache. */
uint32 ResourceTableFrameCounter;
/** RHI device state, independent of underlying OpenGL context used */
FOpenGLRHIState PendingState;
FOpenGLStreamedVertexBufferArray DynamicVertexBuffers;
// FOpenGLStreamedIndexBufferArray DynamicIndexBuffers;
FSamplerStateRHIRef PointSamplerState;
/** A list of all viewport RHIs that have been created. */
vector<FOpenGLViewport*> Viewports;
shared_ptr<FOpenGLViewport> DrawingViewport;
bool bRevertToSharedContextAfterDrawingViewport;
bool bIsRenderingContextAcquired;
/** Per-context state caching */
FOpenGLContextState SharedContextState;
FOpenGLContextState RenderingContextState;
/** Underlying platform-specific data */
struct FPlatformOpenGLDevice* PlatformDevice;
GLuint GetOpenGLFramebuffer(uint32 NumSimultaneousRenderTargets, FOpenGLTextureBase** RenderTargets, uint32* ArrayIndices, uint32* MipmapLevels, FOpenGLTextureBase* DepthStencilTarget);
void InitializeStateResources();
/** needs to be called before each dispatch call */
void EnableVertexElementCached(FOpenGLContextState& ContextCache, const FOpenGLVertexElement &VertexElement, GLsizei Stride, void *Pointer, GLuint Buffer);
void EnableVertexElementCachedZeroStride(FOpenGLContextState& ContextCache, const FOpenGLVertexElement &VertexElement, uint32 NumVertices, FOpenGLVertexBuffer* VertexBuffer);
void SetupVertexArrays(FOpenGLContextState& ContextCache, uint32 BaseVertexIndex, FOpenGLStream* Streams, uint32 NumStreams, uint32 MaxVertices);
void SetupVertexArraysVAB(FOpenGLContextState& ContextCache, uint32 BaseVertexIndex, FOpenGLStream* Streams, uint32 NumStreams, uint32 MaxVertices);
void SetupVertexArraysUP(FOpenGLContextState& ContextState, void* Buffer, uint32 Stride);
// void SetupBindlessTextures( FOpenGLContextState& ContextState, const TArray<FOpenGLBindlessSamplerInfo> &Samplers );
/** needs to be called before each draw call */
void BindPendingFramebuffer( FOpenGLContextState& ContextState );
void BindPendingShaderState( FOpenGLContextState& ContextState );
void BindPendingBufferState(FOpenGLContextState& ContextState);
void BindPendingComputeShaderState( FOpenGLContextState& ContextState, FComputeShaderRHIParamRef ComputeShaderRHI);
void UpdateRasterizerStateInOpenGLContext( FOpenGLContextState& ContextState );
void UpdateDepthStencilStateInOpenGLContext( FOpenGLContextState& ContextState );
void UpdateScissorRectInOpenGLContext( FOpenGLContextState& ContextState );
void UpdateViewportInOpenGLContext( FOpenGLContextState& ContextState );
template <class ShaderType> void SetResourcesFromTables(const ShaderType* RESTRICT);
void CommitGraphicsResourceTables();
void CommitComputeResourceTables(class FOpenGLComputeShader* ComputeShader);
void CommitNonComputeShaderConstants();
void CommitComputeShaderConstants(FComputeShaderRHIParamRef ComputeShaderRHI);
void SetPendingBlendStateForActiveRenderTargets( FOpenGLContextState& ContextState );
void SetupTexturesForDraw( FOpenGLContextState& ContextState);
template <typename StateType>
void SetupTexturesForDraw( FOpenGLContextState& ContextState, const StateType ShaderState, int32 MaxTexturesNeeded);
public:
/** Remember what RHI user wants set on a specific OpenGL texture stage, translating from Stage and TextureIndex for stage pair. */
void InternalSetShaderTexture(FOpenGLTextureBase* Texture, FOpenGLShaderResourceView* SRV, GLint TextureIndex, GLenum Target, GLuint Resource, int NumMips, int LimitMip);
void InternalSetShaderUAV(GLint UAVIndex, GLenum Format, GLuint Resource);
void InternalSetSamplerStates(GLint TextureIndex, FOpenGLSamplerState* SamplerState);
private:
void ApplyTextureStage(FOpenGLContextState& ContextState, GLint TextureIndex, const FTextureStage& TextureStage, FOpenGLSamplerState* SamplerState);
// void ReadSurfaceDataRaw(FOpenGLContextState& ContextState, FTextureRHIParamRef TextureRHI,FIntRect Rect,TArray<uint8>& OutData, FReadSurfaceDataFlags InFlags);
void BindUniformBufferBase(FOpenGLContextState& ContextState, int32 NumUniformBuffers, FUniformBufferRHIRef* BoundUniformBuffers, uint32 FirstUniformBuffer, bool ForceUpdate);
void ClearCurrentFramebufferWithCurrentScissor(FOpenGLContextState& ContextState, int8 ClearType, int32 NumClearColors, const FLinearColor* ClearColorArray, float Depth, uint32 Stencil);
void FreeZeroStrideBuffers();
/** Consumes about 100ms of GPU time (depending on resolution and GPU), useful for making sure we're not CPU bound when GPU profiling. */
void IssueLongGPUTask();
};
|
//===-- server/server-app.hh - ServerApp class definition -------*- C++ -*-===//
//
// ODB Library
// Author: Steven Lariau
//
//===----------------------------------------------------------------------===//
///
/// \file
/// The master class server side, responsible for controlling all the parts of
/// the debugger: core db, program loop, communication with clients
///
//===----------------------------------------------------------------------===//
#pragma once
#include <functional>
#include <memory>
#include "client-handler.hh"
#include "debugger.hh"
#include "fwd.hh"
namespace odb {
struct ServerConfig {
// If true, the debugger is running
// default is false
// env: ODB_CONF_ENABLED=0/1
bool enabled;
// If true, the execution is stopped before the first instruction
// Used to be able to debug a program from the beginning
// default is false
// env: ODB_CONF_NOSTART=0/1
bool nostart;
// If true, the CLI on Server mode is enabled
// With this mode, the debugguer is controled direcly from the VM process,
// with a CLI reading commands from stdin
// When enabled, the VM is stopped at the beginning and the CLI appears right
// away.
// default is false
// env: ODB_CONF_MODE_SERVER_CLI=0/1
bool mode_server_cli;
// If true and ServerCLI is used, a SIGINT signal handler is set that will
// stop the VM execution This way, it's possible to stop execution and get
// back the command line using Ctrl-C
// default is true
// env: ODB_CONF_SERVER_CLI_SIGHANDLER
bool server_cli_sighandler;
// If true, a TCP server is run.
// Whis this mode, can connect to the Debugger from another process with TCP
// client default is false env: ODB_CONF_MODE_TCP=0/1
bool mode_tcp;
// The port the server listens to in TCP_PORT mode
// default is 12644
// env: ODB_CONF_TCP_PORT=<int>
int tcp_port;
};
/// To setup a DB Server, an instance of this class must be created
/// Main class, responsible for controlling every part of ODB server-side
///
/// It has many options, and can be configured by 2 ways:
/// - with a config object given to the constructor
/// - using the default constructor object (recommended)
/// The default disable everything, the debugger is turned OFF
/// - with env variables that can override config values
class ServerApp {
public:
using api_builder_f = std::function<std::unique_ptr<VMApi>()>;
/// `api_builder` is a functor called when needed to build the debugger core
/// It is never called if the debugger isn't enabled
ServerApp(const ServerConfig &conf, const api_builder_f &api_builder);
/// Instantiate with default config
ServerApp(const api_builder_f &api_builder);
ServerApp(const ServerApp &) = delete;
/// Enter the debugger loop
/// Must be called right before executing each instruction
/// More infos in `docs/design.txt`
void loop();
private:
ServerConfig _conf;
api_builder_f _api_builder;
std::unique_ptr<Debugger> _db;
std::unique_ptr<ClientHandler> _client;
// init debugger
void _init();
// disable debugger and clear all allocated memory
void _shutdown();
// block until `_client` connected
void _connect();
// returns true if db stopped (breakpoint, or exit/crash)
bool _db_is_stopped();
// Stop debugger if not stopped already
void _stop_db();
};
} // namespace odb
|
#include <cppunit/extensions/HelperMacros.h>
#include "cppunit/BetterAssert.h"
#include "model/SensorData.h"
using namespace Poco;
using namespace std;
namespace BeeeOn {
class SensorDataTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(SensorDataTest);
CPPUNIT_TEST(testCreate);
CPPUNIT_TEST(testIterator);
CPPUNIT_TEST(testValueAtIndex);
CPPUNIT_TEST_SUITE_END();
public:
void testCreate();
void testIterator();
void testValueAtIndex();
};
CPPUNIT_TEST_SUITE_REGISTRATION(SensorDataTest);
void SensorDataTest::testCreate()
{
const DeviceID id(0x00000000a2010203UL);
const IncompleteTimestamp timestamp;
SensorData sensorData;
sensorData.setDeviceID(id);
sensorData.setTimestamp(timestamp);
CPPUNIT_ASSERT_EQUAL(id, sensorData.deviceID());
CPPUNIT_ASSERT(sensorData.isEmpty());
CPPUNIT_ASSERT(timestamp == sensorData.timestamp());
CPPUNIT_ASSERT(sensorData == sensorData);
}
void SensorDataTest::testIterator()
{
SensorData sensorData;
sensorData.insertValue({0,1});
sensorData.insertValue({1,2});
sensorData.insertValue({2,3});
CPPUNIT_ASSERT(!sensorData.isEmpty());
size_t i = 0;
for (const auto &value : sensorData) {
CPPUNIT_ASSERT_EQUAL(i, value.moduleID().value());
CPPUNIT_ASSERT_EQUAL(i+1, value.value());
i++;
}
}
void SensorDataTest::testValueAtIndex()
{
SensorData sensorData;
sensorData.insertValue({0,1});
sensorData.insertValue({1,2});
CPPUNIT_ASSERT(!sensorData.isEmpty());
CPPUNIT_ASSERT_EQUAL(2, sensorData.size());
CPPUNIT_ASSERT(SensorValue({0,1}) == sensorData.at(0));
CPPUNIT_ASSERT(SensorValue({1,2}) == sensorData.at(1));
CPPUNIT_ASSERT(SensorValue({0,1}) == sensorData[0]);
CPPUNIT_ASSERT(SensorValue({1,2}) == sensorData[1]);
sensorData.at(0) = {3,4};
sensorData[1] = {5,6};
CPPUNIT_ASSERT(SensorValue({3,4}) == sensorData.at(0));
CPPUNIT_ASSERT(SensorValue({5,6}) == sensorData[1]);
CPPUNIT_ASSERT_THROW(sensorData[42], Poco::RangeException);
CPPUNIT_ASSERT_THROW(sensorData[-1], Poco::RangeException);
}
}
|
#include<iostream>
using namespace std;
struct node
{
int data;
node *next;
}*head;
void addNode(int);
void display();
void reverseLL(node**);
int main()
{
int a[] = {1,23,3,45,5,6,7};
int length = sizeof(a)/sizeof(a[0]);
for(int i=0; i<length; i++)
addNode(a[i]);
display();
reverseLL(&head);
display();
return 0;
}
void addNode(int x)
{
node *temp = new node;
temp->data = x;
temp->next = NULL;
if(head == NULL) {
head = temp;
} else {
node *q;
q = head;
while(q->next != NULL) {
q = q->next;
}
q->next = temp;
}
}
void display()
{
node *q = head;
while(q != NULL) {
cout << q->data << " ";
q = q->next;
}
cout << endl;
}
void reverseLL(node **head_ref)
{
node *first, *rest;
if(*head_ref == NULL)
return ;
first = *head_ref;
rest = first->next;
if(rest == NULL)
return ;
reverseLL(&rest);
first->next->next = first;
first->next = NULL;
*head_ref = rest;
}
|
#include "GreeJniHelper.h"
#include <string.h>
#include "CCDirector.h"
#include "jni/Java_org_cocos2dx_lib_Cocos2dxGreePlatform.h"
using namespace cocos2d;
using namespace cocos2d::gree_extension;
jobject gCreateScoreListenerObj;
extern "C" {
// Score
std::string getScoreIdJni(jobject obj){
JniMethodInfo t;
std::string ret;
if(GreeJniHelper::getInstanceMethodInfo(t, obj, "getId", "()Ljava/lang/String;")){
jstring jstr = (jstring)t.env->CallObjectMethod(obj, t.methodID);
const char* str = NULL;
if(jstr != NULL){
str = t.env->GetStringUTFChars(jstr, 0);
ret = str;
t.env->ReleaseStringUTFChars(jstr, str);
}
t.env->DeleteLocalRef(t.classID);
}
return ret;
}
std::string getScoreNicknameJni(jobject obj){
JniMethodInfo t;
std::string ret;
if(GreeJniHelper::getInstanceMethodInfo(t, obj, "getNickname", "()Ljava/lang/String;")){
jstring jstr = (jstring)t.env->CallObjectMethod(obj, t.methodID);
const char* str = NULL;
if(jstr != NULL){
str = t.env->GetStringUTFChars(jstr, 0);
ret = str;
t.env->ReleaseStringUTFChars(jstr, str);
}
t.env->DeleteLocalRef(t.classID);
}
return ret;
}
std::string getScoreThumbnailUrlJni(jobject obj){
JniMethodInfo t;
std::string ret;
if(GreeJniHelper::getInstanceMethodInfo(t, obj, "getThumbnailUrl", "()Ljava/lang/String;")){
jstring jstr = (jstring)t.env->CallObjectMethod(obj, t.methodID);
const char* str = NULL;
if(jstr != NULL){
str = t.env->GetStringUTFChars(jstr, 0);
ret = str;
t.env->ReleaseStringUTFChars(jstr, str);
}
t.env->DeleteLocalRef(t.classID);
}
return ret;
}
long long getScoreRankJni(jobject obj){
JniMethodInfo t;
long long ret = -1;
if(GreeJniHelper::getInstanceMethodInfo(t, obj, "getRank", "()J")){
ret = t.env->CallLongMethod(obj, t.methodID);
t.env->DeleteLocalRef(t.classID);
}
return ret;
}
long long getScoreJni(jobject obj){
JniMethodInfo t;
long long ret = -1;
if(GreeJniHelper::getInstanceMethodInfo(t, obj, "getScore", "()J")){
ret = t.env->CallLongMethod(obj, t.methodID);
t.env->DeleteLocalRef(t.classID);
}
return ret;
}
std::string getScoreAsStringJni(jobject obj){
JniMethodInfo t;
std::string ret;
if(GreeJniHelper::getInstanceMethodInfo(t, obj, "getScoreAsString", "()Ljava/lang/String;")){
jstring jstr = (jstring)t.env->CallObjectMethod(obj, t.methodID);
const char* str = NULL;
if(jstr != NULL){
str = t.env->GetStringUTFChars(jstr, 0);
ret = str;
t.env->ReleaseStringUTFChars(jstr, str);
}
t.env->DeleteLocalRef(t.classID);
}
return ret;
}
void getScoreThumbnailJni(jobject obj, int size, int** pBuf, int *pw, int *ph){
JniMethodInfo t;
jobject img = NULL;
if(GreeJniHelper::getInstanceMethodInfo(t, obj, "getThumbnail", "(I)Landroid/graphics/Bitmap;")){
img = (jobject)t.env->CallObjectMethod(obj, t.methodID, size);
if(img == NULL){
return;
}
// get raw data
{
jclass jParser = JniHelper::getClassID("org/cocos2dx/lib/gree/NativeBitmapParser", t.env);
if(jParser == NULL){
return;
}
jmethodID method = t.env->GetStaticMethodID(jParser, "getBitmapWidth", "(Ljava/lang/Object;)I");
if(method == NULL){
return;
}
*pw = t.env->CallStaticIntMethod(jParser, method, img);
method = t.env->GetStaticMethodID(jParser, "getBitmapHeight", "(Ljava/lang/Object;)I");
if(method == NULL){
return;
}
*ph = t.env->CallStaticIntMethod(jParser, method, img);
if(*pw > 0 && *ph > 0){
*pBuf = (int*)malloc(*pw * *ph * 4);
if(*pBuf != NULL){
method = t.env->GetStaticMethodID(jParser, "getBitmapData", "(Ljava/lang/Object;)[I");
if(method == NULL){
free(*pBuf);
return;
}
jintArray jArr = (jintArray)t.env->CallStaticObjectMethod(jParser, method, img);
jint* arr = t.env->GetIntArrayElements(jArr, 0);
// convert ARGB -> ABGR
//memcpy(*pBuf, arr, *pw * *ph * 4);
for(int i = 0; i < *pw * *ph; i++){
unsigned int colorData = *((unsigned int *)arr + i);
*((unsigned int*)(*pBuf) + i) = ((colorData & 0xff00ff00) |
((colorData & 0x00ff0000) >> 16) |
((colorData & 0x000000ff) << 16));
}
t.env->ReleaseIntArrayElements(jArr, arr, 0);
}
}
t.env->DeleteLocalRef(jParser);
}
t.env->DeleteLocalRef(t.classID);
}
}
bool loadScoreThumbnailJni(jobject obj, int size, void *delegate){
JniMethodInfo t;
bool ret = false;
if(GreeJniHelper::getInstanceMethodInfo(t, obj, "loadThumbnail", "(ILnet/gree/asdk/api/IconDownloadListener;)Z")){
JniMethodInfo l;
if(JniHelper::getMethodInfo(l, "org/cocos2dx/lib/gree/NativeIconDownloadListener", "<init>", "(JI)V")){
jobject listener = l.env->NewObject(l.classID, l.methodID, (unsigned long long)delegate, (int)fTypeLoadScoreThumbnail);
if(listener == NULL){
CCLog("Cannot create new listener object in %s", __func__);
return ret;
}
ret = t.env->CallBooleanMethod(obj, t.methodID, size, listener);
l.env->DeleteLocalRef(l.classID);
}
t.env->DeleteLocalRef(t.classID);
}
return ret;
}
// Leaderboard
void loadLeaderboardsJni(int startIndex, int count){
JniMethodInfo t;
if(JniHelper::getStaticMethodInfo(t, "net/gree/asdk/api/Leaderboard", "loadLeaderboards", "(IILnet/gree/asdk/api/Leaderboard$LeaderboardListener;)V")){
JniMethodInfo l;
if(JniHelper::getMethodInfo(l, "org/cocos2dx/lib/gree/NativeLeaderboardListener", "<init>", "()V")){
jobject listener = l.env->NewObject(l.classID, l.methodID);
if(listener == NULL){
CCLog("Cannot create new listener object in %s", __func__);
return;
}
t.env->CallStaticVoidMethod(t.classID, t.methodID, startIndex, count, listener);
l.env->DeleteLocalRef(l.classID);
}
t.env->DeleteLocalRef(t.classID);
}
}
std::string getLeaderboardIdJni(jobject obj){
JniMethodInfo t;
std::string ret;
if(GreeJniHelper::getInstanceMethodInfo(t, obj, "getId", "()Ljava/lang/String;")){
jstring jstr = (jstring)t.env->CallObjectMethod(obj, t.methodID);
const char* str = NULL;
if(jstr != NULL){
str = t.env->GetStringUTFChars(jstr, 0);
ret = str;
t.env->ReleaseStringUTFChars(jstr, str);
}
t.env->DeleteLocalRef(t.classID);
}
return ret;
}
std::string getLeaderboardNameJni(jobject obj){
JniMethodInfo t;
std::string ret;
if(GreeJniHelper::getInstanceMethodInfo(t, obj, "getName", "()Ljava/lang/String;")){
jstring jstr = (jstring)t.env->CallObjectMethod(obj, t.methodID);
const char* str = NULL;
if(jstr != NULL){
str = t.env->GetStringUTFChars(jstr, 0);
ret = str;
t.env->ReleaseStringUTFChars(jstr, str);
}
t.env->DeleteLocalRef(t.classID);
}
return ret;
}
std::string getLeaderboardThumbnailUrlJni(jobject obj){
JniMethodInfo t;
std::string ret;
if(GreeJniHelper::getInstanceMethodInfo(t, obj, "getThumbnailUrl", "()Ljava/lang/String;")){
jstring jstr = (jstring)t.env->CallObjectMethod(obj, t.methodID);
const char* str = NULL;
if(jstr != NULL){
str = t.env->GetStringUTFChars(jstr, 0);
ret = str;
t.env->ReleaseStringUTFChars(jstr, str);
}
t.env->DeleteLocalRef(t.classID);
}
return ret;
}
int getFormatJni(jobject obj){
JniMethodInfo t;
int ret = -1;
if(GreeJniHelper::getInstanceMethodInfo(t, obj, "getFormat", "()I")){
ret = t.env->CallIntMethod(obj, t.methodID);
t.env->DeleteLocalRef(t.classID);
}
return ret;
}
std::string getFormatSuffixJni(jobject obj){
JniMethodInfo t;
std::string ret;
if(GreeJniHelper::getInstanceMethodInfo(t, obj, "getFormatSuffix", "()Ljava/lang/String;")){
jstring jstr = (jstring)t.env->CallObjectMethod(obj, t.methodID);
const char* str = NULL;
if(jstr != NULL){
str = t.env->GetStringUTFChars(jstr, 0);
ret = str;
t.env->ReleaseStringUTFChars(jstr, str);
}
t.env->DeleteLocalRef(t.classID);
}
return ret;
}
std::string getTimeFormatJni(jobject obj){
JniMethodInfo t;
std::string ret;
if(GreeJniHelper::getInstanceMethodInfo(t, obj, "getTimeFormat", "()Ljava/lang/String;")){
jstring jstr = (jstring)t.env->CallObjectMethod(obj, t.methodID);
const char* str = NULL;
if(jstr != NULL){
str = t.env->GetStringUTFChars(jstr, 0);
ret = str;
t.env->ReleaseStringUTFChars(jstr, str);
}
t.env->DeleteLocalRef(t.classID);
}
return ret;
}
int getFormatDecimalJni(jobject obj){
JniMethodInfo t;
int ret = -1;
if(GreeJniHelper::getInstanceMethodInfo(t, obj, "getFormatDecimal", "()I")){
ret = t.env->CallIntMethod(obj, t.methodID);
t.env->DeleteLocalRef(t.classID);
}
return ret;
}
int getSortJni(jobject obj){
JniMethodInfo t;
int ret = -1;
if(GreeJniHelper::getInstanceMethodInfo(t, obj, "getSort", "()I")){
ret = t.env->CallIntMethod(obj, t.methodID);
t.env->DeleteLocalRef(t.classID);
}
return ret;
}
bool isLeaderboardSecretJni(jobject obj){
JniMethodInfo t;
bool ret = false;
if(GreeJniHelper::getInstanceMethodInfo(t, obj, "isSecret", "()Z")){
ret = t.env->CallBooleanMethod(obj, t.methodID);
t.env->DeleteLocalRef(t.classID);
}
return ret;
}
void getLeaderboardThumbnailJni(jobject obj, int** pBuf, int *pw, int *ph){
JniMethodInfo t;
jobject img = NULL;
if(GreeJniHelper::getInstanceMethodInfo(t, obj, "getThumbnail", "()Landroid/graphics/Bitmap;")){
img = (jobject)t.env->CallObjectMethod(obj, t.methodID);
if(img == NULL){
return;
}
// get raw data
{
jclass jParser = JniHelper::getClassID("org/cocos2dx/lib/gree/NativeBitmapParser", t.env);
if(jParser == NULL){
return;
}
jmethodID method = t.env->GetStaticMethodID(jParser, "getBitmapWidth", "(Ljava/lang/Object;)I");
if(method == NULL){
return;
}
*pw = t.env->CallStaticIntMethod(jParser, method, img);
method = t.env->GetStaticMethodID(jParser, "getBitmapHeight", "(Ljava/lang/Object;)I");
if(method == NULL){
return;
}
*ph = t.env->CallStaticIntMethod(jParser, method, img);
if(*pw > 0 && *ph > 0){
*pBuf = (int*)malloc(*pw * *ph * 4);
if(*pBuf != NULL){
method = t.env->GetStaticMethodID(jParser, "getBitmapData", "(Ljava/lang/Object;)[I");
if(method == NULL){
free(*pBuf);
return;
}
jintArray jArr = (jintArray)t.env->CallStaticObjectMethod(jParser, method, img);
jint* arr = t.env->GetIntArrayElements(jArr, 0);
// convert ARGB -> ABGR
//memcpy(*pBuf, arr, *pw * *ph * 4);
for(int i = 0; i < *pw * *ph; i++){
unsigned int colorData = *((unsigned int *)arr + i);
*((unsigned int*)(*pBuf) + i) = ((colorData & 0xff00ff00) |
((colorData & 0x00ff0000) >> 16) |
((colorData & 0x000000ff) << 16));
}
t.env->ReleaseIntArrayElements(jArr, arr, 0);
}
}
t.env->DeleteLocalRef(jParser);
}
t.env->DeleteLocalRef(t.classID);
}
}
bool loadLeaderboardThumbnailJni(jobject obj, void *delegate){
JniMethodInfo t;
bool ret = false;
if(GreeJniHelper::getInstanceMethodInfo(t, obj, "loadThumbnail", "(Lnet/gree/asdk/api/IconDownloadListener;)Z")){
JniMethodInfo l;
if(JniHelper::getMethodInfo(l, "org/cocos2dx/lib/gree/NativeIconDownloadListener", "<init>", "(JI)V")){
jobject listener = l.env->NewObject(l.classID, l.methodID, (unsigned long long)delegate, (int)fTypeLoadLeaderboardThumbnail);
if(listener == NULL){
CCLog("Cannot create new listener object in %s", __func__);
return ret;
}
ret = t.env->CallBooleanMethod(obj, t.methodID, listener);
l.env->DeleteLocalRef(l.classID);
}
t.env->DeleteLocalRef(t.classID);
}
return ret;
}
void createScoreJni(jobject obj, long long score, void *delegate){
JniMethodInfo t;
if(GreeJniHelper::getInstanceMethodInfo(t, obj, "createScore", "(JLnet/gree/asdk/api/Leaderboard$SuccessListener;)V")){
JniMethodInfo l;
if(JniHelper::getMethodInfo(l, "org/cocos2dx/lib/gree/NativeLeaderboardSuccessListener", "<init>", "(JI)V")){
jobject listener = l.env->NewObject(l.classID, l.methodID, (unsigned long long)delegate, (int)fTypeCreateScore);
if(listener == NULL){
CCLog("Cannot create new listener object in %s", __func__);
return;
}
t.env->CallVoidMethod(obj, t.methodID, score, listener);
l.env->DeleteLocalRef(l.classID);
}
t.env->DeleteLocalRef(t.classID);
}
}
void getLeaderboardScoresJni(jobject obj, int selector, int period, int index, int count, void *delegate){
JniMethodInfo t;
if(GreeJniHelper::getInstanceMethodInfo(t, obj, "getScore", "(IIIILnet/gree/asdk/api/Leaderboard$ScoreListener;)V")){
JniMethodInfo l;
if(JniHelper::getMethodInfo(l, "org/cocos2dx/lib/gree/NativeScoreListener", "<init>", "(J)V")){
jobject listener = l.env->NewObject(l.classID, l.methodID, (unsigned long long)delegate);
if(listener == NULL){
CCLog("Cannot create new listener object in %s", __func__);
return;
}
t.env->CallVoidMethod(obj, t.methodID, selector, period, index, count, listener);
l.env->DeleteLocalRef(l.classID);
}
t.env->DeleteLocalRef(t.classID);
}
}
void deleteScoreJni(jobject obj, void *delegate){
JniMethodInfo t;
if(GreeJniHelper::getInstanceMethodInfo(t, obj, "deleteScore", "(Lnet/gree/asdk/api/Leaderboard$SuccessListener;)V")){
JniMethodInfo l;
if(JniHelper::getMethodInfo(l, "org/cocos2dx/lib/gree/NativeLeaderboardSuccessListener", "<init>", "(JI)V")){
jobject listener = l.env->NewObject(l.classID, l.methodID, (unsigned long long)delegate, (int)fTypeDeleteScore);
if(listener == NULL){
CCLog("Cannot create new listener object in %s", __func__);
return;
}
t.env->CallVoidMethod(obj, t.methodID, listener);
l.env->DeleteLocalRef(l.classID);
}
t.env->DeleteLocalRef(t.classID);
}
}
}
|
/* Author: Mincheul Kang */
#include <boost/chrono.hpp>
#include <boost/foreach.hpp>
#include <ompl/base/SpaceInformation.h>
#include <harmonious_sampling/ManipulationRegion.h>
MainpulationRegion::MainpulationRegion(planning_scene::PlanningScenePtr& planning_scene,
std::string planning_group,
std::string collision_check_group,
HarmoniousParameters ¶ms,
std::vector<harmonious_msgs::BaseConf> &base_confs,
std::vector<harmonious_msgs::JointConf> &joint_confs):
base_confs_(base_confs),
joint_confs_(joint_confs),
params_(params)
{
planning_scene_ = planning_scene;
planning_group_ = planning_group; // base_group
collision_request_.group_name = collision_check_group;
collision_request_.contacts = true;
collision_request_.max_contacts = 100;
collision_request_.max_contacts_per_pair = 1;
collision_request_.verbose = false;
regions_ = new bool**[params_.reg_index_[0]];
for (uint i = 0; i < params_.reg_index_[0]; i++){
regions_[i] = new bool*[params_.reg_index_[1]];
for (uint j = 0; j < params_.reg_index_[1]; j++){
regions_[i][j] = new bool[params_.reg_index_[2]];
}
}
for(uint i = 0; i < params_.reg_index_[0]; i++){
for(uint j = 0; j < params_.reg_index_[1]; j++) {
for (uint k = 0; k < params_.reg_index_[2]; k++) {
regions_[i][j][k] = false;
}
}
}
}
MainpulationRegion::~MainpulationRegion(){
for(uint i=0; i<params_.reg_index_[0]; i++) {
for(uint j=0; j<params_.reg_index_[1]; j++)
delete [] regions_[i][j];
delete [] regions_[i];
}
delete [] regions_;
}
bool MainpulationRegion::isValid(harmonious_msgs::BaseConf &bp) {
std::map<std::string, double> configuration;
collision_detection::CollisionResult collision_result;
std::vector<double> values;
values.push_back(bp.b_c[0]);
values.push_back(bp.b_c[1]);
values.push_back(bp.b_c[2]);
collision_result.clear();
robot_state::RobotState robot_state = planning_scene_->getCurrentStateNonConst();
robot_state.setJointGroupPositions(planning_group_, values);
planning_scene_->checkCollision(collision_request_, collision_result, robot_state);
return !collision_result.collision;
}
void MainpulationRegion::generate_regions(ompl::base::RealVectorBounds &bounds){
for (uint i = 0; i < base_confs_.size(); i++){
if(base_confs_[i].b_c[0] < bounds.low[0] || base_confs_[i].b_c[0] > bounds.high[0]){
joint_confs_[i].j_c.clear();
continue;
}
if(base_confs_[i].b_c[1] < bounds.low[1] || base_confs_[i].b_c[1] > bounds.high[1]){
joint_confs_[i].j_c.clear();
continue;
}
if(isValid(base_confs_[i])){
regions_[int(((base_confs_[i]).b_c[0]-params_.bounds_.low[0]) * params_.resolution_)]
[int(((base_confs_[i]).b_c[1]-params_.bounds_.low[1]) * params_.resolution_)]
[int(((base_confs_[i]).b_c[2]-params_.bounds_.low[2]) * params_.res_yaw_)] = true;
}
}
}
|
//email address: hung.nguyen@student.tut.fi - student id: 272585
//email address: sanghun.2.lee@student.tut.fi - student id: 272571
#include <iostream>
#include <string>
#include <vector>
using namespace std;
//Splitter to split the date string to int-type components.
//Return a vector of integers based on the input string.
vector<int> Splitter(const string& strToSplit){
vector<int> vector;
int tempInt;
string tempString;
string::size_type mark1 = 0;
string::size_type mark2 = 0;
while(1){
mark1 = strToSplit.find('-',mark2);
if(mark1 == string::npos){
tempString = strToSplit.substr(mark2);
tempInt = stoi(tempString);
vector.push_back(tempInt);
break;
}
tempString = strToSplit.substr(mark2,mark1 - mark2);
tempInt = stoi(tempString);
vector.push_back(tempInt);
mark2 = mark1+1;
}
return vector;
}
//Helper function to check if a character is a number.
//Return true if the char variable is a number and vice versa.
bool isANumber(char c){
if(c>='0' && c<='9'){
return true;
}return false;
}
//function to check if the input string s a valid date string with type: day-month-year.
//Return true if the string is of form day-month-year and vice versa.
bool isStringValid(string str){
if(str.size() == 10){
if(str.at(2) == '-' && str.at(5)=='-' && isANumber(str.at(0)) && isANumber(str.at(1)) && isANumber(str.at(3))
&& isANumber(str.at(4)) && isANumber(str.at(6)) && isANumber(str.at(7)) && isANumber(str.at(8)) && isANumber(str.at(9))){
return true;
}
}else if(str.size() == 8){
if(str.at(1)=='-' && str.at(3) == '-' && isANumber(str.at(0)) && isANumber(str.at(2)) && isANumber(str.at(4))
&& isANumber(str.at(5)) && isANumber(str.at(6)) && isANumber(str.at(7))){
return true;
}
}else if(str.size() == 9){
if(str.at(1) == '-' && str.at(4) == '-' && isANumber(str.at(0))&& isANumber(str.at(2))&& isANumber(str.at(3))&& isANumber(str.at(5))&& isANumber(str.at(6))&& isANumber(str.at(7))&& isANumber(str.at(8))){
return true;
}
if(str.at(2) == '-' && str.at(4)=='-' && isANumber(str.at(0))&& isANumber(str.at(1))&& isANumber(str.at(3))&& isANumber(str.at(5))&& isANumber(str.at(6))&& isANumber(str.at(7))&& isANumber(str.at(8))){
return true;
}
}
return false;
}
class date{
public:
date(string date);
date(int day, int month, int year);
bool isValid()const;
void print()const;
void print2()const;
void moveToNextDate();
void moveToLastDate();
string getWeekday()const;
int getDay()const;
int getMonth()const;
int getYear()const;
private:
int day_;
int month_;
int year_;
};
//function to get week day of the current date.
//Return a string from "Monday" to "Sunday"
string date::getWeekday() const {
// The formula for calculating a julian day number is ripped from:
// https://en.wikipedia.org/wiki/Julian_day
int Y = year_;
int M = month_;
int D =day_;
int julian_day_number =
(1461 * (Y + 4800 + (M - 14)/12))/4
+ (367 * (M - 2 - 12 * ((M - 14)/12)))/12
- (3 * ((Y + 4900 + (M - 14)/12)/100))/4 + D - 32075;
int weekday_number = julian_day_number % 7;
switch ( weekday_number ) {
case 0:
return "Monday";
case 1:
return "Tuesday";
case 2:
return "Wednesday";
case 3:
return "Thursday";
case 4:
return "Friday";
case 5:
return "Saturday";
case 6:
return "Sunday";
default:
return "?????";
}
}
//Constructor for input as a string
date::date(string date){
vector<int> vector = Splitter(date);
//vector is only used to store integers from the Splitter
day_ = vector.at(0);
month_ = vector.at(1);
year_ = vector.at(2);
}
//Constructor for input as 3 different int: day, month, year
date::date(int day, int month, int year):
day_(day),month_(month),year_(year){}
//function to check if a date is valid.
//return true if the date is a valid date and vice versa.
bool date::isValid()const{
if(year_ >= 1800){
if(month_==1 || month_==3 || month_==5 || month_==7|| month_==8 || month_==10 ||
month_==12){
if(day_ <= 31 && day_> 0) return true;
}else if(month_ ==4|| month_ ==6 || month_==9||month_==11){
if(day_ <= 30 && day_>0) return true;
}else if(month_ == 2){
if(year_ % 4 == 0){
if(year_ %100 != 0){
if(day_ <= 29 && day_>0) return true;
}else if(year_ %400 == 0){
if(day_ <= 29 && day_> 0) return true;
}
}else{
if(day_<=28 && day_>0) return true;
}
}
return false;
}
return false;
}
//print out the current date.
void date::print() const{
cout<<"Day is "<<day_<<"\nMonth is "<<month_<<"\nYear is "<<year_<<"\nWeekday is "<<getWeekday()<<endl;
}
//another print function to print out the date object.
//because the next and previous dates are printed differently from the input date.
void date::print2() const{
cout<<getWeekday()<<" "<<day_<<"."<<month_<<"."<<year_<<endl;
}
//increment the current date object to the next date.
void date::moveToNextDate(){
int nextDay = day_+1;
int monthNextDay = month_;
int yearNextDay = year_;
date tempDate = date(nextDay,month_,year_);
if(!tempDate.isValid()){
nextDay =1;
monthNextDay = month_+1;
tempDate = date(nextDay,monthNextDay,year_);
if(!tempDate.isValid()){
monthNextDay =1;
yearNextDay = year_ +1;
}
}
day_=nextDay;
month_=monthNextDay;
year_=yearNextDay;
}
//decrement the current date object to the previous date.
void date::moveToLastDate(){
int lastDay = day_ -1;
int monthLastDay = month_;
int yearLastDay = year_;
date tempDate = date(lastDay,month_,year_);
if(!tempDate.isValid()){
if(month_ ==1){
monthLastDay = 12;
yearLastDay = year_-1;
lastDay = 31;
tempDate = date(lastDay,monthLastDay,yearLastDay);
}else{
monthLastDay = month_ -1;
lastDay =31;
while(1){
tempDate = date(lastDay,monthLastDay,yearLastDay);
if(tempDate.isValid()) break;
lastDay--;
}
}
}
day_ = lastDay;
month_ = monthLastDay;
year_ = yearLastDay;
}
//get the day number of the date object.
int date::getDay()const{
return day_;
}
//get the month number of the date object.
int date::getMonth()const{
return month_;
}
//get the year number of the date object.
int date::getYear()const{
return year_;
}
int main(){
string input;
while(1){
cout<<"Input a date in day-month-year format: ";
getline(cin, input);
if(input == "quit"){
cout<<"\nTest program ending, goodbye!\n"<<endl;
break;
}
cout<<"--- TEST OUTPUT BEGIN"<<endl;
if(!isStringValid(input)){
cout<<"Error: this is not a valid date!"<<endl;
}else{
date d1 = date(input);
if(d1.isValid()){
cout<<"The date is a valid date."<<endl;
d1.print();
d1.moveToLastDate();
cout<<"The previous date was: ";
d1.print2();
d1.moveToNextDate();
d1.moveToNextDate();
cout<<"The next date will be: ";
d1.print2();
}else{
cout<<"Error: this is not a valid date"<<endl;
}
}
cout<<"--- TEST OUTPUT END\n"<<endl;
}
return 0;
}
|
// Created on: 1998-06-08
// Created by: data exchange team
// Copyright (c) 1998-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _ShapeAnalysis_Edge_HeaderFile
#define _ShapeAnalysis_Edge_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Standard_Integer.hxx>
#include <ShapeExtend_Status.hxx>
class TopoDS_Edge;
class Geom_Curve;
class TopoDS_Face;
class Geom_Surface;
class TopLoc_Location;
class Geom2d_Curve;
class gp_Pnt2d;
class TopoDS_Vertex;
class gp_Vec2d;
class gp_Pnt;
// resolve name collisions with X11 headers
#ifdef Status
#undef Status
#endif
//! Tool for analyzing the edge.
//! Queries geometrical representations of the edge (3d curve, pcurve
//! on the given face or surface) and topological sub-shapes (bounding
//! vertices).
//! Provides methods for analyzing geometry and topology consistency
//! (3d and pcurve(s) consistency, their adjacency to the vertices).
class ShapeAnalysis_Edge
{
public:
DEFINE_STANDARD_ALLOC
//! Empty constructor; initialises Status to OK
Standard_EXPORT ShapeAnalysis_Edge();
//! Tells if the edge has a 3d curve
Standard_EXPORT Standard_Boolean HasCurve3d (const TopoDS_Edge& edge) const;
//! Returns the 3d curve and bounding parameteres for the edge
//! Returns False if no 3d curve.
//! If <orient> is True (default), takes orientation into account:
//! if the edge is reversed, cf and cl are toggled
Standard_EXPORT Standard_Boolean Curve3d (const TopoDS_Edge& edge, Handle(Geom_Curve)& C3d, Standard_Real& cf, Standard_Real& cl, const Standard_Boolean orient = Standard_True) const;
//! Gives True if the edge has a 3d curve, this curve is closed,
//! and the edge has the same vertex at start and end
Standard_EXPORT Standard_Boolean IsClosed3d (const TopoDS_Edge& edge) const;
//! Tells if the Edge has a pcurve on the face.
Standard_EXPORT Standard_Boolean HasPCurve (const TopoDS_Edge& edge, const TopoDS_Face& face) const;
//! Tells if the edge has a pcurve on the surface (with location).
Standard_EXPORT Standard_Boolean HasPCurve (const TopoDS_Edge& edge, const Handle(Geom_Surface)& surface, const TopLoc_Location& location) const;
Standard_EXPORT Standard_Boolean PCurve (const TopoDS_Edge& edge, const TopoDS_Face& face, Handle(Geom2d_Curve)& C2d, Standard_Real& cf, Standard_Real& cl, const Standard_Boolean orient = Standard_True) const;
//! Returns the pcurve and bounding parameteres for the edge
//! lying on the surface.
//! Returns False if the edge has no pcurve on this surface.
//! If <orient> is True (default), takes orientation into account:
//! if the edge is reversed, cf and cl are toggled
Standard_EXPORT Standard_Boolean PCurve (const TopoDS_Edge& edge, const Handle(Geom_Surface)& surface, const TopLoc_Location& location, Handle(Geom2d_Curve)& C2d, Standard_Real& cf, Standard_Real& cl, const Standard_Boolean orient = Standard_True) const;
Standard_EXPORT Standard_Boolean BoundUV (const TopoDS_Edge& edge, const TopoDS_Face& face, gp_Pnt2d& first, gp_Pnt2d& last) const;
//! Returns the ends of pcurve
//! Calls method PCurve with <orient> equal to True
Standard_EXPORT Standard_Boolean BoundUV (const TopoDS_Edge& edge, const Handle(Geom_Surface)& surface, const TopLoc_Location& location, gp_Pnt2d& first, gp_Pnt2d& last) const;
Standard_EXPORT Standard_Boolean IsSeam (const TopoDS_Edge& edge, const TopoDS_Face& face) const;
//! Returns True if the edge has two pcurves on one surface
Standard_EXPORT Standard_Boolean IsSeam (const TopoDS_Edge& edge, const Handle(Geom_Surface)& surface, const TopLoc_Location& location) const;
//! Returns start vertex of the edge (taking edge orientation
//! into account).
Standard_EXPORT TopoDS_Vertex FirstVertex (const TopoDS_Edge& edge) const;
//! Returns end vertex of the edge (taking edge orientation
//! into account).
Standard_EXPORT TopoDS_Vertex LastVertex (const TopoDS_Edge& edge) const;
Standard_EXPORT Standard_Boolean GetEndTangent2d (const TopoDS_Edge& edge, const TopoDS_Face& face, const Standard_Boolean atEnd, gp_Pnt2d& pos, gp_Vec2d& tang, const Standard_Real dparam = 0.0) const;
//! Returns tangent of the edge pcurve at its start (if atEnd is
//! False) or end (if True), regarding the orientation of edge.
//! If edge is REVERSED, tangent is reversed before return.
//! Returns True if pcurve is available and tangent is computed
//! and is not null, else False.
Standard_EXPORT Standard_Boolean GetEndTangent2d (const TopoDS_Edge& edge, const Handle(Geom_Surface)& surface, const TopLoc_Location& location, const Standard_Boolean atEnd, gp_Pnt2d& pos, gp_Vec2d& tang, const Standard_Real dparam = 0.0) const;
//! Checks the start and/or end vertex of the edge for matching
//! with 3d curve with the given precision.
//! <vtx> = 1 : start vertex only
//! <vtx> = 2 : end vertex only
//! <vtx> = 0 : both (default)
//! If preci < 0 the vertices are considered with their own
//! tolerances, else with the given <preci>.
Standard_EXPORT Standard_Boolean CheckVerticesWithCurve3d (const TopoDS_Edge& edge, const Standard_Real preci = -1, const Standard_Integer vtx = 0);
Standard_EXPORT Standard_Boolean CheckVerticesWithPCurve (const TopoDS_Edge& edge, const TopoDS_Face& face, const Standard_Real preci = -1, const Standard_Integer vtx = 0);
//! Checks the start and/or end vertex of the edge for matching
//! with pcurve with the given precision.
//! <vtx> = 1 : start vertex
//! <vtx> = 2 : end vertex
//! <vtx> = 0 : both
//! If preci < 0 the vertices are considered with their own
//! tolerances, else with the given <preci>.
Standard_EXPORT Standard_Boolean CheckVerticesWithPCurve (const TopoDS_Edge& edge, const Handle(Geom_Surface)& surface, const TopLoc_Location& location, const Standard_Real preci = -1, const Standard_Integer vtx = 0);
Standard_EXPORT Standard_Boolean CheckVertexTolerance (const TopoDS_Edge& edge, const TopoDS_Face& face, Standard_Real& toler1, Standard_Real& toler2);
//! Checks if it is necessary to increase tolerances of the edge
//! vertices to comprise the ends of 3d curve and pcurve on
//! the given face (first method) or all pcurves stored in an edge
//! (second one)
//! toler1 returns necessary tolerance for first vertex,
//! toler2 returns necessary tolerance for last vertex.
Standard_EXPORT Standard_Boolean CheckVertexTolerance (const TopoDS_Edge& edge, Standard_Real& toler1, Standard_Real& toler2);
Standard_EXPORT Standard_Boolean CheckCurve3dWithPCurve (const TopoDS_Edge& edge, const TopoDS_Face& face);
//! Checks mutual orientation of 3d curve and pcurve on the
//! analysis of curves bounding points
Standard_EXPORT Standard_Boolean CheckCurve3dWithPCurve (const TopoDS_Edge& edge, const Handle(Geom_Surface)& surface, const TopLoc_Location& location);
//! Returns the status (in the form of True/False) of last Check
Standard_EXPORT Standard_Boolean Status (const ShapeExtend_Status status) const;
//! Checks the edge to be SameParameter.
//! Calculates the maximal deviation between 3d curve and each
//! pcurve of the edge on <NbControl> equidistant points (the same
//! algorithm as in BRepCheck; default value is 23 as in BRepCheck).
//! This deviation is returned in <maxdev> parameter.
//! If deviation is greater than tolerance of the edge (i.e.
//! incorrect flag) returns False, else returns True.
Standard_EXPORT Standard_Boolean CheckSameParameter (const TopoDS_Edge& edge, Standard_Real& maxdev, const Standard_Integer NbControl = 23);
//! Checks the edge to be SameParameter.
//! Calculates the maximal deviation between 3d curve and each
//! pcurve of the edge on <NbControl> equidistant points (the same
//! algorithm as in BRepCheck; default value is 23 as in BRepCheck).
//! This deviation is returned in <maxdev> parameter.
//! If deviation is greater than tolerance of the edge (i.e.
//! incorrect flag) returns False, else returns True.
Standard_EXPORT Standard_Boolean CheckSameParameter (const TopoDS_Edge& theEdge, const TopoDS_Face& theFace, Standard_Real& theMaxdev, const Standard_Integer theNbControl = 23);
//! Checks possibility for pcurve thePC to have range [theFirst, theLast] (edge range)
//! having respect to real first, last parameters of thePC
Standard_EXPORT Standard_Boolean CheckPCurveRange (const Standard_Real theFirst, const Standard_Real theLast,
const Handle(Geom2d_Curve)& thePC);
//! Checks the first edge is overlapped with second edge.
//! If distance between two edges is less then theTolOverlap
//! edges are overlapped.
//! theDomainDis - length of part of edges on which edges are overlapped.
Standard_EXPORT Standard_Boolean CheckOverlapping (const TopoDS_Edge& theEdge1, const TopoDS_Edge& theEdge2, Standard_Real& theTolOverlap, const Standard_Real theDomainDist = 0.0);
protected:
Standard_Integer myStatus;
private:
//! Check points by pairs (A and A, B and B) with precisions
//! (preci1 and preci2).
//! P1 are the points either from 3d curve or from vertices,
//! P2 are the points from pcurve
Standard_EXPORT Standard_Boolean CheckPoints (const gp_Pnt& P1A, const gp_Pnt& P1B, const gp_Pnt& P2A, const gp_Pnt& P2B, const Standard_Real preci1, const Standard_Real preci2);
};
#endif // _ShapeAnalysis_Edge_HeaderFile
|
#ifndef JOYSTICK_EXCEPTION_HPP
#define JOYSTICK_EXCEPTION_HPP
#include <string>
namespace joystick
{
class exception : public std::exception
{
std::string msg_;
public:
exception(const std::string &msg) : msg_(msg) {}
const char *what() const noexcept override
{
return msg_.c_str();
}
};
} // namespace joystick
#endif //JOYSTICK_EXCEPTION_HPP
|
#pragma once
#include <sstream>
#include <cmath>
#include <assert.h>
#include "object.h"
#include "array.h"
#include "utf8.h"
namespace json {
///enables parsing numbers as precise numbers
/** this option is global for whole application. If you need specify
* option locally, construct Parse instance with correct flag
*/
extern bool enableParsePreciseNumbers;
template<typename Fn>
class Parser {
public:
typedef std::size_t Flags;
///Allows duplicated keys in object
/** Duplicated keys are considered as invalid JSON. This option allows to relax the rule. Note
* that according to JSON standard, when duplicated keys are allowed, the last key is only stored
* within the object
*
* */
static const Flags allowDupKeys = 1;
///Parse numbers as precise
/** Precise numbers are parsed as they are and stored as string. This is transparent
* for the rest of the code. Precise numbers emits special flag preciseNumber. The
* function Value::getString() returns the actual form of the number. If such
* number is serialized, it is serialized 1:1 to its actual form
*
*/
static const Flags allowPreciseNumbers = 2;
Parser(Fn &&source, Flags flags = 0) :rd(std::forward<Fn>(source)),flags(flags) {}
virtual Value parse();
Value parseObject();
Value parseArray();
Value parseTrue();
Value parseFalse();
Value parseNull();
Value parseNumber();
Value parseString();
void checkString(const StringView<char> &str);
protected:
typedef std::pair<std::size_t, std::size_t> StrIdx;
StrViewA getString(StrIdx idx) {
return StrViewA(tmpstr).substr(idx.first, idx.second);
}
StrIdx readString();
void freeString(const StrIdx &str);
class Reader {
///source iterator
Fn source;
///temporary stored char here
int c;
///true if char is loaded, false if not
/** It could be possible to avoid such a flag if the commit()
performs preload of the next character. However this can be a trap.
If the character '}' of the top-level object is the last character
in the stream before it blocks, the commit() should not read the
next character. However it must be commited, because the inner parser
doesn't know anything about on which level operates.
Other reason is that any preloaded character is also lost when the
parser exits. And this preloaded character might be very important for
any following code.
*/
bool loaded;
public:
int next() {
//if char is not loaded, load it now
if (!loaded) {
//load
c = source();
//mark loaded
loaded = true;
}
//return char
return c;
}
int nextWs() {
char n = next();
while (isspace(n)) { commit(); n = next(); }
return n;
}
void commit() {
//just mark character not loaded, which causes, that next() will load next character
loaded = false;
}
int nextCommit() {
if (loaded) {
loaded = false;
return c;
} else {
return source();
}
}
void putBack(int c) {
loaded = true;
this->c = c;
}
///slightly faster read, because it returns character directly from the stream
/**
* Note that previous character must be commited"
* @return next character in the stream;
*/
int readFast() {
return source();
}
Reader(Fn &&fn) :source(std::forward<Fn>(fn)), loaded(false) {}
};
Reader rd;
///parses unsigned from the stream
/**
@param res there will be stored result
@param counter there will be stored count of digits has been read
@retval true number is complete, no more digits in the stream
@retval false number is not complete, parser stopped on integer overflow
*/
bool parseUnsigned(UInt &res, int &counter);
///parses integer and stores result to the double
/** By storing result into double causes, that final number will rounded
@param intPart already parsed pard by parseUnsigned
@return parsed number as double
@note function stops on first non-digit character (including dot)
*/
double parseLargeUnsigned(UInt intPart);
///Parses decimal part
/**
works similar as parseLargeUnsigned, but result is number between 0 and 1
(mantisa). Function stops on first non-digit character (including dot, so
dot must be already extacted)
@return parsed mantisa
*/
double parseDecimalPart();
///Parse number and store it as floating point number
/**
@param intpart part parsed by parseUnsigned. It can be however 0 to start
from the beginning
@param neg true if '-' sign has been extracted.
@return parsed value
@note function doesn't extract leading sign '+' or '-' it expects that
caller already used readSign() function
*/
Value parseDouble(UInt intpart, bool neg);
///Reads sign '+' or '-' from the stream
/**
@retval true there were sign '-'.
@retval false there were sign '+' or nothing
*/
bool readSign();
///Parses unicode sequence encoded as \uXXXX, stores it as UTF-8 into the tmpstr
void parseUnicode();
///Stores unicode character as UTF-8 into the tmpstr
void storeUnicode(UInt uchar);
StrIdx parsePreciseNumber(bool &hint_is_float);
///Temporary string - to keep allocated memory
std::vector<char> tmpstr;
///Temporary array - to keep allocated memory
std::vector<Value> tmpArr;
Flags flags;
};
class ParserHelper {
template<typename Fn>
friend class Parser;
static Value numberFromStringRaw(StrViewA str, bool force_double);
};
class ParseError:public std::exception {
public:
ParseError(std::string msg, int lastInput = -100) :msg(msg), lastInput(lastInput) {}
virtual char const* what() const throw() {
if (whatmsg.empty()) {
std::ostringstream fmt;
fmt << "Parse error: '" + msg + "' at <root>";
std::size_t pos = callstack.size();
while (pos) {
--pos;
fmt << "/" << callstack[pos];
}
if (lastInput != -100) {
fmt << ". Last input: " << lastInput << "(";
if (lastInput == -1) {
fmt << "EOF";
} else {
char c = (char)lastInput;
fmt << "'" << c << "'";
}
fmt << ").";
} else {
fmt<< ". Last input not given.";
}
whatmsg = fmt.str();
}
return whatmsg.c_str();
}
void addContext(const std::string &context) {
whatmsg.clear();
callstack.push_back(context);
}
protected:
std::string msg;
std::vector<std::string> callstack;
mutable std::string whatmsg;
int lastInput;
};
template<typename Fn>
inline Value Value::parse(Fn && source)
{
Parser<Fn> parser(std::forward<Fn>(source), enableParsePreciseNumbers?Parser<Fn>::allowPreciseNumbers:0);
return parser.parse();
}
template<typename Fn>
inline Value Parser<Fn>::parse()
{
int c = rd.nextWs();
switch (c) {
case '{': rd.commit(); return parseObject();
case '[': rd.commit(); return parseArray();
case '"': rd.commit(); return parseString();
case 't': return parseTrue();
case 'f': return parseFalse();
case 'n': return parseNull();
case -1: throw ParseError("Unexpected end of stream",c);
default: if (isdigit(c) || c == '+' || c == '-' || c == '.')
return parseNumber();
else
throw ParseError("Unexpected data",c);
}
}
template<typename Fn>
inline Value Parser<Fn>::parseObject()
{
std::size_t tmpArrPos = tmpArr.size();
int c = rd.nextWs();
if (c == '}') {
rd.commit();
return Value(object);
}
StrIdx name(0,0);
bool cont;
do {
if (c != '"')
throw ParseError("Expected a key (string)", c);
rd.commit();
try {
name = readString();
}
catch (ParseError &e) {
e.addContext(getString(name));
throw;
}
try {
c = rd.nextWs();
if (c != ':')
throw ParseError("Expected ':'", c);
rd.commit();
Value v = parse();
tmpArr.push_back(Value(getString(name),v));
freeString(name);
}
catch (ParseError &e) {
e.addContext(getString(name));
freeString(name);
throw;
}
c = rd.nextWs();
rd.commit();
if (c == '}') {
cont = false;
}
else if (c == ',') {
cont = true;
c = rd.nextWs();
}
else {
throw ParseError("Expected ',' or '}'", c);
}
} while (cont);
StringView<Value> data = tmpArr;
auto mydata=data.substr(tmpArrPos);
Value res(object, mydata);
if (((flags & allowDupKeys) == 0) && (res.size() != mydata.length)) {
throw ParseError("Duplicated keys",c);
}
tmpArr.resize(tmpArrPos);
return res;
}
template<typename Fn>
inline Value Parser<Fn>::parseArray()
{
std::size_t tmpArrPos = tmpArr.size();
int c = rd.nextWs();
if (c == ']') {
rd.commit();
return Value(array);
}
bool cont;
do {
try {
tmpArr.push_back(parse());
}
catch (ParseError &e) {
std::ostringstream buff;
buff << "[" << (tmpArr.size()-tmpArrPos) << "]";
e.addContext(buff.str());
throw;
}
try {
c = rd.nextWs();
rd.commit();
if (c == ']') {
cont = false;
}
else if (c == ',') {
cont = true;
}
else {
throw ParseError("Expected ',' or ']'", c);
}
}
catch (ParseError &e) {
std::ostringstream buff;
buff << "[" << (tmpArr.size()-tmpArrPos) << "]";
e.addContext(buff.str());
throw;
}
} while (cont);
StringView<Value> arrView(tmpArr);
Value res(arrView.substr(tmpArrPos));
tmpArr.resize(tmpArrPos);
return res;
}
template<typename Fn>
inline Value Parser<Fn>::parseTrue()
{
checkString("true");
return Value(true);
}
template<typename Fn>
inline Value Parser<Fn>::parseFalse()
{
checkString("false");
return Value(false);
}
template<typename Fn>
inline Value Parser<Fn>::parseNull()
{
checkString("null");
return Value(nullptr);
}
template<typename Fn>
inline bool Parser<Fn>::readSign() {
bool isneg = false;
char c = rd.next();
if (c == '-') {
isneg = true; rd.commit();
}
else if (c == '+') {
isneg = false; rd.commit();
}
return isneg;
}
template<typename Fn>
inline void Parser<Fn>::parseUnicode()
{
//unicode is parsed from \uXXXX (which can be between 0 and 0xFFFF)
// and it is stored as UTF-8 (which can be 1...3 bytes)
UInt uchar = 0;
for (int i = 0; i < 4; i++) {
int c = rd.readFast();
uchar *= 16;
if (isdigit(c)) uchar += (c - '0');
else if (c >= 'A' && c <= 'F') uchar += (c - 'A' + 10);
else if (c >= 'a' && c <= 'f') uchar += (c - 'a' + 10);
else ParseError("Expected '0'...'9' or 'A'...'F' after the escape sequence \\u: ("+std::string(tmpstr.begin(),tmpstr.end())+")", c);
}
storeUnicode(uchar);
}
template<typename Fn>
inline void Parser<Fn>::storeUnicode(UInt uchar) {
WideToUtf8 conv;
conv(oneCharStream((int)uchar),[&](char c){tmpstr.push_back(c);});
}
template<typename Fn>
inline Value Parser<Fn>::parseNumber()
{
if (flags & allowPreciseNumbers) {
bool hint_is_double = false;
StrIdx numb = parsePreciseNumber(hint_is_double);
Value v = ParserHelper::numberFromStringRaw(getString(numb), hint_is_double);
freeString(numb);
return Value(v);
} else {
//first try to read number as signed or unsigned integer
UInt intpart;
//read sign and return true whether it is '-' (discard '+')
bool isneg = readSign();
//test next character
int c = rd.next();
//it should be digit or dot (because .3 is valid number)
if (!isdigit(c) && c != '.')
throw ParseError("Expected '0'...'9', '.', '+' or '-'", c);
//declared dummy var (we don't need counter here)
int counter;
//parse sequence of numbers as unsigned integer
//function returns false, if overflow detected
bool complete = parseUnsigned(intpart,counter);
//in case of overflow or dot follows, continue to read as floating number
if (!complete || rd.next() == '.' || toupper(rd.next()) == 'E') {
//parse floating number (give it already parsed informations)
return parseDouble(intpart, isneg);
}
//is negative?
if (isneg) {
//tests, whether highest bit of unsigned integer is set
//if so, converting to signed triggers overflow
if (intpart & (UInt(1) << (sizeof(intpart) * 8 - 1))) {
//convert number to float
double v = (double)intpart;
//return negative value
return Value(-v);
}
else {
//convert to signed and return negative
return Value(-intptr_t(intpart));
}
}
else {
//return unsigned version
return Value(intpart);
}
}
}
template<typename Fn>
inline Value Parser<Fn>::parseString()
{
static auto createValue = [](StrViewA val) {
if (val == "∞") return Value(std::numeric_limits<double>::infinity());
else if (val == "-∞") return Value(-std::numeric_limits<double>::infinity());
else return Value(val);
};
StrIdx str = readString();
Value res (createValue(getString(str)));
freeString(str);
return res;
}
template<typename Fn>
inline void Parser<Fn>::freeString(const StrIdx &str)
{
assert(str.first+ str.second== tmpstr.size());
tmpstr.resize(str.first);
}
template<typename Fn>
inline typename Parser<Fn>::StrIdx Parser<Fn>::readString()
{
std::size_t start = tmpstr.size();
try {
Utf8ToWide conv;
conv([&]{
do {
int c = rd.readFast();
if (c == -1) {
throw ParseError("Unexpected end of file", c);
}
else if (c == '"') {
return -1;
}else if (c == '\\') {
//parse escape sequence
c = rd.readFast();
switch (c) {
case '"':
case '\\':
case '/': tmpstr.push_back(c); break;
case 'b': tmpstr.push_back('\b'); break;
case 'f': tmpstr.push_back('\f'); break;
case 'n': tmpstr.push_back('\n'); break;
case 'r': tmpstr.push_back('\r'); break;
case 't': tmpstr.push_back('\t'); break;
case 'u': parseUnicode();break;
default:
throw ParseError("Unexpected escape sequence in the string", c);
}
}
else {
return c;
}
} while (true);
},[&](int w) {
storeUnicode(w);
});
return StrIdx(start, tmpstr.size()-start);
} catch (...) {
tmpstr.resize(start);
throw;
}
}
template<typename Fn>
inline void Parser<Fn>::checkString(const StringView<char>& str)
{
int c = rd.next();
rd.commit();
if (c != str[0]) throw ParseError("Unknown keyword", c);
for (std::size_t i = 1; i < str.length; ++i) {
int c = rd.readFast();
if (c != str.data[i]) throw ParseError("Unknown keyword", c);
}
}
template<typename Fn>
inline bool Parser<Fn>::parseUnsigned(UInt & res, int &counter)
{
const UInt overflowDetection = ((UInt)-1) / 10; //429496729
//start at zero
res = 0;
//count read charactes
counter = 0;
//read first character
char c = rd.next();
//repeat while it is digit
while (isdigit(c)) {
if (res > overflowDetection) {
return false;
}
//calculate next val
UInt nextVal = res * 10 + (c - '0');
//detect overflow
if (nextVal < res) {
//report overflow (maintain already parsed value
return false;
}
//commit chracter
rd.commit();
//read next character
c = rd.next();
//store next value
res = nextVal;
//count character
counter++;
}
//found non digit character, exit parsing - number is complete
return true;
}
template<typename Fn>
inline double Parser<Fn>::parseLargeUnsigned(UInt intPart)
{
//starts with given integer part - convert to double
double res = (double)intPart;
//read while there are digits
int c;
while (isdigit(c = rd.next())) {
//prepare next unsigned integer
UInt part;
//prepare counter
int cnt;
//read next sequence of digits as integer
parseUnsigned(part, cnt);
//now res = res * 10^cnt + part
//this should reduce rounding errors because count of multiplies will be minimal
res = floor(res * pow(10.0, cnt) + double(part));
if (std::isinf(res)) throw ParseError("Too long number", c);
}
//return the result
return res;
}
template<typename Fn>
inline double Parser<Fn>::parseDecimalPart()
{
//parses decimal part as series of unsigned number each is multipled by its position
double res = 0;
unsigned int pos = 0;
//lookup table is slightly faster
static double numbers[10] = {0.0, 1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0};
//first, read digits and create large number
//count of decimals
//collect all numbers
while (isdigit(rd.next())) {
//pick digit ascii
char c = rd.nextCommit();
//convert to index
unsigned int n = c - '0';
//calculate 10*prev_value + number
//always truncate the number to prevent rounding errors
res = floor(res * 10 + numbers[n]);
//increase count of decimals
pos ++;
}
//finally, calculate decimal point shift (as number 10^digits)
//we use 10 because it doesn't generate rounding errors
double m = pow(10,pos);
//one operation divide large number by m, to shift whole number behind deximal page
res = res / m;
//result
return res;
}
template<typename Fn>
inline Value Parser<Fn>::parseDouble(UInt intpart, bool neg)
{
//float number is in format [+/-]digits[.digits][E[+/-]digits]
//sign is stored in neg
//complete to reading integer part
double d = parseLargeUnsigned(intpart);
int c = rd.next();
//if next char is dot
if (c == '.') {
//commit dot
rd.commit();
//next character must be a digit
if (isdigit(c = rd.next())) {
//so parse decimal part
double frac = parseDecimalPart();
//combine with integer part
d = d + frac;
}
else {
//throw exception that next character is not digit
throw ParseError("Expected '0'...'9' after '.'", c);
}
c = rd.next();
}
//next character is 'E' (exponent part)
if (toupper(c) == 'E') {
//commit the 'E'
rd.commit();
//read and discard any possible sign
bool negexp = readSign();
//prepare integer exponent
UInt expn;
//prepare counter (we don't need it)
int counter;
//next character must be a digit
if (!isdigit(c = rd.next()))
//throw exception is doesn't it
throw ParseError("Expected '0'...'9' after 'E'", c);
//parse the exponent
if (!parseUnsigned(expn, counter))
//complain about too large exponent (two or three digits must match to UInt)
throw ParseError("Exponent is too large", c);
//if exponent is negative
if (negexp) {
//calculate d * 0.1^expn
d = d * pow(0.1, expn);
}
else {
//calculate d * 10^expn
d = d * pow(10.0, expn);
}
}
//negative value
if (neg) {
//return negative
return Value(-d);
}
else {
//return positive
return Value(d);
}
}
template<typename Fn>
typename Parser<Fn>::StrIdx Parser<Fn>::parsePreciseNumber(bool& hint_is_float) {
UInt start = tmpstr.size();
try {
int c = rd.nextCommit();
if (c == '+' || c== '-') {
tmpstr.push_back((char)c);
c = rd.readFast();
}
if (!isdigit(c)) {
rd.putBack(c);
throw ParseError("Expected a number", c);
}
while (isdigit(c)) {
tmpstr.push_back((char)c);
c = rd.readFast();
}
if (c == '.') {
hint_is_float = true;
tmpstr.push_back((char)c);
c = rd.readFast();
while (isdigit(c)) {
tmpstr.push_back((char)c);
c = rd.readFast();
}
}
if (c == 'e' || c == 'E') {
hint_is_float = true;
tmpstr.push_back((char)c);
c = rd.readFast();
if (c == '+' || c== '-') {
tmpstr.push_back((char)c);
c = rd.readFast();
}
if (!isdigit(c)) {
rd.putBack(c);
throw ParseError("Expected a number", c);
}
while (isdigit(c)) {
tmpstr.push_back((char)c);
c = rd.readFast();
}
}
rd.putBack(c);
return StrIdx(start, tmpstr.size()-start);
} catch (...) {
tmpstr.resize(start);
throw;
}
}
}
|
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <memory.h>
#include <math.h>
#include <string>
#include <string.h>
#include <queue>
#include <vector>
#include <set>
#include <map>
typedef long long LL;
typedef unsigned long long ULL;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
void Add(int& x) {
int p = 1, y = x;
while (y >= 10) {
p *= 10;
y /= 10;
}
x = (y + 1) * p;
}
char ans[111], s[111];
int l, r;
int main() {
freopen("minlex.in", "r", stdin);
freopen("minlex.out", "w", stdout);
ans[0] = 'z';
cin >> l >> r;
while (l <= r) {
sprintf(s, "%d", l);
if (strcmp(s, ans) < 0) strcpy(ans, s);
Add(l);
}
cout << ans << endl;
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#ifndef _SSL_API_H_
#define _SSL_API_H_
#if defined(_NATIVE_SSL_SUPPORT_)
#include "modules/libssl/base/sslenum.h"
class URL;
class SSL_Options;
class ProtocolComm;
class MessageHandler;
class ServerName;
class SSL_PublicKeyCipher;
class SSL_GeneralCipher;
class SSL_Hash;
class SSL_CertificateHandler;
class SSL_Certificate_Installer_Base;
class SSL_varvector32;
struct SSL_Certificate_Installer_flags;
struct SSL_dialog_config;
class SSL_Private_Key_Generator;
#ifdef SSL_API_REGISTER_LOOKUP_CERT_REPOSITORY
class SSL_External_CertRepository_Base;
#endif // SSL_API_REGISTER_LOOKUP_CERT_REPOSITORY
class SSL_KeyManager;
class SSL_CertificateHandler_ListHead;
class OpWindow;
/** Keysize storage, used to determine lowest keysize among a number of PKI keys */
struct SSL_keysizes
{
/** The keysize for RSA, DH and DSA, 0 means not yet set */
uint32 RSA_keysize;
SSL_keysizes():RSA_keysize(0){}
void Update(const SSL_keysizes &old){if(!RSA_keysize || RSA_keysize> old.RSA_keysize) RSA_keysize = old.RSA_keysize;}
};
/** This class functions as the API to several libssl operations
* that are available to external modules
* It must be referenced as g_ssl_api
*/
class SSL_API
{
#ifdef SELFTEST
BOOL lock_security_manager;
#endif
public:
/** Constructor */
SSL_API(){
#ifdef SELFTEST
lock_security_manager = FALSE;
#endif
};
/** Destructor */
~SSL_API(){};
static void RemoveURLReferences(ProtocolComm *comm);
/** Create an independent SSL_Options security manager object, optionally defining a folder and that
* it register changes that can later be committed to the g_security_manager object
*/
SSL_Options *CreateSecurityManager(BOOL register_changes = FALSE, OpFileFolder folder = OPFILE_HOME_FOLDER);
/** Commit all changes in the optionsManager object into the current SSL preference status */
void CommitOptionsManager(SSL_Options *optionsManager);
/** Check if there is a global security manager, and if necessary create it. Returns FALSE if it was not able to create it */
BOOL CheckSecurityManager();
#ifdef SELFTEST
void UnLoadSecurityManager(BOOL finished =FALSE);
void LockSecurityManager(BOOL flag){lock_security_manager = flag;};
#endif
/** Remove all information that has expired, such as the security password if it has passed the expiration date */
void CheckSecurityTimeouts();
/** Create a SSL protocol object for the specified server */
ProtocolComm *Generate_SSL(MessageHandler* msg_handler, ServerName* hostname,
unsigned short portnumber, BOOL V3_handshake=FALSE, BOOL do_record_splitting = FALSE);
/**
* Create a handler for the the specified Symmetric encryption method
* Implemented in the actual library interface code
*/
DEPRECATED(SSL_GeneralCipher *CreateSymmetricCipherL(SSL_BulkCipherType cipher));
SSL_GeneralCipher *CreateSymmetricCipher(SSL_BulkCipherType cipher, OP_STATUS &op_err);
/**
* Create a handler for the the specified Public Key encryption method
* Implemented in the actual library interface code
*/
DEPRECATED(SSL_PublicKeyCipher *CreatePublicKeyCipherL(SSL_BulkCipherType cipher));
SSL_PublicKeyCipher *CreatePublicKeyCipher(SSL_BulkCipherType cipher, OP_STATUS &op_err);
/**
* Create a handler for the the specified Mesage Digest method
* Implemented in the actual library interface code
*/
SSL_Hash *CreateMessageDigest(SSL_HashAlgorithmType digest, OP_STATUS &op_err);
/**
* Create a handler for a certificate
* Implemented in the actual library interface code
*/
SSL_CertificateHandler *CreateCertificateHandler();
#ifdef USE_SSL_CERTINSTALLER
/** Create a Certificate Installation handler
* The source of the certificate is the specified URL object
* If no SSL_Options object is specified the certificate is committed directly to the security manager
* Interactive mode is implicit by a non-NULL pointer to a SSL_dialog_config object
* Caller must delete
*/
SSL_Certificate_Installer_Base *CreateCertificateInstallerL(URL &source, const SSL_Certificate_Installer_flags &install_flags, SSL_dialog_config *config=NULL, SSL_Options *optManager=NULL);
/** Create a Certificate Installation handler
* The source of the certificate is the specified varvector
* If no SSL_Options object is specified the certificate is committed directly to the security manager
* Interactive mode is implicit by a non-NULL pointer to a SSL_dialog_config object
* Caller must delete
*/
SSL_Certificate_Installer_Base *CreateCertificateInstallerL(SSL_varvector32 &source, const SSL_Certificate_Installer_flags &install_flags, SSL_dialog_config *config=NULL, SSL_Options *optManager=NULL);
#endif
#ifdef LIBSSL_ENABLE_KEYGEN
/**
* Prepares the keygeneration procedure controller. The caller must start the process.
*
* @param config Configuration for dialogs to be displayed as part of the key generation process, as well as the finished message to be sent to the caller
* @param target The form action URL to which the request will be sent. This will be used for the comment in the key entry
* @param format Which certificate request format should be used?
* @param type Which public key encryption algorithm should the key be created for?
* @param challenge A textstring to be included and signed as part of the request
* @param keygen_size The selected length of the key
* @param opt Optional SSL_Options object. If a non-NULL opt is provided, then CommitOptionsManager MUST be used by the caller
*/
SSL_Private_Key_Generator *CreatePrivateKeyGenerator(SSL_dialog_config &config, URL &target, SSL_Certificate_Request_Format format,
SSL_BulkCipherType type, const OpStringC8 &challenge,
unsigned int keygen_size, SSL_Options *opt);
/** Returns (starting at 1) the i'th private keysize availabe for the given cipher type. Zero (0) means end of list */
unsigned int SSL_GetKeygenSize(SSL_BulkCipherType type, int i);
/** Returns the default keygensize for the specified keygen algorithm */
unsigned int SSL_GetDefaultKeyGenSize(SSL_BulkCipherType type);
#endif
#ifdef LIBSSL_SECURITY_PASSWD
/** This operation initiate a reference_counted block of the security password,
* ensuring that the password is not destroyed while performing a longrunning security
* password operation (like multiple encrypt/decrypt operations).
*/
void StartSecurityPasswordSession();
/** Encrypt data with either a specified password or the security password
*
* @param op_err Returns the status of the operation.
* - If successful this contains an OpStatus::OK status
* - If a password was needed InstallerStatus::ERR_PASSWORD_NEEDED is the status.
* The caller should wait until the dialog posts a success or failure message before trying the operation again
* Note: if the dialog configuration finished_message was MSG_NO_MESSAGE no dialog is opened.
* - Other failures result in various error.
*
* @param in_data Pointer to the binary data of in_len bytes to be encrypted
*
* @param in_len Number of bytes in the in_data buffer
*
* @param out_len The number of bytes in the returned buffer is put in this parameter
*
* @param password If non-NULL, this contains the null-terminated password to be used when encrypting the data
* If NULL, the security password is used, and if necessary a dialog is opened according to the
* specification in the config parameter
*
* @param config Dialog configuration to be used if a security password dialog has to be opened.
* If config.finished_message is MSG_NO_MESSAGE no dialog is opened
*
* @return If successful return the pointer to the allocated memory used to store the encrypted data.
* The length of the allocated buffer is specified in out_len. The data must be decrypted
* by DecryptWithSecurityPassword using the same configuration
*/
unsigned char *EncryptWithSecurityPassword(OP_STATUS &op_err,
const unsigned char *in_data, unsigned long in_len, unsigned long &out_len,
const char* password, SSL_dialog_config &config);
/** Decrypt data with either a specified password or the security password
*
* @param op_err Returns the status of the operation.
* - If successful this contains an OpStatus::OK status
* - If a password was needed InstallerStatus::ERR_PASSWORD_NEEDED is the status.
* The caller should wait until the dialog posts a success or failure message before trying the operation again
* Note: if the dialog configuration finished_message was MSG_NO_MESSAGE no dialog is opened.
* - Other failures result in various error.
*
* @param in_data Pointer to the binary data of in_len bytes to be decrypted (the data must have been created
by EncryptWithSecurityPassword using the same configuration)
*
* @param in_len Number of bytes in the in_data buffer
*
* @param out_len The number of bytes in the returned buffer is put in this parameter
*
* @param password If non-NULL, this contains the null-terminated password to be used when decrypting the data
* If NULL, the security password is used, and if necessary a dialog is opened according to the
* specification in the config parameter
*
* @param config Dialog configuration to be used if a security password dialog has to be opened.
* If config.finished_message is MSG_NO_MESSAGE no dialog is opened
*
* @return If successful return the pointer to the allocated memory used to store the decrypted data.
* The length of the allocated buffer is specified in out_len.
*/
unsigned char *DecryptWithSecurityPassword(OP_STATUS &op_err,
const unsigned char *in_data, unsigned long in_len, unsigned long &out_len,
const char* password, SSL_dialog_config &config);
/** This operation ends a reference_counted block of the security password,
* that ensured that the password was not destroyed while performing a longrunning security
* password operation (like multiple encrypt/decrypt operations).
* If the password has expired it will be destroyed if this count reaches zero.
*/
void EndSecurityPasswordSession();
#endif
/** Determined the security level based on the public Key provided, returns the result in the
* security level and security reason parameters
*
* @param key The public cipher key being checked
* @param lowest_key Lowest keysize encountered so far, updated with information from key.
* @param security_level In: Current security level (must be SECURITY_STATE_UNKNOWN first time)
* Out: The resulting security level, including the key being tested
* @param security_reason In: Current security reasons logged (must be SECURITY_REASON_NOT_NEEDED first time)
* Out: The resulting security reasons logged, including for the key being tested.
*
* @return uint32 Length of current key
*/
uint32 DetermineSecurityStrength(SSL_PublicKeyCipher *key, SSL_keysizes &lowest_key, int &security_rating, int &low_security_reason);
#ifdef SSL_API_REGISTER_LOOKUP_CERT_REPOSITORY
/** Register the external Certificate lookup repository implemented for the platform
* The new repository is pushed on top of the stack and used instead (implementations may use
* the Suc() call to dicover and use the next repository).
*
* The repository is only referenced by the module, it does not take ownership, and
* deleting the repository handler will immediately unregister the handler.
*
* @param repository The repository to be registered.
*/
void RegisterExternalCertLookupRepository(SSL_External_CertRepository_Base *repository);
/** If set to TRUE, the Opera SSL stack will stop looking up Opera's own
* certificate repository, only use the external one. Will only work if there
* is a repository registered.
*
* @param disable TRUE if the internal repository will be disconnected, FALSE if it is to be used (default)
*/
void SetDisableInternalLookupRepository(BOOL disable);
/** Is internal lookup disabled? */
BOOL GetDisableInternalLookupRepository(){return g_ssl_disable_internal_repository;};
#endif // SSL_API_REGISTER_LOOKUP_CERT_REPOSITORY
#ifdef _SSL_USE_EXTERNAL_KEYMANAGERS_
public:
void RegisterExternalKeyManager(SSL_KeyManager *);
#endif // _SSL_USE_EXTERNAL_KEYMANAGERS_
};
inline SSL_PublicKeyCipher *SSL_API::CreatePublicKeyCipherL(SSL_BulkCipherType cipher){OP_STATUS op_err = OpStatus::OK; SSL_PublicKeyCipher *ret = CreatePublicKeyCipher(cipher, op_err); LEAVE_IF_ERROR(op_err); return ret;}
inline SSL_GeneralCipher *SSL_API::CreateSymmetricCipherL(SSL_BulkCipherType cipher){OP_STATUS op_err = OpStatus::OK; SSL_GeneralCipher *ret = CreateSymmetricCipher(cipher, op_err); LEAVE_IF_ERROR(op_err); return ret;}
#endif
#endif // _SSL_API_H_
|
#ifdef DEBUG
#define _GLIBCXX_DEBUG
#endif
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <memory.h>
#include <cmath>
#include <string>
#include <cstring>
#include <queue>
#include <vector>
#include <set>
#include <deque>
#include <map>
#include <functional>
#include <numeric>
#include <sstream>
#include <complex>
typedef long double LD;
typedef long long LL;
typedef unsigned long long ULL;
typedef unsigned int uint;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
int f[3333][3333];
char s[3333][3333];
int n, m;
int main() {
freopen(".in", "r", stdin);
freopen(".out", "w", stdout);
scanf("%d%d\n", &n, &m);
for (int i =0 ; i < n; ++i) {
gets(s[i]);
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) if (s[i][j] != '#') {
if (i == 0 && j == 0) f[i][j] = 1;else {
f[i][j] = 0;
if (i > 0) f[i][j] += f[i - 1][j];
if (j > 0) f[i][j] += f[i][j - 1];
if (i > 0 && j > 0) f[i][j] += f[i - 1][j - 1];
}
}
}
cout << f[n][m] << endl;
return 0;
}
|
#ifndef SENSOR_MODEL_H_
#define SENSOR_MODEL_H_
#include "models.h"
namespace model {
template<class T>
class SimpleSensorVelocityModel : public SensorModel<T> {
public:
SimpleSensorVelocityModel() :
SensorModel<T>()
{}
~SimpleSensorVelocityModel() {
}
virtual void calculate(
sigma::SigmaPoints<T>& observation,
sigma::SigmaPoints<T>& prediction)
{
int points = prediction.rows();
for (int i = 0; i < points; ++i) {
observation(i,0) = prediction(i,0);
observation(i,1) = prediction(i,1);
}
}
private:
};
};
#endif
|
#include <posteffects/IdlePostEffect.h>
#include <OGLML/PostProcessor.h>
namespace breakout
{
IdlePostEffect::IdlePostEffect(oglml::PostProcessor* pp)
: APostEffectState(pp)
{
}
IdlePostEffect::~IdlePostEffect()
{
}
void IdlePostEffect::Awake()
{
}
void IdlePostEffect::Begin()
{
}
void IdlePostEffect::End()
{
}
void IdlePostEffect::Draw(float dtMilliseconds)
{
}
}
|
#pragma once
#include "Forms/EntitiesForm/EntitiesForm.h"
class User;
class UsersForm : public EntitiesForm {
Q_OBJECT
public:
explicit UsersForm(QWidget *parent = nullptr);
void showRemoveUserDialog(uint userIndex);
void showEditUserView(const User &user);
void showAddUserView();
signals:
void removeUserClicked(uint userIndex);
void error(const QString &errorMessage);
};
|
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
using namespace std;
vector<int> numsVector { 61, 41, 231, 764, 45 };
sort(numsVector.begin(), numsVector.end(), std::greater<int>());
for (int num : numsVector)
{
cout << num << " ";
}
cout << endl << endl;
string wordsArray[6] { "whales", "cats", "dogs", "fish", "cheetahs", "dodos" };
sort(wordsArray, wordsArray + 6);
for (string word : wordsArray)
{
cout << word << " ";
}
cout << endl;
return 0;
}
|
#ifndef SHOETCPCLIENT_H
#define SHOETCPCLIENT_H
#include <QHostAddress>
#include <QTcpSocket>
#include <QObject>
#include "shoemanagernetwork_global.h"
#include "ShoeManagerTcpSocket.hpp"
class SHOEMANAGERNETWORKSHARED_EXPORT ShoeManagerTcpClient : public QObject
{
Q_OBJECT
public:
ShoeManagerTcpClient(QObject * parent=NULL);
bool initialize(QHostAddress address, int port);
bool finalize();
bool sendPacket(const ShoeMessagePacket& packet);
signals:
void onConnected();
void onDisconnected();
void onPacketSend(const ShoeMessagePacket& ShoeMessagePacket);
void onPacketReceived(const ShoeMessagePacket& packet);
void onErrorOccurred(const QString& errorString);
private:
ShoeTcpSocket* m_socket;
};
#endif // SHOETCPCLIENT_H
|
#ifndef __SPACESHIP_H__
#define __SPACESHIP_H__
#include "cocos2d.h"
// Base class for spaceships
class Spaceship : public cocos2d::Sprite
{
public:
// Initialize instance (sprite)
virtual bool init() override;
// Spaceship's "jump"
void boost();
// Plays basic animation
void onCrash();
private:
// Movement affected by gravity
void fall(float dT);
// Speed of the spaceship
float currentSpeed_ = 0;
// Spaceship isn't controllable after a crash
bool isControllable_ = true;
};
#endif // __SPACESHIP_H__
|
#include "QtTerminalWindow.h"
#include "Line.h"
#include "../pty.h"
#include <QKeyEvent>
#include <QPainter>
#include <QtGlobal>
#include <cstdio>
#include <cmath>
QtTerminalWindow::QtTerminalWindow()
: QFrame(NULL)
, m_pty(NULL)
, m_previousCharacter('\0')
, m_fontMetrics(0)
, m_font(0)
, m_size(80, 25)
{
QFont* newFont = new QFont("Inconsolata");
newFont->setFixedPitch(true);
setFont(newFont);
connect(this, SIGNAL(updateNeeded()),
this, SLOT(handleUpdateNeeded()));
}
void QtTerminalWindow::setFont(QFont* font)
{
delete m_font;
delete m_fontMetrics;
m_font = font;
m_fontMetrics = new QFontMetrics(*m_font);
// It seems that the maxWidth of the font is off by one pixel for many fixed
// width fonts. We likely just need to lay the font out manually, but this is
// a good hack for now.
QSize increment(m_fontMetrics->maxWidth() - 1, m_fontMetrics->height());
setSizeIncrement(increment);
resize(increment.width() * m_size.width(), increment.height() * m_size.height());
}
void QtTerminalWindow::handleUpdateNeeded()
{
// TODO: Be smarter.
update();
}
void QtTerminalWindow::characterAppended()
{
emit updateNeeded();
}
void QtTerminalWindow::somethingLargeChanged()
{
emit updateNeeded();
}
void QtTerminalWindow::renderTextAt(const char* text, size_t numberOfCharacters, bool isCursor, int x, int y)
{
int realX = sizeIncrement().width() * x;
int realY = sizeIncrement().height() * (y + 1);
if (isCursor) {
m_currentPainter->fillRect(QRect(QPoint(realX, realY - m_fontMetrics->ascent()), sizeIncrement()), QBrush(Qt::black));
return;
}
QString string = QString::fromUtf8(text, numberOfCharacters);
m_currentPainter->drawText(realX, realY, text);
}
int QtTerminalWindow::charactersWide()
{
return m_size.width();
}
int QtTerminalWindow::charactersTall()
{
return m_size.height();
}
void QtTerminalWindow::paintEvent(QPaintEvent* event)
{
if (isHidden())
return;
QPainter painter(this);
m_currentPainter = &painter;
painter.fillRect(event->rect(), QBrush(Qt::white));
painter.setFont(*m_font);
paint();
m_currentPainter = 0;
QFrame::paintEvent(event);
}
void QtTerminalWindow::keyPressEvent(QKeyEvent* event)
{
if (!m_pty)
return;
// This is really dumb, but it's only temporary.
QString eventString = event->text();
if (eventString.isEmpty())
return;
QByteArray utf8String = eventString.toUtf8();
m_pty->ptyWrite(utf8String.data(), utf8String.length());
}
void QtTerminalWindow::setPty(Pty* pty)
{
m_pty = pty;
m_pty->setSize(m_size.width(), m_size.height());
}
void QtTerminalWindow::resizeEvent(QResizeEvent* resizeEvent)
{
if (m_pty) {
m_size = QSize(size().width() / sizeIncrement().width(),
size().height() / sizeIncrement().height());
m_pty->setSize(m_size.width(), m_size.height());
m_cursorColumn = 0;
}
QWidget::resizeEvent(resizeEvent);
}
void QtTerminalWindow::bell()
{
printf("BING!\n");
}
|
/**********************************************
**Description: Header file of Person
***********************************************/
#ifndef PERSON_HPP // PERSON.hpp is the Person class specification file.
#define PERSON_HPP
#include<string>
class Person
{
private: //This is member of variable
std::string name;
double age;
public:
Person(std::string, double); //constructor with two paramentors
std::string getName(); //get function
double getAge();
};
#endif
|
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
#define oo 666666666
int A[2001][2001]; //[node][v] - id of edge that connects node with other node with color v
int color[2001][2001];
int edge[2001][2001];
vector<array<int,3>>E;
void dfs(int u, int v, int c1, int c2)
{
if(!A[u][c1] && !A[v][c1])//we can color current edge by c1
{
//cout<<"No more conflicts found, terminating at "<<u<<" "<<v<<"\n";
int col = color[u][v];
int ee = edge[u][v];
if(A[v][col]==ee)A[v][col]=0;
if(A[u][col]==ee)A[u][col]=0;
A[u][c1]=A[v][c1]=ee;
E[ee][2]=c1;
color[u][v]=color[v][u]=c1;
return;
}
int conflictingEdge = A[v][c1];
int other = E[conflictingEdge][0]^v^E[conflictingEdge][1];
int col = color[u][v];
int ee = edge[u][v];
if(A[v][col]==ee)A[v][col]=0;//erase current color
if(A[u][col]==ee)A[u][col]=0;
A[u][c1]=A[v][c1]=ee; //color as needed
E[ee][2]=c1;
color[u][v]=color[v][u]=c1;
//cout<<"Edge "<<u<<" "<<v<<" still bad\n";
dfs(v,other,c2,c1); //we keep alternating colors and because graph is bipartite, it can only have
// even degree cycles - which can be bi-colored, hence in the worst case we will just 'rotate' whole cycle
}
int main()
{
ios::sync_with_stdio(0);cin.tie(0);
int a,b,m;
cin>>a>>b>>m;
E.push_back({0,0,0});
int mx = 0;
while(m--)
{
int u,v;
cin>>u>>v;
v+=a;
E.push_back({u,v,0});
edge[u][v]=edge[v][u]=E.size()-1;
}
for(int i=1; i<E.size(); i++)
{
int c1 = 1, c2 = 1;
int u = E[i][0], v = E[i][1];
while(A[u][c1])c1++;
while(A[v][c2])c2++;
mx=max({mx,c1,c2});
if(c1==c2)
{
E[i][2]=c1;
A[u][c1]=i;
A[v][c1]=i;
color[u][v]=color[v][u]=c1;
}
else
dfs(u,v,c1,c2);
}
cout<<mx<<"\n";
for(int i=1; i<E.size(); i++)
cout<<E[i][2]<<" ";
}
|
/*
* Copyright (C) 2013 Tom Wong. All rights reserved.
*/
#include "gttocmodel.h"
#include "gtbookmark.h"
#include "gtbookmarks.h"
#include "gtdoccommand.h"
#include "gtdocmodel.h"
#include "gtdocpage.h"
#include "gtdocument.h"
#include "gttocdelegate.h"
#include <QtCore/QDebug>
#include <QtCore/QMimeData>
#include <QtWidgets/QUndoStack>
GT_BEGIN_NAMESPACE
class GtTocModelPrivate
{
Q_DECLARE_PUBLIC(GtTocModel)
public:
GtTocModelPrivate(GtTocModel *q);
~GtTocModelPrivate();
public:
void encodeBookmarkList(const QModelIndexList &indexes,
QDataStream &stream) const;
QList<GtBookmark*> decodeBookmarkList(QDataStream &stream);
protected:
GtTocModel *q_ptr;
GtDocModel *m_docModel;
QUndoStack *m_undoStack;
QUndoCommand *m_dragCommand;
QModelIndex m_dragIndex;
GtBookmarks *m_bookmarks;
GtBookmark *m_droppedBookmark;
const QString m_mimeBookmarkList;
const quint16 m_mimeDataMagic;
const quint16 m_mimeDataVersion;
};
GtTocModelPrivate::GtTocModelPrivate(GtTocModel *q)
: q_ptr(q)
, m_docModel(0)
, m_undoStack(0)
, m_dragCommand(0)
, m_bookmarks(0)
, m_droppedBookmark(0)
, m_mimeBookmarkList(QLatin1String("application/x-gtbookmarklist"))
, m_mimeDataMagic(0xF7B4)
, m_mimeDataVersion(1)
{
}
GtTocModelPrivate::~GtTocModelPrivate()
{
}
void GtTocModelPrivate::encodeBookmarkList(const QModelIndexList &indexes,
QDataStream &stream) const
{
stream << m_mimeDataMagic << m_mimeDataVersion;
stream << indexes.size();
GtBookmark *bookmark;
QModelIndexList::ConstIterator it = indexes.begin();
for (; it != indexes.end(); ++it) {
bookmark = static_cast<GtBookmark*>((*it).internalPointer());
stream << *bookmark;
}
}
QList<GtBookmark*> GtTocModelPrivate::decodeBookmarkList(QDataStream &stream)
{
quint16 magic;
quint16 version;
int i, count;
stream >> magic;
if (magic != m_mimeDataMagic) {
qWarning() << "invalid bookmark list magic:" << magic;
return QList<GtBookmark*>();
}
stream >> version;
if (version != m_mimeDataVersion) {
qWarning() << "invalid bookmark list version:" << version;
return QList<GtBookmark*>();
}
stream >> count;
QList<GtBookmark*> list;
for (i = 0; i < count; ++i) {
GtBookmark *bookmark = new GtBookmark();
stream >> *bookmark;
list.append(bookmark);
}
return list;
}
GtTocModel::GtTocModel(QObject *parent)
: QAbstractItemModel(parent)
, d_ptr(new GtTocModelPrivate(this))
{
}
GtTocModel::~GtTocModel()
{
}
GtDocModel* GtTocModel::docModel() const
{
Q_D(const GtTocModel);
return d->m_docModel;
}
void GtTocModel::setDocModel(GtDocModel *docModel)
{
Q_D(GtTocModel);
if (docModel == d->m_docModel)
return;
if (d->m_docModel) {
disconnect(d->m_docModel,
SIGNAL(bookmarksChanged(GtBookmarks*)),
this,
SLOT(bookmarksChanged(GtBookmarks*)));
disconnect(d->m_docModel,
SIGNAL(destroyed(QObject*)),
this,
SLOT(docModelDestroyed(QObject*)));
}
if (d->m_bookmarks) {
disconnect(d->m_bookmarks,
SIGNAL(added(GtBookmark*)),
this,
SLOT(bookmarkAdded(GtBookmark*)));
disconnect(d->m_bookmarks,
SIGNAL(removed(GtBookmark*)),
this,
SLOT(bookmarkRemoved(GtBookmark*)));
disconnect(d->m_bookmarks,
SIGNAL(updated(GtBookmark*, int)),
this,
SLOT(bookmarkUpdated(GtBookmark*, int)));
}
d->m_docModel = docModel;
d->m_bookmarks = 0;
if (d->m_docModel) {
d->m_bookmarks = d->m_docModel->bookmarks();
connect(d->m_docModel,
SIGNAL(bookmarksChanged(GtBookmarks*)),
this,
SLOT(bookmarksChanged(GtBookmarks*)));
connect(d->m_docModel,
SIGNAL(destroyed(QObject*)),
this,
SLOT(docModelDestroyed(QObject*)));
}
if (d->m_bookmarks) {
connect(d->m_bookmarks,
SIGNAL(added(GtBookmark*)),
this,
SLOT(bookmarkAdded(GtBookmark*)));
connect(d->m_bookmarks,
SIGNAL(removed(GtBookmark*)),
this,
SLOT(bookmarkRemoved(GtBookmark*)));
connect(d->m_bookmarks,
SIGNAL(updated(GtBookmark*, int)),
this,
SLOT(bookmarkUpdated(GtBookmark*, int)));
}
}
QUndoStack* GtTocModel::undoStack() const
{
Q_D(const GtTocModel);
return d->m_undoStack;
}
void GtTocModel::setUndoStack(QUndoStack *undoStack)
{
Q_D(GtTocModel);
if (undoStack == d->m_undoStack)
return;
if (d->m_undoStack) {
disconnect(d->m_undoStack,
SIGNAL(destroyed(QObject*)),
this,
SLOT(undoStackDestroyed(QObject*)));
if (d->m_undoStack->parent() == this)
delete d->m_undoStack;
}
d->m_undoStack = undoStack;
if (d->m_undoStack) {
connect(d->m_undoStack,
SIGNAL(destroyed(QObject*)),
this,
SLOT(undoStackDestroyed(QObject*)));
}
}
void GtTocModel::beginDrag(const QModelIndex &index)
{
Q_D(GtTocModel);
d->m_dragCommand = new QUndoCommand();
d->m_dragIndex = index;
}
GtBookmark* GtTocModel::endDrag()
{
Q_D(GtTocModel);
if (d->m_dragCommand->childCount() == 0) {
delete d->m_dragCommand;
d->m_dragCommand = 0;
return 0;
}
d->m_dragCommand->setText(tr("\"Move Bookmark\""));
d->m_undoStack->push(d->m_dragCommand);
d->m_dragCommand = 0;
GtBookmark *dropped = d->m_droppedBookmark;
d->m_droppedBookmark = 0;
return dropped;
}
GtBookmark* GtTocModel::bookmarkFromIndex(const QModelIndex &index) const
{
if (!index.isValid())
return 0;
return static_cast<GtBookmark*>(index.internalPointer());
}
QModelIndex GtTocModel::indexFromBookmark(GtBookmark* bookmark) const
{
if (!bookmark)
return QModelIndex();
return createIndex(bookmark->index(), 0, static_cast<void *>(bookmark));
}
QModelIndex GtTocModel::index(int row, int column,
const QModelIndex &parent) const
{
Q_D(const GtTocModel);
if (!hasIndex(row, column, parent))
return QModelIndex();
GtBookmark *node;
if (!parent.isValid())
node = d->m_bookmarks->root();
else
node = static_cast<GtBookmark*>(parent.internalPointer());
GtBookmark *child = node->children()[row];
if (child)
return createIndex(row, column, child);
return QModelIndex();
}
QModelIndex GtTocModel::parent(const QModelIndex &child) const
{
if (!child.isValid())
return QModelIndex();
GtBookmark *node = static_cast<GtBookmark*>(child.internalPointer());
GtBookmark *parent = node->parent();
if (0 == parent)
return QModelIndex();
return createIndex(parent->index(), 0, static_cast<void *>(parent));
}
int GtTocModel::rowCount(const QModelIndex &parent) const
{
Q_D(const GtTocModel);
if (!d->m_bookmarks)
return 0;
if (parent.column() > 0)
return 0;
GtBookmark *node;
if (!parent.isValid())
node = d->m_bookmarks->root();
else
node = static_cast<GtBookmark*>(parent.internalPointer());
return node->children().size();
}
int GtTocModel::columnCount(const QModelIndex &) const
{
return 1;
}
QVariant GtTocModel::data(const QModelIndex &index, int role) const
{
Q_D(const GtTocModel);
if (!index.isValid())
return QVariant();
GtBookmark *node = static_cast<GtBookmark*>(index.internalPointer());
switch (role) {
case Qt::DisplayRole:
case Qt::EditRole:
case Qt::ToolTipRole:
{
QString title = node->title();
if (title.isEmpty())
title = tr("Untitled");
return QVariant(title);
}
break;
case GtTocDelegate::PageIndex:
return QVariant(node->dest().page() + 1);
case GtTocDelegate::PageLabel:
{
GtDocument *document = d->m_docModel->document();
return QVariant(document->page(node->dest().page())->label());
}
break;
default:
break;
}
return QVariant();
}
bool GtTocModel::setData(const QModelIndex &index,
const QVariant &value, int role)
{
Q_D(GtTocModel);
if (role != Qt::EditRole)
return false;
if (data(index, role) == value)
return true;
GtBookmark *node = static_cast<GtBookmark*>(index.internalPointer());
QString title(value.toString());
QUndoCommand *command = new GtRenameBookmarkCommand(d->m_docModel,
node,
title,
d->m_dragCommand);
if (!d->m_dragCommand)
d->m_undoStack->push(command);
return true;
}
Qt::ItemFlags GtTocModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return 0;
return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable |
Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled;
}
Qt::DropActions GtTocModel::supportedDropActions() const
{
return Qt::CopyAction | Qt::MoveAction;
}
QVariant GtTocModel::headerData(int, Qt::Orientation, int) const
{
return QVariant();
}
bool GtTocModel::removeRows(int row, int count, const QModelIndex &parent)
{
Q_D(GtTocModel);
GtBookmark *pb = bookmarkFromIndex(parent);
for (int i = 0; i < count; ++i) {
GtBookmark *b = pb->children(row + i);
QUndoCommand *c = new GtDelBookmarkCommand(d->m_docModel,
b,
d->m_dragCommand);
if (!d->m_dragCommand)
d->m_undoStack->push(c);
}
return true;
}
bool GtTocModel::dropMimeData(const QMimeData *data, Qt::DropAction action,
int row, int column, const QModelIndex &parent)
{
Q_D(GtTocModel);
if (!data || !(action == Qt::CopyAction || action == Qt::MoveAction))
return false;
if (!parent.isValid())
return false;
if (d->m_dragCommand) {
int dragRow = d->m_dragIndex.row();
if ((dragRow == row || dragRow + 1 == row) &&
d->m_dragIndex.parent() == parent)
{
// drag and drop to the same position
return false;
}
}
if (row > rowCount(parent))
row = rowCount(parent);
if (row == -1)
row = rowCount(parent);
if (column == -1)
column = 0;
if (data->hasFormat(d->m_mimeBookmarkList)) {
// decode and insert
QByteArray encoded = data->data(d->m_mimeBookmarkList);
QDataStream stream(&encoded, QIODevice::ReadOnly);
QList<GtBookmark*> list(d->decodeBookmarkList(stream));
GtBookmark *pb = bookmarkFromIndex(parent);
GtBookmark *nb = 0;
if (row < pb->children().size())
nb = pb->children(row);
QList<GtBookmark*>::iterator it;
for (it = list.begin(); it != list.end(); ++it) {
QUndoCommand *c = new GtAddBookmarkCommand(
d->m_docModel, pb, nb, *it, d->m_dragCommand);
if (!d->m_dragCommand)
d->m_undoStack->push(c);
nb = *it;
}
return true;
}
return false;
}
QMimeData *GtTocModel::mimeData(const QModelIndexList &indexes) const
{
Q_D(const GtTocModel);
if (indexes.count() <= 0)
return 0;
QMimeData *data = new QMimeData();
QByteArray encoded;
QDataStream stream(&encoded, QIODevice::WriteOnly);
d->encodeBookmarkList(indexes, stream);
data->setData(d->m_mimeBookmarkList, encoded);
return data;
}
QStringList GtTocModel::mimeTypes() const
{
Q_D(const GtTocModel);
return QStringList() << d->m_mimeBookmarkList;
}
void GtTocModel::bookmarksChanged(GtBookmarks *bookmarks)
{
Q_D(GtTocModel);
beginResetModel();
if (d->m_bookmarks) {
disconnect(d->m_bookmarks,
SIGNAL(added(GtBookmark*)),
this,
SLOT(bookmarkAdded(GtBookmark*)));
disconnect(d->m_bookmarks,
SIGNAL(removed(GtBookmark*)),
this,
SLOT(bookmarkRemoved(GtBookmark*)));
disconnect(d->m_bookmarks,
SIGNAL(updated(GtBookmark*, int)),
this,
SLOT(bookmarkUpdated(GtBookmark*, int)));
}
d->m_bookmarks = bookmarks;
if (d->m_bookmarks) {
connect(d->m_bookmarks,
SIGNAL(added(GtBookmark*)),
this,
SLOT(bookmarkAdded(GtBookmark*)));
connect(d->m_bookmarks,
SIGNAL(removed(GtBookmark*)),
this,
SLOT(bookmarkRemoved(GtBookmark*)));
connect(d->m_bookmarks,
SIGNAL(updated(GtBookmark*, int)),
this,
SLOT(bookmarkUpdated(GtBookmark*, int)));
}
endResetModel();
}
void GtTocModel::bookmarkAdded(GtBookmark *bookmark)
{
Q_D(GtTocModel);
if (d->m_dragCommand) {
if (!d->m_droppedBookmark)
d->m_droppedBookmark = bookmark;
}
emit layoutChanged();
}
void GtTocModel::bookmarkRemoved(GtBookmark *)
{
emit layoutChanged();
}
void GtTocModel::bookmarkUpdated(GtBookmark *bookmark, int)
{
QModelIndex index = indexFromBookmark(bookmark);
emit dataChanged(index, index);
}
void GtTocModel::docModelDestroyed(QObject *object)
{
Q_D(GtTocModel);
if (object == static_cast<QObject *>(d->m_docModel))
setDocModel(0);
}
void GtTocModel::undoStackDestroyed(QObject *object)
{
Q_D(GtTocModel);
if (object == static_cast<QObject *>(d->m_undoStack))
setUndoStack(0);
}
GT_END_NAMESPACE
|
// DBTestDlg.cpp: 구현 파일
//
#include "pch.h"
#include "framework.h"
#include "DBTest.h"
#include "DBTestDlg.h"
#include "afxdialogex.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
#define DB_LOCATE _T("localhost")// 내지 Server IP
#define DB_USER _T("root") //DB 접속 계정
#define DB_PASS _T("1234") //DB 계정 비밀 번호
#define DB_BASE _T("testdb")// DB 이름
#define DB_TABLE _T("memberdb")// DB 테이블 이름
#define DB_DTABLE(tabName) "testdb."##tabName
// 응용 프로그램 정보에 사용되는 CAboutDlg 대화 상자입니다.
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
// 대화 상자 데이터입니다.
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_ABOUTBOX };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 지원입니다.
// 구현입니다.
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
// CDBTestDlg 대화 상자
CDBTestDlg::CDBTestDlg(CWnd* pParent /*=nullptr*/)
: CDialogEx(IDD_DBTEST_DIALOG, pParent)
, m_szName(_T(""))
, m_szMemNo(_T(""))
, m_szAddress(_T(""))
, m_ph1(_T(""))
, m_szPh2(_T(""))
, m_szPh3(_T(""))
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CDBTestDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_LIST_DATA, m_listData);
DDX_Control(pDX, IDC_EDIT_MemNo, m_EditMemNo);
DDX_Text(pDX, IDC_EDIT_NAME, m_szName);
DDX_Text(pDX, IDC_EDIT_MemNo, m_szMemNo);
DDX_Text(pDX, IDC_EDIT_ADDRESS, m_szAddress);
DDX_Text(pDX, IDC_EDIT_PH1, m_ph1);
DDX_Text(pDX, IDC_EDIT_PH2, m_szPh2);
DDX_Text(pDX, IDC_EDIT_PH3, m_szPh3);
}
BEGIN_MESSAGE_MAP(CDBTestDlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_BUTTON_EDIT, &CDBTestDlg::OnClickedButtonEdit)
ON_BN_CLICKED(IDC_BUTTON_DEL, &CDBTestDlg::OnClickedButtonDel)
ON_BN_CLICKED(IDC_BUTTON_APPEND, &CDBTestDlg::OnClickedButtonAppend)
END_MESSAGE_MAP()
// CDBTestDlg 메시지 처리기
BOOL CDBTestDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// 시스템 메뉴에 "정보..." 메뉴 항목을 추가합니다.
// IDM_ABOUTBOX는 시스템 명령 범위에 있어야 합니다.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != nullptr)
{
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// 이 대화 상자의 아이콘을 설정합니다. 응용 프로그램의 주 창이 대화 상자가 아닐 경우에는
// 프레임워크가 이 작업을 자동으로 수행합니다.
SetIcon(m_hIcon, TRUE); // 큰 아이콘을 설정합니다.
SetIcon(m_hIcon, FALSE); // 작은 아이콘을 설정합니다.
// TODO: 여기에 추가 초기화 작업을 추가합니다.
MYSQL Connect;
MYSQL_ROW Sql_Row;
MYSQL_RES* Sql_Result;
CString Query;
Query.Format(_T("Select * From %s.%s;"), DB_BASE, DB_TABLE);
mysql_init(&Connect);
mysql_real_connect(&connect, DB_LOCATE, DB_USER, DB_PASS, DB_DTABLE(DB_TABLE), 8080, NULL, 0);
mysql_query(&Connect, Query);
Sql_Result = mysql_store_result(&Connect);
CRect rect;
m_listData.GetClientRect(&rect);
m_listData.DeleteAllItems(); // 기존 리스트출력을 비운다.
m_listData.SetExtendedStyle(LVS_EX_GRIDLINES); // 리스트 스타일
m_listData.InsertColumn(0, _T("회원번호"), LVCFMT_LEFT, rect.right / 8, -1);
m_listData.InsertColumn(1, _T("이 름"), LVCFMT_CENTER, rect.right / 6, -1);
m_listData.InsertColumn(2, _T("주 소"), LVCFMT_CENTER, rect.right / 2, -1);
m_listData.InsertColumn(3, _T("전화번호"), LVCFMT_CENTER, rect.right / 4, -1);
return TRUE; // 포커스를 컨트롤에 설정하지 않으면 TRUE를 반환합니다.
}
void CDBTestDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialogEx::OnSysCommand(nID, lParam);
}
}
// 대화 상자에 최소화 단추를 추가할 경우 아이콘을 그리려면
// 아래 코드가 필요합니다. 문서/뷰 모델을 사용하는 MFC 애플리케이션의 경우에는
// 프레임워크에서 이 작업을 자동으로 수행합니다.
void CDBTestDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // 그리기를 위한 디바이스 컨텍스트입니다.
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// 클라이언트 사각형에서 아이콘을 가운데에 맞춥니다.
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// 아이콘을 그립니다.
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialogEx::OnPaint();
}
}
// 사용자가 최소화된 창을 끄는 동안에 커서가 표시되도록 시스템에서
// 이 함수를 호출합니다.
HCURSOR CDBTestDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CDBTestDlg::OnClickedButtonEdit()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
}
void CDBTestDlg::OnClickedButtonDel()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
}
void CDBTestDlg::OnClickedButtonAppend()
{
// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다.
}
|
#ifndef SHOC_MODE_GCM_H
#define SHOC_MODE_GCM_H
#include "shoc/mode/ctr.h"
namespace shoc {
/**
* @brief Shift bits right in array of integer elements from most significant bit
* and considering 0-th byte as the left most.
* uint16_t example: 0b10000000'11100001 ==> 0b11000000'01110000.
*
* @tparam T Integer type
* @tparam L Length of array
* @param x Array of integers, nullptr not acceptable!
* @param len Number of elements
*/
template<class T, size_t L>
constexpr void gcm_shift_right_reflected(T (&x)[L])
{
for (int i = L - 1; i > 0; --i) {
x[i] >>= 1;
x[i] |= (x[i - 1] & 1) << (sizeof(T) * 8 - 1);
}
x[0] >>= 1;
}
/**
* @brief Multiplication in Galois field 2^128.
*
* @param x First 128-bit vector multiplicand
* @param y Second 128-bit vector multiplier
* @param z Output 128-bit vector
*/
inline void gmul(const byte *x, const byte *y, byte *z)
{
byte v[16];
zero(z, 16);
copy(v, y, 16);
for (int i = 0; i < 16; ++i) {
for (int j = 7; j >= 0; --j) {
if (utl::get_bit(x[i], j)) {
xorb(z, v);
}
if (utl::get_bit(v[15], 0)) {
gcm_shift_right_reflected(v);
v[0] ^= 0xe1;
} else {
gcm_shift_right_reflected(v);
}
}
}
}
inline void ghash(const byte *h, const byte *x, size_t x_len, byte *y)
{
byte t[16];
auto blocks = x_len >> 4;
auto remain = x_len & 0xf;
for (size_t i = 0; i < blocks; ++i, x += 16) {
xorb(y, x);
gmul(y, h, t);
copy(y, t, 16);
}
if (remain) {
copy(t, x, remain);
zero(t + remain, 16 - remain);
xorb(y, t);
gmul(y, h, t);
copy(y, t, 16);
}
}
inline void gcm_ghash(
const byte *h,
const byte *aad, size_t aad_len,
const byte *txt, size_t txt_len,
byte *out)
{
// Apply GHASH to [pad(aad) + pad(ciphertext) + 64-bit(aad_len * 8), 64-bit(len * 8))]
byte len[16];
zero(out, 16);
putbe(uint64_t(aad_len * 8), len);
putbe(uint64_t(txt_len * 8), len + 8);
ghash(h, aad, aad_len, out);
ghash(h, txt, txt_len, out);
ghash(h, len, 16, out);
}
template<class E>
inline void gcm_init(const byte *iv, size_t iv_len, byte *h, byte *j0, E &ciph)
{
// Init hash subkey
zero(h, 16);
ciph.encrypt(h, h);
// Prepare J0
zero(j0, 16);
if (iv_len == 12) {
copy(j0, iv, 12);
j0[15] = 0x01;
} else {
// NOTE: I'm pretty sure the GCM paper has error on Page 15, Algorithm 4: GCM-AE, Step 2:
//
// "Otherwise, the IV is padded with the minimum number of '0' bits, possibly none, so
// that the length of the resulting string is a multiple of 128 bits (the block size);
// this string in turn is appended with 64 additional '0' bits, followed by the 64-bit
// representation of the length of the IV"
//
// https://nvlpubs.nist.gov/nistpubs/legacy/sp/nistspecialpublication800-38d.pdf
//
// So, first padding with '0' till (N*128)-bits before 64-bit ['0'] and [iv_len] blocks
// is done in code commented below, but it gives incorrect results with test vectors.
// byte pad[16] = {};
// auto pad_len = 16 - (iv_len & 0xf);
// ghash(h, iv, iv_len, j0);
// ghash(h, pad, pad_len, j0);
// putbe(uint64_t(iv_len * 8), pad + 8);
// ghash(h, pad, 16, j0);
byte pad[16] = {};
putbe(uint64_t(iv_len * 8), pad + 8);
ghash(h, iv, iv_len, j0);
ghash(h, pad, 16, j0);
}
}
template<class E>
inline void gcm_gctr(const byte *j0, const byte *in, byte *out, size_t len, E &ciph)
{
// Increment J0 and pass to GCTR
byte ij0[16];
copy(ij0, j0, 16);
incc(ij0);
ctrf(ij0, in, out, len, ciph);
}
/**
* @brief Encrypt with block cipher in Galois counter mode. All pointers MUST be
* valid when relevant length is not 0. Tag length MUST be {4, 8, 12, 13, 14, 15, 16}:
* https://nvlpubs.nist.gov/nistpubs/legacy/sp/nistspecialpublication800-38d.pdf
*
* @tparam E BLock cipher
* @param key Key
* @param iv Initial vector
* @param iv_len Initial vector length
* @param aad Additional authenticated data
* @param aad_len Additional authenticated data length
* @param tag Output tag
* @param tag_len Output tag desired length
* @param in Plain text
* @param out Cipher text
* @param len Text length
* @return true on success, false if tag length is invalid
*/
template<class E>
inline bool gcm_encrypt(
const byte *key,
const byte *iv, size_t iv_len,
const byte *aad, size_t aad_len,
byte *tag, size_t tag_len,
const byte *in,
byte *out, size_t len)
{
if (tag_len > 16 ||
tag_len < 4 || (tag_len < 12 && tag_len & 3))
return false;
E ciph {key};
byte h[16];
byte j[16];
byte s[16];
byte t[16];
gcm_init(iv, iv_len, h, j, ciph); // 1. Init hash subkey and prepare J0
gcm_gctr(j, in, out, len, ciph); // 2. Increment J0 and pass to GCTR
gcm_ghash(h, aad, aad_len, out, len, s); // 3. Apply GHASH to [pad(aad) + pad(ciphertext) + 64-bit(aad_len * 8), 64-bit(len * 8))]
ctrf(j, s, t, sizeof(t), ciph); // 4. Generate full tag
copy(tag, t, tag_len); // 5. Truncate tag to the desired length
return true;
}
/**
* @brief Decrypt with block cipher in Galois counter mode. All pointers MUST be
* valid when relevant length is not 0. Tag length MUST be {4, 8, 12, 13, 14, 15, 16}:
* https://nvlpubs.nist.gov/nistpubs/legacy/sp/nistspecialpublication800-38d.pdf
*
* @tparam E Block cipher
* @param key Key
* @param iv Initial vector
* @param iv_len Initial vector length
* @param aad Additional authenticated data
* @param aad_len Additional authenticated data length
* @param tag Input tag
* @param tag_len Input tag length
* @param in Cipher text
* @param out Plain text
* @param len Text length
* @return true on success, false if tag length is invalid or authentication failed
*/
template<class E>
inline bool gcm_decrypt(
const byte *key,
const byte *iv, size_t iv_len,
const byte *aad, size_t aad_len,
const byte *tag, size_t tag_len,
const byte *in,
byte *out, size_t len)
{
if (tag_len > 16 ||
tag_len < 4 || (tag_len < 12 && tag_len & 3))
return false;
E ciph {key};
byte h[16];
byte j[16];
byte s[16];
byte t[16];
gcm_init(iv, iv_len, h, j, ciph); // 1. Init hash subkey and prepare J0
gcm_ghash(h, aad, aad_len, in, len, s); // 2. Apply GHASH to [pad(aad) + pad(ciphertext) + 64-bit(aad_len * 8), 64-bit(len * 8))]
gcm_gctr(j, in, out, len, ciph); // 3. Increment J0 and pass to GCTR
ctrf(j, s, t, sizeof(t), ciph); // 4. Generate full tag
if (memcmp(t, tag, tag_len)) { // 5. Compare tag with the given
zero(out, len);
return false;
}
return true;
}
}
#endif
|
/*
实验题目:无向图存储结构的建立与搜索(遍历)
实验内容:
图的搜索(遍历)算法是图型结构相关算法的基础,本实验要求编写程序演示无向图三种典型存储结构的建立和(搜索)遍历过程。
实验要求:
1.分别实现无向图的邻接矩阵、邻接表和邻接多重表存储结构的建立算法,分析和比较各建立算法的时间复杂度以及存储结构的空间占用情况;
2.实现无向图的邻接矩阵、邻接表和邻接多重表三种存储结构的相互转换算法;
3.在上述三种存储结构上,分别实现无向图的深度优先搜索(递归和非递归)和广度优先搜索算法。并以适当的方式存储和显示相应的搜索结果(深度优先或广度优先生成森林(或生成树)、深度优先或广度优先序列和编号);
4.分析搜索算法的时间复杂度;
5.以文件形式输入图的顶点和边,并显示相应的结果。要求顶点不少于10个,边不少于13个;
6.软件功能结构安排合理,界面友好,便于使用
----------------------------------------------------------------------------------------------
*/
#include<iostream>
#include<fstream>
#define max 40
#define ipath "f:\\desktop\\map.in"
#define opath "f:\\desktop\\map.out"
struct edgenode
{
int vex;
edgenode *next;
};
typedef edgenode *edge;
edge v[max]={NULL};
struct multiedgenode
{
int flag,x1,x2;
multiedgenode *next1,*next2;
};
typedef multiedgenode *multiedge;
multiedge vv[max]={NULL};
int n,m,a[max][max],b[max],s[max],top;
using namespace std;
void dfs_matrix_r(int x)
{
int i;
s[++top]=x;
b[x]=1;
for (i=0;i<n;i++)
{
if (a[x][i] && !b[i])
{
dfs_matrix_r(i);
}
}
}
void dfs_matrix_norecursion(int x)
{
cout<<"\ndfs_matrix_norecursion:\n";
int o,j;
memset(b,-1,sizeof(b));
for (j=0;j<n;j++)
{
if (b[j]!=-1) continue;
memset(s,0,sizeof(s));
s[0]=j;
top=0;
cout<<j<<' ';
do
{
do
{
o=++b[s[top]];
if (o==n) break;
if (a[s[top]][o] && (b[o]==-1))
{
cout<<o<<' ';
s[++top]=o;
break;
}
}while (1);
if (o==n) top--;
}while (top!=-1);
cout<<endl;
}
}
void dfs_matrix_recursion(int x)
{
cout<<"\ndfs_matrix_recursion:\n";
int i,j;
memset(b,0,sizeof(b));
for (j=0;j<n;j++)
{
if (b[j]!=0) continue;
top=-1;
dfs_matrix_r(j);
for (i=0;i<=top;i++)
{
cout<<s[i]<<' ';
}
cout<<endl;
}
}
void bfs_matrix(int x)
{
cout<<"\nbfs_matrix:\n";
int l,r,i,j;
memset(s,0,sizeof(s));
for (j=0;j<n;j++)
{
if (s[j]) continue;
l=r=0;
b[0]=j;s[j]=1;
do
{
for (i=0;i<n;i++)
{
if (a[b[l]][i] && !s[i])
{
b[++r]=i;
s[i]=1;
}
}
l++;
}while (l<=r);
for (i=0;i<=r;i++)
{
cout<<b[i]<<' ';
}
cout<<endl;
}
}
void dfs_list_r(int x)
{
edge p=v[x];
s[++top]=x;
b[x]=1;
while((p=p->next)!=NULL)
{
if (!b[p->vex])
dfs_list_r(p->vex);
}
}
void dfs_list_norecursion(int x)
{
cout<<"\ndfs_list_norecursion:\n";
int i,o,j;
edge e[max];
for (i=0;i<n;i++)
{
e[i]=v[i];
v[i]->vex=0;
}
for (j=0;j<n;j++)
{
if (v[j]->vex) continue;
v[j]->vex=1;
memset(s,0,sizeof(s));
s[0]=j;top=0;
cout<<j<<' ';
do
{
do
{
e[s[top]]=e[s[top]]->next;
if (!e[s[top]]) break;
o=e[s[top]]->vex;
if (!v[o]->vex)
{
v[o]->vex=1;
cout<<o<<' ';
s[++top]=o;
break;
}
}while (1);
if (!e[s[top]]) top--;
}while (top!=-1);
cout<<endl;
}
}
void dfs_list_recursion(int x)
{
cout<<"\ndfs_list_recursion:\n";
int i,j;
memset(b,0,sizeof(b));
for (j=0;j<n;j++)
{
if (b[j])continue;
top=-1;
dfs_list_r(j);
for (i=0;i<=top;i++)
{
cout<<s[i]<<' ';
}
cout<<endl;
}
}
void bfs_list(int x)
{
cout<<"\nbfs_list:\n";
edge p;
int l,r,i,j;
memset(s,0,sizeof(s));
for (j=0;j<n;j++)
{
if (s[j]) continue;
l=r=0;
b[0]=j;s[j]=1;
do
{
p=v[b[l]];
while ((p=p->next)!=NULL)
{
if (!s[p->vex])
{
b[++r]=p->vex;
s[p->vex]=1;
}
}
l++;
}while (l<=r);
for (i=0;i<=r;i++)
{
cout<<b[i]<<' ';
}
cout<<endl;
}
}
multiedge next(multiedge p,int i)
{
if (p->x1==i) return p->next1;
return p->next2;
}
int other(multiedge p,int i)
{
if (p->x1==i) return p->x2;
return p->x1;
}
void dfs_multilist_r(int x)
{
multiedge p=vv[x]->next1;
s[++top]=x;
b[x]=1;
while (p)
{
if (p->x1==x && !b[p->x2])
dfs_multilist_r(p->x2);
else if (p->x2==x && !b[p->x1])
dfs_multilist_r(p->x1);
p=next(p,x);
}
}
void dfs_multilist_recursion(int x)
{
int i,j;
cout<<"\ndfs_multilist_recursion:\n";
memset(b,0,sizeof(b));
for (j=0;j<n;j++)
{
if (b[j])continue;
top=-1;
dfs_multilist_r(j);
for (i=0;i<=top;i++)
{
cout<<s[i]<<' ';
}
cout<<endl;
}
}
void dfs_multilist_norecursion(int x)
{
cout<<"\ndfs_multilist_norecursion:\n";
int i,o,j;
memset(s,0,sizeof(s));
multiedge e[max];
for (i=0;i<n;i++) {e[i]=vv[i]->next1;vv[i]->x1=0;}
for (j=0;j<n;j++)
{
if (vv[j]->x1) continue;
s[0]=j;top=0;
cout<<j<<' ';
vv[j]->x1=1;
if (!e[j]) {cout<<endl; continue;}
do
{
do
{
o=other(e[s[top]],s[top]);//下个点
if (!vv[o]->x1)//没走过
{
vv[o]->x1=1;//标记走过
cout<<o<<' ';//输出
s[++top]=o;
break;
}
}while (e[s[top]]=next(e[s[top]],s[top]));
if (!e[s[top]]) top--;
}while (top!=-1);
cout<<endl;
}
}
void bfs_multilist(int x)
{
cout<<"\nbfs_multilist:\n";
multiedge p;
int j,l,r=0,i;
memset(s,0,sizeof(s));
for (j=0;j<n;j++)
{
if (s[j])continue;
l=r=0;
b[0]=j;s[j]=1;
do
{
p=vv[b[l]]->next1;
if (p)
do
{
i=other(p,b[l]);
if (!s[i])
{
b[++r]=i;
s[i]=1;
}
}while ((p=next(p,b[l]))!=NULL);
l++;
}while (l<=r);
for (i=0;i<=r;i++)
{
cout<<b[i]<<' ';
}
cout<<endl;
}
}
void input()
{
int i,j,k;
edge p;
multiedge q;
memset(a,0,sizeof(a));
cin>>n>>m;
for (i=0;i<n;i++){v[i]=new edgenode;v[i]->next=NULL;vv[i]=new multiedgenode;vv[i]->next1=NULL;}
for (i=0;i<m;i++)
{
//martix
cin>>j>>k;
a[j][k]=a[k][j]=1;
//list
p=new edgenode;
p->next=v[j]->next;
p->vex=k;
v[j]->next=p;
p=new edgenode;
p->next=v[k]->next;
p->vex=j;
v[k]->next=p;
//multilist
q=new multiedgenode;
q->x1=j;q->x2=k;
q->next1=vv[j]->next1;
vv[j]->next1=q;
q->next2=vv[k]->next1;
vv[k]->next1=q;
}
}
multiedge local(multiedge vx[],int x,int y)
{
multiedge p=vx[x];
if (!p) return NULL;
p=p->next1;
while (p!=NULL)
{
if (other(p,x)==y) break;
p=next(p,x);
}
return p;
}
void search()
{
int i,j;
edge p;
multiedge q;
cout<<"1.\nadjacency matrix:\n";
for (i=0;i<n;i++)
{
for (j=0;j<n;j++)
{
cout<<a[i][j]<<'\t';
}
cout<<endl;
}
dfs_matrix_recursion(0);
dfs_matrix_norecursion(0);
bfs_matrix(0);
cout<<"\n\n2.\nadjacency list:\n";
for (i=0;i<n;i++)
{
p=v[i];
cout<<i<<":\t";
if (p==NULL) {cout<<endl;continue;}
while ((p=p->next)!=NULL)
{
cout<<p->vex<<'\t';
}
cout<<endl;
}
dfs_list_recursion(0);
dfs_list_norecursion(0);
bfs_list(0);
cout<<"\n\n3.\nadjacency multilist:\n";
for (i=0;i<n;i++)
{
q=vv[i]->next1;
cout<<i<<":\t";
if (q==NULL){cout<<endl;continue;}
do
{
cout<<'('<<q->x1<<','<<q->x2<<")\t";
q=next(q,i);
} while (q);
cout<<endl;
}
dfs_multilist_recursion(0);
dfs_multilist_norecursion(0);
bfs_multilist(0);
}
void change()
{
int i,j,k;
edge p;
multiedge q;
multiedge vv1[max]={NULL};
edge v1[max]={NULL};
int a1[max][max];
memset(a1,0,sizeof(a1));
for (i=0;i<n;i++){v1[i]=new edgenode;v1[i]->next=NULL;vv1[i]=new multiedgenode;vv1[i]->next1=NULL;}
cout<<"\n\nchange:\n";
cout<<"1.matrix->list:\n";
for (i=0;i<n;i++)
{
for (j=i+1;j<n;j++)
{
if (a[i][j])
{
if (!v1[i]) {v1[i]=new edgenode;v1[i]->next=NULL;}
p=new edgenode;
p->next=v1[i]->next;
p->vex=j;
v1[i]->next=p;
if (!v1[j]) {v1[j]=new edgenode;v1[j]->next=NULL;}
p=new edgenode;
p->next=v1[j]->next;
p->vex=i;
v1[j]->next=p;
}
}
}
for (i=0;i<n;i++)
{
p=v1[i];
cout<<i<<":\t";
while ((p=p->next)!=NULL)
{
cout<<p->vex<<'\t';
}
cout<<endl;
}
cout<<"\n2.list->multilist:\n";
for (i=0;i<n;i++)
{
p=v1[i];
while(p=p->next)
{
j=i;
k=p->vex;
if (local(vv1,j,k)) continue;
if (!vv1[j]) {vv1[j]=new multiedgenode;vv1[j]->next1=NULL;}
if (!vv1[k]) {vv1[k]=new multiedgenode;vv1[k]->next1=NULL;}
q=new multiedgenode;
q->x1=j;q->x2=k;
q->next1=vv1[j]->next1;
vv1[j]->next1=q;
q->next2=vv1[k]->next1;
vv1[k]->next1=q;
}
}
for (i=0;i<n;i++)
{
q=vv1[i]->next1;
cout<<i<<":\t";
if (q==NULL) {cout<<endl;continue;}
do
{
cout<<'('<<q->x1<<','<<q->x2<<")\t";
q=next(q,i);
} while (q);
cout<<endl;
}
cout<<"\n3.multilist->matrix:\n";
for (i=0;i<n;i++)
{
q=vv1[i]->next1;
if (!q) continue;
while (q=next(q,i))
{
a1[q->x1][q->x2]=a1[q->x2][q->x1]=1;
}
}
for (i=0;i<n;i++)
{
for (j=0;j<n;j++)
{
cout<<a1[i][j]<<'\t';
}
cout<<endl;
}
}
void main()
{
fstream ifile(ipath,ios::in);
fstream ofile(opath,ios::out);
if (!(ifile&&ofile)) {cout<<"can't open file!"; return;}
cin.rdbuf(ifile.rdbuf());
cout.rdbuf(ofile.rdbuf());
input();
search();
change();
ifile.close();
ofile.close();
//getchar();
}
|
#include "../../gl_framework.h"
using namespace glmock;
extern "C" {
#undef glGenFramebuffers
void CALL_CONV glGenFramebuffers(GLsizei n, GLuint* framebuffers) {
}
DLL_EXPORT PFNGLGENFRAMEBUFFERSPROC __glewGenFramebuffers = &glGenFramebuffers;
}
|
#pragma once
#include "GameNode.h"
// tile 21 x 16
#define MAXTILEX 21
#define MAXTILEY 16
#define MAXWINTILEX WINSIZEX / 25 // 40
#define MAXWINTILEY WINSIZEY / 25 // 30
struct tagTileInfo {
RECT rc;
int x, y; // 윈도우에서 타일의 위치 x, y
int tileX, tileY; // 이미지에서 읽어올 타일 x, y
bool check; // 그려졌는지 체크
};
class MapTool : public GameNode
{
public:
MapTool();
~MapTool();
};
|
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
using namespace std;
int iter = 0;
void gauss(double**& A, double*& B,int size);
void cholesky(double**& A, double*& B,int size);
void jacobi(double**& A, double*& B,int size);
void gauss_seidel(double**& A, double*& B,int size);
void reverse(double**& A, double*& B,int size);
void create_A_B(double**& matrix, double*& vector,int old_size,int size);
void create_my_A_B(double**& matrix, double*& vector);
int main() {
int command;
int size = 4;
int old_size;
double** matrix = nullptr;
double* vector= nullptr;
create_my_A_B(matrix, vector);
while(1) {
system("cls");
cout << "\nChoose method for solve liniar ecuation:" << endl;
cout << "\n1. GAUSS METHOD";
cout << "\n2. CHOLESKY METHOD";
cout << "\n3. JACOBI METHOD";
cout << "\n4. GAUSS-SEIDEL METHOD";
cout << "\n5. JORDAN-GAUSS METHOD (A^-1)";
cout << "\n6. PRINT ALL DATES";
cout << "\n7. INSERT ANOTHER MATRIX AND VECTOR\n";
cout << "\n8. EXIT";
cout << "\n\nCommand: ";
cin >> command;
switch (command) {
case 1 :
system("cls");
gauss(matrix,vector,size);
cout << endl;
system("pause");
break;
case 2 :
system("cls");
cholesky(matrix,vector,size);
cout << endl;
system("pause");
break;
case 3 :
system("cls");
jacobi(matrix,vector,size);
cout << endl;
system("pause");
break;
case 4 :
system("cls");
gauss_seidel(matrix,vector,size);
cout << endl;
system("pause");
break;
case 5 :
system("cls");
reverse(matrix,vector,size);
system("pause");
break;
case 6 :
system("cls");
gauss(matrix,vector,size);
cout << endl;
cholesky(matrix,vector,size);
cout << endl;
jacobi(matrix,vector,size);
cout << endl;
gauss_seidel(matrix,vector,size);
cout << endl;
reverse(matrix,vector,size);
system("pause");
break;
case 7 :
system("cls");
cout << "Insert DIMENSION for Matrix A and Vector B : ";
old_size = size;
cin >> size;
create_A_B(matrix, vector, old_size, size);
break;
case 8 :
system("cls");
cout << "Good Bye!" << endl;
exit(1);
default:
system("cls");
cout << "Press correct key!\a\n" << endl;
system("pause");
break;
}
}
}
void create_A_B(double**& matrix, double*& vector,int old_size,int size) {
if(matrix) {
for(int i=0; i< old_size; i++)
delete[] matrix[i];
delete matrix;
matrix = nullptr;
}
if(vector) {
delete [] vector;
vector = nullptr;
}
matrix = new double*[size];
for (int i = 0; i < size; i++) {
matrix[i] = new double[size];
}
vector = new double[size];
cout << "Insert Matrix A:\n";
for (int j = 0; j < size; j++) {
for (int i = 0; i < size; i++) {
cout << "A[" << j+1 << "," << i+1 << "] = ";
cin >> matrix[j][i];
}
}
cout << "\nInsert Vector B:\n";
for (int k = 0; k < size; k++) {
cout << "B[" << k+1 << "] = ";
cin >> vector[k];
}
}
void create_my_A_B(double**& matrix, double*& vector) {
if(matrix) {
for(int i=0; i< 4; i++)
delete[] matrix[i];
delete matrix;
matrix = nullptr;
}
if(vector) {
delete [] vector;
vector = nullptr;
}
matrix = new double*[4];
for (int i = 0; i < 4; i++) {
matrix[i] = new double[4];
}
vector = new double[4];
matrix[0][0] = 6.1; matrix[0][1] = -1.9; matrix[0][2] = 0.4; matrix[0][3] = 0.2;
matrix[1][0] = -1.9; matrix[1][1] = 16.2; matrix[1][2] = 1.8; matrix[1][3] = 1.4;
matrix[2][0] = 0.4; matrix[2][1] = 1.8; matrix[2][2] = 12.7; matrix[2][3] = -0.6;
matrix[3][0] = 0.2; matrix[3][1] = 1.4; matrix[3][2] = -0.6; matrix[3][3] = 13.1;
vector[0] = 7.1; vector[1] = 10,2; vector[2] = -7.5; vector[3] = 8.6;
}
void gauss(double**& A, double*& B,int size) {
int l;
double t,x[size],a[size][size],b[size];
for (int i = 0; i < size; i++) {
b[i] = B[i];
for (int j = 0; j < size; j++) {
a[i][j] = A[i][j];
}
}
l=0;
while (l < size) {
for (int i = l + 1; i < size; i++) {
t = a[i][l] / a[l][l];
for (int j = l; j < size; j++) {
a[i][j] -= t * a[l][j];
}
b[i] -= t * b[l];
}
l++;
}
for (int i = size - 1; i >= 0; i--) {
t = 0;
for (int j = size - 1; j > i; j--) {
t += a[i][j] * x[j];
}
t = b[i] - t;
x[i] = t / a[i][i];
}
cout << "\nGAUSS METHOD:\n";
for (int i = 0; i < size; i++) {
printf("%7.3f ", x[i]);
}
}
//---------------------------------------------------------------------------
void cholesky(double**& A, double*& B,int size) {
double t,x[size],l[size][size],y[size];
l[0][0] = sqrt(A[0][0]);
for(int i = 1; i < size; i++) {
l[i][0] = A[i][0] / l[0][0];
}
for (int k = 1; k < size; k++) {
t = 0;
for (int j = 0; j < k - 1; j++) {
t += l[k][j] * l[k][j];
}
l[k][k] = sqrt(A[k][k] - t);
for (int i = k + 1; i < size; i++) {
t = 0;
for ( int j = 0; j < k - 1; j++) {
t += l[i][j] * l[k][j];
}
l[i][k] = (A[i][k] - t) / l[k][k];
}
}
for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size; j++) {
l[i][j] = l[j][i];
}
}
for (int i = 0; i < size; i++) {
t = 0;
for (int j = 0; j < i; j++) {
t += l[i][j] * y[j];
}
t = B[i] - t;
y[i] = t / l[i][i];
}
for(int i= size-1;i>=0;i--) {
t = 0;
for (int j = size - 1; j > i; j--) {
t += l[i][j] * x[j];
}
t = y[i] - t;
x[i] = t / l[i][i];
}
cout << "\nCHOLESKY METHOD:\n";
for (int i = 0; i < size; i++) {
printf("%7.3f ", x[i]);
}
}
//---------------------------------------------------------------------------
void jacobi(double**& A, double*& B,int size) {
int k1 = 0;
iter = 0;
double v, x[size], q[size][size], d[size], s[size][size], t[size][size], x1[size], error;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (i == j) {
s[i][j] = 1 / A[i][j];
t[i][j] = 0;
}
else {
s[i][j] = 0;
t[i][j] = A[i][j];
}
}
}
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
v = 0;
for (int m = 0; m < size; m++)
v += s[i][m] * t[m][j];
q[i][j] = -v;
}
}
for (int i = 0; i < size; i++) {
v = 0;
for (int m = 0; m < size; m++) {
v += s[i][m] * B[m];
}
d[i] = v;
}
for (int i = 0; i < size; i++) {
x[i] = d[i];
}
do {
k1++;
for (int i = 0; i < size; i++) {
x1[i] = x[i];
}
for (int i = 0; i < size; i++) {
v = 0;
for (int m = 0; m < size; m++) {
v += x1[m] * q[i][m];
}
x[i] = v + d[i];
}
error = fabs(x1[0] - x[0]);
for (int m = 0; m < size; m++) {
if (error < fabs(x1[m] - x[m]))
error = fabs(x1[m] - x[m]);
}
iter ++;
}
while(error > 0.001);
cout << "JACOBI METHOD:\n";
for (int i = 0; i < size; i++) {
printf("%7.3f ", x[i]);
}
cout << "\n It occured " << iter << " iterations to aproximate system solution to error 0.001";
}
//---------------------------------------------------------------------------
void gauss_seidel(double**& A, double*& B,int size) {
int k1 = 0;
iter = 0;
double v, x[size], q[size][size], d[size], s[size][size], t[size][size], x1[size], er;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (i == j) {
s[i][j] = 1 / A[i][j];
t[i][j] = 0;
} else {
s[i][j] = 0;
t[i][j] = A[i][j];
}
}
}
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
v = 0;
for (int m = 0; m < size; m++)
v += s[i][m] * t[m][j];
q[i][j] = -v;
}
}
for (int i = 0; i < size; i++) {
v = 0;
for (int m = 0; m < size; m++) {
v += s[i][m] * B[m];
}
d[i] = v;
}
for(int i=0;i< size;i++) {
x[i] = d[i];
do {
k1++;
for (i = 0; i < size; i++) {
x1[i] = x[i];
}
for (i = 0; i < size; i++) {
v = 0;
for (int m = 0; m < size; m++) {
v += x[m] * q[i][m];
}
x[i] = v + d[i];
}
er = fabs(x1[0] - x[0]);
for (int m = 1; m < size; m++) {
if (er < fabs(x1[m] - x[m]))
er = fabs(x1[m] - x[m]);
}
iter++;
}
while (er > 0.001);
}
cout << "\nGAUSS-SEIDEL METHOD with error 0.001:\n";
for (int i = 0; i < size; i++) {
printf("%7.3f ", x[i]);
}
cout << "\n It occured " << iter << " iterations to aproximate system solution to error 0.001";
printf("\n");
k1=0;
for (int i = 0; i < size; i++) {
x[i] = d[i];
do {
k1++;
for (i = 0; i < size; i++)
x1[i] = x[i];
for (i = 0; i < size; i++) {
v = 0;
for (int m = 0; m < size; m++)
v += x[m] * q[i][m];
x[i] = v + d[i];
}
er = fabs(x1[0] - x[0]);
for (int m = 1; m < size; m++)
if (er < fabs(x1[m] - x[m]))er = fabs(x1[m] - x[m]);
iter++;
}
while (er > 0.00001);
}
cout << "\nGAUSS-SEIDEL METHOD with error 0.00001:\n";
for (int i = 0; i < size; i++) {
printf("%7.5f ", x[i]);
}
cout << "\n It occured " << iter << " iterations to aproximate system solution to error 0.00001";
}
//---------------------------------------------------------------------------
void reverse(double**& A, double*& B,int size) {
double a[size][2 * size], a1[size][2 * size], I[size][size], v;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++)
a1[i][j] = a[i][j] = A[i][j];
}
for (int i = 0; i < size; i++) {
for (int j = size; j < 2 * size; j++)
if (j - size == i) a1[i][j] = a[i][j] = 1;
else a1[i][j] = a[i][j] = 0;
}
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
a1[i][j] = a[i][j] / a[i][i];
a1[i][j + size] = a[i][j + size] / a[i][i];
}
for (int j = 0; j < size; j++)
for (int m = 0; m < size; m++)
if (j != i) {
a1[j][m] = a[j][m] - a[j][i] * a[i][m] / a[i][i];
a1[j][m + size] = a[j][m + size] - a[j][i] * a[i][m + size] / a[i][i];
}
for (int k = 0; k < size; k++) {
for (int j = 0; j < 2 * size; j++)
a[k][j] = a1[k][j];
}
}
cout << "\nInitial Matrix:\n";
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++)
printf("%4.1f ", A[i][j]);
cout << endl;
}
cout << "\nReverse Matrix:\n";
for (int i = 0; i < size; i++) {
for (int j = size; j < 2 * size; j++) {
printf("%5.2f ", a[i][j]);
}
cout << endl;
}
}
|
/*!
* \file commdialog.cpp
* \author Simon Coakley
* \date 2012
* \copyright Copyright (c) 2012 University of Sheffield
* \brief Implementation of message communication dialog
*/
#include "./commdialog.h"
#include "./messagemodel.h"
#include "./mpredelegate.h"
#include "./messagedelegate.h"
#include "./sortdelegate.h"
CommDialog::CommDialog(Machine * m, QWidget *parent)
: QDialog(parent) {
setupUi(this);
machine = m;
QHeaderView *headerView = tableView_messages->horizontalHeader();
headerView->setResizeMode(QHeaderView::Stretch);
headerView->setResizeMode(1, QHeaderView::Interactive);
tableView_messages->verticalHeader()->hide();
tableView_messages->setItemDelegateForColumn(0,
new MessageDelegate(m->getMessageNames()));
}
void CommDialog::setCommunication(Communication c) {
comm = c;
tableView_messages->setModel(comm.messageModel);
tableView_messages->setItemDelegateForColumn(1,
new MpreDelegate(machine, &comm));
tableView_messages->setItemDelegateForColumn(2,
new SortDelegate(machine, &comm));
}
Communication CommDialog::getCommunication() {
return comm;
}
void CommDialog::on_pushButton_plus_clicked() {
QStringList messages = machine->getMessageNames();
if (messages.count() > 0) {
comm.messageModel->addMessage(messages.first());
} else {
QMessageBox::warning(this, tr("FLAME Editor"),
tr("There are no message types associated with this model to add."));
}
}
void CommDialog::on_pushButton_minus_clicked() {
QModelIndexList indexList =
tableView_messages->selectionModel()->selectedRows();
while (indexList.count() > 0) {
comm.messageModel->removeRow(indexList.at(0).row());
indexList = tableView_messages->selectionModel()->selectedRows();
}
}
|
const int OUT_PIN = 9;
void setup()
{
pinMode(OUT_PIN, OUTPUT);
Serial.begin(9600);
}
float g_x = 0;
void loop()
{
g_x += 0.01f;
double y = cos( g_x );
int vol = y*128 + 128;
Serial.println( vol );
analogWrite(OUT_PIN, vol);
//digitalWrite(OUT_PIN, HIGH);
}
|
#include "UdataUtils.h"
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QProcess>
using udata::UdataUtils;
QString udata::UdataUtils::userFilePath = "";
/**
* @brief UdataUtils::UdataUtils
*/
UdataUtils::UdataUtils() {
}
/**
* @brief UdataUtils::saveUserData
*
* @param newUser
*/
void UdataUtils::saveUserData(User &newUser) {
QFile file(userFilePath);
if (!file.open(QIODevice::WriteOnly)) {
qDebug() << "Could not open " << userFilePath;
return;
}
QDataStream out(&file);
out.setVersion(QDataStream::Qt_5_1);
out << newUser;
file.flush();
file.close();
}
/**
* @brief UdataUtils::loadUserData
*
* @param newUser
*/
void UdataUtils::loadUserData(User &newUser) {
QFile file(UdataUtils::userFilePath);
if (!file.open(QIODevice::ReadOnly)) {
qDebug() << "Could not open " << userFilePath;
return;
}
QDataStream in(&file);
in.setVersion(QDataStream::Qt_5_1);
qDebug() << "loading data";
in >> newUser;
file.close();
}
/**
* @brief UdataUtils::getUsername
*
* @return
*/
QString UdataUtils::getUsername() {
QString name = "";
if (!userFilePath.isEmpty()) {
name = userFilePath;
} else {
qDebug() << "#2";
#ifdef Q_OS_UNIX
qDebug() << "#3";
QProcess getUsername;
qDebug() << "#4";
QString output = "";
qDebug() << "#5";
getUsername.start("whoami");
qDebug() << "#6";
getUsername.waitForFinished();
qDebug() << "#7";
output = QString(getUsername.readAllStandardOutput());
qDebug() << "#8";
name = output.remove(output.length() - 1, 2);
qDebug() << "#9";
if (name == "root") {
qDebug() << "#10";
output = QString(getUsername.readAllStandardOutput());
name = getNotRootUser();
}
#else
// no implementation yet
name = "";
#endif
}
qDebug() << "#11";
return name;
}
/**
* @brief UdataUtils::prepFiles prepares files and directories necessary to
* store commitment data on disk the very first time the user opens tasker
*
* @return 0 on Success. Otherwise -1. Will start defining error codes ASAP.
*/
int UdataUtils::prepFiles() {
int status = 0;
qDebug() << "#1";
QString userName = getUsername();
qDebug() << "#3";
#if defined(Q_OS_LINUX)
const QString newDir{ QString(HOME_FOLDER_NAME) + QDir::separator() +
userName + QDir::separator() + USER_FOLDER_NAME };
#elif defined(Q_OS_OSX)
const QString newDir(QDir::separator() + QString("Users") + QDir::separator() +
userName + QDir::separator() + USER_FOLDER_NAME);
#endif
qDebug() << newDir;
if (userName == ROOT_USER) {
QDir newTaskerFolder{ newDir };
if (newTaskerFolder.exists()) {
userFilePath = newTaskerFolder.absoluteFilePath(userName + TASKER_FILE_EXTENSION);
loadUserData(*User::getInstance());
status = 0;
} else {
QProcess mkdirProcess{};
mkdirProcess.start(QString(MKDIR_COMMAND) + newDir);
mkdirProcess.waitForFinished();
QFile newFile{ newTaskerFolder.absoluteFilePath(userName + TASKER_FILE_EXTENSION) };
if (!newFile.open(QIODevice::WriteOnly)) {
status = -1;
} else {
newFile.close();
newFile.flush();
User::getInstance()->setUsername(userName);
userFilePath = newTaskerFolder.absoluteFilePath(userName + TASKER_FILE_EXTENSION);
saveUserData(*User::getInstance());
qDebug() << "prepared files at:" << userFilePath;
}
}
} else {
QDir temp = QDir::current();
QDir newTaskerFolder{ newDir };
if (newTaskerFolder.exists()) {
userFilePath = newTaskerFolder.absoluteFilePath(userName + TASKER_FILE_EXTENSION);
loadUserData(*User::getInstance());
status = 0;
} else {
if (newTaskerFolder.mkdir(newDir)) {
QFile newFile{ newTaskerFolder.absoluteFilePath(userName + TASKER_FILE_EXTENSION) };
if (!newFile.open(QIODevice::WriteOnly)) {
status = -1;
} else {
newFile.close();
newFile.flush();
User::getInstance()->setUsername(userName);
userFilePath = newTaskerFolder.absoluteFilePath(userName + TASKER_FILE_EXTENSION);
saveUserData(*User::getInstance());
qDebug() << "prepared files at:" << userFilePath;
status = 0;
}
} else {
qDebug() << "mkdir failed:" << newDir;
status = -1;
}
}
}
return status;
}
QString UdataUtils::getNotRootUser() {
QDir homeDir{ HOME_FOLDER_NAME };
QString user = homeDir.entryList().at(2);
return user;
}
|
#include "ErrorMessage.h"
const char* g_errorMsg =
"[Error]\n"
"2=您已离开房间\n"
"1=长时间未操作退出房间\n"
"-1=找不到用户\n"
"-2=找不到房间\n"
"-3=进入房间的等级和服务器等级不同\n"
"-4=您的金币不足以进入房间\n"
"-5=密码错误\n"
"-6=您还没有登陆,请登陆\n"
"-7=匹配失败\n"
"-8=您已经准备不要重复点击准备\n"
"-9=您已经准备不要重复点击准备\n"
"-11=房间不处于玩牌状态\n"
"-12=当前不是轮到您下注\n"
"-13=没有足够的金币下注\n"
"-14=您下注数量有误\n"
"-15=查找的房间不存在\n"
"-16=已经超过您下注上限\n"
"-17=获取房间信息失败\n"
"-18=换房间失败\n"
"-19=进入游戏房间失败\n"
"-20=房间名不能为空\n";
|
#include <assert.h>
#include <jni.h>
#include <android/log.h>
#include "FLACStreamEncoder.h"
#include "VADWebRTC.h"
extern "C" {
static char const * const FLACStreamEncoder_classname = "com/evature/evasdk/evaapis/FLACStreamEncoder";
static char const * const FLACStreamEncoder_mObject = "mObject";
static char const * const FLACStreamEncoder_writeCallback = "writeCallback";
static char const * const VADWebRTC_classname = "com/evature/evasdk/evaapis/VADWebRTC";
static char const * const VADWebRTC_mObject = "mObject";
static char const * const LTAG = "jni_onload/native";
static JavaVM *java_vm;
static jfieldID streamer_mObj;
static jmethodID streamer_writeMethod;
static jfieldID vad_mObj;
JavaVM * get_java_vm() {
return java_vm;
}
jmethodID get_streamer_writeMethod() {
return streamer_writeMethod;
}
/*****************************************************************************
* Helper functions
**/
/**
* Retrieve FLACStreamEncoder instance from the passed jobject.
**/
FLACStreamEncoder * get_encoder(JNIEnv * env, jobject obj) {
jlong encoder_value = env->GetLongField(obj, streamer_mObj);
return reinterpret_cast<FLACStreamEncoder *>(encoder_value);
}
/**
* Store FLACStreamEncoder instance in the passed jobject.
**/
void set_encoder(JNIEnv * env, jobject obj, FLACStreamEncoder * encoder) {
jlong encoder_value = reinterpret_cast<jlong>(encoder);
env->SetLongField(obj, streamer_mObj, encoder_value);
}
/**
* Retrieve VADWebRTC instance from the passed jobject.
**/
VADWebRTC * get_vad(JNIEnv * env, jobject obj) {
jlong vad_value = env->GetLongField(obj, vad_mObj);
return reinterpret_cast<VADWebRTC *>(vad_value);
}
/**
* Store VADWebRTC instance in the passed jobject.
**/
void set_vad(JNIEnv * env, jobject obj, VADWebRTC * vad) {
jlong vad_value = reinterpret_cast<jlong>(vad);
env->SetLongField(obj, vad_mObj, vad_value);
}
jint JNI_OnLoad(JavaVM *vm, void *reserved)
{
// __android_log_print(ANDROID_LOG_INFO, LTAG, ">>> JNI_OnLoad");
java_vm = vm;
// Do the JNI dance for getting the mObject field, and write callback method
JNIEnv* env;
if (java_vm->GetEnv( (void **) &env, JNI_VERSION_1_6) != JNI_OK) {
__android_log_print(ANDROID_LOG_ERROR, LTAG, ">>> GetEnv failed.");
return JNI_ERR;
}
jclass streamer_jcls = env->FindClass(FLACStreamEncoder_classname);
if (env->ExceptionCheck()) {
__android_log_print(ANDROID_LOG_ERROR, LTAG, ">>> failed to get %s class", FLACStreamEncoder_classname);
env->ExceptionDescribe();
return JNI_ERR;
}
static_assert(sizeof(jlong) >= sizeof(FLACStreamEncoder *), "jlong smaller than pointer");
jfieldID object_field = env->GetFieldID(streamer_jcls, FLACStreamEncoder_mObject, "J");
streamer_mObj = object_field;
jmethodID mid = env->GetMethodID(streamer_jcls, FLACStreamEncoder_writeCallback, "([BIII)V"); // buffer, length, samples, frame
if (env->ExceptionCheck()) {
__android_log_print(ANDROID_LOG_ERROR, LTAG, ">>>> Write Callback: failed to get %s method", FLACStreamEncoder_writeCallback);
env->ExceptionDescribe();
return JNI_ERR;
}
assert(mid != 0);
streamer_writeMethod = mid;
jclass vad_jcls = env->FindClass(VADWebRTC_classname);
if (env->ExceptionCheck()) {
__android_log_print(ANDROID_LOG_ERROR, LTAG, ">>> failed to get %s class", VADWebRTC_classname);
env->ExceptionDescribe();
return JNI_ERR;
}
static_assert(sizeof(jlong) >= sizeof(VADWebRTC *), "jlong smaller than pointer");
object_field = env->GetFieldID(vad_jcls, VADWebRTC_mObject, "J");
vad_mObj = object_field;
return JNI_VERSION_1_6;
}
} // extern "C"
|
#include "TakeSeatProc.h"
#include "Logger.h"
#include "HallManager.h"
#include "Room.h"
#include "ErrorMsg.h"
#include "IProcess.h"
#include "ProcessManager.h"
#include "GameCmd.h"
REGISTER_PROCESS(CLIENT_MSG_TAKESEAT, TakeSeatProc)
TakeSeatProc::TakeSeatProc()
{
this->name = "TakeSeatProc";
}
TakeSeatProc::~TakeSeatProc()
{
}
int TakeSeatProc::doRequest(CDLSocketHandler* clientHandler, InputPacket* pPacket, Context* pt )
{
//_NOTUSED(pt);
int cmd = pPacket->GetCmdType();
short seq = pPacket->GetSeqNum();
//short source = pPacket->GetSource();
int uid = pPacket->ReadInt();
int tid = pPacket->ReadInt();
//0表示离座,1表示就座,2表示换座,3庄家申请离庄
int action = pPacket->ReadByte();
int seatid = pPacket->ReadByte();
short svid = tid >> 16;
short realTid = tid & 0x0000FFFF;
_LOG_DEBUG_("==>[TakeSeatProc] cmd[0x%04x] uid[%d]\n", cmd, uid);
_LOG_DEBUG_("[DATA Parse] tid=[%d] svid=[%d] reallTid[%d] action[%d] seatid[%d]\n", tid, svid, realTid, action, seatid);
Room* room = Room::getInstance();
Table* table = room->getTable(realTid);
if(table == NULL)
{
_LOG_ERROR_("[TakeSeatProc] uid=[%d] tid=[%d] realTid=[%d] Table is NULL\n",uid, tid, realTid);
return sendErrorMsg(clientHandler, cmd, uid, -2,ErrorMsg::getInstance()->getErrMsg(-2),seq);
}
Player* player = table->getPlayer(uid);
if(player == NULL)
{
_LOG_ERROR_("[TakeSeatProc] uid=[%d] tid=[%d] realTid=[%d] Your not in This Table\n",uid, tid, realTid);
return sendErrorMsg(clientHandler, cmd, uid, -1,ErrorMsg::getInstance()->getErrMsg(-1),seq);
}
if(player->isActive())
{
_LOG_ERROR_("[TakeSeatProc] uid=[%d] ustatus=[%d] tid=[%d] realTid=[%d] Table status[%d] in active\n",uid, player->m_nStatus, tid, realTid, table->m_nStatus);
return sendErrorMsg(clientHandler, cmd, uid, -41,ErrorMsg::getInstance()->getErrMsg(-41),seq);
}
_LOG_INFO_("[TakeSeatProc] UID=[%d] GameID=[%s] tid=[%d] realTid=[%d] TakeSeatProc OK\n", uid, table->getGameID(), tid, realTid);
int ret = 0;
if (action == 0)
ret = table->playerStandUp(player);
if (action == 1)
ret = table->playerSeatDown(player, seatid);
if (action == 2)
ret = table->playerChangeSeat(player, seatid);
if (ret)
return sendErrorMsg(clientHandler, cmd, uid, ret,ErrorMsg::getInstance()->getErrMsg(ret), seq);
IProcess::sendTakeSeatInfo(table, player, action, seatid, seq);
player->setActiveTime(time(NULL));
return 0;
}
int TakeSeatProc::doResponse(CDLSocketHandler* clientHandler, InputPacket* inputPacket,Context* pt)
{
_NOTUSED(clientHandler);
_NOTUSED(inputPacket);
_NOTUSED(pt);
return 0;
}
|
/***************************************************************************
* Copyright (C) 2009 by Dario Freddi *
* drf54321@gmail.com *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
#ifndef GROUP_H
#define GROUP_H
#include <QtCore/QString>
#include <QtCore/QMetaType>
#include "Visibility.h"
typedef struct __pmgrp_t pmgrp_t;
namespace Aqpm
{
class Package;
class AQPM_EXPORT Group
{
public:
typedef QList<Group*> List;
virtual ~Group();
QString name() const;
QList<Package*> packages();
pmgrp_t *alpmGroup() const;
bool isValid() const;
private:
explicit Group(pmgrp_t *grp);
class Private;
Private *d;
friend class BackendThread;
};
}
Q_DECLARE_METATYPE(Aqpm::Group*)
Q_DECLARE_METATYPE(Aqpm::Group::List)
#endif // GROUP_H
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.