text
stringlengths 8
6.88M
|
|---|
#pragma once
#include <iostream>
#include <string>
#include <fstream>
#include <windows.h>
#define M_PI 3.14159265358979323846
using namespace std;
class Area {
public:
Area() {};
virtual ~Area() {};
virtual double Calc() = 0;
bool FileCheck(ifstream& pFile);
};
|
#include <TransferFunction.h>
bool TransferFunction::comparePoints(ControlPoint a, ControlPoint b){
return a.getPosition().x < b.getPosition().x;
}
void TransferFunction::orderPoints(){
//-- Bubble Sort Ordering
unsigned int n = control_points.size();
for (unsigned int i = 0; i < n -1 ; i++)
for (unsigned int j = 0; j < n - i - 1; j++)
if (control_points[j]->getPosition().x > control_points[j + 1]->getPosition().x)
swap(&control_points[j], &control_points[j+1]);
}
void TransferFunction::swap(ControlPoint** a, ControlPoint** b){
ControlPoint* aux = new ControlPoint(*(*a));
*(a) = *(b);
*(b) = aux;
}
float TransferFunction::divideDifference(int x0, int x1, int fx0, int fx1){
x0++; x1++; fx0++; fx1++;
return float(fx1-fx0)/float(x1-x0);
}
void TransferFunction::linearInterpolation(){
//-- reset values
for (unsigned int i = 0; i < length; i++) {
texture_dataLinearSpline[i * 4 + 0] = 0;
texture_dataLinearSpline[i * 4 + 1] = 0;
texture_dataLinearSpline[i * 4 + 2] = 0;
texture_dataLinearSpline[i * 4 + 3] = 0;
}
double partial_length;
double alpha_factor, r_factor, g_factor, b_factor;
double displacement = double(1) / double(this->length);
unsigned int step, step_acum = 0, index = 0;
unsigned int x, x0, x1;
unsigned int B0;
float r_B0, g_B0, b_B0, a_B0;
float r_B1, g_B1, b_B1, a_B1;
unsigned int steps2interpolate;
for (unsigned int i = 0; i < control_points.size()-1; i++){
partial_length = control_points[i + 1]->getPosition().x - control_points[i]->getPosition().x;
step = unsigned int(this->length * partial_length);
step_acum += step;
if (i == control_points.size() - 2) step += (this->length - step_acum);
//-- Getting X's
x0 = control_points[i]->getPosition().x;
x1 = control_points[i+1]->getPosition().x;
//-- Getting B0's
r_B0 = float(control_points[i]->getColor().r);
g_B0 = float(control_points[i]->getColor().g);
b_B0 = float(control_points[i]->getColor().b);
a_B0 = float(control_points[i]->getPosition().y);
//-- Getting B1's
r_B1 = divideDifference(x0, x1, control_points[i]->getColor().r, control_points[i + 1]->getColor().r);
g_B1 = divideDifference(x0, x1, control_points[i]->getColor().g, control_points[i + 1]->getColor().g);
b_B1 = divideDifference(x0, x1, control_points[i]->getColor().b, control_points[i + 1]->getColor().b);
a_B1 = divideDifference(x0, x1, control_points[i]->getPosition().y, control_points[i + 1]->getPosition().y);
//-- Push x0 value, and x1 value
//-- x0
texture_dataLinearSpline[x0 * 4 + 0] = float(control_points[i]->getColor().r) / float(length - 1);
texture_dataLinearSpline[x0 * 4 + 1] = float(control_points[i]->getColor().g) / float(length - 1);
texture_dataLinearSpline[x0 * 4 + 2] = float(control_points[i]->getColor().b) / float(length - 1);
texture_dataLinearSpline[x0 * 4 + 3] = float(control_points[i]->getPosition().y) / float(length - 1);
//-- x1
texture_dataLinearSpline[x1 * 4 + 0] = float(control_points[i+1]->getColor().r) / float(length - 1);
texture_dataLinearSpline[x1 * 4 + 1] = float(control_points[i+1]->getColor().g) / float(length - 1);
texture_dataLinearSpline[x1 * 4 + 2] = float(control_points[i+1]->getColor().b) / float(length - 1);
texture_dataLinearSpline[x1 * 4 + 3] = float(control_points[i+1]->getPosition().y) / float(length - 1);
for (unsigned int j = x0 + 1; j < x1; j++){
//-- Steps to be interpolated (x0 && x1 are already known)
texture_dataLinearSpline[j * 4 + 0] = float(int(r_B0 + r_B1*(float(j - x0)))) / float(length - 1);
texture_dataLinearSpline[j * 4 + 1] = float(int(g_B0 + g_B1*(float(j - x0)))) / float(length - 1);
texture_dataLinearSpline[j * 4 + 2] = float(int(b_B0 + b_B1*(float(j - x0)))) / float(length - 1);
texture_dataLinearSpline[j * 4 + 3] = float(int(a_B0 + a_B1*(float(j - x0)))) / float(length - 1);
}
}
/*for (unsigned int i = 0; i < length; i++) {
cout << "R :: " << texture_dataLinearSpline[i * 4 + 0];
cout << " G :: " << texture_dataLinearSpline[i * 4 + 1];
cout << " B :: " << texture_dataLinearSpline[i * 4 + 2];
cout << " A :: " << texture_dataLinearSpline[i * 4 + 3] << endl;
}
system("pause");*/
}
void TransferFunction::cuadraticInterpolation(){
}
void TransferFunction::cubicInterpolations(){
}
TransferFunction::TransferFunction(unsigned int length):length(length){
//-- Init first 2 points on the array
//cout << "TransferFunction (Constructor)\n";
this->control_points.push_back(new ControlPoint(tvec2<int>(0, 0), tvec3<int>(0, 0, 0), length));
//this->control_points.push_back(new ControlPoint(tvec2<int>(225, 100), tvec3<int>(255, 255, 255), length));
this->control_points.push_back(new ControlPoint(tvec2<int>(255, 255), tvec3<int>(255, 255, 255), length));
//this->control_points.push_back(new ControlPoint(tvec2<int>(60, 25), tvec3<int>(0, 255, 255), length));
//this->control_points.push_back(new ControlPoint(tvec2<int>(22, 200), tvec3<int>(255, 0, 0), length));
this->controlPointSelected = NULL;
//-- Init texture unit
internalPixelFormat = GL_RGBA8;
if (length = 65536) internalPixelFormat = GL_RGBA16;
glGenTextures(1, &this->texture_unit);
glBindTexture(GL_TEXTURE_1D, this->texture_unit);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage1D(GL_TEXTURE_1D, 0, internalPixelFormat, length, 0, GL_RGBA, GL_FLOAT, NULL);
glBindTexture(GL_TEXTURE_1D, 0);
this->texture_dataLinearSpline = new GLfloat[length * 4];
this->texture_dataCuadraticSpline = new GLfloat[length * 4];
this->texture_dataCubicSpline = new GLfloat[length * 4];
this->orderPoints();
this->linearInterpolation();
//-- Initializing Drawing Structure
//-- Alpha selector structure
vec2 min = vec2(0.51383838f, 0.93939393f);
vec2 max = vec2(0.94444444f, 0.51515151f);
zeroZero = vec2(0.53999988f, 0.559596f);
oneOne = vec2(0.933333f, 0.91999999);
this->gl_quad = {
max.x, min.y, 0.0f, 1.0f, 0.0f,
min.x, max.y, 0.0f, 0.0f, 1.0f,
min.x, min.y, 0.0f, 0.0f, 0.0f,
max.x, min.y, 0.0f, 1.0f, 0.0f,
max.x, max.y, 0.0f, 1.0f, 1.0f,
min.x, max.y, 0.0f, 0.0f, 1.0f
};
glGenVertexArrays(1, &this->glVAO_quad_dir);
glGenBuffers(1, &(this->glVBO_quad_dir));
glBindVertexArray(this->glVAO_quad_dir);
glBindBuffer(GL_ARRAY_BUFFER, this->glVBO_quad_dir);
glBufferData(GL_ARRAY_BUFFER, (this->gl_quad.size()) * sizeof(GLfloat), &(this->gl_quad[0]), GL_STATIC_DRAW);
//-- Vertexes
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0);
//-- Texture Coords
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
glBindVertexArray(0);
alpha_selector_texture = new Texture("../textures/transfer_function/axis.jpg");
alpha_selector_shader = new CGLSLProgram();
alpha_selector_shader->loadShader("../src/shaders/alpha_selector.vert", CGLSLProgram::VERTEX);
alpha_selector_shader->loadShader("../src/shaders/alpha_selector.frag", CGLSLProgram::FRAGMENT);
alpha_selector_shader->create_link();
//-- init default color
color = new float[3];
color[0] = 1.0f;
color[1] = 1.0f;
color[2] = 1.0f;
}
TransferFunction::~TransferFunction() {
this->control_points.~vector();
}
void TransferFunction::pushControlPoint(ControlPoint* controlPoint){
this->control_points.push_back(new ControlPoint(*(controlPoint)));
this->orderPoints();
this->linearInterpolation();
delete controlPoint;
}
bool TransferFunction::popControlPoint(vec2 controlPointPosition){
vector<ControlPoint*>::iterator lower; /*= lower_bound(
control_points.begin(),
control_points.end(),
new ControlPoint(controlPointPosition), comparePoints);*/
unsigned int index = (lower - control_points.begin());
vector<ControlPoint*>::iterator it = control_points.erase(control_points.begin() + index);
return it._Ptr != NULL;
}
bool TransferFunction::popControlPoint(unsigned int index){
vector<ControlPoint*>::iterator it = this->control_points.erase(this->control_points.begin()+index);
return it._Ptr != NULL;
}
void TransferFunction::bindLinearInterpolationTexture(){
//-- Interpolate to generate data
glBindTexture(GL_TEXTURE_1D, this->texture_unit);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage1D(GL_TEXTURE_1D, 0, internalPixelFormat, length, 0, GL_RGBA, GL_FLOAT, texture_dataLinearSpline);
glBindTexture(GL_TEXTURE_1D, 0);
}
GLuint TransferFunction::getTextureUnit(){
return this->texture_unit;
}
float * TransferFunction::getColor(){
return color;
}
bool TransferFunction::isClicked(){
vec2 mousePos = getMousePosition();
int mouseLeftState = getMouseLeftState();
int mouseRightState = getMouseRightState();
if (
(mousePos.x >= zeroZero.x && mousePos.y <= oneOne.x &&
mousePos.y >= zeroZero.y && mousePos.y <= oneOne.y &&
(mouseLeftState == GLFW_PRESS || mouseRightState == GLFW_PRESS))
) return true;
return false;
}
void TransferFunction::reshape(){
projection = glm::perspective(45.0f, (float)getDisplaySize().x / (float)getDisplaySize().y, 0.1f, 1000.0f);
}
void TransferFunction::update(){
vec3 color_transformed = vec3(255 * color[0], 255 * color[1], 255 * color[2]);
if (!isClicked()) {
lastMouseLeftState = getMouseLeftState();
lastMouseRightState = getMouseRightState();
if (controlPointSelected != NULL) {
controlPointSelected->setColor(color_transformed);
this->linearInterpolation();
}
return;
}
//-- Conversion first
//-- Necesary Variables
int mouseLeftState = getMouseLeftState();
int mouseRightState = getMouseRightState();
vec2 point = getMousePosition();
int a = 0, b = 255;
vec2 factor = vec2(b - a, b - a);
vec2 scale_x = vec2(zeroZero.x, oneOne.x);
vec2 scale_y = vec2(zeroZero.y, oneOne.y);
//-- Calculating
point.x = (factor.x*(point.x - scale_x.x) / (scale_x.y - scale_x.x)) + a;
point.y = (factor.y*(point.y - scale_y.x) / (scale_y.y - scale_y.x)) + a;
if (controlPointSelected != NULL && mouseLeftState == GLFW_PRESS) {
controlPointSelected->setColor(color_transformed);
controlPointSelected->setX(int(point.x));
controlPointSelected->setY(int(point.y));
this->orderPoints();
this->linearInterpolation();
return;
}
//-- Checking if a point is clicked (move, select)
int index = 0;
for each (ControlPoint* controlPoint in control_points) {
if (controlPoint->clicked(tvec2<int>(int(point.x), int(point.y))) && mouseRightState == GLFW_PRESS) {
controlPointSelected = controlPoint;
for each (ControlPoint* thePoint in control_points) thePoint->setState(false);
controlPoint->setState(true);
return;
}
index++;
}
//-- If it is not clicked, add a new point
//-- Adding new point
if (mouseRightState == GLFW_PRESS) {
for each (ControlPoint* thePoint in control_points) thePoint->setState(false);
this->control_points.push_back(new ControlPoint(tvec2<int>(int(point.x), int(point.y)), tvec3<int>(int(color_transformed.r), int(color_transformed.g), int(color_transformed.b)), length));
this->orderPoints();
this->linearInterpolation();
}
}
void TransferFunction::draw() {
alpha_selector_shader->enable();
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, alpha_selector_texture->getID());
glUniform1i(alpha_selector_shader->getLocation("alpha_selector_texture"), 0);
glBindVertexArray(glVAO_quad_dir);
glDrawArrays(GL_TRIANGLES, 0, 6);
glBindVertexArray(0);
glBindTexture(GL_TEXTURE_2D, 0);
alpha_selector_shader->disable();
//-- Variables to draw
vec2 point;
vec2 factor = vec2(oneOne.x - zeroZero.x, oneOne.y - zeroZero.y);
vec2 scale = vec2(0, 1);
vector<vec2> points;
//-- Calculating
for each (ControlPoint* controlPoint in control_points){
point = controlPoint->getPositionConvertedZeroOne();
point.x = (factor.x*(point.x - scale.x) / (scale.y - scale.x)) + zeroZero.x;
point.y = (factor.y*(point.y - scale.x) / (scale.y - scale.x)) + zeroZero.y;
points.push_back(point);
}
//-- Draw Line Strip
glColor3f(1.0f, 1.0f, 1.0f);
glPointSize(2.0f);
glBegin(GL_LINE_STRIP);
for each (vec2 point in points)
glVertex2f(point.x, point.y);
glEnd();
//-- Draw Points
glColor3f(1.0f, 1.0f, 1.0f);
glPointSize(7.5f);
glBegin(GL_POINTS);
for (unsigned int i = 0; i < control_points.size(); i++) {
if (control_points[i]->isActive()) glColor3f(0.0f, 0.8f, 0.0f);
else glColor3f(0.6f, 0.6f, 0.6f);
glVertex2f(points[i].x, points[i].y);
}
glEnd();
}
|
#ifndef CIRCULAR_ARRAY_H_
#define CIRCULAR_ARRAY_H_
#include "CircularContainer.h"
template <typename T, int Capacity>
class CircularArray{
public:
CircularArray(){
_buffer.resize(Capacity);
}
size_t size() const{
return _buffer.size();
}
void fill(const T& val){
for(size_t i=0;i<Capacity;i++){
at(i) = val;
}
}
/*
make sure index 'i' is in range of [0,this->size()) .
*/
T& at(const size_t& i){
return _buffer.at(i);
}
/*
make sure index 'i' is in range of [0,this->size()) .
*/
const T& at(const size_t& i) const{
return _buffer.at(i);
}
/*
make sure index 'i' is in range of [0,this->size()) .
*/
T& operator[](const size_t& i){
return _buffer.at(i);
}
/*
make sure index 'i' is in range of [0,this->size()) .
*/
const T& operator[](const size_t& i) const{
return _buffer.at(i);
}
T& front(){
return _buffer.front();
}
const T& front() const{
return _buffer.front();
}
T& back() {
return _buffer.back();
}
const T& back() const{
return _buffer.back();
}
private:
CircularContainer<T, Capacity> _buffer;
};
#endif
|
// Created on: 1995-11-15
// Created by: Jean-Louis Frenkel <rmi@pernox>
// Copyright (c) 1995-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _UnitsAPI_SystemUnits_HeaderFile
#define _UnitsAPI_SystemUnits_HeaderFile
//! Identifies unit systems which may be defined as a
//! basis system in the user's session:
//! - UnitsAPI_DEFAULT : default system (this is the SI system)
//! - UnitsAPI_SI : the SI unit system
//! - UnitsAPI_MDTV : the MDTV unit system; it
//! is equivalent to the SI unit system but the
//! length unit and all its derivatives use
//! millimeters instead of meters.
//! Use the function SetLocalSystem to set up one
//! of these unit systems as working environment.
enum UnitsAPI_SystemUnits
{
UnitsAPI_DEFAULT,
UnitsAPI_SI,
UnitsAPI_MDTV
};
#endif // _UnitsAPI_SystemUnits_HeaderFile
|
#include <iostream>
#include<vector>
#include<conio.h>
#include<stdio.h>
using namespace std;
//Nhap xuat- vecto
void Nhap(vector<int>&arr)
{
cout<<"\n ---Menu----";
cout<<"\n Sau ok \n";
cout<<"\n An 1 de Dung\n";
cout<<"\n An Phim Khac Tiep\n";
cout<<"\n--------------------\n";
int i=0;
while(true)
{
char Luachon=getch();//Lay ki tu chu khong lay so nguyen!
if(Luachon=='1')
{
break;
}
else
{
int x=0;
cout<<" Nhap vao vi tri a["<<i<<"]:\t";
cin>>x;
cout<<" Ok!\n";
arr.push_back(x);
i++;
}
}
}
void Xuat(vector<int> arr)
{
int Size=arr.size();
for(int i=0; i<Size; i++)
{
cout<<arr.at(i)<<" ";
}
}
//Void xuat theo kieu Iterato
void out_Iter(vector<int> arr)
{
for(vector<int>::iterator it=arr.begin();it!=arr.end();it++)//o nho +1 kieu du lieu 4 byte!
{
cout<<*it<<" ";//Xuat ra gia tri trong o nho
}
}
int main()
{
vector<int> arr;
Nhap(arr);
Xuat(arr);
cout<<"\n ****Xuat Iterator (Theo tang o Nho)*****\n";
out_Iter(arr);
return 0;
}
|
#ifdef _WIN32
#pragma comment(lib, "glfw3.lib")
#endif
#include "sandbox.hpp"
void m() {
SandBox sb;
while (sb.open()) {
sb.on_update();
sb.on_gui_update();
}
return;
}
int main(){
m();
std::cout << "Exiting\n";
}
|
#define BOOST_TEST_MODULE dmtk_algo_clustering_hierarchical
#include <boost/test/unit_test.hpp>
#include <tuple>
#include "dmtk.hpp"
using namespace dmtk;
BOOST_AUTO_TEST_CASE( euclidean_min_distance_metric_3_ele) {
std::vector<std::tuple<int, int>> data{{1, 1},{2, 2},{10, 10}};
BOOST_REQUIRE_EQUAL(data.size(), 3);
auto res = hierarchical_clustering(data, euclidean_min_distance_metric{});
BOOST_REQUIRE_EQUAL(res->value.seq_id, 5);
// std::fstream fout("graphviz/hierarchical-data.dot", std::ios::out);
// graphviz_graph_dendrogram(fout, vec);
}
|
#pragma once
#include "orientation.h"
#include <boost/noncopyable.hpp>
#include <memory>
class Transform : boost::noncopyable
{
public:
static std::shared_ptr<Transform> make_transform();
static std::shared_ptr<Transform> make_transform(std::shared_ptr<Transform> rhs);
static std::shared_ptr<Transform> make_transform(const glm::vec3& position, const Orientation& orientation);
static std::shared_ptr<Transform> make_transform(const glm::vec3& position, const Orientation& orientation, std::shared_ptr<const Transform> parent);
glm::vec3& relative_position();
const glm::vec3& relative_position() const;
glm::vec3 position() const;
Orientation& relative_orientation();
const Orientation& relative_orientation() const;
Orientation orientation() const;
glm::mat4 get_model_matrix() const;
protected:
Transform();
Transform(const glm::vec3& position, const Orientation& orientation);
Transform(const glm::vec3& position, const Orientation& orientation, std::shared_ptr<const Transform> parent);
private:
glm::vec3 _position;
Orientation _orientation;
std::shared_ptr<const Transform> _parent;
};
class ITransformable
{
public:
ITransformable();
ITransformable(std::shared_ptr<Transform> transform);
void move_forward(float distance);
void move_right(float distance);
void move_up(float distance);
void rotate_right(float degrees);
void rotate_up(float degrees);
std::shared_ptr<Transform> get_transform();
const std::shared_ptr<const Transform> get_transform() const;
protected:
std::shared_ptr<Transform> _transform;
};
|
class CfgSounds {
sounds[] = {};
/*
class 'nomedoaudio' {
name = "nomedoaudio";
sound[] = {"\sounds\nomedoaudio.ogg",3.5, 1};
titles[] = {};
};
*/
// Efeitos sonoros bizarros
class aiaiiaiaia { // TAZER
name = "aiaiiaiaia";
sound[] = {"\sounds\aiaiiaiaia.ogg", 0.7, 1};
titles[] = {};
};
class paipara { // F2
name = "paipara";
sound[] = {"\sounds\paipara.ogg", 0.7, 1};
titles[] = {};
};
class errou { // F3
name = "errou";
sound[] = {"\sounds\errou.ogg", 0.7, 1};
titles[] = {};
};
// Aviso do TAB
class avisoUmSamu {
name = "avisoUmSamu";
sound[] = {"\sounds\avisoUmSamu.ogg",3.5, 1};
titles[] = {};
};
// Aviso do TAB
class mAssalto_1 {
name = "mAssalto_1";
sound[] = {"\sounds\mAssalto_1.ogg", 3.5, 1};
titles[] = {};
};
// Aviso do TAB
class mAssalto_2 {
name = "mAssalto_2";
sound[] = {"\sounds\mAssalto_2.ogg", 3.5, 1};
titles[] = {};
};
class flashbang {
name = "flashbang";
sound[] = {"\sounds\flashbang.ogg", 1.0, 1};
titles[] = {};
};
// Aviso do TAB
class saiadaarea {
name = "saiadaarea";
sound[] = {"\sounds\saiadaarea.ogg", 3.5, 1};
titles[] = {};
};
// Aviso do TAB
class MnCCop {
name = "MnCCop";
sound[] = {"\sounds\MnCCop.ogg", 3.5, 1};
titles[] = {};
};
// Aviso do TAB
class abordagemcop {
name = "abordagemcop";
sound[] = {"\sounds\abordagemcop.ogg", 3.5, 1};
titles[] = {};
};
class SirenLong {
name = "SirenLong";
sound[] = {"\sounds\Siren_Long.ogg", 4.0, 1};
titles[] = {};
};
class Yelp {
name = "yelp";
sound[] = {"\sounds\Yelp.ogg", 4.0, 1};
titles[] = {};
};
class sms
{
name = "sms";
sound[] = {"\sounds\sms.ogg", 1.0, 1};
titles[] = {};
};
class addicted {
name = "addicted";
sound[] = {"\sounds\addicted.ogg", 1, 1};
titles[] = {};
};
class turn {
name = "turn";
sound[] = {"\sounds\turn.ogg", 1, 1};
titles[] = {};
};
// MUSICA DE ENTRADA - CIV/MED
class introSong
{
name = "introSong";
sound[] = {"\sounds\introSong.ogg", 1.0, 1};
titles[] = {};
};
// MUSICA DE ENTRADA - COP
class copintrosong
{
name = "copintrosong";
sound[] = {"\sounds\copintrosong.ogg", 1.0, 1};
titles[] = {};
};
class Drink
{
name = "Drink";
sound[] = {"\sounds\drink.ogg", 1.0, 1};
titles[] = {};
};
class knockout
{
name = "knockout";
sound[] = {"\sounds\knockout.ogg", 1.0, 1};
titles[] = {};
};
class eat
{
name = "eat";
sound[] = {"\sounds\eat.ogg", 1.0, 1};
titles[] = {};
};
class handcuffs
{
name = "handcuffs";
sound[] = {"\sounds\algemas.ogg", 1.0, 1};
titles[] = {};
};
class medicSiren {
name = "medicSiren";
sound[] = {"\sounds\medic_siren.ogg", 5.5, 1};
titles[] = {};
};
class tazersound {
name = "tazersound";
sound[] = {"\sounds\tazer.ogg", 0.25, 1};
titles[] = {};
};
class mining {
name = "mining";
sound[] = {"\sounds\mining.ogg", 1.0, 1};
titles[] = {};
};
class harvest {
name = "harvest";
sound[] = {"\sounds\harvest.ogg", 1.0, 1};
titles[] = {};
};
class maconha
{
name = "maconha";
sound[] = {"\sounds\maconha.ogg", 1.0, 1};
titles[] = {};
};
class cocaina
{
name = "cocaina";
sound[] = {"\sounds\cocaina.ogg", 1.0, 1};
titles[] = {};
};
class heroina
{
name = "heroina";
sound[] = {"\sounds\heroina.ogg", 1.0, 1};
titles[] = {};
};
class lockCarSound {
name = "lockCarSound";
sound[] = {"\sounds\lockCarSound.ogg", 0.25, 1};
titles[] = {};
};
class UnlockCarSound {
name = "UnlockCarSound";
sound[] = {"\sounds\unlock.ogg", 0.25, 1};
titles[] = {};
};
class removeKebab {
name = "removeKebab";
sound[] = {"\sounds\kebabDeath.ogg", 1.0, 1};
titles[] = {};
};
class sintodeseg {
name = "sintodeseg";
sound[] = {"\sounds\sintoDC.ogg", 1, 1};
titles[] = {};
};
class alarm {
name = "alarm";
sound[] = {"\sounds\caralarm.ogg", 1.0, 1};
titles[] = {};
};
class purchaseS {
name = "purchaseS";
sound[] = {"\sounds\purchase.ogg", 1.0, 1};
titles[] = {};
};
class knockDoor {
name = "knockDoor";
sound[] = {"\sounds\knockDoor.ogg", 1.0, 1};
titles[] = {};
};
class camera {
name = "camera";
sound[] = {"\sounds\camera.ogg", 1.0, 1};
titles[] = {};
};
class wooding {
name = "wooding";
sound[] = {"\sounds\wooding.ogg", 1.0, 1};
titles[] = {};
};
class alarmePosto {
name = "alarmePosto";
sound[] = {"\sounds\alarmePosto.ogg", 1.2, 1};
titles[] = {};
};
class revivendo {
name = "revivendo";
sound[] = {"\sounds\revivendo.ogg", 2.0, 1};
titles[] = {};
};
class YelpMedic {
name = "YelpMedic";
sound[] = {"\sounds\YelpMedic.ogg", 4.5, 1};
titles[] = {};
};
class radiation {
name = "radiation";
sound[] = {"\sounds\rad.ogg", 0.25, 1};
titles[] = {};
};
class zomb1
{
name = "zomb1";
sound[] = {"\sounds\zomb1.ogg", 1, 1};
titles[] = {};
};
class zomb2
{
name = "zomb2";
sound[] = {"\sounds\zomb2.ogg", 1, 1};
titles[] = {};
};
class zomb3
{
name = "zomb3";
sound[] = {"\sounds\zomb3.ogg", 1, 1};
titles[] = {};
};
};
|
/* -*- Mode: c++; indent-tabs-mode: nil; c-file-style: "gnu" -*-
*
* Copyright (C) 1995-2005 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#include "core/pch.h"
#ifdef XPATH_SUPPORT
#include "modules/xpath/src/xpunionexpr.h"
#include "modules/xpath/src/xpvalue.h"
#include "modules/xpath/src/xpnodeset.h"
#include "modules/xpath/src/xpcontext.h"
#include "modules/xpath/src/xplocationpathexpr.h"
#include "modules/xpath/src/xpparser.h"
#include "modules/xpath/src/xpstep.h"
/* static */ XPath_Expression *
XPath_UnionExpression::MakeL (XPath_Parser *parser, XPath_Expression *lhs, XPath_Expression *rhs)
{
XPath_UnionExpression *expression = 0;
XPath_Producer *lhs_producer = 0, *rhs_producer = 0;
OP_STATUS error = OpStatus::OK;
if (lhs->HasFlag (FLAG_UNION))
{
expression = (XPath_UnionExpression *) lhs;
lhs = 0;
}
else if (rhs->HasFlag (FLAG_UNION))
{
expression = (XPath_UnionExpression *) rhs;
rhs = 0;
}
else
{
expression = OP_NEW (XPath_UnionExpression, (parser));
if (!expression || !(expression->producers = OP_NEW (OpVector<XPath_Producer>, ())))
goto exit_oom;
}
if (rhs && rhs->HasFlag (FLAG_UNION))
{
XPath_UnionExpression *rhs_union = (XPath_UnionExpression *) rhs;
for (unsigned index = 0, count = rhs_union->producers->GetCount (); index < count; ++index)
if (OpStatus::IsMemoryError (expression->producers->Add (rhs_union->producers->Get (index))))
goto exit_oom;
rhs_union->producers->Clear ();
OP_DELETE (rhs);
rhs = 0;
}
/* If 'lhs' or 'rhs' are non-NULL, they must be non-union expression that we
want to convert into producers and add to 'expression->producers'. */
if (lhs)
{
lhs_producer = XPath_Expression::GetProducerL (parser, lhs);
if (!lhs_producer)
{
/* FIXME: Error message. */
error = OpStatus::ERR;
goto exit_error;
}
lhs = 0;
if (OpStatus::IsMemoryError (expression->producers->Add (lhs_producer)))
goto exit_oom;
else
lhs_producer = 0;
}
if (rhs)
{
rhs_producer = XPath_Expression::GetProducerL (parser, rhs);
if (!rhs_producer)
{
/* FIXME: Error message. */
error = OpStatus::ERR;
goto exit_error;
}
rhs = 0;
if (OpStatus::IsMemoryError (expression->producers->Add (rhs_producer)))
goto exit_oom;
}
return expression;
exit_oom:
error = OpStatus::ERR_NO_MEMORY;
exit_error:
/* Anything we shouldn't delete will have been set to 0 already. */
OP_DELETE (expression);
OP_DELETE (lhs);
OP_DELETE (rhs);
OP_DELETE (lhs_producer);
OP_DELETE (rhs_producer);
LEAVE (error);
/* Keep compiler happy. Not reached, obviously. */
return 0;
}
/* virtual */
XPath_UnionExpression::~XPath_UnionExpression ()
{
if (producers)
{
producers->DeleteAll ();
OP_DELETE (producers);
}
}
/* virtual */ unsigned
XPath_UnionExpression::GetResultType ()
{
return XP_VALUE_NODESET;
}
/* virtual */ unsigned
XPath_UnionExpression::GetExpressionFlags ()
{
unsigned flags = FLAG_PRODUCER;
for (unsigned index = 0, count = producers->GetCount (); index < count; ++index)
flags |= (producers->Get (index)->GetExpressionFlags ()) & MASK_INHERITED;
return flags;
}
/* virtual */ XPath_Producer *
XPath_UnionExpression::GetProducerInternalL (XPath_Parser *parser)
{
XPath_UnionProducer *producer = OP_NEW_L (XPath_UnionProducer, (parser, producers));
/* Now owned by 'producer'. */
producers = 0;
return producer;
}
XPath_UnionProducer::XPath_UnionProducer (XPath_Parser *parser, OpVector<XPath_Producer> *producers)
: producers (producers),
producer_index_index (parser->GetStateIndex ()),
localci_index (parser->GetContextInformationIndex ())
{
ci_index = localci_index;
}
/* virtual */
XPath_UnionProducer::~XPath_UnionProducer ()
{
if (producers)
{
producers->DeleteAll ();
OP_DELETE (producers);
}
}
static BOOL
XPath_IsMutuallyExclusive (XPath_Producer *producer1, XPath_Producer *producer2)
{
if (XPath_Step::NodeTest::IsMutuallyExclusive (static_cast<XPath_Step::NodeTest *> (producer1->GetPrevious (XPath_Producer::PREVIOUS_NODETEST, TRUE)),
static_cast<XPath_Step::NodeTest *> (producer2->GetPrevious (XPath_Producer::PREVIOUS_NODETEST, TRUE))) ||
XPath_Step::Axis::IsMutuallyExclusive (static_cast<XPath_Step::Axis *> (producer1->GetPrevious (XPath_Producer::PREVIOUS_AXIS, TRUE)),
static_cast<XPath_Step::Axis *> (producer2->GetPrevious (XPath_Producer::PREVIOUS_AXIS, TRUE))))
return TRUE;
else
return FALSE;
}
/* virtual */ unsigned
XPath_UnionProducer::GetProducerFlags ()
{
unsigned flags = 0;
BOOL has_no_duplicates = TRUE;
for (unsigned outer = 0; outer < producers->GetCount (); ++outer)
{
XPath_Producer *producer = producers->Get (outer);
flags |= producer->GetProducerFlags () & (MASK_NEEDS | FLAG_BLOCKING);
for (unsigned inner = 0; inner < outer; ++inner)
if (!XPath_IsMutuallyExclusive (producers->Get (inner), producer))
{
has_no_duplicates = FALSE;
break;
}
}
if (has_no_duplicates)
flags |= FLAG_NO_DUPLICATES;
return flags;
}
/* virtual */ BOOL
XPath_UnionProducer::Reset (XPath_Context *context, BOOL local_context_only)
{
for (unsigned index = 0, count = producers->GetCount (); index < count; ++index)
producers->Get (index)->Reset (context);
context->states[producer_index_index] = 0;
return FALSE;
}
/* virtual */ XPath_Node *
XPath_UnionProducer::GetNextNodeL (XPath_Context *context)
{
unsigned &producer_index = context->states[producer_index_index];
while (producer_index < producers->GetCount ())
{
XPath_Producer *producer = producers->Get (producer_index);
if (XPath_Node *node = producer->GetNextNodeL (context))
return node;
else
++producer_index;
}
return 0;
}
#endif // XPATH_SUPPORT
|
#pragma once
#include "../controls/RollupCtrl.h"
#include "../DecalEntity.h"
enum E_TERRAIN_BRUSH_TYPE
{
E_TERRAIN_BRUSH_NULL_TYPE,
E_TERRAIN_RISE,
E_TERRAIN_LOWER,
E_TERRAIN_BRUSH_TYPE_COUNT
};
class CTerrainModifyTool : public CEditTool
{
public:
DECLARE_DYNCREATE(CTerrainModifyTool)
CTerrainModifyTool();
~CTerrainModifyTool();
void BeginTool();
void EndTool();
void Update();
void OnLButtonDown(UINT nFlags, CPoint point);
void OnLButtonUp(UINT nFlags, CPoint point);
void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
void OnMouseMove(UINT nFlags, CPoint point);
void SetBrushSize( Real brushSize );
void SetBrushHardness( Real hardness );
void SetBrushType( E_TERRAIN_BRUSH_TYPE type );
protected:
CRollupCtrl* m_pTerrainCtrl;
int m_iCurrentPageId;
E_TERRAIN_BRUSH_TYPE mBrushType;
CDecalEntity mEditDecal;
bool mbBeginEdit;
Real mBrushSize;
Real mBrushHardness;
int mHeightUpdateCountDown;
unsigned long mHeightUpdateRate;
unsigned long mTimeLastFrame;
};
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
// only gravity will pull me down
// Longest Common Prefix in an Array
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<string> vs(n);
string res;
cin >> res;
for(int i=1; i<n; i++) {
cin >> vs[i];
int idx = 0, n1 = vs[i].size(), n2 = res.size();
string tmp = "";
while(idx < n1 && idx < n2) {
if(vs[i][idx] == res[idx])
tmp += res[idx];
else
break;
idx++;
}
res = tmp;
}
if(res == "")
cout << -1 << endl;
else
cout << res << endl;
}
return 0;
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef CUEHTTP_DETAIL_SEND_HPP_
#define CUEHTTP_DETAIL_SEND_HPP_
#include <filesystem>
#include <fstream>
#include <sstream>
#include <vector>
#include "cuehttp/compress.hpp"
#include "cuehttp/context.hpp"
#include "cuehttp/detail/mime.hpp"
namespace cue {
namespace http {
namespace send {
struct options final {
std::string root;
bool hidden{false};
std::string index;
std::vector<std::string> extensions;
std::uint64_t chunked_threshold{5 * 1024 * 1024};
bool cross_domain{false};
std::map<std::string, std::string> mime_types;
#ifdef ENABLE_GZIP
bool gzip{true};
std::uint64_t gzip_threshold{2048};
#endif // ENABLE_GZIP
};
} // namespace send
namespace detail {
template <typename _Path, typename _Options>
inline void send_file(context& ctx, _Path&& path, _Options&& options) {
std::string temp_path = std::forward<_Path>(path);
assert(!temp_path.empty());
if (temp_path.back() == '/' && !options.index.empty()) {
temp_path += options.index;
}
try {
namespace fs = std::filesystem;
fs::path real_path{options.root};
real_path += temp_path;
if (!options.hidden && real_path.filename().string()[0] == '.') {
return;
}
if (!real_path.has_extension()) {
for (const auto& item : options.extensions) {
fs::path temp{real_path};
temp.replace_extension(item);
if (fs::exists(temp)) {
real_path = temp;
break;
}
}
}
if (!fs::exists(real_path) || !fs::is_regular_file(real_path)) {
return;
}
std::ifstream file{real_path.string(), std::ios_base::binary};
if (!file.is_open()) {
return;
}
file.seekg(0, std::ios_base::end);
auto file_size = file.tellg();
if (file_size == -1) {
return;
}
file.seekg(std::ios_base::beg);
#ifdef ENABLE_GZIP
std::string data;
if (static_cast<std::uint64_t>(file_size) >= options.gzip_threshold &&
options.gzip) {
std::ostringstream tmp;
tmp << file.rdbuf();
std::string dst;
if (compress::deflate(tmp.str(), dst)) {
data = std::move(dst);
ctx.set("Content-Encoding", "gzip");
}
file_size = data.size();
}
#endif // ENABLE_GZIP
if (options.cross_domain) {
ctx.set("Access-Control-Allow-Origin", "*");
ctx.set("Access-Control-Allow-Headers", "X-Requested-With");
ctx.set("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
}
if (!ctx.res().has("Content-Type")) {
const auto ext_str = real_path.extension().string();
const auto it = options.mime_types.find(utils::to_lower(ext_str));
if (it != options.mime_types.end()) {
ctx.type(it->second);
} else {
ctx.type(get_mime(ext_str));
}
}
ctx.status(200);
if (static_cast<std::uint64_t>(file_size) >= options.chunked_threshold) {
ctx.chunked();
} else {
ctx.length(file_size);
}
#ifdef ENABLE_GZIP
if (data.empty()) {
ctx.body() << file.rdbuf();
} else {
ctx.body() << data;
}
#else
ctx.body() << file.rdbuf();
#endif // ENABLE_GZIP
} catch (...) {
return;
}
}
template <typename _Path>
inline void send_file(context& ctx, _Path&& path) {
send_file(ctx, std::forward<_Path>(path), send::options{});
}
} // namespace detail
} // namespace http
} // namespace cue
#endif // CUEHTTP_DETAIL_SEND_HPP_
|
#include "str_functions.h"
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
// Parsing a protocol where each element consists of a starting and ending tag,
// and there are attributes associated with each tag. Only starting tags can
// have attributes. We can call an attribute by referencing the tag, followed by
// a tilde, '~' and the name of the attribute. The tags may also be nested.
// Parses a custom protocol. Sorry for the uber long function!
void atrbute_parser(){
int N, Q;
std::vector< int > tags_before; // the tag the index tag is contained in (0) if none
tags_before.resize(11); // the max size referenced in the problem
std::vector< std::vector< int > > tags_after; // the tag number that the index tags contains
std::vector< std::vector< std::string > > attribute_names;
std::vector< std::vector< std::string > > attribute_values;
attribute_names.resize(11);
attribute_values.resize(11);
std::vector< int > a (10, 0);
for (int i = 0; i < 11; i++) {
tags_after.push_back(a);
}
std::cin>>N>>Q;
std::string temp = "";
std::string token;
std::string value;
std::string string_tag;
int tag = 0;
int current_tag = 0;
for (int i = 0; i < N + 1; i++) {
// Get one of the lines containing tag definitions.
std::getline(std::cin, temp);
std::stringstream ss(temp);
// Processing each of the words.
while (getline(ss, token, ' ')) {
if (token.at(0) == '<') { // tag
if (token.at(1) == '/') { //closing tag
current_tag = tags_before[current_tag];
} else { // opening tag
string_tag = token.back();
std::stringstream s1(string_tag);
s1 >> tag;
tags_after[current_tag][tag] = tag;
tags_before[tag] = current_tag;
current_tag = tag;
}
} else if (token.at(0) == '"') { // the token is a value
value = token.substr (1,1000);
value.pop_back();
value.pop_back();
attribute_values[current_tag].push_back(value);
} else if (token.at(0) == '=') { // skip if it is an equals sign
} else { // the call name for the values
attribute_names[current_tag].push_back(token);
}
}
}
current_tag = 1;
for (int j = 0; j < Q; j++) {
// Get one of the lines containing tag definitions.
std::getline(std::cin, temp);
std::stringstream ss(temp);
// Processing each of the words.
while (getline(ss, token, '.')) {
size_t tilda = token.find("~");
if (tilda != std::string::npos) { // Requesting a value.
string_tag = token.substr(3, (tilda - 3));
std::stringstream s1(string_tag);
s1 >> tag;
current_tag = tag;
value = token.substr(tilda + 1, 1000);
ptrdiff_t pos = find(attribute_names[current_tag].begin(),
attribute_names[current_tag].end(), value) -
attribute_names[current_tag].begin();
if(pos >= attribute_names[current_tag].size()) {
std::cout << "Not Found!" << std::endl;
} else {
std::cout << attribute_values[current_tag][pos] << std::endl;
}
current_tag = 1;
} else if (token.find("tag") == std::string::npos) { // requesting a value
ptrdiff_t pos = find(attribute_names[current_tag].begin(),
attribute_names[current_tag].end(), token) -
attribute_names[current_tag].begin();
if(pos >= attribute_names[current_tag].size()) {
std::cout << attribute_values[current_tag][pos] << std::endl;
} else {
std::cout << "Not Found!" << std::endl;
}
current_tag = 1;
} else { // specifying a tag
string_tag = token.substr(3, 1000);
std::stringstream s1(string_tag);
s1 >> tag;
current_tag = tag;
}
}
}
}
/*
Custom Input:
12 8
<tag1 value = "HelloWorld">
<tag2 name = "Name1">
<tag3 name = "Name3">
</tag3>
<tag4 name = "Name4" text = "Super">
<tag6 buzz = "Buzz6">
</tag6>
</tag4>
<tag5>
</tag5>
</tag2>
</tag1>
tag1.tag2~name
tag1~name
tag1~value
tag1.tag2.tag3~name
tag1.tag2.tag3~value
tag1.tag2.tag4~text
tag1.tag2.tag4.tag6~text
tag1.tag2.tag4.tag6~buzz
*/
int main() {
atrbute_parser();
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright 2006-2012 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Peter Krefting
*/
#include "core/pch.h"
#ifdef GEOLOCATION_SUPPORT
#include "modules/prefs/prefsmanager/collections/pc_geoloc.h"
#include "modules/prefs/prefsmanager/collections/prefs_macros.h"
#include "modules/prefs/prefsmanager/collections/pc_geoloc_c.inl"
PrefsCollectionGeolocation *PrefsCollectionGeolocation::CreateL(PrefsFile *reader)
{
if (g_opera->prefs_module.m_pcgeolocation)
LEAVE(OpStatus::ERR);
g_opera->prefs_module.m_pcgeolocation = OP_NEW_L(PrefsCollectionGeolocation, (reader));
return g_opera->prefs_module.m_pcgeolocation;
}
PrefsCollectionGeolocation::~PrefsCollectionGeolocation()
{
#ifdef PREFS_COVERAGE
CoverageReport(
m_stringprefdefault, PCGEOLOCATION_NUMBEROFSTRINGPREFS,
m_integerprefdefault, PCGEOLOCATION_NUMBEROFINTEGERPREFS);
#endif
g_opera->prefs_module.m_pcgeolocation = NULL;
}
void PrefsCollectionGeolocation::ReadAllPrefsL(PrefsModule::PrefsInitInfo *)
{
// Read everything
OpPrefsCollection::ReadAllPrefsL(
m_stringprefdefault, PCGEOLOCATION_NUMBEROFSTRINGPREFS,
m_integerprefdefault, PCGEOLOCATION_NUMBEROFINTEGERPREFS);
}
#ifdef PREFS_VALIDATE
void PrefsCollectionGeolocation::CheckConditionsL(int which, int *value, const uni_char *)
{
// Check any post-read/pre-write conditions and adjust value accordingly
switch (static_cast<integerpref>(which))
{
case EnableGeolocation:
case SendLocationRequestOnlyOnChange:
break; // Nothing to do
default:
// Unhandled preference! For clarity, all preferenes not needing to
// be checked should be put in an empty case something: break; clause
// above.
OP_ASSERT(!"Unhandled preference");
}
}
BOOL PrefsCollectionGeolocation::CheckConditionsL(int which, const OpStringC &invalue,
OpString **outvalue, const uni_char *)
{
// Check any post-read/pre-write conditions and adjust value accordingly
switch (static_cast<stringpref>(which))
{
case LocationProviderUrl:
case Google2011LocationProviderAccessToken:
break; // Nothing to do
default:
// Unhandled preference! For clarity, all preferenes not needing to
// be checked should be put in an empty case something: break; clause
// above.
OP_ASSERT(!"Unhandled preference");
}
// When FALSE is returned, no OpString is created for outvalue
return FALSE;
}
#endif // PREFS_VALIDATE
#endif // GEOLOCATION_SUPPORT
|
/*
* day10.cpp
*
* Created on: Dec 10, 2019
* Author: sanja
*/
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <map>
#include <unordered_set>
#include <cmath>
#include <algorithm>
const int noOfVaporized = 200;
std::pair<int, int> laser;
//for putting angle in range (0, 360)
double calculate_angle(std::pair<int, int> laser, std::pair<int, int> asteroid)
{
int delta_x = abs(asteroid.first - laser.first);
int delta_y = abs(asteroid.second - laser.second);
double angle = atan((double) delta_y / (double) delta_x) * 180.0 / (atan(1) * 4);
if (delta_y == 0)
{
if (asteroid.first < laser.first) angle = 0.0;
else angle = 180.0;
}
else if (delta_x == 0)
{
if (asteroid.second > laser.second) angle = 90.0;
else angle = 270.0;
}
else
{
if (asteroid.first < laser.first)
{
if (asteroid.second < laser.second) angle += 270.0;
else angle = 90.0 - angle;
}
else
{
if (asteroid.second < laser.second) angle = 270.0 - angle;
else angle += 90.0;
}
}
return angle;
}
int main() {
std::vector<std::pair<int, int>> asteroids;
std::string line;
int length;
std::ifstream input;
input.open("input.txt");
int row = 0;
while (std::getline(input,line))
{
for(int j = 0; j < line.length(); j++) {
if(line[j] == '#') asteroids.push_back(std::make_pair(j, row));
}
++row;
}
int max = -1, index;
for (int i = 0; i < asteroids.size(); i++)
{
std::vector<double> lines;
for (int j = 0; j < asteroids.size(); j++)
{
if (i == j)
{
continue;
}
lines.push_back(
std::atan2(
(double) asteroids[j].second - asteroids[i].second,
(double) asteroids[j].first - asteroids[i].first));
}
std::sort(lines.begin(), lines.end());
auto it = std::unique(lines.begin(), lines.end());
int num = std::distance(lines.begin(), it);
if (num > max)
{
max = num;
index = i;
}
}
std::cout << max << std::endl;
laser = asteroids[index];
std::map<double, std::vector<std::pair<int, int>>> map;
for (std::pair<int, int> p : asteroids) {
if (p == asteroids[index])
{
continue;
}
double angle = calculate_angle(laser, p);
std::map<double, std::vector<std::pair<int, int>>>::iterator it = map.find(angle);
if (it != map.end())
{
map[angle].push_back(p);
}
else
{
std::vector<std::pair<int, int>> vec;
vec.push_back(p);
map[angle] = vec;
}
}
for (std::map<double, std::vector<std::pair<int, int>>>::iterator it = map.begin(); it != map.end(); ++it)
{
std::sort(it->second.begin(), it->second.end(),
[](const std::pair<int, int> &p1, const std::pair<int, int> &p2)
{
return std::hypot(p1.first - laser.first, p1.second - laser.second)
< std::hypot(p2.first - laser.first, p2.second - laser.second);
});
}
int removed = 1;
while (true)
{
for (std::map<double, std::vector<std::pair<int, int>>>::iterator it = map.begin(); it != map.end(); ++it)
{
std::vector<std::pair<int, int>> vec = it->second;
if (vec.size() == 0)
continue;
if (removed == noOfVaporized)
{
std::cout << 100 * vec[0].first + vec[0].second << std::endl;
return 1;
}
++removed;
it->second.erase(it->second.begin());
}
}
}
|
#include "gtest/gtest.h"
float commission(int locks, int stocks, int barrels)
{
int lockprice = 45;
int stockprice = 30;
int barrelprice = 25;
int total = 0;
float com = 0.0;
if ( locks<1 || locks>70 || stocks<1 || stocks>80 || barrels<1 || barrels>90)
return -1;
total = locks*lockprice + stocks*stockprice + barrels*barrelprice ;
if ( total <= 1000 )
com = total * 0.1 ;
else if( (total > 1000) && (total <= 1800) )
com = 1000 * 0.1 + (total - 1000 ) * 0.15 ;
else if(total > 1800 )
com = 1000 * 0.1 + 800 * 0.15 + (total - 1800) * 0.2 ;
return com;
}
TEST(BoundaryValue, commission)
{
EXPECT_EQ(commission(1,40,40),309);
EXPECT_EQ(commission(2,40,40),318);
EXPECT_EQ(commission(69,40,40),921);
EXPECT_EQ(commission(70,40,40),930);
EXPECT_EQ(commission(71,40,40),-1);
EXPECT_EQ(commission(35,1,40),381);
EXPECT_EQ(commission(35,2,40),387);
EXPECT_EQ(commission(35,80,40),855);
EXPECT_EQ(commission(35,81,40),-1);
EXPECT_EQ(commission(35,40,1),420);
EXPECT_EQ(commission(35,40,2),425);
EXPECT_EQ(commission(35,40,90),865);
EXPECT_EQ(commission(35,40,91),-1);
EXPECT_EQ(commission(35,40,40),615);
}
TEST(Equivalence, commission)
{
//weak robust
EXPECT_EQ(commission(10,10,10), 100);
EXPECT_EQ(commission(-1,40,45), -1);
EXPECT_EQ(commission(-2,40,45), -1);
EXPECT_EQ(commission(71,40,45), -1);
EXPECT_EQ(commission(35,-1,45), -1);
EXPECT_EQ(commission(35,81,45), -1);
EXPECT_EQ(commission(35,40,-1), -1);
EXPECT_EQ(commission(35,40,91), -1);
//strong robust
EXPECT_EQ(commission(-2,40,45), -1);
EXPECT_EQ(commission(35,-1,45), -1);
EXPECT_EQ(commission(35,40,-2), -1);
EXPECT_EQ(commission(-2,-1,45), -1);
EXPECT_EQ(commission(-2,40,-1), -1);
EXPECT_EQ(commission(35,-1,-1), -1);
EXPECT_EQ(commission(-2,-1,-1), -1);
}
TEST(CommissionPath, C0)
{
EXPECT_EQ(commission(0, 10, 4), -1);
EXPECT_EQ(commission(35,1,40),381);
EXPECT_EQ(commission(35,2,40),387);
EXPECT_EQ(commission(35,80,40),855);
}
TEST(CommissionPath, C1)
{
EXPECT_EQ(commission(0, 10, 4), -1);
EXPECT_EQ(commission(35,1,40),381);
EXPECT_EQ(commission(35,2,40),387);
EXPECT_EQ(commission(35,80,40),855);
}
TEST(CommissionPath, C2)
{
EXPECT_EQ(commission(0, 10, 4), -1);
EXPECT_EQ(commission(35,1,40),381);
EXPECT_EQ(commission(35,2,40),387);
EXPECT_EQ(commission(35,80,40),855);
}
TEST(CommissionPath, MCDC)
{
EXPECT_EQ(commission(0, 1, 0), -1);
EXPECT_EQ(commission(0, 1, 91), -1);
EXPECT_EQ(commission(0, 1, 1), -1);
EXPECT_EQ(commission(0, 0, 0), -1);
EXPECT_EQ(commission(0, 0, 91), -1);
EXPECT_EQ(commission(0, 0, 1), -1);
EXPECT_EQ(commission(0, 81, 0), -1);
EXPECT_EQ(commission(0, 81, 91), -1);
EXPECT_EQ(commission(0, 81, 1), -1);
EXPECT_EQ(commission(1, 1, 0), -1);
EXPECT_EQ(commission(1, 1, 91), -1);
EXPECT_EQ(commission(1, 0, 0), -1);
EXPECT_EQ(commission(1, 0, 91), -1);
EXPECT_EQ(commission(1, 0, 1), -1);
EXPECT_EQ(commission(1, 81, 0), -1);
EXPECT_EQ(commission(1, 81, 91), -1);
EXPECT_EQ(commission(1, 81, 1), -1);
EXPECT_EQ(commission(71, 1, 0), -1);
EXPECT_EQ(commission(71, 1, 91), -1);
EXPECT_EQ(commission(71, 1, 1), -1);
EXPECT_EQ(commission(71, 0, 0), -1);
EXPECT_EQ(commission(71, 0, 91), -1);
EXPECT_EQ(commission(71, 0, 1), -1);
EXPECT_EQ(commission(71, 81, 0), -1);
EXPECT_EQ(commission(71, 81, 91), -1);
EXPECT_EQ(commission(71, 81, 1), -1);
EXPECT_NE(commission(1, 1, 1), -1);
EXPECT_EQ(commission(35,1,40),381);
EXPECT_EQ(commission(35,2,40),387);
EXPECT_EQ(commission(35,80,40),855);
}
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
#include <ctime> // for time()
#include <cstdlib> // for rand(), srand(), and RAND_MAX
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct text {
string word;
int occur;
vector<int> pages;
};
struct Node{
text txt;
Node* next[16];
};
Node *head = new Node;
int MAX_HEIGHT = 16;
Node* update[16];
void find(string word, int lnumber);
void insert(string word, int lnumber);
void printInOrder(ostream & output);
|
#include<iostream>
#include<vector>
using std::vector;
using std::cin; using std::cout; using std::endl;
int main()
{
vector<int> v;
int i;
while(cin >> i)
v.push_back(i);
for(auto i : v)
cout << i << endl;
return 0;
}
|
// Created on: 1998-07-09
// Created by: Stephanie HUMEAU
// 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 _GeomFill_FunctionGuide_HeaderFile
#define _GeomFill_FunctionGuide_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Standard_Boolean.hxx>
#include <Standard_Real.hxx>
#include <math_FunctionSetWithDerivatives.hxx>
#include <Standard_Integer.hxx>
#include <math_Vector.hxx>
class Adaptor3d_Curve;
class GeomFill_SectionLaw;
class Geom_Curve;
class Geom_Surface;
class gp_Pnt;
class math_Matrix;
class gp_Vec;
class GeomFill_FunctionGuide : public math_FunctionSetWithDerivatives
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT GeomFill_FunctionGuide(const Handle(GeomFill_SectionLaw)& S, const Handle(Adaptor3d_Curve)& Guide, const Standard_Real ParamOnLaw = 0.0);
Standard_EXPORT void SetParam (const Standard_Real Param, const gp_Pnt& Centre, const gp_XYZ& Dir, const gp_XYZ& XDir);
//! returns the number of variables of the function.
Standard_EXPORT virtual Standard_Integer NbVariables() const Standard_OVERRIDE;
//! returns the number of equations of the function.
Standard_EXPORT virtual Standard_Integer NbEquations() const Standard_OVERRIDE;
//! computes the values <F> of the Functions for the
//! variable <X>.
//! Returns True if the computation was done successfully,
//! False otherwise.
Standard_EXPORT virtual Standard_Boolean Value (const math_Vector& X, math_Vector& F) Standard_OVERRIDE;
//! returns the values <D> of the derivatives for the
//! variable <X>.
//! Returns True if the computation was done successfully,
//! False otherwise.
Standard_EXPORT virtual Standard_Boolean Derivatives (const math_Vector& X, math_Matrix& D) Standard_OVERRIDE;
//! returns the values <F> of the functions and the derivatives
//! <D> for the variable <X>.
//! Returns True if the computation was done successfully,
//! False otherwise.
Standard_EXPORT virtual Standard_Boolean Values (const math_Vector& X, math_Vector& F, math_Matrix& D) Standard_OVERRIDE;
//! returns the values <F> of the T derivatives for
//! the parameter Param .
Standard_EXPORT Standard_Boolean DerivT (const math_Vector& X, const gp_XYZ& DCentre, const gp_XYZ& DDir, math_Vector& DFDT);
//! returns the values <F> of the T2 derivatives for
//! the parameter Param .
//! returns the values <D> of the TX derivatives for
//! the parameter Param .
//! returns Boolean is static;
//! returns the values <T> of the X2 derivatives for
//! the parameter Param .
//! returns Boolean is static;
Standard_EXPORT Standard_Boolean Deriv2T (const gp_XYZ& DCentre, const gp_XYZ& DDir, math_Vector& DFDT, math_Vector& D2FT);
protected:
private:
Standard_EXPORT void DSDT (const Standard_Real U, const Standard_Real V, const gp_XYZ& DCentre, const gp_XYZ& DDir, gp_Vec& DSDT) const;
Handle(Adaptor3d_Curve) TheGuide;
Handle(GeomFill_SectionLaw) TheLaw;
Standard_Boolean isconst;
Handle(Geom_Curve) TheCurve;
Handle(Geom_Curve) TheConst;
Handle(Geom_Surface) TheSurface;
Standard_Real First;
Standard_Real Last;
Standard_Real TheUonS;
gp_XYZ Centre;
gp_XYZ Dir;
};
#endif // _GeomFill_FunctionGuide_HeaderFile
|
//
// Created by glyphack on 7/12/19.
//
#include "Portal.h"
|
//
// DlibKmeansInterface.h
// Author: Michael Bao
// Date: 9/8/2015
//
#pragma once
#include "shared/internal/dlib/DlibInterface.h"
#include "shared/algorithms/cluster/kmeans/KmeansInterface.h"
#include "shared/utility/type/dlib/DlibEigenInterop.h"
#include "dlib/clustering.h"
template<typename ImagePixelType, template<class> class KernelType, int K, int N, int M>
class DlibKmeansInterface: public KmeansInterface<DlibInterface<ImagePixelType>, K, N, M>
{
using Base = KmeansInterface<DlibInterface<ImagePixelType>, K, N, M>;
using SampleType = typename Base::SampleType;
using DlibSampleType = dlib::matrix<double, N, M>;
using FinalKernelType = KernelType<DlibSampleType>;
public:
DlibKmeansInterface():
accuracyParameter(0.01), maximumDictionaryParameters(8)
{
}
virtual void Cluster(const tbb::concurrent_vector<SampleType>& samples, std::array<SampleType, K>& clusters)
{
// Convert Eigen Matrix samples to Dlib Samples
std::vector<DlibSampleType> dlibSamples;
dlibSamples.reserve(samples.size());
std::transform(samples.begin(), samples.end(), std::inserter(dlibSamples, dlibSamples.begin()),
[](auto& s) {
return ConvertToDlibMatrix(s);
});
// Use Dlib K-Means to perform clustering
// Code is based off of: http://dlib.net/kkmeans_ex.cpp.html
dlib::kcentroid<FinalKernelType> kc(*kernel, accuracyParameter, maximumDictionaryParameters);
dlib::kkmeans<FinalKernelType> kmeans(kc);
kmeans.set_number_of_centers(K);
std::vector<DlibSampleType> dlibCenters;
dlibCenters.reserve(K);
dlib::pick_initial_centers(K, dlibCenters, dlibSamples, kmeans.get_kernel());
kmeans.train(dlibSamples, dlibCenters);
// Accumulate the samples in the output 'clusters' array to get the cluster means that we want to use.
int clusterCounter[K] = {};
for (auto i = 0; i < dlibSamples.size(); ++i) {
auto clusterIndex = kmeans(dlibSamples[i]);
clusters[clusterIndex] += ConvertToEigenMatrix_Copy(dlibSamples[i]);
++clusterCounter[clusterIndex];
}
for (int i = 0; i < K; ++i) {
clusters[i] /= (double)clusterCounter[i];
}
}
// Need to be able to change and modify kernel parameters.
void SetKernel(std::unique_ptr<FinalKernelType> inputKernel) {
kernel = std::move(inputKernel);
}
private:
std::unique_ptr<FinalKernelType> kernel;
// Centroid Parameters
double accuracyParameter;
int maximumDictionaryParameters;
};
|
/**
* @file
* @copyright defined in EOTS/LICENSE.txt
*/
#pragma once
#include <eotiolib/memory.h>
#include <eotiolib/print.hpp>
void* sbrk(size_t num_bytes);
extern "C" {
void* malloc(size_t size);
void* calloc(size_t count, size_t size);
void* realloc(void* ptr, size_t size);
void free(void* ptr);
}
|
/****************************************************************************
* *
* Author : lukasz.iwaszkiewicz@gmail.com *
* ~~~~~~~~ *
* License : see COPYING file for details. *
* ~~~~~~~~~ *
****************************************************************************/
#ifndef UPDATECONTEXT_H_
#define UPDATECONTEXT_H_
namespace View {
class GLContext;
}
namespace Util {
class Config;
/**
* Kazdy model w kazdej metodzie update dostanie takie DTO.
*/
struct UpdateContext {
UpdateContext () : glContext (NULL), config (NULL) {}
View::GLContext *glContext;
Util::Config *config;
};
} /* namespace Util */
#endif /* UPDATECONTEXT_H_ */
|
#include "controller.hpp"
using namespace std;
Controller::Controller(int argc, char *argv[])
{
QApplication prog(argc, argv);
MainWindow w;
timer = new QTimer(this);
w.setWindowTitle("Frednator");
w.show();
videoThread = new VideoThread;
videoThread->moveToThread(&workerThread);
int frame_rate = 20;
timer->setInterval( ceil(1000.0 / frame_rate) );
//Connect the button on the GUI to start and stop the video stream
connect(&w, SIGNAL(connectCamera(bool,QString)), videoThread, SLOT(connectVideo(bool,QString)));
//Tells the mainwindow if the connection was successfull
connect(videoThread, SIGNAL(connection(bool)), &w, SLOT(checkConnection(bool)));
//Tells the mainwindow if the connection was successfull
connect(videoThread, SIGNAL(videoOpened(bool)), &w, SLOT(videoOpened(bool)));
//Connect the function selector
connect(&w, SIGNAL(newFunctionSelected(QString, QComboBox*, QFormLayout*)),this, SLOT(functionChanged(QString, QComboBox*, QFormLayout*)));
//Connect the image on the thread to show it on the GUI
connect(videoThread, SIGNAL(sendFrame()), &w, SLOT(displayImage()));
//Start the timer that will control the FPS
connect(videoThread, SIGNAL(startLoop()), this, SLOT(startTimer()));
//Call each frame of the video stream on the correct time
connect(timer,SIGNAL(timeout()), videoThread, SLOT(videoLoop()));
//Connect the record button to start recording the video
connect(&w, SIGNAL(record(QString)), this, SLOT(startRecording(QString)));
//Connect the record button to stop recording the video
connect(&w, SIGNAL(stopRecording()), this, SLOT(stopRecording()));
//Connect the openVideo button to start a video
connect(&w, SIGNAL(openVideo(bool, QString)), this, SLOT(openVideo(bool, QString)));
//Connect the change camera button to change the camera
connect(&w, SIGNAL(changeCamera(int)), this, SLOT(changeCamera(int)));
//Connect the closure of the GUI to end the thread
connect(&w, SIGNAL(finishThread()), this, SLOT(stopThread()));
//Connect the end of the thread loop to terminate the thread
connect(videoThread, SIGNAL(terminateThread()), &workerThread, SLOT(terminate()));
//Connect the end of the thread to close the GUI
connect(videoThread, SIGNAL(terminateThread()), &w, SLOT(threadFinishedslot()));
//Connect the error messages to the GUI
connect(videoThread, SIGNAL(statusMessage(QString)), &w, SLOT(updateStatusMessage(QString)));
//Connect the Save Picture Button with the thread routine
connect(&w, SIGNAL(savePicture()), videoThread, SLOT(savePicture()));
workerThread.start();
prog.exec();
//stopThread();
}
Controller::~Controller()
{
if(timer->isActive())
timer->stop();
workerThread.quit();
workerThread.wait(500);
if(!workerThread.isFinished())
{
workerThread.terminate();
}
}
void Controller::stopThread()
{
timer->stop();
videoThread->stopThread();
workerThread.quit();
workerThread.wait(500);
if(!workerThread.isFinished())
{
workerThread.terminate();
}
}
void Controller::changeCamera(const int &camera)
{
videoThread->changeCamera(camera);
}
void Controller::startTimer()
{
timer->start();
}
void Controller::startRecording(QString fileName)
{
videoThread->startRecording(fileName);
}
void Controller::openVideo(bool open, QString fileName)
{
videoThread->openVideo(open, fileName);
}
void Controller::stopRecording()
{
videoThread->stopRecording();
}
void Controller::addParameter(QString name, double parameter_id, QFormLayout* paramLayout){
QLineEdit* parameter = new QLineEdit(QString::number(parameter_id));
parameter->setPlaceholderText(name);
this->lineEditMap.insert(std::pair<QString, QLineEdit*>(name, parameter));
connect(parameter, SIGNAL(returnPressed()), this, SLOT(paramChanged()));
paramLayout->addRow(name, parameter);
}
void Controller::functionChanged(QString newFunction, QComboBox* vectorSelection, QFormLayout* paramLayout){
newfunction = newFunction;
QLayoutItem* child;
while((child = paramLayout->takeAt(0)) != 0){
if (child->widget()) {
delete child->widget();
}
else{
delete child;
}
}
if(newFunction == "yellowDetector"){ // adicionar os line edits e labels com os argumentos da classe do detector
addParameter("iLowH", videoThread->yellowDetector.iLowH, paramLayout);
addParameter("iHighH", videoThread->yellowDetector.iHighH, paramLayout);
addParameter("iLowS", videoThread->yellowDetector.iLowS, paramLayout);
addParameter("iHighS", videoThread->yellowDetector.iHighS, paramLayout);
addParameter("iLowV", videoThread->yellowDetector.iLowV, paramLayout);
addParameter("iHighV", videoThread->yellowDetector.iHighV, paramLayout);
addParameter("minThreshold", videoThread->yellowDetector.minThreshold, paramLayout);
addParameter("maxThreshold", videoThread->yellowDetector.maxThreshold, paramLayout);
addParameter("minArea", videoThread->yellowDetector.minArea, paramLayout);
addParameter("minConvexity", videoThread->yellowDetector.minConvexity, paramLayout);
addParameter("minCircularity", videoThread->yellowDetector.minCircularity, paramLayout);
addParameter("minInertiaRatio", videoThread->yellowDetector.minInertiaRatio, paramLayout);
}
else if(newFunction == "fieldDetector"){ // adicionar os line edits e labels com os argumentos da classe do detector
addParameter("threshold", videoThread->fieldDetector.threshold, paramLayout);
}
else if(newFunction == "fieldDetector2"){ // adicionar os line edits e labels com os argumentos da classe do detector
addParameter("iLowH", videoThread->fieldDetector2.iLowH, paramLayout);
addParameter("iHighH", videoThread->fieldDetector2.iHighH, paramLayout);
addParameter("iLowL", videoThread->fieldDetector2.iLowL, paramLayout);
addParameter("iHighL", videoThread->fieldDetector2.iHighL, paramLayout);
addParameter("iLowS", videoThread->fieldDetector2.iLowS, paramLayout);
addParameter("iHighS", videoThread->fieldDetector2.iHighS, paramLayout);
addParameter("factor", videoThread->fieldDetector2.factor, paramLayout);
addParameter("dp", videoThread->fieldDetector2.dp, paramLayout);
addParameter("minDist", videoThread->fieldDetector2.minDist, paramLayout);
addParameter("param1", videoThread->fieldDetector2.param1, paramLayout);
addParameter("param1", videoThread->fieldDetector2.param2, paramLayout);
addParameter("minRadius", videoThread->fieldDetector2.minRadius, paramLayout);
addParameter("maxRadius", videoThread->fieldDetector2.maxRadius, paramLayout);
addParameter("kernel", videoThread->fieldDetector2.kernel, paramLayout);
}
else if(newFunction == "ballDetector2"){
addParameter("iLowH", videoThread->ballDetector2.iLowH, paramLayout);
addParameter("iHighH", videoThread->ballDetector2.iHighH, paramLayout);
addParameter("iLowL", videoThread->ballDetector2.iLowL, paramLayout);
addParameter("iHighL", videoThread->ballDetector2.iHighL, paramLayout);
addParameter("iLowS", videoThread->ballDetector2.iLowS, paramLayout);
addParameter("iHighS", videoThread->ballDetector2.iHighS, paramLayout);
addParameter("iLowH2", videoThread->ballDetector2.iLowH2, paramLayout);
addParameter("iHighH2", videoThread->ballDetector2.iHighH2, paramLayout);
addParameter("iLowL2", videoThread->ballDetector2.iLowL2, paramLayout);
addParameter("iHighL2", videoThread->ballDetector2.iHighL2, paramLayout);
addParameter("iLowS2", videoThread->ballDetector2.iLowS2, paramLayout);
addParameter("iHighS2", videoThread->ballDetector2.iHighS2, paramLayout);
addParameter("kernel", videoThread->ballDetector2.kernel, paramLayout);
addParameter("minThreshold", videoThread->ballDetector2.minThreshold, paramLayout);
addParameter("maxThreshold", videoThread->ballDetector2.maxThreshold, paramLayout);
addParameter("minArea", videoThread->ballDetector2.minArea, paramLayout);
addParameter("minConvexity", videoThread->ballDetector2.minConvexity, paramLayout);
addParameter("minCircularity", videoThread->ballDetector2.minCircularity, paramLayout);
addParameter("minInertiaRatio", videoThread->ballDetector2.minInertiaRatio, paramLayout);
}
videoThread->functionChanged(newFunction, vectorSelection, paramLayout);
}
void Controller::paramChanged(){
QLineEdit* lineEdit = qobject_cast<QLineEdit*>(sender());
if(newfunction == "yellowDetector"){
if(lineEdit->placeholderText() == "iLowH"){
videoThread->yellowDetector.iLowH = (lineEdit->text().toInt());
}
else if(lineEdit->placeholderText() == "iHighH"){
videoThread->yellowDetector.iHighH = (lineEdit->text().toInt());
}
else if(lineEdit->placeholderText() == "iLowS"){
videoThread->yellowDetector.iLowS = (lineEdit->text().toInt());
}
else if(lineEdit->placeholderText() == "iHighS"){
videoThread->yellowDetector.iHighS = (lineEdit->text().toInt());
}
else if(lineEdit->placeholderText() == "iLowV"){
videoThread->yellowDetector.iLowV = (lineEdit->text().toInt());
}
else if(lineEdit->placeholderText() == "iHighV"){
videoThread->yellowDetector.iHighV = (lineEdit->text().toInt());
}
else if(lineEdit->placeholderText() == "minThreshold"){
videoThread->yellowDetector.minThreshold = (lineEdit->text().toInt());
}
else if(lineEdit->placeholderText() == "maxThreshold"){
videoThread->yellowDetector.maxThreshold = (lineEdit->text().toInt());
}
else if(lineEdit->placeholderText() == "minArea"){
videoThread->yellowDetector.minArea = (lineEdit->text().toDouble());
}
else if(lineEdit->placeholderText() == "minCircularity"){
videoThread->yellowDetector.minCircularity = (lineEdit->text().toDouble());
}
else if(lineEdit->placeholderText() == "minConvexity"){
videoThread->yellowDetector.minConvexity = (lineEdit->text().toDouble());
}
else if(lineEdit->placeholderText() == "minInertiaRatio"){
videoThread->yellowDetector.minInertiaRatio = (lineEdit->text().toDouble());
}
}
else if(newfunction == "fieldDetector2"){
if(lineEdit->placeholderText() == "iLowH"){
videoThread->fieldDetector2.iLowH = (lineEdit->text().toInt());
}
else if(lineEdit->placeholderText() == "iHighH"){
videoThread->fieldDetector2.iHighH = (lineEdit->text().toInt());
}
else if(lineEdit->placeholderText() == "iLowL"){
videoThread->fieldDetector2.iLowL = (lineEdit->text().toInt());
}
else if(lineEdit->placeholderText() == "iHighL"){
videoThread->fieldDetector2.iHighL = (lineEdit->text().toInt());
}
else if(lineEdit->placeholderText() == "iLowS"){
videoThread->fieldDetector2.iLowS = (lineEdit->text().toInt());
}
else if(lineEdit->placeholderText() == "iHighS"){
videoThread->fieldDetector2.iHighS = (lineEdit->text().toInt());
}
else if(lineEdit->placeholderText() == "factor"){
videoThread->fieldDetector2.factor = (lineEdit->text().toFloat());
}
else if(lineEdit->placeholderText() == "dp"){
videoThread->fieldDetector2.dp = (lineEdit->text().toDouble());
}
else if(lineEdit->placeholderText() == "minDist"){
videoThread->fieldDetector2.minDist = (lineEdit->text().toDouble());
}
else if(lineEdit->placeholderText() == "param1"){
videoThread->fieldDetector2.param1 = (lineEdit->text().toDouble());
}
else if(lineEdit->placeholderText() == "param2"){
videoThread->fieldDetector2.param2 = (lineEdit->text().toDouble());
}
else if(lineEdit->placeholderText() == "maxRadius"){
videoThread->fieldDetector2.maxRadius = (lineEdit->text().toInt());
}
else if(lineEdit->placeholderText() == "minRadius"){
videoThread->fieldDetector2.minRadius = (lineEdit->text().toInt());
}
else if(lineEdit->placeholderText() == "kernel"){
videoThread->fieldDetector2.kernel = (lineEdit->text().toInt());
}
}
else if(newfunction == "fieldDetector"){
if(lineEdit->placeholderText() == "threshold"){
videoThread->fieldDetector.threshold = (lineEdit->text().toInt());
}
}
else if(newfunction == "ballDetector2"){
if(lineEdit->placeholderText() == "iLowH"){
videoThread->ballDetector2.iLowH = (lineEdit->text().toInt());
}
else if(lineEdit->placeholderText() == "iHighH"){
videoThread->ballDetector2.iHighH = (lineEdit->text().toInt());
}
else if(lineEdit->placeholderText() == "iLowL"){
videoThread->ballDetector2.iLowL = (lineEdit->text().toInt());
}
else if(lineEdit->placeholderText() == "iHighL"){
videoThread->ballDetector2.iHighL = (lineEdit->text().toInt());
}
else if(lineEdit->placeholderText() == "iLowS"){
videoThread->ballDetector2.iLowS = (lineEdit->text().toInt());
}
else if(lineEdit->placeholderText() == "iHighS"){
videoThread->ballDetector2.iHighS = (lineEdit->text().toInt());
}
else if(lineEdit->placeholderText() == "iLowH2"){
videoThread->ballDetector2.iLowH2 = (lineEdit->text().toInt());
}
else if(lineEdit->placeholderText() == "iHighH2"){
videoThread->ballDetector2.iHighH2 = (lineEdit->text().toInt());
}
else if(lineEdit->placeholderText() == "iLowL2"){
videoThread->ballDetector2.iLowL2 = (lineEdit->text().toInt());
}
else if(lineEdit->placeholderText() == "iHighL2"){
videoThread->ballDetector2.iHighL2 = (lineEdit->text().toInt());
}
else if(lineEdit->placeholderText() == "iLowS2"){
videoThread->ballDetector2.iLowS2 = (lineEdit->text().toInt());
}
else if(lineEdit->placeholderText() == "iHighS2"){
videoThread->ballDetector2.iHighS2 = (lineEdit->text().toInt());
}
else if(lineEdit->placeholderText() == "kernel"){
videoThread->ballDetector2.kernel = (lineEdit->text().toInt());
}
else if(lineEdit->placeholderText() == "minThreshold"){
videoThread->ballDetector2.minThreshold = (lineEdit->text().toInt());
}
else if(lineEdit->placeholderText() == "maxThreshold"){
videoThread->ballDetector2.maxThreshold = (lineEdit->text().toInt());
}
else if(lineEdit->placeholderText() == "minArea"){
videoThread->ballDetector2.minArea = (lineEdit->text().toDouble());
}
else if(lineEdit->placeholderText() == "minCircularity"){
videoThread->ballDetector2.minCircularity = (lineEdit->text().toDouble());
}
else if(lineEdit->placeholderText() == "minConvexity"){
videoThread->ballDetector2.minConvexity = (lineEdit->text().toDouble());
}
else if(lineEdit->placeholderText() == "minInertiaRatio"){
videoThread->ballDetector2.minInertiaRatio = (lineEdit->text().toDouble());
}
}
}
|
#ifndef __MAPPOINTTOBUCKET_H__
#define __MAPPOINTTOBUCKET_H__
#include <iostream>
#include <dax/Types.h>
#include <dax/Extent.h>
#include <dax/CellTag.h>
#include <dax/cont/UniformGrid.h>
#include <dax/exec/internal/TopologyUniform.h>
#include <dax/math/Compare.h>
#include <dax/math/Precision.h>
using namespace dax::cont;
class MapPointToBucket
{
public:
typedef dax::exec::internal::TopologyUniform TopologyStructConstExecution;
typedef dax::exec::internal::TopologyUniform TopologyStructExecution;
// the main parameters for the uniform grid
dax::Vector3 Origin;
dax::Vector3 Spacing;
dax::Extent3 Extent;
// some constructors to help
DAX_EXEC_CONT_EXPORT
MapPointToBucket() {}
DAX_EXEC_CONT_EXPORT
MapPointToBucket(const dax::Vector3& origin,
const dax::Vector3& spacing,
const dax::Extent3& extent)
: Origin(origin), Spacing(spacing), Extent(extent)
{}
DAX_CONT_EXPORT
MapPointToBucket(const UniformGrid<>& grid)
: Origin(grid.GetOrigin()),
Spacing(grid.GetSpacing()),
Extent(grid.GetExtent())
{}
DAX_EXEC_EXPORT
MapPointToBucket(TopologyStructConstExecution topology)
: Origin(topology.Origin),
Spacing(topology.Spacing),
Extent(topology.Extent)
{}
DAX_EXEC_CONT_EXPORT
dax::Id3 MapToIndex3(const dax::Vector3& point) const
{
// compute the point coordinate within the grid
dax::Vector3 coord(point[0] - this->Origin[0],
point[1] - this->Origin[1],
point[2] - this->Origin[2]);
// which bucket the point belongs
dax::Id3 id;
for (int i = 0; i < 3; ++i)
id[i] = fabs(this->Spacing[i]) < 0.0001 ?
0 : dax::math::Floor(coord[i] / this->Spacing[i]);
return id;
}
DAX_EXEC_CONT_EXPORT
dax::Id MapToFlatIndex(const dax::Vector3& point) const
{
dax::Id3 id = MapToIndex3(point);
dax::Id ret = index3ToFlatIndexCell(id, this->Extent);
return ret;
}
protected:
private:
};
#endif //__MAPPOINTTOBUCKET_H__
|
#pragma once
#include <vector>
#include <limits>
#include <memory>
#include <cassert>
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
namespace py = pybind11;
enum class ShiftDir
{
NONE,
UP,
LEFT,
UPLEFT
};
struct ShiftDirHash
{
template <typename T>
std::size_t operator()(T t) const {
return static_cast<std::size_t>(t);
}
};
class MV
{
public:
/// Constructor
MV(int x = 0,
int y = 0,
ShiftDir shift_dir = ShiftDir::NONE,
long error = std::numeric_limits<long>::max())
: x(x)
, y(y)
, shift_dir(shift_dir)
, error(error)
, subvectors(nullptr)
, is_splitted(false)
{}
/// Copy constructor
MV(const MV& other)
: x(other.x)
, y(other.y)
, shift_dir(other.shift_dir)
, error(other.error)
, subvectors(other.subvectors)
, is_splitted(other.is_splitted)
{
if (is_splitted) {
subvectors = new MV[4];
for (int i = 0; i < 4; ++i) {
subvectors[i] = other.subvectors[i];
}
}
}
/// Move constructor
MV(MV&& other)
: MV()
{
swap(other);
}
/// Copy + move assignment operator
MV& operator=(MV other)
{
swap(other);
return *this;
}
/// Split into 4 subvectors
inline void Split()
{
if (!is_splitted) {
is_splitted = true;
subvectors = new MV[4];
}
}
/// Unsplit
inline void Unsplit()
{
is_splitted = false;
delete[] subvectors;
}
/// Check if the motion vector is split
inline bool IsSplit() const
{
return is_splitted;
}
/// Get a subvector
inline MV& SubVector(int id)
{
assert(is_splitted && id >= 0 && id < 4);
return subvectors[id];
}
~MV() {
if (is_splitted) {
delete[] subvectors;
}
}
int x;
int y;
ShiftDir shift_dir;
long error;
private:
MV* subvectors;
bool is_splitted;
void swap(MV& other)
{
std::swap(x, other.x);
std::swap(y, other.y);
std::swap(shift_dir, other.shift_dir);
std::swap(error, other.error);
std::swap(subvectors, other.subvectors);
std::swap(is_splitted, other.is_splitted);
}
friend class MEField;
};
class MEField {
private:
std::vector<MV> vectors;
size_t block_size;
size_t num_blocks_vert;
size_t num_blocks_hor;
public:
MEField(size_t num_blocks_hor, size_t num_blocks_vert, size_t block_size);
void set_mv(size_t x, size_t y, const MV& vector);
MV& get_mv(size_t x, size_t y);
py::tuple ConvertToOF() const;
py::array_t<unsigned char> Remap(py::array_t<unsigned char> input) const;
};
|
// ####################################################################
// Auteur : Alix Dumay et Mehdi Taguema
// Date : 24/04/2019
// Version : 1.5
// Description : Ce programme permet de créer la classe Data_Météo
// Cette classe permet de réaliser toutes les fonctions nécessaire à la station météo
// ####################################################################
#pragma once
#include <QObject>
#include "bme280.h"
#include "bme280_defs.h"
#include "capteur.h"
#include <deque>
class Data_Meteo : public QObject
{
Q_OBJECT
// ####################################################################
// Déclaration des Q_PROPERTY permettant à l'interface graphique de récupérer
// des attributs et des méthodes de la classe via des signaux et des slots
// #####################################################################
// ####################################################################
// Signaux liés à l'application météo "basique"
// #####################################################################
//Récupếration des métriques
Q_PROPERTY(qreal getTemp READ getTemp NOTIFY tempChanged)
Q_PROPERTY(qreal getHum READ getHum NOTIFY humChanged)
Q_PROPERTY(qreal getPress READ getPress NOTIFY pressChanged)
//Récupération de l'adresse de l'image météo, de l'image Tendance, du texte de description
Q_PROPERTY(QString getImage READ getImage NOTIFY imageChanged)
Q_PROPERTY(QString getTendance READ getTendance NOTIFY tendChanged)
Q_PROPERTY(QString getDescr READ getDescr NOTIFY descrChanged)
Q_PROPERTY(qreal getAnimation READ getAnimation NOTIFY AnimationChanged)
Q_PROPERTY(qreal gettend READ gettend NOTIFY tendanceChanged)
// Récupération de la couleur pour le changement de la couleur du fond en fonction de l'heure
Q_PROPERTY(QString getColor_background READ getColor_background NOTIFY Color_backgroundChanged)
// Récupération de la couleur pour le changement de la couleur du fond en fonction de l'heure
Q_PROPERTY(QString getMoon READ getMoon NOTIFY MoonChanged)
// ####################################################################
// Signaux liés à l'application météo "optionnel" (historique sur 3h)
// #####################################################################
//Récupération de l'historique des températures
Q_PROPERTY(qreal getTemp3 READ getTemp3 NOTIFY Temp3Changed)
Q_PROPERTY(qreal getTemp2 READ getTemp2 NOTIFY Temp2Changed)
Q_PROPERTY(qreal getTemp1 READ getTemp1 NOTIFY Temp1Changed)
//Récupération de l'historique des humidités
Q_PROPERTY(qreal getHum3 READ getHum3 NOTIFY hum3Changed)
Q_PROPERTY(qreal getHum2 READ getHum2 NOTIFY hum2Changed)
Q_PROPERTY(qreal getHum1 READ getHum1 NOTIFY hum1Changed)
//Récupération de l'historique des pressions
Q_PROPERTY(qreal getPress3 READ getPress3 NOTIFY Press3Changed)
Q_PROPERTY(qreal getPress2 READ getPress2 NOTIFY Press2Changed)
Q_PROPERTY(qreal getPress1 READ getPress1 NOTIFY Press1Changed)
//Récupération de l'historique des images météo
Q_PROPERTY(QString getImage_h1 READ getImage_h1 NOTIFY image_h1Changed)
Q_PROPERTY(QString getImage_h2 READ getImage_h2 NOTIFY image_h2Changed)
Q_PROPERTY(QString getImage_h3 READ getImage_h3 NOTIFY image_h3Changed)
// ####################################################################
// Déclaration des attributs privés de la classe
// ####################################################################
private:
// ####################################################################
// Déclaration des attributs liés à l'application "basique"
// ####################################################################
qreal m_temp;
qreal m_humidity;
qreal m_pressure;
qreal m_press_sea;
qreal m_altitude=151.5; //Calcul de l'altitude sur Toulouse, en m
QString m_image="Icones/chargement.svg";
qint32 m_zambretti=2;
qreal m_tendance=0;
QString m_tendance_im; //Variable stockant l'adresse de l'image liée à la tendance
QString m_description="Chargement ...";
qreal m_animation=0;
QString m_color_bg="aquamarine";
// Image lune...
QString m_moon="Icones/chargement.svg";
// ####################################################################
// Déclaration des attributs liés à l'application "optionnelle" (historique sur 3h)
// ####################################################################
//Image de la météo
QString m_image_h1="Icones/chargement.svg";
QString m_image_h2="Icones/chargement.svg";
QString m_image_h3="Icones/chargement.svg";
//Valeur de zambretti
qint32 m_zambretti_h3=2;
qint32 m_zambretti_h2=2;
qint32 m_zambretti_h1=2;
//Pressions
qreal m_pressure_h3;
qreal m_pressure_h2;
qreal m_pressure_h1;
//Températures
qreal m_temp_h3;
qreal m_temp_h2;
qreal m_temp_h1;
//Humidités
qreal m_hum_h3;
qreal m_hum_h2;
qreal m_hum_h1;
// ####################################################################
// Déclaration des containers (deque) liés au stockage des valeurs
// ####################################################################
//Stockage de la pression au niveau de la mer toutes les secondes, puis min, puis heure
std::deque<qreal> val_seconde;
std::deque<qreal> val_minutes;
std::deque<qreal> val_heure;
//Stockage de la température toutes les sec, puis min, puis heure
std::deque<qreal> stock_temp_sec;
std::deque<qreal> stock_temp_min;
std::deque<qreal> stock_temp_heure;
//Stockage de la pression toutes les sec, puis min, puis heure
std::deque<qreal> stock_press_sec;
std::deque<qreal> stock_press_min;
std::deque<qreal> stock_press_heure;
//Stockage de l'humidité toutes les sec, puis min, puis heure
std::deque<qreal> stock_hum_sec;
std::deque<qreal> stock_hum_min;
std::deque<qreal> stock_hum_heure;
//Stockage de la valeur de zambretti toute les heures, pour historique
std::deque<qint32> stock_zambretti;
//Création de structures dev et data liés au capteur bme280
struct bme280_dev m_dev;
struct bme280_data m_data;
// ####################################################################
// Déclaration des signaux pour l'acquisition des attributs de la classe par l'interface
// ####################################################################
signals:
// ####################################################################
// Signaux liés à l'application "basique"
// ####################################################################
void tempChanged();
void humChanged();
void pressChanged();
void imageChanged();
void tendChanged();
void descrChanged();
void tendanceChanged();
void AnimationChanged();
void Color_backgroundChanged();
void MoonChanged();
// ####################################################################
// Signaux liés à l'application "optionnelle"
// ####################################################################
// Singaux liés aux changements de l'image météo
void image_h1Changed();
void image_h2Changed();
void image_h3Changed();
// Singaux liés aux changements de l'humidité
void hum3Changed();
void hum2Changed();
void hum1Changed();
// Singaux liés aux changements de la Température
void Temp3Changed();
void Temp2Changed();
void Temp1Changed();
// Singaux liés aux changements de la Pression
void Press3Changed();
void Press2Changed();
void Press1Changed();
// ####################################################################
// Déclaration des méthodes publiques de la classe, utilisable par l'interface (slots)
// ####################################################################
public slots:
//Actualisation de T,P et H
void maj_temp();
void maj_hum();
void maj_press();
//Mise à jour des métriques lues
void refresh();
//Initialisation du capteur
void capt_init();
//Calcul de la pression au niveau de la mer
void calc_press_sea();
//Algorithme de zambretti
void calc_zambretti(qreal pression);
//Calcul une moyenne d'un vecteur ou deque
qreal moyenne (std::deque <qreal> &nbre);
//Calcul de la tendance
void calc_tendance();
//Stock des valeurs toutes les secondes, puis la moyenne de 60 sec toute les minutes, puis la moyenne de 60min toutes les heures
void calc_history(std::deque<qreal> &stock_data_sec,std::deque<qreal> &stock_data_min,std::deque<qreal> &stock_data_heure, int type);
//Selon la valeur de zambretti stockée, permet de definir la météo et l'image correspondante
void calc_zambretti_history();
//Fonction pour le calcul de la phase lunaire
void calc_moon();
//Fonction permettant de changer le fond d'écran
void change_background();
//fonction permettant l'animation de la flêche
void animation();
// ####################################################################
// Déclaration des méthodes publiques de la classe, permettant l'accès à ces attributs par l'interface
// ####################################################################
public:
//Constructeur de la classe
Data_Meteo();
//Get des attributs de la classe
qreal getTemp() const;
qreal getHum() const;
qreal getPress() const;
qreal getAnimation() const;
qreal gettend() const;
QString getImage() const;
QString getTendance() const;
QString getDescr() const;
QString getColor_background() const;
QString getMoon() const;
qreal getHum3() const;
qreal getHum2() const;
qreal getHum1() const;
qreal getTemp3() const;
qreal getTemp2() const;
qreal getTemp1() const;
qreal getPress3() const;
qreal getPress2() const;
qreal getPress1() const;
QString getImage_h1() const;
QString getImage_h2() const;
QString getImage_h3() const;
};
|
#include <iostream>
#include <queue>
#include <set>
#include <string>
#include <vector>
using namespace std;
const int TC_M[4] = {3, 2, 4, 2};
const int TC_N[4] = {3, 4, 4, 2};
const vector<string> TC_BOARD[4] = {{"DBA", "C*A", "CDB"},
{"NRYN", "ARYA"},
{".ZI.", "M.**", "MZU.", ".IU."},
{"AB", "BA"}};
const string TC_ANSWER[4] = {"ABCD", "RYAN", "MUZI", "IMPOSSIBLE"};
int dir_i[4] = {0, 1, 0, -1};
int dir_j[4] = {1, 0, -1, 0};
bool isFindWithBFS(const char &target, const int &curi, const int &curj,
vector<string> &board, const int &m, const int &n) {
/* 오 */
for (int d = 1; d + curj < n; d++) {
if (board[curi][curj + d] == '.') {
for (int di = -1; di + curi >= 0; di--) {
if (board[curi + di][curj + d] == target) {
board[curi][curj] = '.';
board[curi + di][curj + d] = '.';
return true;
} else if (board[curi + di][curj + d] != '.') {
break;
}
}
for (int di = 1; di + curi < m; di++) {
if (board[curi + di][curj + d] == target) {
board[curi][curj] = '.';
board[curi + di][curj + d] = '.';
return true;
} else if (board[curi + di][curj + d] != '.') {
break;
}
}
} else if (board[curi][curj + d] == target) {
board[curi][curj] = '.';
board[curi][curj + d] = '.';
return true;
} else {
break;
}
}
/* 왼 */
for (int d = -1; d + curj >= 0; d--) {
if (board[curi][curj + d] == '.') {
for (int di = -1; di + curi >= 0; di--) {
if (board[curi + di][curj + d] == target) {
board[curi][curj] = '.';
board[curi + di][curj + d] = '.';
return true;
} else if (board[curi + di][curj + d] != '.') {
break;
}
}
for (int di = 1; di + curi < m; di++) {
if (board[curi + di][curj + d] == target) {
board[curi][curj] = '.';
board[curi + di][curj + d] = '.';
return true;
} else if (board[curi + di][curj + d] != '.') {
break;
}
}
} else if (board[curi][curj + d] == target) {
board[curi][curj] = '.';
board[curi][curj + d] = '.';
return true;
} else {
break;
}
}
/* 위 */
for (int d = -1; d + curi >= 0; d--) {
if (board[curi + d][curj] == '.') {
for (int dj = -1; dj + curj >= 0; dj--) {
if (board[curi + d][curj + dj] == target) {
board[curi][curj] = '.';
board[curi + d][curj + dj] = '.';
return true;
} else if (board[curi + d][curj + dj] != '.') {
break;
}
}
for (int dj = 1; dj + curj < m; dj++) {
if (board[curi + d][curj + dj] == target) {
board[curi][curj] = '.';
board[curi + d][curj + dj] = '.';
return true;
} else if (board[curi + d][curj + dj] != '.') {
break;
}
}
} else if (board[curi + d][curj] == target) {
board[curi][curj] = '.';
board[curi + d][curj] = '.';
return true;
} else {
break;
}
}
/* 아래 */
for (int d = 1; d + curi < m; d++) {
if (board[curi + d][curj] == '.') {
for (int dj = -1; dj + curj >= 0; dj--) {
if (board[curi + d][curj + dj] == target) {
board[curi][curj] = '.';
board[curi + d][curj + dj] = '.';
return true;
} else if (board[curi + d][curj + dj] != '.') {
break;
}
}
for (int dj = 1; dj + curj < m; dj++) {
if (board[curi + d][curj + dj] == target) {
board[curi][curj] = '.';
board[curi + d][curj + dj] = '.';
return true;
} else if (board[curi + d][curj + dj] != '.') {
break;
}
}
} else if (board[curi + d][curj] == target) {
board[curi][curj] = '.';
board[curi + d][curj] = '.';
return true;
} else {
break;
}
}
return false;
}
// 전역 변수를 정의할 경우 함수 내에 초기화 코드를 꼭 작성해주세요.
string solution(int m, int n, vector<string> board) {
string answer = "";
set<char> alphabetList;
for (string str : board) {
for (char ch : str) {
if (ch > 64 && ch < 91) {
alphabetList.insert(ch);
}
}
}
while (!alphabetList.empty()) {
bool operated = false;
for (auto it = alphabetList.begin(); it != alphabetList.end();) {
/* 연결되는 것을 찾으면 제거하고 빠져나온다 */
char currentChar = *it;
for (int i = 0; i < m; i++) {
bool check = false;
for (int j = 0; j < n; j++) {
if (board[i][j] == currentChar) {
check = true;
if (isFindWithBFS(currentChar, i, j, board, m, n)) {
answer += *it;
alphabetList.erase(it);
operated = true;
} else {
it++;
}
break;
}
}
if (check) {
break;
}
}
if (operated) {
break;
}
}
if(!operated){
answer = "IMPOSSIBLE";
break;
}
}
return answer;
}
int main() {
/* test case */
for (int i = 0; i < 4; i++) {
cout << solution(TC_M[i], TC_N[i], TC_BOARD[i]) << '\n';
// if (TC_ANSWER[i].compare(solution(TC_M[i], TC_N[i], TC_BOARD[i])) == 0) {
// cout << "clear" << '\n';
// } else {
// cout << "failed" << '\n';
// }
}
return 0;
}
|
#include <bootcon.h>
#include <8259.h>
#include <kbdtest.h>
#include <port.h>
#include <regsave.h>
extern G2BootConsole console;
extern G2PIC pic8259;
void int2Hex(uint64_t x, char *buf, size_t size) {
// expect buf to be n characters long - last one gets \0
buf[size - 1] = '\0';
uint64_t num = x;
int i = size - 1;
// (void)x;
do {
buf[--i] = "0123456789ABCDEF"[num % 16];
num >>= 4;
} while (num > 0 && i);
while (--i >= 0) buf[i] = '0';
}
__attribute__((interrupt)) void kbdTest(ExceptionStackFrame *frame) {
EM64RegisterSave s;
saveAll(&s);
console.puts("Keyboard event!\n");
G2Inline::inb(0x60);
pic8259.EOI(1);
asm("sti");
return;
}
__attribute__((interrupt)) void KIWF(ExceptionStackFrame *frame, unsigned long int errorCode) {
console.puts(" -- KERNEL MODE FATAL EXCEPTION; HALT NOW\n");
char buf[17];
int2Hex(frame->RIP, buf, sizeof(buf));
console.puts(buf);
asm("cli");
asm("hlt");
return;
}
__attribute__((interrupt)) void illegal(ExceptionStackFrame *frame) {
console.puts("SYS$ILLINSTR -- ILLEGAL INSTRUCTION @ 0x");
char buf[17];
int2Hex(frame->RIP, buf, sizeof(buf));
console.puts(buf);
console.puts("\n");
return;
}
__attribute__((interrupt)) void generalProtection(ExceptionStackFrame *frame, unsigned long int errorCode) {
console.puts(" -- GENERAL PROTECTION FAULT 0x");
char buf[17];
int2Hex(errorCode, buf, sizeof(buf));
console.puts(buf);
console.puts("\n");
return;
}
|
#include "RenderSystem.h"
#include "GlobalVariablePool.h"
#include "OMesh.h"
#include "PreDefine.h"
#include "GpuProgram.h"
#include "Entity.h"
#include "RenderTarget.h"
#include "Camera.h"
#include "Geometry.h"
#include "EGLUtil.h"
#include "ResourceManager.h"
#include "animation_helper.h"
#include "pass.h"
#include "TextureManager.h"
namespace HW
{
vector<RenderQueue> SplitRenderQueue(RenderQueue& queue, int maxNum = 0) {
vector<RenderQueue> outqueue;
SortByMeshName(queue);
string lastname;
int count = 0;
for (int i = 0; i < queue.size(); i++) {
if (queue[i].asMesh == NULL) continue;
count++;
if (outqueue.size() == 0 || queue[i].asMesh->name != lastname || count == maxNum) {
outqueue.push_back(RenderQueue());
count = 0;
}
lastname = queue[i].asMesh->name;
int l = outqueue.size();
outqueue[l - 1].push_back(queue[i]);
}
return outqueue;
}
void CollectWorldMatrixs(RenderQueue& queue, vector<Matrix4>& out) {
out = vector<Matrix4>(queue.size(),Matrix4::IDENTITY);
for (int i = 0; i < queue.size();i++) {
if (queue[i].entity != NULL) {
out[i]=queue[i].entity->getParent()->getWorldMatrix();
}
}
}
void RenderSystem::RenderPass(Camera* camera, RenderQueue & renderqueue, as_Pass* pass, RenderTarget * rt)
{
assert(rt != NULL);
assert(pass != NULL);
GlobalVariablePool* gp = GlobalVariablePool::GetSingletonPtr();
Entity * entity = NULL;
GpuProgram * program = NULL;
program = pass->mProgram;
program->UseProgram();
rt->bindTarget();
if (pass->mClearState.mclearcolorbuffer| pass->mClearState.mcleardepthbuffer| pass->mClearState.mclearstencilbuffer){
// to be fixed
if (pass->name == "gbuffer pass") {
const unsigned clear_color_value[4] = { 0 };
float colorf[4] = { 0,0,0,0 };
const float clear_depth_value = 1.f;
glClearBufferuiv(GL_COLOR, 3, clear_color_value);
glClearBufferfv(GL_COLOR, 0, colorf);
glClearBufferfv(GL_COLOR, 1, colorf);
glClearBufferfv(GL_COLOR, 2, colorf);
glClearBufferfv(GL_DEPTH, 0, &clear_depth_value);
GL_CHECK();
}
else
{
Vector4 c = pass->mClearState.mClearColor;
ClearColor(c.x, c.y, c.z, c.w);
ClearBuffer(pass->mClearState);
}
}
this->SetViewport(0, 0, rt->getWidth(), rt->getHeight());
// Logger::WriteLog("Render Queue %d", renderqueue.size());
this->setBlendState(pass->mBlendState);
this->setDepthStencilState(pass->mDepthStencilState);
this->setRasterState(pass->mRasterState);
//==================================
//ÁÙʱ²âÊÔbone matrix
//vector<Matrix4> temp_matrices;
//
// static float t = 0;
// t += 0.3;
// if (t > 30) t = 0;
// as_Skeleton* ske;
// map<int, Matrix4> temp_bone_matrices;
// auto& g = GlobalResourceManager::getInstance();
// for (auto& skeleton : g.as_skeletonManager.resources){
// ske = skeleton.second;
// }
// for (auto& ani : g.as_skeletonAniManager.resources){
// updateSkeleton(ani.second, t, ske, temp_bone_matrices);
// }
// temp_matrices = vector<Matrix4>(temp_bone_matrices.size());
// for (auto& x : temp_bone_matrices){
// temp_matrices[x.first] = x.second;
// //temp_matrices[x.first] = Matrix4::IDENTITY;
//
// }
//==================================
if (camera != NULL)
gp->SetCamera(camera);
if (pass->UseInstance) {
auto splitdQueues = SplitRenderQueue(renderqueue, pass->InstanceBatchNum);
for (auto& queue : splitdQueues) {
//cout << splitdQueues.size() << endl;
vector<Matrix4> worldMatrixs;
CollectWorldMatrixs(queue, worldMatrixs);
auto x = queue[0];
if (x.asMesh != NULL)
gp->SetMaterial(x.asMesh->material);
program->setProgramConstantData("InstanceMatrix", worldMatrixs.data(), "mat4",
worldMatrixs.size()*sizeof(Matrix4));
program->texture_count = 0;
program->updateProgramData(program->m_ProgramData);
program->UpdateGlobalVariable(pass->mUniformMap);
auto& currentGeo = x.asMesh->renderable;
if (currentGeo == NULL) {
auto g = GlobalResourceManager::getInstance().m_GeometryFactory;
auto& grm = GlobalResourceManager::getInstance();
//auto eg = static_cast<GLGeometryFactory*>(g);
currentGeo = g->create(x.asMesh->geometry, pass->mInputLayout);
}
DrawGeometryInstance(currentGeo,queue.size());
}
}
else {
program->texture_count = 0;
program->updateProgramData(program->m_ProgramData);
for (auto& x : renderqueue) {
if (x.asMesh == NULL) continue;
if (x.entity != NULL) {
gp->SetWorldMatrix(x.entity->getParent()->getWorldMatrix());
}
//gp->setMatrices(temp_matrices);
if (x.asMesh != NULL)
gp->SetMaterial(x.asMesh->material);
program->UpdateGlobalVariable(pass->mUniformMap);
auto& currentGeo = x.asMesh->renderable;
if (currentGeo == NULL) {
auto g = GlobalResourceManager::getInstance().m_GeometryFactory;
auto& grm = GlobalResourceManager::getInstance();
//auto eg = static_cast<GLGeometryFactory*>(g);
currentGeo = g->create(x.asMesh->geometry, pass->mInputLayout);
}
DrawGeometry(currentGeo);
}
}
}
}
|
#include "SCEEventAction.hh"
#include "SCECalorimeterSD.hh"
#include "SCECalorHit.hh"
#include "SCEAnalysis.hh"
#include "G4RunManager.hh"
#include "G4Event.hh"
#include "G4SDManager.hh"
#include "G4HCofThisEvent.hh"
#include "G4UnitsTable.hh"
#include "Randomize.hh"
#include <iomanip>
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
SCEEventAction::SCEEventAction()
: G4UserEventAction(),
fAbsHCID(-1),
fGapHCID(-1)
{}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
SCEEventAction::~SCEEventAction()
{}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
SCECalorHitsCollection*
SCEEventAction::GetHitsCollection(G4int hcID,
const G4Event* event) const
{
auto hitsCollection
= static_cast<SCECalorHitsCollection*>(
event->GetHCofThisEvent()->GetHC(hcID));
if ( ! hitsCollection ) {
G4ExceptionDescription msg;
msg << "Cannot access hitsCollection ID " << hcID;
G4Exception("SCEEventAction::GetHitsCollection()",
"MyCode0003", FatalException, msg);
}
return hitsCollection;
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void SCEEventAction::PrintEventStatistics(
G4double absoEdep, G4double absoTrackLength,
G4double gapEdep, G4double gapTrackLength) const
{
// print event statistics
G4cout
<< " Absorber: total energy: "
<< std::setw(7) << G4BestUnit(absoEdep, "Energy")
<< " total track length: "
<< std::setw(7) << G4BestUnit(absoTrackLength, "Length")
<< G4endl
<< " Gap: total energy: "
<< std::setw(7) << G4BestUnit(gapEdep, "Energy")
<< " total track length: "
<< std::setw(7) << G4BestUnit(gapTrackLength, "Length")
<< G4endl;
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void SCEEventAction::BeginOfEventAction(const G4Event* /*event*/)
{}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void SCEEventAction::EndOfEventAction(const G4Event* event)
{
// Get hits collections IDs (only once)
if ( fAbsHCID == -1 ) {
fAbsHCID
= G4SDManager::GetSDMpointer()->GetCollectionID("AbsorberHitsCollection");
fGapHCID
= G4SDManager::GetSDMpointer()->GetCollectionID("GapHitsCollection");
}
// Get hits collections
auto absoHC = GetHitsCollection(fAbsHCID, event);
auto gapHC = GetHitsCollection(fGapHCID, event);
// Get hit with total values
auto absoHit = (*absoHC)[absoHC->entries()-1];
auto gapHit = (*gapHC)[gapHC->entries()-1];
// Print per event (modulo n)
//
auto eventID = event->GetEventID();
auto printModulo = G4RunManager::GetRunManager()->GetPrintProgress();
if ( ( printModulo > 0 ) && ( eventID % printModulo == 0 ) ) {
G4cout << "---> End of event: " << eventID << G4endl;
PrintEventStatistics(
absoHit->GetEdep(), absoHit->GetTrackLength(),
gapHit->GetEdep(), gapHit->GetTrackLength());
}
// Fill histograms, ntuple
//
// get analysis manager
auto analysisManager = G4AnalysisManager::Instance();
int id = 0;
int id_tup = 0;
double abso_lenght = 0;
double gap_lenght = 0;
// loop over layers
for (int i=0; i<absoHC->entries(); i++) {
absoHit = (*absoHC)[i];
gapHit = (*gapHC)[i];
abso_lenght += absoHit->GetTrackLength();
gap_lenght += gapHit->GetTrackLength();
// fill histograms
analysisManager->FillH1(id, absoHit->GetEdep());
analysisManager->FillH1(id + 1, gapHit->GetEdep());
if (i!=0 && i<(absoHC->entries()-1)) {
analysisManager->FillH1(id + 2, abso_lenght);
analysisManager->FillH1(id + 3, gap_lenght);
}
else {
analysisManager->FillH1(id + 2, absoHit->GetTrackLength());
analysisManager->FillH1(id + 3, gapHit->GetTrackLength());
}
// fill ntuple and pos histo
analysisManager->FillNtupleDColumn(i, id_tup, absoHit->GetEdep());
analysisManager->FillNtupleDColumn(i, id_tup + 1, gapHit->GetEdep());
analysisManager->FillNtupleDColumn(i, id_tup + 2, absoHit->GetTrackLength());
analysisManager->FillNtupleDColumn(i, id_tup + 3, gapHit->GetTrackLength());
if (gapHit->GetPos().empty() == false) {
for (int j=0; j<(int)gapHit->GetPos().size(); ++j) {
analysisManager->FillH1(id + 4, std::sqrt(std::pow(gapHit->GetPos()[j].x(),2)+std::pow(gapHit->GetPos()[j].y(),2)));
analysisManager->FillH2(i, gapHit->GetPos()[j].x(), gapHit->GetPos()[j].y());
analysisManager->FillNtupleDColumn(i, id_tup + 4, std::sqrt(std::pow(gapHit->GetPos()[j].x(),2)+std::pow(gapHit->GetPos()[j].y(),2)));
}
id += 5;
analysisManager->AddNtupleRow(i);
}
}
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
|
ld heron(int a, int b, int c){
ld s = (a+b+c)/2.0;
return sqrtl(s*(s-a)*(s-b)*(s-c));
}
ld heron(int a, int b, int c, int d){
ld s = (a+b+c+d)/2.0;
return sqrtl((s-a)*(s-b)*(s-c)*(s-d));
}
|
/***********************************************************************
!!!!!! DO NOT MODIFY !!!!!!
GacGen.exe Resource.xml
This file is generated by Workflow compiler
https://github.com/vczh-libraries
***********************************************************************/
#ifndef VCZH_WORKFLOW_COMPILER_GENERATED_DEMOPARTIALCLASSES
#define VCZH_WORKFLOW_COMPILER_GENERATED_DEMOPARTIALCLASSES
#include "GacUI.h"
#if defined( _MSC_VER)
#pragma warning(push)
#pragma warning(disable:4250)
#elif defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wparentheses-equality"
#elif defined(__GNUC__)
#pragma GCC diagnostic push
#endif
namespace vl_workflow_global
{
struct __vwsnf10_Demo_demo_SharedSizeItemTemplateConstructor___vwsn_demo_SharedSizeItemTemplate_Initialize_;
struct __vwsnf11_Demo_demo_SharedSizeTextItemTemplateConstructor___vwsn_demo_SharedSizeTextItemTemplate_Initialize_;
struct __vwsnf12_Demo_demo_SharedSizeTextItemTemplateConstructor___vwsn_demo_SharedSizeTextItemTemplate_Initialize_;
struct __vwsnf13_Demo_demo_SharedSizeTextItemTemplateConstructor___vwsn_demo_SharedSizeTextItemTemplate_Initialize_;
struct __vwsnf1_Demo_demo_MainWindowConstructor___vwsn_demo_MainWindow_Initialize_;
struct __vwsnf2_Demo_demo_MainWindowConstructor___vwsn_demo_MainWindow_Initialize_;
struct __vwsnf3_Demo_demo_MainWindowConstructor___vwsn_demo_MainWindow_Initialize_;
struct __vwsnf4_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize_;
struct __vwsnf5_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize_;
struct __vwsnf6_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize_;
struct __vwsnf7_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize_;
struct __vwsnf8_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize_;
struct __vwsnf9_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize_;
class __vwsnc1_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize__vl_reflection_description_IValueSubscription;
class __vwsnc2_Demo_demo_SharedSizeItemTemplateConstructor___vwsn_demo_SharedSizeItemTemplate_Initialize__vl_reflection_description_IValueSubscription;
class __vwsnc3_Demo_demo_SharedSizeTextItemTemplateConstructor___vwsn_demo_SharedSizeTextItemTemplate_Initialize__vl_reflection_description_IValueSubscription;
class __vwsnc4_Demo_demo_SharedSizeTextItemTemplateConstructor___vwsn_demo_SharedSizeTextItemTemplate_Initialize__vl_reflection_description_IValueSubscription;
class __vwsnc5_Demo_demo_SharedSizeTextItemTemplateConstructor___vwsn_demo_SharedSizeTextItemTemplate_Initialize__vl_reflection_description_IValueSubscription;
}
namespace demo
{
class EnglishNumbersControllerConstructor;
class EnglishNumbersController;
class EnglishNumbersControllerTabPageConstructor;
class EnglishNumbersControllerTabPage;
class MainWindowConstructor;
class MainWindow;
class MyTextItem;
class SharedSizeItemTemplateConstructor;
class SharedSizeItemTemplate;
class SharedSizeTextItemTemplateConstructor;
class SharedSizeTextItemTemplate;
class EnglishNumbersControllerConstructor : public ::vl::Object, public ::vl::reflection::Description<EnglishNumbersControllerConstructor>
{
friend class ::vl_workflow_global::__vwsnc1_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize__vl_reflection_description_IValueSubscription;
friend struct ::vl_workflow_global::__vwsnf4_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize_;
friend struct ::vl_workflow_global::__vwsnf5_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize_;
friend struct ::vl_workflow_global::__vwsnf6_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize_;
friend struct ::vl_workflow_global::__vwsnf7_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize_;
friend struct ::vl_workflow_global::__vwsnf8_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize_;
friend struct ::vl_workflow_global::__vwsnf9_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize_;
#ifdef VCZH_DESCRIPTABLEOBJECT_WITH_METADATA
friend struct ::vl::reflection::description::CustomTypeDescriptorSelector<EnglishNumbersControllerConstructor>;
#endif
protected:
::demo::EnglishNumbersController* self;
::vl::presentation::controls::GuiControl* __vwsn_precompile_0;
::vl::presentation::compositions::GuiStackComposition* __vwsn_precompile_1;
::vl::presentation::compositions::GuiStackItemComposition* __vwsn_precompile_2;
::vl::presentation::controls::GuiButton* __vwsn_precompile_3;
::vl::presentation::compositions::GuiBoundsComposition* __vwsn_precompile_4;
::vl::presentation::compositions::GuiStackItemComposition* __vwsn_precompile_5;
::vl::presentation::controls::GuiButton* __vwsn_precompile_6;
::vl::presentation::compositions::GuiBoundsComposition* __vwsn_precompile_7;
::vl::presentation::compositions::GuiStackItemComposition* __vwsn_precompile_8;
::vl::presentation::controls::GuiButton* __vwsn_precompile_9;
::vl::presentation::compositions::GuiBoundsComposition* __vwsn_precompile_10;
::vl::presentation::compositions::GuiStackItemComposition* __vwsn_precompile_11;
::vl::presentation::controls::GuiButton* __vwsn_precompile_12;
::vl::presentation::compositions::GuiBoundsComposition* __vwsn_precompile_13;
::vl::presentation::compositions::GuiStackItemComposition* __vwsn_precompile_14;
::vl::presentation::controls::GuiButton* __vwsn_precompile_15;
::vl::presentation::compositions::GuiBoundsComposition* __vwsn_precompile_16;
::vl::presentation::compositions::GuiBoundsComposition* __vwsn_precompile_17;
::vl::presentation::compositions::GuiGraphicsComposition* __vwsn_precompile_18;
void __vwsn_demo_EnglishNumbersController_Initialize(::demo::EnglishNumbersController* __vwsn_this_);
public:
EnglishNumbersControllerConstructor();
};
class EnglishNumbersController : public ::vl::presentation::controls::GuiCustomControl, public ::demo::EnglishNumbersControllerConstructor, public ::vl::reflection::Description<EnglishNumbersController>
{
friend class ::demo::EnglishNumbersControllerConstructor;
friend class ::vl_workflow_global::__vwsnc1_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize__vl_reflection_description_IValueSubscription;
friend struct ::vl_workflow_global::__vwsnf4_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize_;
friend struct ::vl_workflow_global::__vwsnf5_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize_;
friend struct ::vl_workflow_global::__vwsnf6_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize_;
friend struct ::vl_workflow_global::__vwsnf7_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize_;
friend struct ::vl_workflow_global::__vwsnf8_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize_;
friend struct ::vl_workflow_global::__vwsnf9_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize_;
#ifdef VCZH_DESCRIPTABLEOBJECT_WITH_METADATA
friend struct ::vl::reflection::description::CustomTypeDescriptorSelector<EnglishNumbersController>;
#endif
private:
::vl::vint counter;
public:
::vl::Ptr<::vl::reflection::description::IValueObservableList> __vwsn_prop_ItemsToBind;
::vl::Ptr<::vl::reflection::description::IValueObservableList> GetItemsToBind();
void SetItemsToBind(::vl::Ptr<::vl::reflection::description::IValueObservableList> __vwsn_value_);
private:
::vl::WString ToText_1to9(::vl::vint i);
::vl::WString ToText_11to19(::vl::vint i);
::vl::WString NumberToText_1To99(::vl::vint i);
::vl::WString NumberToText_0to999(::vl::vint i);
::vl::WString NumberToText(::vl::vint i);
public:
EnglishNumbersController();
~EnglishNumbersController();
};
class EnglishNumbersControllerTabPageConstructor : public ::vl::Object, public ::vl::reflection::Description<EnglishNumbersControllerTabPageConstructor>
{
#ifdef VCZH_DESCRIPTABLEOBJECT_WITH_METADATA
friend struct ::vl::reflection::description::CustomTypeDescriptorSelector<EnglishNumbersControllerTabPageConstructor>;
#endif
protected:
::vl::presentation::compositions::GuiCellComposition* content;
::demo::EnglishNumbersController* controller;
::demo::EnglishNumbersControllerTabPage* __vwsn_precompile_0;
::vl::presentation::compositions::GuiTableComposition* __vwsn_precompile_1;
::vl::presentation::compositions::GuiCellComposition* __vwsn_precompile_2;
::vl::presentation::compositions::GuiBoundsComposition* __vwsn_precompile_3;
void __vwsn_demo_EnglishNumbersControllerTabPage_Initialize(::demo::EnglishNumbersControllerTabPage* __vwsn_this_);
public:
EnglishNumbersControllerTabPageConstructor();
};
class EnglishNumbersControllerTabPage : public ::vl::presentation::controls::GuiTabPage, public ::demo::EnglishNumbersControllerTabPageConstructor, public ::vl::reflection::Description<EnglishNumbersControllerTabPage>
{
friend class ::demo::EnglishNumbersControllerTabPageConstructor;
#ifdef VCZH_DESCRIPTABLEOBJECT_WITH_METADATA
friend struct ::vl::reflection::description::CustomTypeDescriptorSelector<EnglishNumbersControllerTabPage>;
#endif
public:
::vl::Ptr<::vl::reflection::description::IValueObservableList> __vwsn_prop_ItemsToBind;
::vl::Ptr<::vl::reflection::description::IValueObservableList> GetItemsToBind();
void SetItemsToBind(::vl::Ptr<::vl::reflection::description::IValueObservableList> __vwsn_value_);
::vl::presentation::compositions::GuiGraphicsComposition* __vwsn_prop_ContentComposition;
::vl::presentation::compositions::GuiGraphicsComposition* GetContentComposition();
void SetContentComposition(::vl::presentation::compositions::GuiGraphicsComposition* __vwsn_value_);
EnglishNumbersControllerTabPage();
void __vwsn_instance_ctor_();
~EnglishNumbersControllerTabPage();
};
class MainWindowConstructor : public ::vl::Object, public ::vl::reflection::Description<MainWindowConstructor>
{
friend struct ::vl_workflow_global::__vwsnf1_Demo_demo_MainWindowConstructor___vwsn_demo_MainWindow_Initialize_;
friend struct ::vl_workflow_global::__vwsnf2_Demo_demo_MainWindowConstructor___vwsn_demo_MainWindow_Initialize_;
friend struct ::vl_workflow_global::__vwsnf3_Demo_demo_MainWindowConstructor___vwsn_demo_MainWindow_Initialize_;
#ifdef VCZH_DESCRIPTABLEOBJECT_WITH_METADATA
friend struct ::vl::reflection::description::CustomTypeDescriptorSelector<MainWindowConstructor>;
#endif
protected:
::demo::EnglishNumbersControllerTabPage* sharedSizeListTabPage;
::demo::EnglishNumbersControllerTabPage* sharedSizeFlowTabPage;
::demo::MainWindow* __vwsn_precompile_0;
::vl::presentation::controls::GuiTab* __vwsn_precompile_1;
::vl::presentation::compositions::GuiBoundsComposition* __vwsn_precompile_2;
::vl::presentation::compositions::GuiGraphicsComposition* __vwsn_precompile_3;
::vl::presentation::compositions::GuiSharedSizeRootComposition* __vwsn_precompile_4;
::vl::presentation::controls::GuiBindableTextList* __vwsn_precompile_5;
::vl::presentation::compositions::GuiBoundsComposition* __vwsn_precompile_6;
::vl::presentation::compositions::GuiGraphicsComposition* __vwsn_precompile_7;
::vl::presentation::controls::GuiScrollContainer* __vwsn_precompile_8;
::vl::presentation::compositions::GuiSharedSizeRootComposition* __vwsn_precompile_9;
::vl::presentation::compositions::GuiRepeatFlowComposition* __vwsn_precompile_10;
::vl::presentation::compositions::GuiBoundsComposition* __vwsn_precompile_11;
void __vwsn_demo_MainWindow_Initialize(::demo::MainWindow* __vwsn_this_);
public:
MainWindowConstructor();
};
class MainWindow : public ::vl::presentation::controls::GuiWindow, public ::demo::MainWindowConstructor, public ::vl::reflection::Description<MainWindow>
{
friend class ::demo::MainWindowConstructor;
friend struct ::vl_workflow_global::__vwsnf1_Demo_demo_MainWindowConstructor___vwsn_demo_MainWindow_Initialize_;
friend struct ::vl_workflow_global::__vwsnf2_Demo_demo_MainWindowConstructor___vwsn_demo_MainWindow_Initialize_;
friend struct ::vl_workflow_global::__vwsnf3_Demo_demo_MainWindowConstructor___vwsn_demo_MainWindow_Initialize_;
#ifdef VCZH_DESCRIPTABLEOBJECT_WITH_METADATA
friend struct ::vl::reflection::description::CustomTypeDescriptorSelector<MainWindow>;
#endif
public:
MainWindow();
~MainWindow();
};
class MyTextItem : public ::vl::Object, public ::vl::reflection::Description<MyTextItem>
{
#ifdef VCZH_DESCRIPTABLEOBJECT_WITH_METADATA
friend struct ::vl::reflection::description::CustomTypeDescriptorSelector<MyTextItem>;
#endif
private:
::vl::WString __vwsn_prop_Name;
public:
::vl::WString GetName();
void SetName(const ::vl::WString& __vwsn_value_);
private:
bool __vwsn_prop_Checked;
public:
bool GetChecked();
void SetChecked(bool __vwsn_value_);
MyTextItem();
};
class SharedSizeItemTemplateConstructor : public ::vl::Object, public ::vl::reflection::Description<SharedSizeItemTemplateConstructor>
{
friend class ::vl_workflow_global::__vwsnc2_Demo_demo_SharedSizeItemTemplateConstructor___vwsn_demo_SharedSizeItemTemplate_Initialize__vl_reflection_description_IValueSubscription;
friend struct ::vl_workflow_global::__vwsnf10_Demo_demo_SharedSizeItemTemplateConstructor___vwsn_demo_SharedSizeItemTemplate_Initialize_;
#ifdef VCZH_DESCRIPTABLEOBJECT_WITH_METADATA
friend struct ::vl::reflection::description::CustomTypeDescriptorSelector<SharedSizeItemTemplateConstructor>;
#endif
protected:
::vl::Ptr<::demo::MyTextItem> ViewModel;
::demo::SharedSizeItemTemplate* __vwsn_precompile_0;
::vl::presentation::compositions::GuiSharedSizeItemComposition* __vwsn_precompile_1;
::vl::presentation::controls::GuiButton* __vwsn_precompile_2;
::vl::presentation::compositions::GuiBoundsComposition* __vwsn_precompile_3;
void __vwsn_demo_SharedSizeItemTemplate_Initialize(::demo::SharedSizeItemTemplate* __vwsn_this_);
public:
SharedSizeItemTemplateConstructor();
};
class SharedSizeItemTemplate : public ::vl::presentation::templates::GuiControlTemplate, public ::demo::SharedSizeItemTemplateConstructor, public ::vl::reflection::Description<SharedSizeItemTemplate>
{
friend class ::demo::SharedSizeItemTemplateConstructor;
friend class ::vl_workflow_global::__vwsnc2_Demo_demo_SharedSizeItemTemplateConstructor___vwsn_demo_SharedSizeItemTemplate_Initialize__vl_reflection_description_IValueSubscription;
friend struct ::vl_workflow_global::__vwsnf10_Demo_demo_SharedSizeItemTemplateConstructor___vwsn_demo_SharedSizeItemTemplate_Initialize_;
#ifdef VCZH_DESCRIPTABLEOBJECT_WITH_METADATA
friend struct ::vl::reflection::description::CustomTypeDescriptorSelector<SharedSizeItemTemplate>;
#endif
public:
::vl::Ptr<::demo::MyTextItem> __vwsn_parameter_ViewModel;
::vl::Ptr<::demo::MyTextItem> GetViewModel();
SharedSizeItemTemplate(::vl::Ptr<::demo::MyTextItem> __vwsn_ctor_parameter_ViewModel);
~SharedSizeItemTemplate();
};
class SharedSizeTextItemTemplateConstructor : public ::vl::Object, public ::vl::reflection::Description<SharedSizeTextItemTemplateConstructor>
{
friend class ::vl_workflow_global::__vwsnc3_Demo_demo_SharedSizeTextItemTemplateConstructor___vwsn_demo_SharedSizeTextItemTemplate_Initialize__vl_reflection_description_IValueSubscription;
friend class ::vl_workflow_global::__vwsnc4_Demo_demo_SharedSizeTextItemTemplateConstructor___vwsn_demo_SharedSizeTextItemTemplate_Initialize__vl_reflection_description_IValueSubscription;
friend class ::vl_workflow_global::__vwsnc5_Demo_demo_SharedSizeTextItemTemplateConstructor___vwsn_demo_SharedSizeTextItemTemplate_Initialize__vl_reflection_description_IValueSubscription;
friend struct ::vl_workflow_global::__vwsnf11_Demo_demo_SharedSizeTextItemTemplateConstructor___vwsn_demo_SharedSizeTextItemTemplate_Initialize_;
friend struct ::vl_workflow_global::__vwsnf12_Demo_demo_SharedSizeTextItemTemplateConstructor___vwsn_demo_SharedSizeTextItemTemplate_Initialize_;
friend struct ::vl_workflow_global::__vwsnf13_Demo_demo_SharedSizeTextItemTemplateConstructor___vwsn_demo_SharedSizeTextItemTemplate_Initialize_;
#ifdef VCZH_DESCRIPTABLEOBJECT_WITH_METADATA
friend struct ::vl::reflection::description::CustomTypeDescriptorSelector<SharedSizeTextItemTemplateConstructor>;
#endif
protected:
::vl::Ptr<::demo::MyTextItem> ViewModel;
::demo::SharedSizeTextItemTemplate* self;
::vl::presentation::compositions::GuiSharedSizeItemComposition* __vwsn_precompile_0;
::vl::Ptr<::vl::presentation::elements::GuiSolidLabelElement> __vwsn_precompile_1;
void __vwsn_demo_SharedSizeTextItemTemplate_Initialize(::demo::SharedSizeTextItemTemplate* __vwsn_this_);
public:
SharedSizeTextItemTemplateConstructor();
};
class SharedSizeTextItemTemplate : public ::vl::presentation::templates::GuiTextListItemTemplate, public ::demo::SharedSizeTextItemTemplateConstructor, public ::vl::reflection::Description<SharedSizeTextItemTemplate>
{
friend class ::demo::SharedSizeTextItemTemplateConstructor;
friend class ::vl_workflow_global::__vwsnc3_Demo_demo_SharedSizeTextItemTemplateConstructor___vwsn_demo_SharedSizeTextItemTemplate_Initialize__vl_reflection_description_IValueSubscription;
friend class ::vl_workflow_global::__vwsnc4_Demo_demo_SharedSizeTextItemTemplateConstructor___vwsn_demo_SharedSizeTextItemTemplate_Initialize__vl_reflection_description_IValueSubscription;
friend class ::vl_workflow_global::__vwsnc5_Demo_demo_SharedSizeTextItemTemplateConstructor___vwsn_demo_SharedSizeTextItemTemplate_Initialize__vl_reflection_description_IValueSubscription;
friend struct ::vl_workflow_global::__vwsnf11_Demo_demo_SharedSizeTextItemTemplateConstructor___vwsn_demo_SharedSizeTextItemTemplate_Initialize_;
friend struct ::vl_workflow_global::__vwsnf12_Demo_demo_SharedSizeTextItemTemplateConstructor___vwsn_demo_SharedSizeTextItemTemplate_Initialize_;
friend struct ::vl_workflow_global::__vwsnf13_Demo_demo_SharedSizeTextItemTemplateConstructor___vwsn_demo_SharedSizeTextItemTemplate_Initialize_;
#ifdef VCZH_DESCRIPTABLEOBJECT_WITH_METADATA
friend struct ::vl::reflection::description::CustomTypeDescriptorSelector<SharedSizeTextItemTemplate>;
#endif
public:
::vl::Ptr<::demo::MyTextItem> __vwsn_parameter_ViewModel;
::vl::Ptr<::demo::MyTextItem> GetViewModel();
SharedSizeTextItemTemplate(::vl::Ptr<::demo::MyTextItem> __vwsn_ctor_parameter_ViewModel);
~SharedSizeTextItemTemplate();
};
}
/***********************************************************************
Global Variables and Functions
***********************************************************************/
namespace vl_workflow_global
{
class Demo
{
public:
static Demo& Instance();
};
/***********************************************************************
Closures
***********************************************************************/
struct __vwsnf10_Demo_demo_SharedSizeItemTemplateConstructor___vwsn_demo_SharedSizeItemTemplate_Initialize_
{
::demo::SharedSizeItemTemplateConstructor* __vwsnthis_0;
__vwsnf10_Demo_demo_SharedSizeItemTemplateConstructor___vwsn_demo_SharedSizeItemTemplate_Initialize_(::demo::SharedSizeItemTemplateConstructor* __vwsnctorthis_0);
void operator()(const ::vl::reflection::description::Value& __vwsn_value_) const;
};
struct __vwsnf11_Demo_demo_SharedSizeTextItemTemplateConstructor___vwsn_demo_SharedSizeTextItemTemplate_Initialize_
{
::demo::SharedSizeTextItemTemplateConstructor* __vwsnthis_0;
__vwsnf11_Demo_demo_SharedSizeTextItemTemplateConstructor___vwsn_demo_SharedSizeTextItemTemplate_Initialize_(::demo::SharedSizeTextItemTemplateConstructor* __vwsnctorthis_0);
void operator()(const ::vl::reflection::description::Value& __vwsn_value_) const;
};
struct __vwsnf12_Demo_demo_SharedSizeTextItemTemplateConstructor___vwsn_demo_SharedSizeTextItemTemplate_Initialize_
{
::demo::SharedSizeTextItemTemplateConstructor* __vwsnthis_0;
__vwsnf12_Demo_demo_SharedSizeTextItemTemplateConstructor___vwsn_demo_SharedSizeTextItemTemplate_Initialize_(::demo::SharedSizeTextItemTemplateConstructor* __vwsnctorthis_0);
void operator()(const ::vl::reflection::description::Value& __vwsn_value_) const;
};
struct __vwsnf13_Demo_demo_SharedSizeTextItemTemplateConstructor___vwsn_demo_SharedSizeTextItemTemplate_Initialize_
{
::demo::SharedSizeTextItemTemplateConstructor* __vwsnthis_0;
__vwsnf13_Demo_demo_SharedSizeTextItemTemplateConstructor___vwsn_demo_SharedSizeTextItemTemplate_Initialize_(::demo::SharedSizeTextItemTemplateConstructor* __vwsnctorthis_0);
void operator()(const ::vl::reflection::description::Value& __vwsn_value_) const;
};
struct __vwsnf1_Demo_demo_MainWindowConstructor___vwsn_demo_MainWindow_Initialize_
{
::demo::MainWindowConstructor* __vwsnthis_0;
__vwsnf1_Demo_demo_MainWindowConstructor___vwsn_demo_MainWindow_Initialize_(::demo::MainWindowConstructor* __vwsnctorthis_0);
::vl::WString operator()(const ::vl::reflection::description::Value& __vwsn_item_) const;
};
struct __vwsnf2_Demo_demo_MainWindowConstructor___vwsn_demo_MainWindow_Initialize_
{
::demo::MainWindowConstructor* __vwsnthis_0;
__vwsnf2_Demo_demo_MainWindowConstructor___vwsn_demo_MainWindow_Initialize_(::demo::MainWindowConstructor* __vwsnctorthis_0);
::vl::presentation::templates::GuiListItemTemplate* operator()(const ::vl::reflection::description::Value& __vwsn_viewModel_) const;
};
struct __vwsnf3_Demo_demo_MainWindowConstructor___vwsn_demo_MainWindow_Initialize_
{
::demo::MainWindowConstructor* __vwsnthis_0;
__vwsnf3_Demo_demo_MainWindowConstructor___vwsn_demo_MainWindow_Initialize_(::demo::MainWindowConstructor* __vwsnctorthis_0);
::vl::presentation::templates::GuiTemplate* operator()(const ::vl::reflection::description::Value& __vwsn_viewModel_) const;
};
struct __vwsnf4_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize_
{
::demo::EnglishNumbersControllerConstructor* __vwsnthis_0;
__vwsnf4_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize_(::demo::EnglishNumbersControllerConstructor* __vwsnctorthis_0);
void operator()(::vl::presentation::compositions::GuiGraphicsComposition* sender, ::vl::presentation::compositions::GuiEventArgs* arguments) const;
};
struct __vwsnf5_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize_
{
::demo::EnglishNumbersControllerConstructor* __vwsnthis_0;
__vwsnf5_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize_(::demo::EnglishNumbersControllerConstructor* __vwsnctorthis_0);
void operator()(::vl::presentation::compositions::GuiGraphicsComposition* sender, ::vl::presentation::compositions::GuiEventArgs* arguments) const;
};
struct __vwsnf6_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize_
{
::demo::EnglishNumbersControllerConstructor* __vwsnthis_0;
__vwsnf6_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize_(::demo::EnglishNumbersControllerConstructor* __vwsnctorthis_0);
void operator()(::vl::presentation::compositions::GuiGraphicsComposition* sender, ::vl::presentation::compositions::GuiEventArgs* arguments) const;
};
struct __vwsnf7_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize_
{
::demo::EnglishNumbersControllerConstructor* __vwsnthis_0;
__vwsnf7_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize_(::demo::EnglishNumbersControllerConstructor* __vwsnctorthis_0);
void operator()(::vl::presentation::compositions::GuiGraphicsComposition* sender, ::vl::presentation::compositions::GuiEventArgs* arguments) const;
};
struct __vwsnf8_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize_
{
::demo::EnglishNumbersControllerConstructor* __vwsnthis_0;
__vwsnf8_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize_(::demo::EnglishNumbersControllerConstructor* __vwsnctorthis_0);
void operator()(::vl::presentation::compositions::GuiGraphicsComposition* sender, ::vl::presentation::compositions::GuiEventArgs* arguments) const;
};
struct __vwsnf9_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize_
{
::demo::EnglishNumbersControllerConstructor* __vwsnthis_0;
__vwsnf9_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize_(::demo::EnglishNumbersControllerConstructor* __vwsnctorthis_0);
void operator()(const ::vl::reflection::description::Value& __vwsn_value_) const;
};
class __vwsnc1_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize__vl_reflection_description_IValueSubscription : public ::vl::Object, public virtual ::vl::reflection::description::IValueSubscription
{
public:
::demo::EnglishNumbersControllerConstructor* __vwsnthis_0;
__vwsnc1_Demo_demo_EnglishNumbersControllerConstructor___vwsn_demo_EnglishNumbersController_Initialize__vl_reflection_description_IValueSubscription(::demo::EnglishNumbersControllerConstructor* __vwsnctorthis_0);
::demo::EnglishNumbersController* __vwsn_bind_cache_0 = nullptr;
::vl::Ptr<::vl::reflection::description::IEventHandler> __vwsn_bind_handler_0_0;
bool __vwsn_bind_opened_ = false;
bool __vwsn_bind_closed_ = false;
void __vwsn_bind_activator_();
void __vwsn_bind_callback_0_0(::vl::presentation::compositions::GuiGraphicsComposition* __vwsn_bind_callback_argument_0, ::vl::presentation::compositions::GuiEventArgs* __vwsn_bind_callback_argument_1);
bool Open() override;
bool Update() override;
bool Close() override;
};
class __vwsnc2_Demo_demo_SharedSizeItemTemplateConstructor___vwsn_demo_SharedSizeItemTemplate_Initialize__vl_reflection_description_IValueSubscription : public ::vl::Object, public virtual ::vl::reflection::description::IValueSubscription
{
public:
::demo::SharedSizeItemTemplateConstructor* __vwsnthis_0;
__vwsnc2_Demo_demo_SharedSizeItemTemplateConstructor___vwsn_demo_SharedSizeItemTemplate_Initialize__vl_reflection_description_IValueSubscription(::demo::SharedSizeItemTemplateConstructor* __vwsnctorthis_0);
bool __vwsn_bind_opened_ = false;
bool __vwsn_bind_closed_ = false;
void __vwsn_bind_activator_();
bool Open() override;
bool Update() override;
bool Close() override;
};
class __vwsnc3_Demo_demo_SharedSizeTextItemTemplateConstructor___vwsn_demo_SharedSizeTextItemTemplate_Initialize__vl_reflection_description_IValueSubscription : public ::vl::Object, public virtual ::vl::reflection::description::IValueSubscription
{
public:
::demo::SharedSizeTextItemTemplateConstructor* __vwsnthis_0;
__vwsnc3_Demo_demo_SharedSizeTextItemTemplateConstructor___vwsn_demo_SharedSizeTextItemTemplate_Initialize__vl_reflection_description_IValueSubscription(::demo::SharedSizeTextItemTemplateConstructor* __vwsnctorthis_0);
bool __vwsn_bind_opened_ = false;
bool __vwsn_bind_closed_ = false;
void __vwsn_bind_activator_();
bool Open() override;
bool Update() override;
bool Close() override;
};
class __vwsnc4_Demo_demo_SharedSizeTextItemTemplateConstructor___vwsn_demo_SharedSizeTextItemTemplate_Initialize__vl_reflection_description_IValueSubscription : public ::vl::Object, public virtual ::vl::reflection::description::IValueSubscription
{
public:
::demo::SharedSizeTextItemTemplateConstructor* __vwsnthis_0;
__vwsnc4_Demo_demo_SharedSizeTextItemTemplateConstructor___vwsn_demo_SharedSizeTextItemTemplate_Initialize__vl_reflection_description_IValueSubscription(::demo::SharedSizeTextItemTemplateConstructor* __vwsnctorthis_0);
::demo::SharedSizeTextItemTemplate* __vwsn_bind_cache_0 = nullptr;
::vl::Ptr<::vl::reflection::description::IEventHandler> __vwsn_bind_handler_0_0;
bool __vwsn_bind_opened_ = false;
bool __vwsn_bind_closed_ = false;
void __vwsn_bind_activator_();
void __vwsn_bind_callback_0_0(::vl::presentation::compositions::GuiGraphicsComposition* __vwsn_bind_callback_argument_0, ::vl::presentation::compositions::GuiEventArgs* __vwsn_bind_callback_argument_1);
bool Open() override;
bool Update() override;
bool Close() override;
};
class __vwsnc5_Demo_demo_SharedSizeTextItemTemplateConstructor___vwsn_demo_SharedSizeTextItemTemplate_Initialize__vl_reflection_description_IValueSubscription : public ::vl::Object, public virtual ::vl::reflection::description::IValueSubscription
{
public:
::demo::SharedSizeTextItemTemplateConstructor* __vwsnthis_0;
__vwsnc5_Demo_demo_SharedSizeTextItemTemplateConstructor___vwsn_demo_SharedSizeTextItemTemplate_Initialize__vl_reflection_description_IValueSubscription(::demo::SharedSizeTextItemTemplateConstructor* __vwsnctorthis_0);
::demo::SharedSizeTextItemTemplate* __vwsn_bind_cache_0 = nullptr;
::vl::Ptr<::vl::reflection::description::IEventHandler> __vwsn_bind_handler_0_0;
bool __vwsn_bind_opened_ = false;
bool __vwsn_bind_closed_ = false;
void __vwsn_bind_activator_();
void __vwsn_bind_callback_0_0(::vl::presentation::compositions::GuiGraphicsComposition* __vwsn_bind_callback_argument_0, ::vl::presentation::compositions::GuiEventArgs* __vwsn_bind_callback_argument_1);
bool Open() override;
bool Update() override;
bool Close() override;
};
}
#if defined( _MSC_VER)
#pragma warning(pop)
#elif defined(__clang__)
#pragma clang diagnostic pop
#elif defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2002 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#ifndef DOM_TREEWALKER_H
#define DOM_TREEWALKER_H
#ifdef DOM2_TRAVERSAL
#include "modules/dom/src/domtraversal/traversal.h"
#include "modules/dom/src/domobj.h"
class DOM_TreeWalker_State;
class DOM_TreeWalker
: public DOM_Object,
public DOM_TraversalObject
{
protected:
DOM_TreeWalker();
DOM_Node *current_node;
DOM_Node *current_candidate;
DOM_Node *best_candidate;
DOM_TreeWalker_State *state;
public:
enum Operation
{
PARENT_NODE,
FIRST_CHILD,
LAST_CHILD,
PREVIOUS_SIBLING,
NEXT_SIBLING,
PREVIOUS_NODE,
NEXT_NODE
};
static OP_STATUS Make(DOM_TreeWalker *&node_iterator, DOM_EnvironmentImpl *environment, DOM_Node *root,
unsigned what_to_show, ES_Object *node_filter, BOOL entity_reference_expansion);
virtual ES_GetState GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime);
virtual ES_PutState PutName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime);
virtual BOOL IsA(int type) { return type == DOM_TYPE_TREEWALKER || DOM_Object::IsA(type); }
virtual void GCTrace();
DOM_DECLARE_FUNCTION_WITH_DATA(move); // parentNode, {first,last}Child, {next,previous}{Sibling,Node}
enum { FUNCTIONS_WITH_DATA_ARRAY_SIZE = 8 };
};
#endif // DOM2_TRAVERSAL
#endif // DOM_TREEWALKER_H
|
#include <iostream>
#include <cmath>
int main() {
long x = 600851475143;
long factor = 2;
long max_factor = sqrt(x);
while (x > factor && factor <= max_factor){
if (x % factor == 0) {
x = x/factor;
}else{
factor++;
}
}
std::cout << factor << std::endl;
}
|
#include <bits/stdc++.h>
using namespace std;
int row[8], TC, a, b, lineCounter;
bool place(int r, int c);
void backtrack(int c);
int main()
{
scanf("%d", &TC);
while(TC--)
{
scanf("%d %d", &a, &b);
a--; b--;
memset(row, 0, sizeof(row)); lineCounter = 0;
printf("SOLN COLUMN\n");
printf(" # 1 2 3 4 5 6 7 8\n\n");
backtrack(0);
if(TC)
printf("\n");
}
return 0;
}
void backtrack(int c)
{
if(c == 8 && row[b] == a)
{
printf("%2d %d", ++lineCounter, row[0] + 1);
for(int j = 1;j < 8;j++)
printf(" %d", row[j] + 1);
putchar('\n');
}
for(int r = 0;r < 8;r++)
if(place(r, c))
{
row[c] = r;
backtrack(c + 1);
}
}
bool place(int r, int c)
{
for(int prev = 0; prev < c;prev++)
if(row[prev] == r || (abs(row[prev] - r) == abs(prev - c)))
return false;
return true;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 2007 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
/** \file
*
* \brief Include file for OpMemUpperTen object
*
* You must include this file if you want to use the OpMemUpperTen object
* used to rank allocation sites.
*
* \author Morten Rolland, mortenro@opera.com
*/
#ifndef MEMORY_UPPERTEN_H
#define MEMORY_UPPERTEN_H
class OpMemUpperTen
{
public:
OpMemUpperTen(int size = 10);
~OpMemUpperTen(void);
void Add(UINTPTR ptr, size_t arg2, int arg3);
void Show(const char* title, const char* format);
private:
int size;
int total_bytes;
int total_count;
BOOL valid;
UINTPTR* ptr1;
size_t* arg2;
int* arg3;
};
#endif // MEMORY_UPPERTEN_H
|
#include "PageManage.h"
CPageManage * CPageManage::GetInstance()
{
static CPageManage page;
return &page;
}
map<PAGE_TYPE, PAGEINFO>& CPageManage::GetPageInfo()
{
return m_sPageInfo;
}
PAGE_TYPE CPageManage::GetCurPage()
{
return m_eCurrentShowPage;
}
void CPageManage::ShowPage(PAGE_TYPE ePageType, bool bIsExit, LPVOID lParam)
{
if (ePageType == m_eCurrentShowPage
|| ePageType == PAGE_BEGIN
|| ePageType == PAGE_END)
return;
if (bIsExit)
{
m_ePrevShowPage = m_eCurrentShowPage;
m_eCurrentShowPage = ePageType;
return;
}
auto &pPageBase = m_sPageInfo[ePageType].pPageBase;
if (pPageBase)
return;
if (m_sPageInfo[ePageType].eParentPage != PAGE_BEGIN
&& m_sPageInfo[ePageType].eParentPage != PAGE_END) //如果有父窗口
{
if (NULL == m_sPageInfo[m_sPageInfo[ePageType].eParentPage].pPageBase)
{
//LOG("ShowPage parentPage...\n");
this->ShowPage(m_sPageInfo[ePageType].eParentPage); //父窗口未创建 则先创建父窗口
m_eCurrentShowPage = m_ePrevShowPage;
}
}
if (this->GetPageInfo()[PAGE_MAIN].pPageBase != NULL)
{
CMainUI* pMainUI = (CMainUI*)this->GetPageInfo()[PAGE_MAIN].pPageBase;
pMainUI->SetEnabledBtn(false);
}
m_ePrevShowPage = m_eCurrentShowPage;
//this->ClosePage(m_ePrevShowPage);
m_eCurrentShowPage = ePageType;
switch (ePageType)
{
case PAGE_MAIN:
pPageBase = new CMainUI();
break;
case PAGE_SERVICECONFIG:
pPageBase = new CServiceConfigUI();
break;
case PAGE_OTHER:
pPageBase = new COtherUI();
break;
case PAGE_END:
break;
default:
break;
}
if(pPageBase)
pPageBase->InitUI(bIsExit,lParam);
}
HWND CPageManage::GetCurHWND()
{
if (m_sPageInfo.find(m_eCurrentShowPage) == m_sPageInfo.end())
return NULL;
if (m_sPageInfo[m_eCurrentShowPage].pPageBase)
return m_sPageInfo[m_eCurrentShowPage].pPageBase->GetHWND();
else
return NULL;
}
HWND CPageManage::GetPreHWND()
{
if (m_sPageInfo.find(m_ePrevShowPage) == m_sPageInfo.end())
return NULL;
if (m_sPageInfo[m_ePrevShowPage].pPageBase)
return m_sPageInfo[m_ePrevShowPage].pPageBase->GetHWND();
else
return NULL;
}
void CPageManage::ClosePage(PAGE_TYPE ePageType)
{
if (m_sPageInfo.find(ePageType) == m_sPageInfo.end())
return;
if (m_sPageInfo[ePageType].pPageBase)
{
m_sPageInfo[ePageType].pPageBase->Close();
m_sPageInfo[ePageType].pPageBase = NULL;
}
}
void CPageManage::Reset()
{
for (size_t i = PAGE_BEGIN; i < PAGE_END; ++i)
{
if (m_sPageInfo[(PAGE_TYPE)i].pPageBase)
{
m_sPageInfo[(PAGE_TYPE)i].pPageBase->Close();
m_sPageInfo[(PAGE_TYPE)i].pPageBase = NULL;
}
}
LOG("CPageManage::Reset()...\n");
}
CPageManage::CPageManage()
{
for (int i = PAGE_BEGIN; i < PAGE_END; ++i)
{
InitPageInfo((PAGE_TYPE)i);
}
m_eCurrentShowPage = PAGE_BEGIN;
}
void CPageManage::InitPageInfo(PAGE_TYPE ePageType, CPageBaseUI * pPageBase)
{
wstring strXmlName = TEXT("");
wstring strPageName = TEXT("");
PAGE_TYPE eParentPage = PAGE_BEGIN;
switch (ePageType)
{
case PAGE_MAIN:
strXmlName = TEXT("MainUI.xml");
//strPageName = TEXT("配置工具");
strPageName = TEXT("Vastool");//modified by cdm,There are problems with Chinese coding
break;
case PAGE_SERVICECONFIG:
eParentPage = PAGE_MAIN;
strXmlName = TEXT("ServiceConfigUI.xml");
strPageName = TEXT("服务器配置");
break;
case PAGE_OTHER:
eParentPage = PAGE_MAIN;
strXmlName = TEXT("other.xml");
strPageName = TEXT("其他配置");
break;
default:
break;
}
m_sPageInfo[ePageType] = PAGEINFO(ePageType,strXmlName,strPageName,eParentPage,pPageBase);
}
__page_info::__page_info(PAGE_TYPE ePageType, wstring strXmlName, wstring strPageName, PAGE_TYPE eParentPage, CPageBaseUI * pPageBase)
{
this->ePageType = ePageType;
this->strXmlName = strXmlName;
this->strPageName = strPageName;
this->pPageBase = pPageBase;
this->eParentPage = eParentPage;
}
|
#include<bits/stdc++.h>
#define PI 3.14159
using namespace std;
int main()
{
double redius, volume;
cin>>redius;
volume = (4.0/3) * PI * (redius*redius*redius);
cout<<"VOLUME = "<<fixed<<setprecision(3)<<volume<<"\n";
return 0;
}
|
#pragma once
#include "ray.h"
#include "camera.h"
#include "random.h"
#include <shapes/shape_list.h>
glm::vec3 color(const Ray& r, ShapeList& world);
glm::vec3 get_random_sphere_unit_point();
double squared_length(const glm::vec3& v);
|
#include "Adafruit_TFTLCD_8bit_STM32.h"
#include "s6b.h"
void wrBus(int b) {
GPIOB->regs->BSRR =0xFF000000 + (b<<8);
digitalWrite(PA13,LOW); //WR
delayMicroseconds(10);
digitalWrite(PA13,HIGH);
}
void wrBus2(int d1, int d2) {
wrBus(d1);
wrBus(d2);
}
void wrBus3(int d1, int d2, int d3) {
wrBus(d1);
wrBus(d2);
wrBus(d3);
}
void s6b_begin(void)
{
digitalWrite(PB2,0); delay(10); digitalWrite(PB2,1);delay(10);
digitalWrite(PA15,0); //CS
digitalWrite(PA14,0); //RS
digitalWrite(PA13,1); //WR
wrBus(0x2c); delay(10); // LCDWriteCommand( 0x2C);delay_1ms(20);------set OTP mode off---------
wrBus(0xea); delay(10);
wrBus2(0x02,0x01);delay(10);//------set internal osc on---------LCDWriteCommand( 0x02);LCDWriteCommand( 0x01);
wrBus2(0x26,0x01);delay(20);//------booster1 on---------------LCDWriteCommand( 0x26);LCDWriteCommand( 0x01);
wrBus2(0x26,0x09);delay(20);//------booster1 on and amp on---------LCDWriteCommand( 0x26);LCDWriteCommand( 0x09);
wrBus2(0x26,0x0B);delay(20);//------booster2 on-------------LCDWriteCommand( 0x26); LCDWriteCommand( 0x0b);
wrBus2(0x26,0x0F);delay(20);//------booster3 on-------------LCDWriteCommand( 0x26);LCDWriteCommand( 0x0f);
//rotate 0x10 , adjust 0x42 together +3
//Register 0x10 DB0 also matters - see s6b33b3 pdf . For rotate, 0x40 bit 0x02 is in effect as well
wrBus2(0x10,0x22);delay(10);//------LCDWriteCommand( 0x10);LCDWriteCommand( 0x21);//FL side 0x22 L,0x25 R
wrBus2(0x20,0x01); delay(10);//------booster1 on---------------LCDWriteCommand( 0x20);LCDWriteCommand( 0x0A);
wrBus2(0x22,0x11); delay(10); //------bias set to 1/5 --------LCDWriteCommand( 0x22);LCDWriteCommand( 0x11);
wrBus2(0x24,0x11);delay(10);//------set clock fpck=fose/32(Normal)/fpck=fose/16(partial1)-------LCDWriteCommand( 0x24);LCDWriteCommand( 0x11);
wrBus2(0x28,0x01);delay(10);//------temp comp ratio -0.05%------ LCDWriteCommand( 0x28);LCDWriteCommand( 0x01);
wrBus2(0x2A,0xd0);delay(10);//------contrast1 set v1 to 3.757v max=4v----0x2A,CTRL1 LCDWriteCommand( 0x2a);LCDWriteCommand( 0xBB); //partial display mode 0
//wrBus2(0x2B,0x10);delay(10);//------contrast2 set v1 to 3.757v max=4v--------LCDWriteCommand( 0x2b);LCDWriteCommand( 0x20); //partial display mode 1
wrBus2(0x30,0x02);delay(10);//------GSM=00:65K color,DSG=0,SGF=0,SGP=01,SGM=0----- LCDWriteCommand( 0x30);LCDWriteCommand( 0x02);//09
wrBus2(0x32,0x0e);delay(10);//------row vector type=Diagonal ,INC=111-----LCDWriteCommand( 0x32);LCDWriteCommand( 0x0E);//0e
wrBus2(0x34,0x89);delay(10);//------frame set FIM=ON,FIP=1FRAME,N-BLOCK=9----- LCDWriteCommand( 0x34);LCDWriteCommand( 0x89);//cd
wrBus2(0x36,0x00);delay(10);//------Low frequency set off-------LCDWriteCommand( 0x36);LCDWriteCommand( 0x00);
wrBus2(0x45,0x00);delay(10);//------ram skip area set no skip------LCDWriteCommand( 0x45);LCDWriteCommand( 0x00);
wrBus2(0x40,0x00);delay(10);//------entry mode set : x addr incr, read modify write off--LCDWriteCommand( 0x40);LCDWriteCommand( 0x00);
wrBus3(0x42,0x02,161);delay(10);//------x address set from 00 to 159--------LCDWriteCommand( 0x42);LCDWriteCommand( 0x00);LCDWriteCommand( 0x9F);
wrBus3(0x43,0x00,127);delay(10);//------y address set from 00 to 127--------LCDWriteCommand( 0x43);LCDWriteCommand( 0x00);LCDWriteCommand( 0x7F);
wrBus2(0x55,0x00);delay(10);//------partial display mode off-------LCDWriteCommand( 0x55);LCDWriteCommand( 0x00);
wrBus2(0x53,0x00);delay(10);//------normal display---------LCDWriteCommand( 0x53);LCDWriteCommand( 0x00);
wrBus2(0x5A,0x00);delay(10);//-------Scroll start line Set------- LCDWriteCommand(0x5A);LCDWriteCommand( 0x00);
wrBus(0x51);delay(300); //------display on set--------delay_1ms(20);LCDWriteCommand( 0x51);
digitalWrite(PA15,1); //CS
digitalWrite(PA14,1); //RS
}
|
#include <cstdio>
#include <vector>
#include <cmath>
using namespace std;
vector <int> input;
int main(void)
{
int M, N;
scanf("%d %d", &M, &N);
int i,j;
for (i = 0; i <= 1000000; i++)
{
input.push_back(i);
}
input.at(1) = 0;
int num = 2;
int maxnum = input.at(input.size() - 1);
int len = sqrt(input.at(input.size() - 1));
for (i = 2; i <= len; i++)
{
num = input.at(i);
if (num == 0)
continue;
for (j = num * 2; j <= maxnum; j +=num)
{
input.at(j) = 0;
}
}
for (i = M; i <= N; i++)
{
if (input.at(i) != 0)
printf("%d\n", input.at(i));
}
}
|
// Copyright Lionel Miele-Herndon 2020
#include "BTService_ClearPlayerLocation.h"
UBTService_ClearPlayerLocation::UBTService_ClearPlayerLocation()
{
NodeName == TEXT("Clear Player Location");
}
void UBTService_ClearPlayerLocation::TickNode(UBehaviorTreeComponent &OwnerComp, uint8* NodeMemory, float DeltaSeconds)
{
Super::TickNode(OwnerComp, NodeMemory, DeltaSeconds);
//if this is not attached to an AI character fail
if (OwnerComp.GetAIOwner() == nullptr) return EBTNodeResult::Failed;
AShooterCharacter* Char = Cast<AShooterCharacter>(OwnerComp.GetAIOwner()->GetPawn());
//if this is not attached to a shooter character, fail
if (Char == nullptr) return EBTNodeResult::Failed;
if (PlayerPawn == nullptr) return;
if (!LineOfSightTo(PlayerPawn))
{
GetBlackboardComponent()->ClearValue(TEXT("PlayerLocation"));
}
return EBTNodeResult::Failed;
}
|
#include"tinyxml2.h"
#include<string>
#include<iostream>
#include<algorithm>
#include<cstddef>
#include<regex>
using namespace tinyxml2;
using namespace std;
void doWork();
void loadFile(int argc, char* argv[]);
string findAuthor(const string &hold);
void print(char* argv[]);
string trim(string str);
string capitalize(string str);
void findAndReplaceAll(string & data, string toSearch, string replaceStr);
string balanceQuotes(string data);
string fixRomanNumerals(string str);
int counter = 0; //starts counter for number of articles
XMLElement* root; //first element of the xml file
/*
struct to introduce the elements of the object
*/
struct magazine {
string author;
string header;
string date;
string volume;
string issue;
string number;
string startPage;
string endPage;
string startPageID;
string endPageID;
};
magazine* article = new magazine[500]; // create an article
/*
main() loads file, prints results, and deletes memory
*/
int main(int argc, char* argv[]) {
loadFile(argc, argv);
print(argv); //printing the results
delete[] article; //freeing the allocated memory
return 0;
}
/*
loadFile(int argc, char* argv[]) checks the arguments passed by the user, and if valid, then runs through the doWork() function
*/
void loadFile(int argc, char* argv[]) {
cerr << "Processing " << argv[1] << "... " << endl;
XMLDocument doc;
if(argc>0){ //if the user enters at least one argument
XMLError loadOK = doc.LoadFile(argv[1]); //load the file that the user requested
if (loadOK == XML_SUCCESS) //if load is successful, then find the root element
{
root = doc.FirstChildElement("algorithms"); //for finding root element
if (root != NULL)
{
doWork(); //if there is a root and it has children, loop through the children in doWork() function
}
else
cerr << "root is null " << endl;
}
else
cerr << "Error loading file " << endl;
}
}
/*
Function: doWork()
Cycles through XML file to extract the article information (children and siblings)
*/
void doWork() {
//cout << "HERE0" << endl;
//iterates through all of child nodes
for (XMLNode* child = root->FirstChild(); child != NULL ; child = child->NextSibling()) //while child is not null, loop through all the children nodes starting at the first one
{
// cout << "HERE1" << endl;
//if(child->NextSibling() != NULL)
//{cout << "looking at next sibling" << child->NextSibling() << endl;
// cout << "what is next sibling " << child->NextSibling()->ToElement()->GetText() << endl;
// }
bool isArticle = false; //default false until conditions are met
smatch match;
// This code may not be used
if(strcmp(child->Value(), "author") == 0) //if the child tag is <author>, store it
{
article[counter].author = child->ToElement()->GetText();
}
// Decide if this is a section header and grab info
if (strcmp(child->Value(), "figure") == 0 || strcmp(child->Value(), "construct") == 0 || strcmp(child->Value(), "table") == 0
|| strcmp(child->Value(), "equation") == 0 || strcmp(child->Value(), "sectionHeader") == 0
|| strcmp(child->Value(), "listItem") == 0 ) //sections where headers are located
{
string tempstr = child->ToElement()->GetText(); //store all of text then narrow it down to 200 characters
string str = tempstr.substr(0, 200);
// cerr << "str: " << str << endl;
int authStart;
XMLElement* sib = child->NextSiblingElement(); //sibling element introduced to loop through
// cerr << "str.length(): " << str.length() << endl;
//err << "str: " << str << endl;
// Extract the author
if (sib!=NULL) {
if (str.length() > 3) { //to keep loop going (so the length value is never negative)
for (authStart = 0; authStart < (str.length()-3 ) ; authStart++)
{
//cerr << "here0" << endl;
if (str[authStart] == 'B'
&& (str[authStart + 1] == 'y' || str[authStart + 1] == 'v')
&& str[authStart + 2] == ' '
&& strcmp(sib->Value(), "bodyText") == 0)
// if an author is in the title, marked by "By", it's the author of the next bodytext element
{
tempstr = str.substr(0, authStart); //store string until 'B' and 'y'
string auth = str.substr(authStart - 1, str.length() - authStart); //store string after'B' 'y'
article[counter].author = capitalize(trim(findAuthor(auth))); //runs thru capitalize, trim, and findAuthor functions and stores
article[counter].startPageID = child->ToElement()->Attribute("page_id"); //looks at attributes to store page ids and numbers
article[counter].startPage = child->ToElement()->Attribute("page_num");
isArticle = true; //it is an article
break;
}
}// this works
}//out << "HERE?" << endl;
for (int headstart = 0; headstart < tempstr.length(); headstart++)
{
//double checking to make sure only uppercase headers that are an article are stored
if (isupper(tempstr[headstart])&& (isupper(tempstr[headstart+1]) || tempstr[headstart+1] == ' ' ) && isArticle==true) //if at least first two characters are uppercase and it is an article, store
{
tempstr = tempstr.substr(headstart, authStart); //from start of Cap letters to the start of the "By"
tempstr = trim(tempstr); //runs thru trim function, then capitalize function, then store
tempstr = capitalize(tempstr);
article[counter].header = tempstr;
break;
}
}
// if author is in body
string temps;
string s;
if (strcmp(sib->Value(), "bodyText") == 0 ||strcmp(sib->Value(), "construct") == 0)
{
// cout << "HERE" << endl;
temps = child->NextSiblingElement()->GetText(); //store bodytext, then only 75 characters of that into s
s = temps.substr(0, 75);
for (int authChar = 0; authChar < s.length(); authChar++) //if author is in the body, it will be within the first 75 characters
{
if (s[authChar] == 'B' && (s[authChar + 1] == 'y'))
{
string hold = s.substr(authChar, 25);
article[counter].author = capitalize(trim(findAuthor(hold)));
//runs thru capitalize, trim, findAuthor functions
article[counter].header = capitalize(trim(str)); //runs thru capitalize and trim funcitions
article[counter].startPageID = child->ToElement()->Attribute("page_id"); //same as above
article[counter].startPage = child->ToElement()->Attribute("page_num");
isArticle = true;
break;
}
}
}
}
regex titleRegex(".*?All Rights Reserved. [A-Za-z]+, [0-9]{4}[.,]?(.+)"); //some titles store this information, so weeding it out via regEx
// regex titleRegex("(All Rights Reserved. [A-Za-z]+, [0-9]{4})");
//cerr << "TITLE BEFORE: " << article[counter].header << endl ;
if (regex_search (article[counter].header, match, titleRegex)) { //if found, then remove irrelevant parts that are not title, and store
//cerr << "TITLE Regex Matched: " << match[1].str() << endl ;
article[counter].header = capitalize(trim(match[1].str()));
//cerr << "here0" << endl;
}
// article[counter].header = fixRomanNumerals article[counter].header);
//when the next section header begins, the last article ends // so end page # and page id of the previous article is the beginning of the next
if (counter >= 1 && isArticle)
{
article[counter-1].endPage = child->ToElement()->Attribute("page_num");
article[counter-1].endPageID = child->ToElement()->Attribute("page_id");
}
}
// Decide if this is a body of text and grab author, date, issue, number.
if (strcmp(child->Value(), "bodyText") == 0 || strcmp(child->Value(), "keyword") == 0 || strcmp(child->Value(), "construct") == 0) //sections where date, issue and vol are
{
string biginfo = child->ToElement()->GetText();
//cerr << "type: " << child->Value() << " Biginfo ---- " << endl << biginfo << endl << "----------- " << endl << endl;
//cerr << "where we stop " << child->Value() << endl;
regex dateRegex("([A ?-Z ?]+),( [0-9]{4})");
if (regex_search(biginfo, match, dateRegex)) {
//cerr << "DATE Regex Matched: " << match[1].str() << match[2].str() << endl ;
article[counter].date = capitalize(trim(match[1].str())) + match[2].str(); //if regex is matched then capitalize, trim and concatenate the month and year
}
regex volRegex("([VYM] ?[Oo] ?[LIR]v?[,.] [IVXLCivxlc0-9]+)"); //if regex is matched then trim volume, if volume is not "VOL" then find and replace with "VOL" and fix wonky roman numerals
if (regex_search(biginfo, match, volRegex)) {
//cerr << "VOL Regex Matched: " << match[1].str() << endl ;
article[counter].volume = trim(match[1].str());
findAndReplaceAll(article[counter].volume, "VOIv", "VOL");
article[counter].volume = capitalize(article[counter].volume);
article[counter].volume = fixRomanNumerals(article[counter].volume);
}
regex numberRegex("(N ?[oO] ?[.,]? [IVXLCivxlc0-9]+)"); //if regex is matched then capitalize and trim the "number" and fix roman numerals if incorrect
if (regex_search(biginfo, match, numberRegex)) {
//cerr << "NUM Regex Matched: " << match[1].str() << endl ;
article[counter].number = capitalize(trim(match[1].str()));
article[counter].number = fixRomanNumerals(article[counter].number);
}
//cerr << "BOOK INFO : " << article[counter].number << " | " << article[counter].date << " | " << article[counter].volume << endl;
}
if (isArticle == true) //only increase counter if articles are found
counter++;
}
// cout << "HERE" << endl;
}
/*
findAuthor(const string &hold) has if statements to look at regular expressions. this is to find the author using "by"
*/
string findAuthor(const string &hold) { //to find authors, use reg expression
//cerr << "Looking at: ---" << hold << "---" << endl;
try {
regex r("B[yv] ([a-z.,-^ ]*?) ?(,|\\.$).*?$");
regex r2("B[yv] ([a-z.,-^ ]*?)[ .,]?[\n\r]+");
regex r3("B[yv] ([a-z.,-^ ]*?)[\n\r]+");
smatch match;
if (regex_search(hold, match, r)) {
// cerr << "Found R: " << match[1] << endl;
return match[1];
}
else if (regex_search(hold, match, r2)) {
// cerr << "Found R2: " << match[1] << endl;
return match[1];
}
else {
//cerr << "Found Nothign " << endl;
return string("");
// cerr << " not Working: " << hold << endl;
}
} catch (regex_error& e) {
return string("");
cerr << " error!" << string("") << endl;
}
return string("");
}
/*
print() prints out all of the article metadata. if there are blanks in the volume, date, issue or number, it just copies from the previous entries until one is ecountered
*/
void print(char* argv[]) {
// cout << "Title" << "\t" <<endl;
// << "Author" << "\t" << "Date" << "\t"
// << "Volume" << "\t" << "Number" << "\t" << "Issue" << "\t"
// << "StartPageID" << "\t" << "EndPageID" << "\t"
// << "StartPage" << "\t" << "EndPage" << endl;
for (int c = 0; c < counter; c++)
{
if (article[c].date == "" && c>0)
{
article[c].date = article[c - 1].date;
article[c].issue = article[c - 1].issue;
article[c].number = article[c - 1].number;
}
if (article[c].volume == "" && c>0)
article[c].volume = article[c - 1].volume;
findAndReplaceAll(article[c].header, "'", "'");
findAndReplaceAll(article[c].header, "''", "\"");
findAndReplaceAll(article[c].header, """, "\"");
article[c].header = balanceQuotes(article[c].header);
cout << article[c].header << "\t"
<< article[c].author << "\t" << article[c].date << "\t"
<< article[c].volume << "\t" << article[c].number << "\t" << article[c].issue << "\t"
<< article[c].startPageID << "\t" << article[c].endPageID << "\t"
<< article[c].startPage << "\t" << article[c].endPage << "\t" << argv[1] << endl;
}
}
/*
trim(string str) trims away new line and extra blank characters in xml
*/
string trim(string str)
{
try {
regex rLeft("^[\r\n .]+");
str = regex_replace(str, rLeft, ""); //if there are spaces before the first word
regex rRight("[\r\n .]+$");
str = regex_replace(str, rRight, ""); // if there are spaces after the last word
regex rNewline("[\r\n]+");
str = regex_replace(str, rNewline, " "); //if there is a newline at end of string, replace with a space
return str;
} catch (exception& e) {
cerr << "exception caught: " << e.what() << " trying to parse " << str << "\n";
return "";
}
}
/*
capitalize(string str) capitalizes the first letter of each word and puts every other letter in lowercase
*/
string capitalize(string str)
{
try {
if (!str.empty())
{
str[0] = toupper(str[0]); //capitalizes first letter
for (size_t counter = 1; counter < str.length(); ++counter) //at second letter on until next word, replaces letters with lower case ones
{
str[counter] = tolower(str[counter]);
if (str[counter - 1] == ' ' || str[counter-1] == '-' || str[counter-1] =='.') //if there is a period or space before the letter, it is a new word and capitalize it
str[counter] = toupper(str[counter]);
}
}
} catch (exception& e) {
cerr << "exception caught: " << e.what() << "\n";
return "";
}
return str;
}
/*
findAndReplaceAll(string & data, string toSearch, string replaceStr) looks for the occurence of a word and replaces it
*/
void findAndReplaceAll(string & data, string toSearch, string replaceStr)
{
// Get the first occurrence
size_t pos = data.find(toSearch);
// Repeat till end is reached
while( pos != string::npos)
{
// Replace this occurrence of Sub String
data.replace(pos, toSearch.size(), replaceStr);
// Get the next occurrence from the current position
pos = data.find(toSearch, pos + replaceStr.size());
}
}
/*
fixRomanNumerals(string str) looks at letters that would be in roman numerals, and if they are lowercase, capitalizes them
*/
string fixRomanNumerals(string str) {
smatch match;
regex r("([IVXLCivxlc]{2,})");
if (regex_search(str, match, r)) {
string u = match[1].str();
for (size_t counter = 1; counter < u.length(); ++counter) {
u[counter] = toupper(u[counter]); //capitalizes each letter and then replaces them
}
str = regex_replace(str, r, u);
}
return str;
}
string balanceQuotes(string data) {
int count = 0;
char quote = '"';
for (int i = 0; i < data.size(); i++)
if (data[i] == quote) count++;
if (count % 2 == 1){
data = "\"" + data;
}
return data;
}
|
/*
Copyright (c) 2015, Vlad Mesco
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
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 "common.h"
#include "document_display.h"
#include "document.h"
#include <algorithm>
#include <numeric>
#include <assert.h>
static bool computedSize = false;
static size_t numThingsPerLine = 0;
Document::Document()
{
for(int i = 0; i < ROWS - 2; ++i) {
staves_.emplace_back();
staves_.back().type_ = 'N';
staves_.back().scale_ = 48;
staves_.back().interpolation_ = 'T';
}
title_ = "Untitled";
active_.x = 13 * N;
active_.y = 1;
selected_ = marked_ = point_t(0, 0);
}
ICell* Document::Cell(point_t p)
{
auto&& found = std::find_if(cells_.begin(), cells_.end(),
[&p](decltype(cells_)::const_reference c) -> bool {
point_t tl = c->Location();
point_t br = point_t(tl.x + c->Width(), tl.y + 1);
return p.x >= tl.x && p.x < br.x
&& p.y >= tl.y && p.y < br.y
;
});
if(found != cells_.end()) return *found;
return NULL;
}
void Document::InitCells()
{
// title bar
TitleCell* title = new TitleCell(*this);
title->SetLocation(point_t(0, 0));
title->SetWidth(COLUMNS * N);
cells_.push_back(title);
for(int i = 0; i < ROWS - 2; ++i) {
size_t x = 0;
StaffName* name = new StaffName(*this);
name->SetStaffIndex(i);
name->SetLocation(point_t(x, i + 1));
name->SetWidth(8 * N);
cells_.push_back(name);
x += name->Width();
StaffType* type = new StaffType(*this);
type->SetStaffIndex(i);
type->SetLocation(point_t(x, i + 1));
type->SetWidth(N);
cells_.push_back(type);
x += type->Width();
StaffScale* scale = new StaffScale(*this);
scale->SetStaffIndex(i);
scale->SetLocation(point_t(x, i + 1));
scale->SetWidth(3 * N);
cells_.push_back(scale);
x += scale->Width();
StaffInterpolation* interpolation = new StaffInterpolation(*this);
interpolation->SetStaffIndex(i);
interpolation->SetWidth(N);
interpolation->SetLocation(point_t(x, i + 1));
cells_.push_back(interpolation);
x += interpolation->Width();
if(!computedSize) numThingsPerLine = 4;
while(x < COLUMNS * N) {
NoteCell* note = new NoteCell(*this);
note->SetStaff(i);
note->SetLocation(point_t(x, i + 1));
note->SetWidth(1);
cells_.push_back(note);
x += note->Width();
if(!computedSize) ++numThingsPerLine;
}
computedSize = true;
}
Scroll(0);
}
void Document::UpdateCache()
{
cache_.clear();
for(int i = 0; i < ROWS - 2; ++i) {
cache_.emplace_back();
for(size_t j = 0; j < staves_[i].notes_.size(); ++j) {
for(int k = 0; k < staves_[i].notes_[j].scale_; ++k) {
cache_[i].push_back(j);
// if(cache_[i].size() >= COLUMNS - 14) break;
}
}
// cache_ should be empty if there are no notes and should only be as long as a full staff
//for(; j < (COLUMNS - 13) * 2; ++j) {
// cache_[i].push_back(-1);
//}
}
}
void Document::Scroll(size_t col)
{
for(int i = 0; i < ROWS - 2; ++i) {
int j;
for(j = 0; j < numThingsPerLine - 4; ++j) {
NoteCell* note = dynamic_cast<NoteCell*>(
cells_[1 // title
+ i * numThingsPerLine // previous staves
+ 4 // staff header
+ j // this note
]
);
assert(note);
note->SetCacheIndex(col + j);
if(col + j < cache_[i].size()) {
note->SetIndex(cache_[i][col + j]);
note->SetFirst(
(j == 0)
|| (col + j == 0)
|| (cache_[i][col + j - 1] != cache_[i][col + j])
);
continue;
} else {
note->SetIndex(-1);
note->SetFirst((j == 0) || (col + j == cache_[i].size()));
continue;
}
}
}
}
void Document::ScrollLeftRight(int ama)
{
int next = scroll_ + ama;
if(next < 0) next = 0;
bool good = false;
int last = 0;
for(size_t i = 0; i < ROWS - 2; ++i) {
//printf(">%d\n", cache_[i].size());
const int lineLength = N*(COLUMNS-13);
int lineDiff = cache_[i].size() - next;
int preferred = cache_[i].size() - lineLength;
//printf("%d %d %d\n", lineLength, lineDiff, preferred);
if(lineDiff > lineLength) {
preferred = next;
}
last = std::max(last, preferred);
//printf("%d\n", last);
if(next >= cache_[i].size() - N*(COLUMNS-13)) {
good = true;
}
}
/*if(good)*/ scroll_ = std::min(last, next);
//printf(" %d\n", scroll_);
Scroll(scroll_);
}
void Document::ScrollRight(bool byPage)
{
if(byPage) ScrollLeftRight(N*(COLUMNS - 13));
else ScrollLeftRight((COLUMNS - 13) * 2 * N / 5);
}
void Document::ScrollLeft(bool byPage)
{
if(byPage) ScrollLeftRight(-N*(COLUMNS - 13));
else ScrollLeftRight(-((COLUMNS - 13) * 2 * N / 5));
}
void Document::Save(std::ostream& fout)
{
for(Staff& s : staves_) {
if(s.name_.empty()) continue;
fout << s.name_ << " ";
switch(s.type_) {
case 'N':
fout << "NOTES" << " ";
fout << "{ " << "Divisor=" << s.scale_ << ", Notes=[" << std::endl << std::string(4, ' ');
for(size_t i = 0; i < s.notes_.size(); ++i) {
if((i + 1) % 16 == 0) fout << std::endl << std::string(4, ' ');
Note n = s.notes_[i];
fout << n.BuildString('N');
if(i < s.notes_.size() - 1) fout << ", ";
else fout << "]";
}
fout << std::endl << "}" << std::endl;
break;
case 'P':
fout << "PCM" << " " << "{Interpolation=";
switch(s.interpolation_) {
case 'C': fout << "Cosine"; break;
case 'T': fout << "Trunc"; break;
case 'L': fout << "Linear"; break;
}
fout << ", Stride=" << s.scale_ << ", " << "Samples=[" << std::endl << std::string(4, ' ');
for(size_t i = 0; i < s.notes_.size(); ++i) {
if((i + 1) % 16 == 0) fout << std::endl << std::string(4, ' ');
Note n = s.notes_[i];
fout << n.BuildString('P');
if(i < s.notes_.size() - 1) fout << ", ";
else fout << "]";
}
fout << std::endl << "}" << std::endl;
break;
}
}
}
void Document::SetActive(ICell* c)
{
active_ = c->Location();
}
void Document::SetMarked(ICell* c)
{
NoteCell* note = dynamic_cast<NoteCell*>(c);
assert(note);
if(note->Index() >= 0) {
marked_.x = note->Index();
marked_.y = note->Staff();
}
}
void Document::SetSelected(ICell* c)
{
NoteCell* note = dynamic_cast<NoteCell*>(c);
assert(note);
if(note->Index() >= 0) {
selected_.x = note->Index();
selected_.y = note->Staff();
}
}
void Document::ClearSelection()
{
marked_ = point_t(-1, -1);
selected_ = point_t(-1, -1);
}
void Document::Cut()
{
auto pc = PreCutSelection();
buffer_ = pc.buffer;
pc.cut();
ClearSelection();
UpdateCache();
ScrollLeftRight(0);
Active()->Select();
Active()->Mark();
}
void Document::Copy()
{
auto pc = PreCutSelection();
buffer_ = pc.buffer;
}
void Document::Paste()
{
switch(insertMode_)
{
case InsertMode_t::INSERT:
{
point_t pos = marked_;
int staffIdx = Active()->Location().y - 1;
if(pos.y >= 0) staffIdx = pos.y;
if(staffIdx < 0) return;
if(marked_.x < 0) pos = point_t(0, staffIdx);
for(size_t i = 0; i < buffer_.size(); ++i) {
if(staffIdx + i >= staves_.size());
Staff& s = staves_[staffIdx + i];
decltype(s.notes_)::iterator it;
if(marked_.x >= 0 && marked_.x < s.notes_.size()) it = s.notes_.begin() + marked_.x;
else { it = s.notes_.begin(); }
for(size_t j = 0; j < buffer_[i].size(); ++j) {
it = s.notes_.insert(it, buffer_[i][j]);
++it;
}
}
ClearSelection();
marked_ = pos;
selected_ = pos;
UpdateCache();
ScrollLeftRight(0);
SetActiveToMarked();
ScrollLeftRight(0);
}
break;
case InsertMode_t::APPEND:
{
point_t pos = { std::max(marked_.x, selected_.x), std::max(marked_.y, selected_.y) };
pos.x++;
int staffIdx = Active()->Location().y - 1;
if(pos.y >= 0) staffIdx = pos.y;
if(staffIdx < 0) return;
if(marked_.x < 0) pos = point_t(staves_[staffIdx].notes_.size(), staffIdx);
for(size_t i = 0; i < buffer_.size(); ++i) {
if(staffIdx + i >= staves_.size());
Staff& s = staves_[staffIdx + i];
decltype(s.notes_)::iterator it;
if(marked_.x >= 0 && marked_.x < s.notes_.size() - 1) it = s.notes_.begin() + marked_.x + 1;
else { it = s.notes_.end(); }
for(size_t j = 0; j < buffer_[i].size(); ++j) {
it = s.notes_.insert(it, buffer_[i][j]);
++it;
}
}
ClearSelection();
marked_ = pos;
selected_ = pos;
UpdateCache();
ScrollLeftRight(0);
SetActiveToMarked();
ScrollLeftRight(0);
}
break;
case InsertMode_t::REPLACE:
{
if(marked_.x < 0 || marked_.y < 0) return;
point_t pos = marked_;
//printf("%d %d %d %d\n", marked_.x, marked_.y, selected_.y, selected_.y);
if(selected_.x >= 0 && selected_.y >= 0) {
pos.x = std::min(selected_.x, pos.x);
pos.y = std::min(selected_.y, pos.y);
}
BufferOp op = PreCutSelection();
op.cut();
//printf("%d %d ==\n", pos.x, pos.y);
marked_ = pos;
selected_ = pos;
insertMode_ = InsertMode_t::INSERT;
Paste();
insertMode_ = InsertMode_t::REPLACE;
ClearSelection();
marked_ = pos;
selected_ = pos;
UpdateCache();
ScrollLeftRight(0);
SetActiveToMarked();
ScrollLeftRight(0);
}
break;
}
}
void Document::SetActiveToMarked()
{
if(marked_.x < 0 || marked_.y < 0) { /*printf("no marked\n");*/ return; }
Staff& s = staves_[marked_.y];
int pos = 0;
pos = std::accumulate(s.notes_.begin(), s.notes_.begin() + marked_.x, pos,
[](int pos, decltype(s.notes_)::const_reference n) -> int {
return pos + n.scale_;
});
if(!(pos >= scroll_ && pos < scroll_ + N*(COLUMNS - 13))) {
scroll_ = pos;
Scroll(pos);
ScrollLeftRight(0);
}
UpdateCache();
//printf("P %d\n", pos);
auto&& cache = cache_;
int staffIdx = marked_.y;
auto&& found = std::find_if(cells_.begin(), cells_.end(),
[staffIdx, pos, cache](ICell* c) -> bool {
NoteCell* nc = dynamic_cast<NoteCell*>(c);
if(!nc) return false;
//printf(" a note: s%d ci%d\n", nc->Staff(), nc->CacheIndex());
return (nc->Staff() == staffIdx)
&& nc->CacheIndex() == pos;
//&& nc->CacheIndex() >= 0 && nc->CacheIndex() < cache[staffIdx].size()
//&& cache[staffIdx][nc->CacheIndex()] == pos;
});
if(found == cells_.end()) {
printf("nothin fuond\n");
return;
}
NoteCell* nc = dynamic_cast<NoteCell*>(*found);
if(!nc) return;
while(!nc->First()) {
//printf("moving left\n");
nc = dynamic_cast<NoteCell*>(Cell(nc->Location().x - 1, nc->Location().y));
}
active_ = nc->Location();
}
void Document::NewNote()
{
Note n = { 12, '-', ' ', ' ' };
Note p = { 12, '5', '0', '0' };
switch(insertMode_)
{
case InsertMode_t::INSERT:
{
point_t pos = marked_;
int staffIdx = Active()->Location().y - 1;
if(pos.y >= 0) staffIdx = pos.y;
if(staffIdx < 0) return;
Staff& s = staves_[staffIdx];
decltype(s.notes_)::iterator it;
if(marked_.x >= 0) it = s.notes_.begin() + marked_.x;
else {
it = s.notes_.begin();
pos = point_t(0, staffIdx);
}
//printf("%d %d\n", marked_.x, it - s.notes_.begin());
if(s.type_ == 'P') n = p;
s.notes_.insert(it, n);
ClearSelection();
marked_ = pos;
selected_ = pos;
UpdateCache();
ScrollLeftRight(0);
SetActiveToMarked();
ScrollLeftRight(0);
}
break;
case InsertMode_t::APPEND:
{
point_t pos = { std::max(marked_.x, selected_.x), std::max(marked_.y, selected_.y) };
pos.x++;
int staffIdx = Active()->Location().y - 1;
if(pos.y >= 0) staffIdx = pos.y;
if(staffIdx < 0) return;
Staff& s = staves_[staffIdx];
decltype(s.notes_)::iterator it;
if(marked_.x >= 0) it = s.notes_.begin() + marked_.x;
else {
it = s.notes_.end();
pos = point_t(s.notes_.size(), staffIdx);
}
if(it != s.notes_.end()) ++it;
if(s.type_ == 'P') n = p;
s.notes_.insert(it, n);
ClearSelection();
marked_ = pos;
selected_ = pos;
UpdateCache();
ScrollLeftRight(0);
SetActiveToMarked();
ScrollLeftRight(0);
}
break;
case InsertMode_t::REPLACE:
{
if(marked_.x < 0 || marked_.y < 0) return;
point_t pos = marked_;
if(selected_.x >= 0 && selected_.y >= 0) {
pos.x = std::min(selected_.x, pos.x);
pos.y = std::min(selected_.y, pos.y);
}
BufferOp op = PreCutSelection();
op.cut();
marked_ = pos;
selected_ = pos;
insertMode_ = InsertMode_t::INSERT;
NewNote();
insertMode_ = InsertMode_t::REPLACE;
ClearSelection();
marked_ = pos;
selected_ = pos;
UpdateCache();
ScrollLeftRight(0);
SetActiveToMarked();
ScrollLeftRight(0);
}
break;
}
}
Document::BufferOp Document::PreCutSelection()
{
BufferOp ret;
std::deque<std::function<void(void)>> cuts;
int left, right, top, bottom;
if(!GetSelectionBox(left, right, top, bottom)) return ret;
for(int i = top; i <= bottom; ++i) {
Staff& s = staves_[i];
ret.buffer.emplace_back();
decltype(s.notes_)::iterator first = s.notes_.end(), last = s.notes_.end();
int n = 0;
for(auto&& it = s.notes_.begin(); it != s.notes_.end(); ++it) {
int idx = it - s.notes_.begin();
if(IsNoteSelected(i, idx)) {
ret.buffer[i - top].push_back(s.notes_[idx]);
if(first != s.notes_.end()) last = it;
else first = it, last = it;
}
}
Staff* pStaff = &s;
cuts.push_back([pStaff, first, last]() mutable {
if(first != pStaff->notes_.end()) pStaff->notes_.erase(first, last + 1);
});
}
ret.cut = [cuts]() {
for(auto&& f : cuts) f();
};
return std::move(ret);
}
void Document::Delete()
{
ICell* c = Active();
if(c->Location().y == 0) return;
if(c->Location().x < N*13) {
Staff& s = staves_[c->Location().y - 1];
s.name_ = "";
s.type_ = 'N';
s.notes_.clear();
UpdateCache();
ScrollLeftRight(0);
//Scroll(scroll_);
} else {
auto pc = PreCutSelection();
pc.cut();
ClearSelection();
UpdateCache();
ScrollLeftRight(0);
Active()->Select();
Active()->Mark();
}
}
int Document::Duration()
{
size_t maxDuration = 0;
maxDuration = std::accumulate(staves_.begin(), staves_.end(), maxDuration,
[](size_t duration, Staff const& s) -> size_t {
double scale = (s.scale_) ? 44100.0 / s.scale_ : 1.0;
double dur = 0;
dur = std::accumulate(s.notes_.begin(), s.notes_.end(), dur, [scale](double dur, Note const& n) -> double {
return dur + scale * n.scale_;
});
return std::max(duration, (size_t)dur);
});
return maxDuration / 44100;
}
int Document::Position()
{
return scroll_;
}
int Document::Max()
{
int max = 0;
max = std::accumulate(cache_.begin(), cache_.end(), max, [](int max, decltype(cache_)::const_reference line) -> int {
return std::max(max, (int)line.size());
});
return max;
}
bool Document::AtEnd()
{
return scroll_ + N*(COLUMNS - 13) >= Max();
}
int Document::Percentage()
{
int max = 1;
max = std::accumulate(cache_.begin(), cache_.end(), max, [](int orig, decltype(cache_)::const_reference curr) -> int {
int potential = curr.size() - 1;
while(potential >= 0) {
if(curr[potential] >= 0) break;
--potential;
}
return std::max(orig, potential);
});
return scroll_ * 100 / max;
}
static void AdjustColumn(Document& doc, int row, int& note)
{
int col = -1;
for(size_t i = 0; i < note; ++i) {
col += doc.staves_[row].notes_[i].scale_;
}
note = col + 1;
}
bool FirstNoteInRange(NoteCell& note, int left, int right)
{
NoteCell* n = ¬e;
while(!n->First()) {
point_t p(n->Location().x - 1, n->Location().y);
n = (NoteCell*)n->doc_.Cell(p);
if(!n) return false;
}
return n->CacheIndex() >= left && n->CacheIndex() <= right;
}
bool Document::GetSelectionBox(int& left, int& right, int& top, int& bottom)
{
left = marked_.x;
right = selected_.x;
top = marked_.y;
bottom = selected_.y;
if(right < 0) right = left;
if(bottom < 0) bottom = top;
if(left < 0 || right < 0 || top < 0 || bottom < 0) return false;
AdjustColumn(*this, top, left);
AdjustColumn(*this, bottom, right);
if(left > right) {
std::swap(left, right);
right += staves_[marked_.y].notes_[marked_.x].scale_ - 1;
} else {
right += staves_[selected_.y].notes_[selected_.x].scale_ - 1;
}
if(top > bottom) std::swap(top, bottom);
return true;
}
bool Document::IsNoteSelected(ICell* c)
{
NoteCell* note = dynamic_cast<NoteCell*>(c);
if(!note) return false;
int left, right, top, bottom;
if(!GetSelectionBox(left, right, top, bottom)) return false;
if(note->Staff() >= top && note->Staff() <= bottom
&& FirstNoteInRange(*note, left, right))
{
return true;
}
return false;
}
bool Document::IsNoteSelected(int staffIdx, int noteIdx)
{
int left, right, top, bottom;
if(!GetSelectionBox(left, right, top, bottom)) return false;
int col = noteIdx;
AdjustColumn(*this, staffIdx, col);
if(staffIdx >= top && staffIdx <= bottom
&& col >= left && col <= right)
{
return true;
} else {
return false;
}
}
void Document::PushState()
{
undoStates_.push_back(staves_);
if(undoStates_.size() > 9) undoStates_.pop_front();
UpdateCache();
ScrollLeftRight(0);
}
void Document::PopState()
{
if(undoStates_.empty()) return;
auto&& state = undoStates_.back();
staves_ = state;
undoStates_.pop_back();
UpdateCache();
ScrollLeftRight(0);
}
std::string Note::BuildString(char type)
{
std::stringstream ss;
Note& n = *this;
if(type == 'N') {
ss << n.scale_ << n.name_;
if(n.sharp_ == '#' || n.sharp_ == 'b') {
ss << n.sharp_;
}
if(n.name_ != '-') ss << n.height_;
} else if(type == 'P') {
int scale = n.scale_;
if(n.name_ >= '0' && n.name_ <= '9') {
int samp = (n.name_ - '0') * 100 + (n.height_ - '0') * 10 + (n.sharp_ - '0');
ss << scale << " " << samp;
} else {
int samp = (n.name_ - 'A') * 100 + (n.height_ - '0') * 10 + (n.sharp_ - '0');
ss << scale << " " << (-samp);
}
}
return ss.str();
}
|
/*****************************************************************
Name :merge_sort
Author :srhuang
Email :lukyandy3162@gmail.com
History :
20191125 Initial Version
*****************************************************************/
#include <iostream>
#include <vector>
#define DEBUG (0)
#define SCALE (10000)
using namespace std;
using namespace std::chrono;
/*==============================================================*/
//Global area
/*==============================================================*/
//Function area
int *random_case(int number)
{
int *result = new int[number];
//generate index ordered arrary
for(int i=0; i<number; i++){
result[i]=i+1;
}
//swap each position
srand(time(NULL));
for(int i=0; i<number-1; i++){
int j = i + rand() / (RAND_MAX / (number-i));
//swap
int t=result[i];
result[i] = result[j];
result[j]=t;
}
return result;
}
void merge(int *input, int front, int end, int mid)
{
vector<int> left(input+front, input+mid+1);
vector<int> right(input+mid+1, input+end+1);
vector<int>::iterator it;
#if 0
cout << "left :";
for(it=left.begin(); it!=left.end(); it++){
cout << *it << " ";
}
cout << endl;
cout << "right :";
for(it=right.begin(); it!=right.end(); it++){
cout << *it << " ";
}
cout << endl;
#endif
int left_index=0;
int right_index=0;
//cout << "front/end :" << front << "/" << end << endl;
for(int i=front; i<=end; i++){
if(left_index >= left.size()){ // left element is exhausted
input[i] = right[right_index++];
//cout << "input right :" << input[i] << endl;
}else if(right_index >= right.size()){ // right element is exhausted
input[i] = left[left_index++];
//cout << "input left :" << input[i] << endl;
}else if(left[left_index] <= right[right_index]){ //keep stable
input[i] = left[left_index++];
//cout << "input left :" << input[i] << endl;
}else{
input[i] = right[right_index++];
//cout << "input right :" << input[i] << endl;
}
}//for
}
void merge_sort(int *input, int front, int end)
{
//cout << "front :" << front << ", end :" << end << endl;
if(front >= end)
return;
int mid = (front+end) / 2;
//recursion
merge_sort(input, front, mid);
merge_sort(input, mid+1, end);
merge(input, front, end, mid);
}
/*==============================================================*/
int main(int argc, char const *argv[]){
int n=SCALE;
//generate data
int *random_data = random_case(n);
#if DEBUG
cout << "Before sorting :";
for(int i=0; i<n; i++){
cout << random_data[i] << " ";
}
cout << endl;
#endif
//sort
auto start = high_resolution_clock::now();
merge_sort(random_data, 0, n-1);
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);
cout << "Time taken by random_data: "
<< duration.count() << " microseconds" << endl;
#if DEBUG
cout << "\nAfter sorting :";
for(int i=0; i<n; i++){
cout << random_data[i] << " ";
}
cout << endl;
#endif
return 0;
}
/*==============================================================*/
|
// Created on: 1993-01-09
// Created by: CKY / Contract Toubro-Larsen ( Anand NATRAJAN )
// 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 _IGESBasic_ExternalRefFileIndex_HeaderFile
#define _IGESBasic_ExternalRefFileIndex_HeaderFile
#include <Standard.hxx>
#include <Interface_HArray1OfHAsciiString.hxx>
#include <IGESData_HArray1OfIGESEntity.hxx>
#include <IGESData_IGESEntity.hxx>
#include <Standard_Integer.hxx>
class TCollection_HAsciiString;
class IGESBasic_ExternalRefFileIndex;
DEFINE_STANDARD_HANDLE(IGESBasic_ExternalRefFileIndex, IGESData_IGESEntity)
//! defines ExternalRefFileIndex, Type <402> Form <12>
//! in package IGESBasic
//! Contains a list of the symbolic names used by the
//! referencing files and the DE pointers to the
//! corresponding definitions within the referenced file
class IGESBasic_ExternalRefFileIndex : public IGESData_IGESEntity
{
public:
Standard_EXPORT IGESBasic_ExternalRefFileIndex();
//! This method is used to set the fields of the class
//! ExternalRefFileIndex
//! - aNameArray : External Reference Entity symbolic names
//! - allEntities : External Reference Entities
//! raises exception if array lengths are not equal
//! if size of aNameArray is not equal to size of allEntities
Standard_EXPORT void Init (const Handle(Interface_HArray1OfHAsciiString)& aNameArray, const Handle(IGESData_HArray1OfIGESEntity)& allEntities);
//! returns number of index entries
Standard_EXPORT Standard_Integer NbEntries() const;
//! returns the External Reference Entity symbolic name
//! raises exception if Index <= 0 or Index > NbEntries()
Standard_EXPORT Handle(TCollection_HAsciiString) Name (const Standard_Integer Index) const;
//! returns the internal entity
//! raises exception if Index <= 0 or Index > NbEntries()
Standard_EXPORT Handle(IGESData_IGESEntity) Entity (const Standard_Integer Index) const;
DEFINE_STANDARD_RTTIEXT(IGESBasic_ExternalRefFileIndex,IGESData_IGESEntity)
protected:
private:
Handle(Interface_HArray1OfHAsciiString) theNames;
Handle(IGESData_HArray1OfIGESEntity) theEntities;
};
#endif // _IGESBasic_ExternalRefFileIndex_HeaderFile
|
//#define _CRT_SECURE_NO_WARNINGS
#include<bits/stdc++.h>
#include<conio.h>
#include<windows.h>
using namespace std;
int mapp[6][6],score,maxscore;
bool mappp[6][6];//判断这个点是否已经合成过
int c;
const char WALL[]="---------------------";
bool over();
void GetMaxScore();
void UpdateMaxScore();
void OutPut();
void Set();
void mov(int,int);
void MoveNum(int,int,int,int,bool &);
void Save();
bool Read();
int main(){
HWND hwnd=GetForegroundWindow();
HANDLE hOut=GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO cursorInfo;
GetConsoleCursorInfo(hOut, &cursorInfo);
cursorInfo.bVisible=0;
SetConsoleCursorInfo(hOut, &cursorInfo);
//设置光标不可见
SetConsoleTitle("2048");
//设置控制台标题
COORD size={24,13};
SetConsoleScreenBufferSize(hOut, size);
//设置控制台缓冲区大小
SMALL_RECT rect={0,0,26,13};
SetConsoleWindowInfo(hOut,1,&rect);
//设置控制台大小
srand(time(NULL));
GetMaxScore();
bool flag=0;
mapp[0][0]=mapp[5][5]=-1;
for(int i=1;i<=4;i++)mapp[i][0]=mapp[0][i]=mapp[i][5]=mapp[5][i]=-1;
while(1){
if(!flag) printf("Press any key to start");
else printf("Press any key to restart");
getch();
if(!flag&&Read()){
printf("\nLast game's record detected\nContinue with it?\n1.Yes 0.No");
if(getch()=='1')goto Start;
}
for(int i=1;i<=4;i++)
for(int j=1;j<=4;j++)mapp[i][j]=0;
Set();
Start:
score=0;
int x=0,y=0;
while(1){
flag=1;
OutPut();
if(over()){
printf("GAME OVER\n");
UpdateMaxScore();
printf("\n\n");
break;
}
c=getch();
if(c=='0'){
printf("Are you sure to exit?\n1.Yes 0.No");
if(getch()=='1'){
Save();
system("cls");
break;
}
else{
OutPut();
c=getch();
}
}
switch(c){
case 224:switch(getch()){
case 75:goto LEFT;
case 80:goto DOWN;
case 77:goto RIGHT;
case 72:goto UP;
}
case 'a':case 'A':LEFT:x=0,y=1;mov(0,-1);break;
case 's':case 'S':DOWN:x=-1,y=0;mov(1,0);break;
case 'd':case 'D':RIGHT:x=0,y=-1;mov(0,1);break;
case 'w':case 'W':UP:x=1,y=0;mov(-1,0);break;
case '\b':ShowWindow(hwnd,SW_MINIMIZE);break;
case 27:Save();return 0;
default:printf("INVALID COMMAND"); Sleep(500);
}
memset(mappp,0,sizeof(mappp));
}
}
return 0;
}
void MoveNum(int i,int j,int x,int y,bool &flag){
if(mapp[i][j]&&!mapp[i+x][j+y]){
mapp[i+x][j+y]=mapp[i][j];
mapp[i][j]=0;
flag=1;
MoveNum(i+x,j+y,x,y,flag);
}
else if(mapp[i][j]==mapp[i+x][j+y]&&mapp[i][j]&&!mappp[i][j]){
mapp[i+x][j+y]+=mapp[i][j];
score+=mapp[i][j];
mapp[i][j]=0;
flag=1;
mappp[i][j]=1;
return;
}
return;
}
void mov(int x,int y){
bool flag=0;//判断移动是否有效
if(x==-1||y==-1){
for(int i=1;i<=4;i++)
for(int j=1;j<=4;j++)
MoveNum(i,j,x,y,flag);
}
else{
for(int i=4;i>0;i--)
for(int j=4;j>0;j--)
MoveNum(i,j,x,y,flag);
}
//同样好tm简陋的移动方式
if(flag) Set();
else{
printf("INVALID COMMAND");
Sleep(500);
}
}
bool over(){
for(int i=1;i<=4;i++)
for(int j=1;j<=4;j++)
if(!mapp[i][j]||mapp[i+1][j]==mapp[i][j]||mapp[i-1][j]==mapp[i][j]||mapp[i][j+1]==mapp[i][j]||mapp[i][j-1]==mapp[i][j])
return 0;
return 1;
}
void GetMaxScore(){
ifstream fin("maxscore");
fin>>maxscore;
fin.close();
}
void UpdateMaxScore(){
if(score>maxscore){
ofstream fout("maxscore");
maxscore=score;
fout<<maxscore;
fout.close();
cout<<"NEW SCORE!";
}
else cout<<"Max score:"<<maxscore;
}
void OutPut(){
system("cls");
for(int i=1;i<=4;i++){
cout<<WALL<<endl;
for(int j=1;j<=4;j++)
if(!mapp[i][j])printf("| ");
else if(mapp[i][j]<10)printf("| %d ",mapp[i][j]);
else if(mapp[i][j]<100)printf("| %d ",mapp[i][j]);
else if(mapp[i][j]<1000)printf("|%d ",mapp[i][j]);
else printf("|%d",mapp[i][j]);
cout<<'|'<<endl;
}//输出方法好tm简陋
cout<<WALL<<endl;
cout<<"score:"<<score<<endl;
}
void Set(){
int x=0,y=0;
while(mapp[x][y])x=rand()%4+1,y=rand()%4+1;
int k=rand()%5;
mapp[x][y]=k<1?4:2;
//20%概率生成4,80%概率生成2
}
void Save(){
ofstream fout("lastgame");
for(int i=1;i<=4;i++)
for(int j=1;j<=4;j++)
fout<<mapp[i][j]<<' ';
fout.close();
}
bool Read(){
ifstream fin("lastgame");
if(!fin.is_open())return 0;
for(int i=1;i<=4;i++)
for(int j=1;j<=4;j++)
fin>>mapp[i][j];
fin.close();
remove("lastgame");
return 1;
}
|
#include <iostream>
#include <math.h>
#include <string.h>
#include "add_control_noise.h"
#include "add_feature.h"
#include "add_observation_noise.h"
#include "compute_weight.h"
#include "data_associate_known.h"
#include "fastslam1_sim.h"
#include "feature_update.h"
#include "get_observations.h"
#include "linalg.h"
#include "predict.h"
#include "resample_particles.h"
#include "fastslam1_utils.h"
#include "predict_update.h"
#include "observe_update.h"
#include "fastrand.h"
void fastslam1_sim( double* lm, const size_t lm_rows, const size_t lm_cols,
double* wp, const size_t wp_rows, const size_t wp_cols,
Particle **particles_, double** weights_)
{
fastslam1_sim_active(lm, lm_rows, lm_cols, wp, wp_rows, wp_cols, particles_, weights_);
}
double fastslam1_sim_base_flops( double* lm, const size_t lm_rows, const size_t lm_cols,
double* wp, const size_t wp_rows, const size_t wp_cols,
Particle **particles_, double** weights_) {
const size_t N_features = lm_rows;
const size_t N_waypoints = wp_rows;
NUMBER_LOOPS=_NUMBER_LOOPS;
Particle *particles;
double *weights;
double weights_copy[NPARTICLES];
Vector3d xtrue = {0,0,0};
setup_initial_particles(&particles, &weights, N_features, xtrue);
setup_initial_Q_R(); // modifies global variables
int *ftag;
int *da_table;
setup_landmarks(&ftag, &da_table, N_features);
Vector2d *z; // This is a dynamic array of Vector2d - see https://stackoverflow.com/a/13597383/5616591
Vector2d *zf;
Vector2d *zn;
int *idf, *ftag_visible;
setup_measurements(&z, &zf, &zn, &idf, &ftag_visible, N_features);
double flop_count = 0;
// if ( SWITCH_PREDICT_NOISE ) {
// printf("Sampling from predict noise usually OFF for FastSLAM 2.0\n");
// }
srand( SWITCH_SEED_RANDOM );
#ifdef __AVX2__
avx_xorshift128plus_init(1,1);
#endif
double dt = DT_CONTROLS; // change in time btw predicts
double dtsum = 0; // change in time since last observation
double T = 0;
int iwp = 0; // index to first waypoint
double G = 0; // initialize steering angle
double V = V_;
size_t Nf_visible = 0;
// Main loop
while ( iwp != -1 ) {
//////////////////////////////////////////////////////////////////
// Prediction
//////////////////////////////////////////////////////////////////
flop_count+= predict_update_base_flops(wp, N_waypoints, V, *Q, dt, NPARTICLES, xtrue, &iwp, &G,particles);
predict_update_base(wp, N_waypoints, V, *Q, dt, NPARTICLES, xtrue, &iwp, &G,particles);
/////////////////////////////////////////////////////////////////
//Update time
dtsum = dtsum + dt;
T+=dt;
flop_count+= 2* tp.add;
// Observation condition
if ( dtsum >= DT_OBSERVE ) {
dtsum = 0;
//////////////////////////////////////////////////////////////
// Observation
//////////////////////////////////////////////////////////////
for (size_t i = 0; i < N_features; i++) {
ftag_visible[i] = ftag[i];
}
flop_count += get_observations_base_flops(xtrue, MAX_RANGE, lm, N_features, ftag_visible, &Nf_visible, z);
get_observations_base(xtrue, MAX_RANGE, lm, N_features, ftag_visible, &Nf_visible, z); // Nf_visible = number of visible features
//z is the range and bearing of the observed landmark
flop_count+= observe_update_base_flops(lm, N_features, xtrue, *R, ftag,
da_table, ftag_visible, z, &Nf_visible, zf, idf,
zn, particles, weights);
observe_update_base(lm, N_features, xtrue, *R, ftag,
da_table, ftag_visible, z, &Nf_visible, zf, idf,
zn, particles, weights);
//////////////////////////////////////////////////////////////
}
}
cleanup_landmarks(&ftag, &da_table);
cleanup_measurements(&z, &zf, &zn, &idf, &ftag_visible);
cleanup_particles(&particles, &weights);
return flop_count;
}
double fastslam1_sim_base_memory( double* lm, const size_t lm_rows, const size_t lm_cols,
double* wp, const size_t wp_rows, const size_t wp_cols,
Particle **particles_, double** weights_){
const size_t N_features = lm_rows;
const size_t N_waypoints = wp_rows;
NUMBER_LOOPS=_NUMBER_LOOPS;
Particle *particles;
double *weights;
Vector3d xtrue = {0,0,0};
setup_initial_particles(&particles, &weights, N_features, xtrue);
setup_initial_Q_R(); // modifies global variables
int *ftag;
int *da_table;
setup_landmarks(&ftag, &da_table, N_features);
Vector2d *z; // This is a dynamic array of Vector2d - see https://stackoverflow.com/a/13597383/5616591
Vector2d *zf;
Vector2d *zn;
int *idf, *ftag_visible;
setup_measurements(&z, &zf, &zn, &idf, &ftag_visible, N_features);
double memory_moved = 0.0;
// if ( SWITCH_PREDICT_NOISE ) {
// printf("Sampling from predict noise usually OFF for FastSLAM 2.0\n");
// }
srand( SWITCH_SEED_RANDOM );
#ifdef __AVX2__
avx_xorshift128plus_init(1,1);
#endif
double dt = DT_CONTROLS; // change in time btw predicts
double dtsum = 0; // change in time since last observation
double T = 0;
int iwp = 0; // index to first waypoint
double G = 0; // initialize steering angle
double V = V_;
size_t Nf_visible = 0;
// Main loop
while ( iwp != -1 ) {
//////////////////////////////////////////////////////////////////
// Prediction
//////////////////////////////////////////////////////////////////
memory_moved+= predict_update_base_memory(wp, N_waypoints, V, *Q, dt, NPARTICLES, xtrue, &iwp, &G,particles);
predict_update_base(wp, N_waypoints, V, *Q, dt, NPARTICLES, xtrue, &iwp, &G,particles);
/////////////////////////////////////////////////////////////////
//Update time
dtsum = dtsum + dt;
T+=dt;
// Observation condition
if ( dtsum >= DT_OBSERVE ) {
dtsum = 0;
//////////////////////////////////////////////////////////////
// Observation
//////////////////////////////////////////////////////////////
for (size_t i = 0; i < N_features; i++) {
ftag_visible[i] = ftag[i];
}
//z is the range and bearing of the observed landmark
memory_moved+= get_observations_base_memory(xtrue, MAX_RANGE, lm, N_features, ftag_visible, &Nf_visible, z);
get_observations_base(xtrue, MAX_RANGE, lm, N_features, ftag_visible, &Nf_visible, z); // Nf_visible = number of visible features
memory_moved+= observe_update_base_memory(lm, N_features, xtrue, *R, ftag,
da_table, ftag_visible, z, &Nf_visible, zf, idf,
zn, particles, weights);
observe_update_base(lm, N_features, xtrue, *R, ftag,
da_table, ftag_visible, z, &Nf_visible, zf, idf,
zn, particles, weights);
//////////////////////////////////////////////////////////////
}
}
cleanup_landmarks(&ftag, &da_table);
cleanup_measurements(&z, &zf, &zn, &idf, &ftag_visible);
cleanup_particles(&particles, &weights);
return memory_moved;
}
double fastslam1_sim_active_flops( double* lm, const size_t lm_rows, const size_t lm_cols,
double* wp, const size_t wp_rows, const size_t wp_cols,
Particle **particles_, double** weights_){
const size_t N_features = lm_rows;
const size_t N_waypoints = wp_rows;
NUMBER_LOOPS=_NUMBER_LOOPS;
Particle *particles;
double *weights;
Vector3d xtrue = {0,0,0};
setup_initial_particles(&particles, &weights, N_features, xtrue);
setup_initial_Q_R(); // modifies global variables
int *ftag;
int *da_table;
setup_landmarks(&ftag, &da_table, N_features);
Vector2d *z; // This is a dynamic array of Vector2d - see https://stackoverflow.com/a/13597383/5616591
Vector2d *zf;
Vector2d *zn;
int *idf, *ftag_visible;
setup_measurements(&z, &zf, &zn, &idf, &ftag_visible, N_features);
double flop_count = 0.0;
// if ( SWITCH_PREDICT_NOISE ) {
// printf("Sampling from predict noise usually OFF for FastSLAM 2.0\n");
// }
srand( SWITCH_SEED_RANDOM );
#ifdef __AVX2__
avx_xorshift128plus_init(1,1);
#endif
double dt = DT_CONTROLS; // change in time btw predicts
double dtsum = 0; // change in time since last observation
double T = 0;
int iwp = 0; // index to first waypoint
double G = 0; // initialize steering angle
double V = V_;
size_t Nf_visible = 0;
// Main loop
while ( iwp != -1 ) {
//////////////////////////////////////////////////////////////////
// Prediction
//////////////////////////////////////////////////////////////////
flop_count+= predict_update_active_flops(wp, N_waypoints, V, *Q, dt, NPARTICLES, xtrue, &iwp, &G,particles);
predict_update_base(wp, N_waypoints, V, *Q, dt, NPARTICLES, xtrue, &iwp, &G,particles);
/////////////////////////////////////////////////////////////////
//Update time
dtsum = dtsum + dt;
T+=dt;
flop_count+= 2* tp.add;
// Observation condition
if ( dtsum >= DT_OBSERVE ) {
dtsum = 0;
//////////////////////////////////////////////////////////////
// Observation
//////////////////////////////////////////////////////////////
for (size_t i = 0; i < N_features; i++) {
ftag_visible[i] = ftag[i];
}
//z is the range and bearing of the observed landmark
flop_count+= get_observations_base_flops(xtrue, MAX_RANGE, lm, N_features, ftag_visible, &Nf_visible, z);
get_observations_base(xtrue, MAX_RANGE, lm, N_features, ftag_visible, &Nf_visible, z); // Nf_visible = number of visible features
flop_count+= observe_update_flops(lm, N_features, xtrue, *R, ftag,
da_table, ftag_visible, z, &Nf_visible, zf, idf,
zn, particles, weights);
observe_update_base(lm, N_features, xtrue, *R, ftag,
da_table, ftag_visible, z, &Nf_visible, zf, idf,
zn, particles, weights);
//////////////////////////////////////////////////////////////
}
}
cleanup_landmarks(&ftag, &da_table);
cleanup_measurements(&z, &zf, &zn, &idf, &ftag_visible);
cleanup_particles(&particles, &weights);
return flop_count;
}
double fastslam1_sim_active_memory( double* lm, const size_t lm_rows, const size_t lm_cols,
double* wp, const size_t wp_rows, const size_t wp_cols,
Particle **particles_, double** weights_) {
const size_t N_features = lm_rows;
const size_t N_waypoints = wp_rows;
NUMBER_LOOPS = _NUMBER_LOOPS;
Particle *particles;
double *weights;
Vector3d xtrue = {0,0,0};
setup_initial_particles(&particles, &weights, N_features, xtrue);
setup_initial_Q_R(); // modifies global variables
int *ftag;
int *da_table;
setup_landmarks(&ftag, &da_table, N_features);
Vector2d *z; // This is a dynamic array of Vector2d - see https://stackoverflow.com/a/13597383/5616591
Vector2d *zf;
Vector2d *zn;
int *idf, *ftag_visible;
setup_measurements(&z, &zf, &zn, &idf, &ftag_visible, N_features);
double memory_moved = 0.0;
// if ( SWITCH_PREDICT_NOISE ) {
// printf("Sampling from predict noise usually OFF for FastSLAM 2.0\n");
// }
srand( SWITCH_SEED_RANDOM );
#ifdef __AVX2__
avx_xorshift128plus_init(1,1);
#endif
double dt = DT_CONTROLS; // change in time btw predicts
double dtsum = 0; // change in time since last observation
double T = 0;
int iwp = 0; // index to first waypoint
double G = 0; // initialize steering angle
double V = V_;
size_t Nf_visible = 0;
// Main loop
while ( iwp != -1 ) {
//////////////////////////////////////////////////////////////////
// Prediction
//////////////////////////////////////////////////////////////////
memory_moved+= predict_update_active_memory(wp, N_waypoints, V, *Q, dt, NPARTICLES, xtrue, &iwp, &G,particles);
predict_update_base(wp, N_waypoints, V, *Q, dt, NPARTICLES, xtrue, &iwp, &G,particles);
/////////////////////////////////////////////////////////////////
//Update time
dtsum = dtsum + dt;
T+=dt;
// Observation condition
if ( dtsum >= DT_OBSERVE ) {
dtsum = 0;
//////////////////////////////////////////////////////////////
// Observation
//////////////////////////////////////////////////////////////
for (size_t i = 0; i < N_features; i++) {
ftag_visible[i] = ftag[i];
}
//z is the range and bearing of the observed landmark
memory_moved += get_observations_base_memory(xtrue, MAX_RANGE, lm, N_features, ftag_visible, &Nf_visible, z);
get_observations_base(xtrue, MAX_RANGE, lm, N_features, ftag_visible, &Nf_visible, z); // Nf_visible = number of visible features
memory_moved += observe_update_base_memory(lm, N_features, xtrue, *R, ftag,
da_table, ftag_visible, z, &Nf_visible, zf, idf,
zn, particles, weights);
observe_update_base(lm, N_features, xtrue, *R, ftag,
da_table, ftag_visible, z, &Nf_visible, zf, idf,
zn, particles, weights);
//////////////////////////////////////////////////////////////
}
}
cleanup_landmarks(&ftag, &da_table);
cleanup_measurements(&z, &zf, &zn, &idf, &ftag_visible);
cleanup_particles(&particles, &weights);
return memory_moved;
}
void fastslam1_sim_base( double* lm, const size_t lm_rows, const size_t lm_cols,
double* wp, const size_t wp_rows, const size_t wp_cols,
Particle **particles_, double** weights_)
{
const size_t N_features = lm_rows;
const size_t N_waypoints = wp_rows;
NUMBER_LOOPS=_NUMBER_LOOPS;
Particle *particles;
double *weights;
Vector3d xtrue = {0,0,0};
setup_initial_particles(&particles, &weights, N_features, xtrue);
setup_initial_Q_R(); // modifies global variables
int *ftag;
int *da_table;
setup_landmarks(&ftag, &da_table, N_features);
Vector2d *z; // This is a dynamic array of Vector2d - see https://stackoverflow.com/a/13597383/5616591
Vector2d *zf;
Vector2d *zn;
int *idf, *ftag_visible;
setup_measurements(&z, &zf, &zn, &idf, &ftag_visible, N_features);
// if ( SWITCH_PREDICT_NOISE ) {
// printf("Sampling from predict noise usually OFF for FastSLAM 2.0\n");
// }
srand( SWITCH_SEED_RANDOM );
#ifdef __AVX2__
avx_xorshift128plus_init(1,1);
#endif
double dt = DT_CONTROLS; // change in time btw predicts
double dtsum = 0; // change in time since last observation
double T = 0;
int iwp = 0; // index to first waypoint
double G = 0; // initialize steering angle
double V = V_;
size_t Nf_visible = 0;
// Main loop
while ( iwp != -1 ) {
//////////////////////////////////////////////////////////////////
// Prediction
//////////////////////////////////////////////////////////////////
predict_update_base(wp, N_waypoints, V, *Q, dt, NPARTICLES, xtrue, &iwp, &G,particles);
/////////////////////////////////////////////////////////////////
//Update time
dtsum = dtsum + dt;
T+=dt;
// Observation condition
if ( dtsum >= DT_OBSERVE ) {
dtsum = 0;
//////////////////////////////////////////////////////////////
// Observation
//////////////////////////////////////////////////////////////
for (size_t i = 0; i < N_features; i++) {
ftag_visible[i] = ftag[i];
}
//z is the range and bearing of the observed landmark
get_observations_base(xtrue, MAX_RANGE, lm, N_features, ftag_visible, &Nf_visible, z); // Nf_visible = number of visible features
observe_update_base(lm, N_features, xtrue, *R, ftag,
da_table, ftag_visible, z, &Nf_visible, zf, idf,
zn, particles, weights);
//////////////////////////////////////////////////////////////
}
}
cleanup_landmarks(&ftag, &da_table);
cleanup_measurements(&z, &zf, &zn, &idf, &ftag_visible);
*particles_ = particles;
*weights_ = weights;
}
void fastslam1_sim_active( double* lm, const size_t lm_rows, const size_t lm_cols,
double* wp, const size_t wp_rows, const size_t wp_cols,
Particle **particles_, double** weights_)
{
const size_t N_features = lm_rows;
const size_t N_waypoints = wp_rows;
NUMBER_LOOPS=_NUMBER_LOOPS;
Particle *particles;
double *weights;
// double *xv; We get them from the configfile
// double *Pv; We get them from the configfile
Vector3d xtrue = {0,0,0};
setup_initial_particles_and_pose(&particles, &weights, &xv, &Pv, NPARTICLES, N_features, xtrue);
setup_initial_Q_R(); // modifies global variables
int *ftag;
int *da_table;
setup_landmarks(&ftag, &da_table, N_features);
Vector2d *z; // This is a dynamic array of Vector2d - see https://stackoverflow.com/a/13597383/5616591
Vector2d *zf;
Vector2d *zn;
int *idf, *ftag_visible;
setup_measurements(&z, &zf, &zn, &idf, &ftag_visible, N_features);
// if ( SWITCH_PREDICT_NOISE ) {
// printf("Sampling from predict noise usually OFF for FastSLAM 2.0\n");
// }
srand( SWITCH_SEED_RANDOM );
#ifdef __AVX2__
avx_xorshift128plus_init(1,1);
#endif
double dt = DT_CONTROLS; // change in time btw predicts
double dtsum = 0; // change in time since last observation
double T = 0;
int iwp = 0; // index to first waypoint
double G = 0; // initialize steering angle
double V = V_;
size_t Nf_visible = 0;
// Main loop
while ( iwp != -1 ) {
//////////////////////////////////////////////////////////////////
// Prediction
//////////////////////////////////////////////////////////////////
predict_update(wp, N_waypoints, V, *Q, dt, NPARTICLES, xtrue, &iwp, &G,particles);
/////////////////////////////////////////////////////////////////
//Update time
dtsum = dtsum + dt;
T+=dt;
// Observation condition
if ( dtsum >= DT_OBSERVE ) {
dtsum = 0;
//////////////////////////////////////////////////////////////
// Observation
//////////////////////////////////////////////////////////////
for (size_t i = 0; i < N_features; i++) {
ftag_visible[i] = ftag[i];
}
//z is the range and bearing of the observed landmark
get_observations_base(xtrue, MAX_RANGE, lm, N_features, ftag_visible, &Nf_visible, z); // Nf_visible = number of visible features
observe_update(lm, N_features, xtrue, *R, ftag,
da_table, ftag_visible, z, &Nf_visible, zf, idf,
zn, particles, weights);
//////////////////////////////////////////////////////////////
}
}
cleanup_landmarks(&ftag, &da_table);
cleanup_measurements(&z, &zf, &zn, &idf, &ftag_visible);
*particles_ = particles;
*weights_ = weights;
}
void fastslam1_sim_base_VP(double* lm, const size_t lm_rows, const size_t lm_cols,
const size_t N_features, Particle **particles_, double** weights_)
{
const size_t N_waypoints = 0;
double *wp = NULL; // dummy
Particle *particles;
double *weights;
Vector3d xtrue = {-67.6493, -41.7142, 35.5*M_PI/180};
setup_initial_particles(&particles, &weights, N_features, xtrue);
setup_initial_Q_R(); // modifies global variables
int *ftag;
int *da_table;
setup_landmarks(&ftag, &da_table, N_features);
Vector2d *z; // This is a dynamic array of Vector2d - see https://stackoverflow.com/a/13597383/5616591
Vector2d *zf;
Vector2d *zn;
int *idf, *ftag_visible;
setup_measurements(&z, &zf, &zn, &idf, &ftag_visible, N_features);
// if ( SWITCH_PREDICT_NOISE ) {
// printf("Sampling from predict noise usually OFF for FastSLAM 2.0\n");
// }
srand( SWITCH_SEED_RANDOM );
#ifdef __AVX2__
avx_xorshift128plus_init(1,1);
#endif
double dt = DT_CONTROLS; // change in time btw predicts
double dtsum = 0; // change in time since last observation
double T = lm[0];
int iwp = 0; // index to first waypoint
double G = 0; // initialize steering angle
double V = 0.0;//V_;
size_t Nf_visible = 0;
// Main loop
int index = 0;
while ( index < lm_rows -1 ) {
//////////////////////////////////////////////////////////////////
// Prediction
//////////////////////////////////////////////////////////////////
dt = (lm[4*(index+1)] - lm[4*(index)]) / 1000.0;
V = lm[4*(index) +2];
G = lm[4*(index) +3];
predict_update_VP_base(wp, N_waypoints, V, *Q, dt, NPARTICLES, xtrue, &iwp, &G,particles);
/////////////////////////////////////////////////////////////////
//Update time
dtsum = dtsum + dt;
T += dt*1000.0;
// Observation condition
if ( lm[4*(index+1) + 1] > -1 ) {
dtsum = 0;
///Setup z, ftag_visible, Nf_visible
Nf_visible = 0;
while ( lm[4*(index+1) + 1] > -1 ) {
index++;
double r = lm[4*(index) +2];
double phi = lm[4*(index) +3];
z[Nf_visible][0] = r;
z[Nf_visible][1] = pi_to_pi_base(phi - M_PI_2);
ftag_visible[Nf_visible] = lm[4*(index) +1] -1;
Nf_visible++;
}
//////////////////////////////////////////////////////////////
// Observation
//////////////////////////////////////////////////////////////
observe_update_base(lm, N_features, xtrue, *R, ftag,
da_table, ftag_visible, z, &Nf_visible, zf, idf,
zn, particles, weights);
dt = (lm[4*(index+1)] - lm[4*(index)]) / 1000.0;
T += dt*1000.0;
predict_update_VP_base(wp, N_waypoints, V, *Q, dt, NPARTICLES, xtrue, &iwp, &G, particles);
//////////////////////////////////////////////////////////////
}
index++;
}
cleanup_landmarks(&ftag, &da_table);
cleanup_measurements(&z, &zf, &zn, &idf, &ftag_visible);
*particles_ = particles;
*weights_ = weights;
}
void fastslam1_sim_active_VP(double* lm, const size_t lm_rows, const size_t lm_cols,
const size_t N_features, Particle **particles_, double** weights_)
{
const size_t N_waypoints = 0;
double *wp = NULL; // dummy
Particle *particles;
double *weights;
Vector3d xtrue = {-67.6493, -41.7142, 35.5*M_PI/180};
setup_initial_particles_and_pose(&particles, &weights, &xv, &Pv, NPARTICLES, N_features, xtrue);
setup_initial_Q_R(); // modifies global variables
int *ftag;
int *da_table;
setup_landmarks(&ftag, &da_table, N_features);
Vector2d *z; // This is a dynamic array of Vector2d - see https://stackoverflow.com/a/13597383/5616591
Vector2d *zf;
Vector2d *zn;
int *idf, *ftag_visible;
setup_measurements(&z, &zf, &zn, &idf, &ftag_visible, N_features);
// if ( SWITCH_PREDICT_NOISE ) {
// printf("Sampling from predict noise usually OFF for FastSLAM 2.0\n");
// }
srand( SWITCH_SEED_RANDOM );
#ifdef __AVX2__
avx_xorshift128plus_init(1,1);
#endif
double dt = DT_CONTROLS; // change in time btw predicts
double dtsum = 0; // change in time since last observation
double T = lm[0];
int iwp = 0; // index to first waypoint
double G = 0; // initialize steering angle
double V = 0.0;//V_;
size_t Nf_visible = 0;
// Main loop
int index = 0;
while ( index < lm_rows -1 ) {
//////////////////////////////////////////////////////////////////
// Prediction
//////////////////////////////////////////////////////////////////
dt = (lm[4*(index+1)] - lm[4*(index)]) / 1000.0;
V = lm[4*(index) +2];
G = lm[4*(index) +3];
predict_update_VP_active(wp, N_waypoints, V, *Q, dt, NPARTICLES, xtrue, &iwp, &G,particles);
/////////////////////////////////////////////////////////////////
//Update time
dtsum = dtsum + dt;
T += dt*1000.0;
// Observation condition
if ( lm[4*(index+1) + 1] > -1 ) {
dtsum = 0;
///Setup z, ftag_visible, Nf_visible
Nf_visible = 0;
while ( lm[4*(index+1) + 1] > -1 ) {
index++;
double r = lm[4*(index) +2];
double phi = lm[4*(index) +3];
z[Nf_visible][0] = r;
z[Nf_visible][1] = pi_to_pi_base(phi - M_PI_2);
ftag_visible[Nf_visible] = lm[4*(index) +1] -1;
Nf_visible++;
}
//////////////////////////////////////////////////////////////
// Observation
//////////////////////////////////////////////////////////////
observe_update(lm, N_features, xtrue, *R, ftag,
da_table, ftag_visible, z, &Nf_visible, zf, idf,
zn, particles, weights);
dt = (lm[4*(index+1)] - lm[4*(index)]) / 1000.0;
T += dt*1000.0;
predict_update_VP_active(wp, N_waypoints, V, *Q, dt, NPARTICLES, xtrue, &iwp, &G, particles);
//////////////////////////////////////////////////////////////
}
index++;
}
cleanup_landmarks(&ftag, &da_table);
cleanup_measurements(&z, &zf, &zn, &idf, &ftag_visible);
*particles_ = particles;
*weights_ = weights;
}
|
/*
Проект разрабатывается в рамках курсовой работы по теме: "Разработка объектной программы для задачи управления группами в социальных сетях".
Это основной файл для клиентского кода.
Выполнил студент 3-го курса Железняк Аркадий в 2018г.
*/
#include <iostream>
#include "SocNetwork.h"
using namespace std;
int main()
{
setlocale(LC_ALL, "ru");
SocNetwork Net; // Сеть будет инициализироваться автоматически, в дальнейшем можно будет создавать несколько соц.сетей(наверное).
// Здесь позже будет консольное меню, а в дальнейшем GUI.
system("pause");
return 0;
}
|
#include <iostream>
#include "cryptobox/core/HSM.hpp"
using namespace cryptobox;
void print(std::vector<unsigned char> const& v) {
for (auto const c : v)
printf("%c", c);
printf("\n");
}
int main() {
// simple test for the very basic functionality: create/sign/verify
auto hsm = std::make_shared<cryptobox::HSM>("default.crb");
// create
auto handle = hsm->Create();
assert(handle.has_value() && "Assert Valid Handle");
// sign
std::vector<unsigned char> msg = {'t', 'e', 'x', 't'};
auto signedMsg = hsm->Sign(handle.value(), msg);
assert(signedMsg.has_value() && "Assert Valid Signed Msg");
// verify
auto status = hsm->Verify(handle.value(), signedMsg.value());
assert(status.has_value() && "Assert Valid Status");
auto const& statusval = status.value();
assert(statusval.first==HSM::Accepted && "Assert Status Valid == Accepted");
// check the original msg and extracted from signedMsg match
assert(statusval.second.size() == msg.size() && "Assert Original Msg size == Verified");
for (int i=0; i<msg.size(); i++)
assert(status.value().second[i] == msg[i] && "Assert Original msg == Verified msg");
printf("all tests passed!\n");
return 0;
}
|
int Tree[maxn];
inline int lowbit(int x){
return (x&-x);
}
void add (int x,int value){
for(int i=x;i<=maxn;i+=lowbit(i)){
Tree[i]+=value;
}
}
int get(int x){
int sum=0;
for(int i=x;i;i-=lowbit(i)){
sum+=Tree[i];
}
return sum;
}
|
#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;
int n, a[11111], p[11111];
int main() {
freopen(".in", "r", stdin);
freopen(".out", "w", stdout);
int T;
cin >> T;
for (int _=0;_<T;_++) {
cin >> n;
for (int i = 0; i < n - 1; i++) {
cin >> a[i];
a[i] --;
p[i] = i;
}
p[n - 1] = n - 1;
bool good = false;
do {
good = true;
for (int i = 0; i < n - 1; i++) {
for (int k = i + 1; k < n ; k++)
if (k < a[i]) {
if (p[k] * (a[i] - i) >= p[i] * (a[i] - i)+ (k - i) * (p[a[i]] - p[i])) {
good = false;
break;
}
} else
if (k > a[i]) {
if (p[k] * (a[i] - i) > p[i] * (a[i] - i) + (k - i) * (p[a[i]] - p[i])) {
good = false;
break;
}
}
}
if (good) break;
} while (next_permutation(p, p + n));
printf("Case #%d:", _ + 1);
if (!good) {
p[n-1] += p[n-1];
p[0] -= p[n-1];
good = false;
do {
good = true;
for (int i = 0; i < n - 1; i++) {
for (int k = i + 1; k < n ; k++)
if (k < a[i]) {
if (p[k] * (a[i] - i) >= p[i] * (a[i] - i)+ (k - i) * (p[a[i]] - p[i])) {
good = false;
break;
}
} else
if (k > a[i]) {
if (p[k] * (a[i] - i) > p[i] * (a[i] - i) + (k - i) * (p[a[i]] - p[i])) {
good = false;
break;
}
}
}
if (good) break;
} while (next_permutation(p, p + n));
if (!good) {
cout << " Impossible" << endl;
} else{
for (int i = 0; i < n; i++) cout << " " << p[i] + 1;
cout << endl;
}
} else{
for (int i = 0; i < n; i++) cout << " " << p[i] + 1;
cout << endl;
}
}
return 0;
}
|
#include<iostream>
#include "quick_sort.cpp"
int main(){
int arr[7] = {12, 2, 56, 23, 11, 45, 12};
quickSort(arr, 0, 6);
for(int i = 0; i < 7; ++i){
std::cout<<arr[i]<<" ";
}
return 0;
}
|
#include "../include/Group.h"
unsigned int CAE::Part::_id = 0;
void CAE::Part::update()
{
auto[x, y, w, h] = box;
quad[0].position = sf::Vector2f(x, y);
quad[1].position = sf::Vector2f(x + w, y);
quad[2].position = sf::Vector2f(x + w, y + h);
quad[3].position = sf::Vector2f(x, y + h);
quad[4].position = sf::Vector2f(x, y);
node[0].setPosition({x + w / 2, y});
node[1].setPosition({x + w, y + h / 2});
node[2].setPosition({x + w / 2, y + h});
node[3].setPosition({x, y + h / 2});
}
CAE::Part::Part(sf::FloatRect _rect) : box(_rect), id(++_id), quad(sf::LinesStrip, 5),
color(sf::Color::Transparent),
IsSelected(false)
{
auto[x, y, w, h] = box;
node[0] = ScaleNode({x + w / 2, y}, 0);
node[1] = ScaleNode({x + w, y + h / 2}, 1);
node[2] = ScaleNode({x + w / 2, y + h}, 2);
node[3] = ScaleNode({x, y + h / 2}, 3);
update();
setSelected(false);
}
CAE::Part::Part(sf::IntRect _rect) : box(_rect), id(++_id), quad(sf::LinesStrip, 5),
color(sf::Color::Transparent),
IsSelected(false)
{
auto[x, y, w, h] = box;
node[0] = ScaleNode({x + w / 2, y}, 0);
node[1] = ScaleNode({x + w, y + h / 2}, 1);
node[2] = ScaleNode({x + w / 2, y + h}, 2);
node[3] = ScaleNode({x, y + h / 2}, 3);
update();
setSelected(false);
}
void CAE::Part::changeColor(sf::Color c)
{
if(c != color)
{
for(int i = 0; i < 5; ++i)
quad[i].color = c;
color = c;
}
}
void CAE::Part::setRect(sf::FloatRect rect)
{
box = rect;
update();
}
void CAE::Group::save(json& j)
{
j["name"] = name;
j["isVisible"] = isEnable;
j["animSpeed"] = animSpeed;
j["scale"] = scale;
int count = 0;
auto& data = j["data"];
for(auto& part : parts)
{
data[count]["pos"]["x"] = part->box.left;
data[count]["pos"]["y"] = part->box.top;
data[count]["width"] = part->box.width;
data[count]["height"] = part->box.height;
++count;
}
}
void CAE::Group::load(json& j)
{
name = j.at("name").get<std::string>();
isEnable = j.at("isVisible").get<bool>();
animSpeed = j.at("animSpeed").get<float>();
scale = j.at("scale").get<float>();
int id = 1;
for(auto& part : j["data"])
{
sf::FloatRect r{};
r.top = part["pos"]["y"].get<float>();
r.left = part["pos"]["x"].get<float>();
r.width = part["width"].get<float>();
r.height = part["height"].get<float>();
this->parts.emplace_back(std::make_shared<Part>(r));
++id;
}
}
|
// system includes
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
// testing 3
// global namespace declaration
using namespace std;
// forward declaration
void EndOfExecPause();
void PrintVector( const vector< int >& inVec);
bool IsOdd ( int );
// --------------------------------------------------------------------------
// main
// --------------------------------------------------------------------------
int main ()
{
int userIn;
vector< int > vecIn;
while ( cin >> userIn )
{
vecIn.push_back( userIn );
}
PrintVector( vecIn );
vector< int >::iterator myIter;
myIter = remove_if( vecIn.begin() , vecIn.end() , IsOdd );
cout << "\n\n";
//vecIn.resize( myIter - vecIn.begin() );
vecIn.erase( myIter, vecIn.end());
PrintVector( vecIn );
EndOfExecPause();
return 0;
}
// --------------------------------------------------------------------------
// PrintVector
// --------------------------------------------------------------------------
void
PrintVector(const vector< int >& inVec)
{
cout << "[ " ;
for ( int i=0; i<inVec.size(); ++i)
cout << inVec[i] << " ";
cout << "]\n";
return;
}
// --------------------------------------------------------------------------
// EndOfExecPause
// --------------------------------------------------------------------------
void
EndOfExecPause()
{
cin.clear();
string a;
cin >> a;
cin >> a;
}
// --------------------------------------------------------------------------
// IsOdd
// --------------------------------------------------------------------------
bool
IsOdd (int i)
{
return i & 0x01; // ((i%2)==1);
}
|
#ifndef __GAME_H__
#define __GAME_H__
/*
===============================================================================
Public game interface with methods to run the game.
===============================================================================
*/
// RAVEN BEGIN
// bgeisler: moved into scripts directory
// default scripts
#define SCRIPT_DEFAULTDEFS "scripts/defs.script"
#define SCRIPT_DEFAULT "scripts/main.script"
// RAVEN END
#define SCRIPT_DEFAULTFUNC "doom_main"
//STRADEX START: DON'T PORT YET
// class idPlayer; //added for Coop (if crash or something, then we're moving to game_local)
//STRADEX END
struct gameReturn_t {
char sessionCommand[MAX_STRING_CHARS]; // "map", "disconnect", "victory", etc
int consistencyHash; // used to check for network game divergence
int health;
int heartRate;
int stamina;
int combat;
bool syncNextGameFrame; // used when cinematics are skipped to prevent session from simulating several game frames to
// keeGetMapLoadingGUIp the game time in sync with real time
};
enum allowReply_t {
ALLOW_YES = 0,
ALLOW_BADPASS, // core will prompt for password and connect again
ALLOW_NOTYET, // core will wait with transmitted message
ALLOW_NO // core will abort with transmitted message
};
enum escReply_t {
ESC_IGNORE = 0, // do nothing
ESC_MAIN, // start main menu GUI
ESC_GUI // set an explicit GUI
};
enum demoState_t {
DEMO_NONE,
DEMO_RECORDING,
DEMO_PLAYING
};
enum demoReliableGameMessage_t {
DEMO_RECORD_CLIENTNUM,
DEMO_RECORD_EXCLUDE,
DEMO_RECORD_COUNT
};
//
// these defines work for all startsounds from all entity types
// make sure to change script/doom_defs.script if you add any channels, or change their order
//
typedef enum {
SND_CHANNEL_ANY = SCHANNEL_ANY,
SND_CHANNEL_VOICE = SCHANNEL_ONE,
SND_CHANNEL_VOICE2,
SND_CHANNEL_BODY,
SND_CHANNEL_BODY2,
SND_CHANNEL_BODY3,
SND_CHANNEL_WEAPON,
SND_CHANNEL_ITEM,
SND_CHANNEL_HEART,
SND_CHANNEL_DEMONIC,
SND_CHANNEL_RADIO,
// internal use only. not exposed to script or framecommands.
SND_CHANNEL_AMBIENT,
SND_CHANNEL_DAMAGE
// RAVEN BEGIN
// bdube: added custom to tell us where the end of the predefined list is
,
SND_CHANNEL_POWERUP,
SND_CHANNEL_POWERUP_IDLE,
SND_CHANNEL_MP_ANNOUNCER,
SND_CHANNEL_CUSTOM
// RAVEN END
} gameSoundChannel_t;
// RAVEN BEGIN
// bdube: forward reference
class rvClientEffect;
// RAVEN END
struct ClientStats_t {
bool isLastPredictFrame;
bool isLagged;
bool isNewFrame;
};
typedef struct userOrigin_s {
idVec3 origin;
int followClient;
} userOrigin_t;
class idGame {
public:
virtual ~idGame() {}
// Initialize the game for the first time.
// RAVEN BEGIN
// jsinger: attempt to eliminate cross-DLL allocation issues
#ifdef RV_UNIFIED_ALLOCATOR
virtual void Init( void *(*allocator)( size_t size ), void (*deallocator)( void *ptr ), size_t (*msize)( void *ptr ) ) = 0;
#else
virtual void Init( void ) = 0;
#endif
// Shut down the entire game.
virtual void Shutdown( void ) = 0;
// Set the local client number. Distinguishes listen ( == 0 ) / dedicated ( == -1 )
virtual void SetLocalClient( int clientNum ) = 0;
// Sets the user info for a client.
// The game can modify the user info in the returned dictionary pointer, server will forward back.
virtual const idDict * SetUserInfo( int clientNum, const idDict &userInfo, bool isClient ) = 0;
// Retrieve the game's userInfo dict for a client.
virtual const idDict * GetUserInfo( int clientNum ) = 0;
// Sets the user info for a viewer.
// The game can modify the user info in the returned dictionary pointer.
virtual const idDict * RepeaterSetUserInfo( int clientNum, const idDict &userInfo ) = 0;
// Checks to see if a client is active
virtual bool IsClientActive( int clientNum ) = 0;
// The game gets a chance to alter userinfo before they are emitted to server.
virtual void ThrottleUserInfo( void ) = 0;
// Sets the serverinfo at map loads and when it changes.
virtual void SetServerInfo( const idDict &serverInfo ) = 0;
// The session calls this before moving the single player game to a new level.
virtual const idDict & GetPersistentPlayerInfo( int clientNum ) = 0;
// The session calls this right before a new level is loaded.
virtual void SetPersistentPlayerInfo( int clientNum, const idDict &playerInfo ) = 0;
// Loads a map and spawns all the entities.
virtual void InitFromNewMap( const char *mapName, idRenderWorld *renderWorld, bool isServer, bool isClient, int randseed ) = 0;
// Loads a map from a savegame file.
virtual bool InitFromSaveGame( const char *mapName, idRenderWorld *renderWorld, idFile *saveGameFile ) = 0;
// Saves the current game state, the session may have written some data to the file already.
// RAVEN BEGIN
// mekberg: added saveTypes
virtual void SaveGame( idFile *saveGameFile, saveType_t saveType = ST_REGULAR ) = 0;
// RAVEN END
// Shut down the current map.
virtual void MapShutdown( void ) = 0;
// Caches media referenced from in key/value pairs in the given dictionary.
virtual void CacheDictionaryMedia( const idDict *dict ) = 0;
// Spawns the player entity to be used by the client.
virtual void SpawnPlayer( int clientNum ) = 0;
// RAVEN BEGIN
// Runs a game frame, may return a session command for level changing, etc
// lastCatchupFrame is always true except if we are running several game frames in a row and this one is not the last one
// subsystems which can tolerate skipping frames will not run during those catchup frames
// several game frames in a row happen when game + renderer time goes above the tick time ( 16ms )
virtual gameReturn_t RunFrame( const usercmd_t *clientCmds, int activeEditors, bool lastCatchupFrame, int serverGameFrame ) = 0;
virtual void MenuFrame( void ) = 0;
// RAVEN END
// Runs a repeater frame
virtual void RepeaterFrame( const userOrigin_t *clientOrigins, bool lastCatchupFrame, int serverGameFrame ) = 0;
// Makes rendering and sound system calls to display for a given clientNum.
virtual bool Draw( int clientNum ) = 0;
// Let the game do it's own UI when ESCAPE is used
virtual escReply_t HandleESC( idUserInterface **gui ) = 0;
// get the games menu if appropriate ( multiplayer )
virtual idUserInterface * StartMenu() = 0;
// When the game is running it's own UI fullscreen, GUI commands are passed through here
// return NULL once the fullscreen UI mode should stop, or "main" to go to main menu
virtual const char * HandleGuiCommands( const char *menuCommand ) = 0;
// main menu commands not caught in the engine are passed here
virtual void HandleMainMenuCommands( const char *menuCommand, idUserInterface *gui ) = 0;
// Early check to deny connect.
virtual allowReply_t ServerAllowClient( int clientId, int numClients, const char *IP, const char *guid, const char *password, const char *privatePassword, char reason[MAX_STRING_CHARS] ) = 0;
// Connects a client.
virtual void ServerClientConnect( int clientNum, const char *guid ) = 0;
// Spawns the player entity to be used by the client.
virtual void ServerClientBegin( int clientNum ) = 0;
// Disconnects a client and removes the player entity from the game.
virtual void ServerClientDisconnect( int clientNum ) = 0;
// Writes initial reliable messages a client needs to recieve when first joining the game.
virtual void ServerWriteInitialReliableMessages( int clientNum ) = 0;
// Early check to deny connect.
virtual allowReply_t RepeaterAllowClient( int clientId, int numClients, const char *IP, const char *guid, bool repeater, const char *password, const char *privatePassword, char reason[MAX_STRING_CHARS] ) = 0;
// Connects a client.
virtual void RepeaterClientConnect( int clientNum ) = 0;
// Spawns the player entity to be used by the client.
virtual void RepeaterClientBegin( int clientNum ) = 0;
// Disconnects a client and removes the player entity from the game.
virtual void RepeaterClientDisconnect( int clientNum ) = 0;
// Writes initial reliable messages a client needs to recieve when first joining the game.
virtual void RepeaterWriteInitialReliableMessages( int clientNum ) = 0;
// Writes a snapshot of the server game state for the given client.
virtual void ServerWriteSnapshot( int clientNum, int sequence, idBitMsg &msg, dword *clientInPVS, int numPVSClients, int lastSnapshotFrame ) = 0;
// Patches the network entity states at the server with a snapshot for the given client.
virtual bool ServerApplySnapshot( int clientNum, int sequence ) = 0;
// Processes a reliable message from a client.
virtual void ServerProcessReliableMessage( int clientNum, const idBitMsg &msg ) = 0;
// Patches the network entity states at the server with a snapshot for the given client.
virtual bool RepeaterApplySnapshot( int clientNum, int sequence ) = 0;
// Processes a reliable message from a client.
virtual void RepeaterProcessReliableMessage( int clientNum, const idBitMsg &msg ) = 0;
// Reads a snapshot and updates the client game state.
virtual void ClientReadSnapshot( int clientNum, int snapshotSequence, const int gameFrame, const int gameTime, const int dupeUsercmds, const int aheadOfServer, const idBitMsg &msg ) = 0;
// Patches the network entity states at the client with a snapshot.
virtual bool ClientApplySnapshot( int clientNum, int sequence ) = 0;
// Processes a reliable message from the server.
virtual void ClientProcessReliableMessage( int clientNum, const idBitMsg &msg ) = 0;
// Runs prediction on entities at the client.
virtual gameReturn_t ClientPrediction( int clientNum, const usercmd_t *clientCmds, bool lastPredictFrame = true, ClientStats_t *cs = NULL ) = 0;
// RAVEN BEGIN
// ddynerman: client game frame
virtual void ClientRun( void ) = 0;
virtual void ClientEndFrame( void ) = 0;
// jshepard: rcon password check
virtual void ProcessRconReturn( bool success ) = 0;
// RAVEN END
virtual bool ValidateServerSettings( const char *map, const char *gameType ) = 0;
// Returns a summary of stats for a given client
virtual void GetClientStats( int clientNum, char *data, const int len ) = 0;
// Switch a player to a particular team
virtual void SwitchTeam( int clientNum, int team ) = 0;
virtual bool DownloadRequest( const char *IP, const char *guid, const char *paks, char urls[ MAX_STRING_CHARS ] ) = 0;
// return true to allow download from the built-in http server
virtual bool HTTPRequest( const char *IP, const char *file, bool isGamePak ) = 0;
// RAVEN BEGIN
// jscott: for the effects system
virtual void StartViewEffect( int type, float time, float scale ) = 0;
virtual rvClientEffect* PlayEffect( const idDecl *effect, const idVec3& origin, const idMat3& axis, bool loop = false, const idVec3& endOrigin = vec3_origin, bool broadcast = false, bool predictBit = false, effectCategory_t category = EC_IGNORE, const idVec4& effectTint = vec4_one ) = 0;
virtual void GetPlayerView( idVec3 &origin, idMat3 &axis ) = 0;
virtual const idVec3 GetCurrentGravity( const idVec3& origin, const idMat3& axis ) const = 0;
virtual void Translation( trace_t &trace, idVec3 &source, idVec3 &dest, idTraceModel *trm, int clipMask ) = 0;
virtual void SpawnClientMoveable ( const char* name, int lifetime, const idVec3& origin, const idMat3& axis, const idVec3& velocity, const idVec3& angular_velocity ) = 0;
// bdube: debugging stuff
virtual void DebugSetString ( const char* name, const char* value ) = 0;
virtual void DebugSetFloat ( const char* name, float value ) = 0;
virtual void DebugSetInt ( const char* name, int value ) = 0;
virtual const char* DebugGetStatString ( const char* name ) = 0;
virtual int DebugGetStatInt ( const char* name ) = 0;
virtual float DebugGetStatFloat ( const char* name ) = 0;
virtual bool IsDebugHudActive ( void ) const = 0;
// rjohnson: for new note taking mechanism
virtual bool GetPlayerInfo( idVec3 &origin, idMat3 &axis, int PlayerNum = -1, idAngles *deltaViewAngles = NULL, int reqClientNum = -1 ) = 0;
virtual void SetPlayerInfo( idVec3 &origin, idMat3 &axis, int PlayerNum = -1 ) = 0;
virtual bool PlayerChatDisabled( int clientNum ) = 0;
virtual void SetViewComments( const char *text = 0 ) = 0;
// ddynerman: utility functions
virtual void GetPlayerName( int clientNum, char* name ) = 0;
virtual void GetPlayerClan( int clientNum, char* clan ) = 0;
virtual void SetFriend( int clientNum, bool isFriend ) = 0;
virtual const char* GetLongGametypeName( const char* gametype ) = 0;
virtual void ReceiveRemoteConsoleOutput( const char* output ) = 0;
// rjohnson: entity usage stats
virtual void ListEntityStats( const idCmdArgs &args ) = 0;
// shouchard: for ban lists
virtual void RegisterClientGuid( int clientNum, const char *guid ) = 0;
virtual bool IsMultiplayer( void ) = 0;
// mekberg: added
virtual bool InCinematic( void ) = 0;
// mekberg: so banlist can be populated outside of multiplayer game
virtual void PopulateBanList( idUserInterface* hud ) = 0;
virtual void RemoveGuidFromBanList( const char *guid ) = 0;
// mekberg: interface
virtual void AddGuidToBanList( const char *guid ) = 0;
virtual const char* GetGuidByClientNum( int clientNum ) = 0;
// jshepard: updating player post-menu
virtual void UpdatePlayerPostMainMenu( void ) = 0;
virtual void ResetRconGuiStatus( void ) = 0;
// RAVEN END
// RAVEN BEGIN
// mwhitlock: Dynamic memory consolidation
#if defined(_RV_MEM_SYS_SUPPORT)
virtual void FlushBeforelevelLoad( void ) = 0;
#endif
// RAVEN END
// Set the demo state.
virtual void SetDemoState( demoState_t state, bool serverDemo, bool timeDemo ) = 0;
// Set the repeater state; engine will call this with true for isRepeater if this is a repeater, and true for serverIsRepeater if we are connected to a repeater
virtual void SetRepeaterState( bool isRepeater, bool serverIsRepeater ) = 0;
// Writes current network info to a file (used as initial state for demo recording).
virtual void WriteNetworkInfo( idFile* file, int clientNum ) = 0;
// Reads current network info from a file (used as initial state for demo playback).
virtual void ReadNetworkInfo( int gameTime, idFile* file, int clientNum ) = 0;
// Let gamecode decide if it wants to accept demos from older releases of the engine.
virtual bool ValidateDemoProtocol( int minor_ref, int minor ) = 0;
// Write a snapshot for server demo recording.
virtual void ServerWriteServerDemoSnapshot( int sequence, idBitMsg &msg, int lastSnapshotFrame ) = 0;
// Read a snapshot from a server demo stream.
virtual void ClientReadServerDemoSnapshot( int sequence, const int gameFrame, const int gameTime, const idBitMsg &msg ) = 0;
// Write a snapshot for repeater clients.
virtual void RepeaterWriteSnapshot( int clientNum, int sequence, idBitMsg &msg, dword *clientInPVS, int numPVSClients, const userOrigin_t &pvs_origin, int lastSnapshotFrame ) = 0;
// Done writing snapshots for repeater clients.
virtual void RepeaterEndSnapshots( void ) = 0;
// Read a snapshot from a repeater stream.
virtual void ClientReadRepeaterSnapshot( int sequence, const int gameFrame, const int gameTime, const int aheadOfServer, const idBitMsg &msg ) = 0;
// Get the currently followed client in demo playback
virtual int GetDemoFollowClient( void ) = 0;
// Build a bot's userCmd
virtual void GetBotInput( int clientNum, usercmd_t &userCmd ) = 0;
// Return the name of a gui to override the loading screen
virtual const char * GetLoadingGui( const char *mapDeclName ) = 0;
// Set any additional gui variables needed by the loading screen
virtual void SetupLoadingGui( idUserInterface *gui ) = 0;
};
extern idGame * game;
/*
===============================================================================
Public game interface with methods for in-game editing.
===============================================================================
*/
struct refSound_t {
// RAVEN BEGIN
int referenceSoundHandle; // this is the interface to the sound system, created
// with idSoundWorld::AllocSoundEmitter() when needed
// RAVEN END
idVec3 origin;
// RAVEN BEGIN
// jscott: for Miles doppler
idVec3 velocity;
// RAVEN END
int listenerId; // SSF_PRIVATE_SOUND only plays if == listenerId from PlaceListener
// no spatialization will be performed if == listenerID
const idSoundShader * shader; // this really shouldn't be here, it is a holdover from single channel behavior
float diversity; // 0.0 to 1.0 value used to select which
// samples in a multi-sample list from the shader are used
bool waitfortrigger; // don't start it at spawn time
soundShaderParms_t parms; // override volume, flags, etc
};
enum {
TEST_PARTICLE_MODEL = 0,
TEST_PARTICLE_IMPACT,
TEST_PARTICLE_MUZZLE,
TEST_PARTICLE_FLIGHT,
TEST_PARTICLE_SELECTED
};
class idEntity;
class idMD5Anim;
// RAVEN BEGIN
// bdube: more forward declarations
class idProgram;
class idInterpreter;
class idThread;
typedef void (*debugInfoProc_t) ( const char* classname, const char* name, const char* value, void *userdata );
// RAVEN END
// FIXME: this interface needs to be reworked but it properly separates code for the time being
class idGameEdit {
public:
virtual ~idGameEdit( void ) {}
// These are the canonical idDict to parameter parsing routines used by both the game and tools.
virtual bool ParseSpawnArgsToRenderLight( const idDict *args, renderLight_t *renderLight );
virtual void ParseSpawnArgsToRenderEntity( const idDict *args, renderEntity_t *renderEntity );
virtual void ParseSpawnArgsToRefSound( const idDict *args, refSound_t *refSound );
// Animation system calls for non-game based skeletal rendering.
virtual idRenderModel * ANIM_GetModelFromEntityDef( const char *classname );
virtual const idVec3 &ANIM_GetModelOffsetFromEntityDef( const char *classname );
virtual idRenderModel * ANIM_GetModelFromEntityDef( const idDict *args );
virtual idRenderModel * ANIM_GetModelFromName( const char *modelName );
virtual const idMD5Anim * ANIM_GetAnimFromEntityDef( const char *classname, const char *animname );
// RAVEN BEGIN
// bdube: added
// scork: added 'const' qualifiers so other stuff would compile
virtual const idMD5Anim * ANIM_GetAnimFromEntity( const idEntity* ent, int animNum );
virtual float ANIM_GetAnimPlaybackRateFromEntity ( idEntity* ent, int animNum );
virtual const char* ANIM_GetAnimNameFromEntity ( const idEntity* ent, int animNum );
// RAVEN END
virtual int ANIM_GetNumAnimsFromEntityDef( const idDict *args );
virtual const char * ANIM_GetAnimNameFromEntityDef( const idDict *args, int animNum );
virtual const idMD5Anim * ANIM_GetAnim( const char *fileName );
virtual int ANIM_GetLength( const idMD5Anim *anim );
virtual int ANIM_GetNumFrames( const idMD5Anim *anim );
// RAVEN BEGIN
// bdube: added
virtual const char * ANIM_GetFilename( const idMD5Anim* anim );
virtual int ANIM_ConvertFrameToTime ( const idMD5Anim* anim, int frame );
virtual int ANIM_ConvertTimeToFrame ( const idMD5Anim* anim, int time );
// RAVEN END
virtual void ANIM_CreateAnimFrame( const idRenderModel *model, const idMD5Anim *anim, int numJoints, idJointMat *frame, int time, const idVec3 &offset, bool remove_origin_offset );
virtual idRenderModel * ANIM_CreateMeshForAnim( idRenderModel *model, const char *classname, const char *animname, int frame, bool remove_origin_offset );
// RAVEN BEGIN
// mekberg: access to animationlib functions for radiant
virtual void FlushUnusedAnims( void );
// RAVEN END
// Articulated Figure calls for AF editor and Radiant.
virtual bool AF_SpawnEntity( const char *fileName );
virtual void AF_UpdateEntities( const char *fileName );
virtual void AF_UndoChanges( void );
virtual idRenderModel * AF_CreateMesh( const idDict &args, idVec3 &meshOrigin, idMat3 &meshAxis, bool &poseIsSet );
// Entity selection.
virtual void ClearEntitySelection( void );
virtual int GetSelectedEntities( idEntity *list[], int max );
virtual void AddSelectedEntity( idEntity *ent );
// Selection methods
virtual void TriggerSelected();
// Entity defs and spawning.
virtual const idDict * FindEntityDefDict( const char *name, bool makeDefault = true ) const;
virtual void SpawnEntityDef( const idDict &args, idEntity **ent );
virtual idEntity * FindEntity( const char *name ) const;
virtual const char * GetUniqueEntityName( const char *classname ) const;
// Entity methods.
virtual void EntityGetOrigin( idEntity *ent, idVec3 &org ) const;
virtual void EntityGetAxis( idEntity *ent, idMat3 &axis ) const;
virtual void EntitySetOrigin( idEntity *ent, const idVec3 &org );
virtual void EntitySetAxis( idEntity *ent, const idMat3 &axis );
virtual void EntityTranslate( idEntity *ent, const idVec3 &org );
// RAVEN BEGIN
// scork: const-qualified 'ent' so other things would compile
virtual const idDict * EntityGetSpawnArgs( const idEntity *ent ) const;
// RAVEN END
virtual void EntityUpdateChangeableSpawnArgs( idEntity *ent, const idDict *dict );
virtual void EntityChangeSpawnArgs( idEntity *ent, const idDict *newArgs );
virtual void EntityUpdateVisuals( idEntity *ent );
virtual void EntitySetModel( idEntity *ent, const char *val );
virtual void EntityStopSound( idEntity *ent );
virtual void EntityDelete( idEntity *ent );
virtual void EntitySetColor( idEntity *ent, const idVec3 color );
// RAVEN BEGIN
// bdube: added
virtual const char* EntityGetName ( idEntity* ent ) const;
virtual int EntityToSafeId( idEntity* ent ) const;
virtual idEntity * EntityFromSafeId( int safeID) const;
virtual void EntitySetSkin ( idEntity *ent, const char* temp ) const;
virtual void EntityClearSkin ( idEntity *ent ) const;
virtual void EntityShow ( idEntity* ent ) const;
virtual void EntityHide ( idEntity* ent ) const;
virtual void EntityGetBounds ( idEntity* ent, idBounds &bounds ) const;
virtual int EntityPlayAnim ( idEntity* ent, int animNum, int time, int blendtime );
virtual void EntitySetFrame ( idEntity* ent, int animNum, int frame, int time, int blendtime );
virtual void EntityStopAllEffects ( idEntity* ent );
virtual void EntityGetDelta ( idEntity* ent, int fromTime, int toTime, idVec3& delta );
virtual void EntityRemoveOriginOffset ( idEntity* ent, bool remove );
virtual const char* EntityGetClassname ( idEntity* ent ) const;
virtual bool EntityIsDerivedFrom ( idEntity* ent, const char* classname ) const;
virtual renderEntity_t* EntityGetRenderEntity ( idEntity* ent );
// scork: accessor functions for various utils
virtual idEntity * EntityGetNextTeamEntity( idEntity *pEnt ) const;
virtual void GetPlayerInfo( idVec3 &v3Origin, idMat3 &mat3Axis, int PlayerNum = -1, idAngles *deltaViewAngles = NULL ) const;
virtual void SetPlayerInfo( idVec3 &v3Origin, idMat3 &mat3Axis, int PlayerNum = -1 ) const;
virtual void EntitySetName( idEntity* pEnt, const char *psName );
// RAVEN END
// Player methods.
virtual bool PlayerIsValid() const;
virtual void PlayerGetOrigin( idVec3 &org ) const;
virtual void PlayerGetAxis( idMat3 &axis ) const;
virtual void PlayerGetViewAngles( idAngles &angles ) const;
virtual void PlayerGetEyePosition( idVec3 &org ) const;
// RAVEN BEGIN
// bdube: new game edit stuff
virtual bool PlayerTraceFromEye ( trace_t &results, float length, int contentMask );
// Effect methods
virtual void EffectRefreshTemplate ( const idDecl *effect ) const;
// Light entity methods
virtual void LightSetParms ( idEntity* ent, int maxLevel, int currentLevel, float radius );
// Common editing functions
virtual int GetGameTime ( int *previous = NULL ) const;
virtual void SetGameTime ( int time ) const;
virtual bool TracePoint ( trace_t &results, const idVec3 &start, const idVec3 &end, int contentMask ) const;
virtual void CacheDictionaryMedia ( const idDict* dict ) const;
virtual void SetCamera ( idEntity* camera ) const;
// RAVEN BEGIN
// bdube: added
virtual int GetGameEntityRegisterTime ( void ) const;
virtual idEntity* GetFirstSpawnedEntity ( void ) const;
virtual idEntity* GetNextSpawnedEntity ( idEntity* from ) const;
// jscott: added
virtual void DrawPlaybackDebugInfo( void );
virtual void RecordPlayback( const usercmd_t &cmd, idEntity *source );
virtual bool PlayPlayback( void );
virtual void ShutdownPlaybacks( void );
// RAVEN END
// Script methods
virtual int ScriptGetStatementLineNumber ( idProgram* program, int instructionPointer ) const;
virtual const char* ScriptGetStatementFileName ( idProgram* program, int instructionPointer ) const;
virtual int ScriptGetStatementOperator ( idProgram* program, int instructionPointer ) const;
virtual void* ScriptGetCurrentFunction ( idInterpreter* interpreter ) const;
virtual const char* ScriptGetCurrentFunctionName ( idInterpreter* interpreter ) const;
virtual int ScriptGetCallstackDepth ( idInterpreter* interpreter ) const;
virtual void* ScriptGetCallstackFunction ( idInterpreter* interpreter, int depth ) const;
virtual const char* ScriptGetCallstackFunctionName ( idInterpreter* interpreter, int depth ) const;
virtual int ScriptGetCallstackStatement ( idInterpreter* interpreter, int depth ) const;
virtual bool ScriptIsReturnOperator ( int op ) const;
virtual const char* ScriptGetRegisterValue ( idInterpreter* interpreter, const char* varname, int callstackDepth ) const;
virtual idThread* ScriptGetThread ( idInterpreter* interpreter ) const;
// Thread methods
virtual int ThreadGetCount ( void );
virtual idThread* ThreadGetThread ( int index );
virtual const char* ThreadGetName ( idThread* thread );
virtual int ThreadGetNumber ( idThread* thread );
virtual const char* ThreadGetState ( idThread* thread );
// Class externals for entity viewer
virtual void GetClassDebugInfo ( const idEntity* entity, debugInfoProc_t proc, void* userdata );
// In game map editing support.
virtual const idDict * MapGetEntityDict( const char *name ) const;
virtual void MapSave( const char *path = NULL ) const;
// RAVEN BEGIN
// rjohnson: added entity export
virtual bool MapHasExportEntities( void ) const;
// scork: simple func for the sound editor
virtual const char* MapLoaded( void ) const;
// cdr: AASTactical
virtual idAASFile* GetAASFile( int i );
// jscott: added entries for memory tracking
virtual void PrintMemInfo( MemInfo *mi );
virtual size_t ScriptSummary( const idCmdArgs &args ) const;
virtual size_t ClassSummary( const idCmdArgs &args ) const;
virtual size_t EntitySummary( const idCmdArgs &args ) const;
// RAVEN END
virtual void MapSetEntityKeyVal( const char *name, const char *key, const char *val ) const ;
virtual void MapCopyDictToEntity( const char *name, const idDict *dict ) const;
virtual int MapGetUniqueMatchingKeyVals( const char *key, const char *list[], const int max ) const;
virtual void MapAddEntity( const idDict *dict ) const;
virtual int MapGetEntitiesMatchingClassWithString( const char *classname, const char *match, const char *list[], const int max ) const;
virtual void MapRemoveEntity( const char *name ) const;
virtual void MapEntityTranslate( const char *name, const idVec3 &v ) const;
};
extern idGameEdit * gameEdit;
// RAVEN BEGIN
// bdube: game logging
/*
===============================================================================
Game Log.
===============================================================================
*/
class rvGameLog {
public:
virtual ~rvGameLog( void ) {}
virtual void Init ( void ) = 0;
virtual void Shutdown ( void ) = 0;
virtual void BeginFrame ( int time ) = 0;
virtual void EndFrame ( void ) = 0;
virtual void Set ( const char* keyword, int value ) = 0;
virtual void Set ( const char* keyword, float value ) = 0;
virtual void Set ( const char* keyword, const char* value ) = 0;
virtual void Set ( const char* keyword, bool value ) = 0;
virtual void Add ( const char* keyword, int value ) = 0;
virtual void Add ( const char* keyword, float value ) = 0;
};
extern rvGameLog * gameLog;
#define GAMELOG_SET(x,y) {if(g_gamelog.GetBool())gameLog->Set ( x, y );}
#define GAMELOG_ADD(x,y) {if(g_gamelog.GetBool())gameLog->Add ( x, y );}
#define GAMELOG_SET_IF(x,y,z) {if(g_gamelog.GetBool()&&(z))gameLog->Set ( x, y );}
#define GAMELOG_ADD_IF(x,y,z) {if(g_gamelog.GetBool()&&(z))gameLog->Add ( x, y );}
// RAVEN END
/*
===============================================================================
Game API.
===============================================================================
*/
// 4: network demos
// 5: fix idNetworkSystem ( memory / DLL boundary related )
// 6: more network demo APIs
// 7: cleanups
// 8: added some demo functions to the FS class
// 9: bump up for 1.1 patch
// 9: Q4 Gold
// 10: Patch 2 changes
// 14: 1.3
// 26: 1.4 beta
// 30: 1.4
// 37: 1.4.2
const int GAME_API_VERSION = 37;
struct gameImport_t {
int version; // API version
idSys * sys; // non-portable system services
idCommon * common; // common
idCmdSystem * cmdSystem; // console command system
idCVarSystem * cvarSystem; // console variable system
idFileSystem * fileSystem; // file system
idNetworkSystem * networkSystem; // network system
idRenderSystem * renderSystem; // render system
idSoundSystem * soundSystem; // sound system
idRenderModelManager * renderModelManager; // render model manager
idUserInterfaceManager * uiManager; // user interface manager
idDeclManager * declManager; // declaration manager
idAASFileManager * AASFileManager; // AAS file manager
idCollisionModelManager * collisionModelManager; // collision model manager
// RAVEN BEGIN
// jscott:
rvBSEManager * bse; // Raven effects system
// RAVEN END
// RAVEN BEGIN
// dluetscher: added the following members to exchange memory system data
#ifdef _RV_MEM_SYS_SUPPORT
rvHeapArena * heapArena; // main heap arena that all other heaps use
rvHeap * systemHeapArray[MAX_SYSTEM_HEAPS]; // array of pointers to rvHeaps that are common to idLib, Game, and executable
#endif
// RAVEN END
};
struct gameExport_t {
int version; // API version
idGame * game; // interface to run the game
idGameEdit * gameEdit; // interface for in-game editing
// RAVEN BEGIN
// bdube: added
rvGameLog * gameLog; // interface for game logging
// RAVEN END
};
extern "C" {
typedef gameExport_t * (*GetGameAPI_t)( gameImport_t *import );
}
#endif /* !__GAME_H__ */
|
#include <string>
#include <unordered_map>
using namespace std;
int lengthOfLongestSubstring(string s) {
string longest_substr;
string cur_substr;
int start_pos = 0;
unordered_map<char, int> tmp;
for (int i = 0; i < s.size(); ++i) {
std::unordered_map<char, int>::const_iterator iter = tmp.find(s[i]);
if (iter != tmp.end()) {
cur_substr = s.substr(start_pos, i - start_pos);
if (cur_substr.size() > longest_substr.size()) {
longest_substr = cur_substr;
}
start_pos = iter->second + 1;
tmp.clear();
}
tmp[s[i]] = i;
}
cur_substr = s.substr(start_pos, s.size() - start_pos);
if (cur_substr.size() > longest_substr.size())
longest_substr = cur_substr;
return longest_substr.size();
}
int lengthOfLongestSubstring2(string s) {
int idx_array[256];
for (int i = 0; i < 256; ++i) {
idx_array[i] = -1;
}
int max_len = 0;
int start_pos = 0;
for (int i = 0; i < s.size(); ++i) {
if (idx_array[s[i]] != -1) {
max_len = (i - start_pos > max_len ? i - start_pos : max_len);
if (idx_array[s[i]] + 1 > start_pos) {
start_pos = idx_array[s[i]] + 1;
}
idx_array[s[i]] = -1;
}
idx_array[s[i]] = i;
}
max_len = (s.size() - start_pos > max_len ? s.size() - start_pos : max_len);
return max_len;
}
|
#ifndef PLATFORMER_CONNECT_GAME_STATE_H
#define PLATFORMER_CONNECT_GAME_STATE_H
#include "Game.h"
namespace platformer {
/**
* Game state that attempts to find and connect to other devices to play
* the competitive multiplayer mode.
*/
class ConnectGameState : public GameState {
private:
// Duration in millis between game ticks.
static const int TICK_RATE = 500;
// The currently running game.
Game *game;
public:
/**
* Constructs a new {@link ConnectGameState}.
*
* @param game the currently running {@link Game}.
*/
explicit ConnectGameState(Game *game);
/**
* {@inheritDoc}
*/
void onButtonAPress() override;
/**
* {@inheritDoc}
*/
void onButtonBPress() override;
/**
* {@inheritDoc}
*/
void onButtonABPress() override;
/**
* {@inheritDoc}
*/
void onMessage(ByteBuf &in) override;
/**
* {@inheritDoc}
*/
void run() override;
/**
* Stops attempting to find and connect with other devices, and switches
* the game back to running the menu {@link MenuGameState}.
*/
void stop();
};
}
#endif //PLATFORMER_CONNECT_GAME_STATE_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; 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.
*
* George Refseth, rfz@opera.com
*/
#ifndef MBOXIMPORTER_H
# define MBOXIMPORTER_H
# include "adjunct/m2/src/import/importer.h"
# include "adjunct/desktop_util/treemodel/optreemodel.h"
class FolderRecursor;
class MboxImporter: public Importer,
public OpTreeModel::SortListener
{
public:
MboxImporter();
virtual ~MboxImporter();
OP_STATUS Init();
OP_STATUS ImportMessages();
protected:
virtual BOOL OnContinueImport();
virtual void OnCancelImport();
virtual void ImportMboxAsync();
virtual void SetImportItems(const OpVector<ImporterModelItem>& items);
BOOL IsValidMboxFile(const uni_char* file_name);
OP_STATUS InitLookAheadBuffers();
OP_STATUS InitMboxFile();
void InitSingleMbox(const OpString& mbox, OpString& virtual_path, INT32 index = -1);
OP_STATUS SetRecursorRoot(const OpString& root);
INT32 GetOrCreateFolder(const OpString& root, OpFile& mbox, OpString& virtual_path);
// Implementing OpTreeModel::SortListener API
INT32 OnCompareItems(OpTreeModel* tree_model, OpTreeModelItem* item0, OpTreeModelItem* item1);
protected:
OpFile* m_mboxFile;
char* m_raw;
INT32 m_raw_length;
INT32 m_raw_capacity;
char* m_one_line_ahead;
char* m_two_lines_ahead;
BOOL m_finished_reading;
BOOL m_found_start_of_message;
BOOL m_found_start_of_next_message;
BOOL m_found_valid_message;
FolderRecursor * m_folder_recursor;
};
#endif //MBOXIMPORTER_H
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: DataKind.h
* Author: frankiezafe
*
* Created on June 14, 2016, 8:51 PM
*/
#ifndef DATAKIND_H
#define DATAKIND_H
class DataKind {
public:
const int & i;
const std::bitset< 8 > & bits;
DataKind(): i(_i), bits(_bits) {
_i = 0;
render_bits();
}
DataKind( int value ): i(_i), bits(_bits) {
_i = value;
render_bits();
}
inline void set( int pos, bool v ) {
if ( v ) { _bits[ pos ] = 1; }
else { _bits[ pos ] = 0; }
render_int();
}
bool operator [] ( int pos ) {
if ( _bits[ pos ] == 1 ) {
return true;
}
return false;
}
void operator = ( int value ) {
_i = value;
render_bits();
}
void operator = ( std::bitset< 8 > & value ) {
for ( int n = 0; n < 8; ++n ) {
_bits[ n ] = value[ n ];
}
render_int();
}
void operator = ( DataKind value ) {
_i = value.i;
render_bits();
}
bool operator == ( DataKind value ) {
return ( _i == value.i );
}
bool operator != ( DataKind value ) {
return ( _i != value.i );
}
protected:
int _i;
std::bitset< 8 > _bits;
void render_bits() {
std::bitset< 8 > tmpb( _i );
for ( int n = 0; n < 8; ++n ) {
_bits[ n ] = tmpb[ n ];
}
}
void render_int() {
_i = (int) _bits.to_ulong();
}
};
#endif /* DATAKIND_H */
|
#pragma once
#include <fstream>
#include <list>
#include <ctime>
#include "kissnet.h"
#include "crossword_board.hpp"
#define CROSSWORD_PORT "3333"
class crossword_server
{
public:
crossword_server(std::ifstream& crossword_data, const std::string& port = CROSSWORD_PORT);
~crossword_server();
void start();
void run();
private:
// Helper functions
void process_message(int size, int type, kissnet::tcp_socket *sender);
void send_board(kissnet::tcp_socket *user);
void process_update(int x, int y, char ch);
void process_cursor(int x, int y, int d, kissnet::tcp_socket *sender);
void process_pause(char on);
void process_solve_word(int clue, int dir);
void process_solve_letter(int x, int y);
std::string make_packet(const std::string& data, int type);
void broadcast_packet(std::string packet, kissnet::tcp_socket *sender = 0);
void remove(kissnet::tcp_socket *sock);
// Member Variables
kissnet::tcp_socket servsock;
std::list<kissnet::tcp_socket*> connsocks;
kissnet::socket_set set;
crossword_board board;
std::string port;
time_t start_time, elapsed_time;
bool paused;
char header[3];
char data[256*256];
};
|
#ifndef INPUTVARIABLE_H
#define INPUTVARIABLE_H
#include "variable.h"
class InputVariable : public Variable
{
public:
/**
* @brief Constructor
* @param name Name of the variable
*/
InputVariable(std::string name);
/**
* @brief Methode creating the fuzzy set definitions needed by the input variable
* @param file File to write the definitions to
*/
virtual void createFuzzySets(std::ofstream& file);
/**
* @brief Methode creating the input streams in the Kernel code
* @param file File to write to
*/
void createInputStream(std::ofstream& file);
/**
* @brief Methode creating the call to the correct fuzzification function for every term of the input variable.
* @param file File to write to
*/
void createFuzzyfication(std::ofstream& file);
private:
/// @brief Forbidden standard constructor
InputVariable();
};
#endif
|
/**
* Copyright (c) 2021, Timothy Stack
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Timothy Stack 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 REGENTS 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 REGENTS 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 "config.h"
#ifdef __CYGWIN__
# include <iostream>
# include <sstream>
#endif
#include "fmt/format.h"
#include "paths.hh"
namespace lnav {
namespace paths {
#ifdef __CYGWIN__
char*
windows_to_unix_file_path(char* input)
{
if (input == nullptr) {
return nullptr;
}
std::string file_path;
file_path.assign(input);
// Replace the slashes
std::replace(file_path.begin(),
file_path.end(),
WINDOWS_FILE_PATH_SEPARATOR,
UNIX_FILE_PATH_SEPARATOR);
// Convert the drive letter to lowercase
std::transform(
file_path.begin(),
file_path.begin() + 1,
file_path.begin(),
[](unsigned char character) { return std::tolower(character); });
// Remove the colon
const auto drive_letter = file_path.substr(0, 1);
const auto remaining_path = file_path.substr(2, file_path.size() - 2);
file_path = drive_letter + remaining_path;
std::stringstream stringstream;
stringstream << "/cygdrive/";
stringstream << file_path;
return const_cast<char*>(stringstream.str().c_str());
}
#endif
ghc::filesystem::path
dotlnav()
{
#ifdef __CYGWIN__
auto home_env = windows_to_unix_file_path(getenv("APPDATA"));
#else
auto home_env = getenv("HOME");
#endif
auto xdg_config_home = getenv("XDG_CONFIG_HOME");
if (home_env != nullptr) {
auto home_path = ghc::filesystem::path(home_env);
if (ghc::filesystem::is_directory(home_path)) {
auto home_lnav = home_path / ".lnav";
if (ghc::filesystem::is_directory(home_lnav)) {
return home_lnav;
}
if (xdg_config_home != nullptr) {
auto xdg_path = ghc::filesystem::path(xdg_config_home);
if (ghc::filesystem::is_directory(xdg_path)) {
return xdg_path / "lnav";
}
}
auto home_config = home_path / ".config";
if (ghc::filesystem::is_directory(home_config)) {
return home_config / "lnav";
}
return home_lnav;
}
}
return ghc::filesystem::current_path();
}
ghc::filesystem::path
workdir()
{
auto subdir_name = fmt::format(FMT_STRING("lnav-user-{}-work"), getuid());
auto tmp_path = ghc::filesystem::temp_directory_path();
return tmp_path / ghc::filesystem::path(subdir_name);
}
} // namespace paths
} // namespace lnav
|
/**
* Copyright 2015 ViajeFacil
* @author Hugo Ferrando Seage
* @author Fernando Saavedra
*/
#include "./fecha.hpp"
Fecha::Fecha() : dia_(0), mes_(0), anio_(0) {}
Fecha::Fecha(int dia, int mes, int anio)
: dia_(dia), mes_(mes), anio_(anio) {}
Fecha::~Fecha() {}
void Fecha::setFecha(int dia, int mes, int anio) {
dia_ = dia;
mes_ = mes;
anio_ = anio;
}
void Fecha::setDia(int dia) { dia_ = dia; }
void Fecha::setMes(int mes) { mes_ = mes; }
void Fecha::setAnio(int anio) { anio_ = anio; }
int Fecha::getDia() { return dia_; }
int Fecha::getMes() { return mes_; }
int Fecha::getAnio() { return anio_; }
|
#include "cpptest.h"
CPPTEST_CONTEXT("core.threads.test.cpptest.TA_Thread_CppTest/core.thread.test.cpptest/src/Thread.cpp");
CPPTEST_TEST_SUITE_INCLUDED_TO("core.threads.test.cpptest.TA_Thread_CppTest/core.thread.test.cpptest/src/Thread.cpp");
class TestSuite_getCurrentThreadId_35492577 : public CppTest_TestSuite
{
public:
CPPTEST_TEST_SUITE(TestSuite_getCurrentThreadId_35492577);
CPPTEST_TEST(test_getCurrentThreadId_1);
CPPTEST_TEST_SUITE_END();
void setUp();
void tearDown();
void test_getCurrentThreadId_1();
};
CPPTEST_TEST_SUITE_REGISTRATION(TestSuite_getCurrentThreadId_35492577);
void TestSuite_getCurrentThreadId_35492577::setUp()
{
FUNCTION_ENTRY( "setUp" );
FUNCTION_EXIT;
}
void TestSuite_getCurrentThreadId_35492577::tearDown()
{
FUNCTION_ENTRY( "tearDown" );
FUNCTION_EXIT;
}
/* CPPTEST_TEST_CASE_BEGIN test_getCurrentThreadId_1 */
/* CPPTEST_TEST_CASE_CONTEXT unsigned int TA_Base_Core::Thread::getCurrentThreadId(void) */
void TestSuite_getCurrentThreadId_35492577::test_getCurrentThreadId_1()
{
FUNCTION_ENTRY( "test_getCurrentThreadId_1" );
/* Pre-condition initialization */
/* Tested function call */
unsigned _return = ::TA_Base_Core::Thread::getCurrentThreadId();
/* Post-condition check */
CPPTEST_POST_CONDITION_UINTEGER("unsigned int _return", ( _return ));
FUNCTION_EXIT;
}
/* CPPTEST_TEST_CASE_END test_getCurrentThreadId_1 */
|
#include <iostream>
using namespace std;
int main()
{
int a = 1;
const int b = 11;
//int * p = &b; //error,const object can`t just be reference by a pointer point to a const object
const int * pc;
pc= &a;
int * const cpa = &a;
const int * const cpb = &b;
int * const cpca = &a;
const int * const cpcb = &b;
//(*pc)++;
++a;
(*cpa)++;
(*cpca)++;
//(*cpb)++; //error
//(*cpcb)++;//error,cpcb after dereference is a const object
cout << a << endl;
return 0;
}
|
#include <benchmark/benchmark.h>
#include <dummy.h>
using namespace dummy;
static void DummyBenchmark(benchmark::State &state) {
Dummy dummy(4);
for (auto _ : state) {
benchmark::DoNotOptimize(dummy.GetDummy());
}
state.SetComplexityN(state.range(0));
state.SetItemsProcessed(state.iterations());
}
BENCHMARK(DummyBenchmark)
->Repetitions(4)
->Range(1 << 4, 1 << 20)
->RangeMultiplier(2)
->Unit(benchmark::kNanosecond)
->ReportAggregatesOnly(true)
->Complexity(benchmark::o1);
BENCHMARK_MAIN();
|
#include "../include/command_interface.h"
#include "../lib/rapidxml/rapidxml.hpp"
using namespace rapidxml;
using namespace std;
bool command_interface::load_device_params(string config_dir_name)
{
unscaled_device_params tmp_device_params;
xml_document<> doc;
ifstream file(config_dir_name);
stringstream buffer;
buffer << file.rdbuf();
file.close();
string content(buffer.str());
doc.parse<0>(&content[0]);
xml_node<> *pRoot = doc.first_node(); // This is the <document/> node
for(xml_node<> *pNode=pRoot->first_node(); pNode; pNode=pNode->next_sibling())
{
/* Load Device data */
if (!strcmp(pNode->name(), "Device"))
{
tmp_device_params.activeLayer = atof(pNode->first_attribute("activeLayer")->value());
tmp_device_params.T = atof(pNode->first_attribute("T")->value());
tmp_device_params.dt = atof(pNode->first_attribute("dt")->value());
tmp_device_params.V_a = atof(pNode->first_attribute("V_a")->value());
tmp_device_params.V_build = atof(pNode->first_attribute("V_build")->value());
tmp_device_params.G_suns = atof(pNode->first_attribute("G_suns")->value());
tmp_device_params.W_a = atof(pNode->first_attribute("W_a")->value())*C_q;
tmp_device_params.W_c = atof(pNode->first_attribute("W_c")->value())*C_q;
tmp_device_params.epsilon = atof(pNode->first_attribute("epsilon")->value());
/* Copy parameters */
layers_params.device = tmp_device_params;
return true;
}
}
return false;
}
bool command_interface::load_stack_params(string config_dir_name)
{
bool isLayerOK = false;
xml_document<> doc;
ifstream file(config_dir_name);
stringstream buffer;
buffer << file.rdbuf();
file.close();
string content(buffer.str());
doc.parse<0>(&content[0]);
xml_node<> *pRoot = doc.first_node(); // This is the <document/> node
for(xml_node<> *pNode=pRoot->first_node(); pNode; pNode=pNode->next_sibling())
{
if (strcmp(pNode->name(), "Device") && strcmp(pNode->name(), "Settings")) // Only layers
isLayerOK = load_layer_params(config_dir_name, pNode->name());
}
return isLayerOK;
}
bool command_interface::load_layer_params(string config_dir_name, string layer_name)
{
unscaled_layer_params tmp_layer_params;
const char * tmp_layer_name = layer_name.c_str();;
xml_document<> doc;
ifstream file(config_dir_name);
stringstream buffer;
buffer << file.rdbuf();
file.close();
string content(buffer.str());
doc.parse<0>(&content[0]);
xml_node<> *pRoot = doc.first_node(); // This is the <document/> node
for(xml_node<> *pNode=pRoot->first_node(); pNode; pNode=pNode->next_sibling())
{
/* Load solar cell data */
if (!strcmp(pNode->name(), tmp_layer_name))
{
tmp_layer_params.name = tmp_layer_name;
tmp_layer_params.ID = layers_params.stack_params.size();
tmp_layer_params.E_r = atof(pNode->first_attribute("E_r")->value());
tmp_layer_params.u_n = atof(pNode->first_attribute("u_n")->value());
tmp_layer_params.u_p = atof(pNode->first_attribute("u_p")->value());
tmp_layer_params.u_a = atof(pNode->first_attribute("u_a")->value());
tmp_layer_params.u_c = atof(pNode->first_attribute("u_c")->value());
tmp_layer_params.L = atof(pNode->first_attribute("L")->value());
tmp_layer_params.N_points = atof(pNode->first_attribute("N_points")->value());
tmp_layer_params.C_nc = atof(pNode->first_attribute("C_nc")->value());
tmp_layer_params.C_nv = atof(pNode->first_attribute("C_nv")->value());
tmp_layer_params.C_pc = atof(pNode->first_attribute("C_pc")->value());
tmp_layer_params.C_pv = atof(pNode->first_attribute("C_pv")->value());
tmp_layer_params.T_n = atof(pNode->first_attribute("T_n")->value());
tmp_layer_params.T_p = atof(pNode->first_attribute("T_p")->value());
tmp_layer_params.E_c = atof(pNode->first_attribute("E_c")->value())*C_q;
tmp_layer_params.E_v = atof(pNode->first_attribute("E_v")->value())*C_q;
tmp_layer_params.E_tn = atof(pNode->first_attribute("E_tn")->value())*C_q;
tmp_layer_params.E_tp = atof(pNode->first_attribute("E_tp")->value())*C_q;
tmp_layer_params.W_tn = atof(pNode->first_attribute("W_tn")->value())*C_q;
tmp_layer_params.W_tp = atof(pNode->first_attribute("W_tp")->value())*C_q;
tmp_layer_params.N_D = atof(pNode->first_attribute("N_D")->value());
tmp_layer_params.N_A = atof(pNode->first_attribute("N_A")->value());
tmp_layer_params.N_0 = atof(pNode->first_attribute("N_0")->value());
tmp_layer_params.N_tn = atof(pNode->first_attribute("N_tn")->value());
tmp_layer_params.N_tp = atof(pNode->first_attribute("N_tp")->value());
tmp_layer_params.N_c = atof(pNode->first_attribute("N_c")->value());
tmp_layer_params.N_v = atof(pNode->first_attribute("N_v")->value());
tmp_layer_params.ksi = atof(pNode->first_attribute("ksi")->value());
// Calculate variables
tmp_layer_params.E_g = abs(tmp_layer_params.E_c - tmp_layer_params.E_v);
tmp_layer_params.n_int = tmp_layer_params.N_c*exp((-tmp_layer_params.E_g) / (2*C_k_B*layers_params.device.T));
/* Copy parameters */
layers_params.stack_params.push_back(tmp_layer_params);
return true;
}
}
return false;
}
bool command_interface::load_settings(string config_dir_name)
{
struct settings tmp_settings;
xml_document<> doc;
ifstream file(config_dir_name);
stringstream buffer;
buffer << file.rdbuf();
file.close();
string content(buffer.str());
doc.parse<0>(&content[0]);
xml_node<> *pRoot = doc.first_node(); // This is the <document/> node
for(xml_node<> *pNode=pRoot->first_node(); pNode; pNode=pNode->next_sibling())
{
/* Load settings */
if (!strcmp(pNode->name(), "Settings"))
{
tmp_settings.first_pulse = atof(pNode->first_attribute("first_pulse_time")->value());
tmp_settings.second_pulse = atof(pNode->first_attribute("second_pulse_time")->value());
tmp_settings.third_pulse = atof(pNode->first_attribute("third_pulse_time")->value());
tmp_settings.V_max = atof(pNode->first_attribute("V_max")->value());
tmp_settings.V_min = atof(pNode->first_attribute("V_min")->value());
tmp_settings.V_step = atof(pNode->first_attribute("V_step")->value());
tmp_settings.V_rate = atof(pNode->first_attribute("V_rate")->value());
/* Copy parameters */
settings = tmp_settings;
return true;
}
}
return false;
}
bool command_interface::load_generation_file(string gener_dir_name)
{
double tmp_x, tmp_G;
vector<double> tmp_x_vector, tmp_G_vector;
ifstream file(gener_dir_name);
if(file.fail())
return false; // No file
while(!file.eof()) // Read file untill the last line
{
file >> tmp_x >> tmp_G; // read two columns of data
tmp_x_vector.push_back(tmp_x);
tmp_G_vector.push_back(tmp_G);
}
file.close();
/* Copy parameters */
layers_params.x_data = tmp_x_vector;
layers_params.G_data = tmp_G_vector;
return true;
}
|
// 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 _gp_QuaternionSLerp_HeaderFile
#define _gp_QuaternionSLerp_HeaderFile
#include <gp_Quaternion.hxx>
//! Perform Spherical Linear Interpolation of the quaternions,
//! return unit length quaternion.
class gp_QuaternionSLerp
{
public:
//! Compute interpolated quaternion between two quaternions.
//! @param theStart first quaternion
//! @param theEnd second quaternion
//! @param theT normalized interpolation coefficient within 0..1 range,
//! with 0 pointing to theStart and 1 to theEnd.
static gp_Quaternion Interpolate (const gp_Quaternion& theQStart,
const gp_Quaternion& theQEnd,
Standard_Real theT)
{
gp_Quaternion aResult;
gp_QuaternionSLerp aLerp (theQStart, theQEnd);
aLerp.Interpolate (theT, aResult);
return aResult;
}
public:
//! Empty constructor,
gp_QuaternionSLerp() {}
//! Constructor with initialization.
gp_QuaternionSLerp (const gp_Quaternion& theQStart, const gp_Quaternion& theQEnd)
{
Init (theQStart, theQEnd);
}
//! Initialize the tool with Start and End values.
void Init (const gp_Quaternion& theQStart, const gp_Quaternion& theQEnd)
{
InitFromUnit (theQStart.Normalized(), theQEnd.Normalized());
}
//! Initialize the tool with Start and End unit quaternions.
void InitFromUnit (const gp_Quaternion& theQStart, const gp_Quaternion& theQEnd)
{
myQStart = theQStart;
myQEnd = theQEnd;
Standard_Real cosOmega = myQStart.Dot (myQEnd);
if (cosOmega < 0.0)
{
cosOmega = -cosOmega;
myQEnd = -myQEnd;
}
if (cosOmega > 0.9999)
{
cosOmega = 0.9999;
}
myOmega = ACos (cosOmega);
Standard_Real invSinOmega = (1.0 / Sin (myOmega));
myQStart.Scale (invSinOmega);
myQEnd.Scale (invSinOmega);
}
//! Set interpolated quaternion for theT position (from 0.0 to 1.0)
void Interpolate (Standard_Real theT, gp_Quaternion& theResultQ) const
{
theResultQ = myQStart * Sin((1.0 - theT) * myOmega) + myQEnd * Sin (theT * myOmega);
}
private:
gp_Quaternion myQStart;
gp_Quaternion myQEnd;
Standard_Real myOmega;
};
#endif //_gp_QuaternionSLerp_HeaderFile
|
#include "sandtrap.h"
#include "globals.h"
#include "physics.h"
#include "game.h"
#include "math_extra.h"
#include <math.h>
Sandtrap* create_sandtrap(int x1, int x2, int y1, int y2){
Sandtrap* sandtrap = (Sandtrap*) malloc(sizeof(Sandtrap));
sandtrap->type = SANDTRAP;
sandtrap->x1 = x1;
sandtrap->x2 = x2;
sandtrap->y1 = y1;
sandtrap->y2 = y2;
sandtrap->should_draw = 1;
return sandtrap;
}
void do_sandtrap(Physics* next, const Physics* curr, Sandtrap* sandtrap)
{
if (curr->px < sandtrap->x2 && curr->px > sandtrap->x1) {
if (curr->py < sandtrap->y2 && curr->py > sandtrap->y1) {
if (fabs(curr->vy) > 1) {
if (curr->vy > 0) {
next->vy = 1;
} else {
next->vy = -1;
}
}
if (fabs(curr->vy) > 1) {
if (curr->vx > 0) {
next->vx = 1;
} else {
next->vx = -1;
}
}
}
}
if (curr->px < sandtrap->x2 + 4 && curr->px > sandtrap->x1 - 4) {
if (curr->py < sandtrap->y2 + 4 && curr->py > sandtrap->y1 - 4) {
sandtrap->should_draw = 1;
}
}
}
void draw_sandtrap(Sandtrap* sandtrap)
{
if (sandtrap->should_draw) {
uLCD.filled_rectangle(sandtrap->x1,sandtrap->y1,sandtrap->x2,sandtrap->y2,0xFFDDDD);
//don't draw again unless the ball falls in again
sandtrap->should_draw = 0;
}
}
|
//
// This file contains the C++ code from Program 7.2 of
// "Data Structures and Algorithms
// with Object-Oriented Design Patterns in C++"
// by Bruno R. Preiss.
//
// Copyright (c) 1998 by Bruno R. Preiss, P.Eng. All rights reserved.
//
// http://www.pads.uwaterloo.ca/Bruno.Preiss/books/opus4/programs/pgm07_02.cpp
//
#ifndef LISTASARRAY_H_
#define LISTASARRAY_H_
#include <List.h>
#include <Array.h>
#include <Object.h>
#include <Visitor.h>
#include <Iterator.h>
class ListAsArray : public virtual OrderedList
{
protected:
Array<Object*> array;
class Pos;
int CompareTo(const Object& o) const
{
ListAsArray const & l = dynamic_cast<ListAsArray const &>(o);
return (int) (count - l.count);
}
public:
ListAsArray (unsigned int);
// ...
void Insert (Object& object);
Object& operator [] (unsigned int offset) const;
bool IsMember (Object const& object) const;
Object& Find (Object const& object) const;
void Withdraw (Object& object);
void InsertAfter ( Position const& arg, Object& object);
void Withdraw (Position const& arg);
Position& FindPosition (Object const& object) const;
Object& operator [] (Position const& arg) const;
Iterator & NewIterator(void) const;
void Accept(Visitor&) const ;
void InsertBefore (Position const& arg, Object& object);
void Purge(void) ;
~ListAsArray()
{
Purge();
}
friend class Pos;
};
class ListAsArray::Pos : public Position
{
protected:
ListAsArray const& list;
unsigned int offset;
public:
// ...
Pos( ListAsArray const& arg) : list(arg) , offset(0)
{}
Pos( ListAsArray const& arg, unsigned int pos)
: list(arg), offset(pos)
{}
void Reset(void)
{
offset = 0;
}
bool IsDone(void) const
{
return ! (offset < list.count );
}
void operator ++ (void)
{
++ offset;
}
Object& operator*() const
{
return *list.array[offset];
}
friend class ListAsArray;
friend class SortedListAsArray;
};
#endif /*LISTASARRAY_H_*/
|
/*
Author: Manish Kumar
Username: manicodebits
Created: 20:46:06 10-04-2021
*/
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define PI 3.141592653589
#define MOD 1000000007
#define FAST_IO ios_base::sync_with_stdio(false), cin.tie(0)
#define deb(x) cout << "[ " << #x << " = " << x << "] "
void solve()
{
int n;
cin >> n;
vector<int> arr(n + 2);
int total = 0, sum = 0;
for (int i = 0; i < n + 2; i++)
cin >> arr[i], total += arr[i];
sort(arr.begin(), arr.end());
for (int i = 0; i < n; i++)
sum += arr[i];
bool flag = false;
int index = -1;
if (sum == arr[n])
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << "\n";
return;
}
int lastElement = arr[n + 1];
//removing last element
total -= lastElement;
for (int i = 0; i < n + 1; i++)
{
if ((total - arr[i]) == lastElement)
{
index = i;
flag = true;
}
}
if (flag)
{
for (int i = 0; i < n + 1; i++)
{
if (i != index)
cout << arr[i] << " ";
}
}
else
{
cout << "-1";
}
cout << "\n";
}
signed main()
{
FAST_IO;
int t = 1;
cin >> t;
while (t--)
solve();
return 0;
}
|
#ifndef CHAINING__H
#define CHAINING__H
#include <iostream>
#include "LinkedList.cpp" // Your Own Implementation
#include <cstring>
#include <fstream>
#include <cmath>
using namespace std;
class HashC
{
protected:
long tableSize;
int collisions;
int a;
LinkedList<string>* hashTable;
public:
HashC(int _a);
void Load(char* file); // Load a file of Strings into your Hash table
int hash(string); // Given a String, return its hash
void insert(string word); // Takes a hash of 'word' and inserts it into hashTable accordingly
ListItem<string>* lookup(string);
int Collisions(); // Return number of collisions in hashTable
};
#endif
|
#include<bits/stdc++.h>
using namespace std;
int fib_helper(int n,int *ans){
if(n <= 1){
return n;
}
//Check if output already exists.
if(ans[n] != -1){
return ans[n];
}
//Calculate output.
int a = fib_helper(n - 1,ans);
int b = fib_helper(n - 2,ans);
//Save the ouput for future use.
ans[n] = a + b;
return ans[n];
}
int fib(int n){
int *ans = new int[n + 1];
for(int i=0;i<n+1;i++){
ans[i] = -1;
}
return fib_helper(n,ans);
}
int main(){
int n;
cin >> n;
cout << fib(n) << endl;
return 0;
}
|
/*
* @lc app=leetcode.cn id=78 lang=cpp
*
* [78] 子集
*/
// @lc code=start
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
vector<vector<int>> res;
vector<vector<int>> subsets(vector<int>& nums) {
res.clear();
vector<int> track;
backtrack(nums, 0, track);
return res;
}
void backtrack(vector<int>& nums, int start, vector<int>& track){
res.push_back(track);
for(int i=start;i<nums.size();i++)
{
track.push_back(nums[i]);
backtrack(nums, i+1, track);
track.pop_back();
}
}
// vector<vector<int>> subsets(vector<int>& nums) {
// if(nums.empty())return {{}};
// int n = nums.back();
// nums.pop_back();
// vector<vector<int> > res = subsets(nums);
// int size = res.size();
// for(int i=0;i<size;i++){
// res.push_back(res[i]);
// res.back().push_back(n);
// }
// return res;
// }
};
// @lc code=end
|
#ifndef GRAFOS_H
#define GRAFOS_H
#define INF 1073741822
#include <iostream>
using namespace std;
class Grafos
{
private:
int m;
int **W; //Matriz W
int **Q; //Matriz Q
public:
Grafos(void);
void pideleAlUsuarioTuMatriz(void);
void muestraTuMatrizDePesos(void);
void generaMatrizQ(void);
void muestraTuMatrizQ(void);
};
Grafos::Grafos(void){
W = new int*[m];
for(int i=0; i<m ; i++){
W[i] = new int[m];
}
Q = new int*[m];
for(int i=0; i<m ; i++){
Q[i] = new int[m];
}
}
void Grafos::pideleAlUsuarioTuMatriz(void){
int i,j;
cout << "Ingresa el tamaņo de la matriz (cuadrada): ";
cin >> m;
for(i=0;i<m;i++){
for(j=0;j<m;j++){
cout << "W[" << i << "][" << j << "]= ";
cin >> *(*(W+i)+j);
}
}
}
void Grafos::muestraTuMatrizDePesos(void){
int i,j;
cout << endl << "Matriz de pesos:" << endl;
for(i=0; i<m; i++){
for(j=0; j<m; j++)
cout << "\t" << *(*(W+i)+j);
cout << endl;
}
}
void Grafos::muestraTuMatrizQ(void){
int i,j;
cout << endl << "Matriz A:" << endl;
for(i=0; i<m; i++){
for(j=0; j<m; j++)
cout << "\t" << *(*(Q+i)+j);
cout << endl;
}
}
void Grafos::generaMatrizQ(void){
int i,j,k;
for(i=0;i<m;i++){
for(j=0;j<m;j++){
if((*(*(W+i)+j)) == 0)
(*(*(Q+i)+j)) = INF;
else
(*(*(Q+i)+j)) = (*(*(W+i)+j));
}
}
for(k=0; k<m; k++){
for(i=0; i<m; i++){
for(j=0; j<m; j++){
(*(*(Q+i)+j)) = min((*(*(Q+i)+j)),(*(*(Q+i)+k))+(*(*(Q+k)+j)));
}
}
}
}
#endif // GRAFOS_H
|
//
// Created by 송지원 on 2020/05/20.
//
#include <cstdio>
using namespace std;
int main() {
char ch;
scanf("%c", &ch);
printf("%d", ch);
return 0;
}
|
//
// LeftBullet.h
// ClientGame
//
// Created by liuxun on 15/3/4.
//
//
#include "stdafx.h"
#include "Player.h"
#include "Bullet.h"
#ifndef __ClientGame__LeftBullet__
#define __ClientGame__LeftBullet__
class LeftBullet : public Bullet {
public:
LeftBullet(Player* player);
};
#endif /* defined(__ClientGame__LeftBullet__) */
|
/*
* Copyright (c) 2015-2021 Morwenn
* SPDX-License-Identifier: MIT
*/
#ifndef CPPSORT_DETAIL_SORTING_NETWORK_SORT24_H_
#define CPPSORT_DETAIL_SORTING_NETWORK_SORT24_H_
namespace cppsort
{
namespace detail
{
template<>
struct sorting_network_sorter_impl<24u>
{
template<
typename RandomAccessIterator,
typename Compare = std::less<>,
typename Projection = utility::identity,
typename = std::enable_if_t<is_projection_iterator_v<
Projection, RandomAccessIterator, Compare
>>
>
auto operator()(RandomAccessIterator first, RandomAccessIterator,
Compare compare={}, Projection projection={}) const
-> void
{
iter_swap_if(first, first + 20u, compare, projection);
iter_swap_if(first + 1u, first + 12u, compare, projection);
iter_swap_if(first + 2u, first + 16u, compare, projection);
iter_swap_if(first + 3u, first + 23u, compare, projection);
iter_swap_if(first + 4u, first + 6u, compare, projection);
iter_swap_if(first + 5u, first + 10u, compare, projection);
iter_swap_if(first + 7u, first + 21u, compare, projection);
iter_swap_if(first + 8u, first + 14u, compare, projection);
iter_swap_if(first + 9u, first + 15u, compare, projection);
iter_swap_if(first + 11u, first + 22u, compare, projection);
iter_swap_if(first + 13u, first + 18u, compare, projection);
iter_swap_if(first + 17u, first + 19u, compare, projection);
iter_swap_if(first, first + 3u, compare, projection);
iter_swap_if(first + 1u, first + 11u, compare, projection);
iter_swap_if(first + 2u, first + 7u, compare, projection);
iter_swap_if(first + 4u, first + 17u, compare, projection);
iter_swap_if(first + 5u, first + 13u, compare, projection);
iter_swap_if(first + 6u, first + 19u, compare, projection);
iter_swap_if(first + 8u, first + 9u, compare, projection);
iter_swap_if(first + 10u, first + 18u, compare, projection);
iter_swap_if(first + 12u, first + 22u, compare, projection);
iter_swap_if(first + 14u, first + 15u, compare, projection);
iter_swap_if(first + 16u, first + 21u, compare, projection);
iter_swap_if(first + 20u, first + 23u, compare, projection);
iter_swap_if(first, first + 1u, compare, projection);
iter_swap_if(first + 2u, first + 4u, compare, projection);
iter_swap_if(first + 3u, first + 12u, compare, projection);
iter_swap_if(first + 5u, first + 8u, compare, projection);
iter_swap_if(first + 6u, first + 9u, compare, projection);
iter_swap_if(first + 7u, first + 10u, compare, projection);
iter_swap_if(first + 11u, first + 20u, compare, projection);
iter_swap_if(first + 13u, first + 16u, compare, projection);
iter_swap_if(first + 14u, first + 17u, compare, projection);
iter_swap_if(first + 15u, first + 18u, compare, projection);
iter_swap_if(first + 19u, first + 21u, compare, projection);
iter_swap_if(first + 22u, first + 23u, compare, projection);
iter_swap_if(first + 2u, first + 5u, compare, projection);
iter_swap_if(first + 4u, first + 8u, compare, projection);
iter_swap_if(first + 6u, first + 11u, compare, projection);
iter_swap_if(first + 7u, first + 14u, compare, projection);
iter_swap_if(first + 9u, first + 16u, compare, projection);
iter_swap_if(first + 12u, first + 17u, compare, projection);
iter_swap_if(first + 15u, first + 19u, compare, projection);
iter_swap_if(first + 18u, first + 21u, compare, projection);
iter_swap_if(first + 1u, first + 8u, compare, projection);
iter_swap_if(first + 3u, first + 14u, compare, projection);
iter_swap_if(first + 4u, first + 7u, compare, projection);
iter_swap_if(first + 9u, first + 20u, compare, projection);
iter_swap_if(first + 10u, first + 12u, compare, projection);
iter_swap_if(first + 11u, first + 13u, compare, projection);
iter_swap_if(first + 15u, first + 22u, compare, projection);
iter_swap_if(first + 16u, first + 19u, compare, projection);
iter_swap_if(first, first + 7u, compare, projection);
iter_swap_if(first + 1u, first + 5u, compare, projection);
iter_swap_if(first + 3u, first + 4u, compare, projection);
iter_swap_if(first + 6u, first + 11u, compare, projection);
iter_swap_if(first + 8u, first + 15u, compare, projection);
iter_swap_if(first + 9u, first + 14u, compare, projection);
iter_swap_if(first + 10u, first + 13u, compare, projection);
iter_swap_if(first + 12u, first + 17u, compare, projection);
iter_swap_if(first + 16u, first + 23u, compare, projection);
iter_swap_if(first + 18u, first + 22u, compare, projection);
iter_swap_if(first + 19u, first + 20u, compare, projection);
iter_swap_if(first, first + 2u, compare, projection);
iter_swap_if(first + 1u, first + 6u, compare, projection);
iter_swap_if(first + 4u, first + 7u, compare, projection);
iter_swap_if(first + 5u, first + 9u, compare, projection);
iter_swap_if(first + 8u, first + 10u, compare, projection);
iter_swap_if(first + 13u, first + 15u, compare, projection);
iter_swap_if(first + 14u, first + 18u, compare, projection);
iter_swap_if(first + 16u, first + 19u, compare, projection);
iter_swap_if(first + 17u, first + 22u, compare, projection);
iter_swap_if(first + 21u, first + 23u, compare, projection);
iter_swap_if(first + 2u, first + 3u, compare, projection);
iter_swap_if(first + 4u, first + 5u, compare, projection);
iter_swap_if(first + 6u, first + 8u, compare, projection);
iter_swap_if(first + 7u, first + 9u, compare, projection);
iter_swap_if(first + 10u, first + 11u, compare, projection);
iter_swap_if(first + 12u, first + 13u, compare, projection);
iter_swap_if(first + 14u, first + 16u, compare, projection);
iter_swap_if(first + 15u, first + 17u, compare, projection);
iter_swap_if(first + 18u, first + 19u, compare, projection);
iter_swap_if(first + 20u, first + 21u, compare, projection);
iter_swap_if(first + 1u, first + 2u, compare, projection);
iter_swap_if(first + 3u, first + 6u, compare, projection);
iter_swap_if(first + 4u, first + 10u, compare, projection);
iter_swap_if(first + 7u, first + 8u, compare, projection);
iter_swap_if(first + 9u, first + 11u, compare, projection);
iter_swap_if(first + 12u, first + 14u, compare, projection);
iter_swap_if(first + 13u, first + 19u, compare, projection);
iter_swap_if(first + 15u, first + 16u, compare, projection);
iter_swap_if(first + 17u, first + 20u, compare, projection);
iter_swap_if(first + 21u, first + 22u, compare, projection);
iter_swap_if(first + 2u, first + 3u, compare, projection);
iter_swap_if(first + 5u, first + 10u, compare, projection);
iter_swap_if(first + 6u, first + 7u, compare, projection);
iter_swap_if(first + 8u, first + 9u, compare, projection);
iter_swap_if(first + 13u, first + 18u, compare, projection);
iter_swap_if(first + 14u, first + 15u, compare, projection);
iter_swap_if(first + 16u, first + 17u, compare, projection);
iter_swap_if(first + 20u, first + 21u, compare, projection);
iter_swap_if(first + 3u, first + 4u, compare, projection);
iter_swap_if(first + 5u, first + 7u, compare, projection);
iter_swap_if(first + 10u, first + 12u, compare, projection);
iter_swap_if(first + 11u, first + 13u, compare, projection);
iter_swap_if(first + 16u, first + 18u, compare, projection);
iter_swap_if(first + 19u, first + 20u, compare, projection);
iter_swap_if(first + 4u, first + 6u, compare, projection);
iter_swap_if(first + 8u, first + 10u, compare, projection);
iter_swap_if(first + 9u, first + 12u, compare, projection);
iter_swap_if(first + 11u, first + 14u, compare, projection);
iter_swap_if(first + 13u, first + 15u, compare, projection);
iter_swap_if(first + 17u, first + 19u, compare, projection);
iter_swap_if(first + 5u, first + 6u, compare, projection);
iter_swap_if(first + 7u, first + 8u, compare, projection);
iter_swap_if(first + 9u, first + 10u, compare, projection);
iter_swap_if(first + 11u, first + 12u, compare, projection);
iter_swap_if(first + 13u, first + 14u, compare, projection);
iter_swap_if(first + 15u, first + 16u, compare, projection);
iter_swap_if(first + 17u, first + 18u, compare, projection);
}
template<typename DifferenceType=std::ptrdiff_t>
static constexpr auto index_pairs()
-> std::array<utility::index_pair<DifferenceType>, 120>
{
return {{
{0, 20}, {1, 12}, {2, 16}, {3, 23}, {4, 6}, {5, 10}, {7, 21}, {8, 14}, {9, 15}, {11, 22}, {13, 18}, {17, 19},
{0, 3}, {1, 11}, {2, 7}, {4, 17}, {5, 13}, {6, 19}, {8, 9}, {10, 18}, {12, 22}, {14, 15}, {16, 21}, {20, 23},
{0, 1}, {2, 4}, {3, 12}, {5, 8}, {6, 9}, {7, 10}, {11, 20}, {13, 16}, {14, 17}, {15, 18}, {19, 21}, {22, 23},
{2, 5}, {4, 8}, {6, 11}, {7, 14}, {9, 16}, {12, 17}, {15, 19}, {18, 21},
{1, 8}, {3, 14}, {4, 7}, {9, 20}, {10, 12}, {11, 13}, {15, 22}, {16, 19},
{0, 7}, {1, 5}, {3, 4}, {6, 11}, {8, 15}, {9, 14}, {10, 13}, {12, 17}, {16, 23}, {18, 22}, {19, 20},
{0, 2}, {1, 6}, {4, 7}, {5, 9}, {8, 10}, {13, 15}, {14, 18}, {16, 19}, {17, 22}, {21, 23},
{2, 3}, {4, 5}, {6, 8}, {7, 9}, {10, 11}, {12, 13}, {14, 16}, {15, 17}, {18, 19}, {20, 21},
{1, 2}, {3, 6}, {4, 10}, {7, 8}, {9, 11}, {12, 14}, {13, 19}, {15, 16}, {17, 20}, {21, 22},
{2, 3}, {5, 10}, {6, 7}, {8, 9}, {13, 18}, {14, 15}, {16, 17}, {20, 21},
{3, 4}, {5, 7}, {10, 12}, {11, 13}, {16, 18}, {19, 20},
{4, 6}, {8, 10}, {9, 12}, {11, 14}, {13, 15}, {17, 19},
{5, 6}, {7, 8}, {9, 10}, {11, 12}, {13, 14}, {15, 16}, {17, 18},
}};
}
};
}}
#endif // CPPSORT_DETAIL_SORTING_NETWORK_SORT24_H_
|
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
//매크로 함수 정의
#define INF 1000 //무한대 값
#define TRUE 1
#define FALSE 0
#define MAX_VERTICES 20 //최대 점점 개수
//전역 변수
int distance[MAX_VERTICES]; //시작정점으로부터의 최단 경로 거리
int found[MAX_VERTICES]; //방문한 정점 표시
//필요한 함수 헤더 정의
void shortest_path(int, int, int**);
int choose(int[], int, int[]);
int main() {
//파일 열기
FILE *fp = fopen("sp3.txt", "r");
//파일에서 배열 크기 입력받기
int n = 0; int m = 0;
fscanf(fp, "%d", &n);
fscanf(fp, "%d", &m);
//배열 생성
int **weight;
weight = (int**)malloc(sizeof(int*)*n);
for (int i = 0; i < n; i++) {
weight[i] = (int*)malloc(sizeof(int)*n);
}
//배열 초기화
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
weight[i][j] = INF;
}
}
//방향 에지와 가중치 입력받기
int v0, v1, num;
for (int i = 0; i < m; i++) {
fscanf(fp, "%d", &v0);
fscanf(fp, "%d", &v1);
fscanf(fp, "%d", &num);
weight[v0][v1] = num;
}
fclose(fp);
//결과 출력
printf("입력파일 = \"sp3.txt\"");
printf("\nv0로부터의 최단경로 :");
shortest_path(0, n, weight);
for (int i = 0; i < n; i++) {
printf("%d ", distance[i]);
}
}
//Dijkstra의 최단경로 찾는 함수
void shortest_path(int start, int n, int** weight) {
int i, u, w;
//시작정점으로부터의 distance 업데이트
for (i = 0; i < n; i++) {
distance[i] = weight[start][i];
found[i] = FALSE;
}
//시작 정점 관련 값들 초기화
found[start] = TRUE;
distance[start] = 0;
//새 정점 found에 포함하고 그 정점 기준으로 distance 업데이트
for (i = 0; i < n - 2; i++){
u = choose(distance, n, found);
found[u] = TRUE;
for (w = 0; w < n; w++) {
if (!found[w])
if (distance[u] + weight[u][w] < distance[w])
distance[w] = distance[u] + weight[u][w];
}
}
}
//인접정점 중 distance 최소인 정점 찾기
int choose(int distance[], int n, int found[]) {
int i, min, minpos;
min = INT_MAX;
minpos = -1;
for (i = 0; i < n; i++) {
if (distance[i] < min && !found[i]) {
min = distance[i];
minpos = i;
}
}
return minpos;
}
|
#include "GameResultManager.h"
//-------------------------------------------------------
//--コンストラクタ・デストラクタ
GameResultManager::GameResultManager( Drawer* drawer, InputChecker* inputChecker, Sounder* sounder, Player* player ) : SceneManager( drawer, inputChecker, sounder ){
_player = player;
_BGMsounded = false;
_pushed = false;
_gameOverWaitCount = 0;
_enemyImage = { SCREEN_WIDTH_CENTER, SCREEN_HEIGHT_CENTER, SCREEN_WIDTH_CENTER - 1, SCREEN_HEIGHT_CENTER - 1 };
}
GameResultManager::~GameResultManager( ) {
_drawer->SetAlpha( 255 ); //フェードアウト後のアルファ値を元に戻す
_drawer->SetDrawBlendMode( DX_BLENDMODE_ALPHA, _drawer->GetAlpha( ) );
delete( _player );
}
//-------------------------------------------------------
//-------------------------------------------------------
//--------------------------------------------
//--ゲッター
//--------------------------------------------
//--------------------------------------------
//--------------------------------------------
//--セッター
//--------------------------------------------
//--------------------------------------------
//--メイン関数
void GameResultManager::Main( ) {
if ( GetSceneChangeFlag( ) ) return; //シーン遷移フラグが立っている時は処理をしない
//メインBGMと足音と敵の歌声を止める-------------------------------------------------------------
/*int soundHandle = _sounder->GetSoundDataManager( ).GetSoundHandle( GAME_MAIN_BGM );
int soundHandle2 = _sounder->GetSoundDataManager( ).GetSoundHandle( ENEMY_VOICE );
int soundHandle3 = _sounder->GetSoundDataManager( ).GetSoundHandle( SoundData::PLAYER_ASIOTO );
if ( _sounder->CheckSoundMem( soundHandle ) ) {
_sounder->StopSoundMem( soundHandle );
}
if ( _sounder->CheckSoundMem( soundHandle2 ) ) {
_sounder->StopSoundMem( soundHandle2 );
}
if ( _sounder->CheckSoundMem( soundHandle3 ) ) {
_sounder->StopSoundMem( soundHandle3 );
}*/ //GameMainシーンで行うことにしました
//----------------------------------------------------------------------------------------------
if ( _player->GetAnswerCount( ) == CLEAR ) { //クリア時
//文字画像描画-----------------------------------------------------------------------------------------------------
int grHandle = _drawer->GetImageManager( ).GetResourceHandle( ResourceData::GAME_CLEAR_TEXT );
_drawer->DrawGraph( SCREEN_WIDTH_CENTER - 170, SCREEN_HEIGHT_CENTER - 45, grHandle, TRUE ); //中央に来るように座標を調整
//-----------------------------------------------------------------------------------------------------------------
//音を鳴らす処理-----------------------------------------------------------------------------------
int soundHandle4 = _sounder->GetSoundDataManager( ).GetSoundHandle( SoundData::GAME_CLEAR );
if ( !_BGMsounded ) {
_sounder->ChangeVolumeSoundMem( 100, soundHandle4 );
_sounder->PlaySoundMem( soundHandle4, DX_PLAYTYPE_BACK, TRUE );
_BGMsounded = true;
}
//------------------------------------------------------------------------------------------------
if ( !_sounder->CheckSoundMem( soundHandle4 ) ) { //音が止まってから行う処理
DrawPushButton( );
}
} else { //ゲームオーバー時
if ( _gameOverWaitCount < GAME_OVER_WAIT_FLAME ) _gameOverWaitCount++; //ゲームオーバーの間
if ( _gameOverWaitCount >= GAME_OVER_WAIT_FLAME ) {
//エネミーが近づく処理------------------------------------------------------------------------------------------------------------------
int grHandle = _drawer->GetImageManager( ).GetResourceHandle( ResourceData::GAME_OVER_IMAGE );
_drawer->DrawExtendGraph( _enemyImage.leftUp_x, _enemyImage.leftUp_y,_enemyImage.rightDown_x,_enemyImage.rightDown_y, grHandle, TRUE );
if ( _enemyImage.leftUp_x > 100 ) {
_enemyImage.leftUp_x -= 40;
_enemyImage.leftUp_y -= 40;
_enemyImage.rightDown_x += 40;
_enemyImage.rightDown_y += 40;
}
//---------------------------------------------------------------------------------------------------------------------------------------
//音を鳴らす処理------------------------------------------------------------------------------------
int soundHandle4 =_sounder->GetSoundDataManager( ).GetSoundHandle( SoundData::GAME_OVER );
if ( !_BGMsounded ) {
_sounder->ChangeVolumeSoundMem( 200, soundHandle4 );
_sounder->PlaySoundMem( soundHandle4, DX_PLAYTYPE_BACK, TRUE );
_BGMsounded = true;
}
//--------------------------------------------------------------------------------------------------
if ( !_sounder->CheckSoundMem( soundHandle4 ) ) { //音が止まってから行う処理
int grHandle2 = _drawer->GetImageManager( ).GetResourceHandle( ResourceData::GAME_OVER_TEXT );
_drawer->DrawGraph( SCREEN_WIDTH_CENTER - 300, SCREEN_HEIGHT_CENTER - 40, grHandle2, TRUE );
DrawPushButton( );
}
}
}
//_inputChecker->UpdateDevice( ); //main.cppで行っているのでやらなくてよい
}
//--PushButtonを表示する関数
void GameResultManager::DrawPushButton( ) {
//文字画像描画----------------------------------------------------------------------------------------------------
if ( !_pushed ) {
int grHandle = _drawer->GetImageManager( ).GetResourceHandle( ResourceData::PUSH_BUTTON_TEXT );
_drawer->FlashGraph( SCREEN_WIDTH_CENTER - 80, SCREEN_HEIGHT_CENTER + 100, grHandle ); //座標は中央下に来るように調整
}
//----------------------------------------------------------------------------------------------------------------
//キー受付------------------------------------------------------------------------------------------------------------------------------------
if ( _inputChecker->GetKey( KEY_INPUT_RETURN ) == 1 ||
_inputChecker->GetJoypad( INPUT_1 ) == 1 ||
_inputChecker->GetJoypad( INPUT_2 ) == 1 ||
_inputChecker->GetJoypad( INPUT_3 ) == 1 ||
_inputChecker->GetJoypad( INPUT_4 ) == 1
) {
int soundHandle5 = _sounder->GetSoundDataManager( ).GetSoundHandle( GAME_START_SE );
_sounder->ChangeVolumeSoundMem( 80, soundHandle5 );
_sounder->PlaySoundMem( soundHandle5, DX_PLAYTYPE_BACK, TRUE );
_pushed = true;
}
//---------------------------------------------------------------------------------------------------------------------------------------------
//キー入力後処理------------------------
if ( _pushed ) {
_drawer->FadeOut( );
if ( _drawer->GetAlpha( ) <= 0 ) {
SetSceneChangeFlag( true );
}
}
//--------------------------------------
}
|
// Created on: 2001-06-26
// Created by: Alexander GRIGORIEV
// Copyright (c) 2001-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 LDOMBasicString_HeaderFile
#define LDOMBasicString_HeaderFile
#include <Standard_Macro.hxx>
#include <TCollection_AsciiString.hxx>
#include <TCollection_ExtendedString.hxx>
class LDOM_MemManager;
class LDOM_NullPtr;
class TCollection_AsciiString;
class TCollection_ExtendedString;
// Block of comments describing class LDOMBasicString
//
class LDOMBasicString
{
friend class LDOM_MemManager;
friend class LDOM_Node;
public:
enum StringType {
LDOM_NULL = 0,
LDOM_Integer,
// LDOM_Real,
LDOM_AsciiFree, // String not connected to any container
LDOM_AsciiDoc, // String connected to LDOM_Document (container)
LDOM_AsciiDocClear, // --"--"--, consists of only XML-valid chars
LDOM_AsciiHashed // String connected to hash table
};
Standard_EXPORT ~LDOMBasicString ();
StringType Type () const { return myType; }
Standard_EXPORT Standard_Boolean
GetInteger (Standard_Integer& aResult) const;
// Conversion to Integer (only for LDOM_Integer)
const char *
GetString () const { return myType == LDOM_Integer ||
myType == LDOM_NULL ?
"" : (const char *) myVal.ptr; }
// Conversion to char * (only for LDOM_Ascii*)
Standard_EXPORT Standard_Boolean
equals (const LDOMBasicString& anOther) const;
// Compare two strings by content
Standard_EXPORT LDOMBasicString&
operator = (const LDOM_NullPtr *);
Standard_EXPORT LDOMBasicString&
operator = (const LDOMBasicString& anOther);
Standard_Boolean
operator == (const LDOM_NullPtr *) const
{ return myType==LDOM_NULL; }
Standard_Boolean
operator != (const LDOM_NullPtr *) const
{ return myType!=LDOM_NULL; }
Standard_Boolean
operator == (const LDOMBasicString& anOther) const
{
return myType==anOther.myType && myVal.i==anOther.myVal.i;
}
Standard_Boolean
operator != (const LDOMBasicString& anOther) const
{
return myType!=anOther.myType || myVal.i!=anOther.myVal.i;
}
// AGV auxiliary API
Standard_EXPORT operator TCollection_AsciiString () const;
Standard_EXPORT operator TCollection_ExtendedString () const;
LDOMBasicString ()
: myType (LDOM_NULL) { myVal.ptr = NULL; }
// Empty constructor
Standard_EXPORT LDOMBasicString (const LDOMBasicString& anOther);
// Copy constructor
LDOMBasicString (const Standard_Integer aValue)
: myType (LDOM_Integer) { myVal.i = aValue; }
Standard_EXPORT LDOMBasicString (const char * aValue);
// Create LDOM_AsciiFree
Standard_EXPORT LDOMBasicString (const char * aValue,
const Handle(LDOM_MemManager)& aDoc);
// Create LDOM_AsciiDoc
Standard_EXPORT LDOMBasicString (const char * aValue,
const Standard_Integer aLen,
const Handle(LDOM_MemManager)& aDoc);
// Create LDOM_AsciiDoc
protected:
// ---------- PROTECTED METHODS ----------
void SetDirect (const StringType aType, const char * aValue)
{ myType = aType; myVal.ptr = (void *) aValue; }
protected:
// ---------- PROTECTED FIELDS ----------
StringType myType;
union {
int i;
void * ptr;
} myVal;
friend char * db_pretty_print (const LDOMBasicString *, int, char *);
};
#endif
|
/* -*- Mode: c++; indent-tabs-mode: nil; c-file-style: "gnu" -*-
*
* Copyright (C) 1995-2002 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#ifndef XMLPARSER_XMLCHECKINGTOKENHANDLER_H
#define XMLPARSER_XMLCHECKINGTOKENHANDLER_H
#include "modules/xmlparser/xmlinternalparser.h"
#include "modules/xmlutils/xmltokenhandler.h"
class XMLCheckingTokenHandler
{
public:
XMLCheckingTokenHandler (XMLInternalParser *parser, XMLTokenHandler *secondary, BOOL is_fragment, XMLNamespaceDeclaration *nsdeclaration);
~XMLCheckingTokenHandler ();
void SetSecondary (XMLTokenHandler *new_secondary) { secondary = new_secondary; }
XMLTokenHandler::Result HandleToken (XMLToken &token, BOOL from_processtoken = FALSE);
BOOL IsReferenceAllowed () { return current != 0 || is_fragment; }
protected:
XMLTokenHandler::Result CallSecondary (XMLToken &token);
XMLTokenHandler::Result HandleSTagToken (XMLToken &token, BOOL from_processtoken);
XMLTokenHandler::Result HandleETagToken (XMLToken &token, BOOL from_processtoken);
XMLTokenHandler::Result SetError (XMLInternalParser::ParseError error);
XMLTokenHandler::Result SetAttributeError (XMLInternalParser::ParseError error, unsigned attrindex, unsigned attrindex_related = ~0u);
class Element
{
public:
Element ()
: qname (0)
#if defined XML_ERRORS && defined OPERA_CONSOLE
, firstnsdecl (0)
#endif // XML_ERRORS && OPERA_CONSOLE
{}
~Element ();
OP_STATUS SetQName (const uni_char *qname, unsigned qname_length);
Element *parent;
XMLDoctype::Entity *containing_entity;
uni_char *qname;
unsigned qname_length, qname_free;
BOOL owns_qname;
const uni_char *uri;
unsigned uri_length;
#ifdef XML_ERRORS
XMLRange range;
#ifdef OPERA_CONSOLE
/** Used to keep track of namespace declarations stemming from a
"known default attribute" (tainted) and declarations that
override such declarations (non-tainted.) If a tainted
namespace declaration is used, we issue a warning in the
console. */
class NamespaceDeclaration
{
public:
~NamespaceDeclaration ();
BOOL tainted, reported;
uni_char *prefix, *uri;
NamespaceDeclaration *nextnsdecl;
} *firstnsdecl;
#endif // OPERA_CONSOLE
#endif // XML_ERRORS
};
#if defined XML_ERRORS && defined OPERA_CONSOLE
XMLTokenHandler::Result AddNamespaceDeclaration (BOOL tainted, const uni_char *prefix, unsigned prefix_length, const uni_char *uri, unsigned uri_length);
BOOL FindTaintedNamespaceDeclaration (const uni_char *prefix, unsigned prefix_length, Element *&ownerelement, Element::NamespaceDeclaration *&nsdecl);
BOOL has_tainted_nsdecls;
#endif // XML_ERRORS && OPERA_CONSOLE
Element *NewElement (), *current, *old;
void FreeElement (Element *element);
BOOL has_xmldecl, has_doctype, has_misc, has_whitespace, has_root, is_fragment;
XMLInternalParser *parser;
XMLDoctype *doctype;
XMLTokenHandler *secondary;
XMLNamespaceDeclaration::Reference nsdeclaration;
unsigned level;
};
#endif // XMLPARSER_XMLCHECKINGTOKENHANDLER_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup" -*-
*
* Copyright (C) Opera Software ASA 1999-2004
*/
#ifndef ES_STRING_OBJECT_H
#define ES_STRING_OBJECT_H
#include "modules/ecmascript/carakan/src/object/es_object.h"
class ES_String_Object : public ES_Object
{
public:
static ES_String_Object *Make(ES_Context *context, ES_Global_Object *global_object, JString *value);
static ES_String_Object *MakePrototypeObject(ES_Context *context, ES_Global_Object *global_object, ES_Class *&instance);
static BOOL GetSubString(ES_Context *context, ES_String_Object *this_object, unsigned index, unsigned length, JString *&result);
JString *&GetValue() { return value; }
private:
static void Initialize(ES_String_Object *string, ES_Class *klass, JString *value)
{
ES_Object::Initialize(string, klass);
string->ChangeGCTag(GCTAG_ES_Object_String);
string->value = value;
}
JString *value;
};
#endif // ES_STRING_OBJECT_H
|
#include <DxLib.h>
#include <stdio.h>
#include "PlayersScore.h"
void PlayersScore::Load() {
FILE *fp;
fopen_s(&fp, "save.dat", "rb");
if (fp == NULL) {
for (int i = 0; i < 4; i++) {
for (int i1 = 0; i1 < 10; i1++) {
strcpy_s(score[i][i1].name, "NoName");
}
score[0][0].score = 200000;
score[0][1].score = 175000;
score[0][2].score = 150000;
score[0][3].score = 125000;
score[0][4].score = 100000;
score[0][5].score = 90000;
score[0][6].score = 80000;
score[0][7].score = 70000;
score[0][8].score = 60000;
score[0][9].score = 50000;
score[1][0].score = 300000;
score[1][1].score = 275000;
score[1][2].score = 250000;
score[1][3].score = 225000;
score[1][4].score = 200000;
score[1][5].score = 175000;
score[1][6].score = 150000;
score[1][7].score = 125000;
score[1][8].score = 100000;
score[1][9].score = 50000;
score[1][0].score = 3000000;
score[1][1].score = 2750000;
score[1][2].score = 2500000;
score[1][3].score = 2250000;
score[1][4].score = 2000000;
score[1][5].score = 1750000;
score[1][6].score = 1500000;
score[1][7].score = 1250000;
score[1][8].score = 1000000;
score[1][9].score = 500000;
score[3][0].score = 4500000;
score[3][1].score = 4250000;
score[3][2].score = 4000000;
score[3][3].score = 3750000;
score[3][4].score = 3500000;
score[3][5].score = 3250000;
score[3][6].score = 3000000;
score[3][7].score = 2500000;
score[3][8].score = 2000000;
score[3][9].score = 1000000;
}
return;
}
for (int i = 0; i < 4; i++) {
for (int i1 = 0; i1 < 10; i1++) {
int s;
fread(score[i][i1].name, sizeof(char), 9, fp);
fread(&s, sizeof(int), 1, fp);
score[i][i1].score = (s + 81425) / 3;
}
}
fclose(fp);
}
void PlayersScore::Save() const {
FILE *fp;
fopen_s(&fp, "save.dat", "wb");
if (fp) {
for (int i = 0; i < 4; i++) {
for (int i1 = 0; i1 < 10; i1++) {
int s = score[i][i1].score * 3 - 81425;
fwrite(score[i][i1].name, sizeof(char), 9, fp);
fwrite(&s, sizeof(int), 1, fp);
}
}
fclose(fp);
}
}
void PlayersScore::Draw() const {
}
Score* PlayersScore::getScore(int diff) {
return score[diff];
}
|
/*****************************************************************
* Copyright (C) 2017-2018 Robert Valler - All rights reserved.
*
* This file is part of the project: DevPlatformAppCMake.
*
* This project can not be copied and/or distributed
* without the express permission of the copyright holder
*****************************************************************/
#include "MainWindow.h"
#include "ui_MainWindow.h"
#include "Output.h"
#include <QMouseEvent>
#include <QGraphicsItem>
#include <QGraphicsScene>
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
newMouseEvent = false;
ui->setupUi(this);
scene = new QGraphicsScene(this);
scene->setSceneRect(ui->graphicsView->geometry());
scene->setItemIndexMethod(QGraphicsScene::NoIndex);
ui->graphicsView->setScene(scene);
ui->graphicsView->setRenderHint(QPainter::Antialiasing);
//ui->graphicsView->setBackgroundBrush(QPixmap(":*.png"));
ui->graphicsView->setCacheMode(QGraphicsView::CacheNone);
ui->graphicsView->setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);
ui->FPSData->setText(QString::number(0));
// hide the layoutContainer widget. it is not meant to be displayed.
ui->layoutContainer->hide();
m_ItemConnection = connect(this, SIGNAL(guiObjItemSignal(QGraphicsItem*, unsigned int)),
this, SLOT(mainWItemSlot(QGraphicsItem*, unsigned int)),
Qt::QueuedConnection);
m_PosConnection = connect(this, SIGNAL(guiObjSetPosSignal(QGraphicsItem*, float, float, float)),
this, SLOT(mainWSetPosSlot(QGraphicsItem*, float, float, float)),
Qt::QueuedConnection);
}
MainWindow::~MainWindow()
{
disconnect(m_ItemConnection);
disconnect(m_PosConnection);
//delete scene; // comment out. crashes
delete ui;
}
void MainWindow::mainWndRegister(QGraphicsItem* pObj)
{
std::lock_guard<std::mutex> guard(registerLock);
//QGraphicsItem *pGuiObj = static_cast<QGraphicsItem*>(pObj);
emit guiObjItemSignal(pObj, ItemSlotAction::AddGraphicsItem);
}
void MainWindow::mainWndDeRegister(QGraphicsItem* pObj)
{
// std::lock_guard<std::mutex> guard(registerLock);
// QGraphicsItem *pGuiObj = static_cast<QGraphicsItem*>(pObj);
emit guiObjItemSignal(pObj, ItemSlotAction::RemoveGraphicsItem);
}
void MainWindow::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
{
QPoint pos = ui->graphicsView->mapFromGlobal(QCursor::pos());
mousePosX = pos.x();
mousePosY = pos.y();
newMouseEvent = true;
}
}
void MainWindow::getDrawWindowSize(int& x, int& y, int& w, int& h)
{
x = ui->graphicsView->geometry().x();
y = ui->graphicsView->geometry().y();
w = ui->graphicsView->geometry().width();
h = ui->graphicsView->geometry().height();
}
unsigned int MainWindow::mainWndGetLayoutContainerData(ObjectParameters& pObj, int level, int index)
{
switch(level) {
case 1: pCurrentLevel = ui->level1; break;
case 2: pCurrentLevel = ui->level2; break;
case 3: pCurrentLevel = ui->level3; break;
default:
Output::print("MainWindow - level selection error");
return listDataReturnVal::error;
}
if( index > (pCurrentLevel->children().size()-1) || index < 0 )
return listDataReturnVal::indexOutOfRange;
const QWidget* wd = static_cast<QWidget*>( (pCurrentLevel->children().at(index)) );
if( wd == nullptr) {
Output::print("MainWindow - pointing to wrong data table");
return listDataReturnVal::error;
}
// find the object type
std::string whatIsIt = wd->whatsThis().toLocal8Bit().constData();
if( "building" == whatIsIt )
pObj.type = ObjectType::t_building;
else if( "avatar" == whatIsIt )
pObj.type = ObjectType::t_avatar;
else if( "mob" == whatIsIt )
pObj.type = ObjectType::t_mob;
else if( "surface" == whatIsIt )
pObj.type = ObjectType::t_surface;
else if( "chaser" == whatIsIt )
pObj.type = ObjectType::t_chaser;
else
return listDataReturnVal::typeNotFound;
// retrieve dimensions and initial position
pObj.dimension.width = wd->geometry().width();
pObj.dimension.height = wd->geometry().height();
pObj.position.x = wd->geometry().x() + (pObj.dimension.width / 2); // add offset, the origin is at the centre
pObj.position.y = wd->geometry().y() + (pObj.dimension.height / 2); // add offset, the origin is at the centre
pObj.position.angle = 0; // default angle set to zero until handled by UI
return listDataReturnVal::ok;
}
// ################# INPUT ##########
bool MainWindow::mainWndIsNewMouseEvent()
{
bool result = newMouseEvent;
newMouseEvent = false;
return result;
}
void MainWindow::mainWndPositionUpdate(QGraphicsItem* pObj, float x, float y, float angle)
{
// QGraphicsItem *pGuiObj = static_cast<QGraphicsItem*>(pObj);
emit guiObjSetPosSignal(pObj, x, y, angle);
}
// SLOTS
void MainWindow::mainWSetPosSlot(QGraphicsItem *pGItem, float x, float y, float angle)
{
std::lock_guard<std::mutex> guard(slotlock);
QPointF scenePoint = ui->graphicsView->mapToScene( static_cast<int>(x), static_cast<int>(y) );
pGItem->setPos(scenePoint);
pGItem->setRotation(static_cast<qreal>(angle));
}
void MainWindow::mainWItemSlot(QGraphicsItem *pGItem, unsigned int action)
{
std::lock_guard<std::mutex> guard(slotlock);
// todo: find out why pGItem is null under high loads.
// this is a temp fix to handle "ghost" signals (null pGItem).
if(pGItem == nullptr)
return;
switch(action)
{
case ItemSlotAction::AddGraphicsItem:
ui->graphicsView->scene()->addItem(pGItem);
break;
case ItemSlotAction::RemoveGraphicsItem:
ui->graphicsView->scene()->removeItem(pGItem);
break;
default:
break;
}
//Output::print("MainWindow: number of items : ", ui->graphicsView->scene()->items().size());
}
|
#pragma once
#include <vector>
#include "Point.h"
#include "GamePiece.h"
using namespace std;
class Region
{
private:
//id of the region
int id;
//token value of the region
int token;
//the player who controls this region
int owner_id;
string type;
string symbol;
bool borderRegion;
/// <summary>
/// The game pieces
/// </summary>
vector<GamePiece*> gamePieces;
// neigboring regions
vector<Region*> neigborRegions; //veken said store pointers //claudia says all object instance variables should be pointers
/// <summary>
/// The x, y pixel coordinates on the picture
/// </summary>
Point point;
public:
Region();
Region(int id, int token);
Region(int id, int token, Point point);
Region(int id, int token, string type, int owner_id, string symbol, bool borderRegion, Point point);
void setId(int token);
int getId();
void setOwner_id(int owner_id);
int getOwner_id();
void setToken(int token);
int getToken();
void setType(string type);
string getType();
void setSymbol(string symbol);
string getSymbol();
void setBorderRegion(bool borderRegion);
bool getBorderRegion();
void setNeigborRegions(vector<Region*> neigborRegions);
void addNeigborRegions(Region* region);
void removeNeigborRegions(Region* region);
vector<Region*> getNeigborRegions();
void setGamePiece(vector<GamePiece*> neigborRegions);
void addGamePiece(GamePiece* region);
void removeGamePiece(GamePiece* region);
vector<GamePiece*> getGamePieces();
void printNeigbors();
};
|
/**
GeekFactory - "INNOVATING TOGETHER"
Distribucion de materiales para el desarrollo e innovacion tecnologica
www.geekfactory.mx
EJEMPLO SENCILLO PARA LECTURA DE TEMPERATURA CON TERMISTOR NTC. EL PROGRAMA
ESTÁ DISENADO PARA TERMISTORES NTC DE 10K NOMINALES A 25 GRADOS CENTIGRADOS.
EL TERMISTOR DEBE SER CONECTADO A LA ENTRADA DEL ADC MEDIANTE UN ARREGLO DE
DIVISOR RESISTIVO REALIZADO CON RESISTENCIA DE 10K Y EL TERMISTOR EN SERIE.
EL ALGORITMO UTILIZADO PARA OBTENER LA TEMPERATURA A PARTIR DE LA RESISTENCIA
DEL TERMISTOR ES UNA IMPLEMENTACIÓN DE LA ECUACIÓN DE STEINHART-HART
*/
#include <Arduino.h>
#include <math.h>
// configurar el pin utilizado para la medicion de voltaje del divisor resistivo del NTC
#define CONFIG_THERMISTOR_ADC_PIN A0
// configurar el valor de la resistencia que va en serie con el termistor NTC en ohms
#define CONFIG_THERMISTOR_RESISTOR 9900l
/**
@brief Obtiene la resistencia del termistor resolviendo el divisor resistivo.
@param adcval Valor medido por el convertidor analógico a digital.
@return int32_t Resistencia electrica del termistor.
*/
int32_t thermistor_get_resistance(uint16_t adcval)
{
// calculamos la resistencia del NTC a partir del valor del ADC
return (CONFIG_THERMISTOR_RESISTOR * ((1023.0 / adcval) - 1));
}
/**
@brief Obtiene la temperatura en grados centigrados a partir de la resistencia
actual del componente.
@param resistance Resistencia actual del termistor.
@return float Temperatura en grados centigrados.
*/
float thermistor_get_temperature(int32_t resistance)
{
// variable de almacenamiento temporal, evita realizar varias veces el calculo de log
float temp;
// calculamos logaritmo natural, se almacena en variable para varios calculos
temp = log(resistance);
// resolvemos la ecuacion de STEINHART-HART
// http://en.wikipedia.org/wiki/Steinhart–Hart_equation
temp = 1 / (0.001129148 + (0.000234125 * temp) + (0.0000000876741 * temp * temp * temp));
// convertir el resultado de kelvin a centigrados y retornar
return temp - 273.15;
}
float calculoNTC()
{
// variable para almacenar la temperatura y resistencia
float sumaTemperaturas;
const byte numeroMuestras;
float temperaturaMedia;
for (int i = 0; i <= numeroMuestras; i++) {
// calcular la resistencia electrica del termistor usando la lectura del ADC
uint32_t resistencia = thermistor_get_resistance(analogRead(CONFIG_THERMISTOR_ADC_PIN));
// luego calcular la temperatura segun dicha resistencia
float temperatura = thermistor_get_temperature(resistencia);
sumaTemperaturas += temperatura;
}
temperaturaMedia = sumaTemperaturas/numeroMuestras;
return temperaturaMedia;
// imprimir resistencia y temperatura al monitor serial
/*Serial.print(F("Resistencia del NTC: "));
Serial.print(resistencia);
Serial.print(" Temperatura: ");
Serial.println(temperatura, 1);
// esperar 5 segundos entre las lecturas
delay(5000);*/
}
|
//
// Created by dylan on 12-11-2019.
// Subclass of rectangle.
// This class is used to create rectangle objects that can move around.
//
#ifndef CPSE2_MOVING_RECTANGLE_HPP
#define CPSE2_MOVING_RECTANGLE_HPP
#include "rectangle.hpp"
class moving_rectangle : public rectangle {
public:
moving_rectangle(sf::Vector2f position, sf::Color color , sf::Vector2f size);
void draw( sf::RenderWindow & window ) const;
void move( sf::Vector2f delta );
void jump( sf::Vector2f target );
void jump( sf::Vector2i target );
};
#endif //CPSE2_MOVING_RECTANGLE_HPP
|
#include <mutex>
#include <thread>
class Singleton
{
private:
Singleton() {};
Singleton(const Singleton& s) = delete;
static std::mutex mtx;
static Singleton *m_instance;
public:
static Singleton* getInstance();
~Singleton();
};
Singleton* Singleton::getInstance() {
// 加锁使得线程同步,避开竞争
mtx.lock();
if (m_instance == nullptr) {
m_instance = new Singleton();
}
mtx.unlock();
// 存在问题,这种竞争实际上只有第一次才会有,之后可以直接返回,每次加锁
// 会带来很大的性能损失,所以这种方法降低了性能,而单例模式的初衷就是提高性能
return m_instance;
}
|
#include "H/3D.h"
/*
void matrixMulVertices(Vertice3D &i,Vertice3D &o, mat4x4 &m){
o.x = i.x * m.m[0][0] + i.y * m.m[1][0] + i.z * m.m[2][0] + m.m[3][0];
o.y = i.x * m.m[0][1] + i.y * m.m[1][1] + i.z * m.m[2][1] + m.m[3][1];
o.z = i.x * m.m[0][2] + i.y * m.m[1][2] + i.z * m.m[2][2] + m.m[3][2];
float w = i.x * m.m[0][3] + i.y * m.m[1][3] + i.z * m.m[2][3] + m.m[3][3];
if (w != 0.0) {
o.x /= w; o.y /= w; o.z /= w;
}
}
void __BOOTSCREEN__(){
Mesh Cube1;
mat4x4 matProj;
Cube1.tris = {
// SOUTH
{ 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f },
{ 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f },
// EAST
{ 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f },
{ 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f },
// NORTH
{ 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f },
{ 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f },
// WEST
{ 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f },
{ 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f },
// TOP
{ 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f },
{ 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f },
// BOTTOM
{ 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f },
{ 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f },
};
float fnear = 0.1;
float fFar = 1000.0;
float fFov = 90.0;
float fAspect = (float)320 / (float)200;
float fFovRad = 0.1 / tanf((fFov * 0.5 / 180.0 * 3,14159));
matProj.m[0][0] = fAspect * fFovRad;
matProj.m[0][0] = fFovRad;
matProj.m[0][0] = fFar / (fFar - fnear);
matProj.m[0][0] = (-fFar * fnear) / (fFar - fnear);
matProj.m[0][0] = 1.0;
matProj.m[0][0] = 0.0;
for (auto tri : Cube1.tris){
triangle triProjected;
matrixMulVertices(tri.p[0], triProjected.p[0], matProj);
matrixMulVertices(tri.p[1], triProjected.p[1], matProj);
matrixMulVertices(tri.p[2], triProjected.p[2], matProj);
Triangle(triProjected.p[0].x,triProjected.p[0].y,
triProjected.p[1].x, triProjected.p[1].y,
triProjected.p[2].x,triProjected.p[2].y, 15);
}
while(1);
}*/
|
#include<cstdio>
#include<bits/stdc++.h>
using namespace std;
#define Max 10000000
double gh[1000][1000];
int N,M;
double mintree(){
int i,j,k;
double m,len=0,Min[1000];
int vis[1000]={0};
vis[0]=1;
for(i=0;i<N;i++)
Min[i]=gh[0][i];
for(i=1;i<N;i++){
for(j=1,m=Max;j<N;j++)
if(m>Min[j]&&!vis[j]){
m=Min[j];
k=j;
}
len+=m;
vis[k]=1;
for(j=1;j<N;j++)
if(gh[k][j]<Min[j])
Min[j]=gh[k][j];
}
return len;
}
int main(){
int i,j,k;
double p[1000][2],d;
while(scanf("%d",&N)!=EOF){
for(i=0;i<N;i++){
scanf("%lf%lf",&p[i][0],&p[i][1]);
for(j=i;j>=0;j--){
d=sqrt((p[i][0]-p[j][0])*(p[i][0]-p[j][0])+(p[i][1]-p[j][1])*(p[i][1]-p[j][1]));
gh[i][j]=d;
gh[j][i]=d;
}
}
scanf("%d",&M);
for(i=0;i<M;i++){
scanf("%d%d",&j,&k);
gh[j-1][k-1]=0;
gh[k-1][j-1]=0;
}
printf("%.2lf\n",mintree());
}
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
*
* Copyright (C) 2003-2010 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* Morten Stenshorne
*/
#include "core/pch.h"
#ifdef PICTOGRAM_SUPPORT
#include "modules/logdoc/src/picturlconverter.h"
#include "modules/util/handy.h"
#include "modules/util/opfile/opfile.h"
void
PictUrlConverter::GetLocalUrlL(
const uni_char *pict_url, int pict_url_len, OpString &out_url_str)
{
out_url_str.Empty();
if (pict_url_len <= 7 || !uni_strni_eq(pict_url, "PICT://", 7))
{
OP_ASSERT(!"Malformed pictogram URL");
return;
}
const uni_char *url_end = pict_url + pict_url_len;
const uni_char *serv_start = pict_url + 7;
const uni_char *serv_end = serv_start;
while (serv_end < url_end && *serv_end != '/')
serv_end ++;
if (serv_end == url_end)
return;
OpString server;
ANCHOR(OpString, server);
if (serv_end == serv_start)
server.SetL("www.wapforum.org");
else
{
server.SetL(serv_start, serv_end - serv_start);
uni_strlwr(server.CStr());
}
OpString loc;
ANCHOR(OpString, loc);
loc.SetL(UNI_L("pictograms"));
loc.AppendL(UNI_L(PATHSEP));
loc.AppendL(server);
loc.AppendL(UNI_L(PATHSEP));
const uni_char *class_start = serv_end;
const uni_char *class_end = class_start;
while (class_start < url_end)
{
while (*class_start == '/')
{
if (++class_start == url_end)
return; // No pictogram name
}
class_end = class_start;
while (class_end < url_end && *class_end != '/')
class_end++;
if (class_end == url_end)
{
// The pictogram name is between class_start and class_end now
break;
}
else if (class_end - class_start != 2 || *class_start != '.' && *(class_start + 1) != '.')
// weed out the ..'s in the path
{
loc.AppendL(class_start, class_end - class_start);
loc.AppendL(UNI_L(PATHSEP));
}
class_start = class_end;
}
loc.AppendL(class_start, class_end - class_start);
#ifdef ADS12 // Sucky linker can't handle array-of-string initializers :-(
const char* exts[4]; // ARRAY OK 2010-07-09 eddy
exts[0] = ".gif"; exts[1] = ".png"; exts[2] = ".jpg"; exts[3] = ".wbmp";
// Update array size before adding any new members !
#else // Make sure the above stays in sync with the following
const char *const exts[] = { ".gif", ".png", ".jpg", ".wbmp" };
#endif
for (int i=0; i<2; i++)
for (size_t j=0; j<ARRAY_SIZE(exts); j++)
{
OpString filename;
ANCHOR(OpString, filename);
filename.SetL(loc);
filename.AppendL(exts[j]);
OpFile file;
ANCHOR(OpFile, file);
LEAVE_IF_ERROR(file.Construct(filename.CStr(), i == 0 ? OPFILE_HOME_FOLDER : OPFILE_RESOURCES_FOLDER));
BOOL exists = FALSE;
OP_STATUS status = file.Exists(exists);
if(status != OpStatus::OK)
{
OP_ASSERT(!"Failed to discover whether pictogram file exists :-(");
}
if(exists)
{
const uni_char* full_path = file.GetFullPath();
if (*full_path != '/')
out_url_str.SetL("file://localhost/");
else
out_url_str.SetL("file://localhost");
out_url_str.AppendL(full_path);
return;
}
}
}
/*static*/ OP_STATUS
PictUrlConverter::GetLocalUrl(
const uni_char *pict_url, int pict_url_len, OpString &out_url_str)
{
TRAPD(ret_stat, GetLocalUrlL(pict_url, pict_url_len, out_url_str));
return ret_stat;
}
#endif // PICTOGRAM_SUPPORT
|
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(void)
{
int N;
scanf("%d", &N);
vector<long long> v(N);
for (int i = 0; i < N; i++)
{
scanf("%lld", &v[i]);
}
sort(v.begin(), v.end());
int nCount = 0;
int nMax = 0;
long long nMaxVal = v[0];
for (int i = 1; i < N; i++)
{
if (v[i] == v[i - 1])
{
nCount++;
}
else
{
nCount = 0;
}
if (nMax < nCount)
{
nMax = nCount;
nMaxVal = v[i];
}
}
printf("%lld\n", nMaxVal);
return 0;
}
|
#include<bits/stdc++.h>
using namespace std;
void cntMoves()
{
int X, Y, moves;
X=Y=0;
cout<<"Number of Moves: ";
cin>>moves;
for(int i=0; i<=moves; i++)
{
if(moves%2==0)
{
if(i!=1 || i%2==0){
Y+=1;
}
}
else
{
if(i==1 || i%2==1){
Y+=i;
}
}
}
cout<<"Sum of all abs(X) & abs(Y) = "<<Y*2<<endl;
return;
}
int main()
{
int T;
cout<<"Enter the test cases : ";
cin>>T;
while(T--)
cntMoves();
return 0;
}
|
#include "aDDictMath.h"
/*float __cdecl sin(float v)
{
volatile float res;
__asm
{
fld v
fsin
fstp res
}
return res;
}
float __cdecl cos(float v)
{
volatile float res;
__asm
{
fld v
fcos
fstp res
}
return res;
}
float __cdecl sqrt(float v)
{
volatile float res;
__asm
{
fld v
fsqrt
fstp res
}
return res;
}
float __cdecl fabs(float v)
{
volatile float res;
__asm
{
fld v
fabs
fstp res
}
return res;
}*/
|
class SystemManager
{
public:
SystemManager(ComponentManager& components)
: components{components}
{
}
template <typename T>
T& add()
{
auto t = new T{};
t->set(components);
auto& system = systems.emplace_back(t);
ComponentMap map = T::TYPE::get_map();
records.push_back({ map, *system });
return *(T*)system.get();
}
void update()
{
for(auto& s : systems)
s->update();
}
void accept(EntityRef ref, ComponentMap& components)
{
for(auto s : records)
{
auto is_accepted = (s.map & components) == s.map;
if(is_accepted)
s.system.accept(ref);
}
}
private:
struct SystemRecord
{
ComponentMap map;
BaseSystem& system;
};
ComponentManager& components;
std::vector<SystemRecord> records;
std::vector<std::unique_ptr<BaseSystem>> systems;
};
|
/*
* A library for controlling a Microchip RN2xx3 LoRa radio.
*
* @Author JP Meijers
* @Author Nicolas Schteinschraber
* @Date 18/12/2015
*
*/
#ifndef rn2xx3_h
#define rn2xx3_h
#include "Arduino.h"
enum RN2xx3_t {
RN_NA = 0, // Not set
RN2903 = 2903,
RN2483 = 2483
};
enum FREQ_PLAN {
SINGLE_CHANNEL_EU = 0,
TTN_EU,
TTN_US,
DEFAULT_EU
};
enum TX_RETURN_TYPE {
TX_FAIL = 0, // The transmission failed.
// If you sent a confirmed message and it is not acked,
// this will be the returned value.
TX_SUCCESS = 1, // The transmission was successful.
// Also the case when a confirmed message was acked.
TX_WITH_RX = 2 // A downlink message was received after the transmission.
// This also implies that a confirmed message is acked.
};
class rn2xx3
{
public:
/*
* A simplified constructor taking only a Stream ({Software/Hardware}Serial) object.
* The serial port should already be initialised when initialising this library.
*/
rn2xx3(Stream& serial);
/*
* Transmit the correct sequence to the rn2xx3 to trigger its autobauding feature.
* After this operation the rn2xx3 should communicate at the same baud rate than us.
*/
bool autobaud();
/*
* Get the hardware EUI of the radio, so that we can register it on The Things Network
* and obtain the correct AppKey.
* You have to have a working serial connection to the radio before calling this function.
* In other words you have to at least call autobaud() some time before this function.
*/
String hweui();
/*
* Returns the AppSKey or AppKey used when initializing the radio.
* In the case of ABP this function will return the App Session Key.
* In the case of OTAA this function will return the App Key.
*/
String appkey();
/*
* In the case of OTAA this function will return the Application EUI used
* to initialize the radio.
*/
String appeui();
/*
* In the case of OTAA this function will return the Device EUI used to
* initialize the radio. This is not necessarily the same as the Hardware EUI.
* To obtain the Hardware EUI, use the hweui() function.
*/
String deveui();
/*
* Get the RN2xx3's hardware and firmware version number. This is also used
* to detect if the module is either an RN2483 or an RN2903.
*/
String sysver();
bool setSF(uint8_t sf);
/*
* Initialise the RN2xx3 and join the LoRa network (if applicable).
* This function can only be called after calling initABP() or initOTAA().
* The sole purpose of this function is to re-initialise the radio if it
* is in an unknown state.
*/
bool init();
/*
* Initialise the RN2xx3 and join a network using personalization.
*
* addr: The device address as a HEX string.
* Example "0203FFEE"
* AppSKey: Application Session Key as a HEX string.
* Example "8D7FFEF938589D95AAD928C2E2E7E48F"
* NwkSKey: Network Session Key as a HEX string.
* Example "AE17E567AECC8787F749A62F5541D522"
*/
bool initABP(const String& addr, const String& AppSKey, const String& NwkSKey);
//TODO: initABP(uint8_t * addr, uint8_t * AppSKey, uint8_t * NwkSKey)
/*
* Initialise the RN2xx3 and join a network using over the air activation.
*
* AppEUI: Application EUI as a HEX string.
* Example "70B3D57ED00001A6"
* AppKey: Application key as a HEX string.
* Example "A23C96EE13804963F8C2BD6285448198"
* DevEUI: Device EUI as a HEX string.
* Example "0011223344556677"
* If the DevEUI parameter is omitted, the Hardware EUI from module will be used
* If no keys, or invalid length keys, are provided, no keys
* will be configured. If the module is already configured with some keys
* they will be used. Otherwise the join will fail and this function
* will return false.
*/
bool initOTAA(const String& AppEUI="", const String& AppKey="", const String& DevEUI="");
/*
* Initialise the RN2xx3 and join a network using over the air activation,
* using byte arrays. This is useful when storing the keys in eeprom or flash
* and reading them out in runtime.
*
* AppEUI: Application EUI as a uint8_t buffer
* AppKey: Application key as a uint8_t buffer
* DevEui: Device EUI as a uint8_t buffer (optional - set to 0 to use Hardware EUI)
*/
bool initOTAA(uint8_t * AppEUI, uint8_t * AppKey, uint8_t * DevEui);
/*
* Transmit the provided data. The data is hex-encoded by this library,
* so plain text can be provided.
* This function is an alias for txUncnf().
*
* Parameter is an ascii text string.
*/
TX_RETURN_TYPE tx(const String& , uint8_t port = 1);
/*
* Transmit raw byte encoded data via LoRa WAN.
* This method expects a raw byte array as first parameter.
* The second parameter is the count of the bytes to send.
*/
TX_RETURN_TYPE txBytes(const byte*, uint8_t size, uint8_t port = 1);
TX_RETURN_TYPE txHexBytes(const String&, uint8_t port = 1);
/*
* Do a confirmed transmission via LoRa WAN.
*
* Parameter is an ascii text string.
*/
TX_RETURN_TYPE txCnf(const String&, uint8_t port = 1);
/*
* Do an unconfirmed transmission via LoRa WAN.
*
* Parameter is an ascii text string.
*/
TX_RETURN_TYPE txUncnf(const String&, uint8_t port = 1);
/*
* Transmit the provided data using the provided command.
*
* String - the tx command to send
can only be one of "mac tx cnf 1 " or "mac tx uncnf 1 "
* String - an ascii text string if bool is true. A HEX string if bool is false.
* bool - should the data string be hex encoded or not
*/
TX_RETURN_TYPE txCommand(const String&, const String&, bool, uint8_t port = 1);
/*
* Change the datarate at which the RN2xx3 transmits.
* A value of between 0 and 5 can be specified,
* as is defined in the LoRaWan specs.
* This can be overwritten by the network when using OTAA.
* So to force a datarate, call this function after initOTAA().
*/
bool setDR(int dr);
/*
* Put the RN2xx3 to sleep for a specified timeframe.
* The RN2xx3 accepts values from 100 to 4294967296.
* Rumour has it that you need to do a autobaud() after the module wakes up again.
*/
void sleep(long msec);
/*
* Send a raw command to the RN2xx3 module.
* Returns the raw string as received back from the RN2xx3.
* If the RN2xx3 replies with multiple line, only the first line will be returned.
*/
String sendRawCommand(const String& command);
/*
* Returns the module type either RN2903 or RN2483, or NA.
*/
RN2xx3_t moduleType();
/*
* Set the active channels to use.
* Returns true if setting the channels is possible.
* Returns false if you are trying to use the wrong channels on the wrong module type.
*/
bool setFrequencyPlan(FREQ_PLAN);
/*
* Returns the last downlink message HEX string.
*/
String getRx();
/*
* Get the RN2xx3's SNR of the last received packet. Helpful to debug link quality.
*/
int getSNR();
/*
* Get the RN2xx3's voltage measurement on the Vdd in mVolt
* 0–3600 (decimal value from 0 to 3600)
*/
int getVbat();
/*
* Return the current data rate formatted like sf7bw125
* Firmware 1.0.1 returns always "sf9"
*/
String getDataRate();
/*
* Return radio Received Signal Strength Indication (rssi) value
* for the last received frame.
* Supported since firmware 1.0.5
*/
int getRSSI();
/*
* Encode an ASCII string to a HEX string as needed when passed
* to the RN2xx3 module.
*/
String base16encode(const String&);
/*
* Decode a HEX string to an ASCII string. Useful to decode a
* string received from the RN2xx3.
*/
String base16decode(const String&);
/*
* Almost all commands can return "invalid_param"
* The last command resulting in such an error can be retrieved.
* Reading this will clear the error.
*/
String getLastErrorInvalidParam();
String peekLastErrorInvalidParam();
bool hasJoined() const { return Status.Joined; }
bool useOTAA() const { return _otaa; }
// Get the current frame counter values for downlink and uplink
bool getFrameCounters(uint32_t &dnctr, uint32_t &upctr);
// Set frame counter values for downlink and uplink
// E.g. to restore them after a reboot or reset of the module.
bool setFrameCounters(uint32_t dnctr, uint32_t upctr);
// At init() the module is assumed to be joined, which is also checked against the
// _otaa flag.
// Allow to set the last used join mode to help prevent unneeded join requests.
void setLastUsedJoinMode(bool isOTAA) { _otaa = isOTAA; }
struct Status_t {
Status_t() { decode(0); }
Status_t(uint32_t value) { decode(value); }
enum MacState_t {
Idle = 0, // Idle (transmissions are possible)
TransmissionOccurring = 1, // Transmission occurring
PreOpenReceiveWindow1 = 2, // Before the opening of Receive window 1
ReceiveWindow1Open = 3, // Receive window 1 is open
BetwReceiveWindow1_2 = 4, // Between Receive window 1 and Receive window 2
ReceiveWindow2Open = 5, // Receive window 2 is open
RetransDelay = 6, // Retransmission delay - used for ADR_ACK delay, FSK can occur
APB_delay = 7, //APB_delay
Class_C_RX2_1_open = 8, // Class C RX2 1 open
Class_C_RX2_2_open = 9 // Class C RX2 2 open
} MacState;
// Joined does not seem to be updated in the status bits.
// Assume joined at first unless a transmit command returns "not_joined".
// This will prevent a lot of unneeded join requests.
bool Joined = true;
bool AutoReply;
bool ADR;
bool SilentImmediately; // indicates the device has been silenced by the network. To enable: "mac forceENABLE"
bool MacPause; // Temporary disable the LoRaWAN protocol interpreter. (e.g. to change radio settings)
bool RxDone;
bool LinkCheck;
bool ChannelsUpdated;
bool OutputPowerUpdated;
bool NbRepUpdated; // NbRep is the number of repetitions for unconfirmed packets
bool PrescalerUpdated;
bool SecondReceiveWindowParamUpdated;
bool RXtimingSetupUpdated;
bool RejoinNeeded;
bool Multicast;
bool decode(uint32_t value) {
_rawstatus = value;
MacState = static_cast<MacState_t>(value & 0xF);
value = value >> 4;
Joined = Joined | (value & 1); value = value >> 1;
AutoReply = (value & 1); value = value >> 1;
ADR = (value & 1); value = value >> 1;
SilentImmediately = (value & 1); value = value >> 1;
MacPause = (value & 1); value = value >> 1;
RxDone = (value & 1); value = value >> 1;
LinkCheck = (value & 1); value = value >> 1;
ChannelsUpdated = ChannelsUpdated | (value & 1); value = value >> 1;
OutputPowerUpdated = OutputPowerUpdated | (value & 1); value = value >> 1;
NbRepUpdated = NbRepUpdated | (value & 1); value = value >> 1;
PrescalerUpdated = PrescalerUpdated | (value & 1); value = value >> 1;
SecondReceiveWindowParamUpdated = SecondReceiveWindowParamUpdated | (value & 1); value = value >> 1;
RXtimingSetupUpdated = RXtimingSetupUpdated | (value & 1); value = value >> 1;
RejoinNeeded = (value & 1); value = value >> 1;
Multicast = (value & 1); value = value >> 1;
/*
The following bits are cleared after issuing a “mac get status” command:
- 11 (Channels updated)
- 12 (Output power updated)
- 13 (NbRep updated)
- 14 (Prescaler updated)
- 15 (Second Receive window parameters updated)
- 16 (RX timing setup updated)
So we must keep track of them to see if they were updated since the last time they were saved to the
*/
_saveSettingsNeeded =
_saveSettingsNeeded ||
ChannelsUpdated ||
OutputPowerUpdated ||
NbRepUpdated ||
PrescalerUpdated ||
SecondReceiveWindowParamUpdated ||
RXtimingSetupUpdated;
return _saveSettingsNeeded;
}
bool saveSettingsNeeded() const { return _saveSettingsNeeded; }
bool clearSaveSettingsNeeded() {
bool ret = _saveSettingsNeeded;
_saveSettingsNeeded = false;
ChannelsUpdated = false;
OutputPowerUpdated = false;
NbRepUpdated = false;
PrescalerUpdated = false;
SecondReceiveWindowParamUpdated = false;
RXtimingSetupUpdated = false;
return ret;
}
uint32_t getRawStatus() const { return _rawstatus; };
private:
uint32_t _rawstatus = 0;
bool _saveSettingsNeeded = false;
} Status;
private:
Stream& _serial;
RN2xx3_t _moduleType = RN_NA;
//Flags to switch code paths. Default is to use OTAA.
bool _otaa = true;
FREQ_PLAN _fp = TTN_EU;
uint8_t _sf = 7;
uint32_t rxdelay1 = 1000;
uint32_t rxdelay2 = 2000;
//The default address to use on TTN if no address is defined.
//This one falls in the "testing" address space.
String _devAddr = "03FFBEEF";
// if you want to use another DevEUI than the hardware one
// use this deveui for LoRa WAN
String _deveui = "0011223344556677";
//the appeui to use for LoRa WAN
String _appeui = "0";
//the nwkskey to use for LoRa WAN
String _nwkskey = "0";
//the appskey/appkey to use for LoRa WAN
String _appskey = "0";
// The downlink messenge
String _rxMessenge = "";
String _lastErrorInvalidParam = "";
/*
* Auto configure for either RN2903 or RN2483 module
*/
RN2xx3_t configureModuleType();
bool resetModule();
void sendEncoded(const String&);
enum received_t {
accepted,
busy,
denied,
frame_counter_err_rejoin_needed,
invalid_data_len,
invalid_param,
keys_not_init,
mac_err,
mac_paused,
mac_rx,
mac_tx_ok,
no_free_ch,
not_joined,
ok,
radio_err,
radio_tx_ok,
silent,
UNKNOWN
};
static received_t determineReceivedDataType(const String& receivedData);
int readIntValue(const String& command);
bool readUIntMacGet(const String& param, uint32_t &value);
// All "mac set ..." commands return either "ok" or "invalid_param"
bool sendMacSet(const String& param, const String& value);
bool sendMacSetEnabled(const String& param, bool enabled);
bool sendMacSetCh(const String& param, unsigned int channel, const String& value);
bool sendMacSetCh(const String& param, unsigned int channel, uint32_t value);
bool setChannelDutyCycle(unsigned int channel, unsigned int dutyCycle);
bool setChannelFrequency(unsigned int channel, uint32_t frequency);
bool setChannelDataRateRange(unsigned int channel, unsigned int minRange, unsigned int maxRange);
// Set channel enabled/disabled.
// Frequency, data range, duty cycle must be issued prior to enabling the status of that channel
bool setChannelEnabled(unsigned int channel, bool enabled);
bool set2ndRecvWindow(unsigned int dataRate, uint32_t frequency);
bool setAdaptiveDataRate(bool enabled);
bool setAutomaticReply(bool enabled);
bool setTXoutputPower(int pwridx);
// Read the internal status of the module
// @retval true when update was successful
bool updateStatus();
bool saveUpdatedStatus();
// Set the serial timeout for standard transactions. (not waiting for a packet acknowledgement)
void setSerialTimeout();
// Set serial timeout to wait for 2nd receive window (RX2)
void setSerialTimeoutRX2();
void clearSerialBuffer();
static bool isHexStr(const String& string);
};
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.