blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
aa1205f35021924e57eb9044121e3e8cf4fa2b13
8c90e0ffb2819653c566aa7894e73b2726fb3640
/mekai/13_class/width.cpp
90b5cfc558374982bd47b4555ad2773743973bd6
[]
no_license
Tetta8/CPP_test
f842390ad60a0aeb259240910d12d1b273ce58ed
a4692aae32bbc6bfce2af61567a9fa0575e47fe0
refs/heads/master
2021-01-04T17:20:09.526885
2020-09-17T05:09:19
2020-09-17T05:09:19
240,681,912
0
0
null
null
null
null
UTF-8
C++
false
false
289
cpp
#include <iostream> using namespace std; int main(){ char str[10]; cout << "文字列を10文字未満で入力せよ:"; cin.width(10); cin >> str; cout << "str = "; cout.width(12); cout << str << endl; cout << "str = " << str << endl; }
[ "tester.ta8@gmail.com" ]
tester.ta8@gmail.com
18dc6b9c00913595e3b9198c86b3c1ded5981ed0
274e1169a03062140871e4fddaf4836e30cce503
/src/CursATE/Screen/help.hpp
0d210d85a70188d13874778bfd626cab002dc886
[ "BSD-2-Clause" ]
permissive
el-bart/LogATE
38df676a9874c42d9ec862cf3090e0e31bc134f2
88569417c0758318a049205bb69f3ecee4d13a32
refs/heads/master
2023-08-29T14:45:26.924602
2023-07-25T17:55:13
2023-07-25T17:55:13
152,469,962
3
3
null
null
null
null
UTF-8
C++
false
false
57
hpp
#pragma once namespace CursATE::Screen { void help(); }
[ "bartosz.szurgot@qiagen.com" ]
bartosz.szurgot@qiagen.com
db4842ca667c42120e5124db7818a9864bb347d7
9e898b8b8033dd02a499e1e8f7801bbae34ba35c
/FM-Index/FMIndex.h
60fb9c7f82562bec21c0d3b9afdd7641d4382645
[]
no_license
KoyanoBunsho/FM-Index
f25dd096d578f5fb1802a68c8235932597a2de06
7a5177fa33dd07728d4e1dcb5f4b6d4bb11ec675
refs/heads/master
2022-02-19T20:23:40.720555
2019-08-20T11:21:05
2019-08-20T11:21:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,179
h
#ifndef __FM_Index__FMIndex__ #define __FM_Index__FMIndex__ #include <map> #include <list> #include <iterator> #include "WaveletTree.h" class FMIndex { public: class const_iterator : public std::iterator<std::forward_iterator_tag, char> { private: const std::unique_ptr<WaveletTree> & BWT_or_BWTr; const size_t end_idx; const std::map<char, size_t> & C; size_t i; // A row index in the hypothetical matrix whose last column is BWT_or_BWTr. char c; // The character at the end of the row in the hypothetical matrix (i.e., in BWT_or_BWTr). public: const_iterator(const std::unique_ptr<WaveletTree> & BWT_or_BWTr, const size_t end_idx, const std::map<char, size_t> & C, const size_t i); const_iterator(const const_iterator & it) : BWT_or_BWTr(it.BWT_or_BWTr), end_idx(it.end_idx), C(it.C), i(it.i), c(it.c) { } //const_iterator & operator=(const const_iterator & it); bool operator==(const const_iterator & it); bool operator!=(const const_iterator & it); const_iterator & operator++(void); // Prefix const_iterator operator++(int); // Postfix char operator*(void) const; //char * operator->(void) const; bool at_end(void) const; }; typedef const_iterator const_reverse_iterator; // What is type-safe way of doing this? private: std::unique_ptr<WaveletTree> BWT_as_wt, BWTr_as_wt; size_t BWT_end_idx, BWTr_end_idx; std::map<char, size_t> C; static size_t BWT_idx_from_row_idx(const size_t i, const size_t end_idx); template <typename ForwardIterator> std::pair<size_t, size_t> backward_search(ForwardIterator i_pattern, ForwardIterator i_pattern_end, const std::unique_ptr<WaveletTree> & BWT_or_BWTr, const size_t end_idx) const; void msd_sort(size_t * fr_perm, const size_t len, const_iterator ** text_iters, const size_t depth_left) const; void populate_C(void); public: FMIndex(const std::string & s); FMIndex(std::istreambuf_iterator<char> serial_data); size_t findn(const std::string & pattern) const; size_t find(std::list<std::pair<const_iterator, const_reverse_iterator>> & matches, const std::string & pattern, const size_t max_context = 100) const; std::list<std::string> find_lines(const std::string & pattern, const char new_line_char = '\n', const size_t max_context = 100) const; size_t size(void) const; const_iterator begin(void) const; void serialize(std::ostreambuf_iterator<char> serial_data) const; void serialize_to_file(const std::string & filename) const; static FMIndex * new_from_serialized_file(const std::string & filename); }; #endif /* defined(__FM_Index__FMIndex__) */
[ "olivernash@Olivers-MacBook-Pro.local" ]
olivernash@Olivers-MacBook-Pro.local
de50b4a6bb27be2d0ca8aff5f5d7c574eeed7e71
e80972c3d72814438e7f2564fbd8931d1eb773ba
/Section01/Nick/Assignment 2 - Steering/SwitchPathfindingMessage.h
3ff8a55ca58afdd23c2e66c81588e3c4f8c21fae
[]
no_license
dacuster/GameAI
9b8a8bc75e34142612d0ddefc8c136a300c0017a
0f6814e33e875af3493eb3de36029ebee491fa02
refs/heads/master
2020-09-01T14:25:49.511069
2019-12-06T09:32:25
2019-12-06T09:32:25
218,979,316
0
0
null
null
null
null
UTF-8
C++
false
false
613
h
/********************************************************************* ** Author: Nick DaCosta ** ** Class: 340 <Section 01> ** ** Assignment: pa 4 ** ** Certification of Authenticity: ** ** I certify that this assignment is entirely my own work. ** *********************************************************************/ #pragma once class SwitchPathfindingMessage : public GameMessage { public: SwitchPathfindingMessage(const PathfindingType type); ~SwitchPathfindingMessage(); void process(); private: PathfindingType mType = INVALID; };
[ "dacosta.nick@yahoo.com" ]
dacosta.nick@yahoo.com
b0576b31cd4a37030f9ab8e1befff3edba64098c
dbb2039848c2a264eedb3510ef800c47cbfe5afc
/shared_model/backend/protobuf/impl/permissions.cpp
fd54529c5aae4c720b4a5fe55255c1796de4b2bf
[ "Apache-2.0", "CC-BY-4.0" ]
permissive
alxndrtarasov/iroha-rest
d5404551db2fcee6299cd8f4b5a43f2c89cf98a1
69975ba6a7a619db612f582ec3720b9460d383eb
refs/heads/master
2022-12-10T21:33:30.915616
2019-04-11T14:19:36
2019-04-11T14:19:36
180,153,183
0
1
Apache-2.0
2022-12-07T23:53:32
2019-04-08T13:18:39
C++
UTF-8
C++
false
false
2,141
cpp
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #include "backend/protobuf/permissions.hpp" namespace shared_model { namespace proto { namespace permissions { interface::permissions::Role fromTransport( iroha::protocol::RolePermission perm) noexcept { return static_cast<interface::permissions::Role>(perm); } iroha::protocol::RolePermission toTransport( interface::permissions::Role r) { return static_cast<iroha::protocol::RolePermission>(r); } std::string toString(interface::permissions::Role r) { return iroha::protocol::RolePermission_Name(toTransport(r)); } interface::permissions::Grantable fromTransport( iroha::protocol::GrantablePermission perm) noexcept { return static_cast<interface::permissions::Grantable>(perm); } iroha::protocol::GrantablePermission toTransport( interface::permissions::Grantable r) { return static_cast<iroha::protocol::GrantablePermission>(r); } std::string toString(interface::permissions::Grantable r) { return iroha::protocol::GrantablePermission_Name(toTransport(r)); } std::vector<std::string> toString( const interface::PermissionSet<interface::permissions::Role> &set) { std::vector<std::string> v; for (size_t i = 0; i < set.size(); ++i) { auto perm = static_cast<interface::permissions::Role>(i); if (set.test(perm)) { v.push_back(toString(perm)); } } return v; } std::vector<std::string> toString( const interface::PermissionSet<interface::permissions::Grantable> &set) { std::vector<std::string> v; for (size_t i = 0; i < set.size(); ++i) { auto perm = static_cast<interface::permissions::Grantable>(i); if (set.test(perm)) { v.push_back(toString(perm)); } } return v; } } // namespace permissions } // namespace proto } // namespace shared_model
[ "trezor0210@gmail.com" ]
trezor0210@gmail.com
43aff7ae8f6eb177c7c4c9702783914fc0405288
93f6548440a8d61e852cbf4683bc551784a74182
/FilePosition.h
518d4611a4583d729a168a600c9dc6c2cfff135f
[]
no_license
RikuSyaCyo/miniSQL
73c756c68241599232551adde6cf6a4355f4ed03
d2ac82c3465e2b0867cb1b32b2d39a1ff55f96c2
refs/heads/master
2021-01-10T15:29:03.779548
2015-11-08T15:33:25
2015-11-08T15:33:25
45,240,408
0
0
null
null
null
null
UTF-8
C++
false
false
535
h
#pragma once #include <string> #include <iostream> #include <sstream> using namespace std; class FilePosition { private: static const int FILENAMELENGTH = 32; // max length of file name char fileName[FILENAMELENGTH]; public: int blockNo; FilePosition(); ~FilePosition(); string Hash() const { stringstream strNo; strNo << blockNo; return filePath() + strNo.str(); } string filePath() const { string str = fileName; return str; } void setFilePath(string filePath) { strcpy_s(fileName,filePath.c_str()); } };
[ "598991258@qq.com" ]
598991258@qq.com
bcab1964e5fbbc98186ea6757550ec6a63d0a59c
b3554c0cfca16513303e49e82b2762498f414c1f
/src/shaders/EffectShaders.h
99ce390591dce726678d219949bfbc60cc6b36f4
[]
no_license
mfkiwl/oculon
9d75148364649b2729e0adffcbd6cc37dc125d88
92d3101c8a0c6b896b4ce37c8169cdbbf3f88a06
refs/heads/master
2023-01-10T11:35:50.173892
2020-11-14T23:10:19
2020-11-14T23:10:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,114
h
// // EffectShaders.h // Oculon // // Created by Ehsan Rezaie on 2014-05-15. // // #pragma once #include "Scene.h" #include "TimeController.h" #include "AudioInputHandler.h" #include "SimplexNoiseTexture.h" #include "FragShader.h" #include "TextureSelector.h" #include "AudioBandSelector.h" #include "cinder/gl/GlslProg.h" #include "cinder/gl/Texture.h" class EffectShaders : public Scene { public: EffectShaders(const std::string& name = "effects"); virtual ~EffectShaders(); // inherited from Scene void setup(); void reset(); void update(double dt); void draw(); protected:// from Scene void setupInterface(); private: void shaderPreDraw(); void shaderPostDraw(); private: // control TimeController mTimeController; AudioInputHandler mAudioInputHandler; // noise SimplexNoiseTexture mDynamicNoiseTexture; TextureSelector mNoiseTextures; // effects std::vector<FragShader*> mEffects; int mCurrentEffect; // inputs TextureSelector mInput1Texture; TextureSelector mInput2Texture; TimelineFloatParam mInput1Alpha; TimelineFloatParam mInput2Alpha; public: #pragma mark - class CathodeRay : public FragShader { public: CathodeRay(); void setupInterface( Interface* interface, const std::string& prefix ); void setCustomParams( AudioInputHandler& audioInputHandler ); void update(double dt); private: float mPowerBandThickness; int mPowerBandThicknessResponse; float mPowerBandIntensity; int mPowerBandIntensityResponse; TimeController mPowerBandTime; float mSignalNoise; int mSignalNoiseResponse; float mScanlines; int mScanlinesBand; float mColorShift; AudioBandSelector mColorShiftBand; // float mInputAlpha; AudioFloatParam mFrameShift; AudioFloatParam mScanShift; ci::ColorAf mTintColor; }; #pragma mark - class Television : public FragShader { public: Television(); void setupInterface( Interface* interface, const std::string& prefix ); void setCustomParams( AudioInputHandler& audioInputHandler ); private: float mVerticalJerk; float mVerticalShift; float mBottomStatic; float mScanlines; float mColorShift; float mHorizontalFuzz; }; #pragma mark - class VideoTape : public FragShader { public: VideoTape(); void setupInterface( Interface* interface, const std::string& prefix ); void setCustomParams( AudioInputHandler& audioInputHandler ); private: }; #pragma mark - class OilWater : public FragShader { public: OilWater(); void setupInterface( Interface* interface, const std::string& prefix ); void setCustomParams( AudioInputHandler& audioInputHandler ); private: }; };
[ "ehsan@ewerx.ca" ]
ehsan@ewerx.ca
f3123b794d47921266d87f1e39b22e4c307ea9c1
93e75fbf66f304abc4b64df6b5c1e46bc045931f
/libs/irrlicht-1.2-patched/source/Irrlicht/CColorConverter.cpp
629acf0c3918f67931ca59b711c0c90cc9feacd2
[ "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference", "Zlib" ]
permissive
fossabot/Bolzplatz2006
3397cd69a0d8e193ecee6e6dde6b196e5be0903b
a368427f9654776d9968de8ae067f200ffb0f68d
refs/heads/master
2023-02-24T08:42:02.268217
2021-01-29T09:49:34
2021-01-29T09:49:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,326
cpp
// Copyright (C) 2002-2006 Nikolaus Gebhardt // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #include "CColorConverter.h" #include "SColor.h" #include "os.h" #include <string.h> namespace irr { namespace video { //! converts a monochrome bitmap to A1R5G5B5 data void CColorConverter::convert1BitTo16Bit(const u8* in, s16* out, s32 width, s32 height, s32 linepad, bool flip) { if (!in || !out) return; if (flip) out += width * height; for (s32 y=0; y<height; ++y) { s32 shift = 7; if (flip) out -= width; for (s32 x=0; x<width; ++x) { out[x] = *in>>shift & 0x01 ? (s16)0xffff : (s16)0x0000; if ((--shift)<0) // 8 pixel done { shift=7; ++in; } } if (shift != 7) // width did not fill last byte ++in; if (!flip) out += width; in += linepad; } } //! converts a 4 bit palettized image to A1R5G5B5 void CColorConverter::convert4BitTo16Bit(const u8* in, s16* out, s32 width, s32 height, const s32* palette, s32 linepad, bool flip) { if (!in || !out || !palette) return; if (flip) out += width*height; for (s32 y=0; y<height; ++y) { s32 shift = 4; if (flip) out -= width; for (s32 x=0; x<width; ++x) { out[x] = X8R8G8B8toA1R5G5B5(palette[(u8)((*in >> shift) & 0xf)]); if (shift==0) { shift = 4; ++in; } else shift = 0; } if (shift == 0) // odd width ++in; if (!flip) out += width; in += linepad; } } //! converts a 8 bit palettized image into A1R5G5B5 void CColorConverter::convert8BitTo16Bit(const u8* in, s16* out, s32 width, s32 height, const s32* palette, s32 linepad, bool flip) { if (!in || !out || !palette) return; if (flip) out += width * height; for (s32 y=0; y<height; ++y) { if (flip) out -= width; // one line back for (s32 x=0; x<width; ++x) { out[x] = X8R8G8B8toA1R5G5B5(palette[(u8)(*in)]); ++in; } if (!flip) out += width; in += linepad; } } //! converts 16bit data to 16bit data void CColorConverter::convert16BitTo16Bit(const s16* in, s16* out, s32 width, s32 height, s32 linepad, bool flip) { if (!in || !out) return; if (flip) out += width * height; for (s32 y=0; y<height; ++y) { if (flip) out -= width; #ifdef __BIG_ENDIAN__ for (s32 x=0; x<width; ++x) out[x]=os::Byteswap::byteswap(in[x]); #else memcpy(out, in, width*sizeof(s16)); #endif if (!flip) out += width; in += width; in += linepad; } } //! copies R8G8B8 24bit data to 24bit data void CColorConverter::convert24BitTo24Bit(const u8* in, u8* out, s32 width, s32 height, s32 linepad, bool flip, bool bgr) { if (!in || !out) return; const s32 lineWidth = 3 * width; if (flip) out += lineWidth * height; for (s32 y=0; y<height; ++y) { if (flip) out -= lineWidth; if (bgr) { for (s32 x=0; x<lineWidth; x+=3) { out[x+0] = in[x+2]; out[x+1] = in[x+1]; out[x+2] = in[x+0]; } } else { memcpy(out,in,lineWidth); } if (!flip) out += lineWidth; in += lineWidth; in += linepad; } } //! Resizes the surface to a new size and converts it at the same time //! to an A8R8G8B8 format, returning the pointer to the new buffer. void CColorConverter::convert16bitToA8R8G8B8andResize(const s16* in, s32* out, s32 newWidth, s32 newHeight, s32 currentWidth, s32 currentHeight) { if (!newWidth || !newHeight) return; // note: this is very very slow. (i didn't want to write a fast version. // but hopefully, nobody wants to convert surfaces every frame. f32 sourceXStep = (f32)currentWidth / (f32)newWidth; f32 sourceYStep = (f32)currentHeight / (f32)newHeight; f32 sy; s32 t; for (s32 x=0; x<newWidth; ++x) { sy = 0.0f; for (s32 y=0; y<newHeight; ++y) { t = in[(s32)(((s32)sy)*currentWidth + x*sourceXStep)]; t = (((t >> 15)&0x1)<<31) | (((t >> 10)&0x1F)<<19) | (((t >> 5)&0x1F)<<11) | (t&0x1F)<<3; out[(s32)(y*newWidth + x)] = t; sy+=sourceYStep; } } } //! copies X8R8G8B8 32 bit data void CColorConverter::convert32BitTo32Bit(const s32* in, s32* out, s32 width, s32 height, s32 linepad, bool flip) { if (!in || !out) return; if (flip) out += width * height; for (s32 y=0; y<height; ++y) { if (flip) out -= width; #ifdef __BIG_ENDIAN__ for (s32 x=0; x<width; ++x) out[x]=os::Byteswap::byteswap(in[x]); #else memcpy(out, in, width*sizeof(s32)); #endif if (!flip) out += width; in += width; in += linepad; } } void CColorConverter::convert_A1R5G5B5toR8G8B8(const void* sP, s32 sN, void* dP) { u16* sB = (u16*)sP; u8 * dB = (u8 *)dP; for (s32 x = 0; x < sN; ++x) { dB[2] = (*sB & 0x7c) << 9; dB[1] = (*sB & 0x3e) << 6; dB[0] = (*sB & 0x1f) << 3; sB += 1; dB += 3; } } void CColorConverter::convert_A1R5G5B5toA8R8G8B8(const void* sP, s32 sN, void* dP) { u16* sB = (u16*)sP; u32* dB = (u32*)dP; for (s32 x = 0; x < sN; ++x) *dB++ = A1R5G5B5toA8R8G8B8(*sB++); } void CColorConverter::convert_A1R5G5B5toA1R5G5B5(const void* sP, s32 sN, void* dP) { memcpy(dP, sP, sN * 2); } void CColorConverter::convert_A1R5G5B5toR5G6B5(const void* sP, s32 sN, void* dP) { u16* sB = (u16*)sP; u16* dB = (u16*)dP; for (s32 x = 0; x < sN; ++x) *dB++ = A1R5G5B5toR5G6B5(*sB++); } void CColorConverter::convert_A8R8G8B8toR8G8B8(const void* sP, s32 sN, void* dP) { u8* sB = (u8*)sP; u8* dB = (u8*)dP; for (s32 x = 0; x < sN; ++x) { // sB[3] is alpha dB[0] = sB[0]; dB[1] = sB[1]; dB[2] = sB[2]; sB += 4; dB += 3; } } void CColorConverter::convert_A8R8G8B8toA8R8G8B8(const void* sP, s32 sN, void* dP) { memcpy(dP, sP, sN * 4); } void CColorConverter::convert_A8R8G8B8toA1R5G5B5(const void* sP, s32 sN, void* dP) { u32* sB = (u32*)sP; u16* dB = (u16*)dP; for (s32 x = 0; x < sN; ++x) *dB++ = A8R8G8B8toA1R5G5B5(*sB++); } void CColorConverter::convert_A8R8G8B8toR5G6B5(const void* sP, s32 sN, void* dP) { u8 * sB = (u8 *)sP; u16* dB = (u16*)dP; for (s32 x = 0; x < sN; ++x) { s32 r = sB[2] >> 3; s32 g = sB[1] >> 2; s32 b = sB[0] >> 3; dB[0] = (r << 11) | (g << 5) | (b); sB += 4; dB += 1; } } void CColorConverter::convert_R8G8B8toR8G8B8(const void* sP, s32 sN, void* dP) { memcpy(dP, sP, sN * 3); } void CColorConverter::convert_R8G8B8toA8R8G8B8(const void* sP, s32 sN, void* dP) { u8* sB = (u8* )sP; u32* dB = (u32*)dP; for (s32 x = 0; x < sN; ++x) { *dB = 0xff000000 | (sB[0]<<16) | (sB[1]<<8) | sB[2]; sB += 3; ++dB; } } void CColorConverter::convert_R8G8B8toA1R5G5B5(const void* sP, s32 sN, void* dP) { u8 * sB = (u8 *)sP; u16* dB = (u16*)dP; for (s32 x = 0; x < sN; ++x) { s32 r = sB[0] >> 3; s32 g = sB[1] >> 3; s32 b = sB[2] >> 3; dB[0] = (0x8000) | (r << 10) | (g << 5) | (b); sB += 3; dB += 1; } } void CColorConverter::convert_R8G8B8toR5G6B5(const void* sP, s32 sN, void* dP) { u8 * sB = (u8 *)sP; u16* dB = (u16*)dP; for (s32 x = 0; x < sN; ++x) { s32 r = sB[0] >> 3; s32 g = sB[1] >> 2; s32 b = sB[2] >> 3; dB[0] = (r << 11) | (g << 5) | (b); sB += 3; dB += 1; } } void CColorConverter::convert_R5G6B5toR5G6B5(const void* sP, s32 sN, void* dP) { memcpy(dP, sP, sN * 2); } void CColorConverter::convert_R5G6B5toR8G8B8(const void* sP, s32 sN, void* dP) { u16* sB = (u16*)sP; u8 * dB = (u8 *)dP; for (s32 x = 0; x < sN; ++x) { dB[0] = (*sB & 0xf800) << 8; dB[1] = (*sB & 0x07e0) << 2; dB[2] = (*sB & 0x001f) << 3; sB += 4; dB += 3; } } void CColorConverter::convert_R5G6B5toA8R8G8B8(const void* sP, s32 sN, void* dP) { u16* sB = (u16*)sP; u32* dB = (u32*)dP; for (s32 x = 0; x < sN; ++x) *dB++ = R5G6B5toA8R8G8B8(*sB++); } void CColorConverter::convert_R5G6B5toA1R5G5B5(const void* sP, s32 sN, void* dP) { u16* sB = (u16*)sP; u16* dB = (u16*)dP; for (s32 x = 0; x < sN; ++x) *dB++ = R5G6B5toA1R5G5B5(*sB++); } } // end namespace video } // end namespace irr
[ "hoehnp@gmx.de" ]
hoehnp@gmx.de
370095a4162be3c0f08604deb76d109b5c25c407
701c6718dcea101242cd37dd8c6e2d937102ad90
/cf_100.cpp
e720fd8d2d60027053b60571a4d96d8553964980
[]
no_license
Ch-Lokesh/cp_practice
e373567fc7233ab4b7fed38ad69bc0498cd2cd57
0b75bcf2661bbbb2791f2ebb4abfd2ca6b7c4c33
refs/heads/main
2023-05-31T20:44:21.384092
2021-07-13T03:50:22
2021-07-13T03:50:22
362,665,985
0
0
null
null
null
null
UTF-8
C++
false
false
1,134
cpp
#include <iostream> #include <bits/stdc++.h> using namespace std; typedef long long int ll; #define fori(i, n) for (int i = 0; i < int(n); i++) #define forll(i, n) for (ll i = 0; i < ll(n); i++) #define MOD 1000000007 void neg() { cout << -1 << endl; } void No() { cout << "No" << endl; } void NO() { cout << "NO" << endl; } void YES() { cout << "YES" << endl; } void Yes() { cout << "Yes" << endl; } void solve() { string s; cin >> s; int a[26] = {0}; for (int i = 0; i < s.size(); i++) { a[s[i] - 'a']++; } int evens = 0, odds = 0; int twos = 0; for (int i = 0; i < 26; i++) { if (a[i] > 1) { twos += (a[i]) / 2; a[i] = a[i] % 2; } } for (int i = 0; i < 26; i++) { if (a[i] > 0) { if (twos > 0) { twos--; } else { NO(); return; } } } YES(); return; } int main() { int t = 1; cin >> t; while (t--) solve(); return 0; }
[ "chikkula@iitkgp.ac.in" ]
chikkula@iitkgp.ac.in
7888e5c580a283a6f068785efd3b5cc1ab740c86
715b2962ea1befeec1ed97733d6fc48337993380
/Classes/UnitTest/CocosGUITest.h
8532f1396a2548cd9856f93e01f1382bdbd873ed
[]
no_license
tklee1975/SimpleTDD-ccx3-demo
69d1e00831b7c02388ab349f605c3f8599fa26de
d39101d999a8d1bd7c9f1bf3f8bd24e3c6c52529
refs/heads/master
2021-01-19T06:34:51.803956
2016-10-23T14:35:07
2016-10-23T14:35:07
31,271,601
0
0
null
null
null
null
UTF-8
C++
false
false
493
h
#ifdef ENABLE_TDD // // CocosGUITest.h // // #ifndef __TDD_CocosGUITest__ #define __TDD_CocosGUITest__ // Include Header #include "TDDBaseTest.h" // Class Declaration class CocosGUITest : public TDDBaseTest { protected: virtual void setUp(); virtual void tearDown(); virtual void defineTests(); virtual void willRunTest(const std::string &name); // before run a test virtual void didRunTest(const std::string &name); // after run a test private: void testGUI(); }; #endif #endif
[ "tklee1975@gmail.com" ]
tklee1975@gmail.com
cefaf08208079b00e5c832d66e9881a62e4f2161
1a1cc549631350f32927d14f43a7b21905729c60
/peternndor_2035_147003_main-2.cpp
75c8875290240b0840eb451708ee81838e796ebb
[]
no_license
thec0dewriter/AlgoGI2020
d17466b379e5073f69edae26e52deead51938532
1cc7a448465fb534922c687f1173d09a5c0a89ca
refs/heads/main
2023-01-21T08:41:51.225765
2020-11-30T21:14:20
2020-11-30T21:14:20
317,330,780
0
0
null
null
null
null
UTF-8
C++
false
false
2,710
cpp
/////PETER NANDOR GI2 #include <iostream> #include <fstream > #include <math.h> using namespace std; ///1. Feladat: MAXIMUM KIVALASZTAS /* void maximum_kivaszlatas(unsigned long int n, unsigned long int a[]); void kiir(unsigned long int n, unsigned long int a[]); int main() { ifstream f("be.txt"); unsigned long int n; f >> n; unsigned long int a[10]; for (int i = 0; i < n ; i++){ f >> a[i]; } maximum_kivaszlatas(n,a); kiir(n,a); return 0; } void maximum_kivaszlatas(unsigned long int n, unsigned long int a[]){ int index_max; int seged; for (int i = 0; i < n; i++){ index_max = i; for (int j = i+1; j < n; j++){ if (a[index_max] < a[j]){ index_max = j; } } seged = a[i]; a[i] = a[index_max]; a[index_max] = seged; } } void kiir(unsigned long int n, unsigned long int a[]){ for (int i = 0 ; i < n ; i++){ cout << a[i] << " "; } }*/ //////2.Feladat PALINDROM SZAM-E /* int palindrom(int n){ if (n == ) return n; else cout << n << " "; return (n / palindrom (n / 10)); } int main () { int n; cout << "n= "; cin >> n; if (palindrom(n) cout << n << " Palindrom" << endl; else cout << n <<" Nem palindrom" << endl; }/* //////3.Feladat SZAMJEGYES /* int szamjegy (int n){ int db; while (n != 0){ n = n / 10; db++; } return db; } int oszto2 (int db){ int oszto2 = 0; if (db == 2) oszto2 = 1; else if (db == 3) oszto2 = 10; else if (db == 4) oszto2 = 100; else if (db == 5) oszto2 = 1000; else if (db == 6) oszto2 = 10000; else if (db == 7) oszto2 = 100000; else if (db == 8) oszto2 = 1000000; else if (db == 9) oszto2 = 10000000; else oszto2 = 100000000; return oszto2; } int main () { int n; cout << "n= "; cin >> n; int seged = n; int db = szamjegy(n); int oszto = pow(10,db-1); int oszto2_1 = oszto2(db); int szam = 0; while (n != szam){ int maradek = seged % oszto; int utolso = seged / oszto; szam = maradek * (oszto / oszto2_1) + utolso; seged = szam; cout << szam << endl; } }*/ //4. Feladat bool binaris (int a){ int db = 0; while (a != 1){ if (a % 2 == 1){ db++; } if (db == 2) return true; else return false; } } int main () { int a,b,k; cout << "a= "; cin >> a; cout << "b= "; cin >> b; cout << "k= "; cin >> k; for (int i = a; i <= b; i++){ if (binaris(i) == k){ cout << i << " "; } } }
[ "kutikmatyas@gmail.com" ]
kutikmatyas@gmail.com
09867a26f454bb45d3e091c8125fb14e5f3bebe3
8662931078c2ff999c8b2ee248ee1ce2109ab81a
/TinySTL/ReverseIterator.h
b54e0b117775c6ec06fcc3a74a145b91f3b6f0f6
[]
no_license
sydtju/TinySTL
6d0d396dc4cf11e686b2abe6edde707ea9e9df3b
a02fe7120f2512b472a133a84d25a57ab8b4d03d
refs/heads/master
2021-01-21T17:03:16.514249
2015-07-16T13:07:32
2015-07-16T13:07:32
39,196,873
2
0
null
2015-07-16T12:58:27
2015-07-16T12:58:27
null
GB18030
C++
false
false
6,332
h
#ifndef _REVERSE_ITERATOR_H_ #define _REVERSE_ITERATOR_H_ #include "Iterator.h" namespace TinySTL{ template<class Iterator> class reverse_iterator_t{ public: typedef Iterator iterator_type; typedef typename iterator_traits<Iterator>::iterator_category iterator_category; typedef typename iterator_traits<Iterator>::value_type value_type; typedef typename iterator_traits<Iterator>::difference_type difference_type; typedef typename iterator_traits<Iterator>::pointer pointer; typedef const pointer const_pointer; typedef typename iterator_traits<Iterator>::reference reference; typedef const reference const_reference; private: Iterator base_; Iterator cur_; public: //构造。复制,析构相关 reverse_iterator_t() :base_(0), cur_(0){} //explicit reverse_iterator_t(const iterator_type& it) :base_(it), cur_(it - 1){} explicit reverse_iterator_t(const iterator_type& it) :base_(it){ auto temp = it; cur_ = --temp; } template <class Iter> reverse_iterator_t(const reverse_iterator_t<Iter>& rev_it){ base_ = (iterator_type)rev_it.base(); auto temp = base_; cur_ = --temp; }; //其他成员函数 iterator_type base(){ return base_; } reference operator*(){ return (*cur_); } const_reference operator*()const{ return(*cur_); } pointer operator->(){ return &(operator *()); } const_pointer operator->()const{ return &(operator*()); } reverse_iterator_t& operator ++(){ --base_; --cur_; return *this; } reverse_iterator_t& operator ++(int){ reverse_iterator_t temp = *this; ++(*this); return temp; } reverse_iterator_t& operator--(){ ++base_; ++cur_; return *this; } reverse_iterator_t operator--(int){ reverse_iterator_t temp = *this; --(*this); return temp; } reference operator[] (difference_type n){ return base()[-n - 1]; } reverse_iterator_t operator + (difference_type n)const; reverse_iterator_t& operator += (difference_type n); reverse_iterator_t operator - (difference_type n)const; reverse_iterator_t& operator -= (difference_type n); private: Iterator advanceNStep(Iterator it, difference_type n, bool right,//true -> \ false <- random_access_iterator_tag){ if (right){ it += n; }else{ it -= n; } return it; } Iterator advanceNStep(Iterator it, difference_type n, bool right,//true -> \ false <- bidirectional_iterator_tag){ difference_type i; difference_type absN = n >= 0 ? n : -n; if ((right && n > 0) || (!right && n < 0)){// -> for (i = 0; i != absN; ++i){ it = it + 1; } } else if ((!right && n > 0) || (right && n < 0)){// <- for (i = 0; i != absN; ++i){ it = it - 1; } } return it; } public: template <class Iterator> friend bool operator == (const reverse_iterator_t<Iterator>& lhs, const reverse_iterator_t<Iterator>& rhs); template <class Iterator> friend bool operator != (const reverse_iterator_t<Iterator>& lhs, const reverse_iterator_t<Iterator>& rhs); template <class Iterator> friend bool operator < (const reverse_iterator_t<Iterator>& lhs, const reverse_iterator_t<Iterator>& rhs); template <class Iterator> friend bool operator <= (const reverse_iterator_t<Iterator>& lhs, const reverse_iterator_t<Iterator>& rhs); template <class Iterator> friend bool operator > (const reverse_iterator_t<Iterator>& lhs, const reverse_iterator_t<Iterator>& rhs); template <class Iterator> friend bool operator >= (const reverse_iterator_t<Iterator>& lhs, const reverse_iterator_t<Iterator>& rhs); template <class Iterator> friend reverse_iterator_t<Iterator> operator + ( typename reverse_iterator_t<Iterator>::difference_type n, const reverse_iterator_t<Iterator>& rev_it); template <class Iterator> friend typename reverse_iterator_t<Iterator>::difference_type operator- ( const reverse_iterator_t<Iterator>& lhs, const reverse_iterator_t<Iterator>& rhs); };// end of reverse_iterator_t template<class Iterator> reverse_iterator_t<Iterator>& reverse_iterator_t<Iterator>::operator += (difference_type n){ base_ = advanceNStep(base_, n, false, iterator_category()); cur_ = advanceNStep(cur_, n, false, iterator_category()); return *this; } template<class Iterator> reverse_iterator_t<Iterator>& reverse_iterator_t<Iterator>::operator -= (difference_type n){ base_ = advanceNStep(base_, n, true, iterator_category()); cur_ = advanceNStep(cur_, n, true, iterator_category()); return *this; } template<class Iterator> reverse_iterator_t<Iterator> reverse_iterator_t<Iterator>::operator + (difference_type n)const{ reverse_iterator_t<Iterator> res = *this; res += n; return res; } template<class Iterator> reverse_iterator_t<Iterator> reverse_iterator_t<Iterator>::operator - (difference_type n)const{ reverse_iterator_t<Iterator> res = *this; res -= n; return res; } template <class Iterator> bool operator == (const reverse_iterator_t<Iterator>& lhs, const reverse_iterator_t<Iterator>& rhs){ return lhs.cur_ == rhs.cur_; } template <class Iterator> bool operator != (const reverse_iterator_t<Iterator>& lhs, const reverse_iterator_t<Iterator>& rhs){ return !(lhs == rhs); } template <class Iterator> bool operator < (const reverse_iterator_t<Iterator>& lhs, const reverse_iterator_t<Iterator>& rhs){ return lhs.cur_ < rhs.cur_; } template <class Iterator> bool operator > (const reverse_iterator_t<Iterator>& lhs, const reverse_iterator_t<Iterator>& rhs){ return lhs.cur_ > rhs.cur_; } template <class Iterator> bool operator >= (const reverse_iterator_t<Iterator>& lhs, const reverse_iterator_t<Iterator>& rhs){ return !(lhs < rhs); } template <class Iterator> bool operator <= (const reverse_iterator_t<Iterator>& lhs, const reverse_iterator_t<Iterator>& rhs){ return !(lhs > rhs); } template <class Iterator> reverse_iterator_t<Iterator> operator + ( typename reverse_iterator_t<Iterator>::difference_type n, const reverse_iterator_t<Iterator>& rev_it){ return rev_it + n; } template <class Iterator> typename reverse_iterator_t<Iterator>::difference_type operator - ( const reverse_iterator_t<Iterator>& lhs, const reverse_iterator_t<Iterator>& rhs){ return lhs.cur_ - rhs.cur_; } } #endif
[ "1210603696@qq.com" ]
1210603696@qq.com
63f26f78b7b938a3bf7d59a4dd2c44d21fa7a650
31ea1a5b210c90a62eb0b1a1732d7a66ca8bb4a0
/IAccessible2Test/win-include-accessibility/CAccessibleHyperlink.h
e7523478f56b253b55ae0b42c38ceca5caadab73
[ "MIT" ]
permissive
define4real/hello-world
b0185f36da57de754d5aaef79e0464933323fd8f
296d79bbdb62872a48f5167101b00cf2073503a2
refs/heads/master
2023-06-08T20:03:36.139123
2023-06-07T13:35:05
2023-06-07T13:35:05
166,627,902
0
0
MIT
2019-01-20T06:08:03
2019-01-20T05:47:25
null
UTF-8
C++
false
false
2,910
h
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim:expandtab:shiftwidth=2:tabstop=2: */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Mozilla Foundation. * Portions created by the Initial Developer are Copyright (C) 2007 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Alexander Surkov <surkov.alexander@gmail.com> (original author) * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef _ACCESSIBLE_HYPERLINK_H #define _ACCESSIBLE_HYPERLINK_H #include "nsISupports.h" #include "CAccessibleAction.h" #include "AccessibleHyperlink.h" class CAccessibleHyperlink: public CAccessibleAction, public IAccessibleHyperlink { public: // IUnknown STDMETHODIMP QueryInterface(REFIID, void**); // IAccessibleAction FORWARD_IACCESSIBLEACTION(CAccessibleAction) virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_anchor( /* [in] */ long index, /* [retval][out] */ VARIANT *anchor); virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_anchorTarget( /* [in] */ long index, /* [retval][out] */ VARIANT *anchorTarget); virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_startIndex( /* [retval][out] */ long *index); virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_endIndex( /* [retval][out] */ long *index); virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_valid( /* [retval][out] */ boolean *valid); }; #endif
[ "define4real@gmail.com" ]
define4real@gmail.com
48023d03a73ae0d1510b2493cd0ed0721af1c065
21553f6afd6b81ae8403549467230cdc378f32c9
/arm/cortex/Freescale/MKL36Z4/include/arch/reg/fgpioe.hpp
80bae73acca966d0d8a8e80c60a71e2e3eff3709
[]
no_license
digint/openmptl-reg-arm-cortex
3246b68dcb60d4f7c95a46423563cab68cb02b5e
88e105766edc9299348ccc8d2ff7a9c34cddacd3
refs/heads/master
2021-07-18T19:56:42.569685
2017-10-26T11:11:35
2017-10-26T11:11:35
108,407,162
3
1
null
null
null
null
UTF-8
C++
false
false
2,918
hpp
/* * OpenMPTL - C++ Microprocessor Template Library * * This program is a derivative representation of a CMSIS System View * Description (SVD) file, and is subject to the corresponding license * (see "Freescale CMSIS-SVD License Agreement.pdf" in the parent directory). * * 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. */ //////////////////////////////////////////////////////////////////////// // // Import from CMSIS-SVD: "Freescale/MKL36Z4.svd" // // vendor: Freescale Semiconductor, Inc. // vendorID: Freescale // name: MKL36Z4 // series: Kinetis_L // version: 1.6 // description: MKL36Z4 Freescale Microcontroller // -------------------------------------------------------------------- // // C++ Header file, containing architecture specific register // declarations for use in OpenMPTL. It has been converted directly // from a CMSIS-SVD file. // // https://digint.ch/openmptl // https://github.com/posborne/cmsis-svd // #ifndef ARCH_REG_FGPIOE_HPP_INCLUDED #define ARCH_REG_FGPIOE_HPP_INCLUDED #warning "using untested register declarations" #include <register.hpp> namespace mptl { /** * General Purpose Input/Output */ struct FGPIOE { static constexpr reg_addr_t base_addr = 0xf8000100; /** * Port Data Output Register */ struct PDOR : public reg< uint32_t, base_addr + 0, rw, 0 > { using type = reg< uint32_t, base_addr + 0, rw, 0 >; using PDO = regbits< type, 0, 32 >; /**< Port Data Output */ }; /** * Port Set Output Register */ struct PSOR : public reg< uint32_t, base_addr + 0x4, wo, 0 > { using type = reg< uint32_t, base_addr + 0x4, wo, 0 >; using PTSO = regbits< type, 0, 32 >; /**< Port Set Output */ }; /** * Port Clear Output Register */ struct PCOR : public reg< uint32_t, base_addr + 0x8, wo, 0 > { using type = reg< uint32_t, base_addr + 0x8, wo, 0 >; using PTCO = regbits< type, 0, 32 >; /**< Port Clear Output */ }; /** * Port Toggle Output Register */ struct PTOR : public reg< uint32_t, base_addr + 0xc, wo, 0 > { using type = reg< uint32_t, base_addr + 0xc, wo, 0 >; using PTTO = regbits< type, 0, 32 >; /**< Port Toggle Output */ }; /** * Port Data Input Register */ struct PDIR : public reg< uint32_t, base_addr + 0x10, ro, 0 > { using type = reg< uint32_t, base_addr + 0x10, ro, 0 >; using PDI = regbits< type, 0, 32 >; /**< Port Data Input */ }; /** * Port Data Direction Register */ struct PDDR : public reg< uint32_t, base_addr + 0x14, rw, 0 > { using type = reg< uint32_t, base_addr + 0x14, rw, 0 >; using PDD = regbits< type, 0, 32 >; /**< Port Data Direction */ }; }; } // namespace mptl #endif // ARCH_REG_FGPIOE_HPP_INCLUDED
[ "axel@tty0.ch" ]
axel@tty0.ch
05b1e16b8e31b2718ab76a413ef53cf7d11b3b53
7d041327921bd0b41b0f6060536872a39eacfb3a
/Подготовительная программа по программированию на С-С++/Task_2.cpp
f2514df3084a4244a960606755647f887e0ea962
[]
no_license
TatyanaMin/Cplusplus
a78479e75550fda90518ad71c2c0d0bfd0fdf214
9a4165b1b18382eefb49289ddae9f186afd5fe9c
refs/heads/master
2023-08-25T04:00:52.893807
2021-10-28T20:19:58
2021-10-28T20:19:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,173
cpp
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> using namespace std; class Student { friend class findStudent; public: Student(); Student(const Student&); Student(char*, char*, char*, char*, char*, char*, char*, char*, char*, char*); void set(char *); void get(); void show(); ~Student(); protected: char *Name; char *Surname; char *Patronymic; char *Day; char *Mount; char *Year; char *Address; char *Phone; char *Faculty; char *Course; private: int strLen(char*); char* copy(char*, const char*); }; Student::Student() :Name(0), Surname(0), Patronymic(0), Day(0), Mount(0), Year(0), Address(0), Phone(0), Faculty(0), Course(0) { } Student::Student(const Student &arg) { Name = new char[strLen(arg.Name)]; copy(Name, arg.Name); Surname = new char[strLen(arg.Surname)]; copy(Name, arg.Surname); Patronymic = new char[strLen(arg.Patronymic)]; copy(Name, arg.Patronymic); Day = new char[strLen(arg.Day)]; copy(Name, arg.Day); Mount = new char[strLen(arg.Mount)]; copy(Name, arg.Mount); Year = new char[strLen(arg.Year)]; copy(Name, arg.Year); Address = new char[strLen(arg.Address)]; copy(Name, arg.Address); Phone = new char[strLen(arg.Phone)]; copy(Name, arg.Phone); Faculty = new char[strLen(arg.Faculty)]; copy(Name, arg.Faculty); Course = new char[strLen(arg.Course)]; copy(Name, arg.Course); } Student::Student(char *nam, char *sur, char *pat, char *d, char *m, char *y, char *add, char *ph, char *fac, char *cor) { Name = new char[strLen(nam)]; copy(Name, nam); Surname = new char[strLen(sur)]; copy(Name, sur); Patronymic = new char[strLen(pat)]; copy(Name, pat); Day = new char[strLen(d)]; copy(Name, d); Mount = new char[strLen(m)]; copy(Name, m); Year = new char[strLen(y)]; copy(Name, y); Address = new char[strLen(add)]; copy(Name, add); Phone = new char[strLen(ph)]; copy(Name, ph); Faculty = new char[strLen(fac)]; copy(Name, fac); Course = new char[strLen(cor)]; copy(Name, cor); } int Student::strLen(char *str) { int i = 0; while(*str) { i++; str++; } return i; } char* Student::copy(char *str1, const char *str2) { char *tmp = str1; while(*tmp++ = *str2++); return str1; } Student::~Student() { delete[] Name; delete[] Surname; delete[] Patronymic; delete[] Day; delete[] Mount; delete[] Year; delete[] Address; delete[] Phone; delete[] Faculty; delete[] Course; } void Student::set(char *sentence) { int i, j, k; i = j = k = 0; for(i = 0; sentence[i] != '\0'; i++) { if(isspace(sentence[i])) { sentence[i] = ' '; } switch(sentence[i]) { case '.': case ',': sentence[i] = ' '; break; default: break; } } //*********NAME******************** for(i = 0; sentence[i] != ' '; i++) {} Name = new char[i + 1]; for(k = 0; k < i; k++) { Name[k] = sentence[k]; sentence[k] = ' '; } Name[k] = '\0'; sentence[k] = ' '; //cout << "Name: " << Name << endl; //*********SURNAME******************** while(sentence[i] == ' ') { i++; } k = i; while(sentence[i] != ' ') { i++; } Surname = new char[i - k + 1]; for(j = 0; j < i - k; j++) { Surname[j] = sentence[k + j]; sentence[k + j] = ' '; } Surname[j] = '\0'; sentence[k + j] = ' '; //cout << "Surname: " << Surname << endl; //*********PATRONYMIC******************** while(sentence[i] == ' ') { i++; } k = i; while(sentence[i] != ' ') { i++; } Patronymic = new char[i - k + 1]; for(j = 0; j < i - k; j++) { Patronymic[j] = sentence[k + j]; sentence[k + j] = ' '; } Patronymic[j] = '\0'; sentence[k + j] = ' '; //cout << "Patronymic: " << Patronymic << endl; //*********DATE******************** while(sentence[i] == ' ') { i++; } k = i; while(sentence[i] != ' ') { i++; } Day = new char[i - k + 1]; for(j = 0; j < i - k; j++) { Day[j] = sentence[k + j]; sentence[k + j] = ' '; } Day[j] = '\0'; sentence[k + j] = ' '; //cout << "day: " << day << endl; //Day = atoi(day); //delete[] day; //cout << "Day: " << Day << endl; while(sentence[i] == ' ') { i++; } k = i; while(sentence[i] != ' ') { i++; } Mount = new char[i - k + 1]; for(j = 0; j < i - k; j++) { Mount[j] = sentence[k + j]; sentence[k + j] = ' '; } Mount[j] = '\0'; sentence[k + j] = ' '; //cout << "day: " << day << endl; //Mount = atoi(mount); //delete[] mount; //cout << "Mount: " << Mount << endl; while(sentence[i] == ' ') { i++; } k = i; while(sentence[i] != ' ') { i++; } Year = new char[i - k + 1]; for(j = 0; j < i - k; j++) { Year[j] = sentence[k + j]; sentence[k + j] = ' '; } Year[j] = '\0'; sentence[k + j] = ' '; //cout << "day: " << day << endl; //Year = atoi(year); //delete[] year; //cout << "Year: " << Year << endl; //*********CITY******************** while(sentence[i] == ' ') { i++; } k = i; while(sentence[i] != ' ') { i++; } Address = new char[i - k + 1]; for(j = 0; j < i - k; j++) { Address[j] = sentence[k + j]; sentence[k + j] = ' '; } Address[j] = '\0'; sentence[k + j] = ' '; //cout << "Address: " << Address << endl; //*********PHONE******************** while(sentence[i] == ' ') { i++; } k = i; while(sentence[i] != ' ') { i++; } Phone = new char[i - k + 1]; for(j = 0; j < i - k; j++) { Phone[j] = sentence[k + j]; sentence[k + j] = ' '; } Phone[j] = '\0'; sentence[k + j] = ' '; //Phone = atoi(phone); //delete[] phone; //cout << "Phone: " << Phone << endl; //*********FACULTY******************** while(sentence[i] == ' ') { i++; } k = i; while(sentence[i] != ' ') { i++; } Faculty = new char[i - k + 1]; for(j = 0; j < i - k; j++) { Faculty[j] = sentence[k + j]; sentence[k + j] = ' '; } Faculty[j] = '\0'; sentence[k + j] = ' '; //cout << "Faculty: " << Faculty << endl; //*********COURSE******************** while(sentence[i] == ' ') { i++; } k = i; while(sentence[i] != ' ') { i++; } Course = new char[i - k + 1]; for(j = 0; j < i - k; j++) { Course[j] = sentence[k + j]; sentence[k + j] = ' '; } Course[j] = '\0'; sentence[k + j] = ' '; //Course = atoi(course); //delete[] course; //cout << "Course: " << Course << endl; } void Student::get() { cout << Name << ", " << Surname << ", " << Patronymic << ", " << Day << "." << Mount << "." << Year << ", " << Address << ", " << Phone << ", " << Faculty << ", " << Course; } void Student::show() { cout << "Name: " << Name << endl; cout << "Surname: " << Surname << endl; cout << "Patronymic: " << Patronymic << endl; cout << "Day: " << Day << endl; cout << "Mount: " << Mount << endl; cout << "Year: " << Year << endl; cout << "Address: " << Address << endl; cout << "Phone: " << Phone << endl; cout << "Faculty: " << Faculty << endl; cout << "Course: " << Course << endl << endl; } class findStudent { public: void find(char*, Student*, int); }; void findStudent::find(char *str1, Student *st, int num) { int i, j, k, n, e, r; int *mas = new int[num]; i = 0; while(str1[i] == ' ') { i++; } k = i; while(str1[i] != ',') { i++; } char *faculty = new char[i - k + 1]; for(j = 0; j < i - k; j++) { faculty[j] = str1[k + j]; str1[k + j] = ' '; } faculty[j] = '\0'; str1[k + j] = ' '; //cout << "faculty: " << faculty << endl; while(str1[i] == ' ') { i++; } k = i; while(str1[i] != ',') { i++; } //for(n = 0; n < M; n++) { char *course = new char[i - k + 1]; for(j = 0; j < i - k; j++) { course[j] = str1[k + j]; str1[k + j] = ' '; } course[j] = '\0'; str1[k + j] = ' '; //cour = atoi(course); //cout << "course: " << course << endl; while(str1[i] == ' ') { i++; } k = i; while(str1[i] != '\0') { i++; } char *year = new char[i - k + 1]; for(j = 0; j < i - k; j++) { year[j] = str1[k + j]; str1[k + j] = ' '; } year[j] = '\0'; str1[k + j] = '\0'; //yyyy = atoi(year); //cout << "year: " << year << endl; e = 0; r = 0; for(n = 0; n < num; n++) { mas[n] = -1; } for(n = 0; n < num; n++) { if(strlen(st[n].Faculty) == strlen(faculty)) { if(!strcmp((st[n].Faculty), faculty)) { mas[e] = n; e++; r++; } } } for(n = 0; n < num; n++) { if(mas[n] >= 0 && r == 1){ st[mas[n]].get(); cout << ". "; } if(mas[n] >= 0 && r > 1){ st[mas[n]].get(); cout << "; "; r--; } } e = 0; r = 0; for(n = 0; n < num; n++) { mas[n] = -1; } for(n = 0; n < num; n++) { if(atoi(st[n].Course) == atoi(course)) { mas[e] = n; e++; r++; } } for(n = 0; n < num; n++) { if(mas[n] >= 0 && r == 1){ st[mas[n]].get(); cout << ". "; } if(mas[n] >= 0 && r > 1){ st[mas[n]].get(); cout << "; "; r--; } } e = 0; r = 0; for(n = 0; n < num; n++) { mas[n] = -1; } for(n = 0; n < num; n++) { if(atoi(st[n].Year) > atoi(year)) { mas[e] = n; e++; r++; } } for(n = 0; n < num; n++) { if(mas[n] >= 0 && r == 1){ st[mas[n]].get(); cout << "."; } if(mas[n] >= 0 && r > 1){ st[mas[n]].get(); cout << "; "; r--; } } delete[] mas; delete[] faculty; delete[] course; delete[] year; } int main() { int i, count, m, j; char c; char *str1 = new char; count = 0; for(i = 2; scanf("%c", &c) != EOF; i++) { char *str2 = new char[i]; strcpy(str2, str1); str2[i - 2] = c; str2[i - 1] = '\0'; delete[] str1; //cout << "delete[] str1: " << str1 << endl; str1 = str2; if(c == '.') { count++; } //cout << "str1 = str2: " << str1 << endl; } //cout << "count: " << count << endl; //cout << "str1: " << str1 << endl; //cout << "str2: " << str2 << endl; if(count/3 > 0) { int num = 0;//count/3; m = 0; Student *st = new Student[count/3]; for(i = 1; str1[i] != 0; i++) { if(str1[i - 1] == '.' && str1[i] ==' ') { char *sentence = new char[i - m]; for(j = 0; j < i - m; j++) { sentence[j] = str1[m + j]; str1[m + j] = ' '; } sentence[j] = '\0'; m = i + 1; //cout << "sentence: " << sentence << endl; st[num].set(sentence); //st[num].show(); //st[num].get(); num++; //st[]set(sentence) f(sentence, st); //cout << "f(sentence, st): " << sentence << endl << endl; delete[] sentence; //cout << "delete[] sentence: " << sentence << endl; } } findStudent *find = new findStudent; find->find(str1, st, num); delete find; // delete[] st; } //cout << "str1: " << str1 << endl; //cout << "Hello world!" << endl; delete[] str1; return 0; }
[ "79032312801@yandex.ru" ]
79032312801@yandex.ru
c99c0b51db9dade53a7a6339753c47fbbe7f3360
6f224b734744e38062a100c42d737b433292fb47
/lldb/test/API/functionalities/data-formatter/data-formatter-stl/generic/deque/main.cpp
b948fe1b4b375fc6080005ee2b6462ea6dcfb8ee
[ "NCSA", "LLVM-exception", "Apache-2.0" ]
permissive
smeenai/llvm-project
1af036024dcc175c29c9bd2901358ad9b0e6610e
764287f1ad69469cc264bb094e8fcdcfdd0fcdfb
refs/heads/main
2023-09-01T04:26:38.516584
2023-08-29T21:11:41
2023-08-31T22:16:12
216,062,316
0
0
Apache-2.0
2019-10-18T16:12:03
2019-10-18T16:12:03
null
UTF-8
C++
false
false
857
cpp
#include <cstdio> #include <deque> struct Foo_small { int a; int b; int c; Foo_small(int a, int b, int c) : a(a), b(b), c(c) {} }; struct Foo_large { int a; int b; int c; char d[1000] = {0}; Foo_large(int a, int b, int c) : a(a), b(b), c(c) {} }; template <typename T> T fill(T deque) { for (int i = 0; i < 100; i++) { deque.push_back({i, i + 1, i + 2}); deque.push_front({-i, -(i + 1), -(i + 2)}); } return deque; } int main() { std::deque<int> empty; std::deque<int> deque_1 = {1}; std::deque<int> deque_3 = {3, 1, 2}; std::deque<Foo_small> deque_200_small; deque_200_small = fill<std::deque<Foo_small>>(deque_200_small); std::deque<Foo_large> deque_200_large; deque_200_large = fill<std::deque<Foo_large>>(deque_200_large); return empty.size() + deque_1.front() + deque_3.front(); // break here }
[ "wallace@fb.com" ]
wallace@fb.com
a35d2a8da874a92d3ab312eded48f1b0f2343799
4dbaea97b6b6ba4f94f8996b60734888b163f69a
/LeetCode/68.cpp
1e1e34dd9a7682b477c991e869f802d9ea64f421
[]
no_license
Ph0en1xGSeek/ACM
099954dedfccd6e87767acb5d39780d04932fc63
b6730843ab0455ac72b857c0dff1094df0ae40f5
refs/heads/master
2022-10-25T09:15:41.614817
2022-10-04T12:17:11
2022-10-04T12:17:11
63,936,497
2
0
null
null
null
null
UTF-8
C++
false
false
1,700
cpp
class Solution { public: vector<string> fullJustify(vector<string>& words, int maxWidth) { vector<int> stringLen; vector<string> output; for(int i = 0; i < words.size(); i++){ stringLen.push_back(words[i].length()); } int i = 0; while(i < stringLen.size()){ int startPos = i; int curLen = 0; while(i < stringLen.size() && curLen + (i - startPos) + stringLen[i] <= maxWidth){ curLen += stringLen[i]; i++; } string outputString = ""; int pad, remain; if(i >= stringLen.size()){ pad = 1; remain = 0; }else if(i > startPos + 1){ pad = (maxWidth - curLen) / (i - startPos - 1); remain = (maxWidth - curLen) % (i - startPos - 1); }else{ pad = 0; remain = 0; } for(int j = startPos; j < i; j++){ outputString += words[j]; if (j < i-1){ for(int k = 0; k < pad; k++){ outputString += " "; } if(j - startPos < remain){ outputString += " "; } }else if(i >= stringLen.size() || i == startPos+1){ for(int k = 0; k < maxWidth - curLen - (i - startPos - 1); k++){ outputString += " "; } } } output.push_back(outputString); } return output; } };
[ "54panguosheng@gmail.com" ]
54panguosheng@gmail.com
f0f50ff9e535b2221f7962a8fe666d0457bd4a90
c19a1d618a295aa685e91b9855d5a686ae23a35d
/LDE/gui/LDEgui_core_draw.cpp
894ad148948d8a50b0b1782e2ae68388a0dfb7a8
[]
no_license
HappyLDE/Faya-Editor
680abb4ae483a7806a3e5345778d92abb00f22fd
c206b3ad8cd32b998b83d47e243b13c08110b971
refs/heads/master
2021-01-01T06:54:30.320700
2012-07-15T21:46:13
2012-07-15T21:46:13
4,239,895
1
0
null
null
null
null
UTF-8
C++
false
false
6,172
cpp
/********************************************************************\ * * Little Dream Engine 2 * * Scene Gamera \********************************************************************/ #include "LDEgui_core.h" void LDEgui::draw( vec2i cursor, LDEfloat frametime ) { unused = 1; focus_window = 0; focus_menu = 0; if ( menu.button.size() ) { if ( cursor.x > menu.pos.x && cursor.x < menu.pos.x + menu.size.x && cursor.y > menu.pos.y && cursor.y < menu.pos.y + menu.size.y ) { menu.coi = 1; focus_menu = 1; } else menu.coi = 0; } for ( LDEuint i = 0; i < window.size(); ++i ) { if ( !window[i]->closed ) { window[i]->elements.input = input; window[i]->elements.mouse = mouse; window[i]->mouse = mouse; window[i]->app_size = app_size; window[i]->focus = 0; if ( focus_menu ) window[i]->coi = 0; else window[i]->cursorOnIt( cursor ); // Is this window on top of the others ? if ( i == window.size()-1 ) window[i]->on_top = 1; else window[i]->on_top = 0; // mouse clicks for ( LDEuint m = 0; m < mouse.size(); ++m ) { if ( mouse[m].left && mouse[m].down ) { if ( window[i]->coi ) { // Cursor's position on the window window[i]->pos_temp.x = cursor.x - window[i]->pos.x; window[i]->pos_temp.y = cursor.y - window[i]->pos.y; window[i]->clicked_away = 0; //if ( !focus_menu ) // window[i]->focus = 1; window[i]->wait = 1; focus_window = 1; } else window[i]->clicked_away = 1; } if ( mouse[m].left && !mouse[m].down ) { window[i]->wait = 0; window[i]->move = 0; } } // If the cursor is on the window if ( window[i]->coi ) { unused = 0; window[i]->focus = 1; // cette boucle est trop abusive for ( LDEuint u = 0; u < i; ++u ) window[u]->focus = 0; // les autres bases n'ont plus le focus } } } /// ///////// DRAW ////////////////// ////////////////////////////////////////////////////// // pannels tests for ( LDEuint i = 0; i < pannel.size(); ++i ) { pannel[i]->elements.mouse = mouse; pannel[i]->focus = 0; pannel[i]->cursorOnIt( cursor ); // mouse clicks for ( LDEuint m = 0; m < mouse.size(); ++m ) { if ( mouse[m].left && mouse[m].down ) { if ( !pannel[i]->coi ) pannel[i]->clicked_away = 1; else pannel[i]->clicked_away = 0; } if ( mouse[m].left && !mouse[m].down ) { pannel[i]->wait = 0; } } // If the cursor is on the pannel if ( pannel[i]->coi ) { if ( !focus_window && !focus_menu ) pannel[i]->focus = 1; pannel[i]->wait = 1; unused = 0; // cette boucle est trop abusive for ( LDEuint u = 0; u < i; ++u ) pannel[u]->focus = 0; // les autres bases n'ont plus le focus } } // Draw Pannels, zorder is creation order for ( LDEuint i = 0; i < pannel.size(); ++i ) { pannel[i]->draw( cursor, frametime ); } /// DRAW WINDOWS for ( LDEuint i = 0; i < window.size(); ++i ) { if ( !window[i]->closed ) { if ( window[i]->bringOnTop ) { window[i]->bringOnTop = 0; LDEgui_window *window_temp = window[i]; window.erase( window.begin() + i ); window.push_back( window_temp ); } if ( window[i]->on_top && !window[i]->clicked_away ) glBindTexture(GL_TEXTURE_2D, window[i]->texture->id); else { glBindTexture(GL_TEXTURE_2D, window[i]->texture_inactive->id ); } // mouse clicks for ( LDEuint m = 0; m < mouse.size(); ++m ) { if ( mouse[m].left && mouse[m].down ) { // If window is not on top and we clicked, bring it on top if ( window[i]->focus && !window[i]->clicked_away ) { LDEgui_window *window_temp = window[i]; window.erase( window.begin() + i ); window.push_back( window_temp ); if ( window[i]->wait ) window[i]->move = 1; } } if ( mouse[m].left && !mouse[m].down ) { window[i]->move = 0; } } if ( window[i]->move && window[i]->can_move && !window[i]->button_resize.pressed ) { window[i]->pos.x = cursor.x - window[i]->pos_temp.x; window[i]->pos.y = cursor.y - window[i]->pos_temp.y; } window[i]->draw( cursor, frametime ); } } if ( close_menu ) { for ( LDEuint i = 0; i < menu.button.size(); ++i ) { menu.button[i]->test_coi = focus_menu; menu.button[i]->mouse = mouse; menu.button[i]->draw( cursor, frametime ); } menu.close(); close_menu = 0; } if ( menu.button.size() ) { menu.changed = 0; glBindTexture(GL_TEXTURE_2D, texture_pannel->id); LDEcustomrectp( texture_pannel->size, vec4i(menu.pos.x - 21, menu.pos.y - 25, menu.size.x + 42, menu.size.y + 50), vec4i(30,30,30,30) ); if ( menu.selected > -1 ) if ( menu.button[menu.selected]->transp < 0.6 ) menu.button[menu.selected]->transp = 0.6; for ( LDEuint i = 0; i < menu.button.size(); ++i ) { menu.button[i]->x = menu.pos.x + menu.button[i]->pos.x; menu.button[i]->y = menu.pos.y + menu.button[i]->pos.y; menu.button[i]->test_coi = focus_menu; menu.button[i]->mouse = mouse; menu.button[i]->draw( cursor, frametime ); if ( menu.button[i]->click ) { menu.selected = i; close_menu = 1; menu.changed = 1; break; } } // mouse clicks for ( LDEuint m = 0; m < mouse.size(); ++m ) { if ( mouse[m].left && mouse[m].down && !menu.coi ) { menu.close(); } } } }
[ "happylde@gmail.com" ]
happylde@gmail.com
13e05e0b2536a1dbb544f3f5054886bc547940c2
62a7571b8e75e6228c5e08290e3e847ff9a07f94
/interfaces/salle.cpp
6bcc8de11be641bc892a0f4e3d41809d88819803
[]
no_license
g4145/smartcinema
ce38295a4f0ba2a7d355270c2c5b991b927b3765
687f4a2d7be8c519866c4afa6bb345ea6bc493ca
refs/heads/main
2023-02-10T13:45:49.283527
2021-01-10T10:22:03
2021-01-10T10:22:03
317,076,877
0
0
null
null
null
null
UTF-8
C++
false
false
7,372
cpp
#include "salle.h" #include <QSqlQuery> Salle::Salle(int id,QString nomsalle,int capacite,int numbloc ) { this->id=id; this->nomsalle=nomsalle; this->capacite=capacite; this->numbloc=numbloc; } Salle::~Salle() { } QString Salle::getnomsalle(){ return nomsalle; } void Salle::setnomsalle(QString nomsalle){ this->nomsalle=nomsalle; } int Salle::getId(){ return id; } void Salle::setId(int id){ this->id=id; } int Salle::getnumbloc(){ return numbloc; } void Salle::setnumbloc(int numbloc){ this->numbloc=numbloc; } int Salle::getcapacite(){ return capacite; } void Salle::setcapacite(int capacite){ this->capacite=capacite; } bool Salle::ajouter(){ QSqlQuery query; query.prepare("insert into salle (id,nom,prenom,date_naissance,salaire,email) values (:id,:nomsalle,:numbloc,:capacite)"); query.bindValue(":id",id); query.bindValue(":nomsalle",nomsalle); query.bindValue(":numbloc",numbloc); query.bindValue(":capacite",capacite); return query.exec(); } bool Salle::supprimer(int id){ QSqlQuery q; q.prepare("select * from salle where id=:id"); q.bindValue(":id",id); q.exec(); int total=0; //mch mawjoud mayfasakhch while(q.next()){ total++; } if(total==1){ QSqlQuery query; query.prepare("delete from salle where id=:id"); query.bindValue(":id",id); return query.exec(); } else{ return false; } } bool Salle::modifier(int idc){ QSqlQuery query; query.prepare("update salle set id=:id,nomsalle=:nomsalle,numbloc=:numbloc,capacite=:capacite where id=:idc"); query.bindValue(":id",id); query.bindValue(":nomsalle",nomsalle); query.bindValue(":numbloc",numbloc); query.bindValue(":capacite",capacite); query.bindValue(":idc",idc); return query.exec(); } QSqlQueryModel * Salle::afficher(){ QSqlQueryModel * model=new QSqlQueryModel(); model->setQuery("select * from salle"); model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID")); model->setHeaderData(1, Qt::Horizontal, QObject::tr("NOMSALLE")); return model; } QSqlQueryModel * Salle::chercher_Salle_par_nom(QString m) { {QSqlQueryModel *model = new QSqlQueryModel; model->setQuery("SELECT * FROM Salle WHERE NOMSALLE like '"+m+"%' "); model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID")); model->setHeaderData(1, Qt::Horizontal, QObject::tr("NOMSALLE")); model->setHeaderData(2, Qt::Horizontal, QObject::tr("NUMBLOC")); model->setHeaderData(3, Qt::Horizontal, QObject::tr("CAPACITE")); return model ; } } QSqlQueryModel *Salle::chercher_Salle_par_id(QString idd) { { QSqlQueryModel *model = new QSqlQueryModel; model->setQuery("SELECT * FROM Salle WHERE ID like '"+idd+"' "); model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID")); model->setHeaderData(1, Qt::Horizontal, QObject::tr("NOMSALLE")); model->setHeaderData(2, Qt::Horizontal, QObject::tr("NUMBLOC")); model->setHeaderData(3, Qt::Horizontal, QObject::tr("CAPACITE")); return model ; } } QSqlQueryModel * Salle::chercher_Salle_par_capacite(QString m) { {QSqlQueryModel *model = new QSqlQueryModel; model->setQuery("SELECT * FROM Salle WHERE capacite like '"+m+"%' "); model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID")); model->setHeaderData(1, Qt::Horizontal, QObject::tr("NOMSALLE")); model->setHeaderData(2, Qt::Horizontal, QObject::tr("NUMBLOC")); model->setHeaderData(3, Qt::Horizontal, QObject::tr("CAPACITE")); return model ; } } QSqlQueryModel* Salle:: trier() { //order by extract (year from date_naissance) QSqlQueryModel * model=new QSqlQueryModel(); model->setQuery("select * from Salle order by (date_naissance)DESC "); model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID")); model->setHeaderData(1, Qt::Horizontal, QObject::tr("NOMSALLE")); model->setHeaderData(2, Qt::Horizontal, QObject::tr("NUMBLOC")); model->setHeaderData(3, Qt::Horizontal, QObject::tr("CAPACITE")); return model; } QSqlQueryModel* Salle:: trier1() { QSqlQueryModel * model=new QSqlQueryModel(); model->setQuery("select * from Salle order by nomsalle "); model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID")); model->setHeaderData(1, Qt::Horizontal, QObject::tr("NOMSALLE")); model->setHeaderData(2, Qt::Horizontal, QObject::tr("NUMBLOC")); model->setHeaderData(3, Qt::Horizontal, QObject::tr("CAPACITE")); return model; } QSqlQueryModel* Salle:: trier2() { QSqlQueryModel * model=new QSqlQueryModel(); model->setQuery("select * from Salle order by capacite "); model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID")); model->setHeaderData(1, Qt::Horizontal, QObject::tr("NOMSALLE")); model->setHeaderData(2, Qt::Horizontal, QObject::tr("NUMBLOC")); model->setHeaderData(3, Qt::Horizontal, QObject::tr("CAPACITE")); return model; } /*Salle Salle::recherche_Id(int id){ QSqlQuery query; query.prepare("select *from Salle where id=:id"); query.bindValue(":id",id); query.exec(); Salle e; while(query.next()){ e.setId(query.value(0).toInt()); e.setnomsalle(query.value(1).toString()); e.setcapacite(query.value(2).toInt()); e.setnumbloc(query.value(3).toInt()); } return e; }*/ /*Salle Salle::recherche_mail(QString mail){ QSqlQuery query; query.prepare("select *from Salle where email like '"+mail+"' "); query.bindValue(":email",email); query.exec(); employe e; while(query.next()){ e.setId(query.value(0).toInt()); e.setNom(query.value(1).toString()); e.setPrenom(query.value(2).toString()); e.setDate_naissance(query.value(3).toDate()); e.setSalaire(query.value(4).toDouble()); e.setEmail(query.value(5).toString()); } return e; }*/ /* QSqlQueryModel* Salle::Filter(int){ QSqlQueryModel* model=new QSqlQueryModel(); QString res=QString::number(id); model->setQuery("select * from citoyen where sexe='"+res+"%'"); model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID")); model->setHeaderData(1, Qt::Horizontal, QObject::tr("NOM")); model->setHeaderData(2, Qt::Horizontal, QObject::tr("PRENOM")); model->setHeaderData(3, Qt::Horizontal, QObject::tr("SEXE")); model->setHeaderData(4, Qt::Horizontal, QObject::tr("DATE N")); return model; }*/ QStringList Salle::listeSalle(){ QSqlQuery query; query.prepare("select * from Salle"); query.exec(); QStringList list; while(query.next()){ list.append(query.value(0).toString()); } return list; } QStringList Salle::listSalle1(){ QSqlQuery query; query.prepare("select * from Salle"); query.exec(); QStringList list; while(query.next()){ list.append(query.value(5).toString()); } return list; } /* int Salle::calcul_Salle(int min, int max){ QSqlQuery query; query.prepare("select *from Salle where capacite between :min and :max"); query.bindValue(":min",min); query.bindValue(":max",max); query.exec(); int total=0; while(query.next()){ total++; } return total; }*/
[ "yassine.brahmi@esprit.tn" ]
yassine.brahmi@esprit.tn
c90d0f93034814c0e83f1b479605ff4415cd1618
0123e81421499171e9a8181edd873ac748f75cc5
/testA3/gui/testA3mw.h
772904bbb0ed70ed2b30dc1525eb7d4a1362679c
[]
no_license
VirusRushTheater/WhimsyAudio
516bbaa032af63a9505f80624502835a3bb07ffc
4df31b7f3f4a2c4e81844bedb5735af70fc9373b
refs/heads/master
2021-01-12T01:48:00.055360
2017-01-10T17:22:56
2017-01-10T17:22:56
78,432,747
5
1
null
null
null
null
UTF-8
C++
false
false
445
h
#include <QWidget> #include <QTextEdit> #include <QPushButton> #include <QGridLayout> #include <QSpinBox> #include <QSlider> #include <QDebug> #include <QLabel> #include <QComboBox> #include "../portaudio_engine/scopedPAContext.h" class TestA3MW : public QWidget { Q_OBJECT public: TestA3MW(QWidget* parent = NULL); ~TestA3MW(); void setPortAudioContext(ScopedPAContext* pactx); private: ScopedPAContext* _pactx; };
[ "virusrushtheater@gmail.com" ]
virusrushtheater@gmail.com
49d4bd99db77f439e574db1410936f51c49fa15d
86b55c5bfd3cbce99db30907ecc63c0038b0f1e2
/gpu/command_buffer/service/shared_image_backing_gl_image.cc
f2593def3206ceb802a780d7e3b984485e145797
[ "BSD-3-Clause" ]
permissive
Claw-Lang/chromium
3ed8160ea3f2b5d51fdc2a7d764aadd5b443eb3f
651cebac57fcd0ce2c7c974494602cc098fe7348
refs/heads/master
2022-11-19T07:46:03.573023
2020-07-28T06:45:27
2020-07-28T06:45:27
283,134,740
1
0
BSD-3-Clause
2020-07-28T07:26:49
2020-07-28T07:26:48
null
UTF-8
C++
false
false
23,569
cc
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gpu/command_buffer/service/shared_image_backing_gl_image.h" #include "base/trace_event/memory_dump_manager.h" #include "build/build_config.h" #include "components/viz/common/resources/resource_format_utils.h" #include "components/viz/common/resources/resource_sizes.h" #include "gpu/command_buffer/common/shared_image_trace_utils.h" #include "gpu/command_buffer/common/shared_image_usage.h" #include "gpu/command_buffer/service/mailbox_manager.h" #include "gpu/command_buffer/service/shared_context_state.h" #include "gpu/command_buffer/service/skia_utils.h" #include "third_party/skia/include/core/SkPromiseImageTexture.h" #include "ui/gl/gl_context.h" #include "ui/gl/gl_fence.h" #include "ui/gl/gl_gl_api_implementation.h" #include "ui/gl/trace_util.h" #if defined(OS_MACOSX) #include "gpu/command_buffer/service/shared_image_backing_factory_iosurface.h" #endif namespace gpu { namespace { size_t EstimatedSize(viz::ResourceFormat format, const gfx::Size& size) { size_t estimated_size = 0; viz::ResourceSizes::MaybeSizeInBytes(size, format, &estimated_size); return estimated_size; } using UnpackStateAttribs = SharedImageBackingGLCommon::UnpackStateAttribs; using ScopedResetAndRestoreUnpackState = SharedImageBackingGLCommon::ScopedResetAndRestoreUnpackState; using ScopedRestoreTexture = SharedImageBackingGLCommon::ScopedRestoreTexture; using InitializeGLTextureParams = SharedImageBackingGLCommon::InitializeGLTextureParams; } // namespace /////////////////////////////////////////////////////////////////////////////// // SharedImageRepresentationGLTextureImpl // Representation of a SharedImageBackingGLTexture as a GL Texture. SharedImageRepresentationGLTextureImpl::SharedImageRepresentationGLTextureImpl( SharedImageManager* manager, SharedImageBacking* backing, SharedImageRepresentationGLTextureClient* client, MemoryTypeTracker* tracker, gles2::Texture* texture) : SharedImageRepresentationGLTexture(manager, backing, tracker), client_(client), texture_(texture) {} SharedImageRepresentationGLTextureImpl:: ~SharedImageRepresentationGLTextureImpl() { texture_ = nullptr; if (client_) client_->SharedImageRepresentationGLTextureRelease(has_context()); } gles2::Texture* SharedImageRepresentationGLTextureImpl::GetTexture() { return texture_; } bool SharedImageRepresentationGLTextureImpl::BeginAccess(GLenum mode) { if (client_ && mode != GL_SHARED_IMAGE_ACCESS_MODE_OVERLAY_CHROMIUM) return client_->SharedImageRepresentationGLTextureBeginAccess(); return true; } void SharedImageRepresentationGLTextureImpl::EndAccess() { if (client_) return client_->SharedImageRepresentationGLTextureEndAccess(); } /////////////////////////////////////////////////////////////////////////////// // SharedImageRepresentationGLTexturePassthroughImpl SharedImageRepresentationGLTexturePassthroughImpl:: SharedImageRepresentationGLTexturePassthroughImpl( SharedImageManager* manager, SharedImageBacking* backing, SharedImageRepresentationGLTextureClient* client, MemoryTypeTracker* tracker, scoped_refptr<gles2::TexturePassthrough> texture_passthrough) : SharedImageRepresentationGLTexturePassthrough(manager, backing, tracker), client_(client), texture_passthrough_(std::move(texture_passthrough)) {} SharedImageRepresentationGLTexturePassthroughImpl:: ~SharedImageRepresentationGLTexturePassthroughImpl() { texture_passthrough_.reset(); if (client_) client_->SharedImageRepresentationGLTextureRelease(has_context()); } const scoped_refptr<gles2::TexturePassthrough>& SharedImageRepresentationGLTexturePassthroughImpl::GetTexturePassthrough() { return texture_passthrough_; } bool SharedImageRepresentationGLTexturePassthroughImpl::BeginAccess( GLenum mode) { if (client_ && mode != GL_SHARED_IMAGE_ACCESS_MODE_OVERLAY_CHROMIUM) return client_->SharedImageRepresentationGLTextureBeginAccess(); return true; } void SharedImageRepresentationGLTexturePassthroughImpl::EndAccess() { if (client_) return client_->SharedImageRepresentationGLTextureEndAccess(); } /////////////////////////////////////////////////////////////////////////////// // SharedImageRepresentationSkiaImpl SharedImageRepresentationSkiaImpl::SharedImageRepresentationSkiaImpl( SharedImageManager* manager, SharedImageBacking* backing, SharedImageRepresentationGLTextureClient* client, scoped_refptr<SharedContextState> context_state, sk_sp<SkPromiseImageTexture> promise_texture, MemoryTypeTracker* tracker) : SharedImageRepresentationSkia(manager, backing, tracker), client_(client), context_state_(std::move(context_state)), promise_texture_(promise_texture) { DCHECK(promise_texture_); #if DCHECK_IS_ON() if (context_state_->GrContextIsGL()) context_ = gl::GLContext::GetCurrent(); #endif } SharedImageRepresentationSkiaImpl::~SharedImageRepresentationSkiaImpl() { if (write_surface_) { DLOG(ERROR) << "SharedImageRepresentationSkia was destroyed while still " << "open for write access."; } promise_texture_.reset(); if (client_) { DCHECK(context_state_->GrContextIsGL()); client_->SharedImageRepresentationGLTextureRelease(has_context()); } } sk_sp<SkSurface> SharedImageRepresentationSkiaImpl::BeginWriteAccess( int final_msaa_count, const SkSurfaceProps& surface_props, std::vector<GrBackendSemaphore>* begin_semaphores, std::vector<GrBackendSemaphore>* end_semaphores) { CheckContext(); if (client_) { DCHECK(context_state_->GrContextIsGL()); if (!client_->SharedImageRepresentationGLTextureBeginAccess()) return nullptr; } if (write_surface_) return nullptr; if (!promise_texture_) return nullptr; SkColorType sk_color_type = viz::ResourceFormatToClosestSkColorType( /*gpu_compositing=*/true, format()); auto surface = SkSurface::MakeFromBackendTexture( context_state_->gr_context(), promise_texture_->backendTexture(), surface_origin(), final_msaa_count, sk_color_type, backing()->color_space().ToSkColorSpace(), &surface_props); write_surface_ = surface.get(); return surface; } void SharedImageRepresentationSkiaImpl::EndWriteAccess( sk_sp<SkSurface> surface) { DCHECK_EQ(surface.get(), write_surface_); DCHECK(surface->unique()); CheckContext(); // TODO(ericrk): Keep the surface around for re-use. write_surface_ = nullptr; if (client_) client_->SharedImageRepresentationGLTextureEndAccess(); } sk_sp<SkPromiseImageTexture> SharedImageRepresentationSkiaImpl::BeginReadAccess( std::vector<GrBackendSemaphore>* begin_semaphores, std::vector<GrBackendSemaphore>* end_semaphores) { CheckContext(); if (client_) { DCHECK(context_state_->GrContextIsGL()); if (!client_->SharedImageRepresentationGLTextureBeginAccess()) return nullptr; } return promise_texture_; } void SharedImageRepresentationSkiaImpl::EndReadAccess() { if (client_) client_->SharedImageRepresentationGLTextureEndAccess(); } bool SharedImageRepresentationSkiaImpl::SupportsMultipleConcurrentReadAccess() { return true; } void SharedImageRepresentationSkiaImpl::CheckContext() { #if DCHECK_IS_ON() if (context_) DCHECK(gl::GLContext::GetCurrent() == context_); #endif } /////////////////////////////////////////////////////////////////////////////// // SharedImageRepresentationOverlayImpl SharedImageRepresentationOverlayImpl::SharedImageRepresentationOverlayImpl( SharedImageManager* manager, SharedImageBacking* backing, MemoryTypeTracker* tracker, scoped_refptr<gl::GLImage> gl_image) : SharedImageRepresentationOverlay(manager, backing, tracker), gl_image_(gl_image) {} SharedImageRepresentationOverlayImpl::~SharedImageRepresentationOverlayImpl() = default; bool SharedImageRepresentationOverlayImpl::BeginReadAccess() { return true; } void SharedImageRepresentationOverlayImpl::EndReadAccess() {} gl::GLImage* SharedImageRepresentationOverlayImpl::GetGLImage() { return gl_image_.get(); } /////////////////////////////////////////////////////////////////////////////// // SharedImageBackingGLImage SharedImageBackingGLImage::SharedImageBackingGLImage( scoped_refptr<gl::GLImage> image, const Mailbox& mailbox, viz::ResourceFormat format, const gfx::Size& size, const gfx::ColorSpace& color_space, GrSurfaceOrigin surface_origin, SkAlphaType alpha_type, uint32_t usage, const InitializeGLTextureParams& params, const UnpackStateAttribs& attribs, bool is_passthrough) : SharedImageBacking(mailbox, format, size, color_space, surface_origin, alpha_type, usage, EstimatedSize(format, size), false /* is_thread_safe */), image_(image), gl_params_(params), gl_unpack_attribs_(attribs), is_passthrough_(is_passthrough), cleared_rect_(params.is_cleared ? gfx::Rect(size) : gfx::Rect()), weak_factory_(this) { DCHECK(image_); } SharedImageBackingGLImage::~SharedImageBackingGLImage() { if (gl_texture_retained_for_legacy_mailbox_) ReleaseGLTexture(have_context()); DCHECK_EQ(gl_texture_retain_count_, 0u); } void SharedImageBackingGLImage::RetainGLTexture() { gl_texture_retain_count_ += 1; if (gl_texture_retain_count_ > 1) return; // Allocate the GL texture. SharedImageBackingGLCommon::MakeTextureAndSetParameters( gl_params_.target, 0 /* service_id */, gl_params_.framebuffer_attachment_angle, is_passthrough_ ? &passthrough_texture_ : nullptr, is_passthrough_ ? nullptr : &texture_); // Set the GLImage to be initially unbound from the GL texture. image_bind_or_copy_needed_ = true; if (is_passthrough_) { passthrough_texture_->SetEstimatedSize(EstimatedSize(format(), size())); passthrough_texture_->SetLevelImage(gl_params_.target, 0, image_.get()); passthrough_texture_->set_is_bind_pending(true); } else { texture_->SetLevelInfo(gl_params_.target, 0, gl_params_.internal_format, size().width(), size().height(), 1, 0, gl_params_.format, gl_params_.type, cleared_rect_); texture_->SetLevelImage(gl_params_.target, 0, image_.get(), gles2::Texture::UNBOUND); texture_->SetImmutable(true, false /* has_immutable_storage */); } } void SharedImageBackingGLImage::ReleaseGLTexture(bool have_context) { DCHECK_GT(gl_texture_retain_count_, 0u); gl_texture_retain_count_ -= 1; if (gl_texture_retain_count_ > 0) return; // If the cached promise texture is referencing the GL texture, then it needs // to be deleted, too. if (cached_promise_texture_) { if (cached_promise_texture_->backendTexture().backend() == GrBackendApi::kOpenGL) { cached_promise_texture_.reset(); } } if (rgb_emulation_texture_) { rgb_emulation_texture_->RemoveLightweightRef(have_context); rgb_emulation_texture_ = nullptr; } if (IsPassthrough()) { if (passthrough_texture_) { if (!have_context) passthrough_texture_->MarkContextLost(); passthrough_texture_.reset(); } } else { if (texture_) { cleared_rect_ = texture_->GetLevelClearedRect(texture_->target(), 0); texture_->RemoveLightweightRef(have_context); texture_ = nullptr; } } } GLenum SharedImageBackingGLImage::GetGLTarget() const { return gl_params_.target; } GLuint SharedImageBackingGLImage::GetGLServiceId() const { if (texture_) return texture_->service_id(); if (passthrough_texture_) return passthrough_texture_->service_id(); return 0; } scoped_refptr<gfx::NativePixmap> SharedImageBackingGLImage::GetNativePixmap() { return image_->GetNativePixmap(); } void SharedImageBackingGLImage::OnMemoryDump( const std::string& dump_name, base::trace_event::MemoryAllocatorDump* dump, base::trace_event::ProcessMemoryDump* pmd, uint64_t client_tracing_id) { // Add a |service_guid| which expresses shared ownership between the // various GPU dumps. auto client_guid = GetSharedImageGUIDForTracing(mailbox()); if (auto service_id = GetGLServiceId()) { auto service_guid = gl::GetGLTextureServiceGUIDForTracing(GetGLServiceId()); pmd->CreateSharedGlobalAllocatorDump(service_guid); // TODO(piman): coalesce constant with TextureManager::DumpTextureRef. int importance = 2; // This client always owns the ref. pmd->AddOwnershipEdge(client_guid, service_guid, importance); } image_->OnMemoryDump(pmd, client_tracing_id, dump_name); } gfx::Rect SharedImageBackingGLImage::ClearedRect() const { if (texture_) return texture_->GetLevelClearedRect(texture_->target(), 0); return cleared_rect_; } void SharedImageBackingGLImage::SetClearedRect(const gfx::Rect& cleared_rect) { if (texture_) texture_->SetLevelClearedRect(texture_->target(), 0, cleared_rect); else cleared_rect_ = cleared_rect; } bool SharedImageBackingGLImage::ProduceLegacyMailbox( MailboxManager* mailbox_manager) { if (!gl_texture_retained_for_legacy_mailbox_) { RetainGLTexture(); gl_texture_retained_for_legacy_mailbox_ = true; } if (IsPassthrough()) mailbox_manager->ProduceTexture(mailbox(), passthrough_texture_.get()); else mailbox_manager->ProduceTexture(mailbox(), texture_); return true; } std::unique_ptr<SharedImageRepresentationGLTexture> SharedImageBackingGLImage::ProduceGLTexture(SharedImageManager* manager, MemoryTypeTracker* tracker) { // The corresponding release will be done when the returned representation is // destroyed, in SharedImageRepresentationGLTextureRelease. RetainGLTexture(); DCHECK(texture_); return std::make_unique<SharedImageRepresentationGLTextureImpl>( manager, this, this, tracker, texture_); } std::unique_ptr<SharedImageRepresentationGLTexturePassthrough> SharedImageBackingGLImage::ProduceGLTexturePassthrough( SharedImageManager* manager, MemoryTypeTracker* tracker) { // The corresponding release will be done when the returned representation is // destroyed, in SharedImageRepresentationGLTextureRelease. RetainGLTexture(); DCHECK(passthrough_texture_); return std::make_unique<SharedImageRepresentationGLTexturePassthroughImpl>( manager, this, this, tracker, passthrough_texture_); } std::unique_ptr<SharedImageRepresentationOverlay> SharedImageBackingGLImage::ProduceOverlay(SharedImageManager* manager, MemoryTypeTracker* tracker) { #if defined(OS_MACOSX) return std::make_unique<SharedImageRepresentationOverlayImpl>( manager, this, tracker, image_); #else // defined(OS_MACOSX) return SharedImageBacking::ProduceOverlay(manager, tracker); #endif // !defined(OS_MACOSX) } std::unique_ptr<SharedImageRepresentationDawn> SharedImageBackingGLImage::ProduceDawn(SharedImageManager* manager, MemoryTypeTracker* tracker, WGPUDevice device) { #if defined(OS_MACOSX) auto result = SharedImageBackingFactoryIOSurface::ProduceDawn( manager, this, tracker, device, image_); if (result) return result; #endif // defined(OS_MACOSX) if (!factory()) { DLOG(ERROR) << "No SharedImageFactory to create a dawn representation."; return nullptr; } return SharedImageBackingGLCommon::ProduceDawnCommon( factory(), manager, tracker, device, this, IsPassthrough()); } std::unique_ptr<SharedImageRepresentationSkia> SharedImageBackingGLImage::ProduceSkia( SharedImageManager* manager, MemoryTypeTracker* tracker, scoped_refptr<SharedContextState> context_state) { SharedImageRepresentationGLTextureClient* gl_client = nullptr; if (context_state->GrContextIsGL()) { // The corresponding release will be done when the returned representation // is destroyed, in SharedImageRepresentationGLTextureRelease. RetainGLTexture(); gl_client = this; } if (!cached_promise_texture_) { if (context_state->GrContextIsMetal()) { #if defined(OS_MACOSX) cached_promise_texture_ = SharedImageBackingFactoryIOSurface::ProduceSkiaPromiseTextureMetal( this, context_state, image_); DCHECK(cached_promise_texture_); #endif } else { GrBackendTexture backend_texture; GetGrBackendTexture(context_state->feature_info(), GetGLTarget(), size(), GetGLServiceId(), format(), &backend_texture); cached_promise_texture_ = SkPromiseImageTexture::Make(backend_texture); } } return std::make_unique<SharedImageRepresentationSkiaImpl>( manager, this, gl_client, std::move(context_state), cached_promise_texture_, tracker); } std::unique_ptr<SharedImageRepresentationGLTexture> SharedImageBackingGLImage::ProduceRGBEmulationGLTexture( SharedImageManager* manager, MemoryTypeTracker* tracker) { if (IsPassthrough()) return nullptr; RetainGLTexture(); if (!rgb_emulation_texture_) { const GLenum target = GetGLTarget(); gl::GLApi* api = gl::g_current_gl_context; ScopedRestoreTexture scoped_restore(api, target); // Set to false as this code path is only used on Mac. const bool framebuffer_attachment_angle = false; SharedImageBackingGLCommon::MakeTextureAndSetParameters( target, 0 /* service_id */, framebuffer_attachment_angle, nullptr, &rgb_emulation_texture_); api->glBindTextureFn(target, rgb_emulation_texture_->service_id()); gles2::Texture::ImageState image_state = gles2::Texture::BOUND; gl::GLImage* image = texture_->GetLevelImage(target, 0, &image_state); DCHECK_EQ(image, image_.get()); DCHECK(image->ShouldBindOrCopy() == gl::GLImage::BIND); const GLenum internal_format = GL_RGB; if (!image->BindTexImageWithInternalformat(target, internal_format)) { LOG(ERROR) << "Failed to bind image to rgb texture."; rgb_emulation_texture_->RemoveLightweightRef(true /* have_context */); rgb_emulation_texture_ = nullptr; ReleaseGLTexture(true /* has_context */); return nullptr; } GLenum format = gles2::TextureManager::ExtractFormatFromStorageFormat(internal_format); GLenum type = gles2::TextureManager::ExtractTypeFromStorageFormat(internal_format); const gles2::Texture::LevelInfo* info = texture_->GetLevelInfo(target, 0); rgb_emulation_texture_->SetLevelInfo(target, 0, internal_format, info->width, info->height, 1, 0, format, type, info->cleared_rect); rgb_emulation_texture_->SetLevelImage(target, 0, image, image_state); rgb_emulation_texture_->SetImmutable(true, false); } return std::make_unique<SharedImageRepresentationGLTextureImpl>( manager, this, this, tracker, rgb_emulation_texture_); } void SharedImageBackingGLImage::Update( std::unique_ptr<gfx::GpuFence> in_fence) { if (in_fence) { // TODO(dcastagna): Don't wait for the fence if the SharedImage is going // to be scanned out as an HW overlay. Currently we don't know that at // this point and we always bind the image, therefore we need to wait for // the fence. std::unique_ptr<gl::GLFence> egl_fence = gl::GLFence::CreateFromGpuFence(*in_fence.get()); egl_fence->ServerWait(); } image_bind_or_copy_needed_ = true; } bool SharedImageBackingGLImage:: SharedImageRepresentationGLTextureBeginAccess() { return BindOrCopyImageIfNeeded(); } void SharedImageBackingGLImage::SharedImageRepresentationGLTextureEndAccess() { #if defined(OS_MACOSX) // If this image could potentially be shared with Metal via WebGPU, then flush // the GL context to ensure Metal will see it. if (usage() & SHARED_IMAGE_USAGE_WEBGPU) { gl::GLApi* api = gl::g_current_gl_context; api->glFlushFn(); } #endif } void SharedImageBackingGLImage::SharedImageRepresentationGLTextureRelease( bool has_context) { ReleaseGLTexture(has_context); } bool SharedImageBackingGLImage::BindOrCopyImageIfNeeded() { // This is called by code that has retained the GL texture. DCHECK(texture_ || passthrough_texture_); if (!image_bind_or_copy_needed_) return true; const GLenum target = GetGLTarget(); gl::GLApi* api = gl::g_current_gl_context; ScopedRestoreTexture scoped_restore(api, target); api->glBindTextureFn(target, GetGLServiceId()); // Un-bind the GLImage from the texture if it is currently bound. if (image_->ShouldBindOrCopy() == gl::GLImage::BIND) { bool is_bound = false; if (IsPassthrough()) { is_bound = !passthrough_texture_->is_bind_pending(); } else { gles2::Texture::ImageState old_state = gles2::Texture::UNBOUND; texture_->GetLevelImage(target, 0, &old_state); is_bound = old_state == gles2::Texture::BOUND; } if (is_bound) image_->ReleaseTexImage(target); } // Bind or copy the GLImage to the texture. gles2::Texture::ImageState new_state = gles2::Texture::UNBOUND; if (image_->ShouldBindOrCopy() == gl::GLImage::BIND) { if (gl_params_.is_rgb_emulation) { if (!image_->BindTexImageWithInternalformat(target, GL_RGB)) { LOG(ERROR) << "Failed to bind GLImage to RGB target"; return false; } } else { if (!image_->BindTexImage(target)) { LOG(ERROR) << "Failed to bind GLImage to target"; return false; } } new_state = gles2::Texture::BOUND; } else { ScopedResetAndRestoreUnpackState scoped_unpack_state(api, gl_unpack_attribs_, /*upload=*/true); if (!image_->CopyTexImage(target)) { LOG(ERROR) << "Failed to copy GLImage to target"; return false; } new_state = gles2::Texture::COPIED; } if (IsPassthrough()) { passthrough_texture_->set_is_bind_pending(new_state == gles2::Texture::UNBOUND); } else { texture_->SetLevelImage(target, 0, image_.get(), new_state); } image_bind_or_copy_needed_ = false; return true; } void SharedImageBackingGLImage::InitializePixels(GLenum format, GLenum type, const uint8_t* data) { DCHECK_EQ(image_->ShouldBindOrCopy(), gl::GLImage::BIND); #if defined(OS_MACOSX) if (SharedImageBackingFactoryIOSurface::InitializePixels(this, image_, data)) return; #else RetainGLTexture(); BindOrCopyImageIfNeeded(); const GLenum target = GetGLTarget(); gl::GLApi* api = gl::g_current_gl_context; ScopedRestoreTexture scoped_restore(api, target); api->glBindTextureFn(target, GetGLServiceId()); ScopedResetAndRestoreUnpackState scoped_unpack_state( api, gl_unpack_attribs_, true /* uploading_data */); api->glTexSubImage2DFn(target, 0, 0, 0, size().width(), size().height(), format, type, data); ReleaseGLTexture(true /* have_context */); #endif } } // namespace gpu
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
e7fdd063828673c96a68b0ad7275989c13c8ecd8
b94bc1eccf537f95f994c71bf80932aa23c8042e
/src/GripPipeline.h
b007de2fb9a47b0891d84d87808bdc1ebcd70f00
[]
no_license
Team3655/Phyllis-7.0
06e2d7df3b6e10cf53037bfbaf942139eebae411
3ef9cd20eb1590f5513c5aba92fecd50046f2527
refs/heads/master
2021-01-12T02:09:32.268658
2017-04-30T03:43:57
2017-04-30T03:43:57
78,480,278
2
7
null
2017-04-06T03:59:38
2017-01-09T23:54:38
C++
UTF-8
C++
false
false
2,004
h
#ifndef GRIP_PIPELINE_H #define GRIP_PIPELINE_H #include <opencv2/objdetect/objdetect.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/core/core.hpp> #include <opencv2/features2d.hpp> #include <iostream> #include <stdio.h> #include <stdlib.h> #include <map> #include <vector> #include <string> #include <math.h> #include <Timer.h> #include <CameraServer.h> #include "Logger.h" namespace grip { // Summary: // struct CameraStuff { double targetHeight; double angle; CameraStuff(double height, double angle) { targetHeight = height; this->angle = angle; } CameraStuff() { targetHeight = 0; this->angle = 0; } }; #define PEG grip::CameraStuff(CS_TARGET_PEG_HEIGHT, CS_CAM1_HORIZON_ANGLE, grip::Target::kPeg) // Summary: // class GripPipeline { public: cv::Mat resizeImageOutput; cv::Mat hslThresholdOutput; std::vector<std::vector<cv::Point>> findContoursOutput; std::vector<std::vector<cv::Point>> filterContoursOutput; std::vector<cv::Rect> targets; frc::Timer* timer; double procTime; CameraStuff stuff; Logger* m_log; void findContours(cv::Mat&, bool, std::vector<std::vector<cv::Point>>&); void filterContours( std::vector<std::vector<cv::Point>>& inputContours, const double minArea, const double minPerimeter, const double minWidth, const double maxWidth, const double minHeight, const double maxHeight, const double solidity[], const double maxVertexCount, const double minVertexCount, const double minRatio, const double maxRatio, std::vector<std::vector<cv::Point>>& output); public: GripPipeline(); void Process(cv::Mat& source); bool getTarget(int, cv::Rect&); double getTargetCenterX(int); double getTargetCenterY(int); double getProcTime(); double getDistance(); cv::Mat& getProcessedFrame() { return hslThresholdOutput; } int getTargets() { return targets.size(); } void setStuff(grip::CameraStuff cs); }; } // end namespace grip #endif // GRIP_PIPELINE_H
[ "agnewsilas@gmail.com" ]
agnewsilas@gmail.com
a72f6d44d9ffaf33c9ef8d75df5685f54abbaa02
cf28facb7ad9cc7eeeed780a9173ca8f98289ef5
/empery_center/src/captain_item_attribute_ids.hpp
4da26bdf18f5c9db55f51a872cac9759a7d3d315
[]
no_license
kspine/referance_solution
aafa5204f3ef840d281e814aa0eeb210ffcf7633
d667f7402cf951ce4784a19aa5619de80245e5f3
refs/heads/master
2021-01-22T05:16:26.760739
2017-02-10T06:41:54
2017-02-10T06:41:54
81,633,340
0
0
null
null
null
null
UTF-8
C++
false
false
482
hpp
#ifndef EMPERY_CENTER_CAPTAIN_ITEM_ATTRIBUTE_IDS_HPP_ #define EMPERY_CENTER_CAPTAIN_ITEM_ATTRIBUTE_IDS_HPP_ #include "id_types.hpp" namespace EmperyCenter { namespace CaptainItemAttributeIds { constexpr CaptainItemAttributeId ID_BEGIN(0), ID_CUSTOM_PUBLIC_END(100), ID_CUSTOM_END(200), ID_PUBLIC_END(300), ID_END(500), ID_BASEID(101), ID_INUSE(102), ID_LEVEL(103), ID_QUALITY(104), ID_ATTRIBUTE(105), ID_AFFIX_ATTRIBUTE(106); } } #endif
[ "root@debian" ]
root@debian
c6b6ab51a48d26097a89f539d3987d079a17d986
7140b7ba22072062fbf77569b753691fe65e2a9b
/CPP/AlgoNotes/chap08/277.cpp
677d4b8d7082bb8d6d8c82f88b7e5665e18453bf
[]
no_license
mosqlwj/workspace_2019
0c2fccd68f7cef5d6782296398827de8ead3758f
5685213b5a66327f3e42443538af4fef35368979
refs/heads/master
2022-01-23T09:02:53.385864
2019-06-12T13:11:09
2019-06-12T13:11:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,766
cpp
// // Created by lenovo on 2019/5/14. // //bfs /* #include <iostream> #include <queue> using namespace std; const int maxn = 100; struct node { int x; int y; } Node; int n = 6, m = 7; int matrix[maxn][maxn] = {{0, 1, 1, 1, 0, 0, 1}, {0, 0, 1, 0, 0, 0, 0}, {0, 0, 0, 0, 1, 0, 0}, {0, 0, 0, 1, 1, 1, 0}, {1, 1, 1, 0, 1, 0, 1}, {1, 1, 1, 1, 0, 0, 0}}; bool inq[maxn][maxn] = {false}; int X[4] = {0, 0, 1, -1}; int Y[4] = {1, -1, 0, 0}; bool judge(int x, int y) { if (x < 0 || x >= n || y < 0 || y >= m) { return false; } if (matrix[x][y] == 0 || inq[x][y] == true) { return false; } return true; } void BFS(int x, int y) { queue<node> Q; Node.x = x; Node.y = y; Q.push(Node); inq[x][y] = true; while (!Q.empty()) { node cur = Q.front(); Q.pop(); for (int i = 0; i < 4; ++i) { int newX = cur.x + X[i]; int newY = cur.y + Y[i]; if (judge(newX, newY)) { Node.x = newX; Node.y = newY; Q.push(Node); inq[newX][newY] = true; } } } } void DFS(int x, int y) { if (!judge(x, y)) { return; } inq[x][y] = true; DFS(x + 1, y); DFS(x, y + 1); DFS(x - 1, y); DFS(x, y - 1); } int main() { int ans = 0; for (int x = 0; x < n; ++x) { for (int y = 0; y < m; ++y) { if (matrix[x][y] == 1 && inq[x][y] == false) { ans++; //BFS(x, y); DFS(x, y); } } } cout << ans << endl; return 0; } */
[ "liwenjie_0121@163.com" ]
liwenjie_0121@163.com
932480814df34e1393cc7874e2055bc97a2d79b3
64e2fed5173f3d073e5fbd224d0bd5fd4f20815b
/3-CS-DQ-Greedy/problems/codeforces/max-distance/maxdist.cpp
47e7aff02ce5c03e6b2ac3165b3fee3d5cd38256
[]
no_license
aldonavarretefp/slides-code
8db375eec294ce571770a91b6d9e93ae35319b50
860e25f04e5a801ab818b76a071df3ea1df87479
refs/heads/main
2023-09-03T20:29:42.723685
2021-10-23T16:48:12
2021-10-23T16:48:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,572
cpp
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; template <typename T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; #define endl '\n' #define fastIO() cin.tie(0); cout.tie(0); #define FO(i, b) for (int i = 0; i < (b); i++) #define FOR(i, a, b) for (int i = (a); i < (b); i++) #define rFOR(i, a, b) for (int i = (a); i > (b); i--) #define TR(v, arr) for (auto& (v) : (arr)) #define debug(x) cout << #x << " = "; _debug(x); cout << endl; #define si(x) scanf("%d",&x) #define sl(x) scanf("%lld",&x) #define pi(x) printf("%d\n",x) #define pl(x) printf("%lld\n",x) #define pb push_back #define mp make_pair #define F first #define S second #define all(x) x.begin(), x.end() #define sz(x) (int) x.size() #define LB(arr, x) lower_bound(all(arr), x)-(arr).begin() #define UB(arr, x) upper_bound(all(arr), x)-(arr).begin() typedef long long ll; typedef vector<int> vi; typedef vector<ll> vll; typedef pair<int, int> pii; typedef pair<ll, ll> pll; const ll MOD = 1e9 + 7; const ll INF = 1e9; void setIO(){ string file = __FILE__; file = string(file.begin(), file.end()-3); string in_file = file+"in"; string out_file = file+"out"; freopen(in_file.c_str(), "r", stdin); freopen(out_file.c_str(), "w", stdout); } template <typename T> void _debug(T& x){ cout << x; } template <typename T1, typename T2> void _debug(pair<T1, T2>& pair){ cout << "{"; _debug(pair.F); cout << ","; _debug(pair.S); cout << "}"; } template <typename T> void _debug(vector<T>& vec){ int n = sz(vec); if(n == 0){cout << "[ ]"; return;} cout << "["; FO(i, n-1){ _debug(vec[i]); cout << " "; } _debug(vec[n-1]); cout << "]"; } void _debug(vector<string>& vec){ int n = sz(vec); cout << endl; FO(i, n){ cout << vec[i] << endl; } } template <typename T> void _debug(vector<vector<T>>& A){ int n = sz(A); cout << endl; FO(i, n){ _debug(A[i]); cout << endl; } } template <typename T> void print(T& x){ cout << x << endl; return; } template <typename T> void print(vector<T>& vec, int a=0, int b=-1){ if(b == -1){b = sz(vec);} if(b == 0){return;} FOR(i, a, b-1){ cout << vec[i] << " "; } cout << vec[b-1] << endl; return; } // ----------------------------------------------------------------------------- // Solution starts here // ----------------------------------------------------------------------------- /* General D = sqrt( (x_0 - y_0)^2 + ... + (x_n - y_n)^2) D^2 = (x_0 - y_0)^2 + ... + (x_n - y_n)^2 */ void solve() { int n; si(n); vi X(n); FO(i, n) si(X[i]); vi Y(n); FO(i, n) si(Y[i]); int ans = -1000000; for(int i = 0; i < n; i++) { for(int j = i+1; j < n; j++) { int ed = pow((X[i] - X[j]),2) + pow(Y[i] - Y[j], 2); ans = max(ans, ed); } } cout << ans << endl; return; } int main() { fastIO(); if(getenv("LOCAL")){setIO();} int T = 1; FO(i, T) { solve(); } return 0; }
[ "nestor.martinez.98@hotmail.com" ]
nestor.martinez.98@hotmail.com
9d3ec72e9f934b675e19118edd71e044b577d185
9b1a0e9ac2c5ffc35f368ca5108cd8953eb2716d
/4/01 General Programming/12 My/Dialogs/DlgEditSphere.cpp
30347f36b34d037884baa8f6ecef242b8834ddc9
[]
no_license
TomasRejhons/gpg-source-backup
c6993579e96bf5a6d8cba85212f94ec20134df11
bbc8266c6cd7df8a7e2f5ad638cdcd7f6298052e
refs/heads/main
2023-06-05T05:14:00.374344
2021-06-16T15:08:41
2021-06-16T15:08:41
377,536,509
2
2
null
null
null
null
UTF-8
C++
false
false
3,077
cpp
// DlgEditSphere.cpp : implementation file // #include "stdafx.h" #include "..\RTTIProps.h" #include "DlgEditSphere.h" #include "EngineMaterial.h" #include "DlgChooseMaterial.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif // static members float CDlgEditSphere::fPosX = 0.f; float CDlgEditSphere::fPosY = 0.f; float CDlgEditSphere::fPosZ = 0.f; float CDlgEditSphere::fRadius = 1.f; UINT CDlgEditSphere::uiLOD = 8; BOOL CDlgEditSphere::boNewMat = TRUE; ///////////////////////////////////////////////////////////////////////////// // CDlgEditSphere dialog CDlgEditSphere::CDlgEditSphere(CWnd* pParent /*=NULL*/) : CDialog(CDlgEditSphere::IDD, pParent) { //{{AFX_DATA_INIT(CDlgEditSphere) m_uiLOD = 0; m_boNewMat = FALSE; m_fPosX = 0.0f; m_fPosY = 0.0f; m_fPosZ = 0.0f; m_fRadius = 0.0f; m_strMaterial = _T("None"); //}}AFX_DATA_INIT m_boInitFromStatic = true; m_pMat = NULL; m_pItem = NULL; } void CDlgEditSphere::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CDlgEditSphere) DDX_Text(pDX, IDC_LOD, m_uiLOD); DDX_Check(pDX, IDC_NEWMAT, m_boNewMat); DDX_Text(pDX, IDC_POSX, m_fPosX); DDX_Text(pDX, IDC_POSY, m_fPosY); DDX_Text(pDX, IDC_POSZ, m_fPosZ); DDX_Text(pDX, IDC_RADIUS, m_fRadius); DDX_Text(pDX, IDC_MATNAME, m_strMaterial); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CDlgEditSphere, CDialog) //{{AFX_MSG_MAP(CDlgEditSphere) ON_BN_CLICKED(IDC_CHOOSEMAT, OnChoosemat) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CDlgEditSphere message handlers BOOL CDlgEditSphere::OnInitDialog() { CDialog::OnInitDialog(); // remember last chosen values if(m_boInitFromStatic) { m_fPosX = fPosX; m_fPosY = fPosY; m_fPosZ = fPosZ; m_fRadius = fRadius; m_uiLOD = uiLOD; m_boNewMat = boNewMat; } else { UpdateMatName(); } UpdateData(false); // return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } // void CDlgEditSphere::OnOK() { UpdateData(true); // save chosen values if(m_boInitFromStatic) { fPosX = m_fPosX; fPosY = m_fPosY; fPosZ = m_fPosZ; fRadius = m_fRadius; uiLOD = m_uiLOD; boNewMat = m_boNewMat; } // CDialog::OnOK(); } // void CDlgEditSphere::OnChoosemat() { CDlgChooseMaterial dlg; dlg.m_pSceneItem = m_pItem; dlg.m_pSelected = m_pMat; if(dlg.DoModal() != IDOK) return; UpdateData(true); m_pMat = dlg.m_pSelected; m_boNewMat = false; UpdateMatName(); } // void CDlgEditSphere::UpdateMatName() { m_strMaterial = "None"; if(m_pMat) { m_strMaterial = m_pMat->GetName(); if(m_strMaterial.IsEmpty()) m_strMaterial = "UNNAMED"; } UpdateData(false); }
[ "t.rejhons@gmail.com" ]
t.rejhons@gmail.com
b3b15466af79cadf0065aef16a4176a50026fd20
4df599a51b13e26d7936b8caa3b28ef43d6a539d
/UniEngine/include/CameraControlSystem.h
dcdb18cbff6661cdd36e9c9b9bbc5c13978a5401
[ "MIT" ]
permissive
bmjoy/UniEngine
b2e47faed2b3503433fcc9ab75063439c1280c96
55e0a1865e0004100f26e4bba3b16a36e9142012
refs/heads/master
2023-02-12T22:55:57.282932
2020-12-21T01:17:45
2020-12-21T01:17:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
548
h
#pragma once #include "Core.h" #include "UniEngineAPI.h" #include "CameraComponent.h" #include "TransformManager.h" namespace UniEngine { class UNIENGINE_API CameraControlSystem : public SystemBase { float _Velocity = 20.0f; float _Sensitivity = 0.1f; float _LastX = 0, _LastY = 0, _LastScrollY = 0; bool _StartMouse = false; float _SceneCameraYawAngle = -90; float _SceneCameraPitchAngle = 0; public: void LateUpdate() override; void SetVelocity(float velocity); void SetSensitivity(float sensitivity); }; }
[ "li2343@purdue.edu" ]
li2343@purdue.edu
e1eb9a48ecce7b1bfc2da1b89b0004b4859605b6
9b841803a2160ce5720d54b7ca6bceaf361bfa0f
/data/audio.cpp
ba22e95516585143bc2a5fffdb824a6780eeb4b6
[ "Apache-2.0" ]
permissive
npmplus/npmplus
560fdee1a7fb2a483ebee1b190cb633254726ec2
97beee9e980f2074a9a9a3d8bd062db2333e9cce
refs/heads/master
2021-04-27T17:45:13.232241
2018-02-23T08:03:25
2018-02-23T08:03:25
122,327,390
0
0
null
null
null
null
UTF-8
C++
false
false
260
cpp
#include <fstream> #include <iostream> using namespace; int main(); { int audio; void audio.mp3.npm(); const << 'sound.mp3' << 'npm'; const << 'Options/audio.json' << 'npm';   void  audio.loop.npm('npm audio loop'); const << 'looping' << 'npm'; return 0; }
[ "noreply@github.com" ]
noreply@github.com
a3918702e5d282fc75ddd3269e27eaea89634b83
0354f4b70ad8731d78801919a275eaa83ee26f3a
/NodeModel/HashNode.cpp
728ac52f06f0a545b326bf5e0fd74464bc86a499
[]
no_license
Wellrabbit/Nodes
d3b2cd5fd200dae534725f8d27c4514d29735a49
66daecedd54ff670e5dcb5b37d0bf2ad11f8928c
refs/heads/master
2021-01-18T20:12:54.843798
2016-05-25T17:22:55
2016-05-25T17:22:55
54,221,419
0
0
null
null
null
null
UTF-8
C++
false
false
486
cpp
// // HashNode.cpp // Nodes // // Created by Orton, Emily on 5/9/16. // Copyright © 2016 CTEC. All rights reserved. // #include "HashNode.hpp" template<class Type> HashNode<Type> :: HashNode() { } template<class Type> HashNode<Type> :: HashNode(int key, const Type& value) { this->key = key; this->value = value; } template<class Type> int HashNode<Type> :: getKey() { return key; } template<class Type> Type HashNode<Type> :: getValue() { return value; }
[ "eort3611@740s-pl-177.local" ]
eort3611@740s-pl-177.local
651a05b3bf8dfa49ba1f4a8a43886c885faff0ca
d6b34f44b77e690644430b08c111623f1014d3e6
/arduino/friend_main/friend_main.ino
7870631828cad7c3ab00725950fa46b3c6cfe549
[]
no_license
das747/GhostHunters
48ac670067eccb820d103d013243664111f38d9f
d3b05e42f9c7944f0efdaa0fd8ac44edb54c9273
refs/heads/master
2020-08-24T05:21:47.780059
2019-11-09T09:47:57
2019-11-09T09:47:57
216,767,570
0
0
null
2019-11-09T09:44:36
2019-10-22T08:54:12
Python
UTF-8
C++
false
false
1,071
ino
#include <Servo.h> const byte US = 7, LEFT_H = 9, RIGHT_H = 10; Servo left_h, right_h; void setup() { Serial.begin(9600); pinMode(US, OUTPUT); left_h.attach(LEFT_H); right_h.attach(RIGHT_H); } void loop() { if(get_us(US, US + 1) < 20){ left_h.write(45); right_h.write(45); delay(1000); Serial.write(1); // ОТПРАВЛЯЕМ СИГНАЛ О ТОМ, ЧТО РУКИ ПОДНЯЛИСЬ } } int get_us(int trig, int echo) { int res = 0; for(byte i=0; i < 5; i++){ digitalWrite(trig, LOW); //НАЧАЛО ПОЛУЧЕНИЯ ДАННЫХ С US ДАТЧИКА delayMicroseconds(5); digitalWrite(trig, HIGH); delayMicroseconds(10); digitalWrite(trig, LOW); //КОНЕЦ ПОЛУЧЕНИЯ ДАННЫХ С US ДАТЧИКА int value = pulseIn(echo, HIGH); //НАЧАЛО ОБРАБОТКИ ПОКАЗАНИЙ US value = (value / 2) / 29.1; //КОНЕЦ ОБРАБОТКИ ПОКАЗАНИЙ US if (value <= 0) value = 1000; res += value; delay(2); } res = int(res / 5); return res; }
[ "40293014+das747@users.noreply.github.com" ]
40293014+das747@users.noreply.github.com
9c5c18dcaae1dcbe81d7a4f7fa6edb817b7a020d
136ee4eec7e1591af2ba60ba6ae342d05b187cee
/Insert Interval.cpp
88626fc5a9cf1adabfc1f4708105bde1ef310e00
[]
no_license
hujunyu1222/leetcode
7cd79c6d5287a6cf1db8ce0e7abb225bd53e525b
b20d4a607bdcbc1fc92670b11142433214d7e32b
refs/heads/master
2021-01-11T06:06:55.377430
2017-04-11T02:54:30
2017-04-11T02:54:30
71,687,068
0
0
null
null
null
null
GB18030
C++
false
false
2,428
cpp
#include <iostream> #include <bits/stdc++.h> using namespace std; struct Interval { int start; int end; Interval() : start(0), end(0) {} Interval(int s, int e) : start(s), end(e) {} }; //O(n) vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) { vector<Interval> res; bool hasInsert = false; for (auto x:intervals){ if (hasInsert){ res.push_back(x); } else { if (newInterval.end < x.start){ res.push_back(newInterval); res.push_back(x); hasInsert = true; } else if (newInterval.start > x.end){ res.push_back(x); } else{ newInterval.start = min(x.start, newInterval.start); newInterval.end = max(x.end, newInterval.end); } } } if (!hasInsert)res.push_back(newInterval); return res; } //二分查找区间 //查找并合并区间的时间复杂度为O(logN),由于所有区间要添加,所以总时间是O(N) int binary_search(vector<Interval>& intervals, int target) { if (intervals.empty()) return -1; int low = 0, high = intervals.size() - 1; while (low < high) { int mid = (low + high) >> 1; if (target > intervals[mid].start) { low = mid + 1; } else { high = mid; } } return intervals[low].start <= target ? low : low - 1; } vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) { vector<Interval> ret; int i1 = binary_search(intervals, newInterval.start), i2 = binary_search(intervals, newInterval.end); int c = ((i1 == -1 || newInterval.start > intervals[i1].end) ? 0 : 1) + ((i2 == -1 || newInterval.end > intervals[i2].end) ? 0 : 2); for (int i = 0; i <= i1; i++) { ret.push_back(intervals[i]); } switch (c) { case 0: ret.push_back(newInterval); break; case 1: ret.back().end = newInterval.end; break; case 2: ret.emplace(ret.end(), newInterval.start, intervals[i2].end); break; case 3: ret.back().end = intervals[i2].end; break; } for (int i = i2 + 1; i < intervals.size(); i++) { ret.push_back(intervals[i]); } return ret; }
[ "hujunyu1222@gmail.com" ]
hujunyu1222@gmail.com
4abe2484d7f86377f7836e1eae72ac39e970a41c
f9dfd01e0f88e5c8cadd7fc0bfa47306b12d8ed5
/Alcohol_Advisory/ASProjectOne/ASProjectOne.cpp
942369ab6447db9d3a7f84cb4f4da9a314bffc1e
[]
no_license
aswinshaji/alcoholadvisory
7c58c725fff6a41f897a1f4584f637e8629bf9b5
fc7ffb4802a373f55372e222290f72edfab67985
refs/heads/main
2022-12-26T13:13:47.078470
2020-10-07T01:52:44
2020-10-07T01:52:44
301,899,902
0
0
null
null
null
null
UTF-8
C++
false
false
2,324
cpp
// ASProjectOne.cpp : This file contains the 'main' function. Program execution begins and ends there. // Aswin Shaji COSC 1436-73426 #include "pch.h" #include <iostream> #include <iomanip> using namespace std; int main() { double N; // Number of standard drinks double W; // Weight of a person int gender = 0; double g; // Gender double t; // Number of hours since the first drink double BAC; // Blood Alcohol Content cout << "Enter number of standard drinks that the person had:" << endl; cin >> N; cout << "Enter the weight of a person (in pounds):" << endl; cin >> W; cout << "Enter the gender of a person (1 for men and 2 for women):" << endl; cin >> gender; cout << "Enter the number of hours that the person drink:" << endl; cin >> t; if (gender == 1) { g = 0.68; // For male } else if (gender == 2) { g = 0.55; // For female } BAC = (-0.015*t) + ((2.84*N) / (W*g)); // Calculation of BAC cout << "BAC value:" << BAC << endl; cout << "Possible effect: " << endl; if (BAC < 0.03) { cout << "Normal behavior, no impairment" << endl; } else if (BAC < 0.06) { cout << "Mild euphoria and impairment" << endl; } else if (BAC < 0.10) { cout << "Euphoric, increased impairment" << endl; } else if (BAC < 0.20) { cout << "Drunk, loss of motor control" << endl; } else if (BAC < 0.30) { cout << "Confused, possible blackout" << endl; } else if (BAC < 0.40) { cout << "Possibly unconscious" << endl; } else { cout << "Unconscious, risk of death" << endl; } if (BAC < 0.08) { cout << "Over the legal limit for driving." << endl; } } // Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Start Debugging menu // Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
[ "noreply@github.com" ]
noreply@github.com
c56788d17f1aedecc7d7c3a41a9846da034020b1
c6e1d19fe37bef584761046987181476eaf9adac
/公用方法/00common/public.11617/common/mysqlwapper/main.cpp
eb74f856459cde5e174e1571e2141c792e3a0ba2
[]
no_license
xiexiaolong1988/mwRepos
d09fb01f442682d9f64334ef5e7b8175821e089e
bdc38c1afdcec480c7fe730f6ff68b878658a938
refs/heads/master
2020-04-05T06:35:54.574601
2018-11-08T03:24:54
2018-11-08T03:24:54
156,643,054
0
1
null
null
null
null
UTF-8
C++
false
false
1,014
cpp
#include "stdio.h" #include "stdlib.h" #include "SQLConnection.h" #include "SQLException.h" #include "SQLResult.h" using namespace std; //#include <unistd.h> int main() { CSQLConnection sqlconn; sqlconn.Open("192.169.1.130", "smsaccount", "root", "521521", 3306); while (1) { try { CSQLResult rs(sqlconn); //rs.Query("insert into testtb (testdata) values ('testdata')", false); rs.Query("CALL GetLoginUserInfo_B('WBS00A')", true); //SQLValueArray values; //while (rs.Fetch(values)) { //printf("get values...\r\n"); } } catch (CSQLException e) { printf("ErrorMsg:%s\r\nDescription:%s\r\n", e.ErrorMessage(), e.Description()); } catch (...) { printf("other error...\r\n"); } sleep(1); } while(1) { #ifdef WIN32 Sleep(1); #else sleep(1); #endif } return 0; }
[ "327363747@qq.com" ]
327363747@qq.com
0db57ebd7bd782263798ac816607219962ff2d5b
604c316b700467f9de35fedc12520a5800663943
/SharedLibrary/include/caching/psdes.h
5b40554e9e659b911e3b70eb42296f7fd0184c29
[]
no_license
Zahraanahle/Projectcode
e19bf614288176b0a930934c1d329dacf6dcb7c5
9db7e2c7549fe53b7dbf1f26884c7c5d97c3fcd8
refs/heads/master
2023-07-27T04:58:06.473947
2021-09-09T08:57:10
2021-09-09T08:57:10
404,650,614
0
0
null
null
null
null
UTF-8
C++
false
false
102
h
namespace caching{ void psdes(unsigned long *lword, unsigned long *irword); }//end namespace caching
[ "zahraanahle98@gmail.com" ]
zahraanahle98@gmail.com
fc88ba1ed6f576999c21f3506a3c013811df8e9b
5840e8abf34d91ec8a0647c9d68a405cc0d80f5a
/13307130444/assignment2/Pj3.cpp
4f5f029d07b0168d7beb45b825cbe889b7abbb6a
[]
no_license
ohlionel/codebase
5d3b086830a0c5dc975bde952a084c3e067d73d2
b816744b290f68f829c9b0d9df37615e13ece264
refs/heads/master
2020-06-19T16:10:21.234359
2014-12-19T12:00:38
2014-12-19T12:00:38
43,301,093
1
0
null
2015-09-28T13:00:50
2015-09-28T13:00:50
null
UTF-8
C++
false
false
1,272
cpp
#ifndef EARN_MUCH_SCHOLARSHIP_ #define EARN_MUCH_SCHOLARSHIP_ #include<iostream> using namespace std; class Student{ int (*stu)[5]; int num; public: void sort(); void display(); Student(int number); ~Student(){delete []stu;}; void swap(int*s1,int*s2); }; #endif Student::Student(int number){ int i=0; num=number; stu=new int[num][5]; for( i=0;i<num;i++) { cin>>stu[i][1]>>stu[i][2]>>stu[i][3]; stu[i][0]=i+1; stu[i][4]=stu[i][1]+stu[i][2]+stu[i][3]; } } void Student::sort(){ int i=0,j=1; for( i=0;i<num;i++) for(j=num-1;j>0;j--){ if(stu[j][4]>stu[j-1][4]) swap(stu[j-1],stu[j]); } for( i=0;i<num;i++) for(j=num-1;j>0;j--){ if(stu[j][1]>stu[j-1][1]&&stu[j][4]==stu[j-1][4]) swap(stu[j-1],stu[j]); } for(i=0;i<num;i++) for(j=num-1;j>0;j--){ if(stu[j][0]<stu[j-1][0]&&stu[j][4]==stu[j-1][4]&&(stu[j][1]==stu[j-1][1])) swap(stu[j-1],stu[j]); } } void Student::display(){ for(int i=0;i<num;i++) cout<<stu[i][0]<<" "<<stu[i][4]<<endl; } void Student::swap(int *s1,int *s2){ int *temp=new int[5]; for(int i=0;i<5;i++) { temp[i]=s1[i]; s1[i]=s2[i]; s2[i]=temp[i]; } delete []temp; } int main() { int num; cin>>num; Student stud(num); stud.sort(); stud.display(); getchar();getchar(); return 0; }
[ "isachriswang@163.com" ]
isachriswang@163.com
4682c8205b5a67f7a18104e50248a0122d8893cb
2c77cd0b0347b9aad46e71d3cb7bd5c01777c088
/sample_sketches/blinking_lights/blinking_lights.ino
5e0a5c600436bf3a807038bf187e8cd07e82b134
[]
no_license
Bschuster3434/Arduino_Projects
75c72c537afdb77c1d17cdcd41f6f0ddae05bbfb
14ec7ae8022a81b0e41a7acc6f0834cf68de141f
refs/heads/master
2016-09-05T20:05:18.632997
2014-12-03T14:46:00
2014-12-03T14:46:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
223
ino
/* Blinking LED Created by Brian Schuster 11/10/14 */ void setup() { pinMode(13, OUTPUT); //Setting pin 13 to 'output' mode } void loop() { digitalWrite(13, HIGH); delay(1000); digitalWrite(13, LOW); delay(1000); }
[ "brian.daniel.schuster@gmail.com" ]
brian.daniel.schuster@gmail.com
02eceb91407a61c917075776a67b3565276b7ea1
fdd175462b2624fe551901e6fcb34d728ef08fec
/content/samples/simplest_directshow_example/simplest_directshow_player_custom/simplest_directshow_player_custom.cpp
6d373b850b86b7c820978183a7dfe9b3b9e973a2
[]
no_license
aicanhelp/ai-video
6e54534760d28d6aff0e34bd2c671fcec3939e71
54f9586f3513684e7336ca8c37c1b068fef1d54f
refs/heads/master
2023-02-11T04:50:25.013920
2022-11-09T15:29:43
2022-11-09T15:29:43
224,360,479
0
1
null
2023-01-20T22:56:19
2019-11-27T06:28:39
C
GB18030
C++
false
false
5,812
cpp
/** * 最简单的基于DirectShow的视频播放器(Custom) * Simplest DirectShow Player (Custom) * * 雷霄骅 Lei Xiaohua * leixiaohua1020@126.com * 中国传媒大学/数字电视技术 * Communication University of China / Digital TV Technology * http://blog.csdn.net/leixiaohua1020 * * 本程序是一个简单的基于DirectShow的视频播放器。该播放器通过逐个添加 * 滤镜并连接这些滤镜实现了视频的播放。适合初学者学习DirectShow。 * * This software is a simple video player based on DirectShow. * It Add DirectShow Filter Manually and Link the Pins of these filters * to play videos.Suitable for the beginner of DirectShow. */ #include "stdafx.h" #include <dshow.h> //'1':Add filters manually //'0':Add filters automatically #define ADD_MANUAL 1 //Find unconnect pins HRESULT get_unconnected_pin( IBaseFilter *pFilter, // Pointer to the filter. PIN_DIRECTION PinDir, // Direction of the pin to find. IPin **ppPin) // Receives a pointer to the pin. { *ppPin = 0; IEnumPins *pEnum = 0; IPin *pPin = 0; HRESULT hr = pFilter->EnumPins(&pEnum); if (FAILED(hr)) { return hr; } while (pEnum->Next(1, &pPin, NULL) == S_OK) { PIN_DIRECTION ThisPinDir; pPin->QueryDirection(&ThisPinDir); if (ThisPinDir == PinDir) { IPin *pTmp = 0; hr = pPin->ConnectedTo(&pTmp); if (SUCCEEDED(hr)) // Already connected, not the pin we want. { pTmp->Release(); } else // Unconnected, the pin we want. { pEnum->Release(); *ppPin = pPin; return S_OK; } } pPin->Release(); } pEnum->Release(); // Did not find a matching pin. return E_FAIL; } //Connect 2 filters HRESULT connect_filters( IGraphBuilder *pGraph, IBaseFilter *pSrc, IBaseFilter *pDest) { if ((pGraph == NULL) || (pSrc == NULL) || (pDest == NULL)) { return E_POINTER; } //Find Output pin in source filter IPin *pOut = 0; HRESULT hr = NULL; hr=get_unconnected_pin(pSrc, PINDIR_OUTPUT, &pOut); if (FAILED(hr)){ return hr; } //Find Input pin in destination filter IPin *pIn = 0; hr = get_unconnected_pin(pDest, PINDIR_INPUT, &pIn); if (FAILED(hr)){ return hr; } //Connnect them hr = pGraph->Connect(pOut, pIn); pIn->Release(); pOut->Release(); return hr; } int _tmain(int argc, _TCHAR* argv[]) { IGraphBuilder *pGraph = NULL; IMediaControl *pControl = NULL; IMediaEvent *pEvent = NULL; // Init COM HRESULT hr = CoInitialize(NULL); if (FAILED(hr)){ printf("Error - Can't init COM."); return -1; } // Create FilterGraph hr=CoCreateInstance(CLSID_FilterGraph, NULL,CLSCTX_INPROC_SERVER,IID_IGraphBuilder, (void **)&pGraph); if (FAILED(hr)){ printf("Error - Can't create Filter Graph."); return -1; } // Query Interface hr = pGraph->QueryInterface(IID_IMediaControl, (void **)&pControl); hr = pGraph->QueryInterface(IID_IMediaEvent, (void **)&pEvent); //1. Add Filters======================= //Source IBaseFilter *pF_source = 0; hr = CoCreateInstance(CLSID_AsyncReader, 0, CLSCTX_INPROC_SERVER,IID_IBaseFilter, (void**)(&pF_source)); if (FAILED(hr)){ printf("Failed to create File Source.\n"); return -1; } hr = pGraph->AddFilter(pF_source, L"Lei's Source"); if (FAILED(hr)){ printf("Failed to add File Source to Filter Graph.\n"); return -1; } IFileSourceFilter* pFileSource; pF_source->QueryInterface(IID_IFileSourceFilter, (void**)&pFileSource); pFileSource->Load(L"cuc_ieschool.mpg", NULL); pFileSource->Release(); #if ADD_MANUAL //Demuxer IBaseFilter *pF_demuxer = 0; hr = CoCreateInstance(CLSID_MPEG1Splitter, 0, CLSCTX_INPROC_SERVER,IID_IBaseFilter, (void**)(&pF_demuxer)); if (FAILED(hr)){ printf("Failed to create Demuxer.\n"); return -1; } hr = pGraph->AddFilter(pF_demuxer, L"Lei's Demuxer"); if (FAILED(hr)){ printf("Failed to add Demuxer to Filter Graph.\n"); return -1; } //Decoder IBaseFilter *pF_decoder = 0; hr = CoCreateInstance(CLSID_CMpegVideoCodec, 0, CLSCTX_INPROC_SERVER,IID_IBaseFilter, (void**)(&pF_decoder)); if (FAILED(hr)){ printf("Failed to create Decoder.\n"); return -1; } hr = pGraph->AddFilter(pF_decoder, L"Lei's Decoder"); if (FAILED(hr)){ printf("Failed to add Decoder to Filter Graph.\n"); return -1; } //Render IBaseFilter *pF_render = 0; hr = CoCreateInstance(CLSID_VideoRenderer, 0, CLSCTX_INPROC_SERVER,IID_IBaseFilter, (void**)(&pF_render)); if (FAILED(hr)){ printf("Failed to create Video Render.\n"); return -1; } hr = pGraph->AddFilter(pF_render, L"Lei's Render"); if (FAILED(hr)){ printf("Failed to add Video Render to Filter Graph.\n"); return -1; } //2. Connect Filters======================= hr = connect_filters(pGraph, pF_source, pF_demuxer); if (FAILED(hr)){ printf("Failed to link Source and Demuxer.\n"); return -1; } hr = connect_filters(pGraph, pF_demuxer, pF_decoder); if (FAILED(hr)){ printf("Failed to link Demuxer and Decoder.\n"); return -1; } hr = connect_filters(pGraph, pF_decoder, pF_render); if (FAILED(hr)){ printf("Failed to link Decoder and Render.\n"); return -1; } pF_source->Release(); pF_demuxer->Release(); pF_decoder->Release(); pF_render->Release(); #else IPin* Pin; ULONG fetched; // get output pin IEnumPins* pEnumPins; hr = pF_source->EnumPins(&pEnumPins); hr = pEnumPins->Reset(); hr = pEnumPins->Next(1, &Pin, &fetched); pEnumPins->Release(); // render pin, graph builder automatically complete rest works hr = pGraph->Render(Pin); #endif if (SUCCEEDED(hr)){ // Run hr = pControl->Run(); if (SUCCEEDED(hr)){ long evCode=0; pEvent->WaitForCompletion(INFINITE, &evCode); } } //Release pControl->Release(); pEvent->Release(); pGraph->Release(); CoUninitialize(); return 0; }
[ "modongsongml@163.com" ]
modongsongml@163.com
b5524a667d5de3c12fb68c083de7ca5eadabd454
51d87b94b8561e41a505b9fbf4cfd9b42c390564
/code/dowidget.cpp
ba5f040f2372ff269970dabeb839abb6272e75a9
[]
no_license
IamHereWaitingForYou/WangyiyunMusicPlayer
52e753c2030519826d860d4487f3988f4201b32e
eac9024909ab32451e25cc4e63a75b933d5e621b
refs/heads/master
2022-12-05T11:27:57.338551
2020-08-31T06:06:34
2020-08-31T06:06:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,226
cpp
#include "dowidget.h" dowidget::dowidget(QWidget *parent) : QWidget(parent) { doButton=new QPushButton(this); undoButton=new QPushButton(this); doButton->setGeometry(0,0,35,25); undoButton->setGeometry(35,0,35,25); doButton->setCursor(Qt::PointingHandCursor); undoButton->setCursor(Qt::PointingHandCursor); doButton->setStyleSheet("QPushButton{background:rgb(0,20,20);border:1px solid rgb(100,100,100);border-radius:2px;}\ QPushButton{image:url(:/image/image/do_flase.png)}\ QPushButton:pressed{image:url(:/image/image/do_true.png);border:0px;}"); undoButton->setStyleSheet("QPushButton{background:rgb(0,20,20);border:1px solid rgb(100,100,100);border-radius:2px;}\ QPushButton{image:url(:/image/image/undo_flase.png)}\ QPushButton:pressed{image:url(:/image/image/undo_true.png);border:0px;}"); connect(doButton,SIGNAL(clicked(bool)),this,SLOT(doSlot())); connect(undoButton,SIGNAL(clicked(bool)),this,SLOT(undoSlot())); } void dowidget::doSlot() { } void dowidget::undoSlot() { }
[ "1627829134@qq.com" ]
1627829134@qq.com
cbb6b577b828c38ee5f7098d61186698fb14c070
d4c324ee70b678b9f5e12120bbf67d338739d30e
/include/util.cpp
7abdcc8127b12199c88264d4dc53a5799395e039
[]
no_license
ezegom/privacy
5e75be05236c53d437f459144b9db282ff38d124
5dc0dfd5eef9b8c5fd17d3a31bea8ee4c9215656
refs/heads/master
2021-01-01T20:04:20.719523
2018-08-31T22:04:13
2018-08-31T22:04:13
98,761,466
3
2
null
2017-08-28T17:49:37
2017-07-29T22:18:32
C++
UTF-8
C++
false
false
1,108
cpp
#include "util.h" #include <algorithm> #include <stdexcept> std::vector<unsigned char> convertIntToVectorLE(const uint64_t val_int) { std::vector<unsigned char> bytes; for(size_t i = 0; i < 8; i++) { bytes.push_back(val_int >> (i * 8)); } return bytes; } // Convert bytes into boolean vector. (MSB to LSB) std::vector<bool> convertBytesVectorToVector(const std::vector<unsigned char>& bytes) { std::vector<bool> ret; ret.resize(bytes.size() * 8); unsigned char c; for (size_t i = 0; i < bytes.size(); i++) { c = bytes.at(i); for (size_t j = 0; j < 8; j++) { ret.at((i*8)+j) = (c >> (7-j)) & 1; } } return ret; } // Convert boolean vector (big endian) to integer uint64_t convertVectorToInt(const std::vector<bool>& v) { if (v.size() > 64) { throw std::length_error ("boolean vector can't be larger than 64 bits"); } uint64_t result = 0; for (size_t i=0; i<v.size();i++) { if (v.at(i)) { result |= (uint64_t)1 << ((v.size() - 1) - i); } } return result; }
[ "eunsoo.sheen@gmail.com" ]
eunsoo.sheen@gmail.com
0b30d3060e7ff0926e8b262b398da5e9472b31eb
c59c628176193afaa221ff083d3b4972aaeb6476
/src/thread/thread_pool.hpp
6c8439c2d88f89bd31eea6b94566a8a5a44cfbe2
[ "Unlicense" ]
permissive
AlexandruIca/GameOfLife
a809e2fd2533171707f278c3aae5ee4502acb93f
fcde17c2ec1741a20d4ccca91643465df0d1dbe5
refs/heads/master
2022-12-09T21:43:44.556409
2020-09-09T18:44:16
2020-09-09T18:44:16
293,868,510
0
0
null
null
null
null
UTF-8
C++
false
false
1,594
hpp
#ifndef GOL_THREAD_THREADPOOL_HPP #define GOL_THREAD_THREADPOOL_HPP #pragma once #include <condition_variable> #include <functional> #include <future> #include <mutex> #include <queue> #include <stdexcept> #include <thread> #include <type_traits> #include <utility> #include <vector> namespace gol { class threadpool { private: std::vector<std::thread> m_workers; std::queue<std::function<void()>> m_tasks; std::mutex m_mutex; std::condition_variable m_cv; bool m_stop{ false }; public: threadpool(threadpool const&) = delete; threadpool(threadpool&&) = delete; ~threadpool() noexcept; explicit threadpool(std::size_t num_threads = std::thread::hardware_concurrency()); auto operator=(threadpool const&) -> threadpool& = delete; auto operator=(threadpool &&) -> threadpool& = delete; template<typename F, typename... Args> auto push(F&& f, Args&&... args) -> std::future<std::invoke_result_t<F, Args...>> { using T = std::invoke_result_t<F, Args...>; auto task = std::make_shared<std::packaged_task<T()>>(std::bind(std::forward<F>(f), std::forward<Args>(args)...)); std::future<T> result = task->get_future(); { std::unique_lock<std::mutex> lock{ m_mutex }; if(m_stop) { throw std::runtime_error{ "Attempted to push to a terminated thread pool!" }; } m_tasks.emplace([task] { (*task)(); }); } m_cv.notify_one(); return result; } }; } // namespace gol #endif // !GOL_THREAD_THREADPOOL_HPP
[ "alexandruica703@gmail.com" ]
alexandruica703@gmail.com
3605dfa77470e8fd8d7d48b3269e5d5ac23faa0a
869693d979ca9bcfdd0a974d06b037c9e775eddf
/EmoCVPR/utils.h
47997ed1555355011fa4f24d2d6d8f0eb9f89daf
[]
no_license
apprisi/facial_expression_recognition
83a154cca002f7dcec2fdb88a7b55c66d4e8a341
fbd3337ffd8b3f366fdb5c026c2cd7cf7855db8b
refs/heads/master
2021-01-19T07:22:31.864181
2017-06-06T11:42:15
2017-06-06T11:42:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
533
h
#ifndef _UTILS_H__ #define _UTILS_H__ #include <opencv2/opencv.hpp> #include "face_detection.h" #include <fstream> #include <io.h> void faceDetect(cv::Mat img); void warpFace(cv::Mat& face, cv::Mat& warp_face,const FacePts& pts, FacePts& rotation_pts); void setUpGausssian(int kernel_width, int kernel_height, std::vector<std::vector<float>>& gauss_matrix); void data_augmentation(cv::Mat &face, FacePts& pts, vector<cv::Mat>& SyntheticImg); void train(); void getFiles(std::string path, std::vector<std::string> &files); #endif
[ "lapcace@gmail.com" ]
lapcace@gmail.com
08cc4d16b6039b54ff217df2681986549d397f1f
852b1bb60ae31bfe9248c482a07a9b9270f13083
/FPGAs/C++/sine_generator/sine_generator.ino
d7ad647d2f9c3261786465e7b197d0367b1731df
[]
no_license
aladinkapic/burch
87064230ee72e53bce0102b0e1e56b297fa351b1
70df0221c991f022329e60a1e13c12c8b7c197e4
refs/heads/master
2020-05-22T19:45:05.346399
2019-05-27T20:18:22
2019-05-27T20:18:22
186,496,042
1
0
null
null
null
null
UTF-8
C++
false
false
969
ino
//Interrupts variables #define FASTLED_ALLOW_INTERRUPTS 0 #define ANALOG_PIN_0 35 volatile int interruptCounter, timer_active = 0; int totalInterruptCounter = 0, analog_value = 0; /** Functions prototypes .. **/ void stopTimer(); void startTimer(); //Timer interrupt routine hw_timer_t * timer = NULL; portMUX_TYPE timerMux = portMUX_INITIALIZER_UNLOCKED; void IRAM_ATTR onTimer(){ portENTER_CRITICAL_ISR(&timerMux); interruptCounter++; portEXIT_CRITICAL_ISR(&timerMux); } void setup() { Serial.begin(230400); } void loop() { Serial.write("1"); delay(500); Serial.write("1"); delay(500); } void stopTimer() { if (timer != NULL) { timerAlarmDisable(timer); timerDetachInterrupt(timer); timerEnd(timer); timer = NULL; } } void startTimer(){ timer = timerBegin(0, 80, true); timerAttachInterrupt(timer, &onTimer, true); timerAlarmWrite(timer, 10000, true); timerAlarmEnable(timer); }
[ "aladin.kapic@stu.ibu.edu.ba" ]
aladin.kapic@stu.ibu.edu.ba
59bc51ab4e5f2f8b4e9d885f5c599e9fe3c2a0e9
8888f9030c1f7536d48fe94e5e3f17185d36f495
/Fundamentals of Programming/dia-lab-2b.cpp
33f7f343505c27088404e04e3ae0b8461bee6e93
[]
no_license
aid8/CS01
f8526ba0af34d26075b18de762f3247d6f3b87da
468b64c56b7c617512f57d8fda27e0f0fb3221df
refs/heads/master
2022-11-06T20:08:32.792796
2020-06-30T14:54:56
2020-06-30T14:54:56
206,121,541
0
0
null
null
null
null
UTF-8
C++
false
false
2,299
cpp
//****************************************************************** // Filename : dia-lab-2b.cpp // Date : 26 July 2019 // Subject : CSDC101 - Fundamentals of Programming // First Semester, SY 2019 - 2020 // Activity : Laboratory Exercise 2 // Problem Title : Drawing Characters // Input : // Output : // // Honor Code : // This is my own program. I have not received any // unauthorized help in completing this work. I have not // copied from my classmate, friend, nor any unauthorized // resource. I am well aware of the policies stipulated // in the handbook regarding academic dishonesty. // If proven guilty, I won't be credited any points for // this exercise. // // Complete Name : Christian A. Dia // ID Number : 2019-1-0094 // Year-Course : 1-BSCS // DCS, College of Computer Studies // Ateneo de Naga University //****************************************************************** #include<iostream> using namespace std; int main() { int n, t; cin >> n; char ch; /* So basically ang string is a group of characters. Gumawa ako dito ng container gamit string, so dito ko ilalagay yung dapat icout ko, since sinabi baga ni sir na dapat pakainput ng numbers saka siya ma output. */ string disp = ""; //According sa constraints ito lang yung dapat na number ng testcase if(n >= 1 && n <= 100) { while(n > 0) { cin >> t >> ch; //COnstraints ulit. if(t >= 1 && t <= 100){ //Kailangan icheck natin kung valid yung character na nainput ng user. if(ch != '*' && ch != '#' && ch != '@') disp += "Cannot draw!"; else{ while(t > 0) { //Kung valid yung character, lalagay ito ng t times ng ch sa loob ng disp; disp += ch; t--; } } disp += "\n"; //Kailangan natin mag lagay ng endline since kung hindi tayo lalagay nito, continuous lang yung output sa isang line. n--; } } //So yan cout disp nalang yung kailangan para idisplay since naka store naman diyan yung gusto ko ipakita sa user. cout << disp; } return 0; }
[ "noreply@github.com" ]
noreply@github.com
4ab38b4c7df40df8fbe9cf9ef796078a063175b6
0f669fb6ab33ba3157d0089a1db923443add8eb1
/srcs/split.cpp
82c556429c0b34bce361dc3ff15bc907916a76d1
[]
no_license
pde-bakk/async_webserv
d17aebdc781303e704f09eab028c7850fa2ad2de
76e886e31dc059654ef43268086021ec5b6d404e
refs/heads/master
2023-02-23T07:41:44.078307
2021-01-20T17:17:19
2021-01-20T17:17:19
330,279,479
0
1
null
null
null
null
UTF-8
C++
false
false
1,343
cpp
/* ************************************************************************** */ /* */ /* :::::::: */ /* split.cpp :+: :+: */ /* +:+ */ /* By: pde-bakk <pde-bakk@student.codam.nl> +#+ */ /* +#+ */ /* Created: 2020/10/08 16:11:55 by pde-bakk #+# #+# */ /* Updated: 2020/10/17 16:32:30 by peerdb ######## odam.nl */ /* */ /* ************************************************************************** */ #include <string> #include <vector> namespace ft { std::vector<std::string> split(const std::string& s, const std::string& delim) { size_t start, end = 0; std::vector<std::string> vec; while (end != std::string::npos) { start = s.find_first_not_of(delim, end); end = s.find_first_of(delim, start); if (end != std::string::npos || start != std::string::npos) vec.push_back(s.substr(start, end - start)); } return vec; } }
[ "pde-bakk@student.codam.nl" ]
pde-bakk@student.codam.nl
3921c963b7e430ad03e5e8971f73a827d4c932a0
67487d255d6d26bb93d486b14d8bf33a85ef61a2
/cpsc585/cpsc585/WorldMesh.h
43b0cc7b248d7fe146a432bd9cffc37d88ca5e18
[]
no_license
ryosaku8/CPSC-585-Game-Project
aec2c5a1e70688ce8e4dc1f7ca5eee27ae1be2ad
2711d94c4e51a9d7dff3229b3da27d53bb7d720a
refs/heads/master
2021-05-26T20:10:20.182220
2012-04-16T18:50:22
2012-04-16T18:50:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
363
h
#pragma once #include "Mesh.h" class WorldMesh : public Mesh { public: static WorldMesh* getInstance(IDirect3DDevice9* device); ~WorldMesh(void); void render(IDirect3DDevice9* device); protected: WorldMesh(IDirect3DDevice9* device); private: void initialize(IDirect3DDevice9* device); public: private: static WorldMesh* mesh; };
[ "cdebavel@ucalgary.ca" ]
cdebavel@ucalgary.ca
de1034b6ca9fcf6b638e6e537f3c6fea2a174224
cb9a3cd4aab883ab083fcde21ea43443f7e4b5c5
/code/lab4/Translation.cpp
53d21dbcf4403add48e1b3ab4b7cbf18e1d4d672
[ "MIT" ]
permissive
Exlie-Flyyi/Chinese-License-Plate-Recognition
187699b24086a2ee1a58d22bbd78a1d5e2aabae9
74ccb90df9a2ee410d74fb82569ef88c9e24b64a
refs/heads/main
2023-07-23T01:51:47.584269
2021-09-06T13:02:46
2021-09-06T13:02:46
402,664,864
0
0
null
null
null
null
GB18030
C++
false
false
19,496
cpp
#include "stdafx.h" #include "lab4Dlg.h" #include "Translation.h" //全局变量声明 //Mat SrcImg; //颜色值变量 int h_lower[2] = { 100 ,15}; int s_lower = 52; int v_lower = 46; int h_upper[2] = { 120 ,40}; int s_upper = 255; int v_upper = 255; vector<cv::RotatedRect>ColorRect; vector<int>CarLabel; //用标签来定义矩形 Mat Translation(Mat& inputImage, int dx, int dy) { CV_Assert(inputImage.depth() == CV_8U); int rows = inputImage.rows + abs(dy); //输出图像行数 int cols = inputImage.cols + abs(dx); //输出图像列数 Mat outputImage; outputImage.create(rows, cols, inputImage.type()); //分配新的阵列数据 (如果需要)。 if (inputImage.channels() == 1) //单通道灰度图 { for (int i = 0; i < rows; i++){ for (int j = 0; j < cols; j++){ //计算在输入图像的位置 int x = j - dx; int y = i - dy; if (x >= 0 && y >= 0 && x < inputImage.cols && y < inputImage.rows) {//保证在原图像像素范围内 outputImage.at<uchar>(i, j) = inputImage.at<uchar>(y, x); } } } } if (inputImage.channels() == 3) { //三通道彩图 for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { int x = j - dx; int y = i - dy; if (x >= 0 && y >= 0 && x < inputImage.cols && y < inputImage.rows) { outputImage.at<cv::Vec3b>(i, j)[0] = inputImage.at<cv::Vec3b>(y, x)[0]; outputImage.at<cv::Vec3b>(i, j)[1] = inputImage.at<cv::Vec3b>(y, x)[1]; outputImage.at<cv::Vec3b>(i, j)[2] = inputImage.at<cv::Vec3b>(y, x)[2]; } } } } return outputImage; } Mat Resize(Mat& src, double scale) { //比例缩放 Mat out = Mat::zeros(src.size(), src.type()); src.copyTo(out); resize(src, out, Size(src.cols * scale, src.rows * scale), 0, 0, INTER_LINEAR); return out; } Mat Perspective(Mat &src) { vector<Point2f> corners(4); int img_width = src.cols; int img_height = src.rows; corners[0] = Point2f(0, 0); corners[1] = Point2f(img_height - 1, 0); corners[2] = Point2f(0, img_width - 1); corners[3] = Point2f(img_width - 1, img_height - 1); vector<Point2f> corners_trans(4); corners_trans[0] = Point2f(50, 50); corners_trans[1] = Point2f(img_height - 1, 0); corners_trans[2] = Point2f(0, img_width - 1); corners_trans[3] = Point2f(img_width - 50, img_height - 60); Mat transform = getPerspectiveTransform(corners, corners_trans); Mat resultImage; warpPerspective(src, resultImage, transform, Size(img_width, img_height), INTER_LINEAR); return resultImage; } Mat Expand(Mat &img) { //膨胀 Mat dilated_dst; Mat element_1 = getStructuringElement(MORPH_RECT, Size(4, 4)); Mat element_2 = getStructuringElement(MORPH_CROSS, Size(15, 15)); Mat element_3 = getStructuringElement(MORPH_ELLIPSE, Size(15, 15)); dilate(img, dilated_dst, element_1); return dilated_dst; } Mat Corrosion(Mat &img) { //腐蚀 //自定义方法 Mat element_1 = getStructuringElement(MORPH_RECT, Size(4, 4)); Mat element_2 = getStructuringElement(MORPH_CROSS, Size(15, 15)); Mat element_3 = getStructuringElement(MORPH_ELLIPSE, Size(15, 15)); Mat eroded_my, eroded_cv; erode(img, eroded_cv, element_1); return eroded_cv; } string Province_Show(int Label) { string pv = ""; switch (Label) { case 0:pv = "皖"; break; case 1:pv = "京"; break; case 2:pv = "渝"; break; case 3:pv = "闽"; break; case 4:pv = "甘"; break; case 5:pv = "粤"; break; case 6:pv = "桂"; break; case 7:pv = "贵"; break; case 8:pv = "琼"; break; case 9:pv = "翼"; break; case 10:pv = "黑"; break; case 11:pv = "豫"; break; case 12:pv = "鄂"; break; case 13:pv = "湘"; break; case 14:pv = "苏"; break; case 15:pv = "赣"; break; case 16:pv = "吉"; break; case 17:pv = "辽"; break; case 18:pv = "蒙"; break; case 19:pv = "宁"; break; case 20:pv = "青"; break; case 21:pv = "鲁"; break; case 22:pv = "晋"; break; case 23:pv = "陕"; break; case 24:pv = "川"; break; case 25:pv = "津"; break; case 26:pv = "新"; break; case 27:pv = "云"; break; case 28:pv = "浙"; break; default: break; } return pv; } void selectRect(vector<cv::Rect>rt, vector<cv::Rect>& LRect) { LRect.resize(2); cv::Rect temp; //numRect->LRect //按照面积排序(从大到小) int Averarea, AverWidth, AverHeight; for (int i = 0; i < rt.size(); i++) { for (int j = i; j < rt.size(); j++) { if (rt[i].area() <= rt[j].area()) { temp = rt[i]; rt[i] = rt[j]; rt[j] = temp; } } } //new->1 Averarea = (rt[0].area() + rt[1].area()) / 2; AverHeight = (rt[0].height + rt[1].height) / 2; AverWidth = (rt[0].width + rt[1].width) / 2; //计算更精确的平均值 int AverHeight1 = 0, Averarea1 = 0, AverWidth1 = 0; int add = 0; for (int q = 0; q < rt.size(); q++) { if (rt[q].area() > 0.4 * Averarea && rt[q].height > AverHeight * 0.7) { AverHeight1 += rt[q].height; AverWidth1 += rt[q].width; Averarea1 += rt[q].area(); add++; } } AverHeight1 /= add; AverWidth1 /= add; Averarea1 /= add; //按照x坐标排列顺序 for (int i = 0; i < rt.size(); i++) { for (int j = i; j < rt.size(); j++) { if (rt[i].x >= rt[j].x) { temp = rt[i]; rt[i] = rt[j]; rt[j] = temp; } } } //判断矩形的位置 //sum_one->Sumof1 //ForSrect->random int Sumof1 = 0; //用来计算1的个数,区分“川”字 cv::Rect random; //第一个或者第二个字母 int total = 0; //random前面的的面积总和 int minX = rt[0].x;//左边不为零的最小值 //开始遍历前三个,鉴别是否为“川”这样的特殊字形 for (int h = 0; h < rt.size() - 4; h++) { if (rt[h].x <= 2 + AverWidth1 / 20) { minX = rt[h + 1].x; continue; } total += rt[h].area(); //判断是否是川 if (rt[h].area() < Averarea1 * 0.5 && rt[h].height > AverHeight1*0.60) { Sumof1++; } if (rt[h].area() > Averarea1 * 0.8) { random = rt[h]; total -= random.area(); if (total > Averarea1 * 0.4 || Sumof1 >= 3) { //? //第二个 LRect[1] = random; //求第一个 //水平方向 int maxX = rt[h - 1].x + rt[h - 1].width; //竖直方向 int minY = 1000; int maxY = 0; for (int w = 0; w < h; w++) { if (minY >= rt[w].y) minY = rt[w].y; if (maxY <= rt[w].y + rt[w].height) maxY = rt[w].y + rt[w].height; } LRect[0] = cv::Rect(cv::Point(minX, minY), cv::Point(maxX, maxY)); } else//? { //第一个 LRect[0] = random; //求第二个 h++; while (rt[h].area() < Averarea1 * 0.7 && h < (rt.size() - 2)) { h++; } LRect[1] = rt[h]; } h++; for (int d = h; d < rt.size(); d++) { if (rt[d].height > AverHeight1 * 0.6) { if (rt[d].width < AverWidth1 * 0.5) { rt[d].x = rt[d].x - (AverWidth1 - rt[d].width) / 2; rt[d].width = AverWidth1; } LRect.push_back(rt[d]); } } break; } } } void Recognition(Mat& img, Mat& lic ,Mat& out, string &proc, char sss[], Mat NumImg[], bool &flag1, bool &flag2) { //计算识别一张图片的时间 int CatchSuccess = 0; //重置图片大小为900*900 //cout << img.rows << " " << img.cols << endl; if (img.rows > 900 || img.cols > 900) { int Wide = max(img.rows, img.cols); resize(img, img, cv::Size(), (double)900 / Wide, (double)900 / Wide); //std::cout << "已经重置图片大小" << endl; } for (int hi = 0; hi < 2; hi++) { flag1 = 0, flag2 = 0; if (CatchSuccess == 0) { //cout << v_lower << endl; //v_lower = 130; //hsv颜色定位 cv::Mat HsvImg; cv::Mat BinHsvImg; cvtColor(img, HsvImg, CV_BGR2HSV); //转成HSV图像 medianBlur(HsvImg, HsvImg, 3); medianBlur(HsvImg, HsvImg, 3); //GaussianBlur(HsvImg, HsvImg, Size(3, 3), 0, 0); inRange(HsvImg, cv::Scalar(h_lower[hi], s_lower, v_lower), cv::Scalar(h_upper[hi], s_upper, v_upper), BinHsvImg); //二值化阈值(hsv范围)操作 //cv::Mat kernel1 = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(4, 4)); //cv::Mat kernel2 = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3)); //morphologyEx(BinHsvImg, BinHsvImg, cv::MORPH_CLOSE, kernel1); //闭运算 //morphologyEx(BinHsvImg, BinHsvImg, cv::MORPH_OPEN, kernel2); //开运算*/ //闭运算 //imshow("后的图片", BinHsvImg); BinHsvImg = Expand(BinHsvImg); BinHsvImg = Corrosion(BinHsvImg); //开运算 BinHsvImg = Corrosion(BinHsvImg); BinHsvImg = Expand(BinHsvImg); //imshow("形态学后的图片", BinHsvImg); //imwrite("stander.png", BinHsvImg); //轮廓检测 vector<vector<cv::Point>>ColorContours;//所有轮廓的点坐标,子容器里面存下 findContours(BinHsvImg, ColorContours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);//检测出物体的轮廓,只检测最外围轮廓,保存拐点信息,保存物体边界上所有连续的轮廓点到contours向量内 vector<cv::RotatedRect>ColorRect;//旋转矩形类 vector<int>CarLabel; //用标签来定义矩形 //cout << "已经找到的矩形框的数量" << ColorContours.size() << endl; for (int i = 0; i < ColorContours.size(); i++)//遍历每一个矩形 { cv::RotatedRect rt; rt = minAreaRect(ColorContours[i]); //作用为计算包围点集的最小旋转矩阵 double width, height; width = max(rt.size.width, rt.size.height); height = min(rt.size.width, rt.size.height);//得到矩形的长度和宽度 if (width * height > 300 && width * height < img.rows * img.cols / 10 && width*1.0 / height> 2.5 && width*1.0 / height < 3.6) { ColorRect.push_back(rt); } } //std::cout << "已经筛选的点的数量" << ColorRect.size() << endl; //透视变换 vector<cv::Mat>ColorROI(ColorRect.size()); for (int i = 0; i < ColorRect.size(); i++) { cv::Point2f SrcVertices[4]; cv::Point2f Midpts;//调整中间点的位置 ColorRect[i].points(SrcVertices); //左上-右上-右下-左下 for (int k = 0; k < 4; k++) { //先按y值从上到下排列 for (int l = k; l < 4; l++) { if (SrcVertices[k].y >= SrcVertices[l].y) { Midpts = SrcVertices[k]; SrcVertices[k] = SrcVertices[l]; SrcVertices[l] = Midpts; } } } //判断最上面那两个点是不是最长边 if (pow(abs(SrcVertices[0].x - SrcVertices[1].x), 2) < pow(abs(SrcVertices[0].x - SrcVertices[2].x), 2)) { Midpts = SrcVertices[1]; SrcVertices[1] = SrcVertices[2]; SrcVertices[2] = Midpts; } if (SrcVertices[0].x > SrcVertices[1].x) { Midpts = SrcVertices[1]; SrcVertices[1] = SrcVertices[0]; SrcVertices[0] = Midpts; } if (SrcVertices[2].x < SrcVertices[3].x) { Midpts = SrcVertices[2]; SrcVertices[2] = SrcVertices[3]; SrcVertices[3] = Midpts; } cv::Point2f DstVertices[4]; double CarWidth = max(ColorRect[i].size.width, ColorRect[i].size.height); double CarHeight = min(ColorRect[i].size.width, ColorRect[i].size.height); DstVertices[0] = cv::Point(0, 0); DstVertices[1] = cv::Point(CarWidth, 0); DstVertices[2] = cv::Point(CarWidth, CarHeight); DstVertices[3] = cv::Point(0, CarHeight); cv::Mat H = getPerspectiveTransform(SrcVertices, DstVertices); ColorROI[i] = cv::Mat(cv::Size(CarWidth, CarHeight), CV_8UC3); warpPerspective(img, ColorROI[i], H, ColorROI[i].size(), 1); //cout << "已经旋转的车牌数量为" << ColorROI.size() << endl; } //对扣下来的车牌进行再处理 vector<cv::Mat>NewColorROI; for (int i = 0; i < ColorROI.size(); i++) { cv::Mat GrayImg; cvtColor(ColorROI[i], GrayImg, CV_BGR2GRAY); cv::imshow("灰度化的车牌", GrayImg); cv::Mat TempImg; cv::Mat Element; Canny(GrayImg, TempImg, 100, 150, 3); //cv::imshow("can的车牌", TempImg); threshold(TempImg, TempImg, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU); //cv::imshow("二值的车牌", TempImg); Element = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(ColorROI[i].cols / 6, 1)); morphologyEx(TempImg, TempImg, cv::MORPH_CLOSE, Element, cv::Point(-1, -1)); //cv::imshow("已经重新处理的车牌", TempImg); //进一步扣取车牌 vector<vector<cv::Point>>LittleContours; findContours(TempImg, LittleContours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE); for (int j = 0; j < LittleContours.size(); j++) { cv::Rect rt; rt = boundingRect(LittleContours[j]); if (rt.width > ColorROI[i].cols * 0.8 && rt.height > ColorROI[i].rows * 0.8) { NewColorROI.push_back(ColorROI[i]); CarLabel.push_back(i); break; } } } if (NewColorROI.size() == 0) { //std::cout << "颜色提取车牌失败" << endl; flag1 = 1; if(hi == 1) return; } //对车牌ROI进行上下切割 for (int num = 0; num < NewColorROI.size(); num++) { //统一大小 //int Radio = 6000 * NewColorROI[num].cols / 126;//用来筛选字母 int Radio = 6000 * NewColorROI[num].cols / 126;//用来筛选字母 cv::Mat GrayCarImg, BinCarImg; cvtColor(NewColorROI[num], GrayCarImg, CV_BGR2GRAY); //cv::imshow("车牌再处理之后的图像", GrayCarImg); threshold(GrayCarImg, BinCarImg, 0, 255, cv::THRESH_OTSU); if (hi == 1) { for (int kk = 0; kk < BinCarImg.rows; kk++) for(int jj = 0; jj < BinCarImg.cols; jj++){ if(BinCarImg.at<uchar>(kk, jj) == 0) BinCarImg.at<uchar>(kk, jj) = 255; else BinCarImg.at<uchar>(kk, jj) = 0; } } //cv::imshow("车牌再处理之后的图像", BinCarImg); lic = BinCarImg; //进行x方向的投影切除字母上下多余的部分 cv::Mat RowSum; reduce(BinCarImg, RowSum, 1, CV_REDUCE_SUM, CV_32SC1);//合并行向量 显示行的数量 //imshow("s", RowSum); cv::Point CutNumY;//Y方向的切割点 int Sign = 1; int Lenth = 0; for (int j = 0; j < RowSum.rows; j++) { if (RowSum.ptr<int>(0)[0] > Radio && Sign == 0) { while (RowSum.ptr<int>(Lenth)[0] >= Radio) { Lenth++; if (Lenth == RowSum.rows - 1) break; } if (Lenth > RowSum.rows * 0.6) { CutNumY = cv::Point(0, Lenth); break; } else { Sign = 1; j = Lenth; Lenth = 0; } } else { Sign = 1; } if (RowSum.ptr<int>(j)[0] > Radio && Sign == 1) { Lenth++; if (j == RowSum.rows - 1) { if (Lenth > RowSum.rows * 0.6) { CutNumY = cv::Point(j - Lenth, j); } } else { CutNumY = cv::Point(RowSum.rows * 0.15, RowSum.rows * 0.85); } } else if (RowSum.ptr<int>(j)[0] <= Radio && Sign == 1) { if (Lenth > RowSum.rows * 0.6) { CutNumY = cv::Point(j - Lenth, j); break; } else if (j == RowSum.rows - 1) { CutNumY = cv::Point(RowSum.rows * 0.15, RowSum.rows * 0.85); } else { Lenth = 0; } } } cv::Mat NewBinCarImg;//字母上下被切割后的图像 NewBinCarImg = BinCarImg(cv::Rect(cv::Point(0, CutNumY.x), cv::Point(BinCarImg.cols, CutNumY.y))); //imshow("qir", NewBinCarImg); //七个字符分割 cv::Mat MidBinCarImg = cv::Mat::zeros(cv::Size(NewBinCarImg.cols + 4, NewBinCarImg.rows + 4), CV_8UC1);//宽增加4个像素点 for (int row = 2; row < MidBinCarImg.rows - 2; row++) { for (int col = 2; col < MidBinCarImg.cols - 2; col++) { MidBinCarImg.ptr<uchar>(row)[col] = NewBinCarImg.ptr<uchar>(row - 2)[col - 2]; } } vector<vector<cv::Point>>NumContours; findContours(MidBinCarImg, NumContours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE); //最小外接矩形 vector<cv::Rect>LittleRect; for (int k = 0; k < NumContours.size(); k++) { LittleRect.push_back(boundingRect(NumContours[k])); } //midbin_carImg->MidBinCarImg //num_rect->LittleRect //矩形框的处理 //real_numRect->AlgRect vector<cv::Rect>AlgRect; if (LittleRect.size() < 7) { continue; } selectRect(LittleRect, AlgRect);//在下面的函数中 if (AlgRect.size() >= 7) { //std::cout << "字符提取成功" << endl; } else { //std::cout << "字符提取失败" << endl; flag2 = 1; return; //continue; } //防止第七个越界 if (AlgRect[6].x + AlgRect[6].width > MidBinCarImg.cols) { AlgRect[6].width = AlgRect[6].x + AlgRect[6].width - MidBinCarImg.cols; } //车牌从左到右字符图像 //cv::Mat NumImg[7]; for (int i = 0; i < 7; i++) { NumImg[i] = MidBinCarImg(cv::Rect(AlgRect[i].x, AlgRect[i].y, AlgRect[i].width, AlgRect[i].height)); } ostringstream CarNumber; string Character; //carnumber->CarNumber; //charater->Character; //testDetector->TestDetector //汉字 Ptr<ml::SVM>SVM_paramsH = ml::SVM::load("..//HOG字svm.xml"); //bin_character->BinCharacter cv::Mat Input; cv::Mat BinCharacter; resize(NumImg[0], BinCharacter, cv::Size(16, 32), 0, 0); cv::HOGDescriptor TestDetector(cv::Size(16, 32), cv::Size(16, 16), cv::Size(8, 8), cv::Size(8, 8), 9); //testDescriptor->TestDescriptor vector<float>TestDescriptor; TestDetector.compute(BinCharacter, TestDescriptor, cv::Size(0, 0), cv::Size(0, 0)); Input.push_back(static_cast<cv::Mat>(TestDescriptor).reshape(1, 1)); int r = SVM_paramsH->predict(Input);//对所有行进行预测 Character = Province_Show(r); //std::cout << "识别结果:" << Province_Show(r) << endl; proc = Province_Show(r); //imshow(proc, Input); //bin_num->BinNum //midBin_num->MidBinNum //数字字母识别 Ptr<ml::SVM>SVM_paramsZ = ml::SVM::load("..//HOG数字字母svm.xml"); for (int i = 1; i < 7; i++) { cv::Mat BinNum = cv::Mat::zeros(cv::Size(16, 32), CV_8UC1); cv::Mat MidBinNum; resize(NumImg[i], BinNum, cv::Size(16, 32), 0, 0); cv::Mat input; cv::HOGDescriptor Detector(cv::Size(16, 32), cv::Size(16, 16), cv::Size(8, 8), cv::Size(8, 8), 9); vector<float>Descriptors; Detector.compute(BinNum, Descriptors, cv::Size(0, 0), cv::Size(0, 0)); input.push_back(static_cast<cv::Mat>(Descriptors).reshape(1, 1));//序列化后的图片依次存入,放在下一个row float r = SVM_paramsZ->predict(input);//对所有行进行预测 //对0和D进行再区分 if (r == 0 || r == 'D') { if (BinNum.ptr<uchar>(0)[0] == 255 || BinNum.ptr<uchar>(31)[0] == 255) r = 'D'; else r = 0; } if (r > 9) { //std::cout << "识别结果" << (char)r << endl; sss[i - 1] = (char)r; CarNumber << (char)r; } else { //std::cout << "识别结果" << r << endl; int k = (int)r; sss[i - 1] = k + '0'; CarNumber << r; } } img.copyTo(out); //在原图中显示车牌号码 Character = Character + CarNumber.str(); //proc = Character; putTextZH(out, &Character[0], cv::Point(ColorRect[CarLabel[num]].boundingRect().x, abs(ColorRect[CarLabel[num]].boundingRect().y - 30)), cv::Scalar(0, 0, 255), 30, "宋体"); cv::Point2f pts[4]; ColorRect[CarLabel[num]].points(pts); for (int j = 0; j < 4; j++) { line(out, pts[j], pts[(j + 1) % 4], cv::Scalar(0, 255, 0), 2); } CatchSuccess = 1; } } } }
[ "habsburg-shan@outlook.com" ]
habsburg-shan@outlook.com
c66f8bdf5d1cb99e661f99e0547da52a14209da7
f4dd0a6de36666c8669bc677a3b5c83077a635dc
/src/libs/CLI11/tests/HelpersTest.cpp
7a497aa1cb05c0af6b77e5668063f57f9525c9bf
[ "MIT", "BSD-3-Clause" ]
permissive
0vercl0k/wtf
f1c42189bee27c6030c2cfa098a2eda050255295
9823579ef764b0b3c0af2f71b61d5aa47fb3de51
refs/heads/main
2023-07-19T17:59:45.759383
2023-07-09T04:21:04
2023-07-09T04:21:04
384,769,357
1,244
117
MIT
2023-07-09T04:21:06
2021-07-10T18:53:57
C++
UTF-8
C++
false
false
47,040
cpp
// Copyright (c) 2017-2021, University of Cincinnati, developed by Henry Schreiner // under NSF AWARD 1414736 and by the respective contributors. // All rights reserved. // // SPDX-License-Identifier: BSD-3-Clause #include "app_helper.hpp" #include <array> #include <atomic> #include <complex> #include <cstdint> #include <cstdio> #include <fstream> #include <limits> #include <map> #include <string> #include <tuple> #include <unordered_map> #include <utility> class NotStreamable {}; class Streamable {}; std::ostream &operator<<(std::ostream &out, const Streamable &) { return out << "Streamable"; } TEST_CASE("TypeTools: Streaming", "[helpers]") { CHECK("" == CLI::detail::to_string(NotStreamable{})); CHECK("Streamable" == CLI::detail::to_string(Streamable{})); CHECK("5" == CLI::detail::to_string(5)); CHECK(std::string("string") == CLI::detail::to_string("string")); CHECK(std::string("string") == CLI::detail::to_string(std::string("string"))); } TEST_CASE("TypeTools: tuple", "[helpers]") { CHECK_FALSE(CLI::detail::is_tuple_like<int>::value); CHECK_FALSE(CLI::detail::is_tuple_like<std::vector<double>>::value); auto v = CLI::detail::is_tuple_like<std::tuple<double, int>>::value; CHECK(v); v = CLI::detail::is_tuple_like<std::tuple<double, double, double>>::value; CHECK(v); } TEST_CASE("TypeTools: type_size", "[helpers]") { auto V = CLI::detail::type_count<int>::value; CHECK(1 == V); V = CLI::detail::type_count<void>::value; CHECK(0 == V); V = CLI::detail::type_count<std::vector<double>>::value; CHECK(1 == V); V = CLI::detail::type_count<std::tuple<double, int>>::value; CHECK(2 == V); V = CLI::detail::type_count<std::tuple<std::string, double, int>>::value; CHECK(3 == V); V = CLI::detail::type_count<std::array<std::string, 5>>::value; CHECK(5 == V); V = CLI::detail::type_count<std::vector<std::pair<std::string, double>>>::value; CHECK(2 == V); V = CLI::detail::type_count<std::tuple<std::pair<std::string, double>>>::value; CHECK(2 == V); V = CLI::detail::type_count<std::tuple<int, std::pair<std::string, double>>>::value; CHECK(3 == V); V = CLI::detail::type_count<std::tuple<std::pair<int, double>, std::pair<std::string, double>>>::value; CHECK(4 == V); // maps V = CLI::detail::type_count<std::map<int, std::pair<int, double>>>::value; CHECK(3 == V); // three level tuples V = CLI::detail::type_count<std::tuple<int, std::pair<int, std::tuple<int, double, std::string>>>>::value; CHECK(5 == V); V = CLI::detail::type_count<std::pair<int, std::vector<int>>>::value; CHECK(CLI::detail::expected_max_vector_size <= V); V = CLI::detail::type_count<std::vector<std::vector<int>>>::value; CHECK(CLI::detail::expected_max_vector_size == V); } TEST_CASE("TypeTools: type_size_min", "[helpers]") { auto V = CLI::detail::type_count_min<int>::value; CHECK(1 == V); V = CLI::detail::type_count_min<void>::value; CHECK(0 == V); V = CLI::detail::type_count_min<std::vector<double>>::value; CHECK(1 == V); V = CLI::detail::type_count_min<std::tuple<double, int>>::value; CHECK(2 == V); V = CLI::detail::type_count_min<std::tuple<std::string, double, int>>::value; CHECK(3 == V); V = CLI::detail::type_count_min<std::array<std::string, 5>>::value; CHECK(5 == V); V = CLI::detail::type_count_min<std::vector<std::pair<std::string, double>>>::value; CHECK(2 == V); V = CLI::detail::type_count_min<std::tuple<std::pair<std::string, double>>>::value; CHECK(2 == V); V = CLI::detail::type_count_min<std::tuple<int, std::pair<std::string, double>>>::value; CHECK(3 == V); V = CLI::detail::type_count_min<std::tuple<std::pair<int, double>, std::pair<std::string, double>>>::value; CHECK(4 == V); // maps V = CLI::detail::type_count_min<std::map<int, std::pair<int, double>>>::value; CHECK(3 == V); // three level tuples V = CLI::detail::type_count_min<std::tuple<int, std::pair<int, std::tuple<int, double, std::string>>>>::value; CHECK(5 == V); V = CLI::detail::type_count_min<std::pair<int, std::vector<int>>>::value; CHECK(2 == V); V = CLI::detail::type_count_min<std::vector<std::vector<int>>>::value; CHECK(1 == V); V = CLI::detail::type_count_min<std::vector<std::vector<std::pair<int, int>>>>::value; CHECK(2 == V); } TEST_CASE("TypeTools: expected_count", "[helpers]") { auto V = CLI::detail::expected_count<int>::value; CHECK(1 == V); V = CLI::detail::expected_count<void>::value; CHECK(0 == V); V = CLI::detail::expected_count<std::vector<double>>::value; CHECK(CLI::detail::expected_max_vector_size == V); V = CLI::detail::expected_count<std::tuple<double, int>>::value; CHECK(1 == V); V = CLI::detail::expected_count<std::tuple<std::string, double, int>>::value; CHECK(1 == V); V = CLI::detail::expected_count<std::array<std::string, 5>>::value; CHECK(1 == V); V = CLI::detail::expected_count<std::vector<std::pair<std::string, double>>>::value; CHECK(CLI::detail::expected_max_vector_size == V); } TEST_CASE("Split: SimpleByToken", "[helpers]") { auto out = CLI::detail::split("one.two.three", '.'); REQUIRE(out.size() == 3u); CHECK(out.at(0) == "one"); CHECK(out.at(1) == "two"); CHECK(out.at(2) == "three"); } TEST_CASE("Split: Single", "[helpers]") { auto out = CLI::detail::split("one", '.'); REQUIRE(out.size() == 1u); CHECK(out.at(0) == "one"); } TEST_CASE("Split: Empty", "[helpers]") { auto out = CLI::detail::split("", '.'); REQUIRE(out.size() == 1u); CHECK(out.at(0) == ""); } TEST_CASE("String: InvalidName", "[helpers]") { CHECK(CLI::detail::valid_name_string("valid")); CHECK_FALSE(CLI::detail::valid_name_string("-invalid")); CHECK(CLI::detail::valid_name_string("va-li-d")); CHECK_FALSE(CLI::detail::valid_name_string("valid{}")); CHECK(CLI::detail::valid_name_string("_valid")); CHECK(CLI::detail::valid_name_string("/valid")); CHECK(CLI::detail::valid_name_string("vali?d")); CHECK(CLI::detail::valid_name_string("@@@@")); CHECK(CLI::detail::valid_name_string("b@d2?")); CHECK(CLI::detail::valid_name_string("2vali?d")); CHECK_FALSE(CLI::detail::valid_name_string("!valid")); } TEST_CASE("StringTools: Modify", "[helpers]") { int cnt{0}; std::string newString = CLI::detail::find_and_modify("======", "=", [&cnt](std::string &str, std::size_t index) { if((++cnt) % 2 == 0) { str[index] = ':'; } return index + 1; }); CHECK("=:=:=:" == newString); } TEST_CASE("StringTools: Modify2", "[helpers]") { std::string newString = CLI::detail::find_and_modify("this is a string test", "is", [](std::string &str, std::size_t index) { if((index > 1) && (str[index - 1] != ' ')) { str[index] = 'a'; str[index + 1] = 't'; } return index + 1; }); CHECK("that is a string test" == newString); } TEST_CASE("StringTools: Modify3", "[helpers]") { // this picks up 3 sets of 3 after the 'b' then collapses the new first set std::string newString = CLI::detail::find_and_modify("baaaaaaaaaa", "aaa", [](std::string &str, std::size_t index) { str.erase(index, 3); str.insert(str.begin(), 'a'); return 0u; }); CHECK("aba" == newString); } TEST_CASE("StringTools: flagValues", "[helpers]") { CHECK(-1 == CLI::detail::to_flag_value("0")); CHECK(1 == CLI::detail::to_flag_value("t")); CHECK(1 == CLI::detail::to_flag_value("1")); CHECK(6 == CLI::detail::to_flag_value("6")); CHECK(-6 == CLI::detail::to_flag_value("-6")); CHECK(-1 == CLI::detail::to_flag_value("false")); CHECK(1 == CLI::detail::to_flag_value("YES")); CHECK_THROWS_AS(CLI::detail::to_flag_value("frog"), std::invalid_argument); CHECK_THROWS_AS(CLI::detail::to_flag_value("q"), std::invalid_argument); CHECK(-1 == CLI::detail::to_flag_value("NO")); CHECK(475555233 == CLI::detail::to_flag_value("475555233")); } TEST_CASE("StringTools: Validation", "[helpers]") { CHECK(CLI::detail::isalpha("")); CHECK(CLI::detail::isalpha("a")); CHECK(CLI::detail::isalpha("abcd")); CHECK_FALSE(CLI::detail::isalpha("_")); CHECK_FALSE(CLI::detail::isalpha("2")); CHECK_FALSE(CLI::detail::isalpha("test test")); CHECK_FALSE(CLI::detail::isalpha("test ")); CHECK_FALSE(CLI::detail::isalpha(" test")); CHECK_FALSE(CLI::detail::isalpha("test2")); } TEST_CASE("Trim: Various", "[helpers]") { std::string s1{" sdlfkj sdflk sd s "}; std::string a1{"sdlfkj sdflk sd s"}; CLI::detail::trim(s1); CHECK(s1 == a1); std::string s2{" a \t"}; CLI::detail::trim(s2); CHECK(s2 == "a"); std::string s3{" a \n"}; CLI::detail::trim(s3); CHECK(s3 == "a"); std::string s4{" a b "}; CHECK(CLI::detail::trim(s4) == "a b"); } TEST_CASE("Trim: VariousFilters", "[helpers]") { std::string s1{" sdlfkj sdflk sd s "}; std::string a1{"sdlfkj sdflk sd s"}; CLI::detail::trim(s1, " "); CHECK(s1 == a1); std::string s2{" a \t"}; CLI::detail::trim(s2, " "); CHECK(s2 == "a \t"); std::string s3{"abdavda"}; CLI::detail::trim(s3, "a"); CHECK(s3 == "bdavd"); std::string s4{"abcabcabc"}; CHECK(CLI::detail::trim(s4, "ab") == "cabcabc"); } TEST_CASE("Trim: TrimCopy", "[helpers]") { std::string orig{" cabc "}; std::string trimmed = CLI::detail::trim_copy(orig); CHECK(trimmed == "cabc"); CHECK(trimmed != orig); CLI::detail::trim(orig); CHECK(orig == trimmed); orig = "abcabcabc"; trimmed = CLI::detail::trim_copy(orig, "ab"); CHECK(trimmed == "cabcabc"); CHECK(trimmed != orig); CLI::detail::trim(orig, "ab"); CHECK(orig == trimmed); } TEST_CASE("Validators: FileExists", "[helpers]") { std::string myfile{"TestFileNotUsed.txt"}; CHECK_FALSE(CLI::ExistingFile(myfile).empty()); bool ok = static_cast<bool>(std::ofstream(myfile.c_str()).put('a')); // create file CHECK(ok); CHECK(CLI::ExistingFile(myfile).empty()); std::remove(myfile.c_str()); CHECK_FALSE(CLI::ExistingFile(myfile).empty()); } TEST_CASE("Validators: FileNotExists", "[helpers]") { std::string myfile{"TestFileNotUsed.txt"}; CHECK(CLI::NonexistentPath(myfile).empty()); bool ok = static_cast<bool>(std::ofstream(myfile.c_str()).put('a')); // create file CHECK(ok); CHECK_FALSE(CLI::NonexistentPath(myfile).empty()); std::remove(myfile.c_str()); CHECK(CLI::NonexistentPath(myfile).empty()); } TEST_CASE("Validators: FileIsDir", "[helpers]") { std::string mydir{"../tests"}; CHECK("" != CLI::ExistingFile(mydir)); } TEST_CASE("Validators: DirectoryExists", "[helpers]") { std::string mydir{"../tests"}; CHECK("" == CLI::ExistingDirectory(mydir)); } TEST_CASE("Validators: DirectoryNotExists", "[helpers]") { std::string mydir{"nondirectory"}; CHECK("" != CLI::ExistingDirectory(mydir)); } TEST_CASE("Validators: DirectoryIsFile", "[helpers]") { std::string myfile{"TestFileNotUsed.txt"}; CHECK(CLI::NonexistentPath(myfile).empty()); bool ok = static_cast<bool>(std::ofstream(myfile.c_str()).put('a')); // create file CHECK(ok); CHECK_FALSE(CLI::ExistingDirectory(myfile).empty()); std::remove(myfile.c_str()); CHECK(CLI::NonexistentPath(myfile).empty()); } TEST_CASE("Validators: PathExistsDir", "[helpers]") { std::string mydir{"../tests"}; CHECK("" == CLI::ExistingPath(mydir)); } TEST_CASE("Validators: PathExistsFile", "[helpers]") { std::string myfile{"TestFileNotUsed.txt"}; CHECK_FALSE(CLI::ExistingPath(myfile).empty()); bool ok = static_cast<bool>(std::ofstream(myfile.c_str()).put('a')); // create file CHECK(ok); CHECK(CLI::ExistingPath(myfile).empty()); std::remove(myfile.c_str()); CHECK_FALSE(CLI::ExistingPath(myfile).empty()); } TEST_CASE("Validators: PathNotExistsDir", "[helpers]") { std::string mydir{"nonpath"}; CHECK("" != CLI::ExistingPath(mydir)); } TEST_CASE("Validators: IPValidate1", "[helpers]") { std::string ip = "1.1.1.1"; CHECK(CLI::ValidIPV4(ip).empty()); ip = "224.255.0.1"; CHECK(CLI::ValidIPV4(ip).empty()); ip = "-1.255.0.1"; CHECK_FALSE(CLI::ValidIPV4(ip).empty()); ip = "1.256.0.1"; CHECK_FALSE(CLI::ValidIPV4(ip).empty()); ip = "1.256.0.1"; CHECK_FALSE(CLI::ValidIPV4(ip).empty()); ip = "aaa"; CHECK_FALSE(CLI::ValidIPV4(ip).empty()); ip = "1.2.3.abc"; CHECK_FALSE(CLI::ValidIPV4(ip).empty()); ip = "11.22"; CHECK_FALSE(CLI::ValidIPV4(ip).empty()); } TEST_CASE("Validators: PositiveValidator", "[helpers]") { std::string num = "1.1.1.1"; CHECK_FALSE(CLI::PositiveNumber(num).empty()); num = "1"; CHECK(CLI::PositiveNumber(num).empty()); num = "10000"; CHECK(CLI::PositiveNumber(num).empty()); num = "0"; CHECK_FALSE(CLI::PositiveNumber(num).empty()); num = "+0.5"; CHECK(CLI::PositiveNumber(num).empty()); num = "-1"; CHECK_FALSE(CLI::PositiveNumber(num).empty()); num = "-1.5"; CHECK_FALSE(CLI::PositiveNumber(num).empty()); num = "a"; CHECK_FALSE(CLI::PositiveNumber(num).empty()); } TEST_CASE("Validators: NonNegativeValidator", "[helpers]") { std::string num = "1.1.1.1"; CHECK_FALSE(CLI::NonNegativeNumber(num).empty()); num = "1"; CHECK(CLI::NonNegativeNumber(num).empty()); num = "10000"; CHECK(CLI::NonNegativeNumber(num).empty()); num = "0"; CHECK(CLI::NonNegativeNumber(num).empty()); num = "+0.5"; CHECK(CLI::NonNegativeNumber(num).empty()); num = "-1"; CHECK_FALSE(CLI::NonNegativeNumber(num).empty()); num = "-1.5"; CHECK_FALSE(CLI::NonNegativeNumber(num).empty()); num = "a"; CHECK_FALSE(CLI::NonNegativeNumber(num).empty()); } TEST_CASE("Validators: NumberValidator", "[helpers]") { std::string num = "1.1.1.1"; CHECK_FALSE(CLI::Number(num).empty()); num = "1.7"; CHECK(CLI::Number(num).empty()); num = "10000"; CHECK(CLI::Number(num).empty()); num = "-0.000"; CHECK(CLI::Number(num).empty()); num = "+1.55"; CHECK(CLI::Number(num).empty()); num = "a"; CHECK_FALSE(CLI::Number(num).empty()); } TEST_CASE("Validators: CombinedAndRange", "[helpers]") { auto crange = CLI::Range(0, 12) & CLI::Range(4, 16); CHECK(crange("4").empty()); CHECK(crange("12").empty()); CHECK(crange("7").empty()); CHECK_FALSE(crange("-2").empty()); CHECK_FALSE(crange("2").empty()); CHECK_FALSE(crange("15").empty()); CHECK_FALSE(crange("16").empty()); CHECK_FALSE(crange("18").empty()); } TEST_CASE("Validators: CombinedOrRange", "[helpers]") { auto crange = CLI::Range(0, 4) | CLI::Range(8, 12); CHECK_FALSE(crange("-2").empty()); CHECK(crange("2").empty()); CHECK_FALSE(crange("5").empty()); CHECK(crange("8").empty()); CHECK(crange("12").empty()); CHECK_FALSE(crange("16").empty()); } TEST_CASE("Validators: CombinedPaths", "[helpers]") { std::string myfile{"TestFileNotUsed.txt"}; CHECK_FALSE(CLI::ExistingFile(myfile).empty()); bool ok = static_cast<bool>(std::ofstream(myfile.c_str()).put('a')); // create file CHECK(ok); std::string dir{"../tests"}; std::string notpath{"nondirectory"}; auto path_or_dir = CLI::ExistingPath | CLI::ExistingDirectory; CHECK(path_or_dir(dir).empty()); CHECK(path_or_dir(myfile).empty()); CHECK_FALSE(path_or_dir(notpath).empty()); auto file_or_dir = CLI::ExistingFile | CLI::ExistingDirectory; CHECK(file_or_dir(dir).empty()); CHECK(file_or_dir(myfile).empty()); CHECK_FALSE(file_or_dir(notpath).empty()); auto path_and_dir = CLI::ExistingPath & CLI::ExistingDirectory; CHECK(path_and_dir(dir).empty()); CHECK_FALSE(path_and_dir(myfile).empty()); CHECK_FALSE(path_and_dir(notpath).empty()); auto path_and_file = CLI::ExistingFile & CLI::ExistingDirectory; CHECK_FALSE(path_and_file(dir).empty()); CHECK_FALSE(path_and_file(myfile).empty()); CHECK_FALSE(path_and_file(notpath).empty()); std::remove(myfile.c_str()); CHECK_FALSE(CLI::ExistingFile(myfile).empty()); } TEST_CASE("Validators: ProgramNameSplit", "[helpers]") { TempFile myfile{"program_name1.exe"}; { std::ofstream out{myfile}; out << "useless string doesn't matter" << std::endl; } auto res = CLI::detail::split_program_name(std::string("./") + std::string(myfile) + " this is a bunch of extra stuff "); CHECK(std::string("./") + std::string(myfile) == res.first); CHECK("this is a bunch of extra stuff" == res.second); TempFile myfile2{"program name1.exe"}; { std::ofstream out{myfile2}; out << "useless string doesn't matter" << std::endl; } res = CLI::detail::split_program_name(std::string(" ") + std::string("./") + std::string(myfile2) + " this is a bunch of extra stuff "); CHECK(std::string("./") + std::string(myfile2) == res.first); CHECK("this is a bunch of extra stuff" == res.second); res = CLI::detail::split_program_name("./program_name this is a bunch of extra stuff "); CHECK("./program_name" == res.first); CHECK("this is a bunch of extra stuff" == res.second); res = CLI::detail::split_program_name(std::string(" ./") + std::string(myfile) + " "); CHECK(std::string("./") + std::string(myfile) == res.first); CHECK(res.second.empty()); } TEST_CASE("CheckedMultiply: Int", "[helpers]") { int a{10}; int b{-20}; REQUIRE(CLI::detail::checked_multiply(a, b)); REQUIRE(-200 == a); a = 0; b = -20; REQUIRE(CLI::detail::checked_multiply(a, b)); REQUIRE(0 == a); a = 20; b = 0; REQUIRE(CLI::detail::checked_multiply(a, b)); REQUIRE(0 == a); a = std::numeric_limits<int>::max(); b = 1; REQUIRE(CLI::detail::checked_multiply(a, b)); REQUIRE(std::numeric_limits<int>::max() == a); a = std::numeric_limits<int>::max(); b = 2; REQUIRE(!CLI::detail::checked_multiply(a, b)); REQUIRE(std::numeric_limits<int>::max() == a); a = std::numeric_limits<int>::max(); b = -1; REQUIRE(CLI::detail::checked_multiply(a, b)); REQUIRE(-std::numeric_limits<int>::max() == a); a = std::numeric_limits<int>::max(); b = std::numeric_limits<int>::max(); REQUIRE(!CLI::detail::checked_multiply(a, b)); REQUIRE(std::numeric_limits<int>::max() == a); a = std::numeric_limits<int>::min(); b = std::numeric_limits<int>::max(); REQUIRE(!CLI::detail::checked_multiply(a, b)); REQUIRE(std::numeric_limits<int>::min() == a); a = std::numeric_limits<int>::min(); b = 1; REQUIRE(CLI::detail::checked_multiply(a, b)); REQUIRE(std::numeric_limits<int>::min() == a); a = std::numeric_limits<int>::min(); b = -1; REQUIRE(!CLI::detail::checked_multiply(a, b)); REQUIRE(std::numeric_limits<int>::min() == a); b = std::numeric_limits<int>::min(); a = -1; REQUIRE(!CLI::detail::checked_multiply(a, b)); REQUIRE(-1 == a); a = std::numeric_limits<int>::min() / 100; b = 99; REQUIRE(CLI::detail::checked_multiply(a, b)); REQUIRE(std::numeric_limits<int>::min() / 100 * 99 == a); a = std::numeric_limits<int>::min() / 100; b = -101; REQUIRE(!CLI::detail::checked_multiply(a, b)); REQUIRE(std::numeric_limits<int>::min() / 100 == a); a = 2; b = std::numeric_limits<int>::min() / 2; REQUIRE(CLI::detail::checked_multiply(a, b)); a = std::numeric_limits<int>::min() / 2; b = 2; REQUIRE(CLI::detail::checked_multiply(a, b)); a = 4; b = std::numeric_limits<int>::min() / 4; REQUIRE(CLI::detail::checked_multiply(a, b)); a = 48; b = std::numeric_limits<int>::min() / 48; REQUIRE(CLI::detail::checked_multiply(a, b)); } TEST_CASE("CheckedMultiply: SizeT", "[helpers]") { std::size_t a = 10; std::size_t b = 20; REQUIRE(CLI::detail::checked_multiply(a, b)); REQUIRE(200u == a); a = 0u; b = 20u; REQUIRE(CLI::detail::checked_multiply(a, b)); REQUIRE(0u == a); a = 20u; b = 0u; REQUIRE(CLI::detail::checked_multiply(a, b)); REQUIRE(0u == a); a = std::numeric_limits<std::size_t>::max(); b = 1u; REQUIRE(CLI::detail::checked_multiply(a, b)); REQUIRE(std::numeric_limits<std::size_t>::max() == a); a = std::numeric_limits<std::size_t>::max(); b = 2u; REQUIRE(!CLI::detail::checked_multiply(a, b)); REQUIRE(std::numeric_limits<std::size_t>::max() == a); a = std::numeric_limits<std::size_t>::max(); b = std::numeric_limits<std::size_t>::max(); REQUIRE(!CLI::detail::checked_multiply(a, b)); REQUIRE(std::numeric_limits<std::size_t>::max() == a); a = std::numeric_limits<std::size_t>::max() / 100; b = 99u; REQUIRE(CLI::detail::checked_multiply(a, b)); REQUIRE(std::numeric_limits<std::size_t>::max() / 100u * 99u == a); } TEST_CASE("CheckedMultiply: Float", "[helpers]") { float a{10.0F}; float b{20.0F}; REQUIRE(CLI::detail::checked_multiply(a, b)); REQUIRE(200 == Approx(a)); a = 0.0F; b = 20.0F; REQUIRE(CLI::detail::checked_multiply(a, b)); REQUIRE(0 == Approx(a)); a = INFINITY; b = 20.0F; REQUIRE(CLI::detail::checked_multiply(a, b)); REQUIRE(INFINITY == Approx(a)); a = 2.0F; b = -INFINITY; REQUIRE(CLI::detail::checked_multiply(a, b)); REQUIRE(-INFINITY == Approx(a)); a = std::numeric_limits<float>::max() / 100.0F; b = 1.0F; REQUIRE(CLI::detail::checked_multiply(a, b)); REQUIRE(std::numeric_limits<float>::max() / 100.0F == Approx(a)); a = std::numeric_limits<float>::max() / 100.0F; b = 99.0F; REQUIRE(CLI::detail::checked_multiply(a, b)); REQUIRE(std::numeric_limits<float>::max() / 100.0F * 99.0F == Approx(a)); a = std::numeric_limits<float>::max() / 100.0F; b = 101; REQUIRE(!CLI::detail::checked_multiply(a, b)); REQUIRE(std::numeric_limits<float>::max() / 100.0F == Approx(a)); a = std::numeric_limits<float>::max() / 100.0F; b = -99; REQUIRE(CLI::detail::checked_multiply(a, b)); REQUIRE(std::numeric_limits<float>::max() / 100.0F * -99.0F == Approx(a)); a = std::numeric_limits<float>::max() / 100.0F; b = -101; REQUIRE(!CLI::detail::checked_multiply(a, b)); REQUIRE(std::numeric_limits<float>::max() / 100.0F == Approx(a)); } TEST_CASE("CheckedMultiply: Double", "[helpers]") { double a{10.0F}; double b{20.0F}; REQUIRE(CLI::detail::checked_multiply(a, b)); REQUIRE(200 == Approx(a)); a = 0; b = 20; REQUIRE(CLI::detail::checked_multiply(a, b)); REQUIRE(0 == Approx(a)); a = INFINITY; b = 20; REQUIRE(CLI::detail::checked_multiply(a, b)); REQUIRE(INFINITY == Approx(a)); a = 2; b = -INFINITY; REQUIRE(CLI::detail::checked_multiply(a, b)); REQUIRE(-INFINITY == Approx(a)); a = std::numeric_limits<double>::max() / 100; b = 1; REQUIRE(CLI::detail::checked_multiply(a, b)); REQUIRE(std::numeric_limits<double>::max() / 100 == Approx(a)); a = std::numeric_limits<double>::max() / 100; b = 99; REQUIRE(CLI::detail::checked_multiply(a, b)); REQUIRE(std::numeric_limits<double>::max() / 100 * 99 == Approx(a)); a = std::numeric_limits<double>::max() / 100; b = 101; REQUIRE(!CLI::detail::checked_multiply(a, b)); REQUIRE(std::numeric_limits<double>::max() / 100 == Approx(a)); a = std::numeric_limits<double>::max() / 100; b = -99; REQUIRE(CLI::detail::checked_multiply(a, b)); REQUIRE(std::numeric_limits<double>::max() / 100 * -99 == Approx(a)); a = std::numeric_limits<double>::max() / 100; b = -101; REQUIRE(!CLI::detail::checked_multiply(a, b)); REQUIRE(std::numeric_limits<double>::max() / 100 == Approx(a)); } // Yes, this is testing an app_helper :) TEST_CASE("AppHelper: TempfileCreated", "[helpers]") { std::string name = "TestFileNotUsed.txt"; { TempFile myfile{name}; CHECK_FALSE(CLI::ExistingFile(myfile).empty()); bool ok = static_cast<bool>(std::ofstream(myfile.c_str()).put('a')); // create file CHECK(ok); CHECK(CLI::ExistingFile(name).empty()); CHECK_THROWS_AS([&]() { TempFile otherfile(name); }(), std::runtime_error); } CHECK_FALSE(CLI::ExistingFile(name).empty()); } TEST_CASE("AppHelper: TempfileNotCreated", "[helpers]") { std::string name = "TestFileNotUsed.txt"; { TempFile myfile{name}; CHECK_FALSE(CLI::ExistingFile(myfile).empty()); } CHECK_FALSE(CLI::ExistingFile(name).empty()); } TEST_CASE("AppHelper: Ofstream", "[helpers]") { std::string name = "TestFileNotUsed.txt"; { TempFile myfile(name); { std::ofstream out{myfile}; out << "this is output" << std::endl; } CHECK(CLI::ExistingFile(myfile).empty()); } CHECK_FALSE(CLI::ExistingFile(name).empty()); } TEST_CASE("Split: StringList", "[helpers]") { std::vector<std::string> results{"a", "long", "--lone", "-q"}; CHECK(CLI::detail::split_names("a,long,--lone,-q") == results); CHECK(CLI::detail::split_names(" a, long, --lone, -q") == results); CHECK(CLI::detail::split_names(" a , long , --lone , -q ") == results); CHECK(CLI::detail::split_names(" a , long , --lone , -q ") == results); CHECK(CLI::detail::split_names("one") == std::vector<std::string>({"one"})); } TEST_CASE("RegEx: Shorts", "[helpers]") { std::string name, value; CHECK(CLI::detail::split_short("-a", name, value)); CHECK(name == "a"); CHECK(value == ""); CHECK(CLI::detail::split_short("-B", name, value)); CHECK(name == "B"); CHECK(value == ""); CHECK(CLI::detail::split_short("-cc", name, value)); CHECK(name == "c"); CHECK(value == "c"); CHECK(CLI::detail::split_short("-simple", name, value)); CHECK(name == "s"); CHECK(value == "imple"); CHECK_FALSE(CLI::detail::split_short("--a", name, value)); CHECK_FALSE(CLI::detail::split_short("--thing", name, value)); CHECK_FALSE(CLI::detail::split_short("--", name, value)); CHECK_FALSE(CLI::detail::split_short("something", name, value)); CHECK_FALSE(CLI::detail::split_short("s", name, value)); } TEST_CASE("RegEx: Longs", "[helpers]") { std::string name, value; CHECK(CLI::detail::split_long("--a", name, value)); CHECK(name == "a"); CHECK(value == ""); CHECK(CLI::detail::split_long("--thing", name, value)); CHECK(name == "thing"); CHECK(value == ""); CHECK(CLI::detail::split_long("--some=thing", name, value)); CHECK(name == "some"); CHECK(value == "thing"); CHECK_FALSE(CLI::detail::split_long("-a", name, value)); CHECK_FALSE(CLI::detail::split_long("-things", name, value)); CHECK_FALSE(CLI::detail::split_long("Q", name, value)); CHECK_FALSE(CLI::detail::split_long("--", name, value)); } TEST_CASE("RegEx: SplittingNew", "[helpers]") { std::vector<std::string> shorts; std::vector<std::string> longs; std::string pname; CHECK_NOTHROW(std::tie(shorts, longs, pname) = CLI::detail::get_names({"--long", "-s", "-q", "--also-long"})); CHECK(longs == std::vector<std::string>({"long", "also-long"})); CHECK(shorts == std::vector<std::string>({"s", "q"})); CHECK(pname == ""); std::tie(shorts, longs, pname) = CLI::detail::get_names({"--long", "", "-s", "-q", "", "--also-long"}); CHECK(longs == std::vector<std::string>({"long", "also-long"})); CHECK(shorts == std::vector<std::string>({"s", "q"})); CHECK_THROWS_AS([&]() { std::tie(shorts, longs, pname) = CLI::detail::get_names({"-"}); }(), CLI::BadNameString); CHECK_THROWS_AS([&]() { std::tie(shorts, longs, pname) = CLI::detail::get_names({"--"}); }(), CLI::BadNameString); CHECK_THROWS_AS([&]() { std::tie(shorts, longs, pname) = CLI::detail::get_names({"-hi"}); }(), CLI::BadNameString); CHECK_THROWS_AS([&]() { std::tie(shorts, longs, pname) = CLI::detail::get_names({"---hi"}); }(), CLI::BadNameString); CHECK_THROWS_AS( [&]() { std::tie(shorts, longs, pname) = CLI::detail::get_names({"one", "two"}); }(), CLI::BadNameString); } TEST_CASE("String: ToLower", "[helpers]") { CHECK("one and two" == CLI::detail::to_lower("one And TWO")); } TEST_CASE("Join: Forward", "[helpers]") { std::vector<std::string> val{{"one", "two", "three"}}; CHECK(CLI::detail::join(val) == "one,two,three"); CHECK(CLI::detail::join(val, ";") == "one;two;three"); } TEST_CASE("Join: Backward", "[helpers]") { std::vector<std::string> val{{"three", "two", "one"}}; CHECK(CLI::detail::rjoin(val) == "one,two,three"); CHECK(CLI::detail::rjoin(val, ";") == "one;two;three"); } TEST_CASE("SplitUp: Simple", "[helpers]") { std::vector<std::string> oput = {"one", "two three"}; std::string orig{R"(one "two three")"}; std::vector<std::string> result = CLI::detail::split_up(orig); CHECK(result == oput); } TEST_CASE("SplitUp: SimpleDifferentQuotes", "[helpers]") { std::vector<std::string> oput = {"one", "two three"}; std::string orig{R"(one `two three`)"}; std::vector<std::string> result = CLI::detail::split_up(orig); CHECK(result == oput); } TEST_CASE("SplitUp: SimpleDifferentQuotes2", "[helpers]") { std::vector<std::string> oput = {"one", "two three"}; std::string orig{R"(one 'two three')"}; std::vector<std::string> result = CLI::detail::split_up(orig); CHECK(result == oput); } TEST_CASE("SplitUp: Layered", "[helpers]") { std::vector<std::string> output = {R"(one 'two three')"}; std::string orig{R"("one 'two three'")"}; std::vector<std::string> result = CLI::detail::split_up(orig); CHECK(result == output); } TEST_CASE("SplitUp: Spaces", "[helpers]") { std::vector<std::string> oput = {"one", " two three"}; std::string orig{R"( one " two three" )"}; std::vector<std::string> result = CLI::detail::split_up(orig); CHECK(result == oput); } TEST_CASE("SplitUp: BadStrings", "[helpers]") { std::vector<std::string> oput = {"one", " two three"}; std::string orig{R"( one " two three )"}; std::vector<std::string> result = CLI::detail::split_up(orig); CHECK(result == oput); oput = {"one", " two three"}; orig = R"( one ' two three )"; result = CLI::detail::split_up(orig); CHECK(result == oput); } TEST_CASE("Types: TypeName", "[helpers]") { std::string int_name = CLI::detail::type_name<int>(); CHECK(int_name == "INT"); std::string int2_name = CLI::detail::type_name<std::int16_t>(); CHECK(int2_name == "INT"); std::string uint_name = CLI::detail::type_name<unsigned char>(); CHECK(uint_name == "UINT"); std::string float_name = CLI::detail::type_name<double>(); CHECK(float_name == "FLOAT"); std::string char_name = CLI::detail::type_name<char>(); CHECK(char_name == "CHAR"); std::string vector_name = CLI::detail::type_name<std::vector<int>>(); CHECK(vector_name == "INT"); vector_name = CLI::detail::type_name<std::vector<double>>(); CHECK(vector_name == "FLOAT"); static_assert(CLI::detail::classify_object<std::pair<int, std::string>>::value == CLI::detail::object_category::tuple_value, "pair<int,string> does not read like a tuple"); static_assert(CLI::detail::classify_object<std::tuple<std::string, double>>::value == CLI::detail::object_category::tuple_value, "tuple<string,double> does not read like a tuple"); std::string pair_name = CLI::detail::type_name<std::vector<std::pair<int, std::string>>>(); CHECK(pair_name == "[INT,TEXT]"); vector_name = CLI::detail::type_name<std::vector<std::vector<unsigned char>>>(); CHECK(vector_name == "UINT"); auto vclass = CLI::detail::classify_object<std::vector<std::vector<unsigned char>>>::value; CHECK(CLI::detail::object_category::container_value == vclass); auto tclass = CLI::detail::classify_object<std::tuple<double>>::value; CHECK(CLI::detail::object_category::number_constructible == tclass); std::string tuple_name = CLI::detail::type_name<std::tuple<double>>(); CHECK(tuple_name == "FLOAT"); static_assert(CLI::detail::classify_object<std::tuple<int, std::string>>::value == CLI::detail::object_category::tuple_value, "tuple<int,string> does not read like a tuple"); tuple_name = CLI::detail::type_name<std::tuple<int, std::string>>(); CHECK(tuple_name == "[INT,TEXT]"); tuple_name = CLI::detail::type_name<std::tuple<const int, std::string>>(); CHECK(tuple_name == "[INT,TEXT]"); tuple_name = CLI::detail::type_name<const std::tuple<int, std::string>>(); CHECK(tuple_name == "[INT,TEXT]"); tuple_name = CLI::detail::type_name<std::tuple<std::string, double>>(); CHECK(tuple_name == "[TEXT,FLOAT]"); tuple_name = CLI::detail::type_name<const std::tuple<std::string, double>>(); CHECK(tuple_name == "[TEXT,FLOAT]"); tuple_name = CLI::detail::type_name<std::tuple<int, std::string, double>>(); CHECK(tuple_name == "[INT,TEXT,FLOAT]"); tuple_name = CLI::detail::type_name<std::tuple<int, std::string, double, unsigned int>>(); CHECK(tuple_name == "[INT,TEXT,FLOAT,UINT]"); tuple_name = CLI::detail::type_name<std::tuple<int, std::string, double, unsigned int, std::string>>(); CHECK(tuple_name == "[INT,TEXT,FLOAT,UINT,TEXT]"); tuple_name = CLI::detail::type_name<std::array<int, 10>>(); CHECK(tuple_name == "[INT,INT,INT,INT,INT,INT,INT,INT,INT,INT]"); std::string text_name = CLI::detail::type_name<std::string>(); CHECK(text_name == "TEXT"); std::string text2_name = CLI::detail::type_name<char *>(); CHECK(text2_name == "TEXT"); enum class test { test1, test2, test3 }; std::string enum_name = CLI::detail::type_name<test>(); CHECK(enum_name == "ENUM"); vclass = CLI::detail::classify_object<std::tuple<test>>::value; CHECK(CLI::detail::object_category::tuple_value == vclass); static_assert(CLI::detail::classify_object<std::tuple<test>>::value == CLI::detail::object_category::tuple_value, "tuple<test> does not classify as a tuple"); std::string enum_name2 = CLI::detail::type_name<std::tuple<test>>(); CHECK(enum_name2 == "ENUM"); std::string umapName = CLI::detail::type_name<std::unordered_map<int, std::tuple<std::string, double>>>(); CHECK(umapName == "[INT,[TEXT,FLOAT]]"); // On older compilers, this may show up as other/TEXT vclass = CLI::detail::classify_object<std::atomic<int>>::value; CHECK((CLI::detail::object_category::wrapper_value == vclass || CLI::detail::object_category::other == vclass)); std::string atomic_name = CLI::detail::type_name<std::atomic<int>>(); CHECK((atomic_name == "INT" || atomic_name == "TEXT")); } TEST_CASE("Types: OverflowSmall", "[helpers]") { signed char x; auto strmax = std::to_string(std::numeric_limits<signed char>::max() + 1); CHECK_FALSE(CLI::detail::lexical_cast(strmax, x)); unsigned char y; strmax = std::to_string(std::numeric_limits<unsigned char>::max() + 1); CHECK_FALSE(CLI::detail::lexical_cast(strmax, y)); } TEST_CASE("Types: LexicalCastInt", "[helpers]") { std::string signed_input = "-912"; int x_signed; CHECK(CLI::detail::lexical_cast(signed_input, x_signed)); CHECK(x_signed == -912); std::string unsigned_input = "912"; unsigned int x_unsigned; CHECK(CLI::detail::lexical_cast(unsigned_input, x_unsigned)); CHECK(x_unsigned == (unsigned int)912); CHECK_FALSE(CLI::detail::lexical_cast(signed_input, x_unsigned)); unsigned char y; std::string overflow_input = std::to_string(std::numeric_limits<uint64_t>::max()) + "0"; CHECK_FALSE(CLI::detail::lexical_cast(overflow_input, y)); char y_signed; CHECK_FALSE(CLI::detail::lexical_cast(overflow_input, y_signed)); std::string bad_input = "hello"; CHECK_FALSE(CLI::detail::lexical_cast(bad_input, y)); std::string extra_input = "912i"; CHECK_FALSE(CLI::detail::lexical_cast(extra_input, y)); std::string empty_input{}; CHECK_FALSE(CLI::detail::lexical_cast(empty_input, x_signed)); CHECK_FALSE(CLI::detail::lexical_cast(empty_input, x_unsigned)); CHECK_FALSE(CLI::detail::lexical_cast(empty_input, y_signed)); } TEST_CASE("Types: LexicalCastDouble", "[helpers]") { std::string input = "9.12"; long double x; CHECK(CLI::detail::lexical_cast(input, x)); CHECK((float)x == Approx((float)9.12)); std::string bad_input = "hello"; CHECK_FALSE(CLI::detail::lexical_cast(bad_input, x)); std::string overflow_input = "1" + std::to_string(std::numeric_limits<long double>::max()); CHECK(CLI::detail::lexical_cast(overflow_input, x)); CHECK_FALSE(std::isfinite(x)); std::string extra_input = "9.12i"; CHECK_FALSE(CLI::detail::lexical_cast(extra_input, x)); std::string empty_input{}; CHECK_FALSE(CLI::detail::lexical_cast(empty_input, x)); } TEST_CASE("Types: LexicalCastBool", "[helpers]") { std::string input = "false"; bool x; CHECK(CLI::detail::lexical_cast(input, x)); CHECK_FALSE(x); std::string bad_input = "happy"; CHECK_FALSE(CLI::detail::lexical_cast(bad_input, x)); std::string input_true = "EnaBLE"; CHECK(CLI::detail::lexical_cast(input_true, x)); CHECK(x); } TEST_CASE("Types: LexicalCastString", "[helpers]") { std::string input = "one"; std::string output; CLI::detail::lexical_cast(input, output); CHECK(output == input); } TEST_CASE("Types: LexicalCastParsable", "[helpers]") { std::string input = "(4.2,7.3)"; std::string fail_input = "4.2,7.3"; std::string extra_input = "(4.2,7.3)e"; std::complex<double> output; CHECK(CLI::detail::lexical_cast(input, output)); CHECK(4.2 == Approx(output.real())); CHECK(7.3 == Approx(output.imag())); CHECK(CLI::detail::lexical_cast("2.456", output)); CHECK(2.456 == Approx(output.real())); CHECK(0.0 == Approx(output.imag())); CHECK_FALSE(CLI::detail::lexical_cast(fail_input, output)); CHECK_FALSE(CLI::detail::lexical_cast(extra_input, output)); } TEST_CASE("Types: LexicalCastEnum", "[helpers]") { enum t1 : signed char { v1 = 5, v3 = 7, v5 = -9 }; t1 output; CHECK(CLI::detail::lexical_cast("-9", output)); CHECK(v5 == output); CHECK_FALSE(CLI::detail::lexical_cast("invalid", output)); enum class t2 : std::uint64_t { enum1 = 65, enum2 = 45667, enum3 = 9999999999999 }; t2 output2{t2::enum2}; CHECK(CLI::detail::lexical_cast("65", output2)); CHECK(t2::enum1 == output2); CHECK_FALSE(CLI::detail::lexical_cast("invalid", output2)); CHECK(CLI::detail::lexical_cast("9999999999999", output2)); CHECK(t2::enum3 == output2); } TEST_CASE("Types: LexicalConversionDouble", "[helpers]") { CLI::results_t input = {"9.12"}; long double x{0.0}; bool res = CLI::detail::lexical_conversion<long double, double>(input, x); CHECK(res); CHECK((float)x == Approx((float)9.12)); CLI::results_t bad_input = {"hello"}; res = CLI::detail::lexical_conversion<long double, double>(bad_input, x); CHECK_FALSE(res); } TEST_CASE("Types: LexicalConversionDoubleTuple", "[helpers]") { CLI::results_t input = {"9.12"}; std::tuple<double> x{0.0}; bool res = CLI::detail::lexical_conversion<decltype(x), decltype(x)>(input, x); CHECK(res); CHECK(std::get<0>(x) == Approx(9.12)); CLI::results_t bad_input = {"hello"}; res = CLI::detail::lexical_conversion<decltype(x), decltype(x)>(bad_input, x); CHECK_FALSE(res); } TEST_CASE("Types: LexicalConversionVectorDouble", "[helpers]") { CLI::results_t input = {"9.12", "10.79", "-3.54"}; std::vector<double> x; bool res = CLI::detail::lexical_conversion<std::vector<double>, double>(input, x); CHECK(res); CHECK(3u == x.size()); CHECK(-3.54 == Approx(x[2])); res = CLI::detail::lexical_conversion<std::vector<double>, std::vector<double>>(input, x); CHECK(res); CHECK(3u == x.size()); CHECK(-3.54 == Approx(x[2])); } static_assert(!CLI::detail::is_tuple_like<std::vector<double>>::value, "vector should not be like a tuple"); static_assert(CLI::detail::is_tuple_like<std::pair<double, double>>::value, "pair of double should be like a tuple"); static_assert(CLI::detail::is_tuple_like<std::array<double, 4>>::value, "std::array<double,4> should be like a tuple"); static_assert(CLI::detail::is_tuple_like<std::array<int, 10>>::value, "std::array<int,10> should be like a tuple"); static_assert(!CLI::detail::is_tuple_like<std::string>::value, "std::string should not be like a tuple"); static_assert(!CLI::detail::is_tuple_like<double>::value, "double should not be like a tuple"); static_assert(CLI::detail::is_tuple_like<std::tuple<double, int, double>>::value, "tuple should look like a tuple"); TEST_CASE("Types: LexicalConversionTuple2", "[helpers]") { CLI::results_t input = {"9.12", "19"}; std::tuple<double, int> x{0.0, 0}; static_assert(CLI::detail::is_tuple_like<decltype(x)>::value, "tuple type must have is_tuple_like trait to be true"); bool res = CLI::detail::lexical_conversion<decltype(x), decltype(x)>(input, x); CHECK(res); CHECK(19 == std::get<1>(x)); CHECK(9.12 == Approx(std::get<0>(x))); input = {"19", "9.12"}; res = CLI::detail::lexical_conversion<decltype(x), decltype(x)>(input, x); CHECK_FALSE(res); } TEST_CASE("Types: LexicalConversionTuple3", "[helpers]") { CLI::results_t input = {"9.12", "19", "hippo"}; std::tuple<double, int, std::string> x; bool res = CLI::detail::lexical_conversion<decltype(x), decltype(x)>(input, x); CHECK(res); CHECK(19 == std::get<1>(x)); CHECK(9.12 == Approx(std::get<0>(x))); CHECK("hippo" == std::get<2>(x)); input = {"19", "9.12"}; res = CLI::detail::lexical_conversion<decltype(x), decltype(x)>(input, x); CHECK_FALSE(res); } TEST_CASE("Types: LexicalConversionTuple4", "[helpers]") { CLI::results_t input = {"9.12", "19", "18.6", "5.87"}; std::array<double, 4> x; bool res = CLI::detail::lexical_conversion<decltype(x), decltype(x)>(input, x); CHECK(res); CHECK(19 == Approx(std::get<1>(x))); CHECK(9.12 == Approx(x[0])); CHECK(18.6 == Approx(x[2])); CHECK(5.87 == Approx(x[3])); input = {"19", "9.12", "hippo"}; res = CLI::detail::lexical_conversion<decltype(x), decltype(x)>(input, x); CHECK_FALSE(res); } TEST_CASE("Types: LexicalConversionTuple5", "[helpers]") { CLI::results_t input = {"9", "19", "18", "5", "235235"}; std::array<unsigned int, 5> x; bool res = CLI::detail::lexical_conversion<decltype(x), decltype(x)>(input, x); CHECK(res); CHECK(19u == std::get<1>(x)); CHECK(9u == x[0]); CHECK(18u == x[2]); CHECK(5u == x[3]); CHECK(235235u == x[4]); input = {"19", "9.12", "hippo"}; res = CLI::detail::lexical_conversion<decltype(x), decltype(x)>(input, x); CHECK_FALSE(res); } TEST_CASE("Types: LexicalConversionTuple10", "[helpers]") { CLI::results_t input = {"9", "19", "18", "5", "235235", "9", "19", "18", "5", "235235"}; std::array<unsigned int, 10> x; bool res = CLI::detail::lexical_conversion<decltype(x), decltype(x)>(input, x); CHECK(res); CHECK(19u == std::get<1>(x)); CHECK(9u == x[0]); CHECK(18u == x[2]); CHECK(5u == x[3]); CHECK(235235u == x[4]); CHECK(235235u == x[9]); input[3] = "hippo"; res = CLI::detail::lexical_conversion<decltype(x), decltype(x)>(input, x); CHECK_FALSE(res); } TEST_CASE("Types: LexicalConversionTuple10XC", "[helpers]") { CLI::results_t input = {"9", "19", "18", "5", "235235", "9", "19", "18", "5", "235235"}; std::array<double, 10> x; bool res = CLI::detail::lexical_conversion<decltype(x), std::array<unsigned int, 10>>(input, x); CHECK(res); CHECK(19.0 == std::get<1>(x)); CHECK(9.0 == x[0]); CHECK(18.0 == x[2]); CHECK(5.0 == x[3]); CHECK(235235.0 == x[4]); CHECK(235235.0 == x[9]); input[3] = "19.7"; res = CLI::detail::lexical_conversion<decltype(x), std::array<unsigned int, 10>>(input, x); CHECK_FALSE(res); } TEST_CASE("Types: LexicalConversionComplex", "[helpers]") { CLI::results_t input = {"5.1", "3.5"}; std::complex<double> x; bool res = CLI::detail::lexical_conversion<std::complex<double>, std::array<double, 2>>(input, x); CHECK(res); CHECK(5.1 == x.real()); CHECK(3.5 == x.imag()); } static_assert(CLI::detail::is_wrapper<std::vector<double>>::value, "vector double should be a wrapper"); static_assert(CLI::detail::is_wrapper<std::vector<std::string>>::value, "vector string should be a wrapper"); static_assert(CLI::detail::is_wrapper<std::string>::value, "string should be a wrapper"); static_assert(!CLI::detail::is_wrapper<double>::value, "double should not be a wrapper"); static_assert(CLI::detail::is_mutable_container<std::vector<double>>::value, "vector class should be a container"); static_assert(CLI::detail::is_mutable_container<std::vector<std::string>>::value, "vector class should be a container"); static_assert(!CLI::detail::is_mutable_container<std::string>::value, "string should be a container"); static_assert(!CLI::detail::is_mutable_container<double>::value, "double should not be a container"); static_assert(!CLI::detail::is_mutable_container<std::array<double, 5>>::value, "array should not be a container"); static_assert(CLI::detail::is_mutable_container<std::vector<int>>::value, "vector int should be a container"); static_assert(CLI::detail::is_readable_container<std::vector<int> &>::value, "vector int & should be a readable container"); static_assert(CLI::detail::is_readable_container<const std::vector<int>>::value, "const vector int should be a readable container"); static_assert(CLI::detail::is_readable_container<const std::vector<int> &>::value, "const vector int & should be a readable container"); TEST_CASE("FixNewLines: BasicCheck", "[helpers]") { std::string input = "one\ntwo"; std::string output = "one\n; two"; std::string result = CLI::detail::fix_newlines("; ", input); CHECK(output == result); } TEST_CASE("FixNewLines: EdgesCheck", "[helpers]") { std::string input = "\none\ntwo\n"; std::string output = "\n; one\n; two\n; "; std::string result = CLI::detail::fix_newlines("; ", input); CHECK(output == result); }
[ "noreply@github.com" ]
noreply@github.com
4cfefb641796b501cff0639ea7899c3bffd15dea
a4f6711f32e68011bafd01ec901bc5e77c1a6f93
/Library/codes/math/gauss.cpp
b4bb886323677d34e8aaf9eeee41dbfdd5c04f30
[]
no_license
studiovc/olympiad
da5ffc51fc77c24c6cc31586a96dc23bdb5b7483
a63c2abfae5a77498c0473775f900506a6f9f04a
refs/heads/master
2023-07-15T14:24:27.833432
2021-09-03T02:59:41
2021-09-03T02:59:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
925
cpp
// TODO: rewrite and refactor to lint int n, inv; vector<int> basis[505]; lint gyesu = 1; void insert(vector<int> v){ for(int i=0; i<n; i++){ if(basis[i].size()) inv ^= 1; // inversion num increases if(v[i] && basis[i].empty()){ basis[i] = v; return; } if(v[i]){ lint minv = ipow(basis[i][i], mod - 2) * v[i] % mod; for(auto &j : basis[i]) j = (j * minv) % mod; gyesu *= minv; gyesu %= mod; for(int j=0; j<basis[i].size(); j++){ v[j] += mod - basis[i][j]; while(v[j] >= mod) v[j] -= mod; } } } puts("0"); exit(0); } // Sample: Calculates Determinant in Z_p Field int main(){ scanf("%d",&n); for(int i=0; i<n; i++){ vector<int> v(n); for(int j=0; j<n; j++) scanf("%d",&v[j]); if(i % 2 == 1) inv ^= 1; insert(v); } if(inv) gyesu = mod - gyesu; gyesu = ipow(gyesu, mod - 2); for(int i=0; i<n; i++) gyesu = gyesu * basis[i][i] % mod; cout << gyesu % mod << endl; }
[ "koosaga@MacBook-Pro.local" ]
koosaga@MacBook-Pro.local
8b5a0f81860f785e2954c1e826284cdc3aa5dcdb
9ed6a9e2331999ee4cda5afca9965562dc813b1b
/libsrcs/angelscript/angelSVN/sdk/tests/test_feature/source/test_addon_serializer.cpp
1b40fa7a9ee863308974616e193c0c6f57b98220
[]
no_license
kalhartt/racesow
20152e59c4dab85252b26b15960ffb75c2cc810a
7616bb7d98d2ef0933231c811f0ca81b5a130e8a
refs/heads/master
2021-01-16T22:28:27.663990
2013-12-20T13:23:30
2013-12-20T13:23:30
16,124,051
3
2
null
null
null
null
UTF-8
C++
false
false
3,569
cpp
#include "utils.h" #include "../../../add_on/scriptarray/scriptarray.h" #include "../../../add_on/serializer/serializer.h" namespace Test_Addon_Serializer { struct CStringType : public CUserType { void Store(CSerializedValue *val, void *ptr) { val->SetUserData(new std::string(*(std::string*)ptr)); } void Restore(CSerializedValue *val, void *ptr) { std::string *buffer = (std::string*)val->GetUserData(); *(std::string*)ptr = *buffer; } void CleanupUserData(CSerializedValue *val) { std::string *buffer = (std::string*)val->GetUserData(); delete buffer; } }; struct CArrayType : public CUserType { void Store(CSerializedValue *val, void *ptr) { CScriptArray *arr = (CScriptArray*)ptr; for( unsigned int i = 0; i < arr->GetSize(); i++ ) val->m_children.push_back(new CSerializedValue(val ,"", arr->At(i), arr->GetElementTypeId())); } void Restore(CSerializedValue *val, void *ptr) { CScriptArray *arr = (CScriptArray*)ptr; arr->Resize(val->m_children.size()); for( size_t i = 0; i < val->m_children.size(); ++i ) val->m_children[i]->Restore(arr->At(i), arr->GetElementTypeId()); } }; bool Test() { bool fail = false; int r; COutStream out; CBufferedOutStream bout; asIScriptEngine *engine; asIScriptModule *mod; { engine = asCreateScriptEngine(ANGELSCRIPT_VERSION); engine->SetMessageCallback(asMETHOD(COutStream,Callback), &out, asCALL_THISCALL); RegisterScriptString(engine); RegisterScriptArray(engine, false); engine->RegisterGlobalFunction("void assert(bool)", asFUNCTION(Assert), asCALL_GENERIC); const char *script = "float f; \n" "string str; \n" "array<int> arr; \n" "class CTest \n" "{ \n" " int a; \n" " string str; \n" "} \n" "CTest @t; \n" "CTest a; \n" "CTest @b; \n" "CTest @t2 = @a; \n" "CTest @n = @a; \n"; mod = engine->GetModule(0, asGM_ALWAYS_CREATE); mod->AddScriptSection("script", script); r = mod->Build(); if( r < 0 ) TEST_FAILED; r = ExecuteString(engine, "f = 3.14f; \n" "str = 'test'; \n" "arr.resize(3); arr[0] = 1; arr[1] = 2; arr[2] = 3; \n" "a.a = 42; \n" "a.str = 'hello'; \n" "@b = @a; \n" "@t = CTest(); \n" "t.a = 24; \n" "t.str = 'olleh'; \n" "@t2 = t; \n" "@n = null; \n", mod); if( r != asEXECUTION_FINISHED ) TEST_FAILED; CSerializer modStore; modStore.AddUserType(new CStringType(), "string"); modStore.AddUserType(new CArrayType(), "array"); r = modStore.Store(mod); if( r < 0 ) TEST_FAILED; engine->DiscardModule(0); mod = engine->GetModule("2", asGM_ALWAYS_CREATE); mod->AddScriptSection("script", script); r = mod->Build(); if( r < 0 ) TEST_FAILED; r = modStore.Restore(mod); if( r < 0 ) TEST_FAILED; r = ExecuteString(engine, "assert(f == 3.14f); \n" "assert(str == 'test'); \n" "assert(arr.length() == 3 && arr[0] == 1 && arr[1] == 2 && arr[2] == 3); \n" "assert(a.a == 42); \n" "assert(a.str == 'hello'); \n" "assert(b is a); \n" "assert(t !is null); \n" "assert(t.a == 24); \n" "assert(t.str == 'olleh'); \n" "assert(t is t2); \n" "assert(n is null); \n", mod); if( r != asEXECUTION_FINISHED ) TEST_FAILED; engine->Release(); } return fail; } } // namespace
[ "karl.glatzer@gmx.de" ]
karl.glatzer@gmx.de
4c3ca5a4bda9f04dce9f8f94ea9c65984cf7b437
808e216ca9c89d639170adf5b0446d9e42a973f3
/src/core/transformations/noise_median.cpp
9b4c91ccba01bb2384dde50578ffbe9e0f09b56f
[]
no_license
RedDevil7/pto2013_reddevils
ac455953f20938ae52a949abf2cd4809d8d3efab
2256c332313246cb9166689b344d7b932d497cca
refs/heads/master
2021-01-20T22:31:23.422828
2014-01-16T22:36:14
2014-01-16T22:36:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,257
cpp
#include "noise_median.h" NoiseMedian::NoiseMedian(PNM* img) : Convolution(img) { } NoiseMedian::NoiseMedian(PNM* img, ImageViewer* iv) : Convolution(img, iv) { } PNM* NoiseMedian::transform() { int width = image->width(); int height = image->height(); PNM* newImage = new PNM(width, height, image->format()); Mode mode = RepeatEdge; for (int x=0; x<width; x++){ for (int y=0; y<height; y++){ if (image->format() == QImage::Format_RGB32){ QRgb pixel = getPixel(x,y,mode); // int r = qRed(pixel); // Get the 0-255 value of the R channel // int g = qGreen(pixel); // Get the 0-255 value of the G channel // int b = qBlue(pixel); int r=getMedian(x,y,RChannel); int g=getMedian(x,y,GChannel); int b=getMedian(x,y,BChannel); if (r>255){ r=255; } if (r<0){ r=0; } if (g>255){ g=255; } if (g<0){ g=0; } if (b>255){ b=255; } if (b<0){ b=0; } //int average = 0.3 * r + 0.6 * g + 0.1 * b; // newImage->setPixel(x,y, average); QColor newPixel = QColor(r,g,b); newImage->setPixel(x,y, newPixel.rgb()); } } } if (image->format() == QImage::Format_Mono) { for (int x=0; x<width; x++) for (int y=0; y<height; y++) { QRgb pixel = image->pixel(x,y); // Getting the pixel(x,y) value int v = qGray(pixel); v=getMedian(x,y,LChannel); newImage->setPixel(x,y, v); } } return newImage; } int NoiseMedian::compare(const void* a, const void* b) { return (*(int*)a - *(int*)b); } int NoiseMedian::getMedian(int x, int y, Channel channel) { int radius = getParameter("radius").toInt(); Mode mode= RepeatEdge; int pom=radius*2+1; double tablica[100]; int licznik=0; math::matrix<double> okno = getWindow(x,y,pom,channel,mode); //double u=okno(0,0); // x=(okno.ColNo()-1)*(okno.RowNo()-1); for (int i=0; i<okno.ColNo();i++){ for (int j=0; j<okno.RowNo();j++){ tablica[licznik]=okno(i,j); licznik++; } } std::sort(&tablica[0],&tablica[licznik]); //return 7; return tablica[licznik/2]; }
[ "afeldfeber@gmail.com" ]
afeldfeber@gmail.com
6bf2e2e39d30eed21a72ef6409e5094a236097f2
d1b2881612efaa2f03dbce9953b1b290926258e8
/src/Controller.h
55a1d6a96ee97b0424c82b58be35d31b56c1757e
[]
no_license
francopettinari/ATG
a780f42a44861c859e8a8fec6a9d6e2b9c6b378b
b14ba0cb28ec181d2691bceee3c8871600db40dd
refs/heads/master
2021-06-25T06:16:31.903969
2020-02-28T07:37:54
2020-02-28T07:37:54
200,795,405
0
0
null
null
null
null
UTF-8
C++
false
false
4,408
h
/* * PidState.h * * Created on: 06 nov 2018 * Author: franc */ #ifndef CONTROLLER_H_ #define CONTROLLER_H_ #include <WString.h> enum EncoderMovement {EncMoveNone=-1,EncMoveCW=0,EncMoveCCW=1}; enum EncoderPushButtonState {EncoderPushButtonNone=0, EncoderPushButtonPressed=1}; #include "Menu.h" #include "pid/PID_v1.h" #include <Servo.h> class LCDHelper; class MenuItem; #include "LCDHelper.h" #include "tempProbe.h" enum PidStateValue { svUndefiend=-1,svMain=0, svRunAuto=10, svRunAutoSetpoint=13,svRunAutoRamp=17, svConfig=20, svPidConfig=22, svPidKpiConfig=23,svPidKpdConfig=24, svPidKiiConfig=25, svPidKidConfig=26,svPidKicConfig=27, svPidKdiConfig=28,svPidKddConfig=29, svPidSampleTimeConfig=30, svServo_Config=40, svConfig_ServoDirection=41, svConfig_ServoMin=42,svConfig_ServoMax=43, svConfig_Probe=50}; enum ServoDirection {ServoDirectionCW=0,ServoDirectionCCW=1}; enum FsmState {psIdle=0,psWaitDelay=5,psRampimg=10,psKeepTemp=30}; enum TemperatureTransitionState {TempStateUndefined=0,TempStateOff=10,TempStateOn=20,TempStateSwitchingOn=30,TempStateSwitchingOff=40}; class Controller { float lastPressMillis=0; float lastPressState = EncoderPushButtonNone; private: FsmState fsmState=psIdle; TemperatureTransitionState TempState = TempStateUndefined; EncoderPushButtonState decodeEncoderPushBtnState (boolean encoderPress); boolean IsEncoderPressed(boolean encoderPress); EncoderMovement decodeEncoderMoveDirection(int encoderPos); void _writeServo(int degree); bool isAutoState(int state); byte eepromVer = 06; // eeprom data tracking PID pid; TemperatureProbe probe; Servo servo; double _setpoint = 25,_dynamicSetpoint=25,_ramp=1; public: double setpoint(){ return _setpoint; } void setSetpoint(double value){ _setpoint=value; } void incSetpoint(){ _setpoint++; if(_setpoint>=120)_setpoint=120; } void decSetpoint(){ _setpoint--; if(_setpoint<0)_setpoint=0;} double dynamicSetpoint(){ return _dynamicSetpoint; } void setDynamicSetpoint(double value){ _dynamicSetpoint=value; } double ramp(){ return _ramp; } void setRamp(double value){ _ramp=value; } void incRamp(){ _ramp++; } void decRamp(){ _ramp--; if(_ramp<0)_ramp=0; } MenuItem *currentMenu=NULL; PidStateValue state = svMain; int autoModeOn = false; //true=> auto mode on, false auto mode paused int forcedOutput = 0; //0 means automatic, !=0 means forced to value LCDHelper *lcdHelper=NULL; MenuItem *topMenu = NULL; int stateSelection = 0, currMenuStart=0; int currEncoderPos=0,prevEncoderPos=0; // a counter for the rotary encoder dial double temperature = 0, lastTemperature=0/*,dTemperature*/; float pidSampleTimeSecs = 5; float lastManualLog = 0; float lastUdpDataSent = 0; float approacingStartMillis,lastDynSetpointCalcMillis = 0; float approacingStartTemp = 0; double Output; float PrevSwitchOnOffMillis = 0; int servoPosition=0; void writeServoPosition(int degree, bool minValueSwitchOff,bool log=true); double kp=50,ki=0.5,kd=0; int expectedReqId = 1; //expected request id double myPTerm; double myITerm; double myDTerm; double myDTimeMillis; double myDInput; double myError; double myOutputSum; ServoDirection servoDirection = ServoDirectionCW; int servoMinValue = 0; //degrees int servoMaxValue = 180; //degrees int temperatureCorrection = 0;//0.1 deg steps: 5=+0.5, -8=-0.8 Controller(); PidStateValue getState(){ return state; } void SetState(PidStateValue value, boolean save=true){ state = value; if(save)savetoEEprom(); stateSelection=0; setCurrentMenu(decodeCurrentMenu()); } int getOutPerc(); void setOutPerc(double val); float getTemperature(){ return temperature; } void setTemperature(double value){ temperature = value; } MenuItem* decodeCurrentMenu(); void setCurrentMenu(MenuItem *m); MenuItem *getCurrentMenu(){ return currentMenu; } void update(int encoderPos, boolean encoderPress); void SetFsmState(FsmState value); // void updatePidStatus(); void startRamp(); bool waitRampStart(); void updateRamp(); void sendStatus(); void loadFromEEProm(); void savetoEEprom(); void saveSetPointTotoEEprom(); void saveServoDirToEEprom(); }; #endif /* CONTROLLER_H_ */
[ "fape@logobject.ch" ]
fape@logobject.ch
936cef31676bf36c5f85faaf4db446b34974dabf
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5751500831719424_0/C++/steppenwolf/main.cpp
02ea2473bf07ce538fcc5290f0a01e11d9b2bbc9
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
1,643
cpp
#include <iostream> #include <set> #include <vector> #include <algorithm> using namespace std; int main() { int T; cin >> T; for (int test = 1; test <= T; ++test) { int n; cin >> n; vector<string> s(n); vector<int> pos(n, 0); for (int i = 0; i < n; ++i) { cin >> s[i]; } bool bad = false; int res = 0; while (pos[0] < s[0].size()) { char cur = s[0][pos[0]]; vector<int> qnt(n); int mx = 0; for (int j = 0; j < n; ++j) { while (pos[j] < s[j].size() && s[j][pos[j]] == cur) { ++pos[j]; ++qnt[j]; } if (!qnt[j]) { bad = true; } else { mx = max(mx, qnt[j]); } } int minDiff = 1000000000; for (int r = 1; r <= mx; ++r) { int diff = 0; for (int j = 0; j < n; ++j) { diff += abs(qnt[j] - r); } minDiff = min(minDiff, diff); } res += minDiff; } for (int i = 0; i < n; ++i) { if (pos[i] < s[i].size()) bad = true; } cout << "Case #" << test << ": "; if (bad) { cout << "Fegla Won" << endl; } else { cout << res << endl; } } return 0; }
[ "eewestman@gmail.com" ]
eewestman@gmail.com
4c8044330b5a60b8d2727f9182b143a504355edb
ce55d412dcbee60af7278083fd8bda2c33eec819
/20190310腾讯提前批/5.cpp
91f42173728bcdeba60a68079dbdac672c5ccaf3
[ "MIT" ]
permissive
Diamondsn/algorithm-programming
9b60f621a6203bfaebf46570057ed25d0d9a7e77
6c52e22f0dfd887e7b77ec49fc1c353d9452e04c
refs/heads/master
2020-03-27T23:41:23.953833
2019-09-29T09:51:36
2019-09-29T09:51:36
147,338,549
0
0
null
null
null
null
UTF-8
C++
false
false
608
cpp
#include<string> #include<vector> #include<iostream> #include<algorithm> #include<stack> #include<math.h> #include<map> #include<set> using namespace std; int main() { int n; cin >> n; vector<int>vec; for (int i = 0; i < n; ++i){ int temp; cin >> temp; vec.push_back(temp); } for (int i = 1; i < n; ++i){ int chazhi = abs(vec[0] - vec[i]); int shu = vec[0]; for (int j = 1; j < i; ++j){ int newchazhi = abs(vec[i] - vec[j]); if (newchazhi < chazhi){ chazhi = newchazhi; shu = vec[j]; } } cout << chazhi <<" "<< shu << endl; } system("pause"); return 0; }
[ "Diamondsn@users.noreply.github.com" ]
Diamondsn@users.noreply.github.com
b90113b6040be78aa0cda2fd17ba4b20e6edbff2
30de44d89a8810cef7305f35dc3dc8954542fde4
/1stSDLWindow/src/Map.cpp
4d703b4f8c78bc994e130e2f472922e5e1c68d4b
[]
no_license
mohitaqpkr/C-_Lean
daac263e9d52fd264da529caeb03fb28894e8e1b
b441e70d23cfa222d4b522a02761ee1c124ad89c
refs/heads/master
2020-04-22T15:30:17.990774
2019-02-13T09:35:10
2019-02-13T09:35:10
170,479,145
0
0
null
null
null
null
UTF-8
C++
false
false
9,435
cpp
#include "Map.h" #include "TextureManager.h" int lvl1[20][25] = { {0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} }; Map::Map() { dirt = TextureManager::LoadTexture("assets/dirt.png"); water = TextureManager::LoadTexture("assets/water.png"); grass = TextureManager::LoadTexture("assets/grass.png"); //LoadMap(lvl1); src.x = 0; src.y = 0; src.w = 32; src.h = 32; dest.x = 0; dest.y = 0; dest.w = 32; dest.h = 32; } Map::~Map() { } void Map::LoadMap(int arr[20][25]) { for (int row = 0; row < 20; row++) { for (int column = 0; column < 25; column++) { map[row][column] = arr[row][column]; } } } void Map::LoadDungeonMap(int features) { generate(features); print(); } void Map::DrawMap() { int type = 0; for (int row = 0; row < 20; row++) { for (int column = 0; column < 25; column++) { type = map[row][column]; dest.x = column *32; dest.y = row * 32; switch (type) { case 0: TextureManager::Draw(water, src, dest); break; case 1: TextureManager::Draw(grass, src, dest); break; case 2: TextureManager::Draw(dirt, src, dest); break; default: break; } } } } //Dungeon Map::Map(int width, int height) : _width(width) , _height(height) , _tiles(width * height, Unused) , _rooms() , _exits() { //_width = width; //_height = height; dirt = TextureManager::LoadTexture("assets/dirt.png"); water = TextureManager::LoadTexture("assets/water.png"); grass = TextureManager::LoadTexture("assets/grass.png"); src.x = 0; src.y = 0; src.w = 32; src.h = 32; dest.x = 0; dest.y = 0; dest.w = 32; dest.h = 32; } void Map::generate(int maxFeatures) { // place the first room in the center if (!makeRoom(_width / 2, _height / 2, static_cast<Direction>(randomInt(4), true))) { std::cout << "Unable to place the first room.\n"; return; } // we already placed 1 feature (the first room) for (int i = 1; i < maxFeatures; ++i) { if (!createFeature()) { std::cout << "Unable to place more features (placed " << i << ").\n"; break; } } if (!placeObject(UpStairs)) { std::cout << "Unable to place up stairs.\n"; return; } if (!placeObject(DownStairs)) { std::cout << "Unable to place down stairs.\n"; return; } for (char& tile : _tiles) { /*if (tile == Unused) tile = '.'; else if (tile == Floor || tile == Corridor) tile = ' ';*/ if (tile == Unused) tile = '0'; else if (tile == Floor || tile == Corridor) tile = '7'; } } void Map::print() { for (int y = 0; y < _height; ++y) { for (int x = 0; x < _width; ++x) { std::cout << getTile(x, y); map[y][x] = getTile(x, y); } std::cout << std::endl; } } char Map::getTile(int x, int y) const { if (x < 0 || y < 0 || x >= _width || y >= _height) { return Unused; } //std::cout << "width is:" << _width << std::endl; //return _tiles[x + y * _width]; return _tiles.at(x + y * _width); } void Map::setTile(int x, int y, char tile) { _tiles[x + y * _width] = tile; } bool Map::createFeature() { for (int i = 0; i < 1000; ++i) { if (_exits.empty()) break; // choose a random side of a random room or corridor int r = randomInt(_exits.size()); int x = randomInt(_exits[r].x, _exits[r].x + _exits[r].width - 1); int y = randomInt(_exits[r].y, _exits[r].y + _exits[r].height - 1); // north, south, west, east for (int j = 0; j < DirectionCount; ++j) { if (createFeature(x, y, static_cast<Direction>(j))) { _exits.erase(_exits.begin() + r); return true; } } } return false; } bool Map::createFeature(int x, int y, Direction dir) { static const int roomChance = 50; // corridorChance = 100 - roomChance int dx = 0; int dy = 0; if (dir == North) dy = 1; else if (dir == South) dy = -1; else if (dir == West) dx = 1; else if (dir == East) dx = -1; if (getTile(x + dx, y + dy) != Floor && getTile(x + dx, y + dy) != Corridor) return false; if (randomInt(100) < roomChance) { if (makeRoom(x, y, dir)) { setTile(x, y, ClosedDoor); return true; } } else { if (makeCorridor(x, y, dir)) { if (getTile(x + dx, y + dy) == Floor) setTile(x, y, ClosedDoor); else // don't place a door between corridors setTile(x, y, Corridor); return true; } } return false; } bool Map::makeRoom(int x, int y, Direction dir, bool firstRoom) { static const int minRoomSize = 3; static const int maxRoomSize = 6; Rect room; room.width = randomInt(minRoomSize, maxRoomSize); room.height = randomInt(minRoomSize, maxRoomSize); if (dir == North) { room.x = x - room.width / 2; room.y = y - room.height; } else if (dir == South) { room.x = x - room.width / 2; room.y = y + 1; } else if (dir == West) { room.x = x - room.width; room.y = y - room.height / 2; } else if (dir == East) { room.x = x + 1; room.y = y - room.height / 2; } if (placeRect(room, Floor)) { _rooms.emplace_back(room); if (dir != South || firstRoom) // north side _exits.emplace_back(Rect{ room.x, room.y - 1, room.width, 1 }); if (dir != North || firstRoom) // south side _exits.emplace_back(Rect{ room.x, room.y + room.height, room.width, 1 }); if (dir != East || firstRoom) // west side _exits.emplace_back(Rect{ room.x - 1, room.y, 1, room.height }); if (dir != West || firstRoom) // east side _exits.emplace_back(Rect{ room.x + room.width, room.y, 1, room.height }); return true; } return false; } bool Map::makeCorridor(int x, int y, Direction dir) { static const int minCorridorLength = 3; static const int maxCorridorLength = 6; Rect corridor; corridor.x = x; corridor.y = y; if (randomBool()) // horizontal corridor { corridor.width = randomInt(minCorridorLength, maxCorridorLength); corridor.height = 1; if (dir == North) { corridor.y = y - 1; if (randomBool()) // west corridor.x = x - corridor.width + 1; } else if (dir == South) { corridor.y = y + 1; if (randomBool()) // west corridor.x = x - corridor.width + 1; } else if (dir == West) corridor.x = x - corridor.width; else if (dir == East) corridor.x = x + 1; } else // vertical corridor { corridor.width = 1; corridor.height = randomInt(minCorridorLength, maxCorridorLength); if (dir == North) corridor.y = y - corridor.height; else if (dir == South) corridor.y = y + 1; else if (dir == West) { corridor.x = x - 1; if (randomBool()) // north corridor.y = y - corridor.height + 1; } else if (dir == East) { corridor.x = x + 1; if (randomBool()) // north corridor.y = y - corridor.height + 1; } } if (placeRect(corridor, Corridor)) { if (dir != South && corridor.width != 1) // north side _exits.emplace_back(Rect{ corridor.x, corridor.y - 1, corridor.width, 1 }); if (dir != North && corridor.width != 1) // south side _exits.emplace_back(Rect{ corridor.x, corridor.y + corridor.height, corridor.width, 1 }); if (dir != East && corridor.height != 1) // west side _exits.emplace_back(Rect{ corridor.x - 1, corridor.y, 1, corridor.height }); if (dir != West && corridor.height != 1) // east side _exits.emplace_back(Rect{ corridor.x + corridor.width, corridor.y, 1, corridor.height }); return true; } return false; } bool Map::placeRect(const Rect& rect, char tile) { if (rect.x < 1 || rect.y < 1 || rect.x + rect.width > _width - 1 || rect.y + rect.height > _height - 1) return false; for (int y = rect.y; y < rect.y + rect.height; ++y) for (int x = rect.x; x < rect.x + rect.width; ++x) { if (getTile(x, y) != Unused) return false; // the area already used } for (int y = rect.y - 1; y < rect.y + rect.height + 1; ++y) for (int x = rect.x - 1; x < rect.x + rect.width + 1; ++x) { if (x == rect.x - 1 || y == rect.y - 1 || x == rect.x + rect.width || y == rect.y + rect.height) setTile(x, y, Wall); else setTile(x, y, tile); } return true; } bool Map::placeObject(char tile) { if (_rooms.empty()) return false; int r = randomInt(_rooms.size()); // choose a random room int x = randomInt(_rooms[r].x + 1, _rooms[r].x + _rooms[r].width - 2); int y = randomInt(_rooms[r].y + 1, _rooms[r].y + _rooms[r].height - 2); if (getTile(x, y) == Floor) { setTile(x, y, tile); // place one object in one room (optional) _rooms.erase(_rooms.begin() + r); return true; } return false; }
[ "mohit@aquacrmsoftware.com" ]
mohit@aquacrmsoftware.com
d0dd96876f6844d4a08e3acefd415f081807c7d4
0611b1cc08b15d329057595365359947c20fcd59
/sf/kaoshi/1.cpp
900b544c558f4c5b59c021919367bf1b30db0974
[]
no_license
Lan-ce-lot/overflow
c9a7167edaeeaa1f9f1e92624726b1d964289798
ae76120e328a5a2991eb6ef7f1ae5e279374e15c
refs/heads/master
2023-04-08T04:24:49.614146
2021-04-25T05:33:06
2021-04-25T05:33:06
279,082,035
0
0
null
null
null
null
UTF-8
C++
false
false
642
cpp
#include <bits/stdc++.h> using namespace std; const int M = 8009999, N = M; vector<int> g[N]; int n, m, I[N], O[N], S, f[N], i, a, u; queue<int> q; int main() { cin >> n >> m; for (; i < m; i++) cin >> a >> u, g[a].push_back(u), I[u]++, O[a]++; for (i = 1; i <= n; i++) if (!I[i]) f[i] = 1, q.push(i); while (!q.empty()) { u = q.front(), q.pop(); for (i = 0; i < g[u].size(); i++) { f[g[u][i]] += f[u] % M, I[g[u][i]]--; if (!I[g[u][i]]) { q.push(g[u][i]); if (!O[g[u][i]]) S += f[g[u][i]] % M; } } } cout << S % M; }
[ "1984737645@qq.com" ]
1984737645@qq.com
8fc47c5956b1212a7d24a85af68dae9b78590e1f
180ef8df3983b9e5ac941e6c491cc5c8747bd512
/leetcode/algorithms/c++/Paint Fence/Paint Fence.cpp
a3f5dbd8cdb9c897be0945324027261cc2728164
[]
no_license
withelm/Algorytmika
71f098cb31c9265065d2d660c24b90dd07a3d078
4c37c9b2e75661236046c2af19bb81381ce0a522
refs/heads/master
2021-12-09T12:58:45.671880
2021-08-22T08:03:04
2021-08-22T08:03:04
10,869,703
0
0
null
null
null
null
UTF-8
C++
false
false
364
cpp
class Solution { public: int numWays(int n, int k) { if (n == 0) return 0; if (n == 1) return k; vector<int> dp(n, 1); dp[1] = k; for (int col = 2; col < n; col++) { dp[col] = dp[col - 1] * (k - 1) + dp[col - 2] * (k - 1); } return dp[n - 1] * k; } };
[ "withelm@gmail.com" ]
withelm@gmail.com
bef2659e60a0f8ea91b2bc76c66cb7361ef007f7
d9c62de55641ed224dd340b0010885e8163cbdbd
/Laborator7/Laborator7.cpp
658ab87ef7c71423fd87b6b78f02608b595ee21d
[]
no_license
albertchirila/EGC
f866d1f65b4202b5608fe8f24dffb60fcefcd202
3458201ec116fc07acd492acb5e2cf1c6c8da112
refs/heads/main
2023-02-16T04:18:55.682467
2021-01-14T14:32:28
2021-01-14T14:32:28
329,639,760
0
0
null
null
null
null
UTF-8
C++
false
false
6,959
cpp
#include "Laborator7.h" #include <vector> #include <string> #include <iostream> #include <Core/Engine.h> using namespace std; Laborator7::Laborator7() { } Laborator7::~Laborator7() { } void Laborator7::Init() { { Mesh* mesh = new Mesh("box"); mesh->LoadMesh(RESOURCE_PATH::MODELS + "Primitives", "box.obj"); meshes[mesh->GetMeshID()] = mesh; } { Mesh* mesh = new Mesh("sphere"); mesh->LoadMesh(RESOURCE_PATH::MODELS + "Primitives", "sphere.obj"); meshes[mesh->GetMeshID()] = mesh; } { Mesh* mesh = new Mesh("plane"); mesh->LoadMesh(RESOURCE_PATH::MODELS + "Primitives", "plane50.obj"); meshes[mesh->GetMeshID()] = mesh; } // Create a shader program for drawing face polygon with the color of the normal { Shader *shader = new Shader("ShaderLab7"); shader->AddShader("Source/Laboratoare/Laborator7/Shaders/VertexShader.glsl", GL_VERTEX_SHADER); shader->AddShader("Source/Laboratoare/Laborator7/Shaders/FragmentShader.glsl", GL_FRAGMENT_SHADER); shader->CreateAndLink(); shaders[shader->GetName()] = shader; } //Light & material properties { lightPosition = glm::vec3(0, 1, 1); materialShininess = 30; materialKd = 0.5; materialKs = 0.5; } } void Laborator7::FrameStart() { // clears the color buffer (using the previously set color) and depth buffer glClearColor(0, 0, 0, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glm::ivec2 resolution = window->GetResolution(); // sets the screen area where to draw glViewport(0, 0, resolution.x, resolution.y); } void Laborator7::Update(float deltaTimeSeconds) { { glm::mat4 modelMatrix = glm::mat4(1); modelMatrix = glm::translate(modelMatrix, glm::vec3(0, 1, 0)); RenderSimpleMesh(meshes["sphere"], shaders["ShaderLab7"], modelMatrix); } { glm::mat4 modelMatrix = glm::mat4(1); modelMatrix = glm::translate(modelMatrix, glm::vec3(2, 0.5f, 0)); modelMatrix = glm::rotate(modelMatrix, RADIANS(60.0f), glm::vec3(1, 0, 0)); modelMatrix = glm::scale(modelMatrix, glm::vec3(0.5f)); RenderSimpleMesh(meshes["box"], shaders["ShaderLab7"], modelMatrix); } { glm::mat4 modelMatrix = glm::mat4(1); modelMatrix = glm::translate(modelMatrix, glm::vec3(-2, 0.5f, 0)); modelMatrix = glm::rotate(modelMatrix, RADIANS(60.0f), glm::vec3(1, 1, 0)); RenderSimpleMesh(meshes["box"], shaders["ShaderLab7"], modelMatrix, glm::vec3(0, 0.5, 0)); } // Render ground { glm::mat4 modelMatrix = glm::mat4(1); modelMatrix = glm::translate(modelMatrix, glm::vec3(0, 0.01f, 0)); modelMatrix = glm::scale(modelMatrix, glm::vec3(0.25f)); RenderSimpleMesh(meshes["plane"], shaders["ShaderLab7"], modelMatrix); } // Render the point light in the scene { glm::mat4 modelMatrix = glm::mat4(1); modelMatrix = glm::translate(modelMatrix, lightPosition); modelMatrix = glm::scale(modelMatrix, glm::vec3(0.1f)); RenderMesh(meshes["sphere"], shaders["Simple"], modelMatrix); } } void Laborator7::FrameEnd() { DrawCoordinatSystem(); } void Laborator7::RenderSimpleMesh(Mesh *mesh, Shader *shader, const glm::mat4 & modelMatrix, const glm::vec3 &color) { if (!mesh || !shader || !shader->GetProgramID()) return; // render an object using the specified shader and the specified position glUseProgram(shader->program); // Set shader uniforms for light & material properties // TODO: Set light position uniform GLint locLightPos = glGetUniformLocation(shader->program, "light_position"); glUniform3fv(locLightPos, 1, glm::value_ptr(lightPosition)); // TODO: Set eye position (camera position) uniform glm::vec3 eyePosition = GetSceneCamera()->transform->GetWorldPosition(); GLint locEyePos = glGetUniformLocation(shader->program, "eye_position"); glUniform3fv(locEyePos, 1, glm::value_ptr(eyePosition)); // TODO: Set material property uniforms (shininess, kd, ks, object color) GLint locMaterial = glGetUniformLocation(shader->program, "material_shininess"); glUniform1i(locMaterial, materialShininess); GLint locMaterialKd = glGetUniformLocation(shader->program, "material_kd"); // diffuse light glUniform1f(locMaterialKd, materialKd); GLint locMaterialKs = glGetUniformLocation(shader->program, "material_ks"); // specular light glUniform1f(locMaterialKs, materialKs); GLint locObject = glGetUniformLocation(shader->program, "object_color"); glUniform3fv(locObject, 1, glm::value_ptr(color)); // Bind model matrix GLint loc_model_matrix = glGetUniformLocation(shader->program, "Model"); glUniformMatrix4fv(loc_model_matrix, 1, GL_FALSE, glm::value_ptr(modelMatrix)); // Bind view matrix glm::mat4 viewMatrix = GetSceneCamera()->GetViewMatrix(); int loc_view_matrix = glGetUniformLocation(shader->program, "View"); glUniformMatrix4fv(loc_view_matrix, 1, GL_FALSE, glm::value_ptr(viewMatrix)); // Bind projection matrix glm::mat4 projectionMatrix = GetSceneCamera()->GetProjectionMatrix(); int loc_projection_matrix = glGetUniformLocation(shader->program, "Projection"); glUniformMatrix4fv(loc_projection_matrix, 1, GL_FALSE, glm::value_ptr(projectionMatrix)); // Draw the object glBindVertexArray(mesh->GetBuffers()->VAO); glDrawElements(mesh->GetDrawMode(), static_cast<int>(mesh->indices.size()), GL_UNSIGNED_SHORT, 0); } // Documentation for the input functions can be found in: "/Source/Core/Window/InputController.h" or // https://github.com/UPB-Graphics/Framework-EGC/blob/master/Source/Core/Window/InputController.h void Laborator7::OnInputUpdate(float deltaTime, int mods) { float speed = 2; if (!window->MouseHold(GLFW_MOUSE_BUTTON_RIGHT)) { glm::vec3 up = glm::vec3(0, 1, 0); glm::vec3 right = GetSceneCamera()->transform->GetLocalOXVector(); glm::vec3 forward = GetSceneCamera()->transform->GetLocalOZVector(); forward = glm::normalize(glm::vec3(forward.x, 0, forward.z)); // Control light position using on W, A, S, D, E, Q if (window->KeyHold(GLFW_KEY_W)) lightPosition -= forward * deltaTime * speed; if (window->KeyHold(GLFW_KEY_A)) lightPosition -= right * deltaTime * speed; if (window->KeyHold(GLFW_KEY_S)) lightPosition += forward * deltaTime * speed; if (window->KeyHold(GLFW_KEY_D)) lightPosition += right * deltaTime * speed; if (window->KeyHold(GLFW_KEY_E)) lightPosition += up * deltaTime * speed; if (window->KeyHold(GLFW_KEY_Q)) lightPosition -= up * deltaTime * speed; } } void Laborator7::OnKeyPress(int key, int mods) { // add key press event } void Laborator7::OnKeyRelease(int key, int mods) { // add key release event } void Laborator7::OnMouseMove(int mouseX, int mouseY, int deltaX, int deltaY) { // add mouse move event } void Laborator7::OnMouseBtnPress(int mouseX, int mouseY, int button, int mods) { // add mouse button press event } void Laborator7::OnMouseBtnRelease(int mouseX, int mouseY, int button, int mods) { // add mouse button release event } void Laborator7::OnMouseScroll(int mouseX, int mouseY, int offsetX, int offsetY) { } void Laborator7::OnWindowResize(int width, int height) { }
[ "albertchirila99@yahoo.com" ]
albertchirila99@yahoo.com
87416d94faa1290c16b77924a3601015fe4828ff
9f0479d3158dc1fc92ab746a94c72d571fc3dfca
/PreProcessing/band.hpp
8a1c4738a11ca67161f7094d531b7a4dd8c5c6b6
[ "BSD-3-Clause", "libtiff", "MIT", "ImageMagick" ]
permissive
pr5syl3ed/Multispectral-Image-Pre-Processing
2848daeb9dacd37f026ca611ed7b0c41389b8a0f
e5851e03ce46c57b0427ebbe2fc7e44aa18b5f8f
refs/heads/master
2021-01-18T11:41:27.203403
2017-08-23T09:08:08
2017-08-23T09:08:08
100,361,058
1
0
null
null
null
null
WINDOWS-1250
C++
false
false
11,662
hpp
//---------------------------------------- // Project: Multispectral Image PreProcessing Tool // Partially developed by: pr5syl3ed // Date: 2017-08-18 //---------------------------------------- // OpenCV License // //By downloading, copying, installing or using the software you agree to this license. //If you do not agree to this license, do not download, install, copy or use //the software. // //License Agreement //For Open Source Computer Vision Library //(3 - clause BSD License) // //Redistribution and use in source and binary forms, with or without //modification, are permitted provided that the following conditions are met : // //- Redistributions of source code must retain the above copyright notice, //this list of conditions and the following disclaimer. // //- Redistributions in binary form must reproduce the above copyright notice, //this list of conditions and the following disclaimer in the documentation //and/or other materials provided with the distribution. // //- Neither the names of the copyright holders nor the names of the 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 copyright //holders 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. // // //Copyright[yyyy][name of copyright owner] // //Licensed under the ImageMagick License(the "License"); you may not use //this file except in compliance with the License.You may obtain a copy //of the License at // //https ://www.imagemagick.org/script/license.php // //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. // // // // // // // // //GDAL / OGR Licensing //================== //Copyright(c) 2000, Frank Warmerdam // //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. // // // // License dirent.h // //The MIT License(MIT) // //Copyright(c) 2015 Toni Rönkkö // //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. // // // // LIBTIFF License // //Copyright(c) 1988 - 1997 Sam Leffler //Copyright(c) 1991 - 1997 Silicon Graphics, Inc. // //Permission to use, copy, modify, distribute, and sell this software and //its documentation for any purpose is hereby granted without fee, provided //that(i) the above copyright notices and this permission notice appear in //all copies of the software and related documentation, and (ii)the names of //Sam Leffler and Silicon Graphics may not be used in any advertising or //publicity relating to the software without the specific, prior written //permission of Sam Leffler and Silicon Graphics. // //THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, //EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY //WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. // //IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR //ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, //OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, //WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF //LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE //OF THIS SOFTWARE. // #pragma once //do not read include files twice if already included #include "stdafx.h" #include <opencv2\core\core.hpp> #include <opencv2\highgui\highgui.hpp> #include <iostream> #include <opencv2\opencv.hpp> #include <iostream> #include <string> #include <tiffio.h> #include <tiff.h> #include <math.h> #include "opencv2/features2d.hpp" //xfeat #include <Magick++.h> #include <list> #include <filesystem> #include <dirent.h> #include <sstream> #include <stdlib.h> #include <direct.h> #include <stdio.h> #include <fstream> #include <cstring> #include <cstddef> #include <cstdlib> #include <cstdarg> #include <bitset> //#include <windows.h> //#include <gdiplus.h> #include <stdarg.h> using namespace cv; using namespace std; using namespace Magick; //using namespace Gdiplus; class band { private: uint32 *tmp1; //temporary pointer uint32 xRes; //Image width uint32 yRes; //image height uint32 bitDepth; //image bitdepth char tmp[255]; //buffer for parsing .tif file unsigned int blacklevel[4]; //blacklevels 0-4 probably oddrow, evenrow, oddcol, evencol long adress; //First ifd adress to jump cv::Mat bitmap; //image buffer unsigned int x = 0; //unvignetting counter unsigned int y = 0;//unvignetting counter double xd = 0.0;//unvignetting counter double yd = 0.0;//unvignetting counter unsigned int channel = 1; //1blue 2green 3red 4NIR 5REdedge Vec3s intensity; //unvignetting double blue; //unvignetting cv::Mat distCoeff; //undistortion cv::Mat cam1; //undistortion cv::Mat buffer; //undistortion string filepath; bool is_blackframe = false; cv::Mat blackframe[256]; //stores 16 blackframes unsigned int counter = 0; unsigned int frame_state = 0; cv::Mat master_blackframe; bool was_blackframe = false; //if last frame was a black frame but the next one is not unsigned int col_counter = 0; unsigned int row_counter = 0; double mean_col_calc[960]; //unvignetting parameter double mean_row_calc[1280]; //unvignetting parameter unsigned int tmp_counter = 0; unsigned int tmp_integer = 0; double row; double mean_col; unsigned int blacklevel_sorted[4]; //the smallest blacklevel is [0] cv::Mat bitmap_signed; cv::Mat black_frame_rec_tmp; unsigned int counter_denoise = 0; cv::Mat abc; cv::Mat def; unsigned int blackframeID_first_before; unsigned int blackframeID_last_before; // Hardcoded Undistortion lens parameters for specific camera double cx_m[5] = { 643.8893602713686,646.2876348370665, 635.112765023685,650.0172410017597, 640.2070796834802 }; double cy_m[5] = { 478.9601599362568,487.8870702000254, 475.9487632367042,489.013354837388,476.4464172256909 }; double fx_m[5] = { 1440.458661165309,1438.025532800022, 1449.574428100889,1448.951418563583, 1445.654664815826 }; double fy_m[5] = { 1440.756614433281, 1438.404713281228, 1450.17247718981,1449.44316823106, 1446.22861154131 }; double k1_m[5] = { -0.09667331646150404, -0.1010525208325428, -0.1042476549325377, -0.1087931871993678, -0.1047408687298381 }; double k2_m[5] = { 0.1521699647928558, 0.1478560987422327, 0.1617802407386409, 0.1682341016318963, 0.1566098332433733 }; double k3_m[5] = { -0.04861534157162112, -0.03838675728217016, -0.05795061949340015, -0.07950791535676657,-0.05174867374762403 }; double k4_m[5] = { 0,0,0,0,0 }; double k5_m[5] = { 0,0,0,0,0 }; double k6_m[5] = { 0,0,0,0,0 }; double p1_m[5] = { -0.0001392743237024886, 0.0005756050781485842, -0.0004677471183437311, 7.218071488114875e-05,0.0009096817577642966 }; double p2_m[5] = { 0.0003938833050405934, 0.0007577955328215453, 0.0008923504691781989,0.0003125173327344626,0.0004917933128005809 }; // Hardcoded Unvignetting lens parameters for specific camera double cx_vign[5] = { 615.0152608933483, 644.3574607588573,637.8219259304681, 634.9355405530644, 651.285524604551 }; double cy_vign[5] = { 477.6321764467883, 476.9726085013394,478.6311498549013, 479.1132551629033,478.6735660570274 }; double k1_vign[5] = { -0.0003417783394512867, -0.0003018824102758406,-0.0001337885913441529, 0.0002149127263262391, -6.776451649295096e-05 }; double k2_vign[5] = { 3.441122739502885e-06,3.455991934675517e-06,1.55949208084643e-06, -4.337508825792706e-06, 2.100633240402365e-07 }; double k3_vign[5] = { -1.848012657237475e-08, -1.988224398824752e-08, -1.016783227835597e-08, 8.873013544504981e-09,-6.385106893758652e-09 }; double k4_vign[5] = { 4.49482539293681e-11, 4.997222904095209e-11, 2.399024838594838e-11, -3.598433534409943e-12, 2.022816878372607e-11 }; double k5_vign[5] = { -5.11116229072061e-14,-5.810650981542908e-14, -2.573233269260111e-14, -7.534529507621262e-15, -2.584696084211612e-14 }; double k6_vign[5] = { 2.154669597661016e-17, 2.489998847836525e-17, 1.000230573442146e-17, 5.957094806158578e-18, 1.155697586103054e-17 }; public: void unvignette(void); //remove lens vignetting band(unsigned int); //constructor void undistortion(void); //remove lens distortion void denoise(void); //reduce image noise void calibrate(void); //calibrate camera signal response unsigned int getchannel(void); //get channel of current image cv::Mat getbitmap(void); //returns the image string getfilename(void); //returns the filename of the image void loadBitmap(string,bool); //load the image and metadata and also filename cv::Mat band::get_masterblackframe(void); bool is_bl(void); };
[ "noreply@github.com" ]
noreply@github.com
3411bfd48e9042bb30e0cd7d3b0d70559797f41d
4f4cd0d52017ac1d59291bbf4f18536b943529fe
/ProjectFolder/ProjectTutorialKinect/Projects/KinectEvolution-XAML/KinectEvolution.Xaml/KinectEvolution.Xaml.Controls/SkeletonPanel.h
f5452e3d10c60aac27cbba3e0b7d4aa34476fa0c
[]
no_license
jacquemard/tutoriel_kinect
812178fcc27dd23c1fef03140127bdf242db9c03
877b0a7efacc5e671f09ab6244d1e4f109f21351
refs/heads/master
2023-05-05T05:35:43.345310
2018-10-18T16:40:40
2018-10-18T16:40:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,733
h
//------------------------------------------------------------------------------ // <copyright file="SkeletonPanel.h" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ #pragma once #include "Panel.h" #include "PrimitiveMesh.h" #include "PrimitiveEffect.h" namespace KinectEvolution { namespace Xaml { namespace Controls { namespace Skeleton { using namespace KinectEvolution::Xaml::Controls::Base; using namespace WindowsPreview::Kinect; enum class Body2DMode { DepthIR, Color, }; struct Bone { JointType JointA; JointType JointB; }; static const struct Bone BodyBones [] = { { JointType::SpineBase, JointType::SpineMid }, { JointType::SpineMid, JointType::SpineShoulder }, { JointType::SpineShoulder, JointType::Neck }, { JointType::Neck, JointType::Head }, { JointType::SpineShoulder, JointType::ShoulderLeft }, { JointType::ShoulderLeft, JointType::ElbowLeft }, { JointType::ElbowLeft, JointType::WristLeft }, { JointType::WristLeft, JointType::HandLeft }, { JointType::HandLeft, JointType::HandTipLeft }, { JointType::WristLeft, JointType::ThumbLeft }, { JointType::SpineShoulder, JointType::ShoulderRight }, { JointType::ShoulderRight, JointType::ElbowRight }, { JointType::ElbowRight, JointType::WristRight }, { JointType::WristRight, JointType::HandRight }, { JointType::HandRight, JointType::HandTipRight }, { JointType::WristRight, JointType::ThumbRight }, { JointType::SpineBase, JointType::HipLeft }, { JointType::HipLeft, JointType::KneeLeft }, { JointType::KneeLeft, JointType::AnkleLeft }, { JointType::AnkleLeft, JointType::FootLeft }, { JointType::SpineBase, JointType::HipRight }, { JointType::HipRight, JointType::KneeRight }, { JointType::KneeRight, JointType::AnkleRight }, { JointType::AnkleRight, JointType::FootRight }, }; // following the hand state color table in NuiView static const DirectX::XMVECTOR HandStateColorTable [] = { { 0.0f, 1.0f, 0.0f, 0.7f }, // open { 1.0f, 0.0f, 0.0f, 0.7f }, // closed { 0.0f, 0.0f, 1.0f, 0.7f }, // lasso { 0.5f, 0.5f, 0.5f, 0.5f }, // unknown }; static const int BODY_COUNT = 6; static const int JOINT_COUNT = 25; static const XMVECTOR NotTrackedColor = { 0.0f, 0.0f, 0.0f, 0.3f }; static const float DefaultJointSize = 0.05f; // diameter in world space (meters) static const float DefaultBoneSize = 0.03f; // diameter in world space static const float NonTrackedScale = 0.3f; // render non-tracked joints different than tracked ones static const float DefaultNormalHandleSize = 0.01f; // diameter of the handle static const float DefaultNormalHandleLength = 0.05f; // length of the handle static const float DefaultNormalArrowLength = 0.05f; static const float DefaultHandStateSize = 4 * DefaultJointSize; [Windows::Foundation::Metadata::WebHostHidden] public ref class SkeletonPanel sealed : public Panel { public: SkeletonPanel(); property WRK::BodyFrameSource^ BodySource { WRK::BodyFrameSource^ get(); void set(_In_ WRK::BodyFrameSource^ value); } property bool RenderBones; property bool RenderJoints; property bool RenderHandStates; property bool RenderJointOrientations; protected private: virtual event Windows::UI::Xaml::Data::PropertyChangedEventHandler^ PropertyChanged; void NotifyPropertyChanged(Platform::String^ prop); virtual void Update(double elapsedTime) override; virtual void Render() override; virtual bool IsLoadingComplete() override { return Panel::IsLoadingComplete() && _loadingComplete; } virtual void ResetDeviceResources() override; virtual void CreateDeviceResources() override; virtual void CreateSizeDependentResources() override; // override to add mouse/touch/pen input virtual void StartRenderLoop() override; virtual void StopRenderLoop() override; private: ~SkeletonPanel(); void DoRenderJoints(UINT bodyIndex, _In_opt_ const PrimitiveParameter* pEffect, float pJointSizeMeters); void DoRenderBones(UINT bodyIndex, _In_opt_ const PrimitiveParameter* pEffect, float pBoneSizeMeters); void RenderBodyHandStates(UINT bodyIndex); void RenderBodyJointOrientations(UINT bodyIndex, _In_opt_ const PrimitiveParameter* pEffect); void RenderBodyJoints(UINT bodyIndex, _In_opt_ const PrimitiveParameter* pEffect) { DoRenderJoints(bodyIndex, pEffect, DefaultJointSize); } void RenderBodyJoints(UINT bodyIndex, _In_opt_ const PrimitiveParameter* pEffect, float pJointSizeMeters) { DoRenderJoints(bodyIndex, pEffect, pJointSizeMeters); } void RenderBodyBones(UINT bodyIndex, _In_opt_ const PrimitiveParameter* pEffect) { DoRenderBones(bodyIndex, pEffect, DefaultBoneSize); } void RenderBodyBones(UINT bodyIndex, _In_opt_ const PrimitiveParameter* pEffect, float pBoneSizeMeters) { DoRenderBones(bodyIndex, pEffect, pBoneSizeMeters); } XMMATRIX GetViewMatrix() { return _viewMatrix; } XMMATRIX GetProjectionMatrix() { return _projectionMatrix; } void ApplyTransformWithWorldViewMatrix(_In_ const DirectX::XMMATRIX& worldViewMatrix) { DirectX::XMMATRIX wvp = worldViewMatrix * GetProjectionMatrix(); _bodyMeshEffect->ApplyTransformAll(_d3dContext.Get(), worldViewMatrix, wvp); } void ApplyTransformWithWorldMatrix(_In_ const DirectX::XMMATRIX& worldMatrix) { DirectX::XMMATRIX wv = worldMatrix * GetViewMatrix(); ApplyTransformWithWorldViewMatrix(wv); } private: BOOL _loadingComplete; Microsoft::WRL::ComPtr<ID3D11BlendState> _blendState; PrimitiveEffect^ _bodyMeshEffect; DirectX::XMMATRIX _viewMatrix; DirectX::XMMATRIX _projectionMatrix; WRK::BodyFrameSource^ _bodySource; WRK::BodyFrameReader^ _bodyReader; Windows::Foundation::Collections::IVector<Body^>^ _bodies; WRK::Vector4 _floorPlane; }; } } } }
[ "remi.jacquemard@heig-vd.ch" ]
remi.jacquemard@heig-vd.ch
34d9a8fd0a562d7d14ea6366efdea33147481d6c
d2a01795ec83a253367a8e268a895b9c3621dcc5
/lab10/prelab10/heap.cpp
0c7d4edda664559edd87d04f3c8531bff57ba8fb
[]
no_license
johnzheng300/Program-and-Data-Representation
032192fec9867296bb2b1f75d0bc446e69c9142e
b8b187dd11cc15bbbac4758aa2803fc5b395b5fd
refs/heads/master
2020-07-28T12:07:59.538146
2019-09-18T21:07:28
2019-09-18T21:07:28
209,404,081
0
3
null
null
null
null
UTF-8
C++
false
false
3,170
cpp
// Code written by Aaron Bloomfield, 2014 // Released under a CC BY-SA license // This code is part of the https://github.com/aaronbloomfield/pdr repository #include <iostream> #include "heap.h" using namespace std; // default constructor binary_heap::binary_heap() : heap_size(0) { heap.push_back(0); } // builds a heap from an unsorted vector binary_heap::binary_heap(vector<huffmanNode*> vec) : heap_size(vec.size()) { heap = vec; heap.push_back(heap[0]); heap[0] = 0; for ( int i = heap_size/2; i > 0; i-- ) percolateDown(i); } // the destructor doesn't need to do much binary_heap::~binary_heap() { } void binary_heap::insert(huffmanNode* node) { // a vector push_back will resize as necessary heap.push_back(node); // move it up into the right position percolateUp(++heap_size); } void binary_heap::percolateUp(int hole) { // get the value just inserted huffmanNode* node = heap[hole]; // while we haven't run off the top and while the // value is less than the parent... for ( ; (hole > 1) && (node->count < heap[hole/2]->count); hole /= 2 ) heap[hole] = heap[hole/2]; // move the parent down // correct position found! insert at that spot heap[hole] = node; } huffmanNode* binary_heap::deleteMin() { // make sure the heap is not empty if ( heap_size == 0 ) throw "deleteMin() called on empty heap"; // save the value to be returned huffmanNode* ret = heap[1]; // move the last inserted position into the root heap[1] = heap[heap_size--]; // make sure the vector knows that there is one less element heap.pop_back(); // percolate the root down to the proper position percolateDown(1); // return the old root node return ret; } void binary_heap::percolateDown(int hole) { // get the value to percolate down huffmanNode* x = heap[hole]; // while there is a left child... while ( hole*2 <= heap_size ) { int child = hole*2; // the left child // is there a right child? if so, is it lesser? if ( (child+1 <= heap_size) && (heap[child+1]->count < heap[child]->count) ) child++; // if the child is greater than the node... if ( x->count > heap[child]->count ) { heap[hole] = heap[child]; // move child up hole = child; // move hole down } else break; } // correct position found! insert at that spot heap[hole] = x; } huffmanNode* binary_heap::findMin() { if ( heap_size == 0 ) throw "findMin() called on empty heap"; return heap[1]; } unsigned int binary_heap::size() { return heap_size; } void binary_heap::makeEmpty() { heap_size = 0; heap.resize(1); } bool binary_heap::isEmpty() { return heap_size == 0; } void binary_heap::print() { cout << "(" << heap[0] << ") "; for ( int i = 1; i <= heap_size; i++ ) { cout << heap[i] << " "; // next line from from http://tinyurl.com/mf9tbgm bool isPow2 = (((i+1) & ~(i))==(i+1))? i+1 : 0; if ( isPow2 ) cout << endl << "\t"; } cout << endl; }
[ "johnzheng@Johns-MBP-5.local" ]
johnzheng@Johns-MBP-5.local
0c5b36e835fd87d2bff1d7cca7965eb513d17829
df6a7072020c0cce62a2362761f01c08f1375be7
/doc/quickbook/oglplus/quickref/enums/color_buffer_class.hpp
3e7ce752bae811cc2c9bb98044467396fecbdb00
[ "BSL-1.0" ]
permissive
matus-chochlik/oglplus
aa03676bfd74c9877d16256dc2dcabcc034bffb0
76dd964e590967ff13ddff8945e9dcf355e0c952
refs/heads/develop
2023-03-07T07:08:31.615190
2021-10-26T06:11:43
2021-10-26T06:11:43
8,885,160
368
58
BSL-1.0
2018-09-21T16:57:52
2013-03-19T17:52:30
C++
UTF-8
C++
false
false
1,296
hpp
// File doc/quickbook/oglplus/quickref/enums/color_buffer_class.hpp // // Automatically generated file, DO NOT modify manually. // Edit the source 'source/enums/oglplus/color_buffer.txt' // or the 'source/enums/make_enum.py' script instead. // // Copyright 2010-2019 Matus Chochlik. // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // //[oglplus_enums_color_buffer_class #if !__OGLPLUS_NO_ENUM_VALUE_CLASSES namespace enums { template <typename Base, template <__ColorBuffer> class Transform> class __EnumToClass<Base, __ColorBuffer, Transform> /*< Specialization of __EnumToClass for the __ColorBuffer enumeration. >*/ : public Base { public: EnumToClass(); EnumToClass(Base&& base); Transform<ColorBuffer::None> None; Transform<ColorBuffer::FrontLeft> FrontLeft; Transform<ColorBuffer::FrontRight> FrontRight; Transform<ColorBuffer::BackLeft> BackLeft; Transform<ColorBuffer::BackRight> BackRight; Transform<ColorBuffer::Front> Front; Transform<ColorBuffer::Back> Back; Transform<ColorBuffer::Left> Left; Transform<ColorBuffer::Right> Right; Transform<ColorBuffer::FrontAndBack> FrontAndBack; }; } // namespace enums #endif //]
[ "chochlik@gmail.com" ]
chochlik@gmail.com
06ab94a193768ca39a0a831592cc973ad84e8323
1aba29a1df97dcb7990d7b93a7042307f9afad42
/DataStructure/ex5.cpp
2020e140ca07fece69ccf8d3c3438e32bfd8b39c
[]
no_license
kkw-11/DataStructure
e9643f3831aa4de3e4ab0951efcdb3452a05feba
05de012b60712ae706ed154aaf2ca01291aed699
refs/heads/master
2023-07-20T23:39:27.245094
2021-08-19T12:53:05
2021-08-19T12:53:05
326,662,580
0
0
null
null
null
null
UHC
C++
false
false
13,300
cpp
#include <stdio.h> #include <stdlib.h> typedef struct q_ { int* queue; int front, rear; int capacity; }Queue; //서버(Queue) void Push(Queue* q, int data) { if ((q->rear + 1) % q->capacity == q->front) return; //rear가 0,1,2,3,4 가 되는 코드 /*rear = rear + 1; if (rear == 5) rear = 0;*/ q->rear = (q->rear + 1) % q->capacity; //위 주석 처리 코드와 같음(rear가 0,1,2,4가 되는 코드) q->queue[q->rear] = data; } int Pop(Queue* q) { if (q->front == q->rear) return 0xfffffff; //오류값으로 임의의 큰 값 지정 //Push에서 대입전 rear를 증가시키고 대입시켰으므로 //Pop에서도 증가시키고 값을 빼야 해당 위치의 값을 정확히 값의 위치로 가리키게됨 q->front = (q->front + 1) % q->capacity; return q->queue[q->front]; } void InitQueue(Queue* q, int cap) { q->queue = (int*)malloc(sizeof(int) * cap); q->capacity = cap; q->front = q->rear = 0; //front 와 rear를 같게만 해주면 됨 0,1,2,3,4 어느것으로 초기화 하든 상관없음 } void UninitQueue(Queue* q) { free(q->queue); q->front = q->rear = 0; //여기서는 Uninit 할거 없지만해줌 } ////////////////////// //클라이언트 int main() { Queue q1; Queue q2; InitQueue(&q1, 100); Push(&q1, 10); Push(&q1, 20); Push(&q1, 30); InitQueue(&q2, 500); Push(&q2, 100); Push(&q2, 150); printf("queue1: %d\n", Pop(&q1)); printf("queue1: %d\n", Pop(&q1)); printf("queue1: %d\n", Pop(&q1)); UninitQueue(&q1); printf("queue2: %d\n", Pop(&q2)); printf("queue2: %d\n", Pop(&q2)); UninitQueue(&q2); return 0; } //#include <stdio.h> //#include <stdlib.h> ////서버(Queue) //typedef struct q_ { // int* queue; // int front, rear; // int capacity; //}Queue; // //void Push(Queue* q, int data) { // if ((q->rear + 1) % q->capacity == q->front) // return; // // //rear가 0,1,2,3,4 가 되는 코드 // /*rear = rear + 1; // if (rear == 5) // rear = 0;*/ // // q->rear = (q->rear + 1) % q->capacity; //위 주석 처리 코드와 같음(rear가 0,1,2,4가 되는 코드) // q->queue[q->rear] = data; //} //int Pop(Queue* q) { // if (q->front == q->rear) // return 0xfffffff; //오류값으로 임의의 큰 값 지정 // // //Push에서 대입전 rear를 증가시키고 대입시켰으므로 // //Pop에서도 증가시키고 값을 빼야 해당 위치의 값을 정확히 값의 위치로 가리키게됨 // q->front = (q->front + 1) % q->capacity; // return q->queue[q->front]; //} //void InitQueue(Queue* q, int cap) { // q->queue = (int*)malloc(sizeof(int) * cap); // q->capacity = cap; // q->front = q->rear = 0; //front 와 rear를 같게만 해주면 됨 0,1,2,3,4 어느것으로 초기화 하든 상관없음 // //} //void UninitQueue(Queue* q) { // free(q->queue); // q->front = q->rear = 0; //여기서는 Uninit 할거 없지만해줌 //} // //////////////////////// ////클라이언트 //int main() { // // Queue q1; // Queue q2; // // InitQueue(&q1, 100); // Push(&q1, 10); // Push(&q1, 20); // Push(&q1, 30); // // InitQueue(&q2, 500); // Push(&q2, 100); // Push(&q2, 150); // // printf("queue1: %d\n", Pop(&q1)); // printf("queue1: %d\n", Pop(&q1)); // printf("queue1: %d\n", Pop(&q1)); // UninitQueue(&q1); // // printf("queue2: %d\n", Pop(&q2)); // printf("queue2: %d\n", Pop(&q2)); // UninitQueue(&q2); // // return 0; //} //#include <stdio.h> //#include <stdlib.h> ////서버(Queue) //typedef struct q_ { // int* queue; // int front, rear; //}Queue; // //void Push(Queue* q, int data) { // if ((q->rear + 1) % 5 == q->front) // return; // // //rear가 0,1,2,3,4 가 되는 코드 // /*rear = rear + 1; // if (rear == 5) // rear = 0;*/ // // q->rear = (q->rear + 1) % 5; //위 주석 처리 코드와 같음(rear가 0,1,2,4가 되는 코드) // q->queue[q->rear] = data; //} //int Pop(Queue* q) { // if (q->front == q->rear) // return 0xfffffff; //오류값으로 임의의 큰 값 지정 // // //Push에서 대입전 rear를 증가시키고 대입시켰으므로 // //Pop에서도 증가시키고 값을 빼야 해당 위치의 값을 정확히 값의 위치로 가리키게됨 // q->front = (q->front + 1) % 5; // return q->queue[q->front]; //} //void InitQueue(Queue* q,int cap) { // q->queue = (int*)malloc(sizeof(int) * cap); // q->front = q->rear = 0; //front 와 rear를 같게만 해주면 됨 0,1,2,3,4 어느것으로 초기화 하든 상관없음 // //} //void UninitQueue(Queue* q) { // free(q->queue); // q->front = q->rear = 0; //여기서는 Uninit 할거 없지만해줌 //} // //////////////////////// ////클라이언트 //int main() { // // Queue q1; // Queue q2; // // InitQueue(&q1,5); // Push(&q1, 10); // Push(&q1, 20); // Push(&q1, 30); // // InitQueue(&q2,5); // Push(&q2, 100); // Push(&q2, 150); // // printf("queue1: %d\n", Pop(&q1)); // printf("queue1: %d\n", Pop(&q1)); // printf("queue1: %d\n", Pop(&q1)); // UninitQueue(&q1); // // printf("queue2: %d\n", Pop(&q2)); // printf("queue2: %d\n", Pop(&q2)); // UninitQueue(&q2); // // return 0; //} //#include <stdio.h> //#include <stdlib.h> ////서버(Queue) //typedef struct q_ { // int queue[5]; // int front, rear; //}Queue; // //void Push(Queue* q, int data) { // if ((q->rear + 1) % 5 == q->front) // return; // // //rear가 0,1,2,3,4 가 되는 코드 // /*rear = rear + 1; // if (rear == 5) // rear = 0;*/ // // q->rear = (q->rear + 1) % 5; //위 주석 처리 코드와 같음(rear가 0,1,2,4가 되는 코드) // q->queue[q->rear] = data; //} //int Pop(Queue* q) { // if (q->front == q->rear) // return 0xfffffff; //오류값으로 임의의 큰 값 지정 // // //Push에서 대입전 rear를 증가시키고 대입시켰으므로 // //Pop에서도 증가시키고 값을 빼야 해당 위치의 값을 정확히 값의 위치를 가리키게됨 // q->front = (q->front + 1) % 5; // return q->queue[q->front]; //} //void InitQueue(Queue* q) { // q->front = q->rear = 0; //front 와 rear를 같게만 해주면 됨 0,1,2,3,4 어느것으로 초기화 하든 상관없음 // //} //void UninitQueue(Queue* q) { // q->front = q->rear = 0; //여기서는 Uninit 할거 없지만해줌 //} // //////////////////////// ////클라이언트 //int main() { // // Queue q1; // Queue q2; // // InitQueue(&q1); // Push(&q1, 10); // Push(&q1, 20); // Push(&q1, 30); // // InitQueue(&q2); // Push(&q2, 100); // Push(&q2, 150); // // printf("queue1: %d\n", Pop(&q1)); // printf("queue1: %d\n", Pop(&q1)); // printf("queue1: %d\n", Pop(&q1)); // UninitQueue(&q1); // // printf("queue2: %d\n", Pop(&q2)); // printf("queue2: %d\n", Pop(&q2)); // UninitQueue(&q2); // // return 0; //} //#include <stdio.h> //#include <stdlib.h> ////서버(Queue) //typedef struct q_ { // int queue[5]; // int front, rear; //}Queue; // //void Push(Queue* q, int data) { // if ((q->rear + 1) % 5 == q->front) // return; // // //rear가 0,1,2,3,4 가 되는 코드 // /*rear = rear + 1; // if (rear == 5) // rear = 0;*/ // // q->rear = (q->rear + 1) % 5; //위 주석 처리 코드와 같음(rear가 0,1,2,4가 되는 코드) // q->queue[q->rear] = data; //} //int Pop(Queue* q) { // if (q->front == q->rear) // return 0xfffffff; //오류값으로 임의의 큰 값 지정 // // //Push에서 대입전 rear를 증가시키고 대입시켰으므로 // //Pop에서도 증가시키고 값을 빼야 해당 위치의 값을 정확히 값의 위치를 가리키게됨 // q->front = (q->front + 1) % 5; // return q->queue[q->front]; //} //////////////////////// ////클라이언트 //int main() { // // Queue 구조체가 어떤지 알기 때문에 // // 아래 처럼 초기화 가능한것 사실 이렇게 하면안됨 그래서 초기화 함수생성 // // Queue q1 = {0}; // Queue q2 = {0}; // // Push(&q1, 10); // Push(&q1, 20); // Push(&q1, 30); // // Push(&q2, 100); // Push(&q2, 150); // // printf("queue1: %d\n", Pop(&q1)); // printf("queue1: %d\n", Pop(&q1)); // printf("queue1: %d\n", Pop(&q1)); // // printf("queue2: %d\n", Pop(&q2)); // printf("queue2: %d\n", Pop(&q2)); // // return 0; //} //#include <stdio.h> //#include <stdlib.h> ////서버(Queue) //void Push(int queue[],int* pfront, int* prear,int data) { // if ((*prear + 1) % 5 == *pfront) // return; // // //rear가 0,1,2,3,4 가 되는 코드 // /*rear = rear + 1; // if (rear == 5) // rear = 0;*/ // // *prear = (*prear + 1) % 5; //위 주석 처리 코드와 같음(rear가 0,1,2,4가 되는 코드) // queue[*prear] = data; //} //int Pop(int queue[], int* pfront, int* prear) { // if (*pfront == *prear) // return 0xfffffff; //오류값으로 임의의 큰 값 지정 // // //Push에서 대입전 rear를 증가시키고 대입시켰으므로 // //Pop에서도 증가시키고 값을 빼야 해당 위치의 값을 정확히 값의 위치를 가리키게됨 // *pfront = (*pfront + 1) % 5; // return queue[*pfront]; //} //////////////////////// ////클라이언트 //int main() { // // int queue1[5]; // int front1 = 0, rear1 = 0; // // int queue2[5]; // int front2 = 0, rear2 = 0; // // Push(queue1, &front1, &rear1, 10); // Push(queue1, &front1, &rear1, 20); // Push(queue1, &front1, &rear1, 30); // // Push(queue2, &front2, &rear2, 100); // Push(queue2, &front2, &rear2, 150); // // printf("queue1: %d\n", Pop(queue1, &front1, &rear1)); // printf("queue1: %d\n", Pop(queue1, &front1, &rear1)); // printf("queue1: %d\n", Pop(queue1, &front1, &rear1)); // // printf("queue2: %d\n", Pop(queue2, &front2, &rear2)); // printf("queue2: %d\n", Pop(queue2, &front2, &rear2)); // // return 0; //} //#include <stdio.h> //#include <stdlib.h> ////서버(Queue) //void Push(int data) { // if ((rear + 1) % 5 == front) // return; // // //rear가 0,1,2,3,4 가 되는 코드 // /*rear = rear + 1; // if (rear == 5) // rear = 0;*/ // // rear = (rear + 1) % 5; //위 주석 처리 코드와 같음(rear가 0,1,2,4가 되는 코드) // queue[rear] = data; //} //int Pop() { // if (front == rear) // return 0xfffffff; //오류값으로 임의의 큰 값 지정 // // //Push에서 대입전 rear를 증가시키고 대입시켰으므로 // //Pop에서도 증가시키고 값을 빼야 해당 위치의 값을 정확히 값의 위치를 가리키게됨 // front = (front + 1) % 5; // return queue[front]; //} //////////////////////// ////클라이언트 //int main() { // // int queue1[5]; // int front1 = 0, rear1 = 0; // // int queue2[5]; // int front2 = 0, rear2 = 0; // // Push(queue1, front1, rear1, 10); // Push(queue1, front1, rear1, 20); // Push(queue1, front1, rear1, 30); // // Push(queue2, front2, rear2, 100); // Push(queue2, front2, rear2, 150); // // pintrf("queue1: %d\n", Pop(queue1, front1, rear1)); // pintrf("queue1: %d\n", Pop(queue1, front1, rear1)); // pintrf("queue1: %d\n", Pop(queue1, front1, rear1)); // // pintrf("queue1: %d\n", Pop(queue2, front2, rear2)); // pintrf("queue1: %d\n", Pop(queue2, front2, rear2)); // // return 0; //} //#include <stdio.h> //#include <stdlib.h> ////서버(Queue) //int queue[5]; //int front = 0, rear = 0; //void Push(int data) { // if ((rear + 1) % 5 == front) // return; // // //rear가 0,1,2,3,4 가 되는 코드 // /*rear = rear + 1; // if (rear == 5) // rear = 0;*/ // // rear = (rear + 1) % 5; //위 주석 처리 코드와 같음(rear가 0,1,2,4가 되는 코드) // queue[rear] = data; //} //int Pop() { // if (front == rear) // return 0xfffffff; //오류값으로 임의의 큰 값 지정 // // //Push에서 대입전 rear를 증가시키고 대입시켰으므로 Pop에서도 증가시키고 값을 빼야 해당 위치의 값을 정확히 값의 위치를 가리키게됨 // front = (front + 1) % 5; // return queue[front]; //} //////////////////////// ////클라이언트 //int main() { // // Push(10); // Push(20); // Push(30); // // printf("%d\n", Pop()); // printf("%d\n", Pop()); // printf("%d\n", Pop()); // // Push(10); // Push(20); // Push(30); // // printf("%d\n", Pop()); // printf("%d\n", Pop()); // printf("%d\n", Pop()); // // return 0; //} //#include <stdio.h> //#include <stdlib.h> ////서버(Queue) //int queue[5]; //int front = 0, rear = 0; //void Push(int data) { // queue[rear++] = data; //후위 증가: 해당위치에 문장을 벗어날 때 증가함 //} //int Pop() { // // return queue[front++]; //} //////////////////////// ////클라이언트 //int main() { // // Push(10); // Push(20); // Push(30); // // printf("%d\n", Pop()); // printf("%d\n", Pop()); // printf("%d\n", Pop()); // // Push(10); // Push(20); // Push(300); // // printf("%d\n", Pop()); // printf("%d\n", Pop()); // printf("%d\n", Pop()); // // return 0; //} //#include <stdio.h> //#include <stdlib.h> ////서버(Queue) //int queue[10]; //int front = 0, rear = 0; //void Push(int data) { // queue[rear++] = data; //후위 증가 해당위치에 문장을 벗어날 때 증가함 //} //int Pop() { // // return queue[front++]; //} //////////////////////// ////클라이언트 //int main() { // // Push(10); // Push(20); // Push(30); // // printf("%d\n", Pop());//10 // printf("%d\n", Pop());//20 // printf("%d\n", Pop());//30 // return 0; //} //#include <stdio.h> //#include <stdlib.h> ////서버(Queue) //void Push(int data) { // //} //int Pop() { // // return 0; //} //////////////////////// ////클라이언트 //int main() { // // Push(10); // Push(20); // Push(30); // // printf("%d\n", Pop());//10 // printf("%d\n", Pop());//20 // printf("%d\n", Pop());//30 // return 0; //}
[ "kkw-11@naver.com" ]
kkw-11@naver.com
6ac8c2a14b52527ad94d173450cf57ae34ccdd1b
2913fc25185d387b5e114c384e4bca9f4b766f30
/qvista.h
f193ba79860cf2d1fa6575eac30845466fb790a8
[]
no_license
DavidGuerrero95/Pruebas-with-C-
9fb0db3c81c466d724b3e1a102be6f9fdf3f6be6
c3c6cef1d066481ef3def3ec2dfd1f3469cf02ef
refs/heads/master
2023-07-31T22:38:10.010653
2021-09-17T04:22:02
2021-09-17T04:22:02
407,402,794
0
0
null
null
null
null
UTF-8
C++
false
false
574
h
#ifndef QVISTA_H #define QVISTA_H #include <QGraphicsView> #include <QMouseEvent> #include <QWheelEvent> #include <QDebug> class QVista : public QGraphicsView { Q_OBJECT public: explicit QVista(QWidget *parent = Q_NULLPTR); explicit QVista(QGraphicsScene *scene, QWidget *parent = Q_NULLPTR); ~QVista(); void wheelEvent(QWheelEvent *event); void mouseMoveEvent(QMouseEvent *event); int get_movedx(); int get_movedy(); signals: void Zoomin(); void Zoomout(); void draggmouse(); private: QPoint PO,PM; }; #endif // QVISTA_H
[ "davids.guerrero@udea.edu.co" ]
davids.guerrero@udea.edu.co
946edd0eea34a51109f86d1a5ebc39d9c4b8ae90
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_1595491_0/C++/zhyu/Dancing_With_the_Googlers.cxx
cc27d9a1069dbe0561a950b2a840a02f666cbcb9
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
482
cxx
#include <cstdio> #include <algorithm> using namespace std; int a[110]; bool cmp(int x,int y) { return x>y; } int main(void) { int t,n,s,p; scanf("%d",&t); for(int cas=1;cas<=t;cas++) { scanf("%d%d%d",&n,&s,&p); int res=0; for(int i=0;i<n;i++) scanf("%d",a+i); sort(a,a+n,cmp); for(int i=0;i<n;i++) { if(a[i]>=p && a[i]>=3*p-2) res++; else if(s && a[i]>=p && a[i]>=3*p-4) { res++; s--; } } printf("Case #%d: %d\n",cas,res); } return 0; }
[ "eewestman@gmail.com" ]
eewestman@gmail.com
651a0db3a7e028fa0cedbbbbefcf828095931e0f
72ce01e4273601ac1676b155be7792ccacff2b5a
/LGE/LMath/include/lshape2d.h
111a501b90ba61bb06b2739571dc34ed733953d3
[]
no_license
lilianjun/LGE
d84d56f50665bc4ba4816991742510f7dd00ace5
73531b295aa900a17842c97fe5515fc00b135de9
refs/heads/master
2021-08-29T18:13:07.712204
2017-12-14T15:05:04
2017-12-14T15:05:04
114,252,294
0
0
null
null
null
null
GB18030
C++
false
false
4,405
h
#pragma once #include "lvector2.h" template <typename tv> class lline2d; template <typename tv> class lrect; template <typename tv> class ltri2d; enum EDetect { // 在外 在内 交叉 eOutSide, eInSide, eCross }; // 一个点是否在两个点之间 template <typename tv> bool inside(const tv& vdet, const tv& vmin, const tv& vmax) { return lgreeq(vdet, vmin) && llesseq(vdet, vmax); } // 2d的线段 template <typename tv> class lline2d { public: lline2d() = default; typedef lvector2<tv> tv2; lline2d(const lvector2<tv>& _p1, const lvector2<tv>& _p2) : p1(_p1), p2(_p2) { } lvector2<tv> p1, p2; tv len()const { return p1.distance(p2); } // 求点 已知X tv2 px(tv _x) { return tv2(_x, llerp(p1.y, p2.y, lweight(p1.x, p2.x, _x))); } // 求点 已知Y tv2 py(tv _y) { return tv2(llerp(p1.x, p2.y, lweight(p1.y, p2.y, _y)), _y); } }; // 2d的三角形 template <typename tv> class ltri2d { public: lvector2<tv> p1, p2, p3; ltri2d() = default; ltri2d(const lvector2<tv>& _p1, const lvector2<tv>& _p2, const lvector2<tv>& _p3 ) : p1(_p1), p2(_p2), p3(_p3) { } lline2d<tv> line1()const { return lline2d<tv>(p1, p2); } lline2d<tv> line2()const { return lline2d<tv>(p2, p3); } lline2d<tv> line3()const { return lline2d<tv>(p3, p1); } bool inrect(tv _x, tv _y)const { return rect().detect_point(_x, _y); } lrect<tv> rect()const { return lrect<tv>( lmin(p1.x, lmin(p2.x, p3.x)), lmin(p1.y, lmin(p2.y, p3.y)), lmax(p1.x, lmax(p2.x, p3.x)), lmax(p1.y, lmax(p2.y, p3.y)) ); } }; // 2D的轴向矩形 template <typename tv> class lrect { public: union { struct { tv xmin, ymin, xmax, ymax; }; struct { lvector2<tv> pmin, pmax; }; }; lrect() :xmin((tv)0), ymin((tv)0), xmax((tv)0), ymax((tv)0) { } lrect(const tv& _xmin, const tv& _ymin, const tv& _xmax, const tv& _ymax) :xmin(_xmin), ymin(_ymin), xmax(_xmax), ymax(_ymax) { } lrect(const lvector2<tv>& _pmin, const lvector2<tv>& _pmax) :pmin(_pmin), pmax(_pmax) { } lrect(const lrect& v) : pmin(v.pmin), pmax(v.pmax) { } lrect& operator = (const lrect& v) { pmin = v.pmin; pmax = v.pmax; return *this; } tv xlen()const { return xmax - xmin; } tv ylen()const { return ymax - ymin; } tv area()const { return xlen() * ylen(); } // 获取顶点 lvector2<tv> point1()const { return pmin; } lvector2<tv> point2()const { return lvector2(xmin, ymax); } lvector2<tv> point3()const { return lvector2(xmax, ymax); } lvector2<tv> point4()const { return pmax; } // 增加点,扩张矩形范围 void add_point(); bool detect_point(tv _x, tv _y)const { return inside(_x, xmin, xmax) && inside(_y, ymin, ymax); } // 点与矩形的碰撞检测 // 0:在矩形外 1 在矩形内 2:位于矩形的边 // x 在xmin xmax之间 y bool detect_point(const lvector2<tv>& v) { return inside(v.x, xmin, xmax,) && inside(v.y, ymin, ymax); } // 与另一个矩形的碰撞检测 int detect_rect(const lrect<tv>& rec) { // x 与y 都在之间,就是碰撞 即任意一点在内 return ( inside(xmin, rec.xmin, rec.xmax) || inside(xmax, rec.xmin, rec.xmax) ) && ( inside(ymin, rec.ymin, rec.ymax) || inside(ymax, rec.ymin, rec.ymax) ); } // 与三角形的碰撞检测 int detect_tri(const ltri2d<tv>& tri) { // 三个点任意一点在内 return detect(tri.p1) || detect(tri.p2) || detect(tri.p3); } // 与射线的碰撞检测 int detect_ray(const lvector2<tv>& vec) { // 射线与轴向矩形的碰撞检测 // 与任意一条边相交 } // 与射线的碰撞检测 // 与圆形的碰撞检测 // static lrect add(const lrect& r1, const lrect& r2) { return lrect(lvector2<tv>::make_min(r1.pmin, r2.pmin), lvector2<tv>::make_max(r1.pmax, r2.pmax)); } static lrect make(const lvector2<tv>& p1, const lvector2<tv>& p2) { return lrect(lmin(p1.x, p2.x), lmin(p1.y, p2.y), lmax(p1.x, p2.x), lmax(p1.y, p2.y)); } }; // 2d的任意四边形 template <typename tv> class lquad { public: }; // 2d的射线 template <typename tv> class lray2d { public: // 由点和方向确定 lvector2 point, direction; }; // 2d的圆形 template <typename tv> class lcircle2d { public: lcircle2d() {} lcircle2d(const lvector2<tv>& _c , tv _r) :center(_c), radius(_r) { } lvector2<tv> center; tv radius; };
[ "jungellj@qq.com" ]
jungellj@qq.com
abd3ebd82f04598a8d664fded3b34d0d61117059
3523c991915f71c23e02026b18cbbcc0d5dd8079
/Classes/HackMan.cpp
73d8e6c504f02b7f0250c93f8bed842c7176bb6c
[]
no_license
YasuhiroKawamoto/HackMan
8ab36f98cb6217bb264787240b423ebf6e24f228
7a221b3669d8842011a601c2b0e8090bb81fc67a
refs/heads/master
2020-12-24T09:44:39.047450
2016-11-15T09:12:50
2016-11-15T09:12:50
73,271,090
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
4,874
cpp
/****************************************/ /*内 容 ゲームクラスのソースファイル */ /*制作者 加藤駿 */ /*制作日 2016/11/10 */ /****************************************/ #include "cocos2d.h" #include "GameMain.h" #include"Player.h" #include"HackMan.h" USING_NS_CC; //+ーーーーーーーーーーーー //|機 能:ゲームのコンストラクタ //|引 数:なし(void) //+ーーーーーーーーーーーー HackMan::HackMan() { //マップデータ int map[MAP_H][MAP_W] = { { 1,1,1,1,1,1,1,1,1,1,1 }, { 1,0,0,0,0,0,0,0,0,0,1 }, { 1,0,1,0,1,0,1,0,1,0,1 }, { 1,0,0,0,0,0,0,0,0,0,1 }, { 1,0,1,0,1,0,1,0,1,0,1 }, { 1,0,0,0,0,0,0,0,0,0,1 }, { 1,0,1,0,1,0,1,0,1,0,1 }, { 1,0,0,0,0,0,0,0,0,0,1 }, { 1,0,1,0,1,0,1,0,1,0,1 }, { 1,0,0,0,0,0,0,0,0,0,1 }, { 1,1,1,1,1,1,1,1,1,1,1 }, }; /*--マップデータをメンバーに変換--*/ for (int i = 0; i < MAP_H; i++) { for (int j = 0; j < MAP_W; j++) { m_map[i][j] = map[i][j]; } } } //+ーーーーーーーーーーーー //|機 能:ゲームのデストラクタ //+ーーーーーーーーーーーー HackMan::~HackMan() { } //+ーーーーーーーーーーーー //|機 能:プレイヤーの登録 //|引 数:プレイヤー(Player*[]) //|返り値:なし(void) //+ーーーーーーーーーーーー void HackMan::RegisterPlayer(Player player[]) { for (int i = 0; i < MAX_PLAYER; i++) { m_player[i] = &player[i]; } } //+ーーーーーーーーーーーー //|機 能:ゲーム本編 //|引 数:なし(void) //|返り値:なし(void) //+ーーーーーーーーーーーー void HackMan::Play() { //エラー回避用 OBJECT* obj; OBJECT player[MAX_PLAYER]; //プレイ時間のカウント用 int playTime = 0; /*--ゲーム本編(時間経過で終了)--*/ while (isFinished(playTime) == false) { /*--プレイヤー情報をコピー--*/ for (int i = 0; i < MAX_PLAYER; i++) { player[i] = m_player[i]->GetObj(); } /*--プレイヤーの処理--*/ for (int i = 0; i < MAX_PLAYER; i++) { //移動 m_player[i]->Move(); //描画 m_player[i]->Draw(); /*--復活処理--*/ if (m_player[i]->GetState() == 1) { m_player[i]->Resurrection(); } } /*--プレイヤーと粘液の判定--*/ for (int i = 0; i < MAX_PLAYER; i++) { for (int j= 0; j < /*粘液最大数*/1 ; j++) { if (/*粘液のstateの判定*/true) { /*--当たっていたら--*/ if (collision(&player[i],/*粘液位置*/obj)) { //プレイヤーにダメージ m_player[i]->Damege(); } } } } /*--プレイヤー同士の当たり判定--*/ for (int i = 0; i < MAX_PLAYER; i++) { /*--プレイヤーが元気な場合--*/ if (m_player[i]->GetState() == 2) { for (int j = 0; j < MAX_PLAYER; j++) { /*--相手が違うプレイヤーの場合--*/ if (i != j) { /*--プレイヤーと相手が当たっていた場合--*/ if (collision(&player[i], &player[j])) { /*--相手が粘液状態の場合--*/ if (m_player[j]->GetState() == 1) { m_player[j]->Damege(); } } } } } } /*--プレイヤーとエサの当たり判定--*/ for (int i = 0; i < MAX_PLAYER; i++) { for (int j = 0; j < /*エサ最大数*/1; j++) { if (/*エサのstateの判定*/true) { /*--当たっていたら--*/ if (collision(&player[i],/*エサ位置*/obj)) { //粘液をストック m_player[i]->StockShoot(); } } } } //時間のカウント playTime++; } } //+ーーーーーーーーーーーー //|機 能:ゲームの終了判定 //|引 数:プレイ時間(int) //|返り値:終了判定(bool) //+ーーーーーーーーーーーー bool HackMan::isFinished(int playTime) { if (playTime > PLAY_TIME) { return true; } return false; } //+ーーーーーーーーーーーーーーーーーーーー+ //|関数名:collision //|機能 :円の当たり判定 計算 //|引数 :オブジェクト (OBJECT*,OBJECT*) //|戻り値:結果 (int) //+ーーーーーーーーーーーーーーーーーーーー+ bool HackMan::collision(const OBJECT* A, const OBJECT* B) { float x1 = A->pos.x; //A中心座標x float y1 = A->pos.y; //A中心座標y float x2 = B->pos.x; //B中心座標x float y2 = B->pos.y; //B中心座標y float r1 = A->grp.w / 2; //A半径 float r2 = B->grp.w / 2; //B半径 float X = x1 - x2; //2点間の距離x float Y = y1 - y2; //2点間の距離y float R = r1 + r2; //2つの半径の和 /*-----[当たり判定]-----*/ if (X*X + Y*Y <= R*R) { //当たっていた場合 return true; } //当たっていない場合 return false; }
[ "hanashun9@gmail.com" ]
hanashun9@gmail.com
a8869bfbf48991646fc394b5be871ffe1084ac5a
04ac4f25086abb864d61772e29c6aab67bd0b0b6
/term2/talks/image_processing/code/04image_algo/image.hpp
c157b3533e72b0f9db4876c52e9ce7afc6534eb7
[]
no_license
v-biryukov/cs_mipt_faki
9adb3e1ca470ab647e2555af6fa095cad0db12ca
075fe8bc104921ab36350e71636fd59aaf669fe9
refs/heads/master
2023-06-22T04:18:50.220177
2023-06-15T09:58:48
2023-06-15T09:58:48
42,241,044
5
2
null
null
null
null
UTF-8
C++
false
false
5,972
hpp
/* Создадим класс изображения */ #pragma once #include <iostream> #include <vector> #include <array> #include <fstream> #include <algorithm> class Image { private: int mWidth {0}; int mHeight {0}; std::vector<unsigned char> mData {}; public: struct Color { unsigned char r, g, b; Color& operator+=(const Color& c) { r = saturateCast(r + c.r); g = saturateCast(g + c.g); b = saturateCast(b + c.b); return *this; } Color operator+(const Color& c) const { Color result = *this; result += c; return result; } private: unsigned char saturateCast(int a) { if (a > 255) a = 255; return static_cast<unsigned char>(a); } }; Image() {} Image(const std::string& filename) { loadPPM(filename); } Image(int width, int height) : mWidth(width), mHeight(height) { mData.resize(3 * mWidth * mHeight); std::fill(mData.begin(), mData.end(), 0); } Image(int width, int height, Color c) : mWidth(width), mHeight(height) { mData.resize(3 * mWidth * mHeight); for (int j = 0; j < mHeight; ++j) { for (int i = 0; i < mWidth; ++i) { setPixel(i, j, c); } } } int getWidth() const {return mWidth;} int getHeight() const {return mHeight;} unsigned char* getData() {return mData.data();} void setPixel(int i, int j, Color c) { mData[3 * (j * mWidth + i) + 0] = c.r; mData[3 * (j * mWidth + i) + 1] = c.g; mData[3 * (j * mWidth + i) + 2] = c.b; } Color getPixel(int i, int j) const { size_t index = j * mWidth + i; return {mData[3 * index + 0], mData[3 * index + 1], mData[3 * index + 2]}; } Color& operator()(int i, int j) { size_t index = j * mWidth + i; return *reinterpret_cast<Color*>(&mData[3 * index]); } void loadPPMText(const std::string& filename) { std::ifstream in {filename}; if (in.fail()) { std::cout << "Error. Can't open file!" << std::endl; std::exit(1); } std::string type; in >> type; if (type != "P3") { std::cout << "Error. File should be type P3 .ppm file!" << std::endl; std::exit(1); } in >> mWidth >> mHeight; int maxValue; in >> maxValue; mData.resize(3 * mWidth * mHeight); for (int j = 0; j < mHeight; ++j) { for (int i = 0; i < mWidth; ++i) { int r, g, b; in >> r >> g >> b; Color pixel = {static_cast<unsigned char>(r), static_cast<unsigned char>(g), static_cast<unsigned char>(b)}; setPixel(i, j, pixel); } } } void savePPMText(const std::string& filename) const { std::ofstream out {filename}; if (out.fail()) { std::cout << "Error. Can't open file!" << std::endl; std::exit(1); } out << "P3\n" << mWidth << " " << mHeight << "\n255\n"; for (int j = 0; j < mHeight; ++j) { for (int i = 0; i < mWidth; ++i) { out << static_cast<int>(mData[3 * (j * mWidth + i) + 0]) << " " << static_cast<int>(mData[3 * (j * mWidth + i) + 1]) << " " << static_cast<int>(mData[3 * (j * mWidth + i) + 2]) << "\n"; } } } void loadPPMBinary(const std::string& filename) { std::ifstream in {filename, std::ios::binary}; if (in.fail()) { std::cout << "Error. Can't open file!" << std::endl; std::exit(1); } std::string type; in >> type; if (type != "P6") { std::cout << "Error. File should be type P6 .ppm file!" << std::endl; std::exit(1); } in >> mWidth >> mHeight; int maxValue; in >> maxValue; char temp; in >> std::noskipws >> temp; mData.resize(3 * mWidth * mHeight); in.read(reinterpret_cast<char*>(&mData[0]), mData.size()); } void savePPMBinary(const std::string& filename) const { std::ofstream out {filename, std::ios::binary}; out << "P6\n" << mWidth << " " << mHeight << "\n255\n"; out.write(reinterpret_cast<const char*>(&mData[0]), mData.size()); } void loadPPM(const std::string& filename) { std::ifstream in {filename, std::ios::binary}; if (in.fail()) { std::cout << "Error. Can't open file!" << std::endl; std::exit(1); } std::string type; in >> type; if (type == "P3") { loadPPMText(filename); } else if (type == "P6") { loadPPMBinary(filename); } else { std::cout << "Error. File should be type P3 or P6 .ppm file!" << std::endl; } } void printInfo() const { std::cout << "Width = " << mWidth << std::endl; std::cout << "Height = " << mHeight << std::endl; std::cout << "Colors:\n"; for (int j = 0; j < mHeight; ++j) { for (int i = 0; i < mWidth; ++i) { auto pixel = getPixel(i, j); std::cout << "(" << static_cast<int>(pixel.r) << ", " << static_cast<int>(pixel.g) << ", " << static_cast<int>(pixel.b) << ") "; } std::cout << "\n"; } } };
[ "biryukov.vova@gmail.com" ]
biryukov.vova@gmail.com
c452d8473da0e72391eeb7afac14f0a2ded2cfcf
04b1803adb6653ecb7cb827c4f4aa616afacf629
/services/network/test/test_url_loader_factory.h
df1d7195bfa36d0b54b8a8efa816134e1c5cc7c3
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
7,988
h
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SERVICES_NETWORK_TEST_TEST_URL_LOADER_FACTORY_H_ #define SERVICES_NETWORK_TEST_TEST_URL_LOADER_FACTORY_H_ #include <map> #include <string> #include <vector> #include "base/macros.h" #include "base/memory/ref_counted.h" #include "mojo/public/cpp/bindings/binding_set.h" #include "net/http/http_status_code.h" #include "services/network/public/cpp/resource_request.h" #include "services/network/public/mojom/url_loader.mojom.h" #include "services/network/public/mojom/url_loader_factory.mojom.h" namespace network { class WeakWrapperSharedURLLoaderFactory; // A helper class to ease testing code that uses URLLoader interface. A test // would pass this factory instead of the production factory to code, and // would prime it with response data for arbitrary URLs. class TestURLLoaderFactory : public mojom::URLLoaderFactory { public: struct PendingRequest { PendingRequest(); ~PendingRequest(); PendingRequest(PendingRequest&& other); PendingRequest& operator=(PendingRequest&& other); mojom::URLLoaderClientPtr client; ResourceRequest request; }; // Bitfield that is used with |SimulateResponseForPendingRequest()| to // control which request is selected. enum ResponseMatchFlags : uint32_t { kMatchDefault = 0x0, kUrlMatchPrefix = 0x1, // Whether URLs are a match if they start with the // URL passed in to // SimulateResponseForPendingRequest kMostRecentMatch = 0x2, // Start with the most recent requests. }; // Flags used with |AddResponse| to control how it produces a response. enum ResponseProduceFlags : uint32_t { kResponseDefault = 0, kResponseOnlyRedirectsNoDestination = 0x1, kSendHeadersOnNetworkError = 0x2, }; TestURLLoaderFactory(); ~TestURLLoaderFactory() override; using Redirects = std::vector<std::pair<net::RedirectInfo, ResourceResponseHead>>; // Adds a response to be served. There is one unique response per URL, and if // this method is called multiple times for the same URL the last response // data is used. // This can be called before or after a request is made. If it's called after, // then pending requests will be "woken up". void AddResponse(const GURL& url, const ResourceResponseHead& head, const std::string& content, const URLLoaderCompletionStatus& status, const Redirects& redirects = Redirects(), ResponseProduceFlags rp_flags = kResponseDefault); // Simpler version of above for the common case of success or error page. void AddResponse(const std::string& url, const std::string& content, net::HttpStatusCode status = net::HTTP_OK); // Returns true if there is a request for a given URL with a living client // that did not produce a response yet. If |request_out| is non-null, // it will give a const pointer to the request. // WARNING: This does RunUntilIdle() first. bool IsPending(const std::string& url, const ResourceRequest** request_out = nullptr); // Returns the total # of pending requests. // WARNING: This does RunUntilIdle() first. int NumPending(); // Clear all the responses that were previously set. void ClearResponses(); using Interceptor = base::RepeatingCallback<void(const ResourceRequest&)>; void SetInterceptor(const Interceptor& interceptor); // Returns a mutable list of pending requests, for consumers that need direct // access. It's recommended that consumers use AddResponse() rather than // servicing requests themselves, whenever possible. std::vector<PendingRequest>* pending_requests() { return &pending_requests_; } // Returns the PendingRequest instance available at the given index |index| // or null if not existing. PendingRequest* GetPendingRequest(size_t index); // Sends a response for the first (oldest) pending request with URL |url|. // Returns false if no such pending request exists. // |flags| can be used to change the default behavior: // - if kUrlMatchPrefix is set, the pending request is a match if its URL // starts with |url| (instead of being equal to |url|). // - if kMostRecentMatch is set, the most recent (instead of oldest) pending // request matching is used. bool SimulateResponseForPendingRequest( const GURL& url, const network::URLLoaderCompletionStatus& completion_status, const ResourceResponseHead& response_head, const std::string& content, ResponseMatchFlags flags = kMatchDefault); // Simpler version of above for the common case of success or error page. bool SimulateResponseForPendingRequest( const std::string& url, const std::string& content, net::HttpStatusCode status = net::HTTP_OK, ResponseMatchFlags flags = kMatchDefault); // Sends a response for the given request |request|. // // Differently from its variant above, this method does not remove |request| // from |pending_requests_|. // // This method is useful to process requests at a given pre-defined order. void SimulateResponseWithoutRemovingFromPendingList( PendingRequest* request, const ResourceResponseHead& head, std::string content, const URLLoaderCompletionStatus& status); // Simpler version of the method above. void SimulateResponseWithoutRemovingFromPendingList(PendingRequest* request, std::string content); // mojom::URLLoaderFactory implementation. void CreateLoaderAndStart(mojom::URLLoaderRequest request, int32_t routing_id, int32_t request_id, uint32_t options, const ResourceRequest& url_request, mojom::URLLoaderClientPtr client, const net::MutableNetworkTrafficAnnotationTag& traffic_annotation) override; void Clone(mojom::URLLoaderFactoryRequest request) override; // Returns a 'safe' ref-counted weak wrapper around this TestURLLoaderFactory // instance. // // Because this is a weak wrapper, it is possible for the underlying // TestURLLoaderFactory instance to be destroyed while other code still holds // a reference to it. // // The weak wrapper returned by this method is guaranteed to have had // Detach() called before this is destructed, so that any future calls become // no-ops, rather than a crash. scoped_refptr<network::WeakWrapperSharedURLLoaderFactory> GetSafeWeakWrapper(); private: bool CreateLoaderAndStartInternal(const GURL& url, mojom::URLLoaderClient* client); static void SimulateResponse(mojom::URLLoaderClient* client, Redirects redirects, ResourceResponseHead head, std::string content, URLLoaderCompletionStatus status, ResponseProduceFlags response_flags); struct Response { Response(); ~Response(); Response(const Response&); GURL url; Redirects redirects; ResourceResponseHead head; std::string content; URLLoaderCompletionStatus status; ResponseProduceFlags flags; }; std::map<GURL, Response> responses_; std::vector<PendingRequest> pending_requests_; scoped_refptr<network::WeakWrapperSharedURLLoaderFactory> weak_wrapper_; Interceptor interceptor_; mojo::BindingSet<network::mojom::URLLoaderFactory> bindings_; DISALLOW_COPY_AND_ASSIGN(TestURLLoaderFactory); }; } // namespace network #endif // SERVICES_NETWORK_TEST_TEST_URL_LOADER_FACTORY_H_
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
7e55db3804f589685e05db10da147da95f027ea5
d89ff67264f51534e900d5c865815530942b3337
/Rcpp/WaterbalanceFunction.cpp
0a8d45a67626b4bdfe493c222b007157bc32c25f
[ "MIT" ]
permissive
WillemVervoort/Ecohydr2D
445dd45a42cc07a1c1659dfa2fe04804064fb6f8
b709148c9c89101527f37ef6be843508a2ad2a21
refs/heads/master
2020-07-04T10:01:35.600396
2018-02-09T02:25:30
2018-02-09T02:25:30
66,457,282
0
0
null
2016-09-04T23:31:42
2016-08-24T11:09:22
R
UTF-8
C++
false
false
6,361
cpp
// [[Rcpp::depends(RcppEigen)]] // [[Rcpp::depends(RcppNumerical)]] #include <Rcpp.h> #include <RcppNumerical.h> #include "VegFun.hpp" #include "Fluxfunctions.hpp" using namespace Numer; using namespace Rcpp; // static stress function // [[Rcpp::export]] double zeta(double s,double s_star, double s_w,double q) { double temp = std::max(pow((s_star-s)/(s_star-s_w),q),0.0); double out = std::min(temp,1.0); return out; } // Rewriting the 2-D water balance implementation across grid cells // First rewrite the water balance function // [[Rcpp::export]] List WB_fun_cpp(List vegpar_in, double In, double last_t_soil_sat, List soilpar_in, double Zmean_in, int deltat, double Z_prev, double Z_in) { const double n = soilpar_in["n"]; const double Zr = vegpar_in["Zr"]; const double ss = vegpar_in["s_star"]; const double sw = vegpar_in["s_w"]; const double q = vegpar_in["q"]; double soil_sat = 0.0; double qcap = 0.0; double static_stress = 0.0; double Tg = 0.0; double Ts = 0.0; double Tt = 0.0; double Leakage = 0.0; double smloss = 0.0; double GWrech = 0.0; const bool funswitch = vegpar_in["DR"]; // Change Rainfall into infiltration double Phi = In; double surfoff = 0.0; double intincr = 1/deltat; // check if soil bucket full, create runoff if(Phi > (1 - last_t_soil_sat)){ Phi = 1 - last_t_soil_sat; surfoff = (In - Phi)*n*Zr; } NumericVector loss(5); // Call the loss model if (funswitch==TRUE) { loss = FB_new_cpp(last_t_soil_sat, soilpar_in, vegpar_in, Z_in, Zmean_in, Z_prev); //Rcpp::Rcout << loss[2] } else { loss = rho_new_cpp(last_t_soil_sat, Z_in, soilpar_in, vegpar_in, Zmean_in, Z_prev); } // update the water balance // ss.t is temporary ss double ss_t = last_t_soil_sat + Phi - loss[0]/(n*Zr)*intincr; // build in safety if capillary flux fills soil with dynamic water table if (ss_t > 1) { // very wet conditions soil_sat = 1; qcap = (loss[3] - (ss_t - 1)*n*Zr/intincr)*intincr; } else { // normal conditions soil_sat = ss_t; qcap = loss[3]*(1/intincr); } static_stress = zeta(soil_sat, ss, sw, q); Tg = loss[2]*intincr; // Rcpp::Rcout << loss[2]; Ts = loss[1]*intincr; Tt = Tg + Ts; if (loss[4] > 0.0) { Leakage = loss[4]*intincr; } //increase with difference between originally calculated and new (pot.reduced) capillary flux smloss = (loss[0]*intincr - (qcap - loss[3]*intincr)); GWrech = Leakage-loss[2]*intincr-qcap; //Rcpp::Rcout << qcap; List out = Rcpp::List::create(Rcpp::Named("s") = soil_sat, Rcpp::Named("qcap") = qcap, Rcpp::Named("Tgw") = Tg, Rcpp::Named("Tsoil") = Ts, Rcpp::Named("Ttotal") = Tt, Rcpp::Named("Leakage") = Leakage, Rcpp::Named("GWrech") = GWrech, Rcpp::Named("smloss") = smloss, Rcpp::Named("static_stress") = static_stress, Rcpp::Named("surfoff") = surfoff); return out; } // this is in the middle part of the overall Bigfun // [[Rcpp::export]] NumericMatrix WBEcoHyd(int x, int y, int t, NumericVector R, NumericVector ETp, CharacterVector vtype, List soilpar, NumericVector s_init, double fullday, NumericVector Zmean, NumericVector GWdepths, NumericVector GWdepths_prev, int deltat, NumericVector NX, NumericVector NY){ // both R and Etp are single vectors of the rainfall and the ETpotential // vtype is a vector of vegetation types along the grid // soilpar is the specification of the soiltype (currently 1 type across the grid) // s_init are the inital soil moisture levels for the day // deltat is the increment in the integration // Zmean is a vector of long term mean gw depths // GWdepths is the gw depths for each gridcell at t // GWdepths_prev are the previous gw depths for each gridcell (at t-1) // define variables int m = NX.size()*NY.size(); double R_in = 0.0; // storage output vectors // grid vectors NumericVector s_g(m), qcap_g(m), Tgw_g(m), Tsoil_g(m), Ttotal_g(m), Leakage_g(m); NumericVector GWrech_g(m), smloss_g(m), static_stress_g(m), surfoff_g(m); //Matrices NumericMatrix Storage_Subday(12,10); // this only works as long as NX = 1 NumericMatrix Storage_Grid(10,m); // run through grid for (int j = 0;j < m;j++) { // Call the vegpar function std::string veg_in = as<std::string>(vtype[j]); List vegpar = Veg_cpp(veg_in, soilpar); vegpar["Ep"] = ETp[j]; // define soil and vegparameters double Zr = vegpar["Zr"]; double n = soilpar["n"]; // Now run integration loop for (int p = 0;p < deltat;p++) { if (p == 0) { R_in = R[t]/(n*Zr); } Rcpp::Rcout << "R_in =" << R_in; // run the water balance double s_old = s_init[j]; if (p > 1 ) s_old = Storage_Subday((p-1),1); // // Storage_Subday is not defined List Water_out = WB_fun_cpp(vegpar, R_in, s_old, soilpar, Zmean[j], deltat, GWdepths_prev[j], GWdepths[j]); //Write water balance list output to subdaily vector int xsize = Storage_Subday.ncol(); for (int k = 0; k < xsize; k++) { Storage_Subday(p,k) = Rcpp::as<double>(Water_out(k)); } // // store s_init for gridcell till next day if (p == 12) s_init(j) = Storage_Subday(p,1); } // close p loop // recalculate to daily output and write away // produce different output, produce daily values for each grid cell int kk = Storage_Grid.ncol(); for (int k = 0; k < kk; k++) { Storage_Grid(j,k) = sum(Storage_Subday(_,k)); if (k > 0) Storage_Grid(j,k) = mean(Storage_Subday(_,k)); } } // close j loop // x = 4; // y = 5; // NumericMatrix out(x,y); return Storage_Grid; }
[ "willem.vervoort@sydney.edu.au" ]
willem.vervoort@sydney.edu.au
f34e670f00987098771cc691a80382a09954439d
e3b66fd2c25f7f07f763054e22adab22087b26c1
/explicit_instantiation/big_example/optimized/use_131.cpp
01381bc58674de3543365ce620c86f428d6fd8eb
[]
no_license
Cubix651/blog-examples
903619d98a64ea32aac48c68b61c1dc777c88e61
0aa025215a0a28a7322786a939a0d9a2fc039b48
refs/heads/master
2020-12-01T21:46:56.361380
2020-09-12T20:37:00
2020-09-12T20:37:00
230,780,565
0
0
null
null
null
null
UTF-8
C++
false
false
13,582
cpp
#include "use_131.h" #include "library.h" int use_131() { int x = 131; x += library_function_0(x); x += library_function_1(x); x += library_function_2(x); x += library_function_3(x); x += library_function_4(x); x += library_function_5(x); x += library_function_6(x); x += library_function_7(x); x += library_function_8(x); x += library_function_9(x); x += library_function_10(x); x += library_function_11(x); x += library_function_12(x); x += library_function_13(x); x += library_function_14(x); x += library_function_15(x); x += library_function_16(x); x += library_function_17(x); x += library_function_18(x); x += library_function_19(x); x += library_function_20(x); x += library_function_21(x); x += library_function_22(x); x += library_function_23(x); x += library_function_24(x); x += library_function_25(x); x += library_function_26(x); x += library_function_27(x); x += library_function_28(x); x += library_function_29(x); x += library_function_30(x); x += library_function_31(x); x += library_function_32(x); x += library_function_33(x); x += library_function_34(x); x += library_function_35(x); x += library_function_36(x); x += library_function_37(x); x += library_function_38(x); x += library_function_39(x); x += library_function_40(x); x += library_function_41(x); x += library_function_42(x); x += library_function_43(x); x += library_function_44(x); x += library_function_45(x); x += library_function_46(x); x += library_function_47(x); x += library_function_48(x); x += library_function_49(x); x += library_function_50(x); x += library_function_51(x); x += library_function_52(x); x += library_function_53(x); x += library_function_54(x); x += library_function_55(x); x += library_function_56(x); x += library_function_57(x); x += library_function_58(x); x += library_function_59(x); x += library_function_60(x); x += library_function_61(x); x += library_function_62(x); x += library_function_63(x); x += library_function_64(x); x += library_function_65(x); x += library_function_66(x); x += library_function_67(x); x += library_function_68(x); x += library_function_69(x); x += library_function_70(x); x += library_function_71(x); x += library_function_72(x); x += library_function_73(x); x += library_function_74(x); x += library_function_75(x); x += library_function_76(x); x += library_function_77(x); x += library_function_78(x); x += library_function_79(x); x += library_function_80(x); x += library_function_81(x); x += library_function_82(x); x += library_function_83(x); x += library_function_84(x); x += library_function_85(x); x += library_function_86(x); x += library_function_87(x); x += library_function_88(x); x += library_function_89(x); x += library_function_90(x); x += library_function_91(x); x += library_function_92(x); x += library_function_93(x); x += library_function_94(x); x += library_function_95(x); x += library_function_96(x); x += library_function_97(x); x += library_function_98(x); x += library_function_99(x); x += library_function_100(x); x += library_function_101(x); x += library_function_102(x); x += library_function_103(x); x += library_function_104(x); x += library_function_105(x); x += library_function_106(x); x += library_function_107(x); x += library_function_108(x); x += library_function_109(x); x += library_function_110(x); x += library_function_111(x); x += library_function_112(x); x += library_function_113(x); x += library_function_114(x); x += library_function_115(x); x += library_function_116(x); x += library_function_117(x); x += library_function_118(x); x += library_function_119(x); x += library_function_120(x); x += library_function_121(x); x += library_function_122(x); x += library_function_123(x); x += library_function_124(x); x += library_function_125(x); x += library_function_126(x); x += library_function_127(x); x += library_function_128(x); x += library_function_129(x); x += library_function_130(x); x += library_function_131(x); x += library_function_132(x); x += library_function_133(x); x += library_function_134(x); x += library_function_135(x); x += library_function_136(x); x += library_function_137(x); x += library_function_138(x); x += library_function_139(x); x += library_function_140(x); x += library_function_141(x); x += library_function_142(x); x += library_function_143(x); x += library_function_144(x); x += library_function_145(x); x += library_function_146(x); x += library_function_147(x); x += library_function_148(x); x += library_function_149(x); x += library_function_150(x); x += library_function_151(x); x += library_function_152(x); x += library_function_153(x); x += library_function_154(x); x += library_function_155(x); x += library_function_156(x); x += library_function_157(x); x += library_function_158(x); x += library_function_159(x); x += library_function_160(x); x += library_function_161(x); x += library_function_162(x); x += library_function_163(x); x += library_function_164(x); x += library_function_165(x); x += library_function_166(x); x += library_function_167(x); x += library_function_168(x); x += library_function_169(x); x += library_function_170(x); x += library_function_171(x); x += library_function_172(x); x += library_function_173(x); x += library_function_174(x); x += library_function_175(x); x += library_function_176(x); x += library_function_177(x); x += library_function_178(x); x += library_function_179(x); x += library_function_180(x); x += library_function_181(x); x += library_function_182(x); x += library_function_183(x); x += library_function_184(x); x += library_function_185(x); x += library_function_186(x); x += library_function_187(x); x += library_function_188(x); x += library_function_189(x); x += library_function_190(x); x += library_function_191(x); x += library_function_192(x); x += library_function_193(x); x += library_function_194(x); x += library_function_195(x); x += library_function_196(x); x += library_function_197(x); x += library_function_198(x); x += library_function_199(x); x += library_function_200(x); x += library_function_201(x); x += library_function_202(x); x += library_function_203(x); x += library_function_204(x); x += library_function_205(x); x += library_function_206(x); x += library_function_207(x); x += library_function_208(x); x += library_function_209(x); x += library_function_210(x); x += library_function_211(x); x += library_function_212(x); x += library_function_213(x); x += library_function_214(x); x += library_function_215(x); x += library_function_216(x); x += library_function_217(x); x += library_function_218(x); x += library_function_219(x); x += library_function_220(x); x += library_function_221(x); x += library_function_222(x); x += library_function_223(x); x += library_function_224(x); x += library_function_225(x); x += library_function_226(x); x += library_function_227(x); x += library_function_228(x); x += library_function_229(x); x += library_function_230(x); x += library_function_231(x); x += library_function_232(x); x += library_function_233(x); x += library_function_234(x); x += library_function_235(x); x += library_function_236(x); x += library_function_237(x); x += library_function_238(x); x += library_function_239(x); x += library_function_240(x); x += library_function_241(x); x += library_function_242(x); x += library_function_243(x); x += library_function_244(x); x += library_function_245(x); x += library_function_246(x); x += library_function_247(x); x += library_function_248(x); x += library_function_249(x); x += library_function_250(x); x += library_function_251(x); x += library_function_252(x); x += library_function_253(x); x += library_function_254(x); x += library_function_255(x); x += library_function_256(x); x += library_function_257(x); x += library_function_258(x); x += library_function_259(x); x += library_function_260(x); x += library_function_261(x); x += library_function_262(x); x += library_function_263(x); x += library_function_264(x); x += library_function_265(x); x += library_function_266(x); x += library_function_267(x); x += library_function_268(x); x += library_function_269(x); x += library_function_270(x); x += library_function_271(x); x += library_function_272(x); x += library_function_273(x); x += library_function_274(x); x += library_function_275(x); x += library_function_276(x); x += library_function_277(x); x += library_function_278(x); x += library_function_279(x); x += library_function_280(x); x += library_function_281(x); x += library_function_282(x); x += library_function_283(x); x += library_function_284(x); x += library_function_285(x); x += library_function_286(x); x += library_function_287(x); x += library_function_288(x); x += library_function_289(x); x += library_function_290(x); x += library_function_291(x); x += library_function_292(x); x += library_function_293(x); x += library_function_294(x); x += library_function_295(x); x += library_function_296(x); x += library_function_297(x); x += library_function_298(x); x += library_function_299(x); x += library_function_300(x); x += library_function_301(x); x += library_function_302(x); x += library_function_303(x); x += library_function_304(x); x += library_function_305(x); x += library_function_306(x); x += library_function_307(x); x += library_function_308(x); x += library_function_309(x); x += library_function_310(x); x += library_function_311(x); x += library_function_312(x); x += library_function_313(x); x += library_function_314(x); x += library_function_315(x); x += library_function_316(x); x += library_function_317(x); x += library_function_318(x); x += library_function_319(x); x += library_function_320(x); x += library_function_321(x); x += library_function_322(x); x += library_function_323(x); x += library_function_324(x); x += library_function_325(x); x += library_function_326(x); x += library_function_327(x); x += library_function_328(x); x += library_function_329(x); x += library_function_330(x); x += library_function_331(x); x += library_function_332(x); x += library_function_333(x); x += library_function_334(x); x += library_function_335(x); x += library_function_336(x); x += library_function_337(x); x += library_function_338(x); x += library_function_339(x); x += library_function_340(x); x += library_function_341(x); x += library_function_342(x); x += library_function_343(x); x += library_function_344(x); x += library_function_345(x); x += library_function_346(x); x += library_function_347(x); x += library_function_348(x); x += library_function_349(x); x += library_function_350(x); x += library_function_351(x); x += library_function_352(x); x += library_function_353(x); x += library_function_354(x); x += library_function_355(x); x += library_function_356(x); x += library_function_357(x); x += library_function_358(x); x += library_function_359(x); x += library_function_360(x); x += library_function_361(x); x += library_function_362(x); x += library_function_363(x); x += library_function_364(x); x += library_function_365(x); x += library_function_366(x); x += library_function_367(x); x += library_function_368(x); x += library_function_369(x); x += library_function_370(x); x += library_function_371(x); x += library_function_372(x); x += library_function_373(x); x += library_function_374(x); x += library_function_375(x); x += library_function_376(x); x += library_function_377(x); x += library_function_378(x); x += library_function_379(x); x += library_function_380(x); x += library_function_381(x); x += library_function_382(x); x += library_function_383(x); x += library_function_384(x); x += library_function_385(x); x += library_function_386(x); x += library_function_387(x); x += library_function_388(x); x += library_function_389(x); x += library_function_390(x); x += library_function_391(x); x += library_function_392(x); x += library_function_393(x); x += library_function_394(x); x += library_function_395(x); x += library_function_396(x); x += library_function_397(x); x += library_function_398(x); x += library_function_399(x); return x; }
[ "cubix651@gmail.com" ]
cubix651@gmail.com
88549abf63c0f6edaadae9409d58aa77c2e56b93
d1661c0a25eac70489761f65cdd5a22b38dee715
/_Qt/project/tests/test_display_html_convertor.cpp
c5e914f884e8e51461a5ec0f6366e1dba1561230
[]
no_license
Teslatec/LPM_Editor
18d69c85f77e798278b274fc874b2cf369566523
647fc8473ee16592df58e1c5b2b63a70b7fa75f8
refs/heads/master
2023-02-02T10:56:36.134912
2020-04-14T15:38:06
2020-04-14T15:38:06
321,923,049
0
0
null
null
null
null
UTF-8
C++
false
false
7,162
cpp
#include "test_display_html_convertor.h" #include <QDebug> const QString htmlLineFeed = "<br>"; const QString htmlCursorBegin = "<u>"; const QString htmlCursorEnd = "</u>"; //const QString htmlHighlightingBegin = "<font color=\"#8852C5\"><b>"; //const QString htmlHighlightingEnd = "</b></font>"; const QString htmlHighlightingBegin = "<b>"; const QString htmlHighlightingEnd = "</b>"; QString convertTextWithoutHighlighting( const QStringList & src, QPoint cursor ); QString convertTextWithOneLineHighlighted( const QStringList & src, QPoint cursorBegin, QPoint cursorEnd ); QString convertTextWithMultiLineHighlighted( const QStringList & src, QPoint cursorBegin, QPoint cursorEnd ); QString makeLine(const QString & line); QString makeLineWithCursor(const QString & line, int x); QString makeLineWithHighlighting(const QString & line, int xBegin, int xEnd); QString makeLineWithHighlightingBegin(const QString & line, int x); QString makeLineWithHighlightingEnd(const QString & line, int x); QString makeMidHighlightedLine(const QString & line, int highlightingBegin, int highlightingEnd, bool underlined); QString makeLeftHighlightedLine(const QString & line, int highlightingBorder, bool underlined); QString makeRightHighlightedLine(const QString & line, int highlightingBorder, bool underlined); QString makeFullHighlightedLine(const QString & line, bool underlined); QString makeLineWithoutCursor(const QString & line); QString makeCursoredLine(const QString & line, int cursorPosition); QString TestDisplayHtmlConvertor::convert( const QStringList & src, QPoint cursorBegin, QPoint cursorEnd ) { if(cursorBegin == cursorEnd) return convertTextWithoutHighlighting(src, cursorBegin); if(cursorBegin.y() == cursorEnd.y()) return convertTextWithOneLineHighlighted(src, cursorBegin, cursorEnd); return convertTextWithMultiLineHighlighted(src, cursorBegin, cursorEnd); } QString TestDisplayHtmlConvertor::convertLine(const QString & line, const QPoint & curs, bool selectAreaUnderlined) { int cursPos = curs.x(); int cursLen = curs.y(); int lineLen = line.size(); if(cursPos >= lineLen) return makeLineWithoutCursor(line); if(cursLen == 0) return makeCursoredLine(line, cursPos); if(cursPos == 0) return cursLen < lineLen ? makeLeftHighlightedLine(line, cursLen, selectAreaUnderlined) : makeFullHighlightedLine(line, selectAreaUnderlined); return (cursPos + cursLen) < lineLen ? makeMidHighlightedLine(line, cursPos, cursPos + cursLen, selectAreaUnderlined) : makeRightHighlightedLine(line, cursPos, selectAreaUnderlined); } QString convertTextWithoutHighlighting( const QStringList & src, QPoint cursor ) { QString html; int lineIndex = 0; for(auto line : src) { if(lineIndex == cursor.y()) html += makeLineWithCursor(line, cursor.x()); else html += makeLine(line); lineIndex++; } return html; } QString convertTextWithOneLineHighlighted( const QStringList & src, QPoint cursorBegin, QPoint cursorEnd ) { QString html; int lineIndex = 0; for(auto line : src) { if(lineIndex == cursorBegin.y()) html += makeLineWithHighlighting(line, cursorBegin.x(), cursorEnd.x()); else html += makeLine(line); lineIndex++; } return html; } QString convertTextWithMultiLineHighlighted( const QStringList & src, QPoint cursorBegin, QPoint cursorEnd ) { QString html; int lineIndex = 0; for(auto line : src) { if(lineIndex == cursorBegin.y()) html += makeLineWithHighlightingBegin(line, cursorBegin.x()); else if(lineIndex == cursorEnd.y()) html += makeLineWithHighlightingEnd(line, cursorEnd.x()); else html += makeLine(line); lineIndex++; } return html; } QString makeLine(const QString & line) { return line + htmlLineFeed; } QString makeLineWithCursor(const QString & line, int x) { QString html = line; html.insert(x+1, htmlCursorEnd); html.insert(x, htmlCursorBegin); html += htmlLineFeed; return html; } QString makeLineWithHighlighting(const QString & line, int xBegin, int xEnd) { QString html = line; html.insert(xEnd, htmlHighlightingEnd); html.insert(xBegin, htmlHighlightingBegin); html += htmlLineFeed; return html; } QString makeLineWithHighlightingBegin(const QString & line, int x) { QString html = line; html.insert(x, htmlHighlightingBegin); html += htmlLineFeed; return html; } QString makeLineWithHighlightingEnd(const QString & line, int x) { QString html = line; html.insert(x, htmlHighlightingEnd); html += htmlLineFeed; return html; } QString makeMidHighlightedLine(const QString & line, int highlightingBegin, int highlightingEnd, bool underlined) { QString hbegin = underlined ? htmlCursorBegin : htmlHighlightingBegin; QString hend = underlined ? htmlCursorEnd : htmlHighlightingEnd; return line.mid(0, highlightingBegin) + hbegin + line.mid(highlightingBegin, highlightingEnd-highlightingBegin) + hend + line.mid(highlightingEnd) + htmlLineFeed; } QString makeLeftHighlightedLine(const QString & line, int highlightingBorder, bool underlined) { QString hbegin = underlined ? htmlCursorBegin : htmlHighlightingBegin; QString hend = underlined ? htmlCursorEnd : htmlHighlightingEnd; return hbegin + line.mid(0, highlightingBorder) + hend + line.mid(highlightingBorder) + htmlLineFeed; } QString makeRightHighlightedLine(const QString & line, int highlightingBorder, bool underlined) { QString hbegin = underlined ? htmlCursorBegin : htmlHighlightingBegin; QString hend = underlined ? htmlCursorEnd : htmlHighlightingEnd; return line.mid(0, highlightingBorder) + hbegin + line.mid(highlightingBorder) + hend + htmlLineFeed; } QString makeFullHighlightedLine(const QString & line, bool underlined) { QString hbegin = underlined ? htmlCursorBegin : htmlHighlightingBegin; QString hend = underlined ? htmlCursorEnd : htmlHighlightingEnd; return hbegin + line + hend + htmlLineFeed; } QString makeLineWithoutCursor(const QString & line) { return line + htmlLineFeed; } QString makeCursoredLine(const QString & line, int cursorPosition) { return line.mid(0, cursorPosition) + htmlCursorBegin + line.mid(cursorPosition, 1) + htmlCursorEnd + line.mid(cursorPosition+1) + htmlLineFeed; }
[ "andrew@teslatec.ru" ]
andrew@teslatec.ru
2ce615beed39dc33827d5298364a97085e859d2e
3b52c7dfd69c842d0d28ac3b4012dd00ebd0e0b1
/src/xhttpdServer.h
302e8f8cf6a1ced6073bff2483d5add25326b4a6
[]
no_license
petib/xhttpd
3c1f371ec1bad44a4618376433ce6254a8cf4799
b68f4c1b96afd86ec296d5ba2f5d07d7f877947b
refs/heads/master
2021-01-16T21:23:04.453983
2015-08-20T02:59:18
2015-08-20T02:59:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
454
h
#ifndef __XHTTPDSERVER_H__ #define __XHTTPDSERVER_H__ #include <memory> #include "Socket.h" #include "xhttpdWorker.h" class xhttpdServer : public std::enable_shared_from_this<xhttpdServer> { public: xhttpdServer(uint16_t port, size_t threads); virtual ~xhttpdServer(); void start(); private: Socket listener_; uint16_t port_; std::vector<xhttpdWorker> xhttpdWorker_; }; typedef std::shared_ptr<xhttpdServer> xhttpdServerPtr; #endif
[ "xiaoyifeibupt@outlook.com" ]
xiaoyifeibupt@outlook.com
a38556dc7a417ece9412f0fbb6c7bac2a9efe5f5
a5e00504919bb338910de4cc5c3c3c4afb71e8c6
/CodeForces/contest/1355/d.cpp
dd8b5aafd8bb700da8516de627a8e4d62b98e958
[]
no_license
samuel21119/Cpp
f55333a6e012e020dd45b54d8fff59a339d0f808
056a6570bd28dd795f66f31c82537c79eb57cc72
refs/heads/master
2023-01-05T15:14:55.357393
2020-10-20T23:32:20
2020-10-20T23:32:20
168,485,083
0
0
null
null
null
null
UTF-8
C++
false
false
650
cpp
/************************************************************************* > File Name: d.cpp > Author: Samuel > Mail: enminghuang21119@gmail.com > Created Time: Mon May 25 18:06:17 2020 *************************************************************************/ #include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(0); cin.tie(0); int n, k; cin >> n >> k; if (n * 2 <= k) { cout << "YES\n"; for (int i = 1; i < n; i++) { cout << "2 "; k -= 2; } cout << k << '\n'; cout << "1\n"; }else cout << "NO\n"; return 0; }
[ "enminghuang21119@gmail.com" ]
enminghuang21119@gmail.com
497967f2eeb62a370c0f580ad125d46c0cb8b862
eab939486d515a0242817de07404c6f4f0cf05d2
/dx_20180906_stg/item.cpp
052384fc8825873000634a41baaf82f78dd6b9c5
[]
no_license
moyasikko/skillcheck
f584399b5307a9d32f3544f7ed407eb872bb50a2
bbc26631891d7d9de1b52780e686524a2dd48706
refs/heads/master
2022-02-19T16:21:23.715203
2019-10-01T07:27:18
2019-10-01T07:27:18
212,037,082
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
3,716
cpp
/******************************************************************************* * インクルードファイル *******************************************************************************/ #include <d3dx9.h> #include "item.h" #include "common.h" #include "texture.h" #include "sprite.h" #include "player.h" /******************************************************************************* * マクロ定義 *******************************************************************************/ #define ITEM_MAX (256) #define ITEM_SIZE (40) #define ITEM_SPEED (5) enum { ITEMTYPE_POWER = 0, ITEMTYPE_SCORE, ITEMTYPE_LIFE, ITEMTYPE_MAX }; /******************************************************************************* * グローバル変数 *******************************************************************************/ static int g_ItemTextureIndex[ITEMTYPE_MAX] = { TEXTURE_INVALID_INDEX }; static bool Item_flag[ITEM_MAX]; static D3DXVECTOR2 g_Position[ITEM_MAX]; static D3DXVECTOR2 g_Speed[ITEM_MAX]; static Circle g_ItemCollision[ITEM_MAX]; static short Item_type[ITEM_MAX]; static bool Item_Getflag[ITEM_MAX]; void Item_Initialize(void) { //テクスチャの読込予約 g_ItemTextureIndex[ITEMTYPE_POWER] = Texture_SetLoadFile("./img/Item_P.png", ITEM_SIZE, ITEM_SIZE); g_ItemTextureIndex[ITEMTYPE_SCORE] = Texture_SetLoadFile("./img/Item_S.png", ITEM_SIZE, ITEM_SIZE); g_ItemTextureIndex[ITEMTYPE_LIFE] = Texture_SetLoadFile("./img/Item_L.png", ITEM_SIZE, ITEM_SIZE); //弾を無効にしておく for (int i = 0; i < ITEM_MAX; i++) { Item_flag[i] = false; Item_Getflag[i] = false; g_ItemCollision[i].cx = 0.0f; g_ItemCollision[i].cy = 0.0f; g_ItemCollision[i].radius = ITEM_SIZE; } } void Item_Finalize(void) { //テクスチャーの解放 Texture_Release(&g_ItemTextureIndex[0], ITEMTYPE_MAX); } void Item_Update(void) { for (int i = 0; i < ITEM_MAX; i++) { //弾が無効だったら何もしない //弾が有効だったら //座標を更新する if (Item_flag[i]) { g_Speed[i].y += 0.05; if (Item_Getflag[i]) { g_Speed[i] = Player_GetPosition() - g_Position[i]; D3DXVec2Normalize(&g_Speed[i], &g_Speed[i]); g_Speed[i] *= ITEM_SPEED * 5; } g_Position[i].x += g_Speed[i].x; g_Position[i].y += g_Speed[i].y; g_ItemCollision[i].cx = g_Position[i].x; g_ItemCollision[i].cy = g_Position[i].y; if (Item_type[i] == 0) if (Player_Power() >= 500) Item_type[i] = 1; } //弾が画面外だったら //無効にする if (g_Position[i].y > SCREEN_HEIGHT) { Item_flag[i] = false; } } } void Item_Draw(void) { for (int i = 0; i < ITEM_MAX; i++) { //弾が有効だったら //弾の絵を描く if (Item_flag[i]) { Sprite_DrawRotate(g_ItemTextureIndex[Item_type[i]], g_Position[i].x, g_Position[i].y, 0); } } } void Item_Create(float x, float y, int type) { for (int i = 0; i < ITEM_MAX; i++) { //弾が無効だったら //弾を有効にして //弾の座標をx,yにする if (Item_flag[i] == false) { Item_flag[i] = true; Item_Getflag[i] = false; Item_type[i] = type; g_Position[i] = D3DXVECTOR2(x, y); g_ItemCollision[i].cx = g_Position[i].x; g_ItemCollision[i].cy = g_Position[i].y; g_Speed[i] = D3DXVECTOR2(0, -ITEM_SPEED); break; } } } void Item_Destroy(int i) { Item_flag[i] = false; } bool Item_IsEnable(int i) { return Item_flag[i]; } const Circle* Item_GetCollision(int i) { return &g_ItemCollision[i]; } int Item_MaxGet(void) { return ITEM_MAX; } int Item_TypeGet(int i) { return Item_type[i]; } void Item_GetFlag(void) { for (int i = 0; i < ITEM_MAX; i++) { if (Item_flag[i]) { Item_Getflag[i] = true; } } }
[ "56017003+moyasikko@users.noreply.github.com" ]
56017003+moyasikko@users.noreply.github.com
fff7701e5763c3698468debfcf6b5748ee95b7e7
c80947c934956f935725ceb8bd1ee194c43a8e19
/stuff from college/CS381 Image Processing/Project 8 sobel edge detector/Main.cpp
3cd922652480eaa9fb65714dec1350261714f55c
[]
no_license
QimanWang/Code-Warehouse
964a152af282f53c0752fb0c1cbba31031999e5f
dffe9e7ebf41456d309435d9abc6b7c0aa1f5c8a
refs/heads/master
2021-03-19T06:44:02.285861
2019-03-17T02:34:27
2019-03-17T02:34:27
99,118,714
0
0
null
null
null
null
UTF-8
C++
false
false
4,939
cpp
#include <iostream> #include<fstream> #include <cmath> using namespace std; static int nRow, nCol; class Image { public: int iRow, jCol, label; int numRow, numCol, minVal, maxVal; int** zeroFramedAry; int** createZeroFramedAry(int** arr, int numRow, int numCol, int frameSize) { arr = new int*[numRow + frameSize]; for (int i = 0; i < numRow + frameSize; i++) { arr[i] = new int[numCol + frameSize](); }//fori to create 0 ary return arr; }//crreate zeroFramedAry void prettyPrint(int** imgAry ) { for (int i = 0; i <numRow+2; i++ ) { for (int j = 0; j < numCol+2; j++) { if (imgAry[i][j]==0) { cout << 0 <<" "; } else { cout << 1<<" "; } }//fori cout << endl; }//forj }//pretty print //~~~~~~~~~ void threshPrint(int** imgAry) { for (int i = 0; i <numRow + 2; i++) { for (int j = 0; j < numCol + 2; j++) { if (imgAry[i][j] <29 ) { cout << 0 << " "; } else { cout << 1 << " "; } }//fori cout << endl; }//forj }//pretty print //~~~~~~~~~~ Image(string inFile) { ifstream inputFile; inputFile.open(inFile); int crit; inputFile >> crit; numRow = crit; inputFile >> crit; numCol = crit; inputFile >> crit; minVal = crit; inputFile >> crit; maxVal = crit; zeroFramedAry = createZeroFramedAry(zeroFramedAry, numRow, numCol, 2); bool findFirst = true; for (int i = 1; i < numRow + 1; i++) { for (int j = 1; j < numCol + 1; j++) { inputFile >> crit; zeroFramedAry[i][j] = crit; if (findFirst) { if (zeroFramedAry[i][j] > 0) { iRow = i; jCol = j; label = zeroFramedAry[i][j]; findFirst = false; } } } } nRow = numRow; nCol = numCol; }//constructor//constructor for image }; // image class class Edge { public: int maskHorizontal[3][3] = { {1,2,1},{0,0,0},{-1,-2,-1} }; int maskVertical[3][3] = { { 1,0,-1 },{ 2,0,-2 },{1,0,-1} }; int maskRightDiag[3][3] = { {0,1,2 },{ -1,0,1 },{-2,-1,0} }; int maskLeftDiag[3][3] = { { 2,1,0 },{ 1,0,-1 },{0,-1,-2} }; int** SobelVertical; int** SobelHorizontal; int** SobelRightDiag; int** SobelLeftDiag; int** gradientEdge; int** createEmptyAry(int** arr, int numRow, int numCol, int frameSize) { arr = new int*[numRow + frameSize]; for (int i = 0; i < numRow + frameSize; i++) { arr[i] = new int[numCol + frameSize](); }//fori to create 0 ary return arr; }//crreate zeroFramedAry //~~~~~~~~~~~~~~~~~~~~~~~~~~~~ int convolute(int i, int j,int mask[][3] ,Image img) { int val=0; val += (mask[0][0] * img.zeroFramedAry[i - 1][j - 1]); val += (mask[0][1] * img.zeroFramedAry[i - 1][j ]); val += (mask[0][2] * img.zeroFramedAry[i - 1][j + 1]); val += (mask[1][0] * img.zeroFramedAry[i ][j - 1]); val += (mask[1][1] * img.zeroFramedAry[i ][j ]); val += (mask[1][2] * img.zeroFramedAry[i ][j + 1]); val += (mask[2][0] * img.zeroFramedAry[i + 1][j - 1]); val += (mask[2][1] * img.zeroFramedAry[i + 1][j ]); val += (mask[2][2] * img.zeroFramedAry[i + 1][j + 1]); return val; }//convolute int computeGradient(int i, int j,int** imgAry) { return(abs(imgAry[i][j] - imgAry[i + 1][j]) + abs(imgAry[i][j] - imgAry[i][j + 1])); }//compute gradient Edge(int row, int col) { SobelHorizontal = createEmptyAry(SobelHorizontal, row, col, 2); SobelVertical = createEmptyAry(SobelVertical, row, col, 2); SobelLeftDiag = createEmptyAry(SobelLeftDiag, row, col, 2); SobelRightDiag = createEmptyAry(SobelRightDiag, row, col, 2); gradientEdge = createEmptyAry(gradientEdge, row, col, 2); }//constructor };//edge class int main(int argc, char** argv) { int c; Image inputImage(argv[1]); Edge myEdge(nRow,nCol); cout << "image had been loaded" << endl; inputImage.prettyPrint(inputImage.zeroFramedAry); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { cout << myEdge.maskHorizontal[i][j] << " "; } cout << endl; } for (int i = 1; i < inputImage.numRow + 1; i++) { for (int j = 0; j < inputImage.numCol + 1; j++) { myEdge.SobelHorizontal[i][j] = abs(myEdge.convolute(i, j, myEdge.maskHorizontal, inputImage)); myEdge.SobelVertical[i][j] = abs(myEdge.convolute(i, j, myEdge.maskVertical, inputImage)); //myEdge.SobelLeftDiag[i][j] = abs(myEdge.convolute(i, j, myEdge.maskLeftDiag, inputImage)); //myEdge.maskRightDiag[i][j] = abs(myEdge.convolute(i, j, myEdge.maskRightDiag, inputImage)); //myEdge.gradientEdge[i][j] = myEdge.computeGradient(i,j,inputImage.zeroFramedAry); }//forj }//fori inputImage.threshPrint(inputImage.zeroFramedAry); cout<<"horizontal detetction"<<endl; inputImage.prettyPrint(myEdge.SobelHorizontal); cout << "vetical detetction" << endl; inputImage.prettyPrint(myEdge.SobelVertical); inputImage.prettyPrint(myEdge.SobelLeftDiag); inputImage.prettyPrint(myEdge.SobelRightDiag); inputImage.prettyPrint(myEdge.gradientEdge); cin >> c; }
[ "wangqiman0111@gmail.com" ]
wangqiman0111@gmail.com
9c653f92135f83eb3be3cc855cb73e82606026b1
db12881b7f37b3524704e5af9a2da9156f29fcf4
/src/qt/paymentrequestplus.cpp
48b2823c47111dbfed31f9ebb42c0caca054be48
[ "MIT" ]
permissive
melihcanmavis/BlacerCoin
415bf9a06a73a11fcee2bbc6bbcf442a4a2ffdbc
9fd2cef476d2f0446a9f2ccc515fd53dca9ea6c9
refs/heads/master
2020-06-15T09:19:49.416239
2019-06-24T09:02:41
2019-06-24T09:02:41
195,259,024
1
0
null
2019-07-04T14:43:39
2019-07-04T14:43:38
null
UTF-8
C++
false
false
7,732
cpp
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2017-2018 The PIVX developers // Copyright (c) 2018 The BlacerCoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // // Wraps dumb protocol buffer paymentRequest // with some extra methods // #include "paymentrequestplus.h" #include <stdexcept> #include <openssl/x509.h> #include <openssl/x509_vfy.h> #include <QDateTime> #include <QDebug> #include <QSslCertificate> using namespace std; class SSLVerifyError : public std::runtime_error { public: SSLVerifyError(std::string err) : std::runtime_error(err) {} }; bool PaymentRequestPlus::parse(const QByteArray& data) { bool parseOK = paymentRequest.ParseFromArray(data.data(), data.size()); if (!parseOK) { qWarning() << "PaymentRequestPlus::parse : Error parsing payment request"; return false; } if (paymentRequest.payment_details_version() > 1) { qWarning() << "PaymentRequestPlus::parse : Received up-version payment details, version=" << paymentRequest.payment_details_version(); return false; } parseOK = details.ParseFromString(paymentRequest.serialized_payment_details()); if (!parseOK) { qWarning() << "PaymentRequestPlus::parse : Error parsing payment details"; paymentRequest.Clear(); return false; } return true; } bool PaymentRequestPlus::SerializeToString(string* output) const { return paymentRequest.SerializeToString(output); } bool PaymentRequestPlus::IsInitialized() const { return paymentRequest.IsInitialized(); } QString PaymentRequestPlus::getPKIType() const { if (!IsInitialized()) return QString("none"); return QString::fromStdString(paymentRequest.pki_type()); } bool PaymentRequestPlus::getMerchant(X509_STORE* certStore, QString& merchant) const { merchant.clear(); if (!IsInitialized()) return false; // One day we'll support more PKI types, but just // x509 for now: const EVP_MD* digestAlgorithm = NULL; if (paymentRequest.pki_type() == "x509+sha256") { digestAlgorithm = EVP_sha256(); } else if (paymentRequest.pki_type() == "x509+sha1") { digestAlgorithm = EVP_sha1(); } else if (paymentRequest.pki_type() == "none") { qWarning() << "PaymentRequestPlus::getMerchant : Payment request: pki_type == none"; return false; } else { qWarning() << "PaymentRequestPlus::getMerchant : Payment request: unknown pki_type " << QString::fromStdString(paymentRequest.pki_type()); return false; } payments::X509Certificates certChain; if (!certChain.ParseFromString(paymentRequest.pki_data())) { qWarning() << "PaymentRequestPlus::getMerchant : Payment request: error parsing pki_data"; return false; } std::vector<X509*> certs; const QDateTime currentTime = QDateTime::currentDateTime(); for (int i = 0; i < certChain.certificate_size(); i++) { QByteArray certData(certChain.certificate(i).data(), certChain.certificate(i).size()); QSslCertificate qCert(certData, QSsl::Der); if (currentTime < qCert.effectiveDate() || currentTime > qCert.expiryDate()) { qWarning() << "PaymentRequestPlus::getMerchant : Payment request: certificate expired or not yet active: " << qCert; return false; } #if QT_VERSION >= 0x050000 if (qCert.isBlacklisted()) { qWarning() << "PaymentRequestPlus::getMerchant : Payment request: certificate blacklisted: " << qCert; return false; } #endif const unsigned char* data = (const unsigned char*)certChain.certificate(i).data(); X509* cert = d2i_X509(NULL, &data, certChain.certificate(i).size()); if (cert) certs.push_back(cert); } if (certs.empty()) { qWarning() << "PaymentRequestPlus::getMerchant : Payment request: empty certificate chain"; return false; } // The first cert is the signing cert, the rest are untrusted certs that chain // to a valid root authority. OpenSSL needs them separately. STACK_OF(X509)* chain = sk_X509_new_null(); for (int i = certs.size() - 1; i > 0; i--) { sk_X509_push(chain, certs[i]); } X509* signing_cert = certs[0]; // Now create a "store context", which is a single use object for checking, // load the signing cert into it and verify. X509_STORE_CTX* store_ctx = X509_STORE_CTX_new(); if (!store_ctx) { qWarning() << "PaymentRequestPlus::getMerchant : Payment request: error creating X509_STORE_CTX"; return false; } char* website = NULL; bool fResult = true; try { if (!X509_STORE_CTX_init(store_ctx, certStore, signing_cert, chain)) { int error = X509_STORE_CTX_get_error(store_ctx); throw SSLVerifyError(X509_verify_cert_error_string(error)); } // Now do the verification! int result = X509_verify_cert(store_ctx); if (result != 1) { int error = X509_STORE_CTX_get_error(store_ctx); throw SSLVerifyError(X509_verify_cert_error_string(error)); } X509_NAME* certname = X509_get_subject_name(signing_cert); // Valid cert; check signature: payments::PaymentRequest rcopy(paymentRequest); // Copy rcopy.set_signature(std::string("")); std::string data_to_verify; // Everything but the signature rcopy.SerializeToString(&data_to_verify); #if OPENSSL_VERSION_NUMBER >= 0x10100000L EVP_MD_CTX *ctx = EVP_MD_CTX_new(); if (!ctx) throw SSLVerifyError("Error allocating OpenSSL context."); #else EVP_MD_CTX _ctx; EVP_MD_CTX *ctx; ctx = &_ctx; #endif EVP_PKEY* pubkey = X509_get_pubkey(signing_cert); EVP_MD_CTX_init(ctx); if (!EVP_VerifyInit_ex(ctx, digestAlgorithm, NULL) || !EVP_VerifyUpdate(ctx, data_to_verify.data(), data_to_verify.size()) || !EVP_VerifyFinal(ctx, (const unsigned char*)paymentRequest.signature().data(), paymentRequest.signature().size(), pubkey)) { throw SSLVerifyError("Bad signature, invalid PaymentRequest."); } #if OPENSSL_VERSION_NUMBER >= 0x10100000L EVP_MD_CTX_free(ctx); #endif // OpenSSL API for getting human printable strings from certs is baroque. int textlen = X509_NAME_get_text_by_NID(certname, NID_commonName, NULL, 0); website = new char[textlen + 1]; if (X509_NAME_get_text_by_NID(certname, NID_commonName, website, textlen + 1) == textlen && textlen > 0) { merchant = website; } else { throw SSLVerifyError("Bad certificate, missing common name."); } // TODO: detect EV certificates and set merchant = business name instead of unfriendly NID_commonName ? } catch (SSLVerifyError& err) { fResult = false; qWarning() << "PaymentRequestPlus::getMerchant : SSL error: " << err.what(); } if (website) delete[] website; X509_STORE_CTX_free(store_ctx); for (unsigned int i = 0; i < certs.size(); i++) X509_free(certs[i]); return fResult; } QList<std::pair<CScript, CAmount> > PaymentRequestPlus::getPayTo() const { QList<std::pair<CScript, CAmount> > result; for (int i = 0; i < details.outputs_size(); i++) { const unsigned char* scriptStr = (const unsigned char*)details.outputs(i).script().data(); CScript s(scriptStr, scriptStr + details.outputs(i).script().size()); result.append(make_pair(s, details.outputs(i).amount())); } return result; }
[ "root@ubuntu16.local" ]
root@ubuntu16.local
313bb38c5369b1a788521c4a17dbb77dd7e5a73b
cca7c1347e2033ee0682741684713624adf68b54
/FluxEngine/Physics/PhysX/PhysxAllocator.h
7b978e6facbd8a932807632efdcb89349e64a71b
[ "MIT" ]
permissive
Junho2009/FluxEngine
df9d88c1913e75dbb4bd5af1bafaaaeb131a2226
9c276016f38869ddb5e8879f1414e508930d3633
refs/heads/master
2023-03-18T06:16:13.694999
2019-01-05T14:35:16
2019-01-05T14:35:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
495
h
#pragma once class PhysxAllocator : public physx::PxAllocatorCallback { public: virtual void* allocate(size_t size, const char* typeName, const char* filename, int line) override { #ifdef PHYSX_DEBUG_ALLOCATIONS FLUX_LOG(Log, "[PhysxAllocator::allocate()] Allocated %d bytes for %s at %s (%d)", size, typename, filename, line); #else typeName; filename; line; #endif return _aligned_malloc(size, 16); } virtual void deallocate(void* ptr) override { _aligned_free(ptr); } };
[ "sim2.coenen@gmail.com" ]
sim2.coenen@gmail.com
64253be5f6e7e3742bfa1bd6baffb8ee42876764
2732c0ecbc3f598b29362f020e79188678d2edd2
/5-Final/Q1.cpp
b1fec09134b1c76a3163983b55fab2d56984da6b
[]
no_license
yfyucesoy/Problems-in-Algorithms-and-Data-Structures
b023263472d51798ece42030204aaa9e4f4d3e6f
c31b9d19ccaed52f3429d4e9f3dc7abe454569a8
refs/heads/master
2022-11-06T20:59:18.763599
2020-06-30T22:54:39
2020-06-30T22:54:39
263,942,377
3
0
null
null
null
null
UTF-8
C++
false
false
2,635
cpp
/* @author: Yusuf Furkan Yucesoy */ #include <stdio.h> #include <iostream> #include <vector> #include <map> #include <list> #include "Q1.h" using namespace std; map<int, std::list<int>::iterator> m; list<int> l; map<int, std::list<int>::iterator>::iterator medianPtr; // Returns "true" if the DS is empty bool Q1DS::empty() { return l.size() == 0; } // Insert "key" in O(logn) void Q1DS::insert(int key) { if (l.empty()) { l.push_back(key); m.insert(make_pair(key, l.begin())); medianPtr = m.begin(); return; } else if (medianPtr->first < key && l.size() % 2 != 0) { auto mapiter = (m.insert(make_pair(key, l.begin()))).first; auto tmp = mapiter; mapiter--; tmp->second=l.insert(std::next((mapiter->second)), key); } else if (medianPtr->first<key && l.size()%2 == 0){ auto mapiter = (m.insert(make_pair(key, l.begin()))).first; auto tmp = mapiter; mapiter--; tmp->second = l.insert(std::next((mapiter->second)), key); medianPtr++; } else if (medianPtr->first > key && l.size()%2 != 0) { auto mapiter = (m.insert(make_pair(key, l.begin()))).first; auto tmp = mapiter; mapiter--; tmp->second = l.insert(std::next((mapiter->second)), key); medianPtr--; } else if (medianPtr->first > key && l.size() % 2 == 0) { auto mapiter = (m.insert(make_pair(key, l.begin()))).first; auto tmp = mapiter; mapiter--; tmp->second = l.insert(std::next((mapiter->second)), key); } } //end-insert // Delete "key" in O(logn) void Q1DS::erase(int key) { if (l.size() == 0) { throw "Size is zero"; } else { if (medianPtr->first <= key && l.size() % 2 != 0) { auto tmp=m.find(key); medianPtr--; l.erase(tmp->second); m.erase(key); } else if (medianPtr->first < key && l.size() % 2 == 0) { auto tmp = m.find(key); l.erase(tmp->second); m.erase(key); } else if (medianPtr->first > key && l.size() % 2 != 0) { auto tmp = m.find(key); l.erase(tmp->second); m.erase(key); } else if (medianPtr->first >= key && l.size() % 2 == 0) { auto tmp = m.find(key); medianPtr++; l.erase(tmp->second); m.erase(key); } } } // end-erase // Return the median in O(1) double Q1DS::median() { double medianvalue; if (l.size() % 2 == 0) { map<int, std::list<int>::iterator>::iterator medianPtrTmp = medianPtr; medianPtrTmp++; medianvalue = (double)((medianPtr->first) + (medianPtrTmp->first))/2; return medianvalue; } else { medianvalue = medianPtr->first; return medianvalue; } return 0; } //end-median
[ "noreply@github.com" ]
noreply@github.com
f3d002a9908851fd10be50f065042a36a603d24f
70927ebfa40ae0b6ce5d19cb5256cfb880de4f07
/Pods/geos/Sources/geos/src/algorithm/PointLocation.cpp
ca38f95ea85081be17aa72b58af071aacd103d40
[ "LGPL-2.1-only", "LGPL-2.0-or-later", "GPL-2.0-only", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
baato/BaatoSwift
44af06fe3a1af26fe8540376cdc82a93e498fdbc
87cb476affbdf24f4b902bb498970051d0382a9c
refs/heads/master
2023-03-28T07:50:10.326223
2020-12-09T09:58:48
2020-12-09T09:58:48
294,601,067
0
0
MIT
2020-12-08T08:09:04
2020-09-11T05:17:37
Swift
UTF-8
C++
false
false
2,457
cpp
/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2018 Paul Ramsey <pramsey@cleverlephant.ca> * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * * Last port: algorithm/PointLocation.java @ 2017-09-04 * **********************************************************************/ #include <cmath> #include <vector> #include <geos/algorithm/LineIntersector.h> #include <geos/algorithm/PointLocation.h> #include <geos/algorithm/RayCrossingCounter.h> #include <geos/geom/CoordinateSequence.h> #include <geos/geom/Coordinate.h> #include <geos/geom/Location.h> #include <geos/util/IllegalArgumentException.h> namespace geos { namespace algorithm { // geos.algorithm /* public static */ bool PointLocation::isOnLine(const geom::Coordinate& p, const geom::CoordinateSequence* pt) { size_t ptsize = pt->getSize(); if(ptsize == 0) { return false; } const geom::Coordinate* pp = &(pt->getAt(0)); for(size_t i = 1; i < ptsize; ++i) { const geom::Coordinate& p1 = pt->getAt(i); if(LineIntersector::hasIntersection(p, *pp, p1)) { return true; } pp = &p1; } return false; } /* public static */ bool PointLocation::isInRing(const geom::Coordinate& p, const std::vector<const geom::Coordinate*>& ring) { return PointLocation::locateInRing(p, ring) != geom::Location::EXTERIOR; } /* public static */ bool PointLocation::isInRing(const geom::Coordinate& p, const geom::CoordinateSequence* ring) { return PointLocation::locateInRing(p, *ring) != geom::Location::EXTERIOR; } /* public static */ geom::Location PointLocation::locateInRing(const geom::Coordinate& p, const std::vector<const geom::Coordinate*>& ring) { return RayCrossingCounter::locatePointInRing(p, ring); } /* public static */ geom::Location PointLocation::locateInRing(const geom::Coordinate& p, const geom::CoordinateSequence& ring) { return RayCrossingCounter::locatePointInRing(p, ring); } } // namespace geos.algorithm } // namespace geos
[ "bhawak.pokhrel@gmail.com" ]
bhawak.pokhrel@gmail.com
82112572f9c620d329252158daec8f66d86be7d5
0cdc5d77e28c119c83d5d8d39c185d2dac600311
/move.hpp
7206f52c749be313ecf1eae0f485d478f17c3a4c
[]
no_license
glewtimo/chess_ai
fcfe7140ee89f044967f9d5d1f632fae7ce909cf
98e1b0631a6d0667eca17ccf1752414e6be46088
refs/heads/master
2020-11-26T12:20:17.099218
2020-03-13T21:12:09
2020-03-13T21:12:09
229,069,862
0
0
null
null
null
null
UTF-8
C++
false
false
878
hpp
/********************************************************************************** * Program name: move.hpp * Author: Tim Glew * Date: 12/19/2019 * Desription: This is the declaration of the class Move which represents one * game move made by a player. * See below for member variables and member functions. *********************************************************************************/ #ifndef MOVE_HPP #define MOVE_HPP /* Forward Declarations */ class Player; class Square; class Piece; class Move { private: Player* player; Square* start; Square* end; Piece* pieceMoved; Piece* pieceKilled; public: Move(Player*, Square*, Square*); Square* getStart(); Square* getEnd(); void setPieceKilled(Piece*); }; #endif
[ "noreply@github.com" ]
noreply@github.com
00a3a9881d14466d4e7089dddb456857aea2cdbb
f0a26ec6b779e86a62deaf3f405b7a83868bc743
/Engine/Source/Developer/CrashDebugHelper/Private/CrashDebugHelperModule.cpp
4106691f399cccd38003f4b05b6c7f67b0fc47c8
[]
no_license
Tigrouzen/UnrealEngine-4
0f15a56176439aef787b29d7c80e13bfe5c89237
f81fe535e53ac69602bb62c5857bcdd6e9a245ed
refs/heads/master
2021-01-15T13:29:57.883294
2014-03-20T15:12:46
2014-03-20T15:12:46
18,375,899
1
0
null
null
null
null
UTF-8
C++
false
false
684
cpp
// Copyright 1998-2014 Epic Games, Inc. All Rights Reserved. #include "CrashDebugHelperPrivatePCH.h" #include "ModuleInterface.h" #include "ModuleManager.h" #include "CrashDebugHelperModule.h" IMPLEMENT_MODULE(FCrashDebugHelperModule, CrashDebugHelper); DEFINE_LOG_CATEGORY(LogCrashDebugHelper); void FCrashDebugHelperModule::StartupModule() { CrashDebugHelper = new FCrashDebugHelper(); if (CrashDebugHelper != NULL) { CrashDebugHelper->Init(); } } void FCrashDebugHelperModule::ShutdownModule() { if (CrashDebugHelper != NULL) { delete CrashDebugHelper; CrashDebugHelper = NULL; } } ICrashDebugHelper* FCrashDebugHelperModule::Get() { return CrashDebugHelper; }
[ "michaellam430@gmail.com" ]
michaellam430@gmail.com
ffbf3e3e556617bab46855dad9e4afc2ecae9a81
14d26d26ac6fc5c7c88fc278f586d5f22cb3759e
/glfw/assimp/camera.h
e86d8846ac41d139901fe6fe9438ecae5c61eb2e
[]
no_license
jsheedy/cube
4e5a1806b191803d87812882b955cc39dc78086e
938c20c299fb9254c1041e33c80798da5acebdb6
refs/heads/master
2021-08-16T12:29:49.667253
2017-11-17T18:15:51
2017-11-17T18:15:51
111,331,387
0
0
null
null
null
null
UTF-8
C++
false
false
4,533
h
#ifndef CAMERA_H #define CAMERA_H #include <glad/glad.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <vector> // Defines several possible options for camera movement. Used as abstraction to stay away from window-system specific input methods enum Camera_Movement { FORWARD, BACKWARD, LEFT, RIGHT, UP, DOWN }; // Default camera values const float YAW = -90.0f; const float PITCH = 0.0f; const float SPEED = 20.5f; const float SENSITIVTY = 0.1f; const float ZOOM = 45.0f; // An abstract camera class that processes input and calculates the corresponding Eular Angles, Vectors and Matrices for use in OpenGL class Camera { public: // Camera Attributes glm::vec3 Position; glm::vec3 Front; glm::vec3 Up; glm::vec3 Right; glm::vec3 WorldUp; // Eular Angles float Yaw; float Pitch; // Camera options float MovementSpeed; float MouseSensitivity; float Zoom; // Constructor with vectors Camera(glm::vec3 position = glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f), float yaw = YAW, float pitch = PITCH) : Front(glm::vec3(0.0f, 0.0f, -1.0f)), MovementSpeed(SPEED), MouseSensitivity(SENSITIVTY), Zoom(ZOOM) { Position = position; WorldUp = up; Yaw = yaw; Pitch = pitch; updateCameraVectors(); } // Constructor with scalar values Camera(float posX, float posY, float posZ, float upX, float upY, float upZ, float yaw, float pitch) : Front(glm::vec3(0.0f, 0.0f, -1.0f)), MovementSpeed(SPEED), MouseSensitivity(SENSITIVTY), Zoom(ZOOM) { Position = glm::vec3(posX, posY, posZ); WorldUp = glm::vec3(upX, upY, upZ); Yaw = yaw; Pitch = pitch; updateCameraVectors(); } // Returns the view matrix calculated using Eular Angles and the LookAt Matrix glm::mat4 GetViewMatrix() { return glm::lookAt(Position, Position + Front, Up); } // Processes input received from any keyboard-like input system. Accepts input parameter in the form of camera defined ENUM (to abstract it from windowing systems) void ProcessKeyboard(Camera_Movement direction, float deltaTime) { float velocity = MovementSpeed * deltaTime; if (direction == FORWARD) Position += Front * velocity; if (direction == BACKWARD) Position -= Front * velocity; if (direction == LEFT) Position -= Right * velocity; if (direction == RIGHT) Position += Right * velocity; if (direction == UP) Position += Up * velocity; if (direction == DOWN) Position += -Up * velocity; } // Processes input received from a mouse input system. Expects the offset value in both the x and y direction. void ProcessMouseMovement(float xoffset, float yoffset, GLboolean constrainPitch = true) { xoffset *= MouseSensitivity; yoffset *= MouseSensitivity; Yaw += xoffset; Pitch += yoffset; // Make sure that when pitch is out of bounds, screen doesn't get flipped if (constrainPitch) { if (Pitch > 89.0f) Pitch = 89.0f; if (Pitch < -89.0f) Pitch = -89.0f; } // Update Front, Right and Up Vectors using the updated Eular angles updateCameraVectors(); } // Processes input received from a mouse scroll-wheel event. Only requires input on the vertical wheel-axis void ProcessMouseScroll(float yoffset) { if (Zoom >= 1.0f && Zoom <= 45.0f) Zoom -= yoffset; if (Zoom <= 1.0f) Zoom = 1.0f; if (Zoom >= 45.0f) Zoom = 45.0f; } private: // Calculates the front vector from the Camera's (updated) Eular Angles void updateCameraVectors() { // Calculate the new Front vector glm::vec3 front; front.x = cos(glm::radians(Yaw)) * cos(glm::radians(Pitch)); front.y = sin(glm::radians(Pitch)); front.z = sin(glm::radians(Yaw)) * cos(glm::radians(Pitch)); Front = glm::normalize(front); // Also re-calculate the Right and Up vector Right = glm::normalize(glm::cross(Front, WorldUp)); // Normalize the vectors, because their length gets closer to 0 the more you look up or down which results in slower movement. Up = glm::normalize(glm::cross(Right, Front)); } }; #endif
[ "joseph.sheedy@gmail.com" ]
joseph.sheedy@gmail.com
4f5ab3efd49ff3e9484d1cf762d79314c13ade6b
79901affb4f74eb2b00a04b60e2eb48118fff381
/src/ofxBranch.cpp
10572a2cc79c21a96364ea21648d3ec4436b52ea
[]
no_license
ofxyz/ofxBranchesPrimitive
af6a851bfb004bc78fd84425e1a4ef9479b81f30
55dedfbddfca8b0706b58840ecf646d2efaf84b9
refs/heads/master
2021-10-03T10:11:10.006227
2018-12-02T14:07:35
2018-12-02T14:07:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,790
cpp
#include "ofxBranch.h" ofxBranch::ofxBranch(glm::vec4 _startPos, glm::vec4 _endPos, glm::quat _orientation, glm::vec3 _startDir){ startPos = _startPos; startDirection = _startDir; endPos = _endPos; startOrientation = _orientation; endDirection = calculateEndDirection(_startPos, _endPos); endOrientation = calculateEndOrientation(_startDir, endDirection); }; void ofxBranch::update(glm::vec4 _startPos, glm::vec4 _endPos, glm::quat _orientation, glm::vec3 _startDir){ startPos = _startPos; startDirection = _startDir; endPos = _endPos; startOrientation = _orientation; endDirection = calculateEndDirection(_startPos, _endPos); endOrientation = calculateEndOrientation(_startDir, endDirection); }; void ofxBranch::setParentByIndex(int parent_index) { this->indexParent = parent_index; }; glm::quat ofxBranch::calculateEndOrientation(glm::vec3 startDirection, glm::vec3 endDirection){ glm::quat topRotation = rotationBetweenVectors(startDirection, endDirection); return topRotation * startOrientation; } glm::vec3 ofxBranch::calculateEndDirection(glm::vec4 startPos, glm::vec4 endPos){ if(startPos == endPos){ // if startPos and endPos are the same, // calculateEndDirection returns NaN, avoid this situation return startDirection; } else { return glm::normalize(glm::vec3(endPos - startPos)); } } // http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-17-quaternions/#how-do-i-find-the-rotation-between-2-vectors- glm::quat ofxBranch::rotationBetweenVectors(glm::vec3 start, glm::vec3 dest){ start = glm::normalize(start); dest = glm::normalize(dest); float cosTheta = dot(start, dest); glm::vec3 rotationAxis; if (cosTheta < -1 + 0.001f){ // special case when vectors in opposite directions: // there is no "ideal" rotation axis // So guess one; any will do as long as it's perpendicular to start rotationAxis = glm::cross(glm::vec3(0.0f, 0.0f, 1.0f), start); if (glm::length2(rotationAxis) < 0.01 ) // bad luck, they were parallel, try again! rotationAxis = glm::cross(glm::vec3(1.0f, 0.0f, 0.0f), start); rotationAxis = glm::normalize(rotationAxis); //return gtx::quaternion::angleAxis(180.0f, rotationAxis); glm::angleAxis(180.0f, rotationAxis); } rotationAxis = glm::cross(start, dest); float s = glm::sqrt( (1+cosTheta)*2 ); float invs = 1 / s; return glm::quat( s * 0.5f, rotationAxis.x * invs, rotationAxis.y * invs, rotationAxis.z * invs ); } const float ofxBranch::getLength(){ return glm::distance(startPos, endPos); };
[ "lastexxit@gmail.com" ]
lastexxit@gmail.com
5f8977a721d6b62970f870950750f8b86f43ca18
7d23b7237a8c435c3c4324f1b59ef61e8b2bde63
/include/log/log_stream.cpp
4d050f9aef976aae0614f690bf3187e6c68bf00b
[]
no_license
chenyu2202863/smart_cpp_lib
af1ec275090bf59af3c29df72b702b94e1e87792
31de423f61998f3b82a14fba1d25653d45e4e719
refs/heads/master
2021-01-13T01:50:49.456118
2016-02-01T07:11:01
2016-02-01T07:11:01
7,198,248
4
3
null
null
null
null
UTF-8
C++
false
false
248
cpp
#include "log_stream.hpp" #include <Windows.h> namespace logging { const char* log_level_name[static_cast<const std::uint32_t>(level::NUM_LOG_LEVELS)] = { "TRACE ", "DEBUG ", "INFO ", "WARN ", "ERROR ", "FATAL ", "" }; }
[ "chenyu2202863@gmail.com" ]
chenyu2202863@gmail.com
02390300657d6d60f4d408090eb489e7184729ba
30a795c612eb8d5851e0ad59749907e964b34672
/include/caffe/layers/cyclesub_layer.hpp
4ec49b3cb27bf75ffa5070477444ac2db8e3f879
[ "LicenseRef-scancode-generic-cla", "BSD-2-Clause", "LicenseRef-scancode-public-domain" ]
permissive
imoisture/caffe
e46de72520ae5a9a144e0d8a1f8b7b9191862c70
4d6892afeff234c57ce470056939101e0ae71369
refs/heads/master
2021-01-02T15:53:19.477997
2020-05-15T12:00:52
2020-05-15T12:00:52
235,069,978
0
0
NOASSERTION
2020-01-20T09:59:04
2020-01-20T09:59:03
null
UTF-8
C++
false
false
3,031
hpp
/* All modification made by Cambricon Corporation: © 2018 Cambricon Corporation All rights reserved. All other contributions: Copyright (c) 2014--2018, the respective contributors All rights reserved. For the list of contributors go to https://github.com/BVLC/caffe/blob/master/CONTRIBUTORS.md Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation 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. */ #ifndef INCLUDE_CAFFE_LAYERS_CYCLESUB_LAYER_HPP_ #define INCLUDE_CAFFE_LAYERS_CYCLESUB_LAYER_HPP_ #include <vector> #include "caffe/blob.hpp" #include "caffe/layer.hpp" #include "caffe/layers/neuron_layer.hpp" #include "caffe/proto/caffe.pb.h" namespace caffe { /** * @brief bottom[0] - bottom[1] = top * the shape of bottom[0] is n * c * h * w * the shape of bottom[1] is 1 * c * 1 * 1 * the shape of top is n * c * h * w * */ template <typename Dtype> class CycleSubLayer: public NeuronLayer<Dtype> { public: explicit CycleSubLayer(const LayerParameter& param) : NeuronLayer<Dtype>(param) {} virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "CycleSub"; } virtual inline int ExactNumBottomBlobs() const { return 2;} protected: virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {} }; } // namespace caffe #endif // INCLUDE_CAFFE_LAYERS_CYCLESUB_LAYER_HPP_
[ "lichao@cambricon.com" ]
lichao@cambricon.com
d3c5895b5cd648da225d81a56a07f8edef6ae5b7
65f6b26271fc16e70c0cbe73666b770557262576
/cartoon.cpp
fd7ac76df74ed9705d32ab24b1142973bd489522
[]
no_license
jiku100/Cartoon
78ee49d027b0425ff26b9d06d8c7c13f46c42aca
aa076df2910fa4a7fee23b983b617f9d2e5b56a2
refs/heads/master
2023-02-15T07:11:18.891183
2021-01-08T17:02:05
2021-01-08T17:02:05
327,924,971
0
0
null
null
null
null
UHC
C++
false
false
5,731
cpp
#include "opencv2/opencv.hpp" using namespace cv; using namespace std; #define DEBUG 0 void cartoonifyImage(InputArray src, OutputArray dst, bool isAlien = false) { Mat srcColor = src.getMat(); // 에지 검출 Mat gray; cvtColor(srcColor, gray, COLOR_BGR2GRAY); #if DEBUG == 1 imshow("gray", gray); #endif const int MEDIAN_BLUR_FILTER_SIZE = 7; medianBlur(gray, gray, MEDIAN_BLUR_FILTER_SIZE); //GaussianBlur(gray, gray, Size(), 1); #if DEBUG == 1 imshow("medianBlur", gray); #endif Mat edges; const int LAPLACIAN_FILTER_SIZE = 5; Laplacian(gray, edges, CV_8U, LAPLACIAN_FILTER_SIZE); #if DEBUG == 1 imshow("edges", edges); #endif Mat mask; const int EDGES_THRESHOLD = 80; threshold(edges, mask, EDGES_THRESHOLD, 255, THRESH_BINARY_INV); dst.create(mask.size(), mask.type()); #if DEBUG == 1 imshow("Mask", mask); #endif // 컬러 페인팅 Size size = srcColor.size(); Size smallSize; smallSize.width = size.width / 2; smallSize.height = size.height / 2; Mat smallImg = Mat(smallSize, CV_8UC3); resize(srcColor, smallImg, smallSize, 0, 0, INTER_LINEAR); Mat tmp = Mat(smallSize, CV_8UC3); int repetitions = 7; for (int i = 0; i < repetitions; i++) { int ksize = 7; double sigmaColor = 9; double sigmaSpace = 5; bilateralFilter(smallImg, tmp, ksize, sigmaColor, sigmaSpace); bilateralFilter(tmp, smallImg, ksize, sigmaColor, sigmaSpace); } #if DEBUG == 1 imshow("bilateral", smallImg); #endif Mat bigImg; resize(smallImg, bigImg, size, 0, 0, INTER_LINEAR); dst.setTo(0); bigImg.copyTo(dst, mask); if (isAlien) { Mat yuv = Mat(smallSize, CV_8UC3); cvtColor(smallImg, yuv, COLOR_BGR2YCrCb); int sw = smallSize.width; int sh = smallSize.height; Mat maskAlien, maskPlusBorder; maskPlusBorder = Mat::zeros(sh + 2, sw + 2, CV_8UC1); maskAlien = maskPlusBorder(Rect(1, 1, sw, sh)); resize(edges, maskAlien, smallSize); threshold(maskAlien, maskAlien, EDGES_THRESHOLD, 255, THRESH_BINARY); dilate(maskAlien, maskAlien, Mat()); erode(maskAlien, maskAlien, Mat()); const int NUM_SKIN_POINTS = 6; Point skinPts[NUM_SKIN_POINTS]; skinPts[0] = Point(sw / 2, sh / 2 - sh / 6); skinPts[1] = Point(sw / 2 - sw / 11, sh / 2 - sh / 6); skinPts[2] = Point(sw / 2 + sw / 11, sh / 2 - sh / 6); skinPts[3] = Point(sw / 2, sh / 2 + sh / 16); skinPts[4] = Point(sw / 2 - sw / 9, sh / 2 + sh / 16); skinPts[5] = Point(sw / 2 + sw / 9, sh / 2 + sh / 16); const int LOWER_Y = 60; const int UPPER_Y = 70; const int LOWER_Cr = 25; const int UPPER_Cr = 15; const int LOWER_Cb = 20; const int UPPER_Cb = 15; Scalar lowerDiff = Scalar(LOWER_Y, LOWER_Cr, LOWER_Cb); Scalar upperDiff = Scalar(UPPER_Y, UPPER_Cr, UPPER_Cb); const int CONNECTED_COMPONENTS = 4; //대각선까지 하려면 8 const int flags = CONNECTED_COMPONENTS | FLOODFILL_FIXED_RANGE | FLOODFILL_MASK_ONLY; Mat edgeMask = maskAlien.clone(); for (int i = 0; i < NUM_SKIN_POINTS; i++) { floodFill(yuv, maskPlusBorder, skinPts[i], Scalar(), NULL, lowerDiff, upperDiff, flags); } maskAlien -= edgeMask; int Red = 0; int Green = 70; int Blue = 0; add(smallImg, CV_RGB(Red, Green, Blue), smallImg, maskAlien); resize(smallImg, bigImg, size, 0, 0, INTER_LINEAR); dst.setTo(0); bigImg.copyTo(dst, mask); } } void cartoonDevImage(InputArray src, OutputArray dst) { Mat srcColor = src.getMat(); // 에지 검출 Mat gray; cvtColor(srcColor, gray, COLOR_BGR2GRAY); #if DEBUG == 1 imshow("gray", gray); #endif const int MEDIAN_BLUR_FILTER_SIZE = 7; medianBlur(gray, gray, MEDIAN_BLUR_FILTER_SIZE); #if DEBUG == 1 imshow("medianBlur", gray); #endif Mat edges, edges2; Scharr(gray, edges, CV_8U, 1, 0); Scharr(gray, edges2, CV_8U, 0, 1); edges += edges2; #if DEBUG == 1 imshow("edge", edges); #endif Mat mask; const int EVIL_EDGE_THRESHOLD = 12; threshold(edges, mask, EVIL_EDGE_THRESHOLD, 255, THRESH_BINARY_INV); medianBlur(mask, mask, 3); #if DEBUG == 1 imshow("mask", mask); #endif dst.setTo(0); srcColor.copyTo(dst, mask); } void cartoonAlien(InputArray src, OutputArray dst) { Mat srcColor = src.getMat(); Size size = srcColor.size(); Mat faceOutline = Mat::zeros(size, CV_8UC3); Scalar color = CV_RGB(255, 255, 0); // == Scalar(0,255,255) int thickness = 4; int sw = size.width; int sh = size.height; int faceH = sh / 2 * 70 / 100; int faceW = faceH * 72 / 100; ellipse(faceOutline, Point(sw / 2, sh / 2), Size(faceW, faceH), 0, 0, 360, color, thickness, LINE_AA); int eyeW = faceW * 23 / 100; int eyeH = faceH * 11 / 200; int eyeX = faceW * 48 / 100; int eyeY = faceH * 13 / 100; Size eyeSize = Size(eyeW, eyeH); int eyeA = 15; int eyeYshift = 5; ellipse(faceOutline, Point(sw / 2 - eyeX, sh / 2 - eyeY), eyeSize, 0, 180 + eyeA, 360 - eyeA, color, thickness, LINE_AA); ellipse(faceOutline, Point(sw / 2 - eyeX, sh / 2 - eyeY - eyeYshift), eyeSize, 0, 0 + eyeA, 180 - eyeA, color, thickness, LINE_AA); ellipse(faceOutline, Point(sw / 2 + eyeX, sh / 2 - eyeY), eyeSize, 0, 180 + eyeA, 360 - eyeA, color, thickness, LINE_AA); ellipse(faceOutline, Point(sw / 2 + eyeX, sh / 2 - eyeY - eyeYshift), eyeSize, 0, 0 + eyeA, 180 - eyeA, color, thickness, LINE_AA); int mouthY = faceH * 48 / 100; int mouthW = faceW * 45 / 100; int mouthH = faceH * 6 / 100; ellipse(faceOutline, Point(sw / 2, sh / 2 + mouthY), Size(mouthW, mouthH), 0, 0, 180, color, thickness, LINE_AA); int fontFace = FONT_HERSHEY_COMPLEX; float fontScale = 1.0f; int fontThickness = 2; String szMsg = "Put your face here"; putText(faceOutline, szMsg, Point(sw * 23 / 100, sh * 10 / 100), fontFace, fontScale, color, fontThickness, LINE_AA); dst.create(srcColor.size(), srcColor.type()); addWeighted(srcColor, 1.0, faceOutline, 0.7, 0, dst, CV_8UC3); }
[ "tlstjrrud007@naver.com" ]
tlstjrrud007@naver.com
11a1feaeb22f35dfb3a6cc659fc53f0dfa1f4bdd
eab07fff7bf5e6d768160b6e2eccd43b5abc7c8b
/contests/atcoder/arc/122/B.cpp
68d5f1dac3686eaebaf7a6d3ce373e72fbef1e25
[]
no_license
btk15049/com-pro
ce04a6f4a6e1903550e982a5bf0e9faf020b9bb8
a1585aea56017221eb893c4eb736ed573c5c2e2b
refs/heads/master
2023-08-16T05:43:25.881208
2021-09-26T15:31:07
2021-09-26T15:31:07
355,559,908
0
0
null
null
null
null
UTF-8
C++
false
false
27,254
cpp
// https://atcoder.jp/contests/arc122/tasks/arc122_b #define STATIC_MOD 1e9 + 7 #ifdef BTK /*<head>*/ # include "Template.hpp" /*</head>*/ #else /*<body>*/ /* #region auto includes */ /* #region stl */ /*<stl>*/ # include <bits/stdc++.h> # include <sys/types.h> # include <unistd.h> using namespace std; /*</stl>*/ /* #endregion */ /* #region template/Grid.hpp*/ /** * @brief グリッドをラップするための関数 * @tparam T std::string や std;:vector を想定 * @tparam U 周りに配置する要素の型 * @param grid 入力、R > 0 でないとバグる * @param material 周りに配置する要素 * @return std::vector<T> material で 周りを埋めた grid */ template <typename T, typename U> inline std::vector<T> wrapGrid(std::vector<T> grid, U material) { std::vector<T> wrappedGrid(grid.size() + 2, T(grid[0].size() + 2, material)); for (std::size_t i = 0; i < grid.size(); i++) { for (std::size_t j = 0; j < grid[i].size(); j++) { wrappedGrid[i + 1][j + 1] = grid[i][j]; } } return wrappedGrid; } /** * @brief * */ constexpr int dr4[] = {0, 1, 0, -1}; constexpr int dc4[] = {-1, 0, 1, 0}; /* #endregion */ /* #region template/IO.hpp*/ /** * @file IO.hpp * @author btk * @brief cin高速化とか,出力の小数桁固定とか * @version 0.2 * @date 2021-03-01 * * @copyright Copyright (c) 2021 */ /** * @brief 入出力の設定を行うための構造体 */ namespace io { inline void enableFastIO() { std::ios::sync_with_stdio(false); std::cin.tie(0); } inline void setDigits(int digits) { std::cout << std::fixed; std::cout << std::setprecision(digits); } } // namespace io /** * @brief * vectorに直接cin流すためのやつ * @tparam T * @param is * @param v * @return istream& */ template <typename T> std::istream& operator>>(std::istream& is, std::vector<T>& v) { for (auto& it : v) is >> it; return is; } /* #endregion */ /* #region template/IncludeSTL.hpp*/ /** * @file IncludeSTL.hpp * @author btk * @brief 標準ライブラリをincludeするだけ * @version 0.1 * @date 2019-07-21 * @todo 何故か2回includeされる(展開scriptに * @copyright Copyright (c) 2019 * */ /* #endregion */ /* #region template/Loop.hpp*/ /** * @file Loop.hpp * @author btk * @brief rangeとかループ系のクラス * @version 0.1 * @date 2019-07-13 * * @copyright Copyright (c) 2019 * */ /** * @brief * rangeを逆向きに操作したいとき用 * @details * ループの範囲は[bg,ed)なので注意 * @see range */ class reverse_range { private: struct I { int x; int operator*() { return x - 1; } bool operator!=(I& lhs) { return x > lhs.x; } void operator++() { --x; } }; I i, n; public: /** * @brief Construct a new reverse range object * * @param n */ reverse_range(int n) : i({0}), n({n}) {} /** * @brief Construct a new reverse range object * * @param i * @param n */ reverse_range(int i, int n) : i({i}), n({n}) {} /** * @brief * begin iterator * @return I& */ I& begin() { return n; } /** * @brief * end iterator * @return I& */ I& end() { return i; } }; /** * @brief * python みたいな range-based for を実現 * @details * ループの範囲は[bg,ed)なので注意 * !つけると逆向きにループが回る (reverse_range) * 空間計算量はO(1) * 使わない変数ができて警告が出がちなので,unused_varとかを使って警告消しするとよい */ class range { private: struct I { int x; int operator*() { return x; } bool operator!=(I& lhs) { return x < lhs.x; } void operator++() { ++x; } }; I i, n; public: /** * @brief Construct a new range object * * @param n */ range(int n) : i({0}), n({n}) {} /** * @brief Construct a new range object * * @param i * @param n */ range(int i, int n) : i({i}), n({n}) {} /** * @brief * begin iterator * @return I& */ I& begin() { return i; } /** * @brief * end iterator * @return I& */ I& end() { return n; } /** * @brief * 逆向きに参照するrange(reverse_rangeを取得できるs) * @return reverse_range */ reverse_range operator!() { return reverse_range(*i, *n); } }; /* #endregion */ /* #region template/Macro.hpp*/ /** * @file Macro.hpp * @author btk * @brief マクロとか,LLとか * @version 0.1 * @date 2019-07-13 * * @copyright Copyright (c) 2019 * */ /** * @def DEBUG * @brief デバッグ用のif文 提出時はif(0)で実行されない */ /*</head>*/ # ifdef BTK # define DEBUG if (1) # else # define DEBUG if (0) # endif /** * @def ALL(v) * @brief * ALLマクロ */ # define ALL(v) (v).begin(), (v).end() /** * @def REC(ret, ...) * @brief * 再帰ラムダをするためのマクロ */ # define REC(ret, ...) std::function<ret(__VA_ARGS__)> /** * @def VAR_NAME(var) * @brief 変数名を取得する */ # define VAR_NAME(var) # var /** * @brief * rangeで生まれる使わない変数を消す用(警告消し) */ template <typename T> inline T& unused_var(T& v) { return v; } template <typename T> std::vector<T> nestingVector(std::size_t size) { return std::vector<T>(size); } template <typename T, typename... Ts> inline auto nestingVector(std::size_t size, Ts... ts) { return std::vector<decltype(nestingVector<T>(ts...))>( size, nestingVector<T>(ts...)); } /* #endregion */ /* #region template/ChainOperation.hpp*/ /** * @file ChainOperation.hpp * @author btk * @brief パラメータパックを利用した演算子結合を実現 */ /** * @brief テンプレート再帰の末尾 * @tparam F 二項演算 * @tparam T * @param v * @return T */ template <typename F, typename T> inline T chain(T&& v) { return v; } /** * @brief 複数項における演算の結果を返す * @tparam F * @tparam T * @tparam Ts * @param head * @param tail * @return T */ template <typename F, typename T, typename... Ts> inline auto chain(const T head, Ts&&... tail) { return F::exec(head, chain<F>(tail...)); } /** * @brief * 先頭の値をFで参照する関数に基づいて変更できたらする * @tparam F * @tparam T * @tparam Ts * @param target * @param candidates * @return true * @return false */ template <typename F, typename T, typename... Ts> inline bool changeTarget(T& target, Ts&&... candidates) { const T old = target; target = chain<F>(target, candidates...); return old != target; } /* #endregion */ /* #region template/Math.hpp*/ /** * @file Math.hpp * @author btk * @brief 最大値とか最小値を求める */ /** * @brief gcd, ceil等自作算数用関数を集める。stdと被るので名前空間を区切る */ namespace math { /** * @brief 拡張ユークリッド互除法 * @details ax + by = gとなるx,yを求める * @param a 入力 * @param b 入力 * @param x 値引き継ぎ用の変数 * @param y 値引き継ぎ用の変数 * @return int64_t g:aとbの最大公約数 */ int64_t extgcd(int64_t a, int64_t b, int64_t& x, int64_t& y) { int64_t g = a; x = 1; y = 0; if (b != 0) g = extgcd(b, a % b, y, x), y -= (a / b) * x; return g; } /** * @brief 一次不定方程式の解 * @details 値の説明は betouzEquation 関数を参照のこと */ struct BetouzSolution { int64_t x, y, dx, dy; }; /** * @brief 一次不定方程式 * @details a(x + k*dx) + b(y -k*dy) = cとなる x, y, dx, dy を求める。 * @param a 入力 * @param b 入力 * @param c 入力 * @return int64_t 解がないときは nullopt が返る */ std::optional<BetouzSolution> betouzEquation(int64_t a, int64_t b, int64_t c) { BetouzSolution sol; const int64_t g = extgcd(a, b, sol.x, sol.y); if (c % g == 0) { return std::nullopt; } sol.dx = b / g; sol.dy = a / g; sol.x *= c / g; sol.y *= c / g; return sol; } namespace inner { /** * @brief 2項のgcdを求める * @tparam T */ template <typename T> struct GCDFunc { /** * @brief 本体 * @param l * @param r * @return T */ static inline T exec(T l, T r) { while (r != 0) { T u = l % r; l = r; r = u; } return l; } }; /** * @brief 2項のgcdを求める * @tparam T */ template <typename T> struct LCMFunc { /** * @brief 本体 * @param l * @param r * @return T */ static inline T exec(T l, T r) { return (l / GCDFunc<T>::exec(l, r)) * r; } }; } // namespace inner /** * @brief valuesの最大公約数 * @tparam Ts パラメータパック * @param values gcdを求めたい値の集合(2個以上) * @return int64 最大公約数 */ template <typename... Ts> inline int64_t gcd(Ts&&... values) { return chain<inner::GCDFunc<int64_t>>(values...); } /** * @brief valuesの最小公倍数 * @tparam Ts パラメータパック * @param values lcmを求めたい値の集合(2個以上) * @return int64 最小公倍数 */ template <typename... Ts> inline int64_t lcm(Ts&&... values) { return chain<inner::LCMFunc<int64_t>>(values...); } /** * @brief iterator で指定された集合のlcmを求める * @tparam ITR iterator * @param l 開始位置 * @param r 終了位置 * @return int64_t lcm */ template <typename ITR> inline int64_t lcmAll(ITR l, ITR r) { int64_t ret = 1; for (auto it = l; it != r; ++it) { ret = lcm(ret, *it); } return ret; } /** * @brief container (配列など) で指定された要素のlcmを求める * @tparam Container vectorやlist * @param container コンテナ * @return int64_t lcm */ template <typename Container> inline int64_t lcmAll(Container container) { int64_t ret = 1; for (auto e : container) { ret = lcm(ret, e); } return ret; } /** * @brief iterator で指定された集合のgcdを求める * @tparam ITR iterator * @param l 開始位置 * @param r 終了位置 * @return int64_t lcm */ template <typename ITR> inline int64_t gcdAll(ITR l, ITR r) { int64_t ret = 0; for (auto it = l; it != r; ++it) { ret = gcd(ret, *it); } return ret; } /** * @brief container (配列など) で指定された要素のgcdを求める * @tparam Container vectorやlist * @param container コンテナ * @return int64_t gcd */ template <typename Container> inline int64_t gcdAll(Container container) { int64_t ret = 0; for (auto e : container) { ret = gcd(ret, e); } return ret; } /** * @brief u/dを切り上げした整数を求める * @todo 負の数への対応 * @tparam T 整数型 * @param u 入力 * @param d 入力 * @return T 切り上げ後の値 */ template <typename T> inline T ceil(T u, T d) { return (u + d - (T)1) / d; } } // namespace math /** * @brief 2項の最小値求める * @tparam T */ template <typename T> struct minFunc { /** * @brief 本体 * @param l * @param r * @return T */ static T exec(const T l, const T r) { return l < r ? l : r; } }; /** * @brief 2項の最大値求める * * @tparam T */ template <typename T> struct maxFunc { /** * @brief 本体 * * @param l * @param r * @return T */ static T exec(const T l, const T r) { return l > r ? l : r; } }; /** * @brief 複数項の最小値 * @see chain * @tparam T * @tparam Ts * @param head * @param tail * @return T */ template <typename T, typename... Ts> inline T minOf(T head, Ts... tail) { return chain<minFunc<T>>(head, tail...); } /** * @brief 複数項の最大値 * @see chain * @tparam T * @tparam Ts * @param head * @param tail * @return T */ template <typename T, typename... Ts> inline T maxOf(T head, Ts... tail) { return chain<maxFunc<T>>(head, tail...); } /** * @brief change min * @tparam T 型 * @param target 変更する値 * @param candidates * @return 更新があればtrue */ template <typename T, typename... Ts> inline bool chmin(T& target, Ts&&... candidates) { return changeTarget<minFunc<T>>(target, candidates...); } /** * @brief chminのmax版 * @see chmin * @tparam T 型 * @param target 変更する値 * @param candidates * @return 更新があればtrue */ template <typename T, typename... Ts> inline bool chmax(T& target, Ts&&... candidates) { return changeTarget<maxFunc<T>>(target, candidates...); } /* #endregion */ /* #region template/Random.hpp*/ /** * @file Random.hpp * @author btk * @brief 乱数生成系 * @version 0.1 * @date 2019-07-13 * @copyright Copyright (c) 2019 */ //! 乱数のシード値をプロセスIDとして取得 const pid_t pid = getpid(); /** * @brief XorShift32の実装 */ class XorShift32 { private: //! XorShiftの現在の値 unsigned value; /** * @brief XorShift32のアルゴリズムに基づいて value を更新 */ inline void update() { value = value ^ (value << 13); value = value ^ (value >> 17); value = value ^ (value << 5); } /** * @brief 値を更新し,更新前の値を返却 * @return unsigned 呼び出し時の value を用いる */ inline unsigned get() { unsigned v = value; update(); return v; } public: /** * @brief [0, 2^bit) の範囲の乱数値を取り出す * @tparam デフォルトは31 * @return int */ template <int bit = 31> inline int next_int() { return (int)(get() >> (32 - bit)); } /** * @brief [-2^bit,2^bit)の範囲の乱数値を取り出す * @tparam デフォルトは31 * @return int */ template <int bit = 31> inline int next_signed() { unsigned v = get(); return (int)((v >> (31 - bit)) - (1 << (bit))); } /** * @brief next_int呼び出し時の最大値を取得 * @tparam 31 * @return int */ template <int bit = 31> inline int range_max() { return (int)((1u << bit) - 1); }; /** * @brief Construct a new XorShift32 object * @param seed * @details 初期シードをvalueとするXorShift32のインスタンスを生成 */ XorShift32(const unsigned seed) { value = seed; update(); } /** * @brief Construct a new XorShift 32 object * @details 初期シードをプロセスIDとするXorShift32のインスタンスを生成 */ XorShift32() : XorShift32(pid) {} }; /* #endregion */ /* #region template/STLExtension.hpp*/ /** * @file STLExtension.hpp * @brief STL独自拡張 */ namespace ext { /** * @brief std::sortのWrapper関数 * @tparam Container std::vectorやstd::listを想定 * @param container ソートしたいコンテナオブジェクト * @return Container& * ソート後のコンテナオブジェクト==引数に渡したオブジェクト */ template <typename Container> inline Container& sort(Container& container) { sort(std::begin(container), std::end(container)); return container; } /** * @brief std::sortのWrapper関数 * @tparam Container std::vectorやstd::listを想定 * @tparam Comparator 比較関数の型 * @param container ソートしたいコンテナオブジェクト * @param comparator 比較関数 * @return Container& * ソート後のコンテナオブジェクト==引数に渡したオブジェクト */ template <typename Container, typename Comparator> inline Container& sort(Container& container, Comparator comparator) { sort(std::begin(container), std::end(container), comparator); return container; } /** * @brief std::reverseのWrapper関数 * @tparam Container std::vectorやstd::listを想定 * @param container 反転したいコンテナオブジェクト * @return Container& * 反転後のコンテナオブジェクト==引数に渡したオブジェクト */ template <typename Container> inline Container& reverse(Container& container) { reverse(std::begin(container), std::end(container)); return container; } /** * @brief std::accumulateのvector限定Wrapper関数 * @tparam T 配列の要素の型 * @tparam U 戻り値の型 * @param container 配列 * @param zero 初期値 * @return U 総和 */ template <typename T, typename U> inline U accumulate(const std::vector<T>& container, U zero) { return std::accumulate(std::begin(container), std::end(container), zero); } /** * @brief std::accumulateのvector限定Wrapper関数の、引数省略版 * @tparam T 配列の要素の型 && 戻り値の型 * @param container 配列 * @return T 総和 overflowに注意 */ template <typename T> inline T accumulate(const std::vector<T>& container) { return accumulate(container, T(0)); } /** * @brief std::countのWrapper関数 * @tparam Container std::vectorやstd::listを想定 * @tparam T 数える値の型 * @param container コンテナオブジェクト * @param value 数える値 * @return int */ template <typename Container, typename T> inline int count(Container& container, T value) { return std::count(std::begin(container), std::end(container), value); } /** * @brief 等差数列のvectorを作る関数 * @param n 要素数 * @param startFrom 初項 * @param step 公差 * @return std::vector<int> 等差数列 */ inline std::vector<int> iota(int n, int startFrom = 0, int step = 1) { std::vector<int> container(n); int v = startFrom; for (int i = 0; i < n; i++, v += step) { container[i] = v; } return container; } /** * @brief * (*max_element) のwrapper、位置は返さない * @tparam ITR iterator * @param l iteratorの最初 * @param r iteratorの終了位置 * @param defaultValue 要素がないときのデフォルト値 * @return auto 最大値、型はコンテナ内の型 */ template <typename ITR> inline auto maxIn(ITR l, ITR r, std::remove_reference_t<decltype(*l)> defaultValue = 0) { if (r == l) { return defaultValue; } return *std::max_element(l, r); } /** * @brief maxIn の vector 限定版 * @tparam T 戻り値の型 * @param containter 最大値求める対象のコンテナ * @param defaultValue コンテナの要素がない場合の初期値 * @return T 最大値、コンテナ似要素がない場合はdefaultValue */ template <typename T> inline T maxIn(std::vector<T> container, T defaultValue = 0) { return maxIn(container.begin(), container.end(), defaultValue); } /** * @brief * (*min_element) のwrapper、位置は返さない * @tparam ITR iterator * @param l iteratorの最初 * @param r iteratorの終了位置 * @param defaultValue 要素がないときのデフォルト値 * @return auto 最小値、型はコンテナ内の型 */ template <typename ITR> inline auto minIn(ITR l, ITR r, std::remove_reference_t<decltype(*l)> defaultValue = 0) { if (r == l) { return defaultValue; } return *std::min_element(l, r); } /** * @brief minIn の vector 限定版 * @tparam T 戻り値の型 * @param containter 最大値求める対象のコンテナ * @param defaultValue コンテナの要素がない場合の初期値 * @return T 最小値、コンテナ似要素がない場合はdefaultValue */ template <typename T> inline T minIn(std::vector<T> container, T defaultValue = 0) { return minIn(container.begin(), container.end(), defaultValue); } } // namespace ext /* #endregion */ /* #region template/Strings.hpp*/ /** * @file Strings.hpp * @author btk * @brief 文字列を扱いやすくするライブラリ */ /** * @brief コレクションを文字列に変換する関数 * @tparam T コレクションの型、range-based for に対応している必要あり * @tparam DelimiterType 区切り文字の型 * @param v コレクション * @param delimiter 区切り文字 * @return std::string delimiterで結合された文字列 */ template <typename T, typename DelimiterType> std::string join(const T& v, const DelimiterType& delimiter) { std::stringstream ss; bool isFirst = true; for (auto& it : v) { if (!isFirst) { ss << delimiter; } isFirst = false; ss << it; } return ss.str(); } /** * @brief コレクションを文字列に変換する関数(イテレータ版) * @tparam ITR イテレータ型 * @tparam DelimiterType 区切り文字の型 * @param bg 開始 * @param ed 終了 * @param delimiter 区切り文字 * @return std::string delimiterで結合された文字列 */ template <typename ITR, typename DelimiterType> std::string join(const ITR bg, const ITR ed, const DelimiterType& delimiter) { std::stringstream ss; bool isFirst = true; for (auto it = bg; it != ed; ++it) { if (!isFirst) { ss << delimiter; } isFirst = false; ss << *it; } return ss.str(); } /** * @brief Strings.hppの内部関数 */ namespace strings { /** * @brief std::size_tをWrapする構造体 * @tparam i 本体 */ template <std::size_t i> struct IndexWrapper {}; /** * @brief tuple用のjoin関数の内部で使われるテンプレート構造体(関数) * @tparam CurrentIndex 現在のindex * @tparam LastIndex 最後のindex * @tparam DelimiterType 区切り文字 * @tparam Ts tupleに使用するパラメータパック */ template <typename CurrentIndex, typename LastIndex, typename DelimiterType, typename... Ts> struct JoinFunc; /** * @brief tuple用join関数の再帰末尾用構造体 .joinが本体 * @tparam i 現在のid = tupleの最後の要素のid * @tparam DelimiterType 区切り文字 * @tparam Ts tupleに使用するパラメータパック */ template <std::size_t i, typename DelimiterType, typename... Ts> struct JoinFunc<IndexWrapper<i>, IndexWrapper<i>, DelimiterType, Ts...> { /** * @brief tuple用join関数の末尾再帰 * @param ss stringstream * @param values 文字列化したいtuple * @param delimiter 区切り文字 * @return std::stringstream& 引数で渡したもの */ static std::stringstream& join(std::stringstream& ss, const std::tuple<Ts...>& values, const DelimiterType& delimiter) { unused_var(delimiter); ss << std::get<i>(values); return ss; } }; /** * @brief tuple用join関数の内部構造体 * @tparam i 現在のid * @tparam j tupleの最後の要素のid * @tparam DelimiterType 区切り文字 * @tparam Ts パラメータパック */ template <std::size_t i, std::size_t j, typename DelimiterType, typename... Ts> struct JoinFunc<IndexWrapper<i>, IndexWrapper<j>, DelimiterType, Ts...> { /** * @brief tuple用join関数の本体 * @param ss stringstream * @param values 文字列化したいtuple * @param delimiter 区切り文字 * @return std::stringstream& 引数で渡したもの */ static std::stringstream& join(std::stringstream& ss, const std::tuple<Ts...>& values, const DelimiterType& delimiter) { ss << std::get<i>(values); ss << delimiter; return JoinFunc<IndexWrapper<i + 1>, IndexWrapper<j>, DelimiterType, Ts...>::join(ss, values, delimiter); } }; } // namespace strings /** * @brief 複数の値をjoinする関数 * @tparam DelimiterType 区切り文字の型 * @tparam Ts パラメータパック * @param values 文字列として結合したいタプル * @param delimiter 区切り文字 * @return std::string 結合後の文字列 */ template <typename DelimiterType, typename... Ts> std::string join(const std::tuple<Ts...>& values, const DelimiterType& delimiter) { std::stringstream ss; constexpr std::size_t lastIndex = std::tuple_size<std::tuple<Ts...>>::value - 1u; return strings::JoinFunc<strings::IndexWrapper<0>, strings::IndexWrapper<lastIndex>, DelimiterType, Ts...>::join(ss, values, delimiter) .str(); } /* #endregion */ /* #region Template.hpp*/ /** * @file Template.hpp * @brief 競技プログラミング用テンプレート * @author btk15049 * @date 2019/05/02 */ /* #endregion */ /* #endregion */ /*</body>*/ #endif struct cww { cww() { io::enableFastIO(); io::setDigits(10); } } star; int N; double A[112345]; double AS[112345]; int main() { /* write here */ cin >> N; for (int i : range(N)) cin >> A[i]; sort(A, A + N); AS[0] = 0; for (int i : range(N)) { AS[i + 1] = AS[i] + A[i]; } double ret = AS[N]; for (int i : range(N)) { const double x = A[i] / 2; const double lower = x * i; const double upper = AS[N] - AS[i] - x * (N - i); chmin(ret, lower + upper); } cout << ret / N << endl; return 0; }
[ "btk15049@live.jp" ]
btk15049@live.jp
e81deb1f33c5ba58cc1409eed883e8756e1040a8
214951a4b94cd13aa2bf181ed00eb1be308e36d2
/sources/library/solvers/072.cpp
115ba62220f0598f90b19f002e739d0b6de6690b
[]
no_license
gcross/CodeQuest
a467d3443e09d1d239cea0719529cb91f8c1f7d5
adbe674dcdf0415070835c47f9820604757e647c
refs/heads/master
2021-01-22T07:10:44.022991
2012-02-01T00:12:49
2012-02-01T00:12:49
210,991
1
0
null
null
null
null
UTF-8
C++
false
false
250
cpp
#include <boost/function.hpp> #include "codequest.hpp" namespace CodeQuest { using boost::function; typedef function<code (const dynamic_operator_vector&,bool)> solver; solver solver_072 = solveForFixedSize<dynamic_operator_vector,72>; }
[ "gcross@phys.washington.edu" ]
gcross@phys.washington.edu
604aa74064fce44029b9e1a9d2982c8392aaadd4
bff9ee7f0b96ac71e609a50c4b81375768541aab
/src/platform/user_pagefault/user_pagefault.hpp
4c51a8ce4c15a24de5d71694f891a38c2f4561c9
[ "BSD-3-Clause" ]
permissive
rohitativy/turicreate
d7850f848b7ccac80e57e8042dafefc8b949b12b
1c31ee2d008a1e9eba029bafef6036151510f1ec
refs/heads/master
2020-03-10T02:38:23.052555
2018-04-11T02:20:16
2018-04-11T02:20:16
129,141,488
1
0
BSD-3-Clause
2018-04-11T19:06:32
2018-04-11T19:06:31
null
UTF-8
C++
false
false
10,261
hpp
/* Copyright © 2017 Apple Inc. All rights reserved. * * Use of this source code is governed by a BSD-3-clause license that can * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause */ #ifndef TURI_USER_PAGEFAULT_H_ #define TURI_USER_PAGEFAULT_H_ #include <cstdint> #include <cstddef> #include <functional> #include <fstream> #include <util/dense_bitset.hpp> #include <parallel/pthread_tools.hpp> namespace turi { /** * \defgroup pagefault User Mode Page Fault Handler */ /** * \ingroup pagefault * \{ */ /** * This implements a user mode page fault handler. * * The basic mechanics of operation are not very complicated. * We first install a segfault_handler. * * When you ask for some memory, we use mmap to allocate a region, but set * memory protection on it to PROT_NONE (disable both read and writes to the * region). This way, every memory access to the region will trigger a segfault. * * When the memory is accessed, the segfault handler (segv_handler()) is * triggered, and try to fill in the data in the page. * To do so, (fill_pages()) we set the protection on the page to * PROT_READ | PROT_WRITE (enable read + write), call a callback function to * fill in the data, then sets the protection on the page to PROT_READ. Then we * return from the segfault handler which allows the program to resume * execution correctly (but cannot write to the memory, only read). * * We keep a queue of pages we have committed (add_to_access_queue()). and when * the queue size becomes too large, we start evicting/decommitting pages * (handle_eviction()). Essentially we are doing FIFO caching. To "evict" * a set of pages simply involves calling madvise(MADV_DONTNEED) on the pages. * * A bunch of additional maintenance stuff are needed: * - a queue of committed pages (used to manage eviction) * - The set of all regions (page_sets) allocated, sorted by address * to permit fast binary searches). this is used to figure out the mapping * between address and callback. * * One key design consideration is the careful use of mmap. The way the * procedure is defined above only calls mmap once for the entire region. * decommitting and committing memory is done by use of memory protection * and madvise. Alternate implementation built entirely around mmap is possible * where we use completely unallocated memory addresses, and use mmap to map * the pages in as required. But this requires a large number of calls to mmap, * which uses up a lot of kernel datastructures, which will cause mmap to fail * with ENOMEM after a while. * * Also, with regards to parallelism, the kernel API does not quite provide * sufficient capability to handle parallel accesses correctly. What is missing * is an atomic "fill and enable page read/write" function. Essentially, while * the callback function is filling in the pages for a particular memory address, * some other thread can read from the same memory addresses and get erroneous * values. mremap could in theory be used to enable this by having the callback * fill to alternate pages, and using mremap to atomically swap those pages in. * However, see the design consideration above regarding excessive use of mmap. * Also, mremap is not available on OS X. */ namespace user_pagefault { struct userpf_page_set; /** * Page filling callback */ typedef std::function<size_t (userpf_page_set* pageset, char* address, size_t fill_length)> userpf_handler_callback; /** * Page release callback */ struct userpf_page_set; typedef std::function<size_t (userpf_page_set* pageset)> userpf_release_callback; /** * The structure used to maintain all the metadata about the pagefault handler. */ struct userpf_page_set { char* begin = nullptr; ///< The start of the managed address char* end = nullptr; ///< The end of the manged address size_t length = 0; ///< end - start /** * The number of "pages". Each pagefault will trigger the fill of one * "page". The size of the page is predefined at compile time. * \ref PAGE_SIZE. */ size_t num_large_pages = 0; bool writable = false; /** * Internal datastructures. Should not touch. */ /// one lock for each page to handle at least, a limited amount of parallelism std::vector<simple_spinlock> locks; /// one bit for each page that is resident (has physical pages associated) dense_bitset resident; /// one bit for each page that is dirty (written to but not flushed) dense_bitset dirty; /** * one bit for each page that is maintained by the pagefault handler's * pagefile instead of using the callback. Basically these pages * are pages which have been written to, and then evicted. */ dense_bitset pagefile_maintained; /** * the callback handler which is called to fill in new page */ userpf_handler_callback fill_callback; /** * the callback handler which is called when the memory is freed. * (this allows an external procedure to potentially persist the data) * This must be reentrant with the filling callback handler since the release * callback may read the entire memory region (which required filling) */ userpf_release_callback release_callback; /** * pagefile_allocation[i] is the handle to the pagefile storing the disk * backed memory. (size_t)(-1) if not allocated. */ std::vector<size_t> pagefile_allocations; }; /** * The page size we operate at. see user_pagefault.cpp for the actual value. * generally, we want to avoid working at the granularity of single system * pages. While that is going to be faster for random access, that will trigger * a very large number of segfaults and will also require quite a lot of kernel * datastructures. */ extern const size_t TURI_PAGE_SIZE; /** * Initializes the on-demand paging handlers. * * \ref max_resident_memory The maximum amount of resident memory to be used * before memory is decommited. If not provided (-1), the environment variable * TURI_DEFAULT_PAGEFAULT_RESIDENT_LIMIT is read. If not available a * default value corresponding to half of total memory size is used. * * Returns true if the pagefault handler was installed successfully, * and false otherwise. */ bool setup_pagefault_handler(size_t max_resident_memory = (size_t)(-1)); /** * Returns true if the pagefault handler is installed */ bool is_pagefault_handler_installed(); /** * Returns the maximum amount of resident memory to be used before memory * is decommitted. \see setup_pagefault_handler */ size_t get_max_resident(); /** * Sets the maximum amount of resident memory to be used before memory * is decommitted. \see setup_pagefault_handler */ void set_max_resident(size_t max_resident_memory); /** * Allocates a block of memory of a certain length, where the contents of * the memory are to be filled using the specified callback function. * * Returns a page_set pointer where page_set->begin is the memory address * at which on-demand paging will be performed. The callback is triggered * to fill in the pages on demand. * * The pagefault handler is an std::function object of the form: * \code * size_t fill_callback(userpf_page_set* ps, * char* address, * size_t fill_length) { * // MUST fill in the contents of address to address + fill_length * // most not write out of the bounds of [address, address+fill_length) * // for instance, to fill in the array such that * // arr = (size_t*)(ps->begin) * // arr[i] == i * // we do the following: * * size_t* root = (size_t*) ps->begin; * size_t* s_addr = (size_t*) page_address; * * size_t begin_value = s_addr - root; * size_t num_to_fill = minimum_fill_length / sizeof(size_t); * * for (size_t i = 0; i < num_to_fill; ++i) { * s_addr[i] = i + begin_value; * } * } * \endcode * * The release_callback is an std::function object of the form: * \code * size_t release_callback(userpf_page_set* ps) { * // for instance, we may write out the contents of * // ps->begin to ps->end to disk here. * } * \endcode * The release_callback function *must* be reentrant with the fill_callback * function. This is because memory accesses performed by release_callback into * to the pointer may trigger the fill_callback to fill in the memory regions. * * If writable is set (default false), the user_pagefault handler will perform * automatic read/write/eviction. * * \param length The number of bytes to allocate * \param fill_callback The callback to be triggered when a page range needs * to be filled. * \param release_callback The callback to be triggered the the memory is * released, i.e. release(pf) is called. * \param writable If the page range is to be writable. The pagefault handler * will handle paging. * The returned object MUST NOT be freed or deallocated. use \ref release. */ userpf_page_set* allocate(size_t length, userpf_handler_callback fill_callback, userpf_release_callback release_callback = nullptr, bool writable = true); /** * Releases the pageset. The caller must ensure that there are no other * memory accesses for this allocation. */ void release(userpf_page_set* pageset); /** * Disables the on-demand paging handlers. * * Releases the pagefault handler, reverting it to the previous handler if any. * Returns true if the pagefault handler was disabled successfully, * false otherwise. */ bool revert_pagefault_handler(); /** * Returns the number of allocations made */ size_t get_num_allocations(); /** * Retursn the total number of bytes allocated to the pagefile */ size_t pagefile_total_allocated_bytes(); /** * Returns the total number of bytes actually stored in the pagefile * (after compression and stuff) */ size_t pagefile_total_stored_bytes(); /** * Returns the total number of bytes stored compressed. */ double pagefile_compression_ratio(); } // user_pagefault /// \} } // turicreate #endif
[ "znation@apple.com" ]
znation@apple.com
db4823d968e5e21ee35db1a1b9d186baf259467a
ae66db103d69be5330a5a564543c427eecde50f8
/ShaderTutors/37_CelShading/main.cpp
68c4a6b2bc9c14e7f5410e9147a86f0654cf69af
[ "BSD-3-Clause" ]
permissive
asylum2010/Asylum_Tutorials
7ccdc9818f9b6efeb2cfbcd9268973630fd1f5f1
5bd0509be2280a575ddd234acd8dfe53a7033c1b
refs/heads/master
2022-11-14T01:37:25.698706
2022-11-12T18:22:36
2022-11-12T18:22:36
8,253,900
231
53
null
null
null
null
UTF-8
C++
false
false
11,213
cpp
#pragma comment(lib, "d3d9.lib") #pragma comment(lib, "d3dx9.lib") #pragma comment(lib, "winmm.lib") #pragma comment(lib, "gdiplus.lib") #include "..\Common\application.h" #include "..\Common\dx9ext.h" #include "..\Common\3Dmath.h" // helper macros #define TITLE "Shader sample 37: Cel shading" #define MYERROR(x) { std::cout << "* Error: " << x << "!\n"; } #define SAFE_RELEASE(x) { if ((x)) { (x)->Release(); (x) = NULL; } } #define CLIP_NEAR 0.5f #define CLIP_FAR 3.0f // sample variables Application* app = nullptr; LPDIRECT3DDEVICE9 device = nullptr; LPDIRECT3DTEXTURE9 colortarget = nullptr; LPDIRECT3DTEXTURE9 normaltarget = nullptr; LPDIRECT3DTEXTURE9 edgetarget = nullptr; LPDIRECT3DTEXTURE9 intensity = nullptr; LPDIRECT3DTEXTURE9 helptext = nullptr; LPDIRECT3DSURFACE9 colorsurface = nullptr; LPDIRECT3DSURFACE9 normalsurface = nullptr; LPDIRECT3DSURFACE9 edgesurface = nullptr; LPD3DXMESH teapot = nullptr; LPD3DXMESH knot = nullptr; LPD3DXMESH mesh = nullptr; LPD3DXEFFECT screenquad = nullptr; LPD3DXEFFECT celshading = nullptr; D3DXVECTOR3 eye(0.5f, 0.5f, -1.5f); D3DXMATRIX world, view, proj; bool stencilcountours = false; bool InitScene() { uint32_t screenwidth = app->GetClientWidth(); uint32_t screenheight = app->GetClientHeight(); if (FAILED(D3DXLoadMeshFromX("../../Media/MeshesDX/teapot.x", D3DXMESH_MANAGED, device, NULL, NULL, NULL, NULL, &teapot))) return false; if (FAILED(D3DXLoadMeshFromX("../../Media/MeshesDX/knot.x", D3DXMESH_MANAGED, device, NULL, NULL, NULL, NULL, &knot))) return false; if (FAILED(DXCreateEffect(device, "../../Media/ShadersDX/celshading.fx", &celshading))) return false; if (FAILED(DXCreateEffect(device, "../../Media/ShadersDX/screenquad.fx", &screenquad))) return false; if (FAILED(DXRenderTextEx(device, "0 - Change object\n1 - Sobel Filter\n2 - Stencil countours", 512, 512, L"Arial", 1, Gdiplus::FontStyleBold, 25, &helptext))) return false; // create render targets if (FAILED(device->CreateTexture(screenwidth, screenheight, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &colortarget, NULL))) return false; if (FAILED(device->CreateTexture(screenwidth, screenheight, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &normaltarget, NULL))) return false; if (FAILED(device->CreateTexture(screenwidth, screenheight, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &edgetarget, NULL))) return false; colortarget->GetSurfaceLevel(0, &colorsurface); normaltarget->GetSurfaceLevel(0, &normalsurface); edgetarget->GetSurfaceLevel(0, &edgesurface); // create intensity ramp if (FAILED(device->CreateTexture(8, 1, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, &intensity, NULL))) return false; D3DLOCKED_RECT rect; intensity->LockRect(0, &rect, NULL, 0); { uint32_t* data = (uint32_t*)rect.pBits; data[0] = 0xff7f7f7f; data[1] = 0xff7f7f7f; data[2] = 0xff7f7f7f; data[3] = 0xffafafaf; data[4] = 0xffafafaf; data[5] = 0xffffffff; data[6] = 0xffffffff; data[7] = 0xffffffff; } intensity->UnlockRect(0); D3DXVECTOR3 look(0, 0, 0); D3DXVECTOR3 up(0, 1, 0); D3DXMatrixPerspectiveFovLH(&proj, D3DX_PI / 3, (float)screenwidth / (float)screenheight, CLIP_NEAR, CLIP_FAR); D3DXMatrixLookAtLH(&view, &eye, &look, &up); mesh = knot; return true; } void UninitScene() { SAFE_RELEASE(colorsurface); SAFE_RELEASE(normalsurface); SAFE_RELEASE(edgesurface); SAFE_RELEASE(colortarget); SAFE_RELEASE(normaltarget); SAFE_RELEASE(edgetarget); SAFE_RELEASE(intensity); SAFE_RELEASE(helptext); SAFE_RELEASE(teapot); SAFE_RELEASE(knot); SAFE_RELEASE(screenquad); SAFE_RELEASE(celshading); } void KeyUp(KeyCode key) { switch (key) { case KeyCode0: mesh = ((mesh == knot) ? teapot : knot); break; case KeyCode1: stencilcountours = false; break; case KeyCode2: stencilcountours = true; break; default: break; } } void Render(float alpha, float elapsedtime) { static float time = 0; D3DXMATRIX worldinv; D3DXMATRIX viewproj; D3DXVECTOR3 axis(0, 1, 0); D3DXVECTOR4 texelsize(1.0f / (float)app->GetClientWidth(), 1.0f / (float)app->GetClientHeight(), 0, 1); D3DXVECTOR4 clipplanes(CLIP_NEAR, CLIP_FAR, 0, 0); Math::Color color; time += elapsedtime; if (mesh == knot) { D3DXMatrixScaling(&world, 0.3f, 0.3f, 0.3f); color = Math::Color::sRGBToLinear(0xff77ff70); } else { D3DXMatrixScaling(&world, 0.6f, 0.6f, 0.6f); color = Math::Color::sRGBToLinear(0xffff7700); } D3DXMatrixRotationAxis(&worldinv, &axis, time); D3DXMatrixMultiply(&world, &world, &worldinv); D3DXMatrixInverse(&worldinv, nullptr, &world); D3DXMatrixMultiply(&viewproj, &view, &proj); celshading->SetMatrix("matWorld", &world); celshading->SetMatrix("matWorldInv", &worldinv); celshading->SetMatrix("matViewProj", &viewproj); celshading->SetVector("baseColor", (D3DXVECTOR4*)&color); celshading->SetVector("texelSize", &texelsize); celshading->SetVector("clipPlanes", &clipplanes); LPDIRECT3DSURFACE9 backbuffer = nullptr; if (SUCCEEDED(device->BeginScene())) { D3DVIEWPORT9 oldviewport; D3DVIEWPORT9 viewport; device->GetViewport(&oldviewport); // render scene + normals/depth celshading->SetTechnique("celshading"); if (!stencilcountours) { device->GetRenderTarget(0, &backbuffer); device->SetRenderTarget(0, colorsurface); device->SetRenderTarget(1, normalsurface); } device->SetRenderState(D3DRS_SRGBWRITEENABLE, TRUE); device->Clear(0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, Math::Color::sRGBToLinear(0xff6694ed), 1.0f, 0); device->SetSamplerState(0, D3DSAMP_SRGBTEXTURE, TRUE); device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT); device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_POINT); device->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_NONE); celshading->Begin(NULL, 0); celshading->BeginPass(0); { device->SetTexture(0, intensity); mesh->DrawSubset(0); } celshading->EndPass(); celshading->End(); if (!stencilcountours) { // detect edges celshading->SetTechnique("edgedetect"); device->SetRenderTarget(0, edgesurface); device->SetRenderTarget(1, nullptr); device->Clear(0, NULL, D3DCLEAR_TARGET, 0xffffffff, 1.0f, 0); device->SetRenderState(D3DRS_ZENABLE, FALSE); device->SetRenderState(D3DRS_SRGBWRITEENABLE, FALSE); device->SetFVF(D3DFVF_XYZW|D3DFVF_TEX1); celshading->Begin(NULL, 0); celshading->BeginPass(0); { device->SetTexture(0, normaltarget); device->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, DXScreenQuadVertices, 6 * sizeof(float)); } celshading->EndPass(); celshading->End(); // compose celshading->SetTechnique("compose"); device->SetRenderTarget(0, backbuffer); device->SetRenderState(D3DRS_SRGBWRITEENABLE, TRUE); device->Clear(0, NULL, D3DCLEAR_TARGET, Math::Color::sRGBToLinear(0xff6694ed), 1.0f, 0); backbuffer->Release(); device->SetSamplerState(1, D3DSAMP_MINFILTER, D3DTEXF_POINT); device->SetSamplerState(1, D3DSAMP_MAGFILTER, D3DTEXF_POINT); device->SetSamplerState(1, D3DSAMP_MIPFILTER, D3DTEXF_NONE); celshading->Begin(NULL, 0); celshading->BeginPass(0); { device->SetTexture(0, colortarget); device->SetTexture(1, edgetarget); device->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, DXScreenQuadVertices, 6 * sizeof(float)); } celshading->EndPass(); celshading->End(); } else { D3DXMATRIX offproj; // use the stencil buffer device->SetRenderState(D3DRS_COLORWRITEENABLE, 0); device->SetRenderState(D3DRS_ZWRITEENABLE, FALSE); device->SetRenderState(D3DRS_STENCILENABLE, TRUE); device->SetRenderState(D3DRS_ZENABLE, FALSE); device->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_ALWAYS); device->SetRenderState(D3DRS_STENCILREF, 1); device->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_REPLACE); device->SetTransform(D3DTS_WORLD, &world); device->SetTransform(D3DTS_VIEW, &view); float thickness = 3.5f; // render object 4 times with offseted frusta for (float i = -thickness; i < thickness + 1; i += 2 * thickness) { for (float j = -thickness; j < thickness + 1; j += 2 * thickness) { D3DXMatrixTranslation(&offproj, i / (float)app->GetClientWidth(), j / (float)app->GetClientHeight(), 0); D3DXMatrixMultiply(&offproj, &proj, &offproj); device->SetTransform(D3DTS_PROJECTION, &offproj); mesh->DrawSubset(0); } } // erase area in the center device->SetRenderState(D3DRS_STENCILREF, 0); device->SetTransform(D3DTS_PROJECTION, &proj); mesh->DrawSubset(0); // now render outlines device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_RED|D3DCOLORWRITEENABLE_GREEN|D3DCOLORWRITEENABLE_BLUE|D3DCOLORWRITEENABLE_ALPHA); device->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_NOTEQUAL); device->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_KEEP); device->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_KEEP); device->SetFVF(D3DFVF_XYZRHW|D3DFVF_TEX1); DXScreenQuadVerticesFFP[6] = DXScreenQuadVerticesFFP[18] = (float)app->GetClientWidth() - 0.5f; DXScreenQuadVerticesFFP[13] = DXScreenQuadVerticesFFP[19] = (float)app->GetClientHeight() - 0.5f; device->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1); device->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_CONSTANT); device->SetTextureStageState(0, D3DTSS_CONSTANT, 0); { device->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, DXScreenQuadVerticesFFP, 6 * sizeof(float)); } device->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE); device->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE); device->SetRenderState(D3DRS_ZENABLE, TRUE); device->SetRenderState(D3DRS_ZWRITEENABLE, TRUE); device->SetRenderState(D3DRS_STENCILENABLE, FALSE); } // render text viewport = oldviewport; viewport.Width = 512; viewport.Height = 512; viewport.X = viewport.Y = 10; device->SetViewport(&viewport); device->SetTexture(0, helptext); device->SetRenderState(D3DRS_ZENABLE, FALSE); device->SetRenderState(D3DRS_SRGBWRITEENABLE, FALSE); device->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); device->SetFVF(D3DFVF_XYZW|D3DFVF_TEX1); screenquad->Begin(NULL, 0); screenquad->BeginPass(0); { device->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, DXScreenQuadVertices, 6 * sizeof(float)); } screenquad->EndPass(); screenquad->End(); // reset states device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE); device->SetRenderState(D3DRS_ZENABLE, TRUE); device->SetViewport(&oldviewport); device->EndScene(); } device->Present(NULL, NULL, NULL, NULL); } int main(int argc, char* argv[]) { app = Application::Create(1360, 768); app->SetTitle(TITLE); if (!app->InitializeDriverInterface(GraphicsAPIDirect3D9)) { delete app; return 1; } device = (LPDIRECT3DDEVICE9)app->GetLogicalDevice(); app->InitSceneCallback = InitScene; app->UninitSceneCallback = UninitScene; app->RenderCallback = Render; app->KeyUpCallback = KeyUp; app->Run(); delete app; return 0; }
[ "darthasylum@gmail.com" ]
darthasylum@gmail.com
bbf1ebcc6fa794095e1701031050f0f5b75be9aa
31589435071cbff4c5e95b357d8f3fa258f43269
/PPTVForWin8/ppbox_1.2.0/src/p2p/server_mod/supernode/UdpServer/RequestParser.cpp
7e3ae766e30cac0bb05b4c953f3d698b338fa325
[]
no_license
huangyt/MyProjects
8d94656f41f6fac9ae30f089230f7c4bfb5448ac
cd17f4b0092d19bc752d949737c6ed3a3ef00a86
refs/heads/master
2021-01-17T20:19:35.691882
2013-05-03T07:19:31
2013-05-03T07:19:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,237
cpp
//------------------------------------------------------------------------------------------ // Copyright (c)2005-2010 PPLive Corporation. All rights reserved. //------------------------------------------------------------------------------------------ #include "Common.h" #include "protocol/Protocol.h" #include "RequestParser.h" namespace super_node { const size_t RequestParser::PeerBlockSize = 2 * 1024 * 1024; void RequestParser::ParseFromPeerToSN(const protocol::RequestSubPiecePacketFromSN & packet, std::map<boost::uint16_t, std::set<boost::uint16_t> > & request_in_sn_type) { for (boost::uint16_t i = 0; i < packet.subpiece_infos_.size(); ++i) { size_t offset_in_resource = packet.subpiece_infos_[i].block_index_ * PeerBlockSize + packet.subpiece_infos_[i].subpiece_index_ * SUB_PIECE_SIZE; boost::uint16_t block_index = offset_in_resource / BlockData::MaxBlockSize; boost::uint16_t subpiece_index = static_cast<boost::uint16_t>((offset_in_resource % BlockData::MaxBlockSize) / SUB_PIECE_SIZE); if (request_in_sn_type.find(block_index) == request_in_sn_type.end()) { std::set<boost::uint16_t> subpiece_indexs; subpiece_indexs.insert(subpiece_index); request_in_sn_type.insert(std::make_pair(block_index, subpiece_indexs)); } else { if (request_in_sn_type[block_index].find(subpiece_index) == request_in_sn_type[block_index].end()) { request_in_sn_type[block_index].insert(subpiece_index); } } } } protocol::SubPieceInfo RequestParser::ParseFromSNToPeer(boost::uint16_t block_index, boost::uint16_t subpiece_index) { size_t offset_in_resource = block_index * BlockData::MaxBlockSize + subpiece_index * SUB_PIECE_SIZE; boost::uint16_t peer_block_index = offset_in_resource / PeerBlockSize; boost::uint16_t peer_subpiece_index = static_cast<boost::uint16_t>((offset_in_resource % PeerBlockSize) / SUB_PIECE_SIZE); return protocol::SubPieceInfo(peer_block_index, peer_subpiece_index); } }
[ "penneryu@outlook.com" ]
penneryu@outlook.com
2097f58821801ed3b2b0edc0e1943df121b72410
d1f4bc93fcf1e21517f112ebacb9fb2f20fa4c0f
/src/data_structure.cpp
e265ceaf63e3e2a65f42560e5aeb4551539ee0b7
[]
no_license
MatthewNielsen27/english-lang
364ee6a5499d72e4eefe6a395588e7d87353a855
486278c4a19812e04507743b4a4c54a6c9b13992
refs/heads/master
2020-03-09T08:23:06.086937
2018-05-01T17:54:11
2018-05-01T17:54:11
128,687,762
1
1
null
2018-05-01T17:54:12
2018-04-08T22:40:57
C++
UTF-8
C++
false
false
3,364
cpp
#include "../include/data_structure.hpp" #include <regex> std::string __to_type(std::string incoming){ if(incoming == "string"){ return "std::string"; }else if(incoming == "integer-list"){ return "int * "; }else if(incoming == "integer"){ return "int"; }else if(incoming == "decimal"){ return "float"; }else if(incoming == "nothing"){ return "void"; }else{ return incoming; } } bool StructureStatement::is_valid(std::string line){ return true; } std::string StructureStatement::parse(std::string line){ line = std::regex_replace(line, std::regex("^ +| +$|( ) +"), "$1"); return line.substr(10); } bool StructureStatement::write(std::string name, std::ofstream& outfile){ outfile << "struct " << name << "{\n"; return true; } bool ClassStructureStatement::is_valid(std::string line){ return true; } std::string ClassStructureStatement::parse(std::string line){ line = std::regex_replace(line, std::regex("^ +| +$|( ) +"), "$1"); return line.substr(16); } bool ClassStructureStatement::write(std::string name, std::ofstream& outfile){ outfile << "class " << name << "{\n"; return true; } bool PrivacyStatement::is_valid(std::string line){ return (line.find("public") != std::string::npos || line.find("private") != std::string::npos); } std::string PrivacyStatement::parse(std::string line){ line = std::regex_replace(line, std::regex("^ +| +$|( ) +"), "$1"); return line.substr(16); } bool PrivacyStatement::write(std::string name, std::ofstream& outfile){ outfile << name << ":\n"; return true; } bool EndStructureStatement::is_valid(std::string line){ return true; } bool EndStructureStatement::write(std::ofstream& outfile){ outfile << "};\n"; return true; } bool ConstructorStatement::is_valid(std::string line){ return true; } std::vector<std::string> ConstructorStatement::parse(std::string line, std::ifstream& infile){ std::vector<std::string> tokens; size_t index; std::string name = ""; std::string params = ""; line = line.substr(12); name = line; int sig_count = 0; while(sig_count != 1){ getline( infile, line ); line = std::regex_replace(line, std::regex("^ +| +$|( ) +"), "$1"); index = line.find(":"); if(line.substr(0, index) == "takes"){ sig_count++; line = line.substr(index + 2); line = std::regex_replace(line, std::regex("^ +| +$|( ) +"), "$1"); if(line != "nothing"){ std::string buffer; std::string var_type; while(line.length() != 0 && index != std::string::npos){ line = std::regex_replace(line, std::regex("^ +| +$|( ) +"), "$1"); index = line.find(","); buffer = line.substr(0, index); var_type = __to_type(buffer.substr(0, buffer.find(" "))); buffer = buffer.substr(buffer.find(" ") + 1); line = line.substr(index + 1); if(params == ""){ params = var_type + " " + buffer; }else{ params += " ," + var_type + " " + buffer; } } } } } tokens.push_back(name); tokens.push_back(params); return tokens; } bool ConstructorStatement::write(std::vector<std::string> tokens, std::ofstream& outfile){ outfile << tokens[0] << "( " << tokens[1] << " )\n"; return true; }
[ "md2999ni@edu.uwaterloo.ca" ]
md2999ni@edu.uwaterloo.ca
ec2bc67896a6fc3f3e85f4e6f7d7e62da4edd5e4
3e08a024eef1aede1310fd8c2f6c0815c88206c5
/src/xtp-quotes/xtp_quote_handler.cpp
2b79f6548e8b7bc43fedc19675c8727cec696aa1
[ "MIT" ]
permissive
zhanghaoda/babel-trader
99b0d14b730e22ed1e9922236f26d4dcf72bbc58
eda17dda5582f5a728fb6b1dbf90cfc404969c59
refs/heads/master
2020-04-05T20:16:13.492365
2018-11-12T06:55:21
2018-11-12T06:55:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,409
cpp
#include "xtp_quote_handler.h" #include "glog/logging.h" #include "rapidjson/writer.h" #include "rapidjson/stringbuffer.h" #include "common/converter.h" #include "common/utils_func.h" const char *exchange_SSE = "SSE"; const char *exchange_SZSE = "SZSE"; const char *exchange_UNKNOWN = "UNKNOWN"; XTPQuoteHandler::XTPQuoteHandler(XTPQuoteConf &conf) : api_(nullptr) , conf_(conf) , req_id_(1) , ws_service_(this, nullptr) , http_service_(this, nullptr) {} void XTPQuoteHandler::run() { // load sub topics for (auto topic : conf_.default_sub_topics) { sub_topics_[topic.symbol] = false; topic_exchange_[topic.symbol] = GetExchangeType(topic.exchange); } // init xtp api RunAPI(); // run service RunService(); } std::vector<Quote> XTPQuoteHandler::GetSubTopics(std::vector<bool> &vec_b) { std::vector<Quote> topics; vec_b.clear(); std::unique_lock<std::mutex> lock(topic_mtx_); for (auto it = sub_topics_.begin(); it != sub_topics_.end(); ++it) { Quote msg; msg.market = g_markets[Market_XTP]; msg.exchange = topic_exchange_[it->first]; msg.type = g_product_types[ProductType_Spot]; msg.symbol = it->first; msg.contract = ""; msg.contract_id = msg.contract; msg.info1 = "marketdata"; topics.push_back(msg); vec_b.push_back(it->second); msg.info1 = "kline"; msg.info2 = "1m"; topics.push_back(msg); vec_b.push_back(it->second); } return std::move(topics); } void XTPQuoteHandler::SubTopic(const Quote &msg) { { std::unique_lock<std::mutex> lock(topic_mtx_); if (sub_topics_.find(msg.symbol) != sub_topics_.end() && sub_topics_[msg.symbol] == true) { return; } sub_topics_[msg.symbol] = false; topic_exchange_[msg.symbol] = GetExchangeType(msg.exchange); } char buf[2][64]; char* topics[2]; topics[0] = buf[0]; strncpy(buf[0], msg.symbol.c_str(), 64 - 1); api_->SubscribeMarketData(topics, 1, GetExchangeType(msg.exchange)); } void XTPQuoteHandler::UnsubTopic(const Quote &msg) { XTP_EXCHANGE_TYPE exhange_type = XTP_EXCHANGE_UNKNOWN; { std::unique_lock<std::mutex> lock(topic_mtx_); if (sub_topics_.find(msg.symbol) == sub_topics_.end()) { return; } exhange_type = topic_exchange_[msg.symbol]; } char buf[2][64]; char* topics[2]; topics[0] = buf[0]; strncpy(buf[0], msg.symbol.c_str(), 64 - 1); api_->UnSubscribeMarketData(topics, 1, exhange_type); } void XTPQuoteHandler::OnDisconnected(int reason) { OutputFrontDisconnected(); // set sub topics flag { std::unique_lock<std::mutex> lock(topic_mtx_); for (auto it = sub_topics_.begin(); it != sub_topics_.end(); ++it) { it->second = false; } } // reconnect auto old_api = api_; RunAPI(); old_api->Release(); } void XTPQuoteHandler::OnError(XTPRI *error_info) { rapidjson::StringBuffer s; rapidjson::Writer<rapidjson::StringBuffer> writer(s); writer.StartObject(); writer.Key("msg"); writer.String("on_error"); writer.Key("error_id"); writer.Int(error_info->error_id); writer.Key("error_msg"); writer.String(error_info->error_msg); writer.EndObject(); LOG(INFO) << s.GetString(); } void XTPQuoteHandler::OnSubMarketData(XTPST *ticker, XTPRI *error_info, bool is_last) { // output OutputRspSubMarketData(ticker, error_info, is_last); // set topic flag if (error_info->error_id == 0) { std::unique_lock<std::mutex> lock(topic_mtx_); sub_topics_[ticker->ticker] = true; kline_builder_.add(ticker->ticker); } } void XTPQuoteHandler::OnUnSubMarketData(XTPST *ticker, XTPRI *error_info, bool is_last) { // output OutputRspUnsubMarketData(ticker, error_info, is_last); // delete topics if (error_info->error_id == 0) { std::unique_lock<std::mutex> lock(topic_mtx_); sub_topics_.erase(ticker->ticker); topic_exchange_.erase(ticker->ticker); kline_builder_.del(ticker->ticker); } } void XTPQuoteHandler::OnSubOrderBook(XTPST *ticker, XTPRI *error_info, bool is_last) {} void XTPQuoteHandler::OnUnSubOrderBook(XTPST *ticker, XTPRI *error_info, bool is_last) {} void XTPQuoteHandler::OnSubTickByTick(XTPST *ticker, XTPRI *error_info, bool is_last) {} void XTPQuoteHandler::OnUnSubTickByTick(XTPST *ticker, XTPRI *error_info, bool is_last) {} void XTPQuoteHandler::OnSubscribeAllMarketData(XTP_EXCHANGE_TYPE exchange_id, XTPRI *error_info) {} void XTPQuoteHandler::OnUnSubscribeAllMarketData(XTP_EXCHANGE_TYPE exchange_id, XTPRI *error_info) {} void XTPQuoteHandler::OnSubscribeAllOrderBook(XTP_EXCHANGE_TYPE exchange_id, XTPRI *error_info) {} void XTPQuoteHandler::OnUnSubscribeAllOrderBook(XTP_EXCHANGE_TYPE exchange_id, XTPRI *error_info) {} void XTPQuoteHandler::OnSubscribeAllTickByTick(XTP_EXCHANGE_TYPE exchange_id, XTPRI *error_info) {} void XTPQuoteHandler::OnUnSubscribeAllTickByTick(XTP_EXCHANGE_TYPE exchange_id, XTPRI *error_info) {} void XTPQuoteHandler::OnDepthMarketData(XTPMD *market_data, int64_t bid1_qty[], int32_t bid1_count, int32_t max_bid1_count, int64_t ask1_qty[], int32_t ask1_count, int32_t max_ask1_count) { #ifndef NDEBUG OutputMarketData(market_data, bid1_qty, bid1_count, max_bid1_count, ask1_qty, ask1_count, max_ask1_count); #endif // convert to common struct Quote quote; MarketData md; ConvertMarketData(market_data, quote, md); BroadcastMarketData(quote, md); // try update kline int64_t sec = (int64_t)time(nullptr); Kline kline; if (kline_builder_.updateMarketData(sec, market_data->ticker, md, kline)) { quote.info1 = "kline"; quote.info2 = "1m"; BroadcastKline(quote, kline); } } void XTPQuoteHandler::OnOrderBook(XTPOB *order_book) {} void XTPQuoteHandler::OnTickByTick(XTPTBT *tbt_data) {} void XTPQuoteHandler::RunAPI() { api_ = XTP::API::QuoteApi::CreateQuoteApi(conf_.client_id, "./log"); api_->RegisterSpi(this); api_->SetHeartBeatInterval(15); int ret = -1; ret = api_->Login( conf_.ip.c_str(), conf_.port, conf_.user_id.c_str(), conf_.password.c_str(), (XTP_PROTOCOL_TYPE)conf_.quote_protocol); if (ret != 0) { auto ri = api_->GetApiLastError(); LOG(INFO) << "Failed to login " << "(" << ri->error_id << ") " << ri->error_msg; exit(-1); } SubTopics(); } void XTPQuoteHandler::RunService() { auto loop_thread = std::thread([&] { uws_hub_.onConnection([&](uWS::WebSocket<uWS::SERVER> *ws, uWS::HttpRequest req) { ws_service_.onConnection(ws, req); }); uws_hub_.onMessage([&](uWS::WebSocket<uWS::SERVER> *ws, char *message, size_t length, uWS::OpCode opCode) { ws_service_.onMessage(ws, message, length, opCode); }); uws_hub_.onDisconnection([&](uWS::WebSocket<uWS::SERVER> *ws, int code, char *message, size_t length) { ws_service_.onDisconnection(ws, code, message, length); }); // rest uws_hub_.onHttpRequest([&](uWS::HttpResponse *res, uWS::HttpRequest req, char *data, size_t length, size_t remainingBytes) { http_service_.onMessage(res, req, data, length, remainingBytes); }); if (!uws_hub_.listen(conf_.quote_ip.c_str(), conf_.quote_port, nullptr, uS::ListenOptions::REUSE_PORT)) { LOG(INFO) << "Failed to listen"; exit(-1); } uws_hub_.run(); }); loop_thread.join(); } void XTPQuoteHandler::OutputFrontDisconnected() { rapidjson::StringBuffer s; rapidjson::Writer<rapidjson::StringBuffer> writer(s); writer.StartObject(); writer.Key("msg"); writer.String("disconnected"); writer.EndObject(); LOG(INFO) << s.GetString(); } void XTPQuoteHandler::OutputRspSubMarketData(XTPST *ticker, XTPRI *error_info, bool is_last) { rapidjson::StringBuffer s; rapidjson::Writer<rapidjson::StringBuffer> writer(s); writer.StartObject(); writer.Key("msg"); writer.String("rspsubmarketdata"); writer.Key("error_id"); writer.Int(error_info->error_id); writer.Key("error_msg"); writer.String(error_info->error_msg); writer.Key("data"); writer.StartObject(); writer.Key("exhange"); writer.String(ConvertExchangeType2Str(ticker->exchange_id)); writer.Key("symbol"); writer.String(ticker->ticker); writer.EndObject(); writer.EndObject(); LOG(INFO) << s.GetString(); } void XTPQuoteHandler::OutputRspUnsubMarketData(XTPST *ticker, XTPRI *error_info, bool is_last) { rapidjson::StringBuffer s; rapidjson::Writer<rapidjson::StringBuffer> writer(s); writer.StartObject(); writer.Key("msg"); writer.String("rspunsubmarketdata"); writer.Key("error_id"); writer.Int(error_info->error_id); writer.Key("error_msg"); writer.String(error_info->error_msg); writer.Key("data"); writer.StartObject(); writer.Key("exhange"); writer.String(ConvertExchangeType2Str(ticker->exchange_id)); writer.Key("symbol"); writer.String(ticker->ticker); writer.EndObject(); writer.EndObject(); LOG(INFO) << s.GetString(); } void XTPQuoteHandler::OutputMarketData(XTPMD *market_data, int64_t bid1_qty[], int32_t bid1_count, int32_t max_bid1_count, int64_t ask1_qty[], int32_t ask1_count, int32_t max_ask1_count) { rapidjson::StringBuffer s; rapidjson::Writer<rapidjson::StringBuffer> writer(s); writer.StartObject(); writer.Key("msg"); writer.String("marketdata"); writer.Key("data"); writer.StartObject(); { writer.Key("exchange_id"); writer.String(ConvertExchangeType2Str(market_data->exchange_id)); writer.Key("ticker"); writer.String(market_data->ticker); writer.Key("last_price"); writer.Double(market_data->last_price); writer.Key("pre_close_price"); writer.Double(market_data->pre_close_price); writer.Key("open_price"); writer.Double(market_data->open_price); writer.Key("high_price"); writer.Double(market_data->high_price); writer.Key("low_price"); writer.Double(market_data->low_price); writer.Key("close_price"); writer.Double(market_data->close_price); writer.Key("pre_total_long_positon"); writer.Int64(market_data->pre_total_long_positon); writer.Key("total_long_positon"); writer.Int64(market_data->total_long_positon); writer.Key("pre_settl_price"); writer.Double(market_data->pre_settl_price); writer.Key("settl_price"); writer.Double(market_data->settl_price); writer.Key("upper_limit_price"); writer.Double(market_data->upper_limit_price); writer.Key("lower_limit_price"); writer.Double(market_data->lower_limit_price); writer.Key("pre_delta"); writer.Double(market_data->pre_delta); writer.Key("curr_delta"); writer.Double(market_data->curr_delta); writer.Key("data_time"); writer.Int64(market_data->data_time); writer.Key("qty"); writer.Int64(market_data->qty); writer.Key("turnover"); writer.Double(market_data->turnover); writer.Key("avg_price"); writer.Double(market_data->avg_price); writer.Key("bid"); writer.StartArray(); for (int i = 0; i < 10; i++) { writer.Double(market_data->bid[i]); } writer.EndArray(); writer.Key("ask"); writer.StartArray(); for (int i = 0; i < 10; i++) { writer.Double(market_data->ask[i]); } writer.EndArray(); writer.Key("bid_qty"); writer.StartArray(); for (int i = 0; i < 10; i++) { writer.Int64(market_data->bid_qty[i]); } writer.EndArray(); writer.Key("ask_qty"); writer.StartArray(); for (int i = 0; i < 10; i++) { writer.Int64(market_data->ask_qty[i]); } writer.EndArray(); writer.Key("trades_count"); writer.Int64(market_data->trades_count); } writer.EndObject(); // data writer.EndObject(); // object LOG(INFO) << s.GetString(); } void XTPQuoteHandler::ConvertMarketData(XTPMD *market_data, Quote &quote, MarketData &md) { quote.market = g_markets[Market_XTP]; quote.exchange = ConvertExchangeType2Str(market_data->exchange_id); switch (market_data->data_type) { case XTP_MARKETDATA_OPTION: quote.type = g_product_types[ProductType_Option]; break; default: quote.type = g_product_types[ProductType_Spot]; break; } quote.symbol = market_data->ticker; quote.contract = ""; quote.contract_id = ""; quote.info1 = "marketdata"; quote.info2 = ""; md.ts = XTPGetTimestamp(market_data->data_time); md.last = market_data->last_price; for (int i = 0; i < 10; i++) { md.bids.push_back({ market_data->bid[i], market_data->bid_qty[i] }); md.asks.push_back({ market_data->ask[i], market_data->ask_qty[i] }); } md.vol = market_data->qty; md.turnover = market_data->turnover; md.avg_price = market_data->avg_price; md.pre_settlement = market_data->pre_settl_price; md.pre_close = market_data->pre_close_price; md.pre_open_interest = market_data->pre_total_long_positon; md.settlement = market_data->settl_price; md.close = market_data->close_price; md.open_interest = market_data->total_long_positon; md.upper_limit = market_data->upper_limit_price; md.lower_limit = market_data->lower_limit_price; md.open = market_data->open_price; md.high = market_data->high_price; md.low = market_data->low_price; md.trading_day = ""; md.action_day = ""; } void XTPQuoteHandler::BroadcastMarketData(const Quote &quote, const MarketData &md) { // serialize rapidjson::StringBuffer s; rapidjson::Writer<rapidjson::StringBuffer> writer(s); SerializeQuoteBegin(writer, quote); SerializeMarketData(writer, md); SerializeQuoteEnd(writer, quote); #ifndef NDEBUG LOG(INFO) << s.GetString(); #endif uws_hub_.getDefaultGroup<uWS::SERVER>().broadcast(s.GetString(), s.GetLength(), uWS::OpCode::TEXT); } void XTPQuoteHandler::BroadcastKline(const Quote &quote, const Kline &kline) { rapidjson::StringBuffer s; rapidjson::Writer<rapidjson::StringBuffer> writer(s); SerializeQuoteBegin(writer, quote); SerializeKline(writer, kline); SerializeQuoteEnd(writer, quote); #ifndef NDEBUG LOG(INFO) << s.GetString(); #endif uws_hub_.getDefaultGroup<uWS::SERVER>().broadcast(s.GetString(), s.GetLength(), uWS::OpCode::TEXT); } void XTPQuoteHandler::SubTopics() { char buf[2][64]; char* topics[2]; for (int i = 0; i < 2; i++) { topics[i] = buf[i]; } std::unique_lock<std::mutex> lock(topic_mtx_); for (auto it = sub_topics_.begin(); it != sub_topics_.end(); ++it) { if (it->second == false) { strncpy(buf[0], it->first.c_str(), sizeof(buf[0]) - 1); api_->SubscribeMarketData(topics, 1, topic_exchange_[it->first]); } } } XTP_EXCHANGE_TYPE XTPQuoteHandler::GetExchangeType(const std::string &exchange) { if (exchange == "SSE") { return XTP_EXCHANGE_SH; } else if (exchange == "SZSE") { return XTP_EXCHANGE_SZ; } return XTP_EXCHANGE_UNKNOWN; } const char* XTPQuoteHandler::ConvertExchangeType2Str(XTP_EXCHANGE_TYPE exchange_type) { switch (exchange_type) { case XTP_EXCHANGE_SH: return exchange_SSE; case XTP_EXCHANGE_SZ: return exchange_SZSE; default: return exchange_UNKNOWN; } }
[ "mugglewei@gmail.com" ]
mugglewei@gmail.com
af5eedae01bc8dc568fd276378351c681a5ffa3d
72f0137abf26c87b6cb1fb542e62b235a0930914
/2_Package/Driver_Motor_Contorl/motor_top.h
8d430b39e4f09c06d3392cf44054b44a61fbebbe
[]
no_license
SiChiTong/Embedded
0b71ffb7f093e6b563751c02fa82ff97ace095a6
82a197ba7cf988f786718fb57811298abd235775
refs/heads/v1.96
2020-12-25T22:20:14.572088
2016-04-07T13:38:45
2016-04-07T13:38:45
55,878,403
3
1
null
2016-04-10T03:13:06
2016-04-10T03:13:05
null
UTF-8
C++
false
false
1,733
h
#ifndef __motor_top_H__ #define __motor_top_H__ #include "motor_config.h" #include "motor_contorl.h" /*******************MOTOR1************************/ #define RCC_MOTOREN1 RCC_AHB1Periph_GPIOE #define GPIO_MOTOREN1 GPIOE #define GPIO_MOTOREN1_Pin GPIO_Pin_8 #define MOTOREN1_OFF() GPIO_ResetBits(GPIO_MOTOREN1 , GPIO_MOTOREN1_Pin) #define MOTOREN1_ON() GPIO_SetBits(GPIO_MOTOREN1 , GPIO_MOTOREN1_Pin) /*********************************************/ /*******************MOTOREN2************************/ #define RCC_MOTOREN2 RCC_AHB1Periph_GPIOE #define GPIO_MOTOREN2 GPIOE #define GPIO_MOTOREN2_Pin GPIO_Pin_10 #define MOTOREN2_OFF() GPIO_ResetBits(GPIO_MOTOREN2 , GPIO_MOTOREN2_Pin) #define MOTOREN2_ON() GPIO_SetBits(GPIO_MOTOREN2 , GPIO_MOTOREN2_Pin) /*********************************************/ /*******************MOTOREN2************************/ #define RCC_MOTOREN3 RCC_AHB1Periph_GPIOE #define GPIO_MOTOREN3 GPIOE #define GPIO_MOTOREN3_Pin GPIO_Pin_12 #define MOTOREN3_OFF() GPIO_ResetBits(GPIO_MOTOREN3 , GPIO_MOTOREN3_Pin) #define MOTOREN3_ON() GPIO_SetBits(GPIO_MOTOREN3 , GPIO_MOTOREN3_Pin) /*********************************************/ class MOTOR_TOP { public: MOTOR_PID motor1,motor2,motor3; unsigned char Enable_M1,Enable_M2,Enable_M3 ; //Whether or not enable motor control float Expect_Angle_Speed_M1,Expect_Angle_Speed_M2,Expect_Angle_Speed_M3; MOTOR_TOP(); void Motor_Top_Init(void); void Motor_Top_Call(void); private: void Motor_Set_PWM(unsigned char Motor_ID , float Pid_out); }; extern MOTOR_TOP motor_top; #endif
[ "315261982@qq.com" ]
315261982@qq.com
0b317d52f9d9211b0b90cfd6206337734c68f1b0
5e8d200078e64b97e3bbd1e61f83cb5bae99ab6e
/main/source/src/protocols/rotamer_recovery/RRProtocolMinPack.cc
4a93e4ed3fede8154888d22200181ac6af2f30ed
[]
no_license
MedicaicloudLink/Rosetta
3ee2d79d48b31bd8ca898036ad32fe910c9a7a28
01affdf77abb773ed375b83cdbbf58439edd8719
refs/heads/master
2020-12-07T17:52:01.350906
2020-01-10T08:24:09
2020-01-10T08:24:09
232,757,729
2
6
null
null
null
null
UTF-8
C++
false
false
2,522
cc
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // (c) Copyright Rosetta Commons Member Institutions. // (c) This file is part of the Rosetta software suite and is made available under license. // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. // (c) For more information, see http://www.rosettacommons.org. Questions about this can be // (c) addressed to University of Washington CoMotion, email: license@uw.edu. /// @file src/protocols/rotamer_recovery/RRProtocolMinPack.cc /// @author Matthew O'Meara (mattjomeara@gmail.com) // Unit Headers #include <protocols/rotamer_recovery/RRProtocolMinPack.hh> // Project Headers #include <protocols/rotamer_recovery/RRComparer.hh> #include <protocols/rotamer_recovery/RRReporter.hh> // Platform Headers #include <basic/Tracer.hh> #include <core/pack/task/PackerTask.hh> #include <core/pack/min_pack.hh> #include <core/pose/Pose.hh> #include <core/scoring/ScoreFunctionFactory.hh> // C++ Headers #include <string> //Auto Headers #include <utility/vector1.hh> using std::string; using core::Size; using core::pack::min_pack; using core::pose::Pose; using core::scoring::ScoreFunction; using core::scoring::get_score_function; using core::pack::task::PackerTask; using core::pack::task::PackerTaskOP; using basic::Tracer; namespace protocols { namespace rotamer_recovery { static Tracer TR("protocol.moves.RRProtocolMinPack"); RRProtocolMinPack::RRProtocolMinPack() = default; RRProtocolMinPack::RRProtocolMinPack( RRProtocolMinPack const & ) : RRProtocol() {} RRProtocolMinPack::~RRProtocolMinPack() = default; string RRProtocolMinPack::get_name() const { return "RRProtocolMinPack"; } string RRProtocolMinPack::get_parameters() const { return ""; } /// @details apply MinPack and measure rotamer recovery for each residue void RRProtocolMinPack::run( RRComparerOP comparer, RRReporterOP reporter, Pose const & pose, ScoreFunction const & score_function, PackerTask const & packer_task ) { // Assume score_function.setup_for_scoring(pose) has already been called. Pose working_pose = pose; // deep copy min_pack(working_pose, score_function, packer_task.get_self_ptr()); for ( Size ii = 1; ii <= pose.size(); ++ii ) { if ( !packer_task.pack_residue(ii) ) continue; measure_rotamer_recovery( comparer, reporter, pose, working_pose, pose.residue(ii), working_pose.residue(ii) ); } } } // rotamer_recovery } // protocols
[ "36790013+MedicaicloudLink@users.noreply.github.com" ]
36790013+MedicaicloudLink@users.noreply.github.com
16df1f98c3ffa35034fa1cd7e8826ea9c160b12b
6f73630836d18973cbcbc1beac26fed9ce626321
/New_Text_Document.cpp
4eaf1ecb1c7cd85d5f590ddc46bd638d5587a4b2
[]
no_license
EternalEdward/QAQ
ae62a370d438e2ad4f0b6c5c21793867b158e1c7
17a9024b00ffe0991540f8fc4aa81e9d09c16c0a
refs/heads/master
2023-06-02T02:59:13.787071
2021-06-18T14:40:20
2021-06-18T14:40:20
376,982,562
0
0
null
2021-06-21T16:42:54
2021-06-14T23:38:13
C++
UTF-8
C++
false
false
120
cpp
#include<bits/stdc++.h> using namespace std; int main(){ char x[20]; cin>>x; cout<<x<<endl; return 0; }
[ "2822134995@qq.com" ]
2822134995@qq.com
7ff2125f524e7ec8a7cc2db17eee3c2047818512
31c50d614b04a8136fe42da9e8f41909c10feb75
/Source/agc030/agc030_b.cpp
ad04d240abb8e1266156bd3f92640cff2b68852c
[ "MIT" ]
permissive
Ryohei222/Competitive-Programming
f7fc50af51732b971f95c72b14f04f2346d4e890
f14d215972cbe2b7e4cd835fc2aaa7670357bb93
refs/heads/master
2020-04-01T05:03:13.948399
2019-05-01T15:58:22
2019-05-01T15:58:22
152,888,435
1
1
null
null
null
null
UTF-8
C++
false
false
2,921
cpp
#include <iostream> #include <algorithm> #include <functional> #include <string> #include <vector> #include <set> #include <queue> #include <stack> #include <numeric> #include <bitset> #include <map> #include <set> #include <list> #include <unordered_set> #include <unordered_map> #include <stdlib.h> using namespace std; typedef long long i64; typedef pair<i64, i64> P; template<class T> const T INF = numeric_limits<T>::max(); template<class T> const T SINF = numeric_limits<T>::max() / 10; static const i64 MOD = 1000000007; //int dx[4] = {0,1,0,-1}, dy[4] = {-1,0,1,0}; //int dx[5] = {-1,0,0,0,1}, dy[5] = {0,-1,0,1,0}; //int dx[8] = {-1,0,1,1,1,0,-1,-1}, dy[8] = {1,1,1,0,-1,-1,-1,0}; //int dx[9] = {-1,0,1,1,1,0,-1,-1,0}, dy[9] = {1,1,1,0,-1,-1,-1,0,0}; struct edge { i64 from, to, cost; edge(i64 to, i64 cost) : from(-1), to(to), cost(cost) {} edge(i64 src, i64 to, i64 cost) : from(src), to(to), cost(cost) {} }; template<typename T> vector<T> make_v(size_t a){return vector<T>(a);} template<typename T,typename... Ts> auto make_v(size_t a,Ts... ts){ return vector<decltype(make_v<T>(ts...))>(a,make_v<T>(ts...)); } template<typename T,typename V> typename enable_if<is_class<T>::value==0>::type fill_v(T &t,const V &v){t=v;} template<typename T,typename V> typename enable_if<is_class<T>::value!=0>::type fill_v(T &t,const V &v){ for(auto &e:t) fill_v(e,v); } //-----end of template-----// int main(){ ios_base::sync_with_stdio(false); cin.tie(0); i64 l, n; cin >> l >> n; vector<i64> x(n); for(i64 i = 0; i < n; ++i) cin >> x[i]; sort(x.begin(), x.end()); i64 left, right, c; left = 1; right = n - 1; c = x[0]; i64 cnt = 1; i64 sum = x[0]; while(cnt != n){ if(left == right){ if(c > x[left]){ sum += max(l - c + x[left], c - x[right]); }else{ sum += max(x[left] - c, c + l - x[right]); } }else if(c > x[left]){ if(l - c + x[left] >= c - x[right]){ sum += l - c + x[left]; c = x[left]; left++; }else{ sum += c - x[right]; c = x[right]; right--; } }else{ if(x[left] - c >= c + l - x[right]){ sum += x[left] - c; c = x[left]; left++; }else{ sum += c + l - x[right]; c = x[right]; right--; } } cnt++; } i64 ans = sum; left = 0; right = n - 2; c = x[n - 1]; cnt = 1; sum = l - x[n - 1]; while(cnt != n){ if(left == right){ if(c > x[left]){ sum += max(l - c + x[left], c - x[right]); }else{ sum += max(x[left] - c, c + l - x[right]); } }else if(c > x[left]){ if(l - c + x[left] >= c - x[right]){ sum += l - c + x[left]; c = x[left]; left++; }else{ sum += c - x[right]; c = x[right]; right--; } }else{ if(x[left] - c >= c + l - x[right]){ sum += x[left] - c; c = x[left]; left++; }else{ sum += c + l - x[right]; c = x[right]; right--; } } cnt++; } cout << ans << endl; cout << sum << endl; }
[ "kobaryo222@gmail.com" ]
kobaryo222@gmail.com
057b204eed334a786afe1610777b59081eef1c48
30ab1090ba15c433f08bbff0a795bcca5817c023
/jni/miniblocxx/COWIntrusiveReference.hpp
04a7ff25c0428f827ad11e9da02e0e539c724838
[]
no_license
dnuffer/redneckracer
0c8e2efea148057bfbb81c689f0c81f5f430526b
f298e0fcda169829ffc7002165d38613eafc6ee8
refs/heads/master
2021-01-01T06:11:42.520020
2012-07-06T04:42:21
2012-07-06T04:42:21
4,918,963
1
0
null
null
null
null
UTF-8
C++
false
false
10,644
hpp
/******************************************************************************* * Copyright (C) 2005, Quest Software, Inc. All rights reserved. * Copyright (C) 2006, Novell, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of * Quest Software, Inc., * nor Novell, Inc., * nor the names of its contributors or employees 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. *******************************************************************************/ // // Copyright (c) 2001, 2002 Peter Dimov // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // /** * @author Peter Dimov * @author Dan Nuffer */ #ifndef BLOCXX_COW_INTRUSIVE_REFERENCE_HPP_INCLUDE_GUARD_ #define BLOCXX_COW_INTRUSIVE_REFERENCE_HPP_INCLUDE_GUARD_ #include "miniblocxx/BLOCXX_config.h" #ifdef BLOCXX_CHECK_NULL_REFERENCES #include "miniblocxx/ReferenceHelpers.hpp" #endif namespace BLOCXX_NAMESPACE { /** * COWIntrusiveReference * A smart pointer that uses intrusive reference counting. It supports * 'copy on write' functionality. * The 'intrusive' in the class names comes from the fact that * referenced objects are required to be sub-classes of * COWIntrusiveCountableBase. If your looking for a non-intrusive smart * smart pointer class that providers copy on write functionality, * check out the COWReference class. * * This class relies on calls to * * void COWIntrusiveReferenceAddRef(T* p); * void COWIntrusiveReferenceRelease(T* p); * bool COWIntrusiveReferenceUnique(T* p); * T* COWIntrusiveReferenceClone(T* p); * * (p != 0) * * The object is responsible for destroying itself. * * If you want your class to be managed by COWIntrusiveReference, you can * derive it from COWIntrusiveCountableBase, or write your own set of * functions. */ template<class T> class COWIntrusiveReference { private: typedef COWIntrusiveReference this_type; public: typedef T element_type; /** * Default constructor * The underlying object pointer will be NULL. */ COWIntrusiveReference(): m_pObj(0) { } /** * Construct a COWIntrusiveReference that will contain a pointer * to a COWIntrusiveCountableBase object. * @param p A pointer to a COWIntrusiveCountableBase derivative. * @param addRef If true the reference count will be incremented before * the constructor returns. Otherwise thre reference count is left alone. */ COWIntrusiveReference(T * p, bool addRef = true): m_pObj(p) { if (m_pObj != 0 && addRef) COWIntrusiveReferenceAddRef(m_pObj); } /** * Copy constructor. This takes a COWIntrusiveReference of a type * derived from T. * This constructor will cause this COWIntrusiveReference object to * share the same underlying COWIntrusiveCountableBase pointer with * another. This will cause the reference count to get incremented on * the underlying object. * @param rhs The object to copy the COWIntrusiveCountableBase * pointer from. */ template<class U> COWIntrusiveReference(COWIntrusiveReference<U> const & rhs): m_pObj(rhs.m_pObj) { if (m_pObj != 0) COWIntrusiveReferenceAddRef(m_pObj); } /** * Copy constructor. This constructor will cause this * COWIntrusiveReference object to share the same underlying * COWIntrusiveCountableBase pointer with another. This will cause the * reference count to get incremented on the underlying object. * @param rhs The object to copy the COWIntrusiveCountableBase * pointer from. */ COWIntrusiveReference(COWIntrusiveReference const & rhs): m_pObj(rhs.m_pObj) { if (m_pObj != 0) COWIntrusiveReferenceAddRef(m_pObj); } /** * Destroy this COWIntrusiveReference. If the reference count to the * underlying COWIntrusiveCountableBase object is zero after it is * decremented in this method it will be deleted. */ ~COWIntrusiveReference() { if (m_pObj != 0) COWIntrusiveReferenceRelease(m_pObj); } /** * Assignment operator that that takes a COWIntrusiveReference of a type * derived from T. * This method will cause this COWIntrusiveReference object to * share the same underlying COWIntrusiveCountableBase pointer with * another. This will cause the reference count to get incremented on * the underlying object. * @param rhs The object to copy the COWIntrusiveCountableBase * pointer from. * @return A reference to this COWIntrusiveReference object. */ template<class U> COWIntrusiveReference & operator=(COWIntrusiveReference<U> const & rhs) { this_type(rhs).swap(*this); return *this; } /** * Assignment operator. * This method will cause this COWIntrusiveReference object to * share the same underlying COWIntrusiveCountableBase pointer with * another. This will cause the reference count to get incremented on * the underlying object. * @param rhs The object to copy the COWIntrusiveCountableBase * pointer from. * @return A reference to this COWIntrusiveReference object. */ COWIntrusiveReference & operator=(COWIntrusiveReference const & rhs) { this_type(rhs).swap(*this); return *this; } /** * Assignment operator. * This changes the underlying COWIntrusiveCountableBase pointer * to the one passed to this method. * @param rhs A pointer to a COWIntrusiveCountableBase object. this * will be the new underlying pointer for this object. * @return A reference to this COWIntrusiveReference object. */ COWIntrusiveReference & operator=(T * rhs) { this_type(rhs).swap(*this); return *this; } /** * @return A read only pointer to the underlying * COWIntrusiveCountableBase object. */ const T * getPtr() const { return m_pObj; } /** * @return A read only reference to the underlying * COWIntrusiveCountableBase object. */ const T & operator*() const { #ifdef BLOCXX_CHECK_NULL_REFERENCES ReferenceHelpers::checkNull(this); ReferenceHelpers::checkNull(m_pObj); #endif return *m_pObj; } /** * @return A read only pointer to the underlying * COWIntrusiveCountableBase object. */ const T * operator->() const { #ifdef BLOCXX_CHECK_NULL_REFERENCES ReferenceHelpers::checkNull(this); ReferenceHelpers::checkNull(m_pObj); #endif return m_pObj; } /** * @return A read/write reference to the underlying * COWIntrusiveCountableBase object. */ T & operator*() { #ifdef BLOCXX_CHECK_NULL_REFERENCES ReferenceHelpers::checkNull(this); ReferenceHelpers::checkNull(m_pObj); #endif getWriteLock(); return *m_pObj; } /** * @return A read/write pointer to the underlying * COWIntrusiveCountableBase object. */ T * operator->() { #ifdef BLOCXX_CHECK_NULL_REFERENCES ReferenceHelpers::checkNull(this); ReferenceHelpers::checkNull(m_pObj); #endif getWriteLock(); return m_pObj; } typedef T * this_type::*unspecified_bool_type; operator unspecified_bool_type () const { return m_pObj == 0? 0: &this_type::m_pObj; } /** * Negation operator * @return true if this objects COWIntrusiveCountableBase pointer * is NULL. */ bool operator! () const { return m_pObj == 0; } void swap(COWIntrusiveReference & rhs) { T * tmp = m_pObj; m_pObj = rhs.m_pObj; rhs.m_pObj = tmp; } #if !defined(__GNUC__) || __GNUC__ > 2 // causes gcc 2.95 to ICE /* This is so the templated constructor will work */ template <class U> friend class COWIntrusiveReference; private: #endif /** * Create a clone of the COWIntrusiveCountableBase object if * there is more than one reference to it. This method is * used to support the copy on write functionality. */ void getWriteLock() { if ((m_pObj != 0) && !COWIntrusiveReferenceUnique(m_pObj)) { m_pObj = COWIntrusiveReferenceClone(m_pObj); } } T * m_pObj; }; template<class T, class U> inline bool operator==(COWIntrusiveReference<T> const & a, COWIntrusiveReference<U> const & b) { return a.getPtr() == b.getPtr(); } template<class T, class U> inline bool operator!=(COWIntrusiveReference<T> const & a, COWIntrusiveReference<U> const & b) { return a.getPtr() != b.getPtr(); } template<class T> inline bool operator==(COWIntrusiveReference<T> const & a, const T * b) { return a.getPtr() == b; } template<class T> inline bool operator!=(COWIntrusiveReference<T> const & a, const T * b) { return a.getPtr() != b; } template<class T> inline bool operator==(const T * a, COWIntrusiveReference<T> const & b) { return a == b.getPtr(); } template<class T> inline bool operator!=(const T * a, COWIntrusiveReference<T> const & b) { return a != b.getPtr(); } #if __GNUC__ == 2 && __GNUC_MINOR__ <= 96 // Resolve the ambiguity between our op!= and the one in rel_ops template<class T> inline bool operator!=(COWIntrusiveReference<T> const & a, COWIntrusiveReference<T> const & b) { return a.getPtr() != b.getPtr(); } #endif template<class T> inline bool operator<(COWIntrusiveReference<T> const & a, COWIntrusiveReference<T> const & b) { return a.getPtr() < b.getPtr(); } template<class T> void swap(COWIntrusiveReference<T> & lhs, COWIntrusiveReference<T> & rhs) { lhs.swap(rhs); } } // end namespace BLOCXX_NAMESPACE #endif
[ "danielnuffer@gmail.com" ]
danielnuffer@gmail.com
e84b5c1bc17a13479e907fac495332e30cb9bbf6
6c253330b7b9345cefe03715dcfbf4962eddb2f0
/Core/Core/Storage/Mongo/Mongo.h
a21418e8ce12ef0c78275c476eaa2ce0ff621df8
[ "MIT" ]
permissive
usingsystem/vortex
14c3effa50e17b0de052182fd928b8f38092d72f
a97031227d4e867986918d39eeb2d184147cf118
refs/heads/master
2023-02-09T06:22:06.340071
2020-12-31T22:54:27
2020-12-31T22:54:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,580
h
#pragma once #include <string> #include <vector> #ifdef VORTEX_HAS_FEATURE_MONGO #include <mongocxx/client.hpp> #endif #include <Maze/Maze.hpp> #include <Core/Storage/Mongo/Db.h> #include <Core/Storage/Mongo/Collection.h> namespace Vortex::Core::Storage::Mongo { class Mongo { public: VORTEX_CORE_API Mongo(); VORTEX_CORE_API Mongo(const Maze::Element& mongo_config); VORTEX_CORE_API void connect(); VORTEX_CORE_API void set_config(const Maze::Element& mongo_config); VORTEX_CORE_API std::string get_connection_uri(); VORTEX_CORE_API std::string get_default_db_name(); VORTEX_CORE_API Db get_db(const std::string& database_name); VORTEX_CORE_API Collection get_collection(const std::string& collection_name); VORTEX_CORE_API Collection get_collection(const std::string& database_name, const std::string& collection_name); VORTEX_CORE_API std::vector<std::string> list_databases(); VORTEX_CORE_API std::vector<std::string> list_collections(const std::string& database_name); VORTEX_CORE_API bool database_exists(const std::string& database); VORTEX_CORE_API bool collection_exists(const std::string& database, const std::string& collection); VORTEX_CORE_API void drop_database(const std::string& database_name); VORTEX_CORE_API void clone_database(const std::string& old_name, const std::string& new_name); VORTEX_CORE_API const bool is_enabled() const; private: #ifdef VORTEX_HAS_FEATURE_MONGO mongocxx::client _client; #endif Maze::Element _mongo_config; bool _enabled = true; }; } // namespace Vortex::Core::Storage::Mongo
[ "ziga@bobnar.net" ]
ziga@bobnar.net
0567678ffe6a2a511d70eeff5bb5330618493b87
2738d272ae9bc90dc9a35877755d632e64ac8974
/adresuRadimas/nuskaitymas.cpp
fb2fc36706335d9b5172f98cd6273a64f25fd31b
[]
no_license
sandra0828/zodziuSkaiciavimas
2757c14fb08ae942c3a8f978bf352038f7a3077d
85dea3edd7e99554dbcd387193d1cdf03368da3d
refs/heads/master
2023-02-09T11:38:37.227325
2020-12-27T11:35:14
2020-12-27T11:35:14
324,555,026
0
0
null
null
null
null
UTF-8
C++
false
false
889
cpp
#include "nuskaitymas.h" void nuskaityti(string failoVardas, vector <string>& adresai) { ifstream fd(failoVardas); try { if (fd.fail()) throw std::runtime_error("Failas nerastas \n"); } catch (const std::runtime_error& e) { std::cout << e.what(); return; } while (!fd.eof()) { string eilute; getline(fd, eilute); stringstream ss(eilute); string zodis; while (ss >> zodis) { if (zodis.size() == 1 && ispunct(zodis.front())) continue; string tinkamasZodis = tikrintiZodi(zodis); if (tinkamasZodis.size() > 0) { if ((arURL(tinkamasZodis)) == true) { adresai.push_back(tinkamasZodis); } } } } fd.close(); }
[ "macsa@LAPTOP-2GDA5VDB" ]
macsa@LAPTOP-2GDA5VDB