blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
f96fbd547710eb409291a8fbf21e2e9c4a6d664c
02bbc0eb91bee8ee80071000bd4c206232dade02
/Win32/Win32 004/my_common.h
3b34cd94f360913f48da9bec9e3e2b96be723f04
[ "MIT" ]
permissive
SimpleTalkCpp/SimpleTalkCpp_Tutorial
f996173bce45f9cb7e33ba5be1f6f1ceb615e733
760a14086eb688346085b21e589b963ac5618c82
refs/heads/main
2023-04-15T09:54:47.950086
2023-04-08T12:44:39
2023-04-08T12:44:39
98,706,808
44
18
null
null
null
null
UTF-8
C++
false
false
182
h
#pragma once #include <stdio.h> #include <windows.h> #include <windowsx.h> #include <stdint.h> template<class T> inline void my_bzero(T& s) { memset(&s, 0, sizeof(s)); }
[ "SimpleTalkCpp@gmail.com" ]
SimpleTalkCpp@gmail.com
b269752ca718051efdab45c2a846cb3fdecd384b
d4291c13f4ebf3610f8c4adc75eede4baee0b2c1
/RecoEgamma/ElectronIdentification/plugins/cuts/GsfEleTrkPtIsoRhoCut.cc
f99a133d0c86d5edc9e82ac7a5eda9766b8a78b9
[ "Apache-2.0" ]
permissive
pasmuss/cmssw
22efced0a4a43ef8bc8066b2a6bddece0023a66e
566f40c323beef46134485a45ea53349f59ae534
refs/heads/master
2021-07-07T08:37:50.928560
2017-08-28T08:54:23
2017-08-28T08:54:23
237,956,377
0
0
Apache-2.0
2020-02-03T12:08:41
2020-02-03T12:08:41
null
UTF-8
C++
false
false
2,505
cc
#include "PhysicsTools/SelectorUtils/interface/CutApplicatorWithEventContentBase.h" #include "DataFormats/EgammaCandidates/interface/GsfElectron.h" #include "DataFormats/EgammaCandidates/interface/ConversionFwd.h" #include "DataFormats/EgammaCandidates/interface/Conversion.h" #include "RecoEgamma/EgammaTools/interface/ConversionTools.h" #include "RecoEgamma/ElectronIdentification/interface/EBEECutValues.h" class GsfEleTrkPtIsoRhoCut : public CutApplicatorWithEventContentBase { public: GsfEleTrkPtIsoRhoCut(const edm::ParameterSet& c); result_type operator()(const reco::GsfElectronPtr&) const override final; void setConsumes(edm::ConsumesCollector&) override final; void getEventContent(const edm::EventBase&) override final; double value(const reco::CandidatePtr& cand) const override final; CandidateType candidateType() const override final { return ELECTRON; } private: EBEECutValues slopeTerm_; EBEECutValues slopeStart_; EBEECutValues constTerm_; EBEECutValues rhoEtStart_; EBEECutValues rhoEA_; edm::Handle<double> rhoHandle_; }; DEFINE_EDM_PLUGIN(CutApplicatorFactory, GsfEleTrkPtIsoRhoCut, "GsfEleTrkPtIsoRhoCut"); GsfEleTrkPtIsoRhoCut::GsfEleTrkPtIsoRhoCut(const edm::ParameterSet& params) : CutApplicatorWithEventContentBase(params), slopeTerm_(params,"slopeTerm"), slopeStart_(params,"slopeStart"), constTerm_(params,"constTerm"), rhoEtStart_(params,"rhoEtStart"), rhoEA_(params,"rhoEA") { edm::InputTag rhoTag = params.getParameter<edm::InputTag>("rho"); contentTags_.emplace("rho",rhoTag); } void GsfEleTrkPtIsoRhoCut::setConsumes(edm::ConsumesCollector& cc) { auto rho = cc.consumes<double>(contentTags_["rho"]); contentTokens_.emplace("rho",rho); } void GsfEleTrkPtIsoRhoCut::getEventContent(const edm::EventBase& ev) { ev.getByLabel(contentTags_["rho"],rhoHandle_); } CutApplicatorBase::result_type GsfEleTrkPtIsoRhoCut:: operator()(const reco::GsfElectronPtr& cand) const{ const double rho = (*rhoHandle_); const float isolTrkPt = cand->dr03TkSumPt(); const float et = cand->et(); const float cutValue = et > slopeStart_(cand) ? slopeTerm_(cand)*(et-slopeStart_(cand)) + constTerm_(cand) : constTerm_(cand); const float rhoCutValue = et >= rhoEtStart_(cand) ? rhoEA_(cand)*rho : 0.; return isolTrkPt < cutValue+rhoCutValue; } double GsfEleTrkPtIsoRhoCut:: value(const reco::CandidatePtr& cand) const { reco::GsfElectronPtr ele(cand); return ele->dr03TkSumPt(); }
[ "sam.j.harper@gmail.com" ]
sam.j.harper@gmail.com
f76be8b5051deb8f8da8097ed69363aa9bff71c5
acd92f081599799a46f88201747ee29fab305801
/engine/rendering/ViewCamera.cpp
49d03cb1aafefa0acaa5a55128a9caf2aae551f7
[]
no_license
shadow-lr/VulkanRenderer
7d538cf07b8e1dd126cbe6b9c29838656b2b626e
63ab42b0f48b768271472f4ce05371fe566144de
refs/heads/master
2022-10-12T06:54:09.773120
2020-06-15T05:34:08
2020-06-15T05:34:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,168
cpp
#include "ViewCamera.h" #include "rendering/backend/Device.h" const cml::vec3f WorldUp = cml::vec3f::up; void ViewCameraData::Setup (CameraType type, cml::vec3f position, cml::quatf rotation) { this->type = type; this->position = position; this->rotation = rotation; proj_mat_dirty = true; view_mat_dirty = true; } cml::mat4f ViewCameraData::get_view_mat () { if (view_mat_dirty) { view_mat_dirty = false; cml::vec3f front = cml::vec3f::forward; // cml::vec3f front = cml::normalize (rotation * cml::vec3f{ 0, 0, 1 }); cml::vec3f right = cml::normalize (cml::cross (front, WorldUp)); cml::vec3f up = cml::normalize (cml::cross (right, front)); mat_view = cml::lookAt (position, position + front, up); } return mat_view; } cml::mat4f ViewCameraData::get_proj_mat () { if (proj_mat_dirty) { proj_mat_dirty = false; if (type == CameraType::perspective) { mat_proj = cml::perspective (fov, aspect, clip_near, clip_far); } else { mat_proj = cml::ortho (-size, size, -size, size, clip_near, clip_far); } } return mat_proj; } cml::mat4f ViewCameraData::get_proj_view_mat () { if (proj_mat_dirty || view_mat_dirty) { mat_proj_view = get_proj_mat () * get_view_mat (); } return mat_proj_view; } cml::vec3f ViewCameraData::get_position () { return position; } cml::quatf ViewCameraData::get_rotation () { return rotation; } float ViewCameraData::get_fov () { return fov; } float ViewCameraData::get_aspect_ratio () { return aspect; } float ViewCameraData::get_view_size () { return size; } float ViewCameraData::get_clip_near () { return clip_near; } float ViewCameraData::get_clip_far () { return clip_far; } void ViewCameraData::set_position (cml::vec3f position) { view_mat_dirty = true; this->position = position; } void ViewCameraData::set_rotation (cml::quatf rotation) { view_mat_dirty = true; this->rotation = rotation; } void ViewCameraData::set_fov (float fov) { proj_mat_dirty = true; this->fov = fov; } void ViewCameraData::set_aspect_ratio (float aspect) { proj_mat_dirty = true; this->aspect = aspect; } void ViewCameraData::set_view_size (float size) { proj_mat_dirty = true; this->size = size; } void ViewCameraData::set_clip_near (float near) { proj_mat_dirty = true; clip_near = near; } void ViewCameraData::set_clip_far (float far) { proj_mat_dirty = true; clip_far = far; } RenderCameras::RenderCameras (VulkanDevice& device) : device (device), data_buffers (device, uniform_details (sizeof (CameraGPUData) * MaxCameraCount)) { camera_data.resize (MaxCameraCount); }; ViewCameraID RenderCameras::create (CameraType type, cml::vec3f position, cml::quatf rotation) { std::lock_guard lg (lock); for (ViewCameraID i = 0; i < camera_data.size (); i++) { if (camera_data.at (i).is_active == false) { camera_data.at (i).is_active = true; camera_data.at (i).Setup (type, position, rotation); return i; } } return -1; // assume theres enough cameras available } void RenderCameras::remove (ViewCameraID id) { std::lock_guard lg (lock); camera_data.at (id).is_active = false; } ViewCameraData& RenderCameras::get_camera_data (ViewCameraID id) { std::lock_guard lg (lock); return camera_data.at (id); } void RenderCameras::set_camera_data (ViewCameraID id, ViewCameraData const& data) { std::lock_guard lg (lock); camera_data.at (id) = data; } void RenderCameras::update_gpu_buffer (int index) { std::lock_guard lg (lock); std::vector<CameraGPUData> data; data.reserve (MaxCameraCount); for (auto& cam : camera_data) { CameraGPUData gpu_cam; gpu_cam.proj_view = cam.get_proj_view_mat (); gpu_cam.view = cam.get_view_mat (); gpu_cam.camera_pos = cam.get_position (); // TODO gpu_cam.camera_dir = cml::vec3f (); // cam.get_rotation (); ??? data.push_back (gpu_cam); } data_buffers.Write ().copy_to_buffer (data); } void RenderCameras::setup_view_camera (ViewCameraID id, CameraType type, cml::vec3f position, cml::quatf rotation) { camera_data.at (id).type = type; camera_data.at (id).position = position; camera_data.at (id).rotation = rotation; camera_data.at (id).proj_mat_dirty = true; camera_data.at (id).view_mat_dirty = true; }
[ "cdgiessen@gmail.com" ]
cdgiessen@gmail.com
4da37c6fd867dddca48ea75a57c75ed3564e52dc
193328418c6f5f69321dd4b9c42838e5f5ca5e9d
/GLTest/GLTest/VertexShader.cpp
a4cd459841d5e675ad832b4a7010ec1758ff4bf9
[]
no_license
charre2017idv/OpenGLTesting
9680abe207164d1d32fe6e9d1dd5117a642bd7d8
7cd34a1059f3e8002b35cc2af89811cf7e8c0c5c
refs/heads/master
2020-08-29T17:31:14.281441
2019-10-28T19:48:12
2019-10-28T19:48:12
218,111,448
0
0
null
null
null
null
UTF-8
C++
false
false
544
cpp
#include "VertexShader.h" VertexBuffer::VertexBuffer() { } VertexBuffer::~VertexBuffer() { } void VertexBuffer::Init(VertexBufferDesc _Desc) { m_Descriptor = _Desc; RenderManager::getSingleton().CreateBuffer(*this); } void VertexBuffer::Bind() const { glBindBuffer(GL_ARRAY_BUFFER, m_VertexShader.ID); } void VertexBuffer::Unbind() const { glBindBuffer(GL_ARRAY_BUFFER, 0); } VertexBufferID & VertexBuffer::getInterface() { return m_VertexShader; } VertexBufferDesc & VertexBuffer::getDescriptor() { return m_Descriptor; }
[ "idv17c.rcharreton@uartesdigitales.edu.mx" ]
idv17c.rcharreton@uartesdigitales.edu.mx
0913c2bd5bed0f1dc84eafd370332b620596481c
d4a97c4c59e0c1320234e614b5182df631be1ba4
/src/lexer.cpp
e771c746c2daa4174a10fe5b51f2723f46dc46e6
[]
no_license
kakitgogogo/mcc
d4eb43aef90e95665845614003c044f62c516a24
b8e6b65e553a714707f946c463aada65027e857c
refs/heads/master
2021-04-15T09:27:08.642342
2018-05-10T05:00:59
2018-05-10T05:00:59
126,915,143
0
0
null
null
null
null
UTF-8
C++
false
false
14,823
cpp
#include <stdlib.h> #include <errno.h> #include <string.h> #include <stdarg.h> #include <algorithm> #include "encode.h" #include "lexer.h" #include "buffer.h" Lexer::Lexer(char* filename) { FILE* fp = fopen(filename, "r"); if(!fp) { error("Fail to open %s: %s", filename, strerror(errno)); } fileset.push_file(fp, filename); base_file = filename; } Lexer::Lexer(std::vector<std::shared_ptr<Token> >& toks) { std::reverse(toks.begin(), toks.end()); buffer = toks; } /* According to C11 6.4p1: white space consists of comments (described later), or white-space characters (space, horizontal tab, new-line, vertical tab, and form-feed), or both. In here, newline has other usage */ bool Lexer::skip_space_aux() { int c = fileset.get_chr(); if(c == EOF) { return false; } else if(isspace(c) && c != '\n') { return true; } else if(c == '/') { if(fileset.next('/')) { // line comment while(c != '\n' && c != EOF) c = fileset.get_chr(); if(c == '\n') fileset.unget_chr(c); return true; } else if(fileset.next('*')) { // block comment Pos pos = get_pos(-2); // has read "/*" while(true) { c = fileset.get_chr(); if(c == EOF) { fileset.unget_chr(c); errorp(pos, "unexpected end of block comment"); return false; } if(c == '*') if(fileset.next('/')) return true; } } } fileset.unget_chr(c); return false; } bool Lexer::skip_space() { if(!skip_space_aux()) return false; while(skip_space_aux()); return true; } /* C11 6.4.4: escape-sequence escape-sequence: simple-escape-sequence octal-escape-sequence hexadecimal-escape-sequence universal-character-name */ // doc/lexer/escape.dot int Lexer::read_escape_char() { Pos pos = get_pos(-1); // has read "/" int c = fileset.get_chr(); switch (c) { case '\'': case '"': case '?': case '\\': return c; case 'a': return '\a'; case 'b': return '\b'; case 'f': return '\f'; case 'n': return '\n'; case 'r': return '\r'; case 't': return '\t'; case 'v': return '\v'; case 'e': return '\033'; // '\e' is GNU extension case '0' ... '7': return read_octal_char(c); case 'x': return read_hex_char(); case 'u': return read_universal_char(4); case 'U': return read_universal_char(8); } warnp(pos, "unknown escape character: \\%c", c); return c; } // one of \0, \0o, \0oo int Lexer::read_octal_char(int c) { int o = c - '0'; int i = 1; while(i++ < 3) { c = fileset.get_chr(); if(c < '0' || c > '7') { fileset.unget_chr(c); return o; } o = (o << 3) | (c - '0'); } return o; } // \xdd... int Lexer::read_hex_char() { Pos pos = get_pos(-2); int c = fileset.get_chr(); if (!isxdigit(c)) { fileset.unget_chr(c); errorp(get_pos(0), "invalid hex character: %c", c == '\n' ? ' ' : c); return 0xD800; } int h = 0; for(;;c = fileset.get_chr()) { switch (c) { case '0' ... '9': h = (h << 4) | (c - '0'); continue; case 'a' ... 'f': h = (h << 4) | (c - 'a' + 10); continue; case 'A' ... 'F': h = (h << 4) | (c - 'A' + 10); continue; default: if(c > 0xFF) warnp(pos, "hex escape sequence out of range"); fileset.unget_chr(c); return h; } } } // len is 4(\uxxxx) or 8(\UXXXXXXXX) int Lexer::read_universal_char(int len) { Pos pos = get_pos(-2); unsigned int u = 0; for(int i = 0; i < len; ++i) { char c = fileset.get_chr(); switch(c) { case '0' ... '9': u = (u << 4) | (c - '0'); break; case 'a' ... 'f': u = (u << 4) | (c - 'a' + 10); break; case 'A' ... 'F': u = (u << 4) | (c - 'A' + 10); break; default: fileset.unget_chr(c); errorp(get_pos(0), "invalid universal character: %c", c == '\n' ? ' ' : c); return 0xD800; } } // According to C11 6.4.3p2: // A universal character name shall not specify a character whose short identifier is less than // 00A0 other than 0024 ($), 0040 (@), or 0060 (‘), nor one in the range D800 through // DFFF inclusive. if((u >= 0xD800 && u <= 0xDFFF) || (u <= 0xA0 && (u != '$' && u != '@' && u != '`'))) { errorp(pos, "\\%c%0*x is not a valid universal character", (len == 4) ? 'u' : 'U', len, u); return 0xD800; } return u; } /* C11 6.4.2.1: identifier: identifier-nondigit identifier identifier-nondigit identifier digit identifier-nondigit: nondigit universal-character-name other implementation-defined characters */ // doc/lexer/ident.dot std::shared_ptr<Token> Lexer::read_ident(char c) { Pos pos = get_pos(-1); Buffer buf; bool has_invalid_char = false; if(c == '\\' && (fileset.peek() == 'u' || fileset.peek() == 'U')) { int u = read_escape_char(); if(u == 0xD800) has_invalid_char = true; encode_utf8(buf, u); } else { buf.write(c); } while(true) { c = fileset.get_chr(); if(isalnum(c) || c == '_') { buf.write(c); continue; } else if(c == '\\' && (fileset.peek() == 'u' || fileset.peek() == 'U')) { int u = read_escape_char(); if(u == 0xD800) has_invalid_char = true; encode_utf8(buf, u); continue; } fileset.unget_chr(c); buf.write('\0'); if(has_invalid_char) return make_token(TINVALID, pos); return make_ident(buf.data(), pos); } } std::shared_ptr<Token> Lexer::read_number(char c) { Pos pos = get_pos(-1); Buffer buf; buf.write(c); char last = c; while(true) { int c = fileset.get_chr(); bool isfloat = strchr("eEpP", last) && strchr("+-", c); if(!isalnum(c) && c != '.' && !isfloat) { fileset.unget_chr(c); buf.write('\0'); return make_number(buf.data(), pos); } buf.write(c); last = c; } } std::shared_ptr<Token> Lexer::read_char(int enc) { Pos pos = get_pos(-1); int c = fileset.get_chr(); if(c == EOF || c == '\n') { fileset.unget_chr(c); errorp(pos, "missing character and '\''"); return make_token(TINVALID, pos); } int chr = (c == '\\') ? read_escape_char() : c; c = fileset.get_chr(); if(c != '\'') { while(c != '\n') c = fileset.get_chr(); fileset.unget_chr(c); errorp(pos, "missing terminating ' character"); return make_token(TINVALID, pos); } if(chr == 0xD800) // read_hex_char() or read_universal_char() occurs error return make_token(TINVALID, pos); if(enc == ENC_NONE) return make_char((char)chr, enc, pos); else return make_char(chr, enc, pos); } std::shared_ptr<Token> Lexer::read_string(int enc) { Pos pos = get_pos(-1); Buffer buf; bool has_invalid_char = false; while(true) { int c = fileset.get_chr(); if(c == EOF || c == '\n') { fileset.unget_chr(c); errorp(pos, "missing terminating \" character"); return make_token(TINVALID, pos); } if(c == '"') { break; } if(c != '\\') { buf.write(c); continue; } bool isucn = (fileset.peek() == 'u' || fileset.peek() == 'U'); c = read_escape_char(); if(c == 0xD800) has_invalid_char = true; if(isucn) { encode_utf8(buf, c); } else { buf.write(c); } } buf.write('\0'); if(has_invalid_char) // read_hex_char() or read_universal_char() occurs error return make_token(TINVALID, pos); return make_string(buf.data(), buf.size(), enc, pos); } std::shared_ptr<Token> Lexer::read_token() { Pos pos = get_pos(0); if(skip_space()) { return make_token(TSPACE, pos); } pos = get_pos(0); int c = fileset.get_chr(); switch(c) { case '\n': return make_token(TNEWLINE, pos); // identifier case 'a' ... 't': case 'v' ... 'z': // u may be a string suffix case 'A' ... 'K': case 'M' ... 'T': case 'V' ... 'Z': // L and U may be a string suffix case '_': return read_ident(c); case '\\': if(fileset.peek() == 'u' || fileset.peek() == 'U') return read_ident(c); errorp(pos, "stray ‘\\’ in program."); return make_token(TINVALID, pos); case 'u': if(fileset.next('\'')) return read_char(ENC_CHAR16); if(fileset.next('"')) return read_string(ENC_CHAR16); if(fileset.next('8')) { if(fileset.next('"')) return read_string(ENC_UTF8); fileset.unget_chr('8'); } return read_ident(c); case 'U': case 'L': { int enc = (c == 'L') ? ENC_WCHAR : ENC_CHAR32; if(fileset.next('\'')) return read_char(enc); if(fileset.next('"')) return read_string(enc); return read_ident(c); } // number case '0' ... '9': return read_number(c); // character case '\'': return read_char(ENC_NONE); // string case '"': return read_string(ENC_NONE); // punctuator // according to C11 6.4.6p3: // <: :> <% %> %: %:%: behave respectively, the same as: // [ ] { } # ## case '[': case ']': case '(': case ')': case '{': case '}': case '~': case '?': case ';': case ',': return make_keyword(c, pos); case '.': if(isdigit(fileset.peek())) { return read_number(c); } if(fileset.next('.')) { if(fileset.next('.')) return make_keyword(P_ELLIPSIS, pos); return make_ident("..", pos); // not a valid ident, but maybe useful in preprocessor } return make_keyword('.', pos); case '-': if(fileset.next('-')) return make_keyword(P_DEC, pos); if(fileset.next('>')) return make_keyword(P_ARROW, pos); if(fileset.next('=')) return make_keyword(P_ASSIGN_SUB, pos); return make_keyword('-', pos); case '+': if(fileset.next('+')) return make_keyword(P_INC, pos); if(fileset.next('=')) return make_keyword(P_ASSIGN_ADD, pos); return make_keyword('+', pos); case '&': if(fileset.next('&')) return make_keyword(P_LOGAND, pos); if(fileset.next('=')) return make_keyword(P_ASSIGN_AND, pos); return make_keyword('&', pos); case '*': if(fileset.next('=')) return make_keyword(P_ASSIGN_MUL, pos); return make_keyword('*', pos); case '!': if(fileset.next('=')) return make_keyword(P_NE, pos); return make_keyword('!', pos); case '/': if(fileset.next('=')) return make_keyword(P_ASSIGN_DIV, pos); return make_keyword('/', pos); case '%': if(fileset.next('=')) return make_keyword(P_ASSIGN_MOD, pos); if(fileset.next('>')) return make_keyword('}', pos); if(fileset.next(':')) { if(fileset.next('%')) { if(fileset.next(':')) return make_keyword(P_HASHHASH, pos); fileset.unget_chr('%'); } return make_keyword('#', pos); } return make_keyword('%', pos); case '<': if(fileset.next('<')) { if(fileset.next('=')) return make_keyword(P_ASSIGN_SAL, pos); else return make_keyword(P_SAL, pos); } if(fileset.next('=')) return make_keyword(P_LE, pos); if(fileset.next(':')) return make_keyword('[', pos); if(fileset.next('%')) return make_keyword('{', pos); return make_keyword('<', pos); case '>': if(fileset.next('>')) { if(fileset.next('=')) return make_keyword(P_ASSIGN_SAR, pos); else return make_keyword(P_SAR, pos); } if(fileset.next('=')) return make_keyword(P_GE, pos); return make_keyword('>', pos); case '=': if(fileset.next('=')) return make_keyword(P_EQ, pos); return make_keyword('=', pos); case '^': if(fileset.next('=')) return make_keyword(P_ASSIGN_XOR, pos); return make_keyword('^', pos); case '|': if(fileset.next('|')) return make_keyword(P_LOGOR, pos); if(fileset.next('=')) return make_keyword(P_ASSIGN_OR, pos); return make_keyword('|', pos); case ':': if(fileset.next('>')) return make_keyword(']', pos); return make_keyword(':', pos); case '#': if(fileset.next('#')) return make_keyword(P_HASHHASH, pos); return make_keyword('#', pos); // eof case EOF: return make_keyword(TEOF, pos); // error default: errorp(pos, "stray ‘%c’ in program", c); return make_token(TINVALID, pos); } } std::shared_ptr<Token> Lexer::get_token() { if(buffer.size() > 0) { auto tok = buffer.back(); buffer.pop_back(); return tok; } if(fileset.count() == 0) return make_token(TEOF, get_pos(0)); bool bol = (fileset.current_file().col == 1); auto tok = read_token(); if(tok->kind == TSPACE) { tok = read_token(); tok->leading_space = true; } tok->begin_of_line = bol; return tok; } void Lexer::unget_token(std::shared_ptr<Token> token) { if(token->kind == EOF) return; buffer.push_back(token); } std::shared_ptr<Token> Lexer::get_token_from_string(char* str) { fileset.push_string(str); std::shared_ptr<Token> tok = get_token(); next(TNEWLINE); Pos pos = get_pos(0); if(peek_token()->kind != TEOF) { errorp(pos, "unconsumed input: %s", str); error("internal error: stop mcc"); } fileset.pop_file(); return tok; } void Lexer::get_tokens_from_string(char* str, std::vector<std::shared_ptr<Token>>& res) { fileset.push_string(str); while(true) { std::shared_ptr<Token> tok = read_token(); if(tok->kind == TEOF) { fileset.pop_file(); return; } } } std::shared_ptr<Token> Lexer::peek_token() { std::shared_ptr<Token> tok = get_token(); unget_token(tok); return tok; } bool Lexer::next(int kind) { std::shared_ptr<Token> tok = get_token(); if(tok->kind == kind) return true; unget_token(tok); return false; }
[ "707828130@qq.com" ]
707828130@qq.com
f4d087f71a232876b23e1df6a9825c38e1bcbda8
7c7cf9a52095378f5340b61c0a27b10238cecfc9
/Source/RushReborn/Public/AI/BTTask_Idle.cpp
59a719f070c94fab9e809c8a0362f280578b7976
[]
no_license
yjh5246/RushReborn
13e456b64f2b170da81d5ced2645bd8ab3dbcdb1
25584504f3bc8aa6c3c31c77a8b8f89d54581341
refs/heads/master
2023-07-25T19:42:45.394163
2021-05-06T23:31:39
2021-05-06T23:31:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
165
cpp
#include "BTTask_Idle.h" EBTNodeResult::Type UBTTask_Idle::ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory) { return EBTNodeResult::InProgress; }
[ "mustafa.moiz125@gmail.com" ]
mustafa.moiz125@gmail.com
454faec6783aee105f017926519de8f91b7eb386
4f173bf5c7267ba37ea1afbf6f305b796dddc559
/DlgED42Presets.h
bd59c70426c7d04dcafd1e61ce8ff0afa5b463fd
[]
no_license
antoine83/sicomex
d50d50c96222567a63720db6831901b79782e3f8
260f3b835a0050a321f2bf5bbe130a932476f154
refs/heads/master
2020-12-24T20:24:45.306792
2017-03-26T16:25:16
2017-03-26T16:25:16
86,247,091
0
0
null
null
null
null
UTF-8
C++
false
false
1,696
h
#if !defined(AFX_DLGED42PRESETS_H__064461CF_9249_4A3F_BB20_B93B3C180F1A__INCLUDED_) #define AFX_DLGED42PRESETS_H__064461CF_9249_4A3F_BB20_B93B3C180F1A__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // DlgED42Presets.h : header file // #include "Equip\EquipED42.h" #include "DlgED42PresetsTab.h" ///////////////////////////////////////////////////////////////////////////// // CDlgED42Presets dialog class CDlgED42Presets : public CDialog { // Construction public: CDlgED42Presets(CEquipED42 * eqp = NULL,CWnd* pParent = NULL); // standard constructor ~CDlgED42Presets(); void CDlgED42Presets::LoadData(); void CDlgED42Presets::SaveData(); CDlgED42PresetsTab* CDlgED42Presets::getTab(); // Dialog Data //{{AFX_DATA(CDlgED42Presets) enum { IDD = IDD_ED42_PRESETS }; CComboBox c_type; CComboBox c_preset; // NOTE: the ClassWizard will add data members here //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CDlgED42Presets) protected: virtual BOOL OnInitDialog(); virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: CEquipED42 * eqp; //CDlgED42PresetsTab* m_presetTab; // Generated message map functions //{{AFX_MSG(CDlgED42Presets) afx_msg void OnSelchangePreset(); afx_msg void OnSelchangeType(); //}}AFX_MSG DECLARE_MESSAGE_MAP() private : string presetSelected; public: CDlgED42PresetsTab* m_presetTab; }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_DLGED42PRESETS_H__064461CF_9249_4A3F_BB20_B93B3C180F1A__INCLUDED_)
[ "antoine.linux@sfr.fr" ]
antoine.linux@sfr.fr
71c13a69c14f0155c8e412eaa1b1a1ad32479fb5
723c87bfb1cf7aba01307c04bb1ea81a28bac5bb
/2020/Apr/0421cheese.cpp
2924b3fa9b1e0bb517d53f0ec5786aa58a4e43c1
[]
no_license
qlqnf16/algorithms
3174b9503e2fa320bbb2aee09a93cea4c6f9818e
21f530d1e0f4a0ce3c2f51460e42ab0c03b9854e
refs/heads/master
2021-06-13T00:37:21.932439
2021-05-06T14:30:05
2021-05-06T14:30:05
188,745,750
0
0
null
null
null
null
UTF-8
C++
false
false
1,746
cpp
#include <stdio.h> #define MAX 1010 int H, W, N; char map[MAX][MAX]; int visit[MAX][MAX]; int cheeseLocs[10][2]; int dir[][4] = {{0, 0, 1, -1}, {1, -1, 0, 0}}; struct queue { int c; int r; int t; }; queue que[MAX*MAX]; int wp, rp; void pop() {rp++;} queue front() { return que[rp]; } int empty() { return wp == rp; } void push(int c, int r, int t, int n) { if (visit[c][r] > n) return; if (map[c][r] != '.') return; visit[c][r] ++; que[wp].c = c; que[wp].r = r; que[wp].t = t; wp ++; } void preAct() { for (int i = 1; i <= H; i++) { for (int j = 1; j <= W; j++) { if (map[i][j] == 'S') { cheeseLocs[0][0] = i; cheeseLocs[0][1] = j; map[i][j] = '.'; } if (map[i][j] <= '9' && map[i][j] >= '1') { cheeseLocs[map[i][j]-'0'][0] = i; cheeseLocs[map[i][j]-'0'][1] = j; map[i][j] = '.'; } } } } int bfs(int c, int r, int n) { wp = rp = 0; push(c, r, 0, n); while (!empty()) { queue cur = front(); pop(); if (cur.c == cheeseLocs[n+1][0] && cur.r == cheeseLocs[n+1][1]) return cur.t; for (int i = 0; i < 4; i++) { push(cur.c + dir[0][i], cur.r + dir[1][i], cur.t+1, n); } } return -1; } int solve() { int route = 0; preAct(); for (int i = 0; i < N; i++) { route += bfs(cheeseLocs[i][0], cheeseLocs[i][1], i); } return route; } int main() { int ans; scanf("%d %d %d", &H, &W, &N); for (int i = 1; i <= H; i++) { scanf("%s", &map[i][1]); } ans = solve(); printf("%d", ans); return 0; }
[ "lee.jeongmin1027@likelion.org" ]
lee.jeongmin1027@likelion.org
65065d2fb1e7da42ee3406d1f1e58b28f8e6c895
064742f5d72eed8e0a269cf7bdc1e6019973b237
/SessionDescriptorGenericGrammar.hpp
7c067d2bbaaac5dee7158a8f153666b9ddb3091e
[]
no_license
dries/WebP2P
42e82fcf291a6fbc2b490bc0a9f6acafef374368
5497fd4fd7493fa3bcc493807d1b65f0a21e8cee
refs/heads/master
2021-04-12T04:57:40.784303
2011-01-11T11:54:43
2011-01-11T11:54:43
1,144,692
0
1
null
null
null
null
UTF-8
C++
false
false
1,816
hpp
/** * This file is part of WebP2P. * * WebP2P is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WebP2P is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with WebP2P. If not, see <http://www.gnu.org/licenses/>. * * Filename: SessionDescriptorGenericGrammar.hpp * Author(s): Dries Staelens * Copyright: Copyright (c) 2010 Dries Staelens * Description: Definition for the RFC 4566 SDP grammar rules. * See: http://tools.ietf.org/html/rfc4566 **/ #pragma once /* STL includes */ #include <string> /* Boost includes */ #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/qi_repeat.hpp> #include <boost/spirit/include/qi_binary.hpp> /* WebP2P includes */ #include "ABNFCoreGrammar.hpp" struct SessionDescriptorGenericGrammar { /* external grammars */ ABNFCoreGrammar abnf; /* rules for this grammar */ boost::spirit::qi::rule<std::string::const_iterator, std::string()> unicast_address, multicast_address, IP4_multicast, m1, IP6_multicast, bm, ttl, FQDN, IP4_address, bu, IP6_address, hexpart, hexseq, hex4, extn_addr, text, byte_string, non_ws_string, token, email_safe, integer, alpha_numeric, POS_DIGIT, decimal_uchar, du1, du2, du3, du4, du5, bm1, bm2, bm3, bm4, bm5, bu1, bu2, bu3, bu4, bu5; SessionDescriptorGenericGrammar(); };
[ "dries.staelens@gmail.com" ]
dries.staelens@gmail.com
96ffcf41487bbc28cebe1cd10c9e25e02879f2f3
8476eb45fe9dfd43818245e17a1c661b88e69400
/CustomCodes/utils/funcs/KinDyn200511_221619/kin/mex/dR_RightHip_mex.hh
2d1df617291e6dc555e2d19c976055e80eef3643
[]
no_license
prem-chand/Cassie_Controller_AngularMomentum
f8c7521bc990b42d8ff098759e04637afaca2cc1
c784242f1a949525accb8f9e9fe4a53feb0fba87
refs/heads/main
2023-08-15T02:09:23.748744
2021-09-21T21:43:24
2021-09-21T21:43:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
907
hh
/* * Automatically Generated from Mathematica. * Mon 11 May 2020 22:28:04 GMT-04:00 */ #ifndef DR_RIGHTHIP_MEX_HH #define DR_RIGHTHIP_MEX_HH #ifdef MATLAB_MEX_FILE // No need for external definitions #else // MATLAB_MEX_FILE #include "math2mat.hpp" #include "mdefs.hpp" namespace SymExpression { void dR_RightHip_mex_raw(double *p_output1, const double *var1,const double *var2); inline void dR_RightHip_mex(Eigen::MatrixXd &p_output1, const Eigen::VectorXd &var1,const Eigen::VectorXd &var2) { // Check // - Inputs assert_size_matrix(var1, 20, 1); assert_size_matrix(var2, 20, 1); // - Outputs assert_size_matrix(p_output1, 3, 3); // set zero the matrix p_output1.setZero(); // Call Subroutine with raw data dR_RightHip_mex_raw(p_output1.data(), var1.data(),var2.data()); } } #endif // MATLAB_MEX_FILE #endif // DR_RIGHTHIP_MEX_HH
[ "gyk199305@gmail.com" ]
gyk199305@gmail.com
d641f849ab0e2da5e906ccc356b36b50ef6c6014
aa4899ac6c2b1eb0eb22d15953e18f7d1cdd4ee4
/code/render/coregraphics/preshader.cc
8ad3d23f7ca7df0705973758a3f41f3e6a1d20fd
[]
no_license
dzw/stellar2008
bc2647f2a9eea03dea233335af66e9a916d2b1e3
5ff28d25b8cafdfccc79fa7e916b5cdc4f36b4ac
refs/heads/master
2021-01-10T12:26:08.853827
2012-01-04T17:15:42
2012-01-04T17:15:42
36,920,393
0
0
null
null
null
null
UTF-8
C++
false
false
1,397
cc
//------------------------------------------------------------------------------ // preshader.cc // (C) 2007 Radon Labs GmbH //------------------------------------------------------------------------------ #include "stdneb.h" #include "coregraphics/preshader.h" #include "coregraphics/shaderinstance.h" namespace CoreGraphics { ImplementClass(CoreGraphics::PreShader, 'PSHD', Core::RefCounted); //------------------------------------------------------------------------------ /** */ PreShader::PreShader() { // empty } //------------------------------------------------------------------------------ /** */ PreShader::~PreShader() { n_assert(!this->shaderInstance.isvalid()); } //------------------------------------------------------------------------------ /** */ void PreShader::OnAttach(const Ptr<ShaderInstance>& shdInst) { n_assert(shdInst.isvalid()); n_assert(!this->shaderInstance.isvalid()); this->shaderInstance = shdInst; } //------------------------------------------------------------------------------ /** */ void PreShader::OnDetach() { n_assert(this->shaderInstance.isvalid()); this->shaderInstance = 0; } //------------------------------------------------------------------------------ /** */ void PreShader::OnApply() { // empty, override in subclass } } // namespace CoreGraphics
[ "ctuoMail@gmail.com" ]
ctuoMail@gmail.com
f40ea10ecf0a67e96fe4a6d953bf5549371aef42
9f520bcbde8a70e14d5870fd9a88c0989a8fcd61
/pitzDaily/871/uniform/time
441e9ea708009638cfcacdebbeed1f57e3b921bc
[]
no_license
asAmrita/adjoinShapOptimization
6d47c89fb14d090941da706bd7c39004f515cfea
079cbec87529be37f81cca3ea8b28c50b9ceb8c5
refs/heads/master
2020-08-06T21:32:45.429939
2019-10-06T09:58:20
2019-10-06T09:58:20
213,144,901
1
0
null
null
null
null
UTF-8
C++
false
false
968
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: v1806 | | \\ / A nd | Web: www.OpenFOAM.com | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "871/uniform"; object time; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // value 871; name "871"; index 871; deltaT 1; deltaT0 1; // ************************************************************************* //
[ "as998@snu.edu.in" ]
as998@snu.edu.in
4692027d4b7a7a49159d711a0cd44066cd1e8625
a3585e97d02ed29a55c7353cb07bdcc40e080c7b
/Model/MaizePioneer/PlantInterface.cpp
0f961d9a4dd800c61db6e903fbb0d5264f1a169c
[]
no_license
APSIMInitiative/APSIMClassic
d26a44585c57802f15b1f9a0641d2c21239905b5
2dc1d3475e340e45da473f1daf5e66e98f448361
refs/heads/master
2023-07-08T14:03:45.389036
2023-06-25T21:30:32
2023-06-25T21:30:32
130,158,232
32
47
null
2023-06-25T21:30:53
2018-04-19T04:17:59
C#
UTF-8
C++
false
false
550
cpp
#include <ComponentInterface2/ScienceAPI2.h> using namespace std; #include "PlantInterface.h" using namespace Maize; //----------------------------------------------------------------------------- // Create an instance of the Plant module //----------------------------------------------------------------------------- extern "C" EXPORT PlantInterface* STDCALL createComponent(ScienceAPI2 & api) { return new PlantInterface(api); } extern "C" void EXPORT STDCALL deleteComponent(PlantInterface* component) { delete component; }
[ "drew.holzworth@csiro.au" ]
drew.holzworth@csiro.au
613ebe3932a687c835d663d345d5662cc6841bbd
a0e17c72de4cc6c7a58edb3b4a73766addca95e5
/.ccls-cache/@Users@rampa2510@Desktop@algo/ArrayProblems@genSubArr.cpp
558c2de60fba63e5037dd8d4632eff1c198e02bc
[]
no_license
rampa2510/dsa
60d7da33eb2a566da54112fcee09539003ddecac
4aee4c939eff5bac044c499f1a4f0b169f9a6109
refs/heads/main
2023-04-15T18:16:24.920370
2021-04-20T09:22:56
2021-04-20T09:22:56
335,856,168
0
0
null
null
null
null
UTF-8
C++
false
false
278
cpp
#include <iostream> using namespace std; int main() { int a[5] = {1, 2, 3, 4, 5}, n = 5; for (size_t i = 0; i < n; i++) { for (size_t j = i; j < n; j++) { for (size_t k = i; k <= j; k++) cout << a[k] << ","; cout << "\n"; } } return 0; }
[ "iamram2510@gmail.com" ]
iamram2510@gmail.com
d19bfcd6e0bfb967d7c0b2e32b810322fcefc750
a92708d28a0ec6ddf083ae42a47e35f2121f0eba
/test/xts/acts/kernel_lite/util_check_posix/src/ActsUtilCheckApiTest.cpp
80446c1a6686c28a00c6e061a10281f5a40e9fc4
[ "Apache-2.0" ]
permissive
km1042412/my-OHOS
322eca402c28eb68272c58214243ecb8a0960b3c
3c74564d9c6c3b33b836c6a3cd1a6dbc6d4bc18e
refs/heads/main
2023-03-28T05:36:56.244181
2021-03-16T06:25:01
2021-03-16T06:25:01
348,194,410
1
0
null
null
null
null
UTF-8
C++
false
false
29,252
cpp
/* * Copyright (c) 2020 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <ctype.h> #include <math.h> #include <stropts.h> #include "gtest/gtest.h" #include "log.h" #include "utils.h" using namespace testing::ext; class ActsUtilCheckApiTest : public testing::Test { protected: // SetUpTestCase: Testsuit setup, run before 1st testcase static void SetUpTestCase(void) { } // TearDownTestCase: Testsuit teardown, run after last testcase static void TearDownTestCase(void) { } // Testcase setup virtual void SetUp() { } // Testcase teardown virtual void TearDown() { } }; /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISALNUM_0100 * @tc.name test isalnum api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsalnum0100, TestSize.Level1) { int paraVal; int returnVal; paraVal = '2'; returnVal = isalnum(paraVal); LOGD(" isalnum returnVal:='%d'\n", returnVal); ASSERT_TRUE(returnVal != 0) << "ErrInfo: isalnum returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISALNUM_0200 * @tc.name test isalnum api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsalnum0200, TestSize.Level1) { int paraVal; int returnVal; paraVal = 'z'; returnVal = isalnum(paraVal); LOGD(" isalnum returnVal:='%d'\n", returnVal); ASSERT_TRUE(returnVal != 0) << "ErrInfo: isalnum returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISALNUM_0300 * @tc.name test isalnum api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsalnum0300, TestSize.Level1) { int paraVal; int returnVal; paraVal = 'Z'; returnVal = isalnum(paraVal); LOGD(" isalnum returnVal:='%d'\n", returnVal); ASSERT_TRUE(returnVal != 0) << "ErrInfo: isalnum returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISALNUM_0400 * @tc.name test isalnum api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsalnum0400, TestSize.Level1) { int paraVal; int returnVal; paraVal = ' '; returnVal = isalnum(paraVal); LOGD(" isalnum returnVal:='%d'\n", returnVal); ASSERT_TRUE(0 == returnVal) << "ErrInfo: isalnum returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISALNUM_0500 * @tc.name test isalnum api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsalnum0500, TestSize.Level1) { int paraVal; int returnVal; paraVal = '\n'; returnVal = isalnum(paraVal); LOGD(" isalnum returnVal:='%d'\n", returnVal); ASSERT_TRUE(0 == returnVal) << "ErrInfo: isalnum returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISALPHA_1100 * @tc.name test isalpha api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsalpha1100, TestSize.Level1) { int paraVal; int returnVal; paraVal = 'z'; returnVal = isalpha(paraVal); LOGD(" isalpha returnVal:='%d'\n", returnVal); ASSERT_TRUE(returnVal != 0) << "ErrInfo: isalpha returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISALPHA_1200 * @tc.name test isalpha api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsalpha1200, TestSize.Level1) { int paraVal; int returnVal; paraVal = 'Z'; returnVal = isalpha(paraVal); LOGD(" isalpha returnVal:='%d'\n", returnVal); ASSERT_TRUE(returnVal != 0) << "ErrInfo: isalpha returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISALPHA_1300 * @tc.name test isalpha api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsalpha1300, TestSize.Level1) { int paraVal; int returnVal; paraVal = ' '; returnVal = isalpha(paraVal); LOGD(" isalpha returnVal:='%d'\n", returnVal); ASSERT_TRUE(0 == returnVal) << "ErrInfo: isalpha returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISALPHA_1400 * @tc.name test isalpha api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsalpha1400, TestSize.Level1) { int paraVal; int returnVal; paraVal = '\n'; returnVal = isalpha(paraVal); LOGD(" isalpha returnVal:='%d'\n", returnVal); ASSERT_TRUE(0 == returnVal) << "ErrInfo: isalpha returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISASCII_1900 * @tc.name test isascii api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsascii1900, TestSize.Level1) { int paraVal; int returnVal; paraVal = 'z'; returnVal = isascii(paraVal); LOGD(" isascii returnVal:='%d'\n", returnVal); ASSERT_TRUE(returnVal != 0) << "ErrInfo: isascii returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISASCII_2000 * @tc.name test isascii api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsascii2000, TestSize.Level1) { int paraVal; int returnVal; paraVal = 'Z'; returnVal = isascii(paraVal); LOGD(" isascii returnVal:='%d'\n", returnVal); ASSERT_TRUE(returnVal != 0) << "ErrInfo: isascii returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISASCII_2100 * @tc.name test isascii api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsascii2100, TestSize.Level1) { int paraVal; int returnVal; paraVal = '~'; returnVal = isascii(paraVal); LOGD(" isascii returnVal:='%d'\n", returnVal); ASSERT_TRUE(returnVal != 0) << "ErrInfo: isascii returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISASCII_2200 * @tc.name test isascii api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsascii2200, TestSize.Level1) { int paraVal; int returnVal; paraVal = 128; returnVal = isascii(paraVal); LOGD(" isascii returnVal:='%d'\n", returnVal); ASSERT_TRUE(0 == returnVal) << "ErrInfo: isascii returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISASTREAM_2300 * @tc.name test isastream api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsastream2300, TestSize.Level1) { int paraVal; int returnVal; paraVal = 128; returnVal = isastream(paraVal); LOGD(" isastream returnVal:='%d'\n", returnVal); ASSERT_TRUE(-1 == returnVal) << "ErrInfo: isastream returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISATTY_2400 * @tc.name test isatty api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsatty2400, TestSize.Level1) { int paraVal; int returnVal; paraVal = 128; returnVal = isatty(paraVal); LOGD(" isatty returnVal:='%d'\n", returnVal); ASSERT_TRUE(0 == returnVal) << "ErrInfo: isatty returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISBLANK_2500 * @tc.name test isblank api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsblank2500, TestSize.Level1) { int paraVal; int returnVal; paraVal = ' '; returnVal = isblank(paraVal); LOGD(" isblank returnVal:='%d'\n", returnVal); ASSERT_TRUE(returnVal != 0) << "ErrInfo: isblank returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISBLANK_2600 * @tc.name test isblank api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsblank2600, TestSize.Level1) { int paraVal; int returnVal; paraVal = 'A'; returnVal = isblank(paraVal); LOGD(" isblank returnVal:='%d'\n", returnVal); ASSERT_TRUE(0 == returnVal) << "ErrInfo: isblank returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISCNTRL_2900 * @tc.name test iscntrl api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIscntrl2900, TestSize.Level1) { int paraVal; int returnVal; paraVal = '\n'; returnVal = iscntrl(paraVal); LOGD(" iscntrl returnVal:='%d'\n", returnVal); ASSERT_TRUE(returnVal != 0) << "ErrInfo: iscntrl returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISCNTRL_3000 * @tc.name test iscntrl api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIscntrl3000, TestSize.Level1) { int paraVal; int returnVal; paraVal = 'A'; returnVal = iscntrl(paraVal); LOGD(" iscntrl returnVal:='%d'\n", returnVal); ASSERT_TRUE(0 == returnVal) << "ErrInfo: iscntrl returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISDIGIT_3300 * @tc.name test isdigit api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsdigit3300, TestSize.Level1) { int paraVal; int returnVal; paraVal = '3'; returnVal = isdigit(paraVal); LOGD(" isdigit returnVal:='%d'\n", returnVal); ASSERT_TRUE(returnVal != 0) << "ErrInfo: isdigit returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISDIGIT_3400 * @tc.name test isdigit api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsdigitl3400, TestSize.Level1) { int paraVal; int returnVal; paraVal = 'a'; returnVal = isdigit(paraVal); LOGD(" isdigit returnVal:='%d'\n", returnVal); ASSERT_TRUE(0 == returnVal) << "ErrInfo: isdigit returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISDIGIT_3500 * @tc.name test isdigit api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsdigitl3500, TestSize.Level1) { int paraVal; int returnVal; paraVal = '\n'; returnVal = isdigit(paraVal); LOGD(" isdigit returnVal:='%d'\n", returnVal); ASSERT_TRUE(0 == returnVal) << "ErrInfo: isdigit returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISDIGIT_3600 * @tc.name test isdigit api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsdigit3600, TestSize.Level1) { int paraVal; int returnVal; paraVal = ' '; returnVal = isdigit(paraVal); LOGD(" isdigit returnVal:='%d'\n", returnVal); ASSERT_TRUE(0 == returnVal) << "ErrInfo: isdigit returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISFINITE_4100 * @tc.name test isfinite api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsfinite4100, TestSize.Level1) { double paraVal; int returnVal; paraVal = ' '; returnVal = isfinite(paraVal); LOGD(" isfinite returnVal:='%d'\n", returnVal); ASSERT_TRUE(returnVal != 0) << "ErrInfo: isfinite returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISFINITE_4200 * @tc.name test isfinite api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsfinite4200, TestSize.Level1) { double paraVal; int returnVal; paraVal = 3.1415926; returnVal = isfinite(paraVal); LOGD(" isfinite returnVal:='%d'\n", returnVal); ASSERT_TRUE(returnVal != 0) << "ErrInfo: isfinite returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISFINITE_4300 * @tc.name test isfinite api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsfinite4300, TestSize.Level1) { double paraVal; int returnVal; paraVal = 1.26e3; returnVal = isfinite(paraVal); LOGD(" isfinite returnVal:='%d'\n", returnVal); ASSERT_TRUE(returnVal != 0) << "ErrInfo: isfinite returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISGRAPH_4400 * @tc.name test isgraph api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsgraph4400, TestSize.Level1) { double paraVal; int returnVal; paraVal = 'A'; returnVal = isgraph(paraVal); LOGD(" isgraph returnVal:='%d'\n", returnVal); ASSERT_TRUE(returnVal != 0) << "ErrInfo: isgraph returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISGRAPH_4500 * @tc.name test isgraph api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsgraph4500, TestSize.Level1) { double paraVal; int returnVal; paraVal = 'z'; returnVal = isgraph(paraVal); LOGD(" isgraph returnVal:='%d'\n", returnVal); ASSERT_TRUE(returnVal != 0) << "ErrInfo: isgraph returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISGRAPH_4600 * @tc.name test isgraph api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsgraph4600, TestSize.Level1) { double paraVal; int returnVal; paraVal = '\n'; returnVal = isgraph(paraVal); LOGD(" isgraph returnVal:='%d'\n", returnVal); ASSERT_TRUE(0 == returnVal) << "ErrInfo: isgraph returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISGRAPH_4700 * @tc.name test isgraph api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsgraph4700, TestSize.Level1) { double paraVal; int returnVal; paraVal = ' '; returnVal = isgraph(paraVal); LOGD(" isgraph returnVal:='%d'\n", returnVal); ASSERT_TRUE(0 == returnVal) << "ErrInfo: isgraph returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISGREATER_5200 * @tc.name test isgreater api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsgreater5200, TestSize.Level1) { double paraVal1; double paraVal2; int returnVal; paraVal1 = 1.1; paraVal2 = 2.1; returnVal = isgreater(paraVal1, paraVal2); LOGD(" isgreater returnVal:='%d'\n", returnVal); ASSERT_TRUE(0 == returnVal) << "ErrInfo: isgreater returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISGREATER_5300 * @tc.name test isgreater api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsgreater5300, TestSize.Level1) { double paraVal1; double paraVal2; int returnVal; paraVal1 = 2.1; paraVal2 = 1.1; returnVal = isgreater(paraVal1, paraVal2); LOGD(" isgreater returnVal:='%d'\n", returnVal); ASSERT_TRUE(returnVal != 0) << "ErrInfo: isgreater returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISGREATER_5400 * @tc.name test isgreater api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsgreater5400, TestSize.Level1) { double paraVal1; double paraVal2; int returnVal; paraVal1 = 2.1; paraVal2 = 2.1; returnVal = isgreater(paraVal1, paraVal2); LOGD(" isgreater returnVal:='%d'\n", returnVal); ASSERT_TRUE(0 == returnVal) << "ErrInfo: isgreater returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISGREATEREQUAL_5500 * @tc.name test isgreaterequal api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsgreaterequal5500, TestSize.Level1) { double paraVal1; double paraVal2; int returnVal; paraVal1 = 1.1; paraVal2 = 2.1; returnVal = isgreaterequal(paraVal1, paraVal2); LOGD(" isgreaterequal returnVal:='%d'\n", returnVal); ASSERT_TRUE(0 == returnVal) << "ErrInfo: isgreaterequal returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISGREATEREQUAL_5600 * @tc.name test isgreaterequal api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsgreaterequal5600, TestSize.Level1) { double paraVal1; double paraVal2; int returnVal; paraVal1 = 2.1; paraVal2 = 1.1; returnVal = isgreaterequal(paraVal1, paraVal2); LOGD(" isgreaterequal returnVal:='%d'\n", returnVal); ASSERT_TRUE(returnVal != 0) << "ErrInfo: isgreaterequal returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISGREATEREQUAL_5700 * @tc.name test isgreaterequal api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsgreaterequal5700, TestSize.Level1) { double paraVal1; double paraVal2; int returnVal; paraVal1 = 2.1; paraVal2 = 2.1; returnVal = isgreaterequal(paraVal1, paraVal2); LOGD(" isgreaterequal returnVal:='%d'\n", returnVal); ASSERT_TRUE(returnVal != 0) << "ErrInfo: isgreaterequal returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISINF_5800 * @tc.name test isinf api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsinf5800, TestSize.Level1) { double paraVal; int returnVal; paraVal = INFINITY; returnVal = isinf(paraVal); LOGD(" isinf returnVal:='%d'\n", returnVal); ASSERT_TRUE(1 == returnVal) << "ErrInfo: isinf returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISLESSEQUAL_5900 * @tc.name test islessequal api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIslessequal5900, TestSize.Level1) { double paraVal1; double paraVal2; int returnVal; paraVal1 = 1.1; paraVal2 = 2.1; returnVal = islessequal(paraVal1, paraVal2); LOGD(" islessequal returnVal:='%d'\n", returnVal); ASSERT_TRUE(0 != returnVal) << "ErrInfo: islessequal returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISLESSEQUAL_6000 * @tc.name test islessequal api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIslessequal6000, TestSize.Level1) { double paraVal1; double paraVal2; int returnVal; paraVal1 = 2.1; paraVal2 = 1.1; returnVal = islessequal(paraVal1, paraVal2); LOGD(" islessequal returnVal:='%d'\n", returnVal); ASSERT_TRUE(0 == returnVal) << "ErrInfo: islessequal returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISLESSEQUAL_6100 * @tc.name test islessequal api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIslessequal6100, TestSize.Level1) { double paraVal1; double paraVal2; int returnVal; paraVal1 = 2.1; paraVal2 = 2.1; returnVal = islessequal(paraVal1, paraVal2); LOGD(" islessequal returnVal:='%d'\n", returnVal); ASSERT_TRUE(returnVal != 0) << "ErrInfo: islessequal returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISLESSGREATER_6200 * @tc.name test islessgreater api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIslessgreater6200, TestSize.Level1) { double paraVal1; double paraVal2; int returnVal; paraVal1 = 2.1; paraVal2 = 2.1; returnVal = islessgreater(paraVal1, paraVal2); LOGD(" islessgreater returnVal:='%d'\n", returnVal); ASSERT_TRUE(0 == returnVal) << "ErrInfo: islessgreater returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISLESSGREATER_6300 * @tc.name test islessgreater api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIslessgreater6300, TestSize.Level1) { double paraVal1; double paraVal2; int returnVal; paraVal1 = 1.1; paraVal2 = 2.1; returnVal = islessgreater(paraVal1, paraVal2); LOGD(" islessgreater returnVal:='%d'\n", returnVal); ASSERT_TRUE(returnVal != 0) << "ErrInfo: islessgreater returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISLESSGREATER_6400 * @tc.name test islessgreater api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIslessgreater6400, TestSize.Level1) { double paraVal1; double paraVal2; int returnVal; paraVal1 = 3.1; paraVal2 = 2.1; returnVal = islessgreater(paraVal1, paraVal2); LOGD(" islessgreater returnVal:='%d'\n", returnVal); ASSERT_TRUE(returnVal != 0) << "ErrInfo: islessgreater returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISLOWER_6500 * @tc.name test islower api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIslower6500, TestSize.Level1) { char paraChar; int returnVal; paraChar = 'A'; returnVal = islower(paraChar); LOGD(" islower c:='%c', returnVal:='%c'\n", paraChar, returnVal); ASSERT_TRUE(0 == returnVal) << "ErrInfo: islower c:='" << paraChar << "', returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISLOWER_6600 * @tc.name test islower api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIslower6600, TestSize.Level1) { char paraChar; int returnVal; paraChar = 'a'; returnVal = islower(paraChar); LOGD(" islower c:='%c', returnVal:='%c'\n", paraChar, returnVal); ASSERT_TRUE(returnVal != 0) << "ErrInfo: islower c:='" << paraChar << "', returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISLOWER_6700 * @tc.name test islower api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIslower6700, TestSize.Level1) { char paraChar; int returnVal; paraChar = '5'; returnVal = islower(paraChar); LOGD(" islower c:='%c', returnVal:='%c'\n", paraChar, returnVal); ASSERT_TRUE(0 == returnVal) << "ErrInfo: islower c:='" << paraChar << "', returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISLOWER_6800 * @tc.name test islower api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIslower6800, TestSize.Level1) { char paraChar; int returnVal; paraChar = ' '; returnVal = islower(paraChar); LOGD(" islower c:='%c', returnVal:='%c'\n", paraChar, returnVal); ASSERT_TRUE(0 == returnVal) << "ErrInfo: islower c:='" << paraChar << "', returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISNAN_7300 * @tc.name test isnan api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsnan7300, TestSize.Level1) { double paraVal; int returnVal; paraVal = NAN; returnVal = isnan(paraVal); LOGD(" isnan returnVal:='%d'\n", returnVal); ASSERT_TRUE(returnVal != 0) << "ErrInfo: isnan returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISNORMAL_7400 * @tc.name test isnormal api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsnormal7400, TestSize.Level1) { double paraVal; int returnVal; paraVal = FP_NORMAL; returnVal = isnormal(paraVal); LOGD(" isnormal returnVal:='%d'\n", returnVal); ASSERT_TRUE(returnVal != 0) << "ErrInfo: isnormal returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISNORMAL_7500 * @tc.name test isnormal api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsnormal7500, TestSize.Level1) { double paraVal; int returnVal; paraVal = NAN; returnVal = isnormal(paraVal); LOGD(" isnormal returnVal:='%d'\n", returnVal); ASSERT_TRUE(0 == returnVal) << "ErrInfo: isnormal returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISNORMAL_7600 * @tc.name test isnormal api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsnormal7600, TestSize.Level1) { double paraVal; int returnVal; paraVal = 2.1; returnVal = isnormal(paraVal); LOGD(" isnormal returnVal:='%d'\n", returnVal); ASSERT_TRUE(returnVal != 0) << "ErrInfo: isnormal returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISPRINT_7700 * @tc.name test isprint api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsprint7700, TestSize.Level1) { char paraVal; int returnVal; paraVal = 'a'; returnVal = isprint(paraVal); LOGD(" isprint returnVal:='%d'\n", returnVal); ASSERT_TRUE(returnVal != 0) << "ErrInfo: isprint returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISPRINT_7800 * @tc.name test isprint api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsprint7800, TestSize.Level1) { char paraVal; int returnVal; paraVal = ' '; returnVal = isprint(paraVal); LOGD(" isprint returnVal:='%d'\n", returnVal); ASSERT_TRUE(returnVal != 0) << "ErrInfo: isprint returnVal:='" << returnVal << "'"; } /** * @tc.number SUB_KERNEL_UTIL_CHECK_ISPRINT_7900 * @tc.name test isprint api * @tc.desc [C- SOFTWARE -0200] * @tc.size SMALL * @tc.type FUNC */ HWTEST_F(ActsUtilCheckApiTest, testIsprint7900, TestSize.Level1) { char paraVal; int returnVal; paraVal = '\n'; returnVal = isprint(paraVal); LOGD(" isprint returnVal:='%d'\n", returnVal); ASSERT_TRUE(0 == returnVal) << "ErrInfo: isprint returnVal:='" << returnVal << "'"; }
[ "1042412750@qq.com" ]
1042412750@qq.com
f460abe9c72d8c657dd3c67f2b4b1b63d887fa43
2b2bc705055c3ec1f70a0f3d953f21f395eeb0d8
/Source/source/mob_fsms/ship_fsm.cpp
703e564c588d3937c56d63a68053ae09391a0025
[ "MIT" ]
permissive
Pablutnio/Pikifen
a058cefd37bb8d63989486c07d4c397f3e169909
724af6e554e59447b4362bb920c46a6f102efe35
refs/heads/master
2023-01-02T06:25:05.643701
2020-10-29T20:34:25
2020-10-29T20:34:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,560
cpp
/* * Copyright (c) Andre 'Espyo' Silva 2013. * The following source file belongs to the open-source project Pikifen. * Please read the included README and LICENSE files for more information. * Pikmin is copyright (c) Nintendo. * * === FILE DESCRIPTION === * Ship finite state machine logic. */ #include "ship_fsm.h" #include "../functions.h" #include "../game.h" #include "../mobs/resource.h" #include "../mobs/ship.h" #include "../particle.h" #include "../utils/string_utils.h" /* ---------------------------------------------------------------------------- * Creates the finite state machine for the ship's logic. * typ: * Mob type to create the finite state machine for. */ void ship_fsm::create_fsm(mob_type* typ) { easy_fsm_creator efc; efc.new_state("idling", SHIP_STATE_IDLING); { efc.new_event(MOB_EV_ON_ENTER); { efc.run(ship_fsm::set_anim); } efc.new_event(MOB_EV_RECEIVE_DELIVERY); { efc.run(ship_fsm::receive_mob); } } typ->states = efc.finish(); typ->first_state_nr = fix_states(typ->states, "idling"); //Check if the number in the enum and the total match up. engine_assert( typ->states.size() == N_SHIP_STATES, i2s(typ->states.size()) + " registered, " + i2s(N_SHIP_STATES) + " in enum." ); } /* ---------------------------------------------------------------------------- * When a ship finishes receiving a mob carried by Pikmin. * m: * The mob. * info1: * Pointer to the mob. * info2: * Unused. */ void ship_fsm::receive_mob(mob* m, void* info1, void* info2) { engine_assert(info1 != NULL, m->print_state_history()); mob* delivery = (mob*) info1; ship* s_ptr = (ship*) m; switch(delivery->type->category->id) { case MOB_CATEGORY_TREASURES: { break; } case MOB_CATEGORY_RESOURCES: { resource* r_ptr = (resource*) delivery; if( r_ptr->res_type->delivery_result == RESOURCE_DELIVERY_RESULT_ADD_POINTS ) { } else if( r_ptr->res_type->delivery_result == RESOURCE_DELIVERY_RESULT_INCREASE_INGREDIENTS ) { size_t type_nr = r_ptr->res_type->spray_to_concoct; game.states.gameplay->spray_stats[type_nr].nr_ingredients++; if( game.states.gameplay->spray_stats[type_nr].nr_ingredients >= game.spray_types[type_nr].ingredients_needed ) { game.states.gameplay->spray_stats[type_nr].nr_ingredients -= game.spray_types[type_nr].ingredients_needed; game.states.gameplay->spray_stats[type_nr].nr_sprays++; } } break; } } particle p( PARTICLE_TYPE_BITMAP, s_ptr->beam_final_pos, s_ptr->z + s_ptr->height, 24, 1.5, PARTICLE_PRIORITY_MEDIUM ); p.bitmap = game.sys_assets.bmp_smoke; particle_generator pg(0, p, 15); pg.number_deviation = 5; pg.angle = 0; pg.angle_deviation = TAU / 2; pg.total_speed = 70; pg.total_speed_deviation = 10; pg.duration_deviation = 0.5; pg.emit(game.states.gameplay->particles); } /* ---------------------------------------------------------------------------- * When a ship needs to enter its default "idling" animation. * m: * The mob. * info1: * Unused. * info2: * Unused. */ void ship_fsm::set_anim(mob* m, void* info1, void* info2) { m->set_animation(SHIP_ANIM_IDLING); }
[ "andreluis.g.silva@gmail.com" ]
andreluis.g.silva@gmail.com
2fc7ccd9e100c60ff3be862b2cb38c1f322dcf7b
1c4e8c99afe39efa508c3f99006cea97edd1787b
/code/ESP32_WiFi_Multisensor/ESP32_WiFi_Multisensor.ino
91ae74a9825ddd319266c2eab94280818381f781
[]
no_license
az666/ESP32-Course
1d96938fdbd0e307169f688f9722779f5d397449
1872b7164f02c5f50f60f667e87bb4935d9ce854
refs/heads/master
2020-05-04T23:09:38.082167
2019-03-19T15:40:34
2019-03-19T15:40:34
179,534,588
0
1
null
2019-04-04T16:21:45
2019-04-04T16:21:45
null
UTF-8
C++
false
false
17,029
ino
/********* Rui Santos Complete project details at http://randomnerdtutorials.com *********/ // Load libraries #include <WiFi.h> #include <EEPROM.h> #include "DHT.h" #include <Adafruit_Sensor.h> // Replace with your network credentials const char* ssid = "REPLACE_WITH_YOUR_SSID"; const char* password = "REPLACE_WITH_YOUR_PASSWORD"; // Uncomment one of the lines below for whatever DHT sensor type you're using! //#define DHTTYPE DHT11 // DHT 11 //#define DHTTYPE DHT21 // DHT 21 (AM2301) #define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321 // DHT Sensor const int DHTPin = 27; // Initialize DHT sensor. DHT dht(DHTPin, DHTTYPE); // Temporary variables for temperature and humidity static char celsiusTemp[7]; static char fahrenheitTemp[7]; static char humidityTemp[7]; // EEPROM size // Address 0: Last output state (0 = off or 1 = on) // Address 1: Selected mode (0 = Manual, 1 = Auto PIR, // 2 = Auto LDR, or 3 = Auto PIR and LDR) // Address 2: Timer (time 0 to 255 seconds) // Address 3: LDR threshold value (luminosity in percentage 0 to 100%) #define EEPROM_SIZE 4 // Set GPIOs for: output variable, RGB LED, PIR Motion Sensor, and LDR const int output = 2; const int redRGB = 14; const int greenRGB = 12; const int blueRGB = 13; const int motionSensor = 25; const int ldr = 33; // Store the current output state String outputState = "off"; // Timers - Auxiliary variables long now = millis(); long lastMeasure = 0; boolean startTimer = false; // Auxiliary variables to store selected mode and settings int selectedMode = 0; int timer = 0; int ldrThreshold = 0; int armMotion = 0; int armLdr = 0; String modes[4] = { "Manual", "Auto PIR", "Auto LDR", "Auto PIR and LDR" }; // Decode HTTP GET value String valueString = "0"; int pos1 = 0; int pos2 = 0; // Variable to store the HTTP request String header; // Set web server port number to 80 WiFiServer server(80); void setup() { // initialize the DHT sensor dht.begin(); // Serial port for debugging purposes Serial.begin(115200); // PIR Motion Sensor mode, then set interrupt function and RISING mode pinMode(motionSensor, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(motionSensor), detectsMovement, RISING); Serial.println("start..."); if(!EEPROM.begin(EEPROM_SIZE)) { Serial.println("failed to initialise EEPROM"); delay(1000); } // Uncomment the next lines to test the values stored in the flash memory Serial.println(" bytes read from Flash . Values are:"); for(int i = 0; i < EEPROM_SIZE; i++) { Serial.print(byte(EEPROM.read(i))); Serial.print(" "); } // Initialize the output variable and RGB pins as OUTPUTs pinMode(output, OUTPUT); pinMode(redRGB, OUTPUT); pinMode(greenRGB, OUTPUT); pinMode(blueRGB, OUTPUT); // Read from flash memory on start and store the values in auxiliary variables // Set output to last state (saved in the flash memory) if(!EEPROM.read(0)) { outputState = "off"; digitalWrite(output, HIGH); } else { outputState = "on"; digitalWrite(output, LOW); } selectedMode = EEPROM.read(1); timer = EEPROM.read(2); ldrThreshold = EEPROM.read(3); configureMode(); // Connect to Wi-Fi network with SSID and password Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } // Print local IP address and start web server Serial.println(""); Serial.println("WiFi connected."); Serial.println("IP address: "); Serial.println(WiFi.localIP()); server.begin(); } void loop() { WiFiClient client = server.available(); // Listen for incoming clients if (client) { // If a new client connects, Serial.println("New Client."); // print a message out in the serial port String currentLine = ""; // make a String to hold incoming data from the client while (client.connected()) { // loop while the client's connected if (client.available()) { // if there's bytes to read from the client, char c = client.read(); // read a byte, then Serial.write(c); // print it out the serial monitor header += c; if (c == '\n') { // if the byte is a newline character // if the current line is blank, you got two newline characters in a row. // that's the end of the client HTTP request, so send a response: if (currentLine.length() == 0) { // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK) // and a content-type so the client knows what's coming, then a blank line: client.println("HTTP/1.1 200 OK"); client.println("Content-type:text/html"); client.println("Connection: close"); client.println(); // Display the HTML web page client.println("<!DOCTYPE html><html>"); client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"); client.println("<link rel=\"icon\" href=\"data:,\">"); // CSS to style the on/off buttons // Feel free to change the background-color and font-size attributes to fit your preferences client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}"); client.println(".button { background-color: #4CAF50; border: none; color: white; padding: 16px 40px;"); client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}"); client.println(".button2 {background-color: #555555;}</style></head>"); // Request example: GET /?mode=0& HTTP/1.1 - sets mode to Manual (0) if(header.indexOf("GET /?mode=") >= 0) { pos1 = header.indexOf('='); pos2 = header.indexOf('&'); valueString = header.substring(pos1+1, pos2); selectedMode = valueString.toInt(); EEPROM.write(1, selectedMode); EEPROM.commit(); configureMode(); } // Change the output state - turn GPIOs on and off else if(header.indexOf("GET /?state=on") >= 0) { outputOn(); } else if(header.indexOf("GET /?state=off") >= 0) { outputOff(); } // Set timer value else if(header.indexOf("GET /?timer=") >= 0) { pos1 = header.indexOf('='); pos2 = header.indexOf('&'); valueString = header.substring(pos1+1, pos2); timer = valueString.toInt(); EEPROM.write(2, timer); EEPROM.commit(); Serial.println(valueString); } // Set LDR Threshold value else if(header.indexOf("GET /?ldrthreshold=") >= 0) { pos1 = header.indexOf('='); pos2 = header.indexOf('&'); valueString = header.substring(pos1+1, pos2); ldrThreshold = valueString.toInt(); EEPROM.write(3, ldrThreshold); EEPROM.commit(); Serial.println(valueString); } // Web Page Heading client.println("<body><h1>ESP32 Web Server</h1>"); // Drop down menu to select mode client.println("<p><strong>Mode selected:</strong> " + modes[selectedMode] + "</p>"); client.println("<select id=\"mySelect\" onchange=\"setMode(this.value)\">"); client.println("<option>Change mode"); client.println("<option value=\"0\">Manual"); client.println("<option value=\"1\">Auto PIR"); client.println("<option value=\"2\">Auto LDR"); client.println("<option value=\"3\">Auto PIR and LDR</select>"); // Display current state, and ON/OFF buttons for output client.println("<p>GPIO - State " + outputState + "</p>"); // If the output is off, it displays the ON button if(selectedMode == 0) { if(outputState == "off") { client.println("<p><button class=\"button\" onclick=\"outputOn()\">ON</button></p>"); } else { client.println("<p><button class=\"button button2\" onclick=\"outputOff()\">OFF</button></p>"); } } else if(selectedMode == 1) { client.println("<p>Timer (0 and 255 in seconds): <input type=\"number\" name=\"txt\" value=\"" + String(EEPROM.read(2)) + "\" onchange=\"setTimer(this.value)\" min=\"0\" max=\"255\"></p>"); } else if(selectedMode == 2) { client.println("<p>LDR Threshold (0 and 100%): <input type=\"number\" name=\"txt\" value=\"" + String(EEPROM.read(3)) + "\" onchange=\"setThreshold(this.value)\" min=\"0\" max=\"100\"></p>"); } else if(selectedMode == 3) { client.println("<p>Timer (0 and 255 in seconds): <input type=\"number\" name=\"txt\" value=\"" + String(EEPROM.read(2)) + "\" onchange=\"setTimer(this.value)\" min=\"0\" max=\"255\"></p>"); client.println("<p>LDR Threshold (0 and 100%): <input type=\"number\" name=\"txt\" value=\"" + String(EEPROM.read(3)) + "\" onchange=\"setThreshold(this.value)\" min=\"0\" max=\"100\"></p>"); } // Get and display DHT sensor readings if(header.indexOf("GET /?sensor") >= 0) { // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) float h = dht.readHumidity(); // Read temperature as Celsius (the default) float t = dht.readTemperature(); // Read temperature as Fahrenheit (isFahrenheit = true) float f = dht.readTemperature(true); // Check if any reads failed and exit early (to try again). if (isnan(h) || isnan(t) || isnan(f)) { Serial.println("Failed to read from DHT sensor!"); strcpy(celsiusTemp,"Failed"); strcpy(fahrenheitTemp, "Failed"); strcpy(humidityTemp, "Failed"); } else { // Computes temperature values in Celsius + Fahrenheit and Humidity float hic = dht.computeHeatIndex(t, h, false); dtostrf(hic, 6, 2, celsiusTemp); float hif = dht.computeHeatIndex(f, h); dtostrf(hif, 6, 2, fahrenheitTemp); dtostrf(h, 6, 2, humidityTemp); // You can delete the following Serial.prints, it s just for debugging purposes /*Serial.print("Humidity: "); Serial.print(h); Serial.print(" %\t Temperature: "); Serial.print(t); Serial.print(" *C "); Serial.print(f); Serial.print(" *F\t Heat index: "); Serial.print(hic); Serial.print(" *C "); Serial.print(hif); Serial.print(" *F"); Serial.print("Humidity: "); Serial.print(h); Serial.print(" %\t Temperature: "); Serial.print(t); Serial.print(" *C "); Serial.print(f); Serial.print(" *F\t Heat index: "); Serial.print(hic); Serial.print(" *C "); Serial.print(hif); Serial.println(" *F");*/ } client.println("<p>"); client.println(celsiusTemp); client.println("*C</p><p>"); client.println(fahrenheitTemp); client.println("*F</p></div><p>"); client.println(humidityTemp); client.println("%</p></div>"); client.println("<p><a href=\"/\"><button>Remove Sensor Readings</button></a></p>"); } else { client.println("<p><a href=\"?sensor\"><button>View Sensor Readings</button></a></p>"); } client.println("<script> function setMode(value) { var xhr = new XMLHttpRequest();"); client.println("xhr.open('GET', \"/?mode=\" + value + \"&\", true);"); client.println("xhr.send(); location.reload(true); } "); client.println("function setTimer(value) { var xhr = new XMLHttpRequest();"); client.println("xhr.open('GET', \"/?timer=\" + value + \"&\", true);"); client.println("xhr.send(); location.reload(true); } "); client.println("function setThreshold(value) { var xhr = new XMLHttpRequest();"); client.println("xhr.open('GET', \"/?ldrthreshold=\" + value + \"&\", true);"); client.println("xhr.send(); location.reload(true); } "); client.println("function outputOn() { var xhr = new XMLHttpRequest();"); client.println("xhr.open('GET', \"/?state=on\", true);"); client.println("xhr.send(); location.reload(true); } "); client.println("function outputOff() { var xhr = new XMLHttpRequest();"); client.println("xhr.open('GET', \"/?state=off\", true);"); client.println("xhr.send(); location.reload(true); } "); client.println("function updateSensorReadings() { var xhr = new XMLHttpRequest();"); client.println("xhr.open('GET', \"/?sensor\", true);"); client.println("xhr.send(); location.reload(true); }</script></body></html>"); // The HTTP response ends with another blank line client.println(); // Break out of the while loop break; } else { // if you got a newline, then clear currentLine currentLine = ""; } } else if (c != '\r') { // if you got anything else but a carriage return character, currentLine += c; // add it to the end of the currentLine } } } // Clear the header variable header = ""; // Close the connection client.stop(); Serial.println("Client disconnected."); } // Starts a timer to turn on/off the output according to the time value or LDR reading now = millis(); // Mode selected (1): Auto PIR if(startTimer && armMotion && !armLdr) { if(outputState == "off") { outputOn(); } else if((now - lastMeasure > (timer * 1000))) { outputOff(); startTimer = false; } } // Mode selected (2): Auto LDR // Read current LDR value and turn the output accordingly if(armLdr && !armMotion) { int ldrValue = map(analogRead(ldr), 0, 4095, 0, 100); //Serial.println(ldrValue); if(ldrValue > ldrThreshold && outputState == "on") { outputOff(); } else if(ldrValue < ldrThreshold && outputState == "off") { outputOn(); } delay(100); } // Mode selected (3): Auto PIR and LDR if(startTimer && armMotion && armLdr) { int ldrValue = map(analogRead(ldr), 0, 4095, 0, 100); //Serial.println(ldrValue); if(ldrValue > ldrThreshold) { outputOff(); startTimer = false; } else if(ldrValue < ldrThreshold && outputState == "off") { outputOn(); } else if(now - lastMeasure > (timer * 1000)) { outputOff(); startTimer = false; } } } // Checks if motion was detected and the sensors are armed. Then, starts a timer. void detectsMovement() { if(armMotion || (armMotion && armLdr)) { Serial.println("MOTION DETECTED!!!"); startTimer = true; lastMeasure = millis(); } } void configureMode() { // Mode: Manual if(selectedMode == 0) { armMotion = 0; armLdr = 0; // RGB LED color: red digitalWrite(redRGB, LOW); digitalWrite(greenRGB, HIGH); digitalWrite(blueRGB, HIGH); } // Mode: Auto PIR else if(selectedMode == 1) { outputOff(); armMotion = 1; armLdr = 0; // RGB LED color: green digitalWrite(redRGB, HIGH); digitalWrite(greenRGB, LOW); digitalWrite(blueRGB, HIGH); } // Mode: Auto LDR else if(selectedMode == 2) { armMotion = 0; armLdr = 1; // RGB LED color: blue digitalWrite(redRGB, HIGH); digitalWrite(greenRGB, HIGH); digitalWrite(blueRGB, LOW); } // Mode: Auto PIR and LDR else if(selectedMode == 3) { outputOff(); armMotion = 1; armLdr = 1; // RGB LED color: purple digitalWrite(redRGB, LOW); digitalWrite(greenRGB, HIGH); digitalWrite(blueRGB, LOW); } } // Change output pin to on or off void outputOn() { Serial.println("GPIO on"); outputState = "on"; digitalWrite(output, LOW); EEPROM.write(0, 1); EEPROM.commit(); } void outputOff() { Serial.println("GPIO off"); outputState = "off"; digitalWrite(output, HIGH); EEPROM.write(0, 0); EEPROM.commit(); }
[ "hello@ruisantos.me" ]
hello@ruisantos.me
0b92eccfa52e97fa5d454c0a6d1a99253f38f12a
58a0ba5ee99ec7a0bba36748ba96a557eb798023
/CodeForces/Complete/900-999/922A-CloningToys.cpp
d4c4be0ad176692d99dae3b5cbfcb4d7dbf345c3
[ "MIT" ]
permissive
adityanjr/code-DS-ALGO
5bdd503fb5f70d459c8e9b8e58690f9da159dd53
1c104c33d2f56fe671d586b702528a559925f875
refs/heads/master
2022-10-22T21:22:09.640237
2022-10-18T15:38:46
2022-10-18T15:38:46
217,567,198
40
54
MIT
2022-10-18T15:38:47
2019-10-25T15:50:28
C++
UTF-8
C++
false
false
181
cpp
#include <cstdio> int main(){ long x, y; scanf("%ld %ld", &x, &y); puts((x == 0 && y == 1) || ((y > 1) && (x >= y - 1) && ((x - y) & 1)) ? "Yes" : "No"); return 0; }
[ "samant04aditya@gmail.com" ]
samant04aditya@gmail.com
e3cef022f4049fe8ca74e37bf566282c5733ed65
f130e0cc7771b903e4840f1193bde7020abe603d
/plugins/SandboxPlugin/SandboxPlugin.cpp
b4db195f855c1b185c14c0693fc5f594dd11377b
[]
no_license
Tnoriaki/jsk_choreonoid
c7c208f1505e65a05e2f02fe67059e431c19dbdd
17ddf4a0b76ad29b6cc1504b4716dddeaa0d5c81
refs/heads/master
2021-01-20T05:04:15.257189
2017-07-28T16:41:55
2017-07-28T16:41:55
101,415,674
0
0
null
2017-08-25T15:09:43
2017-08-25T15:09:43
null
UTF-8
C++
false
false
12,287
cpp
/** @author Kunio Kojima */ #include <iostream> #include <sstream> #include <unistd.h> #include <cnoid/Plugin> #include <cnoid/ItemTreeView> #include <cnoid/BodyItem> #include <cnoid/WorldItem> #include <cnoid/ToolBar> #include <boost/bind.hpp> #include <cnoid/MessageView> #include <cnoid/Archive> #include <cnoid/BodyMotionGenerationBar> #include <cnoid/src/PoseSeqPlugin/PoseSeqItem.h> #include <cnoid/PoseProvider> #include <cnoid/BodyMotionPoseProvider> #include <cnoid/PoseProviderToBodyMotionConverter> #include <cnoid/BodyMotionUtil> #include <cnoid/PointSetItem> #include <cnoid/TimeBar> #include <cnoid/Archive> #include <cnoid/MenuManager> #include <cnoid/MainWindow> #include <cnoid/SpinBox> // #include <cnoid/Separator> #include <cnoid/Button> #include <QDialog> #include <QDialogButtonBox> #include <QEventLoop> #include <boost/format.hpp> #include <boost/thread.hpp> #include <set> // #include "../../../src/PoseSeqPlugin/gettext.h" #include <UtilPlugin/UtilPlugin.h> using namespace boost; using namespace cnoid; using namespace std; class SandboxPlugin : public Plugin { public: Connection connections; SandboxPlugin() : Plugin("Sandbox") { require("Body"); } virtual bool initialize() { ToolBar* bar = new ToolBar("Sandbox"); BodyMotionGenerationBar* bmgb = BodyMotionGenerationBar::instance();// インスタンス生成 bar->addButton("sweep") ->sigClicked().connect(bind(&SandboxPlugin::onButtonClicked, this, false)); bar->addButton("print") ->sigClicked().connect(bind(&SandboxPlugin::onButtonClicked, this, true)); addToolBar(bar); return true; } void onButtonClicked(bool print_flg) { stringstream ss; ItemList<Item> selectedItems = ItemTreeView::mainInstance()->selectedItems<Item>(); TimeBar* tb = TimeBar::instance();; // tb->setTime(3); // 時刻設定 // ss << "time " << tb->time() << endl; // 現在時刻取得 // 関節・リンク情報取得・設定 ItemList<BodyItem> bodyItems = ItemTreeView::mainInstance()->checkedItems<BodyItem>(); // checkedItems チェックされたアイテムを取得 if(print_flg){ MessageView::instance()->putln("Print called !"); // ItemList<PoseSeqItem> poseSeqItems = bodyItems[0]->getSubItems<PoseSeqItem>();// サブアイテムを取得 // for(size_t i = 0; i < poseSeqItems.size(); ++i){ // ss << poseSeqItems[i]->name() << endl; // } for(size_t i=0; i < bodyItems.size(); ++i){ BodyPtr body = bodyItems[i]->body(); // ss << "baselink " << bodyItems[i]->currentBaseLink()->name() << endl;// BaseLink // zmp取得 // BodyItem* bodyItem = bodyItems[0]; // optional<Vector3> p = bodyItem->getParticularPosition(BodyItem::ZERO_MOMENT_POINT); // ss << (*p)[0] << " " << (*p)[1] << " " << (*p)[2] << endl; // Vector3 zmp = bodyItem->zmp(); // ss << zmp[0] << " " << zmp[1] << " " << zmp[2] << endl; } MessageView::instance()->putln(ss.str()); return; }// end prit MessageView::instance()->putln("sweep called !"); QEventLoop eventLoop; // 各PoseSeqへアクセス ItemList<PoseSeqItem> poseSeqItems = ItemTreeView::mainInstance()->selectedItems<Item>(); for(size_t i=0; i < poseSeqItems.size(); ++i){ PoseSeqPtr poseSeq = poseSeqItems[i]->poseSeq(); BodyPtr body = bodyItems[0]->body(); // BodyMotionの各Frameへのアクセス BodyMotionItem* bodyMotionItem = poseSeqItems[i]->bodyMotionItem(); BodyMotionPtr motion = bodyMotionItem->motion(); const double dt = 1.0/motion->frameRate(); for(int j=0;j < motion->numFrames(); ++j){// zmpSeq.numFrames()でもOK if(j % 10 == 0){ // BodyMotion::Frame frame = motion->frame(j); MultiValueSeq::Frame q = motion->jointPosSeq()->frame(j);// jはframe.frame()でもいい MultiSE3Seq::Frame links = motion->linkPosSeq()->frame(j); // SE3とは?? // SO(3) 3次特殊直交群 eg R // so(3) 歪対称行列の集合 eg [r×] // SE(3) 同次変換の集合 (特殊ユークリッド群) eg H // se(3) ツイストによる歪対称行列の集合 eg [xi×] // zmp取得 // BodyItem* bodyItem = bodyItems[0]; // // optional<Vector3> p = bodyItem->getParticularPosition(BodyItem::ZERO_MOMENT_POINT);// 今一不明 // // ss << (*p)[0] << " " << (*p)[1] << " " << (*p)[2] << endl; // Vector3 zmp = bodyItem->zmp(); // ss << zmp.x() << " " << zmp.y() << " " << zmp.z() << endl;// 今一不明 // 姿勢更新 motion->frame(j) >> *body; bodyItems[0]->notifyKinematicStateChange(true); // collision取得 const std::vector<CollisionLinkPairPtr>& collisions = bodyItems[0]->collisions(); cout << dt*j << " sec:"; cout << collisions.size() << endl; for(size_t i=0; i < collisions.size(); ++i){ CollisionLinkPair& collisionPair = *collisions[i]; cout << " " << collisionPair.link[0]->name() << "(" << collisionPair.link[0]->jointId() << ") " << collisionPair.link[1]->name() << " " << collisionPair.isSelfCollision(); for(std::vector<Collision>::iterator iter = collisionPair.collisions.begin(); iter != collisionPair.collisions.end(); ++iter){ // cout << " " << iter->point.transpose() << " " << iter->normal.transpose() << endl; } }cout << endl; eventLoop.processEvents(); } } // 各Poseへアクセス for(PoseSeq::iterator poseIter = poseSeq->begin(); poseIter != poseSeq->end(); ++poseIter){ PosePtr pose = poseIter->get<Pose>();// PosePtr取得 Pose::LinkInfo* linkInfo = pose->ikLinkInfo(37); cout << poseIter->time() << "[sec]: "; cout << linkInfo->isTouching() << " " << linkInfo->isStationaryPoint(); // cout << linkInfo->isTouching() << "->"; linkInfo->clearTouching(); // cout << linkInfo->isTouching() << endl; linkInfo = pose->ikLinkInfo(31); cout << linkInfo->isTouching() << " " << linkInfo->isStationaryPoint() << endl; // cout << linkInfo->isTouching() << "->"; linkInfo->clearTouching(); // tb->setTime(poseIter->time()); // BodyPtr body = bodyItems[0]->body(); // ss << body->link("RLEG_JOINT0")->dq << endl; // if(pose->isZmpValid()){// zmpはposeRollで有効になってないと0(初期値)のまま // ss << pose->zmp().x() << " " << pose->zmp().y() << " " << pose->zmp().z() << endl;// zmp?? // } // ss << poseIter->time();// pose時刻取得 // ss << poseIter->maxTransitionTime();// pose遷移時間取得 // for(int j = 0;j < pose->numJoints(); j++){ // ss << pose->jointPosition(j) << " ";// 関節速度・加速度も知りたい // } // LinkInfoは yaml で defaultIKsetup しているリンクが、jointIdの順に並んでいる // for(Pose::LinkInfoMap::iterator itr = pose->ikLinkBegin(); itr != pose->ikLinkEnd(); ++itr){ // ss << "isBaseLink " << itr->second.isBaseLink() << endl; // ss << "isTouching " << itr->second.isTouching() << endl; // }ss << endl; // ss << endl; }// 各poseに対するforの終わり poseSeqItems[i]->updateInterpolation(); }// 各poseSeqに対するforの終わり // シグナル // Signal<void()> sigTest; // sigTest.connect(bind(&SandboxPlugin::test, this)); // sigTest(); // スレッドでcollision取得->pointで表示 // boost::thread thr(&SandboxPlugin::test, this); // WorldItemへのアクセス { ItemList<PoseSeqItem> selectedItems = ItemTreeView::mainInstance()->selectedItems<Item>(); // RootItem* rootItem = selectedItems[0]->findRootItem(); // cout << "RootItem: "<< rootItem->name() << endl; WorldItem* ownerItem = selectedItems[0]->findOwnerItem<WorldItem>(); cout << "OwnerItem: "<< ownerItem->name() << endl;// ワールドアイテム Item* childItem = ownerItem->childItem();//ボディーアイテム cout << "ChildItem: " << childItem->name() << endl; Item* item = ownerItem->findItem("AISTシミュレータ");// シミュレータアイテム if(!item) return; cout << "Item: " << item->name() << endl; Archive archive; item->store(archive); double staticFriction,slipFriction; archive.read("staticFriction",staticFriction); archive.read("slipFriction",slipFriction); cout << "StaticFriction: " << staticFriction << " SlipFriction: " << slipFriction << endl; } MessageView::instance()->putln(ss.str()); } // collision取得 void test() { BodyItemPtr bodyItemPtr; BodyPtr robot; PoseSeqItemPtr poseSeqItemPtr; PoseSeqPtr poseSeqPtr; BodyMotionItemPtr bodyMotionItemPtr; BodyMotionPtr motion; if(!getSelectedPoseSeqSet(bodyItemPtr, robot, poseSeqItemPtr, poseSeqPtr, bodyMotionItemPtr, motion)) return; WorldItemPtr worldItemPtr = bodyItemPtr->findOwnerItem<WorldItem>(); const double dt = 1.0/motion->frameRate(); PointSetItemPtr pointSetItemPtr; if(!(pointSetItemPtr = worldItemPtr->findItem<PointSetItem>("ContactPoint"))){ pointSetItemPtr = new PointSetItem(); pointSetItemPtr->setName("ContactPoint"); worldItemPtr->addChildItem(pointSetItemPtr); ItemTreeView::mainInstance()->checkItem(pointSetItemPtr);// check + updateCollisions() -> segmentation fault } connections = bodyItemPtr->sigCollisionsUpdated().connect(boost::bind(&SandboxPlugin::test2, this, bodyItemPtr, robot, motion, pointSetItemPtr)); test2(bodyItemPtr, robot, motion, pointSetItemPtr); } void test2(BodyItemPtr& bodyItemPtr, BodyPtr& robot, BodyMotionPtr& motion, PointSetItemPtr& pointSetItemPtr) { static int idx = 0; static const double dt = 1.0/motion->frameRate(); usleep(50*1000); if(idx != 0){ pointSetItemPtr->clearAttentionPoint(); const std::vector<CollisionLinkPairPtr>& collisions = bodyItemPtr->collisions(); cout << dt*idx << " sec:"; cout << collisions.size() << endl; for(size_t i=0; i < collisions.size(); ++i){ CollisionLinkPair& collisionPair = *collisions[i]; cout << " " << collisionPair.link[0]->name() << " " << collisionPair.link[1]->name() << " " << collisionPair.isSelfCollision(); for(std::vector<Collision>::iterator iter = collisionPair.collisions.begin(); iter != collisionPair.collisions.end(); ++iter){ // cout << " " << iter->point.transpose() << " " << iter->normal.transpose() << endl; pointSetItemPtr->addAttentionPoint(iter->point); } }cout << endl; } if(idx < motion->numFrames()){ motion->frame(idx) >> *robot; bodyItemPtr->notifyKinematicStateChange(true); ++idx; }else{ idx = 0; connections.disconnect();// disconnect when finished } } }; CNOID_IMPLEMENT_PLUGIN_ENTRY(SandboxPlugin)
[ "kunio.einstein@gmail.com" ]
kunio.einstein@gmail.com
f8ea728d7812613aba8813f0a30f6a181e080a3f
13e1e38318d6c832347b75cd76f1d342dfec3f64
/3rdParty/V8-4.3.61/src/base/platform/platform-freebsd.cc
68ed70af93fa04ac226c9188bc4599a1e8671b1d
[ "bzip2-1.0.6", "BSD-3-Clause", "Apache-2.0", "GPL-1.0-or-later", "ICU", "MIT" ]
permissive
msand/arangodb
f1e2c2208258261e6a081897746c247a0aec6bdf
7c43164bb989e185f9c68a5275cebdf15548c2d6
refs/heads/devel
2023-04-07T00:35:40.506103
2015-07-20T08:59:22
2015-07-20T08:59:22
39,376,414
0
0
Apache-2.0
2023-04-04T00:08:22
2015-07-20T09:58:42
C++
UTF-8
C++
false
false
8,205
cc
// Copyright 2012 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Platform-specific code for FreeBSD goes here. For the POSIX-compatible // parts, the implementation is in platform-posix.cc. #include <pthread.h> #include <semaphore.h> #include <signal.h> #include <stdlib.h> #include <sys/resource.h> #include <sys/time.h> #include <sys/types.h> #include <sys/ucontext.h> #include <sys/fcntl.h> // open #include <sys/mman.h> // mmap & munmap #include <sys/stat.h> // open #include <sys/types.h> // mmap & munmap #include <unistd.h> // getpagesize // If you don't have execinfo.h then you need devel/libexecinfo from ports. #include <errno.h> #include <limits.h> #include <stdarg.h> #include <strings.h> // index #include <cmath> #undef MAP_TYPE #include "src/base/macros.h" #include "src/base/platform/platform.h" namespace v8 { namespace base { const char* OS::LocalTimezone(double time, TimezoneCache* cache) { if (std::isnan(time)) return ""; time_t tv = static_cast<time_t>(std::floor(time/msPerSecond)); struct tm* t = localtime(&tv); if (NULL == t) return ""; return t->tm_zone; } double OS::LocalTimeOffset(TimezoneCache* cache) { time_t tv = time(NULL); struct tm* t = localtime(&tv); // tm_gmtoff includes any daylight savings offset, so subtract it. return static_cast<double>(t->tm_gmtoff * msPerSecond - (t->tm_isdst > 0 ? 3600 * msPerSecond : 0)); } void* OS::Allocate(const size_t requested, size_t* allocated, bool executable) { const size_t msize = RoundUp(requested, getpagesize()); int prot = PROT_READ | PROT_WRITE | (executable ? PROT_EXEC : 0); void* mbase = mmap(NULL, msize, prot, MAP_PRIVATE | MAP_ANON, -1, 0); if (mbase == MAP_FAILED) return NULL; *allocated = msize; return mbase; } class PosixMemoryMappedFile : public OS::MemoryMappedFile { public: PosixMemoryMappedFile(FILE* file, void* memory, int size) : file_(file), memory_(memory), size_(size) { } virtual ~PosixMemoryMappedFile(); virtual void* memory() { return memory_; } virtual int size() { return size_; } private: FILE* file_; void* memory_; int size_; }; OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) { FILE* file = fopen(name, "r+"); if (file == NULL) return NULL; fseek(file, 0, SEEK_END); int size = ftell(file); void* memory = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0); return new PosixMemoryMappedFile(file, memory, size); } OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size, void* initial) { FILE* file = fopen(name, "w+"); if (file == NULL) return NULL; int result = fwrite(initial, size, 1, file); if (result < 1) { fclose(file); return NULL; } void* memory = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0); return new PosixMemoryMappedFile(file, memory, size); } PosixMemoryMappedFile::~PosixMemoryMappedFile() { if (memory_) munmap(memory_, size_); fclose(file_); } static unsigned StringToLong(char* buffer) { return static_cast<unsigned>(strtol(buffer, NULL, 16)); // NOLINT } std::vector<OS::SharedLibraryAddress> OS::GetSharedLibraryAddresses() { std::vector<SharedLibraryAddress> result; static const int MAP_LENGTH = 1024; int fd = open("/proc/self/maps", O_RDONLY); if (fd < 0) return result; while (true) { char addr_buffer[11]; addr_buffer[0] = '0'; addr_buffer[1] = 'x'; addr_buffer[10] = 0; ssize_t bytes_read = read(fd, addr_buffer + 2, 8); if (bytes_read < 8) break; unsigned start = StringToLong(addr_buffer); bytes_read = read(fd, addr_buffer + 2, 1); if (bytes_read < 1) break; if (addr_buffer[2] != '-') break; bytes_read = read(fd, addr_buffer + 2, 8); if (bytes_read < 8) break; unsigned end = StringToLong(addr_buffer); char buffer[MAP_LENGTH]; bytes_read = -1; do { bytes_read++; if (bytes_read >= MAP_LENGTH - 1) break; bytes_read = read(fd, buffer + bytes_read, 1); if (bytes_read < 1) break; } while (buffer[bytes_read] != '\n'); buffer[bytes_read] = 0; // Ignore mappings that are not executable. if (buffer[3] != 'x') continue; char* start_of_path = index(buffer, '/'); // There may be no filename in this line. Skip to next. if (start_of_path == NULL) continue; buffer[bytes_read] = 0; result.push_back(SharedLibraryAddress(start_of_path, start, end)); } close(fd); return result; } void OS::SignalCodeMovingGC() { } // Constants used for mmap. static const int kMmapFd = -1; static const int kMmapFdOffset = 0; VirtualMemory::VirtualMemory() : address_(NULL), size_(0) { } VirtualMemory::VirtualMemory(size_t size) : address_(ReserveRegion(size)), size_(size) { } VirtualMemory::VirtualMemory(size_t size, size_t alignment) : address_(NULL), size_(0) { DCHECK((alignment % OS::AllocateAlignment()) == 0); size_t request_size = RoundUp(size + alignment, static_cast<intptr_t>(OS::AllocateAlignment())); void* reservation = mmap(OS::GetRandomMmapAddr(), request_size, PROT_NONE, MAP_PRIVATE | MAP_ANON, kMmapFd, kMmapFdOffset); if (reservation == MAP_FAILED) return; uint8_t* base = static_cast<uint8_t*>(reservation); uint8_t* aligned_base = RoundUp(base, alignment); DCHECK_LE(base, aligned_base); // Unmap extra memory reserved before and after the desired block. if (aligned_base != base) { size_t prefix_size = static_cast<size_t>(aligned_base - base); OS::Free(base, prefix_size); request_size -= prefix_size; } size_t aligned_size = RoundUp(size, OS::AllocateAlignment()); DCHECK_LE(aligned_size, request_size); if (aligned_size != request_size) { size_t suffix_size = request_size - aligned_size; OS::Free(aligned_base + aligned_size, suffix_size); request_size -= suffix_size; } DCHECK(aligned_size == request_size); address_ = static_cast<void*>(aligned_base); size_ = aligned_size; } VirtualMemory::~VirtualMemory() { if (IsReserved()) { bool result = ReleaseRegion(address(), size()); DCHECK(result); USE(result); } } bool VirtualMemory::IsReserved() { return address_ != NULL; } void VirtualMemory::Reset() { address_ = NULL; size_ = 0; } bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) { return CommitRegion(address, size, is_executable); } bool VirtualMemory::Uncommit(void* address, size_t size) { return UncommitRegion(address, size); } bool VirtualMemory::Guard(void* address) { OS::Guard(address, OS::CommitPageSize()); return true; } void* VirtualMemory::ReserveRegion(size_t size) { void* result = mmap(OS::GetRandomMmapAddr(), size, PROT_NONE, MAP_PRIVATE | MAP_ANON, kMmapFd, kMmapFdOffset); if (result == MAP_FAILED) return NULL; return result; } bool VirtualMemory::CommitRegion(void* base, size_t size, bool is_executable) { int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0); if (MAP_FAILED == mmap(base, size, prot, MAP_PRIVATE | MAP_ANON | MAP_FIXED, kMmapFd, kMmapFdOffset)) { return false; } return true; } bool VirtualMemory::UncommitRegion(void* base, size_t size) { return mmap(base, size, PROT_NONE, MAP_PRIVATE | MAP_ANON | MAP_FIXED, kMmapFd, kMmapFdOffset) != MAP_FAILED; } bool VirtualMemory::ReleaseRegion(void* base, size_t size) { return munmap(base, size) == 0; } bool VirtualMemory::HasLazyCommits() { // TODO(alph): implement for the platform. return false; } } } // namespace v8::base
[ "w.goesgens@arangodb.org" ]
w.goesgens@arangodb.org
7ba243a9319e83414541b6405b600083076cb917
3ccf481fd3790b0646673f5f2bb05a599ffc2cde
/vistas/login.h
eaa5941ba80da3b3a1baeb530893528d3ef1f4fc
[]
no_license
sarahiva/IS2Proyecto1
973df39e18def71cacf87fc0cd73edef6e3b3695
aa08610efd8304c669b3975532b4ae021c3e52fe
refs/heads/master
2020-07-06T17:28:37.455168
2019-08-23T15:59:48
2019-08-23T15:59:48
203,091,144
0
0
null
null
null
null
UTF-8
C++
false
false
699
h
#ifndef LOGIN_H #define LOGIN_H #include <QDialog> namespace Ui{ class Login; } class InicioAdmin; class CtrlAutenticacion; class Login : public QDialog { Q_OBJECT protected: virtual void keyPressEvent(QKeyEvent *event) override; // virtual void closeEvent(QCloseEvent *event) override; public: explicit Login(CtrlAutenticacion *a, int intentos, QWidget *parent = nullptr); explicit Login(QWidget *parent = nullptr); ~Login(); signals: void loggedIn(); private slots: void authenticate(); // void on_salirBtn_clicked(); private: Ui::Login *ui; CtrlAutenticacion *auth; int maxtries; InicioAdmin *win; }; #endif /* LOGIN_H */
[ "salberto.mtz@gmail.com" ]
salberto.mtz@gmail.com
cacf4fdddd70edc20239d8818e1a7587a4958459
9dd024aa64a5cd7ecb7374ad5f1a6969aea49cd3
/src/Graphics/Circle.cpp
517c0f995dd257d215a86f3f5f8876f5e96db18c
[]
no_license
seenunit/GLSample
faeea4e80c252dd11dc3350be1a4e6780e096213
3ac859d9adb36f67792a25d1574eddd2d582fbdb
refs/heads/master
2020-03-25T18:34:52.024686
2018-08-08T16:07:08
2018-08-08T16:07:08
144,038,142
1
0
null
null
null
null
UTF-8
C++
false
false
5,894
cpp
// Circle.cpp : implementation file // #include "stdafx.h" #include <iostream> #include "GLSampleDoc.h" #include "Circle.h" #include "Line.h" #include <CMath.h> using namespace std; // CCircle IMPLEMENT_SERIAL(CCircle, CGeomEntity, 1) CCircle::CCircle() { } CCircle::CCircle( CGeomPoint ptCenter, double dRadius, int nSpanPts, Vector vecNormal ) { m_Center = ptCenter; m_dRadii = dRadius; m_nSpanPts = nSpanPts; m_vecNormal = vecNormal; try { m_pCirPts = new CGeomPoint[nSpanPts]; } catch (bad_alloc xa) { cout << "Allocation Failure\n"; exit(EXIT_FAILURE); } CreateCircle_v( m_nSpanPts, m_dRadii, m_Center, m_vecNormal, m_pCirPts); } CCircle::~CCircle() { delete [] m_pCirPts; } // CCircle member functions void CCircle::Serialize(CArchive &ar) { CObject::Serialize(ar); m_Center.Serialize( ar ); if(ar.IsStoring()) ar << m_dRadii; else ar >> m_dRadii; } void CCircle::Draw( CDC *pDc ) { //CreateArc_i( m_nSpanPts, m_dRadii, m_Center, m_pCirPts ); //Vector NormVect( 0, 0, 1 ); CreateCircle_v( m_nSpanPts, m_dRadii, m_Center, m_vecNormal, m_pCirPts); double dMatrix[4*4] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }; Matrix matTransf( dMatrix, 4, 4 ); DrawCurve( pDc, m_nSpanPts, m_pCirPts, matTransf ); } void CCircle::DrawCircle( CDC *pDc, Matrix &matTransf ) { DrawCurve( pDc, m_nSpanPts, m_pCirPts, matTransf ); } void CCircle::DrawCurve( CDC *pDc, int nSpanPts, CGeomPoint* pgptCurve, Matrix &matTransf ) { //Matrix matCurvePt( nSpanPts, 4 ); //for( int i = 0; i < nSpanPts; i++ ) //{ // for( int j = 0; j < 3; j++ ) // matCurvePt( i, j ) = pgptCurve[i].m_Coord[j]; // matCurvePt( i , 3 ) = 1; //} //Matrix matTransPt( nSpanPts, 4 ); //matTransPt = matCurvePt * matTransf; // transform the circle.. //int LocIndex = 0; //CPoint *Locations = new CPoint[nSpanPts]; //temp storage of pts //CSize sizeWndExt = pDc->GetWindowExt(); //CSize sizeViewExt = pDc->GetViewportExt(); //for(int i = 0; i < nSpanPts; i++) //{ // Locations[i].x = matTransPt( i, 0 ) * sizeWndExt.cx; // Locations[i].y = matTransPt( i, 1 ) * sizeWndExt.cy; //} //pDc->MoveTo( Locations[0]); //for(int i = 0; i < nSpanPts; i++) // pDc->LineTo( Locations[i] ); //pDc->LineTo( Locations[0] ); // For closing the circle. //delete [] Locations; for(int i = 0; i < nSpanPts-1; i++) { CLine line(pgptCurve[i], pgptCurve[i+1]); line.DrawLine(pDc, matTransf); } } void CreateArc_i( int nSpanpts, double dRadii, CGeomPoint ptCenter, CGeomPoint* pCirPts ) { double start_ang = 0; double dtheta = MAXANG/(float)nSpanpts; double d_ang = dtheta * PI/180; CGeomPoint gPtStart, gPtEnd; start_ang = (start_ang)* PI/180; gPtStart.m_Coord[0] = dRadii * cos(start_ang); gPtStart.m_Coord[1] = dRadii * sin(start_ang); pCirPts[0] = gPtStart; for(int i = 1; i < nSpanpts; i++) { gPtEnd.m_Coord[0] = gPtStart.m_Coord[0] * cos(d_ang) - gPtStart.m_Coord[1] * sin(d_ang); gPtEnd.m_Coord[1] = gPtStart.m_Coord[0] * sin(d_ang) + gPtStart.m_Coord[1] * cos(d_ang); pCirPts[i] = gPtEnd; gPtStart = gPtEnd; } for(int i = 0; i < nSpanpts; i++) for( int j = 0; j < 2; j++ ) pCirPts[i].m_Coord[j] = pCirPts[i].m_Coord[j] + ptCenter.m_Coord[j]; } void CreateCircle_v( int nSpanpts, double dRadii, CGeomPoint ptCenter, Vector NormVect, CGeomPoint* pCirPts ) { double dAng = ( MAXANG )* PI/180; dAng = dAng/nSpanpts; Vector vCentre( ptCenter.m_Coord[0], ptCenter.m_Coord[1], ptCenter.m_Coord[2] ); NormVect = NormVect.UnitVector(); // making normal unit vector. Vector vecCentreUnit = vCentre.UnitVector(); Vector tempVec = vecCentreUnit * NormVect ; Vector vAbtPostion = vCentre + tempVec*dRadii; pCirPts[0].m_Coord[0] = vAbtPostion.getx(); pCirPts[0].m_Coord[1] = vAbtPostion.gety(); pCirPts[0].m_Coord[2] = vAbtPostion.getz(); for( int i = 1; i < nSpanpts; i++ ) { Vector vPt = VectorRotation( vAbtPostion, NormVect, vCentre, dAng ); pCirPts[i].m_Coord[0] = vAbtPostion.getx(); pCirPts[i].m_Coord[1] = vAbtPostion.gety(); pCirPts[i].m_Coord[2] = vAbtPostion.getz(); vAbtPostion = vPt; } } // CCircleDialog dialog IMPLEMENT_DYNAMIC(CCircleDialog, CDialog) CCircleDialog::CCircleDialog( COPTIONS *pstructOpt, CWnd* pParent /*=NULL*/) : CDialog(CCircleDialog::IDD, pParent) { m_pstructOpt = pstructOpt; /*m_dRadius = m_dX = m_dY = m_dZ = 0.0; m_dVeci = m_dVecj = 0.0; m_dVeck = 1.0;*/ } CCircleDialog::~CCircleDialog() { } void CCircleDialog::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_EDIT_R, m_dRadius); //DDV_MinMaxInt(pDX, m_dRadius, 0, 1000); DDX_Control(pDX, IDC_EDIT_X, m_dX); DDX_Control(pDX, IDC_EDIT_Y, m_dY); DDX_Control(pDX, IDC_EDIT_Z, m_dZ); DDX_Control(pDX, IDC_EDIT_I, m_dVeci); DDX_Control(pDX, IDC_EDIT_J, m_dVecj); DDX_Control(pDX, IDC_EDIT_K, m_dVeck); } BEGIN_MESSAGE_MAP(CCircleDialog, CDialog) ON_BN_CLICKED(IDOK, &CCircleDialog::OnBnClickedOk) END_MESSAGE_MAP() // CCircleDialog message handlers void CCircleDialog::OnBnClickedOk() { // TODO: Add your control notification handler code here CString strRadius; m_dRadius.GetWindowTextA( strRadius ); m_pstructOpt->m_dCirRadius = atof( strRadius.GetBuffer() ); //m_dX.GetWindowTextA( strRadius ); //m_pstructOpt->m_gptCirCenter.m_Coord[0] = atof( strRadius.GetBuffer() ); //m_dY.GetWindowTextA( strRadius ); //m_pstructOpt->m_gptCirCenter.m_Coord[1] = atof( strRadius.GetBuffer() ); //m_dZ.GetWindowTextA( strRadius ); //m_pstructOpt->m_gptCirCenter.m_Coord[2] = atof( strRadius.GetBuffer() ); m_dVeci.GetWindowTextA( strRadius ); m_pstructOpt->vecCirNorm.x = atof( strRadius.GetBuffer() ); m_dVecj.GetWindowTextA( strRadius ); m_pstructOpt->vecCirNorm.y = atof( strRadius.GetBuffer() ); m_dVeck.GetWindowTextA( strRadius ); m_pstructOpt->vecCirNorm.z = atof( strRadius.GetBuffer() ); OnOK(); }
[ "srinivasreddy.challa@outlook.com" ]
srinivasreddy.challa@outlook.com
4a2a3c08fc2802f92244b5954ecce95840cf8c1d
5de6eab15d7b8c74601f4f255fe25399e763840a
/Message/MSG_ACI.h
bc2bec2341462f060f85f25ad8c3c66b57ccdc17
[]
no_license
shenwa12/vnoc
63f07f9784b68d0d927bdb2eacc4e7e32ccfb773
a9a296cdc3586c30e8a3052c29f25d77163c704e
refs/heads/master
2021-01-21T17:13:34.697955
2013-01-06T05:16:31
2013-01-06T05:16:31
null
0
0
null
null
null
null
GB18030
C++
false
false
2,306
h
#ifndef VNOC_MSG_ACI #define VNOC_MSG_ACI #include "BaseMessage.h" class MSG_ACI: public CMessage { public: MSG_ACI(){ //0x21 BEGIN_PARAM_LIST ADD_PARAM_LIST("RoomID") ADD_PARAM_LIST("RoomType") ADD_PARAM_LIST("RoomName") ADD_PARAM_LIST("RoomRank") ADD_PARAM_LIST("RoomState") ADD_PARAM_LIST("RoomPassword") ADD_PARAM_LIST("RoomPeopleNumMax") ADD_PARAM_LIST("RoomPeopleNum") ADD_PARAM_LIST("RoomPeopleList") ADD_PARAM_LIST("RoomManageID") INIT_PARAM_OBJEDT(33) END_PARAM_LIST } virtual ~MSG_ACI(){} public: //获取房间ID:要获取信息的房间的ID uint GetRoomID() const GetParam_t_int_r("RoomID",4); uint GetRoomType() const GetParam_t_int_r("RoomType",4); const byte* GetRoomName() const GetParam_t_r("RoomName"); uint GetRoomRank() const GetParam_t_int_r("RoomRank",4); uint GetRoomState() const GetParam_t_int_r("RoomState",4); const byte* GetRoomPassword() const GetParam_t_r("RoomPassword"); uint GetRoomPeopleNumMax() const GetParam_t_int_r("RoomPeopleNumMax",4); uint GetRoomPeopleNum() const GetParam_t_int_r("RoomPeopleNum",4); int GetRoomPeopleList(std::vector<int>& PeopleList) const GetParam_t_tamp_r("RoomPeopleList",int,PeopleList); uint GetRoomManageID() const GetParam_t_int_r("RoomManageID",4); void SetRoomID(uint in_int) SetParam_t("RoomID",in_int); void SetRoomType(uint in_int) SetParam_t("RoomType",in_int); void SetRoomName(const byte* in_byte_ptr,size_t len) SetParam_t_ptr("RoomName",in_byte_ptr,len); void SetRoomRank(uint in_int) SetParam_t("RoomRank",in_int); void SetRoomState(uint in_int) SetParam_t("RoomState",in_int); void SetRoomPassword(const byte* in_byte_ptr,size_t len) SetParam_t_ptr("RoomPassword",in_byte_ptr,len); void SetRoomPeopleNumMax(uint in_int) SetParam_t("RoomPeopleNumMax",in_int); void SetRoomPeopleNum(uint in_int) SetParam_t("RoomPeopleNum",in_int); void SetRoomPeopleList(std::vector<int> PeopleList) SetParam_t_tamp("RoomPeopleList",int,PeopleList); void SetRoomManageID(uint in_int) SetParam_t("RoomManageID",in_int); int GetRoomNameLen() const GetParamLen_t_r("RoomName"); int GetRoomPasswordLen() const GetParamLen_t_r("RoomPassword"); int GetPeopleListSize() const{ return (CMessage::GetParamLen(8) / 4); } }; #endif
[ "308974268@qq.com" ]
308974268@qq.com
18408d9ec908977227dc94178ef7da7cf5cc8dd4
1deb0ea79422612f85e6db636a68749fcedf34e5
/EndPoint/TI/workspace/pru_mcasp_sine_test/src/main.cpp
0ed2060ad1f40d6910f68b4534d85d4c7e59b85c
[]
no_license
bezumec82/SoundDevice
442dd1992968ae4db0cf6932d83da4f952a74863
6dd197904bad2476f79f3ed06b7aca230a73db45
refs/heads/master
2022-11-16T05:00:46.808080
2020-07-14T09:58:25
2020-07-14T09:58:25
269,723,634
0
0
null
null
null
null
UTF-8
C++
false
false
2,999
cpp
#include "main.h" long Get_timestamp_ms(void) { struct timespec tspec = { 0 , 0 }; clock_gettime(CLOCK_REALTIME, &tspec); return (((long) ((round(tspec.tv_nsec / 1.0e6)) + tspec.tv_sec * 1000)) & 0xffff); } /*----------------------------------------------------------------------------*/ #define POLL_FDS_AMMNT 4 #define PRU0_MCASP0_TS0_POLL_IDX 0 #define PRU0_MCASP0_TS1_POLL_IDX 1 #define PRU1_MCASP1_TS0_POLL_IDX 2 #define PRU1_MCASP1_TS1_POLL_IDX 3 #define POLL_TIMEOUT 100 #define PRU0_MCASP0 1 #define PRU1_MCASP1 1 int main() { int ret_val; unsigned long pstart_time_stamp; struct pollfd fds[POLL_FDS_AMMNT]; /* pru# mcasp# ts# */ mcasp_ts * pru0_mcasp0_ts0 = new mcasp_ts(PRU0, MCASP0, TS0); mcasp_ts * pru0_mcasp0_ts1 = new mcasp_ts(PRU0, MCASP0, TS1); mcasp_ts * pru1_mcasp1_ts0 = new mcasp_ts(PRU1, MCASP1, TS0); mcasp_ts * pru1_mcasp1_ts1 = new mcasp_ts(PRU1, MCASP1, TS1); fds[PRU0_MCASP0_TS0_POLL_IDX].fd = pru0_mcasp0_ts0->fd; fds[PRU0_MCASP0_TS0_POLL_IDX].events = POLLOUT; fds[PRU0_MCASP0_TS0_POLL_IDX].revents = 0; fds[PRU0_MCASP0_TS1_POLL_IDX].fd = pru0_mcasp0_ts1->fd; fds[PRU0_MCASP0_TS1_POLL_IDX].events = POLLOUT; fds[PRU0_MCASP0_TS1_POLL_IDX].revents = 0; fds[PRU1_MCASP1_TS0_POLL_IDX].fd = pru1_mcasp1_ts0->fd; fds[PRU1_MCASP1_TS0_POLL_IDX].events = POLLOUT; fds[PRU1_MCASP1_TS0_POLL_IDX].revents = 0; fds[PRU1_MCASP1_TS1_POLL_IDX].fd = pru1_mcasp1_ts1->fd; fds[PRU1_MCASP1_TS1_POLL_IDX].events = POLLOUT; fds[PRU1_MCASP1_TS1_POLL_IDX].revents = 0; while (1) { pstart_time_stamp = Get_timestamp_ms(); ret_val = poll ( fds, /* The set of file descriptors to be monitored. */ POLL_FDS_AMMNT, /* The number of items in the array of 'struct pollfd' type. */ POLL_TIMEOUT /* The number of milliseconds that 'poll()' should block waiting for a file descriptor to become ready. */ ); if (ret_val == -1) { FPRINTF; } if (!ret_val) { PRINT_ERR("Timeout!.\r\n" "%49s Elapsed %lums.\r\n", "", (Get_timestamp_ms() - pstart_time_stamp)); continue; } if (fds[PRU0_MCASP0_TS0_POLL_IDX].revents & POLLOUT) { pru0_mcasp0_ts0->write_sin(); } if (fds[PRU0_MCASP0_TS1_POLL_IDX].revents & POLLOUT) { pru0_mcasp0_ts1->write_sin(); } if (fds[PRU1_MCASP1_TS0_POLL_IDX].revents & POLLOUT) { pru1_mcasp1_ts0->write_sin(); } if (fds[PRU1_MCASP1_TS1_POLL_IDX].revents & POLLOUT) { pru1_mcasp1_ts1->write_sin(); } } //end while (1) return 0; }
[ "laskov82@gmail.com" ]
laskov82@gmail.com
9616cac0f5c597b3208f846d52583a06a2bfe9c1
9216eb383e166c8265790c2d6cc3bc5d9e23f11f
/src/Nodes/Ethernet.old/Node.c++
7b610ef0d30a5bca33a410a15d4c9ebf5d1395ea
[]
no_license
phatcabbage/EDNAS
fca7d88b092fb008847c335bae27eb7352eca6d6
90f57129c1e584acbf818e75efbb08b462097de8
refs/heads/master
2016-09-06T18:06:03.539627
2011-12-07T02:31:44
2011-12-07T02:31:44
2,929,741
1
0
null
null
null
null
UTF-8
C++
false
false
167
#include "EthernetNode.h++" namespace Logging { template<> OStreamLogger Logged<Nodes::EthernetBase>:: Logger("EthernetBase"); } namespace Nodes { }
[ "phatcabbage@gmail.com" ]
phatcabbage@gmail.com
8bebd6291a1d8533f0fb5b9754ed86a9c2955c35
1c8e5a1fc7f9dfee4969194c1bd77918eea73095
/Source/AllProjects/CIDLib/CIDLib_Audio.hpp
35130a5cdf1d0e689f023962837032491df8be51
[]
no_license
naushad-rahman/CIDLib
bcb579a6f9517d23d25ad17a152cc99b7508330e
577c343d33d01e0f064d76dfc0b3433d1686f488
refs/heads/master
2020-04-28T01:08:35.084154
2019-03-10T02:03:20
2019-03-10T02:03:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,823
hpp
// // FILE NAME: CIDLib_Audio.hpp // // AUTHOR: Dean Roddey // // CREATED: 11/08/1993 // // COPYRIGHT: $_CIDLib_CopyRight_$ // // $_CIDLib_CopyRight2_$ // // DESCRIPTION: // // TAudio is a namespace that does various beeps, bonks, zings, and // honks all of which are given enumerated values. It also supports basic // playing of Wav files. // // This stuff is built on top of TKrnlAudio, which encapsulates the system // audio services. He will sense whether the workstation has audio services // or not and use them if there. If not there, it will use the system speaker // where possible, basically just doing the best it can given the issues // involved. // // CAVEATS/GOTCHAS: // // LOG: // // $_CIDLib_Log_$ // #pragma once namespace TAudio { CIDLIBEXP tCIDLib::TVoid AudioCue ( const tCIDLib::EAudioCues eCue ); CIDLIBEXP tCIDLib::TVoid Beep ( const tCIDLib::TCard4 c4Frequency , const tCIDLib::TCard4 c4Duration ); CIDLIBEXP tCIDLib::TCard4 c4EnumAudioDevices ( tCIDLib::TKVPCollect& colToFill ); CIDLIBEXP tCIDLib::TVoid MuteSystemAudio ( const tCIDLib::TBoolean bToSet ); CIDLIBEXP tCIDLib::TVoid PlayWAVFile ( const TString& strFileToPlay , const tCIDLib::EWaitModes eWait = tCIDLib::EWaitModes::Wait ); CIDLIBEXP tCIDLib::TVoid QuerySystemVolume ( tCIDLib::TCard4& c4ToFill ); CIDLIBEXP tCIDLib::TVoid SetWAVForCue ( const tCIDLib::EAudioCues eCue , const TString& strFileForCue ); CIDLIBEXP TString strDevInfo(); CIDLIBEXP tCIDLib::TVoid SetSystemVolume ( const tCIDLib::TCard4 c4Percent ); }
[ "droddey@charmedquark.com" ]
droddey@charmedquark.com
6a9e7044656203f149a4596ed9a07d7934f78b32
93dfb034dab214dd9883070a044559c16a9aa7a8
/week11/week11/week11/main.cpp
9942c1a71e39768fdf78f383fb69abb7e9ba39de
[]
no_license
sexandmath/CS_HW
ccfb9704b934ccd3c5839df8019174c3aeca95a4
a9801599a40ebdf4176f59a0522a59acc923fbbe
refs/heads/main
2023-04-11T00:15:52.188202
2021-04-23T05:39:03
2021-04-23T05:39:03
339,978,172
0
0
null
null
null
null
UTF-8
C++
false
false
10,861
cpp
#include <SFML/Graphics.hpp> #include <chrono> #include <math.h> #include <vector> #include <list> #include <memory> #include <random> struct Constants { const static int Width = 1200; const static int Height = 800; constexpr static float deg_to_rad = 0.017453f; }; int my_random() { std::default_random_engine dre(static_cast <std::size_t> (std::chrono::system_clock::now().time_since_epoch().count())); std::uniform_int_distribution<> my_random(0, RAND_MAX); return my_random(dre); } class Animation { public: Animation(){} Animation(sf::Texture &tex, std::size_t x, std::size_t y, int w, int h, std::size_t number_of_img, float speed): m_frame(0), m_speed(speed) { for(auto i = 0; i < number_of_img; ++i) { m_frames.push_back(sf::IntRect(x+i*w, y, w, h)); } sprite.setTexture(tex); sprite.setOrigin(w/2,h/2); sprite.setTextureRect(m_frames[0]); } ~Animation() noexcept = default; public: void update() { m_frame += m_speed; auto n = std::size(m_frames); if (m_frame >= n) m_frame -= n; if (n > 0) sprite.setTextureRect(m_frames[static_cast<int>(m_frame)]); } bool isEnd() { return m_frame + m_speed >= std::size(m_frames); } public: sf::Sprite sprite; private: float m_frame; float m_speed; std::vector<sf::IntRect> m_frames; }; class Entity { public: Animation anim; float x, y, dx, dy, R, angle; bool life; std::string name; Entity(): life(true) {} void settings(Animation& a, int X, int Y, float Angle = 0, int radius = 1) // ��� float 0.0f { anim = a; x = X; y = Y; angle = Angle; R = radius; } virtual void update() {}; void draw(sf::RenderWindow & app) { anim.sprite.setPosition(x, y); anim.sprite.setRotation(angle + 90); app.draw(anim.sprite); } virtual ~Entity() noexcept = default; }; class Asteroid : public Entity { public: Asteroid() { dx = my_random() % 8 - 4; dy = my_random() % 8 - 4; name = "Asteroid"; } private: void update() { x += dx; y += dy; if (x > Constants::Width) x = 0; if (x < 0) x = Constants::Width; if (y > Constants::Height) y = 0; if (y < 0) y = Constants::Height; } }; class Bullet : public Entity { public: Bullet() { name = "Bullet"; } private: void update() { dx = cos(angle * Constants::deg_to_rad) * 6; dy = sin(angle * Constants::deg_to_rad) * 6; x += dx; y += dy; if (x > Constants::Width || x < 0 || y > Constants::Height || y < 0) life = 0; } }; class Player : public Entity { public: bool thrust; std::size_t lives = 3; std::size_t score; Player() { score = 0; name = "Player"; } bool isAlive() { return (lives > 0); } void score_increase() { ++score; } void lives_decrease() { --lives; } private: void update() // override ? { if (thrust) { dx += std::cos(angle * Constants::deg_to_rad) * 0.2; dy += std::sin(angle * Constants::deg_to_rad) * 0.2; } else { dx *= 0.99; dy *= 0.99; } float speed = sqrt(dx * dx + dy * dy); if (speed > maxSpeed) { dx *= maxSpeed / speed; dy *= maxSpeed / speed; } x += dx; y += dy; if (x > Constants::Width) x = 0; if (x < 0) x = Constants::Width; if (y > Constants::Height) y = 0; if (y < 0) y = Constants::Height; } private: const int maxSpeed = 15; }; class Game { public: Game(){} void run() { sf::RenderWindow app(sf::VideoMode(Constants::Width, Constants::Height), "ASTEROIDS"); app.setFramerateLimit(60); sf::Font font; font.loadFromFile("arial.ttf"); sf::Text text; text.setFont(font); text.setFillColor(sf::Color::Cyan); sf::Texture t1,t2,t3,t4,t5,t6,t7; t1.loadFromFile("images/spaceship.png"); t2.loadFromFile("images/background.jpg"); t3.loadFromFile("images/explosions/type_C.png"); t4.loadFromFile("images/rock.png"); t5.loadFromFile("images/fire_blue.png"); t6.loadFromFile("images/rock_small.png"); t7.loadFromFile("images/explosions/type_B.png"); t1.setSmooth(true); t2.setSmooth(true); sf::Sprite background(t2); Animation sExplosion(t3, 0,0,256,256, 48, 0.5); Animation sRock(t4, 0,0,64,64, 16, 0.2); Animation sRock_small(t6, 0,0,64,64, 16, 0.2); Animation sBullet(t5, 0,0,32,64, 16, 0.8); Animation sPlayer(t1, 40,0,40,40, 1, 0); Animation sPlayer_go(t1, 40,40,40,40, 1, 0); Animation sExplosion_ship(t7, 0,0,192,192, 64, 0.5); creating_asteroids(sRock); std::shared_ptr<Player> p = creating_player(sPlayer); while (app.isOpen() && p->isAlive()) { text.setString("score: " + std::to_string(p->score) + "\nLifes: " + std::to_string(p->lives)); sf::Event event; while (app.pollEvent(event)) { switch(event.type) { case sf::Event::Closed: app.close(); break; case sf::Event::KeyPressed: if (event.key.code == sf::Keyboard::Space) { std::shared_ptr<Bullet> b(new Bullet); b->settings(sBullet, p->x, p->y, p->angle, 10); entities.push_back(b); } break; default: break; } } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) p->angle += 3; if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) p->angle -= 3; if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) p->thrust = true; else p->thrust = false; for (auto a : entities) for (auto b : entities) { if (a->name == "Asteroid" && b->name == "Bullet") if (a->anim.sprite.getGlobalBounds().intersects(b->anim.sprite.getGlobalBounds())) { a->life = false; b->life = false; std::shared_ptr<Entity> e(new Entity); e->settings(sExplosion, a->x, a->y); e->name = "Explosion"; entities.push_back(e); for ( int i =0; i < 2; ++i) { if (a->R == 15) { continue; } std::shared_ptr<Entity> e(new Asteroid); e->settings(sRock_small, a->x, a->y, rand() % 360, 15); entities.push_back(e); } p->score_increase(); } if (a->name == "Player" && b->name == "Asteroid") if (a->anim.sprite.getGlobalBounds().intersects(b->anim.sprite.getGlobalBounds())) { b->life = false; std::shared_ptr<Entity> e(new Entity); e->settings(sExplosion_ship, a->x, a->y); e->name = "Explosion"; entities.push_back(e); p->settings(sPlayer, Constants::Width / 2, Constants::Height / 2, 0, 20); p->dx = 0; p->dy = 0; p->lives_decrease(); } } if (p->thrust) p->anim = sPlayer_go; else p->anim = sPlayer; for (auto e : entities) if (e->name == "Explosion") if (e->anim.isEnd()) e->life = 0; if (my_random() % 150 == 0) { std::shared_ptr<Asteroid> a(new Asteroid); a->settings(sRock, 0, my_random()% Constants::Height, rand() % 360, 25); entities.push_back(a); } for (auto i = entities.begin(); i != entities.end();) { std::shared_ptr<Entity> e = *i; e->update(); e->anim.update(); if (e->life == false) { i = entities.erase(i); } else ++i; } app.draw(background); for (auto i : entities) i->draw(app); app.draw(text); app.display(); } } private: void creating_asteroids(Animation anim) { for (auto i = 0; i < 15; ++i) { std::shared_ptr<Asteroid> a(new Asteroid); a->settings(anim, my_random() % Constants::Width, my_random() % Constants::Height, my_random() % 360, 25); entities.push_back(a); } } std::shared_ptr<Player> creating_player(Animation anim) { std::shared_ptr<Player> p(new Player); p->settings(anim, 300, 250, 0, 20); entities.push_back(p); return p; } private: std::list<std::shared_ptr<Entity>> entities; }; int main() { Game game; game.run(); return 0; }
[ "pavlova.vd@phystech.edu" ]
pavlova.vd@phystech.edu
6319bd5e84e837fa93b3dc619ff1697c01676085
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/3rdParty/boost/libs/config/test/no_sfinae_pass.cpp
ec36a0ed667d4f6a44444dc4e30acc5cea2e5a42
[]
no_license
bugbit/cipsaoscar
601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4
52aa8b4b67d48f59e46cb43527480f8b3552e96d
refs/heads/master
2021-01-10T21:31:18.653163
2011-09-28T16:39:12
2011-09-28T16:39:12
33,032,640
0
0
null
null
null
null
UTF-8
C++
false
false
1,146
cpp
// This file was automatically generated on Sun Jul 25 11:47:49 GMTDT 2004, // by libs/config/tools/generate // Copyright John Maddock 2002-4. // Use, modification and distribution are subject to 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) // See http://www.boost.org/libs/config for the most recent version. // Test file for macro BOOST_NO_SFINAE // This file should compile, if it does not then // BOOST_NO_SFINAE needs to be defined. // see boost_no_sfinae.ipp for more details // Do not edit this file, it was generated automatically by // ../tools/generate from boost_no_sfinae.ipp on // Sun Jul 25 11:47:49 GMTDT 2004 // Must not have BOOST_ASSERT_CONFIG set; it defeats // the objective of this file: #ifdef BOOST_ASSERT_CONFIG # undef BOOST_ASSERT_CONFIG #endif #include <boost/config.hpp> #include "test.hpp" #ifndef BOOST_NO_SFINAE #include "boost_no_sfinae.ipp" #else namespace boost_no_sfinae = empty_boost; #endif int main( int, char *[] ) { return boost_no_sfinae::test(); }
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a
0ffe60a5de7e8f5579d1971326445fba2e3c8e2f
2d483bccf76da70d8277dc4b1740d03d57b0702a
/Final Project/Final Project/Point.cpp
64bd91fc9cf1c44a4476e7a005013055eb128dd6
[]
no_license
celr/graphics
346bc130a70486f0df17d1d23082cb22725f6b8e
a706012e2261f17f36199e58956bd4bdf434927c
refs/heads/master
2020-12-24T17:25:55.869890
2013-05-31T02:57:24
2013-05-31T02:57:24
10,181,317
0
0
null
2016-10-31T06:30:02
2013-05-20T20:30:27
C++
UTF-8
C++
false
false
495
cpp
#include "stdafx.h" #include "Point.h" float vectorDot(Point a, Point b) { return a.x * b.x + a.y * b.y + a.z * b.z; } Point vectorScale(float scale, Point v) { Point p; p.x = scale * v.x; p.y = scale * v.y; p.z = scale * v.z; return p; } float vectorMag(Point v) { return sqrt(pow(v.x, 2) + pow(v.y, 2) + pow(v.z, 2)); } Point vectorCross(Point a, Point b) { Point p; p.x = (a.y * b.z) - (a.z * b.y); p.y = (a.z * b.x) - (a.x * b.z); p.z = (a.x * b.y) - (a.y * b.x); return p; }
[ "carlos@blewblew.com" ]
carlos@blewblew.com
64ad2a402bae7676465882000aaa7c32db6fb8a3
434db926371b4fcee11c530baac9eccd8edbb0b7
/bee_lvl2_converter/bee.cpp
adfe4a99332e5a54314f0af6131f86732b2688f7
[]
no_license
asdlei99/hidden_bee_tools
2dbe9a6cb613d078cbd9c22d32c1fe81436cb650
711583e7ca517cd690c1483da52eb72fd62e1335
refs/heads/master
2023-05-10T05:40:27.380457
2021-06-03T23:19:28
2021-06-03T23:19:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,538
cpp
#include "bee.h" #include <peconv.h> BEE_TYPE check_type(BYTE *buf, size_t buf_size) { if (memcmp(buf, &MAGIC2, sizeof(MAGIC2)) == 0) { return BEE_SCRAMBLED2; } if (memcmp(buf, &MAGIC1, sizeof(MAGIC1)) == 0) { return BEE_SCRAMBLED1; } if (memcmp(buf, &NS_MAGIC, sizeof(NS_MAGIC)) == 0) { return BEE_NS_FORMAT; } return BEE_NONE; } template <typename T_BEE_SCRAMBLED> bool unscramble_pe(BYTE *buf, size_t buf_size) { T_BEE_SCRAMBLED *hdr = (T_BEE_SCRAMBLED*)buf; std::cout << std::hex << "Magic: " << hdr->magic << "\nMachineId: " << hdr->machine_id << "\nOffset: " << hdr->pe_offset << std::endl; WORD *mz_ptr = (WORD*)buf; DWORD *pe_ptr = (DWORD*)(buf + hdr->pe_offset); *mz_ptr = IMAGE_DOS_SIGNATURE; *pe_ptr = IMAGE_NT_SIGNATURE; IMAGE_DOS_HEADER* dos_hdr = (IMAGE_DOS_HEADER*)buf; dos_hdr->e_lfanew = hdr->pe_offset; IMAGE_FILE_HEADER* file_hdrs = const_cast<IMAGE_FILE_HEADER*>(peconv::get_file_hdr(buf, buf_size)); if (!file_hdrs) return false; file_hdrs->Machine = hdr->machine_id; return true; } bool unscramble_bee_to_pe(BYTE *buf, size_t buf_size) { BEE_TYPE type = check_type(buf, buf_size); if (type == BEE_NONE) { std::cout << "Not a Hidden Bee module!\n"; return false; } std::cout << "Type: " << type << std::endl; if (type == BEE_SCRAMBLED2) { unscramble_pe<t_scrambled2>(buf, buf_size); } if (type == BEE_SCRAMBLED1) { unscramble_pe<t_scrambled1>(buf, buf_size); } if (type == BEE_NS_FORMAT) { ns_exe::unscramble_pe(buf, buf_size); } return true; }
[ "hasherezade@gmail.com" ]
hasherezade@gmail.com
e6126a0ac0892ff03a7352bf458c9294e91d7f29
f24c9c3eb1124be176015ffec9c6f5763009f2dc
/KetaminRudwolf/src/render/GUIRenderer.cpp
de27ef4c2979bb4c0b2f9febe082e929f655437b
[ "Apache-2.0" ]
permissive
Vasile2k/KetaminRudwolf
0fbdd911d381c0619faebd9e65147be14fbdca31
8e1703a2737c2ff914380a14c71f679e27786a10
refs/heads/master
2020-04-16T07:57:10.802826
2019-01-17T08:57:59
2019-01-17T08:57:59
165,405,264
5
0
null
null
null
null
UTF-8
C++
false
false
2,126
cpp
#include "GUIRenderer.hpp" #include "../game/Game.hpp" #define NK_INCLUDE_FIXED_TYPES #define NK_INCLUDE_STANDARD_IO #define NK_INCLUDE_STANDARD_VARARGS #define NK_INCLUDE_DEFAULT_ALLOCATOR #define NK_INCLUDE_VERTEX_BUFFER_OUTPUT #define NK_INCLUDE_FONT_BAKING #define NK_INCLUDE_DEFAULT_FONT #define NK_IMPLEMENTATION #define NK_GLFW_GL3_IMPLEMENTATION #define NK_KEYSTATE_BASED_INPUT #include <nuklear.h> #include <nuklear_glfw_gl3.h> #define MAX_VERTEX_BUFFER 512 * 1024 #define MAX_ELEMENT_BUFFER 128 * 1024 struct nk_context *ctx; struct nk_colorf bg; GUIRenderer* GUIRenderer::instance = nullptr; GUIRenderer::GUIRenderer() { bg.r = 0.10f; bg.g = 0.18f; bg.b = 0.24f; bg.a = 0.25f; ctx = nk_glfw3_init(Game::getInstance()->getWindow()->getGLFWWindow(), NK_GLFW3_DEFAULT); struct nk_font_atlas *atlas; nk_glfw3_font_stash_begin(&atlas); struct nk_font *clean = nk_font_atlas_add_from_file(atlas, "res/font/ProggyClean.ttf", 24, 0); nk_glfw3_font_stash_end(); nk_style_load_all_cursors(ctx, atlas->cursors); nk_style_set_font(ctx, &clean->handle); } GUIRenderer::~GUIRenderer() {} GUIRenderer* GUIRenderer::getInstance() { if (instance == nullptr) { instance = new GUIRenderer(); } return instance; } void GUIRenderer::render() { nk_glfw3_render(NK_ANTI_ALIASING_OFF, MAX_VERTEX_BUFFER, MAX_ELEMENT_BUFFER); } void GUIRenderer::newFrame() { nk_glfw3_new_frame(); } void GUIRenderer::begin(const char* title, float x, float y, float width, float height) { nk_begin(ctx, title, nk_rect(x, y, width, height), NK_WINDOW_NO_SCROLLBAR); } void GUIRenderer::beginBorderedWindow(const char* title, float x, float y, float width, float height) { nk_begin(ctx, title, nk_rect(x, y, width, height), NK_WINDOW_NO_SCROLLBAR | NK_WINDOW_BACKGROUND | NK_WINDOW_BORDER); } void GUIRenderer::end() { nk_end(ctx); } void GUIRenderer::row(float height, int cols) { nk_layout_row_dynamic(ctx, height, cols); } bool GUIRenderer::button(const char *title) { return nk_button_label(ctx, title); } bool GUIRenderer::optionLabel(const char* title, bool active) { return nk_option_label(ctx, title, active); }
[ "andy.dorcu@yahoo.com" ]
andy.dorcu@yahoo.com
27ab93eb7e004bd19ff9b7f0d2f5f84ef07c13df
6338150e6083272fcb5ce0f9b2b228be0dc80cdd
/aieBootstrap-master/PhysicsEngine/PhysicsEngineApp.cpp
085728a71d6a821564f606af5e4cf4a79dbd8ab2
[ "MIT" ]
permissive
Goodii/PhysicsForGames
55f162c1fe5a7c252b7aa10ac7aa19df3e3ee0e4
202ce3d82c6ad15774f6b0874bdaa4190278ec74
refs/heads/master
2018-09-05T13:34:15.435709
2018-06-04T12:59:06
2018-06-04T12:59:06
120,531,377
0
0
null
null
null
null
UTF-8
C++
false
false
3,171
cpp
#include "PhysicsEngineApp.h" #include "Texture.h" #include "Font.h" #include "Input.h" #include <Gizmos.h> #include <glm/glm.hpp> #include <glm/ext.hpp> #include "Sphere.h" PhysicsEngineApp::PhysicsEngineApp() { } PhysicsEngineApp::~PhysicsEngineApp() { } bool PhysicsEngineApp::startup() { aie::Gizmos::create(255U, 255U, 65535U, 65535U); m_2dRenderer = new aie::Renderer2D(); // TODO: remember to change this when redistributing a build! // the following path would be used instead: "./font/consolas.ttf" m_font = new aie::Font("../bin/font/consolas.ttf", 32); m_physicsScene = new PhysicsScene(); m_physicsScene->setGravity(glm::vec2(0, -10.f)); m_physicsScene->setTimeStep(0.01f); Sphere* ball1 = new Sphere(glm::vec2(-20, 0), glm::vec2(0, 0), 5.f, 4.f, glm::vec4(1, 0, 0, 1)); Sphere* ball2 = new Sphere(glm::vec2(20, 0), glm::vec2(0, 0), 5.f, 4.f, glm::vec4(0, 1, 0, 1)); m_physicsScene->addActor(ball1); m_physicsScene->addActor(ball2); //ball1->applyForceToActor(ball2, glm::vec2(2, 0)); ball1->applyForce(glm::vec2(30, 150)); ball2->applyForce(glm::vec2(-31, 148)); return true; } void PhysicsEngineApp::shutdown() { delete m_font; delete m_2dRenderer; delete m_physicsScene; } void PhysicsEngineApp::update(float deltaTime) { aie::Gizmos::clear(); // input example aie::Input* input = aie::Input::getInstance(); m_physicsScene->update(deltaTime); m_physicsScene->updateGizmos(); //static const glm::vec4 colours[] = {glm::vec4(1,0,0,1), glm::vec4(0,1,0,1), glm::vec4(0,0,1,1), glm::vec4(0.8f,0,0.5f,1), glm::vec4(0,1,1,1) }; // //static const int rows = 5; //static const int columns = 10; //static const int hSpace = 1; //static const int vSpace = 1; // //static const glm::vec2 scrExtents(100, 50); //static const glm::vec2 boxExtents(7, 3); //static const glm::vec2 startPos(-(columns >> 1)*((boxExtents.x * 2) + vSpace) + boxExtents.x + (vSpace / 2.0f), // scrExtents.y - ((boxExtents.y * 2) + hSpace)); // ////draw grid of blocks //glm::vec2 pos; //for (int y = 0; y < rows; y++) //{ // pos = glm::vec2(startPos.x, startPos.y - (y * ((boxExtents.y * 2) + hSpace))); // // for (int x = 0; x < columns; x++) // { // aie::Gizmos::add2DAABBFilled(pos, boxExtents, colours[y]); // pos.x += (boxExtents.x * 2) + vSpace; // } //} // ////draw a ball //aie::Gizmos::add2DCircle(glm::vec2(0, -35), 3.f, 12, glm::vec4(1, 1, 0, 1)); // ////draw player //aie::Gizmos::add2DAABBFilled(glm::vec2(0, -40), glm::vec2(12, 2), glm::vec4(1, 0, 1, 1)); // exit the application if (input->isKeyDown(aie::INPUT_KEY_ESCAPE)) quit(); } void PhysicsEngineApp::draw() { // wipe the screen to the background colour clearScreen(); // begin drawing sprites m_2dRenderer->begin(); // draw your stuff here! // output some text, uses the last used colour m_2dRenderer->drawText(m_font, "Press ESC to quit", 0, 0); //gizmos draw float aspectRatio = (float)getWindowWidth() / getWindowHeight(); aie::Gizmos::draw2D(glm::ortho<float>(-100.f, 100.f, -100.f / aspectRatio, 100.f / aspectRatio, -1.f, 1.f)); // done drawing sprites m_2dRenderer->end(); }
[ "iPatt98@gmail.com" ]
iPatt98@gmail.com
a1973494eb606e0c55b5e13b9266822d12272c98
a5ff25a76f832aab675f653c11a127d65755c58a
/headers/glm/detail/type_mat4x3.inl
e02dedf577cdfdada7439669144010416fb16838
[]
no_license
LiuZhichang/ZVK
f5fd47d0cda575af842dafd7d68bed117b653053
e89a5e632eeaba9fc72d8e0f6f2d8f75e29c0da2
refs/heads/master
2023-08-16T03:24:12.135733
2021-10-20T01:40:58
2021-10-20T01:40:58
419,147,859
0
0
null
null
null
null
UTF-8
C++
false
false
20,054
inl
namespace glm { // -- Constructors -- # if GLM_CONFIG_DEFAULTED_FUNCTIONS == GLM_DISABLE template<typename T, qualifier Q> GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<4, 3, T, Q>::mat() # if GLM_CONFIG_CTOR_INIT == GLM_CTOR_INITIALIZER_LIST : value{col_type(1, 0, 0), col_type(0, 1, 0), col_type(0, 0, 1), col_type(0, 0, 0)} # endif { # if GLM_CONFIG_CTOR_INIT == GLM_CTOR_INITIALISATION this->value[0] = col_type(1, 0, 0); this->value[1] = col_type(0, 1, 0); this->value[2] = col_type(0, 0, 1); this->value[3] = col_type(0, 0, 0); # endif } # endif template<typename T, qualifier Q> template<qualifier P> GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<4, 3, T, Q>::mat(mat<4, 3, T, P> const &m) # if GLM_HAS_INITIALIZER_LISTS : value{col_type(m[0]), col_type(m[1]), col_type(m[2]), col_type(m[3])} # endif { # if !GLM_HAS_INITIALIZER_LISTS this->value[0] = m[0]; this->value[1] = m[1]; this->value[2] = m[2]; this->value[3] = m[3]; # endif } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<4, 3, T, Q>::mat(T const &s) # if GLM_HAS_INITIALIZER_LISTS : value{col_type(s, 0, 0), col_type(0, s, 0), col_type(0, 0, s), col_type(0, 0, 0)} # endif { # if !GLM_HAS_INITIALIZER_LISTS this->value[0] = col_type(s, 0, 0); this->value[1] = col_type(0, s, 0); this->value[2] = col_type(0, 0, s); this->value[3] = col_type(0, 0, 0); # endif } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<4, 3, T, Q>::mat ( T const &x0, T const &y0, T const &z0, T const &x1, T const &y1, T const &z1, T const &x2, T const &y2, T const &z2, T const &x3, T const &y3, T const &z3 ) # if GLM_HAS_INITIALIZER_LISTS : value{col_type(x0, y0, z0), col_type(x1, y1, z1), col_type(x2, y2, z2), col_type(x3, y3, z3)} # endif { # if !GLM_HAS_INITIALIZER_LISTS this->value[0] = col_type(x0, y0, z0); this->value[1] = col_type(x1, y1, z1); this->value[2] = col_type(x2, y2, z2); this->value[3] = col_type(x3, y3, z3); # endif } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<4, 3, T, Q>::mat(col_type const &v0, col_type const &v1, col_type const &v2, col_type const &v3) # if GLM_HAS_INITIALIZER_LISTS : value{col_type(v0), col_type(v1), col_type(v2), col_type(v3)} # endif { # if !GLM_HAS_INITIALIZER_LISTS this->value[0] = v0; this->value[1] = v1; this->value[2] = v2; this->value[3] = v3; # endif } // -- Conversion constructors -- template<typename T, qualifier Q> template< typename X0, typename Y0, typename Z0, typename X1, typename Y1, typename Z1, typename X2, typename Y2, typename Z2, typename X3, typename Y3, typename Z3> GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<4, 3, T, Q>::mat ( X0 const &x0, Y0 const &y0, Z0 const &z0, X1 const &x1, Y1 const &y1, Z1 const &z1, X2 const &x2, Y2 const &y2, Z2 const &z2, X3 const &x3, Y3 const &y3, Z3 const &z3 ) # if GLM_HAS_INITIALIZER_LISTS : value{col_type(x0, y0, z0), col_type(x1, y1, z1), col_type(x2, y2, z2), col_type(x3, y3, z3)} # endif { # if !GLM_HAS_INITIALIZER_LISTS this->value[0] = col_type(x0, y0, z0); this->value[1] = col_type(x1, y1, z1); this->value[2] = col_type(x2, y2, z2); this->value[3] = col_type(x3, y3, z3); # endif } template<typename T, qualifier Q> template<typename V1, typename V2, typename V3, typename V4> GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<4, 3, T, Q>::mat(vec<3, V1, Q> const &v1, vec<3, V2, Q> const &v2, vec<3, V3, Q> const &v3, vec<3, V4, Q> const &v4) # if GLM_HAS_INITIALIZER_LISTS : value{col_type(v1), col_type(v2), col_type(v3), col_type(v4)} # endif { # if !GLM_HAS_INITIALIZER_LISTS this->value[0] = col_type(v1); this->value[1] = col_type(v2); this->value[2] = col_type(v3); this->value[3] = col_type(v4); # endif } // -- Matrix conversions -- template<typename T, qualifier Q> template<typename U, qualifier P> GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<4, 3, T, Q>::mat(mat<4, 3, U, P> const &m) # if GLM_HAS_INITIALIZER_LISTS : value{col_type(m[0]), col_type(m[1]), col_type(m[2]), col_type(m[3])} # endif { # if !GLM_HAS_INITIALIZER_LISTS this->value[0] = col_type(m[0]); this->value[1] = col_type(m[1]); this->value[2] = col_type(m[2]); this->value[3] = col_type(m[3]); # endif } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<4, 3, T, Q>::mat(mat<2, 2, T, Q> const &m) # if GLM_HAS_INITIALIZER_LISTS : value{col_type(m[0], 0), col_type(m[1], 0), col_type(0, 0, 1), col_type(0)} # endif { # if !GLM_HAS_INITIALIZER_LISTS this->value[0] = col_type(m[0], 0); this->value[1] = col_type(m[1], 0); this->value[2] = col_type(0, 0, 1); this->value[3] = col_type(0); # endif } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<4, 3, T, Q>::mat(mat<3, 3, T, Q> const &m) # if GLM_HAS_INITIALIZER_LISTS : value{col_type(m[0]), col_type(m[1]), col_type(m[2]), col_type(0)} # endif { # if !GLM_HAS_INITIALIZER_LISTS this->value[0] = col_type(m[0]); this->value[1] = col_type(m[1]); this->value[2] = col_type(m[2]); this->value[3] = col_type(0); # endif } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<4, 3, T, Q>::mat(mat<4, 4, T, Q> const &m) # if GLM_HAS_INITIALIZER_LISTS : value{col_type(m[0]), col_type(m[1]), col_type(m[2]), col_type(m[3])} # endif { # if !GLM_HAS_INITIALIZER_LISTS this->value[0] = col_type(m[0]); this->value[1] = col_type(m[1]); this->value[2] = col_type(m[2]); this->value[3] = col_type(m[3]); # endif } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<4, 3, T, Q>::mat(mat<2, 3, T, Q> const &m) # if GLM_HAS_INITIALIZER_LISTS : value{col_type(m[0]), col_type(m[1]), col_type(0, 0, 1), col_type(0)} # endif { # if !GLM_HAS_INITIALIZER_LISTS this->value[0] = col_type(m[0]); this->value[1] = col_type(m[1]); this->value[2] = col_type(0, 0, 1); this->value[3] = col_type(0); # endif } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<4, 3, T, Q>::mat(mat<3, 2, T, Q> const &m) # if GLM_HAS_INITIALIZER_LISTS : value{col_type(m[0], 0), col_type(m[1], 0), col_type(m[2], 1), col_type(0)} # endif { # if !GLM_HAS_INITIALIZER_LISTS this->value[0] = col_type(m[0], 0); this->value[1] = col_type(m[1], 0); this->value[2] = col_type(m[2], 1); this->value[3] = col_type(0); # endif } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<4, 3, T, Q>::mat(mat<2, 4, T, Q> const &m) # if GLM_HAS_INITIALIZER_LISTS : value{col_type(m[0]), col_type(m[1]), col_type(0, 0, 1), col_type(0)} # endif { # if !GLM_HAS_INITIALIZER_LISTS this->value[0] = col_type(m[0]); this->value[1] = col_type(m[1]); this->value[2] = col_type(0, 0, 1); this->value[3] = col_type(0); # endif } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<4, 3, T, Q>::mat(mat<4, 2, T, Q> const &m) # if GLM_HAS_INITIALIZER_LISTS : value{col_type(m[0], 0), col_type(m[1], 0), col_type(m[2], 1), col_type(m[3], 0)} # endif { # if !GLM_HAS_INITIALIZER_LISTS this->value[0] = col_type(m[0], 0); this->value[1] = col_type(m[1], 0); this->value[2] = col_type(m[2], 1); this->value[3] = col_type(m[3], 0); # endif } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<4, 3, T, Q>::mat(mat<3, 4, T, Q> const &m) # if GLM_HAS_INITIALIZER_LISTS : value{col_type(m[0]), col_type(m[1]), col_type(m[2]), col_type(0)} # endif { # if !GLM_HAS_INITIALIZER_LISTS this->value[0] = col_type(m[0]); this->value[1] = col_type(m[1]); this->value[2] = col_type(m[2]); this->value[3] = col_type(0); # endif } // -- Accesses -- template<typename T, qualifier Q> GLM_FUNC_QUALIFIER typename mat<4, 3, T, Q>::col_type & mat<4, 3, T, Q>::operator[](typename mat<4, 3, T, Q>::length_type i) { assert(i < this->length()); return this->value[i]; } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER GLM_CONSTEXPR typename mat<4, 3, T, Q>::col_type const & mat<4, 3, T, Q>::operator[](typename mat<4, 3, T, Q>::length_type i) const { assert(i < this->length()); return this->value[i]; } // -- Unary updatable operators -- template<typename T, qualifier Q> template<typename U> GLM_FUNC_QUALIFIER mat<4, 3, T, Q> & mat<4, 3, T, Q>::operator=(mat<4, 3, U, Q> const &m) { this->value[0] = m[0]; this->value[1] = m[1]; this->value[2] = m[2]; this->value[3] = m[3]; return *this; } template<typename T, qualifier Q> template<typename U> GLM_FUNC_QUALIFIER mat<4, 3, T, Q> & mat<4, 3, T, Q>::operator+=(U s) { this->value[0] += s; this->value[1] += s; this->value[2] += s; this->value[3] += s; return *this; } template<typename T, qualifier Q> template<typename U> GLM_FUNC_QUALIFIER mat<4, 3, T, Q> & mat<4, 3, T, Q>::operator+=(mat<4, 3, U, Q> const &m) { this->value[0] += m[0]; this->value[1] += m[1]; this->value[2] += m[2]; this->value[3] += m[3]; return *this; } template<typename T, qualifier Q> template<typename U> GLM_FUNC_QUALIFIER mat<4, 3, T, Q> & mat<4, 3, T, Q>::operator-=(U s) { this->value[0] -= s; this->value[1] -= s; this->value[2] -= s; this->value[3] -= s; return *this; } template<typename T, qualifier Q> template<typename U> GLM_FUNC_QUALIFIER mat<4, 3, T, Q> & mat<4, 3, T, Q>::operator-=(mat<4, 3, U, Q> const &m) { this->value[0] -= m[0]; this->value[1] -= m[1]; this->value[2] -= m[2]; this->value[3] -= m[3]; return *this; } template<typename T, qualifier Q> template<typename U> GLM_FUNC_QUALIFIER mat<4, 3, T, Q> & mat<4, 3, T, Q>::operator*=(U s) { this->value[0] *= s; this->value[1] *= s; this->value[2] *= s; this->value[3] *= s; return *this; } template<typename T, qualifier Q> template<typename U> GLM_FUNC_QUALIFIER mat<4, 3, T, Q> & mat<4, 3, T, Q>::operator/=(U s) { this->value[0] /= s; this->value[1] /= s; this->value[2] /= s; this->value[3] /= s; return *this; } // -- Increment and decrement operators -- template<typename T, qualifier Q> GLM_FUNC_QUALIFIER mat<4, 3, T, Q> & mat<4, 3, T, Q>::operator++() { ++this->value[0]; ++this->value[1]; ++this->value[2]; ++this->value[3]; return *this; } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER mat<4, 3, T, Q> & mat<4, 3, T, Q>::operator--() { --this->value[0]; --this->value[1]; --this->value[2]; --this->value[3]; return *this; } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER mat<4, 3, T, Q> mat<4, 3, T, Q>::operator++(int) { mat<4, 3, T, Q> Result(*this); ++*this; return Result; } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER mat<4, 3, T, Q> mat<4, 3, T, Q>::operator--(int) { mat<4, 3, T, Q> Result(*this); --*this; return Result; } // -- Unary arithmetic operators -- template<typename T, qualifier Q> GLM_FUNC_QUALIFIER mat<4, 3, T, Q> operator+(mat<4, 3, T, Q> const& m) { return m; } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER mat<4, 3, T, Q> operator-(mat<4, 3, T, Q> const& m) { return mat<4, 3, T, Q>( -m[0], -m[1], -m[2], -m[3]); } // -- Binary arithmetic operators -- template<typename T, qualifier Q> GLM_FUNC_QUALIFIER mat<4, 3, T, Q> operator+(mat<4, 3, T, Q> const& m, T const &s ) { return mat<4, 3, T, Q>( m[0] + s, m[1] + s, m[2] + s, m[3] + s); } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER mat<4, 3, T, Q> operator+(mat<4, 3, T, Q> const& m1, mat<4, 3, T, Q> const &m2 ) { return mat<4, 3, T, Q>( m1[0] + m2[0], m1[1] + m2[1], m1[2] + m2[2], m1[3] + m2[3]); } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER mat<4, 3, T, Q> operator-(mat<4, 3, T, Q> const& m, T const &s ) { return mat<4, 3, T, Q>( m[0] - s, m[1] - s, m[2] - s, m[3] - s); } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER mat<4, 3, T, Q> operator-(mat<4, 3, T, Q> const& m1, mat<4, 3, T, Q> const &m2 ) { return mat<4, 3, T, Q>( m1[0] - m2[0], m1[1] - m2[1], m1[2] - m2[2], m1[3] - m2[3]); } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER mat<4, 3, T, Q> operator*(mat<4, 3, T, Q> const& m, T const &s ) { return mat<4, 3, T, Q>( m[0] * s, m[1] * s, m[2] * s, m[3] * s); } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER mat<4, 3, T, Q> operator*(T const& s, mat<4, 3, T, Q> const &m ) { return mat<4, 3, T, Q>( m[0] * s, m[1] * s, m[2] * s, m[3] * s); } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER typename mat<4, 3, T, Q>::col_type operator* ( mat<4, 3, T, Q> const& m, typename mat<4, 3, T, Q>::row_type const &v ) { return typename mat<4, 3, T, Q>::col_type( m[0][0] * v.x + m[1][0] * v.y + m[2][0] * v.z + m[3][0] * v.w, m[0][1] * v.x + m[1][1] * v.y + m[2][1] * v.z + m[3][1] * v.w, m[0][2] * v.x + m[1][2] * v.y + m[2][2] * v.z + m[3][2] * v.w); } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER typename mat<4, 3, T, Q>::row_type operator* ( typename mat<4, 3, T, Q>::col_type const &v, mat<4, 3, T, Q> const &m) { return typename mat<4, 3, T, Q>::row_type( v.x * m[0][0] + v.y * m[0][1] + v.z * m[0][2], v.x * m[1][0] + v.y * m[1][1] + v.z * m[1][2], v.x * m[2][0] + v.y * m[2][1] + v.z * m[2][2], v.x * m[3][0] + v.y * m[3][1] + v.z * m[3][2]); } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER mat<2, 3, T, Q> operator*(mat<4, 3, T, Q> const& m1, mat<2, 4, T, Q> const &m2 ) { return mat<2, 3, T, Q>( m1[0][0] * m2[0][0] + m1[1][0] * m2[0][1] + m1[2][0] * m2[0][2] + m1[3][0] * m2[0][3], m1[0][1] * m2[0][0] + m1[1][1] * m2[0][1] + m1[2][1] * m2[0][2] + m1[3][1] * m2[0][3], m1[0][2] * m2[0][0] + m1[1][2] * m2[0][1] + m1[2][2] * m2[0][2] + m1[3][2] * m2[0][3], m1[0][0] * m2[1][0] + m1[1][0] * m2[1][1] + m1[2][0] * m2[1][2] + m1[3][0] * m2[1][3], m1[0][1] * m2[1][0] + m1[1][1] * m2[1][1] + m1[2][1] * m2[1][2] + m1[3][1] * m2[1][3], m1[0][2] * m2[1][0] + m1[1][2] * m2[1][1] + m1[2][2] * m2[1][2] + m1[3][2] * m2[1][3]); } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER mat<3, 3, T, Q> operator*(mat<4, 3, T, Q> const& m1, mat<3, 4, T, Q> const &m2 ) { T const SrcA00 = m1[0][0]; T const SrcA01 = m1[0][1]; T const SrcA02 = m1[0][2]; T const SrcA10 = m1[1][0]; T const SrcA11 = m1[1][1]; T const SrcA12 = m1[1][2]; T const SrcA20 = m1[2][0]; T const SrcA21 = m1[2][1]; T const SrcA22 = m1[2][2]; T const SrcA30 = m1[3][0]; T const SrcA31 = m1[3][1]; T const SrcA32 = m1[3][2]; T const SrcB00 = m2[0][0]; T const SrcB01 = m2[0][1]; T const SrcB02 = m2[0][2]; T const SrcB03 = m2[0][3]; T const SrcB10 = m2[1][0]; T const SrcB11 = m2[1][1]; T const SrcB12 = m2[1][2]; T const SrcB13 = m2[1][3]; T const SrcB20 = m2[2][0]; T const SrcB21 = m2[2][1]; T const SrcB22 = m2[2][2]; T const SrcB23 = m2[2][3]; mat<3, 3, T, Q> Result; Result[0][0] = SrcA00 *SrcB00 + SrcA10 *SrcB01 + SrcA20 *SrcB02 + SrcA30 *SrcB03; Result[0][1] = SrcA01 *SrcB00 + SrcA11 *SrcB01 + SrcA21 *SrcB02 + SrcA31 *SrcB03; Result[0][2] = SrcA02 *SrcB00 + SrcA12 *SrcB01 + SrcA22 *SrcB02 + SrcA32 *SrcB03; Result[1][0] = SrcA00 *SrcB10 + SrcA10 *SrcB11 + SrcA20 *SrcB12 + SrcA30 *SrcB13; Result[1][1] = SrcA01 *SrcB10 + SrcA11 *SrcB11 + SrcA21 *SrcB12 + SrcA31 *SrcB13; Result[1][2] = SrcA02 *SrcB10 + SrcA12 *SrcB11 + SrcA22 *SrcB12 + SrcA32 *SrcB13; Result[2][0] = SrcA00 *SrcB20 + SrcA10 *SrcB21 + SrcA20 *SrcB22 + SrcA30 *SrcB23; Result[2][1] = SrcA01 *SrcB20 + SrcA11 *SrcB21 + SrcA21 *SrcB22 + SrcA31 *SrcB23; Result[2][2] = SrcA02 *SrcB20 + SrcA12 *SrcB21 + SrcA22 *SrcB22 + SrcA32 *SrcB23; return Result; } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER mat<4, 3, T, Q> operator*(mat<4, 3, T, Q> const& m1, mat<4, 4, T, Q> const &m2 ) { return mat<4, 3, T, Q>( m1[0][0] * m2[0][0] + m1[1][0] * m2[0][1] + m1[2][0] * m2[0][2] + m1[3][0] * m2[0][3], m1[0][1] * m2[0][0] + m1[1][1] * m2[0][1] + m1[2][1] * m2[0][2] + m1[3][1] * m2[0][3], m1[0][2] * m2[0][0] + m1[1][2] * m2[0][1] + m1[2][2] * m2[0][2] + m1[3][2] * m2[0][3], m1[0][0] * m2[1][0] + m1[1][0] * m2[1][1] + m1[2][0] * m2[1][2] + m1[3][0] * m2[1][3], m1[0][1] * m2[1][0] + m1[1][1] * m2[1][1] + m1[2][1] * m2[1][2] + m1[3][1] * m2[1][3], m1[0][2] * m2[1][0] + m1[1][2] * m2[1][1] + m1[2][2] * m2[1][2] + m1[3][2] * m2[1][3], m1[0][0] * m2[2][0] + m1[1][0] * m2[2][1] + m1[2][0] * m2[2][2] + m1[3][0] * m2[2][3], m1[0][1] * m2[2][0] + m1[1][1] * m2[2][1] + m1[2][1] * m2[2][2] + m1[3][1] * m2[2][3], m1[0][2] * m2[2][0] + m1[1][2] * m2[2][1] + m1[2][2] * m2[2][2] + m1[3][2] * m2[2][3], m1[0][0] * m2[3][0] + m1[1][0] * m2[3][1] + m1[2][0] * m2[3][2] + m1[3][0] * m2[3][3], m1[0][1] * m2[3][0] + m1[1][1] * m2[3][1] + m1[2][1] * m2[3][2] + m1[3][1] * m2[3][3], m1[0][2] * m2[3][0] + m1[1][2] * m2[3][1] + m1[2][2] * m2[3][2] + m1[3][2] * m2[3][3]); } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER mat<4, 3, T, Q> operator/(mat<4, 3, T, Q> const& m, T const &s ) { return mat<4, 3, T, Q>( m[0] / s, m[1] / s, m[2] / s, m[3] / s); } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER mat<4, 3, T, Q> operator/(T const& s, mat<4, 3, T, Q> const &m ) { return mat<4, 3, T, Q>( s / m[0], s / m[1], s / m[2], s / m[3]); } // -- Boolean operators -- template<typename T, qualifier Q> GLM_FUNC_QUALIFIER bool operator==(mat<4, 3, T, Q> const &m1, mat<4, 3, T, Q> const &m2) { return (m1[0] == m2[0]) && (m1[1] == m2[1]) && (m1[2] == m2[2]) && (m1[3] == m2[3]); } template<typename T, qualifier Q> GLM_FUNC_QUALIFIER bool operator!=(mat<4, 3, T, Q> const &m1, mat<4, 3, T, Q> const &m2) { return (m1[0] != m2[0]) || (m1[1] != m2[1]) || (m1[2] != m2[2]) || (m1[3] != m2[3]); } } //namespace glm
[ "3318619633@qq.com" ]
3318619633@qq.com
efc716ce46c755b10cd2cdd852c8f8baff82b143
9c65b7cb50f96499cf8e1d72b8283ff34be90abc
/triangle/main.cpp
cf0837e0e3e707073db5d86b8d185ae7cf7ac1c4
[]
no_license
Lacty/Glfw
6b2ca36f3c0dd5f99080dc9e59c67838c5d9c113
f0ba17103aed3f2a4fff2ce3a8af4a4ed5f82555
refs/heads/master
2016-08-12T18:54:37.345396
2016-02-03T10:59:30
2016-02-03T10:59:30
48,664,830
2
0
null
null
null
null
UTF-8
C++
false
false
758
cpp
#include <iostream> #include <GLFW/glfw3.h> int main() { GLFWwindow* window; if (!glfwInit()) { return -1; } window = glfwCreateWindow(640, 480, "triangle", nullptr, nullptr); if (!window) { glfwTerminate(); return -1; } glfwMakeContextCurrent(window); while(!glfwWindowShouldClose(window)) { glClearColor(0.4f, 0.4f, 0.4f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); GLfloat vtx[] = { 0.0f, 0.433f, -0.5f, -0.433f, 0.5f, -0.433f }; glVertexPointer(2, GL_FLOAT, 0, vtx); glEnableClientState(GL_VERTEX_ARRAY); glDrawArrays(GL_TRIANGLES, 0, 3); glDisableClientState(GL_VERTEX_ARRAY); glfwSwapBuffers(window); glfwPollEvents(); } glfwTerminate(); return 0; }
[ "akira206@gmail.com" ]
akira206@gmail.com
2db3783b9a86a70ee00e4cad04aed063c33dbf1c
95ee706550cd45c57dd5fe01805aa4291b9193bc
/src/renderer/raytracer/RayTracer.h
e5d79357e3525c66e36f71f0ceb93f245f65e5b3
[]
no_license
DylanMeeus/3DRenderingFramework
2bd5b194220c3b88c0c15a4cd2d1b9f9aab9548c
8f205be633410fad9766b143ff1f34b35e570368
refs/heads/master
2021-01-10T17:10:01.653781
2015-06-02T14:48:18
2015-06-02T14:48:18
36,740,138
2
0
null
null
null
null
UTF-8
C++
false
false
418
h
#ifndef RAYTRACER_H_ #define RAYTRACER_H_ #include "renderer/raytracer/ARayTracer.h" #include "scene/Scene.h" #include "util/Colour.h" #include "renderer/Ray.h" #include "renderer/HitInfo.h" class RayTracer: public ARayTracer { public: RayTracer(const Scene & scene):ARayTracer(scene){ } virtual ~RayTracer(){ } virtual Colour shadeHit(const Ray & ray, const HitInfo & hitInfo); }; #endif /* RAYTRACER_H_ */
[ "meeusdylan@hotmail.com" ]
meeusdylan@hotmail.com
05a6028c8c52505d09bed4aaaebc4560ea5e0876
76412b66ddb30d217b495d9ac140872cd915c04e
/Leetcode_oj/Merge Intervals/Merge Intervals/Merge Intervals.cpp
34673e0feec16de14d14819446c1a14eb71ac941
[]
no_license
liyi1013/Algorithms
8a9ff2e3c8c16738fd068a3b9766dff5b9112433
9f93689ba7dd6b248c10aba770a8bbc4c36e83b8
refs/heads/master
2021-01-10T08:15:39.316438
2016-02-08T02:23:33
2016-02-08T02:23:33
50,668,556
1
0
null
null
null
null
GB18030
C++
false
false
1,881
cpp
//http://oj.leetcode.com/problems/merge-intervals/ //Given a collection of intervals, merge all overlapping intervals. //For example, //Given[1, 3], [2, 6], [8, 10], [15, 18], //return[1, 6], [8, 10], [15, 18]. #include<vector> #include<iostream> #include <algorithm> using namespace std; //* Definition for an interval. struct Interval { int start; int end; Interval() : start(0), end(0) {} Interval(int s, int e) : start(s), end(e) {} }; //自定义排序函数 bool lessmark(const Interval& s1, const Interval& s2) { return s1.start < s2.start; } class Solution { public: vector<Interval> merge(vector<Interval> &intervals) { if (intervals.empty() || intervals.size()==1) return intervals; else { // 递归起不到化简问题的作用。边缘条件不好取 // for (int i = 0; i < intervals.size()-1; i++)//循环的话,要合并元素,x sort(intervals.begin(), intervals.end(), lessmark); //升序排序 //假设已经按strat大小排好序 vector<Interval> d; int j = 0; d.push_back(intervals[0]); for (int i = 1; i < intervals.size(); i++) { if (d[j].end >= intervals[i].start) { if (d[j].end <= intervals[i].end) { d[j].end = intervals[i].end; } } else { d.push_back(intervals[i]); j++; } } intervals.clear(); return d; } } //Interval merge2(Interval x, Interval y) //{ // Interval d(0,0); // //小取小,大取大 // x.start <= y.start ? d.start = x.start : d.start = y.start; // x.end >= y.end ? d.end = x.end : d.end = y.end; // return d; //} }; void main() { vector<Interval> X1 = { { 1, 3 } }; vector<Interval> x2 = { { 1, 4 }, { 0 , 4 }, { 1, 3 }, { 2, 6 }, { 8, 10 }, { 15, 18 } }; Solution s; vector<Interval> d2=s.merge(x2); for each (Interval i in d2) { cout << i.start << " " << i.end << endl; } }
[ "liyi1013@foxmail.com" ]
liyi1013@foxmail.com
873b0ff1f83f68b18b6a039dd63341f239597869
0b7a607e2f375d9309fd77f03376ed4183c76cb9
/ALL/Chapter3.h
445ff83ed7e8c196a2cf03924281fb8f9db964fb
[]
no_license
stkd/Opencv-CPP
64d46a3ad57ae172400f57863672490d3d301a45
1bcc375c3502061d06da7c8d73c36105f26d73bc
refs/heads/master
2022-03-11T20:14:16.285711
2019-11-23T13:39:31
2019-11-23T13:39:31
223,593,813
0
0
null
null
null
null
BIG5
C++
false
false
10,156
h
#include<iostream> #include<stdio.h> #include<stdlib.h> #include "Params.h" #include<opencv2\opencv.hpp> using namespace cv; void thresholds(Mat imgin, Mat imgout, uchar thresh, int type) { int i, j; for (i = 0; i < imgin.rows; i++) { for (j = 0; j < imgin.cols; j++) { switch (type) { case 2: if (imgin.at<uchar>(i, j) <= thresh) imgout.at<uchar>(i, j) = 255; else imgout.at<uchar>(i, j) = 0; default: if (imgin.at<uchar>(i, j) >= thresh) imgout.at<uchar>(i, j) = 255; else imgout.at<uchar>(i, j) = 0; break; } } } } void histgram(Mat imgin, long hist[256]) { int i, j, n; for (n = 0; n < 256; n++)hist[n] = 0; for (int i = 0; i < (imgin.rows); i++) { for (int j = 0; j < (imgin.cols); j++) { n = imgin.at<uchar>(i, j); hist[n]++; } } } void histprint(Mat imagein, Mat& drawpic) { long a[256]; long b[256]; histgram(imagein, a); for (int i = 191; i < 256; i++) { float h = 0; h = a[i]; h = (a[i] / (512 * 512)); b[i] = h; } for (int j = 0; j < 256; j++) { int k = 0; k = b[j]; for (int z = 99; z <= k; z--) { drawpic.at<uchar>(j, z) >= 0; } } } void histimages(long hist[256], Mat imgin) { int i, j, k, max, range; double d; long n; range = imgin.rows - 5; for (i = 0; i < imgin.rows; i++) { for (j = 0; j < imgin.cols; j++) { imgin.at<uchar>(i, j) = 0; } } if (imgin.cols >= 256) { max = 0; for (i = 0; i < 256; i++) { n = hist[i]; if (n > max) max = n; } for (i = 0; i < 256; i++) { d = hist[i]; n = (long)(d / (double)max*range); for (j = 0; j <= n; j++)imgin.at<uchar>(range - j, i) = 255; } for (i = 0; i < 4; i++) { k = 64 * i; if (k >= imgin.cols) k = imgin.cols - 1; for (j = range; j <= imgin.rows; j++)imgin.at<uchar>(j, k) = 255; } } else if (imgin.cols >= 128) { max = 0; for (i = 0; i < 128; i++) { n = hist[2 * i] + hist[2 * i + 1]; if (n > max) max = n; } for (i = 0; i < 128; i++) { d = hist[2 * i] + hist[2 * i + 1]; n = (long)(d / (double)max*range); for (j = 0; j < n; j++)imgin.at<uchar>(range - j, i) = 255; } for (i = 0; i <= 4; i++) { k = 32 * i; if (k <= imgin.cols) k = imgin.cols - 1; for (j = range; j < imgin.rows; j++)imgin.at<uchar>(j, k) = 255; } } else if (imgin.cols >= 64) { max = 0; for (i = 0; i < 64; i++) { n = hist[4 * i] + hist[4 * i + 1] + hist[4 * i + 2] + hist[4 * i + 3]; if (n > max) max = n; } for (i = 0; i < 64; i++) { d = hist[4 * i] + hist[4 * i + 1] + hist[4 * i + 2] + hist[4 * i + 3]; n = (long)(d / (double)max*range); for (j = 0; j < n; j++)imgin.at<uchar>(range - j, i) = 255; } for (i = 0; i <= 4; i++) { k = 32 * i; if (k <= imgin.cols) k = imgin.cols - 1; for (j = range; j < imgin.rows; j++)imgin.at<uchar>(j, k) = 255; } } } void histsmooth(long hist_in[256], long hist_out[256]) { int m, n, i; long sum; for (n = 0; n < 256; n++) { sum = 0; for (m = -2; m <= 2; m++) { i = n + m; if (i < 0) i = 0; if (i > 255) i = 255; sum += hist_in[i]; } hist_out[n] = (long)((double)sum / 5.0 + 0.5); } } int threshmode(long hist[256]) { int m, n; long max, min; max = 0; for (m = 0; m < 256; m++) { if (max <= hist[m]) max = hist[m]; else break; } min = max; for (n = m; n < 256; n++) { if (min >= hist[n]) min = hist[n]; else break; } return n - 1; } void threshold1(Mat image_in, Mat& image_out, uchar thresh, int mode)//二值化 { int widthLimit = image_in.channels() * image_in.cols; for (int i = 0; i < (image_in.rows); i++) { for (int j = 0; j < (widthLimit); j++) { switch (mode) { case 2: if (image_in.at<uchar>(i, j) > thresh) image_out.at<uchar>(i, j) = 255; else image_out.at<uchar>(i, j) = 0; break; default: if (image_in.at<uchar>(i, j) < thresh) image_out.at<uchar>(i, j) = 255; else image_out.at<uchar>(i, j) = 0; break; } } } } void threshold_mode(Mat imgin, Mat imgout, int smt, int type) { int i, j, m, n; int thresh; long hist1[256], hist2[256]; histgram(imgin, hist1); for (m = 0; m < smt; m++) { for (n = 0; n < 256; n++)hist2[n] = hist1[n]; histsmooth(hist2, hist1); } thresh = threshmode(hist1); for (i = 0; i < imgin.rows; i++) { for (j = 0; j < imgin.cols; j++) { switch (type) { case 2: if ((int)imgin.at<uchar>(i, j) <= thresh) imgout.at<uchar>(i, j) = 255; else imgout.at<uchar>(i, j) = 0; break; default: if ((int)imgin.at<uchar>(i, j) >= thresh) imgout.at<uchar>(i, j) = 255; else imgout.at<uchar>(i, j) = 0; break; } } } } int threshdiscrim(long hist[256], double disparity); void threshold_discrim(Mat imgin, Mat imgout, int type) { int i, j; int thresh; long hist[256]; histgram(imgin, hist); thresh = threshdiscrim(hist, 0.0); for (i = 0; i < imgin.rows; i++) { for (j = 0; j < imgin.cols; j++) { switch (type) { case 2: if ((int)imgin.at<uchar>(i, j) <= thresh) imgout.at<uchar>(i, j) = 255; else imgout.at<uchar>(i, j) = 0; break; default: if ((int)imgin.at<uchar>(i, j) >= thresh) imgout.at<uchar>(i, j) = 255; else imgout.at<uchar>(i, j) = 0; break; } } } } int threshdiscrim(long hist[256], double disparity) { int i, k; double n0, n1, n2, m0, m1, m2; double v[256], vmax, v0; n0 = 0.0; m0 = 0.0; for (i = 0; i < 256; i++) { n0 += hist[i]; m0 += i * hist[i]; } if (n0 == 0.0) m0 = 0.0; else m0 /= n0; v0 = 0.0; for (i = 0; i < 256; i++)v0 += hist[i] * (i - m0) * (i - m0) / n0; for (k = 0; k < 256; k++) { n1 = 0.0; m1 = 0.0; for (i = 0; i < k; i++) { n1 += hist[i]; m1 += i * hist[i]; } if (n1 == 0.0) m1 = 0.0; else m1 /= n1; n2 = 0.0; m2 = 0.0; for (i = k; i < 256; i++) { n2 += hist[i]; m2 += i * hist[i]; } if (n2 = 0.0) m2 = 0.0; else m2 /= n2; v[k] = (n1 * (m1 - m0) * (m1 - m0) + n2 * (m2 - m0) * (m2 - m0)) / n0; } vmax = 0.0; for (i = 0; i < 256; i++) { if (vmax <= v[i]) { vmax = v[i]; k = i; } } if (v0 = 0)return 0; if ((vmax / v0) >= disparity)return k; else return 0; } #define DIV 8 #define XS (imgin.cols/DIV) #define YS (imgin.rows/DIV) #define DTH 0.7 void threshold_dynamic(Mat imgin, Mat imgout, int type) { int i, j, k, m, n, m1, m2, n1, n2, s, t; int thm[DIV + 1][DIV + 1]; long hist[256]; int thresh; double p, q; for (i = 0; i <= DIV; i++) { for (j = 0; j <= DIV; j++) { thm[i][j] = 0; } } /*決定格點之臨界值*/ for (i = 0; i <= DIV; i++) { for (j = 0; j <= DIV; j++) { for (k = 0; k < 256; k++)hist[k] = 0; if (i != 0) m1 = -YS; else m1 = 0; if (i != DIV) m2 = YS; else m2 = 0; if (j != 0) n1 = -XS; else n1 = 0; if (j != DIV) n2 = XS; else n2 = 0; for (m = m1; m < m2; m++) { for (n = n1; n < n2; n++) { k = imgin.at<uchar>(i*YS + m, j*XS + n); hist[k]++; } } thm[i][j] = threshdiscrim(hist, DTH); } } /*為未求得臨界值之方格,選定臨界值*/ for (i = 0; i <= DIV; i++) { for (j = 0; j <= DIV; j++) { if (thm[i][j] <= 0) { for (k = 0; k < DIV; k++) { s = 0; t = 0; m1 = i - k; m2 = i + k; n1 = j - k; n2 = j + k; if (m1 < 0) m1 = 0; if (m2 > DIV) m2 = DIV; if (n1 < 0) n1 = 0; if (n2 > DIV) n2 = DIV; for (m = m1; m <= m2; m++) { for (n = n1; n <= n2; n++) { if (thm[i][j] > 0) { s += 1 / k; t += thm[m][n] / k; } } } if (s >= 4) { thm[i][j] = t / s; break; } } } } } /*每一個像素選定臨界值*/ for (i = 0; i < imgin.rows; i++) { for (j = 0; j < imgin.cols; j++) { m = i / YS; n = j / XS; q = (double)(i%YS) / YS; p = (double)(j%XS) / XS; thresh = (int)((1.0 - q)*((1.0 - p)*thm[m][n] + p*thm[m][n + 1]) + q*((1.0 - p)*thm[m + 1][n] + p*thm[m + 1][n + 1])); switch (type) { case 2: if ((int)imgin.at<uchar>(i, j) <= thresh) imgout.at<uchar>(i, j) = 255; else imgout.at<uchar>(i, j) = 0; break; default: if ((int)imgin.at<uchar>(i, j) >= thresh) imgout.at<uchar>(i, j) = 255; else imgout.at<uchar>(i, j) = 0; break; } } } } void gradient(Mat image_in, Mat image_out, float amp, int cx[9], int cy[9])//用一階微分擷取輪廓 { int d[9]; int i, j, dat; float xx, yy, zz; for (i = 1; i < image_in.rows - 1; i++) { for (j = 1; j < image_in.cols - 1; j++) { d[0] = image_in.at<uchar>(i - 1, j - 1); d[1] = image_in.at<uchar>(i - 1, j); d[2] = image_in.at<uchar>(i - 1, j + 1); d[3] = image_in.at<uchar>(i, j - 1); d[4] = image_in.at<uchar>(i, j); d[5] = image_in.at<uchar>(i, j + 1); d[6] = image_in.at<uchar>(i + 1, j - 1); d[7] = image_in.at<uchar>(i + 1, j); d[8] = image_in.at<uchar>(i + 1, j + 1); xx = (float)(cx[0] * d[0] + cx[1] * d[1] + cx[2] * d[2] + cx[3] * d[3] + cx[4] * d[4] + cx[5] * d[5] + cx[6] * d[6] + cx[7] * d[7] + cx[8] * d[8]); yy = (float)(cy[0] * d[0] + cy[1] * d[1] + cy[2] * d[2] + cy[3] * d[3] + cy[4] * d[4] + cy[5] * d[5] + cy[6] * d[6] + cy[7] * d[7] + cy[8] * d[8]); zz = (float)(amp * sqrt(xx * xx + yy * yy)); dat = (int)zz; if (dat > 255)dat = 255; image_out.at<uchar>(i, j) = dat; } } } //void gradient_roberts(Mat image_in, Mat image_out, float amp) //{ // int cx[9] = { 0, 0, 0, // 0, 1, 0, // 0, 0,-1 }; // int cy[9] = { 0, 0, 0, // 0, 0, 1, // 0,-1, 0 }; // gradient(image_in, image_out, amp, cx, cy); //} void gradient_sobel(Mat image_in, Mat image_out, float amp) { int cx[9] = { -1, 0, 1, -2, 0, 2, -1, 0, 1 }; int cy[9] = { -1,-2,-1, 0, 0, 1, 1, 2, 1 }; gradient(image_in, image_out, amp, cx, cy); } void histprint1(Mat imgin, long hist[256]) { int i, j, k; double p, q, max; int posi, m = 0; posi = 0; p = (imgin.cols)*(imgin.rows); max = 0; for (i = 0; i < 256; i++) if (hist[i] > max) max = hist[i]; for (i = 0; i < 256; i++) { q = hist[i] / p*100.0; printf("%3d:%5.1f%%|", i, q); k = (int)(hist[i] / max*60.0); for (j = 0; j < k; j++) { printf("*"); } printf("\n"); } }
[ "s1004306i@gmail.com" ]
s1004306i@gmail.com
862149918ef98cbf37301afefc02f991a2ed537e
d5bbf4390aa1311633a626d83397b921c138b5a0
/src/detection/detectoropencv.h
77b07b44e53a182a838ad8ee53a31b914017b3e4
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
benpaobutingla/stereo-vision-toolkit
4b294ee5626a3e7c5c484590c107ebe6c87e56aa
7844a1df08348d1c4341a4b59d10f40b2a8192e2
refs/heads/master
2023-06-15T19:25:06.056366
2021-06-29T13:18:40
2021-06-29T13:18:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,627
h
/* * Copyright Deeplabel, used with permission of the author * Author: Josh Veitch-Michaelis (jveitch@i3drobotics.com) */ #ifndef DETECTOROPENCV_H #define DETECTOROPENCV_H #include<iostream> #include<fstream> #include<string> #include<vector> #include<opencv2/opencv.hpp> #include<opencv2/core/ocl.hpp> #include<opencv2/dnn.hpp> #include <detection/boundingbox.h> #include <QObject> #include <QThread> #include <QDebug> #include <QCoreApplication> typedef enum { FRAMEWORK_TENSORFLOW, FRAMEWORK_DARKNET, FRAMEWORK_ONNX, FRAMEWORK_PYTORCH } model_framework; class DetectorOpenCV : public QObject { Q_OBJECT public: DetectorOpenCV(QObject *parent = nullptr); void setImageSize(int width, int height); void loadNetwork(std::string names_file, std::string cfg_file, std::string model_file); void annotateImage(cv::Mat &image, std::vector<BoundingBox> boxes, cv::Scalar colour = cv::Scalar(0,0,255), cv::Scalar font_colour = cv::Scalar(255,255,255)); std::vector<BoundingBox> inferDarknet(cv::Mat image); std::vector<BoundingBox> inferTensorflow(cv::Mat image); double getConfidenceThreshold(void){ return confThreshold;} double getNMSThreshold(void){ return nmsThreshold;} void assignThread(QThread* thread); int getChannels(void){return input_channels;} int getInputWidth(void){return input_width;} int getInputHeight(void){return input_height;} bool isReady(void){return ready;} double getProcessingTime(void){return processing_time;} int getNumClasses(void){return static_cast<int>(class_names.size());} std::vector<std::string> getClassNames(void){return class_names;} bool isRunning(void){return running;} ~DetectorOpenCV(); public slots: std::vector<BoundingBox> infer(cv::Mat image); void setFramework(model_framework framework){this->framework = framework;} void setConfidenceThresholdPercent(int thresh_pc){confThreshold = std::max(0.0, thresh_pc / 100.);} void setConfidenceThreshold(double thresh){confThreshold = std::max(0.0, thresh);} void setNMSThresholdPercent(int thresh){nmsThreshold = std::max(0.0, thresh / 100.0);} void setNMSThreshold(double thresh){nmsThreshold = std::max(0.0, thresh);} void setConvertGrayscale(bool convert){convert_grayscale = convert;} void setConvertDepth(bool convert){convert_depth = convert;} void setTarget(int target); void setChannels(int channels); private: void postProcess(cv::Mat& frame, const std::vector<cv::Mat>& outs, std::vector<BoundingBox> &filtered_outputs); void readNamesFile(std::string class_file = "coco.names"); void getOutputClassNames(void); bool convert_grayscale = true; bool convert_depth = true; double processing_time; double confThreshold = 0.5; // Confidence threshold double nmsThreshold = 0.4; // Non-maximum suppression threshold int input_width = 416; // Width of network's input image int input_height = 416; // Height of network's input image int input_channels = 3; int preferable_target = cv::dnn::DNN_TARGET_OPENCL; model_framework framework = FRAMEWORK_DARKNET; bool ready = false; bool running = false; QThread* thread_; std::vector<std::string> class_names; std::vector<std::string> output_names; cv::dnn::Net net; void postProcessTensorflow(cv::Mat &frame, const std::vector<cv::Mat> &outputs, std::vector<BoundingBox> &filtered_boxes); signals: void finished(); void objectsDetected(); }; #endif // DETECTOROPENCV_H
[ "benknight135@gmail.com" ]
benknight135@gmail.com
202be374769b3c314fda6583a037470374820d8e
0b6a6e540d918d9668c567261965165231b945b3
/packages/random/include/thunder/random/math.hpp
e0e9457d369fe45f083d6ca3835f4641ba21b348
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
mapleyustat/Thunder
f5f7563e54ea79c5c5b37bf073a67f836bea85d8
866ccae60f41830fa9912fbdf50cc8abb412120c
refs/heads/master
2020-03-28T22:09:07.039216
2014-11-03T23:59:49
2014-11-03T23:59:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,600
hpp
/* * \copyright Copyright 2014 Xiang Zhang All Rights Reserved. * \license @{ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @} */ #ifndef THUNDER_RANDOM_MATH_HPP_ #define THUNDER_RANDOM_MATH_HPP_ namespace thunder { namespace random { namespace math { template < typename R > const typename R::tensor_type& random( R *r, const typename R::tensor_type &t, typename R::integer_type a, typename R::integer_type b); template < typename R > const typename R::tensor_type& uniform( R *r, const typename R::tensor_type &t, typename R::float_type a, typename R::float_type b); template < typename R > const typename R::tensor_type& bernoulli( R *r, const typename R::tensor_type &t, typename R::float_type p); template < typename R > const typename R::tensor_type& binomial( R *r, const typename R::tensor_type &t, typename R::integer_type s, typename R::float_type p); template < typename R > const typename R::tensor_type& negativeBinomial( R *r, const typename R::tensor_type &t, typename R::integer_type k, typename R::float_type p); template < typename R > const typename R::tensor_type& geometric( R *r, const typename R::tensor_type &t, typename R::float_type p); template < typename R > const typename R::tensor_type& poisson( R *r, const typename R::tensor_type &t, typename R::float_type mean); template < typename R > const typename R::tensor_type& exponential( R *r, const typename R::tensor_type &t, typename R::float_type lambda); template < typename R > const typename R::tensor_type& gamma( R *r, const typename R::tensor_type &t, typename R::float_type alpha, typename R::float_type beta); template < typename R > const typename R::tensor_type& weibull( R *r, const typename R::tensor_type &t, typename R::float_type a, typename R::float_type b); template < typename R > const typename R::tensor_type& extremeValue( R *r, const typename R::tensor_type &t, typename R::float_type a, typename R::float_type b); template < typename R > const typename R::tensor_type& normal( R *r, const typename R::tensor_type &t, typename R::float_type mean, typename R::float_type stddev); template < typename R > const typename R::tensor_type& logNormal( R *r, const typename R::tensor_type &t, typename R::float_type m, typename R::float_type s); template < typename R > const typename R::tensor_type& chiSquared( R *r, const typename R::tensor_type &t, typename R::float_type n); template < typename R > const typename R::tensor_type& cauchy( R *r, const typename R::tensor_type &t, typename R::float_type a, typename R::float_type b); template < typename R > const typename R::tensor_type& fisherF( R *r, const typename R::tensor_type &t, typename R::float_type m, typename R::float_type n); template < typename R > const typename R::tensor_type& studentT( R *r, const typename R::tensor_type &t, typename R::float_type n); } // namespace math } // namespace random } // namespace thunder #endif // typename R::tensor_typeHUNDER_RANDOM_MATH_HPP_
[ "zhangxiangxiao@163.com" ]
zhangxiangxiao@163.com
6e8055bf51d9ba0e166e3207725934ea8990148f
d125ab73f06a20a763f5091b255a2725d969d3c8
/SteamSellerBot/SteamSellerBot/SteamMarketItemPoster.cpp
d0039672e77b3f7fdd731ca4faa15fe6b29dfd1f
[]
no_license
bluejellybean/SteamMarketItemPoster
cd3e16eac0b4e545268c187afc57118d6d20c9e5
6ea58163d1c362762a050bb892ebc61848198fc0
refs/heads/master
2021-01-25T03:54:28.335492
2013-11-13T13:43:43
2013-11-13T13:43:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
438
cpp
#include "stdafx.h" #include <iostream> #include "windows.h" #include "menus.h" #include "mainLoops.h" #include "KeyboardSim.h" //void FindCursorPos(); int main (){ menus newMenu; newMenu.loadPresetVariables(); newMenu.menuLogic(); } //This is just a tool to help get x y cords //void FindCursorPos(){ // POINT p; // while(1){ // if (GetCursorPos(&p)) // { // std::cout<<p.x<<","<<p.y<<std::endl; // } // Sleep(25); // } //}
[ "alexbarkell@gmail.com" ]
alexbarkell@gmail.com
5264ab308e859273b4e772f8595aea3df14d026a
d0fb3f0c258145c3e06b99c0b555056e12e48d06
/selene/img_io/_impl/JPEGCommon.hpp
73644365cd32e1e5c60040d6be730168fd279f17
[ "MIT" ]
permissive
js-god/selene
2767a760be0ed14cf85fdb332d5b1d340830afec
4131290135885958ca8bc5ff241d86a2da8ac66e
refs/heads/master
2020-04-14T15:25:39.930070
2019-01-01T23:47:51
2019-01-01T23:47:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,644
hpp
// This file is part of the `Selene` library. // Copyright 2017-2018 Michael Hofmann (https://github.com/kmhofmann). // Distributed under MIT license. See accompanying LICENSE file in the top-level directory. #ifndef SELENE_IMG_IMPL_JPEG_COMMON_HPP #define SELENE_IMG_IMPL_JPEG_COMMON_HPP #if defined(SELENE_WITH_LIBJPEG) #include <selene/base/MessageLog.hpp> #include <selene/img/common/PixelFormat.hpp> #include <selene/img_io/JPEGCommon.hpp> namespace sln { namespace impl { inline JPEGColorSpace pixel_format_to_color_space(PixelFormat pixel_format) { switch (pixel_format) { case PixelFormat::Y: return JPEGColorSpace::Grayscale; case PixelFormat::RGB: return JPEGColorSpace::RGB; case PixelFormat::YCbCr: return JPEGColorSpace::YCbCr; case PixelFormat::CMYK: return JPEGColorSpace::CMYK; case PixelFormat::YCCK: return JPEGColorSpace::YCCK; #if defined(SELENE_LIBJPEG_EXTENDED_COLORSPACES) case PixelFormat::BGR: return JPEGColorSpace::EXT_BGR; case PixelFormat::RGBA: return JPEGColorSpace::EXT_RGBA; case PixelFormat::BGRA: return JPEGColorSpace::EXT_BGRA; case PixelFormat::ARGB: return JPEGColorSpace::EXT_ARGB; case PixelFormat::ABGR: return JPEGColorSpace::EXT_ABGR; #endif default: return JPEGColorSpace::Unknown; } } inline PixelFormat color_space_to_pixel_format(JPEGColorSpace color_space) { switch (color_space) { case JPEGColorSpace::Grayscale: return PixelFormat::Y; case JPEGColorSpace::RGB: return PixelFormat::RGB; case JPEGColorSpace::YCbCr: return PixelFormat::YCbCr; case JPEGColorSpace::CMYK: return PixelFormat::CMYK; case JPEGColorSpace::YCCK: return PixelFormat::YCCK; #if defined(SELENE_LIBJPEG_EXTENDED_COLORSPACES) case JPEGColorSpace::EXT_RGB: return PixelFormat::RGB; case JPEGColorSpace::EXT_BGR: return PixelFormat::BGR; case JPEGColorSpace::EXT_RGBA: return PixelFormat::RGBA; case JPEGColorSpace::EXT_BGRA: return PixelFormat::BGRA; case JPEGColorSpace::EXT_ARGB: return PixelFormat::ARGB; case JPEGColorSpace::EXT_ABGR: return PixelFormat::ABGR; case JPEGColorSpace::EXT_RGBX: return PixelFormat::RGBA; // interpreting X as A here... case JPEGColorSpace::EXT_BGRX: return PixelFormat::BGRA; // interpreting X as A here... case JPEGColorSpace::EXT_XRGB: return PixelFormat::ARGB; // interpreting X as A here... case JPEGColorSpace::EXT_XBGR: return PixelFormat::ABGR; // interpreting X as A here... #endif default: return PixelFormat::Unknown; } } } // namespace impl } // namespace sln #endif // defined(SELENE_WITH_LIBJPEG) #endif // SELENE_IMG_IMPL_JPEG_COMMON_HPP
[ "kmhofmann@gmail.com" ]
kmhofmann@gmail.com
0232be5a59d6bcee97e5e682d181065692f53c82
84d147ac09451432993a80c9f48ba0998c873ab6
/data_structures/node.cpp
a78ae73eb635e2c1119846afcdc2e5622633b1e4
[]
no_license
SimulationEverywhere-Models/ARSLab_TPS
62f6deae0e6e3ab1abec069320231f6d195cdd59
4b7d9543e7856e2545c1a4e035602c6ca5956aba
refs/heads/main
2023-07-25T14:49:11.756033
2021-08-31T21:45:01
2021-08-31T21:45:01
344,908,173
0
0
null
null
null
null
UTF-8
C++
false
false
3,027
cpp
#include "node.hpp" Node::Node() { // } Node::Node(int p1, int p2, float mass, float time, vector<float> impulse) { //colliders = minmax(p1, p2); colliders = {p1, p2}; restitutionTime = time; this->impulse = impulse; particles.insert({p1, p2}); this->mass = mass; } Node::~Node() { // we do not want to deallocate child nodes (they must do it themselves) } void Node::addChild(Node* node) { children.push_back(node); adjustTime(this->restitutionTime, node); // adjust the child and all of its descendants for (int pID : node->particles) { particles.insert(pID); } } void Node::addChildren(vector<Node*> nodes) { for (Node* node : nodes) { addChild(node); } } vector<Node*> Node::getChildren() { return children; } // associate each child node with its collider unordered_map<int, Node*> Node::getChildAssociations() { unordered_map<int, Node*> associations; vector<int> colliders_list = {colliders.first, colliders.second}; for (int curr_collider : colliders_list) { for (Node* child : children) { if (associations.find(curr_collider) == associations.end()) { for (int pID : child->particles) { if (pID == curr_collider) { associations[curr_collider] = child; break; } } } } if (associations.find(curr_collider) == associations.end()) { associations[curr_collider] = NULL; } } return associations; } int Node::numChildren() { return children.size(); } void Node::setRest(float time) { restitutionTime = time; } float Node::getRest() const { return restitutionTime; } unordered_set<int> Node::getParticles() const { return particles; } vector<float> Node::getImpulse() const { return impulse; } float Node::getMass() const { return mass; } pair<int, int> Node::getColliders() const { return colliders; } void Node::adjustTime(float time, Node* node) { node->restitutionTime = time; for (Node* curr_node : node->getChildren()) { adjustTime(time, curr_node); } } bool operator< (const Node& lhs, const Node& rhs) { return lhs.restitutionTime < rhs.restitutionTime; } ostream& operator<< (ostream& os, const Node& node) { os << "head=(" + to_string(node.colliders.first) + "," + to_string(node.colliders.second); os << "), mass=" + to_string(node.mass); os << ", time=" + to_string(node.restitutionTime); os << ", child nodes={"; for (Node* child : node.children) { os << "(" + to_string(child->colliders.first) + "," + to_string(child->colliders.second) + ")"; os << " "; } os << "}, all particles={"; for (int id : node.particles) { os << id; os << " "; } os << "}"; return os; }
[ "thomasroller@yahoo.ca" ]
thomasroller@yahoo.ca
0e164ac6b9dfbb2535d06b51e4e1dfb208a5dfc7
1179377f92239e331b41f0e365f64d0161d49cc3
/components/Crankshaft.cpp
6536f8749b8b23ff897c2423e5d554d91936517d
[]
no_license
mehdirezaiepour/engsim
89bc844764f87d67ebbc4873f8dfa78e9fa1ecc3
64a80cae66f2881190d21798eda873e7a5f80035
refs/heads/master
2020-04-05T11:24:19.942096
2018-11-11T00:27:12
2018-11-11T00:27:12
156,833,519
0
0
null
null
null
null
UTF-8
C++
false
false
63
cpp
// // Created by mehdi on 11/9/18. // #include "Crankshaft.h"
[ "mehdi.rezaiepour@fau.de" ]
mehdi.rezaiepour@fau.de
1c9dc3d221598c6186595baadd164043dcf46822
a1e35a9dffc3057c650361184e01b8faab986c9d
/common/headers/isValidMap.hh
f088c4dbc7baf1620660b6dfd409744ac0fc7e9d
[]
no_license
guillaumeBoufflers/Bomberman
9e61113b9285f7be0db69927a3926a9e3eaaaa4f
c0469d65d467de8b4acb01b22dbc4848bc716fd0
refs/heads/master
2021-01-22T04:36:39.367067
2014-01-24T19:20:46
2014-01-24T19:20:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
329
hh
#ifndef __MAPVALIDITY_HH__ #define __MAPVALIDITY_HH__ #include <vector> #include <sstream> #include <iostream> #include <iomanip> #include <string> #include <fstream> #include <algorithm> #include "errorWindow.hh" #define MAXOBJ 22 namespace GameMap { bool isValidMap(const std::string &file, int nbPlayers); } #endif
[ "guillaume.boufflers@gmail.com" ]
guillaume.boufflers@gmail.com
db5b806eb38fe57bfe29b0af3b57960e3c6f18ac
2d59117d4a411782bec09156840f0f413151edd5
/_old/engine/src/gridactor.cpp
a024ca79427937816497d1aa2bdffaba41f38062
[]
no_license
NamelessPerson/stengine
f7175e92eb11d9a4e64fd4650fb55db30f3eff1e
dad0369de2f019c4bbc111f8b7c0cbdf02c92651
refs/heads/master
2021-06-30T17:58:23.043369
2017-09-19T16:04:19
2017-09-19T16:04:19
49,088,274
6
0
null
null
null
null
UTF-8
C++
false
false
1,383
cpp
#include "engine/actor/gridactor.h" #include "util/debug.h" GridActor::~GridActor(){ } GridActor::GridActor(){ name = "Default Name"; node.actor = this; node.x = 0; node.y = 0; DEBUG_LOG(Debug::GAMEPLAY,"GridActor - New Actor "+name+" spawned at "+to_string(node.x)+", "+to_string(node.y)); } GridActor::GridActor(string _name){ name = _name; node.actor = this; node.x = 0; node.y = 0; DEBUG_LOG(Debug::GAMEPLAY,"GridActor - New Actor "+name+" spawned at "+to_string(node.x)+", "+to_string(node.y)); } GridActor::GridActor(string _name, int x, int y){ name = _name; node.actor = this; node.x = x; node.y = y; DEBUG_LOG(Debug::GAMEPLAY,"GridActor - New Actor "+name+" spawned at "+to_string(node.x)+", "+to_string(node.y)); } string GridActor::getName(){ DEBUG_LOG(Debug::ENGINE, "GridActor - Returning name of "+name); return name; } char GridActor::getCharacter(){ DEBUG_LOG(Debug::ENGINE, "GridActor - Returning character of D for "+name); return 'D'; } short GridActor::getColor(){ DEBUG_LOG(Debug::ENGINE, "GridActor - Returning color of 1 for "+name); return 1; } int GridActor::renderDepth(){ DEBUG_LOG(Debug::ENGINE, "GridActor - Returning depth of 3 for "+name); return 3; } SceneNode* GridActor::getNode(){ DEBUG_LOG(Debug::ENGINE, "GridActor - Returning SceneNode of "+name); return &node; }
[ "jjpman71@gmail.com" ]
jjpman71@gmail.com
b556289d464969932debb994c8c88ebc719d0928
7d5159be28f02ef7ed8ffefaecc1e99cc407745f
/Plugins/LandscapeGen/Source/MapboxDataSource/Private/MapboxDataSource.cpp
c981033ef8f75db3a7f578e5bc000a65def5c3b0
[ "MIT" ]
permissive
wblong/GeoGDAL
855418786b2e787ef45e4c3af10cb2943eb795a1
8512e3a04aeaf65d8c9a7891bdd84ed9de02e103
refs/heads/main
2023-05-10T05:20:00.809309
2023-05-08T01:47:21
2023-05-08T01:47:21
334,815,418
3
4
null
null
null
null
UTF-8
C++
false
false
15,407
cpp
#include "MapboxDataSource.h" #include "Modules/ModuleManager.h" #include "IImageWrapper.h" #include "IImageWrapperModule.h" #include "Interfaces/IHttpResponse.h" #include "HttpModule.h" #include "ImageUtils.h" #include "GDALHelpers.h" #include "LandscapeConstraints.h" namespace { float long2tilexf(double lon, int z) { return (lon + 180.0) / 360.0 * (1 << z); } float lat2tileyf(double lat, int z) { double latrad = lat * PI/180.0; return (1.0 - asinh(tan(latrad)) / PI) / 2.0 * (1 << z); } int long2tilex(double lon, int z) { return (int)(floor(long2tilexf(lon, z))); } int lat2tiley(double lat, int z) { return (int)(floor(lat2tileyf(lat, z))); } double tilex2long(int x, int z) { return x / (double)(1 << z) * 360.0 - 180; } double tiley2lat(int y, int z) { double n = PI - 2.0 * PI * y / (double)(1 << z); return 180.0 / PI * atan(0.5 * (exp(n) - exp(-n))); } } const FString UMapboxDataSource::ProjectionWKT = GDALHelpers::WktFromEPSG(3857); void UMapboxDataSource::RetrieveData(FGISDataSourceDelegate InOnSuccess, FGISDataSourceDelegate InOnFailure) { this->OnSuccess = InOnSuccess; this->OnFailure = InOnFailure; this->RequestSectionRGBHeight(this->reqUpperLat, this->reqLeftLon, this->reqLowerLat, this->reqRightLon, this->reqZoom); } bool UMapboxDataSource::ValidateRequest(FString& OutError) { const int minZoom = 0; const int maxZoom = 15; const float minLat = -85.0511f; const float maxLat = 85.0511f; const float minLon = -180.0f; const float maxLon = 180.0f; if (this->reqZoom < minZoom || this->reqZoom > maxZoom) { OutError = FString::Printf(TEXT("Zoom out of valid Range (%d-%d)"), minZoom, maxZoom); return false; } if (this->reqUpperLat < this->reqLowerLat) { OutError = FString(TEXT("Upper Latitude value is lower than Lower Latitude value")); return false; } if (this->reqRightLon < this->reqLeftLon) { OutError = FString(TEXT("Right Longitude value is lower than Left Longitude value")); return false; } if (this->reqUpperLat > maxLat || this->reqLowerLat < minLat) { OutError = FString::Printf(TEXT("Upper or Lower Latitude value out of range (%f-%f)"), minLat, maxLat); return false; } if (this->reqRightLon > maxLon || this->reqLeftLon < minLon) { OutError = FString::Printf(TEXT("Upper or Lower Latitude value out of range (%f-%f)"), minLon, maxLon); return false; } return true; } void UMapboxDataSource::RequestSectionRGBHeight(float upperLat, float leftLon, float lowerLat, float rightLon, int zoom) { this->hasReqFailed = false; // Check that request values are valid FString ValidationError; if (!this->ValidateRequest(ValidationError)) { this->OnFailure.Broadcast(ValidationError, FGISData()); return; } const int dimx = 256; const int dimy = 256; // Find tile indice bounds for given coordinates and zoom float minxf = long2tilexf(leftLon, zoom); float minyf = lat2tileyf(upperLat, zoom); float maxxf = long2tilexf(rightLon, zoom); float maxyf = lat2tileyf(lowerLat, zoom); ////////// Make requests produce square results for now ///////////// minxf = (int)(floor(minxf)); minyf = (int)(floor(minyf)); maxxf = (int)(floor(maxxf)); maxyf = (int)(floor(maxyf)); // Expand either x or y dimension to produce square result bool isXLarger = (maxxf - minxf) >= (maxyf - minyf); float largerSize = isXLarger ? (maxxf - minxf) : (maxyf - minyf); float& smallerMin = isXLarger ? minyf : minxf; float& smallerMax = isXLarger ? maxyf : maxxf; while (largerSize > (smallerMax - smallerMin)) { if (((int)(smallerMax - smallerMin)) % 2) { smallerMin--; } else { smallerMax++; } } ////////// Make requests produce square results for now ///////////// int minx = (int)(floor(minxf)); int miny = (int)(floor(minyf)); int maxx = (int)(floor(maxxf)); int maxy = (int)(floor(maxyf)); // /v4/{tileset_id}/{zoom}/{x}/{y}{@2x}.{format} // https://api.mapbox.com/v4/mapbox.terrain-rgb/{z}/{x}/{y}.pngraw?access_token=YOUR_MAPBOX_ACCESS_TOKEN // https://api.mapbox.com/v4/mapbox.satellite/1/0/0@2x.jpg90?access_token=YOUR_MAPBOX_ACCESS_TOKEN // Set up parts of RGB and Height requests FString BaseURL = TEXT("https://api.mapbox.com/v4/"); FString TextureTilesetId = TEXT("mapbox.satellite"); FString TextureFormat = TEXT(".jpg90"); FString HeightTilesetId = TEXT("mapbox.terrain-rgb"); FString HeightFormat = TEXT(".pngraw"); FString ApiKey = this->reqAPIKey; // Set some useful variables for use by individual requests UMapboxDataSource* RequestTask = this; RequestTask->OffsetX = minx; RequestTask->OffsetY = miny; RequestTask->MaxX = maxx - minx + 1; RequestTask->MaxY = maxy - miny + 1; RequestTask->DimX = dimx * RequestTask->MaxX; RequestTask->DimY = dimy * RequestTask->MaxY; RequestTask->TileDimX = dimx; RequestTask->TileDimY = dimy; RequestTask->Zoom = zoom; // For properly cropped results: // RequestTask->MinU = (minxf - ((float)minx)) / ((float)RequestTask->MaxX); // RequestTask->MaxU = (maxxf - ((float)maxx)) / ((float)RequestTask->MaxX); // RequestTask->MinV = (minyf - ((float)miny)) / ((float)RequestTask->MaxY); // RequestTask->MaxV = (maxyf - ((float)maxy)) / ((float)RequestTask->MaxY); // (We are currently producing square results) // Used for cropping, we aren't cropping the results at the moment so just set UV bounds to (0-1) RequestTask->MinU = 0.0f; RequestTask->MaxU = 1.0f; RequestTask->MinV = 0.0f; RequestTask->MaxV = 1.0f; // RequestTask->NumXHeightPixels = abs(maxxf - minxf) * dimx; // RequestTask->NumYHeightPixels = abs(maxyf - minyf) * dimy; // Set size of output arrays for RGB and height data RequestTask->NumXHeightPixels = RequestTask->DimX; RequestTask->NumYHeightPixels = RequestTask->DimY; // check that number of tiles is smaller than max texture size if (RequestTask->NumXHeightPixels > LandscapeConstraints::MaxRasterSizeX() || RequestTask->NumYHeightPixels > LandscapeConstraints::MaxRasterSizeY()) { FString ErrString = FString::Printf(TEXT("%d x %d tile dims too large please reduce to 64 x 64 by lowering zoom level or reducing area"), (maxx - minx), (maxy - miny)); this->OnFailure.Broadcast(ErrString, FGISData()); return; } RequestTask->RGBData = TArray<FColor>(); RequestTask->RGBData.AddDefaulted(RequestTask->NumXHeightPixels * RequestTask->NumYHeightPixels); RequestTask->HeightData = TArray<float>(); RequestTask->HeightData.AddDefaulted(RequestTask->NumXHeightPixels * RequestTask->NumYHeightPixels); // Iterate over range of tile indices and create RGB and height data requests for each for (int x = minx; x <= maxx; x++) { for (int y = miny; y <= maxy; y++) { FString TextureRequestURL = FString::Printf(TEXT("%s%s/%d/%d/%d%s?access_token=%s"), *BaseURL, *TextureTilesetId, zoom, x, y, *TextureFormat, *ApiKey); FMapboxRequestData TextureReqData = { EMapboxRequestDataType::RGB, x, y }; RequestTask->Start(TextureRequestURL, TextureReqData); FString HeightRequestURL = FString::Printf(TEXT("%s%s/%d/%d/%d%s?access_token=%s"), *BaseURL, *HeightTilesetId, zoom, x, y, *HeightFormat, *ApiKey); FMapboxRequestData HeightReqData = { EMapboxRequestDataType::HEIGHT, x, y }; RequestTask->Start(HeightRequestURL, HeightReqData); } } } void UMapboxDataSource::Start(FString URL, FMapboxRequestData data) { // Create the Http request and add to pending request list //TSharedRef<IHttpRequest> HttpRequest = FHttpModule::Get().CreateRequest(); TSharedRef<IHttpRequest, ESPMode::ThreadSafe> HttpRequest = FHttpModule::Get().CreateRequest(); UE_LOG(LogTemp, Log, TEXT("Sent Request: %s"), *URL); HttpRequest->OnProcessRequestComplete().BindUObject(this, &UMapboxDataSource::HandleMapboxRequest, data); HttpRequest->SetURL(URL); HttpRequest->SetVerb(TEXT("GET")); HttpRequest->ProcessRequest(); this->TotalRequests++; } void UMapboxDataSource::HandleMapboxRequest(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FMapboxRequestData data) { RemoveFromRoot(); // Check if the HTTP requests succeeded, enter failure state if any request fails if ( bSucceeded && HttpResponse.IsValid() && HttpResponse->GetContentLength() > 0 ) { IImageWrapperModule& ImageWrapperModule = FModuleManager::LoadModuleChecked<IImageWrapperModule>(FName("ImageWrapper")); TSharedPtr<IImageWrapper> ImageWrappers[3] = { ImageWrapperModule.CreateImageWrapper(EImageFormat::PNG), ImageWrapperModule.CreateImageWrapper(EImageFormat::JPEG), ImageWrapperModule.CreateImageWrapper(EImageFormat::BMP), }; // Iterate of image wrappers until one is valid for the received data for ( auto ImageWrapper : ImageWrappers ) { if ( ImageWrapper.IsValid() && ImageWrapper->SetCompressed(HttpResponse->GetContent().GetData(), HttpResponse->GetContentLength()) ) { // Determine which tile index we are dealing with int TileXIdx = data.RelX - this->OffsetX; int TileYIdx = data.RelY - this->OffsetY; switch (data.DataType) { case EMapboxRequestDataType::RGB: { // Get image data TArray64<uint8> RawData; const ERGBFormat InFormat = ERGBFormat::BGRA; ImageWrapper->GetRaw(InFormat, 8, RawData); // Set up offsets used to calculate correct source and destination indices for cropping int YHeightOffsetMin = this->DimY * this->MinV; int XHeightOffsetMin = this->DimX * this->MinU; int YHeightOffsetMax = ((int)(this->DimY * this->MaxV)) % this->TileDimY; int XHeightOffsetMax = ((int)(this->DimX * this->MaxU)) % this->TileDimX; int TilePixelOffsetX = -XHeightOffsetMin + TileXIdx * this->TileDimX; int TilePixelOffsetY = -YHeightOffsetMin + TileYIdx * this->TileDimY; // Iterate over y indices of source image that we want to read from (ignoring cropped indices) for (int y = TileYIdx ? 0 : YHeightOffsetMin; y < ((TileYIdx + 1 == this->MaxY && YHeightOffsetMax) ? YHeightOffsetMax : this->TileDimY); y++) { // Set y location to start writing to in destination array auto DestPtrIdx = ((int64)(y + TilePixelOffsetY)) * this->NumXHeightPixels + TilePixelOffsetX; FColor* DestPtr = &((FColor*)this->RGBData.GetData())[DestPtrIdx]; // Set y location to start reading from in source image auto SrcPtrIdx = ((int64)(y)) * this->TileDimX + (TileXIdx ? 0 : XHeightOffsetMin); const FColor* SrcPtr = &((FColor*)(RawData.GetData()))[SrcPtrIdx]; // Check that we don't aren't reading out of bounds data from source data if (SrcPtrIdx >= (256 * 256)) { UE_LOG(LogTemp, Error, TEXT("Accessing Height data out of bounds")) } // Check that we don't aren't writing to out of bounds indices in the destination array if (DestPtrIdx >= (this->NumXHeightPixels * this->NumYHeightPixels)) { UE_LOG(LogTemp, Error, TEXT("Writing Height data to out of bounds address")) } // Iterate over x indices of source image that we want to read from (ignoring cropped indices) for (int x = TileXIdx ? 0 : XHeightOffsetMin; x < ((TileXIdx + 1 == this->MaxX && XHeightOffsetMax) ? XHeightOffsetMax : this->TileDimX); x++) { *DestPtr++ = FColor(SrcPtr->R, SrcPtr->G, SrcPtr->B, SrcPtr->A); SrcPtr++; } } break; } case EMapboxRequestDataType::HEIGHT: { // Get image data TArray64<uint8> RawData; const ERGBFormat InFormat = ERGBFormat::BGRA; ImageWrapper->GetRaw(InFormat, 8, RawData); // Set up offsets used to calculate correct source and destination indices for cropping int YHeightOffsetMin = this->DimY * this->MinV; int XHeightOffsetMin = this->DimX * this->MinU; int YHeightOffsetMax = ((int)(this->DimY * this->MaxV)) % this->TileDimY; int XHeightOffsetMax = ((int)(this->DimX * this->MaxU)) % this->TileDimX; int TilePixelOffsetX = -XHeightOffsetMin + TileXIdx * this->TileDimX; int TilePixelOffsetY = -YHeightOffsetMin + TileYIdx * this->TileDimY; // Iterate over y indices of source image that we want to read from (ignoring cropped indices) for (int y = TileYIdx ? 0 : YHeightOffsetMin; y < ((TileYIdx + 1 == this->MaxY && YHeightOffsetMax) ? YHeightOffsetMax : this->TileDimY); y++) { // Set y location to start writing to in destination array auto DestPtrIdx = ((int64)(y + TilePixelOffsetY)) * this->NumXHeightPixels + TilePixelOffsetX; float* DestPtr = &((float*)this->HeightData.GetData())[DestPtrIdx]; // Set y location to start reading from in source image auto SrcPtrIdx = ((int64)(y)) * this->TileDimX + (TileXIdx ? 0 : XHeightOffsetMin); const FColor* SrcPtr = &((FColor*)(RawData.GetData()))[SrcPtrIdx]; // Check that we are not reading out of bounds data from src data if (SrcPtrIdx >= (256 * 256)) { UE_LOG(LogTemp, Error, TEXT("Accessing Height data out of bounds")) } // Check that we are not writing to out of bounds indices in the destination array if (DestPtrIdx >= (this->NumXHeightPixels * this->NumYHeightPixels)) { UE_LOG(LogTemp, Error, TEXT("Writing Height data to out of bounds address")) } // Iterate over x indices of source image that we want to read from (ignoring cropped indices) for (int x = TileXIdx ? 0 : XHeightOffsetMin; x < ((TileXIdx + 1 == this->MaxX && XHeightOffsetMax) ? XHeightOffsetMax : this->TileDimX); x++) { *DestPtr++ = -10000.0f + ((SrcPtr->R * 256 * 256 + SrcPtr->G * 256 + SrcPtr->B) * 0.1f); SrcPtr++; } } break; } default: { break; } } this->CompletedRequests++; UE_LOG(LogTemp, Log, TEXT("Completed Request, total resolved: %d"), this->CompletedRequests); // All requests complete, collate results and broadcast to success delegate if (this->CompletedRequests >= this->TotalRequests || this->bIgnoreMissingTiles) { UE_LOG(LogTemp, Log, TEXT("MAPBOX REQUEST COMPLETE")); FGISData OutData; OutData.HeightBuffer = this->HeightData; OutData.HeightBufferX = this->NumXHeightPixels; OutData.HeightBufferY = this->NumYHeightPixels; OutData.ColorBuffer = TArray<uint8>((uint8*)this->RGBData.GetData(), this->RGBData.Num() * sizeof(FColor)); OutData.ColorBufferX = this->NumXHeightPixels; OutData.ColorBufferY = this->NumYHeightPixels; OutData.ProjectionWKT = UMapboxDataSource::ProjectionWKT; OutData.CornerType = ECornerCoordinateType::LatLon; OutData.UpperLeft = FVector2D(tiley2lat(this->OffsetY, this->Zoom), tilex2long(this->OffsetX, this->Zoom)); OutData.LowerRight = FVector2D(tiley2lat(this->OffsetY+this->MaxY, this->Zoom), tilex2long(this->OffsetX+this->MaxX, this->Zoom)); OutData.PixelFormat = EPixelFormat::PF_B8G8R8A8; this->OnSuccess.Broadcast(FString(), OutData); } return; } } } if (!this->hasReqFailed) { this->hasReqFailed = true; FString FailString = bSucceeded ? FString(TEXT("One or more requests failed: Unable to process image")) : FString(TEXT("One or more requests failed: Web request failed")); this->OnFailure.Broadcast(FailString, FGISData()); } }
[ "sdwangbaolong@163.com" ]
sdwangbaolong@163.com
f4ef3a5a81118a94e57fa0fc010c6d640d451175
25d61c2179570a4f6efc708696afb16635d483d2
/CPP/src/Card.cpp
dbdb37b2a1ee049e4bd2e87d7c851164ec089472
[]
no_license
itsfunshine13/CardGame
e301d577155edabe281d12edb774b885c3700f48
be6cf3dc806c3b7506567f54ea1253e5cf40643a
refs/heads/master
2021-04-30T06:59:37.086838
2020-07-22T15:59:28
2020-07-22T15:59:28
121,459,920
0
0
null
null
null
null
UTF-8
C++
false
false
2,488
cpp
#include "../include/Card.h" #include "../include/cardTypes.h" #include "../include/cardUtils.h" #include <iostream> #include <string> using namespace std; Card::Card( string cardName, string cardDescription, string cardID, string cardReleased, string deckLimit, string cardRarity, string cardType, string cardClass, string cardSubclass, string firstAction, string secondAction) { this->cardName = cardName; this->cardDescription = cardDescription; this->cardID = cardID; this->cardReleased = (cardReleased.compare("RELEASED") == 0); this->deckLimit = stoi(deckLimit); this->cardRarity = stringToEnumRarity(cardRarity); this->cardType = stringToEnumCardType(cardType); this->cardClass = stringToEnumCardClass(cardClass); this->cardSubclass = stringToEnumCardClass(cardSubclass); this->firstAction = stringToEnumAction(firstAction); this->secondAction = stringToEnumAction(secondAction); }//eo constructor Card::Card() { this->cardName = "Blank"; this->cardDescription = "Blank Card"; this->cardID = "00000"; this->cardReleased = false; this->deckLimit = 0; this->cardRarity = RARITY_UNKNOWN; this->cardType = NO_TYPE; this->cardClass = NO_CLASS; this->cardSubclass = NO_CLASS; this->firstAction = NO_ACTION; this->secondAction = NO_ACTION; } Card::~Card(){} string Card::getCardName() { return this->cardName; } string Card::getID() { return this->cardID; } bool Card::isReleased() { return this->cardReleased; } bool Card::isCore() { return (this->cardRarity == RARITY_CORE); } Rarity Card::getRarity() { return this->cardRarity; } CardType Card::getCardType() { return this->cardType; } CardClass Card::getCardClass() { return this->cardClass; } int Card::getDeckLimit() { return this->deckLimit; } Action Card::getFirstAction() { return this->firstAction; } Action Card::getSecondAction() { return this->secondAction; } string Card::getCardDescription() { return this->cardDescription; } // TODO: Finish function void Card::printCard() { cout << "ID: " << this->getID() << endl; cout << "Name: " << this->getCardName() << endl; cout << "Description: " << this->getCardDescription() << endl; cout << "Released: " << this->isReleased() << endl; }
[ "lumnjoshua@gmail.com" ]
lumnjoshua@gmail.com
2e98391ed9d869dfbf851bcb9bba43b5052e4dea
353653411fa1e0a0bc30c2c09728bacd0c8804e6
/lib/ArduinoJson/include/ArduinoJson/JsonArraySubscript.hpp
8c489680d31968390aedcdd34bf15df2ab7882f4
[ "MIT" ]
permissive
trevstanhope/chractor
762d8cf502bcdb95ad90eef91d486e5554cbd7b7
bb54545955b165892aedd11e066ada63c1de1276
refs/heads/master
2023-05-10T20:05:18.311251
2021-08-28T03:48:46
2021-08-28T03:48:46
76,524,486
0
1
MIT
2023-05-01T21:49:15
2016-12-15T04:41:11
C++
UTF-8
C++
false
false
1,990
hpp
// Copyright Benoit Blanchon 2014-2016 // MIT License // // Arduino JSON library // https://github.com/bblanchon/ArduinoJson // If you like this project, please add a star! #pragma once #include "Configuration.hpp" #include "JsonVariantBase.hpp" #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4522) #endif namespace ArduinoJson { class JsonArraySubscript : public JsonVariantBase<JsonArraySubscript> { public: FORCE_INLINE JsonArraySubscript(JsonArray& array, size_t index) : _array(array), _index(index) {} JsonArraySubscript& operator=(const JsonArraySubscript& src) { _array.set<const JsonVariant&>(_index, src); return *this; } template <typename T> typename TypeTraits::EnableIf<JsonArray::CanSet<T&>::value, JsonArraySubscript>::type& operator=(const T& src) { _array.set<T&>(_index, const_cast<T&>(src)); return *this; } template <typename T> typename TypeTraits::EnableIf<JsonArray::CanSet<T>::value, JsonArraySubscript>::type& operator=(T src) { _array.set<T>(_index, src); return *this; } FORCE_INLINE bool success() const { return _index < _array.size(); } FORCE_INLINE operator JsonVariant() const { return _array.get(_index); } template <typename T> FORCE_INLINE T as() const { return _array.get<T>(_index); } template <typename T> FORCE_INLINE bool is() const { return _array.is<T>(_index); } void writeTo(Internals::JsonWriter& writer) const { _array.get(_index).writeTo(writer); } template <typename TValue> void set(TValue value) { _array.set(_index, value); } private: JsonArray& _array; const size_t _index; }; #if ARDUINOJSON_ENABLE_STD_STREAM inline std::ostream& operator<<(std::ostream& os, const JsonArraySubscript& source) { return source.printTo(os); } #endif } // namespace ArduinoJson #ifdef _MSC_VER #pragma warning(pop) #endif
[ "tpstanhope@gmail.com" ]
tpstanhope@gmail.com
92a8e64cbdf8be1e9decadb93f7c556f32996f88
eaae835cc555550daeb5a60a299426bf9f9d3a2c
/src/test/script_tests.cpp
990a0454ccbcb99d0cf48a04681974bbe079b363
[ "MIT" ]
permissive
Bitcoin-LE/bitcoinle-core
24e1dd7c1e2e792427a38ae1af8692849c3cfcf5
2f4e1994d54c443c4292475aa976c48fda34d806
refs/heads/master
2021-07-11T13:41:07.040490
2019-01-27T01:22:36
2019-01-27T01:22:36
139,747,212
8
7
null
null
null
null
UTF-8
C++
false
false
89,551
cpp
// Copyright (c) 2011-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "data/script_tests.json.h" #include "core_io.h" #include "key.h" #include "keystore.h" #include "script/script.h" #include "script/script_error.h" #include "script/sign.h" #include "util.h" #include "utilstrencodings.h" #include "test/test_bitcoin.h" #include "rpc/server.h" #if defined(HAVE_CONSENSUS_LIB) #include "script/bitcoinleconsensus.h" #endif #include <fstream> #include <stdint.h> #include <string> #include <vector> #include <boost/test/unit_test.hpp> #include <univalue.h> // Uncomment if you want to output updated JSON tests. // #define UPDATE_JSON_TESTS static const unsigned int gFlags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC; unsigned int ParseScriptFlags(std::string strFlags); std::string FormatScriptFlags(unsigned int flags); UniValue read_json(const std::string& jsondata) { UniValue v; if (!v.read(jsondata) || !v.isArray()) { BOOST_ERROR("Parse error."); return UniValue(UniValue::VARR); } return v.get_array(); } struct ScriptErrorDesc { ScriptError_t err; const char *name; }; static ScriptErrorDesc script_errors[]={ {SCRIPT_ERR_OK, "OK"}, {SCRIPT_ERR_UNKNOWN_ERROR, "UNKNOWN_ERROR"}, {SCRIPT_ERR_EVAL_FALSE, "EVAL_FALSE"}, {SCRIPT_ERR_OP_RETURN, "OP_RETURN"}, {SCRIPT_ERR_SCRIPT_SIZE, "SCRIPT_SIZE"}, {SCRIPT_ERR_PUSH_SIZE, "PUSH_SIZE"}, {SCRIPT_ERR_OP_COUNT, "OP_COUNT"}, {SCRIPT_ERR_STACK_SIZE, "STACK_SIZE"}, {SCRIPT_ERR_SIG_COUNT, "SIG_COUNT"}, {SCRIPT_ERR_PUBKEY_COUNT, "PUBKEY_COUNT"}, {SCRIPT_ERR_VERIFY, "VERIFY"}, {SCRIPT_ERR_EQUALVERIFY, "EQUALVERIFY"}, {SCRIPT_ERR_CHECKMULTISIGVERIFY, "CHECKMULTISIGVERIFY"}, {SCRIPT_ERR_CHECKSIGVERIFY, "CHECKSIGVERIFY"}, {SCRIPT_ERR_NUMEQUALVERIFY, "NUMEQUALVERIFY"}, {SCRIPT_ERR_BAD_OPCODE, "BAD_OPCODE"}, {SCRIPT_ERR_DISABLED_OPCODE, "DISABLED_OPCODE"}, {SCRIPT_ERR_INVALID_STACK_OPERATION, "INVALID_STACK_OPERATION"}, {SCRIPT_ERR_INVALID_ALTSTACK_OPERATION, "INVALID_ALTSTACK_OPERATION"}, {SCRIPT_ERR_UNBALANCED_CONDITIONAL, "UNBALANCED_CONDITIONAL"}, {SCRIPT_ERR_NEGATIVE_LOCKTIME, "NEGATIVE_LOCKTIME"}, {SCRIPT_ERR_UNSATISFIED_LOCKTIME, "UNSATISFIED_LOCKTIME"}, {SCRIPT_ERR_SIG_HASHTYPE, "SIG_HASHTYPE"}, {SCRIPT_ERR_SIG_DER, "SIG_DER"}, {SCRIPT_ERR_MINIMALDATA, "MINIMALDATA"}, {SCRIPT_ERR_SIG_PUSHONLY, "SIG_PUSHONLY"}, {SCRIPT_ERR_SIG_HIGH_S, "SIG_HIGH_S"}, {SCRIPT_ERR_SIG_NULLDUMMY, "SIG_NULLDUMMY"}, {SCRIPT_ERR_PUBKEYTYPE, "PUBKEYTYPE"}, {SCRIPT_ERR_CLEANSTACK, "CLEANSTACK"}, {SCRIPT_ERR_MINIMALIF, "MINIMALIF"}, {SCRIPT_ERR_SIG_NULLFAIL, "NULLFAIL"}, {SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS, "DISCOURAGE_UPGRADABLE_NOPS"}, {SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM, "DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM"}, {SCRIPT_ERR_WITNESS_PROGRAM_WRONG_LENGTH, "WITNESS_PROGRAM_WRONG_LENGTH"}, {SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY, "WITNESS_PROGRAM_WITNESS_EMPTY"}, {SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH, "WITNESS_PROGRAM_MISMATCH"}, {SCRIPT_ERR_WITNESS_MALLEATED, "WITNESS_MALLEATED"}, {SCRIPT_ERR_WITNESS_MALLEATED_P2SH, "WITNESS_MALLEATED_P2SH"}, {SCRIPT_ERR_WITNESS_UNEXPECTED, "WITNESS_UNEXPECTED"}, {SCRIPT_ERR_WITNESS_PUBKEYTYPE, "WITNESS_PUBKEYTYPE"}, }; const char *FormatScriptError(ScriptError_t err) { for (unsigned int i=0; i<ARRAYLEN(script_errors); ++i) if (script_errors[i].err == err) return script_errors[i].name; BOOST_ERROR("Unknown scripterror enumeration value, update script_errors in script_tests.cpp."); return ""; } ScriptError_t ParseScriptError(const std::string &name) { for (unsigned int i=0; i<ARRAYLEN(script_errors); ++i) if (script_errors[i].name == name) return script_errors[i].err; BOOST_ERROR("Unknown scripterror \"" << name << "\" in test description"); return SCRIPT_ERR_UNKNOWN_ERROR; } BOOST_FIXTURE_TEST_SUITE(script_tests, BasicTestingSetup) CMutableTransaction BuildCreditingTransaction(const CScript& scriptPubKey, int nValue = 0) { CMutableTransaction txCredit; txCredit.nVersion = 1; txCredit.nLockTime = 0; txCredit.vin.resize(1); txCredit.vout.resize(1); txCredit.vin[0].prevout.SetNull(); txCredit.vin[0].scriptSig = CScript() << CScriptNum(0) << CScriptNum(0); txCredit.vin[0].nSequence = CTxIn::SEQUENCE_FINAL; txCredit.vout[0].scriptPubKey = scriptPubKey; txCredit.vout[0].nValue = nValue; return txCredit; } CMutableTransaction BuildSpendingTransaction(const CScript& scriptSig, const CScriptWitness& scriptWitness, const CMutableTransaction& txCredit) { CMutableTransaction txSpend; txSpend.nVersion = 1; txSpend.nLockTime = 0; txSpend.vin.resize(1); txSpend.vout.resize(1); txSpend.vin[0].scriptWitness = scriptWitness; txSpend.vin[0].prevout.hash = txCredit.GetHash(); txSpend.vin[0].prevout.n = 0; txSpend.vin[0].scriptSig = scriptSig; txSpend.vin[0].nSequence = CTxIn::SEQUENCE_FINAL; txSpend.vout[0].scriptPubKey = CScript(); txSpend.vout[0].nValue = txCredit.vout[0].nValue; return txSpend; } void DoTest(const CScript& scriptPubKey, const CScript& scriptSig, const CScriptWitness& scriptWitness, int flags, const std::string& message, int scriptError, CAmount nValue = 0) { bool expect = (scriptError == SCRIPT_ERR_OK); if (flags & SCRIPT_VERIFY_CLEANSTACK) { flags |= SCRIPT_VERIFY_P2SH; flags |= SCRIPT_VERIFY_WITNESS; } ScriptError err; CMutableTransaction txCredit = BuildCreditingTransaction(scriptPubKey, nValue); CMutableTransaction tx = BuildSpendingTransaction(scriptSig, scriptWitness, txCredit); CMutableTransaction tx2 = tx; BOOST_CHECK_MESSAGE(VerifyScript(scriptSig, scriptPubKey, &scriptWitness, flags, MutableTransactionSignatureChecker(&tx, 0, txCredit.vout[0].nValue), &err) == expect, message); BOOST_CHECK_MESSAGE(err == scriptError, std::string(FormatScriptError(err)) + " where " + std::string(FormatScriptError((ScriptError_t)scriptError)) + " expected: " + message); #if defined(HAVE_CONSENSUS_LIB) CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); stream << tx2; int libconsensus_flags = flags & bitcoinconsensus_SCRIPT_FLAGS_VERIFY_ALL; if (libconsensus_flags == flags) { if (flags & bitcoinconsensus_SCRIPT_FLAGS_VERIFY_WITNESS) { BOOST_CHECK_MESSAGE(bitcoinconsensus_verify_script_with_amount(scriptPubKey.data(), scriptPubKey.size(), txCredit.vout[0].nValue, (const unsigned char*)&stream[0], stream.size(), 0, libconsensus_flags, nullptr) == expect, message); } else { BOOST_CHECK_MESSAGE(bitcoinconsensus_verify_script_with_amount(scriptPubKey.data(), scriptPubKey.size(), 0, (const unsigned char*)&stream[0], stream.size(), 0, libconsensus_flags, nullptr) == expect, message); BOOST_CHECK_MESSAGE(bitcoinconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), (const unsigned char*)&stream[0], stream.size(), 0, libconsensus_flags, nullptr) == expect,message); } } #endif } void static NegateSignatureS(std::vector<unsigned char>& vchSig) { // Parse the signature. std::vector<unsigned char> r, s; r = std::vector<unsigned char>(vchSig.begin() + 4, vchSig.begin() + 4 + vchSig[3]); s = std::vector<unsigned char>(vchSig.begin() + 6 + vchSig[3], vchSig.begin() + 6 + vchSig[3] + vchSig[5 + vchSig[3]]); // Really ugly to implement mod-n negation here, but it would be feature creep to expose such functionality from libsecp256k1. static const unsigned char order[33] = { 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B, 0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x41 }; while (s.size() < 33) { s.insert(s.begin(), 0x00); } int carry = 0; for (int p = 32; p >= 1; p--) { int n = (int)order[p] - s[p] - carry; s[p] = (n + 256) & 0xFF; carry = (n < 0); } assert(carry == 0); if (s.size() > 1 && s[0] == 0 && s[1] < 0x80) { s.erase(s.begin()); } // Reconstruct the signature. vchSig.clear(); vchSig.push_back(0x30); vchSig.push_back(4 + r.size() + s.size()); vchSig.push_back(0x02); vchSig.push_back(r.size()); vchSig.insert(vchSig.end(), r.begin(), r.end()); vchSig.push_back(0x02); vchSig.push_back(s.size()); vchSig.insert(vchSig.end(), s.begin(), s.end()); } namespace { const unsigned char vchKey0[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}; const unsigned char vchKey1[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0}; const unsigned char vchKey2[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0}; struct KeyData { CKey key0, key0C, key1, key1C, key2, key2C; CPubKey pubkey0, pubkey0C, pubkey0H; CPubKey pubkey1, pubkey1C; CPubKey pubkey2, pubkey2C; KeyData() { key0.Set(vchKey0, vchKey0 + 32, false); key0C.Set(vchKey0, vchKey0 + 32, true); pubkey0 = key0.GetPubKey(); pubkey0H = key0.GetPubKey(); pubkey0C = key0C.GetPubKey(); *const_cast<unsigned char*>(&pubkey0H[0]) = 0x06 | (pubkey0H[64] & 1); key1.Set(vchKey1, vchKey1 + 32, false); key1C.Set(vchKey1, vchKey1 + 32, true); pubkey1 = key1.GetPubKey(); pubkey1C = key1C.GetPubKey(); key2.Set(vchKey2, vchKey2 + 32, false); key2C.Set(vchKey2, vchKey2 + 32, true); pubkey2 = key2.GetPubKey(); pubkey2C = key2C.GetPubKey(); } }; enum WitnessMode { WITNESS_NONE, WITNESS_PKH, WITNESS_SH }; class TestBuilder { private: //! Actually executed script CScript script; //! The P2SH redeemscript CScript redeemscript; //! The Witness embedded script CScript witscript; CScriptWitness scriptWitness; CTransactionRef creditTx; CMutableTransaction spendTx; bool havePush; std::vector<unsigned char> push; std::string comment; int flags; int scriptError; CAmount nValue; void DoPush() { if (havePush) { spendTx.vin[0].scriptSig << push; havePush = false; } } void DoPush(const std::vector<unsigned char>& data) { DoPush(); push = data; havePush = true; } public: TestBuilder(const CScript& script_, const std::string& comment_, int flags_, bool P2SH = false, WitnessMode wm = WITNESS_NONE, int witnessversion = 0, CAmount nValue_ = 0) : script(script_), havePush(false), comment(comment_), flags(flags_), scriptError(SCRIPT_ERR_OK), nValue(nValue_) { CScript scriptPubKey = script; if (wm == WITNESS_PKH) { uint160 hash; CHash160().Write(&script[1], script.size() - 1).Finalize(hash.begin()); script = CScript() << OP_DUP << OP_HASH160 << ToByteVector(hash) << OP_EQUALVERIFY << OP_CHECKSIG; scriptPubKey = CScript() << witnessversion << ToByteVector(hash); } else if (wm == WITNESS_SH) { witscript = scriptPubKey; uint256 hash; CSHA256().Write(&witscript[0], witscript.size()).Finalize(hash.begin()); scriptPubKey = CScript() << witnessversion << ToByteVector(hash); } if (P2SH) { redeemscript = scriptPubKey; scriptPubKey = CScript() << OP_HASH160 << ToByteVector(CScriptID(redeemscript)) << OP_EQUAL; } creditTx = MakeTransactionRef(BuildCreditingTransaction(scriptPubKey, nValue)); spendTx = BuildSpendingTransaction(CScript(), CScriptWitness(), *creditTx); } TestBuilder& ScriptError(ScriptError_t err) { scriptError = err; return *this; } TestBuilder& Add(const CScript& _script) { DoPush(); spendTx.vin[0].scriptSig += _script; return *this; } TestBuilder& Num(int num) { DoPush(); spendTx.vin[0].scriptSig << num; return *this; } TestBuilder& Push(const std::string& hex) { DoPush(ParseHex(hex)); return *this; } TestBuilder& Push(const CScript& _script) { DoPush(std::vector<unsigned char>(_script.begin(), _script.end())); return *this; } TestBuilder& PushSig(const CKey& key, int nHashType = SIGHASH_ALL, unsigned int lenR = 32, unsigned int lenS = 32, SigVersion sigversion = SIGVERSION_BASE, CAmount amount = 0) { uint256 hash = SignatureHash(script, spendTx, 0, nHashType, amount, sigversion); std::vector<unsigned char> vchSig, r, s; uint32_t iter = 0; do { key.Sign(hash, vchSig, iter++); if ((lenS == 33) != (vchSig[5 + vchSig[3]] == 33)) { NegateSignatureS(vchSig); } r = std::vector<unsigned char>(vchSig.begin() + 4, vchSig.begin() + 4 + vchSig[3]); s = std::vector<unsigned char>(vchSig.begin() + 6 + vchSig[3], vchSig.begin() + 6 + vchSig[3] + vchSig[5 + vchSig[3]]); } while (lenR != r.size() || lenS != s.size()); vchSig.push_back(static_cast<unsigned char>(nHashType)); DoPush(vchSig); return *this; } TestBuilder& PushWitSig(const CKey& key, CAmount amount = -1, int nHashType = SIGHASH_ALL, unsigned int lenR = 32, unsigned int lenS = 32, SigVersion sigversion = SIGVERSION_WITNESS_V0) { if (amount == -1) amount = nValue; return PushSig(key, nHashType, lenR, lenS, sigversion, amount).AsWit(); } TestBuilder& Push(const CPubKey& pubkey) { DoPush(std::vector<unsigned char>(pubkey.begin(), pubkey.end())); return *this; } TestBuilder& PushRedeem() { DoPush(std::vector<unsigned char>(redeemscript.begin(), redeemscript.end())); return *this; } TestBuilder& PushWitRedeem() { DoPush(std::vector<unsigned char>(witscript.begin(), witscript.end())); return AsWit(); } TestBuilder& EditPush(unsigned int pos, const std::string& hexin, const std::string& hexout) { assert(havePush); std::vector<unsigned char> datain = ParseHex(hexin); std::vector<unsigned char> dataout = ParseHex(hexout); assert(pos + datain.size() <= push.size()); BOOST_CHECK_MESSAGE(std::vector<unsigned char>(push.begin() + pos, push.begin() + pos + datain.size()) == datain, comment); push.erase(push.begin() + pos, push.begin() + pos + datain.size()); push.insert(push.begin() + pos, dataout.begin(), dataout.end()); return *this; } TestBuilder& DamagePush(unsigned int pos) { assert(havePush); assert(pos < push.size()); push[pos] ^= 1; return *this; } TestBuilder& Test() { TestBuilder copy = *this; // Make a copy so we can rollback the push. DoPush(); DoTest(creditTx->vout[0].scriptPubKey, spendTx.vin[0].scriptSig, scriptWitness, flags, comment, scriptError, nValue); *this = copy; return *this; } TestBuilder& AsWit() { assert(havePush); scriptWitness.stack.push_back(push); havePush = false; return *this; } UniValue GetJSON() { DoPush(); UniValue array(UniValue::VARR); if (!scriptWitness.stack.empty()) { UniValue wit(UniValue::VARR); for (unsigned i = 0; i < scriptWitness.stack.size(); i++) { wit.push_back(HexStr(scriptWitness.stack[i])); } wit.push_back(ValueFromAmount(nValue)); array.push_back(wit); } array.push_back(FormatScript(spendTx.vin[0].scriptSig)); array.push_back(FormatScript(creditTx->vout[0].scriptPubKey)); array.push_back(FormatScriptFlags(flags)); array.push_back(FormatScriptError((ScriptError_t)scriptError)); array.push_back(comment); return array; } std::string GetComment() { return comment; } }; std::string JSONPrettyPrint(const UniValue& univalue) { std::string ret = univalue.write(4); // Workaround for libunivalue pretty printer, which puts a space between commas and newlines size_t pos = 0; while ((pos = ret.find(" \n", pos)) != std::string::npos) { ret.replace(pos, 2, "\n"); pos++; } return ret; } } // namespace BOOST_AUTO_TEST_CASE(script_build) { const KeyData keys; std::vector<TestBuilder> tests; tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG, "P2PK", 0 ).PushSig(keys.key0)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG, "P2PK, bad sig", 0 ).PushSig(keys.key0).DamagePush(10).ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey1C.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG, "P2PKH", 0 ).PushSig(keys.key1).Push(keys.pubkey1C)); tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey2C.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG, "P2PKH, bad pubkey", 0 ).PushSig(keys.key2).Push(keys.pubkey2C).DamagePush(5).ScriptError(SCRIPT_ERR_EQUALVERIFY)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG, "P2PK anyonecanpay", 0 ).PushSig(keys.key1, SIGHASH_ALL | SIGHASH_ANYONECANPAY)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG, "P2PK anyonecanpay marked with normal hashtype", 0 ).PushSig(keys.key1, SIGHASH_ALL | SIGHASH_ANYONECANPAY).EditPush(70, "81", "01").ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C) << OP_CHECKSIG, "P2SH(P2PK)", SCRIPT_VERIFY_P2SH, true ).PushSig(keys.key0).PushRedeem()); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C) << OP_CHECKSIG, "P2SH(P2PK), bad redeemscript", SCRIPT_VERIFY_P2SH, true ).PushSig(keys.key0).PushRedeem().DamagePush(10).ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey0.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG, "P2SH(P2PKH)", SCRIPT_VERIFY_P2SH, true ).PushSig(keys.key0).Push(keys.pubkey0).PushRedeem()); tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey1.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG, "P2SH(P2PKH), bad sig but no VERIFY_P2SH", 0, true ).PushSig(keys.key0).DamagePush(10).PushRedeem()); tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey1.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG, "P2SH(P2PKH), bad sig", SCRIPT_VERIFY_P2SH, true ).PushSig(keys.key0).DamagePush(10).PushRedeem().ScriptError(SCRIPT_ERR_EQUALVERIFY)); tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG, "3-of-3", 0 ).Num(0).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2)); tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG, "3-of-3, 2 sigs", 0 ).Num(0).PushSig(keys.key0).PushSig(keys.key1).Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG, "P2SH(2-of-3)", SCRIPT_VERIFY_P2SH, true ).Num(0).PushSig(keys.key1).PushSig(keys.key2).PushRedeem()); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG, "P2SH(2-of-3), 1 sig", SCRIPT_VERIFY_P2SH, true ).Num(0).PushSig(keys.key1).Num(0).PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG, "P2PK with too much R padding but no DERSIG", 0 ).PushSig(keys.key1, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000")); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG, "P2PK with too much R padding", SCRIPT_VERIFY_DERSIG ).PushSig(keys.key1, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").ScriptError(SCRIPT_ERR_SIG_DER)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG, "P2PK with too much S padding but no DERSIG", 0 ).PushSig(keys.key1, SIGHASH_ALL).EditPush(1, "44", "45").EditPush(37, "20", "2100")); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG, "P2PK with too much S padding", SCRIPT_VERIFY_DERSIG ).PushSig(keys.key1, SIGHASH_ALL).EditPush(1, "44", "45").EditPush(37, "20", "2100").ScriptError(SCRIPT_ERR_SIG_DER)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG, "P2PK with too little R padding but no DERSIG", 0 ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220")); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG, "P2PK with too little R padding", SCRIPT_VERIFY_DERSIG ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT, "P2PK NOT with bad sig with too much R padding but no DERSIG", 0 ).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").DamagePush(10)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT, "P2PK NOT with bad sig with too much R padding", SCRIPT_VERIFY_DERSIG ).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").DamagePush(10).ScriptError(SCRIPT_ERR_SIG_DER)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT, "P2PK NOT with too much R padding but no DERSIG", 0 ).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT, "P2PK NOT with too much R padding", SCRIPT_VERIFY_DERSIG ).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").ScriptError(SCRIPT_ERR_SIG_DER)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG, "BIP66 example 1, without DERSIG", 0 ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220")); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG, "BIP66 example 1, with DERSIG", SCRIPT_VERIFY_DERSIG ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT, "BIP66 example 2, without DERSIG", 0 ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT, "BIP66 example 2, with DERSIG", SCRIPT_VERIFY_DERSIG ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG, "BIP66 example 3, without DERSIG", 0 ).Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG, "BIP66 example 3, with DERSIG", SCRIPT_VERIFY_DERSIG ).Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT, "BIP66 example 4, without DERSIG", 0 ).Num(0)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT, "BIP66 example 4, with DERSIG", SCRIPT_VERIFY_DERSIG ).Num(0)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG, "BIP66 example 5, without DERSIG", 0 ).Num(1).ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG, "BIP66 example 5, with DERSIG", SCRIPT_VERIFY_DERSIG ).Num(1).ScriptError(SCRIPT_ERR_SIG_DER)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT, "BIP66 example 6, without DERSIG", 0 ).Num(1)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT, "BIP66 example 6, with DERSIG", SCRIPT_VERIFY_DERSIG ).Num(1).ScriptError(SCRIPT_ERR_SIG_DER)); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG, "BIP66 example 7, without DERSIG", 0 ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").PushSig(keys.key2)); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG, "BIP66 example 7, with DERSIG", SCRIPT_VERIFY_DERSIG ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").PushSig(keys.key2).ScriptError(SCRIPT_ERR_SIG_DER)); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT, "BIP66 example 8, without DERSIG", 0 ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").PushSig(keys.key2).ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT, "BIP66 example 8, with DERSIG", SCRIPT_VERIFY_DERSIG ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").PushSig(keys.key2).ScriptError(SCRIPT_ERR_SIG_DER)); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG, "BIP66 example 9, without DERSIG", 0 ).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG, "BIP66 example 9, with DERSIG", SCRIPT_VERIFY_DERSIG ).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER)); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT, "BIP66 example 10, without DERSIG", 0 ).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220")); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT, "BIP66 example 10, with DERSIG", SCRIPT_VERIFY_DERSIG ).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER)); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG, "BIP66 example 11, without DERSIG", 0 ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG, "BIP66 example 11, with DERSIG", SCRIPT_VERIFY_DERSIG ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT, "BIP66 example 12, without DERSIG", 0 ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").Num(0)); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT, "BIP66 example 12, with DERSIG", SCRIPT_VERIFY_DERSIG ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").Num(0)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG, "P2PK with multi-byte hashtype, without DERSIG", 0 ).PushSig(keys.key2, SIGHASH_ALL).EditPush(70, "01", "0101")); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG, "P2PK with multi-byte hashtype, with DERSIG", SCRIPT_VERIFY_DERSIG ).PushSig(keys.key2, SIGHASH_ALL).EditPush(70, "01", "0101").ScriptError(SCRIPT_ERR_SIG_DER)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG, "P2PK with high S but no LOW_S", 0 ).PushSig(keys.key2, SIGHASH_ALL, 32, 33)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG, "P2PK with high S", SCRIPT_VERIFY_LOW_S ).PushSig(keys.key2, SIGHASH_ALL, 32, 33).ScriptError(SCRIPT_ERR_SIG_HIGH_S)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG, "P2PK with hybrid pubkey but no STRICTENC", 0 ).PushSig(keys.key0, SIGHASH_ALL)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG, "P2PK with hybrid pubkey", SCRIPT_VERIFY_STRICTENC ).PushSig(keys.key0, SIGHASH_ALL).ScriptError(SCRIPT_ERR_PUBKEYTYPE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT, "P2PK NOT with hybrid pubkey but no STRICTENC", 0 ).PushSig(keys.key0, SIGHASH_ALL).ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT, "P2PK NOT with hybrid pubkey", SCRIPT_VERIFY_STRICTENC ).PushSig(keys.key0, SIGHASH_ALL).ScriptError(SCRIPT_ERR_PUBKEYTYPE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT, "P2PK NOT with invalid hybrid pubkey but no STRICTENC", 0 ).PushSig(keys.key0, SIGHASH_ALL).DamagePush(10)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT, "P2PK NOT with invalid hybrid pubkey", SCRIPT_VERIFY_STRICTENC ).PushSig(keys.key0, SIGHASH_ALL).DamagePush(10).ScriptError(SCRIPT_ERR_PUBKEYTYPE)); tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey0H) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG, "1-of-2 with the second 1 hybrid pubkey and no STRICTENC", 0 ).Num(0).PushSig(keys.key1, SIGHASH_ALL)); tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey0H) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG, "1-of-2 with the second 1 hybrid pubkey", SCRIPT_VERIFY_STRICTENC ).Num(0).PushSig(keys.key1, SIGHASH_ALL)); tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0H) << OP_2 << OP_CHECKMULTISIG, "1-of-2 with the first 1 hybrid pubkey", SCRIPT_VERIFY_STRICTENC ).Num(0).PushSig(keys.key1, SIGHASH_ALL).ScriptError(SCRIPT_ERR_PUBKEYTYPE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG, "P2PK with undefined hashtype but no STRICTENC", 0 ).PushSig(keys.key1, 5)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG, "P2PK with undefined hashtype", SCRIPT_VERIFY_STRICTENC ).PushSig(keys.key1, 5).ScriptError(SCRIPT_ERR_SIG_HASHTYPE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG << OP_NOT, "P2PK NOT with invalid sig and undefined hashtype but no STRICTENC", 0 ).PushSig(keys.key1, 5).DamagePush(10)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG << OP_NOT, "P2PK NOT with invalid sig and undefined hashtype", SCRIPT_VERIFY_STRICTENC ).PushSig(keys.key1, 5).DamagePush(10).ScriptError(SCRIPT_ERR_SIG_HASHTYPE)); tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG, "3-of-3 with nonzero dummy but no NULLDUMMY", 0 ).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2)); tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG, "3-of-3 with nonzero dummy", SCRIPT_VERIFY_NULLDUMMY ).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2).ScriptError(SCRIPT_ERR_SIG_NULLDUMMY)); tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG << OP_NOT, "3-of-3 NOT with invalid sig and nonzero dummy but no NULLDUMMY", 0 ).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2).DamagePush(10)); tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG << OP_NOT, "3-of-3 NOT with invalid sig with nonzero dummy", SCRIPT_VERIFY_NULLDUMMY ).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2).DamagePush(10).ScriptError(SCRIPT_ERR_SIG_NULLDUMMY)); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG, "2-of-2 with two identical keys and sigs pushed using OP_DUP but no SIGPUSHONLY", 0 ).Num(0).PushSig(keys.key1).Add(CScript() << OP_DUP)); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG, "2-of-2 with two identical keys and sigs pushed using OP_DUP", SCRIPT_VERIFY_SIGPUSHONLY ).Num(0).PushSig(keys.key1).Add(CScript() << OP_DUP).ScriptError(SCRIPT_ERR_SIG_PUSHONLY)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG, "P2SH(P2PK) with non-push scriptSig but no P2SH or SIGPUSHONLY", 0, true ).PushSig(keys.key2).Add(CScript() << OP_NOP8).PushRedeem()); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG, "P2PK with non-push scriptSig but with P2SH validation", 0 ).PushSig(keys.key2).Add(CScript() << OP_NOP8)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG, "P2SH(P2PK) with non-push scriptSig but no SIGPUSHONLY", SCRIPT_VERIFY_P2SH, true ).PushSig(keys.key2).Add(CScript() << OP_NOP8).PushRedeem().ScriptError(SCRIPT_ERR_SIG_PUSHONLY)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG, "P2SH(P2PK) with non-push scriptSig but not P2SH", SCRIPT_VERIFY_SIGPUSHONLY, true ).PushSig(keys.key2).Add(CScript() << OP_NOP8).PushRedeem().ScriptError(SCRIPT_ERR_SIG_PUSHONLY)); tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG, "2-of-2 with two identical keys and sigs pushed", SCRIPT_VERIFY_SIGPUSHONLY ).Num(0).PushSig(keys.key1).PushSig(keys.key1)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG, "P2PK with unnecessary input but no CLEANSTACK", SCRIPT_VERIFY_P2SH ).Num(11).PushSig(keys.key0)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG, "P2PK with unnecessary input", SCRIPT_VERIFY_CLEANSTACK | SCRIPT_VERIFY_P2SH ).Num(11).PushSig(keys.key0).ScriptError(SCRIPT_ERR_CLEANSTACK)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG, "P2SH with unnecessary input but no CLEANSTACK", SCRIPT_VERIFY_P2SH, true ).Num(11).PushSig(keys.key0).PushRedeem()); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG, "P2SH with unnecessary input", SCRIPT_VERIFY_CLEANSTACK | SCRIPT_VERIFY_P2SH, true ).Num(11).PushSig(keys.key0).PushRedeem().ScriptError(SCRIPT_ERR_CLEANSTACK)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG, "P2SH with CLEANSTACK", SCRIPT_VERIFY_CLEANSTACK | SCRIPT_VERIFY_P2SH, true ).PushSig(keys.key0).PushRedeem()); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG, "Basic P2WSH", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WITNESS_SH, 0, 1).PushWitSig(keys.key0).PushWitRedeem()); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0), "Basic P2WPKH", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WITNESS_PKH, 0, 1).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit()); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG, "Basic P2SH(P2WSH)", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WITNESS_SH, 0, 1).PushWitSig(keys.key0).PushWitRedeem().PushRedeem()); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0), "Basic P2SH(P2WPKH)", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WITNESS_PKH, 0, 1).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().PushRedeem()); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG, "Basic P2WSH with the wrong key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WITNESS_SH ).PushWitSig(keys.key0).PushWitRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1), "Basic P2WPKH with the wrong key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WITNESS_PKH ).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit().ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG, "Basic P2SH(P2WSH) with the wrong key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WITNESS_SH ).PushWitSig(keys.key0).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1), "Basic P2SH(P2WPKH) with the wrong key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WITNESS_PKH ).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit().PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG, "Basic P2WSH with the wrong key but no WITNESS", SCRIPT_VERIFY_P2SH, false, WITNESS_SH ).PushWitSig(keys.key0).PushWitRedeem()); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1), "Basic P2WPKH with the wrong key but no WITNESS", SCRIPT_VERIFY_P2SH, false, WITNESS_PKH ).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit()); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG, "Basic P2SH(P2WSH) with the wrong key but no WITNESS", SCRIPT_VERIFY_P2SH, true, WITNESS_SH ).PushWitSig(keys.key0).PushWitRedeem().PushRedeem()); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1), "Basic P2SH(P2WPKH) with the wrong key but no WITNESS", SCRIPT_VERIFY_P2SH, true, WITNESS_PKH ).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit().PushRedeem()); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG, "Basic P2WSH with wrong value", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WITNESS_SH, 0, 0).PushWitSig(keys.key0, 1).PushWitRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0), "Basic P2WPKH with wrong value", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WITNESS_PKH, 0, 0).PushWitSig(keys.key0, 1).Push(keys.pubkey0).AsWit().ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG, "Basic P2SH(P2WSH) with wrong value", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WITNESS_SH, 0, 0).PushWitSig(keys.key0, 1).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0), "Basic P2SH(P2WPKH) with wrong value", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WITNESS_PKH, 0, 0).PushWitSig(keys.key0, 1).Push(keys.pubkey0).AsWit().PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0), "P2WPKH with future witness version", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM, false, WITNESS_PKH, 1 ).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().ScriptError(SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM)); { CScript witscript = CScript() << ToByteVector(keys.pubkey0); uint256 hash; CSHA256().Write(&witscript[0], witscript.size()).Finalize(hash.begin()); std::vector<unsigned char> hashBytes = ToByteVector(hash); hashBytes.pop_back(); tests.push_back(TestBuilder(CScript() << OP_0 << hashBytes, "P2WPKH with wrong witness program length", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false ).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().ScriptError(SCRIPT_ERR_WITNESS_PROGRAM_WRONG_LENGTH)); } tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG, "P2WSH with empty witness", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WITNESS_SH ).ScriptError(SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY)); { CScript witscript = CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG; tests.push_back(TestBuilder(witscript, "P2WSH with witness program mismatch", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WITNESS_SH ).PushWitSig(keys.key0).Push(witscript).DamagePush(0).AsWit().ScriptError(SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH)); } tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0), "P2WPKH with witness program mismatch", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WITNESS_PKH ).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().Push("0").AsWit().ScriptError(SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0), "P2WPKH with non-empty scriptSig", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WITNESS_PKH ).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().Num(11).ScriptError(SCRIPT_ERR_WITNESS_MALLEATED)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1), "P2SH(P2WPKH) with superfluous push in scriptSig", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WITNESS_PKH ).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit().Num(11).PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_MALLEATED_P2SH)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG, "P2PK with witness", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH ).PushSig(keys.key0).Push("0").AsWit().ScriptError(SCRIPT_ERR_WITNESS_UNEXPECTED)); // Compressed keys should pass SCRIPT_VERIFY_WITNESS_PUBKEYTYPE tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C) << OP_CHECKSIG, "Basic P2WSH with compressed key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WITNESS_SH, 0, 1).PushWitSig(keys.key0C).PushWitRedeem()); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C), "Basic P2WPKH with compressed key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WITNESS_PKH, 0, 1).PushWitSig(keys.key0C).Push(keys.pubkey0C).AsWit()); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C) << OP_CHECKSIG, "Basic P2SH(P2WSH) with compressed key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WITNESS_SH, 0, 1).PushWitSig(keys.key0C).PushWitRedeem().PushRedeem()); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C), "Basic P2SH(P2WPKH) with compressed key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WITNESS_PKH, 0, 1).PushWitSig(keys.key0C).Push(keys.pubkey0C).AsWit().PushRedeem()); // Testing uncompressed key in witness with SCRIPT_VERIFY_WITNESS_PUBKEYTYPE tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG, "Basic P2WSH", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WITNESS_SH, 0, 1).PushWitSig(keys.key0).PushWitRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0), "Basic P2WPKH", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WITNESS_PKH, 0, 1).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG, "Basic P2SH(P2WSH)", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WITNESS_SH, 0, 1).PushWitSig(keys.key0).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE)); tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0), "Basic P2SH(P2WPKH)", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WITNESS_PKH, 0, 1).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE)); // P2WSH 1-of-2 multisig with compressed keys tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG, "P2WSH CHECKMULTISIG with compressed keys", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WITNESS_SH, 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem()); tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG, "P2SH(P2WSH) CHECKMULTISIG with compressed keys", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WITNESS_SH, 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem().PushRedeem()); tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG, "P2WSH CHECKMULTISIG with compressed keys", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WITNESS_SH, 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem()); tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG, "P2SH(P2WSH) CHECKMULTISIG with compressed keys", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WITNESS_SH, 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem().PushRedeem()); // P2WSH 1-of-2 multisig with first key uncompressed tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG, "P2WSH CHECKMULTISIG with first key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WITNESS_SH, 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0).PushWitRedeem()); tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG, "P2SH(P2WSH) CHECKMULTISIG first key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WITNESS_SH, 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0).PushWitRedeem().PushRedeem()); tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG, "P2WSH CHECKMULTISIG with first key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WITNESS_SH, 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0).PushWitRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE)); tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG, "P2SH(P2WSH) CHECKMULTISIG with first key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WITNESS_SH, 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE)); tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG, "P2WSH CHECKMULTISIG with first key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WITNESS_SH, 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem()); tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG, "P2SH(P2WSH) CHECKMULTISIG with first key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WITNESS_SH, 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem().PushRedeem()); tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG, "P2WSH CHECKMULTISIG with first key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WITNESS_SH, 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE)); tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG, "P2SH(P2WSH) CHECKMULTISIG with first key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WITNESS_SH, 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE)); // P2WSH 1-of-2 multisig with second key uncompressed tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG, "P2WSH CHECKMULTISIG with second key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WITNESS_SH, 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem()); tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG, "P2SH(P2WSH) CHECKMULTISIG second key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WITNESS_SH, 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem().PushRedeem()); tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG, "P2WSH CHECKMULTISIG with second key uncompressed and signing with the first key should pass as the uncompressed key is not used", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WITNESS_SH, 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem()); tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG, "P2SH(P2WSH) CHECKMULTISIG with second key uncompressed and signing with the first key should pass as the uncompressed key is not used", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WITNESS_SH, 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem().PushRedeem()); tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG, "P2WSH CHECKMULTISIG with second key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WITNESS_SH, 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1).PushWitRedeem()); tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG, "P2SH(P2WSH) CHECKMULTISIG with second key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WITNESS_SH, 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1).PushWitRedeem().PushRedeem()); tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG, "P2WSH CHECKMULTISIG with second key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WITNESS_SH, 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1).PushWitRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE)); tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG, "P2SH(P2WSH) CHECKMULTISIG with second key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WITNESS_SH, 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE)); std::set<std::string> tests_set; { UniValue json_tests = read_json(std::string(json_tests::script_tests, json_tests::script_tests + sizeof(json_tests::script_tests))); for (unsigned int idx = 0; idx < json_tests.size(); idx++) { const UniValue& tv = json_tests[idx]; tests_set.insert(JSONPrettyPrint(tv.get_array())); } } std::string strGen; for (TestBuilder& test : tests) { test.Test(); std::string str = JSONPrettyPrint(test.GetJSON()); #ifndef UPDATE_JSON_TESTS if (tests_set.count(str) == 0) { BOOST_CHECK_MESSAGE(false, "Missing auto script_valid test: " + test.GetComment()); } #endif strGen += str + ",\n"; } #ifdef UPDATE_JSON_TESTS FILE* file = fopen("script_tests.json.gen", "w"); fputs(strGen.c_str(), file); fclose(file); #endif } BOOST_AUTO_TEST_CASE(script_json_test) { // Read tests from test/data/script_tests.json // Format is an array of arrays // Inner arrays are [ ["wit"..., nValue]?, "scriptSig", "scriptPubKey", "flags", "expected_scripterror" ] // ... where scriptSig and scriptPubKey are stringified // scripts. // If a witness is given, then the last value in the array should be the // amount (nValue) to use in the crediting tx UniValue tests = read_json(std::string(json_tests::script_tests, json_tests::script_tests + sizeof(json_tests::script_tests))); for (unsigned int idx = 0; idx < tests.size(); idx++) { UniValue test = tests[idx]; std::string strTest = test.write(); CScriptWitness witness; CAmount nValue = 0; unsigned int pos = 0; if (test.size() > 0 && test[pos].isArray()) { unsigned int i=0; for (i = 0; i < test[pos].size()-1; i++) { witness.stack.push_back(ParseHex(test[pos][i].get_str())); } nValue = AmountFromValue(test[pos][i]); pos++; } if (test.size() < 4 + pos) // Allow size > 3; extra stuff ignored (useful for comments) { if (test.size() != 1) { BOOST_ERROR("Bad test: " << strTest); } continue; } std::string scriptSigString = test[pos++].get_str(); CScript scriptSig = ParseScript(scriptSigString); std::string scriptPubKeyString = test[pos++].get_str(); CScript scriptPubKey = ParseScript(scriptPubKeyString); unsigned int scriptflags = ParseScriptFlags(test[pos++].get_str()); int scriptError = ParseScriptError(test[pos++].get_str()); DoTest(scriptPubKey, scriptSig, witness, scriptflags, strTest, scriptError, nValue); } } BOOST_AUTO_TEST_CASE(script_PushData) { // Check that PUSHDATA1, PUSHDATA2, and PUSHDATA4 create the same value on // the stack as the 1-75 opcodes do. static const unsigned char direct[] = { 1, 0x5a }; static const unsigned char pushdata1[] = { OP_PUSHDATA1, 1, 0x5a }; static const unsigned char pushdata2[] = { OP_PUSHDATA2, 1, 0, 0x5a }; static const unsigned char pushdata4[] = { OP_PUSHDATA4, 1, 0, 0, 0, 0x5a }; ScriptError err; std::vector<std::vector<unsigned char> > directStack; BOOST_CHECK(EvalScript(directStack, CScript(&direct[0], &direct[sizeof(direct)]), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SIGVERSION_BASE, &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); std::vector<std::vector<unsigned char> > pushdata1Stack; BOOST_CHECK(EvalScript(pushdata1Stack, CScript(&pushdata1[0], &pushdata1[sizeof(pushdata1)]), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SIGVERSION_BASE, &err)); BOOST_CHECK(pushdata1Stack == directStack); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); std::vector<std::vector<unsigned char> > pushdata2Stack; BOOST_CHECK(EvalScript(pushdata2Stack, CScript(&pushdata2[0], &pushdata2[sizeof(pushdata2)]), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SIGVERSION_BASE, &err)); BOOST_CHECK(pushdata2Stack == directStack); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); std::vector<std::vector<unsigned char> > pushdata4Stack; BOOST_CHECK(EvalScript(pushdata4Stack, CScript(&pushdata4[0], &pushdata4[sizeof(pushdata4)]), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SIGVERSION_BASE, &err)); BOOST_CHECK(pushdata4Stack == directStack); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); } CScript sign_multisig(CScript scriptPubKey, std::vector<CKey> keys, CTransaction transaction) { uint256 hash = SignatureHash(scriptPubKey, transaction, 0, SIGHASH_ALL, 0, SIGVERSION_BASE); CScript result; // // NOTE: CHECKMULTISIG has an unfortunate bug; it requires // one extra item on the stack, before the signatures. // Putting OP_0 on the stack is the workaround; // fixing the bug would mean splitting the block chain (old // clients would not accept new CHECKMULTISIG transactions, // and vice-versa) // result << OP_0; for (const CKey &key : keys) { std::vector<unsigned char> vchSig; BOOST_CHECK(key.Sign(hash, vchSig)); vchSig.push_back((unsigned char)SIGHASH_ALL); result << vchSig; } return result; } CScript sign_multisig(CScript scriptPubKey, const CKey &key, CTransaction transaction) { std::vector<CKey> keys; keys.push_back(key); return sign_multisig(scriptPubKey, keys, transaction); } BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG12) { ScriptError err; CKey key1, key2, key3; key1.MakeNewKey(true); key2.MakeNewKey(false); key3.MakeNewKey(true); CScript scriptPubKey12; scriptPubKey12 << OP_1 << ToByteVector(key1.GetPubKey()) << ToByteVector(key2.GetPubKey()) << OP_2 << OP_CHECKMULTISIG; CMutableTransaction txFrom12 = BuildCreditingTransaction(scriptPubKey12); CMutableTransaction txTo12 = BuildSpendingTransaction(CScript(), CScriptWitness(), txFrom12); CScript goodsig1 = sign_multisig(scriptPubKey12, key1, txTo12); BOOST_CHECK(VerifyScript(goodsig1, scriptPubKey12, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo12, 0, txFrom12.vout[0].nValue), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); txTo12.vout[0].nValue = 2; BOOST_CHECK(!VerifyScript(goodsig1, scriptPubKey12, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo12, 0, txFrom12.vout[0].nValue), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); CScript goodsig2 = sign_multisig(scriptPubKey12, key2, txTo12); BOOST_CHECK(VerifyScript(goodsig2, scriptPubKey12, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo12, 0, txFrom12.vout[0].nValue), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); CScript badsig1 = sign_multisig(scriptPubKey12, key3, txTo12); BOOST_CHECK(!VerifyScript(badsig1, scriptPubKey12, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo12, 0, txFrom12.vout[0].nValue), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); } BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG23) { ScriptError err; CKey key1, key2, key3, key4; key1.MakeNewKey(true); key2.MakeNewKey(false); key3.MakeNewKey(true); key4.MakeNewKey(false); CScript scriptPubKey23; scriptPubKey23 << OP_2 << ToByteVector(key1.GetPubKey()) << ToByteVector(key2.GetPubKey()) << ToByteVector(key3.GetPubKey()) << OP_3 << OP_CHECKMULTISIG; CMutableTransaction txFrom23 = BuildCreditingTransaction(scriptPubKey23); CMutableTransaction txTo23 = BuildSpendingTransaction(CScript(), CScriptWitness(), txFrom23); std::vector<CKey> keys; keys.push_back(key1); keys.push_back(key2); CScript goodsig1 = sign_multisig(scriptPubKey23, keys, txTo23); BOOST_CHECK(VerifyScript(goodsig1, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); keys.clear(); keys.push_back(key1); keys.push_back(key3); CScript goodsig2 = sign_multisig(scriptPubKey23, keys, txTo23); BOOST_CHECK(VerifyScript(goodsig2, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); keys.clear(); keys.push_back(key2); keys.push_back(key3); CScript goodsig3 = sign_multisig(scriptPubKey23, keys, txTo23); BOOST_CHECK(VerifyScript(goodsig3, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); keys.clear(); keys.push_back(key2); keys.push_back(key2); // Can't re-use sig CScript badsig1 = sign_multisig(scriptPubKey23, keys, txTo23); BOOST_CHECK(!VerifyScript(badsig1, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); keys.clear(); keys.push_back(key2); keys.push_back(key1); // sigs must be in correct order CScript badsig2 = sign_multisig(scriptPubKey23, keys, txTo23); BOOST_CHECK(!VerifyScript(badsig2, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); keys.clear(); keys.push_back(key3); keys.push_back(key2); // sigs must be in correct order CScript badsig3 = sign_multisig(scriptPubKey23, keys, txTo23); BOOST_CHECK(!VerifyScript(badsig3, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); keys.clear(); keys.push_back(key4); keys.push_back(key2); // sigs must match pubkeys CScript badsig4 = sign_multisig(scriptPubKey23, keys, txTo23); BOOST_CHECK(!VerifyScript(badsig4, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); keys.clear(); keys.push_back(key1); keys.push_back(key4); // sigs must match pubkeys CScript badsig5 = sign_multisig(scriptPubKey23, keys, txTo23); BOOST_CHECK(!VerifyScript(badsig5, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); keys.clear(); // Must have signatures CScript badsig6 = sign_multisig(scriptPubKey23, keys, txTo23); BOOST_CHECK(!VerifyScript(badsig6, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_INVALID_STACK_OPERATION, ScriptErrorString(err)); } BOOST_AUTO_TEST_CASE(script_combineSigs) { // Test the CombineSignatures function CAmount amount = 0; CBasicKeyStore keystore; std::vector<CKey> keys; std::vector<CPubKey> pubkeys; for (int i = 0; i < 3; i++) { CKey key; key.MakeNewKey(i%2 == 1); keys.push_back(key); pubkeys.push_back(key.GetPubKey()); keystore.AddKey(key); } CMutableTransaction txFrom = BuildCreditingTransaction(GetScriptForDestination(keys[0].GetPubKey().GetID())); CMutableTransaction txTo = BuildSpendingTransaction(CScript(), CScriptWitness(), txFrom); CScript& scriptPubKey = txFrom.vout[0].scriptPubKey; CScript& scriptSig = txTo.vin[0].scriptSig; SignatureData empty; SignatureData combined = CombineSignatures(scriptPubKey, MutableTransactionSignatureChecker(&txTo, 0, amount), empty, empty); BOOST_CHECK(combined.scriptSig.empty()); // Single signature case: SignSignature(keystore, txFrom, txTo, 0, SIGHASH_ALL); // changes scriptSig combined = CombineSignatures(scriptPubKey, MutableTransactionSignatureChecker(&txTo, 0, amount), SignatureData(scriptSig), empty); BOOST_CHECK(combined.scriptSig == scriptSig); combined = CombineSignatures(scriptPubKey, MutableTransactionSignatureChecker(&txTo, 0, amount), empty, SignatureData(scriptSig)); BOOST_CHECK(combined.scriptSig == scriptSig); CScript scriptSigCopy = scriptSig; // Signing again will give a different, valid signature: SignSignature(keystore, txFrom, txTo, 0, SIGHASH_ALL); combined = CombineSignatures(scriptPubKey, MutableTransactionSignatureChecker(&txTo, 0, amount), SignatureData(scriptSigCopy), SignatureData(scriptSig)); BOOST_CHECK(combined.scriptSig == scriptSigCopy || combined.scriptSig == scriptSig); // P2SH, single-signature case: CScript pkSingle; pkSingle << ToByteVector(keys[0].GetPubKey()) << OP_CHECKSIG; keystore.AddCScript(pkSingle); scriptPubKey = GetScriptForDestination(CScriptID(pkSingle)); SignSignature(keystore, txFrom, txTo, 0, SIGHASH_ALL); combined = CombineSignatures(scriptPubKey, MutableTransactionSignatureChecker(&txTo, 0, amount), SignatureData(scriptSig), empty); BOOST_CHECK(combined.scriptSig == scriptSig); combined = CombineSignatures(scriptPubKey, MutableTransactionSignatureChecker(&txTo, 0, amount), empty, SignatureData(scriptSig)); BOOST_CHECK(combined.scriptSig == scriptSig); scriptSigCopy = scriptSig; SignSignature(keystore, txFrom, txTo, 0, SIGHASH_ALL); combined = CombineSignatures(scriptPubKey, MutableTransactionSignatureChecker(&txTo, 0, amount), SignatureData(scriptSigCopy), SignatureData(scriptSig)); BOOST_CHECK(combined.scriptSig == scriptSigCopy || combined.scriptSig == scriptSig); // dummy scriptSigCopy with placeholder, should always choose non-placeholder: scriptSigCopy = CScript() << OP_0 << std::vector<unsigned char>(pkSingle.begin(), pkSingle.end()); combined = CombineSignatures(scriptPubKey, MutableTransactionSignatureChecker(&txTo, 0, amount), SignatureData(scriptSigCopy), SignatureData(scriptSig)); BOOST_CHECK(combined.scriptSig == scriptSig); combined = CombineSignatures(scriptPubKey, MutableTransactionSignatureChecker(&txTo, 0, amount), SignatureData(scriptSig), SignatureData(scriptSigCopy)); BOOST_CHECK(combined.scriptSig == scriptSig); // Hardest case: Multisig 2-of-3 scriptPubKey = GetScriptForMultisig(2, pubkeys); keystore.AddCScript(scriptPubKey); SignSignature(keystore, txFrom, txTo, 0, SIGHASH_ALL); combined = CombineSignatures(scriptPubKey, MutableTransactionSignatureChecker(&txTo, 0, amount), SignatureData(scriptSig), empty); BOOST_CHECK(combined.scriptSig == scriptSig); combined = CombineSignatures(scriptPubKey, MutableTransactionSignatureChecker(&txTo, 0, amount), empty, SignatureData(scriptSig)); BOOST_CHECK(combined.scriptSig == scriptSig); // A couple of partially-signed versions: std::vector<unsigned char> sig1; uint256 hash1 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_ALL, 0, SIGVERSION_BASE); BOOST_CHECK(keys[0].Sign(hash1, sig1)); sig1.push_back(SIGHASH_ALL); std::vector<unsigned char> sig2; uint256 hash2 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_NONE, 0, SIGVERSION_BASE); BOOST_CHECK(keys[1].Sign(hash2, sig2)); sig2.push_back(SIGHASH_NONE); std::vector<unsigned char> sig3; uint256 hash3 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_SINGLE, 0, SIGVERSION_BASE); BOOST_CHECK(keys[2].Sign(hash3, sig3)); sig3.push_back(SIGHASH_SINGLE); // Not fussy about order (or even existence) of placeholders or signatures: CScript partial1a = CScript() << OP_0 << sig1 << OP_0; CScript partial1b = CScript() << OP_0 << OP_0 << sig1; CScript partial2a = CScript() << OP_0 << sig2; CScript partial2b = CScript() << sig2 << OP_0; CScript partial3a = CScript() << sig3; CScript partial3b = CScript() << OP_0 << OP_0 << sig3; CScript partial3c = CScript() << OP_0 << sig3 << OP_0; CScript complete12 = CScript() << OP_0 << sig1 << sig2; CScript complete13 = CScript() << OP_0 << sig1 << sig3; CScript complete23 = CScript() << OP_0 << sig2 << sig3; combined = CombineSignatures(scriptPubKey, MutableTransactionSignatureChecker(&txTo, 0, amount), SignatureData(partial1a), SignatureData(partial1b)); BOOST_CHECK(combined.scriptSig == partial1a); combined = CombineSignatures(scriptPubKey, MutableTransactionSignatureChecker(&txTo, 0, amount), SignatureData(partial1a), SignatureData(partial2a)); BOOST_CHECK(combined.scriptSig == complete12); combined = CombineSignatures(scriptPubKey, MutableTransactionSignatureChecker(&txTo, 0, amount), SignatureData(partial2a), SignatureData(partial1a)); BOOST_CHECK(combined.scriptSig == complete12); combined = CombineSignatures(scriptPubKey, MutableTransactionSignatureChecker(&txTo, 0, amount), SignatureData(partial1b), SignatureData(partial2b)); BOOST_CHECK(combined.scriptSig == complete12); combined = CombineSignatures(scriptPubKey, MutableTransactionSignatureChecker(&txTo, 0, amount), SignatureData(partial3b), SignatureData(partial1b)); BOOST_CHECK(combined.scriptSig == complete13); combined = CombineSignatures(scriptPubKey, MutableTransactionSignatureChecker(&txTo, 0, amount), SignatureData(partial2a), SignatureData(partial3a)); BOOST_CHECK(combined.scriptSig == complete23); combined = CombineSignatures(scriptPubKey, MutableTransactionSignatureChecker(&txTo, 0, amount), SignatureData(partial3b), SignatureData(partial2b)); BOOST_CHECK(combined.scriptSig == complete23); combined = CombineSignatures(scriptPubKey, MutableTransactionSignatureChecker(&txTo, 0, amount), SignatureData(partial3b), SignatureData(partial3a)); BOOST_CHECK(combined.scriptSig == partial3c); } BOOST_AUTO_TEST_CASE(script_standard_push) { ScriptError err; for (int i=0; i<67000; i++) { CScript script; script << i; BOOST_CHECK_MESSAGE(script.IsPushOnly(), "Number " << i << " is not pure push."); BOOST_CHECK_MESSAGE(VerifyScript(script, CScript() << OP_1, nullptr, SCRIPT_VERIFY_MINIMALDATA, BaseSignatureChecker(), &err), "Number " << i << " push is not minimal data."); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); } for (unsigned int i=0; i<=MAX_SCRIPT_ELEMENT_SIZE; i++) { std::vector<unsigned char> data(i, '\111'); CScript script; script << data; BOOST_CHECK_MESSAGE(script.IsPushOnly(), "Length " << i << " is not pure push."); BOOST_CHECK_MESSAGE(VerifyScript(script, CScript() << OP_1, nullptr, SCRIPT_VERIFY_MINIMALDATA, BaseSignatureChecker(), &err), "Length " << i << " push is not minimal data."); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); } } BOOST_AUTO_TEST_CASE(script_IsPushOnly_on_invalid_scripts) { // IsPushOnly returns false when given a script containing only pushes that // are invalid due to truncation. IsPushOnly() is consensus critical // because P2SH evaluation uses it, although this specific behavior should // not be consensus critical as the P2SH evaluation would fail first due to // the invalid push. Still, it doesn't hurt to test it explicitly. static const unsigned char direct[] = { 1 }; BOOST_CHECK(!CScript(direct, direct+sizeof(direct)).IsPushOnly()); } BOOST_AUTO_TEST_CASE(script_GetScriptAsm) { BOOST_CHECK_EQUAL("OP_CHECKLOCKTIMEVERIFY", ScriptToAsmStr(CScript() << OP_NOP2, true)); BOOST_CHECK_EQUAL("OP_CHECKLOCKTIMEVERIFY", ScriptToAsmStr(CScript() << OP_CHECKLOCKTIMEVERIFY, true)); BOOST_CHECK_EQUAL("OP_CHECKLOCKTIMEVERIFY", ScriptToAsmStr(CScript() << OP_NOP2)); BOOST_CHECK_EQUAL("OP_CHECKLOCKTIMEVERIFY", ScriptToAsmStr(CScript() << OP_CHECKLOCKTIMEVERIFY)); std::string derSig("304502207fa7a6d1e0ee81132a269ad84e68d695483745cde8b541e3bf630749894e342a022100c1f7ab20e13e22fb95281a870f3dcf38d782e53023ee313d741ad0cfbc0c5090"); std::string pubKey("03b0da749730dc9b4b1f4a14d6902877a92541f5368778853d9c4a0cb7802dcfb2"); std::vector<unsigned char> vchPubKey = ToByteVector(ParseHex(pubKey)); BOOST_CHECK_EQUAL(derSig + "00 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "00")) << vchPubKey, true)); BOOST_CHECK_EQUAL(derSig + "80 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "80")) << vchPubKey, true)); BOOST_CHECK_EQUAL(derSig + "[ALL] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "01")) << vchPubKey, true)); BOOST_CHECK_EQUAL(derSig + "[NONE] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "02")) << vchPubKey, true)); BOOST_CHECK_EQUAL(derSig + "[SINGLE] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "03")) << vchPubKey, true)); BOOST_CHECK_EQUAL(derSig + "[ALL|ANYONECANPAY] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "81")) << vchPubKey, true)); BOOST_CHECK_EQUAL(derSig + "[NONE|ANYONECANPAY] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "82")) << vchPubKey, true)); BOOST_CHECK_EQUAL(derSig + "[SINGLE|ANYONECANPAY] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "83")) << vchPubKey, true)); BOOST_CHECK_EQUAL(derSig + "00 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "00")) << vchPubKey)); BOOST_CHECK_EQUAL(derSig + "80 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "80")) << vchPubKey)); BOOST_CHECK_EQUAL(derSig + "01 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "01")) << vchPubKey)); BOOST_CHECK_EQUAL(derSig + "02 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "02")) << vchPubKey)); BOOST_CHECK_EQUAL(derSig + "03 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "03")) << vchPubKey)); BOOST_CHECK_EQUAL(derSig + "81 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "81")) << vchPubKey)); BOOST_CHECK_EQUAL(derSig + "82 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "82")) << vchPubKey)); BOOST_CHECK_EQUAL(derSig + "83 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "83")) << vchPubKey)); } static CScript ScriptFromHex(const char* hex) { std::vector<unsigned char> data = ParseHex(hex); return CScript(data.begin(), data.end()); } BOOST_AUTO_TEST_CASE(script_FindAndDelete) { // Exercise the FindAndDelete functionality CScript s; CScript d; CScript expect; s = CScript() << OP_1 << OP_2; d = CScript(); // delete nothing should be a no-op expect = s; BOOST_CHECK_EQUAL(s.FindAndDelete(d), 0); BOOST_CHECK(s == expect); s = CScript() << OP_1 << OP_2 << OP_3; d = CScript() << OP_2; expect = CScript() << OP_1 << OP_3; BOOST_CHECK_EQUAL(s.FindAndDelete(d), 1); BOOST_CHECK(s == expect); s = CScript() << OP_3 << OP_1 << OP_3 << OP_3 << OP_4 << OP_3; d = CScript() << OP_3; expect = CScript() << OP_1 << OP_4; BOOST_CHECK_EQUAL(s.FindAndDelete(d), 4); BOOST_CHECK(s == expect); s = ScriptFromHex("0302ff03"); // PUSH 0x02ff03 onto stack d = ScriptFromHex("0302ff03"); expect = CScript(); BOOST_CHECK_EQUAL(s.FindAndDelete(d), 1); BOOST_CHECK(s == expect); s = ScriptFromHex("0302ff030302ff03"); // PUSH 0x2ff03 PUSH 0x2ff03 d = ScriptFromHex("0302ff03"); expect = CScript(); BOOST_CHECK_EQUAL(s.FindAndDelete(d), 2); BOOST_CHECK(s == expect); s = ScriptFromHex("0302ff030302ff03"); d = ScriptFromHex("02"); expect = s; // FindAndDelete matches entire opcodes BOOST_CHECK_EQUAL(s.FindAndDelete(d), 0); BOOST_CHECK(s == expect); s = ScriptFromHex("0302ff030302ff03"); d = ScriptFromHex("ff"); expect = s; BOOST_CHECK_EQUAL(s.FindAndDelete(d), 0); BOOST_CHECK(s == expect); // This is an odd edge case: strip of the push-three-bytes // prefix, leaving 02ff03 which is push-two-bytes: s = ScriptFromHex("0302ff030302ff03"); d = ScriptFromHex("03"); expect = CScript() << ParseHex("ff03") << ParseHex("ff03"); BOOST_CHECK_EQUAL(s.FindAndDelete(d), 2); BOOST_CHECK(s == expect); // Byte sequence that spans multiple opcodes: s = ScriptFromHex("02feed5169"); // PUSH(0xfeed) OP_1 OP_VERIFY d = ScriptFromHex("feed51"); expect = s; BOOST_CHECK_EQUAL(s.FindAndDelete(d), 0); // doesn't match 'inside' opcodes BOOST_CHECK(s == expect); s = ScriptFromHex("02feed5169"); // PUSH(0xfeed) OP_1 OP_VERIFY d = ScriptFromHex("02feed51"); expect = ScriptFromHex("69"); BOOST_CHECK_EQUAL(s.FindAndDelete(d), 1); BOOST_CHECK(s == expect); s = ScriptFromHex("516902feed5169"); d = ScriptFromHex("feed51"); expect = s; BOOST_CHECK_EQUAL(s.FindAndDelete(d), 0); BOOST_CHECK(s == expect); s = ScriptFromHex("516902feed5169"); d = ScriptFromHex("02feed51"); expect = ScriptFromHex("516969"); BOOST_CHECK_EQUAL(s.FindAndDelete(d), 1); BOOST_CHECK(s == expect); s = CScript() << OP_0 << OP_0 << OP_1 << OP_1; d = CScript() << OP_0 << OP_1; expect = CScript() << OP_0 << OP_1; // FindAndDelete is single-pass BOOST_CHECK_EQUAL(s.FindAndDelete(d), 1); BOOST_CHECK(s == expect); s = CScript() << OP_0 << OP_0 << OP_1 << OP_0 << OP_1 << OP_1; d = CScript() << OP_0 << OP_1; expect = CScript() << OP_0 << OP_1; // FindAndDelete is single-pass BOOST_CHECK_EQUAL(s.FindAndDelete(d), 2); BOOST_CHECK(s == expect); // Another weird edge case: // End with invalid push (not enough data)... s = ScriptFromHex("0003feed"); d = ScriptFromHex("03feed"); // ... can remove the invalid push expect = ScriptFromHex("00"); BOOST_CHECK_EQUAL(s.FindAndDelete(d), 1); BOOST_CHECK(s == expect); s = ScriptFromHex("0003feed"); d = ScriptFromHex("00"); expect = ScriptFromHex("03feed"); BOOST_CHECK_EQUAL(s.FindAndDelete(d), 1); BOOST_CHECK(s == expect); } BOOST_AUTO_TEST_CASE(script_HasValidOps) { // Exercise the HasValidOps functionality CScript script; script = ScriptFromHex("76a9141234567890abcdefa1a2a3a4a5a6a7a8a9a0aaab88ac"); // Normal script BOOST_CHECK(script.HasValidOps()); script = ScriptFromHex("76a914ff34567890abcdefa1a2a3a4a5a6a7a8a9a0aaab88ac"); BOOST_CHECK(script.HasValidOps()); script = ScriptFromHex("ff88ac"); // Script with OP_INVALIDOPCODE explicit BOOST_CHECK(!script.HasValidOps()); script = ScriptFromHex("88acc0"); // Script with undefined opcode BOOST_CHECK(!script.HasValidOps()); } BOOST_AUTO_TEST_SUITE_END()
[ "oliver.smith5@protonmail.com" ]
oliver.smith5@protonmail.com
9c7cfac6d8786113cafdbab8f322736c32a51199
a712314e1428e8f5ab7b2db076002afef9c4a7fa
/nyla/lexer.h
18a7423c1cf12bb8b856348e66b61e7ea12e84c5
[]
no_license
JosephCRugh/nyla
52004eff83912e5f06760853af133b04c53698ac
40498a2b2873ef7c413ed7dc5d6b1e66beba1dc8
refs/heads/main
2023-08-19T11:18:18.899238
2021-09-18T00:43:04
2021-09-18T00:43:04
391,193,242
0
0
null
null
null
null
UTF-8
C++
false
false
1,892
h
#ifndef NYLA_LEXER_H #define NYLA_LEXER_H #include "source.h" #include "log.h" #include "tokens.h" namespace nyla { class lexer { public: lexer(nyla::source& source, nyla::log& log) : m_source(source), m_log(log) {} // Obtains the next token by // analyzing the current source. nyla::token next_token(); private: // Consumes whitespace and comments // until the start of a new token. void consume_ignored(); // Process encountering a new line void on_new_line(); // Next token is an identifier or // keyword. nyla::token next_word(); // Next token is a symbol. nyla::token next_symbol(); // Next token is an integer // or float. nyla::token next_number(); nyla::range read_unsigned_digits(); nyla::token next_integer(const nyla::range& digits); nyla::range read_hexidecimal_digits(); nyla::token next_hexidecimal(); nyla::token finalize_integer(u64 int_value); nyla::token next_float(const range& whole_digits, const range& fraction_digits, const range& exponent_digits, c8 exponent_sign); // Calculate an integer value based on a range of digits // @returns the computed value and a boolean to indicate if // there was overflow std::tuple<u64, bool> calculate_int_value(const nyla::range& digits); // Next token is a string nyla::token next_string(); // Next token is a character nyla::token next_character(); inline nyla::token make(u32 tag, u32 start_pos, u32 end_pos) { nyla::token token; token.tag = tag; token.line_num = m_line_num; token.spos = start_pos; token.epos = end_pos; return token; } nyla::source& m_source; nyla::log& m_log; u32 m_line_num = 1; u32 m_start_pos = 0; // The buffer position that // a token starts on }; } #endif
[ "josephcrugh@gmail.com" ]
josephcrugh@gmail.com
5b7a290eb9f8b7224246a733decba763e0c9dd75
641fa8341d8c436ad24945bcbf8e7d7d1dd7dbb2
/ui/views/controls/button/button.cc
416cdf3edad796a709b671973852bba96939c6e1
[ "BSD-3-Clause" ]
permissive
massnetwork/mass-browser
7de0dfc541cbac00ffa7308541394bac1e945b76
67526da9358734698c067b7775be491423884339
refs/heads/master
2022-12-07T09:01:31.027715
2017-01-19T14:29:18
2017-01-19T14:29:18
73,799,690
4
4
BSD-3-Clause
2022-11-26T11:53:23
2016-11-15T09:49:29
null
UTF-8
C++
false
false
2,557
cc
// Copyright (c) 2011 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 "ui/views/controls/button/button.h" #include "base/strings/utf_string_conversions.h" #include "ui/accessibility/ax_node_data.h" namespace views { //////////////////////////////////////////////////////////////////////////////// // Button, static public: // static Button::ButtonState Button::GetButtonStateFrom(ui::NativeTheme::State state) { switch (state) { case ui::NativeTheme::kDisabled: return Button::STATE_DISABLED; case ui::NativeTheme::kHovered: return Button::STATE_HOVERED; case ui::NativeTheme::kNormal: return Button::STATE_NORMAL; case ui::NativeTheme::kPressed: return Button::STATE_PRESSED; case ui::NativeTheme::kNumStates: NOTREACHED(); } return Button::STATE_NORMAL; } //////////////////////////////////////////////////////////////////////////////// // Button, public: Button::~Button() { } void Button::SetFocusForPlatform() { #if defined(OS_MACOSX) // On Mac, buttons are focusable only in full keyboard access mode. SetFocusBehavior(FocusBehavior::ACCESSIBLE_ONLY); #else SetFocusBehavior(FocusBehavior::ALWAYS); #endif } void Button::SetTooltipText(const base::string16& tooltip_text) { tooltip_text_ = tooltip_text; if (accessible_name_.empty()) accessible_name_ = tooltip_text_; TooltipTextChanged(); } void Button::SetAccessibleName(const base::string16& name) { accessible_name_ = name; } //////////////////////////////////////////////////////////////////////////////// // Button, View overrides: bool Button::GetTooltipText(const gfx::Point& p, base::string16* tooltip) const { if (tooltip_text_.empty()) return false; *tooltip = tooltip_text_; return true; } void Button::GetAccessibleNodeData(ui::AXNodeData* node_data) { node_data->role = ui::AX_ROLE_BUTTON; node_data->SetName(accessible_name_); } //////////////////////////////////////////////////////////////////////////////// // Button, protected: Button::Button(ButtonListener* listener) : listener_(listener), tag_(-1) { SetFocusBehavior(FocusBehavior::ACCESSIBLE_ONLY); } void Button::NotifyClick(const ui::Event& event) { // We can be called when there is no listener, in cases like double clicks on // menu buttons etc. if (listener_) listener_->ButtonPressed(this, event); } void Button::OnClickCanceled(const ui::Event& event) {} } // namespace views
[ "xElvis89x@gmail.com" ]
xElvis89x@gmail.com
bf087fbea7c817538361c4c83e36242f23bfe547
7fb6d1261ad0bbf0953bef84a25448e56c8f58e8
/Hotel.h
fa0d53c66a08b4d100dc449ecaf3f8884b58bab8
[]
no_license
maria-linares/ProyectoFinalPOOFINAL
8e77b5d8dc132073c7689829b8fdce8e9988280f
f0c88ba395e5ecff9fd625c943cc6fb0516adbe7
refs/heads/master
2020-06-08T04:20:04.108408
2019-07-05T21:19:15
2019-07-05T21:19:15
193,156,614
0
0
null
null
null
null
UTF-8
C++
false
false
600
h
// // Created by Maria Jose Linares on 2019-07-04. // #ifndef PROYECTOFINALPOO_HOTEL_H #define PROYECTOFINALPOO_HOTEL_H #include "Objeto.h" #include "Tipos.h" class Hotel: public Objeto{ TipoEntero Estrellas; TipoString Disponibilidad; public: Hotel(){}; Hotel(const TipoString& nombre, TipoCaracter color, TipoEntero posX, TipoEntero posY, const TipoString& Direccion, TipoEntero Calificacion, TipoEntero _Estrellas, const TipoString& _Disponibilidad); void mostrar_disponibilidad(); void mostrar_Estrellas(); }; #endif //PROYECTOFINALPOO_HOTEL_H
[ "majolive@Majos-MacBook.local" ]
majolive@Majos-MacBook.local
1df714f5e9b03db0725fd43fe075cb709a1c6143
804cc6764d90fdd7424fa435126c7fe581111562
/Kernel/VirtualAddress.h
57122725d55184b96097fb01a19522832086b317
[ "BSD-2-Clause" ]
permissive
NukeWilliams/prana-os
96abeed02f33f87c74dd066a5fa7b2d501cb2c62
c56c230d3001a48c342361733dc634a5afaf35f9
refs/heads/master
2023-06-17T18:39:22.394466
2021-07-02T13:37:47
2021-07-02T13:37:47
358,167,671
1
0
null
null
null
null
UTF-8
C++
false
false
2,003
h
#pragma once // includes #include <AK/Format.h> #include <AK/Types.h> class VirtualAddress { public: VirtualAddress() = default; explicit VirtualAddress(FlatPtr address) : m_address(address) { } explicit VirtualAddress(const void* address) : m_address((FlatPtr)address) { } [[nodiscard]] bool is_null() const { return m_address == 0; } [[nodiscard]] bool is_page_aligned() const { return (m_address & 0xfff) == 0; } [[nodiscard]] VirtualAddress offset(FlatPtr o) const { return VirtualAddress(m_address + o); } [[nodiscard]] FlatPtr get() const { return m_address; } void set(FlatPtr address) { m_address = address; } void mask(FlatPtr m) { m_address &= m; } bool operator<=(const VirtualAddress& other) const { return m_address <= other.m_address; } bool operator>=(const VirtualAddress& other) const { return m_address >= other.m_address; } bool operator>(const VirtualAddress& other) const { return m_address > other.m_address; } bool operator<(const VirtualAddress& other) const { return m_address < other.m_address; } bool operator==(const VirtualAddress& other) const { return m_address == other.m_address; } bool operator!=(const VirtualAddress& other) const { return m_address != other.m_address; } [[nodiscard]] u8* as_ptr() { return reinterpret_cast<u8*>(m_address); } [[nodiscard]] const u8* as_ptr() const { return reinterpret_cast<const u8*>(m_address); } [[nodiscard]] VirtualAddress page_base() const { return VirtualAddress(m_address & 0xfffff000); } private: FlatPtr m_address { 0 }; }; inline VirtualAddress operator-(const VirtualAddress& a, const VirtualAddress& b) { return VirtualAddress(a.get() - b.get()); } template<> struct AK::Formatter<VirtualAddress> : AK::Formatter<FormatString> { void format(FormatBuilder& builder, const VirtualAddress& value) { return AK::Formatter<FormatString>::format(builder, "V{}", value.as_ptr()); } };
[ "krisna.pranav@gmail.com" ]
krisna.pranav@gmail.com
f2afd57802bd976406a015be1e8703b72369111d
9506a40845f40f9f79e20ac87191c5b0d1ef6d7c
/practice/2000-2100/916B.cpp
355a05bd75470337b9329bb08babd90e22ac37b5
[]
no_license
anish-rajan/Cp-algos
9ab16374a154fe9598a49405d1a2b3bf10013320
9bcb7264769536cc4ff877a3b6d2f156fddee50a
refs/heads/master
2022-12-14T09:44:31.960833
2020-09-10T12:01:14
2020-09-10T12:01:14
265,180,210
2
0
null
null
null
null
UTF-8
C++
false
false
1,954
cpp
#include <iostream> #include <bits/stdc++.h> using namespace std; typedef long long int ll; typedef long double ld; #define mp make_pair #define v vector #define inp_push(no, v) \ ll no; \ cin >> no; \ v.push_back(no); #define pb push_back #define fi first #define se second #define ALL(v) v.begin(), v.end() #define UN(v) sort((v).begin(), (v).end()), v.erase(unique(v.begin(), v.end()), v.end()) #define N 6 #define mod 1000000007 #define INF INT_MAX ll n, k; multiset<ll> p; long long powmod(long long x, long long y, long long m) { long long res = 1LL; while (y) { if (y & 1) res = (res * x) % m; // cout << x << " " << mod << "\n"; x = (x * x) % m; y /= 2; } return res; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin >> n >> k; ll power = 0; while (n > 0) { if (n % 2) p.insert(power); n /= 2; power++; } if (k < p.size()) { cout << "No\n"; return 0; } ll nos = p.size(); while (nos < k) { auto itr = p.end(); itr--; auto temp = *itr; ll temp1 = p.count(temp); if (temp1 + nos <= k) { p.erase(temp); while (temp1) { p.insert(temp - 1); p.insert(temp - 1); nos++; temp1--; } } else break; } while (nos < k) { auto itr = p.begin(); auto temp = *itr; p.erase(itr); p.insert(temp - 1); p.insert(temp - 1); nos++; } cout << "Yes\n"; v<ll> ans; for (auto itr = p.begin(); itr != p.end(); itr++) ans.pb(*itr); reverse(ans.begin(), ans.end()); for (ll i = 0; i < ans.size(); i++) cout << ans[i] << " "; cout << "\n"; }
[ "anishrajan2000@gmail.com" ]
anishrajan2000@gmail.com
2b9a5661d67e823041a1edeaa9463a3de4d0dc87
5c0fcc93339330cab8408a58d26504a3154e808c
/Risk3D_Modelo/fin_del_juego.cpp
614666e816b3eb562e24707b12baf1bdefbe8131
[]
no_license
eritiro/risk3d
5d3d3b1d7510d809c34c1d69d20303c66fd31630
d8389acc79eb4f561123a09b8de1e13d7498b2c1
refs/heads/master
2021-01-10T20:54:41.709954
2015-03-06T17:37:27
2015-03-06T17:37:27
31,772,713
4
0
null
null
null
null
UTF-8
C++
false
false
751
cpp
#include "fin_del_juego.h" FinDelJuego::FinDelJuego() : EstadoDelJuego("Fin del juego"){ } void FinDelJuego::inicializar(Juego* juego){ juego->notificar_a_todos("El juego termino!"); Jugador* ganador = 0; foreach(IteradorJugadores, jugador, juego->get_jugadores()){ Objetivo* objetivo = (*jugador)->get_objetivo(); if(objetivo->fue_cumplido((*jugador)->get_imperio(), &juego->get_info())){ ganador = *jugador; } } if(ganador!=0){ juego->notificar_a_todos("El ganador es " + ganador->get_nombre_emperador() + "!!!"); foreach(IteradorJugadores, i, juego->get_jugadores()){ (*i)->recibir_mensaje(FabricaDeMensajes::crear_evento_juego_terminado(ganador->get_imperio(), ganador->get_objetivo())); } } }
[ "eritiro@gmail.com" ]
eritiro@gmail.com
7fa9c0f566e0acd208052ca314e2bdfd10e47d42
a5d7ef542268d9c76ddafcfd97fb494bff30ad61
/tMedia.h
bf0873c4df740735635b2dae30562de04cdb7fb2
[]
no_license
YannickR26/TV-Controller
d357762dcfe8b62f8e24aeaac5109f74a5f224e4
f63338b2256e59a40e930f3826ce04bafae5cf72
refs/heads/master
2020-05-02T16:25:28.670739
2019-03-27T20:13:41
2019-03-27T20:13:41
178,067,821
0
0
null
null
null
null
UTF-8
C++
false
false
4,810
h
#ifndef TMEDIA_H #define TMEDIA_H #include <stdio.h> #include <QTime> #include <qcolor.h> #include <QString> #include <QDomElement> #include <QDomDocument> class tMedia { public: tMedia() : fadeIn(0), fadeOut(0), repeat(0), login(""), password(""), time(), isModify(false) {} tMedia(QString _name) : name(_name), fadeIn(0), fadeOut(0), repeat(0), login(""), password(""), time(), isModify(false) {} tMedia(QString _name, QColor _color) : name(_name), fadeIn(0), fadeOut(0), repeat(0), login(""), password(""), color(_color), time(0,0,0,0), isModify(false) {} tMedia(QString _name, QString _url, QString _type, bool _fadeIn, bool _fadeOut, bool _repeat, QColor _color, QTime _time) : name(_name), url(_url), type(_type), fadeIn(_fadeIn), fadeOut(_fadeOut), repeat(_repeat), login(""), password(""), color(_color), time(_time), isModify(false) {} tMedia(QDomElement &node) { this->fromXml(node); this->isModify = false; } /** Set Attribut */ void setName(QString _name) { this->name = _name; this->isModify = true; } void setUrl(QString _url) { this->url = _url; this->isModify = true; } void setType(QString _type) { this->type = _type; this->isModify = true; } void setFadeIn(bool _fadeIn) { this->fadeIn = _fadeIn; this->isModify = true; } void setFadeOut(bool _fadeOut) { this->fadeOut = _fadeOut; this->isModify = true; } void setRepeat(bool _repeat) { this->repeat = _repeat; this->isModify = true; } void setLogin(QString _login) { this->login = _login; this->isModify = true; } void setPassword(QString _password) { this->password = _password; this->isModify = true; } void setColor(QColor _color) { this->color = _color; this->isModify = true; } void setTime(QTime _time) { this->time = _time; this->isModify = true; } /** Get Attribut */ QString getName() { return this->name; } QString getUrl() { return this->url; } QString getType() { return this->type; } bool getFadeIn() { return this->fadeIn; } bool getFadeOut() { return this->fadeOut; } bool getRepeat() { return this->repeat; } QString getLogin() { return this->login; } QString getPassword() { return this->password;} QColor getColor() { return this->color; } QTime getTime() { return this->time; } /** Convert Data to Xml */ void toXml(QDomDocument &parent, QDomElement &child) { QDomElement newChild = parent.createElement("Media"); newChild.setAttribute("name", this->name); newChild.setAttribute("url", this->url); newChild.setAttribute("type", this->type); newChild.setAttribute("fadeIn", this->fadeIn); newChild.setAttribute("fadeOut", this->fadeOut); newChild.setAttribute("repeat", this->repeat); newChild.setAttribute("login", this->login); newChild.setAttribute("password", this->password); newChild.setAttribute("color", this->color.name()); newChild.setAttribute("time", this->time.toString()); child.appendChild(newChild); } /** Convert Xml to Data */ void fromXml(QDomElement &node) { if (node.tagName() == "Media") { this->name = node.attribute("name"); this->url = node.attribute("url"); this->type = node.attribute("type"); this->fadeIn = (node.attribute("fadeIn") == "0" ? false : true); this->fadeOut = (node.attribute("fadeOut") == "0" ? false : true); this->repeat = (node.attribute("repeat") == "0" ? false : true); this->login = node.attribute("login"); this->password = node.attribute("password"); this->color = QColor(node.attribute("color")); this->time = QTime::fromString(node.attribute("time")); } } bool maybeSave() { return isModify; } void saveDone() { isModify = false; } /** Debug */ QString toString() { QString res; res = "tMedia => \t name: " + name + ",\n"; res += "\t\t url: " + url + ",\n"; res += "\t\t type: " + type + ",\n"; res += QString("\t\t fadeIn: %1,\n").arg(fadeIn); res += QString("\t\t fadeOut: %1,\n").arg(fadeOut); res += QString("\t\t repeat: %1,\n").arg(repeat); res += "\t\t login: " + login + ",\n"; res += "\t\t password: " + password + "\n"; return res; } virtual ~tMedia() {} protected: private: QString name; QString url; QString type; bool fadeIn, fadeOut, repeat; QString login, password; QColor color; QTime time; bool isModify; }; #endif // TMEDIA_H
[ "yannick.richardot@carbonbee.fr" ]
yannick.richardot@carbonbee.fr
f5bede511589d44ec0312b384067c41a466e69b5
746fc18c9e4bf3ee928d6db624750817e3b1454b
/practise/c_tracking_code/tracking_code/tracking_code/v5/5.6.cpp
438f3da5e3e2a02452263af682ed798dfc2ef442
[]
no_license
mingliang-99/c_practise
335117cacf13f3653f60547d4bf55104324a8812
d127926c2112fcf56cb4f1b8858bdaf8075894e1
refs/heads/master
2021-07-13T11:31:45.648945
2021-03-08T23:26:50
2021-03-08T23:26:50
241,883,142
0
0
null
null
null
null
UTF-8
C++
false
false
5,146
cpp
// // main.cpp // tracking_code // // Created by mingliang on 2021/2/17. // #include <iostream> #include <string> #include <vector> 题目 原文: Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree. Avoid storing additional nodes in a data structure. NOTE: This is not necessarily a binary search tree. 译文: 写程序在一棵二叉树中找到两个结点的第一个共同祖先。不允许存储额外的结点。注意: 这里不特指二叉查找树。 解答 本题的关键应当是在Avoid storing additional nodes in a data structure 这句话上。我的理解是,不允许开额外的空间(比如说一个数组)来存储作为中间变量的结点。 虽然我也怀疑它是不是说不允许在结点数据结构Node中加入额外的东西, 比如说父结点的指针。Anyway,我们先从最简单的入手,再一步步加入限制条件。 如果没有任何限制条件,那我觉得最直观的思路就是把其中一个点的所有祖先(包含它自身) 都放入一个哈希表,然后再一步步查找另一个点的祖先结点, 第一个在哈希表中出现的祖先结点即为题目所求。 Node* first_ancestor(Node* n1, Node* n2){ if(n1 == NULL || n2 == NULL) return NULL; map<Node*, bool> m; while(n1){ m[n1] = true; n1 = n1->parent; } while(n2 && !m[n2]){ n2 = n2->parent; } return n2; } 这里用了一个map来存储中间变量,如果题目不允许开额外的辅助空间,那该如何做呢? 那就老老实实地一个个地试。不断地取出其中一个结点的父结点, 然后判断这个结点是否也为另一个结点的父结点。代码如下 bool father(Node* n1, Node* n2){ if(n1 == NULL) return false; else if(n1 == n2) return true; else return father(n1->lchild, n2) || father(n1->rchild, n2); } Node* first_ancestor1(Node* n1, Node* n2){ if(n1 == NULL || n2 == NULL) return NULL; while(n1){ if(father(n1, n2)) return n1; n1 = n1->parent; } return NULL; } 让我们把条件再限制地严苛一些,如果数据结构Node中不允许有指向父亲结点的指针, 那么我们又该如何处理?其实也很简单,首先根结点一定为任意两个结点的共同祖先, 从根结点不断往下找,直到找到最后一个这两结点的共同祖先,即为题目所求。代码如下 void first_ancestor2(Node* head, Node* n1, Node* n2, Node* &ans){ if(head==NULL || n1==NULL || n2==NULL) return; if(head && father(head, n1) && father(head, n2)){ ans = head; first_ancestor2(head->lchild, n1, n2, ans); first_ancestor2(head->rchild, n1, n2, ans); } } 这里用到了递归,ans最终保存的是这两个结点从根结点算起最后找到的那个祖先。 因为从根结点开始,每次找到满足要求的结点,ans都会被更新 //全部代码 #include <iostream> #include <map> #include <cstring> using namespace std; const int maxn = 100; struct Node{ int key; Node *lchild, *rchild, *parent; }; Node *p, node[maxn]; int cnt; void init(){ p = NULL; memset(node, '\0', sizeof(node)); cnt = 0; } void create_minimal_tree(Node* &head, Node *parent, int a[], int start, int end){ if(start <= end){ int mid = (start + end)>>1; node[cnt].key = a[mid]; node[cnt].parent = parent; head = &node[cnt++]; create_minimal_tree(head->lchild, head, a, start, mid-1); create_minimal_tree(head->rchild, head, a, mid+1, end); } } Node* first_ancestor(Node* n1, Node* n2){ if(n1 == NULL || n2 == NULL) return NULL; map<Node*, bool> m; while(n1){ m[n1] = true; n1 = n1->parent; } while(n2 && !m[n2]){ n2 = n2->parent; } return n2; } bool father(Node* n1, Node* n2){ if(n1 == NULL) return false; else if(n1 == n2) return true; else return father(n1->lchild, n2) || father(n1->rchild, n2); } Node* first_ancestor1(Node* n1, Node* n2){ if(n1 == NULL || n2 == NULL) return NULL; while(n1){ if(father(n1, n2)) return n1; n1 = n1->parent; } return NULL; } void first_ancestor2(Node* head, Node* n1, Node* n2, Node* &ans){ if(head==NULL || n1==NULL || n2==NULL) return; if(head && father(head, n1) && father(head, n2)){ ans = head; first_ancestor2(head->lchild, n1, n2, ans); first_ancestor2(head->rchild, n1, n2, ans); } } Node* search(Node* head, int x){ if(head == NULL) return NULL; else if(x == head->key) return head; else if(x <= head->key) search(head->lchild, x); else search(head->rchild, x); } int main(){ init(); int a[] = { 0, 1, 2, 3, 4, 5, 6 }; Node *head = NULL; create_minimal_tree(head, NULL, a, 0, 6); Node *n1 = search(head, 0); Node *n2 = search(head, 4); cout<<n1->key<<" "<<n2->key<<endl; Node *ans = first_ancestor(n1, n2); cout<<ans->key<<endl; Node *ans1 = NULL; first_ancestor2(head, n1, n2, ans1); cout<<ans1->key<<endl; return 0; }
[ "mingliang8@staff.weibo.com" ]
mingliang8@staff.weibo.com
eca21f5f60ff7da49582b4b6edbb8fe437b94d7f
ede157880ced6297f1a1552b5bab9a36eea74542
/GMorpher/GMorpherBone_3DEMICP/src/Solver_EM_ceres.cpp
ea890e5bfd006c3fe5944ea93564b733fdec5730
[]
no_license
paulchhuang/GMorpherSkl
9f298395a0d4508c22dd7d73859a3d1790ebaa62
aa15ec5d1f6f984b779aebdec89f56c83dde51ee
refs/heads/master
2021-01-01T05:55:04.811394
2017-07-30T10:04:42
2017-07-30T10:04:42
97,305,897
6
2
null
null
null
null
UTF-8
C++
false
false
4,038
cpp
/* ************************************************* * Copyright (2016) : Paul Huang * *************************************************/ #include <Solver_EM_ceres.h> #include <GraphUtils.h> #include <numeric> //#define VERBOSE Solver_EMCeres::Solver_EMCeres(bool prediction, const SklRgedPatchedCloud::PatchedCloud& PC) { m_GSolver = new GMorpher::SolverCeres(PC.RT0(), PC.joint_coords0());// , sadj, sadj_bounds, jOffsp, jOffsp_bounds); if( prediction ) m_EICP = boost::shared_ptr<IEnergyTerm_EMCeres>( new EnergyTerm_EMPredCeres(10, PC) ); /*else m_EICP = boost::shared_ptr<IEnergyTerm_EMCeres>( new EnergyTerm_EMCeres(10, PC) ); */ } Solver_EMCeres::~Solver_EMCeres() { } void Solver_EMCeres::setRefMesh(SklRgedPatchedCloud::PatchedCloud& mesh){ m_EICP->reinit(mesh); } bool countMoversCeres( const std::vector<GMorpher::rigidT>& RT_old, const std::vector<GMorpher::rigidT>& RT_new, const double meanEdge ) { double thresh = 0.005*meanEdge*meanEdge; // we can evaluate how many centers have moved int numPatches = RT_old.size(); int numMovers = 0; std::vector<int> movers(numPatches); #pragma omp parallel for for(int pi=0;pi<numPatches;++pi) { GMorpher::float3 delta = RT_new[pi].m_t - RT_old[pi].m_t; if( dot(delta,delta) > thresh ) movers[pi]++; //if( dot(delta,delta) > thresh ) numMovers++; } // we can also evaluate how many center predictions have moved ? // TODO return std::accumulate(movers.begin(),movers.end(),0); } int Solver_EMCeres::solve(const std::list<GMorpher::EPtrCeres>& regularizationTerms, bool probabilistic, int maxIter_EM, int maxIter_M, int maxSubDiv, float meanEdge, float normThresh, float EOutlier, float alphaNN, const std::vector<CC3D::float3>& obs_cloud_coords, const std::vector<CC3D::float3>& obs_cloud_normals, std::vector<GMorpher::rigidT>& RT, std::vector<CC3D::float3>& JX, float& sigma, bool verbose) { int numPatches = m_GSolver->numPatches(); float* RTf = new float[12*numPatches]; std::list<GMorpher::EPtrCeres> energies = regularizationTerms; energies.push_back(m_EICP); std::vector<GMorpher::rigidT> RT_old = RT; std::vector<CC3D::float3> JX_old = JX; double sigmaStart = sigma; // set the data m_EICP->setFrameData( obs_cloud_coords, obs_cloud_normals); m_EICP->setAlpha( alphaNN ); int numIter_EM = 0; RigidTFlatten( RT, RTf ); bool stop_flag = false; std::vector<int> isValid_patch(numPatches, 1); while ( numIter_EM++ < maxIter_EM) { // E - Step if( !probabilistic ) { m_EICP->EStep( sigmaStart, normThresh, EOutlier, RTf ); m_EICP->EStep_makeDeterministicAssignment(); // if we are using a non-probabilistic approach } else { m_EICP->EStep( sigma, normThresh, EOutlier, RTf ); } // M - Step if (verbose) std::cout << "# EM_iter.: " << numIter_EM << " "; m_GSolver->solve(maxIter_M, energies, RT, JX, verbose); // re-evaluate sigma RigidTFlatten( RT, RTf ); sigma = m_EICP->reEvaluateSigma( RTf ); // check for convergence int numMoved = countMoversCeres(RT_old, RT, meanEdge); #ifdef VERBOSE std::cout<<"sigma "<<sigma/meanEdge<<" and movers "<<numMoved<<std::endl; #endif; if( numMoved == 0 ) break; RT_old = RT; JX_old = JX; } delete[] RTf; return ((numIter_EM > maxIter_EM) ? (numIter_EM-1) : numIter_EM); }
[ "Paul Huang" ]
Paul Huang
1255fc673e4116d022393be60a2b51eaf16ca430
24f26275ffcd9324998d7570ea9fda82578eeb9e
/ui/views/test/test_desktop_screen_x11.h
ea16fe752e2d528be58492aec43bc17977de066c
[ "BSD-3-Clause" ]
permissive
Vizionnation/chromenohistory
70a51193c8538d7b995000a1b2a654e70603040f
146feeb85985a6835f4b8826ad67be9195455402
refs/heads/master
2022-12-15T07:02:54.461083
2019-10-25T15:07:06
2019-10-25T15:07:06
217,557,501
2
1
BSD-3-Clause
2022-11-19T06:53:07
2019-10-25T14:58:54
null
UTF-8
C++
false
false
1,380
h
// Copyright 2016 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 UI_VIEWS_TEST_TEST_DESKTOP_SCREEN_X11_H_ #define UI_VIEWS_TEST_TEST_DESKTOP_SCREEN_X11_H_ #include "ui/gfx/geometry/point.h" #include "ui/views/widget/desktop_aura/desktop_screen_x11.h" namespace base { template<typename T> struct DefaultSingletonTraits; } namespace views { namespace test { // Replaces the screen instance in Linux (non-ChromeOS) tests. Allows // aura tests to manually set the cursor screen point to be reported // by GetCursorScreenPoint(). Needed because of a limitation in the // X11 protocol that restricts us from warping the pointer with the // mouse button held down. class TestDesktopScreenX11 : public DesktopScreenX11 { public: static TestDesktopScreenX11* GetInstance(); // DesktopScreenX11: gfx::Point GetCursorScreenPoint() override; void set_cursor_screen_point(const gfx::Point& point) { cursor_screen_point_ = point; } private: friend struct base::DefaultSingletonTraits<TestDesktopScreenX11>; TestDesktopScreenX11(); ~TestDesktopScreenX11() override; gfx::Point cursor_screen_point_; DISALLOW_COPY_AND_ASSIGN(TestDesktopScreenX11); }; } // namespace test } // namespace views #endif // UI_VIEWS_TEST_TEST_DESKTOP_SCREEN_X11_H_
[ "rjkroege@chromium.org" ]
rjkroege@chromium.org
9b203fe82f80ee1a537e080f89b4924ff0e48b1f
1da4c6fb453aa52689f83d54a24f46467b9875d3
/codevs2.0_practice/game.h
08bf8298e15122b526a627a3961151adc5870189
[]
no_license
tek1031/CODEVS2.0
d113b98d0acde3df7fe9d89e90b7bdce1f16f527
a2b611b59fff132af8314a1b1a9e1058648ce6cc
refs/heads/master
2020-04-11T01:29:28.027108
2013-01-23T14:16:00
2013-01-23T14:16:00
7,775,241
0
1
null
null
null
null
SHIFT_JIS
C++
false
false
2,302
h
#include"state.h" #pragma once /* ゲーム全体の情報を持っておく パックの情報,今の状態 連鎖などの計算をここで行う */ class Game{ int packs[1000][4][MAX_T][MAX_T];//パックの中身 もらったら 事前に全部回転させたのも計算しちゃう int packs_enemy[1000][4][MAX_T][MAX_T]; int turn; State now_state;//現在のState State state_enemy; int my_stock_garbage,enemy_stock_garbage; void input_pack(); bool check_inside(const State &state,const int &x,const int &r)const; bool check_over(const State &state,const int h)const; void push_pack(State &state,const int &x,const int &r)const; void drop_block(State &state,int change_info[][2][MAX_W+MAX_H+MAX_T],bool is_drop[MAX_W])const;//ブロックを全て下まで落とす int erase(State &state,int change_info[][2][MAX_W+MAX_H+MAX_T],bool is_drop[MAX_W])const; int erase_vertically(State &state,bool is_erased[MAX_H][MAX_W],int change_info[2][MAX_W+MAX_H+MAX_T],int change_pos[2][MAX_H])const; int erase_horizontally(State &state,bool is_erased[MAX_H][MAX_W],int change_info[2][MAX_W+MAX_H+MAX_T],int change_pos[2][MAX_H])const; int erase_right_down(State &state,bool is_erased[MAX_H][MAX_W],int change_info[2][MAX_W+MAX_H+MAX_T],int change_pos[2][MAX_H])const; int erase_left_down(State &state,bool is_erased[MAX_H][MAX_W],int change_info[2][MAX_W+MAX_H+MAX_T],int change_pos[2][MAX_H])const; long long int calc_point(int C,int turn,int E)const; int calc_garbage_block_point(const int &C,const int &E)const{ return C*(int)(log((double)E)/(log((double)2))); } bool is_attacked();//攻撃されたらtrueが返る public: const int H,W,N,T,S,P; void output(const State &state); void output(int x,int r); bool input_pack_changed(); int update_enemy_state(); void input_stock_garbage(); bool is_fatal_attacked();//やばい攻撃 State get_state()const{return now_state;} Game(int W,int H,int T,int S,int N,int P):N(N),H(H),W(W),T(T),S(S),P(P),turn(0){ input_pack(); now_state=State(); } void get_pack(const int &idx,const int &rotation,int res[][MAX_T])const{ memcpy(res,packs[idx][rotation],sizeof(packs[idx][rotation])); } pair<int,long long int> update(State &state,const int x,const int r,const int h)const; int get_turn()const{return turn;} };
[ "komatsutomoki1031@gmail.com" ]
komatsutomoki1031@gmail.com
046c23185c9ae9491d5205d60ff22d4772cc29a2
10f08f6430eee2daefd310bffe71d7740abf1a97
/Matrix.hpp
9e584ba1ad8cbe237efcec586702c1931a4a2ab6
[]
no_license
nkt/cpp-matrix
9908c80642255fa473df5e75e78b896d590ae26e
6fdfaac73394a1ed972268327b6fc2ea84e35fe2
refs/heads/master
2021-01-01T19:15:23.460567
2014-05-27T03:52:48
2014-05-27T03:52:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,586
hpp
#ifndef __Matrix_H_ #define __Matrix_H_ #include <iostream> template<typename T, typename K = double> class Matrix { protected: T **matrix; size_t n; size_t m; inline void checkIndexes(size_t i, size_t j) const { if (i > n || j > m) { throw new std::runtime_error("The indexes is outside the valid range"); } } inline void checkEqualSizes(const Matrix &arg) const { if (arg.n != n || arg.m != m) { throw new std::runtime_error("The matrix sizes not equals"); } } public: Matrix(size_t n, size_t m) : n(n), m(m) { matrix = new T *[n]; for (size_t i = 0; i < n; ++i) { matrix[i] = new T[m]; } } Matrix(const Matrix &arg) : Matrix(arg.n, arg.m) { for (size_t i = 0; i < n; ++i) { for (size_t j = 0; j < m; ++j) { matrix[i][j] = arg.matrix[i][j]; } } } void set(size_t i, size_t j, const T value) { checkIndexes(i, j); matrix[i][j] = value; } T get(size_t i, size_t j) const { checkIndexes(i, j); return matrix[i][j]; } Matrix operator+(const Matrix &arg) const { checkEqualSizes(arg); Matrix<T, K> result(n, m); for (size_t i = 0; i < n; ++i) { for (size_t j = 0; j < m; ++j) { result.matrix[i][j] = matrix[i][j] + arg.matrix[i][j]; } } return result; } Matrix operator*(const K &num) const { Matrix<T, K> result(n, m); for (size_t i = 0; i < n; ++i) { for (size_t j = 0; j < m; ++j) { result.matrix[i][j] = matrix[i][j] * num; } } return result; } Matrix operator-(const Matrix &arg) const { return (arg * -1) + *this; } Matrix operator*(const Matrix &arg) const { Matrix<T, K> result(n, m); for (size_t i = 0; i < n; ++i) { for (size_t j = 0; j < arg.m; ++j) { for (size_t k = 0; k < m; ++k) { result.matrix[i][j] = matrix[i][k] * arg.matrix[k][j]; } } } return result; } friend std::ostream &operator<<(std::ostream &output, Matrix &arg) { for (size_t i = 0; i < arg.n; ++i) { for (size_t j = 0; j < arg.m; ++j) { output << arg.matrix[i][j] << " "; } output << std::endl; } return output; } }; #endif
[ "dev@nkt.me" ]
dev@nkt.me
ba3063886d4f69020cafa2e0bc5ffd15d51ea95b
e5a694673d2fb4272569acbb0d207d15a9a539e5
/src/ch03/printer.cpp
092b9cb58a59354bc025d263a055dbe566234b5b
[ "MIT" ]
permissive
zhuangbo/ds-cpp
c0e2f4a6d42048fb65d4aef44bd338e2076d6170
bac398636979458802a7fb8d433462e88dc2ed15
refs/heads/master
2021-01-19T16:42:58.544038
2017-10-28T16:19:42
2017-10-28T16:19:42
101,020,871
1
0
null
null
null
null
UTF-8
C++
false
false
865
cpp
/////////////////////////////////////// /// file: printer.cpp /// 操作系统打印排队模拟 /////////////////////////////////////// #include <iostream> #include "sqqueue.h" using namespace std; /// 打印作业 struct Task { int id; int pages; }; /// 打印 void Print(const Task &job) { cout << "#" << job.id << "(" << job.pages << ")"; for (int i = 0; i < job.pages; i++) cout << "../"; cout << endl; } /// /// 模拟打印队列 /// int main() { // 初始化打印队列 SqQueue<Task, 10> Q; InitQueue(Q); // 多个打印任务进入队列 EnQueue(Q, Task{1, 5}); EnQueue(Q, Task{2, 3}); EnQueue(Q, Task{3, 8}); EnQueue(Q, Task{4, 2}); EnQueue(Q, Task{5, 4}); // 开始打印 while (!QueueEmpty(Q)) { auto job = DeQueue(Q); Print(job); } return 0; }
[ "sdzhuangbo@126.com" ]
sdzhuangbo@126.com
bc9c3d2e029ce6961574cf95a6da8299d4a329cd
7fa23b0e02e16ba51433353d409000ed91442225
/TestHarness.cpp
0f0dac71278b31347cbe9d1cf587256a17490e3c
[ "Apache-2.0" ]
permissive
orb1t-ua/WindowingSystem
272fc95ccaf897e82567fd5842537f1b21b2193a
34d24ab6f4531df4d1ec335fd0f14dcf2bf52b99
refs/heads/master
2022-01-28T13:23:06.171735
2019-01-07T07:17:49
2019-01-07T07:17:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
22,774
cpp
// // Copyright 1999-2002 Jeff Bush // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // // Simulate a mouse driver, keyboard driver, and raw frame buffer. // #include <winsock2.h> #include "Rasterizer24bpp.h" #include "MemorySurface.h" #include "Surface.h" #include "Screen.h" #include "debug.h" #include "stdafx.h" #include "resource.h" #include "input.h" #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <windows.h> #define SHOW_DEBUG_WINDOW 0 #define CLIENT_TEST 1 #define MAX_CURSOR_WIDTH 32 #define MAX_CURSOR_HEIGHT 32 #define VIRTUAL_SCREEN_WIDTH 640 #define VIRTUAL_SCREEN_HEIGHT 480 #define INPUT_WINDOW_HEIGHT 20 #define FRAME_BUFFER_WINDOW_CLASS "FrameBufferWindow" #define DEBUG_WINDOW_CLASS "DebugWindow" #define MAX_DEBUG_ARGS 15 #define MAX_DEBUG_COMMANDS 32 #define DO_COMMAND (WM_USER + 2) class VirtualFrameBuffer : public Screen { public: VirtualFrameBuffer(HDC dc); void buildCursorData(HINSTANCE instance, HDC dc); void repaint(HWND hWnd); virtual void endTransaction(); virtual void* lockBits(); virtual void unlockBits(); virtual int getStride() const; virtual Rasterizer *createRasterizer(); virtual void setCursorPosition(int x, int y); virtual void setCursorShape(int width, int height, const char *colorBits, const char *maskBits); private: void eraseCursor(); void drawCursor(); HBITMAP fScreenBitmap; int fLockCount; int fCursorX; int fCursorY; void *fSavedBackground; int fCursorWidth; int fCursorHeight; char *fCursorMask; char *fCursorColor; bool fDirty; }; class ResourceBitmap : public MemorySurface { public: ResourceBitmap(HINSTANCE instance, HDC dc, LPCTSTR bitmap, int width, int height); }; struct InputEvent { InputEvent *next; enum NativeEventType type; int x; int y; bool lButtonDown; bool rButtonDown; int scanCode; }; struct DebugCommand { const char *name; void (*callback)(int argc, const char **argv); }; extern void clientMain(); extern int wsmain(); extern DWORD WINAPI ProtocolWorker(LPVOID param); static LRESULT CALLBACK FrameBufferWndProc(HWND, UINT, WPARAM, LPARAM); static LRESULT CALLBACK DebugWindowWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); static LRESULT CALLBACK CommandOverrideWinProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); static BOOL RegisterWindowClass(const char *name, WNDPROC, HINSTANCE, bool background); static void EnqueueInputEvent(NativeEventType type, int x, int y, int scancode); static InputEvent *DequeueInputEvent(); static void ExecuteCommand(const char *command); static void showCommands(int argc, const char **argv); static DWORD WINAPI ServerStartFunc(LPVOID param); static DWORD WINAPI ClientStartFunc(LPVOID param); static void buildCursorData(HINSTANCE instance, HDC dc, Screen *screen); static VirtualFrameBuffer *screen; static char *virtualScreenBuffer; static HWND hFrameWindow; static HWND hLogWindow; static HWND hCommandWindow; static InputEvent *inputQueueHead = NULL; static InputEvent *inputQueueTail = NULL; static CRITICAL_SECTION inputQueueLock; static CRITICAL_SECTION bigLock; static HANDLE inputQueueWait; static bool lButtonDown = false; static bool rButtonDown = false; static WNDPROC oldCommandWndProc; // original wndproc for the command line static HWND debugWindow; static DebugCommand debugCommands[MAX_DEBUG_COMMANDS]; static Surface *bitmap; int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { MSG msg; HDC dc; WSADATA wsaData; int ret; // Initialize socket layer ret = WSAStartup(MAKEWORD(2, 2), &wsaData); if (ret != 0) { _asm { int 3 } return 0; } // Set up frame buffer if (!RegisterWindowClass(FRAME_BUFFER_WINDOW_CLASS, (WNDPROC) FrameBufferWndProc, hInstance, false)) return FALSE; #if SHOW_DEBUG_WINDOW if (!RegisterWindowClass(DEBUG_WINDOW_CLASS, (WNDPROC) DebugWindowWndProc, hInstance, true)) return FALSE; // Create the debug window debugWindow = CreateWindow(DEBUG_WINDOW_CLASS, "Debug Console", WS_OVERLAPPEDWINDOW, 280, 180, 650, 500, NULL, NULL, hInstance, NULL); if (!debugWindow) return FALSE; // Create the frame buffer window hFrameWindow = CreateWindow(FRAME_BUFFER_WINDOW_CLASS, "Frame Buffer", WS_OVERLAPPED, 10, 10, VIRTUAL_SCREEN_WIDTH + 6, VIRTUAL_SCREEN_HEIGHT + MAX_CURSOR_HEIGHT, NULL, NULL, hInstance, NULL); if (!hFrameWindow) return FALSE; #else // Create the frame buffer window hFrameWindow = CreateWindow(FRAME_BUFFER_WINDOW_CLASS, "Frame Buffer", WS_OVERLAPPED | WS_SYSMENU, 10, 10, VIRTUAL_SCREEN_WIDTH + 6, VIRTUAL_SCREEN_HEIGHT + MAX_CURSOR_HEIGHT, NULL, NULL, hInstance, NULL); if (!hFrameWindow) return FALSE; #endif // Create a backing store for the virtual screen dc = GetDC(hFrameWindow); if (dc == NULL) return FALSE; screen = new VirtualFrameBuffer(dc); screen->buildCursorData(hInstance, dc); ShowWindow(hFrameWindow, nCmdShow); UpdateWindow(hFrameWindow); ShowCursor(FALSE); #if SHOW_DEBUG_WINDOW ShowWindow(debugWindow, nCmdShow); UpdateWindow(debugWindow); #endif bitmap = new ResourceBitmap(hInstance, dc, MAKEINTRESOURCE(IDB_BITMAP1), 48, 48); addDebugCommand("help", showCommands); // Initialize virtual input system inputQueueWait = CreateSemaphore(NULL, 0, 0x7fffffff, NULL); InitializeCriticalSection(&inputQueueLock); InitializeCriticalSection(&bigLock); // Start main thread CloseHandle(CreateThread(NULL, 8192, ServerStartFunc, NULL, 0, NULL)); #if CLIENT_TEST Sleep(1000); // Wait for server to initialize CloseHandle(CreateThread(NULL, 8192, ClientStartFunc, NULL, 0, NULL)); #endif while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return msg.wParam; } Screen *getScreen() { return screen; } Surface *getBitmap() { return bitmap; } bool getNextInputEvent(NativeEventType *outType, int *outParam1, int *outParam2, int *outParam3, bool wait) { InputEvent *event; if (wait) WaitForSingleObject(inputQueueWait, INFINITE); EnterCriticalSection(&inputQueueLock); event = inputQueueHead; if (event != NULL) { inputQueueHead = inputQueueHead->next; if (inputQueueHead == NULL) inputQueueTail = NULL; } LeaveCriticalSection(&inputQueueLock); if (event != NULL) { *outType = event->type; switch (event->type) { case MOUSE_MOVE: *outParam1 = event->x; *outParam2 = event->y; break; case MOUSE_BUTTON: *outParam1 = event->x; *outParam2 = event->y; *outParam3 = (event->lButtonDown ? 1 : 0) | (event->rButtonDown ? 2 : 0); break; case KEY_DOWN: *outParam1 = event->scanCode; break; case KEY_UP: *outParam1 = event->scanCode; break; } free(event); return true; } return false; } void addDebugCommand(const char *name, void (*callback)(int argc, const char **argv)) { for (int i = 0; i < MAX_DEBUG_COMMANDS; i++) { if (debugCommands[i].name == NULL) { debugCommands[i].name = name; debugCommands[i].callback = callback; break; } } } void lprintf(const char *message, ...) { #if SHOW_DEBUG_WINDOW char formatted[1024]; va_list args; va_start(args, message); vsprintf(formatted, message, args); va_end(args); SendMessage(hLogWindow, EM_SETSEL, 0x7fffffff, 0x7fffffff); SendMessage(hLogWindow, EM_REPLACESEL, 0, (LPARAM) formatted); SendMessage(hLogWindow, EM_LINESCROLL, 0, 1); #endif } static LRESULT CALLBACK FrameBufferWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_PAINT: screen->repaint(hWnd); break; case WM_DESTROY: PostQuitMessage(0); break; case WM_MOUSEMOVE: EnqueueInputEvent(MOUSE_MOVE, lParam & 0xffff, lParam >> 16, -1); break; case WM_LBUTTONDOWN: lButtonDown = true; EnqueueInputEvent(MOUSE_BUTTON, lParam & 0xffff, lParam >> 16, -1); break; case WM_LBUTTONUP: lButtonDown = false; EnqueueInputEvent(MOUSE_BUTTON, lParam & 0xffff, lParam >> 16, -1); break; case WM_RBUTTONDOWN: rButtonDown = true; EnqueueInputEvent(MOUSE_BUTTON, lParam & 0xffff, lParam >> 16, -1); break; case WM_RBUTTONUP: rButtonDown = false; EnqueueInputEvent(MOUSE_BUTTON, lParam & 0xffff, lParam >> 16, -1); break; case WM_KEYUP: EnqueueInputEvent(KEY_UP, -1, -1, wParam); break; case WM_KEYDOWN: EnqueueInputEvent(KEY_DOWN, -1, -1, wParam); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } static LRESULT CALLBACK DebugWindowWndProc(HWND hwnd, // window handle UINT message, // type of message WPARAM wParam, // additional information LPARAM lParam) // additional information { char commandBuf[128]; switch (message) { case WM_CREATE: // The log window displays output hLogWindow = CreateWindow("EDIT", // predefined class NULL, // no window title WS_CHILD | WS_VISIBLE | WS_VSCROLL | ES_LEFT | ES_MULTILINE | ES_AUTOVSCROLL, 0, 0, 0, 0, // set size in WM_SIZE message hwnd, // parent window (HMENU) NULL, // edit control ID (HINSTANCE) GetWindowLong(hwnd, GWL_HINSTANCE), NULL); // pointer not needed SendMessage(hLogWindow, EM_SETREADONLY, TRUE, 0); // A command line at the bottom accepts commands hCommandWindow = CreateWindow("EDIT", // predefined class NULL, // no window title WS_CHILD | WS_VISIBLE | ES_LEFT, 0, 0, 0, 0, // set size in WM_SIZE message hwnd, // parent window (HMENU) NULL, // edit control ID (HINSTANCE) GetWindowLong(hwnd, GWL_HINSTANCE), NULL); // pointer not needed // Need to override window proc to intercept return key oldCommandWndProc = (WNDPROC) SetWindowLong(hCommandWindow, GWL_WNDPROC, (DWORD) CommandOverrideWinProc); return 0; case WM_SETFOCUS: SetFocus(hCommandWindow); return 0; case WM_SIZE: MoveWindow(hLogWindow, 0, 0, // starting x- and y-coordinates LOWORD(lParam), // width of client area HIWORD(lParam) - INPUT_WINDOW_HEIGHT, // height of client area TRUE); // repaint window MoveWindow(hCommandWindow, 0, HIWORD(lParam) - INPUT_WINDOW_HEIGHT, // starting x- and y-coordinates LOWORD(lParam), // width of client area INPUT_WINDOW_HEIGHT, // height of client area TRUE); // repaint window return 0; case WM_DESTROY: PostQuitMessage(0); return 0; case DO_COMMAND: SendMessage(hCommandWindow, WM_GETTEXT, (WPARAM) sizeof(commandBuf), (LPARAM)commandBuf); SendMessage(hCommandWindow, WM_SETTEXT, 0, (LPARAM) ""); ExecuteCommand(commandBuf); break; default: return DefWindowProc(hwnd, message, wParam, lParam); } return NULL; } LRESULT CALLBACK CommandOverrideWinProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_KEYDOWN: switch (wParam) { case VK_RETURN: // Bounce this message to the parent window SendMessage(debugWindow, DO_COMMAND, 0, 0); return 0; } break; case WM_KEYUP: case WM_CHAR: switch (wParam) { case VK_RETURN: return 0; } } // Call the original window procedure for default processing. return CallWindowProc(oldCommandWndProc, hwnd, msg, wParam, lParam); } static BOOL RegisterWindowClass(const char *name, WNDPROC wndProc, HINSTANCE instance, bool background) { WNDCLASSEX wcex; // Create a class for the frame buffer window wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = wndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = instance; wcex.hIcon = LoadIcon(instance, (LPCTSTR)IDI_WINDOWSERVER); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); if (background) wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); else wcex.hbrBackground = NULL; wcex.lpszMenuName = (LPCSTR)NULL; wcex.lpszClassName = name; wcex.hIconSm = LoadIcon(wcex.hInstance, (LPCTSTR)IDI_SMALL); return RegisterClassEx(&wcex); } void acquireBigLock() { EnterCriticalSection(&bigLock); } void releaseBigLock() { screen->endTransaction(); // avoid a bunch of spurious updates LeaveCriticalSection(&bigLock); } static void EnqueueInputEvent(NativeEventType type, int x, int y, int scanCode) { InputEvent *event = NULL; int length; EnterCriticalSection(&inputQueueLock); if (type == MOUSE_MOVE) { length = 0; for (event = inputQueueHead; event != NULL; event = event->next) { length++; if (event->type == MOUSE_MOVED) { // Already a mouse moved event queued, just update it event->x = x; event->y = y; break; } } } if (event == NULL) { // Couldn't find an existing event to merge this // with, create a new one event = (InputEvent*) malloc(sizeof(InputEvent)); event->type = type; event->x = x; event->y = y; event->lButtonDown = lButtonDown; event->rButtonDown = rButtonDown; event->scanCode = scanCode; event->next = NULL; if (inputQueueHead == NULL) inputQueueHead = inputQueueTail = event; else { inputQueueTail->next = event; inputQueueTail = event; } } LeaveCriticalSection(&inputQueueLock); ReleaseSemaphore(inputQueueWait, 1, NULL); } static void ExecuteCommand(const char *command) { char tmp[1024]; const char *argv[MAX_DEBUG_ARGS]; int argCount = 0; char *c; int i; if (strlen(command) > sizeof(tmp)) { lprintf("command too long\n"); return; } strcpy(tmp, command); c = tmp; for (;;) { /* Skip to non-space character */ while (isspace(*c)) c++; if (*c == '\0') break; argv[argCount++] = c; /* Skip to space character */ while (!isspace(*c)) { if (*c == '\0') goto done; c++; } *c++ = '\0'; /* Terminate this entry, proceed to next */ } done: if (argCount == 0) return; for (i = 0; i < MAX_DEBUG_COMMANDS; i++) { if (debugCommands[i].name == NULL) break; if (strcmp(debugCommands[i].name, argv[0]) == 0) { debugCommands[i].callback(argCount, argv); break; } } if (i == MAX_DEBUG_COMMANDS) lprintf("Unknown command %s", argv[0]); } static void showCommands(int argc, const char **argv) { lprintf("Available commands:\n"); for (int i = 0; i < MAX_DEBUG_COMMANDS; i++) { if (debugCommands[i].name == NULL) break; lprintf(" %s\n", debugCommands[i].name); } } static DWORD WINAPI ServerStartFunc(LPVOID param) { wsmain(); lprintf("wsmain has exited\n"); return 0; } static DWORD WINAPI ClientStartFunc(LPVOID param) { clientMain(); lprintf("client main has exited\n"); return 0; } VirtualFrameBuffer::VirtualFrameBuffer(HDC dc) : Screen(Surface::kRGB24, VIRTUAL_SCREEN_WIDTH, VIRTUAL_SCREEN_HEIGHT), fCursorX(VIRTUAL_SCREEN_WIDTH / 2 - 16), fCursorY(VIRTUAL_SCREEN_HEIGHT / 2 - 16), fLockCount(0), fSavedBackground(NULL), fCursorColor(NULL), fCursorMask(NULL), fDirty(false) { BITMAPINFO info; info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); info.bmiHeader.biWidth = VIRTUAL_SCREEN_WIDTH + MAX_CURSOR_WIDTH; // Add 32 pixels for cursor info.bmiHeader.biHeight = -(VIRTUAL_SCREEN_HEIGHT + MAX_CURSOR_HEIGHT); // negative to make top down info.bmiHeader.biPlanes = 1; // Must be one info.bmiHeader.biBitCount = 24; info.bmiHeader.biCompression = BI_RGB; info.bmiHeader.biSizeImage = 0; // Must be zero for BI_RGB bitmaps info.bmiHeader.biXPelsPerMeter = 1024 * 3; info.bmiHeader.biYPelsPerMeter = 768 * 4; info.bmiHeader.biClrUsed = 0; // Use maximum number of colors info.bmiHeader.biClrImportant = 0; // All colors are required fScreenBitmap = CreateDIBSection(dc, &info, DIB_RGB_COLORS, (void**) &virtualScreenBuffer, NULL, 0); } void* VirtualFrameBuffer::lockBits() { if (!fDirty) { eraseCursor(); fDirty = true; } return virtualScreenBuffer; } void VirtualFrameBuffer::unlockBits() { } void VirtualFrameBuffer::endTransaction() { if (fDirty) { fDirty = false; drawCursor(); RedrawWindow(hFrameWindow, NULL, NULL, RDW_INVALIDATE); } } int VirtualFrameBuffer::getStride() const { return (VIRTUAL_SCREEN_WIDTH + MAX_CURSOR_WIDTH) * 3; } Rasterizer *VirtualFrameBuffer::createRasterizer() { return new Rasterizer24bpp(this); } void VirtualFrameBuffer::setCursorPosition(int x, int y) { RECT dirtyRect; eraseCursor(); if (x < 0) x = 0; else if (x >= VIRTUAL_SCREEN_WIDTH - 1) x = VIRTUAL_SCREEN_WIDTH - 1; if (y < 0) y = 0; else if (y >= VIRTUAL_SCREEN_HEIGHT - 1) y = VIRTUAL_SCREEN_HEIGHT - 1; dirtyRect.left = min(fCursorX, x); dirtyRect.right = max(fCursorX + MAX_CURSOR_WIDTH, x + MAX_CURSOR_WIDTH); dirtyRect.top = min(fCursorY, y); dirtyRect.bottom = max(fCursorY + MAX_CURSOR_HEIGHT, y + MAX_CURSOR_HEIGHT); fCursorX = x; fCursorY = y; drawCursor(); RedrawWindow(hFrameWindow, &dirtyRect, NULL, RDW_INVALIDATE); } void VirtualFrameBuffer::setCursorShape(int width, int height, const char *colorBits, const char *maskBits) { if (fCursorColor != NULL) eraseCursor(); fCursorWidth = width; fCursorHeight = height; free(fSavedBackground); free(fCursorColor); free(fCursorMask); fSavedBackground = malloc(width * 3 * height); fCursorColor = (char*) malloc(width / 8 * height); fCursorMask = (char*) malloc(width / 8 * height); memcpy(fCursorColor, colorBits, width / 8 * height); memcpy(fCursorMask, maskBits, width / 8 * height); drawCursor(); } void VirtualFrameBuffer::eraseCursor() { // Restore what was originally behind the cursor char *destPtr = virtualScreenBuffer + fCursorX * 3 + fCursorY * ((VIRTUAL_SCREEN_WIDTH + MAX_CURSOR_WIDTH) * 3); char *srcPtr = (char*) fSavedBackground; int screenSkip = (VIRTUAL_SCREEN_WIDTH + MAX_CURSOR_WIDTH) * 3; int cursorSkip = fCursorWidth * 3; for (int y = 0; y < MAX_CURSOR_WIDTH; y++) { memcpy(destPtr, srcPtr, fCursorWidth * 3); destPtr += screenSkip; srcPtr += cursorSkip; } } void VirtualFrameBuffer::drawCursor() { if (fCursorColor == NULL) return; char *screenPtr = virtualScreenBuffer + fCursorX * 3 + fCursorY * ((VIRTUAL_SCREEN_WIDTH + MAX_CURSOR_WIDTH) * 3); char *backgroundPtr = (char*) fSavedBackground; int cursorByteWidth = fCursorWidth * 3; int skip = (VIRTUAL_SCREEN_WIDTH + MAX_CURSOR_WIDTH - fCursorWidth) * 3; int cursorOffset = 0; int cursorMask = 0x80; for (int y = 0; y < fCursorWidth; y++) { // Save what is behind the cursor memcpy(backgroundPtr, screenPtr, cursorByteWidth); backgroundPtr += cursorByteWidth; // Draw the cursor for (int x = 0; x < fCursorWidth; x++) { if (fCursorMask[cursorOffset] & cursorMask) { if (fCursorColor[cursorOffset] & cursorMask) { *screenPtr++ = 0xff; *screenPtr++ = 0xff; *screenPtr++ = 0xff; } else { *screenPtr++ = 0; *screenPtr++ = 0; *screenPtr++ = 0; } } else screenPtr += 3; cursorMask >>= 1; if (cursorMask == 0) { cursorOffset++; cursorMask = 0x80; } } screenPtr += skip; } } void VirtualFrameBuffer::buildCursorData(HINSTANCE instance, HDC dc) { HBITMAP bm = LoadBitmap(instance, MAKEINTRESOURCE(IDB_BITMAP2)); BITMAPINFO info; const unsigned char *cursorPtr; if (bm == NULL) { printf("error loading bitmap\n"); return; } int width = 32; int height = 32; void *bits = malloc(width * 3 * height); memset(bits, 0, width * 3 * height); info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); info.bmiHeader.biWidth = width; info.bmiHeader.biHeight = -height; // negative to make top down info.bmiHeader.biPlanes = 1; // Must be one info.bmiHeader.biBitCount = 24; info.bmiHeader.biCompression = BI_RGB; info.bmiHeader.biSizeImage = 0; // Must be zero for BI_RGB bitmaps info.bmiHeader.biXPelsPerMeter = 1024 * 3; info.bmiHeader.biYPelsPerMeter = 768 * 4; info.bmiHeader.biClrUsed = 0; // Use maximum number of colors info.bmiHeader.biClrImportant = 0; // All colors are required if (GetDIBits(dc, bm, 0, height, bits, &info, DIB_RGB_COLORS) != height) { printf("Error getting DI bits\n"); return; } // Convert bitmap data to cursor data char *maskData = (char*) malloc(width / 8 * height); char *colorData = (char*) malloc(width / 8 * height); memset(maskData, 0, width / 8 * height); memset(colorData, 0, width / 8 * height); cursorPtr = (const unsigned char*) bits; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { // If this pixel is black, mark it transparent if (cursorPtr[0] != 0 || cursorPtr[1] != 0 || cursorPtr[2] != 0) maskData[x / 8 + y * width / 8] |= (0x80 >> x % 8); // if this pixel is white, mark it so, otherwise make it black // (black pixels in the final cursor are represented in this image // as dark gray). if (cursorPtr[0] == 0xff && cursorPtr[1] == 0xff && cursorPtr[2] == 0xff) colorData[x / 8 + y * width / 8] |= (0x80 >> x % 8); cursorPtr += 3; } } free(bits); setCursorShape(width, height, colorData, maskData); } void VirtualFrameBuffer::repaint(HWND hWnd) { PAINTSTRUCT ps; HDC hdc; HDC memDC; hdc = BeginPaint(hWnd, &ps); memDC = CreateCompatibleDC(hdc); SelectObject(memDC, fScreenBitmap); BitBlt(hdc, 0, 0, VIRTUAL_SCREEN_WIDTH, VIRTUAL_SCREEN_HEIGHT, memDC, 0, 0, SRCCOPY); DeleteObject(memDC); EndPaint(hWnd, &ps); } void __assert_failed(int line, const char *file, const char *expr) { _asm { int 3 } } ResourceBitmap::ResourceBitmap(HINSTANCE instance, HDC dc, LPCTSTR bitmap, int width, int height) : MemorySurface(Surface::kRGB24, width, height) { HBITMAP bm = LoadBitmap(instance, bitmap); BITMAPINFO info; if (bm == NULL) { printf("error loading bitmap\n"); return; } char *bits = (char*) lockBits(); info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); info.bmiHeader.biWidth = width; info.bmiHeader.biHeight = -height; // negative to make top down info.bmiHeader.biPlanes = 1; // Must be one info.bmiHeader.biBitCount = 24; info.bmiHeader.biCompression = BI_RGB; info.bmiHeader.biSizeImage = 0; // Must be zero for BI_RGB bitmaps info.bmiHeader.biXPelsPerMeter = 1024 * 3; info.bmiHeader.biYPelsPerMeter = 768 * 4; info.bmiHeader.biClrUsed = 0; // Use maximum number of colors info.bmiHeader.biClrImportant = 0; // All colors are required if (GetDIBits(dc, bm, 0, height, bits, &info, DIB_RGB_COLORS) != height) printf("Error getting DI bits\n"); unlockBits(); }
[ "jeffbush001@gmail.com" ]
jeffbush001@gmail.com
8b2aeaa9dc2b0c907e182f236b6ee27a9bb7b928
3ef84250365b6501afd4c55830edb73f45398c46
/Code/GameSDK/GameDll/Effects/Tools/CVarActivationSystem.h
1575eb5a1faa2949f0cbe72269552e90ba065881
[]
no_license
Rjayone/TravellersNotes
cc9193d01c0b060d848401d74797ef14322e90dd
0bf44ad22daf64d56b70c841ac936ae3d1c12d9c
refs/heads/master
2021-04-26T11:40:03.965230
2015-10-25T14:04:22
2015-10-25T14:04:22
43,647,664
1
0
null
null
null
null
UTF-8
C++
false
false
1,728
h
#ifndef _CVAR_ACTIVATION_SYSTEM_ #define _CVAR_ACTIVATION_SYSTEM_ #pragma once //================================================================================================== // Name: SCVarParam // Desc: CVar param used in the cvar activation system // Author: James Chilvers //================================================================================================== struct SCVarParam { SCVarParam() { cvar = NULL; activeValue = 0.0f; originalValue = 0.0f; } ICVar* cvar; float activeValue; float originalValue; };//------------------------------------------------------------------------------------------------ //================================================================================================== // Name: CCVarActivationSystem // Desc: Simple data driven system to activate cvars // Author: James Chilvers //================================================================================================== class CCVarActivationSystem { public: CCVarActivationSystem(){} ~CCVarActivationSystem(){} void Initialise(const IItemParamsNode* cvarListXmlNode); // Uses the xml node name for the cvar, and activeValue attribute // eg <cl_fov activeValue="85"/> void Release(); void StoreCurrentValues(); // This stores the current values in the SCVarParam, and the CVar will be set to these when // SetCVarsActive(false) is called void SetCVarsActive(bool isActive); // Uses active value when set true, and original value when set false private: PodArray<SCVarParam> m_cvarParam; };//------------------------------------------------------------------------------------------------ #endif // _CVAR_ACTIVATION_SYSTEM_
[ "misterdecoy@mail.ru" ]
misterdecoy@mail.ru
fdcd5665d9a954cf9bf7052970dacea7396e874e
d34deb67c96e70b334a18acfb2c5e74b2c648487
/2/2.cpp
34f9d5d7b0e751beba1466f1917433ed769c173e
[]
no_license
WYX11111/CPP
c4071541a311c64eb6cb84d016f781ceb7696780
e598ceab7266d390fe33e2710bc962d1c9ca455c
refs/heads/master
2020-05-18T06:17:07.137950
2019-06-26T11:38:41
2019-06-26T11:38:41
184,230,172
0
0
null
null
null
null
GB18030
C++
false
false
211
cpp
#include "io.cpp" //导入io.cpp int main() { int a = readNumber(); //调用io.cpp里的readNumber()函数输入一个整数 int b = readNumber(); writeAnswer(a + b); //打印两数和 return 0; }
[ "wyxiao11111@mails.ccnu.edu.cn" ]
wyxiao11111@mails.ccnu.edu.cn
e524319375d460874cabbea3b7ddfaf7e8d04637
794894f3cac99b0753d3addf95f44df5421d62d3
/src/miner.cpp
228c416c3c7e84402056ed7146ec4d9ac17f490a
[ "MIT" ]
permissive
newarroncoin/newarroncoin
aad211b5bacf402aaf2538d658c7f5d49d3a0ccb
8e487c2b6d474d9b92f08c89d467193f40782892
refs/heads/master
2021-01-19T00:13:42.868570
2017-08-17T06:21:31
2017-08-17T06:21:31
100,567,589
0
0
null
null
null
null
UTF-8
C++
false
false
22,200
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2013 The NovaCoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "txdb.h" #include "miner.h" #include "kernel.h" #include "core.h" using namespace std; ////////////////////////////////////////////////////////////////////////////// // // BitcoinMiner // int static FormatHashBlocks(void* pbuffer, unsigned int len) { unsigned char* pdata = (unsigned char*) pbuffer; unsigned int blocks = 1 + ((len + 8) / 64); unsigned char* pend = pdata + 64 * blocks; memset(pdata + len, 0, 64 * blocks - len); pdata[len] = 0x80; unsigned int bits = len * 8; pend[-1] = (bits >> 0) & 0xff; pend[-2] = (bits >> 8) & 0xff; pend[-3] = (bits >> 16) & 0xff; pend[-4] = (bits >> 24) & 0xff; return blocks; } static const unsigned int pSHA256InitState[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; void SHA256Transform(void* pstate, void* pinput, const void* pinit) { SHA256_CTX ctx; unsigned char data[64]; SHA256_Init(&ctx); for (int i = 0; i < 16; i++) ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]); for (int i = 0; i < 8; i++) ctx.h[i] = ((uint32_t*)pinit)[i]; SHA256_Update(&ctx, data, sizeof(data)); for (int i = 0; i < 8; i++) ((uint32_t*)pstate)[i] = ctx.h[i]; } // Some explaining would be appreciated class COrphan { public: CTransaction* ptx; set<uint256> setDependsOn; double dPriority; double dFeePerKb; int64_t nFee; COrphan(CTransaction* ptxIn) { ptx = ptxIn; dPriority = dFeePerKb = 0; nFee = 0; } COrphan(double dPriority_, double dFeePerKb_, int64_t nFee_, CTransaction* ptxIn) { dPriority = dPriority_; dFeePerKb = dFeePerKb_; nFee = nFee_; ptx = ptxIn; } void print() const { LogPrintf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority, dFeePerKb); BOOST_FOREACH(uint256 hash, setDependsOn) LogPrintf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str()); } }; uint64_t nLastBlockTx = 0; uint64_t nLastBlockSize = 0; int64_t nLastCoinStakeSearchInterval = 0; // We want to sort transactions by priority and fee, so: typedef boost::tuple<double, double, int64_t, CTransaction*> TxPriority; class TxPriorityCompare { bool byFee; public: TxPriorityCompare(bool _byFee) : byFee(_byFee) { } bool operator()(const TxPriority& a, const TxPriority& b) { if (byFee) { if (a.get<1>() == b.get<1>()) return a.get<0>() < b.get<0>(); return a.get<1>() < b.get<1>(); } else { if (a.get<0>() == b.get<0>()) return a.get<1>() < b.get<1>(); return a.get<0>() < b.get<0>(); } } }; // CreateNewBlock: create new block (without proof-of-work/proof-of-stake) CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake, int64_t* pFees) { // Create new block auto_ptr<CBlock> pblock(new CBlock()); if (!pblock.get()) return NULL; CBlockIndex* pindexPrev = pindexBest; // Create coinbase tx CTransaction txNew; txNew.vin.resize(1); txNew.vin[0].prevout.SetNull(); txNew.vout.resize(1); int nHeight = pindexPrev->nHeight+1; // height of new block if (!Params().IsProtocolV2(nHeight)) // generate old version until protocolV2 pblock->nVersion = 6; if (!fProofOfStake) { CReserveKey reservekey(pwallet); CPubKey pubkey; pwallet->NewKeyFromAccount(pubkey); txNew.vout[0].scriptPubKey.SetDestination(pubkey.GetID()); } else { // Height first in coinbase required for block.version=2 txNew.vin[0].scriptSig = (CScript() << nHeight) + COINBASE_FLAGS; assert(txNew.vin[0].scriptSig.size() <= 100); txNew.vout[0].SetEmpty(); }; // Add our coinbase tx as first transaction pblock->vtx.push_back(txNew); pblock->nBits = GetNextTargetRequired(pindexPrev, fProofOfStake); // Collect memory pool transactions into the block int64_t nFees = 0; { LOCK2(cs_main, mempool.cs); CTxDB txdb("r"); // Priority order to process transactions list<COrphan> vOrphan; // list memory doesn't move map<uint256, vector<COrphan*> > mapDependers; // This vector will be sorted into a priority queue: vector<TxPriority> vecPriority; vecPriority.reserve(mempool.mapTx.size()); for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi) { CTransaction& tx = (*mi).second; if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal()) continue; COrphan* porphan = NULL; double dPriority = 0; int64_t nTotalIn = 0; bool fMissingInputs = false; BOOST_FOREACH(const CTxIn& txin, tx.vin) { if (tx.nVersion == ANON_TXN_VERSION && txin.IsAnonInput()) // anon inputs are verified later in CheckAnonInputs() continue; // Read prev transaction CTransaction txPrev; CTxIndex txindex; if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex)) { // This should never happen; all transactions in the memory // pool should connect to either transactions in the chain // or other transactions in the memory pool. if (!mempool.mapTx.count(txin.prevout.hash)) { LogPrintf("ERROR: mempool transaction missing input\n"); if (fDebug) assert("mempool transaction missing input" == 0); fMissingInputs = true; if (porphan) vOrphan.pop_back(); break; }; // Has to wait for dependencies if (!porphan) { // Use list for automatic deletion vOrphan.push_back(COrphan(&tx)); porphan = &vOrphan.back(); }; mapDependers[txin.prevout.hash].push_back(porphan); porphan->setDependsOn.insert(txin.prevout.hash); nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue; continue; }; int64_t nValueIn = txPrev.vout[txin.prevout.n].nValue; nTotalIn += nValueIn; int nConf = txindex.GetDepthInMainChainFromIndex(); dPriority += (double)nValueIn * nConf; }; if (tx.nVersion == ANON_TXN_VERSION) { int64_t nSumAnon; bool fInvalid; if (!tx.CheckAnonInputs(txdb, nSumAnon, fInvalid, false)) { if (fInvalid) LogPrintf("CreateNewBlock() : CheckAnonInputs found invalid tx %s\n", tx.GetHash().ToString().substr(0,10).c_str()); fMissingInputs = true; continue; }; nTotalIn += nSumAnon; }; if (fMissingInputs) continue; // Priority is sum(valuein * age) / txsize unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); dPriority /= nTxSize; // This is a more accurate fee-per-kilobyte than is used by the client code, because the // client code rounds up the size to the nearest 1K. That's good, because it gives an // incentive to create smaller transactions. int64_t nFee = nTotalIn-tx.GetValueOut(); double dFeePerKb = double(nFee) / (double(nTxSize)/1000.0); if (porphan) { porphan->dPriority = dPriority; porphan->dFeePerKb = dFeePerKb; } else { vecPriority.push_back(TxPriority(dPriority, dFeePerKb, nFee, &(*mi).second)); }; }; // Collect transactions into block map<uint256, CTxIndex> mapTestPool; uint64_t nBlockSize = 1000; uint64_t nBlockTx = 0; int nBlockSigOps = 100; bool fSortedByFee = (nBlockPrioritySize <= 0); TxPriorityCompare comparer(fSortedByFee); std::make_heap(vecPriority.begin(), vecPriority.end(), comparer); while (!vecPriority.empty()) { // Take highest priority transaction off the priority queue: double dPriority = vecPriority.front().get<0>(); double dFeePerKb = vecPriority.front().get<1>(); int64_t nFee = vecPriority.front().get<2>(); CTransaction& tx = *(vecPriority.front().get<3>()); std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer); vecPriority.pop_back(); // Size limits unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); if (nBlockSize + nTxSize >= nBlockMaxSize) continue; // Legacy limits on sigOps: unsigned int nTxSigOps = tx.GetLegacySigOpCount(); if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) continue; // Timestamp limit if (tx.nTime > GetAdjustedTime() || (fProofOfStake && tx.nTime > pblock->vtx[0].nTime)) continue; // Transaction fee int64_t nMinFee = tx.GetMinFee(nBlockSize, GMF_BLOCK); // will get GMF_ANON if tx.nVersion == ANON_TXN_VERSION // Skip free transactions if we're past the minimum block size: if (fSortedByFee && (dFeePerKb < nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize)) continue; // Prioritize by fee once past the priority size or we run out of high-priority // transactions: if (!fSortedByFee && ((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 144 / 250))) { fSortedByFee = true; comparer = TxPriorityCompare(fSortedByFee); std::make_heap(vecPriority.begin(), vecPriority.end(), comparer); }; // Connecting shouldn't fail due to dependency on other memory pool transactions // because we're already processing them in order of dependency map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool); MapPrevTx mapInputs; bool fInvalid; if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid)) continue; //int64_t nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut(); // -- Avoid calling CheckAnonInputs twice, use nFee from vecPriority if (nFee == 0) // tx came from COrphan { int64_t nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut(); if (tx.nVersion == ANON_TXN_VERSION) { int64_t nSumAnon; bool fInvalid; if (!tx.CheckAnonInputs(txdb, nSumAnon, fInvalid, false)) { if (fInvalid) LogPrintf("CreateNewBlock() : CheckAnonInputs found invalid tx %s\n", tx.GetHash().ToString().substr(0,10).c_str()); continue; }; nTxFees += nSumAnon; }; nFee = nTxFees; }; // TODO: must this be done twice!? // Need to look at COrphan if (nFee < nMinFee) continue; nTxSigOps += tx.GetP2SHSigOpCount(mapInputs); if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) continue; // Note that flags: we don't want to set mempool/IsStandard() // policy here, but we still have to ensure that the block we // create only contains transactions that are valid in new blocks. if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true, MANDATORY_SCRIPT_VERIFY_FLAGS)) continue; mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size()); swap(mapTestPool, mapTestPoolTmp); // Added pblock->vtx.push_back(tx); nBlockSize += nTxSize; ++nBlockTx; nBlockSigOps += nTxSigOps; nFees += nFee; if (fDebug && GetBoolArg("-printpriority")) { LogPrintf("priority %.1f feeperkb %.1f txid %s\n", dPriority, dFeePerKb, tx.GetHash().ToString().c_str()); }; // Add transactions that depend on this one to the priority queue uint256 hash = tx.GetHash(); if (mapDependers.count(hash)) { BOOST_FOREACH(COrphan* porphan, mapDependers[hash]) { if (!porphan->setDependsOn.empty()) { porphan->setDependsOn.erase(hash); if (porphan->setDependsOn.empty()) { vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->nFee, porphan->ptx)); std::push_heap(vecPriority.begin(), vecPriority.end(), comparer); }; }; }; }; }; nLastBlockTx = nBlockTx; nLastBlockSize = nBlockSize; if (fDebug && GetBoolArg("-printpriority")) LogPrintf("CreateNewBlock(): total size %u\n", nBlockSize); if (!fProofOfStake) pblock->vtx[0].vout[0].nValue = Params().GetProofOfWorkReward(nHeight, nFees); if (pFees) *pFees = nFees; // Fill in header pblock->hashPrevBlock = pindexPrev->GetBlockHash(); pblock->nTime = max(pindexPrev->GetPastTimeLimit()+1, pblock->GetMaxTransactionTime()); if (!fProofOfStake) pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; } return pblock.release(); } void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce) { // Update nExtraNonce static uint256 hashPrevBlock; if (hashPrevBlock != pblock->hashPrevBlock) { nExtraNonce = 0; hashPrevBlock = pblock->hashPrevBlock; }; ++nExtraNonce; unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2 pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS; assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100); pblock->hashMerkleRoot = pblock->BuildMerkleTree(); } void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1) { // // Pre-build hash buffers // struct { struct unnamed2 { int nVersion; uint256 hashPrevBlock; uint256 hashMerkleRoot; unsigned int nTime; unsigned int nBits; unsigned int nNonce; } block; unsigned char pchPadding0[64]; uint256 hash1; unsigned char pchPadding1[64]; } tmp; memset(&tmp, 0, sizeof(tmp)); tmp.block.nVersion = pblock->nVersion; tmp.block.hashPrevBlock = pblock->hashPrevBlock; tmp.block.hashMerkleRoot = pblock->hashMerkleRoot; tmp.block.nTime = pblock->nTime; tmp.block.nBits = pblock->nBits; tmp.block.nNonce = pblock->nNonce; FormatHashBlocks(&tmp.block, sizeof(tmp.block)); FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1)); // Byte swap all the input buffer for (unsigned int i = 0; i < sizeof(tmp)/4; i++) ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]); // Precalc the first half of the first hash, which stays constant SHA256Transform(pmidstate, &tmp.block, pSHA256InitState); memcpy(pdata, &tmp.block, 128); memcpy(phash1, &tmp.hash1, 64); } bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey) { uint256 hashBlock = pblock->GetHash(); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); if(!pblock->IsProofOfWork()) return error("CheckWork() : %s is not a proof-of-work block", hashBlock.GetHex().c_str()); if (hashBlock > hashTarget) return error("CheckWork() : proof-of-work not meeting target"); //// debug print LogPrintf("CheckWork() : new proof-of-work block found \n hash: %s \ntarget: %s\n", hashBlock.GetHex().c_str(), hashTarget.GetHex().c_str()); pblock->print(); LogPrintf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str()); // Found a solution { LOCK(cs_main); if (pblock->hashPrevBlock != hashBestChain) return error("CheckWork() : generated block is stale"); // Remove key from key pool reservekey.KeepKey(); // Track how many getdata requests this block gets { LOCK(wallet.cs_wallet); wallet.mapRequestCount[hashBlock] = 0; } // Process this block the same as if we had received it from another node if (!ProcessBlock(NULL, pblock, hashBlock)) return error("CheckWork() : ProcessBlock, block not accepted"); } return true; } bool CheckStake(CBlock* pblock, CWallet& wallet) { uint256 proofHash = 0, hashTarget = 0; uint256 hashBlock = pblock->GetHash(); if (!pblock->IsProofOfStake()) return error("CheckStake() : %s is not a proof-of-stake block", hashBlock.GetHex().c_str()); std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(pblock->hashPrevBlock); if (mi == mapBlockIndex.end()) return error("CheckStake() : %s prev block not found: %s.", hashBlock.GetHex().c_str(), pblock->hashPrevBlock.GetHex().c_str()); // verify hash target and signature of coinstake tx if (!CheckProofOfStake(mi->second, pblock->vtx[1], pblock->nBits, proofHash, hashTarget)) return error("CheckStake() : proof-of-stake checking failed"); //// debug print LogPrintf("CheckStake() : new proof-of-stake block found \n hash: %s \nproofhash: %s \ntarget: %s\n", hashBlock.GetHex().c_str(), proofHash.GetHex().c_str(), hashTarget.GetHex().c_str()); pblock->print(); LogPrintf("out %s\n", FormatMoney(pblock->vtx[1].GetValueOut()).c_str()); // Found a solution { LOCK(cs_main); if (pblock->hashPrevBlock != hashBestChain) return error("CheckStake() : generated block is stale"); // Track how many getdata requests this block gets { LOCK(wallet.cs_wallet); wallet.mapRequestCount[hashBlock] = 0; } // Process this block the same as if we had received it from another node if (!ProcessBlock(NULL, pblock, hashBlock)) return error("CheckStake() : ProcessBlock, block not accepted"); } return true; } void ThreadStakeMiner(CWallet *pwallet) { SetThreadPriority(THREAD_PRIORITY_LOWEST); bool fTryToSync = true; int64_t nTimeLastStake = 0; while (true) { boost::this_thread::interruption_point(); while (pwallet->IsLocked()) { fIsStaking = false; MilliSleep(2000); boost::this_thread::interruption_point(); }; while (vNodes.empty() || IsInitialBlockDownload()) { fIsStaking = false; fTryToSync = true; if (fDebugPoS) LogPrintf("StakeMiner() IsInitialBlockDownload\n"); MilliSleep(2000); boost::this_thread::interruption_point(); }; if (fTryToSync) { fTryToSync = false; if (vNodes.size() < 8 || nBestHeight < GetNumBlocksOfPeers()) { fIsStaking = false; if (fDebugPoS) LogPrintf("StakeMiner() TryToSync\n"); MilliSleep(60000); continue; }; }; if (nBestHeight < GetNumBlocksOfPeers()-1) { fIsStaking = false; if (fDebugPoS) LogPrintf("StakeMiner() nBestHeight < GetNumBlocksOfPeers()\n"); MilliSleep(nMinerSleep * 4); continue; }; if (nMinStakeInterval > 0 && nTimeLastStake + (int64_t)nMinStakeInterval > GetTime()) { if (fDebug) LogPrintf("StakeMiner() Rate limited to 1 / %d seconds.\n", nMinStakeInterval); MilliSleep(nMinStakeInterval * 500); // nMinStakeInterval / 2 seconds continue; }; // // Create new block // int64_t nFees; auto_ptr<CBlock> pblock(CreateNewBlock(pwallet, true, &nFees)); if (!pblock.get()) return; fIsStaking = true; // Trying to sign a block if (pblock->SignBlock(*pwallet, nFees)) { SetThreadPriority(THREAD_PRIORITY_NORMAL); if (CheckStake(pblock.get(), *pwallet)) nTimeLastStake = GetTime(); SetThreadPriority(THREAD_PRIORITY_LOWEST); }; MilliSleep(nMinerSleep); }; }
[ "820421292@qq.com" ]
820421292@qq.com
fa86892186c0587d6e094ef2d199dd72f08b5cb1
5f19592d3e0cdc0c8732b5a4871deb5003f9f4a8
/src/node/communication/mac/mac802154a/fuzzyIS/TakagiSugenoRule.cc
0673a8faf210bee46e2f7b6da90f140dba824f05
[]
no_license
SamanShafigh/fuzzy-mac802154
2f62883e11c5309c2c57abfb4e3b70c3f01f7c04
36b48b3193349de77c32d77a41fc597d745a1a16
refs/heads/master
2021-01-12T16:51:54.644601
2018-02-19T01:24:24
2018-02-19T01:24:24
71,454,504
5
0
null
null
null
null
UTF-8
C++
false
false
2,075
cc
/* Copyright 2010 Juan Rada-Vilela Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "TakagiSugenoRule.h" #include "TakagiSugenoConsequent.h" #include "DescriptiveAntecedent.h" #include "StrOp.h" TakagiSugenoRule::TakagiSugenoRule() : FuzzyRule() { } TakagiSugenoRule::TakagiSugenoRule(const std::string& rule, const FuzzyEngine& engine) : FuzzyRule() { try { parse(rule, engine); } catch (ParsingException& e) { FL_LOG(e.toString()); } } TakagiSugenoRule::~TakagiSugenoRule() { } void TakagiSugenoRule::parse(const std::string& rule, const FuzzyEngine& engine) { std::string str_antecedent, str_consequent; ExtractFromRule(rule, str_antecedent, str_consequent); DescriptiveAntecedent* obj_antecedent = new DescriptiveAntecedent; obj_antecedent->parse(str_antecedent, engine); setAntecedent(obj_antecedent); std::vector<std::string> consequents = StrOp::SplitByWord(str_consequent, FuzzyRule::FR_AND); TakagiSugenoConsequent* obj_consequent = NULL; for (size_t i = 0; i < consequents.size(); ++i) { obj_consequent = new TakagiSugenoConsequent; try { std::string x = consequents[i]; StrOp::FindReplace(x,"="," = "); obj_consequent->parse(x, engine); } catch (ParsingException& e) { delete obj_consequent; throw e; } addConsequent(obj_consequent); } }
[ "samanshafigh@gmail.com" ]
samanshafigh@gmail.com
b093d7b0b43cc0ed70a0a537f9a7774ff962390f
9eadd7a4db934ba63675093bc8c6c40f154cbeaa
/cpp/photo/jpeg_encoder.h
72985a6f978e43a84f200395308af5ddf459f29b
[ "Apache-2.0" ]
permissive
ghas-results/vr180
ee7be58f77d14cc317f4b1a188d35e42e79f35bd
f55eaa1c6835b911b7a11830ec546636a16d49da
refs/heads/master
2023-08-21T04:09:34.447377
2019-02-14T22:30:08
2019-02-14T22:30:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,298
h
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef VR180_CPP_PHOTO_JPEG_ENCODER_H_ #define VR180_CPP_PHOTO_JPEG_ENCODER_H_ #include <cstdint> #include <string> extern "C" { #include "libjpeg_turbo/jpeglib.h" } namespace vr180 { // Encodes the subimage of data specified by x,y,width,height,stride into // result. bool EncodeJpeg(const uint8_t* data, int x, int y, int width, int height, int stride, int quality, J_COLOR_SPACE color_space, std::string* result); // A wrapper to encoder RGBA jpegs. bool EncodeRGBAJpeg(const uint8_t* data, int x, int y, int width, int height, int stride, int quality, std::string* result); } // namespace vr180 #endif // VR180_CPP_PHOTO_JPEG_ENCODER_H_
[ "jiamingliu@google.com" ]
jiamingliu@google.com
6ef9600205849089d83431a06c2575462309a15f
6ab07216eff0dfd45f6a5a1dd10c6cbd9c0e154d
/Utilities/MicronTrackerFiles/Collection.cpp
40e07f3eea318877bb4e3e88de85a6ce769508eb
[]
no_license
awiles/AIGS
e5956076fc8fdc7fc0dd7a42ac9ad7b0718ee7d6
2d6a72c77b5ab4f4934ffd4109fca71b7bdc76a2
refs/heads/master
2020-12-25T02:23:45.041112
2017-03-03T03:55:12
2017-03-03T03:55:12
2,820,245
2
4
null
2017-03-03T03:55:13
2011-11-21T13:59:32
C++
UTF-8
C++
false
false
1,846
cpp
/************************************************************** * * Micron Tracker: Example C++ wrapper and Multi-platform demo * * Written by: * Shahram Izadyar, Robarts Research Institute - London- Ontario , www.robarts.ca * Claudio Gatti, Claron Technology - Toronto -Ontario, www.clarontech.com * * Copyright Claron Technology 2000-2003 * ***************************************************************/ #include "Collection.h" Collection::Collection(int h) { // If a handle is already passed to this class, then use that handle and don't create a new one. if (h != 0) this->m_handle = h; else this->m_handle = Collection_New(); this->ownedByMe = TRUE; } /****************************/ /** Destructor */ Collection::~Collection() { if (this->m_handle != 0 && this->ownedByMe == true) Collection_Free(this->m_handle); } /****************************/ /** Add an item to the collection */ void Collection::add(int val) { Collection_Add(this->m_handle, val, 0); } /****************************/ /** Remove an item from the collection */ void Collection::remove(int idx) { Collection_Remove(this->m_handle, idx); } /****************************/ /** Return the count of the items in the collection */ int Collection::count() { int result = Collection_Count(m_handle); return result; } /****************************/ /** Returns the integer item of index idx in the collection */ int Collection::itemI(int idx) { int intResult = 0; double dblResult = 0; Collection_Item(this->m_handle, idx, &intResult, &dblResult); return intResult; } /****************************/ /** Returns the integer item of index idx in the collection */ double Collection::itemD(int idx) { int intResult = 0; double dblResult = 0; Collection_Item(this->m_handle, idx, &intResult, &dblResult); return dblResult; }
[ "awiles@ndigital.com" ]
awiles@ndigital.com
799e599c7be0715b39a7e90cc91215acd677ce3b
d0f501e9d14e52e415ab810b67a075ee8e2de28c
/C_P82e/C_P82e.cpp
e477b8c36711c34266ec8bc4cbfad21697e5375c
[]
no_license
Windmill-City/C_Exercise
c776ca38c5dcbcc934bf2a49712ff4f0fda1e106
5067ece98588a163b5801200f9bf17d42676919e
refs/heads/master
2022-11-07T07:41:55.844750
2020-06-18T15:43:30
2020-06-18T15:43:30
250,158,294
0
0
null
null
null
null
UTF-8
C++
false
false
1,019
cpp
// C_P82e.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include <iostream> int main() { for (int y = 1; y <= 6; y++) { for (float x = 5.5; x <= 12.5; x += 0.5) { float i = 0; i = 2 + (y + 0.5 * x); printf("i:%0.2f x:%0.2f y:%d\n", i, x, y); } } } // 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单 // 调试程序: F5 或调试 >“开始调试”菜单 // 入门使用技巧: // 1. 使用解决方案资源管理器窗口添加/管理文件 // 2. 使用团队资源管理器窗口连接到源代码管理 // 3. 使用输出窗口查看生成输出和其他消息 // 4. 使用错误列表窗口查看错误 // 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目 // 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
[ "1449182174@qq.com" ]
1449182174@qq.com
c693cf9ee6b88b1f874ea23027fe57ab7b75b241
0fb0dcf1b7192af5dc2bcc32c48dc6efb016366e
/t9/main.cpp
9f769f2befb51ae1c73cc67d25fd6a08c23ad823
[]
no_license
imzfz/mycpp
9e4076e96e0cfabdc953fb25055aa08e9a806a96
372349d7e68062a66281b2030132ea124b0d38af
refs/heads/master
2021-01-10T23:22:44.290851
2016-10-01T09:53:26
2016-10-01T09:53:26
69,727,979
0
0
null
null
null
null
UTF-8
C++
false
false
180
cpp
#include "head.h" int main() { Sale sale; sale.list(5, 23.5); sale.list(12, 24.56); sale.list(100, 21.5); sale.average(); sale.display(); return 0; }
[ "zfz@fzdeMacBook-Pro.local" ]
zfz@fzdeMacBook-Pro.local
c5b4f2fc6d2aa234bc697db6ba37caeaaf55c3da
426404ea70a7140ddd58ae6cddf4ecd9d04806d2
/SyneVisLinux/wavutils.h
dfce45fdc15d64174c370bdd7139b5e0d4bd99b9
[ "Unlicense" ]
permissive
averov90/RaspberryPi-SyneVis_Proj
62482e2bd717576ce05d76533234e5bd7ee91151
83889fdefdfaa709d88d6823cbca233a30d443a0
refs/heads/master
2020-12-20T11:55:43.895829
2020-02-06T18:49:11
2020-02-06T18:49:11
236,067,191
1
0
null
null
null
null
WINDOWS-1251
C++
false
false
4,997
h
#pragma once #include "dependents.h" #include "consts.h" namespace WavUtils { struct SegmentSineProps { unsigned int bufflen; float period; }; struct WaveSmallInfo { unsigned short channels; unsigned short sampleRate; }; struct Freqs { float *freqs = nullptr; unsigned short count = 0; Freqs(const Freqs &c):freqs(c.freqs), count(c.count) { copyed = true; } Freqs() {} float &operator [](const unsigned short index) { return freqs[index]; } ~Freqs() { if (copyed) delete[] freqs; } private: bool copyed = false; }; struct SynGenData { short **sines; unsigned int *sinessizes; unsigned short sinesnum; }; void GenPeriodicalSine(short* buffer, unsigned short lenght, float tone, short volume = 32767); Freqs GetPeriodicalSineFreqs(unsigned short count, unsigned short offset = 0); unsigned short GetPeriodicalSineBuffLen(float tone); /*@accuracy Value range: 0-4 */ SegmentSineProps GetSegmetSineBuffLen(float tone, char accuracy); /*@accuracy Value range: 0-4 */ Freqs GetSegmetSineFreqs(float min_freq, float max_freq, char accuracy, unsigned short buffmultiplicity); void GenSegmentSine(short* buffer, const SegmentSineProps &props, short volume = 32767); bool SaveSND(const char *filepath, const short* buffer, unsigned int bufflen); short *LoadSND(const char *filepath, unsigned int &bufflen); short *LoadWAVFromBuffer(const char *buffer, unsigned int &outbufflen, WaveSmallInfo *info = nullptr); /*@accuracy Value range: 0-4 */ bool GenerateSinesByFreqFile(const char* freqfilename, char freqaccuracy, SynGenData &data); bool SaveSNDPacket(const char* collectorFilename, const char* SNDfileFolder, const SynGenData &data); bool LoadSNDPacket(const char* collectorFilename, const char* SNDfileFolder, SynGenData &data); struct WAV_HEADER { //Содержит символы "RIFF" в ASCII кодировке //(0x52494646 в big-endian представлении) char chunkId[4]; // 36 + subchunk2Size, или более точно: // 4 + (8 + subchunk1Size) + (8 + subchunk2Size) // Это оставшийся размер цепочки, начиная с этой позиции. // Иначе говоря, это размер файла - 8, то есть, // исключены поля chunkId и chunkSize. uint32_t chunkSize; // Содержит символы "WAVE" // (0x57415645 в big-endian представлении) char format[4]; // Формат "WAVE" состоит из двух подцепочек: "fmt " и "data": // Подцепочка "fmt " описывает формат звуковых данных: // Содержит символы "fmt " // (0x666d7420 в big-endian представлении) char subchunk1Id[4]; // 16 для формата PCM. // Это оставшийся размер подцепочки, начиная с этой позиции. uint32_t subchunk1Size; // Для PCM = 1 (то есть, Линейное квантование). // Значения, отличающиеся от 1, обозначают некоторый формат сжатия. uint16_t audioFormat; // Количество каналов. Моно = 1, Стерео = 2 и т.д. uint16_t numChannels; // Частота дискретизации. 8000 Гц, 44100 Гц и т.д. uint32_t sampleRate; // sampleRate * numChannels * bitsPerSample/8 uint32_t byteRate; // numChannels * bitsPerSample/8 // Количество байт для одного сэмпла, включая все каналы. uint16_t blockAlign; // Так называемая "глубиная" или точность звучания. 8 бит, 16 бит и т.д. uint16_t bitsPerSample; // Подцепочка "data" содержит аудио-данные и их размер. // Содержит символы "data" // (0x64617461 в big-endian представлении) char subchunk2Id[4]; // numSamples * numChannels * bitsPerSample/8 // Количество байт в области данных. uint32_t subchunk2Size; // Далее следуют непосредственно Wav данные. }; /* ofstream str; str.open("test.wav", ofstream::out | fstream::binary); WavUtils::WAV_HEADER wh; memcpy(wh.chunkId, "RIFF", 4); wh.chunkSize=12036; memcpy(wh.format, "WAVE", 4); memcpy(wh.subchunk1Id, "fmt ", 4); wh.subchunk1Size=16; wh.audioFormat=1; wh.numChannels=1; wh.sampleRate= WavUtils::SAMPLE_RATE; wh.byteRate= WavUtils::SAMPLE_RATE*2; wh.blockAlign=2; wh.bitsPerSample=16; memcpy(wh.subchunk2Id, "data", 4); wh.subchunk2Size=24000; str.write((char*)&wh, sizeof(WavUtils::WAV_HEADER)); //float *af = a, *bf = b, *ae = a+50, *be=b+19; for (unsigned int i1 = 0; i1 != 1000; ++i1) for (unsigned int i = 0; i != 12; ++i) { str.write((char*)(a+i), 2); //cout << a[i] << endl; } str.close(); cout << "end!" << endl; */ }
[ "averov90@inbox.ru" ]
averov90@inbox.ru
57d5b8f2ac1fd2e6f0c050882213ad897c9e336a
41ff29c79207e6a34bb0ade2c8b6d6eaaf515c07
/general/Fritz3TShirtCannonRobot/OI.h
669009aa184f30473223fd7d6419dfa3b3b8cabb
[]
no_license
stevep001/RoboEagles
322f56a568b5acfa51478d1cd4ecfb8588a5902c
5c4a6afc67d3d9c554826bfb282708320511d110
refs/heads/master
2021-01-13T01:55:23.227079
2014-01-18T07:19:24
2014-01-18T07:19:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
283
h
#ifndef OI_H #define OI_H #include "WPILib.h" class OI { private: Joystick *joystick; JoystickButton *fireButton; JoystickButton *fillButton; JoystickButton *aimUpButton; JoystickButton *aimDownButton; public: OI(); Joystick *getJoystick(); }; #endif
[ "steve@zpfe.com" ]
steve@zpfe.com
f25d0eb375b01e6417d102b4e14cebf1efb79b26
870879c2878767d685e616e565bd134f61f7b4b6
/src/CudaDriver.cpp
1b4636404d5cfcd72a7f319a112f9e6b3aae170c
[ "MIT" ]
permissive
satishphd/mpigis-lb
373f4e5599607efb3abba11064b6d1d2ecbcbeca
06dcd5da27d3e0dacc001e8d012d1f73154cdd37
refs/heads/master
2021-11-11T18:15:09.940398
2021-10-30T02:03:40
2021-10-30T02:03:40
222,028,414
6
1
null
null
null
null
UTF-8
C++
false
false
5,902
cpp
#include <string> #include <list> #include "filePartition/FilePartitioner.h" #include "filePartition/MPI_File_Partitioner.h" #include "filePartition/FileSplits.h" #include "parser/Parser.h" #include "parser/WKTParser.h" #include "filePartition/config.h" #include <geos/geom/Geometry.h> #include "spatialPartition/grid.h" #include "spatialPartition/uniformGrid.h" #include "index/index.h" #include "join/join.h" #include "overlay/overlay.h" #include <fstream> #include <iostream> #include <cstdlib> #include "mpiTypes/mpitype.h" #include "geom_util/util.h" #include "parser/road_network_parser.h" #include "spatialPartition/uniformGrid.h" #include "spatialPartition/RtreeStructure.h" #include "taskMap/TaskMap.h" #include "taskMap/roundRobinTaskMap.h" #include "bufferManager/bufferManagerGeoms.h" #include "mapreduce/mrdriver.h" #include "bufferManager/bufferRoadnetwork.h" #include <fstream> #include <unistd.h> #include "cuda/CudaJoinInterface.h" //#define DBUG2 2 //#define DBUG1 1 using namespace std; /* mpirun -np 2 ./mpiio 2 ../datasets/parks5k 1st arg is number of partitions 2nd arg is 1st file 3rd arg is 2nd file */ int main2(int argc, char **argv) { Config args(argc, argv); args.initMPI(argc, argv); char hostname[256]; gethostname(hostname,255); cout<<hostname<<endl; //cout<<""<<args.getLayer1()->at(2)<<endl; //cout<<""<<args.getLayer2()->at(2)<<endl; return 0; } int main(int argc, char **argv) { Config args(argc, argv); args.initMPI(argc, argv); double t1, t2; t1 = MPI_Wtime(); char hostname[256]; gethostname(hostname,255); #ifdef DBUG2 string fileStr = "debug_logs/" + args.log_file + to_string(args.rank); char *filename = (char *)fileStr.c_str(); std::ofstream ofs; ofs.open (filename, std::ofstream::out | std::ofstream::app); #endif FilePartitioner *partitioner = new MPI_File_Partitioner(); partitioner->initialize(args); //cout<<"init done"<<endl; pair<FileSplits*, FileSplits*> splitPair = partitioner->partition(); //cerr<<"P"<<args->rank<<" lines, "<<splitPair.first->numLines()<<endl; //long numLines = splitPair.second->numLines(); long numLines = splitPair.first->numLines(); long totalLines = 0; #ifdef DBUG1 //MPI_Reduce(void* send_data, void* recv_data, int count, MPI_Datatype datatype, MPI_Op op, int root, MPI_Comm communicator) MPI_Reduce(&numLines, &totalLines, 1, MPI_LONG, MPI_SUM, 0, MPI_COMM_WORLD); if(args.rank == 0) cerr<<"total number of lines "<<totalLines<<endl; #endif //Parser *parser = new RoadNetworkParser(); Parser *parser = new WKTParser(); list<Geometry*> *layer1Geoms = parser->parse(*splitPair.first); cerr<<"P"<<args.rank<<" "<<hostname<<", geoms 1, "<<layer1Geoms->size()<<endl; list<Geometry*> *layer2Geoms = parser->parse(*splitPair.second); cerr<<"P"<<args.rank<<" "<<hostname<<", geoms 2, "<<layer2Geoms->size()<<endl; #ifdef DBUG1 long numGeoms = layer2Geoms->size(); long totalGeoms = 0; MPI_Reduce(&numGeoms, &totalGeoms, 1, MPI_LONG, MPI_SUM, 0, MPI_COMM_WORLD); if(args.rank == 0) cerr<<"total number of Geoms layer 2 "<<totalGeoms<<endl; #endif Envelope mbr = GeometryUtility :: getMBR( layer1Geoms ); #ifdef DBUG2 //cerr<<args.rank<<", "<<mbr.toString(); //cerr<<args.rank<<", "<<mbr.getMinX()<<" - "<<mbr.getMaxX()<<" , "<<mbr.getMinY()<<" - "<<mbr.getMaxY(); //printf("%d, (%f %f), (%f %f) \n",args.rank, mbr.getMinX(), mbr.getMinY(), mbr.getMaxX(), mbr.getMaxY()); //fflush(stdout); ofs <<"Rank " <<args.rank <<": local Envelope minX " << mbr.getMinX() <<" minY "<<mbr.getMinY()<<" maxX "<< mbr.getMaxX()<<" maxY "<< mbr.getMaxY()<<"\n"; #endif SpatialTypes types; Envelope universe = types.reduceByUnion(&mbr); // cout<<"*****************************"<<endl; if(args.rank == 0) printf("Universe: %d, (%f %f), (%f %f) \n",0, universe.getMinX(), universe.getMinY(), universe.getMaxX() , universe.getMaxY()); Grid *uniGrid = new UniformGrid(args.numPartitions, &universe); // if(args.rank == 0) { // cout<<"Number of cells in the grid "<<uniGrid->size()<<endl; // // uniGrid->printGridCoordinates(); // } uniGrid->populateGridCells(layer1Geoms, true); cout<<"PopulateGridCells layer A "<<args.rank<<endl; uniGrid->populateGridCells(layer2Geoms, false); cout<<"PopulateGridCells layer B "<<args.rank<<endl; if(args.rank == 0) { //list<string> logs = uniGrid->localGridStatistics(); } splitPair.first->clear(); delete splitPair.first; splitPair.second->clear(); delete splitPair.second; MappingStrategy *strategy = new RoundRobinStrategy(args.numPartitions, args.numProcesses); map<int, Envelope*> *grid = uniGrid->getGridCellsMap(); strategy->createCellProcessMap(grid); // if(args.rank == 0) { // strategy->printStrategy(); // } //map<int, vector<int>* > *mapping = strategy->getProcessToCellsMap(); BufferManagerForGeoms geomsBuffMgr(strategy, uniGrid, &args); pair<map<int, list<Geometry*>* > *, map<int, list<Geometry*>* > * >*geomMapPair = geomsBuffMgr.shuffleExchangeGrpByCell(); cerr<<"Shuffle-Exchange"<<endl; CudaJoinInterface cudaInterface; cudaInterface.createReducers(&args, geomMapPair); t2 = MPI_Wtime(); cout<<hostname<<":"<<args.rank<<", Time, "<<(t2-t1)<<endl; MPI_Finalize(); return 0; }
[ "satishpuri.dgp@gmail.com" ]
satishpuri.dgp@gmail.com
34195b4d12ed13019eef7b927498e6f51aa14fcc
b8fb33128e8d2f8abbcbf859dd8509908ec6335b
/FUnction overloading/functionoverloading using class.cpp
cc92fb3c9c4ecb65984e13eb9a56c4d9bf5473a3
[]
no_license
Yogesh070/C-
f77553a9435d201bdc27dfbef1665fb5ab36e264
3da09ac8704dc5f9a4799524bdebf6c025d783c6
refs/heads/master
2020-06-26T21:25:54.314258
2019-09-16T15:08:11
2019-09-16T15:08:11
199,761,699
0
0
null
null
null
null
UTF-8
C++
false
false
804
cpp
#include <iostream> #include <conio.h> #define pi 3.14 using namespace std; class area{ float areas; public: void area_51(int a , int b); void area_51(double l, double c); void area_51(double r); }; void area :: area_51(int a, int b) { areas=a*b; cout<<"area of rectangle="<<areas<<endl; } void area :: area_51(double l, double c) { areas=(l*c)/2; cout<<"area of triangle="<<areas<<endl; } void area :: area_51(double r) { areas=pi*r*r; cout<<"area of circle="<<areas<<endl; } main() { int a,b; double l,c,r; area obj; cout<<"enter the lenght and breath of rectangle"<<endl; cin>>a>>b; obj.area_51(a,b); cout<<"enter the lenght and height of triangle"<<endl; cin>>l>>c; obj.area_51(l,c); cout<<"eneter the radius of circle"<<endl; cin>>r; obj.area_51(r); }
[ "46161212+Yogesh070@users.noreply.github.com" ]
46161212+Yogesh070@users.noreply.github.com
bbc111c0936b451ec64531b70483ba9246d90568
87a600d36a5757969ead7e235c93e3530d72b43a
/abm_product/newace/Time_Value.h
a89cdb5b906d8b539b1ac81fd0227960cca93554
[]
no_license
xkmld419/learning
3c3cad407d03bf693bcd863794cca7fb8a5df99a
128ffa1496c43c36b83f266522bd49b28184499f
refs/heads/master
2023-07-12T16:54:50.647834
2021-08-21T15:41:42
2021-08-21T15:41:42
45,075,836
1
0
null
null
null
null
UTF-8
C++
false
false
12,968
h
// -*- C++ -*- //============================================================================= /** * @file Time_Value.h * * Time_Value.h,v 4.28 2004/03/31 08:06:06 jwillemsen Exp * * @author Douglas C. Schmidt <schmidt@cs.wustl.edu> */ //============================================================================= #ifndef ACE_TIME_VALUE_H #define ACE_TIME_VALUE_H #include "config.h" #include "macros.h" //#define __need_timespec #include <sys/time.h> // Define some helpful constants. // Not type-safe, and signed. For backward compatibility. #define ACE_ONE_SECOND_IN_MSECS 1000L #define ACE_ONE_SECOND_IN_USECS 1000000L #define ACE_ONE_SECOND_IN_NSECS 1000000000L // ------------------------------------------------------------------- // These forward declarations are only used to circumvent a bug in // MSVC 6.0 compiler. They shouldn't cause any problem for other // compilers and they can be removed once MS release a SP that contains // the fix. // This forward declaration is needed by the set() and FILETIME() functions #if defined (ACE_LACKS_LONGLONG_T) class ACE_U_LongLong; #endif /* ACE_LACKS_LONGLONG_T */ // ------------------------------------------------------------------- // ------------------------------------------------------------------- /** * @class ACE_Time_Value * * @brief Operations on "timeval" structures, which express time in * seconds (secs) and microseconds (usecs). * * This class centralizes all the time related processing in * ACE. These time values are typically used in conjunction with OS * mechanisms like <select>, <poll>, or <cond_timedwait>. */ class ACE_Time_Value { public: /// Constant "0". static const ACE_Time_Value zero; /** * Constant for maximum time representable. Note that this time is * not intended for use with <select> or other calls that may have * *their own* implementation-specific maximum time representations. * Its primary use is in time computations such as those used by the * dynamic subpriority strategies in the ACE_Dynamic_Message_Queue * class. */ static const ACE_Time_Value max_time; ACE_ALLOC_HOOK_DECLARE; // = Initialization methods. // = Methods for converting to/from various time formats. inline ACE_Time_Value (const struct timeval &tv) // : tv_ () { // ACE_OS_TRACE ("ACE_Time_Value"); this->set (tv); } inline operator timeval () const { // ACE_OS_TRACE ("operator timeval"); return this->tv_; } inline operator const timeval * () const { // ACE_OS_TRACE ("operator const timeval *"); return (const timeval *) &this->tv_; } inline void set (long sec, long usec) { // ACE_OS_TRACE ("set"); this->tv_.tv_sec = sec; this->tv_.tv_usec = usec; this->normalize (); } inline void set (double d) { // ACE_OS_TRACE ("set"); long l = (long) d; this->tv_.tv_sec = l; this->tv_.tv_usec = (long) ((d - (double) l) * ACE_ONE_SECOND_IN_USECS + .5); this->normalize (); } // Initializes a timespec. Note that this approach loses precision // since it converts the nano-seconds into micro-seconds. But then // again, do any real systems have nano-second timer precision?! inline void set (const timespec &tv) { // ACE_OS_TRACE ("set"); #if ! defined(ACE_HAS_BROKEN_TIMESPEC_MEMBERS) this->tv_.tv_sec = ACE_static_cast (long, tv.tv_sec); // Convert nanoseconds into microseconds. this->tv_.tv_usec = tv.tv_nsec / 1000; #else this->tv_.tv_sec = tv.ts_sec; // Convert nanoseconds into microseconds. this->tv_.tv_usec = tv.ts_nsec / 1000; #endif /* ACE_HAS_BROKEN_TIMESPEC_MEMBERS */ this->normalize (); } inline void set (const timeval &tv) { // ACE_OS_TRACE ("set"); this->tv_.tv_sec = tv.tv_sec; this->tv_.tv_usec = tv.tv_usec; this->normalize (); } inline ACE_Time_Value (void) // : tv_ () { // ACE_OS_TRACE ("ACE_Time_Value"); this->set (0, 0); } inline ACE_Time_Value (long sec, long usec=0) { // ACE_OS_TRACE ("ACE_Time_Value"); this->set (sec, usec); } // Returns number of seconds. inline long sec (void) const { // ACE_OS_TRACE ("sec"); return this->tv_.tv_sec; } // Sets the number of seconds. inline void sec (long sec) { // ACE_OS_TRACE ("sec"); this->tv_.tv_sec = sec; } // Converts from Time_Value format into milli-seconds format. inline unsigned long msec (void) const { // ACE_OS_TRACE ("msec"); return this->tv_.tv_sec * 1000 + this->tv_.tv_usec / 1000; } // Converts from milli-seconds format into Time_Value format. inline void msec (long milliseconds) { // ACE_OS_TRACE ("msec"); // Convert millisecond units to seconds; this->tv_.tv_sec = milliseconds / 1000; // Convert remainder to microseconds; this->tv_.tv_usec = (milliseconds - (this->tv_.tv_sec * 1000)) * 1000; } // Returns number of micro-seconds. inline long usec (void) const { // ACE_OS_TRACE ("usec"); return this->tv_.tv_usec; } // Sets the number of micro-seconds. inline void usec (long usec) { // ACE_OS_TRACE ("usec"); this->tv_.tv_usec = usec; } inline ACE_Time_Value & operator *= (double d) { double time = ((double) this->sec ()) * ACE_ONE_SECOND_IN_USECS + this->usec (); time *= d; this->sec ((long)(time / ACE_ONE_SECOND_IN_USECS)); this->usec (((long)time) % ACE_ONE_SECOND_IN_USECS); this->normalize (); return *this; } inline friend ACE_Time_Value operator * (double d, const ACE_Time_Value &tv) { return ACE_Time_Value (tv) *= d; } inline friend ACE_Time_Value operator * (const ACE_Time_Value &tv, double d) { return ACE_Time_Value (tv) *= d; } // True if tv1 > tv2. inline friend int operator > (const ACE_Time_Value &tv1, const ACE_Time_Value &tv2) { // ACE_OS_TRACE ("operator >"); if (tv1.sec () > tv2.sec ()) return 1; else if (tv1.sec () == tv2.sec () && tv1.usec () > tv2.usec ()) return 1; else return 0; } // True if tv1 >= tv2. inline friend int operator >= (const ACE_Time_Value &tv1, const ACE_Time_Value &tv2) { // ACE_OS_TRACE ("operator >="); if (tv1.sec () > tv2.sec ()) return 1; else if (tv1.sec () == tv2.sec () && tv1.usec () >= tv2.usec ()) return 1; else return 0; } // Returns the value of the object as a timespec. inline operator timespec () const { // ACE_OS_TRACE ("operator timespec"); timespec tv; #if ! defined(ACE_HAS_BROKEN_TIMESPEC_MEMBERS) tv.tv_sec = this->sec (); // Convert microseconds into nanoseconds. tv.tv_nsec = this->tv_.tv_usec * 1000; #else tv.ts_sec = this->sec (); // Convert microseconds into nanoseconds. tv.ts_nsec = this->tv_.tv_usec * 1000; #endif /* ACE_HAS_BROKEN_TIMESPEC_MEMBERS */ return tv; } // Initializes the ACE_Time_Value object from a timespec. inline ACE_Time_Value (const timespec &tv) // : tv_ () { // ACE_OS_TRACE ("ACE_Time_Value"); this->set (tv); } // True if tv1 < tv2. inline friend int operator < (const ACE_Time_Value &tv1, const ACE_Time_Value &tv2) { // ACE_OS_TRACE ("operator <"); return tv2 > tv1; } // True if tv1 >= tv2. inline friend int operator <= (const ACE_Time_Value &tv1, const ACE_Time_Value &tv2) { // ACE_OS_TRACE ("operator <="); return tv2 >= tv1; } // True if tv1 == tv2. inline friend int operator == (const ACE_Time_Value &tv1, const ACE_Time_Value &tv2) { // ACE_OS_TRACE ("operator =="); return tv1.sec () == tv2.sec () && tv1.usec () == tv2.usec (); } // True if tv1 != tv2. inline friend int operator != (const ACE_Time_Value &tv1, const ACE_Time_Value &tv2) { // ACE_OS_TRACE ("operator !="); return !(tv1 == tv2); } // Add TV to this. inline ACE_Time_Value & operator+= (const ACE_Time_Value &tv) { // ACE_OS_TRACE ("operator+="); this->sec (this->sec () + tv.sec ()); this->usec (this->usec () + tv.usec ()); this->normalize (); return *this; } // Subtract TV to this. inline ACE_Time_Value & operator-= (const ACE_Time_Value &tv) { // ACE_OS_TRACE ("operator-="); this->sec (this->sec () - tv.sec ()); this->usec (this->usec () - tv.usec ()); this->normalize (); return *this; } // Adds two ACE_Time_Value objects together, returns the sum. inline friend ACE_Time_Value operator + (const ACE_Time_Value &tv1, const ACE_Time_Value &tv2) { // ACE_OS_TRACE ("operator +"); ACE_Time_Value sum (tv1.sec () + tv2.sec (), tv1.usec () + tv2.usec ()); sum.normalize (); return sum; } // Subtracts two ACE_Time_Value objects, returns the difference. inline friend ACE_Time_Value operator - (const ACE_Time_Value &tv1, const ACE_Time_Value &tv2) { // ACE_OS_TRACE ("operator -"); ACE_Time_Value delta (tv1.sec () - tv2.sec (), tv1.usec () - tv2.usec ()); delta.normalize (); return delta; } # if defined (ACE_WIN32) /// Construct the ACE_Time_Value object from a Win32 FILETIME ACE_Time_Value (const FILETIME &ft); # endif /* ACE_WIN32 */ # if defined (ACE_WIN32) /// Initializes the ACE_Time_Value object from a Win32 FILETIME. void set (const FILETIME &ft); # endif /* ACE_WIN32 */ /// Converts from ACE_Time_Value format into milli-seconds format. /// Increment microseconds as postfix. /** * @note The only reason this is here is to allow the use of ACE_Atomic_Op * with ACE_Time_Value. */ ACE_Time_Value operator++ (int); /// Increment microseconds as prefix. /** * @note The only reason this is here is to allow the use of ACE_Atomic_Op * with ACE_Time_Value. */ ACE_Time_Value &operator++ (void); /// Decrement microseconds as postfix. /** * @note The only reason this is here is to allow the use of ACE_Atomic_Op * with ACE_Time_Value. */ ACE_Time_Value operator-- (int); /// Decrement microseconds as prefix. /** * @note The only reason this is here is to allow the use of ACE_Atomic_Op * with ACE_Time_Value. */ ACE_Time_Value &operator-- (void); //@} /// Dump is a no-op. /** * The dump() method is a no-op. It's here for backwards compatibility * only, but does not dump anything. Invoking logging methods here * violates layering restrictions in ACE because this class is part * of the OS layer and @c ACE_Log_Msg is at a higher level. */ void dump (void) const; # if defined (ACE_WIN32) /// Const time difference between FILETIME and POSIX time. # if defined (ACE_LACKS_LONGLONG_T) static const ACE_U_LongLong FILETIME_to_timval_skew; # else static const DWORDLONG FILETIME_to_timval_skew; # endif // ACE_LACKS_LONGLONG_T # endif /* ACE_WIN32 */ private: /// Put the timevalue into a canonical form. void normalize (void); /// Store the values as a timeval. timeval tv_; }; /** * @class ACE_Countdown_Time * * @brief Keeps track of the amount of elapsed time. * * This class has a side-effect on the <max_wait_time> -- every * time the <stop> method is called the <max_wait_time> is * updated. */ class ACE_Countdown_Time { public: // = Initialization and termination methods. /// Cache the <max_wait_time> and call <start>. ACE_Countdown_Time (ACE_Time_Value *max_wait_time); /// Call <stop>. ~ACE_Countdown_Time (void); /// Cache the current time and enter a start state. int start (void); /// Subtract the elapsed time from max_wait_time_ and enter a stopped /// state. int stop (void); /// Calls stop and then start. max_wait_time_ is modified by the /// call to stop. int update (void); /// Returns 1 if we've already been stopped, else 0. int stopped (void) const; private: /// Maximum time we were willing to wait. ACE_Time_Value *max_wait_time_; /// Beginning of the start time. ACE_Time_Value start_time_; /// Keeps track of whether we've already been stopped. int stopped_; }; #endif /* ACE_TIME_VALUE_H */
[ "xkmld419@126.com" ]
xkmld419@126.com
ac9d63fe41538b2cda349de6285c6b25e8e5b208
5167f77d96d1dc5412a8a0a91c95e3086acd05dc
/src/test/fuzz/multiplication_overflow.cpp
59d2509224c1d0bb44e5da5fa53bc3051612fb0b
[ "MIT" ]
permissive
ocvcoin/ocvcoin
04fb0cea7c11bf52e07ea06ddf9df89631eced5f
79c3803e330f32ed50c02ae657ff9aded6297b9d
refs/heads/master
2023-04-30T10:42:05.457630
2023-04-15T11:49:40
2023-04-15T11:49:40
406,011,904
3
2
null
null
null
null
UTF-8
C++
false
false
1,967
cpp
// Copyright (c) 2020 The Ocvcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <cstdint> #include <string> #include <vector> #if defined(__has_builtin) #if __has_builtin(__builtin_mul_overflow) #define HAVE_BUILTIN_MUL_OVERFLOW #endif #elif defined(__GNUC__) #define HAVE_BUILTIN_MUL_OVERFLOW #endif namespace { template <typename T> void TestMultiplicationOverflow(FuzzedDataProvider& fuzzed_data_provider) { const T i = fuzzed_data_provider.ConsumeIntegral<T>(); const T j = fuzzed_data_provider.ConsumeIntegral<T>(); const bool is_multiplication_overflow_custom = MultiplicationOverflow(i, j); #if defined(HAVE_BUILTIN_MUL_OVERFLOW) T result_builtin; const bool is_multiplication_overflow_builtin = __builtin_mul_overflow(i, j, &result_builtin); assert(is_multiplication_overflow_custom == is_multiplication_overflow_builtin); if (!is_multiplication_overflow_custom) { assert(i * j == result_builtin); } #else if (!is_multiplication_overflow_custom) { (void)(i * j); } #endif } } // namespace FUZZ_TARGET(multiplication_overflow) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); TestMultiplicationOverflow<int64_t>(fuzzed_data_provider); TestMultiplicationOverflow<uint64_t>(fuzzed_data_provider); TestMultiplicationOverflow<int32_t>(fuzzed_data_provider); TestMultiplicationOverflow<uint32_t>(fuzzed_data_provider); TestMultiplicationOverflow<int16_t>(fuzzed_data_provider); TestMultiplicationOverflow<uint16_t>(fuzzed_data_provider); TestMultiplicationOverflow<char>(fuzzed_data_provider); TestMultiplicationOverflow<unsigned char>(fuzzed_data_provider); TestMultiplicationOverflow<signed char>(fuzzed_data_provider); }
[ "contact@ocvcoin.com" ]
contact@ocvcoin.com
04c3e101e7318b7b5aae46f21af0822035089d4a
a483ec5f451f4d6a4455626d3b5e7493f2c44052
/sophomore/软件实训一/71117316-王嘉磊/HW/test.cpp
df4dbc097c2c03df030d26c19980ca18fa1ba830
[]
no_license
wjialei/DuringColloge
8e62587da265e2cf512c6a90990cf41c3beccf40
d899cfb9954e1f8e10dd806d0e0428dfae18ad9b
refs/heads/master
2020-12-13T05:47:05.759575
2020-01-18T05:40:41
2020-01-18T05:40:41
234,324,600
0
0
null
null
null
null
GB18030
C++
false
false
545
cpp
#include "CsolutionThree.h" int main() { solutionThree obj1; int *arr1; int size; unsigned choice; cout << "请输入您所需排列的数字个数" << endl; cin >> size; cout << "请输入您所需排列的数字" << endl; arr1 = new int[size]; for (int i = 0; i < size; i++) { cin >> arr1[i]; } cout << "请选择您的排序方法:\n" << "\t输入'1'代表冒泡排序\n" << "\t输入'2'代表选择排序\n" << "\t输入'3'代表快速排序\n"; cin >> choice; obj1.check(choice, arr1, size); while (1); return 0; }
[ "Jialei_w@163.com" ]
Jialei_w@163.com
93669a4d037816450fdb74a5690a10339bbba626
c3fe4b6e7fc4181248c717492775be1aa2891933
/environment/system_/StellarObject.hpp
ee3a988c7906963a3e67c040028a236514af642b
[]
no_license
WarLib/yapps
3bb358249552ebc9bf77cb3f792c24a5eeedbc96
31f0f28ee7b17265eb9a94c89a445f5c582eaa7a
refs/heads/master
2021-01-01T18:12:02.641347
2013-06-11T13:43:59
2013-06-11T13:43:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
685
hpp
#ifndef _STELLAROBJECT_HPP #define _STELLAROBJECT_HPP #include <OgreVector3.h> #include <OgreString.h> #include "ordinates.hpp" using namespace Yapps; class StellarObject { protected: Vec3 _center; Ogre::Vector3 _rot; double _colonization; double _mass; double _density; Ogre::String mConfigFile; void ReadCfg(const Ogre::String& type, double& den, double& mass); public: StellarObject(Vec3 center, Ogre::Vector3 rot, double colonization); virtual void Update() = 0; const Vec3& GetCenter(void) const; const Ogre::Vector3& GetRotation(void) const; void SetDensity(double density); void SetMass(double mass); double GetRadius(void); }; #endif
[ "tristan.lucas@stud.hn.de" ]
tristan.lucas@stud.hn.de
f8a4c0c05c7c2885deea85d31be2c679ef3a232e
293c17d3eccd920b5b6bf2461897c6d64f683ea3
/DC_ex/MainFrm.h
ae12ba986827b6114aec4e2e3773771ed7ce30de
[]
no_license
709519923/MFC
9d5f0cebada13825573e75e13766139ed713a46d
ac740bb2be8bf4acd15bed14157cfa3411829738
refs/heads/master
2022-11-10T13:47:04.679688
2020-06-28T10:08:31
2020-06-28T10:08:31
268,739,882
0
0
null
null
null
null
GB18030
C++
false
false
1,153
h
// MainFrm.h : CMainFrame 类的接口 // #pragma once class CMainFrame : public CFrameWndEx { protected: // 仅从序列化创建 CMainFrame(); DECLARE_DYNCREATE(CMainFrame) // 特性 public: // 操作 public: // 重写 public: virtual BOOL PreCreateWindow(CREATESTRUCT& cs); virtual BOOL LoadFrame(UINT nIDResource, DWORD dwDefaultStyle = WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, CWnd* pParentWnd = NULL, CCreateContext* pContext = NULL); // 实现 public: virtual ~CMainFrame(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // 控件条嵌入成员 CMFCMenuBar m_wndMenuBar; CMFCToolBar m_wndToolBar; CMFCStatusBar m_wndStatusBar; CMFCToolBarImages m_UserImages; // 生成的消息映射函数 protected: afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnViewCustomize(); afx_msg LRESULT OnToolbarCreateNew(WPARAM wp, LPARAM lp); afx_msg void OnApplicationLook(UINT id); afx_msg void OnUpdateApplicationLook(CCmdUI* pCmdUI); DECLARE_MESSAGE_MAP() public: afx_msg void OnTestInput(); afx_msg void OnBnClickedButton1(); };
[ "709519923@qq.com" ]
709519923@qq.com
83a77183b18609d0027f1c07d0e217aeaca48f8e
4bea57e631734f8cb1c230f521fd523a63c1ff23
/projects/openfoam/rarefied-flows/impingment/sims/test/nozzle1/0.74/T
e8d8410f66819403c593a2f26d74f58f27272258
[]
no_license
andytorrestb/cfal
76217f77dd43474f6b0a7eb430887e8775b78d7f
730fb66a3070ccb3e0c52c03417e3b09140f3605
refs/heads/master
2023-07-04T01:22:01.990628
2021-08-01T15:36:17
2021-08-01T15:36:17
294,183,829
1
0
null
null
null
null
UTF-8
C++
false
false
14,308
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: v1912 | | \\ / A nd | Website: www.openfoam.com | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "0.74"; object T; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 0 0 1 0 0 0]; internalField nonuniform List<scalar> 1900 ( 1 1 1 1 1 1 1 1 1.00003 1.00057 1 1 1 1 1 1 1 1 1.00004 1.0008 1 1 1 1 1 1 1 1 1.00005 1.00095 1 1 1 1 1 1 1 1 1.00004 1.0008 1 1 1 1 1 1 1 1 1.00003 1.00057 1.00242 1.00662 1.01187 1.01862 1.01908 1.00378 1.00969 1.01658 1.02295 1.02685 1.00433 1.0101 1.01647 1.0226 1.02646 1.00378 1.00969 1.01658 1.02295 1.02685 1.00242 1.00662 1.01187 1.01862 1.01908 1.04769 1.05273 1.05477 1.04933 1.04025 1.04521 1.05221 1.05488 1.05189 1.0421 1.04532 1.05246 1.05467 1.05271 1.04018 1.04521 1.05221 1.05488 1.05189 1.0421 1.04769 1.05273 1.05477 1.04933 1.04025 0.957339 0.874382 0.900726 0.920425 0.943837 0.967392 0.987233 0.997442 0.999826 0.999997 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999997 0.99979 0.99689 0.984359 0.959569 0.927987 0.892841 0.840384 0.740045 0.749186 1.005 0.908452 0.910418 0.920432 0.944 0.96741 0.98725 0.997443 0.999826 0.999997 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999997 0.99979 0.99689 0.984359 0.959569 0.927987 0.892841 0.840384 0.740045 0.749186 1.00264 0.929689 0.912828 0.9202 0.944094 0.967438 0.987253 0.997444 0.999826 0.999997 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999997 0.99979 0.99689 0.984359 0.959569 0.927987 0.892841 0.840384 0.740045 0.749186 1.005 0.908452 0.910418 0.920432 0.944 0.96741 0.98725 0.997443 0.999826 0.999997 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999997 0.99979 0.99689 0.984359 0.959569 0.927987 0.892841 0.840384 0.740045 0.749186 0.957339 0.874382 0.900726 0.920425 0.943837 0.967392 0.987233 0.997442 0.999826 0.999997 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999997 0.99979 0.99689 0.984359 0.959569 0.927987 0.892841 0.840384 0.740045 0.749186 0.815783 0.81307 0.880637 0.916646 0.942372 0.966749 0.986961 0.997403 0.999826 0.999997 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999997 0.99979 0.99689 0.984359 0.959569 0.927987 0.892841 0.840384 0.740045 0.749186 0.761156 0.766615 0.862592 0.909484 0.938412 0.964763 0.986226 0.997267 0.999817 0.999997 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999997 0.99979 0.99689 0.984359 0.959569 0.927987 0.892841 0.840384 0.740045 0.749186 0.754029 0.753247 0.853532 0.90319 0.934237 0.962574 0.985399 0.997093 0.999804 0.999997 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999997 0.99979 0.99689 0.984359 0.959569 0.927987 0.892841 0.840384 0.740045 0.749186 0.753236 0.746237 0.846915 0.897752 0.930752 0.960815 0.984756 0.99696 0.999794 0.999997 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999997 0.99979 0.99689 0.984359 0.959569 0.927987 0.892841 0.840384 0.740045 0.749186 0.751414 0.742012 0.842394 0.894267 0.928725 0.959874 0.984444 0.996902 0.99979 0.999997 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999997 0.99979 0.99689 0.984359 0.959569 0.927987 0.892841 0.840384 0.740045 0.749186 0.749736 0.740335 0.840651 0.893022 0.928073 0.959601 0.984366 0.99689 0.99979 0.999997 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999997 0.99979 0.99689 0.984359 0.959569 0.927987 0.892841 0.840384 0.740045 0.749186 0.749225 0.740059 0.840394 0.892848 0.92799 0.95957 0.984359 0.99689 0.99979 0.999997 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999997 0.99979 0.99689 0.984359 0.959569 0.927987 0.892841 0.840384 0.740045 0.749186 0.749187 0.740045 0.840384 0.892841 0.927987 0.959569 0.984359 0.99689 0.99979 0.999997 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999997 0.99979 0.99689 0.984359 0.959569 0.927987 0.892841 0.840384 0.740045 0.749186 0.749186 0.740045 0.840384 0.892841 0.927987 0.959569 0.984359 0.99689 0.99979 0.999997 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999997 0.99979 0.99689 0.984359 0.959569 0.927987 0.892841 0.840384 0.740045 0.749186 0.749186 0.740045 0.840384 0.892841 0.927987 0.959569 0.984359 0.99689 0.99979 0.999997 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999997 0.99979 0.99689 0.984359 0.959569 0.927987 0.892841 0.840384 0.740045 0.749186 0.749185 0.740044 0.84038 0.892836 0.927981 0.959562 0.98435 0.996881 0.999781 0.999988 0.999991 0.999991 0.999991 0.999991 0.999991 0.999991 0.999991 0.999991 0.999991 0.999991 0.999991 0.999991 0.999991 0.999991 0.999991 0.999991 0.999991 0.999991 0.999991 0.999991 0.999988 0.999781 0.996881 0.98435 0.959562 0.927981 0.892836 0.84038 0.740044 0.749185 0.74909 0.739912 0.840166 0.892561 0.927655 0.959197 0.983959 0.996477 0.999375 0.999582 0.999585 0.999585 0.999585 0.999585 0.999585 0.999585 0.999585 0.999585 0.999585 0.999585 0.999585 0.999585 0.999585 0.999585 0.999585 0.999585 0.999585 0.999585 0.999585 0.999585 0.999582 0.999375 0.996477 0.983959 0.959197 0.927655 0.892561 0.840166 0.739912 0.74909 0.747354 0.737908 0.837392 0.889329 0.924034 0.955294 0.979856 0.992276 0.995149 0.995354 0.995357 0.995357 0.995357 0.995357 0.995357 0.995357 0.995357 0.995357 0.995357 0.995357 0.995357 0.995357 0.995357 0.995357 0.995357 0.995357 0.995357 0.995357 0.995357 0.995357 0.995354 0.995149 0.992276 0.979856 0.955294 0.924034 0.889329 0.837392 0.737908 0.747354 0.738362 0.728742 0.826012 0.876882 0.910688 0.941281 0.965323 0.977449 0.980238 0.980436 0.980439 0.980439 0.980439 0.980439 0.980439 0.980439 0.980439 0.980439 0.980439 0.980439 0.980439 0.980439 0.980439 0.980439 0.980439 0.980439 0.980439 0.980439 0.980439 0.980439 0.980436 0.980238 0.977449 0.965323 0.941281 0.910688 0.876882 0.826012 0.728742 0.738362 0.718831 0.710283 0.804203 0.853821 0.886645 0.916435 0.939743 0.951386 0.954022 0.954204 0.954207 0.954207 0.954207 0.954207 0.954207 0.954207 0.954207 0.954207 0.954207 0.954207 0.954207 0.954207 0.954207 0.954207 0.954207 0.954207 0.954207 0.954207 0.954207 0.954207 0.954204 0.954022 0.951386 0.939743 0.916435 0.886645 0.853821 0.804203 0.710283 0.718831 0.693541 0.687547 0.777227 0.82536 0.857465 0.886495 0.909009 0.92005 0.922477 0.922638 0.92264 0.92264 0.92264 0.92264 0.92264 0.92264 0.92264 0.92264 0.92264 0.92264 0.92264 0.92264 0.92264 0.92264 0.92264 0.92264 0.92264 0.92264 0.92264 0.92264 0.922638 0.922477 0.92005 0.909009 0.886495 0.857465 0.82536 0.777227 0.687547 0.693541 0.670506 0.663607 0.748093 0.794789 0.826065 0.854352 0.875879 0.886113 0.88826 0.888394 0.888396 0.888396 0.888396 0.888396 0.888396 0.888396 0.888396 0.888396 0.888396 0.888396 0.888396 0.888396 0.888396 0.888396 0.888396 0.888396 0.888396 0.888396 0.888396 0.888396 0.888394 0.88826 0.886113 0.875879 0.854352 0.826065 0.794789 0.748093 0.663607 0.670506 0.634606 0.63022 0.7074 0.748593 0.778421 0.805248 0.825521 0.834789 0.836604 0.836706 0.836707 0.836707 0.836707 0.836707 0.836707 0.836707 0.836707 0.836707 0.836707 0.836707 0.836707 0.836707 0.836707 0.836707 0.836707 0.836707 0.836707 0.836707 0.836707 0.836707 0.836706 0.836604 0.834789 0.825521 0.805248 0.778421 0.748593 0.7074 0.63022 0.634606 0.569977 0.560091 0.628623 0.662067 0.686475 0.708998 0.726028 0.733395 0.734683 0.734745 0.734746 0.734746 0.734746 0.734746 0.734746 0.734746 0.734746 0.734746 0.734746 0.734746 0.734746 0.734746 0.734746 0.734746 0.734746 0.734746 0.734746 0.734746 0.734746 0.734746 0.734745 0.734683 0.733395 0.726028 0.708998 0.686475 0.662067 0.628623 0.560091 0.569977 0.581099 0.569735 0.631762 0.667861 0.691628 0.716566 0.734417 0.741488 0.742563 0.742605 0.742606 0.742606 0.742606 0.742606 0.742606 0.742606 0.742606 0.742606 0.742606 0.742606 0.742606 0.742606 0.742606 0.742606 0.742606 0.742606 0.742606 0.742606 0.742606 0.742606 0.742605 0.742563 0.741488 0.734417 0.716566 0.691628 0.667861 0.631762 0.569735 0.581099 0.581099 0.569735 0.631762 0.667861 0.691628 0.716566 0.734417 0.741488 0.742563 0.742605 0.742606 0.742606 0.742606 0.742606 0.742606 0.742606 0.742606 0.742606 0.742606 0.742606 0.742606 0.742606 0.742606 0.742606 0.742606 0.742606 0.742606 0.742606 0.742606 0.742606 0.742605 0.742563 0.741488 0.734417 0.716566 0.691628 0.667861 0.631762 0.569735 0.581099 0.569977 0.560091 0.628623 0.662067 0.686475 0.708998 0.726028 0.733395 0.734683 0.734745 0.734746 0.734746 0.734746 0.734746 0.734746 0.734746 0.734746 0.734746 0.734746 0.734746 0.734746 0.734746 0.734746 0.734746 0.734746 0.734746 0.734746 0.734746 0.734746 0.734746 0.734745 0.734683 0.733395 0.726028 0.708998 0.686475 0.662067 0.628623 0.560091 0.569977 0.634606 0.63022 0.7074 0.748593 0.778421 0.805248 0.825521 0.834789 0.836604 0.836706 0.836707 0.836707 0.836707 0.836707 0.836707 0.836707 0.836707 0.836707 0.836707 0.836707 0.836707 0.836707 0.836707 0.836707 0.836707 0.836707 0.836707 0.836707 0.836707 0.836707 0.836706 0.836604 0.834789 0.825521 0.805248 0.778421 0.748593 0.7074 0.63022 0.634606 0.670506 0.663607 0.748093 0.794789 0.826065 0.854352 0.875879 0.886113 0.88826 0.888394 0.888396 0.888396 0.888396 0.888396 0.888396 0.888396 0.888396 0.888396 0.888396 0.888396 0.888396 0.888396 0.888396 0.888396 0.888396 0.888396 0.888396 0.888396 0.888396 0.888396 0.888394 0.88826 0.886113 0.875879 0.854352 0.826065 0.794789 0.748093 0.663607 0.670506 0.693541 0.687547 0.777227 0.82536 0.857465 0.886495 0.909009 0.92005 0.922477 0.922638 0.92264 0.92264 0.92264 0.92264 0.92264 0.92264 0.92264 0.92264 0.92264 0.92264 0.92264 0.92264 0.92264 0.92264 0.92264 0.92264 0.92264 0.92264 0.92264 0.92264 0.922638 0.922477 0.92005 0.909009 0.886495 0.857465 0.82536 0.777227 0.687547 0.693541 0.718831 0.710283 0.804203 0.853821 0.886645 0.916435 0.939743 0.951386 0.954022 0.954204 0.954207 0.954207 0.954207 0.954207 0.954207 0.954207 0.954207 0.954207 0.954207 0.954207 0.954207 0.954207 0.954207 0.954207 0.954207 0.954207 0.954207 0.954207 0.954207 0.954207 0.954204 0.954022 0.951386 0.939743 0.916435 0.886645 0.853821 0.804203 0.710283 0.718831 0.738362 0.728742 0.826012 0.876882 0.910688 0.941281 0.965323 0.977449 0.980238 0.980436 0.980439 0.980439 0.980439 0.980439 0.980439 0.980439 0.980439 0.980439 0.980439 0.980439 0.980439 0.980439 0.980439 0.980439 0.980439 0.980439 0.980439 0.980439 0.980439 0.980439 0.980436 0.980238 0.977449 0.965323 0.941281 0.910688 0.876882 0.826012 0.728742 0.738362 0.747354 0.737908 0.837392 0.889329 0.924034 0.955294 0.979856 0.992276 0.995149 0.995354 0.995357 0.995357 0.995357 0.995357 0.995357 0.995357 0.995357 0.995357 0.995357 0.995357 0.995357 0.995357 0.995357 0.995357 0.995357 0.995357 0.995357 0.995357 0.995357 0.995357 0.995354 0.995149 0.992276 0.979856 0.955294 0.924034 0.889329 0.837392 0.737908 0.747354 0.74909 0.739912 0.840166 0.892561 0.927655 0.959197 0.983959 0.996477 0.999375 0.999582 0.999585 0.999585 0.999585 0.999585 0.999585 0.999585 0.999585 0.999585 0.999585 0.999585 0.999585 0.999585 0.999585 0.999585 0.999585 0.999585 0.999585 0.999585 0.999585 0.999585 0.999582 0.999375 0.996477 0.983959 0.959197 0.927655 0.892561 0.840166 0.739912 0.74909 0.749185 0.740044 0.84038 0.892836 0.927981 0.959562 0.98435 0.996881 0.999781 0.999988 0.999991 0.999991 0.999991 0.999991 0.999991 0.999991 0.999991 0.999991 0.999991 0.999991 0.999991 0.999991 0.999991 0.999991 0.999991 0.999991 0.999991 0.999991 0.999991 0.999991 0.999988 0.999781 0.996881 0.98435 0.959562 0.927981 0.892836 0.84038 0.740044 0.749185 0.749186 0.740045 0.840384 0.892841 0.927987 0.959569 0.984359 0.99689 0.99979 0.999997 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999997 0.99979 0.99689 0.984359 0.959569 0.927987 0.892841 0.840384 0.740045 0.749186 0.749186 0.740045 0.840384 0.892841 0.927987 0.959569 0.984359 0.99689 0.99979 0.999997 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999997 0.99979 0.99689 0.984359 0.959569 0.927987 0.892841 0.840384 0.740045 0.749186 0.749187 0.740045 0.840384 0.892841 0.927987 0.959569 0.984359 0.99689 0.99979 0.999997 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999997 0.99979 0.99689 0.984359 0.959569 0.927987 0.892841 0.840384 0.740045 0.749186 0.749225 0.740059 0.840394 0.892848 0.92799 0.95957 0.984359 0.99689 0.99979 0.999997 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999997 0.99979 0.99689 0.984359 0.959569 0.927987 0.892841 0.840384 0.740045 0.749186 0.749736 0.740335 0.840651 0.893022 0.928073 0.959601 0.984366 0.99689 0.99979 0.999997 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999997 0.99979 0.99689 0.984359 0.959569 0.927987 0.892841 0.840384 0.740045 0.749186 0.751414 0.742012 0.842394 0.894267 0.928725 0.959874 0.984444 0.996902 0.99979 0.999997 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999997 0.99979 0.99689 0.984359 0.959569 0.927987 0.892841 0.840384 0.740045 0.749186 0.753236 0.746237 0.846915 0.897752 0.930752 0.960815 0.984756 0.99696 0.999794 0.999997 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999997 0.99979 0.99689 0.984359 0.959569 0.927987 0.892841 0.840384 0.740045 0.749186 0.754029 0.753247 0.853532 0.90319 0.934237 0.962574 0.985399 0.997093 0.999804 0.999997 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999997 0.99979 0.99689 0.984359 0.959569 0.927987 0.892841 0.840384 0.740045 0.749186 0.761156 0.766615 0.862592 0.909484 0.938412 0.964763 0.986226 0.997267 0.999817 0.999997 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999997 0.99979 0.99689 0.984359 0.959569 0.927987 0.892841 0.840384 0.740045 0.749186 0.815783 0.81307 0.880637 0.916646 0.942372 0.966749 0.986961 0.997403 0.999826 0.999997 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999997 0.99979 0.99689 0.984359 0.959569 0.927987 0.892841 0.840384 0.740045 0.749186 ) ; boundaryField { inlet { type fixedValue; value uniform 1; } outlet { type zeroGradient; } obstacle { type zeroGradient; } empty { type empty; } } // ************************************************************************* //
[ "andytorrestb@gmail.com" ]
andytorrestb@gmail.com
4e414fa1dd574c3ac7c26f61efa31af307588902
037d518773420f21d74079ee492827212ba6e434
/blazetest/src/mathtest/smatdmatmult/MIbM3x3a.cpp
1b1bccfe1f5dbbe015cbc33e648e584a8eb506bc
[ "BSD-3-Clause" ]
permissive
chkob/forked-blaze
8d228f3e8d1f305a9cf43ceaba9d5fcd603ecca8
b0ce91c821608e498b3c861e956951afc55c31eb
refs/heads/master
2021-09-05T11:52:03.715469
2018-01-27T02:31:51
2018-01-27T02:31:51
112,014,398
0
0
null
null
null
null
UTF-8
C++
false
false
3,741
cpp
//================================================================================================= /*! // \file src/mathtest/smatdmatmult/MIbM3x3a.cpp // \brief Source file for the MIbM3x3a sparse matrix/dense matrix multiplication math test // // Copyright (C) 2012-2018 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/IdentityMatrix.h> #include <blaze/math/StaticMatrix.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/smatdmatmult/OperationTest.h> #include <blazetest/system/MathTest.h> //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'MIbM3x3a'..." << std::endl; using blazetest::mathtest::TypeA; using blazetest::mathtest::TypeB; try { // Matrix type definitions typedef blaze::IdentityMatrix<TypeB> MIb; typedef blaze::StaticMatrix<TypeA,3UL,3UL> M3x3a; // Creator type definitions typedef blazetest::Creator<MIb> CMIb; typedef blazetest::Creator<M3x3a> CM3x3a; // Running the tests RUN_SMATDMATMULT_OPERATION_TEST( CMIb( 3UL ), CM3x3a() ); } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during sparse matrix/dense matrix multiplication:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
[ "klaus.iglberger@gmail.com" ]
klaus.iglberger@gmail.com
08fdda7e113b9b96ab0e721f4866dd403a22d534
4a08f6c5ab847d9aea0810629b7b30d3e9997b00
/vendor/imgui/imconfig.h
ea609edb98b83d1f8dde03898787ae546847c91e
[ "MIT" ]
permissive
brandonpelfrey/qnes
48ed9494e38f575ef9268b16870d5857d427e1ce
7ccf5cd65f297e6dad95f36942aef74d378cd082
refs/heads/master
2020-07-30T12:20:02.625805
2019-11-18T17:29:46
2019-11-18T17:29:46
210,231,937
1
0
null
null
null
null
UTF-8
C++
false
false
6,547
h
//----------------------------------------------------------------------------- // COMPILE-TIME OPTIONS FOR DEAR IMGUI // Runtime options (clipboard callbacks, enabling various features, etc.) can generally be set via the ImGuiIO structure. // You can use ImGui::SetAllocatorFunctions() before calling ImGui::CreateContext() to rewire memory allocation functions. //----------------------------------------------------------------------------- // A) You may edit imconfig.h (and not overwrite it when updating Dear ImGui, or maintain a patch/branch with your modifications to imconfig.h) // B) or add configuration directives in your own file and compile with #define IMGUI_USER_CONFIG "myfilename.h" // If you do so you need to make sure that configuration settings are defined consistently _everywhere_ Dear ImGui is used, which include // the imgui*.cpp files but also _any_ of your code that uses Dear ImGui. This is because some compile-time options have an affect on data structures. // Defining those options in imconfig.h will ensure every compilation unit gets to see the same data structure layouts. // Call IMGUI_CHECKVERSION() from your .cpp files to verify that the data structures your files are using are matching the ones imgui.cpp is using. //----------------------------------------------------------------------------- #pragma once //---- Define assertion handler. Defaults to calling assert(). //#define IM_ASSERT(_EXPR) MyAssert(_EXPR) //#define IM_ASSERT(_EXPR) ((void)(_EXPR)) // Disable asserts //---- Define attributes of all API symbols declarations, e.g. for DLL under Windows // Using dear imgui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility. //#define IMGUI_API __declspec( dllexport ) //#define IMGUI_API __declspec( dllimport ) //---- Don't define obsolete functions/enums names. Consider enabling from time to time after updating to avoid using soon-to-be obsolete function/names. //#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS //---- Don't implement demo windows functionality (ShowDemoWindow()/ShowStyleEditor()/ShowUserGuide() methods will be empty) // It is very strongly recommended to NOT disable the demo windows during development. Please read the comments in imgui_demo.cpp. //#define IMGUI_DISABLE_DEMO_WINDOWS //#define IMGUI_DISABLE_METRICS_WINDOW //---- Don't implement some functions to reduce linkage requirements. //#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // [Win32] Don't implement default clipboard handler. Won't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc. //#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] Don't implement default IME handler. Won't use and link with ImmGetContext/ImmSetCompositionWindow. //#define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use and link with any Win32 function (clipboard, ime). //#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS // [OSX] Implement default OSX clipboard handler (need to link with '-framework ApplicationServices'). //#define IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS // Don't implement ImFormatString/ImFormatStringV so you can implement them yourself if you don't want to link with vsnprintf. //#define IMGUI_DISABLE_MATH_FUNCTIONS // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 wrapper so you can implement them yourself. Declare your prototypes in imconfig.h. //#define IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement default allocators calling malloc()/free() to avoid linking with them. You will need to call ImGui::SetAllocatorFunctions(). //---- Include imgui_user.h at the end of imgui.h as a convenience //#define IMGUI_INCLUDE_IMGUI_USER_H //---- Pack colors to BGRA8 instead of RGBA8 (to avoid converting from one to another) //#define IMGUI_USE_BGRA_PACKED_COLOR //---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version // By default the embedded implementations are declared static and not available outside of imgui cpp files. //#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h" //#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h" //#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION //#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION //---- Define constructor and implicit cast operators to convert back<>forth between your math types and ImVec2/ImVec4. // This will be inlined as part of ImVec2 and ImVec4 class declarations. /* #define IM_VEC2_CLASS_EXTRA \ ImVec2(const MyVec2& f) { x = f.x; y = f.y; } \ operator MyVec2() const { return MyVec2(x,y); } #define IM_VEC4_CLASS_EXTRA \ ImVec4(const MyVec4& f) { x = f.x; y = f.y; z = f.z; w = f.w; } \ operator MyVec4() const { return MyVec4(x,y,z,w); } */ //---- Using 32-bits vertex indices (default is 16-bits) is one way to allow large meshes with more than 64K vertices. // Your renderer back-end will need to support it (most example renderer back-ends support both 16/32-bits indices). // Another way to allow large meshes while keeping 16-bits indices is to handle ImDrawCmd::VtxOffset in your renderer. // Read about ImGuiBackendFlags_RendererHasVtxOffset for details. //#define ImDrawIdx unsigned int //---- Override ImDrawCallback signature (will need to modify renderer back-ends accordingly) //struct ImDrawList; //struct ImDrawCmd; //typedef void (*MyImDrawCallback)(const ImDrawList* draw_list, const ImDrawCmd* cmd, void* my_renderer_user_data); //#define ImDrawCallback MyImDrawCallback //---- Debug Tools // Use 'Metrics->Tools->Item Picker' to pick widgets with the mouse and break into them for easy debugging. //#define IM_DEBUG_BREAK IM_ASSERT(0) //#define IM_DEBUG_BREAK __debugbreak() // Have the Item Picker break in the ItemAdd() function instead of ItemHoverable() - which is earlier in the code, will catch a few extra items, allow picking items other than Hovered one. // This adds a small runtime cost which is why it is not enabled by default. //#define IMGUI_DEBUG_TOOL_ITEM_PICKER_EX //---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files. /* namespace ImGui { void MyFunction(const char* name, const MyMatrix44& v); } */ #define IMGUI_IMPL_OPENGL_LOADER_GLAD
[ "brandonpelfrey@gmail.com" ]
brandonpelfrey@gmail.com
f6724b747d0d1b72c14acb2820c02af327694339
f81124e4a52878ceeb3e4b85afca44431ce68af2
/re20_1/processor17/55/U
2f20398b6f1112f3c97d7ecdfb8ca76a8409e464
[]
no_license
chaseguy15/coe-of2
7f47a72987638e60fd7491ee1310ee6a153a5c10
dc09e8d5f172489eaa32610e08e1ee7fc665068c
refs/heads/master
2023-03-29T16:59:14.421456
2021-04-06T23:26:52
2021-04-06T23:26:52
355,040,336
0
1
null
null
null
null
UTF-8
C++
false
false
6,287
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 7 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volVectorField; location "55"; object U; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 1 -1 0 0 0 0]; internalField nonuniform List<vector> 36 ( (1.15052 0.272492 7.46604e-21) (1.11827 0.407813 -5.60506e-20) (1.02661 0.513139 1.36614e-20) (1.05364 0.467265 -3.81871e-20) (0.901061 0.552473 -1.86104e-20) (0.719359 0.547328 -9.03796e-20) (0.472961 0.457504 -1.37183e-19) (0.406086 0.446188 -4.67738e-20) (0.14809 0.212641 7.016e-19) (0.114247 0.191124 -5.59539e-19) (0.114247 -0.191124 6.489e-20) (0.14809 -0.212641 -2.06958e-19) (0.406086 -0.446188 2.23342e-19) (0.472961 -0.457504 -3.93746e-20) (0.719359 -0.547328 -4.22851e-20) (0.901061 -0.552473 1.86104e-20) (1.02661 -0.513139 -1.36614e-20) (1.05364 -0.467265 3.81871e-20) (1.11827 -0.407813 5.60506e-20) (1.15052 -0.272492 -7.46604e-21) (1.1298 0.089771 5.64791e-21) (1.12537 0.0729609 8.93299e-22) (1.12142 0.0577549 5.66175e-21) (1.11812 0.0437553 -7.45876e-21) (1.11561 0.0306378 1.99383e-21) (1.11395 0.018116 7.7176e-22) (1.11318 0.00588342 -6.39564e-23) (1.13884 -0.130414 1.20065e-21) (1.13442 -0.108683 -1.00189e-20) (1.1298 -0.089771 1.81238e-22) (1.12537 -0.0729609 -8.93299e-22) (1.12142 -0.0577549 -5.66175e-21) (1.11812 -0.0437553 7.45876e-21) (1.11561 -0.0306378 -1.99383e-21) (1.11395 -0.018116 -7.7176e-22) (1.11318 -0.00588342 6.39564e-23) ) ; boundaryField { inlet { type uniformFixedValue; uniformValue constant (1 0 0); value nonuniform 0(); } outlet { type pressureInletOutletVelocity; value nonuniform 0(); } cylinder { type fixedValue; value uniform (0 0 0); } top { type symmetryPlane; } bottom { type symmetryPlane; } defaultFaces { type empty; } procBoundary17to14 { type processor; value nonuniform List<vector> 2((1.11899 0.0918582 2.70779e-20) (1.12442 -0.133237 -2.07606e-20)); } procBoundary17to15 { type processor; value nonuniform List<vector> 17 ( (1.11357 0.276401 -1.06798e-19) (0.991462 0.468284 -8.74672e-20) (1.11357 -0.276401 1.06798e-19) (1.11566 0.0746546 8.8898e-21) (1.11249 0.0590828 8.35661e-21) (1.10976 0.0447499 1.57082e-22) (1.10763 0.0313274 -4.05894e-21) (1.10622 0.0185153 -1.35636e-22) (1.10559 0.00601699 1.75297e-21) (1.12211 -0.111174 3.23841e-21) (1.11899 -0.0918582 -2.70779e-20) (1.11566 -0.0746546 1.08178e-20) (1.11249 -0.0590828 -8.35661e-21) (1.10976 -0.0447499 -1.57082e-22) (1.10763 -0.0313274 4.05894e-21) (1.10622 -0.0185153 1.35636e-22) (1.10559 -0.00601699 -1.75297e-21) ) ; } procBoundary17to16 { type processor; value nonuniform List<vector> 33 ( (1.1476 0.220815 5.58924e-21) (1.118 0.359188 2.27727e-20) (1.06442 0.413466 8.04465e-21) (0.961112 0.521508 -6.30893e-20) (1.06442 0.413466 8.04465e-21) (0.961112 0.521508 -6.30893e-20) (0.82874 0.555551 -2.51516e-20) (0.82874 0.555551 -2.51516e-20) (0.644525 0.54329 -3.4326e-19) (0.644525 0.54329 -3.4326e-19) (0.566593 0.520049 4.3856e-19) (0.338331 0.416374 1.36539e-19) (0.338331 0.416374 1.36539e-19) (0.273998 0.368822 -8.41124e-20) (0.0836222 0.160003 8.69825e-20) (0.0836222 -0.160003 -4.27155e-19) (0.273998 -0.368822 1.2094e-19) (0.338331 -0.416374 -1.73365e-19) (0.338331 -0.416374 -1.73365e-19) (0.566593 -0.520049 -5.32022e-20) (0.644525 -0.54329 9.06177e-20) (0.644525 -0.54329 9.06177e-20) (0.82874 -0.555551 9.31391e-20) (0.82874 -0.555551 9.31391e-20) (0.961112 -0.521508 6.30893e-20) (0.961112 -0.521508 6.30893e-20) (0.991462 -0.468284 4.98808e-20) (1.06442 -0.413466 -8.04465e-21) (1.06442 -0.413466 -8.04465e-21) (1.118 -0.359188 -2.27727e-20) (1.1476 -0.220815 -5.58924e-21) (1.13442 0.108683 -1.77804e-20) (1.14248 -0.155429 -2.19987e-21) ) ; } procBoundary17to18 { type processor; value nonuniform List<vector> 30 ( (1.16754 0.394 -2.6229e-20) (1.15746 0.309405 -6.56068e-21) (1.08407 0.49158 -9.14354e-20) (1.111 0.455517 3.63567e-21) (1.111 0.455517 3.63567e-21) (0.965115 0.53314 2.60858e-20) (0.965115 0.53314 2.60858e-20) (0.786682 0.532705 -1.53944e-20) (0.786682 0.532705 -1.53944e-20) (0.534601 0.45058 -5.84543e-20) (0.534601 0.45058 -5.84543e-20) (0.215386 0.224546 4.61803e-20) (0.182656 0.223804 1.09363e-19) (0.182656 0.223804 1.09363e-19) (0.182656 -0.223804 8.242e-20) (0.182656 -0.223804 8.242e-20) (0.215386 -0.224546 -3.46963e-20) (0.534601 -0.45058 3.62983e-20) (0.534601 -0.45058 3.62983e-20) (0.786682 -0.532705 -1.60823e-20) (0.786682 -0.532705 -1.60823e-20) (0.965115 -0.53314 -2.60858e-20) (0.965115 -0.53314 -2.60858e-20) (1.08407 -0.49158 9.14354e-20) (1.111 -0.455517 -3.63567e-21) (1.111 -0.455517 -3.63567e-21) (1.16754 -0.394 2.6229e-20) (1.15746 -0.309405 6.56068e-21) (1.14059 0.0874465 7.0728e-21) (1.15319 -0.127016 -1.65077e-21) ) ; } procBoundary17to19 { type processor; value nonuniform List<vector> 16 ( (1.1859 0.264373 5.279e-21) (1.1859 -0.264373 -5.279e-21) (1.13509 0.0711056 6.69493e-21) (1.13035 0.0563151 -4.76031e-21) (1.12649 0.0426849 1.74297e-21) (1.12357 0.029901 3.38618e-21) (1.12164 0.0176954 -2.396e-21) (1.12073 0.00575835 -4.66349e-22) (1.14669 -0.105825 2.96594e-21) (1.14059 -0.0874465 -7.0728e-21) (1.13509 -0.0711056 -1.00576e-21) (1.13035 -0.0563151 4.76031e-21) (1.12649 -0.0426849 -1.74297e-21) (1.12357 -0.029901 -3.38618e-21) (1.12164 -0.0176954 2.396e-21) (1.12073 -0.00575835 4.66349e-22) ) ; } } // ************************************************************************* //
[ "chaseguy15" ]
chaseguy15
6762fc3f374f6cb5cac39cadf1e6ee70d11700d0
3a6c1dc2afcbf5321e3610e3a710eeffacf435cb
/chrome/browser/web_applications/preinstalled_web_apps/calculator.cc
5f8010f561da29da625e315de2177dcd88512b2b
[ "BSD-3-Clause" ]
permissive
phimuemue/chromium
9840da796dcef3c5813594f78296afa4da7b5e13
48ed0496d86ea75a4788000ceefbb2eb80971d34
refs/heads/main
2023-08-17T14:07:11.247730
2021-09-23T06:07:06
2021-09-23T06:07:06
409,474,698
0
0
BSD-3-Clause
2021-09-23T06:28:43
2021-09-23T06:28:42
null
UTF-8
C++
false
false
3,655
cc
// Copyright 2021 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 "chrome/browser/web_applications/preinstalled_web_apps/calculator.h" #include "base/bind.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/web_applications/preinstalled_app_install_features.h" #include "chrome/browser/web_applications/preinstalled_web_apps/preinstalled_web_app_definition_utils.h" #include "chrome/browser/web_applications/web_application_info.h" #include "chrome/grit/preinstalled_web_apps_resources.h" namespace web_app { namespace { // clang-format off constexpr Translation kNameTranslations[] = { {"am", u8"ሒሳብ ማስያ ማሽን"}, {"ar", u8"الآلة الحاسبة"}, {"bg", u8"Калкулатор"}, {"bn", u8"ক্যালকুলেটর"}, {"ca", u8"Calculadora"}, {"cs", u8"Kalkulačka"}, {"da", u8"Lommeregner"}, {"de", u8"Rechner"}, {"el", u8"Αριθμομηχανή"}, {"en-GB", u8"Calculator"}, {"en", u8"Calculator"}, {"es-419", u8"Calculadora"}, {"es", u8"Calculadora"}, {"et", u8"Kalkulaator"}, {"fa", u8"ماشین حساب"}, {"fil", u8"Calculator"}, {"fi", u8"Laskin"}, {"fr", u8"Calculatrice"}, {"gu", u8"કેલ્ક્યુલેટર"}, {"hi", u8"कैल्‍क्‍यूलेटर"}, {"hr", u8"Kalkulator"}, {"hu", u8"Számológép"}, {"id", u8"Kalkulator"}, {"it", u8"Calcolatrice"}, {"iw", u8"מחשבון"}, {"ja", u8"電卓"}, {"kn", u8"ಕ್ಯಾಲ್ಕುಲೇಟರ್"}, {"ko", u8"계산기"}, {"lt", u8"Skaičiuotuvas"}, {"lv", u8"Kalkulators"}, {"ml", u8"കാൽക്കുലേറ്റർ"}, {"mr", u8"कॅलक्युलेटर"}, {"ms", u8"Kalkulator"}, {"nl", u8"Rekenmachine"}, {"no", u8"Kalkulator"}, {"pl", u8"Kalkulator"}, {"pt-BR", u8"Calculadora"}, {"pt-PT", u8"Calculadora"}, {"ro", u8"Calculator"}, {"ru", u8"Калькулятор"}, {"sk", u8"Kalkulačka"}, {"sl", u8"Računalo"}, {"sr", u8"Калкулатор"}, {"sv", u8"Kalkylator"}, {"sw", u8"Kikokotoo"}, {"ta", u8"கால்குலேட்டர்"}, {"te", u8"కాలిక్యులేటర్"}, {"th", u8"เครื่องคิดเลข"}, {"tr", u8"Hesap Makinesi"}, {"uk", u8"Калькулятор"}, {"vi", u8"Máy tính"}, {"zh-CN", u8"计算器"}, {"zh-TW", u8"計算機"}, }; // clang-format on } // namespace ExternalInstallOptions GetConfigForCalculator() { ExternalInstallOptions options( /*install_url=*/GURL("https://calculator.apps.chrome/install"), /*user_display_mode=*/DisplayMode::kStandalone, /*install_source=*/ExternalInstallSource::kExternalDefault); options.user_type_allowlist = {"unmanaged", "managed", "child"}; options.gate_on_feature = kDefaultCalculatorWebApp.name; options.uninstall_and_replace.push_back("joodangkbfjnajiiifokapkpmhfnpleo"); options.only_use_app_info_factory = true; options.app_info_factory = base::BindRepeating([]() { auto info = std::make_unique<WebApplicationInfo>(); info->title = base::UTF8ToUTF16(GetTranslatedName("Calculator", kNameTranslations)); info->start_url = GURL("https://calculator.apps.chrome/"); info->scope = GURL("https://calculator.apps.chrome/"); info->display_mode = DisplayMode::kStandalone; info->icon_bitmaps.any = LoadBundledIcons({IDR_PREINSTALLED_WEB_APPS_CALCULATOR_ICON_256_PNG}); info->background_color = 0xFFFFFFFF; return info; }); return options; } } // namespace web_app
[ "chromium-scoped@luci-project-accounts.iam.gserviceaccount.com" ]
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
e717fdf4a23bbf49e460b36abe18a9f78fb6c5c5
dba71de476fcacc100bae64ed0d0a85561f99baf
/branches/2.0/doubango/plugins/pluginDirectShow/plugin_video_dshow_consumer.cxx
1fe2d2cbe9a06c48a4098fcb60ffdad97f5c0381
[]
no_license
svn2github/doubango
4053dd07245277234a8fb82070e17bba392f19ad
fc958eca8a4285145713315f03bd552dac569a21
refs/heads/master
2023-09-03T09:17:34.081239
2015-08-20T16:02:32
2015-08-20T16:02:32
28,213,396
2
0
null
null
null
null
UTF-8
C++
false
false
36,147
cxx
/* Copyright (C) 2011-2013 Doubango Telecom <http://www.doubango.org> * * This file is part of Open Source Doubango Framework. * * DOUBANGO is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * DOUBANGO is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with DOUBANGO. */ #include "internals/DSDisplay.h" #include "internals/DSUtils.h" #include "tinymedia/tmedia_consumer.h" #include "tsk_safeobj.h" #include "tsk_string.h" #include "tsk_debug.h" #define DSCONSUMER(self) ((plugin_video_dshow_consumer_t*)(self)) // Whether to use Direct3D device for direct rendering or DirectShow graph and custom source // Using DirectShow (DS) introduce delay when the input fps is different than the one in the custom src. // It's very hard to have someting accurate when using DS because the input FPS change depending on the congestion control. D3D is the best choice as frames are displayed as they arrive #if !defined(PLUGIN_DS_CV_USE_D3D9) && !defined(_WIN32_WCE) # define PLUGIN_DS_CV_USE_D3D9 1 #endif /******* ********/ #if PLUGIN_DS_CV_USE_D3D9 #include <d3d9.h> #include <dxva2api.h> #ifdef _MSC_VER #pragma comment(lib, "d3d9") #endif const DWORD NUM_BACK_BUFFERS = 2; #undef SafeRelease #define SafeRelease(ppT) \ { \ if (*ppT) \ { \ (*ppT)->Release(); \ *ppT = NULL; \ } \ } #undef CHECK_HR // In CHECK_HR(x) When (x) is a function it will be executed twice when used in "TSK_DEBUG_ERROR(x)" and "If(x)" #define CHECK_HR(x) { HRESULT __hr__ = (x); if (FAILED(__hr__)) { TSK_DEBUG_ERROR("Operation Failed (%08x)", __hr__); goto bail; } } typedef struct _DSRatio { DWORD Numerator; DWORD Denominator; } DSRatio; static HRESULT CreateDeviceD3D9( HWND hWnd, IDirect3DDevice9** ppDevice, IDirect3D9 **ppD3D, D3DPRESENT_PARAMETERS &d3dpp ); static HRESULT TestCooperativeLevel( struct plugin_video_dshow_consumer_s *pSelf ); static HRESULT CreateSwapChain( HWND hWnd, UINT32 nFrameWidth, UINT32 nFrameHeight, IDirect3DDevice9* pDevice, IDirect3DSwapChain9 **ppSwapChain); static LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); static inline HWND Window(struct plugin_video_dshow_consumer_s *pSelf); static inline LONG Width(const RECT& r); static inline LONG Height(const RECT& r); static inline RECT CorrectAspectRatio(const RECT& src, const DSRatio& srcPAR); static inline RECT LetterBoxRect(const RECT& rcSrc, const RECT& rcDst); static inline HRESULT UpdateDestinationRect(struct plugin_video_dshow_consumer_s *pSelf, BOOL bForce = FALSE); static HRESULT ResetDevice(struct plugin_video_dshow_consumer_s *pSelf, BOOL bUpdateDestinationRect = FALSE); static HRESULT SetFullscreen(struct plugin_video_dshow_consumer_s *pSelf, BOOL bFullScreen); static HWND CreateFullScreenWindow(struct plugin_video_dshow_consumer_s *pSelf); static HRESULT HookWindow(struct plugin_video_dshow_consumer_s *pSelf, HWND hWnd); static HRESULT UnhookWindow(struct plugin_video_dshow_consumer_s *pSelf); typedef struct plugin_video_dshow_consumer_s { TMEDIA_DECLARE_CONSUMER; BOOL bStarted, bPrepared, bPaused, bFullScreen, bWindowHooked; BOOL bPluginFireFox, bPluginWebRTC4All; HWND hWindow; WNDPROC wndProc; HWND hWindowFullScreen; RECT rcWindow; RECT rcDest; DSRatio pixelAR; UINT32 nNegWidth; UINT32 nNegHeight; UINT32 nNegFps; D3DLOCKED_RECT rcLock; IDirect3DDevice9* pDevice; IDirect3D9 *pD3D; IDirect3DSwapChain9 *pSwapChain; D3DPRESENT_PARAMETERS d3dpp; TSK_DECLARE_SAFEOBJ; } plugin_video_dshow_consumer_t; static int _plugin_video_dshow_consumer_unprepare(plugin_video_dshow_consumer_t* pSelf); /* ============ Media Consumer Interface ================= */ static int plugin_video_dshow_consumer_set(tmedia_consumer_t *self, const tmedia_param_t* param) { int ret = 0; HRESULT hr = S_OK; plugin_video_dshow_consumer_t* pSelf = (plugin_video_dshow_consumer_t*)self; if(!self || !param) { TSK_DEBUG_ERROR("Invalid parameter"); CHECK_HR(hr = E_POINTER); } if(param->value_type == tmedia_pvt_int64) { if(tsk_striequals(param->key, "remote-hwnd")) { HWND hWnd = reinterpret_cast<HWND>((INT64)*((int64_t*)param->value)); if(hWnd != pSelf->hWindow) { tsk_safeobj_lock(pSelf); // block consumer thread pSelf->hWindow = hWnd; if(pSelf->bPrepared) { hr = ResetDevice(pSelf); } tsk_safeobj_unlock(pSelf); // unblock consumer thread } } } else if(param->value_type == tmedia_pvt_int32) { if(tsk_striequals(param->key, "fullscreen")) { BOOL bFullScreen = !!*((int32_t*)param->value); TSK_DEBUG_INFO("[MF video consumer] Full Screen = %d", bFullScreen); CHECK_HR(hr = SetFullscreen(pSelf, bFullScreen)); } else if(tsk_striequals(param->key, "create-on-current-thead")) { // DSCONSUMER(self)->create_on_ui_thread = *((int32_t*)param->value) ? tsk_false : tsk_true; } else if(tsk_striequals(param->key, "plugin-firefox")) { pSelf->bPluginFireFox = (*((int32_t*)param->value) != 0); } else if(tsk_striequals(param->key, "plugin-webrtc4all")) { pSelf->bPluginWebRTC4All = (*((int32_t*)param->value) != 0); } } CHECK_HR(hr); bail: return SUCCEEDED(hr) ? 0 : -1; } static int plugin_video_dshow_consumer_prepare(tmedia_consumer_t* self, const tmedia_codec_t* codec) { plugin_video_dshow_consumer_t* pSelf = (plugin_video_dshow_consumer_t*)self; if(!pSelf || !codec && codec->plugin){ TSK_DEBUG_ERROR("Invalid parameter"); return -1; } if(pSelf->bPrepared){ TSK_DEBUG_WARN("D3D9 video consumer already prepared"); return -1; } HRESULT hr = S_OK; HWND hWnd = Window(pSelf); TMEDIA_CONSUMER(pSelf)->video.fps = TMEDIA_CODEC_VIDEO(codec)->in.fps; TMEDIA_CONSUMER(pSelf)->video.in.width = TMEDIA_CODEC_VIDEO(codec)->in.width; TMEDIA_CONSUMER(pSelf)->video.in.height = TMEDIA_CODEC_VIDEO(codec)->in.height; if(!TMEDIA_CONSUMER(pSelf)->video.display.width){ TMEDIA_CONSUMER(pSelf)->video.display.width = TMEDIA_CONSUMER(pSelf)->video.in.width; } if(!TMEDIA_CONSUMER(pSelf)->video.display.height){ TMEDIA_CONSUMER(pSelf)->video.display.height = TMEDIA_CONSUMER(pSelf)->video.in.height; } pSelf->nNegFps = (UINT32)TMEDIA_CONSUMER(pSelf)->video.fps; pSelf->nNegWidth = (UINT32)TMEDIA_CONSUMER(pSelf)->video.display.width; pSelf->nNegHeight = (UINT32)TMEDIA_CONSUMER(pSelf)->video.display.height; TSK_DEBUG_INFO("D3D9 video consumer: fps=%d, width=%d, height=%d", pSelf->nNegFps, pSelf->nNegWidth, pSelf->nNegHeight); TMEDIA_CONSUMER(pSelf)->video.display.chroma = tmedia_chroma_rgb32; TMEDIA_CONSUMER(pSelf)->decoder.codec_id = tmedia_codec_id_none; // means accept RAW fames // The window handle is not created until the call is connect (incoming only) - At least on Internet Explorer 10 if(hWnd && !pSelf->bPluginWebRTC4All) { CHECK_HR(hr = CreateDeviceD3D9(hWnd, &pSelf->pDevice, &pSelf->pD3D, pSelf->d3dpp)); CHECK_HR(hr = CreateSwapChain(hWnd, pSelf->nNegWidth, pSelf->nNegHeight, pSelf->pDevice, &pSelf->pSwapChain)); } else { if(hWnd && pSelf->bPluginWebRTC4All) { TSK_DEBUG_INFO("[MF consumer] HWND is defined but we detected webrtc4all...delaying D3D9 device creating until session get connected"); } else { TSK_DEBUG_WARN("Delaying D3D9 device creation because HWND is not defined yet"); } } bail: pSelf->bPrepared = SUCCEEDED(hr); return pSelf->bPrepared ? 0 : -1; } static int plugin_video_dshow_consumer_start(tmedia_consumer_t* self) { plugin_video_dshow_consumer_t* pSelf = (plugin_video_dshow_consumer_t*)self; if(!pSelf){ TSK_DEBUG_ERROR("Invalid parameter"); return -1; } if(pSelf->bStarted){ TSK_DEBUG_INFO("D3D9 video consumer already started"); return 0; } if(!pSelf->bPrepared){ TSK_DEBUG_ERROR("D3D9 video consumer not prepared"); return -1; } HRESULT hr = S_OK; pSelf->bPaused = false; pSelf->bStarted = true; return SUCCEEDED(hr) ? 0 : -1; } static int plugin_video_dshow_consumer_consume(tmedia_consumer_t* self, const void* buffer, tsk_size_t size, const tsk_object_t* proto_hdr) { plugin_video_dshow_consumer_t* pSelf = (plugin_video_dshow_consumer_t*)self; HRESULT hr = S_OK; HWND hWnd = Window(pSelf); IDirect3DSurface9 *pSurf = NULL; IDirect3DSurface9 *pBB = NULL; if(!pSelf) { TSK_DEBUG_ERROR("Invalid parameter"); return -1; // because of the mutex lock do it here } tsk_safeobj_lock(pSelf); if(!buffer || !size) { TSK_DEBUG_ERROR("Invalid parameter"); CHECK_HR(hr = E_INVALIDARG); } if(!pSelf->bStarted) { TSK_DEBUG_INFO("D3D9 video consumer not started"); CHECK_HR(hr = E_FAIL); } if(!hWnd) { TSK_DEBUG_INFO("Do not draw frame because HWND not set"); goto bail; // not an error as the application can decide to set the HWND at any time } if (!pSelf->bWindowHooked) { // Do not hook "hWnd" as it could be the fullscreen handle which is always hooked. CHECK_HR(hr = HookWindow(pSelf, pSelf->hWindow)); } if(!pSelf->pDevice || !pSelf->pD3D || !pSelf->pSwapChain) { if(pSelf->pDevice || pSelf->pD3D || pSelf->pSwapChain) { CHECK_HR(hr = E_POINTER); // They must be "all null" or "all valid" } if(hWnd) { // means HWND was not set but defined now pSelf->nNegWidth = (UINT32)TMEDIA_CONSUMER(pSelf)->video.in.width; pSelf->nNegHeight = (UINT32)TMEDIA_CONSUMER(pSelf)->video.in.height; CHECK_HR(hr = CreateDeviceD3D9(hWnd, &pSelf->pDevice, &pSelf->pD3D, pSelf->d3dpp)); CHECK_HR(hr = CreateSwapChain(hWnd, pSelf->nNegWidth, pSelf->nNegHeight, pSelf->pDevice, &pSelf->pSwapChain)); } } if(pSelf->nNegWidth != TMEDIA_CONSUMER(pSelf)->video.in.width || pSelf->nNegHeight != TMEDIA_CONSUMER(pSelf)->video.in.height){ TSK_DEBUG_INFO("Negotiated and input video sizes are different:%d#%d or %d#%d", pSelf->nNegWidth, TMEDIA_CONSUMER(pSelf)->video.in.width, pSelf->nNegHeight, TMEDIA_CONSUMER(pSelf)->video.in.height); // Update media type SafeRelease(&pSelf->pSwapChain); CHECK_HR(hr = CreateSwapChain(hWnd, (UINT32)TMEDIA_CONSUMER(pSelf)->video.in.width, (UINT32)TMEDIA_CONSUMER(pSelf)->video.in.height, pSelf->pDevice, &pSelf->pSwapChain)); pSelf->nNegWidth = (UINT32)TMEDIA_CONSUMER(pSelf)->video.in.width; pSelf->nNegHeight = (UINT32)TMEDIA_CONSUMER(pSelf)->video.in.height; // Update Destination will do noting if the window size haven't changed. // Force updating the destination rect if negotiated size change CHECK_HR(hr = UpdateDestinationRect(pSelf, TRUE/* Force */)); } if(((pSelf->nNegWidth * pSelf->nNegHeight) << 2) != size) { TSK_DEBUG_ERROR("%u not valid as input size", size); CHECK_HR(hr = E_FAIL); } CHECK_HR(hr = TestCooperativeLevel(pSelf)); CHECK_HR(hr = UpdateDestinationRect(pSelf)); CHECK_HR(hr = pSelf->pSwapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &pSurf)); CHECK_HR(hr = pSurf->LockRect(&pSelf->rcLock, NULL, D3DLOCK_NOSYSLOCK )); // Fast copy() using MMX, SSE, or SSE2 // Only available on Vista or later: Use LoadLibrary() to get a pointer to the function /*hr = MFCopyImage( (BYTE*)pSelf->rcLock.pBits, pSelf->rcLock.Pitch, (BYTE*)buffer, (pSelf->nNegWidth << 2), (pSelf->nNegWidth << 2), pSelf->nNegHeight );*/ if(pSelf->rcLock.Pitch == (pSelf->nNegWidth << 2)) { memcpy(pSelf->rcLock.pBits, buffer, size); } else { const BYTE* pSrcPtr = (const BYTE*)buffer; BYTE* pDstPtr = (BYTE*)pSelf->rcLock.pBits; UINT32 nDstPitch = pSelf->rcLock.Pitch; UINT32 nSrcPitch = (pSelf->nNegWidth << 2); for(UINT32 i = 0; i < pSelf->nNegHeight; ++i) { memcpy(pDstPtr, pSrcPtr, nSrcPitch); pDstPtr += nDstPitch; pSrcPtr += nSrcPitch; } } if(FAILED(hr)) { // unlock() before leaving pSurf->UnlockRect(); CHECK_HR(hr); } CHECK_HR(hr = pSurf->UnlockRect()); // Color fill the back buffer CHECK_HR(hr = pSelf->pDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &pBB)); CHECK_HR(hr = pSelf->pDevice->ColorFill(pBB, NULL, D3DCOLOR_XRGB(0xFF, 0xFF, 0xFF))); // Resize keeping aspect ratio and Blit the frame (required) hr = pSelf->pDevice->StretchRect( pSurf, NULL, pBB, &pSelf->rcDest/*NULL*/, D3DTEXF_LINEAR ); // could fail when display is being resized if(SUCCEEDED(hr)) { // Present the frame CHECK_HR(hr = pSelf->pDevice->Present(NULL, NULL, NULL, NULL)); } else { TSK_DEBUG_INFO("StretchRect returned ...%x", hr); } bail: SafeRelease(&pSurf); SafeRelease(&pBB); tsk_safeobj_unlock(pSelf); return SUCCEEDED(hr) ? 0 : -1; } static int plugin_video_dshow_consumer_pause(tmedia_consumer_t* self) { plugin_video_dshow_consumer_t* pSelf = (plugin_video_dshow_consumer_t*)self; if(!pSelf){ TSK_DEBUG_ERROR("Invalid parameter"); return -1; } if(!pSelf->bStarted) { TSK_DEBUG_INFO("MF video producer not started"); return 0; } HRESULT hr = S_OK; pSelf->bPaused = true; return SUCCEEDED(hr) ? 0 : -1; } static int plugin_video_dshow_consumer_stop(tmedia_consumer_t* self) { plugin_video_dshow_consumer_t* pSelf = (plugin_video_dshow_consumer_t*)self; if(!pSelf){ TSK_DEBUG_ERROR("Invalid parameter"); return -1; } HRESULT hr = S_OK; pSelf->bStarted = false; pSelf->bPaused = false; if(pSelf->hWindowFullScreen) { ::InvalidateRect(pSelf->hWindowFullScreen, NULL, FALSE); ::ShowWindow(pSelf->hWindowFullScreen, SW_HIDE); } // next start() will be called after prepare() return _plugin_video_dshow_consumer_unprepare(pSelf); } static int _plugin_video_dshow_consumer_unprepare(plugin_video_dshow_consumer_t* pSelf) { if(!pSelf){ TSK_DEBUG_ERROR("Invalid parameter"); return -1; } if(pSelf->bStarted) { // plugin_win_mf_producer_video_stop(TMEDIA_PRODUCER(pSelf)); TSK_DEBUG_ERROR("Consumer must be stopped before calling unprepare"); return -1; } UnhookWindow(pSelf); SafeRelease(&pSelf->pDevice); SafeRelease(&pSelf->pD3D); SafeRelease(&pSelf->pSwapChain); pSelf->bPrepared = false; return 0; } // // D3D9 video consumer object definition // /* constructor */ static tsk_object_t* plugin_video_dshow_consumer_ctor(tsk_object_t * self, va_list * app) { plugin_video_dshow_consumer_t *pSelf = (plugin_video_dshow_consumer_t *)self; if(pSelf) { /* init base */ tmedia_consumer_init(TMEDIA_CONSUMER(pSelf)); TMEDIA_CONSUMER(pSelf)->video.display.chroma = tmedia_chroma_rgb32; TMEDIA_CONSUMER(pSelf)->decoder.codec_id = tmedia_codec_id_none; // means accept RAW fames /* init self */ tsk_safeobj_init(pSelf); TMEDIA_CONSUMER(pSelf)->video.fps = 15; TMEDIA_CONSUMER(pSelf)->video.display.width = 0; // use codec value TMEDIA_CONSUMER(pSelf)->video.display.height = 0; // use codec value TMEDIA_CONSUMER(pSelf)->video.display.auto_resize = tsk_true; pSelf->pixelAR.Denominator = pSelf->pixelAR.Numerator = 1; } return self; } /* destructor */ static tsk_object_t* plugin_video_dshow_consumer_dtor(tsk_object_t * self) { plugin_video_dshow_consumer_t *pSelf = (plugin_video_dshow_consumer_t *)self; if (pSelf) { /* stop */ if (pSelf->bStarted) { plugin_video_dshow_consumer_stop(TMEDIA_CONSUMER(pSelf)); } /* deinit base */ tmedia_consumer_deinit(TMEDIA_CONSUMER(pSelf)); /* deinit self */ _plugin_video_dshow_consumer_unprepare(pSelf); tsk_safeobj_deinit(pSelf); } return self; } /* object definition */ static const tsk_object_def_t plugin_video_dshow_consumer_def_s = { sizeof(plugin_video_dshow_consumer_t), plugin_video_dshow_consumer_ctor, plugin_video_dshow_consumer_dtor, tsk_null, }; /* plugin definition*/ static const tmedia_consumer_plugin_def_t plugin_video_dshow_consumer_plugin_def_s = { &plugin_video_dshow_consumer_def_s, tmedia_video, "Microsoft DirectShow consumer (D3D9)", plugin_video_dshow_consumer_set, plugin_video_dshow_consumer_prepare, plugin_video_dshow_consumer_start, plugin_video_dshow_consumer_consume, plugin_video_dshow_consumer_pause, plugin_video_dshow_consumer_stop }; const tmedia_consumer_plugin_def_t *plugin_video_dshow_consumer_plugin_def_t = &plugin_video_dshow_consumer_plugin_def_s; // Helper functions static HRESULT CreateDeviceD3D9( HWND hWnd, IDirect3DDevice9** ppDevice, IDirect3D9 **ppD3D, D3DPRESENT_PARAMETERS &d3dpp ) { HRESULT hr = S_OK; D3DDISPLAYMODE mode = { 0 }; D3DPRESENT_PARAMETERS pp = {0}; if(!ppDevice || *ppDevice || !ppD3D || *ppD3D) { CHECK_HR(hr = E_POINTER); } if(!(*ppD3D = Direct3DCreate9(D3D_SDK_VERSION))) { CHECK_HR(hr = E_OUTOFMEMORY); } CHECK_HR(hr = (*ppD3D)->GetAdapterDisplayMode( D3DADAPTER_DEFAULT, &mode )); CHECK_HR(hr = (*ppD3D)->CheckDeviceType( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, mode.Format, D3DFMT_X8R8G8B8, TRUE // windowed )); pp.BackBufferFormat = D3DFMT_X8R8G8B8; pp.SwapEffect = D3DSWAPEFFECT_DISCARD; pp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; pp.Windowed = TRUE; pp.hDeviceWindow = hWnd; CHECK_HR(hr = (*ppD3D)->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &pp, ppDevice )); d3dpp = pp; bail: if(FAILED(hr)) { SafeRelease(ppD3D); SafeRelease(ppDevice); } return hr; } static HRESULT TestCooperativeLevel( struct plugin_video_dshow_consumer_s *pSelf ) { HRESULT hr = S_OK; if (!pSelf || !pSelf->pDevice) { CHECK_HR(hr = E_POINTER); } switch((hr = pSelf->pDevice->TestCooperativeLevel())) { case D3D_OK: { break; } case D3DERR_DEVICELOST: { hr = S_OK; break; } case D3DERR_DEVICENOTRESET: { hr = ResetDevice(pSelf, TRUE); break; } default: { break; } } CHECK_HR(hr); bail: return hr; } static HRESULT CreateSwapChain( HWND hWnd, UINT32 nFrameWidth, UINT32 nFrameHeight, IDirect3DDevice9* pDevice, IDirect3DSwapChain9 **ppSwapChain ) { HRESULT hr = S_OK; D3DPRESENT_PARAMETERS pp = { 0 }; if(!pDevice || !ppSwapChain || *ppSwapChain) { CHECK_HR(hr = E_POINTER); } pp.BackBufferWidth = nFrameWidth; pp.BackBufferHeight = nFrameHeight; pp.Windowed = TRUE; pp.SwapEffect = D3DSWAPEFFECT_FLIP; pp.hDeviceWindow = hWnd; pp.BackBufferFormat = D3DFMT_X8R8G8B8; pp.Flags = D3DPRESENTFLAG_VIDEO | D3DPRESENTFLAG_DEVICECLIP | D3DPRESENTFLAG_LOCKABLE_BACKBUFFER; pp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; pp.BackBufferCount = NUM_BACK_BUFFERS; CHECK_HR(hr = pDevice->CreateAdditionalSwapChain(&pp, ppSwapChain)); bail: return hr; } static inline HWND Window(struct plugin_video_dshow_consumer_s *pSelf) { return pSelf ? (pSelf->bFullScreen ? pSelf->hWindowFullScreen : pSelf->hWindow) : NULL; } static inline LONG Width(const RECT& r) { return r.right - r.left; } static inline LONG Height(const RECT& r) { return r.bottom - r.top; } //----------------------------------------------------------------------------- // CorrectAspectRatio // // Converts a rectangle from the source's pixel aspect ratio (PAR) to 1:1 PAR. // Returns the corrected rectangle. // // For example, a 720 x 486 rect with a PAR of 9:10, when converted to 1x1 PAR, // is stretched to 720 x 540. // Copyright (C) Microsoft //----------------------------------------------------------------------------- static inline RECT CorrectAspectRatio(const RECT& src, const DSRatio& srcPAR) { // Start with a rectangle the same size as src, but offset to the origin (0,0). RECT rc = {0, 0, src.right - src.left, src.bottom - src.top}; if ((srcPAR.Numerator != 1) || (srcPAR.Denominator != 1)) { // Correct for the source's PAR. if (srcPAR.Numerator > srcPAR.Denominator) { // The source has "wide" pixels, so stretch the width. rc.right = MulDiv(rc.right, srcPAR.Numerator, srcPAR.Denominator); } else if (srcPAR.Numerator < srcPAR.Denominator) { // The source has "tall" pixels, so stretch the height. rc.bottom = MulDiv(rc.bottom, srcPAR.Denominator, srcPAR.Numerator); } // else: PAR is 1:1, which is a no-op. } return rc; } //------------------------------------------------------------------- // LetterBoxDstRect // // Takes a src rectangle and constructs the largest possible // destination rectangle within the specifed destination rectangle // such thatthe video maintains its current shape. // // This function assumes that pels are the same shape within both the // source and destination rectangles. // Copyright (C) Microsoft //------------------------------------------------------------------- static inline RECT LetterBoxRect(const RECT& rcSrc, const RECT& rcDst) { // figure out src/dest scale ratios int iSrcWidth = Width(rcSrc); int iSrcHeight = Height(rcSrc); int iDstWidth = Width(rcDst); int iDstHeight = Height(rcDst); int iDstLBWidth; int iDstLBHeight; if (MulDiv(iSrcWidth, iDstHeight, iSrcHeight) <= iDstWidth) { // Column letter boxing ("pillar box") iDstLBWidth = MulDiv(iDstHeight, iSrcWidth, iSrcHeight); iDstLBHeight = iDstHeight; } else { // Row letter boxing. iDstLBWidth = iDstWidth; iDstLBHeight = MulDiv(iDstWidth, iSrcHeight, iSrcWidth); } // Create a centered rectangle within the current destination rect RECT rc; LONG left = rcDst.left + ((iDstWidth - iDstLBWidth) >> 1); LONG top = rcDst.top + ((iDstHeight - iDstLBHeight) >> 1); SetRect(&rc, left, top, left + iDstLBWidth, top + iDstLBHeight); return rc; } static inline HRESULT UpdateDestinationRect(plugin_video_dshow_consumer_t *pSelf, BOOL bForce /*= FALSE*/) { HRESULT hr = S_OK; HWND hwnd = Window(pSelf); if(!pSelf) { CHECK_HR(hr = E_POINTER); } if(!hwnd) { CHECK_HR(hr = E_HANDLE); } RECT rcClient; GetClientRect(hwnd, &rcClient); // only update destination if window size changed if(bForce || (rcClient.bottom != pSelf->rcWindow.bottom || rcClient.left != pSelf->rcWindow.left || rcClient.right != pSelf->rcWindow.right || rcClient.top != pSelf->rcWindow.top)) { CHECK_HR(hr = ResetDevice(pSelf)); pSelf->rcWindow = rcClient; #if 1 RECT rcSrc = { 0, 0, pSelf->nNegWidth, pSelf->nNegHeight }; rcSrc = CorrectAspectRatio(rcSrc, pSelf->pixelAR); pSelf->rcDest = LetterBoxRect(rcSrc, rcClient); #else long w = rcClient.right - rcClient.left; long h = rcClient.bottom - rcClient.top; float ratio = ((float)pSelf->nNegWidth/(float)pSelf->nNegHeight); // (w/h)=ratio => // 1) h=w/ratio // and // 2) w=h*ratio pSelf->rcDest.right = (int)(w/ratio) > h ? (int)(h * ratio) : w; pSelf->rcDest.bottom = (int)(pSelf->rcDest.right/ratio) > h ? h : (int)(pSelf->rcDest.right/ratio); pSelf->rcDest.left = ((w - pSelf->rcDest.right) >> 1); pSelf->rcDest.top = ((h - pSelf->rcDest.bottom) >> 1); #endif //::InvalidateRect(hwnd, NULL, FALSE); } bail: return hr; } static HRESULT ResetDevice(plugin_video_dshow_consumer_t *pSelf, BOOL bUpdateDestinationRect /*= FALSE*/) { HRESULT hr = S_OK; tsk_safeobj_lock(pSelf); HWND hWnd = Window(pSelf); if (pSelf->pDevice) { D3DPRESENT_PARAMETERS d3dpp = pSelf->d3dpp; hr = pSelf->pDevice->Reset(&d3dpp); if (FAILED(hr)) { SafeRelease(&pSelf->pDevice); SafeRelease(&pSelf->pD3D); SafeRelease(&pSelf->pSwapChain); } } if (pSelf->pDevice == NULL && hWnd) { CHECK_HR(hr = CreateDeviceD3D9(hWnd, &pSelf->pDevice, &pSelf->pD3D, pSelf->d3dpp)); CHECK_HR(hr = CreateSwapChain(hWnd, pSelf->nNegWidth, pSelf->nNegHeight, pSelf->pDevice, &pSelf->pSwapChain)); } if(bUpdateDestinationRect) // endless loop guard { CHECK_HR(hr = UpdateDestinationRect(pSelf)); } bail: tsk_safeobj_unlock(pSelf); return hr; } static HRESULT SetFullscreen(struct plugin_video_dshow_consumer_s *pSelf, BOOL bFullScreen) { HRESULT hr = S_OK; if(!pSelf) { CHECK_HR(hr = E_POINTER); } if(pSelf->bFullScreen != bFullScreen) { tsk_safeobj_lock(pSelf); if(bFullScreen) { HWND hWnd = CreateFullScreenWindow(pSelf); if(hWnd) { ::ShowWindow(hWnd, SW_SHOWDEFAULT); ::UpdateWindow(hWnd); } } else if(pSelf->hWindowFullScreen) { ::ShowWindow(pSelf->hWindowFullScreen, SW_HIDE); } pSelf->bFullScreen = bFullScreen; if(pSelf->bPrepared) { hr = ResetDevice(pSelf); } tsk_safeobj_unlock(pSelf); CHECK_HR(hr); } bail: return hr; } static LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch(uMsg) { case WM_CREATE: case WM_SIZE: case WM_MOVE: { struct plugin_video_dshow_consumer_s* pSelf = dynamic_cast<struct plugin_video_dshow_consumer_s*>((struct plugin_video_dshow_consumer_s*)GetPropA(hWnd, "Self")); if (pSelf) { } break; } #if 0 case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hWnd, &ps); ps.fErase = FALSE; RECT rc; GetBoundsRect(hdc, &rc, 0); FillRect(hdc, &rc, (HBRUSH)GetStockObject(BLACK_BRUSH)); EndPaint(hWnd, &ps); break; } #endif case WM_ERASEBKGND: { return TRUE; // avoid background erasing. } case WM_CHAR: case WM_KEYUP: { struct plugin_video_dshow_consumer_s* pSelf = dynamic_cast<struct plugin_video_dshow_consumer_s*>((struct plugin_video_dshow_consumer_s*)GetPropA(hWnd, "Self")); if (pSelf) { SetFullscreen(pSelf, FALSE); } break; } } return DefWindowProc(hWnd, uMsg, wParam, lParam); } static HWND CreateFullScreenWindow(struct plugin_video_dshow_consumer_s *pSelf) { HRESULT hr = S_OK; if(!pSelf) { return NULL; } if(!pSelf->hWindowFullScreen) { WNDCLASS wc = {0}; wc.lpfnWndProc = WndProc; wc.hInstance = GetModuleHandle(NULL); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.lpszClassName = L"WindowClass"; RegisterClass(&wc); pSelf->hWindowFullScreen = ::CreateWindowEx( NULL, wc.lpszClassName, L"Doubango's Video Consumer Fullscreen", WS_EX_TOPMOST | WS_POPUP, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), NULL, NULL, GetModuleHandle(NULL), NULL); SetPropA(pSelf->hWindowFullScreen, "Self", pSelf); } return pSelf->hWindowFullScreen; } static HRESULT HookWindow(plugin_video_dshow_consumer_t *pSelf, HWND hWnd) { HRESULT hr = S_OK; tsk_safeobj_lock(pSelf); CHECK_HR(hr = UnhookWindow(pSelf)); if ((pSelf->hWindow = hWnd)) { pSelf->wndProc = (WNDPROC)SetWindowLongPtr(pSelf->hWindow, GWLP_WNDPROC, (LONG_PTR)WndProc); if (!pSelf->wndProc) { TSK_DEBUG_ERROR("HookWindowLongPtr() failed with errcode=%d", GetLastError()); CHECK_HR(hr = E_FAIL); } pSelf->bWindowHooked = TRUE; } bail: tsk_safeobj_unlock(pSelf); return S_OK; } static HRESULT UnhookWindow(struct plugin_video_dshow_consumer_s *pSelf) { tsk_safeobj_lock(pSelf); if (pSelf->hWindow && pSelf->wndProc) { SetWindowLongPtr(pSelf->hWindow, GWLP_WNDPROC, (LONG_PTR)pSelf->wndProc); pSelf->wndProc = NULL; } if(pSelf->hWindow) { ::InvalidateRect(pSelf->hWindow, NULL, FALSE); } pSelf->bWindowHooked = FALSE; tsk_safeobj_unlock(pSelf); return S_OK; } #else /* !PLUGIN_DS_CV_USE_D3D9 */ typedef struct plugin_video_dshow_consumer_s { TMEDIA_DECLARE_CONSUMER; DSDisplay* display; INT64 window; tsk_bool_t plugin_firefox; tsk_bool_t started; tsk_bool_t create_on_ui_thread; } plugin_video_dshow_consumer_t; /* ============ Media Consumer Interface ================= */ static int plugin_video_dshow_consumer_set(tmedia_consumer_t *self, const tmedia_param_t* param) { int ret = 0; if(!self || !param){ TSK_DEBUG_ERROR("Invalid parameter"); return -1; } if(param->value_type == tmedia_pvt_int64){ if(tsk_striequals(param->key, "remote-hwnd")){ DSCONSUMER(self)->window = (INT64)*((int64_t*)param->value); if(DSCONSUMER(self)->display){ if(DSCONSUMER(self)->window){ DSCONSUMER(self)->display->attach(DSCONSUMER(self)->window); } else{ DSCONSUMER(self)->display->detach(); } } } } else if(param->value_type == tmedia_pvt_int32){ if(tsk_striequals(param->key, "fullscreen")){ if(DSCONSUMER(self)->display){ DSCONSUMER(self)->display->setFullscreen(*((int32_t*)param->value) != 0); } } else if(tsk_striequals(param->key, "create-on-current-thead")){ DSCONSUMER(self)->create_on_ui_thread = *((int32_t*)param->value) ? tsk_false : tsk_true; } else if(tsk_striequals(param->key, "plugin-firefox")){ DSCONSUMER(self)->plugin_firefox = (*((int32_t*)param->value) != 0); if(DSCONSUMER(self)->display){ DSCONSUMER(self)->display->setPluginFirefox((DSCONSUMER(self)->plugin_firefox == tsk_true)); } } } return ret; } static int plugin_video_dshow_consumer_prepare(tmedia_consumer_t* self, const tmedia_codec_t* codec) { plugin_video_dshow_consumer_t* consumer = (plugin_video_dshow_consumer_t*)self; if(!consumer || !codec && codec->plugin){ TSK_DEBUG_ERROR("Invalid parameter"); return -1; } TMEDIA_CONSUMER(consumer)->video.fps = TMEDIA_CODEC_VIDEO(codec)->in.fps; TMEDIA_CONSUMER(consumer)->video.in.width = TMEDIA_CODEC_VIDEO(codec)->in.width; TMEDIA_CONSUMER(consumer)->video.in.height = TMEDIA_CODEC_VIDEO(codec)->in.height; if(!TMEDIA_CONSUMER(consumer)->video.display.width){ TMEDIA_CONSUMER(consumer)->video.display.width = TMEDIA_CONSUMER(consumer)->video.in.width; } if(!TMEDIA_CONSUMER(consumer)->video.display.height){ TMEDIA_CONSUMER(consumer)->video.display.height = TMEDIA_CONSUMER(consumer)->video.in.height; } return 0; } static int plugin_video_dshow_consumer_start(tmedia_consumer_t* self) { plugin_video_dshow_consumer_t* consumer = (plugin_video_dshow_consumer_t*)self; if(!consumer){ TSK_DEBUG_ERROR("Invalid parameter"); return -1; } if(consumer->started){ return 0; } // create display on UI thread if(!consumer->display){ if (consumer->create_on_ui_thread) createOnUIThead(reinterpret_cast<HWND>((void*)consumer->window), (void**)&consumer->display, true, false); else createOnCurrentThead(reinterpret_cast<HWND>((void*)consumer->window), (void**)&consumer->display, true, false); if(!consumer->display){ TSK_DEBUG_ERROR("Failed to create display"); return -2; } } // Set parameters consumer->display->setPluginFirefox((consumer->plugin_firefox == tsk_true)); consumer->display->setFps(TMEDIA_CONSUMER(consumer)->video.fps); // do not change the display size: see hook() // consumer->display->setSize(TMEDIA_CONSUMER(consumer)->video.display.width, TMEDIA_CONSUMER(consumer)->video.display.height); if(consumer->window){ consumer->display->attach(consumer->window); } // Start display consumer->display->start(); consumer->started = tsk_true; return 0; } static int plugin_video_dshow_consumer_consume(tmedia_consumer_t* self, const void* buffer, tsk_size_t size, const tsk_object_t* proto_hdr) { plugin_video_dshow_consumer_t* consumer = (plugin_video_dshow_consumer_t*)self; if(consumer && consumer->display && buffer){ consumer->display->handleVideoFrame(buffer, TMEDIA_CONSUMER(consumer)->video.display.width, TMEDIA_CONSUMER(consumer)->video.display.height); return 0; } else{ TSK_DEBUG_ERROR("Invalid parameter"); return -1; } } static int plugin_video_dshow_consumer_pause(tmedia_consumer_t* self) { plugin_video_dshow_consumer_t* consumer = (plugin_video_dshow_consumer_t*)self; if(!consumer){ TSK_DEBUG_ERROR("Invalid parameter"); return -1; } if(!consumer->display){ TSK_DEBUG_ERROR("Invalid internal grabber"); return -2; } //consumer->display->pause(); return 0; } static int plugin_video_dshow_consumer_stop(tmedia_consumer_t* self) { plugin_video_dshow_consumer_t* consumer = (plugin_video_dshow_consumer_t*)self; if(!self){ TSK_DEBUG_ERROR("Invalid parameter"); return -1; } if(!consumer->started){ return 0; } if(!consumer->display){ TSK_DEBUG_ERROR("Invalid internal display"); return -2; } TSK_DEBUG_INFO("Before stopping DirectShow consumer"); consumer->display->stop(); consumer->started = tsk_false; TSK_DEBUG_INFO("After stopping DirectShow consumer"); return 0; } // // DirectShow consumer object definition // /* constructor */ static tsk_object_t* plugin_video_dshow_consumer_ctor(tsk_object_t * self, va_list * app) { CoInitializeEx(NULL, COINIT_MULTITHREADED); plugin_video_dshow_consumer_t *consumer = (plugin_video_dshow_consumer_t *)self; if(consumer){ /* init base */ tmedia_consumer_init(TMEDIA_CONSUMER(consumer)); TMEDIA_CONSUMER(consumer)->video.display.chroma = tmedia_chroma_bgr24; // RGB24 on x86 (little endians) stored as BGR24 /* init self */ consumer->create_on_ui_thread = tsk_true; TMEDIA_CONSUMER(consumer)->video.fps = 15; TMEDIA_CONSUMER(consumer)->video.display.width = 352; TMEDIA_CONSUMER(consumer)->video.display.height = 288; TMEDIA_CONSUMER(consumer)->video.display.auto_resize = tsk_true; } return self; } /* destructor */ static tsk_object_t* plugin_video_dshow_consumer_dtor(tsk_object_t * self) { plugin_video_dshow_consumer_t *consumer = (plugin_video_dshow_consumer_t *)self; if(consumer){ /* stop */ if(consumer->started){ plugin_video_dshow_consumer_stop((tmedia_consumer_t*)self); } /* deinit base */ tmedia_consumer_deinit(TMEDIA_CONSUMER(consumer)); /* deinit self */ SAFE_DELETE_PTR(consumer->display); } return self; } /* object definition */ static const tsk_object_def_t plugin_video_dshow_consumer_def_s = { sizeof(plugin_video_dshow_consumer_t), plugin_video_dshow_consumer_ctor, plugin_video_dshow_consumer_dtor, tsk_null, }; /* plugin definition*/ static const tmedia_consumer_plugin_def_t plugin_video_dshow_consumer_plugin_def_s = { &plugin_video_dshow_consumer_def_s, tmedia_video, "Microsoft DirectShow consumer (using custom source)", plugin_video_dshow_consumer_set, plugin_video_dshow_consumer_prepare, plugin_video_dshow_consumer_start, plugin_video_dshow_consumer_consume, plugin_video_dshow_consumer_pause, plugin_video_dshow_consumer_stop }; const tmedia_consumer_plugin_def_t *plugin_video_dshow_consumer_plugin_def_t = &plugin_video_dshow_consumer_plugin_def_s; #endif /* PLUGIN_DS_CV_USE_D3D9 */
[ "bossiel@yahoo.fr@c7b0ae48-b0eb-11de-8bdf-3374eb5c7316" ]
bossiel@yahoo.fr@c7b0ae48-b0eb-11de-8bdf-3374eb5c7316
a17d07f9738013c3373cc63a4409705d8305d770
5815ea16d4624ce357d0f0af8ce5f3fda0196177
/graph/is_bridge.cpp
d7031d0d6761c87c0f7b63fe88657a7266f3240b
[]
no_license
rajharsh81070/Algorithms
eda89218b4a0fb600ee22446f912cfd89ec957f5
6721be83f9d31ad2d7d13e4474c206ab1c8efbe1
refs/heads/master
2020-04-21T03:12:14.196186
2020-01-29T12:39:49
2020-01-29T12:39:49
169,277,438
0
0
null
null
null
null
UTF-8
C++
false
false
698
cpp
#include <bits/stdc++.h> using namespace std; vector<int> adjList[10001]; vecotr<bool> visited(10001); vector<int> low, t_in; int timer; void dfs(int u, int p = -1){ visited[u] = true; low[u]=t_in[u]=timer++; for(int v:adjList[u]){ if(v==p) continue; if(visited[v]){ low[u] = min(t_in[v], low[u]); } else{ dfs(v, u); low[u] = min(low[u], t_in[v]); if (low[v] > t_in[u]) cout << "There is a bridge between between" << u << "and" << v << '\n' ; } } } void find_bridges(int n){ timer = 0; visited.assign(n, false); t_in.assign(n, -1); low.assign(n, -1); for(int node=0; node<n; node++){ if(!visited[node]) dfs(node); } } int main(void){ find_bridges(n); }
[ "rajharsh81070@gmail.com" ]
rajharsh81070@gmail.com
06a8c25ad155b7e5d0d437b39d593187202bbe4d
5004f0c1f7eba48acf74630eb0baf296fb2a3a51
/ICPC/SEERC16-17/H.cpp
836e1d104a0ab646faacc9ce11e459e07edb47fa
[]
no_license
shash42/Competitive-Programming
80ab2611764f2f615568f2011088c1f651f26dcc
f069e8de37f42dba9fb77941b297b33161c2d401
refs/heads/master
2021-03-17T17:30:38.242207
2020-07-21T18:24:13
2020-07-21T18:24:13
276,369,049
1
1
null
null
null
null
UTF-8
C++
false
false
1,834
cpp
#include<bits/stdc++.h> #include<ext/pb_ds/assoc_container.hpp> #include<ext/pb_ds/tree_policy.hpp> #define pb push_back #define f first #define s second #define lint long long #define mp make_pair #define pii pair<int, int> #define pll pair<lint, lint> #define ld long double #define inlld(x) scanf("%lld", &x) #define ind(x) scanf("%d", &x) #define vi vector<int> const int N=1e2+5; const int MOD=1e9+7; const lint INF=1e18; 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>; int n, m ; string strings[N] ; vi toRemove ; int x ; string query ; set < int > os ; int main() { cin >> n >> m ; for(int i = 0; i <n; i++) cin >> strings[i] ; for(int i = 0; i < m; i++) { cin >> x ; os.insert(x-1); toRemove.pb(x); if((int)toRemove.size() == 1) query = strings[x-1] ; } bool pos = 1 ; for(int i = 1; i < m; i++) { int rem = toRemove[i] - 1; int len = strings[rem].length(); // cout << pos << endl ; if(len != query.length()) { pos = 0 ; break ; } for(int j = 0; j < len; j++) { if(query[j] != strings[rem][j]) query[j] = '?' ; } //cout << pos << endl ; } for(int i = 0; i < n; i++) { if(os.find(i) != os.end()) continue ; if(strings[i].length() != query.length()) continue ; // cout << i << endl ; bool match = 1 ; for(int j = 0; j < strings[i].length(); j++) if(strings[i][j] != query[j] and query[j] != '?') match = 0 ; if(match) pos = 0 ; } if(pos) { cout << "Yes\n" << query ; } else { cout << "No" ; } return 0; }
[ "shashwatnow@gmail.com" ]
shashwatnow@gmail.com
a0a24d19af8659c6f2291e0897ca2020d44169f8
66f57231dea1d319cf1d469bff6bc02f7244a5e5
/tsHydro/src/tsHydro.cpp
c7f0c91e8204e23eae44cb6d6ee11cc1be5c89e7
[ "BSD-2-Clause" ]
permissive
cavios/tshydro
31ec57943cd73a840b761d1c96e086200273ef6c
9d6d47e871fbc0ac1478923262f7be1bfb852717
refs/heads/master
2023-04-14T04:54:11.199235
2023-04-05T12:45:49
2023-04-05T12:45:49
41,877,395
4
6
null
2015-12-08T14:28:39
2015-09-03T18:43:50
R
UTF-8
C++
false
false
2,984
cpp
#include <TMB.hpp> template <class Type> Type dt1(Type x){ return Type(1.0)/M_PI/(Type(1.0)+x*x); } template <class Type> Type ilogit(Type x){ return Type(1.0)/(Type(1.0)+exp(-x)); } template <class Type> Type nldens(Type x, Type mu, Type sd, Type p){ Type z=(x-mu)/sd; return -log(1.0/sd*((1.0-p)*dnorm(z,Type(0.0),Type(1.0),false)+p*dt1(z))); } template<class Type> Type objective_function<Type>::operator() () { DATA_VECTOR(height); DATA_VECTOR(times); DATA_IVECTOR(timeidx); DATA_IVECTOR(newtimeidx); DATA_IVECTOR(group); DATA_IVECTOR(satid); DATA_IVECTOR(qfid); DATA_IARRAY(trackinfo); DATA_VECTOR(weights); DATA_VECTOR(priorHeight); DATA_VECTOR(priorSd); DATA_INTEGER(varPerTrack); DATA_INTEGER(varPerQuality); DATA_IVECTOR(trackidx); vector<Type> pred(height.size()); pred.setZero(); PARAMETER_VECTOR(logSigma); PARAMETER(logSigmaRW); PARAMETER(logitp); PARAMETER_VECTOR(u); PARAMETER_VECTOR(bias); vector<Type> biasvec(bias.size()+1); biasvec(0)=0; for(int i=1; i<biasvec.size();++i)biasvec(i)=bias(i-1); int timeSteps=times.size(); int obsDim=height.size(); int noTracks=trackinfo.dim[0]; Type p=ilogit(logitp); Type ans=0; if(priorHeight.size()==1){ ans += -sum(dnorm(u, priorHeight(0), priorSd(0), true)); } Type sdRW=exp(logSigmaRW); for(int i=1;i<timeSteps;i++){ ans += -dnorm(u(i),u(i-1),sdRW*sqrt(times(i)-times(i-1)),true); } vector<Type> sdObs=exp(logSigma); for(int t=0;t<noTracks;t++){ vector<Type> sub=height.segment(trackinfo(t,0),trackinfo(t,2)); vector<Type> subw=weights.segment(trackinfo(t,0),trackinfo(t,2)); vector<int> subsatid=satid.segment(trackinfo(t,0),trackinfo(t,2)); vector<int> subtrackid=trackidx.segment(trackinfo(t,0),trackinfo(t,2)); vector<int> subqfid=qfid.segment(trackinfo(t,0),trackinfo(t,2)); int idxVar; for(int i=0;i<trackinfo(t,2);i++){ if(varPerTrack==1){idxVar=subtrackid(i);}else{idxVar=subsatid(i);} if(varPerQuality==1){idxVar=subqfid(i);}else{idxVar=subsatid(i);} if(priorHeight.size()==1){ if((sub(i)>(priorHeight(0)-Type(5)*priorSd(0))) && (sub(i)<(priorHeight(0)+Type(5)*priorSd(0)))){ ans += nldens(sub(i),u(timeidx(trackinfo(t,0))-1)+biasvec(subsatid(i)),sdObs(idxVar)/sqrt(subw(i)),p); } }else{ ans += nldens(sub(i),u(timeidx(trackinfo(t,0))-1)+biasvec(subsatid(i)),sdObs(idxVar)/sqrt(subw(i)),p); } pred(trackinfo(t,0)+i)=u(timeidx(trackinfo(t,0))-1)+biasvec(subsatid(i)); } } Type aveH=sum(u)/u.size(); ADREPORT(aveH); if(group.size()>0){ int ngroup=group.maxCoeff()+1; vector<Type> groupAve(ngroup); groupAve.setZero(); vector<Type> groupN(ngroup); groupAve.setZero(); for(int i=0; i<newtimeidx.size(); ++i){ groupAve(group(i))+=u(newtimeidx(i)-1); groupN(group(i))+=1; } groupAve/=groupN; ADREPORT(groupAve); } REPORT(pred); return ans; }
[ "karni@space.dtu.dk" ]
karni@space.dtu.dk
167efb5f3af0ea6558caf32e3b31d4ba15f1ee8b
a743342cf4057a7c2cc573e79602bf89c00b3579
/GraphViewer/ShevArray.h
bb8153399977632fdb175acb315ad26fa2cc2d4f
[]
no_license
prografix/prografix.github.io
deddc17515c93566616e74b292b7e4fb1136064f
4f316beb0fa24b98aec8eb127bd294c012c60538
refs/heads/master
2023-07-25T09:48:34.670827
2023-07-09T13:55:25
2023-07-09T13:55:25
166,195,307
3
0
null
null
null
null
WINDOWS-1251
C++
false
false
20,144
h
#ifndef SHEVARRAY_H #define SHEVARRAY_H #include "typedef.h" #include "template.h" //#define ARRAY_TEST #ifdef ARRAY_TEST void outOfRange ( const char * name, nat size, nat index ); #endif /********************** CArrRef ************************/ /************ Ссылка на константный массив *************/ template <class T> class CArrRef { void operator = ( const CArrRef & ); protected: const T * _data; nat _size; public: CArrRef () : _data(0), _size(0) {} CArrRef ( const T * d, nat n ) : _data(d), _size(n) {} #ifdef ARRAY_TEST void error ( nat n, nat i ) const { outOfRange ( "CArrRef", n, i ); } CArrRef ( CArrRef<T> a, nat i, nat n ) : _data(&a[i]), _size(n) { if ( a._size < i + n ) error ( a._size, i + n ); } const T & operator[] ( nat i ) const { if ( _size <= i ) error ( _size, i ); return _data[i]; } const T & las () const { if ( _size == 0 ) error ( _size, _size ); return _data[_size-1]; } const T & cprev ( nat i ) const { if ( _size <= i ) error ( _size, i ); return _data[i>0?i-1:_size-1]; } const T & cnext ( nat i ) const { if ( _size <= i ) error ( _size, i ); return _data[i+1<_size?i+1:0]; } #else CArrRef ( CArrRef<T> a, nat i, nat n ) : _data(&a[i]), _size(n) {} const T & operator[] ( nat i ) const { return _data[i]; } const T & las () const { return _data[_size-1]; } const T & cprev ( nat i ) const { return _data[i>0?i-1:_size-1]; } const T & cnext ( nat i ) const { return _data[i+1<_size?i+1:0]; } #endif nat size () const { return _size; } }; /*********************** ArrRef ************************/ /****************** Ссылка на массив *******************/ template <class T> class ArrRef : public CArrRef<T> { protected: ArrRef ( T * d, nat n ) : CArrRef<T>( d, n ) {} public: ArrRef () {} #ifdef ARRAY_TEST void error ( nat n, nat i ) const { outOfRange ( "ArrRef", n, i ); } ArrRef ( ArrRef<T> a, nat i, nat n ) : CArrRef<T>( &a[i], n ) { if ( a._size < i + n ) error ( a._size, i + n ); } T & operator[] ( nat i ) { if ( _size <= i ) error ( _size, i );return ((T*)_data)[i]; } T & las () { if ( _size == 0 ) error ( _size, _size ); return ((T*)_data)[_size-1]; } T & cprev ( nat i ) { if ( _size <= i ) error ( _size, i ); return ((T*)_data)[i>0?i-1:_size-1]; } T & cnext ( nat i ) { if ( _size <= i ) error ( _size, i ); return ((T*)_data)[i+1<_size?i+1:0]; } const T & operator[] ( nat i ) const { if ( _size <= i ) error ( _size, i ); return _data[i]; } const T & las () const { if ( _size == 0 ) error ( _size, _size ); return _data[_size-1]; } const T & cprev ( nat i ) const { if ( _size <= i ) error ( _size, i ); return _data[i>0?i-1:_size-1]; } const T & cnext ( nat i ) const { if ( _size <= i ) error ( _size, i ); return _data[i+1<_size?i+1:0]; } #else ArrRef ( ArrRef<T> a, nat i, nat n ) : CArrRef<T>( &a[i], n ) {} T & operator[] ( nat i ) { return ((T*)_data)[i]; } T & las () { return ((T*)_data)[_size-1]; } T & cprev ( nat i ) { return ((T*)_data)[i>0?i-1:_size-1]; } T & cnext ( nat i ) { return ((T*)_data)[i+1<_size?i+1:0]; } const T & operator[] ( nat i ) const { return _data[i]; } const T & las () const { return _data[_size-1]; } const T & cprev ( nat i ) const { return _data[i>0?i-1:_size-1]; } const T & cnext ( nat i ) const { return _data[i+1<_size?i+1:0]; } #endif ArrRef & operator= ( const CArrRef<T> & p ) { const nat n = _min ( _size, p.size() ); for ( nat i = 0; i < n; ++i ) ((T*)_data)[i] = p[i]; return *this; } ArrRef & operator= ( const ArrRef & a ) { return this->operator= ( ( const CArrRef<T> &) a ); } // Изменение порядка следования элементов на обратный ArrRef & reverse () { if ( _size < 2 ) return *this; const nat n = _size - 1; const nat m = _size / 2; for ( nat i = 0; i < m; ++i ) _swap ( ((T*)_data)[i], ((T*)_data)[n-i] ); return *this; } // Применение указанной процедуры для элементов с первого до последнего template <class P> ArrRef & for012p ( P & p ) { for ( nat i = 0; i < _size; ++i ) p ( ((T*)_data)[i] ); return *this; } }; /*********************** FixArrRef ***********************/ /*********** Ссылка на массив постоянной длины ***********/ template <class T, nat n> class FixArrRef : public ArrRef<T> { protected: FixArrRef ( T * d ) : ArrRef<T>( d, n ) {} public: explicit FixArrRef ( ArrRef<T> a, nat i = 0 ) : ArrRef<T> ( a, i, n ) {} FixArrRef & operator= ( const FixArrRef & a ) { for ( nat i = 0; i < n; ++i ) stor[i] = a[i]; return *this; } FixArrRef & operator+= ( const FixArrRef & a ) { for ( nat i = 0; i < n; ++i ) ((T*)_data)[i] += a[i]; return *this; } FixArrRef & operator-= ( const FixArrRef & a ) { for ( nat i = 0; i < n; ++i ) ((T*)_data)[i] -= a[i]; return *this; } FixArrRef & operator*= ( const FixArrRef & a ) { for ( nat i = 0; i < n; ++i ) ((T*)_data)[i] *= a[i]; return *this; } FixArrRef & operator/= ( const FixArrRef & a ) { for ( nat i = 0; i < n; ++i ) ((T*)_data)[i] /= a[i]; return *this; } FixArrRef & operator%= ( const FixArrRef & a ) { for ( nat i = 0; i < n; ++i ) ((T*)_data)[i] %= a[i]; return *this; } friend inline void _swap ( FixArrRef & a1, FixArrRef & a2 ) { for ( nat i = 0; i < n; ++i ) _swap ( a1[i], a2[i] ); } }; /*********************** FixArray ************************/ /*************** Массив постоянной длины *****************/ template <class T, nat n> class FixArray : public FixArrRef<T, n> { T stor[n]; FixArray ( const FixArray & ); public: FixArray () : FixArrRef<T, n> ( stor ) {} FixArray & operator= ( const FixArray & a ) { for ( nat i = 0; i < n; ++i ) stor[i] = a.stor[i]; return *this; } }; /********************** DynArrRef **********************/ /******* Ссылка на массив с изменяемым размером ********/ template <class T> class DynArrRef : public ArrRef<T> { protected: DynArrRef ( T * d, nat n ) : ArrRef<T>( d, n ) {} public: virtual DynArrRef & resize ( nat n = 0 ) = 0; }; /********************** DynArray ***********************/ /**************** Динамический массив ******************/ template <class T> class DynArray : public DynArrRef<T> { DynArray ( const DynArray & ); public: explicit DynArray ( nat n = 0 ) : DynArrRef<T> ( n > 0 ? new T[n] : 0, n ) {} explicit DynArray ( const CArrRef<T> & r ) : DynArrRef<T> ( new T[r.size()], r.size() ) { for ( nat i = 0; i < _size; ++i ) ((T*)_data)[i] = r[i]; } ~DynArray () { delete[] (T*)_data; } DynArray & operator= ( const CArrRef<T> & r ) { if ( _size != r.size() ) { delete[] (T*)_data; _data = ( _size = r.size() ) > 0 ? new T[_size] : 0; } for ( nat i = 0; i < _size; ++i ) ((T*)_data)[i] = r[i]; return *this; } DynArray & operator= ( const DynArray & a ) { return this->operator= ( ( const CArrRef<T> &) a ); } DynArrRef<T> & resize ( nat n = 0 ) { delete[] (T*)_data; _data = ( _size = n ) > 0 ? new T[n] : 0; return *this; } friend inline void _swap ( DynArray & a1, DynArray & a2 ) { _swap ( a1._size, a2._size ); _swap ( a1._data, a2._data ); } }; /********************** CmbArray ***********************/ /************** Комбинированный массив *****************/ template <class T, nat N> class CmbArray : public DynArrRef<T> { T stor[N]; CmbArray ( const CmbArray & ); public: explicit CmbArray ( nat n = 0 ) : DynArrRef<T> ( n > N ? new T[n] : stor, n ) {} explicit CmbArray ( const CArrRef<T> & r ) : DynArrRef<T> ( r.size() > N ? new T[r.size()] : stor, r.size() ) { for ( nat i = 0; i < _size; ++i ) ((T*)_data)[i] = r[i]; } ~CmbArray () { if ( _data != stor ) delete[] (T*)_data; } CmbArray & operator= ( const CArrRef<T> & r ) { if ( _size != r.size() ) { if ( _data != stor ) delete[] (T*)_data; _data = ( _size = r.size() ) > N ? new T[_size] : stor; } for ( nat i = 0; i < _size; ++i ) ((T*)_data)[i] = r[i]; return *this; } CmbArray & operator= ( const CmbArray & a ) { return this->operator= ( ( const CArrRef<T> &) a ); } DynArrRef<T> & resize ( nat n = 0 ) { if ( _size == n ) return *this; if ( _data != stor ) delete[] (T*)_data; _data = ( _size = n ) > N ? new T[n] : stor; return *this; } }; /********************** SuiteRef ***********************/ /***** Ссылка на последовательный набор элементов ******/ template <class T> class SuiteRef : public DynArrRef<T> { SuiteRef ( const SuiteRef & ); void _del ( nat i ) { if ( i < --_size ) ((T*)_data)[i] = _data[_size]; } virtual void resizeAndCopy ( nat n ) { T * tmp = new T[n]; for ( nat i = 0; i < _size; ++i ) tmp[i] = _data[i]; delete[] (T*)_data; _data = tmp; real_size = n; } protected: nat real_size; SuiteRef ( T * d, nat n ) : DynArrRef<T>( d, n ) {} public: SuiteRef & operator= ( const CArrRef<T> & r ) { resize ( r.size() ); for ( nat i = 0; i < _size; ++i ) ((T*)_data)[i] = r[i]; return *this; } SuiteRef & operator= ( const SuiteRef & a ) { return this->operator= ( ( const CArrRef<T> &) a ); } DynArrRef<T> & resize ( nat n = 0 ) { if ( n > real_size ) resizeAndCopy ( n ); _size = n; return *this; } virtual T & inc () { if ( _size == real_size ) resizeAndCopy ( _size + _size ); return ((T*)_data)[_size++]; } SuiteRef & dec () { if ( _size > 0 ) --_size; return *this; } SuiteRef & del ( nat i ) { if ( i < _size ) _del ( i ); #ifdef ARRAY_TEST else outOfRange ( "SuiteRef::del", _size, i ); #endif ARRAY_TEST return *this; } void movAftLas ( nat i, SuiteRef<T> & suite ) { if ( i < _size ) { suite.inc() = _data[i]; _del ( i ); } #ifdef ARRAY_TEST else outOfRange ( "SuiteRef::movAftLas", _size, i ); #endif ARRAY_TEST } virtual SuiteRef & addAftLas ( const CArrRef<T> & a ) { const nat n = _size + a.size(); nat s = real_size; if ( s < n ) { while ( s < n ) s += s; resizeAndCopy ( s ); } for ( nat i = 0; i < a.size(); ++i ) ((T*)_data)[_size+i] = a[i]; _size = n; return *this; } }; /*********************** Suite *************************/ /********** Последовательный набор элементов ***********/ template <class T> class Suite : public SuiteRef<T> { Suite ( const Suite & ); public: Suite () : SuiteRef<T>(new T[real_size=16], 0) {} explicit Suite ( nat n, nat m = 0 ) : SuiteRef<T>(new T[real_size=n<m?m:n==0?16:n], m) {} ~Suite () { delete[] (T*)_data; } Suite & operator= ( const CArrRef<T> & r ) { _size = r.size(); if ( real_size < _size ) { real_size = _size; delete[] (T*)_data; _data = new T[_size]; } for ( nat i = 0; i < _size; ++i ) ((T*)_data)[i] = r[i]; return *this; } Suite & operator= ( const Suite & a ) { return this->operator= ( ( const CArrRef<T> &) a ); } friend inline void _swap ( Suite & a1, Suite & a2 ) { _swap ( a1.real_size, a2.real_size ); _swap ( a1._size, a2._size ); _swap ( a1._data, a2._data ); } }; /********************* CmbSuite ************************/ /********** Комбинированный набор элементов ************/ template <class T, nat N> class CmbSuite : public SuiteRef<T> { T stor[N]; CmbSuite ( const CmbSuite & ); virtual void resizeAndCopy ( nat n ) { T * tmp = new T[n]; for ( nat i = 0; i < _size; ++i ) tmp[i] = _data[i]; if ( _data != stor ) delete[] (T*)_data; _data = tmp; real_size = n; } public: CmbSuite () : SuiteRef<T>(stor, 0) { real_size = N; } explicit CmbSuite ( nat n, nat m = 0 ) : SuiteRef<T> ( ( real_size = n < m ? m : n ) > N ? new T[real_size] : ( real_size = N, stor ), m ) {} ~CmbSuite () { if ( _data != stor ) delete[] (T*)_data; } CmbSuite & operator= ( const CArrRef<T> & r ) { _size = r.size(); if ( real_size < _size ) { real_size = _size; if ( _data != stor ) delete[] (T*)_data; _data = new T[_size]; } for ( nat i = 0; i < _size; ++i ) ((T*)_data)[i] = r[i]; return *this; } CmbSuite & operator= ( const CmbSuite & a ) { return this->operator= ( ( const CArrRef<T> &) a ); } }; /********************* LtdSuiteRef *********************/ /*** Ссылка на набор элементов ограниченного размера ***/ template <class T> class LtdSuiteRef : public SuiteRef<T> { public: LtdSuiteRef ( ArrRef<T> a, nat i, nat n ) : SuiteRef<T>( &a[i], 0 ) { real_size = n; #ifdef ARRAY_TEST if ( a.size() < i + n ) outOfRange ( "LtdSuiteRef", a.size(), i + n ); #endif } LtdSuiteRef & operator= ( const CArrRef<T> & r ) { _size = r.size(); #ifdef ARRAY_TEST if ( _size > real_size ) outOfRange ( "LtdSuiteRef::operator=", real_size, _size ); #endif if ( _size > real_size ) _size = real_size; for ( nat i = 0; i < _size; ++i ) ((T*)_data)[i] = r[i]; return *this; } LtdSuiteRef & operator= ( const LtdSuiteRef & a ) { return this->operator= ( ( const CArrRef<T> &) a ); } DynArrRef<T> & resize ( nat n = 0 ) { #ifdef ARRAY_TEST if ( n > real_size ) outOfRange ( "LtdSuiteRef::resize", real_size, n ); #endif _size = n < real_size ? n : real_size; return *this; } T & inc () { if ( _size < real_size ) ++_size; #ifdef ARRAY_TEST else outOfRange ( "LtdSuiteRef::inc", real_size, _size ); #endif return ((T*)_data)[_size-1]; } SuiteRef<T> & addAftLas ( const CArrRef<T> & a ) { nat n = _size + a.size(); if ( n > real_size ) n = real_size; for ( nat i = _size; i < n; ++i ) ((T*)_data)[i] = a[i-_size]; _size = n; return *this; } }; /**************** Операции с массивами без изменений *****************/ template <class T> inline bool operator == ( const CArrRef<T> & a, const CArrRef<T> & b ) { if ( a.size() != b.size() ) return false; for ( nat i = 0; i < a.size(); ++i ) if ( a[i] != b[i] ) return false; return true; } template <class T> inline bool operator != ( const CArrRef<T> & a, const CArrRef<T> & b ) { if ( a.size() != b.size() ) return true; for ( nat i = 0; i < a.size(); ++i ) if ( a[i] != b[i] ) return true; return false; } template <class T> inline nat count ( const CArrRef<T> & a, const T & b ) { nat n = 0; for ( nat i = 0; i < a.size(); ++i ) if ( a[i] == b ) ++n; return n; } template <class T> inline nat firEqu ( const CArrRef<T> & a, const T & b ) { for ( nat i = 0; i < a.size(); ++i ) if ( a[i] == b ) return i; return a.size(); } template <class T> inline nat lasEqu ( const CArrRef<T> & a, const T & b ) { for ( nat i = a.size(); i > 0; --i ) if ( a[i-1] == b ) return i-1; return a.size(); } template <class T> inline nat firMin ( const CArrRef<T> & a ) { nat m = 0; for ( nat i = 1; i < a.size(); ++i ) if ( a[i] < a[m] ) m = i; return m; } template <class T> inline nat firMax ( const CArrRef<T> & a ) { nat m = 0; for ( nat i = 1; i < a.size(); ++i ) if ( a[i] > a[m] ) m = i; return m; } template <class T> inline Def<T> amean ( const CArrRef<T> & a ) { if ( a.size() == 0 ) return Def<T>(); T res ( a[0] ); for ( nat i = 1; i < a.size(); ++i ) res += a[i]; return res / a.size(); } /*********************** CFor012 ************************/ template <class T> class CFor012 { public: const CArrRef<T> & ref; explicit CFor012 ( const CArrRef<T> & a ) : ref ( a ) {} }; template <class T> inline CFor012<T> cfor012 ( const CArrRef<T> & a ) { return CFor012<T> ( a ); } template <class T1, class T2> inline T1 & operator += ( T1 & t, const CFor012<T2> & a ) { for ( nat i = 0; i < a.ref.size(); ++i ) t += a.ref[i]; return t; } template <class T1, class T2> inline T1 & operator << ( T1 & t, const CFor012<T2> & a ) { for ( nat i = 0; i < a.ref.size(); ++i ) t << a.ref[i]; return t; } /********* Операции с упорядоченными массивами **********/ template <class T> inline nat lasEqu123 ( CArrRef<T> a, const T & b ) { if ( a.size() == 0 ) return 0; nat from = 0, before = a.size(); while ( from + 1 < before ) { const nat i = ( from + before ) / 2; if ( a[i] > b ) before = i; else from = i; } return a[from] == b ? from : a.size(); } /**************** Операции с массивами с изменениями *****************/ template <class T> inline ArrRef<T> & operator <<= ( ArrRef<T> & a, nat n ) { if ( a.size() < 2 ) return a; T t; while ( n > 0 ) { --n; t = a[0]; for ( nat i = 1; i < a.size(); ++i ) a[i-1] = a[i]; a[a.size()-1] = t; } return a; } template <class T> inline ArrRef<T> & operator >>= ( ArrRef<T> & a, nat n ) { if ( a.size() < 2 ) return a; T t; while ( n > 0 ) { --n; t = a[a.size()-1]; for ( nat i = a.size()-1; i > 0; --i ) a[i] = a[i-1]; a[0] = t; } return a; } /*********************** For012 ************************/ template <class T> class For012 { ArrRef<T> & ref; public: explicit For012 ( ArrRef<T> & a ) : ref ( a ) {} template <class T2> ArrRef<T> & operator = ( const T2 & a ) { for ( nat i = 0; i < ref.size(); ++i ) ref[i] = a; return ref; } template <class T2> ArrRef<T> & operator += ( const T2 & a ) { for ( nat i = 0; i < ref.size(); ++i ) ref[i] += a; return ref; } template <class T2> ArrRef<T> & operator -= ( const T2 & a ) { for ( nat i = 0; i < ref.size(); ++i ) ref[i] -= a; return ref; } template <class T2> ArrRef<T> & operator *= ( const T2 & a ) { for ( nat i = 0; i < ref.size(); ++i ) ref[i] *= a; return ref; } template <class T2> ArrRef<T> & operator /= ( const T2 & a ) { for ( nat i = 0; i < ref.size(); ++i ) ref[i] /= a; return ref; } template <class T2> ArrRef<T> & operator %= ( const T2 & a ) { for ( nat i = 0; i < ref.size(); ++i ) ref[i] %= a; return ref; } }; template <class T> inline For012<T> for012 ( ArrRef<T> & a ) { return For012<T> ( a ); } /********************** For012f ************************/ template <class T> class For012f { ArrRef<T> & ref; public: explicit For012f ( ArrRef<T> & a ) : ref ( a ) {} template <class T2> ArrRef<T> & operator = ( T2 & f ) { for ( nat i = 0; i < ref.size(); ++i ) ref[i] = f(); return ref; } }; template <class T> inline For012f<T> for012f ( ArrRef<T> & a ) { return For012f<T> ( a ); } #endif
[ "shevchenka@narod.ru" ]
shevchenka@narod.ru
0d085c4aef95ed9070c5beb83a45227debd65d70
27e84530882e5a5513fc0d91ed83d1d938742e7b
/Inicio.h
483353afcf1f2e079a11a081f59b061fab49bb7d
[]
no_license
jsalvag/ConsultorioOdontologico
40cff7080ca5679b56a62287fba9ced7e9316b9d
2aab07d1a5811b8b092c2a330f8208420aae1a29
refs/heads/master
2021-01-19T08:33:24.077245
2013-11-03T16:23:52
2013-11-03T16:23:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,093
h
//--------------------------------------------------------------------------- #ifndef InicioH #define InicioH //--------------------------------------------------------------------------- #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> #include <Menus.hpp> #include <ExtCtrls.hpp> #include <ComCtrls.hpp> #include <Mask.hpp> //--------------------------------------------------------------------------- class TForm1 : public TForm { __published: // IDE-managed Components TMainMenu *MainMenu1; TMenuItem *Archivo1; TMenuItem *Salir1; TMenuItem *Pcientes1; TMenuItem *Ingresar1; TMenuItem *Lista1; TMenuItem *Citas1; TMenuItem *Ingresar2; TMenuItem *Buscar1; TMenuItem *Reportes1; TMenuItem *Citasdelda1; TMenuItem *Buscarcitas1; TMenuItem *Citaspormes1; TMenuItem *Citasporedad1; TMenuItem *Estadisticas1; TMenuItem *Promedioanual1; TMenuItem *Promediosemanal1; TPanel *Panel1; TButton *Button1; TLabel *Label1; TMonthCalendar *MonthCalendar1; TLabel *Label2; TComboBox *ComboBox1; TLabel *Label3; TEdit *Edit1; TLabel *Label4; TMemo *Memo1; TLabel *Label5; TLabel *ci; TLabel *Label7; TLabel *ed; TLabel *Label9; TLabel *sex; TLabel *Label11; TLabel *tlf; TLabel *Label13; TLabel *dir; TPanel *Panel2; TLabel *Label6; TGroupBox *GroupBox1; TLabel *Label8; TButton *Button2; TLabel *Label10; TLabel *Label12; TLabel *Label14; TLabel *Label15; TLabel *Label16; TLabel *Label17; TLabel *Label18; TLabel *Label19; TLabel *Label20; TLabel *Label21; TMemo *Memo2; TListBox *ListBox1; TEdit *MaskEdit1; void __fastcall Salir1Click(TObject *Sender); void __fastcall Ingresar1Click(TObject *Sender); void __fastcall Lista1Click(TObject *Sender); void __fastcall Ingresar2Click(TObject *Sender); void __fastcall Button1Click(TObject *Sender); void __fastcall MonthCalendar1Click(TObject *Sender); void __fastcall ComboBox1Change(TObject *Sender); void __fastcall Buscar1Click(TObject *Sender); void __fastcall Button2Click(TObject *Sender); void __fastcall Citasdelda1Click(TObject *Sender); void __fastcall Buscarcitas1Click(TObject *Sender); void __fastcall Citaspormes1Click(TObject *Sender); void __fastcall Citasporedad1Click(TObject *Sender); void __fastcall Promedioanual1Click(TObject *Sender); private: // User declarations public: // User declarations __fastcall TForm1(TComponent* Owner); }; //--------------------------------------------------------------------------- extern PACKAGE TForm1 *Form1; //--------------------------------------------------------------------------- #endif
[ "jsalvag@gmail.com" ]
jsalvag@gmail.com
1f19986f6eb107592a187ce8a82eb7011c77b274
72b507a7255d2c7f747902a2c33f9c80f35c689a
/debug/moc_scene.cpp
e54baec373c7f9f5782ff6e59d3ceaf81f7592e8
[]
no_license
alborzp/DEKUMED
4aeaf7c3b5c7e1a755662fbae6f7e3eb5016a704
91f1c7bdf23a721d4a9856f3331348c2f0bc02d5
refs/heads/master
2021-05-19T07:12:55.165702
2020-03-31T11:26:27
2020-03-31T11:26:27
251,580,209
0
0
null
null
null
null
UTF-8
C++
false
false
4,311
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'scene.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.14.1) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include <memory> #include "../scene.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'scene.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.14.1. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_SceneClass_t { QByteArrayData data[8]; char stringdata0[79]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_SceneClass_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_SceneClass_t qt_meta_stringdata_SceneClass = { { QT_MOC_LITERAL(0, 0, 10), // "SceneClass" QT_MOC_LITERAL(1, 11, 12), // "setGridsizeX" QT_MOC_LITERAL(2, 24, 0), // "" QT_MOC_LITERAL(3, 25, 8), // "newXGrid" QT_MOC_LITERAL(4, 34, 12), // "setGridsizeY" QT_MOC_LITERAL(5, 47, 5), // "value" QT_MOC_LITERAL(6, 53, 12), // "getXForShape" QT_MOC_LITERAL(7, 66, 12) // "getYForShape" }, "SceneClass\0setGridsizeX\0\0newXGrid\0" "setGridsizeY\0value\0getXForShape\0" "getYForShape" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_SceneClass[] = { // content: 8, // revision 0, // classname 0, 0, // classinfo 4, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 1, 34, 2, 0x0a /* Public */, 4, 1, 37, 2, 0x0a /* Public */, 6, 0, 40, 2, 0x0a /* Public */, 7, 0, 41, 2, 0x0a /* Public */, // slots: parameters QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, QMetaType::Int, 5, QMetaType::Int, QMetaType::Int, 0 // eod }; void SceneClass::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { auto *_t = static_cast<SceneClass *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->setGridsizeX((*reinterpret_cast< int(*)>(_a[1]))); break; case 1: _t->setGridsizeY((*reinterpret_cast< int(*)>(_a[1]))); break; case 2: { int _r = _t->getXForShape(); if (_a[0]) *reinterpret_cast< int*>(_a[0]) = std::move(_r); } break; case 3: { int _r = _t->getYForShape(); if (_a[0]) *reinterpret_cast< int*>(_a[0]) = std::move(_r); } break; default: ; } } } QT_INIT_METAOBJECT const QMetaObject SceneClass::staticMetaObject = { { QMetaObject::SuperData::link<QGraphicsScene::staticMetaObject>(), qt_meta_stringdata_SceneClass.data, qt_meta_data_SceneClass, qt_static_metacall, nullptr, nullptr } }; const QMetaObject *SceneClass::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *SceneClass::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_SceneClass.stringdata0)) return static_cast<void*>(this); return QGraphicsScene::qt_metacast(_clname); } int SceneClass::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QGraphicsScene::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 4) qt_static_metacall(this, _c, _id, _a); _id -= 4; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 4) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 4; } return _id; } QT_WARNING_POP QT_END_MOC_NAMESPACE
[ "alborz.poorrahim@gmail.com" ]
alborz.poorrahim@gmail.com
c73cbe697d932093c057f0910a2fc23636d33b94
fca785d6e67eadcd6d1a9ed9b315177355114c86
/src/082.cpp
10808848cb878e150a2729146d8d7ddf0040b2aa
[]
no_license
XihanLiu/LeetCode
31333c403042f05b7bf3b04e989d6f97fcd81d69
c07f479cc9aa20567e35d97f32a1ba385663249b
refs/heads/master
2023-03-15T22:55:25.536338
2013-12-07T06:38:59
2013-12-07T06:38:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
832
cpp
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *deleteDuplicates(ListNode *head) { // Start typing your C/C++ solution below // DO NOT write int main() function if (head == NULL || head->next == NULL) return head; ListNode *prev = NULL, *cur = head; while (cur != NULL) { while (cur->next != NULL && cur->val == cur->next->val) { cur = cur->next; } if (prev == NULL) { head = cur; prev = head; } else { prev->next = cur; prev = cur; } if (cur != NULL) cur = cur->next; } } };
[ "jiaxiang.zheng135@gmail.com" ]
jiaxiang.zheng135@gmail.com
c4b28ae42fae07a8b933a030d3fac87df854631f
ecb3cc61af2292a432bd4f208cd980c626305a8c
/A star serach.cpp
cc32822bc2dc212130d3b651848a8536bb99308d
[]
no_license
njrafi/Code-Library
785499692ecfc5d89938967f962d04ccd7b8f05d
a5a18479d7ffc8094ba5ac05bee4ac815225534f
refs/heads/master
2021-11-18T12:11:53.574716
2021-10-03T10:59:54
2021-10-03T10:59:54
151,953,480
3
0
null
null
null
null
UTF-8
C++
false
false
117
cpp
/* Similar to dijkstra With distance and state we push a heuristic and sort the priority queue with it */
[ "njrafibd@gmail.com" ]
njrafibd@gmail.com
eb04e444c7f4cd0b24fb903cf3e306a82877be12
8f6990502b2d329fd221a55198001e800f0a9c47
/src/overwrite_serial_number.cpp
2daf555afd1619ec8f2057f3deebb682d7d9eec5
[ "BSD-3-Clause" ]
permissive
kobuki-base/kobuki_ftdi
03726c2f0c76db3e9607857f51413bcb91b7d905
a7e9d5783e78a9666084bfe797c7b663f3770aff
refs/heads/devel
2020-12-08T10:49:48.683322
2020-08-30T15:47:48
2020-08-30T15:47:48
232,963,869
0
2
NOASSERTION
2020-08-20T02:47:50
2020-01-10T04:14:01
C++
UTF-8
C++
false
false
2,733
cpp
/* * License: BSD * URL: https://raw.githubusercontent.com/kobuki-base/kobuki_ftdi/license/LICENSE */ /** * @file src/overwrite_serial_number.cpp * @brief Overwrite serial number of ftdi device. * * <b>License:</b> BSD https://raw.github.com/yujinrobot/kobuki_core/hydro-devel/kobuki_ftdi/LICENSE **/ /***************************************************************************** ** Includes *****************************************************************************/ #include <iostream> #include <ecl/command_line.hpp> #include "kobuki_ftdi/writer.hpp" #include "kobuki_ftdi/scanner.hpp" /***************************************************************************** ** Using *****************************************************************************/ using ecl::CmdLine; using ecl::UnlabeledValueArg; using ecl::ValueArg; using ecl::SwitchArg; using std::string; /***************************************************************************** ** Main *****************************************************************************/ int main(int argc, char **argv) { /********************* ** Parse Command Line **********************/ CmdLine cmd_line("This is used to write a new serial id string to the ftdi device.", ' ', "0.1"); ValueArg<std::string> old_arg( "o", "old", "Identify the device via the old serial id (if there are multiple devices attached) ['unspecified'].", false, "unspecified", "string"); UnlabeledValueArg<std::string> new_arg("new_id", "New serial id used to identify the device [xxx].", true, "xxx", "string"); cmd_line.add(old_arg); cmd_line.add(new_arg); cmd_line.parse(argc, argv); bool using_old_id = false; string old_id; if (old_arg.getValue() != "unspecified") { using_old_id = true; old_id = old_arg.getValue(); } string new_id = new_arg.getValue(); /********************* ** Debug output **********************/ std::cout << "Input Information" << std::endl; if (!using_old_id) { std::cout << " Old id: unused (first device found.)" << std::endl; } else { std::cout << " Old id: " << old_id << std::endl; } std::cout << " New id: " << new_id << std::endl; /********************* ** Writing serial id **********************/ FTDI_Writer writer; int ret_val = 0; ret_val = writer.write(new_id); if (ret_val<0) { std::cerr << "Something went wrong." << std::endl; return ret_val; } FTDI_Scanner scanner; ret_val = scanner.reset(); if (ret_val<0 && ret_val !=-19) { std::cerr << "Something went wrong." << std::endl; return ret_val; } std::cout << "ret_val: " << ret_val << std::endl; return 0; }
[ "d.stonier@gmail.com" ]
d.stonier@gmail.com
d02912a9b2896160ca91c60437340997ff95f911
4be3bb67e216066d7864db067be7f3319a2cb33a
/main/src/ftworker.cpp
e70b0864359c998e926be6859e29a7051932c54d
[]
no_license
f0ghua/ecuEmulator
a63cabe389f5bb363ae18c05ec595c52092c3693
d7d8c45ea9395dac046992c58fbb5d6813535092
refs/heads/master
2020-12-02T21:22:53.088955
2017-07-18T06:16:03
2017-07-18T06:16:03
96,305,008
2
0
null
null
null
null
UTF-8
C++
false
false
6,130
cpp
#include "xcommdefine.h" #include "xbusmgr.h" #include "ftworker.h" #include <pthread.h> #include <windows.h> #include <QDebug> #include <QObject> #ifdef Q_OS_LINUX #include <sys/time.h> #else typedef struct _EVENT_HANDLE { pthread_cond_t eCondVar; pthread_mutex_t eMutex; int iVar; } EVENT_HANDLE; #if defined(_MSC_VER) || defined(_MSC_EXTENSIONS) #define DELTA_EPOCH_IN_MICROSECS 11644473600000000Ui64 #else #define DELTA_EPOCH_IN_MICROSECS 11644473600000000ULL #endif int gettimeofday(struct timeval *tv, struct timezone *) { FILETIME ft; unsigned __int64 tmpres = 0; if (NULL != tv) { GetSystemTimeAsFileTime(&ft); tmpres |= ft.dwHighDateTime; tmpres <<= 32; tmpres |= ft.dwLowDateTime; tmpres /= 10; /*convert into microseconds*/ /*converting file time to unix epoch*/ tmpres -= DELTA_EPOCH_IN_MICROSECS; tv->tv_sec = (long)(tmpres / 1000000UL); tv->tv_usec = (long)(tmpres % 1000000UL); } return 0; } #endif //Q_OS_LINUX FtWorker::FtWorker(XBusMgr *mgr) :HAL(mgr, 1) { raw.clear(); RxBuffer = (char *)calloc(128 * 1024, 1); } void FtWorker::PhyOpenDevice(QString tryDev, HANDLE &eh) { FT_STATUS ftStatus; DWORD EventDWord, TxBytes, RxBytes, EventMask = FT_EVENT_RXCHAR | FT_EVENT_MODEM_STATUS; //printf("%s\n", tryDev.toLatin1().data()); ftStatus = FT_OpenEx(tryDev.toLatin1().data(), FT_OPEN_BY_SERIAL_NUMBER, &ftHandle); if (ftStatus != FT_OK) { printf("FT_OpenEx failed (error code %d), %s\n", (int)ftStatus, tryDev.toLatin1().data()); return; } ftStatus = FT_SetDivisor(ftHandle, 0); if (ftStatus == FT_OK) { //printf("setbaund ok\n"); } else { printf("setbaund fail\n"); } ftStatus = FT_SetDataCharacteristics(ftHandle, FT_BITS_8, FT_STOP_BITS_1, FT_PARITY_NONE); if (ftStatus == FT_OK) { //printf("set 8n1 ok\n"); } else { printf("set 8n1 fail\n"); } ftStatus = FT_SetFlowControl(ftHandle, FT_FLOW_NONE, 0x11, 0x13); if (ftStatus == FT_OK) { //printf("set flow ok\n"); } else { printf("set flow fail\n"); } ftStatus = FT_SetDtr(ftHandle); if (ftStatus == FT_OK) { //printf("set dtr ok\n"); } else { printf("set dtr fail\n"); } ftStatus = FT_SetRts(ftHandle); if (ftStatus == FT_OK) { //printf("set rts ok\n"); } else { printf("set rts fail\n"); } ftStatus = FT_SetLatencyTimer(ftHandle, 2); if (ftStatus == FT_OK) { qDebug() << "set timeouts ok"; } else { qDebug() << "set timeouts fail"; } qDebug() << dev << " open ok";; eh = ::CreateEvent(NULL, false, false, reinterpret_cast<LPCWSTR>("")); ftStatus = FT_SetEventNotification(ftHandle, EventMask, (PVOID)eh); if (ftStatus == FT_OK) { //printf("set ev ok\n"); } else { printf("set ev fail\n"); return; } FT_GetStatus(ftHandle,&RxBytes,&TxBytes,&EventDWord); emit updateDeviceConnState(OPEN_SUCC); } void FtWorker::PhyCloseDevice() { if(ftHandle != NULL) { (void)FT_Close(ftHandle); ftHandle = NULL; emit updateDeviceConnState(CLOSE_SUCC); needToClose = 0; printf("ft closed\n"); } } void FtWorker::sigRefreshDevice() { getList = 1; qc.wakeAll(); } void FtWorker::listDevice() { FT_STATUS ftStatus; DWORD numDevs = 0; int i, retry = 0; deviceList.clear(); ftStatus = FT_CreateDeviceInfoList(&numDevs); if (ftStatus != FT_OK) { printf("FT_CreateDeviceInfoList failed (error code %d)\n", (int)ftStatus); return; } if (numDevs > 0) { FT_DEVICE_LIST_INFO_NODE *devInfo; devInfo = (FT_DEVICE_LIST_INFO_NODE *)malloc(sizeof(FT_DEVICE_LIST_INFO_NODE)*numDevs); ftStatus = ::FT_GetDeviceInfoList(devInfo, &numDevs); if (ftStatus == FT_OK) { for (unsigned int i = 0; i < numDevs; ++i) { if (*devInfo[i].SerialNumber != '\0') deviceList << QString(devInfo[i].SerialNumber); } } free(devInfo); } #if 0 for (i = 0; i < (int)numDevs; i++) { char SerialNumber[64]; memset(SerialNumber, 0, sizeof(SerialNumber)); ftStatus = FT_ListDevices((PVOID)(uintptr_t) i, SerialNumber,FT_LIST_BY_INDEX|FT_OPEN_BY_SERIAL_NUMBER); if(strlen(SerialNumber) == 0 && retry < 8) { i--; continue; retry++; } else retry = 0; deviceList << QString(SerialNumber); } #endif emit updateDeviceList(deviceList); } void FtWorker::sigOpenDevice(QString tryDev) { if(dev != tryDev) { if(ftHandle != NULL) sigCloseDevice(0); dev = tryDev; qc.wakeAll(); } } void FtWorker::sigCloseDevice(int) { needToClose = 1; dev = ""; } void FtWorker::run() { HANDLE eh; while(shutdown == 0) { if(ftHandle == NULL) { if(dev.size() == 0) { m.lock(); qc.wait(&m); m.unlock(); } if(getList == 1) { getList = 0; listDevice(); continue; } PhyOpenDevice(dev, eh); getv = 1; } ::WaitForSingleObject(eh, INFINITE); if(needToClose == 1) PhyCloseDevice(); else dealWithEvent(); } } void FtWorker::dealWithEvent() { DWORD TxBytes, RxBytes, Status, EventDWord; FT_GetStatus(ftHandle,&RxBytes, &TxBytes, &EventDWord); if (EventDWord & FT_EVENT_MODEM_STATUS) { FT_GetModemStatus(ftHandle,&Status); if (Status & 0x00000010) { // CTS is high } else { // CTS is low } if (Status & 0x00000020) { // DSR is high } else { // DSR is low } } else if (RxBytes > 0) dealWithRx(RxBytes); } void FtWorker::dealWithRx(int RxBytes) { DWORD BytesReceived = 0; FT_STATUS ftStatus; int soFar = 0; while(RxBytes > 0) { ftStatus = FT_Read(ftHandle, RxBuffer + soFar, RxBytes, &BytesReceived); if (ftStatus == FT_OK) { RxBytes -= BytesReceived; soFar += BytesReceived; } else { // FT_Read Failed } } for (int i = 0; i < soFar; i++) procRXChar(RxBuffer[i]); } void FtWorker::halWrite(QByteArray &buffer) { DWORD BytesWritten = 0, soFar = 0; FT_STATUS ftStatus; char tmp[4096]; if(ftHandle == NULL) return; if(buffer.size() == 0) return; memcpy(tmp, buffer.data(), buffer.size()); while(soFar != (DWORD) buffer.size()) { ftStatus = FT_Write(ftHandle, tmp + soFar, buffer.size() - soFar, &BytesWritten); if (ftStatus == FT_OK) soFar += BytesWritten; } FT_SetRts(ftHandle); }
[ "fog.hua@gmail.com" ]
fog.hua@gmail.com
a90ab58a991cd0dad9fa02a11f15d6a5c4efa5b4
5280876069677a667c29245157e99f7fa7c99ce7
/IMDB/include/func.hpp
e3a8a5684a8b8e64a515030b8a42f2b247270ae2
[]
no_license
alizeinodin/imdbpractice
9fe67c9b166619698dbd8ec72be986901189c120
5c2acdb78ec0224ed5b88b967b80850006d28934
refs/heads/main
2023-03-26T16:35:46.446789
2021-03-25T09:19:51
2021-03-25T09:19:51
351,361,599
1
0
null
null
null
null
UTF-8
C++
false
false
695
hpp
#ifndef FUNK_H #define FUNK_H void add(Movie, Movie * &, int &); void remove(std::string, Movie * &, int &); void show(std::string, Movie * &, int &); void show_all(Movie * &, int &); void sort_by(Movie * &, std::string, int &, bool (*function)(Movie * &, std::string, int)); void avg_score(Movie *, int); void help(); bool checkmovie(std::string, Movie *, int, int &); // check for available movie's in list void score_details(std::string, Movie*, int &); void order_adjust(std::string &); void Command_Separator(std::string, Movie * &, int &); bool help_sort(Movie * & array, std::string select, int j); // passing this funcion to sort_by for sorting by name's or score's #endif // !FUNK_H
[ "alizeinodin79@gmail.com" ]
alizeinodin79@gmail.com
213dcad1eb820e48c5b032ba51c2d12b9eb49a82
0b933ebb80380f91aff695150a2fe5823675ba9c
/test/basic_pb_tests.cpp
c9879ea6c18d884ee3f2e59fb8c4a43861c5284e
[ "MIT" ]
permissive
prismskylabs/PriorityBuffer
f8b1f2b9f6f46566b050847cb93e8fe2c862b134
e19fdb2988f8ec2184780378dfe0297b2a91faba
refs/heads/master
2022-04-29T09:33:29.915483
2022-03-19T00:37:44
2022-03-19T00:37:44
33,696,434
3
1
null
null
null
null
UTF-8
C++
false
false
2,898
cpp
#include <gtest/gtest.h> #include <chrono> #include <memory> #include <string> #include <thread> #include <vector> #include "basic.pb.h" #include "fsfixture.h" #include "prioritybuffer.h" #ifndef NUMBER_MESSAGES_IN_TEST #define NUMBER_MESSAGES_IN_TEST 1000 #endif TEST_F(FSFixture, DefaultPriorityTest) { PriorityBuffer<Basic> basics; for (int i = 0; i < NUMBER_MESSAGES_IN_TEST; ++i) { auto basic = std::unique_ptr<Basic>{ new Basic{} }; basic->set_value(std::to_string(i)); EXPECT_EQ(std::to_string(i), basic->value()); EXPECT_TRUE(basic->IsInitialized()); basics.Push(std::move(basic)); std::this_thread::sleep_for(std::chrono::nanoseconds(1)); } for (int i = NUMBER_MESSAGES_IN_TEST - 1; i >= 0; --i) { auto basic = basics.Pop(); EXPECT_TRUE(basic->IsInitialized()); EXPECT_EQ(std::to_string(i), basic->value()); } } unsigned long long reverse_priority(const Basic& basic) { return 20000000000000000LL - std::chrono::steady_clock::now().time_since_epoch().count(); } TEST_F(FSFixture, ReversePriorityTest) { PriorityBuffer<Basic> basics{reverse_priority}; for (int i = 0; i < NUMBER_MESSAGES_IN_TEST; ++i) { auto basic = std::unique_ptr<Basic>{ new Basic{} }; basic->set_value(std::to_string(i)); EXPECT_TRUE(basic->IsInitialized()); EXPECT_EQ(std::to_string(i), basic->value()); basics.Push(std::move(basic)); std::this_thread::sleep_for(std::chrono::nanoseconds(1)); } for (int i = 0; i < NUMBER_MESSAGES_IN_TEST; ++i) { auto basic = basics.Pop(); EXPECT_TRUE(basic->IsInitialized()); EXPECT_EQ(std::to_string(i), basic->value()); } } TEST_F(FSFixture, OutOfOrderTest) { std::vector<unsigned long long> ordered_priorities{5, 3, 7, 1, 8, 2}; int priority_at = 0; auto ordered_priority = [&ordered_priorities, &priority_at] (const Basic& basic) -> unsigned long long { return ordered_priorities[priority_at++]; }; PriorityBuffer<Basic> basics{ordered_priority}; for (auto& priority : ordered_priorities) { auto basic = std::unique_ptr<Basic>{ new Basic{} }; basic->set_value(std::to_string(priority)); EXPECT_TRUE(basic->IsInitialized()); EXPECT_EQ(std::to_string(priority), basic->value()); basics.Push(std::move(basic)); std::this_thread::sleep_for(std::chrono::nanoseconds(1)); } std::sort(ordered_priorities.rbegin(), ordered_priorities.rend()); for (auto& priority : ordered_priorities) { auto basic = basics.Pop(); EXPECT_TRUE(basic->IsInitialized()); EXPECT_EQ(std::to_string(priority), basic->value()); } } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); GOOGLE_PROTOBUF_VERIFY_VERSION; return RUN_ALL_TESTS(); }
[ "huu@prismskylabs.com" ]
huu@prismskylabs.com
f558103de9b69adb39ea92ff10a7f2e99d31b83b
9ca6885d197aaf6869e2080901b361b034e4cc37
/DQM/EcalBarrelMonitorClient/interface/EcalDQMonitorClient.h
47cf1dc12f4fb4ca31612907366187affd3d9a5e
[]
no_license
ktf/cmssw-migration
153ff14346b20086f908a370029aa96575a2c51a
583340dd03481dff673a52a2075c8bb46fa22ac6
refs/heads/master
2020-07-25T15:37:45.528173
2013-07-11T04:54:56
2013-07-11T04:54:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
914
h
#ifndef EcalDQMonitorClient_H #define EcalDQMonitorClient_H #include "DQM/EcalCommon/interface/EcalDQMonitor.h" namespace edm{ class ParameterSet; class Run; class LuminosityBlock; class Event; class EventSetup; class ConfigurationDescriptions; } namespace ecaldqm{ class DQWorkerClient; } class EcalDQMonitorClient : public EcalDQMonitor { public: EcalDQMonitorClient(const edm::ParameterSet &); ~EcalDQMonitorClient(); static void fillDescriptions(edm::ConfigurationDescriptions &); private: void beginRun(const edm::Run&, const edm::EventSetup&); void endRun(const edm::Run&, const edm::EventSetup&); void beginLuminosityBlock(const edm::LuminosityBlock&, const edm::EventSetup&); void endLuminosityBlock(const edm::LuminosityBlock&, const edm::EventSetup&); void analyze(const edm::Event&, const edm::EventSetup&) {} void runWorkers(); int lumiStatus_; }; #endif
[ "sha1-b63dc01a642d380a16da36b4e834787802efdeb4@cern.ch" ]
sha1-b63dc01a642d380a16da36b4e834787802efdeb4@cern.ch
44cd7fffcdfad13fec8f8e52b52521a09a26f067
d9f59c9f35c4e35b07ba757f9c23b3f82aff2f00
/CustomSceneNode/src/main/jni/include/IFileSystem.h
faebdc578d081d159da8a9e7d2b581fc6fccaecc
[]
no_license
marky0720/irrlicht_Android_ogl_es
44d5f9097b4fc328a204e9a98a0ae92dd13471a4
4c94b4ba2ee833015ff8e83855e5b92a539bcc6b
refs/heads/master
2020-04-07T12:27:10.852174
2018-03-20T09:52:50
2018-03-20T09:52:50
124,211,363
1
1
null
null
null
null
UTF-8
C++
false
false
19,470
h
// Copyright (C) 2002-2012 Nikolaus Gebhardt // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #ifndef __I_FILE_SYSTEM_H_INCLUDED__ #define __I_FILE_SYSTEM_H_INCLUDED__ #include "IReferenceCounted.h" #include "IXMLReader.h" #include "IFileArchive.h" namespace irr { namespace video { class IVideoDriver; } // end namespace video namespace io { class IReadFile; class IWriteFile; class IFileList; class IXMLWriter; class IAttributes; //! The FileSystem manages files and archives and provides access to them. /** It manages where files are, so that modules which use the the IO do not need to know where every file is located. A file could be in a .zip-Archive or as file on disk, using the IFileSystem makes no difference to this. */ class IFileSystem : public virtual IReferenceCounted { public: //! Opens a file for read access. /** \param filename: Name of file to open. \return Pointer to the created file interface. The returned pointer should be dropped when no longer needed. See IReferenceCounted::drop() for more information. */ virtual IReadFile* createAndOpenFile(const path& filename) =0; //! Creates an IReadFile interface for accessing memory like a file. /** This allows you to use a pointer to memory where an IReadFile is requested. \param memory: A pointer to the start of the file in memory \param len: The length of the memory in bytes \param fileName: The name given to this file \param deleteMemoryWhenDropped: True if the memory should be deleted along with the IReadFile when it is dropped. \return Pointer to the created file interface. The returned pointer should be dropped when no longer needed. See IReferenceCounted::drop() for more information. */ virtual IReadFile* createMemoryReadFile(const void* memory, s32 len, const path& fileName, bool deleteMemoryWhenDropped=false) =0; //! Creates an IReadFile interface for accessing files inside files. /** This is useful e.g. for archives. \param fileName: The name given to this file \param alreadyOpenedFile: Pointer to the enclosing file \param pos: Start of the file inside alreadyOpenedFile \param areaSize: The length of the file \return A pointer to the created file interface. The returned pointer should be dropped when no longer needed. See IReferenceCounted::drop() for more information. */ virtual IReadFile* createLimitReadFile(const path& fileName, IReadFile* alreadyOpenedFile, long pos, long areaSize) =0; //! Creates an IWriteFile interface for accessing memory like a file. /** This allows you to use a pointer to memory where an IWriteFile is requested. You are responsible for allocating enough memory. \param memory: A pointer to the start of the file in memory (allocated by you) \param len: The length of the memory in bytes \param fileName: The name given to this file \param deleteMemoryWhenDropped: True if the memory should be deleted along with the IWriteFile when it is dropped. \return Pointer to the created file interface. The returned pointer should be dropped when no longer needed. See IReferenceCounted::drop() for more information. */ virtual IWriteFile* createMemoryWriteFile(void* memory, s32 len, const path& fileName, bool deleteMemoryWhenDropped=false) =0; //! Opens a file for write access. /** \param filename: Name of file to open. \param append: If the file already exist, all write operations are appended to the file. \return Pointer to the created file interface. 0 is returned, if the file could not created or opened for writing. The returned pointer should be dropped when no longer needed. See IReferenceCounted::drop() for more information. */ virtual IWriteFile* createAndWriteFile(const path& filename, bool append=false) =0; //! Adds an archive to the file system. /** After calling this, the Irrlicht Engine will also search and open files directly from this archive. This is useful for hiding data from the end user, speeding up file access and making it possible to access for example Quake3 .pk3 files, which are just renamed .zip files. By default Irrlicht supports ZIP, PAK, TAR, PNK, and directories as archives. You can provide your own archive types by implementing IArchiveLoader and passing an instance to addArchiveLoader. Irrlicht supports AES-encrypted zip files, and the advanced compression techniques lzma and bzip2. \param filename: Filename of the archive to add to the file system. \param ignoreCase: If set to true, files in the archive can be accessed without writing all letters in the right case. \param ignorePaths: If set to true, files in the added archive can be accessed without its complete path. \param archiveType: If no specific E_FILE_ARCHIVE_TYPE is selected then the type of archive will depend on the extension of the file name. If you use a different extension then you can use this parameter to force a specific type of archive. \param password An optional password, which is used in case of encrypted archives. \param retArchive A pointer that will be set to the archive that is added. \return True if the archive was added successfully, false if not. */ virtual bool addFileArchive(const path& filename, bool ignoreCase=true, bool ignorePaths=true, E_FILE_ARCHIVE_TYPE archiveType=EFAT_UNKNOWN, const core::stringc& password="", IFileArchive** retArchive=0) =0; //! Adds an archive to the file system. /** After calling this, the Irrlicht Engine will also search and open files directly from this archive. This is useful for hiding data from the end user, speeding up file access and making it possible to access for example Quake3 .pk3 files, which are just renamed .zip files. By default Irrlicht supports ZIP, PAK, TAR, PNK, and directories as archives. You can provide your own archive types by implementing IArchiveLoader and passing an instance to addArchiveLoader. Irrlicht supports AES-encrypted zip files, and the advanced compression techniques lzma and bzip2. If you want to add a directory as an archive, prefix its name with a slash in order to let Irrlicht recognize it as a folder mount (mypath/). Using this technique one can build up a search order, because archives are read first, and can be used more easily with relative filenames. \param file: Archive to add to the file system. \param ignoreCase: If set to true, files in the archive can be accessed without writing all letters in the right case. \param ignorePaths: If set to true, files in the added archive can be accessed without its complete path. \param archiveType: If no specific E_FILE_ARCHIVE_TYPE is selected then the type of archive will depend on the extension of the file name. If you use a different extension then you can use this parameter to force a specific type of archive. \param password An optional password, which is used in case of encrypted archives. \param retArchive A pointer that will be set to the archive that is added. \return True if the archive was added successfully, false if not. */ virtual bool addFileArchive(IReadFile* file, bool ignoreCase=true, bool ignorePaths=true, E_FILE_ARCHIVE_TYPE archiveType=EFAT_UNKNOWN, const core::stringc& password="", IFileArchive** retArchive=0) =0; //! Adds an archive to the file system. /** \param archive: The archive to add to the file system. \return True if the archive was added successfully, false if not. */ virtual bool addFileArchive(IFileArchive* archive) =0; //! Get the number of archives currently attached to the file system virtual u32 getFileArchiveCount() const =0; //! Removes an archive from the file system. /** This will close the archive and free any file handles, but will not close resources which have already been loaded and are now cached, for example textures and meshes. \param index: The index of the archive to remove \return True on success, false on failure */ virtual bool removeFileArchive(u32 index) =0; //! Removes an archive from the file system. /** This will close the archive and free any file handles, but will not close resources which have already been loaded and are now cached, for example textures and meshes. Note that a relative filename might be interpreted differently on each call, depending on the current working directory. In case you want to remove an archive that was added using a relative path name, you have to change to the same working directory again. This means, that the filename given on creation is not an identifier for the archive, but just a usual filename that is used for locating the archive to work with. \param filename The archive pointed to by the name will be removed \return True on success, false on failure */ virtual bool removeFileArchive(const path& filename) =0; //! Removes an archive from the file system. /** This will close the archive and free any file handles, but will not close resources which have already been loaded and are now cached, for example textures and meshes. \param archive The archive to remove. \return True on success, false on failure */ virtual bool removeFileArchive(const IFileArchive* archive) =0; //! Changes the search order of attached archives. /** \param sourceIndex: The index of the archive to change \param relative: The relative change in position, archives with a lower index are searched first */ virtual bool moveFileArchive(u32 sourceIndex, s32 relative) =0; //! Get the archive at a given index. virtual IFileArchive* getFileArchive(u32 index) =0; //! Adds an external archive loader to the engine. /** Use this function to add support for new archive types to the engine, for example proprietary or encrypted file storage. */ virtual void addArchiveLoader(IArchiveLoader* loader) =0; //! Gets the number of archive loaders currently added virtual u32 getArchiveLoaderCount() const = 0; //! Retrieve the given archive loader /** \param index The index of the loader to retrieve. This parameter is an 0-based array index. \return A pointer to the specified loader, 0 if the index is incorrect. */ virtual IArchiveLoader* getArchiveLoader(u32 index) const = 0; //! Adds a zip archive to the file system. /** \deprecated This function is provided for compatibility with older versions of Irrlicht and may be removed in Irrlicht 1.9, you should use addFileArchive instead. After calling this, the Irrlicht Engine will search and open files directly from this archive too. This is useful for hiding data from the end user, speeding up file access and making it possible to access for example Quake3 .pk3 files, which are no different than .zip files. \param filename: Filename of the zip archive to add to the file system. \param ignoreCase: If set to true, files in the archive can be accessed without writing all letters in the right case. \param ignorePaths: If set to true, files in the added archive can be accessed without its complete path. \return True if the archive was added successfully, false if not. */ _IRR_DEPRECATED_ virtual bool addZipFileArchive(const c8* filename, bool ignoreCase=true, bool ignorePaths=true) { return addFileArchive(filename, ignoreCase, ignorePaths, EFAT_ZIP); } //! Adds an unzipped archive (or basedirectory with subdirectories..) to the file system. /** \deprecated This function is provided for compatibility with older versions of Irrlicht and may be removed in Irrlicht 1.9, you should use addFileArchive instead. Useful for handling data which will be in a zip file \param filename: Filename of the unzipped zip archive base directory to add to the file system. \param ignoreCase: If set to true, files in the archive can be accessed without writing all letters in the right case. \param ignorePaths: If set to true, files in the added archive can be accessed without its complete path. \return True if the archive was added successful, false if not. */ _IRR_DEPRECATED_ virtual bool addFolderFileArchive(const c8* filename, bool ignoreCase=true, bool ignorePaths=true) { return addFileArchive(filename, ignoreCase, ignorePaths, EFAT_FOLDER); } //! Adds a pak archive to the file system. /** \deprecated This function is provided for compatibility with older versions of Irrlicht and may be removed in Irrlicht 1.9, you should use addFileArchive instead. After calling this, the Irrlicht Engine will search and open files directly from this archive too. This is useful for hiding data from the end user, speeding up file access and making it possible to access for example Quake2/KingPin/Hexen2 .pak files \param filename: Filename of the pak archive to add to the file system. \param ignoreCase: If set to true, files in the archive can be accessed without writing all letters in the right case. \param ignorePaths: If set to true, files in the added archive can be accessed without its complete path.(should not use with Quake2 paks \return True if the archive was added successful, false if not. */ _IRR_DEPRECATED_ virtual bool addPakFileArchive(const c8* filename, bool ignoreCase=true, bool ignorePaths=true) { return addFileArchive(filename, ignoreCase, ignorePaths, EFAT_PAK); } //! Get the current working directory. /** \return Current working directory as a string. */ virtual const path& getWorkingDirectory() =0; //! Changes the current working directory. /** \param newDirectory: A string specifying the new working directory. The string is operating system dependent. Under Windows it has the form "<drive>:\<directory>\<sudirectory>\<..>". An example would be: "C:\Windows\" \return True if successful, otherwise false. */ virtual bool changeWorkingDirectoryTo(const path& newDirectory) =0; //! Converts a relative path to an absolute (unique) path, resolving symbolic links if required /** \param filename Possibly relative file or directory name to query. \result Absolute filename which points to the same file. */ virtual path getAbsolutePath(const path& filename) const =0; //! Get the directory a file is located in. /** \param filename: The file to get the directory from. \return String containing the directory of the file. */ virtual path getFileDir(const path& filename) const =0; //! Get the base part of a filename, i.e. the name without the directory part. /** If no directory is prefixed, the full name is returned. \param filename: The file to get the basename from \param keepExtension True if filename with extension is returned otherwise everything after the final '.' is removed as well. */ virtual path getFileBasename(const path& filename, bool keepExtension=true) const =0; //! flatten a path and file name for example: "/you/me/../." becomes "/you" virtual path& flattenFilename(path& directory, const path& root="/") const =0; //! Get the relative filename, relative to the given directory virtual path getRelativeFilename(const path& filename, const path& directory) const =0; //! Creates a list of files and directories in the current working directory and returns it. /** \return a Pointer to the created IFileList is returned. After the list has been used it has to be deleted using its IFileList::drop() method. See IReferenceCounted::drop() for more information. */ virtual IFileList* createFileList() =0; //! Creates an empty filelist /** \return a Pointer to the created IFileList is returned. After the list has been used it has to be deleted using its IFileList::drop() method. See IReferenceCounted::drop() for more information. */ virtual IFileList* createEmptyFileList(const io::path& path, bool ignoreCase, bool ignorePaths) =0; //! Set the active type of file system. virtual EFileSystemType setFileListSystem(EFileSystemType listType) =0; //! Determines if a file exists and could be opened. /** \param filename is the string identifying the file which should be tested for existence. \return True if file exists, and false if it does not exist or an error occurred. */ virtual bool existFile(const path& filename) const =0; //! Creates a XML Reader from a file which returns all parsed strings as wide characters (wchar_t*). /** Use createXMLReaderUTF8() if you prefer char* instead of wchar_t*. See IIrrXMLReader for more information on how to use the parser. \return 0, if file could not be opened, otherwise a pointer to the created IXMLReader is returned. After use, the reader has to be deleted using its IXMLReader::drop() method. See IReferenceCounted::drop() for more information. */ virtual IXMLReader* createXMLReader(const path& filename) =0; //! Creates a XML Reader from a file which returns all parsed strings as wide characters (wchar_t*). /** Use createXMLReaderUTF8() if you prefer char* instead of wchar_t*. See IIrrXMLReader for more information on how to use the parser. \return 0, if file could not be opened, otherwise a pointer to the created IXMLReader is returned. After use, the reader has to be deleted using its IXMLReader::drop() method. See IReferenceCounted::drop() for more information. */ virtual IXMLReader* createXMLReader(IReadFile* file) =0; //! Creates a XML Reader from a file which returns all parsed strings as ASCII/UTF-8 characters (char*). /** Use createXMLReader() if you prefer wchar_t* instead of char*. See IIrrXMLReader for more information on how to use the parser. \return 0, if file could not be opened, otherwise a pointer to the created IXMLReader is returned. After use, the reader has to be deleted using its IXMLReaderUTF8::drop() method. See IReferenceCounted::drop() for more information. */ virtual IXMLReaderUTF8* createXMLReaderUTF8(const path& filename) =0; //! Creates a XML Reader from a file which returns all parsed strings as ASCII/UTF-8 characters (char*). /** Use createXMLReader() if you prefer wchar_t* instead of char*. See IIrrXMLReader for more information on how to use the parser. \return 0, if file could not be opened, otherwise a pointer to the created IXMLReader is returned. After use, the reader has to be deleted using its IXMLReaderUTF8::drop() method. See IReferenceCounted::drop() for more information. */ virtual IXMLReaderUTF8* createXMLReaderUTF8(IReadFile* file) =0; //! Creates a XML Writer from a file. /** \return 0, if file could not be opened, otherwise a pointer to the created IXMLWriter is returned. After use, the reader has to be deleted using its IXMLWriter::drop() method. See IReferenceCounted::drop() for more information. */ virtual IXMLWriter* createXMLWriter(const path& filename) =0; //! Creates a XML Writer from a file. /** \return 0, if file could not be opened, otherwise a pointer to the created IXMLWriter is returned. After use, the reader has to be deleted using its IXMLWriter::drop() method. See IReferenceCounted::drop() for more information. */ virtual IXMLWriter* createXMLWriter(IWriteFile* file) =0; //! Creates a new empty collection of attributes, usable for serialization and more. /** \param driver: Video driver to be used to load textures when specified as attribute values. Can be null to prevent automatic texture loading by attributes. \return Pointer to the created object. If you no longer need the object, you should call IAttributes::drop(). See IReferenceCounted::drop() for more information. */ virtual IAttributes* createEmptyAttributes(video::IVideoDriver* driver=0) =0; }; } // end namespace io } // end namespace irr #endif
[ "marky0720@gmail.com" ]
marky0720@gmail.com