text
stringlengths 8
6.88M
|
|---|
#include <iostream>
#include <ctime>
#include <cstdlib>
#define randomInt(a,b) (rand()%(b-a+1)+a)
using namespace std;
int main()
{
int i, j;
// 设置种子
srand((unsigned)time(NULL));
/* 生成 10 个随机数 */
for (i = 0; i < 10; i++)
{
// 生成实际的随机数
j = rand();
cout << "随机数: " << j << endl;
}
for (int i = 0; i < 20; i++)
{
cout << " 随机数2:" << randomInt(1, 100) << "\n";//求[1-100]之间的随机数
}
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
|
//
// Created by wqy on 19-12-11.
//
#include "Action.h"
using namespace esc;
/*Action::Action() {
}*/
string Action::to_string() const {
return "";
}
|
#pragma once
#include <Arcane/Graphics/Renderer/Renderpass/RenderPass.h>
#include <Arcane/Platform/OpenGL/Framebuffer/Framebuffer.h>
#include <Arcane/Util/Timer.h>
namespace Arcane
{
class Shader;
class Scene3D;
class ICamera;
class PostProcessPass : public RenderPass {
public:
PostProcessPass(Scene3D *scene);
virtual ~PostProcessPass() override;
PreLightingPassOutput executePreLightingPass(GeometryPassOutput &geometryData, ICamera *camera);
void executePostProcessPass(Framebuffer *framebufferToProcess);
// Post Processing Effects
void tonemapGammaCorrect(Framebuffer *target, Texture *hdrTexture);
void fxaa(Framebuffer *target, Texture *texture);
void vignette(Framebuffer *target, Texture *texture, Texture *optionalVignetteMask = nullptr);
void chromaticAberration(Framebuffer *target, Texture *texture);
void filmGrain(Framebuffer *target, Texture *texture);
Texture* bloom(Texture *hdrSceneTexture);
private:
inline float lerp(float a, float b, float amount) { return a + amount * (b - a); }
private:
Shader *m_PassthroughShader;
Shader *m_TonemapGammaCorrectShader;
Shader *m_FxaaShader;
Shader *m_SsaoShader, *m_SsaoBlurShader;
Shader *m_BloomBrightPassShader, *m_BloomGaussianBlurShader, *m_BloomComposite;
Shader *m_VignetteShader;
Shader *m_ChromaticAberrationShader;
Shader *m_FilmGrainShader;
Framebuffer m_SsaoRenderTarget;
Framebuffer m_SsaoBlurRenderTarget;
Framebuffer m_TonemappedNonLinearTarget;
Framebuffer m_ScreenRenderTarget; // Only used if the render resolution differs from the window resolution
Framebuffer m_ResolveRenderTarget; // Only used if multi-sampling is enabled so it can be resolved
Framebuffer m_BrightPassRenderTarget;
Framebuffer m_BloomFullRenderTarget;
Framebuffer m_BloomHalfRenderTarget;
Framebuffer m_BloomQuarterRenderTarget;
Framebuffer m_BloomEightRenderTarget;
// Utility Framebuffers
Framebuffer m_FullRenderTarget;
Framebuffer m_HalfRenderTarget;
Framebuffer m_QuarterRenderTarget;
Framebuffer m_EightRenderTarget;
// Post Processing Tweaks
float m_GammaCorrection = 2.2f;
float m_Exposure = 1.0f;
float m_BloomThreshold = 1.0f;
bool m_FxaaEnabled = true;
bool m_SsaoEnabled = true;
float m_SsaoSampleRadius = 2.0f;
float m_SsaoStrength = 3.0f;
bool m_VignetteEnabled = false;
Texture *m_VignetteTexture;
glm::vec3 m_VignetteColour = glm::vec3(0.0f, 0.0f, 0.0f);
float m_VignetteIntensity = 0.25f;
bool m_ChromaticAberrationEnabled = false;
float m_ChromaticAberrationIntensity = 0.25f;
bool m_FilmGrainEnabled = false;
float m_FilmGrainIntensity = 0.25f;
// SSAO Tweaks
std::array<glm::vec3, SSAO_KERNEL_SIZE> m_SsaoKernel;
Texture m_SsaoNoiseTexture;
Timer m_ProfilingTimer;
Timer m_EffectsTimer;
};
}
|
#include <fstream>
namespace
{
template <typename T>
std::unique_ptr<T[]> Read(const std::string &rFileName, size_t &rFileSize)
{
if (rFileName.empty())
{
rFileSize = 0;
return nullptr;
}
std::ifstream fileStream(rFileName, std::ios_base::in | std::ios_base::binary);
if (!fileStream.is_open())
{
rFileSize = 0;
return nullptr;
}
fileStream.seekg(0, std::ios_base::end);
rFileSize = fileStream.tellg();
fileStream.seekg(0, std::ios_base::beg);
std::unique_ptr<T[]> buffer;
if (rFileSize > 0)
{
buffer = std::unique_ptr<T[]>(new T[rFileSize]);
fileStream.read((char *)buffer.get(), rFileSize);
}
fileStream.close();
return buffer;
}
}
namespace FastCG
{
std::unique_ptr<char[]> FileReader::ReadText(const std::string &rFileName, size_t &rFileSize)
{
return Read<char>(rFileName, rFileSize);
}
std::unique_ptr<uint8_t[]> FileReader::ReadBinary(const std::string &rFileName, size_t &rFileSize)
{
return Read<uint8_t>(rFileName, rFileSize);
}
}
|
#include <cstdlib>
#include <vector>
#include <iostream>
#include <iterator>
using namespace std;
vector<int> mergesort(vector<int> &unsorted) {
vector<int> firsthalf;
vector<int> secondhalf;
for(int iter = 0; iter < unsorted.size(); ++iter) {
if(iter < unsorted.size()/2) {
firsthalf.push_back(unsorted[iter]);
}
else {
secondhalf.push_back(unsorted[iter]);
}
}
if(firsthalf.size() > 1) {
firsthalf = mergesort(firsthalf);
}
if(secondhalf.size() > 1) {
secondhalf = mergesort(secondhalf);
}
vector<int> sorted;
auto leftptr = firsthalf.begin();
auto rightptr = secondhalf.begin();
while(sorted.size() < (firsthalf.size() + secondhalf.size())) {
if(*leftptr < *rightptr and (leftptr != firsthalf.end())) {
sorted.push_back(*leftptr);
if(leftptr+1 == firsthalf.end()) {
while(rightptr != secondhalf.end()) {
sorted.push_back(*rightptr);
++rightptr;
}
}
++leftptr;
}
else {
sorted.push_back(*rightptr);
if(rightptr+1 == secondhalf.end()) {
while(leftptr != firsthalf.end()) {
sorted.push_back(*leftptr);
++leftptr;
}
}
++rightptr;
}
}
return sorted;
}
int main() {
vector<int> numvec = {4,6,123,29,79,1020,2,1,10,89,67};
for (int x : numvec) {
cout << x << " ";
}
cout << endl;
numvec = mergesort(numvec);
for (int x : numvec) {
cout << x << " ";
}
return 0;
}
|
#ifndef SPHERE
#define SPHERE
#include <bits/stdc++.h>
#include <GL/glut.h>
#include <windows.h>
#include "1605002_Object.hpp"
#include "1605002_Vector3D.hpp"
#include "1605002_Constants.hpp"
#include "1605002_Utils.hpp"
using namespace std;
Vector3D spherePoints[SPHERE_STACKS + 10][SPHERE_SLICES + 10];
class Sphere : public Object
{
public:
Vector3D center;
double radius;
void drawRing()
{
//draw quads using generated points
for (int i = 0; i < SPHERE_STACKS; i++)
{
for (int j = 0; j < SPHERE_SLICES; j++)
{
glBegin(GL_QUADS);
{
glVertex3f(spherePoints[i][j].x(), spherePoints[i][j].y(), spherePoints[i][j].z());
glVertex3f(spherePoints[i][j + 1].x(), spherePoints[i][j + 1].y(), spherePoints[i][j + 1].z());
glVertex3f(spherePoints[i + 1][j + 1].x(), spherePoints[i + 1][j + 1].y(), spherePoints[i + 1][j + 1].z());
glVertex3f(spherePoints[i + 1][j].x(), spherePoints[i + 1][j].y(), spherePoints[i + 1][j].z());
}
glEnd();
}
}
}
void drawHalfSphere(int shamne)
{
//generate points
for (int i = 0; i <= SPHERE_STACKS; i++)
{
double h = radius * sin(((double)i / (double)SPHERE_STACKS) * (PI / 2));
double r = radius * cos(((double)i / (double)SPHERE_STACKS) * (PI / 2));
for (int j = 0; j <= SPHERE_SLICES; j++)
{
double x = r * cos(((double)j / (double)SPHERE_SLICES) * 2 * PI);
double y = h * shamne;
double z = r * sin(((double)j / (double)SPHERE_SLICES) * 2 * PI);
spherePoints[i][j] = Vector3D(x, y, z);
}
}
drawRing();
}
Sphere() {}
Sphere(Vector3D center, double radius) : center(center), radius(radius) {}
virtual void draw()
{
glPushMatrix();
glTranslatef(center.coords[0], center.coords[1], center.coords[2]);
glColor3f(color[0], color[1], color[2]);
drawHalfSphere(1);
drawHalfSphere(-1);
glPopMatrix();
}
virtual double getChed(Ray ray)
{
ray.start -= center;
double a = 1;
double b = 2 * ray.start.dot(ray.dir);
double c = ray.start.dot(ray.start) - radius * radius;
double t1, t2;
return getSol(a, b, c, t1, t2);
}
virtual Ray getNormal(Vector3D point, Ray incident)
{
return Ray(point, point - center);
}
virtual void chapao()
{
cout << "sphere" << endl;
cout << "center = " << center << endl;
cout << "radius = " << radius << endl;
cout << "colors = " << color[0] << " " << color[1] << " " << color[2] << endl;
cout << "coEffs = " << coEfficients[0] << " " << coEfficients[1] << " " << coEfficients[2] << " " << coEfficients[3] << endl;
cout << "shine = " << shine << endl
<< endl;
}
friend istream &operator>>(istream &, Sphere &);
};
istream &operator>>(istream &din, Sphere &s)
{
din >> s.center >> s.radius;
for (int i = 0; i < 3; i++)
din >> s.color[i];
for (int i = 0; i < 4; i++)
din >> s.coEfficients[i];
din >> s.shine;
return din;
}
#endif
|
#pragma once
//===----------------------------------------------------------------------===//
// This file is based on the original Cuckoo filter implementation,
// that can be found on GitHub: https://github.com/efficient/cuckoofilter
// Usable under the terms in the Apache License, Version 2.0.
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
//
// Copyright (C) 2013, Carnegie Mellon University and Intel Corporation
//
// 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.
//
//===----------------------------------------------------------------------===//
// Change log:
// 2017-2018 | H. Lang (TUM), P. Boncz (CWI):
// - memory needs to be managed by the caller
// - configurable associativity (number of tags per bucket)
// - the filter size is no longer restricted to powers of two (see "dtl/filter/block_addressing_logic.hpp" for details)
// - an interface for batched lookups
// - SIMDized implementations for batched lookups (AVX2, AVX-512, and experimental CUDA)
// - faster hashing (multiplicative)
// - removed 'deletion' support
#include <bitset>
#include <dtl/dtl.hpp>
#include <dtl/math.hpp>
#include <dtl/mem.hpp>
#include <dtl/simd.hpp>
#include <dtl/filter/blocked_bloomfilter/block_addressing_logic.hpp>
#include <dtl/filter/blocked_bloomfilter/hash_family.hpp>
#include "cuckoofilter_table.hpp"
namespace dtl {
namespace cuckoofilter {
// Dispatch batch_contains calls either to batch_contains_scalar or batch_contains_vec.
namespace internal {
//===----------------------------------------------------------------------===//
// Batch-wise Contains (SIMD)
//===----------------------------------------------------------------------===//
template<
typename filter_t,
u64 vector_len
>
struct batch_contains {
// Typedefs
using key_t = typename filter_t::key_t;
using word_t = typename filter_t::word_t;
__attribute__ ((__noinline__))
static $u64
dispatch(const filter_t& filter,
const word_t* __restrict filter_data,
const key_t* __restrict keys, u32 key_cnt,
$u32* __restrict match_positions, u32 match_offset) {
return filter.template batch_contains_vec<vector_len>(filter_data, keys, key_cnt, match_positions, match_offset);
}
};
//===----------------------------------------------------------------------===//
// Batch-wise Contains (no SIMD)
//===----------------------------------------------------------------------===//
template<
typename filter_t
>
struct batch_contains<filter_t, 0> {
// Typedefs
using key_t = typename filter_t::key_t;
using word_t = typename filter_t::word_t;
__attribute__ ((__noinline__))
static $u64
dispatch(const filter_t& filter,
const word_t* __restrict filter_data,
const key_t* __restrict keys, u32 key_cnt,
$u32* __restrict match_positions, u32 match_offset) {
return filter.batch_contains_scalar(filter_data, keys, key_cnt, match_positions, match_offset);
}
};
} // namespace internal
//===----------------------------------------------------------------------===//
// A cuckoo filter class exposes a Bloomier filter interface,
// providing methods of insert, Delete, contain. It takes three
// template parameters:
// bits_per_tag: how many bits each item is hashed into
// tags_per_bucket: how items fit into a single bucket
// table_t: the storage of the table
//===----------------------------------------------------------------------===//
template <std::size_t bits_per_tag,
std::size_t tags_per_bucket,
template <std::size_t, std::size_t> class table_t = cuckoofilter_table,
dtl::block_addressing block_addressing = dtl::block_addressing::POWER_OF_TWO
>
class cuckoofilter_logic {
// Maximum number of cuckoo kicks before claiming failure.
static constexpr std::size_t max_relocation_count = 500;
public:
using key_t = uint32_t;
using word_t = typename table_t<bits_per_tag, tags_per_bucket>::word_t;
static constexpr uint32_t tag_mask = static_cast<uint32_t>((1ull << bits_per_tag) - 1);
// An overflow entry for a single item (used when the filter became full)
typedef struct {
uint32_t index;
uint32_t tag;
bool used;
} victim_cache_t;
// The block addressing logic (either MAGIC or POWER_OF_TWO).
// In the context of cuckoo filters a 'block' refers to a 'bucket'.
using addr_t = dtl::block_addressing_logic<block_addressing>;
const addr_t block_addr;
// The table logic.
const table_t<bits_per_tag, tags_per_bucket> table;
// The victim cache is stored at the very end of the (externally managed) filter data. // TODO consider removing the victim cache.
const std::size_t victim_cache_offset;
static constexpr std::size_t
bucket_bitlength = table_t<bits_per_tag, tags_per_bucket>::bytes_per_bucket * 8;
//===----------------------------------------------------------------------===//
explicit
cuckoofilter_logic(const std::size_t desired_bitlength)
: block_addr((desired_bitlength + (bucket_bitlength - 1)) / bucket_bitlength),
table(block_addr.get_block_cnt()),
victim_cache_offset(table.word_cnt()) {
}
cuckoofilter_logic(cuckoofilter_logic&&) noexcept = default;
cuckoofilter_logic(const cuckoofilter_logic&) = default;
~cuckoofilter_logic() = default;
cuckoofilter_logic& operator=(cuckoofilter_logic&&) = default;
cuckoofilter_logic& operator=(const cuckoofilter_logic&) = default;
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
/// Maps a 32-bit hash value to a bucket index.
__forceinline__ __host__ __device__
uint32_t
index_hash(uint32_t hash_val) const {
return block_addr.get_block_idx(hash_val);
}
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
/// Derives a (valid) tag from the given 32 bit hash value.
__forceinline__ __host__ __device__
uint32_t
tag_hash(uint32_t hash_value) const {
uint32_t tag;
tag = hash_value & tag_mask;
tag += (tag == 0);
return tag;
}
template<typename Tv, typename = std::enable_if_t<dtl::is_vector<Tv>::value>>
__forceinline__ __host__
dtl::vec<uint32_t, dtl::vector_length<Tv>::value>
tag_hash(const Tv& hash_value) const {
const auto m = tag_mask;
auto tag = hash_value & m;
tag[tag == 0] += 1;
return tag;
}
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
/// Hash the key and derive the tag and the bucket index.
__forceinline__ __host__ __device__
void
generate_index_tag_hash(const key_t& key, uint32_t* index, uint32_t* tag) const {
*index = index_hash(dtl::hasher<uint32_t, 0>::hash(key));
*tag = tag_hash(dtl::hasher<uint32_t, 1>::hash(key));
}
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
/// Compute the alternative bucket index
/// where # of buckets is a power of two.
__forceinline__ __host__ __device__
uint32_t
alt_index(const uint32_t bucket_idx, const uint32_t tag,
const dtl::block_addressing_logic<dtl::block_addressing::POWER_OF_TWO>& addr_logic) const {
// NOTE(binfan): originally we use:
// bucket_idx ^ HashUtil::BobHash((const void*) (&tag), 4)) & table->INDEXMASK;
// now doing a quick-n-dirty way:
// 0x5bd1e995 is the hash constant from MurmurHash2
return (bucket_idx ^ (tag * 0x5bd1e995)) & block_addr.block_cnt_mask;
}
// vectorized
template<typename Tv, typename = std::enable_if_t<dtl::is_vector<Tv>::value>>
__forceinline__ __host__
dtl::vec<uint32_t, dtl::vector_length<Tv>::value>
alt_index(const Tv& bucket_idx, const Tv& tag,
const dtl::block_addressing_logic<dtl::block_addressing::POWER_OF_TWO>& addr_logic) const {
// auto c = Tv::make(block_addr.block_cnt_mask);
// return (bucket_idx ^ (tag * 0x5bd1e995)) & c;
return (bucket_idx ^ (tag * 0x5bd1e995)) & block_addr.block_cnt_mask;
}
/// Compute the alternative bucket index
/// where the # of buckets is NOT a power of two (aka MAGIC addressing)
/// See [1] for more details on partial-key cuckoo hashing in tables that are
/// not a power of two in size.
///
/// [1] https://databasearchitects.blogspot.com/2019/07/cuckoo-filters-with-arbitrarily-sized.html
__forceinline__ __host__ __device__
uint32_t
alt_index(const uint32_t bucket_idx, const uint32_t tag,
const dtl::block_addressing_logic<dtl::block_addressing::MAGIC>& addr_logic) const {
auto c = block_addr.get_block_cnt();
auto s_mod_m = block_addr.get_block_idx(tag * 0x5bd1e995);
auto x = c - s_mod_m;
auto mask = (x < bucket_idx)*(~0);
auto ret_val = (mask & c) + (x - bucket_idx);
return ret_val;
// return block_addr.get_block_idx(-(bucket_idx + (tag * 0x5bd1e995)));
}
// vectorized
template<typename Tv, typename = std::enable_if_t<dtl::is_vector<Tv>::value>>
__forceinline__ __host__
dtl::vec<uint32_t, dtl::vector_length<Tv>::value>
alt_index(const Tv& bucket_idx, const Tv& tag,
const dtl::block_addressing_logic<dtl::block_addressing::MAGIC>& addr_logic) const {
auto c = Tv::make(block_addr.get_block_cnt());
auto s_mod_m = block_addr.get_block_idxs(tag * 0x5bd1e995);
auto x = c - s_mod_m;
auto ret_val = x - bucket_idx;
ret_val[x < bucket_idx] += c;
return ret_val;
// return block_addr.get_block_idxs(Tv::make(0) - (bucket_idx + (tag * 0x5bd1e995)));
}
/// Compute the alternative bucket index.
__forceinline__ __host__ __device__
uint32_t
alt_index(const uint32_t bucket_idx, const uint32_t tag) const {
// Dispatch based on the addressing type.
// Note: This doesn't induce runtime overhead.
return alt_index(bucket_idx, tag, block_addr);
}
// vectorized
template<typename Tv, typename = std::enable_if_t<dtl::is_vector<Tv>::value>>
__forceinline__ __host__
dtl::vec<uint32_t, dtl::vector_length<Tv>::value>
alt_index(const Tv& bucket_idx, const Tv& tag) const {
return alt_index(bucket_idx, tag, block_addr);
}
//===----------------------------------------------------------------------===//
public:
//===----------------------------------------------------------------------===//
// Insert
//===----------------------------------------------------------------------===//
bool
insert(word_t* __restrict filter_data, const key_t& key) {
uint32_t i;
uint32_t tag;
victim_cache_t& victim = *reinterpret_cast<victim_cache_t*>(&filter_data[victim_cache_offset]);
if (victim.used) {
return false;
}
generate_index_tag_hash(key, &i, &tag);
uint32_t curindex = i;
uint32_t curtag = tag;
uint32_t oldtag;
for (uint32_t count = 0; count < max_relocation_count; count++) {
bool kickout = count > 0;
oldtag = 0;
if (table.insert_tag_to_bucket(filter_data, curindex, curtag, kickout, oldtag)) {
return true;
}
if (kickout) {
curtag = oldtag;
}
assert(alt_index(alt_index(curindex, curtag), curtag) == curindex);
curindex = alt_index(curindex, curtag);
}
victim.index = curindex;
victim.tag = curtag;
victim.used = true;
return true;
};
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// Batch Insert
//===----------------------------------------------------------------------===//
bool
batch_insert(word_t* __restrict filter_data,
const key_t* keys, u32 key_cnt) noexcept {
$u1 success = true;
for (std::size_t i = 0; i < key_cnt; i++) {
success &= insert(filter_data, keys[i]);
}
return success;
}
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// Contains
//===----------------------------------------------------------------------===//
// Scalar code path.
__forceinline__ __host__ __device__
bool
contains(const word_t* __restrict filter_data, const key_t& key) const {
uint32_t i1, i2;
uint32_t tag;
generate_index_tag_hash(key, &i1, &tag);
i2 = alt_index(i1, tag);
assert(i1 == alt_index(i2, tag));
const victim_cache_t& victim = *reinterpret_cast<const victim_cache_t*>(&filter_data[victim_cache_offset]);
bool found = victim.used && (tag == victim.tag) &&
(i1 == victim.index || i2 == victim.index);
return found | table.find_tag_in_buckets(filter_data, i1, i2, tag);
}
// Vectorized code path.
template<typename Tv, typename = std::enable_if_t<dtl::is_vector<Tv>::value>>
__forceinline__ __host__
typename dtl::vec<uint32_t, dtl::vector_length<Tv>::value>::mask
contains_vec(const word_t* __restrict filter_data, const Tv& keys) const {
Tv i1 = block_addr.get_block_idxs(dtl::hasher<Tv, 0>::hash(keys));
Tv tags = tag_hash(dtl::hasher<Tv, 1>::hash(keys));
Tv i2 = alt_index(i1, tags);
auto found_mask = Tv::mask::make_none_mask();
const victim_cache_t& victim = *reinterpret_cast<const victim_cache_t*>(&filter_data[victim_cache_offset]);
if (victim.used) {
auto found_in_victim_cache = (tags == victim.tag) & ((i1 == victim.index) | (i2 == victim.index));
found_mask |= found_in_victim_cache;
}
found_mask |= table.find_tag_in_buckets(filter_data, i1, i2, tags);
return found_mask;
}
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// Batch-wise Contains
//===----------------------------------------------------------------------===//
template<u64 vector_len = dtl::simd::lane_count<u32>>
$u64
batch_contains(const word_t* __restrict filter_data,
const key_t* __restrict keys, u32 key_cnt,
$u32* __restrict match_positions, u32 match_offset) const {
// determine whether a SIMD implementation is available
constexpr u64 actual_vector_len = table_t<bits_per_tag, tags_per_bucket>::is_vectorized
? vector_len
: 0;
return internal::batch_contains<cuckoofilter_logic, actual_vector_len>
::dispatch(*this, filter_data,
keys, key_cnt,
match_positions, match_offset);
}
$u64
batch_contains_scalar(const word_t* __restrict filter_data,
const key_t* keys, u32 key_cnt,
$u32* match_positions, u32 match_offset) const {
$u32* match_writer = match_positions;
$u32 i = 0;
if (key_cnt >= 4) {
for (; i < key_cnt - 4; i += 4) {
u1 is_match_0 = contains(filter_data, keys[i]);
u1 is_match_1 = contains(filter_data, keys[i + 1]);
u1 is_match_2 = contains(filter_data, keys[i + 2]);
u1 is_match_3 = contains(filter_data, keys[i + 3]);
*match_writer = i + match_offset;
match_writer += is_match_0;
*match_writer = (i + 1) + match_offset;
match_writer += is_match_1;
*match_writer = (i + 2) + match_offset;
match_writer += is_match_2;
*match_writer = (i + 3) + match_offset;
match_writer += is_match_3;
}
}
for (; i < key_cnt; i++) {
u1 is_match = contains(filter_data, keys[i]);
*match_writer = i + match_offset;
match_writer += is_match;
}
return match_writer - match_positions;
}
template<
std::size_t vector_len = dtl::simd::lane_count<u32>
>
__attribute_noinline__ $u64
batch_contains_vec(const word_t* __restrict filter_data,
const key_t* keys, u32 key_cnt,
$u32* match_positions, u32 match_offset) const {
using vec_t = dtl::vec<key_t, vector_len>;
const key_t* reader = keys;
$u32* match_writer = match_positions;
// Determine the number of keys that need to be probed sequentially, due to alignment.
u64 required_alignment_bytes = vec_t::byte_alignment;
u64 t = dtl::mem::is_aligned(reader) // should always be true
? (required_alignment_bytes - (reinterpret_cast<uintptr_t>(reader) % required_alignment_bytes)) / sizeof(key_t) // FIXME first elements are processed sequentially even if aligned
: key_cnt;
u64 unaligned_key_cnt = std::min(static_cast<$u64>(key_cnt), t);
// Process the unaligned keys sequentially.
$u64 read_pos = 0;
for (; read_pos < unaligned_key_cnt; read_pos++) {
u1 is_match = contains(filter_data, *reader);
*match_writer = static_cast<$u32>(read_pos) + match_offset;
match_writer += is_match;
reader++;
}
// Process the aligned keys vectorized.
u64 aligned_key_cnt = ((key_cnt - unaligned_key_cnt) / vector_len) * vector_len;
for (; read_pos < (unaligned_key_cnt + aligned_key_cnt); read_pos += vector_len) {
const auto mask = contains_vec(filter_data, *reinterpret_cast<const vec_t*>(reader));
u64 match_cnt = mask.to_positions(match_writer, read_pos + match_offset);
match_writer += match_cnt;
reader += vector_len;
}
// Process remaining keys sequentially.
for (; read_pos < key_cnt; read_pos++) {
u1 is_match = contains(filter_data, *reader);
*match_writer = static_cast<$u32>(read_pos) + match_offset;
match_writer += is_match;
reader++;
}
return match_writer - match_positions;
}
//===----------------------------------------------------------------------===//
/// Returns the size of the filter in number of words.
__forceinline__ __host__ __device__
std::size_t
word_cnt() const {
return table.word_cnt() + ((sizeof(victim_cache_t) + (sizeof(word_t) - 1)) / sizeof(word_t));
}
std::size_t
size_in_bytes() const {
return table_t<bits_per_tag, tags_per_bucket>::bytes_per_bucket * table.num_buckets_;
}
std::size_t
count_occupied_slots(const word_t* __restrict filter_data) const {
const victim_cache_t& victim = *reinterpret_cast<const victim_cache_t*>(&filter_data[victim_cache_offset]);
return table.count_occupied_entires(filter_data) + victim.used;
}
std::size_t
get_bucket_count() const {
return table.num_buckets();
}
std::size_t
get_slot_count() const {
return table.size_in_tags() + 1 /* victim cache */;
}
std::size_t
get_tags_per_bucket() const {
return tags_per_bucket;
}
std::size_t
get_bits_per_tag() const {
return bits_per_tag;
}
};
//===----------------------------------------------------------------------===//
} // namespace cuckoofilter
} // namespace dtl
|
//loads sounds structures into specified container
/*
void Loader::loadSounds(SoundContainer& container) {
container.reserve(Counters::sounds);
container.push_back(new Sound(0, "No_new Sound"));
container.push_back(new Sound(1, "FireBlast"));
container.push_back(new Sound(1, "FireballMove"));
container.push_back(new Sound(1, "EnchantCast"));
container.push_back(new Sound(1, "BurnCast"));
container.push_back(new Sound(1, "CounterSpellCast"));
container.push_back(new Sound(1, "DispellUndeadCast"));
container.push_back(new Sound(1, "EboltCast"));
container.push_back(new Sound(2, "EboltFire"));
container.push_back(new Sound(1, "EarthquakeCast"));
container.push_back(new Sound(1, "ForceFieldOn"));
container.push_back(new Sound(1, "ForceFieldOff"));
container.push_back(new Sound(1, "AnchorOn"));
container.push_back(new Sound(1, "AnchorOff"));
container.push_back(new Sound(1, "DeathRayCast"));
container.push_back(new Sound(1, "LightningCast"));
container.push_back(new Sound(2, "LightningFire"));
container.push_back(new Sound(1, "ProtectionOn"));
container.push_back(new Sound(1, "ProtectionOff"));
container.push_back(new Sound(1, "Heal"));
container.push_back(new Sound(1, "GHealOn"));
container.push_back(new Sound(1, "GHealOff"));
container.push_back(new Sound(1, "HasteOn"));
container.push_back(new Sound(1, "HasteOff"));
container.push_back(new Sound(1, "Inversion"));
container.push_back(new Sound(1, "MissilesMove"));
container.push_back(new Sound(1, "MissilesBlast"));
container.push_back(new Sound(1, "ManaDrain"));
container.push_back(new Sound(1, "ManaAbsorb"));
container.push_back(new Sound(1, "ManaDrainCast"));
container.push_back(new Sound(1, "ManaBurn"));
container.push_back(new Sound(1, "Pull"));
container.push_back(new Sound(1, "Push"));
container.push_back(new Sound(1, "RSOn"));
container.push_back(new Sound(1, "RSOff"));
container.push_back(new Sound(1, "ShockOn"));
container.push_back(new Sound(1, "ShockOff"));
container.push_back(new Sound(3, "RingOfFireCast"));
container.push_back(new Sound(1, "SlowOn"));
container.push_back(new Sound(1, "SlowOff"));
container.push_back(new Sound(1, "Teleport"));
container.push_back(new Sound(1, "Swap"));
container.push_back(new Sound(1, "WallOn"));
container.push_back(new Sound(1, "WallHurt"));
container.push_back(new Sound(1, "WallOff"));
container.push_back(new Sound(1, "FistCast"));
container.push_back(new Sound(1, "FistFall"));
container.push_back(new Sound(1, "VampirismOn"));
container.push_back(new Sound(1, "VampirismOff"));
container.push_back(new Sound(1, "StunOn"));
container.push_back(new Sound(1, "StunOff"));
container.push_back(new Sound(1, "ToxicCloudCast"));
container.push_back(new Sound(1, "ForceOfNatureCast"));
container.push_back(new Sound(1, "ForceOfNatureMove"));
container.push_back(new Sound(1, "PixiesCast"));
container.push_back(new Sound(2, "PixieHit"));
container.push_back(new Sound(1, "CharmCast"));
container.push_back(new Sound(1, "CharmSuccess"));
container.push_back(new Sound(1, "CharmFail"));
container.push_back(new Sound(1, "MeteorCast"));
container.push_back(new Sound(1, "MeteorFall"));
container.push_back(new Sound(1, "PoisonOn"));
container.push_back(new Sound(1, "PoisonOff"));
container.push_back(new Sound(1, "HammerStrike"));
container.push_back(new Sound(2, "LongSwordStrike"));
container.push_back(new Sound(3, "BowShot"));
container.push_back(new Sound(1, "FireStaffShot"));
container.push_back(new Sound(1, "TripleStaffShot"));
container.push_back(new Sound(1, "ShurikenThrow"));
container.push_back(new Sound(1, "ShurikenMove"));
container.push_back(new Sound(1, "FireSpark"));
container.push_back(new Sound(1, "ArrowMove"));
container.push_back(new Sound(1, "EnchantMove"));
container.push_back(new Sound(1, "PixieMove"));
container.push_back(new Sound(6, "Poison"));
container.push_back(new Sound(1, "ForceFieldHit"));
container.push_back(new Sound(1, "FONReflect"));
container.push_back(new Sound(1, "RSReflect"));
container.push_back(new Sound(1, "NullOn"));
container.push_back(new Sound(1, "NullOff"));
container.push_back(new Sound(1, "ShockHit"));
container.push_back(new Sound(1, "WallCrush"));
container.push_back(new Sound(2, "ShieldHit"));
container.push_back(new Sound(1, "NoMana"));
container.push_back(new Sound(1, "Berserker"));
container.push_back(new Sound(1, "HarpoonReleased"));
container.push_back(new Sound(1, "HarpoonCut"));
container.push_back(new Sound(1, "HarpoonHooked"));
container.push_back(new Sound(1, "WarCry"));
container.push_back(new Sound(1, "gesture_UN"));
container.push_back(new Sound(1, "gesture_KA"));
container.push_back(new Sound(1, "gesture_ET"));
container.push_back(new Sound(1, "gesture_RO"));
container.push_back(new Sound(1, "gesture_ZO"));
container.push_back(new Sound(1, "gesture_DO"));
container.push_back(new Sound(1, "gesture_CHA"));
container.push_back(new Sound(1, "gesture_IN"));
}*/
|
#ifndef SRC_PT_PTUNARYOP_H
#define SRC_PT_PTUNARYOP_H
/// @file src/pt/PtUnaryOp.h
/// @brief PtUnaryOp のヘッダファイル
/// @author Yusuke Matsunaga (松永 裕介)
///
/// Copyright (C) 2005-2011 Yusuke Matsunaga
/// All rights reserved.
#include "PtNode.h"
BEGIN_NAMESPACE_YM_BB
//////////////////////////////////////////////////////////////////////
/// @class PtUnaryOp PtUnaryOp.h "PtUnaryOp.h"
/// @brief 単項演算子の基底クラス
//////////////////////////////////////////////////////////////////////
class PtUnaryOp :
public PtNode
{
public:
/// @brief コンストラクタ
/// @param[in] file_region ファイル上の位置
/// @param[in] opr1 オペランド
PtUnaryOp(const FileRegion& file_region,
PtNode* opr1);
/// @brief デストラクタ
virtual
~PtUnaryOp();
public:
//////////////////////////////////////////////////////////////////////
// PtNode の仮想関数
//////////////////////////////////////////////////////////////////////
/// @brief オペランド数を返す.
virtual
ymuint
operand_num() const;
/// @brief オペランドを返す.
/// @param[in] pos 位置番号 ( 0 <= pos < operand_num() )
virtual
PtNode*
operand(ymuint pos) const;
private:
//////////////////////////////////////////////////////////////////////
// データメンバ
//////////////////////////////////////////////////////////////////////
PtNode* mOpr1;
};
END_NAMESPACE_YM_BB
#endif // SRC_PT_PTUNARYOP_H
|
#ifndef __RESOURCE_CONVERTER__
#define __RESOURCE_CONVERTER__
#include "Common.h"
#include "FileUtils.h"
class ResourceConverter
{
public:
static bool Generate( StrVec* resource_names );
private:
static File* Convert( const string& name, File& file );
static File* ConvertImage( const string& name, File& file );
static File* Convert3d( const string& name, File& file );
};
#endif // __RESOURCE_CONVERTER__
|
#ifndef SUPERHERO_H
#define SUPERHERO_H
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
class Superhero
{
private:
string name;
int age;
char superpower;
public:
Superhero();
Superhero(string name, int age, char superpower);
friend istream& operator >>(istream& in, Superhero& superhero);
friend ostream& operator << (ostream& out, const Superhero& superhero);
// void set_name(Superhero superhero, string new_name);
};
#endif // SUPERHERO_H
|
/*
Author: Nayeemul Islam Swad
Idea:
- https://codeforces.com/blog/entry/70720
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned int uint;
typedef pair<int, int> pii;
#define x first
#define y second
#ifdef LOCAL
#include "debug.h"
#endif
const int N = int(1e5) + 10;
int n, p;
list<int> que;
set<int> waitlist;
set<array<ll, 3>> timeline;
ll ans[N];
int main() {
#ifdef LOCAL
freopen("in", "r", stdin);
freopen("out", "w", stdout);
#endif
scanf("%d %d", &n, &p);
for (int i = 1; i <= n; i++) {
int t;
scanf("%d", &t);
timeline.insert(array<ll, 3>{t, 0, i});
}
ll at_time;
while (!timeline.empty()) {
array<ll, 3> curr = *timeline.begin();
timeline.erase(timeline.begin());
at_time = curr[0];
int event_type = curr[1];
int person_id = curr[2];
if (event_type == 0) {
if (que.empty()) {
que.push_back(person_id);
timeline.insert(array<ll, 3>{at_time + p, 1, person_id});
}
else if (person_id < que.back()) que.push_back(person_id);
else waitlist.insert(person_id);
}
else {
ans[person_id] = at_time;
que.pop_front();
if (!que.empty()) {
timeline.insert(array<ll, 3>{at_time + p, 1, que.front()});
}
else if (!waitlist.empty()) {
person_id = *waitlist.begin();
waitlist.erase(waitlist.begin());
que.push_back(person_id);
timeline.insert(array<ll, 3>{at_time + p, 1, person_id});
}
}
}
for (int person_id : waitlist) {
at_time += p;
ans[person_id] = at_time;
}
for (int i = 1; i <= n; i++) {
printf("%lld", ans[i]);
if (i < n) printf(" ");
else printf("\n");
}
return 0;
}
|
//
// Created by Peter Chen on 5/29/16.
//
#ifndef CUBEWORLD_AVATARCOMPONENTAI_H
#define CUBEWORLD_AVATARCOMPONENTAI_H
class AvatarComponentAI {
};
#endif //CUBEWORLD_AVATARCOMPONENTAI_H
|
#include<eosiolib/eosio.hpp>
#include<eosiolib/print.hpp>
using namespace eosio;
using namespace std;
using std::string;
class invent : public eosio::contract
{
public:
using contract::contract;
///@abi table admin i64
struct admin
{
account_name id;
string name;
uint64_t amount;
uint64_t primary_key() const {return id; }
};
EOSLIB_SERIALIZE(admin,(id)(name)(amount))
typedef multi_index<N(admin),admin> admin1;
///@abi action
void adminreg(account_name id,string name)
{
admin1 ad(_self,_self);
auto i = ad.find(id);
if(i==ad.end())
{
ad.emplace(_self,[&](auto& admin)
{
admin.id=id;
admin.name=name;
admin.amount=0;
});
}
}
///@abi table cust i64
struct cust
{
account_name id;
string name;
uint64_t amount;
uint64_t primary_key() const {return id; }
};
EOSLIB_SERIALIZE(cust,(id)(name)(amount))
typedef multi_index<N(cust),cust> cust1;
///@abi action
void customer(account_name id,string name,uint64_t amount)
{
cust1 ad(_self,_self);
auto i = ad.find(id);
if(i==ad.end())
{
ad.emplace(_self,[&](auto& cust)
{
cust.id=id;
cust.name=name;
cust.amount=amount;
});
}
}
///@abi table sp i64
struct sp
{
account_name id;
string pname;
uint64_t qty;
uint64_t price;
uint64_t primary_key() const {return id; }
};
EOSLIB_SERIALIZE(sp,(id)(pname)(qty)(price))
typedef multi_index<N(sp),sp> sp1;
///@abi action
void setproducts(account_name id,account_name aid,string name,uint64_t qty,uint64_t price)
{
admin1 ad1(_self,_self);
auto i1 = ad1.find(aid);
if(i1!=ad1.end())
{
sp1 ad(_self,_self);
auto i = ad.find(id);
if(i==ad.end())
{
ad.emplace(_self,[&](auto& sp)
{
sp.id=id;
sp.pname=name;
sp.qty=qty;
sp.price=price;
});
}
}
}
///@abi action
void getproducts(account_name id,account_name aid,account_name cid,uint64_t qty,uint64_t amt)
{
sp1 ad(_self,_self);
auto i = ad.find(id);
if(i!=ad.end())
{
ad.modify(i,_self,[&](auto& sp)
{
if(sp.id==id)
{
sp.qty-=qty;
}
});
}
int a=0;
cust1 ad1(_self,_self);
auto it = ad1.find(cid);
if(it!=ad1.end())
{
ad1.modify(it,_self,[&](auto& cust)
{
cust.amount-=amt;
a=1;
});
}
admin1 ad2(_self,_self);
auto itr = ad2.find(aid);
if(itr!=ad2.end())
{
ad2.modify(itr,_self,[&](auto& admin)
{
if(a==1)
{
admin.amount=+amt;
}
});
}
}
};
EOSIO_ABI(invent,(adminreg)(customer)(setproducts)(getproducts))
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
int Solution::solve(ListNode* A, int B) {
int len=0;
ListNode* head=A;
while(A)
{
len++;
A=A->next;
}
if((len/2)+1-B<=0)return -1;
int target=((len/2)+1)-B-1;
while(target)
{
target--;
head=head->next;
}
return head->val;
}
|
%{Cpp:LicenseTemplate}\
#ifndef %{GUARD}
#define %{GUARD}
#include <Cutelyst/Application>
using namespace Cutelyst;
class %{ProjectName} : public Application
{
Q_OBJECT
CUTELYST_APPLICATION(IID "%{ProjectName}")
public:
Q_INVOKABLE explicit %{ProjectName}(QObject *parent = nullptr);
~%{ProjectName}();
bool init() override;
};
#endif // %{GUARD}\
|
#ifndef GBMSOLVER_H
#define GBMSOLVER_H
/// @file GbmSolver.h
/// @brief GbmSolver のヘッダファイル
/// @author Yusuke Matsunaga (松永 裕介)
///
/// Copyright (C) 2013 Yusuke Matsunaga
/// All rights reserved.
#include "YmTools.h"
#include "YmLogic/TvFunc.h"
BEGIN_NAMESPACE_YM
class RcfNetwork;
//////////////////////////////////////////////////////////////////////
/// @class GbmSolver GbmSolver.h "GbmSolver.h"
/// @brief GBM を解くクラス
//////////////////////////////////////////////////////////////////////
class GbmSolver
{
public:
/// @brief コンストラクタ
GbmSolver();
/// @brief デストラクタ
virtual
~GbmSolver();
/// @brief 派生クラスを作るクラスメソッド
/// @param[in] method 手法を表す文字列
static
GbmSolver*
new_solver(const string& method = string());
public:
//////////////////////////////////////////////////////////////////////
// 外部インターフェイス
//////////////////////////////////////////////////////////////////////
/// @brief verify フラグを立てる
void
verify_on();
/// @brief verify フラグを降ろす
void
verify_off();
/// @brief debug フラグを立てる.
void
debug_on();
/// @brief debug フラグを降ろす.
void
debug_off();
/// @brief debug フラグを得る.
bool
debug() const;
/// @brief 入力順を考慮したマッチング問題を解く
/// @param[in] networrk RcfNetwork
/// @param[in] func マッチング対象の関数
/// @param[out] conf_bits configuration ビットの値を収める配列
/// @param[out] iorder 入力順序
/// iorder[pos] に network の pos 番めの入力に対応した
/// 関数の入力番号が入る.
bool
solve(const RcfNetwork& network,
const TvFunc& func,
vector<bool>& conf_bits,
vector<ymuint>& iorder,
ymuint& loop_count);
private:
//////////////////////////////////////////////////////////////////////
// 内部で用いられる関数
//////////////////////////////////////////////////////////////////////
/// @brief 入力順を考慮したマッチング問題を解く
/// @param[in] network RcfNetwork
/// @param[in] output Reconfigurable Network の出力
/// @param[in] func マッチング対象の関数
/// @param[in] rep 関数の対称変数の代表番号を収める配列
/// rep[pos] に pos 番めの入力の代表番号が入る.
/// @param[out] conf_bits configuration ビットの値を収める配列
/// @param[out] iorder 入力順序
/// iorder[pos] に network の pos 番めの入力に対応した
/// 関数の入力番号が入る.
virtual
bool
_solve(const RcfNetwork& network,
const TvFunc& func,
const vector<ymuint>& rep,
vector<bool>& conf_bits,
vector<ymuint>& iorder,
ymuint& loop_count) = 0;
/// @brief 検証を行う.
/// @param[in] network RcfNetwork
/// @param[in] func マッチング対象の関数
/// @param[in] conf_bits configuration ビットの値を収める配列
/// @param[in] iorder 入力順序
/// iorder[pos] に network の pos 番めの入力に対応した
/// 関数の入力番号が入る.
bool
verify(const RcfNetwork& network,
const TvFunc& func,
const vector<bool>& conf_bits,
const vector<ymuint>& iorder);
private:
//////////////////////////////////////////////////////////////////////
// データメンバ
//////////////////////////////////////////////////////////////////////
// verify フラグ
bool mVerify;
// debug フラグ
bool mDebug;
};
END_NAMESPACE_YM
#endif // GBMSOLVER_H
|
#include <SoftwareSerial.h>
#include <string.h>
#include "Motor.h"
#include "Driver.h"
#include "Sensor.h"
#include "Schedule.h"
#include "Logic.h"
#include "Map.h"
//motor pins
#define RMOTA 23
#define RMOTB 22
#define LMOTA 21
#define LMOTB 20
//sensors
#define LSENSOR 17
#define RSENSOR 16
#define LDSENSOR 5
#define RDSENSOR 4
#define FSENSOR 15
#define BSENSOR 0
//other pins
#define RX 9
#define TX 10
//commands
#define STOP 0
#define START 1
#define ASERIAL
Motor motorRight(RMOTA, RMOTB, 1, 0);
Motor motorLeft(LMOTA, LMOTB, 3, 2);
Sensor front(FSENSOR, IR);
Sensor back(BSENSOR, IR);
Sensor right(RSENSOR, IRSHORTR);
Sensor left(LSENSOR, IRSHORTL);
Sensor rightD(RDSENSOR, IRD);
Sensor leftD(LDSENSOR, IRD);
//GyroAccl gyro;
Driver driver(&motorLeft, &motorRight, &front, &back, &right, &left, &rightD, &leftD);
Schedule schedule(&driver, &front, &back, &right, &left, &rightD, &leftD);
Map gMap(&driver);
Logic logic(&driver, &gMap);
SoftwareSerial xbee(RX, TX);
//Queue<char> commandQ;
char currCString[200];
//char* currString = malloc(200*sizeof(char));
//currString[0] = '\0';
//String currString;
volatile short command = START;
void setup() {
schedule.init();
pinMode(13, OUTPUT);
digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)
driver.init();
gMap.init(12, 13, 23, 24, UP);
randomSeed(analogRead(A0));
xbee.begin(9600);
//while(!Serial) { }
//testing();
}
volatile int startUpTime = 2000;
void loop() {
if(startUpTime > 0) {
schedule.updateSensorsOnly();
//xxbee.println(startUpTime);
startUpTime--;
}
else {
//getCommand();
if(command == START) {
schedule.update();
logic.update();
Serial.println(front.distance);
}
else if(command == STOP) {
driver.freeze();
}
// /sendCurrentCoor();
}
}
//char tempQ;
//void getCommand() {
// while(xbee.available() <= 1 && command == STOP) { }
// while(xbee.available() > 0) {
// tempQ = xbee.read();
// Serial.print(tempQ);
// if(tempQ != ';')
// commandQ.push(tempQ);
// else
// interpret();
// }
//}
int ii = 0;
int stringLen = 0;
bool firstTime = true;
char tempChar;
void getCommand(){
while(xbee.available() <= 1 && command == STOP) { }
while(xbee.available() > 0) {
tempChar = xbee.read();
if (firstTime == true){
firstTime = false;
}
else if(tempChar == '$'){
stringLen = ii;
ii = 0;
command = START;
interpret();
//currCString[0] = '\0';
}
else if(tempChar == 's') {
command = STOP;
}
//Serial.println(ii);
currCString[ii] = tempChar;
//Serial.println();
ii++;
}
}
void sendCurrentCoor() {
xbee.print(gMap.pac->x1);
xbee.print(" ");
xbee.print(gMap.pac->x2);
xbee.print(" ");
xbee.print(gMap.pac->y1);
xbee.print(" ");
xbee.print(gMap.pac->y1);
xbee.println();
}
//void interpret() {
// char c;
// while(commandQ.size > 0) {
// c = commandQ.pop();
// if(c == 0) {
//// command = START;
//// reset();
// }
// else if(c == 1) {
//// command = STOP;
//// logic.mode = DEAD;
// driver.Kill();
// }
//
// }
// commandQ.reset();
//}
int timer = 0, pos, prevPos = 1;
char delim = '#';
String token;
#define blinky (&gMap.ghosts[0].pos)
#define pinky (&gMap.ghosts[1].pos)
#define clyde (&gMap.ghosts[2].pos)
#define inky (&gMap.ghosts[3].pos)
void interpret(){
String currString(currCString);
//Serial.println(currString);
//Serial.println(currCString);
pos = 0; prevPos = 1;
timer = 0;
if(stringLen == 0){
return;
}
if (stringLen < 4){
command = STOP;
return;
}
//erase first char
pos = currString.indexOf(delim, prevPos);
token = currString.substring(prevPos, pos);
gMap.pac->x = atoi(token.c_str());
prevPos = pos+1;
pos = currString.indexOf(delim, prevPos);
token = currString.substring(prevPos, pos);
gMap.pac->y = atoi(token.c_str());
prevPos = pos+1;
pos = currString.indexOf(delim, prevPos);
token = currString.substring(prevPos, pos);
blinky->x = atoi(token.c_str());
prevPos = pos+1;
pos = currString.indexOf(delim, prevPos);
token = currString.substring(prevPos, pos);
blinky->y = atoi(token.c_str());
prevPos = pos+1;
pos = currString.indexOf(delim, prevPos);
token = currString.substring(prevPos, pos);
pinky->x = atoi(token.c_str());
prevPos = pos+1;
pos = currString.indexOf(delim, prevPos);
token = currString.substring(prevPos, pos);
pinky->y = atoi(token.c_str());
prevPos = pos+1;
pos = currString.indexOf(delim, prevPos);
token = currString.substring(prevPos, pos);
clyde->x = atoi(token.c_str());
prevPos = pos+1;
pos = currString.indexOf(delim, prevPos);
token = currString.substring(prevPos, pos);
clyde->y = atoi(token.c_str());
prevPos = pos+1;
pos = currString.indexOf(delim, prevPos);
token = currString.substring(prevPos, pos);
inky->x = atoi(token.c_str());
prevPos = pos+1;
pos = currString.indexOf(delim, prevPos);
token = currString.substring(prevPos, pos);
inky->y = atoi(token.c_str());
prevPos = pos+1;
if (pos != stringLen){
pos = currString.indexOf(delim, prevPos);
token = currString.substring(prevPos, pos);
timer = atoi(token.c_str());
}
// gMap.pac->printd();
// blinky->printd();
// pinky->printd();
// clyde->printd();
// inky->printd();
// Serial.println(timer);
// Serial.println(command == START);
}
void reset() {
gMap.init(14, 14, 23, 24, UP);
gMap.reset();
driver.status = SLEEP;
}
void testing() {
Serial.println("testing");
// vector<5> p;
// p[0] = 26;
// p[1] = 27;
// p[2] = 20;
// p[3] = 21 ;
// vector<5> d;
// d[0] = 26;
// d[1] = 27;
// d[2] = 8;
// d[3] = 9;
// PathAl g;
// vector<2> dir;
// dir[0] = 0;
// dir[1] = -1;
// vector<5> n;
// g.projectMod(p, dir, &gMap, 0, &n);
// unsigned long a = micros();
// g.shortestPathD(p, d, &gMap);
// //unsigned long a = micros();
// //logic.simpleAI();
// a = micros()- a;
// Serial.println(a);
Pos a(9, 10, 17, 18, RIGHT);
Pos b(18, 19, 17, 18, LEFT);
gMap.eatFood(&a, &b);
}
|
#ifndef _HS_SFM_PROJECTIVE_MLE_CERES_OPTIMIZOR_HPP_
#define _HS_SFM_PROJECTIVE_MLE_CERES_OPTIMIZOR_HPP_
#include <ceres/problem.h>
#include <ceres/ceres.h>
#include <ceres/rotation.h>
#include "hs_sfm/projective/mle/intrinsic_constrained_vector_function.hpp"
#include "hs_sfm/projective/mle/intrinsic_constrained_y_covariance_inverse.hpp"
namespace hs
{
namespace sfm
{
namespace projective
{
class IntrinsicConstrainedProjection
{
public:
IntrinsicConstrainedProjection(
const std::vector<double>& observes,
const std::vector<double>& covariants,
const std::vector<double>& points)
: observes_(observes)
, covariants_(covariants)
, points_(points) {}
template <typename T>
bool operator() (const T* const x, T* residuals) const
{
size_t number_of_points = points_.size() / 3;
if (number_of_points != observes_.size() / 2 ||
number_of_points != covariants_.size() / 4) return false;
for (size_t i = 0; i < number_of_points; i++)
{
T rotation[3];
rotation[0] = x[0];
rotation[1] = x[1];
rotation[2] = x[2];
T point[3];
point[0] = T(points_[i * 3 + 0]);
point[1] = T(points_[i * 3 + 1]);
point[2] = T(points_[i * 3 + 2]);
T camera_point[3];
ceres::AngleAxisRotatePoint(rotation, point, camera_point);
camera_point[0] += x[3];
camera_point[1] += x[4];
camera_point[2] += x[5];
T normalized_x = camera_point[0] / camera_point[2];
T normalized_y = camera_point[1] / camera_point[2];
T r2 = normalized_x * normalized_x + normalized_y * normalized_y;
T r4 = r2 * r2;
T r6 = r2 * r4;
T radial_coeff = x[11] * r2 + x[12] * r4 + x[13] * r6;
T radial_x = radial_coeff * normalized_x;
T radial_y = radial_coeff * normalized_y;
T decentering_x = 2.0 * x[14] * normalized_x * normalized_y +
x[15] * (r2 + 2.0 * normalized_x * normalized_x);
T decentering_y = 2.0 * x[15] * normalized_x * normalized_y +
x[14] * (r2 + 2.0 * normalized_y * normalized_y);
T image_x = x[6] * normalized_x + x[7] * normalized_y + x[8];
T image_y = x[6] * x[10] * normalized_y + x[9];
T diff_x = image_x - T(observes_[i * 2 + 0]);
T diff_y = image_y - T(observes_[i * 2 + 1]);
T cov_inv_00 = T(covariants_[i * 4 + 0]);
T cov_inv_01 = T(covariants_[i * 4 + 1]);
T cov_inv_10 = T(covariants_[i * 4 + 2]);
T cov_inv_11 = T(covariants_[i * 4 + 3]);
residuals[i * 2 + 0] = T(cov_inv_00) * diff_x + T(cov_inv_01) * diff_y;
residuals[i * 2 + 1] = T(cov_inv_10) * diff_x + T(cov_inv_11) * diff_y;
}
return true;
}
static ceres::CostFunction* Create(
const std::vector<double>& observes,
const std::vector<double>& covariants,
const std::vector<double>& points)
{
return (new ceres::AutoDiffCostFunction<
IntrinsicConstrainedProjection, ceres::DYNAMIC, 16>(
new IntrinsicConstrainedProjection(observes, covariants, points),
int(observes.size())));
}
protected:
const std::vector<double>& observes_;
const std::vector<double>& covariants_;
const std::vector<double>& points_;
};
template <typename _VectorFunction>
class IntrinsicConstrainedCeresOptimizor;
template <typename _Scalar>
class IntrinsicConstrainedCeresOptimizor<
IntrinsicConstrainedVectorFunction<_Scalar> >
{
public:
typedef _Scalar Scalar;
typedef int Err;
typedef IntrinsicConstrainedVectorFunction<Scalar> VectorFunction;
typedef typename VectorFunction::XVector XVector;
typedef typename VectorFunction::YVector YVector;
typedef IntrinsicConstrainedYCovarianceInverse<Scalar> YCovarianceInverse;
private:
typedef typename VectorFunction::Index Index;
typedef typename YCovarianceInverse::KeyBlock KeyBlock;
public:
IntrinsicConstrainedCeresOptimizor(const XVector& initial_x)
: initial_x_(initial_x) {}
Err operator() (const VectorFunction& vector_function,
const YVector& near_y,
const YCovarianceInverse& y_covariance_inverse,
XVector& optimized_x) const
{
Index x_size = vector_function.GetXSize();
if (initial_x_.rows() != x_size)
{
return -1;
}
optimized_x = initial_x_;
double* x_data = nullptr;
EIGEN_VECTOR(double, Eigen::Dynamic) casted_x;
if (!std::is_same<Scalar, double>::value)
{
casted_x = optimized_x.template cast<double>();
x_data = casted_x.data();
}
else
{
x_data = optimized_x.data();
}
ceres::Problem problem;
size_t number_of_points = vector_function.points().size();
double expected_focal_length = near_y[Index(number_of_points) * 2 + 0];
double expected_skew = near_y[Index(number_of_points) * 2 + 1];
double expected_principal_x = near_y[Index(number_of_points) * 2 + 2];
double expected_principal_y = near_y[Index(number_of_points) * 2 + 3];
double expected_pixel_ratio = near_y[Index(number_of_points) * 2 + 4];
double expected_k1 = near_y[Index(number_of_points) * 2 + 5];
double expected_k2 = near_y[Index(number_of_points) * 2 + 6];
double expected_k3 = near_y[Index(number_of_points) * 2 + 7];
double expected_d1 = near_y[Index(number_of_points) * 2 + 8];
double expected_d2 = near_y[Index(number_of_points) * 2 + 9];
std::vector<double> observes;
std::vector<double> covariants;
std::vector<double> points;
for (size_t i = 0; i < number_of_points; i++)
{
observes.push_back(double(near_y[i * 2 + 0]));
observes.push_back(double(near_y[i * 2 + 1]));
const KeyBlock& key_block = y_covariance_inverse.key_blocks[i];
covariants.push_back(double(key_block(0, 0)));
covariants.push_back(double(key_block(0, 1)));
covariants.push_back(double(key_block(1, 0)));
covariants.push_back(double(key_block(1, 1)));
points.push_back(double(vector_function.points()[i][0]));
points.push_back(double(vector_function.points()[i][1]));
points.push_back(double(vector_function.points()[i][2]));
}
ceres::CostFunction* cost_function =
IntrinsicConstrainedProjection::Create(observes, covariants, points);
problem.AddResidualBlock(cost_function, NULL, x_data);
problem.SetParameterLowerBound(
x_data, 6, expected_focal_length -
y_covariance_inverse.focal_length_stddev);
problem.SetParameterUpperBound(
x_data, 6, expected_focal_length +
y_covariance_inverse.focal_length_stddev);
problem.SetParameterLowerBound(
x_data, 7, expected_skew -
y_covariance_inverse.skew_stddev);
problem.SetParameterUpperBound(
x_data, 7, expected_skew +
y_covariance_inverse.skew_stddev);
problem.SetParameterLowerBound(
x_data, 8, expected_principal_x -
y_covariance_inverse.principal_point_x_stddev);
problem.SetParameterUpperBound(
x_data, 8, expected_principal_x +
y_covariance_inverse.principal_point_x_stddev);
problem.SetParameterLowerBound(
x_data, 9, expected_principal_y -
y_covariance_inverse.principal_point_y_stddev);
problem.SetParameterUpperBound(
x_data, 9, expected_principal_y +
y_covariance_inverse.principal_point_y_stddev);
problem.SetParameterLowerBound(
x_data, 10, expected_pixel_ratio -
y_covariance_inverse.pixel_ratio_stddev);
problem.SetParameterUpperBound(
x_data, 10, expected_pixel_ratio +
y_covariance_inverse.pixel_ratio_stddev);
problem.SetParameterLowerBound(
x_data, 11, expected_k1 -
y_covariance_inverse.k1_stddev);
problem.SetParameterUpperBound(
x_data, 11, expected_k1 +
y_covariance_inverse.k1_stddev);
problem.SetParameterLowerBound(
x_data, 12, expected_k2 -
y_covariance_inverse.k2_stddev);
problem.SetParameterUpperBound(
x_data, 12, expected_k2 +
y_covariance_inverse.k2_stddev);
problem.SetParameterLowerBound(
x_data, 13, expected_k3 -
y_covariance_inverse.k3_stddev);
problem.SetParameterUpperBound(
x_data, 13, expected_k3 +
y_covariance_inverse.k3_stddev);
problem.SetParameterLowerBound(
x_data, 14, expected_d1 -
y_covariance_inverse.d1_stddev);
problem.SetParameterUpperBound(
x_data, 14, expected_d1 +
y_covariance_inverse.d1_stddev);
problem.SetParameterLowerBound(
x_data, 15, expected_d2 -
y_covariance_inverse.d2_stddev);
problem.SetParameterUpperBound(
x_data, 15, expected_d2 +
y_covariance_inverse.d2_stddev);
ceres::Solver::Options options;
options.max_num_iterations = 50;
options.function_tolerance = 1e-9;
options.parameter_tolerance = 1e-9;
options.logging_type = ceres::SILENT;
ceres::Solver::Summary summary;
ceres::Solve(options, &problem, &summary);
if (!std::is_same<Scalar, double>::value)
{
optimized_x = casted_x.template cast<Scalar>();
}
return 0;
}
private:
XVector initial_x_;
};
}
}
}
#endif
|
//
// Copyright (C) 2018 Ruslan Manaev (manavrion@yandex.com)
// This file is part of the Modern Expert System
//
#include "pch.h"
|
#include <iostream>
using namespace std;
class Singleton
{
public :
static Singleton * GetInstance() // 静态成员函数构造一个实例
{
// Lock(); // 多线程时(Boost库支持Lock操作)
if (m_Instance == NULL)
{
m_Instance = new Singleton(); // ①
}
// UnLock();// static Singleton m_Instance; // ② 多线程时
return m_Instance;
// return const_cast <Singleton *>(m_Instance); // ③ 常量对象只有一次创建的机会
}
static void DestoryInstance()
{
if (m_Instance != NULL )
{
delete m_Instance;
m_Instance = NULL ;
}
}
// This is just a operation example
int GetTest()
{
return m_Test;
}
private:
Singleton(){ m_Test = 10; } // 构造函数私有
Singleton::Singleton(const Singleton&) {} // 拷贝构造函数私有
Singleton &Singleton::operator=(const Singleton&) {} // 赋值运算符私有
static Singleton* m_Instance; // 静态数据成员用于判断是否存在类实例
int m_Test; // used for test
};
Singleton *Singleton ::m_Instance = NULL;
int main(int argc , char *argv [])
{
Singleton *singletonObj = Singleton ::GetInstance();
cout<<singletonObj->GetTest()<<endl; //10
Singleton ::DestoryInstance();
return 0;
}
|
#include"undirGraphProc.hh"
DepthFirstSearch::DepthFirstSearch(Graph& G, int s){
this->marked=new bool[G.V()];
for(int i=0; i<G.V(); i++){
marked[i]=false;
}
dfs(G,s);
}
DepthFirstSearch::~DepthFirstSearch(void){
delete[] marked;
}
void DepthFirstSearch::dfs(Graph& G, int v){
marked[v]=true;
count++;
MyBag* iterator= G.adjV(v);
iterator->beginIte();
int ite;
while(iterator->hasNext())
if(!marked[(ite=iterator->next())])
dfs(G,ite);
}
//-------DFS to find paths, class implementation
DFSfindPaths::DFSfindPaths(Graph& G, int s){
this->marked=new bool[G.V()];
this->edgeTo=new int[G.V()];
this->path=NULL;
this->s=s;
for(int i=0; i<G.V(); i++){
marked[i]=false;
}
for(int i=0; i<G.V(); i++){
edgeTo[i]=0;
}
dfs(G,s);
}
DFSfindPaths::~DFSfindPaths(void){
delete[] marked;
delete[] edgeTo;
delete path;
}
void DFSfindPaths::dfs(Graph& G, int v){
marked[v]=true;
MyBag* iterator= G.adjV(v);
iterator->beginIte();
int ite;
while(iterator->hasNext())
if(!marked[(ite=iterator->next())]){
edgeTo[ite]=v;
dfs(G,ite);
}
}
MyStack* DFSfindPaths::pathTo(int v){
if(!hasPathTo(v))
path=NULL;
else{
path=new MyStack();
for(int x=v; x!=s; x=edgeTo[x])
path->push(x);
path->push(s);
}
return path;
}
//----Breadth first search for paths class implementation-----
BreadthFirstPaths::BreadthFirstPaths(Graph& G, int s){
this->marked=new bool[G.V()];
this->edgeTo=new int[G.V()];
this->path=NULL;
this->queue=NULL;
this->s=s;
for(int i=0; i<G.V(); i++){
marked[i]=false;
}
for(int i=0; i<G.V(); i++){
edgeTo[i]=0;
}
bfs(G,s);
}
BreadthFirstPaths::~BreadthFirstPaths(void){
delete[] marked;
delete[] edgeTo;
delete path;
delete queue;
}
void BreadthFirstPaths::bfs(Graph& G, int s){
queue=new MyQueue();
marked[s]=true;
queue->enqueue(s);
while(!queue->isEmpty()){
int v=queue->dequeue();
MyBag* iterator= G.adjV(v);
iterator->beginIte();
int ite;
while(iterator->hasNext())
if(!marked[(ite=iterator->next())]){
edgeTo[ite]=v;
marked[ite]=true;
queue->enqueue(ite);
}
}
}
MyStack* BreadthFirstPaths::pathTo(int v){
if(!hasPathTo(v))
path=NULL;
else{
path=new MyStack();
for(int x=v; x!=s; x=edgeTo[x])
path->push(x);
path->push(s);
}
return path;
}
//---DFS to find connected componentes class implementation---
CC::CC(Graph& G){
this->marked=new bool[G.V()];
this->id=new int[G.V()];
this->count=0;
for(int i=0; i<G.V(); i++){
marked[i]=false;
}
for(int i=0; i<G.V(); i++){
id[i]=0;
}
}
CC::~CC(void){
delete[] marked;
delete[] id;
}
void CC::dfs(Graph& G, int v){
marked[v]=true;
id[v]=count;
MyBag* iterator= G.adjV(v);
iterator->beginIte();
int ite;
while(iterator->hasNext())
if(!marked[(ite=iterator->next())]){
dfs(G,ite);
}
}
|
/*************************************************************
* > File Name : P4568.cpp
* > Author : Tony
* > Created Time : 2019/10/17 16:17:46
* > Algorithm : 分层图最短路
**************************************************************/
#include <bits/stdc++.h>
using namespace std;
inline int read() {
int x = 0; int f = 1; char ch = getchar();
while (!isdigit(ch)) {if (ch == '-') f = -1; ch = getchar();}
while (isdigit(ch)) {x = x * 10 + ch - 48; ch = getchar();}
return x * f;
}
const int maxn = 10010;
const int maxl = 15;
struct Edge {
int from, to, val;
Edge(int u, int v, int w): from(u), to(v), val(w) {}
};
vector<Edge> edges;
vector<int> G[maxn];
void add(int u, int v, int w) {
edges.push_back(Edge(u, v, w));
edges.push_back(Edge(v, u, w));
int mm = edges.size();
G[v].push_back(mm - 1);
G[u].push_back(mm - 2);
}
int n, m, k, dis[maxn][maxl];
bool vis[maxn][maxl];
struct heap {
int u, d;
heap(int u, int d): u(u), d(d) {}
bool operator < (const heap& a) const {
return d > a.d;
}
};
void Dijkstra(int s) {
priority_queue<heap> q;
memset(dis, 0x3f, sizeof(dis));
dis[s][0] = 0; q.push(heap(s, 0));
while (!q.empty()) {
heap top = q.top(); q.pop();
int level = top.u / n, u = top.u % n;
if (vis[u][level]) continue;
vis[u][level] = true;
for (int i = 0; i < G[u].size(); ++i) {
Edge& e = edges[G[u][i]];
if (dis[e.to][level] > dis[u][level] + e.val) {
dis[e.to][level] = dis[u][level] + e.val;
q.push(heap(e.to + level * n, dis[e.to][level]));
}
if (level < k && dis[e.to][level + 1] > dis[u][level]) {
dis[e.to][level + 1] = dis[u][level];
q.push(heap(e.to + (level + 1) * n, dis[e.to][level + 1]));
}
}
}
}
int main() {
n = read(); m = read(); k = read();
int s = read(), t = read();
for (int i = 1; i <= m; ++i) {
int u = read(), v = read(), w = read();
add(u, v, w);
}
Dijkstra(s);
int ans = 0x3f3f3f3f;
for (int i = 0; i <= k; ++i) {
ans = min(ans, dis[t][i]);
}
printf("%d\n", ans);
return 0;
}
|
#pragma once
#include "Characters.h"
/** Summary:
According to to variable function encrypt and decrypt. If "to" is true that means right shifting.
Otherwise ıt is left shifting.
*/
class Kaydirma :
public Characters
{
public:
void Encryption(char* mesaj, int key, bool to);
void Decryption(char* mesaj, int key, bool to);
void toRight(char* mesaj, int key);
void toLeft(char* mesaj, int key);
};
|
//
// C++ Implementation: keyboard_dialog
//
// Description:
//
//
// Author: Juan Linietsky <reduz@gmail.com>, (C) 2006
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "bundles/window_box.h"
#include "containers/center_container.h"
#include "containers/box_container.h"
#include "keyboard_dialog.h"
#include "editor/key_bindings.h"
#include "base/keyboard.h"
#include "widgets/separator.h"
#include <stdio.h>
void KeyboardDialog::keybind_selected( int p_which) {
update_kb_text();
}
void KeyboardDialog::update_kb_text() {
int idx=list->get_selected();
if (idx<0)
return;
unsigned int bind=KeyBind::get_keybind_code( idx );
if (bind==NO_BIND)
bind_string->set_text("No KeyBind");
else
bind_string->set_text( Keyboard::get_code_name( bind ) );
}
void KeyboardDialog::update_keybind_list() {
bind_string->clear();
list->clear();
for(int i=0;i<KeyBind::get_keybind_count();i++) {
list->add_string( KeyBind::get_keybind_description(i));
}
}
void KeyboardDialog::kb_change_ok() {
int idx=list->get_selected();
if (idx<0)
return;
kb_change_window->hide();
KeyBindList bind_exists=KeyBind::get_bind(kb_change_last);
if (bind_exists!=KB_MAX && bind_exists!=idx) {
mb->show( Keyboard::get_code_name( kb_change_last ) + String(" Already assigned to: ")+KeyBind::get_keybind_description(bind_exists) );
return;
}
KeyBind::set_keybind_code(idx,kb_change_last);
update_kb_text();
}
void KeyboardDialog::key_handler(unsigned long p_unicode, unsigned long p_scan_code,bool p_press,bool p_repeat,int p_modifier_mask) {
if (!p_press)
return ;
kb_change_last=p_scan_code|p_modifier_mask;
kb_change_label->set_text( Keyboard::get_code_name( kb_change_last ) );
return ;
}
void KeyboardDialog::change_cbk() {
int idx=list->get_selected();
if (idx<0)
return;
kb_change_last=KeyBind::get_keybind_code( idx );
if (kb_change_last==NO_BIND)
kb_change_label->set_text("No KeyBind");
else
kb_change_label->set_text(Keyboard::get_code_name( kb_change_last ));
kb_change_window->show();
}
void KeyboardDialog::clear_cbk() {
int idx=list->get_selected();
if (idx<0)
return;
KeyBind::set_keybind_code(idx,NO_BIND);
update_kb_text();
}
void KeyboardDialog::read_slot(String p_section,String p_entry,String p_value) {
if (p_section!="KeyBindings")
return;
if (p_entry=="keybind_count") {
allow_kb_load=( (int)p_value.to_double()==KB_MAX );
} else if (p_entry=="keyrepeat_rate") {
spin_rate->get_range()->set( p_value.to_double() );
} else if (p_entry=="keyrepeat_delay") {
spin_delay->get_range()->set( p_value.to_double() );
} else {
if (!allow_kb_load)
return;
int entrynum=(int)(p_entry.to_double());
if (entrynum<=0 || entrynum>KB_MAX)
return;
entrynum--;
int code=(int)(p_value.to_double());
KeyBind::set_keybind_code( entrynum, code );
}
}
void KeyboardDialog::read_finished() {
update_kb_text();
}
void KeyboardDialog::save_slot() {
config->set_section( "KeyBindings" );
config->add_entry( "keybind_count",String::num( KB_MAX ),"Please use UI to edit");
config->add_entry( "keyrepeat_rate",String::num( spin_rate->get_range()->get() ),"ms");
config->add_entry( "keyrepeat_delay",String::num( spin_delay->get_range()->get() ),"ms");
for(int i=0;i<KeyBind::get_keybind_count();i++) {
int code=KeyBind::get_keybind_code(i);
config->add_entry( String::num(i+1) , String::num(code),String( KeyBind::get_keybind_description(i))+" - code is: "+ String(Keyboard::get_code_name( code ) ));
list->add_string( KeyBind::get_keybind_description(i));
}
}
void KeyboardDialog::keyrepeat_changed(double) {
get_painter()->set_key_repeat( (int)spin_delay->get_range()->get(), (int)spin_rate->get_range()->get() );
}
void KeyboardDialog::set_default_it() {
KeyBind::set(KB_CURSOR_MOVE_UP, KEY_UP);
KeyBind::set(KB_CURSOR_MOVE_DOWN,KEY_DOWN );
KeyBind::set(KB_CURSOR_MOVE_LEFT, KEY_LEFT );
KeyBind::set(KB_CURSOR_MOVE_RIGHT,KEY_RIGHT );
KeyBind::set(KB_CURSOR_PAGE_UP, KEY_PAGEUP );
KeyBind::set(KB_CURSOR_PAGE_DOWN, KEY_PAGEDOWN );
KeyBind::set(KB_CURSOR_MOVE_UP_1_ROW, KEY_MASK_CMD|KEY_HOME);
KeyBind::set(KB_CURSOR_MOVE_DOWN_1_ROW, KEY_MASK_CMD|KEY_END);
KeyBind::set(KB_CURSOR_MOVE_TRACK_LEFT,KEY_MASK_ALT|KEY_LEFT);
KeyBind::set(KB_CURSOR_MOVE_TRACK_RIGHT,KEY_MASK_ALT|KEY_RIGHT);
KeyBind::set(KB_CURSOR_HOME, KEY_HOME);
KeyBind::set(KB_CURSOR_END, KEY_END );
KeyBind::set(KB_CURSOR_INSERT, KEY_INSERT );
KeyBind::set(KB_CURSOR_DELETE, KEY_DELETE );
KeyBind::set(KB_CURSOR_TAB, KEY_TAB );
KeyBind::set(KB_CURSOR_BACKTAB, KEY_MASK_SHIFT|KEY_TAB );
KeyBind::set(KB_CURSOR_FIELD_CLEAR, KEY_PERIOD);
KeyBind::set(KB_PATTERN_CURSOR_SPACING_0,KEY_MASK_ALT|KEY_0);
KeyBind::set(KB_PATTERN_CURSOR_SPACING_1,KEY_MASK_ALT|KEY_1);
KeyBind::set(KB_PATTERN_CURSOR_SPACING_2,KEY_MASK_ALT|KEY_2);
KeyBind::set(KB_PATTERN_CURSOR_SPACING_3,KEY_MASK_ALT|KEY_3);
KeyBind::set(KB_PATTERN_CURSOR_SPACING_4,KEY_MASK_ALT|KEY_4);
KeyBind::set(KB_PATTERN_CURSOR_SPACING_5,KEY_MASK_ALT|KEY_5);
KeyBind::set(KB_PATTERN_CURSOR_SPACING_6,KEY_MASK_ALT|KEY_6);
KeyBind::set(KB_PATTERN_CURSOR_SPACING_7,KEY_MASK_ALT|KEY_7);
KeyBind::set(KB_PATTERN_CURSOR_SPACING_8,KEY_MASK_ALT|KEY_8);
KeyBind::set(KB_PATTERN_CURSOR_SPACING_9,KEY_MASK_ALT|KEY_9);
KeyBind::set(KB_PATTERN_CURSOR_NOTE_OFF,KEY_BACKQUOTE);
KeyBind::set(KB_PATTERN_CURSOR_PLAY_FIELD, KEY_4);
KeyBind::set(KB_PATTERN_CURSOR_PLAY_ROW, KEY_8);
KeyBind::set(KB_PATTERN_MUTE_TOGGLE_CHANNEL,KEY_F9);
KeyBind::set(KB_PATTERN_SOLO_TOGGLE_CHANNEL,KEY_F10);
KeyBind::set(KB_PATTERN_PAN_WINDOW_UP,KEY_MASK_ALT|KEY_UP);
KeyBind::set(KB_PATTERN_PAN_WINDOW_DOWN,KEY_MASK_ALT|KEY_DOWN);
KeyBind::set(KB_PATTERN_MARK_BLOCK_BEGIN, KEY_MASK_ALT|KEY_b );
KeyBind::set(KB_PATTERN_MARK_BLOCK_END, KEY_MASK_ALT|KEY_e);
KeyBind::set(KB_PATTERN_MARK_COLUMN_ALL, KEY_MASK_ALT|KEY_l );
KeyBind::set(KB_PATTERN_BLOCK_COPY, KEY_MASK_ALT|KEY_c );
KeyBind::set(KB_PATTERN_BLOCK_PASTE_INSERT, KEY_MASK_ALT|KEY_p);
KeyBind::set(KB_PATTERN_BLOCK_PASTE_OVERWRITE, KEY_MASK_ALT|KEY_o);
KeyBind::set(KB_PATTERN_BLOCK_PASTE_MIX, KEY_MASK_ALT|KEY_m);
KeyBind::set(KB_PATTERN_BLOCK_UNMARK, KEY_MASK_ALT|KEY_u);
KeyBind::set(KB_PATTERN_BLOCK_CUT, KEY_MASK_ALT|KEY_z);
KeyBind::set(KB_PATTERN_BLOCK_SET_CURRENT_VOLUME, KEY_MASK_ALT|KEY_v);
KeyBind::set(KB_PATTERN_BLOCK_WIPE_STRAY_VOLUMES, KEY_MASK_ALT|KEY_w);
KeyBind::set(KB_PATTERN_BLOCK_RAMP_VALUES, KEY_MASK_ALT|KEY_k);
KeyBind::set(KB_PATTERN_BLOCK_AMPLIFY_VOLUMES, KEY_MASK_ALT|KEY_j);
KeyBind::set(KB_PATTERN_BLOCK_DOUBLE_BLOCK_LENGTH, KEY_MASK_ALT|KEY_f);
KeyBind::set(KB_PATTERN_BLOCK_HALVE_BLOCK_LENGTH, KEY_MASK_ALT|KEY_g);
KeyBind::set(KB_PATTERN_FIELD_TOGGLE_MASK, KEY_COMMA);
KeyBind::set(KB_PATTERN_FIELD_COPY_CURRENT, KEY_RETURN);
KeyBind::set(KB_PATTERN_FIELD_WRITE_CURRENT, KEY_SPACE );
KeyBind::set(KB_PATTERN_RAISE_NOTES, KEY_MASK_ALT|KEY_q);
KeyBind::set(KB_PATTERN_LOWER_NOTES, KEY_MASK_ALT|KEY_a);
KeyBind::set(KB_PATTERN_RAISE_12_NOTES, KEY_MASK_SHIFT|KEY_MASK_ALT|KEY_q );
KeyBind::set(KB_PATTERN_LOWER_12_NOTES, KEY_MASK_SHIFT|KEY_MASK_ALT|KEY_a);
KeyBind::set(KB_PATTERN_NEXT, KEY_KP_PLUS);
KeyBind::set(KB_PATTERN_PREV, KEY_KP_MINUS);
KeyBind::set(KB_PATTERN_NEXT_ORDER, KEY_MASK_CMD|KEY_KP_PLUS);
KeyBind::set(KB_PATTERN_PREV_ORDER, KEY_MASK_CMD|KEY_KP_MINUS);
KeyBind::set(KB_PIANO_C0, KEY_z);
KeyBind::set(KB_PIANO_Cs0, KEY_s );
KeyBind::set(KB_PIANO_D0, KEY_x);
KeyBind::set(KB_PIANO_Ds0, KEY_d);
KeyBind::set(KB_PIANO_E0, KEY_c);
KeyBind::set(KB_PIANO_F0, KEY_v);
KeyBind::set(KB_PIANO_Fs0, KEY_g );
KeyBind::set(KB_PIANO_G0, KEY_b);
KeyBind::set(KB_PIANO_Gs0, KEY_h);
KeyBind::set(KB_PIANO_A0, KEY_n);
KeyBind::set(KB_PIANO_As0, KEY_j);
KeyBind::set(KB_PIANO_B0, KEY_m);
KeyBind::set(KB_PIANO_C1, KEY_q);
KeyBind::set(KB_PIANO_Cs1, KEY_2);
KeyBind::set(KB_PIANO_D1, KEY_w);
KeyBind::set(KB_PIANO_Ds1, KEY_3);
KeyBind::set(KB_PIANO_E1, KEY_e);
KeyBind::set(KB_PIANO_F1, KEY_r);
KeyBind::set(KB_PIANO_Fs1, KEY_5);
KeyBind::set(KB_PIANO_G1, KEY_t);
KeyBind::set(KB_PIANO_Gs1, KEY_6);
KeyBind::set(KB_PIANO_A1, KEY_y);
KeyBind::set(KB_PIANO_As1, KEY_7);
KeyBind::set(KB_PIANO_B1, KEY_u);
KeyBind::set(KB_PIANO_C2, KEY_i);
KeyBind::set(KB_PIANO_Cs2, KEY_9);
KeyBind::set(KB_PIANO_D2, KEY_o);
KeyBind::set(KB_PIANO_Ds2, KEY_0);
KeyBind::set(KB_PIANO_E2, KEY_p);
KeyBind::set(KB_ORDERLIST_INSERT_SEPARATOR,KEY_EQUALS);
KeyBind::set(KB_CURSOR_WRITE_MASK,KEY_SPACE);
KeyBind::set(KB_GOTO_PATTERN_SCREEN,KEY_F2);
KeyBind::set(KB_GOTO_PATTERN_SCREEN_ORDERLIST,KEY_F11);
KeyBind::set(KB_OCTAVE_RAISE, KEY_KP_MULTIPLY);
KeyBind::set(KB_OCTAVE_LOWER, KEY_KP_DIVIDE);
KeyBind::set(KB_PATTERN_SCREEN_SONG_FOLLOW,KEY_MASK_CMD|KEY_f);
KeyBind::set(KB_PATTERN_SCREEN_OPTIONS,KEY_MASK_SHIFT|KEY_F2);
KeyBind::set(KB_PLAYER_PLAY_SONG,KEY_F5);
KeyBind::set(KB_PLAYER_STOP_SONG,KEY_F8);
KeyBind::set(KB_PLAYER_FF_SONG,KEY_MASK_ALT|KEY_KP_PLUS);
KeyBind::set(KB_PLAYER_RW_SONG,KEY_MASK_ALT|KEY_KP_MINUS);
KeyBind::set(KB_PLAYER_PLAY_PATTERN,KEY_F6);
KeyBind::set(KB_PLAYER_PLAY_CURSOR,KEY_F7);
KeyBind::set(KB_PLAYER_PLAY_ORDER,KEY_MASK_SHIFT|KEY_F6);
KeyBind::set(KB_FILE_OPEN,KEY_MASK_CMD|KEY_o);
KeyBind::set(KB_FILE_SAVE,KEY_MASK_CMD|KEY_s);
KeyBind::set(KB_FILE_SAVE_AS,KEY_MASK_CMD|KEY_MASK_SHIFT|KEY_s);
KeyBind::set(KB_DISPLAY_TOGGLE_FULLSCREEN,KEY_MASK_CMD|KEY_RETURN);
KeyBind::set(KB_UNDO,KEY_MASK_CMD|KEY_z);
KeyBind::set(KB_REDO,KEY_MASK_CMD|KEY_MASK_SHIFT|KEY_z);
KeyBind::set(KB_QUIT,KEY_MASK_CMD|KEY_x);
}
KeyboardDialog::KeyboardDialog(Window *p_parent,ConfigApi *p_config) : Window(p_parent,MODE_POPUP,SIZE_TOPLEVEL_CENTER) {
config=p_config;
WindowBox *vb = new WindowBox("Keyboard Configuration");
set_root_frame( vb );
MarginGroup *mg = vb->add( new MarginGroup("Key Binding List:"),1);
HBoxContainer *hbc = mg->add( new HBoxContainer,1 );
list=hbc->add( new List,1 );
list->selected_signal.connect(this,&KeyboardDialog::keybind_selected);
hbc->add( new VScrollBar )->set_range( list->get_range() );
mg = vb->add( new MarginGroup("Selected Bind:"));
bind_string=mg->add( new LineEdit );
hbc=mg->add( new CenterContainer)->set(new HBoxContainer );
hbc->add(new Button("Change"))->pressed_signal.connect(this,&KeyboardDialog::change_cbk );
hbc->add(new Button("Clear"))->pressed_signal.connect(this,&KeyboardDialog::clear_cbk );
update_keybind_list();
kb_change_window = new Window(this,MODE_POPUP,SIZE_CENTER);
mg = new MarginGroup("Press New KeyBind: ");
kb_change_window->set_root_frame( mg );
kb_change_label=mg->add( new Label());
kb_change_label->set_align( Label::ALIGN_CENTER );
Button *b = mg->add( new CenterContainer)->set(new Button("Apply") );
b->set_focus_mode( FOCUS_NONE );
b->pressed_signal.connect(this,&KeyboardDialog::kb_change_ok );
kb_change_window->key_unhandled_signal.connect(this,&KeyboardDialog::key_handler);
vb->add( new HSeparator );
HBoxContainer *key_hb =vb->add( new HBoxContainer );
spin_delay=key_hb->add( new MarginGroup("Key Repeat Delay (ms):"),1)->add(new SpinBox );
spin_delay->get_range()->config( 1,1000, get_painter()->get_key_repeat_delay(), 1 );
spin_delay->get_range()->value_changed_signal.connect(this,&KeyboardDialog::keyrepeat_changed);
spin_rate=key_hb->add( new MarginGroup("Key Repeat Rate (ms):"),1)->add(new SpinBox );
spin_rate->get_range()->config( 1,1000, get_painter()->get_key_repeat_rate(), 1 );
spin_rate->get_range()->value_changed_signal.connect(this,&KeyboardDialog::keyrepeat_changed);
vb->add( new MarginGroup("Test:"))->add(new LineEdit);
mb= new MessageBox(this);
config->write_entry_signal.connect( this, &KeyboardDialog::save_slot );
config->read_entry_signal.connect( this, &KeyboardDialog::read_slot );
config->read_finished_signal.connect( this, &KeyboardDialog::read_finished );
allow_kb_load=false;
}
KeyboardDialog::~KeyboardDialog()
{
}
|
#include <iostream>
#include <map>
#include <iomanip>
using namespace std;
struct node
{
char s;
int next;
bool flag;
node(char s, int n, bool f) : s(s), next(n), flag(f) {}
node() {}
};
map<int, node> m;
int a, b, c;
int d, e;
char cc;
int main()
{
// freopen("a.txt", "r", stdin);
scanf("%d%d%d", &a, &b, &c);
for(int i = 0; i < c; i++)
{
scanf("%d%s%d", &d, &cc, &e);
node n(cc, e, false);
m[d] = n;
}
int tmp = b;
while (tmp != -1)
{
m[tmp].flag = true;
tmp = m[tmp].next;
}
tmp = a;
while (tmp != -1)
{
if(m[tmp].flag == true)
break;
tmp = m[tmp].next;
}
if(tmp != -1)
{
cout.fill('0');
cout<<setw(5)<<std::right<<tmp<<endl;
}
else cout<<tmp<<endl;
}
|
#include "menuWrapper.h"
#include <vector>
MenuWrapper::MenuWrapper(int levels, int difficulty, int width_, int height_, int fps_)
: width(width_), height(height_), fps(fps_)
{
for (int i = 0; i < levels; i++)
{
std::vector<int> t;
for (int j = 0; j < difficulty; j++)
t.push_back(0);
progress.push_back(t);
}
}
|
#ifndef FUNCTION_H
#define FUNCTION_H
#include <QList>
#include <QMap>
#include <QString>
#include <QDebug>
class Function
{
public:
Function(QString name, QMap<QString, QString> parameters);
QString getUrl();
~Function();
private:
QMap<QString, QString> _parameters;
QString _name;
};
#endif // FUNCTION_H
|
#include <pybind11/pybind11.h>
#include <pybind11/iostream.h>
#include <pybind11/functional.h>
#include <pybind11/eigen.h>
#include <memory>
#include <rmf_fleet_adapter/agv/Adapter.hpp>
#include <rmf_utils/clone_ptr.hpp>
namespace py = pybind11;
namespace agv = rmf_fleet_adapter::agv;
void bind_tests(py::module &m) {
// Simply use something like f.test_lambda(lambda: print("wow")) in Python
m.def("test_lambda",
[](std::function<void()> f){ f(); },
"Call a C++ lambda function created in Python.");
// Test shared_ptr passing
m.def("test_shared_ptr",
[](std::shared_ptr<agv::RobotCommandHandle> handle,
std::string print_str = "DUMMY_DOCK_NAME",
std::function<void()> docking_finished_callback = [](){})
{
handle->dock(print_str, docking_finished_callback);
},
py::arg("handle"),
py::arg("print_str") = "DUMMY_DOCK_NAME",
py::arg("docking_finished_callback") = (std::function<void()>) [](){},
"Test a shared_ptr<agv::RobotCommandHandle> "
"by testing its dock() method",
py::call_guard<py::scoped_ostream_redirect,
py::scoped_estream_redirect>()
);
// Test clone_ptr passing
// TODO(CH3): clone_ptrs do not work at the moment
// Something about clone_ptr indirection is breaking
m.def("test_clone_ptr",
[](rmf_utils::clone_ptr<
rmf_traffic::agv::Graph::OrientationConstraint> constraint_ptr,
Eigen::Vector3d& position,
const Eigen::Vector2d& course_vector)
{
return constraint_ptr->apply(position, course_vector);
},
"Test a clone_ptr<rmf_traffic::agv::Graph::OrientationConstraint> "
"by testing its get() method",
py::call_guard<py::scoped_ostream_redirect,
py::scoped_estream_redirect>(),
py::return_value_policy::reference_internal
);
}
|
#ifndef EX2_4_GAME_H
#define EX2_4_GAME_H
#include <iostream>
#include "util.h"
template<typename F, typename P1, typename P2>
struct game {
F field;
P1 player1;
P2 player2;
int current;
public:
game(P1 p1, P2 p2) : player1(p1), player2(p2) {
current = 1;
}
void play() {
while (util<F>::is_not_full(field)) {
field.print();
std::cout << "It it player " << current << "'s turn: ";
if (current == F::player1) {
play_round(player1, F::player1);
}
else if (current == F::player2) {
play_round(player2, F::player2);
}
if (util<F>::has_won(field, current)) {
field.print();
std::cout << "Player " << current << " won!" << std::endl;
return;
}
current = util<F>::next_player(current);
}
std::cout << "It's a draw..." << std::endl;
}
template<typename P>
void play_round(P p, int player) {
int column = p.play(field);
field.insert(column, player);
}
};
#endif //EX2_4_GAME_H
|
unsigned long bur_heap_size = 0xFFFF;
/***** Header files *****/
#ifdef _DEFAULT_INCLUDES
#include <AsDefault.h>
#endif
#include <bur/plctypes.h>
#include <fileIO.h>
#include <asZip.h>
#include <arProject.h>
#include <string>
//Variables
UINT status = 0;
USINT step = 0;
char LocalDevName[] = "FLASH3";
char RemoteDevName[] = "NET";
char RemoteFolder[] = "/softwareUpdate";
char LocalFolder[] = "/softwareUpdate";
char pipRemoteFolder[] = "/softwareUpdate/Default_X20CP04xx/pipconfig.xml";
char pipLocalFolder[] = "/softwareUpdate/Default_X20CP04xx/pipconfig.xml";
char pipServerVersion[32];
char pipLocalVersion[32];
char serverParam[] = "/SIP=192.168.1.10 /PROTOCOL=ftp /USER=ftpuser /PASSWORD=12345678";
char localParam[] = "/DEVICE=C:/";
_INIT void Init(void){
step = 0;
}
_CYCLIC void Cyclic(void){
//File transfer and installation state-machine
switch (step){
case 0:
break;
case 1:
//Create remote devlink
status = 1;
DevLink_REMOTE.enable = 1;
DevLink_REMOTE.pDevice = (UDINT) &RemoteDevName[0]; //(UDINT) &devname[0];
DevLink_REMOTE.pParam = (UDINT) &serverParam[0]; //(UDINT) "/SIP=192.168.1.10 /PROTOCOL=ftp /USER=ftpuser /PASSWORD=12345678"; //(UDINT) ¶m[0];
DevLink(&DevLink_REMOTE);
status = DevLink_REMOTE.status;
if(status == 0){
step = 2;
break;
}
break;
case 2:
//Create local devlink
status = 1;
DevLink_LOCAL.enable = 1;
DevLink_LOCAL.pDevice = (UDINT) &LocalDevName[0]; //(UDINT) &devname[0];
DevLink_LOCAL.pParam = (UDINT) &localParam[0]; //(UDINT) "/DEVICE=C:/"; //(UDINT) ¶m[0];
DevLink(&DevLink_LOCAL);
status = DevLink_LOCAL.status;
if(status == 0){
step = 3;
break;
}
break;
case 3:
//Check installation file version on server
status = 1;
strcpy(FCheckServer.DeviceName , RemoteDevName);
strcpy(FCheckServer.FilePath, pipRemoteFolder);
FCheckServer.Execute = 1;
ArProjectGetPackageInfo(&FCheckServer);
if(FCheckServer.Done == true){
strcpy(pipServerVersion, FCheckServer.ConfigurationVersion);
step = 4;
FCheckServer.Execute = 0;
break;
}
break;
case 4:
//Check installation version on target
status = 1;
FCheckLocal.Execute = 1;
ArProjectGetInfo(&FCheckLocal);
if(FCheckLocal.Done == true){
strcpy(pipLocalVersion, FCheckLocal.ConfigurationVersion);
if(strcmp(pipServerVersion, pipLocalVersion) == 0){
setOutput1 = true;
step = 9;
} else{
step = 5;
}
FCheckLocal.Execute = 0;
break;
}
break;
case 5:
//Copy installation files if server version is newer
status = 1;
//Copy an entire folder
DCopy.enable = 1;
DCopy.pSrcDev = (UDINT) &RemoteDevName[0];
DCopy.pSrcDir = (UDINT) &RemoteFolder[0];
DCopy.pDestDev = (UDINT) &LocalDevName[0];
DCopy.pDestDir = (UDINT) &LocalFolder[0];
DCopy.option = fiOVERWRITE;
DirCopy(&DCopy);
status = DCopy.status;
if(status == 0){
step = 8;
DCopy.enable = 0;
break;
}
/*
//Copy a single file - "Used to copy a zipped archive"
FCopy.enable = 1;
FCopy.pSrcDev = (UDINT) &RemoteDevName[0]; //(UDINT) &srcdl[0];
FCopy.pSrc = (UDINT) "softwareUpdate.tar.gz"; //(UDINT) &srcfn[0];
FCopy.pDestDev = (UDINT) &LocalDevName[0]; //(UDINT) &desdl[0];
FCopy.pDest = (UDINT) "softwareUpdate.tar.gz"; //(UDINT) &desfn[0];
FCopy.option = fiOVERWRITE;
FileCopy(&FCopy);
status = FCopy.status;
if(status == 0){
setOutput3 = true;
step = 6;
FCopy.enable = 0;
break;
}
*/
break;
case 6:
//Unzip files tar.gz files if update is downloaded as a zipped archive - maybe not needed
status = 1;
FUnzip.enable = 1;
FUnzip.pArchiveDevice = (UDINT) &LocalDevName[0]; //(UDINT) &devname[0];
FUnzip.pArchiveFile = (UDINT) "softwareUpdate.tar.gz"; //(UDINT) &filename[0];
FUnzip.pOutDevice = (UDINT) &LocalDevName[0]; //(UDINT) &devname[0];
FUnzip.pOutFolder = (UDINT) "/";
zipExtract(&FUnzip);
status = FUnzip.status;
if(status == 0){
setOutput4 = true;
step = 7;
FUnzip.enable = 0;
break;
}
break;
case 7:
//Deletes the tar.gz archive
status = 1;
FDelete.enable = 1;
FDelete.pDevice = (UDINT) &LocalDevName[0];
FDelete.pName = (UDINT) "softwareUpdate.tar.gz";
FileDelete(&FDelete);
status = FDelete.status;
if(status == 0){
setOutput5 = true;
step = 8;
FDelete.enable = 0;
break;
}
break;
case 8:
//Install the update
status = 1;
strcpy(FInstall.DeviceName, LocalDevName);
strcpy(FInstall.FilePath, pipLocalFolder);
FInstall.Execute = 1;
ArProjectInstallPackage(&FInstall);
if(FInstall.Done == true){
step = 9;
FInstall.Execute = 0;
break;
}
break;
case 9:
//Unlink remote devlink
status = 1;
DevLink_REMOTE.enable = 0; //Disable function-block before unlinking
DevLink_UNLINK.enable = 1;
DevLink_UNLINK.handle = DevLink_REMOTE.handle;
DevUnlink(&DevLink_UNLINK);
status = DevLink_UNLINK.status;
if(status == 0){
DevLink_UNLINK.enable = 0;
step = 10;
break;
}
break;
case 10:
//Unlink local devlink
status = 1;
DevLink_LOCAL.enable = 0; //Disable functionblock before unlinking
DevLink_UNLINK.enable = 1;
DevLink_UNLINK.handle = DevLink_LOCAL.handle;
DevUnlink(&DevLink_UNLINK);
status = DevLink_UNLINK.status;
if(status == 0){
setOutput6 = true;
DevLink_UNLINK.enable = 0;
step = 0;
break;
}
break;
}
}
|
/*
* BulkMem.hpp
*
* Created on: Aug 7, 2018
* Author: yyhu
*/
#ifndef INCLUDE_BULKMEM_BULKMEM_HPP_
#define INCLUDE_BULKMEM_BULKMEM_HPP_
#include <iostream>
#include <string>
#include <sstream>
#include "SLFException/SLFException.hpp"
namespace slf
{
typedef unsigned long i_t;
class MemSize
{
public:
MemSize();
~MemSize();
static void show_memory_usage(void);
protected:
static const i_t GB = 1024 * 1024 * 1024;
static i_t TOTAL_SIZE;
static i_t MAX_SIZE;
};
template<class _T>
class BulkMem : public MemSize
{
public:
BulkMem(i_t* dim, i_t nDim = 1, bool faked = false);
~BulkMem();
_T* get(void);
i_t get_n_dim(void);
i_t* get_dim(void);
i_t get_size(void);
bool is_faked(void);
i_t total_size(void);
void assign(const _T& val);
void assign(const _T* val);
public:
_T* ptr;
protected:
i_t mSize;
i_t mNDim;
i_t* mDim;
bool mFaked;
private:
BulkMem(const BulkMem& bm) { }
BulkMem(BulkMem& bm) { }
};
template<typename _T>
BulkMem<_T>::BulkMem(i_t* dim, i_t nDim, bool faked)
: MemSize()
{
mNDim = nDim;
mDim = new i_t[mNDim];
mSize = 1;
for ( i_t i = 0; i < mNDim; ++i )
{
mSize *= dim[i];
mDim[i] = dim[i];
}
mFaked = faked;
if ( false == mFaked )
{
ptr = new _T[ mSize ];
}
// Update TOTAL_SIZE.
TOTAL_SIZE += mSize * sizeof(_T);
if ( TOTAL_SIZE > MAX_SIZE )
{
MAX_SIZE = TOTAL_SIZE;
}
}
template<typename _T>
BulkMem< _T >::~BulkMem()
{
if ( ptr != NULL && false == mFaked )
{
delete [] ptr; ptr = NULL;
}
if ( mDim != NULL )
{
delete [] mDim; mDim = NULL;
}
// Update TOTAL_SIZE;
TOTAL_SIZE -= mSize * sizeof(_T);
}
template<typename _T>
_T* BulkMem<_T>::get(void)
{
return ptr;
}
template<typename _T>
i_t BulkMem<_T>::get_n_dim(void)
{
return mNDim;
}
template<typename _T>
i_t* BulkMem<_T>::get_dim(void)
{
return mDim;
}
template<typename _T>
i_t BulkMem<_T>::get_size(void)
{
return mSize;
}
template<typename _T>
bool BulkMem<_T>::is_faked(void)
{
return mFaked;
}
template<typename _T>
i_t BulkMem<_T>::total_size(void)
{
return TOTAL_SIZE;
}
template<typename _T>
void BulkMem<_T>::assign(const _T& val)
{
for ( i_t i = 0; i < mSize; ++i )
{
ptr[i] = val;
}
}
template<typename _T>
void BulkMem<_T>::assign(const _T* val)
{
for ( i_t i = 0; i < mSize; ++i )
{
ptr[i] = val[i];
}
}
} // Namespace slf.
#endif /* INCLUDE_BULKMEM_BULKMEM_HPP_ */
|
#include "BulletCollision/CollisionShapes/btMultiSphereShape.h"
#include "BulletDynamics/Dynamics/btRigidBody.h"
#include "BulletCollision/CollisionDispatch/btCollisionWorld.h"
#include "LinearMath/btDefaultMotionState.h"
#include "DynamicCharacterController.h"
DynamicCharacterController::DynamicCharacterController(btCollisionObject* body) {
downRayLambda = 1.0;
m_rigidBody = (Player*) body;
}
DynamicCharacterController::~DynamicCharacterController() {
}
void DynamicCharacterController::destroy() {
if (m_shape) {
delete m_shape;
}
if (m_rigidBody) {
delete m_rigidBody;
m_rigidBody = 0;
}
}
btCollisionObject* DynamicCharacterController::getCollisionObject() {
return m_rigidBody;
}
void DynamicCharacterController::preStep(btCollisionWorld* collisionWorld, btScalar dt) {
Player* myGrabber = m_rigidBody->getMyGrabber();
if (myGrabber) {
m_rigidBody->applyCentralImpulse(btVector3(0, 10, 0) * dt);
btVector3 origin = m_rigidBody->getCenterOfMassPosition();
//std::cerr << origin.getX() << " " << origin.getY() << " " << origin.getZ() << std::endl;
btTransform grabbeeTransform = m_rigidBody->getCenterOfMassTransform();
btVector3 grabberPosition = myGrabber->getCenterOfMassPosition();
grabbeeTransform.setOrigin(grabberPosition + btVector3(0, 17, 0) + grabberLook * -10);
//setLookDirection();
m_rigidBody->setCenterOfMassTransform(grabbeeTransform);
origin = m_rigidBody->getCenterOfMassPosition();
//std::cerr << origin.getX() << " " << origin.getY() << " " << origin.getZ() << std::endl;
m_rigidBody->getMotionState()->setWorldTransform(grabbeeTransform);
return;
}
btTransform xform;
m_rigidBody->getMotionState()->getWorldTransform(xform);
btVector3 down = -xform.getBasis()[1];
down.normalize();
class ClosestNotMe : public btCollisionWorld::ClosestRayResultCallback {
public:
ClosestNotMe(btRigidBody* me) : btCollisionWorld::ClosestRayResultCallback(btVector3(0.0, 0.0, 0.0), btVector3(0.0, 0.0, 0.0)) {
m_me = me;
}
virtual btScalar addSingleResult(btCollisionWorld::LocalRayResult& rayResult, bool normalInWorldSpace) {
if (rayResult.m_collisionObject == m_me)
return 1.0;
return ClosestRayResultCallback::addSingleResult(rayResult, normalInWorldSpace
);
}
protected:
btRigidBody* m_me;
};
ClosestNotMe rayCallback(m_rigidBody);
downRaySource = xform.getOrigin() + btVector3(0.0, 0.1, 0.0);
downRayTarget = downRaySource + down * btScalar(1.1);
rayCallback.m_closestHitFraction = 1.0;
collisionWorld->rayTest(downRaySource, downRayTarget, rayCallback);
if (rayCallback.hasHit()) {
downRayLambda = rayCallback.m_closestHitFraction;
}
else {
downRayLambda = 1.0;
}
btVector3 localLook(0.0f, 0.0f, 1.0f);
btTransform transform = m_rigidBody->getCenterOfMassTransform();
btQuaternion rotation = transform.getRotation();
btVector3 currentLook = quatRotate(rotation, localLook);
btVector3 rotationAxis(0.0f, 1.0f, 0.0f);
btScalar angle = 1.05f;
btQuaternion rot1(rotationAxis, angle);
btQuaternion rot2(rotationAxis, -angle);
btQuaternion newRot1 = rot1 * rotation;
btQuaternion newRot2 = rot2 * rotation;
btVector3 look1 = quatRotate(newRot1, localLook);
btVector3 look2 = quatRotate(newRot2, localLook);
forwardRaySource = xform.getOrigin() + btVector3(0, 5, 0);
forwardRayTarget = forwardRaySource + currentLook * 7;
ClosestNotMe rayCallback2(m_rigidBody);
rayCallback2.m_closestHitFraction = 1.0;
collisionWorld->rayTest(forwardRaySource, forwardRayTarget, rayCallback2);
if (rayCallback2.hasHit()) {
punchTarget = rayCallback2.m_collisionObject;
}
else {
punchTarget = nullptr;
}
btVector3 ram0Source = xform.getOrigin() + btVector3(0, 1, 0);
btVector3 ram0Target = forwardRaySource + currentLook * 12;
btVector3 ram1Source = xform.getOrigin() + btVector3(0, 1, 0);
btVector3 ram1Target = forwardRaySource + look1 * 12;
btVector3 ram2Source = xform.getOrigin() + btVector3(0, 1, 0);
btVector3 ram2Target = forwardRaySource + look2 * 12;
ClosestNotMe rayCallback3(m_rigidBody);
rayCallback3.m_closestHitFraction = 1.0;
ClosestNotMe rayCallback4(m_rigidBody);
rayCallback4.m_closestHitFraction = 1.0;
ClosestNotMe rayCallback5(m_rigidBody);
rayCallback5.m_closestHitFraction = 1.0;
collisionWorld->rayTest(ram0Source, ram0Target, rayCallback3);
collisionWorld->rayTest(ram1Source, ram1Target, rayCallback4);
collisionWorld->rayTest(ram2Source, ram2Target, rayCallback5);
if (rayCallback3.hasHit()) {
ramTarget = rayCallback3.m_collisionObject;
}
else if (rayCallback4.hasHit()){
ramTarget = rayCallback4.m_collisionObject;
}
else if (rayCallback5.hasHit()){
ramTarget = rayCallback5.m_collisionObject;
}
else {
ramTarget = nullptr;
}
ClosestNotMe rayCallback6(m_rigidBody);
rayCallback6.m_closestHitFraction = 1.0;
forwardRaySource = xform.getOrigin() + btVector3(0, 5, 0);
forwardRayTarget = forwardRaySource + currentLook * 20;
collisionWorld->rayTest(forwardRaySource, forwardRayTarget, rayCallback6);
if (rayCallback6.hasHit()) {
wrenchTarget = rayCallback6.m_collisionObject;
}
else {
wrenchTarget = nullptr;
}
}
void DynamicCharacterController::playerStep(const btCollisionWorld*, btVector3& dir) {
setLookDirection(dir);
dir.setY(0);
btVector3 velocity = m_rigidBody->getLinearVelocity();
btVector3 planeVelocity = velocity;
planeVelocity.setY(0);
btScalar speed = planeVelocity.length();
m_rigidBody->applyCentralForce(dir * 5);
}
bool DynamicCharacterController::canJump() const {
return onGround();
}
void DynamicCharacterController::jump() {
if (!canJump()) {
return;
}
btTransform xform;
m_rigidBody->getMotionState()->getWorldTransform(xform);
btVector3 up = xform.getBasis()[1];
up.normalize();
btScalar magnitude = 15;
m_rigidBody->applyCentralImpulse(up * magnitude);
}
bool DynamicCharacterController::onGround() const {
return downRayLambda < btScalar(1.0);
}
void DynamicCharacterController::warp(const btVector3& origin) {
}
void DynamicCharacterController::registerPairCacheAndDispatcher(btOverlappingPairCache* pairCache, btCollisionDispatcher* dispatcher) {
}
void DynamicCharacterController::setLookDirection(const btVector3& newLook) {
btVector3 localLook(0.0f, 0.0f, 1.0f);
btVector3 rotationAxis(0.0f, 1.0f, 0.0f);
btTransform transform;
transform = m_rigidBody->getCenterOfMassTransform();
btQuaternion rotation = transform.getRotation();
btVector3 currentLook = quatRotate(rotation, localLook);
btScalar angle = currentLook.angle(newLook.normalized());
btQuaternion deltaRotation1(rotationAxis, angle);
btQuaternion deltaRotation2(rotationAxis, -angle);
btQuaternion newRotation1 = deltaRotation1 * rotation;
btQuaternion newRotation2 = deltaRotation2 * rotation;
btVector3 testLook1 = quatRotate(newRotation1, localLook);
btVector3 testLook2 = quatRotate(newRotation2, localLook);
btQuaternion newRotation;
if (testLook1.angle(newLook.normalized()) < testLook2.angle(newLook.normalized())) {
newRotation = newRotation1;
}
else {
newRotation = newRotation2;
}
transform.setRotation(newRotation);
m_rigidBody->setCenterOfMassTransform(transform);
m_rigidBody->getMotionState()->setWorldTransform(transform);
}
void DynamicCharacterController::grabOrientation(Player* grabber) {
grabberLook = quatRotate(grabber->getCenterOfMassTransform().getRotation(), btVector3(0, 0, 1));
setLookDirection(quatRotate(grabber->getCenterOfMassTransform().getRotation(), btVector3(0, 0, 1)));
btVector3 localLook(0.0f, 0.0f, 1.0f);
btVector3 rotationAxis(0.0f, 1.0f, 0.0f);
btTransform transform;
transform = m_rigidBody->getCenterOfMassTransform();
btQuaternion rotation = transform.getRotation();
btQuaternion deltaRotation(rotationAxis, 3.14 / 2);
btQuaternion sideRotation = deltaRotation * rotation;
btVector3 sideAxis = quatRotate(sideRotation, localLook);
btQuaternion turnDelta(sideAxis, 3.14 / 2);
btQuaternion turnRotation = turnDelta * rotation;
transform.setRotation(turnRotation);
m_rigidBody->setCenterOfMassTransform(transform);
m_rigidBody->getMotionState()->setWorldTransform(transform);
}
void DynamicCharacterController::straightOrientation() {
btVector3 localLook(0.0f, -1.0f, 0.0f);
btVector3 rotationAxis(0.0f, 1.0f, 0.0f);
btTransform transform;
transform = m_rigidBody->getCenterOfMassTransform();
btQuaternion rotation = transform.getRotation();
btQuaternion deltaRotation(rotationAxis, 3.14 / 2);
btQuaternion sideRotation = deltaRotation * rotation;
btVector3 sideAxis = quatRotate(sideRotation, localLook);
btQuaternion turnDelta(sideAxis, 3.14 / 2);
btQuaternion turnRotation = turnDelta * rotation;
transform.setRotation(turnRotation);
m_rigidBody->setCenterOfMassTransform(transform);
m_rigidBody->getMotionState()->setWorldTransform(transform);
}
|
#pragma once
#ifndef SPOTIFYAPI_H
#define SPOTIFYAPI_H
#include <string>
#include <QJsonDocument>
#include <QDebug>
#include "IHTTPDispatcher.h"
#include "IHTTPRequest.h"
class SpotifyAPI {
private:
IHTTPDispatcher* dispatcher;
IHTTPRequest* http_request;
std::string encoded_authorization; //base64 client id and client secret;
QJsonDocument sendGetRequest();
QJsonDocument sendPostRequest();
public:
SpotifyAPI(IHTTPDispatcher* d, IHTTPRequest* hr, std::string e_auth);
QJsonDocument getAccessToken();
QJsonDocument searchByArtist(std::string artist, std::string bearer_token);
QJsonDocument searchByTrack(std::string track, std::string bearer_token);
QJsonDocument getArtistTopTracks(std::string artist_id, std::string bearer_token, std::string market="BR");
QJsonDocument getArtistAlbums(std::string artist_id, std::string bearer_token, std::string market = "BR");
QJsonDocument getAlbumTracks(std::string album_id, std::string bearer_token, std::string market = "BR");
QJsonDocument getTrack(std::string track_id, std::string bearer_token, std::string market = "BR");
};
#endif
|
#ifndef INC_MULTNode_hpp__
#define INC_MULTNode_hpp__
#include "BinaryOperatorAST.hpp"
/** A simple node to represent MULT operation */
class MULTNode : public BinaryOperatorAST {
public:
MULTNode(ANTLR_USE_NAMESPACE(antlr)RefToken tok) {
}
/** Compute value of subtree; this is heterogeneous part :) */
int value() const {
return left()->value() * right()->value();
}
ANTLR_USE_NAMESPACE(std)string toString() const {
return " *";
}
// satisfy abstract methods from BaseAST
void initialize(int t, const ANTLR_USE_NAMESPACE(std)string& txt) {
}
void initialize(ANTLR_USE_NAMESPACE(antlr)RefAST t) {
}
void initialize(ANTLR_USE_NAMESPACE(antlr)RefToken tok) {
}
};
typedef ANTLR_USE_NAMESPACE(antlr)ASTRefCount<MULTNode> RefMULTNode;
#endif //INC_MULTNode_hpp__
|
#pragma once
class SubscribeOperation
{
public:
SubscribeOperation(char variable, int rank) : variable(variable), rank(rank) {};
~SubscribeOperation();
private:
char variable;
int rank;
};
|
#pragma once
#include <vector>
#include "Entity.h"
#include "Physics.h"
#include "GraphicsComponent.h"
#include "InputComponent.h"
#include "InputMapping.h"
#include "RessourceManager.h"
#include "Timer.h"
#include "Sprites.h"
class EntityGenerator {
private:
Timer* _timer = nullptr;
int _dispWidth = 0;
int _dispHeight = 0;
// singleton stuff
private:
EntityGenerator() {}
EntityGenerator(const EntityGenerator&) = delete;
EntityGenerator& operator= (const EntityGenerator&) = delete;
private:
inline Entity* createBasicEntity(int x, int y, double scale, std::string spriteTag) {
auto sprite = RessourceManager::getInstance().getByTag<Sprite*>(spriteTag);
auto graphics = new BasicGraphics(sprite);
auto physics = new StaticPhysics(0.f, 0.f, 0.f, 0.f,
x, y, (int)(sprite->getHeight()*scale), (int)(sprite->getWidth()*scale));
return new Entity(physics, graphics);
}
public:
static EntityGenerator& getInstance() {
static EntityGenerator instance;
return instance;
}
void init(int width, int height, Timer* timer) {
_dispWidth = width;
_dispHeight = height;
_timer = timer;
}
// generates the bird player
Entity* generatePlayerBird() {
auto physics = new DynamicPhysics(0.f, 0.1f, 2.5f, 0.f,
0.f, 200.f, // x, y
50.f, 70.f); // h, w
// graphics component
// create bird spritesheet
std::vector<Rect> rector;
rector.emplace_back(Rect(0, 0, 18, 12));
rector.emplace_back(Rect(0, 0, 18, 12));
rector.emplace_back(Rect(18, 0, 18, 12));
rector.emplace_back(Rect(36, 0, 18, 12));
rector.emplace_back(Rect(36, 0, 18, 12));
rector.emplace_back(Rect(18, 0, 18, 12));
auto spriteSheet = new SpriteSheet(rector, RessourceManager::getInstance().getByTag<Sprite*>("bird"));
auto uTimer = UpdateTimer(_timer, 250);
auto graphics = new BirdGraphics(spriteSheet, uTimer);
// input component
auto input = new PlayerInput();
InputMapper::getInstance().registerContext(input);
return new Entity(physics, graphics, input);
}
// generates a top and bottom PipeEntity
std::pair<Entity*, Entity*> generatePipes(int xPos, int gapPos, int gapHeight) {
auto spriteBot = RessourceManager::getInstance().getByTag<Sprite*>("pipebot");
auto spriteMid= RessourceManager::getInstance().getByTag<Sprite*>("pipemid");
auto botPipeGraphics = new PipeGraphics(spriteBot, spriteMid, true);
auto topPipeGraphics = new PipeGraphics(spriteBot, spriteMid, false);
int gapEndY = gapPos + gapHeight;
auto topPhysics = new StaticPhysics(0.f, 0.f, 0.f, 0.f,
(float)xPos, 0.f,
(float)gapPos, 130.f);
auto botPhysics = new StaticPhysics(0.f, 0.f, 0.f, 0.f,
(float)xPos, (float)gapEndY,
(float)(_dispHeight - gapEndY), 130.f);
auto botEntity = new Entity(botPhysics, botPipeGraphics);
auto topEntity = new Entity(topPhysics, topPipeGraphics);
return std::make_pair(botEntity, topEntity);
}
Entity* generateBackground() {
auto bgSprite = RessourceManager::getInstance().getByTag<Sprite*>("sky");
auto bgGraphics = new BackgroundGraphics2(bgSprite, 4, 8);
auto bgPhy = new StaticPhysics(0.f, 0.f, 0.f, 0.f, 0.f, 0.f, _dispHeight, _dispWidth);
return new Entity(bgPhy, bgGraphics);
}
Entity* generateForeground() {
auto fgSprite = RessourceManager::getInstance().getByTag<Sprite*>("land");
auto bgGraphics = new ForegroundGraphics(fgSprite, 1.5, 2);
auto bgPhy = new StaticPhysics(0.f, 0.f, 0.f, 0.f,
0.f, _dispHeight, _dispHeight, _dispWidth);
return new Entity(bgPhy, bgGraphics);
}
Entity* generateBorderBottom() {
auto physics = new StaticPhysics(0.f, 0.f, 0.f, 0.f,
FLT_MIN, _dispHeight, FLT_MAX, FLT_MAX);
return new Entity(physics);
}
Entity* generateBorderTop() {
auto physics = new StaticPhysics(0.f, 0.f, 0.f, 0.f,
FLT_MIN, FLT_MIN, -FLT_MIN, FLT_MAX);
return new Entity(physics);
}
Entity* createMedalPlatinum(int x, int y, double scale) {
return createBasicEntity(x, y, scale, "medal_platinum");
}
Entity* createMedalGold(int x, int y, double scale) {
return createBasicEntity(x, y, scale, "medal_gold");
}
Entity* createMedalSilver(int x, int y, double scale) {
return createBasicEntity(x, y, scale, "medal_silver");
}
Entity* createMedalBronze(int x, int y, double scale) {
return createBasicEntity(x, y, scale, "medal_bronze");
}
Entity* createScoreboard(int x, int y, double scale) {
return createBasicEntity(x, y, scale, "scoreboard");
}
Entity* createCounterEntity(int n, int x, int y, double scale) {
std::vector<Rect> digitsPos;
Sprite *numbers = RessourceManager::getInstance().getByTag<Sprite*>("numbers");
float width = ((float)numbers->getWidth() / 10);
float xPos = 1;
int height = 18;
for (int i = 1; i < 11; i++)
{
digitsPos.emplace_back(Rect(xPos, 1, width - 1, height));
xPos = width*i + 1;
}
auto graphics = new CounterGraphics(new SpriteSheet(digitsPos, numbers), n);
auto physics = new StaticPhysics(0, 0, 0, 0,
x, y, (int)(height*scale), (int)((width-1)*scale));
return new Entity(physics, graphics);
}
};
|
#pragma once
#include <landstalker-lib/patches/game_patch.hpp>
/**
* In the original game, you need to save Tibor to make teleport trees usable.
* This patch removes this requirement.
*/
class PatchRemoveTiborRequirement : public GamePatch
{
public:
void alter_rom(md::ROM& rom) override
{
// Remove the check of the "completed Tibor sidequest" flag to make trees usable
rom.set_code(0x4E4A, md::Code().nop(5));
}
};
|
/*******************************************************************************
* Cristian Alexandrescu *
* 2163013577ba2bc237f22b3f4d006856 *
* 11a4bb2c77aca6a9927b85f259d9af10db791ce5cf884bb31e7f7a889d4fb385 *
* bc9a53289baf23d369484f5343ed5d6c *
*******************************************************************************/
/* Problem 12488 - Start Grid */
#include <stdio.h>
int main() {
const int MAX_DRIVERS = 32;
int nN;
while (scanf("%d", &nN) == 1) {
int arrnPos[MAX_DRIVERS];
for (int nLoop = 0; nLoop < nN; nLoop++) {
int nNumber;
scanf("%d", &nNumber);
arrnPos[nNumber] = nLoop;
}
int arrnGoal[MAX_DRIVERS];
for (int nLoop = 0; nLoop < nN; nLoop++)
scanf("%d", &arrnGoal[nLoop]);
int nSol = 0;
for (int nLoop1 = 1; nLoop1 < nN; nLoop1++)
for (int nLoop2 = nLoop1; nLoop2; nLoop2--)
if (arrnPos[arrnGoal[nLoop2]] < arrnPos[arrnGoal[nLoop2 - 1]]) {
int nTemp = arrnGoal[nLoop2];
arrnGoal[nLoop2] = arrnGoal[nLoop2 - 1];
arrnGoal[nLoop2 - 1] = nTemp;
nSol++;
} else {
break;
}
printf("%d\n", nSol);
}
return 0;
}
|
#pragma once
#include "VSmartPointer.h"
#include "VMemory.h"
//////////////////////////////////////////////////////////////////////////
class VSmartMemBlock : public VSmartBase
{
public:
//create a new object with specified parameters
//the main purpose of this class is to allocate all necessary data in one allocation instead of 3 separate objects (RefCountData , Object , Memory)
static VSmartMemBlock* Create(size_t size, size_t align = 16, bool bZeroMemory = true);
//return the size of memory block in bytes
size_t GetSize() const { return mSize; }
//returns pointer to the memory block
void* GetData() { return mMemory; }
const void* GetData() const { return &mMemory; }
void operator delete(void * p) { VMemFree(p); }
private:
VSmartMemBlock(size_t size, void* pMem) : mSize(size), mMemory(pMem)
{}
size_t mSize;
void* mMemory;
size_t mDataHead;
};
|
#include "..\inc.h"
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
class Solution {
public:
vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
if(intervals.empty())
return vector<Interval>(1, newInterval);
//find first overlap
int f = 0, c = intervals.size();
while(c > 0){
int m = c / 2;
if(intervals[f + m].end < newInterval.start){
f += m + 1;
c -= m + 1;
}else
c = m;
}
//combine intervals
vector<Interval> r;
if(f > 0)
r.assign(intervals.begin(), intervals.begin() + f);
if(f < int(intervals.size())){
if(newInterval.end < intervals[f].start){
c = f;
}else{
newInterval.start = min(newInterval.start, intervals[f].start);
for(c = f;c < int(intervals.size());++c)
if(intervals[c].start > newInterval.end)
break;
newInterval.end = max(newInterval.end, intervals[c - 1].end);
}
r.push_back(newInterval);
if(c < int(intervals.size()))
r.insert(r.end(), intervals.begin() + c, intervals.end());
}else
r.push_back(newInterval);
return r;
}
};
class Solution2 {
public:
vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
const size_t f = help(intervals, 0, intervals.size(), newInterval.start);
vector<Interval> ret(intervals.begin(), intervals.begin() + f);
if(f < intervals.size())
newInterval.start = min(newInterval.start, intervals[f].start);
size_t t = help(intervals, f, intervals.size() - f, newInterval.end);
if(t < intervals.size() && intervals[t].start <= newInterval.end)
newInterval.end = max(newInterval.end, intervals[t++].end);
ret.push_back(newInterval);
ret.insert(ret.end(), intervals.begin() + t, intervals.end());
return ret;
}
size_t help(const vector<Interval> & intervals, size_t from, size_t len, int val){
while(len){
size_t mid = len / 2;
if(val <= intervals[from + mid].end){
len = mid;
}else{
from += mid + 1;
len -= mid + 1;
}
}
return from;
}
};
int main()
{
{
vector<Interval> v;
v.push_back(Interval(1,3));
v.push_back(Interval(6,9));
//print(Solution().insert(v, Interval(2,5)));
}{
vector<Interval> v;
v.push_back(Interval(1,2));
v.push_back(Interval(3,5));
v.push_back(Interval(6,7));
v.push_back(Interval(8,10));
v.push_back(Interval(12,16));
//print(Solution().insert(v, Interval(4,9)));
}{
vector<Interval> v;
v.push_back(Interval(1,5));
//print(Solution().insert(v, Interval(0,0)));
}
}
|
#ifndef FINTERPOL_H
#define FINTERPOL_H
#include <map>
#include <limits>
class finterpol
{
std::map<double, double> cache;
public:
finterpol()
{
}
void addValue(double x, double y)
{
cache[x] = y;
}
double operator()(double fi) const
{
std::map<double, double>::const_iterator next,
iter = cache.lower_bound(fi);
if (iter == cache.end())
{
if (iter == cache.begin())
{
assert(!"empty map");
return 0.0;
}
iter = cache.end();
return (--iter)->second;
}
if (iter == cache.end())
{
iter = cache.end();
if (iter == cache.begin())
return std::numeric_limits<double>::quiet_NaN();
--iter;
return iter->second;
}
if (iter == cache.begin())
{
return iter->second;
} else
{
next = iter; --iter;
return scale(fi, iter->first, next->first,
iter->second, next->second);
}
}
};
#endif // FINTERPOL_H
|
#pragma once
#include "camera.h"
#include "Box.h"
class World {
public:
World();
~World();
Camera *GetCamera() { return _camera; }
Box *GetBox() { return _box; }
private:
void _InitWorld();
void _DeInitWorld();
Camera *_camera;
Box *_box;
};
|
/* _____
* /\ _ \ __
* \ \ \_\ \ __ __ __ /\_\
* \ \ __ \ /'_ `\ /\ \/\ \\/\ \
* \ \ \/\ \ /\ \_\ \\ \ \_\ \\ \ \
* \ \_\ \_\\ \____ \\ \____/ \ \_\
* \/_/\/_/ \/____\ \\/___/ \/_/
* /\____/
* \_/__/
*
* Copyright (c) 2011 Joshua Larouche
*
*
* License: (BSD)
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name of Agui nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "TextField.hpp"
namespace cge
{
TextField::~TextField(void)
{
}
TextField::TextField( agui::Image* bgImage, agui::Image* focusImage, PopUpMenu* menu )
:m_bgImage(bgImage), m_focusImage(focusImage), m_menu(menu),
m_cutItem("Cut", "Ctrl + X"), m_copyItem("Copy","Ctrl + C"),
m_pasteItem("Paste","Ctrl + V"), m_selectAllItem("Select All","Ctrl + A"),
m_deleteItem("Delete"),
m_separatorItem(agui::PopUpMenuItem::SEPARATOR)
{
if(menu)
{
menu->addItem(&m_cutItem);
menu->addItem(&m_copyItem);
menu->addItem(&m_pasteItem);
menu->addItem(&m_deleteItem);
menu->addItem(&m_separatorItem);
menu->addItem(&m_selectAllItem);
menu->addActionListener(this);
}
}
void TextField::paintBackground( const agui::PaintEvent &paintEvent )
{
agui::Image* img = NULL;
if(isFocused())
{
img = m_focusImage;
}
else
{
img = m_bgImage;
}
paintEvent.graphics()->drawNinePatchImage(img,agui::Point(0,0),getSize());
}
void TextField::paintComponent( const agui::PaintEvent &paintEvent )
{
int caretLoc = getCaretLocation();
int textLoc = getTextOffset();
agui::Rectangle sideclip = getInnerRectangle();
sideclip = agui::Rectangle(sideclip.getX() + getLeftPadding() ,
sideclip.getY() + 2,sideclip.getSize().getWidth() - getLeftPadding()
- getRightPadding() + 1, sideclip.getHeight() - 4);
paintEvent.graphics()->pushClippingRect(sideclip);
if(getSelectionStart() != getSelectionEnd() && (isFocused() || !isHidingSelection()) )
{
agui::Rectangle selRect = agui::Rectangle(
getSelectionLocation(),
(getInnerHeight() / 2) -
(getFont()->getLineHeight() / 2),
getSelectionWidth(),
getFont()->getLineHeight());
paintEvent.graphics()->drawFilledRectangle(
selRect,getSelectionBackColor());
}
paintEvent.graphics()->drawText(agui::Point(textLoc, +
((getInnerSize().getHeight() - getFont()->getLineHeight()) / 2)),getText().c_str(),
getFontColor(),getFont());
if(isFocused())
{
if(isBlinking())
paintEvent.graphics()->drawLine(agui::Point(caretLoc + 1,
((getInnerSize().getHeight() / 2) + (getFont()->getLineHeight() / 2))),
agui::Point(caretLoc + 1, ((getInnerSize().getHeight() / 2) -
(getFont()->getLineHeight() / 2))),
agui::Color(0,0,0));
}
paintEvent.graphics()->popClippingRect();
}
void TextField::actionPerformed( const agui::ActionEvent &evt )
{
if(evt.getSource() == &m_selectAllItem)
{
selectAll();
focus();
}
else if(evt.getSource() == &m_copyItem)
{
copy();
focus();
}
else if(evt.getSource() == &m_pasteItem)
{
if(!isReadOnly())
{
paste();
focus();
}
}
else if(evt.getSource() == &m_cutItem)
{
cut();
focus();
}
else if(evt.getSource() == &m_deleteItem)
{
if(!isReadOnly())
{
deleteSelection();
focus();
}
}
}
void TextField::mouseDown( agui::MouseEvent &mouseEvent )
{
agui::TextField::mouseDown(mouseEvent);
if(mouseEvent.getButton() == agui::MOUSE_BUTTON_RIGHT)
{
if(m_menu)
{
m_pasteItem.setEnabled(!isReadOnly());
m_cutItem.setEnabled(!isReadOnly() && !(getSelectionStart() == getSelectionEnd()));
m_copyItem.setEnabled(!(getSelectionStart() == getSelectionEnd()));
m_deleteItem.setEnabled(!isReadOnly() && !(getSelectionStart() == getSelectionEnd()));
m_menu->showPopUp(this,mouseEvent.getX(),mouseEvent.getY());
}
}
}
}
|
#pragma once
#include <stdio.h>
#include "Figura.h"
#include <map>
class Ploca
{
private:
std::map<int, Figura*> polje;
public:
Ploca();
virtual ~Ploca();
void zauzmiPolje(Figura* figura,int trenutnoPolje);
Figura* provjeraPolja(int trenutnoPolje);
};
|
#pragma once
/// Includes ///
#include <GL/glew.h>
#include <glm/glm.hpp>
#include <glm/mat4x4.hpp>
#include <glm/mat4x3.hpp>
#include <glm/vec4.hpp>
#include <glm/vec3.hpp>
#include <glm/vec2.hpp>
#include <openvr.h>
#include <map>
#include <exception>
#include <string>
#include <vector>
/// Re-definitions ///
typedef unsigned int uint;
typedef unsigned char uchar;
/// String Functions ///
std::string StringPrintf(const std::string fmt, ...);
std::vector<std::string> Split(const std::string& s, char delimiter);
/// Print Functions ///
void PrintMat(vr::HmdMatrix34_t mat);
void PrintMat(glm::mat4x4);
void PrintMat(glm::mat3x3);
void PrintMat(glm::mat4x3);
void PrintVec(glm::vec4);
void PrintVec(glm::vec3);
void PrintVec(glm::vec2);
void ClearConsole();
/// OpenGL error Checking ///
class WorldException : public std::exception {
std::string mReason;
public:
WorldException(std::string reason) : mReason(reason) {}
const char *what() const noexcept override { return mReason.c_str(); }
};
/// redefines for inline error checking.
#define GLChkErr GLChkErrFtn(__LINE__, __FILE__)
void GLChkErrFtn(int, std::string);
/// Error map for easy access
const std::map<int, std::string> cError
{{GL_NO_ERROR, "GL_NO_ERROR"},
{GL_INVALID_ENUM, "GL_INVALID_ENUM"},
{GL_INVALID_VALUE, "GL_INVALID_VALUE"},
{GL_INVALID_OPERATION, "GL_INVALID_OPERATION"},
{GL_INVALID_FRAMEBUFFER_OPERATION, "GL_INVALID_FRAMEBUFFER_OPERATION"},
{GL_OUT_OF_MEMORY, "GL_OUT_OF_MEMORY"},
{GL_STACK_UNDERFLOW, "GL_STACK_UNDERFLOW"},
{GL_STACK_OVERFLOW, "GL_STACK_OVERFLOW"}};
|
/*
* @lc app=leetcode.cn id=85 lang=cpp
*
* [85] 最大矩形
*/
#include <vector>
#include <stack>
// @lc code=start
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
if (matrix.size() == 0 || matrix[0].size() == 0) return 0;
// 判断行列是否均为0
int H = matrix.size(), W = matrix[0].size();
int height[W+1];
int i, j , MAX = 0;
stack<int> st;
memset(height, 0, sizeof(height)); // 给数组初始化, 数组右端端又会有一个哨兵
for (i = 0; i < H; ++ i) {
while (!st.empty()) st.pop(); // 每次循环均清空栈
for (j = 0; j < W; ++j) {
if(matrix[i][j] == '1') height[j]++;
else height[j] = 0;
}
for (int j = 0; j <= W; ++j) {
while (!st.empty() && height[st.top()] > height[j]) {
int tmp = st.top();
st.pop();
MAX = max(MAX, height[tmp] * (st.empty() ? j : j - st.top() - 1)); // 求最大面积
}
st.push(j); // 压入单调栈
}
}
return MAX;
}
};
// @lc code=end
|
#include "mainwindow.h"
#include "setupdialog.h"
#include "initialdialog.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
InitialDialog id;
if (id.exec() == 0)
{
exit(0);
}
SetupDialog d;
if (d.exec() == 0)
{
exit(0);
}
MainWindow w;
w.show();
return a.exec();
}
|
// IsCryptSolution
// Given [word1, word2, word3], check word1+word2=word3, containing no numbers with leading zeroes
// For crypt = ["SEND", "MORE", "MONEY"] and
// solution = [['O', '0'],
// ['M', '1'],
// ['Y', '2'],
// ['E', '5'],
// ['N', '6'],
// ['D', '7'],
// ['R', '8'],
// ['S', '9']]
// the output should be
// isCryptSolution(crypt, solution) = true, since 9567 + 1085 = 10652.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
bool isCryptSolution (vector<string>& crypt, vector<vector<char>>& solution) {
for (string & s : crypt) {
for (vector<char> sol : solution) replace(s.begin(), s.end(), sol[0], sol[1]); // #include <algorithm>
}
for (string s : crypt) {
if (s[0] == '0' && s.size() > 1) return false;
}
return stoi(crypt[0]) + stoi(crypt[1]) == stoi(crypt[2]);
}
int main() {
vector<vector<char>> solution = {{'O', '0'}, {'M', '1'}, {'Y', '2'},
{'E', '5'}, {'N', '6'}, {'D', '7'},
{'R', '8'}, {'S', '9'}};
vector<string> crypt = {"SEND", "MORE", "MONEY"};
if (isCryptSolution(crypt, solution))
cout << "True" << endl;
else
cout << "False" << endl;
return 0;
}
|
//
// JsonData.cpp
// SMFrameWork
//
// Created by SteveMac on 2018. 5. 21..
//
#include "JsonData.h"
const char * CheckVersionInfoString::APP_ID = "APP_ID";
const char * CheckVersionInfoString::ResultMessage = "ResultMessage";
const char * CheckVersionInfoString::VER_NUM = "VER_NUM";
const char * CheckVersionInfoString::Result = "Result";
bool CheckVersion::parseFunc(JsonWrapper<CheckVersion> &p, CheckVersion &item)
{
item.APP_ID = p.getString(CheckVersionInfoString::APP_ID);
item.ResultMessage = p.getString(CheckVersionInfoString::ResultMessage);
item.VER_NUM = p.getString(CheckVersionInfoString::VER_NUM);
item.Result = p.getString(CheckVersionInfoString::Result);
return true;
}
const char * SummaryInfoString::SEND_UNCHECK = "SEND_UNCHECK";
const char * SummaryInfoString::ORDER_UNCHECK = "ORDER_UNCHECK";
const char * SummaryInfoString::ORDER_REPORT_MONTH = "ORDER_REPORT_MONTH";
const char * SummaryInfoString::SEND_MONTH = "SEND_MONTH";
const char * SummaryInfoString::SEND_TOTAL = "SEND_TOTAL";
const char * SummaryInfoString::RECEIVE_UNCHECK = "RECEIVE_UNCHECK";
const char * SummaryInfoString::ORDER_DECIDE_WAIT = "ORDER_DECIDE_WAIT";
const char * SummaryInfoString::RECEIVE_MONTH = "RECEIVE_MONTH";
const char * SummaryInfoString::ORDER_REPORT_UNCHECK = "ORDER_REPORT_UNCHECK";
const char * SummaryInfoString::ORDER_MONTH = "ORDER_MONTH";
const char * SummaryInfoString::BOARD_NEW_COUNT = "BOARD_NEW_COUNT";
const char * SummaryInfoString::RECEIVE_TOTAL = "RECEIVE_TOTAL";
bool SummaryInfo::parseFunc(JsonWrapper<SummaryInfo> &p, SummaryInfo &item)
{
item.SEND_UNCHECK = p.getString(SummaryInfoString::SEND_UNCHECK);
item.ORDER_UNCHECK = p.getString(SummaryInfoString::ORDER_UNCHECK);
item.ORDER_REPORT_MONTH = p.getString(SummaryInfoString::ORDER_REPORT_MONTH);
item.SEND_MONTH = p.getString(SummaryInfoString::SEND_MONTH);
item.SEND_TOTAL = p.getString(SummaryInfoString::SEND_TOTAL);
item.RECEIVE_UNCHECK = p.getString(SummaryInfoString::RECEIVE_UNCHECK);
item.ORDER_DECIDE_WAIT = p.getString(SummaryInfoString::ORDER_DECIDE_WAIT);
item.RECEIVE_MONTH = p.getString(SummaryInfoString::RECEIVE_MONTH);
item.ORDER_REPORT_UNCHECK = p.getString(SummaryInfoString::ORDER_REPORT_UNCHECK);
item.ORDER_MONTH = p.getString(SummaryInfoString::ORDER_MONTH);
item.BOARD_NEW_COUNT = p.getString(SummaryInfoString::BOARD_NEW_COUNT);
item.RECEIVE_TOTAL = p.getString(SummaryInfoString::RECEIVE_TOTAL);
return true;
}
const char * NewCheckInfoString::REPORT_NEW_CNT = "REPORT_NEW_CNT";
const char * NewCheckInfoString::NOTICE_NEW_CNT = "NOTICE_NEW_CNT";
const char * NewCheckInfoString::BOARD_NEW_COUNT = "BOARD_NEW_COUNT";
const char * NewCheckInfoString::ORDER_NEW_CNT = "ORDER_NEW_CNT";
bool NewCheckInfo::parseFunc(JsonWrapper<NewCheckInfo> &p, NewCheckInfo &item)
{
item.REPORT_NEW_CNT = p.getString(NewCheckInfoString::REPORT_NEW_CNT);
item.NOTICE_NEW_CNT = p.getString(NewCheckInfoString::NOTICE_NEW_CNT);
item.BOARD_NEW_COUNT = p.getString(NewCheckInfoString::BOARD_NEW_COUNT);
item.ORDER_NEW_CNT = p.getString(NewCheckInfoString::ORDER_NEW_CNT);
return true;
}
|
//~ author : Sumit Prajapati
#include <bits/stdc++.h>
using namespace std;
#define ull unsigned long long
#define ll long long
#define int long long
#define pii pair<int, int>
#define pll pair<ll, ll>
#define pb push_back
#define mk make_pair
#define ff first
#define ss second
#define all(a) a.begin(),a.end()
#define trav(x,v) for(auto &x:v)
#define rep(i,n) for(int i=0;i<n;i++)
#define repe(i,n) for(int i=1;i<=n;i++)
#define read(a,n) rep(i,n)cin>>a[i]
#define reade(a,n) repe(i,n)cin>>a[i]
#define FOR(i,a,b) for(int i=a;i<=b;i++)
#define printar(a,s,e) FOR(i,s,e)cout<<a[i]<<" ";cout<<'\n'
#define curtime chrono::high_resolution_clock::now()
#define timedif(start,end) chrono::duration_cast<chrono::nanoseconds>(end - start).count()
auto time0 = curtime;
const int MD=1e9+7;
const int MDL=998244353;
const int INF=1e9;
const int MX=1505;
const int p=101;
int powp[MX];
void solve(){
string s;
cin>>s;
string isbad;
cin>>isbad;
int k;
cin>>k;
set<int>st;
int n=s.length();
rep(i,n){
int cur_hash1=0;
int cur_hash2=0;
int bad=0;
for(int j=i;j<n;j++){
cur_hash1=(cur_hash1+(s[j]-'a'+1)*powp[j-i]);
bad+=(isbad[s[j]-'a']=='0');
if(bad<=k){
st.insert(cur_hash1);
}
}
}
cout<<(int)st.size()<<'\n';
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
time0 = curtime;
srand(time(NULL));
int t=1;
// cin>>t;
powp[0]=1;
repe(i,MX-1)
powp[i]=p*powp[i-1];
repe(tt,t){
// cout<<"Case #"<<tt<<": ";
solve();
}
// cerr<<"Execution Time: "<<timedif(time0,curtime)*1e-9<<" sec\n";
return 0;
}
|
#include <iostream>
#include <stdio.h>
#include <cstring>
#include <cstdlib>
#include <vector>
#include <cstring>
#include <set>
using namespace std;
int lcp(const string& a, const string& b) {
int lim = min(a.size(), b.size());
for (int i = 0; i < lim; ++i)
if (a[i] != b[i]) return i;
return lim;
}
int main() {
string s;
cin >> s;
int n = s.size();
set<string> q;
for (int i = 0; i < n; ++i) {
for (int j = 0; i + j <= n; ++j) {
q.insert(s.substr(i, j));
}
}
int mx = 0;
set<int> qq;
for (int i = 0; i < n; ++i)
for (int j = i + 1; j < n; ++j) {
int val = lcp(s.substr(i), s.substr(j));
mx = max(mx, val);
qq.insert(val);
}
cout << q.size() << " " << mx << " " << qq.size() << endl;
return 0;
}
|
#pragma once
#include <tudocomp/Compressor.hpp>
#include <tudocomp/decompressors/WrapDecompressor.hpp>
namespace tdc {
class NoopCompressor: public CompressorAndDecompressor {
public:
inline static Meta meta() {
Meta m(Compressor::type_desc(), "noop",
"Simply forwards the unmodified input to the output.");
m.param("mode",
"The processing mode:\n"
"\"stream\" - Streams the input\n"
"\"buffer\" - Buffers the input\n"
).primitive("stream");
m.param("debug", "Enables debugging").primitive(false);
return m;
}
using CompressorAndDecompressor::CompressorAndDecompressor;
inline virtual void compress(Input& i, Output& o) override final {
auto os = o.as_stream();
if (config().param("mode").as_string() == "stream") {
auto is = i.as_stream();
if (config().param("debug").as_bool()) {
std::stringstream ss;
ss << is.rdbuf();
std::string txt = ss.str();
DLOG(INFO) << vec_to_debug_string(txt);
os << txt;
} else {
os << is.rdbuf();
}
} else {
auto iv = i.as_view();
if (config().param("debug").as_bool()) {
DLOG(INFO) << vec_to_debug_string(iv);
os << iv;
} else {
os << iv;
}
}
}
inline virtual void decompress(Input& i, Output& o) override final {
auto os = o.as_stream();
if (config().param("mode").as_string() == "stream") {
auto is = i.as_stream();
if (config().param("debug").as_bool()) {
std::stringstream ss;
ss << is.rdbuf();
std::string txt = ss.str();
DLOG(INFO) << vec_to_debug_string(txt);
os << txt;
} else {
os << is.rdbuf();
}
} else {
auto iv = i.as_view();
if (config().param("debug").as_bool()) {
DLOG(INFO) << vec_to_debug_string(iv);
os << iv;
} else {
os << iv;
}
}
}
inline std::unique_ptr<Decompressor> decompressor() const override {
return std::make_unique<WrapDecompressor>(*this);
}
};
}
|
#ifndef __THREAD_H
#define __THREAD_H
/*
*****************************************************************************
* ___ _ _ _ _
* / _ \ __ _| |_| |__(_) |_ ___
* | (_) / _` | / / '_ \ | _(_-<
* \___/\__,_|_\_\_.__/_|\__/__/
* Copyright (c) 2011
*
* 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.
*****************************************************************************/
/**
* @author R. Picard
* @date 2011/05/08
*
*****************************************************************************/
#include <stdint.h>
#include <pthread.h>
namespace edkit
{
class Thread
{
public:
Thread(void);
virtual ~Thread(void);
int32_t Start(void);
int32_t WaitForEnd(void);
bool IsStarted(void) const {return(Started);};
protected:
virtual void Loop(void) = 0;
private:
static void* PThreadLoop(void* p_Thread);
pthread_t ThreadId;
bool Started;
};
} // namespace
#endif
|
//Semestre 2019-2
//RCSE
//************************************************************//
#include "texture.h"
#include "figuras.h"
#include "Camera.h"
#include <windows.h>
#include <mmsystem.h>
#include "cmodel/CModel.h"
#if (_MSC_VER >= 1900)
# pragma comment( lib, "legacy_stdio_definitions.lib" )
#endif
float pX = 0, pY = 0, pZ = 0, tamX = 1, tamY = 1, tamZ = 1, rot1 = 0;
//Para crear una figura
float rot = 0.0;
int w = 500, h = 500;
int frame=0,time,timebase=0;
int deltaTime = 0;
CCamera objCamera; //Create objet Camera
GLfloat g_lookupdown = 0.0f; // Look Position In The Z-Axis (NEW)
CTexture text1;
CTexture text2;
CTexture text3; //Flecha
CTexture pisoLoceta;
CTexture pisoLocetaExt;
CTexture tree;
CTexture pisojardin;
CTexture hoja;
CTexture door;
CTexture pasto;
CTexture alfombra;
CTexture garage;
CTexture gpiso;
CTexture paredpink;
CTexture ParedBlanca;
CTexture ParedBlanca2;
CTexture VentanaSimple;
CTexture Ventana;
CTexture verd;
CTexture manta;
CTexture azul;
CTexture alfombra4;
CTexture alfombra5;
CTexture tcesped1;
////Textura Muebles
CTexture cabecera;
CTexture SabanaColchon;
CTexture Buro;
CTexture buro;
CTexture cobijaac;
CTexture azulgris;
CTexture metallamp;
CTexture metallamp2;
CTexture tlamp1;
CTexture tlamp2;
CTexture bmetalico;
CTexture tlamp3;
CTexture tlamp4;
CFiguras sky;
CFiguras bardas;
CFiguras obj; //obj prisma, obj esfera. obj.esfera
void lamp(GLuint textura1, GLuint textura2)
{
glPushMatrix();
glDisable(GL_LIGHTING);
glTranslatef(-18.0, 0.20, -6.35);
obj.cilindro(0.20, 0.05, 20, textura1);
glEnable(GL_LIGHTING);
glPopMatrix();
glPushMatrix();
glDisable(GL_LIGHTING);
glTranslatef(-18.0, 0.25, -6.35);
obj.cilindro(0.03, 0.5, 20, textura1);
glEnable(GL_LIGHTING);
glPopMatrix();
glPushMatrix();
glDisable(GL_LIGHTING);
glTranslatef(-18.0, 0.75, -6.35);
obj.cilindro(0.2, 0.6, 20, textura2);
glEnable(GL_LIGHTING);
glPopMatrix();
}
void cesped(GLuint textura1)
{
GLfloat vertice[8][3] = {
{ 0.0 ,0.0, 0.0 }, //Coordenadas Vértice 0 V0
{ 1.0 ,0.0, 0.0 }, //Coordenadas Vértice 1 V1
{ 1.0 ,1.0, 0.0 }, //Coordenadas Vértice 2 V2
{ 0.0 ,1.0, 0.0 }, //Coordenadas Vértice 3 V3
{ 0.0 ,0.0, 1.0 }, //Coordenadas Vértice 4 V4
{ 1.0 ,0.0, 1.0 }, //Coordenadas Vértice 5 V5
{ 1.0 ,1.0, 1.0 }, //Coordenadas Vértice 6 V6
{ 0.0 ,1.0, 1.0 }, //Coordenadas Vértice 7 V7
};
glBindTexture(GL_TEXTURE_2D, textura1); // choose the texture to use.
glBegin(GL_POLYGON); //Front
glColor3f(1.0, 1.0, 1.0);
glNormal3f(0.0f, 0.0f, 1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3fv(vertice[4]);
glTexCoord2f(1.0, 0.0f); glVertex3fv(vertice[5]);
glTexCoord2f(1.0, 1.0); glVertex3fv(vertice[6]);
glTexCoord2f(0.0f, 1.0); glVertex3fv(vertice[7]);
glEnd();
glBegin(GL_POLYGON); //Right
glNormal3f(1.0f, 0.0f, 0.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3fv(vertice[1]);
glTexCoord2f(1.0f, 0.0f); glVertex3fv(vertice[5]);
glTexCoord2f(1.0f, 1.0f); glVertex3fv(vertice[6]);
glTexCoord2f(0.0f, 1.0f); glVertex3fv(vertice[2]);
glEnd();
glBegin(GL_POLYGON); //Back
glNormal3f(0.0f, 0.0f, -1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3fv(vertice[0]);
glTexCoord2f(1.0f, 0.0f); glVertex3fv(vertice[1]);
glTexCoord2f(1.0f, 1.0f); glVertex3fv(vertice[5]);
glTexCoord2f(0.0f, 1.0f); glVertex3fv(vertice[4]);
glEnd();
glBegin(GL_POLYGON); //Left
glNormal3f(-1.0f, 0.0f, 0.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3fv(vertice[0]);
glTexCoord2f(1.0f, 0.0f); glVertex3fv(vertice[3]);
glTexCoord2f(1.0f, 1.0f); glVertex3fv(vertice[7]);
glTexCoord2f(0.0f, 1.0f); glVertex3fv(vertice[4]);
glEnd();
glBegin(GL_POLYGON); //Bottom
glNormal3f(0.0f, -1.0f, 0.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3fv(vertice[0]);
glTexCoord2f(1.0f, 0.0f); glVertex3fv(vertice[1]);
glTexCoord2f(1.0f, 1.0f); glVertex3fv(vertice[2]);
glTexCoord2f(0.0f, 1.0f); glVertex3fv(vertice[3]);
glEnd();
glBegin(GL_POLYGON); //Top
glNormal3f(0.0f, 1.0f, 0.0f);
glTexCoord2f(10.0, 0.0f); glVertex3fv(vertice[3]);
glTexCoord2f(10.0, 10.0f); glVertex3fv(vertice[2]);
glTexCoord2f(0.0, 10.0f); glVertex3fv(vertice[6]);
glTexCoord2f(0.0f, 0.0f); glVertex3fv(vertice[7]);
glEnd();
}
void InitGL ( GLvoid ) // Inicializamos parametros
{
glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // Negro de fondo
glEnable(GL_TEXTURE_2D);
glShadeModel (GL_SMOOTH);
glEnable ( GL_COLOR_MATERIAL );
glClearDepth(1.0f); // Configuramos Depth Buffer
glEnable(GL_DEPTH_TEST); // Habilitamos Depth Testing
glDepthFunc(GL_LEQUAL); // Tipo de Depth Testing a realizar
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glEnable(GL_AUTO_NORMAL);
glEnable(GL_NORMALIZE);
text1.LoadTGA("sky1.tga");
text1.BuildGLTexture();
text1.ReleaseImage();
text3.LoadTGA("texturas/city/arrow.tga");
text3.BuildGLTexture();
text3.ReleaseImage();
pisojardin.LoadTGA("texturas/pisojardin.tga");
pisojardin.BuildGLTexture();
pisojardin.ReleaseImage();
hoja.LoadTGA("texturas/hoja.tga");
hoja.BuildGLTexture();
hoja.ReleaseImage();
door.LoadTGA("texturas/door.tga");
door.BuildGLTexture();
door.ReleaseImage();
pasto.LoadTGA("texturas/pasto.tga");
pasto.BuildGLTexture();
pasto.ReleaseImage();
alfombra.LoadTGA("texturas/alfombra.tga");
alfombra.BuildGLTexture();
alfombra.ReleaseImage();
garage.LoadTGA("texturas/garage.tga");
garage.BuildGLTexture();
garage.ReleaseImage();
gpiso.LoadTGA("texturas/gpiso.tga");
gpiso.BuildGLTexture();
gpiso.ReleaseImage();
pisoLocetaExt.LoadTGA("texturas/pisogris.tga");
pisoLocetaExt.BuildGLTexture();
pisoLocetaExt.ReleaseImage();
VentanaSimple.LoadTGA("texturas/VentanaSimple.tga");
VentanaSimple.BuildGLTexture();
VentanaSimple.ReleaseImage();
paredpink.LoadTGA("texturas/paredpink.tga");
paredpink.BuildGLTexture();
paredpink.ReleaseImage();
ParedBlanca2.LoadTGA("texturas/ParedBlanca2.tga");
ParedBlanca2.BuildGLTexture();
ParedBlanca2.ReleaseImage();
//texturas muebles
buro.LoadTGA("texturas/buro.tga");//buro
buro.BuildGLTexture();
buro.ReleaseImage();
azulgris.LoadTGA("texturas/azulgris.tga");
azulgris.BuildGLTexture();
azulgris.ReleaseImage();
metallamp.LoadTGA("texturas/metallamp.tga");
metallamp.BuildGLTexture();
metallamp.ReleaseImage();
metallamp2.LoadTGA("texturas/metallamp2.tga");
metallamp2.BuildGLTexture();
metallamp2.ReleaseImage();
tlamp1.LoadTGA("texturas/lamp2.tga");
tlamp1.BuildGLTexture();
tlamp1.ReleaseImage();
bmetalico.LoadTGA("texturas/bmetalico.tga");
bmetalico.BuildGLTexture();
bmetalico.ReleaseImage();
verd.LoadTGA("texturas/verd.tga");
verd.BuildGLTexture();
verd.ReleaseImage();
manta.LoadTGA("texturas/manta.tga");
manta.BuildGLTexture();
manta.ReleaseImage();
azul.LoadTGA("texturas/azul.tga");
azul.BuildGLTexture();
azul.ReleaseImage();
alfombra4.LoadTGA("texturas/alfombra4.tga");
alfombra4.BuildGLTexture();
alfombra4.ReleaseImage();
alfombra5.LoadTGA("texturas/alfombra5.tga");
alfombra5.BuildGLTexture();
alfombra5.ReleaseImage();
tree.LoadTGA("texturas/tree.tga");
tree.BuildGLTexture();
tree.ReleaseImage();
cabecera.LoadTGA("texturas/cabecera.tga");
cabecera.BuildGLTexture();
cabecera.ReleaseImage();
SabanaColchon.LoadTGA("Muebles/SabanaColchon.tga");
SabanaColchon.BuildGLTexture();
SabanaColchon.ReleaseImage();
Buro.LoadTGA("Muebles/Buro.tga");
Buro.BuildGLTexture();
Buro.ReleaseImage();
//END NEW//////////////////////////////
objCamera.Position_Camera(0,2.5f,3, 0,2.5f,0, 0, 1, 0);
}
void display ( void ) // Creamos la funcion donde se dibuja
{
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glPushMatrix();
glRotatef(g_lookupdown,1.0f,0,0);
gluLookAt( objCamera.mPos.x, objCamera.mPos.y, objCamera.mPos.z,
objCamera.mView.x, objCamera.mView.y, objCamera.mView.z,
objCamera.mUp.x, objCamera.mUp.y, objCamera.mUp.z);
glPushMatrix();
glPushMatrix(); //Creamos cielo
glDisable(GL_LIGHTING);
glTranslatef(-20,67,-35);
glColor3f(1.0, 1.0, 1.0);
sky.skybox(180.0, 180.0, 180.0,text1.GLindex);// Cielo
glEnable(GL_LIGHTING);
//glColor3f(1.0, 1.0, 1.0);
glPopMatrix();
//Colocamos codigo
//Elementos que dibujaremos
glPushMatrix();///////////////////////////
///////////////////////////////////////////////////////////////////////////////jardin
glPushMatrix();//loceta piso
glDisable(GL_LIGHTING);
glTranslatef(-40.80, -4.99, 22.10);
bardas.prisma(0.01,3.80,2.25, gpiso.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
glPushMatrix();//loceta piso
glDisable(GL_LIGHTING);
glTranslatef(-41.20, -4.99, 16.61);
glRotatef(45, 0, 1, 0);
bardas.prisma(0.01, 3.86, 2.34, gpiso.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
glPushMatrix();//loceta piso
glDisable(GL_LIGHTING);
glTranslatef(-39.40, -4.99, 18.80);
glScalef(1, 0.01, 1);
bardas.esfera(1.4, 20, 20, gpiso.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
glPushMatrix();//loceta piso
glDisable(GL_LIGHTING);
glTranslatef(-41.50,-4.99,13);
glScalef(0.49, 0.01, 1.31);
bardas.esfera(1.4, 20, 20, gpiso.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
glPushMatrix();//loceta piso
glDisable(GL_LIGHTING);
glTranslatef(-39.20, -4.99, 13.70);
glScalef(0.49, 0.01, 1.31);
bardas.esfera(1.4, 20, 20, gpiso.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
glPushMatrix();//loceta piso
glDisable(GL_LIGHTING);
glTranslatef(-40.40, -4.99, 9.90);
glRotatef(-45, 0, 1, 0);
bardas.prisma(0.01, 3.56, 2.83, gpiso.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
//////////////////////////////////////////////////////////////loceta puerta garage
glPushMatrix();//loceta piso
glDisable(GL_LIGHTING);
glTranslatef(-22, -4.99, -9.10);
bardas.prisma(0.01, 7.80, 3.5, gpiso.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
glPushMatrix();//loceta piso
glDisable(GL_LIGHTING);
glTranslatef(-22, -4.99, -5.10);
bardas.prisma(0.01, 7.80, 3.5, gpiso.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
glPushMatrix();//loceta piso
glDisable(GL_LIGHTING);
glTranslatef(-22, -4.99, -1.10);
bardas.prisma(0.01, 7.80, 3.5, gpiso.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
glPushMatrix();//loceta piso
glDisable(GL_LIGHTING);
glTranslatef(-22, -4.99, 3.10);
bardas.prisma(0.01, 7.80, 3.5, gpiso.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
glPushMatrix();//loceta piso
glDisable(GL_LIGHTING);
glTranslatef(-22, -4.99, 7.10);
bardas.prisma(0.01, 7.80, 3.5, gpiso.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
glPushMatrix();//loceta piso
glDisable(GL_LIGHTING);
glTranslatef(-22, -4.99, 12.10);
bardas.prisma(0.01, 7.80, 3.5, gpiso.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
glPushMatrix();//loceta piso
glDisable(GL_LIGHTING);
glTranslatef(-22, -4.99, 17.10);
bardas.prisma(0.01, 7.80, 3.5, gpiso.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
glPushMatrix();//loceta piso
glDisable(GL_LIGHTING);
glTranslatef(-22, -4.99, 22.10);
bardas.prisma(0.01, 7.80, 3.5, gpiso.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
///////////////////////////////////////////////////////////////////////////Cesped
glPushMatrix();
glDisable(GL_LIGHTING);
glTranslatef(-38, -5, -2.89);
glScalef(10,1,2.79);
cesped(pasto.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
//////////////////////////////////////////////////////////////plantas
glPushMatrix();
glDisable(GL_LIGHTING);
glTranslatef(-36,1.0,-1);
obj.esfera(0.9, 2, 20, hoja.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
glPushMatrix(); //tronco
glDisable(GL_LIGHTING);
glTranslatef(-36,-7.0,-1);
obj.cilindro(0.03, 7.28, 20, tree.GLindex); //textura tronco arbol
glEnable(GL_LIGHTING);
glPopMatrix();
glPushMatrix();//2
glDisable(GL_LIGHTING);
glTranslatef(-33, 1.0, -1);
obj.esfera(0.9, 2, 20, hoja.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
glPushMatrix(); //tronco arbol
glDisable(GL_LIGHTING);
glTranslatef(-33, -7.0, -1);
obj.cilindro(0.03, 7.28, 20, tree.GLindex); //textura tronco arbol
glEnable(GL_LIGHTING);
glPopMatrix();
glPushMatrix();//3
glDisable(GL_LIGHTING);
glTranslatef(-30, 1.0, -1);
obj.esfera(0.9, 2, 20, hoja
.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
glPushMatrix(); //tronco arbol
glDisable(GL_LIGHTING);
glTranslatef(-30, -7.0, -1);
obj.cilindro(0.03, 7.28, 20, tree.GLindex); //textura tronco arbol
glEnable(GL_LIGHTING);
glPopMatrix();
glPushMatrix(); ///////////////////////////////////////////////////////////CESPED PUERTAA
glDisable(GL_LIGHTING);
glTranslatef(-59.80, -5.10, 1.30);
glScalef(35, 0.01, 25);
cesped(pasto.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
glPushMatrix();///////////////////////////////////cesped derecha
glDisable(GL_LIGHTING);
glTranslatef(-27.7, -5.0, -70);
glScalef(40, 0.01, 95);
cesped(pasto.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
/////////////////////////CESPED ORILLAS
glPushMatrix();
glDisable(GL_LIGHTING);
glTranslatef(-27.7, -5.0, -70);
glScalef(40, 0.01, 95);
cesped(pasto.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
glPushMatrix();
glDisable(GL_LIGHTING);
glTranslatef(-85.7, -5.0, -70);
glScalef(35, 0.01, 95);
cesped(pasto.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
////////////////////////////////////////////////////////////7muebles
glDisable(GL_LIGHTING);
glPushMatrix();//Cama
glPushMatrix();//Cabecera
glTranslatef(-37,1.5,-39.7);
glRotatef(180, 0.0, 1.0, 0.0);
bardas.prisma(5, 10, 0.5, cabecera.GLindex);
glPopMatrix();
glPushMatrix();//Colchon rosa
glTranslatef(-37, -1.3,-35.7);
glRotatef(90, 1.0, 0.0, 0.0);
bardas.prisma(6.7, 2.7, 4, manta.GLindex);
glPopMatrix();
//glPushMatrix();//Cobija
//glTranslatef(-37.1, 0.70, -35.7);
//glRotatef(90, 1.0, 0.0, 0.0);
//bardas.prisma(6.7, 2.7, 0.1, CabeceraColchon.GLindex);
//glPopMatrix();
glPushMatrix();//Almohada
glTranslatef(-37,0.70,-37.7);
glRotatef(90, 1.0, 0.0, 0.0);
bardas.prisma(1.6, 1.3, 1.2, SabanaColchon.GLindex);
glPopMatrix();
glPushMatrix();//Colchon verde
glTranslatef(-40, -1.3, -35.7);
glRotatef(90, 1.0, 0.0, 0.0);
bardas.prisma(6.7, 2.7, 4, verd.GLindex);
glPopMatrix();
glPushMatrix();//Almohada
glTranslatef(-40, 0.70, -37.7);
glRotatef(90, 1.0, 0.0, 0.0);
bardas.prisma(1.6, 1.3, 1.2, SabanaColchon.GLindex);
glPopMatrix();
glPushMatrix();//Colchon azul
glTranslatef(-34, -1.3, -35.7);
glRotatef(90, 1.0, 0.0, 0.0);
bardas.prisma(6.7, 2.7, 4, azul.GLindex);
glPopMatrix();
glPushMatrix();//Almohada
glTranslatef(-34, 0.70, -37.7);
glRotatef(90, 1.0, 0.0, 0.0);
bardas.prisma(1.6, 1.3, 1.2, SabanaColchon.GLindex);
glPopMatrix();
glPopMatrix();
////////////////////////////////////////////////////// ////Creacion del Buro
glPushMatrix();//Mueble
glTranslatef(-44, -1.3, -35.7);
//glRotatef(180, 0.0, 1.0, 0.0);
bardas.prisma(3, 1.5, 1.5, cabecera.GLindex);
glPopMatrix();
glPushMatrix();//Frente
glTranslatef(-44, -1.3, -34.99);
//glRotatef(180, 0.0, 1.0, 0.0);
bardas.prisma(3, 1.5, 0.1, Buro.GLindex);
glPopMatrix();
glPopMatrix();
//////////////////////////////////////////////////////////Creacion del Buro 2
glPushMatrix();//Mueble
glTranslatef(-30, -2.5, -22.5);
//glRotatef(90, 0.0, 1.0, 0.0);
bardas.prisma(3, 1.5, 1.5, cabecera.GLindex);
glPopMatrix();
glPushMatrix();//Frente
glTranslatef(-30.8, -2.5, -22.5);
glRotatef(90, 0.0, 1.0, 0.0);
bardas.prisma(3, 1.5, 0.1, Buro.GLindex);
glPopMatrix();
glPushMatrix();//repisa
glTranslatef(-31, 5, -40.5);
//glRotatef(90, 0.0, 1.0, 0.0);
bardas.prisma(0.55, 1.7, 0.4, cabecera.GLindex);
glPopMatrix();
glPushMatrix();//repisa 2
glTranslatef(-31, 7, -40.5);
bardas.prisma(0.55, 1.7, 0.4, cabecera.GLindex);
glPopMatrix();
glPushMatrix();//repisa libros
glTranslatef(-43, 7, -40.5);
bardas.prisma(0.55, 1.7, 0.4, cabecera.GLindex);
glPopMatrix();
///////////////////////////////////////////////////LIBROS
//glPushMatrix();//pata
//glTranslatef(3.25, -2.75, 0);
//glRotatef(90, 0.0, 1.0, 0.0);
//bardas.prisma(5, 1, 0.5, Cabecera.GLindex);
//glPopMatrix();
/////////////////////////////////////////////////////////////////////////lampara de buro
glPushMatrix();
glDisable(GL_LIGHTING);
glTranslatef(-8.49 - 1.30, -3.39+ 3.19, -22.50 - 1.40);
glScaled(1 + 0.90, 1 + 0.90, 1 + 0.90);
lamp(metallamp.GLindex, tlamp1.GLindex); //cambiar la textura
glEnable(GL_LIGHTING);
glPopMatrix();
/////////////////////////////////////////////////////////////CONSTRUCCION BARDAS
glPushMatrix();//19 Pivote
glDisable(GL_LIGHTING);
glTranslatef(0, 5, -11.25);
glRotatef(90, 0.0, 1.0, 0.0);
glEnable(GL_LIGHTING);
glPopMatrix();
////////////////////////////////////CASA CENTRAL
glPushMatrix();//Fachada
glDisable(GL_LIGHTING);
glTranslatef(-46.5, 5.5, -2.9);
bardas.prisma(60, 3, 0.2, ParedBlanca2.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
glPushMatrix();//Puerta Fachada Barda Arriba
glDisable(GL_LIGHTING);
glTranslatef(-37, 28, -2.9);
bardas.prisma(16, 18, 0.01, ParedBlanca2.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glPushMatrix();//circulos ventanas
glDisable(GL_LIGHTING);
glTranslatef(-42, 28, -2.9);
obj.esfera(2,25, 25, VentanaSimple.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
glBindTexture(GL_TEXTURE_2D, 0);
glDisable(GL_BLEND);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glPushMatrix();//circulos ventanas
glDisable(GL_LIGHTING);
glTranslatef(-37, 28, -2.9);
obj.esfera(2, 25, 25, VentanaSimple.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
glBindTexture(GL_TEXTURE_2D, 0);
glDisable(GL_BLEND);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glPushMatrix();//circulos ventanas
glDisable(GL_LIGHTING);
glTranslatef(-32, 28, -2.9);
obj.esfera(2, 25,25, VentanaSimple.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
glBindTexture(GL_TEXTURE_2D, 0);
glDisable(GL_BLEND);
////////////////////////////////////////Creacion de las PAREDES
glPushMatrix();
glDisable(GL_LIGHTING);
glTranslatef(-48, 0, -23);
glRotatef(90, 0.0, 1.0, 0.0);
bardas.prisma(70, 40.0, 0.6, ParedBlanca2.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
glPushMatrix();//dentro cuarto
glDisable(GL_LIGHTING);
glTranslatef(-47.7, 0, -22.7);
glRotatef(90, 0.0, 1.0, 0.0);
bardas.prisma(69, 39.5, 0.6, paredpink.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
glPushMatrix();
glDisable(GL_LIGHTING);
glTranslatef(-28, 0, -25.5);
glRotatef(90, 0.0, 1.0, 0.0);
bardas.prisma(70, 34.5, 0.6, ParedBlanca2.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
glPushMatrix();//dentro cuarto
glDisable(GL_LIGHTING);
glTranslatef(-29, 0, -25);
glRotatef(90, 0.0, 1.0, 0.0);
bardas.prisma(69, 34, 0.6, paredpink.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
///////////////////////////pared ventana abajo pricipal
glPushMatrix();
glDisable(GL_LIGHTING);
glTranslatef(-33, -1.3, -2.9);
bardas.prisma(7.7, 10.5, 0.6, ParedBlanca2.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
///////////////////////////////////ventana abajo pared
glPushMatrix();
glDisable(GL_LIGHTING);
glTranslatef(-28, -1.3, -5.5);
glRotatef(90, 0.0, 1.0, 0.0);
bardas.prisma(7.7, 5.5, 0.6, ParedBlanca2.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
//////////////////////////////ventana arriba pared
glPushMatrix();
glDisable(GL_LIGHTING);
glTranslatef(-28, 26.5, -5.5);
glRotatef(90, 0.0, 1.0, 0.0);
bardas.prisma(17.7, 5.5, 0.6, ParedBlanca2.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
//atras
glPushMatrix();
glDisable(GL_LIGHTING);
glTranslatef(-38, 0, -43);
glRotatef(180, 0.0, 1.0, 0.0);
bardas.prisma(70, 20.0, 0.6, ParedBlanca2.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
glPushMatrix();//dentro cuarto
glDisable(GL_LIGHTING);
glTranslatef(-38, 0, -42);
glRotatef(180, 0.0, 1.0, 0.0);
bardas.prisma(69, 19, 0.6, paredpink.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
glPushMatrix();// Puerta Entrada
glDisable(GL_LIGHTING);
glTranslatef(-41.7, 6.0, -2.9);
//glRotatef(90, 0.0, 1.0, 0.0);
bardas.prisma(28, 7, 0.01, door.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
//pared ventana y puerta
glPushMatrix();
glDisable(GL_LIGHTING);
glTranslatef(-37, 11.0, -2.9);
bardas.prisma(18, 2.5, 0.6, ParedBlanca2.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
//arriba ventana puerta
glPushMatrix();
glDisable(GL_LIGHTING);
glTranslatef(-32, 19, -2.9);
bardas.prisma(2.5, 8, 0.6, ParedBlanca2.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
/////////////////////////Loceta exterior cubre todo el terreno
glPushMatrix();//loceta exterior
glDisable(GL_LIGHTING);
glTranslatef(-41.7, -5.1, -37.5);
glRotatef(90, 1.0, 0.0, 0.0);
bardas.prisma(125, 60, 0.01, pisoLocetaExt.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
//Ventana Simple Vidrio Fachada
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glPushMatrix();
glDisable(GL_LIGHTING);
glTranslatef(-32, 10.0, -2.9);
bardas.prisma(15.2, 8., 0.01, VentanaSimple.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
glBindTexture(GL_TEXTURE_2D, 0);
glDisable(GL_BLEND);
//Ventana Simple Vidrio Fachada
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glPushMatrix();
glDisable(GL_LIGHTING);
glTranslatef(-28, 10.0, -5.9);
glRotatef(90, 0.0, 1.0, 0.0);
bardas.prisma(15.2, 6.5, 0.01, VentanaSimple.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
glBindTexture(GL_TEXTURE_2D, 0);
glDisable(GL_BLEND);
/////////////////////////////////////////////////////////GARAGE
//Creacion de las PAREDS
glPushMatrix();
glDisable(GL_LIGHTING);
glTranslatef(-22, 0, -28);
glRotatef(180, 0.0, 1.0, 0.0);
bardas.prisma(25, 12, 0.6, ParedBlanca2.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
glPushMatrix();//puerta arriba
glDisable(GL_LIGHTING);
glTranslatef(-22, 12, -12);
glRotatef(180, 0.0, 1.0, 0.0);
bardas.prisma(3.5, 12, 0.6, ParedBlanca2.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
glPushMatrix();
glDisable(GL_LIGHTING);
glTranslatef(-16, 0, -20);
glRotatef(90, 0.0, 1.0, 0.0);
bardas.prisma(25, 17, 0.6, ParedBlanca2.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
// Techo
glPushMatrix();
glDisable(GL_LIGHTING);
glTranslatef(-21.5, 13, -19.5);
glRotatef(90, 1.0, 0.0, 0.0);
bardas.prisma(19, 10, 0.2, ParedBlanca2.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
//puerta garageeeeeeeeeee
glPushMatrix();// Puerta Entrada
glDisable(GL_LIGHTING);
glTranslatef(-22, 0, -12);
//glRotatef(90, 0.0, 1.0, 0.0);
bardas.prisma(20, 12, 0.6, garage.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
// Techo
glPushMatrix();// Techo mas grande
glDisable(GL_LIGHTING);
glTranslatef(-38, 34, -22.5);
glRotatef(90, 1.0, 0.0, 0.0);
bardas.prisma(39, 20, 0.2, ParedBlanca2.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
glPushMatrix();// Pisoo
glDisable(GL_LIGHTING);
glTranslatef(-38, -4, -22.5);
glRotatef(90, 1.0, 0.0, 0.0);
bardas.prisma(39, 20, 0.2, alfombra.GLindex);
glEnable(GL_LIGHTING);
glPopMatrix();
glPopMatrix();
glPopMatrix();
glPopMatrix();
glutSwapBuffers ( );
}
void animacion()
{
/*fig2.text_izq -= 0.001;
fig2.text_der -= 0.001;
if (fig2.text_izq<-1)
fig2.text_izq = 0;
if (fig2.text_der<0)
fig2.text_der = 1;
*/
rot += 00000000000000000000.1;
glutPostRedisplay();
}
void reshape ( int width , int height ) // Creamos funcion Reshape
{
if (height==0) // Prevenir division entre cero
{
height=1;
}
glViewport(0,0,width,height);
glMatrixMode(GL_PROJECTION); // Seleccionamos Projection Matrix
glLoadIdentity();
// Tipo de Vista
glFrustum (-0.1, 0.1,-0.1, 0.1, 0.1, 400.0);
glMatrixMode(GL_MODELVIEW); // Seleccionamos Modelview Matrix
glLoadIdentity();
}
void keyboard(unsigned char key, int x, int y) // Create Keyboard Function
{
switch (key) {
case 'w': //Movimientos de camara
case 'W':
objCamera.Move_Camera(CAMERASPEED + 0.2);
break;
case 'x':
case 'X':
objCamera.Move_Camera(-(CAMERASPEED + 0.2));
break;
case 'a':
case 'A':
objCamera.Strafe_Camera(-(CAMERASPEED + 0.4));
break;
case 'd':
case 'D':
objCamera.Strafe_Camera(CAMERASPEED + 0.4);
break;
case ' ': //Poner algo en movimiento
//g_fanimacion^= true; //Activamos/desactivamos la animacíon
break;
case 27: // Cuando Esc es presionado...
exit(0); // Salimos del programa
break;
default: // Cualquier otra
break;
}
glutPostRedisplay();
}
void arrow_keys ( int a_keys, int x, int y ) // Funcion para manejo de teclas especiales (arrow keys)
{
switch ( a_keys ) {
case GLUT_KEY_PAGE_UP:
objCamera.UpDown_Camera(CAMERASPEED);
break;
case GLUT_KEY_PAGE_DOWN:
objCamera.UpDown_Camera(-CAMERASPEED);
break;
case GLUT_KEY_UP: // Presionamos tecla ARRIBA...
g_lookupdown -= 1.0f;
break;
case GLUT_KEY_DOWN: // Presionamos tecla ABAJO...
g_lookupdown += 1.0f;
break;
case GLUT_KEY_LEFT:
objCamera.Rotate_View(-CAMERASPEED);
break;
case GLUT_KEY_RIGHT:
objCamera.Rotate_View( CAMERASPEED);
break;
default:
break;
}
glutPostRedisplay();
}
int main ( int argc, char** argv ) // Main Function
{
glutInit (&argc, argv); // Inicializamos OpenGL
glutInitDisplayMode (GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); // Display Mode (Clores RGB y alpha | Buffer Doble )
glutInitWindowSize (2000, 2000); // Tamaño de la Ventana
glutInitWindowPosition (0, 0); //Posicion de la Ventana
glutCreateWindow ("Proyecto"); // Nombre de la Ventana
//glutFullScreen ( ); // Full Screen
InitGL (); // Parametros iniciales de la aplicacion
glutDisplayFunc ( display ); //Indicamos a Glut función de dibujo
glutReshapeFunc ( reshape ); //Indicamos a Glut función en caso de cambio de tamano
glutKeyboardFunc ( keyboard ); //Indicamos a Glut función de manejo de teclado
glutSpecialFunc ( arrow_keys ); //Otras
glutIdleFunc ( animacion );
glutMainLoop ( ); //
return 0;
}
|
#ifndef PN532_NFC_READER_CPP
#define PN532_NFC_READER_CPP
#include "Pn532nfcReader.h"
static const byte comparisonByteVector[] = {'P','N','R','D'};
String comparisonString = "PNRD";
Pn532NfcReader::Pn532NfcReader(NfcAdapter* adapter):Reader(){
nfcAdapter = adapter;
}
void Pn532NfcReader::initialize(){
nfcAdapter->begin();
};
ReadError Pn532NfcReader::read(Pnrd* pnrd){
if (nfcAdapter->tagPresent()){
NfcTag tag = nfcAdapter->read();
if (tag.hasNdefMessage()){
NdefMessage message = tag.getNdefMessage();
int recordCount = message.getRecordCount();
NdefRecord record;
for(int recordNumber = 0; recordNumber < recordCount; recordNumber++){
record = message.getRecord(recordNumber);
if(record.getType().equals(comparisonString)){
int payloadLength = record.getPayloadLength();
byte payload[payloadLength];
record.getPayload(payload);
int uidLength = tag.getUidLength();
byte uid[uidLength];
tag.getUid(uid, uidLength);
//Stores only the two last hex values of the uid as the tag id;
pnrd->setTagId(uid[uidLength - 2]);
return getInformation( payload, pnrd);
}
}
return ReadError::INFORMATION_NOT_PRESENT;
}else{
return ReadError::INFORMATION_NOT_PRESENT;
}
}else{
return ReadError::TAG_NOT_PRESENT;
}
return ReadError::ERROR_UNKNOWN;
};
WriteError Pn532NfcReader::write(Pnrd* pnrd){
if (nfcAdapter->tagPresent()){
NdefRecord record = NdefRecord();
int typeSize = 4;
NdefMessage writeMessage = NdefMessage();
record.setType(comparisonByteVector , typeSize);
uint16_t size = 4;
if (pnrd->isTagInformation(PetriNetInformation::TOKEN_VECTOR)) {
size += sizeof(uint16_t) * pnrd->getNumberOfPlaces();
}
if (pnrd->isTagInformation(PetriNetInformation::ADJACENCY_LIST)) {
size += 2;
size += (pnrd->getNumberMaxOfInputs() + pnrd->getNumberMaxOfOutputs()) * pnrd->getNumberOfTransitions();
}
if (pnrd->isTagInformation(PetriNetInformation::FIRE_VECTOR)) {
size += sizeof(uint16_t) * (pnrd->getNumberOfTransitions());
}
if (pnrd->isTagInformation(PetriNetInformation::CONDITIONS)) {
size += (pnrd->getNumberOfTransitions() + 7) / 8;
}
if (pnrd->isTagInformation(PetriNetInformation::TAG_HISTORY)) {
size += 2;
size += sizeof(TagHistoryEntry) * MAX_NUM_OF_TAG_HISTORY_ENTRIES;
}
if(size > 1024){
return WriteError::NOT_ENOUGH_SPACE;
}
byte pointer[size];
setInformation(pointer, pnrd);
record.setPayload(pointer, size);
writeMessage.addRecord(record);
if (nfcAdapter->write(writeMessage)) {
return WriteError::NO_ERROR;
}else {
free(pointer);
return WriteError::INFORMATION_NOT_SAVED;
}
}else{
return WriteError::TAG_NOT_PRESENT;
}
return WriteError::ERROR_UNKNOWN;
};
ReadError Pn532NfcReader::getInformation(byte* payload,Pnrd * pnrd) {
uint16_t index = 0;
byte version = payload[index];
index++;
if (version != (byte) 1 ) {
return ReadError::VERSION_NOT_SUPPORTED;
}
if (pnrd->setup == PnrdPolicy::TAG_SETUP) {
pnrd->getDataInTag()[0] = payload[index];
index++;
} else {
if(payload[index] != pnrd->getDataInTag()[0]){
return ReadError::INFORMATION_NOT_PRESENT;
}
index++;
}
uint8_t size = (uint8_t) payload[index];
index++;
if (size != pnrd->getNumberOfPlaces()) {
return ReadError::DATA_SIZE_NOT_COMPATIBLE;
}
size = (uint8_t) payload[index];
index++;
if (size != pnrd->getNumberOfTransitions()) {
return ReadError::DATA_SIZE_NOT_COMPATIBLE;
}
if (pnrd->isTagInformation(PetriNetInformation::TOKEN_VECTOR)) {
size = sizeof(uint16_t) * pnrd->getNumberOfPlaces();
for(uint16_t counter = 0; counter < size ; counter++) {
((byte*)pnrd->getTokenVectorPointer())[counter] = payload[index];
index++;
}
}
if (pnrd->isTagInformation(PetriNetInformation::ADJACENCY_LIST)) {
size = (uint8_t) payload[index];
index++;
if (size != pnrd->getNumberMaxOfInputs()) {
return ReadError::DATA_SIZE_NOT_COMPATIBLE;
}
size = (uint8_t) payload[index];
index++;
if (size != pnrd->getNumberMaxOfOutputs()) {
return ReadError::DATA_SIZE_NOT_COMPATIBLE;
}
size = sizeof(uint8_t) * (pnrd->getNumberMaxOfInputs() + pnrd->getNumberMaxOfOutputs()) * pnrd->getNumberOfTransitions();
for(uint16_t counter = 0; counter < size ; counter++) {
((byte*)pnrd->getAdjacencyListPointer())[counter] = payload[index];
index++;
}
}
if (pnrd->isTagInformation(PetriNetInformation::FIRE_VECTOR)) {
size = sizeof(uint16_t) * pnrd->getNumberOfTransitions();
for(uint16_t counter = 0; counter < size ; counter++) {
((byte*)pnrd->getFireVectorPointer())[counter] = payload[index];
index++;
}
}
if (pnrd->isTagInformation(PetriNetInformation::CONDITIONS)) {
size = sizeof(uint8_t) * (pnrd->getNumberOfTransitions() + 7) / 8;
for(uint16_t counter = 0; counter < size ; counter++) {
((byte*) pnrd->getConditionsPointer())[counter] = payload[index];
index++;
}
}
if (pnrd->isTagInformation(PetriNetInformation::TAG_HISTORY)) {
uint8_t* tagIndex = pnrd->getTagHistoryIndexPointer();
size = sizeof(uint8_t);
for(uint16_t counter = 0; counter < size ; counter++) {
((byte*) tagIndex)[counter] = payload[index];
index++;
}
size = sizeof(TagHistoryEntry) * MAX_NUM_OF_TAG_HISTORY_ENTRIES;
for(uint16_t counter = 0; counter < size ; counter++) {
((byte*)pnrd->getTagHistoryPointer())[counter] = payload[index];
index++;
}
}
return ReadError::NO_ERROR;
}
WriteError Pn532NfcReader::setInformation(byte* payload, Pnrd *pnrd) {
uint8_t version = 1;
uint16_t index = 0;
uint16_t size = 0;
payload[index] = version;
index++;
payload[index] = pnrd->getDataInTag()[0];
index++;
payload[index] = pnrd->getNumberOfPlaces();
index++;
payload[index] = pnrd->getNumberOfTransitions();
index++;
if (pnrd->isTagInformation(PetriNetInformation::TOKEN_VECTOR)) {
size = sizeof(uint16_t)* pnrd->getNumberOfPlaces();
for(uint16_t counter = 0; counter < size ; counter++) {
payload[index] = ((byte*) pnrd->getTokenVectorPointer())[counter];
index++;
}
}
if (pnrd->isTagInformation(PetriNetInformation::ADJACENCY_LIST)) {
payload[index] = pnrd->getNumberMaxOfInputs();
index++;
payload[index] = pnrd->getNumberMaxOfOutputs();
index++;
size = sizeof(uint8_t) * (pnrd->getNumberMaxOfInputs() + pnrd->getNumberMaxOfOutputs()) * pnrd->getNumberOfTransitions();
for(uint16_t counter = 0; counter < size ; counter++) {
payload[index] = ((byte*)pnrd->getAdjacencyListPointer())[counter];
index++;
}
}
if (pnrd->isTagInformation(PetriNetInformation::FIRE_VECTOR)) {
size = sizeof(uint16_t*) *pnrd->getNumberOfTransitions();
for(uint16_t counter = 0; counter < size ; counter++) {
payload[index] = ((byte*)pnrd->getFireVectorPointer())[counter];
index++;
}
}
if (pnrd->isTagInformation(PetriNetInformation::CONDITIONS)) {
size = (pnrd->getNumberOfTransitions() + 7) / 8;
for(uint16_t counter = 0; counter < size ; counter++) {
payload[index] = ((byte*)pnrd->getConditionsPointer())[counter];
index++;
}
}
if (pnrd->isTagInformation(PetriNetInformation::TAG_HISTORY)) {
uint8_t* tagIndex = pnrd->getTagHistoryIndexPointer();
byte* pointer = (byte*) pnrd->getTagHistoryPointer();
payload[index] = tagIndex[0];
index++;
size = sizeof(TagHistoryEntry) * MAX_NUM_OF_TAG_HISTORY_ENTRIES;
for(uint16_t counter = 0; counter < size ; counter++) {
payload[index] = pointer[counter];
index++;
}
}
return WriteError::NO_ERROR;
}
#endif
|
// Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Author: Junyi Sun (sunjunyi01@baidu.com)
// Description: memtable built on leveldb
#ifndef STORAGE_LEVELDB_DB_MEMTABLE_ON_LEVELDB_H_
#define STORAGE_LEVELDB_DB_MEMTABLE_ON_LEVELDB_H_
#include "db/memtable.h"
#include "helpers/memenv/memenv.h"
#include "db/db_impl.h"
#include "leveldb/env.h"
namespace leveldb {
class MemTableOnLevelDB : public MemTable{
public:
MemTableOnLevelDB (const InternalKeyComparator& comparator,
CompactStrategyFactory* compact_strategy_factory,
size_t write_buffer_size,
size_t block_size,
Logger* info_log);
~MemTableOnLevelDB();
size_t ApproximateMemoryUsage();
Iterator* NewIterator();
void Add(SequenceNumber seq, ValueType type,
const Slice& key,
const Slice& value);
bool Get(const LookupKey& key, std::string* value, Status* s);
const uint64_t GetSnapshot(uint64_t last_sequence);
void ReleaseSnapshot(uint64_t sequence_number);
private:
Env* GetBaseEnv();
leveldb::DBImpl* memdb_;
leveldb::Env* memenv_;
};
} //namespace leveldb
#endif //STORAGE_LEVELDB_DB__MEMTABLE_ON_LEVELDB_H_
|
#include <stdio.h>
#include <stdlib.h>
int main(){
int **p;
p = (int **) calloc(2,sizeof(int));
printf("Linha: %d \n", p);
for (int i = 0; i < 2; i++){
p[i] = (int *) calloc(2, sizeof(int));
printf("COluna: %d\n" ,p[i]);
}
printf("\n");
for(int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
printf("(%d) (%d) = %d | " ,i,i,p[i][j]);
}
printf("\n");
}
}
|
//
// prototype.h
// design_pattern
//
// Created by jack on 14-7-13.
// Copyright (c) 2014年 jack. All rights reserved.
//
#ifndef design_pattern_prototype_h
#define design_pattern_prototype_h
using namespace std;
/**
* 简历我们可能只需要修改一下名字就好了
*/
class ResumeProto
{
public:
ResumeProto(){}
virtual ~ResumeProto(){}
virtual ResumeProto * Clone()=0;
virtual void SetName(char *name)=0;
virtual void Show()=0;
protected:
char *name_;
int name_len_;
};
class Resume: public ResumeProto
{
public:
Resume(const char *name);
~Resume();
/**
* 采用的深拷贝
*/
Resume(const Resume &r);
Resume * Clone();
/**
* 改变名字
*
* @param name 名字
*/
void SetName(char *name);
void Show();
};
Resume::Resume(const char *name):ResumeProto()
{
if(name == NULL) {
name_ = new char[1];
name_[0] = '\0';
name_len_=1;
}
else {
name_ = new char[strlen(name)+1];
name_len_=strlen(name)+1;
strcpy(name_, name);
}
}
Resume::~Resume() { delete [] name_;}
Resume::Resume(const Resume &r) {
name_ = new char[strlen(r.name_)+1];
strcpy(name_, r.name_);
}
Resume* Resume::Clone() {
return new Resume(*this);
}
void Resume::SetName(char *name)
{
if (strlen(name)>=name_len_) {
name_len_=strlen(name)+1;
name_=(char *)realloc(name_,name_len_);
strcpy(name_,name);
}else{
strcpy(name_,name);
}
}
void Resume::Show() {
cout<<"Resume name : "<<name_<<endl;
}
#endif
|
/*************************************************************************
> File Name : SecCertificateRequest.cpp
> Author : YangShuai
> Created Time: 2016年08月12日 星期五 14时49分10秒
> Description :
************************************************************************/
#include<time.h>
#include"Primitive.h"
#include"PrimitiveTools.h"
#include"../database/dbfunc.h"
Result Sec_CertificateRequest(SignerInfoType signer_type,
CMH cmh,
HolderType cert_type,
PublicKey_Transfer_Type transfer_type,
Cme_Permissions& permissions,
Data& identifier,
GeographicRegion& region,
bool start_validity,
bool life_time_duration,
Time32 start_time,
Time32 expiry_time,
PublicKey& veri_pub_key,
PublicKey& enc_pub_key,
PublicKey& respon_enc_key,
Certificate& ca_cert,
Data& certificate_request,
CertId10& request_hash
){
Result res = SUCCESS;
Cme_Permissions ca_permis, csr_cert_permis;
vector<HolderType> ca_permis_holdertype, csr_cert_permis_holdertype;
GeographicRegion ca_geo_scope, csr_cert_geo_scope;
Certificate csr_cert;
PublicKey cmh_pub_key;
Data cmh_pri_key;
if(signer_type == CERTIFICATE){
if(db_get_cert_and_prikey(cmh, csr_cert, cmh_pri_key) < 0){
ERROR_PRINT("获取证书和私钥失败");
return FAILURE;
}
if(Extract_VerifyKey_From_Cert(csr_cert, cmh_pub_key)){ //这里应该是取出签名验证公钥吧??
ERROR_PRINT("从证书中取出公钥失败");
return FAILURE;
}
}
else if(signer_type == SELF){
if(db_get_pubkey_and_prikey(cmh, cmh_pub_key, cmh_pri_key) < 0){
ERROR_PRINT("获取密钥对失败");
return FAILURE;
}
}
Identifier_Type type_temp;
Data identifier_temp;
Data cert_data_temp;
Time32 last_temp, next_temp;
bool trust_temp, veri_temp;
type_temp = ID_CERTIFICATE;
identifier_temp.init(ca_cert._datasize());
if(ca_cert._encode(identifier_temp) < 0){
ERROR_PRINT("证书编码失败");
return FAILURE;
}
if(Cme_CertificateInfo_Request(type_temp, identifier_temp,
cert_data_temp, ca_permis, ca_geo_scope,
last_temp, next_temp, trust_temp, veri_temp)){
ERROR_PRINT("获取根证书信息失败");
return FAILURE;
}
/*欧标证书里面没有permitted_holder_types这个字段,忽略这个字段的处理*/
if((Check_Permission_Consistency(permissions, ca_permis) == false) ||
(geographic_region_in_geographic_region(region, ca_geo_scope) == false)){
return INCONSISTENT_CA_PERMISSIONS;
}
if(signer_type == CERTIFICATE){
type_temp = ID_CERTIFICATE;
identifier_temp.init(csr_cert._datasize());
if(csr_cert._encode(identifier_temp) < 0){
ERROR_PRINT("证书编码失败");
return FAILURE;
}
cert_data_temp.clear();
if(Cme_CertificateInfo_Request(type_temp, identifier_temp,
cert_data_temp, csr_cert_permis, csr_cert_geo_scope,
last_temp, next_temp, trust_temp, veri_temp)){
ERROR_PRINT("获取证书信息失败");
return FAILURE;
}
/*欧标证书里面没有permitted_holder_types这个字段,忽略这个字段的处理*/
if((Check_Permission_Consistency(csr_cert_permis, permissions) == false) ||
(geographic_region_in_geographic_region(csr_cert_geo_scope, region) == false)){
return INCONSISITENT_CSR_PERMISSIONS;
}
}
if(signer_type == SELF){
if(veri_pub_key != cmh_pub_key){
return INCONSISITENT_KEYS_IN_REQUEST;
}
}
if(permissions.len() > MAX_PERMISSIONS_LEN){
return TOO_MANY_ENTRIES_IN_PERMISSON_ARRAY;
}
if(region.region_type != NONE && region.region_type != CIRCLE && region.region_type != RECTANGLE &&
region.region_type != POLYGON && region.region_type != ID){
return UNSUPPORTED_REGION_TYPE_IN_CERTIFICATE;
}
if(region.region_type == RECTANGLE && region.u.rectangular_region.size() > MAX_NUM_OF_RECTANGLES){
return TOO_MANY_ENTRIES_IN_RECTANGULAR_GEOGRAPHIC_SCOPE;
}
if(region.region_type == POLYGON && region.u.polygonal_region.polygonalregion.size() > MAX_NUM_OF_POLYGON_VERTICES){
return TOO_MANY_ENTRIES_IN_POLYGONAL_GEOGRAPHIC_SCOPE;
}
ToBeSignedCertificateRequest tbs;
if(transfer_type == EXPLICIT) tbs.version_and_type = 2;
else if(transfer_type == IMPLICIT) tbs.version_and_type = 3;
if(start_validity){
tbs.cf = (CertificateContentFlags)(tbs.cf | USE_START_VALIDITY); //这里的值后面测一下
tbs.flags_content.start_validity = start_time;
}
if(life_time_duration){
tbs.cf = (CertificateContentFlags)(tbs.cf | LIFETIME_IS_DURATION);
tbs.flags_content.lifetime = caculate_duration(expiry_time - start_time);
}
tbs.request_time = time(NULL);
tbs.holder_type = cert_type;
//crl_signer没有填充,感觉应该用不到,root_ca中的permitted_holder_types也用不到,后面删掉吧
vector<u8> id_vec;
for(int32 i = 0;i < identifier.len;i++){
id_vec.push_back(*(identifier.buf + i));
}
switch(cert_type){
case HT_ROOT_CA:
tbs.type_specific_data.u.root_ca_scope.name = id_vec;
tbs.type_specific_data.u.root_ca_scope.flags_content.secure_data_permissions.type = SPECIFIED;
tbs.type_specific_data.u.root_ca_scope.flags_content.secure_data_permissions.u.permissions_list = permissions.u.its_aid_vec;
tbs.type_specific_data.u.root_ca_scope.region = region;
break;
case HT_SDE_CA:
case HT_SDE_ENROLMENT:
tbs.type_specific_data.u.sde_ca_scope.name = id_vec;
tbs.type_specific_data.u.sde_ca_scope.permissions.type = SPECIFIED;
tbs.type_specific_data.u.sde_ca_scope.permissions.u.permissions_list = permissions.u.its_aid_vec;
tbs.type_specific_data.u.sde_ca_scope.region = region;
break;
case HT_CRL_SIGNER:
/*------*/
break;
case HT_SDE_IDENTIFIED_NOT_LOCALIZED:
tbs.type_specific_data.u.id_non_loc_scope.name = id_vec;
tbs.type_specific_data.u.id_non_loc_scope.permissions.type = SPECIFIED;
tbs.type_specific_data.u.id_non_loc_scope.permissions.u.permissions_list = permissions.u.its_aid_ssp_vec;
break;
case HT_SDE_IDENTIFIED_LOCALIZED:
tbs.type_specific_data.u.id_scope.name = id_vec;
tbs.type_specific_data.u.id_scope.permissions.type = SPECIFIED;
tbs.type_specific_data.u.id_scope.permissions.u.permissions_list = permissions.u.its_aid_ssp_vec;
tbs.type_specific_data.u.id_scope.region = region;
break;
case HT_SDE_ANONYMOUS:
tbs.type_specific_data.u.anonymous_scope.permissions.type = SPECIFIED;
tbs.type_specific_data.u.anonymous_scope.permissions.u.permissions_list = permissions.u.its_aid_ssp_vec;
tbs.type_specific_data.u.anonymous_scope.region = region;
break;
default:
ERROR_PRINT("参数错误,不支持的类型");
return FAILURE;
}
tbs.vecrification_key = veri_pub_key;
tbs.response_encryption_key = respon_enc_key;
CertificateRequest cr;
Sign_With_Fast_Verification swfv = NO;
Data tbs_data(tbs._datasize());
Digest digest;
Data tbs_digest(32);
cr.signer.type = signer_type;
cr.signer.u.certificate = csr_cert;
cr.unsigned_csr = tbs;
if(tbs._encode(tbs_data) < 0){
ERROR_PRINT("ToBeSignedCertificateRequest编码失败");
return FAILURE;
}
if(digest.caculate(tbs_data)){
ERROR_PRINT("计算数据摘要失败");
return FAILURE;
}
digest.get_digest(tbs_digest.buf);
if(Get_Message_Signature(cmh_pri_key, tbs_digest, swfv, cr.signature)){
ERROR_PRINT("计算签名失败");
return FAILURE;
}
Data cr_data(cr._datasize());
Digest hash;
if(cr._encode(cr_data) < 0){
ERROR_PRINT("CertificateRequest编码失败");
return FAILURE;
}
if(hash.caculate(cr_data)){
ERROR_PRINT("计算hash值失败");
return FAILURE;
}
hash.get_hash10(request_hash.certid10);
PayloadType payload_type = UNSECURED;
vector<Certificate> certs{ca_cert};
vector<Certificate> fail_cert_temp;
if(Sec_EncryptedData(payload_type, cr_data, certs, true, 0, certificate_request, fail_cert_temp)){
ERROR_PRINT("证书请求报文失败");
return FAILURE;
}
return res;
}
|
#include "Serial.h"
void PrintfSerial::begin(unsigned long value)
{
printf("[?] Serial.begin(%lu)\n", value);
}
size_t PrintfSerial::print(const char value[])
{
printf("[W] Serial.print(\"%s\")\n", value);
return 0;
}
size_t PrintfSerial::print(int value)
{
printf("[W] Serial.print(%d)\n", value);
return 0;
}
size_t PrintfSerial::print(unsigned int value)
{
printf("[W] Serial.print(%u)\n", value);
return 0;
}
size_t PrintfSerial::print(long value)
{
printf("[W] Serial.print(%ld)\n", value);
return 0;
}
size_t PrintfSerial::print(unsigned long value)
{
printf("[W] Serial.print(%lu)\n", value);
return 0;
}
size_t PrintfSerial::print(double value)
{
printf("[W] Serial.print(%f)\n", value);
return 0;
}
PrintfSerial Serial;
|
#include "ClasslessLogger.hpp"
#include <chrono>
#include <ctime>
#include <iostream>
void fileLog(const char * logData, const char * logSpace)
{
FILE* logFile;
logFile = fopen("Logger_default.txt", "a");
if (!logFile)
{
std::cout << "logFile open failed!" << std::endl;
exit(1);
}
auto time = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::string timeAsString = ctime(&time);
timeAsString.erase(timeAsString.end()-1);
fprintf(logFile, "%s %s %s\n", timeAsString.c_str(), logSpace, logData);
fclose(logFile);
}
|
#ifndef DECK_H
#define DECK_H
#include "data_structures.h"
class Deck {
public:
// Initializes deck in order and full
Deck();
// Refills deck and shuffles it
void shuffle();
// draws num_cards cards
std::deque<card_t> draw(int num_cards);
// draws one card
card_t draw();
private:
std::deque<card_t> cards;
void reset();
};
#endif
|
/*
File Name: SimpleQueue.h
Author: Geun-Hyung Kim
Description:
정수형 배열로 구성된 Queue 클래스 기능 구형 프로그램
Date: 2021. 3. 24
Version: 0.1.0
*/
#include <iostream>
#include "SimpleQueue.h"
bool Queue::full() {
return rear == length-1;
}
bool Queue::empty() {
return rear == front;
}
void Queue::enQueue(int data) {
if (!full()) {
dataArray[++rear] = data;
size++;
}
else {
throw "Queue is full!!";
}
}
int Queue::deQueue() {
if (!empty()) {
size--;
return dataArray[++front];
}
else {
throw "Queue is empty!!";
}
}
int Queue::Front() {
return front;
}
int Queue::Back() {
return rear;
}
ostream& operator<<(ostream& os, const Queue& q) {
os << "length : " << q.length << endl
<< "size : " << q.size << endl
<< "front : " << q.front << endl
<< "rear : " << q.rear << "\n\n";
return os;
}
|
#ifndef SET_GRAPH_HPP
#define SET_GRAPH_HPP
#include <unordered_set>
#include <list>
#include "IGraph.hpp"
class SetGraph : IGraph {
public:
SetGraph(unsigned int verticesNumber);
explicit SetGraph(const IGraph ©);
void AddEdge(int from, int to);
int VerticesCount() const;
std::vector<int> GetNextVertices(int vertex) const;
std::vector<int> GetPrevVertices(int vertex) const;
private:
unsigned int verticesNumber;
std::vector<std::unordered_set<int>> out;
std::vector<std::unordered_set<int>> in;
};
#endif //C_SET_GRAPH_HPP
|
/*
Turn on
Turns an LED on
*/
#define LED 8 //LED connected to pin 8
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin LED as an output.
pinMode(LED, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
digitalWrite(LED, HIGH); // turn the LED on (HIGH is the voltage level)
}
|
// by thaiph99
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define FOR(i, a, b) for(int i = a; i <= (int)(b); i++)
#define FORR(i, a, b) for (int i = a; i >= (int)(b); i--)
#define iosb ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
const int nax=15*1e4+9;
ll n, par[nax], rak[nax], u, v;
vector<ll> g[nax];
int find(ll u)
{
return par[u]==-1 ? u : par[u]=find(par[u]);
}
void join(ll u, ll v)
{
u = find(u);
v = find(v);
if(u==v)
return;
if(rak[u]<rak[v])
swap(u,v);
par[v]=u;
g[u].push_back(v);
if(rak[u]==rak[v])
rak[u]++;
}
void dfs(ll uu)
{
cout<<uu<<" ";
for(auto &vv : g[uu])
dfs(vv);
}
int main()
{
iosb;
freopen("INPUT.INP", "r", stdin);
cin>>n;
memset(par, -1, sizeof(par));
FOR(i,1,n-1)
{
cin>>u>>v;
join(u,v);
}
dfs(find(1));
}
|
#include<bits/stdc++.h>
using namespace std;
int main(){
float base,area,height;
cin>>base>>area;
height=2*area/base;
int res=ceil(height);
cout<<res;
}
|
#include <iostream>
#include <vector>
#include <queue>
#include <future>
#include <assert.h>
#include <cstdlib>
#include "separate.h"
#include "private_queue.h"
#include "processor.h"
std::vector <processor*> g_processors;
int max_iters = 20000;
class producer {
public:
separate <std::queue <int> > *m_queue;
private_queue <std::queue <int>> m_private_queue;
producer (separate <std::queue <int> >* queue) :
m_private_queue (queue->make_queue())
{
m_queue = queue;
}
void live() {
for (int i = 0; i < max_iters; i++) {
// std::cout << "producer run: " << i << std::endl;
run (i);
}
std::cout << "done producing" << std::endl;
}
void run(int i) {
// Lock the processor, setup the queue.
// auto l_queue = m_queue->lock ();
m_queue->lock_with(m_private_queue);
// // If we want the traditional SCOOP behaviour:
// std::function <bool(std::queue<int>*)> wait = [](std::queue<int> *q) {
// return true;
// };
// auto fut = m_private_queue.log_call_with_result (wait);
// fut.get();
// log the call.
m_private_queue.log_call ([=](std::queue<int> *q) {
q->push(i);
});
// end the queue
m_private_queue.unlock();
}
};
class consumer {
public:
separate <std::queue <int> > *m_queue;
private_queue <std::queue <int>> m_private_queue;
consumer (separate <std::queue <int> >* queue):
m_private_queue (queue->make_queue())
{
m_queue = queue;
}
void live() {
for (int i = 0; i < max_iters; i++) {
// std::cout << "consumer run " << i << std::endl;
run ();
}
std::cout << "done consuming" << std::endl;
}
void run() {
processor *p = &m_queue->m_proc;
bool wait_cond;
// Lock the processor and check the wait-condition.
// auto l_queue = m_queue->lock();
m_queue->lock_with (m_private_queue);
std::function <bool(std::queue<int> *)> wait_func = [](std::queue<int> *q) {
return !q->empty();
};
// auto fut = l_queue.log_call_with_result (wait_func);
wait_cond = m_private_queue.log_call_with_result (wait_func);
// If the wait-condition isn't satisfied, wait and recheck
// when we're woken up (by another thread).
while (!wait_cond) {
// l_queue.unlock();
m_private_queue.unlock();
p->wait_until_available();
// l_queue = m_queue->lock();
m_queue->lock_with (m_private_queue);
// auto fut = l_queue.log_call_with_result (wait_func);
wait_cond = m_private_queue.log_call_with_result (wait_func);
}
// log the call with result.
std::function<int (std::queue<int> *)> f = [](std::queue<int> *q) {
int tmp = q->front();
q->pop();
return tmp;
};
// std::future <int> res = l_queue.log_call_with_result (f);
int res = m_private_queue.log_call_with_result (f);
// end the queue
// l_queue.unlock();
m_private_queue.unlock ();
}
};
int main (int argc, char** argv) {
max_iters = atoi(argv[1]);
auto max_each = atoi(argv[2]);
std::vector <std::future <bool> > workers;
auto q = new std::queue <int>() ;
separate <std::queue <int> > queue (q);
g_processors.push_back (&queue.m_proc);
for (int i = 0; i < max_each; i++) {
workers.push_back
(std::async
(std::launch::async,
[&queue]() {
producer p (&queue);
p.live();
return true;
}));
workers.push_back
(std::async
(std::launch::async,
[&queue]() {
consumer p (&queue);
p.live();
return true;
}));
}
for (auto& worker : workers) {
worker.get();
}
// example of final shutdown, this should be done by the GC in a real
// implementation.
for (auto& proc : g_processors) {
proc->shutdown ();
proc->join();
}
return 0;
}
|
#include <iostream>
using namespace std;
const int size=5;
void fill_array(int [],int);
void extreme_index(int [],int,int &,int&);
int main(){
int myarray[size],sindex,lindex;
fill_array(myarray,size);
extreme_index(myarray,size,sindex,lindex);
cout << "Largest Element Index: " << lindex << endl;
cout << "Smallest Element Index: " << sindex <<endl;
system("pause");
}
//----------------------- fill_array
void fill_array(int array[],int size){
int value;
for(int i=0; i< size; i++){
cout << "enter " << i+1 << "th: ";
cin >> value;
array[i]=value;
}
}
//-----------------
void extreme_index(int array[],int size,int &si,int &li){
int g=array[0],s=array[0];
for(int i=0; i<size; i++){
if(array[i] > g){g=array[i];li=i;}
else if(array[i] < s){s=array[i];si=i;}
}
}
|
#ifndef _INC__RPG2K__STRUCTURE_HPP
#define _INC__RPG2K__STRUCTURE_HPP
#include "Define.hpp"
#include "Map.hpp"
#include <iomanip>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
#include <climits>
#include <cstring>
namespace rpg2kLib
{
static uint const STREAM_BUFFER_SIZE = 512;
#define rpg2kLib_setStreamBuffer(name) \
char name##Buf[rpg2kLib::STREAM_BUFFER_SIZE]; \
name.rdbuf()->pubsetbuf(name##Buf, rpg2kLib::STREAM_BUFFER_SIZE)
namespace structure
{
class StreamReader;
class StreamWriter;
static uint const
BER_BIT = (CHAR_BIT-1),
BER_SIGN = 0x01 << BER_BIT,
BER_MASK = BER_SIGN - 1;
extern uint getBERSize(uint num);
class Element;
class Descriptor;
class Binary : public std::vector< uint8_t >
{
private:
static void exchangeEndianIfNeed(uint8_t* dst, uint8_t const* src, uint sizeOf, uint eleNum);
public:
Binary(Element& e, Descriptor const& info);
Binary(Element& e, Descriptor const& info, StreamReader& f);
Binary(Element& e, Descriptor const& info, Binary const& b);
Binary() : std::vector< uint8_t >() {}
explicit Binary(uint size) : std::vector< uint8_t >(size) {}
explicit Binary(uint8_t* data, uint size) : std::vector< uint8_t >(data, data + size) {}
Binary(Binary const& b) : std::vector< uint8_t >(b) {}
Binary(RPG2kString str) { setString(str); }
uint8_t const* pointer(uint index = 0) const { return &((*this)[index]); }
uint8_t* pointer(uint index = 0) { return &((*this)[index]); }
bool isNumber() const;
bool isString() const;
// setter
void setString(RPG2kString const& str);
void setNumber(int32_t num);
void setBool(bool b);
void setDouble(double d);
// converter
RPG2kString toString() const;
int toNumber() const;
bool toBool () const;
double toDouble() const;
// operator wrap of converter
operator RPG2kString() const { return toString(); }
operator int () const { return toNumber(); }
operator bool () const { return toBool (); }
operator double() const { return toDouble(); }
// operator wrap of setter
Binary& operator =(RPG2kString const& src) { setString(src); return *this; }
Binary& operator =(int src) { setNumber(src); return *this; }
Binary& operator =(bool src) { setBool (src); return *this; }
Binary& operator =(double src) { setDouble(src); return *this; }
uint serializedSize() const;
void serialize(StreamWriter& s) const;
// Binary serialize() const { return *this; }
template< typename T >
void assign(std::vector< T > const& src)
{
resize( sizeof(T) * src.size() );
exchangeEndianIfNeed(
this->pointer(),
reinterpret_cast< uint8_t const* >( &src.front() ),
sizeof(T), src.size()
);
}
template< typename T >
std::vector< T > convert() const
{
if( ( size() % sizeof(T) ) != 0 ) throw std::runtime_error("Convert failed.");
uint length = this->size() / sizeof(T);
std::vector< T > output(length);
exchangeEndianIfNeed(
reinterpret_cast< uint8_t* >( &output.front() ),
this->pointer(),
sizeof(T), length
);
return output;
}
bool operator ==(Binary const& src) const
{
return
( this->size() == src.size() ) &&
( std::memcmp( this->pointer(), src.pointer(), this->size() ) == 0 );
}
bool operator !=(Binary const& src) const { return !( (*this) == src ); }
template< typename T >
Binary(std::vector< T > const& input) { assign(input); }
template< typename T >
Binary& operator =(std::vector< T > const& input) { assign(input); return *this; }
template< typename T >
operator std::vector< T >() const { return convert< T >(); }
}; // class Binary
} // namespace structure
} // namespace rpg2kLib
#endif // _INC__RPG2K__STRUCTURE_HPP
|
#include <bits/stdc++.h>
using namespace std;
const int MAX_INT = std::numeric_limits<int>::max();
const int MIN_INT = std::numeric_limits<int>::min();
const int INF = 1000000000;
const int NEG_INF = -1000000000;
#define max(a,b)(a>b?a:b)
#define min(a,b)(a<b?a:b)
#define MEM(arr,val)memset(arr,val, sizeof arr)
#define PI acos(0)*2.0
#define eps 1.0e-9
#define are_equal(a,b)fabs(a-b)<eps
#define LS(b)(b& (-b)) // Least significant bit
#define DEG_to_RAD(a)((a*PI)/180.0) // convert to radians
typedef long long ll;
typedef pair<int, int> ii;
typedef pair<int, char> ic;
typedef pair<long, char> lc;
typedef vector<int> vi;
typedef vector<ii> vii;
typedef pair<ii, ii> iiii;
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
int lcm(int a, int b) {
return a * (b / gcd(a, b));
}
int n, m, mod = 1000000;
int dy[4] = { 0, 1, 0, -1 };
int dx[4] = { -1, 0, 1, 0 };
int paths[101][101][4], len[101][101][4];
queue<iiii> q;
void makemove(int i, int j, int d, iiii cur) {
if (len[i][j][d] == 0) {
len[i][j][d] = cur.second.second + 1;
q.push(iiii(ii(i, j), ii(d, cur.second.second + 1)));
}
if (len[i][j][d] == cur.second.second + 1) {
paths[i][j][d] += paths[cur.first.first][cur.first.second][cur.second.first];
paths[i][j][d] %= mod;
}
}
int main() {
while (cin >> n >> m && n) {
char grid[n][m];
int si, sj, sd, ti, tj;
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j) {
cin >> grid[i][j];
if (grid[i][j] == 'X')
ti = i, tj = j;
if (grid[i][j] == 'N')
si = i, sj = j, sd = 0;
if (grid[i][j] == 'E')
si = i, sj = j, sd = 1;
if (grid[i][j] == 'S')
si = i, sj = j, sd = 2;
if (grid[i][j] == 'W')
si = i, sj = j, sd = 3;
}
MEM(paths, 0);
MEM(len, 0);
paths[si][sj][sd] = 1;
iiii entry(ii(si, sj), ii(sd, 0));
q = queue<iiii>();
q.push(entry);
int foundpath = INF;
while (!q.empty()) {
iiii cur = q.front(); q.pop();
if (cur.second.second > foundpath)
break;
if (cur.first.first == ti && cur.first.second == tj)
foundpath = cur.second.second;
// cout << foundpath << " " << " " << cur.second.second << endl;
// printf("foundpath : %d, i : %d, j : %d, dir : %d, dist : %d\n", foundpath, cur.first.first, cur.first.second, cur.second.first, cur.second.second);
int newd = (cur.second.first + 1) % 4;
makemove(cur.first.first, cur.first.second, newd, cur);
newd = (cur.second.first + 3) % 4;
makemove(cur.first.first, cur.first.second, newd, cur);
int newi = cur.first.first + dx[cur.second.first];
int newj = cur.first.second + dy[cur.second.first];
while (0 <= newi && newi < n && 0 <= newj && newj < m
&& grid[newi][newj] != '*') {
makemove(newi, newj, cur.second.first, cur);
newi += dx[cur.second.first];
newj += dy[cur.second.first];
}
}
int minlen = INF;
for (int i = 0; i < 4; i++) {
if (len[ti][tj][i] < minlen && len[ti][tj][i] > 0)
minlen = len[ti][tj][i];
}
// cout << minlen << endl;
int totalpaths = 0;
for (int i = 0; i < 4; i++) {
if (len[ti][tj][i] == minlen) {
totalpaths += paths[ti][tj][i];
totalpaths %= mod;
}
}
// cout << totalpaths << endl;
if (!totalpaths)
cout << 0 << " " << 0 << endl;
else cout << minlen << " " << totalpaths << endl;
}
return 0;
}
|
#include "Package.h"
int GetSize(char* Arr)
{
int s=0;
while (Arr[s] != '\0')
{
s++;
}
s++;
return s;
}
Package::Package(char* Rnam, char* RAdd, char* RCit, char* RNum, char* Snam, char* SAdd, char* SCit, char* SNum, float Cos, float Wei)
{
int s = GetSize(Rnam);
Rname = new char[s];
for (int i = 0; i < s; i++)
{
Rname[i] = Rnam[i];
}
Rname[s - 1] = '\0';
s = GetSize(RNum);
Rnum = new char[s];
for (int i = 0; i < s; i++)
{
Rnum[i] = RNum[i];
}
Rnum[s - 1] = '\0';
s = GetSize(RAdd);
Raddress = new char[s];
for (int i = 0; i < s; i++)
{
Raddress[i] = RAdd[i];
}
Raddress[s - 1] = '\0';
s = GetSize(RCit);
Rcity = new char[s];
for (int i = 0; i < s; i++)
{
Rcity[i] = RCit[i];
}
Rcity[s - 1] = '\0';
s = GetSize(Snam);
Sname = new char[s];
for (int i = 0; i < s; i++)
{
Sname[i] = Snam[i];
}
Sname[s - 1] = '\0';
s = GetSize(SNum);
Snum = new char[s];
for (int i = 0; i < s; i++)
{
Snum[i] = SNum[i];
}
Snum[s - 1] = '\0';
s = GetSize(SAdd);
Saddress = new char[s];
for (int i = 0; i < s; i++)
{
Saddress[i] = SAdd[i];
}
Saddress[s - 1] = '\0';
s = GetSize(SCit);
Scity = new char[s];
for (int i = 0; i < s; i++)
{
Scity[i] = SCit[i];
}
Scity[s - 1] = '\0';
Weight = Wei;
cost = Cos;
}
Package::~Package()
{
delete[] Sname;
Sname=nullptr;
delete[]Snum;
Snum = nullptr;
delete[] Saddress;
Saddress = nullptr;
delete[] Scity;
Scity = nullptr;
delete[] Rname;
Rname = nullptr;
delete[]Rnum;
Rnum = nullptr;
delete[] Raddress;
Raddress = nullptr;
delete[]Rcity;
Rcity = nullptr;
Weight=0;
cost=0;
}
|
// This file is part of kfilter.
// kfilter is a C++ variable-dimension extended kalman filter library.
//
// Copyright (C) 2004 Vincent Zalzal, Sylvain Marleau
// Copyright (C) 2001, 2004 Richard Gourdeau
// Copyright (C) 2004 GRPR and DGE's Automation sector
// École Polytechnique de Montréal
//
// Code adapted from algorithms presented in :
// Bierman, G. J. "Factorization Methods for Discrete Sequential
// Estimation", Academic Press, 1977.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#ifndef MFILE_H
#define MFILE_H
#include <vector>
#include <string>
#include "kalman/ktypes.hpp"
#include "kalman/kvector.hpp"
#include "kalman/kmatrix.hpp"
namespace Kalman {
#define LINE_MAX_LENGTH 65536
#define ROW_VECTOR 0
#define COLUMN_VECTOR 1
struct MFileElement
{
unsigned int Index;
unsigned int Rows;
unsigned int Cols;
std::string Name;
MFileElement();
MFileElement(const MFileElement& tmp);
~MFileElement();
MFileElement& operator=(const MFileElement& tmp);
};
class MFile {
public:
MFile();
~MFile();
int read(char *filename);
int save(char *filename);
void print();
template<typename T, K_UINT_32 BEG, bool DBG>
inline int get(std::string name, Kalman::KVector<T,BEG,DBG>& tmpvector);
template<typename T, K_UINT_32 BEG, bool DBG>
inline int get(std::string name, Kalman::KMatrix<T,BEG,DBG>& tmpmatrix);
template<typename T, K_UINT_32 BEG, bool DBG>
inline int add(std::string name, Kalman::KVector<T,BEG,DBG>& tmpvector, int type=ROW_VECTOR);
template<typename T, K_UINT_32 BEG, bool DBG>
inline int add(std::string name, Kalman::KMatrix<T,BEG,DBG>& tmpmatrix);
private:
bool add_double(std::string &tmpstr);
std::vector<MFileElement> VectorMFileElement;
std::vector<double> Data;
};
}
#include "MFile_impl.hpp"
#endif
|
// Copyright (c) 2020 gladcow
// Copyright (c) 2009-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "crypto.h"
#include <openssl/sha.h>
#include <openssl/ripemd.h>
#include <openssl/ec.h>
#include <openssl/bn.h>
#include <openssl/obj_mac.h>
#include <memory>
#include <algorithm>
namespace btc_utils
{
/** All alphanumeric characters except for "0", "I", "O", and "l" */
static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
std::string encode_base58(const std::vector<unsigned char>& data)
{
// Skip & count leading zeroes.
auto pbegin = std::find_if(data.begin(), data.end(),
[](unsigned char c) { return c != 0u; });
size_t zeroes = size_t(pbegin - data.begin());
// Allocate enough space in big-endian base58 representation.
size_t size = (data.size() - zeroes) * 138u / 100u + 1u; // log(256) / log(58), rounded up.
std::vector<unsigned char> b58(size);
size_t length = 0;
// Process the bytes.
while (pbegin != data.end()) {
unsigned carry = *pbegin;
unsigned i = 0;
// Apply "b58 = b58 * 256 + ch".
for (auto it = b58.rbegin(); (carry != 0 || i < length) && (it != b58.rend()); it++, i++) {
carry += 256u * (*it);
*it = static_cast<unsigned char>(carry % 58u);
carry /= 58u;
}
length = i;
pbegin++;
}
// Skip leading zeroes in base58 result.
auto it = std::next(b58.begin(), static_cast<long int>(size - length));
while (it != b58.end() && *it == 0)
it++;
// Translate the result into a string.
std::string str;
str.reserve(zeroes + static_cast<size_t>(b58.end() - it));
str.assign(zeroes, '1');
while (it != b58.end())
str += pszBase58[*(it++)];
return str;
}
std::string encode_base58_check(const std::vector<unsigned char> &data)
{
// add 4-byte hash check to the end
std::vector<unsigned char> vch(data);
uint256_t tmp = hash_sha256(vch);
uint256_t h = hash_sha256(std::vector<unsigned char>(tmp.begin(), tmp.end()));
vch.insert(vch.end(), &h[0], &h[0] + 4);
return encode_base58(vch);
}
uint256_t hash_sha256(const std::vector<unsigned char> &data)
{
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, data.data(), data.size());
uint256_t res;
SHA256_Final(&res[0], &sha256);
return res;
}
uint160_t hash_ripemd160(const std::vector<unsigned char> &data)
{
RIPEMD160_CTX ripemd;
RIPEMD160_Init(&ripemd);
RIPEMD160_Update(&ripemd, data.data(), data.size());
uint160_t res;
RIPEMD160_Final(&res[0], &ripemd);
return res;
}
const signed char p_util_hexdigit[256] =
{ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
-1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
signed char HexDigit(char c)
{
return p_util_hexdigit[static_cast<unsigned char>(c)];
}
std::vector<unsigned char> from_hex(const std::string& hex)
{
if(hex.length() % 2 != 0)
throw std::runtime_error("Invalid hex string size");
std::vector<unsigned char> res;
res.resize(hex.length() / 2);
auto it = hex.begin();
size_t count = 0;
static signed char failed = static_cast<signed char>(-1);
while (it != hex.end())
{
signed char c = HexDigit(*it++);
if (c == failed)
throw std::runtime_error("Invalid symbol in hex string");
unsigned char n = static_cast<unsigned char>(c << 4);
c = HexDigit(*it++);
if (c == failed)
throw std::runtime_error("Invalid symbol in hex string");
n = static_cast<unsigned char>(n | c);
res[count++] = n;
}
return res;
}
std::string to_hex(const std::vector<unsigned char>& v)
{
std::string rv;
static const char hexmap[16] = { '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
rv.reserve(v.size() * 2);
for(auto c = v.rend(); c != v.rbegin(); c++)
{
unsigned char val = *c;
rv.push_back(hexmap[val>>4]);
rv.push_back(hexmap[val&15]);
}
return rv;
}
uint256_t uint256_from_hex(const std::string& hex)
{
if(hex.length() != 64u)
throw std::runtime_error("Invalid hex string size for uint256");
uint256_t res;
auto it = hex.begin();
size_t count = 0;
static signed char failed = static_cast<signed char>(-1);
while (it != hex.end())
{
signed char c = HexDigit(*it++);
if (c == failed)
throw std::runtime_error("Invalid symbol in hex string");
unsigned char n = static_cast<unsigned char>(c << 4);
c = HexDigit(*it++);
if (c == failed)
throw std::runtime_error("Invalid symbol in hex string");
n = static_cast<unsigned char>(n | c);
res[count++] = n;
}
return res;
}
std::string uint256_to_hex(const uint256_t& v)
{
std::string rv;
static const char hexmap[16] = { '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
rv.reserve(v.size() * 2);
for(auto c = v.rend(); c != v.rbegin(); c++)
{
unsigned char val = *c;
rv.push_back(hexmap[val>>4]);
rv.push_back(hexmap[val&15]);
}
return rv;
}
pub_key_t priv_key_t::get_pub_key() const
{
std::unique_ptr<BN_CTX, decltype(&BN_CTX_free)> ctx(
BN_CTX_new(),
&BN_CTX_free
);
if(!ctx)
throw std::runtime_error("Failed to create BN_CTX");
std::unique_ptr<EC_GROUP, decltype(&EC_GROUP_free)> curve(
EC_GROUP_new_by_curve_name(NID_secp256k1),
&EC_GROUP_free
);
if(!curve)
throw std::runtime_error("Failed to get secp256k1 group");
std::unique_ptr<BIGNUM, decltype(&BN_free)> prv(
BN_bin2bn(data_.data(), static_cast<int>(data_.size()), nullptr),
&BN_free
);
std::unique_ptr<EC_POINT, decltype(&EC_POINT_free)> pub(
EC_POINT_new(curve.get()),
&EC_POINT_free
);
if (1 != EC_POINT_mul(curve.get(), pub.get(), prv.get(), NULL, NULL,
ctx.get()))
throw std::runtime_error("Failed to calc public key");
std::unique_ptr<EC_KEY, decltype(&EC_KEY_free)> key(
EC_KEY_new_by_curve_name(NID_secp256k1),
&EC_KEY_free
);
if(!key)
throw std::runtime_error("Failed to generate EC_KEY");
if(1 != EC_KEY_set_private_key(key.get(), prv.get()))
throw std::runtime_error("Failed to set private key in EC_KEY");
if(1 != EC_KEY_set_public_key(key.get(), pub.get()))
throw std::runtime_error("Failed to set public key in EC_KEY");
point_conversion_form_t form = compressed_ ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED;
unsigned char* tmp = nullptr;
size_t len = EC_KEY_key2buf(key.get(), form, &tmp, ctx.get());
std::unique_ptr<unsigned char, decltype(&free)> autofree(tmp, &free);
pub_key_t result;
result.set(tmp, tmp + len);
return result;
}
}
|
/****************************************
*
* INSERT-PROJECT-NAME-HERE - INSERT-GENERIC-NAME-HERE
* Copyright (C) 2019 Victor Tran
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* *************************************/
#include "stickdiagnostics.h"
#include "ui_stickdiagnostics.h"
#include <QGamepad>
#include "gamepadevent.h"
#include "pauseoverlay.h"
#include "questionoverlay.h"
struct StickDiagnosticsPrivate {
QGamepad gamepad;
};
StickDiagnostics::StickDiagnostics(int gamepadId, QWidget *parent) :
QWidget(parent),
ui(new Ui::StickDiagnostics)
{
ui->setupUi(this);
d = new StickDiagnosticsPrivate();
d->gamepad.setDeviceId(gamepadId);
ui->stickL->setSide(tr("L", "L for (L)eft"));
ui->stickR->setSide(tr("R", "R for (R)ight"));
PauseOverlay::overlayForWindow(parent)->pushOverlayWidget(this);
connect(&d->gamepad, &QGamepad::connectedChanged, this, [=](bool connected) {
if (!connected) {
d->gamepad.blockSignals(true);
QuestionOverlay* question = new QuestionOverlay(this);
question->setIcon(QMessageBox::Critical);
question->setTitle(tr("Gamepad Disconnected"));
question->setText(tr("The gamepad that you were testing was disconnected."));
question->setButtons(QMessageBox::Ok);
auto after = [=] {
question->deleteLater();
quit();
};
connect(question, &QuestionOverlay::accepted, this, after);
connect(question, &QuestionOverlay::rejected, this, after);
}
});
ui->gamepadHud->setButtonText(QGamepadManager::ButtonB, tr("Done"));
ui->gamepadHud->setButtonAction(QGamepadManager::ButtonB, [=] {
ui->finishButton->click();
});
}
StickDiagnostics::~StickDiagnostics()
{
delete ui;
delete d;
}
void StickDiagnostics::quit()
{
d->gamepad.blockSignals(true);
PauseOverlay::overlayForWindow(this)->popOverlayWidget([=] {
emit done();
});
}
bool StickDiagnostics::event(QEvent*event)
{
if (event->type() == GamepadEvent::type()) {
GamepadEvent* e = static_cast<GamepadEvent*>(event);
if (e->gamepad()->deviceId() == d->gamepad.deviceId() && !e->isButtonEvent()) {
StickDiagnosticsStickWidget* w;
if (e->axis() == QGamepadManager::AxisLeftX || e->axis() == QGamepadManager::AxisLeftY) {
w = ui->stickL;
} else {
w = ui->stickR;
}
w->setAxisLocation(e->newAxisLocation());
}
e->accept();
return true;
}
return false;
}
void StickDiagnostics::on_finishButton_clicked()
{
quit();
}
|
#pragma once
#include <SFML/Graphics.hpp>
#include <string>
#include "Animation.h"
class Object : public Animation
{
public:
Object();
Object(sf::RenderWindow* window);
~Object();
sf::Vector2f get_pos() const { return pos_; }
void set_pos(const int&x, const int& y) { pos_ = sf::Vector2f(x, y); }
protected:
sf::Vector2f pos_;
};
|
// heap sort
// _ ____ __ _ _ __
// (_/_(_(_(_)(__ / (_(_/_(_(_(_/__(/_/ (_
// /( .-/ .-/
// (_) (_/ (_/
#include "../_library_sort_.h"
// Độ phức tạp:
// Best: O(nlogn) | Avarage: O(nlogn) | Worst: O(nlogn) | Memory: O(1) | Unstable
// Dynamic Programming, Greedy
// Internal sort
// Non-adaptive sort
// Ưu điểm:
// - Nhanh với bất kì bộ dữ liệu nào
// - Có thể cài đặt không đệ quy
// - Không có worst case
// Nhược điểm:
// - Chậm hơn Merge & Quick Sort
// - Không ổn định
template<class T> void HeapSort(T *arr, lli n) {
lli i, j;
// Build Max Heap
for (i = 1; i < n; i++)
{
// Node con lớn node cha
if (arr[i] > arr[(i - 1) / 2])
{
j = i;
// Đưa node con lên trên
// j: Node con | (j - 1) / 2]: Node cha
while (arr[j] > arr[(j - 1) / 2])
{
Swap(arr[j], arr[(j - 1) / 2]);
j = (j - 1) / 2;
}
}
}
for (i = n - 1; i > 0; i--)
{
// Cho phần tử lớn nhất xuống dưới cùng,
// Sau đó, cập nhật lại cây
Swap(arr[0], arr[i]);
j = 0;
lli childLeft;
lli childRight;
do
{
childLeft = (2 * j + 1);
childRight = childLeft + 1;
if (arr[childLeft] < arr[childRight] && childLeft < (i - 1)) {
childLeft++;
}
if (arr[j] < arr[childLeft] && childLeft < i) {
Swap(arr[j], arr[childLeft]);
}
j = childLeft;
} while (childLeft < i);
}
}
// Heap sort đệ quy
template<class T> void HeapSort_UseRecursion(T *arr, lli n)
{
// Build heap bằng cây nhị phân
for (lli i = n / 2 - 1; i >= 0; i--) {
Heapify(arr, n, i);
}
// Heap Sort
for (lli i = n - 1; i >= 0; i--)
{
// Cho phần tử lớn nhất xuống dưới cùng,
// Sau đó, cập nhật lại cây
Swap(arr[i], arr[0]);
Heapify(arr, i, 0);
}
}
template<class T> void Heapify(T *arr, lli n, lli i)
{
lli childLeft = 2 * i + 1;
lli childRight = 2 * i + 2;
lli maxIdx;
// Tìm ra node lớn nhất trong 3 node: node cha và 2 node con
if (childLeft < n && arr[childLeft] > arr[i]) maxIdx = childLeft;
else maxIdx = i;
if (childRight < n && arr[childRight] > arr[maxIdx]) maxIdx = childRight;
// Đổi chỗ và tiếp tục đệ quy
if (maxIdx != i)
{
Swap(arr[i], arr[maxIdx]);
Heapify(arr, n, maxIdx);
}
}
int main() {
lli *arr;
lli n{};
Input(arr, n);
HeapSort(arr, n);
Output(arr, n);
return 0;
}
|
// p244
// 차근차근
// 제곱합
// 범위 내 제곱 계산 알아두기
#include <iostream>
#include <stdio.h>
using namespace std;
const int INF = 987654321;
int n;
// pSum : 합 / pSqSum : 제곱합
int A[101], pSum[101], pSqSum[101];
int cache[101][11];
void precalc(){
sort(A, A+n);
pSum[0] = A[0];
pSqSum[0] = A[0]*A[0];
for(int i=1; i<n; i++){
pSum[i] = pSum[i-1] + A[i];
pSqSum[i] = pSqSum[i-1] + A[i]*A[i];
}
}
// N[a...b]
int minError(int a, int b){
// A[a] + ... + A[b]
int sum = pSum[b] - (a == 0? 0 : pSum[a-1]);
int sqSum = pSqSum[b] - (a==0? 0: pSqSum[a-1]);
// int (0.5) 더하는건 반올림하려고!!!
int m = int( 0.5 + (double)sum/(b-a+1));
// sum (A[i]-m)^2 (b-a+1)곱해주는건 범위때문에!
int res = sqSum - 2*m*sum + m*m*(b-a+1);
}
// 정렬된 후
// 첫묶음 크기 x + n-x개를 s-1개로 묶기
int quantize(int from, int s){
// 마지막일 때
if (from == n) return 0;
if (s==0) return INF;
int& res = cache[from][s];
if (res!=-1) return res;
res = INF;
for(int i=1; i+from <= n; i++){
res = min(res, minError(from, from+i-1) + quantize(from+i, s-1));
}
return res;
}
int main(){
int tcase, s;
cin>>tcase;
for (int i=0; i<tcase; i++){
scanf("%d %d",&n,&s);
// vector<int> N(n);
for (int j=0 ; j<n; j++){
scanf("%d",&A[j]);
}
precalc();
quantize(0, s);
}
}
|
// Copyright 2020 JD.com, Inc. Galileo Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ==============================================================================
#pragma once
#include <glog/logging.h>
#include <zookeeper/zookeeper.h>
#include <condition_variable>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include "discovery/consts.h"
namespace galileo {
namespace discovery {
typedef void (*ConnectionWatcher)(zhandle_t *zh, int type, int state,
const char *path, void *watcherCtx);
class Connection {
public:
explicit Connection(const std::string &address);
~Connection();
zhandle_t *GetHandle();
template <typename Context>
void Connect(Context *, ConnectionWatcher watcher,
uint32_t max_retry_times = kMaxRetryTimes);
void Close();
template <typename Context>
void Reconnect(Context *context, ConnectionWatcher watcher,
uint32_t max_retry_times = kMaxRetryTimes) {
Close();
Connect(context, watcher, max_retry_times);
}
void Connected(zhandle_t *handle);
private:
void _WaitConnect();
Connection(const Connection &) = delete;
Connection &operator=(const Connection &) = delete;
std::string address_;
zhandle_t *handle_;
std::mutex mt_;
std::condition_variable cv_;
};
template <typename Context>
void Connection::Connect(Context *context, ConnectionWatcher watcher,
uint32_t max_retry_times) {
zhandle_t *handle = nullptr;
if (max_retry_times < 1) {
max_retry_times = 1;
}
for (uint32_t t = 1; t <= max_retry_times; ++t) {
handle = zookeeper_init(address_.c_str(), watcher, kSessionTimeoutMS,
/*clientid=*/nullptr, /*context=*/context, 0);
if (handle == nullptr) {
LOG(WARNING) << " Failed to create zookeeper client, "
"recreating ... #" +
std::to_string(t);
std::chrono::seconds sp(5 * t);
std::this_thread::sleep_for(sp);
} else {
break;
}
}
if (handle == nullptr) {
std::string error =
" Failed to create zookeeper client, "
"and reached the max retry times " +
std::to_string(max_retry_times);
LOG(ERROR) << error;
throw std::runtime_error(error);
}
this->_WaitConnect();
}
} // namespace discovery
} // namespace galileo
|
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
const double eps = 1e-14;
struct Point
{
double x, y;
};
class Shape
{
public:
Shape(const string &name);
//default copy constructor
//default assign operator
virtual ~Shape(){}
virtual double getSquare()const=0;
virtual double getPerimeter()const=0;
string getName();
private:
string m_name;
};
class Circle: public Shape
{
public:
Circle(Point origin, double radius, const string &name);
//default copy constructor
//default assign operator
//default destructor
double getSquare()const;
double getPerimeter()const;
private:
Point m_origin;
double m_radius;
};
class Triangle: public Shape
{
public:
Triangle(Point A, Point B, Point C, const string &name);
//default copy constructor
//default assign operator
//default destructor
double getSquare()const;
double getPerimeter()const;
private:
Point m_A, m_B, m_C;
};
void input(Shape **array,int count);
void output(Shape **array,int count);
double calcRatio(const Shape &shape);
Point input();
int main()
{
Shape **array = 0;
int count;
cout<<"Enter number of shapes:\n";
cin>>count;
array = new Shape*[count];
for(int i = 0; i < count; ++i)
array[i] = 0;
input(array, count);
output(array, count);
for(int i = 0; i < count; ++i)
delete array[i];
delete [] array;
return 0;
}
double calcRatio(const Shape &shape)
{
if(fabs(shape.getPerimeter())>eps)
return shape.getSquare()/shape.getPerimeter();
else
return 0.0;
}
void input(Shape **array,int count)
{
for(int i = 0; i < count; ++i)
{
int selection;
do
{
cout<<"Select the type of a shype:\n";
cout<<"1) circle\n2) triangle\n";
cin>>selection;
string name;
Point O, A, B, C;
switch(selection)
{
case 1:
cout<<"enter the name of the circle:\n";
cin>>name;
cout<<"enter the center of the circle:\n";
O=input();
cout<<"enter the radius of the circle:\n";
double radius;
cin>>radius;
array[i] = new Circle(O,radius,name);
break;
case 2:
cout<<"enter the name of the triangle:\n";
cin>>name;
cout<<"enter the vertices of triangle\n";
cout<<"enter the point A:\n";
A=input();
cout<<"enter the point B:\n";
B=input();
cout<<"enter the point C:\n";
C=input();
array[i] = new Triangle(A, B, C, name);
break;
default:
cerr<<"incorrect selection\n";
}
}while(selection < 1 || selection > 2);
}
}
void output(Shape **array,int count)
{
for(int i = 0; i < count; ++i)
{
cout<<"The "<<i+1<<" is the "<<array[i]->getName()<<".\n";
cout<<"It has perimeter "<<array[i]->getPerimeter()<<".\n";
cout<<"It has square "<<array[i]->getSquare()<<".\n";
cout<<"The square-perimeter ratio is "<<calcRatio(*array[i])<<".\n";
cout<<endl<<endl;
}
}
Point input()
{
Point result;
cout<<"enter x coordinate:\n";
cin>>result.x;
cout<<"enter y coordinate:\n";
cin>>result.y;
return result;
}
Shape::Shape(const string &name):
m_name(name)
{}
string Shape::getName()
{
return m_name;
}
Circle::Circle(Point origin, double radius, const string &name):
Shape(string("circle ")+name),
m_origin(origin),
m_radius(radius)
{}
double Circle::getSquare()const
{
return M_PI*m_radius*m_radius;
}
double Circle::getPerimeter()const
{
return 2.0*M_PI*m_radius;
}
Triangle::Triangle(Point A, Point B, Point C, const string &name):
Shape(string("triangle ")+name),
m_A(A),
m_B(B),
m_C(C)
{}
double Triangle::getSquare()const
{
double a = sqrt((m_B.x - m_C.x) * (m_B.x - m_C.x) + (m_B.y - m_C.y) * (m_B.y - m_C.y));
double b = sqrt((m_C.x - m_A.x) * (m_C.x - m_A.x) + (m_C.y - m_A.y) * (m_C.y - m_A.y));
double c = sqrt((m_A.x - m_B.x) * (m_A.x - m_B.x) + (m_A.y - m_B.y) * (m_A.y - m_B.y));
double p = getPerimeter()/2.0;
return sqrt(p * (p - a) * (p - b) * (p - c));
}
double Triangle::getPerimeter()const
{
double a = sqrt((m_B.x - m_C.x) * (m_B.x - m_C.x) + (m_B.y - m_C.y) * (m_B.y - m_C.y));
double b = sqrt((m_C.x - m_A.x) * (m_C.x - m_A.x) + (m_C.y - m_A.y) * (m_C.y - m_A.y));
double c = sqrt((m_A.x - m_B.x) * (m_A.x - m_B.x) + (m_A.y - m_B.y) * (m_A.y - m_B.y));
return a + b + c;
}
|
#define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include <string>
#define MYVALUE 100
class Person {
public:
const int age; // 변수형태의 공간을 갖고있는 상수다. -> 강제적으로 바꿀 수 없다.
Person(int n) : age(n) {
}
};
int main() {
const char* str;
char* myStr = new char[100];
strcpy(myStr, "Hello World!");
str = myStr;
printf("%s", str);
return 0;
int input;
fseek(stdin, 0, SEEK_END);
scanf("%d", &input);
Person* p = new Person(input);
printf("%d", p->age);
return 0;
}
|
#include "StdAfx.h"
#include "QuoteUdpAgent.h"
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
CQuoteUdpAgent::CQuoteUdpAgent(CQuoteAgentCallback* pCallback)
: CQuoteAgentBase(pCallback)
{
}
CQuoteUdpAgent::~CQuoteUdpAgent()
{
}
int GetQuoteBroadcastPort(const string& frontAddr)
{
bool isUdp = boost::istarts_with(frontAddr, "udp://255.255.255.255");
int nPort = -1;
if (isUdp)
{
string portStr = frontAddr.substr(22);
try
{
nPort = boost::lexical_cast<int>(portStr);
}
catch (const boost::bad_lexical_cast &)
{
}
}
return nPort;
}
boost::tuple<bool, string> CQuoteUdpAgent::Login(const string& frontAddr, const string& brokerId, const string& investorId, const string& userId, const string& password)
{
m_brokerID = brokerId;
m_userID = investorId;
int nPort = GetQuoteBroadcastPort(frontAddr);
if (nPort > 0)
{
m_udpListener = UdpQuoteListenerPtr(
new CUdpQuoteListener(nPort,
boost::bind(&CQuoteUdpAgent::OnUdpDataReceived, this, _1, _2)));
m_bIsConnected = true;
return boost::make_tuple(true, "");
}
else
{
return boost::make_tuple(false, "Cannot find port from connection string");
}
}
void CQuoteUdpAgent::Logout()
{
if (m_bIsConnected)
{
m_bIsConnected = false;
m_udpListener.reset();
}
}
bool CQuoteUdpAgent::SubscribesQuotes(vector<string>& subscribeArr)
{
boost::mutex::scoped_lock lock(m_mutSymbol);
for (vector<string>::iterator iter = subscribeArr.begin(); iter != subscribeArr.end(); ++iter)
{
m_symbols.insert(*iter);
}
return true;
}
bool CQuoteUdpAgent::UnSubscribesQuotes(vector<string>& unSubscribeArr)
{
boost::mutex::scoped_lock lock(m_mutSymbol);
for (vector<string>::iterator iter = unSubscribeArr.begin(); iter != unSubscribeArr.end(); ++iter)
{
set<string>::iterator iterFound = m_symbols.find(*iter);
{
if (iterFound != m_symbols.end())
{
m_symbols.erase(iterFound);
}
}
}
return true;
}
void CQuoteUdpAgent::OnUdpDataReceived(char* pData, std::size_t nSize)
{
boost::mutex::scoped_lock lock(m_mutSymbol);
CThostFtdcDepthMarketDataField *pDepthMarketData = reinterpret_cast<CThostFtdcDepthMarketDataField*>(pData);
set<string>::iterator iterFound = m_symbols.find(pDepthMarketData->InstrumentID);
if (iterFound != m_symbols.end())
{
longlong timestamp = boost::chrono::steady_clock::now().time_since_epoch().count();
m_pCallback->OnQuoteReceived(pDepthMarketData, timestamp);
}
}
|
/*
1614. 영식이의 손가락
수가 쭉 나열되는 것은 규칙이 있는지 살펴보자.
범위를 잘 파악하자 int -> long
*/
#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
typedef long long ll;
ll N, M;
ll Answer;
int main()
{
cin >> N >> M;
Answer = N - 1;
if(M > 0)
{
if(N == 1 || N == 5)
{
Answer += 8 * M;
}
else
{
Answer += M / 2 * 8;
if(N == 2)
{
if(M % 2) Answer += 6;
}
else if(N == 3)
{
if(M % 2) Answer += 4;
}
else if(N == 4)
{
if(M % 2) Answer += 2;
}
}
}
cout << Answer << endl;
return 0;
}
|
#include <bits/stdc++.h>
using namespace std;
using ll = long long int;
int const N = 2e5 + 10;
vector< int > x;
int dp[3][N];
int n,k;
int DP(int pos, int l){
if(pos >= n) return 0;
int &ret = dp[l][pos] ;
if(ret != -1) return ret;
ret = DP(pos+1,l);
if(l>0){
int _pos = upper_bound(x.begin() , x.end(), x[pos]+k) - x.begin();
ret = max(ret, _pos - pos + DP(_pos, l-1));
}
return ret;
}
int main(){
ios::sync_with_stdio(0); cin.tie(0);
int t;
cin >> t;
while(t--){
cin >> n >> k;
x.resize(n);
for(int i = 0; i < n; i++){
cin >> x[i];
}
int tmp;
for(int i = 0; i < n; i++) cin >> tmp;
sort(x.begin(), x.end());
for(int i= 0; i <= 2; i++)
for(int j = 0; j <= n + 5; j++)
dp[i][j] = -1;
cout << DP(0,2) << '\n';
}
}
|
#ifndef QADDDIALOG_H
#define QADDDIALOG_H
#include <QWidget>
#include <QFormLayout>
#include <QLineEdit>
#include <QComboBox>
#include <QPushButton>
#include <iostream>
using std::cout;
using std::endl;
class QAddDialog : public QWidget
{
Q_OBJECT
private:
std::string name;
std::string sname;
std::string cf;
std::string contr;
QLineEdit* insert_name;
QLineEdit* insert_sname;
QLineEdit* insert_cf;
QComboBox* insert_cont;
public:
explicit QAddDialog(QWidget *parent = nullptr);
signals:
void emitAdd(const std::string&, const std::string&, const std::string&, const std::string&);
void enableConfirm(const bool&);
public slots:
void slotAdd();
void checkFilled();
};
#endif // QADDDIALOG_H
|
#include <bits/stdc++.h>
#define ll long long
using namespace std;
typedef tuple<ll, ll, ll> tp;
typedef pair<ll, ll> pr;
const ll MOD = 1000000007;
const ll INF = 1e18;
template <typename T> void print(const T &t) {
std::copy(t.cbegin(), t.cend(),
std::ostream_iterator<typename T::value_type>(std::cout, " "));
cout << endl;
}
template <typename T> void print2d(const T &t) {
std::for_each(t.cbegin(), t.cend(), print<typename T::value_type>);
}
void setIO(string s) { // the argument is the filename without the extension
freopen((s + ".in").c_str(), "r", stdin);
freopen((s + ".out").c_str(), "w", stdout);
}
int n;
int ans = 0;
bool valid(vector<vector<int>>& S, string curr){
for(ll i = 0; i < n; i++){
if(curr[i] == '1'){
for(ll j = 0; j < n; j++){
if(S[i][j] != 2 && S[i][j] != curr[j] - '0') return false;
}
}
}
return true;
}
void dfs(vector<vector<int>>& S, int i, int cnt, string curr){
if(i == n){
if(valid(S, curr)) ans = max(ans, cnt);
return;
}
curr.append(1, '0'); // this is bad person
dfs(S, i + 1, cnt, curr);
curr.back() = '1'; // This is good person
dfs(S, i + 1, cnt+1, curr);
curr.pop_back();
}
int maximumGood(vector<vector<int>>& S) {
n = S.size();
string curr = "";
dfs(S, 0, 0, curr);
return ans;
}
int main() {
cin.tie(0)->sync_with_stdio(0);
cin.exceptions(cin.failbit);
}
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "XSpace.h"
#include "XCapsuleSpace.generated.h"
/**
*
*/
UCLASS()
class XPROJECT_API AXCapsuleSpace : public AXSpace
{
GENERATED_BODY()
public:
AXCapsuleSpace();
// Called every frame
virtual void Tick(float DeltaTime) override;
UFUNCTION(BlueprintCallable)
void SetRadiusDelta(float Height);
UFUNCTION(BlueprintCallable)
float GetRadiusDelta();
UFUNCTION(BlueprintCallable)
void SetRadiusMinimum(float Minimum);
UFUNCTION(BlueprintCallable)
float GetRadiusMinimum();
UFUNCTION(BlueprintCallable)
void SetRadiusMaximum(float Maximum);
UFUNCTION(BlueprintCallable)
float GetRadiusMaximum();
UFUNCTION(BlueprintCallable)
void SetHeightDelta(float SpaceSize);
UFUNCTION(BlueprintCallable)
float GetHeightDelta();
UFUNCTION(BlueprintCallable)
void SetHeightMinimum(float Minimum);
UFUNCTION(BlueprintCallable)
float GetHeightMinimum();
UFUNCTION(BlueprintCallable)
void SetHeightMaximum(float Maximum);
UFUNCTION(BlueprintCallable)
float GetHeightMaximum();
UShapeComponent * GetCollisionComponent() override;
//// Komponent kuli z kolizja
UPROPERTY(VisibleDefaultsOnly, BlueprintReadWrite)
UCapsuleComponent * CapsuleCollisionComponent;
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
private:
UPROPERTY(EditAnywhere)
float RadiusDelta;
UPROPERTY(EditAnywhere)
float RadiusMinimum;
UPROPERTY(EditAnywhere)
float RadiusMaximum;
UPROPERTY(EditAnywhere)
float HalfHeightDelta;
UPROPERTY(EditAnywhere)
float HalfHeightMinimum;
UPROPERTY(EditAnywhere)
float HalfHeightMaximum;
};
|
// FindkthMaxValueByHeap.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include "pch.h"
#include <iostream>
#include <queue>
using namespace std;
class Solution{
public:
int findKthLargest(vector<int> &nums, int k) {
priority_queue<int, vector<int>, greater<int>> Q;
for (int i = 0; i < nums.size(); i++) {
if (Q.size() < k)
Q.push(nums[i]);
else if (Q.top() < nums[i]) {
Q.pop();
Q.push(nums[i]);
}
}
return Q.top();
}
};
int main()
{
vector<int> v{ 3,4,6,2,8,9,10 };
int num = Solution().findKthLargest(v, 3);
cout << num << endl;
std::cout << "Hello World!\n";
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门提示:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
|
#include "Arduino.h"
elapsedMicros time_data;
void setup()
{
// initialize serial comms
Serial.begin(115200);
}
elapsedMicros wait = 0;
int unsigned wait_time = 300;
void loop()
{
// read A0
if(wait >= wait_time){
wait = 0;
int val1 = analogRead(6);
//int temp_time = time_data;
//time_data = 0;
// print to serial
Serial.print(val1);
//Serial.print(",");
//Serial.print(temp_time);
Serial.print("\n");
}
}
|
#include <math.h>
#include <stdio.h>
#include "common.h"
#include "smd3d.h"
/***************************************
* Global Variables
***************************************/
static LPDEVICEDESC lpDeviceDesc = NULL;
//The RenderDevice Object
RenderDevice renderDevice;
extern int ParkPlaying; //Of the video player
extern RECT ParkPlayRect; //
extern HWND hwnd;
extern HWND hFocusWnd;
extern DWORD smBackColor;
static DWORD FlagsToBitDepth(DWORD dwFlags)
{
if (dwFlags & DDBD_1)
return 1L;
else if (dwFlags & DDBD_2)
return 2L;
else if (dwFlags & DDBD_4)
return 4L;
else if (dwFlags & DDBD_8)
return 8L;
else if (dwFlags & DDBD_16)
return 16L;
else if (dwFlags & DDBD_24)
return 24L;
else if (dwFlags & DDBD_32)
return 32L;
else
return 0L;
}
// Direct3D Device EnumCallback Functions
HRESULT WINAPI DeviceEnumCallback(LPGUID lpGuid, LPSTR lpDeviceDescription, LPSTR lpDeviceName, LPD3DDEVICEDESC lpD3DHWDeviceDesc, LPD3DDEVICEDESC lpD3DHELDeviceDesc, LPVOID lpUserArg)
{
if (!lpUserArg)
return DDENUMRET_OK;
// Direct3D Device Add to the list
LPDEVICEDESC desc, *lpDesc = (LPDEVICEDESC *)lpUserArg;
if (!*lpDesc)
desc = *lpDesc = renderDevice.CreateDevice();
else
desc = renderDevice.CreateDevice(*lpDesc);
// Guid값 복사
memcpy(&desc->guid, lpGuid, sizeof(GUID));
// 디바이스 정보 복사
strcpy(desc->szName, lpDeviceName);
strcpy(desc->szDesc, lpDeviceDescription);
// 하드웨어 드라이브 인지 검사 하고 드라이브 정보 복사
if (lpD3DHWDeviceDesc->dcmColorModel)
{
desc->bIsHardware = TRUE;
memcpy(&desc->Desc, lpD3DHWDeviceDesc, sizeof(D3DDEVICEDESC));
}
else
{
desc->bIsHardware = FALSE;
memcpy(&desc->Desc, lpD3DHELDeviceDesc, sizeof(D3DDEVICEDESC));
}
return DDENUMRET_OK;
}
// Direct3D Device EnumCallback Functions
static HRESULT WINAPI EnumZBufferCallback(DDPIXELFORMAT *DDP_Format, VOID *DDP_Desired)
{
if (DDP_Format->dwFlags == DDPF_ZBUFFER)
{
memcpy(DDP_Desired, DDP_Format, sizeof(DDPIXELFORMAT));
return D3DENUMRET_CANCEL;
}
return D3DENUMRET_OK;
}
RenderDevice::RenderDevice()
{
WindowMode = WINMODE;
smTextureBPP = 16;
smScreenWidth = 0;
smScreenHeight = 0;
smFlipCount = 0;
lpD3DDeviceDesc = NULL;
// DirectDraw
lpDD = NULL;
lpDDSPrimary = NULL;
lpDDSBack = NULL;
lpDDClipper = NULL;
// Direct3D
lpD3D = NULL;
lpD3DDevice = NULL;
lpD3DViewport = NULL;
lpDDSZBuffer = NULL;
}
RenderDevice::~RenderDevice()
{
}
void RenderDevice::SetWindowMode(int _WindowMode)
{
WindowMode = _WindowMode;
}
LPDEVICEDESC RenderDevice::FindDevice(LPDEVICEDESC lpDesc, LPGUID lpGuid)
{
LPDEVICEDESC desc = lpDesc;
while (desc)
{
if (!memcmp(lpGuid, &desc->guid, sizeof(GUID)))
break;
desc = desc->lpNext;
}
return desc;
}
LPDEVICEDESC RenderDevice::FindBestDevice(LPDEVICEDESC lpDesc)
{
LPDEVICEDESC desc = FindDevice(lpDesc, (LPGUID)&IID_IDirect3DHALDevice);
if (!desc)
desc = FindDevice(lpDesc, (LPGUID)&IID_IDirect3DMMXDevice);
if (!desc)
desc = FindDevice(lpDesc, (LPGUID)&IID_IDirect3DRGBDevice);
return desc;
}
LPDEVICEDESC RenderDevice::CreateDevice()
{
LPDEVICEDESC desc = new DEVICEDESC;
if (!desc)
return NULL;
ZeroMemory(desc, sizeof(DEVICEDESC));
return desc;
}
LPDEVICEDESC RenderDevice::CreateDevice(LPDEVICEDESC lpDesc)
{
if (!lpDesc)
return CreateDevice();
LPDEVICEDESC desc = new DEVICEDESC;
if (!desc)
return NULL;
ZeroMemory(desc, sizeof(DEVICEDESC));
LPDEVICEDESC lastDesc = lpDesc;
while (lastDesc->lpNext)
lastDesc = lastDesc->lpNext;
lastDesc->lpNext = desc;
return desc;
}
// Direct3D Generation
BOOL RenderDevice::CreateD3D()
{
// DirectDraw Interface generation
LPDIRECTDRAW lpdd;
//Set DirectDraw Device
HRESULT hresult = DirectDrawCreate(NULL, &lpdd, NULL);
if (hresult != DD_OK)
{
Utils_Log(LOG_ERROR, "DirectDrawCreate");
return FALSE;
}
// DirectDraw2 Get Interface
hresult = lpdd->QueryInterface(IID_IDirectDraw4, (LPVOID*)&lpDD);
if (hresult != DD_OK)
{
Utils_Log(LOG_ERROR, "lpdd->QueryInterface");
return FALSE;
}
// DirectDraw Interfaces removed
lpdd->Release();
// Direct3D Get Interface
hresult = lpDD->QueryInterface(IID_IDirect3D3, (LPVOID*)&lpD3D);
if (hresult != DD_OK)
{
Utils_Log(LOG_ERROR, "lpDD3->QueryInterface");
return FALSE;
}
// Direct3D Device Get Interface
hresult = lpD3D->EnumDevices(DeviceEnumCallback, (LPVOID)&lpDeviceDesc);
if (hresult != DD_OK)
{
Utils_Log(LOG_ERROR, "lpD3D->EnumDevices");
return FALSE;
}
lpD3DDeviceDesc = FindBestDevice(lpDeviceDesc);
if (!lpD3DDeviceDesc)
return FALSE;
return TRUE;
}
// Direct3D Removal
void RenderDevice::ReleaseD3D()
{
//######################################################################################
//작 성 자 : 오 영 석
DestroyDevice(lpDeviceDesc);
//######################################################################################
//######################################################################################
//작 성 자 : 오 영 석
ReleaseNewRenderTarget();
//######################################################################################
// Viewport 제거
if (lpD3DViewport)
{
// Direct3D Device 에서 Viewport 제거
lpD3DDevice->DeleteViewport(lpD3DViewport);
lpD3DViewport->Release();
lpD3DViewport = NULL;
}
// Direct3D Device 제거
if (lpD3DDevice)
{
lpD3DDevice->Release();
lpD3DDevice = NULL;
}
// Z-Buffer Surface 제거
if (lpDDSZBuffer)
{
// Back Surface 에서 Z-Buffer Surface 제거
if (lpDDSBack)
lpDDSBack->DeleteAttachedSurface(0L, lpDDSZBuffer);
lpDDSZBuffer->Release();
lpDDSZBuffer = NULL;
}
//######################################################################################
//작 성 자 : 오 영 석
if (lpDDSBack)
{
lpDDSBack->Release();
lpDDSBack = NULL;
}
//######################################################################################
// Direct3D Interface 제거
if (lpD3D)
{
lpD3D->Release();
lpD3D = NULL;
}
// Primary Surface 제거
if (lpDDSPrimary)
{
lpDDSPrimary->Release();
lpDDSPrimary = NULL;
}
// DirectDraw2 Interface 제거
if (lpDD)
{
// 비디오 모드 복귀
lpDD->RestoreDisplayMode();
lpDD->Release();
lpDD = NULL;
}
}
//Destroy the DirectX Device
void RenderDevice::DestroyDevice(LPDEVICEDESC lpDesc)
{
LPDEVICEDESC desc;
while (lpDesc->lpNext)
{
desc = lpDesc->lpNext;
lpDesc->lpNext = lpDesc->lpNext->lpNext;
delete[] desc;
}
delete[] lpDesc;
}
// Video mode switching (fullmode)
BOOL RenderDevice::SetDisplayMode(HWND hWnd, DWORD Width, DWORD Height, DWORD BPP)
{
Utils_Log(LOG_DEBUG, "D3DX SetDisplayMode() Width(%d) Height(%d) Color(%d)", Width, Height, BPP);
// Set Cooperative Level
smTextureBPP = BPP;
if (WindowMode)
return SetDisplayModeWin(hWnd, Width, Height, BPP);
HRESULT hresult = lpDD->SetCooperativeLevel(hWnd, DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN | DDSCL_ALLOWMODEX);
if (hresult != DD_OK)
{
Utils_Log(LOG_ERROR, "lpDD->SetCooperativeLevel");
return FALSE;
}
// 풀화면 모드로 전환
hresult = lpDD->SetDisplayMode(Width, Height, BPP, 0, 0);
if (hresult != DD_OK)
{
Utils_Log(LOG_ERROR, "lpDD3->SetDisplayMode");
return FALSE;
}
// Primary Surface 생성
DDSURFACEDESC2 ddsd;
ZeroMemory(&ddsd, sizeof(ddsd));
ddsd.dwSize = sizeof(ddsd);
ddsd.dwBackBufferCount = 1;
ddsd.dwFlags = DDSD_CAPS | DDSD_BACKBUFFERCOUNT;
ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE | DDSCAPS_FLIP | DDSCAPS_COMPLEX | DDSCAPS_VIDEOMEMORY | DDSCAPS_3DDEVICE;
// Primary surface 생성
hresult = CreateSurface(&ddsd, &lpDDSPrimary, NULL);
if (hresult != DD_OK)
{
Utils_Log(LOG_ERROR, "CreateSurface(lpDDSPrimary)");
return FALSE;
}
// Back Surface 생성(?)
DDSCAPS2 ddscaps;
ddscaps.dwCaps = DDSCAPS_BACKBUFFER;
hresult = lpDDSPrimary->GetAttachedSurface(&ddscaps, &lpDDSBack);
if (hresult != DD_OK)
{
Utils_Log(LOG_ERROR, "lpDDSPrimary->GetAttachedSurface");
return FALSE;
}
//////////// 클리퍼 생성 ////////////////////////
lpDD->CreateClipper(0, &lpDDClipper, NULL);
lpDDClipper->SetHWnd(0, hWnd);
lpDDSPrimary->SetClipper(lpDDClipper);
lpDDClipper->Release();
// z-buffer Surface 생성
ZeroMemory(&ddsd, sizeof(ddsd));
ddsd.dwSize = sizeof(ddsd);
ddsd.dwFlags = DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT | DDSD_PIXELFORMAT;
ddsd.dwWidth = Width;
ddsd.dwHeight = Height;
lpD3D->EnumZBufferFormats(IID_IDirect3DHALDevice, EnumZBufferCallback, (VOID *)&ddsd.ddpfPixelFormat);
//######################################################################################
//작 성 자 : 오 영 석
::CopyMemory(&g_ddpfPixelFormatZ, &ddsd.ddpfPixelFormat, sizeof(g_ddpfPixelFormatZ));
//######################################################################################
// 하드웨어 이면 z-buffer를 비디오 메모리에 만든다.
if (lpD3DDeviceDesc->bIsHardware)
ddsd.ddsCaps.dwCaps = DDSCAPS_ZBUFFER | DDSCAPS_VIDEOMEMORY;
else
ddsd.ddsCaps.dwCaps = DDSCAPS_ZBUFFER | DDSCAPS_SYSTEMMEMORY;
// Create the ZBuffer surface.
hresult = CreateSurface(&ddsd, &lpDDSZBuffer, NULL);
if (hresult != DD_OK)
{
Utils_Log(LOG_ERROR, "CreateSurface(lpDDSZBuffer)");
return FALSE;
}
// Back Surface에 Z-buffer를 붙인다.
hresult = lpDDSBack->AddAttachedSurface(lpDDSZBuffer);
if (hresult != DD_OK)
{
Utils_Log(LOG_ERROR, "lpDDSBack->AddAttachedSurface");
return FALSE;
}
// Direct3D Device 생성
hresult = lpD3D->CreateDevice(lpD3DDeviceDesc->guid, lpDDSBack, &lpD3DDevice, NULL);
if (hresult != D3D_OK)
{
Utils_Log(LOG_ERROR, "lpD3D->CreateDevice");
return FALSE;
}
// Viewport Size Settings
D3DRect.x1 = 0;
D3DRect.y1 = 0;
D3DRect.x2 = Width;
D3DRect.y2 = Height;
smScreenWidth = Width;
smScreenHeight = Height;
return CreateViewport();
}
// Video mode switching (winmode)
BOOL RenderDevice::SetDisplayModeWin(HWND hWnd, DWORD Width, DWORD Height, DWORD BPP)
{
Utils_Log(LOG_DEBUG, "D3DX SetDisplayModeWin() Width(%d) Height(%d) Color(%d)", Width, Height, BPP);
// Set Cooperative Level
HRESULT hresult = lpDD->SetCooperativeLevel(hWnd, DDSCL_NORMAL);
if (hresult != DD_OK)
{
Utils_Log(LOG_ERROR, "lpDD->SetCooperativeLevel");
return FALSE;
}
// Primary Surface 생성
DDSURFACEDESC2 ddsd;
ZeroMemory(&ddsd, sizeof(ddsd));
ddsd.dwSize = sizeof(ddsd);
ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE |
DDSCAPS_3DDEVICE;
// Primary surface 생성
hresult = CreateSurface(&ddsd, &lpDDSPrimary, NULL);
if (hresult != DD_OK)
{
Utils_Log(LOG_ERROR, "CreateSurface(lpDDSPrimary)");
return FALSE;
}
int w, h;
RECT lpRect;
GetWindowRect(GetDesktopWindow(), &lpRect);
w = lpRect.right - lpRect.left;
h = lpRect.bottom - lpRect.top;
// 백 버퍼 1 생성
ZeroMemory(&ddsd, sizeof(ddsd));
ddsd.dwSize = sizeof(ddsd);
ddsd.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH;
ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN | DDSCAPS_3DDEVICE | DDSCAPS_VIDEOMEMORY;
ddsd.dwWidth = w;
ddsd.dwHeight = h;
CreateSurface(&ddsd, &lpDDSBack, NULL);
lpDD->CreateClipper(0, &lpDDClipper, NULL);
lpDDClipper->SetHWnd(0, hWnd);
lpDDSPrimary->SetClipper(lpDDClipper);
lpDDClipper->Release();
DDPIXELFORMAT ddpx;
// z-buffer Surface 생성
ZeroMemory(&ddsd, sizeof(ddsd));
ddsd.dwSize = sizeof(ddsd);
ddsd.dwFlags = DDSD_CAPS |
DDSD_WIDTH |
DDSD_HEIGHT |
DDSD_PIXELFORMAT;
ddsd.dwWidth = w;
ddsd.dwHeight = h;
lpD3D->EnumZBufferFormats(lpD3DDeviceDesc->guid, EnumZBufferCallback, (VOID *)&ddpx);
memcpy(&ddsd.ddpfPixelFormat, &ddpx, sizeof(DDPIXELFORMAT));
//######################################################################################
//작 성 자 : 오 영 석
::CopyMemory(&g_ddpfPixelFormatZ, &ddsd.ddpfPixelFormat, sizeof(g_ddpfPixelFormatZ));
//######################################################################################
// 하드웨어 이면 z-buffer를 비디오 메모리에 만든다.
if (lpD3DDeviceDesc->bIsHardware)
ddsd.ddsCaps.dwCaps = DDSCAPS_ZBUFFER | DDSCAPS_VIDEOMEMORY;
else
ddsd.ddsCaps.dwCaps = DDSCAPS_ZBUFFER | DDSCAPS_SYSTEMMEMORY;
// Create the ZBuffer surface.
hresult = CreateSurface(&ddsd, &lpDDSZBuffer, NULL);
if (hresult != DD_OK)
{
Utils_Log(LOG_ERROR, "CreateSurface(lpDDSZBuffer)");
return FALSE;
}
// Back Surface에 Z-buffer를 붙인다.
hresult = lpDDSBack->AddAttachedSurface(lpDDSZBuffer);
if (hresult != DD_OK)
{
Utils_Log(LOG_ERROR, "lpDDSBack->AddAttachedSurface");
return FALSE;
}
// Direct3D Device 생성
hresult = lpD3D->CreateDevice(lpD3DDeviceDesc->guid,
lpDDSBack,
&lpD3DDevice,
NULL);
if (hresult != D3D_OK)
{
Utils_Log(LOG_ERROR, "lpD3D->CreateDevice");
return FALSE;
}
// Viewport Size Settings
D3DRect.x1 = 0;
D3DRect.y1 = 0;
D3DRect.x2 = w;
D3DRect.y2 = h;
smScreenWidth = Width;
smScreenHeight = Height;
return CreateViewport();
}
// Viewport Generation
BOOL RenderDevice::CreateViewport()
{
// Viewport 생성
HRESULT hresult = lpD3D->CreateViewport(&lpD3DViewport, NULL);
if (hresult != D3D_OK)
{
Utils_Log(LOG_ERROR, "Failed to set CreateViewport()");
return FALSE;
}
// Direct3D Device 에 Viewport 추가
hresult = lpD3DDevice->AddViewport(lpD3DViewport);
if (hresult != D3D_OK)
{
Utils_Log(LOG_ERROR, "Failed to set AddViewport()");
return FALSE;
}
D3DVIEWPORT2 Viewdata;
ZeroMemory(&Viewdata, sizeof(D3DVIEWPORT2));
Viewdata.dwSize = sizeof(Viewdata);
Viewdata.dwX = D3DRect.x1;
Viewdata.dwY = D3DRect.y1;
Viewdata.dwWidth = D3DRect.x2;
Viewdata.dwHeight = D3DRect.y2;
Viewdata.dvClipWidth = 2.0f;
Viewdata.dvClipHeight = (float)(D3DRect.y2 * 2.0 / D3DRect.x2);
Viewdata.dvClipX = -1.0f;
Viewdata.dvClipY = Viewdata.dvClipHeight / 2.0f;
Viewdata.dvMinZ = 0.0f;
Viewdata.dvMaxZ = 1.0f;
//viewport.dvMinZ = 0.0f;
//viewport.dvMaxZ = 1.0f;
// lpD3DViewport2 설정
hresult = lpD3DViewport->SetViewport2(&Viewdata);
if (hresult != D3D_OK)
{
Utils_Log(LOG_ERROR, "Failed to set SetViewport2()");
return FALSE;
}
// 현제 Viewport를 lpD3DViewport2로 설정
hresult = lpD3DDevice->SetCurrentViewport(lpD3DViewport);
if (hresult != D3D_OK)
{
Utils_Log(LOG_ERROR, "Failed to set SetCurrentViewport()");
return FALSE;
}
//######################################################################################
//작 성 자 : 오 영 석
if (g_IsCreateFilterEffect)
CreateNewRenderTarget();
//######################################################################################
return TRUE;
}
// Initialze the Render
void RenderDevice::InitRender()
{
// Turn on Z-buffering
lpD3DDevice->SetRenderState(D3DRENDERSTATE_ZENABLE, TRUE);
lpD3DDevice->SetRenderState(D3DRENDERSTATE_ZWRITEENABLE, TRUE);
lpD3DDevice->SetRenderState(D3DRENDERSTATE_ZFUNC, D3DCMP_LESSEQUAL);
//lpD3DDevice->SetRenderState( D3DRENDERSTATE_ZENABLE, D3DZB_USEW );//TRUE );
// null out the texture handle
lpD3DDevice->SetRenderState(D3DRENDERSTATE_TEXTUREHANDLE, 0);
// turn on dithering
lpD3DDevice->SetRenderState(D3DRENDERSTATE_DITHERENABLE, TRUE);
lpD3DDevice->SetRenderState(D3DRENDERSTATE_TEXTUREADDRESS, D3DTADDRESS_WRAP);
lpD3DDevice->SetRenderState(D3DRENDERSTATE_TEXTUREPERSPECTIVE, TRUE);
// D3DFILTER_LINEAR
lpD3DDevice->SetRenderState(D3DRENDERSTATE_TEXTUREMAG, D3DFILTER_LINEAR);
lpD3DDevice->SetRenderState(D3DRENDERSTATE_TEXTUREMIN, D3DFILTER_LINEAR);
lpD3DDevice->SetRenderState(D3DRENDERSTATE_SPECULARENABLE, TRUE);
lpD3DDevice->SetRenderState(D3DRENDERSTATE_COLORKEYENABLE, FALSE);
lpD3DDevice->SetRenderState(D3DRENDERSTATE_TEXTUREMAPBLEND, D3DTBLEND_MODULATE);
lpD3DDevice->SetRenderState(D3DRENDERSTATE_ALPHABLENDENABLE, TRUE);
lpD3DDevice->SetRenderState(D3DRENDERSTATE_DESTBLEND, D3DBLEND_INVSRCALPHA);
lpD3DDevice->SetRenderState(D3DRENDERSTATE_SRCBLEND, D3DBLEND_SRCALPHA);
smRender.AlphaTestDepth = 60;
smRender.dwMatDispMask = sMATS_SCRIPT_NOTVIEW;
smRender.DeviceRendMode = TRUE;
smRender.ZWriteAuto = FALSE;
}
// Page-flipping
int RenderDevice::Flip()
{
//동영상 재생
if (ParkPlaying && (smFlipCount & 1) == 0)
{
updateFrameWin_Video();
return TRUE;
}
if (WindowMode || (hFocusWnd && (smFlipCount & 1) == 0))
{
updateFrameWin();
return TRUE;
}
HRESULT hresult = lpDDSPrimary->Flip(NULL, DDFLIP_WAIT);
if (hresult == DDERR_SURFACELOST)
{
lpDDSPrimary->Restore();
return FALSE;
}
smFlipCount++; //플리핑 카운터
return TRUE;
}
void RenderDevice::updateFrameWin_Video()
{
RECT rcRect;
RECT rcRect1;
RECT rcRect2;
RECT rcRect3;
RECT rcRect4;
RECT destRect;
RECT destRect1;
RECT destRect2;
RECT destRect3;
RECT destRect4;
HRESULT ddrval;
POINT pt;
GetClientRect(hwnd, &destRect);
pt.x = pt.y = 0;
ClientToScreen(hwnd, &pt);
OffsetRect(&destRect, pt.x, pt.y);
//////////////////////////////////////////////////////////////
// 두개의 페이지 전환이 이루어 지는 곳
// Blt() 함수가 실제로 비트맵을 그리는 함수
rcRect.left = 0;
rcRect.right = smScreenWidth;
rcRect.top = 0;
rcRect.bottom = smScreenHeight;
destRect1.left = 0;
destRect1.right = smScreenWidth;
destRect1.top = 0;
destRect1.bottom = ParkPlayRect.top;
destRect2.left = 0;
destRect2.right = ParkPlayRect.left;
destRect2.top = ParkPlayRect.top;
destRect2.bottom = ParkPlayRect.bottom;
destRect3.left = ParkPlayRect.right;
destRect3.right = smScreenWidth;
destRect3.top = ParkPlayRect.top;
destRect3.bottom = ParkPlayRect.bottom;
destRect4.left = 0;
destRect4.right = smScreenWidth;
destRect4.top = ParkPlayRect.bottom;
destRect4.bottom = smScreenHeight;
rcRect1.left = 0;
rcRect1.right = smScreenWidth;
rcRect1.top = 0;
rcRect1.bottom = ParkPlayRect.top;
rcRect2.left = 0;
rcRect2.right = ParkPlayRect.left;
rcRect2.top = ParkPlayRect.top;
rcRect2.bottom = ParkPlayRect.bottom;
rcRect3.left = ParkPlayRect.right;
rcRect3.right = smScreenWidth;
rcRect3.top = ParkPlayRect.top;
rcRect3.bottom = ParkPlayRect.bottom;
rcRect4.left = 0;
rcRect4.right = smScreenWidth;
rcRect4.top = ParkPlayRect.bottom;
rcRect4.bottom = smScreenHeight;
while (1)
{
ddrval = Blt(lpDDSPrimary, &destRect1, lpDDSBack, &rcRect1, NULL, NULL);
ddrval = Blt(lpDDSPrimary, &destRect2, lpDDSBack, &rcRect2, NULL, NULL);
ddrval = Blt(lpDDSPrimary, &destRect3, lpDDSBack, &rcRect3, NULL, NULL);
ddrval = Blt(lpDDSPrimary, &destRect4, lpDDSBack, &rcRect4, NULL, NULL);
if (ddrval == DD_OK) break;
if (ddrval == DDERR_SURFACELOST)
{
// ddrval = restoreAll();
if (ddrval != DD_OK)
return;
}
if (ddrval != DDERR_WASSTILLDRAWING)
break;
}
}
void RenderDevice::updateFrameWin()
{
RECT rcRect;
RECT destRect;
HRESULT ddrval;
POINT pt;
GetClientRect(hwnd, &destRect);
pt.x = pt.y = 0;
ClientToScreen(hwnd, &pt);
OffsetRect(&destRect, pt.x, pt.y);
//////////////////////////////////////////////////////////////
// Which consists of two pages where conversions
// Blt() function is the function actually draws bitmaps
rcRect.left = 0;
rcRect.right = smScreenWidth;
rcRect.top = 0;
rcRect.bottom = smScreenHeight;
while (1)
{
ddrval = Blt(lpDDSPrimary, &destRect, lpDDSBack, &rcRect, NULL, NULL);
if (ddrval == DD_OK)
break;
if (ddrval == DDERR_SURFACELOST)
{
if (ddrval != DD_OK)
return;
}
if (ddrval != DDERR_WASSTILLDRAWING)
break;
}
}
void RenderDevice::ClearViewport(DWORD flags)
{
lpD3DViewport->Clear2(1UL, &renderDevice.D3DRect, flags, smBackColor, 1, 0L);
}
BOOL RenderDevice::IsDevice()
{
if (lpD3DDevice)
return TRUE;
return FALSE;
}
void RenderDevice::SetRenderState(_D3DRENDERSTATETYPE stateType, DWORD value)
{
lpD3DDevice->SetRenderState(stateType, value);
}
void RenderDevice::SetTextureStageState(DWORD stage, D3DTEXTURESTAGESTATETYPE type, DWORD value)
{
lpD3DDevice->SetTextureStageState(stage, type, value);
}
HRESULT RenderDevice::EnumTextureFormats(LPD3DENUMPIXELFORMATSCALLBACK Textures, LPVOID TexturePixelFormat)
{
return lpD3DDevice->EnumTextureFormats(Textures, TexturePixelFormat);
}
HRESULT RenderDevice::SetTransform(D3DTRANSFORMSTATETYPE type, LPD3DMATRIX matrix)
{
return lpD3DDevice->SetTransform(type, matrix);
}
HRESULT RenderDevice::SetTexture(DWORD sampler, DRZTEXTURE2 texture)
{
return lpD3DDevice->SetTexture(sampler, texture);
}
HRESULT RenderDevice::SetRenderTarget(DIRECTDRAWSURFACE pRenderTarget, DWORD RenderTargetIndex)
{
return lpD3DDevice->SetRenderTarget(pRenderTarget, RenderTargetIndex);
}
HRESULT RenderDevice::GetRenderTarget(DIRECTDRAWSURFACE* renderTarget)
{
return lpD3DDevice->GetRenderTarget(renderTarget);
}
HRESULT RenderDevice::DrawPrimitive(D3DPRIMITIVETYPE PrimitiveType, DWORD VertexTypeDesc, LPVOID Vertices, DWORD VertexCount, DWORD Flags)
{
return lpD3DDevice->DrawPrimitive(PrimitiveType, VertexTypeDesc, Vertices, VertexCount, Flags);
}
HRESULT RenderDevice::Blt(DIRECTDRAWSURFACE targetSurface, LPRECT lpDestRect, DIRECTDRAWSURFACE srcSurface, LPRECT srcRect, DWORD dwFlags, LPDDBLTFX lpDDBltFx)
{
HRESULT hr = targetSurface->Blt(lpDestRect, srcSurface, srcRect, dwFlags, lpDDBltFx);
if (FAILED(hr))
Utils_Log(LOG_ERROR, "DirectX Error - Blt() failed");
return hr;
}
HRESULT RenderDevice::BltFast(DIRECTDRAWSURFACE targetSurface, DWORD dwX, DWORD dwY, DIRECTDRAWSURFACE srcSurface, LPRECT srcRect, DWORD dwFlags)
{
HRESULT hr = targetSurface->BltFast(dwX, dwY, srcSurface, srcRect, dwFlags);
/*
if (FAILED(hr))
Utils_Log(LOG_ERROR, "DirectX Error - BltFast() failed");
*/
return hr;
}
HRESULT RenderDevice::CreateSurface(LPDDSURFACEDESC2 SurfaceDesc, DIRECTDRAWSURFACE* surface, IUnknown* UnkPointer)
{
return lpDD->CreateSurface(SurfaceDesc, surface, UnkPointer);
}
void RenderDevice::BeginScene()
{
lpD3DDevice->BeginScene();
}
void RenderDevice::EndScene()
{
lpD3DDevice->EndScene();
}
|
#include<iostream>
#include<string>
using namespace std;
// string的查找和替换
//字符串比较
//单个字符的存取
//查找
void test01()
{
string str1 = "abcdedefg";
//find()函数
int pos = str1.find("de");//查找函数,存在返回位置下标,不存在返回-1
if(pos == -1)
{
cout<<"未找到"<<endl;
}
else{
cout<<pos<<endl;
}
//rfind()函数
pos = str1.rfind("de");
cout<<pos<<endl;
//find()是从左往右找,rfind 是从右往左找
}
//替换
void test02()
{
string str1 = "abcdedefg";
//将从pos开始的n个字符替换为字符串str
str1.replace(1,3,"1111");
cout<<str1<<endl;
}
//字符串比较(ascll码) campare() 主要用来比较两个字符串是否相等
void test03()
{
string str1 = "hellow";
string str2 = "hellow";
string str3 = "aellow";
string str4 = "zellow";
if(str1.compare(str2)==0)
{
cout<<str1.compare(str2)<<" str1 等于 str2"<<endl;
}
if(str1.compare(str3) > 0)
{
cout<<str1.compare(str3)<<" str1 大于 str3"<<endl;
}
if(str1.compare(str4) < 0)
{
cout<<str1.compare(str4)<<" str1 小于 str4"<<endl;
}
}
//单个字符的存取
void test04()
{
string str1 = "hellow";
cout<<"str1.size(): "<<str1.size()<<endl;//size()函数返回字符串的长度
// cout<<str1<<endl;
// 1.通过[]访问单个字符
for(int i = 0; i < str1.size();i++)
{
cout<<str1[i]<<" ";
}
cout<<endl;
//2.通过at方式访问单个字符
for(int i = 0;i < str1.size();i++)
{
cout<<str1.at(i)<<" ";
}
cout<<endl;
//3.修改单个字符
str1[0] = 'a';
str1.at(1)='b';
cout<<str1<<endl;
}
int main()
{
cout<<"--------------------test01()-----------------"<<endl;
test01();
cout<<"--------------------test02()-----------------"<<endl;
test02();
cout<<"--------------------test03()-----------------"<<endl;
test03();
cout<<"--------------------test04()-----------------"<<endl;
test04();
return 0;
}
|
#include "plot/root_draw.h"
#include "base/std_ext/memory.h"
#include "base/std_ext/string.h"
#include "base/Logger.h"
#include "TH1D.h"
#include "TH2D.h"
#include "TObject.h"
#include "TNamed.h"
#include "TCanvas.h"
#include "TROOT.h"
#include "THStack.h"
#include "TVirtualPad.h"
#include <iostream>
#include <sstream>
#include <iomanip>
#include <algorithm>
using namespace ant;
using namespace std;
const padoption padoption::Legend = [] (TVirtualPad* p) {p->BuildLegend();};
const padoption padoption::LogX = [] (TVirtualPad* p) {p->SetLogx();};
const padoption padoption::LogY = [] (TVirtualPad* p) {p->SetLogy();};
const padoption padoption::LogZ = [] (TVirtualPad* p) {p->SetLogz();};
const padoption padoption::MakeSquare = [] (TVirtualPad* p) {
auto min_size = std::min(p->GetWh(), p->GetWw());
p->SetCanvasSize(min_size, min_size);
};
unsigned int canvas::num = 0;
const endcanvas ant::endc = endcanvas();
const endrow ant::endr = endrow();
const samepad_t ant::samepad = samepad_t();
canvas::canvas(const string& title) :
name(), pads(), current_drawoption(), global_padoptions()
{
CreateTCanvas(title);
}
canvas::~canvas()
{
if(!endcanvas_called && !pads.empty())
LOG(WARNING) << "ant::canvas went out of scope without being drawn. Forgot '<< ant::endc'?";
}
TCanvas* canvas::CreateTCanvas(const string& title)
{
name = std_ext::formatter() << "_canvas_" << setfill('0') << setw(3) << num++;
return new TCanvas(name.c_str(), title.c_str());
}
TCanvas* canvas::FindTCanvas()
{
TObject* o = gROOT->FindObjectAny(name.c_str());
TCanvas* c = dynamic_cast<TCanvas*>(o);
if(c)
return c;
else
return CreateTCanvas();
}
void canvas::DrawObjs(TCanvas* c, unsigned cols, unsigned rows)
{
c->Divide(cols,rows);
int pad=1;
unsigned ninrow =0;
for(const pad_t& p : pads) {
if(p.DrawableItems.empty()) {
pad += (cols-ninrow);
ninrow = 0;
} else {
TVirtualPad* vpad = c->cd(pad);
// draw the objects
for(const auto& item : p.DrawableItems) {
item.Drawable->Draw(item.Option);
}
// set pad options
for(const auto& option : p.PadOptions) {
(*option)(vpad);
}
++pad;
}
ninrow++;
}
}
void canvas::cd()
{
TCanvas* c = FindTCanvas();
if(c) {
c->cd();
}
}
void canvas::AddDrawable(std::unique_ptr<root_drawable_traits> drawable)
{
onetime_padoptions.insert(onetime_padoptions.end(),
global_padoptions.begin(),
global_padoptions.end());
string drawoption = current_drawoption;
if(!addobject || pads.empty()) {
pads.emplace_back(onetime_padoptions);
}
else {
drawoption += "same";
}
pads.back().DrawableItems.emplace_back(move(drawable), drawoption);
onetime_padoptions.clear();
addobject = false;
}
canvas& canvas::operator<<(root_drawable_traits& drawable)
{
using container_t = drawable_container<root_drawable_traits*>;
AddDrawable(std_ext::make_unique<container_t>(addressof(drawable)));
return *this;
}
canvas& canvas::operator<<(TObject* hist)
{
using container_t = drawable_container<TObject*>;
AddDrawable(std_ext::make_unique<container_t>(hist));
return *this;
}
canvas& canvas::operator<<(const endrow&)
{
// just an empty pad indicates the end of the row
pads.emplace_back();
automode = false;
return *this;
}
canvas& canvas::operator<<(const samepad_t&)
{
addobject = true;
return *this;
}
canvas& canvas::operator<<(const drawoption& c)
{
current_drawoption = c.Option();
return *this;
}
canvas&canvas::operator<<(const padoption& c)
{
onetime_padoptions.emplace_back(std::addressof(c));
return *this;
}
canvas& canvas::operator<<(const padoption::enable& c)
{
global_padoptions.emplace_back(c.Modifier);
return *this;
}
canvas& canvas::operator<<(const padoption::disable& c)
{
global_padoptions.remove(c.Modifier);
return *this;
}
canvas& canvas::operator<<(const endcanvas&)
{
if(pads.empty()) {
return *this;
}
endcanvas_called = true;
TCanvas* c = FindTCanvas();
if(c) {
unsigned cols =0;
unsigned rows =0;
if(automode) {
cols = ceil(sqrt(pads.size()));
rows = ceil((double)pads.size()/(double)cols);
} else {
unsigned ccols=0;
for(const auto& o : pads) {
if(o.DrawableItems.empty()) {
cols = max(ccols,cols);
ccols=0;
rows++;
} else {
ccols++;
}
}
}
DrawObjs(c,cols,rows);
}
return *this;
}
canvas& canvas::operator>>(const string& filename)
{
TCanvas* c = FindTCanvas();
if(c) {
c->SaveAs(filename.c_str());
}
return *this;
}
const std::vector<Color_t> ColorPalette::Colors = {kRed, kGreen+1, kBlue, kYellow+1, kMagenta, kCyan, kOrange, kPink+9, kSpring+10, kGray};
|
/*
2014年4月11日21:03:12
二维数组整体向右缩进是 Tab键,向左缩进shift+Tab
怎样输出二维数组
*printf哪里%d加空格,输出页面也有空格
*/
# include <stdio.h>
int main(void)
{
int a[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
int i, j;
for(i=0; i<3; ++i)
{
for(j=0;j<4;++j)
printf(" %d", a[i][j]);
printf("\n");
}
return 0;
}
|
/*
Name: Mohit Kishorbhai Sheladiya
Student ID: 117979203
Student Email: mksheladiya@myseneca.ca
Date: 21/02/05
*/
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <iomanip>
#include <cstring>
#include "Food.h"
using namespace std;
namespace sdds {
void Item::setName(const char* name) {
strncpy(m_itemName, name, 30);
m_itemName[30] = '\0';
}
void Item::setEmpty() {
m_cal = 0.;
m_itemName[0] = '\0';
}
void Item::set(const char* name, int cal, int meal) {
setEmpty();
if (name != nullptr && cal > 0 && cal <= 3000) {
setName(name);
m_cal = cal;
m_meal = meal;
}
}
int Item::cal()const {
return m_cal;
}
bool Item::isValid()const {
if (m_cal > 0 && m_cal <= 3000 && m_itemName != NULL && m_meal > 0 && m_meal < 5) {
return true;
}
else
return false;
}
void Item::display()const {
bool a = isValid();
if (a) {
cout << "| ";
cout << left << setfill('.') << setw(30) << m_itemName;
cout << " | ";
cout.setf(ios::right);
cout.width(4);
cout << fixed << setfill(' ');
cout << m_cal;
cout << " | ";
if (m_meal == 1) {
cout << "Breakfast ";
} else if (m_meal == 2) {
cout << "Lunch ";
} else if (m_meal == 3) {
cout << "Dinner ";
} else if (m_meal == 4) {
cout << "Snack ";
}
else {
cout << " ";
}
cout << " |";
cout << endl;
}
else {
cout << "| xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx | xxxx | xxxxxxxxxx |";
cout << endl;
}
}
}
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
int edges;
cin>>edges;
int adj[n][n];
int arr[n];
for(int i=0;i<n;i++)
{
arr[i]=0;
for(int j=0;j<n;j++)
{
adj[i][j]=0;
}
}
for(int i=0;i<edges;i++)
{
int x;
int y;
cin>>x;
cin>>y;
adj[x][y]=1;
adj[y][x]=1;
}
int src;
cin>>src;
//DFS TRAVERSAL IN UNDIRECTED GRAPH....
cout<<"DFS TRAVERSAL IN UNDIRECTED GRAPH...."<<endl;
stack<int> s;
s.push(src);
arr[src]=1;
while(s.size()!=0)
{
cout<<s.top();
int x=s.top();
s.pop();int grv=0;
for(int i=n-1;i>-1;i--)
{
if(adj[x][i]==1&&arr[i]==0)
{
s.push(i);
arr[i]+=1;
}
else if(adj[x][i]==1&&arr[i]==1)
{
cout<<" "<<i<<" ";
cout<<"cycle is present"<<endl;
grv+=1;
break;
}
}
for(int i=0;i<n;i++)//FOR DETECTION OF CYCLE....
{
adj[x][i]=0;
adj[i][x]=0;
}
if(grv!=0)
{
break;
}
}
cout<<endl;
for(int i=0;i<n;i++)
{
arr[i]=0;
}
//BFS TRAVERSAL IN UNDIRECTED GRAPH....
cout<<"BFS TRAVERSAL IN UNDIRECTED GRAPH...."<<endl;
for(int i=0;i<edges;i++)
{
int x;
int y;
cin>>x;
cin>>y;
adj[x][y]=1;
adj[y][x]=1;
}
queue<int> q;
q.push(src);
arr[src]=2;
while(q.size()!=0)
{
cout<<q.front();
for(int i=0;i<n;i++)
{
if(adj[q.front()][i]==1&&arr[i]==0)
{
q.push(i);
arr[i]=1;
}
}
q.pop();
}
}
|
///////////////////////////////////////////////////////////////////
//Copyright 2019-2020 Perekupenko Stanislav. All Rights Reserved.//
//@Author Perekupenko Stanislav (stanislavperekupenko@gmail.com) //
///////////////////////////////////////////////////////////////////
#include "CPPW_Details.h"
#include "Components/ScrollBox.h"
void UCPPW_Details::SetDetails(const TArray<FMaterialStruct> & _materialVariants, ACPP_SelectableActor* _actor)
{
ScrollBox->ClearChildren();
SetVisibility(ESlateVisibility::Hidden);
if (MaterialButtonWidgetClass)
{
for (int i=0 ;i< _materialVariants.Num();i++)
{
UCPPW_MaterialButton* newWidget = CreateWidget<UCPPW_MaterialButton>(this, MaterialButtonWidgetClass);
newWidget->SetButtonDetails(_materialVariants[i], _actor);
ScrollBox->AddChild(newWidget);
}
}
}
|
#pragma once
#include "Vertex2D.h"
#include "Vertex3D_NoTex2.h"
#define _USE_MATH_DEFINES
#include <math.h>
class Vertex3Ds
{
public:
Vertex3Ds();
Vertex3Ds(const float _x, const float _y, const float _z);
void Set(const float a, const float b, const float c);
void SetZero();
Vertex3Ds operator+(const Vertex3Ds& v) const;
Vertex3Ds operator-(const Vertex3Ds& v) const;
Vertex3Ds operator-() const;
Vertex3Ds& operator+=(const Vertex3Ds& v);
Vertex3Ds& operator-=(const Vertex3Ds& v);
Vertex3Ds operator*(const float s) const;
friend Vertex3Ds operator*(const float s, const Vertex3Ds& v)
{
return Vertex3Ds(s * v.x, s * v.y, s * v.z);
}
Vertex3Ds operator/(const float s) const;
Vertex3Ds& operator*=(const float s);
Vertex3Ds& operator/=(const float s);
void Normalize();
void Normalize(const float scalar);
void NormalizeSafe();
float Dot(const Vertex3Ds& pv) const;
float Dot(const Vertex3D_NoTex2& pv) const;
float LengthSquared() const;
float Length() const;
bool IsZero() const;
Vertex2D& xy();
const Vertex2D& xy() const;
float x;
float y;
float z;
};
void RotateAround(const Vertex3Ds& pvAxis, Vertex3D_NoTex2* const pvPoint, int count, float angle);
void RotateAround(const Vertex3Ds& pvAxis, Vertex3Ds* const pvPoint, int count, float angle);
Vertex3Ds RotateAround(const Vertex3Ds& pvAxis, const Vertex2D& pvPoint, float angle);
inline Vertex3Ds CrossProduct(const Vertex3Ds& pv1, const Vertex3Ds& pv2)
{
return Vertex3Ds(pv1.y * pv2.z - pv1.z * pv2.y,
pv1.z * pv2.x - pv1.x * pv2.z,
pv1.x * pv2.y - pv1.y * pv2.x);
}
////////////////////////////////////////////////////////////////////////////////
//
// license:GPLv3+
// Ported at: VisualPinball.Engine/Math/Vertex3D.cs
//
inline Vertex3Ds GetRotatedAxis(const float angle, const Vertex3Ds& axis, const Vertex3Ds& temp)
{
Vertex3Ds u = axis;
u.Normalize();
const float sinAngle = sinf((float)(M_PI / 180.0) * angle);
const float cosAngle = cosf((float)(M_PI / 180.0) * angle);
const float oneMinusCosAngle = 1.0f - cosAngle;
Vertex3Ds rotMatrixRow0, rotMatrixRow1, rotMatrixRow2;
rotMatrixRow0.x = u.x * u.x + cosAngle * (1.f - u.x * u.x);
rotMatrixRow0.y = u.x * u.y * oneMinusCosAngle - sinAngle * u.z;
rotMatrixRow0.z = u.x * u.z * oneMinusCosAngle + sinAngle * u.y;
rotMatrixRow1.x = u.x * u.y * oneMinusCosAngle + sinAngle * u.z;
rotMatrixRow1.y = u.y * u.y + cosAngle * (1.f - u.y * u.y);
rotMatrixRow1.z = u.y * u.z * oneMinusCosAngle - sinAngle * u.x;
rotMatrixRow2.x = u.x * u.z * oneMinusCosAngle - sinAngle * u.y;
rotMatrixRow2.y = u.y * u.z * oneMinusCosAngle + sinAngle * u.x;
rotMatrixRow2.z = u.z * u.z + cosAngle * (1.f - u.z * u.z);
return Vertex3Ds(temp.Dot(rotMatrixRow0), temp.Dot(rotMatrixRow1), temp.Dot(rotMatrixRow2));
}
//
// end of license:GPLv3+, back to 'old MAME'-like
//
inline Vertex3Ds sphere_sample(const float u, const float v)
{
const float phi = v * (float)(2.0 * M_PI);
const float z = 1.0f - (u + u);
const float r = sqrtf(1.0f - z * z);
return Vertex3Ds(cosf(phi) * r, z, sinf(phi) * r);
}
inline Vertex3Ds hemisphere_sample(const float u, const float v)
{
const float phi = v * (float)(2.0 * M_PI);
const float cosTheta = 1.0f - u;
const float sinTheta = sqrtf(1.0f - cosTheta * cosTheta);
return Vertex3Ds(cosf(phi) * sinTheta, cosTheta, sinf(phi) * sinTheta);
}
inline Vertex3Ds cos_hemisphere_sample(const float u, const float v)
{
const float phi = v * (float)(2.0 * M_PI);
const float cosTheta = sqrtf(1.0f - u);
const float sinTheta = sqrtf(u);
return Vertex3Ds(cosf(phi) * sinTheta, cosTheta, sinf(phi) * sinTheta);
}
inline Vertex3Ds rotate_to_vector_upper(const Vertex3Ds& vec, const Vertex3Ds& normal)
{
if (normal.y > -0.99999f)
{
const float h = 1.0f / (1.0f + normal.y);
const float hz = h * normal.z;
const float hzx = hz * normal.x;
return Vertex3Ds(
vec.x * (normal.y + hz * normal.z) + vec.y * normal.x - vec.z * hzx,
vec.y * normal.y - vec.x * normal.x - vec.z * normal.z,
vec.y * normal.z - vec.x * hzx + vec.z * (normal.y + h * normal.x * normal.x));
}
return -vec;
}
inline Vertex3Ds rotate_to_vector_full(const Vertex3Ds& vec, const Vertex3Ds& normal)
{
if (fabsf(normal.y) <= 0.99999f)
{
const float xx = normal.x * normal.x;
const float zz = normal.z * normal.z;
const float h = (1.0f - normal.y) / (xx + zz);
const float hzx = h * normal.z * normal.x;
return Vertex3Ds(
vec.x * (normal.y + h * zz) + vec.y * normal.x - vec.z * hzx,
vec.y * normal.y - vec.x * normal.x - vec.z * normal.z,
vec.y * normal.z - vec.x * hzx + vec.z * (normal.y + h * xx));
}
return (normal.y < 0.0f) ? -vec : vec;
}
|
// $Id: Identifier.h,v 1.9 2013/02/09 19:00:33 david Exp $ -*- c++ -*-
#ifndef __CDK8_NODE_EXPRESSION_IDENTIFIER_H__
#define __CDK8_NODE_EXPRESSION_IDENTIFIER_H__
#include <cdk/nodes/expressions/Simple.h>
#include <string>
#include "SemanticProcessor.h"
namespace cdk {
namespace node {
namespace expression {
/**
* Class for describing syntactic tree leaves for holding identifier
* values.
*/
class Identifier: public Simple<std::string> {
public:
inline Identifier(int lineno, const char *s) :
Simple<std::string> (lineno, s) {
}
inline Identifier(int lineno, const std::string &s) :
Simple<std::string> (lineno, s) {
}
inline Identifier(int lineno, const std::string *s) :
Simple<std::string> (lineno, *s) {
}
/**
* @return the name of the node's class
*/
const char *name() const {
return "Identifier";
}
/**
* @param sp semantic processor visitor
* @param level syntactic tree level
*/
virtual void accept(SemanticProcessor *sp, int level) {
sp->processIdentifier(this, level);
}
};
} // expression
} // node
} // cdk
#endif
// $Log: Identifier.h,v $
// Revision 1.9 2013/02/09 19:00:33 david
// First CDK8 commit. Major code simplification.
// Starting C++11 implementation.
//
// Revision 1.8 2012/04/10 19:01:04 david
// Removed initialization-dependent static members in factories.
// Handling of ProgramNodes is now better encapsulated by visitors (not done
// by evaluators, as before). Major cleanup (comments).
//
// Revision 1.7 2012/03/06 15:07:45 david
// Added subtype to ExpressionType. This allows for more expressiveness in
// type description.
//
|
#include<stdio.h>
#include<stdlib.h>
#include<string>
#define NO_OF_CHAR 256
int *getCharCount(char *);
char *removeDirtyString(char *,char *);
int main(){
char mask_str[]="mask";
char str[]="geeksforgeeks";
printf("%s",removeDirtyString(str,mask_str));
getchar();
return 0;
}
char *removeDirtyString(char *str,char *mask_str){
int *count= getCharCount(mask_str);
int ip_idx=0,res_idx=0;
char temp;
while(*(str+ip_idx)){
temp=*(str+ip_idx);
if(count[temp]==0){
*(str+res_idx)= *(str+ip_idx);
res_idx++;
}
ip_idx;
}
*(str+res_idx)='\0';
return str;
}
int *getCharCount(char *str){
int *count =(int *)calloc(sizeof(int),NO_OF_CHAR);
int i;
for(i=0;*(str+i);i++)
count[*(str+i)]++;
return count;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.