text
stringlengths 8
6.88M
|
|---|
#include "stdafx.h"
#include "stdio.h"
#include "math.h"
#include "Gz.h"
#include "rend.h"
#include<vector>
#include<algorithm>
/***********************************************/
/* HW1 methods: copy here the methods from HW1 */
GzRender::GzRender(int xRes, int yRes)
{
/* HW1.1 create a framebuffer for MS Windows display:
-- set display resolution
-- allocate memory for framebuffer : 3 bytes(b, g, r) x width x height
-- allocate memory for pixel buffer
*/
xres = xRes;
yres = yRes;
framebuffer = (char *)malloc(xres * yres * 64 * sizeof(char));
pixelbuffer = static_cast<GzPixel*>(malloc(xres * yres * 64 * sizeof(struct GzPixel*)));
}
GzRender::~GzRender()
{
/* HW1.2 clean up, free buffer memory */
if (framebuffer != NULL) {
delete framebuffer;
}
if (pixelbuffer != NULL) {
delete pixelbuffer;
}
}
int GzRender::GzDefault()
{
/* HW1.3 set pixel buffer to some default values - start a new frame */
for (int j = 0; j < yres; j++) {
for (int i = 0; i < xres; i++) {
int index = ARRAY(i, j);
(pixelbuffer + index)->red = 4000;
(pixelbuffer + index)->green = 4000;
(pixelbuffer + index)->blue = 4000;
(pixelbuffer + index)->alpha = 1;
(pixelbuffer + index)->z = INT_MAX;
}
}
return GZ_SUCCESS;
}
int GzRender::GzPut(int i, int j, GzIntensity r, GzIntensity g, GzIntensity b, GzIntensity a, GzDepth z)
{
/* HW1.4 write pixel values into the buffer */
r = (r > 4095) ? 4095 : r;
g = (g > 4095) ? 4095 : g;
b = (b > 4095) ? 4095 : b;
i = (i < 0) ? 0 : i;
j = (j < 0) ? 0 : j;
i = (i >= yres) ? yres - 1 : i;
j = (j >= xres) ? xres - 1 : j;
int index = ARRAY(i, j);
(pixelbuffer + index)->red = r;
(pixelbuffer + index)->green = g;
(pixelbuffer + index)->blue = b;
(pixelbuffer + index)->alpha = a;
(pixelbuffer + index)->z = z;
return GZ_SUCCESS;
}
int GzRender::GzGet(int i, int j, GzIntensity *r, GzIntensity *g, GzIntensity *b, GzIntensity *a, GzDepth *z)
{
/* HW1.5 retrieve a pixel information from the pixel buffer */
int index = ARRAY(i, j);
r = &(pixelbuffer + index)->red;
g = &(pixelbuffer + index)->green;
b = &(pixelbuffer + index)->blue;
a = &(pixelbuffer + index)->alpha;
z = &(pixelbuffer + index)->z;
return GZ_SUCCESS;
}
int GzRender::GzFlushDisplay2File(FILE* outfile)
{
/* HW1.6 write image to ppm file -- "P6 %d %d 255\r" */
fprintf(outfile, "P6 %d %d 255\r", xres, yres);
for (int j = 0; j < yres; j++) {
for (int i = 0; i < xres; i++) {
int index = ARRAY(i, j);
fprintf(outfile, "%c%c%c",
(pixelbuffer + index)->red >> 4,
(pixelbuffer + index)->green >> 4,
(pixelbuffer + index)->blue >> 4);
}
}
return GZ_SUCCESS;
}
int GzRender::GzFlushDisplay2FrameBuffer()
{
/* HW1.7 write pixels to framebuffer:
- put the pixels into the frame buffer
- CAUTION: when storing the pixels into the frame buffer, the order is blue, green, and red
- NOT red, green, and blue !!!
*/
int k = 0;
for (int j = 0; j < yres; j++) {
for (int i = 0; i < xres; i++) {
int index = ARRAY(i, j);
framebuffer[k++] = (pixelbuffer + index)->blue >> 4;
framebuffer[k++] = (pixelbuffer + index)->green >> 4;
framebuffer[k++] = (pixelbuffer + index)->red >> 4;
}
}
char* test = framebuffer;
printf("Test");
return GZ_SUCCESS;
}
/***********************************************/
/* HW2 methods: implement from here */
int GzRender::GzPutAttribute(int numAttributes, GzToken *nameList, GzPointer *valueList)
{
/* HW 2.1
-- Set renderer attribute states (e.g.: GZ_RGB_COLOR default color)
-- In later homeworks set shaders, interpolaters, texture maps, and lights
*/
switch (numAttributes) {
case 1:
float *color = (*(GzColor *)valueList[0]);
for (int i = 0; i < 3; i++) {
flatcolor[i] = *color;
color++;
}
}
return GZ_SUCCESS;
}
int GzRender::GzPutTriangle(int numParts, GzToken *nameList, GzPointer *valueList)
/* numParts - how many names and values */
{
/* HW 2.2
-- Pass in a triangle description with tokens and values corresponding to
GZ_NULL_TOKEN: do nothing - no values
GZ_POSITION: 3 vert positions in model space
-- Invoke the rastrizer/scanline framework
-- Return error code
*/
float *position = (*(GzCoord *)valueList[0]);
renderTriangle(position);
return GZ_SUCCESS;
}
void GzRender::renderTriangle(float *position) {
sortVertices(position);
assignEdges();
float xp = determineLeftRightEdge(v1, v3, v2[1]);
if (xp > v2[0]) {
renderLeftTriangle();
}
else {
renderRightTriangle();
}
}
void GzRender::renderLeftTriangle() {
GzCoord spanStart, spanEnd, spanCurrent;
float spanSlopeZ;
float yDeltaV1V2 = findDelta(eV1V2.current[1]);
while (eV1V2.current[1] <= floor(eV1V2.end[1])) {
updateTopEdges(yDeltaV1V2);
for (int i = 0; i < 3; i++) {
spanStart[i] = eV1V2.current[i];
spanEnd[i] = eV1V3.current[i];
spanCurrent[i] = eV1V2.current[i];
}
spanSlopeZ = findSlope('s', spanStart, spanEnd);
float deltaX = findDelta(spanCurrent[0]);
while (spanCurrent[0] <= spanEnd[0]) {
spanCurrent[0] = spanCurrent[0] + deltaX;
spanCurrent[2] = spanCurrent[2] + deltaX * spanSlopeZ;
int index = ARRAY(spanCurrent[0], spanCurrent[1]);
int zPix = (pixelbuffer + index)->z;
if (spanCurrent[2] < zPix) {
GzPut(spanCurrent[0], spanCurrent[1],
ctoi(flatcolor[0]), ctoi(flatcolor[1]), ctoi(flatcolor[2]), 1, spanCurrent[2]);
}
}
}
float yDeltaV2V3 = findDelta(eV2V3.current[1]);
while (eV2V3.current[1] <= floor(eV2V3.end[1])) {
updateBottomEdges(yDeltaV2V3);
for (int i = 0; i < 3; i++) {
spanStart[i] = eV2V3.current[i];
spanEnd[i] = eV1V3.current[i];
spanCurrent[i] = eV2V3.current[i];
}
spanSlopeZ = findSlope('s', spanStart, spanEnd);
float deltaX = findDelta(spanCurrent[0]);
while (spanCurrent[0] <= spanEnd[0]) {
spanCurrent[0] = spanCurrent[0] + deltaX;
spanCurrent[2] = spanCurrent[2] + deltaX * spanSlopeZ;
int index = ARRAY(spanCurrent[0], spanCurrent[1]);
int zPix = (pixelbuffer + index)->z;
if (spanCurrent[2] < zPix) {
GzPut(spanCurrent[0], spanCurrent[1],
ctoi(flatcolor[0]), ctoi(flatcolor[1]), ctoi(flatcolor[2]), 1, spanCurrent[2]);
}
}
}
}
void GzRender::renderRightTriangle() {
GzCoord spanStart, spanEnd, spanCurrent;
float spanSlopeZ;
short r = 0, g = 0, b = 0, a = 0;
int z = 0;
float yDeltaV1V2 = findDelta(eV1V2.current[1]);
while (eV1V2.current[1] <= floor(eV1V2.end[1])) {
updateTopEdges(yDeltaV1V2);
for (int i = 0; i < 3; i++) {
spanStart[i] = eV1V3.current[i];
spanEnd[i] = eV1V2.current[i];
spanCurrent[i] = eV1V3.current[i];
}
spanSlopeZ = findSlope('s', spanStart, spanEnd);
float deltaX = findDelta(spanCurrent[0]);
while (spanCurrent[0] <= spanEnd[0]) {
spanCurrent[0] = spanCurrent[0] + deltaX;
spanCurrent[2] = spanCurrent[2] + deltaX * spanSlopeZ;
int index = ARRAY(spanCurrent[0], spanCurrent[1]);
int zPix = (pixelbuffer + index)->z;
if (spanCurrent[2] < zPix) {
GzPut(spanCurrent[0], spanCurrent[1],
ctoi(flatcolor[0]), ctoi(flatcolor[1]), ctoi(flatcolor[2]), 1, spanCurrent[2]);
}
}
}
float yDeltaV2V3 = findDelta(eV2V3.current[1]);
while (eV2V3.current[1] <= floor(eV2V3.end[1])) {
updateBottomEdges(yDeltaV2V3);
for (int i = 0; i < 3; i++) {
spanStart[i] = eV1V3.current[i];
spanEnd[i] = eV2V3.current[i];
spanCurrent[i] = eV1V3.current[i];
}
spanSlopeZ = findSlope('s', spanStart, spanEnd);
float deltaX = findDelta(spanCurrent[0]);
while (spanCurrent[0] <= spanEnd[0]) {
spanCurrent[0] = spanCurrent[0] + deltaX;
spanCurrent[2] = spanCurrent[2] + deltaX * spanSlopeZ;
int index = ARRAY(spanCurrent[0], spanCurrent[1]);
int zPix = (pixelbuffer + index)->z;
if (spanCurrent[2] < zPix) {
GzPut(spanCurrent[0], spanCurrent[1],
ctoi(flatcolor[0]), ctoi(flatcolor[1]), ctoi(flatcolor[2]), 1, spanCurrent[2]);
}
}
}
}
bool sortHelper(const float &y1, const float &y2) {
return (y1 < y2);
}
void GzRender::sortVertices(float *position) {
GzCoord vert1 = { position[6], position[7], position[8] };
GzCoord vert2 = { position[3], position[4], position[5] };
GzCoord vert3 = { position[0], position[1], position[2] };
std::vector<float> v;
v.push_back(position[1]);
v.push_back(position[4]);
v.push_back(position[7]);
std::sort(v.begin(), v.end(), sortHelper);
int i = 1, j = 0;
while (i < 8) {
if (position[i] == v[0]) {
v1[j++] = position[i - 1];
v1[j++] = position[i];
v1[j++] = position[i + 1];
j = 0;
}
if (position[i] == v[1]) {
v2[j++] = position[i - 1];
v2[j++] = position[i];
v2[j++] = position[i + 1];
j = 0;
}
if (position[i] == v[2]) {
v3[j++] = position[i - 1];
v3[j++] = position[i];
v3[j++] = position[i + 1];
j = 0;
}
i += 3;
}
}
float GzRender::determineLeftRightEdge(GzCoord v1, GzCoord v2, float y) {
return -1 * ((v2[0] - v1[0]) * y + (v1[0] * v2[1] - v2[0] * v1[1])) / (v1[1] - v2[1]);
}
void GzRender::assignEdges() {
for (int i = 0; i < 3; i++) {
eV1V2.start[i] = v1[i];
eV1V2.end[i] = v2[i];
eV1V2.current[i] = v1[i];
eV2V3.start[i] = v2[i];
eV2V3.end[i] = v3[i];
eV2V3.current[i] = v2[i];
eV1V3.start[i] = v1[i];
eV1V3.end[i] = v3[i];
eV1V3.current[i] = v1[i];
}
eV1V2.slopeX = findSlope('x', eV1V2.start, eV1V2.end);
eV1V2.slopeZ = findSlope('z', eV1V2.start, eV1V2.end);
eV2V3.slopeX = findSlope('x', eV2V3.start, eV2V3.end);
eV2V3.slopeZ = findSlope('z', eV2V3.start, eV2V3.end);
eV1V3.slopeX = findSlope('x', eV1V3.start, eV1V3.end);
eV1V3.slopeZ = findSlope('z', eV1V3.start, eV1V3.end);
}
void GzRender::updateTopEdges(float deltaY) {
eV1V2.current[0] = eV1V2.current[0] + eV1V2.slopeX * deltaY;
eV1V3.current[0] = eV1V3.current[0] + eV1V3.slopeX * deltaY;
eV1V2.current[1] = eV1V2.current[1] + deltaY;
eV1V3.current[1] = eV1V3.current[1] + deltaY;
eV1V2.current[2] = eV1V2.current[2] + eV1V2.slopeZ * deltaY;
eV1V3.current[2] = eV1V3.current[2] + eV1V3.slopeZ * deltaY;
}
void GzRender::updateBottomEdges(float deltaY) {
eV2V3.current[0] = eV2V3.current[0] + eV2V3.slopeX * deltaY;
eV1V3.current[0] = eV1V3.current[0] + eV1V3.slopeX * deltaY;
eV2V3.current[1] = eV2V3.current[1] + deltaY;
eV1V3.current[1] = eV1V3.current[1] + deltaY;
eV2V3.current[2] = eV2V3.current[2] + eV2V3.slopeZ * deltaY;
eV1V3.current[2] = eV1V3.current[2] + eV1V3.slopeZ * deltaY;
}
float GzRender::findSlope(char axis, GzCoord v1, GzCoord v2) {
switch (axis) {
case 'x':
return (v2[0] - v1[0]) / (v2[1] - v1[1]);
break;
case 'z':
return (v2[2] - v1[2]) / (v2[1] - v1[1]);
break;
case 's':
return (v2[2] - v1[2]) / (v2[0] - v1[0]);
break;
}
}
|
#pragma once
#include "Preamble.h"
/**
*@file
*
* MyPdf.h defines class MyPdf and creates references for all memberfunctions.
*
* The class MyPdf creates the probability density function for the Monte Carlo Simulation.
* This follows an exponential disgtribution multiplied by a sinusoid.
*
*/
class MyPdf
{
public:
/**
* Constructor that initializes all the parameters for the probability density function
*
* @param tau is the rate of change.
*
* @param A sets the amplitude of the sinusoid.
*
* @param t_max sets the maximum of the interval for which
* the exponential distribution can be used
*/
MyPdf(double tau, double A, double t_max);
/**
* sets parameters tau and A in the pdf
*/
void setParameters(mat params);
/**
* Gives a random value drawn from an exponential distribution multiplied by a sinusoid.
*
* @param noise is the noise fraction from a normal distribution to be added.
*
* @return random value drawn from the pdf
*/
double drawNextValueNoise(double noise);
/**
* Evaluates the probability density function at a point in time t
*
* @param t free parameter in the probability density function
* @return value of probability density function at a point in time t
*/
double evaluate( double t );
private:
double tau, A, t_max, max_random, omega;
};
|
#include "stdafx.h"
#include "debugInfo.h"
debugInfo::debugInfo()
{
}
debugInfo::~debugInfo()
{
}
void debugInfo::reload()
{
pair[0] ++;
int idx = s_voxelObj->m_hashTable.getSymmetricBox(pair[0]);
pair[1] = idx;
}
void debugInfo::reloadData()
{
FILE * f = fopen("../test/debugInfo.txt", "r");
ASSERT(f);
data.clear();
int row, col;
fscanf(f, "%d %d", &row, &col);
for (int i = 0; i < row; i++)
{
std::vector <std::string> d;
for (int j = 0; j < col; j++)
{
char tmp[101];
fscanf(f, "%s", tmp);
d.push_back(std::string(tmp));
}
data.push_back(d);
}
fclose(f);
// Load int array
voxelIdxs.clear();
for (int i = 0; i < data.size(); i++)
{
voxelIdxs.push_back(atoi(data[i][1].c_str()));
}
}
void debugInfo::drawVoxelIdxs()
{
std::vector<voxelBox> *boxes = &s_voxelObj->m_boxes;
for (int i = 0; i < voxelIdxs.size(); i++)
{
Util_w::drawBoxSurface(boxes->at(voxelIdxs[i]).leftDown, boxes->at(voxelIdxs[i]).rightUp);
}
}
void debugInfo::drawtestVoxelSym()
{
int idx = s_voxelObj->m_hashTable.getSymmetricBox(pair[0]);
pair[1] = idx;
std::vector<voxelBox> *boxes = &s_voxelObj->m_boxes;
for (int i = 0; i < 2; i++)
{
if (pair[i] != -1)
{
Util_w::drawBoxSurface(boxes->at(pair[i]).leftDown, boxes->at(pair[i]).rightUp);
}
}
}
|
#include "stdafx.h"
#include "Sparkler.h"
#include "Components.h"
Sparkler::Sparkler(DirectX::XMFLOAT3 position, DirectX::XMFLOAT4 color, float lifeTime, std::wstring assetFile, float size, float speed, UINT amount) :
m_ElapsedTime(0.f),
m_LifeTime(lifeTime),
m_Size(size),
m_Speed(speed),
m_Position(position),
m_AssetFile(assetFile),
m_pParticleEmitter(nullptr),
m_Color(color),
m_Amount(amount)
{
}
void Sparkler::Initialize(const GameContext& gameContext)
{
SetTag(L"Sparkler");
UNREFERENCED_PARAMETER(gameContext);
m_pParticleEmitter = new ParticleEmitterComponent(m_AssetFile, m_Amount);
AddComponent(m_pParticleEmitter);
m_pParticleEmitter->SetMinSize(m_Size*0.5f);
m_pParticleEmitter->SetMaxSize(m_Size);
m_pParticleEmitter->SetMinEnergy(0.2f);
m_pParticleEmitter->SetMaxEnergy(0.5f);
m_pParticleEmitter->SetVelocity({m_Speed, m_Speed, m_Speed});
m_pParticleEmitter->SetColor(m_Color);
GetTransform()->Translate(m_Position);
}
void Sparkler::Update(const GameContext& gameContext)
{
m_ElapsedTime += gameContext.pGameTime->GetElapsed();
if (m_ElapsedTime > m_LifeTime)
this->~Sparkler();
}
|
#include <DIET_data.h>
#define EST_CPUIDLE (EST_USERDEFINED+1)
#define EST_CONSO (EST_USERDEFINED+2)
#define EST_NODEFLOPS (EST_USERDEFINED+3)
#define EST_COREFLOPS (EST_USERDEFINED+4)
#define EST_NUMCORES (EST_USERDEFINED+5)
#define EST_CURRENTJOBS (EST_USERDEFINED+6)
#define EST_CONSOJOB (EST_USERDEFINED+7)
|
#include <stdio.h>
#include <conio.h>
#include <dos.h>
void main () {
clrscr();
int A[2][2]={2,3,3,5};
int r,c;
// SYMMETRIC MATRIX
printf("\n\n\tSYMMETRIC MATRIX");
printf("\n\n A Square Matrix is said to be Symmetric,\n\n\t\tIf A(transpose) = A.");
printf("\n\n\n\tLet A be any Matrix\n\n");
for (int i=0; i<2; i++){
printf("\t");
for(int j=0; j<2; j++)
printf(" %d ",A[i][j]);
printf("\n");
}
printf("\n\n\tTranspose of Matrix A will be\n\n");
for (i=0; i<2; i++){
printf("\t");
for(int j=0; j<2; j++)
printf(" %d ",A[j][i]);
printf("\n");
}
getche();
}
|
#pragma once
#include <QObject>
#include <QStringList>
#include "PhoneticService.h"
#include "ComponentsInfrastructure.h"
#include "SpeechAnnotation.h"
#include "SpeechDataValidation.h"
namespace PticaGovorun
{
class PhoneticDictionaryViewModel : public QObject
{
Q_OBJECT
std::shared_ptr<SpeechData> speechData_;
public:
signals :
void matchedWordsChanged();
void phoneticTrnascriptChanged();
public:
PhoneticDictionaryViewModel(std::shared_ptr<SpeechData> speechData, std::shared_ptr<PhoneRegistry> phoneReg);
void updateSuggesedWordsList(const QString& browseDictStr, const QString& currentWord);
const QStringList& matchedWords() const;
void showWordPhoneticTranscription(const QString& browseDictStr, const std::wstring& word);
const QString wordPhoneticTranscript() const;
void setEditedWordSourceDictionary(const QString& editedWordSourceDictionary);
void updateWordPronunciation(const QString& dictStr, const QString& newWord, const QString& newWordProns);
QString getWordAutoPhoneticExpansion(const QString& word) const;
private:
std::shared_ptr<PhoneRegistry> phoneReg_;
QStringList matchedWords_;
QString wordPhoneticTrnascript_;
QString editedWordSourceDictionary_; // the dictId from where the current word is taken
};
}
|
// Copyright (c) 2006, Giovanni P. Deretta
// Copyright (c) 2012 Hartmut Kaiser
// Copyright (c) 2011-2014 Bryce Adelstein-Lelbach
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <pika/pika.hpp>
#include <pika/pika_init.hpp>
#include <pika/string_util/classification.hpp>
#include <pika/string_util/split.hpp>
#include <fmt/printf.h>
#include <chrono>
#include <cstdint>
#include <ctime>
#include <iostream>
#include <random>
#include <string>
#include <vector>
#include "worker_timed.hpp"
char const* benchmark_name = "Context Switching Overhead - pika";
using namespace pika::program_options;
using namespace pika::threads;
using pika::threads::coroutine_type;
using std::cout;
///////////////////////////////////////////////////////////////////////////////
std::uint64_t payload = 0;
std::uint64_t contexts = 1000;
std::uint64_t iterations = 100000;
std::uint64_t seed = 0;
bool header = true;
///////////////////////////////////////////////////////////////////////////////
std::string format_build_date()
{
std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now();
std::time_t current_time = std::chrono::system_clock::to_time_t(now);
std::string ts = std::ctime(¤t_time);
ts.resize(ts.size() - 1); // remove trailing '\n'
return ts;
}
///////////////////////////////////////////////////////////////////////////////
void print_results(double w_M)
{
if (header)
{
cout << "# BENCHMARK: " << benchmark_name << "\n";
cout << "# VERSION: " << PIKA_HAVE_GIT_COMMIT << " " << format_build_date() << "\n"
<< "#\n";
// Note that if we change the number of fields above, we have to
// change the constant that we add when printing out the field # for
// performance counters below (e.g. the last_index part).
cout << "## 0:PLOAD:Payload [micro-seconds] - Independent Variable\n"
"## 1:OSTHRDS:OS-Threads - Independent Variable\n"
"## 2:CTXS:# of Contexts - Independent Variable\n"
"## 3:ITER:# of Iterations - Independent Variable\n"
"## 4:SEED:PRNG seed - Independent Variable\n"
"## 5:WTIME_CS:Walltime/Context Switch [nano-seconds]\n";
}
std::uint64_t const os_thread_count = pika::get_os_thread_count();
double w_T = iterations * payload * os_thread_count * 1e-6;
// double E = w_T/w_M;
double O = w_M - w_T;
fmt::print(cout, "{} {} {} {} {} {:.14g}", payload, os_thread_count, contexts, iterations, seed,
(O / (2 * iterations * os_thread_count)) * 1e9);
cout << "\n";
}
///////////////////////////////////////////////////////////////////////////////
struct kernel
{
pika::threads::detail::thread_result_type operator()(thread_restart_state) const
{
worker_timed(payload * 1000);
return pika::threads::detail::thread_result_type(
pika::threads::detail::thread_schedule_state::pending,
pika::threads::detail::invalid_thread_id);
}
bool operator!() const { return true; }
};
double perform_2n_iterations()
{
std::vector<coroutine_type*> coroutines;
std::vector<std::uint64_t> indices;
coroutines.reserve(contexts);
indices.reserve(iterations);
std::mt19937_64 prng(seed);
std::uniform_int_distribution<std::uint64_t> dist(0, contexts - 1);
kernel k;
for (std::uint64_t i = 0; i < contexts; ++i)
{
coroutine_type* c = new coroutine_type(k, pika::threads::detail::invalid_thread_id);
coroutines.push_back(c);
}
for (std::uint64_t i = 0; i < iterations; ++i) indices.push_back(dist(prng));
///////////////////////////////////////////////////////////////////////
// Warmup
for (std::uint64_t i = 0; i < iterations; ++i) { (*coroutines[indices[i]])(wait_signaled); }
pika::chrono::detail::high_resolution_timer t;
for (std::uint64_t i = 0; i < iterations; ++i) { (*coroutines[indices[i]])(wait_signaled); }
double elapsed = t.elapsed();
for (std::uint64_t i = 0; i < contexts; ++i) { delete coroutines[i]; }
coroutines.clear();
return elapsed;
}
int pika_main(variables_map& vm)
{
{
if (vm.count("no-header")) header = false;
if (!seed) seed = std::uint64_t(std::time(nullptr));
std::uint64_t const os_thread_count = pika::get_os_thread_count();
std::vector<pika::shared_future<double>> futures;
std::uint64_t num_thread = pika::get_worker_thread_num();
for (std::uint64_t i = 0; i < os_thread_count; ++i)
{
if (num_thread == i) continue;
futures.push_back(pika::async(&perform_2n_iterations));
}
double total_elapsed = perform_2n_iterations();
for (std::uint64_t i = 0; i < futures.size(); ++i) total_elapsed += futures[i].get();
print_results(total_elapsed);
}
return pika::finalize();
}
///////////////////////////////////////////////////////////////////////////////
int main(int argc, char* argv[])
{
// Configure application-specific options.
options_description cmdline("usage: " PIKA_APPLICATION_STRING " [options]");
cmdline.add_options()("payload", value<std::uint64_t>(&payload)->default_value(0),
"artificial delay of each coroutine")
("contexts", value<std::uint64_t>(&contexts)->default_value(100000),
"number of contexts use")
("iterations", value<std::uint64_t>(&iterations)->default_value(100000),
"number of iterations to invoke (2 * iterations context switches will occur)")
("seed", value<std::uint64_t>(&seed)->default_value(0),
"seed for the pseudo random number generator (if 0, a seed is chosen based on "
"the current system time)")
("no-header", "do not print out the header");
// Initialize and run pika.
pika::init_params init_args;
init_args.desc_cmdline = cmdline;
return pika::init(argc, argv, init_args);
}
|
#include "Widget/timelinewidget.h"
#include "ui_timelinewidget.h"
#include <QStyle>
TimeLineWidget::TimeLineWidget(QWidget *parent) :
QFrame(parent),
ui(new Ui::TimeLineWidget)
{
ui->setupUi(this);
ui->playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));
ui->pauseButton->setIcon(style()->standardIcon(QStyle::SP_MediaPause));
ui->gotoStartButton->setIcon(style()->standardIcon(QStyle::SP_MediaSkipBackward));
ui->gotoEndButton->setIcon(style()->standardIcon(QStyle::SP_MediaSkipForward));
ui->scrubber->setRange(ui->startFrame->value(), ui->endFrame->value());
// initialise timeline
m_timeLine = std::unique_ptr<TimeLine>(new TimeLine((ui->endFrame->value() - ui->startFrame->value())* ui->fps->value() * 1000, this));
// initialise default values
m_timeLine->setLoopCount(0);
m_timeLine->SetFrameRange(ui->startFrame->value(), ui->endFrame->value());
m_timeLine->setCurveShape(TimeLine::CurveShape::LinearCurve);
m_timeLine->setDuration(1000 * (ui->endFrame->value() - ui->startFrame->value())/ ui->fps->value());
//------------------------------
// Setup connections
connect(ui->startFrame, QOverload<int>::of(&QSpinBox::valueChanged), [this](int value){
m_timeLine->setStartFrame(value);
m_timeLine->setDuration(1000 * (ui->endFrame->value() - ui->startFrame->value())/ ui->fps->value());
ui->scrubber->setRange(value, ui->endFrame->value());
// ui->scrubber->setValue(m_timeLine->currentFrame());
});
connect(ui->endFrame, QOverload<int>::of(&QSpinBox::valueChanged), [this](int value){
m_timeLine->setEndFrame(value);
m_timeLine->setDuration(1000 * (ui->endFrame->value() - ui->startFrame->value())/ ui->fps->value());
ui->scrubber->setRange(ui->startFrame->value(), value);
// ui->scrubber->setValue(m_timeLine->currentFrame());
});
connect(ui->fps, QOverload<double>::of(&QDoubleSpinBox::valueChanged), [this](double value){
m_timeLine->setUpdateInterval(1000/value);
m_timeLine->setDuration(1000 * (ui->endFrame->value() - ui->startFrame->value())/ ui->fps->value());
});
connect(ui->playButton, &QPushButton::clicked, [this](bool checked){
Play();
});
connect(ui->pauseButton, &QPushButton::clicked, [this](bool checked){
Pause();
});
connect(ui->gotoStartButton, &QPushButton::clicked, [this](bool checked){
m_timeLine->setCurrentTime(0);
});
connect(ui->gotoEndButton, &QPushButton::clicked, [this](bool checked){
m_timeLine->setCurrentTime((1000*ui->endFrame->value()-1)/ui->fps->value());
});
connect(ui->scrubber, &QSlider::sliderMoved,[this](int frame){
if(m_timeLine->state() != TimeLine::State::Running)
{
m_timeLine->setCurrentTime((1000*frame)/ui->fps->value());
}
});
connect(ui->frame, QOverload<int>::of(&QSpinBox::valueChanged), [this](int value){
if(m_timeLine->state() != TimeLine::State::Running)
{
m_timeLine->setCurrentTime((1000*value)/ui->fps->value());
}
});
connect(m_timeLine.get(), &TimeLine::frameChanged, ui->scrubber, &QSlider::setValue);
connect(m_timeLine.get(), &TimeLine::frameChanged, ui->frame, &QSpinBox::setValue);
connect(m_timeLine.get(), &TimeLine::frameChanged, this, &TimeLineWidget::OnFrameChanged);
connect(ui->cache, &QCheckBox::clicked, [this](bool checked){
emit CacheChecked(checked);
});
}
TimeLineWidget::~TimeLineWidget()
{
delete ui;
}
void TimeLineWidget::Pause()
{
// m_timeLine->SetSavedState(TimeLine::State::Paused);
auto state = m_timeLine->state();
if(state == TimeLine::State::Running)
{
m_timeLine->setPaused(true);
}
}
void TimeLineWidget::Play()
{
// m_timeLine->SetSavedState(TimeLine::State::Running);
auto state = m_timeLine->state();
if(state == TimeLine::State::NotRunning)
{
m_timeLine->resume();
}
else if(state == TimeLine::State::Paused)
{
m_timeLine->resume();
}
}
void TimeLineWidget::OnFrameChanged(int frame)
{
emit FrameChanged(frame);
}
void TimeLineWidget::OnFrameCached(int frame)
{
}
void TimeLineWidget::OnFrameFinished(int frame)
{
m_timeLine->OnFrameFinished(frame);
}
void TimeLineWidget::OnFrameRangeChanged(int frameRange)
{
ui->startFrame->setValue(0);
ui->endFrame->setValue(frameRange);
// m_timeLine->setEndFrame(frameRange);
// m_timeLine->setDuration(1000 * (ui->endFrame->value() - ui->startFrame->value())/ ui->fps->value());
// ui->scrubber->setRange(ui->startFrame->value(), value);
// ui->scrubber->setValue(m_timeLine->currentFrame());
}
|
#include<bits/stdc++.h>
using namespace std;
class Node{
public:
int key;
Node* left;
Node* right;
};
class BST{
public:
Node* search(Node* root, int key){
if(root==NULL||root->key==key){
cout<<"search node: "<<root->key<<endl;
return root;
}
if(root->key<key){
return search(root->right,key);
}
if(root->key>key){
return search(root->left,key);
}
return root;
}
Node* insert(Node* root, int key){
if(!root){
Node* n = new Node();
n->key = key;
n->left = NULL;
n->right = NULL;
return n;
}
if(key>root->key){
root->right = insert(root->right,key);
}
else{
root->left = insert(root->left, key);
}
return root;
}
void inorder(Node* root){
if(root!=NULL){
inorder(root->left);
cout<<root->key<<" ";
inorder(root->right);
}
}
Node* minValue(Node* root){
Node* min = root;
while(min&&min->left!=NULL){
min = min->left;
}
cout<<"THE MINIMUM VALUE OF THE BST IS "<<min->key<<endl;
return min;
}
void maxValue(Node* root){
Node* max = root;
while(max&&max->left!=NULL){
max = max->left;
}
cout<<"THE MAXIMUM VALUE OF THE BST IS "<<max->key<<endl;
}
Node* del(Node* root, int key){
if(root == NULL){
return root;
}
if(key>root->key){
root->right = del(root->right,key);
}
else if(key< root->key){
root->left = del(root->left, key);
}
else{
if(root->left==NULL){
Node* temp = root->right;
free(root);
return temp;
}
else if(root->right==NULL){
Node* temp = root->left;
free(root);
return temp;
}
Node* temp = minValue(root->right);
root->key = temp->key;
root->right = del(root->right,temp->key);
}
return root;
}
};
int main(){
Node* root = NULL;
BST b;
root = b.insert(root, 34);
root = b.insert(root, 323);
root = b.insert(root, 12);
root = b.insert(root, 23);
root= b.insert(root,512);
b.search(root,34);
cout<<root->key<<endl;
b.inorder(root);
root = b.del(root, 23);
b.inorder(root);
return 0;
}
|
#include <cstdio>
int main(){
//1
/*int numero;
int dias;
int minutos;
int horas;
int resto;
printf("Introduzca minutos");
scanf("%d", &numero);
dias = numero / 1440;
resto = numero % 1440;
horas = resto / 60;
minutos = resto % 60;
printf(" %d Dias, %d horas, %d minutos", dias, horas, minutos);
//2
int num1;
int num2;
printf("Introduzca un numero: ");
scanf("%d", &num1);
printf("Introduzca otro numero: ");
scanf("%d", &num2);
if (((num1 < 0) && (num2 > 0)) || ((num1 > 0) && (num2 < 0))){
printf("El resultado es negativo");
}else{
if ((num1 == 0 ) || (num2 == 0)){
printf("Resul nulo");
}else{
printf("Resul positivo");
}
}
//3
int num1;
int num2;
int num3;
printf("introduzca un numero:");
scanf("%d", &num1);
printf("introduzca un numero:");
scanf("%d", &num2);
printf("introduzca un numero:");
scanf("%d", &num3);
if((num1 %2 == 0) && (num2 %2 == 0)){
printf("los numeros %d y %d son pares.", num1, num2);
}else{
if((num1%2 == 0) && (num3%2 == 0)){
printf("los numeros %d y %d son pares.", num1, num3);
}else{
if((num2%2 == 0) && (num3%2 == 0)){
printf("los numeros %d y %d son pares.", num2, num3);
}
}
}
//4
int num1;
int num2;
int resultado = 1;
do{
printf("Introduzca base: ");
scanf("%d", &num1);
printf("Introduzca exponente: ");
scanf("%d", &num2);
}while(((num1 <1) && (num2 <1)) || ((num1 <1) || (num2 <1)));
for(int i=0;i<num2;i++){
resultado = resultado * num1;
}
printf ("El resultado es: %d", resultado);
//5
int maximo=0;
int minimo=0;
int num;
printf("introduzca numero 1: ");
scanf("%d", &num);
maximo = num;
minimo = num;
for(int i=0;i<19;i++){
printf("introduzca numero %d: ", i+2);
scanf("%d", &num);
if (num > maximo){
maximo = num;
}else{
if(num < minimo){
minimo = num;
}
}
}
printf("El maximo es %d y el minimo es %d ", maximo, minimo);
//6
int num1;
printf("introduzca un numero: ");
scanf("%d", &num1);
if((num1<1)||(num1>9)){
printf("ERROR");
}else{
if((num1 == 1) || (num1 == 2) || (num1 == 3) || (num1 == 5) || (num1 == 7) || (num1 == 9)){
printf("primo");
}else{
printf("no primo");
}
}
//7
int num;
int anterior;
do {
printf("Introduce un numero. 0 para terminar: ");
scanf("%d", &num);
}while (num<0);
anterior=num;
while (num>0){
do{
printf("introduce otro numero. 0 para terminar: ");
scanf("%d", &num);
if ((num<=anterior) && (num!=0))
printf("numero no válido\n");
} while ((num<anterior) && (num!=0));
if (num!=0)
anterior=num;
}
//8
int num;
int cont_pares = 0;
int suma=0;
int sumaimp=0;
int cont_imp = 0;
float media;
for(int i=0; i<10;i++){
printf("numero: ");
scanf("%d", &num);
if(num%2 == 0 ){
cont_pares = cont_pares + 1;
suma = suma + num;
}else{
cont_imp = cont_imp + 1;
sumaimp = sumaimp + num;
}
}
media = (sumaimp / cont_imp) ;
printf("Suma pares: %d", suma);
printf("\nNumero pares: %d", cont_pares);
printf("\nMedia impares: %f", media);
*/
return 0;
}
|
/*
* Copyright (c) 2015-2017 Morwenn
* SPDX-License-Identifier: MIT
*/
#ifndef CPPSORT_DETAIL_ANY_ALL_H_
#define CPPSORT_DETAIL_ANY_ALL_H_
namespace cppsort
{
namespace detail
{
constexpr auto any(bool head)
-> bool
{
return head;
}
template<typename... Bools>
constexpr auto any(bool head, Bools... tail)
-> bool
{
return head || any(tail...);
}
constexpr auto all(bool head)
-> bool
{
return head;
}
template<typename... Bools>
constexpr auto all(bool head, Bools... tail)
-> bool
{
return head && all(tail...);
}
}}
#endif // CPPSORT_DETAIL_ANY_ALL_H_
|
#include <iostream>
using namespace std;
int main()
{
int num = 0;
cout << "How many numbers would you like to have? ";
cin >> num;
for ( int a = 1; a <= num; ++a) {
if ( a % 3 == 0 and a % 7 == 0 ) {
cout << "zip boing" << endl;
} else if ( a % 3 == 0 ) {
cout << "zip" << endl;
} else if ( a % 7 == 0 and a % 7 == 0 ) {
cout << "boing" << endl;
} else {
cout << a << endl;
}
}
}
|
#include<iostream>
#include<cstdio>
#include<vector>
#include<queue>
using namespace std;
const int maxn = 2000 + 10;
const int INF = 1 << 30;
struct edge{
int from,to,dist;
edge(int from,int to,int dist):from(from),to(to),dist(dist) {}
bool operator < (const edge& rhs) const {
return dist < rhs.dist;
}
};
struct node{
int from,dist;
bool operator < (const node& rhs) const {
return dist < rhs.dist;
}
};
struct Dijkstra{
int n,m;
vector<edge> edges;
vector<int> G[maxn];
int dis[maxn];
int path[maxn];
void init(int n)
{
this->n = n;
for (int i = 1;i <= n; i++)
{G[i].clear();
dis[i] = INF;
}
edges.clear();
}
void addedge(int from,int to,int dist)
{
edges.push_back((edge){from,to,dist});
G[from].push_back(edges.size()-1);
}
int dijk(int s,int t)
{
priority_queue<node> Q;
dis[s] = 0;
Q.push((node){s,0});
while (!Q.empty())
{node now = Q.top();Q.pop();
if (now.dist != dis[now.from]) continue;
for (int i = 0;i < G[now.from].size(); i++)
{edge& rec = edges[G[now.from][i]];
if (dis[rec.to] > dis[now.from] + rec.dist)
{dis[rec.to] = dis[now.from] + rec.dist;
path[rec.to] = G[now.from][i];
Q.push((node){rec.to,dis[rec.to]});
}
}
}
return dis[t];
}
};
Dijkstra D;
int main()
{int n,m,s,t;
cin >> n >> m >> s >> t;
D.init(n);
for (int i = 1;i <= m; i++)
{int from,to,dist;
scanf("%d%d%d",&from,&to,&dist);
D.addedge(from,to,dist);
}
cout << D.dijk(s,t) << endl;
return 0;
}
|
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
void Init_ListNode(ListNode* head, vector<int> vec)
{
if (vec.size() == 0)
{
head = NULL;
return;
}
ListNode* p;
p = head;
p->val = vec[0];
for (int i = 1; i < vec.size(); i++)
{
ListNode* q = new ListNode(vec[i]);
p->next = q;
p = p->next;
}
}
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
//基本思想:单链表基本操作,记得删除等于val节点内存空间
ListNode* start = new ListNode(0);
start->next = head;
ListNode* p = start, * toDelete = nullptr;
while (p != NULL && p->next != NULL)
{
if (p->next->val == val)
{
toDelete = p->next;
p->next = p->next->next;
delete toDelete;
}
else
p = p->next;
}
return start->next;
}
};
int main()
{
Solution solute;
ListNode* head = new ListNode(0);
vector<int> vec = { 6,6,6,1,2,3,6,4,5,6 };
Init_ListNode(head, vec);
ListNode* p;
int val = 6;
p = solute.removeElements(head, val);
while (p != NULL)
{
cout << p->val << " ";
p = p->next;
}
cout << endl;
return 0;
}
|
#include "connector.hpp"
#include "log.hpp"
#include "utils/assert.hpp"
#include <cppconn/prepared_statement.h>
#include <istream>
#include <sstream>
#include <boost/asio.hpp>
using namespace std;
namespace ba = boost::asio;
namespace nora {
namespace db {
inline string build_procedure_string_(const message *message) {
string ret = "CALL " + message->procedure() + "(";
for (size_t i = 0; i < message->params().size(); ++i) {
if (i != message->params().size() - 1) {
ret += "?,";
} else {
ret += "?";
}
}
ret += ")";
return ret;
}
class data_stream : public iostream {
public:
data_stream() : iostream(&streambuf_) {}
size_t size() {
return streambuf_.size();
}
ba::streambuf streambuf_;
};
inline void fill_params_(sql::PreparedStatement *pstmt, message *message) {
pstmt->clearParameters();
const auto& params = message->params();
for (auto i = 0ul; i < params.size(); ++i) {
auto *str_param = boost::any_cast<string>(¶ms[i]);
if (str_param) {
pstmt->setString(i + 1, *str_param);
continue;
}
auto *u64_param = boost::any_cast<uint64_t>(¶ms[i]);
if (u64_param) {
pstmt->setUInt64(i + 1, *u64_param);
continue;
}
auto *u32_param = boost::any_cast<uint32_t>(¶ms[i]);
if (u32_param) {
pstmt->setUInt(i + 1, *u32_param);
continue;
}
auto *int_param = boost::any_cast<int>(¶ms[i]);
if (int_param) {
pstmt->setInt(i + 1, *int_param);
continue;
}
DB_ELOG << "got invalid procedure parameter type";
ASSERT(0);
}
}
inline void process_select_(sql::PreparedStatement *pstmt, message *message) {
unique_ptr<sql::ResultSet> rs(pstmt->executeQuery());
sql::ResultSetMetaData *meta = rs->getMetaData();
unsigned int col_count = meta->getColumnCount();
while (rs->next()) {
message->results().push_back(vector<boost::any>());
for (unsigned int i = 1; i <= col_count; ++i) {
switch (meta->getColumnType(i)) {
case sql::DataType::CHAR:
case sql::DataType::VARCHAR:
message->results().back().push_back(rs->getString(i).asStdString());
break;
case sql::DataType::INTEGER:
if (meta->isSigned(i)) {
message->results().back().push_back(rs->getInt(i));
} else {
message->results().back().push_back(rs->getUInt(i));
}
break;
case sql::DataType::BIGINT:
if (meta->isSigned(i)) {
message->results().back().push_back(rs->getInt64(i));
} else {
message->results().back().push_back(rs->getUInt64(i));
}
break;
case sql::DataType::VARBINARY:
case sql::DataType::LONGVARBINARY: {
message->results().back().push_back(rs->getString(i).asStdString());
break;
}
default:
ASSERT(0);
}
}
}
// we assume we will never use stored procedures with multi result set
// we still need to drain all the results because stored procedure +
// prepared statement seems to have this problem:
// http://forums.mysql.com/read.php?167,416487,416487
while (pstmt->getMoreResults()) {
rs.reset(pstmt->getResultSet());
}
}
inline void process_update_(sql::PreparedStatement *pstmt, message *msg) {
try {
pstmt->executeUpdate();
} catch (const sql::SQLException& e) {
auto ec = e.getErrorCode();
if (ec == 1062) {
msg->set_update_got_duplicate();
return;
} else {
throw;
}
}
}
connector::connector(const string& ipport,
const string& user,
const string& passwd,
const string& database) :
st_(make_shared<service_thread>("db-connector")),
ipport_(ipport),
user_(user),
passwd_(passwd),
database_(database) {
sql::mysql::MySQL_Driver *driver = sql::mysql::get_driver_instance();
conn_ = unique_ptr<sql::Connection>(driver->connect(ipport_, user_, passwd_));
conn_->setSchema(database_);
}
connector::~connector() {
stop();
}
void connector::start() {
st_->start();
}
void connector::push_message(const shared_ptr<message>& msg, const shared_ptr<service_thread>& st) {
ASSERT(!msg->has_finish_handler() || st);
st_->async_call(
[this, msg, st] {
DB_DLOG << *msg;
while (true) {
try {
shared_ptr<sql::PreparedStatement> pstmt;
if (pstmts_.count(msg->procedure()) > 0) {
pstmt = pstmts_.at(msg->procedure());
fill_params_(pstmt.get(), msg.get());
} else {
string pstmtString = build_procedure_string_(msg.get());
pstmt.reset(conn_->prepareStatement(pstmtString));
pstmts_[msg->procedure()] = pstmt;
fill_params_(pstmt.get(), msg.get());
}
switch (msg->get_req_type()) {
case message::rt_select:
process_select_(pstmt.get(), msg.get());
break;
case message::rt_insert:
case message::rt_update:
case message::rt_delete:
process_update_(pstmt.get(), msg.get());
break;
case message::rt_control:
break;
}
if (pstmt) {
pstmt->clearParameters();
}
} catch (const sql::SQLException& e) {
auto ec = e.getErrorCode();
if (ec == 2013 || ec == 2006) {
this_thread::sleep_for(1ms);
pstmts_.clear();
conn_->reconnect();
conn_->setSchema(database_);
DB_ILOG << "db lost connection, reconnect to mysql";
continue;
} else {
DB_ELOG << *msg << " got exception: " << e.what();
return;
}
}
break;
}
if (st) {
st->async_call(
[msg] {
msg->finish();
});
} else {
msg->finish();
}
});
}
void connector::stop() {
if (stopped_) {
return;
}
stopped_ = true;
st_->stop();
conn_->close();
conn_.reset();
}
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2010 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#include "core/pch.h"
#include "adjunct/quick_toolkit/bindings/ReversibleQuickBinder.h"
ReversibleQuickBinder::ReversibleQuickBinder()
: m_committed(false)
{
}
ReversibleQuickBinder::~ReversibleQuickBinder()
{
if (!m_committed)
{
RevertAll();
}
}
OP_STATUS ReversibleQuickBinder::AddReverter(PrefUtils::IntegerAccessor& accessor)
{
OpAutoPtr<IntegerPrefReverter> reverter(OP_NEW(IntegerPrefReverter, (accessor)));
RETURN_OOM_IF_NULL(reverter.get());
RETURN_IF_ERROR(m_reverters.Add(reverter.get()));
reverter.release();
return OpStatus::OK;
}
OP_STATUS ReversibleQuickBinder::AddReverter(PrefUtils::StringAccessor& accessor)
{
OpAutoPtr<StringPrefReverter> reverter(OP_NEW(StringPrefReverter, (accessor)));
RETURN_OOM_IF_NULL(reverter.get());
RETURN_IF_ERROR(reverter->Init());
RETURN_IF_ERROR(m_reverters.Add(reverter.get()));
reverter.release();
return OpStatus::OK;
}
void ReversibleQuickBinder::Commit()
{
m_committed = true;
}
void ReversibleQuickBinder::RevertAll()
{
for (UINT32 i = 0; i < m_reverters.GetCount(); ++i)
{
m_reverters.Get(i)->Revert();
}
}
|
#include <iostream>
#include <vector>
#include <string.h>
#include "scene.h"
using namespace std;
Scene::Scene()
{
texTotal_ = 0;
}
Scene::Scene(const char * sceneFile)
{
texTotal_ = 0;
loadScene(sceneFile);
}
Scene::~Scene()
{
}
void Scene::loadScene(const char * sceneFile)
{
FILE* data;
char token[100], buf[100];
double v[3];
data = fopen(sceneFile, "r");
if (!data) {
cout << "Can not open Scene File \"" << sceneFile << "\" !" << endl;
return;
}
cout << endl << sceneFile << endl;
while (!feof(data)) {
token[0] = '\0';
fscanf(data, "%s", token);
if (strcmp(token, "model") == 0) {
Model m;
fscanf(data, "%s", buf);
m.objFile_ = buf;
fscanf(data, "%lf%lf%lf", &v[0], &v[1], &v[2]);
m.scale_.set(v);
fscanf(data, "%lf%lf%lf%lf", &m.angle_, &v[0], &v[1], &v[2]);
m.rotate_.set(v);
fscanf(data, "%lf%lf%lf", &v[0], &v[1], &v[2]);
m.translate_.set(v);
cout << m.objFile_ << endl;
m.texIndex_ = texList_.size() - 1; // the index in texList_
modelList_.push_back(m);
}
else if (strcmp(token, "no-texture") == 0) {
Textures t;
t.technique_ = 0;
t.imageTotal_ = 0;
texList_.push_back(t);
}
else if (strcmp(token, "single-texture") == 0) {
Textures t;
t.technique_ = 1;
t.imageTotal_ = 1;
fscanf(data, "%s", buf);
TexImage ti(buf);
t.imageList_.push_back(ti);
texList_.push_back(t);
}
else if (strcmp(token, "multi-texture") == 0) {
Textures t;
t.technique_ = 2;
t.imageTotal_ = 2;
for (size_t i = 0; i < t.imageTotal_; i++) {
fscanf(data, "%s", buf);
TexImage ti(buf);
t.imageList_.push_back(ti);
}
texList_.push_back(t);
}
else if (strcmp(token, "cube-map") == 0) {
Textures t;
t.technique_ = 3;
t.imageTotal_ = 6;
for (size_t i = 0; i < t.imageTotal_; i++) {
fscanf(data, "%s", buf);
TexImage ti(buf);
t.imageList_.push_back(ti);
}
texList_.push_back(t);
}
}
if (data) fclose(data);
texTotal_ = texList_.size();
modelTotal_ = modelList_.size();
printf("total models: %zu\n", modelTotal_);
printf("total textures: %zu\n", texTotal_);
}
Model& Scene::searchModel(const string modelName)
{
for (vector<Model>::iterator it = modelList_.begin(); it != modelList_.end(); it++)
if (it->objFile_ == modelName)
return *it;
cout << "Don't have " << modelName << " in modelList in Scene" << endl;
return Model();
}
|
#include<bits/stdc++.h>
using namespace std;
const double pi=acos(-1.0);
const double eps=1e-8;
int cmp(double x){
if(fabs(x)<eps) return 0;
if(x>0) return 1;
return -1;
}
inline double sqr(double x){
return x*x;
}
struct point{
double x,y;
point(){}
point(double a,double b):x(a),y(b){}
friend point operator + (const point &a,const point &b){
return point(a.x+b.x,a.y+b.y);
}
friend point operator - (const point &a,const point &b){
return point(a.x-b.x,a.y-b.y);
}
friend bool operator == (const point &a,const point &b){
return cmp(a.x-b.x)==0&&cmp(a.y-b.y)==0;
}
friend point operator * (const point &a,const double &b){
return point(a.x*b,a.y*b);
}
friend point operator * (const double &a,const point &b){
return point(a*b.x,a*b.y);
}
friend point operator / (const point &a,const double &b){
return point(a.x/b,a.y/b);
}
double norm(){
return sqrt(sqr(x)+sqr(y));
}
};
//计算向量叉积
double det(const point &a,const point &b){
return a.x*b.y-a.y*b.x;
}
//计算向量点积
double dot(const point &a,const point &b){
return a.x*b.x+a.y*b.y;
}
point res;
struct line{
point a,b;
line(){}
line(point x,point y):a(x),b(y){}
};
bool parallel(line a,line b){
return !cmp(det(a.a-a.b,b.a-b.b));
}
bool line_make_point(line a,line b){
if(parallel(a,b)) return false;
double s1=det(a.a-b.a,b.b-b.a);
double s2=det(a.b-b.a,b.b-b.a);
res=(s1*a.b-s2*a.a)/(s1-s2);
return true;
}
/////////////////////////////////////////////
bool judge(line a,line b){
if(parallel(a,line(a.a,b.a))&¶llel(a,line(a.a,b.b)))
return true;
return false;
}
int main(){
// clock_t start,finish;
// start=clock();
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
int n;
scanf("%d",&n);
printf("INTERSECTING LINES OUTPUT\n");
while(n--){
point a,b,c,d;
scanf("%lf%lf%lf%lf%lf%lf%lf%lf",&a.x,&a.y,&b.x,&b.y,&c.x,&c.y,&d.x,&d.y);
line la=line(a,b);
line lb=line(c,d);
if(parallel(la,lb)){
if(judge(la,lb)){
printf("LINE\n");
}else
printf("NONE\n");
}else{
line_make_point(la,lb);
printf("POINT %.2f %.2f\n",res.x,res.y);
}
}
printf("END OF OUTPUT\n");
// finish=clock();
// cout<<finish-start<<endl;
return 0;
}
|
/*****************************************************************************
* *
* OpenNI 2.x Alpha *
* Copyright (C) 2012 PrimeSense Ltd. *
* *
* This file is part of OpenNI. *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* *
*****************************************************************************/
#ifndef ONIENUMS_H
#define ONIENUMS_H
namespace openni
{
/** Possible failure values */
typedef enum
{
STATUS_OK = 0,
STATUS_ERROR = 1,
STATUS_NOT_IMPLEMENTED = 2,
STATUS_NOT_SUPPORTED = 3,
STATUS_BAD_PARAMETER = 4,
STATUS_OUT_OF_FLOW = 5,
STATUS_NO_DEVICE = 6,
STATUS_NOT_WRITE_PUBLIC_KEY = 7,
STATUS_PUBLIC_KEY_MD5_VERIFY_FAILED = 8,
STATUS_NOT_WRITE_MD5 = 9,
STATUS_RSKEY_VERIFY_FAILED =10,
//New add
STATUS_DEVICE_IS_ALREADY_OPENED = 0x1001, //Device is already opened
STATUS_USB_DRIVER_NOT_FOUND = 0x1002, //USB driver not found,for windows!
STATUS_USB_DEVICE_NOT_FOUND = 0x1003, //USB device not found
STATUS_USB_GET_DRIVER_VERSION = 0x1004, //Failed to get the USB driver version,for windows!
STATUS_USB_GET_SPEED_FAILED = 0x1005, //Failed to get the device speed!
STATUS_USB_SET_INTERFACE_FAILED = 0x1006, //Failed to set USB interface!
STATUS_USB_DEVICE_OPEN_FAILED = 0x1007, //pid,vid,bus id is zero,for linux
STATUS_USB_ENUMERATE_FAILED = 0x1008, //USB enum fail,for linux
STATUS_USB_SET_CONFIG_FAILED = 0x1009, //usb set config fail ,for linux
STATUS_USB_INIT_FAILED = 0x1010, //libusb open fail
STATUS_LIBUSB_ERROR_NO_MEM = 0x1011, //Insufficient memory
STATUS_LIBUSB_ERROR_ACCESS = 0x1012, //Access denied (insufficient permissions)
STATUS_LIBUSB_ERROR_NO_DEVICE = 0x1013, //No such device (it may have been disconnected)
STATUS_LIBUSB_ERROR_IO = 0x1014, //Input/output error
STATUS_LIBUSB_ERROR_NOT_FOUND = 0x1015, //Entity not found
STATUS_LIBUSB_ERROR_BUSY = 0x1016, //Resource busy
STATUS_LIBUSB_ERROR_OTHER = 0x1000, //Other error
//STATUS_STREAM_ALREADY_EXISTS = 25, //stream already exists
//STATUS_UNSUPPORTED_STREAM = 26, // unsupport stream
STATUS_TIME_OUT = 102,
} Status;
/** The source of the stream */
typedef enum
{
SENSOR_IR = 1,
SENSOR_COLOR = 2,
SENSOR_DEPTH = 3,
} SensorType;
/** All available formats of the output of a stream */
typedef enum
{
// Depth
PIXEL_FORMAT_DEPTH_1_MM = 100,
PIXEL_FORMAT_DEPTH_100_UM = 101,
PIXEL_FORMAT_SHIFT_9_2 = 102,
PIXEL_FORMAT_SHIFT_9_3 = 103,
// Color
PIXEL_FORMAT_RGB888 = 200,
PIXEL_FORMAT_YUV422 = 201,
PIXEL_FORMAT_GRAY8 = 202,
PIXEL_FORMAT_GRAY16 = 203,
PIXEL_FORMAT_JPEG = 204,
PIXEL_FORMAT_YUYV = 205,
PIXEL_FORMAT_LOG = 207,
} PixelFormat;
typedef enum
{
DEVICE_STATE_OK = 0,
DEVICE_STATE_ERROR = 1,
DEVICE_STATE_NOT_READY = 2,
DEVICE_STATE_EOF = 3
} DeviceState;
typedef enum
{
IMAGE_REGISTRATION_OFF = 0,
IMAGE_REGISTRATION_DEPTH_TO_COLOR = 1,
} ImageRegistrationMode;
typedef enum
{
PARAMS_REGISTRATION_OFF = 0,
PARAMS_REGISTRATION_DEPTH_TO_COLOR = 1,
PARAMS_REGISTRATION_USE_DISTORTION = 2,
} ParamsRegistrationMode;
static const int TIMEOUT_NONE = 0;
static const int TIMEOUT_FOREVER = -1;
} // namespace openni
#endif // ONIENUMS_H
|
#include "stdafx.h"
#include "CppUnitTest.h"
#include <iostream>
#include <utility> // for pair
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace UnitTestSample
{
TEST_CLASS(UnitTest1)
{
public:
TEST_METHOD(TestMethod1)
{
std::pair<int, int> p1 = std::make_pair(10, 20);
std::pair<int, int> p2(30, 40);
Assert::AreEqual(10, p1.first);
Assert::AreEqual(30, p2.first);
p1.swap(p2);
Assert::AreEqual(30, p1.first);
Assert::AreEqual(10, p2.first);
if (p1 == p2) {
Assert::Fail(L"Fail");
}
else {
Assert::Fail(L"Success");
}
}
};
}
|
#include<iostream>
using namespace std;
int main(){
int marks = 46;
string result = (marks >= 40) ? "Passed" : "Failed"; Code to cheak pass or fail
cout<<result<<endl;
return 0;
}
|
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <bitset>
#include <queue>
#include <algorithm>
#include <functional>
#include <cmath>
using namespace std;
class SpaceWarDiv2 {
struct Enemy {
int strength,count;
};
static
bool compS(const Enemy &lhs,const Enemy &rhs)
{
return lhs.strength > rhs.strength;
}
public:
int minimalFatigue(vector <int> magicalGirlStrength, vector <int> enemyStrength, vector <int> enemyCount)
{
vector<Enemy> e(enemyStrength.size());
for (int i=0; i<enemyStrength.size(); ++i) {
e[i].strength = enemyStrength[i];
e[i].count = enemyCount[i];
}
sort(e.begin(), e.end(), compS);
sort(magicalGirlStrength.begin(), magicalGirlStrength.end(),greater<int>());
if (magicalGirlStrength[0] < e[0].strength) {
return -1;
}
int ans = 0;
bool stillFight = true;
while (stillFight) {
++ans;
for (int i=0; i<magicalGirlStrength.size(); ++i) {
int pos=0;
for (int j=0; j<e.size(); ++j) {
if (magicalGirlStrength[i]>=e[j].strength && e[j].count>0) {
pos = j;
--e[pos].count;
break;
}
}
}
stillFight = false;
for (int i=0; i<e.size(); ++i) {
if (e[i].count>0) {
stillFight = true;
break;
}
}
}
return ans;
}
};
|
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int hours,mins,seconds,x;
cout<<"Enter hours=";
cin>>hours;
cout<<"\nEnter minutes=";
cin>>mins;
cout<<"\nEnter seconds=";
cin>>seconds;
if(hours > 24)
{
cout<<"Invalid Entery";
}
else
{
cout<<"\n24 Hours Format\n";
cout<<"Hours : Mins : Seconds\n"<<" "<<hours<<" : "<<mins<<" : "<<seconds<<"\n";
if(hours > 12)
{
hours=hours-12;
cout<<"12 Hours Format\n";
cout<<"Hours : Mins : Seconds\n"<<" "<<hours<<" : "<<mins<<" : "<<seconds;
}
else
{
cout<<"12 Hours Format\n";
cout<<"Hours : Mins : Seconds\n"<<" "<<hours<<": "<<mins<<" : "<<seconds;
}
}
} // end of main
|
#pragma once
// Здесь представленно описание класса "Участник" и прототипы всех необходимых методов.
#include <string>
class Member
{
public:
Member(); // Конструктор по умолчанию
Member(const char*, const char*); // Параметрический конструктор
~Member(); // Деструктор
private:
char nickname[10]; // Никнейм участника
char memberStatus[10]; // Статус участника
};
|
#include <bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
#define ll long long
#define fi first
#define se second
#define pb push_back
#define ALL(v) v.begin(), v.end()
#define FOR(a, b, c) for (int(a) = (b); (a) < (c); ++(a))
#define FORN(a, b, c) for (int(a) = (b); (a) <= (c); ++(a))
#define FORD(a, b, c) for (int(a) = (b); (a) >= (c); --(a))
#define FOREACH(a, b) for (auto&(a) : (b))
#define REP(i, n) FOR(i, 0, n)
#define REPN(i, n) FORN(i, 1, n)
#define dbg(x) cout << (#x) << " is " << (x) << endl;
#define dbg2(x, y) cout << (#x) << " is " << (x) << " and " << (#y) << " is " << y << endl;
#define dbgarr(x, sz) \
for (int asdf = 0; asdf < (sz); asdf++) cout << x[asdf] << ' '; \
cout << endl;
#define dbgarr2(x, rose, colin) \
for (int asdf2 = 0; asdf2 < rose; asdf2++) { \
dbgarr(x[asdf2], colin); \
}
#define dbgitem(x) \
for (auto asdf = x.begin(); asdf != x.end(); asdf++) cout << *asdf << ' '; \
cout << endl;
const int mod = 1e9 + 7;
int n, m;
vi adj[10000];
unordered_map<string, int> um;
unordered_map<int, int> common[10000];
string names[10000];
struct Solution {
vi solve() {
vi res(n);
REP(i, n) {
int count[10000] = {0};
count[i] = -1;
for (int j : adj[i])
count[j] = -1;
for (int j : adj[i]) {
for (int k : adj[j]) {
if (k != i && count[k] != -1) count[k]++;
}
}
int best = 0;
REP(j, n) {
int c = count[j];
if (c > best) best = c, res[i] = 0;
if (c == best) res[i]++;
}
}
return res;
}
};
void print(vector<int>& nums) {
for (auto num : nums) cout << num << " ";
cout << endl;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> m;
string s, t;
REP(i, m) {
cin >> s >> t;
if (!um.count(s)) um[s] = n++;
if (!um.count(t)) um[t] = n++;
int a = um[s], b = um[t];
names[a] = s, names[b] = t;
adj[a].push_back(b), adj[b].push_back(a);
}
Solution test;
auto res = test.solve();
cout << res.size() << endl;
REP(i, n)
cout << names[i] << " " << res[i] << endl;
}
|
#include <ionir/syntax/ast_printer.h>
#include <ionir/misc/bootstrap.h>
#include "pch.h"
using namespace ionir;
TEST(AstPrinter, GetString) {
Ast ast = Bootstrap::functionAst();
AstPrinter astPrinter = AstPrinter(ast);
std::optional<std::string> astString = astPrinter.make();
if (astString.has_value()) {
std::cout << "Printer result: \n" << *astString << std::endl;
}
else {
std::cout << "Printer has no result." << std::endl;
}
}
|
#include "hashtable.hpp"
#include <iostream>
#include <fstream>
int main()
{
// Even, odd, prime
const std::vector<int> TABLE_SIZES = {100, 101, 99};
std::ofstream output;
output.open("kmt_oa.txt");
// Key mod tablesize and open-addressing
for (const int TABLE_SIZE : TABLE_SIZES)
{
hashtable hash(TABLE_SIZE);
for (int i = 0; i < TABLE_SIZE; i++)
{
output << i + 1 << ' ';
std::cout << "Run #" << i + 1 << "\n" << std::endl;
const int HASH_CODE = hash.key_mod_tablesize();
std::cout << "Hash: " << HASH_CODE << std::endl;
hash.add(HASH_CODE, false);
output << hash.get_load_factor() << ' ' << hash.get_num_collisions() << std::endl;
}
}
output.close();
output.open("kmt_ch.txt");
// Key mod tablesize and chaining
for (const int TABLE_SIZE : TABLE_SIZES)
{
hashtable hash(TABLE_SIZE);
for (int i = 0; i < TABLE_SIZE; i++)
{
output << i + 1 << ' ';
std::cout << "Run #" << i + 1 << "\n" << std::endl;
const int HASH_CODE = hash.key_mod_tablesize();
std::cout << "Hash: " << HASH_CODE << std::endl;
hash.add(HASH_CODE, true);
output << hash.get_load_factor() << ' ' << hash.get_num_collisions() << std::endl;
}
}
output.close();
output.open("mid_sq_oa.txt");
// Mid-square and open-addressing
for (const int TABLE_SIZE : TABLE_SIZES)
{
hashtable hash(TABLE_SIZE);
for (int i = 0; i < TABLE_SIZE; i++)
{
output << i + 1 << ' ';
std::cout << "Run #" << i + 1 << "\n" << std::endl;
const int HASH_CODE = hash.mid_square();
std::cout << "Hash: " << HASH_CODE << std::endl;
hash.add(HASH_CODE, false);
output << hash.get_load_factor() << ' ' << hash.get_num_collisions() << std::endl;
}
}
output.close();
output.open("mid_sq_ch.txt");
// Mid-square and chaining
for (const int TABLE_SIZE : TABLE_SIZES)
{
hashtable hash(TABLE_SIZE);
for (int i = 0; i < TABLE_SIZE; i++)
{
output << i + 1 << ' ';
std::cout << "Run #" << i + 1 << "\n" << std::endl;
const int HASH_CODE = hash.mid_square();
std::cout << "Hash: " << HASH_CODE << std::endl;
hash.add(HASH_CODE, true);
output << hash.get_load_factor() << ' ' << hash.get_num_collisions() << std::endl;
}
}
output.close();
}
|
#ifndef UI_ACTION_ADAPTOR_CONTROLADAPTOR_H_
#define UI_ACTION_ADAPTOR_CONTROLADAPTOR_H_
#pragma once
namespace ui
{
class UILIB_API ControlAdaptor
{
public:
ControlAdaptor(Control* ctrl);
void RunAction(Action* action);
private:
Control* ctrl_;
};
}
#endif
|
#include <iostream>
#include <set>
#include <cstdlib>
#include <string>
#include <time.h>
#include "tensor.h"
#define NUM_TENSORS 40
//we should not have tensorflow namespace here!!
void random_initialization_test(){
//this test creats a number of tensors and initializes them with new allocated buffers, or share buffers with previous tensors
//set total number of tensors to be initialized
int num_random_t = 100;
//tensor index [1..num_random_t]
int t_cnt;
//r=0: allocate new tensor; r=1: use copy constructor for tensor
//r_t: hold a random number in [1..t_cnt]
int r, r_t;
//d=0: do nothing; d=1: deallocate some previous tensor this round
//d_t: hold a random number in [1..t_cnt], for deallocation
int d, d_t;
//contains all references to allocated tensors
//[WARNING] note that when a tensor is deallocated in this set, the reference is not moved out, the tensor pointer may points to an empty space!
std::set<tensorflow::Tensor*> tensorset;
std::set<tensorflow::Tensor*>::iterator tensorset_it;
//if d=1, how many tensors will be deallocated this round
int d_num = 3;
//temporary tensor reference
tensorflow::Tensor* tensor_temp;
//copy constructor tensot reference
tensorflow::Tensor* cp_tensor_temp;
//give a random seed
std::srand (time(NULL));
for(t_cnt=1; t_cnt < num_random_t+1; ++t_cnt){
if (t_cnt>1){
//for the later tensors, we randomly use default (r=0), or copy constructor (r=1).
r = std::rand()%2;//generate a random number in [0,1]
}
else {
//for the first tensor, we must use the default tensor constructor
r = 0;
}
// step 1: allocate/copy a tensor
if (r==0){
//using default tensor constructor
if(std::getenv("DEBUG_FLAG") && atoi(std::getenv("DEBUG_FLAG")) == 0){
std::cout << "[main.cc]: Default tensor constructor is used for tensor, TID = " << t_cnt << ", BID = " << t_cnt << std::endl;
}
tensor_temp = new tensorflow::Tensor(t_cnt);
tensorset.insert(tensor_temp);
}
else {
//using copy tensor constructor
//select a previous tensor index to initialize the new tensor
r_t = std::rand()%tensorset.size()+1;//generate a random number in [1..t_cnt]
if(std::getenv("DEBUG_FLAG") && atoi(std::getenv("DEBUG_FLAG")) == 0){
std::cout << "[main.cc]: Copy tensor constructor is used for tensor, TID = " << t_cnt << ". Seed tensor, TID = "<< r_t << std::endl;
}
for(tensorset_it = tensorset.begin(); tensorset_it != tensorset.end(); ++tensorset_it){
r_t--;
if (r_t==0){
tensor_temp = *tensorset_it;
cp_tensor_temp = new tensorflow::Tensor(t_cnt,tensor_temp);
tensorset.insert(cp_tensor_temp);
break;
}
}
}
//std::cout << "[main.cc]: step1 finished: allocate/copy a tensor" << std::endl;
//the new tensor has been added to tensorset
// step2: decide if we want to deallocate some tensors this iteration
d = std::rand()%2;//generate a random number in [0,1]
if (d==1){
int rnd = 0;
while ( rnd < d_num ){
rnd++;
//deallocate a previous tensor this round
if (tensorset.size()>10) {
//we only deallocate tensor only if there are still 20 tensors alive
d_t = std::rand()%tensorset.size()+1;//generate a random number in [1..t_cnt]
//std::cout << "[main.cc]: before dealloc a tensor: " << tensorset.size() << std::endl;
for(tensorset_it = tensorset.begin(); tensorset_it != tensorset.end(); ++tensorset_it){
d_t--;
if (d_t==0){
tensor_temp = *tensorset_it;
tensorset.erase(tensor_temp);
std::cout << "[main.cc]: deallocate tensor, tid = " << tensor_temp->getid() << std::endl;
delete tensor_temp;
tensor_temp = NULL;
break;
}
}
//std::cout << "[main.cc]: after dealloc a tensor: " << tensorset.size() << std::endl;
}
}
}
//std::cout << "[main.cc]: step2 finished: deallocate a tensor or not: "<< d << std::endl;
// step3: check if the buffer size overflows? Then gc or not
if(tensorflow::Buffer::buf_tracer.get_buffer_set_size()>tensorflow::Buffer::buf_tracer.get_thresh()){
std::cout << "[main.cc]: Start tracing. Current total buffer size (memory) = " << tensorflow::Buffer::buf_tracer.get_buffer_set_size() << std::endl;
//get reference for BufTracer::tracing_set
std::set<tensorflow::Buffer*>* tracing_set_ptr = tensorflow::Buffer::buf_tracer.get_tracing_set();
//start tracing
//put all reacheable object to tracing_set_ptr
tensorflow::Tensor::tensor_tracer.start_tracing(tracing_set_ptr);
//mark garbage and move
tensorflow::Buffer::buf_tracer.mark_mv_garbage_set();
//clean all garbage
tensorflow::Buffer::buf_tracer.free_garbage_set();
std::cout << "[main.cc]: After GC, total buffer size (memory) = " << tensorflow::Buffer::buf_tracer.get_buffer_set_size() << std::endl;
}
std::cout << "[main.cc] total buffer memory = " << tensorflow::Buffer::buf_tracer.get_buffer_set_size() << std::endl;
}
std::cout << "[main.cc] tensor set size (total tensors)="<<tensorset.size() << std::endl;
for(tensorset_it = tensorset.begin(); tensorset_it != tensorset.end(); ++tensorset_it){
tensor_temp = *tensorset_it;
delete tensor_temp;
}
std::cout << "[main.cc]: *cleanup* Current total buffer size (memory) = " << tensorflow::Buffer::buf_tracer.get_buffer_set_size() << std::endl;
//get reference for BufTracer::tracing_set
std::set<tensorflow::Buffer*>* tracing_set_ptr = tensorflow::Buffer::buf_tracer.get_tracing_set();
//start tracing
//put all reacheable object to tracing_set_ptr
tensorflow::Tensor::tensor_tracer.start_tracing(tracing_set_ptr);
//mark garbage and move
tensorflow::Buffer::buf_tracer.mark_mv_garbage_set();
//clean all garbage
tensorflow::Buffer::buf_tracer.free_garbage_set();
std::cout << "[main.cc]: *cleanup* After GC, total buffer size (memory) = " << tensorflow::Buffer::buf_tracer.get_buffer_set_size() << std::endl;
std::cout << "[main.cc] total buffer memory = " << tensorflow::Buffer::buf_tracer.get_buffer_set_size() << std::endl;
}
void linear_initialization_test(){
int tid;
std::set<tensorflow::Tensor*> tensorset;
std::set<tensorflow::Tensor*>::iterator tensorset_it;
tensorflow::Tensor* tensor_temp;
tensorflow::Tensor* cp_tensor_temp;
//allocate NUM_TENSORS tensors linearly
for(tid=0; tid<NUM_TENSORS; tid++){
tensor_temp = new tensorflow::Tensor(tid);
tensorset.insert(tensor_temp);
}
//allocate NUM_TENSORS copy-allocated tensors linearly
tensorset_it = tensorset.begin();
for(tid=0; tid<NUM_TENSORS; tid++){
tensor_temp = *tensorset_it;
cp_tensor_temp = new tensorflow::Tensor(tid+NUM_TENSORS, tensor_temp);
tensorset.insert(cp_tensor_temp);
tensorset_it++;
}
//deallocate the first 10 tensors
//deallocate the first 10 copy-allocated tensors
tid = 1;
for (tensorset_it = tensorset.begin(); tensorset_it != tensorset.end(); ++tensorset_it){
if (tid > 0 && tid < 11){
tensor_temp = *tensorset_it;
delete tensor_temp;
}
if (tid > NUM_TENSORS && tid < NUM_TENSORS + 11){
tensor_temp = *tensorset_it;
delete tensor_temp;
}
tid++;
}
//start tracing here
std::set<tensorflow::Buffer*>* tracing_set_ptr = tensorflow::Buffer::buf_tracer.get_tracing_set();
tensorflow::Tensor::tensor_tracer.start_tracing(tracing_set_ptr);
tensorflow::Buffer::buf_tracer.mark_mv_garbage_set();
tensorflow::Buffer::buf_tracer.free_garbage_set();
}
int main(){
//check debug flag
if(std::getenv("DEBUG_FLAG") != NULL){
std::cout << "debug-"<< atoi(std::getenv("DEBUG_FLAG")) <<" enabled" << std::endl;
}
else{
std::cout << "debug disabled, please set DEBUG_FLAG" << std::endl;
std::cout << "$ export DEBUG_FLAG = <DEBUG_LVL>" << std::endl;
exit(0);
}
//use linear initialization here
//std::cout << "===start linear initialization ===" << std::endl;
//linear_initialization_test();
//std::cout << "===end linear initialization ===" << std::endl;
//use random initiatization here
std::cout << "===start random initialization ===" << std::endl;
random_initialization_test();
std::cout << "===end random initialization ===" << std::endl;
return 0;
}
|
#include "../headers/Transaction.h"
Transaction::Transaction(string from, string to, double amount) : from(from), to(to), amount(amount) {
timeT = time(nullptr);
}
|
// Created on: 1995-12-01
// Created by: EXPRESS->CDL V0.2 Translator
// 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 _StepBasic_SiUnitAndLengthUnit_HeaderFile
#define _StepBasic_SiUnitAndLengthUnit_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <StepBasic_SiUnit.hxx>
#include <StepBasic_SiPrefix.hxx>
#include <StepBasic_SiUnitName.hxx>
class StepBasic_LengthUnit;
class StepBasic_SiUnitAndLengthUnit;
DEFINE_STANDARD_HANDLE(StepBasic_SiUnitAndLengthUnit, StepBasic_SiUnit)
class StepBasic_SiUnitAndLengthUnit : public StepBasic_SiUnit
{
public:
//! Returns a SiUnitAndLengthUnit
Standard_EXPORT StepBasic_SiUnitAndLengthUnit();
Standard_EXPORT void Init (const Standard_Boolean hasAprefix, const StepBasic_SiPrefix aPrefix, const StepBasic_SiUnitName aName);
Standard_EXPORT void SetLengthUnit (const Handle(StepBasic_LengthUnit)& aLengthUnit);
Standard_EXPORT Handle(StepBasic_LengthUnit) LengthUnit() const;
DEFINE_STANDARD_RTTIEXT(StepBasic_SiUnitAndLengthUnit,StepBasic_SiUnit)
protected:
private:
Handle(StepBasic_LengthUnit) lengthUnit;
};
#endif // _StepBasic_SiUnitAndLengthUnit_HeaderFile
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2006 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_CSS_TRANSFORM_VALUE_H
#define DOM_CSS_TRANSFORM_VALUE_H
#ifdef CSS_TRANSFORMS
class DOM_CSSStyleDeclaration;
#include "modules/display/vis_dev_transform.h"
class DOM_CSSMatrix : public DOM_Object
{
public:
~DOM_CSSMatrix() {}
static OP_STATUS Make(DOM_CSSMatrix*& matrix, const AffineTransform &t, DOM_CSSStyleDeclaration *s);
virtual void GCTrace();
virtual BOOL IsA(int type) { return type == DOM_TYPE_CSS_MATRIX || DOM_Object::IsA(type); }
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);
DOM_DECLARE_FUNCTION(setMatrixValue);
DOM_DECLARE_FUNCTION(multiply);
DOM_DECLARE_FUNCTION(inverse);
DOM_DECLARE_FUNCTION(translate);
DOM_DECLARE_FUNCTION(scale);
DOM_DECLARE_FUNCTION(rotate);
enum { FUNCTIONS_ARRAY_SIZE = 7 };
private:
DOM_CSSMatrix(const AffineTransform &t, DOM_CSSStyleDeclaration *s) : transform(t), style_declaration(s) {}
AffineTransform transform;
DOM_CSSStyleDeclaration *style_declaration;
};
#endif // !CSS_TRANSFORMS
#endif // !DOM_CSS_TRANSFORM_VALUE_H
|
#include <iostream>
using namespace std;
int Stock(int s)
{
int res = s-1;
int i=2;
while (res>=i)
res-=i++;
return (i-3)*(i-2)/2+res+1;
}
int main()
{
int n;
while (cin>>n)
cout<<Stock(n)<<endl;
return 0;
}
|
#include <bits/stdc++.h>
#define INF 1<<30
using namespace std;
char MA[505][505];
int custo[505][505];
struct POS
{
int ii, jj, w;
POS(int a, int b, int c)
{
ii = a; jj = b; w = c;
}
};
struct comp
{
bool operator()(POS a, POS b)
{
return a.w>b.w;
}
};
int dijkstra(pair<int,int>ori, pair<int,int>des);
int main()
{
int n, m, ret;
pair<int,int>ori, des;
scanf("%d %d", &n, &m); getchar();
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
scanf("%c", &MA[i][j]); custo[i][j]=INF;
if(MA[i][j]=='H')
{
ori = pair<int,int>(i, j); MA[i][j]='0';
}
else if(MA[i][j]=='E')
{
des = pair<int,int>(i, j); MA[i][j]='0';
}
else if(MA[i][j]=='.')
MA[i][j]='0';
}
getchar();
}
ret = dijkstra(ori, des);
if(ret==-1)
printf("ARTSKJID\n");
else
printf("%d\n", ret);
return 0;
}
int dijkstra(pair<int,int>ori, pair<int,int>des)
{
priority_queue<POS, vector<POS>, comp>fila;
int i, j, ww;
custo[ori.first][ori.second]=0;
fila.push(POS(ori.first, ori.second, 0));
while(!fila.empty())
{
i = fila.top().ii; j = fila.top().jj; ww = fila.top().w; fila.pop();
if(custo[i][j]==ww)
{
if(MA[i+1][j]>='0' && MA[i+1][j]<='9' && custo[i+1][j]>(ww+MA[i+1][j]-'0'))
{
custo[i+1][j] = custo[i][j]+MA[i+1][j]-'0';
fila.push(POS(i+1, j, custo[i+1][j]));
}
if(MA[i-1][j]>='0' && MA[i-1][j]<='9' && custo[i-1][j]>(ww+MA[i-1][j]-'0'))
{
custo[i-1][j] = ww+MA[i-1][j]-'0';
fila.push(POS(i-1, j, custo[i-1][j]));
}
if(MA[i][j+1]>='0' && MA[i][j+1]<='9' && custo[i][j+1]>(ww+MA[i][j+1]-'0'))
{
custo[i][j+1] = ww+MA[i][j+1]-'0';
fila.push(POS(i, j+1, custo[i][j+1]));
}
if(MA[i][j-1]>='0' && MA[i][j-1]<='9' && custo[i][j-1]>(ww+MA[i][j-1]-'0'))
{
custo[i][j-1] = ww+MA[i][j-1]-'0';
fila.push(POS(i, j-1, custo[i][j-1]));
}
}
}
if(custo[des.first][des.second]==INF)
return -1;
else
return custo[des.first][des.second];
}
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <functional>
#include <queue>
#include <string>
#include <cstring>
#include <numeric>
#include <cstdlib>
#include <cmath>
using namespace std;
typedef long long ll;
#define INF 10e17 // 4倍しても(4回足しても)long longを溢れない
#define rep(i,n) for(int i=0; i<n; i++)
#define rep_r(i,n,m) for(int i=m; i<n; i++)
#define END cout << endl
#define MOD 1000000007
#define pb push_back
#define sorti(x) sort(x.begin(), x.end())
#define sortd(x) sort(x.begin(), x.end(), std::greater<int>())
#define debug(x) std::cerr << (x) << std::endl;
#define roll(x) for (auto itr : x) { debug(itr); }
template <class T> inline void chmax(T &ans, T t) { if (t > ans) ans = t;}
template <class T> inline void chmin(T &ans, T t) { if (t < ans) ans = t;}
template<class T>
class UnionFind {
using _Tp = T;
using size_type = std::size_t;
public:
vector<int> par;
vector<int> rank;
vector<_Tp> diff_weight;
UnionFind(int n = 1, _Tp SUM_UNITY = 0) {
init(n, SUM_UNITY);
}
const _Tp & operator[] (size_type i) {
root(i);
return diff_weight[i];
}
void init(int n = 1, _Tp SUM_UNITY = 0) {
par.resize(n); rank.resize(n); diff_weight.resize(n);
for (int i = 0; i < n; ++i) par[i] = i, rank[i] = 0, diff_weight[i] = SUM_UNITY;
}
int root(int x) {
if (par[x] == x) {
return x;
}
else {
int r = root(par[x]);
diff_weight[x] += diff_weight[par[x]];
return par[x] = r;
}
}
_Tp weight(int x) {
root(x);
return diff_weight[x];
}
bool issame(int x, int y) {
return root(x) == root(y);
}
bool merge(int x, int y, _Tp w) {
w += weight(x); w -= weight(y);
x = root(x); y = root(y);
if (x == y) return false;
if (rank[x] < rank[y]) swap(x, y), w = -w;
if (rank[x] == rank[y]) ++rank[x];
par[y] = x;
diff_weight[y] = w;
return true;
}
_Tp diff(int x, int y) {
return weight(y) - weight(x);
}
};
int main() {
int n,q;
cin >> n >> q;
UnionFind<int> uf(n+1);
rep(i, q) {
int j;
cin >> j;
int x,y,z;
if (j) {
cin >> x >> y;
if (uf.issame(x,y)) {
cout << uf[y] - uf[x] << endl;
} else {
cout << "?" << endl;
}
} else {
cin >> x >> y >> z;
uf.merge(x,y,z);
}
}
}
|
//知识点 :图论
/*
By:Luckyblock
分析题意:
题意中指出: 路径上的所有点的出边 ,
所指向的点都直接或间接与终点联通
所以要将不直接或间接与终点联通的点 ,
即不合法点都在图中删除.
直接寻找与终点不直接间接联通的点 比较麻烦
但是可以进行转换,
先寻找 直接间接与终点相连的点.
算法实现:
要寻找直接间接与终点相连的点,
可以通过从终点反向BFS来实现.
先将 与终点直接连通的点加入队列,
之后 再将与队列中的点相连接的点 加入队列
给队列中的点打标记,表明暂时合法.
在暂时合法的 点中,还存在一些 与不合法的点直接相连的点
它们也是不合法的
所以还要枚举不合法的点, 即没有被打上暂时合法标记的点
将与他们直接相连的点的暂时合法标记去除.
最后对于仍然存在标记的点,
在它们中跑一遍 最短路即可.
*/
#include<cstdio>
#include<queue>
#include<ctype.h>
#define int long long
const int INF = 2e9+7;
const int MARX = 1e4+10;
//=============================================================
struct edge
{
int u,v,ne;
}e[MARX<<5];
int n,m,st,to , head[MARX],dis[MARX];//存图
bool vis[MARX],ju[MARX];//标记合法点
//=============================================================
inline int read()
{
int s=1, w=0; char ch=getchar();
for(; !isdigit(ch);ch=getchar()) if(ch=='-') s =-1;
for(; isdigit(ch);ch=getchar()) w = w*10+ch-'0';
return s*w;
}
void bfs()//bfs求得合法点
{
std::queue <int> qu; qu.push(to);
while(!qu.empty())//以终点为起点 , 进行反向bfs
{
int top=qu.front();
qu.pop();
for(int i=head[top]; i; i=e[i].ne)//枚举出边
if(!ju[e[i].v])
{
ju[e[i].v]=1;//打上暂时合法标记
qu.push(e[i].v);
}
}
ju[to]=1;//出点合法
bool jud[MARX]={0};
for(int i=1; i<=n; i++)
if(!ju[i])//剔除 与不合法的点相邻的暂时合法点
for(int j=head[i]; j; j=e[j].ne)
jud[e[j].v]=1;//打不合法标记
for(int i=1; i<=n; i++)//去除合法标记
ju[i]=( jud[i]?0:ju[i] );
}
void spfa()//最短路模板
{
for(int i=1; i<=n; i++) dis[i]=INF * ju[i];//初始化
std::queue <int> qu; qu.push(to);
dis[to]=0 , vis[to]=1;
while(!qu.empty())//spfa
{
int u=qu.front();
qu.pop();
vis[u]=0;
for(int i=head[u]; i; i=e[i].ne)
if(ju[e[i].v] && dis[u]+1<dis[e[i].v])
{
dis[e[i].v]=dis[u]+1;
if(!vis[e[i].v]) qu.push(e[i].v);
vis[e[i].v]=1;
}
}
}
//=============================================================
signed main()
{
n=read(),m=read();
for(int i=1;i<=m;i++)//建图
{
int u=read(),v=read();
e[i].u=v , e[i].v=u;
e[i].ne=head[e[i].u],head[e[i].u]=i;
}
st=read(),to=read();
bfs();
if(ju[st])//起点合法
{
spfa();
printf("%lld",dis[st]==INF?-1:dis[st]);
return 0;
}
printf("-1");
}
|
#include "common.hpp"
namespace po=boost::program_options;
void add_eod_option(boost::program_options::options_description& desc, std::string* eodmarker) {
desc.add_options()
("eodmarker",po::value<std::string>(eodmarker)->value_name("<string>")->default_value("eeeoddd"),"end of document marker");
}
void add_context_options(po::options_description& desc, std::string* ssmarker, std::string* esmarker) {
desc.add_options()
("ssmarker", po::value<std::string>(ssmarker)->value_name("<string>")->default_value("<s>"),"start of sentence fill token")
("esmarker", po::value<std::string>(esmarker)->value_name("<string>")->default_value("</s>"), "end sentence fill token")
;
}
void add_indexing_options(po::options_description& desc, std::string* oovtoken, std::string* digit_rep) {
desc.add_options()
("oovtoken", po::value<std::string>(oovtoken)->value_name("<string>")->default_value("UUUNKKK"), "OOV token")
("digify", po::value<std::string>(digit_rep)->value_name("<string>")->implicit_value("DG"), "digify OOV numbers by replacing all digits with the given string")
;
}
static std::regex numregex("[-+]?\\d*\\.?\\d+", std::regex::ECMAScript | std::regex::optimize);
static std::regex digitregex("\\d", std::regex::ECMAScript | std::regex::optimize);
int read_index(const std::string& index, int vocabsize) {
int result=std::stoi(index);
if(result<0 || result>=vocabsize) {
throw std::out_of_range("Out of vocab range");
}
return result;
}
int lookup_word(const boost::unordered_map<std::string, int>& vocabmap, const std::string& word, bool preindexed, int oovind, boost::optional<const std::string&> digit_rep) {
if(preindexed) {
return read_index(word, vocabmap.size());
} else {
boost::unordered_map<std::string,int>::const_iterator index = vocabmap.find(word);
if(index != vocabmap.end()) {
return index->second;
}
if(digit_rep.is_initialized()) {
if(std::regex_match(word,numregex)) {
std::string digified = std::regex_replace(word, digitregex, *digit_rep);
index=vocabmap.find(digified);
if(index !=vocabmap.end()){
return index->second;
}
}
}
return oovind;
}
}
void compute_context(const boost::circular_buffer<int>& context, const std::vector<float>& idfs, const arma::fmat& origvects, arma::fvec& outvec, unsigned int vecdim, unsigned int contextsize) {
float idfc[2*contextsize+1]; //idf context window
//Look up the idfs of the words in context
std::transform(context.begin(),context.end(),idfc,[&idfs](int c) ->float {return idfs[c];});
float idfsum=std::accumulate(idfc,&idfc[contextsize],0.0f)+std::accumulate(&idfc[contextsize+1],&idfc[2*contextsize+1],0.0f);
if(idfsum==0) {
return;
}
float invidfsum=1/idfsum;
for(unsigned int i=0; i<contextsize; i++) {
float idfterm=idfc[i]*invidfsum;
std::transform(outvec.begin(), outvec.end(),origvects.unsafe_col(context[i]).begin(), outvec.begin(), [idfterm](float f1, float f2) -> float { return f1+f2*idfterm; });
}
for(unsigned int i=contextsize+1; i<2*contextsize+1; i++) {
float idfterm=idfc[i]*invidfsum;
std::transform(outvec.begin(), outvec.end(),origvects.unsafe_col(context[i]).begin(), outvec.begin(), [idfterm](float f1, float f2) -> float { return f1+f2*idfterm; });
}
}
|
// Copyright (c) 2013 Nick Porcino, All rights reserved.
// License is MIT: http://opensource.org/licenses/MIT
#include "LandruCompiler/Tokens.h"
namespace Landru
{
#ifdef TOKEN_DECL
# undef TOKEN_DECL
#endif
#define TOKEN_DECL(a, b) case kToken##a: return b;
char const* tokenName(TokenId t)
{
switch (t)
{
#include "LandruCompiler/TokenDefs.h"
}
return "";
}
#undef TOKEN_DECL
}
|
#define max_msgs 16
dimension2d<s32> charSize = dimension2d<s32>(16, 15);
SColor chatBG = SColor(128,0,0,0);
int lineHeight = -18, letterSpacing = -3;
#define chatPos position2d<s32>(32,SS.Height-64);
ITexture* font;
std::string chat[max_msgs];
clock_t lastChat = clock();
void writeChat(std::string msg) {
range(i, 0, max_msgs-1) chat[i]=chat[i+1];
chat[max_msgs-1]=msg;
lastChat = clock();
}
void drawText(std::string text, position2d<s32> at) {
position2d<s32> c = at;
driver->draw2DRectangle(chatBG, rect<s32>(c, dimension2d<s32>((charSize.Width+letterSpacing)*text.length(),charSize.Height)));
range(i,0,text.length()) {
int ch = text.at(i);
driver->draw2DImage(font, c, rect<s32>(dimension2d<s32>((ch&15)*charSize.
Width,charSize.Height*(ch/16)),charSize), NULL, GREY(255), true);
c.X += charSize.Width + letterSpacing;
}
}
void drawChat() {
if (((float)(clock()-lastChat))/CLOCKS_PER_SEC>3) return;
position2d<s32> c = chatPos;
for (int i = max_msgs-1; i > -1; i--) {
drawText(chat[i], c);
c.Y += lineHeight;
}
}
|
#include <iostream>
#include <fstream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <map>
#include <vector>
#include <algorithm>
#include <math.h>
#define pb push_back
using namespace std;
int bd, kt, ck;
void input() {
scanf("%d %d", &bd, &kt);
}
int tinhChuky(int n) {
int demCk = 1;
while (n > 1) {
if (n%2 == 0) {
demCk++;
n = n/2;
} else {
demCk++;
n = 3*n + 1;
}
}
return demCk;
}
void solve() {
ck = 0;
for (int i = bd; i <= kt; i++ ) {
int temp = tinhChuky(i);
if (temp > ck)
ck = temp;
}
}
void output() {
printf("%d %d %d\n", bd, kt, ck);
}
int main()
{
int ntest;
freopen("trunghoc8.inp", "r", stdin);
scanf("%d", &ntest);
for (int itest = 0; itest < ntest; itest++) {
input();
solve();
output();
}
return 0;
}
|
#ifndef BOOKWRITER_H
#define BOOKWRITER_H
#include "book.h"
#include <QMetaObject>
#include <QMetaProperty>
class BookWriter
{
public:
BookWriter();
BookWriter(QString fn);
bool saveBook(QObject &b);
private:
QString fileName;
};
#endif // BOOKWRITER_H
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <fmt/format.h>
#include <folly/chrono/Conv.h>
#include <folly/io/Cursor.h>
#include <folly/io/SocketOptionMap.h>
#include <folly/system/ThreadId.h>
#include <quic/QuicConstants.h>
#include <quic/common/SocketUtil.h>
#include <quic/common/Timers.h>
#include <atomic>
#ifdef FOLLY_HAVE_MSG_ERRQUEUE
#include <linux/net_tstamp.h>
#else
#define SOF_TIMESTAMPING_SOFTWARE 0
#endif
#include <folly/Conv.h>
#include <quic/congestion_control/Bbr.h>
#include <quic/congestion_control/Copa.h>
#include <quic/fizz/handshake/FizzRetryIntegrityTagGenerator.h>
#include <quic/server/AcceptObserver.h>
#include <quic/server/QuicServerWorker.h>
#include <quic/server/handshake/StatelessResetGenerator.h>
#include <quic/server/handshake/TokenGenerator.h>
#include <quic/server/third-party/siphash.h>
#include <quic/state/QuicConnectionStats.h>
// This hook is invoked by mvfst for every UDP socket it creates.
#if FOLLY_HAVE_WEAK_SYMBOLS
extern "C" FOLLY_ATTR_WEAK void mvfst_hook_on_socket_create(int fd);
#else
static void (*mvfst_hook_on_socket_create)(int fd) = nullptr;
#endif
namespace {
bool isValidConnIdLength(const quic::ConnectionId& connId) {
return quic::kMinInitialDestinationConnIdLength <= connId.size() &&
connId.size() <= quic::kMaxConnectionIdSize;
}
} // namespace
namespace quic {
std::atomic_int globalUnfinishedHandshakes{0};
QuicServerWorker::QuicServerWorker(
std::shared_ptr<QuicServerWorker::WorkerCallback> callback,
SetEventCallback ec)
: callback_(std::move(callback)),
setEventCallback_(ec),
takeoverPktHandler_(this),
observerList_(this) {
pending0RttData_.setPruneHook(
[&](auto, auto) { QUIC_STATS(statsCallback_, onZeroRttBufferedPruned); });
}
folly::EventBase* QuicServerWorker::getEventBase() const {
return evb_.get();
}
void QuicServerWorker::setSocket(
std::unique_ptr<QuicAsyncUDPSocketType> socket) {
socket_ = std::move(socket);
evb_ = folly::Executor::KeepAlive(socket_->getEventBase());
}
void QuicServerWorker::bind(
const folly::SocketAddress& address,
QuicAsyncUDPSocketType::BindOptions bindOptions) {
DCHECK(!supportedVersions_.empty());
CHECK(socket_);
switch (setEventCallback_) {
case SetEventCallback::NONE:
break;
case SetEventCallback::RECVMSG:
socket_->setEventCallback(this);
break;
case SetEventCallback::RECVMSG_MULTISHOT:
socket_->setRecvmsgMultishotCallback(this);
break;
};
// TODO this totally doesn't work, we can't apply socket options before
// bind, since bind creates the fd.
if (socketOptions_) {
applySocketOptions(
*socket_,
*socketOptions_,
address.getFamily(),
folly::SocketOptionKey::ApplyPos::PRE_BIND);
}
socket_->bind(address, bindOptions);
if (socketOptions_) {
applySocketOptions(
*socket_,
*socketOptions_,
address.getFamily(),
folly::SocketOptionKey::ApplyPos::POST_BIND);
}
socket_->setDFAndTurnOffPMTU();
if (transportSettings_.numGROBuffers_ > kDefaultNumGROBuffers) {
socket_->setGRO(true);
if (socket_->getGRO() > 0) {
numGROBuffers_ = std::min(
transportSettings_.numGROBuffers_, (uint32_t)kMaxNumGROBuffers);
}
}
socket_->setTimestamping(SOF_TIMESTAMPING_SOFTWARE);
socket_->setTXTime({CLOCK_MONOTONIC, /*deadline=*/false});
if (mvfst_hook_on_socket_create) {
mvfst_hook_on_socket_create(getSocketFd(*socket_));
}
}
void QuicServerWorker::applyAllSocketOptions() {
CHECK(socket_);
if (socketOptions_) {
applySocketOptions(
*socket_,
*socketOptions_,
getAddress().getFamily(),
folly::SocketOptionKey::ApplyPos::PRE_BIND);
applySocketOptions(
*socket_,
*socketOptions_,
getAddress().getFamily(),
folly::SocketOptionKey::ApplyPos::POST_BIND);
}
}
void QuicServerWorker::setTransportSettingsOverrideFn(
TransportSettingsOverrideFn fn) {
transportSettingsOverrideFn_ = std::move(fn);
}
void QuicServerWorker::setTransportStatsCallback(
std::unique_ptr<QuicTransportStatsCallback> statsCallback) noexcept {
CHECK(statsCallback);
statsCallback_ = std::move(statsCallback);
}
QuicTransportStatsCallback* QuicServerWorker::getTransportStatsCallback()
const noexcept {
return statsCallback_.get();
}
void QuicServerWorker::setConnectionIdAlgo(
std::unique_ptr<ConnectionIdAlgo> connIdAlgo) noexcept {
CHECK(connIdAlgo);
connIdAlgo_ = std::move(connIdAlgo);
}
void QuicServerWorker::setCongestionControllerFactory(
std::shared_ptr<CongestionControllerFactory> ccFactory) {
CHECK(ccFactory);
ccFactory_ = ccFactory;
}
void QuicServerWorker::setRateLimiter(
std::unique_ptr<RateLimiter> rateLimiter) {
newConnRateLimiter_ = std::move(rateLimiter);
}
void QuicServerWorker::setUnfinishedHandshakeLimit(
std::function<int()> limitFn) {
unfinishedHandshakeLimitFn_ = std::move(limitFn);
}
void QuicServerWorker::start() {
CHECK(socket_);
if (!pacingTimer_) {
pacingTimer_ = TimerHighRes::newTimer(
evb_.get(), transportSettings_.pacingTimerResolution);
}
socket_->resumeRead(this);
VLOG(10) << fmt::format(
"Registered read on worker={}, thread={}, processId={}",
fmt::ptr(this),
folly::getCurrentThreadID(),
(int)processId_);
}
void QuicServerWorker::timeoutExpired() noexcept {
logTimeBasedStats();
}
void QuicServerWorker::logTimeBasedStats() {
for (auto [transport, handle] : boundServerTransports_) {
if (!handle.expired()) {
transport->logTimeBasedStats();
}
}
evb_->timer().scheduleTimeout(this, timeLoggingSamplingInterval_);
}
void QuicServerWorker::pauseRead() {
CHECK(socket_);
socket_->pauseRead();
}
int QuicServerWorker::getFD() {
CHECK(socket_);
return getSocketFd(*socket_);
}
const folly::SocketAddress& QuicServerWorker::getAddress() const {
CHECK(socket_);
return socket_->address();
}
void QuicServerWorker::getReadBuffer(void** buf, size_t* len) noexcept {
auto readBufferSize = transportSettings_.maxRecvPacketSize * numGROBuffers_;
readBuffer_ = folly::IOBuf::createCombined(readBufferSize);
*buf = readBuffer_->writableData();
*len = readBufferSize;
}
// Returns true if we either drop the packet or send a version
// negotiation packet to the client. Returns false if there's
// no need for version negotiation.
bool QuicServerWorker::maybeSendVersionNegotiationPacketOrDrop(
const folly::SocketAddress& client,
bool isInitial,
LongHeaderInvariant& invariant,
size_t datagramLen) {
folly::Optional<std::pair<VersionNegotiationPacket, Buf>>
versionNegotiationPacket;
if (isInitial && datagramLen < kMinInitialPacketSize) {
VLOG(3) << "Dropping initial packet due to invalid size";
QUIC_STATS(
statsCallback_, onPacketDropped, PacketDropReason::INVALID_PACKET_SIZE);
return true;
}
isInitial =
isInitial && invariant.version != QuicVersion::VERSION_NEGOTIATION;
if (rejectNewConnections_() && isInitial) {
VersionNegotiationPacketBuilder builder(
invariant.dstConnId,
invariant.srcConnId,
std::vector<QuicVersion>{QuicVersion::MVFST_INVALID});
versionNegotiationPacket.emplace(std::move(builder).buildPacket());
}
if (!versionNegotiationPacket) {
bool negotiationNeeded = std::find(
supportedVersions_.begin(),
supportedVersions_.end(),
invariant.version) == supportedVersions_.end();
if (negotiationNeeded && !isInitial) {
VLOG(3) << "Dropping non-initial packet due to invalid version";
QUIC_STATS(
statsCallback_,
onPacketDropped,
PacketDropReason::INVALID_PACKET_VERSION);
return true;
}
if (negotiationNeeded) {
VersionNegotiationPacketBuilder builder(
invariant.dstConnId, invariant.srcConnId, supportedVersions_);
versionNegotiationPacket =
folly::make_optional(std::move(builder).buildPacket());
}
}
if (versionNegotiationPacket) {
VLOG(4) << "Version negotiation sent to client=" << client;
auto len = versionNegotiationPacket->second->computeChainDataLength();
QUIC_STATS(statsCallback_, onWrite, len);
QUIC_STATS(statsCallback_, onPacketProcessed);
QUIC_STATS(statsCallback_, onPacketSent);
socket_->write(client, versionNegotiationPacket->second);
return true;
}
return false;
}
void QuicServerWorker::sendVersionNegotiationPacket(
const folly::SocketAddress& client,
LongHeaderInvariant& invariant) {
VersionNegotiationPacketBuilder builder(
invariant.dstConnId, invariant.srcConnId, supportedVersions_);
auto versionNegotiationPacket = std::move(builder).buildPacket();
VLOG(4) << "Version negotiation sent to client=" << client;
auto len = versionNegotiationPacket.second->computeChainDataLength();
QUIC_STATS(statsCallback_, onWrite, len);
QUIC_STATS(statsCallback_, onPacketProcessed);
QUIC_STATS(statsCallback_, onPacketSent);
socket_->write(client, versionNegotiationPacket.second);
}
void QuicServerWorker::onDataAvailable(
const folly::SocketAddress& client,
size_t len,
bool truncated,
OnDataAvailableParams params) noexcept {
auto packetReceiveTime = Clock::now();
auto originalPacketReceiveTime = packetReceiveTime;
if (params.ts) {
// This is the software system time from the datagram.
auto packetNowDuration =
folly::to<std::chrono::microseconds>(params.ts.value()[0]);
auto wallNowDuration =
std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::system_clock::now().time_since_epoch());
auto durationSincePacketNow = wallNowDuration - packetNowDuration;
if (packetNowDuration != 0us && durationSincePacketNow > 0us) {
packetReceiveTime -= durationSincePacketNow;
}
}
// System time can move backwards, so we want to make sure that the receive
// time we are using is monotonic relative to itself.
if (packetReceiveTime < largestPacketReceiveTime_) {
packetReceiveTime = originalPacketReceiveTime;
}
largestPacketReceiveTime_ =
std::max(largestPacketReceiveTime_, packetReceiveTime);
VLOG(10) << fmt::format(
"Worker={}, Received data on thread={}, processId={}",
fmt::ptr(this),
folly::getCurrentThreadID(),
(int)processId_);
// Move readBuffer_ first so that we can get rid
// of it immediately so that if we return early,
// we've flushed it.
Buf data = std::move(readBuffer_);
if (params.gro <= 0) {
if (truncated) {
// This is an error, drop the packet.
return;
}
data->append(len);
QUIC_STATS(statsCallback_, onPacketReceived);
QUIC_STATS(statsCallback_, onRead, len);
handleNetworkData(client, std::move(data), packetReceiveTime);
} else {
// if we receive a truncated packet
// we still need to consider the prev valid ones
// AsyncUDPSocket::handleRead() sets the len to be the
// buffer size in case the data is truncated
if (truncated) {
len -= len % params.gro;
}
data->append(len);
QUIC_STATS(statsCallback_, onPacketReceived);
QUIC_STATS(statsCallback_, onRead, len);
size_t remaining = len;
size_t offset = 0;
while (remaining) {
if (static_cast<int>(remaining) <= params.gro) {
// do not clone the last packet
// start at offset, use all the remaining data
data->trimStart(offset);
DCHECK_EQ(data->length(), remaining);
handleNetworkData(client, std::move(data), packetReceiveTime);
break;
}
auto tmp = data->cloneOne();
// start at offset
tmp->trimStart(offset);
// the actual len is len - offset now
// leave params.gro_ bytes
tmp->trimEnd(len - offset - params.gro);
DCHECK_EQ(tmp->length(), params.gro);
offset += params.gro;
remaining -= params.gro;
handleNetworkData(client, std::move(tmp), packetReceiveTime);
}
}
}
void QuicServerWorker::handleNetworkData(
const folly::SocketAddress& client,
Buf data,
const TimePoint& packetReceiveTime,
bool isForwardedData) noexcept {
// if packet drop reason is set, invoke stats cb accordingly
auto packetDropReason = PacketDropReason::NONE;
auto maybeReportPacketDrop = folly::makeGuard([&]() {
if (packetDropReason != PacketDropReason::NONE) {
QUIC_STATS(statsCallback_, onPacketDropped, packetDropReason);
}
});
try {
// check error conditions for packet drop & early return
folly::io::Cursor cursor(data.get());
if (shutdown_) {
VLOG(4) << "Packet received after shutdown, dropping";
packetDropReason = PacketDropReason::SERVER_SHUTDOWN;
} else if (isBlockListedSrcPort_(client.getPort())) {
VLOG(4) << "Dropping packet with blocklisted src port: "
<< client.getPort();
packetDropReason = PacketDropReason::INVALID_SRC_PORT;
} else if (!callback_) {
VLOG(0) << "Worker callback is null. Dropping packet.";
packetDropReason = PacketDropReason::WORKER_NOT_INITIALIZED;
} else if (!cursor.canAdvance(sizeof(uint8_t))) {
VLOG(4) << "Dropping packet too small";
packetDropReason = PacketDropReason::INVALID_PACKET_INITIAL_BYTE;
}
// terminate early
if (packetDropReason != PacketDropReason::NONE) {
return;
}
uint8_t initialByte = cursor.readBE<uint8_t>();
HeaderForm headerForm = getHeaderForm(initialByte);
if (headerForm == HeaderForm::Short) {
if (auto maybeParsedShortHeader =
parseShortHeaderInvariants(initialByte, cursor)) {
RoutingData routingData(
headerForm,
false, /* isInitial */
false, /* is0Rtt */
std::move(maybeParsedShortHeader->destinationConnId),
folly::none);
return forwardNetworkData(
client,
std::move(routingData),
NetworkData(std::move(data), packetReceiveTime),
folly::none, /* quicVersion */
isForwardedData);
}
} else if (
auto maybeParsedLongHeader =
parseLongHeaderInvariant(initialByte, cursor)) {
// TODO: check version before looking at type
LongHeader::Types longHeaderType = parseLongHeaderType(initialByte);
bool isInitial = longHeaderType == LongHeader::Types::Initial;
bool is0Rtt = longHeaderType == LongHeader::Types::ZeroRtt;
auto& invariant = maybeParsedLongHeader->invariant;
if (isInitial) {
// This stats gets updated even if the client initial will be dropped.
QUIC_STATS(statsCallback_, onClientInitialReceived, invariant.version);
}
if (maybeSendVersionNegotiationPacketOrDrop(
client, isInitial, invariant, data->computeChainDataLength())) {
return;
}
bool isClientChosenDcid = isInitial || is0Rtt;
if (!isClientChosenDcid &&
invariant.dstConnId.size() < kMinSelfConnectionIdV1Size) {
// drop packet if connId is present but is not valid.
VLOG(3) << "Dropping packet due to invalid connectionId";
packetDropReason = PacketDropReason::INVALID_PACKET_CID;
return;
}
RoutingData routingData(
headerForm,
isInitial,
is0Rtt,
std::move(invariant.dstConnId),
std::move(invariant.srcConnId));
return forwardNetworkData(
client,
std::move(routingData),
NetworkData(std::move(data), packetReceiveTime),
invariant.version,
isForwardedData);
}
if (!tryHandlingAsHealthCheck(client, *data)) {
VLOG(6) << "Failed to parse long header";
packetDropReason = PacketDropReason::PARSE_ERROR_LONG_HEADER;
}
} catch (const std::exception& ex) {
// Drop the packet.
VLOG(6) << "Failed to parse packet header " << ex.what();
packetDropReason = PacketDropReason::PARSE_ERROR_EXCEPTION;
}
}
void QuicServerWorker::recvmsgMultishotCallback(
MultishotHdr* hdr,
int res,
std::unique_ptr<folly::IOBuf> io_buf) {
if (res < 0) {
return;
}
folly::EventRecvmsgMultishotCallback::ParsedRecvMsgMultishot p;
if (!folly::EventRecvmsgMultishotCallback::parseRecvmsgMultishot(
io_buf->coalesce(), hdr->data_, p)) {
return;
}
auto bytesRead = p.payload.size();
if (bytesRead > 0) {
OnDataAvailableParams params;
#ifdef FOLLY_HAVE_MSG_ERRQUEUE
if (p.control.size()) {
// hacky
struct msghdr msg;
msg.msg_controllen = p.control.size();
msg.msg_control = (void*)p.control.data();
QuicAsyncUDPSocketType::fromMsg(params, msg);
}
#endif
bool truncated = false;
if ((size_t)bytesRead != p.realPayloadLength) {
truncated = true;
}
folly::SocketAddress addr;
addr.setFromSockaddr(
reinterpret_cast<sockaddr const*>(p.name.data()), p.name.size());
io_buf->trimStart(p.payload.data() - io_buf->data());
readBuffer_ = std::move(io_buf);
// onDataAvailable will add bytesRead back
readBuffer_->trimEnd(bytesRead);
onDataAvailable(addr, bytesRead, truncated, params);
}
}
void QuicServerWorker::eventRecvmsgCallback(MsgHdr* msgHdr, int bytesRead) {
auto& msg = msgHdr->data_;
if (bytesRead > 0) {
OnDataAvailableParams params;
#ifdef FOLLY_HAVE_MSG_ERRQUEUE
if (msg.msg_control) {
QuicAsyncUDPSocketType::fromMsg(params, msg);
}
#endif
bool truncated = false;
if ((size_t)bytesRead > msgHdr->len_) {
truncated = true;
bytesRead = ssize_t(msgHdr->len_);
}
readBuffer_ = std::move(msgHdr->ioBuf_);
folly::SocketAddress addr;
addr.setFromSockaddr(
reinterpret_cast<sockaddr*>(msg.msg_name), msg.msg_namelen);
onDataAvailable(addr, bytesRead, truncated, params);
}
msgHdr_.reset(msgHdr);
}
bool QuicServerWorker::tryHandlingAsHealthCheck(
const folly::SocketAddress& client,
const folly::IOBuf& data) {
// If we cannot parse the long header then it is not a QUIC invariant
// packet, so just drop it after checking whether it could be a health
// check.
if (!healthCheckToken_) {
return false;
}
folly::IOBufEqualTo eq;
// TODO: make this constant time, the token might be secret, but we're
// current assuming it's not.
if (eq(*healthCheckToken_.value(), data)) {
// say that we are OK. The response is much smaller than the
// request, so we are not creating an amplification vector. Also
// ignore the error code.
VLOG(4) << "Health check request, response=OK";
socket_->write(client, folly::IOBuf::copyBuffer("OK"));
return true;
}
return false;
}
void QuicServerWorker::forwardNetworkData(
const folly::SocketAddress& client,
RoutingData&& routingData,
NetworkData&& networkData,
folly::Optional<QuicVersion> quicVersion,
bool isForwardedData) {
// if it's not Client initial or ZeroRtt, AND if the connectionId version
// mismatches: forward if pktForwarding is enabled else dropPacket
if (!routingData.clientChosenDcid &&
!connIdAlgo_->canParse(routingData.destinationConnId)) {
if (packetForwardingEnabled_ && !isForwardedData) {
VLOG(3) << fmt::format(
"Forwarding packet with unknown connId version from client={} to another process, routingInfo={}",
client.describe(),
logRoutingInfo(routingData.destinationConnId));
auto recvTime = networkData.receiveTimePoint;
takeoverPktHandler_.forwardPacketToAnotherServer(
client, std::move(networkData).moveAllData(), recvTime);
QUIC_STATS(statsCallback_, onPacketForwarded);
return;
} else {
VLOG(3) << fmt::format(
"Dropping packet due to unknown connectionId version, routingInfo={}",
logRoutingInfo(routingData.destinationConnId));
QUIC_STATS(
statsCallback_,
onPacketDropped,
PacketDropReason::UNKNOWN_CID_VERSION);
}
return;
}
callback_->routeDataToWorker(
client,
std::move(routingData),
std::move(networkData),
std::move(quicVersion),
isForwardedData);
}
void QuicServerWorker::setPacingTimer(
TimerHighRes::SharedPtr pacingTimer) noexcept {
pacingTimer_ = std::move(pacingTimer);
}
QuicServerTransport::Ptr QuicServerWorker::makeTransport(
QuicVersion quicVersion,
const folly::SocketAddress& client,
const folly::Optional<ConnectionId>& srcConnId,
const ConnectionId& dstConnId,
bool validNewToken) {
// create 'accepting' transport
auto* evb = getEventBase();
auto sock = makeSocket(evb);
auto trans =
transportFactory_->make(evb, std::move(sock), client, quicVersion, ctx_);
if (trans) {
globalUnfinishedHandshakes++;
if (transportSettings_.dataPathType == DataPathType::ContinuousMemory &&
bufAccessor_) {
trans->setBufAccessor(bufAccessor_.get());
}
trans->setPacingTimer(pacingTimer_);
trans->setRoutingCallback(this);
trans->setHandshakeFinishedCallback(this);
trans->setSupportedVersions(supportedVersions_);
trans->setOriginalPeerAddress(client);
if (validNewToken) {
trans->verifiedClientAddress();
}
trans->setCongestionControllerFactory(ccFactory_);
trans->setTransportStatsCallback(statsCallback_.get()); // ok if nullptr
if (quicVersion == QuicVersion::MVFST_EXPERIMENTAL) {
transportSettings_.initCwndInMss = 45;
}
auto transportSettings = transportSettingsOverrideFn_
? transportSettingsOverrideFn_(
transportSettings_, client.getIPAddress())
.value_or(transportSettings_)
: transportSettings_;
LOG_IF(
ERROR,
transportSettings.dataPathType != transportSettings_.dataPathType)
<< "Overriding DataPathType isn't supported. Requested datapath="
<< (transportSettings.dataPathType == DataPathType::ContinuousMemory
? "ContinuousMemory"
: "ChainedMemory");
trans->setTransportSettings(transportSettings);
trans->setConnectionIdAlgo(connIdAlgo_.get());
trans->setServerConnectionIdRejector(this);
if (srcConnId) {
trans->setClientConnectionId(*srcConnId);
}
trans->setClientChosenDestConnectionId(dstConnId);
// parameters to create server chosen connection id
trans->setServerConnectionIdParams(ServerConnectionIdParams(
cidVersion_, hostId_, static_cast<uint8_t>(processId_), workerId_));
trans->accept();
auto result = sourceAddressMap_.emplace(
std::make_pair(std::make_pair(client, dstConnId), trans));
CHECK(result.second);
for (const auto& observer : observerList_.getAll()) {
observer->accept(trans.get());
}
}
return trans;
}
PacketDropReason QuicServerWorker::isDstConnIdMisrouted(
const ConnectionId& dstConnId,
const folly::SocketAddress& client) {
// parse dst conn-id to determine if packet was misrouted
if (!connIdAlgo_->canParse(dstConnId)) {
VLOG(3) << "Dropping packet with bad DCID, routingInfo="
<< logRoutingInfo(dstConnId);
// TODO do we need to reset?
return PacketDropReason::PARSE_ERROR_BAD_DCID;
}
auto maybeParsedConnIdParam = connIdAlgo_->parseConnectionId(dstConnId);
if (maybeParsedConnIdParam.hasError()) {
const auto& ex = maybeParsedConnIdParam.error();
VLOG(3) << fmt::format(
"Dropping packet due to DCID parsing error={}, errorCode={},"
"routingInfo = {} ",
ex.what(),
folly::to_underlying(ex.errorCode()),
logRoutingInfo(dstConnId));
// TODO do we need to reset?
return PacketDropReason::PARSE_ERROR_DCID;
}
const auto& connIdParams = maybeParsedConnIdParam.value();
if (connIdParams.hostId != hostId_) {
VLOG(3) << fmt::format(
"Dropping packet routed to wrong host, from client={}, routingInfo={},",
client.describe(),
logRoutingInfo(dstConnId));
return PacketDropReason::ROUTING_ERROR_WRONG_HOST;
}
if (connIdParams.processId == static_cast<uint8_t>(processId_)) {
// There's no existing connection for the packet's CID or the client's
// addr, and doesn't belong to the old server. Send a Reset.
VLOG(3) << fmt::format(
"Dropping packet, unknown DCID, from client={}, routingInfo={},",
client.describe(),
logRoutingInfo(dstConnId));
return PacketDropReason::CONNECTION_NOT_FOUND;
}
return PacketDropReason::NONE;
}
void QuicServerWorker::dispatchPacketData(
const folly::SocketAddress& client,
RoutingData&& routingData,
NetworkData&& networkData,
folly::Optional<QuicVersion> quicVersion,
bool isForwardedData) noexcept {
DCHECK(socket_);
CHECK(transportFactory_);
// if set, log drop reason and do *not* attempt to forward packet
auto packetDropReason = PacketDropReason::NONE;
// if set, *should* attempt to forward packet to another server
bool shouldFwdPacket = false;
const auto& maybeSrcConnId = routingData.sourceConnId;
const auto& dstConnId = routingData.destinationConnId;
auto cit = connectionIdMap_.find(dstConnId);
// if conditions satisfy, drop packet or fwd to another server
auto handlePacketFwdOrDrop = folly::makeGuard([&]() {
if (packetDropReason == PacketDropReason::NONE && !shouldFwdPacket) {
// nothing to do here, early return
return;
}
// should either be marked as dropped or fwd-ed, can't be both
CHECK((packetDropReason != PacketDropReason::NONE) ^ shouldFwdPacket);
if (packetDropReason != PacketDropReason::NONE) {
QUIC_STATS(statsCallback_, onPacketDropped, packetDropReason);
return;
}
packetDropReason = isDstConnIdMisrouted(dstConnId, client);
if (packetDropReason != PacketDropReason::NONE) {
QUIC_STATS(statsCallback_, onPacketDropped, packetDropReason);
if (packetDropReason == PacketDropReason::ROUTING_ERROR_WRONG_HOST ||
packetDropReason == PacketDropReason::CONNECTION_NOT_FOUND) {
// packet was misrouted, send reset packet
sendResetPacket(routingData.headerForm, client, networkData, dstConnId);
}
return;
}
// send reset packet if packet fwd-ing isn't enabled or packet has
// already been fwd-ed
if (!packetForwardingEnabled_ || isForwardedData) {
packetDropReason = PacketDropReason::CANNOT_FORWARD_DATA;
VLOG(3) << fmt::format(
"Dropping packet, cannot forward, from client={}, routingInfo={},",
client.describe(),
logRoutingInfo(dstConnId));
QUIC_STATS(statsCallback_, onPacketDropped, packetDropReason);
sendResetPacket(routingData.headerForm, client, networkData, dstConnId);
return;
}
// Optimistically route to another server if the packet type is not
// Initial and if there is not any connection associated with the given
// packet
VLOG(4) << fmt::format(
"Forwarding packet from client={} to another process, routingInfo={}",
client.describe(),
logRoutingInfo(dstConnId));
auto recvTime = networkData.receiveTimePoint;
takeoverPktHandler_.forwardPacketToAnotherServer(
client, std::move(networkData).moveAllData(), recvTime);
QUIC_STATS(statsCallback_, onPacketForwarded);
});
// helper fn to handle fwd-ing data to the transport
auto fwdNetworkDataToTransport = [&](QuicServerTransport* transport) {
DCHECK(transport->getEventBase()->isInEventBaseThread());
transport->onNetworkData(client, std::move(networkData));
// process pending 0rtt data for this DCID if present
if (routingData.isInitial && !pending0RttData_.empty()) {
auto itr = pending0RttData_.find(dstConnId);
if (itr != pending0RttData_.end()) {
for (auto& data : itr->second) {
transport->onNetworkData(client, std::move(data));
}
pending0RttData_.erase(itr);
}
}
};
if (cit != connectionIdMap_.end()) {
VLOG(10) << "Found existing connection for CID=" << dstConnId.hex() << " "
<< *cit->second.get();
fwdNetworkDataToTransport(cit->second.get());
return;
}
if (routingData.headerForm == HeaderForm::Short) {
// Drop if short header packet w/ unrecognized dst conn id
VLOG(3) << fmt::format(
"Dropping short header packet with no connid match routingInfo={}",
logRoutingInfo(dstConnId));
// try forwarding the packet to the old server (if it is enabled)
shouldFwdPacket = true;
return;
}
// For LongHeader packets without existing associated connection, try to
// route with destinationConnId chosen by the peer and IP address of the
// peer.
CHECK(routingData.headerForm == HeaderForm::Long);
auto sit = sourceAddressMap_.find({client, dstConnId});
if (sit != sourceAddressMap_.end()) {
VLOG(4) << "Found existing connection for client=" << client << " "
<< sit->second.get();
fwdNetworkDataToTransport(sit->second.get());
return;
}
// If it's a 0RTT packet and we have no CID, we probably lost the
// initial and want to buffer it for a while.
if (routingData.is0Rtt) {
// creates vector if it doesn't already exist
auto& vec = pending0RttData_.insert(dstConnId, {}).first->second;
if (vec.size() < vec.max_size()) {
vec.emplace_back(std::move(networkData));
QUIC_STATS(statsCallback_, onZeroRttBuffered);
}
return;
}
// non-initial packet w/o existing connection may have been misrouted.
if (!routingData.isInitial) {
VLOG(3) << fmt::format(
"Dropping packet from client={}, routingInfo={}",
client.describe(),
logRoutingInfo(dstConnId));
// try forwarding the packet to the old server (if it is enabled)
shouldFwdPacket = true;
return;
}
// check that we have a proper quic version before creating transport
CHECK(quicVersion.has_value()) << "no QUIC version to create transport";
VLOG(4) << fmt::format(
"Creating new connection for client={}, routingInfo={}",
client.describe(),
logRoutingInfo(dstConnId));
// This could be a new connection, add it in the map
// verify that the initial packet is at least min initial bytes
// to avoid amplification attacks. Also check CID sizes.
if (networkData.totalData < kMinInitialPacketSize ||
!isValidConnIdLength(dstConnId)) {
// Don't even attempt to forward the packet, just drop it.
VLOG(3) << "Dropping small initial packet from client=" << client;
packetDropReason = PacketDropReason::INVALID_PACKET_SIZE_INITIAL;
return;
}
// If there is a token present, decrypt it (could be either a retry
// token or a new token)
folly::io::Cursor cursor(networkData.packets.front().get());
auto maybeEncryptedToken = maybeGetEncryptedToken(cursor);
bool hasTokenSecret = transportSettings_.retryTokenSecret.hasValue();
// If the retryTokenSecret is not set, just skip evaluating validity of
// token and assume true
bool isValidRetryToken = !hasTokenSecret ||
(maybeEncryptedToken &&
validRetryToken(*maybeEncryptedToken, dstConnId, client.getIPAddress()));
bool isValidNewToken = !hasTokenSecret ||
(maybeEncryptedToken &&
validNewToken(*maybeEncryptedToken, client.getIPAddress()));
if (isValidNewToken) {
QUIC_STATS(statsCallback_, onNewTokenReceived);
} else if (maybeEncryptedToken && !isValidRetryToken) {
// Failed to decrypt the token as either a new or retry token
QUIC_STATS(statsCallback_, onTokenDecryptFailure);
}
// If rate-limiting is configured and there is no retry token,
// send a retry packet back to the client
if (!isValidRetryToken &&
((newConnRateLimiter_ &&
newConnRateLimiter_->check(networkData.receiveTimePoint)) ||
(unfinishedHandshakeLimitFn_.has_value() &&
globalUnfinishedHandshakes >= (*unfinishedHandshakeLimitFn_)()))) {
QUIC_STATS(statsCallback_, onConnectionRateLimited);
sendRetryPacket(
client,
dstConnId,
maybeSrcConnId.value_or(ConnectionId(std::vector<uint8_t>())));
return;
}
auto transport = makeTransport(
quicVersion.value(), client, maybeSrcConnId, dstConnId, isValidNewToken);
if (!transport) {
// Act as though we received a junk Initial – don't forward packet.
CHECK(maybeSrcConnId.has_value());
LongHeaderInvariant inv{
QuicVersion::MVFST_INVALID, maybeSrcConnId.value(), dstConnId};
packetDropReason = PacketDropReason::CANNOT_MAKE_TRANSPORT;
sendVersionNegotiationPacket(client, inv);
return;
}
fwdNetworkDataToTransport(transport.get());
}
void QuicServerWorker::sendResetPacket(
const HeaderForm& headerForm,
const folly::SocketAddress& client,
const NetworkData& networkData,
const ConnectionId& connId) {
if (headerForm != HeaderForm::Short) {
// Only send resets in response to short header packets.
return;
}
auto packetSize = networkData.totalData;
auto resetSize = std::min<uint16_t>(packetSize, kDefaultMaxUDPPayload);
// Per the spec, less than 43 we should respond with packet size - 1.
if (packetSize < 43) {
resetSize = std::max<uint16_t>(packetSize - 1, kMinStatelessPacketSize);
} else {
resetSize = std::max<uint16_t>(
folly::Random::secureRand32() % resetSize, kMinStatelessPacketSize);
}
CHECK(transportSettings_.statelessResetTokenSecret.has_value());
StatelessResetGenerator generator(
*transportSettings_.statelessResetTokenSecret,
getAddress().getFullyQualified());
StatelessResetToken token = generator.generateToken(connId);
StatelessResetPacketBuilder builder(resetSize, token);
auto resetData = std::move(builder).buildPacket();
auto resetDataLen = resetData->computeChainDataLength();
socket_->write(client, std::move(resetData));
QUIC_STATS(statsCallback_, onWrite, resetDataLen);
QUIC_STATS(statsCallback_, onPacketSent);
QUIC_STATS(statsCallback_, onStatelessReset);
}
folly::Optional<std::string> QuicServerWorker::maybeGetEncryptedToken(
folly::io::Cursor& cursor) {
// Move cursor to the byte right after the initial byte
if (!cursor.canAdvance(1)) {
return folly::none;
}
auto initialByte = cursor.readBE<uint8_t>();
// We already know this is an initial packet, which uses a long header
auto parsedLongHeader = parseLongHeader(initialByte, cursor);
if (!parsedLongHeader || !parsedLongHeader->parsedLongHeader.has_value()) {
return folly::none;
}
auto header = parsedLongHeader->parsedLongHeader.value().header;
if (!header.hasToken()) {
return folly::none;
}
return header.getToken();
}
/**
* Helper method to calculate the delta between nowInMs and the time the token
* was issued. This delta is compared against the max lifetime of the token
* (e.g. 1 day for new tokens and 5 min for retry tokens) to determine
* validity.
*/
static bool checkTokenAge(uint64_t tokenIssuedMs, uint64_t kTokenValidMs) {
uint64_t nowInMs = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch())
.count();
// Retry timestamps can also come from the future as the system clock can
// move both forwards and backwards due to it being synchronized by NTP
auto tokenAgeMs = nowInMs > tokenIssuedMs ? nowInMs - tokenIssuedMs
: tokenIssuedMs - nowInMs;
return tokenAgeMs <= kTokenValidMs;
}
bool QuicServerWorker::validRetryToken(
std::string& encryptedToken,
const ConnectionId& dstConnId,
const folly::IPAddress& clientIp) {
CHECK(transportSettings_.retryTokenSecret.hasValue());
TokenGenerator tokenGenerator(transportSettings_.retryTokenSecret.value());
// Create a pseudo token to generate the assoc data.
RetryToken token(dstConnId, clientIp, 0);
auto maybeDecryptedRetryTokenMs = tokenGenerator.decryptToken(
folly::IOBuf::copyBuffer(encryptedToken), token.genAeadAssocData());
return maybeDecryptedRetryTokenMs &&
checkTokenAge(maybeDecryptedRetryTokenMs, kMaxRetryTokenValidMs);
}
bool QuicServerWorker::validNewToken(
std::string& encryptedToken,
const folly::IPAddress& clientIp) {
CHECK(transportSettings_.retryTokenSecret.hasValue());
TokenGenerator tokenGenerator(transportSettings_.retryTokenSecret.value());
// Create a pseudo token to generate the assoc data.
NewToken token(clientIp);
auto maybeDecryptedNewTokenMs = tokenGenerator.decryptToken(
folly::IOBuf::copyBuffer(encryptedToken), token.genAeadAssocData());
return maybeDecryptedNewTokenMs &&
checkTokenAge(maybeDecryptedNewTokenMs, kMaxNewTokenValidMs);
}
void QuicServerWorker::sendRetryPacket(
const folly::SocketAddress& client,
const ConnectionId& dstConnId,
const ConnectionId& srcConnId) {
if (!transportSettings_.retryTokenSecret.hasValue()) {
VLOG(4) << "Not sending retry packet since retry token secret is not set";
return;
}
// Create the encrypted retry token
TokenGenerator generator(transportSettings_.retryTokenSecret.value());
// RetryToken defaults to currentTimeInMs
RetryToken retryToken(dstConnId, client.getIPAddress(), client.getPort());
auto encryptedToken = generator.encryptToken(retryToken);
CHECK(encryptedToken.has_value());
std::string encryptedTokenStr =
encryptedToken.value()->moveToFbString().toStdString();
// Create the integrity tag
// For the tag to be correctly validated by the client, the initalByte
// needs to match the initialByte in the retry packet
uint8_t initialByte = kHeaderFormMask | LongHeader::kFixedBitMask |
(static_cast<uint8_t>(LongHeader::Types::Retry)
<< LongHeader::kTypeShift);
// Flip the src conn ID and dst conn ID as per section 7.3 of QUIC draft
// for both pseudo retry builder and the actual retry packet builder
PseudoRetryPacketBuilder pseudoBuilder(
initialByte,
dstConnId, /* src conn id */
srcConnId, /* dst conn id */
dstConnId, /* original dst conn id */
QuicVersion::MVFST_INVALID,
folly::IOBuf::copyBuffer(encryptedTokenStr));
Buf pseudoRetryPacketBuf = std::move(pseudoBuilder).buildPacket();
FizzRetryIntegrityTagGenerator fizzRetryIntegrityTagGenerator;
auto integrityTag = fizzRetryIntegrityTagGenerator.getRetryIntegrityTag(
QuicVersion::MVFST_INVALID, pseudoRetryPacketBuf.get());
// Create the actual retry packet
RetryPacketBuilder builder(
dstConnId, /* src conn id */
srcConnId, /* dst conn id */
QuicVersion::MVFST_INVALID,
std::move(encryptedTokenStr),
std::move(integrityTag));
auto retryData = std::move(builder).buildPacket();
auto retryDataLen = retryData->computeChainDataLength();
socket_->write(client, retryData);
QUIC_STATS(statsCallback_, onWrite, retryDataLen);
QUIC_STATS(statsCallback_, onPacketSent);
}
void QuicServerWorker::allowBeingTakenOver(
std::unique_ptr<QuicAsyncUDPSocketType> socket,
const folly::SocketAddress& address) {
DCHECK(!takeoverCB_);
// We instantiate and bind the TakeoverHandlerCallback to the given address.
// It is reset at shutdownAllConnections (i.e. only when the process dies).
takeoverCB_ = std::make_unique<TakeoverHandlerCallback>(
this, takeoverPktHandler_, transportSettings_, std::move(socket));
takeoverCB_->bind(address);
}
const folly::SocketAddress& QuicServerWorker::overrideTakeoverHandlerAddress(
std::unique_ptr<QuicAsyncUDPSocketType> socket,
const folly::SocketAddress& address) {
CHECK(takeoverCB_);
takeoverCB_->rebind(std::move(socket), address);
return takeoverCB_->getAddress();
}
void QuicServerWorker::startPacketForwarding(
const folly::SocketAddress& destAddr) {
packetForwardingEnabled_ = true;
takeoverPktHandler_.setDestination(destAddr);
}
void QuicServerWorker::stopPacketForwarding() {
packetForwardingEnabled_ = false;
takeoverPktHandler_.stop();
}
void QuicServerWorker::onReadError(
const folly::AsyncSocketException& ex) noexcept {
VLOG(4) << "QuicServer readerr: " << ex.what();
if (!callback_) {
VLOG(0) << "Worker callback is null. Ignoring worker error.";
return;
}
callback_->handleWorkerError(LocalErrorCode::INTERNAL_ERROR);
}
void QuicServerWorker::onReadClosed() noexcept {
shutdownAllConnections(LocalErrorCode::SHUTTING_DOWN);
}
int QuicServerWorker::getTakeoverHandlerSocketFD() {
CHECK(takeoverCB_);
return takeoverCB_->getSocketFD();
}
TakeoverProtocolVersion QuicServerWorker::getTakeoverProtocolVersion()
const noexcept {
return takeoverPktHandler_.getTakeoverProtocolVersion();
}
void QuicServerWorker::setProcessId(enum ProcessId id) noexcept {
processId_ = id;
}
ProcessId QuicServerWorker::getProcessId() const noexcept {
return processId_;
}
void QuicServerWorker::setWorkerId(uint8_t id) noexcept {
workerId_ = id;
}
uint8_t QuicServerWorker::getWorkerId() const noexcept {
return workerId_;
}
void QuicServerWorker::setHostId(uint32_t hostId) noexcept {
hostId_ = hostId;
}
void QuicServerWorker::setConnectionIdVersion(
ConnectionIdVersion cidVersion) noexcept {
cidVersion_ = cidVersion;
}
void QuicServerWorker::setNewConnectionSocketFactory(
QuicUDPSocketFactory* factory) {
socketFactory_ = factory;
takeoverPktHandler_.setSocketFactory(socketFactory_);
}
void QuicServerWorker::setTransportFactory(
QuicServerTransportFactory* factory) {
transportFactory_ = factory;
}
void QuicServerWorker::setSupportedVersions(
const std::vector<QuicVersion>& supportedVersions) {
supportedVersions_ = supportedVersions;
}
void QuicServerWorker::setFizzContext(
std::shared_ptr<const fizz::server::FizzServerContext> ctx) {
ctx_ = ctx;
}
void QuicServerWorker::setTransportSettings(
TransportSettings transportSettings) {
transportSettings_ = transportSettings;
if (transportSettings_.batchingMode != QuicBatchingMode::BATCHING_MODE_GSO) {
if (transportSettings_.dataPathType == DataPathType::ContinuousMemory) {
LOG(ERROR) << "Unsupported data path type and batching mode combination";
}
transportSettings_.dataPathType = DataPathType::ChainedMemory;
}
if (transportSettings_.dataPathType == DataPathType::ContinuousMemory) {
// TODO: maxBatchSize is only a good start value when each transport does
// its own socket writing. If we experiment with multiple transports GSO
// together, we will need a better value.
bufAccessor_ = std::make_unique<SimpleBufAccessor>(
kDefaultMaxUDPPayload * transportSettings_.maxBatchSize);
VLOG(10) << "GSO write buf accessor created for ContinuousMemory data path";
}
}
void QuicServerWorker::rejectNewConnections(
std::function<bool()> rejectNewConnections) {
rejectNewConnections_ = std::move(rejectNewConnections);
}
void QuicServerWorker::setIsBlockListedSrcPort(
std::function<bool(uint16_t)> isBlockListedSrcPort) {
isBlockListedSrcPort_ = std::move(isBlockListedSrcPort);
}
void QuicServerWorker::setHealthCheckToken(
const std::string& healthCheckToken) {
healthCheckToken_ = folly::IOBuf::copyBuffer(healthCheckToken);
}
std::unique_ptr<QuicAsyncUDPSocketType> QuicServerWorker::makeSocket(
folly::EventBase* evb) const {
CHECK(socket_);
auto sock = socketFactory_->make(evb, getSocketFd(*socket_));
if (sock && mvfst_hook_on_socket_create) {
mvfst_hook_on_socket_create(getSocketFd(*sock));
}
return sock;
}
std::unique_ptr<QuicAsyncUDPSocketType> QuicServerWorker::makeSocket(
folly::EventBase* evb,
int fd) const {
auto sock = socketFactory_->make(evb, fd);
if (sock && mvfst_hook_on_socket_create) {
mvfst_hook_on_socket_create(getSocketFd(*sock));
}
return sock;
}
const QuicServerWorker::ConnIdToTransportMap&
QuicServerWorker::getConnectionIdMap() const {
return connectionIdMap_;
}
const QuicServerWorker::SrcToTransportMap&
QuicServerWorker::getSrcToTransportMap() const {
return sourceAddressMap_;
}
void QuicServerWorker::onConnectionIdAvailable(
QuicServerTransport::Ptr transport,
ConnectionId id) noexcept {
VLOG(4) << "Adding into connectionIdMap_ for CID=" << id << " " << *transport;
QuicServerTransport* transportPtr = transport.get();
std::weak_ptr<QuicServerTransport> weakTransport = transport;
auto result =
connectionIdMap_.emplace(std::make_pair(id, std::move(transport)));
if (!result.second) {
// In the case of duplicates, log if they represent the same transport,
// or different ones.
auto it = result.first;
QuicServerTransport* existingTransportPtr = it->second.get();
LOG(ERROR) << "connectionIdMap_ already has CID=" << id
<< " Is same transport: "
<< (existingTransportPtr == transportPtr);
} else if (boundServerTransports_.emplace(transportPtr, weakTransport)
.second) {
if (!isScheduled()) {
// If we aren't currently running, start the timer.
evb_->timer().scheduleTimeout(this, timeLoggingSamplingInterval_);
}
QUIC_STATS(statsCallback_, onNewConnection);
}
}
void QuicServerWorker::onConnectionIdRetired(
QuicServerTransport::Ref transport,
ConnectionId id) noexcept {
auto it = connectionIdMap_.find(id);
if (it == connectionIdMap_.end()) {
LOG(ERROR) << "Failed to retire CID=" << id << " " << transport;
} else {
VLOG(4) << "Retiring CID=" << id << " " << transport;
connectionIdMap_.erase(it);
}
}
void QuicServerWorker::onConnectionIdBound(
QuicServerTransport::Ptr transport) noexcept {
auto clientInitialDestCid = transport->getClientChosenDestConnectionId();
CHECK(clientInitialDestCid);
auto source = std::make_pair(
transport->getOriginalPeerAddress(), *clientInitialDestCid);
VLOG(4) << "Removing from sourceAddressMap_ address=" << source.first;
auto iter = sourceAddressMap_.find(source);
if (iter == sourceAddressMap_.end() || iter->second != transport) {
LOG(ERROR) << "Transport not match, client=" << *transport;
} else {
sourceAddressMap_.erase(source);
}
}
void QuicServerWorker::onConnectionUnbound(
QuicServerTransport* transport,
const QuicServerTransport::SourceIdentity& source,
const std::vector<ConnectionIdData>& connectionIdData) noexcept {
VLOG(4) << "Removing from sourceAddressMap_ address=" << source.first;
auto& localConnectionError = transport->getState()->localConnectionError;
if (transport->getConnectionsStats().totalBytesSent == 0 &&
!(localConnectionError && localConnectionError->code.asLocalErrorCode() &&
*localConnectionError->code.asLocalErrorCode() ==
LocalErrorCode::CONNECTION_ABANDONED)) {
QUIC_STATS(statsCallback_, onConnectionCloseZeroBytesWritten);
}
// Ensures we only process `onConnectionUnbound()` once.
transport->setRoutingCallback(nullptr);
boundServerTransports_.erase(transport);
// Cancel the timeout if we don't have any connections.
if (boundServerTransports_.empty()) {
cancelTimeout();
}
for (auto& connId : connectionIdData) {
VLOG(4) << fmt::format(
"Removing CID from connectionIdMap_, routingInfo={}",
logRoutingInfo(connId.connId));
auto it = connectionIdMap_.find(connId.connId);
// This should be nullptr in most cases. In order to investigate if
// an incorrect server transport is removed, this will be set to the value
// of the incorrect transport, to see if boundServerTransports_ will
// still hold a pointer to the incorrect transport.
QuicServerTransport* incorrectTransportPtr = nullptr;
if (it == connectionIdMap_.end()) {
VLOG(3) << "CID not found in connectionIdMap_ CID= " << connId.connId;
} else {
QuicServerTransport* existingPtr = it->second.get();
if (existingPtr != transport) {
LOG(ERROR) << "Incorrect transport being removed for duplicate CID="
<< connId.connId;
incorrectTransportPtr = existingPtr;
}
}
connectionIdMap_.erase(connId.connId);
if (incorrectTransportPtr != nullptr) {
if (boundServerTransports_.find(incorrectTransportPtr) !=
boundServerTransports_.end()) {
LOG(ERROR)
<< "boundServerTransports_ contains deleted transport for duplicate CID="
<< connId.connId;
}
}
}
sourceAddressMap_.erase(source);
}
void QuicServerWorker::onHandshakeFinished() noexcept {
CHECK_GE(--globalUnfinishedHandshakes, 0);
}
void QuicServerWorker::onHandshakeUnfinished() noexcept {
CHECK_GE(--globalUnfinishedHandshakes, 0);
}
void QuicServerWorker::shutdownAllConnections(LocalErrorCode error) {
VLOG(4) << "QuicServer shutdown all connections."
<< " addressMap=" << sourceAddressMap_.size()
<< " connectionIdMap=" << connectionIdMap_.size();
if (shutdown_) {
return;
}
shutdown_ = true;
if (socket_) {
socket_->pauseRead();
}
if (takeoverCB_) {
takeoverCB_->pause();
}
callback_ = nullptr;
// Shut down all transports without bound connection ids.
for (auto& it : sourceAddressMap_) {
auto transport = it.second;
transport->setRoutingCallback(nullptr);
transport->setTransportStatsCallback(nullptr);
transport->setHandshakeFinishedCallback(nullptr);
transport->closeNow(
QuicError(QuicErrorCode(error), std::string("shutting down")));
}
// Shut down all transports with bound connection ids.
for (auto transport : boundServerTransports_) {
if (auto t = transport.second.lock()) {
t->setRoutingCallback(nullptr);
t->setTransportStatsCallback(nullptr);
t->setHandshakeFinishedCallback(nullptr);
t->closeNow(
QuicError(QuicErrorCode(error), std::string("shutting down")));
}
}
cancelTimeout();
boundServerTransports_.clear();
sourceAddressMap_.clear();
connectionIdMap_.clear();
takeoverPktHandler_.stop();
if (statsCallback_) {
statsCallback_.reset();
}
socket_.reset();
takeoverCB_.reset();
pacingTimer_.reset();
evb_.reset();
}
QuicServerWorker::~QuicServerWorker() {
shutdownAllConnections(LocalErrorCode::SHUTTING_DOWN);
}
bool QuicServerWorker::rejectConnectionId(
const ConnectionId& candidate) const noexcept {
return connectionIdMap_.find(candidate) != connectionIdMap_.end();
}
std::string QuicServerWorker::logRoutingInfo(const ConnectionId& connId) const {
std::string base = fmt::format(
"CID={}, cidVersion={}, workerId={}, processId={}, hostId={}, threadId={}, ",
connId.hex(),
(uint32_t)cidVersion_,
(uint32_t)workerId_,
(uint32_t)processId_,
(uint32_t)hostId_,
folly::getCurrentThreadID());
if (connIdAlgo_->canParse(connId)) {
auto maybeParsedConnIdParam = connIdAlgo_->parseConnectionId(connId);
if (maybeParsedConnIdParam.hasValue()) {
const auto& connIdParam = maybeParsedConnIdParam.value();
return base +
fmt::format(
"cidVersion in packet={}, workerId in packet={}, processId in packet={}, hostId in packet={}, ",
(uint32_t)connIdParam.version,
(uint32_t)connIdParam.workerId,
(uint32_t)connIdParam.processId,
(uint32_t)connIdParam.hostId);
}
}
return base;
}
QuicServerWorker::AcceptObserverList::AcceptObserverList(
QuicServerWorker* worker)
: worker_(worker) {}
QuicServerWorker::AcceptObserverList::~AcceptObserverList() {
for (const auto& cb : observers_) {
cb->acceptorDestroy(worker_);
}
}
void QuicServerWorker::AcceptObserverList::add(AcceptObserver* observer) {
// adding the same observer multiple times is not allowed
CHECK(
std::find(observers_.begin(), observers_.end(), observer) ==
observers_.end());
observers_.emplace_back(CHECK_NOTNULL(observer));
observer->observerAttach(worker_);
}
bool QuicServerWorker::AcceptObserverList::remove(AcceptObserver* observer) {
auto it = std::find(observers_.begin(), observers_.end(), observer);
if (it == observers_.end()) {
return false;
}
observer->observerDetach(worker_);
observers_.erase(it);
return true;
}
void QuicServerWorker::getAllConnectionsStats(
std::vector<QuicConnectionStats>& stats) {
folly::F14FastMap<QuicServerTransport::Ptr, uint32_t> uniqueConns;
for (const auto& [connId, transport] : connectionIdMap_) {
if (transport && transport->getState()) {
uniqueConns[transport]++;
}
}
stats.reserve(stats.size() + uniqueConns.size());
for (const auto& [transport, count] : uniqueConns) {
QuicConnectionStats connStats = transport->getConnectionsStats();
connStats.workerID = workerId_;
connStats.numConnIDs = count;
stats.emplace_back(connStats);
}
}
size_t QuicServerWorker::SourceIdentityHash::operator()(
const QuicServerTransport::SourceIdentity& sid) const {
static const ::siphash::Key hashKey(
folly::Random::secureRandom<std::uint64_t>(),
folly::Random::secureRandom<std::uint64_t>());
// We opt to manually lay out the key in order to ensure that our key
// has a unique object representation. (i.e. no padding).
//
// (sockaddr, quic connection id, port)
constexpr size_t kKeySize =
sizeof(struct sockaddr_storage) + kMaxConnectionIdSize + sizeof(uint16_t);
// Zero initialization is intentional here.
std::array<unsigned char, kKeySize> key{};
struct sockaddr_storage* storage =
reinterpret_cast<struct sockaddr_storage*>(key.data());
const auto& sockaddr = sid.first;
sockaddr.getAddress(storage);
unsigned char* connid = key.data() + sizeof(struct sockaddr_storage);
memcpy(connid, sid.second.data(), sid.second.size());
uint16_t* port = reinterpret_cast<uint16_t*>(
key.data() + sizeof(struct sockaddr_storage) + kMaxConnectionIdSize);
*port = sid.first.getPort();
return siphash::siphash24(key.data(), key.size(), &hashKey);
}
} // namespace quic
|
#ifndef __GENERATOR__
#define __GENERATOR__
#include <string>
#include <vector>
//-------------------------------------------------------------------------------------------------
// Абстрактный генератор кода на всякий случай
// Возможно придется связывать динамически разные генераторы в общий список или массив
// Сюда же, возможно, добавятся общие статические объекты
struct GlobalSpaceGen;
struct AbstractGen {
static GlobalSpaceGen* globalSpaceGenPtr;
virtual void Generate(std::string &str) = 0;
virtual void GenValue(std::string &str) {}
};
//-------------------------------------------------------------------------------------------------
// Генератор кода для глобального пространства
// Наряду с константной оберкой обеспечивает запись глобальных объектов
struct GlobalSpaceGen: AbstractGen {
std::vector<AbstractGen*> globalObjects;
std::string space; // строка с собранным глобальным пространством
// Добавление очередного объекта к глобальному пространству
void Add(AbstractGen* obj);
void Generate(std::string &str);
void GenValue(std::string &str);
};
//-------------------------------------------------------------------------------------------------
// Генератор кода для глобальных переменных
// Накапливает необходимые значения в соответствующих строках
struct GlobalVarGen: AbstractGen {
std::string name; // идентификатор переменной
std::string type; // тип переменной
std::string value; // значение переменной
virtual void Generate(std::string &str);
virtual void GenValue(std::string &str);
};
//-------------------------------------------------------------------------------------------------
// Генератор кода для глобальных функций
// Накапливает необходимые значения в соответствующих строках
struct GlobalFuncGen: AbstractGen {
std::string name; // имя объекта-функции
std::vector<std::string> paramNames; // список имен параметров (типы не нужны)
// Возращаемый параметры передается как дополнительный атрибут с некоторым именем,
// которое не должно нигде встречаться в другом контексте.
virtual void Generate(std::string &str);
virtual void GenValue(std::string &str);
};
//-------------------------------------------------------------------------------------------------
// Класс Generator. Собирает все воедино для единицы компиляции
struct FullGen: AbstractGen {
void Generate(std::string &str);
};
//-------------------------------------------------------------------------------------------------
// Генератор кода приложения
// Используется для формирования кода, запускающего программу
struct ApplicationGen: AbstractGen {
std::string appCode; // строка с порождаемым кодом
void Generate(std::string &str);
};
#endif // __GENERATOR__
|
#include "MyMeshObject.h"
MyMeshObject::MyMeshObject(MyMesh& mesh)
{
_mesh = mesh;
populatePolygons();
calculateBoundingSphere();
}
MyMeshObject::~MyMeshObject()
{
if (_boundingSphere)
{
delete(_boundingSphere);
}
}
int MyMeshObject::intersect(Ray& ray, double tMax, double& t, Point3d& P,
Vector3d& N, Color3d& texColor) const
{
bool intersectBoundingSphere = _boundingSphere->getRoots(ray);
if (!intersectBoundingSphere)
{
return 0;
}
int retVal = 0;
for (size_t i = 0; i < _polygons.size(); i++)
{
int intersectPolygon = _polygons[i].intersect(ray, tMax, t, P, N, texColor);
if (intersectPolygon == 1)
{
tMax = t;
retVal = 1;
}
}
return retVal;
}
void MyMeshObject::populatePolygons()
{
_mesh.request_face_normals();
_mesh.update_normals();
_mesh.request_vertex_texcoords2D();
bool textured = _mesh.has_vertex_texcoords2D();
bool hasNormal =_mesh.has_face_normals();
for (MyMesh::FaceIter h_it=_mesh.faces_begin(); h_it!=_mesh.faces_end(); ++h_it)
{
vector<Point3d> vertices;
vector<Point2d> textices;
// circulate around the current face
for (MyMesh::FaceVertexIter fv_it = _mesh.fv_iter(h_it); fv_it; ++fv_it)
{
MyMesh::Point p = _mesh.point(fv_it.handle());
vertices.push_back(p);
if (textured)
{
MyMesh::TexCoord2D uv = _mesh.texcoord2D(fv_it);// vhandle is a VertexHandle
textices.push_back(uv);
}
}
if (textured)
{
if (hasNormal)
{
Vector3d n = _mesh.normal(h_it);
_polygons.push_back(Polygon(vertices, textices, n));
}
else
{
_polygons.push_back(Polygon(vertices, textices));
}
}
else
{
if (hasNormal)
{
Vector3d n = _mesh.normal(h_it);
_polygons.push_back(Polygon(vertices, n));
}
else
{
_polygons.push_back(Polygon(vertices));
}
}
_polygons.back().setParent(this);
}
_mesh.release_face_normals();
}
void MyMeshObject::calculateBoundingSphere()
{
Point3d center = Point3d(0, 0, 0);
double radius = 0.0;
MyMesh::VertexIter vertexIter;
int vNum = _mesh.n_vertices();
for (vertexIter = _mesh.vertices_begin(); vertexIter != _mesh.vertices_end(); ++vertexIter)
{
center += _mesh.point(vertexIter);
}
center /= (double)vNum;
for (vertexIter = _mesh.vertices_begin(); vertexIter != _mesh.vertices_end(); ++vertexIter)
{
Point3d p = center - _mesh.point(vertexIter);
radius = std::max(radius, p.length());
}
_boundingSphere = new Sphere(center, radius + EPS);
}
void MyMeshObject::set_texture_map(BImage* image)
{
_diffuseTexture = image;
for (size_t i=0; i<_polygons.size(); i++)
{
_polygons[i].set_texture_map(image);
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#ifndef MODULES_HARDCORE_MH_MH_H
#define MODULES_HARDCORE_MH_MH_H
#include "modules/hardcore/mh/mh_enum.h"
#include "modules/hardcore/mh/messobj.h"
#include "modules/hardcore/unicode/unicode.h"
#include "modules/util/simset.h"
#include "modules/util/twoway.h"
#include "modules/hardcore/mh/messagelisteners.h"
#include "modules/otl/list.h"
class Window;
class DocumentManager;
class URL;
class MessageHandler;
#ifdef CPUUSAGETRACKING
class CPUUsageTracker;
#endif // CPUUSAGETRACKING
class MessageHandlerObserver
: public Link
{
public:
virtual void MessageHandlerDestroyed(MessageHandler *mh) = 0;
/**< Called from MessageHandler::~MessageHandler(). There is no need to
unregister the observer when called, this will already have been done.
(In fact, an OP_ASSERT will fail in MessageHandler::RemoveObserver() if
is called to unregister this observer.) */
protected:
virtual ~MessageHandlerObserver() { Link::Out(); }
/**< Never destroyed via this interface. */
};
class MessageHandler : public Link, public TwoWayPointer_Target
{
public:
/**
* Creates a MessageHandler.
*
* @param window The Window that the MessageHandler belongs to, or NULL
* if the MessageHandler does not belong to a Window.
* @param docman The DocumentManager that the MessageHandler belongs to, or NULL
* if the MessageHandler belongs to a Window, or when MessageHandler
* is the g_main_message_handler.
*/
MessageHandler(Window* window, DocumentManager* docman = NULL);
/**
* Destroys the MessageHandler. Clears up its memory usage and all
* pending messages.
*/
~MessageHandler();
Window* GetWindow() const { return window; }
DocumentManager* GetDocumentManager() const { return docman; }
/**
* SetCallBack lets the MessageObject listen to a number of messages with a defined id.
*
* @param obj The MessageObject which will be called when messages arrive.
* @param id The id which must match the id of the sent message to be able to receive it.
* If id is 0 the message will be forwarded even if the id's don't match.
* @param messagearray Array of OpMessage elements.
* @param messages Number of messages in the array messagearray.
* @return OpStatus::OK or OpStatus::ERR_NO_MEMORY.
*/
OP_STATUS SetCallBackList(MessageObject* obj, MH_PARAM_1 id, const OpMessage* messagearray, size_t messages);
OP_STATUS DEPRECATED(SetCallBackList(MessageObject* obj, MH_PARAM_1 id, int unused_parameter_was_priority, const OpMessage* messagearray, size_t messages));
/**
* SetCallBack lets the MessageObject listen to a specific message with a defined id.
*
* @param obj The MessageObject which will be called when messages arrive.
* @param msg Message to listen to.
* @param id The id which must match the id of the sent message to be able to receive it.
* If id is 0 the message will be forwarded even if the id's don't match.
* @return OpStatus::OK or OpStatus::ERR_NO_MEMORY.
*/
/*
What happens if the same id or msg or both is added. Check implmentation.
*/
OP_STATUS SetCallBack(MessageObject* obj, OpMessage msg, MH_PARAM_1 id);
OP_STATUS DEPRECATED(SetCallBack(MessageObject* obj, OpMessage msg, MH_PARAM_1 id, int unused_parameter_was_priority));
/**
* @deprecated This function is like RemoveCallBacks(), except it only
* removes the first callback. This is probably not what any one really
* means. Optimizing the case where one knows there is only one listener
* should not be terribly important. Use RemoveCallBacks() instead.
*/
void DEPRECATED(RemoveCallBack(MessageObject* obj, MH_PARAM_1 id));
/**
* @deprecated This function has never actually existed (until now).
* UnsetCallBack(MessageObject *, OpMessage) should be used instead.
*/
void DEPRECATED(RemoveCallBack(MessageObject* obj, OpMessage msg));
void RemoveCallBacks(MessageObject* obj, MH_PARAM_1 id);
/**
@return TRUE if the MessageHandler has a callback for the MessageObject, and the following msg and id.
*/
BOOL HasCallBack(MessageObject* obj, OpMessage msg, MH_PARAM_1 id);
/**
What is the difference between UnsetCallBack and RemoveCallBack?
They seem to take different parameters, but they are so confusing.
*/
void UnsetCallBack(MessageObject* obj, OpMessage msg, MH_PARAM_1 id);
void UnsetCallBack(MessageObject* obj, OpMessage msg);
void UnsetCallBacks(MessageObject* obj);
/**
* Post a message to the currently running core component.
*
* @param msg The message type.
* @param par1 Custom message parameter 1.
* @param par2 Custom message parameter 2.
* @param delay The number of milliseconds from now that this message should be delivered.
*
* @return TRUE on success, FALSE on OOM.
*/
BOOL PostMessage(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2, unsigned long delay=0);
BOOL PostDelayedMessage(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2, unsigned long delay);
void RemoveDelayedMessage(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2);
void RemoveDelayedMessages(OpMessage msg, MH_PARAM_1 par1);
void RemoveFirstDelayedMessage(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2);
void RemoveFirstDelayedMessage(OpMessage msg, MH_PARAM_1 par1);
void HandleErrors();
void HandleMessage(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2);
void PostOOMCondition( BOOL must_abort );
void PostOODCondition();
void AddObserver(MessageHandlerObserver *observer);
/**< Registers an observer that will be notified when the MessageHandler is
destroyed. The observer is not owned by the MessageHandler, and will
be called at most once, and is guaranteed to be called once unless it
is destroyed or unregistered before the MessageHandler is destroyed.
If the observer is already observing this MessageHandler, nothing
happens, and if it is observing another MessageHandler, it will be
unregistered from it automatically. */
void RemoveObserver(MessageHandlerObserver *observer);
/**< Unregisters an observer previously registered using AddObserver(). An
observer will always unregister itself in its destructor, so it is only
necessary to unregister it if it should stop observing before it is
destroyed. */
private:
OP_STATUS HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2);
OP_STATUS HandleMessageBox(int id);
Window* window;
#ifdef CPUUSAGETRACKING
CPUUsageTracker* cpu_usage_tracker;
#endif // CPUUSAGETRACKING
DocumentManager* docman;
CoreComponent* component;
HC_MessageListeners listeners;
int handle_msg_count; // Keeps track of nesting calls to HandleMessage routine
// This is necessary if a SendMessage is sent from the object's
// HandleMessage routine.
int msb_box_id;
AutoDeleteHead msb_box_list;
Head observers;
};
class MsgHndlListElm
{
friend class MsgHndlList;
private:
TwoWayPointer<MessageHandler> mh;
BOOL load_as_inline;
BOOL check_modified_silent;
BOOL load_silent;
MsgHndlListElm(MessageHandler* m, BOOL inline_loading, BOOL silent_modified_check, BOOL silent_loading) { mh = m; load_as_inline = inline_loading; check_modified_silent = silent_modified_check, load_silent = silent_loading; };
public:
MsgHndlListElm() : load_as_inline(FALSE), check_modified_silent(FALSE), load_silent(FALSE) {}
MessageHandler* GetMessageHandler() { return mh; }
BOOL GetLoadAsInline() const { return load_as_inline; };
BOOL GetCheckModifiedSilent() const { return check_modified_silent; };
BOOL GetLoadSilent() const { return load_silent; }
};
class MsgHndlList
{
public:
typedef OtlList<MsgHndlListElm*>::Iterator Iterator;
typedef OtlList<MsgHndlListElm*>::ConstIterator ConstIterator;
MsgHndlList() {}
~MsgHndlList() { Clean(); }
void Clean();
OP_STATUS Add(MessageHandler* m, BOOL inline_loading, BOOL check_modified_silent, BOOL load_silent, BOOL always_new, BOOL first);
void Remove(MessageHandler* m);
BOOL HasMsgHandler(MessageHandler* m, BOOL inline_loading, BOOL check_modified_silent, BOOL load_silent);
MessageHandler* FirstMsgHandler();
void BroadcastMessage(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2, int flags) { LocalBroadcastMessage(msg, par1, par2, flags, 0); };
BOOL BroadcastDelayedMessage(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2, int flags, unsigned long delay) { return LocalBroadcastMessage(msg, par1, par2, flags, delay); }
BOOL IsEmpty() {CleanList(); return mh_list.IsEmpty(); }
void SetProgressInformation(ProgressState progress_level, unsigned long progress_info1, const uni_char *progress_info2, URL *url = NULL);
Iterator Begin() { return mh_list.Begin(); }
ConstIterator Begin() const { return mh_list.Begin(); }
ConstIterator End() const { return mh_list.End(); }
private:
BOOL LocalBroadcastMessage(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2, int flags, unsigned long delay);
void CleanList();
OtlList<MsgHndlListElm*> mh_list;
};
// Utility function available by enabling API_HC_MESSAGE_NAMES
#ifdef MESSAGE_NAMES
const char* GetStringFromMessage(OpMessage);
#endif // MESSAGE_NAMES
#endif // !MODULES_HARDCORE_MH_MH_H
|
#pragma once
#include "vfs/vfs.h"
#include "script/jsfunctioncall.h"
#include "script/jsfunction.h"
#include "script/wrappedhelpers.hpp"
namespace script
{
class ScriptEngine;
class GlobalObject : public ScriptedObject
{
friend class ScriptEngine;
public:
static ScriptClass m_scriptClass;
protected:
void destroyScriptObject() {}
};
class ScriptEngine
{
private:
JSRuntime *rt;
JSContext *cx;
JSErrorReporter reporter;
GlobalObject m_global;
public:
ScriptEngine();
~ScriptEngine();
JSErrorReporter SetErrorReporter(JSErrorReporter reporter);
void ReportError(char* format, ...);
bool RunScript(const char* script);
bool RunScript(const char* script, jsval* retval);
bool RunScript(const char* name, uintN lineno, const char* script);
bool RunScript(const char* name, uintN lineno, const char* script, jsval* retval);
bool RunScript(vfs::File file);
bool CheckException();
JSFunction* AddFunction(const char* name, uintN argc, JSNative call);
JSFunction* AddFunction(JSObject* obj, const char* name, uintN argc, JSNative call);
JSObject* AddObject(const char* name, JSObject* parent);
inline JSObject* GetGlobal() { return m_global.getScriptObject(); }
inline JSContext* GetContext() { return cx; }
bool AddProperty(JSObject* obj, const char* name, jsval value, JSPropertyOp getter, JSPropertyOp setter, uintN flags);
bool GetProperty(JSObject* parent, const char* name, jsval* object);
JSObject* GetObject(const char* name, bool create = false);
const char* GetClassName(JSObject* obj);
void DumpObject(JSObject* obj, bool recurse = false, const char* objname = "", const char* name = "");
pair<string, vector<string>> TabComplete(const std::string& command);
};
// hack, replace with getScriptEngine()
extern ScriptEngine* gScriptEngine;
void errorreporter(JSContext *cx, const char *message, JSErrorReport *report);
void init();
void release();
JSObject* GetObject(const string& name);
}
|
#include<iostream>
#include<vector>
#include<memory>
using namespace std;
class Konto;
class Bank{
vector<shared_ptr<Person>> kunden;
string bankname;
public:
Bank();
Bank(string);
ostream& print(ostream&) const;
void neuerKunde(string, char);
vector<shared_ptr<Person>> getKunden() const;
void kuendigen();
};
inline ostream& operator <<(ostream& o, const Bank& b){
return b.print(o);
}
|
#include "Vulkan/VulkanSwapChain.h"
#include "Vulkan/VulkanFunction.h"
#include <GLFW/glfw3.h>
using namespace Rocket;
void VulkanSwapChain::Connect(VkInstance instance, VkPhysicalDevice physicalDevice, VkDevice device, VkSurfaceKHR surface)
{
this->instance = instance;
this->physicalDevice = physicalDevice;
this->device = device;
this->surface = surface;
GET_INSTANCE_PROC_ADDR(instance, GetPhysicalDeviceSurfaceSupportKHR);
GET_INSTANCE_PROC_ADDR(instance, GetPhysicalDeviceSurfaceCapabilitiesKHR);
GET_INSTANCE_PROC_ADDR(instance, GetPhysicalDeviceSurfaceFormatsKHR);
GET_INSTANCE_PROC_ADDR(instance, GetPhysicalDeviceSurfacePresentModesKHR);
GET_DEVICE_PROC_ADDR(device, CreateSwapchainKHR);
GET_DEVICE_PROC_ADDR(device, DestroySwapchainKHR);
GET_DEVICE_PROC_ADDR(device, GetSwapchainImagesKHR);
GET_DEVICE_PROC_ADDR(device, AcquireNextImageKHR);
GET_DEVICE_PROC_ADDR(device, QueuePresentKHR);
SwapChainSupportDetails swapChainSupport = QuerySwapChainSupport(physicalDevice, surface);
surfaceFormat = ChooseSwapSurfaceFormat(swapChainSupport.formats);
extent = ChooseSwapExtent(swapChainSupport.capabilities, windowHandle);
colorFormat = surfaceFormat.format;
colorSpace = surfaceFormat.colorSpace;
}
void VulkanSwapChain::Initialize(bool vsync)
{
VkSwapchainKHR oldSwapchain = swapChain;
// Get physical device surface properties and formats
VkSurfaceCapabilitiesKHR surfCaps;
VK_CHECK(fpGetPhysicalDeviceSurfaceCapabilitiesKHR(physicalDevice, surface, &surfCaps));
// Get available present modes
uint32_t presentModeCount;
VK_CHECK(fpGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, surface, &presentModeCount, NULL));
RK_GRAPHICS_ASSERT(presentModeCount > 0, "available present modes = 0");
Vec<VkPresentModeKHR> presentModes(presentModeCount);
VK_CHECK(fpGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, surface, &presentModeCount, presentModes.data()));
// Select a present mode for the swapchain
// The VK_PRESENT_MODE_FIFO_KHR mode must always be present as per spec
// This mode waits for the vertical blank ("v-sync")
VkPresentModeKHR swapchainPresentMode = VK_PRESENT_MODE_FIFO_KHR;
// If v-sync is not requested, try to find a mailbox mode
// It's the lowest latency non-tearing present mode available
if (!vsync)
{
for (size_t i = 0; i < presentModeCount; i++)
{
if (presentModes[i] == VK_PRESENT_MODE_MAILBOX_KHR)
{
swapchainPresentMode = VK_PRESENT_MODE_MAILBOX_KHR;
break;
}
if ((swapchainPresentMode != VK_PRESENT_MODE_MAILBOX_KHR) && (presentModes[i] == VK_PRESENT_MODE_IMMEDIATE_KHR))
{
swapchainPresentMode = VK_PRESENT_MODE_IMMEDIATE_KHR;
}
}
}
// Determine the number of images
uint32_t desiredNumberOfSwapchainImages = surfCaps.minImageCount + 1;
if ((surfCaps.maxImageCount > 0) && (desiredNumberOfSwapchainImages > surfCaps.maxImageCount))
{
desiredNumberOfSwapchainImages = surfCaps.maxImageCount;
}
// Find the transformation of the surface
VkSurfaceTransformFlagsKHR preTransform;
if (surfCaps.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR)
{
// We prefer a non-rotated transform
preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
}
else
{
preTransform = surfCaps.currentTransform;
}
// Find a supported composite alpha format (not all devices support alpha opaque)
VkCompositeAlphaFlagBitsKHR compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
// Simply select the first composite alpha format available
std::vector<VkCompositeAlphaFlagBitsKHR> compositeAlphaFlags = {
VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR,
VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR,
VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR,
};
for (auto& compositeAlphaFlag : compositeAlphaFlags) {
if (surfCaps.supportedCompositeAlpha & compositeAlphaFlag) {
compositeAlpha = compositeAlphaFlag;
break;
};
}
// Set Image Sharing Mode
QueueFamilyIndices indices = FindQueueFamilies(physicalDevice, surface);
std::set<uint32_t> uniqueQueueFamilyIndices = {
indices.graphicsFamily.value(),
indices.computeFamily.value(),
indices.presentFamily.value()
};
Vec<uint32_t> uniqueQueueFamilyIndicesVec;
for (auto indices : uniqueQueueFamilyIndices)
{
uniqueQueueFamilyIndicesVec.push_back(indices);
}
VkSharingMode sharingMode;
if (uniqueQueueFamilyIndices.size() > 1)
sharingMode = VK_SHARING_MODE_CONCURRENT;
else
sharingMode = VK_SHARING_MODE_EXCLUSIVE;
VkSwapchainCreateInfoKHR swapchainCI = {};
swapchainCI.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
swapchainCI.pNext = NULL;
swapchainCI.surface = surface;
swapchainCI.minImageCount = desiredNumberOfSwapchainImages;
swapchainCI.imageFormat = colorFormat;
swapchainCI.imageColorSpace = colorSpace;
swapchainCI.imageExtent = { extent.width, extent.height };
swapchainCI.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
swapchainCI.preTransform = (VkSurfaceTransformFlagBitsKHR)preTransform;
swapchainCI.imageArrayLayers = 1;
swapchainCI.imageSharingMode = sharingMode;
if (sharingMode == VK_SHARING_MODE_CONCURRENT)
{
swapchainCI.queueFamilyIndexCount = static_cast<uint32_t>(uniqueQueueFamilyIndices.size());
swapchainCI.pQueueFamilyIndices = uniqueQueueFamilyIndicesVec.data();
}
swapchainCI.queueFamilyIndexCount = 0;
swapchainCI.pQueueFamilyIndices = NULL;
swapchainCI.presentMode = swapchainPresentMode;
swapchainCI.oldSwapchain = oldSwapchain;
// Setting clipped to VK_TRUE allows the implementation to discard rendering outside of the surface area
swapchainCI.clipped = VK_TRUE;
swapchainCI.compositeAlpha = compositeAlpha;
// Set additional usage flag for blitting from the swapchain images if supported
VkFormatProperties formatProps;
vkGetPhysicalDeviceFormatProperties(physicalDevice, colorFormat, &formatProps);
if ((formatProps.optimalTilingFeatures & VK_FORMAT_FEATURE_TRANSFER_SRC_BIT_KHR) || (formatProps.optimalTilingFeatures & VK_FORMAT_FEATURE_BLIT_SRC_BIT)) {
swapchainCI.imageUsage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
}
VK_CHECK(fpCreateSwapchainKHR(device, &swapchainCI, nullptr, &swapChain));
// If an existing swap chain is re-created, destroy the old swap chain
// This also cleans up all the presentable images
if (oldSwapchain != VK_NULL_HANDLE)
{
for (uint32_t i = 0; i < imageCount; i++)
{
vkDestroyImageView(device, buffers[i].view, nullptr);
}
fpDestroySwapchainKHR(device, oldSwapchain, nullptr);
}
VK_CHECK(fpGetSwapchainImagesKHR(device, swapChain, &imageCount, NULL));
// Get the swap chain images
images.resize(imageCount);
VK_CHECK(fpGetSwapchainImagesKHR(device, swapChain, &imageCount, images.data()));
// Get the swap chain buffers containing the image and imageview
buffers.resize(imageCount);
for (uint32_t i = 0; i < imageCount; i++)
{
VkImageViewCreateInfo colorAttachmentView = {};
colorAttachmentView.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
colorAttachmentView.pNext = NULL;
colorAttachmentView.format = colorFormat;
colorAttachmentView.components = {
VK_COMPONENT_SWIZZLE_R,
VK_COMPONENT_SWIZZLE_G,
VK_COMPONENT_SWIZZLE_B,
VK_COMPONENT_SWIZZLE_A
};
colorAttachmentView.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
colorAttachmentView.subresourceRange.baseMipLevel = 0;
colorAttachmentView.subresourceRange.levelCount = 1;
colorAttachmentView.subresourceRange.baseArrayLayer = 0;
colorAttachmentView.subresourceRange.layerCount = 1;
colorAttachmentView.viewType = VK_IMAGE_VIEW_TYPE_2D;
colorAttachmentView.flags = 0;
buffers[i].image = images[i];
colorAttachmentView.image = buffers[i].image;
VK_CHECK(vkCreateImageView(device, &colorAttachmentView, nullptr, &buffers[i].view));
}
}
VkResult VulkanSwapChain::AcquireNextImage(VkSemaphore presentCompleteSemaphore, uint32_t* imageIndex)
{
if (swapChain == VK_NULL_HANDLE) {
// Probably acquireNextImage() is called just after cleanup() (e.g. window has been terminated on Android).
// todo : Use a dedicated error code.
return VK_ERROR_OUT_OF_DATE_KHR;
}
// By setting timeout to UINT64_MAX we will always wait until the next image has been acquired or an actual error is thrown
// With that we don't have to handle VK_NOT_READY
return fpAcquireNextImageKHR(device, swapChain, UINT64_MAX, presentCompleteSemaphore, (VkFence)nullptr, imageIndex);
}
VkResult VulkanSwapChain::QueuePresent(VkQueue queue, uint32_t imageIndex, VkSemaphore waitSemaphore)
{
VkPresentInfoKHR presentInfo = {};
presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
presentInfo.pNext = NULL;
presentInfo.swapchainCount = 1;
presentInfo.pSwapchains = &swapChain;
presentInfo.pImageIndices = &imageIndex;
// Check if a wait semaphore has been specified to wait for before presenting the image
if (waitSemaphore != VK_NULL_HANDLE)
{
presentInfo.pWaitSemaphores = &waitSemaphore;
presentInfo.waitSemaphoreCount = 1;
}
return fpQueuePresentKHR(queue, &presentInfo);
}
void VulkanSwapChain::Finalize()
{
if (swapChain != VK_NULL_HANDLE)
{
for (uint32_t i = 0; i < imageCount; i++)
{
vkDestroyImageView(device, buffers[i].view, nullptr);
}
}
if (swapChain != VK_NULL_HANDLE)
{
fpDestroySwapchainKHR(device, swapChain, nullptr);
}
swapChain = VK_NULL_HANDLE;
//if (surface != VK_NULL_HANDLE)
//{
// fpDestroySwapchainKHR(device, swapChain, nullptr);
// vkDestroySurfaceKHR(instance, surface, nullptr);
//}
//surface = VK_NULL_HANDLE;
}
|
/*
* vegetation.cpp
*
*
* Places vegetation objects on the terrain
* Created on: 30 Mar 2012
* Author: sash
*/
#include "terrain_generator.hpp"
#include <vector>
extern int crop_height;
extern int crop_width;
extern int** tmap;
extern int snow_level;
extern int sea_level;
extern int n_rivers;
extern RiverPoint** source_river_points;
int n_vegetation = DEFAULT_NO_OF_VEGETATION;
int root_radius = DEAFULT_ROOT_RADIUS;
int generations = DEAFULT_VEGETATION_GENERATIONS;
std::vector<int*> candidate_veg_location;
std::vector<int*> veg_location;
std::vector<int*> water_tile_location;
bool point_at_river_tile(int x, int y){
for (int i = 0; i < water_tile_location.size(); ++i) {
if(water_tile_location[i][0] == x && water_tile_location[i][1] == y) return true;
}
return false;
}
bool veg_candidate_constraint(int x, int y) {
bool result = true;
result = result && point_below_snow_top_level(x, y) && point_above_sealevel(x,y) && !point_at_river_tile(x,y);
//std::cout << "Snow level " << snowtop_level << "Sea level" << sea_level << " : " << tmap[y][x] << " " << result << std::endl;
return result;
}
void calculate_veg_candiates() {
for (int i = 0; i < crop_height; ++i) {
for (int j = 0; j < crop_width; ++j) {
if (veg_candidate_constraint(j, i)) {
int *point = new int[2];
point[0] = j;
point[1] = i;
candidate_veg_location.push_back(point);
}
}
}
}
int get_branch_id(RiverPoint* rp) {
do {
// std::cout << "Branch " << rp->x << "," << rp->y << " ~ " << x << ","
// << y << std::endl;
if (rp != 0)
return rp->river_id;
rp = rp->next;
} while (rp != 0);
return -1;
}
void calculate_water_tiles() {
for (int i = 0; i < n_rivers; ++i) {
RiverPoint *rp = source_river_points[i];
do {
if (rp != 0) {
int* loc = new int[2];
loc[0] = rp->x;
loc[1] = rp->y;
water_tile_location.push_back(loc);
//check branches
if (rp->branch != 0) {
int r = get_branch_id(rp->branch);
if (r > -1) {
int* loc = new int[2];
loc[0] = rp->x;
loc[1] = rp->y;
water_tile_location.push_back(loc);
}
}
rp = rp->next;
}
} while (rp != 0);
}
}
void populate_veg() {
for (int j = 0; j < n_vegetation; ++j) {
if (candidate_veg_location.empty())
return;
int i = rand() % candidate_veg_location.size();
int* loc = new int[2];
loc[0] = candidate_veg_location[i][0];
loc[1] = candidate_veg_location[i][1];
veg_location.push_back(loc);
candidate_veg_location.erase(candidate_veg_location.begin() + i);
}
}
bool veg_tile(int x, int y){
for (int i = 0; i < veg_location.size(); ++i) {
if(x== veg_location[i][0] && y== veg_location[i][1]) return true;
}
return false;
}
bool water_tile = false;
void refine_veg(){
std::vector<int*> remove_indeces;
std::vector<int*> add_points;
for (int i = 0; i < veg_location.size(); ++i) {
int x = veg_location[i][0];
int y = veg_location[i][1];
std::vector<int*> neighbours;
//fill neighbourhood
for (int j = y-root_radius; j < y+root_radius; ++j) {
if(j>=0 && j<crop_height){
for (int k = x-root_radius; k < x+root_radius; ++k) {
if(k>=0 && k<crop_width){
int* n = new int[2];
n[0] = k;
n[1] = j;
neighbours.push_back(n);
}
}
}
}
int veg_neighbous = 0;
int* point = new int[2];
bool water_present = false;
for (int j = 0; j < neighbours.size(); ++j) {
int nx = neighbours[j][0];
int ny = neighbours[j][1];
point[0] = nx;
point[1] = ny;
//get local veg count
if(veg_tile(nx,ny)) veg_neighbous++;
if(point_at_river_tile(nx,ny) || !point_above_sealevel(nx,ny)) water_present = true;
}
if(!water_present && veg_neighbous>=3){
remove_indeces.push_back(point);
} else if(veg_neighbous>=6){
remove_indeces.push_back(point);
}else{
for (int j = 0; j < neighbours.size(); ++j) {
int nx = neighbours[j][0];
int ny = neighbours[j][1];
int chance = neighbours.size()-j;
if (rand()%(chance)==0 &&
!veg_tile(nx, ny) && !point_at_river_tile(nx, ny)
&& point_above_sealevel(nx, ny) && nx != x && ny != y) {
point[0] = nx;
point[1] = ny;
add_points.push_back(point);
break;
}
}
}
}
for (int i = 0; i < remove_indeces.size(); ++i){
for(std::vector<int*>::iterator it = veg_location.begin(); it != veg_location.end(); ++it) {
if(((int*)*it)[0] == remove_indeces[i][0] && ((int*)*it)[1] == remove_indeces[i][1]){
veg_location.erase(it);
break;
}
}
}
remove_indeces.clear();
for (int i = 0; i < add_points.size(); ++i){
veg_location.push_back(add_points[i]);
}
add_points.clear();
}
void vegetation(bool verbose) {
//create a list of river tiles
calculate_water_tiles();
calculate_veg_candiates();
populate_veg();
for (int i = 0; i < generations; ++i) {
if(verbose)std::cout << "\tGen " << i << " pop "<< veg_location.size() << std::endl;
refine_veg();
}
}
void print_vegetation(FILE* stream) {
if (stream == 0) {
stream = fopen(DEAFULT_VEGETATION_FILE, "w");
}
if (stream == NULL)
perror("Error opening file");
else {
fprintf(stream, "<vegetation>\n");
for (int i = 0; i < veg_location.size(); ++i) {
int* loc = veg_location[i];
fprintf(stream, "<veg x = '%d' y = '%d'>"
"</veg>\n", loc[0], loc[1]);
}
fprintf(stream, "</vegetation>\n");
}
}
|
#include "mainwindow.hh"
#include "ui_mainwindow.h"
Mainwindow::Mainwindow(QWidget *parent) :QWidget(parent), ui(new Ui::Mainwindow){
ui->setupUi(this);
connect(ui->clear, SIGNAL(clicked()), this, SLOT(clear_clicked()));
connect(ui->km, SIGNAL(valueChanged(int)), this, SLOT(km_changed()));
}
Mainwindow::~Mainwindow(){
delete ui;
}
void Mainwindow::clear_clicked(){
ui->km->setValue(0);
ui->miles->display(0.0);
}
void Mainwindow::km_changed(){
ui->miles->display(ui->km->value()/1.609);
}
|
//算法:模拟
//将A-B=C转化为A-C=B
//这样可以在输入时顺便减去C,获得B
//最后统计B在原序列中 的出现次数即可
#include<cstdio>
#include<map>
using namespace std;
int n,c;
long long ans;
long long a[2000010];
map <long long,int> s;//map存出现次数
int main()
{
scanf("%d%d",&n,&c);
for(int i=1;i<=n;i++)
{
scanf("%lld",&a[i]);
s[a[i]]++;//记录次数
a[i]-=c;//减去,获得b
}
for(int i=1;i<=n;i++)//统计出现次数
ans+=s[a[i]];
printf("%lld",ans);
}
|
//
// Leaf.h
// GetFish
//
// Created by zhusu on 15/3/11.
//
//
#ifndef __GetFish__Leaf__
#define __GetFish__Leaf__
#include "cocos2d.h"
#include "Actor.h"
USING_NS_CC;
class Leaf : public Actor
{
public:
const static int DIR_LEFT = 0;
const static int DIR_RIGHT =1 ;
static Leaf* create(const char* name,int hp,int dir,float speedx,float speedy);
virtual bool init(const char* name,int hp,int dir,float speedx,float speedy);
Leaf();
virtual ~Leaf();
virtual void cycle(float delta);
void subHp();
int getHp() const;
private:
int _hp;
int _maxHp;
int _dir;
float _speedx;
float _speedy;
};
#endif /* defined(__GetFish__Leaf__) */
|
#include "Move.h"
Move::Move(Character* character, Node* move_node)
{
this->character = character;
vector<Node*> frame_nodes = move_node->getNodeByName("Frames")->getNodesByName("Frame");
for(int i=0;i<(int)frame_nodes.size();i++)
{
Frame* frame = new Frame(character, this, frame_nodes[i]);
this->frames.push_back(frame);
}
if(move_node->getNodeByName("Cancels"))
{
vector<Node*> cancel_nodes = move_node->getNodeByName("Cancels")->getNodesByName("Cancel");
for(int i=0;i<(int)cancel_nodes.size();i++)
{
this->cancels.push_back(cancel_nodes[i]->attributes["move"]);
}
}
if(move_node->getNodeByName("Inputs"))
{
vector<Node*> input_nodes = move_node->getNodeByName("Inputs")->getNodesByName("Input");
for(int i=0;i<(int)input_nodes.size();i++)
{
vector<Node*> button_nodes = input_nodes[0]->getNodesByName("Button");
vector<string> input;
for(int i=0;i<(int)button_nodes.size();i++)
{
input.push_back(button_nodes[i]->attributes["name"]);
}
inputs.push_back(input);
}
}
this->restart();
}
void Move::draw(int x, int y, bool flipped)
{
Frame* frame = frames[this->current_frame];
frame->draw(x, y, flipped);
}
void Move::logic()
{
tick++;
Frame* frame = frames[this->current_frame];
frame->logic();
if(frame->isFinished())
{
this->current_frame++;
if(current_frame>=(int)frames.size())
{
current_frame=0;
finished=true;
}
frame = frames[this->current_frame];
frame->restart();
frame->logic();
}
}
void Move::restart()
{
tick = 0;
current_frame = 0;
finished = false;
Frame* frame = frames[this->current_frame];
frame->restart();
}
bool Move::isFinished()
{
return finished;
}
bool Move::canCancel(string move)
{
for(int i=0; i<(int)cancels.size();i++)
{
if(cancels[i]==move)
return true;
}
return false;
}
bool Move::inputIsInBuffer()
{
for(int i=0;i<(int)inputs.size();i++)
{
list<string>::iterator current_move_button = character->input_buffer.begin();
bool input_found = true;
for(int j=0;j<(int)inputs[i].size();j++)
{
if(inputs[i][j].size()!=(*current_move_button).size())
{
input_found = false;
break;
}
for(int k=0;k<(int)inputs[i][j].size();k++)
{
if(inputs[i][j][k]=='*')
continue;
if(inputs[i][j][k]!=(*current_move_button)[k])
{
input_found = false;
break;
}
}
current_move_button++;
}
if(input_found)
return true;
}
return false;
}
Frame* Move::getCurrentFrame()
{
return frames[this->current_frame];
}
|
/**********************************************************
//
// Wih (Wireless Interface Hockey)
//
// main.cpp (ウィンドウメッセージの制御)
//
// Copyright (C) 2007,
// Masayuki Morita, Kazuki Hamada, Tatsuya Mori,
// All Rights Reserved.
**********************************************************/
#include <string.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include "resource.h"
#include "airhockey.h"
#include "msgqueue.h"
//前方宣言
//アプリケーション関係
BOOL InitApp(HINSTANCE hInst, WNDPROC WndProc, LPCTSTR szClassName);
BOOL InitInstance(HINSTANCE hInst, LPCSTR szClassName, int nCmdShow);
//プロシージャ
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp);
static LRESULT OnCreateProc(HWND hwnd , LPCREATESTRUCT lpcs);
static LRESULT OnDestroyProc(HWND hwnd);
static LRESULT OnPaintProc(HWND hwnd);
static LRESULT OnTimerProc(HWND hwnd, WPARAM wp);
static LRESULT OnKeydownProc(HWND hwnd,WPARAM wp);
//作業バッファ関係
void CreateBackBuf(HWND hwnd);
void DeleteBackBuf();
void PaintScreen(HDC hdc);
//その他
HFONT SetMyFont(HDC hdc, LPCTSTR face, int h);
void WaitUpdate(int msec);
bool ReadSettingFile(const char* file);
//global
static HDC g_BackBufDC;
static HBITMAP g_BackBufBMP;
static CAirHockey* g_pAirhockey;
HWND g_hwnd;
CMsgQueue* g_pMsgQueue;
SGameSetting g_game_setting;
//WinMain
int WINAPI WinMain(HINSTANCE hCurInst, HINSTANCE hPrevInst,
LPSTR lpsCmdLine, int nCmdShow)
{
MSG msg;
char szClassName[] = "Airhockey"; //ウィンドウクラス
if (!hPrevInst) {
if (!InitApp(hCurInst, WndProc, szClassName))
return FALSE;
}
if (!InitInstance(hCurInst, szClassName, nCmdShow)) {
return FALSE;
}
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int) msg.wParam;
}
//ウィンドウクラス登録
BOOL InitApp(HINSTANCE hInst, WNDPROC WndProc, LPCTSTR szClassName)
{
WNDCLASS wc;
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WndProc; //プロシージャ名
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInst; //インスタンス
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wc.lpszMenuName = NULL; //メニュー名
wc.lpszClassName = (LPCSTR)szClassName;
return (RegisterClass(&wc));
}
//ウィンドウの生成
BOOL InitInstance(HINSTANCE hInst, LPCSTR szClassName, int nCmdShow)
{
HWND hwnd;
hwnd = CreateWindow(szClassName,
"Wih (Wireless Interface Hockey)",//タイトルバー
WS_OVERLAPPEDWINDOW, //ウィンドウの種類
CW_USEDEFAULT, //X座標
CW_USEDEFAULT, //Y座標
PARENT_WIDTH+5, //幅
PARENT_HEIGHT+35, //高さ
NULL, //親ウィンドウのハンドル、親を作るときはNULL
NULL, //メニューハンドル、クラスメニューを使うときはNULL
hInst, //インスタンスハンドル
NULL);
if (!hwnd)
return FALSE;
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
return TRUE;
}
/////////////////////////////////////////////////////////
// ウィンドウプロシージャ
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
{
g_hwnd=hwnd;
switch (msg) {
case WM_PAINT:
return OnPaintProc(hwnd);
case WM_TIMER:
return OnTimerProc(hwnd,wp);
case WM_KEYDOWN:
return OnKeydownProc(hwnd,wp);
case WM_CREATE:
return OnCreateProc(hwnd,(LPCREATESTRUCT)lp);
case WM_DESTROY:
OnDestroyProc(hwnd);
default:
return (DefWindowProc(hwnd, msg, wp, lp));
}
return 0L;
}
//WM_CREATEハンドラ
//アプリケーション初期化
static LRESULT OnCreateProc(HWND hwnd , LPCREATESTRUCT lpcs)
{
//設定ファイルの読み込み
if(!ReadSettingFile(SETTING_FILE)){
char str[256];
sprintf(str,"設定ファイル%sが見つかりません",SETTING_FILE);
MessageBox(hwnd,str,"初期化エラー",MB_OK | MB_ICONERROR);
SendMessage(hwnd,WM_CLOSE,0,0);
return 2;
}
//作業用バッファの生成
CreateBackBuf(hwnd);
//メッセージボックスの作成
g_pMsgQueue=new CMsgQueue(hwnd,ID_TIMER_MSG,MSG_WIDTH,MSG_HEIGHT);
//ゲーム内部の初期化
g_pAirhockey=new CAirHockey();
if(g_pAirhockey==NULL) return 1;
if(!g_pAirhockey->init()){
MessageBox(hwnd,"初期化に失敗しました。入力デバイスを確認してください。","初期化エラー",MB_OK | MB_ICONERROR);
SendMessage(hwnd,WM_CLOSE,0,0);
return 2;
}
//タイマー作成
SetTimer(hwnd,ID_TIMER_UPDATE,g_game_setting.update_time_interval_,NULL);
//ゲーム開始
g_pAirhockey->start();
return 0;
}
//WM_DESTROYハンドラ
//アプリケーション終了
static LRESULT OnDestroyProc(HWND hwnd)
{
//ゲーム内部の後始末
if(g_pAirhockey!=NULL){
g_pAirhockey->cleanup();
delete g_pAirhockey;
}
//描画関係の後始末
DeleteBackBuf();
//タイマー
KillTimer(hwnd,ID_TIMER_UPDATE);
KillTimer(g_hwnd,ID_TIMER_WAIT);
KillTimer(g_hwnd,ID_TIMER_MSG);
delete g_pMsgQueue;
PostQuitMessage(0);
return 0;
}
//WM_PAINTハンドラ
//画面描画
static LRESULT OnPaintProc(HWND hwnd)
{
PAINTSTRUCT ps;
HDC wndDC;
wndDC = BeginPaint(hwnd,&ps);
if(g_pAirhockey!=NULL){
//描画処理
g_pAirhockey->draw(g_BackBufDC);
//メッセージがある場合は表示
if(g_pMsgQueue->exist()){
g_pMsgQueue->draw(g_BackBufDC);
}
//バッファを画面に出力
PaintScreen(wndDC);
}
EndPaint(hwnd,&ps);
return 0;
}
//WM_TIMERハンドラ
//タイマー呼び出しにより一定間隔ごとに実行
static LRESULT OnTimerProc(HWND hwnd,WPARAM wp)
{
if(g_pAirhockey==NULL) return 0;
switch(wp){
case ID_TIMER_UPDATE:
//ゲームのメインループ用タイマー
g_pAirhockey->update();
break;
case ID_TIMER_WAIT:
//ゲームを一定時間中断用
KillTimer(g_hwnd,ID_TIMER_WAIT);
g_pAirhockey->set_wait_flg(false);
if(g_pAirhockey->state()==CAirHockey::EState::game_countdown_start){
g_pAirhockey->set_state(CAirHockey::EState::game_play);
}
break;
case ID_TIMER_MSG:
//メッセージ用タイマー
g_pMsgQueue->timeout();
break;
default:
break;
}
InvalidateRect(hwnd,NULL,false);
return 0;
}
//WM_KEYDOWNハンドラ
//スペースによりゲーム開始
//ゲーム中はスペースで一時中断
static LRESULT OnKeydownProc(HWND hwnd,WPARAM wp){
switch(wp){
case VK_SPACE:
if((g_pAirhockey!=NULL) && (g_pAirhockey->state()!=CAirHockey::EState::init_ng)){
//関係ない状態のときのスペースは無視
if( !(g_pAirhockey->state()==CAirHockey::EState::game_play ||
g_pAirhockey->state()==CAirHockey::EState::game_end ||
g_pAirhockey->state()==CAirHockey::EState::init_ok)
)
break;
if(g_pAirhockey->wait_flg()){
//wait中
g_pMsgQueue->clear();
g_pAirhockey->set_wait_flg(false);
if(g_pAirhockey->state()==CAirHockey::EState::game_end){
//ゲーム終了後の場合はリセット
g_pAirhockey->reset();
}else if(g_pAirhockey->state()==CAirHockey::EState::init_ok){
//ゲーム開始or得点後の再開の場合はカウントダウンへ
g_pAirhockey->set_state(CAirHockey::EState::game_countdown_start);
}
}else{
//game中のウェイト要求
WaitUpdate(-1);
}
}
break;
}
InvalidateRect(hwnd,NULL,false);
return 0;
}
////////////////////////////////////////////////////////////
// 作業用バッファ関係
// ちらつきの抑制のため作業バッファ上で描画し、画面に転送
//生成
void CreateBackBuf(HWND hwnd)
{
HDC WndDC = GetWindowDC(hwnd);
g_BackBufDC = CreateCompatibleDC(WndDC); //作業用DCを取得
g_BackBufBMP= CreateCompatibleBitmap(WndDC,PARENT_WIDTH,PARENT_HEIGHT);
ReleaseDC(hwnd,WndDC);
SelectObject(g_BackBufDC,g_BackBufBMP);
}
//削除
void DeleteBackBuf()
{
DeleteDC(g_BackBufDC); //作業用DCを消去
DeleteObject(g_BackBufBMP); //読み込んだ画像も消去
}
//転送
void PaintScreen(HDC hdc)
{
BitBlt(hdc,0,0,PARENT_WIDTH,PARENT_HEIGHT,
g_BackBufDC,0,0,SRCCOPY); //転送
}
//フォント作成用
HFONT SetMyFont(HDC hdc, LPCTSTR face, int h)
{
HFONT hFont;
hFont = CreateFont(h, //フォント高さ
0, //文字幅
0, //テキストの角度
0, //ベースラインとx軸との角度
FW_REGULAR, //フォントの重さ(太さ)
FALSE, //イタリック体
FALSE, //アンダーライン
FALSE, //打ち消し線
SHIFTJIS_CHARSET, //文字セット
OUT_DEFAULT_PRECIS, //出力精度
CLIP_DEFAULT_PRECIS,//クリッピング精度
PROOF_QUALITY, //出力品質
FIXED_PITCH | FF_MODERN,//ピッチとファミリー
face); //書体名
return hFont;
}
//一定時間ウェイトする
//時間が-1の場合はスペース押すまで無期限ウェイト
void WaitUpdate(int msec){
g_pAirhockey->set_wait_flg(true);
if(msec!=-1){
SetTimer(g_hwnd,ID_TIMER_WAIT,msec,0);
}else{
//Space押すまで無期限ウェイト
g_pMsgQueue->push("Press SPACE",-1);
}
}
/////////////////////////////////////////////////////////////
// 設定ファイルの読み込み
//行読み飛ばしマクロ
#define MACRO_SKEP_LINE() std::getline(ifs,line,'\n')
#define MACRO_SKEP_COMMENT() do{std::getline(ifs,line,'\n');}while((line.c_str()[0])=='#')
//設定ファイルの読み込み
//設定ファイルはカレントディレクトリに置くこと
bool ReadSettingFile(const char* file){
std::ifstream ifs(file);
if(!ifs.is_open()){//ファイルオープン失敗
return false;
}else{//ファイルオープン成功
std::string line;
//設定データの読み込み
MACRO_SKEP_COMMENT();
g_game_setting.update_time_interval_=atoi(line.c_str());
MACRO_SKEP_COMMENT();
g_game_setting.puck_step_=atoi(line.c_str());
MACRO_SKEP_COMMENT();
g_game_setting.game_score_=atoi(line.c_str());
MACRO_SKEP_COMMENT();
g_game_setting.input_mode1_=atoi(line.c_str());
MACRO_SKEP_COMMENT();
g_game_setting.input_mode2_=atoi(line.c_str());
MACRO_SKEP_COMMENT();
g_game_setting.input_com_=atoi(line.c_str());
MACRO_SKEP_COMMENT();
g_game_setting.input_kando_=atof(line.c_str());
//ファイルを閉じる
ifs.close();
}
return true;
}
|
#include<bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
using ll = long long;
bool dont_have_seven (int x , int divisor){
while(x != 0){
if(x % divisor == 7)return false;
x /= divisor;
}
return true;
}
int main(){
int N;
cin >> N;
int ans = 0;
for(int i = 1; i <= N; i++){
if(dont_have_seven(i,10) && dont_have_seven(i,8))ans++;
}
cout << ans << endl;
}
//関数名わかりにくいからかえたほうがいいかも
|
#pragma once
#include "level.hpp"
#include "music.hpp"
#include "utility.hpp"
class Lagunita {
public:
void init();
void loop();
private:
void update();
void render();
bool canSave();
bool canLoad();
void save();
void load();
private:
enum class Menus : uint8_t { main, game, credits, help, lost };
enum class MainSelections : uint8_t { play, load, save, credits, help, audio };
uint8_t help_page = 0;
int16_t weed = 0;
Arduboy2Base arduboy;
Drawing drawing = {arduboy.sBuffer};
Tinyfont tinyfont = {arduboy.sBuffer, Arduboy2Base::width(), Arduboy2Base::height()};
Music music = {arduboy};
Level level = {arduboy, tinyfont, drawing};
Menus currentMenu = Menus::main;
MainSelections currentMainSelection = MainSelections::play;
};
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup" -*-
*
* Copyright (C) Opera Software ASA 2012
*
* @author Andreas Farre
*/
#ifndef ES_ALLOCATION_CONTEXT_H
#define ES_ALLOCATION_CONTEXT_H
#include "modules/ecmascript/carakan/src/vm/es_context.h"
class ES_Allocation_Context
: public ES_Context
{
public:
ES_Allocation_Context(ES_Runtime *runtime);
ES_Allocation_Context(ESRT_Data *rt_data);
~ES_Allocation_Context();
void SetHeap(ES_Heap *new_heap);
void Remove();
void MoveToHeap(ES_Heap *new_heap);
private:
ES_Allocation_Context *next;
};
#endif // ES_ALLOCATION_CONTEXT_H
|
/*
* mysql_head.h
* Copyright: 2018 Shanghai Yikun Electrical Engineering Co,Ltd
*/
#ifndef MYSQL_HEAD_H
#define MYSQL_HEAD_H
#include <iostream>
#include <ros/ros.h>
#include <mysql/mysql.h>
#include <string>
#include <vector>
#include <set>
#include <algorithm>
#include <map>
#include <time.h>
#include <ctime>
#define NORMALSIZE 255
/**
* @brief 延时
*/
static void _delay(int usec)
{
clock_t now = clock();
while(clock()-now < usec);
}
//从机状态
enum SlaveState{
UnKnown = -1,
ShutDown = 10,
Start = 11,
Mapping = 12,
Nav = 13,//idle
EmergencyStop = 14,
Error = 15,
Cancel = 16,
Pause = 21,
Executing = 22,
ManualControl = 23,
Aborted = 24,
Completed = 25,
Planning = 26,
Driving = 27
};
//小车状态
typedef struct runtimeinfo{
int state; //状态
float pos_x; //x轴坐标位置
float pos_y; //y轴的坐标位置
float theta; //z轴的旋转角度
float battery; //电量
float vel_x; //线速度
float vel_th; //角速度
std::string map_id; //当前正在使用的地图id
}RuntimeInfo;
//小车信息
typedef struct robot {
int id; //小车id
std::string hostname; //小车的主机名
std::string addr; //小车地址
std::string port; //小车端口号
double time_delay; //小车的往返时延
}Robot;
//小车信息
typedef struct robotsinfo {
int robot_id; //小车id
double timestamp; //时间戳
RuntimeInfo info; //小车信息
}RobotsInfo;
static const std::string __INFO = "INFO";
static const std::string __WARN = "WARN";
static const std::string __ERROR = "ERROR";
static const std::string __FATAL = "FATAL";
#endif // MYSQL_HEAD_H
|
#ifndef WALI_UTIL_BASE64_INCULDE
#define WALI_UTIL_BASE64_INCULDE
#include <string>
namespace wali {
namespace util {
std::string base64_encode(unsigned char const* , size_t len);
std::string base64_decode(std::string const& s);
}
}
#endif
|
#ifndef _HEXAPI_H
#define _HEXAPI_H
#include "ros/ros.h"
#include <tf2/LinearMath/Vector3.h>
/**
* This class represents the high level concept of the functions Hexapi and perform,
* such as movement, surveillance. (All in the LH Frame with Z pointing up and X pointing forward)
* Supports:
* 1. Initial boot up (standing position)
* 2. Adjusting body based on commands
*/
#define Z_MAX 6
#define Z_MIN 4.5
class Hexapi {
public:
Hexapi(const ros::NodeHandle &nh);
Hexapi();
~Hexapi();
void init();
void move(tf2::Vector3 vel);
tf2::Vector3 move(tf2::Vector3 current, tf2::Vector3 vel, float dt);
void setActTime(ros::Time time_to_set);
const tf2::Vector3 getBodyCenter();
void setBodyCenter(const tf2::Vector3 body_center);
private:
ros::Time time_prev_act_;
tf2::Vector3 body_center_;
// Constants taken from the param server
double length_leg_lower_hor_;
double length_leg_lower_vert_;
double z_min_;
double z_max_;
bool is_initialized_ = false;
};
#endif
|
//https://www.patest.cn/contests/gplt/L2-017
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<vector>
#include<set>
#include<map>
#include<algorithm>
using namespace std;
int main(){
//input
int n;
cin>>n;
vector<int> input;
for(int i=0;i<n;++i){
int temp;
cin>>temp;
input.push_back(temp);
}
//deal with
sort(input.begin(),input.end());
int number_one = input.size()/2;
int number_two = input.size() - number_one;
int sum_one = 0;
int sum_two = 0;
for(int i=0;i<number_one;++i){
sum_one += input[i];
}
for(int i=number_one;i<input.size();++i){
sum_two += input[i];
}
//output
cout<<"Outgoing #: "<<number_two<<endl;
cout<<"Introverted #: "<<number_one<<endl;
cout<<"Diff = "<<sum_two-sum_one;
return 0;
}
|
// -*- LSST-C++ -*-
/*
* LSST Data Management System
* Copyright 2014-2015 AURA/LSST.
*
* This product includes software developed by the
* LSST Project (http://www.lsst.org/).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the LSST License Statement and
* the GNU General Public License along with this program. If not,
* see <http://www.lsstcorp.org/LegalNotices/>.
*/
/**
* @file
*
* @brief QueryRequest. XrdSsiRequest impl for czar query dispatch
*
* @author Daniel L. Wang, SLAC
*/
// Class header
#include "qdisp/QueryRequest.h"
// System headers
#include <cstddef>
#include <iostream>
// LSST headers
#include "lsst/log/Log.h"
// Qserv headers
#include "qdisp/JobStatus.h"
#include "qdisp/ResponseHandler.h"
#include "util/common.h"
namespace lsst {
namespace qserv {
namespace qdisp {
////////////////////////////////////////////////////////////////////////
// QueryRequest
////////////////////////////////////////////////////////////////////////
QueryRequest::QueryRequest( XrdSsiSession* session, std::shared_ptr<JobQuery> const& jobQuery) :
_session(session), _jobQuery(jobQuery), _jobDesc(_jobQuery->getDescription()),
_jobId(jobQuery->getId()) {
LOGF_INFO("New QueryRequest with payload(%1%)" % _jobDesc.payload().size());
LOGF_DEBUG("QueryRequest JQ_jobId=%1%" % _jobId);
}
QueryRequest::~QueryRequest() {
LOGF_DEBUG("~QueryRequest JQ_jobId=%1%)" % _jobId);
if(_session) {
if(_session->Unprovision()) {
LOGF_DEBUG("Unprovision ok.");
} else {
LOGF_ERROR("Error unprovisioning");
}
}
}
// content of request data
char* QueryRequest::GetRequest(int& requestLength) {
requestLength = _jobDesc.payload().size();
LOGF_DEBUG("Requesting, payload size: [%1%]" % requestLength);
// Andy promises that his code won't corrupt it.
return const_cast<char*>(_jobDesc.payload().data());
}
// Deleting the buffer (payload) would cause us problems, as this class is not the owner.
void QueryRequest::RelRequestBuffer() {
LOGF_DEBUG("RelRequestBuffer");
}
// precondition: rInfo.rType != isNone
// Must not throw exceptions: calling thread cannot trap them.
// Callback function for XrdSsiRequest.
// See QueryResource::ProvisionDone which invokes ProcessRequest(QueryRequest*))
bool QueryRequest::ProcessResponse(XrdSsiRespInfo const& rInfo, bool isOk) {
std::string errorDesc;
if(isCancelled()) {
cancel(); // calls _errorFinish()
return true;
}
if(!isOk) {
_jobDesc.respHandler()->errorFlush(std::string("Request failed"), -1);
_jobQuery->getStatus()->updateInfo(JobStatus::RESPONSE_ERROR);
_errorFinish();
return true;
}
switch(rInfo.rType) {
case XrdSsiRespInfo::isNone: // All responses are non-null right now
errorDesc += "Unexpected XrdSsiRespInfo.rType == isNone";
break;
case XrdSsiRespInfo::isData: // Local-only
errorDesc += "Unexpected XrdSsiRespInfo.rType == isData";
break;
case XrdSsiRespInfo::isError: // isOk == true
_jobQuery->getStatus()->updateInfo(JobStatus::RESPONSE_ERROR, rInfo.eNum, std::string(rInfo.eMsg));
return _importError(std::string(rInfo.eMsg), rInfo.eNum);
case XrdSsiRespInfo::isFile: // Local-only
errorDesc += "Unexpected XrdSsiRespInfo.rType == isFile";
break;
case XrdSsiRespInfo::isStream: // All remote requests
_jobQuery->getStatus()->updateInfo(JobStatus::RESPONSE_READY);
return _importStream();
default:
errorDesc += "Out of range XrdSsiRespInfo.rType";
}
return _importError(errorDesc, -1);
}
/// Retrieve and process results in using the XrdSsi stream mechanism
bool QueryRequest::_importStream() {
bool success = false;
// Pass ResponseHandler's buffer directly.
std::vector<char>& buffer = _jobDesc.respHandler()->nextBuffer();
LOGF_DEBUG("QueryRequest::_importStream buffer.size=%1%" % buffer.size());
const void* pbuf = (void*)(&buffer[0]);
LOGF_DEBUG("_importStream->GetResponseData size=%1% %2% %3%" %
buffer.size() % pbuf % util::prettyCharList(buffer, 5));
success = GetResponseData(&buffer[0], buffer.size());
LOGF_DEBUG("Initiated request %1%" % (success ? "ok" : "err"));
if(!success) {
_jobQuery->getStatus()->updateInfo(JobStatus::RESPONSE_DATA_ERROR);
if (Finished()) {
_jobQuery->getStatus()->updateInfo(JobStatus::RESPONSE_DATA_ERROR_OK);
} else {
_jobQuery->getStatus()->updateInfo(JobStatus::RESPONSE_DATA_ERROR_CORRUPT);
}
_errorFinish();
return false;
} else {
return true;
}
}
/// Process an incoming error.
bool QueryRequest::_importError(std::string const& msg, int code) {
_jobDesc.respHandler()->errorFlush(msg, code);
_errorFinish();
return true;
}
void QueryRequest::ProcessResponseData(char *buff, int blen, bool last) { // Step 7
LOGF_INFO("ProcessResponseData with buflen=%1% %2%" % blen % (last ? "(last)" : "(more)"));
if(blen < 0) { // error, check errinfo object.
int eCode;
const char* chs = eInfo.Get(eCode);
std::string reason = (chs == nullptr) ? "nullptr" : chs;
_jobQuery->getStatus()->updateInfo(JobStatus::RESPONSE_DATA_NACK, eCode, reason);
LOGF_ERROR("ProcessResponse[data] error(%1%,\"%2%\")" % eCode % reason);
_jobDesc.respHandler()->errorFlush("Couldn't retrieve response data:" + reason, eCode);
_errorFinish();
return;
}
_jobQuery->getStatus()->updateInfo(JobStatus::RESPONSE_DATA);
bool flushOk = _jobDesc.respHandler()->flush(blen, last);
if(flushOk) {
if (last) {
auto sz = _jobDesc.respHandler()->nextBuffer().size();
if (last && sz != 0) {
LOGF_WARN("Connection closed when more information expected sz=%1%" % sz);
}
_jobQuery->getStatus()->updateInfo(JobStatus::COMPLETE);
_finish();
} else {
std::vector<char>& buffer = _jobDesc.respHandler()->nextBuffer();
const void* pbuf = (void*)(&buffer[0]);
LOGF_INFO("_importStream->GetResponseData size=%1% %2% %3%" %
buffer.size() % pbuf % util::prettyCharList(buffer, 5));
if(!GetResponseData(&buffer[0], buffer.size())) {
_errorFinish();
return;
}
}
} else {
LOGF_INFO("ProcessResponse data flush failed");
ResponseHandler::Error err = _jobDesc.respHandler()->getError();
_jobQuery->getStatus()->updateInfo(JobStatus::MERGE_ERROR, err.getCode(), err.getMsg());
// @todo DM-2378 Take a closer look at what causes this error and take
// appropriate action. There could be cases where this is recoverable.
_retried.store(true); // Do not retry
_errorFinish();
}
}
void QueryRequest::cancel() {
{
std::lock_guard<std::mutex> lock(_finishStatusMutex);
if(_cancelled) {
return; // Don't do anything if already cancelled.
}
_cancelled = true;
_retried.store(true); // Prevent retries.
}
_jobQuery->getStatus()->updateInfo(JobStatus::CANCEL);
_errorFinish(true);
}
bool QueryRequest::isCancelled() {
std::lock_guard<std::mutex> lock(_finishStatusMutex);
return _cancelled;
}
void QueryRequest::cleanup() {
_jobQuery.reset();
_keepAlive.reset();
}
/// Finalize under error conditions and retry or report completion
/// This function will destroy this object.
void QueryRequest::_errorFinish(bool shouldCancel) {
LOGF_DEBUG("Error finish");
{
std::lock_guard<std::mutex> lock(_finishStatusMutex);
if (_finishStatus != ACTIVE) {
return;
}
_finishStatus = ERROR;
bool ok = Finished(shouldCancel);
if(!ok) {
LOGF_ERROR("Error cleaning up QueryRequest");
} else {
LOGF_INFO("Request::Finished() with error (clean).");
}
}
// Make the calls outside of the mutex lock.
if (!_retried.exchange(true)) {
// There's a slight race condition here. _jobQuery::runJob() creates a
// new QueryResource object which is used to create a new QueryRequest object
// which will replace this one in _jobQuery. The replacement could show up
// before this one's cleanup is called, so this will keep this alive.
_keepAlive = _jobQuery->getQueryRequest(); // shared pointer to this
if (_jobQuery->runJob()) {
// Retry failed, nothing left to try.
_callMarkComplete(false);
}
} else {
_callMarkComplete(false);
}
cleanup(); // Reset smart pointers so this object can be deleted.
}
/// Finalize under success conditions and report completion.
void QueryRequest::_finish() {
{
std::lock_guard<std::mutex> lock(_finishStatusMutex);
if (_finishStatus != ACTIVE) {
return;
}
_finishStatus = FINISHED;
bool ok = Finished();
if(!ok) {
LOGF_ERROR("Error with Finished()");
} else {
LOGF_INFO("Finished() ok.");
}
}
_callMarkComplete(true);
cleanup();
}
/// Inform the Executive that this query completed, and
// Call MarkCompleteFunc only once.
void QueryRequest::_callMarkComplete(bool success) {
if (!_calledMarkComplete.exchange(true)) {
_jobQuery->getMarkCompleteFunc()->operator ()(success);
}
}
std::ostream& operator<<(std::ostream& os, QueryRequest const& r) {
return os;
}
}}} // lsst::qserv::qdisp
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser.
** It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#include "modules/search_engine/log/Log.h"
#ifdef SEARCH_ENGINE
#include "modules/pi/OpSystemInfo.h"
#include "modules/search_engine/log/FileLogger.h"
#ifdef QUICK
// used for MoveLogFile
#include "adjunct/desktop_util/opfile/desktop_opfile.h"
#endif
OutputLogDevice *SearchEngineLog::CreateLog(int device, ...)
{
va_list args;
const uni_char *fname;
OpFileFolder folder;
FileLogger *flogger;
switch (device & 255)
{
case SearchEngineLog::File:
case SearchEngineLog::FolderFile:
{
if ((flogger = OP_NEW(FileLogger, ((device & SearchEngineLog::LogOnce) != 0))) == NULL)
return NULL;
va_start(args, device);
fname = va_arg(args, const uni_char *);
if ((device & 255) == SearchEngineLog::FolderFile)
folder = (OpFileFolder)va_arg(args, int);
else
folder = OPFILE_ABSOLUTE_FOLDER;
va_end(args);
if (OpStatus::IsError(flogger->Open((device & SearchEngineLog::FOverwrite) != 0, fname, folder)))
{
OP_DELETE(flogger);
return NULL;
}
return flogger;
}
}
return NULL;
}
#ifdef QUICK
#define MoveLogFile DesktopOpFileUtils::Move
#else
OP_STATUS MoveLogFile(OpFile *old_location, OpFile *new_location)
{
OP_STATUS err;
err = new_location->CopyContents(old_location, TRUE);
if (OpStatus::IsError(err))
return err;
old_location->Delete();
return OpStatus::OK;
}
#endif
static const uni_char *MkFName(OpString &fname, const uni_char *base, int num)
{
if (OpStatus::IsError(fname.Set(base)))
return NULL;
if (num <= 0)
return fname.CStr();
if (OpStatus::IsError(fname.AppendFormat(UNI_L(".%i"), num)))
return NULL;
return fname.CStr();
}
OP_STATUS SearchEngineLog::ShiftLogFile(int max_files, const uni_char *filename, OpFileFolder folder)
{
OpString logfname;
OpFile f, mf;
int i;
BOOL exists;
if (logfname.Reserve((int)uni_strlen(filename) + 5) == NULL)
return OpStatus::ERR_NO_MEMORY;
i = max_files;
RETURN_IF_ERROR(f.Construct(MkFName(logfname, filename, i), folder));
if (OpStatus::IsError(f.Exists(exists)))
exists = TRUE; // try to delete it anyway
while (exists && i <= 100)
{
RETURN_IF_ERROR(f.Delete());
++i;
RETURN_IF_ERROR(f.Construct(MkFName(logfname, filename, i), folder));
if (OpStatus::IsError(f.Exists(exists)))
exists = FALSE; // to avoid infinite loop
}
i = max_files - 1;
while (i >= 0)
{
RETURN_IF_ERROR(f.Construct(MkFName(logfname, filename, i), folder));
RETURN_IF_ERROR(f.Exists(exists));
if (exists)
{
RETURN_IF_ERROR(mf.Construct(MkFName(logfname, filename, i + 1), folder));
RETURN_IF_ERROR(MoveLogFile(&f, &mf));
}
--i;
}
return OpStatus::OK;
}
InputLogDevice *SearchEngineLog::OpenLog(const uni_char *filename, OpFileFolder folder)
{
InputLogDevice *ld;
if ((ld = OP_NEW(InputLogDevice, ())) == NULL)
return NULL;
if (OpStatus::IsError(ld->Construct(filename, folder)))
{
OP_DELETE(ld);
return NULL;
}
return ld;
}
int OutputLogDevice::Hash(const char *data, int size)
{
const char *endp = data + size;
int hash = 0;
while (data < endp)
{
hash = ((hash << 5) + hash) + *data++; // hash*33 + c
}
return hash;
}
const char *SearchEngineLog::SeverityStr(int severity)
{
int i = 0;
if (!severity)
return "";
while (severity != 1)
{
severity = ((unsigned)severity) >> 1;
++i;
}
switch (i)
{
case 0:
return "D";
case 1:
return "I";
case 2:
return "N";
case 3:
return "W";
case 4:
return "C";
case 5:
return "A";
case 6:
return "E";
}
return "";
}
OP_BOOLEAN OutputLogDevice::MakeLine(OpString8 &dst, int severity, const char *id, const char *format, va_list args)
{
int hash;
time_t current_time;
struct tm *loc_time;
double msec;
OpString8 fmt;
msec = g_op_time_info->GetWallClockMS();
op_time(¤t_time);
msec -= (unsigned long)(msec / 1000.0) * 1000.0;
loc_time = op_localtime(¤t_time);
RETURN_IF_ERROR(fmt.AppendFormat("%.04i-%.02i-%.02iT%.02i:%.02i:%.02i.%.03i %s [%s] %s\r\n",
loc_time->tm_year + 1900, loc_time->tm_mon + 1, loc_time->tm_mday,
loc_time->tm_hour, loc_time->tm_min, loc_time->tm_sec, (int)(msec + 0.5),
SearchEngineLog::SeverityStr(severity),
id == NULL ? "" : id,
format));
RETURN_IF_ERROR(dst.AppendVFormat(fmt.CStr(), args));
if (!m_once)
return OpBoolean::IS_TRUE;
hash = Hash(dst.CStr() + 24, dst.Length() - 26);
if (hash == m_hash)
return OpBoolean::IS_FALSE;
m_hash = hash;
return OpBoolean::IS_TRUE;
}
OP_BOOLEAN OutputLogDevice::MakeLine(OpString8 &dst, int severity, const char *id, const uni_char *format, va_list args)
{
int hash;
time_t current_time;
struct tm *loc_time;
double msec;
OpString sev_str, id_str, udst, fmt;
msec = g_op_time_info->GetWallClockMS();
op_time(¤t_time);
msec -= (unsigned long)(msec / 1000.0) * 1000.0;
loc_time = op_localtime(¤t_time);
RETURN_IF_ERROR(sev_str.Set(SearchEngineLog::SeverityStr(severity)));
RETURN_IF_ERROR(id_str.Set(id));
RETURN_IF_ERROR(fmt.AppendFormat(UNI_L("%.04i-%.02i-%.02iT%.02i:%.02i:%.02i.%.03i %s [%s] %s\r\n"),
loc_time->tm_year + 1900, loc_time->tm_mon + 1, loc_time->tm_mday,
loc_time->tm_hour, loc_time->tm_min, loc_time->tm_sec, (int)(msec + 0.5),
sev_str.CStr(),
id_str.CStr() == NULL ? UNI_L("") : id_str.CStr(),
format));
RETURN_IF_ERROR(udst.AppendVFormat(fmt.CStr(), args));
RETURN_IF_ERROR(dst.SetUTF8FromUTF16(udst.CStr()));
if (!m_once)
return OpBoolean::IS_TRUE;
hash = Hash(dst.CStr() + 24, dst.Length() - 26);
if (hash == m_hash)
return OpBoolean::IS_FALSE;
m_hash = hash;
return OpBoolean::IS_TRUE;
}
OP_STATUS OutputLogDevice::MakeBLine(OpString8 &dst, int severity, const char *id)
{
time_t current_time;
struct tm *loc_time;
double msec;
OpString8 str_size;
msec = g_op_time_info->GetWallClockMS();
op_time(¤t_time);
msec -= (unsigned long)(msec / 1000.0) * 1000.0;
loc_time = op_localtime(¤t_time);
return dst.AppendFormat("%.04i-%.02i-%.02iT%.02i:%.02i:%.02i.%.03i %s [%s]\\\r\n",
loc_time->tm_year + 1900, loc_time->tm_mon + 1, loc_time->tm_mday,
loc_time->tm_hour, loc_time->tm_min, loc_time->tm_sec, (int)(msec + 0.5),
SearchEngineLog::SeverityStr(severity),
id == NULL ? "" : id);
}
void OutputLogDevice::Write(int severity, const char *id, const char *format, ...)
{
va_list args;
if ((severity & m_mask) == 0)
return;
va_start(args, format);
VWrite(severity, id, format, args);
va_end(args);
}
void OutputLogDevice::Write(int severity, const char *id, const uni_char *format, ...)
{
va_list args;
if ((severity & m_mask) == 0)
return;
va_start(args, format);
VWrite(severity, id, format, args);
va_end(args);
}
#include "modules/zlib/zlib.h"
InputLogDevice::InputLogDevice(void)
{
m_time = 0;
m_severity = (SearchEngineLog::Severity)0;
m_binary = FALSE;
m_size = 0;
m_compressed_size = 0;
m_data = NULL;
}
InputLogDevice::~InputLogDevice(void)
{
m_file.Close();
OP_DELETEA(m_data);
}
OP_STATUS InputLogDevice::Construct(const uni_char *filename, OpFileFolder folder)
{
RETURN_IF_ERROR(m_file.Construct(filename, folder));
return m_file.Open(OPFILE_READ);
}
BOOL InputLogDevice::End(void)
{
OpFileLength pos, size;
if (!m_file.IsOpen())
return TRUE;
if (!m_binary || m_compressed_size == 0)
{
if (m_file.Eof())
return TRUE;
if (OpStatus::IsError(m_file.GetFilePos(pos)))
return TRUE;
if (OpStatus::IsError(m_file.GetFileLength(size)))
return TRUE;
return pos >= size;
}
if (OpStatus::IsError(m_file.GetFilePos(pos)))
return TRUE;
if (OpStatus::IsError(m_file.GetFileLength(size)))
return TRUE;
return pos + m_compressed_size + 2 >= size;
}
OP_BOOLEAN InputLogDevice::Read(void)
{
char *s, *e;
struct tm iso_time;
time_t sec_time;
int i;
char chr_length[8]; /* ARRAY OK 2010-09-24 roarl */
OpFileLength pos;
if (m_data != NULL)
{
OP_DELETEA(m_data);
m_data = NULL;
}
else if (m_binary)
{
RETURN_IF_ERROR(m_file.GetFilePos(pos));
RETURN_IF_ERROR(m_file.SetFilePos(pos + m_compressed_size + 2));
}
m_size = 0;
m_compressed_size = 0;
m_umessage.Empty();
if (!m_file.IsOpen() || m_file.Eof())
return OpBoolean::IS_FALSE;
RETURN_IF_ERROR(m_file.ReadLine(m_message));
if (m_file.Eof())
return OpBoolean::IS_FALSE;
s = m_message.DataPtr();
// this would be unnecessary if OpFile/OpLowLevelFile wasn't buggy
e = s + op_strlen(s) - 1;
while ((*e == '\r' || *e == '\n') && e >= s)
{
*e = 0;
--e;
}
op_memset(&iso_time, 0, sizeof(iso_time));
e = s + 4;
if (*e != '-')
return OpStatus::ERR_PARSING_FAILED;
iso_time.tm_year = op_atoi(s) - 1900;
s = e + 1;
e = s + 2;
if (*e != '-')
return OpStatus::ERR_PARSING_FAILED;
iso_time.tm_mon = op_atoi(s) - 1;
s = e + 1;
e = s + 2;
if (*e != 'T')
return OpStatus::ERR_PARSING_FAILED;
iso_time.tm_mday = op_atoi(s);
s = e + 1;
e = s + 2;
if (*e != ':')
return OpStatus::ERR_PARSING_FAILED;
iso_time.tm_hour = op_atoi(s);
s = e + 1;
e = s + 2;
if (*e != ':')
return OpStatus::ERR_PARSING_FAILED;
iso_time.tm_min = op_atoi(s);
s = e + 1;
e = s + 2;
if (*e != '.')
return OpStatus::ERR_PARSING_FAILED;
iso_time.tm_sec = op_atoi(s);
s = e + 1;
e = s + 3;
if (*e != ' ')
return OpStatus::ERR_PARSING_FAILED;
if ((sec_time = op_mktime(&iso_time)) == (time_t)-1)
return OpStatus::ERR_PARSING_FAILED;
m_time = (double)sec_time;
m_time *= 1000.0;
m_time += op_atoi(s);
i = 0;
s = e + 1;
do
{
++i;
e = (char *)SearchEngineLog::SeverityStr(i);
if (*e == 0)
return OpStatus::ERR_PARSING_FAILED;
} while (op_strncmp(s, e, op_strlen(e)) != 0);
m_severity = (SearchEngineLog::Severity)i;
s += op_strlen(e) + 1;
if (*s != '[')
return OpStatus::ERR_PARSING_FAILED;
++s;
e = s;
while (*e != ']' && *e != 0)
++e;
if (*e != ']')
return OpStatus::ERR_PARSING_FAILED;
if (e == s)
m_id.Empty();
else
RETURN_IF_ERROR(m_id.Set(s, (int)(e - s)));
s = e + 1;
switch (*s)
{
case ' ':
m_binary = FALSE;
m_message.Delete(0, (int)(s - m_message.CStr() + 1));
break;
case '\\':
m_binary = TRUE;
m_message.Empty();
RETURN_IF_ERROR(m_file.Read(chr_length, 8, &pos));
if (pos != 8)
return OpStatus::ERR;
m_size = 0;
for (i = sizeof(m_size) - 1; i >= 0; --i)
{
m_size <<= 8;
m_size |= (unsigned char)chr_length[i];
}
m_compressed_size = 0;
RETURN_IF_ERROR(m_file.Read(chr_length, 8, &pos));
if (pos != 8)
return OpStatus::ERR;
for (i = sizeof(m_compressed_size) - 1; i >= 0; --i)
{
m_compressed_size <<= 8;
m_compressed_size |= (unsigned char)chr_length[i];
}
break;
default:
return OpStatus::ERR_PARSING_FAILED;
}
return OpBoolean::IS_TRUE;
}
const uni_char *InputLogDevice::UMessage(void)
{
if (OpStatus::IsError(m_umessage.SetFromUTF8(m_message.CStr())))
return NULL;
return m_umessage.CStr();
}
const void *InputLogDevice::Data(void)
{
OpString buf;
z_stream decompressor;
OpFileLength bytes_read;
if (m_data != NULL)
return m_data;
if (buf.Reserve((unsigned)m_compressed_size + 2) == NULL)
return NULL;
if ((m_data = OP_NEWA(char, (unsigned)m_size)) == NULL)
return NULL;
if (OpStatus::IsError(m_file.Read(buf.DataPtr(), m_compressed_size + 2, &bytes_read)) || bytes_read != m_compressed_size + 2)
{
OP_DELETEA(m_data);
m_data = NULL;
return NULL;
}
decompressor.zalloc = (alloc_func)0;
decompressor.zfree = (free_func)0;
decompressor.next_in = (unsigned char *)buf.DataPtr();
decompressor.avail_in = (unsigned)m_compressed_size;
decompressor.next_out = (unsigned char *)m_data;
decompressor.avail_out = (unsigned)m_size;
if (inflateInit(&decompressor) != 0)
return NULL;
inflate(&decompressor, Z_FINISH);
inflateEnd(&decompressor);
return m_data;
}
OP_STATUS InputLogDevice::SaveData(const uni_char *file_name, OpFileFolder folder)
{
OpString8 r_buf, w_buf; // using OpString as a kind of auto pointer
z_stream decompressor;
OpFileLength c_size, bytes_read;
OpFile f;
int r_size;
if (m_compressed_size == 0)
return OpStatus::ERR;
if (r_buf.Reserve(4096) == NULL)
return OpStatus::ERR_NO_MEMORY;
if (w_buf.Reserve(4096) == NULL)
return OpStatus::ERR_NO_MEMORY;
decompressor.zalloc = Z_NULL;
decompressor.zfree = Z_NULL;
decompressor.opaque = Z_NULL;
decompressor.avail_in = 0;
decompressor.next_in = Z_NULL;
if (inflateInit(&decompressor) != Z_OK)
return OpStatus::ERR;
RETURN_IF_ERROR(f.Construct(file_name, folder));
RETURN_IF_ERROR(f.Open(OPFILE_WRITE));
c_size = 0;
while (c_size < m_compressed_size)
{
r_size = (int)(c_size + r_buf.Capacity() < m_compressed_size ? r_buf.Capacity() : m_compressed_size - c_size);
RETURN_IF_ERROR(m_file.Read(r_buf.DataPtr(), r_size, &bytes_read));
if (bytes_read != static_cast<OpFileLength>(r_size))
return OpStatus::ERR;
c_size += r_size;
decompressor.avail_in = r_size;
decompressor.next_in = (unsigned char *)r_buf.DataPtr();
do {
decompressor.avail_out = w_buf.Capacity();
decompressor.next_out = (unsigned char *)w_buf.DataPtr();
inflate(&decompressor, Z_NO_FLUSH);
if (OpStatus::IsError(f.Write(w_buf.DataPtr(), w_buf.Capacity() - decompressor.avail_out)))
{
inflateEnd(&decompressor);
return OpStatus::ERR_NO_DISK;
}
} while (decompressor.avail_out == 0);
}
m_file.Read(&r_size, 2, &bytes_read); // skip \r\n
inflateEnd(&decompressor);
f.Close();
m_binary = FALSE;
return OpStatus::OK;
}
//#else // SEARCH_ENGINE
/*****************************************************************************/
/* this is used when logging is disabled */
/*****************************************************************************/
/*int OutputLogDevice::Hash(const char *data, int size)
{
return 0;
}
const char *OutputLogDevice::SeverityStr(int severity)
{
return NULL;
}
void OutputLogDevice::Write(int severity, const char *id, const char *format, ...)
{
}
void OutputLogDevice::Write(int severity, const char *id, const uni_char *format, ...)
{
}
class EmptyLogger : public OutputLogDevice
{
virtual ~EmptyLogger(void) {}
virtual void Write(SearchEngineLog::Severity severity, const char *id, const char *format, ...) {}
virtual void Write(SearchEngineLog::Severity severity, const char *id, const uni_char *format, ...) {}
virtual void Write(SearchEngineLog::Severity severity, const char *id, const void *data, int size) {}
};
OutputLogDevice *SearchEngineLog::CreateLog(Device device, ...)
{
return OP_NEW(EmptyLogger, ());
}
InputLogDevice *SearchEngineLog::OpenLog(const uni_char *filename, OpFileFolder)
{
return NULL;
}*/
#endif // SEARCH_ENGINE
|
/*
cin 通过 blank,\t,\n来确定字符串结束位置
*/
/*
cin.getline(arrname, N):最多读取N-1个字符到arrname中
cin.getline()读取整行,通过回车键输入的换行符确定输入结尾
RK: getline会将缓冲区的换行符直接读入结束输入!getline会读取换行符,但是会把它替换为空
试一下如果超出N-1输入
*/
/*
cin.get(arrname, N):类似getline,但是换行符将留在输入缓冲区!
cin.get(无参数):读取下一个字符,哪怕是换行符
留换行符的办法使得我们可以通过检查队列里第一个字符来确定cin是得到N-1个字符停止还是得到一行而停止
*/
#include <iostream>
int main()
{
using namespace std;
const int ArSize = 20;
char name[ArSize];
char dessert[ArSize];
cout << "When we use cin:" << endl;
cout << "Please enter your name:\n";
cin >> name;
cout << "Please enter your favorite dessert:\n";
cin >> dessert;
cout << "I have some delicious " << dessert << " for you, " << name << endl; // Ya ya,对name而言cin捕捉Ya,而把ya放在输入队列,被dessert捕捉到。
cin.sync(); // 清空输入缓存
cout << "When we use getline:" << endl;
cout << "Please enter your name:\n";
cin.getline(name, ArSize);
cout << "Please enter your favorite dessert:\n";
cin.getline(dessert, ArSize);
cout << "I have some delicious " << dessert << " for you, " << name << endl;
cin.sync();
cout << "When we use get:" << endl;
cout << "Please enter your name:\n";
cin.get(name, ArSize);
cout << "Please enter your favorite dessert:\n";
cin.get(); // tricky one
cin.get(dessert, ArSize);
cout << "I have some delicious " << dessert << " for you, " << name << endl;
return 0;
}
|
#include <bits/stdc++.h>
using namespace std;
struct UnionFind {
vector<int> par;
UnionFind(int n) : par(n, -1) {}
void init(int n) {par.assign(n, -1);}
int root(int x){
if(par[x] < 0) return x;
else return par[x] = root(par[x]);
}
bool same(int x, int y){
return (root(x) == root(y));
}
bool merge(int x, int y){
x = root(x);
y = root(y);
if(x == y) return false;
if(par[x] > par[y]) swap(x, y);
par[x] += par[y];
par[y] = x;
return true;
}
int size(int x){
return -par[root(x)];
}
};
int Loop_Node[10000];
int main(){
int N, M;
cin >> N >> M;
UnionFind uf(N);
for(int i=0; i<M; i++){
int u, v;
cin >> u >> v;
//閉路を記録
if(uf.root(u) == uf.root(v)) Loop_Node[u] = -1;
uf.merge(u, v);
}
set<int> Invalid, root;
for(int i=1; i<=N; i++){
if(Loop_Node[i] == -1) Invalid.insert(uf.root(i));
root.insert(uf.root(i));
}
int ans = root.size() - Invalid.size();
cout << ans << endl;
return 0;
}
|
//fibanocci series using recursion
#include<iostream>
using namespace std;
void fibanocci(int n)
{
static int n1=0, n2=1,sum;
if(n>0)
{
sum=n1+n2;
cout<<sum<<" ";
n1=n2;
n2=sum;
fibanocci(n-1);
}
}
int main(){
int n;
cout<<"Enter no.of elements: ";
cin>>n;
cout<<"0 "<<"1 ";
fibanocci(n-2);
}
|
#include <bits/stdc++.h>
using namespace std;
void solve() {
int n, m, r, c;
cin >> n >> m >> r >> c; --r; --c;
vector<vector<int>> mat(n, vector<int>(m));
for (auto& row: mat)
for (auto &i: row) cin >> i;
for (int i = 0; i < n; ++i) {
if (i == r) continue;
for (int j = 0; j < m; ++j) {
if (j == c) continue;
cout << mat[i][j] << " ";
}
cout << "\n";
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int t = 1;
//cin >> t;
while (t--) {
solve();
}
}
|
//
// 155. Min Stack.cpp
// leetcode
//
// Created by Xujian CHEN on 5/24/20.
// Copyright © 2020 Xujian CHEN. All rights reserved.
//
/*
155. Min Stack
Easy
3156
304
Add to List
Share
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
getMin() -- Retrieve the minimum element in the stack.
Example 1:
Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
Output
[null,null,null,null,-3,null,0,-2]
Explanation
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top(); // return 0
minStack.getMin(); // return -2
Constraints:
Methods pop, top and getMin operations will always be called on non-empty stacks.
Accepted
529,240
Submissions
1,214,581
*/
#include <iostream>
#include <vector>
using namespace std;
class MinStack {
vector<int> data;
vector<int> mins;
//int m;
public:
/** initialize your data structure here. */
MinStack() {
mins.push_back(INT_MAX);
//m = INT_MAX;
}
void push(int x) {
/*
if(m>x){
m = x;
cout<<m<<endl;
}
mins.push_back(m);
*/
if (mins.back()>x){
mins.push_back(x);
}else{
mins.push_back(mins.back());
}
data.push_back(x);
}
void pop() {
data.pop_back();
mins.pop_back();
}
int top() {
return data.back();
}
int getMin() {
return mins.back();
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(x);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/
int main(){
MinStack* obj = new MinStack();
int a;
obj->push(2147483646);
obj->push(2147483646);
obj->push(21474836467);
a = obj->top();
cout<<a<<endl;
obj->pop();
a = obj->getMin();
cout<<a<<endl;
obj->pop();
a = obj->getMin();
cout<<a<<endl;
obj->pop();
obj->push(21474836467);
a = obj->top();
cout<<a<<endl;
a = obj->getMin();
cout<<a<<endl;
obj->push(-21474836468);
a = obj->top();
cout<<a<<endl;
a = obj->getMin();
cout<<a<<endl;
obj->pop();
a = obj->getMin();
cout<<a<<endl;
return 0;
}
|
#ifndef SERVO_SUPPLY_H
#define SERVO_SUPPLY_H
#include "bluetooth.h"
class supply : public Bluetooth {
public:
void supplySetup(); //inizializza i pin ultilizzati per l'alimentazione
float getVoltage(); //funzione che legge e restituisce la tensione di una sola cella della batteria LiPo
byte getDutyCicle(); //funzione che in base alla tensione della batteria restituisce il valore del duty cicle fra 0 e 255
void pwmMos(); //funzione che gestisce il mosfet in pwm a 62500Hz (valore dutyCicle in ingresso deve essere compreso fra 0 e 255)
private:
#define batteryPin A1
#define mosPin 3 //pin 3 obbligatorio per l'uso del Timer2
#define lipoCells 2 //numero di celle della batteria LiPo (min 2)
#define batteryVpin A5 // pin virtuale di Blynk al quale è connesso il display level
#define supplyValue 6 //voltaggio voluto per l'alimentazione
int voltage;
int scaledVoltage;
float battVoltage;
float dutyCicle;
byte scaled_dutyCicle;
};
#endif
|
#pragma once
#include "PhysicsInclude.h"
#include "Physics.h"
void Physics::GetClosestTwoSegments(const Vector3 &segmentPointA0, const Vector3 &segmentPointA1,
const Vector3 &segmentPointB0, const Vector3 &segmentPointB1,
Vector3 &closestPointA, Vector3 &closestPointB)
{
Vector3 v1 = segmentPointA1 - segmentPointA0;
Vector3 v2 = segmentPointB1 - segmentPointB0;
Vector3 r = segmentPointA0 - segmentPointB0;
float a = dot(v1, v1);
float b = dot(v1, v2);
float c = dot(v2, v2);
float d = dot(v1, r);
float e = dot(v2, r);
float det = -a*c + b*b;
float s = 0.0f, t = 0.0f;
// 逆行列の存在をチェック
if (det*det > EPSILON) {
s = (c*d - b*e) / det;
}
// 線分A上の最近接点を決めるパラメータsを0.0〜1.0でクランプ
s = CLAMP(s, 0.0f, 1.0f);
// 線分Bのtを求める
//t = dot((segmentPointA0+s*v1) - segmentPointB0,v2) / dot(v2,v2);
t = (e + s*b) / c;
// 線分B上の最近接点を決めるパラメータtを0.0〜1.0でクランプ
t = CLAMP(t, 0.0f, 1.0f);
// 再度、線分A上の点を求める
//s = dot((segmentPointB0+t*v2) - segmentPointA0,v1) / dot(v1,v1);
s = (-d + t*b) / a;
s = CLAMP(s, 0.0f, 1.0f);
closestPointA = segmentPointA0 + s * v1;
closestPointB = segmentPointB0 + t * v2;
}
inline
void GetClosestPointLine(const Vector3 &point,const Vector3 &linePoint,const Vector3 &lineDirection,Vector3 &closestPoint)
{
float s = dot(point - linePoint, lineDirection) / dot(lineDirection, lineDirection);
closestPoint = linePoint + s * lineDirection;
}
void Physics::GetClosestPointTriangle(const Vector3 &point,
const Vector3 &trianglePoint0, const Vector3 &trianglePoint1,const Vector3 &trianglePoint2,
const Vector3 &triangleNormal,Vector3 &closestPoint)
{
// 3角形面上の投影点
Vector3 proj = point - dot(triangleNormal, point - trianglePoint0) * triangleNormal;
// エッジP0,P1のボロノイ領域
Vector3 edgeP01 = trianglePoint1 - trianglePoint0;
Vector3 edgeP01_normal = cross(edgeP01, triangleNormal);
float voronoiEdgeP01_check1 = dot(proj - trianglePoint0, edgeP01_normal);
float voronoiEdgeP01_check2 = dot(proj - trianglePoint0, edgeP01);
float voronoiEdgeP01_check3 = dot(proj - trianglePoint1, -edgeP01);
if (voronoiEdgeP01_check1 > 0.0f && voronoiEdgeP01_check2 > 0.0f && voronoiEdgeP01_check3 > 0.0f) {
GetClosestPointLine(trianglePoint0, edgeP01, proj, closestPoint);
return;
}
// エッジP1,P2のボロノイ領域
Vector3 edgeP12 = trianglePoint2 - trianglePoint1;
Vector3 edgeP12_normal = cross(edgeP12, triangleNormal);
float voronoiEdgeP12_check1 = dot(proj - trianglePoint1, edgeP12_normal);
float voronoiEdgeP12_check2 = dot(proj - trianglePoint1, edgeP12);
float voronoiEdgeP12_check3 = dot(proj - trianglePoint2, -edgeP12);
if (voronoiEdgeP12_check1 > 0.0f && voronoiEdgeP12_check2 > 0.0f && voronoiEdgeP12_check3 > 0.0f) {
GetClosestPointLine(trianglePoint1, edgeP12, proj, closestPoint);
return;
}
// エッジP2,P0のボロノイ領域
Vector3 edgeP20 = trianglePoint0 - trianglePoint2;
Vector3 edgeP20_normal = cross(edgeP20, triangleNormal);
float voronoiEdgeP20_check1 = dot(proj - trianglePoint2, edgeP20_normal);
float voronoiEdgeP20_check2 = dot(proj - trianglePoint2, edgeP20);
float voronoiEdgeP20_check3 = dot(proj - trianglePoint0, -edgeP20);
if (voronoiEdgeP20_check1 > 0.0f && voronoiEdgeP20_check2 > 0.0f && voronoiEdgeP20_check3 > 0.0f) {
GetClosestPointLine(trianglePoint2, edgeP20, proj, closestPoint);
return;
}
// 3角形面の内側
if (voronoiEdgeP01_check1 <= 0.0f && voronoiEdgeP12_check1 <= 0.0f && voronoiEdgeP20_check1 <= 0.0f) {
closestPoint = proj;
return;
}
// 頂点P0のボロノイ領域
if (voronoiEdgeP01_check2 <= 0.0f && voronoiEdgeP20_check3 <= 0.0f) {
closestPoint = trianglePoint0;
return;
}
// 頂点P1のボロノイ領域
if (voronoiEdgeP01_check3 <= 0.0f && voronoiEdgeP12_check2 <= 0.0f) {
closestPoint = trianglePoint1;
return;
}
// 頂点P2のボロノイ領域
if (voronoiEdgeP20_check2 <= 0.0f && voronoiEdgeP12_check3 <= 0.0f) {
closestPoint = trianglePoint2;
return;
}
}
|
#include "XDemux.h"
#include <iostream>
using namespace std;
extern "C"
{
#include "libavcodec/avcodec.h"
#include "libavutil/avutil.h"
#include "libavformat/avformat.h"
}
#pragma comment(lib, "avformat.lib")
#pragma comment(lib, "avcodec.lib")
#pragma comment(lib, "avutil.lib")
static double r2d(AVRational r)
{
return r.den == 0 ? 0 : (double)r.num / (double)r.den;
}
XDemux::XDemux()
{
videoStreamId = 0;
audioStreamId = 0;
m_nWidth = 0;
m_nHeight = 0;
Init();
}
XDemux::~XDemux()
{
}
bool XDemux::Init()
{
static bool isFirst = true;
if (!isFirst)
return false;
//初始化FFMPEG 调用了这个才能正常适用编码器和解码器
av_register_all();
//初始化网络参数
avformat_network_init();
//设置部分参数
//设置rtsp流以tcp协议打开
av_dict_set(&opt, "rtsp_transport", "tcp", 0);
//网络延迟时间设置
av_dict_set(&opt, "max_delay", "500", 0);
isFirst = false;
}
bool XDemux::Open(const char* url)
{
//打开之前先关闭系统
Close();
int ret = avformat_open_input(&pCtx, url,
0, //表示自动寻找解码器
&opt);
if (ret != 0)
{
char buf[1024] = { 0 };
av_strerror(ret, buf, sizeof(buf)-1);
return false;
}
//获取流信息
ret = avformat_find_stream_info(pCtx, NULL);
m_totalMs = pCtx->duration / (AV_TIME_BASE / 1000);
//获得视频流Index
videoStreamId = av_find_best_stream(pCtx, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0);
//打印视频流信息
av_dump_format(pCtx, videoStreamId, url, NULL);
//获得视频流指针
AVStream *vs = pCtx->streams[videoStreamId];
//流信息中的解码器参数
m_nWidth = vs->codecpar->width;
m_nHeight = vs->codecpar->height;
cout << "==================================================================" << endl;
cout << "视频信息" << videoStreamId << endl;
cout << "code_id = " << vs->codecpar->codec_id << endl;
cout << "format = " << vs->codecpar->format << endl;
cout << "width = " << m_nWidth << endl;
cout << "height = " << m_nHeight << endl;
cout << "video fps = " << r2d(vs->avg_frame_rate) << endl;
cout << "video 格式 = " << pCtx->iformat->long_name << endl;
//获取音频流信息
audioStreamId = av_find_best_stream(pCtx, AVMEDIA_TYPE_AUDIO, -1, -1, NULL, 0);
AVStream *as = pCtx->streams[audioStreamId];
m_nSampleRate = as->codecpar->sample_rate;
m_nChannels = as->codecpar->channels;
cout << "==================================================================" << endl;
cout << "音频信息" << audioStreamId << endl;
cout << "code_id=" << as->codecpar->codec_id << endl;
cout << "format=" << as->codecpar->format << endl;
cout << "sampleRate = " << m_nSampleRate << endl;
cout << "channels = " << m_nChannels << endl;
cout << "frame_size = " << as->codecpar->frame_size << endl;
return true;
}
void XDemux::Close()
{
if (!pCtx)
return;
avformat_close_input(&pCtx);
m_nWidth = 0;
m_nHeight = 0;
m_nSampleRate = 0;
m_totalMs = 0;
m_nChannels = 0;
}
//清空读取缓存
void XDemux::Clear()
{
if (!pCtx)
return;
avformat_flush(pCtx);
}
bool XDemux::Seek(double pos)
{
if (!pCtx)
return false;
Clear();
long long seekPos = 0;
seekPos = pCtx->streams[videoStreamId]->duration*pos;
int ret = av_seek_frame(pCtx, videoStreamId, seekPos, 0);
if (ret != 0)
{
char buf[1024] = { 0 };
av_strerror(ret, buf, sizeof(buf) - 1);
return false;
}
return true;
}
AVCodecParameters* XDemux::CopyVParam()
{
if (!pCtx)
{
return false;
}
//参数复制进行空间初始化申请
AVCodecParameters *params = avcodec_parameters_alloc();
avcodec_parameters_copy(params, pCtx->streams[videoStreamId]->codecpar);
return params;
}
AVCodecParameters* XDemux::CopyAParam()
{
if (!pCtx)
{
return false;
}
//参数复制进行空间初始化申请
AVCodecParameters *params = avcodec_parameters_alloc();
avcodec_parameters_copy(params, pCtx->streams[audioStreamId]->codecpar);
return params;
}
bool XDemux::IsAudio(AVPacket* pkt)
{
if (!pkt)
return false;
//
if (pkt->stream_index == audioStreamId)
return true;
return false;
}
AVPacket* XDemux::ReadVideoPkt()
{
if (!pCtx)
return NULL;
AVPacket* pkt = NULL;
long millsec = 0;
while (true)
{
pkt = Read();
if (!pkt)
break;
if (pkt->stream_index != videoStreamId)
break;
if(millsec++ > 100)
break;
av_packet_free(&pkt);
}
return pkt;
}
//读取每一帧视频包
AVPacket* XDemux::Read()
{
if (!pCtx)
return NULL;
//初始化空间
AVPacket* pkt = av_packet_alloc();
int ret = av_read_frame(pCtx, pkt);
if (ret != 0)
{
char buf[1024] = { 0 };
av_strerror(ret, buf, sizeof(buf) - 1);
av_packet_free(&pkt);
return NULL;
}
//将Pkt的dts转换毫秒
pkt->dts = pkt->dts * (1000 * r2d(pCtx->streams[videoStreamId]->time_base));
pkt->pts = pkt->pts * (1000 * r2d(pCtx->streams[videoStreamId]->time_base));
return pkt;
}
|
/*
2016年5月1日14:27:17
#1141 : 二分·归并排序之逆序对
时间限制:10000ms
单点时限:1000ms
内存限制:256MB
描述
在上一回、上上回以及上上上回里我们知道Nettle在玩《艦これ》。经过了一番苦战之后,Nettle又获得了的很多很多的船。
这一天Nettle在检查自己的舰队列表:
我们可以看到,船默认排序是以等级为参数。但实际上一个船的火力值和等级的关系并不大,所以会存在A船比B船等级高,但是A船火力却低于B船这样的情况。比如上图中77级的飞龙改二火力就小于55级的夕立改二。
现在Nettle将按照等级高低的顺序给出所有船的火力值,请你计算出一共有多少对船满足上面提到的这种情况。
提示:火力高才是猛!
拿到这道题目,可以很容易想到两重For循环枚举,复杂度为O(N^2),对于1000ms的时限来说显然会TLE。
既然是分治专题,这题必然和分治相关咯?
没错。这道题需要用到的是长期被我们忽略的归并排序。
我们来看一个归并排序的过程:
给定的数组为[2, 4, 5, 3, 1],二分后的数组分别为[2, 4, 5], [1, 3],假设我们已经完成了子过程,现在进行到该数组的“并”操作:
a: [2, 4, 5] b: [1, 3] result:[1] 选取b数组的1
a: [2, 4, 5] b: [3] result:[1, 2] 选取a数组的2
a: [4, 5] b: [3] result:[1, 2, 3] 选取b数组的3
a: [4, 5] b: [] result:[1, 2, 3, 4] 选取a数组的4
a: [5] b: [] result:[1, 2, 3, 4, 5] 选取a数组的5
在执行[2, 4, 5]和[1, 3]合并的时候我们可以发现,当我们将a数组的元素k放入result数组时,result中存在的b数组的元素一定比k小。
在原数组中,b数组中的元素位置一定在k之后,也就是说k和这些元素均构成了逆序对。
那么在放入a数组中的元素时,我们通过计算result中b数组的元素个数,就可以计算出对于k来说,b数组中满足逆序对的个数。
又因为递归的过程中,a数组中和k满足逆序对的数也计算过。则在该次递归结束时,[2, 4, 5, 3, 1]中所有k的逆序对个数也就都统计了。
同理对于a中其他的元素也同样有这样的性质。
由于每一次的归并过程都有着同样的情况,则我们可以很容易推断出:
若将每一次合并过程中得到的逆序对个数都加起来,即可得到原数组中所有逆序对的总数。
即在一次归并排序中计算出了所有逆序对的个数,时间复杂度为O(NlogN)
另外,逆序对的计算还有一种同样O(NlogN)的算法,使用的是树状数组,有兴趣的话可以自行搜索一下资料。
输入
第1行:1个整数N。N表示舰船数量, 1≤N≤100,000
第2行:N个整数,第i个数表示等级第i低的船的火力值a[i],1≤a[i]≤2^31-1。
输出
第1行:一个整数,表示有多少对船满足“A船比B船等级高,但是A船火力低于B船”。
样例输入10
1559614248 709366232 500801802 128741032 1669935692 1993231896 369000208 381379206 962247088 237855491
样例输出27
*/
#include <stdio.h>
#include <iostream>
#include <string>
#include <vector>
using std::string;
using std::vector;
using std::cout;
using std::cin;
using std::endl;
int a[100005];
int tmp[100005];
void Merge(int low, int mid, int high)
{
int leftPoint = low, rightPoint = mid;
int tmpPoint = low;
while (leftPoint < mid && rightPoint < high)
{
if (a[leftPoint] < a[rightPoint])
{
tmp[tmpPoint++] = a[leftPoint++];
}
else
{
tmp[tmpPoint++] = a[rightPoint++];
}
}
while (leftPoint < mid)
{
tmp[tmpPoint++] = a[leftPoint++];
}
while (rightPoint < high)
{
tmp[tmpPoint++] = a[rightPoint++];
}
for (int i = low; i < high; ++ i)
{
a[i] = tmp[i];
}
}
void MergeSort(int low, int high)//数组的下标范围为[low,high) , 总共high - low个元素
{
if (low == high || (low + 1) == high)
{
return;
}
int mid = (low + high) / 2;
//将数组分为[low, mid)和[mid, high),所以存在划分时low==mid的情况和low+1 == mid的情况,这两种情况都为终止情况;
MergeSort(low, mid);
MergeSort(mid, high);
Merge(low, mid, high);
}
int main()
{
freopen("../test.txt", "r", stdin);
int N = 0;
cin >> N;
for (int i = 0; i != N; ++ i)
{
cin >> a[i];
}
MergeSort(0, N);
for (int i = 0; i != N; ++i)
{
cout << a[i] << endl;
}
}
|
#include <bits/stdc++.h>
#define loop(i,s,e) for(int i = s;i<=e;i++) //including end point
#define pb(a) push_back(a)
#define sqr(x) ((x)*(x))
#define CIN ios_base::sync_with_stdio(0); cin.tie(0);
#define ll long long
#define ull unsigned long long
#define SZ(a) int(a.size())
#define read() freopen("input.txt", "r", stdin)
#define write() freopen("output.txt", "w", stdout)
#define ms(a,b) memset(a, b, sizeof(a))
#define all(v) v.begin(), v.end()
#define PI acos(-1.0)
#define pf printf
#define sfi(a) scanf("%d",&a);
#define sfii(a,b) scanf("%d %d",&a,&b);
#define sfl(a) scanf("%lld",&a);
#define sfll(a,b) scanf("%lld %lld",&a,&b);
#define sful(a) scanf("%llu",&a);
#define sfulul(a,b) scanf("%llu %llu",&a,&b);
#define sful2(a,b) scanf("%llu %llu",&a,&b); // A little different
#define sfc(a) scanf("%c",&a);
#define sfs(a) scanf("%s",a);
#define getl(s) getline(cin,s);
#define mp make_pair
#define paii pair<int, int>
#define padd pair<dd, dd>
#define pall pair<ll, ll>
#define vi vector<int>
#define vll vector<ll>
#define mii map<int,int>
#define mlli map<ll,int>
#define mib map<int,bool>
#define fs first
#define sc second
#define CASE(t) printf("Case %d: ",++t) // t initialized 0
#define cCASE(t) cout<<"Case "<<++t<<": ";
#define D(v,status) cout<<status<<" "<<v<<endl;
#define INF 1000000000 //10e9
#define EPS 1e-9
#define flc fflush(stdout); //For interactive programs , flush while using pf (that's why __c )
#define CONTEST 1
using namespace std;
//Bit Manipulation
bool Check_ON(int mask,int pos) //Check if pos th bit (from right) of mask is ON
{
if( (mask & (1<<pos) ) == 0 )return false;
return true;
}
int SET(int mask,int pos) //Save the returned mask into some var //Turn on pos th bit in mask
{
return (mask | (1<<pos));
}
int RESET(int mask,int pos) //Save the returned mask into some var //Turn off pos th bit in mask
{
return (mask & ~(1<<pos));
}
int FLIP(int mask,int pos) //Save the returned mask into some var //Toggle/Flip pos th bit in mask
{
return (mask ^ (1<<pos));
}
int LSB(int mask) // The actual LSB mask
{
return (mask & (-mask));
}
int LSB_pos(int mask) // 0 based position
{
int mask_2 = (mask & (-mask));
for(int pos = 0; pos<=15; pos++)
{
if(Check_ON(mask_2,pos))
return pos;
}
return -1;//
}
int ON_Bits(int mask)
{
return __builtin_popcount(mask);
}
inline int clz(int N) // O(1) way to calculate log2(X) (int s only)
{
return N ? 32 - __builtin_clz(N) : -INF;
}
ll arr[100005];
ll cx[100005];
struct node
{
multiset<ll>cumxor;
};
node tree[4*100005];
struct node2
{
bool updated;
ll val;
node2()
{
updated = false;
val = 0;
}
};
node2 tree2[400005];
void build(int root,int b,int e)
{
if(b==e)
{
tree[root].cumxor.insert(cx[b]);
return;
}
int lefc = root*2;
int righc = lefc+1;
int mid = (b+e)/2;
build(lefc,b,mid);
build(righc,mid+1,e);
tree[root].cumxor.insert(tree[lefc].cumxor.begin(),tree[lefc].cumxor.end());
tree[root].cumxor.insert(tree[righc].cumxor.begin(),tree[righc].cumxor.end());
}
ll query_o(int root,int b,int e,int i)
{
if(b>i || e<i)
return 0;
if(b==e && b==i)
{
multiset<ll>::iterator it =
tree[root].cumxor.begin();
return (ll)(*it);
}
int lefc = root*2;
int righc = lefc+1;
int mid = (b+e)/2;
ll q1 = query_o(lefc,b,mid,i);
ll q2 = query_o(righc,mid+1,e,i);
return (q1^q2);
}
int query(int root,int b,int e,int i,ll x)
{
if(b>i)
{
return 0;
}
if(e<=i)
{
auto lo = lower_bound(tree[root].cumxor.begin(),tree[root].cumxor.end(),x);
auto hi = upper_bound(tree[root].cumxor.begin(),tree[root].cumxor.end(),x);
int diff = hi - lo;
if(diff>=0)
return diff;
else
return 0;
}
int lefc = root*2;
int righc = lefc+1;
int mid = (b+e)/2;
int p1 = query(lefc,b,mid,i,x);
int p2 = query(righc,mid+1,e,i,x);
return p1+p2;
}
void update(int root,int b,int e,int i,ll x)
{
if(b>i || e<i)
{
return;
}
if(b==e && b==i)
{
if(!tree2[root].updated)
{
tree2[root].val = arr[i]^x;
}
else
{
tree2[root].val^=x;
}
return;
}
int lefc = root*2;
int righc = lefc+1;
int mid = (b+e)/2;
update(lefc,b,mid,i,x);
update(righc,mid+1,e,i,x);
tree2[root].val = tree2[lefc].val^tree2[righc].val;
}
ll query2(int root,int b,int e,int i)
{
if(b>i)
return 0;
if(e<=i)
{
return tree2[root].val;
}
int lefc = root*2;
int righc = lefc+1;
int mid = (b+e)/2;
ll p1 = query2(lefc,b,mid,i);
ll p2 = query2(righc,mid+1,e,i);
return p1^p2;
}
//1-320,321-640,....
int main()
{
int n,q;
sfii(n,q);
ll xv = 0;
for(int i=1; i<=n; i++)
{
sfl(arr[i]);
xv = xv^arr[i];
cx[i] = xv;
}
build(1,1,n);
while(q--)
{
int cmd;
sfi(cmd);
if(cmd==1)
{
int i;
ll x;
sfi(i);
sfl(x);
//update tree
ll prevx = arr[i];
prevx ^= x;
arr[i] = x;
ll pntq = query_o(1,1,n,i);
update(1,1,n,i,pntq,x);
}
else
{
int i;
sfi(i);
ll k;
sfl(k);
//query
ll nx = query2(1,1,n,i);
k ^= nx;
//new query
int qans = query(1,1,n,i,k);
pf("%d\n",qans);
}
}
return 0;
}
|
#include "Survey.h"
#include "NonGamingStudent.h"
// Constructor
Survey::Survey(int participants) {
numOfStudents = participants;
this->participants = new Person*[numOfStudents];
// This sets all of the values to 0 so they can be incremented properly
numOfGamers = 0;
averageAgeGamer = 0;
averageHoursGaming = 0;
numOfNonGamers = 0;
averageAgeNonGamer = 0;
averageHoursEntertainment = 0;
for (int x = 0; x < 13; x++)
favouriteServicePos[x] = 0;
for (int x = 0; x < 8; x++)
favouriteDevicePos[x] = 0;
}
void Survey::addParticipant(int spot, Student* student) {
participants[spot] = student;
}
void Survey::processData() {
for (int x = 0; x < numOfStudents; x++) {
// Checks to see if the student is a gamer or not and increment appropriate variables accordingly
if (static_cast<Student*>(participants[x])->getGamer()) {
numOfGamers++;
averageAgeGamer += participants[x]->getAge();
averageHoursGaming += static_cast<GamingStudent*>(participants[x])->getGamerHours();
++favouriteDevicePos[static_cast<GamingStudent*>(participants[x])->getPositionOfDevice()];
}
else
{
numOfNonGamers++;
averageAgeNonGamer += participants[x]->getAge();
averageHoursEntertainment += static_cast<NonGamingStudent*>(participants[x])->getStreamHours();
++favouriteServicePos[static_cast<NonGamingStudent*>(participants[x])->getPositionOfService()];
}
}
if (numOfGamers != 0) {
averageAgeGamer /= numOfGamers;
averageHoursGaming /= numOfGamers;
}
else {
averageAgeGamer = 0;
averageHoursGaming = 0;
}
if (numOfNonGamers != 0) {
averageAgeNonGamer /= numOfNonGamers;
averageHoursEntertainment /= numOfNonGamers;
}
else {
averageAgeNonGamer = 0;
averageHoursEntertainment = 0;
}
int mostPopular = 0; // This is a temp variable to compare the amount of votes for a specific console/streaming service
int votes = 0; // This will hold the number of votes for a specific console/service
// This will determine the most popular console
for (int x = 0; x < 8; x++)
{
if (votes < favouriteDevicePos[x]) {
votes = favouriteDevicePos[x];
mostPopular = x;
}
}
favouriteDevice = (new GamingStudent)->getListOfDevices(mostPopular);
mostPopular = 0;
votes = 0;
// This will determine the most popular streaming service
for (int x = 0; x < 13; x++)
{
if (votes < favouriteServicePos[x]) {
votes = favouriteServicePos[x];
mostPopular = x;
}
}
favouriteService = (new NonGamingStudent)->getListOfServices(mostPopular);
}
// getters
int Survey::getNumOfStudents() { return numOfStudents; }
int Survey::getNumOfNonGamers() { return numOfNonGamers; }
double Survey::getAverageAgeNonGamer() { return averageAgeGamer; }
double Survey::getAverageHoursEntertainment() { return averageHoursEntertainment; }
std::string Survey::getFavouriteService() { return favouriteService; }
int Survey::getNumOfGamers() { return numOfGamers; }
double Survey::getAverageAgeGamer() { return averageAgeNonGamer; }
double Survey::getAverageHoursGaming() { return averageHoursGaming; }
std::string Survey::getFavouriteDevice() { return favouriteDevice; }
std::string Survey::getName(int spot) { return participants[spot]->getName(); }
Student* Survey::getStudent(int spot) { return static_cast<Student*>(participants[spot]); }
std::ostream& operator<<(std::ostream& out, Survey survey)
{
int spaces = 0;
// SURVEY SAYS:
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 13);
out << " ____________________________________________________________" << std::endl;
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 13);
out << " || ";
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 11);
out << " SURVEY SAYS:";
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 13);
out << " ||" << std::endl;
// Divider
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 13); // Purple
out << " ||========================================================||" << std::endl;
// Number of Participants in survey
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 13); // Purple
out << " ||";
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 11); // Cyan
out << " Number of participants in the survey";
out << std::setw(18) << std::setfill(' ');
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN); // Orange
out << survey.getNumOfStudents();
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 13);
out << " ||" << std::endl;
// Divider
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 13);
out << " ||•--•--•--•--•--•--•--•--•--•--•--•--•--•--•--•--•--•--•-||" << std::endl;
// Number of gaming students
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 13);
out << " ||";
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 11);
out << " Number of gaming students ";
out << std::setw(28) << std::setfill(' ');
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN);
out << survey.getNumOfGamers();
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 13);
out << " ||" << std::endl;
// Average Gamer age
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 13);
out << " ||";
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 11);
out << " Average age ";
out << std::setw(42) << std::setfill(' ');
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN);
out << survey.getAverageAgeGamer();
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 13);
out << " ||" << std::endl;
// Favourite gaming console
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 13);
out << " || ";
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 11);
out << "Favourite gaming console";
out << std::setw(30) << std::setfill(' ');
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN);
out << survey.getFavouriteDevice();
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 13);
out << " ||" << std::endl;
// Average number of hours spent gaming
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 13);
out << " ||";
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 11);
out << " Average number of hours spent gaming ";
out << std::setw(17) << std::setfill(' ');
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN);
out << survey.getAverageHoursGaming();
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 13);
out << " ||" << std::endl;
// Divider
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 13);
out << " ||-•--•--•--•--•--•--•--•--•--•--•--•--•--•--•--•--•--•--•||" << std::endl;
// Number of non-gaming students
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 13);
out << " ||";
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 11);
out << " Number of non-gaming students ";
out << std::setw(24) << std::setfill(' ');
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN);
out << survey.getNumOfNonGamers();
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 13);
out << " ||" << std::endl;
// Average Nongamer age
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 13);
out << " ||";
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 11);
out << " Average age ";
out << std::setw(42) << std::setfill(' ');
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN);
out << survey.getAverageAgeNonGamer();
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 13);
out << " ||" << std::endl;
// Favourite streaming service
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 13);
out << " ||";
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 11);
out << " Favourite streaming service";
out << std::setw(27) << std::setfill(' ');
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN);
out << survey.getFavouriteService();
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 13);
out << " ||" << std::endl;
// Average number of hours spent
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 13);
out << " || ";
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 11);
out << "Average number of hours spent";
out << std::setw(25) << std::setfill(' ');
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN);
out << survey.getAverageHoursEntertainment();
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 13);
out << " ||" << std::endl;
// Divider
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 13);
out << " |==========================================================|" << std::endl;
return out;
}
|
#pragma once
#include "CoreMinimal.h"
#include "Engine/DataTable.h"
#include "Enum/CharacterClassType.h"
#include "CharacterClassInfo.generated.h"
USTRUCT(BlueprintType)
struct ARPG_API FCharacterClassInfo :
public FTableRowBase
{
GENERATED_USTRUCT_BODY()
public:
// 캐릭터 클래스를 나타냅니다.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "클래스")
ECharacterClassType ClassType;
// 기본으로 장착되는 장비 아이템 코드들을 나타냅니다.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "기타")
TArray<FName> DefaultEquipItemCodes;
};
|
#define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
#include "octonav/OctoGraph.hpp"
#include "octonav/visualize.hpp"
using namespace std;
using namespace octomap;
TEST_CASE("Tunnel neighbors", "[graph]")
{
OcTree tree(1);
OctoGraphSparse graph(tree);
for (int x = 0; x < 3; x++)
{
tree.updateNode(point3d(x, 0, 0), true); //left
tree.updateNode(point3d(x, 2, 0), true); // right
tree.updateNode(point3d(x, 1, 1), true); // top
tree.updateNode(point3d(x, 1, -1), true); // botton
tree.updateNode(point3d(x, 1, 0), false); // center is free
}
optional<OctoNode> start_option = coordToEndnode(tree, point3d(1, 1, 0)).value();
REQUIRE(start_option.has_value());
OctoNode start = start_option.value();
REQUIRE(start.depth == 16);
auto n = graph.neighbors(start);
REQUIRE(n.size() == 2);
//REQUIRE(count(n.begin(), n.end(), OctoNode(OcTreeKey(start.key[0] + 1, start.key[1], start.key[2]), 16)) == 1);
//REQUIRE(count(n.begin(), n.end(), OctoNode(OcTreeKey(start.key[0] - 1, start.key[1], start.key[2]), 16)) == 1);
}
|
/**************************************************************************************
* File Name : DataReader.hpp
* Project Name : Keyboard Warriors
* Primary Author : JeongHak Kim
* Secondary Author :
* Copyright Information :
* "All content 2019 DigiPen (USA) Corporation, all rights reserved."
**************************************************************************************/
#pragma once
#include <fstream>
#include <string>
#include <sstream>
#include <vec2.hpp>
#include "Object.h"
#include "UnitStateComponent.hpp"
class DataReader {
public:
static bool ReadData(const std::string& file_name, Object* object) {
const std::string file = "../data/" + file_name;
std::ifstream ifstream;
ifstream.open(file.c_str(), std::ios::in);
if (!ifstream.is_open()) {
return false;
}
object->SetName(file_name.substr(0, file_name.size() - 4)); // 4 means .txt
vec2<float> position, size, speed, attackRange;
std::string line, read;
while (!ifstream.eof()) {
std::stringstream lineStream;
std::getline(ifstream, line);
lineStream << line;
lineStream >> read;
if (read == "Position:") {
lineStream >> position.x;
lineStream >> position.y;
object->SetPosition(position);
}
else if (read == "Size:") {
lineStream >> size.x;
lineStream >> size.y;
object->SetSize(size);
}
else if (read == "Speed:") {
lineStream >> speed.x;
lineStream >> speed.y;
object->speed = speed;
//object->SetSpeed(speed);
}
else if (read == "Health:") {
lineStream >> read;
object->GetComponent<BaseUnitState>()->SetHealth(stoi(read));
object->GetComponent<BaseUnitState>()->healthBar.Initialize(object->transform.GetTranslation(), stoi(read));
}
else if (read == "Damage:") {
lineStream >> read;
object->GetComponent<BaseUnitState>()->SetDamage(stoi(read));
}
else if (read == "AttackRange:") {
lineStream >> attackRange.x;
object->GetComponent<BaseUnitState>()->SetAttackRange(attackRange);
}
else if (read == "Camp:") {
lineStream >> read;
if (read == "PlayerUnit") {
object->GetComponent<BaseUnitState>()->SetType(Player);
}
else if (read == "EnemyUnit") {
object->GetComponent<BaseUnitState>()->SetType(Enemy);
}
else if (read == "PlayerProjectile") {
object->GetComponent<BaseUnitState>()->SetType(ProjectilesPlayer);
}
else if (read == "EnemyProjectile") {
object->GetComponent<BaseUnitState>()->SetType(ProjectilesEnemy);
}
}
}
object->transform.SetTranslation(position);
const vec2<float> halfSize = size / 2.f;
object->min = position - halfSize;
object->max = position + halfSize;
object->transform.SetScale(size);
return true;
}
};
|
#pragma once
#include "mapper.hpp"
class Mapper4 : public Mapper
{
uint8_t reg8000;
uint8_t regs[8];
bool horizMirroring;
uint8_t irqPeriod;
uint8_t irqCounter;
bool irqEnabled;
void apply();
public:
Mapper4(uint8_t* rom) : Mapper(rom)
{
for (int i = 0; i < 8; i++)
regs[i] = 0;
horizMirroring = true;
irqEnabled = false;
irqPeriod = irqCounter = 0;
map_prg<8>(3, -1);
apply();
}
uint8_t write(uint16_t addr, uint8_t v);
uint8_t chr_write(uint16_t addr, uint8_t v);
void signal_scanline();
};
|
// 0913_4.cpp : 定义控制台应用程序的入口点。
//先输入一个整数,再输入整数个数的数据,输出和
#include <iostream>
using namespace std;
/*
int main()
{
int N,i;
while (cin >> N)
{
if (N == 0)
break;
else
{
for (i = 1; i <= N; i++)
cout << i << ' ';
cout << endl<<N*(1 + N) / 2;
}
}
return 0;
}
*/
int main()
{
int N, i;
while (cin >> N)
{
if (N == 0)
break;
else
{
int sum = 0;
int x;
for (i = 1; i <= N; i++)
{
cin >> x;
sum = sum + x;
}
cout << sum << endl;
}
}
return 0;
}
|
#include <Wire.h>
#include "defines.h"
#include "helpers.h"
enum class EngineState
{
Idle,
Work
};
EngineState g_CurrentEngineState = EngineState::Idle;
bool g_IsAutoRPM = false;
uint16_t g_WorkRPM = 1500;
uint16_t g_IdleRPM = 600;
uint16_t g_CurrentRPM = 0;
float g_LastFrameTime = 0.f;
float g_TargetTimeToIdle = 10.f;
void setup()
{
Wire.begin();
Serial.begin(9600);
SetupPins();
}
void SetupPins()
{
pinMode(P_TURN_EFFECT, INPUT);
pinMode(M_TURN_BREAK, OUTPUT);
pinMode(M_HLD, OUTPUT);
pinMode(R_START_HEATER, OUTPUT);
pinMode(P_EXTRA, OUTPUT);
pinMode(P_SSC, OUTPUT);
pinMode(M_FLOAT_MODE, OUTPUT);
pinMode(R_FUEL_VALVE, OUTPUT);
pinMode(R_WIPER_UPPER, OUTPUT);
pinMode(R_WIPER_LOWER, OUTPUT);
pinMode(N_ENGINE_OIL, INPUT_PULLUP);
pinMode(N_HYDRAULIC_OIL, INPUT_PULLUP);
pinMode(LEVER_SENSE, INPUT);
pinMode(PEDAL_SENSE, INPUT);
pinMode(DRIVE_PEDAL_SENSE, INPUT);
pinMode(R_ENGINE_HEATER, OUTPUT);
pinMode(R_FAN, OUTPUT);
pinMode(N_WATERSEPERATOR, INPUT_PULLUP);
pinMode(RPM_ENGINE, INPUT);
pinMode(RPM_TURN, INPUT);
pinMode(MANUEVER_LOCK, INPUT);
pinMode(QUICK_LOCK_SENSE, INPUT);
pinMode(S_LOW_GEAR, INPUT);
pinMode(S_HLD, INPUT);
pinMode(S_LEFT_LEVER, INPUT);
pinMode(S_OVERLOAD_ALARM, INPUT);
pinMode(S_START_HEATER, INPUT);
pinMode(S_AUTOMATIC_RPM, INPUT);
pinMode(N_COOLANT, INPUT);
pinMode(TV_AIR_FILTER, INPUT);
pinMode(V_START_HEATER, INPUT);
pinMode(N_LUBRICATION_PUMP, INPUT);
pinMode(TV_OVERLOAD, INPUT);
pinMode(S_WIPER_UPPER, INPUT);
pinMode(S_AUTO_TURN_BRAKE, INPUT);
pinMode(S_AUTOMATIC_RPM2, INPUT);
pinMode(S_WIPER_LOWER, INPUT);
pinMode(L_CENTRAL, OUTPUT);
pinMode(L_WARNING, OUTPUT);
pinMode(L_OVERLOAD, OUTPUT);
pinMode(L_SHOVEL_LOCK, OUTPUT);
pinMode(L_HLD, OUTPUT);
pinMode(L_FLOAT_MODE, OUTPUT);
pinMode(L_AIRCONDITIONING, OUTPUT);
pinMode(TG_MANOUVER_PRESSURE, INPUT);
pinMode(TEMP_COOLANT, INPUT);
pinMode(TEMP_HYDRAULIC_OIL, INPUT);
pinMode(NG_FUEL, INPUT);
pinMode(TG_ENGINE_OIL, INPUT);
}
void loop()
{
float time = (float)millis();
Timestep timestep = time / 1000 - g_LastFrameTime;
g_LastFrameTime = time / 1000;
g_TargetTimeToIdle -= timestep;
if(g_IsAutoRPM && g_CurrentEngineState == EngineState::Work)
{
if (g_TargetTimeToIdle <= 0.f)
{
g_CurrentEngineState = EngineState::Idle;
g_TargetTimeToIdle = 10.f;
}
}
CheckSwitches();
CheckGuards();
delay(500);
}
void CheckSwitches()
{
short switchState = digitalRead(S_AUTO_TURN_BRAKE);
if (switchState == HIGH)
{
/* code */
}
else
{
/* code */
}
switchState = LOW;
switchState = digitalRead(S_AUTOMATIC_RPM);
if(switchState == HIGH)
{
g_IsAutoRPM = true;
}
else
{
g_IsAutoRPM = false;
}
switchState = LOW;
switchState = digitalRead(S_AUTOMATIC_RPM2);
if(switchState == HIGH)
{
}
else
{
/* code */
}
switchState = LOW;
switchState = digitalRead(S_HLD);
if(switchState == HIGH)
{
digitalWrite(M_HLD, 1);
digitalWrite(L_HLD, 1);
}
else
{
digitalWrite(M_HLD, 0);
digitalWrite(L_HLD, 0);
}
switchState = LOW;
switchState = digitalRead(S_LOW_GEAR);
if(switchState == HIGH)
{
}
else
{
/* code */
}
switchState = LOW;
switchState = digitalRead(S_OVERLOAD_ALARM);
if(switchState == HIGH)
{
digitalWrite(L_OVERLOAD, 1);
}
else
{
digitalWrite(L_OVERLOAD, 0);
}
switchState = LOW;
switchState = digitalRead(S_START_HEATER);
if(switchState == HIGH)
{
}
else
{
/* code */
}
switchState = LOW;
switchState = digitalRead(S_WIPER_LOWER);
if(switchState == HIGH)
{
}
else
{
/* code */
}
switchState = LOW;
switchState = digitalRead(S_WIPER_UPPER);
if(switchState == HIGH)
{
}
else
{
/* code */
}
switchState = LOW;
switchState = digitalRead(S_LOW_GEAR);
if(switchState == HIGH)
{
}
else
{
}
}
void CheckGuards()
{
/////Engine Oil/////
short state = digitalRead(N_ENGINE_OIL);
static bool engineOilLevel = false;
if (state == LOW && !engineOilLevel)
{
engineOilLevel = true;
Wire.beginTransmission(10);
Wire.write("{3Låg motorolja!}");
Wire.endTransmission();
//Turn off the engine
digitalWrite(R_FUEL_VALVE, 1);
}
////////////////////
/////Hydraulic Oil//////
state = HIGH;
state = digitalRead(N_HYDRAULIC_OIL);
static bool hydraulicOilLevel = false;
if (state == LOW && !hydraulicOilLevel)
{
hydraulicOilLevel = true;
Wire.beginTransmission(10);
Wire.write("{3Låg hydraulolja!}");
Wire.endTransmission();
}
////////////////////////
/////Coolant level/////
state = LOW;
state = digitalRead(N_COOLANT);
static bool coolantLevel = false;
if (state == HIGH && !coolantLevel)
{
coolantLevel = true;
Wire.beginTransmission(10);
Wire.write("{3Låg kylvätska!}");
Wire.endTransmission();
}
///////////////////////
/////Water seperator/////
state = HIGH;
state = digitalRead(N_WATERSEPERATOR);
static bool waterSeperator = false;
if (state == LOW && !waterSeperator)
{
waterSeperator = true;
Wire.beginTransmission(10);
Wire.write("{2Vatten seperator full!}");
Wire.endTransmission();
}
/////////////////////////
/////Overload warning/////
state = LOW;
state = digitalRead(S_OVERLOAD_ALARM);
if (state == HIGH)
{
state = LOW;
state = digitalRead(TV_OVERLOAD);
static bool overloadWarning = false;
if (state == HIGH && !overloadWarning)
{
overloadWarning = true;
Wire.beginTransmission(10);
Wire.write("{3Varning! Överlast!}");
Wire.endTransmission();
digitalWrite(L_OVERLOAD, 1);
}
else
{
digitalWrite(L_OVERLOAD, 0);
}
}
//////////////////////////
/////Air filter/////
state = LOW;
state = digitalRead(TV_AIR_FILTER);
static bool airFilter = false;
if (state == HIGH && !airFilter)
{
airFilter = true;
Wire.beginTransmission(10);
Wire.write("{2Luftfilter igensatt!}");
Wire.endTransmission();
}
//////////////////////////////
}
void CheckSensors()
{
/////Engine oil sensor/////
float sensorValue = analogRead(TG_ENGINE_OIL);
float voltage = (float)sensorValue * (5.f / 1023.f);
float val = (voltage * 0.7f) / 5.f;
static bool engineOilSensor = false;
if ((g_CurrentRPM > 400 && g_CurrentRPM < 1000) && val < 0.07f)
{
engineOilSensor = true;
Wire.beginTransmission(10);
Wire.write("{3Lågt oljetryck!}");
Wire.endTransmission();
//Turn off the engine
digitalWrite(R_FUEL_VALVE, 1);
}
///////////////////////////
/////Engine RPM/////
////////////////////
if (g_IsAutoRPM)
{
short sensorState = digitalRead(LEVER_SENSE);
if (sensorState == HIGH)
{
g_CurrentEngineState = EngineState::Work;
}
sensorState = LOW;
sensorState = digitalRead(PEDAL_SENSE);
if (sensorState == HIGH)
{
g_CurrentEngineState = EngineState::Work;
}
sensorState = LOW;
sensorState = digitalRead(DRIVE_PEDAL_SENSE);
if (sensorState == HIGH)
{
g_CurrentEngineState = EngineState::Work;
}
}
}
|
#ifndef CONFIG_H
#define CONFIG_H
#include "MonsterTypes.h"
class CGame;
class CSkill;
class TiXmlElement;
class CMonster;
class CConfig
{
public:
static void init(CGame* pGame);
private:
static CSkill* createSkill(std::wstring& sName, TiXmlElement* pSkillNode);
static void initFeatures(TiXmlElement* pNode, const std::string& sName, double* dFeatures);
static void initSkills(TiXmlElement* pNode, std::vector<CSkill*>& oSkills, CMonster* pOwner = nullptr);
};
#endif // !CONFIG_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2002-2011 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"
#include "modules/prefs/prefsmanager/prefsmanager.h"
#include "modules/prefs/prefsmanager/opprefscollection.h"
#include "modules/prefsfile/prefssection.h"
#include "modules/prefsfile/impl/backend/prefssectioninternal.h"
#include "modules/prefsfile/prefsentry.h"
#include "modules/prefsfile/prefsfile.h"
#include "modules/prefs/prefsmanager/collections/pc_core.h"
#include "modules/prefs/prefsmanager/collections/pc_network.h"
#include "modules/prefs/prefsmanager/collections/pc_display.h"
#include "modules/prefs/prefsmanager/collections/pc_doc.h"
#include "modules/prefs/prefsmanager/collections/pc_parsing.h"
#include "modules/prefs/prefsmanager/collections/pc_fontcolor.h"
#ifdef _PRINT_SUPPORT_
# include "modules/prefs/prefsmanager/collections/pc_print.h"
#endif
#include "modules/prefs/prefsmanager/collections/pc_app.h"
#include "modules/prefs/prefsmanager/collections/pc_files.h"
#if defined GEOLOCATION_SUPPORT
# include "modules/prefs/prefsmanager/collections/pc_geoloc.h"
#endif
#include "modules/prefs/prefsmanager/collections/pc_js.h"
#ifdef DATABASE_MODULE_MANAGER_SUPPORT
# include "modules/database/prefscollectiondatabase.h"
#endif //DATABASE_MODULE_MANAGER_SUPPORT
#ifdef WEBSERVER_SUPPORT
# include "modules/prefs/prefsmanager/collections/pc_webserver.h"
#endif
#ifdef PREFS_HAVE_DESKTOP_UI
# include "modules/prefs/prefsmanager/collections/pc_ui.h"
#endif
#ifdef M2_SUPPORT
# include "modules/prefs/prefsmanager/collections/pc_m2.h"
#endif
#ifdef PREFS_HAVE_MSWIN
# include "modules/prefs/prefsmanager/collections/pc_mswin.h"
#endif
#ifdef PREFS_HAVE_COREGOGI
# include "platforms/core/prefscollectioncoregogi.h"
#endif
#ifdef PREFS_HAVE_UNIX
# include "modules/prefs/prefsmanager/collections/pc_unix.h"
#endif
#ifdef PREFS_HAVE_MAC
# include "modules/prefs/prefsmanager/collections/pc_macos.h"
#endif
#if defined SCOPE_SUPPORT || defined SUPPORT_DEBUGGING_SHELL
# include "modules/prefs/prefsmanager/collections/pc_tools.h"
#endif
#ifdef SUPPORT_DATA_SYNC
# include "modules/prefs/prefsmanager/collections/pc_sync.h"
#endif
#ifdef PREFS_HAVE_OPERA_ACCOUNT
# include "modules/prefs/prefsmanager/collections/pc_opera_account.h"
#endif
#ifdef DOM_JIL_API_SUPPORT
# include "modules/prefs/prefsmanager/collections/pc_jil.h"
#endif
#ifdef MSWIN
# include "platforms/windows/pi/WindowsOpSystemInfo.h"
#endif
#ifdef PREFS_GETOVERRIDDENHOSTS
# include "modules/util/opstrlst.h"
#endif
PrefsManager::PrefsManager(PrefsFile *reader)
: m_initialized(FALSE)
#ifdef PREFS_READ
, m_reader(reader)
#endif
#ifdef PREFS_HOSTOVERRIDE
, m_overrides(NULL)
# ifdef PREFS_READ
, m_overridesreader(NULL)
# endif
#endif
{
}
PrefsManager::~PrefsManager()
{
// Destroy all collections
g_opera->prefs_module.m_collections->Clear();
#ifdef PREFS_READ
// Destroy reader
OP_DELETE(m_reader);
#endif
#ifdef PREFS_HOSTOVERRIDE
// Destroy cache of overridden hosts
OP_DELETE(m_overrides);
# ifdef PREFS_READ
// Destroy overrides reader
OP_DELETE(m_overridesreader);
# endif
#endif
}
void PrefsManager::ConstructL()
{
// Create all preference collections, and store them in the linked list
// owned by the PrefsModule instance. The CreateL methods also make
// sure the "global" g_pc* objects are set up properly.
Head *collections = g_opera->prefs_module.m_collections;
#ifndef PREFS_READ
PrefsFile *m_reader = NULL; // Hack to avoid ifdefs below
#endif
// Continue with the files collection, which is referenced by several
// other collections in their initialization.
PrefsCollectionFiles::CreateL(m_reader)->Into(collections);
// Now create the other collections, the order should not matter.
PrefsCollectionNetwork::CreateL(m_reader)->Into(collections);
PrefsCollectionCore::CreateL(m_reader)->Into(collections);
PrefsCollectionDisplay::CreateL(m_reader)->Into(collections);
PrefsCollectionDoc::CreateL(m_reader)->Into(collections);
PrefsCollectionParsing::CreateL(m_reader)->Into(collections);
PrefsCollectionFontsAndColors::CreateL(m_reader)->Into(collections);
#if defined GEOLOCATION_SUPPORT
PrefsCollectionGeolocation::CreateL(m_reader)->Into(collections);
#endif
#ifdef _PRINT_SUPPORT_
PrefsCollectionPrint::CreateL(m_reader)->Into(collections);
#endif
PrefsCollectionApp::CreateL(m_reader)->Into(collections);
PrefsCollectionJS::CreateL(m_reader)->Into(collections);
#ifdef DATABASE_MODULE_MANAGER_SUPPORT
PrefsCollectionDatabase::CreateL(m_reader)->Into(collections);
#endif // DATABASE_MODULE_MANAGER_SUPPORT
#ifdef WEBSERVER_SUPPORT
PrefsCollectionWebserver::CreateL(m_reader)->Into(collections);
#endif
#if defined SCOPE_SUPPORT || defined SUPPORT_DEBUGGING_SHELL
PrefsCollectionTools::CreateL(m_reader)->Into(collections);
#endif
#ifdef SUPPORT_DATA_SYNC
PrefsCollectionSync::CreateL(m_reader)->Into(collections);
#endif
#ifdef PREFS_HAVE_DESKTOP_UI
PrefsCollectionUI::CreateL(m_reader)->Into(collections);
#endif
#ifdef M2_SUPPORT
PrefsCollectionM2::CreateL(m_reader)->Into(collections);
#endif
#ifdef PREFS_HAVE_MSWIN
PrefsCollectionMSWIN::CreateL(m_reader)->Into(collections);
#endif
#ifdef PREFS_HAVE_COREGOGI
PrefsCollectionCoregogi::CreateL(m_reader)->Into(collections);
#endif
#ifdef PREFS_HAVE_UNIX
PrefsCollectionUnix::CreateL(m_reader)->Into(collections);
#endif
#ifdef PREFS_HAVE_MAC
PrefsCollectionMacOS::CreateL(m_reader)->Into(collections);
#endif
#ifdef PREFS_HAVE_OPERA_ACCOUNT
PrefsCollectionOperaAccount::CreateL(m_reader)->Into(collections);
#endif
#ifdef DOM_JIL_API_SUPPORT
PrefsCollectionJIL::CreateL(m_reader)->Into(collections);
#endif
}
void PrefsManager::ReadAllPrefsL(PrefsModule::PrefsInitInfo *info)
{
#ifdef PREFS_READ
// Load the INI file into memory; a missing file is not a fatal error,
// the file will be created whenever the defaults are changed anyway.
OpStatus::Ignore(m_reader->LoadAllL());
#endif
// Ask all collections to read their settings
OpPrefsCollection *first_collection =
g_opera->prefs_module.GetFirstCollection();
OpPrefsCollection *p = first_collection;
while (p)
{
p->ReadAllPrefsL(info);
p = static_cast<OpPrefsCollection *>(p->Suc());
}
#ifdef PREFS_HOSTOVERRIDE
PrefsCollectionFiles *pcfiles = g_pcfiles; // cache
// Create an object for the override.ini file.
OpStackAutoPtr<PrefsFile> overrideini(OP_NEW_L(PrefsFile, (PREFS_STD)));
overrideini->ConstructL();
overrideini->SetFileL(pcfiles->GetFile(PrefsCollectionFiles::OverridesFile));
# ifdef PREFSFILE_CASCADE
# ifdef PREFSFILE_WRITE_GLOBAL
// Defaults file is used by prefs download to make sure it doesn't
// overwrite the settings from the user
overrideini->SetGlobalFileL(pcfiles->GetFile(PrefsCollectionFiles::DownloadedOverridesFile));
# endif
// Global fixed file in the usual location
OpStackAutoPtr<OpFile> fixedoverridesini(OP_NEW_L(OpFile, ()));
LEAVE_IF_ERROR(fixedoverridesini->Construct(DEFAULT_OVERRIDES_FILE, OPFILE_FIXEDPREFS_FOLDER));
if (uni_strcmp(fixedoverridesini->GetSerializedName(),
pcfiles->GetFile(PrefsCollectionFiles::OverridesFile)->GetSerializedName()) != 0)
{
overrideini->SetGlobalFixedFileL(fixedoverridesini.get());
}
# endif
m_overridesreader = overrideini.release();
m_overridesreader->LoadAllL();
// Let all the collections know about this reader
p = first_collection;
while (p)
{
p->SetOverrideReader(m_overridesreader);
p = static_cast<OpPrefsCollection *>(p->Suc());
}
// Read the override section and check for host overrides
m_overrides = m_overridesreader->ReadSectionInternalL(UNI_L("Overrides"));
const PrefsEntry *overridehost =
m_overrides ? m_overrides->Entries() : NULL;
while (overridehost)
{
// Each override entry has the host name in the key. All overrides
// are stored in a section with the same name as the host, so
// first we load that section. If the section isn't available,
// there is no need to try reading the settings.
OpStackAutoPtr<PrefsSection>
overrides(m_overridesreader->ReadSectionL(overridehost->Key()));
if (overrides.get())
{
// Check if this override was set by the user.
#ifdef PREFSFILE_WRITE_GLOBAL
BOOL entered_by_user = m_overridesreader->IsSectionLocal(overridehost->Key());
#else
const BOOL entered_by_user = TRUE;
#endif
// Disable flag is stored as the value 0. All other values
// (including a missing value) means active.
const uni_char *v = overridehost->Get();
BOOL active = v == NULL || *v != '0';
// We pass the host name and the section down to all collections.
p = first_collection;
while (p)
{
p->ReadOverridesL(overridehost->Key(), overrides.get(), active, entered_by_user);
p = static_cast<OpPrefsCollection *>(p->Suc());
}
}
overridehost = static_cast<const PrefsEntry *>(overridehost->Suc());
}
m_overridesreader->Flush();
#endif // PREFS_HOSTOVERRIDE
// Specials:
#ifdef PREFS_HAVE_FORCE_CD
if (g_pcnet->GetIntegerPref(PrefsCollectionNetwork::ForceCD))
{
char cdletter =
static_cast<WindowsOpSystemInfo *>(g_op_system_info)->GetCDLetter();
// Setup home URL
OpStringC oldhomeurl =
g_pccore->GetStringPref(PrefsCollectionCore::HomeURL);
if (!oldhomeurl.IsEmpty() && KNotFound == oldhomeurl.FindFirstOf(':'))
{
OpString newurl; ANCHOR(OpString, newurl);
newurl.ReserveL(oldhomeurl.Length() + 21);
uni_sprintf(newurl.CStr(), UNI_L("file://localhost/%c:\\%s"), cdletter, oldhomeurl.CStr());
g_pccore->WriteStringL(PrefsCollectionCore::HomeURL, newurl);
// oldhomeurl is now invalid
}
}
#endif
m_initialized = TRUE;
}
#ifdef PREFS_HOSTOVERRIDE
# ifdef PREFS_WRITE
BOOL PrefsManager::RemoveOverridesL(const uni_char *host, BOOL from_user)
{
# ifdef PREFSFILE_WRITE_GLOBAL
if (from_user)
# endif
{
// Delete the settings from the [Overrides] section in the INI file
if (m_overridesreader->DeleteKeyL(UNI_L("Overrides"), host))
{
// There was an entry for this host, and we are allowed to remove it,
// delete the corresponding entries
m_overridesreader->DeleteSectionL(host);
// Remove all data from the collections
OpPrefsCollection *p = g_opera->prefs_module.GetFirstCollection();
while (p)
{
p->RemoveOverridesL(host);
p = static_cast<OpPrefsCollection *>(p->Suc());
}
// Remove the host key from our cache
if (m_overrides)
{
m_overrides->DeleteEntry(host);
}
return TRUE;
}
}
# ifdef PREFSFILE_WRITE_GLOBAL
else
{
// FIXME: When deleting global overrides, the deletion does not take
// affect immediately if there are also local overrides. Need to
// rewrite the RemoveOverridesL code to be able to handle this case
if (m_overridesreader->DeleteKeyGlobalL(UNI_L("Overrides"), host))
{
if (!m_overridesreader->IsKey(UNI_L("Overrides"), host))
{
// There are no longer any overrides for this host, delete it
// completely.
m_overridesreader->DeleteSectionGlobalL(host);
// Remove all data from the collections
OpPrefsCollection *p = g_opera->prefs_module.GetFirstCollection();
while (p)
{
p->RemoveOverridesL(host);
p = static_cast<OpPrefsCollection *>(p->Suc());
}
if (m_overrides)
{
m_overrides->DeleteEntry(host);
}
}
return TRUE;
}
}
# endif
return FALSE;
}
BOOL PrefsManager::RemoveOverridesAllHostsL(BOOL from_user)
{
OpString_list* host_list = NULL;
host_list = GetOverriddenHostsL();
if (host_list)
{
OP_STATUS err;
OP_MEMORY_VAR OP_STATUS last_err = OpStatus::OK;
OP_MEMORY_VAR BOOL removed_any = FALSE;
for (OP_MEMORY_VAR unsigned int i = 0; i < host_list->Count(); i++)
{
err = OpStatus::OK;
OP_MEMORY_VAR BOOL removed_this = FALSE;
TRAP(err, removed_this = RemoveOverridesL(host_list->Item(i).CStr(), from_user));
if (OpStatus::IsSuccess(err))
{
if (removed_this)
removed_any = TRUE;
}
else
{
last_err = err;
}
}
OP_DELETE(host_list);
CommitL();
LEAVE_IF_ERROR(last_err);
return removed_any;
}
return FALSE;
}
# endif // PREFS_WRITE
HostOverrideStatus PrefsManager::IsHostOverridden(const uni_char *host, BOOL exact)
{
// The collections only keep the override objects for the domains
// where there are overrides for themselves, so we need to iterate
// and check them all. Also, objects may have different ideas on
// whether the override was set by the user if it has been modified
// at run-time, so we need to continue checking if we are told it
// is a global override.
OpPrefsCollection *p = g_opera->prefs_module.GetFirstCollection();
HostOverrideStatus rc = HostNotOverridden;
while (p)
{
HostOverrideStatus status = p->IsHostOverridden(host, exact);
if (status != HostNotOverridden)
{
// Return immediately if we are told the setting is set by the
// user.
if (HostOverrideActive == status || HostOverrideDisabled == status)
return status;
// Otherwise we cache the value.
rc = status;
}
p = static_cast<OpPrefsCollection *>(p->Suc());
}
return rc;
}
size_t PrefsManager::HostOverrideCount(const uni_char *host)
{
size_t override_count = 0;
OpPrefsCollection *collection = g_opera->prefs_module.GetFirstCollection();
for (; collection; collection = static_cast<OpPrefsCollection *>(collection->Suc()))
override_count += collection->HostOverrideCount(host);
return override_count;
}
BOOL PrefsManager::SetHostOverrideActiveL(const uni_char *host, BOOL active)
{
// The collections only keep the override objects for the domains
// where there are overrides for themselves, so we need to iterate
// and check them all.
BOOL found = FALSE;
OpPrefsCollection *p = g_opera->prefs_module.GetFirstCollection();
while (p)
{
if (p->SetHostOverrideActive(host, active))
{
found = TRUE;
}
p = static_cast<OpPrefsCollection *>(p->Suc());
}
#ifdef PREFS_WRITE
if (found)
{
// There is an override recorded for this host, change its status in
// the preferences file.
m_overridesreader->WriteIntL(UNI_L("Overrides"), host, active);
}
#endif
return found;
}
# ifdef PREFS_GETOVERRIDDENHOSTS
OpString_list *PrefsManager::GetOverriddenHostsL()
{
return m_overrides->GetKeyListL();
}
# endif
# ifdef PREFS_WRITE
void PrefsManager::OverrideHostAddedL(const uni_char *host)
{
// Add the new host to the list
if (!m_overrides->FindEntry(host))
{
m_overrides->NewEntryL(host, NULL);
}
}
# endif
#endif // PREFS_HOSTOVERRIDE
#ifdef PREFS_HAVE_STRING_API
BOOL PrefsManager::GetPreferenceL(
const char *section, const char *key, OpString &target,
BOOL defval, const uni_char *host)
{
// Check validity of parameters
if (!section || !key)
{
LEAVE(OpStatus::ERR_NULL_POINTER);
}
OP_ASSERT(!defval || !host); // Can't get a default value for a host
OpPrefsCollection::IniSection section_id =
OpPrefsCollection::SectionStringToNumber(section);
// Try reading the preference from each of the collections in turn
OpPrefsCollection *p = g_opera->prefs_module.GetFirstCollection();
while (p)
{
if (p->GetPreferenceL(section_id, key, target, defval, host))
return TRUE;
p = static_cast<OpPrefsCollection *>(p->Suc());
}
return FALSE;
}
#endif // PREFS_HAVE_STRING_API
#if defined PREFS_HAVE_STRING_API && defined PREFS_WRITE
BOOL PrefsManager::WritePreferenceL(const char *section, const char *key, const OpStringC value)
{
// Check validity of parameters (value may be NULL)
if (!section || !key)
{
LEAVE(OpStatus::ERR_NULL_POINTER);
}
OpPrefsCollection::IniSection section_id =
OpPrefsCollection::SectionStringToNumber(section);
// Try writing the preference to each of the collections in turn
OpPrefsCollection *p = g_opera->prefs_module.GetFirstCollection();
while (p)
{
if (p->WritePreferenceL(section_id, key, value))
return TRUE;
p = static_cast<OpPrefsCollection *>(p->Suc());
}
return FALSE;
}
# ifdef PREFS_HOSTOVERRIDE
BOOL PrefsManager::OverridePreferenceL(
const uni_char *host, const char *section, const char *key,
const OpStringC value, BOOL from_user)
{
// Check validity of parameters (value may be NULL)
if (!host || !section || !key)
{
LEAVE(OpStatus::ERR_NULL_POINTER);
}
OpPrefsCollection::IniSection section_id =
OpPrefsCollection::SectionStringToNumber(section);
// Try writing the preference to each of the collections in turn
OpPrefsCollection *p = g_opera->prefs_module.GetFirstCollection();
while (p)
{
if (p->OverridePreferenceL(host, section_id, key, value, from_user))
return TRUE;
p = static_cast<OpPrefsCollection *>(p->Suc());
}
return FALSE;
}
BOOL PrefsManager::RemoveOverrideL(const uni_char *host, const char *section,
const char *key, BOOL from_user)
{
if (!section || !key)
LEAVE(OpStatus::ERR_NULL_POINTER);
OpPrefsCollection::IniSection section_id =
OpPrefsCollection::SectionStringToNumber(section);
BOOL override_removed = FALSE;
OpPrefsCollection *p = g_opera->prefs_module.GetFirstCollection();
while (p)
{
override_removed |= p->RemoveOverrideL(host, section_id, key, from_user);
p = static_cast<OpPrefsCollection *>(p->Suc());
}
return override_removed;
}
# endif
#endif // PREFS_HAVE_STRING_API && PREFS_WRITE
#ifdef PREFS_ENUMERATE
prefssetting *PrefsManager::GetPreferencesL(BOOL sort, unsigned int &length) const
{
const OpPrefsCollection *first = g_opera->prefs_module.GetFirstCollection();
// Count
unsigned int numprefs = 0;
for (const OpPrefsCollection *p = first; p;
p = static_cast<OpPrefsCollection *>(p->Suc()))
{
numprefs += p->GetNumberOfPreferences();
}
// Fetch
prefssetting *settings;
settings = OP_NEWA_L(prefssetting, numprefs);
ANCHOR_ARRAY(prefssetting, settings);
prefssetting *cur = settings;
for (const OpPrefsCollection *q = first; q;
q = static_cast<OpPrefsCollection *>(q->Suc()))
{
cur += q->GetPreferencesL(cur);
}
OP_ASSERT(cur == settings + numprefs); // Sanity check
// Sort
if (sort)
{
op_qsort(settings, numprefs, sizeof (prefssetting), GetPreferencesSort);
}
#ifdef PREFSFILE_CASCADE
// Flag which settings user is allowed to change; do this after
// sorting to optimize PrefsMap lookups.
for (prefssetting *r = settings; r < cur; ++ r)
{
r->enabled = m_reader->AllowedToChangeL(r->section, r->key);
}
#endif
length = numprefs;
ANCHOR_ARRAY_RELEASE(settings);
return settings;
}
/** Helper for GetPreferencesL */
/*static*/ int PrefsManager::GetPreferencesSort(const void *p1, const void *p2)
{
int diff =
op_strcmp(reinterpret_cast<const prefssetting *>(p1)->section,
reinterpret_cast<const prefssetting *>(p2)->section);
if (!diff)
{
diff =
op_strcmp(reinterpret_cast<const prefssetting *>(p1)->key,
reinterpret_cast<const prefssetting *>(p2)->key);
}
return diff;
}
#endif
|
#include <Adafruit_GPS.h>
#include <SoftwareSerial.h>
#include <Wire.h>
// Connect the GPS Power pin to 5V
// Connect the GPS Ground pin to ground
// Connect the GPS TX (transmit) pin to Digital 8
// Connect the GPS RX (receive) pin to Digital 7
SoftwareSerial mySerial(8, 7);
Adafruit_GPS GPS(&mySerial);
const byte dataCount = 20;
union Lat {byte b[4]; float f;} Lat;
union Long {byte b[4]; float f;} Long;
union Spd {byte b[4]; float f;} Spd;
union Alt {byte b[4]; float f;} Alt;
union Angle {byte b[4]; float f;} Angle;
// Set GPSECHO to 'false' to turn off echoing the GPS data to the Serial console
// Set to 'true' if you want to debug and listen to the raw GPS sentences
#define GPSECHO false
void requestEvent()
{
if(GPS.fix)
{
Lat.f = (GPS.latitude);
Long.f = (GPS.longitude);
Spd.f = (GPS.speed);
Alt.f = (GPS.altitude);
Angle.f = (GPS.angle);
byte data[dataCount];
byte j = 0;
for(byte i = 0; i<4; i++)
{
j = i * 5;
data[j] = Lat.b[i];
data[j+1] = Long.b[i];
data[j+2] = Spd.b[i];
data[j+3] = Alt.b[i];
data[j+4] = Angle.b[i];
}
Wire.write(data, dataCount);
}
}
void setup()
{
// connect at 115200 so we can read the GPS fast enough and echo without dropping chars
// also spit it out
Serial.begin(115200);
delay(5000);
Serial.println("Adafruit GPS library basic test!");
Serial.println("Maybe this might actually work!");
Wire.begin(9);
Wire.onRequest(requestEvent);//to send data via i2c
// 9600 NMEA is the default baud rate for Adafruit MTK GPS's- some use 4800
GPS.begin(9600);
GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
// Set the update rate
GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ); // 1 Hz update rate
// Request updates on antenna status, comment out to keep quiet
// GPS.sendCommand(PGCMD_ANTENNA);
delay(1000);
// Ask for firmware version
mySerial.println(PMTK_Q_RELEASE);
}
uint32_t timer = millis();
void loop() // run over and over again
{
char c = GPS.read();
// if you want to debug, this is a good time to do it!
if ((c) && (GPSECHO))
Serial.write(c);
// if a sentence is received, we can check the checksum, parse it...
if (GPS.newNMEAreceived()) {
// a tricky thing here is if we print the NMEA sentence, or data
// we end up not listening and catching other sentences!
// so be very wary if using OUTPUT_ALLDATA and trytng to print out data
//Serial.println(GPS.lastNMEA()); // this also sets the newNMEAreceived() flag to false
if (!GPS.parse(GPS.lastNMEA())) // this also sets the newNMEAreceived() flag to false
return; // we can fail to parse a sentence in which case we should just wait for another
// if millis() or timer wraps around, we'll just reset it
if (timer > millis()) timer = millis();
// approximately every 2 seconds or so, print out the current stats
// if (millis() - timer > 2000) {
// timer = millis(); // reset the timer
//
// Serial.print("\nTime: ");
// Serial.print(GPS.hour, DEC); Serial.print(':');
// Serial.print(GPS.minute, DEC); Serial.print(':');
// Serial.print(GPS.seconds, DEC); Serial.print('.');
// Serial.println(GPS.milliseconds);
// Serial.print("Date: ");
// Serial.print(GPS.day, DEC); Serial.print('/');
// Serial.print(GPS.month, DEC); Serial.print("/20");
// Serial.println(GPS.year, DEC);
// Serial.print("Fix: "); Serial.print((int)GPS.fix);
// Serial.print(" quality: "); Serial.println((int)GPS.fixquality);
// if (GPS.fix) {
// Serial.print("Location: ");
// Serial.print(GPS.latitude, 4); Serial.print(GPS.lat);
// Serial.print(", ");
// Serial.print(GPS.longitude, 4); Serial.println(GPS.lon);
// Serial.print("Speed (knots): "); Serial.println(GPS.speed);
// Serial.print("Angle: "); Serial.println(GPS.angle);
// Serial.print("Altitude: "); Serial.println(GPS.altitude);
// Serial.print("Satellites: "); Serial.println((int)GPS.satellites);
// }
// }
}
}
|
// Created on: 1995-05-12
// Created by: Christian CAILLET
// 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 _Interface_IntList_HeaderFile
#define _Interface_IntList_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Standard_Integer.hxx>
#include <TColStd_HArray1OfInteger.hxx>
#include <Standard_Boolean.hxx>
//! This class detains the data which describe a Graph. A Graph
//! has two lists, one for shared refs, one for sharing refs
//! (the reverses). Each list comprises, for each Entity of the
//! Model of the Graph, a list of Entities (shared or sharing).
//! In fact, entities are identified by their numbers in the Model
//! or Graph : this gives better performances.
//!
//! A simple way to implement this is to instantiate a HArray1
//! with a HSequenceOfInteger : each Entity Number designates a
//! value, which is a Sequence (if it is null, it is considered as
//! empty : this is a little optimisation).
//!
//! This class gives a more efficient way to implement this.
//! It has two lists (two arrays of integers), one to describe
//! list (empty, one value given immediately, or negated index in
//! the second list), one to store refs (pointed from the first
//! list). This is much more efficient than a list of sequences,
//! in terms of speed (especially for read) and of memory
//!
//! An IntList can also be set to access data for a given entity
//! number, it then acts as a single sequence
//!
//! Remark that if an IntList is created from another one, it can
//! be read, but if it is created without copying, it may not be
//! edited
class Interface_IntList
{
public:
DEFINE_STANDARD_ALLOC
//! Creates empty IntList.
Standard_EXPORT Interface_IntList();
//! Creates an IntList for <nbe> entities
Standard_EXPORT Interface_IntList(const Standard_Integer nbe);
//! Creates an IntList from another one.
//! if <copied> is True, copies data
//! else, data are not copied, only the header object is
Standard_EXPORT Interface_IntList(const Interface_IntList& other, const Standard_Boolean copied);
//! Initialize IntList by number of entities.
Standard_EXPORT void Initialize (const Standard_Integer nbe);
//! Returns internal values, used for copying
Standard_EXPORT void Internals (Standard_Integer& nbrefs, Handle(TColStd_HArray1OfInteger)& ents, Handle(TColStd_HArray1OfInteger)& refs) const;
//! Returns count of entities to be aknowledged
Standard_EXPORT Standard_Integer NbEntities() const;
//! Changes the count of entities (ignored if decreased)
Standard_EXPORT void SetNbEntities (const Standard_Integer nbe);
//! Sets an entity number as current (for read and fill)
Standard_EXPORT void SetNumber (const Standard_Integer number);
//! Returns the current entity number
Standard_EXPORT Standard_Integer Number() const;
//! Returns an IntList, identical to <me> but set to a specified
//! entity Number
//! By default, not copied (in order to be read)
//! Specified <copied> to produce another list and edit it
Standard_EXPORT Interface_IntList List (const Standard_Integer number, const Standard_Boolean copied = Standard_False) const;
//! Sets current entity list to be redefined or not
//! This is used in a Graph for redefinition list : it can be
//! disable (no redefinition, i.e. list is cleared), or enabled
//! (starts as empty). The original list has not to be "redefined"
Standard_EXPORT void SetRedefined (const Standard_Boolean mode);
//! Makes a reservation for <count> references to be later
//! attached to the current entity. If required, it increases
//! the size of array used to store refs. Remark that if count is
//! less than two, it does nothing (because immediate storing)
Standard_EXPORT void Reservate (const Standard_Integer count);
//! Adds a reference (as an integer value, an entity number) to
//! the current entity number. Zero is ignored
Standard_EXPORT void Add (const Standard_Integer ref);
//! Returns the count of refs attached to current entity number
Standard_EXPORT Standard_Integer Length() const;
//! Returns True if the list for a number
//! (default is taken as current) is "redefined" (useful for empty list)
Standard_EXPORT Standard_Boolean IsRedefined (const Standard_Integer num = 0) const;
//! Returns a reference number in the list for current number,
//! according to its rank
Standard_EXPORT Standard_Integer Value (const Standard_Integer num) const;
//! Removes an item in the list for current number, given its rank
//! Returns True if done, False else
Standard_EXPORT Standard_Boolean Remove (const Standard_Integer num);
//! Clears all data, hence each entity number has an empty list
Standard_EXPORT void Clear();
//! Resizes lists to exact sizes. For list of refs, a positive
//! margin can be added.
Standard_EXPORT void AdjustSize (const Standard_Integer margin = 0);
private:
Standard_Integer thenbe;
Standard_Integer thenbr;
Standard_Integer thenum;
Standard_Integer thecount;
Standard_Integer therank;
Handle(TColStd_HArray1OfInteger) theents;
Handle(TColStd_HArray1OfInteger) therefs;
};
#endif // _Interface_IntList_HeaderFile
|
/*
replay
Software Library
Copyright (c) 2010-2019 Marius Elvert
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <cmath>
#include <replay/quaternion.hpp>
#include <replay/vector_math.hpp>
replay::quaternion& replay::quaternion::set(const float w, const float x, const float y, const float z)
{
this->w = w;
this->x = x;
this->y = y;
this->z = z;
return *this;
}
replay::quaternion& replay::quaternion::set_identity()
{
return set(1.f, 0.f, 0.f, 0.f);
}
replay::quaternion& replay::quaternion::set_rotation(float angle, const vector3f& axis)
{
angle *= 0.5f;
w = std::cos(angle);
angle = std::sin(angle);
x = axis[0] * angle;
y = axis[1] * angle;
z = axis[2] * angle;
return (*this);
}
replay::quaternion::quaternion()
: w(1.f)
, x(0.f)
, y(0.f)
, z(0.f)
{
}
replay::quaternion::quaternion(const float angle, const vector3f& axis)
{
set_rotation(angle, axis);
}
replay::quaternion::quaternion(const float w, const float x, const float y, const float z)
: w(w)
, x(x)
, y(y)
, z(z)
{
}
const replay::quaternion replay::quaternion::operator*(const quaternion& operand) const
{
return multiply(*this, operand);
}
replay::quaternion& replay::quaternion::operator*=(const quaternion& operand)
{
return (*this = multiply(*this, operand));
}
const replay::quaternion replay::quaternion::operator*(const float rhs) const
{
return quaternion(w * rhs, x * rhs, y * rhs, z * rhs);
}
const replay::quaternion replay::quaternion::operator+(const quaternion& q) const
{
return quaternion(w + q.w, x + q.x, y + q.y, z + q.z);
}
const replay::quaternion replay::quaternion::operator-(const quaternion& q) const
{
return quaternion(w - q.w, x - q.x, y - q.y, z - q.z);
}
const replay::quaternion replay::quaternion::operator/(const float value) const
{
return ((*this) * (1.f / value));
}
replay::quaternion& replay::quaternion::operator*=(const float value)
{
w *= value;
x *= value;
y *= value;
z *= value;
return (*this);
}
replay::quaternion& replay::quaternion::operator/=(const float value)
{
return ((*this) *= (1.f / value));
}
const float replay::quaternion::squared() const
{
return w * w + x * x + y * y + z * z;
}
const float replay::quaternion::magnitude() const
{
return std::sqrt(squared());
}
replay::quaternion& replay::quaternion::conjugate()
{
x = -x;
y = -y;
z = -z;
return *this;
}
const replay::quaternion replay::quaternion::conjugated() const
{
return quaternion(w, -x, -y, -z);
}
const replay::quaternion replay::quaternion::negated() const
{
return quaternion(-w, -x, -y, -z);
}
replay::quaternion& replay::quaternion::negate()
{
w = -w;
x = -x;
y = -y;
z = -z;
return *this;
}
replay::quaternion& replay::quaternion::normalize()
{
const float s = squared();
if (s != 1.0)
(*this) /= std::sqrt(s);
return *this;
}
void replay::rotate(quaternion& q, const float angle, const vector3f& axis)
{
const quaternion delta(angle, axis);
q *= delta;
q.normalize();
}
std::tuple<replay::vector3f, float> replay::to_axis_angle(const quaternion& obj)
{
const float angle = 2.f * std::acos(math::clamp_absolute(obj.w, 1.f));
// begin calculating the inverse sine
float factor = std::sqrt(std::max(1.f - (obj.w * obj.w), 0.f));
// FIXME: is this needed?
if (std::fabs(factor) < 0.0001f)
factor = 1.f;
else
factor = 1.f / factor;
return std::make_tuple(replay::vector3f(obj.x * factor, obj.y * factor, obj.z * factor), angle);
}
const replay::vector3f replay::quaternion::get_transformed_x() const
{
return vector3f(1.f - 2.f * (y * y + z * z), 2.f * (x * y + w * z), 2.f * (x * z - w * y));
}
const replay::vector3f replay::quaternion::get_transformed_y() const
{
return vector3f(2.f * (x * y - w * z), 1.f - 2.f * (x * x + z * z), 2.f * (y * z + w * x));
}
const replay::vector3f replay::quaternion::get_transformed_z() const
{
return vector3f(2.f * (x * z + w * y), 2.f * (y * z - w * x), 1.f - 2.f * (x * x + y * y));
}
const float replay::dot(const quaternion& a, const quaternion& b)
{
return a.w * b.w + a.x * b.x + a.y * b.y + a.z * b.z;
}
const replay::quaternion replay::shortest_arc(const vector3f& a, const vector3f& b)
{
// Compute the cosine of the angle between the two vectors
const float cos = dot(a, b);
// Return an identity if the angle is zero
if (math::fuzzy_equals(cos, 1.f))
return quaternion();
// Otherwise rotate around the perpendicular vector
const vector3f axis = normalized(cross(a, b));
return quaternion(std::acos(cos), axis);
}
replay::vector3f replay::transform(const quaternion& q, const vector3f& v)
{
return vector3f((1.f - 2.f * (q.y * q.y + q.z * q.z)) * v[0] + 2.f * (q.x * q.y - q.z * q.w) * v[1] +
2.f * (q.x * q.z + q.y * q.w) * v[2],
2.f * (q.x * q.y + q.z * q.w) * v[0] + (1.f - 2.f * (q.x * q.x + q.z * q.z)) * v[1] +
2.f * (q.y * q.z - q.x * q.w) * v[2],
2.f * (q.x * q.z - q.y * q.w) * v[0] + 2.f * (q.y * q.z + q.x * q.w) * v[1] +
(1.f - 2.f * (q.x * q.x + q.y * q.y)) * v[2]);
}
const replay::quaternion replay::nlerp(const replay::quaternion& a, const replay::quaternion& b, const float x)
{
quaternion result;
// Turn the right way...
if (dot(a, b) < 0.f)
result = (a * (1.f - x) - b * x);
else
result = (a * (1.f - x) + b * x);
result.normalize();
return result;
}
const replay::quaternion replay::slerp(const replay::quaternion& a, const replay::quaternion& b, const float x)
{
const float angle = dot(a, b);
if (angle < 0.f)
{
if (math::fuzzy_equals(angle, -1.f)) // nlerp
{
quaternion result(a * (1.f - x) - b * x);
return result.normalize();
}
const float theta = std::acos(math::clamp_absolute(-angle, 1.f));
const float sin_theta = std::sin(theta);
const float m = std::sin((1.f - x) * theta) / sin_theta;
const float n = std::sin(x * theta) / sin_theta;
return a * m - b * n;
}
else
{
if (math::fuzzy_equals(angle, 1.f)) // nlerp
{
quaternion result(a * (1.f - x) + b * x);
return result.normalize();
}
const float theta = std::acos(math::clamp_absolute(angle, 1.f));
const float sin_theta = std::sin(theta);
const float m = std::sin((1.f - x) * theta) / sin_theta;
const float n = std::sin(x * theta) / sin_theta;
return a * m + b * n;
}
}
const replay::quaternion replay::short_rotation(const quaternion& a, const quaternion& b)
{
quaternion result(b * inverse(a));
if (dot(a, b) < 0.f)
result.negate();
return result;
}
const replay::quaternion replay::inverse(const quaternion& a)
{
return a.conjugated() / a.squared();
}
|
#include "stdafx.h"
#include "QuizSession.h"
#include "QuestionStates.h"
namespace qp
{
using namespace std;
CQuizSession::CQuizSession(CConstQuizPtr const& quiz, const CQuestionStates & questionStates)
:m_questionStates(questionStates)
,m_currentQuestionIndex(0)
{
quiz;
questionStates;
}
CQuizSession::~CQuizSession()
{
}
const CQuestionStates & CQuizSession::GetQuestionStates()const
{
return m_questionStates;
}
qp::IQuestionStatePtr CQuizSession::GetCurrentQuestionState() const
{
return m_questionStates.GetQuestionStateAtIndex(m_currentQuestionIndex);
}
void CQuizSession::GotoNextQuestion()
{
m_currentQuestionIndex = (m_currentQuestionIndex + 1) % m_questionStates.GetCount();
}
}
|
// gestionVehicules.h : fichier Include pour les fichiers Include système standard,
// ou les fichiers Include spécifiques aux projets.
#pragma once
#include <iostream>
#include <string>
#include <vector>
#include "Vehicule.h"
// TODO: Référencez ici les en-têtes supplémentaires nécessaires à votre programme.
|
#include "NewProjectPop.h"
#include "Common.h"
using namespace studio;
static ImVec2 itemWidthxxx = ImVec2(0.0f, 0.0f);
void NewProjectPop::draw()
{
ImGui::OpenPopup(u8"新建项目");
if (ImGui::BeginPopupModal(u8"新建项目", &Datas::ShowNewProjectPop, /*ImGuiWindowFlags_NoResize |*/ ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize))
{
static char nameBuf[64] = "";
//ImGui::SetKeyboardFocusHere();
ImGui::InputText(u8"##0", nameBuf, IM_ARRAYSIZE(nameBuf)); ImGui::SameLine(); if (ImGui::Button(NB_ICON(ICON_FA_ERASER))) { memset(nameBuf, 0, IM_ARRAYSIZE(nameBuf)); }
static char localionBuf[256] = "";
ImGui::InputText(u8"##1", localionBuf, IM_ARRAYSIZE(localionBuf)); ImGui::SameLine(); ImGui::Button(NB_ICON( ICON_FA_ELLIPSIS_H ));
if (ImGui::Button(u8"取消", ImVec2(-ImGui::GetWindowWidth() / 2.0f, 0.0f))) {}
ImGui::SameLine();
if (ImGui::Button(u8"创建", ImVec2(-FLT_MIN, 0.0f))) {}
ImGui::EndPopup();
}
}
|
// Created on: 2015-07-13
// Created by: Irina KRYLOVA
// Copyright (c) 2015 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 _StepDimTol_RunoutZoneDefinition_HeaderFile
#define _StepDimTol_RunoutZoneDefinition_HeaderFile
#include <Standard.hxx>
#include <StepDimTol_RunoutZoneOrientation.hxx>
#include <StepDimTol_ToleranceZoneDefinition.hxx>
#include <Standard_Integer.hxx>
class StepRepr_HArray1OfShapeAspect;
class StepDimTol_RunoutZoneDefinition;
DEFINE_STANDARD_HANDLE(StepDimTol_RunoutZoneDefinition, StepDimTol_ToleranceZoneDefinition)
//! Representation of STEP entity ToleranceZoneDefinition
class StepDimTol_RunoutZoneDefinition : public StepDimTol_ToleranceZoneDefinition
{
public:
//! Empty constructor
Standard_EXPORT StepDimTol_RunoutZoneDefinition();
//! Initialize all fields (own and inherited)
Standard_EXPORT void Init (const Handle(StepDimTol_ToleranceZone)& theZone,
const Handle(StepRepr_HArray1OfShapeAspect)& theBoundaries,
const Handle(StepDimTol_RunoutZoneOrientation)& theOrientation);
//! Returns field Orientation
inline Handle(StepDimTol_RunoutZoneOrientation) Orientation () const
{
return myOrientation;
}
//! Set field Orientation
inline void SetOrientation (const Handle(StepDimTol_RunoutZoneOrientation) &theOrientation)
{
myOrientation = theOrientation;
}
DEFINE_STANDARD_RTTIEXT(StepDimTol_RunoutZoneDefinition,StepDimTol_ToleranceZoneDefinition)
private:
Handle(StepDimTol_RunoutZoneOrientation) myOrientation;
};
#endif // _StepDimTol_RunoutToleranceZone_HeaderFile
|
#ifndef PGTOOLS_SEPARATEDPSEUDOGENOME_H
#define PGTOOLS_SEPARATEDPSEUDOGENOME_H
#include "readslist/SeparatedExtendedReadsList.h"
#include "SeparatedPseudoGenomeBase.h"
namespace PgTools {
const string PGTYPE_SEPARATED = "SEPARATED_PGEN";
class SeparatedPseudoGenome: public SeparatedPseudoGenomeBase {
protected:
string pgSequence;
ExtendedReadsListWithConstantAccessOption* readsList;
// iteration variables
uint64_t nextRlIdx = 0;
uint64_t curPos = 0;
uint64_t curMisCumCount = 0;
public:
SeparatedPseudoGenome(uint_pg_len_max sequenceLength, ReadsSetProperties* properties);
SeparatedPseudoGenome(string &&pgSequence,
ExtendedReadsListWithConstantAccessOption *readsList, ReadsSetProperties* properties);
string &getPgSequence();
ExtendedReadsListWithConstantAccessOption *getReadsList();
virtual ~SeparatedPseudoGenome();
void applyIndexesMapping(IndexesMapping *indexesMapping);
void applyRevComplPairFile();
string getTypeID() override;
void write(std::ostream &dest) override;
const string getPseudoGenomeVirtual() override;
void disposeReadsList();
// read access
inline void getRawSequenceOfReadLength(char *ptr, uint_pg_len_max pos) {
memcpy((void*) ptr, (void*) (pgSequence.data() + pos), this->readsList->readLength);
}
const string getRead(uint_reads_cnt_max idx);
inline void getRead_RawSequence(uint_reads_cnt_max idx, char *ptr) {
getRawSequenceOfReadLength(ptr, this->readsList->pos[idx]);
}
void getRead_Unsafe(uint_reads_cnt_max idx, char *ptr);
void getRead(uint_reads_cnt_max idx, char *ptr);
// iteration routines
void getNextRead_RawSequence(char *ptr);
void getNextRead_Unsafe(char *ptr, uint_pg_len_max pos);
void getNextRead_Unsafe(char *ptr);
void rewind();
};
class GeneratedSeparatedPseudoGenome: public SeparatedPseudoGenome {
private:
uint_pg_len_max pos = 0;
uint_read_len_max delta = 0;
char_pg* sequence;
public:
char_pg *getSequencePtr() const;
GeneratedSeparatedPseudoGenome(uint_pg_len_max sequenceLength, ReadsSetProperties* properties);
void append(const string& read, uint_read_len_max length, uint_read_len_max overlap, uint_reads_cnt_max orgIdx);
void append(uint_read_len_max length, uint_read_len_max overlap, uint_reads_cnt_max orgIdx);
void validate();
};
}
#endif //PGTOOLS_SEPARATEDPSEUDOGENOME_H
|
#ifndef CavesApp_HPP
#define CavesApp_HPP
#include "OgreFramework.h"
#include "BasicApp.h"
#include "PerlinNoiseGenerator.h"
#include "CaveRegion.h"
#include "DensityCubeBrush.h"
#include "SquareDensityBrush.h"
#include "StandardCubeSmoother.h"
#include "CubeWalker.h"
class CavesApp : public BasicApp
{
private:
CaveRegion* mRegion;
CaveRegion* mRegion2;
SquareDensityCubeBrush *mBrush;
CubeWalker *mWalker;
StandardCubeSmoother *mSmoother;
virtual void setupScene();
virtual void cleanScene();
public:
virtual void updateLogic();
};
#endif
|
//
// EnemyTypes.h
// Dev
//
// Created by Wahid Chowdhury on 5/28/13.
// Copyright (c) 2013 Wahid Chowdhury. All rights reserved.
//
#ifndef __Dev__EnemyTypes__
#define __Dev__EnemyTypes__
#include <iostream>
#include "OBJLoader/OBJObject.h"
#include "OBJLoader/TexturedOBJObject.h"
#define NUM_ENEMY_TYPES 3
//Defines a collection of different enemy types. Just a way to group
//all the data that defines how enemies look.
class EnemyTypes {
public:
EnemyTypes(const OBJObjectShaderHandles &shaderHandles) {
Transform cMw, wMo;
//Default shader params in case the file has none defined (will make things red and shiny)
OBJObjectParams defaults;
defaults.material_ambient = GLJoe::Vec4(.1,.1,.1,1);
defaults.material_diffuse = GLJoe::Vec4(.7,.7,.3,1);
defaults.material_specular = GLJoe::Vec4(1,1,1,1);
defaults.material_shininess = 300;
enemies[0] = new OBJObject("Models/Animals/pig.obj", shaderHandles, cMw, wMo, &defaults);
enemies[0]->initializeOpenGLBuffers();
enemies[1] = new TexturedOBJObject("Images/waterTexture.png",1280,800,"Models/Animals/shark.obj", shaderHandles, cMw, wMo, &defaults);
enemies[1]->initializeOpenGLBuffers();
enemies[2] = new OBJObject("Models/Animals/eagle.obj", shaderHandles, cMw, wMo, &defaults);
enemies[2]->initializeOpenGLBuffers();
}
~EnemyTypes() {
for(int i = 0; i < NUM_ENEMY_TYPES;i++) {
delete enemies[i];
}
}
OBJObject *enemies[NUM_ENEMY_TYPES];
};
#endif /* defined(__Dev__EnemyTypes__) */
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2012 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#ifndef NET_STATUS_POLLER_H_
#define NET_STATUS_POLLER_H_
#ifdef PI_NETWORK_INTERFACE_MANAGER
#include "modules/hardcore/timer/optimer.h"
#include "modules/util/OpHashTable.h"
#include "modules/pi/network/OpNetworkInterface.h"
#include "modules/url/protocols/comm.h"
// If it's less than MINIMUM_INTERNETCONNECTION_CHECK_INTERVAL_MS milliseconds
// since GetNetworkStatus() was called, we use a cached value.
#define MINIMUM_INTERNETCONNECTION_CHECK_INTERVAL_MS 1000
/**
* @usage API for checking network status.
*
* Check status using g_network_connection_status_checker->GetNetworkStatus();
*
*
* Note that we can only report offline accurately. Thus we report NETWORK_STATUS_MIGHT_BE_ONLINE
* when we are most likely online.
*/
class InternetConnectionStatusChecker
: public OpNetworkInterfaceListener
, public OpTimerListener
{
public:
enum InternetConnectionStatus
{
NETWORK_STATUS_IS_OFFLINE, // We are definitely offline.
NETWORK_STATUS_MIGHT_BE_ONLINE // Maybe online, but we really cannot know for sure.
};
/**
* Check if this device is offline.
*
* NETWORK_STATUS_IS_OFFLINE means that there are no network interfaces
* connected to a network.
*
* NETWORK_STATUS_MIGHT_BE_ONLINE means that there are one or more interfaces
* connected to a network.
*
* LOCALHOST is not counted as a network interface.
*
* @return NETWORK_STATUS_IS_OFFLINE if device is offline, or
* NETWORK_STATUS_MIGHT_BE_ONLINE if device might be online.
*/
InternetConnectionStatus GetNetworkStatus();
/**
* Check if a socket is connected through a network interface that is
* still up.
*
* Note that this function does not check if the socket is connected.
* If the socket is not connected through an interface, GetNetworkStatus()
* above will be returned.
*
* If socket is connected to LOCALHOST, we define that as an online
* network interface, and will return NETWORK_STATUS_MIGHT_BE_ONLINE.
*
* @param socket The socket whose network interface to check.
* @return NETWORK_STATUS_IS_OFFLINE if the interface the is
* going through has gone down, or NETWORK_STATUS_MIGHT_BE_ONLINE
* otherwise.
*/
InternetConnectionStatus GetNetworkInterfaceStatus(OpSocket *socket);
virtual ~InternetConnectionStatusChecker();
private:
static OP_STATUS Make(InternetConnectionStatusChecker *&internet_status_checker);
OpPointerHashTable<Comm, Comm> *GetComTable(){ return &m_existing_comm_objects; }
InternetConnectionStatusChecker() : m_last_time_checked(0), m_cached_network_status(NETWORK_STATUS_MIGHT_BE_ONLINE) {}
/** Caller must delete the returned object. */
OpSocketAddress *GetSocketAddressFromInterface(OpNetworkInterface *nic);
virtual void OnInterfaceAdded(OpNetworkInterface *nic);
virtual void OnInterfaceRemoved(OpNetworkInterface *nic);
virtual void OnInterfaceChanged(OpNetworkInterface *nic);
void CloseAllSocketsOnNetworkInterface(OpSocketAddress *nic, OpSocketAddress *server_address = NULL);
virtual void OnTimeOut(OpTimer *timer);
double m_last_time_checked;
struct SocketAddressHashItem
{
OpString socket_adress_string;
OpAutoPtr<OpSocketAddress> socket_address;
};
InternetConnectionStatus m_cached_network_status;
OpAutoStringHashTable<SocketAddressHashItem> m_open_network_interfaces;
OP_STATUS MaintainInterfaceList(OpNetworkInterface* nic, OpAutoStringHashTable<SocketAddressHashItem> &open_network_interfaces);
OpNetworkInterfaceManager *m_interface_manager;
OpPointerHashTable<Comm, Comm> m_existing_comm_objects; // Only Comm objects are allowed to add or remove themselves. Used for checking only.
OpTimer m_extra_interface_check_timer;
friend class Comm;
friend class UrlModule;
};
#endif // PI_NETWORK_INTERFACE_MANAGER
#endif /* NET_STATUS_POLLER_H_ */
|
#include "sculptor.h"
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdlib>
#include <vector>
#include <string>
Sculptor::Sculptor(int _nx, int _ny, int _nz){
nx = _nx;
ny = _ny;
nz = _nz;
if(nx <= 0 || ny <= 0 || nz <= 0){
nx = 0;
ny = 0;
nz = 0;
}
v = new Voxel**[nx];
if(v == nullptr){
std::cout << "v não armazenado" << std::endl;
exit(0);
}
v[0]= new Voxel*[nx * ny];
if(v[0] == nullptr){
std::cout <<"v[0] não armazenado" <<std::endl;
exit(0);
}
v[0][0]= new Voxel[nx * ny * nz];
if(v[0][0] == nullptr){
std::cout << "v[0][0] não armazenado" << std::endl;
exit(0);
}
int x, y, z;
for(x = 0; x < nx; x++){
if(x < (nx - 1)){
v[x + 1] = v[x] + ny;
}
for(y = 0; y < ny; y++){
if((y == ny - 1) && (x != (nx - 1))){
v[x + 1][0] = v[x][y] + nz;
} else {
v[x][y + 1] = v[x][y] + nz;
}
for(z = 0; z < nz; z++){
v[x][y][z].isOn = false;
}
}
}
}
Sculptor::~Sculptor(){
if(nx == 0 || ny == 0 || nz == 0){
return;
}
delete [] v[0][0];
delete [] v[0];
delete [] v;
}
void Sculptor::setColor(float _r, float _g, float _b, float alpha){
r = _r;
g = _g;
b = _b;
a = alpha;
}
void Sculptor::putVoxel(int x, int y, int z){
if ((x >= nx) || (y >= ny) || (z >= nz)){
return;
}
if ((x < 0) || (y < 0) || (z < 0)){
return;
}
v[x][y][z].r = r;
v[x][y][z].g = g;
v[x][y][z].b = b;
v[x][y][z].a = a;
v[x][y][z].isOn = true;
}
void Sculptor::cutVoxel(int x, int y, int z){
if ((x >= nx) || (y >= ny) || (z >= nz)){
return;
}
if ((x < 0) || (y < 0) || (z < 0)){
return;
}
if(v[x][y][z].isOn == true){
v[x][y][z].isOn = false;
}
}
void Sculptor::putBox(int x0, int x1, int y0, int y1, int z0, int z1){
int x, y, z;
int aux = 0;
if(x0 > x1){
aux = x0;
x0 = x1;
x1 = aux;
}
if(y0 > y1){
aux = y0;
y0 = y1;
y1 = aux;
}
if(z0 > z1){
aux = z0;
z0 = z1;
z1 = aux;
}
if(x0 < 0){
x0 = 0;
}
for(x = x0; x <= x1; x++){
for(y = y0; y <= y1; y++){
for(z = z0; z <= z1; z++){
putVoxel(x, y, z);
}
}
}
}
void Sculptor::cutBox(int x0, int x1, int y0, int y1, int z0, int z1){
int x, y, z;
int aux = 0;
if(x0 > x1){
aux = x0;
x0 = x1;
x1 = aux;
}
if(y0 > y1){
aux = y0;
y0 = y1;
y1 = aux;
}
if(z0 > z1){
aux = z0;
z0 = z1;
z1 = aux;
}
if(x0 < 0){
x0 = 0;
}
for(x = x0; x <= x1; x++){
for(y = y0; y <= y1; y++){
for(z = z0; z <= z1; z++){
cutVoxel(x, y, z);
}
}
}
}
void Sculptor::putSphere(int xcenter, int ycenter, int zcenter, int radius){
int x, y, z;
float aux;
for(x = 0; x < nx; x++){
for(y = 0; y < ny; y++){
for(z = 0; z < nz; z++){
aux = ((float) pow((x - xcenter), 2) / pow(radius, 2)) + ((float) pow((y - ycenter), 2) / pow(radius, 2)) + ((float) pow((z - zcenter), 2) / pow(radius, 2));
if(aux <= 1.0){
putVoxel(x, y, z);
}
}
}
}
}
void Sculptor::cutSphere(int xcenter, int ycenter, int zcenter, int radius){
int x, y, z;
float aux;
for(x = 0; x < nx; x++){
for(y = 0; y < ny; y++){
for(z = 0; z < nz; z++){
aux = ((float) pow((x - xcenter), 2) / pow(radius, 2)) + ((float) pow((y - ycenter), 2) / pow(radius, 2)) + ((float) pow((z - zcenter), 2) / pow(radius, 2));
if(aux <= 1.0){
cutVoxel(x, y, z);
}
}
}
}
}
void Sculptor::putEllipsoid(int xcenter, int ycenter, int zcenter, int rx, int ry, int rz){
int x, y, z;
float aux;
for(x = 0; x < nx; x++){
for(y = 0; y < ny; y++){
for(z = 0; z < nz; z++){
aux = ((float) pow((x - xcenter), 2) / pow(rx, 2)) + ((float) pow((y - ycenter), 2) / pow(ry, 2)) + ((float) pow((z - zcenter), 2) / pow(rz, 2));
if(aux <= 1.0){
putVoxel(x, y, z);
}
}
}
}
}
void Sculptor::cutEllipsoid(int xcenter, int ycenter, int zcenter, int rx, int ry, int rz){
int x, y, z;
float aux;
for(x = 0; x < nx; x++){
for(y = 0; y < ny; y++){
for(z = 0; z < nz; z++){
aux = ((float) pow((x - xcenter), 2) / pow(rx, 2)) + ((float) pow((y - ycenter), 2) / pow(ry, 2)) + ((float) pow((z - zcenter), 2) / pow(rz, 2));
if(aux <= 1.0){
cutVoxel(x, y, z);
}
}
}
}
}
std::vector<std::vector<Voxel>> Sculptor::createGrid(int slice){
std::vector<std::vector<Voxel>> matriz;
std::vector<Voxel> linha;
int x, y;
linha.resize(ny);
for(x = 0; x < nx; x++){
for (y = 0; y < ny; ++y) {
linha[y].r = v[x][y][slice].r;
linha[y].g = v[x][y][slice].g;
linha[y].b = v[x][y][slice].b;
linha[y].a = v[x][y][slice].a;
linha[y].isOn = v[x][y][slice].isOn;
}
matriz.push_back(linha);
}
linha.clear();
return (matriz);
}
void Sculptor::writeOFF(char* filename){
std::ofstream fout;
fout.open(filename);
if(!fout.is_open()){
std::cout << "Falha ao criar o arquivo" << std::endl;
exit(0);
}
//Primeira linha do arquivo OFF
fout << "OFF" << std::endl;
int x, y, z;
int Nvoxels = 0;
for(x = 0; x < nx; x++){
for(y = 0; y < ny; y++){
for(z = 0; z < nz; z++){
if(v[x][y][z].isOn){
Nvoxels++;
}
}
}
}
//Segunda linha do arquivo OFF
fout << 8*Nvoxels << " " << 6*Nvoxels << " " << 0 << std::endl;
for(x = 0; x < nx; x++){
for(y = 0; y < ny; y++){
for(z = 0; z < nz; z++){
if(v[x][y][z].isOn){
fout << x - 0.5 << " " << y + 0.5 << " " << z - 0.5 << std::endl;
fout << x - 0.5 << " " << y - 0.5 << " " << z - 0.5 << std::endl;
fout << x + 0.5 << " " << y - 0.5 << " " << z - 0.5 << std::endl;
fout << x + 0.5 << " " << y + 0.5 << " " << z - 0.5 << std::endl;
fout << x - 0.5 << " " << y + 0.5 << " " << z + 0.5 << std::endl;
fout << x - 0.5 << " " << y - 0.5 << " " << z + 0.5 << std::endl;
fout << x + 0.5 << " " << y - 0.5 << " " << z + 0.5 << std::endl;
fout << x + 0.5 << " " << y + 0.5 << " " << z + 0.5 << std::endl;
}
}
}
}
int aux = 0;
for(x = 0; x < nx; x++){
for(y = 0; y < ny; y++){
for(z = 0; z < nz; z++){
if(v[x][y][z].isOn){
fout << 4 << " " << aux + 0 << " " << aux + 3 << " " << aux + 2 << " " << aux + 1 << " " << v[x][y][z].r << " " << v[x][y][z].g << " " << v[x][y][z].b << " " << v[x][y][z].a << std::endl;
fout << 4 << " " << aux + 4 << " " << aux + 5 << " " << aux + 6 << " " << aux + 7 << " " << v[x][y][z].r << " " << v[x][y][z].g << " " << v[x][y][z].b << " " << v[x][y][z].a << std::endl;
fout << 4 << " " << aux + 0 << " " << aux + 1 << " " << aux + 5 << " " << aux + 4 << " " << v[x][y][z].r << " " << v[x][y][z].g << " " << v[x][y][z].b << " " << v[x][y][z].a << std::endl;
fout << 4 << " " << aux + 0 << " " << aux + 4 << " " << aux + 7 << " " << aux + 3 << " " << v[x][y][z].r << " " << v[x][y][z].g << " " << v[x][y][z].b << " " << v[x][y][z].a << std::endl;
fout << 4 << " " << aux + 3 << " " << aux + 7 << " " << aux + 6 << " " << aux + 2 << " " << v[x][y][z].r << " " << v[x][y][z].g << " " << v[x][y][z].b << " " << v[x][y][z].a << std::endl;
fout << 4 << " " << aux + 1 << " " << aux + 2 << " " << aux + 6 << " " << aux + 5 << " " << v[x][y][z].r << " " << v[x][y][z].g << " " << v[x][y][z].b << " " << v[x][y][z].a << std::endl;
aux = aux + 8;
}
}
}
}
if(fout.is_open()){
std::cout << "Arquivo .OFF criado com sucesso!" << std::endl;
}
fout.close();
}
|
//Expedi SPOJ
//its wrong,but i dont know what is wrong
#include<iostream>
#include<bits/stdc++.h>
#include<algorithm>
using namespace std;
#define ll long long
vector<pair<ll,ll>>vec;
bool comp(pair<ll,ll>p1,pair<ll,ll>p2)
{
return p1.first<p2.first;
}
int main()
{
ll t;
cin>>t;
while(t--)
{
ll n,d;
cin>>n;
for(int i=0;i<n;i++)
{
ll p,q;
cin>>p>>q;
vec.push_back(make_pair(p,q));
}
pair<ll,ll>p;
cin>>p.first>>p.second;
d=p.first;
for(int i = 0;i<n;i++)
{
vec[i].first = d - vec[i].first;
}
sort(vec.begin(),vec.end(),comp);
ll flag=0,cool=0,count=p.second;
ll t=0;
for(int i=0;i<n;i++)
{
if(p.second>=(vec[i].first-t))
{
p.second=p.second-(vec[i].first-t)+vec[i].second;
flag++;
count=count+vec[i].second;
t=vec[i].first;
}
if(count>=d)
{
cool=1;
break;
}
}
if(cool)
cout<<flag<<endl;
else
cout<<"-1"<<endl;
}
vec.clear();
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
* psmaas - Patricia Aas
*/
#include "core/pch.h"
#ifdef HISTORY_SUPPORT
#include "modules/history/src/HistoryKey.h"
#ifdef HISTORY_DEBUG
INT HistoryKey::m_number_of_keys = 0;
OpVector<HistoryKey> HistoryKey::keys;
#endif //HISTORY_DEBUG
/***********************************************************************************
**
**
**
**
**
***********************************************************************************/
HistoryKey * HistoryKey::Create(const OpStringC& key)
{
OpAutoPtr<HistoryKey> history_key(OP_NEW(HistoryKey, ()));
if(!history_key.get())
return 0;
RETURN_VALUE_IF_ERROR(history_key->m_key.Set(key.CStr()), 0);
return history_key.release();
}
/***********************************************************************************
**
**
**
**
**
***********************************************************************************/
HistoryKey::~HistoryKey()
{
#ifdef HISTORY_DEBUG
keys.RemoveByItem(this);
m_number_of_keys--;
#endif //HISTORY_DEBUG
OP_ASSERT(!InUse());
}
/***********************************************************************************
**
**
**
**
**
***********************************************************************************/
HistoryKey::HistoryKey()
{
#ifdef HISTORY_DEBUG
keys.Add(this);
m_number_of_keys++;
#endif //HISTORY_DEBUG
}
#endif // HISTORY_SUPPORT
|
// M32/M203 grenades
class 1Rnd_HE_M203: CA_Magazine
{
scope = 2;
type = 16;
displayName = "$STR_DN_HE_M203";
model = "\z\addons\dayz_epoch_w\magazine\dze_m203_he.p3d";
picture = "\Ca\weapons\Data\Equip\m_40mmHP_CA.paa";
ammo = "G_40mm_HE";
initSpeed = 80;
count = 1;
nameSound = "grenadelauncher";
descriptionShort = "$STR_DSS_1Rnd_HE_M203";
};
class 6Rnd_HE_M203: 1Rnd_HE_M203
{
count = 6;
displayName = "$STR_EP1_DN_6Rnd_HE_M203";
descriptionShort = "$STR_EP1_DSS_6Rnd_HE_M203";
type = 256;
picture = "\CA\weapons_E\Data\icons\m_6x40mmHP_CA.paa";
model = "\z\addons\dayz_epoch_w\magazine\dze_6rnd_m32_mag.p3d";
};
class FlareWhite_M203: CA_Magazine
{
scope = 2;
type = 16;
displayName = "$STR_DN_FLAREWHITE_M203";
picture = "\Ca\weapons\Data\Equip\m_FlareWhite_CA.paa";
model = "\z\addons\dayz_epoch_w\magazine\dze_m203_flare.p3d";
ammo = "F_40mm_White";
initSpeed = 80;
count = 1;
nameSound = "grenadelauncher";
descriptionShort = "$STR_DSS_1Rnd_FLAREWHITE_M203";
};
class 6Rnd_FlareWhite_M203: FlareWhite_M203
{
count = 6;
displayName = "$STR_EP1_DN_6Rnd_FlareWhite_M203";
descriptionShort = "$STR_EP1_DSS_6Rnd_FlareWhite_M203";
type = 256;
picture = "\CA\weapons_E\Data\icons\m_6x40mmFlare_CA.paa";
model = "\z\addons\dayz_epoch_w\magazine\dze_6rnd_m32_mag.p3d";
};
class FlareGreen_M203: FlareWhite_M203
{
displayName = "$STR_DN_FLAREGREEN_M203";
ammo = "F_40mm_Green";
picture = "\Ca\weapons\Data\Equip\m_FlareGreen_CA.paa";
descriptionShort = "$STR_DSS_1Rnd_FLAREGREEN_M203";
};
class 6Rnd_FlareGreen_M203: FlareGreen_M203
{
count = 6;
displayName = "$STR_EP1_DN_6Rnd_FlareGreen_M203";
descriptionShort = "$STR_EP1_DSS_6Rnd_FlareGreen_M203";
type = 256;
picture = "\CA\weapons_E\Data\icons\m_6x40mmFlare_CA.paa";
model = "\z\addons\dayz_epoch_w\magazine\dze_6rnd_m32_mag.p3d";
};
class FlareRed_M203: FlareWhite_M203
{
displayName = "$STR_DN_FLARERED_M203";
ammo = "F_40mm_Red";
picture = "\Ca\weapons\Data\Equip\m_FlareRed_CA.paa";
descriptionShort = "$STR_DSS_1Rnd_FLARERED_M203";
};
class 6Rnd_FlareRed_M203: FlareRed_M203
{
count = 6;
displayName = "$STR_EP1_DN_6Rnd_FlareRed_M203";
descriptionShort = "$STR_EP1_DSS_6Rnd_FlareRed_M203";
type = 256;
picture = "\CA\weapons_E\Data\icons\m_6x40mmFlare_CA.paa";
model = "\z\addons\dayz_epoch_w\magazine\dze_6rnd_m32_mag.p3d";
};
class FlareYellow_M203: FlareWhite_M203
{
displayName = "$STR_DN_FLAREYELLOW_M203";
ammo = "F_40mm_Yellow";
picture = "\Ca\weapons\Data\Equip\m_FlareYelow_CA.paa";
descriptionShort = "$STR_DSS_1Rnd_FLAREYELLOW_M203";
};
class 6Rnd_FlareYellow_M203: FlareYellow_M203
{
count = 6;
displayName = "$STR_EP1_DN_6Rnd_FlareYellow_M203";
descriptionShort = "$STR_EP1_DSS_6Rnd_FlareYellow_M203";
type = 256;
picture = "\CA\weapons_E\Data\icons\m_6x40mmFlare_CA.paa";
model = "\z\addons\dayz_epoch_w\magazine\dze_6rnd_m32_mag.p3d";
};
class 1Rnd_Smoke_M203: 1Rnd_HE_M203
{
displayName = "$STR_MN_SMOKE_M203";
picture = "\Ca\weapons_E\Data\icons\m_40mmSmoke_CA.paa";
model = "\z\addons\dayz_epoch_w\magazine\dze_m203_smoke.p3d";
ammo = "G_40mm_Smoke";
descriptionShort = "$STR_DSS_1Rnd_SMOKE_M203";
};
class 6Rnd_Smoke_M203: 1Rnd_Smoke_M203
{
count = 6;
displayName = "$STR_EP1_DN_6Rnd_Smoke_M203";
descriptionShort = "$STR_EP1_DSS_6Rnd_Smoke_M203";
type = 256;
picture = "\CA\weapons_E\Data\icons\m_6x40mmSmoke_CA.paa";
model = "\z\addons\dayz_epoch_w\magazine\dze_6rnd_m32_mag.p3d";
};
class 1Rnd_SmokeRed_M203: 1Rnd_Smoke_M203
{
ammo = "G_40mm_SmokeRed";
displayName = "$STR_DN_1Rnd_SmokeRed_M203";
descriptionShort = "$STR_DSS_1Rnd_SMOKERED_M203";
picture = "\Ca\weapons_E\Data\icons\m_40mmSmokeRed_CA.paa";
};
class 6Rnd_SmokeRed_M203: 1Rnd_SmokeRed_M203
{
count = 6;
displayName = "$STR_EP1_DN_6Rnd_SmokeRed_M203";
descriptionShort = "$STR_EP1_DSS_6Rnd_SmokeRed_M203";
type = 256;
picture = "\CA\weapons_E\Data\icons\m_6x40mmSmoke_CA.paa";
model = "\z\addons\dayz_epoch_w\magazine\dze_6rnd_m32_mag.p3d";
};
class 1Rnd_SmokeGreen_M203: 1Rnd_Smoke_M203
{
ammo = "G_40mm_SmokeGreen";
displayName = "$STR_DN_1Rnd_SmokeGreen_M203";
descriptionShort = "$STR_DSS_1Rnd_SMOKEGREEN_M203";
picture = "\Ca\weapons_E\Data\icons\m_40mmSmokeGreen_CA.paa";
};
class 6Rnd_SmokeGreen_M203: 1Rnd_SmokeGreen_M203
{
count = 6;
displayName = "$STR_EP1_DN_6Rnd_SmokeGreen_M203";
descriptionShort = "$STR_EP1_DSS_6Rnd_SmokeGreen_M203";
type = 256;
picture = "\CA\weapons_E\Data\icons\m_6x40mmSmoke_CA.paa";
model = "\z\addons\dayz_epoch_w\magazine\dze_6rnd_m32_mag.p3d";
};
class 1Rnd_SmokeYellow_M203: 1Rnd_Smoke_M203
{
ammo = "G_40mm_SmokeYellow";
displayName = "$STR_DN_1Rnd_SmokeYellow_M203";
descriptionShort = "$STR_DSS_1Rnd_SMOKEYELLOW_M203";
picture = "\Ca\weapons_E\Data\icons\m_40mmSmokeYellow_CA.paa";
};
class 6Rnd_SmokeYellow_M203: 1Rnd_SmokeYellow_M203
{
count = 6;
displayName = "$STR_EP1_DN_6Rnd_SmokeYellow_M203";
descriptionShort = "$STR_EP1_DSS_6Rnd_SmokeYellow_M203";
type = 256;
picture = "\CA\weapons_E\Data\icons\m_6x40mmSmoke_CA.paa";
model = "\z\addons\dayz_epoch_w\magazine\dze_6rnd_m32_mag.p3d";
};
// GP-25
class 1Rnd_HE_GP25: CA_Magazine
{
scope = 2;
type = 16;
displayName = "$STR_DN_HE_GP25";
picture = "\Ca\weapons_E\Data\icons\M_GP25_HE_CA.paa";
model = "\z\addons\dayz_epoch_w\magazine\dze_gp_he.p3d";
ammo = "G_40mm_HE";
initSpeed = 80;
count = 1;
nameSound = "grenadelauncher";
descriptionShort = "$STR_DSS_1Rnd_HE_GP25";
};
class FlareWhite_GP25: CA_Magazine
{
scope = 2;
type = 16;
displayName = "$STR_DN_FLAREWHITE_GP25";
descriptionShort = "$str_dss_1rnd_flarewhite_gp25";
picture = "\Ca\weapons_E\Data\icons\M_GP25_white_CA.paa";
model = "\z\addons\dayz_epoch_w\magazine\dze_gp_flare.p3d";
ammo = "F_40mm_White";
initSpeed = 80;
count = 1;
nameSound = "grenadelauncher";
};
class FlareGreen_GP25: FlareWhite_GP25
{
displayName = "$STR_DN_FLAREGREEN_GP25";
ammo = "F_40mm_Green";
picture = "\Ca\weapons_E\Data\icons\M_GP25_green_CA.paa";
descriptionShort = "$STR_DSS_1Rnd_FLAREGREEN_GP25";
};
class FlareRed_GP25: FlareWhite_GP25
{
displayName = "$STR_DN_FLARERED_GP25";
ammo = "F_40mm_Red";
picture = "\Ca\weapons_E\Data\icons\M_GP25_red_CA.paa";
descriptionShort = "$STR_DSS_1Rnd_FLARERED_GP25";
};
class FlareYellow_GP25: FlareWhite_GP25
{
displayName = "$STR_DN_FLAREYELLOW_GP25";
ammo = "F_40mm_Yellow";
picture = "\Ca\weapons_E\Data\icons\M_GP25_yellow_CA.paa";
descriptionShort = "$STR_DSS_1Rnd_FLAREYELLOW_GP25";
};
class 1Rnd_SMOKE_GP25: 1Rnd_HE_GP25
{
displayName = "$STR_MN_SMOKE_GP25";
picture = "\Ca\weapons_E\Data\icons\M_GP25_white_CA.paa";
model = "\z\addons\dayz_epoch_w\magazine\dze_gp_smoke.p3d";
ammo = "G_40mm_Smoke";
descriptionShort = "$STR_DSS_1Rnd_SMOKE_GP25";
};
class 1Rnd_SmokeRed_GP25: 1Rnd_SMOKE_GP25
{
displayName = "$STR_DN_1Rnd_SmokeRed_GP25";
picture = "\Ca\weapons_E\Data\icons\M_GP25_red_CA.paa";
ammo = "G_40mm_SmokeRed";
descriptionShort = "$STR_DSS_1Rnd_SMOKERED_GP25";
};
class 1Rnd_SmokeYellow_GP25: 1Rnd_SMOKE_GP25
{
displayName = "$STR_DN_1Rnd_SmokeYellow_GP25";
picture = "\Ca\weapons_E\Data\icons\M_GP25_yellow_CA.paa";
ammo = "G_40mm_SmokeYellow";
descriptionShort = "$STR_DSS_1Rnd_SMOKEYELLOW_GP25";
};
class 1Rnd_SmokeGreen_GP25: 1Rnd_SMOKE_GP25
{
displayName = "$STR_DN_1Rnd_SmokeGreen_GP25";
picture = "\Ca\weapons_E\Data\icons\M_GP25_green_CA.paa";
ammo = "G_40mm_SmokeGreen";
descriptionShort = "$STR_DSS_1Rnd_SMOKEGREEN_GP25";
};
|
#include <iostream>
int convers(int num, int system) {
int result = 0;
int i = 1;
while (0 != num) {
result = result + (num % system) * i;
num = num / system;
i = i * 10;
}
return result;
}
void convers1(int num, int system) {
std::string result1;
int i = 0;
while(0 != num) {
int balance = num % system;
switch(balance) {
case (10):
result1[i] = 'A';
break;
case (11):
result1[i] = 'B';
break;
case (12):
result1[i] = 'C';
break;
case (13):
result1[i] = 'D';
break;
case (14):
result1[i] = 'E';
break;
case (15):
result1[i] = 'F';
break;
default:
result1[i] = balance;
break;
}
i++;
num = num / system;
}
for(int j = i - 1; j >= 0; --j) {
std::cout<<result1[i];
}
}
int main() {
int num = 0;
int system = 0;
std::cout<<"Mutqagrel tiv@ -> ";
std::cin>>num;
std::cout<<"Mutqagrel hamakarg@ ->";
std::cin>>system;
if(10 >= system){
std::cout<<"Nor hamakargi tiv@ klini -> "<<convers(num, system)<<'\n';
} else if(16 >= system || 10 < system) {
std::cout<<"Nor hamakargi tiv@ klini -> ";
convers1(num, system);
} else {
std::cout<<"Sxal mutqagrum \n";
}
return 0;
}
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kwillum <kwillum@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/16 01:13:00 by kwillum #+# #+# */
/* Updated: 2021/01/22 18:22:39 by kwillum ### ########.fr */
/* */
/* ************************************************************************** */
#include "Form.hpp"
#include "Bureaucrat.hpp"
#include "PresidentialPardonForm.hpp"
#include "RobotomyRequestForm.hpp"
#include "ShrubberyCreationForm.hpp"
#include "Intern.hpp"
int main(void)
{
std::cout << "\033[32m Create Bureaucrats: \033[0m\n";
Bureaucrat President("President", 1);
Bureaucrat Ministr("Prime Minister", 50);
Bureaucrat CityHandler("CityHandler", 100);
Bureaucrat Civilian("CiviliaN", 149);
std::cout << "\033[32m Create Intern: \033[0m\n";
Intern someRandomIntern;
Form* testForms[15];
std::cout << "\033[32m Create Robotomy forms: \033[0m\n";
testForms[0] = someRandomIntern.makeForm("robotomy request", "0");
testForms[1] = someRandomIntern.makeForm("tomy request", "1");
testForms[2] = someRandomIntern.makeForm("RobOtomy requesT", "2");
testForms[3] = someRandomIntern.makeForm("robotomYrequest", "3");
testForms[4] = someRandomIntern.makeForm("robotomy request form", "4");
std::cout << "\033[32m Create Presidental forms: \033[0m\n";
testForms[5] = someRandomIntern.makeForm("PresidentialPardonForm", "5");
testForms[6] = someRandomIntern.makeForm("PresidentialPardonFormas", "6");
testForms[7] = someRandomIntern.makeForm("Presidential PArdon Form", "7");
testForms[8] = someRandomIntern.makeForm("PresidentialPardon", "8");
testForms[9] = someRandomIntern.makeForm("PresidentiaL Pardon", "9");
std::cout << "\033[32m Create Shurbbery forms: \033[0m\n";
testForms[10] = someRandomIntern.makeForm("ShrubberyCreationForm", "10");
testForms[11] = someRandomIntern.makeForm("ShrubberyCreationFormas", "11");
testForms[12] = someRandomIntern.makeForm("ShruBbery crEAtion Form", "12");
testForms[13] = someRandomIntern.makeForm("ShrubberyCReation", "13");
testForms[14] = someRandomIntern.makeForm("ShrubbEry creaTIon", "14");
std::cout << "\033[32m Sign and exec all forms \033[0m\n";
for (int i = 0; i < 15; i++)
{
std::cout << "\033[32m [" << i << "]\033[0m \n";
(testForms[i]) ? (std::cout << *testForms[i] << std::endl) : (std::cout << "NULL-form\n");
if (testForms[i])
{
Civilian.signForm(*testForms[i]);
Civilian.executeForm(*testForms[i]);
CityHandler.signForm(*testForms[i]);
CityHandler.executeForm(*testForms[i]);
Ministr.signForm(*testForms[i]);
Ministr.executeForm(*testForms[i]);
President.signForm(*testForms[i]);
President.executeForm(*testForms[i]);
}
}
for (int i = 0; i < 15; i++)
{
if (testForms[i])
delete testForms[i];
}
return (0);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.