blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
a35dd990f341ce5b726dd7faf711bab43c587fbd
7dbb249f0ee4d17fd39fb3f7e7b6ed9b11bb0ac0
/assignment 6/11th.cpp
a898c635bb5a077fe05c17a596e85e9f1e532c5b
[]
no_license
rjsuraj/C-
639796d7550aeb14db22f19dd852bef817fc1164
6ec17e6f9d464b422cb96a584e367758af6806ac
refs/heads/main
2023-07-21T10:31:26.719077
2021-09-04T07:09:05
2021-09-04T07:09:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
258
cpp
#include<iostream> #include<conio.h> using namespace std; int sumOdd(int); int sumOdd(int n){ if (n==1) return 1; return sumOdd(n-1)+(n*2-1); } int main(){ int n; cin>>n; cout<<sumOdd(n); getch(); return 0; }
[ "noreply@github.com" ]
noreply@github.com
829d80498942cc342f8b035dc5eb3d3c6841579b
a54ac66295479fe1e76ab2c9a04e17d611707598
/loginwindow.cpp
b1ffef0845c3b623e7c2290b94616d1d17380879
[]
no_license
Faridik/Kursbd
4b19284d8220c397e7754b832ae89dbd0829db98
ac00b760eea71c59a592c84bc9499025ebf1a676
refs/heads/master
2020-04-09T00:09:29.753855
2018-12-03T13:21:12
2018-12-03T13:21:12
159,855,362
0
0
null
null
null
null
UTF-8
C++
false
false
350
cpp
#include "loginwindow.h" #include "ui_loginwindow.h" loginWindow::loginWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::loginWindow) { ui->setupUi(this); connect(ui->backButton,SIGNAL(pressed()),this,SLOT(backToMain())); } void loginWindow::backToMain() { emit back(); } loginWindow::~loginWindow() { delete ui; }
[ "noreply@github.com" ]
noreply@github.com
724ab1e1ae853cdd8193a00ebc2777bca337e62b
9cf93b1882fa33f77340347c387da98bb19223e9
/AmethystEngine/cError.cpp
2a4b69be5b9547bfca5810cf02b212b7e00db2b9
[]
no_license
KirkbyD/edu-Gfx2-Starfield
b8ddec2beec9b3a906e865c3fd6435b4234cf3c3
72bd698328dddb6194ec7b004742397981b15b8c
refs/heads/main
2023-04-03T10:45:34.418408
2021-04-15T04:06:58
2021-04-15T04:06:58
358,122,593
0
0
null
null
null
null
UTF-8
C++
false
false
1,013
cpp
#define _CRTDBG_MAP_ALLOC #include <cstdlib> #include <crtdbg.h> #include <memory> #ifdef _DEBUG #define DEBUG_NEW new (_NORMAL_BLOCK , __FILE__ , __LINE__) #else #define DBG_NEW #endif #include "cError.hpp" #include "cErrorImp.hpp" cError::cError() { this->pErrorImp = new cErrorImp(); } cError::~cError() { delete this->pErrorImp; } // method calls point the the implementation methods void cError::WriteError() { this->pErrorImp->WriteErrorLog(); } void cError::LogError(std::string eclass, std::string efunc, std::string etype, std::string err, std::string edata) { this->pErrorImp->LogError(eclass, efunc, etype, err, edata); } void cError::DisplayError(std::string eclass, std::string efunc, std::string etype, std::string emessage) { this->pErrorImp->DisplayError(eclass, efunc, etype, emessage); } void cError::DisplayError(std::string eclass, std::string efunc, std::string etype, std::string emessage, std::string edata) { this->pErrorImp->DisplayError(eclass, efunc, etype, emessage, edata); }
[ "kirkby.dylan@gmail.com" ]
kirkby.dylan@gmail.com
e7668a65072f3132c8031684a9fc2e481efaac2c
88ae8695987ada722184307301e221e1ba3cc2fa
/v8/src/codegen/code-reference.h
c44ec54252e8248fb969375091bd96ee5a08dd7d
[ "BSD-3-Clause", "SunPro", "Apache-2.0" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
1,953
h
// Copyright 2018 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. #ifndef V8_CODEGEN_CODE_REFERENCE_H_ #define V8_CODEGEN_CODE_REFERENCE_H_ #include "src/base/platform/platform.h" #include "src/handles/handles.h" #include "src/objects/code.h" namespace v8 { namespace internal { class InstructionStream; class Code; class CodeDesc; namespace wasm { class WasmCode; } // namespace wasm class CodeReference { public: CodeReference() : kind_(Kind::NONE), null_(nullptr) {} explicit CodeReference(const wasm::WasmCode* wasm_code) : kind_(Kind::WASM_CODE), wasm_code_(wasm_code) {} explicit CodeReference(const CodeDesc* code_desc) : kind_(Kind::CODE_DESC), code_desc_(code_desc) {} explicit CodeReference(Handle<Code> code) : kind_(Kind::CODE), code_(code) {} Address constant_pool() const; Address instruction_start() const; Address instruction_end() const; int instruction_size() const; const uint8_t* relocation_start() const; const uint8_t* relocation_end() const; int relocation_size() const; Address code_comments() const; int code_comments_size() const; bool is_null() const { return kind_ == Kind::NONE; } bool is_code() const { return kind_ == Kind::CODE; } bool is_wasm_code() const { return kind_ == Kind::WASM_CODE; } Handle<Code> as_code() const { DCHECK_EQ(Kind::CODE, kind_); return code_; } const wasm::WasmCode* as_wasm_code() const { DCHECK_EQ(Kind::WASM_CODE, kind_); return wasm_code_; } private: enum class Kind { NONE, CODE, WASM_CODE, CODE_DESC } kind_; union { std::nullptr_t null_; const wasm::WasmCode* wasm_code_; const CodeDesc* code_desc_; Handle<Code> code_; }; DISALLOW_NEW_AND_DELETE() }; ASSERT_TRIVIALLY_COPYABLE(CodeReference); } // namespace internal } // namespace v8 #endif // V8_CODEGEN_CODE_REFERENCE_H_
[ "jengelh@inai.de" ]
jengelh@inai.de
cdb388559b96b5862d6d5512ac48277762c89c3a
a7099d3c3fb6eb8e4b9ef927c857609d4fd49518
/HORRIBLE.cpp
3a569c93ef4b3ccd6e396d4350a67345260b8cf5
[]
no_license
singhsd/SPOJ-Codes
30ae79ffd7f46f3d9dd0d0a67b190e3256f0e390
e646acd5099ef62d94a5263c6f3898f559049aa9
refs/heads/master
2020-03-29T11:49:33.365567
2018-09-22T12:04:47
2018-09-22T12:04:47
149,872,654
0
0
null
null
null
null
UTF-8
C++
false
false
1,485
cpp
#include<bits/stdc++.h> using namespace std; int a[100002]; long long int tree[400004],lazy[400004]; void propogate(int ss, int se, int i) { tree[i]+=(long long int)(se-ss+1)*lazy[i]; if(ss!=se) { lazy[2*i+1]+=lazy[i]; lazy[2*i+2]+=lazy[i]; } lazy[i]=0; } void update(int ss, int se, int l, int r, int i, int k) { if(lazy[i]) propogate(ss,se,i); if(l>se||r<ss) return; if(l<=ss&&r>=se) { lazy[i]+=(long)k; propogate(ss,se,i); return; } int mid=(ss+se)/2; update(ss,mid,l,r,2*i+1,k); update(mid+1,se,l,r,2*i+2,k); tree[i]=tree[2*i+1]+tree[2*i+2]; return; } long long int get(int ss, int se, int l, int r, int i) { if(lazy[i]) propogate(ss,se,i); if(l>se || r<ss) return 0; if(l<=ss&&r>=se) return tree[i]; int m=ss+(se-ss)/2; return get(ss,m,l,r,2*i+1)+get(m+1,se,l,r,2*i+2); } int main() { int t; cin>>t; while(t--) { int n,c; cin>>n>>c; for(int i=0; i<4*n; i++) lazy[i]=0,tree[i]=0; int a[n],x,w,y,z; memset(a,0,n); for(int i=0; i<c; i++) { cin>>x; if(x==0) { cin>>w>>y>>z; if(z) update(0,n-1,w-1,y-1,0,z); } else { cin>>y>>z; cout<<get(0,n-1,y-1,z-1,0)<<endl; } } } return 0; }
[ "sahil.khalsaboy@gmail.com" ]
sahil.khalsaboy@gmail.com
dd0c927f8144172d56b4d0642b4b504c6237fe06
d17a8870ff8ac77b82d0d37e20c85b23aa29ca74
/lite/core/optimizer/mir/fusion/matmul_elementwise_add_fuser.cc
ee8f8ceec46c22bb23414b4df378735c8810a71b
[ "Apache-2.0" ]
permissive
PaddlePaddle/Paddle-Lite
4ab49144073451d38da6f085a8c56822caecd5b2
e241420f813bd91f5164f0d9ee0bc44166c0a172
refs/heads/develop
2023-09-02T05:28:14.017104
2023-09-01T10:32:39
2023-09-01T10:32:39
104,208,128
2,545
1,041
Apache-2.0
2023-09-12T06:46:10
2017-09-20T11:41:42
C++
UTF-8
C++
false
false
6,070
cc
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "lite/core/optimizer/mir/fusion/matmul_elementwise_add_fuser.h" #include <cmath> #include <memory> #include <vector> namespace paddle { namespace lite { namespace mir { namespace fusion { void MatmulElementwiseAddFuser::CreatePattern() { // create nodes. auto* x = VarNode("x")->assert_is_op_input("matmul", "X"); auto* W = VarNode("W")->assert_is_persistable_var()->assert_is_op_input( "matmul", "Y"); auto* b = VarNode("b")->assert_is_persistable_var(); auto* matmul = OpNode("matmul", "matmul") ->assert_op_attr_satisfied<float>("alpha", [](float attr) { return (std::fabs(attr - 1.0) < 1e-5); }); auto* matmul_out = VarNode("matmul_out"); auto* add = OpNode("add", "elementwise_add"); auto* Out = VarNode("Out"); // create topology. std::vector<PMNode*> matmul_inputs{W, x}; std::vector<PMNode*> add_inputs{matmul_out, b}; matmul_inputs >> *matmul >> *matmul_out; // Some op specialities. matmul_out->AsIntermediate(); matmul->AsIntermediate(); add->AsIntermediate(); if (with_relu_) { auto* add_out = VarNode("add_out"); auto* relu = OpNode("relu", "relu"); std::vector<PMNode*> relu_inputs{add_out}; add_inputs >> *add >> *add_out; relu_inputs >> *relu >> *Out; add_out->AsIntermediate(); relu->AsIntermediate(); } else { add_inputs >> *add >> *Out; } } void MatmulElementwiseAddFuser::BuildPattern() { for (auto& node : graph_->StmtTopologicalOrder()) { if (node->IsStmt() && node->AsStmt().op_type() == "matmul") { auto* scope = node->stmt()->op()->scope(); auto op_desc = node->stmt()->mutable_op_info(); bool transpose_x = op_desc->GetAttr<bool>("transpose_X"); bool transpose_y = op_desc->GetAttr<bool>("transpose_Y"); auto arg_y_name = op_desc->Input("Y").front(); auto& tensor_y = scope->FindVar(arg_y_name)->Get<lite::Tensor>(); bool is_persist = tensor_y.persistable(); if ((!transpose_x && !transpose_y) || (!transpose_x && transpose_y && is_persist)) { CreatePattern(); return; } } } } void MatmulElementwiseAddFuser::InsertNewNode(SSAGraph* graph, const key2nodes_t& matched) { auto op_desc = GenOpDesc(matched); auto fc_op = LiteOpRegistry::Global().Create("fc"); auto mul = matched.at("matmul")->stmt()->op(); auto* scope = mul->scope(); auto& valid_places = mul->valid_places(); fc_op->Attach(op_desc, scope); auto* new_op_node = graph->GraphCreateInstructNode(fc_op, valid_places); IR_NODE_LINK_TO(matched.at("W"), new_op_node); IR_NODE_LINK_TO(matched.at("x"), new_op_node); IR_NODE_LINK_TO(matched.at("b"), new_op_node); IR_NODE_LINK_TO(new_op_node, matched.at("Out")); } template <typename T> void transpose(T* dst, const T* src, const int src_rows, const int src_cols) { CHECK(src && dst && src_rows > 0 && src_cols > 0); for (int r = 0; r < src_rows; ++r) { for (int c = 0; c < src_cols; ++c) { dst[c * src_rows + r] = src[r * src_cols + c]; } } } cpp::OpDesc MatmulElementwiseAddFuser::GenOpDesc(const key2nodes_t& matched) { auto op_desc = *matched.at("matmul")->stmt()->op_info(); // Get the input scale from mul std::vector<float> x_scale_vct; std::vector<float> y_scale_vct; auto input_x_name = op_desc.Input("X").front(); auto input_y_name = op_desc.Input("Y").front(); bool is_quantized_op = op_desc.HasInputScale(input_x_name) && op_desc.HasInputScale(input_y_name); if (is_quantized_op) { x_scale_vct = op_desc.GetInputScale(input_x_name); y_scale_vct = op_desc.GetInputScale(input_y_name); } auto* scope = matched.at("matmul")->stmt()->op()->scope(); auto x_shape = scope->FindVar(input_x_name)->Get<lite::Tensor>().dims(); int x_num_col_dims = x_shape.size() - 1; VLOG(4) << "x_shape: " << x_shape; VLOG(4) << "y_shape: " << scope->FindVar(input_y_name)->Get<lite::Tensor>().dims(); VLOG(4) << "x_num_col_dims: " << x_num_col_dims; bool transpose_y = op_desc.GetAttr<bool>("transpose_Y"); if (transpose_y) { auto* y_t = scope->FindVar(input_y_name)->GetMutable<lite::Tensor>(); auto y_dims = y_t->dims(); Tensor y_t_tmp; y_t_tmp.CopyDataFrom(*y_t); // in order to copy y_t's // target_,lod_,precision_, etc,. to y_t_tmp y_t_tmp.Resize({y_dims[1], y_dims[0]}); const float* src = y_t->data<float>(); float* dst = y_t_tmp.mutable_data<float>(); transpose<float>(dst, src, y_dims[0], y_dims[1]); y_t->CopyDataFrom(y_t_tmp); } op_desc.mutable_inputs()->clear(); op_desc.mutable_outputs()->clear(); op_desc.SetType("fc"); op_desc.SetInput("Input", {matched.at("x")->arg()->name}); op_desc.SetInput("W", {matched.at("W")->arg()->name}); op_desc.SetInput("Bias", {matched.at("b")->arg()->name}); op_desc.SetOutput("Out", {matched.at("Out")->arg()->name}); op_desc.SetAttr("in_num_col_dims", x_num_col_dims); if (with_relu_) { op_desc.SetAttr("activation_type", std::string{"relu"}); } // Set the input scale into fc if (is_quantized_op) { op_desc.SetInputScale(matched.at("x")->arg()->name, x_scale_vct); op_desc.SetInputScale(matched.at("W")->arg()->name, y_scale_vct); } return op_desc; } } // namespace fusion } // namespace mir } // namespace lite } // namespace paddle
[ "noreply@github.com" ]
noreply@github.com
c6c457862ea039de118ca54fc7409cc2ac332bfd
32f541dd6dcb2121f21b13071678a799eb293f10
/libraries/uvm/src/uvm/llex.cpp
cc53fd80a40d90136d3c85d16ac642a2ffb069d7
[ "MIT" ]
permissive
Whitecoin-XWC/Whitecoin-core
b62de0b712ab8557ecd16dc1d0e4389c439eb3db
8f15e0764fe60ff8d77228a2aca6bdff723439bd
refs/heads/develop
2022-12-10T18:12:23.027195
2022-11-23T03:53:04
2022-11-23T03:53:04
397,646,406
0
3
MIT
2022-11-28T01:20:26
2021-08-18T15:17:39
C++
UTF-8
C++
false
false
18,490
cpp
/* ** $Id: llex.c,v 2.95 2015/11/19 19:16:22 roberto Exp $ ** Lexical Analyzer ** See Copyright Notice in lua.h */ #define llex_cpp #define LUA_CORE #include "uvm/lprefix.h" #include <locale.h> #include <string.h> #include "uvm/lua.h" #include "uvm/lctype.h" #include "uvm/ldebug.h" #include "uvm/ldo.h" #include "uvm/lgc.h" #include "uvm/llex.h" #include "uvm/lobject.h" #include "uvm/lparser.h" #include "uvm/lstate.h" #include "uvm/lstring.h" #include "uvm/ltable.h" #include "uvm/lzio.h" #define next(ls) (ls->current = zgetc(ls->z)) #define currIsNewline(ls) (ls->current == '\n' || ls->current == '\r') /* ORDER RESERVED */ static const char *const luaX_tokens[] = { "and", "break", "do", "else", "elseif", "end", "false", "for", "function", "goto", "if", "in", "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while", "//", "..", "...", "==", ">=", "<=", "~=", "<<", ">>", "::", "<eof>", "<number>", "<integer>", "<name>", "<string>" }; #define save_and_next(ls) (save(ls, ls->current), next(ls)) static void lexerror(LexState *ls, const char *msg, int token); static void save(LexState *ls, int c) { Mbuffer *b = ls->buff; if (luaZ_bufflen(b) + 1 > luaZ_sizebuffer(b)) { size_t newsize; if (luaZ_sizebuffer(b) >= UVM_MAX_SIZE / 2) lexerror(ls, "lexical element too long", 0); newsize = luaZ_sizebuffer(b) * 2; luaZ_resizebuffer(ls->L, b, newsize); } b->buffer[luaZ_bufflen(b)++] = lua_cast(char, c); } void luaX_init(lua_State *L) { //delete; modify isreseved move to llex.h ? int i; uvm_types::GcString *e = luaS_newliteral(L, LUA_ENV); /* create env name */ /*for (i = 0; i < NUM_RESERVED; i++) { uvm_types::GcString *ts = luaS_new(L, luaX_tokens[i]); ts->extra = cast_byte(i + 1); // reserved word }*/ } const char *luaX_token2str(LexState *ls, int token) { if (token < FIRST_RESERVED) { /* single-byte symbols? */ lua_assert(token == cast_uchar(token)); return luaO_pushfstring(ls->L, "'%c'", token); } else { const char *s = luaX_tokens[token - FIRST_RESERVED]; if (token < TK_EOS) /* fixed format (symbols and reserved words)? */ return luaO_pushfstring(ls->L, "'%s'", s); else /* names, strings, and numerals */ return s; } } static const char *txtToken(LexState *ls, int token) { switch (token) { case TK_NAME: case TK_STRING: case TK_FLT: case TK_INT: save(ls, '\0'); return luaO_pushfstring(ls->L, "'%s'", luaZ_buffer(ls->buff)); default: return luaX_token2str(ls, token); } } static void lexerror(LexState *ls, const char *msg, int token) { msg = luaG_addinfo(ls->L, msg, ls->source, ls->linenumber); lua_set_compile_error(ls->L, msg); if (token) luaO_pushfstring(ls->L, "%s near %s", msg, txtToken(ls, token)); luaD_throw(ls->L, LUA_ERRSYNTAX); } void luaX_syntaxerror(LexState *ls, const char *msg) { lexerror(ls, msg, ls->t.token); } /* ** creates a new string and anchors it in scanner's table so that ** it will not be collected until the end of the compilation ** (by that time it should be anchored somewhere) */ uvm_types::GcString *luaX_newstring(LexState *ls, const char *str, size_t l) { lua_State *L = ls->L; TValue *o; /* entry for 'str' */ uvm_types::GcString *ts = luaS_newlstr(L, str, l); /* create new string */ // if its reservedword then set extra for (int i = 0; i < NUM_RESERVED; i++) { auto reservedword = luaX_tokens[i]; auto len = strlen(reservedword); if (l == len && (memcmp(str, reservedword, l*sizeof(char)) == 0)) { /* reserved word? */ ts->extra = cast_byte(i + 1); // set extra } } setsvalue2s(L, L->top++, ts); /* temporarily anchor it in stack */ o = luaH_set(L, ls->h, L->top - 1); if (ttisnil(o)) { /* not in use yet? */ /* boolean value does not need GC barrier; table has no metatable, so it does not need to invalidate cache */ setbvalue(o, 1); /* t[string] = true */ luaC_checkGC(L); } //else { /* string already present */ // ts = tsvalue(keyfromval(o)); /* re-use value previously stored */ //} L->top--; /* remove string from stack */ return ts; } /* ** increment line number and skips newline sequence (any of ** \n, \r, \n\r, or \r\n) */ static void inclinenumber(LexState *ls) { int old = ls->current; lua_assert(currIsNewline(ls)); next(ls); /* skip '\n' or '\r' */ if (currIsNewline(ls) && ls->current != old) next(ls); /* skip '\n\r' or '\r\n' */ if (++ls->linenumber >= MAX_INT) lexerror(ls, "chunk has too many lines", 0); } void luaX_setinput(lua_State *L, LexState *ls, ZIO *z, uvm_types::GcString *source, int firstchar) { ls->t.token = 0; ls->decpoint = '.'; ls->L = L; ls->current = firstchar; ls->lookahead.token = TK_EOS; /* no look-ahead token */ ls->z = z; ls->fs = nullptr; ls->linenumber = 1; ls->lastline = 1; ls->source = source; ls->envn = luaS_newliteral(L, LUA_ENV); /* get env name */ luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER); /* initialize buffer */ } /* ** ======================================================= ** LEXICAL ANALYZER ** ======================================================= */ static int check_next1(LexState *ls, int c) { if (ls->current == c) { next(ls); return 1; } else return 0; } /* ** Check whether current char is in set 'set' (with two chars) and ** saves it */ static int check_next2(LexState *ls, const char *set) { lua_assert(set[2] == '\0'); if (ls->current == set[0] || ls->current == set[1]) { save_and_next(ls); return 1; } else return 0; } /* ** change all characters 'from' in buffer to 'to' */ static void buffreplace(LexState *ls, char from, char to) { if (from != to) { size_t n = luaZ_bufflen(ls->buff); char *p = luaZ_buffer(ls->buff); while (n--) if (p[n] == from) p[n] = to; } } /* ** in case of format error, try to change decimal point separator to ** the one defined in the current locale and check again */ static void trydecpoint(LexState *ls, TValue *o) { char old = ls->decpoint; ls->decpoint = lua_getlocaledecpoint(); buffreplace(ls, old, ls->decpoint); /* try new decimal separator */ if (luaO_str2num(luaZ_buffer(ls->buff), o) == 0) { /* format error with correct decimal point: no more options */ buffreplace(ls, ls->decpoint, '.'); /* undo change (for error message) */ lexerror(ls, "malformed number", TK_FLT); } } /* LUA_NUMBER */ /* ** this function is quite liberal in what it accepts, as 'luaO_str2num' ** will reject ill-formed numerals. */ static int read_numeral(LexState *ls, SemInfo *seminfo) { TValue obj; const char *expo = "Ee"; int first = ls->current; lua_assert(lisdigit(ls->current)); save_and_next(ls); if (first == '0' && check_next2(ls, "xX")) /* hexadecimal? */ expo = "Pp"; for (;;) { if (check_next2(ls, expo)) /* exponent part? */ check_next2(ls, "-+"); /* optional exponent sign */ if (lisxdigit(ls->current)) save_and_next(ls); else if (ls->current == '.') save_and_next(ls); else break; } save(ls, '\0'); buffreplace(ls, '.', ls->decpoint); /* follow locale for decimal point */ if (luaO_str2num(luaZ_buffer(ls->buff), &obj) == 0) /* format error? */ trydecpoint(ls, &obj); /* try to update decimal point separator */ if (ttisinteger(&obj)) { seminfo->i = ivalue(&obj); return TK_INT; } else { lua_assert(ttisfloat(&obj)); seminfo->r = fltvalue(&obj); return TK_FLT; } } /* ** skip a sequence '[=*[' or ']=*]'; if sequence is well formed, return ** its number of '='s; otherwise, return a negative number (-1 iff there ** are no '='s after initial bracket) */ static int skip_sep(LexState *ls) { int count = 0; int s = ls->current; lua_assert(s == '[' || s == ']'); save_and_next(ls); while (ls->current == '=') { save_and_next(ls); count++; } return (ls->current == s) ? count : (-count) - 1; } static void read_long_string(LexState *ls, SemInfo *seminfo, int sep) { int line = ls->linenumber; /* initial line (for error message) */ save_and_next(ls); /* skip 2nd '[' */ if (currIsNewline(ls)) /* string starts with a newline? */ inclinenumber(ls); /* skip it */ for (;;) { switch (ls->current) { case EOZ: { /* error */ const char *what = (seminfo ? "string" : "comment"); const char *msg = luaO_pushfstring(ls->L, "unfinished long %s (starting at line %d)", what, line); lexerror(ls, msg, TK_EOS); break; /* to avoid warnings */ } case ']': { if (skip_sep(ls) == sep) { save_and_next(ls); /* skip 2nd ']' */ goto endloop; } break; } case '\n': case '\r': { save(ls, '\n'); inclinenumber(ls); if (!seminfo) luaZ_resetbuffer(ls->buff); /* avoid wasting space */ break; } default: { if (seminfo) save_and_next(ls); else next(ls); } } } endloop: if (seminfo) seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + (2 + sep), luaZ_bufflen(ls->buff) - 2 * (2 + sep)); } static void esccheck(LexState *ls, int c, const char *msg) { if (!c) { if (ls->current != EOZ) save_and_next(ls); /* add current to buffer for error message */ lexerror(ls, msg, TK_STRING); } } static int gethexa(LexState *ls) { save_and_next(ls); esccheck(ls, lisxdigit(ls->current), "hexadecimal digit expected"); return luaO_hexavalue(ls->current); } static int readhexaesc(LexState *ls) { int r = gethexa(ls); r = (r << 4) + gethexa(ls); luaZ_buffremove(ls->buff, 2); /* remove saved chars from buffer */ return r; } static unsigned long readutf8esc(LexState *ls) { unsigned long r; int i = 4; /* chars to be removed: '\', 'u', '{', and first digit */ save_and_next(ls); /* skip 'u' */ esccheck(ls, ls->current == '{', "missing '{'"); r = gethexa(ls); /* must have at least one digit */ while ((save_and_next(ls), lisxdigit(ls->current))) { i++; r = (r << 4) + luaO_hexavalue(ls->current); esccheck(ls, r <= 0x10FFFF, "UTF-8 value too large"); } esccheck(ls, ls->current == '}', "missing '}'"); next(ls); /* skip '}' */ luaZ_buffremove(ls->buff, i); /* remove saved chars from buffer */ return r; } static void utf8esc(LexState *ls) { char buff[UTF8BUFFSZ]; int n = luaO_utf8esc(buff, readutf8esc(ls)); for (; n > 0; n--) /* add 'buff' to string */ save(ls, buff[UTF8BUFFSZ - n]); } static int readdecesc(LexState *ls) { int i; int r = 0; /* result accumulator */ for (i = 0; i < 3 && lisdigit(ls->current); i++) { /* read up to 3 digits */ r = 10 * r + ls->current - '0'; save_and_next(ls); } esccheck(ls, r <= UCHAR_MAX, "decimal escape too large"); luaZ_buffremove(ls->buff, i); /* remove read digits from buffer */ return r; } static void read_string(LexState *ls, int del, SemInfo *seminfo) { save_and_next(ls); /* keep delimiter (for error messages) */ while (ls->current != del) { switch (ls->current) { case EOZ: lexerror(ls, "unfinished string", TK_EOS); break; /* to avoid warnings */ case '\n': case '\r': lexerror(ls, "unfinished string", TK_STRING); break; /* to avoid warnings */ case '\\': { /* escape sequences */ int c; /* final character to be saved */ save_and_next(ls); /* keep '\\' for error messages */ switch (ls->current) { case 'a': c = '\a'; goto read_save; case 'b': c = '\b'; goto read_save; case 'f': c = '\f'; goto read_save; case 'n': c = '\n'; goto read_save; case 'r': c = '\r'; goto read_save; case 't': c = '\t'; goto read_save; case 'v': c = '\v'; goto read_save; case 'x': c = readhexaesc(ls); goto read_save; case 'u': utf8esc(ls); goto no_save; case '\n': case '\r': inclinenumber(ls); c = '\n'; goto only_save; case '\\': case '\"': case '\'': c = ls->current; goto read_save; case EOZ: goto no_save; /* will raise an error next loop */ case 'z': { /* zap following span of spaces */ luaZ_buffremove(ls->buff, 1); /* remove '\\' */ next(ls); /* skip the 'z' */ while (lisspace(ls->current)) { if (currIsNewline(ls)) inclinenumber(ls); else next(ls); } goto no_save; } default: { esccheck(ls, lisdigit(ls->current), "invalid escape sequence"); c = readdecesc(ls); /* digital escape '\ddd' */ goto only_save; } } read_save: next(ls); /* go through */ only_save: luaZ_buffremove(ls->buff, 1); /* remove '\\' */ save(ls, c); /* go through */ no_save: break; } default: save_and_next(ls); } } save_and_next(ls); /* skip delimiter */ seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + 1, luaZ_bufflen(ls->buff) - 2); } static int llex(LexState *ls, SemInfo *seminfo) { luaZ_resetbuffer(ls->buff); for (;;) { switch (ls->current) { case '\n': case '\r': { /* line breaks */ inclinenumber(ls); break; } case ' ': case '\f': case '\t': case '\v': { /* spaces */ next(ls); break; } case '-': { /* '-' or '--' (comment) */ next(ls); if (ls->current != '-') return '-'; /* else is a comment */ next(ls); if (ls->current == '[') { /* long comment? */ int sep = skip_sep(ls); luaZ_resetbuffer(ls->buff); /* 'skip_sep' may dirty the buffer */ if (sep >= 0) { read_long_string(ls, nullptr, sep); /* skip long comment */ luaZ_resetbuffer(ls->buff); /* previous call may dirty the buff. */ break; } } /* else short comment */ while (!currIsNewline(ls) && ls->current != EOZ) next(ls); /* skip until end of line (or end of file) */ break; } case '[': { /* long string or simply '[' */ int sep = skip_sep(ls); if (sep >= 0) { read_long_string(ls, seminfo, sep); return TK_STRING; } else if (sep != -1) /* '[=...' missing second bracket */ lexerror(ls, "invalid long string delimiter", TK_STRING); return '['; } case '=': { next(ls); if (check_next1(ls, '=')) return TK_EQ; else return '='; } case '<': { next(ls); if (check_next1(ls, '=')) return TK_LE; else if (check_next1(ls, '<')) return TK_SHL; else return '<'; } case '>': { next(ls); if (check_next1(ls, '=')) return TK_GE; else if (check_next1(ls, '>')) return TK_SHR; else return '>'; } case '/': { next(ls); if (check_next1(ls, '/')) return TK_IDIV; else return '/'; } case '~': { next(ls); if (check_next1(ls, '=')) return TK_NE; else return '~'; } case ':': { next(ls); if (check_next1(ls, ':')) return TK_DBCOLON; else return ':'; } case '"': case '\'': { /* short literal strings */ read_string(ls, ls->current, seminfo); return TK_STRING; } case '.': { /* '.', '..', '...', or number */ save_and_next(ls); if (check_next1(ls, '.')) { if (check_next1(ls, '.')) return TK_DOTS; /* '...' */ else return TK_CONCAT; /* '..' */ } else if (!lisdigit(ls->current)) return '.'; else return read_numeral(ls, seminfo); } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { return read_numeral(ls, seminfo); } case EOZ: { return TK_EOS; } default: { if (lislalpha(ls->current)) { /* identifier or reserved word? */ uvm_types::GcString *ts; do { save_and_next(ls); } while (lislalnum(ls->current)); ts = luaX_newstring(ls, luaZ_buffer(ls->buff), luaZ_bufflen(ls->buff)); seminfo->ts = ts; if (isreserved(ts)) { return ts->extra - 1 + FIRST_RESERVED; } return TK_NAME; } else { /* single-char tokens (+ - / ...) */ int c = ls->current; next(ls); return c; } } } } } void luaX_next(LexState *ls) { ls->lastline = ls->linenumber; if (ls->lookahead.token != TK_EOS) { /* is there a look-ahead token? */ ls->t = ls->lookahead; /* use this one */ ls->lookahead.token = TK_EOS; /* and discharge it */ } else ls->t.token = llex(ls, &ls->t.seminfo); /* read next token */ } int luaX_lookahead(LexState *ls) { lua_assert(ls->lookahead.token == TK_EOS); ls->lookahead.token = llex(ls, &ls->lookahead.seminfo); return ls->lookahead.token; }
[ "WhitecoinFounder@gmail.com" ]
WhitecoinFounder@gmail.com
e4209878979f3ec0b7c26eba56c8ca164ef6b6bf
ea8aeed853a94d2a20b9bd2d90ac50658eb47b5a
/Alphi_includes/IrigDecoder.h
e4aa1201b0925df893ed8769bc4bbe8f2db072b8
[]
no_license
loulansuiye/Mini_PCIe
9606bd1ee147287222a2f9ae784b0a4c07a57649
7b0282eaf4cefc70cf2e16c48116f2b145ec0af2
refs/heads/main
2023-04-08T22:56:13.039147
2021-03-24T20:43:26
2021-03-24T20:43:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,380
h
#pragma once // // Copyright (c) 2020 Alphi Technology Corporation, Inc. All Rights Reserved // // You are hereby granted a copyright license to use, modify and // distribute this SOFTWARE so long as the entire notice is retained // without alteration in any modified and/or redistributed versions, // and that such modified versions are clearly identified as such. // No licenses are granted by implication, estopple or otherwise under // any patents or trademarks of Alphi Technology Corporation (Alphi). // // The SOFTWARE is provided on an "AS IS" basis and without warranty, // to the maximum extent permitted by applicable law. // // ALPHI DISCLAIMS ALL WARRANTIES WHETHER EXPRESS OR IMPLIED, INCLUDING // WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE // AND ANY WARRANTY AGAINST INFRINGEMENT WITH REGARD TO THE SOFTWARE // (INCLUDING ANY MODIFIED VERSIONS THEREOF) AND ANY ACCOMPANYING // WRITTEN MATERIAL. // // To the maximum extent permitted by applicable law, IN NO EVENT SHALL // ALPHI BE LIABLE FOR ANY DAMAGE WHATSOEVER (INCLUDING WITHOUT LIMITATION, // DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF // BUSINESS INFORMATION, OR OTHER PECUNIARY LOSS) ARISING FROM THE USE // OR INABILITY TO USE THE SOFTWARE. GMS assumes no responsibility for // for the maintenance or support of the SOFTWARE // /** @file IrigDecoder.h * @brief Irig Decoder class to get time */ // Maintenance Log //--------------------------------------------------------------------- // v1.0 9/23/2020 phf Written //--------------------------------------------------------------------- #include "AlphiDll.h" #include <stdint.h> #include <ctime> class DLL IrigDecoder { public: struct IrigDate { int tm_sec; int tm_min; int tm_hour; int tm_yday; int tm_year; }; static const int time_offset = 2; static const int day_offset = 3; static const int second_offset = 4; inline IrigDecoder(volatile void* addr) { base = (volatile uint32_t*)addr; } inline uint32_t getTimeRaw() { return base[time_offset]; } // irig_b_time_d <= {2'b0 ,h_10 ,h_1 ,1'b0 ,m_10 ,m_1 ,1'b0, s_10, s_1, 4'b0, s_p1}; // hh:mm:ss:0t inline void getTime(IrigDate* ttm) { uint32_t t = getTimeRaw(); // uint8_t s_p1 = t & 0xf; t = t >> 8; ttm->tm_sec = (t & 0xf) + ((t >> 4) & 0x07) * 10; t = t >> 8; ttm->tm_min = (t & 0xf) + ((t >> 4) & 0x07) * 10; t = t >> 8; ttm->tm_hour = (t & 0xf) + ((t >> 4) & 0x03) * 10; } inline uint32_t getDayRaw() { return base[day_offset]; } // irig_b_day_d <= {8'b0 ,y_10 ,y_1 ,2'b0, d_100, d_10, d_1}; // 00:yy:0ddd inline void getDay(IrigDate* ttm) { uint32_t t = getDayRaw(); ttm->tm_yday = t & 0xf; t = t >> 4; ttm->tm_yday += t & 0xf * 10; t = t >> 4; ttm->tm_yday += t & 0x3 * 10; t = t >> 4; ttm->tm_year = t & 0xf; t = t >> 4; ttm->tm_year = t & 0xf * 10; } inline uint32_t getSecond() { return base[second_offset]; } /* assign avl_readdata = { 32{avl_addr == 3'b010}} & irig_b_time // | {32{avl_addr == 3'b011}} & irig_b_day // | {32{avl_addr == 3'b100}} & irig_b_sec reg [3:0] s_1 ; reg [2:0] s_10 ; reg [3:0] m_1 ; reg [2:0] m_10 ; reg [3:0] h_1 ; reg [1:0] h_10 ; reg [3:0] d_1 ; reg [3:0] d_10 ; reg [1:0] d_100; reg [3:0] s_p1 ; reg [3:0] y_1 ; reg [3:0] y_10 ; reg [17:0] unus ; reg [15:0] sec ; // irig_b_time_d <= {2'b0 ,h_10 ,h_1 ,1'b0 ,m_10 ,m_1 ,1'b0, s_10, s_1, 4'b0, s_p1}; // hh:mm:ss:0t // irig_b_sec_d <= {16'b0, sec}; // 0000:ssss tm_sec int seconds after the minute 0-60* tm_min int minutes after the hour 0-59 tm_hour int hours since midnight 0-23 tm_mday int day of the month 1-31 tm_mon int months since January 0-11 tm_year int years since 1900 tm_wday int days since Sunday 0-6 tm_yday int days since January 1 0-365 tm_isdst int Daylight Saving Time flag */ inline void getIrigDate(struct tm* t) { IrigDate d = { 0 }; getTime(&d); getDay(&d); char s[100] = "2014-224-17:20:00"; sprintf(s, "20%02d-%d-%d:%d:%d", d.tm_year, d.tm_yday, d.tm_hour, d.tm_min, d.tm_sec); strftime(s, strlen(s), "%Y-%j-%H:%M:%S", t); } private: volatile uint32_t* base; };
[ "noreply@github.com" ]
noreply@github.com
77d214e4071dafa36ed38c66b6d9dc04bd0f3894
55a050b3392ed899fa62d968b559f15803bc5490
/src/dice/concreteFairDice.h
98c25e2dc0f65066cb14924acab9569d075bd87e
[]
no_license
colinywu/Settlers-of-Catan
d39900d0ac32c0b610824b15186edf9f5c25ce23
69bc37e4ce63ccf55c1d2953c3be37e24cb42c05
refs/heads/main
2023-04-29T20:06:12.627668
2021-05-15T00:30:39
2021-05-15T00:30:39
367,507,233
0
0
null
null
null
null
UTF-8
C++
false
false
273
h
#ifndef CONCRETEFAIRDICE_H #define CONCRETEFAIRDICE_H #include "dice.h" #include <vector> #include <random> #include <algorithm> class ConcreteFairDice: public Dice { public: virtual int rollDice() const override; ConcreteFairDice(unsigned int seed); }; #endif
[ "colin.y.wu@gmail.com" ]
colin.y.wu@gmail.com
a42d340b3d5901c1eb36b4e4edd69c3b4942a455
a4a03d391f0c911e5b0aed27fe21e4eb36624609
/HDU/1042/11984969_TLE_0ms_0kB.cpp
d737974a68a49f152bff8bcb25815066063900a1
[]
no_license
jiaaaaaaaqi/ACM_Code
5e689bed9261ba768cfbfa01b39bd8fb0992e560
66b222d15544f6477cd04190c0d7397f232ed15e
refs/heads/master
2020-05-21T21:38:57.727420
2019-12-11T14:30:52
2019-12-11T14:30:52
186,153,816
0
0
null
null
null
null
UTF-8
C++
false
false
1,985
cpp
#include<stdio.h> #include<string.h> #include<ctype.h> char mul[10000][10000]={0}; char num[1005][10000]={0}; void numswap(char a[],int n) { char temp; for(int i=0; i<=n/2-1; i++) { temp=a[i]; a[i]=a[n-1-i]; a[n-1-i]=temp; } } int main() { int m,i,j; int N; while(scanf("%d",&N)!=EOF) { num[0][0]='1'; if(N>1) { for(m=1; m<N; m++) { int n=m+1; //用来乘 char num1[1000]={0}; char num2[1000]={0}; strcpy(num2, num[m-1]); for(i=0; ; i++) { num1[i]=n%10+48; n=n/10; if(n==0) break; } int len1=strlen(num1); int len2=strlen(num2); numswap(num1, len1); numswap(num1, len1); numswap(num2, len2); int i_mul,j_mul,x_mul,up_mul; for(i_mul=0; i_mul<len2; i_mul++)//乘 { int l=len1; up_mul=0; for(j_mul=0; j_mul<len1; j_mul++) { x_mul=(num1[j_mul]-48)*(num2[i_mul]-48)+up_mul; mul[i_mul][j_mul]=x_mul%10; up_mul=x_mul/10; } if(up_mul) { mul[i_mul][l]=up_mul; l++; } numswap(mul[i_mul], l); for(i=0; i<l; i++) mul[i_mul][i]+=48; for(int z=0; z<i_mul; z++) mul[i_mul][l+z]='0'; } int i_add,j_add,x_add,up_add;//加 for(i=0; i<len2; i++) { int len3=strlen(mul[i]); int len4=strlen(num[m]); int lenmax=len3>=len4 ? len3:len4; int lenmin=len3<=len4 ? len3:len4; numswap(mul[i], len3); numswap(num[m], len4); up_add=0; for(i_add=0; i_add<lenmax; i_add++) { if(i_add<lenmin) x_add=mul[i][i_add]+num[m][i_add]+up_add-96; else { if(len3>len4) x_add=mul[i][i_add]-48+up_add; if(len3<len4) x_add=num[m][i_add]-48+up_add; } num[m][i_add]=x_add%10; up_add=x_add/10; } if(up_add) { num[m][lenmax]=1; lenmax++; } for(j=0; j<lenmax; j++) num[m][j]+=48; numswap(num[m], lenmax); } memset(mul, 0, sizeof(mul)); memset(num1, 0, sizeof(num1)); memset(num2, 0, sizeof(num2)); } } printf("%s\n",num[N-1]); memset(num, 0, sizeof(num)); } return 0; }
[ "735301510@qq.com" ]
735301510@qq.com
a0f98f7a4c62888aa799dbaa45d7af65778cda40
94a62234a20b4ecf8d16ad0675f04a6e2b35f1a6
/tuw_object_publisher/include/cone_object.h
a8eb3cc9f4298d8613b9731d244ed460045c2c6d
[ "BSD-3-Clause" ]
permissive
tuw-robotics/tuw_door_detection
1957f34afe5118fb76eb10e53d89b198cb73b770
ee84e40760d1494d399e63fb5c388a6b8ae4cf93
refs/heads/master
2020-03-19T13:33:29.481175
2019-04-18T10:25:34
2019-04-18T10:25:34
136,585,240
2
0
null
null
null
null
UTF-8
C++
false
false
458
h
#ifndef CONE_OBJECT_H #define CONE_OBJECT_H #include "base_pub_object.h" #include <eigen3/Eigen/Core> namespace tuw { class ConeObject : public BasePubObject { public: ConeObject(std::string &type, std::string &file_path, std::string &publisher_topic); virtual ~ConeObject(); virtual bool createMsg(); private: std::vector<std::vector<double>> file_contents_parsed_; }; } #endif
[ "felix0koenig@gmail.com" ]
felix0koenig@gmail.com
6d82c7e9130c743f6cfd8e842a8e48b56730b2d7
8cf763c4c29db100d15f2560953c6e6cbe7a5fd4
/src/qt/qtbase/src/3rdparty/angle/src/libGLESv2/Query.h
a7ec404f8537e9342705c96614497c8653ceeceb
[ "LGPL-2.0-or-later", "LGPL-2.1-only", "GFDL-1.3-only", "Qt-LGPL-exception-1.1", "LicenseRef-scancode-digia-qt-commercial", "LGPL-3.0-only", "GPL-3.0-only", "LicenseRef-scancode-digia-qt-preview", "LGPL-2.1-or-later", "GPL-1.0-or-later", "LicenseRef-scancode-unknown-license-reference", "GPL-2.0...
permissive
chihlee/phantomjs
69d6bbbf1c9199a78e82ae44af072aca19c139c3
644e0b3a6c9c16bcc6f7ce2c24274bf7d764f53c
refs/heads/master
2021-01-19T13:49:41.265514
2018-06-15T22:48:11
2018-06-15T22:48:11
82,420,380
0
0
BSD-3-Clause
2018-06-15T22:48:12
2017-02-18T22:34:48
C++
UTF-8
C++
false
false
827
h
// // Copyright (c) 2012 The ANGLE 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. // // Query.h: Defines the gl::Query class #ifndef LIBGLESV2_QUERY_H_ #define LIBGLESV2_QUERY_H_ #include "libGLESv2/Error.h" #include "common/angleutils.h" #include "common/RefCountObject.h" #include "angle_gl.h" namespace rx { class QueryImpl; } namespace gl { class Query : public RefCountObject { public: Query(rx::QueryImpl *impl, GLuint id); virtual ~Query(); Error begin(); Error end(); Error getResult(GLuint *params); Error isResultAvailable(GLuint *available); GLenum getType() const; private: DISALLOW_COPY_AND_ASSIGN(Query); rx::QueryImpl *mQuery; }; } #endif // LIBGLESV2_QUERY_H_
[ "ariya.hidayat@gmail.com" ]
ariya.hidayat@gmail.com
a9a4a476490c15dc5ffa6f80ec35b52e5cb1f359
4c84d6f2e63244a1d9f7d769a06a6d3d9b694101
/ppro/PrivacyProtection/kuc/ucipc.h
2c135afbbfedac6f8e783ec3eb0c884e26092f1f
[ "Apache-2.0", "RSA-MD" ]
permissive
liangqidong/Guardian-demo
ad3582c9fc53924d2ce0ca3570bf2e0a909d1391
3bf26f02450a676b2b8f77892a895c328dfb6814
refs/heads/master
2020-03-06T22:37:53.416632
2018-03-28T08:26:10
2018-03-28T08:26:10
127,108,413
0
1
null
null
null
null
GB18030
C++
false
false
4,123
h
/************************************************************************ * @file : ucipc.h * @author : WangBin5 <WangBin5.com> * @date : 26/11/2009 AM 11:53:11 * @brief : 与内核通信IPC的用户层代码 * * $Id: $ /************************************************************************/ #ifndef _UC_IPC_H_ #define _UC_IPC_H_ #include <windows.h> #include <list> //#include "defendengine/kavutyu.h" #include "kxeuc.h" #include "ucipc_def.h" #define UC_IPC_EVENT_SEND_C1 L"Global\\{1B42EA3C-727D-4366-BDC6-5940B29F34E3}" #define UC_IPC_EVENT_RECV_C1 L"Global\\{54DDC4D8-66B5-416f-A436-02D71456F9C6}" #define UC_IPC_EVENT_SEND_C2 L"Global\\{96DC960C-5F03-47c4-BAFC-9A386D321296}" #define UC_IPC_EVENT_RECV_C2 L"Global\\{F25FB848-C89D-42fc-9005-1854F5187777}" #define UC_IPC_FILEMAPNAME_C1 L"Global\\{C82FCCB5-4070-4a60-A627-FF1143DE4BEF}" #define UC_IPC_UNINIT_EVENT L"Global\\{2EDB1C62-344F-45ad-82ED-9506A77FC541}" #define UC_IPC_MD5_SIZE 64 // 用于校检的MD5符串大小 typedef struct _KeIpcMsgHead { ULONG ulPort; ULONG ulInBufLen1; ULONG ulInBufLen2; CHAR Md5[UC_IPC_MD5_SIZE]; } KeIpcMsgHead, *PKeIpcMsgHead; class CKxEUCAllocator : public KucIAllocator { #define ArrListSize 63 public: CKxEUCAllocator() { InitializeCriticalSection(&m_cs); memset(m_ArrList, 0, (ArrListSize + 1) * sizeof(LPVOID)); m_nArrConut = 0; } virtual LPVOID WINAPI Alloc( /* [in] */ ULONG ulSize // 要分配的内存大小 ) { LPVOID pvData = NULL; EnterCriticalSection(&m_cs); if (m_nArrConut < ArrListSize) { pvData = (LPVOID)malloc(ulSize); if (!pvData) {goto _Exit_;} m_ArrList[m_nArrConut++] = pvData; } _Exit_: LeaveCriticalSection(&m_cs); return pvData; } void Clear() { int i = 0; EnterCriticalSection(&m_cs); for (i = 0; i < m_nArrConut; i++) { free (m_ArrList[i]); m_ArrList[i] = NULL; } m_nArrConut = 0; LeaveCriticalSection(&m_cs); } private: int m_nArrConut; LPVOID m_ArrList[ArrListSize + 1]; CRITICAL_SECTION m_cs; #undef ArrListSize }; class UcIpc { public: UcIpc(); ~UcIpc(); BOOL InitIpc( IN ULONG nIpcAddr, IN KucPCALLBACK pCallbackRoutine, IN PVOID pvParam, IN ULONG ulSize, IN ULONG ulSize2 ); BOOL Uninit( VOID ); BOOL InitMap( IN LPCWSTR szMapName, IN ULONG ulSize ); static DWORD WINAPI CommunicationWorker( LPVOID lpPrarm ); DWORD SendMsg( IN BOOL bChannel, IN ULONG ulPort, IN PBYTE pInBuf1, IN ULONG ulInBufLen1, IN OPTIONAL PBYTE pInBuf2, IN OPTIONAL ULONG ulInBufLen2, IN DWORD Timeout ); DWORD RecvMsg( IN CKxEUCAllocator* allocator, IN BOOL bChannel, IN OUT PULONG pulPort, IN OUT PBYTE* ppInBuf1, IN OUT PULONG pulInBufLen1, IN OUT PBYTE* ppInBuf2, IN OUT PULONG pulInBufLen2, IN DWORD Timeout ); ULONG GetAddr() {return m_bInitFlag ? m_nIpcAddr : -1;} PBYTE GetMapBuf() {return m_pMapFileBuf;} ULONG GetMapSize() {return m_BufSize;} ULONG GetMapSize2() {return m_BufSize2;} BOOL GetCloseStatus() {return m_bCloseStatus;} BOOL SetCloseStatus(BOOL Status) {return m_bCloseStatus = Status;} private: BOOL m_bInitFlag; HANDLE m_hWork; HANDLE m_hSendEventC1; HANDLE m_hRecvEventC1; PSECURITY_ATTRIBUTES m_pSendSAC1; PSECURITY_ATTRIBUTES m_pRecvSAC1; HANDLE m_hSendEventC2; HANDLE m_hRecvEventC2; PSECURITY_ATTRIBUTES m_pSendSAC2; PSECURITY_ATTRIBUTES m_pRecvSAC2; HANDLE m_hEndEvent; PSECURITY_ATTRIBUTES m_pEndSA; // 通知各线程退出的事件 HANDLE m_hMapFile; PBYTE m_pMapFileBuf; PSECURITY_ATTRIBUTES m_pMapSA; KucPCALLBACK m_pCallbackRoutine; // 回调函数 PVOID m_pvParam; // 回调函数自定义的参数 ULONG m_BufSize; ULONG m_BufSize2; // 第2个channel的大小 ULONG m_nIpcAddr; BOOL m_bCloseStatus; // 是否被临时的关闭.false表示被关闭 }; #endif
[ "18088708700@163.com" ]
18088708700@163.com
e0f36d9635bed547a8ef3200419a5583014a9234
3d1bb0866f069e1846594e4b7d72e4269d3575f5
/Stable/CSCommon/Include/MMatchRuleQuestChallenge.h
6982a156147b1615dd3106094056acfcb53ba6b1
[]
no_license
JumpingY/Gunz1.5
9d3c6c6cefbbe7773ee12a3177b03ee110b99325
cb817a4d871c38cdaf9e50d6240bf8fa8b3f0469
refs/heads/main
2023-09-03T01:23:48.243472
2021-10-31T22:40:46
2021-10-31T22:40:46
null
0
0
null
null
null
null
UHC
C++
false
false
2,645
h
#ifndef _MMATCHRULEQUESTCHALLENGE_H #define _MMATCHRULEQUESTCHALLENGE_H #include "IMatchRuleNewQuest.h" #include "MActorDef.h" #include "MNewQuestScenario.h" class MNewQuestPlayerManager; class MNewQuestNpcManager; class MMatchRuleQuestChallenge : public IMatchRuleNewQuest { static MNewQuestScenarioManager ms_scenarioMgr; public: static void InitScenarioMgr(); static MNewQuestScenarioManager* GetScenarioMgr(); private: MNewQuestScenario* m_pScenario; int m_nCurrSector; // 현재 진행중인 섹터 protected: virtual bool RoundCount(); ///< 라운드 카운트. 모든 라운드가 끝나면 false를 반환한다. virtual void OnBegin(); ///< 전체 게임 시작시 호출 virtual void OnEnd(); ///< 전체 게임 종료시 호출 virtual void OnRoundBegin(); ///< 라운드 시작할 때 호출 virtual void OnRoundEnd(); ///< 라운드 끝날 때 호출 virtual bool OnRun(); ///< 게임틱시 호출 virtual void OnEnterBattle(MUID& uidChar); virtual void OnLeaveBattle(MUID& uidChar); virtual void OnGameKill(const MUID& uidAttacker, const MUID& uidVictim); virtual void OnRequestPlayerDead(const MUID& uidPlayer); virtual void RouteSpawnLateJoinNpc(MUID uidLateJoiner, MUID uidNpc, const char* szNpcDefName, int nCustomSpawnTypeIndex, int nSpawnIndex); protected: virtual bool OnCheckRoundFinish(); ///< 라운드가 끝났는지 체크 virtual bool CheckPlayersAlive(); public: virtual MMATCH_GAMETYPE GetGameType() { return MMATCH_GAMETYPE_QUEST_CHALLENGE; } public: MMatchRuleQuestChallenge(MMatchStage* pStage); virtual ~MMatchRuleQuestChallenge(); virtual void OnCommand(MCommand* pCommand); void RefreshStageGameInfo(); private: virtual void RouteSpawnNpc(MUID uidNPC, MUID uidController, const char* szNpcDefName, int nCustomSpawnTypeIndex, int nSpawnIndex); virtual void RouteSpawnNpcSummon(MUID uidNPC, MUID uidController, int num, const char* szNpcDefName, MShortVector sVec, MShortVector dir, const int route); void RouteNpcDead(MUID uidNPC, MUID uidKiller); void RouteMoveToNextSector(); virtual void ProcessNpcSpawning(); MUID SpawnNpc(const char* szActorDef, int nCustomSpawnTypeIndex, int nSpawnIndex, int nDropItemId); void SpawnNpcSummon(const char* szActorDef, int num, MShortVector nSpawnPos, MShortVector nSpawnDir,const int route); void DropItemByNpcDead(const MUID& uidKiller, int nWorldItemId, const MVector& pos); void RouteXpBpBonus(); void OnSectorBonus(MMatchObject* pObj, const unsigned int nAddedXP, const unsigned int nAddedBP); void MakeStageGameInfo(); void RouteStageGameInfo(); }; #endif
[ "jduncan0392@gmail.com" ]
jduncan0392@gmail.com
91198a8af54c41cfc2b55099f097e63ff48dc5fc
5e00242dc035fdab6aa6bbb40c6d7e6c119ad8e6
/Vault/Others/PROGYM7/J.cpp
6858f2af4145e65d97bc17d7b040f21ab0019eea
[]
no_license
AkiLotus/AkikazeCP
39b9c649383dcb7c71962a161e830b9a9a54a4b3
064db52198873bf61872ea66235d66b97fcde80e
refs/heads/master
2023-07-15T09:53:36.520644
2021-09-03T09:54:06
2021-09-03T09:54:06
141,382,884
9
1
null
null
null
null
UTF-8
C++
false
false
2,788
cpp
// Template by proptit_4t41 // Applied for C++11/C++14 // Add -std=c++14 to your IDE. #include <bits/stdc++.h> using namespace std; #define endl '\n' #define i64 long long #define u64 unsigned long long #define ld long double #define pub push_back #define puf push_front #define pob pop_back #define pof pop_front #define mp make_pair #define mt make_tuple #define fi first #define se second #define MOD 1000000007LL #define INF 1e9 #define LINF 1e18 #define EPS 1e-9 #define GOLD ((1+sqrt(5))/2) #define REcheck cout << "RE here?\n" #define tracker1(i) cout << "working at " << i << endl; #define tracker2(i,j) cout << "working at " << i << "-" << j << endl; #define tracker3(i,j,k) cout << "working at " << i << "-" << j << "-" << k << endl; const double PI=3.14159265358979323846264338327950288419716939937510582097494459230; typedef pair<i64, i64> pii; typedef tuple<i64, i64> tii; typedef tuple<i64, i64, i64> tiii; // global variables here // custom typedef here // functions here int main() { //freopen("FILE.INP", "r", stdin); //freopen("FILE.OUT", "w", stdout); ios_base::sync_with_stdio(0); //cin.tie(NULL); // code here vector<int> next(111111, -1); vector<int> prev(111111, -1); vector<int> toFr(111111, 0); vector<int> token(111111); int fr = -1, bk = -1; int n; cin >> n; int i=1; for (int a=0; a<n; a++) { for (int q=1; q<i; q++) if (prev[q] != -2) cout << prev[q] << " " << q << " " << next[q] << " | token = " << token[q] << endl; cout << "fr = " << fr << " | bk = " << bk << endl; char z; cin >> z; if (z == 'F') { if (bk != -1) { next[i] = fr; token[i] = token[fr] - 1; } else { token[i] = 0; bk = i; } cout << "token[" << i << "] = " << token[i] << endl; prev[fr] = i; fr = i; i++; } else if (z == 'B') { if (fr != -1) { prev[i] = bk; token[i] = token[bk] + 1; } else { token[i] = 0; fr = i; } cout << "token[" << i << "] = " << token[i] << endl; next[bk] = i; bk = i; i++; } else { int out; cin >> out; cout << min(token[bk]-token[out], token[out]-token[fr]) << endl; if (token[bk] - token[out] < token[out] - token[fr]) { // Backdoor int zz = token[fr], j = bk; while (j != out) { if (j == bk) token[j] = zz-1; else token[j] = token[next[j]] - 1; j = prev[j]; } prev[fr] = bk; next[bk] = fr; fr = next[out]; bk = prev[out]; prev[next[out]] = -1; next[prev[out]] = -1; } else { // Frontdoor int zz = token[bk], j = fr; while (j != out) { if (j == fr) token[j] = zz+1; else token[j] = token[prev[j]] + 1; j = next[j]; } prev[fr] = bk; next[bk] = fr; fr = next[out]; bk = prev[out]; prev[next[out]] = -1; next[prev[out]] = -1; } prev[out] = -2; next[out] = -2; } } return 0; }
[ "duybach.224575@gmail.com" ]
duybach.224575@gmail.com
d0678ca23907250dbfaf8e44e64a44e93f7a19d4
4652840c8fa0d701aaca8de426bf64c340a5e831
/content/browser/renderer_host/media/video_capture_controller.cc
bf0d9d9c0a955761f59085374597e3bf0c035f9e
[ "BSD-3-Clause" ]
permissive
remzert/BraveBrowser
de5ab71293832a5396fa3e35690ebd37e8bb3113
aef440e3d759cb825815ae12bd42f33d71227865
refs/heads/master
2022-11-07T03:06:32.579337
2017-02-28T23:02:29
2017-02-28T23:02:29
84,563,445
1
5
BSD-3-Clause
2022-10-26T06:28:58
2017-03-10T13:38:48
null
UTF-8
C++
false
false
19,333
cc
// Copyright (c) 2012 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 "content/browser/renderer_host/media/video_capture_controller.h" #include <stddef.h> #include <stdint.h> #include <map> #include <set> #include "base/bind.h" #include "base/command_line.h" #include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" #include "base/metrics/sparse_histogram.h" #include "build/build_config.h" #include "components/display_compositor/gl_helper.h" #include "content/browser/renderer_host/media/media_stream_manager.h" #include "content/browser/renderer_host/media/video_capture_buffer_tracker_factory_impl.h" #include "content/browser/renderer_host/media/video_capture_gpu_jpeg_decoder.h" #include "content/browser/renderer_host/media/video_capture_manager.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/content_switches.h" #include "media/base/video_frame.h" #include "media/capture/video/video_capture_buffer_pool_impl.h" #include "media/capture/video/video_capture_device_client.h" #if !defined(OS_ANDROID) #include "content/browser/compositor/image_transport_factory.h" #endif using media::VideoCaptureFormat; using media::VideoFrame; using media::VideoFrameMetadata; namespace content { namespace { static const int kInfiniteRatio = 99999; #define UMA_HISTOGRAM_ASPECT_RATIO(name, width, height) \ UMA_HISTOGRAM_SPARSE_SLOWLY( \ name, \ (height) ? ((width) * 100) / (height) : kInfiniteRatio); class SyncTokenClientImpl : public VideoFrame::SyncTokenClient { public: explicit SyncTokenClientImpl(display_compositor::GLHelper* gl_helper) : gl_helper_(gl_helper) {} ~SyncTokenClientImpl() override {} void GenerateSyncToken(gpu::SyncToken* sync_token) override { gl_helper_->GenerateSyncToken(sync_token); } void WaitSyncToken(const gpu::SyncToken& sync_token) override { gl_helper_->WaitSyncToken(sync_token); } private: display_compositor::GLHelper* gl_helper_; }; void ReturnVideoFrame(const scoped_refptr<VideoFrame>& video_frame, const gpu::SyncToken& sync_token) { DCHECK_CURRENTLY_ON(BrowserThread::UI); #if defined(OS_ANDROID) NOTREACHED(); #else display_compositor::GLHelper* gl_helper = ImageTransportFactory::GetInstance()->GetGLHelper(); // UpdateReleaseSyncToken() creates a new sync_token using |gl_helper|, so // wait the given |sync_token| using |gl_helper|. if (gl_helper) { gl_helper->WaitSyncToken(sync_token); SyncTokenClientImpl client(gl_helper); video_frame->UpdateReleaseSyncToken(&client); } #endif } std::unique_ptr<media::VideoCaptureJpegDecoder> CreateGpuJpegDecoder( const media::VideoCaptureJpegDecoder::DecodeDoneCB& decode_done_cb) { return base::MakeUnique<VideoCaptureGpuJpegDecoder>(decode_done_cb); } // Decorator for media::VideoFrameReceiver that forwards all incoming calls // to the Browser IO thread. class VideoFrameReceiverOnIOThread : public media::VideoFrameReceiver { public: explicit VideoFrameReceiverOnIOThread( const base::WeakPtr<VideoFrameReceiver>& receiver) : receiver_(receiver) {} void OnIncomingCapturedVideoFrame( std::unique_ptr<media::VideoCaptureDevice::Client::Buffer> buffer, scoped_refptr<media::VideoFrame> frame) override { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&VideoFrameReceiver::OnIncomingCapturedVideoFrame, receiver_, base::Passed(&buffer), std::move(frame))); } void OnError() override { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&VideoFrameReceiver::OnError, receiver_)); } void OnLog(const std::string& message) override { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&VideoFrameReceiver::OnLog, receiver_, message)); } void OnBufferDestroyed(int buffer_id_to_drop) override { BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(&VideoFrameReceiver::OnBufferDestroyed, receiver_, buffer_id_to_drop)); } private: base::WeakPtr<VideoFrameReceiver> receiver_; }; } // anonymous namespace struct VideoCaptureController::ControllerClient { ControllerClient(VideoCaptureControllerID id, VideoCaptureControllerEventHandler* handler, media::VideoCaptureSessionId session_id, const media::VideoCaptureParams& params) : controller_id(id), event_handler(handler), session_id(session_id), parameters(params), session_closed(false), paused(false) {} ~ControllerClient() {} // ID used for identifying this object. const VideoCaptureControllerID controller_id; VideoCaptureControllerEventHandler* const event_handler; const media::VideoCaptureSessionId session_id; const media::VideoCaptureParams parameters; // Buffers that are currently known to this client. std::set<int> known_buffers; // Buffers currently held by this client, and sync token callback to call when // they are returned from the client. typedef std::map<int, scoped_refptr<VideoFrame>> ActiveBufferMap; ActiveBufferMap active_buffers; // State of capture session, controlled by VideoCaptureManager directly. This // transitions to true as soon as StopSession() occurs, at which point the // client is sent an OnEnded() event. However, because the client retains a // VideoCaptureController* pointer, its ControllerClient entry lives on until // it unregisters itself via RemoveClient(), which may happen asynchronously. // // TODO(nick): If we changed the semantics of VideoCaptureHost so that // OnEnded() events were processed synchronously (with the RemoveClient() done // implicitly), we could avoid tracking this state here in the Controller, and // simplify the code in both places. bool session_closed; // Indicates whether the client is paused, if true, VideoCaptureController // stops updating its buffer. bool paused; }; VideoCaptureController::VideoCaptureController(int max_buffers) : buffer_pool_(new media::VideoCaptureBufferPoolImpl( base::MakeUnique<VideoCaptureBufferTrackerFactoryImpl>(), max_buffers)), state_(VIDEO_CAPTURE_STATE_STARTED), has_received_frames_(false), weak_ptr_factory_(this) { DCHECK_CURRENTLY_ON(BrowserThread::IO); } base::WeakPtr<VideoCaptureController> VideoCaptureController::GetWeakPtrForIOThread() { return weak_ptr_factory_.GetWeakPtr(); } std::unique_ptr<media::VideoCaptureDevice::Client> VideoCaptureController::NewDeviceClient() { DCHECK_CURRENTLY_ON(BrowserThread::IO); return base::MakeUnique<media::VideoCaptureDeviceClient>( base::MakeUnique<VideoFrameReceiverOnIOThread>( this->GetWeakPtrForIOThread()), buffer_pool_, base::Bind(&CreateGpuJpegDecoder, base::Bind(&VideoFrameReceiver::OnIncomingCapturedVideoFrame, this->GetWeakPtrForIOThread()))); } void VideoCaptureController::AddClient( VideoCaptureControllerID id, VideoCaptureControllerEventHandler* event_handler, media::VideoCaptureSessionId session_id, const media::VideoCaptureParams& params) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DVLOG(1) << "VideoCaptureController::AddClient() -- id=" << id << ", session_id=" << session_id << ", params.requested_format=" << media::VideoCaptureFormat::ToString(params.requested_format); // Check that requested VideoCaptureParams are valid and supported. If not, // report an error immediately and punt. if (!params.IsValid() || !(params.requested_format.pixel_format == media::PIXEL_FORMAT_I420 || params.requested_format.pixel_format == media::PIXEL_FORMAT_Y16) || params.requested_format.pixel_storage != media::PIXEL_STORAGE_CPU) { // Crash in debug builds since the renderer should not have asked for // invalid or unsupported parameters. LOG(DFATAL) << "Invalid or unsupported video capture parameters requested: " << media::VideoCaptureFormat::ToString(params.requested_format); event_handler->OnError(id); return; } // If this is the first client added to the controller, cache the parameters. if (controller_clients_.empty()) video_capture_format_ = params.requested_format; // Signal error in case device is already in error state. if (state_ == VIDEO_CAPTURE_STATE_ERROR) { event_handler->OnError(id); return; } // Do nothing if this client has called AddClient before. if (FindClient(id, event_handler, controller_clients_)) return; std::unique_ptr<ControllerClient> client = base::MakeUnique<ControllerClient>(id, event_handler, session_id, params); // If we already have gotten frame_info from the device, repeat it to the new // client. if (state_ == VIDEO_CAPTURE_STATE_STARTED) { controller_clients_.push_back(std::move(client)); return; } } int VideoCaptureController::RemoveClient( VideoCaptureControllerID id, VideoCaptureControllerEventHandler* event_handler) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DVLOG(1) << "VideoCaptureController::RemoveClient, id " << id; ControllerClient* client = FindClient(id, event_handler, controller_clients_); if (!client) return kInvalidMediaCaptureSessionId; // Take back all buffers held by the |client|. for (const auto& buffer : client->active_buffers) buffer_pool_->RelinquishConsumerHold(buffer.first, 1); client->active_buffers.clear(); int session_id = client->session_id; controller_clients_.remove_if( [client](const std::unique_ptr<ControllerClient>& ptr) { return ptr.get() == client; }); return session_id; } void VideoCaptureController::PauseClient( VideoCaptureControllerID id, VideoCaptureControllerEventHandler* event_handler) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DVLOG(1) << "VideoCaptureController::PauseClient, id " << id; ControllerClient* client = FindClient(id, event_handler, controller_clients_); if (!client) return; DLOG_IF(WARNING, client->paused) << "Redundant client configuration"; client->paused = true; } bool VideoCaptureController::ResumeClient( VideoCaptureControllerID id, VideoCaptureControllerEventHandler* event_handler) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DVLOG(1) << "VideoCaptureController::ResumeClient, id " << id; ControllerClient* client = FindClient(id, event_handler, controller_clients_); if (!client) return false; if (!client->paused) { DVLOG(1) << "Calling resume on unpaused client"; return false; } client->paused = false; return true; } int VideoCaptureController::GetClientCount() const { DCHECK_CURRENTLY_ON(BrowserThread::IO); return controller_clients_.size(); } bool VideoCaptureController::HasActiveClient() const { DCHECK_CURRENTLY_ON(BrowserThread::IO); for (const auto& client : controller_clients_) { if (!client->paused) return true; } return false; } bool VideoCaptureController::HasPausedClient() const { DCHECK_CURRENTLY_ON(BrowserThread::IO); for (const auto& client : controller_clients_) { if (client->paused) return true; } return false; } void VideoCaptureController::StopSession(int session_id) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DVLOG(1) << "VideoCaptureController::StopSession, id " << session_id; ControllerClient* client = FindClient(session_id, controller_clients_); if (client) { client->session_closed = true; client->event_handler->OnEnded(client->controller_id); } } void VideoCaptureController::ReturnBuffer( VideoCaptureControllerID id, VideoCaptureControllerEventHandler* event_handler, int buffer_id, const gpu::SyncToken& sync_token, double consumer_resource_utilization) { DCHECK_CURRENTLY_ON(BrowserThread::IO); ControllerClient* client = FindClient(id, event_handler, controller_clients_); // If this buffer is not held by this client, or this client doesn't exist // in controller, do nothing. ControllerClient::ActiveBufferMap::iterator iter; if (!client || (iter = client->active_buffers.find(buffer_id)) == client->active_buffers.end()) { NOTREACHED(); return; } // Set the RESOURCE_UTILIZATION to the maximum of those provided by each // consumer (via separate calls to this method that refer to the same // VideoFrame). The producer of this VideoFrame may check this value, after // all consumer holds are relinquished, to make quality versus performance // trade-off decisions. scoped_refptr<VideoFrame> frame = iter->second; if (std::isfinite(consumer_resource_utilization) && consumer_resource_utilization >= 0.0) { double resource_utilization = -1.0; if (frame->metadata()->GetDouble(VideoFrameMetadata::RESOURCE_UTILIZATION, &resource_utilization)) { frame->metadata()->SetDouble(VideoFrameMetadata::RESOURCE_UTILIZATION, std::max(consumer_resource_utilization, resource_utilization)); } else { frame->metadata()->SetDouble(VideoFrameMetadata::RESOURCE_UTILIZATION, consumer_resource_utilization); } } client->active_buffers.erase(iter); buffer_pool_->RelinquishConsumerHold(buffer_id, 1); #if defined(OS_ANDROID) DCHECK(!sync_token.HasData()); #endif if (sync_token.HasData()) BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&ReturnVideoFrame, frame, sync_token)); } const media::VideoCaptureFormat& VideoCaptureController::GetVideoCaptureFormat() const { DCHECK_CURRENTLY_ON(BrowserThread::IO); return video_capture_format_; } VideoCaptureController::~VideoCaptureController() { } void VideoCaptureController::OnIncomingCapturedVideoFrame( std::unique_ptr<media::VideoCaptureDevice::Client::Buffer> buffer, scoped_refptr<VideoFrame> frame) { DCHECK_CURRENTLY_ON(BrowserThread::IO); const int buffer_id = buffer->id(); DCHECK_NE(buffer_id, media::VideoCaptureBufferPool::kInvalidId); int count = 0; if (state_ == VIDEO_CAPTURE_STATE_STARTED) { if (!frame->metadata()->HasKey(VideoFrameMetadata::FRAME_RATE)) { frame->metadata()->SetDouble(VideoFrameMetadata::FRAME_RATE, video_capture_format_.frame_rate); } std::unique_ptr<base::DictionaryValue> metadata( new base::DictionaryValue()); frame->metadata()->MergeInternalValuesInto(metadata.get()); // Only I420 and Y16 pixel formats are currently supported. DCHECK(frame->format() == media::PIXEL_FORMAT_I420 || frame->format() == media::PIXEL_FORMAT_Y16) << "Unsupported pixel format: " << media::VideoPixelFormatToString(frame->format()); // Sanity-checks to confirm |frame| is actually being backed by |buffer|. DCHECK(frame->storage_type() == media::VideoFrame::STORAGE_SHMEM); DCHECK(frame->data(media::VideoFrame::kYPlane) >= buffer->data(0) && (frame->data(media::VideoFrame::kYPlane) < (reinterpret_cast<const uint8_t*>(buffer->data(0)) + buffer->mapped_size()))) << "VideoFrame does not appear to be backed by Buffer"; for (const auto& client : controller_clients_) { if (client->session_closed || client->paused) continue; // On the first use of a buffer on a client, share the memory handles. const bool is_new_buffer = client->known_buffers.insert(buffer_id).second; if (is_new_buffer) DoNewBufferOnIOThread(client.get(), buffer.get(), frame); client->event_handler->OnBufferReady(client->controller_id, buffer_id, frame); const bool inserted = client->active_buffers.insert(std::make_pair(buffer_id, frame)) .second; DCHECK(inserted) << "Unexpected duplicate buffer: " << buffer_id; count++; } } if (!has_received_frames_) { UMA_HISTOGRAM_COUNTS("Media.VideoCapture.Width", frame->visible_rect().width()); UMA_HISTOGRAM_COUNTS("Media.VideoCapture.Height", frame->visible_rect().height()); UMA_HISTOGRAM_ASPECT_RATIO("Media.VideoCapture.AspectRatio", frame->visible_rect().width(), frame->visible_rect().height()); double frame_rate = 0.0f; if (!frame->metadata()->GetDouble(VideoFrameMetadata::FRAME_RATE, &frame_rate)) { frame_rate = video_capture_format_.frame_rate; } UMA_HISTOGRAM_COUNTS("Media.VideoCapture.FrameRate", frame_rate); has_received_frames_ = true; } buffer_pool_->HoldForConsumers(buffer_id, count); } void VideoCaptureController::OnError() { DCHECK_CURRENTLY_ON(BrowserThread::IO); state_ = VIDEO_CAPTURE_STATE_ERROR; for (const auto& client : controller_clients_) { if (client->session_closed) continue; client->event_handler->OnError(client->controller_id); } } void VideoCaptureController::OnLog(const std::string& message) { DCHECK_CURRENTLY_ON(BrowserThread::IO); MediaStreamManager::SendMessageToNativeLog("Video capture: " + message); } void VideoCaptureController::OnBufferDestroyed(int buffer_id_to_drop) { DCHECK_CURRENTLY_ON(BrowserThread::IO); for (const auto& client : controller_clients_) { if (client->session_closed) continue; if (client->known_buffers.erase(buffer_id_to_drop)) { client->event_handler->OnBufferDestroyed(client->controller_id, buffer_id_to_drop); } } } void VideoCaptureController::DoNewBufferOnIOThread( ControllerClient* client, media::VideoCaptureDevice::Client::Buffer* buffer, const scoped_refptr<media::VideoFrame>& frame) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK_EQ(media::VideoFrame::STORAGE_SHMEM, frame->storage_type()); const int buffer_id = buffer->id(); mojo::ScopedSharedBufferHandle handle = buffer_pool_->GetHandleForTransit(buffer_id); client->event_handler->OnBufferCreated(client->controller_id, std::move(handle), buffer->mapped_size(), buffer_id); } VideoCaptureController::ControllerClient* VideoCaptureController::FindClient( VideoCaptureControllerID id, VideoCaptureControllerEventHandler* handler, const ControllerClients& clients) { for (const auto& client : clients) { if (client->controller_id == id && client->event_handler == handler) return client.get(); } return nullptr; } VideoCaptureController::ControllerClient* VideoCaptureController::FindClient( int session_id, const ControllerClients& clients) { for (const auto& client : clients) { if (client->session_id == session_id) return client.get(); } return nullptr; } } // namespace content
[ "serg.zhukovsky@gmail.com" ]
serg.zhukovsky@gmail.com
dc3220db7d3ca307feb0af75d8575e71249f25db
bfe74845c2345a9c00f9ceb2eeb1b8600aefcab3
/Stack 1/Char_Stack/stack.h
0acce7186753455258538f0f6e77ee1987ccc1f1
[]
no_license
AbbyBounty/ds-solution
395cd9150e55f5be96def8f60831ff41bd69bf8e
780f4a3c00d49c40ce0e4bf7f69bc756a6e1947e
refs/heads/main
2023-01-09T07:08:12.238688
2020-11-09T16:48:04
2020-11-09T16:48:04
311,227,861
0
0
null
null
null
null
UTF-8
C++
false
false
267
h
#define _CRT_SECURE_NO_WARNINGS #include<iostream> using namespace std; #define ERROR -9999 class CStack { int size, top; char *arr; public: CStack(); CStack(int); void push(char); char pop(); char isFull(); char isEmpty(); char peek(); void display(); };
[ "abhilash.kamble376@gmail.com" ]
abhilash.kamble376@gmail.com
4bb4b38ebaaa44f073916ce85fe98ab6e0ee83ae
ab97a8915347c76d05d6690dbdbcaf23d7f0d1fd
/chromeos/services/device_sync/remote_device_v2_loader_impl.cc
700ec48c20894a0de52aae0e9e8d077d80bc3a66
[ "BSD-3-Clause" ]
permissive
laien529/chromium
c9eb243957faabf1b477939e3b681df77f083a9a
3f767cdd5c82e9c78b910b022ffacddcb04d775a
refs/heads/master
2022-11-28T00:28:58.669067
2020-08-20T08:37:31
2020-08-20T08:37:31
288,961,699
1
0
BSD-3-Clause
2020-08-20T09:21:57
2020-08-20T09:21:56
null
UTF-8
C++
false
false
4,446
cc
// Copyright 2019 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 "chromeos/services/device_sync/remote_device_v2_loader_impl.h" #include <utility> #include "base/bind.h" #include "base/memory/ptr_util.h" #include "chromeos/components/multidevice/beacon_seed.h" #include "chromeos/components/multidevice/logging/logging.h" #include "chromeos/components/multidevice/secure_message_delegate_impl.h" #include "chromeos/services/device_sync/async_execution_time_metrics_logger.h" #include "chromeos/services/device_sync/cryptauth_task_metrics_logger.h" namespace chromeos { namespace device_sync { // static RemoteDeviceV2LoaderImpl::Factory* RemoteDeviceV2LoaderImpl::Factory::test_factory_ = nullptr; // static std::unique_ptr<RemoteDeviceV2Loader> RemoteDeviceV2LoaderImpl::Factory::Create() { if (test_factory_) return test_factory_->CreateInstance(); return base::WrapUnique(new RemoteDeviceV2LoaderImpl()); } // static void RemoteDeviceV2LoaderImpl::Factory::SetFactoryForTesting( Factory* test_factory) { test_factory_ = test_factory; } RemoteDeviceV2LoaderImpl::Factory::~Factory() = default; RemoteDeviceV2LoaderImpl::RemoteDeviceV2LoaderImpl() : secure_message_delegate_( multidevice::SecureMessageDelegateImpl::Factory::Create()) {} RemoteDeviceV2LoaderImpl::~RemoteDeviceV2LoaderImpl() = default; void RemoteDeviceV2LoaderImpl::Load( const CryptAuthDeviceRegistry::InstanceIdToDeviceMap& id_to_device_map, const std::string& user_email, const std::string& user_private_key, LoadCallback callback) { DCHECK(!user_email.empty()); DCHECK(!user_private_key.empty()); DCHECK(callback_.is_null()); callback_ = std::move(callback); DCHECK(id_to_device_map_.empty()); id_to_device_map_ = id_to_device_map; if (id_to_device_map_.empty()) { std::move(callback_).Run(remote_devices_); return; } DCHECK(remaining_ids_to_process_.empty()); for (const auto& id_device_pair : id_to_device_map_) remaining_ids_to_process_.insert(id_device_pair.first); for (const auto& id_device_pair : id_to_device_map_) { if (!id_device_pair.second.better_together_device_metadata || id_device_pair.second.better_together_device_metadata->public_key() .empty()) { AddRemoteDevice(id_device_pair.second, user_email, std::string() /* psk */); continue; } // Performs ECDH key agreement to generate a shared secret between the local // device and the remote device of |id_device_pair|. secure_message_delegate_->DeriveKey( user_private_key, id_device_pair.second.better_together_device_metadata->public_key(), base::Bind(&RemoteDeviceV2LoaderImpl::OnPskDerived, base::Unretained(this), id_device_pair.second, user_email)); } } void RemoteDeviceV2LoaderImpl::OnPskDerived(const CryptAuthDevice& device, const std::string& user_email, const std::string& psk) { if (psk.empty()) PA_LOG(WARNING) << "Derived persistent symmetric key is empty."; AddRemoteDevice(device, user_email, psk); } void RemoteDeviceV2LoaderImpl::AddRemoteDevice(const CryptAuthDevice& device, const std::string& user_email, const std::string& psk) { const base::Optional<cryptauthv2::BetterTogetherDeviceMetadata>& beto_metadata = device.better_together_device_metadata; remote_devices_.emplace_back( user_email, device.instance_id(), device.device_name, beto_metadata ? beto_metadata->no_pii_device_name() : std::string(), beto_metadata ? beto_metadata->public_key() : std::string(), psk, device.last_update_time.ToJavaTime(), device.feature_states, beto_metadata ? multidevice::FromCryptAuthV2SeedRepeatedPtrField( beto_metadata->beacon_seeds()) : std::vector<multidevice::BeaconSeed>(), beto_metadata ? beto_metadata->bluetooth_public_address() : std::string()); remaining_ids_to_process_.erase(device.instance_id()); if (remaining_ids_to_process_.empty()) std::move(callback_).Run(remote_devices_); } } // namespace device_sync } // namespace chromeos
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
a60dfb01ecdf90101e2070c195f08f64a52758e6
a850b07742a9573c48e3f655cf66990fd41c32da
/enigmamachine.h
61f5f67b78b10b93e6319cf7d0a9b2ba7fddc9b0
[]
no_license
StewartDouglas/EnigmaMachine
3c2fd7da7c36efa0c752f56157aa4944d1f06452
6a66356b6506c9d21b78886f4eba092d3f477b7d
refs/heads/master
2020-12-09T12:29:59.437468
2016-09-07T11:34:53
2016-09-07T11:34:53
14,539,774
1
0
null
null
null
null
UTF-8
C++
false
false
776
h
#ifndef __ENIGMAMACHINE_H_INCLUDED__ #define __ENIGMAMACHINE_H_INCLUDED__ #include "enigma.h" #include "plugboard.h" #include "reflector.h" #include "rotor.h" /* The EnigmaMachine class contains instances of all the necessary Components to create a functioning simulation of the original enigma machine. This includes a plugboard, a reflector and an array of rotors. It has a constructor method, and runEnigmaMachine() encrypts the users input (for a valid character, runEnigmaMachine() serves as a bijective function.) */ class EnigmaMachine { private: Plugboard plugboard; Reflector reflector; Rotor* rotor_array; int numberRotors; public: EnigmaMachine(int argc, const char * argv[]); ~EnigmaMachine(); void runEnigmaMachine(); }; #endif
[ "stewart@Stewarts-MacBook-Air.local" ]
stewart@Stewarts-MacBook-Air.local
672eda523ddfa8aa939063b38514815028a2f262
573dea83dd96e5107ffc652bb8f91fe6d7884598
/7. Reverse Integer.cpp
218dcb24ce771c15871396699f306bd44a023c22
[]
no_license
haomingchan0811/Leetcode
bc1bfbf121227a6145c8efb631fe788746d5afcd
1a0dbcabb0f454a4fdcc31af9b919f5d30664335
refs/heads/master
2020-12-26T00:53:29.838925
2017-09-20T17:26:00
2017-09-20T17:26:00
67,911,625
0
0
null
null
null
null
UTF-8
C++
false
false
490
cpp
class Solution { public: // 6ms, 72.14%, ok int reverse(int x) { if(x == 0) return 0; long temp = 0; // bool isNegative = false; // no need for "%": can handle negative case // if(x < 0) {x = -x; isNegative = true;} while(x){ temp = temp * 10 + x % 10; if(temp > INT_MAX || temp < INT_MIN) // bug: deal with overflow problem return 0; x /= 10; } return int(temp); } };
[ "chenhaomingsz@gmail.com" ]
chenhaomingsz@gmail.com
c5387d5fbaf6f509abcedb839dcd405900389996
c732649de5f651143089f1cac878e86513487906
/cpp/open3d/visualization/gui/Window.cpp
4aeb1ca5a958d13ad6f9cc4fc1846587305d47c3
[ "MIT" ]
permissive
syncle/Open3D
7186726abd5511885e0c3cfc52baf42dc4a28e23
a019b78a3aff5105d355f2bef83b57ce015c9dbc
refs/heads/master
2022-02-23T01:40:13.474994
2022-02-08T18:59:03
2022-02-08T18:59:03
90,085,935
0
0
MIT
2018-01-31T01:41:49
2017-05-02T23:03:26
C
UTF-8
C++
false
false
47,434
cpp
// ---------------------------------------------------------------------------- // - Open3D: www.open3d.org - // ---------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2018-2021 www.open3d.org // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // ---------------------------------------------------------------------------- #include "open3d/visualization/gui/Window.h" #include <imgui.h> #include <imgui_internal.h> // so we can examine the current context #include <algorithm> #include <cmath> #include <memory> #include <queue> #include <unordered_map> #include <vector> #include "open3d/utility/Logging.h" #include "open3d/visualization/gui/Application.h" #include "open3d/visualization/gui/Button.h" #include "open3d/visualization/gui/Dialog.h" #include "open3d/visualization/gui/ImguiFilamentBridge.h" #include "open3d/visualization/gui/Label.h" #include "open3d/visualization/gui/Layout.h" #include "open3d/visualization/gui/Menu.h" #include "open3d/visualization/gui/SceneWidget.h" #include "open3d/visualization/gui/Theme.h" #include "open3d/visualization/gui/Util.h" #include "open3d/visualization/gui/Widget.h" #include "open3d/visualization/gui/WindowSystem.h" #include "open3d/visualization/rendering/filament/FilamentRenderer.h" #ifdef BUILD_WEBRTC #include "open3d/visualization/webrtc_server/WebRTCWindowSystem.h" #endif // ---------------------------------------------------------------------------- namespace open3d { namespace visualization { namespace gui { namespace { static constexpr int CENTERED_X = -10000; static constexpr int CENTERED_Y = -10000; static constexpr int AUTOSIZE_WIDTH = 0; static constexpr int AUTOSIZE_HEIGHT = 0; // Assumes the correct ImGuiContext is current void UpdateImGuiForScaling(float new_scaling) { ImGuiStyle& style = ImGui::GetStyle(); // FrameBorderSize is not adjusted (we want minimal borders) style.FrameRounding *= new_scaling; } void ChangeAllRenderQuality( SceneWidget::Quality quality, const std::vector<std::shared_ptr<Widget>>& children) { for (auto child : children) { auto sw = std::dynamic_pointer_cast<SceneWidget>(child); if (sw) { sw->SetRenderQuality(quality); } else { if (child->GetChildren().size() > 0) { ChangeAllRenderQuality(quality, child->GetChildren()); } } } } struct ImguiWindowContext : public FontContext { const Theme* theme = nullptr; std::unique_ptr<ImguiFilamentBridge> imgui_bridge; ImGuiContext* context = nullptr; std::vector<ImFont*> fonts; // references, not owned by us float scaling = 1.0; void* GetFont(FontId font_id) { return this->fonts[font_id]; } void CreateFonts() { // ImGUI puts all fonts into one big texture atlas. However, there are // separate ImFont* pointers for each conceptual font. This means that // while we can have many fonts, all the fonts that we are ever going // to use must be loaded up front, which makes a large font selection // inconsistent with small memory footprint. Also, we might bump into // OpenGL texture size limitations. auto& font_descs = Application::GetInstance().GetFontDescriptions(); this->fonts.reserve(font_descs.size()); for (auto& fd : font_descs) { this->fonts.push_back(AddFont(fd)); } ImGuiIO& io = ImGui::GetIO(); unsigned char* pixels; int textureW, textureH, bytesPerPx; io.Fonts->GetTexDataAsAlpha8(&pixels, &textureW, &textureH, &bytesPerPx); // Some fonts seem to result in 0x0 textures (maybe if the font does // not contain any of the code points?), which cause Filament to // panic. Handle this gracefully. if (textureW == 0 || textureH == 0) { utility::LogWarning( "Got zero-byte font texture; ignoring custom fonts"); io.Fonts->Clear(); this->fonts[0] = io.Fonts->AddFontFromFileTTF(this->theme->font_path.c_str(), float(this->theme->font_size)); for (unsigned int i = 1; i < font_descs.size(); ++i) { this->fonts[i] = this->fonts[0]; } io.Fonts->GetTexDataAsAlpha8(&pixels, &textureW, &textureH, &bytesPerPx); } this->imgui_bridge->CreateAtlasTextureAlpha8(pixels, textureW, textureH, bytesPerPx); ImGui::SetCurrentFont(this->fonts[Application::DEFAULT_FONT_ID]); } ImFont* AddFont(const FontDescription& fd) { // We can assume that everything in the FontDescription is usable, since // Application::SetFont() should have ensured that it is usable. ImFont* imfont = nullptr; ImGuiIO& io = ImGui::GetIO(); float point_size; if (fd.point_size_ <= 0) { point_size = float(this->theme->font_size); } else { point_size = this->scaling * float(fd.point_size_); } // The first range should be "en" from // FontDescription::FontDescription() if (fd.ranges_.size() == 1) { imfont = io.Fonts->AddFontFromFileTTF(fd.ranges_[0].path.c_str(), point_size); } else { imfont = io.Fonts->AddFontFromFileTTF( fd.ranges_[0].path.c_str(), point_size, NULL, io.Fonts->GetGlyphRangesDefault()); } ImFontConfig config; config.MergeMode = true; for (auto& r : fd.ranges_) { if (!r.lang.empty()) { const ImWchar* range; if (r.lang == "en") { continue; // added above, don't add cyrillic too } else if (r.lang == "ja") { range = io.Fonts->GetGlyphRangesJapanese(); } else if (r.lang == "ko") { range = io.Fonts->GetGlyphRangesKorean(); } else if (r.lang == "th") { range = io.Fonts->GetGlyphRangesThai(); } else if (r.lang == "vi") { range = io.Fonts->GetGlyphRangesVietnamese(); } else if (r.lang == "zh") { range = io.Fonts->GetGlyphRangesChineseSimplifiedCommon(); } else if (r.lang == "zh_all") { range = io.Fonts->GetGlyphRangesChineseFull(); } else { // so many languages use Cyrillic it can be the // default range = io.Fonts->GetGlyphRangesCyrillic(); } imfont = io.Fonts->AddFontFromFileTTF( r.path.c_str(), point_size, &config, range); } else if (!r.code_points.empty()) { // TODO: the ImGui docs say that this must exist until // CreateAtlastTextureAlpha8(). ImVector<ImWchar> range; ImFontGlyphRangesBuilder builder; for (auto c : r.code_points) { builder.AddChar(c); } builder.BuildRanges(&range); imfont = io.Fonts->AddFontFromFileTTF( r.path.c_str(), point_size, &config, range.Data); } } return imfont; } }; } // namespace const int Window::FLAG_HIDDEN = (1 << 0); const int Window::FLAG_TOPMOST = (1 << 1); struct Window::Impl { Impl() {} ~Impl() {} WindowSystem::OSWindow window_ = nullptr; std::string title_; // there is no glfwGetWindowTitle()... bool draw_menu_ = true; std::unordered_map<Menu::ItemId, std::function<void()>> menu_callbacks_; std::function<bool(void)> on_tick_event_; std::function<bool(void)> on_close_; // We need these for mouse moves and wheel events. // The only source of ground truth is button events, so the rest of // the time we monitor key up/down events. int mouse_mods_ = 0; // ORed KeyModifiers double last_render_time_ = 0.0; double last_button_down_time_ = 0.0; // we have to compute double-click MouseButton last_button_down_ = MouseButton::NONE; Theme theme_; // so that the font size can be different based on scaling visualization::rendering::FilamentRenderer* renderer_; ImguiWindowContext imgui_; std::vector<std::shared_ptr<Widget>> children_; // Active dialog is owned here. It is not put in the children because // we are going to add it and take it out during draw (since that's // how an immediate mode GUI works) and that involves changing the // children while iterating over it. Also, conceptually it is not a // child, it is a child window, and needs to be on top, which we cannot // guarantee if it is a child widget. std::shared_ptr<Dialog> active_dialog_; std::queue<std::function<void()>> deferred_until_before_draw_; std::queue<std::function<void()>> deferred_until_draw_; Widget* mouse_grabber_widget_ = nullptr; // only if not ImGUI widget Widget* focus_widget_ = nullptr; // only used if ImGUI isn't taking keystrokes bool wants_auto_size_ = false; bool wants_auto_center_ = false; bool needs_layout_ = true; bool needs_redraw_ = true; // set by PostRedraw to defer if already drawing bool is_resizing_ = false; bool is_drawing_ = false; }; Window::Window(const std::string& title, int flags /*= 0*/) : Window(title, CENTERED_X, CENTERED_Y, AUTOSIZE_WIDTH, AUTOSIZE_HEIGHT) {} Window::Window(const std::string& title, int width, int height, int flags /*= 0*/) : Window(title, CENTERED_X, CENTERED_Y, width, height) {} Window::Window(const std::string& title, int x, int y, int width, int height, int flags /*= 0*/) : impl_(new Window::Impl()) { // Make sure that the Application instance is initialized before creating // the window. It is easy to call, e.g. O3DVisualizer() and forgetting to // initialize the application. This will cause a crash because the window // system will not exist, nor will the resource directory be located, and // so the renderer will not load properly and give cryptic messages. Application::GetInstance().VerifyIsInitialized(); impl_->wants_auto_center_ = (x == CENTERED_X || y == CENTERED_Y); impl_->wants_auto_size_ = (width == AUTOSIZE_WIDTH || height == AUTOSIZE_HEIGHT); bool visible = (!(flags & FLAG_HIDDEN) && (impl_->wants_auto_size_ || impl_->wants_auto_center_)); int ws_flags = 0; if (!visible) { ws_flags |= WindowSystem::FLAG_HIDDEN; } if (flags & FLAG_TOPMOST) { ws_flags |= WindowSystem::FLAG_TOPMOST; } int initial_width = std::max(10, width); int initial_height = std::max(10, height); auto& ws = Application::GetInstance().GetWindowSystem(); impl_->window_ = ws.CreateOSWindow(this, initial_width, initial_height, title.c_str(), ws_flags); impl_->title_ = title; if (x != CENTERED_X || y != CENTERED_Y) { ws.SetWindowPos(impl_->window_, x, y); } auto& theme = impl_->theme_; // shorter alias impl_->imgui_.context = ImGui::CreateContext(); auto oldContext = MakeDrawContextCurrent(); // ImGUI creates a bitmap atlas from a font, so we need to have the correct // size when we create it, because we can't change the bitmap without // reloading the whole thing (expensive). // Note that GetScaling() gets the pixel scaling. On macOS, coordinates are // specified in points, not device pixels. The conversion to device pixels // is the scaling factor. On Linux, there is no scaling of pixels (just // like in Open3D's GUI library), and glfwGetWindowContentScale() returns // the appropriate scale factor for text and icons and such. float scaling = ws.GetUIScaleFactor(impl_->window_); impl_->imgui_.scaling = scaling; impl_->theme_ = Application::GetInstance().GetTheme(); impl_->theme_.font_size = int(std::round(impl_->theme_.font_size * scaling)); impl_->theme_.default_margin = int(std::round(impl_->theme_.default_margin * scaling)); impl_->theme_.default_layout_spacing = int(std::round(impl_->theme_.default_layout_spacing * scaling)); ImGui::StyleColorsDark(); ImGuiStyle& style = ImGui::GetStyle(); style.WindowPadding = ImVec2(0, 0); style.WindowRounding = 0; style.WindowBorderSize = 0; style.FrameBorderSize = float(theme.border_width); style.FrameRounding = float(theme.border_radius); style.ChildRounding = float(theme.border_radius); style.Colors[ImGuiCol_WindowBg] = colorToImgui(theme.background_color); style.Colors[ImGuiCol_ChildBg] = colorToImgui(theme.background_color); style.Colors[ImGuiCol_Text] = colorToImgui(theme.text_color); style.Colors[ImGuiCol_Border] = colorToImgui(theme.border_color); style.Colors[ImGuiCol_Button] = colorToImgui(theme.button_color); style.Colors[ImGuiCol_ButtonHovered] = colorToImgui(theme.button_hover_color); style.Colors[ImGuiCol_ButtonActive] = colorToImgui(theme.button_active_color); style.Colors[ImGuiCol_CheckMark] = colorToImgui(theme.checkbox_check_color); style.Colors[ImGuiCol_FrameBg] = colorToImgui(theme.combobox_background_color); style.Colors[ImGuiCol_FrameBgHovered] = colorToImgui(theme.combobox_hover_color); style.Colors[ImGuiCol_FrameBgActive] = style.Colors[ImGuiCol_FrameBgHovered]; style.Colors[ImGuiCol_SliderGrab] = colorToImgui(theme.slider_grab_color); style.Colors[ImGuiCol_SliderGrabActive] = colorToImgui(theme.slider_grab_color); style.Colors[ImGuiCol_Tab] = colorToImgui(theme.tab_inactive_color); style.Colors[ImGuiCol_TabHovered] = colorToImgui(theme.tab_hover_color); style.Colors[ImGuiCol_TabActive] = colorToImgui(theme.tab_active_color); ImGuiIO& io = ImGui::GetIO(); io.IniFilename = nullptr; // ImGUI's io.KeysDown is indexed by our scan codes, and we fill out // io.KeyMap to map from our code to ImGui's code. io.KeyMap[ImGuiKey_Tab] = KEY_TAB; io.KeyMap[ImGuiKey_LeftArrow] = KEY_LEFT; io.KeyMap[ImGuiKey_RightArrow] = KEY_RIGHT; io.KeyMap[ImGuiKey_UpArrow] = KEY_UP; io.KeyMap[ImGuiKey_DownArrow] = KEY_DOWN; io.KeyMap[ImGuiKey_PageUp] = KEY_PAGEUP; io.KeyMap[ImGuiKey_PageDown] = KEY_PAGEDOWN; io.KeyMap[ImGuiKey_Home] = KEY_HOME; io.KeyMap[ImGuiKey_End] = KEY_END; io.KeyMap[ImGuiKey_Insert] = KEY_INSERT; io.KeyMap[ImGuiKey_Delete] = KEY_DELETE; io.KeyMap[ImGuiKey_Backspace] = KEY_BACKSPACE; io.KeyMap[ImGuiKey_Space] = ' '; io.KeyMap[ImGuiKey_Enter] = KEY_ENTER; io.KeyMap[ImGuiKey_Escape] = KEY_ESCAPE; io.KeyMap[ImGuiKey_A] = 'a'; io.KeyMap[ImGuiKey_C] = 'c'; io.KeyMap[ImGuiKey_V] = 'v'; io.KeyMap[ImGuiKey_X] = 'x'; io.KeyMap[ImGuiKey_Y] = 'y'; io.KeyMap[ImGuiKey_Z] = 'z'; /* io.SetClipboardTextFn = [this](void*, const char* text) { glfwSetClipboardString(this->impl_->window, text); }; io.GetClipboardTextFn = [this](void*) -> const char* { return glfwGetClipboardString(this->impl_->window); }; */ io.ClipboardUserData = nullptr; // Restore the context, in case we are creating a window during a draw. // (This is quite likely, since ImGUI only handles things like button // presses during draw. A file open dialog is likely to create a window // after pressing "Open".) RestoreDrawContext(oldContext); CreateRenderer(); } void Window::CreateRenderer() { // This is a delayed part of the constructor. See comment at end of ctor. auto old_context = MakeDrawContextCurrent(); // On single-threaded platforms, Filament's OpenGL context must be current, // not GLFW's context, so create the renderer after the window. impl_->renderer_ = Application::GetInstance().GetWindowSystem().CreateRenderer( impl_->window_); impl_->renderer_->SetClearColor({1.0f, 1.0f, 1.0f, 1.0f}); impl_->imgui_.imgui_bridge = std::make_unique<ImguiFilamentBridge>(impl_->renderer_, GetSize()); impl_->imgui_.theme = &impl_->theme_; impl_->imgui_.CreateFonts(); RestoreDrawContext(old_context); } Window::~Window() { impl_->active_dialog_.reset(); impl_->children_.clear(); // needs to happen before deleting renderer ImGui::SetCurrentContext(impl_->imgui_.context); ImGui::DestroyContext(); delete impl_->renderer_; DestroyWindow(); } void Window::DestroyWindow() { Application::GetInstance().GetWindowSystem().DestroyWindow(impl_->window_); // Ensure DestroyWindow() can be called multiple times, which will // happen if you call DestroyWindow() before the destructor. impl_->window_ = nullptr; } int Window::GetMouseMods() const { return impl_->mouse_mods_; } std::string Window::GetWebRTCUID() const { #ifdef BUILD_WEBRTC if (auto* webrtc_ws = dynamic_cast<webrtc_server::WebRTCWindowSystem*>( &Application::GetInstance().GetWindowSystem())) { return webrtc_ws->GetWindowUID(impl_->window_); } else { return "window_undefined"; } #else return "window_undefined"; #endif } const std::vector<std::shared_ptr<Widget>>& Window::GetChildren() const { return impl_->children_; } void* Window::MakeDrawContextCurrent() const { auto old_context = ImGui::GetCurrentContext(); ImGui::SetCurrentContext(impl_->imgui_.context); return old_context; } void Window::RestoreDrawContext(void* oldContext) const { ImGui::SetCurrentContext((ImGuiContext*)oldContext); } const Theme& Window::GetTheme() const { return impl_->theme_; } visualization::rendering::Renderer& Window::GetRenderer() const { return *impl_->renderer_; } Rect Window::GetOSFrame() const { auto& ws = Application::GetInstance().GetWindowSystem(); auto pos = ws.GetWindowPos(impl_->window_); auto size = ws.GetWindowSize(impl_->window_); return Rect(pos.x, pos.y, size.width, size.height); } void Window::SetOSFrame(const Rect& r) { auto& ws = Application::GetInstance().GetWindowSystem(); ws.SetWindowPos(impl_->window_, r.x, r.y); ws.SetWindowSize(impl_->window_, r.width, r.height); } const char* Window::GetTitle() const { return impl_->title_.c_str(); } void Window::SetTitle(const char* title) { impl_->title_ = title; return Application::GetInstance().GetWindowSystem().SetWindowTitle( impl_->window_, title); } // Note: can only be called if the ImGUI context is current (that is, // after MakeDrawContextCurrent() has been called), otherwise // ImGUI won't be able to access the font. Size Window::CalcPreferredSize() { // If we don't have any children--unlikely, but might happen when you're // experimenting and just create an empty window to see if you understand // how to config the library--return a non-zero size, since a size of (0, 0) // will end up with a crash. if (impl_->children_.empty()) { return Size(int(std::round(640.0f * impl_->imgui_.scaling)), int(std::round(480.0f * impl_->imgui_.scaling))); } Rect bbox(0, 0, 0, 0); for (auto& child : impl_->children_) { auto pref = child->CalcPreferredSize(GetLayoutContext(), Widget::Constraints()); Rect r(child->GetFrame().x, child->GetFrame().y, pref.width, pref.height); bbox = bbox.UnionedWith(r); } // Note: we are doing (bbox.GetRight() - 0) NOT (bbox.GetRight() - bbox.x) // (and likewise for height) because the origin of the window is // (0, 0) and anything up/left is clipped. return Size(bbox.GetRight(), bbox.GetBottom()); } void Window::SizeToFit() { // CalcPreferredSize() can only be called while the ImGUI context // is current, but we are probably calling this while setting up the // window. auto auto_size = [this]() { SetSize(CalcPreferredSize()); }; impl_->deferred_until_draw_.push(auto_size); } void Window::SetSize(const Size& size) { // Make sure we do the resize outside of a draw, to avoid unsightly // errors if we happen to do this in the middle of a draw. auto resize = [this, size /*copy*/]() { auto scaling = this->impl_->imgui_.scaling; int width = int(std::round(float(size.width) / scaling)); int height = int(std::round(float(size.height) / scaling)); Application::GetInstance().GetWindowSystem().SetWindowSize( impl_->window_, width, height); }; impl_->deferred_until_before_draw_.push(resize); } Size Window::GetSize() const { return Application::GetInstance().GetWindowSystem().GetWindowSizePixels( impl_->window_); } Rect Window::GetContentRect() const { auto size = GetSize(); int menu_height = 0; MakeDrawContextCurrent(); auto menubar = Application::GetInstance().GetMenubar(); if (menubar && impl_->draw_menu_) { menu_height = menubar->CalcHeight(GetTheme()); } return Rect(0, menu_height, size.width, size.height - menu_height); } float Window::GetScaling() const { return Application::GetInstance().GetWindowSystem().GetWindowScaleFactor( impl_->window_); } Point Window::GlobalToWindowCoord(int global_x, int global_y) { auto pos = Application::GetInstance().GetWindowSystem().GetWindowPos( impl_->window_); return Point(global_y - pos.x, global_y - pos.y); } bool Window::IsVisible() const { return Application::GetInstance().GetWindowSystem().GetWindowIsVisible( impl_->window_); } void Window::Show(bool vis /*= true*/) { Application::GetInstance().GetWindowSystem().ShowWindow(impl_->window_, vis); } void Window::Close() { if (impl_->on_close_) { bool should_close = impl_->on_close_(); if (!should_close) { Application::GetInstance().GetWindowSystem().CancelUserClose( impl_->window_); return; } } Application::GetInstance().RemoveWindow(this); } void Window::SetNeedsLayout() { impl_->needs_layout_ = true; } void Window::PostRedraw() { // Windows cannot actually post an expose event, and the actual mechanism // requires that PostNativeExposeEvent() not be called while drawing // (see the implementation for details). if (impl_->is_drawing_) { impl_->needs_redraw_ = true; } else { Application::GetInstance().GetWindowSystem().PostRedrawEvent( impl_->window_); } } void Window::RaiseToTop() const { Application::GetInstance().GetWindowSystem().RaiseWindowToTop( impl_->window_); } bool Window::IsActiveWindow() const { return Application::GetInstance().GetWindowSystem().IsActiveWindow( impl_->window_); } void Window::SetFocusWidget(Widget* w) { impl_->focus_widget_ = w; } void Window::AddChild(std::shared_ptr<Widget> w) { impl_->children_.push_back(w); impl_->needs_layout_ = true; } void Window::SetOnMenuItemActivated(Menu::ItemId item_id, std::function<void()> callback) { impl_->menu_callbacks_[item_id] = callback; } void Window::SetOnTickEvent(std::function<bool()> callback) { impl_->on_tick_event_ = callback; } void Window::SetOnClose(std::function<bool()> callback) { impl_->on_close_ = callback; } void Window::ShowDialog(std::shared_ptr<Dialog> dlg) { if (impl_->active_dialog_) { CloseDialog(); } impl_->active_dialog_ = dlg; dlg->OnWillShow(); auto deferred_layout = [this, dlg]() { auto context = GetLayoutContext(); auto content_rect = GetContentRect(); auto pref = dlg->CalcPreferredSize(context, Widget::Constraints()); int w = dlg->GetFrame().width; int h = dlg->GetFrame().height; if (w == 0) { w = pref.width; } if (h == 0) { h = pref.height; } w = std::min(w, int(std::round(0.8 * content_rect.width))); h = std::min(h, int(std::round(0.8 * content_rect.height))); dlg->SetFrame(gui::Rect((content_rect.width - w) / 2, (content_rect.height - h) / 2, w, h)); dlg->Layout(context); }; impl_->deferred_until_draw_.push(deferred_layout); } void Window::CloseDialog() { if (impl_->focus_widget_ == impl_->active_dialog_.get()) { SetFocusWidget(nullptr); } impl_->active_dialog_.reset(); // The dialog might not be closing from within a draw call, such as when // a native file dialog closes, so we need to post a redraw, just in case. // If it is from within a draw call, then any redraw request from that will // get merged in with this one by the OS. PostRedraw(); } void Window::ShowMessageBox(const char* title, const char* message) { auto em = GetTheme().font_size; auto margins = Margins(GetTheme().default_margin); auto dlg = std::make_shared<Dialog>(title); auto layout = std::make_shared<Vert>(em, margins); layout->AddChild(std::make_shared<Label>(message)); auto ok = std::make_shared<Button>("Ok"); ok->SetOnClicked([this]() { this->CloseDialog(); }); layout->AddChild(Horiz::MakeCentered(ok)); dlg->AddChild(layout); ShowDialog(dlg); } void Window::ShowMenu(bool show) { impl_->draw_menu_ = show; SetNeedsLayout(); } LayoutContext Window::GetLayoutContext() { return {GetTheme(), impl_->imgui_}; } void Window::Layout(const LayoutContext& context) { if (impl_->children_.size() == 1) { auto r = GetContentRect(); impl_->children_[0]->SetFrame(r); impl_->children_[0]->Layout(context); } else { for (auto& child : impl_->children_) { child->Layout(context); } } } void Window::OnMenuItemSelected(Menu::ItemId item_id) { auto callback = impl_->menu_callbacks_.find(item_id); if (callback != impl_->menu_callbacks_.end()) { callback->second(); PostRedraw(); // might not be in a draw if from native menu } } WindowSystem::OSWindow Window::GetOSWindow() const { return impl_->window_; } namespace { enum Mode { NORMAL, DIALOG, NO_INPUT }; Widget::DrawResult DrawChild(DrawContext& dc, const char* name, std::shared_ptr<Widget> child, Mode mode) { // Note: ImGUI's concept of a "window" is really a moveable child of the // OS window. We want a child to act like a child of the OS window, // like native UI toolkits, Qt, etc. So the top-level widgets of // a window are drawn using ImGui windows whose frame is specified // and which have no title bar, resizability, etc. ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse; // Q: When we want no input, why not use ImGui::BeginPopupModal(), // which takes care of blocking input for us, since a modal popup // is the most likely use case for wanting no input? // A: It animates an overlay, which would require us to constantly // redraw, otherwise it only animates when the mouse moves. But // we don't need constant animation for anything else, so that would // be a waste of CPU and battery (and really annoys people like me). if (mode == NO_INPUT) { flags |= ImGuiWindowFlags_NoInputs; } auto frame = child->GetFrame(); bool bg_color_not_default = !child->IsDefaultBackgroundColor(); auto is_3d = (std::dynamic_pointer_cast<SceneWidget>(child) != nullptr); if (!is_3d) { dc.uiOffsetX = frame.x; dc.uiOffsetY = frame.y; ImGui::SetNextWindowPos(ImVec2(float(frame.x), float(frame.y))); ImGui::SetNextWindowSize( ImVec2(float(frame.width), float(frame.height))); if (bg_color_not_default) { auto& bgColor = child->GetBackgroundColor(); ImGui::PushStyleColor(ImGuiCol_WindowBg, colorToImgui(bgColor)); } ImGui::Begin(name, nullptr, flags); } else { dc.uiOffsetX = 0; dc.uiOffsetY = 0; } Widget::DrawResult result; result = child->Draw(dc); if (!is_3d) { ImGui::End(); if (bg_color_not_default) { ImGui::PopStyleColor(); } } return result; } } // namespace Widget::DrawResult Window::DrawOnce(bool is_layout_pass) { // These are here to provide fast unique window names. (Hence using // char* instead of a std::string, just in case c_str() recreates // the buffer on some platform and unwittingly makes // ImGui::DrawChild(dc, name.c_str(), ...) slow. // If you find yourself needing more than a handful of top-level // children, you should probably be using a layout of some sort // (gui::Vert, gui::Horiz, gui::VGrid, etc. See Layout.h). static const std::vector<const char*> win_names = { "win1", "win2", "win3", "win4", "win5", "win6", "win7", "win8", "win9", "win10", "win11", "win12", "win13", "win14", "win15", "win16", "win17", "win18", "win19", "win20"}; bool needs_layout = false; bool needs_redraw = false; // ImGUI uses the dt parameter to calculate double-clicks, so it // needs to be reasonably accurate. double now = Application::GetInstance().Now(); double dt_sec = now - impl_->last_render_time_; impl_->last_render_time_ = now; // Run the deferred callbacks that need to happen outside a draw while (!impl_->deferred_until_before_draw_.empty()) { impl_->deferred_until_before_draw_.front()(); impl_->deferred_until_before_draw_.pop(); } // Set current context MakeDrawContextCurrent(); // make sure our ImGUI context is active ImGuiIO& io = ImGui::GetIO(); io.DeltaTime = float(dt_sec); // Set mouse information io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX); auto& ws = Application::GetInstance().GetWindowSystem(); if (IsActiveWindow()) { auto mouse_pos = ws.GetMousePosInWindow(impl_->window_); io.MousePos = ImVec2(float(mouse_pos.x), float(mouse_pos.y)); } auto buttons = ws.GetMouseButtons(impl_->window_); io.MouseDown[0] = (buttons & int(MouseButton::LEFT)); io.MouseDown[1] = (buttons & int(MouseButton::RIGHT)); io.MouseDown[2] = (buttons & int(MouseButton::MIDDLE)); // Set key information io.KeyShift = (impl_->mouse_mods_ & int(KeyModifier::SHIFT)); io.KeyAlt = (impl_->mouse_mods_ & int(KeyModifier::ALT)); io.KeyCtrl = (impl_->mouse_mods_ & int(KeyModifier::CTRL)); io.KeySuper = (impl_->mouse_mods_ & int(KeyModifier::META)); // Begin an ImGUI frame. We should NOT begin a filament frame here: // a) ImGUI always needs to "draw", because event processing happens // during draw for immediate mode GUIs, but if this is a layout // pass (as ImGUI can take up two draws to layout widgets and text) // we aren't actually going to render it. // b) Filament pumps events during a beginFrame(), which can cause // a key up event to process and erase the key down state from // the ImGuiIO structure before we get a chance to draw/process it. ImGui::NewFrame(); ImGui::PushFont( (ImFont*)impl_->imgui_.GetFont(Application::DEFAULT_FONT_ID)); // Run the deferred callbacks that need to happen inside a draw // In particular, text sizing with ImGUI seems to require being // in a frame, otherwise there isn't an GL texture info and we crash. while (!impl_->deferred_until_draw_.empty()) { impl_->deferred_until_draw_.front()(); impl_->deferred_until_draw_.pop(); } // Layout if necessary. This must happen within ImGui setup so that widgets // can query font information. auto& theme = impl_->theme_; if (impl_->needs_layout_) { Layout(GetLayoutContext()); impl_->needs_layout_ = false; } auto size = GetSize(); int em = theme.font_size; // em = font size in digital type (see Wikipedia) DrawContext dc{theme, *impl_->renderer_, impl_->imgui_, 0, 0, size.width, size.height, em, float(dt_sec)}; // Draw all the widgets. These will get recorded by ImGui. size_t win_idx = 0; Mode draw_mode = (impl_->active_dialog_ ? NO_INPUT : NORMAL); for (auto& child : this->impl_->children_) { if (!child->IsVisible()) { continue; } if (win_idx >= win_names.size()) { win_idx = win_names.size() - 1; utility::LogWarning( "Using too many top-level child widgets; use a layout " "instead."); } auto result = DrawChild(dc, win_names[win_idx++], child, draw_mode); if (result != Widget::DrawResult::NONE) { needs_redraw = true; } if (result == Widget::DrawResult::RELAYOUT) { needs_layout = true; } } // Draw menubar after the children so it is always on top (although it // shouldn't matter, as there shouldn't be anything under it) auto menubar = Application::GetInstance().GetMenubar(); if (menubar && impl_->draw_menu_) { auto id = menubar->DrawMenuBar(dc, !impl_->active_dialog_); if (id != Menu::NO_ITEM) { OnMenuItemSelected(id); needs_redraw = true; } } // Draw any active dialog if (impl_->active_dialog_) { ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, float(theme.dialog_border_width)); ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, float(theme.dialog_border_radius)); if (DrawChild(dc, "dialog", impl_->active_dialog_, DIALOG) != Widget::DrawResult::NONE) { needs_redraw = true; } ImGui::PopStyleVar(2); } // Finish frame and generate the commands ImGui::PopFont(); ImGui::EndFrame(); ImGui::Render(); // creates the draw data (i.e. Render()s to data) // Draw the ImGui commands impl_->imgui_.imgui_bridge->Update(ImGui::GetDrawData()); // Draw. Since ImGUI is an immediate mode gui, it does layout during // draw, and if we are drawing for layout purposes, don't actually // draw, because we are just going to draw again after this returns. if (!is_layout_pass) { impl_->renderer_->BeginFrame(); impl_->renderer_->Draw(); impl_->renderer_->EndFrame(); } if (needs_layout) { return Widget::DrawResult::RELAYOUT; } else if (needs_redraw) { return Widget::DrawResult::REDRAW; } else { return Widget::DrawResult::NONE; } } void Window::OnDraw() { impl_->is_drawing_ = true; bool needed_layout = impl_->needs_layout_; auto result = DrawOnce(needed_layout); if (result == Widget::DrawResult::RELAYOUT) { impl_->needs_layout_ = true; } // ImGUI can take two frames to do its layout, so if we did a layout // redraw a second time. This helps prevent a brief red flash when the // window first appears, as well as corrupted images if the // window initially appears underneath the mouse. if (needed_layout || impl_->needs_layout_) { DrawOnce(false); } impl_->is_drawing_ = false; if (impl_->needs_redraw_) { result = Widget::DrawResult::REDRAW; impl_->needs_redraw_ = false; } if (result == Widget::DrawResult::REDRAW) { // Can't just draw here, because Filament sometimes fences within // a draw, and then you can get two draws happening at the same // time, which ends up with a crash. PostRedraw(); } } void Window::OnResize() { impl_->needs_layout_ = true; Application::GetInstance().GetWindowSystem().ResizeRenderer( impl_->window_, impl_->renderer_); impl_->imgui_.imgui_bridge->OnWindowResized(*this); auto size = GetSize(); auto scaling = GetScaling(); auto old_context = MakeDrawContextCurrent(); ImGuiIO& io = ImGui::GetIO(); io.DisplaySize = ImVec2(float(size.width), float(size.height)); if (impl_->imgui_.scaling != scaling) { UpdateImGuiForScaling(1.0f / impl_->imgui_.scaling); // undo previous UpdateImGuiForScaling(scaling); impl_->imgui_.scaling = scaling; } io.DisplayFramebufferScale.x = 1.0f; io.DisplayFramebufferScale.y = 1.0f; if (impl_->wants_auto_size_ || impl_->wants_auto_center_) { auto& ws = Application::GetInstance().GetWindowSystem(); auto screen_size = ws.GetScreenSize(impl_->window_); int w = GetOSFrame().width; int h = GetOSFrame().height; if (impl_->wants_auto_size_) { ImGui::NewFrame(); ImGui::PushFont((ImFont*)impl_->imgui_.GetFont( Application::DEFAULT_FONT_ID)); auto pref = CalcPreferredSize(); ImGui::PopFont(); ImGui::EndFrame(); w = std::min(screen_size.width, int(std::round(pref.width / impl_->imgui_.scaling))); // screen_height is the screen height, not the usable screen height. // If we cannot call glfwGetMonitorWorkarea(), then we need to guess // at the size. The window titlebar is about 2 * em, and then there // is often a global menubar (Linux/GNOME, macOS) or a toolbar // (Windows). A toolbar is somewhere around 2 - 3 ems. int unusable_height = 4 * impl_->theme_.font_size; h = std::min(screen_size.height - unusable_height, int(std::round(pref.height / impl_->imgui_.scaling))); ws.SetWindowSize(impl_->window_, w, h); } if (impl_->wants_auto_center_) { int x = (screen_size.width - w) / 2; int y = (screen_size.height - h) / 2; ws.SetWindowPos(impl_->window_, x, y); } impl_->wants_auto_size_ = false; impl_->wants_auto_center_ = false; OnResize(); } // Resizing looks bad if drawing takes a long time, so turn off MSAA // while we resize. On macOS this is critical, because the GL driver does // not release the memory for all the buffers of the new sizes right away // so it eats up GBs of memory rapidly and then resizing looks awful and // eventually stops working correctly. Unfortunately, there isn't a good // way to tell when we've stopped resizing, so we use the mouse movement. // (We get no mouse events while resizing, so any mouse even must mean we // are no longer resizing.) if (!impl_->is_resizing_) { impl_->is_resizing_ = true; ChangeAllRenderQuality(SceneWidget::Quality::FAST, impl_->children_); } RestoreDrawContext(old_context); PostRedraw(); } void Window::OnMouseEvent(const MouseEvent& e) { MakeDrawContextCurrent(); // We don't have a good way of determining when resizing ends; the most // likely action after resizing a window is to move the mouse. if (impl_->is_resizing_) { impl_->is_resizing_ = false; ChangeAllRenderQuality(SceneWidget::Quality::BEST, impl_->children_); } impl_->mouse_mods_ = e.modifiers; switch (e.type) { case MouseEvent::MOVE: case MouseEvent::BUTTON_DOWN: case MouseEvent::DRAG: case MouseEvent::BUTTON_UP: break; case MouseEvent::WHEEL: { ImGuiIO& io = ImGui::GetIO(); float dx = 0.0, dy = 0.0; if (e.wheel.dx != 0) { dx = e.wheel.dx / std::abs(e.wheel.dx); // get sign } if (e.wheel.dy != 0) { dy = e.wheel.dy / std::abs(e.wheel.dy); // get sign } // Note: ImGUI's documentation says that 1 unit of wheel movement // is about 5 lines of text scrolling. if (e.wheel.isTrackpad) { io.MouseWheelH += dx * 0.25f; io.MouseWheel += dy * 0.25f; } else { io.MouseWheelH += dx; io.MouseWheel += dy; } break; } } if (impl_->mouse_grabber_widget_) { impl_->mouse_grabber_widget_->Mouse(e); if (e.type == MouseEvent::BUTTON_UP) { impl_->mouse_grabber_widget_ = nullptr; } PostRedraw(); return; } // Some ImGUI widgets have popup windows, in particular, the color // picker, which creates a popup window when you click on the color // patch. Since these aren't gui::Widgets, we don't know about them, // and will deliver mouse events to something below them. So find any // that would use the mouse, and if it isn't a toplevel child, then // eat the event for it. if (e.type == MouseEvent::BUTTON_DOWN || e.type == MouseEvent::BUTTON_UP) { ImGuiContext* context = ImGui::GetCurrentContext(); for (auto* w : context->Windows) { if (!w->Hidden && w->Flags & ImGuiWindowFlags_Popup) { Rect r(int(w->Pos.x), int(w->Pos.y), int(w->Size.x), int(w->Size.y)); if (r.Contains(e.x, e.y)) { bool weKnowThis = false; for (auto child : impl_->children_) { if (child->GetFrame() == r) { weKnowThis = true; break; } } if (!weKnowThis) { // This is not a rect that is one of our children, // must be an ImGUI internal popup. Eat event. PostRedraw(); return; } } } } } // Iterate backwards so that we send mouse events from the top down. auto HandleMouseForChild = [this](const MouseEvent& e, std::shared_ptr<Widget> child) -> bool { if (child->GetFrame().Contains(e.x, e.y) && child->IsVisible()) { if (e.type == MouseEvent::BUTTON_DOWN) { SetFocusWidget(child.get()); } auto result = child->Mouse(e); if (e.type == MouseEvent::BUTTON_DOWN) { if (result == Widget::EventResult::CONSUMED) { impl_->mouse_grabber_widget_ = child.get(); } } else if (e.type == MouseEvent::BUTTON_UP) { impl_->mouse_grabber_widget_ = nullptr; } return true; } return false; }; if (impl_->active_dialog_) { HandleMouseForChild(e, impl_->active_dialog_); } else { // Mouse move and wheel always get delivered. // Button up and down get delivered if they weren't in an ImGUI popup. // Drag should only be delivered if the grabber widget exists; // if it is null, then the mouse is being dragged over an ImGUI popup. if (e.type != MouseEvent::DRAG || impl_->mouse_grabber_widget_) { std::vector<std::shared_ptr<Widget>>& children = impl_->children_; for (auto it = children.rbegin(); it != children.rend(); ++it) { if (HandleMouseForChild(e, *it)) { break; } } } } PostRedraw(); } void Window::OnKeyEvent(const KeyEvent& e) { auto this_mod = 0; if (e.key == KEY_LSHIFT || e.key == KEY_RSHIFT) { this_mod = int(KeyModifier::SHIFT); } else if (e.key == KEY_LCTRL || e.key == KEY_RCTRL) { this_mod = int(KeyModifier::CTRL); } else if (e.key == KEY_ALT) { this_mod = int(KeyModifier::ALT); } else if (e.key == KEY_META) { this_mod = int(KeyModifier::META); } else if (e.key == KEY_ESCAPE) { Close(); } if (e.type == KeyEvent::UP) { impl_->mouse_mods_ &= ~this_mod; } else { impl_->mouse_mods_ |= this_mod; } auto old_context = MakeDrawContextCurrent(); ImGuiIO& io = ImGui::GetIO(); if (e.key < IM_ARRAYSIZE(io.KeysDown)) { io.KeysDown[e.key] = (e.type == KeyEvent::DOWN); } // If an ImGUI widget is not getting keystrokes, we can send them to // non-ImGUI widgets if (ImGui::GetCurrentContext()->ActiveId == 0 && impl_->focus_widget_) { impl_->focus_widget_->Key(e); } RestoreDrawContext(old_context); PostRedraw(); } void Window::OnTextInput(const TextInputEvent& e) { auto old_context = MakeDrawContextCurrent(); ImGuiIO& io = ImGui::GetIO(); io.AddInputCharactersUTF8(e.utf8); RestoreDrawContext(old_context); PostRedraw(); } void Window::OnTickEvent(const TickEvent& e) { auto old_context = MakeDrawContextCurrent(); bool redraw = false; if (impl_->on_tick_event_) { redraw = impl_->on_tick_event_(); } for (auto child : impl_->children_) { if (child->Tick(e) == Widget::DrawResult::REDRAW) { redraw = true; } } RestoreDrawContext(old_context); if (redraw) { PostRedraw(); } } void Window::OnDragDropped(const char* path) {} } // namespace gui } // namespace visualization } // namespace open3d
[ "noreply@github.com" ]
noreply@github.com
0dccd583d4d7bf0c5fdaed17b3185f37c1d75a0b
971b000b9e6c4bf91d28f3723923a678520f5bcf
/doc/qxsl-fo.0.0.1/src/viewitems/fotable/fotabledoc.cpp
1650f4d5be6d721603c7f219dd180cdfdb42bb9d
[]
no_license
google-code-export/fop-miniscribus
14ce53d21893ce1821386a94d42485ee0465121f
966a9ca7097268c18e690aa0ea4b24b308475af9
refs/heads/master
2020-12-24T17:08:51.551987
2011-09-02T07:55:05
2011-09-02T07:55:05
32,133,292
2
0
null
null
null
null
UTF-8
C++
false
false
3,053
cpp
//http://www.zvon.org/xxl/xslfoReference/Output/index.html /* | source-document | role | azimuth | cue-after | cue-before | elevation | pause-after | pause-before | pitch | pitch-range | play-during | richness | speak | speak-header | speak-numeral | speak-punctuation | speech-rate | stress | voice-family | volume | background-attachment | background-color | background-image | background-repeat | background-position-horizontal | background-position-vertical | border-before-color | border-before-style | border-before-width | border-after-color | border-after-style | border-after-width | border-start-color | border-start-style | border-start-width | border-end-color | border-end-style | border-end-width | border-top-color | border-top-style | border-top-width | border-bottom-color | border-bottom-style | border-bottom-width | border-left-color | border-left-style | border-left-width | border-right-color | border-right-style | border-right-width | padding-before | padding-after | padding-start | padding-end | padding-top | padding-bottom | padding-left | padding-right | margin-top | margin-bottom | margin-left | margin-right | space-before | space-after | start-indent | end-indent | relative-position | block-progression-dimension | border-after-precedence | border-before-precedence | border-collapse | border-end-precedence | border-separation | border-start-precedence | break-after | break-before | id | inline-progression-dimension | intrusion-displace | height | keep-together | keep-with-next | keep-with-previous | table-layout | table-omit-footer-at-break | table-omit-header-at-break | width | writing-mode | */ //own include #include "fotabledoc.h" //qt includes #include <QDomElement> //project inceludes #include "objectfodoc.h" #include "fotablebodydoc.h" #include "fotablerowdoc.h" FoTableDoc::FoTableDoc(QDomElement pElement,ObjectFoContainerDoc *parentContainer) : ObjectFoContainerSimpleDoc(ObjectFoDoc::typeFoTable,parentContainer,pElement) { loadTableBody(pElement); //get new position for our block setPositionValue(parentContainer->positionForNewChildFoObject()); // addAttribute(new AttributeFo(AttributeFo::font_size,NULL)); // addAttribute(new AttributeFo(AttributeFo::font_family,NULL)); } FoTableDoc::~FoTableDoc() { } void FoTableDoc::loadTableBody(QDomElement pElement) { for(QDomNode n = pElement.firstChild();!n.isNull(); n = n.nextSibling()) { QDomElement e = n.toElement(); // try to convert the node to an element. if(!e.isNull()) { if (e.tagName()=="fo:table-body") { m_pFoTableBodyDoc=new FoTableBodyDoc(e,this); } } } } FoSize FoTableDoc::widthValue() { return m_pParentContainer->widthValue(); } FoTableRowDoc *FoTableDoc::row(int i) { return m_pFoTableBodyDoc->row(i); } FoTableRowDoc* FoTableDoc::appendRow() { //create rowdoc in tabledoc and return it return m_pFoTableBodyDoc->appendRow(); } void FoTableDoc::appendColumn() { m_pFoTableBodyDoc->appendColumn(); } FoSize FoTableDoc::height() { return ObjectFoDoc::height(); }
[ "ppkciz@9af58faf-7e3e-0410-b956-55d145112073" ]
ppkciz@9af58faf-7e3e-0410-b956-55d145112073
0d8ed740d2bdde483b9d3352003930c571dd23c3
323fac9e077ad960f8be0c09b3b5ff5eedfc73d3
/branches/lib/libjson/Source/JSON_Base64.h
6b71db741e79f74957cae684bd4493345a13dbb2
[ "BSD-2-Clause" ]
permissive
yellowbigbird/bird-self-lib
226f08a1d5a0c7cde994fe14c2a47f5ac443ba3e
04dae41aa62609028d61f13490b2562ae1479134
refs/heads/master
2021-06-13T15:49:35.125938
2017-08-03T07:18:06
2017-08-03T07:18:06
39,172,862
1
2
null
null
null
null
UTF-8
C++
false
false
459
h
#ifndef JSON_BASE64_H #define JSON_BASE64_H #include "JSONDebug.h" #if defined(JSON_BINARY) || defined(JSON_EXPOSE_BASE64) //if this is not needed, don't waste space compiling it #include <string> class JSONBase64 { public: static json_string json_encode64(const unsigned char * binary, size_t bytes) json_nothrow json_cold; static std::string json_decode64(const json_string & encoded) json_nothrow json_cold; }; #endif #endif
[ "yellowbigbird@gmail.com" ]
yellowbigbird@gmail.com
d50a985a4b6d3f56abdd77efe8207932d97f8914
82d3bf9721fe5e6b8cd6fa1fe2c40a5c3358daa5
/MQTTUnsubscribeServer.cpp
63cd25bb32d6797527fd9cff1513e5588d770800
[]
no_license
gochaudhari/MQTTLinuxProject
9aa617f238dc8c19a89fc4c10d87b1ab89d6cb1f
ebb635a405b677c97f2100c89898a95a8cfa5dbb
refs/heads/master
2021-01-20T20:18:36.387409
2016-08-09T06:34:58
2016-08-09T06:34:58
65,033,495
0
0
null
null
null
null
UTF-8
C++
false
false
3,059
cpp
/******************************************************************************* * Copyright (c) 2014 IBM Corp. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Eclipse Distribution License v1.0 which accompany this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Ian Craggs - initial API and implementation and/or initial documentation *******************************************************************************/ #include "MQTTPacket.hpp" #include "StackTrace.hpp" #include <string.h> /** * Deserializes the supplied (wire) buffer into unsubscribe data * @param dup integer returned - the MQTT dup flag * @param packetid integer returned - the MQTT packet identifier * @param maxcount - the maximum number of members allowed in the topicFilters and requestedQoSs arrays * @param count - number of members in the topicFilters and requestedQoSs arrays * @param topicFilters - array of topic filter names * @param buf the raw buffer data, of the correct length determined by the remaining length field * @param buflen the length in bytes of the data in the supplied buffer * @return the length of the serialized data. <= 0 indicates error */ int MQTTDeserialize_unsubscribe(unsigned char* dup, unsigned short* packetid, int maxcount, int* count, MQTTString topicFilters[], unsigned char* buf, int len) { MQTTHeader header = {0}; unsigned char* curdata = buf; unsigned char* enddata = NULL; int rc = 0; int mylen = 0; FUNC_ENTRY; header.byte = readChar(&curdata); if (header.bits.type != UNSUBSCRIBE) goto exit; *dup = header.bits.dup; curdata += (rc = MQTTPacket_decodeBuf(curdata, &mylen)); /* read remaining length */ enddata = curdata + mylen; *packetid = readInt(&curdata); *count = 0; while (curdata < enddata) { if (!readMQTTLenString(&topicFilters[*count], &curdata, enddata)) goto exit; (*count)++; } rc = 1; exit: FUNC_EXIT_RC(rc); return rc; } /** * Serializes the supplied unsuback data into the supplied buffer, ready for sending * @param buf the buffer into which the packet will be serialized * @param buflen the length in bytes of the supplied buffer * @param packetid integer - the MQTT packet identifier * @return the length of the serialized data. <= 0 indicates error */ int MQTTSerialize_unsuback(unsigned char* buf, int buflen, unsigned short packetid) { MQTTHeader header = {0}; int rc = 0; unsigned char *ptr = buf; FUNC_ENTRY; if (buflen < 2) { rc = MQTTPACKET_BUFFER_TOO_SHORT; goto exit; } header.byte = 0; header.bits.type = UNSUBACK; writeChar(&ptr, header.byte); /* write header */ ptr += MQTTPacket_encode(ptr, 2); /* write remaining length */ writeInt(&ptr, packetid); rc = ptr - buf; exit: FUNC_EXIT_RC(rc); return rc; }
[ "gochaudhari@gmail.com" ]
gochaudhari@gmail.com
8c7621665fbfc646326835b33cfab05de3a45c28
8652a66d3994098ef4cf9186cd36171eb3833ad3
/WINCE600/PLATFORM/COMMON/SRC/SOC/COMMON_FSL_V2_PDK1_7/HSI2C/PDK/hsi2c_io.cpp
2b8718846efad33f47546991e20b34937c9a68e7
[]
no_license
KunYi/em-works
789e038ecaf4d0ec264d16fdd47df00b841de60c
3b70b2690782acfcba7f4b0e43e05b5b070ed0da
refs/heads/master
2016-09-06T03:47:56.913454
2013-11-05T03:28:15
2013-11-05T03:28:15
32,260,142
1
0
null
null
null
null
UTF-8
C++
false
false
31,936
cpp
// // Copyright (c) Microsoft Corporation. All rights reserved. // // Use of this source code is subject to the terms of the Microsoft end-user // license agreement (EULA) under which you licensed this SOFTWARE PRODUCT. // If you did not accept the terms of the EULA, you are not authorized to use // this source code. For a copy of the EULA, please see the LICENSE.RTF on your // install media. // //------------------------------------------------------------------------------ // // Copyright (C) 2004-2008, Freescale Semiconductor, Inc. All Rights Reserved. // THIS SOURCE CODE, AND ITS USE AND DISTRIBUTION, IS SUBJECT TO THE TERMS // AND CONDITIONS OF THE APPLICABLE LICENSE AGREEMENT // //------------------------------------------------------------------------------ // // File: HSI2C_IO.cpp // // This module provides a stream interface for the HSI2C bus // driver. Client drivers can use the stream interface to // configure and exchange data with the HSI2C peripheral. // //------------------------------------------------------------------------------ #pragma warning(push) #pragma warning(disable: 4115 4201 4204 4214) #include <windows.h> #include <Devload.h> #include <windev.h> #include <ceddk.h> #pragma warning(pop) #include "common_ddk.h" #include "common_hsi2c.h" #include "hsi2cbus.h" #include "hsi2cclass.h" #pragma warning(push) #pragma warning(disable: 4512) #include "marshal.hpp" //helper classes to marshal/alloc embedded/async buffer #pragma warning(pop) //------------------------------------------------------------------------------ // External Functions //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // External Variables //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Defines //------------------------------------------------------------------------------ #define REG_DEVINDEX_VAL_NAME L"Index" #define HSI2C_DEVINDEX_MAX_VAL 1 #define HSI2C_DEVINDEX_MIN_VAL 1 #define HSI2C_DEVINDEX_DEFAULT_VAL 1 #ifdef DEBUG DBGPARAM dpCurSettings = { TEXT("HSI2C"), { TEXT("Init"),TEXT("Deinit"),TEXT("Open"),TEXT("Close"), TEXT("IOCtl"),TEXT("Thread"),TEXT(""),TEXT(""), TEXT(""),TEXT(""),TEXT(""),TEXT(""), TEXT(""),TEXT("Function"),TEXT("Warning"),TEXT("Error") }, (ZONEMASK_WARN | ZONEMASK_ERROR) }; #endif // DEBUG //------------------------------------------------------------------------------ // Types //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Global Variables //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Local Variables //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Local Functions //------------------------------------------------------------------------------ //----------------------------------------------------------------------------- // // Function: HIC_Init // // The Device Manager calls this function as a result of a call to the // ActivateDevice() function. // // Parameters: // pContext // [in] Pointer to a string containing the registry path to the // active key for the stream interface driver. // // Returns: // Returns a handle to the device context created if successful. Returns // zero if not successful. // //----------------------------------------------------------------------------- DWORD HIC_Init(LPCTSTR pContext) { UINT32 error; HKEY hKey; DWORD dwIndex, dwSize; DEBUGMSG (ZONE_INIT|ZONE_FUNCTION, (TEXT("HSI2C_Init +\r\n"))); // try to open active device registry key for this context hKey = OpenDeviceKey(pContext); if (hKey == NULL) { DEBUGMSG(ZONE_ERROR, (TEXT("HSI2C_Init: OpenDeviceKey failed!!!\r\n"))); return 0; } // try to load HSI2C index from registry data dwSize = sizeof(DWORD); error = RegQueryValueEx( hKey, // handle to currently open key REG_DEVINDEX_VAL_NAME, // string containing value to query NULL, // reserved, set to NULL NULL, // type not required, set to NULL (LPBYTE)(&dwIndex), // pointer to buffer receiving value &dwSize); // pointer to buffer size // close handle to open key RegCloseKey(hKey); // check for errors during RegQueryValueEx if (error != ERROR_SUCCESS) { DEBUGMSG(ZONE_ERROR, (TEXT("HSI2C_Init: RegQueryValueEx failed!!!\r\n"))); return 0; } // Construct the HSI2C Module Class HSI2CClass* pHSI2C = new HSI2CClass(dwIndex); // Managed to create the class? if (pHSI2C == NULL) { return NULL; } PREFAST_SUPPRESS(28197, "HSI2C class own this slave buffer handle, allocate outside the class so that customize this buffer size"); HSI2CSLAVEBUF *pSlave = new HSI2CSLAVEBUF; if (pSlave == NULL) { delete pHSI2C; return NULL; } pSlave->iBufSize=1; pSlave->byBuf[0]=(BYTE)0; pHSI2C->SetSlaveBuf(pSlave); // If class construction not successful? if (pHSI2C->IsLastActionOK() != TRUE) { // Dispose the instance DEBUGMSG (ZONE_INIT|ZONE_ERROR, (TEXT("HSI2C_Init: I2C Class Failed! Err=%d\r\n"), pHSI2C->GetLastResult())); delete pHSI2C; return NULL; } DEBUGMSG (ZONE_INIT|ZONE_FUNCTION, (TEXT("HSI2C_Init - hDev=0x%x\r\n"), pHSI2C)); // Otherwise return the created instance return (DWORD) pHSI2C; } //----------------------------------------------------------------------------- // // Function: HIC_Deinit // // This function uninitializes a device. // // Parameters: // hDeviceContext // [in] Handle to the device context. // // Returns: // TRUE indicates success. FALSE indicates failure. // //----------------------------------------------------------------------------- BOOL HIC_Deinit(DWORD hDeviceContext) { HSI2CClass * pHSI2C = (HSI2CClass*) hDeviceContext; DEBUGMSG (ZONE_DEINIT|ZONE_FUNCTION, (TEXT("HSI2C_Deinit +DeviceContext=0x%x\r\n"),hDeviceContext)); if (pHSI2C != NULL) { delete pHSI2C; } DEBUGMSG (ZONE_DEINIT|ZONE_FUNCTION, (TEXT("HSI2C_Deinit -\r\n"))); return TRUE; } //----------------------------------------------------------------------------- // // Function: HIC_Open // // This function opens a device for reading, writing, or both. // // Parameters: // hDeviceContext // [in] Handle to the device context. The XXX_Init function creates // and returns this handle. // AccessCode // [in] Access code for the device. The access is a combination of // read and write access from CreateFile. // ShareMode // [in] File share mode of the device. The share mode is a // combination of read and write access sharing from CreateFile. // // Returns: // This function returns a handle that identifies the open context of // the device to the calling application. // //----------------------------------------------------------------------------- DWORD HIC_Open(DWORD hDeviceContext, DWORD AccessCode, DWORD ShareMode) { DEBUGMSG (ZONE_OPEN|ZONE_FUNCTION, (TEXT("HSI2C_Open +hDeviceContext=0x%x\r\n"),hDeviceContext)); // Remove-W4: Warning C4100 workaround UNREFERENCED_PARAMETER(AccessCode); UNREFERENCED_PARAMETER(ShareMode); DEBUGMSG (ZONE_OPEN|ZONE_FUNCTION, (TEXT("HSI2C_Open -\r\n"))); // Open is meaningless! return hDeviceContext; } //----------------------------------------------------------------------------- // // Function: HIC_Close // // This function opens a device for reading, writing, or both. // // Parameters: // hOpenContext // [in] Handle returned by the XXX_Open function, used to identify // the open context of the device. // // Returns: // TRUE indicates success. FALSE indicates failure. // //----------------------------------------------------------------------------- BOOL HIC_Close(DWORD hOpenContext) { DEBUGMSG (ZONE_CLOSE|ZONE_FUNCTION, (TEXT("HSI2C_Close +\r\n"))); // Remove-W4: Warning C4100 workaround UNREFERENCED_PARAMETER(hOpenContext); DEBUGMSG (ZONE_CLOSE|ZONE_FUNCTION, (TEXT("HSI2C_Close -\r\n"))); // Close is meaningless! return TRUE; } //----------------------------------------------------------------------------- // // Function: HIC_PowerDown // // This function suspends power to the device. It is useful only with // devices that can power down under software control. // // Parameters: // hDeviceContext // [in] Handle to the device context. // // Returns: // None. // //----------------------------------------------------------------------------- void HIC_PowerDown(DWORD hDeviceContext) { // Remove-W4: Warning C4100 workaround UNREFERENCED_PARAMETER(hDeviceContext); // Not implemented! } //----------------------------------------------------------------------------- // // Function: HIC_PowerUp // // This function restores power to a device. // // Parameters: // hDeviceContext // [in] Handle to the device context. // // Returns: // None. // //----------------------------------------------------------------------------- void HIC_PowerUp(void) { // Not implemented! } //----------------------------------------------------------------------------- // // Function: HIC_Read // // This function reads data from the device identified by the open // context. // // Parameters: // hOpenContext // [in] Handle to the open context of the device. The XXX_Open // function creates and returns this identifier. // pBuffer // [out] Pointer to the buffer that stores the data read from the // device. This buffer should be at least Count bytes long. // Count // [in] Number of bytes to read from the device into pBuffer. // // Returns: // Returns zero to indicate end-of-file. Returns -1 to indicate an // error. Returns the number of bytes read to indicate success. // //----------------------------------------------------------------------------- DWORD HIC_Read(DWORD hOpenContext, LPVOID pBuffer, DWORD Count) { // Remove-W4: Warning C4100 workaround UNREFERENCED_PARAMETER(hOpenContext); UNREFERENCED_PARAMETER(pBuffer); UNREFERENCED_PARAMETER(Count); // Nothing to read return 0; } //----------------------------------------------------------------------------- // // Function: HIC_Write // // This function writes data to the device. // // Parameters: // hOpenContext // [in] Handle to the open context of the device. The XXX_Open // function creates and returns this identifier. // pBuffer // [out] Pointer to the buffer that contains the data to write. // Count // [in] Number of bytes to read from the device into pBuffer. // // Returns: // The number of bytes written indicates success. A value of -1 indicates // failure. // //----------------------------------------------------------------------------- DWORD HIC_Write(DWORD Handle, LPCVOID pBuffer, DWORD dwNumBytes) { // Remove-W4: Warning C4100 workaround UNREFERENCED_PARAMETER(Handle); UNREFERENCED_PARAMETER(pBuffer); UNREFERENCED_PARAMETER(dwNumBytes); // Nothing to write return 0; } //----------------------------------------------------------------------------- // // Function: HIC_Seek // // This function moves the data pointer in the device. // // Parameters: // hOpenContext // [in] Handle to the open context of the device. The XXX_Open // function creates and returns this identifier. // Amount // [in] Number of bytes to move the data pointer in the device. // A positive value moves the data pointer toward the end of the // file, and a negative value moves it toward the beginning. // Type // [in] Starting point for the data pointer. // // Returns: // The new data pointer for the device indicates success. A value of -1 // indicates failure. // //----------------------------------------------------------------------------- DWORD HIC_Seek(DWORD hOpenContext, long Amount, WORD Type) { // Remove-W4: Warning C4100 workaround UNREFERENCED_PARAMETER(hOpenContext); UNREFERENCED_PARAMETER(Amount); UNREFERENCED_PARAMETER(Type); // Seeking is meaningless! return (DWORD)-1; } //----------------------------------------------------------------------------- // // Function: HIC_IOControl // // This function sends a command to a device. // // Parameters: // hOpenContext // [in] Handle to the open context of the device. The XXX_Open // function creates and returns this identifier. // dwCode // [in] I/O control operation to perform. These codes are // device-specific and are usually exposed to developers through // a header file. // pBufIn // [in] Pointer to the buffer containing data to transfer to the // device. // dwLenIn // [in] Number of bytes of data in the buffer specified for pBufIn. // // pBufOut // [out] Pointer to the buffer used to transfer the output data // from the device. // dwLenOut // [in] Maximum number of bytes in the buffer specified by pBufOut. // // pdwActualOut // [out] Pointer to the DWORD buffer that this function uses to // return the actual number of bytes received from the device. // // Returns: // The new data pointer for the device indicates success. A value of -1 // indicates failure. // //----------------------------------------------------------------------------- BOOL HIC_IOControl(DWORD hOpenContext, DWORD dwCode, PBYTE pBufIn, DWORD dwLenIn, PBYTE pBufOut, DWORD dwLenOut, PDWORD pdwActualOut) { BOOL bRet = FALSE; // hOpenContext is a pointer to HSI2CClass instance! HSI2CClass* pHSI2C = (HSI2CClass*) hOpenContext; DEBUGMSG (ZONE_IOCTL|ZONE_FUNCTION, (TEXT("HSI2C_IOControl: +hOpenContext=0x%x\r\n"),hOpenContext)); if (pHSI2C != NULL) { switch (dwCode) { case HSI2C_IOCTL_SET_SLAVE_MODE: { DEBUGMSG (ZONE_IOCTL|ZONE_FUNCTION, (TEXT("HSI2C_IOControl:SET_SLAVE_MODE +\r\n"))); //Set slave mode from IOCTL is obsolete feature, //use enable slave instead. //Keep the definition here for back compatible purpose. //pHSI2C->SetMode(I2C_SLAVE_MODE); bRet = FALSE; DEBUGMSG (ZONE_IOCTL|ZONE_FUNCTION, (TEXT("HSI2C_IOControl:SET_SLAVE_MODE -\r\n"))); break; } case HSI2C_IOCTL_SET_MASTER_MODE: { DEBUGMSG (ZONE_IOCTL|ZONE_FUNCTION, (TEXT("HSI2C_IOControl:SET_MASTER_MODE +\r\n"))); pHSI2C->SetMode(HSI2C_MASTER_MODE); bRet = TRUE; DEBUGMSG (ZONE_IOCTL|ZONE_FUNCTION, (TEXT("HSI2C_IOControl:SET_MASTER_MODE +\r\n"))); break; } case HSI2C_IOCTL_IS_MASTER: { if (dwLenOut != sizeof(BOOL)) return FALSE; if( (NULL == pBufOut) ) { return FALSE; } DEBUGMSG (ZONE_IOCTL|ZONE_FUNCTION, (TEXT("HSI2C_IOControl:IS_MASTER +\r\n"))); PBOOL pbIsMaster = (PBOOL) pBufOut; if (pHSI2C->GetMode() == HSI2C_MASTER_MODE) *pbIsMaster = TRUE; else *pbIsMaster = FALSE; bRet = TRUE; DEBUGMSG (ZONE_IOCTL|ZONE_FUNCTION, (TEXT("HSI2C_IOControl:IS_MASTER - Val=0x%x\r\n"), *pbIsMaster)); break; } case HSI2C_IOCTL_IS_SLAVE: { if (dwLenOut != sizeof(BOOL)) return FALSE; if( (NULL == pBufOut) ) { return FALSE; } DEBUGMSG (ZONE_IOCTL|ZONE_FUNCTION, (TEXT("HSI2C_IOControl:IS_SLAVE +\r\n"))); PBOOL pbIsSlave = (PBOOL) pBufOut; if (pHSI2C->GetMode() == HSI2C_SLAVE_MODE) *pbIsSlave = TRUE; else *pbIsSlave = FALSE; bRet = TRUE; DEBUGMSG (ZONE_IOCTL|ZONE_FUNCTION, (TEXT("HSI2C_IOControl:IS_SLAVE - Val=0x%x\r\n"), *pbIsSlave)); break; } case HSI2C_IOCTL_GET_CLOCK_RATE: { if (dwLenOut != sizeof(WORD)) return FALSE; if( (NULL == pBufOut) ) { return FALSE; } DEBUGMSG (ZONE_IOCTL|ZONE_FUNCTION, (TEXT("HSI2C_IOControl:GET_CLOCK_RATE +\r\n"))); PWORD pwClkRate = (PWORD) pBufOut; *pwClkRate = pHSI2C->GetClockRateDivider(); bRet = TRUE; DEBUGMSG (ZONE_IOCTL|ZONE_FUNCTION, (TEXT("HSI2C_IOControl:GET_CLOCK_RATE - Val=0x%x\r\n"), *pwClkRate)); break; } case HSI2C_IOCTL_SET_CLOCK_RATE: { if (dwLenIn != sizeof(WORD)) return FALSE; if( (NULL == pBufIn) ) { return FALSE; } PWORD pwClkRate = (PWORD) pBufIn; DEBUGMSG (ZONE_IOCTL|ZONE_FUNCTION, (TEXT("HSI2C_IOControl:SET_CLOCK_RATE + ValIn=0x%x\r\n"), *pwClkRate)); pHSI2C->SetClockRateDivider(*pwClkRate); bRet = TRUE; break; } case HSI2C_IOCTL_SET_FREQUENCY: { if (dwLenIn != sizeof(DWORD)) return FALSE; if( (NULL == pBufIn) ) { return FALSE; } PDWORD pdwFrequency = (PDWORD) pBufIn; DWORD dwFreq = *pdwFrequency; DEBUGMSG (ZONE_IOCTL|ZONE_FUNCTION, (TEXT("HSI2C_IOControl:SET_FREQUENCY + ValIn=0x%x\r\n"), dwFreq)); if (*pdwFrequency > HSI2C_MAX_FREQUENCY) { RETAILMSG (1, (TEXT("HSI2C_IOControl: I2C frequency may not exceed %d...setting to %d\r\n"), HSI2C_MAX_FREQUENCY, HSI2C_MAX_FREQUENCY)); dwFreq = HSI2C_MAX_FREQUENCY; bRet = FALSE; } WORD wClkRate = pHSI2C->CalculateClkRateDiv(dwFreq); pHSI2C->SetClockRateDivider(wClkRate); bRet = TRUE; break; } case HSI2C_IOCTL_SET_SELF_ADDR: { if (dwLenIn != sizeof(BYTE)) return FALSE; if( (NULL == pBufIn) ) { return FALSE; } PBYTE pbySelfAddr = (PBYTE) pBufIn; DEBUGMSG (ZONE_IOCTL|ZONE_FUNCTION, (TEXT("HSI2C_IOControl:SET_SELF_ADDR + ValIn=0x%x\r\n"), *pbySelfAddr)); pHSI2C->SetSelfAddress(*pbySelfAddr); bRet = TRUE; break; } case HSI2C_IOCTL_GET_SELF_ADDR: { if (dwLenOut != sizeof(BYTE)) return FALSE; if( (dwLenOut > 0) && (NULL == pBufOut) ) { return FALSE; } DEBUGMSG (ZONE_IOCTL|ZONE_FUNCTION, (TEXT("HSI2C_IOControl:GET_SELF_ADDR +\r\n"))); PBYTE pbySelfAddr = (PBYTE) pBufOut; *pbySelfAddr = pHSI2C->GetSelfAddress(); bRet = TRUE; DEBUGMSG (ZONE_IOCTL|ZONE_FUNCTION, (TEXT("HSI2C_IOControl:GET_SELF_ADDR - Val=0x%x\r\n"), *pbySelfAddr)); break; } case HSI2C_IOCTL_TRANSFER: { #define MARSHAL 1 #if MARSHAL DuplicatedBuffer_t Marshalled_pInBuf(pBufIn, dwLenIn, ARG_I_PTR); pBufIn = reinterpret_cast<PBYTE>( Marshalled_pInBuf.ptr() ); if( (dwLenIn > 0) && (NULL == pBufIn) ) { return FALSE; } #endif HSI2C_TRANSFER_BLOCK *pXferBlock = (HSI2C_TRANSFER_BLOCK *) pBufIn; if (pXferBlock->iNumPackets<=0) { return FALSE; } #if MARSHAL MarshalledBuffer_t Marshalled_pPackets(pXferBlock->pHSI2CPackets, pXferBlock->iNumPackets*sizeof(HSI2C_PACKET), ARG_I_PTR); HSI2C_PACKET *pPackets = reinterpret_cast<HSI2C_PACKET *>(Marshalled_pPackets.ptr()); if( (NULL == pPackets) ) { return FALSE; } #else HSI2C_PACKET *pPackets = pXferBlock->pHSI2CPackets; #endif #if MARSHAL struct Marshalled_I2C_PACKET { MarshalledBuffer_t *pbyBuf; MarshalledBuffer_t *lpiResult; } *Marshalled_of_pPackets; Marshalled_of_pPackets = new Marshalled_I2C_PACKET[pXferBlock->iNumPackets]; if (Marshalled_of_pPackets==0) { return FALSE; } MarshalledBuffer_t *pMarshalled_ptr; int i; // Map pointers for each packet in the array for (i = 0; i < pXferBlock->iNumPackets; i++) { switch( pPackets[i].byRW & HSI2C_METHOD_MASK ) { case HSI2C_RW_WRITE: pMarshalled_ptr = new MarshalledBuffer_t( pPackets[i].pbyBuf, pPackets[i].wLen, ARG_I_PTR, FALSE, FALSE); if (pMarshalled_ptr ==0) { bRet = FALSE; goto cleanupPass1; } if (pMarshalled_ptr->ptr()==0) { bRet = FALSE; delete pMarshalled_ptr; goto cleanupPass1; } break; case HSI2C_RW_READ: pMarshalled_ptr = new MarshalledBuffer_t( pPackets[i].pbyBuf, pPackets[i].wLen, ARG_O_PTR, FALSE, FALSE); if (pMarshalled_ptr ==0) { bRet = FALSE; goto cleanupPass1; } if (pMarshalled_ptr->ptr()==0) { bRet = FALSE; delete pMarshalled_ptr; goto cleanupPass1; } break; default: bRet = FALSE; goto cleanupPass1; } pPackets[i].pbyBuf = reinterpret_cast<PBYTE>(pMarshalled_ptr->ptr()); Marshalled_of_pPackets[i].pbyBuf = pMarshalled_ptr; } for (i = 0; i < pXferBlock->iNumPackets; i++) { pMarshalled_ptr = new MarshalledBuffer_t( pPackets[i].lpiResult, sizeof(INT), ARG_O_PDW, FALSE, FALSE); if (pMarshalled_ptr ==0) { bRet = FALSE; goto cleanupPass2; } if (pMarshalled_ptr->ptr()==0) { bRet = FALSE; delete pMarshalled_ptr; goto cleanupPass2; } pPackets[i].lpiResult = reinterpret_cast<LPINT>(pMarshalled_ptr->ptr()); Marshalled_of_pPackets[i].lpiResult = pMarshalled_ptr; } #endif bRet = pHSI2C->ProcessPackets(pPackets, pXferBlock->iNumPackets); #if MARSHAL DEBUGMSG (ZONE_IOCTL|ZONE_FUNCTION, (TEXT("I2C_IOControl:I2C_IOCTL_TRANSFER -\r\n"))); i = pXferBlock->iNumPackets; cleanupPass2: for (--i; i>=0; --i) { delete Marshalled_of_pPackets[i].lpiResult; } i = pXferBlock->iNumPackets; cleanupPass1: for (--i; i>=0; --i) { delete Marshalled_of_pPackets[i].pbyBuf; } delete[] Marshalled_of_pPackets; #endif break; } case HSI2C_IOCTL_RESET: { DEBUGMSG (ZONE_IOCTL|ZONE_FUNCTION, (TEXT("HSI2C_IOControl:RESET +\r\n"))); pHSI2C->Reset(); bRet = TRUE; DEBUGMSG (ZONE_IOCTL|ZONE_FUNCTION, (TEXT("HSI2C_IOControl:RESET -\r\n"))); break; } case HSI2C_IOCTL_ENABLE_SLAVE: case HSI2C_IOCTL_DISABLE_SLAVE: case HSI2C_IOCTL_SET_SLAVE_TXT: case HSI2C_IOCTL_GET_SLAVE_TXT: case HSI2C_IOCTL_SET_SLAVESIZE: case HSI2C_IOCTL_GET_SLAVESIZE: { SetLastError(ERROR_NOT_SUPPORTED); bRet = FALSE; break; } case IOCTL_POWER_CAPABILITIES: { // Tell the power manager about ourselves. if (pBufOut != NULL && dwLenOut >= sizeof(POWER_CAPABILITIES) && pdwActualOut != NULL) { PREFAST_SUPPRESS(6320, "Generic exception handler"); __try { PPOWER_CAPABILITIES ppc = (PPOWER_CAPABILITIES) pBufOut; memset(ppc, 0, sizeof(*ppc)); ppc->DeviceDx = DX_MASK(D0) | DX_MASK(D1) | DX_MASK(D4); *pdwActualOut = sizeof(*ppc); bRet = TRUE; } __except(EXCEPTION_EXECUTE_HANDLER) { ERRORMSG(TRUE, (_T("Exception in CSPI IOCTL_POWER_CAPABILITIES\r\n"))); } } break; } case IOCTL_POWER_SET: { if(pBufOut != NULL && dwLenOut == sizeof(CEDEVICE_POWER_STATE) && pdwActualOut != NULL) { PREFAST_SUPPRESS(6320, "Generic exception handler"); __try { CEDEVICE_POWER_STATE dx = *(PCEDEVICE_POWER_STATE) pBufOut; if (VALID_DX(dx)) { // Any request that is not D0 becomes a D4 request if (dx != D0 && dx != D1) { dx = D4; } *(PCEDEVICE_POWER_STATE) pBufOut = dx; *pdwActualOut = sizeof(CEDEVICE_POWER_STATE); // change the current power state pHSI2C->m_dxCurrent = dx; bRet = TRUE; } } __except(EXCEPTION_EXECUTE_HANDLER) { ERRORMSG(TRUE, (_T("Exception in CSPI IOCTL_POWER_CAPABILITIES\r\n"))); } } break; } case IOCTL_POWER_GET: { if(pBufOut != NULL && dwLenOut == sizeof(CEDEVICE_POWER_STATE) && pdwActualOut != NULL) { // Just return our current Dx value PREFAST_SUPPRESS(6320, "Generic exception handler"); __try { *(PCEDEVICE_POWER_STATE) pBufOut = pHSI2C->m_dxCurrent; //getCurrentPowerState(); *pdwActualOut = sizeof(CEDEVICE_POWER_STATE); bRet = TRUE; } __except(EXCEPTION_EXECUTE_HANDLER) { ERRORMSG(TRUE, (_T("Exception in CSPI IOCTL_POWER_CAPABILITIES\r\n"))); } } break; } default: { bRet = FALSE; break; } } } DEBUGMSG (ZONE_IOCTL|ZONE_FUNCTION, (TEXT("HSI2C_IOControl -\r\n"))); return bRet; } BOOL WINAPI HIC_DllEntry(HANDLE hInstDll, DWORD dwReason, LPVOID lpvReserved) { // Remove-W4: Warning C4100 workaround UNREFERENCED_PARAMETER(lpvReserved); switch (dwReason) { case DLL_PROCESS_ATTACH: DEBUGREGISTER((HINSTANCE) hInstDll); DEBUGMSG(ZONE_FUNCTION, (TEXT("HSI2C_DllEntry: DLL_PROCESS_ATTACH lpvReserved(0x%x)\r\n"),lpvReserved)); DisableThreadLibraryCalls((HMODULE) hInstDll); break; case DLL_PROCESS_DETACH: DEBUGMSG(ZONE_FUNCTION, (TEXT("HSI2C_DllEntry: DLL_PROCESS_DETACH lpvReserved(0x%x)\r\n"),lpvReserved)); break; } // return TRUE for success return TRUE; }
[ "lqk.sch@gmail.com@9677f95b-f147-b01e-6ec8-0db75aaa1bab" ]
lqk.sch@gmail.com@9677f95b-f147-b01e-6ec8-0db75aaa1bab
0e2d00bc1652253983483a9aa1aebf0688d5fc9f
82de12ba0df6add9ab63c834989eceb624d8c135
/treeList.cpp
a364a6bf03ac99183d36d9bd59af04b394052ec5
[]
no_license
mendi2770/Multi-nodes-tree
8af1e7f6e4eb798153dfd4aa515d41c23d472431
2bdf97bc102d847c207cca56012579a2157937b6
refs/heads/main
2023-06-03T00:27:53.004343
2021-06-15T22:24:52
2021-06-15T22:24:52
377,307,504
0
0
null
null
null
null
UTF-8
C++
false
false
3,950
cpp
/* Shimon Dyskin && Mendi Ben-Ezra Course Name: Data Structures 2 Exercise 1 Description: Forums of discussions and responses based on trees and lists (This is the treeList.cpp file) */ #include "treeList.h" treeList::~treeList() // deallocate tree { clearAllTrees(); } void treeList::clearAllTrees() //clear all of the trees { while (!tList.empty()) //as long there is still a tree in the list { Tree* temp = tList.front(); // take the first tree temp->clear(); // clear the sub tree tList.pop_front(); // pop destroys the pointers } } void treeList::clearOneTree(Tree::Node* rootCurrent) //delete one tree { for (list<Tree*>::iterator it = tList.begin(); it != tList.end(); it++) //loop itarator the tree to delete { if ((*it)->root == rootCurrent) //if we found the tree { (*it)->clear(); //call the function clear to delete the all tree return; } } } void treeList::addNewTree(string val) { //add a new tree Tree* t = new Tree(val); //allocate place for the new tree tList.push_back(t); //place the tree in the list } bool treeList::addResponse(string title, string father, string son) //add a new respone { for (list<Tree*>::iterator it = tList.begin(); it != tList.end(); it++) { if ((*it)->root->getContent() == title) //if the tree we wnat to responed on is found { return (*it)->addResp(father, son); //call the function add resp for adding the new respon } } return false; // Reached the end of the list of trees without finding the title } bool treeList::delResponse(string title, string val) { //delete respon bool flag = (title == val); for (list<Tree*>::iterator it = tList.begin(); it != tList.end(); it++) { if ((*it)->root->getContent() == title) { if (flag) // If found the title and it equals the value to delete { (*it)->delSubTree(title); // Delets the subtree tList.erase(it); // Erases the tree from the list return true; } else // If the title isn't the value to delete { return (*it)->delSubTree(val); } } } return false; // Reached the end of the list of trees without finding the title } void treeList::printAllTrees() //print all tree { int i = 1; //variable to check the level of the tree(for the 3 indention) for (list<Tree*>::reverse_iterator it = tList.rbegin(); it != tList.rend(); it++, i++) { cout << "Tree #" << i << endl; //the indention (*it)->print((*it)->root); //call function print ro print the current tree cout << endl; } } void treeList::printOneTree(string title) //function for print a single tree { for (list<Tree*>::iterator it = tList.begin(); it != tList.end(); it++) { if ((*it)->root->getContent() == title) //in case we found the tree for printing { (*it)->print((*it)->root); //call function print ro print the current tree return; } } } void treeList::printSubTree(string title, string val) //printing sub tree { for (list<Tree*>::iterator it = tList.begin(); it != tList.end(); it++) { if ((*it)->root->getContent() == title) //in case we found the tree { Tree::Node* temp = (*it)->find(val); //finding the node we want to print from if (temp != NULL) { (*it)->printFromNode(val); //print from this node (*it)->printToNode(val); //print the track to the node cout << endl; } } } } bool treeList::searchAndPrint(string val) //search and print { bool flag = false; //in case we didn't found the tree for (list<Tree*>::reverse_iterator it = tList.rbegin(); it != tList.rend(); it++) { Tree::Node* temp = (*it)->find(val); //in case we found the tree if (temp != NULL) { (*it)->printFromNode(val); (*it)->printToNode(val); cout << endl; flag = true; //returning true because we found the tree } } return flag; }
[ "noreply@github.com" ]
noreply@github.com
b53695ee3e238726457d6531414f5425c77cfbfa
bc8b842b711f6cb7a7cbe6e602c62dba252e88bb
/student.h
8bf6c024ddfa0df106523b49515e6ea0cd0ec09f
[]
no_license
AbelWeldaregay/representative-test-data-generator
9e72fe33c4d688aae9cac3023fb34d02395de494
a588c7b21eb5a46edbbd9bad7bb1ee7d600e3f1a
refs/heads/master
2021-04-26T23:23:44.352697
2018-12-20T18:41:29
2018-12-20T18:41:29
123,985,854
1
0
null
null
null
null
UTF-8
C++
false
false
363
h
#ifndef STUDENT_H_INCLUDED #define STUDENT_H_INCLUDED using namespace std; struct student { string className; int studentID; string firstName; string lastName; string studentAnswers; student(); }; void readFirstStudent(student studentType[]); void createAnswersFile(student studentType[]); #endif // STUDENT_H_INCLUDED
[ "aweld002@odu.edu" ]
aweld002@odu.edu
367a31d1944aca2ba5ed0113ffa89d93a418bb08
5074212db056d7a5f38b3b575e97210d0f9c1363
/L2Server/Area.h
73c2ab05f515f7957ff062f9d81b1669fe7d2a73
[]
no_license
izoodeh/Lotus-GF
05a2d0c113c4b657b533c1fe1bf728df111873f9
c3764b5f618a362c9bb08d32813ee49cf93414de
refs/heads/master
2022-11-09T18:52:12.364085
2020-06-29T15:07:43
2020-06-29T15:07:43
275,847,221
1
3
null
null
null
null
UTF-8
C++
false
false
447
h
#pragma once #include "MemoryObject.h" #include "Territory.h" //1F8 - areaType class CArea : public CBaseObject { public: /* 18 */ LPVOID _unkn18[9]; /* 60 */ CTerritory range; bool IsOn(UINT instantZoneId); bool IsBannedPoint(FVector& pos, bool param = true); bool IsInside(CCreature *pCreature); }; class CAreaDB { LPVOID m_orgInstance; public: CAreaDB(); ~CAreaDB(); CArea* FindArea(const WCHAR* wName); }; extern CAreaDB g_AreaDB;
[ "67592508+izoodeh@users.noreply.github.com" ]
67592508+izoodeh@users.noreply.github.com
ad9f7b2a3ead8256cdeacffa2ba3f340863002f4
023f19af6f722f93803afac6261562e8e34ec1da
/src/PointLight.cpp
f21df83381594ec6724782eee55aabf683abf33c
[ "BSD-2-Clause" ]
permissive
dlarudgus20/cpfps
d1a772c2593358707235331f861121e699b19981
53adf0979749a7244e8503f19e4653247f154869
refs/heads/master
2021-01-10T18:52:39.316654
2017-05-30T09:54:11
2017-05-30T09:54:11
42,655,222
0
0
null
null
null
null
UTF-8
C++
false
false
3,295
cpp
// Copyright (c) 2014, 임경현 // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /** * @file Light.cpp * @date 2015. 9. 25. * @author dlarudgus20 * @copyright The BSD (2-Clause) License */ #include "pch.h" #include "ext.h" #include "PointLight.h" #include "Shader.h" #include "LightManager.h" PointLight::PointLight() : m_index(-1) , m_position(0.0f, 0.0f, 0.0f) , m_attenuationConstant(1.0f), m_attenuationLinear(0.0f), m_attenuationQuadratic(0.0f) { } void PointLight::setIndex(int i) { m_index = i; } int PointLight::getIndex() const { return m_index; } void PointLight::setPosition(const glm::vec3 &pos) { m_position = pos; } const glm::vec3 &PointLight::getPosition() const { return m_position; } void PointLight::setAttenuation(float constant, float linear, float quadratic) { m_attenuationConstant = constant; m_attenuationLinear = linear; m_attenuationQuadratic = quadratic; } float PointLight::getAttenuationConstant() const { return m_attenuationConstant; } float PointLight::getAttenuationLinear() const { return m_attenuationLinear; } float PointLight::getAttenuationQuadratic() const { return m_attenuationQuadratic; } void PointLight::apply(const glm::mat4 &viewMatrix) const { assert(0 <= m_index && m_index <= LightManager::POINTLIGHT_COUNT); assert(m_index <= 9); std::string prefix = "ptLights[ ]"; prefix[9] = '0' + m_index; glm::vec3 pos = glm::vec3(viewMatrix * glm::vec4(m_position, 1.0f)); Shader *pShader = Shader::getCurrentShader(); pShader->setUniform3f(prefix + ".position", pos); pShader->setUniform1f(prefix + ".constant", m_attenuationConstant); pShader->setUniform1f(prefix + ".linear", m_attenuationLinear); pShader->setUniform1f(prefix + ".quadratic", m_attenuationQuadratic); pShader->setUniform3f(prefix + ".ambient", m_ambient); pShader->setUniform3f(prefix + ".diffuse", m_diffuse); pShader->setUniform3f(prefix + ".specular", m_specular); }
[ "dlarudgus20@naver.com" ]
dlarudgus20@naver.com
e2fab732c72303cc2a5492913dd5e3804909ca2e
0590e3430c60296b2930d1c532efb9d116ba1c17
/KisokaraCpp-samples/04/04-if4.cpp
dc330e594ffad031440eab8e2a13e475b54662e5
[]
no_license
datsu0/cpp
645b8f9e9991fccbe514d6ea59a9353ee7da0841
0e363668fc89e589fedadbc79801d9adf53b05c9
refs/heads/master
2022-08-06T12:06:56.100520
2020-05-24T14:15:54
2020-05-24T14:15:54
255,307,034
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
308
cpp
#include <iostream> using namespace std; int main() { int n = 9; if (n % 2 == 1) { cout << "nは奇数です。\n"; //出力値:nは奇数です。 if (n % 3 == 0) cout << "nは3の倍数かつ奇数です。\n";//出力値:nは3の倍数かつ奇数です。 } }
[ "atsu34412@gmail.com" ]
atsu34412@gmail.com
ffb4c7b7ff3958624f9c883fcf479d944bddf7a5
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/CMake/CMake-gumtree/Kitware_CMake_repos_basic_block_block_13652.cpp
a23d70bdf5f810837fd4bdf1004e0441fe61a756
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
891
cpp
{ const char *p; (void)best_bid; /* UNUSED */ if ((p = __archive_read_ahead(a, 4, NULL)) == NULL) return (-1); /* * Bid of 29 here comes from: * + 16 bits for "PK", * + next 16-bit field has 6 options so contributes * about 16 - log_2(6) ~= 16 - 2.6 ~= 13 bits * * So we've effectively verified ~29 total bits of check data. */ if (p[0] == 'P' && p[1] == 'K') { if ((p[2] == '\001' && p[3] == '\002') || (p[2] == '\003' && p[3] == '\004') || (p[2] == '\005' && p[3] == '\006') || (p[2] == '\006' && p[3] == '\006') || (p[2] == '\007' && p[3] == '\010') || (p[2] == '0' && p[3] == '0')) return (29); } /* TODO: It's worth looking ahead a little bit for a valid * PK signature. In particular, that would make it possible * to read some UUEncoded SFX files or SFX files coming from * a network socket. */ return (0); }
[ "993273596@qq.com" ]
993273596@qq.com
27bedb7944733c024b2a3bd3180742a96e32245d
900cc80a8312eeb2ac0fcee4f7474331ee4286e3
/CodeBreaker/Classes/utils/JsonObject.h
c5ad1f992b4531aad9bacfdaffe345b6fc16f75a
[]
no_license
nigamshah/CodeBreaker
680031cb9ed5665b7646a5cf40f7863cd3f2500e
b66f98b57aff62c86612471689dfd2bf269a8f40
refs/heads/master
2016-09-06T13:14:14.486620
2013-08-22T23:01:34
2013-08-22T23:01:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,821
h
// // JsonObject.h // CodeBreaker // // Created by Nigam Shah on 8/14/13. // // #ifndef __CodeBreaker__JsonObject__ #define __CodeBreaker__JsonObject__ #include "cocos2d.h" #include "StringUtils.h" #include "Json.h" using namespace cocos2d; using namespace cocos2d::extension; using namespace std; namespace codebreaker { /* // #define Json_False 0 // #define Json_True 1 // #define Json_NULL 2 // #define Json_Number 3 // #define Json_String 4 // #define Json_Array 5 // #define Json_Object 6 */ class JsonObject : public CCObject { private: Json* _getChildNode(string keyPath) { Json* result = _jsonNode; vector<string> keyVector = StringUtils::split(keyPath, '.'); for(string key : keyVector) { result = Json_getItem(result, key.c_str()); if (!result) { CCLOGERROR("Error! Bad Json query for: %s", keyPath.c_str()); } } return result; } public: CC_SYNTHESIZE(Json*, _jsonNode, JsonNode); CREATE_FUNC(JsonObject); bool init() { return true; } JsonObject* getChild(string keyPath) { Json* targetNode = _getChildNode(keyPath); JsonObject* result = JsonObject::create(); result->setJsonNode(targetNode); return result; } // only if the jsonNode is a json array JsonObject* getItemAt(int index) { if (_jsonNode->type != Json_Array) { CCLOGERROR("Cannot call getItemAt on a node that is not an array"); return nullptr; } Json* targetNode = Json_getItemAt(_jsonNode, index); JsonObject* result = JsonObject::create(); result->setJsonNode(targetNode); return result; } int getInt() { return _jsonNode->valueint; } float getFloat() { return _jsonNode->valuefloat; } string getString() { return string(_jsonNode->valuestring); } }; } #endif /* defined(__CodeBreaker__JsonObject__) */
[ "nshah@zynga.com" ]
nshah@zynga.com
b806752318d52a1a9af3719995785797e7bf0c15
9369318cdbde33f5910c6de3736f1d07400cf276
/246D.cpp
c4704c7b40e7f4ed932dee9ad680f7b194de5773
[]
no_license
cwza/codeforces
cc58c646383a201e10422ec80567b52bef4a0da9
e193f5d766e8ddda6cdc8a43b9f1826eeecfc870
refs/heads/master
2023-04-11T12:22:04.555974
2021-04-22T04:45:20
2021-04-22T04:45:20
352,477,628
0
0
null
null
null
null
UTF-8
C++
false
false
1,092
cpp
#include <bits/stdc++.h> using namespace std; #define ll long long #define ar array int n, m; const int maxN = 1e5, maxC = 1e5; vector<int> adj[maxN]; int c[maxN]; bool vis[maxN]; set<int> q[maxC]; void dfs(int u) { vis[u] = true; for(int v : adj[u]) { if(c[v]!=c[u]) q[c[u]].insert(c[v]); if(!vis[v]) { dfs(v); } } } int main() { ios::sync_with_stdio(0); cin.tie(0); // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); cin >> n >> m; for(int i = 0, a; i < n; ++i) { cin >> a; a--; c[i] = a; } for(int i = 0, u, v; i < m; ++i) { cin >> u >> v; u--, v--; adj[u].push_back(v); adj[v].push_back(u); } for(int u = 0; u < n; ++u) { if(!vis[u]) { dfs(u); } } int ansV = 0; int ans = -1; for(int i = 0; i < maxC; ++i) { if(q[i].size() > ansV) { ansV = q[i].size(); ans = i; } } if(ans==-1) cout << *min_element(c, c+n)+1; else cout << ans + 1; }
[ "cwz0205a@gmail.com" ]
cwz0205a@gmail.com
e191366b665de9f8bac94d41f7bcd67816f5df1f
4ce2b9731da6372539c73ebb17325d80b841887f
/x/src/x/nfl/Segment.cpp
4ea99f982b94b3f6d9af98061e238ea2e253237c
[ "Apache-2.0" ]
permissive
limbo018/rsyn-x
ed2795222fff6f118ef9d64c047880c88bc7d77c
3855afbf6d25347f7d91f86aba8d1b1664373563
refs/heads/master
2021-02-10T04:15:59.918006
2020-02-25T16:19:34
2020-02-25T16:19:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
39,955
cpp
/* Copyright 2014-2018 Rsyn * * 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. */ /* * File: Segment.cpp * Author: isoliveira * * Created on 12 de Março de 2018, 17:32 */ #include <iostream> #include "Segment.h" #include "Bin.h" #include "Row.h" #include "Blockage.h" namespace NFL { void Segment::initBins() { const DBU binWidth = clsBinLength[X]; const int numBins = roundedUpIntegralDivision(getWidth(), binWidth); clsBins.reserve(numBins); Bounds bounds = getBounds(); const DBU rightPos = getCoordinate(UPPER, X); Bin * left = nullptr; do { bounds[UPPER][X] = std::min(bounds[LOWER][X] + binWidth, rightPos); // Merging remain space to the current bin. if (rightPos - bounds[UPPER][X] < binWidth) bounds[UPPER][X] = rightPos; const int id = clsBins.size(); clsBins.push_back(Bin()); Bin & bin = clsBins.back(); bin.setBounds(bounds); bin.setId(id); bin.setSegment(this); bounds[LOWER][X] = bounds[UPPER][X]; if (left) { left->setRight(&bin); bin.setLeft(left); } // end if left = &bin; // connecting horizontal bins } while (bounds[UPPER][X] + binWidth <= rightPos); } // end method // ----------------------------------------------------------------------------- void Segment::initLegalize() { Node * inst = createWhitespaceNode(getBounds()); clsLeftNode = inst; clsRighNode = inst; insertNode(inst); } // end method // ----------------------------------------------------------------------------- void Segment::setLeft(Segment * left) { const std::string & id = left->getFullId(); if (clsSegments.find(id) == clsSegments.end()) { clsLeft = left; clsNeighbors.push_back(left); clsSegments.insert(id); } // end if } // end method // ----------------------------------------------------------------------------- void Segment::setRight(Segment * right) { const std::string & id = right->getFullId(); if (clsSegments.find(id) == clsSegments.end()) { clsRight = right; clsNeighbors.push_back(right); clsSegments.insert(id); } // end if } // end method // ----------------------------------------------------------------------------- void Segment::addLower(Segment * lower) { const std::string & id = lower->getFullId(); if (clsSegments.find(id) == clsSegments.end()) { clsLower.push_back(lower); clsNeighbors.push_back(lower); clsSegments.insert(id); if (lower->getCoordinate(UPPER, Y) == getPosition(Y)) { clsVerticalNeighbors.push_back(lower); } // end if } // end if } // end method // ----------------------------------------------------------------------------- void Segment::addUpper(Segment * upper) { const std::string & id = upper->getFullId(); if (clsSegments.find(id) == clsSegments.end()) { clsUpper.push_back(upper); clsNeighbors.push_back(upper); clsSegments.insert(id); if (upper->getPosition(Y) == getCoordinate(UPPER, Y)) { clsVerticalNeighbors.push_back(upper); } // end if } // end if } // end method // ----------------------------------------------------------------------------- bool Segment::isInsidePosition(const DBUxy & pos) const { const Bounds & bds = getBounds(); if (pos[X] < bds[LOWER][X] || pos[X] > bds[UPPER][X] || pos[Y] < bds[LOWER][Y] || pos[Y] > bds[UPPER][Y]) return false; return true; } // end method // ----------------------------------------------------------------------------- std::string Segment::getFullId(const std::string & separator) const { int rowId = clsRow->getId(); return std::to_string(rowId) + separator + std::to_string(getId()); } // end method // ----------------------------------------------------------------------------- void Segment::insertNode(Node * inst) { int left = getBinIndex(inst->getCoordinate(LOWER, X), false); int right = getBinIndex(inst->getCoordinate(UPPER, X), true); for (int index = left; index < right; ++index) { Bin * bin = getBinByIndex(index); bin->insertNode(inst); } //end for if (!inst->isWhitespace()) { clsNodeUsage += inst->getWidth(); } // end if } // end method // ----------------------------------------------------------------------------- void Segment::removeNode(Node * inst) { int left = getBinIndex(inst->getCoordinate(LOWER, X), false); int right = getBinIndex(inst->getCoordinate(UPPER, X), true); for (int index = left; index < right; ++index) { Bin * bin = getBinByIndex(index); bin->removeNode(inst); } //end for if (!inst->isWhitespace()) { clsNodeUsage -= inst->getWidth(); } // end if } // end method // ----------------------------------------------------------------------------- Bin * Segment::getBinByPosition(const DBU posX) { const int id = getBinIndex(posX); return getBinByIndex(id); } // end method // ----------------------------------------------------------------------------- Bin * Segment::getBinByIndex(const int index) { if (index >= 0 && index < getNumBins()) return &clsBins[index]; return nullptr; } // end method // ----------------------------------------------------------------------------- int Segment::getBinIndex(const DBU posX, const bool roundUp) { const DBU delta = posX - getPosition(X); const DBU length = getDefaultBinLength(X); int numBins = roundUp ? getNumBins() : getNumBins() - 1; int index = static_cast<int> (delta / length); if (roundUp) { index = delta % length ? index + 1 : index; } // end if return std::min(index, numBins); } // end method // ----------------------------------------------------------------------------- DBU Segment::getDisplacement(const DBUxy pos) { const DBU dispY = std::abs(pos[Y] - clsBounds[LOWER][Y]); if (pos[X] >= clsBounds[LOWER][X] && pos[X] <= clsBounds[UPPER][X]) return dispY; const DBU dispX = std::min(std::abs(clsBounds[LOWER][X] - pos[X]), std::abs(clsBounds[UPPER][X] - pos[X])); return dispY + dispX; } // end method // ----------------------------------------------------------------------------- bool Segment::computeLegalPosition(LegalAux & legalAux) { Node * inst = legalAux.clsNode; DBUxy & pos = legalAux.clsPos; pos[X] = inst->getPosition(X); pos[Y] = getPosition(Y); pos[X] = clsRow->getSiteAdjustedPosition(inst->getPosition(X)); legalAux.clsLegalSegment = this; const Bounds & segBds = getBounds(); if (pos[X] < segBds[LOWER][X] || pos[X] > segBds[UPPER][X]) { legalAux.clsCost = std::numeric_limits<DBU>::max(); return false; } // end if getOverlapNode(legalAux); Node * refNode = legalAux.clsReferenceNode; const Bounds & overlapBds = refNode->getBounds(); const DBU nodeWidth = inst->getWidth(); if (!isEnclosedNodeInWhitespace(legalAux)) { DBU requiredMove = inst->getWidth(); std::vector<DBU> leftCost; std::vector<DBU> rightCost; DBU leftOverflowMove = 0; DBU rightOverflowMove = 0; Node * leftRefNode = legalAux.clsReferenceNode; Node * rightRefNode = leftRefNode->getRightNode(); computeShiftToSide(leftRefNode, requiredMove, leftOverflowMove, leftCost, true); computeShiftToSide(rightRefNode, requiredMove, rightOverflowMove, rightCost, false); const DBU maxOffsetLeft = requiredMove - leftOverflowMove; const DBU maxOffsetRight = requiredMove - rightOverflowMove; if (maxOffsetLeft + maxOffsetRight < requiredMove) { std::cout << "ERROR required move\n"; return false; exit(0); //overflow = true; //return 0; // we don't return int max to avoid overflow } // end for DBU displacementCost = std::numeric_limits<DBU>::max(); int numRequiredSites = getNumSites(requiredMove); int numLeftsites = getNumSites(maxOffsetLeft); int numRightSites = getNumSites(maxOffsetRight); int shiftToLeft = -1; const DBU initPosX = inst->getInitialPosition(X); const DBU posX = inst->getPosition(X); const DBU siteWidth = getSiteWidth(); // std::cout << "--------\n"; for (int i = numLeftsites; i >= numRequiredSites - numRightSites; --i) { DBU targetPosX = refNode->getCoordinate(UPPER, X) - (siteWidth * i); DBU nodeCost = computePositionCost(initPosX, posX, targetPosX); DBU currentCost = nodeCost + leftCost[i] + rightCost[numRequiredSites - i] ; if (currentCost < displacementCost) { shiftToLeft = i; displacementCost = currentCost; } } // end for legalAux.clsLeftMove = shiftToLeft * siteWidth; legalAux.clsRightMove = requiredMove - legalAux.clsLeftMove; legalAux.clsPos[X] = refNode->getCoordinate(UPPER, X) - legalAux.clsLeftMove; legalAux.clsPos[Y] = refNode->getPosition(Y); legalAux.clsCost = displacementCost; } // end if-else return true; } // end method // ----------------------------------------------------------------------------- bool Segment::legalizeNode(LegalAux & legalAux) { Node * node = legalAux.clsNode; Node * reference = legalAux.clsReferenceNode; Node * left = reference; Node * right = reference->getRightNode(); bool enclosed = isEnclosedNodeInWhitespace(legalAux); clsRow->moveNode(legalAux.clsNode, legalAux.clsOriginSegment, legalAux.clsLegalSegment, legalAux.clsPos); if (enclosed) { if (reference->getWidth() > node->getWidth()) { devideWhitespace(node, reference); DBU posX = legalAux.clsPos[X]; if (reference->getPosition(X) > posX) { left = reference->getLeftNode(); right = reference; } else { left = reference; right = reference->getRightNode(); } // end if-else } else { removeNode(reference); left = reference->getLeftNode(); right = reference->getRightNode(); deleteWhitespaceNode(reference); } // end if-else connectNodes(left, node, right); } else { connectNodes(left, node, right); if (legalAux.clsLeftMove > 0) { moveLegalizedNodes(left, legalAux.clsLeftMove, true); } // end if if (legalAux.clsRightMove > 0) { moveLegalizedNodes(right, legalAux.clsRightMove, false); } // end if } updateLeftAndRightSegmentNodes(node->getLeftNode(), node, node->getRightNode()); node->setLegalized(true); return false; } // end method // ----------------------------------------------------------------------------- bool Segment::isEnclosedNodeInWhitespace(LegalAux & legalAux) { Node * nodeRef = legalAux.clsReferenceNode; if (!nodeRef->isWhitespace()) return false; Node * node = legalAux.clsNode; const DBU width = node->getWidth(); const DBUxy & pos = legalAux.clsPos; const Bounds &refBds = nodeRef->getBounds(); if (refBds[LOWER][X] <= pos[X] && refBds[UPPER][X] >= pos[X] + width) { return true; } // end if return false; } // end method // ----------------------------------------------------------------------------- void Segment::getOverlapNode(LegalAux & legalAux) { DBUxy pos = legalAux.clsPos; Bin * bin = getBinByPosition(pos[X]); Node * binInst = bin->getOverlapNode(pos[X]); legalAux.clsReferenceNode = binInst; } // end method // ----------------------------------------------------------------------------- void Segment::computeLeftShift(LegalAux & legalAux, std::vector<DBU> & cost) { Node * left = legalAux.clsReferenceNode; // the overlap node is the left one. const DBU siteWidth = getSiteWidth(); DBU requiredLeftMove = legalAux.clsRequiredMove; if (left->isWhitespace()) { requiredLeftMove = std::max((DBU) 0, requiredLeftMove - left->getWidth()); left = left->getLeftNode(); } // end if DBU leftMove = requiredLeftMove; while (left && leftMove > 0) { if (left->isWhitespace()) { leftMove -= left->getWidth(); left = left->getLeftNode(); continue; } // end if DBUxy pos = left->getPosition(); const DBU diffCost = computeDifferencePositionCost(pos[X], pos[X] - siteWidth, left->getInitialPosition(X)); int numSites = getNumSites(leftMove) + 1; for (int i = 1; i < numSites; ++i) { cost[i] += i * diffCost; } // end for left = left->getLeftNode(); } // end while // } // end if-else leftMove = std::max((DBU) 0, leftMove); legalAux.clsLeftMove = requiredLeftMove - leftMove; } // end method // ----------------------------------------------------------------------------- void Segment::computeRightShift(LegalAux & legalAux, std::vector<DBU> & cost) { Node * right = legalAux.clsReferenceNode; // the overlap node is the left one. const DBU siteWidth = getSiteWidth(); DBU requiredRightMove = legalAux.clsRequiredMove; if (right->isWhitespace()) { Node * node = legalAux.clsNode; const Bounds & nodeBds = node->getBounds(); const Bounds & rightBds = right->getBounds(); Bounds overlap = nodeBds.overlapRectangle(rightBds); const DBU length = overlap.computeLength(X); requiredRightMove = std::max((DBU) 0, requiredRightMove - length); } // end if DBU rightMove = requiredRightMove; right = right->getRightNode(); while (right && rightMove > 0) { if (right->isWhitespace()) { rightMove -= right->getWidth(); right = right->getRightNode(); continue; } // end if DBUxy pos = right->getPosition(); const DBU diffCost = computeDifferencePositionCost(pos[X], pos[X] + siteWidth, right->getInitialPosition(X)); int numSites = getNumSites(rightMove) + 1; for (int i = 1; i < numSites; ++i) { cost[i] += i * diffCost; } // end for right = right->getRightNode(); } // end while rightMove = std::max((DBU) 0, rightMove); legalAux.clsRightMove = requiredRightMove - rightMove; } // end method // ----------------------------------------------------------------------------- void Segment::computeShiftToSide(Node * refNode, const DBU requiredMove, DBU & overflowMove, std::vector<DBU> &cost, const bool isToLeft) { overflowMove = requiredMove; int numRequiredSites = getNumSites(overflowMove); cost.resize(numRequiredSites + 1, 0); int sites = 0; Node * ref = refNode; while (ref && overflowMove > 0) { if (ref->isWhitespace()) { const DBU maxOverflowAllowed = ref->getWidth() > overflowMove ? overflowMove : ref->getWidth(); sites += getNumSites(maxOverflowAllowed); overflowMove -= maxOverflowAllowed; } else { const DBU siteWidth = isToLeft ? -getSiteWidth() : +getSiteWidth(); const DBU initPosX = ref->getInitialPosition(X); const DBU legalPosX = ref->getPosition(X); for (int i = sites + 1; i <= numRequiredSites; ++i) { DBU targetPosX = legalPosX + (i * siteWidth); const DBU costX = computePositionCost(initPosX, legalPosX, targetPosX); cost[i] += costX; } // end for } // end if-else ref = isToLeft ? ref->getLeftNode() : ref->getRightNode(); } // end while } // end method // ----------------------------------------------------------------------------- void Segment::computeOptimizedPosition(LegalAux & legalAux, std::vector<DBU> & leftCost, std::vector<DBU> &rightCost) { Node * node = legalAux.clsNode; DBUxy pos = legalAux.clsPos; DBU initPos = node->getInitialPosition(X); DBU cost = std::numeric_limits<DBU>::max(); int numRequiredSites = getNumSites(legalAux.clsRequiredMove); int numAvailableLeftSites = getNumSites(legalAux.clsLeftMove); int numAvailableRightSites = getNumSites(legalAux.clsRightMove); int lowerLimit = numRequiredSites - numAvailableRightSites; int leftSiteMove = 0; int rightSiteMove = 0; for (int leftId = numAvailableLeftSites; leftId >= lowerLimit; --leftId) { int rightId = numRequiredSites - leftId; DBU moveCost = leftCost[leftId] + rightCost[rightId]; DBU leftPos = pos[X] - (leftId * getSiteWidth()); DBU cellCost = computeDifferencePositionCost(pos[X], leftPos, initPos); DBU totalCost = moveCost + cellCost; if (totalCost <= cost) { leftSiteMove = leftId; rightSiteMove = rightId; cost = totalCost; } // end if } // end for DBU leftMove = leftSiteMove * getSiteWidth(); DBU rightMove = rightSiteMove * getSiteWidth(); legalAux.clsLeftMove = leftMove; legalAux.clsRightMove = rightMove; Node * left = legalAux.clsReferenceNode; if (left->isWhitespace()) { Bounds nodeBds = node->getBounds(); nodeBds.moveTo(pos[X], X); const Bounds & rightBds = left->getBounds(); Bounds overlap = nodeBds.overlapRectangle(rightBds); const DBU length = overlap.computeLength(X); const DBU nodeWidth = node->getWidth(); if (nodeWidth > length) { DBU diff = nodeWidth - length; diff -= rightMove; if (diff < 0) { std::cout << "DEBUG REQUIRED. DIFF < 0. diff: " << diff << " node: " << node->getName() << "\n"; } pos[X] -= diff; } // end if } else { pos[X] = left->getCoordinate(UPPER, X) - leftMove; } // end if-else legalAux.clsPos[X] = pos[X]; } // end method // ----------------------------------------------------------------------------- DBU Segment::computeDifferencePositionCost(const DBU fromPosX, const DBU toPosX, const DBU initPosX) { const DBU toCost = std::abs(toPosX - initPosX); const DBU fromCost = std::abs(fromPosX - initPosX); return toCost - fromCost; } // end method // ----------------------------------------------------------------------------- void Segment::computeLegalizationCost(LegalAux & legalAux) { Node * node = legalAux.clsNode; Node * left = legalAux.clsReferenceNode; Node * right = left->getRightNode(); legalAux.clsCost = computeDisplacementCost(node, legalAux.clsPos); DBU leftMove = legalAux.clsLeftMove; DBU rightMove = legalAux.clsRightMove; while (left && leftMove >= 0) { if (left->isWhitespace()) { leftMove -= left->getWidth(); } else { DBUxy pos = left->getPosition(); pos[X] -= leftMove; legalAux.clsCost += computeDisplacementCost(left, pos); } // end if-else left = left->getLeftNode(); } // end while while (right && rightMove >= 0) { if (right->isWhitespace()) { rightMove -= right->getWidth(); } else { DBUxy pos = right->getPosition(); pos[X] += rightMove; legalAux.clsCost += computeDisplacementCost(right, pos); } // end if-else right = right->getRightNode(); } // end while } // end method // ----------------------------------------------------------------------------- DBU Segment::computePositionCost(const DBU initPos, const DBU currentPos, const DBU targetPos) { return std::abs(targetPos - initPos) - std::abs(currentPos - initPos); } // end method // ----------------------------------------------------------------------------- void Segment::openRequiredSpace(LegalAux & legalAux) { if (legalAux.clsLeftMove > 0) moveLeftCells(legalAux); if (legalAux.clsRightMove > 0) moveRightCells(legalAux); } // end method // ----------------------------------------------------------------------------- void Segment::moveLeftCells(LegalAux & legalAux) { DBU reqMove = legalAux.clsLeftMove; Node * left = legalAux.clsReferenceNode; std::deque<Node *> deleteInsts; if (left->isWhitespace()) left = left->getLeftNode(); while (left && reqMove > 0) { if (left->isWhitespace()) { DBU width = left->getWidth(); if (reqMove >= width) { // reset whitespace width removeNode(left); left->setWhitespaceBounds(UPPER, X, left->getPosition(X)); reqMove -= width; deleteInsts.push_back(left); } else { removeNode(left); DBU upperX = left->getCoordinate(UPPER, X) - reqMove; left->setWhitespaceBounds(UPPER, X, upperX); reqMove = 0; insertNode(left); } // end if-else } else { DBUxy pos = left->getPosition(); pos[X] -= reqMove; clsRow->moveNode(left, this, this, pos); } // end if-else left = left->getLeftNode(); } // end while for (Node * node : deleteInsts) { deleteWhitespaceNode(node); } // end for } // end method // ----------------------------------------------------------------------------- void Segment::moveRightCells(LegalAux & legalAux) { DBU reqMove = legalAux.clsRightMove; Node * right = legalAux.clsReferenceNode; right = right->getRightNode(); std::deque<Node *> deleteInsts; while (right && reqMove > 0) { if (right->isWhitespace()) { DBU width = right->getWidth(); if (reqMove >= width) { removeNode(right); reqMove -= width; right->setWhitespaceBounds(LOWER, X, right->getCoordinate(UPPER, X)); deleteInsts.push_back(right); } else { removeNode(right); DBU lowerX = right->getPosition(X) + reqMove; right->setWhitespaceBounds(LOWER, X, lowerX); reqMove = 0; insertNode(right); } // end if-else } else { DBUxy pos = right->getPosition(); pos[X] += reqMove; clsRow->moveNode(right, this, this, pos); } // end if-else right = right->getRightNode(); } // end while for (Node * node : deleteInsts) { deleteWhitespaceNode(node); } // end for } // end method // ----------------------------------------------------------------------------- void Segment::moveLegalizedNodes(Node * refNode, const DBU requiredMove, const bool isToLeft) { DBU overflow = requiredMove; Node * node = refNode; std::deque<Node *> deleteInsts; while (overflow > 0) { if (node->isWhitespace()) { DBU width = node->getWidth(); if (width <= overflow) { removeNode(node); overflow -= width; deleteInsts.push_back(node); } else { removeNode(node); if (isToLeft) { node->setDisplacementWhitespaceBounds(UPPER, X, -overflow); } else { node->setDisplacementWhitespaceBounds(LOWER, X, overflow); } // end if-else overflow = 0; insertNode(node); } // end if-else } else { DBUxy pos = node->getPosition(); pos[X] = isToLeft ? pos[X] - overflow : pos[X] + overflow; clsRow->moveNode(node, this, this, pos); } // end if-else //BEGIN DEBUG bool pt = node->getName().compare("g214985_u0") == 0; if (pt) { std::cout << "refNode: " << refNode->getName() << " maxDispNd: " << node->getName() << " disp: " << node->getDisplacement() << " pos: " << node->getPosition() << "\n"; } //END DEBUG node = isToLeft ? node->getLeftNode() : node->getRightNode(); } // end while for (Node * node : deleteInsts) { deleteWhitespaceNode(node); } // end for } // end method // ----------------------------------------------------------------------------- void Segment::devideWhitespace(Node * node, Node * reference) { const Bounds & instBds = node->getBounds(); const Bounds & refBds = reference->getBounds(); removeNode(reference); if (instBds[LOWER][X] == refBds[LOWER][X]) { reference->setWhitespaceBounds(LOWER, X, instBds[UPPER][X]); } else if (instBds[UPPER][X] == refBds[UPPER][X]) { reference->setWhitespaceBounds(UPPER, X, instBds[LOWER][X]); } else { Bounds space = refBds; space[LOWER][X] = instBds[UPPER][X]; reference->setWhitespaceBounds(UPPER, X, instBds[LOWER][X]); Node * right = createWhitespaceNode(space); connectNodes(reference, right, reference->getRightNode()); insertNode(right); } // end if-else insertNode(reference); } // end method // ----------------------------------------------------------------------------- void Segment::connectNodes(Node * left, Node * node, Node * right) { connectNodes(left, node); connectNodes(node, right); } // end method // ----------------------------------------------------------------------------- void Segment::connectNodes(Node * left, Node *right) { if (left) left->setRightNode(right); if (right) right->setLeftNode(left); } // end method // ----------------------------------------------------------------------------- DBU Segment::computeDisplacementCost(Node * inst, DBUxy targetPos) { const DBUxy pos = inst->getPosition(); const DBUxy initPos = inst->getInitialPosition(); DBUxy currentDisp = pos - initPos; DBUxy targetDisp = targetPos - initPos; currentDisp.abs(); targetDisp.abs(); DBUxy costDisp = targetDisp - currentDisp; return costDisp.aggregated(); } // end method // ----------------------------------------------------------------------------- void Segment::optimizeCellDisplacement(Node * node) { Node * left = node->getLeftNode(); Node * right = node->getRightNode(); bool swapLeft = false; bool swapRight = false; DBU righCost = std::numeric_limits<DBU>::max(); DBU leftCost = std::numeric_limits<DBU>::max(); DBU nodeSwapRightCost = std::numeric_limits<DBU>::max(); DBU nodeSwapLeftCost = std::numeric_limits<DBU>::max(); if (right && !right->isWhitespace()) { DBUxy pos = node->getPosition(); righCost = computeDisplacementCost(right, pos); pos[X] += right->getWidth(); nodeSwapRightCost = computeDisplacementCost(node, pos); if (righCost < 0 && nodeSwapRightCost < 0) { swapRight = true; } // end if } // end if if (left && !left->isWhitespace()) { DBUxy pos = node->getPosition(); leftCost = computeDisplacementCost(left, pos); pos[X] += left->getWidth(); nodeSwapLeftCost = computeDisplacementCost(node, pos); if (leftCost < 0 && nodeSwapLeftCost < 0) { swapLeft = true; } // end if } // end if if (swapLeft && swapRight) { DBU leftTotalCost = leftCost + nodeSwapLeftCost; DBU rightTotalCost = righCost + nodeSwapRightCost; if (leftTotalCost < rightTotalCost) { swapRight = false; } else { swapLeft = false; } // end if-else } // end if if (swapLeft) { swapNodes(left, node); } // end if if (swapRight) { swapNodes(node, right); } // end if } // end method // ----------------------------------------------------------------------------- void Segment::swapNodes(Node * node0, Node * node1) { if (!node0 || !node1) return; if (node0->getPosition(X) > node1->getPosition(X)) { Node * temp = node0; node0 = node1; node1 = temp; } // end if if (node0->getCoordinate(UPPER, X) != node1->getPosition(X)) { return; } // end if Node * node0Left = node0->getLeftNode(); Node * node1Right = node1->getRightNode(); DBUxy nodePos = node0->getPosition(); clsRow->moveNode(node1, this, this, nodePos); nodePos[X] += node1->getWidth(); clsRow->moveNode(node0, this, this, nodePos); node0->disconectNode(); node1->disconectNode(); if (node0Left) { node0Left->setRightNode(node1); } // end if node1->setLeftNode(node0Left); node1->setRightNode(node0); node0->setLeftNode(node1); node0->setRightNode(node1Right); if (node1Right) { node1Right->setLeftNode(node0); } // end if updateLeftSegmentNode(node1); updateRightSegmentNode(node0); } // end method // ----------------------------------------------------------------------------- void Segment::updateLeftAndRightSegmentNodes(Node * left, Node * node, Node * right) { updateLeftSegmentNode(node); updateRightSegmentNode(node); updateLeftSegmentNode(left); updateRightSegmentNode(right); } // end method // ----------------------------------------------------------------------------- void Segment::updateLeftSegmentNode(Node * left) { if (left && left->getPosition(X) < clsLeftNode->getPosition(X)) { clsLeftNode = left; } // end if } // end method // ----------------------------------------------------------------------------- void Segment::updateRightSegmentNode(Node * right) { if (right && right->getPosition(X) > clsRighNode->getPosition(X)) { clsRighNode = right; } // end if } // end method // ----------------------------------------------------------------------------- void Segment::setLeftSegmentNode(Node * left) { if (left) { clsLeftNode = left; } // end if } // end method // ----------------------------------------------------------------------------- void Segment::setRightSegmentNode(Node * right) { if (right) { clsRighNode = right; } // end if } // end method // ----------------------------------------------------------------------------- Node * Segment::createWhitespaceNode(const Bounds & bounds) { Node * inst = nullptr; if (clsDeletedWhitespaceNodes.empty()) { clsWhitespaceNodes.push_back(Node()); inst = &clsWhitespaceNodes.back(); const int id = getNextWhitespaceId(); inst->setId(id); } else { std::set<int>::iterator it = clsDeletedWhitespaceNodes.begin(); const int id = *it - clsWhitespaceThreshold; clsDeletedWhitespaceNodes.erase(it); inst = &clsWhitespaceNodes[id]; } // end if-else inst->setWhitespaceBounds(bounds); inst->setWhitespace(true); inst->setDeletedWhitespace(false); return inst; } // end method // ----------------------------------------------------------------------------- void Segment::deleteWhitespaceNode(Node * inst) { disconectNode(inst); clsDeletedWhitespaceNodes.insert(inst->getId()); inst->setDeletedWhitespace(true); } // end method // ----------------------------------------------------------------------------- void Segment::disconectNode(Node * inst) { if (!inst) { return; } // end if Node * left = inst->getLeftNode(); Node * right = inst->getRightNode(); if (left) { left->setRightNode(right); } // end if if (right) { right->setLeftNode(left); } // end if Node * segmentLeft = getLeftNode(); Node * segmentRight = getRightNode(); if (inst->getId() == segmentLeft->getId()) { setLeftSegmentNode(right); } // end if if (inst->getId() == segmentRight->getId()) { setRightSegmentNode(left); } // end if inst->disconectNode(); } // end method // ----------------------------------------------------------------------------- int Segment::getNextWhitespaceId() { clsWhitespaceLastId++; return clsWhitespaceLastId - 1; } // end method // ----------------------------------------------------------------------------- DBU Segment::getSiteWidth() { return clsRow->getSiteWidth(); } // end method // ----------------------------------------------------------------------------- int Segment::getNumSites(const DBU length) { return length / clsRow->getSiteWidth(); } // end method // ----------------------------------------------------------------------------- bool Segment::isSiteAligned(Node * node) { DBUxy pos = node->getPosition(); return !(pos[X] % getSiteWidth()); } // end method // ----------------------------------------------------------------------------- bool Segment::isInsideSegment(Node * node) { const Bounds & nodeBds = node->getBounds(); const Bounds & segmentBds = getBounds(); if (nodeBds[LOWER][X] < segmentBds[LOWER][X]) { return true; } // end if if (nodeBds[UPPER][X] > segmentBds[UPPER][X]) { return true; } // end if if (nodeBds[LOWER][Y] < segmentBds[LOWER][Y]) { return true; } // end if if (nodeBds[UPPER][Y] > segmentBds[UPPER][Y]) { return true; } // end if return false; } // end method // ----------------------------------------------------------------------------- // negative width is also considered zero width bool Segment::hasZeroWidth(Node * node) { if (node->isWhitespace()) { return node->getWidth() <= 0; } // end if return false; } // end method // ----------------------------------------------------------------------------- const void Segment::checkSanityBinsConnected() const { int i = 1; const Bin * currentBin = &clsBins.front(); while (currentBin->getRight() != nullptr) { if (currentBin->getRight()->getSegment() == currentBin->getSegment()) { currentBin = currentBin->getRight(); i++; } else break; } // end while if (i != clsBins.size()) std::cout << "A bin in segment " << getFullId() << " is not connected\n"; } // end method // ----------------------------------------------------------------------------- const void Segment::checkSanityBinsInside() const { for (const Bin & bin : clsBins) { if (!clsBounds.inside(bin.getBounds())) { std::cout << "Bin " << bin.getFullId() << " is outside its parent\n"; } } // end for } // end method // ----------------------------------------------------------------------------- const void Segment::checkSanityBinsOverlap() const { const Bin * currentBin = &clsBins.front(); const Bin * leftBin; while (currentBin->getRight() != nullptr) { if (currentBin->getRight()->getSegment() == currentBin->getSegment()) { leftBin = currentBin; currentBin = currentBin->getRight(); if (leftBin->getBounds().overlapArea(currentBin->getBounds()) > 1) std::cout << "Bins " << currentBin->getFullId() << " and " << leftBin->getFullId() << " overlap\n"; if (currentBin == leftBin) std::cout << "Bin " << currentBin->getFullId() << " is repeated\n"; } else break; } // end while } // end method // ----------------------------------------------------------------------------- bool Segment::checkSanitySegmentList() { int numInstBins = 0; for (Bin & bin : clsBins) numInstBins += bin.getNumNodes(); bool hasZeroWidthWhitespace = false; int numInstSegmentFront = 0; Node * front = getLeftNode(); while (front) { if (!front->isWhitespace()) numInstSegmentFront++; if (front->isWhitespace() && front->getWidth() <= 0) { std::cout << "Node " << front->getName() << " has zero width in segment " << getFullId() << " NodeBds: " << front->getBounds() << "\n"; hasZeroWidthWhitespace = true; } // end if front = front->getRightNode(); } // end while int numInstSegmentBack = 0; Node * back = getRightNode(); while (back) { if (!back->isWhitespace()) numInstSegmentBack++; back = back->getLeftNode(); } // std::cout << ">>>>>>>>>>>>>>> checkSanity: " << getFullId(); // std::cout << "\t#binInsts: " << numInstBins << " #instFront: " << numInstSegmentFront // << " #instBack: " << numInstSegmentBack << " has0Width: " << hasZeroWidthWhitespace // << "\n"; if (hasZeroWidthWhitespace) { std::cout << "Debug Required. Segment " << getFullId() << " has whitespace with zero width\n"; } return hasZeroWidthWhitespace; } // end method // ----------------------------------------------------------------------------- bool Segment::checkSanitySegmentInstances() { DBU segmentWidth = clsBounds.computeLength(X); DBU leftWidthInstaces = 0; DBU rightWidthInstances = 0; Node * left = getLeftNode(); Node * right = getRightNode(); while (left) { leftWidthInstaces += left->getWidth(); left = left->getRightNode(); } while (right) { rightWidthInstances += right->getWidth(); right = right->getLeftNode(); } if (leftWidthInstaces != segmentWidth) { std::cout << "Segment bounds: " << getBounds() << "\n"; left = getLeftNode(); int count = 0; while (left) { std::cout << "bds: " << left->getBounds() << " name: " << left->getName() << " WS: " << left->isWhitespace() << "\n"; left = left->getRightNode(); count++; if (count > 15) break; } std::cout << "Width left to right in segment " << getFullId() << " is not equal to total cell width. SegmentW: " << segmentWidth << " nodeW: " << leftWidthInstaces << "\n"; std::cout << "Exiting....\n"; //exit(0); return true; } if (rightWidthInstances != segmentWidth) { std::cout << "Segment bounds: " << getBounds() << "\n"; right = getRightNode(); int count = 0; while (right) { std::cout << "bds: " << right->getBounds() << " name: " << right->getName() << " WS: " << right->isWhitespace() << "\n"; right = right->getLeftNode(); count++; if (count > 10) break; } std::cout << "Width right to left in segment " << getFullId() << " is not equal to total cell width. SegmentW: " << segmentWidth << " nodeW: " << rightWidthInstances << "\n"; std::cout << "Exiting....\n"; //exit(0); return true; } return false; } // end method // ----------------------------------------------------------------------------- bool Segment::checkSanitySiteAligment() { Node * left = getLeftNode(); while (left) { bool siteAligned = isSiteAligned(left); if (!siteAligned) { std::cout << "Instance is not aligned to site. Inst: " << left->getName() << " pos: " << left->getPosition() << " segment: " << getFullId() << "\n"; std::cout << "Exiting.....\n"; //exit(0); return true; } left = left->getRightNode(); } return false; } // end method // ----------------------------------------------------------------------------- bool Segment::checkSanityZeroWidth() { Node * left = getLeftNode(); bool zeroWidth = false; while (left) { zeroWidth = hasZeroWidth(left); if (zeroWidth) break; left = left->getRightNode(); } if (zeroWidth) { std::cout << "Zero Width node detected\n"; Node * left = getLeftNode(); while (left) { std::cout << "bds: " << left->getBounds() << " name: " << left->getName() << " WS: " << left->isWhitespace() << "\n"; left = left->getRightNode(); } std::cout << "Instance has zero width. Inst: " << left->getName() << " bounds: " << left->getBounds() << " pos: " << left->getPosition() << " segment: " << getFullId() << "\n"; std::cout << "Exiting.....\n"; return true; //exit(0); } return false; } // end method // ----------------------------------------------------------------------------- bool Segment::checkSanityNodeBounds() { Node * left = getLeftNode(); Node * right = left->getRightNode(); while (right) { const Bounds & leftBds = left->getBounds(); const Bounds & rightBds = right->getBounds(); if (leftBds[UPPER][X] != rightBds[LOWER][X]) { std::cout << "Instances do not share bounds. left: " << left->getName() << " right: " << right->getName() << " leftBds: " << leftBds << " rightBds: " << rightBds << "\n"; std::cout << "Exiting.....\n"; //exit(0); return true; } // end if left = right; right = right->getRightNode(); } // end while return false; } // end method // ----------------------------------------------------------------------------- bool Segment::checkSanityNodesInsideSegment() { Node * left = getLeftNode(); const Bounds & segmentBds = getBounds(); while (left) { const Bounds & bds = left->getBounds(); if (bds[LOWER][X] < segmentBds[LOWER][X] || bds[UPPER][X] > segmentBds[UPPER][X] || bds[LOWER][Y] < segmentBds[LOWER][Y] || bds[UPPER][Y] > segmentBds[UPPER][Y]) { std::cout << "Instance is outside of segment bounds. inst: " << left->getName() << " instBds: " << bds << " segBds: " << segmentBds << "\n"; std::cout << "Exiting.....\n"; return true; //exit(0); } // end if left = left->getRightNode(); } // end while return false; } // end method // ----------------------------------------------------------------------------- bool Segment::checkSanityCache() { return false; } // end method // ----------------------------------------------------------------------------- bool Segment::checkSanityBins() { for (Bin & bin : clsBins) { if (bin.checkSanityBin()) return true; } // end for return false; } // end method // ----------------------------------------------------------------------------- bool Segment::checkSanityNodes() { if (checkSanitySegmentList()) { std::cout << "Debug required on checkSanitySegmentList\n"; return true; } // end if if (checkSanitySegmentInstances()) { std::cout << "Debug required on checkSanitySegmentInstances\n"; return true; } // end if if (checkSanitySiteAligment()) { std::cout << "Debug required on checkSanitySiteAligment\n"; return true; } // end if if (checkSanityZeroWidth()) { std::cout << "Debug required on checkSanityZeroWidth\n"; return true; } // end if if (checkSanityNodeBounds()) { std::cout << "Debug required on checkSanityNodeBounds\n"; return true; } // end if if (checkSanityNodesInsideSegment()) { std::cout << "Debug required on checkSanityNodesInsideSegment\n"; return true; } // end if if (checkSanityCache()) { std::cout << "Debug required on checkSanityCache\n"; return true; } // end if if (checkSanityBins()) { std::cout << "Debug required on checkSanityBins\n"; return true; } // end if return false; } // end method // ----------------------------------------------------------------------------- } // end namespace
[ "jucemar.monteiro@inf.ufrgs.br" ]
jucemar.monteiro@inf.ufrgs.br
71bb9dcce5167d78291f3f7af6a26be336b0cafc
964743cc9072f09d3d60a88ddd90971e48e8a956
/NewGeneUI/NewGene/Widgets/newgenewidget.h
1fffc1b8ccfc9ab82b8a12db5af9369fa5d21021
[]
no_license
daniel347x/newgene
f6a7abae718bc4b3813c6adf2c2f991dca535954
dc0b5ddaeea441d905d627a4145d7a3e2eda78b5
refs/heads/master
2022-06-27T17:19:42.205690
2022-06-21T21:52:07
2022-06-21T21:52:07
9,526,888
0
2
null
2022-06-21T21:52:08
2013-04-18T16:55:22
C
UTF-8
C++
false
false
7,288
h
#ifndef NEWGENEWIDGET_H #define NEWGENEWIDGET_H #include "globals.h" #include "../../../NewGeneBackEnd/UIData/DataWidgets.h" class QWidget; class NewGeneMainWindow; class UIInputProject; class UIOutputProject; class WidgetCreationInfo; class NewGeneWidget { public: enum WIDGET_NATURE { WIDGET_NATURE_UNKNOWN , WIDGET_NATURE_GENERAL , WIDGET_NATURE_INPUT_WIDGET , WIDGET_NATURE_OUTPUT_WIDGET }; enum UPDATE_CONNECTIONS_TYPE { RELEASE_CONNECTIONS_INPUT_PROJECT , ESTABLISH_CONNECTIONS_INPUT_PROJECT , RELEASE_CONNECTIONS_OUTPUT_PROJECT , ESTABLISH_CONNECTIONS_OUTPUT_PROJECT }; public: NewGeneWidget(WidgetCreationInfo const & creation_info); virtual ~NewGeneWidget(); NewGeneMainWindow & mainWindow(); bool IsTopLevel() { return top_level; } virtual void PrepareInputWidget(bool const also_link_output = true); virtual void PrepareOutputWidget(); virtual void HandleChanges(DataChangeMessage const &) {} // Be sure to call this only in the context of the UI thread void ShowMessageBox(std::string msg); protected slots: // **************************************************************************************************************************** // Pseudo-slots. virtual void UpdateInputConnections(NewGeneWidget::UPDATE_CONNECTIONS_TYPE connection_type, UIInputProject * project); virtual void UpdateOutputConnections(NewGeneWidget::UPDATE_CONNECTIONS_TYPE connection_type, UIOutputProject * project); // /* Remove if unnecessary virtual void RefreshAllWidgets() {} */ // public: // // The following base class functions are not necessary. // However, they do assist in assuring that derived classes use the same naming scheme. // At some point, errors could be added to these otherwise empty functions to further // encourage the proper naming scheme in derived classes. // // Output-project related refreshes virtual void WidgetDataRefreshReceive(WidgetDataItem_VARIABLE_GROUPS_SCROLL_AREA) {} virtual void WidgetDataRefreshReceive(WidgetDataItem_VARIABLE_GROUPS_TOOLBOX) {} virtual void WidgetDataRefreshReceive(WidgetDataItem_VARIABLE_GROUP_VARIABLE_GROUP_INSTANCE) {} virtual void WidgetDataRefreshReceive(WidgetDataItem_VARIABLE_GROUPS_SUMMARY_SCROLL_AREA) {} virtual void WidgetDataRefreshReceive(WidgetDataItem_VARIABLE_GROUPS_SUMMARY_VARIABLE_GROUP_INSTANCE) {} virtual void WidgetDataRefreshReceive(WidgetDataItem_KAD_SPIN_CONTROLS_AREA) {} virtual void WidgetDataRefreshReceive(WidgetDataItem_KAD_SPIN_CONTROL_WIDGET) {} virtual void WidgetDataRefreshReceive(WidgetDataItem_TIMERANGE_REGION_WIDGET) {} virtual void WidgetDataRefreshReceive(WidgetDataItem_DATETIME_WIDGET) {} virtual void WidgetDataRefreshReceive(WidgetDataItem_GENERATE_OUTPUT_TAB) {} virtual void WidgetDataRefreshReceive(WidgetDataItem_LIMIT_DMUS_TAB) {} // // Input-project related refreshes virtual void WidgetDataRefreshReceive(WidgetDataItem_MANAGE_DMUS_WIDGET) {} virtual void WidgetDataRefreshReceive(WidgetDataItem_MANAGE_UOAS_WIDGET) {} virtual void WidgetDataRefreshReceive(WidgetDataItem_MANAGE_VGS_WIDGET) {} // **************************************************************************************************************************** protected: // **************************************************************************************************************************** // Pseudo-signals. // The following base class functions are not necessary. // However, they do assist in assuring that derived classes use the same naming scheme. // At some point, errors could be added to these otherwise empty functions to further // encourage the proper naming scheme in derived classes. // // Output-project related refreshes virtual void RefreshWidget(WidgetDataItemRequest_VARIABLE_GROUPS_SCROLL_AREA) {} virtual void RefreshWidget(WidgetDataItemRequest_VARIABLE_GROUPS_TOOLBOX) {} virtual void RefreshWidget(WidgetDataItemRequest_VARIABLE_GROUP_VARIABLE_GROUP_INSTANCE) {} virtual void RefreshWidget(WidgetDataItemRequest_VARIABLE_GROUPS_SUMMARY_SCROLL_AREA) {} virtual void RefreshWidget(WidgetDataItemRequest_VARIABLE_GROUPS_SUMMARY_VARIABLE_GROUP_INSTANCE) {} virtual void RefreshWidget(WidgetDataItemRequest_KAD_SPIN_CONTROLS_AREA) {} virtual void RefreshWidget(WidgetDataItemRequest_KAD_SPIN_CONTROL_WIDGET) {} virtual void RefreshWidget(WidgetDataItemRequest_TIMERANGE_REGION_WIDGET) {} virtual void RefreshWidget(WidgetDataItemRequest_DATETIME_WIDGET) {} virtual void RefreshWidget(WidgetDataItemRequest_GENERATE_OUTPUT_TAB) {} virtual void RefreshWidget(WidgetDataItemRequest_LIMIT_DMUS_TAB) {} // // Input-project related refreshes virtual void RefreshWidget(WidgetDataItemRequest_MANAGE_DMUS_WIDGET) {} virtual void RefreshWidget(WidgetDataItemRequest_MANAGE_UOAS_WIDGET) {} virtual void RefreshWidget(WidgetDataItemRequest_MANAGE_VGS_WIDGET) {} // **************************************************************************************************************************** public: QWidget * self; WIDGET_NATURE widget_nature; NewGeneUUID uuid; NewGeneUUID uuid_parent; UIInputProject * inp; UIOutputProject * outp; DATA_WIDGETS widget_type; WidgetInstanceIdentifier data_instance; bool top_level; static NewGeneMainWindow * theMainWindow; public: bool IsInputProjectWidget() const; bool IsOutputProjectWidget() const; protected: virtual void Empty() {} protected: bool inputConnected; bool outputConnected; }; class WidgetCreationInfo { public: WidgetCreationInfo( QWidget * const self_, NewGeneWidget::WIDGET_NATURE const widget_nature_ = NewGeneWidget::WIDGET_NATURE::WIDGET_NATURE_UNKNOWN, DATA_WIDGETS const widget_type_ = WIDGET_TYPE_NONE, NewGeneUUID const & uuid_parent_ = "", bool const top_level_ = false, WidgetInstanceIdentifier data_instance_ = WidgetInstanceIdentifier() ) : self(self_) , widget_nature(widget_nature_) , widget_type(widget_type_) , uuid_parent(uuid_parent_) , top_level(top_level_) , data_instance(data_instance_) { } WidgetCreationInfo( QWidget * const self_, QWidget * parent, NewGeneWidget::WIDGET_NATURE const widget_nature_ = NewGeneWidget::WIDGET_NATURE::WIDGET_NATURE_UNKNOWN, DATA_WIDGETS const widget_type_ = WIDGET_TYPE_NONE, bool const top_level_ = false, WidgetInstanceIdentifier data_instance_ = WidgetInstanceIdentifier() ) : self(self_) , widget_nature(widget_nature_) , widget_type(widget_type_) , top_level(top_level_) , data_instance(data_instance_) { if (parent) { try { NewGeneWidget * newgene_parent_widget = dynamic_cast<NewGeneWidget *>(parent); if (newgene_parent_widget) { uuid_parent = newgene_parent_widget->uuid; } } catch (std::bad_cast & bc) { // nothing to do } } } QWidget * self; NewGeneWidget::WIDGET_NATURE widget_nature; DATA_WIDGETS widget_type; NewGeneUUID uuid_parent; bool top_level; // Is this widget class tied into a UI Form, or is it created dynamically in code via "new" from some other widget? WidgetInstanceIdentifier data_instance; }; #include "../q_declare_metatype.h" #endif // NEWGENEWIDGET_H
[ "daniel347x@gmail.com" ]
daniel347x@gmail.com
19f4a87a8d16adbd6149150068885669394e6b8d
303fdef7d8f917541dacd1209d078bbf825dc744
/src/formats/packed/esvcruncher.cpp
de7013538dd42cc84ff405608b4891ec867e1527
[]
no_license
djdron/zxtune
7073149ed166bf8fab5a4eb0b0f6a0e3a07a4adb
b9b14282857451acbd7dcb4f8306a4f6cfabe915
refs/heads/master
2022-12-22T18:54:38.923836
2022-11-21T20:31:19
2022-11-21T20:31:19
15,060,257
7
1
null
null
null
null
UTF-8
C++
false
false
13,013
cpp
/** * * @file * * @brief ESVCruncher packer support * * @author vitamin.caig@gmail.com * * @note Based on XLook sources by HalfElf * **/ // local includes #include "formats/packed/container.h" #include "formats/packed/pack_utils.h" // common includes #include <byteorder.h> #include <make_ptr.h> #include <pointers.h> // library includes #include <binary/format_factories.h> #include <formats/packed.h> #include <math/numeric.h> // std includes #include <algorithm> #include <functional> #include <iterator> #include <numeric> namespace Formats::Packed { namespace ESVCruncher { const std::size_t MAX_DECODED_SIZE = 0xc000; const Char DESCRIPTION[] = "ESV Cruncher"; const auto DEPACKER_PATTERN = //$=6978 // depack to 9900/61a8 "?" // di/nop "21??" // ld hl,xxxx 698f/698f "11??" // ld de,xxxx 6000/5b00 "01a300" // ld bc,0x00a3 rest depacker size "d5" // push de "edb0" // ldir "21??" // ld hl,xxxx last/first of packed (data = +#0e) 89b6/6a32 "11??" // ld de,xxxx last/first dst of packed (data = +#11) b884/61a7 "01??" // ld bc,xxxx size of packed (data = +#14) 1f85/0815 "c9" // ret "ed?" // lddr/lddr +0x17 b8/b0 "21??" // ld hl,xxxx last of packed (data = +#1a) b884/69bb "010801" // ld bc,xxxx 0108 "d9" // exx "e5" // push hl "11??" // ld de,xxxx last of depacked (data = +#22) f929/72bb "210100" // ld hl,xxxx 0001 /* "cd??" // call getbit 6099 "44" // ld b,h "3025" // jr nc,xxxx "45" // ld b,l "2c" // inc l "cd??" // call getbit 6099 "382f" // jr c,xx "04" // inc b "2e04" // ld l,xx "cd??" // call getbit 6099 "3827" // jr c,xx "cd??" // call getbit 6099 "301e" // jr nc,xxxx "45" // ld b,l "cd??" // call getbits 608c "c608" // ld a,xx "6f" // ld l,a "1820" // jr xxxx "0605" // ld b,xx "cd??" // call getbits 608c "c60a" // ld a,xx "6f" // ld l,a "4d" // ld c,l "d9" // exx "e5" // push hl "d9" // exx "e1" // pop hl "edb8" // lddr "e5" // push hl "d9" // exx "e1" // pop hl "d9" // exx "1836" // jr xxxx "2e18" // ld l,xx "0608" // ld b,xx "cd??" // call getbits 608c "09" // add hl,bc "3c" // inc a "28f7" // jr z,xx "e5" // push hl "cd??" // call getbit 6099 "212100" // ld hl,xxxx 0021 "380f" // jr c,xx "0609" // ld b,xx "19" // add hl,de "cd??" // call xxxx 6099 "3013" // jr nc,xxxx "0605" // ld b,xx "6b" // ld l,e "62" // ld h,d "23" // inc hl "180c" // jr xxxx "2602" // ld h,xx "c1" // pop bc "79" // ld a,c "94" // sub h "b0" // or b "28c0" // jr z,xx "c5" // push bc "06?" // ld b,xx ; window size (data = +0x8c) "19" // add hl,de "cd??" // call xxxx 608c "09" // add hl,bc "c1" // pop bc "edb8" // lddr "21??" // ld hl,xxxx ; start of packed-1 (data = + 98ff/61a7 "ed52" // sbc hl,de "da??" // jp c,xxxx "e1" // pop hl "d9" // exx "?" // di/ei/nop "c3??" // jp xxxx 0052/61a8 //getbits "af" // xor a "4f" // ld c,a "cd??" // call xxxx 6099 "cb11" // rl c "17" // lra "10f8" // djnz xx "47" // ld b,a "79" // ld a,c "c9" // ret //getbit "d9" // exx "1003" // djnz xx "41" // ld b,c "5e" // ld e,(hl) "2b" // dec hl "cb13" // rl e "d9" // exx "c9" // ret */ ""_sv; struct RawHeader { //+0x00 uint8_t Padding1[0x0e]; //+0x0e le_uint16_t PackedSource; //+0x10 uint8_t Padding2; //+0x11 le_uint16_t PackedTarget; //+0x13 uint8_t Padding3; //+0x14 le_uint16_t SizeOfPacked; //+0x16 uint8_t Padding4[2]; //+0x18 uint8_t PackedDataCopyDirection; //+0x19 uint8_t Padding5; //+0x1a le_uint16_t LastOfPacked; //+0x1c uint8_t Padding6[0x6]; //+0x22 le_uint16_t LastOfDepacked; //+0x24 uint8_t Padding7[0x68]; //+0x8c uint8_t WindowSize; //+0x8d uint8_t Padding8[9]; //+0x96 le_uint16_t DepackedLimit; // depacked - 1 //+0x98 uint8_t Padding9[0x22]; //+0xba uint8_t Data[1]; }; static_assert(sizeof(RawHeader) * alignof(RawHeader) == 0xba + 1, "Invalid layout"); const std::size_t MIN_SIZE = sizeof(RawHeader); // dsq bitstream decoder class Bitstream { public: Bitstream(const uint8_t* data, std::size_t size) : Data(data) , Pos(Data + size) , Bits() , Mask(0) {} bool Eof() const { return Pos < Data; } uint8_t GetByte() { return Eof() ? 0 : *--Pos; } uint_t GetBit() { if (!(Mask >>= 1)) { Bits = GetByte(); Mask = 0x80; } return Bits & Mask ? 1 : 0; } uint_t GetBits(uint_t count) { uint_t result = 0; while (count--) { result = 2 * result | GetBit(); } return result; } private: const uint8_t* const Data; const uint8_t* Pos; uint_t Bits; uint_t Mask; }; class Container { public: Container(const void* data, std::size_t size) : Data(static_cast<const uint8_t*>(data)) , Size(size) {} bool FastCheck() const { if (Size < sizeof(RawHeader)) { return false; } const RawHeader& header = GetHeader(); if (!Math::InRange<uint_t>(header.WindowSize, 0x0b, 0x0f)) { return false; } if (header.LastOfDepacked <= ((header.DepackedLimit + 1) & 0xffff)) { return false; } const DataMovementChecker checker(header.PackedSource, header.PackedTarget, header.SizeOfPacked, header.PackedDataCopyDirection); if (!checker.IsValid()) { return false; } if (checker.LastOfMovedData() != header.LastOfPacked) { return false; } const uint_t usedSize = GetUsedSize(); if (Size < usedSize) { return false; } return true; } uint_t GetUsedSize() const { const RawHeader& header = GetHeader(); return sizeof(header) + header.SizeOfPacked - sizeof(header.Data); } const RawHeader& GetHeader() const { assert(Size >= sizeof(RawHeader)); return *safe_ptr_cast<const RawHeader*>(Data); } private: const uint8_t* const Data; const std::size_t Size; }; class DataDecoder { public: explicit DataDecoder(const Container& container) : IsValid(container.FastCheck()) , Header(container.GetHeader()) , Stream(Header.Data, Header.SizeOfPacked) , Result(new Binary::Dump()) , Decoded(*Result) { if (IsValid && !Stream.Eof()) { IsValid = DecodeData(); } } std::unique_ptr<Binary::Dump> GetResult() { return IsValid ? std::move(Result) : std::unique_ptr<Binary::Dump>(); } private: bool DecodeData() { const uint_t unpackedSize = 1 + Header.LastOfDepacked - ((Header.DepackedLimit + 1) & 0xffff); Decoded.reserve(unpackedSize); while (!Stream.Eof() && Decoded.size() < unpackedSize) { if (!Stream.GetBit()) { Decoded.push_back(Stream.GetByte()); } else if (!DecodeCmd()) { return false; } } std::reverse(Decoded.begin(), Decoded.end()); return true; } bool DecodeCmd() { const uint_t len = GetLength(); if (const uint_t off = GetOffset(len)) { return CopyFromBack(off, Decoded, len); } return true; } uint_t GetLength() { //%1 if (Stream.GetBit()) { //%11 return 2 + Stream.GetBit(); } //%10 if (Stream.GetBit()) { //%101 return 4 + Stream.GetBits(2); } //%100 if (Stream.GetBit()) { //%1001 return 8 + Stream.GetBits(4); } //%1000 uint_t res = 0x18; for (uint_t add = 0xff; add == 0xff;) { add = Stream.GetBits(8); res += add; } return res; } uint_t GetOffset(uint_t len) { if (Stream.GetBit()) { //%1 if (2 != len) { return 0x221 + Stream.GetBits(Header.WindowSize); } const uint_t size = 0x0a + Stream.GetBits(5); std::generate_n(std::back_inserter(Decoded), size, std::bind(&Bitstream::GetByte, &Stream)); return 0; } //%0 if (Stream.GetBit()) { //%01 return 1 + Stream.GetBits(5); } //%00 return 0x21 + Stream.GetBits(9); } private: bool IsValid; const RawHeader& Header; Bitstream Stream; std::unique_ptr<Binary::Dump> Result; Binary::Dump& Decoded; }; } // namespace ESVCruncher class ESVCruncherDecoder : public Decoder { public: ESVCruncherDecoder() : Depacker(Binary::CreateFormat(ESVCruncher::DEPACKER_PATTERN, ESVCruncher::MIN_SIZE)) {} String GetDescription() const override { return ESVCruncher::DESCRIPTION; } Binary::Format::Ptr GetFormat() const override { return Depacker; } Container::Ptr Decode(const Binary::Container& rawData) const override { if (!Depacker->Match(rawData)) { return Container::Ptr(); } const ESVCruncher::Container container(rawData.Start(), rawData.Size()); if (!container.FastCheck()) { return Container::Ptr(); } ESVCruncher::DataDecoder decoder(container); return CreateContainer(decoder.GetResult(), container.GetUsedSize()); } private: const Binary::Format::Ptr Depacker; }; Decoder::Ptr CreateESVCruncherDecoder() { return MakePtr<ESVCruncherDecoder>(); } } // namespace Formats::Packed
[ "vitamin.caig@gmail.com" ]
vitamin.caig@gmail.com
3853a16252c63db67821a028ffb7c19c0d9601bf
3e6dcff8ede0a9b4047d374267340e6bb5da1689
/goods.h
cc2ce2176779c16882b3d6ed58cb5416e847b1db
[]
no_license
hskim-mma/code_review
db2e0e17b0cdf66648a20dcb111d725a2c9692fd
c20d9c2f3066189efcab0691b0c975f5fd56e5fe
refs/heads/master
2020-07-27T21:50:36.911942
2019-09-18T07:08:24
2019-09-18T07:08:24
209,225,671
0
1
null
null
null
null
UTF-8
C++
false
false
677
h
#ifndef GOODS_H_ #define GOODS_H_ // Goods class for representing goods information with index and price // Example: // Goods test; // test.SetGoodsInfo(1, 10000); // std::cout << test.GetIndex() << " - " << test.GetPrice << endl; class Goods{ public: Goods(int index, int price) { if (index < 0) || (price < 0)) { goods_index_ = 0; goods_price_ = 0; cout << "index and price can't be minus value" << endl; } else { goods_index = index; goods_price = price; } } void SetGoodsInfo(int index, int price); int GetIndex(); int GetPrice(); private: int goods_index_ = 0; int goods_price_ = 0; }; #endif // GOODS_H_
[ "noreply@github.com" ]
noreply@github.com
b9e8b69ba54e1fb44c0eb5f4a6049c87bc529173
9a94e85ef2820d626cd76123b9aa49190c991003
/HSPF_MRO_ANDR/build/Android/Release/app/src/main/include/Fuse.Animations.ContinuousTrackProvider.h
a199044987827169c8a01dede806fed2b67d4f3a
[]
no_license
jaypk-104/FUSE
448db1717a29052f7b551390322a6167dfea34cd
0464afa07998eea8de081526a9337bd9af42dcf3
refs/heads/master
2023-03-13T14:32:43.855977
2021-03-18T01:57:10
2021-03-18T01:57:10
348,617,284
0
0
null
null
null
null
UTF-8
C++
false
false
1,637
h
// This file was generated based on /usr/local/share/uno/Packages/Fuse.Animations/1.12.0/TrackAnimator.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Fuse.Animations.TrackProvider.h> #include <Uno.Object.h> namespace g{namespace Fuse{namespace Animations{struct TrackAnimatorState;}}} namespace g{namespace Uno{struct Float4;}} namespace g{ namespace Fuse{ namespace Animations{ // internal abstract interface ContinuousTrackProvider // { uInterfaceType* ContinuousTrackProvider_typeof(); struct ContinuousTrackProvider { void(*fp_GetSeekProgress)(uObject*, ::g::Fuse::Animations::TrackAnimatorState*, double*, double*, int32_t*, ::g::Uno::Float4*, double*, int32_t*); void(*fp_GetSeekTime)(uObject*, ::g::Fuse::Animations::TrackAnimatorState*, double*, double*, int32_t*, ::g::Uno::Float4*, double*, int32_t*); static int32_t GetSeekProgress(const uInterface& __this, ::g::Fuse::Animations::TrackAnimatorState* tas, double progress, double interval, int32_t dir, ::g::Uno::Float4* value, double* strength) { int32_t __retval; return __this.VTable<ContinuousTrackProvider>()->fp_GetSeekProgress(__this, tas, &progress, &interval, &dir, value, strength, &__retval), __retval; } static int32_t GetSeekTime(const uInterface& __this, ::g::Fuse::Animations::TrackAnimatorState* tas, double elapsed, double interval, int32_t dir, ::g::Uno::Float4* value, double* strength) { int32_t __retval; return __this.VTable<ContinuousTrackProvider>()->fp_GetSeekTime(__this, tas, &elapsed, &interval, &dir, value, strength, &__retval), __retval; } }; // } }}} // ::g::Fuse::Animations
[ "sommelier0052@gmail.com" ]
sommelier0052@gmail.com
ed02169b4b4aac75070c54f810fad3c1cb7211e7
e8b1ee7746bc8ed75ed08a8ef41c3be2dbd5f2ba
/Archive/Arduino/Car/Legacycode/ObjectOreinted/TestCode/testdriveOO/ControlOutputs00.cpp
b99f5c0b02f5002349e46b50edaa45adb188c408
[]
no_license
julianblanco/objeeAirlines
ac2b254603eaf4681da81e0d1d2096f2faec0239
f6e19ca61ea7f44b8abc7e06c4d81c1964cedb43
refs/heads/master
2021-01-20T15:30:46.613900
2017-05-09T23:25:33
2017-05-09T23:25:33
90,778,550
0
0
null
null
null
null
UTF-8
C++
false
false
1,767
cpp
#include "ControlOutputs.h" //=================================================================== // // Program: ControlOutputs.cpp // // Author: Julian Blanco // Date: Sep 4 2015 // // Description: Description // //=================================================================== void execute_control(float heading_error) { update_motors(heading_error); } // Calculate the current error between the current and desired headings float control_output(float current_heading, float target_heading) { float heading_error; // Calculate the heading error given the target and current headings heading_error = target_heading - current_heading; if ( heading_error >= 180) heading_error = heading_error - 360; if ( heading_error < -180) heading_error = heading_error + 360; return (heading_error); } // Calculate control response and send control output to the motors int update_motors(float heading_error) { // Calculate left/right motor response (positive -> right) int response = (int)P_COEF * (int)heading_error; // Write responses to each motor #ifdef ENABLE_MOTORS #ifdef ANALOG_MOTORS int PWM_left = velocidad - (int)response; int PWM_right = velocidad + (int)response; // Bound PWM values if (PWM_left > 255) PWM_left = 255; else if (PWM_left < 0) PWM_left = 0; if (PWM_right > 255) PWM_right = 255; else if (PWM_right < 0) PWM_right = 0; analogWrite(LeftMotor, PWM_left ); analogWrite(RightMotor, PWM_right); #endif #ifdef PWM_MOTOR int steer = response + 1500; // Bound PWM output if(steer < 1200) steer = 1200; else if (steer > 1800) steer = 1800; //steer = map(steer,1200,1800,1800,1200); steer = 1600; return steer; #endif // PWM_MOTOR #endif // ENABLE_MOTORS }
[ "julianblanco@bitbucket.com" ]
julianblanco@bitbucket.com
5f0b14b0e1c94eafbfb5440218dcc4bb0a616684
8afb5afd38548c631f6f9536846039ef6cb297b9
/_REPO/MICROSOFT/PowerToys/src/modules/colorPicker/ColorPicker/dllmain.cpp
57bc5a89e72cb8f923ca0f2a6330b9aead74b017
[ "MIT", "BSL-1.0", "Unlicense", "LicenseRef-scancode-generic-cla" ]
permissive
bgoonz/UsefulResourceRepo2.0
d87588ffd668bb498f7787b896cc7b20d83ce0ad
2cb4b45dd14a230aa0e800042e893f8dfb23beda
refs/heads/master
2023-03-17T01:22:05.254751
2022-08-11T03:18:22
2022-08-11T03:18:22
382,628,698
10
12
MIT
2022-10-10T14:13:54
2021-07-03T13:58:52
null
UTF-8
C++
false
false
8,515
cpp
// dllmain.cpp : Defines the entry point for the DLL application. #include "pch.h" #include <interface/powertoy_module_interface.h> #include "trace.h" #include "Generated Files/resource.h" #include <common/logger/logger.h> #include <common/SettingsAPI/settings_objects.h> #include <common/utils/resources.h> #include <colorPicker/ColorPicker/ColorPickerConstants.h> #include <common/interop/shared_constants.h> #include <common/utils/logger_helper.h> #include <common/utils/winapi_error.h> BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: Trace::RegisterProvider(); case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: break; case DLL_PROCESS_DETACH: Trace::UnregisterProvider(); break; } return TRUE; } namespace { const wchar_t JSON_KEY_PROPERTIES[] = L"properties"; const wchar_t JSON_KEY_WIN[] = L"win"; const wchar_t JSON_KEY_ALT[] = L"alt"; const wchar_t JSON_KEY_CTRL[] = L"ctrl"; const wchar_t JSON_KEY_SHIFT[] = L"shift"; const wchar_t JSON_KEY_CODE[] = L"code"; const wchar_t JSON_KEY_ACTIVATION_SHORTCUT[] = L"ActivationShortcut"; } struct ModuleSettings { } g_settings; class ColorPicker : public PowertoyModuleIface { private: bool m_enabled = false; std::wstring app_name; //contains the non localized key of the powertoy std::wstring app_key; HANDLE m_hProcess; // Time to wait for process to close after sending WM_CLOSE signal static const int MAX_WAIT_MILLISEC = 10000; HANDLE send_telemetry_event; Hotkey m_hotkey; // Handle to event used to invoke ColorPicker HANDLE m_hInvokeEvent; void parse_hotkey(PowerToysSettings::PowerToyValues& settings) { auto settingsObject = settings.get_raw_json(); if (settingsObject.GetView().Size()) { try { auto jsonHotkeyObject = settingsObject.GetNamedObject(JSON_KEY_PROPERTIES).GetNamedObject(JSON_KEY_ACTIVATION_SHORTCUT); m_hotkey.win = jsonHotkeyObject.GetNamedBoolean(JSON_KEY_WIN); m_hotkey.alt = jsonHotkeyObject.GetNamedBoolean(JSON_KEY_ALT); m_hotkey.shift = jsonHotkeyObject.GetNamedBoolean(JSON_KEY_SHIFT); m_hotkey.ctrl = jsonHotkeyObject.GetNamedBoolean(JSON_KEY_CTRL); m_hotkey.key = static_cast<unsigned char>(jsonHotkeyObject.GetNamedNumber(JSON_KEY_CODE)); } catch (...) { Logger::error("Failed to initialize ColorPicker start shortcut"); } } else { Logger::info("ColorPicker settings are empty"); } if (!m_hotkey.key) { Logger::info("ColorPicker is going to use default shortcut"); m_hotkey.win = true; m_hotkey.alt = false; m_hotkey.shift = true; m_hotkey.ctrl = false; m_hotkey.key = 'C'; } } bool is_process_running() { return WaitForSingleObject(m_hProcess, 0) == WAIT_TIMEOUT; } void launch_process() { Logger::trace(L"Starting ColorPicker process"); unsigned long powertoys_pid = GetCurrentProcessId(); std::wstring executable_args = L""; executable_args.append(std::to_wstring(powertoys_pid)); SHELLEXECUTEINFOW sei{ sizeof(sei) }; sei.fMask = { SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_NO_UI }; sei.lpFile = L"modules\\ColorPicker\\ColorPickerUI.exe"; sei.nShow = SW_SHOWNORMAL; sei.lpParameters = executable_args.data(); if (ShellExecuteExW(&sei)) { Logger::trace("Successfully started the Color Picker process"); } else { Logger::error( L"ColorPicker failed to start. {}", get_last_error_or_default(GetLastError())); } m_hProcess = sei.hProcess; } // Load the settings file. void init_settings() { try { // Load and parse the settings file for this PowerToy. PowerToysSettings::PowerToyValues settings = PowerToysSettings::PowerToyValues::load_from_settings_file(get_key()); parse_hotkey(settings); } catch (std::exception ex) { Logger::warn(L"An exception occurred while loading the settings file"); // Error while loading from the settings file. Let default values stay as they are. } } public: ColorPicker() { app_name = GET_RESOURCE_STRING(IDS_COLORPICKER_NAME); app_key = ColorPickerConstants::ModuleKey; LoggerHelpers::init_logger(app_key, L"ModuleInterface", "ColorPicker"); send_telemetry_event = CreateDefaultEvent(CommonSharedConstants::COLOR_PICKER_SEND_SETTINGS_TELEMETRY_EVENT); m_hInvokeEvent = CreateDefaultEvent(CommonSharedConstants::SHOW_COLOR_PICKER_SHARED_EVENT); init_settings(); } ~ColorPicker() { if (m_enabled) { } m_enabled = false; } // Destroy the powertoy and free memory virtual void destroy() override { Logger::trace("ColorPicker::destroy()"); delete this; } // Return the localized display name of the powertoy virtual const wchar_t* get_name() override { return app_name.c_str(); } // Return the non localized key of the powertoy, this will be cached by the runner virtual const wchar_t* get_key() override { return app_key.c_str(); } virtual bool get_config(wchar_t* buffer, int* buffer_size) override { HINSTANCE hinstance = reinterpret_cast<HINSTANCE>(&__ImageBase); // Create a Settings object. PowerToysSettings::Settings settings(hinstance, get_name()); settings.set_description(GET_RESOURCE_STRING(IDS_COLORPICKER_SETTINGS_DESC)); settings.set_overview_link(L"https://aka.ms/PowerToysOverview_ColorPicker"); return settings.serialize_to_buffer(buffer, buffer_size); } virtual void call_custom_action(const wchar_t* action) override { } virtual void set_config(const wchar_t* config) override { try { // Parse the input JSON string. PowerToysSettings::PowerToyValues values = PowerToysSettings::PowerToyValues::from_json_string(config, get_key()); parse_hotkey(values); // If you don't need to do any custom processing of the settings, proceed // to persists the values calling: values.save_to_settings_file(); // Otherwise call a custom function to process the settings before saving them to disk: // save_settings(); } catch (std::exception ex) { // Improper JSON. } } virtual void enable() { Logger::trace("ColorPicker::enable()"); ResetEvent(send_telemetry_event); ResetEvent(m_hInvokeEvent); launch_process(); m_enabled = true; }; virtual void disable() { Logger::trace("ColorPicker::disable()"); if (m_enabled) { ResetEvent(send_telemetry_event); ResetEvent(m_hInvokeEvent); TerminateProcess(m_hProcess, 1); } m_enabled = false; } virtual bool on_hotkey(size_t hotkeyId) override { if (m_enabled) { Logger::trace(L"ColorPicker hotkey pressed"); if (!is_process_running()) { launch_process(); } SetEvent(m_hInvokeEvent); return true; } return false; } virtual size_t get_hotkeys(Hotkey* hotkeys, size_t buffer_size) override { if (m_hotkey.key) { if (hotkeys && buffer_size >= 1) { hotkeys[0] = m_hotkey; } return 1; } else { return 0; } } virtual bool is_enabled() override { return m_enabled; } virtual void send_settings_telemetry() override { SetEvent(send_telemetry_event); } }; extern "C" __declspec(dllexport) PowertoyModuleIface* __cdecl powertoy_create() { return new ColorPicker(); }
[ "bryan.guner@gmail.com" ]
bryan.guner@gmail.com
d65e8133fb681011854dfe1facc75c09bbb9cd77
f57a583d41ddf3bf4e8a96e32f38de9d83ff6ae8
/zmq3/router_dealer_server_msg.cpp
f0b44f91c2a64ef45e251d2622edf71260a33031
[]
no_license
sansajn/test
5bc34a7e8ef21ba600f22ea258f6c75e42ce4c4e
c1bed95984123d90ced1376a6de93e3bb37fac76
refs/heads/master
2023-09-01T00:04:48.222555
2023-08-22T15:14:34
2023-08-22T15:14:34
224,257,205
2
3
null
null
null
null
UTF-8
C++
false
false
1,431
cpp
// spojenie typu ROUTER <-> DEALER, serverovska cast implementovana v zmq // za pouzitia zmq_msg_t struktury nameisto char* buffrou #include <string> #include <iostream> #include <cassert> #include <zmq.h> using std::string; using std::cout; int main(int argc, char * argv[]) { void * ctx = zmq_ctx_new(); void * socket = zmq_socket(ctx, ZMQ_ROUTER); int rc = zmq_bind(socket, "tcp://*:5557"); assert(rc == 0 && "unsuccessful binding"); while (true) { // odpoved pride ako (identity, message) zmq_msg_t identity; int rc = zmq_msg_init(&identity); assert(rc == 0); rc = zmq_msg_recv(&identity, socket, 0); assert(rc != -1); assert(rc == zmq_msg_size(&identity)); string s((char *)zmq_msg_data(&identity), zmq_msg_size(&identity)); cout << "identity: " << s << std::endl; // zisti, ci je sprav viac int more; size_t option_len = sizeof(more); rc = zmq_getsockopt(socket, ZMQ_RCVMORE, &more, &option_len); assert(rc == 0); assert(more == 1 && "este cakam spravu"); if (more) { zmq_msg_t msg; zmq_msg_init(&msg); rc = zmq_msg_recv(&msg, socket, 0); assert(rc != -1); assert(rc == zmq_msg_size(&msg)); string s((char *)zmq_msg_data(&msg), zmq_msg_size(&msg)); cout << "message: " << s << std::endl; zmq_msg_close(&msg); } // answer zmq_msg_send(&identity, socket, ZMQ_SNDMORE); zmq_send(socket, "world", 5, 0); zmq_msg_close(&identity); } return 0; }
[ "adam.hlavatovic@protonmail.ch" ]
adam.hlavatovic@protonmail.ch
f542f9f27b4441a341f75509d1acdfe1e0b0776c
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/chromium_org/printing/print_settings_initializer_win.h
fcbacc280f2c9ec5bcbeac4a68f8b64ffa8b1f5c
[ "MIT", "BSD-3-Clause" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
C++
false
false
923
h
// 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. #ifndef PRINTING_PRINTING_SETTINGS_INITIALIZER_WIN_H_ #define PRINTING_PRINTING_SETTINGS_INITIALIZER_WIN_H_ #include <string> #include "base/logging.h" #include "printing/page_range.h" typedef struct HDC__* HDC; typedef struct _devicemodeW DEVMODE; namespace printing { class PrintSettings; // Initializes a PrintSettings object from the provided device context. class PRINTING_EXPORT PrintSettingsInitializerWin { public: static void InitPrintSettings(HDC hdc, const DEVMODE& dev_mode, PrintSettings* print_settings); private: DISALLOW_IMPLICIT_CONSTRUCTORS(PrintSettingsInitializerWin); }; } // namespace printing #endif // PRINTING_PRINTING_SETTINGS_INITIALIZER_WIN_H_
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
458bddc7d1cbfe65c5f98a9aef79a10979fcf79a
815b7ab9da91efff32eff7ac21d5ce9234ea66a1
/libraries/Adafruit-GFX-Library/Adafruit_SPITFT.cpp
5750a641d6fa79047e67b7b69db9233e3437e034
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
hyunhan3008/Internet-Of-Things---TV-B-Gone
df17722fa592f119c8f2c3cb78c10268d786b9ee
45b2c795fc9d47b400f2e9680bb55ccd0df13ac3
refs/heads/master
2020-05-31T17:58:10.105844
2019-08-12T15:31:31
2019-08-12T15:31:31
190,422,722
1
0
null
null
null
null
UTF-8
C++
false
false
19,427
cpp
// Adafruit_SPITFT.cpp // DON'T EDIT FROM HERE TO "END" // (this stuff is injected to support unPhone's TCA9555 IO expander chip) #include <Wire.h> // (we need digitalRead etc. defined before redefining) class IOExpander { // this is an excerpt of the full definition that... public: // ...just declares the injected methods static void pinMode(uint8_t pin, uint8_t mode); static void digitalWrite(uint8_t pin, uint8_t value); static uint8_t digitalRead(uint8_t pin); }; #define digitalWrite IOExpander::digitalWrite // call... #define digitalRead IOExpander::digitalRead // ...ours... #define pinMode IOExpander::pinMode // ...please // END -- normal library code follows /*! * @file Adafruit_SPITFT.cpp * * @mainpage Adafruit SPI TFT Displays * * @section intro_sec Introduction This is our library for generic SPI TFT Displays with address windows and 16 bit color (e.g. ILI9341, HX8357D, ST7735...) Check out the links above for our tutorials and wiring diagrams These displays use SPI to communicate, 4 or 5 pins are required to interface (RST is optional) Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! Written by Limor Fried/Ladyada for Adafruit Industries. MIT license, all text above must be included in any redistribution * @section dependencies Dependencies * * This library depends on <a href="https://github.com/adafruit/Adafruit_GFX"> * Adafruit_GFX</a> being present on your system. Please make sure you have * installed the latest version before using this library. * * @section author Author * * Written by Limor "ladyada" Fried for Adafruit Industries. * * @section license License * * BSD license, all text here must be included in any redistribution. * */ #if !defined(__AVR_ATtiny85__) // NOT A CHANCE of this stuff working on ATtiny #include "Adafruit_SPITFT.h" #if !defined(ARDUINO_STM32_FEATHER) #include "pins_arduino.h" #endif #if !defined(ARDUINO_STM32_FEATHER) && !defined(RASPI) #include "wiring_private.h" #endif #include <limits.h> #include "Adafruit_SPITFT_Macros.h" /**************************************************************************/ /*! @brief Pass 8-bit (each) R,G,B, get back 16-bit packed color This function converts 8-8-8 RGB data to 16-bit 5-6-5 @param red Red 8 bit color @param green Green 8 bit color @param blue Blue 8 bit color @return Unsigned 16-bit down-sampled color in 5-6-5 format */ /**************************************************************************/ uint16_t Adafruit_SPITFT::color565(uint8_t red, uint8_t green, uint8_t blue) { return ((red & 0xF8) << 8) | ((green & 0xFC) << 3) | ((blue & 0xF8) >> 3); } /**************************************************************************/ /*! @brief Instantiate Adafruit SPI display driver with software SPI @param w Display width in pixels @param h Display height in pixels @param cs Chip select pin # @param dc Data/Command pin # @param mosi SPI MOSI pin # @param sclk SPI Clock pin # @param rst Reset pin # (optional, pass -1 if unused) @param miso SPI MISO pin # (optional, pass -1 if unused) */ /**************************************************************************/ Adafruit_SPITFT::Adafruit_SPITFT(uint16_t w, uint16_t h, int8_t cs, int8_t dc, int8_t mosi, int8_t sclk, int8_t rst, int8_t miso) : Adafruit_GFX(w, h) { _cs = cs; _dc = dc; _rst = rst; _sclk = sclk; _mosi = mosi; _miso = miso; _freq = 0; #ifdef USE_FAST_PINIO dcport = (RwReg *)portOutputRegister(digitalPinToPort(dc)); dcpinmask = digitalPinToBitMask(dc); clkport = (RwReg *)portOutputRegister(digitalPinToPort(sclk)); clkpinmask = digitalPinToBitMask(sclk); mosiport = (RwReg *)portOutputRegister(digitalPinToPort(mosi)); mosipinmask = digitalPinToBitMask(mosi); if(miso >= 0){ misoport = (RwReg *)portInputRegister(digitalPinToPort(miso)); misopinmask = digitalPinToBitMask(miso); } else { misoport = 0; misopinmask = 0; } if(cs >= 0) { csport = (RwReg *)portOutputRegister(digitalPinToPort(cs)); cspinmask = digitalPinToBitMask(cs); } else { // No chip-select line defined; might be permanently tied to GND. // Assign a valid GPIO register (though not used for CS), and an // empty pin bitmask...the nonsense bit-twiddling might be faster // than checking _cs and possibly branching. csport = dcport; cspinmask = 0; } #endif } /**************************************************************************/ /*! @brief Instantiate Adafruit SPI display driver with hardware SPI @param w Display width in pixels @param h Display height in pixels @param cs Chip select pin # @param dc Data/Command pin # @param rst Reset pin # (optional, pass -1 if unused) */ /**************************************************************************/ Adafruit_SPITFT::Adafruit_SPITFT(uint16_t w, uint16_t h, int8_t cs, int8_t dc, int8_t rst) : Adafruit_SPITFT(w, h, &SPI, cs, dc, rst) { // We just call the hardware SPI instantiator with the default SPI device (&SPI) } /**************************************************************************/ /*! @brief Instantiate Adafruit SPI display driver with hardware SPI @param w Display width in pixels @param h Display height in pixels @param spiClass A pointer to an SPI hardware interface, e.g. &SPI1 @param cs Chip select pin # @param dc Data/Command pin # @param rst Reset pin # (optional, pass -1 if unused) */ /**************************************************************************/ Adafruit_SPITFT::Adafruit_SPITFT(uint16_t w, uint16_t h, SPIClass *spiClass, int8_t cs, int8_t dc, int8_t rst) : Adafruit_GFX(w, h) { _cs = cs; _dc = dc; _rst = rst; _spi = spiClass; _sclk = -1; _mosi = -1; _miso = -1; _freq = 0; #ifdef USE_FAST_PINIO clkport = 0; clkpinmask = 0; mosiport = 0; mosipinmask = 0; misoport = 0; misopinmask = 0; dcport = (RwReg *)portOutputRegister(digitalPinToPort(dc)); dcpinmask = digitalPinToBitMask(dc); if(cs >= 0) { csport = (RwReg *)portOutputRegister(digitalPinToPort(cs)); cspinmask = digitalPinToBitMask(cs); } else { // See notes in prior constructor. csport = dcport; cspinmask = 0; } #endif } /**************************************************************************/ /*! @brief Initialiaze the SPI interface (hardware or software) @param freq The desired maximum SPI hardware clock frequency */ /**************************************************************************/ void Adafruit_SPITFT::initSPI(uint32_t freq) { _freq = freq; // Control Pins if(_cs >= 0) { pinMode(_cs, OUTPUT); digitalWrite(_cs, HIGH); // Deselect } pinMode(_dc, OUTPUT); digitalWrite(_dc, LOW); // Software SPI if(_sclk >= 0){ pinMode(_mosi, OUTPUT); digitalWrite(_mosi, LOW); pinMode(_sclk, OUTPUT); digitalWrite(_sclk, HIGH); if(_miso >= 0){ pinMode(_miso, INPUT); } } // Hardware SPI SPI_BEGIN(); // toggle RST low to reset if (_rst >= 0) { pinMode(_rst, OUTPUT); digitalWrite(_rst, HIGH); delay(100); digitalWrite(_rst, LOW); delay(100); digitalWrite(_rst, HIGH); delay(200); } } /**************************************************************************/ /*! @brief Read one byte from SPI interface (hardware or software) @returns One byte, MSB order */ /**************************************************************************/ uint8_t Adafruit_SPITFT::spiRead() { if(_sclk < 0){ return HSPI_READ(); } if(_miso < 0){ return 0; } uint8_t r = 0; for (uint8_t i=0; i<8; i++) { SSPI_SCK_LOW(); SSPI_SCK_HIGH(); r <<= 1; if (SSPI_MISO_READ()){ r |= 0x1; } } return r; } /**************************************************************************/ /*! @brief Write one byte to SPI interface (hardware or software) @param b One byte to send, MSB order */ /**************************************************************************/ void Adafruit_SPITFT::spiWrite(uint8_t b) { if(_sclk < 0){ HSPI_WRITE(b); return; } for(uint8_t bit = 0x80; bit; bit >>= 1){ if((b) & bit){ SSPI_MOSI_HIGH(); } else { SSPI_MOSI_LOW(); } SSPI_SCK_LOW(); SSPI_SCK_HIGH(); } } /* * Transaction API * */ /**************************************************************************/ /*! @brief Begin an SPI transaction & set CS low. */ /**************************************************************************/ void inline Adafruit_SPITFT::startWrite(void){ SPI_BEGIN_TRANSACTION(); SPI_CS_LOW(); } /**************************************************************************/ /*! @brief Begin an SPI transaction & set CS high. */ /**************************************************************************/ void inline Adafruit_SPITFT::endWrite(void){ SPI_CS_HIGH(); SPI_END_TRANSACTION(); } /**************************************************************************/ /*! @brief Write a command byte (must have a transaction in progress) @param cmd The 8-bit command to send */ /**************************************************************************/ void Adafruit_SPITFT::writeCommand(uint8_t cmd){ SPI_DC_LOW(); spiWrite(cmd); SPI_DC_HIGH(); } /**************************************************************************/ /*! @brief Push a 2-byte color to the framebuffer RAM, will start transaction @param color 16-bit 5-6-5 Color to draw */ /**************************************************************************/ void Adafruit_SPITFT::pushColor(uint16_t color) { startWrite(); SPI_WRITE16(color); endWrite(); } /**************************************************************************/ /*! @brief Blit multiple 2-byte colors (must have a transaction in progress) @param colors Array of 16-bit 5-6-5 Colors to draw @param len How many pixels to draw - 2 bytes per pixel! */ /**************************************************************************/ void Adafruit_SPITFT::writePixels(uint16_t * colors, uint32_t len){ SPI_WRITE_PIXELS((uint8_t*)colors , len * 2); } /**************************************************************************/ /*! @brief Blit a 2-byte color many times (must have a transaction in progress) @param color The 16-bit 5-6-5 Color to draw @param len How many pixels to draw */ /**************************************************************************/ void Adafruit_SPITFT::writeColor(uint16_t color, uint32_t len){ #ifdef SPI_HAS_WRITE_PIXELS if(_sclk >= 0){ for (uint32_t t=0; t<len; t++){ writePixel(color); } return; } static uint16_t temp[SPI_MAX_PIXELS_AT_ONCE]; size_t blen = (len > SPI_MAX_PIXELS_AT_ONCE)?SPI_MAX_PIXELS_AT_ONCE:len; uint16_t tlen = 0; for (uint32_t t=0; t<blen; t++){ temp[t] = color; } while(len){ tlen = (len>blen)?blen:len; writePixels(temp, tlen); len -= tlen; } #else uint8_t hi = color >> 8, lo = color; if(_sclk < 0){ //AVR Optimization for (uint32_t t=len; t; t--){ HSPI_WRITE(hi); HSPI_WRITE(lo); } return; } for (uint32_t t=len; t; t--){ spiWrite(hi); spiWrite(lo); } #endif } /**************************************************************************/ /*! @brief Write a pixel (must have a transaction in progress) @param x x coordinate @param y y coordinate @param color 16-bit 5-6-5 Color to draw with */ /**************************************************************************/ void Adafruit_SPITFT::writePixel(int16_t x, int16_t y, uint16_t color) { if((x < 0) ||(x >= _width) || (y < 0) || (y >= _height)) return; setAddrWindow(x,y,1,1); writePixel(color); } /**************************************************************************/ /*! @brief Write a filled rectangle (must have a transaction in progress) @param x Top left corner x coordinate @param y Top left corner y coordinate @param w Width in pixels @param h Height in pixels @param color 16-bit 5-6-5 Color to fill with */ /**************************************************************************/ void Adafruit_SPITFT::writeFillRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color){ if((x >= _width) || (y >= _height)) return; int16_t x2 = x + w - 1, y2 = y + h - 1; if((x2 < 0) || (y2 < 0)) return; // Clip left/top if(x < 0) { x = 0; w = x2 + 1; } if(y < 0) { y = 0; h = y2 + 1; } // Clip right/bottom if(x2 >= _width) w = _width - x; if(y2 >= _height) h = _height - y; int32_t len = (int32_t)w * h; setAddrWindow(x, y, w, h); writeColor(color, len); } /**************************************************************************/ /*! @brief Write a perfectly vertical line (must have a transaction in progress) @param x Top-most x coordinate @param y Top-most y coordinate @param h Height in pixels @param color 16-bit 5-6-5 Color to fill with */ /**************************************************************************/ void inline Adafruit_SPITFT::writeFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color){ writeFillRect(x, y, 1, h, color); } /**************************************************************************/ /*! @brief Write a perfectly horizontal line (must have a transaction in progress) @param x Left-most x coordinate @param y Left-most y coordinate @param w Width in pixels @param color 16-bit 5-6-5 Color to fill with */ /**************************************************************************/ void inline Adafruit_SPITFT::writeFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color){ writeFillRect(x, y, w, 1, color); } /**************************************************************************/ /*! @brief Draw a pixel - sets up transaction @param x x coordinate @param y y coordinate @param color 16-bit 5-6-5 Color to draw with */ /**************************************************************************/ void Adafruit_SPITFT::drawPixel(int16_t x, int16_t y, uint16_t color){ startWrite(); writePixel(x, y, color); endWrite(); } /**************************************************************************/ /*! @brief Write a perfectly vertical line - sets up transaction @param x Top-most x coordinate @param y Top-most y coordinate @param h Height in pixels @param color 16-bit 5-6-5 Color to fill with */ /**************************************************************************/ void Adafruit_SPITFT::drawFastVLine(int16_t x, int16_t y, int16_t h, uint16_t color) { startWrite(); writeFastVLine(x, y, h, color); endWrite(); } /**************************************************************************/ /*! @brief Write a perfectly horizontal line - sets up transaction @param x Left-most x coordinate @param y Left-most y coordinate @param w Width in pixels @param color 16-bit 5-6-5 Color to fill with */ /**************************************************************************/ void Adafruit_SPITFT::drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color) { startWrite(); writeFastHLine(x, y, w, color); endWrite(); } /**************************************************************************/ /*! @brief Fill a rectangle completely with one color. @param x Top left corner x coordinate @param y Top left corner y coordinate @param w Width in pixels @param h Height in pixels @param color 16-bit 5-6-5 Color to fill with */ /**************************************************************************/ void Adafruit_SPITFT::fillRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color) { startWrite(); writeFillRect(x,y,w,h,color); endWrite(); } /**************************************************************************/ /*! @brief Invert the display using built-in hardware command @param i True if you want to invert, false to make 'normal' */ /**************************************************************************/ void Adafruit_SPITFT::invertDisplay(boolean i) { startWrite(); writeCommand(i ? invertOnCommand : invertOffCommand); endWrite(); } /**************************************************************************/ /*! @brief Draw a 16-bit image (RGB 5/6/5) at the specified (x,y) position. For 16-bit display devices; no color reduction performed. Adapted from https://github.com/PaulStoffregen/ILI9341_t3 by Marc MERLIN. See examples/pictureEmbed to use this. 5/6/2017: function name and arguments have changed for compatibility with current GFX library and to avoid naming problems in prior implementation. Formerly drawBitmap() with arguments in different order. @param x Top left corner x coordinate @param y Top left corner y coordinate @param pcolors 16-bit array with 16-bit color bitmap @param w Width of bitmap in pixels @param h Height of bitmap in pixels */ /**************************************************************************/ void Adafruit_SPITFT::drawRGBBitmap(int16_t x, int16_t y, uint16_t *pcolors, int16_t w, int16_t h) { int16_t x2, y2; // Lower-right coord if(( x >= _width ) || // Off-edge right ( y >= _height) || // " top ((x2 = (x+w-1)) < 0 ) || // " left ((y2 = (y+h-1)) < 0) ) return; // " bottom int16_t bx1=0, by1=0, // Clipped top-left within bitmap saveW=w; // Save original bitmap width value if(x < 0) { // Clip left w += x; bx1 = -x; x = 0; } if(y < 0) { // Clip top h += y; by1 = -y; y = 0; } if(x2 >= _width ) w = _width - x; // Clip right if(y2 >= _height) h = _height - y; // Clip bottom pcolors += by1 * saveW + bx1; // Offset bitmap ptr to clipped top-left startWrite(); setAddrWindow(x, y, w, h); // Clipped area while(h--) { // For each (clipped) scanline... writePixels(pcolors, w); // Push one (clipped) row pcolors += saveW; // Advance pointer by one full (unclipped) line } endWrite(); } #endif // !__AVR_ATtiny85__
[ "hyunhan9508@gmail.com" ]
hyunhan9508@gmail.com
8f7b253801da5968ec97eb2c6d09efa8f4409677
1de331d068456cedbd2a5b4d4a6b16145646f97d
/src/libv/glr/procedural/cube.hpp
f3acfb49703807c3d71bfc368a4caf2525998d9d
[ "Zlib" ]
permissive
sheerluck/libv
ed37015aeeb49ea8504d7b3aa48a69bde754708f
293e382f459f0acbc540de8ef6283782b38d2e63
refs/heads/master
2023-05-26T01:18:50.817268
2021-04-18T01:06:51
2021-04-27T03:20:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,074
hpp
// Project: libv.glr, File: src/libv/glr/procedural/cube.hpp, Author: Császár Mátyás [Vader] #pragma once // libv #include <libv/math/vec.hpp> namespace libv { namespace glr { // ------------------------------------------------------------------------------------------------- // TODO P5: Possible to make a Triangle Strip version template <typename Precision = float, typename Position, typename Normal, typename Texture0, typename Index> void generateCube(Position& position, Normal& normal, Texture0& texture0, Index& index) { using in = typename Index::value_type; using vec2 = libv::vec2_t<Precision>; using vec3 = libv::vec3_t<Precision>; const in ioffset = static_cast<in>(position.size()); static constexpr std::array data_position = { vec3{-1, -1, 1}, vec3{ 1, -1, 1}, vec3{ 1, 1, 1}, vec3{-1, 1, 1}, vec3{ 1, 1, -1}, vec3{ 1, -1, -1}, vec3{-1, -1, -1}, vec3{-1, 1, -1}, vec3{ 1, 1, 1}, vec3{ 1, 1, -1}, vec3{-1, 1, -1}, vec3{-1, 1, 1}, vec3{-1, -1, -1}, vec3{ 1, -1, -1}, vec3{ 1, -1, 1}, vec3{-1, -1, 1}, vec3{ 1, -1, -1}, vec3{ 1, 1, -1}, vec3{ 1, 1, 1}, vec3{ 1, -1, 1}, vec3{-1, 1, 1}, vec3{-1, 1, -1}, vec3{-1, -1, -1}, vec3{-1, -1, 1}, }; static constexpr std::array data_normal = { vec3{ 0, 0, 1}, vec3{ 0, 0, 1}, vec3{ 0, 0, 1}, vec3{ 0, 0, 1}, vec3{ 0, 0, -1}, vec3{ 0, 0, -1}, vec3{ 0, 0, -1}, vec3{ 0, 0, -1}, vec3{ 0, 1, 0}, vec3{ 0, 1, 0}, vec3{ 0, 1, 0}, vec3{ 0, 1, 0}, vec3{ 0, -1, 0}, vec3{ 0, -1, 0}, vec3{ 0, -1, 0}, vec3{ 0, -1, 0}, vec3{ 1, 0, 0}, vec3{ 1, 0, 0}, vec3{ 1, 0, 0}, vec3{ 1, 0, 0}, vec3{-1, 0, 0}, vec3{-1, 0, 0}, vec3{-1, 0, 0}, vec3{-1, 0, 0}, }; static constexpr std::array data_texture0 = { vec2{0, 0}, vec2{1, 0}, vec2{1, 1}, vec2{0, 1}, vec2{0, 0}, vec2{1, 0}, vec2{1, 1}, vec2{0, 1}, vec2{1, 1}, vec2{1, 0}, vec2{0, 0}, vec2{0, 1}, vec2{1, 1}, vec2{1, 0}, vec2{0, 0}, vec2{0, 1}, vec2{0, 0}, vec2{1, 0}, vec2{1, 1}, vec2{0, 1}, vec2{0, 0}, vec2{1, 0}, vec2{1, 1}, vec2{0, 1}, }; static constexpr std::array data_index = { in{ 0}, in{ 1}, in{ 2}, in{ 2}, in{ 3}, in{ 0}, in{ 4}, in{ 5}, in{ 6}, in{ 6}, in{ 7}, in{ 4}, in{ 8}, in{ 9}, in{10}, in{10}, in{11}, in{ 8}, in{12}, in{13}, in{14}, in{14}, in{15}, in{12}, in{16}, in{17}, in{18}, in{18}, in{19}, in{16}, in{20}, in{21}, in{22}, in{22}, in{23}, in{20}, }; position(data_position); normal(data_normal); texture0(data_texture0); index(data_index); // Adjust indices if geometry was non-empty if (ioffset != 0) for (auto& i : index.view_last(data_index.size())) i += ioffset; } template <typename Precision = float, typename Position, typename Index> void generateInnerCube(Position& position, Index& index) { using in = typename Index::value_type; using vec3 = libv::vec3_t<Precision>; const in ioffset = static_cast<in>(position.size()); static constexpr std::array data_position = { vec3{-1, -1, 1}, vec3{ 1, -1, 1}, vec3{ 1, 1, 1}, vec3{-1, 1, 1}, vec3{ 1, 1, -1}, vec3{ 1, -1, -1}, vec3{-1, -1, -1}, vec3{-1, 1, -1}, vec3{ 1, 1, 1}, vec3{ 1, 1, -1}, vec3{-1, 1, -1}, vec3{-1, 1, 1}, vec3{-1, -1, -1}, vec3{ 1, -1, -1}, vec3{ 1, -1, 1}, vec3{-1, -1, 1}, vec3{ 1, -1, -1}, vec3{ 1, 1, -1}, vec3{ 1, 1, 1}, vec3{ 1, -1, 1}, vec3{-1, 1, 1}, vec3{-1, 1, -1}, vec3{-1, -1, -1}, vec3{-1, -1, 1}, }; static constexpr std::array data_index = { in{ 0}, in{ 2}, in{ 1}, in{ 2}, in{ 0}, in{ 3}, in{ 4}, in{ 6}, in{ 5}, in{ 6}, in{ 4}, in{ 7}, in{ 8}, in{10}, in{ 9}, in{10}, in{ 8}, in{11}, in{12}, in{14}, in{13}, in{14}, in{12}, in{15}, in{16}, in{18}, in{17}, in{18}, in{16}, in{19}, in{20}, in{22}, in{21}, in{22}, in{20}, in{23}, }; position(data_position); index(data_index); // Adjust indices if geometry was non-empty if (ioffset != 0) for (auto& i : index.view_last(data_index.size())) i += ioffset; } // ------------------------------------------------------------------------------------------------- } // namespace glr } // namespace libv
[ "vaderhun@gmail.com" ]
vaderhun@gmail.com
ef66b362a4e606b94c01343e9eea8327dbb08a5a
ae7c0a1a113630cec8936c7a0e19973801acf3a3
/include/QAlg/Components/Operator/PauliOperator.h
40b559ac84b3b63a824e1301dfffed82effbff2b
[ "Apache-2.0" ]
permissive
AmberHan/QPanda-2
d3d97c2e907dfe725bd0d7b6e037ed2b769502ed
a57d39297310f076ad4673dbba4601ae326d3152
refs/heads/master
2020-08-02T21:13:12.801905
2019-09-27T13:47:13
2019-09-27T13:47:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,457
h
/* Copyright (c) 2017-2018 Origin Quantum Computing. All Right Reserved. Licensed under the Apache License 2.0 Author: LiYe Created in 2019-01-22 */ #ifndef PAULIROPERATOR_H #define PAULIROPERATOR_H #include <map> #include <vector> #include "Core/Utilities/QString.h" #include "Core/Utilities/QPandaNamespace.h" #include "QAlg/DataStruct.h" QPANDA_BEGIN template<class T> class PauliOp { public: using PauliItem = std::pair<QPauliPair, T>; using PauliData = std::vector<PauliItem>; using PauliMap = std::map<std::string, T>; public: PauliOp(){} PauliOp(const T &value) { insertData("", value); } PauliOp(double value) { insertData("", T(value)); } PauliOp(const std::string &key, const T &value) { insertData(key, value); } PauliOp(const PauliMap &map) { for (auto iter = map.begin(); iter != map.end(); iter++) { insertData(iter->first, iter->second); } reduceDuplicates(); } PauliOp(PauliOp &&op): m_data(std::move(op.m_data)) { } PauliOp(const PauliOp &op): m_data(op.m_data) { } PauliOp(PauliData &&pauli): m_data(std::move(pauli)) { reduceDuplicates(); } PauliOp(const PauliData &pauli): m_data(pauli) { reduceDuplicates(); } PauliOp &operator = (const PauliOp &op) { m_data = op.m_data; return *this; } PauliOp &operator = (PauliOp &&op) { m_data = std::move(op.m_data); return *this; } PauliOp dagger() const { auto tmp_data = m_data; for (size_t i = 0; i < tmp_data.size(); i++) { auto &item = tmp_data[i]; item.second = T(item.second.real(), -item.second.imag()); } return PauliOp(tmp_data); } PauliOp remapQubitIndex(std::map<size_t, size_t> &index_map) { index_map.clear(); for (size_t i = 0; i < m_data.size(); i++) { auto pair = m_data[i].first; QTerm term = pair.first; for (auto iter = term.begin(); iter != term.end(); iter++) { index_map.insert(std::make_pair(iter->first, 1)); } } size_t cnt = 0; for (auto iter = index_map.begin(); iter != index_map.end(); iter++) { index_map[iter->first] = cnt; cnt++; } PauliData pauli_data; for (size_t i = 0; i < m_data.size(); i++) { QTerm tmp_term; auto pair = m_data[i].first; QTerm term = pair.first; for (auto iter = term.begin(); iter != term.end(); iter++) { tmp_term.insert(std::make_pair(index_map[iter->first], iter->second)); } pauli_data.emplace_back( std::make_pair(QPauliPair(tmp_term, QTerm2StdString(tmp_term)), m_data[i].second)); } return PauliOp(pauli_data); } size_t getMaxIndex() { int max_index = -1; for (size_t i = 0; i < m_data.size(); i++) { auto index_map = m_data[i].first.first; auto iter = index_map.rbegin(); if (iter != index_map.rend()) { if (int(iter->first) > max_index) { max_index = iter->first; } } } max_index++; return max_index; } bool isEmpty() { return m_data.empty(); } bool isAllPauliZorI() { for (size_t i = 0; i < m_data.size(); i++) { auto item = m_data[i]; auto map = item.first.first; for (auto iter = map.begin(); iter != map.end(); iter++) { if ('Z' != iter->second) { return false; } } } return true; } void setErrorThreshold(double threshold) { m_error_threshold = threshold; } double error_threshold() const { return m_error_threshold; } std::string toString() const { std::string str = "{"; for (size_t i = 0; i < m_data.size(); i++) { str += "\n"; auto item = m_data[i]; auto pair = item.first; auto value = item.second; str += pair.second + " : "; if (fabs(value.real()) < m_error_threshold) { str += std::to_string(value.imag()) + "i"; } else if (fabs(value.imag()) < m_error_threshold) { str += std::to_string(value.real()); } else { if (value.imag() < 0) { str += "(" + std::to_string(value.real()) + std::to_string(value.imag()) + "i)"; } else { str += "(" + std::to_string(value.real()) + "+" + std::to_string(value.imag()) + "i)"; } } } if (!m_data.empty()) { str += "\n"; } str += "}"; return str; } PauliData data() const { return m_data; } QHamiltonian toHamiltonian(bool *ok = nullptr) { QHamiltonian hamiltonian; for (size_t i = 0; i < m_data.size(); i++) { auto item = m_data[i]; auto pair = item.first; auto value = item.second; if (fabs(value.imag()) > fabs(m_error_threshold)) { std::cout << "PauliOperator data cannot convert to Hamiltonian." << std::endl; if (ok) { *ok = false; } return QHamiltonian(); } hamiltonian.emplace_back(std::make_pair(pair.first, value.real())); } if (ok) { *ok = true; } return hamiltonian; } PauliOp operator + (const PauliOp &rhs) const { PauliData pauli_data = m_data; pauli_data.insert(pauli_data.end(), rhs.m_data.begin(), rhs.m_data.end()); PauliOp pauli_op(std::move(pauli_data)); return pauli_op; } PauliOp operator - (const PauliOp &rhs) const { PauliData tmp_data = rhs.m_data; for (auto i = 0u; i < tmp_data.size(); i++) { tmp_data[i].second = tmp_data[i].second * T(-1.0,0); } PauliData pauli_data = m_data; pauli_data.insert(pauli_data.end(), tmp_data.begin(), tmp_data.end()); PauliOp pauli_op(std::move(pauli_data)); return pauli_op; } PauliOp operator * (const PauliOp &rhs) const { PauliData pauli_data; PauliData rhs_data = rhs.m_data; for (size_t i = 0; i < m_data.size(); i++) { auto &item_i = m_data[i]; for (size_t j = 0; j < rhs_data.size(); j++) { auto &item_j = rhs_data[j]; auto &map_i = item_i.first.first; auto &map_j = item_j.first.first; auto item = genPauliItem(map_i, map_j, item_i.second * item_j.second); pauli_data.emplace_back(item); } } PauliOp pauli(std::move(pauli_data)); return pauli; } PauliOp &operator +=(const PauliOp &rhs) { m_data.insert(m_data.end(), rhs.m_data.begin(), rhs.m_data.end()); reduceDuplicates(); return *this; } PauliOp &operator -=(const PauliOp &rhs) { PauliData tmp_data = rhs.m_data; for (auto i = 0u; i < tmp_data.size(); i++) { tmp_data[i].second = tmp_data[i].second * T(-1.0,0); } m_data.insert(m_data.end(), tmp_data.begin(), tmp_data.end()); reduceDuplicates(); return *this; } PauliOp &operator *=(const PauliOp &rhs) { PauliData tmp_data; PauliData rhs_data = rhs.m_data; for (size_t i = 0; i < m_data.size(); i++) { auto &item_i = m_data[i]; for (size_t j = 0; j < rhs_data.size(); j++) { auto &item_j = rhs_data[j]; auto &map_i = item_i.first.first; auto &map_j = item_j.first.first; auto item = genPauliItem(map_i, map_j, item_i.second * item_j.second); tmp_data.emplace_back(item); } } m_data = std::move(tmp_data); reduceDuplicates(); return *this; } friend PauliOp operator + (const T &lhs, const PauliOp &rhs) { return rhs + lhs; } friend PauliOp operator - (const T &lhs, const PauliOp &rhs) { PauliData tmp_data = rhs.m_data; for (auto i = 0u; i < tmp_data.size(); i++) { tmp_data[i].second = tmp_data[i].second * T(-1.0,0); } PauliOp tmp(std::move(tmp_data)); return tmp + lhs; } friend PauliOp operator * (const T &lhs, const PauliOp &rhs) { return rhs * lhs; } friend PauliOp operator + (const double &lhs, const PauliOp &rhs) { return rhs + lhs; } friend PauliOp operator - (const double &lhs, const PauliOp &rhs) { PauliData tmp_data = rhs.m_data; for (auto i = 0u; i < tmp_data.size(); i++) { tmp_data[i].second = tmp_data[i].second * T(-1.0,0); } PauliOp tmp(std::move(tmp_data)); return tmp + lhs; } friend PauliOp operator * (const double &lhs, const PauliOp &rhs) { return rhs * lhs; } friend std::ostream &operator <<(std::ostream &out, const PauliOp &rhs) { out << rhs.toString(); return out; } private: QTermPair genQTermPair(const QString &str) const { if (str.size() < 2) { std::string err = "size < 2."; std::cout << err << std::endl; throw err; } char ch = static_cast<char>(toupper(str.at(0))); std::string check_str = "XYZ"; if (check_str.find(ch) == std::string::npos) { std::string err = std::string("Param not in [XYZ]. str: ") + str.data(); std::cout << err << std::endl; throw err; } bool ok = false; auto index = str.mid(1).toInt(&ok); if (!ok) { std::string err = "Convert index to int failed."; std::cout << err << std::endl; throw err; } return QTermPair(index, ch); } void insertData(const std::string &str, const T &value) { QString key(str); auto str_vec = key.split(" ", QString::SkipEmptyParts); if (str_vec.empty()) { QPauliPair pair; pair.first = QTerm(); pair.second = ""; m_data.emplace_back(std::make_pair(pair, value)); return; } QTerm one_term; for (size_t i = 0; i < str_vec.size(); i++) { QTermPair one_pair = genQTermPair(str_vec[i]); if (one_term.find(one_pair.first) != one_term.end()) { std::string err = "Bad param in QPuliMap: Index repeat."; std::cout << err << std::endl; QCERR(err); throw std::invalid_argument(err); } one_term.insert(one_pair); } QPauliPair pair; pair.first = one_term; pair.second = QTerm2StdString(one_term); m_data.emplace_back(std::make_pair(pair, value)); } PauliItem genPauliItem(const QTerm &map_i, const QTerm &map_j, const T &value) const { auto tmp_map = map_i; auto result = value; auto iter_j = map_j.begin(); for (; iter_j != map_j.end(); iter_j++) { auto iter_t = tmp_map.find(iter_j->first); if (iter_t == tmp_map.end()) { tmp_map.insert(*iter_j); } else { std::string tmp = iter_t->second + std::string() + iter_j->second; if (("XX" == tmp) || ("YY" == tmp) || ("ZZ" == tmp)) { tmp_map.erase(iter_t->first); } else if ("XY" == tmp) { result *= complex_d{0, 1}; iter_t->second = 'Z'; } else if ("XZ" == tmp) { result *= complex_d{0, -1}; iter_t->second = 'Y'; } else if ("YX" == tmp) { result *= complex_d{0, -1}; iter_t->second = 'Z'; } else if ("YZ" == tmp) { result *= complex_d{0, 1}; iter_t->second = 'X'; } else if ("ZX" == tmp) { result *= complex_d{0, 1}; iter_t->second = 'Y'; } else if ("ZY" == tmp) { result *= complex_d{0, -1}; iter_t->second = 'X'; } else { std::string err = "Bad para in QPauli."; std::cout << err << std::endl; throw err; } } } QPauliPair pair; pair.first = tmp_map; pair.second = QTerm2StdString(tmp_map); PauliItem item; item.first = pair; item.second = result; return item; } std::string QTerm2StdString(const QTerm &map) const { std::string str; bool next = false; for (auto iter = map.begin(); iter != map.end(); iter++) { if (!next) { next = true; } else { str += " "; } char ch = static_cast<char>(toupper(iter->second)); str += ch + std::to_string(iter->first); } return str; } void reduceDuplicates() { std::map<std::string, T> data_map; std::map<std::string, QTerm> term_map; for (size_t i = 0; i < m_data.size(); i++) { auto item = m_data[i]; auto pair = item.first; auto value = item.second; QTerm term = pair.first; std::string str = pair.second; if (data_map.find(str) != data_map.end()) { data_map[str] = data_map[str] + value; } else { data_map.insert(std::make_pair(str, value)); term_map.insert(std::make_pair(str, term)); } } PauliData pauli_data; for (auto iter = data_map.begin(); iter != data_map.end(); iter++) { auto err = std::abs(iter->second); if (err > fabs(m_error_threshold)) { QPauliPair pair; pair.first = term_map[iter->first]; pair.second = iter->first; pauli_data.emplace_back(std::make_pair(pair, iter->second)); } } m_data = std::move(pauli_data); } private: PauliData m_data; double m_error_threshold{1e-6}; }; using PauliOperator = PauliOp<complex_d>; QPANDA_END #endif // PAULIROPERATOR_H
[ "369038080@qq.com" ]
369038080@qq.com
fcd5e10134afd9e48030fa0782e2fdcafe96502f
d70187d22cbee1d0350acc9d89ccec89374df00c
/Arkanoid/State.h
8aed3490b2fbeea83df9df9d867aa5e056e525ac
[]
no_license
ramses2099/Arkanoid
44c8c369d6b809feea8b65ed08e422eabcfb299e
d8ad672686b235472964f66ef6eea65d188debd6
refs/heads/master
2020-06-27T21:10:16.941290
2019-08-09T15:32:16
2019-08-09T15:32:16
200,050,519
0
0
null
null
null
null
UTF-8
C++
false
false
124
h
#pragma once class GameBaseEntity; class State { public: virtual void Execute(GameBaseEntity* entity, float dt) = 0; };
[ "jose.encarnacion@hit.com.do" ]
jose.encarnacion@hit.com.do
8f23e904b6e0dd2e2d6880a1960d4153eda4d871
56f0b99fa7605b34af0c5c1c860bed492f3f07a8
/Source/BloodyBlade/BaseEnemy.h
af4e0312c4b237f38a90c3e26a02f5ccc682f8c3
[]
no_license
APTist/BloodyBlade
6e5b61eb944fb412ef8e3db7f9938b160cee1251
85a032bf47f5e47c3229dcbfa72fbf6e56918c92
refs/heads/main
2023-08-21T18:40:53.087128
2021-10-11T19:06:37
2021-10-11T19:06:37
413,153,033
0
0
null
null
null
null
UTF-8
C++
false
false
1,417
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Character.h" #include "BaseEnemy.generated.h" UCLASS() class BLOODYBLADE_API ABaseEnemy : public ACharacter { GENERATED_BODY() public: // Sets default values for this character's properties ABaseEnemy(); //Max Health Variable UPROPERTY(BlueprintReadOnly, VisibleAnywhere, Category = Character) float MaxHealth; //Health UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = Character) float Health; //isDead bool UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = Character) bool isDead; //CurrentWeapon UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = Character) AActor* CurrentWeapon; //Damage UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = Character) float Damage; /* FUNCTIONS */ //Dead check func UFUNCTION(BlueprintCallable, Category = Character) virtual void CalculateDead(); //Health Change Func UFUNCTION(BlueprintCallable, Category = Character) virtual void CalculateHealth(float Delta); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; public: // Called every frame virtual void Tick(float DeltaTime) override; // Called to bind functionality to input virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override; };
[ "rikitikitavy39@gmail.com" ]
rikitikitavy39@gmail.com
bb0325cda0a077530cb575280d6944357f7aab20
dfd6e4bb0a6e6b395f3753e11ec2459c8c3b8adc
/Dot_Engine/src/Dot/Renderer/Buffers/Buffer.h
2d1356b86782c674b4fdc791628bd7dbf3786fe0
[ "Apache-2.0" ]
permissive
SimonGido/Dot_Engine
f2bce1d4b85c7aa6bd32afd43618da2b4a29c437
1db28c56eeecefaed8aa3f1d87932765d5b16dd4
refs/heads/master
2022-04-03T08:37:16.832443
2020-02-09T21:30:23
2020-02-09T21:30:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,044
h
#pragma once #include "Dot/Debug/Log.h" #include <glm/glm.hpp> #define D_STATIC_DRAW 0x88E4 #define D_DYNAMIC_DRAW 0x88E8 #define D_STREAM_DRAW 0x88E0 namespace Dot { enum class ShaderDataType { None = 0, Float, Float2, Float3, Float4, Mat3, Mat4, Int, Int2, Int3, Int4, Bool }; static unsigned int ShaderDataTypeSize(ShaderDataType type) { switch (type) { case ShaderDataType::Float: return 4; case ShaderDataType::Float2: return 4 * 2; case ShaderDataType::Float3: return 4 * 3; case ShaderDataType::Float4: return 4 * 4; case ShaderDataType::Mat3: return 4 * 3 * 3; case ShaderDataType::Mat4: return 4 * 4 * 4; case ShaderDataType::Int: return 4; case ShaderDataType::Int2: return 4 * 2; case ShaderDataType::Int3: return 4 * 3; case ShaderDataType::Int4: return 4 * 4; case ShaderDataType::Bool: return 1; } LOG_ERR("Buffer: Unknown ShaderDataType"); return 0; } struct BufferElement { BufferElement(unsigned int Index,ShaderDataType Type, const std::string& Name, unsigned int Divisor = 0, bool Norm = false) :index(Index),type(Type), name(Name), size(ShaderDataTypeSize(type)), divisor(Divisor), offset(0), normalized(Norm) { }; std::string name; ShaderDataType type; unsigned int size; unsigned int offset; unsigned int index; unsigned int divisor; bool normalized; unsigned int GetComponentCount() const { switch (type) { case ShaderDataType::Float: return 1; case ShaderDataType::Float2: return 2; case ShaderDataType::Float3: return 3; case ShaderDataType::Float4: return 4; case ShaderDataType::Mat3: return 3 * 3; case ShaderDataType::Mat4: return 4 * 4; case ShaderDataType::Int: return 1; case ShaderDataType::Int2: return 2; case ShaderDataType::Int3: return 3; case ShaderDataType::Int4: return 4; case ShaderDataType::Bool: return 1; } LOG_ERR("Buffer: Unknown ShaderDataType"); return 0; } }; class BufferLayout { public: BufferLayout() {}; BufferLayout(const std::initializer_list<BufferElement>& elements) : m_elements(elements) { CreateMat4(); CalculateOffsetsAndStride(); }; inline const std::vector<BufferElement>&GetElements() const { return m_elements; } inline const unsigned int GetStride() const { return m_stride; } std::vector<BufferElement>::iterator begin() { return m_elements.begin(); } std::vector<BufferElement>::iterator end() { return m_elements.end(); } std::vector<BufferElement>::const_iterator begin() const { return m_elements.begin(); } std::vector<BufferElement>::const_iterator end() const { return m_elements.end(); } private: void CalculateOffsetsAndStride() { unsigned int offset = 0; m_stride = 0; for (auto& element : m_elements) { element.offset = offset; offset += element.size; m_stride += element.size; } }; void CreateMat4() { for (auto& element : m_elements) { switch (element.type) { case ShaderDataType::Mat4: { element.type = ShaderDataType::Float4; element.size = 4 * 4; BufferElement tmpElement = element; m_elements.push_back(BufferElement(tmpElement.index + 1, tmpElement.type, tmpElement.name, tmpElement.divisor)); m_elements.push_back(BufferElement(tmpElement.index + 2, tmpElement.type, tmpElement.name, tmpElement.divisor)); m_elements.push_back(BufferElement(tmpElement.index + 3, tmpElement.type, tmpElement.name, tmpElement.divisor)); } } } } private: std::vector<BufferElement> m_elements; unsigned int m_stride = 0; }; class VertexBuffer { public: virtual ~VertexBuffer() = default; virtual void Bind() const = 0; virtual void UnBind() const = 0; virtual void Update(const void *vertices,unsigned int size, int offset) = 0; virtual void* MapBuffer() = 0; virtual void UnMapBuffer() = 0; virtual void ClearBuffer() = 0; virtual void Resize(const void* vertices, unsigned int size) = 0; virtual void SetLayout(const BufferLayout& layout) = 0; virtual const BufferLayout &GetLayout() const = 0; static Ref<VertexBuffer> Create(float* vertices, unsigned int size, int drawMod); }; class IndexBuffer { public: virtual ~IndexBuffer() = default; virtual void Bind() const = 0; virtual void UnBind() const = 0; virtual unsigned int GetCount() const = 0; static Ref<IndexBuffer> Create(const void* indices, unsigned int count); }; class ShaderStorageBuffer { public: virtual ~ShaderStorageBuffer() = default; virtual void BindBase(unsigned int point) = 0; virtual void BindRange(int offset,int size,unsigned int index) = 0; virtual void Bind() = 0; virtual void Update(const void* vertices, unsigned int size, int offset) = 0; virtual void Resize(const void* vertices, unsigned int size) = 0; virtual void SetLayout(const BufferLayout& layout) = 0; virtual const BufferLayout & GetLayout() const = 0; static Ref<ShaderStorageBuffer> Create(float* vertices, unsigned int size, int drawMod); }; }
[ "simongido1@gmail.com" ]
simongido1@gmail.com
8e61cc8e3dafe3734e93e80e57128a8e4e8bb0a6
7ebdd4e09f7286b3e2dd61a147e0f443eb61621a
/sig/include/sigkin/kn_joint.h
3971d9ac2e9e05e1da02bff57cfa9f29acc3d844
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
bpgeck/metaballs
681968d100d808e89e403b087d7c7755dc5c2e95
ad75def1ba5d090c8f0e531c99b433030807dc2c
refs/heads/master
2020-04-08T14:11:21.023513
2018-11-28T02:17:25
2018-11-28T02:17:25
159,425,922
0
0
null
null
null
null
UTF-8
C++
false
false
10,318
h
/*======================================================================= Copyright (c) 2018 Marcelo Kallmann. This software is distributed under the Apache License, Version 2.0. All copies must contain the full copyright notice licence.txt located at the base folder of the distribution. =======================================================================*/ # ifndef KN_JOINT_H # define KN_JOINT_H # include <sig/gs_mat.h> # include <sig/gs_quat.h> # include <sig/gs_array.h> # include <sigkin/kn_ik_solver.h> # include <sigkin/kn_joint_pos.h> # include <sigkin/kn_joint_rot.h> # include <sigkin/kn_joint_name.h> class GsModel; /*! KnJoint defines one joint and controls its translations and rotations. The translation is always set by using the KnJointPos object returned by method pos(), while the rotation can be set with different types of parameterization and joint limit control via the KnJointRot object returned by method rot() (methods euler() and st() are shortcuts to the methods with same name in KnJointRot). */ class KnJoint { public : /*! RotType specifies the specified default joint rotation parameterization */ enum RotType { TypeQuat, // Quaternion without limits, fastest convertion to matrix TypeST, // Swing-twist: axis-angle (x,y) swing, z rotation twist, and ellipse limits TypeEuler, // Euler angles with min/max limits per dof TypeUndef // Type not defined, no rotation channel should exist, but values can still be set }; private : GsModel* _visgeo; // the attached geometry to visualize this joint GsModel* _colgeo; // the attached geometry used for collision detection KnJoint* _parent; // the parent joint GsArray<KnJoint*> _children; // the children joints GsMat _gmat; // global matrix: from the root to the children of this joint GsMat _lmat; // local matrix: from this joint to its children gscbool _lmattodate; // true if lmat is up to date gscenum _rtype; // one of the RotType enumerator KnJointName _name; // the given name int _index; // its index in KnSkeleton::_joints int _coldetid; // index used in collision detection KnSkeleton* _skeleton; // pointer to the associated skeleton GsVec _offset; // offset from the parent joint to this joint KnJointPos _pos; // controls the translation parameterization KnJointRot _rot; // access to the rotation in any parameterization KnIkSolver* _ik; // a generic ik solver if this joint has one, null otherwise friend class KnSkeleton; friend class KnColdet; public : void* udata; // initialized as null and then completely up to user maintainance private: // constructor sets all dofs to non active, and rotation type as euler KnJoint ( KnSkeleton* kn, KnJoint* parent, RotType rtype, int i ); ~KnJoint (); public : /*! Init this joint with the same parameters as given joint j. The considered parameters copied are: _rtype, _name, _offset, _pos, and _rot. */ void init ( const KnJoint* j ); /*! Get a pointer for the attached geometry for visualization, or null if no such geometry was loaded. The geometry pointers can be shared ( see GsModel::ref/unref). */ GsModel* visgeo () const { return _visgeo; } /*! Get a pointer for the attached geometry for collision detection, or null if no such geometry was loaded. The geometry pointers can be shared ( see GsModel::ref/unref). */ GsModel* colgeo () const { return _colgeo; } /*! Replaces the visualization geometry pointer with the new one. The ref/unref methods are used during replacement and null can be passed in order to only unref the visualization geometry */ void visgeo ( GsModel* m ) { updrefs(_visgeo,m); } /*! Replaces the collision geometry pointer with the new one. The ref/unref methods are used during replacement and null can be passed in order to only unref the collision geometry */ void colgeo ( GsModel* m ) { updrefs(_colgeo,m); } /*! Get a pointer to the skeleton owner of this joint */ KnSkeleton* skeleton () { return _skeleton; } /*! traverse hierarchy */ KnJoint* parent() const { return _parent; } KnJoint* child ( int i ) const { return _children[i]; } int children () const { return _children.size(); } /*! Set the name of this joint */ void name ( KnJointName jn ) { _name=jn; } KnJointName name () const { return _name; } /*! Returns the index of this joint in the KnSkeleton list of joints */ int index () const { return _index; } /*! Returns the collision detection id of the colgeo attached to this joint (or -1 if no id). */ int coldetid () const { return _coldetid; } /*! returns the fixed frame translation relative to the parent */ const GsVec& offset () const { return _offset; } /*! change the fixed frame translation relative to the parent */ void offset ( const GsVec& o ); /*! Access the translation parameterization of the joint. */ KnJointPos* pos () { return &_pos; } const KnJointPos* cpos () const { return &_pos; } /*! Set the desired rotation model. The rotation model is important for defining how the rotation of the joint should be represented in channels, what will determine the values that are stored in postures and motions. The default value is TypeUndef. */ void rot_type ( RotType t ) { _rtype = (gscenum)t; } /*! Returns the current used rotation parameterization */ RotType rot_type () const { return (RotType)_rtype; } /*! Access the Euler rotation parameterization model of the joint. */ KnJointEuler* euler () { return _rot.euler(); } const KnJointEuler* ceuler () { return _rot.ceuler(); } /*! Access the Swing and Twist rotation parameterization model of the joint. */ KnJointST* st () { return _rot.st(); } const KnJointST* cst () { return _rot.cst(); } /*! Access the joint rotation class that controls the rotation of the joint. */ KnJointRot* rot () { return &_rot; } const KnJointRot* crot () { return &_rot; } /*! This method is the same as rot(), it access the joint rotation class so that quaternions can be manipulated. Note that depending on the KnJointRot mode, the local (before pre/post) or total (after pre/post) quaternion will be accessed. */ KnJointRot* quat () { return &_rot; } const KnJointRot* cquat () { return &_rot; } /*! Set the position values to zero */ void initpos () { pos()->value(0,0,0); } /*! Set the rotation to zero in the joint rotation type */ void initrot (); /*! Set the active channels (both position and rotation) to their "zero" values */ void init_values () { initpos(); initrot(); } /*! If the current local matrix is not up to date, it will recalculate the local matrix based on the current local translation and rotation parameterization */ void update_lmat (); /*! Recursivelly updates the local matrix and the global matrices of the joint and all its children. It assumes that the global matrix of the parent is up to date. Note: whenever this method is called, the whole branch under the joint is updated */ void update_gmat (); /*! Same as update_gmat(), but it stops at the given stopjoints */ void update_gmat ( KnJoint*stopjoint1, KnJoint*stopjoint2 ); /*! Optimized version of update_gmat() for single branch types of skeletons. It will just traverse the first child of each joint. Optional stopjoint will terminate early when stopjoint is found */ void update_branch_gmat ( KnJoint* stopjoint=0 ); /*! Updates the local matrix and set the global matrix of this joint to be the local matrix multiplied by the parent global matrix */ void update_gmat_local (); /*! Finds and updates the local and global matrices of all joints in the branch leading to the root joint, until stop_joint or until the root is found (stop_joint is not updated). */ void update_gmat_up ( KnJoint* stop_joint=0 ); /*! Ensures that the local matrix is updated and returns it. */ const GsMat& lmat () { update_lmat(); return _lmat; } /*! Will force the reconstruction of the local matrix from the rotation and position parameters. The skeleton is also notified with a call to invalidate_global_matrices() */ void set_lmat_changed (); /*! Returns the current global matrix. Be sure that it is up to date by calling one of the several updated methods. It gives the transformation from the root to the children of this joint */ const GsMat& gmat () const { return _gmat; } /*! Returns the translation encoded in the current global matrix. Be sure that the global matrix is up to date */ GsVec gcenter () const { return GsVec(_gmat.e14,_gmat.e24,_gmat.e34); } /*! Get a single visualization model for this node and all the children (update_gmat) is called */ void unite_visgeo ( GsModel& m ); /*! Get a single collision model for this node and all the children (update_gmat) is called */ void unite_colgeo ( GsModel& m ); /*! Recursivelly push to the given list all joints in the subtree of this joint, which is not included in the list */ void subtree ( GsArray<KnJoint*>& jointlist ) const; /*! Initializes the ik solver, allocating it if needed, ref/unref rules followed */ bool ikinit ( KnIk::Type t ); /*! Defines or updates the ik solver currenlty being referenced */ void ik ( KnIkSolver* iks ) { updrefs(_ik,iks); } /*! Access the ik solver; will be null if none is associated */ KnIkSolver* ik () { return _ik; } /*! Solve and apply the ik to the given target position, which is expected to be in global coordinates if fr=='G' and in base coordinates otherwise. */ KnIk::Result iksolve ( const GsVec& p, char fr='G' ); /*! Solve and apply the ik to the given target position and orientation, which are expected to be in global coordinates if fr=='G' and in base coordinates otherwise, */ KnIk::Result iksolve ( const GsVec& p, const GsQuat& q, char fr='G' ); /*! Solve and apply the ik to the given target position and orientation, which are expected to be in global coordinates if fr=='G' and in base coordinates otherwise */ KnIk::Result iksolve ( const GsMat& m, char fr='G' ); /*! Compute the transformation matrix of this end effector with respect to the base joint and save it in ik()->goal */ void ikgetmat (); }; //==================================== End of File =========================================== # endif // KN_JOINT_H
[ "b.geck@yahoo.com" ]
b.geck@yahoo.com
d78eef579fb616d1562ac7c2e31123b8e3ffa0e0
6bd1285d2e38324a4bda92fad0f4ea80baca37c6
/src/display/Arduino_SSD1351.h
1770fbb70a731335d7df68956b288da82a28b7a9
[]
no_license
Lmorales45/Arduino_GFX
dc40f98be63f02923039a142a864008ba17190fe
b79d529c0094afcdb742e1f21c9dcf876b6ce4ae
refs/heads/master
2023-03-19T03:02:57.843887
2021-03-15T15:04:25
2021-03-15T15:04:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,151
h
/* * start rewrite from: * https://github.com/adafruit/Adafruit-GFX-Library.git * https://github.com/adafruit/Adafruit-SSD1351-library.git */ #ifndef _ARDUINO_SSD1351_H_ #define _ARDUINO_SSD1351_H_ #include <Arduino.h> #include <Print.h> #include "../Arduino_GFX.h" #include "../Arduino_TFT.h" #define SSD1351_TFTWIDTH 128 ///< SSD1351 max TFT width #define SSD1351_TFTHEIGHT 128 ///< SSD1351 max TFT height #define SSD1351_SETCOLUMN 0x15 #define SSD1351_SETROW 0x75 #define SSD1351_WRITERAM 0x5C #define SSD1351_READRAM 0x5D #define SSD1351_SETREMAP 0xA0 #define SSD1351_STARTLINE 0xA1 #define SSD1351_DISPLAYOFFSET 0xA2 #define SSD1351_DISPLAYALLOFF 0xA4 #define SSD1351_DISPLAYALLON 0xA5 #define SSD1351_NORMALDISPLAY 0xA6 #define SSD1351_INVERTDISPLAY 0xA7 #define SSD1351_FUNCTIONSELECT 0xAB #define SSD1351_DISPLAYOFF 0xAE #define SSD1351_DISPLAYON 0xAF #define SSD1351_PRECHARGE 0xB1 #define SSD1351_DISPLAYENHANCE 0xB2 #define SSD1351_CLOCKDIV 0xB3 #define SSD1351_SETVSL 0xB4 #define SSD1351_SETGPIO 0xB5 #define SSD1351_PRECHARGE2 0xB6 #define SSD1351_SETGRAY 0xB8 #define SSD1351_USELUT 0xB9 #define SSD1351_PRECHARGELEVEL 0xBB #define SSD1351_VCOMH 0xBE #define SSD1351_CONTRASTABC 0xC1 #define SSD1351_CONTRASTMASTER 0xC7 #define SSD1351_MUXRATIO 0xCA #define SSD1351_COMMANDLOCK 0xFD #define SSD1351_HORIZSCROLL 0x96 #define SSD1351_STOPSCROLL 0x9E #define SSD1351_STARTSCROLL 0x9F class Arduino_SSD1351 : public Arduino_TFT { public: Arduino_SSD1351( Arduino_DataBus *bus, int8_t rst = -1, uint8_t r = 0, int16_t w = SSD1351_TFTWIDTH, int16_t h = SSD1351_TFTHEIGHT, uint8_t col_offset1 = 0, uint8_t row_offset1 = 0, uint8_t col_offset2 = 0, uint8_t row_offset2 = 0); virtual void begin(int32_t speed = 0); virtual void writeAddrWindow(int16_t x, int16_t y, uint16_t w, uint16_t h); virtual void setRotation(uint8_t r); virtual void invertDisplay(bool); virtual void displayOn(); virtual void displayOff(); protected: virtual void tftInit(); private: }; #endif
[ "moononournation@gmail.com" ]
moononournation@gmail.com
f70296aa76d8747aa53ae01e70bfbffaedbea725
bd1fea86d862456a2ec9f56d57f8948456d55ee6
/000/246/879/CWE78_OS_Command_Injection__wchar_t_console_execl_81a.cpp
bb02c14e74dd65b6e7fed07b3a456fce65a86562
[]
no_license
CU-0xff/juliet-cpp
d62b8485104d8a9160f29213368324c946f38274
d8586a217bc94cbcfeeec5d39b12d02e9c6045a2
refs/heads/master
2021-03-07T15:44:19.446957
2020-03-10T12:45:40
2020-03-10T12:45:40
246,275,244
0
1
null
null
null
null
UTF-8
C++
false
false
3,190
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE78_OS_Command_Injection__wchar_t_console_execl_81a.cpp Label Definition File: CWE78_OS_Command_Injection.strings.label.xml Template File: sources-sink-81a.tmpl.cpp */ /* * @description * CWE: 78 OS Command Injection * BadSource: console Read input from the console * GoodSource: Fixed string * Sinks: execl * BadSink : execute command with wexecl * Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference * * */ #include "std_testcase.h" #include "CWE78_OS_Command_Injection__wchar_t_console_execl_81.h" namespace CWE78_OS_Command_Injection__wchar_t_console_execl_81 { #ifndef OMITBAD void bad() { wchar_t * data; wchar_t dataBuffer[100] = COMMAND_ARG2; data = dataBuffer; { /* Read input from the console */ size_t dataLen = wcslen(data); /* if there is room in data, read into it from the console */ if (100-dataLen > 1) { /* POTENTIAL FLAW: Read data from the console */ if (fgetws(data+dataLen, (int)(100-dataLen), stdin) != NULL) { /* The next few lines remove the carriage return from the string that is * inserted by fgetws() */ dataLen = wcslen(data); if (dataLen > 0 && data[dataLen-1] == L'\n') { data[dataLen-1] = L'\0'; } } else { printLine("fgetws() failed"); /* Restore NUL terminator if fgetws fails */ data[dataLen] = L'\0'; } } } const CWE78_OS_Command_Injection__wchar_t_console_execl_81_base& baseObject = CWE78_OS_Command_Injection__wchar_t_console_execl_81_bad(); baseObject.action(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ static void goodG2B() { wchar_t * data; wchar_t dataBuffer[100] = COMMAND_ARG2; data = dataBuffer; /* FIX: Append a fixed string to data (not user / external input) */ wcscat(data, L"*.*"); const CWE78_OS_Command_Injection__wchar_t_console_execl_81_base& baseObject = CWE78_OS_Command_Injection__wchar_t_console_execl_81_goodG2B(); baseObject.action(data); } void good() { goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE78_OS_Command_Injection__wchar_t_console_execl_81; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
[ "frank@fischer.com.mt" ]
frank@fischer.com.mt
b4ace8acbca12478ab9e9ac906c9125301bd8453
c8300ef66c1964c48510bc3b72ee9ba130e07a1f
/Uri 2310 volleyball.cxx
3cc7b4ee280addc50e1cf5a3f0d3815bdeec4502
[]
no_license
Rakhibul-Hasan/Uri-solutions-02
c00d15697a61cdcb1f9ce45bcfd2d323a819bb2c
ffe626796f948f5ed5b2c58065efd1f19e8df262
refs/heads/master
2023-04-15T05:57:58.638880
2021-04-27T11:51:38
2021-04-27T11:51:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
512
cxx
#include<stdio.h> int main() { int s[101],ss[101],b[101],sb[101],a[101],sa[101]; int n,i,j,as=0,ab=0,aa=0,as1=0,ab1=0,aa1=0; double x,y,z; scanf("%d",&n); for(i=0;i<n;i++){ scanf("%*s%d%d%d%d%d%d",&s[i],&b[i],&a[i],&ss[i],&sb[i],&sa[i]); } for(j=0;j<n;j++){ as1+= s[j]; ab1+= b[j]; aa1+= a[j]; as+= ss[j]; ab+= sb[j]; aa+= sa[j]; } x=as*100.00/as1; y=ab*100.00/ab1; z=aa*100.00/aa1; printf("Pontos de Saque: %.2lf %%.\nPontos de Bloqueio: %.2lf %%.\nPontos de Ataque: %.2lf %%.\n",x,y,z); }
[ "noreply@github.com" ]
noreply@github.com
3d5e9c5661080e4f69030203d80b9c65b6ff63aa
c6af1c3213aa75ad8d7e4176b6d28bbfca067d50
/EpicEngine/Camera.h
68badc39806424f8514534797ff6a0f2c3ef1aa3
[]
no_license
TaehunKim0/EpicEngine
f2d34849fb70f3fedab29065508272c2a5a7a5f1
67fb6368ccd591b946a4a55a91cdca32215b9566
refs/heads/master
2023-04-27T17:42:13.424134
2019-09-30T18:00:45
2019-09-30T18:00:45
null
0
0
null
null
null
null
UHC
C++
false
false
1,139
h
#pragma once #ifndef _CAMERA_H_ #define _CAMERA_H_ #include <d3dx10math.h> /* 우리는 HLSL의 프로그래밍과, 정점/인덱스 버퍼를 셋업하는 방법 그리고 ColorShaderClass를 사용하여 HLSL 셰이더를 호출하는 방법을 살펴보았습니다. 하지만 우리가 한가지 놓친 것이 있는데, 그것은 바로 월드에서 우리가 보는 시점입니다. 이를 구현하기 위해서는 어떻게 우리가 장면을 보는지에 대한 정보를 DirectX 11에게 전달하는 카메라 클래스가 필요합니다. 카메라 클래스는 카메라의 위치와 현재 회전 상태를 계속 가지고 있어야 합니다. 또한 이 정보를 이용하여 렌더링시에 HLSL 셰이더에서 사용할 뷰 행렬을 생성합니다. */ class Camera { public: Camera(); Camera(const Camera& other); ~Camera(); void SetPosition(float, float, float); void SetRotation(float, float, float); D3DXVECTOR3 GetPosition(); D3DXVECTOR3 GetRotation(); void Render(); void GetViewMatrix(D3DXMATRIX&); private: D3DXVECTOR3 m_Position; D3DXVECTOR3 m_Rotation; D3DXMATRIX m_viewMatrix; }; #endif
[ "jack071000@naver.com" ]
jack071000@naver.com
c06d80db44b907379806e568e47e20af51ff4127
342d1974b808b8f312b6acd4742c2c64ef0f305f
/DBDesign/property/property/recordmeterdialog.h
f676a91ae571f80841f62cc228d4ede7e00f773c
[]
no_license
DrizztLei/project
d715bd11bc7c6a6432da4b146c9d75ae9d503810
d827595f1eefdf0a67677862d36983845e49e18b
refs/heads/master
2020-03-09T23:55:05.814874
2018-04-11T03:26:06
2018-04-11T03:26:06
129,069,300
0
2
null
null
null
null
UTF-8
C++
false
false
735
h
#ifndef RECORDMETERDIALOG_H #define RECORDMETERDIALOG_H #include "http.h" #include <QDialog> // #include <QSqlQuery> #include <QStandardItemModel> #include <vector> namespace Ui { class RecordMeterDialog; } class RecordMeterDialog : public QDialog { Q_OBJECT public: explicit RecordMeterDialog(QWidget *parent = 0); ~RecordMeterDialog(); // static HTTP& getHTTP(); private slots: void on_buildingomboBox_currentIndexChanged(int index); void on_insertRecordPushButton_clicked(); void on_confirmPushButton_clicked(); private: Ui::RecordMeterDialog *ui; QStandardItemModel *model; const int size = 8; std::vector<HTTP> list; // static HTTP http; }; #endif // RECORDMETERDIALOG_H
[ "elvis.linuxer@gamil.com" ]
elvis.linuxer@gamil.com
952e61e5d28fdf8e811cf3dc79de13c24b85d98c
e69c6452c8ce23d552ef39da4752f8c620b939b9
/Code/CPP/CrystalDiskMark/DHtmlDialogEx.cpp
b2226f9f209601b60810907f55f5246bd881b518
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
madnessw/thesnow
31a155e428bb6f79d2003c229cf2e570ca620c0f
0f1aeb7903397dda06e0044aa6e35cc2705ed71c
refs/heads/master
2021-01-23T12:00:27.906724
2014-01-09T05:42:41
2014-01-09T05:42:41
37,446,411
1
1
null
null
null
null
UTF-8
C++
false
false
8,375
cpp
/*---------------------------------------------------------------------------*/ // Author : hiyohiyo // Mail : hiyohiyo@crystalmark.info // Web : http://crystalmark.info/ // License : The modified BSD license // // Copyright 2007-2009 hiyohiyo. All rights reserved. /*---------------------------------------------------------------------------*/ #include "stdafx.h" #include "resource.h" #include "DHtmlDialogEx.h" #include "GetOsInfo.h" CDHtmlDialogEx::CDHtmlDialogEx(UINT dlgResouce, UINT dlgHtml, CWnd* pParent) :CDHtmlDialog(dlgResouce, dlgHtml, pParent) { m_FlagShowWindow = FALSE; m_FlagModelessDlg = FALSE; m_ParentWnd = NULL; m_DlgWnd = NULL; m_MenuId = 0; m_ZoomRatio = 1.0; m_ZoomType = ZOOM_TYPE_AUTO; } CDHtmlDialogEx::~CDHtmlDialogEx() { } void CDHtmlDialogEx::DoDataExchange(CDataExchange* pDX) { CDHtmlDialog::DoDataExchange(pDX); } BOOL CDHtmlDialogEx::OnInitDialog() { CDHtmlDialog::OnInitDialog(); m_hAccelerator = ::LoadAccelerators(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDR_ACCELERATOR)); return TRUE; } BEGIN_MESSAGE_MAP(CDHtmlDialogEx, CDHtmlDialog) END_MESSAGE_MAP() BEGIN_DHTML_EVENT_MAP(CDHtmlDialogEx) END_DHTML_EVENT_MAP() BOOL CDHtmlDialogEx::PreTranslateMessage(MSG* pMsg) { if(m_hAccelerator != NULL) { if(::TranslateAccelerator(m_hWnd, m_hAccelerator, pMsg) != 0) { return TRUE; } } return CDialog::PreTranslateMessage(pMsg); } BOOL CDHtmlDialogEx::OnAmbientProperty(COleControlSite* pSite, DISPID dispid, VARIANT* pvar) { if(dispid == DISPID_AMBIENT_DLCONTROL) { pvar->vt = VT_I4; pvar->lVal |= DLCTL_DLIMAGES; return TRUE; } return CDHtmlDialog::OnAmbientProperty(pSite, dispid, pvar); } /* void CDHtmlDialogEx::ChangeAmbient(void) { LPOLECONTROL pOleControl = NULL; m_pBrowserApp.QueryInterface(&pOleControl); pOleControl->OnAmbientPropertyChange(DISPID_AMBIENT_DLCONTROL); if(pOleControl)pOleControl->Release(); } */ void CDHtmlDialogEx::OnDocumentComplete(LPDISPATCH pDisp, LPCTSTR szUrl) { CString cstr; cstr = szUrl; if(cstr.Find(_T("html")) != -1 || cstr.Find(_T("dlg")) != -1) { UpdateData(FALSE); m_FlagShowWindow = TRUE; ShowWindow(SW_SHOW); } } double CDHtmlDialogEx::GetZoomRatio() { return m_ZoomRatio; } #ifndef DOCHOSTUIFLAG_DPI_AWARE #define DOCHOSTUIFLAG_DPI_AWARE 0x40000000 #endif void CDHtmlDialogEx::EnableDpiAware() { if(GetIeVersion() >= 800) { DOCHOSTUIINFO info; info.cbSize = sizeof(info); GetHostInfo(&info); SetHostFlags(info.dwFlags | DOCHOSTUIFLAG_DIALOG | DOCHOSTUIFLAG_THEME | DOCHOSTUIFLAG_DPI_AWARE); } } DWORD CDHtmlDialogEx::ChangeZoomType(DWORD zoomType) { if(GetIeVersion() < 800) { return (DWORD)-1; } DWORD current; VARIANT zoom; VariantInit(&zoom); zoom.vt = VT_I4; m_pBrowserApp->ExecWB(OLECMDID_OPTICAL_ZOOM, OLECMDEXECOPT_DODEFAULT, NULL, &zoom); current = zoom.lVal; if(zoomType == ZOOM_TYPE_AUTO) { if(current >= 200) { zoomType = ZOOM_TYPE_200; } else if(current >= 150) { zoomType = ZOOM_TYPE_150; } else if(current >= 125) { zoomType = ZOOM_TYPE_125; } else { zoomType = ZOOM_TYPE_100; } } // Force reset Zoom value zoom.lVal = 10; m_pBrowserApp->ExecWB(OLECMDID_OPTICAL_ZOOM, OLECMDEXECOPT_DODEFAULT, &zoom, NULL); zoom.lVal = zoomType; m_pBrowserApp->ExecWB(OLECMDID_OPTICAL_ZOOM, OLECMDEXECOPT_DODEFAULT, &zoom, NULL); m_ZoomRatio = zoomType / 100.0; VariantClear(&zoom); return zoomType; } void CDHtmlDialogEx::InitDHtmlDialog(DWORD sizeX, DWORD sizeY, CString dialogPath) { // Enabled Visual Style DOCHOSTUIINFO info; info.cbSize = sizeof(info); GetHostInfo(&info); SetHostFlags(info.dwFlags | DOCHOSTUIFLAG_DIALOG | DOCHOSTUIFLAG_THEME); // ReSize Dialog SetClientRect((DWORD)(sizeX * m_ZoomRatio), (DWORD)(sizeY * m_ZoomRatio)); CenterWindow(); // Navigate // ChangeAmbient(); Navigate(_T("file://") + dialogPath, navNoHistory); } // 2008/1/19 // void CDHtmlDialogEx::SetClientRect(DWORD sizeX, DWORD sizeY, DWORD menuLine) { RECT rc; RECT clientRc; rc.left = 0; rc.top = 0; rc.right = sizeX; rc.bottom = sizeY; GetClientRect(&clientRc); if(clientRc.bottom - clientRc.top == sizeY && clientRc.right - clientRc.left == sizeX) { return; } WINDOWINFO wi = {0}; wi.cbSize = sizeof(WINDOWINFO); GetWindowInfo(&wi); // 0x94CE004C AdjustWindowRect(&rc, wi.dwStyle, TRUE); SetWindowPos(&CWnd::wndTop, -1, -1, rc.right - rc.left, rc.bottom - rc.top + GetSystemMetrics(SM_CYMENU) * menuLine, SWP_NOMOVE); GetClientRect(&clientRc); if(clientRc.bottom - clientRc.top != sizeY) { SetWindowPos(&CWnd::wndTop , -1, -1, rc.right - rc.left, rc.bottom - rc.top + GetSystemMetrics(SM_CYMENU) * menuLine + sizeY - (clientRc.bottom - clientRc.top), SWP_NOMOVE); } } BOOL CDHtmlDialogEx::Create(UINT nIDTemplate, CWnd* pDlgWnd, UINT menuId, CWnd* pParentWnd) { m_FlagModelessDlg = TRUE; m_ParentWnd = pParentWnd; m_DlgWnd = pDlgWnd; m_MenuId = menuId; if(m_MenuId != 0 && m_ParentWnd != NULL) { CMenu *menu = m_ParentWnd->GetMenu(); menu->EnableMenuItem(m_MenuId, MF_GRAYED); m_ParentWnd->SetMenu(menu); m_ParentWnd->DrawMenuBar(); } return CDialog::Create(nIDTemplate, pParentWnd); } void CDHtmlDialogEx::OnCancel() { if(m_FlagModelessDlg) { if(m_MenuId != 0 && m_ParentWnd != NULL) { CMenu *menu = m_ParentWnd->GetMenu(); menu->EnableMenuItem(m_MenuId, MF_ENABLED); m_ParentWnd->SetMenu(menu); m_ParentWnd->DrawMenuBar(); } CWnd::DestroyWindow(); } else { CDialog::OnCancel(); } } void CDHtmlDialogEx::PostNcDestroy() { if(m_FlagModelessDlg) { m_DlgWnd = NULL; delete this; } } void CDHtmlDialogEx::OnOK() { } void CDHtmlDialogEx::ShowWindowEx(int nCmdShow) { m_FlagShowWindow = TRUE; ShowWindow(nCmdShow); SetForegroundWindow(); } void CDHtmlDialogEx::SetElementPropertyEx(LPCTSTR szElementId, DISPID dispid, CString className) { CComPtr<IDispatch> spdispElem; GetElement(szElementId, &spdispElem); VARIANT v; VariantInit(&v); v.vt = VT_BSTR; v.bstrVal = CComBSTR(className); if(spdispElem) { DISPPARAMS dispparams = {NULL, NULL, 1, 1}; dispparams.rgvarg = &v; DISPID dispidPut = DISPID_PROPERTYPUT; dispparams.rgdispidNamedArgs = &dispidPut; spdispElem->Invoke(dispid, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYPUT, &dispparams, NULL, NULL, NULL); } VariantClear(&v); } void CDHtmlDialogEx::SetElementOuterHtmlEx(LPCTSTR szElementId, CString outerHtml) { CComPtr<IHTMLElement> sphtmlElem; GetElement(szElementId, &sphtmlElem); if(sphtmlElem) { sphtmlElem->put_outerHTML(CComBSTR(outerHtml)); } } void CDHtmlDialogEx::SetElementInnerHtmlEx(LPCTSTR szElementId, CString innerHtml) { CComPtr<IHTMLElement> sphtmlElem; GetElement(szElementId, &sphtmlElem); if(sphtmlElem) { sphtmlElem->put_innerHTML(CComBSTR(innerHtml)); } } void CDHtmlDialogEx::CallScript(CString function, CString argument) { CComPtr<IHTMLDocument2> pDocument; HRESULT hr = GetDHtmlDocument(&pDocument); ASSERT( hr == S_OK ); CComPtr<IDispatch> script; hr = pDocument->get_Script(&script); ASSERT( hr == S_OK ); CComBSTR name = CComBSTR(function); DISPID dispid; hr = script->GetIDsOfNames( IID_NULL, &name, 1, LOCALE_SYSTEM_DEFAULT, &dispid); ASSERT( hr == S_OK ); CComVariant arg1 = CComVariant(argument); DISPPARAMS params = {&arg1, NULL, 1, 0}; VARIANT ret; VariantInit(&ret); EXCEPINFO exp; hr = script->Invoke( dispid, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_METHOD, &params, &ret, &exp, NULL); ASSERT( hr == S_OK ); VariantClear(&ret); } CString CDHtmlDialogEx::i18n(CString section, CString key) { TCHAR str[256]; CString cstr; GetPrivateProfileString(section, key, _T(""), str, 256, m_CurrentLangPath); cstr = str; if(cstr.IsEmpty()) { GetPrivateProfileString(section, key, _T(""), str, 256, m_DefaultLangPath); cstr = str; } return cstr; }
[ "thegfw@58104c5a-2bea-11de-ae9b-2be1a451ffb1" ]
thegfw@58104c5a-2bea-11de-ae9b-2be1a451ffb1
37c328182c299349a4bba2ee47008131065af08a
2e8a389b4f8a2beb787c2948b6ca1c3100cf78e7
/nfa/non-vtf/unprocessed/armc-automata/fsa/unsolved/Bebop/gen-inv2.cc
f4db85975924d582bc3a748f00c28002e27dde1e
[]
no_license
ondrik/automata-benchmarks
186f3149f3ccc3439db65bef6fef13d0f52e2e06
4a0081afa3440a882d265901dab6f45e10b22183
refs/heads/master
2022-08-21T05:07:29.248055
2022-07-28T14:14:30
2022-07-28T14:14:30
36,347,620
3
2
null
2021-08-02T19:58:35
2015-05-27T06:23:14
null
UTF-8
C++
false
false
1,576
cc
#include <iostream> #include <iomanip> #include <stdlib.h> int main(int argc,char *argv[]) { int n; if (argc!=2) { cerr << "One numerical argument is to be provided!\n"; return 1; } n=atoi(argv[1]); cout << "fa(\n\n"; cout << "%begin sigma and symbols\n"; cout << "r(fsa_preds),\n"; cout << "%end sigma and symbols\n\n"; cout << (n-1)*6+3+5+1 << ", % number of states\n\n"; cout << "[ % begin start states\n"; cout << "0\n"; cout << "], % end start states\n\n"; cout << "[ % begin final states\n"; cout << "1\n"; cout << "], % end final states\n\n"; cout << "[ % begin transitions\n\n"; for (int i=n;i>0;i--) { cout << "%%%%%%% LEVEL " << i << "\n\n"; cout << "trans(0,in(['0','1'])," << (n-i)*6+3 << "),\n"; cout << "trans(" << (n-i)*6+3 << ",in([a,b,c,d,e,f])," << (n-i)*6+3+1 << "),\n"; cout << "trans(" << (n-i)*6+3+1 << ",'" << i << "'," << (n-i)*6+3+2 << "),\n"; cout << "trans(" << (n-i)*6+3+2 << ",in(['0','1'])," << (n-i)*6+3+3 << "),\n"; cout << "trans(" << (n-i)*6+3+3 << ",in(['0','1'])," << (n-i)*6+3+4 << "),\n"; cout << "trans(" << (n-i)*6+3+4 << ",in(['0','1'])," << (n-i)*6+3+5 << "),\n"; cout << "trans(" << (n-i)*6+3+5 << ",in([d,e])," << (n-i)*6+3+7 << "),\n\n"; } cout << "%%%%%%% THE MAIN FUNCTION LEVEL\n\n"; cout << "trans(3,in([p,q,r,s,t]),2),\n"; cout << "trans(" << (n-1)*6+3+5 << ",in([q,r]),2),\n"; cout << "trans(2,in(['0','1']),1)\n\n"; cout << "], % end transitions\n"; cout << "[]). % jumps\n"; return 0; }
[ "ondra.lengal@gmail.com" ]
ondra.lengal@gmail.com
516935585f1934b912400832bc073e797897bd54
819ba50f4d2482e856f3bab84bc77ce361f084e1
/Light.cpp
a4a46e0af7a8bd1fa17b20c379a20433985ca5f2
[]
no_license
ShuyangLiu/RayTracing
772dfdcf2ae0cd9523ba689ece9b21baa9b5f978
7a220be0695afd67ba536652d828ad7854f8d912
refs/heads/master
2021-01-20T09:19:42.824861
2017-05-05T05:40:54
2017-05-05T05:40:54
90,236,059
0
0
null
null
null
null
UTF-8
C++
false
false
539
cpp
// // Created by shuyang on 5/3/17. // #include "Light.h" Light::Light(const Vector &position, const Color &color) : position(position), color(color) {} Light::Light() { position = Vector(0,0,0); color = Color(1,1,1,0); } const Vector &Light::getPosition() const { return position; } void Light::setPosition(const Vector &position) { Light::position = position; } const Color &Light::getColor() const { return color; } void Light::setColor(const Color &color) { Light::color = color; } Light::~Light() { }
[ "liushuyang2009@gmail.com" ]
liushuyang2009@gmail.com
8638bc1e9b61e5d046bae31847b9a22e18d6cea7
57713b9b5226fc69eea314dee30097cca2ea3e6f
/Data-Structures/Sorted-List/array/sorted-list-array.cpp
2e05ede9712dbdf908baa7548f5c7307418bdfb8
[]
no_license
Just-Sieb/School
ef7b52a408538882ccf11eeacf4707af40f1e293
50d989e941df3bde8ccbf02c2a39a08327105bda
refs/heads/master
2021-01-09T20:14:42.736506
2016-07-15T05:35:02
2016-07-15T05:35:02
62,327,818
0
0
null
null
null
null
UTF-8
C++
false
false
4,376
cpp
#include <iostream> #include "sorted.h" #include "ItemType.h" using namespace std; void MergeLists(SortedType &list1, SortedType &list2, SortedType& result) { result.ResetList(); list1.ResetList(); list2.ResetList(); ItemType item; for(int count = 0; count < list2.GetLength(); count++) { item = list2.GetNextItem(); result.PutItem(item); } for(int count = 0; count < list1.GetLength(); count++) { item = list1.GetNextItem(); result.PutItem(item); } } // for int values void check(int listValue, int correctValue){ if (listValue == correctValue) { cout << "Passed: " << listValue << " - " << correctValue << endl; } else cout << "ERROR: The following values did not pass the test, " << listValue << " - " << correctValue << endl; } // for boolean values void check(bool listValue, bool correctValue){ if (listValue == correctValue){ cout << "Passed: " << listValue << " - " << correctValue << endl; } else cout << "ERROR: The following values did not pass the test, " << listValue << " - " << correctValue << endl; } void printList(SortedType &list) { list.ResetList(); ItemType current; for (int counter = 0; counter < list.GetLength(); counter++) { current = list.GetNextItem(); current.Print(); } cout << endl; } int main(){ cout << "Starting program" << endl; SortedType clientList1; SortedType clientList2; SortedType clientList3; SortedType listMergeInFunc1; SortedType listMergeInFunc2; SortedType listMergeInFunc3; ItemType item; SortedType list1; SortedType list2; SortedType list3; SortedType list4; cout << "Adding item to the lists: " << endl; item.Initialize(1); list1.PutItem(item); item.Initialize(72); list1.PutItem(item); item.Initialize(3); list1.PutItem(item); item.Initialize(33); list1.PutItem(item); item.Initialize(253); list1.PutItem(item); item.Initialize(12); list1.PutItem(item); item.Initialize(67); list1.PutItem(item); item.Initialize(132); list2.PutItem(item); item.Initialize(505); list2.PutItem(item); item.Initialize(34); list2.PutItem(item); item.Initialize(23); list2.PutItem(item); item.Initialize(263); list2.PutItem(item); item.Initialize(7); list2.PutItem(item); item.Initialize(54); list2.PutItem(item); item.Initialize(56); list3.PutItem(item); item.Initialize(1746); list3.PutItem(item); item.Initialize(92); list3.PutItem(item); item.Initialize(574); list3.PutItem(item); item.Initialize(78); list3.PutItem(item); item.Initialize(14); list3.PutItem(item); item.Initialize(1000); list3.PutItem(item); item.Initialize(894); list4.PutItem(item); item.Initialize(728); list4.PutItem(item); item.Initialize(5673); list4.PutItem(item); item.Initialize(333); list4.PutItem(item); item.Initialize(27); list4.PutItem(item); item.Initialize(19); list4.PutItem(item); item.Initialize(693); list4.PutItem(item); cout << "\nThe initial lists\n"; printList(list1); printList(list2); printList(list3); printList(list4); cout << "\nMerge lists using the client function:\n"; MergeLists(list1, list2, clientList1); MergeLists(list3, list4, clientList2); MergeLists(clientList1, clientList2, clientList3); printList(clientList1); printList(clientList2); printList(clientList3); cout << "\nMerge lists using the functions built into the class\n"; listMergeInFunc1.MergeLists(list1, list2); listMergeInFunc2.MergeLists(list3, list4); listMergeInFunc3.MergeLists(listMergeInFunc1, listMergeInFunc2); printList(listMergeInFunc1); printList(listMergeInFunc2); printList(listMergeInFunc3); cout << "Finished running" << endl; return 0; }
[ "just.sieb@gmail.com" ]
just.sieb@gmail.com
8a7eb9f7435bd12756a0e83a89916387c9145d08
f38bfeb7139a97f054963f2671b9be4b1685d17c
/src/headers.cpp
91d613289cc8fe03ed1a9f6fd6d8279b70bc6296
[]
no_license
a-n-t-h-o-n-y/HTTP-Library
774f90eb7d06a132c26b436e9108c98c243c3f89
b9e6ed223b7001b6a4bd0383fff7db4dd250d610
refs/heads/master
2020-03-16T06:43:13.145825
2019-05-26T20:41:59
2019-05-26T20:41:59
132,561,275
1
0
null
null
null
null
UTF-8
C++
false
false
320
cpp
#include <http/headers.hpp> #include <sstream> #include <string> namespace http { std::string to_string(const Headers& headers) { std::stringstream ss; for (const auto& kv : headers) { ss << kv.first << ": " << kv.second << "\r\n"; } ss << "\r\n"; return ss.str(); } } // namespace http
[ "anthonym.leedom@gmail.com" ]
anthonym.leedom@gmail.com
3f1803e595a84ce5b5b0b6bf465c1c6b287f6926
b23d74c3f6725a9254ac0382fadf242a3aabb0e5
/src/media/audio/drivers/aml-g12-tdm/test/dai-test.cc
549c5781fd5479e31c61528ca3bd5b562bcf6502
[ "BSD-3-Clause" ]
permissive
Eissen/fuchsia
dacd48dbfa50550d3ea34befdb536b5df5fed61d
0df256e4ea207e2b83b11ba9c88fb1eca786a8bc
refs/heads/master
2023-02-02T01:55:06.110096
2020-12-15T05:51:48
2020-12-15T05:51:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,505
cc
// Copyright 2020 The Fuchsia 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 "../dai.h" #include <lib/device-protocol/pdev.h> #include <lib/fake-bti/bti.h> #include <lib/fake_ddk/fake_ddk.h> #include <lib/sync/completion.h> #include <thread> #include <ddktl/protocol/composite.h> #include <fake-mmio-reg/fake-mmio-reg.h> #include <soc/aml-s905d2/s905d2-hw.h> #include <zxtest/zxtest.h> #include "fuchsia/hardware/audio/cpp/fidl.h" #include "lib/async/default.h" #include "soc/aml-common/aml-audio.h" namespace audio::aml_g12 { struct DaiClient { DaiClient(ddk::DaiProtocolClient proto_client) { proto_client_ = proto_client; ZX_ASSERT(proto_client_.is_valid()); zx::channel channel_remote, channel_local; ASSERT_OK(zx::channel::create(0, &channel_local, &channel_remote)); ASSERT_OK(proto_client_.Connect(std::move(channel_remote))); dai_.Bind(std::move(channel_local)); } ddk::DaiProtocolClient proto_client_; ::fuchsia::hardware::audio::DaiSyncPtr dai_; }; class FakePDev : public ddk::PDevProtocol<FakePDev, ddk::base_protocol> { public: FakePDev() : proto_({&pdev_protocol_ops_, this}) { regs_ = std::make_unique<ddk_fake::FakeMmioReg[]>(kRegCount); mmio_ = std::make_unique<ddk_fake::FakeMmioRegRegion>(regs_.get(), sizeof(uint32_t), kRegCount); } const pdev_protocol_t* proto() const { return &proto_; } zx_status_t PDevGetMmio(uint32_t index, pdev_mmio_t* out_mmio) { EXPECT_EQ(index, 0); out_mmio->offset = reinterpret_cast<size_t>(this); return ZX_OK; } zx_status_t PDevGetInterrupt(uint32_t index, uint32_t flags, zx::interrupt* out_irq) { return ZX_ERR_NOT_SUPPORTED; } zx_status_t PDevGetBti(uint32_t index, zx::bti* out_bti) { return fake_bti_create(out_bti->reset_and_get_address()); } zx_status_t PDevGetSmc(uint32_t index, zx::resource* out_resource) { return ZX_ERR_NOT_SUPPORTED; } zx_status_t PDevGetDeviceInfo(pdev_device_info_t* out_info) { return ZX_ERR_NOT_SUPPORTED; } zx_status_t PDevGetBoardInfo(pdev_board_info_t* out_info) { return ZX_ERR_NOT_SUPPORTED; } ddk::MmioBuffer mmio() { return ddk::MmioBuffer(mmio_->GetMmioBuffer()); } ddk_fake::FakeMmioReg& reg(size_t ix) { return regs_[ix >> 2]; // AML registers are in virtual address units. } private: static constexpr size_t kRegCount = S905D2_EE_AUDIO_LENGTH / sizeof(uint32_t); // in 32 bits chunks. pdev_protocol_t proto_; std::unique_ptr<ddk_fake::FakeMmioReg[]> regs_; std::unique_ptr<ddk_fake::FakeMmioRegRegion> mmio_; }; class TestAmlG12TdmDai : public AmlG12TdmDai { public: explicit TestAmlG12TdmDai() : AmlG12TdmDai(fake_ddk::kFakeParent) {} dai_protocol_t GetProto() { return {&this->dai_protocol_ops_, this}; } bool AllowNonContiguousRingBuffer() override { return true; } }; class AmlG12TdmDaiTest : public zxtest::Test { public: void SetUp() override { static constexpr size_t kNumBindProtocols = 1; fbl::Array<fake_ddk::ProtocolEntry> protocols(new fake_ddk::ProtocolEntry[kNumBindProtocols], kNumBindProtocols); protocols[0] = {ZX_PROTOCOL_PDEV, *reinterpret_cast<const fake_ddk::Protocol*>(pdev_.proto())}; tester_.SetProtocols(std::move(protocols)); } protected: FakePDev pdev_; fake_ddk::Bind tester_; }; TEST_F(AmlG12TdmDaiTest, InitializeI2sOut) { metadata::AmlConfig metadata = {}; metadata.is_input = false; metadata.mClockDivFactor = 10; metadata.sClockDivFactor = 25; metadata.ring_buffer.number_of_channels = 2; metadata.lanes_enable_mask[0] = 3; metadata.bus = metadata::AmlBus::TDM_C; metadata.version = metadata::AmlVersion::kS905D2G; metadata.dai.type = metadata::DaiType::I2s; metadata.dai.number_of_channels = 2; metadata.dai.bits_per_sample = 16; metadata.dai.bits_per_slot = 32; tester_.SetMetadata(&metadata, sizeof(metadata)); auto dai = std::make_unique<TestAmlG12TdmDai>(); auto dai_proto = dai->GetProto(); ASSERT_OK(dai->InitPDev()); ASSERT_OK(dai->DdkAdd("test")); // step helps track of the expected sequence of reads and writes. int step = 0; // Configure TDM OUT for I2S. // TDM OUT CTRL0 disable, then // TDM OUT CTRL0 config, bitoffset 2, 2 slots, 32 bits per slot. pdev_.reg(0x580).SetReadCallback([&step]() -> uint32_t { if (step == 0) { return 0xffff'ffff; } else if (step == 3) { return 0x0000'0000; } else if (step == 6) { return 0x3001'003f; } else if (step == 7) { return 0x0001'003f; } else if (step == 8) { return 0x2001'003f; } else if (step == 9) { return 0x8001'003f; } ADD_FAILURE(); return 0; }); pdev_.reg(0x580).SetWriteCallback([&step](size_t value) { if (step == 0) { EXPECT_EQ(0x7fff'ffff, value); // Disable. step++; } else if (step == 3) { EXPECT_EQ(0x0001'003f, value); step++; } else if (step == 6) { EXPECT_EQ(0x0001'003f, value); // Sync. step++; } else if (step == 7) { EXPECT_EQ(0x2001'003f, value); // Sync. step++; } else if (step == 8) { EXPECT_EQ(0x3001'003f, value); // Sync. step++; } else if (step == 9) { EXPECT_EQ(0x0001'003f, value); // Disable on Shutdown. step++; } else { EXPECT_TRUE(0); } }); // TDM OUT CTRL1 FRDDR C with 16 bits per sample. pdev_.reg(0x584).SetWriteCallback([](size_t value) { EXPECT_EQ(0x0200'0f20, value); }); // SCLK CTRL, enabled, 24 sdiv, 31 lrduty, 63 lrdiv. pdev_.reg(0x050).SetWriteCallback([](size_t value) { EXPECT_EQ(0xc180'7c3f, value); }); // SCLK CTRL1, clear delay, sclk_invert_ph0. pdev_.reg(0x054).SetWriteCallback([&step](size_t value) { if (step == 4) { EXPECT_EQ(0x0000'0000, value); step++; } else if (step == 5) { EXPECT_EQ(0x0000'0001, value); step++; } }); // CLK TDMOUT CTL, enable, no sclk_inv, sclk_ws_inv, mclk_ch 2. pdev_.reg(0x098).SetWriteCallback([&step](size_t value) { if (step == 1) { EXPECT_EQ(0x0000'0000, value); // Disable step++; } else if (step == 2) { EXPECT_EQ(0xd220'0000, value); step++; } else if (step == 10) { EXPECT_EQ(0x0000'0000, value); // Disable on Shutdown step++; } }); DaiClient client(&dai_proto); client.dai_->Reset(); dai->DdkAsyncRemove(); dai.release()->DdkRelease(); EXPECT_TRUE(tester_.Ok()); EXPECT_EQ(step, 11); } TEST_F(AmlG12TdmDaiTest, InitializePcmOut) { metadata::AmlConfig metadata = {}; metadata.is_input = false; metadata.mClockDivFactor = 10; metadata.sClockDivFactor = 25; metadata.bus = metadata::AmlBus::TDM_C; metadata.version = metadata::AmlVersion::kS905D2G; metadata.ring_buffer.number_of_channels = 1; metadata.lanes_enable_mask[0] = 1; metadata.dai.type = metadata::DaiType::Tdm1; metadata.dai.number_of_channels = 1; metadata.dai.bits_per_sample = 16; metadata.dai.bits_per_slot = 16; metadata.dai.sclk_on_raising = true; tester_.SetMetadata(&metadata, sizeof(metadata)); auto dai = std::make_unique<TestAmlG12TdmDai>(); auto dai_proto = dai->GetProto(); ASSERT_OK(dai->InitPDev()); ASSERT_OK(dai->DdkAdd("test")); // step helps track of the expected sequence of reads and writes. int step = 0; // Configure TDM OUT for PCM. // TDM OUT CTRL0 disable, then // TDM OUT CTRL0 config, bitoffset 2, 1 slot, 16 bits per slot. pdev_.reg(0x580).SetReadCallback([&step]() -> uint32_t { if (step == 0) { return 0xffff'ffff; } else if (step == 3) { return 0x0000'0000; } else if (step == 6) { return 0x3001'000f; } else if (step == 7) { return 0x0001'000f; } else if (step == 8) { return 0x2001'000f; } else if (step == 9) { return 0x8001'000f; } ADD_FAILURE(); return 0; }); pdev_.reg(0x580).SetWriteCallback([&step](size_t value) { if (step == 0) { EXPECT_EQ(0x7fff'ffff, value); // Disable. step++; } else if (step == 3) { EXPECT_EQ(0x0001'000f, value); step++; } else if (step == 6) { EXPECT_EQ(0x0001'000f, value); // Sync. step++; } else if (step == 7) { EXPECT_EQ(0x2001'000f, value); // Sync. step++; } else if (step == 8) { EXPECT_EQ(0x3001'000f, value); // Sync. step++; } else if (step == 9) { EXPECT_EQ(0x0001'000f, value); // Disable on Shutdown. step++; } else { EXPECT_TRUE(0); } }); // TDM OUT CTRL1 FRDDR C with 16 bits per sample. pdev_.reg(0x584).SetWriteCallback([](size_t value) { EXPECT_EQ(0x0200'0f20, value); }); // SCLK CTRL, enabled, 24 sdiv, 0 lrduty, 15 lrdiv. pdev_.reg(0x050).SetWriteCallback([](size_t value) { EXPECT_EQ(0xc180'000f, value); }); // SCLK CTRL1, clear delay, no sclk_invert_ph0. pdev_.reg(0x054).SetWriteCallback([&step](size_t value) { if (step == 4) { EXPECT_EQ(0x0000'0000, value); step++; } else if (step == 5) { EXPECT_EQ(0x0000'0000, value); step++; } }); // CLK TDMOUT CTL, enable, no sclk_inv, sclk_ws_inv, mclk_ch 2. pdev_.reg(0x098).SetWriteCallback([&step](size_t value) { if (step == 1) { EXPECT_EQ(0x0000'0000, value); // Disable step++; } else if (step == 2) { EXPECT_EQ(0xd220'0000, value); step++; } else if (step == 10) { EXPECT_EQ(0x0000'0000, value); // Disable on Shutdown step++; } }); DaiClient client(&dai_proto); client.dai_->Reset(); dai->DdkAsyncRemove(); dai.release()->DdkRelease(); EXPECT_TRUE(tester_.Ok()); EXPECT_EQ(step, 11); } TEST_F(AmlG12TdmDaiTest, GetFormatsAndVmo) { metadata::AmlConfig metadata = {}; metadata.is_input = false; metadata.mClockDivFactor = 10; metadata.sClockDivFactor = 25; metadata.ring_buffer.number_of_channels = 2; metadata.lanes_enable_mask[0] = 3; metadata.bus = metadata::AmlBus::TDM_C; metadata.version = metadata::AmlVersion::kS905D2G; metadata.dai.type = metadata::DaiType::I2s; metadata.dai.number_of_channels = 2; metadata.dai.bits_per_sample = 16; metadata.dai.bits_per_slot = 32; tester_.SetMetadata(&metadata, sizeof(metadata)); auto dai = std::make_unique<TestAmlG12TdmDai>(); auto dai_proto = dai->GetProto(); ASSERT_OK(dai->InitPDev()); ASSERT_OK(dai->DdkAdd("test")); DaiClient client(&dai_proto); // Get ring buffer formats. ::fuchsia::hardware::audio::Dai_GetRingBufferFormats_Result ring_buffer_formats_out; ASSERT_OK(client.dai_->GetRingBufferFormats(&ring_buffer_formats_out)); auto& all_pcm_formats = ring_buffer_formats_out.response().ring_buffer_formats; auto& pcm_formats = all_pcm_formats[0].pcm_supported_formats(); ASSERT_EQ(1, pcm_formats.number_of_channels.size()); ASSERT_EQ(metadata.ring_buffer.number_of_channels, pcm_formats.number_of_channels[0]); ASSERT_EQ(1, pcm_formats.sample_formats.size()); ASSERT_EQ(::fuchsia::hardware::audio::SampleFormat::PCM_SIGNED, pcm_formats.sample_formats[0]); ASSERT_EQ(2, pcm_formats.frame_rates.size()); ASSERT_EQ(48'000, pcm_formats.frame_rates[0]); ASSERT_EQ(96'000, pcm_formats.frame_rates[1]); ASSERT_EQ(1, pcm_formats.bytes_per_sample.size()); ASSERT_EQ(2, pcm_formats.bytes_per_sample[0]); ASSERT_EQ(1, pcm_formats.valid_bits_per_sample.size()); ASSERT_EQ(16, pcm_formats.valid_bits_per_sample[0]); // Get DAI formats. ::fuchsia::hardware::audio::Dai_GetDaiFormats_Result dai_formats_out; ASSERT_OK(client.dai_->GetDaiFormats(&dai_formats_out)); auto& all_dai_formats = dai_formats_out.response().dai_formats; ASSERT_EQ(1, all_dai_formats.size()); auto& dai_formats = all_dai_formats[0]; ASSERT_EQ(1, dai_formats.number_of_channels.size()); ASSERT_EQ(metadata.dai.number_of_channels, dai_formats.number_of_channels[0]); ASSERT_EQ(1, dai_formats.sample_formats.size()); ASSERT_EQ(::fuchsia::hardware::audio::DaiSampleFormat::PCM_SIGNED, dai_formats.sample_formats[0]); ASSERT_EQ(2, dai_formats.frame_rates.size()); ASSERT_EQ(48'000, dai_formats.frame_rates[0]); ASSERT_EQ(96'000, dai_formats.frame_rates[1]); ASSERT_EQ(1, dai_formats.bits_per_slot.size()); ASSERT_EQ(32, dai_formats.bits_per_slot[0]); ASSERT_EQ(1, dai_formats.bits_per_sample.size()); ASSERT_EQ(16, dai_formats.bits_per_sample[0]); // Create ring buffer, pick first ring buffer format and first DAI format. ::fuchsia::hardware::audio::DaiFormat dai_format = {}; dai_format.number_of_channels = dai_formats.number_of_channels[0]; dai_format.channels_to_use_bitmask = (1 << dai_format.number_of_channels) - 1; // Use all. dai_format.sample_format = dai_formats.sample_formats[0]; dai_format.frame_format.set_frame_format_standard( dai_formats.frame_formats[0].frame_format_standard()); dai_format.frame_rate = dai_formats.frame_rates[0]; dai_format.bits_per_sample = dai_formats.bits_per_sample[0]; dai_format.bits_per_slot = dai_formats.bits_per_slot[0]; ::fuchsia::hardware::audio::Format ring_buffer_format = {}; ring_buffer_format.mutable_pcm_format()->number_of_channels = pcm_formats.number_of_channels[0]; ring_buffer_format.mutable_pcm_format()->channels_to_use_bitmask = (1 << ring_buffer_format.pcm_format().number_of_channels) - 1; // Use all. ring_buffer_format.mutable_pcm_format()->sample_format = pcm_formats.sample_formats[0]; ring_buffer_format.mutable_pcm_format()->frame_rate = pcm_formats.frame_rates[0]; ring_buffer_format.mutable_pcm_format()->bytes_per_sample = pcm_formats.bytes_per_sample[0]; ring_buffer_format.mutable_pcm_format()->valid_bits_per_sample = pcm_formats.valid_bits_per_sample[0]; // GetVmo then loose channel. { zx::channel local, remote; ASSERT_OK(zx::channel::create(0, &local, &remote)); ::fidl::InterfaceRequest<::fuchsia::hardware::audio::RingBuffer> ring_buffer_intf; ring_buffer_intf.set_channel(std::move(remote)); client.dai_->CreateRingBuffer(std::move(dai_format), std::move(ring_buffer_format), std::move(ring_buffer_intf)); ::fuchsia::hardware::audio::RingBuffer_SyncProxy ring_buffer(std::move(local)); ::fuchsia::hardware::audio::RingBuffer_GetVmo_Result out_result = {}; ASSERT_OK(ring_buffer.GetVmo(8192, 0, &out_result)); ZX_ASSERT(out_result.response().num_frames == 8192); ZX_ASSERT(out_result.response().ring_buffer.is_valid()); int64_t out_start_time = 0; ring_buffer.Start(&out_start_time); // Must fail, already started. ASSERT_NOT_OK(ring_buffer.GetVmo(8192, 0, &out_result)); ring_buffer.Stop(); // Must still fail, we lost the channel. ASSERT_NOT_OK(ring_buffer.GetVmo(4096, 0, &out_result)); } // GetVmo multiple times. { zx::channel local, remote; ASSERT_OK(zx::channel::create(0, &local, &remote)); ::fidl::InterfaceRequest<::fuchsia::hardware::audio::RingBuffer> ring_buffer_intf; ring_buffer_intf.set_channel(std::move(remote)); client.dai_->CreateRingBuffer(std::move(dai_format), std::move(ring_buffer_format), std::move(ring_buffer_intf)); ::fuchsia::hardware::audio::RingBuffer_SyncProxy ring_buffer(std::move(local)); ::fuchsia::hardware::audio::RingBuffer_GetVmo_Result out_result = {}; ASSERT_OK(ring_buffer.GetVmo(1, 0, &out_result)); // 2 x 16 bits samples = 4 bytes frames, and must align to HW buffer (64 bits), so we need 2. ZX_ASSERT(out_result.response().num_frames == 2); ZX_ASSERT(out_result.response().ring_buffer.is_valid()); int64_t out_start_time = 0; ring_buffer.Start(&out_start_time); ring_buffer.Stop(); ASSERT_OK(ring_buffer.GetVmo(1, 0, &out_result)); // 2 x 16 bits samples = 4 bytes frames, and must align to HW buffer (64 bits), so we need 2. ZX_ASSERT(out_result.response().num_frames == 2); ZX_ASSERT(out_result.response().ring_buffer.is_valid()); } dai->DdkAsyncRemove(); dai.release()->DdkRelease(); EXPECT_TRUE(tester_.Ok()); } } // namespace audio::aml_g12 // Redefine PDevMakeMmioBufferWeak per the recommendation in pdev.h. zx_status_t ddk::PDevMakeMmioBufferWeak(const pdev_mmio_t& pdev_mmio, std::optional<MmioBuffer>* mmio, uint32_t cache_policy) { auto* test_harness = reinterpret_cast<audio::aml_g12::FakePDev*>(pdev_mmio.offset); mmio->emplace(test_harness->mmio()); return ZX_OK; }
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
3e575f64e7b5b2a3f157510066f53c555620a7b8
6b5de3c98e553ce896dc4a8c32e1d3d6282d2716
/ino/src/eyelink.cpp
0b9ca7553b81cb990892f7163d45c5e8269925b7
[]
no_license
nfagan/brains
f6e7a9cce80c49826342daa9efab15d066d92d0c
8fd7d42ba0031e6af3fd390ed76bbfd6a64cac6d
refs/heads/master
2021-01-18T23:26:40.907613
2019-03-15T17:11:09
2019-03-15T17:11:09
87,111,514
0
0
null
null
null
null
UTF-8
C++
false
false
5,297
cpp
#include "eyelink.h" // // bounds // bounds::bounds() { for (unsigned i = 0; i < 4; i++) { rect[i] = 0; } state_changed = false; } void bounds::update(float x, float y) { bool prev = in; check(x, y); state_changed = prev != in; } void bounds::check(float x, float y) { bool in_x = x >= rect[0] && x <= rect[2]; bool in_y = y >= rect[1] && y <= rect[3]; in = in_x && in_y; } void bounds::print(HardwareSerial *serial) { String bounds_str; for (int i = 0; i < size; i++) { bounds_str += rect[i]; if (i < size-1) { bounds_str += ','; } } serial->println(bounds_str); } // // rois // rois::rois() { for (unsigned i = 0; i < n_rects; ++i) { rects[i] = bounds(); } } void rois::update(float x, float y) { for (unsigned i = 0; i < n_rects; ++i) { rects[i].update(x, y); } } void rois::print(HardwareSerial *serial) { for (int i = 0; i < n_rects; i++) { rects[i].print(serial); } } // // eyelink manager // el_manager::el_manager(HardwareSerial *serial, int x_pin, int y_pin) { this->serial = serial; this->pin_x = x_pin; this->pin_y = y_pin; this->name = ""; } el_manager::~el_manager() { // } void el_manager::set_name(const char *name) { this->name = String(name); } void el_manager::print_bounds() { serial->println(name + ":"); m_rois.print(serial); } void el_manager::print_gaze() { serial->println(name + ":"); String x = String(gaze_x); String y = String(gaze_y); String print_str = x + "," + y; serial->println(print_str); } void el_manager::init_pins() { pinMode(pin_x, INPUT); pinMode(pin_y, INPUT); } void el_manager::update() { gaze_x = update_one(pin_x, 0, 2); gaze_y = update_one(pin_y, 1, 3); m_rois.update(gaze_x, gaze_y); } coord el_manager::get_position() const { coord res; res.x = gaze_x; res.y = gaze_y; return res; } float el_manager::update_one(int pin, int min_i, int max_i) { int level = analogRead(pin); long min = m_rois.rects[ROI_INDICES::screen].rect[min_i]; long max = m_rois.rects[ROI_INDICES::screen].rect[max_i]; return el_manager::to_pixels(level, MAX_V, min, max); } float el_manager::to_pixels(int level, int denom, int screen_min, int screen_max) { float v = (float)level; float max = (float)denom; float r = v / max; float px = (r * (screen_max - screen_min)) + screen_min; return px; } void el_manager::set_rect_element(ROI_INDICES::ROI_INDICES index, unsigned int element, long value) { if (element > m_rois.rects[0].size-1) { serial->println('!'); return; } m_rois.rects[index].rect[element] = value; } bool el_manager::state_changed(ROI_INDICES::ROI_INDICES index) { return m_rois.rects[index].state_changed; } bool el_manager::in_bounds(ROI_INDICES::ROI_INDICES index) const { return m_rois.rects[index].in; } bool el_manager::in_bounds_face(float dist) const { const long *rect = &m_rois.rects[ROI_INDICES::face].rect[0]; const float r0 = (const float)rect[0]; const float r1 = (const float)rect[1]; const float r2 = (const float)rect[2]; const float r3 = (const float)rect[3]; const float cx = r0 + (r2-r0) / 2.0f; const float cy = r1 + (r3-r1) / 2.0f; const float x0 = cx - (dist/2.0f); const float y0 = cy - (dist/2.0f); const float x1 = cx + (dist/2.0f); const float y1 = cy + (dist/2.0f); bool res = gaze_x >= x0 && gaze_x <= x1 && gaze_y >= y0 && gaze_y <= y1; return res; } bool el_manager::in_bounds_radius(ROI_INDICES::ROI_INDICES index, float radius) const { if (index != ROI_INDICES::eyes) return false; if (name != "M1") return false; const long *rect = &m_rois.rects[index].rect[0]; const float r0 = (const float)rect[0]; const float r1 = (const float)rect[1]; const float r2 = (const float)rect[2]; const float r3 = (const float)rect[3]; const float cx = r0 + (r2-r0) / 2.0f; const float cy = r1 + (r3-r1) / 2.0f; const float x0 = cx - (radius/2.0f); const float y0 = cy - (radius/2.0f); const float x1 = cx + (radius/2.0f); const float y1 = cy + (radius/2.0f); bool res = gaze_x >= x0 && gaze_x <= x1 && gaze_y >= y0 && gaze_y <= y1; // serial->println("In bounds? "); serial->println(res); // serial->println(x0); // serial->println(y0); // serial->println(x1); // serial->println(y1); return res; // const float w = (const float)(rect[2] - rect[0]); // const float h = (const float)(rect[3] - rect[1]); // // const float center_x = (const float)(rect[0]) + (w / 2.0f); // const float center_y = (const float)(rect[1]) + (h / 2.0f); // // float delta_x = gaze_x - center_x; // float delta_y = gaze_y - center_y; // // float delta_x2 = delta_x * delta_x; // float delta_y2 = delta_y * delta_y; // // float dist = sqrt(delta_x2 + delta_y2); // // serial->println("Name: "); // serial->println(name); // serial->println("Width: "); // serial->println(w); // serial->println("Height: "); // serial->println(h); // serial->println("Dist: "); // serial->println(dist); // serial->println("Radius: "); // serial->println(radius); // serial->println("X: "); // serial->println(gaze_x); // serial->println("Y: "); // serial->println(gaze_y); // serial->println("In bounds? "); // serial->println(dist <= radius); // // return dist <= radius; }
[ "nick@fagan.org" ]
nick@fagan.org
ec70a8e5f6ffacbe0ac67408c988dfce1e84b04c
5d7807e52888b9505c4b5a0e24f5f87e4f6c343f
/cryengine/CryCommon/Cry_Geo.h
8d18072d81029c840dbf85db239eaa76a0707b38
[]
no_license
CapsAdmin/oohh
01533c72450c5ac036a245ffbaba09b6fda00e69
b63abeb717e1cd1ee2d3483bd5f0954c81bfc6e9
refs/heads/master
2021-01-25T10:44:22.976777
2016-10-11T19:05:47
2016-10-11T19:05:47
32,117,923
1
1
null
null
null
null
UTF-8
C++
false
false
27,031
h
////////////////////////////////////////////////////////////////////// // // Crytek Common Source code // // File: Cry_Geo.h // Description: Common structures for geometry computations // // History: // -March 15,2003: Created by Ivo Herzeg // ////////////////////////////////////////////////////////////////////// #ifndef CRYGEOSTRUCTS_H #define CRYGEOSTRUCTS_H #if _MSC_VER > 1000 # pragma once #endif #include "Cry_Math.h" /////////////////////////////////////////////////////////////////////////////// // Forward declarations // /////////////////////////////////////////////////////////////////////////////// struct Ray; template <typename F> struct Lineseg_tpl; template <typename F> struct Triangle_tpl; struct AABB; struct OBB; struct Sphere; struct AAEllipsoid; struct Ellipsoid; //----------------------------------------------------- /////////////////////////////////////////////////////////////////////////////// // Definitions // /////////////////////////////////////////////////////////////////////////////// // // Random geometry generation functions. // enum EGeomForm { GeomForm_Vertices, GeomForm_Edges, GeomForm_Surface, GeomForm_Volume }; AUTO_TYPE_INFO(EGeomForm) enum EGeomType { GeomType_None, GeomType_BoundingBox, GeomType_Physics, GeomType_Render, }; AUTO_TYPE_INFO(EGeomType) struct PosNorm { Vec3 vPos; Vec3 vNorm; }; inline void Transform(PosNorm& ran, Matrix34 const& mx) { ran.vPos = mx * ran.vPos; ran.vNorm = Matrix33(mx) * ran.vNorm; } inline void Transform(PosNorm& ran, QuatTS const& qts) { ran.vPos = qts * ran.vPos; ran.vNorm = qts.q * ran.vNorm; } struct RectF { float x, y, w, h; RectF() : x(0), y(0), w(1), h(1) { } AUTO_STRUCT_INFO }; struct RectI { int x, y, w, h; RectI() : x(0), y(0), w(1), h(1) { } RectI(int inX, int inY, int inW, int inH) : x(inX), y(inY), w(inW), h(inH) { } _inline void Add(RectI rcAdd) { int x2 = x + w; int y2 = y + h; int x22 = rcAdd.x + rcAdd.w; int y22 = rcAdd.y + rcAdd.h; x = min(x, rcAdd.x); y = min(y, rcAdd.y ); x2 = max(x2, x22); y2 = max(y2, y22); w = x2-x; h = y2-y; } _inline void Add(int inX, int inY, int inW, int inH) { Add(RectI(inX, inY, inW, inH)); } }; /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // struct Line /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// struct Line { Vec3 pointonline; Vec3 direction; //caution: the direction is important for any intersection test //default Line constructor (without initialisation) inline Line( void ) {} inline Line( const Vec3 &o, const Vec3 &d ) { pointonline=o; direction=d; } inline void operator () ( const Vec3 &o, const Vec3 &d ) { pointonline=o; direction=d; } ~Line( void ) {}; }; /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // struct Ray /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// struct Ray { Vec3 origin; Vec3 direction; //default Ray constructor (without initialisation) inline Ray( void ) {} inline Ray( const Vec3 &o, const Vec3 &d ) { origin=o; direction=d; } inline void operator () ( const Vec3 &o, const Vec3 &d ) { origin=o; direction=d; } ~Ray( void ) {}; }; /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // struct Lineseg /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// template <typename F> struct Lineseg_tpl { Vec3_tpl<F> start; Vec3_tpl<F> end; //default Lineseg constructor (without initialisation) inline Lineseg_tpl( void ) {} inline Lineseg_tpl( const Vec3_tpl<F> &s, const Vec3_tpl<F> &e ) { start=s; end=e; } inline void operator () ( const Vec3_tpl<F> &s, const Vec3_tpl<F> &e ) { start=s; end=e; } Vec3 GetPoint(F t) const {return t * end + (F(1.0) - t) * start;} ~Lineseg_tpl( void ) {}; }; typedef Lineseg_tpl<float> Lineseg; typedef Lineseg_tpl<real> Linesegr; /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // struct Triangle /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// template <typename F> struct Triangle_tpl { Vec3_tpl<F> v0,v1,v2; //default Lineseg constructor (without initialisation) ILINE Triangle_tpl( void ) {} ILINE Triangle_tpl( const Vec3_tpl<F>& a, const Vec3_tpl<F>& b, const Vec3_tpl<F>& c ) { v0=a; v1=b; v2=c; } ILINE void operator () ( const Vec3_tpl<F>& a, const Vec3_tpl<F>& b, const Vec3_tpl<F>& c ) { v0=a; v1=b; v2=c; } ~Triangle_tpl( void ) {}; Vec3_tpl<F> GetNormal() const { return ((v1-v0) ^ (v2-v0)).GetNormalized(); } F GetArea() const { return 0.5f * (v1-v0).Cross(v2-v0).GetLength(); } }; /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // struct AABB /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// struct AABB { Vec3 min; Vec3 max; /// default AABB constructor (without initialisation) ILINE AABB() {} enum type_reset { RESET }; // AABB aabb(RESET) generates a reset aabb ILINE AABB(type_reset) { Reset(); } ILINE explicit AABB( float radius ) { max = Vec3(radius); min = -max; } ILINE explicit AABB( const Vec3& v ) { min = max = v; } ILINE AABB( const Vec3& v, float radius ) { Vec3 ext(radius); min = v-ext; max = v+ext; } ILINE AABB( const Vec3 &vmin, const Vec3 &vmax ) { min=vmin; max=vmax; } ILINE AABB( const AABB &aabb ) { min.x = aabb.min.x; min.y = aabb.min.y; min.z = aabb.min.z; max.x = aabb.max.x; max.y = aabb.max.y; max.z = aabb.max.z; } inline AABB( const Vec3* points, int num ) { Reset(); for ( int i=0; i<num; i++ ) Add( points[i] ); } //! Reset Bounding box before calculating bounds. //! These values ensure that Add() functions work correctly for Reset bbs, without additional comparisons. ILINE void Reset() { min = Vec3(1e15f); max = Vec3(-1e15f); } ILINE bool IsReset() const { return min.x > max.x; } ILINE float IsResetSel(float ifReset, float ifNotReset) const { return (float)__fsel(max.x - min.x, ifNotReset, ifReset); } //! Check if bounding box is empty (Zero volume). ILINE bool IsEmpty() const { return min == max; } ILINE Vec3 GetCenter() const { return (min+max)*0.5f; } ILINE Vec3 GetSize() const { return (max-min) * IsResetSel(0.0f, 1.0f); } ILINE float GetRadius() const { return IsResetSel(0.0f, (max-min).GetLengthFloat()*0.5f); } ILINE float GetRadiusSqr() const { return IsResetSel(0.0f, ((max-min)*0.5f).GetLengthSquaredFloat()); } ILINE float GetVolume() const { return IsResetSel(0.0f, (max.x-min.x) * (max.y-min.y) * (max.z-min.z)); } ILINE void Add( const Vec3 &v ) { min.CheckMin(v); max.CheckMax(v); } inline void Add( const Vec3& v, float radius ) { Vec3 ext(radius); min.CheckMin(v-ext); max.CheckMax(v+ext); } ILINE void Add( const AABB& bb ) { min.CheckMin(bb.min); max.CheckMax(bb.max); } inline void Move( const Vec3& v ) { const float moveMult = IsResetSel(0.0f, 1.0f); const Vec3 vMove = v * moveMult; min += vMove; max += vMove; } inline void Expand( Vec3 const& v ) { if (!IsReset()) { min -= v; max += v; } } // Augment the box on all sides by a box. inline void Augment( AABB const& bb ) { if (!IsReset() && !bb.IsReset()) { Add( min + bb.min ); Add( max + bb.max ); } } void ClipToBox( AABB const& bb ) { min.CheckMax(bb.min); max.CheckMin(bb.max); } void ClipMoveToBox( AABB const& bb ) { for (int a = 0; a < 3; a++) { if (max[a] - min[a] > bb.max[a] - bb.min[a]) { min[a] = bb.min[a]; max[a] = bb.max[a]; } else if (min[a] < bb.min[a]) { max[a] += bb.min[a] - min[a]; min[a] = bb.min[a]; } else if (max[a] > bb.max[a]) { min[a] += bb.max[a] - max[a]; max[a] = bb.max[a]; } } } //! Check if this bounding box overlap with bounding box of sphere. bool IsOverlapSphereBounds( const Vec3 &pos,float radius ) const { assert( min.IsValid() ); assert( max.IsValid() ); assert( pos.IsValid() ); if (pos.x > min.x && pos.x < max.x && pos.y > min.y && pos.y < max.y && pos.z > min.z && pos.z < max.z) return true; if (pos.x+radius < min.x) return false; if (pos.y+radius < min.y) return false; if (pos.z+radius < min.z) return false; if (pos.x-radius > max.x) return false; if (pos.y-radius > max.y) return false; if (pos.z-radius > max.z) return false; return true; } //! Check if this bounding box contain sphere within itself. bool IsContainSphere( const Vec3 &pos,float radius ) const { assert( min.IsValid() ); assert( max.IsValid() ); assert( pos.IsValid() ); if (pos.x-radius < min.x) return false; if (pos.y-radius < min.y) return false; if (pos.z-radius < min.z) return false; if (pos.x+radius > max.x) return false; if (pos.y+radius > max.y) return false; if (pos.z+radius > max.z) return false; return true; } //! Check if this bounding box contains a point within itself. bool IsContainPoint( const Vec3 &pos) const { assert( min.IsValid() ); assert( max.IsValid() ); assert( pos.IsValid() ); if (pos.x < min.x) return false; if (pos.y < min.y) return false; if (pos.z < min.z) return false; if (pos.x > max.x) return false; if (pos.y > max.y) return false; if (pos.z > max.z) return false; return true; } float GetDistanceSqr( Vec3 const& v ) const { Vec3 vNear = v; vNear.CheckMax(min); vNear.CheckMin(max); return vNear.GetSquaredDistance(v); } float GetDistance( Vec3 const& v ) const { return sqrt(GetDistanceSqr(v)); } bool ContainsBox( AABB const& b ) const { assert( min.IsValid() ); assert( max.IsValid() ); assert( b.min.IsValid() ); assert( b.max.IsValid() ); return min.x <= b.min.x && min.y <= b.min.y && min.z <= b.min.z && max.x >= b.max.x && max.y >= b.max.y && max.z >= b.max.z; } // Check two bounding boxes for intersection. inline bool IsIntersectBox( const AABB &b ) const { assert( min.IsValid() ); assert( max.IsValid() ); assert( b.min.IsValid() ); assert( b.max.IsValid() ); // Check for intersection on X axis. if ((min.x > b.max.x)||(b.min.x > max.x)) return false; // Check for intersection on Y axis. if ((min.y > b.max.y)||(b.min.y > max.y)) return false; // Check for intersection on Z axis. if ((min.z > b.max.z)||(b.min.z > max.z)) return false; // Boxes overlap in all 3 axises. return true; } /*! * calculate the new bounds of a transformed AABB * * Example: * AABB aabb = AABB::CreateAABBfromOBB(m34,aabb); * * return values: * expanded AABB in world-space */ ILINE void SetTransformedAABB( const Matrix34& m34, const AABB& aabb ) { if (aabb.IsReset()) Reset(); else { Matrix33 m33; m33.m00=fabs_tpl(m34.m00); m33.m01=fabs_tpl(m34.m01); m33.m02=fabs_tpl(m34.m02); m33.m10=fabs_tpl(m34.m10); m33.m11=fabs_tpl(m34.m11); m33.m12=fabs_tpl(m34.m12); m33.m20=fabs_tpl(m34.m20); m33.m21=fabs_tpl(m34.m21); m33.m22=fabs_tpl(m34.m22); Vec3 sz = m33*((aabb.max-aabb.min)*0.5f); Vec3 pos = m34*((aabb.max+aabb.min)*0.5f); min = pos-sz; max = pos+sz; } } ILINE static AABB CreateTransformedAABB( const Matrix34& m34, const AABB& aabb ) { AABB taabb; taabb.SetTransformedAABB(m34,aabb); return taabb; } ILINE void SetTransformedAABB( const QuatT& qt, const AABB& aabb ) { if (aabb.IsReset()) Reset(); else { Matrix33 m33=Matrix33(qt.q); m33.m00=fabs_tpl(m33.m00); m33.m01=fabs_tpl(m33.m01); m33.m02=fabs_tpl(m33.m02); m33.m10=fabs_tpl(m33.m10); m33.m11=fabs_tpl(m33.m11); m33.m12=fabs_tpl(m33.m12); m33.m20=fabs_tpl(m33.m20); m33.m21=fabs_tpl(m33.m21); m33.m22=fabs_tpl(m33.m22); Vec3 sz = m33*((aabb.max-aabb.min)*0.5f); Vec3 pos = qt*((aabb.max+aabb.min)*0.5f); min = pos-sz; max = pos+sz; } } ILINE static AABB CreateTransformedAABB( const QuatT& qt, const AABB& aabb ) { AABB taabb; taabb.SetTransformedAABB(qt,aabb); return taabb; } //create an AABB using just the extensions of the OBB and ignore the orientation. ILINE void SetAABBfromOBB(const OBB& obb); ILINE static AABB CreateAABBfromOBB(const OBB& obb); /*! * converts an OBB into an tight fitting AABB * * Example: * AABB aabb = AABB::CreateAABBfromOBB(wposition,obb,1.0f); * * return values: * expanded AABB in world-space */ ILINE void SetAABBfromOBB(const Vec3& wpos, const OBB& obb, f32 scaling = 1.f); ILINE static AABB CreateAABBfromOBB(const Vec3& wpos, const OBB& obb, f32 scaling = 1.f); AUTO_STRUCT_INFO }; ILINE bool IsEquivalent( const AABB& a, const AABB& b, float epsilon=VEC_EPSILON ) { return IsEquivalent(a.min, b.min, epsilon) && IsEquivalent(a.max, b.max, epsilon); } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // struct OBB /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// struct OBB { Matrix33 m33; //orientation vectors Vec3 h; //half-length-vector Vec3 c; //center of obb ILINE void SetOBB( const Matrix33& matrix, const Vec3& hlv, const Vec3& center ) { m33=matrix; h=hlv; c=center; } ILINE static OBB CreateOBB(const Matrix33& m33, const Vec3& hlv, const Vec3& center) { OBB obb; obb.m33=m33; obb.h=hlv; obb.c=center; return obb; } ILINE void SetOBBfromAABB( const Matrix33& mat33, const AABB& aabb ) { m33 = mat33; h = (aabb.max-aabb.min)*0.5f; //calculate the half-length-vectors c = (aabb.max+aabb.min)*0.5f; //the center is relative to the PIVOT } ILINE void SetOBBfromAABB( const Quat& q, const AABB& aabb ) { m33 = Matrix33(q); h = (aabb.max-aabb.min)*0.5f; //calculate the half-length-vectors c = (aabb.max+aabb.min)*0.5f; //the center is relative to the PIVOT } ILINE static OBB CreateOBBfromAABB( const Matrix33& m33, const AABB& aabb ) { OBB obb; obb.SetOBBfromAABB(m33,aabb); return obb; } ILINE static OBB CreateOBBfromAABB( const Quat& q, const AABB& aabb ) { OBB obb; obb.SetOBBfromAABB(q,aabb); return obb; } AUTO_STRUCT_INFO }; //create an AABB using just the extensions of the OBB and ignore the orientation. ILINE void AABB::SetAABBfromOBB(const OBB& obb) { min = obb.c - obb.h; max = obb.c + obb.h; } ILINE /* static */ AABB AABB::CreateAABBfromOBB(const OBB& obb) { return AABB(obb.c - obb.h, obb.c + obb.h); } /*! * converts an OBB into an tight fitting AABB * * Example: * AABB aabb = AABB::CreateAABBfromOBB(wposition,obb,1.0f); * * return values: * expanded AABB in world-space */ ILINE void AABB::SetAABBfromOBB(const Vec3& wpos, const OBB& obb, f32 scaling /* = 1.f */) { Vec3 pos = obb.m33 * obb.c * scaling + wpos; Vec3 sz = obb.m33.GetFabs() * obb.h * scaling; min = pos - sz; max = pos + sz; } ILINE /* static */ AABB AABB::CreateAABBfromOBB(const Vec3& wpos, const OBB& obb, f32 scaling /* = 1.f */) { AABB taabb; taabb.SetAABBfromOBB(wpos, obb, scaling); return taabb; } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // struct Sphere /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// struct Sphere { Vec3 center; float radius; Sphere() {} Sphere(const Vec3& c, float r) : center(c), radius(r) {} void operator()(const Vec3& c, float r) { center = c; radius = r; } }; struct HWVSphere { hwvec3 center; simdf radius; ILINE HWVSphere( const hwvec3 &c, const simdf &r ) { center = c; radius = r; } ILINE HWVSphere(const Sphere& sp) { center = HWVLoadVecUnaligned(&sp.center); radius = SIMDFLoadFloat(sp.radius); } }; /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // struct AAEllipsoid /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// struct AAEllipsoid { Vec3 center; Vec3 radius_vec; //default AAEllipsoid constructor (without initialisation) inline AAEllipsoid( void ) {} inline AAEllipsoid( const Vec3 &c, const Vec3 &rv ) { radius_vec=rv; center=c; } inline void operator () ( const Vec3 &c, const Vec3 &rv ) { radius_vec=rv; center=c; } ~AAEllipsoid( void ) {}; }; /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // struct Ellipsoid /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// struct Ellipsoid { Matrix34 ExtensionPos; //default Ellipsoid constructor (without initialisation) inline Ellipsoid( void ) {} inline Ellipsoid( const Matrix34 &ep ) { ExtensionPos=ep; } inline void operator () ( const Matrix34 &ep ) { ExtensionPos=ep; } ~Ellipsoid( void ) {}; }; /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // struct TRect /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// template <class Num> struct TRect_tpl { typedef Vec2_tpl<Num> Vec; Vec Min, Max; inline TRect_tpl() {} inline TRect_tpl(Num x1, Num y1, Num x2, Num y2): Min(x1, y1), Max(x2, y2) {} inline TRect_tpl(const TRect_tpl<Num> &rc): Min(rc.Min), Max(rc.Max) {} inline bool IsEmpty() const { return Max.x < Min.x && Max.y < Min.y; } inline TRect_tpl<Num> &SetEmpty() { Max = Vec(-1, -1); Min = Vec(0, 0); return *this; } inline Vec GetDim() const { return Max - Min; } inline Num GetWidth() const { return Max.x - Min.x; } inline Num GetHeight() const { return Max.y - Min.y; } inline bool IsEqual(const TRect_tpl<Num> &rc) const { return Min.x == rc.Min.x && Min.y == rc.Min.y && Max.x == rc.Max.x && Max.y == rc.Max.y; } inline bool InRect(const TRect_tpl<Num> &rc) const { return rc.Min.x >= Min.x && rc.Max.x <= Max.x && rc.Min.y >= Min.y && rc.Max.y <= Max.y; } inline bool InRect(Vec pt) const { return pt.x >= Min.x && pt.x <= Max.x && pt.y >= Min.y && pt.y <= Max.y; } inline Vec &IntoRect(Vec &pt) const { if (pt.x < Min.x) pt.x = Min.x; else if (pt.x > Max.x) pt.x = Max.x; if (pt.y < Min.y) pt.y = Min.y; else if (pt.y > Max.y) pt.y = Max.y; return pt; } inline bool Intersects(const TRect_tpl<Num> &rc) const { return !IsEmpty() && !rc.IsEmpty() && !(Min.x > rc.Max.x || Max.x < rc.Min.x || Min.y > rc.Max.y || Max.y < rc.Min.y); } inline TRect_tpl<Num> &DoUnite(const TRect_tpl<Num> &rc) { if(IsEmpty()) { Min = rc.Min; Max = rc.Max; return *this;} if(rc.IsEmpty()) return *this; if(Min.x > rc.Min.x) Min.x = rc.Min.x; if(Min.y > rc.Min.y) Min.y = rc.Min.y; if(Max.x < rc.Max.x) Max.x = rc.Max.x; if(Max.y < rc.Max.y) Max.y = rc.Max.y; return *this; } inline TRect_tpl<Num> &DoIntersect(const TRect_tpl<Num> &rc) { if (IsEmpty()) return *this; if (rc.IsEmpty()) return SetEmpty(); if (Min.x < rc.Min.x) Min.x = rc.Min.x; if (Min.y < rc.Min.y) Min.y = rc.Min.y; if (Max.x > rc.Max.x) Max.x = rc.Max.x; if (Max.y > rc.Max.y) Max.y = rc.Max.y; return *this; } inline TRect_tpl<Num> GetSubRect(const TRect_tpl<Num> &rc) const { if (IsEmpty()) return *this; if (rc.IsEmpty()) return rc; return TRect_tpl<Num>(Min.x + rc.Min.x * GetWidth(), Min.y + rc.Min.y * GetHeight(), Min.x + rc.Max.x * GetWidth(), Min.y + rc.Max.y * GetHeight()); } inline TRect_tpl<Num> GetSubRectInv(const TRect_tpl<Num> &rcSub) const { if (IsEmpty()) return *this; if (rcSub.IsEmpty()) return rcSub; return TRect_tpl((rcSub.Min.x - Min.x) / GetWidth(), (rcSub.Min.y - Min.y) / GetHeight(), (rcSub.Max.x - Min.x) / GetWidth(), (rcSub.Max.y - Min.y) / GetHeight()); } }; typedef TRect_tpl<float> TRect; typedef TRect_tpl<int> TRectI; typedef Triangle_tpl<f32> Triangle; typedef Triangle_tpl<f64> Triangle_f64; ////////////////////////////////////////////////////////////////////////// // Manage linear and rotational 3D velocity in a class class Velocity3 { public: Vec3 vLin, vRot; Velocity3() {} Velocity3(type_zero) : vLin(ZERO), vRot(ZERO) {} Velocity3(Vec3 const& vLin) : vLin(vLin), vRot(ZERO) {} Velocity3(Vec3 const& vLin, Vec3 const& vRot) : vLin(vLin), vRot(vRot) {} void FromDelta(QuatT const& loc0, QuatT const& loc1, float fTime) { float fInvT = 1.f / fTime; vLin = (loc1.t - loc0.t) * fInvT; vRot = Quat::log(loc1.q * loc0.q.GetInverted()) * fInvT; } Vec3 VelocityAt(Vec3 const& vPosRel) const { return vLin + (vRot % vPosRel); } void operator += (Velocity3 const& vv) { vLin += vv.vLin; vRot += vv.vRot; } void operator *= (float f) { vLin *= f; vRot *= f; } void Interp(Velocity3 const& vv, float f) { vLin += (vv.vLin - vLin) * f; vRot += (vv.vRot - vRot) * f; } }; ////////////////////////////////////////////////////////////////////////// #include "Cry_GeoDistance.h" #include "Cry_GeoOverlap.h" #include "Cry_GeoIntersect.h" ///////////////////////////////////////////////////////////////////////// //this is some special engine stuff, should be moved to a better location ///////////////////////////////////////////////////////////////////////// // for bbox's checks and calculations #define MAX_BB +99999.0f #define MIN_BB -99999.0f //! checks if this has been set to minBB inline bool IsMinBB( const Vec3& v ) { if (v.x<=MIN_BB) return (true); if (v.y<=MIN_BB) return (true); if (v.z<=MIN_BB) return (true); return (false); } //! checks if this has been set to maxBB inline bool IsMaxBB( const Vec3& v ) { if (v.x>=MAX_BB) return (true); if (v.y>=MAX_BB) return (true); if (v.z>=MAX_BB) return (true); return (false); } inline Vec3 SetMaxBB( void ) { return Vec3(MAX_BB,MAX_BB,MAX_BB); } inline Vec3 SetMinBB( void ) { return Vec3(MIN_BB,MIN_BB,MIN_BB); } inline void AddToBounds (const Vec3& v, Vec3& mins, Vec3& maxs) { if (v.x < mins.x) mins.x = v.x; if (v.x > maxs.x) maxs.x = v.x; if (v.y < mins.y) mins.y = v.y; if (v.y > maxs.y) maxs.y = v.y; if (v.z < mins.z) mins.z = v.z; if (v.z > maxs.z) maxs.z = v.z; } //////////////////////////////////////////////////////////////// //! calc the area of a polygon giving a list of vertices and normal inline float CalcArea(const Vec3 *vertices,int numvertices,const Vec3 &normal) { Vec3 csum(0,0,0); int n=numvertices; for (int i = 0, j = 1; i <= n-2; i++, j++) { csum.x += vertices[i].y*vertices[j].z-vertices[i].z*vertices[j].y; csum.y += vertices[i].z*vertices[j].x-vertices[i].x*vertices[j].z; csum.z += vertices[i].x*vertices[j].y-vertices[i].y*vertices[j].x; } csum.x += vertices[n-1].y*vertices[0].z-vertices[n-1].z*vertices[0].y; csum.y += vertices[n-1].z*vertices[0].x-vertices[n-1].x*vertices[0].z; csum.z += vertices[n-1].x*vertices[0].y-vertices[n-1].y*vertices[0].x; float area=0.5f*(float)fabs(normal|csum); return (area); } #endif //geostructs
[ "eliashogstvedt@gmail.com" ]
eliashogstvedt@gmail.com
b343257f62ad8fa85c6a00d847d96cb4d30eb853
3a8e503170c50a466b3c7f42973291637f0cff17
/Source/ConditionFactory.cpp
3ec325f6530e248c934fda3a27f8c1e4a52b82ef
[ "Unlicense" ]
permissive
haskellstudio/Chataigne
4388aed28358360ab222ea99baaaba1ee06ec49c
b8fcbb9d14f61cce4c8a95e22aa11edf0cd165e3
refs/heads/master
2021-01-15T12:42:53.871648
2017-07-09T10:19:49
2017-07-09T10:19:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,491
cpp
/* ============================================================================== ConditionFactory.cpp Created: 21 Feb 2017 11:56:12am Author: Ben ============================================================================== */ #include "ConditionFactory.h" #include "StandardCondition.h" #include "ConditionGroup.h" #include "ScriptCondition.h" juce_ImplementSingleton(ConditionFactory) ConditionFactory::ConditionFactory() { conditionDefs.add(new ConditionDefinition("", "Standard", &StandardCondition::create)); conditionDefs.add(new ConditionDefinition("", "Group", &ConditionGroup::create)); conditionDefs.add(new ConditionDefinition("", "Script", &ScriptCondition::create)); buildPopupMenu(); } void ConditionFactory::buildPopupMenu() { OwnedArray<PopupMenu> subMenus; Array<String> subMenuNames; for (auto &d : conditionDefs) { int itemID = conditionDefs.indexOf(d) + 1;//start at 1 for menu if (d->menuPath.isEmpty()) { menu.addItem(itemID, d->conditionType); continue; } int subMenuIndex = -1; for (int i = 0; i < subMenus.size(); i++) { if (subMenuNames[i] == d->menuPath) { subMenuIndex = i; break; } } if (subMenuIndex == -1) { subMenuNames.add(d->menuPath); subMenus.add(new PopupMenu()); subMenuIndex = subMenus.size() - 1; } subMenus[subMenuIndex]->addItem(itemID, d->conditionType); } for (int i = 0; i < subMenus.size(); i++) menu.addSubMenu(subMenuNames[i], *subMenus[i]); }
[ "bkuperberg@gmail.com" ]
bkuperberg@gmail.com
dd17d7c21ea7074d6972d7f60d13a5cdca224f80
d4a240f412b0b9df47fe5efb9864a776b5522bce
/src/pwm_controlled_peltier/pwm_controlled_peltier.ino
7bd59723e34d17488f32594a4e49607a776d8f5b
[]
no_license
ideapod/peltier-fermenter
12a3d3ca201e9d3eb7f9f9cc48d37de363dd76b5
4707b6522e40ea4cd81f5e32f4f2c0d2a96c1422
refs/heads/master
2021-01-25T04:01:49.199262
2013-12-05T04:43:51
2013-12-05T04:43:51
10,396,660
1
0
null
null
null
null
UTF-8
C++
false
false
658
ino
////////////////////////////////////////////////////////////////// //©2011 bildr //Released under the MIT License - Please reuse change and share //Simple code to output a PWM sine wave signal on pin 9 ////////////////////////////////////////////////////////////////// const int fadePin = 3; void setup(){ pinMode(fadePin, OUTPUT); } void loop(){ for(int i = 0; i<360; i++){ //convert 0-360 angle to radian (needed for sin function) float rad = DEG_TO_RAD * i; //calculate sin of angle as number between 0 and 255 int sinOut = constrain((sin(rad) * 128) + 128, 0, 255); analogWrite(fadePin, sinOut); delay(15); } }
[ "ideapod@optusnet.com.au" ]
ideapod@optusnet.com.au
2bae34337f866cad41f63f20cae23d80c5579256
09e691cd33d9eab57b903d717e8e65194aedcca7
/SDK/PUBG_CustomizableObject_parameters.hpp
8acf11fd26ad4123e1f241eed0c4ad88b2f6be58
[]
no_license
violarulan/PUBG-SDK
8a6ed46abe103147c772cd31cf1e07541a99e844
148a48829ef23355a2a6a3ecb286985677f4e274
refs/heads/master
2021-01-06T20:40:15.064387
2017-08-03T16:24:22
2017-08-03T16:24:22
99,541,605
1
0
null
2017-08-07T05:55:34
2017-08-07T05:55:34
null
UTF-8
C++
false
false
506
hpp
#pragma once // PLAYERUNKNOWN'S BATTLEGROUNDS (2.5.26) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace Classes { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function CustomizableObject.CustomizableObjectInstance.SetRandomValues struct UCustomizableObjectInstance_SetRandomValues_Params { }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "pubgsdk@gmail.com" ]
pubgsdk@gmail.com
6452291cc09c45c3fc97f9d46b78e8329b889906
da5e146576291666521269108b583ec6f7c76f5a
/SolidSBCSDK/src/net/CSolidSBCSocketResult.h
a15a766d76c361a7eb31ab18959c6bc59c08c91e
[]
no_license
M0WA/SolidSBCLinux
8a1a477effa56a21592c8a55fd382d962c68176e
72e8aabbff9fd815ac2ea60381707618a73ea4ce
refs/heads/master
2020-04-19T14:40:38.413911
2011-11-20T03:49:43
2011-11-20T03:49:43
168,250,400
0
0
null
null
null
null
UTF-8
C++
false
false
829
h
/* * CSolidSBCSocketResult.h * * Created on: 05.09.2011 * Author: Moritz Wagner */ #ifndef CSOLIDSBCSOCKETRESULT_H_ #define CSOLIDSBCSOCKETRESULT_H_ #include "CSolidSBCSocket.h" class CSolidSBCSocketResult: public CSolidSBCSocket { public: CSolidSBCSocketResult(); virtual ~CSolidSBCSocketResult(); virtual _SSBC_SOCKET_CONNECT_STATE Connect(const std::string& sHost, const short nPort, const std::string& sClientName, const std::string& sUuid, OnConnectCallback pCallback = 0); bool IsInitialized(void) const {return m_bInitialized;} static void* OnConnect(const CSolidSBCSocket::_SSBC_SOCKET_CONNECT_STATE nState, CSolidSBCSocket::_PSSBC_SOCKET_PARAM pConnectParams); private: std::string m_sClientName; std::string m_sUuid; volatile bool m_bInitialized; }; #endif /* CSOLIDSBCSOCKETRESULT_H_ */
[ "admin@12d8b6cd-ff96-4cb4-b477-b191590c26b9" ]
admin@12d8b6cd-ff96-4cb4-b477-b191590c26b9
ffe35c8d770c8f4c7de6f0c50c3e548bf781e71d
1f1e6cf88fb2de1ea55db73d03232157bf37495c
/metaq-client4cpp/ext/lwpr/src/EventNetDispatch.cpp
db164dd8a4cfcd104d3165cb639f8f5a1b45e702
[ "Apache-2.0" ]
permissive
abscasey/metaq
5f84615181c56164e843b33cd5001d045cc70535
62496e978d431bb8c74a17eec95309c7e41bb309
refs/heads/master
2020-12-25T11:05:16.336529
2014-12-15T11:18:28
2014-12-15T11:18:28
null
0
0
null
null
null
null
GB18030
C++
false
false
13,355
cpp
/* * $Id: EventNetDispatch.cpp 3 2011-08-19 02:25:45Z $ */ #include "EventNetDispatch.h" #include "Synchronized.h" #include "Utility.h" #include <assert.h> namespace LWPR { //---------------------------------------------------------------------------------- // class EventNetHandler //---------------------------------------------------------------------------------- SOCKET_RET_TYPE_E EventNetHandler::DoReceiveNormalData(SOCKET_FD_T fd) { assert(fd >= 0); return SOCKET_RET_OK; } SOCKET_RET_TYPE_E EventNetHandler::DoReceiveConnection(SOCKET_FD_T fd) { assert(fd >= 0); return SOCKET_RET_OK; } LWPR::SOCKET_RET_TYPE_E EventNetHandler::DoCloseExpiredSocket(SOCKET_FD_T fd) { assert(fd >= 0); return SOCKET_RET_OK; } //---------------------------------------------------------------------------------- // struct event_net_option //---------------------------------------------------------------------------------- event_net_option::event_net_option() : strIP("0.0.0.0"), nMinPort(0), nMaxPort(0), nThreadPoolMin(5), nThreadPoolMax(300), nThreadPoolMaxIdle(100), nHousekeepInterval(60 * 10), nSocketExpiredTime(60 * 20), bAllowDoHousekeep(false), bAllowDoCloseHandler(false), bAllowDoRcvConnHandler(false), pHandler(NULL) { } //---------------------------------------------------------------------------------- // class EventNetDispatch //---------------------------------------------------------------------------------- EventNetDispatch::EventNetDispatch(EVENT_NET_OPTION_T& opt) : m_EventNetOption(opt), m_nIdleThread(0), m_nTotalThread(0) { if(m_EventNetOption.nMaxPort == 0) { m_EventNetOption.nMaxPort = m_EventNetOption.nMinPort; } assert(m_EventNetOption.nMinPort >= 0); assert(m_EventNetOption.nMaxPort >= 0); assert(m_EventNetOption.nThreadPoolMin > 0); assert(m_EventNetOption.nThreadPoolMax > 0); assert(m_EventNetOption.nThreadPoolMaxIdle > 0); assert(m_EventNetOption.nHousekeepInterval > 0); assert(m_EventNetOption.nSocketExpiredTime > 0); assert(m_EventNetOption.pHandler != NULL); FD_ZERO(&m_setActiveFd); m_listReadableSocket.reserve(FD_SETSIZE + 1); opt.pHandler->SetEventNetDispatch(this); } EventNetDispatch::~EventNetDispatch() { if(m_EventNetOption.pHandler != NULL) { delete m_EventNetOption.pHandler; } } void EventNetDispatch::Activate() { // 创建监听端口 m_fdListen = Socket::CreateServerTCPSocket(m_EventNetOption.nMinPort, m_EventNetOption.nMaxPort, m_EventNetOption.strIP.c_str()); if(m_fdListen == -1) { throw LWPR_EVENT_NET_CREATE_SERVER_SOCKET_ERROR(EXCEPTION_TRACE, "CreateServerTCPSocket error"); } // 连接自身,(当Server端socket监听端口建立后,client端的connect动作就会顺利完成三路握手,并返回) std::string strSelfIP = (m_EventNetOption.strIP == "0.0.0.0" ? "127.0.0.1" : m_EventNetOption.strIP); m_fdConnSelfClient = Socket::ConnectRemoteHost(strSelfIP.c_str(), m_EventNetOption.nMinPort); if(m_fdConnSelfClient == -1) { throw LWPR_EVENT_NET_CONNECT_SELEF_ERROR(EXCEPTION_TRACE, "ConnectRemoteHost error"); } // 连接自身 m_fdConnSelfServer = Socket::AcceptSocket(m_fdListen); if(m_fdConnSelfClient == -1) { throw LWPR_EVENT_NET_CONNECT_SELEF_ERROR(EXCEPTION_TRACE, "AcceptSocket error"); } // 校验自身Socket // 通过m_fdConnSelfClient写入本进程号,并通过m_fdConnSelfServer读出,如果未能成功读出, // 或者读出的进程号与写入的不同,则认为m_fdConnSelfClient与m_fdConnSelfServer不配套 PID_T nPid = Utility::GetPid(); SOCKET_RET_TYPE_E nRet = Socket::WriteSocket(m_fdConnSelfClient, (const char*)&nPid, sizeof(nPid)); if(nRet != SOCKET_RET_OK) { throw LWPR_EVENT_NET_CONNECT_SELEF_ERROR(EXCEPTION_TRACE, "WriteSocket error"); } Buffer buf; nRet = Socket::ReadSocket(m_fdConnSelfServer, buf, sizeof(nPid), 0); if(nRet != SOCKET_RET_OK) { throw LWPR_EVENT_NET_CONNECT_SELEF_ERROR(EXCEPTION_TRACE, "ReadSocket error"); } PID_T* pPid = (PID_T*)buf.Inout(); if(*pPid != nPid) { throw LWPR_EVENT_NET_CONNECT_SELEF_ERROR(EXCEPTION_TRACE, "m_fdConnSelfServer accept other process request"); } // 取最大socket m_fdMax = (m_fdConnSelfClient > m_fdListen) ? m_fdConnSelfClient : m_fdListen; // 设置m_fdActive FD_SET(m_fdListen, &m_setActiveFd); FD_SET(m_fdConnSelfServer, &m_setActiveFd); // 创建线程对象,并启动线程 for(int i = 0; i < m_EventNetOption.nThreadPoolMin; i++) { EventNetWorkThread* pThread = new EventNetWorkThread(*this); pThread->Start(); m_listThread.push_back(pThread); } // 启动管理线程 this->Start(); } void EventNetDispatch::Halt() { SOCKET_SELF_MSG_T msg; msg.nMsgType = SOCKET_SELF_MSG_EXIT_THREAD; msg.nSocketFd = 0; { Synchronized syn(m_MutexClient); Socket::WriteSocket(m_fdConnSelfClient, (const char*)&msg, sizeof(msg)); } Socket::CloseSocket(m_fdListen); this->StopRunning(); } void EventNetDispatch::Run() { while(IsContinue()) { // 以后会替换成wait Thread::Sleep(3); // 清理死去的线程 ClearDeadThread(); // 动态调整线程池 if(IsServiceBusy()) { if(m_nTotalThread < m_EventNetOption.nThreadPoolMax) { EventNetWorkThread* pThread = new EventNetWorkThread(*this); pThread->Start(); m_listThread.push_back(pThread); } } else { if(m_nIdleThread > m_EventNetOption.nThreadPoolMaxIdle) { EventNetWorkThread* pThread = m_listThread.front(); if(pThread != NULL) { pThread->StopRunning(); } } } } // 令线程池中线程退出 std::list< EventNetWorkThread* >::iterator it = m_listThread.begin(); for(; it != m_listThread.end(); it++) { (*it)->StopRunning(); } // 清理线程资源 for(int i = 0; i < 5 && m_listThread.size() > 0; i++) { ClearDeadThread(); Thread::Sleep(1); } Socket::CloseSocket(m_fdConnSelfServer); Socket::CloseSocket(m_fdConnSelfClient); } void EventNetDispatch::MakeSocketDispatching(SOCKET_FD_T fd) { assert(fd >= 0); SOCKET_SELF_MSG_T msg; msg.nMsgType = SOCKET_SELF_MSG_ADD_FD; msg.nSocketFd = fd; Synchronized syn(m_MutexClient); LWPR::SOCKET_RET_TYPE_E nRet = Socket::WriteSocket(m_fdConnSelfClient, (const char*)&msg, sizeof(msg)); if(nRet != LWPR::SOCKET_RET_OK) { // 信号发生时,会执行到这里 LWPR::Socket::CloseSocket(fd); } } bool EventNetDispatch::IsServiceBusy() { // 认为线程池的负载正常 bool bResult = (m_nIdleThread >= 3); return !bResult; } void EventNetDispatch::ClearDeadThread() { std::list< EventNetWorkThread* >::iterator it = m_listThread.begin(); for(; it != m_listThread.end();) { if(!(*it)->IsContinue() && (*it)->IsExited()) { delete(*it); m_listThread.erase(it); } else { it++; } } } //---------------------------------------------------------------------------------- // class EventNetThreadImpl //---------------------------------------------------------------------------------- EventNetWorkThread::EventNetWorkThread(EventNetDispatch& dispatch) : m_EventNetDispatch(dispatch) { } EventNetWorkThread::~EventNetWorkThread() { } void EventNetWorkThread::Run() { AutomaticCount autoTotalThread(m_EventNetDispatch.m_nTotalThread); while(IsContinue()) { try { // 可读socket SOCKET_FD_T nReadySocket = -1; { // 空闲线程计数 AutomaticCount autoIdleThread(m_EventNetDispatch.m_nIdleThread); // 加锁,获取可读的Socket(进入临界区) Synchronized syn(m_EventNetDispatch.m_MutexEvent); // 找一个可读socket,开始工作 if(m_EventNetDispatch.m_listReadableSocket.size() > 0) { nReadySocket = m_EventNetDispatch.m_listReadableSocket.back(); m_EventNetDispatch.m_listReadableSocket.pop_back(); } // 如果没有可读socket,则select while(-1 == nReadySocket) { // 判断当前线程是否可以继续执行 if(!m_EventNetDispatch.IsContinue()) { return; } fd_set setReadableFd; memcpy(&setReadableFd, &m_EventNetDispatch.m_setActiveFd, sizeof(m_EventNetDispatch.m_setActiveFd)); struct timeval tv = {0}; tv.tv_sec = m_EventNetDispatch.m_EventNetOption.nHousekeepInterval; tv.tv_usec = 0; struct timeval *ptv = &tv; if(!m_EventNetDispatch.m_EventNetOption.bAllowDoHousekeep) { ptv = NULL; } int nCode = select(m_EventNetDispatch.m_fdMax + 1, &setReadableFd, NULL, NULL, ptv); // 有socket可读 if(nCode > 0) { for(int i = 0; i <= m_EventNetDispatch.m_fdMax; i++) { if(FD_ISSET(i, &setReadableFd)) { // 更新socket最后活跃时间 m_EventNetDispatch.m_mapActiveFd[i] = time(NULL); // 处理新来连接 if(i == m_EventNetDispatch.m_fdListen) { SOCKET_FD_T fd = LWPR::Socket::AcceptSocket(i); if(fd != -1) { // 如果新来的连接超过select支持的最大数,则CloseSocket if(fd >= FD_SETSIZE) { Socket::CloseSocket(fd); } else { FD_SET(fd, &m_EventNetDispatch.m_setActiveFd); m_EventNetDispatch.m_mapActiveFd[fd] = time(NULL); m_EventNetDispatch.m_fdMax = (fd > m_EventNetDispatch.m_fdMax) ? fd : m_EventNetDispatch.m_fdMax; if(m_EventNetDispatch.m_EventNetOption.bAllowDoRcvConnHandler) { try { m_EventNetDispatch.m_EventNetOption.pHandler->DoReceiveConnection(fd); } catch(...) { } } } } } // 处理自身连接,用来内部控制信息的传递 else if(i == m_EventNetDispatch.m_fdConnSelfServer) { LWPR::Buffer buf; SOCKET_RET_TYPE_E res = Socket::ReadSocket(i, buf, sizeof(SOCKET_SELF_MSG_T)); if(res == SOCKET_RET_OK) { SOCKET_SELF_MSG_T* pMsg = (SOCKET_SELF_MSG_T*)buf.Inout(); switch(pMsg->nMsgType) { case SOCKET_SELF_MSG_ADD_FD: FD_SET(pMsg->nSocketFd, &m_EventNetDispatch.m_setActiveFd); m_EventNetDispatch.m_mapActiveFd[pMsg->nSocketFd] = time(NULL); break; case SOCKET_SELF_MSG_EXIT_THREAD: break; default: assert(0); } } } // 处理第一个可读socket else if(-1 == nReadySocket) { nReadySocket = i; FD_CLR(i, &m_EventNetDispatch.m_setActiveFd); } // 处理其余可读socket else { m_EventNetDispatch.m_listReadableSocket.push_back(i); FD_CLR(i, &m_EventNetDispatch.m_setActiveFd); } } } } // select 超时 else if(nCode == 0) { // 检查不活跃的socket if(m_EventNetDispatch.m_EventNetOption.bAllowDoHousekeep) { for(int i = 0; i <= m_EventNetDispatch.m_fdMax; i++) { if(FD_ISSET(i, &m_EventNetDispatch.m_setActiveFd)) { if(i == m_EventNetDispatch.m_fdListen) { } else if(i == m_EventNetDispatch.m_fdConnSelfServer) { } else { if((time(NULL) - m_EventNetDispatch.m_mapActiveFd[i]) >= m_EventNetDispatch.m_EventNetOption.nSocketExpiredTime) { if(m_EventNetDispatch.m_EventNetOption.bAllowDoCloseHandler) { try { m_EventNetDispatch.m_EventNetOption.pHandler->DoCloseExpiredSocket(i); } catch(...) { } } Socket::CloseSocket(i); FD_CLR(i, &m_EventNetDispatch.m_setActiveFd); } } } } } } } // end of while(-1 == nReadableSocket) } // end of Lock // 准备处理找到的连接 SOCKET_RET_TYPE_E nRet = SOCKET_RET_OK; try { nRet = m_EventNetDispatch.m_EventNetOption.pHandler->DoReceiveNormalData(nReadySocket); } catch(...) { nRet = SOCKET_RET_FAILED; } switch(nRet) { case SOCKET_RET_FAILED: case SOCKET_RET_TIMEOUT: Socket::CloseSocket(nReadySocket); break; case SOCKET_RET_OK: m_EventNetDispatch.MakeSocketDispatching(nReadySocket); break; case SOCKET_RET_FREE: break; default: assert(0); } } catch(const LWPR::Exception& e) { fprintf(stderr, "%s\n", e.what()); } } } };
[ "vintage.wang@gmail.com" ]
vintage.wang@gmail.com
eb7f7baad04196cbaa5773b72f87a96b4e5cb1f2
b66c34b4bb4a9e017f0af16b4ea055264fd04eb0
/Source/EndlessVehicleRunner/Vehicles/EVRVehicleAI.cpp
c7bb1264445127ed1e01ebbd56665c409be85918
[]
no_license
Stephen1902/EndlessVehicleRunner
798049912210420e23d8033eebbb8fac425c7698
f8e750fcf6238151c1b552a4a2d54c1057f61548
refs/heads/main
2023-08-06T20:40:27.796938
2021-09-30T20:00:55
2021-09-30T20:00:55
404,382,213
0
0
null
null
null
null
UTF-8
C++
false
false
4,201
cpp
// Copyright 2021 DME Games #include "EVRVehicleAI.h" #include "EVRVehiclePlayer.h" #include "Components/BoxComponent.h" #include "Kismet/GameplayStatics.h" AEVRVehicleAI::AEVRVehicleAI() { // Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; FrontOfVehicleCollision = CreateDefaultSubobject<UBoxComponent>(TEXT("Vehicle Front Collision")); FrontOfVehicleCollision->SetupAttachment(StaticMeshComp); FrontOfVehicleCollision->SetBoxExtent(FVector(64.f, 32.f, 32.f), false); FrontOfVehicleCollision->SetHiddenInGame(false); FrontOfVehicleCollision->OnComponentBeginOverlap.AddDynamic(this, &AEVRVehicleAI::OnFrontCollisionOverlap); StaticMeshComp->OnComponentBeginOverlap.AddDynamic(this, &AEVRVehicleAI::OnBeginOverlap); } void AEVRVehicleAI::BeginPlay() { Super::BeginPlay(); SetLifeSpan(40.f); SetReferences(); SetLocationOfFrontCollision(); // Enter a variation in speed for the vehicle in increments of 25 const int32 RandomSpeedVariation = FMath::RandRange(1, 4) * 25; if (FMath::RandRange(0, 1) == 0) { SetMaxSpeed(-RandomSpeedVariation); } else { SetMaxSpeed(RandomSpeedVariation); } } void AEVRVehicleAI::OnBeginOverlap(UPrimitiveComponent* HitComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult) { if (PlayerVehicleRef && OtherActor == PlayerVehicleRef) { const float PlayerLifeToRestore = PlayerVehicleRef->GetStartingLife() * (PlayerHealthRestored / 100.f); PlayerVehicleRef->ChangePlayerLife(-PlayerLifeToRestore); float PlayerSpeedToReduce = PlayerVehicleRef->GetMaxSpeed() * (PlayerSpeedDecrease / 100.f); // Calculate if player hits a moving spawn from behind or from the side and adjust speed accordingly. const FVector PlayerCurrentPosition = PlayerVehicleRef->StaticMeshComp->GetComponentLocation(); const FVector SpawnCurrentPosition = GetActorLocation(); // Check to see if the player is travelling along the X or Y Axis. if (PlayerVehicleRef->GetActorForwardVector().X != 1.f) { // Check whether the Y locations match. If not, the hit is on the side and the speed loss is reduced. if (!FMath::IsNearlyEqual(PlayerCurrentPosition.Y, SpawnCurrentPosition.Y, 1.0f)) { PlayerSpeedToReduce *= .5f; } } else { // Check whether the X locations match. If not, the hit is on the side and the speed loss is reduced. if (!FMath::IsNearlyEqual(PlayerCurrentPosition.X, SpawnCurrentPosition.X, 1.0f)) { PlayerSpeedToReduce *= .5f; } } PlayerVehicleRef->SetCurrentSpeed(PlayerSpeedToReduce); if (EndOfLifeParticle) { const FVector LocationToSpawnParticle = StaticMeshComp->GetComponentLocation(); UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), EndOfLifeParticle, LocationToSpawnParticle, GetActorRotation()); } if (EndOfLifeSound) { UGameplayStatics::PlaySound2D(GetWorld(), EndOfLifeSound); } Destroy(); } } void AEVRVehicleAI::OnFrontCollisionOverlap(UPrimitiveComponent* HitComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult) { AEVRVehicleAI* VehicleHit = Cast<AEVRVehicleAI>(OtherActor); if (HornSound && VehicleHit && !bIsTurning) { // Only play the horn 1 in 3 times if (FMath::RandRange(0, 2) == 0) { UGameplayStatics::PlaySoundAtLocation(GetWorld(), HornSound, GetActorLocation()); } switch(LocationIndex) { case 0: TurnRight(); break; case 1: default: if (FMath::RandRange(0, 1) == 0) { TurnLeft(); } else { TurnRight(); } break; case 2: TurnLeft(); break; } } } void AEVRVehicleAI::SetReferences() { PlayerVehicleRef = Cast<AEVRVehiclePlayer>(GetWorld()->GetFirstPlayerController()->GetPawn()); } void AEVRVehicleAI::SetLocationOfFrontCollision() const { FVector LocalMin; FVector LocalMax; StaticMeshComp->GetLocalBounds(LocalMin, LocalMax); const float NewBoxLocation = (LocalMax.X + 68.f); FrontOfVehicleCollision->SetRelativeLocation(FVector(NewBoxLocation, 0.f, 100.f)); }
[ "s_nichols_other@yahoo.co.uk" ]
s_nichols_other@yahoo.co.uk
f7483fd6dc2a422aa0d0759ca4c1942bc906420c
7c742432f93af1bd8a2bc5a0e4e7f2dd4539d10f
/Code/477_Total_Hamming_Distance.cpp
1fdbea18e34d29fee35e95cf48bc0a6b8e0bed6e
[]
no_license
FeibHwang/OJ-Leetcode
f84725c78e376cd1f115d62578db5c7e9ba6cb4a
71700a5cfe6319a248253a61b67a8f406c5a091f
refs/heads/master
2021-01-16T22:09:25.581307
2017-03-09T20:29:53
2017-03-09T20:29:53
64,374,675
0
0
null
null
null
null
UTF-8
C++
false
false
1,202
cpp
/* The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Now your job is to find the total Hamming distance between all pairs of the given numbers. Example: Input: 4, 14, 2 Output: 6 Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just showing the four bits relevant in this case). So the answer will be: HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6. Note: Elements of the given array are in the range of 0 to 10^9 Length of the array will not exceed 10^4. */ /* expand in bit wise couting the number of 1s in the same bit position of every element dist in this bit is (nums of 1s * nums of 0s) total dist is adding the 32 bit distance together */ class Solution { public: int totalHammingDistance(vector<int>& nums) { if(nums.size()<2) return 0; int res = 0; for(int i = 0; i < 32; ++i) { int cnt = 0; for(int j = 0; j < nums.size(); ++j) { cnt += (1 & (nums[j]>>i)); } res += cnt*(nums.size()-cnt); } return res; } };
[ "feibai.hwang@outlook.com" ]
feibai.hwang@outlook.com
f47a29e41e471019618b566f2dd1402b78f51ab2
82871bf2328b9d2ecc78b56ff77c57e6a2c21c7a
/cpp/include/cudf/io/orc.hpp
c2187f056cfd12d7547b87ff25624ff3926f347b
[ "Apache-2.0" ]
permissive
galipremsagar/cudf
63e3a7479b38a85e99aaf26fbbfb3f0545a29712
2c6b0dac61a6671642bb5b076e910e20e2bdd1b6
refs/heads/branch-22.04
2023-08-31T10:17:42.664118
2022-01-31T23:35:47
2022-01-31T23:35:47
190,782,603
0
0
Apache-2.0
2019-06-07T17:20:57
2019-06-07T17:20:56
null
UTF-8
C++
false
false
31,206
hpp
/* * Copyright (c) 2020-2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cudf/io/detail/orc.hpp> #include <cudf/io/types.hpp> #include <cudf/table/table_view.hpp> #include <cudf/types.hpp> #include <memory> #include <string> #include <unordered_map> #include <vector> namespace cudf { namespace io { /** * @addtogroup io_readers * @{ * @file */ constexpr size_t default_stripe_size_bytes = 64 * 1024 * 1024; constexpr size_type default_stripe_size_rows = 1000000; constexpr size_type default_row_index_stride = 10000; /** * @brief Builds settings to use for `read_orc()`. */ class orc_reader_options_builder; /** * @brief Settings to use for `read_orc()`. */ class orc_reader_options { source_info _source; // Names of column to read; empty is all std::vector<std::string> _columns; // List of individual stripes to read (ignored if empty) std::vector<std::vector<size_type>> _stripes; // Rows to skip from the start; size_type _skip_rows = 0; // Rows to read; -1 is all size_type _num_rows = -1; // Whether to use row index to speed-up reading bool _use_index = true; // Whether to use numpy-compatible dtypes bool _use_np_dtypes = true; // Cast timestamp columns to a specific type data_type _timestamp_type{type_id::EMPTY}; // Columns that should be converted from Decimal to Float64 std::vector<std::string> _decimal_cols_as_float; // Columns that should be read as Decimal128 std::vector<std::string> _decimal128_columns; friend orc_reader_options_builder; /** * @brief Constructor from source info. * * @param src source information used to read orc file. */ explicit orc_reader_options(source_info const& src) : _source(src) {} public: /** * @brief Default constructor. * * This has been added since Cython requires a default constructor to create objects on stack. */ orc_reader_options() = default; /** * @brief Creates `orc_reader_options_builder` which will build `orc_reader_options`. * * @param src Source information to read orc file. * @return Builder to build reader options. */ static orc_reader_options_builder builder(source_info const& src); /** * @brief Returns source info. */ [[nodiscard]] source_info const& get_source() const { return _source; } /** * @brief Returns names of the columns to read. */ [[nodiscard]] std::vector<std::string> const& get_columns() const { return _columns; } /** * @brief Returns vector of vectors, stripes to read for each input source */ std::vector<std::vector<size_type>> const& get_stripes() const { return _stripes; } /** * @brief Returns number of rows to skip from the start. */ size_type get_skip_rows() const { return _skip_rows; } /** * @brief Returns number of row to read. */ size_type get_num_rows() const { return _num_rows; } /** * @brief Whether to use row index to speed-up reading. */ bool is_enabled_use_index() const { return _use_index; } /** * @brief Whether to use numpy-compatible dtypes. */ bool is_enabled_use_np_dtypes() const { return _use_np_dtypes; } /** * @brief Returns timestamp type to which timestamp column will be cast. */ data_type get_timestamp_type() const { return _timestamp_type; } /** * @brief Fully qualified names of columns that should be converted from Decimal to Float64. */ std::vector<std::string> const& get_decimal_cols_as_float() const { return _decimal_cols_as_float; } /** * @brief Fully qualified names of columns that should be read as 128-bit Decimal. */ std::vector<std::string> const& get_decimal128_columns() const { return _decimal128_columns; } // Setters /** * @brief Sets names of the column to read. * * @param col_names Vector of column names. */ void set_columns(std::vector<std::string> col_names) { _columns = std::move(col_names); } /** * @brief Sets list of stripes to read for each input source * * @param stripes Vector of vectors, mapping stripes to read to input sources */ void set_stripes(std::vector<std::vector<size_type>> stripes) { CUDF_EXPECTS(stripes.empty() or (_skip_rows == 0), "Can't set stripes along with skip_rows"); CUDF_EXPECTS(stripes.empty() or (_num_rows == -1), "Can't set stripes along with num_rows"); _stripes = std::move(stripes); } /** * @brief Sets number of rows to skip from the start. * * @param rows Number of rows. */ void set_skip_rows(size_type rows) { CUDF_EXPECTS(rows == 0 or _stripes.empty(), "Can't set both skip_rows along with stripes"); _skip_rows = rows; } /** * @brief Sets number of row to read. * * @param nrows Number of rows. */ void set_num_rows(size_type nrows) { CUDF_EXPECTS(nrows == -1 or _stripes.empty(), "Can't set both num_rows along with stripes"); _num_rows = nrows; } /** * @brief Enable/Disable use of row index to speed-up reading. * * @param use Boolean value to enable/disable row index use. */ void enable_use_index(bool use) { _use_index = use; } /** * @brief Enable/Disable use of numpy-compatible dtypes * * @param use Boolean value to enable/disable. */ void enable_use_np_dtypes(bool use) { _use_np_dtypes = use; } /** * @brief Sets timestamp type to which timestamp column will be cast. * * @param type Type of timestamp. */ void set_timestamp_type(data_type type) { _timestamp_type = type; } /** * @brief Set columns that should be converted from Decimal to Float64 * * @param val Vector of fully qualified column names. */ [[deprecated( "Decimal to float conversion is deprecated and will be remove in future release")]] void set_decimal_cols_as_float(std::vector<std::string> val) { _decimal_cols_as_float = std::move(val); } /** * @brief Set columns that should be read as 128-bit Decimal * * @param val Vector of fully qualified column names. */ void set_decimal128_columns(std::vector<std::string> val) { _decimal128_columns = std::move(val); } }; class orc_reader_options_builder { orc_reader_options options; public: /** * @brief Default constructor. * * This has been added since Cython requires a default constructor to create objects on stack. */ explicit orc_reader_options_builder() = default; /** * @brief Constructor from source info. * * @param src The source information used to read orc file. */ explicit orc_reader_options_builder(source_info const& src) : options{src} {}; /** * @brief Sets names of the column to read. * * @param col_names Vector of column names. * @return this for chaining. */ orc_reader_options_builder& columns(std::vector<std::string> col_names) { options._columns = std::move(col_names); return *this; } /** * @brief Sets list of individual stripes to read per source * * @param stripes Vector of vectors, mapping stripes to read to input sources * @return this for chaining. */ orc_reader_options_builder& stripes(std::vector<std::vector<size_type>> stripes) { options.set_stripes(std::move(stripes)); return *this; } /** * @brief Sets number of rows to skip from the start. * * @param rows Number of rows. * @return this for chaining. */ orc_reader_options_builder& skip_rows(size_type rows) { options.set_skip_rows(rows); return *this; } /** * @brief Sets number of row to read. * * @param nrows Number of rows. * @return this for chaining. */ orc_reader_options_builder& num_rows(size_type nrows) { options.set_num_rows(nrows); return *this; } /** * @brief Enable/Disable use of row index to speed-up reading. * * @param use Boolean value to enable/disable row index use. * @return this for chaining. */ orc_reader_options_builder& use_index(bool use) { options._use_index = use; return *this; } /** * @brief Enable/Disable use of numpy-compatible dtypes. * * @param use Boolean value to enable/disable. * @return this for chaining. */ orc_reader_options_builder& use_np_dtypes(bool use) { options._use_np_dtypes = use; return *this; } /** * @brief Sets timestamp type to which timestamp column will be cast. * * @param type Type of timestamp. * @return this for chaining. */ orc_reader_options_builder& timestamp_type(data_type type) { options._timestamp_type = type; return *this; } /** * @brief Columns that should be converted from decimals to float64. * * @param val Vector of column names. * @return this for chaining. */ [[deprecated( "Decimal to float conversion is deprecated and will be remove in future " "release")]] orc_reader_options_builder& decimal_cols_as_float(std::vector<std::string> val) { options._decimal_cols_as_float = std::move(val); return *this; } /** * @brief Columns that should be read as 128-bit Decimal * * @param val Vector of column names. * @return this for chaining. */ orc_reader_options_builder& decimal128_columns(std::vector<std::string> val) { options._decimal128_columns = std::move(val); return *this; } /** * @brief move orc_reader_options member once it's built. */ operator orc_reader_options&&() { return std::move(options); } /** * @brief move orc_reader_options member once it's built. * * This has been added since Cython does not support overloading of conversion operators. */ orc_reader_options&& build() { return std::move(options); } }; /** * @brief Reads an ORC dataset into a set of columns. * * The following code snippet demonstrates how to read a dataset from a file: * @code * auto source = cudf::io::source_info("dataset.orc"); * auto options = cudf::io::orc_reader_options::builder(source); * auto result = cudf::io::read_orc(options); * @endcode * * Note: Support for reading files with struct columns is currently experimental, the output may not * be as reliable as reading for other datatypes. * * @param options Settings for controlling reading behavior. * @param mr Device memory resource used to allocate device memory of the table in the returned * table_with_metadata. * * @return The set of columns. */ table_with_metadata read_orc( orc_reader_options const& options, rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** @} */ // end of group /** * @addtogroup io_writers * @{ * @file */ /** * @brief Builds settings to use for `write_orc()`. */ class orc_writer_options_builder; /** * @brief Constants to disambiguate statistics terminology for ORC. * * ORC refers to its finest granularity of row-grouping as "row group", * which corresponds to Parquet "pages". * Similarly, ORC's "stripe" corresponds to a Parquet "row group". * The following constants disambiguate the terminology for the statistics * collected at each level. */ static constexpr statistics_freq ORC_STATISTICS_STRIPE = statistics_freq::STATISTICS_ROWGROUP; static constexpr statistics_freq ORC_STATISTICS_ROW_GROUP = statistics_freq::STATISTICS_PAGE; /** * @brief Settings to use for `write_orc()`. */ class orc_writer_options { // Specify the sink to use for writer output sink_info _sink; // Specify the compression format to use compression_type _compression = compression_type::AUTO; // Specify frequency of statistics collection statistics_freq _stats_freq = ORC_STATISTICS_ROW_GROUP; // Maximum size of each stripe (unless smaller than a single row group) size_t _stripe_size_bytes = default_stripe_size_bytes; // Maximum number of rows in stripe (unless smaller than a single row group) size_type _stripe_size_rows = default_stripe_size_rows; // Row index stride (maximum number of rows in each row group) size_type _row_index_stride = default_row_index_stride; // Set of columns to output table_view _table; // Optional associated metadata const table_input_metadata* _metadata = nullptr; // Optional footer key_value_metadata std::map<std::string, std::string> _user_data; friend orc_writer_options_builder; /** * @brief Constructor from sink and table. * * @param sink The sink used for writer output. * @param table Table to be written to output. */ explicit orc_writer_options(sink_info const& sink, table_view const& table) : _sink(sink), _table(table) { } public: /** * @brief Default constructor. * * This has been added since Cython requires a default constructor to create objects on stack. */ explicit orc_writer_options() = default; /** * @brief Create builder to create `orc_writer_options`. * * @param sink The sink used for writer output. * @param table Table to be written to output. * * @return Builder to build `orc_writer_options`. */ static orc_writer_options_builder builder(sink_info const& sink, table_view const& table); /** * @brief Returns sink info. */ [[nodiscard]] sink_info const& get_sink() const { return _sink; } /** * @brief Returns compression type. */ [[nodiscard]] compression_type get_compression() const { return _compression; } /** * @brief Whether writing column statistics is enabled/disabled. */ [[nodiscard]] bool is_enabled_statistics() const { return _stats_freq != statistics_freq::STATISTICS_NONE; } /** * @brief Returns frequency of statistics collection. */ [[nodiscard]] statistics_freq get_statistics_freq() const { return _stats_freq; } /** * @brief Returns maximum stripe size, in bytes. */ [[nodiscard]] auto get_stripe_size_bytes() const { return _stripe_size_bytes; } /** * @brief Returns maximum stripe size, in rows. */ [[nodiscard]] auto get_stripe_size_rows() const { return _stripe_size_rows; } /** * @brief Returns the row index stride. */ auto get_row_index_stride() const { auto const unaligned_stride = std::min(_row_index_stride, get_stripe_size_rows()); return unaligned_stride - unaligned_stride % 8; } /** * @brief Returns table to be written to output. */ [[nodiscard]] table_view get_table() const { return _table; } /** * @brief Returns associated metadata. */ [[nodiscard]] table_input_metadata const* get_metadata() const { return _metadata; } /** * @brief Returns Key-Value footer metadata information. */ [[nodiscard]] std::map<std::string, std::string> const& get_key_value_metadata() const { return _user_data; } // Setters /** * @brief Sets compression type. * * @param comp Compression type. */ void set_compression(compression_type comp) { _compression = comp; } /** * @brief Choose granularity of statistics collection. * * The granularity can be set to: * - cudf::io::STATISTICS_NONE: No statistics are collected. * - cudf::io::ORC_STATISTICS_STRIPE: Statistics are collected for each ORC stripe. * - cudf::io::ORC_STATISTICS_ROWGROUP: Statistics are collected for each ORC row group. * * @param val Frequency of statistics collection. */ void enable_statistics(statistics_freq val) { _stats_freq = val; } /** * @brief Sets the maximum stripe size, in bytes. */ void set_stripe_size_bytes(size_t size_bytes) { CUDF_EXPECTS(size_bytes >= 64 << 10, "64KB is the minimum stripe size"); _stripe_size_bytes = size_bytes; } /** * @brief Sets the maximum stripe size, in rows. * * If the stripe size is smaller that the row group size, row group size will be reduced to math * the stripe size. */ void set_stripe_size_rows(size_type size_rows) { CUDF_EXPECTS(size_rows >= 512, "Maximum stripe size cannot be smaller than 512"); _stripe_size_rows = size_rows; } /** * @brief Sets the row index stride. * * Rounded down to a multiple of 8. */ void set_row_index_stride(size_type stride) { CUDF_EXPECTS(stride >= 512, "Row index stride cannot be smaller than 512"); _row_index_stride = stride; } /** * @brief Sets table to be written to output. * * @param tbl Table for the output. */ void set_table(table_view tbl) { _table = tbl; } /** * @brief Sets associated metadata * * @param meta Associated metadata. */ void set_metadata(table_input_metadata const* meta) { _metadata = meta; } /** * @brief Sets metadata. * * @param metadata Key-Value footer metadata */ void set_key_value_metadata(std::map<std::string, std::string> metadata) { _user_data = std::move(metadata); } }; class orc_writer_options_builder { orc_writer_options options; public: /** * @brief Default constructor. * * This has been added since Cython requires a default constructor to create objects on stack. */ orc_writer_options_builder() = default; /** * @brief Constructor from sink and table. * * @param sink The sink used for writer output. * @param table Table to be written to output. */ orc_writer_options_builder(sink_info const& sink, table_view const& table) : options{sink, table} { } /** * @brief Sets compression type. * * @param comp The compression type to use. * @return this for chaining. */ orc_writer_options_builder& compression(compression_type comp) { options._compression = comp; return *this; } /** * @brief Choose granularity of column statistics to be written * * The granularity can be set to: * - cudf::io::STATISTICS_NONE: No statistics are collected. * - cudf::io::ORC_STATISTICS_STRIPE: Statistics are collected for each ORC stripe. * - cudf::io::ORC_STATISTICS_ROWGROUP: Statistics are collected for each ORC row group. * * @param val Level of statistics collection. * @return this for chaining. */ orc_writer_options_builder& enable_statistics(statistics_freq val) { options._stats_freq = val; return *this; } /** * @brief Sets the maximum stripe size, in bytes. * * @param val maximum stripe size * @return this for chaining. */ orc_writer_options_builder& stripe_size_bytes(size_t val) { options.set_stripe_size_bytes(val); return *this; } /** * @brief Sets the maximum number of rows in output stripes. * * @param val maximum number or rows * @return this for chaining. */ orc_writer_options_builder& stripe_size_rows(size_type val) { options.set_stripe_size_rows(val); return *this; } /** * @brief Sets the row index stride. * * @param val new row index stride * @return this for chaining. */ orc_writer_options_builder& row_index_stride(size_type val) { options.set_row_index_stride(val); return *this; } /** * @brief Sets table to be written to output. * * @param tbl Table for the output. * @return this for chaining. */ orc_writer_options_builder& table(table_view tbl) { options._table = tbl; return *this; } /** * @brief Sets associated metadata. * * @param meta Associated metadata. * @return this for chaining. */ orc_writer_options_builder& metadata(table_input_metadata const* meta) { options._metadata = meta; return *this; } /** * @brief Sets Key-Value footer metadata. * * @param metadata Key-Value footer metadata * @return this for chaining. */ orc_writer_options_builder& key_value_metadata(std::map<std::string, std::string> metadata) { options._user_data = std::move(metadata); return *this; } /** * @brief move orc_writer_options member once it's built. */ operator orc_writer_options&&() { return std::move(options); } /** * @brief move orc_writer_options member once it's built. * * This has been added since Cython does not support overloading of conversion operators. */ orc_writer_options&& build() { return std::move(options); } }; /** * @brief Writes a set of columns to ORC format. * * The following code snippet demonstrates how to write columns to a file: * @code * auto destination = cudf::io::sink_info("dataset.orc"); * auto options = cudf::io::orc_writer_options::builder(destination, table->view()); * cudf::io::write_orc(options); * @endcode * * Note: Support for writing tables with struct columns is currently experimental, the output may * not be as reliable as writing for other datatypes. * * @param options Settings for controlling reading behavior. * @param mr Device memory resource to use for device memory allocation. */ void write_orc(orc_writer_options const& options, rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Builds settings to use for `write_orc_chunked()`. */ class chunked_orc_writer_options_builder; /** * @brief Settings to use for `write_orc_chunked()`. */ class chunked_orc_writer_options { // Specify the sink to use for writer output sink_info _sink; // Specify the compression format to use compression_type _compression = compression_type::AUTO; // Specify granularity of statistics collection statistics_freq _stats_freq = ORC_STATISTICS_ROW_GROUP; // Maximum size of each stripe (unless smaller than a single row group) size_t _stripe_size_bytes = default_stripe_size_bytes; // Maximum number of rows in stripe (unless smaller than a single row group) size_type _stripe_size_rows = default_stripe_size_rows; // Row index stride (maximum number of rows in each row group) size_type _row_index_stride = default_row_index_stride; // Optional associated metadata const table_input_metadata* _metadata = nullptr; // Optional footer key_value_metadata std::map<std::string, std::string> _user_data; friend chunked_orc_writer_options_builder; /** * @brief Constructor from sink and table. * * @param sink The sink used for writer output. */ chunked_orc_writer_options(sink_info const& sink) : _sink(sink) {} public: /** * @brief Default constructor. * * This has been added since Cython requires a default constructor to create objects on stack. */ explicit chunked_orc_writer_options() = default; /** * @brief Create builder to create `chunked_orc_writer_options`. * * @param sink The sink used for writer output. * * @return Builder to build chunked_orc_writer_options. */ static chunked_orc_writer_options_builder builder(sink_info const& sink); /** * @brief Returns sink info. */ [[nodiscard]] sink_info const& get_sink() const { return _sink; } /** * @brief Returns compression type. */ [[nodiscard]] compression_type get_compression() const { return _compression; } /** * @brief Returns granularity of statistics collection. */ [[nodiscard]] statistics_freq get_statistics_freq() const { return _stats_freq; } /** * @brief Returns maximum stripe size, in bytes. */ [[nodiscard]] auto get_stripe_size_bytes() const { return _stripe_size_bytes; } /** * @brief Returns maximum stripe size, in rows. */ [[nodiscard]] auto get_stripe_size_rows() const { return _stripe_size_rows; } /** * @brief Returns the row index stride. */ auto get_row_index_stride() const { auto const unaligned_stride = std::min(_row_index_stride, get_stripe_size_rows()); return unaligned_stride - unaligned_stride % 8; } /** * @brief Returns associated metadata. */ [[nodiscard]] table_input_metadata const* get_metadata() const { return _metadata; } /** * @brief Returns Key-Value footer metadata information. */ [[nodiscard]] std::map<std::string, std::string> const& get_key_value_metadata() const { return _user_data; } // Setters /** * @brief Sets compression type. * * @param comp The compression type to use. */ void set_compression(compression_type comp) { _compression = comp; } /** * @brief Choose granularity of statistics collection * * The granularity can be set to: * - cudf::io::STATISTICS_NONE: No statistics are collected. * - cudf::io::ORC_STATISTICS_STRIPE: Statistics are collected for each ORC stripe. * - cudf::io::ORC_STATISTICS_ROWGROUP: Statistics are collected for each ORC row group. * * @param val Frequency of statistics collection. */ void enable_statistics(statistics_freq val) { _stats_freq = val; } /** * @brief Sets the maximum stripe size, in bytes. */ void set_stripe_size_bytes(size_t size_bytes) { CUDF_EXPECTS(size_bytes >= 64 << 10, "64KB is the minimum stripe size"); _stripe_size_bytes = size_bytes; } /** * @brief Sets the maximum stripe size, in rows. * * If the stripe size is smaller that the row group size, row group size will be reduced to math * the stripe size. */ void set_stripe_size_rows(size_type size_rows) { CUDF_EXPECTS(size_rows >= 512, "maximum stripe size cannot be smaller than 512"); _stripe_size_rows = size_rows; } /** * @brief Sets the row index stride. * * Rounded down to a multiple of 8. */ void set_row_index_stride(size_type stride) { CUDF_EXPECTS(stride >= 512, "Row index stride cannot be smaller than 512"); _row_index_stride = stride; } /** * @brief Sets associated metadata. * * @param meta Associated metadata. */ void metadata(table_input_metadata const* meta) { _metadata = meta; } /** * @brief Sets Key-Value footer metadata. * * @param metadata Key-Value footer metadata */ void set_key_value_metadata(std::map<std::string, std::string> metadata) { _user_data = std::move(metadata); } }; class chunked_orc_writer_options_builder { chunked_orc_writer_options options; public: /** * @brief Default constructor. * * This has been added since Cython requires a default constructor to create objects on stack. */ chunked_orc_writer_options_builder() = default; /** * @brief Constructor from sink and table. * * @param sink The sink used for writer output. */ explicit chunked_orc_writer_options_builder(sink_info const& sink) : options{sink} {} /** * @brief Sets compression type. * * @param comp The compression type to use. * @return this for chaining. */ chunked_orc_writer_options_builder& compression(compression_type comp) { options._compression = comp; return *this; } /** * @brief Choose granularity of statistics collection * * The granularity can be set to: * - cudf::io::STATISTICS_NONE: No statistics are collected. * - cudf::io::ORC_STATISTICS_STRIPE: Statistics are collected for each ORC stripe. * - cudf::io::ORC_STATISTICS_ROWGROUP: Statistics are collected for each ORC row group. * * @param val Frequency of statistics collection. * @return this for chaining. */ chunked_orc_writer_options_builder& enable_statistics(statistics_freq val) { options._stats_freq = val; return *this; } /** * @brief Sets the maximum stripe size, in bytes. * * @param val maximum stripe size * @return this for chaining. */ chunked_orc_writer_options_builder& stripe_size_bytes(size_t val) { options.set_stripe_size_bytes(val); return *this; } /** * @brief Sets the maximum number of rows in output stripes. * * @param val maximum number or rows * @return this for chaining. */ chunked_orc_writer_options_builder& stripe_size_rows(size_type val) { options.set_stripe_size_rows(val); return *this; } /** * @brief Sets the row index stride. * * @param val new row index stride * @return this for chaining. */ chunked_orc_writer_options_builder& row_index_stride(size_type val) { options.set_row_index_stride(val); return *this; } /** * @brief Sets associated metadata. * * @param meta Associated metadata. * @return this for chaining. */ chunked_orc_writer_options_builder& metadata(table_input_metadata const* meta) { options._metadata = meta; return *this; } /** * @brief Sets Key-Value footer metadata. * * @param metadata Key-Value footer metadata * @return this for chaining. */ chunked_orc_writer_options_builder& key_value_metadata( std::map<std::string, std::string> metadata) { options._user_data = std::move(metadata); return *this; } /** * @brief move chunked_orc_writer_options member once it's built. */ operator chunked_orc_writer_options&&() { return std::move(options); } /** * @brief move chunked_orc_writer_options member once it's built. * * This has been added since Cython does not support overloading of conversion operators. */ chunked_orc_writer_options&& build() { return std::move(options); } }; /** * @brief Chunked orc writer class writes an ORC file in a chunked/stream form. * * The intent of the write_orc_chunked_ path is to allow writing of an * arbitrarily large / arbitrary number of rows to an ORC file in multiple passes. * * The following code snippet demonstrates how to write a single ORC file containing * one logical table by writing a series of individual cudf::tables. * @code * ... * std::string filepath = "dataset.orc"; * cudf::io::chunked_orc_writer_options options = cudf::io::chunked_orc_writer_options * options::builder(cudf::sink_info(filepath)); * ... * orc_chunked_writer writer(options) * writer.write(table0) * writer.write(table1) * ... * writer.close(); * @endcode */ class orc_chunked_writer { public: /** * @brief Default constructor, this should never be used. * This is added just to satisfy cython. */ orc_chunked_writer() = default; /** * @brief Constructor with chunked writer options * * @param[in] options options used to write table * @param[in] mr Device memory resource to use for device memory allocation */ orc_chunked_writer(chunked_orc_writer_options const& options, rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource()); /** * @brief Writes table to output. * * @param[in] table Table that needs to be written * @return returns reference of the class object */ orc_chunked_writer& write(table_view const& table); /** * @brief Finishes the chunked/streamed write process. */ void close(); // Unique pointer to impl writer class std::unique_ptr<cudf::io::detail::orc::writer> writer; }; /** @} */ // end of group } // namespace io } // namespace cudf
[ "noreply@github.com" ]
noreply@github.com
3f39f5ef1d07d78f22827d1909726511e7bf1014
30ec2372ac36d40f4557c5f39cb606452e6e6bf5
/StarVMC/geant3/geant321/s_mat.inc
51244114388bccec7d6f2eec1f0806d927af7c77
[]
no_license
yfisyak/star-sw
fe77d1f6f246bfa200a0781a0335ede7e3f0ce77
449bba9cba3305baacbd7f18f7b3a51c61b81e61
refs/heads/main
2023-07-12T01:15:45.728968
2021-08-04T22:59:16
2021-08-04T22:59:16
382,115,093
2
0
null
2021-07-01T17:54:02
2021-07-01T17:54:01
null
UTF-8
C++
false
false
806
inc
* * $Id: s_mat.inc,v 1.1.1.3 2009/02/18 20:33:07 fisyak Exp $ * * $Log: s_mat.inc,v $ * Revision 1.1.1.3 2009/02/18 20:33:07 fisyak * *** empty log message *** * * Revision 1.1.1.1 2002/06/16 15:18:38 hristov * Separate distribution of Geant3 * * Revision 1.1.1.1 1999/05/18 15:55:17 fca * AliRoot sources * * Revision 1.1.1.1 1995/10/24 10:20:44 cernlib * Geant * * #ifndef CERNLIB_GEANT321_S_MAT_INC #define CERNLIB_GEANT321_S_MAT_INC * * * s_mat.inc * COMMON/MAT / LMAT, * DEN(21),RADLTH(21),ATNO(21),ZNO(21),ABSL(21), * CDEN(21),MDEN(21),X0DEN(21),X1DEN(21),RION(21), * MATID(21),MATID1(21,24),PARMAT(21,10), * IFRAT,IFRAC(21),FRAC1(21,10),DEN1(21,10), * ATNO1(21,10),ZNO1(21,10) C #endif
[ "fisyak@rcas6005.rcf.bnl.gov" ]
fisyak@rcas6005.rcf.bnl.gov
91a11346d2d744311f51b7cb71f012f2bf800d33
e2b259476b2c47a701d87f16f2271ef760e02d5f
/include/tweedledee/qasm/qasm.hpp
f057fb46f9b2bf3ce3503c1040d09ba3506d5725
[ "MIT" ]
permissive
meamy/tweedledee
d0da06ca6f3158ee4440d3e67b80cd6c38616761
8eeea0534f5a5e7a8d9332c9c1380603d95e337d
refs/heads/master
2020-05-23T16:01:36.134853
2019-05-29T19:53:56
2019-05-29T19:53:56
186,840,339
0
0
MIT
2019-05-15T14:11:28
2019-05-15T14:11:27
null
UTF-8
C++
false
false
1,302
hpp
/*------------------------------------------------------------------------------------------------- | This file is distributed under the MIT License. | See accompanying file /LICENSE for details. | Author(s): Bruno Schmitt *------------------------------------------------------------------------------------------------*/ #include "../base/source_manager.hpp" #include "../base/diagnostic.hpp" #include "ast/ast.hpp" #include "parser.hpp" #include "preprocessor.hpp" #include "token.hpp" #include "token_kinds.hpp" #include <string> #include <memory> namespace tweedledee::qasm { inline std::unique_ptr<ast_context> read_from_file(std::string const& path) { source_manager source_manager; error_diagnostic_engine diagnostic; preprocessor pp_lexer(source_manager, diagnostic); parser parser(pp_lexer, source_manager, diagnostic); pp_lexer.add_target_file(path); auto success = parser.parse(); return success; } inline std::unique_ptr<ast_context> read_from_buffer(std::string const& buffer) { source_manager source_manager; error_diagnostic_engine diagnostic; preprocessor pp_lexer(source_manager, diagnostic); parser parser(pp_lexer, source_manager, diagnostic); pp_lexer.add_target_buffer(buffer); auto success = parser.parse(); return success; } } // namespace tweedledee::qasm
[ "matt.e.amy@gmail.com" ]
matt.e.amy@gmail.com
3f6261e1b85ef3ee29937f2eba7c133c42e15d9a
2c4a5c6037ecc40d04c89d55c867c347042f1f4e
/Wet4/tests/test158.cpp
3105b6cdcf834edac9973ab75483d9157f26ecb4
[]
no_license
kariander1/OperatingSystems
056d684833286e49ef375e2ed0a0b00f482064ef
4671a3cc6746e02e6938c9eb229b3e7016f06c69
refs/heads/master
2023-08-11T04:01:39.533946
2021-10-09T10:17:06
2021-10-09T10:17:06
358,538,381
0
0
null
null
null
null
UTF-8
C++
false
false
45,228
cpp
#include "aux_macro.h" #include "../malloc_3.cpp" #include <iostream> void printStats() { std::cout << "_num_free_blocks: " << _num_free_blocks() << std::endl; std::cout << "_num_free_bytes: " << _num_free_bytes() << std::endl; std::cout << "_num_allocated_blocks: " << _num_allocated_blocks() << std::endl; std::cout << "_num_allocated_bytes: " << _num_allocated_bytes() << std::endl; std::cout << "_num_meta_data_bytes: " << _num_meta_data_bytes() << std::endl; std::cout << "_size_meta_data: " << _size_meta_data() << std::endl; } int main() { PRINT_POINTER(scalloc(123,111);); printStats(); void* p0 = last_address; PRINT_POINTER(srealloc(p0,1);); printStats(); void* p1 = last_address; PRINT_POINTER(smalloc(144);); printStats(); void* p2 = last_address; PRINT_POINTER(srealloc(p2,120);); printStats(); void* p3 = last_address; DEBUG_PRINT(sfree(p1);); printStats(); PRINT_POINTER(srealloc(p3,127);); printStats(); void* p4 = last_address; PRINT_POINTER(srealloc(p4,246);); printStats(); void* p5 = last_address; DEBUG_PRINT(sfree(p5);); printStats(); PRINT_POINTER(scalloc(85,10);); printStats(); void* p6 = last_address; PRINT_POINTER(scalloc(48,87);); printStats(); void* p7 = last_address; PRINT_POINTER(smalloc(116);); printStats(); void* p8 = last_address; PRINT_POINTER(scalloc(18,163);); printStats(); void* p9 = last_address; PRINT_POINTER(smalloc(24);); printStats(); void* p10 = last_address; PRINT_POINTER(scalloc(146,146);); printStats(); void* p11 = last_address; DEBUG_PRINT(sfree(p9);); printStats(); PRINT_POINTER(smalloc(198);); printStats(); void* p12 = last_address; PRINT_POINTER(srealloc(p8,29);); printStats(); void* p13 = last_address; PRINT_POINTER(smalloc(4);); printStats(); void* p14 = last_address; DEBUG_PRINT(sfree(p10);); printStats(); PRINT_POINTER(scalloc(108,108);); printStats(); void* p15 = last_address; PRINT_POINTER(smalloc(34);); printStats(); void* p16 = last_address; DEBUG_PRINT(sfree(p14);); printStats(); PRINT_POINTER(smalloc(38);); printStats(); void* p17 = last_address; PRINT_POINTER(scalloc(77,84);); printStats(); void* p18 = last_address; PRINT_POINTER(srealloc(p7,28);); printStats(); void* p19 = last_address; PRINT_POINTER(smalloc(121);); printStats(); void* p20 = last_address; DEBUG_PRINT(sfree(p17);); printStats(); PRINT_POINTER(scalloc(14,28);); printStats(); void* p21 = last_address; DEBUG_PRINT(sfree(p20);); printStats(); DEBUG_PRINT(sfree(p19);); printStats(); PRINT_POINTER(smalloc(204);); printStats(); void* p22 = last_address; PRINT_POINTER(smalloc(56);); printStats(); void* p23 = last_address; DEBUG_PRINT(sfree(p15);); printStats(); PRINT_POINTER(scalloc(243,152);); printStats(); void* p24 = last_address; PRINT_POINTER(smalloc(9);); printStats(); void* p25 = last_address; DEBUG_PRINT(sfree(p18);); printStats(); PRINT_POINTER(scalloc(89,104);); printStats(); void* p26 = last_address; PRINT_POINTER(scalloc(45,112);); printStats(); void* p27 = last_address; PRINT_POINTER(smalloc(115);); printStats(); void* p28 = last_address; PRINT_POINTER(srealloc(p24,67);); printStats(); void* p29 = last_address; PRINT_POINTER(srealloc(p13,86);); printStats(); void* p30 = last_address; PRINT_POINTER(scalloc(80,83);); printStats(); void* p31 = last_address; PRINT_POINTER(srealloc(p26,90);); printStats(); void* p32 = last_address; PRINT_POINTER(scalloc(170,231);); printStats(); void* p33 = last_address; DEBUG_PRINT(sfree(p32);); printStats(); PRINT_POINTER(scalloc(226,231);); printStats(); void* p34 = last_address; PRINT_POINTER(srealloc(p25,20);); printStats(); void* p35 = last_address; PRINT_POINTER(smalloc(147);); printStats(); void* p36 = last_address; PRINT_POINTER(scalloc(83,7);); printStats(); void* p37 = last_address; PRINT_POINTER(srealloc(p31,185);); printStats(); void* p38 = last_address; PRINT_POINTER(scalloc(163,101);); printStats(); void* p39 = last_address; PRINT_POINTER(srealloc(p16,233);); printStats(); void* p40 = last_address; PRINT_POINTER(srealloc(p33,14);); printStats(); void* p41 = last_address; PRINT_POINTER(smalloc(163);); printStats(); void* p42 = last_address; PRINT_POINTER(scalloc(130,110);); printStats(); void* p43 = last_address; PRINT_POINTER(srealloc(p22,164);); printStats(); void* p44 = last_address; PRINT_POINTER(scalloc(136,125);); printStats(); void* p45 = last_address; PRINT_POINTER(srealloc(p36,59);); printStats(); void* p46 = last_address; DEBUG_PRINT(sfree(p21);); printStats(); PRINT_POINTER(srealloc(p27,9);); printStats(); void* p47 = last_address; DEBUG_PRINT(sfree(p6);); printStats(); PRINT_POINTER(scalloc(170,162);); printStats(); void* p48 = last_address; DEBUG_PRINT(sfree(p29);); printStats(); PRINT_POINTER(srealloc(p46,36);); printStats(); void* p49 = last_address; PRINT_POINTER(srealloc(p48,83);); printStats(); void* p50 = last_address; DEBUG_PRINT(sfree(p47);); printStats(); DEBUG_PRINT(sfree(p11);); printStats(); PRINT_POINTER(smalloc(140);); printStats(); void* p51 = last_address; PRINT_POINTER(srealloc(p23,15);); printStats(); void* p52 = last_address; PRINT_POINTER(srealloc(p42,23);); printStats(); void* p53 = last_address; PRINT_POINTER(smalloc(11);); printStats(); void* p54 = last_address; DEBUG_PRINT(sfree(p39);); printStats(); PRINT_POINTER(srealloc(p38,157);); printStats(); void* p55 = last_address; PRINT_POINTER(srealloc(p45,152);); printStats(); void* p56 = last_address; PRINT_POINTER(smalloc(161);); printStats(); void* p57 = last_address; DEBUG_PRINT(sfree(p50);); printStats(); DEBUG_PRINT(sfree(p35);); printStats(); DEBUG_PRINT(sfree(p41);); printStats(); PRINT_POINTER(srealloc(p53,151);); printStats(); void* p58 = last_address; PRINT_POINTER(smalloc(202);); printStats(); void* p59 = last_address; PRINT_POINTER(srealloc(p40,187);); printStats(); void* p60 = last_address; DEBUG_PRINT(sfree(p60);); printStats(); PRINT_POINTER(srealloc(p59,233);); printStats(); void* p61 = last_address; PRINT_POINTER(scalloc(192,147);); printStats(); void* p62 = last_address; PRINT_POINTER(scalloc(180,91);); printStats(); void* p63 = last_address; PRINT_POINTER(scalloc(59,190);); printStats(); void* p64 = last_address; PRINT_POINTER(smalloc(54);); printStats(); void* p65 = last_address; DEBUG_PRINT(sfree(p43);); printStats(); DEBUG_PRINT(sfree(p44);); printStats(); PRINT_POINTER(smalloc(153);); printStats(); void* p66 = last_address; DEBUG_PRINT(sfree(p52);); printStats(); PRINT_POINTER(smalloc(170);); printStats(); void* p67 = last_address; PRINT_POINTER(smalloc(226);); printStats(); void* p68 = last_address; PRINT_POINTER(scalloc(2,59);); printStats(); void* p69 = last_address; PRINT_POINTER(smalloc(22);); printStats(); void* p70 = last_address; DEBUG_PRINT(sfree(p57);); printStats(); PRINT_POINTER(srealloc(p30,143);); printStats(); void* p71 = last_address; PRINT_POINTER(srealloc(p66,218);); printStats(); void* p72 = last_address; PRINT_POINTER(scalloc(38,8);); printStats(); void* p73 = last_address; DEBUG_PRINT(sfree(p62);); printStats(); PRINT_POINTER(smalloc(186);); printStats(); void* p74 = last_address; PRINT_POINTER(srealloc(p56,99);); printStats(); void* p75 = last_address; PRINT_POINTER(srealloc(p73,13);); printStats(); void* p76 = last_address; PRINT_POINTER(srealloc(p54,45);); printStats(); void* p77 = last_address; PRINT_POINTER(smalloc(188);); printStats(); void* p78 = last_address; PRINT_POINTER(scalloc(39,215);); printStats(); void* p79 = last_address; PRINT_POINTER(smalloc(115);); printStats(); void* p80 = last_address; PRINT_POINTER(scalloc(53,50);); printStats(); void* p81 = last_address; PRINT_POINTER(scalloc(72,116);); printStats(); void* p82 = last_address; PRINT_POINTER(smalloc(49);); printStats(); void* p83 = last_address; PRINT_POINTER(srealloc(p34,99);); printStats(); void* p84 = last_address; PRINT_POINTER(srealloc(p68,194);); printStats(); void* p85 = last_address; PRINT_POINTER(srealloc(p77,134);); printStats(); void* p86 = last_address; PRINT_POINTER(scalloc(81,26);); printStats(); void* p87 = last_address; PRINT_POINTER(srealloc(p79,64);); printStats(); void* p88 = last_address; PRINT_POINTER(smalloc(45);); printStats(); void* p89 = last_address; PRINT_POINTER(smalloc(115);); printStats(); void* p90 = last_address; DEBUG_PRINT(sfree(p85);); printStats(); PRINT_POINTER(scalloc(140,2);); printStats(); void* p91 = last_address; PRINT_POINTER(scalloc(173,137);); printStats(); void* p92 = last_address; PRINT_POINTER(srealloc(p65,195);); printStats(); void* p93 = last_address; PRINT_POINTER(scalloc(28,72);); printStats(); void* p94 = last_address; PRINT_POINTER(smalloc(234);); printStats(); void* p95 = last_address; DEBUG_PRINT(sfree(p83);); printStats(); PRINT_POINTER(smalloc(209);); printStats(); void* p96 = last_address; PRINT_POINTER(scalloc(174,15);); printStats(); void* p97 = last_address; PRINT_POINTER(srealloc(p88,134);); printStats(); void* p98 = last_address; DEBUG_PRINT(sfree(p93);); printStats(); DEBUG_PRINT(sfree(p97);); printStats(); PRINT_POINTER(smalloc(44);); printStats(); void* p99 = last_address; PRINT_POINTER(smalloc(1);); printStats(); void* p100 = last_address; PRINT_POINTER(smalloc(94);); printStats(); void* p101 = last_address; PRINT_POINTER(smalloc(130);); printStats(); void* p102 = last_address; PRINT_POINTER(scalloc(98,191);); printStats(); void* p103 = last_address; PRINT_POINTER(smalloc(215);); printStats(); void* p104 = last_address; PRINT_POINTER(scalloc(189,242);); printStats(); void* p105 = last_address; PRINT_POINTER(smalloc(203);); printStats(); void* p106 = last_address; PRINT_POINTER(scalloc(190,111);); printStats(); void* p107 = last_address; PRINT_POINTER(scalloc(41,83);); printStats(); void* p108 = last_address; PRINT_POINTER(smalloc(52);); printStats(); void* p109 = last_address; DEBUG_PRINT(sfree(p95);); printStats(); DEBUG_PRINT(sfree(p81);); printStats(); PRINT_POINTER(scalloc(210,191);); printStats(); void* p110 = last_address; PRINT_POINTER(srealloc(p58,150);); printStats(); void* p111 = last_address; PRINT_POINTER(scalloc(27,26);); printStats(); void* p112 = last_address; DEBUG_PRINT(sfree(p102);); printStats(); PRINT_POINTER(scalloc(68,155);); printStats(); void* p113 = last_address; PRINT_POINTER(smalloc(43);); printStats(); void* p114 = last_address; DEBUG_PRINT(sfree(p100);); printStats(); DEBUG_PRINT(sfree(p104);); printStats(); PRINT_POINTER(scalloc(44,108);); printStats(); void* p115 = last_address; PRINT_POINTER(smalloc(128);); printStats(); void* p116 = last_address; DEBUG_PRINT(sfree(p12);); printStats(); DEBUG_PRINT(sfree(p114);); printStats(); DEBUG_PRINT(sfree(p94);); printStats(); PRINT_POINTER(scalloc(173,228);); printStats(); void* p117 = last_address; PRINT_POINTER(smalloc(230);); printStats(); void* p118 = last_address; PRINT_POINTER(scalloc(42,49);); printStats(); void* p119 = last_address; PRINT_POINTER(smalloc(158);); printStats(); void* p120 = last_address; PRINT_POINTER(smalloc(177);); printStats(); void* p121 = last_address; PRINT_POINTER(srealloc(p28,38);); printStats(); void* p122 = last_address; PRINT_POINTER(smalloc(136);); printStats(); void* p123 = last_address; PRINT_POINTER(scalloc(220,93);); printStats(); void* p124 = last_address; PRINT_POINTER(smalloc(185);); printStats(); void* p125 = last_address; PRINT_POINTER(smalloc(36);); printStats(); void* p126 = last_address; PRINT_POINTER(smalloc(102);); printStats(); void* p127 = last_address; PRINT_POINTER(srealloc(p70,91);); printStats(); void* p128 = last_address; PRINT_POINTER(srealloc(p103,41);); printStats(); void* p129 = last_address; PRINT_POINTER(smalloc(49);); printStats(); void* p130 = last_address; PRINT_POINTER(scalloc(148,89);); printStats(); void* p131 = last_address; PRINT_POINTER(srealloc(p69,178);); printStats(); void* p132 = last_address; PRINT_POINTER(srealloc(p105,201);); printStats(); void* p133 = last_address; PRINT_POINTER(smalloc(55);); printStats(); void* p134 = last_address; PRINT_POINTER(scalloc(208,3);); printStats(); void* p135 = last_address; PRINT_POINTER(scalloc(174,116);); printStats(); void* p136 = last_address; PRINT_POINTER(srealloc(p55,149);); printStats(); void* p137 = last_address; PRINT_POINTER(srealloc(p122,158);); printStats(); void* p138 = last_address; DEBUG_PRINT(sfree(p138);); printStats(); PRINT_POINTER(srealloc(p120,247);); printStats(); void* p139 = last_address; DEBUG_PRINT(sfree(p111);); printStats(); PRINT_POINTER(smalloc(234);); printStats(); void* p140 = last_address; PRINT_POINTER(srealloc(p96,181);); printStats(); void* p141 = last_address; PRINT_POINTER(srealloc(p126,7);); printStats(); void* p142 = last_address; PRINT_POINTER(smalloc(41);); printStats(); void* p143 = last_address; PRINT_POINTER(srealloc(p113,233);); printStats(); void* p144 = last_address; DEBUG_PRINT(sfree(p140);); printStats(); PRINT_POINTER(srealloc(p116,184);); printStats(); void* p145 = last_address; DEBUG_PRINT(sfree(p124);); printStats(); PRINT_POINTER(smalloc(8);); printStats(); void* p146 = last_address; PRINT_POINTER(smalloc(133);); printStats(); void* p147 = last_address; PRINT_POINTER(srealloc(p115,239);); printStats(); void* p148 = last_address; PRINT_POINTER(srealloc(p110,158);); printStats(); void* p149 = last_address; PRINT_POINTER(smalloc(168);); printStats(); void* p150 = last_address; PRINT_POINTER(srealloc(p82,13);); printStats(); void* p151 = last_address; PRINT_POINTER(scalloc(221,108);); printStats(); void* p152 = last_address; PRINT_POINTER(scalloc(199,238);); printStats(); void* p153 = last_address; PRINT_POINTER(scalloc(101,223);); printStats(); void* p154 = last_address; DEBUG_PRINT(sfree(p49);); printStats(); DEBUG_PRINT(sfree(p135);); printStats(); DEBUG_PRINT(sfree(p98);); printStats(); DEBUG_PRINT(sfree(p153);); printStats(); PRINT_POINTER(smalloc(40);); printStats(); void* p155 = last_address; PRINT_POINTER(scalloc(11,209);); printStats(); void* p156 = last_address; PRINT_POINTER(smalloc(193);); printStats(); void* p157 = last_address; PRINT_POINTER(smalloc(150);); printStats(); void* p158 = last_address; PRINT_POINTER(smalloc(127);); printStats(); void* p159 = last_address; PRINT_POINTER(scalloc(40,8);); printStats(); void* p160 = last_address; DEBUG_PRINT(sfree(p139);); printStats(); DEBUG_PRINT(sfree(p133);); printStats(); DEBUG_PRINT(sfree(p74);); printStats(); PRINT_POINTER(scalloc(4,178);); printStats(); void* p161 = last_address; PRINT_POINTER(srealloc(p134,52);); printStats(); void* p162 = last_address; PRINT_POINTER(srealloc(p131,187);); printStats(); void* p163 = last_address; PRINT_POINTER(scalloc(186,41);); printStats(); void* p164 = last_address; PRINT_POINTER(srealloc(p51,125);); printStats(); void* p165 = last_address; PRINT_POINTER(srealloc(p154,2);); printStats(); void* p166 = last_address; PRINT_POINTER(scalloc(209,165);); printStats(); void* p167 = last_address; PRINT_POINTER(smalloc(49);); printStats(); void* p168 = last_address; DEBUG_PRINT(sfree(p164);); printStats(); DEBUG_PRINT(sfree(p149);); printStats(); DEBUG_PRINT(sfree(p78);); printStats(); PRINT_POINTER(smalloc(208);); printStats(); void* p169 = last_address; PRINT_POINTER(smalloc(150);); printStats(); void* p170 = last_address; DEBUG_PRINT(sfree(p130);); printStats(); PRINT_POINTER(smalloc(112);); printStats(); void* p171 = last_address; PRINT_POINTER(srealloc(p119,156);); printStats(); void* p172 = last_address; PRINT_POINTER(scalloc(42,107);); printStats(); void* p173 = last_address; PRINT_POINTER(scalloc(102,85);); printStats(); void* p174 = last_address; DEBUG_PRINT(sfree(p76);); printStats(); PRINT_POINTER(srealloc(p112,220);); printStats(); void* p175 = last_address; DEBUG_PRINT(sfree(p89);); printStats(); DEBUG_PRINT(sfree(p136);); printStats(); PRINT_POINTER(scalloc(204,228);); printStats(); void* p176 = last_address; DEBUG_PRINT(sfree(p156);); printStats(); PRINT_POINTER(scalloc(196,112);); printStats(); void* p177 = last_address; PRINT_POINTER(srealloc(p127,134);); printStats(); void* p178 = last_address; PRINT_POINTER(srealloc(p172,126);); printStats(); void* p179 = last_address; PRINT_POINTER(scalloc(15,15);); printStats(); void* p180 = last_address; PRINT_POINTER(srealloc(p168,109);); printStats(); void* p181 = last_address; PRINT_POINTER(scalloc(169,212);); printStats(); void* p182 = last_address; PRINT_POINTER(scalloc(146,37);); printStats(); void* p183 = last_address; PRINT_POINTER(srealloc(p117,199);); printStats(); void* p184 = last_address; PRINT_POINTER(smalloc(242);); printStats(); void* p185 = last_address; PRINT_POINTER(smalloc(171);); printStats(); void* p186 = last_address; PRINT_POINTER(scalloc(46,84);); printStats(); void* p187 = last_address; PRINT_POINTER(srealloc(p187,180);); printStats(); void* p188 = last_address; PRINT_POINTER(smalloc(154);); printStats(); void* p189 = last_address; PRINT_POINTER(srealloc(p174,233);); printStats(); void* p190 = last_address; DEBUG_PRINT(sfree(p173);); printStats(); DEBUG_PRINT(sfree(p159);); printStats(); PRINT_POINTER(smalloc(73);); printStats(); void* p191 = last_address; DEBUG_PRINT(sfree(p107);); printStats(); PRINT_POINTER(scalloc(119,247);); printStats(); void* p192 = last_address; PRINT_POINTER(srealloc(p191,129);); printStats(); void* p193 = last_address; PRINT_POINTER(smalloc(136);); printStats(); void* p194 = last_address; DEBUG_PRINT(sfree(p145);); printStats(); PRINT_POINTER(srealloc(p141,111);); printStats(); void* p195 = last_address; PRINT_POINTER(srealloc(p185,146);); printStats(); void* p196 = last_address; PRINT_POINTER(scalloc(2,131);); printStats(); void* p197 = last_address; PRINT_POINTER(smalloc(217);); printStats(); void* p198 = last_address; PRINT_POINTER(srealloc(p183,193);); printStats(); void* p199 = last_address; DEBUG_PRINT(sfree(p193);); printStats(); PRINT_POINTER(srealloc(p181,67);); printStats(); void* p200 = last_address; DEBUG_PRINT(sfree(p84);); printStats(); PRINT_POINTER(srealloc(p142,174);); printStats(); void* p201 = last_address; PRINT_POINTER(srealloc(p99,81);); printStats(); void* p202 = last_address; PRINT_POINTER(srealloc(p137,4);); printStats(); void* p203 = last_address; DEBUG_PRINT(sfree(p91);); printStats(); PRINT_POINTER(scalloc(38,16);); printStats(); void* p204 = last_address; PRINT_POINTER(scalloc(121,86);); printStats(); void* p205 = last_address; DEBUG_PRINT(sfree(p125);); printStats(); PRINT_POINTER(scalloc(44,191);); printStats(); void* p206 = last_address; PRINT_POINTER(srealloc(p150,175);); printStats(); void* p207 = last_address; PRINT_POINTER(srealloc(p108,191);); printStats(); void* p208 = last_address; PRINT_POINTER(smalloc(248);); printStats(); void* p209 = last_address; PRINT_POINTER(scalloc(69,226);); printStats(); void* p210 = last_address; PRINT_POINTER(scalloc(37,3);); printStats(); void* p211 = last_address; DEBUG_PRINT(sfree(p203);); printStats(); PRINT_POINTER(srealloc(p123,199);); printStats(); void* p212 = last_address; PRINT_POINTER(srealloc(p166,65);); printStats(); void* p213 = last_address; PRINT_POINTER(srealloc(p155,166);); printStats(); void* p214 = last_address; PRINT_POINTER(srealloc(p170,107);); printStats(); void* p215 = last_address; PRINT_POINTER(smalloc(225);); printStats(); void* p216 = last_address; DEBUG_PRINT(sfree(p189);); printStats(); DEBUG_PRINT(sfree(p197);); printStats(); PRINT_POINTER(srealloc(p132,235);); printStats(); void* p217 = last_address; PRINT_POINTER(srealloc(p75,189);); printStats(); void* p218 = last_address; PRINT_POINTER(scalloc(6,110);); printStats(); void* p219 = last_address; DEBUG_PRINT(sfree(p157);); printStats(); DEBUG_PRINT(sfree(p214);); printStats(); PRINT_POINTER(scalloc(183,115);); printStats(); void* p220 = last_address; PRINT_POINTER(smalloc(9);); printStats(); void* p221 = last_address; PRINT_POINTER(srealloc(p178,64);); printStats(); void* p222 = last_address; PRINT_POINTER(scalloc(176,76);); printStats(); void* p223 = last_address; DEBUG_PRINT(sfree(p177);); printStats(); PRINT_POINTER(smalloc(156);); printStats(); void* p224 = last_address; DEBUG_PRINT(sfree(p171);); printStats(); PRINT_POINTER(scalloc(60,92);); printStats(); void* p225 = last_address; PRINT_POINTER(scalloc(90,114);); printStats(); void* p226 = last_address; DEBUG_PRINT(sfree(p86);); printStats(); PRINT_POINTER(smalloc(10);); printStats(); void* p227 = last_address; PRINT_POINTER(scalloc(120,205);); printStats(); void* p228 = last_address; DEBUG_PRINT(sfree(p63);); printStats(); DEBUG_PRINT(sfree(p212);); printStats(); PRINT_POINTER(smalloc(173);); printStats(); void* p229 = last_address; PRINT_POINTER(srealloc(p202,234);); printStats(); void* p230 = last_address; PRINT_POINTER(smalloc(105);); printStats(); void* p231 = last_address; PRINT_POINTER(scalloc(42,146);); printStats(); void* p232 = last_address; PRINT_POINTER(srealloc(p194,149);); printStats(); void* p233 = last_address; PRINT_POINTER(srealloc(p207,52);); printStats(); void* p234 = last_address; DEBUG_PRINT(sfree(p199);); printStats(); PRINT_POINTER(smalloc(114);); printStats(); void* p235 = last_address; PRINT_POINTER(srealloc(p235,69);); printStats(); void* p236 = last_address; PRINT_POINTER(srealloc(p92,222);); printStats(); void* p237 = last_address; PRINT_POINTER(scalloc(50,194);); printStats(); void* p238 = last_address; PRINT_POINTER(srealloc(p230,68);); printStats(); void* p239 = last_address; PRINT_POINTER(smalloc(180);); printStats(); void* p240 = last_address; PRINT_POINTER(smalloc(233);); printStats(); void* p241 = last_address; PRINT_POINTER(smalloc(201);); printStats(); void* p242 = last_address; PRINT_POINTER(scalloc(21,237);); printStats(); void* p243 = last_address; DEBUG_PRINT(sfree(p129);); printStats(); DEBUG_PRINT(sfree(p161);); printStats(); PRINT_POINTER(srealloc(p201,132);); printStats(); void* p244 = last_address; PRINT_POINTER(srealloc(p152,212);); printStats(); void* p245 = last_address; PRINT_POINTER(smalloc(226);); printStats(); void* p246 = last_address; PRINT_POINTER(scalloc(70,44);); printStats(); void* p247 = last_address; PRINT_POINTER(scalloc(48,136);); printStats(); void* p248 = last_address; PRINT_POINTER(smalloc(172);); printStats(); void* p249 = last_address; PRINT_POINTER(smalloc(175);); printStats(); void* p250 = last_address; PRINT_POINTER(srealloc(p221,89);); printStats(); void* p251 = last_address; PRINT_POINTER(scalloc(219,109);); printStats(); void* p252 = last_address; PRINT_POINTER(srealloc(p101,41);); printStats(); void* p253 = last_address; PRINT_POINTER(smalloc(10);); printStats(); void* p254 = last_address; PRINT_POINTER(srealloc(p215,200);); printStats(); void* p255 = last_address; PRINT_POINTER(scalloc(53,141);); printStats(); void* p256 = last_address; PRINT_POINTER(scalloc(234,137);); printStats(); void* p257 = last_address; PRINT_POINTER(srealloc(p241,176);); printStats(); void* p258 = last_address; PRINT_POINTER(scalloc(191,110);); printStats(); void* p259 = last_address; DEBUG_PRINT(sfree(p209);); printStats(); DEBUG_PRINT(sfree(p162);); printStats(); PRINT_POINTER(scalloc(99,182);); printStats(); void* p260 = last_address; PRINT_POINTER(smalloc(171);); printStats(); void* p261 = last_address; PRINT_POINTER(smalloc(237);); printStats(); void* p262 = last_address; PRINT_POINTER(smalloc(167);); printStats(); void* p263 = last_address; PRINT_POINTER(smalloc(225);); printStats(); void* p264 = last_address; PRINT_POINTER(smalloc(170);); printStats(); void* p265 = last_address; DEBUG_PRINT(sfree(p253);); printStats(); DEBUG_PRINT(sfree(p237);); printStats(); PRINT_POINTER(scalloc(3,244);); printStats(); void* p266 = last_address; DEBUG_PRINT(sfree(p236);); printStats(); PRINT_POINTER(srealloc(p231,49);); printStats(); void* p267 = last_address; PRINT_POINTER(srealloc(p265,246);); printStats(); void* p268 = last_address; PRINT_POINTER(srealloc(p200,136);); printStats(); void* p269 = last_address; PRINT_POINTER(smalloc(50);); printStats(); void* p270 = last_address; DEBUG_PRINT(sfree(p262);); printStats(); PRINT_POINTER(srealloc(p247,84);); printStats(); void* p271 = last_address; PRINT_POINTER(smalloc(52);); printStats(); void* p272 = last_address; PRINT_POINTER(scalloc(105,168);); printStats(); void* p273 = last_address; DEBUG_PRINT(sfree(p233);); printStats(); PRINT_POINTER(scalloc(33,184);); printStats(); void* p274 = last_address; PRINT_POINTER(srealloc(p263,183);); printStats(); void* p275 = last_address; PRINT_POINTER(srealloc(p216,232);); printStats(); void* p276 = last_address; PRINT_POINTER(scalloc(152,161);); printStats(); void* p277 = last_address; PRINT_POINTER(smalloc(8);); printStats(); void* p278 = last_address; DEBUG_PRINT(sfree(p160);); printStats(); DEBUG_PRINT(sfree(p218);); printStats(); PRINT_POINTER(smalloc(135);); printStats(); void* p279 = last_address; PRINT_POINTER(srealloc(p276,193);); printStats(); void* p280 = last_address; PRINT_POINTER(smalloc(55);); printStats(); void* p281 = last_address; PRINT_POINTER(smalloc(91);); printStats(); void* p282 = last_address; PRINT_POINTER(scalloc(201,177);); printStats(); void* p283 = last_address; PRINT_POINTER(srealloc(p64,224);); printStats(); void* p284 = last_address; PRINT_POINTER(smalloc(214);); printStats(); void* p285 = last_address; PRINT_POINTER(srealloc(p167,120);); printStats(); void* p286 = last_address; DEBUG_PRINT(sfree(p252);); printStats(); PRINT_POINTER(smalloc(184);); printStats(); void* p287 = last_address; PRINT_POINTER(scalloc(157,76);); printStats(); void* p288 = last_address; DEBUG_PRINT(sfree(p256);); printStats(); PRINT_POINTER(scalloc(30,246);); printStats(); void* p289 = last_address; PRINT_POINTER(scalloc(231,109);); printStats(); void* p290 = last_address; PRINT_POINTER(scalloc(245,94);); printStats(); void* p291 = last_address; PRINT_POINTER(scalloc(171,71);); printStats(); void* p292 = last_address; DEBUG_PRINT(sfree(p205);); printStats(); PRINT_POINTER(scalloc(173,55);); printStats(); void* p293 = last_address; PRINT_POINTER(srealloc(p243,186);); printStats(); void* p294 = last_address; PRINT_POINTER(smalloc(44);); printStats(); void* p295 = last_address; PRINT_POINTER(scalloc(247,119);); printStats(); void* p296 = last_address; PRINT_POINTER(srealloc(p238,128);); printStats(); void* p297 = last_address; DEBUG_PRINT(sfree(p261);); printStats(); PRINT_POINTER(smalloc(186);); printStats(); void* p298 = last_address; PRINT_POINTER(smalloc(95);); printStats(); void* p299 = last_address; PRINT_POINTER(smalloc(35);); printStats(); void* p300 = last_address; DEBUG_PRINT(sfree(p217);); printStats(); PRINT_POINTER(srealloc(p250,148);); printStats(); void* p301 = last_address; PRINT_POINTER(smalloc(119);); printStats(); void* p302 = last_address; PRINT_POINTER(smalloc(136);); printStats(); void* p303 = last_address; PRINT_POINTER(smalloc(242);); printStats(); void* p304 = last_address; PRINT_POINTER(scalloc(193,10);); printStats(); void* p305 = last_address; PRINT_POINTER(smalloc(227);); printStats(); void* p306 = last_address; PRINT_POINTER(srealloc(p182,167);); printStats(); void* p307 = last_address; PRINT_POINTER(smalloc(170);); printStats(); void* p308 = last_address; DEBUG_PRINT(sfree(p289);); printStats(); PRINT_POINTER(smalloc(224);); printStats(); void* p309 = last_address; DEBUG_PRINT(sfree(p80);); printStats(); PRINT_POINTER(srealloc(p176,234);); printStats(); void* p310 = last_address; PRINT_POINTER(smalloc(101);); printStats(); void* p311 = last_address; PRINT_POINTER(scalloc(28,218);); printStats(); void* p312 = last_address; DEBUG_PRINT(sfree(p118);); printStats(); DEBUG_PRINT(sfree(p158);); printStats(); PRINT_POINTER(smalloc(175);); printStats(); void* p313 = last_address; PRINT_POINTER(smalloc(110);); printStats(); void* p314 = last_address; PRINT_POINTER(scalloc(191,51);); printStats(); void* p315 = last_address; PRINT_POINTER(srealloc(p303,160);); printStats(); void* p316 = last_address; PRINT_POINTER(smalloc(5);); printStats(); void* p317 = last_address; DEBUG_PRINT(sfree(p283);); printStats(); DEBUG_PRINT(sfree(p242);); printStats(); DEBUG_PRINT(sfree(p266);); printStats(); PRINT_POINTER(scalloc(174,200);); printStats(); void* p318 = last_address; DEBUG_PRINT(sfree(p294);); printStats(); DEBUG_PRINT(sfree(p270);); printStats(); PRINT_POINTER(smalloc(140);); printStats(); void* p319 = last_address; PRINT_POINTER(smalloc(165);); printStats(); void* p320 = last_address; PRINT_POINTER(smalloc(57);); printStats(); void* p321 = last_address; DEBUG_PRINT(sfree(p290);); printStats(); PRINT_POINTER(smalloc(164);); printStats(); void* p322 = last_address; PRINT_POINTER(scalloc(110,138);); printStats(); void* p323 = last_address; PRINT_POINTER(srealloc(p234,172);); printStats(); void* p324 = last_address; PRINT_POINTER(smalloc(40);); printStats(); void* p325 = last_address; PRINT_POINTER(smalloc(245);); printStats(); void* p326 = last_address; DEBUG_PRINT(sfree(p121);); printStats(); PRINT_POINTER(srealloc(p225,163);); printStats(); void* p327 = last_address; PRINT_POINTER(smalloc(60);); printStats(); void* p328 = last_address; PRINT_POINTER(srealloc(p210,88);); printStats(); void* p329 = last_address; PRINT_POINTER(smalloc(228);); printStats(); void* p330 = last_address; PRINT_POINTER(scalloc(208,35);); printStats(); void* p331 = last_address; PRINT_POINTER(smalloc(44);); printStats(); void* p332 = last_address; PRINT_POINTER(smalloc(179);); printStats(); void* p333 = last_address; PRINT_POINTER(scalloc(103,71);); printStats(); void* p334 = last_address; DEBUG_PRINT(sfree(p90);); printStats(); PRINT_POINTER(srealloc(p67,67);); printStats(); void* p335 = last_address; PRINT_POINTER(smalloc(4);); printStats(); void* p336 = last_address; PRINT_POINTER(smalloc(186);); printStats(); void* p337 = last_address; DEBUG_PRINT(sfree(p305);); printStats(); DEBUG_PRINT(sfree(p298);); printStats(); PRINT_POINTER(smalloc(216);); printStats(); void* p338 = last_address; PRINT_POINTER(srealloc(p37,29);); printStats(); void* p339 = last_address; DEBUG_PRINT(sfree(p188);); printStats(); PRINT_POINTER(scalloc(185,159);); printStats(); void* p340 = last_address; PRINT_POINTER(srealloc(p190,179);); printStats(); void* p341 = last_address; PRINT_POINTER(scalloc(54,128);); printStats(); void* p342 = last_address; DEBUG_PRINT(sfree(p264);); printStats(); PRINT_POINTER(srealloc(p285,158);); printStats(); void* p343 = last_address; PRINT_POINTER(smalloc(159);); printStats(); void* p344 = last_address; DEBUG_PRINT(sfree(p297);); printStats(); DEBUG_PRINT(sfree(p204);); printStats(); PRINT_POINTER(srealloc(p226,151);); printStats(); void* p345 = last_address; PRINT_POINTER(smalloc(44);); printStats(); void* p346 = last_address; PRINT_POINTER(scalloc(36,22);); printStats(); void* p347 = last_address; PRINT_POINTER(scalloc(128,17);); printStats(); void* p348 = last_address; PRINT_POINTER(srealloc(p267,59);); printStats(); void* p349 = last_address; DEBUG_PRINT(sfree(p179);); printStats(); PRINT_POINTER(scalloc(1,210);); printStats(); void* p350 = last_address; PRINT_POINTER(srealloc(p304,200);); printStats(); void* p351 = last_address; PRINT_POINTER(scalloc(192,95);); printStats(); void* p352 = last_address; PRINT_POINTER(smalloc(105);); printStats(); void* p353 = last_address; PRINT_POINTER(smalloc(213);); printStats(); void* p354 = last_address; PRINT_POINTER(smalloc(203);); printStats(); void* p355 = last_address; PRINT_POINTER(scalloc(85,192);); printStats(); void* p356 = last_address; PRINT_POINTER(srealloc(p192,33);); printStats(); void* p357 = last_address; PRINT_POINTER(scalloc(82,226);); printStats(); void* p358 = last_address; PRINT_POINTER(srealloc(p246,219);); printStats(); void* p359 = last_address; DEBUG_PRINT(sfree(p348);); printStats(); DEBUG_PRINT(sfree(p219);); printStats(); PRINT_POINTER(scalloc(199,15);); printStats(); void* p360 = last_address; PRINT_POINTER(smalloc(210);); printStats(); void* p361 = last_address; DEBUG_PRINT(sfree(p223);); printStats(); PRINT_POINTER(srealloc(p339,198);); printStats(); void* p362 = last_address; DEBUG_PRINT(sfree(p337);); printStats(); PRINT_POINTER(smalloc(211);); printStats(); void* p363 = last_address; PRINT_POINTER(smalloc(59);); printStats(); void* p364 = last_address; PRINT_POINTER(smalloc(175);); printStats(); void* p365 = last_address; PRINT_POINTER(srealloc(p232,163);); printStats(); void* p366 = last_address; PRINT_POINTER(srealloc(p321,1);); printStats(); void* p367 = last_address; DEBUG_PRINT(sfree(p322);); printStats(); DEBUG_PRINT(sfree(p365);); printStats(); PRINT_POINTER(scalloc(230,123);); printStats(); void* p368 = last_address; DEBUG_PRINT(sfree(p300);); printStats(); DEBUG_PRINT(sfree(p148);); printStats(); PRINT_POINTER(scalloc(197,1);); printStats(); void* p369 = last_address; DEBUG_PRINT(sfree(p309);); printStats(); PRINT_POINTER(smalloc(46);); printStats(); void* p370 = last_address; PRINT_POINTER(srealloc(p271,75);); printStats(); void* p371 = last_address; PRINT_POINTER(srealloc(p239,14);); printStats(); void* p372 = last_address; PRINT_POINTER(scalloc(19,191);); printStats(); void* p373 = last_address; PRINT_POINTER(scalloc(51,146);); printStats(); void* p374 = last_address; PRINT_POINTER(srealloc(p323,30);); printStats(); void* p375 = last_address; PRINT_POINTER(smalloc(61);); printStats(); void* p376 = last_address; PRINT_POINTER(smalloc(215);); printStats(); void* p377 = last_address; PRINT_POINTER(smalloc(68);); printStats(); void* p378 = last_address; DEBUG_PRINT(sfree(p255);); printStats(); DEBUG_PRINT(sfree(p249);); printStats(); PRINT_POINTER(smalloc(188);); printStats(); void* p379 = last_address; DEBUG_PRINT(sfree(p291);); printStats(); PRINT_POINTER(smalloc(183);); printStats(); void* p380 = last_address; PRINT_POINTER(smalloc(36);); printStats(); void* p381 = last_address; PRINT_POINTER(scalloc(244,77);); printStats(); void* p382 = last_address; PRINT_POINTER(srealloc(p275,105);); printStats(); void* p383 = last_address; DEBUG_PRINT(sfree(p308);); printStats(); PRINT_POINTER(smalloc(39);); printStats(); void* p384 = last_address; PRINT_POINTER(smalloc(164);); printStats(); void* p385 = last_address; DEBUG_PRINT(sfree(p269);); printStats(); PRINT_POINTER(scalloc(35,183);); printStats(); void* p386 = last_address; DEBUG_PRINT(sfree(p359);); printStats(); PRINT_POINTER(srealloc(p369,227);); printStats(); void* p387 = last_address; DEBUG_PRINT(sfree(p146);); printStats(); PRINT_POINTER(scalloc(85,14);); printStats(); void* p388 = last_address; PRINT_POINTER(scalloc(164,158);); printStats(); void* p389 = last_address; PRINT_POINTER(srealloc(p324,18);); printStats(); void* p390 = last_address; PRINT_POINTER(scalloc(22,164);); printStats(); void* p391 = last_address; DEBUG_PRINT(sfree(p279);); printStats(); DEBUG_PRINT(sfree(p354);); printStats(); DEBUG_PRINT(sfree(p356);); printStats(); PRINT_POINTER(smalloc(187);); printStats(); void* p392 = last_address; PRINT_POINTER(smalloc(78);); printStats(); void* p393 = last_address; PRINT_POINTER(scalloc(217,74);); printStats(); void* p394 = last_address; PRINT_POINTER(srealloc(p350,86);); printStats(); void* p395 = last_address; DEBUG_PRINT(sfree(p296);); printStats(); PRINT_POINTER(scalloc(139,42);); printStats(); void* p396 = last_address; PRINT_POINTER(smalloc(94);); printStats(); void* p397 = last_address; PRINT_POINTER(smalloc(90);); printStats(); void* p398 = last_address; PRINT_POINTER(srealloc(p376,150);); printStats(); void* p399 = last_address; PRINT_POINTER(scalloc(159,145);); printStats(); void* p400 = last_address; PRINT_POINTER(srealloc(p244,199);); printStats(); void* p401 = last_address; PRINT_POINTER(scalloc(95,218);); printStats(); void* p402 = last_address; PRINT_POINTER(smalloc(179);); printStats(); void* p403 = last_address; PRINT_POINTER(smalloc(217);); printStats(); void* p404 = last_address; PRINT_POINTER(smalloc(242);); printStats(); void* p405 = last_address; PRINT_POINTER(smalloc(3);); printStats(); void* p406 = last_address; PRINT_POINTER(smalloc(2);); printStats(); void* p407 = last_address; DEBUG_PRINT(sfree(p396);); printStats(); PRINT_POINTER(scalloc(158,163);); printStats(); void* p408 = last_address; PRINT_POINTER(smalloc(133);); printStats(); void* p409 = last_address; PRINT_POINTER(scalloc(143,243);); printStats(); void* p410 = last_address; DEBUG_PRINT(sfree(p299);); printStats(); PRINT_POINTER(scalloc(230,109);); printStats(); void* p411 = last_address; PRINT_POINTER(scalloc(114,183);); printStats(); void* p412 = last_address; DEBUG_PRINT(sfree(p352);); printStats(); PRINT_POINTER(scalloc(89,81);); printStats(); void* p413 = last_address; PRINT_POINTER(scalloc(218,176);); printStats(); void* p414 = last_address; PRINT_POINTER(smalloc(172);); printStats(); void* p415 = last_address; PRINT_POINTER(smalloc(67);); printStats(); void* p416 = last_address; PRINT_POINTER(scalloc(0,42);); printStats(); void* p417 = last_address; PRINT_POINTER(srealloc(p395,169);); printStats(); void* p418 = last_address; PRINT_POINTER(smalloc(1);); printStats(); void* p419 = last_address; DEBUG_PRINT(sfree(p292);); printStats(); PRINT_POINTER(srealloc(p281,188);); printStats(); void* p420 = last_address; PRINT_POINTER(scalloc(249,168);); printStats(); void* p421 = last_address; PRINT_POINTER(scalloc(48,107);); printStats(); void* p422 = last_address; DEBUG_PRINT(sfree(p334);); printStats(); PRINT_POINTER(scalloc(50,138);); printStats(); void* p423 = last_address; PRINT_POINTER(srealloc(p358,148);); printStats(); void* p424 = last_address; DEBUG_PRINT(sfree(p385);); printStats(); DEBUG_PRINT(sfree(p61);); printStats(); DEBUG_PRINT(sfree(p310);); printStats(); PRINT_POINTER(scalloc(152,217);); printStats(); void* p425 = last_address; PRINT_POINTER(smalloc(214);); printStats(); void* p426 = last_address; PRINT_POINTER(smalloc(189);); printStats(); void* p427 = last_address; PRINT_POINTER(smalloc(113);); printStats(); void* p428 = last_address; DEBUG_PRINT(sfree(p329);); printStats(); DEBUG_PRINT(sfree(p228);); printStats(); PRINT_POINTER(srealloc(p416,118);); printStats(); void* p429 = last_address; PRINT_POINTER(smalloc(101);); printStats(); void* p430 = last_address; DEBUG_PRINT(sfree(p272);); printStats(); PRINT_POINTER(scalloc(189,20);); printStats(); void* p431 = last_address; DEBUG_PRINT(sfree(p367);); printStats(); PRINT_POINTER(smalloc(61);); printStats(); void* p432 = last_address; PRINT_POINTER(smalloc(87);); printStats(); void* p433 = last_address; PRINT_POINTER(smalloc(245);); printStats(); void* p434 = last_address; PRINT_POINTER(scalloc(214,233);); printStats(); void* p435 = last_address; PRINT_POINTER(scalloc(199,32);); printStats(); void* p436 = last_address; PRINT_POINTER(scalloc(110,33);); printStats(); void* p437 = last_address; PRINT_POINTER(srealloc(p394,14);); printStats(); void* p438 = last_address; PRINT_POINTER(scalloc(184,154);); printStats(); void* p439 = last_address; PRINT_POINTER(scalloc(2,168);); printStats(); void* p440 = last_address; PRINT_POINTER(scalloc(140,135);); printStats(); void* p441 = last_address; PRINT_POINTER(smalloc(146);); printStats(); void* p442 = last_address; PRINT_POINTER(smalloc(135);); printStats(); void* p443 = last_address; PRINT_POINTER(srealloc(p165,148);); printStats(); void* p444 = last_address; DEBUG_PRINT(sfree(p413);); printStats(); PRINT_POINTER(srealloc(p393,51);); printStats(); void* p445 = last_address; DEBUG_PRINT(sfree(p198);); printStats(); PRINT_POINTER(smalloc(62);); printStats(); void* p446 = last_address; PRINT_POINTER(smalloc(30);); printStats(); void* p447 = last_address; PRINT_POINTER(scalloc(184,240);); printStats(); void* p448 = last_address; DEBUG_PRINT(sfree(p372);); printStats(); PRINT_POINTER(srealloc(p397,150);); printStats(); void* p449 = last_address; PRINT_POINTER(smalloc(0);); printStats(); void* p450 = last_address; PRINT_POINTER(srealloc(p277,102);); printStats(); void* p451 = last_address; DEBUG_PRINT(sfree(p398);); printStats(); PRINT_POINTER(scalloc(79,67);); printStats(); void* p452 = last_address; DEBUG_PRINT(sfree(p437);); printStats(); PRINT_POINTER(scalloc(14,216);); printStats(); void* p453 = last_address; PRINT_POINTER(srealloc(p312,249);); printStats(); void* p454 = last_address; PRINT_POINTER(smalloc(213);); printStats(); void* p455 = last_address; PRINT_POINTER(srealloc(p383,133);); printStats(); void* p456 = last_address; PRINT_POINTER(smalloc(214);); printStats(); void* p457 = last_address; PRINT_POINTER(srealloc(p87,205);); printStats(); void* p458 = last_address; PRINT_POINTER(srealloc(p259,249);); printStats(); void* p459 = last_address; PRINT_POINTER(srealloc(p432,231);); printStats(); void* p460 = last_address; PRINT_POINTER(smalloc(148);); printStats(); void* p461 = last_address; PRINT_POINTER(smalloc(143);); printStats(); void* p462 = last_address; PRINT_POINTER(scalloc(181,129);); printStats(); void* p463 = last_address; PRINT_POINTER(scalloc(199,202);); printStats(); void* p464 = last_address; PRINT_POINTER(scalloc(60,213);); printStats(); void* p465 = last_address; PRINT_POINTER(scalloc(217,80);); printStats(); void* p466 = last_address; PRINT_POINTER(srealloc(p386,130);); printStats(); void* p467 = last_address; DEBUG_PRINT(sfree(p458);); printStats(); PRINT_POINTER(scalloc(116,164);); printStats(); void* p468 = last_address; PRINT_POINTER(scalloc(213,242);); printStats(); void* p469 = last_address; DEBUG_PRINT(sfree(p444);); printStats(); PRINT_POINTER(smalloc(68);); printStats(); void* p470 = last_address; PRINT_POINTER(scalloc(16,84);); printStats(); void* p471 = last_address; PRINT_POINTER(smalloc(68);); printStats(); void* p472 = last_address; PRINT_POINTER(srealloc(p425,183);); printStats(); void* p473 = last_address; PRINT_POINTER(scalloc(83,68);); printStats(); void* p474 = last_address; DEBUG_PRINT(sfree(p421);); printStats(); PRINT_POINTER(srealloc(p399,175);); printStats(); void* p475 = last_address; PRINT_POINTER(srealloc(p467,64);); printStats(); void* p476 = last_address; PRINT_POINTER(srealloc(p341,0);); printStats(); void* p477 = last_address; DEBUG_PRINT(sfree(p474);); printStats(); PRINT_POINTER(srealloc(p222,105);); printStats(); void* p478 = last_address; PRINT_POINTER(smalloc(102);); printStats(); void* p479 = last_address; DEBUG_PRINT(sfree(p409);); printStats(); PRINT_POINTER(srealloc(p415,133);); printStats(); void* p480 = last_address; PRINT_POINTER(smalloc(44);); printStats(); void* p481 = last_address; PRINT_POINTER(srealloc(p288,148);); printStats(); void* p482 = last_address; DEBUG_PRINT(sfree(p435);); printStats(); DEBUG_PRINT(sfree(p280);); printStats(); PRINT_POINTER(srealloc(p414,153);); printStats(); void* p483 = last_address; PRINT_POINTER(srealloc(p480,190);); printStats(); void* p484 = last_address; PRINT_POINTER(smalloc(61);); printStats(); void* p485 = last_address; DEBUG_PRINT(sfree(p400);); printStats(); PRINT_POINTER(scalloc(217,82);); printStats(); void* p486 = last_address; PRINT_POINTER(smalloc(89);); printStats(); void* p487 = last_address; PRINT_POINTER(scalloc(37,35);); printStats(); void* p488 = last_address; PRINT_POINTER(srealloc(p326,137);); printStats(); void* p489 = last_address; PRINT_POINTER(srealloc(p440,36);); printStats(); void* p490 = last_address; PRINT_POINTER(smalloc(153);); printStats(); void* p491 = last_address; PRINT_POINTER(scalloc(47,120);); printStats(); void* p492 = last_address; PRINT_POINTER(scalloc(124,233);); printStats(); void* p493 = last_address; PRINT_POINTER(srealloc(p451,119);); printStats(); void* p494 = last_address; PRINT_POINTER(scalloc(239,96);); printStats(); void* p495 = last_address; PRINT_POINTER(scalloc(107,63);); printStats(); void* p496 = last_address; PRINT_POINTER(srealloc(p443,231);); printStats(); void* p497 = last_address; PRINT_POINTER(scalloc(166,183);); printStats(); void* p498 = last_address; PRINT_POINTER(smalloc(39);); printStats(); void* p499 = last_address; DEBUG_PRINT(sfree(p363);); printStats(); PRINT_POINTER(srealloc(p278,132);); printStats(); void* p500 = last_address; PRINT_POINTER(srealloc(p468,230);); printStats(); void* p501 = last_address; PRINT_POINTER(scalloc(136,90);); printStats(); void* p502 = last_address; PRINT_POINTER(scalloc(241,191);); printStats(); void* p503 = last_address; PRINT_POINTER(srealloc(p208,122);); printStats(); void* p504 = last_address; PRINT_POINTER(scalloc(135,148);); printStats(); void* p505 = last_address; PRINT_POINTER(smalloc(130);); printStats(); void* p506 = last_address; DEBUG_PRINT(sfree(p442);); printStats(); PRINT_POINTER(smalloc(17);); printStats(); void* p507 = last_address; PRINT_POINTER(smalloc(234);); printStats(); void* p508 = last_address; DEBUG_PRINT(sfree(p487);); printStats(); PRINT_POINTER(srealloc(p486,83);); printStats(); void* p509 = last_address; PRINT_POINTER(smalloc(179);); printStats(); void* p510 = last_address; DEBUG_PRINT(sfree(p485);); printStats(); PRINT_POINTER(srealloc(p109,30);); printStats(); void* p511 = last_address; PRINT_POINTER(srealloc(p353,122);); printStats(); void* p512 = last_address; DEBUG_PRINT(sfree(p195);); printStats(); PRINT_POINTER(smalloc(72);); printStats(); void* p513 = last_address; PRINT_POINTER(srealloc(p286,206);); printStats(); void* p514 = last_address; DEBUG_PRINT(sfree(p344);); printStats(); PRINT_POINTER(smalloc(128);); printStats(); void* p515 = last_address; }
[ "shaiyehezkel@campus.technion.ac.il" ]
shaiyehezkel@campus.technion.ac.il
24796c9f951fa7c463099aefcf563008fc6dc5c3
df968d326125adfd97e4451d646c3847308ea6ad
/cpp_primer_plus/chapter_07/procedure_09/strgfun.cpp
adeb67f3caec43239e83dc417ae361c200a52e89
[]
no_license
buxucixingztx/cpp_learning
f47d9212c0f01673de29ec82e094c44e48d97ad1
2047c75a34cf2240288234ba95a32b28f2838353
refs/heads/master
2023-01-09T10:47:03.225070
2020-11-06T03:29:32
2020-11-06T03:29:32
271,570,711
0
0
null
null
null
null
UTF-8
C++
false
false
617
cpp
// strgfun.cpp -- functions with a string argument #include <iostream> unsigned int c_in_str(const char * str, char ch); int main() { using namespace std; char mmm[15] = "minimum"; char *wail = "ululate"; unsigned int ms = c_in_str(mmm, 'm'); unsigned int us = c_in_str(wail, 'u'); cout << ms << " m characters in " << mmm << endl; cout << us << " u characters in " << wail << endl; return 0; } unsigned int c_in_str(const char * str, char ch){ unsigned int count = 0; while (*str){ if (*str == ch) count++; str++; } return count; }
[ "bxucixing@163.com" ]
bxucixing@163.com
f9a9ce124e709eaf6b248086da03909dc1d629cc
34b17d5c0411d2105ec9ee8b53aa8dcf6a58bbbd
/node_mcu/blink_led/blink_led.ino
1eae81f3ea76035bd7f4b8f6e07e010eb85e34c6
[]
no_license
damiancipolat/arduino101
007989e6388f6d3938c81477e6ef7d8e8dd6691f
41baaf0142898812eaaf2a1517a09b45905ed02c
refs/heads/master
2023-02-26T08:35:21.141236
2021-02-03T08:49:35
2021-02-03T08:49:35
280,681,701
1
1
null
null
null
null
UTF-8
C++
false
false
606
ino
#define LED_BUILTIN 5 void setup() { pinMode(LED_BUILTIN, OUTPUT); // Initialize the LED_BUILTIN pin as an output } // the loop function runs over and over again forever void loop() { digitalWrite(LED_BUILTIN, LOW); // Turn the LED on (Note that LOW is the voltage level // but actually the LED is on; this is because // it is acive low on the ESP-01) delay(1000); // Wait for a second digitalWrite(LED_BUILTIN, HIGH); // Turn the LED off by making the voltage HIGH delay(2000); // Wait for two seconds (to demonstrate the active low LED) }
[ "damian.cipolat@gmail.com" ]
damian.cipolat@gmail.com
0bb8da489a9400049edfa48bf01b4596dd17aea8
0bdd5a3adf6e66ac6631cc63bf0d212f30904e9c
/DesignMode/Singleton/HungrySingleton.cpp
9654b7ddcdff8bf965438defac36c1d9331d0e52
[]
no_license
BigMouseFive/DesignMode
a20a4b2ae4712144b20644620943cee05f83f28c
433e598388e3c78fe987505cdf638ea171f0755d
refs/heads/master
2020-08-31T10:42:20.619056
2019-11-02T02:58:19
2019-11-02T02:58:19
218,671,927
0
1
null
null
null
null
UTF-8
C++
false
false
263
cpp
#include "HungrySingleton.h" #include<cstdio> HungrySingleton* HungrySingleton::instance = new HungrySingleton(); HungrySingleton::HungrySingleton(){ printf("HungrySingleton: Created.\n"); } HungrySingleton* HungrySingleton::GetInstance(){ return instance; }
[ "790545771@qq.com" ]
790545771@qq.com
8071423f7e1984724f8c45571c0a070afb661781
e74670462bc1d91d8a1b6361a849adb9968c7a56
/c++/src/capnp/schema-parser-test.c++
3e0e2362763f05d279d1aed8056018be420b14bf
[ "BSD-2-Clause" ]
permissive
Mause/capnproto
53344d6b9edfef5d64bfd0bbc2f2f0e68d388fb9
b90263bb0cc56315d1ddc413377390fd92f2f6d5
refs/heads/master
2022-06-16T22:26:18.336061
2013-12-06T11:12:29
2013-12-06T11:12:29
14,927,598
0
0
BSD-2-Clause
2022-05-17T03:17:53
2013-12-04T15:29:48
C++
UTF-8
C++
false
false
7,410
// Copyright (c) 2013, Kenton Varda <temporal@gmail.com> // All rights reserved. // // 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. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "schema-parser.h" #include <gtest/gtest.h> #include "test-util.h" #include <kj/debug.h> #include <map> namespace capnp { namespace { class FakeFileReader final: public SchemaFile::FileReader { public: void add(kj::StringPtr name, kj::StringPtr content) { files[name] = content; } bool exists(kj::StringPtr path) const override { return files.count(path) > 0; } kj::Array<const char> read(kj::StringPtr path) const override { auto iter = files.find(path); KJ_ASSERT(iter != files.end(), "FakeFileReader has no such file.", path); auto result = kj::heapArray<char>(iter->second.size()); memcpy(result.begin(), iter->second.begin(), iter->second.size()); return kj::mv(result); } private: std::map<kj::StringPtr, kj::StringPtr> files; }; static uint64_t getFieldTypeFileId(StructSchema::Field field) { return field.getContainingStruct() .getDependency(field.getProto().getSlot().getType().getStruct().getTypeId()) .getProto().getScopeId(); } TEST(SchemaParser, Basic) { SchemaParser parser; FakeFileReader reader; reader.add("src/foo/bar.capnp", "@0x8123456789abcdef;\n" "struct Bar {\n" " baz @0: import \"baz.capnp\".Baz;\n" " corge @1: import \"../qux/corge.capnp\".Corge;\n" " grault @2: import \"/grault.capnp\".Grault;\n" " garply @3: import \"/garply.capnp\".Garply;\n" "}\n"); reader.add("src/foo/baz.capnp", "@0x823456789abcdef1;\n" "struct Baz {}\n"); reader.add("src/qux/corge.capnp", "@0x83456789abcdef12;\n" "struct Corge {}\n"); reader.add("/usr/include/grault.capnp", "@0x8456789abcdef123;\n" "struct Grault {}\n"); reader.add("/opt/include/grault.capnp", "@0x8000000000000001;\n" "struct WrongGrault {}\n"); reader.add("/usr/local/include/garply.capnp", "@0x856789abcdef1234;\n" "struct Garply {}\n"); kj::StringPtr importPath[] = { "/usr/include", "/usr/local/include", "/opt/include" }; ParsedSchema barSchema = parser.parseFile(SchemaFile::newDiskFile( "foo2/bar2.capnp", "src/foo/bar.capnp", importPath, reader)); auto barProto = barSchema.getProto(); EXPECT_EQ(0x8123456789abcdefull, barProto.getId()); EXPECT_EQ("foo2/bar2.capnp", barProto.getDisplayName()); auto barStruct = barSchema.getNested("Bar"); auto barFields = barStruct.asStruct().getFields(); ASSERT_EQ(4u, barFields.size()); EXPECT_EQ("baz", barFields[0].getProto().getName()); EXPECT_EQ(0x823456789abcdef1ull, getFieldTypeFileId(barFields[0])); EXPECT_EQ("corge", barFields[1].getProto().getName()); EXPECT_EQ(0x83456789abcdef12ull, getFieldTypeFileId(barFields[1])); EXPECT_EQ("grault", barFields[2].getProto().getName()); EXPECT_EQ(0x8456789abcdef123ull, getFieldTypeFileId(barFields[2])); EXPECT_EQ("garply", barFields[3].getProto().getName()); EXPECT_EQ(0x856789abcdef1234ull, getFieldTypeFileId(barFields[3])); auto bazSchema = parser.parseFile(SchemaFile::newDiskFile( "not/used/because/already/loaded", "src/foo/baz.capnp", importPath, reader)); EXPECT_EQ(0x823456789abcdef1ull, bazSchema.getProto().getId()); EXPECT_EQ("foo2/baz.capnp", bazSchema.getProto().getDisplayName()); auto bazStruct = bazSchema.getNested("Baz").asStruct(); EXPECT_EQ(bazStruct, barStruct.getDependency(bazStruct.getProto().getId())); auto corgeSchema = parser.parseFile(SchemaFile::newDiskFile( "not/used/because/already/loaded", "src/qux/corge.capnp", importPath, reader)); EXPECT_EQ(0x83456789abcdef12ull, corgeSchema.getProto().getId()); EXPECT_EQ("qux/corge.capnp", corgeSchema.getProto().getDisplayName()); auto corgeStruct = corgeSchema.getNested("Corge").asStruct(); EXPECT_EQ(corgeStruct, barStruct.getDependency(corgeStruct.getProto().getId())); auto graultSchema = parser.parseFile(SchemaFile::newDiskFile( "not/used/because/already/loaded", "/usr/include/grault.capnp", importPath, reader)); EXPECT_EQ(0x8456789abcdef123ull, graultSchema.getProto().getId()); EXPECT_EQ("grault.capnp", graultSchema.getProto().getDisplayName()); auto graultStruct = graultSchema.getNested("Grault").asStruct(); EXPECT_EQ(graultStruct, barStruct.getDependency(graultStruct.getProto().getId())); // Try importing the other grault.capnp directly. It'll get the display name we specify since // it wasn't imported before. auto wrongGraultSchema = parser.parseFile(SchemaFile::newDiskFile( "weird/display/name.capnp", "/opt/include/grault.capnp", importPath, reader)); EXPECT_EQ(0x8000000000000001ull, wrongGraultSchema.getProto().getId()); EXPECT_EQ("weird/display/name.capnp", wrongGraultSchema.getProto().getDisplayName()); } TEST(SchemaParser, Constants) { // This is actually a test of the full dynamic API stack for constants, because the schemas for // constants are not actually accessible from the generated code API, so the only way to ever // get a ConstSchema is by parsing it. SchemaParser parser; FakeFileReader reader; reader.add("const.capnp", "@0x8123456789abcdef;\n" "const uint32Const :UInt32 = 1234;\n" "const listConst :List(Float32) = [1.25, 2.5, 3e4];\n" "const structConst :Foo = (bar = 123, baz = \"qux\");\n" "struct Foo {\n" " bar @0 :Int16;\n" " baz @1 :Text;\n" "}\n"); ParsedSchema barSchema = parser.parseFile(SchemaFile::newDiskFile( "const.capnp", "const.capnp", nullptr, reader)); EXPECT_EQ(1234, barSchema.getNested("uint32Const").asConst().as<uint32_t>()); auto list = barSchema.getNested("listConst").asConst().as<DynamicList>(); ASSERT_EQ(3u, list.size()); EXPECT_EQ(1.25, list[0].as<float>()); EXPECT_EQ(2.5, list[1].as<float>()); EXPECT_EQ(3e4f, list[2].as<float>()); auto structConst = barSchema.getNested("structConst").asConst().as<DynamicStruct>(); EXPECT_EQ(123, structConst.get("bar").as<int16_t>()); EXPECT_EQ("qux", structConst.get("baz").as<Text>()); } } // namespace } // namespace capnp
[ "temporal@gmail.com" ]
temporal@gmail.com
773d9703b8fc751bd2e5eea86e158f575dbd5947
23ca310ab083819810f1f6471173e0f22e946261
/lab12/factors.cpp
445c37f586d4b13aebe3ce59e1843bc190362685
[]
no_license
siomon0330/USC-CSCI455
e62f456683e769957148660226247c1794d9f0be
5c096e8f216028e4ee44e5d033b34a3db62d8e92
refs/heads/master
2021-05-05T10:44:09.295787
2017-09-20T20:16:25
2017-09-20T20:16:25
104,261,637
13
5
null
null
null
null
UTF-8
C++
false
false
396
cpp
#include <iostream> using namespace std; // finds all of n's factors // not including 1 and itself void factors (int n) { //int k = 2; int k = 0; while (k < n) { if (n % k == 0) { cout << k << endl; } // k++; } } int main() { int n; cout << "Find factors of what number? "; cin >> n; cout << "Factors of n are: " << endl; factors (n); cout << endl; }
[ "noreply@github.com" ]
noreply@github.com
b6ed6f46f4901e462d9839f1008befcc11705049
675e0bd80e7cb4ee507dc70e6e714e6fa4f5b5a4
/plugins/uep/src/WorldLogic.cpp
984e47f8933734836a66df0856dda674221f65eb
[]
no_license
MaxStgs/MagicFirstBase
264e0b0cd1cecf41c7d981e7a20cd879fff02c4a
0f540dcc57df7c2d57a40e4b6a312f4a429ff46e
refs/heads/master
2022-07-17T16:27:32.581761
2020-05-22T12:46:52
2020-05-22T12:46:52
266,108,939
0
0
null
null
null
null
UTF-8
C++
false
false
1,940
cpp
#include "WorldLogic.h" #include <UnigineConsole.h> #include <UnigineInput.h> #include <UnigineApp.h> #include <UnigineControls.h> #include <UnigineEditor.h> #include <Windows.h> using namespace Unigine; int my_world_logic::init() { if (!Editor::isLoaded()) { take_focus(); } Log::message("uep MyWorldLogic::init()\n"); return 1; } int my_world_logic::update() { check_should_reload_world(); check_have_focus(); return 1; } void my_world_logic::check_should_reload_world() { if (Input::isKeyPressed(Input::KEY_CTRL) && Input::isKeyPressed(Input::KEY_SHIFT) && Input::isKeyPressed(Input::KEY_R)) { Console::run("world_reload"); } if (Input::isKeyPressed(Input::KEY_R)) { Log::message("Ctrl pressed!\n"); } } void my_world_logic::take_focus() const { App::setMouseGrab(true); ControlsApp::setMouseHandle(Input::MOUSE_HANDLE_GRAB); ControlsApp::setMouseEnabled(true); if (debug_) { Log::message("active\n"); } } void my_world_logic::unfocus() const { App::setMouseGrab(false); ControlsApp::setMouseHandle(Input::MOUSE_HANDLE_USER); ControlsApp::setMouseEnabled(false); if (debug_) { Log::message("is not active\n"); } } void my_world_logic::check_have_focus() { if (Editor::isLoaded()) return; const bool is_in_focus = is_app_in_focus(); if (is_in_focus == is_last_focused_) return; if (is_in_focus) { is_last_focused_ = true; take_focus(); } else { is_last_focused_ = false; unfocus(); } } bool my_world_logic::is_app_in_focus() { DWORD activePID; GetWindowThreadProcessId(GetForegroundWindow(), &activePID); return activePID == GetCurrentProcessId(); } int my_world_logic::shutdown() { Log::message("reload_world_plugin MyWorldLogic::shutdown()\n"); return 1; }
[ "peters2011.pm@gmail.com" ]
peters2011.pm@gmail.com
b27453e078b59e007915e4e8c3e316b77dcf090d
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/make/old_hunk_434.cpp
0891070620fb1e2a7aa1bc08000595fb77c05cd3
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
807
cpp
expand_builtin_function (char *o, int argc, char **argv, const struct function_table_entry *entry_p) { if (argc < (int)entry_p->minimum_args) fatal (*expanding_var, _("insufficient number of arguments (%d) to function '%s'"), argc, entry_p->name); /* I suppose technically some function could do something with no arguments, but so far none do, so just test it for all functions here rather than in each one. We can change it later if necessary. */ if (!argc) return o; if (!entry_p->func_ptr) fatal (*expanding_var, _("unimplemented on this platform: function '%s'"), entry_p->name); return entry_p->func_ptr (o, argv, entry_p->name); } /* Check for a function invocation in *STRINGP. *STRINGP points at the
[ "993273596@qq.com" ]
993273596@qq.com
59d484ecd9d0333632b5b9318976b99a8f031f29
1fb14697fc0b8a0d3fcaf29c8295aca0440049e9
/include/sbml/packages/fbc/util/CobraToFbcConverter.h
4ded93d629ba85ac2ca0f673d78a0dd92f9cf29d
[]
no_license
rwinlib/libsbml
7144aca4dbd0989e4f42609ee18756d7c8f10d5f
0538ddb0c671e4f56d30271f39fa72a9ff986542
refs/heads/master
2023-04-20T05:31:18.057667
2021-05-15T11:36:04
2021-05-15T11:36:04
367,614,993
1
0
null
null
null
null
UTF-8
C++
false
false
6,259
h
/** * @file CobraToFbcConverter.h * @brief Definition of a cobra 2 fbc converter. * @author Frank T. Bergmann * * <!-------------------------------------------------------------------------- * This file is part of libSBML. Please visit http://sbml.org for more * information about SBML, and the latest version of libSBML. * * Copyright (C) 2020 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. University of Heidelberg, Heidelberg, Germany * 3. University College London, London, UK * * Copyright (C) 2019 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. University of Heidelberg, Heidelberg, Germany * * Copyright (C) 2013-2018 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK * 3. University of Heidelberg, Heidelberg, Germany * * Copyright (C) 2009-2013 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation. A copy of the license agreement is provided * in the file named "LICENSE.txt" included with this software distribution * and also available online as http://sbml.org/software/libsbml/license.html * ---------------------------------------------------------------------- --> * * @class CobraToFbcConverter * @sbmlbrief{fbc} COBRA to SBML Level 3 &ldquo;fbc&rdquo; converter. * * @htmlinclude libsbml-facility-only-warning.html * * This converter takes a model in COBRA format and converts it to the * &ldquo;fbc&rdquo; Version&nbsp;2 format. * * CobraToFbcConverter is enabled by creating a ConversionProperties object * with the option <code>"convert cobra"</code> (literally that full string, * including the spaces), and passing this properties object to * SBMLDocument::convert(@if java ConversionProperties@endif). The converter * offers two options: * * @li @c "checkCompatibility": whether to check the SBML Level/Version * compatibility * @li @c "removeUnits": whether to remove unit definitions * * @copydetails doc_section_using_sbml_converters */ #ifndef CobraToFbcConverter_h #define CobraToFbcConverter_h #include <sbml/common/extern.h> #include <sbml/SBMLNamespaces.h> #include <sbml/conversion/SBMLConverter.h> #include <sbml/conversion/SBMLConverterRegister.h> #ifdef __cplusplus LIBSBML_CPP_NAMESPACE_BEGIN class LIBSBML_EXTERN CobraToFbcConverter : public SBMLConverter { public: /** @cond doxygenLibsbmlInternal */ /** * Register with the ConversionRegistry. */ static void init(); /** @endcond */ /** * Creates a new CobraToFbcConverter object. */ CobraToFbcConverter(); /** * Copy constructor; creates a copy of an CobraToFbcConverter * object. * * @param orig the CobraToFbcConverter object to copy. */ CobraToFbcConverter(const CobraToFbcConverter& orig); /** * Creates and returns a deep copy of this CobraToFbcConverter object. * * @return a (deep) copy of this CobraToFbcConverter. */ virtual CobraToFbcConverter* clone() const; /** * Destroy this CobraToFbcConverter object. */ virtual ~CobraToFbcConverter (); /** * Returns @c true if this converter object's properties match the given * properties. * * A typical use of this method involves creating a ConversionProperties * object, setting the options desired, and then calling this method on * an CobraToFbcConverter object to find out if the object's * property values match the given ones. This method is also used by * SBMLConverterRegistry::getConverterFor(@if java ConversionProperties@endif) * to search across all registered converters for one matching particular * properties. * * @param props the properties to match. * * @return @c true if this converter's properties match, @c false * otherwise. */ virtual bool matchesProperties(const ConversionProperties &props) const; /** * Perform the conversion. * * This method causes the converter to do the actual conversion work, * that is, to convert the SBMLDocument object set by * SBMLConverter::setDocument(@if java SBMLDocument@endif) and * with the configuration options set by * SBMLConverter::setProperties(@if java ConversionProperties@endif). * * @copydetails doc_returns_success_code * @li @sbmlconstant{LIBSBML_OPERATION_SUCCESS, OperationReturnValues_t} * @li @sbmlconstant{LIBSBML_OPERATION_FAILED, OperationReturnValues_t} * @li @sbmlconstant{LIBSBML_INVALID_OBJECT, OperationReturnValues_t} */ virtual int convert(); /** * Returns the default properties of this converter. * * A given converter exposes one or more properties that can be adjusted * in order to influence the behavior of the converter. This method * returns the @em default property settings for this converter. It is * meant to be called in order to discover all the settings for the * converter object. * * @return the ConversionProperties object describing the default properties * for this converter. */ virtual ConversionProperties getDefaultProperties() const; /** * Returns @c true if the option property to check Level and Version of the * source document (@c "checkCompatibility") is @c true. * * @return @c true if the option @c "checkCompatibility" has been set to * @c true, @c false otherwise. */ bool checkCompatibility() const; }; LIBSBML_CPP_NAMESPACE_END #endif /* __cplusplus */ #ifndef SWIG LIBSBML_CPP_NAMESPACE_BEGIN BEGIN_C_DECLS END_C_DECLS LIBSBML_CPP_NAMESPACE_END #endif /* !SWIG */ #endif /* CobraToFbcConverter_h*/
[ "jeroenooms@gmail.com" ]
jeroenooms@gmail.com
a668bac8139d18f2a1f0bd6198c0dfe4a1997e43
983424bb42cdbef82975287229652d490dd8f521
/Sorting 1.cpp
cda5a814081179c10c720f93d82bd6392315ec12
[]
no_license
namnguyen215/Thuc_hanh_tin
d6802641b73576fdda951f38bb6b5ab31d7d5d7f
c6958a8f9a1ca4a3fc578054cfc289fd9e935bae
refs/heads/main
2023-07-17T07:32:51.408534
2021-08-06T14:29:34
2021-08-06T14:29:34
305,582,293
0
0
null
null
null
null
UTF-8
C++
false
false
288
cpp
#include<bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--){ int n; cin>>n; int a[n+1]; for(int i=0;i<n;i++) cin>>a[i]; sort(a,a+n); for(int i=0;i<n/2;i++) { cout<<a[n-1-i]<<" "<<a[i]<<" "; } if(n%2!=0) cout<<a[(n-1)/2]; cout<<endl; } }
[ "namnguyenphuong215@gmail.com" ]
namnguyenphuong215@gmail.com
e0b42059ddba2c19af4655edaad3a28361cc9eda
a62342d6359a88b0aee911e549a4973fa38de9ea
/0.6.0.3/Internal/SDK/NavArea_WildAnimals_classes.h
d244b7f1987fb13f12ab58db636e5bc0bcb6c34d
[]
no_license
zanzo420/Medieval-Dynasty-SDK
d020ad634328ee8ee612ba4bd7e36b36dab740ce
d720e49ae1505e087790b2743506921afb28fc18
refs/heads/main
2023-06-20T03:00:17.986041
2021-07-15T04:51:34
2021-07-15T04:51:34
386,165,085
0
0
null
null
null
null
UTF-8
C++
false
false
744
h
#pragma once // Name: Medieval Dynasty, Version: 0.6.0.3 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass NavArea_WildAnimals.NavArea_WildAnimals_C // 0x0000 (FullSize[0x0048] - InheritedSize[0x0048]) class UNavArea_WildAnimals_C : public UNavArea { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass NavArea_WildAnimals.NavArea_WildAnimals_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
7c3ee1a2ad24eb2025a5ad7ede7b105ecd66eb25
3888b3333cf1ee5c9bfcf751c5f87f5d3be96ae9
/Receive.ino
555b97212ee2c75625ae8e449457418bbbc4c37d
[ "MIT" ]
permissive
highground88/CC1101-FSK
28caea4bf4e0be0ed346c67883a5a243977ec6d1
36261ae9dcd842d05102eeb50a8765c41a0d72e1
refs/heads/master
2021-01-13T08:43:25.668195
2017-02-05T11:08:16
2017-02-05T11:08:16
81,635,235
3
0
null
2017-02-11T06:23:30
2017-02-11T06:23:30
null
UTF-8
C++
false
false
2,569
ino
#include "EEPROM.h" #include "cc1101.h" // The connection to the hardware chip CC1101 the RF Chip CC1101 cc1101; byte b; byte i; byte syncWord = 199; long counter = 0; byte chan = 0; // a flag that a wireless packet has been received boolean packetAvailable = false; /* Handle interrupt from CC1101 (INT0) gdo0 on pin2 */ void cc1101signalsInterrupt(void) { // set the flag that a package is available packetAvailable = true; } void setup() { Serial.begin(38400); Serial.println("start"); // initialize the RF Chip cc1101.init(); //cc1101.setSyncWord(&syncWord, false); cc1101.setCarrierFreq(CFREQ_433); cc1101.disableAddressCheck(); //if not specified, will only display "packet received" //cc1101.setTxPowerAmp(PA_LowPower); Serial.print("CC1101_PARTNUM "); //cc1101=0 Serial.println(cc1101.readReg(CC1101_PARTNUM, CC1101_STATUS_REGISTER)); Serial.print("CC1101_VERSION "); //cc1101=4 Serial.println(cc1101.readReg(CC1101_VERSION, CC1101_STATUS_REGISTER)); Serial.print("CC1101_MARCSTATE "); Serial.println(cc1101.readReg(CC1101_MARCSTATE, CC1101_STATUS_REGISTER) & 0x1f); cc1101.setRxState(); //ADDED BY ME attachInterrupt(0, cc1101signalsInterrupt, FALLING); Serial.println("device initialized"); } void ReadLQI() { byte lqi = 0; byte value = 0; lqi = (cc1101.readReg(CC1101_LQI, CC1101_STATUS_REGISTER)); value = 0x3F - (lqi & 0x3F); Serial.print("CC1101_LQI "); Serial.println(value); } void ReadRSSI() { byte rssi = 0; byte value = 0; rssi = (cc1101.readReg(CC1101_RSSI, CC1101_STATUS_REGISTER)); if (rssi >= 128) { value = 255 - rssi; value /= 2; value += 74; } else { value = rssi / 2; value += 74; } Serial.print("CC1101_RSSI "); Serial.println(value); } void loop() { if (packetAvailable) { Serial.println("packet received"); // Disable wireless reception interrupt detachInterrupt(0); ReadRSSI(); ReadLQI(); // clear the flag packetAvailable = false; CCPACKET packet; if (cc1101.receiveData(&packet) > 0) { if (!packet.crc_ok) { Serial.println("crc not ok"); } if (packet.length > 0) { Serial.print("packet: len "); Serial.print(packet.length); Serial.print(" data: "); for (int j = 0; j < packet.length; j++) { Serial.print(packet.data[j], HEX); Serial.print(" "); } Serial.println("."); } } // Enable wireless reception interrupt attachInterrupt(0, cc1101signalsInterrupt, FALLING); } }
[ "noreply@github.com" ]
noreply@github.com
6721d709b5d4d99c3cc4d3a2c6a0f7f258ab981d
a6407eb8fb10668bc0e3f347ad106080a4ad7631
/1000/1021.cpp
b438f3827887b9fa55c76508ea20c2f7b45c5066
[]
no_license
shingiyeon/baekjoon
76007b6d7dac1eba8cabbf1533abbdd39048bf16
116d272077c7647864045b727e4f7814cd994f91
refs/heads/master
2022-05-10T06:44:11.904843
2022-04-16T07:12:44
2022-04-16T07:12:44
175,241,620
0
1
null
null
null
null
UTF-8
C++
false
false
782
cpp
#include <stdio.h> #include <vector> using namespace std; vector<int> v; void left(){ int a = v[v.size()-1]; v.pop_back(); v.insert(v.begin(), a); } void right(){ int a = v[0]; v.erase(v.begin()); v.push_back(a); } int pop(){ int a = v[0]; v.erase(v.begin()); return a; } int main(){ int N, K; int arr[50]; int ans = 0; scanf("%d%d",&N,&K); for(int i=1; i<=N; i++) v.push_back(i); for(int i=0; i<K; i++) scanf("%d",&arr[i]); for(int i=0; i<K; i++){ int idx; for(int j=0; j<v.size(); j++){ if(v[j] == arr[i]){ idx = j; } } if(idx <= v.size()/2){ for(int j=0; j<idx; j++){ right(); ans++; } pop(); } else{ int size = v.size(); for(int j=idx+1; j<=size; j++){ left(); ans++; } pop(); } } printf("%d",ans); }
[ "nuclear852@kaist.ac.kr" ]
nuclear852@kaist.ac.kr
7054955b2d61f8981f3b26d45bef875d53389dd1
c06574d4ddf1e2cab62737e8b74accea3c34007a
/Codeforces/Round551/BServalAndToyBricks.cpp
2a8e54a47381d91ec8fbc5b5d477e0d306a113ab
[]
no_license
t1war1/CP
5ec8210c37c54262cb8758647fe52c0fec402f35
237c8e32e351511142c4fd79bb965a4e8efa37b6
refs/heads/master
2022-12-21T11:03:14.300293
2020-04-10T11:06:24
2020-04-10T11:06:24
116,372,420
0
1
null
2020-10-01T20:37:31
2018-01-05T10:19:59
C++
UTF-8
C++
false
false
1,479
cpp
#include <bits/stdc++.h> #define mod 1000000007ll #define mod2 100000009ll #define mod3 998244353 #define pb push_back #define fastIO ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL); #define readi(x) scanf("%d",&x) #define reads(x) scanf("%s", x) #define readl(x) scanf("%I64d",&x) #define PI 3.141592653589793238462643383 #define repi(i,a,b) for(int i=a;i<b;i++) #define repd(i,a,b) for(int i=a;i>b;i--) #define mp make_pair #define ll long long #define sorti(a,b) sort(a,b) #define sortd(a,b,tp) sort(a,b,greater<tp>()) #define ff first #define ss second using namespace std; typedef pair<int,int> pii; typedef pair<ll,ll> pll; typedef pair<long double,long double>pdd; template<class T> using max_pq = priority_queue<T>; template<class T> using min_pq = priority_queue<T,vector<T>,greater<T>>; int oo = 0x3f3f3f3f; class BServalAndToyBricks { int arr[101][101]; int n,m,h; int front[101],left[101]; public: void solve(istream& cin, ostream& cout) { cin>>n>>m>>h; repi(i,0,m) { cin>>front[i]; } repi(i,0,n) { cin>>left[i]; } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { cin>>arr[i][j]; } } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { cout<<min(front[j],left[i])*arr[i][j]<<" " ; } cout<<"\n"; } } };
[ "tiwarigaurav1998@gmail.com" ]
tiwarigaurav1998@gmail.com
c6793bf986894297a6ba09a9f7ba1b4a055d92d3
96e57c9a645f7cb124756f922ed9a50011347a8f
/Lab - Minesweeper/L1 - Minesweeper/Array_2D.h
c8869b1af96909bdce8eb7cc4a852a3fd3277887
[]
no_license
tannalynn/CST211-DataStructs
1a7b325656eab3acc8930eb7469d1d04f28a0127
b286571f6d9681f615010a08b2e1947fb46fe359
refs/heads/master
2016-09-09T14:16:42.577476
2015-04-04T18:39:58
2015-04-04T18:39:58
33,414,531
0
0
null
null
null
null
UTF-8
C++
false
false
9,674
h
/*************************************************************************************************** * Author: Tanna McClure * File: Array_2D.h * Date Created: 1/7/2015 * * Modification Date: 1/9/2015 * Modification: Finished * ***************************************************************************************************//*************************************************************************************************** * Class: Array_2D * * Purpose: * 2D array class. * * Manager Functions: * Array_2D(); * Default Constructor * Array_2D(int row, int col = 0); * 2 arg ctor * Array_2D(const Array_2D<T> & copy); * Copy Constructor * ~Array_2D(); * dtor * Array_2D<T> & operator = (const Array_2D<T> & rhs); * Assignment Operator * * Methods: * Row<T> operator [] (int i) const; * [] operator - returns a row object that you can use to get an element from the array * const Row<T> Array_2D<T>::operator[](int i) const * [] operator - returns a CONST row object that you can use to get an element from the array * int GetRow() const; * gets the number of rows in the array * int GetColumn() const; * gets the number of columns in the array * void SetRow(int i); * changes the number of rows in the array * void SetColumn(int i); * changes the number * T & Select(int row, int col) const; * returns a specific element in the array * ***************************************************************************************************/ #ifndef ARRAY_2D_H #define ARRAY_2D_H #include "Array_1D.h" #include "Row.h" template <typename T> class Array_2D { public: //Default Constructor Array_2D(); //2 arg ctor Array_2D(int row, int col = 0); //Copy Constructor Array_2D(const Array_2D<T> & copy); //Destructor ~Array_2D(); //Assignment Operator Array_2D<T> & operator = (const Array_2D<T> & rhs); //[] operator Row<T> operator [] (int i); const Row<T> operator[](int i) const; //getters int GetRow() const; int GetColumn() const; //setters void SetRow(int i); void SetColumn(int i); //Deletes everything in the Array void Purge(); //returns the data from a specific spot in the 2d array T & Select(int row, int col); const T & Select(int row, int col) const; private: Array_1D<T> m_array; int m_row; int m_col; }; /*************************************************************************************************** * Function Definitions ***************************************************************************************************/ /*************************************************************************************************** * Purpose: default ctor * * Entry: none * * Exit: initializes everything to zero ***************************************************************************************************/ template <typename T> Array_2D<T>::Array_2D() : m_col(0), m_row(0) { } /*************************************************************************************************** * Purpose: 2 arg ctor * * Entry: number of rows and columns * * Exit: the array is set to the length needed for the number of rows and columns passed in * * Exception: Throws an exception if the row or column passed in is negative ***************************************************************************************************/ template <typename T> Array_2D<T>::Array_2D(int row, int col /*= 0*/) : m_row(row), m_col(col) { if (m_row < 0 || m_col < 0) { m_row = m_col = 0; throw Exception("Exception: Array_2D - 2 arg ctor: Invalid row or column"); } m_array.SetLength(m_col*m_row); } /*************************************************************************************************** * Purpose: copy ctor * * Entry: the array to copy * * Exit: this is equal to the array passed in ***************************************************************************************************/ template <typename T> Array_2D<T>::Array_2D(const Array_2D<T> & copy) : m_row(copy.m_row), m_col(copy.m_col), m_array(copy.m_array) { } /*************************************************************************************************** * Purpose: dtor * * Entry: none * * Exit: object is destroyed and values set back to 0 ***************************************************************************************************/ template <typename T> Array_2D<T>::~Array_2D() { Purge(); } /*************************************************************************************************** * Purpose: assignment operator * * Entry: the array to copy * * Exit: this is now the same as rhs ***************************************************************************************************/ template <typename T> Array_2D<T> & Array_2D<T>::operator=(const Array_2D<T> & rhs) { m_row = rhs.m_row; m_col = rhs.m_col; m_array = rhs.m_array; return *this; } /*************************************************************************************************** * Purpose: gets the row to access * * Entry: the row * * Exit: the Row object is returned containing the row to access and a ref to the 2d array ***************************************************************************************************/ template <typename T> Row<T> Array_2D<T>::operator[](int i) { if (i < 0 || i >= m_row) throw Exception("Exception: Array_2D - [] operator: Invalid position"); return Row<T>(*this, i); } /*************************************************************************************************** * Purpose: gets the row to access CONST * * Entry: the row * * Exit: the Row object is returned containing the row to access and a ref to the 2d array ***************************************************************************************************/ template <typename T> const Row<T> Array_2D<T>::operator[](int i) const { if (i < 0 || i >= m_row) throw Exception("Exception: Array_2D - [] operator: Invalid position"); return Row<T>(*this, i); } /*************************************************************************************************** * Purpose: gets the number of rows in the array * * Entry: none * * Exit: returns m_row ***************************************************************************************************/ template <typename T> int Array_2D<T>::GetRow() const { return m_row; } /*************************************************************************************************** * Purpose: gets the number of columns in the array * * Entry: none * * Exit: returns m_col ***************************************************************************************************/ template <typename T> int Array_2D<T>::GetColumn() const { return m_col; } /*************************************************************************************************** * Purpose: sets the number of rows * * Entry: the new number of rows * * Exit: the array has been changed ***************************************************************************************************/ template <typename T> void Array_2D<T>::SetRow(int i) { if (i < 0) throw Exception("Exception: Array_2D - SetRow: Invalid Row"); if (m_row != i) { m_row = i; m_array.SetLength(m_row * m_col); } } /*************************************************************************************************** * Purpose: sets the number of columns in the array * * Entry: the number of columns * * Exit: array size is changed ***************************************************************************************************/ template <typename T> void Array_2D<T>::SetColumn(int new_col) { if (new_col < 0) throw Exception("Exception: Array_2D - SetColumn: Invalid Column"); if (m_col != new_col) { Array_1D<T> temp(new_col * m_row); int col_min = new_col < m_col ? new_col : m_col; for (int i(0), row(0); row < m_row; row++) for (int j(0); j < col_min; j++) temp[(row*new_col) + j] = m_array[(row*m_col) + j]; m_col = new_col; m_array = temp; } } /*************************************************************************************************** * Purpose: returns an element in the array at a specified location * * Entry: the row and column * * Exit: the data at that part of the array is returned by reference ***************************************************************************************************/ template <typename T> T & Array_2D<T>::Select(int row, int col) { if (row > m_row || row < 0 || col > m_col || col < 0) throw Exception("Exception: Array_2D - Select: Invalid Row or Column"); return m_array[(row* m_col) + col]; } /*************************************************************************************************** * Purpose: returns an element in the array at a specified location CONST * * Entry: the row and column * * Exit: the data at that part of the array is returned by reference ***************************************************************************************************/ template <typename T> const T & Array_2D<T>::Select(int row, int col) const { if (row > m_row || row < 0 || col > m_col || col < 0) throw Exception("Exception: Array_2D - Select: Invalid Row or Column"); return m_array[(row* m_col) + col]; } /*************************************************************************************************** * Purpose: empties the array * * Entry: none * * Exit: array is set back to size 0 ***************************************************************************************************/ template <typename T> void Array_2D<T>::Purge() { m_row = 0; m_col = 0; m_array.SetLength(0); } #endif
[ "tanna.la.lynn@gmail.com" ]
tanna.la.lynn@gmail.com
9c75cc0d7dea69143da9ad30e09b7fe52b0c5879
a7d529b80ddcb0c48df98596970e2f8e3d8e1673
/codcad/Programacao Basica/Caracteres/31 Auto Estrada.cpp
5832e065c21e98005aa2692985a0536610d95659
[]
no_license
jeffersonjpr/maratona
b3d662c5852865806bd898c3040910e316335e81
5e740a9e25a926c7ba4625e010dbbd77eb90e5e3
refs/heads/master
2021-07-11T02:13:38.858177
2020-06-16T19:35:56
2020-06-16T19:35:56
154,176,430
0
0
null
null
null
null
UTF-8
C++
false
false
244
cpp
#include <iostream> using namespace std; int main(){ int n,res=0; char a; cin >> n; for(;n>0;n--){ cin >> a; if(a == 'P'){res += 2;} else if(a == 'C'){res += 2;} else if(a == 'A'){res += 1;} } printf("%i\n",res); }
[ "jefferson_michael407@hotmail.com" ]
jefferson_michael407@hotmail.com
22da0814dde406db7dcf8901a1f7243c6ca17580
c53d25b27b443ad7a2d367d91321d041ba1095b6
/UVa/537_Artificial Intelligence/537.cc
ae6ac01b57c1f2960a0742597dc9b3a32d498176
[ "MIT" ]
permissive
hangim/ACM
52323c5e890549e91b17e94ca5f69125e7dc6faf
956b3d03a5d3f070ef24c940b7459f5cccb11d6c
refs/heads/master
2021-01-19T13:52:22.072249
2015-09-28T12:31:11
2015-09-28T12:31:11
19,826,325
1
0
null
null
null
null
UTF-8
C++
false
false
1,534
cc
#include <iostream> #include <iomanip> #include <stdio.h> using namespace std; bool isContinue(); double getPrefix(); int main() { int t; cin >> t; cin.get(); for (int index = 1; index <= t; index++) { double u = -1, p = -1, i = -1; char var; while (true) { var = getchar(); if (var == '\n') break; if (var == 'U') { if (isContinue()) { cin >> u; u *= getPrefix(); } } else if (var == 'P') { if (isContinue()) { cin >> p; p *= getPrefix(); } } else if (var == 'I') { if (isContinue()) { cin >> i; i *= getPrefix(); } } } cout << "Problem #" << index << endl; cout << setprecision(2) << fixed; if (p == -1) cout << "P=" << u * i << "W" << endl; else if (i == -1) cout << "I=" << p / u << "A" << endl; else cout << "U=" << p / i << "V" << endl; cout << endl; } return 0; } bool isContinue() { char var = getchar(); if (var == '=') return true; else return false; } double getPrefix() { char var; cin >> var; if (var == 'm') return 1e-3; if (var == 'k') return 1e3; if (var == 'M') return 1e6; return 1.0; }
[ "pdszhh@qq.com" ]
pdszhh@qq.com
d7655f5fcd1fdab435d4cd1324dfd138c9967d53
455a676e549f1fc1f889d7536c921126476acca2
/llvm/lib/Transforms/Utils/InlineFunction.cpp
fd27cb9a130f53549a13c7c17a6910cbaef0d797
[ "LicenseRef-scancode-other-permissive", "NCSA", "MIT", "LLVM-exception", "Apache-2.0" ]
permissive
neboat/opencilk-ppopp-23
db342b1c1e83af424df7f5b1809c1ec1d19abf09
3fd08f23ef9b792f4a55e7aeebc7d44beddf3532
refs/heads/main
2023-04-13T22:44:17.301592
2023-01-06T22:16:27
2023-01-06T22:16:27
565,455,474
0
0
null
null
null
null
UTF-8
C++
false
false
136,361
cpp
//===- InlineFunction.cpp - Code to perform function inlining -------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements inlining of a function into a call site, resolving // parameters and the return value as appropriate. // //===----------------------------------------------------------------------===// #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/None.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/iterator_range.h" #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/AssumptionCache.h" #include "llvm/Analysis/BlockFrequencyInfo.h" #include "llvm/Analysis/CallGraph.h" #include "llvm/Analysis/CaptureTracking.h" #include "llvm/Analysis/EHPersonalities.h" #include "llvm/Analysis/InstructionSimplify.h" #include "llvm/Analysis/ObjCARCAnalysisUtils.h" #include "llvm/Analysis/ObjCARCUtil.h" #include "llvm/Analysis/ProfileSummaryInfo.h" #include "llvm/Analysis/ValueTracking.h" #include "llvm/Analysis/VectorUtils.h" #include "llvm/IR/Argument.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/CFG.h" #include "llvm/IR/Constant.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DIBuilder.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/DebugInfo.h" #include "llvm/IR/DebugInfoMetadata.h" #include "llvm/IR/DebugLoc.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Dominators.h" #include "llvm/IR/Function.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/InlineAsm.h" #include "llvm/IR/InstrTypes.h" #include "llvm/IR/Instruction.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/MDBuilder.h" #include "llvm/IR/Metadata.h" #include "llvm/IR/Module.h" #include "llvm/IR/Type.h" #include "llvm/IR/User.h" #include "llvm/IR/Value.h" #include "llvm/Support/Casting.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Transforms/Utils/AssumeBundleBuilder.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" #include "llvm/Transforms/Utils/Cloning.h" #include "llvm/Transforms/Utils/Local.h" #include "llvm/Transforms/Utils/TapirUtils.h" #include "llvm/Transforms/Utils/ValueMapper.h" #include <algorithm> #include <cassert> #include <cstdint> #include <iterator> #include <limits> #include <string> #include <utility> #include <vector> using namespace llvm; using ProfileCount = Function::ProfileCount; static cl::opt<bool> EnableNoAliasConversion("enable-noalias-to-md-conversion", cl::init(true), cl::Hidden, cl::desc("Convert noalias attributes to metadata during inlining.")); static cl::opt<bool> UseNoAliasIntrinsic("use-noalias-intrinsic-during-inlining", cl::Hidden, cl::ZeroOrMore, cl::init(true), cl::desc("Use the llvm.experimental.noalias.scope.decl " "intrinsic during inlining.")); // Disabled by default, because the added alignment assumptions may increase // compile-time and block optimizations. This option is not suitable for use // with frontends that emit comprehensive parameter alignment annotations. static cl::opt<bool> PreserveAlignmentAssumptions("preserve-alignment-assumptions-during-inlining", cl::init(false), cl::Hidden, cl::desc("Convert align attributes to assumptions during inlining.")); static cl::opt<bool> UpdateReturnAttributes( "update-return-attrs", cl::init(true), cl::Hidden, cl::desc("Update return attributes on calls within inlined body")); static cl::opt<unsigned> InlinerAttributeWindow( "max-inst-checked-for-throw-during-inlining", cl::Hidden, cl::desc("the maximum number of instructions analyzed for may throw during " "attribute inference in inlined body"), cl::init(4)); namespace { /// A class for recording information about inlining a landing pad. class LandingPadInliningInfo { /// Destination of the invoke's unwind. BasicBlock *OuterResumeDest; /// Destination for the callee's resume. BasicBlock *InnerResumeDest = nullptr; /// LandingPadInst associated with the invoke. LandingPadInst *CallerLPad = nullptr; /// PHI for EH values from landingpad insts. PHINode *InnerEHValuesPHI = nullptr; SmallVector<Value*, 8> UnwindDestPHIValues; public: LandingPadInliningInfo(InvokeInst *II) : OuterResumeDest(II->getUnwindDest()) { // If there are PHI nodes in the unwind destination block, we need to keep // track of which values came into them from the invoke before removing // the edge from this block. BasicBlock *InvokeBB = II->getParent(); BasicBlock::iterator I = OuterResumeDest->begin(); for (; isa<PHINode>(I); ++I) { // Save the value to use for this edge. PHINode *PHI = cast<PHINode>(I); UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(InvokeBB)); } CallerLPad = cast<LandingPadInst>(I); } /// The outer unwind destination is the target of /// unwind edges introduced for calls within the inlined function. BasicBlock *getOuterResumeDest() const { return OuterResumeDest; } BasicBlock *getInnerResumeDest(); LandingPadInst *getLandingPadInst() const { return CallerLPad; } /// Forward the 'resume' instruction to the caller's landing pad block. /// When the landing pad block has only one predecessor, this is /// a simple branch. When there is more than one predecessor, we need to /// split the landing pad block after the landingpad instruction and jump /// to there. void forwardResume(ResumeInst *RI, SmallPtrSetImpl<LandingPadInst*> &InlinedLPads); /// Add incoming-PHI values to the unwind destination block for the given /// basic block, using the values for the original invoke's source block. void addIncomingPHIValuesFor(BasicBlock *BB) const { addIncomingPHIValuesForInto(BB, OuterResumeDest); } void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) const { BasicBlock::iterator I = dest->begin(); for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) { PHINode *phi = cast<PHINode>(I); phi->addIncoming(UnwindDestPHIValues[i], src); } } }; } // end anonymous namespace /// Get or create a target for the branch from ResumeInsts. BasicBlock *LandingPadInliningInfo::getInnerResumeDest() { if (InnerResumeDest) return InnerResumeDest; // Split the landing pad. BasicBlock::iterator SplitPoint = ++CallerLPad->getIterator(); InnerResumeDest = OuterResumeDest->splitBasicBlock(SplitPoint, OuterResumeDest->getName() + ".body"); // The number of incoming edges we expect to the inner landing pad. const unsigned PHICapacity = 2; // Create corresponding new PHIs for all the PHIs in the outer landing pad. Instruction *InsertPoint = &InnerResumeDest->front(); BasicBlock::iterator I = OuterResumeDest->begin(); for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) { PHINode *OuterPHI = cast<PHINode>(I); PHINode *InnerPHI = PHINode::Create(OuterPHI->getType(), PHICapacity, OuterPHI->getName() + ".lpad-body", InsertPoint); OuterPHI->replaceAllUsesWith(InnerPHI); InnerPHI->addIncoming(OuterPHI, OuterResumeDest); } // Create a PHI for the exception values. InnerEHValuesPHI = PHINode::Create(CallerLPad->getType(), PHICapacity, "eh.lpad-body", InsertPoint); CallerLPad->replaceAllUsesWith(InnerEHValuesPHI); InnerEHValuesPHI->addIncoming(CallerLPad, OuterResumeDest); // All done. return InnerResumeDest; } /// Forward the 'resume' instruction to the caller's landing pad block. /// When the landing pad block has only one predecessor, this is a simple /// branch. When there is more than one predecessor, we need to split the /// landing pad block after the landingpad instruction and jump to there. void LandingPadInliningInfo::forwardResume( ResumeInst *RI, SmallPtrSetImpl<LandingPadInst *> &InlinedLPads) { BasicBlock *Dest = getInnerResumeDest(); BasicBlock *Src = RI->getParent(); BranchInst::Create(Dest, Src); // Update the PHIs in the destination. They were inserted in an order which // makes this work. addIncomingPHIValuesForInto(Src, Dest); InnerEHValuesPHI->addIncoming(RI->getOperand(0), Src); RI->eraseFromParent(); } /// Helper for getUnwindDestToken/getUnwindDestTokenHelper. static Value *getParentPad(Value *EHPad) { if (auto *FPI = dyn_cast<FuncletPadInst>(EHPad)) return FPI->getParentPad(); return cast<CatchSwitchInst>(EHPad)->getParentPad(); } using UnwindDestMemoTy = DenseMap<Instruction *, Value *>; /// Helper for getUnwindDestToken that does the descendant-ward part of /// the search. static Value *getUnwindDestTokenHelper(Instruction *EHPad, UnwindDestMemoTy &MemoMap) { SmallVector<Instruction *, 8> Worklist(1, EHPad); while (!Worklist.empty()) { Instruction *CurrentPad = Worklist.pop_back_val(); // We only put pads on the worklist that aren't in the MemoMap. When // we find an unwind dest for a pad we may update its ancestors, but // the queue only ever contains uncles/great-uncles/etc. of CurrentPad, // so they should never get updated while queued on the worklist. assert(!MemoMap.count(CurrentPad)); Value *UnwindDestToken = nullptr; if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(CurrentPad)) { if (CatchSwitch->hasUnwindDest()) { UnwindDestToken = CatchSwitch->getUnwindDest()->getFirstNonPHI(); } else { // Catchswitch doesn't have a 'nounwind' variant, and one might be // annotated as "unwinds to caller" when really it's nounwind (see // e.g. SimplifyCFGOpt::SimplifyUnreachable), so we can't infer the // parent's unwind dest from this. We can check its catchpads' // descendants, since they might include a cleanuppad with an // "unwinds to caller" cleanupret, which can be trusted. for (auto HI = CatchSwitch->handler_begin(), HE = CatchSwitch->handler_end(); HI != HE && !UnwindDestToken; ++HI) { BasicBlock *HandlerBlock = *HI; auto *CatchPad = cast<CatchPadInst>(HandlerBlock->getFirstNonPHI()); for (User *Child : CatchPad->users()) { // Intentionally ignore invokes here -- since the catchswitch is // marked "unwind to caller", it would be a verifier error if it // contained an invoke which unwinds out of it, so any invoke we'd // encounter must unwind to some child of the catch. if (!isa<CleanupPadInst>(Child) && !isa<CatchSwitchInst>(Child)) continue; Instruction *ChildPad = cast<Instruction>(Child); auto Memo = MemoMap.find(ChildPad); if (Memo == MemoMap.end()) { // Haven't figured out this child pad yet; queue it. Worklist.push_back(ChildPad); continue; } // We've already checked this child, but might have found that // it offers no proof either way. Value *ChildUnwindDestToken = Memo->second; if (!ChildUnwindDestToken) continue; // We already know the child's unwind dest, which can either // be ConstantTokenNone to indicate unwind to caller, or can // be another child of the catchpad. Only the former indicates // the unwind dest of the catchswitch. if (isa<ConstantTokenNone>(ChildUnwindDestToken)) { UnwindDestToken = ChildUnwindDestToken; break; } assert(getParentPad(ChildUnwindDestToken) == CatchPad); } } } } else { auto *CleanupPad = cast<CleanupPadInst>(CurrentPad); for (User *U : CleanupPad->users()) { if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(U)) { if (BasicBlock *RetUnwindDest = CleanupRet->getUnwindDest()) UnwindDestToken = RetUnwindDest->getFirstNonPHI(); else UnwindDestToken = ConstantTokenNone::get(CleanupPad->getContext()); break; } Value *ChildUnwindDestToken; if (auto *Invoke = dyn_cast<InvokeInst>(U)) { ChildUnwindDestToken = Invoke->getUnwindDest()->getFirstNonPHI(); } else if (isa<CleanupPadInst>(U) || isa<CatchSwitchInst>(U)) { Instruction *ChildPad = cast<Instruction>(U); auto Memo = MemoMap.find(ChildPad); if (Memo == MemoMap.end()) { // Haven't resolved this child yet; queue it and keep searching. Worklist.push_back(ChildPad); continue; } // We've checked this child, but still need to ignore it if it // had no proof either way. ChildUnwindDestToken = Memo->second; if (!ChildUnwindDestToken) continue; } else { // Not a relevant user of the cleanuppad continue; } // In a well-formed program, the child/invoke must either unwind to // an(other) child of the cleanup, or exit the cleanup. In the // first case, continue searching. if (isa<Instruction>(ChildUnwindDestToken) && getParentPad(ChildUnwindDestToken) == CleanupPad) continue; UnwindDestToken = ChildUnwindDestToken; break; } } // If we haven't found an unwind dest for CurrentPad, we may have queued its // children, so move on to the next in the worklist. if (!UnwindDestToken) continue; // Now we know that CurrentPad unwinds to UnwindDestToken. It also exits // any ancestors of CurrentPad up to but not including UnwindDestToken's // parent pad. Record this in the memo map, and check to see if the // original EHPad being queried is one of the ones exited. Value *UnwindParent; if (auto *UnwindPad = dyn_cast<Instruction>(UnwindDestToken)) UnwindParent = getParentPad(UnwindPad); else UnwindParent = nullptr; bool ExitedOriginalPad = false; for (Instruction *ExitedPad = CurrentPad; ExitedPad && ExitedPad != UnwindParent; ExitedPad = dyn_cast<Instruction>(getParentPad(ExitedPad))) { // Skip over catchpads since they just follow their catchswitches. if (isa<CatchPadInst>(ExitedPad)) continue; MemoMap[ExitedPad] = UnwindDestToken; ExitedOriginalPad |= (ExitedPad == EHPad); } if (ExitedOriginalPad) return UnwindDestToken; // Continue the search. } // No definitive information is contained within this funclet. return nullptr; } /// Given an EH pad, find where it unwinds. If it unwinds to an EH pad, /// return that pad instruction. If it unwinds to caller, return /// ConstantTokenNone. If it does not have a definitive unwind destination, /// return nullptr. /// /// This routine gets invoked for calls in funclets in inlinees when inlining /// an invoke. Since many funclets don't have calls inside them, it's queried /// on-demand rather than building a map of pads to unwind dests up front. /// Determining a funclet's unwind dest may require recursively searching its /// descendants, and also ancestors and cousins if the descendants don't provide /// an answer. Since most funclets will have their unwind dest immediately /// available as the unwind dest of a catchswitch or cleanupret, this routine /// searches top-down from the given pad and then up. To avoid worst-case /// quadratic run-time given that approach, it uses a memo map to avoid /// re-processing funclet trees. The callers that rewrite the IR as they go /// take advantage of this, for correctness, by checking/forcing rewritten /// pads' entries to match the original callee view. static Value *getUnwindDestToken(Instruction *EHPad, UnwindDestMemoTy &MemoMap) { // Catchpads unwind to the same place as their catchswitch; // redirct any queries on catchpads so the code below can // deal with just catchswitches and cleanuppads. if (auto *CPI = dyn_cast<CatchPadInst>(EHPad)) EHPad = CPI->getCatchSwitch(); // Check if we've already determined the unwind dest for this pad. auto Memo = MemoMap.find(EHPad); if (Memo != MemoMap.end()) return Memo->second; // Search EHPad and, if necessary, its descendants. Value *UnwindDestToken = getUnwindDestTokenHelper(EHPad, MemoMap); assert((UnwindDestToken == nullptr) != (MemoMap.count(EHPad) != 0)); if (UnwindDestToken) return UnwindDestToken; // No information is available for this EHPad from itself or any of its // descendants. An unwind all the way out to a pad in the caller would // need also to agree with the unwind dest of the parent funclet, so // search up the chain to try to find a funclet with information. Put // null entries in the memo map to avoid re-processing as we go up. MemoMap[EHPad] = nullptr; #ifndef NDEBUG SmallPtrSet<Instruction *, 4> TempMemos; TempMemos.insert(EHPad); #endif Instruction *LastUselessPad = EHPad; Value *AncestorToken; for (AncestorToken = getParentPad(EHPad); auto *AncestorPad = dyn_cast<Instruction>(AncestorToken); AncestorToken = getParentPad(AncestorToken)) { // Skip over catchpads since they just follow their catchswitches. if (isa<CatchPadInst>(AncestorPad)) continue; // If the MemoMap had an entry mapping AncestorPad to nullptr, since we // haven't yet called getUnwindDestTokenHelper for AncestorPad in this // call to getUnwindDestToken, that would mean that AncestorPad had no // information in itself, its descendants, or its ancestors. If that // were the case, then we should also have recorded the lack of information // for the descendant that we're coming from. So assert that we don't // find a null entry in the MemoMap for AncestorPad. assert(!MemoMap.count(AncestorPad) || MemoMap[AncestorPad]); auto AncestorMemo = MemoMap.find(AncestorPad); if (AncestorMemo == MemoMap.end()) { UnwindDestToken = getUnwindDestTokenHelper(AncestorPad, MemoMap); } else { UnwindDestToken = AncestorMemo->second; } if (UnwindDestToken) break; LastUselessPad = AncestorPad; MemoMap[LastUselessPad] = nullptr; #ifndef NDEBUG TempMemos.insert(LastUselessPad); #endif } // We know that getUnwindDestTokenHelper was called on LastUselessPad and // returned nullptr (and likewise for EHPad and any of its ancestors up to // LastUselessPad), so LastUselessPad has no information from below. Since // getUnwindDestTokenHelper must investigate all downward paths through // no-information nodes to prove that a node has no information like this, // and since any time it finds information it records it in the MemoMap for // not just the immediately-containing funclet but also any ancestors also // exited, it must be the case that, walking downward from LastUselessPad, // visiting just those nodes which have not been mapped to an unwind dest // by getUnwindDestTokenHelper (the nullptr TempMemos notwithstanding, since // they are just used to keep getUnwindDestTokenHelper from repeating work), // any node visited must have been exhaustively searched with no information // for it found. SmallVector<Instruction *, 8> Worklist(1, LastUselessPad); while (!Worklist.empty()) { Instruction *UselessPad = Worklist.pop_back_val(); auto Memo = MemoMap.find(UselessPad); if (Memo != MemoMap.end() && Memo->second) { // Here the name 'UselessPad' is a bit of a misnomer, because we've found // that it is a funclet that does have information about unwinding to // a particular destination; its parent was a useless pad. // Since its parent has no information, the unwind edge must not escape // the parent, and must target a sibling of this pad. This local unwind // gives us no information about EHPad. Leave it and the subtree rooted // at it alone. assert(getParentPad(Memo->second) == getParentPad(UselessPad)); continue; } // We know we don't have information for UselesPad. If it has an entry in // the MemoMap (mapping it to nullptr), it must be one of the TempMemos // added on this invocation of getUnwindDestToken; if a previous invocation // recorded nullptr, it would have had to prove that the ancestors of // UselessPad, which include LastUselessPad, had no information, and that // in turn would have required proving that the descendants of // LastUselesPad, which include EHPad, have no information about // LastUselessPad, which would imply that EHPad was mapped to nullptr in // the MemoMap on that invocation, which isn't the case if we got here. assert(!MemoMap.count(UselessPad) || TempMemos.count(UselessPad)); // Assert as we enumerate users that 'UselessPad' doesn't have any unwind // information that we'd be contradicting by making a map entry for it // (which is something that getUnwindDestTokenHelper must have proved for // us to get here). Just assert on is direct users here; the checks in // this downward walk at its descendants will verify that they don't have // any unwind edges that exit 'UselessPad' either (i.e. they either have no // unwind edges or unwind to a sibling). MemoMap[UselessPad] = UnwindDestToken; if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(UselessPad)) { assert(CatchSwitch->getUnwindDest() == nullptr && "Expected useless pad"); for (BasicBlock *HandlerBlock : CatchSwitch->handlers()) { auto *CatchPad = HandlerBlock->getFirstNonPHI(); for (User *U : CatchPad->users()) { assert( (!isa<InvokeInst>(U) || (getParentPad( cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) == CatchPad)) && "Expected useless pad"); if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U)) Worklist.push_back(cast<Instruction>(U)); } } } else { assert(isa<CleanupPadInst>(UselessPad)); for (User *U : UselessPad->users()) { assert(!isa<CleanupReturnInst>(U) && "Expected useless pad"); assert((!isa<InvokeInst>(U) || (getParentPad( cast<InvokeInst>(U)->getUnwindDest()->getFirstNonPHI()) == UselessPad)) && "Expected useless pad"); if (isa<CatchSwitchInst>(U) || isa<CleanupPadInst>(U)) Worklist.push_back(cast<Instruction>(U)); } } } return UnwindDestToken; } /// When we inline a basic block into an invoke, /// we have to turn all of the calls that can throw into invokes. /// This function analyze BB to see if there are any calls, and if so, /// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI /// nodes in that block with the values specified in InvokeDestPHIValues. static BasicBlock *HandleCallsInBlockInlinedThroughInvoke( BasicBlock *BB, BasicBlock *UnwindEdge, UnwindDestMemoTy *FuncletUnwindMap = nullptr) { for (Instruction &I : llvm::make_early_inc_range(*BB)) { // We only need to check for function calls: inlined invoke // instructions require no special handling. CallInst *CI = dyn_cast<CallInst>(&I); if (!CI || CI->doesNotThrow()) continue; if (CI->isInlineAsm()) { InlineAsm *IA = cast<InlineAsm>(CI->getCalledOperand()); if (!IA->canThrow()) { continue; } } // We do not need to (and in fact, cannot) convert possibly throwing calls // to @llvm.experimental_deoptimize (resp. @llvm.experimental.guard) into // invokes. The caller's "segment" of the deoptimization continuation // attached to the newly inlined @llvm.experimental_deoptimize // (resp. @llvm.experimental.guard) call should contain the exception // handling logic, if any. if (auto *F = CI->getCalledFunction()) if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize || F->getIntrinsicID() == Intrinsic::experimental_guard) continue; if (auto FuncletBundle = CI->getOperandBundle(LLVMContext::OB_funclet)) { // This call is nested inside a funclet. If that funclet has an unwind // destination within the inlinee, then unwinding out of this call would // be UB. Rewriting this call to an invoke which targets the inlined // invoke's unwind dest would give the call's parent funclet multiple // unwind destinations, which is something that subsequent EH table // generation can't handle and that the veirifer rejects. So when we // see such a call, leave it as a call. auto *FuncletPad = cast<Instruction>(FuncletBundle->Inputs[0]); Value *UnwindDestToken = getUnwindDestToken(FuncletPad, *FuncletUnwindMap); if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken)) continue; #ifndef NDEBUG Instruction *MemoKey; if (auto *CatchPad = dyn_cast<CatchPadInst>(FuncletPad)) MemoKey = CatchPad->getCatchSwitch(); else MemoKey = FuncletPad; assert(FuncletUnwindMap->count(MemoKey) && (*FuncletUnwindMap)[MemoKey] == UnwindDestToken && "must get memoized to avoid confusing later searches"); #endif // NDEBUG } changeToInvokeAndSplitBasicBlock(CI, UnwindEdge); return BB; } return nullptr; } // Helper method to check if the given UnwindEdge unwinds a taskframe, i.e., if // it is terminated with a taskframe.resume intrinsic. static bool isTaskFrameUnwind(const BasicBlock *UnwindEdge) { return isTaskFrameResume(UnwindEdge->getTerminator()); } static void splitTaskFrameEnds(Instruction *TFCreate) { // Split taskframe.end that use TFCreate. SmallVector<Instruction *, 8> TFEndToSplit; for (User *U : TFCreate->users()) if (IntrinsicInst *UI = dyn_cast<IntrinsicInst>(U)) if (Intrinsic::taskframe_end == UI->getIntrinsicID()) TFEndToSplit.push_back(UI); for (Instruction *TFEnd : TFEndToSplit) { if (TFEnd != TFEnd->getParent()->getTerminator()->getPrevNode()) { BasicBlock::iterator Iter = ++TFEnd->getIterator(); SplitBlock(TFEnd->getParent(), &*Iter); // Try to attach debug info to the new terminator after the taskframe.end // call. Instruction *SplitTerminator = TFEnd->getParent()->getTerminator(); if (!SplitTerminator->getDebugLoc()) SplitTerminator->setDebugLoc(TFEnd->getDebugLoc()); Iter->getParent()->setName(TFEnd->getParent()->getName() + ".tfend"); } } } // Recursively handle inlined tasks. static void HandleInlinedTasksHelper( SmallPtrSetImpl<BasicBlock *> &BlocksToProcess, BasicBlock *FirstNewBlock, BasicBlock *UnwindEdge, BasicBlock *Unreachable, Value *CurrentTaskFrame, SmallVectorImpl<BasicBlock *> *ParentWorklist, LandingPadInliningInfo &Invoke, SmallPtrSetImpl<LandingPadInst *> &InlinedLPads) { SmallVector<DetachInst *, 8> DetachesToReplace; SmallVector<BasicBlock *, 32> Worklist; // TODO: See if we need a global Visited set over all recursive calls, i.e., // to handle shared exception-handling blocks. SmallPtrSet<BasicBlock *, 32> Visited; Worklist.push_back(FirstNewBlock); do { BasicBlock *BB = Worklist.pop_back_val(); // Skip blocks we've seen before if (!Visited.insert(BB).second) continue; // Skip blocks not in the set to process. if (!BlocksToProcess.count(BB)) continue; if (Instruction *TFCreate = FindTaskFrameCreateInBlock(BB)) { if (TFCreate != CurrentTaskFrame) { // Split the block at the taskframe.create, if necessary. BasicBlock *NewBB; if (TFCreate != &BB->front()) { NewBB = SplitBlock(BB, TFCreate); BlocksToProcess.insert(NewBB); } else NewBB = BB; // Split any blocks containing taskframe.end intrinsics that use // TFCreate. splitTaskFrameEnds(TFCreate); // Create an unwind edge for the taskframe. BasicBlock *TaskFrameUnwindEdge = CreateSubTaskUnwindEdge( Intrinsic::taskframe_resume, TFCreate, UnwindEdge, Unreachable, TFCreate); // Recursively check all blocks HandleInlinedTasksHelper(BlocksToProcess, NewBB, TaskFrameUnwindEdge, Unreachable, TFCreate, &Worklist, Invoke, InlinedLPads); // Remove the unwind edge for the taskframe if it is not needed. if (pred_empty(TaskFrameUnwindEdge)) TaskFrameUnwindEdge->eraseFromParent(); continue; } } // Promote any calls in the block to invokes. if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke( BB, UnwindEdge)) { // If this is the topmost invocation of HandleInlinedTasksHelper, update // any PHI nodes in the exceptional block to indicate that there is now a // new entry in them. if (nullptr == ParentWorklist) Invoke.addIncomingPHIValuesFor(NewBB); BlocksToProcess.insert( cast<InvokeInst>(NewBB->getTerminator())->getNormalDest()); } // Forward any resumes that are remaining here. if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) Invoke.forwardResume(RI, InlinedLPads); // Ignore reattach terminators. if (isa<ReattachInst>(BB->getTerminator()) || isDetachedRethrow(BB->getTerminator())) continue; // If we find a taskframe.end, add its successor to the parent search. if (endsTaskFrame(BB, CurrentTaskFrame)) { // We may not have a parent worklist, if inlining itself created // the taskframe. if (ParentWorklist) ParentWorklist->push_back(BB->getSingleSuccessor()); continue; } // If we find a taskframe.resume terminator, add its successor to the parent // search. if (isTaskFrameResume(BB->getTerminator()) && ParentWorklist) { assert(isTaskFrameUnwind(UnwindEdge) && "Unexpected taskframe.resume, doesn't correspond to unwind edge"); InvokeInst *II = cast<InvokeInst>(BB->getTerminator()); // We may not have a parent worklist, however, if inlining itself created // the taskframe. if (ParentWorklist) ParentWorklist->push_back(II->getUnwindDest()); continue; } // Process a detach instruction specially. In particular, process the // spawned task recursively. if (DetachInst *DI = dyn_cast<DetachInst>(BB->getTerminator())) { if (!DI->hasUnwindDest()) { // Create an unwind edge for the subtask, which is terminated with a // detached-rethrow. BasicBlock *SubTaskUnwindEdge = CreateSubTaskUnwindEdge( Intrinsic::detached_rethrow, DI->getSyncRegion(), UnwindEdge, Unreachable, DI); // Recursively check all blocks in the detached task. HandleInlinedTasksHelper(BlocksToProcess, DI->getDetached(), SubTaskUnwindEdge, Unreachable, CurrentTaskFrame, &Worklist, Invoke, InlinedLPads); // If the new unwind edge is not used, remove it. if (pred_empty(SubTaskUnwindEdge)) SubTaskUnwindEdge->eraseFromParent(); else { DetachesToReplace.push_back(DI); // Update PHI nodes in the exceptional block to indicate that // SubTaskUnwindEdge is a new entry in them. This should only have an // effect for the topmost call to HandleInlinedTasksHelper. Invoke.addIncomingPHIValuesFor(SubTaskUnwindEdge); } } else if (Visited.insert(DI->getUnwindDest()).second) { // If the detach-unwind isn't dead, add it to the worklist. Worklist.push_back(DI->getUnwindDest()); } // Add the continuation to the worklist. if (isTaskFrameUnwind(UnwindEdge) && (CurrentTaskFrame == getTaskFrameUsed(DI->getDetached()))) { // This detach-continuation terminates the current taskframe, so push it // onto the parent worklist. assert(ParentWorklist && "Unexpected taskframe unwind edge"); ParentWorklist->push_back(DI->getContinue()); } else { // We can process this detach-continuation directly, because it does not // terminate the current taskframe. Worklist.push_back(DI->getContinue()); } continue; } // In the normal case, add all successors of BB to the worklist. for (BasicBlock *Successor : successors(BB)) Worklist.push_back(Successor); } while (!Worklist.empty()); // Replace detaches that now require unwind destinations. while (!DetachesToReplace.empty()) { DetachInst *DI = DetachesToReplace.pop_back_val(); // If this is the topmost invocation of HandleInlinedTasksHelper, update any // PHI nodes in the exceptional block to indicate that there is now a new // entry in them. if (nullptr == ParentWorklist) Invoke.addIncomingPHIValuesFor(DI->getParent()); ReplaceInstWithInst(DI, DetachInst::Create( DI->getDetached(), DI->getContinue(), UnwindEdge, DI->getSyncRegion())); } } static void HandleInlinedTasks( SmallPtrSetImpl<BasicBlock *> &BlocksToProcess, BasicBlock *FirstNewBlock, Value *TFCreate, BasicBlock *UnwindEdge, LandingPadInliningInfo &Invoke, SmallPtrSetImpl<LandingPadInst *> &InlinedLPads) { Function *Caller = UnwindEdge->getParent(); // Create the normal return for the detached rethrow. BasicBlock *UnreachableBlk = BasicBlock::Create( Caller->getContext(), UnwindEdge->getName()+".unreachable", Caller); // Recursively handle inlined tasks. HandleInlinedTasksHelper(BlocksToProcess, FirstNewBlock, UnwindEdge, UnreachableBlk, TFCreate, nullptr, Invoke, InlinedLPads); // Either finish the unreachable block or remove it, depending on whether it // is used. if (!pred_empty(UnreachableBlk)) { IRBuilder<> Builder(UnreachableBlk); Builder.CreateUnreachable(); } else { UnreachableBlk->eraseFromParent(); } } static void GetInlinedLPads(SmallPtrSetImpl<BasicBlock *> &BlocksToProcess, SmallPtrSetImpl<LandingPadInst *> &InlinedLPads) { SmallVector<BasicBlock *, 32> Worklist; SmallPtrSet<BasicBlock *, 32> Visited; // Push all blocks to process that are terminated by a resume onto the // worklist. for (BasicBlock *BB : BlocksToProcess) if (isa<ResumeInst>(BB->getTerminator())) Worklist.push_back(BB); // Traverse the blocks to process from the resumes going backwards (through // predecessors). while(!Worklist.empty()) { BasicBlock *BB = Worklist.pop_back_val(); // Skip blocks we've seen before if (!Visited.insert(BB).second) continue; // Skip blocks not in the set to process. if (!BlocksToProcess.count(BB)) continue; // If BB is a landingpad... if (BB->isLandingPad()) { // Record BB's landingpad instruction. InlinedLPads.insert(BB->getLandingPadInst()); // Add predecessors of BB to the worklist, skipping predecessors via a // detached.rethrow or taskframe.resume. for (BasicBlock *Predecessor : predecessors(BB)) if (!isDetachedRethrow(Predecessor->getTerminator()) && !isTaskFrameResume(Predecessor->getTerminator())) Worklist.push_back(Predecessor); continue; } // In the normal case, add predecessors of BB to the worklist, excluding // predecessors via reattach, detached.rethrow, or taskframe.resume for (BasicBlock *Predecessor : predecessors(BB)) if (!isa<ResumeInst>(Predecessor->getTerminator()) && !isDetachedRethrow(Predecessor->getTerminator()) && !isTaskFrameResume(Predecessor->getTerminator())) Worklist.push_back(Predecessor); } } /// If we inlined an invoke site, we need to convert calls /// in the body of the inlined function into invokes. /// /// II is the invoke instruction being inlined. FirstNewBlock is the first /// block of the inlined code (the last block is the end of the function), /// and InlineCodeInfo is information about the code that got inlined. static void HandleInlinedLandingPad(InvokeInst *II, BasicBlock *FirstNewBlock, Value *TFCreate, ClonedCodeInfo &InlinedCodeInfo) { BasicBlock *InvokeDest = II->getUnwindDest(); Function *Caller = FirstNewBlock->getParent(); // The inlined code is currently at the end of the function, scan from the // start of the inlined code to its end, checking for stuff we need to // rewrite. LandingPadInliningInfo Invoke(II); // Special processing is needed to inline a function that contains a task. if (InlinedCodeInfo.ContainsDetach) { // Get the set of blocks for the inlined function. SmallPtrSet<BasicBlock *, 32> BlocksToProcess; for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end(); BB != E; ++BB) BlocksToProcess.insert(&*BB); // Get all of the inlined landing pad instructions. SmallPtrSet<LandingPadInst*, 16> InlinedLPads; GetInlinedLPads(BlocksToProcess, InlinedLPads); // Append the clauses from the outer landing pad instruction into the // inlined landing pad instructions. LandingPadInst *OuterLPad = Invoke.getLandingPadInst(); for (LandingPadInst *InlinedLPad : InlinedLPads) { unsigned OuterNum = OuterLPad->getNumClauses(); InlinedLPad->reserveClauses(OuterNum); for (unsigned OuterIdx = 0; OuterIdx != OuterNum; ++OuterIdx) InlinedLPad->addClause(OuterLPad->getClause(OuterIdx)); if (OuterLPad->isCleanup()) InlinedLPad->setCleanup(true); } // Process inlined subtasks. HandleInlinedTasks(BlocksToProcess, FirstNewBlock, TFCreate, Invoke.getOuterResumeDest(), Invoke, InlinedLPads); // Now that everything is happy, we have one final detail. The PHI nodes in // the exception destination block still have entries due to the original // invoke instruction. Eliminate these entries (which might even delete the // PHI node) now. InvokeDest->removePredecessor(II->getParent()); return; } // Get all of the inlined landing pad instructions. SmallPtrSet<LandingPadInst*, 16> InlinedLPads; for (Function::iterator I = FirstNewBlock->getIterator(), E = Caller->end(); I != E; ++I) if (InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator())) InlinedLPads.insert(II->getLandingPadInst()); // Append the clauses from the outer landing pad instruction into the inlined // landing pad instructions. LandingPadInst *OuterLPad = Invoke.getLandingPadInst(); for (LandingPadInst *InlinedLPad : InlinedLPads) { unsigned OuterNum = OuterLPad->getNumClauses(); InlinedLPad->reserveClauses(OuterNum); for (unsigned OuterIdx = 0; OuterIdx != OuterNum; ++OuterIdx) InlinedLPad->addClause(OuterLPad->getClause(OuterIdx)); if (OuterLPad->isCleanup()) InlinedLPad->setCleanup(true); } for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end(); BB != E; ++BB) { if (InlinedCodeInfo.ContainsCalls) if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke( &*BB, Invoke.getOuterResumeDest())) // Update any PHI nodes in the exceptional block to indicate that there // is now a new entry in them. Invoke.addIncomingPHIValuesFor(NewBB); // Forward any resumes that are remaining here. if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) Invoke.forwardResume(RI, InlinedLPads); } // Now that everything is happy, we have one final detail. The PHI nodes in // the exception destination block still have entries due to the original // invoke instruction. Eliminate these entries (which might even delete the // PHI node) now. InvokeDest->removePredecessor(II->getParent()); } /// If we inlined an invoke site, we need to convert calls /// in the body of the inlined function into invokes. /// /// II is the invoke instruction being inlined. FirstNewBlock is the first /// block of the inlined code (the last block is the end of the function), /// and InlineCodeInfo is information about the code that got inlined. static void HandleInlinedEHPad(InvokeInst *II, BasicBlock *FirstNewBlock, ClonedCodeInfo &InlinedCodeInfo) { BasicBlock *UnwindDest = II->getUnwindDest(); Function *Caller = FirstNewBlock->getParent(); assert(UnwindDest->getFirstNonPHI()->isEHPad() && "unexpected BasicBlock!"); // If there are PHI nodes in the unwind destination block, we need to keep // track of which values came into them from the invoke before removing the // edge from this block. SmallVector<Value *, 8> UnwindDestPHIValues; BasicBlock *InvokeBB = II->getParent(); for (PHINode &PHI : UnwindDest->phis()) { // Save the value to use for this edge. UnwindDestPHIValues.push_back(PHI.getIncomingValueForBlock(InvokeBB)); } // Add incoming-PHI values to the unwind destination block for the given basic // block, using the values for the original invoke's source block. auto UpdatePHINodes = [&](BasicBlock *Src) { BasicBlock::iterator I = UnwindDest->begin(); for (Value *V : UnwindDestPHIValues) { PHINode *PHI = cast<PHINode>(I); PHI->addIncoming(V, Src); ++I; } }; // This connects all the instructions which 'unwind to caller' to the invoke // destination. UnwindDestMemoTy FuncletUnwindMap; for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end(); BB != E; ++BB) { if (auto *CRI = dyn_cast<CleanupReturnInst>(BB->getTerminator())) { if (CRI->unwindsToCaller()) { auto *CleanupPad = CRI->getCleanupPad(); CleanupReturnInst::Create(CleanupPad, UnwindDest, CRI); CRI->eraseFromParent(); UpdatePHINodes(&*BB); // Finding a cleanupret with an unwind destination would confuse // subsequent calls to getUnwindDestToken, so map the cleanuppad // to short-circuit any such calls and recognize this as an "unwind // to caller" cleanup. assert(!FuncletUnwindMap.count(CleanupPad) || isa<ConstantTokenNone>(FuncletUnwindMap[CleanupPad])); FuncletUnwindMap[CleanupPad] = ConstantTokenNone::get(Caller->getContext()); } } Instruction *I = BB->getFirstNonPHI(); if (!I->isEHPad()) continue; Instruction *Replacement = nullptr; if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) { if (CatchSwitch->unwindsToCaller()) { Value *UnwindDestToken; if (auto *ParentPad = dyn_cast<Instruction>(CatchSwitch->getParentPad())) { // This catchswitch is nested inside another funclet. If that // funclet has an unwind destination within the inlinee, then // unwinding out of this catchswitch would be UB. Rewriting this // catchswitch to unwind to the inlined invoke's unwind dest would // give the parent funclet multiple unwind destinations, which is // something that subsequent EH table generation can't handle and // that the veirifer rejects. So when we see such a call, leave it // as "unwind to caller". UnwindDestToken = getUnwindDestToken(ParentPad, FuncletUnwindMap); if (UnwindDestToken && !isa<ConstantTokenNone>(UnwindDestToken)) continue; } else { // This catchswitch has no parent to inherit constraints from, and // none of its descendants can have an unwind edge that exits it and // targets another funclet in the inlinee. It may or may not have a // descendant that definitively has an unwind to caller. In either // case, we'll have to assume that any unwinds out of it may need to // be routed to the caller, so treat it as though it has a definitive // unwind to caller. UnwindDestToken = ConstantTokenNone::get(Caller->getContext()); } auto *NewCatchSwitch = CatchSwitchInst::Create( CatchSwitch->getParentPad(), UnwindDest, CatchSwitch->getNumHandlers(), CatchSwitch->getName(), CatchSwitch); for (BasicBlock *PadBB : CatchSwitch->handlers()) NewCatchSwitch->addHandler(PadBB); // Propagate info for the old catchswitch over to the new one in // the unwind map. This also serves to short-circuit any subsequent // checks for the unwind dest of this catchswitch, which would get // confused if they found the outer handler in the callee. FuncletUnwindMap[NewCatchSwitch] = UnwindDestToken; Replacement = NewCatchSwitch; } } else if (!isa<FuncletPadInst>(I)) { llvm_unreachable("unexpected EHPad!"); } if (Replacement) { Replacement->takeName(I); I->replaceAllUsesWith(Replacement); I->eraseFromParent(); UpdatePHINodes(&*BB); } } if (InlinedCodeInfo.ContainsCalls) for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end(); BB != E; ++BB) if (BasicBlock *NewBB = HandleCallsInBlockInlinedThroughInvoke( &*BB, UnwindDest, &FuncletUnwindMap)) // Update any PHI nodes in the exceptional block to indicate that there // is now a new entry in them. UpdatePHINodes(NewBB); // Now that everything is happy, we have one final detail. The PHI nodes in // the exception destination block still have entries due to the original // invoke instruction. Eliminate these entries (which might even delete the // PHI node) now. UnwindDest->removePredecessor(InvokeBB); } /// When inlining a call site that has !llvm.mem.parallel_loop_access, /// !llvm.access.group, !alias.scope or !noalias metadata, that metadata should /// be propagated to all memory-accessing cloned instructions. static void PropagateCallSiteMetadata(CallBase &CB, Function::iterator FStart, Function::iterator FEnd) { MDNode *MemParallelLoopAccess = CB.getMetadata(LLVMContext::MD_mem_parallel_loop_access); MDNode *AccessGroup = CB.getMetadata(LLVMContext::MD_access_group); MDNode *AliasScope = CB.getMetadata(LLVMContext::MD_alias_scope); MDNode *NoAlias = CB.getMetadata(LLVMContext::MD_noalias); if (!MemParallelLoopAccess && !AccessGroup && !AliasScope && !NoAlias) return; for (BasicBlock &BB : make_range(FStart, FEnd)) { for (Instruction &I : BB) { // This metadata is only relevant for instructions that access memory. if (!I.mayReadOrWriteMemory()) continue; if (MemParallelLoopAccess) { // TODO: This probably should not overwrite MemParalleLoopAccess. MemParallelLoopAccess = MDNode::concatenate( I.getMetadata(LLVMContext::MD_mem_parallel_loop_access), MemParallelLoopAccess); I.setMetadata(LLVMContext::MD_mem_parallel_loop_access, MemParallelLoopAccess); } if (AccessGroup) I.setMetadata(LLVMContext::MD_access_group, uniteAccessGroups( I.getMetadata(LLVMContext::MD_access_group), AccessGroup)); if (AliasScope) I.setMetadata(LLVMContext::MD_alias_scope, MDNode::concatenate( I.getMetadata(LLVMContext::MD_alias_scope), AliasScope)); if (NoAlias) I.setMetadata(LLVMContext::MD_noalias, MDNode::concatenate( I.getMetadata(LLVMContext::MD_noalias), NoAlias)); } } } namespace { /// Utility for cloning !noalias and !alias.scope metadata. When a code region /// using scoped alias metadata is inlined, the aliasing relationships may not /// hold between the two version. It is necessary to create a deep clone of the /// metadata, putting the two versions in separate scope domains. class ScopedAliasMetadataDeepCloner { using MetadataMap = DenseMap<const MDNode *, TrackingMDNodeRef>; SetVector<const MDNode *> MD; MetadataMap MDMap; void addRecursiveMetadataUses(); public: ScopedAliasMetadataDeepCloner(const Function *F); /// Create a new clone of the scoped alias metadata, which will be used by /// subsequent remap() calls. void clone(); /// Remap instructions in the given range from the original to the cloned /// metadata. void remap(Function::iterator FStart, Function::iterator FEnd); }; } // namespace ScopedAliasMetadataDeepCloner::ScopedAliasMetadataDeepCloner( const Function *F) { for (const BasicBlock &BB : *F) { for (const Instruction &I : BB) { if (const MDNode *M = I.getMetadata(LLVMContext::MD_alias_scope)) MD.insert(M); if (const MDNode *M = I.getMetadata(LLVMContext::MD_noalias)) MD.insert(M); // We also need to clone the metadata in noalias intrinsics. if (const auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I)) MD.insert(Decl->getScopeList()); } } addRecursiveMetadataUses(); } void ScopedAliasMetadataDeepCloner::addRecursiveMetadataUses() { SmallVector<const Metadata *, 16> Queue(MD.begin(), MD.end()); while (!Queue.empty()) { const MDNode *M = cast<MDNode>(Queue.pop_back_val()); for (const Metadata *Op : M->operands()) if (const MDNode *OpMD = dyn_cast<MDNode>(Op)) if (MD.insert(OpMD)) Queue.push_back(OpMD); } } void ScopedAliasMetadataDeepCloner::clone() { assert(MDMap.empty() && "clone() already called ?"); SmallVector<TempMDTuple, 16> DummyNodes; for (const MDNode *I : MD) { DummyNodes.push_back(MDTuple::getTemporary(I->getContext(), None)); MDMap[I].reset(DummyNodes.back().get()); } // Create new metadata nodes to replace the dummy nodes, replacing old // metadata references with either a dummy node or an already-created new // node. SmallVector<Metadata *, 4> NewOps; for (const MDNode *I : MD) { for (const Metadata *Op : I->operands()) { if (const MDNode *M = dyn_cast<MDNode>(Op)) NewOps.push_back(MDMap[M]); else NewOps.push_back(const_cast<Metadata *>(Op)); } MDNode *NewM = MDNode::get(I->getContext(), NewOps); MDTuple *TempM = cast<MDTuple>(MDMap[I]); assert(TempM->isTemporary() && "Expected temporary node"); TempM->replaceAllUsesWith(NewM); NewOps.clear(); } } void ScopedAliasMetadataDeepCloner::remap(Function::iterator FStart, Function::iterator FEnd) { if (MDMap.empty()) return; // Nothing to do. for (BasicBlock &BB : make_range(FStart, FEnd)) { for (Instruction &I : BB) { // TODO: The null checks for the MDMap.lookup() results should no longer // be necessary. if (MDNode *M = I.getMetadata(LLVMContext::MD_alias_scope)) if (MDNode *MNew = MDMap.lookup(M)) I.setMetadata(LLVMContext::MD_alias_scope, MNew); if (MDNode *M = I.getMetadata(LLVMContext::MD_noalias)) if (MDNode *MNew = MDMap.lookup(M)) I.setMetadata(LLVMContext::MD_noalias, MNew); if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I)) if (MDNode *MNew = MDMap.lookup(Decl->getScopeList())) Decl->setScopeList(MNew); } } } /// If the inlined function has noalias arguments, /// then add new alias scopes for each noalias argument, tag the mapped noalias /// parameters with noalias metadata specifying the new scope, and tag all /// non-derived loads, stores and memory intrinsics with the new alias scopes. static void AddAliasScopeMetadata(CallBase &CB, ValueToValueMapTy &VMap, const DataLayout &DL, AAResults *CalleeAAR, ClonedCodeInfo &InlinedFunctionInfo) { if (!EnableNoAliasConversion) return; const Function *CalledFunc = CB.getCalledFunction(); SmallVector<const Argument *, 4> NoAliasArgs; for (const Argument &Arg : CalledFunc->args()) if (CB.paramHasAttr(Arg.getArgNo(), Attribute::NoAlias) && !Arg.use_empty()) NoAliasArgs.push_back(&Arg); if (NoAliasArgs.empty()) return; // To do a good job, if a noalias variable is captured, we need to know if // the capture point dominates the particular use we're considering. DominatorTree DT; DT.recalculate(const_cast<Function&>(*CalledFunc)); // noalias indicates that pointer values based on the argument do not alias // pointer values which are not based on it. So we add a new "scope" for each // noalias function argument. Accesses using pointers based on that argument // become part of that alias scope, accesses using pointers not based on that // argument are tagged as noalias with that scope. DenseMap<const Argument *, MDNode *> NewScopes; MDBuilder MDB(CalledFunc->getContext()); // Create a new scope domain for this function. MDNode *NewDomain = MDB.createAnonymousAliasScopeDomain(CalledFunc->getName()); for (unsigned i = 0, e = NoAliasArgs.size(); i != e; ++i) { const Argument *A = NoAliasArgs[i]; std::string Name = std::string(CalledFunc->getName()); if (A->hasName()) { Name += ": %"; Name += A->getName(); } else { Name += ": argument "; Name += utostr(i); } // Note: We always create a new anonymous root here. This is true regardless // of the linkage of the callee because the aliasing "scope" is not just a // property of the callee, but also all control dependencies in the caller. MDNode *NewScope = MDB.createAnonymousAliasScope(NewDomain, Name); NewScopes.insert(std::make_pair(A, NewScope)); if (UseNoAliasIntrinsic) { // Introduce a llvm.experimental.noalias.scope.decl for the noalias // argument. MDNode *AScopeList = MDNode::get(CalledFunc->getContext(), NewScope); auto *NoAliasDecl = IRBuilder<>(&CB).CreateNoAliasScopeDeclaration(AScopeList); // Ignore the result for now. The result will be used when the // llvm.noalias intrinsic is introduced. (void)NoAliasDecl; } } // Iterate over all new instructions in the map; for all memory-access // instructions, add the alias scope metadata. for (ValueToValueMapTy::iterator VMI = VMap.begin(), VMIE = VMap.end(); VMI != VMIE; ++VMI) { if (const Instruction *I = dyn_cast<Instruction>(VMI->first)) { if (!VMI->second) continue; Instruction *NI = dyn_cast<Instruction>(VMI->second); if (!NI || InlinedFunctionInfo.isSimplified(I, NI)) continue; bool IsArgMemOnlyCall = false, IsFuncCall = false; SmallVector<const Value *, 2> PtrArgs; if (const LoadInst *LI = dyn_cast<LoadInst>(I)) PtrArgs.push_back(LI->getPointerOperand()); else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) PtrArgs.push_back(SI->getPointerOperand()); else if (const VAArgInst *VAAI = dyn_cast<VAArgInst>(I)) PtrArgs.push_back(VAAI->getPointerOperand()); else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I)) PtrArgs.push_back(CXI->getPointerOperand()); else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I)) PtrArgs.push_back(RMWI->getPointerOperand()); else if (const auto *Call = dyn_cast<CallBase>(I)) { // If we know that the call does not access memory, then we'll still // know that about the inlined clone of this call site, and we don't // need to add metadata. if (Call->doesNotAccessMemory()) continue; IsFuncCall = true; if (CalleeAAR) { FunctionModRefBehavior MRB = CalleeAAR->getModRefBehavior(Call); // We'll retain this knowledge without additional metadata. if (AAResults::onlyAccessesInaccessibleMem(MRB)) continue; if (AAResults::onlyAccessesArgPointees(MRB)) IsArgMemOnlyCall = true; } for (Value *Arg : Call->args()) { // We need to check the underlying objects of all arguments, not just // the pointer arguments, because we might be passing pointers as // integers, etc. // However, if we know that the call only accesses pointer arguments, // then we only need to check the pointer arguments. if (IsArgMemOnlyCall && !Arg->getType()->isPointerTy()) continue; PtrArgs.push_back(Arg); } } // If we found no pointers, then this instruction is not suitable for // pairing with an instruction to receive aliasing metadata. // However, if this is a call, this we might just alias with none of the // noalias arguments. if (PtrArgs.empty() && !IsFuncCall) continue; // It is possible that there is only one underlying object, but you // need to go through several PHIs to see it, and thus could be // repeated in the Objects list. SmallPtrSet<const Value *, 4> ObjSet; SmallVector<Metadata *, 4> Scopes, NoAliases; SmallSetVector<const Argument *, 4> NAPtrArgs; for (const Value *V : PtrArgs) { SmallVector<const Value *, 4> Objects; getUnderlyingObjects(V, Objects, /* LI = */ nullptr); for (const Value *O : Objects) ObjSet.insert(O); } // Figure out if we're derived from anything that is not a noalias // argument. bool CanDeriveViaCapture = false, UsesAliasingPtr = false; for (const Value *V : ObjSet) { // Is this value a constant that cannot be derived from any pointer // value (we need to exclude constant expressions, for example, that // are formed from arithmetic on global symbols). bool IsNonPtrConst = isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<ConstantPointerNull>(V) || isa<ConstantDataVector>(V) || isa<UndefValue>(V); if (IsNonPtrConst) continue; // If this is anything other than a noalias argument, then we cannot // completely describe the aliasing properties using alias.scope // metadata (and, thus, won't add any). if (const Argument *A = dyn_cast<Argument>(V)) { if (!CB.paramHasAttr(A->getArgNo(), Attribute::NoAlias)) UsesAliasingPtr = true; } else { UsesAliasingPtr = true; } // If this is not some identified function-local object (which cannot // directly alias a noalias argument), or some other argument (which, // by definition, also cannot alias a noalias argument), then we could // alias a noalias argument that has been captured). if (!isa<Argument>(V) && !isIdentifiedFunctionLocal(const_cast<Value*>(V))) CanDeriveViaCapture = true; } // A function call can always get captured noalias pointers (via other // parameters, globals, etc.). if (IsFuncCall && !IsArgMemOnlyCall) CanDeriveViaCapture = true; // First, we want to figure out all of the sets with which we definitely // don't alias. Iterate over all noalias set, and add those for which: // 1. The noalias argument is not in the set of objects from which we // definitely derive. // 2. The noalias argument has not yet been captured. // An arbitrary function that might load pointers could see captured // noalias arguments via other noalias arguments or globals, and so we // must always check for prior capture. for (const Argument *A : NoAliasArgs) { if (!ObjSet.count(A) && (!CanDeriveViaCapture || // It might be tempting to skip the // PointerMayBeCapturedBefore check if // A->hasNoCaptureAttr() is true, but this is // incorrect because nocapture only guarantees // that no copies outlive the function, not // that the value cannot be locally captured. !PointerMayBeCapturedBefore(A, /* ReturnCaptures */ false, /* StoreCaptures */ false, I, &DT))) NoAliases.push_back(NewScopes[A]); } if (!NoAliases.empty()) NI->setMetadata(LLVMContext::MD_noalias, MDNode::concatenate( NI->getMetadata(LLVMContext::MD_noalias), MDNode::get(CalledFunc->getContext(), NoAliases))); // Next, we want to figure out all of the sets to which we might belong. // We might belong to a set if the noalias argument is in the set of // underlying objects. If there is some non-noalias argument in our list // of underlying objects, then we cannot add a scope because the fact // that some access does not alias with any set of our noalias arguments // cannot itself guarantee that it does not alias with this access // (because there is some pointer of unknown origin involved and the // other access might also depend on this pointer). We also cannot add // scopes to arbitrary functions unless we know they don't access any // non-parameter pointer-values. bool CanAddScopes = !UsesAliasingPtr; if (CanAddScopes && IsFuncCall) CanAddScopes = IsArgMemOnlyCall; if (CanAddScopes) for (const Argument *A : NoAliasArgs) { if (ObjSet.count(A)) Scopes.push_back(NewScopes[A]); } if (!Scopes.empty()) NI->setMetadata( LLVMContext::MD_alias_scope, MDNode::concatenate(NI->getMetadata(LLVMContext::MD_alias_scope), MDNode::get(CalledFunc->getContext(), Scopes))); } } } static bool MayContainThrowingOrExitingCall(Instruction *Begin, Instruction *End) { assert(Begin->getParent() == End->getParent() && "Expected to be in same basic block!"); return !llvm::isGuaranteedToTransferExecutionToSuccessor( Begin->getIterator(), End->getIterator(), InlinerAttributeWindow + 1); } static AttrBuilder IdentifyValidAttributes(CallBase &CB) { AttrBuilder AB(CB.getContext(), CB.getAttributes().getRetAttrs()); if (!AB.hasAttributes()) return AB; AttrBuilder Valid(CB.getContext()); // Only allow these white listed attributes to be propagated back to the // callee. This is because other attributes may only be valid on the call // itself, i.e. attributes such as signext and zeroext. if (auto DerefBytes = AB.getDereferenceableBytes()) Valid.addDereferenceableAttr(DerefBytes); if (auto DerefOrNullBytes = AB.getDereferenceableOrNullBytes()) Valid.addDereferenceableOrNullAttr(DerefOrNullBytes); if (AB.contains(Attribute::NoAlias)) Valid.addAttribute(Attribute::NoAlias); if (AB.contains(Attribute::NonNull)) Valid.addAttribute(Attribute::NonNull); return Valid; } static void AddReturnAttributes(CallBase &CB, ValueToValueMapTy &VMap) { if (!UpdateReturnAttributes) return; AttrBuilder Valid = IdentifyValidAttributes(CB); if (!Valid.hasAttributes()) return; auto *CalledFunction = CB.getCalledFunction(); auto &Context = CalledFunction->getContext(); for (auto &BB : *CalledFunction) { auto *RI = dyn_cast<ReturnInst>(BB.getTerminator()); if (!RI || !isa<CallBase>(RI->getOperand(0))) continue; auto *RetVal = cast<CallBase>(RI->getOperand(0)); // Check that the cloned RetVal exists and is a call, otherwise we cannot // add the attributes on the cloned RetVal. Simplification during inlining // could have transformed the cloned instruction. auto *NewRetVal = dyn_cast_or_null<CallBase>(VMap.lookup(RetVal)); if (!NewRetVal) continue; // Backward propagation of attributes to the returned value may be incorrect // if it is control flow dependent. // Consider: // @callee { // %rv = call @foo() // %rv2 = call @bar() // if (%rv2 != null) // return %rv2 // if (%rv == null) // exit() // return %rv // } // caller() { // %val = call nonnull @callee() // } // Here we cannot add the nonnull attribute on either foo or bar. So, we // limit the check to both RetVal and RI are in the same basic block and // there are no throwing/exiting instructions between these instructions. if (RI->getParent() != RetVal->getParent() || MayContainThrowingOrExitingCall(RetVal, RI)) continue; // Add to the existing attributes of NewRetVal, i.e. the cloned call // instruction. // NB! When we have the same attribute already existing on NewRetVal, but // with a differing value, the AttributeList's merge API honours the already // existing attribute value (i.e. attributes such as dereferenceable, // dereferenceable_or_null etc). See AttrBuilder::merge for more details. AttributeList AL = NewRetVal->getAttributes(); AttributeList NewAL = AL.addRetAttributes(Context, Valid); NewRetVal->setAttributes(NewAL); } } /// If the inlined function has non-byval align arguments, then /// add @llvm.assume-based alignment assumptions to preserve this information. static void AddAlignmentAssumptions(CallBase &CB, InlineFunctionInfo &IFI) { if (!PreserveAlignmentAssumptions || !IFI.GetAssumptionCache) return; AssumptionCache *AC = &IFI.GetAssumptionCache(*CB.getCaller()); auto &DL = CB.getCaller()->getParent()->getDataLayout(); // To avoid inserting redundant assumptions, we should check for assumptions // already in the caller. To do this, we might need a DT of the caller. DominatorTree DT; bool DTCalculated = false; Function *CalledFunc = CB.getCalledFunction(); for (Argument &Arg : CalledFunc->args()) { unsigned Align = Arg.getType()->isPointerTy() ? Arg.getParamAlignment() : 0; if (Align && !Arg.hasPassPointeeByValueCopyAttr() && !Arg.hasNUses(0)) { if (!DTCalculated) { DT.recalculate(*CB.getCaller()); DTCalculated = true; } // If we can already prove the asserted alignment in the context of the // caller, then don't bother inserting the assumption. Value *ArgVal = CB.getArgOperand(Arg.getArgNo()); if (getKnownAlignment(ArgVal, DL, &CB, AC, &DT) >= Align) continue; CallInst *NewAsmp = IRBuilder<>(&CB).CreateAlignmentAssumption(DL, ArgVal, Align); AC->registerAssumption(cast<AssumeInst>(NewAsmp)); } } } /// Once we have cloned code over from a callee into the caller, /// update the specified callgraph to reflect the changes we made. /// Note that it's possible that not all code was copied over, so only /// some edges of the callgraph may remain. static void UpdateCallGraphAfterInlining(CallBase &CB, Function::iterator FirstNewBlock, ValueToValueMapTy &VMap, InlineFunctionInfo &IFI) { CallGraph &CG = *IFI.CG; const Function *Caller = CB.getCaller(); const Function *Callee = CB.getCalledFunction(); CallGraphNode *CalleeNode = CG[Callee]; CallGraphNode *CallerNode = CG[Caller]; // Since we inlined some uninlined call sites in the callee into the caller, // add edges from the caller to all of the callees of the callee. CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end(); // Consider the case where CalleeNode == CallerNode. CallGraphNode::CalledFunctionsVector CallCache; if (CalleeNode == CallerNode) { CallCache.assign(I, E); I = CallCache.begin(); E = CallCache.end(); } for (; I != E; ++I) { // Skip 'refererence' call records. if (!I->first) continue; const Value *OrigCall = *I->first; ValueToValueMapTy::iterator VMI = VMap.find(OrigCall); // Only copy the edge if the call was inlined! if (VMI == VMap.end() || VMI->second == nullptr) continue; // If the call was inlined, but then constant folded, there is no edge to // add. Check for this case. auto *NewCall = dyn_cast<CallBase>(VMI->second); if (!NewCall) continue; // We do not treat intrinsic calls like real function calls because we // expect them to become inline code; do not add an edge for an intrinsic. if (NewCall->getCalledFunction() && NewCall->getCalledFunction()->isIntrinsic()) continue; // Remember that this call site got inlined for the client of // InlineFunction. IFI.InlinedCalls.push_back(NewCall); // It's possible that inlining the callsite will cause it to go from an // indirect to a direct call by resolving a function pointer. If this // happens, set the callee of the new call site to a more precise // destination. This can also happen if the call graph node of the caller // was just unnecessarily imprecise. if (!I->second->getFunction()) if (Function *F = NewCall->getCalledFunction()) { // Indirect call site resolved to direct call. CallerNode->addCalledFunction(NewCall, CG[F]); continue; } CallerNode->addCalledFunction(NewCall, I->second); } // Update the call graph by deleting the edge from Callee to Caller. We must // do this after the loop above in case Caller and Callee are the same. CallerNode->removeCallEdgeFor(*cast<CallBase>(&CB)); } static void HandleByValArgumentInit(Type *ByValType, Value *Dst, Value *Src, Module *M, BasicBlock *InsertBlock, InlineFunctionInfo &IFI) { IRBuilder<> Builder(InsertBlock, InsertBlock->begin()); Value *Size = Builder.getInt64(M->getDataLayout().getTypeStoreSize(ByValType)); // Always generate a memcpy of alignment 1 here because we don't know // the alignment of the src pointer. Other optimizations can infer // better alignment. Builder.CreateMemCpy(Dst, /*DstAlign*/ Align(1), Src, /*SrcAlign*/ Align(1), Size); } /// When inlining a call site that has a byval argument, /// we have to make the implicit memcpy explicit by adding it. static Value *HandleByValArgument(Type *ByValType, Value *Arg, Instruction *TheCall, const Function *CalledFunc, InlineFunctionInfo &IFI, unsigned ByValAlignment) { assert(cast<PointerType>(Arg->getType()) ->isOpaqueOrPointeeTypeMatches(ByValType)); Function *Caller = TheCall->getFunction(); const DataLayout &DL = Caller->getParent()->getDataLayout(); // If the called function is readonly, then it could not mutate the caller's // copy of the byval'd memory. In this case, it is safe to elide the copy and // temporary. if (CalledFunc->onlyReadsMemory()) { // If the byval argument has a specified alignment that is greater than the // passed in pointer, then we either have to round up the input pointer or // give up on this transformation. if (ByValAlignment <= 1) // 0 = unspecified, 1 = no particular alignment. return Arg; AssumptionCache *AC = IFI.GetAssumptionCache ? &IFI.GetAssumptionCache(*Caller) : nullptr; // If the pointer is already known to be sufficiently aligned, or if we can // round it up to a larger alignment, then we don't need a temporary. if (getOrEnforceKnownAlignment(Arg, Align(ByValAlignment), DL, TheCall, AC) >= ByValAlignment) return Arg; // Otherwise, we have to make a memcpy to get a safe alignment. This is bad // for code quality, but rarely happens and is required for correctness. } // Create the alloca. If we have DataLayout, use nice alignment. Align Alignment(DL.getPrefTypeAlignment(ByValType)); // If the byval had an alignment specified, we *must* use at least that // alignment, as it is required by the byval argument (and uses of the // pointer inside the callee). Alignment = max(Alignment, MaybeAlign(ByValAlignment)); BasicBlock *NewCtx = GetDetachedCtx(TheCall->getParent()); Value *NewAlloca = new AllocaInst(ByValType, DL.getAllocaAddrSpace(), nullptr, Alignment, Arg->getName(), &*NewCtx->begin()); IFI.StaticAllocas.push_back(cast<AllocaInst>(NewAlloca)); // Uses of the argument in the function should use our new alloca // instead. return NewAlloca; } // Check whether this Value is used by a lifetime intrinsic. static bool isUsedByLifetimeMarker(Value *V) { for (User *U : V->users()) if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) if (II->isLifetimeStartOrEnd()) return true; return false; } // Check whether the given alloca already has // lifetime.start or lifetime.end intrinsics. static bool hasLifetimeMarkers(AllocaInst *AI) { Type *Ty = AI->getType(); Type *Int8PtrTy = Type::getInt8PtrTy(Ty->getContext(), Ty->getPointerAddressSpace()); if (Ty == Int8PtrTy) return isUsedByLifetimeMarker(AI); // Do a scan to find all the casts to i8*. for (User *U : AI->users()) { if (U->getType() != Int8PtrTy) continue; if (U->stripPointerCasts() != AI) continue; if (isUsedByLifetimeMarker(U)) return true; } return false; } /// Return the result of AI->isStaticAlloca() if AI were moved to the entry /// block. Allocas used in inalloca calls and allocas of dynamic array size /// cannot be static. static bool allocaWouldBeStaticInEntry(const AllocaInst *AI ) { return isa<Constant>(AI->getArraySize()) && !AI->isUsedWithInAlloca(); } /// Returns a DebugLoc for a new DILocation which is a clone of \p OrigDL /// inlined at \p InlinedAt. \p IANodes is an inlined-at cache. static DebugLoc inlineDebugLoc(DebugLoc OrigDL, DILocation *InlinedAt, LLVMContext &Ctx, DenseMap<const MDNode *, MDNode *> &IANodes) { auto IA = DebugLoc::appendInlinedAt(OrigDL, InlinedAt, Ctx, IANodes); return DILocation::get(Ctx, OrigDL.getLine(), OrigDL.getCol(), OrigDL.getScope(), IA); } /// Update inlined instructions' line numbers to /// to encode location where these instructions are inlined. static void fixupLineNumbers(Function *Fn, Function::iterator FI, Instruction *TheCall, bool CalleeHasDebugInfo) { const DebugLoc &TheCallDL = TheCall->getDebugLoc(); if (!TheCallDL) return; auto &Ctx = Fn->getContext(); DILocation *InlinedAtNode = TheCallDL; // Create a unique call site, not to be confused with any other call from the // same location. InlinedAtNode = DILocation::getDistinct( Ctx, InlinedAtNode->getLine(), InlinedAtNode->getColumn(), InlinedAtNode->getScope(), InlinedAtNode->getInlinedAt()); // Cache the inlined-at nodes as they're built so they are reused, without // this every instruction's inlined-at chain would become distinct from each // other. DenseMap<const MDNode *, MDNode *> IANodes; // Check if we are not generating inline line tables and want to use // the call site location instead. bool NoInlineLineTables = Fn->hasFnAttribute("no-inline-line-tables"); for (; FI != Fn->end(); ++FI) { for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ++BI) { // Loop metadata needs to be updated so that the start and end locs // reference inlined-at locations. auto updateLoopInfoLoc = [&Ctx, &InlinedAtNode, &IANodes](Metadata *MD) -> Metadata * { if (auto *Loc = dyn_cast_or_null<DILocation>(MD)) return inlineDebugLoc(Loc, InlinedAtNode, Ctx, IANodes).get(); return MD; }; updateLoopMetadataDebugLocations(*BI, updateLoopInfoLoc); if (!NoInlineLineTables) if (DebugLoc DL = BI->getDebugLoc()) { DebugLoc IDL = inlineDebugLoc(DL, InlinedAtNode, BI->getContext(), IANodes); BI->setDebugLoc(IDL); continue; } if (CalleeHasDebugInfo && !NoInlineLineTables) continue; // If the inlined instruction has no line number, or if inline info // is not being generated, make it look as if it originates from the call // location. This is important for ((__always_inline, __nodebug__)) // functions which must use caller location for all instructions in their // function body. // Don't update static allocas, as they may get moved later. if (auto *AI = dyn_cast<AllocaInst>(BI)) if (allocaWouldBeStaticInEntry(AI)) continue; BI->setDebugLoc(TheCallDL); } // Remove debug info intrinsics if we're not keeping inline info. if (NoInlineLineTables) { BasicBlock::iterator BI = FI->begin(); while (BI != FI->end()) { if (isa<DbgInfoIntrinsic>(BI)) { BI = BI->eraseFromParent(); continue; } ++BI; } } } } /// Update the block frequencies of the caller after a callee has been inlined. /// /// Each block cloned into the caller has its block frequency scaled by the /// ratio of CallSiteFreq/CalleeEntryFreq. This ensures that the cloned copy of /// callee's entry block gets the same frequency as the callsite block and the /// relative frequencies of all cloned blocks remain the same after cloning. static void updateCallerBFI(BasicBlock *CallSiteBlock, const ValueToValueMapTy &VMap, BlockFrequencyInfo *CallerBFI, BlockFrequencyInfo *CalleeBFI, const BasicBlock &CalleeEntryBlock) { SmallPtrSet<BasicBlock *, 16> ClonedBBs; for (auto Entry : VMap) { if (!isa<BasicBlock>(Entry.first) || !Entry.second) continue; auto *OrigBB = cast<BasicBlock>(Entry.first); auto *ClonedBB = cast<BasicBlock>(Entry.second); uint64_t Freq = CalleeBFI->getBlockFreq(OrigBB).getFrequency(); if (!ClonedBBs.insert(ClonedBB).second) { // Multiple blocks in the callee might get mapped to one cloned block in // the caller since we prune the callee as we clone it. When that happens, // we want to use the maximum among the original blocks' frequencies. uint64_t NewFreq = CallerBFI->getBlockFreq(ClonedBB).getFrequency(); if (NewFreq > Freq) Freq = NewFreq; } CallerBFI->setBlockFreq(ClonedBB, Freq); } BasicBlock *EntryClone = cast<BasicBlock>(VMap.lookup(&CalleeEntryBlock)); CallerBFI->setBlockFreqAndScale( EntryClone, CallerBFI->getBlockFreq(CallSiteBlock).getFrequency(), ClonedBBs); } /// Update the branch metadata for cloned call instructions. static void updateCallProfile(Function *Callee, const ValueToValueMapTy &VMap, const ProfileCount &CalleeEntryCount, const CallBase &TheCall, ProfileSummaryInfo *PSI, BlockFrequencyInfo *CallerBFI) { if (CalleeEntryCount.isSynthetic() || CalleeEntryCount.getCount() < 1) return; auto CallSiteCount = PSI ? PSI->getProfileCount(TheCall, CallerBFI) : None; int64_t CallCount = std::min(CallSiteCount.getValueOr(0), CalleeEntryCount.getCount()); updateProfileCallee(Callee, -CallCount, &VMap); } void llvm::updateProfileCallee( Function *Callee, int64_t EntryDelta, const ValueMap<const Value *, WeakTrackingVH> *VMap) { auto CalleeCount = Callee->getEntryCount(); if (!CalleeCount.hasValue()) return; const uint64_t PriorEntryCount = CalleeCount->getCount(); // Since CallSiteCount is an estimate, it could exceed the original callee // count and has to be set to 0 so guard against underflow. const uint64_t NewEntryCount = (EntryDelta < 0 && static_cast<uint64_t>(-EntryDelta) > PriorEntryCount) ? 0 : PriorEntryCount + EntryDelta; // During inlining ? if (VMap) { uint64_t CloneEntryCount = PriorEntryCount - NewEntryCount; for (auto Entry : *VMap) if (isa<CallInst>(Entry.first)) if (auto *CI = dyn_cast_or_null<CallInst>(Entry.second)) CI->updateProfWeight(CloneEntryCount, PriorEntryCount); } if (EntryDelta) { Callee->setEntryCount(NewEntryCount); for (BasicBlock &BB : *Callee) // No need to update the callsite if it is pruned during inlining. if (!VMap || VMap->count(&BB)) for (Instruction &I : BB) if (CallInst *CI = dyn_cast<CallInst>(&I)) CI->updateProfWeight(NewEntryCount, PriorEntryCount); } } /// An operand bundle "clang.arc.attachedcall" on a call indicates the call /// result is implicitly consumed by a call to retainRV or claimRV immediately /// after the call. This function inlines the retainRV/claimRV calls. /// /// There are three cases to consider: /// /// 1. If there is a call to autoreleaseRV that takes a pointer to the returned /// object in the callee return block, the autoreleaseRV call and the /// retainRV/claimRV call in the caller cancel out. If the call in the caller /// is a claimRV call, a call to objc_release is emitted. /// /// 2. If there is a call in the callee return block that doesn't have operand /// bundle "clang.arc.attachedcall", the operand bundle on the original call /// is transferred to the call in the callee. /// /// 3. Otherwise, a call to objc_retain is inserted if the call in the caller is /// a retainRV call. static void inlineRetainOrClaimRVCalls(CallBase &CB, objcarc::ARCInstKind RVCallKind, const SmallVectorImpl<ReturnInst *> &Returns) { Module *Mod = CB.getModule(); assert(objcarc::isRetainOrClaimRV(RVCallKind) && "unexpected ARC function"); bool IsRetainRV = RVCallKind == objcarc::ARCInstKind::RetainRV, IsUnsafeClaimRV = !IsRetainRV; for (auto *RI : Returns) { Value *RetOpnd = objcarc::GetRCIdentityRoot(RI->getOperand(0)); bool InsertRetainCall = IsRetainRV; IRBuilder<> Builder(RI->getContext()); // Walk backwards through the basic block looking for either a matching // autoreleaseRV call or an unannotated call. auto InstRange = llvm::make_range(++(RI->getIterator().getReverse()), RI->getParent()->rend()); for (Instruction &I : llvm::make_early_inc_range(InstRange)) { // Ignore casts. if (isa<CastInst>(I)) continue; if (auto *II = dyn_cast<IntrinsicInst>(&I)) { if (II->getIntrinsicID() != Intrinsic::objc_autoreleaseReturnValue || !II->hasNUses(0) || objcarc::GetRCIdentityRoot(II->getOperand(0)) != RetOpnd) break; // If we've found a matching authoreleaseRV call: // - If claimRV is attached to the call, insert a call to objc_release // and erase the autoreleaseRV call. // - If retainRV is attached to the call, just erase the autoreleaseRV // call. if (IsUnsafeClaimRV) { Builder.SetInsertPoint(II); Function *IFn = Intrinsic::getDeclaration(Mod, Intrinsic::objc_release); Value *BC = Builder.CreateBitCast(RetOpnd, IFn->getArg(0)->getType()); Builder.CreateCall(IFn, BC, ""); } II->eraseFromParent(); InsertRetainCall = false; break; } auto *CI = dyn_cast<CallInst>(&I); if (!CI) break; if (objcarc::GetRCIdentityRoot(CI) != RetOpnd || objcarc::hasAttachedCallOpBundle(CI)) break; // If we've found an unannotated call that defines RetOpnd, add a // "clang.arc.attachedcall" operand bundle. Value *BundleArgs[] = {*objcarc::getAttachedARCFunction(&CB)}; OperandBundleDef OB("clang.arc.attachedcall", BundleArgs); auto *NewCall = CallBase::addOperandBundle( CI, LLVMContext::OB_clang_arc_attachedcall, OB, CI); NewCall->copyMetadata(*CI); CI->replaceAllUsesWith(NewCall); CI->eraseFromParent(); InsertRetainCall = false; break; } if (InsertRetainCall) { // The retainRV is attached to the call and we've failed to find a // matching autoreleaseRV or an annotated call in the callee. Emit a call // to objc_retain. Builder.SetInsertPoint(RI); Function *IFn = Intrinsic::getDeclaration(Mod, Intrinsic::objc_retain); Value *BC = Builder.CreateBitCast(RetOpnd, IFn->getArg(0)->getType()); Builder.CreateCall(IFn, BC, ""); } } } static bool isTaskFrameCreate(const Instruction &I) { if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I)) return Intrinsic::taskframe_create == II->getIntrinsicID(); return false; } static BasicBlock *SplitResume(ResumeInst *RI, Intrinsic::ID TermFunc, Value *Token, BasicBlock *Unreachable) { Value *RIValue = RI->getValue(); BasicBlock *OldBB = RI->getParent(); Module *M = OldBB->getModule(); // Split the resume block at the resume. BasicBlock *NewBB = SplitBlock(OldBB, RI); // Invoke the specified terminator function at the end of the old block. InvokeInst *TermFuncInvoke = InvokeInst::Create( Intrinsic::getDeclaration(M, TermFunc, { RIValue->getType() }), Unreachable, NewBB, { Token, RIValue }); ReplaceInstWithInst(OldBB->getTerminator(), TermFuncInvoke); // Insert a landingpad at the start of the new block. IRBuilder<> Builder(RI); LandingPadInst *LPad = Builder.CreateLandingPad(RIValue->getType(), 0, RIValue->getName()); LPad->setCleanup(true); // Replace the argument of the resume with the value of the new landingpad. RI->setOperand(0, LPad); return NewBB; } static void HandleInlinedResumeInTask(BasicBlock *EntryBlock, BasicBlock *Ctx, ResumeInst *Resume, BasicBlock *Unreachable) { // If the DetachedBlock has no predecessor, then it is the entry of the // function. There's nothing to do in this case, so simply return. if (pred_empty(EntryBlock) && EntryBlock == Ctx) return; BasicBlock *Parent = (EntryBlock != Ctx ? Ctx : EntryBlock->getSinglePredecessor()); Module *M = Parent->getModule(); if (isTaskFrameCreate(EntryBlock->front())) { Value *TaskFrame = &EntryBlock->front(); if (InvokeInst *TFResume = getTaskFrameResume(TaskFrame)) { BasicBlock *ResumeDest = TFResume->getUnwindDest(); // Replace the resume with a taskframe.resume, whose unwind destination // matches the unwind destination of the taskframe. InvokeInst *NewTFResume = InvokeInst::Create( Intrinsic::getDeclaration(M, Intrinsic::taskframe_resume, {Resume->getValue()->getType()}), Unreachable, ResumeDest, {TaskFrame, Resume->getValue()}); ReplaceInstWithInst(Resume, NewTFResume); // Update PHI nodes in ResumeDest. for (PHINode &PN : ResumeDest->phis()) // Add an entry to the PHI node for the new predecessor block, // NewTFResume->getParent(), using the same value as that from // TFResume->getParent(). PN.addIncoming(PN.getIncomingValueForBlock(TFResume->getParent()), NewTFResume->getParent()); // No need to continue up the stack of contexts. return; } // Otherwise, split the resume to insert a novel invocation of // taskframe.resume for this taskframe. SplitResume(Resume, Intrinsic::taskframe_resume, TaskFrame, Unreachable); // Recursively handle parent contexts. if (EntryBlock != Ctx) HandleInlinedResumeInTask(Ctx, Ctx, Resume, Unreachable); else { BasicBlock *NewCtx = GetDetachedCtx(Parent); HandleInlinedResumeInTask(NewCtx, NewCtx, Resume, Unreachable); } } else { assert(EntryBlock == Ctx && "Unexpected context for detached entry block."); DetachInst *DI = cast<DetachInst>(Parent->getTerminator()); Value *SyncRegion = DI->getSyncRegion(); if (DI->hasUnwindDest()) { // Replace the resume with a detached.rethrow, whose unwind destination // matches the unwind destination of the detach. BasicBlock *DetUnwind = DI->getUnwindDest(); InvokeInst *NewDetRethrow = InvokeInst::Create( Intrinsic::getDeclaration(M, Intrinsic::detached_rethrow, {Resume->getValue()->getType()}), Unreachable, DetUnwind, {SyncRegion, Resume->getValue()}); ReplaceInstWithInst(Resume, NewDetRethrow); // Update PHI nodes in unwind dest. for (PHINode &PN : DetUnwind->phis()) // Add an entry to the PHI node for the new predecessor block, // NewDetRethrow->getParent(), using the same value as that from Parent. PN.addIncoming(PN.getIncomingValueForBlock(Parent), NewDetRethrow->getParent()); // No need to continue up the stack of contexts. return; } // Insert an invocation of detached.rethrow before the resume. BasicBlock *NewBB = SplitResume(Resume, Intrinsic::detached_rethrow, SyncRegion, Unreachable); // Add NewBB as the unwind destination of DI. ReplaceInstWithInst(DI, DetachInst::Create(EntryBlock, DI->getContinue(), NewBB, SyncRegion)); // Recursively handle parent contexts. BasicBlock *NewCtx = GetDetachedCtx(Parent); HandleInlinedResumeInTask(NewCtx, NewCtx, Resume, Unreachable); } } /// This function inlines the called function into the basic block of the /// caller. This returns false if it is not possible to inline this call. /// The program is still in a well defined state if this occurs though. /// /// Note that this only does one level of inlining. For example, if the /// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now /// exists in the instruction stream. Similarly this will inline a recursive /// function by one level. llvm::InlineResult llvm::InlineFunction(CallBase &CB, InlineFunctionInfo &IFI, AAResults *CalleeAAR, bool InsertLifetime, Function *ForwardVarArgsTo) { assert(CB.getParent() && CB.getFunction() && "Instruction not in function!"); // FIXME: we don't inline callbr yet. if (isa<CallBrInst>(CB)) return InlineResult::failure("We don't inline callbr yet."); // If IFI has any state in it, zap it before we fill it in. IFI.reset(); Function *CalledFunc = CB.getCalledFunction(); if (!CalledFunc || // Can't inline external function or indirect CalledFunc->isDeclaration()) // call! return InlineResult::failure("external or indirect"); // The inliner does not know how to inline through calls with operand bundles // in general ... if (CB.hasOperandBundles()) { for (int i = 0, e = CB.getNumOperandBundles(); i != e; ++i) { uint32_t Tag = CB.getOperandBundleAt(i).getTagID(); // ... but it knows how to inline through "deopt" operand bundles ... if (Tag == LLVMContext::OB_deopt) continue; // ... and "funclet" operand bundles. if (Tag == LLVMContext::OB_funclet) continue; if (Tag == LLVMContext::OB_clang_arc_attachedcall) continue; return InlineResult::failure("unsupported operand bundle"); } } // If the call to the callee cannot throw, set the 'nounwind' flag on any // calls that we inline. bool MarkNoUnwind = CB.doesNotThrow(); BasicBlock *OrigBB = CB.getParent(); Function *Caller = OrigBB->getParent(); // Canonicalize the caller by splitting blocks containing taskframe.create // intrinsics. if (splitTaskFrameCreateBlocks(*Caller)) OrigBB = CB.getParent(); // GC poses two hazards to inlining, which only occur when the callee has GC: // 1. If the caller has no GC, then the callee's GC must be propagated to the // caller. // 2. If the caller has a differing GC, it is invalid to inline. if (CalledFunc->hasGC()) { if (!Caller->hasGC()) Caller->setGC(CalledFunc->getGC()); else if (CalledFunc->getGC() != Caller->getGC()) return InlineResult::failure("incompatible GC"); } // Get the personality function from the callee if it contains a landing pad. Constant *CalledPersonality = CalledFunc->hasPersonalityFn() ? CalledFunc->getPersonalityFn()->stripPointerCasts() : nullptr; // Find the personality function used by the landing pads of the caller. If it // exists, then check to see that it matches the personality function used in // the callee. Constant *CallerPersonality = Caller->hasPersonalityFn() ? Caller->getPersonalityFn()->stripPointerCasts() : nullptr; if (CalledPersonality) { Triple T(Caller->getParent()->getTargetTriple()); if (!CallerPersonality) Caller->setPersonalityFn(CalledPersonality); else if (CalledPersonality != CallerPersonality) { // See if we want to replace CallerPersonality with the CalledPersonality, // because CalledPersonality is a proper superset. if (classifyEHPersonality(CallerPersonality) == getDefaultEHPersonality(T)) // The caller is using the default personality function. We assume // CalledPersonality is a superset. Caller->setPersonalityFn(CalledPersonality); else if (classifyEHPersonality(CalledPersonality) == EHPersonality::Cilk_CXX && classifyEHPersonality(CallerPersonality) == EHPersonality::GNU_CXX) // The Cilk personality is a superset of the caller's. Caller->setPersonalityFn(CalledPersonality); // If the personality functions match, then we can perform the // inlining. Otherwise, we can't inline. // TODO: This isn't 100% true. Some personality functions are proper // supersets of others and can be used in place of the other. else { EHPersonality CalledEHPersonality = classifyEHPersonality(CalledPersonality); // We can inline if: // - CalledPersonality is the default personality, or // - CallerPersonality is the Cilk personality and CalledPersonality is // GNU_CXX. // Otherwise, declare that we can't inline. if (CalledEHPersonality != getDefaultEHPersonality(T) && (classifyEHPersonality(CallerPersonality) != EHPersonality::Cilk_CXX || CalledEHPersonality != EHPersonality::GNU_CXX)) return InlineResult::failure("incompatible personality"); } } } // We need to figure out which funclet the callsite was in so that we may // properly nest the callee. Instruction *CallSiteEHPad = nullptr; if (CallerPersonality) { EHPersonality Personality = classifyEHPersonality(CallerPersonality); if (isScopedEHPersonality(Personality)) { Optional<OperandBundleUse> ParentFunclet = CB.getOperandBundle(LLVMContext::OB_funclet); if (ParentFunclet) CallSiteEHPad = cast<FuncletPadInst>(ParentFunclet->Inputs.front()); // OK, the inlining site is legal. What about the target function? if (CallSiteEHPad) { if (Personality == EHPersonality::MSVC_CXX) { // The MSVC personality cannot tolerate catches getting inlined into // cleanup funclets. if (isa<CleanupPadInst>(CallSiteEHPad)) { // Ok, the call site is within a cleanuppad. Let's check the callee // for catchpads. for (const BasicBlock &CalledBB : *CalledFunc) { if (isa<CatchSwitchInst>(CalledBB.getFirstNonPHI())) return InlineResult::failure("catch in cleanup funclet"); } } } else if (isAsynchronousEHPersonality(Personality)) { // SEH is even less tolerant, there may not be any sort of exceptional // funclet in the callee. for (const BasicBlock &CalledBB : *CalledFunc) { if (CalledBB.isEHPad()) return InlineResult::failure("SEH in cleanup funclet"); } } } } } // Determine if we are dealing with a call in an EHPad which does not unwind // to caller. bool EHPadForCallUnwindsLocally = false; if (CallSiteEHPad && isa<CallInst>(CB)) { UnwindDestMemoTy FuncletUnwindMap; Value *CallSiteUnwindDestToken = getUnwindDestToken(CallSiteEHPad, FuncletUnwindMap); EHPadForCallUnwindsLocally = CallSiteUnwindDestToken && !isa<ConstantTokenNone>(CallSiteUnwindDestToken); } // Get the entry block of the detached context into which we're inlining. If // we move allocas from the inlined code, we must move them to this block. BasicBlock *DetachedCtxEntryBlock; { DetachedCtxEntryBlock = GetDetachedCtx(OrigBB); assert(((&(Caller->getEntryBlock()) == DetachedCtxEntryBlock) || pred_empty(DetachedCtxEntryBlock) || DetachedCtxEntryBlock->getSinglePredecessor()) && "Entry block of detached context has multiple predecessors."); } bool MayBeUnsyncedAtCall = mayBeUnsynced(OrigBB); // Get an iterator to the last basic block in the function, which will have // the new function inlined after it. Function::iterator LastBlock = --Caller->end(); // Make sure to capture all of the return instructions from the cloned // function. SmallVector<ReturnInst*, 8> Returns; SmallVector<ResumeInst*, 8> Resumes; ClonedCodeInfo InlinedFunctionInfo; Function::iterator FirstNewBlock; { // Scope to destroy VMap after cloning. ValueToValueMapTy VMap; struct ByValInit { Value *Dst; Value *Src; Type *Ty; }; // Keep a list of pair (dst, src) to emit byval initializations. SmallVector<ByValInit, 4> ByValInits; // When inlining a function that contains noalias scope metadata, // this metadata needs to be cloned so that the inlined blocks // have different "unique scopes" at every call site. // Track the metadata that must be cloned. Do this before other changes to // the function, so that we do not get in trouble when inlining caller == // callee. ScopedAliasMetadataDeepCloner SAMetadataCloner(CB.getCalledFunction()); auto &DL = Caller->getParent()->getDataLayout(); // Calculate the vector of arguments to pass into the function cloner, which // matches up the formal to the actual argument values. auto AI = CB.arg_begin(); unsigned ArgNo = 0; for (Function::arg_iterator I = CalledFunc->arg_begin(), E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) { Value *ActualArg = *AI; // When byval arguments actually inlined, we need to make the copy implied // by them explicit. However, we don't do this if the callee is readonly // or readnone, because the copy would be unneeded: the callee doesn't // modify the struct. if (CB.isByValArgument(ArgNo)) { ActualArg = HandleByValArgument(CB.getParamByValType(ArgNo), ActualArg, &CB, CalledFunc, IFI, CalledFunc->getParamAlignment(ArgNo)); if (ActualArg != *AI) ByValInits.push_back( {ActualArg, (Value *)*AI, CB.getParamByValType(ArgNo)}); } VMap[&*I] = ActualArg; } // TODO: Remove this when users have been updated to the assume bundles. // Add alignment assumptions if necessary. We do this before the inlined // instructions are actually cloned into the caller so that we can easily // check what will be known at the start of the inlined code. AddAlignmentAssumptions(CB, IFI); AssumptionCache *AC = IFI.GetAssumptionCache ? &IFI.GetAssumptionCache(*Caller) : nullptr; /// Preserve all attributes on of the call and its parameters. salvageKnowledge(&CB, AC); // We want the inliner to prune the code as it copies. We would LOVE to // have no dead or constant instructions leftover after inlining occurs // (which can happen, e.g., because an argument was constant), but we'll be // happy with whatever the cloner can do. CloneAndPruneFunctionInto(Caller, CalledFunc, VMap, /*ModuleLevelChanges=*/false, Returns, Resumes, ".i", &InlinedFunctionInfo); // Remember the first block that is newly cloned over. FirstNewBlock = LastBlock; ++FirstNewBlock; // Insert retainRV/clainRV runtime calls. objcarc::ARCInstKind RVCallKind = objcarc::getAttachedARCFunctionKind(&CB); if (RVCallKind != objcarc::ARCInstKind::None) inlineRetainOrClaimRVCalls(CB, RVCallKind, Returns); // Updated caller/callee profiles only when requested. For sample loader // inlining, the context-sensitive inlinee profile doesn't need to be // subtracted from callee profile, and the inlined clone also doesn't need // to be scaled based on call site count. if (IFI.UpdateProfile) { if (IFI.CallerBFI != nullptr && IFI.CalleeBFI != nullptr) // Update the BFI of blocks cloned into the caller. updateCallerBFI(OrigBB, VMap, IFI.CallerBFI, IFI.CalleeBFI, CalledFunc->front()); if (auto Profile = CalledFunc->getEntryCount()) updateCallProfile(CalledFunc, VMap, *Profile, CB, IFI.PSI, IFI.CallerBFI); } // Inject byval arguments initialization. for (ByValInit &Init : ByValInits) HandleByValArgumentInit(Init.Ty, Init.Dst, Init.Src, Caller->getParent(), &*FirstNewBlock, IFI); Optional<OperandBundleUse> ParentDeopt = CB.getOperandBundle(LLVMContext::OB_deopt); if (ParentDeopt) { SmallVector<OperandBundleDef, 2> OpDefs; for (auto &VH : InlinedFunctionInfo.OperandBundleCallSites) { CallBase *ICS = dyn_cast_or_null<CallBase>(VH); if (!ICS) continue; // instruction was DCE'd or RAUW'ed to undef OpDefs.clear(); OpDefs.reserve(ICS->getNumOperandBundles()); for (unsigned COBi = 0, COBe = ICS->getNumOperandBundles(); COBi < COBe; ++COBi) { auto ChildOB = ICS->getOperandBundleAt(COBi); if (ChildOB.getTagID() != LLVMContext::OB_deopt) { // If the inlined call has other operand bundles, let them be OpDefs.emplace_back(ChildOB); continue; } // It may be useful to separate this logic (of handling operand // bundles) out to a separate "policy" component if this gets crowded. // Prepend the parent's deoptimization continuation to the newly // inlined call's deoptimization continuation. std::vector<Value *> MergedDeoptArgs; MergedDeoptArgs.reserve(ParentDeopt->Inputs.size() + ChildOB.Inputs.size()); llvm::append_range(MergedDeoptArgs, ParentDeopt->Inputs); llvm::append_range(MergedDeoptArgs, ChildOB.Inputs); OpDefs.emplace_back("deopt", std::move(MergedDeoptArgs)); } Instruction *NewI = CallBase::Create(ICS, OpDefs, ICS); // Note: the RAUW does the appropriate fixup in VMap, so we need to do // this even if the call returns void. ICS->replaceAllUsesWith(NewI); VH = nullptr; ICS->eraseFromParent(); } } // Update the callgraph if requested. if (IFI.CG) UpdateCallGraphAfterInlining(CB, FirstNewBlock, VMap, IFI); // For 'nodebug' functions, the associated DISubprogram is always null. // Conservatively avoid propagating the callsite debug location to // instructions inlined from a function whose DISubprogram is not null. fixupLineNumbers(Caller, FirstNewBlock, &CB, CalledFunc->getSubprogram() != nullptr); // Now clone the inlined noalias scope metadata. SAMetadataCloner.clone(); SAMetadataCloner.remap(FirstNewBlock, Caller->end()); // Add noalias metadata if necessary. AddAliasScopeMetadata(CB, VMap, DL, CalleeAAR, InlinedFunctionInfo); // Clone return attributes on the callsite into the calls within the inlined // function which feed into its return value. AddReturnAttributes(CB, VMap); // Propagate metadata on the callsite if necessary. PropagateCallSiteMetadata(CB, FirstNewBlock, Caller->end()); // Register any cloned assumptions. if (IFI.GetAssumptionCache) for (BasicBlock &NewBlock : make_range(FirstNewBlock->getIterator(), Caller->end())) for (Instruction &I : NewBlock) if (auto *II = dyn_cast<AssumeInst>(&I)) IFI.GetAssumptionCache(*Caller).registerAssumption(II); } // If there are any alloca instructions in the block that used to be the entry // block for the callee, move them to the entry block of the caller. First // calculate which instruction they should be inserted before. We insert the // instructions at the end of the current alloca list. { BasicBlock::iterator InsertPoint = DetachedCtxEntryBlock->begin(); if (isTaskFrameCreate(*InsertPoint)) InsertPoint++; for (BasicBlock::iterator I = FirstNewBlock->begin(), E = FirstNewBlock->end(); I != E; ) { AllocaInst *AI = dyn_cast<AllocaInst>(I++); if (!AI) continue; // If the alloca is now dead, remove it. This often occurs due to code // specialization. if (AI->use_empty()) { AI->eraseFromParent(); continue; } if (!allocaWouldBeStaticInEntry(AI)) continue; // Keep track of the static allocas that we inline into the caller. IFI.StaticAllocas.push_back(AI); // Scan for the block of allocas that we can move over, and move them // all at once. while (isa<AllocaInst>(I) && !cast<AllocaInst>(I)->use_empty() && allocaWouldBeStaticInEntry(cast<AllocaInst>(I))) { IFI.StaticAllocas.push_back(cast<AllocaInst>(I)); ++I; } // Transfer all of the allocas over in a block. Using splice means // that the instructions aren't removed from the symbol table, then // reinserted. DetachedCtxEntryBlock->getInstList().splice( InsertPoint, FirstNewBlock->getInstList(), AI->getIterator(), I); } // Move any syncregion_start's into the entry basic block. Avoid moving // syncregions if we'll need to insert a taskframe for this inlined call. if (InlinedFunctionInfo.ContainsDetach && !InlinedFunctionInfo.ContainsDynamicAllocas && !MayBeUnsyncedAtCall) { for (BasicBlock::iterator I = FirstNewBlock->begin(), E = FirstNewBlock->end(); I != E; ) { IntrinsicInst *II = dyn_cast<IntrinsicInst>(I++); if (!II) continue; if (Intrinsic::syncregion_start != II->getIntrinsicID()) continue; while (isa<IntrinsicInst>(I) && Intrinsic::syncregion_start == cast<IntrinsicInst>(I)->getIntrinsicID()) ++I; DetachedCtxEntryBlock->getInstList().splice( InsertPoint, FirstNewBlock->getInstList(), II->getIterator(), I); } } } SmallVector<Value*,4> VarArgsToForward; SmallVector<AttributeSet, 4> VarArgsAttrs; for (unsigned i = CalledFunc->getFunctionType()->getNumParams(); i < CB.arg_size(); i++) { VarArgsToForward.push_back(CB.getArgOperand(i)); VarArgsAttrs.push_back(CB.getAttributes().getParamAttrs(i)); } bool InlinedMustTailCalls = false, InlinedDeoptimizeCalls = false; if (InlinedFunctionInfo.ContainsCalls) { CallInst::TailCallKind CallSiteTailKind = CallInst::TCK_None; if (CallInst *CI = dyn_cast<CallInst>(&CB)) CallSiteTailKind = CI->getTailCallKind(); // For inlining purposes, the "notail" marker is the same as no marker. if (CallSiteTailKind == CallInst::TCK_NoTail) CallSiteTailKind = CallInst::TCK_None; for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E; ++BB) { for (Instruction &I : llvm::make_early_inc_range(*BB)) { CallInst *CI = dyn_cast<CallInst>(&I); if (!CI) continue; // Forward varargs from inlined call site to calls to the // ForwardVarArgsTo function, if requested, and to musttail calls. if (!VarArgsToForward.empty() && ((ForwardVarArgsTo && CI->getCalledFunction() == ForwardVarArgsTo) || CI->isMustTailCall())) { // Collect attributes for non-vararg parameters. AttributeList Attrs = CI->getAttributes(); SmallVector<AttributeSet, 8> ArgAttrs; if (!Attrs.isEmpty() || !VarArgsAttrs.empty()) { for (unsigned ArgNo = 0; ArgNo < CI->getFunctionType()->getNumParams(); ++ArgNo) ArgAttrs.push_back(Attrs.getParamAttrs(ArgNo)); } // Add VarArg attributes. ArgAttrs.append(VarArgsAttrs.begin(), VarArgsAttrs.end()); Attrs = AttributeList::get(CI->getContext(), Attrs.getFnAttrs(), Attrs.getRetAttrs(), ArgAttrs); // Add VarArgs to existing parameters. SmallVector<Value *, 6> Params(CI->args()); Params.append(VarArgsToForward.begin(), VarArgsToForward.end()); CallInst *NewCI = CallInst::Create( CI->getFunctionType(), CI->getCalledOperand(), Params, "", CI); NewCI->setDebugLoc(CI->getDebugLoc()); NewCI->setAttributes(Attrs); NewCI->setCallingConv(CI->getCallingConv()); CI->replaceAllUsesWith(NewCI); CI->eraseFromParent(); CI = NewCI; } if (Function *F = CI->getCalledFunction()) InlinedDeoptimizeCalls |= F->getIntrinsicID() == Intrinsic::experimental_deoptimize; // We need to reduce the strength of any inlined tail calls. For // musttail, we have to avoid introducing potential unbounded stack // growth. For example, if functions 'f' and 'g' are mutually recursive // with musttail, we can inline 'g' into 'f' so long as we preserve // musttail on the cloned call to 'f'. If either the inlined call site // or the cloned call site is *not* musttail, the program already has // one frame of stack growth, so it's safe to remove musttail. Here is // a table of example transformations: // // f -> musttail g -> musttail f ==> f -> musttail f // f -> musttail g -> tail f ==> f -> tail f // f -> g -> musttail f ==> f -> f // f -> g -> tail f ==> f -> f // // Inlined notail calls should remain notail calls. CallInst::TailCallKind ChildTCK = CI->getTailCallKind(); if (ChildTCK != CallInst::TCK_NoTail) ChildTCK = std::min(CallSiteTailKind, ChildTCK); CI->setTailCallKind(ChildTCK); InlinedMustTailCalls |= CI->isMustTailCall(); // Calls inlined through a 'nounwind' call site should be marked // 'nounwind'. if (MarkNoUnwind) CI->setDoesNotThrow(); } } } // Leave lifetime markers for the static alloca's, scoping them to the // function we just inlined. // We need to insert lifetime intrinsics even at O0 to avoid invalid // access caused by multithreaded coroutines. The check // `Caller->isPresplitCoroutine()` would affect AlwaysInliner at O0 only. if ((InsertLifetime || Caller->isPresplitCoroutine()) && !IFI.StaticAllocas.empty()) { IRBuilder<> builder(&FirstNewBlock->front()); for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) { AllocaInst *AI = IFI.StaticAllocas[ai]; // Don't mark swifterror allocas. They can't have bitcast uses. if (AI->isSwiftError()) continue; // If the alloca is already scoped to something smaller than the whole // function then there's no need to add redundant, less accurate markers. if (hasLifetimeMarkers(AI)) continue; // Try to determine the size of the allocation. ConstantInt *AllocaSize = nullptr; if (ConstantInt *AIArraySize = dyn_cast<ConstantInt>(AI->getArraySize())) { auto &DL = Caller->getParent()->getDataLayout(); Type *AllocaType = AI->getAllocatedType(); TypeSize AllocaTypeSize = DL.getTypeAllocSize(AllocaType); uint64_t AllocaArraySize = AIArraySize->getLimitedValue(); // Don't add markers for zero-sized allocas. if (AllocaArraySize == 0) continue; // Check that array size doesn't saturate uint64_t and doesn't // overflow when it's multiplied by type size. if (!AllocaTypeSize.isScalable() && AllocaArraySize != std::numeric_limits<uint64_t>::max() && std::numeric_limits<uint64_t>::max() / AllocaArraySize >= AllocaTypeSize.getFixedSize()) { AllocaSize = ConstantInt::get(Type::getInt64Ty(AI->getContext()), AllocaArraySize * AllocaTypeSize); } } builder.CreateLifetimeStart(AI, AllocaSize); for (ReturnInst *RI : Returns) { // Don't insert llvm.lifetime.end calls between a musttail or deoptimize // call and a return. The return kills all local allocas. if (InlinedMustTailCalls && RI->getParent()->getTerminatingMustTailCall()) continue; if (InlinedDeoptimizeCalls && RI->getParent()->getTerminatingDeoptimizeCall()) continue; IRBuilder<>(RI).CreateLifetimeEnd(AI, AllocaSize); } } } // If the inlined code contained dynamic alloca instructions, wrap the inlined // code with llvm.stacksave/llvm.stackrestore intrinsics. CallInst *TFCreate = nullptr; BasicBlock *TFEntryBlock = DetachedCtxEntryBlock; if (InlinedFunctionInfo.ContainsDetach && (InlinedFunctionInfo.ContainsDynamicAllocas || MayBeUnsyncedAtCall)) { Module *M = Caller->getParent(); // Get the two intrinsics we care about. Function *TFCreateFn = Intrinsic::getDeclaration(M, Intrinsic::taskframe_create); // Insert the llvm.taskframe.create. TFCreate = IRBuilder<>(&*FirstNewBlock, FirstNewBlock->begin()) .CreateCall(TFCreateFn, {}, "tf.i"); TFCreate->setDebugLoc(CB.getDebugLoc()); TFEntryBlock = &*FirstNewBlock; // If we're inlining an invoke, insert a taskframe.resume at the unwind // destination of the invoke. if (auto *II = dyn_cast<InvokeInst>(&CB)) { BasicBlock *UnwindEdge = II->getUnwindDest(); // Create the normal return for the detached rethrow. BasicBlock *UnreachableBlk = BasicBlock::Create( Caller->getContext(), UnwindEdge->getName()+".unreachable", Caller); { // Add an unreachable instruction to the end of UnreachableBlk. IRBuilder<> Builder(UnreachableBlk); Builder.CreateUnreachable(); } // Create an unwind edge for the taskframe. BasicBlock *TaskFrameUnwindEdge = CreateSubTaskUnwindEdge( Intrinsic::taskframe_resume, TFCreate, UnwindEdge, UnreachableBlk, II); for (PHINode &PN : UnwindEdge->phis()) PN.replaceIncomingBlockWith(II->getParent(), TaskFrameUnwindEdge); // Replace the unwind destination of the invoke with the unwind edge for // the taskframe. II->setUnwindDest(TaskFrameUnwindEdge); } } else if (InlinedFunctionInfo.ContainsDynamicAllocas) { Module *M = Caller->getParent(); // Get the two intrinsics we care about. Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave); Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore); // Insert the llvm.stacksave. CallInst *SavedPtr = IRBuilder<>(&*FirstNewBlock, FirstNewBlock->begin()) .CreateCall(StackSave, {}, "savedstack"); // Insert a call to llvm.stackrestore before any return instructions in the // inlined function. for (ReturnInst *RI : Returns) { // Don't insert llvm.stackrestore calls between a musttail or deoptimize // call and a return. The return will restore the stack pointer. if (InlinedMustTailCalls && RI->getParent()->getTerminatingMustTailCall()) continue; if (InlinedDeoptimizeCalls && RI->getParent()->getTerminatingDeoptimizeCall()) continue; IRBuilder<>(RI).CreateCall(StackRestore, SavedPtr); } } // If we are inlining for an invoke instruction, we must make sure to rewrite // any call instructions into invoke instructions. This is sensitive to which // funclet pads were top-level in the inlinee, so must be done before // rewriting the "parent pad" links. if (auto *II = dyn_cast<InvokeInst>(&CB)) { BasicBlock *UnwindDest = II->getUnwindDest(); Instruction *FirstNonPHI = UnwindDest->getFirstNonPHI(); if (isa<LandingPadInst>(FirstNonPHI)) { HandleInlinedLandingPad(II, &*FirstNewBlock, TFCreate, InlinedFunctionInfo); } else { HandleInlinedEHPad(II, &*FirstNewBlock, InlinedFunctionInfo); } } else if (!Resumes.empty() && (&Caller->getEntryBlock() != TFEntryBlock)) { // If we inlined into a detached task, and the inlined function contains // resumes, then we need to insert additional calls to EH intrinsics, // specifically, detached.rethrow and taskframe.resume. // Create the normal (unreachable) return for the invocations of EH // intrinsics. BasicBlock *UnreachableBlk = BasicBlock::Create( Caller->getContext(), CalledFunc->getName()+".unreachable", Caller); { // Add an unreachable instruction to the end of UnreachableBlk. IRBuilder<> Builder(UnreachableBlk); Builder.CreateUnreachable(); } ResumeInst *Resume = Resumes[0]; // If multiple resumes were inlined, unify them, so that the detach // instruction has a single unwind destination. if (Resumes.size() > 1) { // Create the unified resume block. BasicBlock *UnifiedResume = BasicBlock::Create( Caller->getContext(), "eh.unified.resume.i", Caller); // Add a PHI node at the beginning of the block. IRBuilder<> Builder(UnifiedResume); PHINode *PN = Builder.CreatePHI(Resume->getValue()->getType(), Resumes.size()); for (ResumeInst *RI : Resumes) { // Insert incoming values to the PHI node. PN->addIncoming(RI->getValue(), RI->getParent()); // Replace the resume with a branch to the unified block. ReplaceInstWithInst(RI, BranchInst::Create(UnifiedResume)); } // Insert a resume instruction at the end of the block. Resume = Builder.CreateResume(PN); } // Handle resumes within the task. HandleInlinedResumeInTask(TFEntryBlock, DetachedCtxEntryBlock, Resume, UnreachableBlk); } // Update the lexical scopes of the new funclets and callsites. // Anything that had 'none' as its parent is now nested inside the callsite's // EHPad. if (CallSiteEHPad) { for (Function::iterator BB = FirstNewBlock->getIterator(), E = Caller->end(); BB != E; ++BB) { // Add bundle operands to any top-level call sites. SmallVector<OperandBundleDef, 1> OpBundles; for (Instruction &II : llvm::make_early_inc_range(*BB)) { CallBase *I = dyn_cast<CallBase>(&II); if (!I) continue; // Skip call sites which are nounwind intrinsics. auto *CalledFn = dyn_cast<Function>(I->getCalledOperand()->stripPointerCasts()); if (CalledFn && CalledFn->isIntrinsic() && I->doesNotThrow()) continue; // Skip call sites which already have a "funclet" bundle. if (I->getOperandBundle(LLVMContext::OB_funclet)) continue; I->getOperandBundlesAsDefs(OpBundles); OpBundles.emplace_back("funclet", CallSiteEHPad); Instruction *NewInst = CallBase::Create(I, OpBundles, I); NewInst->takeName(I); I->replaceAllUsesWith(NewInst); I->eraseFromParent(); OpBundles.clear(); } // It is problematic if the inlinee has a cleanupret which unwinds to // caller and we inline it into a call site which doesn't unwind but into // an EH pad that does. Such an edge must be dynamically unreachable. // As such, we replace the cleanupret with unreachable. if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(BB->getTerminator())) if (CleanupRet->unwindsToCaller() && EHPadForCallUnwindsLocally) changeToUnreachable(CleanupRet); Instruction *I = BB->getFirstNonPHI(); if (!I->isEHPad()) continue; if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I)) { if (isa<ConstantTokenNone>(CatchSwitch->getParentPad())) CatchSwitch->setParentPad(CallSiteEHPad); } else { auto *FPI = cast<FuncletPadInst>(I); if (isa<ConstantTokenNone>(FPI->getParentPad())) FPI->setParentPad(CallSiteEHPad); } } } if (InlinedDeoptimizeCalls) { // We need to at least remove the deoptimizing returns from the Return set, // so that the control flow from those returns does not get merged into the // caller (but terminate it instead). If the caller's return type does not // match the callee's return type, we also need to change the return type of // the intrinsic. if (Caller->getReturnType() == CB.getType()) { llvm::erase_if(Returns, [](ReturnInst *RI) { return RI->getParent()->getTerminatingDeoptimizeCall() != nullptr; }); } else { SmallVector<ReturnInst *, 8> NormalReturns; Function *NewDeoptIntrinsic = Intrinsic::getDeclaration( Caller->getParent(), Intrinsic::experimental_deoptimize, {Caller->getReturnType()}); for (ReturnInst *RI : Returns) { CallInst *DeoptCall = RI->getParent()->getTerminatingDeoptimizeCall(); if (!DeoptCall) { NormalReturns.push_back(RI); continue; } // The calling convention on the deoptimize call itself may be bogus, // since the code we're inlining may have undefined behavior (and may // never actually execute at runtime); but all // @llvm.experimental.deoptimize declarations have to have the same // calling convention in a well-formed module. auto CallingConv = DeoptCall->getCalledFunction()->getCallingConv(); NewDeoptIntrinsic->setCallingConv(CallingConv); auto *CurBB = RI->getParent(); RI->eraseFromParent(); SmallVector<Value *, 4> CallArgs(DeoptCall->args()); SmallVector<OperandBundleDef, 1> OpBundles; DeoptCall->getOperandBundlesAsDefs(OpBundles); auto DeoptAttributes = DeoptCall->getAttributes(); DeoptCall->eraseFromParent(); assert(!OpBundles.empty() && "Expected at least the deopt operand bundle"); IRBuilder<> Builder(CurBB); CallInst *NewDeoptCall = Builder.CreateCall(NewDeoptIntrinsic, CallArgs, OpBundles); NewDeoptCall->setCallingConv(CallingConv); NewDeoptCall->setAttributes(DeoptAttributes); if (NewDeoptCall->getType()->isVoidTy()) Builder.CreateRetVoid(); else Builder.CreateRet(NewDeoptCall); } // Leave behind the normal returns so we can merge control flow. std::swap(Returns, NormalReturns); } } // Handle any inlined musttail call sites. In order for a new call site to be // musttail, the source of the clone and the inlined call site must have been // musttail. Therefore it's safe to return without merging control into the // phi below. if (InlinedMustTailCalls) { // Check if we need to bitcast the result of any musttail calls. Type *NewRetTy = Caller->getReturnType(); bool NeedBitCast = !CB.use_empty() && CB.getType() != NewRetTy; // Handle the returns preceded by musttail calls separately. SmallVector<ReturnInst *, 8> NormalReturns; for (ReturnInst *RI : Returns) { CallInst *ReturnedMustTail = RI->getParent()->getTerminatingMustTailCall(); if (!ReturnedMustTail) { NormalReturns.push_back(RI); continue; } if (!NeedBitCast) continue; // Delete the old return and any preceding bitcast. BasicBlock *CurBB = RI->getParent(); auto *OldCast = dyn_cast_or_null<BitCastInst>(RI->getReturnValue()); RI->eraseFromParent(); if (OldCast) OldCast->eraseFromParent(); // Insert a new bitcast and return with the right type. IRBuilder<> Builder(CurBB); Builder.CreateRet(Builder.CreateBitCast(ReturnedMustTail, NewRetTy)); } // Leave behind the normal returns so we can merge control flow. std::swap(Returns, NormalReturns); } // Now that all of the transforms on the inlined code have taken place but // before we splice the inlined code into the CFG and lose track of which // blocks were actually inlined, collect the call sites. We only do this if // call graph updates weren't requested, as those provide value handle based // tracking of inlined call sites instead. Calls to intrinsics are not // collected because they are not inlineable. if (InlinedFunctionInfo.ContainsCalls && !IFI.CG) { // Otherwise just collect the raw call sites that were inlined. for (BasicBlock &NewBB : make_range(FirstNewBlock->getIterator(), Caller->end())) for (Instruction &I : NewBB) if (auto *CB = dyn_cast<CallBase>(&I)) if (!(CB->getCalledFunction() && CB->getCalledFunction()->isIntrinsic())) IFI.InlinedCallSites.push_back(CB); } // If we cloned in _exactly one_ basic block, and if that block ends in a // return instruction, we splice the body of the inlined callee directly into // the calling basic block. if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) { // Move all of the instructions right before the call. OrigBB->getInstList().splice(CB.getIterator(), FirstNewBlock->getInstList(), FirstNewBlock->begin(), FirstNewBlock->end()); // Remove the cloned basic block. Caller->getBasicBlockList().pop_back(); // If the call site was an invoke instruction, add a branch to the normal // destination. if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) { BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), &CB); NewBr->setDebugLoc(Returns[0]->getDebugLoc()); } // If the return instruction returned a value, replace uses of the call with // uses of the returned value. if (!CB.use_empty()) { ReturnInst *R = Returns[0]; if (&CB == R->getReturnValue()) CB.replaceAllUsesWith(UndefValue::get(CB.getType())); else CB.replaceAllUsesWith(R->getReturnValue()); } // Since we are now done with the Call/Invoke, we can delete it. CB.eraseFromParent(); // Since we are now done with the return instruction, delete it also. Returns[0]->eraseFromParent(); // We are now done with the inlining. return InlineResult::success(); } // Otherwise, we have the normal case, of more than one block to inline or // multiple return sites. // We want to clone the entire callee function into the hole between the // "starter" and "ender" blocks. How we accomplish this depends on whether // this is an invoke instruction or a call instruction. BasicBlock *AfterCallBB; BranchInst *CreatedBranchToNormalDest = nullptr; if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) { // Add an unconditional branch to make this look like the CallInst case... CreatedBranchToNormalDest = BranchInst::Create(II->getNormalDest(), &CB); // Split the basic block. This guarantees that no PHI nodes will have to be // updated due to new incoming edges, and make the invoke case more // symmetric to the call case. AfterCallBB = OrigBB->splitBasicBlock(CreatedBranchToNormalDest->getIterator(), CalledFunc->getName() + ".exit"); } else { // It's a call // If this is a call instruction, we need to split the basic block that // the call lives in. // AfterCallBB = OrigBB->splitBasicBlock(CB.getIterator(), CalledFunc->getName() + ".exit"); } if (IFI.CallerBFI) { // Copy original BB's block frequency to AfterCallBB IFI.CallerBFI->setBlockFreq( AfterCallBB, IFI.CallerBFI->getBlockFreq(OrigBB).getFrequency()); } // If we inserted a taskframe.create, insert a taskframe.end at the start of // AfterCallBB. if (TFCreate) { Function *TFEndFn = Intrinsic::getDeclaration(Caller->getParent(), Intrinsic::taskframe_end); IRBuilder<>(&AfterCallBB->front()).CreateCall(TFEndFn, TFCreate); } // Change the branch that used to go to AfterCallBB to branch to the first // basic block of the inlined function. // Instruction *Br = OrigBB->getTerminator(); assert(Br && Br->getOpcode() == Instruction::Br && "splitBasicBlock broken!"); Br->setOperand(0, &*FirstNewBlock); // Now that the function is correct, make it a little bit nicer. In // particular, move the basic blocks inserted from the end of the function // into the space made by splitting the source basic block. Caller->getBasicBlockList().splice(AfterCallBB->getIterator(), Caller->getBasicBlockList(), FirstNewBlock, Caller->end()); // Handle all of the return instructions that we just cloned in, and eliminate // any users of the original call/invoke instruction. Type *RTy = CalledFunc->getReturnType(); PHINode *PHI = nullptr; if (Returns.size() > 1) { // The PHI node should go at the front of the new basic block to merge all // possible incoming values. if (!CB.use_empty()) { PHI = PHINode::Create(RTy, Returns.size(), CB.getName(), &AfterCallBB->front()); // Anything that used the result of the function call should now use the // PHI node as their operand. CB.replaceAllUsesWith(PHI); } // Loop over all of the return instructions adding entries to the PHI node // as appropriate. if (PHI) { for (unsigned i = 0, e = Returns.size(); i != e; ++i) { ReturnInst *RI = Returns[i]; assert(RI->getReturnValue()->getType() == PHI->getType() && "Ret value not consistent in function!"); PHI->addIncoming(RI->getReturnValue(), RI->getParent()); } } // Add a branch to the merge points and remove return instructions. DebugLoc Loc; for (unsigned i = 0, e = Returns.size(); i != e; ++i) { ReturnInst *RI = Returns[i]; BranchInst* BI = BranchInst::Create(AfterCallBB, RI); Loc = RI->getDebugLoc(); BI->setDebugLoc(Loc); RI->eraseFromParent(); } // We need to set the debug location to *somewhere* inside the // inlined function. The line number may be nonsensical, but the // instruction will at least be associated with the right // function. if (CreatedBranchToNormalDest) CreatedBranchToNormalDest->setDebugLoc(Loc); } else if (!Returns.empty()) { // Otherwise, if there is exactly one return value, just replace anything // using the return value of the call with the computed value. if (!CB.use_empty()) { if (&CB == Returns[0]->getReturnValue()) CB.replaceAllUsesWith(UndefValue::get(CB.getType())); else CB.replaceAllUsesWith(Returns[0]->getReturnValue()); } // Update PHI nodes that use the ReturnBB to use the AfterCallBB. BasicBlock *ReturnBB = Returns[0]->getParent(); ReturnBB->replaceAllUsesWith(AfterCallBB); // Splice the code from the return block into the block that it will return // to, which contains the code that was after the call. AfterCallBB->getInstList().splice(AfterCallBB->begin(), ReturnBB->getInstList()); if (CreatedBranchToNormalDest) CreatedBranchToNormalDest->setDebugLoc(Returns[0]->getDebugLoc()); // Delete the return instruction now and empty ReturnBB now. Returns[0]->eraseFromParent(); ReturnBB->eraseFromParent(); } else if (!CB.use_empty()) { // No returns, but something is using the return value of the call. Just // nuke the result. CB.replaceAllUsesWith(UndefValue::get(CB.getType())); } // Since we are now done with the Call/Invoke, we can delete it. CB.eraseFromParent(); // If we inlined any musttail calls and the original return is now // unreachable, delete it. It can only contain a bitcast and ret. if (InlinedMustTailCalls && pred_empty(AfterCallBB)) AfterCallBB->eraseFromParent(); // We should always be able to fold the entry block of the function into the // single predecessor of the block... assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!"); BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0); // Splice the code entry block into calling block, right before the // unconditional branch. CalleeEntry->replaceAllUsesWith(OrigBB); // Update PHI nodes OrigBB->getInstList().splice(Br->getIterator(), CalleeEntry->getInstList()); // Remove the unconditional branch. OrigBB->getInstList().erase(Br); // Now we can remove the CalleeEntry block, which is now empty. Caller->getBasicBlockList().erase(CalleeEntry); // If we inserted a phi node, check to see if it has a single value (e.g. all // the entries are the same or undef). If so, remove the PHI so it doesn't // block other optimizations. if (PHI) { AssumptionCache *AC = IFI.GetAssumptionCache ? &IFI.GetAssumptionCache(*Caller) : nullptr; auto &DL = Caller->getParent()->getDataLayout(); if (Value *V = SimplifyInstruction(PHI, {DL, nullptr, nullptr, AC})) { PHI->replaceAllUsesWith(V); PHI->eraseFromParent(); } } return InlineResult::success(); }
[ "neboat@mit.edu" ]
neboat@mit.edu
7e66f69f4d2b313dd53a8c393661500c63ae4bd2
ee5666df7308225a4d0cfa820968f5b532e1a164
/const_member_function.cpp
e7c131f7eaa4f2a5b2497d80cb80a3b5dfdb85ed
[ "Apache-2.0" ]
permissive
johnhany/cpp_notes
199995e12ec1fbaf3df72917b9e6df582dbf7f97
913002f1bd6089ca5d0d7f9ca3f1f25d888fdd0b
refs/heads/master
2022-09-25T16:56:13.890465
2020-06-07T03:48:43
2020-06-07T03:48:43
266,788,592
0
0
null
null
null
null
UTF-8
C++
false
false
1,035
cpp
#include <iostream> using namespace std; class MyClass { private: int counter; public: void Foo() { counter++; std::cout << "Foo" << std::endl; } void Foo() const { //counter++; std::cout << "Foo const" << std::endl; } int GetInvocations() const { return counter; } }; class MyClass2 { private: mutable int counter; public: MyClass2() : counter(0) {} void Foo() { counter++; std::cout << "Foo" << std::endl; } void Foo() const { counter++; std::cout << "Foo const" << std::endl; } int GetInvocations() const { return counter; } }; int main() { MyClass cc; const MyClass& ccc = cc; cc.Foo(); ccc.Foo(); std::cout << "Foo has been invoked " << ccc.GetInvocations() << " times" << endl; MyClass2 dd; const MyClass2& ddd = dd; dd.Foo(); ddd.Foo(); std::cout << "Foo has been invoked " << ddd.GetInvocations() << " times" << endl; return 0; }
[ "johnhany@163.com" ]
johnhany@163.com
ac3efe809659a34b8d62b2699e869cba1c4e3d85
1b0aadb6dc881bf363cbebbc59ac0c41a956ed5c
/xtk/Samples/Utilities/CommandBarsDesigner/DialogNewSymbol.h
15c3a8474e7b717f66caaeb3b9dcdd0f40fe34d0
[]
no_license
chinatiny/OSS
bc60236144d73ab7adcbe52cafbe610221292ba6
87b61b075f00b67fd34cfce557abe98ed6f5be70
refs/heads/master
2022-09-21T03:11:09.661243
2018-01-02T10:12:35
2018-01-02T10:12:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,056
h
// DialogNewSymbol.h : header file // // This file is a part of the XTREME TOOLKIT PRO MFC class library. // (c)1998-2007 Codejock Software, All Rights Reserved. // // THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE // RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN // CONSENT OF CODEJOCK SOFTWARE. // // THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED // IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO // YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A // SINGLE COMPUTER. // // CONTACT INFORMATION: // support@codejock.com // http://www.codejock.com // ///////////////////////////////////////////////////////////////////////////// #if !defined(AFX_DIALOGNEWSYMBOL_H__C1517853_612F_49CD_8653_D3A8D12CF835__INCLUDED_) #define AFX_DIALOGNEWSYMBOL_H__C1517853_612F_49CD_8653_D3A8D12CF835__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CResourceManager; ///////////////////////////////////////////////////////////////////////////// // CDialogNewSymbol dialog class CDialogNewSymbol : public CDialog { // Construction public: CDialogNewSymbol(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CDialogNewSymbol) enum { IDD = IDD_DIALOG_RESOURCE_NEW }; CString m_strName; UINT m_nValue; //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CDialogNewSymbol) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation public: CResourceManager* m_pResourceManager; protected: // Generated message map functions //{{AFX_MSG(CDialogNewSymbol) virtual BOOL OnInitDialog(); afx_msg void OnChangeEditName(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_DIALOGNEWSYMBOL_H__C1517853_612F_49CD_8653_D3A8D12CF835__INCLUDED_)
[ "w.z.y2006@163.com" ]
w.z.y2006@163.com
aa82bf14c6392f5d7360fc3a2b66da75488c5811
a637c6c71a11fa9731354e963f0ad47ff8b2f12e
/BRUSH.H
f28643b8d8203ad6aa177129d699a525ec1c2df0
[]
no_license
cooling-technology-institute/CTIBluebook2017
ddc6ce4094658ce7381f286851132af92c2352e7
1041ddfd0a02faf7e04afc4843759251b98ad1c0
refs/heads/master
2020-08-01T23:38:45.947013
2019-09-26T22:17:20
2019-09-26T22:17:20
211,161,022
0
0
null
null
null
null
UTF-8
C++
false
false
1,212
h
#if !defined(AFX_BRUSH_H__4BE02FA8_0229_11D2_AE48_00400141862D__INCLUDED_) #define AFX_BRUSH_H__4BE02FA8_0229_11D2_AE48_00400141862D__INCLUDED_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 // Machine generated IDispatch wrapper class(es) created by Microsoft Visual C++ // NOTE: Do not modify the contents of this file. If this class is regenerated by // Microsoft Visual C++, your modifications will be overwritten. ///////////////////////////////////////////////////////////////////////////// // CBrush1 wrapper class class CBrush1 : public COleDispatchDriver { public: CBrush1() {} // Calls COleDispatchDriver default constructor CBrush1(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {} CBrush1(const CBrush1& dispatchSrc) : COleDispatchDriver(dispatchSrc) {} // Attributes public: // Operations public: unsigned long GetColor(); void SetColor(unsigned long newValue); long GetStyle(); void SetStyle(long nNewValue); }; //{{AFX_INSERT_LOCATION}} // Microsoft Developer Studio will insert additional declarations immediately before the previous line. #endif // !defined(AFX_BRUSH_H__4BE02FA8_0229_11D2_AE48_00400141862D__INCLUDED_)
[ "noreply@github.com" ]
noreply@github.com
f75f105358fb5d8d4953010a7edbeca18fe5c4c7
4728c8d66b28dbc2644b0e89713d1815804da237
/src/media/audio/lib/effects_loader/effects_processor.h
9d2db80bedf83dabb8d0f4bc6c72e06a4ef2db22
[ "BSD-3-Clause" ]
permissive
osphea/zircon-rpi
094aca2d06c9a5f58ceb66c3e7d3d57e8bde9e0c
82c90329892e1cb3d09c99fee0f967210d11dcb2
refs/heads/master
2022-11-08T00:22:37.817127
2020-06-29T23:16:20
2020-06-29T23:16:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,314
h
// Copyright 2018 The Fuchsia 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 SRC_MEDIA_AUDIO_LIB_EFFECTS_LOADER_EFFECTS_PROCESSOR_H_ #define SRC_MEDIA_AUDIO_LIB_EFFECTS_LOADER_EFFECTS_PROCESSOR_H_ #include <zircon/types.h> #include <vector> #include "src/media/audio/lib/effects_loader/effect.h" namespace media::audio { // EffectsProcessor represents a queue of active effect instances and manages chaining calls of // Process/ProcessInPlace through a chain of effects. // // This class is designed to be used synchronously and is not explicitly multi-thread-safe. class EffectsProcessor { public: // Creates a new, empty effects processor. EffectsProcessor() = default; // Disallow copy/move. EffectsProcessor(const EffectsProcessor&) = delete; EffectsProcessor& operator=(const EffectsProcessor&) = delete; EffectsProcessor(EffectsProcessor&& o) = delete; EffectsProcessor& operator=(EffectsProcessor&& o) = delete; // Adds an `Effect` to the end of the queue of effects included in this processor. // // When the first `Effect` is added, that effects input channels becomes the input to the entire // processor. Likewise that effects output channels becomes the processors output channels. // // When subsequent effects are added, the new effects input channels must match exactly the out- // put channels of last added effect. The output channels for the processor will be updated to // match the output channels of the newly added effect. // // Aborts if `e` is an invalid `Effect`. zx_status_t AddEffect(Effect e); // Returns the number of active instances in the enclosed effect chain. [[nodiscard]] uint16_t size() const { return effects_chain_.size(); } // Returns the number of input channels for this effect. This will be the number of channels // expected for input frames to `Process` or `ProcessInPlace`. // // Returns 0 if this processor has no effects. [[nodiscard]] uint32_t channels_in() const { return channels_in_; } // Returns the number of output channels for this effect. // // Returns 0 if this processor has no effects. [[nodiscard]] uint32_t channels_out() const { return channels_out_; } // Returns the required block size (in frames) for this processor. Calls to |ProcessInPlace| must // provide frames in multiples of |block_size()|. [[nodiscard]] uint32_t block_size() const { return block_size_; } // Returns the maximum buffer size the processor is prepared to handle with a single call to // |ProcessInPlace| or |Process|. // // Returns 0 if the plugin can handle arbitrary buffer sizes. [[nodiscard]] uint32_t max_batch_size() const { return max_batch_size_; } // Returns the number of frames the input signal will be delayed after being run through this // |EffectsProcessor|. [[nodiscard]] uint32_t delay_frames() const { return delay_frames_; } // Returns the number of frames of silence that this processor requires to idle. [[nodiscard]] uint32_t ring_out_frames() const { return ring_out_frames_; } [[nodiscard]] auto begin() { return effects_chain_.begin(); } [[nodiscard]] auto end() { return effects_chain_.end(); } [[nodiscard]] auto cbegin() const { return effects_chain_.cbegin(); } [[nodiscard]] auto cend() const { return effects_chain_.cend(); } // Returns the instance at the specified (zero-based) position in the chain. [[nodiscard]] const Effect& GetEffectAt(size_t position) const; // These maps directly to the corresponding ABI call, for each instance. zx_status_t ProcessInPlace(uint32_t num_frames, float* audio_buff_in_out) const; zx_status_t Process(uint32_t num_frames, float* audio_buff_in, float** audio_buff_out) const; zx_status_t Flush() const; void SetStreamInfo(const fuchsia_audio_effects_stream_info& stream_info) const; private: std::vector<Effect> effects_chain_; std::vector<fuchsia_audio_effects_parameters> effects_parameters_; uint32_t channels_in_ = 0; uint32_t channels_out_ = 0; uint32_t block_size_ = 1; uint32_t max_batch_size_ = 0; uint32_t delay_frames_ = 0; uint32_t ring_out_frames_ = 0; }; } // namespace media::audio #endif // SRC_MEDIA_AUDIO_LIB_EFFECTS_LOADER_EFFECTS_PROCESSOR_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
28c6a0a4347489a8789377cbb6b565edd246989a
af7e277c2a503fdc85601c7b58d549b14f9c3e63
/lab3/house.h
0c9ac553c9b41c25ae954d90a30157331848d83d
[]
no_license
fridajan/cdate
070892f47de3f164ee93ec61e2b647d605be4eaa
cd48056cd4790416d441ef015d4a7bb0b1dcb46b
refs/heads/master
2016-09-05T10:58:27.575299
2014-01-22T16:12:14
2014-01-22T16:12:14
14,136,585
0
1
null
null
null
null
UTF-8
C++
false
false
417
h
#ifndef HOUSE_H_ #define HOUSE_H_ #include "place.h" #include "room.h" #include "garden.h" #include "Items/item.h" #include <stdexcept> #include <string> #include <vector> #include <map> namespace haunted_house { class House { private: std::vector<Place*> places; public: House(); ~House(); void printHouse(); static const std::string directions[]; }; } #endif /* HOUSE_H_ */
[ "frida.k.jansson@gmail.com" ]
frida.k.jansson@gmail.com
79ea662258e0895d72c6bd27d6515b79f6b488d5
9537303a499408e640830402ab82f821cbc3bc90
/QT5-Development-and-examples/CH3/contact.h
f497e13f84b968f55dbc4bf2a312ede5155e82a9
[]
no_license
yang-360/Qt_project
f7961ed38f5f0b157a6e8f5e4b068deec263e680
13f3ec436cc251e01903c16033709ed00132a6a0
refs/heads/master
2023-04-14T19:37:48.031145
2021-05-05T17:20:38
2021-05-05T17:20:38
266,720,384
0
0
null
2020-05-25T09:13:19
2020-05-25T08:05:22
null
UTF-8
C++
false
false
619
h
#ifndef CONTACT_H #define CONTACT_H #include <QWidget> #include <QLabel> #include <QGridLayout> #include <QLineEdit> #include <QCheckBox> class contact : public QWidget { Q_OBJECT public: explicit contact(QWidget *parent = nullptr); signals: private: QLabel *EmailLabel; QLineEdit *EmailLineEdit; QLabel *AddrLabel; QLineEdit *AddrLineEdit; QLabel *CodeLabel; QLineEdit *CodeLineEdit; QLabel *MoviTelLabel; QLineEdit *MoviTelLineEdit; QCheckBox *MoviTelCheckBook; QLabel *ProTelLabel; QLineEdit *ProTelLineEdit; QGridLayout *mainLayout; }; #endif // CONTACT_H
[ "13755546592@163.com" ]
13755546592@163.com
0bceeddd59e07d74d85c4fd9a97e2fc19885a902
064741ef54df109388c291db9e5820bc90b9f664
/cppfiles/318A.cpp
cbd55a189b82648560bcda6e04eb7c4df6e986e5
[]
no_license
overlorde/codeforces
2bf48bb3b638e8c8406d39c25c265b84115043fa
87a6fdde921abaccbe88e13d75b0a929bea7117c
refs/heads/master
2023-06-14T15:22:38.483292
2021-07-08T09:45:57
2021-07-08T09:45:57
266,014,269
0
0
null
null
null
null
UTF-8
C++
false
false
472
cpp
#include <bits/stdc++.h> using namespace std; #define ll long long int main() { ll n,k; cin>>n>>k; if(n%2==0) { if(k<=n/2) { cout<<2*k-1<<endl; } else{ k=k-n/2; cout<<2*k<<endl; } } else{ if(k<=(n/2)+1) { cout<<2*k-1<<endl; } else{ k=k-n/2-1; cout<<2*k<<endl; } } return 0; }
[ "farhansaif488@gmail.com" ]
farhansaif488@gmail.com
c7e540f5f2e208fd121ad45d0cb2bf07ca5e32c4
b16e2f8cc94df8320f9caf8c8592fa21b1f7c413
/Luogu/P4777/chinese_remainder_theorem.cpp
1349d0d1855caad4860b573a9960d0220057c6cc
[ "MIT" ]
permissive
codgician/Competitive-Programming
000dfafea0575b773b0a10502f5128d2088f3398
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
refs/heads/master
2022-06-13T04:59:52.322037
2020-04-29T06:38:59
2020-04-29T06:38:59
104,017,512
3
0
null
null
null
null
UTF-8
C++
false
false
1,443
cpp
#include <bits/stdc++.h> using namespace std; #define SIZE 100010 long long int cstArr[SIZE], modArr[SIZE]; int equNum; long long int fastMul(long long int a, long long int n, long long int mod) { long long int ret = 0; a %= mod; while (n > 0) { if (n & 1) ret = (ret + a) % mod; a = (a << 1) % mod; n >>= 1; } return ret; } long long int extEuclid(long long int a, long long int b, long long int & x, long long int & y) { if (b == 0) { x = 1, y = 0; return a; } long long int gcd = extEuclid(b, a % b, x, y), tmp = x; x = y; y = tmp - y * (a / b); return gcd; } long long int crt() { long long int modProd = modArr[0], ans = cstArr[0]; for (int i = 1; i < equNum; i++) { long long int x, y, a = modProd, b = modArr[i]; long long int c = (cstArr[i] - ans % b + b) % b; long long int gcd = extEuclid(a, b, x, y), bg = b / gcd; if (c % gcd != 0) return -1; long long int cntAns = fastMul(x, c / gcd, bg); ans += modProd * cntAns; modProd *= bg; ans = (ans % modProd + modProd) % modProd; } return (ans % modProd + modProd) % modProd; } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> equNum; for (int i = 0; i < equNum; i++) cin >> modArr[i] >> cstArr[i]; cout << crt() << '\n'; return 0; }
[ "codgician@users.noreply.github.com" ]
codgician@users.noreply.github.com
88d3fb14518db3c2c97a999521dc451baa137011
36c31b485a5906ab514c964491b8f001a70a67f5
/AtCoder/ABC188B.cpp
6c4e7cd2b5a46c36a12592fbc1290abab2a59a1a
[]
no_license
SMiles02/CompetitiveProgramming
77926918d5512824900384639955b31b0d0a5841
035040538c7e2102a88a2e3587e1ca984a2d9568
refs/heads/master
2023-08-18T22:14:09.997704
2023-08-13T20:30:42
2023-08-13T20:30:42
277,504,801
25
5
null
2022-11-01T01:34:30
2020-07-06T09:54:44
C++
UTF-8
C++
false
false
1,050
cpp
#include <bits/stdc++.h> #define ll long long #define sz(x) (int)(x).size() using namespace std; //mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); //uniform_int_distribution<int>(1000,10000)(rng) ll binpow(ll a, ll b) { ll res = 1; while (b > 0) { if (b & 1) res = res * a; a = a * a; b >>= 1; } return res; } ll gcd(ll a,ll b) { if (b==0) return a; return gcd(b,a%b); } string to_upper(string a) { for (int i=0;i<(int)a.size();++i) if (a[i]>='a' && a[i]<='z') a[i]-='a'-'A'; return a; } string to_lower(string a) { for (int i=0;i<(int)a.size();++i) if (a[i]>='A' && a[i]<='Z') a[i]+='a'-'A'; return a; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n; cin>>n; int a[n],b[n]; for (int i=0;i<n;++i) cin>>a[i]; for (int i=0;i<n;++i) cin>>b[i]; ll ans=0; for (int i=0;i<n;++i) ans+=(a[i]*b[i]); if (ans==0) cout<<"Yes"; else cout<<"No"; return 0; }
[ "mahajan.suneet2002@gmail.com" ]
mahajan.suneet2002@gmail.com
8bcce4d3601d0a84fe79db18244399e5baba71c1
acaee026fefd54051676991ba1b24ae62a212436
/tut_6/Source Files/main.1.cpp
3e10ef67e5bc9b4386416af5bb3e429dbb05ee48
[]
no_license
Chris-QingYuan/pick_up_cpp
596e063f47334dd1596e5cab0f7d58b02483a084
e72a2c19789eae46de97cd467d87f912cd5f8594
refs/heads/master
2020-03-28T21:56:39.857672
2018-09-23T17:58:48
2018-09-23T17:58:48
149,194,139
0
0
null
null
null
null
UTF-8
C++
false
false
665
cpp
#include <iostream> #include <cstdlib> #include <string> #include <vector> #include <numeric> #include <sstream> std::vector<std::string> strToVec(std::string str, char separator); int main(int argc, char const *argv[]) { std::vector<std::string> vec = strToVec("what is in this string?", ' '); for (std::string ele : vec) { std::cout << ele << std::endl; } return 0; } std::vector<std::string> strToVec(std::string str, char separator) { std::vector<std::string> words; std::stringstream ss(str); std::string tmp; while (getline(ss, tmp, separator)) { words.push_back(tmp); } return words; }
[ "1515y.chris@gmail.com" ]
1515y.chris@gmail.com