blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
sequencelengths
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
sequencelengths
1
1
author
stringlengths
0
119
551ae3d51ee38c8c76b2733bc1c07f0ffac20a44
5fd0b45b2f6ec6a6c1802fce1b52e0218d189f89
/platform/android/MapboxGLAndroidSDK/src/cpp/snapshotter/map_snapshot.hpp
6b82d02835be7f6fa97bd8920a6fe3c4f8c84fc5
[ "BSD-3-Clause", "MIT", "Apache-2.0", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference", "curl", "ISC", "BSL-1.0", "JSON" ]
permissive
reezer/maplibre-gl-native
ca8e7a87331e39a23e2f3cade3578cfb7be50aa8
d716b5b408900776cbffdc5cffa00c5486e7d1d2
refs/heads/master
2023-04-17T03:24:26.571128
2021-04-07T01:46:21
2021-04-07T01:46:21
357,980,368
0
1
BSD-2-Clause
2021-04-30T12:59:38
2021-04-14T17:00:10
null
UTF-8
C++
false
false
1,435
hpp
#pragma once #include <mbgl/map/map_snapshotter.hpp> #include <jni/jni.hpp> #include "../geometry/lat_lng.hpp" #include "../graphics/pointf.hpp" #include <vector> #include <string> namespace mbgl { namespace android { class MapSnapshot { public: using PointForFn = mbgl::MapSnapshotter::PointForFn; using LatLngForFn = mbgl::MapSnapshotter::LatLngForFn; static constexpr auto Name() { return "com/mapbox/mapboxsdk/snapshotter/MapSnapshot"; }; static void registerNative(jni::JNIEnv&); static jni::Local<jni::Object<MapSnapshot>> New(JNIEnv& env, PremultipliedImage&& image, float pixelRatio, std::vector<std::string> attributions, bool showLogo, PointForFn pointForFn, LatLngForFn latLngForFn); MapSnapshot(jni::JNIEnv&) {}; MapSnapshot(float pixelRatio, PointForFn, LatLngForFn); ~MapSnapshot(); jni::Local<jni::Object<PointF>> pixelForLatLng(jni::JNIEnv&, jni::Object<LatLng>&); jni::Local<jni::Object<LatLng>> latLngForPixel(jni::JNIEnv&, jni::Object<PointF>&); private: float pixelRatio; mbgl::MapSnapshotter::PointForFn pointForFn; mbgl::MapSnapshotter::LatLngForFn latLngForFn; }; } // namespace android } // namespace mbgl
eb0416936ce7747c5dd80cd21cdea848c6154e04
4324378b92a258c471d99d7d10804861961a952b
/Source/MagicBattleSoccer/Classes/Traps/MagicBattleSoccerTrap.h
3e30862efb8293f9c99331746f3fdcf88f22f2b9
[]
no_license
Gamieon/UBattleSoccerPrototype
8fadb3721fb89abd6be3488e10ef0dc8f079e363
77039cd3d47d026f69517261fbc00826446f4f78
refs/heads/master
2020-12-24T13:29:36.702182
2015-03-10T21:18:04
2015-03-10T21:18:04
23,994,481
27
12
null
2019-05-10T18:21:12
2014-09-13T13:06:14
C++
UTF-8
C++
false
false
578
h
#pragma once #include "GameFramework/Actor.h" #include "MagicBattleSoccerTrap.generated.h" /** * Actor is the base class for an Object that can be placed or spawned in a level. * Actors may contain a collection of ActorComponents, which can be used to control how actors move, how they are rendered, etc. * The other main function of an Actor is the replication of properties and function calls across the network during play. */ UCLASS(Abstract, Blueprintable) class MAGICBATTLESOCCER_API AMagicBattleSoccerTrap : public AActor { GENERATED_UCLASS_BODY() };
e267b66d75cf1e62d0333f9d510d7a2c34d6db7f
ee5bed0cace70439a34e3d96e4f8e97334db44c9
/data-structure/1-基本概念/printN.cpp
d49980cd619be700ca8df91f4fad124ff9be1277
[]
no_license
ahabhgk/my-DSA
8ed35d3c82ee4ca203d0f266e998f20d828294e2
5709598aa0858205a5184e70c955b767ebefba38
refs/heads/master
2020-08-03T08:10:33.538664
2019-12-25T17:18:04
2019-12-25T17:18:04
211,679,320
0
0
null
null
null
null
UTF-8
C++
false
false
343
cpp
#include <iostream> using namespace std; void loopPrinter(int n) { for (;n > 0; n--) cout << n << endl; return; } void recursivePrinter(int n) { if (n == 0) return; cout << n << endl; recursivePrinter(n - 1); } void(*const fn)(int) = recursivePrinter; // const void(*fn)(int) 表示 fn 返回值是常量 int main() { fn(1000000); }
b3dac9189c710ac77ad7fc8e1aca1fe89ad8fd40
1d928c3f90d4a0a9a3919a804597aa0a4aab19a3
/c++/Halide/2016/4/bit_counting.cpp
a4f6cb2eddf17115f1be036ccaef7d1eed024637
[]
no_license
rosoareslv/SED99
d8b2ff5811e7f0ffc59be066a5a0349a92cbb845
a062c118f12b93172e31e8ca115ce3f871b64461
refs/heads/main
2023-02-22T21:59:02.703005
2021-01-28T19:40:51
2021-01-28T19:40:51
306,497,459
1
1
null
2020-11-24T20:56:18
2020-10-23T01:18:07
null
UTF-8
C++
false
false
2,907
cpp
#include "Halide.h" #include <stdio.h> #include <stdint.h> #include <string> using namespace Halide; uint32_t local_popcount(uint32_t v) { uint32_t count = 0; while (v) { if (v & 1) ++count; v >>= 1; } return count; } uint32_t local_count_trailing_zeros(uint32_t v) { for (uint32_t b = 0; b < 32; ++b) { if (v & (1 << b)) // found a set bit return b; } return 0; } uint32_t local_count_leading_zeros(uint32_t v) { for (uint32_t b = 0; b < 32; ++b) { if (v & (1 << (31 - b))) // found a set bit return b; } return 0; } std::string as_bits(uint32_t v) { std::string ret; for (int i = 31; i >= 0; --i) ret += (v & (1 << i)) ? '1' : '0'; return ret; } int main() { Image<uint32_t> input(256); for (int i = 0; i < 256; i++) { if (i < 16) input(i) = i; else if (i < 32) input(i) = 0xfffffffful - i; else input(i) = rand(); } Var x; Func popcount_test("popcount_test"); popcount_test(x) = popcount(input(x)); Image<uint32_t> popcount_result = popcount_test.realize(256); for (int i = 0; i < 256; ++i) { if (popcount_result(i) != local_popcount(input(i))) { std::string bits_string = as_bits(input(i)); printf("Popcount of %u [0b%s] returned %d (should be %d)\n", input(i), bits_string.c_str(), popcount_result(i), local_popcount(input(i))); return -1; } } Func ctlz_test("ctlz_test"); ctlz_test(x) = count_leading_zeros(input(x)); Image<uint32_t> ctlz_result = ctlz_test.realize(256); for (int i = 0; i < 256; ++i) { if (input(i) == 0) // results are undefined for zero input continue; if (ctlz_result(i) != local_count_leading_zeros(input(i))) { std::string bits_string = as_bits(input(i)); printf("Ctlz of %u [0b%s] returned %d (should be %d)\n", input(i), bits_string.c_str(), ctlz_result(i), local_count_leading_zeros(input(i))); return -1; } } Func cttz_test("cttz_test"); cttz_test(x) = count_trailing_zeros(input(x)); Image<uint32_t> cttz_result = cttz_test.realize(256); for (int i = 0; i < 256; ++i) { if (input(i) == 0) // results are undefined for zero input continue; if (cttz_result(i) != local_count_trailing_zeros(input(i))) { std::string bits_string = as_bits(input(i)); printf("Cttz of %u [0b%s] returned %d (should be %d)\n", input(i), bits_string.c_str(), cttz_result(i), local_count_trailing_zeros(input(i))); return -1; } } printf("Success!\n"); return 0; }
aa151bbb77c55945e3e7345dd1675b60f1a0a822
ccec956c2ad7c1eced7415a827d4cb88260ef5c9
/NotePad/scintilla/lexers/LexMMIXAL.cxx
d3e735b8047985f39870f2f95adfcc0b84f782d8
[]
no_license
Dylan-H/NotePadUWP
b7a7e33edbec0525abdae053a4e83e61455d5b34
0af598f9b6d0982374307ffa648190770d3464e9
refs/heads/master
2020-05-30T07:34:18.527504
2019-05-31T14:09:44
2019-05-31T14:09:44
189,601,013
2
0
null
null
null
null
UTF-8
C++
false
false
5,651
cxx
// Scintilla source code edit control // Encoding: UTF-8 /** @file LexMMIXAL.cxx ** Lexer for MMIX Assembler Language. ** Written by Christoph Hösler <[email protected]> ** For information about MMIX visit http://www-cs-faculty.stanford.edu/~knuth/mmix.html **/ // Copyright 1998-2003 by Neil Hodgson <[email protected]> // The License.txt file describes the conditions under which this software may be distributed. #include "pch.h" #include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdarg.h> #include <assert.h> #include <ctype.h> #include "ILexer.h" #include "Scintilla.h" #include "SciLexer.h" #include "WordList.h" #include "LexAccessor.h" #include "Accessor.h" #include "StyleContext.h" #include "CharacterSet.h" #include "LexerModule.h" using namespace Scintilla; static inline bool IsAWordChar(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == ':' || ch == '_'); } inline bool isMMIXALOperator(char ch) { if (IsASCII(ch) && isalnum(ch)) return false; if (ch == '+' || ch == '-' || ch == '|' || ch == ' ' || ch == '*' || ch == '/' || ch == '%' || ch == '<' || ch == '>' || ch == '&' || ch == '~' || ch == '$' || ch == ',' || ch == '(' || ch == ')' || ch == '[' || ch == ']') return true; return false; } static void ColouriseMMIXALDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &opcodes = *keywordlists[0]; WordList &special_register = *keywordlists[1]; WordList &predef_symbols = *keywordlists[2]; StyleContext sc(startPos, length, initStyle, styler); for (; sc.More(); sc.Forward()) { // No EOL continuation if (sc.atLineStart) { if (sc.ch == '@' && sc.chNext == 'i') { sc.SetState(SCE_MMIXAL_INCLUDE); } else { sc.SetState(SCE_MMIXAL_LEADWS); } } // Check if first non whitespace character in line is alphanumeric if (sc.state == SCE_MMIXAL_LEADWS && !isspace(sc.ch)) { // LEADWS if(!IsAWordChar(sc.ch)) { sc.SetState(SCE_MMIXAL_COMMENT); } else { if(sc.atLineStart) { sc.SetState(SCE_MMIXAL_LABEL); } else { sc.SetState(SCE_MMIXAL_OPCODE_PRE); } } } // Determine if the current state should terminate. if (sc.state == SCE_MMIXAL_OPERATOR) { // OPERATOR sc.SetState(SCE_MMIXAL_OPERANDS); } else if (sc.state == SCE_MMIXAL_NUMBER) { // NUMBER if (!isdigit(sc.ch)) { if (IsAWordChar(sc.ch)) { char s[100]; sc.GetCurrent(s, sizeof(s)); sc.ChangeState(SCE_MMIXAL_REF); sc.SetState(SCE_MMIXAL_REF); } else { sc.SetState(SCE_MMIXAL_OPERANDS); } } } else if (sc.state == SCE_MMIXAL_LABEL) { // LABEL if (!IsAWordChar(sc.ch) ) { sc.SetState(SCE_MMIXAL_OPCODE_PRE); } } else if (sc.state == SCE_MMIXAL_REF) { // REF if (!IsAWordChar(sc.ch) ) { char s[100]; sc.GetCurrent(s, sizeof(s)); if (*s == ':') { // ignore base prefix for match for (size_t i = 0; i != sizeof(s); ++i) { *(s+i) = *(s+i+1); } } if (special_register.InList(s)) { sc.ChangeState(SCE_MMIXAL_REGISTER); } else if (predef_symbols.InList(s)) { sc.ChangeState(SCE_MMIXAL_SYMBOL); } sc.SetState(SCE_MMIXAL_OPERANDS); } } else if (sc.state == SCE_MMIXAL_OPCODE_PRE) { // OPCODE_PRE if (!isspace(sc.ch)) { sc.SetState(SCE_MMIXAL_OPCODE); } } else if (sc.state == SCE_MMIXAL_OPCODE) { // OPCODE if (!IsAWordChar(sc.ch) ) { char s[100]; sc.GetCurrent(s, sizeof(s)); if (opcodes.InList(s)) { sc.ChangeState(SCE_MMIXAL_OPCODE_VALID); } else { sc.ChangeState(SCE_MMIXAL_OPCODE_UNKNOWN); } sc.SetState(SCE_MMIXAL_OPCODE_POST); } } else if (sc.state == SCE_MMIXAL_STRING) { // STRING if (sc.ch == '\"') { sc.ForwardSetState(SCE_MMIXAL_OPERANDS); } else if (sc.atLineEnd) { sc.ForwardSetState(SCE_MMIXAL_OPERANDS); } } else if (sc.state == SCE_MMIXAL_CHAR) { // CHAR if (sc.ch == '\'') { sc.ForwardSetState(SCE_MMIXAL_OPERANDS); } else if (sc.atLineEnd) { sc.ForwardSetState(SCE_MMIXAL_OPERANDS); } } else if (sc.state == SCE_MMIXAL_REGISTER) { // REGISTER if (!isdigit(sc.ch)) { sc.SetState(SCE_MMIXAL_OPERANDS); } } else if (sc.state == SCE_MMIXAL_HEX) { // HEX if (!isxdigit(sc.ch)) { sc.SetState(SCE_MMIXAL_OPERANDS); } } // Determine if a new state should be entered. if (sc.state == SCE_MMIXAL_OPCODE_POST || // OPCODE_POST sc.state == SCE_MMIXAL_OPERANDS) { // OPERANDS if (sc.state == SCE_MMIXAL_OPERANDS && isspace(sc.ch)) { if (!sc.atLineEnd) { sc.SetState(SCE_MMIXAL_COMMENT); } } else if (isdigit(sc.ch)) { sc.SetState(SCE_MMIXAL_NUMBER); } else if (IsAWordChar(sc.ch) || sc.Match('@')) { sc.SetState(SCE_MMIXAL_REF); } else if (sc.Match('\"')) { sc.SetState(SCE_MMIXAL_STRING); } else if (sc.Match('\'')) { sc.SetState(SCE_MMIXAL_CHAR); } else if (sc.Match('$')) { sc.SetState(SCE_MMIXAL_REGISTER); } else if (sc.Match('#')) { sc.SetState(SCE_MMIXAL_HEX); } else if (isMMIXALOperator(static_cast<char>(sc.ch))) { sc.SetState(SCE_MMIXAL_OPERATOR); } } } sc.Complete(); } static const char * const MMIXALWordListDesc[] = { "Operation Codes", "Special Register", "Predefined Symbols", 0 }; LexerModule lmMMIXAL(SCLEX_MMIXAL, ColouriseMMIXALDoc, "mmixal", 0, MMIXALWordListDesc);
7aadfcc34860f07a0592a3fd2a322b44f19c2d85
775d7b96a5d279e0774340b84917369dcc4b1512
/managecard.h
790e077caa151b3ac2b575caff50d790dd310506
[]
no_license
Tiffanylqc/Library-Database-System
be3c2921ad37ce62a365951ee79f267be80f3292
8d80e7140fcb3ef00544189830913ee4fe1b6fbd
refs/heads/master
2021-01-20T08:29:33.813189
2017-05-03T13:35:49
2017-05-03T13:35:49
90,151,855
0
0
null
null
null
null
UTF-8
C++
false
false
370
h
#ifndef MANAGECARD_H #define MANAGECARD_H #include <QDialog> namespace Ui { class ManageCard; } class ManageCard : public QDialog { Q_OBJECT public: explicit ManageCard(QWidget *parent = 0); ~ManageCard(); private slots: void on_pushButton_clicked(); void on_pushButton_2_clicked(); private: Ui::ManageCard *ui; }; #endif // MANAGECARD_H
f85797e6dbd336087afb8f1c6cd526685bd1e599
d17a8870ff8ac77b82d0d37e20c85b23aa29ca74
/lite/core/optimizer/mir/__xpu__quantization_parameters_propagation_pass.cc
5098391f965b5d7abef074a5f260a0a509569066
[ "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
18,614
cc
// Copyright (c) 2023 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/__xpu__quantization_parameters_propagation_pass.h" #include <cmath> #include <set> #include <string> #include <unordered_map> #include <unordered_set> #include <vector> #include "lite/core/optimizer/mir/graph_visualize_pass.h" #include "lite/core/optimizer/mir/pass_registry.h" namespace paddle { namespace lite { namespace mir { static bool HasOutputThreshold(const OpInfo* op_info, const std::string& name, bool is_threshold_name) { bool res = false; if (is_threshold_name) { res = op_info->HasAttr(name); } else { std::string argname; int index; if (op_info->HasAttr("out_threshold")) { res = true; } else if (op_info->GetOutputArgname(name, &argname) && op_info->GetOutputIndex(name, &index)) { res = op_info->HasAttr(argname + to_string(index) + "_threshold"); } } return res; } static float GetOutputThreshold(const OpInfo* op_info, const std::string& name, bool is_threshold_name) { std::string threshold_name; if (is_threshold_name) { threshold_name = name; } else if (op_info->HasAttr("out_threshold")) { threshold_name = "out_threshold"; } else { std::string arg_name; int arg_index; CHECK(op_info->GetOutputArgname(name, &arg_name)); CHECK(op_info->GetOutputIndex(name, &arg_index)); threshold_name = arg_name + to_string(arg_index) + "_threshold"; } float threshold = 0.0; if (op_info->GetAttrType(threshold_name) == OpDescAPI::AttrType::FLOAT) { threshold = op_info->GetAttr<float>(threshold_name); } else if (op_info->GetAttrType(threshold_name) == OpDescAPI::AttrType::FLOATS) { threshold = op_info->GetAttr<std::vector<float>>(threshold_name)[0]; } return threshold; } // Complete the output scale from the input scale of its consumer ops. static bool SetOutScaleFromNextInScale( const std::unique_ptr<SSAGraph>& graph, int auto_complete_quant_scale_level = 0) { bool found = false; for (auto& op_node : graph->StmtTopologicalOrder()) { if (!op_node->IsStmt()) continue; auto op_info = op_node->AsStmt().mutable_op_info(); for (auto in_var_node : op_node->inlinks) { CHECK(in_var_node->IsArg()); auto in_var_name = in_var_node->arg()->name; if (!op_info->HasInputScale(in_var_name)) continue; auto in_var_scale = op_info->GetInputScale(in_var_name); for (auto in_op_node : in_var_node->inlinks) { if (!in_op_node->IsStmt()) continue; auto in_op_info = in_op_node->AsStmt().mutable_op_info(); bool in_op_is_quanted = HasOutputThreshold(in_op_info, in_var_name, false); auto in_op_in_vars = in_op_node->inlinks; for (auto in_op_in_var : in_op_in_vars) { in_op_is_quanted = in_op_is_quanted || in_op_info->HasInputScale(in_op_in_var->arg()->name); } in_op_is_quanted = in_op_is_quanted || auto_complete_quant_scale_level >= 1; if (in_op_is_quanted) { // Use this input scale to update the output scale of the quantized op in_op_info->SetOutputScale(in_var_name, in_var_scale); found = true; } } } } return found; } // Complete the output scale from the user-defined configurations. static bool SetOutScaleFromConfigs( const std::unique_ptr<SSAGraph>& graph, const std::string& auto_complete_quant_scale_configs) { if (auto_complete_quant_scale_configs.empty()) return false; std::unordered_map<std::string, float> var_nodes; const auto& lines = Split(auto_complete_quant_scale_configs, "\n"); for (const auto& line : lines) { const auto& items = Split(line, "-"); if (items.empty()) continue; for (const auto& item : items) { if (item.empty()) continue; const auto& vars = Split(item, ","); for (const auto& var : vars) { auto info = Split(var, ":"); CHECK_EQ(info.size(), 2); auto& out_var_name = info[0]; auto out_threshold = parse_string<float>(info[1]); CHECK_GT(out_threshold, 0); CHECK(!var_nodes.count(out_var_name)); var_nodes[out_var_name] = out_threshold; } } } if (var_nodes.empty()) return false; bool found = false; for (auto& op_node : graph->StmtTopologicalOrder()) { if (!op_node->IsStmt()) continue; auto op_info = op_node->AsStmt().mutable_op_info(); for (auto out_var_node : op_node->outlinks) { CHECK(out_var_node->IsArg()); auto out_var_name = out_var_node->arg()->name; if (op_info->HasOutputScale(out_var_name)) continue; if (!var_nodes.count(out_var_name)) continue; int bit_length = 8; // op_info->GetAttr<int>("bit_length"); int range = (1 << (bit_length - 1)) - 1; auto out_var_scale = std::vector<float>{var_nodes.at(out_var_name) / range}; op_info->SetOutputScale(out_var_name, out_var_scale); found = true; } } return found; } // Complete the output scale from its out_threshold attribute. static bool SetOutScaleFromCurOutThreshold( const std::unique_ptr<SSAGraph>& graph) { bool found = false; for (auto& op_node : graph->StmtTopologicalOrder()) { if (!op_node->IsStmt()) continue; auto op_info = op_node->AsStmt().mutable_op_info(); for (auto out_var_node : op_node->outlinks) { CHECK(out_var_node->IsArg()); auto out_var_name = out_var_node->arg()->name; if (op_info->HasOutputScale(out_var_name)) continue; // skip if the output scale had been already set if (!HasOutputThreshold(op_info, out_var_name, false)) continue; // If it's a quantized op, calculate its output scale according to the // output threshold(abs_max value) int bit_length = 8; // op_info->GetAttr<int>("bit_length"); int range = (1 << (bit_length - 1)) - 1; auto out_var_scale = std::vector<float>{ GetOutputThreshold(op_info, out_var_name, false) / range}; op_info->SetOutputScale(out_var_name, out_var_scale); found = true; } } return found; } // Complete the input scale from the output scale of its producer op. static bool SetInScaleFromPrevOutScale(const std::unique_ptr<SSAGraph>& graph) { bool found = false; for (auto& op_node : graph->StmtTopologicalOrder()) { if (!op_node->IsStmt()) continue; auto op_info = op_node->AsStmt().mutable_op_info(); for (auto in_var_node : op_node->inlinks) { CHECK(in_var_node->IsArg()); auto in_var_name = in_var_node->arg()->name; if (op_info->HasInputScale(in_var_name)) continue; std::vector<float> in_var_scale; for (auto in_op_node : in_var_node->inlinks) { if (!in_op_node->IsStmt()) continue; auto in_op_info = in_op_node->AsStmt().mutable_op_info(); if (!in_op_info->HasOutputScale(in_var_name)) continue; auto candidate_var_scale = in_op_info->GetOutputScale(in_var_name); if (!in_var_scale.empty()) { auto scale_size = in_var_scale.size(); CHECK_EQ(scale_size, candidate_var_scale.size()); for (size_t i = 0; i < scale_size; i++) { CHECK(fabs(in_var_scale[i] - candidate_var_scale[i]) <= 1e-7f); } } else { in_var_scale = candidate_var_scale; } } if (!in_var_scale.empty()) { op_info->SetInputScale(in_var_name, in_var_scale); found = true; } } } return found; } // Complete the output scale according to the input scale, because the input // scale and output scale of the ops should be the same. static bool SetOutScaleFromCurInScale( const std::unique_ptr<SSAGraph>& graph, const std::unordered_map<std::string, std::unordered_map<std::string, std::string>>& op_types) { bool found = false; for (auto& op_node : graph->StmtTopologicalOrder()) { if (!op_node->IsStmt()) continue; auto op_info = op_node->AsStmt().mutable_op_info(); auto op_type = op_info->Type(); if (!op_types.count(op_type)) continue; for (auto out_var_node : op_node->outlinks) { CHECK(out_var_node->IsArg()); auto out_var_name = out_var_node->arg()->name; if (op_info->HasOutputScale(out_var_name)) continue; std::string out_arg_name; if (!op_info->GetOutputArgname(out_var_name, &out_arg_name)) continue; for (auto in_var_node : op_node->inlinks) { CHECK(in_var_node->IsArg()); auto in_var_name = in_var_node->arg()->name; if (!op_info->HasInputScale(in_var_name)) continue; std::string in_arg_name; if (!op_info->GetInputArgname(in_var_name, &in_arg_name)) continue; if (!op_types.at(op_type).count(in_arg_name)) continue; if (op_types.at(op_type).at(in_arg_name) != out_arg_name) continue; op_info->SetOutputScale(out_var_name, op_info->GetInputScale(in_var_name)); found = true; break; } } } return found; } // Complete the input scale according to the output scale, because the input // scale and output scale of the ops should be the same. static bool SetInScaleFromCurOutScale( const std::unique_ptr<SSAGraph>& graph, const std::unordered_map<std::string, std::unordered_map<std::string, std::string>>& op_types) { bool found = false; for (auto& op_node : graph->StmtTopologicalOrder()) { if (!op_node->IsStmt()) continue; auto op_info = op_node->AsStmt().mutable_op_info(); auto op_type = op_info->Type(); if (!op_types.count(op_type)) continue; for (auto in_var_node : op_node->inlinks) { CHECK(in_var_node->IsArg()); auto in_var_name = in_var_node->arg()->name; if (op_info->HasInputScale(in_var_name)) continue; std::string in_arg_name; if (!op_info->GetInputArgname(in_var_name, &in_arg_name)) continue; if (!op_types.at(op_type).count(in_arg_name)) continue; for (auto out_var_node : op_node->outlinks) { CHECK(out_var_node->IsArg()); auto out_var_name = out_var_node->arg()->name; if (!op_info->HasOutputScale(out_var_name)) continue; std::string out_arg_name; if (!op_info->GetOutputArgname(out_var_name, &out_arg_name)) continue; if (op_types.at(op_type).at(in_arg_name) != out_arg_name) continue; op_info->SetInputScale(in_var_name, op_info->GetOutputScale(out_var_name)); found = true; break; } } } return found; } // Complete the output scale according to the formula of some special ops // themselves. static bool SetOutScaleFromSpecialOps(const std::unique_ptr<SSAGraph>& graph) { const std::unordered_set<std::string> op_types{"relu6", "softmax"}; bool found = false; for (auto& op_node : graph->StmtTopologicalOrder()) { if (!op_node->IsStmt()) continue; auto op_info = op_node->AsStmt().mutable_op_info(); auto op_type = op_info->Type(); if (!op_types.count(op_type)) continue; for (auto out_var_node : op_node->outlinks) { CHECK(out_var_node->IsArg()); auto out_var_name = out_var_node->arg()->name; if (op_info->HasOutputScale(out_var_name)) continue; std::string out_arg_name; if (!op_info->GetOutputArgname(out_var_name, &out_arg_name)) continue; float out_threshold; if (op_type == "relu6" && out_arg_name == "Out") { out_threshold = 6.0f; } else if (op_type == "softmax" && out_arg_name == "Out") { out_threshold = 1.0f; } else { continue; } int bit_length = 8; // op_info->GetAttr<int>("bit_length"); int range = (1 << (bit_length - 1)) - 1; auto out_var_scale = std::vector<float>{out_threshold / range}; op_info->SetOutputScale(out_var_name, out_var_scale); found = true; } } return found; } // Print variables without outscale static void PrintVariablesWithoutOutScale( const std::unique_ptr<SSAGraph>& graph) { std::ostringstream os; for (auto& op_node : graph->StmtTopologicalOrder()) { if (!op_node->IsStmt()) continue; auto op_info = op_node->AsStmt().mutable_op_info(); auto op_type = op_info->Type(); for (auto out_var_node : op_node->outlinks) { CHECK(out_var_node->IsArg()); auto out_var_name = out_var_node->arg()->name; if (op_info->HasOutputScale(out_var_name)) continue; if (out_var_node->outlinks.size() > 0) os << out_var_name << "\n"; } } VLOG(5) << "\nVariables without outscale:\n" << os.str(); } void XPUQuantizationParametersPropagationPass::ResetScale( const std::unique_ptr<SSAGraph>& graph) { for (auto& op_node : graph->StmtTopologicalOrder()) { if (!op_node->IsStmt()) continue; auto op_info = op_node->AsStmt().mutable_op_info(); auto op_type = op_info->Type(); int bit_length = 8; // op_info->GetAttr<int>("bit_length"); int range = (1 << (bit_length - 1)) - 1; // Reset intput/output sclae value,thanks to lite quant pass. for (auto in_var_node : op_node->inlinks) { CHECK(in_var_node->IsArg()); auto in_var_name = in_var_node->arg()->name; if (!op_info->HasInputScale(in_var_name)) continue; auto in_var_scale = op_info->GetInputScale(in_var_name); for (int i = 0; i < in_var_scale.size(); i++) { in_var_scale[i] = in_var_scale[i] * range; } op_info->SetInputScale(in_var_name, in_var_scale); } for (auto out_var_node : op_node->outlinks) { CHECK(out_var_node->IsArg()); auto out_var_name = out_var_node->arg()->name; if (!op_info->HasOutputScale(out_var_name)) continue; auto out_var_scale = op_info->GetOutputScale(out_var_name); for (int i = 0; i < out_var_scale.size(); i++) { out_var_scale[i] = out_var_scale[i] * range; } op_info->SetOutputScale(out_var_name, out_var_scale); } } } void XPUQuantizationParametersPropagationPass::Apply( const std::unique_ptr<SSAGraph>& graph) { VLOG(5) << "\n" << Visualize(graph.get()); // Due to various reasons (such as bugs from PaddleSlim), some ops in // the // model lack quantization parameters. Optionally, the missing // quantization // parameters can be completed by the following rules. auto auto_complete_quant_scale_level = GetIntFromEnv(QUANT_AUTO_COMPLETE_SCALE_LEVEL); // (a) Complete the output scale from the input scale of its consumer // ops. SetOutScaleFromNextInScale(graph, auto_complete_quant_scale_level); // (b) Complete the output scale from the user - // defined configurations. auto auto_complete_quant_scale_configs = GetConfigsFromEnv(QUANT_AUTO_COMPLETE_SCALE_CONFIG_FILE, QUANT_AUTO_COMPLETE_SCALE_CONFIG_BUFFER); if (!auto_complete_quant_scale_configs.empty()) { SetOutScaleFromConfigs(graph, auto_complete_quant_scale_configs); } // (c) Complete the output scale from its out_threshold attribute. SetOutScaleFromCurOutThreshold(graph); // (d) Complete the input scale from the output scale of its producer // op. SetInScaleFromPrevOutScale(graph); // (e) Reset all scale(* 127) in xpu op. ResetScale(graph); // (f) Complete the output scale according to the input scale, or // complete // the input scale according to the output scale, because the input // scale and // output scale of some ops should be the same. const std::unordered_map<std::string, std::unordered_map<std::string, std::string>> in_scale_same_as_out_scale_ops{ {"transpose", {{"X", "Out"}}}, {"transpose2", {{"X", "Out"}}}, {"squeeze", {{"X", "Out"}}}, {"squeeze2", {{"X", "Out"}}}, {"unsqueeze", {{"X", "Out"}}}, {"unsqueeze2", {{"X", "Out"}}}, {"reshape", {{"X", "Out"}}}, {"reshape2", {{"X", "Out"}}}, {"flatten", {{"X", "Out"}}}, {"flatten2", {{"X", "Out"}}}, {"flatten_contiguous_range", {{"X", "Out"}}}, {"expand", {{"X", "Out"}}}, {"expand_v2", {{"X", "Out"}}}, {"bilinear_interp", {{"X", "Out"}}}, {"bilinear_interp_v2", {{"X", "Out"}}}, {"nearest_interp", {{"X", "Out"}}}, {"nearest_interp_v2", {{"X", "Out"}}}, {"pool2d", {{"X", "Out"}}}, {"leaky_relu", {{"X", "Out"}}}, {"relu", {{"X", "Out"}}}}; if (auto_complete_quant_scale_level >= 2) { bool found = true; do { found = SetOutScaleFromCurInScale(graph, in_scale_same_as_out_scale_ops); SetInScaleFromPrevOutScale(graph); } while (found); do { found = SetInScaleFromCurOutScale(graph, in_scale_same_as_out_scale_ops); SetOutScaleFromNextInScale(graph, auto_complete_quant_scale_level); } while (found); } // (g) Complete the output scale according to the formula of some // special ops // themselves. if (auto_complete_quant_scale_level >= 3) { SetOutScaleFromSpecialOps(graph); SetInScaleFromPrevOutScale(graph); bool found = true; do { found = SetOutScaleFromCurInScale(graph, in_scale_same_as_out_scale_ops); SetInScaleFromPrevOutScale(graph); } while (found); do { found = SetInScaleFromCurOutScale(graph, in_scale_same_as_out_scale_ops); SetOutScaleFromNextInScale(graph, auto_complete_quant_scale_level); } while (found); } // Print variables without outscale to help users set out threshold // manually PrintVariablesWithoutOutScale(graph); VLOG(5) << "\n" << Visualize(graph.get()); } } // namespace mir } // namespace lite } // namespace paddle REGISTER_MIR_PASS(__xpu__quantization_parameters_propagation_pass, paddle::lite::mir::XPUQuantizationParametersPropagationPass) .BindTargets({TARGET(kXPU)});
ad928a4245e965e8490d9b284bcbe1a0e389ef7f
fcc4255330e54117e785fe4f9ad7f03f13e9b59f
/practice/cpp/divide_and_conquer/largest_rectangle_in_histogram.cpp
71b28422e4de0885ca9030ff5ea07f25006b9b7b
[]
no_license
truongpt/warm_up
f5cc018e997e7edefe2802c6e346366e32c41b35
47c5694537fbe32ed389e82c862e283b90a9066d
refs/heads/master
2023-07-18T11:10:22.978036
2021-09-02T20:32:04
2021-09-02T20:32:04
242,413,021
4
0
null
null
null
null
UTF-8
C++
false
false
1,133
cpp
/* - Problem: https://leetcode.com/problems/largest-rectangle-in-histogram/ - Solution: - [2,1,5,6,2,3]. ^ - Find minimum value element of array -> min value. - result = max ( min value * size of array, recursive left side, recursive right side) */ #include <iostream> #include <vector> #include <algorithm> using namespace std; int getMaxArea(vector<int>& heights, int start, int end) { if (start > end) { return 0; } int min_index = start; int min_value = heights[min_index]; for (int i = start; i <= end; i++) { if (heights[i] < min_value) { min_value = heights[i]; min_index = i; } } int base_value = min_value * (end - start + 1); return max(base_value, max(getMaxArea(heights, start, min_index-1), getMaxArea(heights, min_index+1, end)) ); } int largestRectangle(vector<int>& heights) { return getMaxArea(heights, 0, heights.size()-1); } int main(void) { vector<int> heights = {2,1,5,6,2,3}; cout << largestRectangle(heights) << endl; }
feffef2f8bfaa0612d9a6d0ff609e4a1bf6b9efa
1b81a18199c9ed8af1deeddcac9e60503b39319c
/ladder2c/ap.cpp
79ed1271b40e4c20ffc84842f436d667c01336dc
[]
no_license
ayushsawlani/codeforces
50948375f86738ffd5e8b6a6b0fa77ed51691f8a
4eebdf5143156ead2a287531abdab3aee0663f2d
refs/heads/master
2022-12-10T21:15:36.881289
2020-09-13T13:05:47
2020-09-13T13:05:47
285,869,577
0
0
null
null
null
null
UTF-8
C++
false
false
1,496
cpp
#include <bits/stdc++.h> using namespace std; #define ll long long int main() { ll n; cin>>n; ll a[n]; for(ll i=0;i<n;i++) { cin>>a[i]; } if(n==1) { cout<<-1<<endl; return 0; } sort(a,a+n); ll d[n-1]; map <ll,ll> m; for(ll i=0;i<n-1;i++) { d[i]=a[i+1]-a[i]; if(m.find(d[i])!=m.end()) { m[d[i]]++; } else { m[d[i]]=1; } } vector <ll> v; if(m.size()>2) { cout<<0<<endl; return 0; } else if(m.size()==1) { v.push_back(a[0]-d[0]); if(d[0]!=0) v.push_back(a[n-1]+d[0]); if(n==2) { if((d[0]%2==0)&&(d[0]!=0)) { v.push_back(a[0]+d[0]/2); } } } else { ll x[2]; x[0]=d[0]; for(ll i=1;i<n-1;i++) { if(d[i]!=x[0]) { x[1]=d[i]; break; } } sort(x,x+2); if((x[1]!=x[0]*2)||(m[x[1]]>1)) { cout<<0<<endl; return 0; } else { ll i=0; while(d[i]!=x[1]) { i++; } v.push_back(a[i]+x[0]); } } sort(v.begin(),v.end()); cout<<v.size()<<endl; for(ll i=0;i<v.size();i++) cout<<v[i]<<" "; cout<<endl; }
521fb4a842db0971a1bf05569327bd1ea2bfb3dd
6bd9d7679011042f46104d97080786423ae58879
/1000/a/a.cc
774cd205983ed7109c30e50e90a6c25f2f4fce20
[ "CC-BY-4.0" ]
permissive
lucifer1004/codeforces
20b77bdd707a1e04bc5b1230f5feb4452d5f4c78
d1fe331d98d6d379723939db287a499dff24c519
refs/heads/master
2023-04-28T16:00:37.673566
2023-04-17T03:40:27
2023-04-17T03:40:27
212,258,015
3
1
null
2020-10-27T06:54:02
2019-10-02T04:53:36
C++
UTF-8
C++
false
false
552
cc
#include <iostream> #include <unordered_map> using namespace std; typedef long long ll; class Solution { public: void solve() { int n; cin >> n; unordered_map<string, int> cnt; string size; for (int i = 0; i < n; ++i) { cin >> size; cnt[size]++; } for (int i = 0; i < n; ++i) { cin >> size; cnt[size]--; } int ans = 0; for (auto p : cnt) { if (p.second < 0) ans -= p.second; } cout << ans; } }; int main() { Solution solution = Solution(); solution.solve(); }
c869e94a6c3376f0309f565fd3424c377d0f8be1
46f53e9a564192eed2f40dc927af6448f8608d13
/components/nacl/broker/nacl_broker_listener.cc
6dec3e6563621ea2864dbbe6a25ae5b4c2b7bd68
[ "BSD-3-Clause" ]
permissive
sgraham/nope
deb2d106a090d71ae882ac1e32e7c371f42eaca9
f974e0c234388a330aab71a3e5bbf33c4dcfc33c
refs/heads/master
2022-12-21T01:44:15.776329
2015-03-23T17:25:47
2015-03-23T17:25:47
32,344,868
2
2
null
null
null
null
UTF-8
C++
false
false
5,232
cc
// Copyright 2013 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 "components/nacl/broker/nacl_broker_listener.h" #include "base/base_switches.h" #include "base/bind.h" #include "base/command_line.h" #include "base/message_loop/message_loop.h" #include "base/message_loop/message_loop_proxy.h" #include "base/path_service.h" #include "base/process/process.h" #include "base/process/process_handle.h" #include "components/nacl/common/nacl_cmd_line.h" #include "components/nacl/common/nacl_debug_exception_handler_win.h" #include "components/nacl/common/nacl_messages.h" #include "components/nacl/common/nacl_switches.h" #include "content/public/common/content_switches.h" #include "content/public/common/sandbox_init.h" #include "ipc/ipc_channel.h" #include "ipc/ipc_switches.h" #include "sandbox/win/src/sandbox_policy.h" namespace { void SendReply(IPC::Channel* channel, int32 pid, bool result) { channel->Send(new NaClProcessMsg_DebugExceptionHandlerLaunched(pid, result)); } } // namespace NaClBrokerListener::NaClBrokerListener() { } NaClBrokerListener::~NaClBrokerListener() { } void NaClBrokerListener::Listen() { std::string channel_name = base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kProcessChannelID); channel_ = IPC::Channel::CreateClient(channel_name, this); CHECK(channel_->Connect()); base::MessageLoop::current()->Run(); } // NOTE: changes to this method need to be reviewed by the security team. void NaClBrokerListener::PreSpawnTarget(sandbox::TargetPolicy* policy, bool* success) { // This code is duplicated in chrome_content_browser_client.cc. // Allow the server side of a pipe restricted to the "chrome.nacl." // namespace so that it cannot impersonate other system or other chrome // service pipes. sandbox::ResultCode result = policy->AddRule( sandbox::TargetPolicy::SUBSYS_NAMED_PIPES, sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY, L"\\\\.\\pipe\\chrome.nacl.*"); *success = (result == sandbox::SBOX_ALL_OK); } void NaClBrokerListener::OnChannelConnected(int32 peer_pid) { browser_process_ = base::Process::OpenWithExtraPriviles(peer_pid); CHECK(browser_process_.IsValid()); } bool NaClBrokerListener::OnMessageReceived(const IPC::Message& msg) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(NaClBrokerListener, msg) IPC_MESSAGE_HANDLER(NaClProcessMsg_LaunchLoaderThroughBroker, OnLaunchLoaderThroughBroker) IPC_MESSAGE_HANDLER(NaClProcessMsg_LaunchDebugExceptionHandler, OnLaunchDebugExceptionHandler) IPC_MESSAGE_HANDLER(NaClProcessMsg_StopBroker, OnStopBroker) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void NaClBrokerListener::OnChannelError() { // The browser died unexpectedly, quit to avoid a zombie process. base::MessageLoop::current()->Quit(); } void NaClBrokerListener::OnLaunchLoaderThroughBroker( const std::string& loader_channel_id) { base::ProcessHandle loader_handle_in_browser = 0; // Create the path to the nacl broker/loader executable - it's the executable // this code is running in. base::FilePath exe_path; PathService::Get(base::FILE_EXE, &exe_path); if (!exe_path.empty()) { base::CommandLine* cmd_line = new base::CommandLine(exe_path); nacl::CopyNaClCommandLineArguments(cmd_line); cmd_line->AppendSwitchASCII(switches::kProcessType, switches::kNaClLoaderProcess); cmd_line->AppendSwitchASCII(switches::kProcessChannelID, loader_channel_id); base::Process loader_process = content::StartSandboxedProcess(this, cmd_line); if (loader_process.IsValid()) { // Note: PROCESS_DUP_HANDLE is necessary here, because: // 1) The current process is the broker, which is the loader's parent. // 2) The browser is not the loader's parent, and so only gets the // access rights we confer here. // 3) The browser calls DuplicateHandle to set up communications with // the loader. // 4) The target process handle to DuplicateHandle needs to have // PROCESS_DUP_HANDLE access rights. DuplicateHandle( ::GetCurrentProcess(), loader_process.Handle(), browser_process_.Handle(), &loader_handle_in_browser, PROCESS_DUP_HANDLE | PROCESS_QUERY_INFORMATION | PROCESS_TERMINATE, FALSE, 0); } } channel_->Send(new NaClProcessMsg_LoaderLaunched(loader_channel_id, loader_handle_in_browser)); } void NaClBrokerListener::OnLaunchDebugExceptionHandler( int32 pid, base::ProcessHandle process_handle, const std::string& startup_info) { NaClStartDebugExceptionHandlerThread( base::Process(process_handle), startup_info, base::MessageLoopProxy::current(), base::Bind(SendReply, channel_.get(), pid)); } void NaClBrokerListener::OnStopBroker() { base::MessageLoop::current()->Quit(); }
630931858bd1d2bdbb93f3268c27594d4bbda5bc
5ca7c30e1ab250c981eda169d4712f632c7b6061
/flecsi-tutorial/05-sparse-data/sparse-data.cc
50998b1b48bfe28d3168dafd1a756d0fc40ad8ea
[ "BSD-2-Clause" ]
permissive
tylerjereddy/flecsi
4cf92bcc86903eeac20f26b6ebd24e7cadbd32d8
4e0f9d89ccec984c1ae96e490687ccf99ba11415
refs/heads/master
2021-05-05T05:03:23.389572
2018-01-23T04:38:52
2018-01-23T04:38:52
118,654,984
0
0
null
2018-01-23T18:58:22
2018-01-23T18:58:21
null
UTF-8
C++
false
false
2,131
cc
/* @@@@@@@@ @@ @@@@@@ @@@@@@@@ @@ /@@///// /@@ @@////@@ @@////// /@@ /@@ /@@ @@@@@ @@ // /@@ /@@ /@@@@@@@ /@@ @@///@@/@@ /@@@@@@@@@/@@ /@@//// /@@/@@@@@@@/@@ ////////@@/@@ /@@ /@@/@@//// //@@ @@ /@@/@@ /@@ @@@//@@@@@@ //@@@@@@ @@@@@@@@ /@@ // /// ////// ////// //////// // Copyright (c) 2016, Los Alamos National Security, LLC All rights reserved. */ #include <cstdlib> #include <iostream> #include<flecsi-tutorial/specialization/mesh/mesh.h> #include<flecsi/data/data.h> #include<flecsi/execution/execution.h> using namespace flecsi; using namespace flecsi::tutorial; flecsi_register_data_client(mesh_t, clients, mesh); flecsi_register_field(mesh_t, hydro, densities, double, sparse, 1, cells); namespace hydro { void initialize_materials(mesh<ro> mesh, sparse_field_mutator d) { for(auto c: mesh.cells()) { const size_t random = (rand()/double{RAND_MAX}) * 5; for(size_t i{0}; i<random; ++i) { const size_t index = (rand()/double{RAND_MAX}) * 5; d(c,index) = index; } // for } // for } // initialize_pressure flecsi_register_task(initialize_materials, hydro, loc, single); void print_materials(mesh<ro> mesh, sparse_field<ro> d) { for(auto c: mesh.cells()) { for(auto m: d.entries(c)) { std::cout << d(c,m) << " "; } // for std::cout << std::endl; } // for } // print_pressure flecsi_register_task(print_materials, hydro, loc, single); } // namespace hydro namespace flecsi { namespace execution { void driver(int argc, char ** argv) { auto m = flecsi_get_client_handle(mesh_t, clients, mesh); { auto d = flecsi_get_mutator(m, hydro, densities, double, sparse, 0, 5); flecsi_execute_task(initialize_materials, hydro, single, m, d); } // scope { auto d = flecsi_get_handle(m, hydro, densities, double, sparse, 0); flecsi_execute_task(print_materials, hydro, single, m, d); } // scope } // driver } // namespace execution } // namespace flecsi
51c76b3c58d48a568bf34a725e07738995a52a61
65b94c7a4f68171738b5c66c4d53fd8af4cdeb8e
/MFCApplication4/MFCApplication4/MFCApplication4View.cpp
1846c92687b034df260171d9bd1b8e83cdb5c793
[]
no_license
shaovoon/asan_mfc_sdi_mdi_crash
a8a5cf162cc98f751a03f76bde9e5fcccef4a2b2
10d275e21d931e661afb069a94241af9396730b7
refs/heads/master
2022-12-03T06:39:44.852589
2020-08-17T12:44:59
2020-08-17T12:44:59
288,171,122
0
0
null
null
null
null
UTF-8
C++
false
false
2,799
cpp
// MFCApplication4View.cpp : implementation of the CMFCApplication4View class // #include "pch.h" #include "framework.h" // SHARED_HANDLERS can be defined in an ATL project implementing preview, thumbnail // and search filter handlers and allows sharing of document code with that project. #ifndef SHARED_HANDLERS #include "MFCApplication4.h" #endif #include "MFCApplication4Doc.h" #include "MFCApplication4View.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CMFCApplication4View IMPLEMENT_DYNCREATE(CMFCApplication4View, CView) BEGIN_MESSAGE_MAP(CMFCApplication4View, CView) // Standard printing commands ON_COMMAND(ID_FILE_PRINT, &CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, &CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, &CMFCApplication4View::OnFilePrintPreview) ON_WM_CONTEXTMENU() ON_WM_RBUTTONUP() END_MESSAGE_MAP() // CMFCApplication4View construction/destruction CMFCApplication4View::CMFCApplication4View() noexcept { // TODO: add construction code here } CMFCApplication4View::~CMFCApplication4View() { } BOOL CMFCApplication4View::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs return CView::PreCreateWindow(cs); } // CMFCApplication4View drawing void CMFCApplication4View::OnDraw(CDC* /*pDC*/) { CMFCApplication4Doc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; // TODO: add draw code for native data here } // CMFCApplication4View printing void CMFCApplication4View::OnFilePrintPreview() { #ifndef SHARED_HANDLERS AFXPrintPreview(this); #endif } BOOL CMFCApplication4View::OnPreparePrinting(CPrintInfo* pInfo) { // default preparation return DoPreparePrinting(pInfo); } void CMFCApplication4View::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add extra initialization before printing } void CMFCApplication4View::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add cleanup after printing } void CMFCApplication4View::OnRButtonUp(UINT /* nFlags */, CPoint point) { ClientToScreen(&point); OnContextMenu(this, point); } void CMFCApplication4View::OnContextMenu(CWnd* /* pWnd */, CPoint point) { #ifndef SHARED_HANDLERS theApp.GetContextMenuManager()->ShowPopupMenu(IDR_POPUP_EDIT, point.x, point.y, this, TRUE); #endif } // CMFCApplication4View diagnostics #ifdef _DEBUG void CMFCApplication4View::AssertValid() const { CView::AssertValid(); } void CMFCApplication4View::Dump(CDumpContext& dc) const { CView::Dump(dc); } CMFCApplication4Doc* CMFCApplication4View::GetDocument() const // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CMFCApplication4Doc))); return (CMFCApplication4Doc*)m_pDocument; } #endif //_DEBUG // CMFCApplication4View message handlers
7138a09ab257674f0cb3d0f150e95c344bf1ef3f
985369eae7de2dfafdf2528332c670c30fd10eac
/src/VisionTargetPair.cpp
3673ca7ef3f39c85bb255e91cdcbf2d25a1eaf58
[]
no_license
valentinBeynard/Raspberry_Visio_V1
743788e25f2ec19e6d100ebbbb107dc93aa812d2
7413cdb3c13220837be121074d7b652373167ea7
refs/heads/master
2020-04-22T01:20:06.175640
2019-02-10T18:30:47
2019-02-10T18:30:47
170,011,280
0
0
null
null
null
null
UTF-8
C++
false
false
14,914
cpp
#include "VisionTargetPair.h" #include "Tools.h" #include "Values.h" const float VisionTargetPair::assemble(VisionTarget * pshapeA, VisionTarget * pshapeB) { Point2f topv, basev; float f, basenorm,topnorm; // setup m_pvisionTargetA = pshapeA; m_pvisionTargetB = pshapeB; m_quality = 0.0f; float nb = 0.0f; // nombre de notes attribu�es. // ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // Angle apparent entre les deux shapes: // ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // 1: L'angle est-il "bien" ou "mal" orient� ? // X product VT1.n1 x VT2.n1 < 0 signifie que l'angle entre les deux visions target est 'bien' orient� ( l'angle entre les deux vecteurs est ouvert en bas ) // X product VT1.n1 x VT2.n1 > 0 signifie que l'angle entre les deux visions target est 'mal' orient� ( l'angle entre les deux vecteurs est ouvert en haut/ferm� en bas ) // // ..... ..... ..... ..... // / / \ \ \ \ / / // / / \ \ \ \ / / // / / \ \ \ \ / / // / / \ \ \ \ / / // ..... ..... ..... ..... // // Bien orient� Mal orient� if (m_pvisionTargetA->n01.cross(m_pvisionTargetB->n01) > 0.0f) { // Angle mal orient� m_quality = -1.0f; return -1.0f; } else { // Angle Bien Orient�: m_quality += 1.0f; nb += 1.0f; } #ifdef PRECOMPIL_LOGICFILTER_VISIONTARGETPAIR_VISIONTARGETS_ANGLE_TOO_LARGE // 2: L'angle est-il a "peu pr�s" bon ? C'est � dire ne semble t'il pas "TROP grand" entre les deux Vision target? // Dot Product, VT1.n1 � VT2.n1 < limit signifie que l'angle est trop grand. // rappel: // Les deux vecteurs m_pvisionTargetA->n01 et m_pvisionTargetB->n01 sont normalis� ( longeur = 1 ) donc leur produit scalaire est �gal au cosinus de l'angle entre eux. // -Dot product = 1 signifie que les deux vecteurs sont align�s (angle = 0)et regardent dans la m^zmz direction // -Dot product = 0 signifie que les deux vecteur forment un angle de 90�. // -Dot product = -1 signifie que les deux vecteur sont align�s (angle = 180�) mais oppos�s // -Plus l'angle est ferm� et plus le dot product se rapproche de 1, plus l'angle est ouvert et plus il se rapproche de -1. // L'angle r�el entre les deux vision target est d'environ 14.5 deg ( cos(14.5 deg) = 0.96814 ), mais une fois projet� ( vue perspective ) il pourra sembl� plus �troit ( angle < 14.5) , peut �tre m�me l�g�rement plus grand dans certain cas ( angle > 14.5 )... // pour un angle de 30� entre les deux vision target ( ce qui correspond environ au double de l'angle r�el) on obtient un Dot Product de 0.8660f ( cos(30 deg) = 0.8660 ... ) f = m_pvisionTargetA->n01.dot(m_pvisionTargetB->n01); if (f < VISIONTARGET1_DOT_VISIONTARGET2_UNDERLIMIT) { // Angle trop grand m_quality = -1.0f; return -1.0f; } else { // Angle apparement correct: // Comparons le cosinus de cet angle avec le cosinus Etalon, c'est � dire celui d'un couple de Vision target pleinement de face. ( cos( 14.5deg ) = 0.96814 . // l'objectif, attribuer la note de 1 si l'angle est �gal � celui de l'�talon et d�gressive jusqu'� la limite base ( note = 0.0f ). // Notez que la note sera �galement d�gressive si l'angle est plus grand que l'angle Etalon. f = fabs( f - VISIONTARGET1_DOT_VISIONTARGET2_STANDARD); m_quality += 1.0f - f / (VISIONTARGET1_DOT_VISIONTARGET2_STANDARD - VISIONTARGET1_DOT_VISIONTARGET2_UNDERLIMIT); nb += 1.0f; } #endif #ifdef PRECOMPIL_LOGICFILTER_VISIONTARGETPAIR_HIGH_RATIO // ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // Rapports remarquables // ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // Rapport des "hauteurs" // Les deux visions targets sont identiques, � l'exception de leur orientation (symetrique / l'axe verticale ). // Une fois projet�es, les deux visions target d'un m�me couple (suppos�) auront certes une l�g�re difference de taille ( la VT la plus pr�s de la camera apparaitra plus grosse) mais cette diff�rence // reste "l�g�re", particuli�rement sur la "hauteur". Donc une trop grande diff�rence de hauteur entre deux VT d'un m�me couple suppos� peut �tre un bon indicateur pour invalider ce couple. f = MIN(m_pvisionTargetA->norm01, m_pvisionTargetB->norm01) / MAX(m_pvisionTargetA->norm01, m_pvisionTargetB->norm01); // f �volue entre 0 et 1: 0 < f < 1 if( f < VISIONTARGET_COUPLE_VTA_VTB_HEIGHT_RATIO_UNDERLIMIT ) { // Trop grande diff�rence de taille entre les deux vision Target m_quality = -1.0f; return -1.0f; } else { // 'hauteur' relative apparement correcte: // Comparons le rapport de hauteur calcul� avec le rapport �talon c'est � dire celui d'un couple de Vision target pleinement de face. // Dans ce cas, les deux vision target ont exactement la m�me hauteur,leur rapport vaut 1.0f. // Plus les deux hauteurs ont des longueurs similaires , meilleure sera la note. m_quality += f; nb += 1.0f; } #endif #ifdef PRECOMPIL_LOGICFILTER_VISIONTARGETPAIR_QUADSIDE_RATIO // Rapport de la Vision Target avec la taille apparente la plus petite sur la longueur apparente du top du Quadrilatere du couple. // Les deux vision Target d'un m�me couple sont toujours s�par�es par la m�me distance. Les Visual Targets �tant inclin�es l'une vers l'autre, // la distance s�parant les points les plus hauts est plus longue que celle s�parant les points les plus bas. // Une fois projet�es, les distances apparentes diff�rent mais leurs rapports demeurent globalement coh�rent. topv = m_pvisionTargetB->m_higher2D - m_pvisionTargetA->m_higher2D; topnorm = sqrtf(topv.x*topv.x + topv.y*topv.y); if ( (topnorm < VISIONTARGET_COUPLE_QUADSIDE_NORM_MIN ) || ((f = MIN(m_pvisionTargetA->norm01, m_pvisionTargetB->norm01)/topnorm) < VISIONTARGET_COUPLE_QUADSIDE_RATIO_UNDERLIMIT)) { // Proportion du quadrilat�re non conforme. C'est � dire quadrilat�re trop �tir� horizontalement m_quality = -1.0f; return -1.0f; } else { // On compare le ratio r avec le ratio �talon c'est � dire le ratio obtenu avec un quadrilatere pleinement de face. // Dans ce cas, le ratio est de 0.4929. // Empiriquement on constate que ce ratio �volue entre environ 0.4 au minimum et jusqu'� environ 5 au maximum. // On attribuera la note maximum � un quadrilat�re ayant des proportions identiques au quadrilat�re Etalon. f = 1.0f - MIN( 1.0f, fabs(f - VISIONTARGET_COUPLE_QUADSIDE_RATIO_STANDARD) / (VISIONTARGET_COUPLE_QUADSIDE_RATIO_STANDARD - VISIONTARGET_COUPLE_QUADSIDE_RATIO_UNDERLIMIT) ); m_quality += 1.0f; nb += 1.0f; } #endif #ifdef PRECOMPIL_LOGICFILTER_VISIONTARGETPAIR_ANGLE_QUADTOP_HORIZONTAL // ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // Angle apparent du couple avec "l'horizontale" // ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // Les visions target sont toutes situ�es dans deux plans horizontaux ( toutes celles du bas dans un "plan bas" et celles du haut des fus�es dans "plan haut" .) // Une fois projet�es les Paires de Visions Target semblent toutes align�es avec l'horizontale plut�t qu'avec la verticale. En cons�quence les Couples de Vision Target ayant une // trop forte pente apparente avec l'horizontale peuvent �tre rejet�s. // Pour estimer cette pente on regarde simplement l'ordonn�e (valeur absolue) du vecteur directeur de la base du quadrilat�re. Cette valeur repr�sente le sinus de l'angle de la base du quadrilat�re // avec l'horizontale. #ifdef PRECOMPIL_LOGICFILTER_VISIONTARGETPAIR_QUADSIDE_RATIO // ( ... On r�utilise "topv" et "topnorm" d�j� calcul�s quelques lilgnes plus haut ) //basev.x /= basenorm; !!! Inutile de normaliser basev.x, car on ne l'utilise pas. topv.y /= topnorm; #else // Le bloc de code "PRECOMPIL_LOGICFILTER_VISIONTARGETPAIR_QUADSIDE_RATIO" est inactif, on calcule topv et topnorm topv = m_pvisionTargetB->m_higher2D - m_pvisionTargetA->m_higher2D; topnorm = sqrtf(topv.x*topv.x + topv.y*topv.y); //topv.x /= basenorm; !!! Inutile de normaliser basev.x, car on ne l'utilise pas. topv.y /= topnorm; #endif if ( fabs(topv.y) > VISIONTARGET_COUPLE_INCLINE_UPPERLIMIT) { // Proportion du quadrilat�re non conforme. C'est � dire quadrilat�re trop �tir� horizontalement m_quality = -1.0f; return -1.0f; } else { // plus un quadrilat�re est horizontal mieux c'est. Donc plus la valeur absolue de topv.y est proche de 0, meilleure sera la qualit� ! m_quality += 1.0f- fabs(topv.y); nb += 1.0f; } #endif #ifdef PRECOMPIL_LOGICFILTER_VISIONTARGETPAIR_ANGLE_QUADBASE_HORIZONTAL // On refait la m�me chose avec la 'base' du quadrilat�re. En effet, certain "faux couple" form�s par des "fausses Visual Targets" peuvent �tre �tonnement d�form�s. Cette double v�rification peut aider � en �liminer // certains. basev = m_pvisionTargetB->m_lower2D - m_pvisionTargetA->m_lower2D; basenorm = sqrtf(basev.x*basev.x + basev.y + basev.y); //basev.x /= topnorm; !!! Inutile de normaliser basev.x, car on ne l'utilise pas. basev.y /= basenorm; if (fabs(basev.y) > VISIONTARGET_COUPLE_INCLINE_UPPERLIMIT) { // Proportion du quadrilat�re non conforme. C'est � dire quadrilat�re trop �tir� horizontalement m_quality = -1.0f; return -1.0f; } else { // plus un quadrilat�re est horizontal mieux c'est. Donc plus la valeur absolue de basev.y est proche de 0, meilleure sera la qualit� ! m_quality += 1.0f - fabs(basev.y); nb += 1.0f; } #endif // ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // Distance apparente entre les deux shapes // ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- /* cv::Point3f v = m_pvisionTargetB->middleBottom3D - m_pvisionTargetA->middleBottom3D; m_norm3DBottom = sqrt(v.x*v.x + v.y*v.y + v.z*v.z); if (m_norm3DBottom <= FLT_EPSILON_NORM) { m_quality = -1.0f; return -1.0f; } v = m_pvisionTargetB->middleTop3D - m_pvisionTargetA->middleTop3D; m_norm3DTop = sqrt(v.x*v.x + v.y*v.y + v.z*v.z); float f = m_norm3DTop / m_norm3DBottom; float r = MIN(f, PAIR_NORM3DRATIO) / MAX(f, PAIR_NORM3DRATIO); if (f<0.5f || f>2.0f) { m_quality = -1.0f; return -1.0f; } else { m_quality += f; nb += 1.0f; } */ // Setup Finalisation // Calcul du centre du trapeze[A3][A0][B1][B2] Tools::SegXSeg(pshapeA->m_higher2D, pshapeB->m_lower2D, pshapeA->m_lower2D, pshapeB->m_higher2D, m_center[VisionTargetPair::TRAPEZOID]); // Calcul du projet� (selon l'axe Y ) du centre du trap�ze su rle segement [B1][B2], pour obtenir le milieu du segment [B1][B2] en respectant la d�formation perspective // ( On suppose donc ici qu'une droite verticale dans le monde reste une droite verticale une fois projet�e ... ( ce qui n'est pas tout a fait vrai ... mais bon ) basev = m_center[0]; basev.y += CAPTURED_IMAGE_HEIGHT; Tools::SegXSeg(pshapeA->m_lower2D, pshapeB->m_lower2D, m_center[0], basev, m_center[VisionTargetPair::TRAPEZOID_BOTTOM_SIDE]); m_quality /= nb; return m_quality; /* // Une Paire d�j� existante r�f�rence pshapeA ! if(pshapeA->m_pVisionTargetPair) { assert(pshapeB->m_pVisionTargetPair==NULL); // La paire pr�-existante semble de moins bonne qualit�. // La nouvelle paire la remplace.... if(pshapeA->m_pVisionTargetPair->m_quality < m_quality) { } else // La paire pr�-existante semble de meilleure qualit� il faut la garder ! Et tout simplement oublier la nouvelle. { m_quality = -2.0f; return m_quality; } } else if(pshapeB->m_pVisionTargetPair)// Une Paire d�j� existante r�f�rence pshapeB ! { // La paire pr�-existante semble de moins bonne qualit�. // La nouvelle paire la remplace.... if (pshapeB->m_pVisionTargetPair->m_quality < m_quality) { } else // La paire pr�-existante semble de meilleure qualit� il faut la garder ! Et tout simplement oublier la nouvelle. { m_quality = -2.0f; return m_quality; } } */ return m_quality; } void VisionTargetChain::buildChainGraph() { Point3f u, v; float unormxz, vnormxz; // for (std::vector<VisionTarget>::iterator vta = m_visionTargets.begin(); vta != m_visionTargets.end() - 1; vta ++) { for (std::vector<VisionTarget>::iterator vtb = vta + 1; vtb != m_visionTargets.end(); vtb++) { // Angle entre les deux VisionTarget: //----------------------------------- // Distance entre les deux vision targets dans le plan XZ: //-------------------------------------------------------- // Les Points Haut des deux visions targets sont-ils s�par� par une distance suffisement en phase avec la r�alit� ? u = vta->m_higher3D - vtb->m_higher3D; unormxz = u.x*u.x + u.y*u.y; // Tout aussi juste ici que la 'vraie' distance ( mais on gagne une racine carr�e :) ) if ( (unormxz < REAL_VISIONTARGETPAIR_NORM_TRAPEZOID_TOP_DISTMIN) || (unormxz > REAL_VISIONTARGETPAIR_NORM_TRAPEZOID_TOP_DISTMAX) ) continue; // Les Points Bas des deux visions targets sont-ils s�par� par une distance suffisement en phase avec la r�alit� ? v = vta->m_lower3D - vtb->m_lower3D; vnormxz = v.x*v.x + v.y*v.y; // Tout aussi juste ici que la 'vraie' distance ( mais on gagne une racine carr�e :) ) if ( (unormxz < REAL_VISIONTARGETPAIR_NORM_TRAPEZOID_BOTTOM_DISTMIN) || (unormxz > REAL_VISIONTARGETPAIR_NORM_TRAPEZOID_BOTTOM_DISTMAX)) continue; // Evaluation et Validation du lien: if (vta->m_linkSize < VISIONTARGET_LINKSIZE) { //vta->m_links[vta->m_linkSize].m_pto = &vtb; vta->m_linkSize ++; } } } }
9cb196d417fdae1e15b96d9410435f5c05135792
02bfcea5e6f9af90f812922fd3b9fb388b281f4c
/src/Class/stage/SsaveMap.cpp
1bb996712d4995504ea7e8e4ad598243bd32342f
[]
no_license
tim099/AgeOfCube
900f9ee765d2d5935554144b34e58e3281ead8aa
abd33a3ae8fa9edd60e2a9294342e4f7623117c7
refs/heads/master
2021-03-12T19:57:14.656563
2014-12-19T08:25:18
2014-12-19T08:25:18
28,218,835
1
0
null
null
null
null
UTF-8
C++
false
false
818
cpp
#include "SsaveMap.h" SsaveMap::SsaveMap() { input_str=new std::string("Map01");//delete by list list->push_str(input_str,0,0);//->call_string(); list->push_str(std::string("Enter Map Name"),0,0.006); SLB->creat_short_button("Save",Signal(S_SAVE_MAP),-0.01,-0.006); SLB->creat_short_button("Back",Signal(S_BACK),0.01,-0.006); } SsaveMap::~SsaveMap() { //delete input_str; } void SsaveMap::Stage_signal_process(Signal s){ char file[100]="files/maps/"; switch(s.sig()){ case S_SAVE_MAP: for(unsigned i=0;i<input_str->size();i++){ file[i+11]=input_str->at(i); } file[input_str->size()+11]='\0'; sent_signal(Signal(S_SAVE_MAP_NAME,std::string(file))); end=true; break; default: printf("unknown signal to savemap stage %d\n",s.sig()); } } void SsaveMap::timer_tick(){ get_input(); }
c9b0a451746a1bc98937285c1733531d7d2f43d3
14081cec5294ff0dc0b6258f381de2a7a823a830
/kami_puro/Sources/SCENE/GAME/UI/COverLay.cpp
e63406549cd3895d6ea7f6dca77bd54e38810678
[]
no_license
NojiriMisoten/OMTT
ec21a5269cef72710e79d59586adfad5a27eb868
86f0752d63375cfe4115393b2515f3f59f1a513b
refs/heads/master
2021-01-01T06:54:31.800869
2016-01-18T16:38:12
2016-01-18T16:38:12
42,498,516
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
4,721
cpp
//============================================================================= // // COverLayクラス [COverLay.cpp] // Author : 塚本俊彦 // //============================================================================= //***************************************************************************** // インクルード //***************************************************************************** #include "COverLay.h" //***************************************************************************** // 定数 //***************************************************************************** static const float WIDTH = SCREEN_WIDTH; static const float HEIGHT = SCREEN_HEIGHT / 720.f * 300.f; static const D3DXVECTOR3 POS = D3DXVECTOR3(SCREEN_WIDTH * 0.5f, SCREEN_HEIGHT * 0.5f, 0); //============================================================================= // コンストラクタ //============================================================================= COverLay::COverLay(LPDIRECT3DDEVICE9 *pDevice) { m_pD3DDevice = pDevice; m_p2D = NULL; m_isIn = false; m_isOut = false; m_isWait = false; m_IntervalMax = 0; m_IntervalCount = 0; m_Color = D3DXCOLOR(1, 1, 1, 1); } //============================================================================= // デストラクタ //============================================================================= COverLay::~COverLay(void) { } //============================================================================= // 初期化 //============================================================================= void COverLay::Init(LPDIRECT3DDEVICE9 *pDevice) { // 2D初期化 m_p2D = CScene2D::Create(m_pD3DDevice, D3DXVECTOR3(POS), WIDTH, HEIGHT, TEXTURE_BLUE); m_p2D->AddLinkList(CRenderer::TYPE_RENDER_UI); // フェードアウトの白さ初期化 m_Color = D3DXCOLOR(1, 1, 1, 0); m_p2D->SetColorPolygon(m_Color); } //============================================================================= // 終了 //============================================================================= void COverLay::Uninit(void) { } //============================================================================= // 更新 //============================================================================= void COverLay::Update(void) { if (m_isIn) In(); if (m_isWait) Wait(); if (m_isOut) Out(); } //============================================================================= // 描画 //============================================================================= void COverLay::DrawUI(void) { } //============================================================================= // 作成 //============================================================================= COverLay* COverLay::Create( LPDIRECT3DDEVICE9 *pDevice) { COverLay* p = new COverLay(pDevice); p->Init(pDevice); return p; } //============================================================================= // カットインスタート //============================================================================= void COverLay::Start(Data *data) { m_isIn = true; m_isOut = false; m_isWait = false; m_IntervalCount = 0; m_IntervalMax = data->interval; m_FadeInSpeed = data->fadeInSpeed; m_FadeOutSpeed = data->fadeOutSpeed; // テクスチャ m_p2D->ChangeTexture(data->texture); // フェードアウトの白さ初期化 m_Color = D3DXCOLOR(1, 1, 1, 0); m_p2D->SetColorPolygon(m_Color); } //============================================================================= // 画面内に入ってくる更新 //============================================================================= void COverLay::In() { m_Color.a += m_FadeInSpeed; if (m_Color.a <= 1.0f) { m_p2D->SetColorPolygon(m_Color); } else { m_Color.a = 1.0f; m_p2D->SetColorPolygon(m_Color); m_isIn = false; m_isWait = true; m_IntervalCount = 0; } } //============================================================================= // カットインして表示している状態 //============================================================================= void COverLay::Wait() { // カットインをアウトするまでのカウント m_IntervalCount++; if (m_IntervalCount > m_IntervalMax) { m_isWait = false; m_isOut = true; } } //============================================================================= // 画面外に出ていく更新 //============================================================================= void COverLay::Out() { m_Color.a -= m_FadeOutSpeed; if (m_Color.a >= 0.0f) { m_p2D->SetColorPolygon(m_Color); } else { m_Color.a = 0.0f; m_p2D->SetColorPolygon(m_Color); m_isOut = false; } } //----EOF----
8e8132dab65bc9d9e4bd7f12aa6f3a4a87738668
3e24f87bb9ffc5c733b98858ae380c267869e7ce
/mobile/generated-src/jni/NativeClientRegistrationData.hpp
93761bd905d0bce4fdb9b3cb9018f46dc0c05e3c
[]
no_license
proximax-storage/sirius-stream-client-mobile-sdk
b051892d5e71f28f5d12248654b0ef77596c1a8d
7544449c5d09e003034a80dc76282743e12a787c
refs/heads/master
2022-04-08T23:37:02.937024
2020-03-03T14:57:05
2020-03-03T14:57:05
195,406,885
0
0
null
null
null
null
UTF-8
C++
false
false
1,300
hpp
// AUTOGENERATED FILE - DO NOT MODIFY! // This file generated by Djinni from ClientApp.djinni #pragma once #include "ClientRegistrationData.hpp" #include "djinni_support.hpp" namespace djinni_generated { class NativeClientRegistrationData final { public: using CppType = ::clientsdk::ClientRegistrationData; using JniType = jobject; using Boxed = NativeClientRegistrationData; ~NativeClientRegistrationData(); static CppType toCpp(JNIEnv* jniEnv, JniType j); static ::djinni::LocalRef<JniType> fromCpp(JNIEnv* jniEnv, const CppType& c); private: NativeClientRegistrationData(); friend ::djinni::JniClass<NativeClientRegistrationData>; const ::djinni::GlobalRef<jclass> clazz { ::djinni::jniFindClass("com/peerstream/psp/sdk/bridge/ClientRegistrationData") }; const jmethodID jconstructor { ::djinni::jniGetMethodID(clazz.get(), "<init>", "(Ljava/lang/String;Ljava/lang/String;[B)V") }; const jfieldID field_mIdentity { ::djinni::jniGetFieldID(clazz.get(), "mIdentity", "Ljava/lang/String;") }; const jfieldID field_mSecretKey { ::djinni::jniGetFieldID(clazz.get(), "mSecretKey", "Ljava/lang/String;") }; const jfieldID field_mCertificate { ::djinni::jniGetFieldID(clazz.get(), "mCertificate", "[B") }; }; } // namespace djinni_generated
74549d4eeec1921de4285c8ecabd715cdc08d768
eb36c8f053f1d9ea9cf8cd7e257446036fadfe8b
/chrome/browser/predictors/resource_prefetch_predictor_unittest.cc
724bd8a6687572ff482e16e30127d97bce4f52c4
[ "BSD-3-Clause" ]
permissive
Thompson-NO3/chromium
f1b5402628d9a99231dabc4fe875d9d7d6c46fe6
359103b8cbdf5ec81cb9827cc29c84405fb0fa17
refs/heads/master
2022-12-12T21:27:19.601825
2019-07-28T00:46:33
2019-07-28T00:46:33
199,234,236
0
0
BSD-3-Clause
2019-07-28T02:40:22
2019-07-28T02:40:22
null
UTF-8
C++
false
false
32,540
cc
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/predictors/resource_prefetch_predictor.h" #include <algorithm> #include <iostream> #include <memory> #include <utility> #include "base/memory/ref_counted.h" #include "base/sequenced_task_runner.h" #include "base/strings/stringprintf.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/test_simple_task_runner.h" #include "base/time/time.h" #include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/predictors/loading_predictor.h" #include "chrome/browser/predictors/loading_test_util.h" #include "chrome/browser/predictors/resource_prefetch_predictor_tables.h" #include "chrome/test/base/testing_profile.h" #include "components/history/core/browser/history_service.h" #include "components/history/core/browser/history_types.h" #include "components/sessions/core/session_id.h" #include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_utils.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using testing::StrictMock; using testing::UnorderedElementsAre; namespace predictors { namespace { using RedirectDataMap = std::map<std::string, RedirectData>; using OriginDataMap = std::map<std::string, OriginData>; template <typename T> class FakeLoadingPredictorKeyValueTable : public LoadingPredictorKeyValueTable<T> { public: FakeLoadingPredictorKeyValueTable() : LoadingPredictorKeyValueTable<T>("") {} void GetAllData(std::map<std::string, T>* data_map, sql::Database* db) const override { *data_map = data_; } void UpdateData(const std::string& key, const T& data, sql::Database* db) override { data_[key] = data; } void DeleteData(const std::vector<std::string>& keys, sql::Database* db) override { for (const auto& key : keys) data_.erase(key); } void DeleteAllData(sql::Database* db) override { data_.clear(); } std::map<std::string, T> data_; }; class MockResourcePrefetchPredictorTables : public ResourcePrefetchPredictorTables { public: MockResourcePrefetchPredictorTables( scoped_refptr<base::SequencedTaskRunner> db_task_runner) : ResourcePrefetchPredictorTables(std::move(db_task_runner)) {} void ScheduleDBTask(const base::Location& from_here, DBTask task) override { ExecuteDBTaskOnDBSequence(std::move(task)); } void ExecuteDBTaskOnDBSequence(DBTask task) override { std::move(task).Run(nullptr); } LoadingPredictorKeyValueTable<RedirectData>* host_redirect_table() override { return &host_redirect_table_; } LoadingPredictorKeyValueTable<OriginData>* origin_table() override { return &origin_table_; } FakeLoadingPredictorKeyValueTable<RedirectData> host_redirect_table_; FakeLoadingPredictorKeyValueTable<OriginData> origin_table_; protected: ~MockResourcePrefetchPredictorTables() override = default; }; class MockResourcePrefetchPredictorObserver : public TestObserver { public: explicit MockResourcePrefetchPredictorObserver( ResourcePrefetchPredictor* predictor) : TestObserver(predictor) {} MOCK_METHOD1(OnNavigationLearned, void(const PageRequestSummary& summary)); }; } // namespace class ResourcePrefetchPredictorTest : public testing::Test { public: ResourcePrefetchPredictorTest(); ~ResourcePrefetchPredictorTest() override; void SetUp() override; void TearDown() override; protected: void InitializePredictor() { loading_predictor_->StartInitialization(); db_task_runner_->RunUntilIdle(); profile_->BlockUntilHistoryProcessesPendingRequests(); } void ResetPredictor(bool small_db = true) { if (loading_predictor_) loading_predictor_->Shutdown(); LoadingPredictorConfig config; PopulateTestConfig(&config, small_db); loading_predictor_ = std::make_unique<LoadingPredictor>(config, profile_.get()); predictor_ = loading_predictor_->resource_prefetch_predictor(); predictor_->set_mock_tables(mock_tables_); } void InitializeSampleData(); content::TestBrowserThreadBundle thread_bundle_; std::unique_ptr<TestingProfile> profile_; scoped_refptr<base::TestSimpleTaskRunner> db_task_runner_; std::unique_ptr<LoadingPredictor> loading_predictor_; ResourcePrefetchPredictor* predictor_; scoped_refptr<StrictMock<MockResourcePrefetchPredictorTables>> mock_tables_; RedirectDataMap test_host_redirect_data_; OriginDataMap test_origin_data_; std::unique_ptr<base::HistogramTester> histogram_tester_; }; ResourcePrefetchPredictorTest::ResourcePrefetchPredictorTest() : profile_(std::make_unique<TestingProfile>()), db_task_runner_(base::MakeRefCounted<base::TestSimpleTaskRunner>()), mock_tables_( base::MakeRefCounted<StrictMock<MockResourcePrefetchPredictorTables>>( db_task_runner_)) {} ResourcePrefetchPredictorTest::~ResourcePrefetchPredictorTest() = default; void ResourcePrefetchPredictorTest::SetUp() { InitializeSampleData(); CHECK(profile_->CreateHistoryService(true, false)); profile_->BlockUntilHistoryProcessesPendingRequests(); CHECK(HistoryServiceFactory::GetForProfile( profile_.get(), ServiceAccessType::EXPLICIT_ACCESS)); // Initialize the predictor with empty data. ResetPredictor(); // The first creation of the LoadingPredictor constructs the PredictorDatabase // for the |profile_|. The PredictorDatabase is initialized asynchronously and // we have to wait for the initialization completion even though the database // object is later replaced by a mock object. content::RunAllTasksUntilIdle(); CHECK_EQ(predictor_->initialization_state_, ResourcePrefetchPredictor::NOT_INITIALIZED); InitializePredictor(); CHECK_EQ(predictor_->initialization_state_, ResourcePrefetchPredictor::INITIALIZED); histogram_tester_ = std::make_unique<base::HistogramTester>(); } void ResourcePrefetchPredictorTest::TearDown() { EXPECT_EQ(*predictor_->host_redirect_data_->data_cache_, mock_tables_->host_redirect_table_.data_); EXPECT_EQ(*predictor_->origin_data_->data_cache_, mock_tables_->origin_table_.data_); loading_predictor_->Shutdown(); } void ResourcePrefetchPredictorTest::InitializeSampleData() { { // Host redirect data. RedirectData bbc = CreateRedirectData("bbc.com", 9); InitializeRedirectStat(bbc.add_redirect_endpoints(), GURL("https://www.bbc.com"), 8, 4, 1); InitializeRedirectStat(bbc.add_redirect_endpoints(), GURL("https://m.bbc.com"), 5, 8, 0); InitializeRedirectStat(bbc.add_redirect_endpoints(), GURL("http://bbc.co.uk"), 1, 3, 0); InitializeRedirectStat(bbc.add_redirect_endpoints(), GURL("https://bbc.co.uk"), 1, 3, 0); RedirectData microsoft = CreateRedirectData("microsoft.com", 10); InitializeRedirectStat(microsoft.add_redirect_endpoints(), GURL("https://www.microsoft.com"), 10, 0, 0); test_host_redirect_data_.clear(); test_host_redirect_data_.insert(std::make_pair(bbc.primary_key(), bbc)); test_host_redirect_data_.insert( std::make_pair(microsoft.primary_key(), microsoft)); } { // Origin data. OriginData google = CreateOriginData("google.com", 12); InitializeOriginStat(google.add_origins(), "https://static.google.com", 12, 0, 0, 3., false, true); InitializeOriginStat(google.add_origins(), "https://cats.google.com", 12, 0, 0, 5., true, true); test_origin_data_.insert({"google.com", google}); OriginData twitter = CreateOriginData("twitter.com", 42); InitializeOriginStat(twitter.add_origins(), "https://static.twitter.com", 12, 0, 0, 3., false, true); InitializeOriginStat(twitter.add_origins(), "https://random.140chars.com", 12, 0, 0, 3., false, true); test_origin_data_.insert({"twitter.com", twitter}); } } // Tests that the predictor initializes correctly without any data. TEST_F(ResourcePrefetchPredictorTest, LazilyInitializeEmpty) { EXPECT_TRUE(mock_tables_->host_redirect_table_.data_.empty()); EXPECT_TRUE(mock_tables_->origin_table_.data_.empty()); } // Tests that the history and the db tables data are loaded correctly. TEST_F(ResourcePrefetchPredictorTest, LazilyInitializeWithData) { mock_tables_->host_redirect_table_.data_ = test_host_redirect_data_; mock_tables_->origin_table_.data_ = test_origin_data_; ResetPredictor(); InitializePredictor(); // Test that the internal variables correctly initialized. EXPECT_EQ(predictor_->initialization_state_, ResourcePrefetchPredictor::INITIALIZED); // Integrity of the cache and the backend storage is checked on TearDown. } // Single navigation that will be recorded. Will check for duplicate // resources and also for number of resources saved. TEST_F(ResourcePrefetchPredictorTest, NavigationUrlNotInDB) { std::vector<content::mojom::ResourceLoadInfoPtr> resources; resources.push_back(CreateResourceLoadInfo("http://www.google.com")); resources.push_back(CreateResourceLoadInfo( "http://google.com/style1.css", content::ResourceType::kStylesheet)); resources.push_back(CreateResourceLoadInfo("http://google.com/script1.js", content::ResourceType::kScript)); resources.push_back(CreateResourceLoadInfo("http://google.com/script2.js", content::ResourceType::kScript)); resources.push_back(CreateResourceLoadInfo("http://google.com/script1.js", content::ResourceType::kScript)); resources.push_back(CreateResourceLoadInfo("http://google.com/image1.png", content::ResourceType::kImage)); resources.push_back(CreateResourceLoadInfo("http://google.com/image2.png", content::ResourceType::kImage)); resources.push_back(CreateResourceLoadInfo( "http://google.com/style2.css", content::ResourceType::kStylesheet)); resources.push_back( CreateResourceLoadInfo("http://static.google.com/style2-no-store.css", content::ResourceType::kStylesheet, /* always_access_network */ true)); resources.push_back(CreateResourceLoadInfoWithRedirects( {"http://reader.google.com/style.css", "http://dev.null.google.com/style.css"}, content::ResourceType::kStylesheet)); resources.back()->network_info->always_access_network = true; auto page_summary = CreatePageRequestSummary( "http://www.google.com", "http://www.google.com", resources); StrictMock<MockResourcePrefetchPredictorObserver> mock_observer(predictor_); EXPECT_CALL(mock_observer, OnNavigationLearned(page_summary)); predictor_->RecordPageRequestSummary( std::make_unique<PageRequestSummary>(page_summary)); profile_->BlockUntilHistoryProcessesPendingRequests(); OriginData origin_data = CreateOriginData("www.google.com"); InitializeOriginStat(origin_data.add_origins(), "http://www.google.com/", 1, 0, 0, 1., false, true); InitializeOriginStat(origin_data.add_origins(), "http://static.google.com/", 1, 0, 0, 3., true, true); InitializeOriginStat(origin_data.add_origins(), "http://dev.null.google.com/", 1, 0, 0, 5., true, true); InitializeOriginStat(origin_data.add_origins(), "http://google.com/", 1, 0, 0, 2., false, true); InitializeOriginStat(origin_data.add_origins(), "http://reader.google.com/", 1, 0, 0, 4., false, true); EXPECT_EQ(mock_tables_->origin_table_.data_, OriginDataMap({{origin_data.host(), origin_data}})); RedirectData host_redirect_data = CreateRedirectData("www.google.com"); InitializeRedirectStat(host_redirect_data.add_redirect_endpoints(), GURL("http://www.google.com"), 1, 0, 0); EXPECT_EQ(mock_tables_->host_redirect_table_.data_, RedirectDataMap( {{host_redirect_data.primary_key(), host_redirect_data}})); } // Tests that navigation is recorded correctly for URL already present in // the database cache. TEST_F(ResourcePrefetchPredictorTest, NavigationUrlInDB) { ResetPredictor(); InitializePredictor(); std::vector<content::mojom::ResourceLoadInfoPtr> resources; resources.push_back(CreateResourceLoadInfo("http://www.google.com")); resources.push_back(CreateResourceLoadInfo( "http://google.com/style1.css", content::ResourceType::kStylesheet)); resources.push_back(CreateResourceLoadInfo("http://google.com/script1.js", content::ResourceType::kScript)); resources.push_back(CreateResourceLoadInfo("http://google.com/script2.js", content::ResourceType::kScript)); resources.push_back(CreateResourceLoadInfo("http://google.com/script1.js", content::ResourceType::kScript)); resources.push_back(CreateResourceLoadInfo("http://google.com/image1.png", content::ResourceType::kImage)); resources.push_back(CreateResourceLoadInfo("http://google.com/image2.png", content::ResourceType::kImage)); resources.push_back(CreateResourceLoadInfo( "http://google.com/style2.css", content::ResourceType::kStylesheet)); resources.push_back(CreateResourceLoadInfo( "http://static.google.com/style2-no-store.css", content::ResourceType::kStylesheet, /* always_access_network */ true)); auto page_summary = CreatePageRequestSummary( "http://www.google.com", "http://www.google.com", resources); StrictMock<MockResourcePrefetchPredictorObserver> mock_observer(predictor_); EXPECT_CALL(mock_observer, OnNavigationLearned(page_summary)); predictor_->RecordPageRequestSummary( std::make_unique<PageRequestSummary>(page_summary)); profile_->BlockUntilHistoryProcessesPendingRequests(); RedirectData host_redirect_data = CreateRedirectData("www.google.com"); InitializeRedirectStat(host_redirect_data.add_redirect_endpoints(), GURL("http://www.google.com"), 1, 0, 0); EXPECT_EQ(mock_tables_->host_redirect_table_.data_, RedirectDataMap( {{host_redirect_data.primary_key(), host_redirect_data}})); OriginData origin_data = CreateOriginData("www.google.com"); InitializeOriginStat(origin_data.add_origins(), "http://www.google.com/", 1., 0, 0, 1., false, true); InitializeOriginStat(origin_data.add_origins(), "http://static.google.com/", 1, 0, 0, 3., true, true); InitializeOriginStat(origin_data.add_origins(), "http://google.com/", 1, 0, 0, 2., false, true); EXPECT_EQ(mock_tables_->origin_table_.data_, OriginDataMap({{origin_data.host(), origin_data}})); } // Tests that a URL is deleted before another is added if the cache is full. TEST_F(ResourcePrefetchPredictorTest, NavigationUrlNotInDBAndDBFull) { mock_tables_->origin_table_.data_ = test_origin_data_; ResetPredictor(); InitializePredictor(); std::vector<content::mojom::ResourceLoadInfoPtr> resources; resources.push_back(CreateResourceLoadInfo("http://www.nike.com")); resources.push_back(CreateResourceLoadInfo( "http://nike.com/style1.css", content::ResourceType::kStylesheet)); resources.push_back(CreateResourceLoadInfo("http://nike.com/image2.png", content::ResourceType::kImage)); auto page_summary = CreatePageRequestSummary( "http://www.nike.com", "http://www.nike.com", resources); StrictMock<MockResourcePrefetchPredictorObserver> mock_observer(predictor_); EXPECT_CALL(mock_observer, OnNavigationLearned(page_summary)); predictor_->RecordPageRequestSummary( std::make_unique<PageRequestSummary>(page_summary)); profile_->BlockUntilHistoryProcessesPendingRequests(); RedirectData host_redirect_data = CreateRedirectData("www.nike.com"); InitializeRedirectStat(host_redirect_data.add_redirect_endpoints(), GURL("http://www.nike.com"), 1, 0, 0); EXPECT_EQ(mock_tables_->host_redirect_table_.data_, RedirectDataMap( {{host_redirect_data.primary_key(), host_redirect_data}})); OriginData origin_data = CreateOriginData("www.nike.com"); InitializeOriginStat(origin_data.add_origins(), "http://www.nike.com/", 1, 0, 0, 1., false, true); InitializeOriginStat(origin_data.add_origins(), "http://nike.com/", 1, 0, 0, 2., false, true); OriginDataMap expected_origin_data = test_origin_data_; expected_origin_data.erase("google.com"); expected_origin_data["www.nike.com"] = origin_data; EXPECT_EQ(mock_tables_->origin_table_.data_, expected_origin_data); } TEST_F(ResourcePrefetchPredictorTest, NavigationManyResourcesWithDifferentOrigins) { std::vector<content::mojom::ResourceLoadInfoPtr> resources; resources.push_back(CreateResourceLoadInfo("http://www.google.com")); auto gen = [](int i) { return base::StringPrintf("http://cdn%d.google.com/script.js", i); }; const int num_resources = predictor_->config_.max_origins_per_entry + 10; for (int i = 1; i <= num_resources; ++i) { resources.push_back( CreateResourceLoadInfo(gen(i), content::ResourceType::kScript)); } auto page_summary = CreatePageRequestSummary( "http://www.google.com", "http://www.google.com", resources); StrictMock<MockResourcePrefetchPredictorObserver> mock_observer(predictor_); EXPECT_CALL(mock_observer, OnNavigationLearned(page_summary)); predictor_->RecordPageRequestSummary( std::make_unique<PageRequestSummary>(page_summary)); profile_->BlockUntilHistoryProcessesPendingRequests(); OriginData origin_data = CreateOriginData("www.google.com"); InitializeOriginStat(origin_data.add_origins(), "http://www.google.com/", 1, 0, 0, 1, false, true); for (int i = 1; i <= static_cast<int>(predictor_->config_.max_origins_per_entry) - 1; ++i) { InitializeOriginStat(origin_data.add_origins(), GURL(gen(i)).GetOrigin().spec(), 1, 0, 0, i + 1, false, true); } EXPECT_EQ(mock_tables_->origin_table_.data_, OriginDataMap({{origin_data.host(), origin_data}})); } TEST_F(ResourcePrefetchPredictorTest, RedirectUrlNotInDB) { std::vector<content::mojom::ResourceLoadInfoPtr> resources; resources.push_back(CreateResourceLoadInfoWithRedirects( {"http://fb.com/google", "https://facebook.com/google"})); auto page_summary = CreatePageRequestSummary( "https://facebook.com/google", "http://fb.com/google", resources); StrictMock<MockResourcePrefetchPredictorObserver> mock_observer(predictor_); EXPECT_CALL(mock_observer, OnNavigationLearned(page_summary)); predictor_->RecordPageRequestSummary( std::make_unique<PageRequestSummary>(page_summary)); profile_->BlockUntilHistoryProcessesPendingRequests(); RedirectData host_redirect_data = CreateRedirectData("fb.com"); InitializeRedirectStat(host_redirect_data.add_redirect_endpoints(), GURL("https://facebook.com"), 1, 0, 0); EXPECT_EQ(mock_tables_->host_redirect_table_.data_, RedirectDataMap( {{host_redirect_data.primary_key(), host_redirect_data}})); } // Tests that redirect is recorded correctly for URL already present in // the database cache. TEST_F(ResourcePrefetchPredictorTest, RedirectUrlInDB) { mock_tables_->host_redirect_table_.data_ = test_host_redirect_data_; ResetPredictor(); InitializePredictor(); std::vector<content::mojom::ResourceLoadInfoPtr> resources; resources.push_back(CreateResourceLoadInfoWithRedirects( {"http://fb.com/google", "https://facebook.com/google"})); auto page_summary = CreatePageRequestSummary( "https://facebook.com/google", "http://fb.com/google", resources); StrictMock<MockResourcePrefetchPredictorObserver> mock_observer(predictor_); EXPECT_CALL(mock_observer, OnNavigationLearned(page_summary)); predictor_->RecordPageRequestSummary( std::make_unique<PageRequestSummary>(page_summary)); profile_->BlockUntilHistoryProcessesPendingRequests(); RedirectData host_redirect_data = CreateRedirectData("fb.com"); InitializeRedirectStat(host_redirect_data.add_redirect_endpoints(), GURL("https://facebook.com"), 1, 0, 0); RedirectDataMap expected_host_redirect_data = test_host_redirect_data_; expected_host_redirect_data.erase("bbc.com"); expected_host_redirect_data[host_redirect_data.primary_key()] = host_redirect_data; EXPECT_EQ(mock_tables_->host_redirect_table_.data_, expected_host_redirect_data); } // Tests that redirect is recorded correctly for URL already present in // the database cache. Test with both https and http schemes for the same // host. TEST_F(ResourcePrefetchPredictorTest, RedirectUrlInDB_MultipleSchemes) { mock_tables_->host_redirect_table_.data_ = test_host_redirect_data_; ResetPredictor(); InitializePredictor(); { std::vector<content::mojom::ResourceLoadInfoPtr> resources_https; resources_https.push_back(CreateResourceLoadInfoWithRedirects( {"https://fb.com/google", "https://facebook.com/google"})); auto page_summary_https = CreatePageRequestSummary("https://facebook.com/google", "https://fb.com/google", resources_https); StrictMock<MockResourcePrefetchPredictorObserver> mock_observer(predictor_); EXPECT_CALL(mock_observer, OnNavigationLearned(page_summary_https)); predictor_->RecordPageRequestSummary( std::make_unique<PageRequestSummary>(page_summary_https)); profile_->BlockUntilHistoryProcessesPendingRequests(); RedirectData host_redirect_data_https = CreateRedirectData("fb.com"); InitializeRedirectStat(host_redirect_data_https.add_redirect_endpoints(), GURL("https://facebook.com"), 1, 0, 0); RedirectDataMap expected_host_redirect_data_https = test_host_redirect_data_; expected_host_redirect_data_https.erase("bbc.com"); expected_host_redirect_data_https[host_redirect_data_https.primary_key()] = host_redirect_data_https; EXPECT_EQ(mock_tables_->host_redirect_table_.data_, expected_host_redirect_data_https); EXPECT_EQ(1, mock_tables_->host_redirect_table_ .data_[host_redirect_data_https.primary_key()] .redirect_endpoints() .size()); EXPECT_EQ("https", mock_tables_->host_redirect_table_ .data_[host_redirect_data_https.primary_key()] .redirect_endpoints(0) .url_scheme()); EXPECT_EQ(443, mock_tables_->host_redirect_table_ .data_[host_redirect_data_https.primary_key()] .redirect_endpoints(0) .url_port()); } { std::vector<content::mojom::ResourceLoadInfoPtr> resources_http; resources_http.push_back(CreateResourceLoadInfoWithRedirects( {"http://fb.com/google", "http://facebook.com/google"})); auto page_summary_http = CreatePageRequestSummary( "http://facebook.com/google", "http://fb.com/google", resources_http); StrictMock<MockResourcePrefetchPredictorObserver> mock_observer(predictor_); EXPECT_CALL(mock_observer, OnNavigationLearned(page_summary_http)); predictor_->RecordPageRequestSummary( std::make_unique<PageRequestSummary>(page_summary_http)); profile_->BlockUntilHistoryProcessesPendingRequests(); RedirectData host_redirect_data_http = CreateRedirectData("fb.com"); InitializeRedirectStat(host_redirect_data_http.add_redirect_endpoints(), GURL("http://facebook.com"), 1, 0, 0); RedirectDataMap expected_host_redirect_data_http = test_host_redirect_data_; expected_host_redirect_data_http.erase("bbc.com"); expected_host_redirect_data_http[host_redirect_data_http.primary_key()] = host_redirect_data_http; EXPECT_EQ(2, mock_tables_->host_redirect_table_ .data_[host_redirect_data_http.primary_key()] .redirect_endpoints() .size()); EXPECT_EQ("facebook.com", mock_tables_->host_redirect_table_ .data_[host_redirect_data_http.primary_key()] .redirect_endpoints(1) .url()); EXPECT_EQ("http", mock_tables_->host_redirect_table_ .data_[host_redirect_data_http.primary_key()] .redirect_endpoints(1) .url_scheme()); EXPECT_EQ(80, mock_tables_->host_redirect_table_ .data_[host_redirect_data_http.primary_key()] .redirect_endpoints(1) .url_port()); } } TEST_F(ResourcePrefetchPredictorTest, DeleteUrls) { ResetPredictor(false); InitializePredictor(); // Add some dummy entries to cache. RedirectDataMap host_redirects; host_redirects.insert( {"www.google.com", CreateRedirectData("www.google.com")}); host_redirects.insert({"www.nike.com", CreateRedirectData("www.nike.com")}); host_redirects.insert( {"www.wikipedia.org", CreateRedirectData("www.wikipedia.org")}); for (const auto& redirect : host_redirects) { predictor_->host_redirect_data_->UpdateData(redirect.first, redirect.second); } // TODO(alexilin): Add origin data. history::URLRows rows; rows.push_back(history::URLRow(GURL("http://www.google.com/page2.html"))); rows.push_back(history::URLRow(GURL("http://www.apple.com"))); rows.push_back(history::URLRow(GURL("http://www.nike.com"))); host_redirects.erase("www.google.com"); host_redirects.erase("www.nike.com"); predictor_->DeleteUrls(rows); EXPECT_EQ(mock_tables_->host_redirect_table_.data_, host_redirects); predictor_->DeleteAllUrls(); EXPECT_TRUE(mock_tables_->host_redirect_table_.data_.empty()); } // Tests that DeleteAllUrls deletes all urls even if called before the // initialization is completed. TEST_F(ResourcePrefetchPredictorTest, DeleteAllUrlsUninitialized) { mock_tables_->host_redirect_table_.data_ = test_host_redirect_data_; mock_tables_->origin_table_.data_ = test_origin_data_; ResetPredictor(); CHECK_EQ(predictor_->initialization_state_, ResourcePrefetchPredictor::NOT_INITIALIZED); EXPECT_FALSE(mock_tables_->origin_table_.data_.empty()); predictor_->DeleteAllUrls(); // Caches aren't initialized yet, so data should be deleted only after the // initialization. EXPECT_FALSE(mock_tables_->origin_table_.data_.empty()); InitializePredictor(); CHECK_EQ(predictor_->initialization_state_, ResourcePrefetchPredictor::INITIALIZED); EXPECT_TRUE(mock_tables_->origin_table_.data_.empty()); } TEST_F(ResourcePrefetchPredictorTest, GetRedirectEndpoint) { auto& redirect_data = *predictor_->host_redirect_data_; std::string redirect_endpoint; // Returns the initial url if data_map doesn't contain an entry for the url. EXPECT_TRUE(predictor_->GetRedirectEndpoint("bbc.com", redirect_data, &redirect_endpoint)); EXPECT_EQ(redirect_endpoint, "bbc.com"); // The data to be requested for the confident endpoint. RedirectData nyt = CreateRedirectData("nyt.com", 1); InitializeRedirectStat(nyt.add_redirect_endpoints(), GURL("https://mobile.nytimes.com"), 10, 0, 0); redirect_data.UpdateData(nyt.primary_key(), nyt); EXPECT_TRUE(predictor_->GetRedirectEndpoint("nyt.com", redirect_data, &redirect_endpoint)); EXPECT_EQ(redirect_endpoint, "mobile.nytimes.com"); // The data to check negative result due not enough confidence. RedirectData facebook = CreateRedirectData("fb.com", 3); InitializeRedirectStat(facebook.add_redirect_endpoints(), GURL("https://facebook.com"), 5, 5, 0); redirect_data.UpdateData(facebook.primary_key(), facebook); EXPECT_FALSE(predictor_->GetRedirectEndpoint("fb.com", redirect_data, &redirect_endpoint)); // The data to check negative result due ambiguity. RedirectData google = CreateRedirectData("google.com", 4); InitializeRedirectStat(google.add_redirect_endpoints(), GURL("https://google.com"), 10, 0, 0); InitializeRedirectStat(google.add_redirect_endpoints(), GURL("https://google.fr"), 10, 1, 0); InitializeRedirectStat(google.add_redirect_endpoints(), GURL("https://google.ws"), 20, 20, 0); redirect_data.UpdateData(google.primary_key(), google); EXPECT_FALSE(predictor_->GetRedirectEndpoint("google.com", redirect_data, &redirect_endpoint)); } TEST_F(ResourcePrefetchPredictorTest, TestPredictPreconnectOrigins) { const GURL main_frame_url("http://google.com/?query=cats"); auto prediction = std::make_unique<PreconnectPrediction>(); // No prefetch data. EXPECT_FALSE(predictor_->IsUrlPreconnectable(main_frame_url)); EXPECT_FALSE( predictor_->PredictPreconnectOrigins(main_frame_url, prediction.get())); const char* cdn_origin = "https://cdn%d.google.com"; auto gen_origin = [cdn_origin](int n) { return base::StringPrintf(cdn_origin, n); }; // Add origins associated with the main frame host. OriginData google = CreateOriginData("google.com"); InitializeOriginStat(google.add_origins(), gen_origin(1), 10, 0, 0, 1.0, true, true); // High confidence - preconnect. InitializeOriginStat(google.add_origins(), gen_origin(2), 10, 5, 0, 2.0, true, true); // Medium confidence - preresolve. InitializeOriginStat(google.add_origins(), gen_origin(3), 1, 10, 10, 3.0, true, true); // Low confidence - ignore. predictor_->origin_data_->UpdateData(google.host(), google); prediction = std::make_unique<PreconnectPrediction>(); EXPECT_TRUE(predictor_->IsUrlPreconnectable(main_frame_url)); EXPECT_TRUE( predictor_->PredictPreconnectOrigins(main_frame_url, prediction.get())); EXPECT_EQ(*prediction, CreatePreconnectPrediction( "google.com", false, {{GURL(gen_origin(1)), 1}, {GURL(gen_origin(2)), 0}})); // Add a redirect. RedirectData redirect = CreateRedirectData("google.com", 3); InitializeRedirectStat(redirect.add_redirect_endpoints(), GURL("https://www.google.com"), 10, 0, 0); predictor_->host_redirect_data_->UpdateData(redirect.primary_key(), redirect); // Prediction failed: no data associated with the redirect endpoint. prediction = std::make_unique<PreconnectPrediction>(); EXPECT_FALSE(predictor_->IsUrlPreconnectable(main_frame_url)); EXPECT_FALSE( predictor_->PredictPreconnectOrigins(main_frame_url, prediction.get())); // Add a resource associated with the redirect endpoint. OriginData www_google = CreateOriginData("www.google.com", 4); InitializeOriginStat(www_google.add_origins(), gen_origin(4), 10, 0, 0, 1.0, true, true); // High confidence - preconnect. predictor_->origin_data_->UpdateData(www_google.host(), www_google); prediction = std::make_unique<PreconnectPrediction>(); EXPECT_TRUE(predictor_->IsUrlPreconnectable(main_frame_url)); EXPECT_TRUE( predictor_->PredictPreconnectOrigins(main_frame_url, prediction.get())); EXPECT_EQ(*prediction, CreatePreconnectPrediction("www.google.com", true, {{GURL(gen_origin(4)), 1}})); } } // namespace predictors
2d8ef16ff2c3cd824dcc2bae0a69d8e6f5b80406
eeb1455f6557a10b01cbd988be0b5c4e58e42625
/ddraw/ddraw.h
d7046a79e6aecb88b2c18334613b021322621b8c
[ "Zlib" ]
permissive
albykunx3/dxwrapper
961c9c277f4b0d219a1e1d4bb7295fff69172e3f
fff67ed5c0e066decf64da94613a5a106f6349d8
refs/heads/master
2020-03-09T04:16:02.755178
2018-04-04T08:22:22
2018-04-04T08:22:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,177
h
#pragma once #define INITGUID #include <ddraw.h> #include <ddrawex.h> #include <d3d.h> class m_IDirectDraw; class m_IDirectDraw2; class m_IDirectDraw3; class m_IDirectDraw4; class m_IDirectDraw7; class m_IDirectDrawSurface; class m_IDirectDrawSurface2; class m_IDirectDrawSurface3; class m_IDirectDrawSurface4; class m_IDirectDrawSurface7; #include "AddressLookupTable.h" #include "Settings\Settings.h" #include "Logging\Logging.h" typedef void(WINAPI *AcquireDDThreadLockProc)(); typedef HRESULT(WINAPI *D3DParseUnknownCommandProc)(LPVOID lpCmd, LPVOID *lpRetCmd); typedef HRESULT(WINAPI *DirectDrawCreateProc)(GUID FAR *lpGUID, LPDIRECTDRAW FAR *lplpDD, IUnknown FAR *pUnkOuter); typedef HRESULT(WINAPI *DirectDrawCreateClipperProc)(DWORD dwFlags, LPDIRECTDRAWCLIPPER *lplpDDClipper, LPUNKNOWN pUnkOuter); typedef HRESULT(WINAPI *DDrawEnumerateAProc)(LPDDENUMCALLBACKA lpCallback, LPVOID lpContext); typedef HRESULT(WINAPI *DDrawEnumerateExAProc)(LPDDENUMCALLBACKEXA lpCallback, LPVOID lpContext, DWORD dwFlags); typedef HRESULT(WINAPI *DDrawEnumerateExWProc)(LPDDENUMCALLBACKEXW lpCallback, LPVOID lpContext, DWORD dwFlags); typedef HRESULT(WINAPI *DDrawEnumerateWProc)(LPDDENUMCALLBACKW lpCallback, LPVOID lpContext); typedef HRESULT(WINAPI *DDrawCreateExProc)(GUID FAR *lpGUID, LPVOID *lplpDD, REFIID riid, IUnknown FAR *pUnkOuter); typedef HRESULT(WINAPI *DllCanUnloadNowProc)(); typedef HRESULT(WINAPI *DllGetClassObjectProc)(REFCLSID rclsid, REFIID riid, LPVOID *ppv); typedef HRESULT(WINAPI *GetSurfaceFromDCProc)(HDC hdc, LPDIRECTDRAWSURFACE7 *lpDDS); typedef void(WINAPI *ReleaseDDThreadLockProc)(); typedef HRESULT(WINAPI *SetAppCompatDataProc)(DWORD, DWORD); REFIID ConvertREFIID(REFIID riid); HRESULT ProxyQueryInterface(LPVOID ProxyInterface, REFIID CalledID, LPVOID * ppvObj, REFIID CallerID, LPVOID WrapperInterface); void genericQueryInterface(REFIID riid, LPVOID * ppvObj); extern AddressLookupTableDdraw<void> ProxyAddressLookupTable; // Direct3D #include "IDirect3D.h" #include "IDirect3D2.h" #include "IDirect3D3.h" #include "IDirect3D7.h" #include "IDirect3DDevice.h" #include "IDirect3DDevice2.h" #include "IDirect3DDevice3.h" #include "IDirect3DDevice7.h" #include "IDirect3DExecuteBuffer.h" #include "IDirect3DLight.h" #include "IDirect3DMaterial.h" #include "IDirect3DMaterial2.h" #include "IDirect3DMaterial3.h" #include "IDirect3DTexture.h" #include "IDirect3DTexture2.h" #include "IDirect3DVertexBuffer.h" #include "IDirect3DVertexBuffer7.h" #include "IDirect3DViewport.h" #include "IDirect3DViewport2.h" #include "IDirect3DViewport3.h" // DirectDraw #include "IDirectDrawX.h" #include "IDirectDraw.h" #include "IDirectDraw2.h" #include "IDirectDraw3.h" #include "IDirectDraw4.h" #include "IDirectDraw7.h" #include "IDirectDrawClipper.h" #include "IDirectDrawColorControl.h" #include "IDirectDrawEnumCallback.h" #include "IDirectDrawFactory.h" #include "IDirectDrawGammaControl.h" #include "IDirectDrawPalette.h" #include "IDirectDrawSurfaceX.h" #include "IDirectDrawSurface.h" #include "IDirectDrawSurface2.h" #include "IDirectDrawSurface3.h" #include "IDirectDrawSurface4.h" #include "IDirectDrawSurface7.h" #include "IDirectDrawTypes.h"
25c2b6f4efbee02fb3357004178edcc149a6e481
d2aac673c7a50c25681bf9da76e9622ada6ecab9
/Engine/src/graphics/layers/layer.h
1c17d9758bde109fcc5431041a48e79d9741b2ff
[]
no_license
Basicula/Engine
72d44a7b6c47fa702793a595f280a0abf30e5486
78b9c5949f69baf51fdb24154c14467de5050823
refs/heads/master
2021-04-26T22:28:31.116805
2018-03-16T20:12:23
2018-03-16T20:12:23
124,097,288
0
0
null
null
null
null
UTF-8
C++
false
false
482
h
#pragma once #include "../renderer2d.h" #include "../renderable2d.h" namespace Engine { namespace Graphics { class Layer { protected: Renderer2D * m_Renderer; std::vector<Renderable2D*> m_Renderables; Shader* m_Shader; Math::mat4 m_ProjectionMatrix; protected: Layer(Renderer2D* renderer, Shader* shader, Math::mat4 projectionMatrix); public: virtual ~Layer(); virtual void add(Renderable2D* renderable); virtual void render(); }; } }
4a49d74f0befecea3d10df6cdbd28e5f0f5bd9b8
f68082abf520ff5f83827a65ea1ed72990e40cb0
/100_sameTree/main.cpp
0e738cb759ee7fda96139b23180444ca7a928534
[]
no_license
whitefusion/AlgorithmPractice_C
b659d739ea6096f1d521ea08b4a8e60d6581645b
a7cded04b6d80abeb19cd5e681c5595832587d31
refs/heads/master
2021-01-11T21:42:57.323790
2017-03-03T14:51:56
2017-03-03T14:51:56
78,838,425
0
0
null
null
null
null
UTF-8
C++
false
false
563
cpp
#include <iostream> struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: bool isSameTree(TreeNode* p, TreeNode* q) { if(p == NULL && q == NULL) return true; if((p == NULL && q != NULL) || (p != NULL && q == NULL)) return false; if(p->val != q->val) return false; return isSameTree(p->right,q->right) && isSameTree(p->left,q->left); } }; int main() { std::cout << "Hello, World!" << std::endl; return 0; }
701457f559fe78226c1af51685e7a6cc46879e71
942b7b337019aa52862bce84a782eab7111010b1
/xray/Layers/xrRender/DetailManager_soft.cpp
7370a6989675f1dc293adbee1db9933c49c70049
[]
no_license
galek/xray15
338ad7ac5b297e9e497e223e0fc4d050a4a78da8
015c654f721e0fbed1ba771d3c398c8fa46448d9
refs/heads/master
2021-11-23T12:01:32.800810
2020-01-10T15:52:45
2020-01-10T15:52:45
168,657,320
0
0
null
2019-02-01T07:11:02
2019-02-01T07:11:01
null
UTF-8
C++
false
false
4,951
cpp
#include "stdafx.h" #include "detailmanager.h" const u32 vs_size = 3000; void CDetailManager::soft_Load () { R_ASSERT(RCache.Vertex.Buffer()); R_ASSERT(RCache.Index.Buffer()); // Vertex Stream soft_Geom.create (D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1, RCache.Vertex.Buffer(), RCache.Index.Buffer()); } void CDetailManager::soft_Unload () { soft_Geom.destroy (); } void CDetailManager::soft_Render () { // Render itself // float fPhaseRange = PI/16; // float fPhaseX = _sin(Device.fTimeGlobal*0.1f) *fPhaseRange; // float fPhaseZ = _sin(Device.fTimeGlobal*0.11f)*fPhaseRange; // Get index-stream _IndexStream& _IS = RCache.Index; _VertexStream& _VS = RCache.Vertex; for (u32 O=0; O<objects.size(); O++) { CDetail& Object = *objects[O]; u32 vCount_Object = Object.number_vertices; u32 iCount_Object = Object.number_indices; xr_vector<SlotItemVec*>& _vis = m_visibles[0][O]; xr_vector <SlotItemVec* >::iterator _vI = _vis.begin(); xr_vector <SlotItemVec* >::iterator _vE = _vis.end(); for (; _vI!=_vE; _vI++){ SlotItemVec* items = *_vI; u32 vCount_Total = items->size()*vCount_Object; // calculate lock count needed u32 lock_count = vCount_Total/vs_size; if (vCount_Total>(lock_count*vs_size)) lock_count++; // calculate objects per lock u32 o_total = items->size(); u32 o_per_lock = o_total/lock_count; if (o_total > (o_per_lock*lock_count)) o_per_lock++; // Fill VB (and flush it as nesessary) RCache.set_Shader (Object.shader); Fmatrix mXform; for (u32 L_ID=0; L_ID<lock_count; L_ID++){ // Calculate params u32 item_start = L_ID*o_per_lock; u32 item_end = item_start+o_per_lock; if (item_end>o_total) item_end = o_total; if (item_end<=item_start) break; u32 item_range = item_end-item_start; // Calc Lock params u32 vCount_Lock = item_range*vCount_Object; u32 iCount_Lock = item_range*iCount_Object; // Lock buffers u32 vBase,iBase,iOffset=0; CDetail::fvfVertexOut* vDest = (CDetail::fvfVertexOut*) _VS.Lock(vCount_Lock,soft_Geom->vb_stride,vBase); u16* iDest = (u16*) _IS.Lock(iCount_Lock,iBase); // Filling itself for (u32 item_idx=item_start; item_idx<item_end; ++item_idx){ SlotItem& Instance = *items->at(item_idx); float scale = Instance.scale_calculated; // Build matrix Fmatrix& M = Instance.mRotY; mXform._11=M._11*scale; mXform._12=M._12*scale; mXform._13=M._13*scale; mXform._14=M._14; mXform._21=M._21*scale; mXform._22=M._22*scale; mXform._23=M._23*scale; mXform._24=M._24; mXform._31=M._31*scale; mXform._32=M._32*scale; mXform._33=M._33*scale; mXform._34=M._34; mXform._41=M._41; mXform._42=M._42; mXform._43=M._43; mXform._44=1; // Transfer vertices { u32 C = 0xffffffff; CDetail::fvfVertexIn *srcIt = Object.vertices, *srcEnd = Object.vertices+Object.number_vertices; CDetail::fvfVertexOut *dstIt = vDest; for (; srcIt!=srcEnd; srcIt++, dstIt++){ mXform.transform_tiny (dstIt->P,srcIt->P); dstIt->C = C; dstIt->u = srcIt->u; dstIt->v = srcIt->v; } } // Transfer indices (in 32bit lines) VERIFY (iOffset<65535); { u32 item = (iOffset<<16) | iOffset; u32 count = Object.number_indices/2; LPDWORD sit = LPDWORD(Object.indices); LPDWORD send = sit+count; LPDWORD dit = LPDWORD(iDest); for (; sit!=send; dit++,sit++) *dit=*sit+item; if (Object.number_indices&1) iDest[Object.number_indices-1]=(u16)(Object.indices[Object.number_indices-1]+u16(iOffset)); } // Increment counters vDest += vCount_Object; iDest += iCount_Object; iOffset += vCount_Object; } _VS.Unlock (vCount_Lock,soft_Geom->vb_stride); _IS.Unlock (iCount_Lock); // Render u32 dwNumPrimitives = iCount_Lock/3; RCache.set_Geometry (soft_Geom); RCache.Render (D3DPT_TRIANGLELIST,vBase,0,vCount_Lock,iBase,dwNumPrimitives); } } // Clean up _vis.clear_not_free (); } } /* //. VERIFY(sizeof(CDetail::fvfVertexOut)==soft_Geom->vb_stride); CDetail::fvfVertexOut *dstIt = vDest; VERIFY(items->size()*Object.number_vertices==vCount_Lock); for (u32 k=0; k<vCount_Lock; k++) { // Transfer vertices { u32 C = 0xffffffff; CDetail::fvfVertexIn *srcIt = Object.vertices, *srcEnd = Object.vertices+Object.number_vertices; CDetail::fvfVertexOut *dstIt = vDest; for (; srcIt!=srcEnd; srcIt++, dstIt++) { mXform.transform_tiny (dstIt->P,srcIt->P); dstIt->C = C; dstIt->u = srcIt->u; dstIt->v = srcIt->v; } } } */
54d635841bbf10b6971b6458c32c3b30090239d4
ab772d6c5ee1aa571d5b579356e00eb9090d8a08
/qtlearnings/paramconfig/Util/ItemBase.cpp
fc15d5062f718e1f35672a76f298e49f1d8628ea
[]
no_license
ldhshao/mylearnings
916ecaf67487c12272ab9ba1f22a8c10bcf888d7
d20fc1640a9da379fc946573ce11df1b924a017c
refs/heads/master
2022-03-12T17:59:08.908442
2022-01-05T10:02:05
2022-01-05T10:02:05
234,214,640
0
0
null
2020-09-25T07:59:07
2020-01-16T02:11:03
JavaScript
UTF-8
C++
false
false
3,324
cpp
#include "ItemBase.h" #include <qtextstream.h> #include <QtDebug> HNDZ_IMPLEMENT_DYNCREATE(XmlItem, BaseObject) bool XmlItem::initFromDomElement(QDomElement element) { QString strId, strName; strId = element.attribute("id"); strName = element.attribute("name"); if (!strId.isEmpty()) m_id = strId.toInt(); if (!strName.isEmpty()) m_name = strName; return true; } void XmlItem::dump() { qDebug()<<"ID "<<m_id<<" name "<<m_name; } HNDZ_IMPLEMENT_DYNCREATE(XmlList, XmlItem) ReflectFactory XmlList::m_reflectFactory; XmlList::~XmlList() { deleteAll(); } bool XmlList::readXmlFile(QString strFile) { QFile file(strFile); if(!file.exists(strFile)) { return false; } if(!file.open(QIODevice::ReadOnly)) { return false; } QDomDocument doc; QTextStream stream(file.readAll()); if(!doc.setContent(stream.readAll())) //QString err; //int iLine, iCol; //if(!doc.setContent(file.readAll(), false, &err, &iLine, &iCol)) { file.close(); return false; } file.close(); qDebug()<<"load successfully 1"; qWarning()<<"load successfully 2"; return initFromDomElement(doc.documentElement()); } void XmlList::deleteAll() { QList<XmlItem*>::ConstIterator it = m_children.cbegin(); for (; it != m_children.cend(); it++){ delete *it; } m_children.clear(); } XmlItem* XmlList::getHead() { m_it = m_children.begin(); if (m_children.end() != m_it) return *m_it; return nullptr; } XmlItem* XmlList::getNext() { if (m_children.end() != m_it){ m_it++; if (m_children.end() != m_it) return *m_it; } return nullptr; } XmlItem* XmlList::getItemById(int id) { if (id == m_id) return this; QList<XmlItem*>::iterator it = m_children.begin(); for (; it != m_children.cend(); it++){ XmlList *pList = dynamic_cast<XmlList*>(*it); if (nullptr != pList){ XmlItem* pItem = pList->getItemById(id); if (nullptr != pItem) return pItem; }else { if (id == (*it)->getId()) return *it; } } return nullptr; } bool XmlList::initFromDomElement(QDomElement element) { if (XmlItem::initFromDomElement(element)) return initChildrenFromDomElement(element.childNodes()); return false; } bool XmlList::initChildrenFromDomElement(QDomNodeList list) { int count = list.count(); for(int i = 0; i < count; i++) { QDomNode dn = list.at(i); if(dn.isElement()) { QDomElement ele = dn.toElement(); QString tag = ele.tagName(); const char *strName = tag.toUtf8().constData(); //create XmlItem XmlItem* pItem = dynamic_cast<XmlItem*>(m_reflectFactory.CreateObject(ele.tagName().toUtf8().constData())); if (nullptr == pItem) return false; //init from Dom pItem->initFromDomElement(ele); //add list m_children.append(pItem); } } } void XmlList::dump() { XmlItem::dump(); QList<XmlItem*>::ConstIterator it = m_children.cbegin(); for (; it != m_children.cend(); it++){ (*it)->dump(); } }
fec9231edce99afc06d051bae44fe1784929bc64
b0a7ea0cd1daf9f20237e63803bbe9b365256e19
/app/src/main/jni/Irrlicht/modes/follow_the_leader.cpp
116a2b72379fdbbdb020cac9d1c248df05d07034
[]
no_license
marky0720/STK_android
bac4ba54e89ccb357503abe92f4c59e06b10c427
3205b46788da71c387af2d2b71a927d0ba45952a
refs/heads/master
2021-04-30T07:56:24.419223
2018-03-12T10:45:57
2018-03-12T10:45:57
121,360,998
0
0
null
2018-02-13T09:05:50
2018-02-13T09:05:49
null
UTF-8
C++
false
false
6,771
cpp
// SuperTuxKart - a fun racing game with go-kart // Copyright (C) 2004 SuperTuxKart-Team // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 3 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include "modes/follow_the_leader.hpp" #include "audio/music_manager.hpp" #include "challenges/unlock_manager.hpp" #include "config/user_config.hpp" #include "items/powerup_manager.hpp" #include "states_screens/race_gui_base.hpp" #include "tracks/track.hpp" #include "utils/translation.hpp" //----------------------------------------------------------------------------- FollowTheLeaderRace::FollowTheLeaderRace() : LinearWorld() { // We have to make sure that no kart finished the set number of laps // in a FTL race (since otherwise its distance will not be computed // correctly, and as a result e.g. a leader might suddenly fall back // after crossing the start line race_manager->setNumLaps(99999); m_leader_intervals = stk_config->m_leader_intervals; for(unsigned int i=0; i<m_leader_intervals.size(); i++) m_leader_intervals[i] += stk_config->m_leader_time_per_kart*race_manager->getNumberOfKarts(); m_use_highscores = false; // disable high scores setClockMode(WorldStatus::CLOCK_COUNTDOWN, m_leader_intervals[0]); } //----------------------------------------------------------------------------- FollowTheLeaderRace::~FollowTheLeaderRace() { } #if 0 #pragma mark - #pragma mark clock events #endif //----------------------------------------------------------------------------- /** Returns the original time at which the countdown timer started. This is * used by the race_gui to display the music credits in FTL mode correctly. */ float FollowTheLeaderRace::getClockStartTime() { return m_leader_intervals[0]; } // getClockStartTime //----------------------------------------------------------------------------- /** Called when a kart must be eliminated. */ void FollowTheLeaderRace::countdownReachedZero() { if(m_leader_intervals.size()>1) m_leader_intervals.erase(m_leader_intervals.begin()); WorldStatus::setTime(m_leader_intervals[0]); // If the leader kart is not the first kart, remove the first // kart, otherwise remove the last kart. int position_to_remove = m_karts[0]->getPosition()==1 ? getCurrentNumKarts() : 1; Kart *kart = getKartAtPosition(position_to_remove); if(!kart || kart->isEliminated()) { fprintf(stderr,"Problem with removing leader: position %d not found\n", position_to_remove); for(unsigned int i=0; i<m_karts.size(); i++) { fprintf(stderr,"kart %d: eliminated %d position %d\n", i,m_karts[i]->isEliminated(), m_karts[i]->getPosition()); } // for i } // else { removeKart(kart->getWorldKartId()); // In case that the kart on position 1 was removed, we have // to set the correct position (which equals the remaining // number of karts) for the removed kart, as well as recompute // the position for all other karts if(position_to_remove==1) { // We have to add 1 to the number of karts to get the correct // position, since the eliminated kart was already removed // from the value returned by getCurrentNumKarts (and we have // to remove the kart before we can call updateRacePosition). // Note that we can not call WorldWithRank::setKartPosition // here, since it would not properly support debugging kart // ranks (since this kart would get its position set again // in updateRacePosition). We only set the rank of the eliminated // kart, and updateRacePosition will then call setKartPosition // for the now eliminated kart. kart->setPosition(getCurrentNumKarts()+1); updateRacePosition(); } } // almost over, use fast music if(getCurrentNumKarts()==3) { music_manager->switchToFastMusic(); } if (isRaceOver()) { // Mark all still racing karts to be finished. for (unsigned int n=0; n<m_karts.size(); n++) { if (!m_karts[n]->isEliminated() && !m_karts[n]->hasFinishedRace()) { m_karts[n]->finishedRace(getTime()); } } } // End of race is detected from World::updateWorld() } // countdownReachedZero //----------------------------------------------------------------------------- /** The follow the leader race is over if there is only one kart left (plus * the leader), or if all (human) players have been eliminated. */ bool FollowTheLeaderRace::isRaceOver() { return getCurrentNumKarts()==2 || getCurrentNumPlayers()==0; } // isRaceOver //----------------------------------------------------------------------------- void FollowTheLeaderRace::restartRace() { LinearWorld::restartRace(); m_leader_intervals.clear(); m_leader_intervals = stk_config->m_leader_intervals; for(unsigned int i=0; i<m_leader_intervals.size(); i++) m_leader_intervals[i] += stk_config->m_leader_time_per_kart*race_manager->getNumberOfKarts(); WorldStatus::setClockMode(WorldStatus::CLOCK_COUNTDOWN, m_leader_intervals[0]); } // restartRace //----------------------------------------------------------------------------- /** Returns the internal identifier for this kind of race. */ std::string FollowTheLeaderRace::getIdent() const { return FTL_IDENT; } // getIdent //----------------------------------------------------------------------------- /** Sets the title for all karts that is displayed in the icon list. In * this mode the title for the first kart is set to 'leader'. */ RaceGUIBase::KartIconDisplayInfo* FollowTheLeaderRace::getKartsDisplayInfo() { LinearWorld::getKartsDisplayInfo(); m_kart_display_info[0].special_title = _("Leader"); return m_kart_display_info; } // getKartsDisplayInfo
2814357b14af5734bf567dc67432f4a1bf2ed98a
238ff696ee7e5490326f9662a092a92a0c736c70
/_studio/shared/mfx_trace/src/mfx_reflect.cpp
9d23986d32870741fade326f867c0ab7470ebc2f
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "Intel" ]
permissive
dongbaoy/MediaSDK
f677949fd1762f95c7940037f9f57a2b2c66bfbf
563f94e99939f0c27745fc51cceca90343eb5452
refs/heads/master
2021-04-06T06:24:05.869031
2018-03-19T01:20:27
2018-03-19T01:20:27
124,819,229
0
0
MIT
2018-03-12T01:51:09
2018-03-12T01:51:09
null
UTF-8
C++
false
false
21,124
cpp
// Copyright (c) 2017 Intel Corporation // // 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 "mfx_reflect.h" #include <iostream> #include <iomanip> #include <sstream> #include <algorithm> #include <cstddef> #include "mfxstructures.h" #include "mfxvp8.h" #include "mfxplugin.h" #include "mfxmvc.h" #include "mfxfei.h" #include "mfxla.h" #if (MFX_VERSION >= MFX_VERSION_NEXT) #include "mfxfeihevc.h" #endif #if (MFX_VERSION >= 1025) #include "ts_typedef.h" #include <memory> namespace mfx_reflect { template<class T> struct mfx_ext_buffer_id { enum { id = 0 }; }; #define EXTBUF(STRUCT, ID) \ template<>struct mfx_ext_buffer_id<STRUCT> { \ enum { id = ID }; }; #include "ts_ext_buffers_decl.h" void AccessorField::SetFieldAddress() { m_P = (*m_Iterator)->GetAddress(m_BaseStruct.m_P); char *result = (char*)m_P; result += m_pReflection->FieldType->Size * m_IndexElement; m_P = (void*)result; } AccessorField& AccessorField::operator++() { m_IndexElement = 0; m_Iterator++; if (IsValid()) { SetIterator(m_Iterator); } return *this; } bool AccessorField::IsValid() const { return m_Iterator != m_BaseStruct.m_pReflection->m_Fields.end(); } AccessorType AccessorField::AccessSubtype() const { return AccessorType(m_P, *(m_pReflection->FieldType)); } AccessorField AccessorType::AccessField(ReflectedField::FieldsCollectionCI iter) const { if (m_pReflection->m_Fields.end() != iter) { return AccessorField(*this, iter); // Address of base, not field. } else { throw std::invalid_argument(std::string("No such field")); } } AccessorField AccessorType::AccessField(const std::string& fieldName) const { ReflectedField::FieldsCollectionCI iter = m_pReflection->FindField(fieldName); return AccessField(iter); } AccessorField AccessorType::AccessFirstField() const { return AccessField(m_pReflection->m_Fields.begin()); } AccessorType AccessorType::AccessSubtype(const std::string& fieldName) const { return AccessField(fieldName).AccessSubtype(); } ReflectedType::ReflectedType(ReflectedTypesCollection *pCollection, std::type_index typeIndex, const std::string& typeName, size_t size, bool isPointer, mfxU32 extBufferId) : m_TypeIndex(typeIndex) , TypeNames(1, typeName) , Size(size) , m_pCollection(pCollection) , m_bIsPointer(isPointer) , ExtBufferId(extBufferId) { if (NULL == m_pCollection) { m_pCollection = NULL; } } ReflectedField::SP ReflectedType::AddField(std::type_index typeIndex, const std::string &typeName, size_t typeSize, bool isPointer, size_t offset, const std::string &fieldName, size_t count, mfxU32 extBufferId) { ReflectedField::SP pField; if (typeName.empty()) { throw std::invalid_argument(std::string("Unexpected behavior - typeName is empty")); } if (NULL == m_pCollection) { return pField; } else { ReflectedType* pType = m_pCollection->FindOrDeclareType(typeIndex, typeName, typeSize, isPointer, extBufferId).get(); if (pType != NULL) { StringList::iterator findIterator = std::find(pType->TypeNames.begin(), pType->TypeNames.end(), typeName); if (pType->TypeNames.end() == findIterator) { throw std::invalid_argument(std::string("Unexpected behavior - fieldTypeName is NULL")); } m_Fields.push_back(ReflectedField::SP(new ReflectedField(m_pCollection, this, pType, *findIterator, offset, fieldName, count))); //std::make_shared cannot access protected constructor pField = m_Fields.back(); } return pField; } } ReflectedField::FieldsCollectionCI ReflectedType::FindField(const std::string& fieldName) const { ReflectedField::FieldsCollectionCI iter = m_Fields.begin(); for (; iter != m_Fields.end(); ++iter) { if ((*iter)->FieldName == fieldName) { break; } } return iter; } ReflectedType::SP ReflectedTypesCollection::FindExistingByTypeInfoName(const char* name) //currenly we are not using this { for (Container::iterator iter = m_KnownTypes.begin(); iter != m_KnownTypes.end(); ++iter) { if (0 == strcmp(iter->first.name(), name)) { return iter->second; } } ReflectedType::SP pEmptyType; return pEmptyType; } ReflectedType::SP ReflectedTypesCollection::FindExistingType(std::type_index typeIndex) { Container::const_iterator it = m_KnownTypes.find(typeIndex); if (m_KnownTypes.end() != it) { return it->second; } ReflectedType::SP pEmptyType; return pEmptyType; } ReflectedType::SP ReflectedTypesCollection::FindExtBufferTypeById(mfxU32 ExtBufferId) //optimize with map (index -> type) { for (Container::iterator iter = m_KnownTypes.begin(); iter != m_KnownTypes.end(); ++iter) { if (ExtBufferId == iter->second->ExtBufferId) { return iter->second; } } ReflectedType::SP pEmptyExtBufferType; return pEmptyExtBufferType; } ReflectedType::SP ReflectedTypesCollection::DeclareType(std::type_index typeIndex, const std::string& typeName, size_t typeSize, bool isPointer, mfxU32 extBufferId) { if (m_KnownTypes.end() == m_KnownTypes.find(typeIndex)) { ReflectedType::SP pType; pType = std::make_shared<ReflectedType>(this, typeIndex, typeName, typeSize, isPointer, extBufferId); m_KnownTypes.insert(std::make_pair(pType->m_TypeIndex, pType)); return pType; } throw std::invalid_argument(std::string("Unexpected behavior - type is already declared")); } ReflectedType::SP ReflectedTypesCollection::FindOrDeclareType(std::type_index typeIndex, const std::string& typeName, size_t typeSize, bool isPointer, mfxU32 extBufferId) { ReflectedType::SP pType = FindExistingType(typeIndex); if (pType == NULL) { pType = DeclareType(typeIndex, typeName, typeSize, isPointer, extBufferId); } else { if (typeSize != pType->Size) { pType.reset(); } else if (!typeName.empty()) { ReflectedType::StringList::iterator findIterator = std::find(pType->TypeNames.begin(), pType->TypeNames.end(), typeName); if (pType->TypeNames.end() == findIterator) { pType->TypeNames.push_back(typeName); } } } return pType; } template <class T> bool PrintFieldIfTypeMatches(std::ostream& stream, AccessorField field) { bool bResult = false; if (field.m_pReflection->FieldType->m_TypeIndex == field.m_pReflection->m_pCollection->FindExistingType<T>()->m_TypeIndex) { stream << field.Get<T>(); bResult = true; } return bResult; } void PrintFieldValue(std::ostream &stream, AccessorField field) { if (field.m_pReflection->FieldType->m_bIsPointer) { stream << "0x" << field.Get<void*>(); } else { bool bPrinted = false; #define PRINT_IF_TYPE(T) if (!bPrinted) { bPrinted = PrintFieldIfTypeMatches<T>(stream, field); } PRINT_IF_TYPE(mfxU16); PRINT_IF_TYPE(mfxI16); PRINT_IF_TYPE(mfxU32); PRINT_IF_TYPE(mfxI32); if (!bPrinted) { size_t fieldSize = field.m_pReflection->FieldType->Size; { stream << "<Unknown type \"" << field.m_pReflection->FieldType->m_TypeIndex.name() << "\" (size = " << fieldSize << ")>"; } } } } void PrintFieldName(std::ostream &stream, AccessorField field) { stream << field.m_pReflection->FieldName; if (field.m_pReflection->Count > 1) { stream << "[" << field.GetIndexElement() << "]"; } } std::ostream& operator<< (std::ostream& stream, AccessorField field) { PrintFieldName(stream, field); stream << " = "; PrintFieldValue(stream, field); return stream; } std::ostream& operator<< (std::ostream& stream, AccessorType data) { stream << data.m_pReflection->m_TypeIndex.name() << " = {"; size_t nFields = data.m_pReflection->m_Fields.size(); for (AccessorField field = data.AccessFirstField(); field.IsValid(); ++field) { if (nFields > 1) { stream << std::endl; } stream << "\t" << field; } stream << "}"; return stream; } TypeComparisonResultP CompareExtBufferLists(mfxExtBuffer** pExtParam1, mfxU16 numExtParam1, mfxExtBuffer** pExtParam2, mfxU16 numExtParam2, ReflectedTypesCollection* collection); AccessorTypeP GetAccessorOfExtBufferOriginalType(mfxExtBuffer& pExtInnerParam, ReflectedTypesCollection& collection); TypeComparisonResultP CompareTwoStructs(AccessorType data1, AccessorType data2) // Always return not null result { TypeComparisonResultP result = std::make_shared<TypeComparisonResult>(); if (data1.m_pReflection != data2.m_pReflection) { throw std::invalid_argument(std::string("Types mismatch")); } mfxExtBuffer** pExtParam1 = NULL; mfxExtBuffer** pExtParam2 = NULL; mfxU16 numExtParam = 0; for (AccessorField field1 = data1.AccessFirstField(); field1.IsValid(); ++field1) { AccessorField field2 = data2.AccessField(field1.m_Iterator); if (std::type_index(typeid(mfxExtBuffer**)) == field1.m_pReflection->FieldType->m_TypeIndex) { pExtParam1 = field1.Get<mfxExtBuffer**>(); pExtParam2 = field2.Get<mfxExtBuffer**>(); } else if ((field1.m_pReflection->FieldName == "NumExtParam") && (field1.m_pReflection->FieldType->m_TypeIndex == std::type_index(typeid(mfxU16))) && (field2.m_pReflection->FieldType->m_TypeIndex == std::type_index(typeid(mfxU16)))) { if (field1.Get<mfxU16>() == field2.Get<mfxU16>()) { numExtParam = field1.Get<mfxU16>(); } else { throw std::invalid_argument(std::string("NumExtParam mismatch")); } } else { for (size_t i = 0; i < field1.m_pReflection->Count; ++i) { field1.SetIndexElement(i); field2.SetIndexElement(i); AccessorType subtype1 = field1.AccessSubtype(); TypeComparisonResultP subtypeResult = NULL; if (subtype1.m_pReflection->m_Fields.size() > 0) { AccessorType subtype2 = field2.AccessSubtype(); if (subtype1.m_pReflection != subtype2.m_pReflection) { throw std::invalid_argument(std::string("Subtypes mismatch - should never happen for same types")); } subtypeResult = CompareTwoStructs(subtype1, subtype2); } if (!field1.Equal(field2)) { FieldComparisonResult fields = { field1 , field2, subtypeResult }; result->push_back(fields); } } } } if ((pExtParam1 != NULL) && (pExtParam2 != NULL) && (numExtParam > 0)) { TypeComparisonResultP extBufferCompareResult = CompareExtBufferLists(pExtParam1, numExtParam, pExtParam2, numExtParam, data1.AccessFirstField().m_pReflection->m_pCollection); if (extBufferCompareResult != NULL) { result->splice(result->end(), *extBufferCompareResult); //move elements of *extBufferCompareResult to the end of *result if (!extBufferCompareResult->extBufferIdList.empty()) { result->extBufferIdList.splice(result->extBufferIdList.end(), extBufferCompareResult->extBufferIdList); } } else { throw std::invalid_argument(std::string("Unexpected behavior - ExtBuffer comparison result is NULL")); } } return result; } AccessorTypeP GetAccessorOfExtBufferOriginalType(mfxExtBuffer& pExtBufferParam, ReflectedTypesCollection& collection) { AccessorTypeP pExtBuffer; mfxU32 id = pExtBufferParam.BufferId; if (0 != id) { ReflectedType::SP pTypeExtBuffer = collection.FindExtBufferTypeById(id); //find in KnownTypes this BufferId if (pTypeExtBuffer != NULL) { pExtBuffer = std::make_shared<AccessorType>(&pExtBufferParam, *pTypeExtBuffer); } } return pExtBuffer; } TypeComparisonResultP CompareExtBufferLists(mfxExtBuffer** pExtParam1, mfxU16 numExtParam1, mfxExtBuffer** pExtParam2, mfxU16 numExtParam2, ReflectedTypesCollection* collection) //always return not null result { TypeComparisonResultP result = std::make_shared<TypeComparisonResult>(); if (NULL != pExtParam1 && NULL != pExtParam2 && NULL != collection) { for (int i = 0; i < numExtParam1 && i < numExtParam2; i++) { //supported only extBuffers with same Id order if (NULL != pExtParam1[i] && NULL != pExtParam2[i]) { AccessorTypeP extBufferOriginTypeAccessor1 = GetAccessorOfExtBufferOriginalType(*pExtParam1[i], *collection); AccessorTypeP extBufferOriginTypeAccessor2 = GetAccessorOfExtBufferOriginalType(*pExtParam2[i], *collection); if (NULL != extBufferOriginTypeAccessor1 && NULL != extBufferOriginTypeAccessor2) { TypeComparisonResultP tempResult = CompareTwoStructs(*extBufferOriginTypeAccessor1, *extBufferOriginTypeAccessor2); if (NULL != tempResult) { result->splice(result->end(), *tempResult); } else { throw std::invalid_argument(std::string("Unexpected behavior - comparison result is NULL")); } } else { result->extBufferIdList.push_back(pExtParam1[i]->BufferId); } } } } return result; } void PrintStuctsComparisonResult(std::ostream& comparisonResult, const std::string& prefix, const TypeComparisonResultP& result) { for (std::list<FieldComparisonResult>::iterator i = result->begin(); i != result->end(); ++i) { TypeComparisonResultP subtypeResult = i->subtypeComparisonResultP; ReflectedType* aggregatingType = i->accessorField1.m_pReflection->AggregatingType; std::list< std::string >::const_iterator it = aggregatingType->TypeNames.begin(); std::string strTypeName = ((it != aggregatingType->TypeNames.end()) ? *(it) : "unknown_type"); if (NULL != subtypeResult) { std::stringstream fieldName; PrintFieldName(fieldName, i->accessorField1); std::string strFieldName = fieldName.str(); std::string newprefix; newprefix = prefix.empty() ? (strTypeName + "." + strFieldName) : (prefix + "." + strFieldName); PrintStuctsComparisonResult(comparisonResult, newprefix, subtypeResult); } else { if (!prefix.empty()) { comparisonResult << prefix << "."; } else if (!strTypeName.empty()) { comparisonResult << strTypeName << "."; } comparisonResult << i->accessorField1 << " -> "; PrintFieldValue(comparisonResult, i->accessorField2); comparisonResult << std::endl; } } if (!result->extBufferIdList.empty()) { comparisonResult << "Id of unparsed ExtBuffer types: " << std::endl; while (!result->extBufferIdList.empty()) { unsigned char* FourCC = reinterpret_cast<unsigned char*>(&result->extBufferIdList.front()); comparisonResult << "0x" << std::hex << std::setfill('0') << result->extBufferIdList.front() << " \"" << FourCC[0] << FourCC[1] << FourCC[2] << FourCC[3] << "\""; result->extBufferIdList.pop_front(); if (!result->extBufferIdList.empty()) { comparisonResult << ", "; } } } } std::string CompareStructsToString(AccessorType data1, AccessorType data2) { std::ostringstream comparisonResult; if (data1.m_P == data2.m_P) { comparisonResult << "Comparing of VideoParams is unsupported: In and Out pointers are the same."; } else { comparisonResult << "Incompatible VideoParams were updated:" << std::endl; TypeComparisonResultP result = CompareTwoStructs(data1, data2); PrintStuctsComparisonResult(comparisonResult, "", result); } return comparisonResult.str(); } template <class T> ReflectedField::SP AddFieldT(ReflectedType &type, const std::string typeName, size_t offset, const std::string fieldName, size_t count) { unsigned int extBufId = 0; extBufId = mfx_ext_buffer_id<T>::id; bool isPointer = false; isPointer = std::is_pointer<T>(); return type.AddField(std::type_index(typeid(T)), typeName, sizeof(T), isPointer, offset, fieldName, count, extBufId); } template <class T> ReflectedType::SP DeclareTypeT(ReflectedTypesCollection& collection, const std::string typeName) { unsigned int extBufId = 0; extBufId = mfx_ext_buffer_id<T>::id; bool isPointer = false; isPointer = std::is_pointer<T>(); return collection.DeclareType(std::type_index(typeid(T)), typeName, sizeof(T), isPointer, extBufId); } void ReflectedTypesCollection::DeclareMsdkStructs() { #define STRUCT(TYPE, FIELDS) { \ typedef TYPE BaseType; \ ReflectedType::SP pType = DeclareTypeT<TYPE>(*this, #TYPE); \ FIELDS \ } #define FIELD_T(FIELD_TYPE, FIELD_NAME) \ (void)AddFieldT<FIELD_TYPE>( \ *pType, \ #FIELD_TYPE, \ offsetof(BaseType, FIELD_NAME), \ #FIELD_NAME, \ (sizeof(((BaseType*)0)->FIELD_NAME)/sizeof(::FIELD_TYPE)) ); #define FIELD_S(FIELD_TYPE, FIELD_NAME) FIELD_T(FIELD_TYPE, FIELD_NAME) #include "ts_struct_decl.h" } } #endif
31d4acbec7b5948df097c1034cdcc99bf1dc815a
9829d2cd112b340000f1a46bb71ccfbf3d8861d2
/mycaptain project2.cpp
db4b27a13a8c25e03490714c7405bc381f2d24e0
[]
no_license
shubham0412/mycaptain-Shubham-Thakur
4dfb36f569a713dab86e95e2cc58cdbab5f225f6
a30120d183e546443f3bb32eb0e8120473c708c9
refs/heads/master
2022-11-17T01:07:09.739226
2020-07-05T08:27:09
2020-07-05T08:27:09
277,260,295
0
0
null
null
null
null
UTF-8
C++
false
false
219
cpp
#include <iostream> using namespace std; int main() { double a, b, product; cout << "Enter two numbers: "; cin >> a >> b; product = a*b; cout << "Product = " << product; return 0; }
b8470cad6f90daca8db0527c4f95bbe4b3c4220e
1aa3331a3488c03b2891ad75a991e7a975dd8ced
/NeuralNetworkSimulator/neuralnetworksimulator.cpp
f316ac63d2ccc78b7ca644eaaddd4251d6f2b8a6
[]
no_license
mponza/NeuralNetworkSimulator
f3f6f21b18b21a042b950858e7852efd96776ae3
c72b09365ab32d8c1f707fa137832d25d25bc4af
refs/heads/master
2021-01-10T06:11:36.186244
2015-10-27T17:41:03
2015-10-27T17:41:03
45,058,610
0
0
null
null
null
null
UTF-8
C++
false
false
15,862
cpp
#include "neuralnetworksimulator.h" NeuralNetworkSimulator::NeuralNetworkSimulator() { trainingSet = fileManager.getTrainingSet(); testSet = fileManager.getTestSet(); } NeuralNetworkSimulator::NeuralNetworkSimulator(const int& monkIndex) { NeuralNetworkSimulator::monkIndex = monkIndex; fileManager = FileManager(monkIndex); trainingSet = fileManager.getTrainingSet(); testSet = fileManager.getTestSet(); } void NeuralNetworkSimulator::simulate(HyperParameters parameters) { if(monkIndex >= 1) { cout << "Running Monk "<< monkIndex << " Simulation" << endl; generateMonkPerformance(parameters); cout << "...end of the Monk "<< monkIndex << " Simulation" << endl; } else { cout << "Running Loc Simulation" << endl; generateLocPerformance(parameters); generateCompetition(parameters); cout << "...end of the Loc Simulation." << endl; } } void NeuralNetworkSimulator::simulate() { if(monkIndex >= 1) { cout << "Running Monk "<< monkIndex << " Simulation..." << endl; HyperParameters bestParameters; bestParameters = Validation(trainingSet.get1OfKDataSet()).validate(getMonkParameters()); generateMonkPerformance(bestParameters); cout << "...end of the Monk "<< monkIndex << " Simulation." << endl; } else { cout << "Running Loc Simulation..." << endl; vector<HyperParameters> bestParameters; bestParameters = CrossValidation(trainingSet.getScaledDataSet(), 5, 3, true).validate(getLocParameters()); bestParameters = CrossValidation(trainingSet.getScaledDataSet(), 10, 1, false).validate(getLocParameters()); generateLocPerformance(bestParameters[0]); generateCompetition(bestParameters[0]); cout << "...end of the Loc Simulation." << endl; } } /////////////////////////////////////////////////// Loc Functions ////////////////////////////////////////////////// vector<HyperParameters> NeuralNetworkSimulator::getLocParameters() const { vector<HyperParameters> parameters; vector<int> nNeurons; nNeurons.push_back(10); nNeurons.push_back(15); nNeurons.push_back(20); vector<double> etas; etas.push_back(0.005); vector<double> alphas; alphas.push_back(0); alphas.push_back(0.1); alphas.push_back(0.3); alphas.push_back(0.5); alphas.push_back(0.8); vector<double> lambdas; lambdas.push_back(0); lambdas.push_back(0.001); lambdas.push_back(0.003); lambdas.push_back(0.005); lambdas.push_back(0.008); for(auto n = nNeurons.begin(); n != nNeurons.end(); ++n) { for(auto eta = etas.begin(); eta != etas.end(); ++eta) { for(auto lambda = lambdas.begin(); lambda != lambdas.end(); ++lambda) { for(auto alpha = alphas.begin(); alpha != alphas.end(); ++alpha) { parameters.push_back(HyperParameters(loc, *n, 10000, *eta, *lambda, *alpha)); } } } } return parameters; } void NeuralNetworkSimulator::locRun(HyperParameters& parameters) { vector<Data> scaledTraining = trainingSet.getScaledDataSet(); vector<Data> originalTraining = trainingSet.dataSet; vector<Data> trainingDataSet = vector<Data>(scaledTraining.begin(), scaledTraining.begin() + scaledTraining.size() * 0.7); vector<Data> validationDataSet = vector<Data>(scaledTraining.begin() + scaledTraining.size() * 0.7, scaledTraining.end()); vector<Data> originalTrainingDataSet = vector<Data>(originalTraining.begin(), originalTraining.begin() + originalTraining.size() * 0.7); vector<Data> originalValidationDataSet = vector<Data>(originalTraining.begin() + originalTraining.size() * 0.7, originalTraining.end()); vector<pair<double, double>> trainingMSE; vector<pair<double, double>> validationMSE; vector<pair<double, double>> trainingMEE; vector<pair<double, double>> validationMEE; int maxEpochs = parameters.epochs; cout << "Loc Running..." << endl; // save the mse and mee errors for every epoch NeuralNetwork nn(parameters); nn.parameters.epochs = 1; trainingMSE.push_back(make_pair<int, double>(0, nn.computeError(trainingDataSet))); validationMSE.push_back(make_pair<int, double>(0, nn.computeError(validationDataSet))); trainingMEE.push_back(make_pair<int, double>(0, computeMee(trainingSet.rescaleOutputs(nn.computeOutput(trainingDataSet)), originalTrainingDataSet))); validationMEE.push_back(make_pair<int, double>(0, computeMee(trainingSet.rescaleOutputs(nn.computeOutput(validationDataSet)), originalValidationDataSet))); for(int i = 1; i <= maxEpochs; ++i) { nn.train(trainingDataSet); if(i % 10 == 0) { trainingMSE.push_back(make_pair<int, double>(i, nn.computeError(trainingDataSet))); validationMSE.push_back(make_pair<int, double>(i, nn.computeError(validationDataSet))); trainingMEE.push_back(make_pair<int, double>(i, computeMee(trainingSet.rescaleOutputs(nn.computeOutput(trainingDataSet)), originalTrainingDataSet))); validationMEE.push_back(make_pair<int, double>(i, computeMee(trainingSet.rescaleOutputs(nn.computeOutput(validationDataSet)), originalValidationDataSet))); if((validationMSE[validationMSE.size() - 1].second == 0) || (i % 100 == 0 && validationMSE[validationMSE.size() - 1].second > validationMSE[validationMSE.size() - 10].second)) break; } } parameters.epochs = maxEpochs; cout << "Final Training MSE: " << trainingMSE[trainingMSE.size() - 1].second << endl; cout << "Final Validation MSE: " << validationMSE[validationMSE.size() - 1].second << endl; cout << "Final Training MEE: " << trainingMEE[trainingMEE.size() - 1].second << endl; cout << "Final Validation MEE: " << validationMEE[validationMEE.size() - 1].second << endl; cout << "Writing Loc performance on file..."; // writing errors about training and test set fileManager.writeErrors(trainingMSE, "TrainingRunMSE"); fileManager.writeErrors(validationMSE, "ValidationRunMSE"); fileManager.writeErrors(trainingMEE, "TrainingRunMEE"); fileManager.writeErrors(validationMEE, "ValidationRunMEE"); cout << " end of the performance writing." << endl; cout << "end of the Loc Running." << endl; } void NeuralNetworkSimulator::locFoldRun(HyperParameters& parameters) { vector<Data> scaledTraining = trainingSet.getScaledDataSet(); vector<Data> originalTraining = trainingSet.dataSet; Folds scaledFolds = Folds(scaledTraining, 10); Folds originalFolds = Folds(originalTraining, 10); int n = 5; // (2, 5 or 7) vector<pair<double, double>> trainingMSE; vector<pair<double, double>> validationMSE; vector<pair<double, double>> trainingMEE; vector<pair<double, double>> validationMEE; int maxEpochs = parameters.epochs; cout << "Loc Fold Running..." << endl; // save the mse and mee errors for every epoch NeuralNetwork nn(parameters); nn.parameters.epochs = 1; trainingMSE.push_back(make_pair<int, double>(0, nn.computeError(scaledFolds.getTrainingSet(n)))); validationMSE.push_back(make_pair<int, double>(0, nn.computeError(scaledFolds.folds[n]))); trainingMEE.push_back(make_pair<int, double>(0, computeMee(trainingSet.rescaleOutputs(nn.computeOutput(scaledFolds.getTrainingSet(n))), originalFolds.getTrainingSet(n)))); validationMEE.push_back(make_pair<int, double>(0, computeMee(trainingSet.rescaleOutputs(nn.computeOutput(scaledFolds.folds[n])), originalFolds.folds[n]))); for(int i = 1; i <= maxEpochs; ++i) { nn.train(scaledFolds.getTrainingSet(n)); if(i % 10 == 0) { trainingMSE.push_back(make_pair<int, double>(i, nn.computeError(scaledFolds.getTrainingSet(n)))); validationMSE.push_back(make_pair<int, double>(i, nn.computeError(scaledFolds.folds[n]))); trainingMEE.push_back(make_pair<int, double>(i, computeMee(trainingSet.rescaleOutputs(nn.computeOutput(scaledFolds.getTrainingSet(n))), originalFolds.getTrainingSet(n)))); validationMEE.push_back(make_pair<int, double>(i, computeMee(trainingSet.rescaleOutputs(nn.computeOutput(scaledFolds.folds[n])), originalFolds.folds[n]))); } } parameters.epochs = maxEpochs; cout << "Final Training MSE: " << trainingMSE[trainingMSE.size() - 1].second << endl; cout << "Final Validation MSE: " << validationMSE[validationMSE.size() - 1].second << endl; cout << "Final Training MEE: " << trainingMEE[trainingMEE.size() - 1].second << endl; cout << "Final Validation MEE: " << validationMEE[validationMEE.size() - 1].second << endl; cout << "Writing Loc performance on file..."; stringstream ss; ss << parameters.nNeurons; // writing errors about training and test set fileManager.writeErrors(trainingMSE, "TrainingFoldRunMSE_" + ss.str()); fileManager.writeErrors(validationMSE, "ValidationFoldRunMSE_" + ss.str()); fileManager.writeErrors(trainingMEE, "TrainingFoldRunMEE_" + ss.str()); fileManager.writeErrors(validationMEE, "ValidationFoldRunMEE_" + ss.str()); cout << " end of the performance writing." << endl; cout << "end of the Loc Running." << endl; } void NeuralNetworkSimulator::generateLocPerformance(HyperParameters parameters) { vector<pair<double, double>> trainingMSE; vector<pair<double, double>> testMSE; vector<pair<double, double>> trainingMEE; vector<pair<double, double>> testMEE; double finalMSE = 0; double finalMEE = 0; int maxEpochs = parameters.epochs; vector<Data> trainingDataSet = trainingSet.getScaledDataSet(); vector<Data> testDataSet = trainingSet.scale(testSet.dataSet); cout << "Loc Testing..." << endl; // save the mse and mee errors for every epoch NeuralNetwork nn(parameters); nn.parameters.epochs = 1; trainingMSE.push_back(make_pair<int, double>(0, nn.computeError(trainingDataSet))); testMSE.push_back(make_pair<int, double>(0, nn.computeError(testDataSet))); trainingMEE.push_back(make_pair<int, double>(0, computeMee(trainingSet.rescaleOutputs(nn.computeOutput(trainingDataSet)), trainingSet.dataSet))); testMEE.push_back(make_pair<int, double>(0, computeMee(trainingSet.rescaleOutputs(nn.computeOutput(testDataSet)), testSet.dataSet))); for(int i = 1; i <= maxEpochs; ++i) { nn.train(trainingDataSet); if(i % 10 == 0) { trainingMSE.push_back(make_pair<int, double>(i, nn.computeError(trainingDataSet))); testMSE.push_back(make_pair<int, double>(i, nn.computeError(testDataSet))); trainingMEE.push_back(make_pair<int, double>(i, computeMee(trainingSet.rescaleOutputs(nn.computeOutput(trainingDataSet)), trainingSet.dataSet))); testMEE.push_back(make_pair<int, double>(i, computeMee(trainingSet.rescaleOutputs(nn.computeOutput(testDataSet)), testSet.dataSet))); } } nn.parameters.epochs = maxEpochs; cout << "Writing Loc performance on file..." << endl; // writing errors about training and test set fileManager.writeErrors(trainingMSE, "TrainingMSE"); fileManager.writeErrors(testMSE, "TestMSE"); fileManager.writeErrors(trainingMEE, "TrainingMEE"); fileManager.writeErrors(testMEE, "TestMEE"); cout << "...end of the performance writing." << endl; nn.train(trainingDataSet); cout << "Writing points on file..." << endl; vector<vector<double>> points = trainingSet.rescaleOutputs(nn.computeOutput(testDataSet)); fileManager.writePoints(points, testSet.dataSet); cout << "End of writing points on file." << endl; cout << "Computing the average errors on 10 runs..." << endl; for(int i = 0; i < 10; ++i) { nn.train(trainingDataSet); finalMSE += nn.computeError(testDataSet); finalMEE += computeMee(trainingSet.rescaleOutputs(nn.computeOutput(testDataSet)), testSet.dataSet); nn.reset(); } finalMSE /= 10; finalMEE /= 10; cout << "The final MSE on the test set is " << finalMSE << endl; cout << "The final MEE on the test set is " << finalMEE << endl; cout << "end of the Loc Testing." << endl; } double NeuralNetworkSimulator::computeMee(const vector<vector<double>>& outputs, const vector<Data>& dataSet) const { double mee = 0; for(int i = 0; i < static_cast<int>(outputs.size()); ++i) { double outputX = outputs[i][0]; double outputY = outputs[i][1]; double targetX = dataSet[i].targets[0]; double targetY = dataSet[i].targets[1]; mee += sqrt(pow(outputX - targetX, 2.0) + pow(outputY - targetY, 2.0)); } return (mee/outputs.size()); } void NeuralNetworkSimulator::generateCompetition(const HyperParameters& parameters) const { // generate the complete dataSet (training set merged with the test set) DataSet dataSet; dataSet.dataSet = trainingSet.dataSet; dataSet.dataSet.insert(dataSet.dataSet.end(), testSet.dataSet.begin(), testSet.dataSet.end()); vector<Data> competitionSet = dataSet.scale(fileManager.getCompetitionSet().dataSet); NeuralNetwork nn(parameters); nn.train(dataSet.getScaledDataSet()); cout << "Computing the blind test results..." << endl; vector<vector<double>> outputs = dataSet.rescaleOutputs(nn.computeOutput(competitionSet)); fileManager.writeCompetition(outputs); cout << "End of the blind test results computation." << endl; } /////////////////////////////////////////////////// Monk Functions ////////////////////////////////////////////////// vector<HyperParameters> NeuralNetworkSimulator::getMonkParameters() const { vector<HyperParameters> parameters; vector<int> nNeurons; nNeurons.push_back(3); nNeurons.push_back(4); nNeurons.push_back(5); vector<double> etas; etas.push_back(0.05); vector<double> alphas; alphas.push_back(0); alphas.push_back(0.2); alphas.push_back(0.5); vector<double> lambdas; lambdas.push_back(0); lambdas.push_back(0.02); lambdas.push_back(0.05); for(auto n = nNeurons.begin(); n != nNeurons.end(); ++n) { for(auto eta = etas.begin(); eta != etas.end(); ++eta) { for(auto lambda = lambdas.begin(); lambda != lambdas.end(); ++lambda) { for(auto alpha = alphas.begin(); alpha != alphas.end(); ++alpha) { parameters.push_back(HyperParameters(monk, *n, 1000, *eta, *lambda, *alpha)); } } } } return parameters; } void NeuralNetworkSimulator::generateMonkPerformance(const HyperParameters& parameters) const { vector<Data> trainingSet = NeuralNetworkSimulator::trainingSet.get1OfKDataSet(); vector<Data> testSet = NeuralNetworkSimulator::testSet.get1OfKDataSet(); vector<pair<double, double>> trainingMSE; vector<pair<double, double>> testMSE; int maxEpochs = parameters.epochs; cout << "Monk " << monkIndex << " Testing..." << endl; // save the lms errors for every epoch NeuralNetwork nn(parameters); nn.parameters.epochs = 1; trainingMSE.push_back(make_pair<int, double>(0, nn.computeError(trainingSet))); testMSE.push_back(make_pair<int, double>(0, nn.computeError(testSet))); for(int i = 1; i <= maxEpochs; ++i) { nn.train(trainingSet); if(i % 10 == 0) { trainingMSE.push_back(make_pair<int, double>(i, nn.computeError(trainingSet))); testMSE.push_back(make_pair<int, double>(i, nn.computeError(testSet))); } if(testMSE[testMSE.size() - 1].second == 0) break; } cout << "Writing Monk " << monkIndex << " performance on file..."; // writing errors about training and test set fileManager.writeErrors(trainingMSE, "Training"); fileManager.writeErrors(testMSE, "Test"); cout << " end of the performance writing." << endl; }
34ec378d1a38838ebce89ba29b23e24c66c23725
e780ac4efed690d0671c9e25df3e9732a32a14f5
/RaiderEngine/libs/PhysX-4.1/physx/source/pvd/src/PxPvdObjectModelInternalTypes.h
4a0d8a984c5553a4afb7ee9d996137746dd94905
[ "MIT" ]
permissive
rystills/RaiderEngine
fbe943143b48f4de540843440bd4fcd2a858606a
3fe2dcdad6041e839e1bad3632ef4b5e592a47fb
refs/heads/master
2022-06-16T20:35:52.785407
2022-06-11T00:51:40
2022-06-11T00:51:40
184,037,276
6
0
MIT
2022-05-07T06:00:35
2019-04-29T09:05:20
C++
UTF-8
C++
false
false
6,569
h
// // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2021 NVIDIA Corporation. All rights reserved. #ifndef PXPVDSDK_PXPVDOBJECTMODELINTERNALTYPES_H #define PXPVDSDK_PXPVDOBJECTMODELINTERNALTYPES_H #include "foundation/PxMemory.h" #include "PxPvdObjectModelBaseTypes.h" #include "PsArray.h" #include "PxPvdFoundation.h" namespace physx { namespace pvdsdk { struct PvdInternalType { enum Enum { None = 0, #define DECLARE_INTERNAL_PVD_TYPE(type) type, #include "PxPvdObjectModelInternalTypeDefs.h" Last #undef DECLARE_INTERNAL_PVD_TYPE }; }; PX_COMPILE_TIME_ASSERT(uint32_t(PvdInternalType::Last) <= uint32_t(PvdBaseType::InternalStop)); template <typename T> struct DataTypeToPvdTypeMap { bool compile_error; }; template <PvdInternalType::Enum> struct PvdTypeToDataTypeMap { bool compile_error; }; #define DECLARE_INTERNAL_PVD_TYPE(type) \ template <> \ struct DataTypeToPvdTypeMap<type> \ { \ enum Enum \ { \ BaseTypeEnum = PvdInternalType::type \ }; \ }; \ template <> \ struct PvdTypeToDataTypeMap<PvdInternalType::type> \ { \ typedef type TDataType; \ }; \ template <> \ struct PvdDataTypeToNamespacedNameMap<type> \ { \ NamespacedName Name; \ PvdDataTypeToNamespacedNameMap<type>() : Name("physx3_debugger_internal", #type) \ { \ } \ }; #include "PxPvdObjectModelInternalTypeDefs.h" #undef DECLARE_INTERNAL_PVD_TYPE template <typename TDataType, typename TAlloc> DataRef<TDataType> toDataRef(const shdfnd::Array<TDataType, TAlloc>& data) { return DataRef<TDataType>(data.begin(), data.end()); } static inline bool safeStrEq(const DataRef<String>& lhs, const DataRef<String>& rhs) { uint32_t count = lhs.size(); if(count != rhs.size()) return false; for(uint32_t idx = 0; idx < count; ++idx) if(!safeStrEq(lhs[idx], rhs[idx])) return false; return true; } static inline char* copyStr(const char* str) { str = nonNull(str); uint32_t len = static_cast<uint32_t>(strlen(str)); char* newData = reinterpret_cast<char*>(PX_ALLOC(len + 1, "string")); PxMemCopy(newData, str, len); newData[len] = 0; return newData; } // Used for predictable bit fields. template <typename TDataType, uint8_t TNumBits, uint8_t TOffset, typename TInputType> struct BitMaskSetter { // Create a mask that masks out the orginal value shift into place static TDataType createOffsetMask() { return createMask() << TOffset; } // Create a mask of TNumBits number of tis static TDataType createMask() { return static_cast<TDataType>((1 << TNumBits) - 1); } void setValue(TDataType& inCurrent, TInputType inData) { PX_ASSERT(inData < (1 << TNumBits)); // Create a mask to remove the current value. TDataType theMask = ~(createOffsetMask()); // Clear out current value. inCurrent = inCurrent & theMask; // Create the new value. TDataType theAddition = reinterpret_cast<TDataType>(inData << TOffset); // or it into the existing value. inCurrent = inCurrent | theAddition; } TInputType getValue(TDataType inCurrent) { return static_cast<TInputType>((inCurrent >> TOffset) & createMask()); } }; } } #endif // PXPVDSDK_PXPVDOBJECTMODELINTERNALTYPES_H
bf1b594d1cd231369496f516841fde432b52e55c
5d83739af703fb400857cecc69aadaf02e07f8d1
/Archive/184e668bc17ce1bffd9774efbd809f07/main.cpp
f8899a2705b92a21f94049ae9b13751f7b438034
[]
no_license
WhiZTiM/coliru
3a6c4c0bdac566d1aa1c21818118ba70479b0f40
2c72c048846c082f943e6c7f9fa8d94aee76979f
refs/heads/master
2021-01-01T05:10:33.812560
2015-08-24T19:09:22
2015-08-24T19:09:22
56,789,706
3
0
null
null
null
null
UTF-8
C++
false
false
642
cpp
#include <iostream> #define TRACE std::cout << __PRETTY_FUNCTION__ << std::endl; #define NAMESPACE(Name) namespace Name { struct Identify {}; } namespace Name NAMESPACE(Foo) { void process(Identify = {}) { TRACE } } NAMESPACE(Bar) { void process(Identify = {}) { TRACE } } void initialize() { std::cout << "general init" << std::endl; } void finalize () { std::cout << "general finit\n" << std::endl; } template<typename ID> void transaction(ID id) { initialize(); process(id); finalize(); } int main() { transaction(Foo::Identify()); transaction(Bar::Identify()); }
[ "francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df" ]
francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df
f8cacf3588904e2b67657caeba4493b7c7484bfb
53bea2549b85861f96efd5a74c211523b938ef54
/log-watch/LogReader.cpp
b5137365479ca8e0109b20f9a1529347413663d9
[ "Apache-2.0" ]
permissive
projectceladon/log_capture
f1004006e4310806a248cd86ce3c24e3a48d1fe2
4947af2dfbbabd3be2dc57d0a68e14259ade3023
refs/heads/master
2023-09-01T23:19:23.874863
2023-06-02T10:21:22
2023-06-02T10:21:22
199,820,325
3
9
Apache-2.0
2023-08-31T09:27:25
2019-07-31T09:06:25
C
UTF-8
C++
false
false
1,399
cpp
/* * Copyright (C) Intel 2015 * * 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 "LogReader.h" #include <asm-generic/errno-base.h> #include <stddef.h> #include <string> #include "KmsgReader.h" #include "UeventReader.h" #ifdef ANDROID_TARGET #include "LogdReader.h" #endif #include "LwLog.h" std::shared_ptr<LogItem> LogReader::get() { std::shared_ptr<LogItem> ret = std::make_shared<LogItem>(); if (!ret) LwLog::critical("Cannot allocate log item"); ret->setEof(true); return ret; } LogReader::~LogReader() { } LogReader* LogReader::getReader(std::string type, std::string args) { // TODO(tsc): maybe better if (type == "kmsg") return new KmsgReader(args == "nonblock"); if (type == "uevent") return new UeventReader(args == "nonblock"); #ifdef ANDROID_TARGET if (type == "logd") return new LogdReader(args); #endif return NULL; }
76b06aad67f2651e7af7edcbf6bf1104558e58a5
d6953acaef09a40c993af5810ce47ef818ad606b
/Application/src/main/jniLibs/Superpowered/AndroidIO/SuperpoweredAndroidAudioIO.h
84d0f06c87d67ed8d039cf24c4a2bf3df8826162
[]
no_license
sfink17/PhasedArrayApp
4ad50706da7d070e828b87d7768a769e6401e953
b9c10bab3b303144253415fa9b8474d70dbc24e7
refs/heads/master
2021-01-19T18:36:14.633595
2017-04-16T15:53:35
2017-04-16T15:53:35
88,367,535
0
0
null
null
null
null
UTF-8
C++
false
false
3,086
h
#ifndef Header_SuperpoweredAndroidAudioIO #define Header_SuperpoweredAndroidAudioIO struct SuperpoweredAndroidAudioIOInternals; /** @brief This is the prototype of an audio processing callback function. If the application requires both audio input and audio output, this callback is called once (there is no separate audio input and audio output callback). Audio input is available in audioIO, and the application should change it's contents for audio output. @param clientdata A custom pointer your callback receives. @param audioIO 16-bit stereo interleaved audio input and/or output. @param numberOfSamples The number of samples received and/or requested. @param samplerate The current sample rate in Hz. */ typedef bool (*audioProcessingCallback) (void *clientdata, short int *audioIO, int numberOfSamples, int samplerate); /** @brief Easy handling of OpenSL ES audio input and/or output. */ class SuperpoweredAndroidAudioIO { public: /** @brief Creates an audio I/O instance. Audio input and/or output immediately starts after calling this. @param samplerate The requested sample rate in Hz. @param buffersize The requested buffer size (number of samples). @param enableInput Enable audio input. @param enableOutput Enable audio output. @param callback The audio processing callback function to call periodically. @param clientdata A custom pointer the callback receives. @param inputStreamType OpenSL ES stream type, such as SL_ANDROID_RECORDING_PRESET_GENERIC. -1 means default. SLES/OpenSLES_AndroidConfiguration.h has them. @param outputStreamType OpenSL ES stream type, such as SL_ANDROID_STREAM_MEDIA or SL_ANDROID_STREAM_VOICE. -1 means default. SLES/OpenSLES_AndroidConfiguration.h has them. @param latencySamples How many samples to have in the internal fifo buffer minimum. Works only when both input and output are enabled. Might help if you have many dropouts. */ SuperpoweredAndroidAudioIO(int samplerate, int buffersize, bool enableInput, bool enableOutput, audioProcessingCallback callback, void *clientdata, int inputStreamType = -1, int outputStreamType = -1, int latencySamples = 0); ~SuperpoweredAndroidAudioIO(); /* @brief Call this in the main activity's onResume() method. Calling this is important if you'd like to save battery. When there is no audio playing and the app goes to the background, it will automatically stop audio input and/or output. */ void onForeground(); /* @brief Call this in the main activity's onPause() method. Calling this is important if you'd like to save battery. When there is no audio playing and the app goes to the background, it will automatically stop audio input and/or output. */ void onBackground(); /* @brief Starts audio input and/or output. */ void start(); /* @brief Stops audio input and/or output. */ void stop(); void callback(); private: SuperpoweredAndroidAudioIOInternals *internals; SuperpoweredAndroidAudioIO(const SuperpoweredAndroidAudioIO&); SuperpoweredAndroidAudioIO& operator=(const SuperpoweredAndroidAudioIO&); }; #endif
a28a7d3b4ca33a8fdca24c6b97ea6b898ba57bbd
2dd3fd9a14adf671c7d4cc523af299c48005a076
/src/SqlDB.h
ee69a268bbbba8e27ce1d134095637de749ff6cb
[]
no_license
1slammer/StepHelper
d61d25349943e2195e57d76f5cf92ccc3a87d9fc
52b51f6129b5d542dab628ca3bcc361bc35fce37
refs/heads/master
2020-03-19T18:54:50.627593
2018-06-11T16:06:17
2018-06-11T16:06:17
136,830,958
0
0
null
null
null
null
UTF-8
C++
false
false
448
h
#include <stdio.h> #include <sqlite3.h> #include <string> #include <iostream> #include <vector> using namespace std; using Record = std::vector<std::string>; using Records = std::vector<Record>; class SqlDB { public: void OpenDB(); void CloseDB(); void CreateFourthStepTableIfNotExists(); Records RetrieveFourthStepInfo(); void sql_stmt(const char* stmt); Records select_stmt(const char* stmt); private: sqlite3 *db; };
e42add9ae8fb0448df023699c6cda36c41036ad8
29c1b74b8feb933a544147632785ec88e9bbecec
/2018-11-13/Arranging-Coins.cc
e9fbf052b62fa51cb969afb68c38d63e8145a9d8
[]
no_license
ckcd/leetcode
b901b07374682891bfbfc27acd2dfacecfbfd590
4697ed77dd6fd7a97086d98d15ce95d213d6748f
refs/heads/master
2020-03-31T21:25:49.900235
2019-03-20T10:19:17
2019-03-20T10:19:17
152,580,241
0
0
null
null
null
null
UTF-8
C++
false
false
1,020
cc
/* You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins. Given n, find the total number of full staircase rows that can be formed. n is a non-negative integer and fits within the range of a 32-bit signed integer. Example 1: n = 5 The coins can form the following rows: ¤ ¤ ¤ ¤ ¤ Because the 3rd row is incomplete, we return 2. Example 2: n = 8 The coins can form the following rows: ¤ ¤ ¤ ¤ ¤ ¤ ¤ ¤ Because the 4th row is incomplete, we return 3. */ #include <iostream> #include <vector> #include <iterator> #include <math.h> using namespace std; /* class Solution { public: int arrangeCoins(int n) { int i = 1; while(n - i >= 0) { n = n - i; i++; } return i - 1; } }; */ class Solution { public: int arrangeCoins(int n) { return int((sqrt(8.0 * n + 1)-1)/2); } }; int main() { Solution s; cout << s.arrangeCoins(8) << endl; return 0; }
ec4185f9a016fc22f435e5266bf8cdb0b5b35d55
ad1fbd8b33039f2dc9056dd070bd049300b9fbb0
/src/t1_package/src/simple_node_2.cpp
3fa37b903ec1666b7c3d1139563a93287a8bf5be
[]
no_license
ShaziaSulemane/trsa
0f037f78dfefbbb917f9114d42f47ce4a2e6fe40
90ce090ddeafc0dbb761756d75aa4cfd77ce025b
refs/heads/master
2022-03-04T12:45:22.414097
2019-10-02T11:20:35
2019-10-02T11:20:35
212,317,816
0
0
null
null
null
null
UTF-8
C++
false
false
243
cpp
#include <ros/ros.h> int main( int argc, char** argv ) { ros::init (argc, argv, "trsa_node_2"); ros::NodeHandle node; ros::Rate rate(10); while ( ros::ok() ) { ROS_INFO( "Yet Another Node" ); rate.sleep(); } return 0; }
0e6cda41019144a3ed8b4473c97169f749912de8
ac5442020a5247231ede042926530e500b16b501
/compilers/hybrid-backend/src/runtime/structure.cc
45ea1e207d296c7c1befbfea02542ffe283c146c
[]
no_license
MuhammadNurYanhaona/ITandPCubeS
e8a42d8d50f56eb76954bdf2cb786377cb5a8ee5
8928c56587db8293f0ec02c7cb030cfb540ce2b4
refs/heads/master
2021-01-24T06:22:37.089569
2017-04-22T15:57:04
2017-04-22T15:57:04
15,794,818
1
1
null
null
null
null
UTF-8
C++
false
false
3,974
cc
#include "structure.h" #include "../utils/utility.h" #include <iostream> #include <fstream> #include <stdlib.h> #include <algorithm> //------------------------------------------- Dimension -------------------------------------------------/ int Dimension::getLength() { return abs(range.max - range.min) + 1; } void Dimension::setLength(int length) { range.min = 0; range.max = length - 1; this->length = length; } void Dimension::setLength() { this->length = getLength(); } bool Dimension::isIncreasing() { return (range.min <= range.max); } Range Dimension::getPositiveRange() { if (isIncreasing()) return range; Range positiveRange; positiveRange.min = range.max; positiveRange.max = range.min; return positiveRange; } Range Dimension::adjustPositiveSubRange(Range positiveSubRange) { if (isIncreasing()) return positiveSubRange; Range subRange; subRange.min = range.min - positiveSubRange.min; subRange.max = range.min - positiveSubRange.max; return subRange; } Dimension Dimension::getNormalizedDimension() { int length = getLength(); Range normalRange; normalRange.min = 0; normalRange.max = length - 1; Dimension normalDimension; normalDimension.range = normalRange; normalDimension.length = length; return normalDimension; } bool Dimension::isEqual(Dimension other) { return (this->range.min == other.range.min) && (this->range.max == other.range.max); } void Dimension::print(std::ostream &stream) { stream << range.min << "--" << range.max; } //----------------------------------------- Part Dimension ---------------------------------------------/ void PartDimension::print(std::ofstream &stream, int indentLevel) { for (int i = 0; i < indentLevel; i++) stream << "\t"; stream << "count: " << count << " "; stream << "index: " << index << " "; stream << "storage: "; storage.print(stream); stream << " partition: "; partition.print(stream); stream << std::endl; } bool PartDimension::isIncluded(int index) { if (partition.range.min > partition.range.max) { return index >= partition.range.max && index <= partition.range.min; } else { return index >= partition.range.min && index <= partition.range.max; } } int PartDimension::adjustIndex(int index) { if (partition.range.min > partition.range.max) return partition.range.min - index; else return index + partition.range.min; } int PartDimension::safeNormalizeIndex(int index, bool matchToMin) { int normalIndex = index - partition.range.min; int length = partition.getLength(); if (normalIndex >= 0 && normalIndex < length) return normalIndex; return (matchToMin) ? 0 : length - 1; } PartDimension PartDimension::getSubrange(int begin, int end) { PartDimension subDimension = PartDimension(); subDimension.storage = this->storage; subDimension.partition.range.min = begin; subDimension.partition.range.max = end; subDimension.partition.setLength(); return subDimension; } int PartDimension::getDepth() { if (parent == NULL) return 1; else return parent->getDepth() + 1; } //--------------------------------------------- PPU ID --------------------------------------------------/ void PPU_Ids::print(std::ofstream &stream) { stream << "\tLPS Name: " << lpsName << std::endl; stream << "\t\tGroup Id: " << groupId << std::endl; stream << "\t\tGroup Size: " << groupSize << std::endl; stream << "\t\tPPU Count: " << ppuCount << std::endl; if (id != INVALID_ID) { stream << "\t\tId: " << id << std::endl; } } //------------------------------------------- Thread IDs ------------------------------------------------/ void ThreadIds::print(std::ofstream &stream) { stream << "Thread No: " << threadNo << std::endl; for (int i = 0; i < lpsCount; i++) { ppuIds[i].print(stream); } stream.flush(); } int *ThreadIds::getAllPpuCounts() { int *counts = new int[lpsCount]; Assert(counts != NULL && lpsCount > 0); for (int i = 0; i < lpsCount; i++) counts[i] = ppuIds[i].ppuCount; return counts; }
69550e80c1ebb2a57fbfe9026892bda5b6433b65
defb9464cdb07f08d05af5a9c33fc872e669eaa6
/usb_test/usb_test/usb_test.cpp
38ec290c49a9255094c5e5b7ae8ce10edf078c36
[]
no_license
mojianc/USBHIDTest
4b3b669e50c0e9743b9b13e7208ce404dfc0fbac
51bc95171315359c3a433e4f0158d26400d0ec67
refs/heads/master
2020-06-01T16:09:24.052692
2019-06-08T04:35:20
2019-06-08T04:35:20
190,845,266
0
0
null
null
null
null
GB18030
C++
false
false
3,746
cpp
// hook_test.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <Dbt.h> #include <iostream> #include "usb_hid.h" using namespace std; const _TCHAR CLASS_NAME[] = _T("usb_test msg window"); HWND m_hwnd; HHOOK hook; usb_hid usb; ///////////////////////////////////////////////////////////////////// //usb 拔插相关代码 bool CreateMessageOnlyWindow() { m_hwnd = CreateWindowEx(0, CLASS_NAME, _T(""), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, // Parent window NULL, // Menu GetModuleHandle(NULL), // Instance handle NULL // Additional application data ); return m_hwnd != NULL; } void UsbDeviceChange(WPARAM wParam, LPARAM lParam) { if (DBT_DEVICEREMOVECOMPLETE == wParam)//拔 { PDEV_BROADCAST_HDR pHdr = (PDEV_BROADCAST_HDR)lParam; if (DBT_DEVTYP_DEVICEINTERFACE == pHdr->dbch_devicetype) { PDEV_BROADCAST_DEVICEINTERFACE pDevInf = (PDEV_BROADCAST_DEVICEINTERFACE)pHdr; wstring dbccName = pDevInf->dbcc_name; wcout << L"usb remove" << dbccName.c_str() << endl; if (dbccName.length() > 0) { //这里判断pid vid是否对应的设备 wstring::size_type id1 = dbccName.find(L"VID_040B"); wstring::size_type id2 = dbccName.find(L"PID_2803"); if (id1 != string::npos&&id2 != string::npos) { usb.stop(); } } } } else if (DBT_DEVICEARRIVAL == wParam)//插 { PDEV_BROADCAST_HDR pHdr = (PDEV_BROADCAST_HDR)lParam; if (DBT_DEVTYP_DEVICEINTERFACE == pHdr->dbch_devicetype) { PDEV_BROADCAST_DEVICEINTERFACE pDevInf = (PDEV_BROADCAST_DEVICEINTERFACE)pHdr; wstring dbccName = pDevInf->dbcc_name; wcout << L"usb arrival" << dbccName.c_str() << endl; if (dbccName.length() > 0) { //这里判断pid vid是否对应的设备 wstring::size_type id1 = dbccName.find(L"VID_040B"); wstring::size_type id2 = dbccName.find(L"PID_2803"); if (id1 != string::npos&&id2 != string::npos) { usb.start(); } } } } } LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_PAINT: break; case WM_SIZE: break; case WM_DEVICECHANGE: UsbDeviceChange(wParam, lParam); break; } return DefWindowProc(hWnd, message, wParam, lParam); } ATOM MyRegisterClass() { WNDCLASS wc = { 0 }; wc.lpfnWndProc = WndProc; wc.hInstance = GetModuleHandle(NULL); wc.lpszClassName = CLASS_NAME; return RegisterClass(&wc); } bool RegisterDevice() { const GUID GUID_DEVINTERFACE_LIST[] = { { 0xA5DCBF10, 0x6530, 0x11D2, { 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED } }, { 0x53f56307, 0xb6bf, 0x11d0, { 0x94, 0xf2, 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b } }, { 0x4D1E55B2, 0xF16F, 0x11CF, { 0x88, 0xCB, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30 } }, /* HID */ { 0xad498944, 0x762f, 0x11d0, { 0x8d, 0xcb, 0x00, 0xc0, 0x4f, 0xc3, 0x35, 0x8c } } }; DEV_BROADCAST_DEVICEINTERFACE NotificationFilter; ZeroMemory(&NotificationFilter, sizeof(NotificationFilter)); NotificationFilter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE); NotificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; NotificationFilter.dbcc_classguid = GUID_DEVINTERFACE_LIST[0]; HDEVNOTIFY hDevNotify = RegisterDeviceNotification(m_hwnd, &NotificationFilter, DEVICE_NOTIFY_WINDOW_HANDLE); if (!hDevNotify) { return false; } return true; } ///////////////////////////////////////////////// int _tmain(int argc, _TCHAR* argv[]) { MyRegisterClass(); CreateMessageOnlyWindow(); RegisterDevice(); usb.start(); usb.usb_write_data_test(); MSG msg; while (int ret = GetMessage(&msg, m_hwnd, 0, 0)) { if (ret != -1) { TranslateMessage(&msg); DispatchMessage(&msg); } } return 0; }
254b772c006cb73310b049fb9853dee8ff692458
b5d24389b69025fe0dd08cbe1b1b394f39c2cb81
/src/services/ObjLoader.cpp
9521daf4af7b3ad431424fb7eb1fb6ed0daf750f
[]
no_license
seanchas116/Lattice
8d34ded9bb69d251f33f9e87d51bfb025db9f08e
4595cd6db7644955bc23ec176cea21dd1029eaa2
refs/heads/master
2020-04-10T12:09:56.093183
2019-12-14T16:26:54
2019-12-14T16:26:54
161,013,502
2
0
null
null
null
null
UTF-8
C++
false
false
4,239
cpp
#include "ObjLoader.hpp" #include "../document/Document.hpp" #include "../document/ImageManager.hpp" #include "../document/MeshObject.hpp" #include "../support/Debug.hpp" #include "../support/Hash.hpp" #include <meshlib/Mesh.hpp> #include <tiny_obj_loader.h> using namespace glm; namespace Lattice { namespace Services { std::vector<SP<Document::MeshObject>> ObjLoader::load(const SP<Document::Document> &document, const boost::filesystem::path &filePath) { tinyobj::attrib_t attrib; std::vector<tinyobj::shape_t> objShapes; std::vector<tinyobj::material_t> objMaterials; auto parentPath = filePath.parent_path(); std::string warn; std::string err; bool ret = tinyobj::LoadObj(&attrib, &objShapes, &objMaterials, &warn, &err, filePath.string().data(), parentPath.string().data(), false); if (!warn.empty()) { qWarning() << warn.c_str(); } if (!err.empty()) { qWarning() << err.c_str(); } if (!ret) { return {}; } std::vector<SP<Document::MeshObject>> objects; auto loadImage = [&](const std::string &name) -> Opt<SP<Document::Image>> { if (name.empty()) { return {}; } auto path = parentPath / name; return document->imageManager()->openImage(path.string()); }; for (auto &objShape : objShapes) { auto object = makeShared<Document::MeshObject>(); object->setName(objShape.name); meshlib::Mesh mesh; // TODO: use index_t as key std::unordered_map<std::pair<int, int>, meshlib::UVPointHandle> uvPointForIndices; std::vector<Document::Material> materials; // Add materials for (auto &objMaterial : objMaterials) { vec3 diffuse(objMaterial.diffuse[0], objMaterial.diffuse[1], objMaterial.diffuse[2]); auto diffuseImage = loadImage(objMaterial.diffuse_texname); Document::Material material; material.setBaseColor(diffuse); material.setBaseColorImage(diffuseImage); // TODO: set more values materials.push_back(material); } object->setMaterials(materials); for (size_t v = 0; v < attrib.vertices.size() / 3; ++v) { tinyobj::real_t vx = attrib.vertices[3 * v + 0]; tinyobj::real_t vy = attrib.vertices[3 * v + 1]; tinyobj::real_t vz = attrib.vertices[3 * v + 2]; mesh.addVertex(glm::vec3(vx, vy, vz)); } // Loop over faces(polygon) size_t index_offset = 0; for (size_t f = 0; f < objShape.mesh.num_face_vertices.size(); f++) { size_t fv = objShape.mesh.num_face_vertices[f]; std::vector<meshlib::UVPointHandle> uvPoints; // Loop over vertices in the face. for (size_t v = 0; v < fv; v++) { // access to vertex tinyobj::index_t idx = objShape.mesh.indices[index_offset + v]; auto vertex = meshlib::VertexHandle(idx.vertex_index); auto uvPoint = [&] { auto uvPointIt = uvPointForIndices.find({idx.vertex_index, idx.texcoord_index}); if (uvPointIt != uvPointForIndices.end()) { return uvPointIt->second; } tinyobj::real_t tx = attrib.texcoords[2 * idx.texcoord_index + 0]; tinyobj::real_t ty = attrib.texcoords[2 * idx.texcoord_index + 1]; glm::vec2 uv(tx, ty); auto uvPoint = mesh.addUVPoint(vertex, uv); uvPointForIndices[{idx.vertex_index, idx.texcoord_index}] = uvPoint; return uvPoint; }(); uvPoints.push_back(uvPoint); } index_offset += fv; auto materialID = objShape.mesh.material_ids[f]; if (materialID >= 0) { mesh.addFace(uvPoints, meshlib::MaterialHandle(materialID)); } else { // TODO: add default material } } object->setMesh(std::move(mesh)); objects.push_back(object); } return objects; } } // namespace Services } // namespace Lattice
4248b2728a87d289506d72f187e8efc44a7542eb
3195ea3c507d958eb598c4054f2f382eb6b49ec3
/Object Oriented/jdo3643_HW5/jdo3643_main.cpp
259f239182e6ceeeaadfb68ec7be76f1a401eef4
[]
no_license
jdolds09/Jerry-Olds-Projects
3c75d5d4240cd3cccbbfdcaab238ff9735551211
eec161042861ef80021edba181c931dbe08ae555
refs/heads/master
2023-01-03T11:25:18.900613
2021-01-19T01:46:08
2021-01-19T01:46:08
243,045,245
0
0
null
null
null
null
UTF-8
C++
false
false
233
cpp
#include "jdo3643_Controller.h" int main() { // Objects Transaction_List list{}; View view{list}; Controller controller{ list, view }; // Load save file list.load(); // Call cli controller.cli(); // End of program return 0; }
d602864775b71e432e51e5f016d04526b514ad7d
3531dd9f52b11ae26d0c5f624a815538bf4c1964
/examples/ITVDN_CPP/CPP_Starter/002_Storedlnformation/DefaultTypes/DefaultTypes.cpp
dc6cacc3d4c9e1e28ff0e99e87cb7a148ae1a8c8
[]
no_license
syurskyi/CPP_Topics
b9a481fa828fb763fe4e21388cd04b4e90c2cd96
c9851ab9e254e2fc01ab1bb819ca1d642f623fae
refs/heads/master
2022-12-11T16:12:49.219989
2020-09-01T22:36:08
2020-09-01T22:36:08
277,678,709
0
0
null
null
null
null
UTF-8
C++
false
false
225
cpp
// DefaultTypes.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> using namespace std; int main() { int a = 5; char b = 'B'; double c; cout << b; return 0; }
f3488674a0fbd06f76b275624f9309c544389ac4
0181482e75a03cdcab4f8ea925993a83be18e3d7
/luxrays/src/luxrays/accelerators/embreeaccel.cpp
c9e1031a7db525404471c3d51db6ae3c53ebcdc5
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
yangzhengxing/luxrender
f70db784370454193803df27dc5b4e54c0f78c60
fc78235e99e4dfd7df9e8ca07c035dd94ee65e53
refs/heads/master
2021-01-20T19:18:38.180639
2016-06-05T06:35:44
2016-06-05T06:35:44
60,435,194
3
4
null
null
null
null
UTF-8
C++
false
false
8,583
cpp
/*************************************************************************** * Copyright 1998-2015 by authors (see AUTHORS.txt) * * * * This file is part of LuxRender. * * * * 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 <string> #include <limits> #if defined (_MSC_VER) || defined (__INTEL_COMPILER) #include <intrin.h> #endif #include <boost/foreach.hpp> #include "luxrays/core/context.h" #include "luxrays/accelerators/embreeaccel.h" namespace luxrays { void Embree_error_handler(const RTCError code, const char *str) { std::string errType; switch (code) { case RTC_UNKNOWN_ERROR: errType = "RTC_UNKNOWN_ERROR"; break; case RTC_INVALID_ARGUMENT: errType = "RTC_INVALID_ARGUMENT"; break; case RTC_INVALID_OPERATION: errType = "RTC_INVALID_OPERATION"; break; case RTC_OUT_OF_MEMORY: errType = "RTC_OUT_OF_MEMORY"; break; case RTC_UNSUPPORTED_CPU: errType = "RTC_UNSUPPORTED_CPU"; break; default: errType = "invalid error code"; break; } std::cout << "Embree error: " << str << "\n"; abort(); } boost::mutex EmbreeAccel::initMutex; u_int EmbreeAccel::initCount = 0; EmbreeAccel::EmbreeAccel(const Context *context) : ctx(context), uniqueRTCSceneByMesh(MeshPtrCompare) { embreeScene = NULL; // Initialize Embree boost::unique_lock<boost::mutex> lock(initMutex); if (initCount == 0) { rtcInit(NULL); rtcSetErrorFunction(Embree_error_handler); } ++initCount; } EmbreeAccel::~EmbreeAccel() { if (embreeScene) { rtcDeleteScene(embreeScene); // I have to free all Embree scene used for instances std::pair<const Mesh *, RTCScene> elem; BOOST_FOREACH(elem, uniqueRTCSceneByMesh) rtcDeleteScene(elem.second); } // Shutdown Embree if I was the last one boost::unique_lock<boost::mutex> lock(initMutex); if (initCount == 1) rtcExit(); --initCount; } u_int EmbreeAccel::ExportTriangleMesh(const RTCScene embreeScene, const Mesh *mesh) const { const u_int geomID = rtcNewTriangleMesh(embreeScene, RTC_GEOMETRY_STATIC, mesh->GetTotalTriangleCount(), mesh->GetTotalVertexCount(), 1); // Share with Embree the mesh vertices Point *meshVerts = mesh->GetVertices(); rtcSetBuffer(embreeScene, geomID, RTC_VERTEX_BUFFER, meshVerts, 0, 3 * sizeof(float)); // Share with Embree the mesh triangles Triangle *meshTris = mesh->GetTriangles(); rtcSetBuffer(embreeScene, geomID, RTC_INDEX_BUFFER, meshTris, 0, 3 * sizeof(int)); return geomID; } u_int EmbreeAccel::ExportMotionTriangleMesh(const RTCScene embreeScene, const MotionTriangleMesh *mtm) const { const u_int geomID = rtcNewTriangleMesh(embreeScene, RTC_GEOMETRY_STATIC, mtm->GetTotalTriangleCount(), mtm->GetTotalVertexCount(), 2); const MotionSystem &ms = mtm->GetMotionSystem(); // Copy the mesh start position vertices float *vertices0 = (float *)rtcMapBuffer(embreeScene, geomID, RTC_VERTEX_BUFFER0); for (u_int i = 0; i < mtm->GetTotalVertexCount(); ++i) { const Point v = mtm->GetVertex(ms.StartTime(), i); *vertices0++ = v.x; *vertices0++ = v.y; *vertices0++ = v.z; ++vertices0; } rtcUnmapBuffer(embreeScene, geomID, RTC_VERTEX_BUFFER0); // Copy the mesh end position vertices float *vertices1 = (float *)rtcMapBuffer(embreeScene, geomID, RTC_VERTEX_BUFFER1); for (u_int i = 0; i < mtm->GetTotalVertexCount(); ++i) { const Point v = mtm->GetVertex(ms.EndTime(), i); *vertices1++ = v.x; *vertices1++ = v.y; *vertices1++ = v.z; ++vertices1; } rtcUnmapBuffer(embreeScene, geomID, RTC_VERTEX_BUFFER1); // Share the mesh triangles Triangle *meshTris = mtm->GetTriangles(); rtcSetBuffer(embreeScene, geomID, RTC_INDEX_BUFFER, meshTris, 0, 3 * sizeof(int)); return geomID; } void EmbreeAccel::Init(const std::deque<const Mesh *> &meshes, const u_longlong totalVertexCount, const u_longlong totalTriangleCount) { const double t0 = WallClockTime(); //-------------------------------------------------------------------------- // Extract the meshes min. and max. time. To normalize between 0.f and 1.f. //-------------------------------------------------------------------------- minTime = std::numeric_limits<float>::max(); maxTime = std::numeric_limits<float>::min(); BOOST_FOREACH(const Mesh *mesh, meshes) { const MotionTriangleMesh *mtm = dynamic_cast<const MotionTriangleMesh *>(mesh); if (mtm) { minTime = Min(minTime, mtm->GetMotionSystem().StartTime()); maxTime = Min(maxTime, mtm->GetMotionSystem().EndTime()); } } if ((minTime == std::numeric_limits<float>::max()) || (maxTime == std::numeric_limits<float>::min())) { minTime = 0.f; maxTime = 1.f; timeScale = 1.f; } else timeScale = 1.f / (maxTime - minTime); //-------------------------------------------------------------------------- // Convert the meshes to an Embree Scene //-------------------------------------------------------------------------- embreeScene = rtcNewScene(RTC_SCENE_STATIC, RTC_INTERSECT1); BOOST_FOREACH(const Mesh *mesh, meshes) { switch (mesh->GetType()) { case TYPE_TRIANGLE: case TYPE_EXT_TRIANGLE: ExportTriangleMesh(embreeScene, mesh); break; case TYPE_TRIANGLE_INSTANCE: case TYPE_EXT_TRIANGLE_INSTANCE: { const InstanceTriangleMesh *itm = dynamic_cast<const InstanceTriangleMesh *>(mesh); // Check if a RTCScene has already been created std::map<const Mesh *, RTCScene, bool (*)(const Mesh *, const Mesh *)>::iterator it = uniqueRTCSceneByMesh.find(itm->GetTriangleMesh()); RTCScene instScene; if (it == uniqueRTCSceneByMesh.end()) { TriangleMesh *instancedMesh = itm->GetTriangleMesh(); // Create a new RTCScene instScene = rtcNewScene(RTC_SCENE_STATIC, RTC_INTERSECT1); ExportTriangleMesh(instScene, instancedMesh); rtcCommit(instScene); uniqueRTCSceneByMesh[instancedMesh] = instScene; } else instScene = it->second; const u_int instID = rtcNewInstance(embreeScene, instScene); rtcSetTransform(embreeScene, instID, RTC_MATRIX_ROW_MAJOR, &(itm->GetTransformation().m.m[0][0])); break; } case TYPE_TRIANGLE_MOTION: case TYPE_EXT_TRIANGLE_MOTION: { const MotionTriangleMesh *mtm = dynamic_cast<const MotionTriangleMesh *>(mesh); ExportMotionTriangleMesh(embreeScene, mtm); break; } default: throw std::runtime_error("Unknown Mesh type in EmbreeAccel::Init(): " + ToString(mesh->GetType())); } } rtcCommit(embreeScene); LR_LOG(ctx, "EmbreeAccel build time: " << int((WallClockTime() - t0) * 1000) << "ms"); } bool EmbreeAccel::MeshPtrCompare(const Mesh *p0, const Mesh *p1) { return p0 < p1; } bool EmbreeAccel::Intersect(const Ray *ray, RayHit *hit) const { RTCRay embreeRay; embreeRay.org[0] = ray->o.x; embreeRay.org[1] = ray->o.y; embreeRay.org[2] = ray->o.z; embreeRay.dir[0] = ray->d.x; embreeRay.dir[1] = ray->d.y; embreeRay.dir[2] = ray->d.z; embreeRay.tnear = ray->mint; embreeRay.tfar = ray->maxt; embreeRay.geomID = RTC_INVALID_GEOMETRY_ID; embreeRay.primID = RTC_INVALID_GEOMETRY_ID; embreeRay.instID = RTC_INVALID_GEOMETRY_ID; embreeRay.mask = 0xFFFFFFFF; embreeRay.time = (ray->time - minTime) * timeScale; rtcIntersect(embreeScene, embreeRay); if (embreeRay.geomID != RTC_INVALID_GEOMETRY_ID) { hit->meshIndex = (embreeRay.instID == RTC_INVALID_GEOMETRY_ID) ? embreeRay.geomID : embreeRay.instID; hit->triangleIndex = embreeRay.primID; hit->t = embreeRay.tfar; hit->b1 = embreeRay.u; hit->b2 = embreeRay.v; return true; } else return false; } }
86115db959cced1d24d470baf2a23178c1492ecb
7247dbe86fba860f1716abb189a32c7cd46d9f33
/BOJ/2000/2738.cpp
93897349a3b5ed4284cc045d8f125b7e7aab3923
[]
no_license
SE93WO/Algorithm
a5bdc76378e959161085428b3442d1b2df73655f
a7b256de35fe15dbe59a43af344c930792b478c3
refs/heads/master
2020-03-19T17:42:33.695927
2019-12-18T09:39:43
2019-12-18T09:39:43
136,773,550
0
0
null
null
null
null
UTF-8
C++
false
false
434
cpp
#include <iostream> using namespace std; int main() { int N, M; int matrix[100][100]; cin >> N >> M; for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) cin >> matrix[i][j]; for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) { int temp; cin >> temp; matrix[i][j] += temp; } for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { cout << matrix[i][j] << " "; } cout << "\n"; } }
b847e6d2ac47e1afff7b9b989982ea0589ebef25
6eadf2833aa4290dda7fb93509b9c6c8822f718c
/Robot2014/Commands/AutonomousTest.h
ffb2d59d957ec244ebd13181b2e4a087c9718dd7
[]
no_license
AGHSEagleRobotics/frc1388-2014
d1d78b16361ae603efd249a7d3fcc18d0a5295ce
95a721a94d655a6210cdfbb21fdc71582c0c5a1c
refs/heads/master
2021-03-12T22:54:51.514002
2014-03-25T04:16:08
2014-03-25T04:16:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
725
h
// RobotBuilder Version: 0.0.2 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // C++ from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in th future. #ifndef AUTONOMOUSTEST_H #define AUTONOMOUSTEST_H #include "Commands/CommandGroup.h" /** * * * @author ExampleAuthor */ class AutonomousTest: public CommandGroup { public: AutonomousTest(); }; #endif
93c70ecb4de042d9699ced72b96fe40ca4aa08e8
7bae6e823c2460c6107c9ae8e1b8145f7fa3cdc8
/alg/gdalpansharpen.cpp
a531fca401d45b29e6979fccdaa4209d096c0dc7
[ "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-warranty-disclaimer", "MIT", "SunPro", "LicenseRef-scancode-info-zip-2005-02", "BSD-3-Clause" ]
permissive
gajgeospatial/gdal-3.1.0
ed0cfeedd93f4fcd087dc890ba83879bb0b40820
ac735c543bbdb0bfa6c817920a852e38faf84645
refs/heads/master
2022-11-15T19:51:12.169674
2020-07-11T21:06:32
2020-07-11T21:06:32
261,614,185
0
1
null
null
null
null
UTF-8
C++
false
false
69,425
cpp
/****************************************************************************** * * Project: GDAL Pansharpening module * Purpose: Implementation of pansharpening. * Author: Even Rouault <even.rouault at spatialys.com> * ****************************************************************************** * Copyright (c) 2015, Even Rouault <even.rouault at spatialys.com> * Copyright (c) 2015, Airbus DS Geo SA (weighted Brovey algorithm) * * 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 "cpl_port.h" #include "gdalpansharpen.h" #include <algorithm> #include <cstddef> #include <cstdio> #include <cstdlib> #include <cstring> #include <limits> #include <new> #include "cpl_conv.h" #include "cpl_error.h" #include "cpl_multiproc.h" #include "cpl_vsi.h" #include "../frmts/mem/memdataset.h" #include "../frmts/vrt/vrtdataset.h" #include "gdal_priv.h" #include "gdal_priv_templates.hpp" // #include "gdalsse_priv.h" // Limit types to practical use cases. #define LIMIT_TYPES 1 CPL_CVSID("$Id: gdalpansharpen.cpp 685b96644b37dcd526ccb68cbb763f67a4108800 2020-03-20 17:27:19 +0100 Even Rouault $") /************************************************************************/ /* GDALCreatePansharpenOptions() */ /************************************************************************/ /** Create pansharpening options. * * @return a newly allocated pansharpening option structure that must be freed * with GDALDestroyPansharpenOptions(). * * @since GDAL 2.1 */ GDALPansharpenOptions * GDALCreatePansharpenOptions() { GDALPansharpenOptions* psOptions = static_cast<GDALPansharpenOptions *>( CPLCalloc(1, sizeof(GDALPansharpenOptions))); psOptions->ePansharpenAlg = GDAL_PSH_WEIGHTED_BROVEY; psOptions->eResampleAlg = GRIORA_Cubic; return psOptions; } /************************************************************************/ /* GDALDestroyPansharpenOptions() */ /************************************************************************/ /** Destroy pansharpening options. * * @param psOptions a pansharpening option structure allocated with * GDALCreatePansharpenOptions() * * @since GDAL 2.1 */ void GDALDestroyPansharpenOptions( GDALPansharpenOptions* psOptions ) { if( psOptions == nullptr ) return; CPLFree(psOptions->padfWeights); CPLFree(psOptions->pahInputSpectralBands); CPLFree(psOptions->panOutPansharpenedBands); CPLFree(psOptions); } /************************************************************************/ /* GDALClonePansharpenOptions() */ /************************************************************************/ /** Clone pansharpening options. * * @param psOptions a pansharpening option structure allocated with * GDALCreatePansharpenOptions() * @return a newly allocated pansharpening option structure that must be freed * with GDALDestroyPansharpenOptions(). * * @since GDAL 2.1 */ GDALPansharpenOptions* GDALClonePansharpenOptions( const GDALPansharpenOptions* psOptions) { GDALPansharpenOptions* psNewOptions = GDALCreatePansharpenOptions(); psNewOptions->ePansharpenAlg = psOptions->ePansharpenAlg; psNewOptions->eResampleAlg = psOptions->eResampleAlg; psNewOptions->nBitDepth = psOptions->nBitDepth; psNewOptions->nWeightCount = psOptions->nWeightCount; if( psOptions->padfWeights ) { psNewOptions->padfWeights = static_cast<double *>( CPLMalloc(sizeof(double) * psOptions->nWeightCount)); memcpy(psNewOptions->padfWeights, psOptions->padfWeights, sizeof(double) * psOptions->nWeightCount); } psNewOptions->hPanchroBand = psOptions->hPanchroBand; psNewOptions->nInputSpectralBands = psOptions->nInputSpectralBands; if( psOptions->pahInputSpectralBands ) { psNewOptions->pahInputSpectralBands = static_cast<GDALRasterBandH *>( CPLMalloc(sizeof(GDALRasterBandH) * psOptions->nInputSpectralBands)); memcpy(psNewOptions->pahInputSpectralBands, psOptions->pahInputSpectralBands, sizeof(GDALRasterBandH) * psOptions->nInputSpectralBands); } psNewOptions->nOutPansharpenedBands = psOptions->nOutPansharpenedBands; if( psOptions->panOutPansharpenedBands ) { psNewOptions->panOutPansharpenedBands = static_cast<int *>( CPLMalloc(sizeof(int) * psOptions->nOutPansharpenedBands)); memcpy(psNewOptions->panOutPansharpenedBands, psOptions->panOutPansharpenedBands, sizeof(int) * psOptions->nOutPansharpenedBands); } psNewOptions->bHasNoData = psOptions->bHasNoData; psNewOptions->dfNoData = psOptions->dfNoData; psNewOptions->nThreads = psOptions->nThreads; psNewOptions->dfMSShiftX = psOptions->dfMSShiftX; psNewOptions->dfMSShiftY = psOptions->dfMSShiftY; return psNewOptions; } /************************************************************************/ /* GDALPansharpenOperation() */ /************************************************************************/ /** Pansharpening operation constructor. * * The object is ready to be used after Initialize() has been called. */ GDALPansharpenOperation::GDALPansharpenOperation() = default; /************************************************************************/ /* ~GDALPansharpenOperation() */ /************************************************************************/ /** Pansharpening operation destructor. */ GDALPansharpenOperation::~GDALPansharpenOperation() { GDALDestroyPansharpenOptions(psOptions); for( size_t i = 0; i < aVDS.size(); i++ ) delete aVDS[i]; delete poThreadPool; } /************************************************************************/ /* Initialize() */ /************************************************************************/ /** Initialize the pansharpening operation. * * @param psOptionsIn pansharpening options. Must not be NULL. * * @return CE_None in case of success, CE_Failure in case of failure. */ CPLErr GDALPansharpenOperation::Initialize( const GDALPansharpenOptions* psOptionsIn ) { if( psOptionsIn->hPanchroBand == nullptr ) { CPLError(CE_Failure, CPLE_AppDefined, "hPanchroBand not set"); return CE_Failure; } if( psOptionsIn->nInputSpectralBands <= 0 ) { CPLError(CE_Failure, CPLE_AppDefined, "No input spectral bands defined"); return CE_Failure; } if( psOptionsIn->padfWeights == nullptr || psOptionsIn->nWeightCount != psOptionsIn->nInputSpectralBands ) { CPLError(CE_Failure, CPLE_AppDefined, "No weights defined, or not the same number as input " "spectral bands"); return CE_Failure; } GDALRasterBandH hRefBand = psOptionsIn->pahInputSpectralBands[0]; int bSameDataset = psOptionsIn->nInputSpectralBands > 1; if( bSameDataset ) anInputBands.push_back(GDALGetBandNumber(hRefBand)); for( int i = 1; i < psOptionsIn->nInputSpectralBands; i++ ) { GDALRasterBandH hBand = psOptionsIn->pahInputSpectralBands[i]; if( GDALGetRasterBandXSize(hBand) != GDALGetRasterBandXSize(hRefBand) || GDALGetRasterBandYSize(hBand) != GDALGetRasterBandYSize(hRefBand) ) { CPLError(CE_Failure, CPLE_AppDefined, "Dimensions of input spectral band %d different from " "first spectral band", i); return CE_Failure; } if( bSameDataset ) { if( GDALGetBandDataset(hBand) == nullptr || GDALGetBandDataset(hBand) != GDALGetBandDataset(hRefBand) ) { anInputBands.resize(0); bSameDataset = FALSE; } else { anInputBands.push_back(GDALGetBandNumber(hBand)); } } } if( psOptionsIn->nOutPansharpenedBands == 0 ) { CPLError(CE_Warning, CPLE_AppDefined, "No output pansharpened band defined"); } for( int i = 0; i < psOptionsIn->nOutPansharpenedBands; i++ ) { if( psOptionsIn->panOutPansharpenedBands[i] < 0 || psOptionsIn->panOutPansharpenedBands[i] >= psOptionsIn->nInputSpectralBands ) { CPLError(CE_Failure, CPLE_AppDefined, "Invalid value panOutPansharpenedBands[%d] = %d", i, psOptionsIn->panOutPansharpenedBands[i]); return CE_Failure; } } GDALRasterBand* poPanchroBand = GDALRasterBand::FromHandle( psOptionsIn->hPanchroBand); GDALDataType eWorkDataType = poPanchroBand->GetRasterDataType(); if( psOptionsIn->nBitDepth ) { if( psOptionsIn->nBitDepth < 0 || psOptionsIn->nBitDepth > 31 || (eWorkDataType == GDT_Byte && psOptionsIn->nBitDepth > 8) || (eWorkDataType == GDT_UInt16 && psOptionsIn->nBitDepth > 16) || (eWorkDataType == GDT_UInt32 && psOptionsIn->nBitDepth > 32) ) { CPLError(CE_Failure, CPLE_AppDefined, "Invalid value nBitDepth = %d for type %s", psOptionsIn->nBitDepth, GDALGetDataTypeName(eWorkDataType)); return CE_Failure; } } psOptions = GDALClonePansharpenOptions(psOptionsIn); if( psOptions->nBitDepth == GDALGetDataTypeSize(eWorkDataType) ) psOptions->nBitDepth = 0; if( psOptions->nBitDepth && !(eWorkDataType == GDT_Byte || eWorkDataType == GDT_UInt16 || eWorkDataType == GDT_UInt32) ) { CPLError(CE_Warning, CPLE_AppDefined, "Ignoring nBitDepth = %d for type %s", psOptions->nBitDepth, GDALGetDataTypeName(eWorkDataType)); psOptions->nBitDepth = 0; } // Detect negative weights. for( int i = 0; i<psOptions->nInputSpectralBands; i++ ) { if( psOptions->padfWeights[i] < 0.0 ) { bPositiveWeights = FALSE; break; } } for( int i = 0; i < psOptions->nInputSpectralBands; i++ ) { aMSBands.push_back( GDALRasterBand::FromHandle( psOptions->pahInputSpectralBands[i]) ); } if( psOptions->bHasNoData ) { bool bNeedToWrapInVRT = false; for( int i = 0; i < psOptions->nInputSpectralBands; i++ ) { GDALRasterBand* poBand = GDALRasterBand::FromHandle( psOptions->pahInputSpectralBands[i]); int bHasNoData = FALSE; double dfNoData = poBand->GetNoDataValue(&bHasNoData); if( !bHasNoData || dfNoData != psOptions->dfNoData ) bNeedToWrapInVRT = true; } if( bNeedToWrapInVRT ) { // Wrap spectral bands in a VRT if they don't have the nodata value. VRTDataset* poVDS = nullptr; for( int i = 0; i < psOptions->nInputSpectralBands; i++ ) { GDALRasterBand* poSrcBand = aMSBands[i]; int iVRTBand; if( anInputBands.empty() || i == 0 ) { poVDS = new VRTDataset(poSrcBand->GetXSize(), poSrcBand->GetYSize()); aVDS.push_back(poVDS); iVRTBand = 1; } else { anInputBands[i] = i + 1; iVRTBand = i + 1; } poVDS->AddBand(poSrcBand->GetRasterDataType(), nullptr); VRTSourcedRasterBand* poVRTBand = dynamic_cast<VRTSourcedRasterBand*>( poVDS->GetRasterBand(iVRTBand)); if( poVRTBand == nullptr ) return CE_Failure; aMSBands[i] = poVRTBand; poVRTBand->SetNoDataValue(psOptions->dfNoData); const char* pszNBITS = poSrcBand->GetMetadataItem("NBITS", "IMAGE_STRUCTURE"); if( pszNBITS ) poVRTBand->SetMetadataItem("NBITS", pszNBITS, "IMAGE_STRUCTURE"); VRTSimpleSource* poSimpleSource = new VRTSimpleSource(); poVRTBand->ConfigureSource(poSimpleSource, poSrcBand, FALSE, 0, 0, poSrcBand->GetXSize(), poSrcBand->GetYSize(), 0, 0, poSrcBand->GetXSize(), poSrcBand->GetYSize()); poVRTBand->AddSource( poSimpleSource ); } } } // Setup thread pool. int nThreads = psOptions->nThreads; if( nThreads == -1 ) nThreads = CPLGetNumCPUs(); else if( nThreads == 0 ) { const char* pszNumThreads = CPLGetConfigOption("GDAL_NUM_THREADS", nullptr); if( pszNumThreads ) { if( EQUAL(pszNumThreads, "ALL_CPUS") ) nThreads = CPLGetNumCPUs(); else nThreads = std::max(0, std::min(128, atoi(pszNumThreads))); } } if( nThreads > 1 ) { CPLDebug("PANSHARPEN", "Using %d threads", nThreads); poThreadPool = new (std::nothrow) CPLWorkerThreadPool(); // coverity[tainted_data] if( poThreadPool == nullptr || !poThreadPool->Setup( nThreads, nullptr, nullptr ) ) { delete poThreadPool; poThreadPool = nullptr; } } GDALRIOResampleAlg eResampleAlg = psOptions->eResampleAlg; if( eResampleAlg != GRIORA_NearestNeighbour ) { const char* pszResampling = (eResampleAlg == GRIORA_Bilinear) ? "BILINEAR" : (eResampleAlg == GRIORA_Cubic) ? "CUBIC" : (eResampleAlg == GRIORA_CubicSpline) ? "CUBICSPLINE" : (eResampleAlg == GRIORA_Lanczos) ? "LANCZOS" : (eResampleAlg == GRIORA_Average) ? "AVERAGE" : (eResampleAlg == GRIORA_Mode) ? "MODE" : (eResampleAlg == GRIORA_Gauss) ? "GAUSS" : "UNKNOWN"; GDALGetResampleFunction(pszResampling, &nKernelRadius); } return CE_None; } /************************************************************************/ /* WeightedBroveyWithNoData() */ /************************************************************************/ template<class WorkDataType, class OutDataType> void GDALPansharpenOperation::WeightedBroveyWithNoData( const WorkDataType* pPanBuffer, const WorkDataType* pUpsampledSpectralBuffer, OutDataType* pDataBuf, size_t nValues, size_t nBandValues, WorkDataType nMaxValue) const { WorkDataType noData, validValue; GDALCopyWord(psOptions->dfNoData, noData); if( !(std::numeric_limits<WorkDataType>::is_integer) ) validValue = static_cast<WorkDataType>(noData + 1e-5); else if( noData == std::numeric_limits<WorkDataType>::min() ) validValue = std::numeric_limits<WorkDataType>::min() + 1; else validValue = noData - 1; for( size_t j = 0; j < nValues; j++ ) { double dfPseudoPanchro = 0.0; for( int i = 0; i < psOptions->nInputSpectralBands; i++ ) { WorkDataType nSpectralVal = pUpsampledSpectralBuffer[i * nBandValues + j]; if( nSpectralVal == noData ) { dfPseudoPanchro = 0.0; break; } dfPseudoPanchro += psOptions->padfWeights[i] * nSpectralVal; } if( dfPseudoPanchro != 0.0 && pPanBuffer[j] != noData ) { const double dfFactor = pPanBuffer[j] / dfPseudoPanchro; for( int i = 0; i < psOptions->nOutPansharpenedBands; i++ ) { WorkDataType nRawValue = pUpsampledSpectralBuffer[ psOptions->panOutPansharpenedBands[i] * nBandValues + j]; WorkDataType nPansharpenedValue; GDALCopyWord(nRawValue * dfFactor, nPansharpenedValue); if( nMaxValue != 0 && nPansharpenedValue > nMaxValue ) nPansharpenedValue = nMaxValue; // We don't want a valid value to be mapped to NoData. if( nPansharpenedValue == noData ) nPansharpenedValue = validValue; GDALCopyWord(nPansharpenedValue, pDataBuf[i * nBandValues + j]); } } else { for( int i = 0; i < psOptions->nOutPansharpenedBands; i++ ) { GDALCopyWord(noData, pDataBuf[i * nBandValues + j]); } } } } /************************************************************************/ /* ComputeFactor() */ /************************************************************************/ template<class T> static inline double ComputeFactor(T panValue, double dfPseudoPanchro) { if( dfPseudoPanchro == 0.0 ) return 0.0; return panValue / dfPseudoPanchro; } /************************************************************************/ /* ClampAndRound() */ /************************************************************************/ template<class T> static inline T ClampAndRound(double dfVal, T nMaxValue) { if( dfVal > nMaxValue ) return nMaxValue; else return static_cast<T>(dfVal + 0.5); } /************************************************************************/ /* WeightedBrovey() */ /************************************************************************/ template<class WorkDataType, class OutDataType, int bHasBitDepth> void GDALPansharpenOperation::WeightedBrovey3( const WorkDataType* pPanBuffer, const WorkDataType* pUpsampledSpectralBuffer, OutDataType* pDataBuf, size_t nValues, size_t nBandValues, WorkDataType nMaxValue) const { if( psOptions->bHasNoData ) { WeightedBroveyWithNoData<WorkDataType, OutDataType> (pPanBuffer, pUpsampledSpectralBuffer, pDataBuf, nValues, nBandValues, nMaxValue); return; } for( size_t j = 0; j < nValues; j++ ) { double dfFactor = 0.0; // if( pPanBuffer[j] == 0 ) // dfFactor = 1.0; // else { double dfPseudoPanchro = 0.0; for( int i = 0; i < psOptions->nInputSpectralBands; i++ ) dfPseudoPanchro += psOptions->padfWeights[i] * pUpsampledSpectralBuffer[i * nBandValues + j]; dfFactor = ComputeFactor(pPanBuffer[j], dfPseudoPanchro); } for( int i = 0; i < psOptions->nOutPansharpenedBands; i++ ) { WorkDataType nRawValue = pUpsampledSpectralBuffer[psOptions->panOutPansharpenedBands[i] * nBandValues + j]; WorkDataType nPansharpenedValue; GDALCopyWord(nRawValue * dfFactor, nPansharpenedValue); if( bHasBitDepth && nPansharpenedValue > nMaxValue ) nPansharpenedValue = nMaxValue; GDALCopyWord(nPansharpenedValue, pDataBuf[i * nBandValues + j]); } } } /* We restrict to 64bit processors because they are guaranteed to have SSE2 */ /* Could possibly be used too on 32bit, but we would need to check at runtime */ #if defined(__x86_64) || defined(_M_X64) #include "gdalsse_priv.h" template<class T, int NINPUT, int NOUTPUT> size_t GDALPansharpenOperation::WeightedBroveyPositiveWeightsInternal( const T* pPanBuffer, const T* pUpsampledSpectralBuffer, T* pDataBuf, size_t nValues, size_t nBandValues, T nMaxValue) const { CPL_STATIC_ASSERT( NINPUT == 3 || NINPUT == 4 ); CPL_STATIC_ASSERT( NOUTPUT == 3 || NOUTPUT == 4 ); const XMMReg4Double w0 = XMMReg4Double::Load1ValHighAndLow(psOptions->padfWeights + 0); const XMMReg4Double w1 = XMMReg4Double::Load1ValHighAndLow(psOptions->padfWeights + 1); const XMMReg4Double w2 = XMMReg4Double::Load1ValHighAndLow(psOptions->padfWeights + 2); const XMMReg4Double w3 = (NINPUT == 3) ? XMMReg4Double::Zero() : XMMReg4Double::Load1ValHighAndLow(psOptions->padfWeights + 3); const XMMReg4Double zero = XMMReg4Double::Zero(); double dfMaxValue = nMaxValue; const XMMReg4Double maxValue = XMMReg4Double::Load1ValHighAndLow(&dfMaxValue); size_t j = 0; // Used after for. for( ; j + 3 < nValues; j += 4 ) { XMMReg4Double pseudoPanchro = zero; XMMReg4Double val0 = XMMReg4Double::Load4Val(pUpsampledSpectralBuffer + 0 * nBandValues + j); XMMReg4Double val1 = XMMReg4Double::Load4Val(pUpsampledSpectralBuffer + 1 * nBandValues + j); XMMReg4Double val2 = XMMReg4Double::Load4Val(pUpsampledSpectralBuffer + 2 * nBandValues + j); XMMReg4Double val3; if( NINPUT == 4 || NOUTPUT == 4 ) { val3 = XMMReg4Double::Load4Val(pUpsampledSpectralBuffer + 3 * nBandValues + j); } pseudoPanchro += w0 * val0; pseudoPanchro += w1 * val1; pseudoPanchro += w2 * val2; if( NINPUT == 4 ) pseudoPanchro += w3 * val3; /* Little trick to avoid use of ternary operator due to one of the branch being zero */ XMMReg4Double factor = XMMReg4Double::And( XMMReg4Double::NotEquals(pseudoPanchro, zero), XMMReg4Double::Load4Val(pPanBuffer + j) / pseudoPanchro ); val0 = XMMReg4Double::Min(val0 * factor, maxValue); val1 = XMMReg4Double::Min(val1 * factor, maxValue); val2 = XMMReg4Double::Min(val2 * factor, maxValue); if( NOUTPUT == 4 ) { val3 = XMMReg4Double::Min(val3 * factor, maxValue); } val0.Store4Val(pDataBuf + 0 * nBandValues + j); val1.Store4Val(pDataBuf + 1 * nBandValues + j); val2.Store4Val(pDataBuf + 2 * nBandValues + j); if( NOUTPUT == 4 ) { val3.Store4Val(pDataBuf + 3 * nBandValues + j); } } return j; } #else template<class T, int NINPUT, int NOUTPUT> size_t GDALPansharpenOperation::WeightedBroveyPositiveWeightsInternal( const T* pPanBuffer, const T* pUpsampledSpectralBuffer, T* pDataBuf, size_t nValues, size_t nBandValues, T nMaxValue) const { // cppcheck-suppress knownConditionTrueFalse CPLAssert( NINPUT == 3 || NINPUT == 4 ); const double dfw0 = psOptions->padfWeights[0]; const double dfw1 = psOptions->padfWeights[1]; const double dfw2 = psOptions->padfWeights[2]; // cppcheck-suppress knownConditionTrueFalse const double dfw3 = (NINPUT == 3) ? 0 : psOptions->padfWeights[3]; size_t j = 0; // Used after for. for( ; j + 1 < nValues; j += 2 ) { double dfFactor = 0.0; double dfFactor2 = 0.0; double dfPseudoPanchro = 0.0; double dfPseudoPanchro2 = 0.0; dfPseudoPanchro += dfw0 * pUpsampledSpectralBuffer[j]; dfPseudoPanchro2 += dfw0 * pUpsampledSpectralBuffer[j + 1]; dfPseudoPanchro += dfw1 * pUpsampledSpectralBuffer[nBandValues + j]; dfPseudoPanchro2 += dfw1 * pUpsampledSpectralBuffer[nBandValues + j + 1]; dfPseudoPanchro += dfw2 * pUpsampledSpectralBuffer[2 * nBandValues + j]; dfPseudoPanchro2 += dfw2 * pUpsampledSpectralBuffer[2 * nBandValues + j + 1]; if( NINPUT == 4 ) { dfPseudoPanchro += dfw3 * pUpsampledSpectralBuffer[3 * nBandValues + j]; dfPseudoPanchro2 += dfw3 * pUpsampledSpectralBuffer[3 * nBandValues + j + 1]; } dfFactor = ComputeFactor(pPanBuffer[j], dfPseudoPanchro); dfFactor2 = ComputeFactor(pPanBuffer[j+1], dfPseudoPanchro2); for( int i = 0; i < NOUTPUT; i++ ) { T nRawValue = pUpsampledSpectralBuffer[i * nBandValues + j]; double dfTmp = nRawValue * dfFactor; pDataBuf[i * nBandValues + j] = ClampAndRound(dfTmp, nMaxValue); T nRawValue2 = pUpsampledSpectralBuffer[i * nBandValues + j + 1]; double dfTmp2 = nRawValue2 * dfFactor2; pDataBuf[i * nBandValues + j + 1] = ClampAndRound(dfTmp2, nMaxValue); } } return j; } #endif template <class T> void GDALPansharpenOperation::WeightedBroveyPositiveWeights( const T* pPanBuffer, const T* pUpsampledSpectralBuffer, T* pDataBuf, size_t nValues, size_t nBandValues, T nMaxValue) const { if( psOptions->bHasNoData ) { WeightedBroveyWithNoData<T, T> (pPanBuffer, pUpsampledSpectralBuffer, pDataBuf, nValues, nBandValues, nMaxValue); return; } if( nMaxValue == 0 ) nMaxValue = std::numeric_limits<T>::max(); size_t j; if( psOptions->nInputSpectralBands == 3 && psOptions->nOutPansharpenedBands == 3 && psOptions->panOutPansharpenedBands[0] == 0 && psOptions->panOutPansharpenedBands[1] == 1 && psOptions->panOutPansharpenedBands[2] == 2 ) { j = WeightedBroveyPositiveWeightsInternal<T, 3, 3>( pPanBuffer, pUpsampledSpectralBuffer, pDataBuf, nValues, nBandValues, nMaxValue); } else if( psOptions->nInputSpectralBands == 4 && psOptions->nOutPansharpenedBands == 4 && psOptions->panOutPansharpenedBands[0] == 0 && psOptions->panOutPansharpenedBands[1] == 1 && psOptions->panOutPansharpenedBands[2] == 2 && psOptions->panOutPansharpenedBands[3] == 3 ) { j = WeightedBroveyPositiveWeightsInternal<T, 4, 4>( pPanBuffer, pUpsampledSpectralBuffer, pDataBuf, nValues, nBandValues, nMaxValue); } else if( psOptions->nInputSpectralBands == 4 && psOptions->nOutPansharpenedBands == 3 && psOptions->panOutPansharpenedBands[0] == 0 && psOptions->panOutPansharpenedBands[1] == 1 && psOptions->panOutPansharpenedBands[2] == 2 ) { j = WeightedBroveyPositiveWeightsInternal<T, 4, 3>( pPanBuffer, pUpsampledSpectralBuffer, pDataBuf, nValues, nBandValues, nMaxValue); } else { for( j = 0; j + 1 < nValues; j += 2 ) { double dfFactor = 0.0; double dfFactor2 = 0.0; double dfPseudoPanchro = 0.0; double dfPseudoPanchro2 = 0.0; for( int i = 0; i < psOptions->nInputSpectralBands; i++ ) { dfPseudoPanchro += psOptions->padfWeights[i] * pUpsampledSpectralBuffer[i * nBandValues + j]; dfPseudoPanchro2 += psOptions->padfWeights[i] * pUpsampledSpectralBuffer[i * nBandValues + j + 1]; } dfFactor = ComputeFactor(pPanBuffer[j], dfPseudoPanchro); dfFactor2 = ComputeFactor(pPanBuffer[j+1], dfPseudoPanchro2); for( int i = 0; i < psOptions->nOutPansharpenedBands; i++ ) { const T nRawValue = pUpsampledSpectralBuffer[psOptions->panOutPansharpenedBands[i] * nBandValues + j]; const double dfTmp = nRawValue * dfFactor; pDataBuf[i * nBandValues + j] = ClampAndRound(dfTmp, nMaxValue); const T nRawValue2 = pUpsampledSpectralBuffer[psOptions->panOutPansharpenedBands[i] * nBandValues + j + 1]; const double dfTmp2 = nRawValue2 * dfFactor2; pDataBuf[i * nBandValues + j + 1] = ClampAndRound(dfTmp2, nMaxValue); } } } for( ;j<nValues ;j++) { double dfFactor = 0.0; double dfPseudoPanchro = 0.0; for( int i = 0; i < psOptions->nInputSpectralBands; i++ ) dfPseudoPanchro += psOptions->padfWeights[i] * pUpsampledSpectralBuffer[i * nBandValues + j]; dfFactor = ComputeFactor(pPanBuffer[j], dfPseudoPanchro); for( int i = 0; i < psOptions->nOutPansharpenedBands; i++ ) { T nRawValue = pUpsampledSpectralBuffer[psOptions->panOutPansharpenedBands[i] * nBandValues + j]; double dfTmp = nRawValue * dfFactor; pDataBuf[i * nBandValues + j] = ClampAndRound(dfTmp, nMaxValue); } } } template<class WorkDataType, class OutDataType> void GDALPansharpenOperation::WeightedBrovey( const WorkDataType* pPanBuffer, const WorkDataType* pUpsampledSpectralBuffer, OutDataType* pDataBuf, size_t nValues, size_t nBandValues, WorkDataType nMaxValue ) const { if( nMaxValue == 0 ) WeightedBrovey3<WorkDataType, OutDataType, FALSE>( pPanBuffer, pUpsampledSpectralBuffer, pDataBuf, nValues, nBandValues, 0); else { WeightedBrovey3<WorkDataType, OutDataType, TRUE>( pPanBuffer, pUpsampledSpectralBuffer, pDataBuf, nValues, nBandValues, nMaxValue); } } template<class T> void GDALPansharpenOperation::WeightedBroveyGByteOrUInt16( const T* pPanBuffer, const T* pUpsampledSpectralBuffer, T* pDataBuf, size_t nValues, size_t nBandValues, T nMaxValue ) const { if( bPositiveWeights ) { WeightedBroveyPositiveWeights( pPanBuffer, pUpsampledSpectralBuffer, pDataBuf, nValues, nBandValues, nMaxValue); } else if( nMaxValue == 0 ) { WeightedBrovey3<T, T, FALSE>( pPanBuffer, pUpsampledSpectralBuffer, pDataBuf, nValues, nBandValues, 0); } else { WeightedBrovey3<T, T, TRUE>( pPanBuffer, pUpsampledSpectralBuffer, pDataBuf, nValues, nBandValues, nMaxValue); } } template<> void GDALPansharpenOperation::WeightedBrovey<GByte, GByte>( const GByte* pPanBuffer, const GByte* pUpsampledSpectralBuffer, GByte* pDataBuf, size_t nValues, size_t nBandValues, GByte nMaxValue ) const { WeightedBroveyGByteOrUInt16(pPanBuffer, pUpsampledSpectralBuffer, pDataBuf, nValues, nBandValues, nMaxValue); } template<> void GDALPansharpenOperation::WeightedBrovey<GUInt16, GUInt16>( const GUInt16* pPanBuffer, const GUInt16* pUpsampledSpectralBuffer, GUInt16* pDataBuf, size_t nValues, size_t nBandValues, GUInt16 nMaxValue ) const { WeightedBroveyGByteOrUInt16(pPanBuffer, pUpsampledSpectralBuffer, pDataBuf, nValues, nBandValues, nMaxValue); } template<class WorkDataType> CPLErr GDALPansharpenOperation::WeightedBrovey( const WorkDataType* pPanBuffer, const WorkDataType* pUpsampledSpectralBuffer, void *pDataBuf, GDALDataType eBufDataType, size_t nValues, size_t nBandValues, WorkDataType nMaxValue ) const { switch( eBufDataType ) { case GDT_Byte: WeightedBrovey(pPanBuffer, pUpsampledSpectralBuffer, static_cast<GByte *>(pDataBuf), nValues, nBandValues, nMaxValue); break; case GDT_UInt16: WeightedBrovey(pPanBuffer, pUpsampledSpectralBuffer, static_cast<GUInt16 *>(pDataBuf), nValues, nBandValues, nMaxValue); break; #ifndef LIMIT_TYPES case GDT_Int16: WeightedBrovey(pPanBuffer, pUpsampledSpectralBuffer, static_cast<GInt16 *>(pDataBuf), nValues, nBandValues, nMaxValue); break; case GDT_UInt32: WeightedBrovey(pPanBuffer, pUpsampledSpectralBuffer, static_cast<GUInt32 *>(pDataBuf), nValues, nBandValues, nMaxValue); break; case GDT_Int32: WeightedBrovey(pPanBuffer, pUpsampledSpectralBuffer, static_cast<GInt32 *>(pDataBuf), nValues, nBandValues, nMaxValue); break; case GDT_Float32: WeightedBrovey(pPanBuffer, pUpsampledSpectralBuffer, static_cast<float *>(pDataBuf), nValues, nBandValues, nMaxValue); break; #endif case GDT_Float64: WeightedBrovey(pPanBuffer, pUpsampledSpectralBuffer, static_cast<double *>(pDataBuf), nValues, nBandValues, nMaxValue); break; default: CPLError(CE_Failure, CPLE_NotSupported, "eBufDataType not supported"); return CE_Failure; break; } return CE_None; } template<class WorkDataType> CPLErr GDALPansharpenOperation::WeightedBrovey( const WorkDataType* pPanBuffer, const WorkDataType* pUpsampledSpectralBuffer, void *pDataBuf, GDALDataType eBufDataType, size_t nValues, size_t nBandValues ) const { switch( eBufDataType ) { case GDT_Byte: WeightedBrovey3<WorkDataType, GByte, FALSE>( pPanBuffer, pUpsampledSpectralBuffer, static_cast<GByte *>(pDataBuf), nValues, nBandValues, 0); break; case GDT_UInt16: WeightedBrovey3<WorkDataType, GUInt16, FALSE>( pPanBuffer, pUpsampledSpectralBuffer, static_cast<GUInt16 *>(pDataBuf), nValues, nBandValues, 0); break; #ifndef LIMIT_TYPES case GDT_Int16: WeightedBrovey3<WorkDataType, GInt16, FALSE>( pPanBuffer, pUpsampledSpectralBuffer, static_cast<GInt16 *>(pDataBuf), nValues, nBandValues, 0); break; case GDT_UInt32: WeightedBrovey3<WorkDataType, GUInt32, FALSE>( pPanBuffer, pUpsampledSpectralBuffer, static_cast<GUInt32 *>(pDataBuf), nValues, nBandValues, 0); break; case GDT_Int32: WeightedBrovey3<WorkDataType, GInt32, FALSE>( pPanBuffer, pUpsampledSpectralBuffer, static_cast<GInt32 *>(pDataBuf), nValues, nBandValues, 0); break; case GDT_Float32: WeightedBrovey3<WorkDataType, float, FALSE>( pPanBuffer, pUpsampledSpectralBuffer, static_cast<float *>(pDataBuf), nValues, nBandValues, 0); break; #endif case GDT_Float64: WeightedBrovey3<WorkDataType, double, FALSE>( pPanBuffer, pUpsampledSpectralBuffer, static_cast<double *>(pDataBuf), nValues, nBandValues, 0); break; default: CPLError(CE_Failure, CPLE_NotSupported, "eBufDataType not supported"); return CE_Failure; break; } return CE_None; } /************************************************************************/ /* ClampValues() */ /************************************************************************/ template< class T > static void ClampValues( T* panBuffer, size_t nValues, T nMaxVal ) { for( size_t i = 0; i < nValues; i++ ) { if( panBuffer[i] > nMaxVal ) panBuffer[i] = nMaxVal; } } /************************************************************************/ /* ProcessRegion() */ /************************************************************************/ /** Executes a pansharpening operation on a rectangular region of the * resulting dataset. * * The window is expressed with respect to the dimensions of the panchromatic * band. * * Spectral bands are upsampled and merged with the panchromatic band according * to the select algorithm and options. * * @param nXOff pixel offset. * @param nYOff pixel offset. * @param nXSize width of the pansharpened region to compute. * @param nYSize height of the pansharpened region to compute. * @param pDataBuf output buffer. Must be nXSize * nYSize * * GDALGetDataTypeSizeBytes(eBufDataType) * * psOptions->nOutPansharpenedBands large. * It begins with all values of the first output band, followed * by values of the second output band, etc... * @param eBufDataType data type of the output buffer * * @return CE_None in case of success, CE_Failure in case of failure. * * @since GDAL 2.1 */ CPLErr GDALPansharpenOperation::ProcessRegion( int nXOff, int nYOff, int nXSize, int nYSize, void *pDataBuf, GDALDataType eBufDataType ) { if( psOptions == nullptr ) return CE_Failure; // TODO: Avoid allocating buffers each time. GDALRasterBand* poPanchroBand = GDALRasterBand::FromHandle( psOptions->hPanchroBand); GDALDataType eWorkDataType = poPanchroBand->GetRasterDataType(); #ifdef LIMIT_TYPES if( eWorkDataType != GDT_Byte && eWorkDataType != GDT_UInt16 ) eWorkDataType = GDT_Float64; #endif const int nDataTypeSize = GDALGetDataTypeSizeBytes(eWorkDataType); GByte* pUpsampledSpectralBuffer = static_cast<GByte *>( VSI_MALLOC3_VERBOSE(nXSize, nYSize, psOptions->nInputSpectralBands * nDataTypeSize)); GByte* pPanBuffer = static_cast<GByte *>( VSI_MALLOC3_VERBOSE(nXSize, nYSize, nDataTypeSize)); if( pUpsampledSpectralBuffer == nullptr || pPanBuffer == nullptr ) { VSIFree(pUpsampledSpectralBuffer); VSIFree(pPanBuffer); return CE_Failure; } CPLErr eErr = poPanchroBand->RasterIO(GF_Read, nXOff, nYOff, nXSize, nYSize, pPanBuffer, nXSize, nYSize, eWorkDataType, 0, 0, nullptr); if( eErr != CE_None ) { VSIFree(pUpsampledSpectralBuffer); VSIFree(pPanBuffer); return CE_Failure; } int nTasks = 0; if( poThreadPool ) { nTasks = poThreadPool->GetThreadCount(); if( nTasks > nYSize ) nTasks = nYSize; } GDALRasterIOExtraArg sExtraArg; INIT_RASTERIO_EXTRA_ARG(sExtraArg); const GDALRIOResampleAlg eResampleAlg = psOptions->eResampleAlg; sExtraArg.eResampleAlg = eResampleAlg; sExtraArg.bFloatingPointWindowValidity = TRUE; double dfRatioX = static_cast<double>(poPanchroBand->GetXSize()) / aMSBands[0]->GetXSize(); double dfRatioY = static_cast<double>(poPanchroBand->GetYSize()) / aMSBands[0]->GetYSize(); sExtraArg.dfXOff = (nXOff + psOptions->dfMSShiftX) / dfRatioX; sExtraArg.dfYOff = (nYOff + psOptions->dfMSShiftY) / dfRatioY; sExtraArg.dfXSize = nXSize / dfRatioX; sExtraArg.dfYSize = nYSize / dfRatioY; if( sExtraArg.dfXOff + sExtraArg.dfXSize > aMSBands[0]->GetXSize() ) sExtraArg.dfXOff = aMSBands[0]->GetXSize() - sExtraArg.dfXSize; if( sExtraArg.dfYOff + sExtraArg.dfYSize > aMSBands[0]->GetYSize() ) sExtraArg.dfYOff = aMSBands[0]->GetYSize() - sExtraArg.dfYSize; int nSpectralXOff = static_cast<int>(sExtraArg.dfXOff); int nSpectralYOff = static_cast<int>(sExtraArg.dfYOff); int nSpectralXSize = static_cast<int>(0.49999 + sExtraArg.dfXSize); int nSpectralYSize = static_cast<int>(0.49999 + sExtraArg.dfYSize); if( nSpectralXSize == 0 ) nSpectralXSize = 1; if( nSpectralYSize == 0 ) nSpectralYSize = 1; // When upsampling, extract the multispectral data at // full resolution in a temp buffer, and then do the upsampling. if( nSpectralXSize < nXSize && nSpectralYSize < nYSize && eResampleAlg != GRIORA_NearestNeighbour && nYSize > 1 ) { // Take some margin to take into account the radius of the // resampling kernel. int nXOffExtract = nSpectralXOff - nKernelRadius; int nYOffExtract = nSpectralYOff - nKernelRadius; int nXSizeExtract = nSpectralXSize + 1 + 2 * nKernelRadius; int nYSizeExtract = nSpectralYSize + 1 + 2 * nKernelRadius; if( nXOffExtract < 0 ) { nXSizeExtract += nXOffExtract; nXOffExtract = 0; } if( nYOffExtract < 0 ) { nYSizeExtract += nYOffExtract; nYOffExtract = 0; } if( nXOffExtract + nXSizeExtract > aMSBands[0]->GetXSize() ) nXSizeExtract = aMSBands[0]->GetXSize() - nXOffExtract; if( nYOffExtract + nYSizeExtract > aMSBands[0]->GetYSize() ) nYSizeExtract = aMSBands[0]->GetYSize() - nYOffExtract; GByte* pSpectralBuffer = static_cast<GByte *>( VSI_MALLOC3_VERBOSE( nXSizeExtract, nYSizeExtract, psOptions->nInputSpectralBands * nDataTypeSize)); if( pSpectralBuffer == nullptr ) { VSIFree(pUpsampledSpectralBuffer); VSIFree(pPanBuffer); return CE_Failure; } if( !anInputBands.empty() ) { // Use dataset RasterIO when possible. eErr = aMSBands[0]->GetDataset()->RasterIO( GF_Read, nXOffExtract, nYOffExtract, nXSizeExtract, nYSizeExtract, pSpectralBuffer, nXSizeExtract, nYSizeExtract, eWorkDataType, static_cast<int>(anInputBands.size()), &anInputBands[0], 0, 0, 0, nullptr); } else { for( int i = 0; eErr == CE_None && i < psOptions->nInputSpectralBands; i++ ) { eErr = aMSBands[i]->RasterIO( GF_Read, nXOffExtract, nYOffExtract, nXSizeExtract, nYSizeExtract, pSpectralBuffer + static_cast<size_t>(i) * nXSizeExtract * nYSizeExtract * nDataTypeSize, nXSizeExtract, nYSizeExtract, eWorkDataType, 0, 0, nullptr); } } if( eErr != CE_None ) { VSIFree(pSpectralBuffer); VSIFree(pUpsampledSpectralBuffer); VSIFree(pPanBuffer); return CE_Failure; } // Create a MEM dataset that wraps the input buffer. GDALDataset* poMEMDS = MEMDataset::Create("", nXSizeExtract, nYSizeExtract, 0, eWorkDataType, nullptr); char szBuffer0[64] = {}; char szBuffer1[64] = {}; char szBuffer2[64] = {}; snprintf(szBuffer1, sizeof(szBuffer1), "PIXELOFFSET=" CPL_FRMT_GIB, static_cast<GIntBig>(nDataTypeSize)); snprintf(szBuffer2, sizeof(szBuffer2), "LINEOFFSET=" CPL_FRMT_GIB, static_cast<GIntBig>(nDataTypeSize) * nXSizeExtract); char* apszOptions[4] = {}; apszOptions[0] = szBuffer0; apszOptions[1] = szBuffer1; apszOptions[2] = szBuffer2; apszOptions[3] = nullptr; for( int i = 0; i < psOptions->nInputSpectralBands; i++ ) { char szBuffer[32] = {}; int nRet = CPLPrintPointer( szBuffer, pSpectralBuffer + static_cast<size_t>(i) * nDataTypeSize * nXSizeExtract * nYSizeExtract, sizeof(szBuffer)); szBuffer[nRet] = 0; snprintf(szBuffer0, sizeof(szBuffer0), "DATAPOINTER=%s", szBuffer); poMEMDS->AddBand(eWorkDataType, apszOptions); const char* pszNBITS = aMSBands[i]->GetMetadataItem("NBITS", "IMAGE_STRUCTURE"); if( pszNBITS ) poMEMDS->GetRasterBand(i+1)->SetMetadataItem("NBITS", pszNBITS, "IMAGE_STRUCTURE"); if( psOptions->bHasNoData ) poMEMDS->GetRasterBand(i+1) ->SetNoDataValue(psOptions->dfNoData); } if( nTasks <= 1 ) { nSpectralXOff -= nXOffExtract; nSpectralYOff -= nYOffExtract; sExtraArg.dfXOff -= nXOffExtract; sExtraArg.dfYOff -= nYOffExtract; CPL_IGNORE_RET_VAL(poMEMDS->RasterIO(GF_Read, nSpectralXOff, nSpectralYOff, nSpectralXSize, nSpectralYSize, pUpsampledSpectralBuffer, nXSize, nYSize, eWorkDataType, psOptions->nInputSpectralBands, nullptr, 0, 0, 0, &sExtraArg)); } else { // We are abusing the contract of the GDAL API by using the // MEMDataset from several threads. In this case, this is safe. In // case, that would no longer be the case we could create as many // MEMDataset as threads pointing to the same buffer. // To avoid races in threads, we query now the mask flags, // so that implicit mask bands are created now. if( eResampleAlg != GRIORA_NearestNeighbour ) { for( int i = 0; i < poMEMDS->GetRasterCount(); i++ ) { poMEMDS->GetRasterBand(i+1)->GetMaskFlags(); } } std::vector<GDALPansharpenResampleJob> asJobs; asJobs.resize( nTasks ); GDALPansharpenResampleJob* pasJobs = &(asJobs[0]); { std::vector<void*> ahJobData; ahJobData.resize( nTasks ); #ifdef DEBUG_TIMING struct timeval tv; #endif for( int i=0;i<nTasks;i++) { const size_t iStartLine = (static_cast<size_t>(i) * nYSize) / nTasks; const size_t iNextStartLine = (static_cast<size_t>(i+1) * nYSize) / nTasks; pasJobs[i].poMEMDS = poMEMDS; pasJobs[i].eResampleAlg = eResampleAlg; pasJobs[i].dfXOff = sExtraArg.dfXOff - nXOffExtract; pasJobs[i].dfYOff = (nYOff + psOptions->dfMSShiftY + iStartLine) / dfRatioY - nYOffExtract; pasJobs[i].dfXSize = sExtraArg.dfXSize; pasJobs[i].dfYSize = (iNextStartLine - iStartLine) / dfRatioY; if( pasJobs[i].dfXOff + pasJobs[i].dfXSize > aMSBands[0]->GetXSize() ) { pasJobs[i].dfXOff = aMSBands[0]->GetXSize() - pasJobs[i].dfXSize; } if( pasJobs[i].dfYOff + pasJobs[i].dfYSize > aMSBands[0]->GetYSize() ) { pasJobs[i].dfYOff = aMSBands[0]->GetYSize() - pasJobs[i].dfYSize; } pasJobs[i].nXOff = static_cast<int>(pasJobs[i].dfXOff); pasJobs[i].nYOff = static_cast<int>(pasJobs[i].dfYOff); pasJobs[i].nXSize = static_cast<int>(0.4999 + pasJobs[i].dfXSize); pasJobs[i].nYSize = static_cast<int>(0.4999 + pasJobs[i].dfYSize); if( pasJobs[i].nXSize == 0 ) pasJobs[i].nXSize = 1; if( pasJobs[i].nYSize == 0 ) pasJobs[i].nYSize = 1; pasJobs[i].pBuffer = pUpsampledSpectralBuffer + static_cast<size_t>(iStartLine) * nXSize * nDataTypeSize; pasJobs[i].eDT = eWorkDataType; pasJobs[i].nBufXSize = nXSize; pasJobs[i].nBufYSize = static_cast<int>(iNextStartLine - iStartLine); pasJobs[i].nBandCount = psOptions->nInputSpectralBands; pasJobs[i].nBandSpace = static_cast<GSpacing>(nXSize) * nYSize * nDataTypeSize; #ifdef DEBUG_TIMING pasJobs[i].ptv = &tv; #endif ahJobData[i] = &(pasJobs[i]); } #ifdef DEBUG_TIMING gettimeofday(&tv, nullptr); #endif poThreadPool->SubmitJobs(PansharpenResampleJobThreadFunc, ahJobData); poThreadPool->WaitCompletion(); } } GDALClose(poMEMDS); VSIFree(pSpectralBuffer); } else { if( !anInputBands.empty() ) { // Use dataset RasterIO when possible. eErr = aMSBands[0]->GetDataset()->RasterIO( GF_Read, nSpectralXOff, nSpectralYOff, nSpectralXSize, nSpectralYSize, pUpsampledSpectralBuffer, nXSize, nYSize, eWorkDataType, static_cast<int>(anInputBands.size()), &anInputBands[0], 0, 0, 0, &sExtraArg); } else { for( int i = 0; eErr == CE_None && i < psOptions->nInputSpectralBands; i++ ) { eErr = aMSBands[i]->RasterIO( GF_Read, nSpectralXOff, nSpectralYOff, nSpectralXSize, nSpectralYSize, pUpsampledSpectralBuffer + static_cast<size_t>(i) * nXSize * nYSize * nDataTypeSize, nXSize, nYSize, eWorkDataType, 0, 0, &sExtraArg); } } if( eErr != CE_None ) { VSIFree(pUpsampledSpectralBuffer); VSIFree(pPanBuffer); return CE_Failure; } } // In case NBITS was not set on the spectral bands, clamp the values // if overshoot might have occurred. int nBitDepth = psOptions->nBitDepth; if( nBitDepth && (eResampleAlg == GRIORA_Cubic || eResampleAlg == GRIORA_CubicSpline || eResampleAlg == GRIORA_Lanczos) ) { for( int i = 0; i < psOptions->nInputSpectralBands; i++ ) { GDALRasterBand* poBand = aMSBands[i]; int nBandBitDepth = 0; const char* pszNBITS = poBand->GetMetadataItem("NBITS", "IMAGE_STRUCTURE"); if( pszNBITS ) nBandBitDepth = atoi(pszNBITS); if( nBandBitDepth < nBitDepth ) { if( eWorkDataType == GDT_Byte ) { ClampValues(reinterpret_cast<GByte*>(pUpsampledSpectralBuffer) + static_cast<size_t>(i) * nXSize * nYSize, static_cast<size_t>(nXSize)*nYSize, static_cast<GByte>((1 << nBitDepth)-1)); } else if( eWorkDataType == GDT_UInt16 ) { ClampValues(reinterpret_cast<GUInt16*>(pUpsampledSpectralBuffer) + static_cast<size_t>(i) * nXSize * nYSize, static_cast<size_t>(nXSize)*nYSize, static_cast<GUInt16>((1 << nBitDepth)-1)); } #ifndef LIMIT_TYPES else if( eWorkDataType == GDT_UInt32 ) { ClampValues(reinterpret_cast<GUInt32*>(pUpsampledSpectralBuffer) + static_cast<size_t>(i) * nXSize * nYSize, static_cast<size_t>(nXSize)*nYSize, (static_cast<GUInt32>((1 << nBitDepth)-1)); } #endif } } } GUInt32 nMaxValue = (1 << nBitDepth) - 1; double* padfTempBuffer = nullptr; GDALDataType eBufDataTypeOri = eBufDataType; void* pDataBufOri = pDataBuf; // CFloat64 is the query type used by gdallocationinfo... #ifdef LIMIT_TYPES if( eBufDataType != GDT_Byte && eBufDataType != GDT_UInt16 ) #else if( eBufDataType == GDT_CFloat64 ) #endif { padfTempBuffer = static_cast<double * >( VSI_MALLOC3_VERBOSE( nXSize, nYSize, psOptions->nOutPansharpenedBands * sizeof(double))); if( padfTempBuffer == nullptr ) { VSIFree(pUpsampledSpectralBuffer); VSIFree(pPanBuffer); return CE_Failure; } pDataBuf = padfTempBuffer; eBufDataType = GDT_Float64; } if( nTasks > 1 ) { std::vector<GDALPansharpenJob> asJobs; asJobs.resize( nTasks ); GDALPansharpenJob* pasJobs = &(asJobs[0]); { std::vector<void*> ahJobData; ahJobData.resize( nTasks ); #ifdef DEBUG_TIMING struct timeval tv; #endif for( int i=0;i<nTasks;i++) { const size_t iStartLine = (static_cast<size_t>(i) * nYSize) / nTasks; const size_t iNextStartLine = (static_cast<size_t>(i + 1) * nYSize) / nTasks; pasJobs[i].poPansharpenOperation = this; pasJobs[i].eWorkDataType = eWorkDataType; pasJobs[i].eBufDataType = eBufDataType; pasJobs[i].pPanBuffer = pPanBuffer + iStartLine * nXSize * nDataTypeSize; pasJobs[i].pUpsampledSpectralBuffer = pUpsampledSpectralBuffer + iStartLine * nXSize * nDataTypeSize; pasJobs[i].pDataBuf = static_cast<GByte*>(pDataBuf) + iStartLine * nXSize * GDALGetDataTypeSizeBytes(eBufDataType); pasJobs[i].nValues = (iNextStartLine - iStartLine) * nXSize; pasJobs[i].nBandValues = static_cast<size_t>(nXSize) * nYSize; pasJobs[i].nMaxValue = nMaxValue; #ifdef DEBUG_TIMING pasJobs[i].ptv = &tv; #endif ahJobData[i] = &(pasJobs[i]); } #ifdef DEBUG_TIMING gettimeofday(&tv, nullptr); #endif poThreadPool->SubmitJobs(PansharpenJobThreadFunc, ahJobData); poThreadPool->WaitCompletion(); } eErr = CE_None; for( int i=0;i<nTasks;i++) { if( pasJobs[i].eErr != CE_None ) eErr = CE_Failure; } } else { eErr = PansharpenChunk( eWorkDataType, eBufDataType, pPanBuffer, pUpsampledSpectralBuffer, pDataBuf, static_cast<size_t>(nXSize) * nYSize, static_cast<size_t>(nXSize) * nYSize, nMaxValue); } if( padfTempBuffer ) { GDALCopyWords64(padfTempBuffer, GDT_Float64, sizeof(double), pDataBufOri, eBufDataTypeOri, GDALGetDataTypeSizeBytes(eBufDataTypeOri), static_cast<size_t>(nXSize)*nYSize*psOptions->nOutPansharpenedBands); VSIFree(padfTempBuffer); } VSIFree(pUpsampledSpectralBuffer); VSIFree(pPanBuffer); return eErr; } /************************************************************************/ /* PansharpenResampleJobThreadFunc() */ /************************************************************************/ // static int acc=0; void GDALPansharpenOperation::PansharpenResampleJobThreadFunc(void* pUserData) { GDALPansharpenResampleJob* psJob = static_cast<GDALPansharpenResampleJob*>(pUserData); #ifdef DEBUG_TIMING struct timeval tv; gettimeofday(&tv, nullptr); const GIntBig launch_time = static_cast<GIntBig>(psJob->ptv->tv_sec) * 1000000 + static_cast<GIntBig>(psJob->ptv->tv_usec); const GIntBig start_job = static_cast<GIntBig>(tv.tv_sec) * 1000000 + static_cast<GIntBig>(tv.tv_usec); #endif #if 0 for(int i=0;i<1000000;i++) acc += i * i; #else GDALRasterIOExtraArg sExtraArg; INIT_RASTERIO_EXTRA_ARG(sExtraArg); sExtraArg.eResampleAlg = psJob->eResampleAlg; sExtraArg.bFloatingPointWindowValidity = TRUE; sExtraArg.dfXOff = psJob->dfXOff; sExtraArg.dfYOff = psJob->dfYOff; sExtraArg.dfXSize = psJob->dfXSize; sExtraArg.dfYSize = psJob->dfYSize; CPL_IGNORE_RET_VAL(psJob->poMEMDS->RasterIO(GF_Read, psJob->nXOff, psJob->nYOff, psJob->nXSize, psJob->nYSize, psJob->pBuffer, psJob->nBufXSize, psJob->nBufYSize, psJob->eDT, psJob->nBandCount, nullptr, 0, 0, psJob->nBandSpace, &sExtraArg)); #endif #ifdef DEBUG_TIMING struct timeval tv_end; gettimeofday(&tv_end, nullptr); const GIntBig end = static_cast<GIntBig>(tv_end.tv_sec) * 1000000 + static_cast<GIntBig>(tv_end.tv_usec); if( start_job - launch_time > 500 ) /*ok*/printf("Resample: Delay before start=" CPL_FRMT_GIB ", completion time=" CPL_FRMT_GIB "\n", start_job - launch_time, end - start_job); #endif } /************************************************************************/ /* PansharpenJobThreadFunc() */ /************************************************************************/ void GDALPansharpenOperation::PansharpenJobThreadFunc(void* pUserData) { GDALPansharpenJob* psJob = static_cast<GDALPansharpenJob*>(pUserData); #ifdef DEBUG_TIMING struct timeval tv; gettimeofday(&tv, nullptr); const GIntBig launch_time = static_cast<GIntBig>(psJob->ptv->tv_sec) * 1000000 + static_cast<GIntBig>(psJob->ptv->tv_usec); const GIntBig start_job = static_cast<GIntBig>(tv.tv_sec) * 1000000 + static_cast<GIntBig>(tv.tv_usec); #endif #if 0 for( int i = 0; i < 1000000; i++ ) acc += i * i; psJob->eErr = CE_None; #else psJob->eErr = psJob->poPansharpenOperation->PansharpenChunk( psJob->eWorkDataType, psJob->eBufDataType, psJob->pPanBuffer, psJob->pUpsampledSpectralBuffer, psJob->pDataBuf, psJob->nValues, psJob->nBandValues, psJob->nMaxValue); #endif #ifdef DEBUG_TIMING struct timeval tv_end; gettimeofday(&tv_end, nullptr); const GIntBig end = static_cast<GIntBig>(tv_end.tv_sec) * 1000000 + static_cast<GIntBig>(tv_end.tv_usec); if( start_job - launch_time > 500 ) /*ok*/printf("Pansharpen: Delay before start=" CPL_FRMT_GIB ", completion time=" CPL_FRMT_GIB "\n", start_job - launch_time, end - start_job); #endif } /************************************************************************/ /* PansharpenChunk() */ /************************************************************************/ CPLErr GDALPansharpenOperation::PansharpenChunk( GDALDataType eWorkDataType, GDALDataType eBufDataType, const void* pPanBuffer, const void* pUpsampledSpectralBuffer, void* pDataBuf, size_t nValues, size_t nBandValues, GUInt32 nMaxValue) const { CPLErr eErr = CE_None; switch( eWorkDataType ) { case GDT_Byte: eErr = WeightedBrovey(static_cast<const GByte*>(pPanBuffer), static_cast<const GByte*>(pUpsampledSpectralBuffer), pDataBuf, eBufDataType, nValues, nBandValues, static_cast<GByte>(nMaxValue)); break; case GDT_UInt16: eErr = WeightedBrovey(static_cast<const GUInt16*>(pPanBuffer), static_cast<const GUInt16*>(pUpsampledSpectralBuffer), pDataBuf, eBufDataType, nValues, nBandValues, static_cast<GUInt16>(nMaxValue)); break; #ifndef LIMIT_TYPES case GDT_Int16: eErr = WeightedBrovey(static_cast<const GInt16*>(pPanBuffer), static_cast<const GInt16*>(pUpsampledSpectralBuffer), pDataBuf, eBufDataType, nValues, nBandValues); break; case GDT_UInt32: eErr = WeightedBrovey(static_cast<const GUInt32*>(pPanBuffer), static_cast<const GUInt32*>(pUpsampledSpectralBuffer), pDataBuf, eBufDataType, nValues, nBandValues, nMaxValue); break; case GDT_Int32: eErr = WeightedBrovey(static_cast<const GInt32*>(pPanBuffer), static_cast<const GInt32*>(pUpsampledSpectralBuffer), pDataBuf, eBufDataType, nValues, nBandValues); break; case GDT_Float32: eErr = WeightedBrovey(static_cast<const float*>(pPanBuffer), static_cast<const float*>(pUpsampledSpectralBuffer), pDataBuf, eBufDataType, nValues, nBandValues); break; #endif case GDT_Float64: eErr = WeightedBrovey(static_cast<const double*>(pPanBuffer), static_cast<const double*>(pUpsampledSpectralBuffer), pDataBuf, eBufDataType, nValues, nBandValues); break; default: CPLError( CE_Failure, CPLE_NotSupported, "eWorkDataType not supported"); eErr = CE_Failure; break; } return eErr; } /************************************************************************/ /* GetOptions() */ /************************************************************************/ /** Return options. * @return options. */ GDALPansharpenOptions* GDALPansharpenOperation::GetOptions() { return psOptions; } /************************************************************************/ /* GDALCreatePansharpenOperation() */ /************************************************************************/ /** Instantiate a pansharpening operation. * * The passed options are validated. * * @param psOptions a pansharpening option structure allocated with * GDALCreatePansharpenOptions(). It is duplicated by this function. * @return a valid pansharpening operation handle, or NULL in case of failure. * * @since GDAL 2.1 */ GDALPansharpenOperationH GDALCreatePansharpenOperation( const GDALPansharpenOptions* psOptions ) { GDALPansharpenOperation* psOperation = new GDALPansharpenOperation(); if( psOperation->Initialize(psOptions) == CE_None ) return reinterpret_cast<GDALPansharpenOperationH>(psOperation); delete psOperation; return nullptr; } /************************************************************************/ /* GDALDestroyPansharpenOperation() */ /************************************************************************/ /** Destroy a pansharpening operation. * * @param hOperation a valid pansharpening operation. * * @since GDAL 2.1 */ void GDALDestroyPansharpenOperation( GDALPansharpenOperationH hOperation ) { delete reinterpret_cast<GDALPansharpenOperation*>(hOperation); } /************************************************************************/ /* GDALPansharpenProcessRegion() */ /************************************************************************/ /** Executes a pansharpening operation on a rectangular region of the * resulting dataset. * * The window is expressed with respect to the dimensions of the panchromatic * band. * * Spectral bands are upsampled and merged with the panchromatic band according * to the select algorithm and options. * * @param hOperation a valid pansharpening operation. * @param nXOff pixel offset. * @param nYOff pixel offset. * @param nXSize width of the pansharpened region to compute. * @param nYSize height of the pansharpened region to compute. * @param pDataBuf output buffer. Must be nXSize * nYSize * * GDALGetDataTypeSizeBytes(eBufDataType) * * psOptions->nOutPansharpenedBands large. * It begins with all values of the first output band, followed * by values of the second output band, etc... * @param eBufDataType data type of the output buffer * * @return CE_None in case of success, CE_Failure in case of failure. * * @since GDAL 2.1 */ CPLErr GDALPansharpenProcessRegion( GDALPansharpenOperationH hOperation, int nXOff, int nYOff, int nXSize, int nYSize, void *pDataBuf, GDALDataType eBufDataType) { return reinterpret_cast<GDALPansharpenOperation*>(hOperation)-> ProcessRegion(nXOff, nYOff, nXSize, nYSize, pDataBuf, eBufDataType); }
3decc24d3e2e368974d77a30129d72b05d4bb091
cccfb7be281ca89f8682c144eac0d5d5559b2deb
/ui/gfx/client_native_pixmap_factory.h
f4508a9802fb172ab068623518f415fa07e63e46
[ "BSD-3-Clause" ]
permissive
SREERAGI18/chromium
172b23d07568a4e3873983bf49b37adc92453dd0
fd8a8914ca0183f0add65ae55f04e287543c7d4a
refs/heads/master
2023-08-27T17:45:48.928019
2021-11-11T22:24:28
2021-11-11T22:24:28
428,659,250
1
0
BSD-3-Clause
2021-11-16T13:08:14
2021-11-16T13:08:14
null
UTF-8
C++
false
false
1,223
h
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_GFX_CLIENT_NATIVE_PIXMAP_FACTORY_H_ #define UI_GFX_CLIENT_NATIVE_PIXMAP_FACTORY_H_ #include <memory> #include <vector> #include "base/files/scoped_file.h" #include "ui/gfx/buffer_types.h" #include "ui/gfx/client_native_pixmap.h" #include "ui/gfx/gfx_export.h" namespace gfx { struct NativePixmapHandle; class Size; // The Ozone interface allows external implementations to hook into Chromium to // provide a client pixmap for non-GPU processes. class GFX_EXPORT ClientNativePixmapFactory { public: virtual ~ClientNativePixmapFactory() {} // Import the native pixmap from |handle| to be used in non-GPU processes. // Implementations must verify that the buffer in |handle| fits an image of // the specified |size| and |format|. Otherwise nullptr is returned. virtual std::unique_ptr<ClientNativePixmap> ImportFromHandle( gfx::NativePixmapHandle handle, const gfx::Size& size, gfx::BufferFormat format, gfx::BufferUsage usage) = 0; }; } // namespace gfx #endif // UI_GFX_CLIENT_NATIVE_PIXMAP_FACTORY_H_
d8429c5676cfbe5cdf3c45637d991f6942df3360
3ef16236cc4566b03328552843b28adde7389612
/chrome/browser/ash/login/quick_unlock/fingerprint_utils.cc
daa3a32265cd80a8abbd67a7af6ebaae6ab50238
[ "BSD-3-Clause" ]
permissive
moteesh-in2tive/chromium
c5962834c8218ba607846ce59d0ba008be00fe2b
e1e495b29e1178a451f65980a6c4ae017c34dc94
refs/heads/main
2023-09-05T00:46:48.898998
2021-11-23T19:52:34
2021-11-23T19:52:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
919
cc
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ash/login/quick_unlock/fingerprint_utils.h" #include "ash/public/cpp/login_types.h" #include "chrome/browser/ash/login/quick_unlock/quick_unlock_factory.h" #include "chrome/browser/ash/login/quick_unlock/quick_unlock_storage.h" #include "components/user_manager/user.h" namespace ash { namespace quick_unlock { FingerprintState GetFingerprintStateForUser(const user_manager::User* user) { QuickUnlockStorage* quick_unlock_storage = QuickUnlockFactory::GetForUser(user); // Quick unlock storage must be available. if (!user->is_logged_in() || !quick_unlock_storage) return FingerprintState::UNAVAILABLE; return quick_unlock_storage->GetFingerprintState(); } } // namespace quick_unlock } // namespace ash
3c55050c0f15883499648230bcdbb652a4bb7ef6
2cb681e118e3f1e4b2b141372ae1c6914599b835
/codeforces/546_C1.cpp
5a559b011fd1a4c4e2f572fdf3bf8047f4644a1f
[]
no_license
jatinarora2702/Competitive-Coding
1ad978a91122c920c839483e46812b5fb70a246e
a77f5d4f1737ca4e408ccf706128ba90ed664286
refs/heads/master
2021-01-11T20:11:34.791960
2020-12-31T00:21:06
2020-12-31T00:21:06
79,060,813
0
0
null
null
null
null
UTF-8
C++
false
false
980
cpp
#include <iostream> #include <stdio.h> #include <deque> #include <list> using namespace std; int fact(int n){ int cnt = 1; for(int i = 2 ; i <= n ; i++) cnt *= i; return cnt; } int main(){ ios::sync_with_stdio(false); int n, k[2], x, x1, x2, cnt; deque < int > l[2]; scanf("%d", &n); for(int i = 0 ; i < 2 ; i++){ scanf("%d", &k[i]); for(int j = 0 ; j < k[i] ; j++){ scanf("%d", &x); l[i].push_back(x); } } cnt = 39916800; // cnt = min(cnt, (int)1e5); // cout << fact(11) << endl; // cout << "cnt=" << cnt << endl; for(int i = 0 ; i < cnt ; i++){ if(l[0].size() == 0){ cout << i << " 2"; return 0; } else if(l[1].size() == 0){ cout << i << " 1"; return 0; } x1 = l[0].front(); x2 = l[1].front(); // cout << x1 << " " << x2 << endl; l[0].pop_front(); l[1].pop_front(); if(x1 > x2){ l[0].push_back(x2); l[0].push_back(x1); } else{ l[1].push_back(x1); l[1].push_back(x2); } } printf("-1"); return 0; }
10881d392f26d394e1e3b2eacab698ffc0c8480d
43619cfb79d5e9160e15cd455f1e2bdc44ebba2c
/railwayManagementSystem .cpp
6eb8a416ea67f83d732dec9b3854fcda79c0ee81
[]
no_license
arushi-kalra/Railway-Management-System
5055330b81d6c823a99b96596040ac9ef3a02c10
dc348b7c295c993638ff13bc161b029bb394df06
refs/heads/main
2023-07-10T10:12:15.269720
2021-08-22T15:19:50
2021-08-22T15:19:50
398,831,424
1
0
null
null
null
null
UTF-8
C++
false
false
17,470
cpp
#include <iostream> #include <queue> #include <map> #include <string.h> #include <conio.h> using namespace std; void gotoxy(int x,int y) { for(int j=0;j<y;j++) { cout<<"\n"; } for(int i=0;i<x;i++) { cout<<" "; } } struct details { string name,phno,email; int adhar,seats; struct details * next; }; struct details * insert_end(struct details * root,string n,string p,string e,int a,int s) { struct details *root1=root; struct details * temp=new details; temp->name=n; temp->phno=p; temp->email=e; temp->adhar=a; temp->seats=s; temp->next=NULL; if(root==NULL) { root=temp; root1=temp; } else { while(root->next!=NULL) { root=root->next; } root->next=temp; } return root1; } void searching(struct details * root,int ad) { while(root!=NULL) { if(root->adhar==ad) { cout<<endl<<"CUSTOMER DETAILS: "<<endl<<"Name : "<<root->name<<" "<<"Phno : "<<root->phno<<" "<<"Email ID : "<<root->email<<" "<<"Adhar : "<<root->adhar<<" "<<"Seats : "<<root->seats<<endl; return; } root=root->next; } } int getseat(struct details * root,int ad) { while(root!=NULL) { if(root->adhar==ad) { return root->seats; } root=root->next; } } struct n2 { string d; string d_time; string arr_time; int seats; string t_name; string des; int pnr; int price; n2*rp; }; struct n1 { string s; n1*dp; n2 *rp; }; struct n2* temp,old_temp; struct n1 * newnode1(queue<string>* source) { struct n1 * temp=new n1; temp->dp=NULL; temp->rp=NULL; temp->s=source->front(); source->pop(); return temp; } struct n2 * newnode2(queue<string>* dest,queue<string>* dep_time ,queue<string>* arrival_time,queue<int>* seats_ava,queue<int>* pnr_no,queue<string>* train_name,queue<string>* desc,queue<int>* price) { struct n2 * temp=new n2; temp->rp=NULL; temp->d=dest->front(); temp->arr_time=arrival_time->front(); temp->d_time=dep_time->front(); temp->t_name=train_name->front(); temp->seats=seats_ava->front(); temp->pnr=pnr_no->front(); temp->des=desc->front(); temp->price=price->front(); dest->pop(); arrival_time->pop(); dep_time->pop(); seats_ava->pop(); pnr_no->pop(); desc->pop(); price->pop(); train_name->pop(); return temp; } struct n1* insert(queue<string>* source,queue<string>* dest,queue<string>* dep_time ,queue<string>* arrival_time,queue<int>* seats_ava,queue<int>* pnr_no,queue<string>* train_name,queue<string>* desc,queue<int>* price) { struct n1 *start1,*start;struct n2*current; for(int i=0;i<5;i++) { if(i==0) { start=newnode1(source); start1=start; } start->rp=newnode2(dest,dep_time,arrival_time,seats_ava,pnr_no,train_name,desc,price); current=start->rp; for(int j=0;j<4;j++) { struct n2* tmp=newnode2(dest,dep_time,arrival_time,seats_ava,pnr_no,train_name,desc,price); current->rp=tmp; current=tmp; } start->dp=newnode1(source); start=start->dp; } return start1; } void search_train(struct n1 * start,int p) { while(start->dp!=NULL) { struct n2 *t=start->rp; cout<<endl; while(t!=NULL) { if(t->pnr==p) { cout<<"SOURCE : "<<start->s<<endl; cout<<"DESTINATION : "<<t->d<<endl; cout<<"TRAIN NAME : "<<t->t_name<<endl; cout<<"DEPARTURE TIME : "<<t->d_time<<endl; cout<<"ARRIVAL TIME : "<<t->arr_time<<endl; cout<<"SEATS AVAILABLE : "<<t->seats<<endl; cout<<"PNR NUMBER : "<<t->pnr<<endl; cout<<"TRAIN DESCRIPTION: "<<t->des<<endl; cout<<"PRICE : "<<t->price<<endl; cout<<"\n"; } t=t->rp; } cout<<endl; cout<<"\n"; start=start->dp; } } update_lol(struct n1 * start,int p,int seat) { while(start->dp!=NULL) { struct n2 *t=start->rp; cout<<endl; while(t!=NULL) { if(t->pnr==p) { t->seats=t->seats-seat; } t=t->rp; } cout<<endl; cout<<"\n"; start=start->dp; } } update_lol2(struct n1 * start,int p,int seat) { while(start->dp!=NULL) { struct n2 *t=start->rp; cout<<endl; while(t!=NULL) { if(t->pnr==p) { t->seats=t->seats+seat; } t=t->rp; } cout<<endl; cout<<"\n"; start=start->dp; } } struct details *delete_details(struct details *root,int ad) { struct details *root1=root; struct details *ptr=root; if(root==root1 && root->adhar==ad) { root1=root->next; } else { while(root!=NULL) { if(root->adhar==ad) { ptr->next=root->next; break; } else { ptr=root; root=root->next; } } } return root1; }; int give_price(struct n1 * start,int p) { while(start->dp!=NULL) { struct n2 *t=start->rp; cout<<endl; while(t!=NULL) { if(t->pnr==p) { return t->price; } t=t->rp; } start=start->dp; } cout<<endl<<"There's no train with the entered pnr number"<<endl; } int main() { map <int , int> m; struct details * root=NULL; string name,email,phno; int choice,p,c,pnr,adhar,seat,s,d; queue<string>source; queue<string>dest; queue<string>dep_time; queue<string>arrival_time; queue<int>seats_ava; queue<int>pnr_no; queue<string>train_name; queue<string>desc; queue<int>price; source.push("DELHI"); source.push("LUCKNOW"); source.push("MUMBAI"); source.push("KOLKATA"); source.push("JAIPUR"); dest.push("LUCKNOW"); dest.push("CHANDIGARH"); dest.push("AHMEDABAD"); dest.push("THIRUVANANTHPURAM"); dest.push("MUMBAI"); dest.push("DELHI"); dest.push("CHENNAI"); dest.push("AGRA"); dest.push("VARANSI"); dest.push("GANDHINAGAR"); dest.push("DELHI"); dest.push("PUNE"); dest.push("CHENNAI"); dest.push("HYDERABAD"); dest.push("KOLKATA"); dest.push("JAIPUR"); dest.push("SURAT"); dest.push("CHANDIGARH"); dest.push("KOCHI"); dest.push("INDORE"); dest.push("DELHI"); dest.push("PUNE"); dest.push("AHMEDABAD"); dest.push("LUCKNOW"); dest.push("KOLKATA"); dep_time.push("6:50:00"); dep_time.push("19:40:00"); dep_time.push("21:00:00"); dep_time.push("5:30:00"); dep_time.push("9:20:00"); dep_time.push("8:00:00"); dep_time.push("18:30:00"); dep_time.push("15:30:00"); dep_time.push("4:10:00"); dep_time.push("5:50:00"); dep_time.push("7:15:00"); dep_time.push("20:50:00"); dep_time.push("22:40:00"); dep_time.push("15:00:00"); dep_time.push("19:25:00"); dep_time.push("00:20:00"); dep_time.push("23:50:00"); dep_time.push("6:00:00"); dep_time.push("14:05:00"); dep_time.push("18:55:00"); dep_time.push("14:50:00"); dep_time.push("13:00:00"); dep_time.push("12:00:00"); dep_time.push("11:50:00"); dep_time.push("10:50:00"); arrival_time.push("6:00:00"); arrival_time.push("14:05:00"); arrival_time.push("18:55:00"); arrival_time.push("14:50:00"); arrival_time.push("13:00:00"); arrival_time.push("6:00:00"); arrival_time.push("14:05:00"); arrival_time.push("18:55:00"); arrival_time.push("14:50:00"); arrival_time.push("13:00:00"); arrival_time.push("4:10:00"); arrival_time.push("5:50:00"); arrival_time.push("7:15:00"); arrival_time.push("20:50:00"); arrival_time.push("22:40:00"); arrival_time.push("22:40:00"); arrival_time.push("15:00:00"); arrival_time.push("19:25:00"); arrival_time.push("00:20:00"); arrival_time.push("23:50:00"); arrival_time.push("6:50:00"); arrival_time.push("19:40:00"); arrival_time.push("21:00:00"); arrival_time.push("5:30:00"); arrival_time.push("9:20:00"); seats_ava.push(2000); seats_ava.push(5000); seats_ava.push(6000); seats_ava.push(8000); seats_ava.push(9000); seats_ava.push(2000); seats_ava.push(3000); seats_ava.push(4000); seats_ava.push(10000); seats_ava.push(5500); seats_ava.push(6300); seats_ava.push(4800); seats_ava.push(7700); seats_ava.push(5000); seats_ava.push(6500); seats_ava.push(5400); seats_ava.push(3500); seats_ava.push(5200); seats_ava.push(7000); seats_ava.push(2500); seats_ava.push(11000); seats_ava.push(8500); seats_ava.push(9400); seats_ava.push(2600); seats_ava.push(5900); pnr_no.push(145); pnr_no.push(143); pnr_no.push(152); pnr_no.push(195); pnr_no.push(123); pnr_no.push(133); pnr_no.push(197); pnr_no.push(167); pnr_no.push(149); pnr_no.push(140); pnr_no.push(142); pnr_no.push(150); pnr_no.push(135); pnr_no.push(245); pnr_no.push(235); pnr_no.push(240); pnr_no.push(285); pnr_no.push(234); pnr_no.push(126); pnr_no.push(183); pnr_no.push(286); pnr_no.push(254); pnr_no.push(110); pnr_no.push(134); pnr_no.push(170); desc.push("ac"); desc.push("non ac"); desc.push("ac"); desc.push("ac"); desc.push("non ac"); desc.push("non ac"); desc.push("ac"); desc.push("ac"); desc.push("ac"); desc.push("non ac"); desc.push("non ac"); desc.push("non ac"); desc.push("ac"); desc.push("non ac"); desc.push("ac"); desc.push("ac"); desc.push("ac"); desc.push("ac"); desc.push("non ac"); desc.push("ac"); desc.push("non ac"); desc.push("ac"); desc.push("non ac"); desc.push("ac"); desc.push("ac"); train_name.push("AC express"); train_name.push("Chandigarh express"); train_name.push("Gujrat Sampark Kranti express"); train_name.push("Kerela Sampark Kranti express"); train_name.push("Pune Duronto express"); train_name.push("Chennai central express"); train_name.push("Agra Duronto express"); train_name.push("Upsana express"); train_name.push("Marudhar express"); train_name.push("Paschim express"); train_name.push("Pragati express"); train_name.push("Chennai express"); train_name.push("Devagiri express"); train_name.push("Gitanjali express"); train_name.push("Pratap express"); train_name.push("HWH ADI express"); train_name.push("HWH DLI KLK express"); train_name.push("Gurudev express"); train_name.push("Shipra express"); train_name.push("Ajmer Shatabdi express"); train_name.push("Ashram express"); train_name.push("Wainganga express"); train_name.push("Narudhar express"); train_name.push("Rajdhani express"); train_name.push("Jaipur to Agra Shatabdi express"); price.push(1000); price.push(2000); price.push(2500); price.push(3000); price.push(1500); price.push(900); price.push(1000); price.push(2000); price.push(1500); price.push(2500); price.push(780); price.push(1400); price.push(2100); price.push(890); price.push(1000); price.push(2000); price.push(2400); price.push(1100); price.push(1700); price.push(2050); price.push(1080); price.push(1110); price.push(2000); price.push(1020); price.push(800); struct n1* start=insert(&source,&dest,&dep_time,&arrival_time,&seats_ava,&pnr_no,&train_name,&desc,&price); struct n1* start1=start; do { START: gotoxy(15,3); cout<<"WELCOME TO THE"<<"\n"; gotoxy(15,3); cout<<"INDIAN RAILWAY BOOKING PORTAL"<<endl; gotoxy(15,3); cout<<"1. TRAIN DETAILS"<<endl; gotoxy(15,3); cout<<"2. BOOK THE TRAIN"<<endl; gotoxy(15,3); cout<<"3. SEARCH THE TRAIN"<<endl; gotoxy(15,3); cout<<"4. CUSTOMER DETAILS"<<endl; gotoxy(15,3); cout<<"5. BOOKING CANCELLATION"<<endl; cin>>choice; switch(choice) { case 1: while(start->dp!=NULL) { struct n2 *t=start->rp; cout<<"SOURCE : "<<start->s<<endl; cout<<endl; while(t!=NULL) { cout<<"DESTINATION : "<<t->d<<endl; cout<<"TRAIN NAME : "<<t->t_name<<endl; cout<<"DEPARTURE TIME : "<<t->d_time<<endl; cout<<"ARRIVAL TIME : "<<t->arr_time<<endl; cout<<"SEATS AVAILABLE : "<<t->seats<<endl; cout<<"PNR NUMBER : "<<t->pnr<<endl; cout<<"TRAIN DESCRIPTION: "<<t->des<<endl; cout<<"PRICE : "<<t->price<<endl; cout<<"\n"; t=t->rp; } cout<<"********************************************************************************************"; cout<<endl; cout<<"\n"; start=start->dp; } goto START; break; case 2: gotoxy(15,3); cout<<"Enter your Name,Adhar number,Email id,Phone number and PNR number of the train you wish to BOOK."<<endl; gotoxy(15,3); cout<<"Also provide the number of seats you wish to book"<<endl; cin>>name>>adhar>>email>>phno>>pnr>>seat; root=insert_end(root,name,phno,email,adhar,seat); m.insert(pair <int , int> (adhar, pnr)); update_lol(start,pnr,seat); cout<<"BOOKING SUCCESSFUL!"<<endl; d=give_price(start1,pnr); s=d*seat; cout<<"You have to pay Rs. "<<s<<" in total "; goto START; break; case 3: gotoxy(15,3); cout<<"Enter the PNR number of the train you want to SEARCH"<<endl; cin>>p; search_train(start1,p); goto START; break; case 4: { gotoxy(15,3); cout<<"Enter the Adhar number of the customer you wish to search about."<<endl; cin>>adhar; map<int , int>::iterator it ; it = m.find(adhar); if(it == m.end()) cout << "No customer with this Adhar number is present." <<endl; else { pnr = it->second ; searching(root,adhar); search_train(start1,pnr); } goto START; break; } case 5: { gotoxy(15,3); cout<<"Enter your Adhar number and the PNR number."<<endl; cin>>adhar>>pnr; int s = getseat(root,adhar); update_lol2(start,pnr,s); root=delete_details(root,adhar); map<int , int>::iterator i ; if(s!=0) { i=m.find(adhar); m.erase(i); } goto START; break; } default: gotoxy(15,3); cout<<"Enter a valid choice."<<endl; goto START; break; } }while(choice!=0); return 0; }
96909a7f25cf61e46cdaa8096dd3600a642c5afd
64e4fabf9b43b6b02b14b9df7e1751732b30ad38
/src/chromium/gen/gen_combined/third_party/blink/renderer/bindings/modules/v8/v8_xr.h
e95effa0e211b1ed9eb77531e4ae5db845c61dd0
[ "BSD-3-Clause" ]
permissive
ivan-kits/skia-opengl-emscripten
8a5ee0eab0214c84df3cd7eef37c8ba54acb045e
79573e1ee794061bdcfd88cacdb75243eff5f6f0
refs/heads/master
2023-02-03T16:39:20.556706
2020-12-25T14:00:49
2020-12-25T14:00:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,422
h
// Copyright 2014 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. // This file has been auto-generated from the Jinja2 template // third_party/blink/renderer/bindings/templates/interface.h.tmpl // by the script code_generator_v8.py. // DO NOT MODIFY! // clang-format off #ifndef THIRD_PARTY_BLINK_RENDERER_BINDINGS_MODULES_V8_V8_XR_H_ #define THIRD_PARTY_BLINK_RENDERER_BINDINGS_MODULES_V8_V8_XR_H_ #include "third_party/blink/renderer/bindings/core/v8/generated_code_helper.h" #include "third_party/blink/renderer/bindings/core/v8/native_value_traits.h" #include "third_party/blink/renderer/bindings/core/v8/to_v8_for_core.h" #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h" #include "third_party/blink/renderer/bindings/core/v8/v8_event_target.h" #include "third_party/blink/renderer/modules/modules_export.h" #include "third_party/blink/renderer/modules/xr/xr.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" #include "third_party/blink/renderer/platform/bindings/v8_dom_wrapper.h" #include "third_party/blink/renderer/platform/bindings/wrapper_type_info.h" #include "third_party/blink/renderer/platform/heap/handle.h" namespace blink { MODULES_EXPORT extern const WrapperTypeInfo v8_xr_wrapper_type_info; class V8XR { STATIC_ONLY(V8XR); public: MODULES_EXPORT static bool HasInstance(v8::Local<v8::Value>, v8::Isolate*); static v8::Local<v8::Object> FindInstanceInPrototypeChain(v8::Local<v8::Value>, v8::Isolate*); MODULES_EXPORT static v8::Local<v8::FunctionTemplate> DomTemplate(v8::Isolate*, const DOMWrapperWorld&); static XR* ToImpl(v8::Local<v8::Object> object) { return ToScriptWrappable(object)->ToImpl<XR>(); } MODULES_EXPORT static XR* ToImplWithTypeCheck(v8::Isolate*, v8::Local<v8::Value>); MODULES_EXPORT static constexpr const WrapperTypeInfo* GetWrapperTypeInfo() { return &v8_xr_wrapper_type_info; } static constexpr int kInternalFieldCount = kV8DefaultWrapperInternalFieldCount; MODULES_EXPORT static void InstallConditionalFeatures( v8::Local<v8::Context>, const DOMWrapperWorld&, v8::Local<v8::Object> instance_object, v8::Local<v8::Object> prototype_object, v8::Local<v8::Function> interface_object, v8::Local<v8::FunctionTemplate> interface_template); // Callback functions MODULES_EXPORT static void OndevicechangeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>&); MODULES_EXPORT static void OndevicechangeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>&); MODULES_EXPORT static void SupportsSessionMethodCallback(const v8::FunctionCallbackInfo<v8::Value>&); MODULES_EXPORT static void RequestSessionMethodCallback(const v8::FunctionCallbackInfo<v8::Value>&); static void InstallRuntimeEnabledFeaturesOnTemplate( v8::Isolate*, const DOMWrapperWorld&, v8::Local<v8::FunctionTemplate> interface_template); }; template <> struct NativeValueTraits<XR> : public NativeValueTraitsBase<XR> { MODULES_EXPORT static XR* NativeValue(v8::Isolate*, v8::Local<v8::Value>, ExceptionState&); MODULES_EXPORT static XR* NullValue() { return nullptr; } }; template <> struct V8TypeOf<XR> { typedef V8XR Type; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_BINDINGS_MODULES_V8_V8_XR_H_
112dbce61b58baed8472060f39fe0542b941f1fd
243dd70b2592a7f2e75bc06598f61d400249627d
/kernel/src/glue/v4-mips64/timer.h
a8304c1669d5160948d1c27f49a47fff8b7664cb
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
vmlemon/Orion
4d1445f750c8450f9c5ac1979eb846dbaed178f5
61f894826a802c24076c22c1c9439bc7382a276a
refs/heads/master
2020-07-06T08:20:32.942117
2020-01-25T19:08:09
2020-01-25T19:08:09
202,951,911
6
0
null
2019-10-24T00:37:40
2019-08-18T02:40:09
C
UTF-8
C++
false
false
2,062
h
/********************************************************************* * * Copyright (C) 2002-2003, University of New South Wales * * File path: glue/v4-mips64/timer.h * Description: MIPS64 timer handler * * 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 AUTHOR 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 AUTHOR 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. * * $Id: timer.h,v 1.5 2003/09/24 19:04:50 skoglund Exp $ * ********************************************************************/ #ifndef __GLUE__V4_MIPS64__TIMER_H__ #define __GLUE__V4_MIPS64__TIMER_H__ #include <timer.h> class timer_t : public generic_periodic_timer_t { public: void init_global(); void init_cpu(); u32_t compare; }; INLINE timer_t * get_timer() { extern timer_t timer; return &timer; } #endif /* __GLUE__V4_MIPS64__TIMER_H__ */
ebc808f70a3a5acf989784c847485e100e676e24
c129b0332535a99a960c42779478a6c6fd29059a
/C++数据结构笔记/代码存放/10/exception.h
abe2c4a497fdd68750e2363e0c1ac3990da3eeb6
[]
no_license
USST-member/mynote
168e44c9e29e984e83ef8de84916e37b040d3b17
446e74bba224a485e61bd45fc357ee49064da079
refs/heads/master
2021-07-13T12:49:07.622286
2021-02-28T07:31:20
2021-02-28T07:31:20
231,055,142
0
0
null
null
null
null
UTF-8
C++
false
false
3,777
h
#ifndef EXCEPTIOM_H #define EXCEPTIOM_H namespace dong { //抛出异常宏函数 #define THROW_EXCEPTION(e,m) (throw e(m,__FILE,__LINE__))//抛出异常 //父类 抽象层 class Exception { protected: char *m_message; char *m_location; void init(const char *message,const char *file,int line);//相当于二级构造 public: Exception(const char * message); Exception(const char * file,int line); Exception(const char * message,const char * file,int line); Exception(const Exception& e); Exception& operator =(const Exception& e); virtual const char *message() const; virtual const char *location() const; virtual ~Exception()=0; }; //子类 计算异常 class ArithmeticException : public Exception { public: ArithmeticException():Exception(nullptr){} ArithmeticException(const char * message):Exception(message){} ArithmeticException(const char * file,int line):Exception(file ,line){} ArithmeticException(const char * message,const char * file,int line):Exception(message,file ,line){} ArithmeticException(const ArithmeticException& e):Exception(e){} ArithmeticException& operator=(const ArithmeticException& e) { Exception::operator=(e); return *this; } }; //子类 空指针异常 class NullPointerException : public Exception { public: NullPointerException():Exception(nullptr){} NullPointerException(const char * message):Exception(message){} NullPointerException(const char * file,int line):Exception(file ,line){} NullPointerException(const char * message,const char * file,int line):Exception(message,file ,line){} NullPointerException(const NullPointerException& e):Exception(e){} NullPointerException& operator=(const NullPointerException& e) { Exception::operator=(e); return *this; } }; //子类 越界异常 class IndexOutofBoubdsException : public Exception { public: IndexOutofBoubdsException():Exception(nullptr){} IndexOutofBoubdsException(const char * message):Exception(message){} IndexOutofBoubdsException(const char * file,int line):Exception(file ,line){} IndexOutofBoubdsException(const char * message,const char * file,int line):Exception(message,file ,line){} IndexOutofBoubdsException(const IndexOutofBoubdsException& e):Exception(e){} IndexOutofBoubdsException& operator=(const IndexOutofBoubdsException& e) { Exception::operator=(e); return *this; } }; //子类 内存不足异常 class NoenoughmemoryException : public Exception { public: NoenoughmemoryException():Exception(nullptr){} NoenoughmemoryException(const char * message):Exception(message){} NoenoughmemoryException(const char * file,int line):Exception(file ,line){} NoenoughmemoryException(const char * message,const char * file,int line):Exception(message,file ,line){} NoenoughmemoryException(const NoenoughmemoryException& e):Exception(e){} NoenoughmemoryException& operator=(const NoenoughmemoryException& e) { Exception::operator=(e); return *this; } }; //子类 参数错误异常 class InvalidparameterException : public Exception { public: InvalidparameterException():Exception(nullptr){} InvalidparameterException(const char * message):Exception(message){} InvalidparameterException(const char * file,int line):Exception(file ,line){} InvalidparameterException(const char * message,const char * file,int line):Exception(message,file ,line){} InvalidparameterException(const InvalidparameterException& e):Exception(e){} InvalidparameterException& operator=(const InvalidparameterException& e) { Exception::operator=(e); return *this; } }; } #endif // EXCEPTIOM_H
37a8acbc5f17ab8a8b1f0099ea178e4d8b3fc5a7
ee8f70e022c396d2bae771a4f833f2648d45c9b2
/include/Aurora/Dispatch/DoubleDispatcher.hpp
fa5d04eb72c76e389b7e974df3c29b8cf924e160
[ "Zlib" ]
permissive
Bromeon/Aurora
428267b0b59a1ba8ce206e92dfc36bc8b9777ded
906e90bc272a0b13b3c9435b28f374d52d2f455c
refs/heads/master
2022-05-01T09:15:47.959298
2022-04-16T10:08:18
2022-04-16T10:08:18
3,751,402
33
4
null
2014-04-26T09:28:11
2012-03-17T23:00:15
C++
UTF-8
C++
false
false
13,048
hpp
///////////////////////////////////////////////////////////////////////////////// // // Aurora C++ Library // Copyright (c) 2012-2022 Jan Haller // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // ///////////////////////////////////////////////////////////////////////////////// /// @file /// @brief Class template aurora::DoubleDispatcher #ifndef AURORA_DOUBLEDISPATCHER_HPP #define AURORA_DOUBLEDISPATCHER_HPP #include <Aurora/Dispatch/DispatchTraits.hpp> #include <Aurora/Tools/NonCopyable.hpp> #include <Aurora/Tools/Exceptions.hpp> #include <Aurora/Tools/Hash.hpp> #include <Aurora/Meta/Templates.hpp> #include <Aurora/Config.hpp> #include <unordered_map> #include <functional> #include <algorithm> #include <cassert> namespace aurora { /// @addtogroup Dispatch /// @{ /// @brief Class that is able to perform dynamic dispatch on multiple functions with two parameters. /// @details Sometimes you encounter the situation where you need to implement polymorphic behavior to dispatch /// dynamically on more than one type. Like overloading functions with two parameters at compile time, this class /// allows you to perform a dispatch on two arguments at runtime. At invocation time, all you need is the static /// type of the base class, the %DoubleDispatcher figures out which dynamic types match which function. /// @tparam Signature Function signature <b>R(B, B)</b>or <b>R(B, B, U)</b>, with the following types: /// * <b>B</b>: Reference or pointer to polymorphic base class. This is the base class of every dispatched function's /// parameter type. When it is a pointer, the arguments of the dispatched functions shall be pointers too (the /// same applies to references). /// the dispatched functions shall have arguments of type pointer or reference to const, too. /// * <b>R</b>: Return type of the dispatched functions. /// * <b>U</b>: Any parameter type that can be used to forward user arguments to the functions /// @tparam Traits Traits class to customize the usage of the dispatcher. To define your own traits, you can (but don't have to) /// inherit the class @ref aurora::DispatchTraits<K>, where K is your key. It predefines most members for convenience. /// In general, the @c Traits class must contain the following members: /// @code /// struct Traits /// { /// // The type that is used to differentiate objects. For RTTI class hierarchies, std::type_index is a good choice /// // -- but you're free to choose anything, such as an enum or a string. The requirements are that Key can be used /// // as a key in std::unordered_map, i.e. it must support a std::hash<Key> specialization and operator==. /// typedef K Key; /// /// // A function that returns the corresponding key (such as std::type_index) from a type identifier (such as aurora::Type<T>). /// // The type identifier is passed to bind() and can contain static type information, while the key is used by the map /// // storing the registered functions. Often, key and type identifier are the same. /// static Key keyFromId(Id id); /// /// // Given a function argument base, this static function extracts the key from it. B corresponds to the template parameter /// // specified at SingleDispatcher, that is, it is a reference or pointer. /// static Key keyFromBase(B base); /// /// // trampoline2() takes a function that is passed to DoubleDispatcher::bind() and modifies it in order to fit the common /// // R(B, B) signature. It therefore acts as a wrapper for user-defined functions which can link different signatures together. /// // For example, this is the place to insert downcasts. /// // The first two template parameters Id1 and Id2 are required, as they will be explicitly specified when trampoline2() is called. /// template <typename Id1, typename Id2, typename Fn> /// static std::function<R(B, B)> trampoline2(Fn f); /// /// // Optional function that returns a string representation of key for debugging. /// static const char* name(Key k); /// }; /// @endcode /// /// Usage example: /// @code /// // Example class hierarchy /// class Base { public: virtual ~Base() {} }; /// class Derived1 : public Base {}; /// class Derived2 : public Base {}; /// /// // Free functions for the derived types /// void func11(Derived1* lhs, Derived1* rhs); /// void func12(Derived1* lhs, Derived2* rhs); /// void func22(Derived2* lhs, Derived2* rhs); /// /// // Create dispatcher and register functions /// aurora::DoubleDispatcher<void(Base*,Base*)> dispatcher; /// dispatcher.bind(aurora::Type<Derived1>(), aurora::Type<Derived1>(), &func11); /// dispatcher.bind(aurora::Type<Derived1>(), aurora::Type<Derived2>(), &func12); /// dispatcher.bind(aurora::Type<Derived2>(), aurora::Type<Derived2>(), &func22); /// /// // Invoke functions on base class pointer /// Base* ptr = new Derived1; /// dispatcher.call(ptr, ptr); // Invokes void func11(Derived1* lhs, Derived1* rhs); /// delete ptr; /// @endcode template <typename Signature, class Traits = RttiDispatchTraits<Signature, 2>> class DoubleDispatcher : private NonCopyable { // --------------------------------------------------------------------------------------------------------------------------- // Public types public: /// @brief Function return type /// typedef typename FunctionResult<Signature>::Type Result; /// @brief Function parameter type denoting the object used for the dispatch /// typedef typename FunctionParam<Signature, 0>::Type Parameter; /// @brief Addition parameter for user data, only useful if @c Signature contains more than 2 parameters /// typedef typename FunctionParam<Signature, 2>::Type UserData; // --------------------------------------------------------------------------------------------------------------------------- // Static assertions // Make sure that B is either T* or T& static_assert(std::is_pointer<Parameter>::value || std::is_lvalue_reference<Parameter>::value, "Function parameter must be a pointer or reference."); // For signature R(X, Y), ensure that X == Y static_assert(std::is_same<typename FunctionParam<Signature, 0>::Type, typename FunctionParam<Signature, 1>::Type>::value, "The two function parameters must have the same type."); // --------------------------------------------------------------------------------------------------------------------------- // Public member functions public: /// @brief Constructor /// @param symmetric Is true if the calls <b>fn(a,b)</b> and <b>fn(b,a)</b> are equivalent and it's enough /// to register one of both variants. Otherwise, both calls have to be registered separately and are resolved /// to different functions. explicit DoubleDispatcher(bool symmetric = true); /// @brief Move constructor DoubleDispatcher(DoubleDispatcher&& source); /// @brief Move assignment operator DoubleDispatcher& operator= (DoubleDispatcher&& source); /// @brief Destructor ~DoubleDispatcher(); /// @brief Registers a function bound to a specific key. /// @tparam Id1,Id2 %Types that identify the argument types. By default, these are aurora::Type<D>, where D is a /// derived class. Can be deduced from the argument. /// @tparam Fn %Type of the function. Can be deduced from the argument. /// @param identifier1,identifier2 Values that identify the object. The key, which is mapped to the function, is computed /// from each identifier through Traits::keyFromId(identifier). /// @param function Function to register and associate with the given identifier. Usually, the function has the signature /// <tt>Result(Parameter, Parameter)</tt>, but it's possible to deviate from it (e.g. using derived classes), see also the /// note about trampolines in the Traits classes. In case you specified a third parameter for the @c Signature template /// parameter, the function should have the signature <tt>Result(Parameter, Parameter, UserData)</tt>. template <typename Id1, typename Id2, typename Fn> void bind(const Id1& identifier1, const Id2& identifier2, Fn function); /// @brief Dispatches the key of @c arg1 and @c arg2 and invokes the corresponding function. /// @details <tt>Traits::keyFromBase(arg)</tt> is invoked to determine the key of each passed argument. The function bound to /// the combination of both keys is then looked up in the map and invoked. If no match is found and a fallback function has /// been registered using fallback(), then the fallback function will be invoked. /// @n@n When the dispatcher is configured in symmetric mode (see constructor), then the arguments are forwarded to the /// correct parameters in the registered functions, even if the order is different. When necessary, they are swapped. /// In other words, symmetric dispatchers don't care about the order of the arguments at all. /// @param arg1,arg2 Function arguments as references or pointers. /// @return The return value of the dispatched function, if any. /// @throw FunctionCallException when no corresponding function is found and no fallback has been registered. Result call(Parameter arg1, Parameter arg2) const; /// @brief Invokes the function depending on @c arg1 and @c arg2 and passes a user-defined argument @c data /// @details <tt>Traits::keyFromBase(arg)</tt> is invoked to determine the key of the passed argument. The function bound to /// that key is then looked up in the map and invoked. If no match is found and a fallback function has been registered /// using fallback(), then the fallback function will be invoked. /// @n@n When the dispatcher is configured in symmetric mode (see constructor), then the arguments are forwarded to the /// correct parameters in the registered functions, even if the order is different. When necessary, they are swapped. /// In other words, symmetric dispatchers don't care about the order of the first two arguments. /// @n@n This method is only enabled if the @c Signature template parameter contains 3 parameters. /// @param arg1,arg2 Function arguments as references or pointers. /// @param data An additional user argument that is forwarded to the function. /// @return The return value of the dispatched function, if any. /// @throw FunctionCallException when no corresponding function is found and no fallback has been registered. Result call(Parameter arg1, Parameter arg2, UserData data) const; /// @brief Registers a fallback function. /// @details The passed function will be invoked when call() doesn't find a registered function. It can be used when /// not finding a match does not represent an exceptional situation, but a common case. /// @n@n If you want to perform no action, you can pass aurora::NoOp<R, 2>(). /// @param function Function according to the specified signature. void fallback(std::function<Signature> function); // --------------------------------------------------------------------------------------------------------------------------- // Private types private: typedef typename Traits::Key SingleKey; typedef std::function<Signature> BaseFunction; struct Key { Key(const SingleKey& key1, const SingleKey& key2, bool swapped); bool operator== (const Key& rhs) const; std::pair<SingleKey, SingleKey> keyPair; bool swapped; }; struct Hasher { std::size_t operator() (const Key& k) const; }; typedef std::unordered_map<Key, BaseFunction, Hasher> FnMap; // --------------------------------------------------------------------------------------------------------------------------- // Private member functions private: // Makes sure that the keys are sorted in case we use symmetric argument dispatching. Key makeKey(SingleKey key1, SingleKey key2) const; // --------------------------------------------------------------------------------------------------------------------------- // Private variables private: FnMap mMap; BaseFunction mFallback; bool mSymmetric; }; /// @} } // namespace aurora #include <Aurora/Dispatch/Detail/DoubleDispatcher.inl> #endif // AURORA_DOUBLEDISPATCHER_HPP
859ea754c0b4fd8999d745047994a08a3d80cdd9
e682a062c4183bc3fd1aa70518a9033424ecab86
/02_动态规划/02_BagProblem.cpp
9cee40b1e13412da682baafc4f058eb6eef5b62d
[]
no_license
happier233/ACM-Code
a5f6b88a45a957e03042abb1d11ef207fed59774
dda4432c2c15461d74077b599db54b7dff3c7e0d
refs/heads/master
2020-04-27T19:55:30.560331
2020-02-16T16:16:56
2020-02-16T16:16:56
174,639,328
5
1
null
null
null
null
UTF-8
C++
false
false
963
cpp
#define N 1000 // val=价值 wei=重量 num=数量 int val[N], wei[N], num[N], f[N]; // n=种类个数 m=背包最大值 // 01背包 void dp1(int n, int m) { for (int i = 0; i < n; i++) { for (int j = m; j >= wei[i]; j--) f[j] = max(f[j], f[j - wei[i]] + val[i]); } } // 完全背包 void dp2(int n, int m) { //初始化看要求 for (int i = 0; i <= m; i++) { f[i] = INF; } f[0] = 0; //若要求恰好装满背包,那在初始化时除了f[0]=0其它f[1..V]均=-∞ //若没要求背包装满,只希望价格大,初始化时应将f[0..V]=0) for (int i = 0; i < n; i++) for (int j = wei[i]; j <= m; j++) f[j] = max(f[j], f[j - wei[i]] + val[i]); } // 多重背包 void dp3(int n, int m) { for (int i = 0; i < n; i++) for (int k = 0; k < num[i]; k++) for (int j = m; j >= wei[i]; j--) f[j] = max(f[j], f[j - wei[i]] + val[i]); }
b95bdcb124b9c0397034b6abc5da26f031a334b1
f69ad70bf1a8857301980f986e1b4c31c94d731e
/TP3/Flame.cpp
ea834af02701a25c1d9e3c12490aa2d1312a6c1e
[]
no_license
deboxta/IMAGWZIT
3fd5d3df3622849dd1106d96659125f4b2ca818e
a24764a00f77bcb31910b4d2136f729c4fae08e7
refs/heads/master
2023-02-01T12:56:42.447719
2020-12-16T07:37:19
2020-12-16T07:37:19
264,275,370
0
0
null
null
null
null
UTF-8
C++
false
false
225
cpp
#include "Flame.h" #include "WeaponType.h" namespace TP3Prog { Flame::Flame() : Projectile(20, 15,false, 1) { } Flame::~Flame() { } void Flame::loadTexture() { setTexture(projectileTextures[FLAMETHROWER]); } }
285bc404178bdbfcd685fa46947a801b03cbacd1
a609c8ae28ff013f54a1a765b9c2f4eb216480eb
/Source/FPSGame/Public/FPSObjectiveActor.h
1caebca16159909ab3c9916f548183a0436c06f4
[]
no_license
nerliss/StealthGame
e630b6231bd35a8882f1c21e6f32f6cc1689a14c
f6d33001fce11bcb1edea70f4ed07e88f19b825f
refs/heads/main
2023-03-29T14:43:29.247047
2021-04-14T08:06:56
2021-04-14T08:06:56
351,058,884
0
0
null
null
null
null
UTF-8
C++
false
false
841
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "FPSObjectiveActor.generated.h" class USphereComponent; UCLASS() class FPSGAME_API AFPSObjectiveActor : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties AFPSObjectiveActor(); protected: UPROPERTY(VisibleAnywhere, Category = "Components") UStaticMeshComponent* MeshComp; UPROPERTY(VisibleAnywhere, Category = "Components") USphereComponent* SphereComp; UPROPERTY(EditDefaultsOnly, Category = "Effects") UParticleSystem* PickupFX; // Called when the game starts or when spawned virtual void BeginPlay() override; void PlayEffects(); public: virtual void NotifyActorBeginOverlap(AActor* OtherActor) override; };
662e840cefe03d3c0813a2392e67a463dc47cc0c
03f037d0f6371856ede958f0c9d02771d5402baf
/graphics/VTK-7.0.0/Filters/Core/vtkMergeFilter.cxx
a3f689a38bf8e95373cb138faad18fe7a72df2d7
[ "BSD-3-Clause" ]
permissive
hlzz/dotfiles
b22dc2dc5a9086353ed6dfeee884f7f0a9ddb1eb
0591f71230c919c827ba569099eb3b75897e163e
refs/heads/master
2021-01-10T10:06:31.018179
2016-09-27T08:13:18
2016-09-27T08:13:18
55,040,954
4
0
null
null
null
null
UTF-8
C++
false
false
15,176
cxx
/*========================================================================= Program: Visualization Toolkit Module: vtkMergeFilter.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkMergeFilter.h" #include "vtkCellData.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPolyData.h" #include "vtkRectilinearGrid.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkStructuredGrid.h" #include "vtkStructuredPoints.h" #include "vtkUnstructuredGrid.h" vtkStandardNewMacro(vtkMergeFilter); class vtkFieldNode { public: vtkFieldNode(const char* name, vtkDataSet* ptr=0) { int length = static_cast<int>(strlen(name)); if (length > 0) { this->Name = new char[length+1]; strcpy(this->Name, name); } else { this->Name = 0; } this->Ptr = ptr; this->Next = 0; } ~vtkFieldNode() { delete[] this->Name; } const char* GetName() { return Name; } vtkDataSet* Ptr; vtkFieldNode* Next; private: vtkFieldNode(const vtkFieldNode&) {} void operator=(const vtkFieldNode&) {} char* Name; }; class vtkFieldList { public: vtkFieldList() { this->First = 0; this->Last = 0; } ~vtkFieldList() { vtkFieldNode* node = this->First; vtkFieldNode* next; while(node) { next = node->Next; delete node; node = next; } } void Add(const char* name, vtkDataSet* ptr) { vtkFieldNode* newNode = new vtkFieldNode(name, ptr); if (!this->First) { this->First = newNode; this->Last = newNode; } else { this->Last->Next = newNode; this->Last = newNode; } } friend class vtkFieldListIterator; private: vtkFieldNode* First; vtkFieldNode* Last; }; class vtkFieldListIterator { public: vtkFieldListIterator(vtkFieldList* list) { this->List = list; this->Position = 0; } void Begin() { this->Position = this->List->First; } void Next() { if (this->Position) { this->Position = this->Position->Next; } } int End() { return this->Position ? 0 : 1; } vtkFieldNode* Get() { return this->Position; } private: vtkFieldNode* Position; vtkFieldList* List; }; //------------------------------------------------------------------------------ // Create object with no input or output. vtkMergeFilter::vtkMergeFilter() { this->FieldList = new vtkFieldList; this->SetNumberOfInputPorts(6); } vtkMergeFilter::~vtkMergeFilter() { delete this->FieldList; } vtkDataSet* vtkMergeFilter::GetGeometry() { if (this->GetNumberOfInputConnections(0) < 1) { return NULL; } return vtkDataSet::SafeDownCast( this->GetExecutive()->GetInputData(0, 0)); } void vtkMergeFilter::SetScalarsData(vtkDataSet *input) { this->SetInputData(1, input); } vtkDataSet *vtkMergeFilter::GetScalars() { if (this->GetNumberOfInputConnections(1) < 1) { return NULL; } return vtkDataSet::SafeDownCast( this->GetExecutive()->GetInputData(1, 0)); } void vtkMergeFilter::SetVectorsData(vtkDataSet *input) { this->SetInputData(2, input); } vtkDataSet *vtkMergeFilter::GetVectors() { if (this->GetNumberOfInputConnections(2) < 1) { return NULL; } return vtkDataSet::SafeDownCast( this->GetExecutive()->GetInputData(2, 0)); } void vtkMergeFilter::SetNormalsData(vtkDataSet *input) { this->SetInputData(3, input); } vtkDataSet *vtkMergeFilter::GetNormals() { if (this->GetNumberOfInputConnections(3) < 1) { return NULL; } return vtkDataSet::SafeDownCast( this->GetExecutive()->GetInputData(3, 0)); } void vtkMergeFilter::SetTCoordsData(vtkDataSet *input) { this->SetInputData(4, input); } vtkDataSet *vtkMergeFilter::GetTCoords() { if (this->GetNumberOfInputConnections(4) < 1) { return NULL; } return vtkDataSet::SafeDownCast( this->GetExecutive()->GetInputData(4, 0)); } void vtkMergeFilter::SetTensorsData(vtkDataSet *input) { this->SetInputData(5, input); } vtkDataSet *vtkMergeFilter::GetTensors() { if (this->GetNumberOfInputConnections(5) < 1) { return NULL; } return vtkDataSet::SafeDownCast( this->GetExecutive()->GetInputData(5, 0)); } void vtkMergeFilter::AddField(const char* name, vtkDataSet* input) { this->FieldList->Add(name, input); } int vtkMergeFilter::RequestData( vtkInformation *vtkNotUsed(request), vtkInformationVector **inputVector, vtkInformationVector *outputVector) { // get the info objects vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); vtkInformation *outInfo = outputVector->GetInformationObject(0); vtkInformation *scalarsInfo = inputVector[1]->GetInformationObject(0); vtkInformation *vectorsInfo = inputVector[2]->GetInformationObject(0); vtkInformation *normalsInfo = inputVector[3]->GetInformationObject(0); vtkInformation *tCoordsInfo = inputVector[4]->GetInformationObject(0); vtkInformation *tensorsInfo = inputVector[5]->GetInformationObject(0); // get the input and output vtkDataSet *input = vtkDataSet::SafeDownCast( inInfo->Get(vtkDataObject::DATA_OBJECT())); vtkDataSet *output = vtkDataSet::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); vtkDataSet *scalarsData = 0; vtkDataSet *vectorsData = 0; vtkDataSet *normalsData = 0; vtkDataSet *tCoordsData = 0; vtkDataSet *tensorsData = 0; if (scalarsInfo) { scalarsData = vtkDataSet::SafeDownCast( scalarsInfo->Get(vtkDataObject::DATA_OBJECT())); } if (vectorsInfo) { vectorsData = vtkDataSet::SafeDownCast( vectorsInfo->Get(vtkDataObject::DATA_OBJECT())); } if (normalsInfo) { normalsData = vtkDataSet::SafeDownCast( normalsInfo->Get(vtkDataObject::DATA_OBJECT())); } if (tCoordsInfo) { tCoordsData = vtkDataSet::SafeDownCast( tCoordsInfo->Get(vtkDataObject::DATA_OBJECT())); } if (tensorsInfo) { tensorsData = vtkDataSet::SafeDownCast( tensorsInfo->Get(vtkDataObject::DATA_OBJECT())); } vtkIdType numPts, numScalars=0, numVectors=0, numNormals=0, numTCoords=0; vtkIdType numTensors=0; vtkIdType numCells, numCellScalars=0, numCellVectors=0, numCellNormals=0; vtkIdType numCellTCoords=0, numCellTensors=0; vtkPointData *pd; vtkDataArray *scalars = NULL; vtkDataArray *vectors = NULL; vtkDataArray *normals = NULL; vtkDataArray *tcoords = NULL; vtkDataArray *tensors = NULL; vtkCellData *cd; vtkDataArray *cellScalars = NULL; vtkDataArray *cellVectors = NULL; vtkDataArray *cellNormals = NULL; vtkDataArray *cellTCoords = NULL; vtkDataArray *cellTensors = NULL; vtkPointData *outputPD = output->GetPointData(); vtkCellData *outputCD = output->GetCellData(); vtkDebugMacro(<<"Merging data!"); // geometry needs to be copied output->CopyStructure(input); if ( (numPts = input->GetNumberOfPoints()) < 1 ) { vtkWarningMacro(<<"Nothing to merge!"); } numCells = input->GetNumberOfCells(); if ( scalarsData ) { pd = scalarsData->GetPointData(); scalars = pd->GetScalars(); if ( scalars != NULL ) { numScalars = scalars->GetNumberOfTuples(); } cd = scalarsData->GetCellData(); cellScalars = cd->GetScalars(); if ( cellScalars != NULL ) { numCellScalars = cellScalars->GetNumberOfTuples(); } } if ( vectorsData ) { pd = vectorsData->GetPointData(); vectors = pd->GetVectors(); if ( vectors != NULL ) { numVectors= vectors->GetNumberOfTuples(); } cd = vectorsData->GetCellData(); cellVectors = cd->GetVectors(); if ( cellVectors != NULL ) { numCellVectors = cellVectors->GetNumberOfTuples(); } } if ( normalsData ) { pd = normalsData->GetPointData(); normals = pd->GetNormals(); if ( normals != NULL ) { numNormals= normals->GetNumberOfTuples(); } cd = normalsData->GetCellData(); cellNormals = cd->GetNormals(); if ( cellNormals != NULL ) { numCellNormals = cellNormals->GetNumberOfTuples(); } } if ( tCoordsData ) { pd = tCoordsData->GetPointData(); tcoords = pd->GetTCoords(); if ( tcoords != NULL ) { numTCoords= tcoords->GetNumberOfTuples(); } cd = tCoordsData->GetCellData(); cellTCoords = cd->GetTCoords(); if ( cellTCoords != NULL ) { numCellTCoords = cellTCoords->GetNumberOfTuples(); } } if ( tensorsData ) { pd = tensorsData->GetPointData(); tensors = pd->GetTensors(); if ( tensors != NULL ) { numTensors = tensors->GetNumberOfTuples(); } cd = tensorsData->GetCellData(); cellTensors = cd->GetTensors(); if ( cellTensors != NULL ) { numCellTensors = cellTensors->GetNumberOfTuples(); } } // merge data only if it is consistent if ( numPts == numScalars ) { outputPD->SetScalars(scalars); } else { vtkWarningMacro("Scalars for point data cannot be merged because the number of points in the input geometry do not match the number of point scalars " << numPts << " != " << numScalars); } if ( numCells == numCellScalars ) { outputCD->SetScalars(cellScalars); } else { vtkWarningMacro("Scalars for cell data cannot be merged because the number of cells in the input geometry do not match the number of cell scalars " << numCells << " != " << numCellScalars); } if ( numPts == numVectors ) { outputPD->SetVectors(vectors); } else { vtkWarningMacro("Vectors for point data cannot be merged because the number of points in the input geometry do not match the number of point vectors " << numPts << " != " << numVectors); } if ( numCells == numCellVectors ) { outputCD->SetVectors(cellVectors); } else { vtkWarningMacro("Vectors for cell data cannot be merged because the number of cells in the input geometry do not match the number of cell vectors " << numCells << " != " << numCellVectors); } if ( numPts == numNormals ) { outputPD->SetNormals(normals); } else { vtkWarningMacro("Normals for point data cannot be merged because the number of points in the input geometry do not match the number of point normals " << numPts << " != " << numNormals); } if ( numCells == numCellNormals ) { outputCD->SetNormals(cellNormals); } else { vtkWarningMacro("Normals for cell data cannot be merged because the number of cells in the input geometry do not match the number of cell normals " << numCells << " != " << numCellNormals); } if ( numPts == numTCoords ) { outputPD->SetTCoords(tcoords); } else { vtkWarningMacro("TCoords for point data cannot be merged because the number of points in the input geometry do not match the number of point tcoords " << numPts << " != " << numTCoords); } if ( numCells == numCellTCoords ) { outputCD->SetTCoords(cellTCoords); } else { vtkWarningMacro("TCoords for cell data cannot be merged because the number of cells in the input geometry do not match the number of cell tcoords " << numCells << " != " << numCellTCoords); } if ( numPts == numTensors ) { outputPD->SetTensors(tensors); } else { vtkWarningMacro("Tensors for point data cannot be merged because the number of points in the input geometry do not match the number of point tensors " << numPts << " != " << numTensors); } if ( numCells == numCellTensors ) { outputCD->SetTensors(cellTensors); } else { vtkWarningMacro("Tensors for cell data cannot be merged because the number of cells in the input geometry do not match the number of cell tcoords " << numCells << " != " << numTCoords); } vtkFieldListIterator it(this->FieldList); vtkDataArray* da; const char* name; vtkIdType num; for(it.Begin(); !it.End() ; it.Next()) { pd = it.Get()->Ptr->GetPointData(); cd = it.Get()->Ptr->GetCellData(); name = it.Get()->GetName(); if ( (da=pd->GetArray(name)) ) { num = da->GetNumberOfTuples(); if (num == numPts) { outputPD->AddArray(da); } } if ( (da=cd->GetArray(name)) ) { num = da->GetNumberOfTuples(); if (num == numCells) { outputCD->AddArray(da); } } } return 1; } //---------------------------------------------------------------------------- // Trick: Abstract data types that may or may not be the same type // (structured/unstructured), but the points/cells match up. // Output/Geometry may be structured while ScalarInput may be // unstructured (but really have same triangulation/topology as geometry). // Just request all the input. Always generate all of the output (todo). int vtkMergeFilter::RequestUpdateExtent( vtkInformation *vtkNotUsed(request), vtkInformationVector **inputVector, vtkInformationVector *vtkNotUsed(outputVector)) { vtkInformation *inputInfo; int idx; for (idx = 0; idx < 6; ++idx) { inputInfo = inputVector[idx]->GetInformationObject(0); if (inputInfo) { inputInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER(), 0); inputInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES(), 1); inputInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_GHOST_LEVELS(), 0); inputInfo->Set(vtkStreamingDemandDrivenPipeline::EXACT_EXTENT(), 1); } } return 1; } int vtkMergeFilter::FillInputPortInformation(int port, vtkInformation *info) { int retval = this->Superclass::FillInputPortInformation(port, info); if (port > 0) { info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(), 1); } return retval; } void vtkMergeFilter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); }
e99ef73273d777062be07994d1ad9addf8b3865d
10246051565cc5b500515dd88d9565eb69cc9ec8
/raytrace/raytrace/sdf_compile.h
5cb2644a06b866eb0585bc8de07734c1b579079c
[]
no_license
anthonyvd/glsl-pathtracer
ffe85d5d69e98016e3da14f7f8eca68a3e1640aa
1876128e53b9e2e1b49c7b77c8f92340ed888e7a
refs/heads/main
2023-04-02T08:33:27.483020
2021-04-14T04:23:38
2021-04-14T04:23:38
357,769,505
0
0
null
null
null
null
UTF-8
C++
false
false
310
h
#ifndef _SDF_COMPILE_H_ #define _SDF_COMPILE_H_ #include <string> // Takes a scene defined in our own weird S-expression DSL // and generate GLSL SDF evaluation code that computes the // shortest distance to the SDF as well as material properties. std::string compile_scene(const std::string& scene); #endif
aa7a7d35bf6dcd643c6ef0e70345cb1d6417eae5
820ca0fce88f15ffc86c7f898f85f59c926aeb3e
/faceTrack/face-tracking/face-tracking/src/layer/convolution.h
e66a8fbf9f59c4949ded29b08706c5f7149c194a
[ "MIT" ]
permissive
ForrestPi/FaceSolution
b53fb4ae10b3c815756761e031b0fa38f41bf3ff
cf19b2916a8bf285e457903e8d202055b092fc73
refs/heads/master
2022-04-04T08:49:20.689884
2020-02-22T08:28:30
2020-02-22T08:28:30
218,427,840
1
0
null
null
null
null
UTF-8
C++
false
false
1,601
h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #ifndef LAYER_CONVOLUTION_H #define LAYER_CONVOLUTION_H #include "../layer.h" namespace ncnn { class Convolution : public Layer { public: Convolution(); ~Convolution(); virtual int load_param(const ParamDict& pd); virtual int load_model(const ModelBin& mb); virtual int forward(const Mat& bottom_blob, Mat& top_blob, const Option& opt) const; public: // param int num_output; int kernel_w; int kernel_h; int dilation_w; int dilation_h; int stride_w; int stride_h; int pad_w; int pad_h; int bias_term; int weight_data_size; int int8_scale_term; // model Mat weight_data; Mat bias_data; float weight_data_int8_scale; float bottom_blob_int8_scale; bool use_int8_inference; ncnn::Layer* quantize; ncnn::Layer* dequantize; }; } // namespace ncnn #endif // LAYER_CONVOLUTION_H
a7718b31e85885406988a6f8583dc8beab853b21
3f935da243e0839f15392d914d45f9c7037e1ddf
/DriverStation/udptransmitter.h
157043e2f294ebf4affd0b8574649874ea19a4ff
[]
no_license
dgitz/DriverStation
d7fe1ab0c3f9ad9f6e8fa6acd9d309b4b65f6771
0110d75b465e75bf3c4514fb76006bf2aaecc1b0
refs/heads/master
2021-01-19T07:55:14.316051
2020-04-05T20:05:58
2020-04-05T20:05:58
83,970,385
0
1
null
2020-04-05T20:05:59
2017-03-05T13:04:31
C++
UTF-8
C++
false
false
4,106
h
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** BSD License Usage ** Alternatively, you may use this file under the terms of the BSD license ** as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of The Qt Company Ltd nor the names of its ** contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef UDPTRANSMITTER_H #define UDPTRANSMITTER_H #include <QDialog> #include <QHostAddress> #include <QTimer> #include <QElapsedTimer> #include "helper.h" #include "udpmessage.h" QT_BEGIN_NAMESPACE class QLabel; class QPushButton; class QUdpSocket; QT_END_NAMESPACE class UDPTransmitter : public QObject { Q_OBJECT public: UDPTransmitter(QWidget *parent = 0); bool set_RemoteControl_message(); bool set_RC_server(QString server,uint32_t port); bool send_RemoteControl_0xAB10(quint64 timestamp,int axis1,int axis2,int axis3,int axis4,int axis5,int axis6,int axis7,int axis8, int button1,int button2,int button3,int button4, int button5,int button6,int button7,int button8); bool send_ArmControl_0xAB26(int device,int axis1,int axis2,int axis3,int axis4,int axis5,int axis6,int button1,int button2,int button3,int button4,int button5,int button6); bool send_Command_0xAB02(int command,int option1,int option2,int option3, std::string commandtext, std::string description); bool send_Heartbeat_0xAB31(std::string hostname,uint64_t t,uint64_t t2); bool send_TuneControlGroup_0xAB39(std::string name, std::string type, double v1, double v2, double v3, int maxvalue, int minvalue, int defaultvalue); signals: private: QUdpSocket *xmit_socket; QTimer timer; QString RC_Server; UDPMessageHandler *udpmessagehandler; uint32_t unicast_port; QElapsedTimer RemoteControl_AB10_timer; QElapsedTimer ArmControl_AB26_timer; QElapsedTimer Command_AB02_timer; QElapsedTimer Heartbeat_AB31_timer; QElapsedTimer TuneControlGroup_0A39_timer; }; #endif
6413770d11cbd1a0d894b89332a9d55f14434736
0a40a0d63c8fce17f4a686e69073a4b18657b160
/src/qt/cerebellum/settings/settingsnetworkwidget.h
a1d46ccc16ff6d69bd0cc2f54e730d9cb973c323
[ "MIT" ]
permissive
MotoAcidic/Cerebellum
23f1b8bd4f2170c1ed930eafb3f2dfff07df1c24
6aec42007c5b59069048b27db5a8ea1a31ae4085
refs/heads/main
2023-05-13T06:31:23.481786
2021-06-09T15:28:28
2021-06-09T15:28:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
701
h
// Copyright (c) 2019 The CEREBELLUM developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef SETTINGSNETWORKWIDGET_H #define SETTINGSNETWORKWIDGET_H #include <QWidget> #include <QDataWidgetMapper> #include "qt/cerebellum/pwidget.h" namespace Ui { class SettingsNetworkWidget; } class SettingsNetworkWidget : public PWidget { Q_OBJECT public: explicit SettingsNetworkWidget(CEREBELLUMGUI* _window, QWidget *parent = nullptr); ~SettingsNetworkWidget(); void setMapper(QDataWidgetMapper *mapper); private: Ui::SettingsNetworkWidget *ui; }; #endif // SETTINGSNETWORKWIDGET_H
675c0f5dc43221b06f18d9abe9076148ce3efc4b
8c9086596b876140dea6b825808d574f8803dc23
/TimeTracker/include/FileStreamProvider.h
9014b70686984d2f15685ace740264d2df519978
[]
no_license
stephenverderame/TimeTracker
b78e47e70e8d30053b811799895c714ed57fd643
f99800b28087d1fa044a5431da14323253e68414
refs/heads/master
2023-02-15T11:47:54.375163
2021-01-06T21:52:04
2021-01-06T21:52:04
326,541,262
0
0
null
null
null
null
UTF-8
C++
false
false
553
h
#pragma once #include "StreamProvider.h" class FileStreamProvider : public StreamProvider { struct impl; std::unique_ptr<impl> pimpl; public: std::shared_ptr<StreamWrapper> getStream(const char* name) override; bool doesStreamExist(const char* name) const override; void clearStreamData(const char* name) override; std::vector<std::string> getAllStreamNames() const override; ~FileStreamProvider(); /** * @param streamNames, the name of the folder that all file streams will be located in */ FileStreamProvider(const char * streamNames); };
8cbdb3b00929de613b6eb3a767051ce449ce55c1
fab9d865463fbd6070cc7e7bd568472cfde7b415
/211.cpp
e5b204b7d82d2dc63335d5fa5f56dd5c9788ae33
[]
no_license
rubana13/player
735dd48e81a18fd3beef6a45999104105cc5cbbc
eaf69fc4d1ec10f8145e08919419d3a9ad4db89e
refs/heads/master
2020-03-08T02:11:38.770052
2018-05-25T10:09:58
2018-05-25T10:09:58
127,852,148
0
0
null
null
null
null
UTF-8
C++
false
false
254
cpp
#include <iostream> #include <string> using namespace std; int main() { int b,h; float Area; cout<<"Enter the breadth and height of triangle:\n"; cin>>b>>h; if(b,h<=1000000) { Area=(b*h)/2; cout<<Area; } if(!cin) { cout<<"Invalid input"; }
55a260397f491e7ab281099b86a80394d69a2a23
f3c51b8178225ec58cb8953be678f116d4c9bb9b
/02/f2.cpp
ba6d34cce4d2b8313f68240e6b26b082d9df153c
[]
no_license
Sakura1124/ZJU-DScode
ab960bce2882f7f6ae0717887049fcef6d715a81
d5fb992e44f4415531450fc991c1b138516e35cf
refs/heads/master
2022-12-05T04:12:31.127285
2020-08-12T04:05:32
2020-08-12T04:05:32
258,498,671
0
0
null
null
null
null
UTF-8
C++
false
false
1,195
cpp
#include<stdio.h> List Merge( List L1, List L2 ); typedef struct Node *PtrToNode; struct Node { ElementType Data; /* 存储结点数据 */ PtrToNode Next; /* 指向下一个结点的指针 */ }; typedef PtrToNode List; /* 定义单链表类型 */ #include <stdio.h> #include <stdlib.h> typedef int ElementType; typedef struct Node *PtrToNode; struct Node { ElementType Data; PtrToNode Next; }; typedef PtrToNode List; List Read(); /* 细节在此不表 */ void Print( List L ); /* 细节在此不表;空链表将输出NULL */ List Merge( List L1, List L2 ); int main() { List L1, L2, L; L1 = Read(); L2 = Read(); L = Merge(L1, L2); Print(L); Print(L1); Print(L2); return 0; } /* 你的代码将被嵌在这里 */ List Merge( List L1, List L2 ) { List p = L1->Next,q = L2->Next; L1 -> Next = L2 ->Next = NULL; List head = (List)malloc(sizeof(struct Node)); List rear = head; while(p && q ) { if(p->Data <= q->Data) { rear->Next = p; rear = p; p = p->Next; } else { rear->Next = q; rear = q; q = q->Next; } } if(p != NULL) { rear->Next = p; } if(q != NULL) { rear->Next = q; } return head; }
8c3ad1ba40147d04b821c6f9332667eca35ed716
fb16cb8d503bb674613f655e4ab29ab2a05936a2
/httpserver.cpp
e8f80bfaeae9d1ce8b687d9290eba345f61cb83a
[]
no_license
tabor-lukasz/sh_data_provider
beb178972b650b630af01b6af131c4c884e95807
dc37c8f66c44ba6aac7d6ed30d9d01554db36675
refs/heads/master
2022-12-01T22:45:50.672614
2020-08-16T17:25:39
2020-08-16T17:25:39
286,847,425
0
0
null
null
null
null
UTF-8
C++
false
false
2,307
cpp
#include "httpserver.h" #include <QtNetwork/QTcpSocket> #include <QJsonObject> #include <QJsonDocument> HttpServer::HttpServer(QObject *parent) : QObject(parent) { connect(&m_server,&QTcpServer::newConnection,this,&HttpServer::onNewConection); } void HttpServer::run() { if (!m_server.listen(QHostAddress::Any,8008)) { qDebug() << m_server.serverError(); } } void HttpServer::onSensorConfig(QVector<SensorConfig> sensor_cfgs) { m_sensor_cfgs = sensor_cfgs; } void HttpServer::onNewConection() { auto socket = m_server.nextPendingConnection(); if (!socket) return; m_socket2data[socket] = QByteArray(); connect(socket,&QTcpSocket::readyRead,this,&HttpServer::onSocketReadyRead); connect(socket,&QTcpSocket::disconnected,this,&HttpServer::onSocketDisconnected); } void HttpServer::onSocketReadyRead() { QTcpSocket *socket = static_cast<QTcpSocket*>(sender()); m_socket2data[socket].append(socket->readAll()); qDebug() << "c"; if (m_socket2data[socket].contains("\r\n\r\n")){ qDebug() << "a"; if (m_socket2data[socket].startsWith("GET")) { qDebug() << "b"; QString request = m_socket2data[socket]; auto list = request.split(' '); qDebug() << request; processGetRequest(socket,list[1]); } } } void HttpServer::onSocketDisconnected() { QTcpSocket* socket = qobject_cast<QTcpSocket*>(sender()); if(socket) { m_socket2data.remove(socket); socket->deleteLater(); } else { qDebug() << "WTF"; } } void HttpServer::processGetRequest(QTcpSocket *socket, QString endpoint) { qDebug() << "processing GET:" << endpoint; if (endpoint.compare("/live") == 0){ QJsonObject data; for (const auto& d : m_live_data) { data.insert(QString::number(d.sensor_id),d.value); } QJsonDocument doc(data); QString ss = QString("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n" "Content-Length: %1\r\n" "Connection: close\r\n\r\n").arg(doc.toJson(QJsonDocument::Compact).size()); ss += doc.toJson(QJsonDocument::Compact); qDebug() << ss; qDebug() << socket->write(ss.toLocal8Bit()); } }
539c3895b8bf27d2d605be2484d5ece6c4a8d296
286a912ce57a8af1799decc0daef2ebc5547a3a0
/v1.0/module/simple3dpiv/frame_3dpoint.cpp
4a1979a8cd43ce4f199236a8b7e66eeea61554cd
[]
no_license
feijincong/3D-Synthetic-Aperture-Particle-Image-Velocimetry
a39062aec54b4dedaf87fe2f54e95fb55f5c29b0
51f701dbdb0732e01699949c7f65a6e2b56cb61c
refs/heads/master
2021-01-15T23:51:14.804651
2015-03-13T02:07:41
2015-03-13T02:07:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
142
cpp
#include "frame_3dpoint.h" Frame3DPoint::Frame3DPoint(int x, int y, int z) { this->xPos = x; this->yPos = y; this->zPos = z; }
41c3e217989d28f7cf183b34788c301dea062751
2bce17904e161a4bdaa2d65cefd25802bf81c85b
/codeforces/482/B/B.cc
21c50403cb1f876388f1b72a3e1e5e20aa6da6c6
[]
no_license
lichenk/AlgorithmContest
9c3e26ccbe66d56f27e574f5469e9cfa4c6a74a9
74f64554cb05dc173b5d44b8b67394a0b6bb3163
refs/heads/master
2020-03-24T12:52:13.437733
2018-08-26T01:41:13
2018-08-26T01:41:13
142,727,319
0
0
null
null
null
null
UTF-8
C++
false
false
1,886
cc
#include <bits/stdc++.h> #include <assert.h> using namespace std; typedef long long ll; typedef long double ld; #define PB push_back #define MP make_pair #define MOD 1000000007LL #define endl "\n" #define fst first #define snd second const ll UNDEF = -1; const ll INF=1e18; template<typename T> inline bool chkmax(T &aa, T bb) { return aa < bb ? aa = bb, true : false; } template<typename T> inline bool chkmin(T &aa, T bb) { return aa > bb ? aa = bb, true : false; } typedef pair<ll,ll> pll; typedef vector<ll> vll; int rint() { int x; scanf("%d",&x); return x; } int segn; void modify(int *t, int l, int r, int value) { int n=segn; r++; for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if (l&1) t[l++] |= value; if (r&1) t[--r] |= value; } } void push(int *t) { int n=segn; for (int i = 1; i < n; ++i) { t[i<<1] |= t[i]; t[i<<1|1] |= t[i]; t[i] = 0; } } void build(int *t) { // build the tree int n=segn; for (int i = n - 1; i > 0; --i) t[i] = t[i<<1] & t[i<<1|1]; } int query(int *t, int l, int r) { // sum on interval [l, r) int n=segn; r++; int res = (1<<30)-1; for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if (l&1) res &= t[l++]; if (r&1) res &= t[--r]; } return res; } const int mn=1e5+2; int vt[2*mn],vl[mn],vr[mn],vq[mn]; int main() { ios_base::sync_with_stdio(false); cin.tie(0); int n=rint(),m=rint(); //for (int i=1;i<=n;i++) {a[i]=rint();} segn=n+1; for (int i=0;i<m;i++) { vl[i]=rint(),vr[i]=rint(),vq[i]=rint(); modify(vt,vl[i],vr[i],vq[i]); } push(vt); //for (int i=1;i<=n;i++) printf("%d ",vt[segn+i]); //printf("\n"); build(vt); for (int i=0;i<m;i++) { int got=query(vt,vl[i],vr[i]); //printf("got:%d\n",got); if (vq[i]!=got) { printf("NO\n"); return 0; } } printf("YES\n"); for (int i=1;i<=n;i++) printf("%d ",vt[i+segn]); printf("\n"); }
[ "Li Chen Koh" ]
Li Chen Koh
c20f4b34f66044fa09668ab5e2e2d653b6a3fad4
47abd462bf24f3b19000d88b7f9d63622a1a3fe6
/JB/Week1/2504_ValueOfBracket/main.cpp
c43aeee3ca4b9bae95e1922dc572da7c1841f268
[ "Apache-2.0" ]
permissive
alps-jbnu/ALPS_2020_Summer_Study
1f5b9e59ca2e8dcd10fdeced043f19e3a3b5aeeb
3656d5c6ab44f7f43c1f8c691e75352495c76adc
refs/heads/master
2022-12-16T04:28:25.099163
2020-08-27T07:20:31
2020-08-27T07:20:31
277,059,912
1
0
null
null
null
null
UTF-8
C++
false
false
2,199
cpp
#include <bits/stdc++.h> using namespace std; int main() { string str; cin >> str; stack<pair<char, int> > st; for(int idx = 0; str[idx]; idx++) { if(str[idx] == '(') st.push(make_pair('(', -1)); else if(str[idx] == '[') st.push(make_pair('[', -1)); else if(str[idx] == ')') { if(st.empty()) { cout << 0; return 0; } int sum = 0; pair<char, int>& now = st.top(); while(!(now.first == '(' && now.second == -1)) { if(now.second < 0) { cout << 0; return 0; } sum += now.second; st.pop(); if (st.empty()) { cout << 0; return 0; } now = st.top(); } if(sum == 0) sum = 1; if (st.empty()){ cout << 0; return 0; } st.pop(); st.push(make_pair('(', sum * 2)); } else if(str[idx] == ']') { if (st.empty()) { cout << 0; return 0; } int sum = 0; pair<char, int> &now = st.top(); while (!(now.first == '[' && now.second == -1)) { if(now.second < 0) { cout << 0; return 0; } sum += now.second; st.pop(); if (st.empty()) { cout << 0; return 0; } now = st.top(); } if (sum == 0) sum = 1; if(st.empty()) { cout << 0; return 0; } st.pop(); st.push(make_pair('[', sum * 3)); } } int ans = 0; while(!st.empty()) { if(st.top().second < 0) { cout << 0; return 0; } ans += st.top().second; st.pop(); } cout << ans; }
09eb64f0f3889e6ce548098c710cdae4aa665c26
af833d30aa294472ac0f6f445fb2175c7717e244
/src/graphics/base/v4.h
75f3bd9d0463b97e390d2fa0f9021693ace734e9
[ "Apache-2.0" ]
permissive
nomadsinteractive/ark
338451f9891edf4c369719596cad2368a11d12a0
b8cd2672aac6f4576e4a3196c5ba0cdcea8c10e8
refs/heads/master
2023-06-07T19:43:25.805463
2023-05-31T06:10:32
2023-05-31T06:10:32
108,817,094
7
1
null
null
null
null
UTF-8
C++
false
false
1,327
h
#pragma once #include "core/base/api.h" #include "graphics/base/v3.h" namespace ark { class ARK_API V4 : public V3 { public: explicit V4(float v = 0); V4(float x, float y, float z, float w); V4(const V2& xy, float z, float w); V4(const V3& xyz, float w); V4(const std::initializer_list<float>& values); DEFAULT_COPY_AND_ASSIGN_NOEXCEPT(V4); bool operator ==(const V4& other) const; bool operator !=(const V4& other) const; V4& operator +=(const V4& other); V4& operator -=(const V4& other); V4& operator *=(const V4& other); V4& operator /=(const V4& other); friend ARK_API V4 operator +(const V4& lvalue, const V4& rvalue); friend ARK_API V4 operator -(const V4& lvalue, const V4& rvalue); friend ARK_API V4 operator *(const V4& lvalue, const V4& rvalue); friend ARK_API V4 operator *(const V4& lvalue, float rvalue); friend ARK_API V4 operator *(float lvalue, const V4& rvalue); friend ARK_API V4 operator /(const V4& lvalue, const V4& rvalue); friend ARK_API V4 operator /(const V4& lvalue, float rvalue); float w() const; V4 operator -() const; float dot(const V4& other) const; float hypot() const; V4 normalize() const; V4 floorDiv(const V4& other) const; private: float _w; friend class Color; }; }
d377f47fcc00adccced16392c5a658efe0bc5c5c
175f2317d2a3104ea504164865b36620c232a8d8
/supportingcode.h
65388bb5f4734612a6872d22f1b903cb8038110f
[ "MIT" ]
permissive
ascetic85/LevelEditor-NG
2911715c9aa919313c35774e617ee0f9ead1268b
64d3ae040e063615a8945b5cb3e7eca14a67b707
refs/heads/master
2016-09-05T13:29:47.378062
2012-12-28T05:19:42
2012-12-28T05:19:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
323
h
#ifndef SUPPORTINGCODE_H #define SUPPORTINGCODE_H #include <QWidget> namespace Ui { class SupportingCode; } class SupportingCode : public QWidget { Q_OBJECT public: explicit SupportingCode(QWidget *parent = 0); ~SupportingCode(); private: Ui::SupportingCode *ui; }; #endif // SUPPORTINGCODE_H
df43ffc06e7923ddf06cbe53203f6cc778061f1a
282b879c6fae19d015b5ab38e8b8d49ecdbd2a98
/test_logger.cpp
ef9fdfbc35871bcffe1911b945207b3197f4f002
[]
no_license
dvetutnev/qapp
0b75083cd0dd6bce3bc2a6fa9f98d18dd2e790a3
10fa22c9b2dad7ada15e933f8e1712c138ba8b84
refs/heads/master
2023-06-01T01:13:35.742188
2021-06-11T01:07:52
2021-06-11T01:07:52
375,800,465
0
0
null
null
null
null
UTF-8
C++
false
false
443
cpp
#include "logger.h" #include <gtest/gtest.h> #include <filesystem> #include <fstream> const std::filesystem::path path = "test.log"; TEST(Logger, file) { std::filesystem::remove_all(path); core_set_error_handler(logging_error_handler); core_handle_error(43, "test_logging"); std::string result; std::ifstream f{path}; std::getline(f, result); ASSERT_EQ(result, "[Loglevel: 4] Message 43, test_logging"); }
6c209ec79e77439a900f1976abc73f1d9d9b9aa0
eb8b2dffe055de423bc320e6ee949a0d0d0c401d
/June Lunchtime 2021 Contest/Riche rich.cpp
c9927710f7537e8dcfe3058db570636ecfc54862
[ "MIT" ]
permissive
MadanParth786/Codeshef-Problems
7dafe59c1e326f3ad4491f1c2752bc5f821fec6f
64ec3b9849992f3350dfe67f2dbc6332a665b471
refs/heads/main
2023-08-27T03:00:42.725312
2021-10-28T16:35:12
2021-10-28T16:35:12
376,236,369
1
0
null
null
null
null
UTF-8
C++
false
false
190
cpp
#include<iostream> using namespace std; int main(void) { int n,a,b,c; cin>>n; while(n--){ cin>>a>>b>>c; if(b>a){ int d=b-a; int r=d/c; cout<<r<<"\n"; } } }
e04e05db4b8f5e9b8297a9bdaaf0aeb0628a1eec
7af437afb04dd692491a3e22ea53fbeea654bd92
/Code/Exe2-2_Options06.cpp
b8005be147663115e470ba5149ef5cb47ded343e
[]
no_license
shivam-modi/cpp_coursework
a9755980a05465809569dda9dea2282176212201
e1b8c4f04e2a4a76210b586dbcc478ef0b520e75
refs/heads/master
2023-04-30T21:13:32.828912
2019-03-28T20:07:47
2019-03-28T20:07:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,894
cpp
#include "Exe2-2_Options06.h" #include "BinModel02.h" #include <iostream> #include <cmath> using namespace std; double EurOption::PriceByCRR(BinModel Model) { double q=Model.RiskNeutProb(); double Price[N+1]; for (int i=0; i<=N; i++) { Price[i]=Payoff(Model.S(N,i)); } for (int n=N-1; n>=0; n--) { for (int i=0; i<=n; i++) { Price[i]=(q*Price[i+1]+(1-q)*Price[i]) /(1+Model.GetR()); } } return Price[0]; } int Call::GetInputData() { cout << "Enter call option data:" << endl; int N; cout << "Enter steps to expiry N: "; cin >> N; SetN(N); cout << "Enter strike price K: "; cin >> K; cout << endl; return 0; } double Call::Payoff(double z) { if (z>K) return z-K; return 0.0; } int Put::GetInputData() { cout << "Enter put option data:" << endl; int N; cout << "Enter steps to expiry N: "; cin >> N; SetN(N); cout << "Enter strike price K: "; cin >> K; cout << endl; return 0; } double Put::Payoff(double z) { if (z<K) return K-z; return 0.0; } int BullSpread::GetInputData() { cout << "Enter European bull spread data:" << endl; int N; cout << "Enter steps to expiry N: "; cin >> N; SetN(N); cout << "Enter parameter K1: "; cin >> K1; cout << "Enter parameter K2: "; cin >> K2; cout << endl; return 0; } double BullSpread::Payoff(double z) { if (K2<=z) return K2-K1; else if (K1<z) return z-K1; return 0.0; } int BearSpread::GetInputData() { cout << "Enter European bear spread data:" << endl; int N; cout << "Enter steps to expiry N: "; cin >> N; SetN(N); cout << "Enter parameter K1: "; cin >> K1; cout << "Enter parameter K2: "; cin >> K2; cout << endl; return 0; } double BearSpread::Payoff(double z) { if (K2<=z) return 0.0; else if (K1<z) return K2-z; return K2-K1; }
35afff1d4f632e85290cd15c855b0b8d43538100
210c4e09819715f0784cedb1863d4529dcc58528
/qt_monitor/mainwindow.cpp
681d485c007c1e57adae519e8651d3b336093aaf
[ "MIT" ]
permissive
jiaxiangshun/qt
ef66a64fd927cf9a922e215fcf37ee29bb3d33fa
64b93496658edbd45c528d8cd8e1cbe889a02813
refs/heads/master
2022-02-11T16:32:03.179880
2019-07-29T15:51:32
2019-07-29T15:51:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,174
cpp
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); client =new QTcpSocket(); //tcp messsage socket connect(ui->pushButton_3,SIGNAL(clicked()),this,SLOT(runMessage())); // write message connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(writeMessage())); connect(ui->pushButton_2,SIGNAL(clicked()),this,SLOT(writeMessage())); connect(ui->pushButton_4,SIGNAL(clicked()),this,SLOT(writeMessage())); connect(ui->pushButton_7,SIGNAL(clicked()),this,SLOT(writeMessage())); // printf connect(this, SIGNAL(sendString(QString)), ui->textEdit, SLOT(append(QString))); connect(client,SIGNAL(readyRead()),this,SLOT(readMessage())); } MainWindow::~MainWindow() { delete ui; } void MainWindow::runMessage(){ //client->connectToHost("192.168.46.230",8848); client->connectToHost(ui->lineEdit->text(),ui->lineEdit_2->text().toInt()); //client->write("ccy") } void MainWindow::Tran(){ //QString ip = ui->lineEdit->text(); //quint8 port = ui->lineEdit_2->text().toInt(); //client->connectToHost(ui->lineEdit->text(),ui->lineEdit_2->text().toInt()); //client1->connectToHost("localhost",8848); } void MainWindow::test(){ // const char na[255]="ccy"; // char pcCMD[255]; // sprintf(pcCMD,"mkdir %s",na); // system(pcCMD); // QString data =ui->lineEdit_3->text(); // client->write(data.toStdString().c_str()); } void MainWindow::writeMessage(){ QPushButton *p = (QPushButton*)sender(); QString name = p->text(); if(name == "Preview") { client->write(name.toStdString().c_str()); } if(name == "Capture") { client->write(name.toStdString().c_str()); } if(name == "StopCap") { client->write(name.toStdString().c_str()); } if(name == "Unpre") { client->write(name.toStdString().c_str()); } // QString info =ui->lineEdit_3->text(); // client->write(info.toStdString().c_str()); } void MainWindow::readMessage(){ QString message =client->readAll(); ui->textEdit->setText(message); }
bf2ea21cb20be3a0d2ab4daf506a48b50641927b
c477cebec2c9daaab1489dc241df5925193809d2
/crypter/crypter/crypter.cpp
02f45caa53a5ab7a8d1e4ad10ad8e427d75b4a3f
[ "Unlicense" ]
permissive
SuperNov4d/Xor-Crypter-
317dfb7e642511bb32131795f2d8be952b3e016e
8d2566ab81704de3f35da8bb8b15db9e11dcf7a4
refs/heads/main
2023-07-10T18:49:28.587511
2021-08-13T15:28:01
2021-08-13T15:28:01
395,650,179
2
0
null
null
null
null
UTF-8
C++
false
false
724
cpp
#include <iostream> #include <stdio.h> #include <Windows.h> using namespace std; string xorCrypt(string keyword) { char key[3] = { 'C','Q','D' }; string output = keyword; for (int i = 0; i < keyword.size(); i++) output[i] = keyword[i] ^ key[i % sizeof(key) / sizeof(char)]; return output; } int main() { string word; cout << "------XOR CRYPTER-------"<<endl; for (int i = 0; i < 2; i++) { cout << "\n"; } cout << "Owner[!] : SuperNova"<<"\n"; for (int i = 0; i < 2; i++) { cout << "\n"; } cout << "Enter a word : "; cin >> word; string encrypt = xorCrypt(word); cout << "Encrypt : " << encrypt<<endl; cout << "Decrypt : " << word; return 0; }
a3c04c11d2bb27daed88f3fbaa302cd46c6b3282
ba9322f7db02d797f6984298d892f74768193dcf
/live/include/alibabacloud/live/model/ApplyBoardTokenRequest.h
a52615be8e689b6eda0710625a590729d62ade5b
[ "Apache-2.0" ]
permissive
sdk-team/aliyun-openapi-cpp-sdk
e27f91996b3bad9226c86f74475b5a1a91806861
a27fc0000a2b061cd10df09cbe4fff9db4a7c707
refs/heads/master
2022-08-21T18:25:53.080066
2022-07-25T10:01:05
2022-07-25T10:01:05
183,356,893
3
0
null
2019-04-25T04:34:29
2019-04-25T04:34:28
null
UTF-8
C++
false
false
4,264
h
/* * Copyright 2009-2017 Alibaba Cloud 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. */ #ifndef ALIBABACLOUD_LIVE_MODEL_APPLYBOARDTOKENREQUEST_H_ #define ALIBABACLOUD_LIVE_MODEL_APPLYBOARDTOKENREQUEST_H_ #include <string> #include <vector> #include <alibabacloud/core/RpcServiceRequest.h> #include <alibabacloud/live/LiveExport.h> namespace AlibabaCloud { namespace Live { namespace Model { class ALIBABACLOUD_LIVE_EXPORT ApplyBoardTokenRequest : public RpcServiceRequest { public: ApplyBoardTokenRequest(); ~ApplyBoardTokenRequest(); long getCallerParentId()const; void setCallerParentId(long callerParentId); bool getProxy_original_security_transport()const; void setProxy_original_security_transport(bool proxy_original_security_transport); std::string getProxy_original_source_ip()const; void setProxy_original_source_ip(const std::string& proxy_original_source_ip); std::string getOwnerIdLoginEmail()const; void setOwnerIdLoginEmail(const std::string& ownerIdLoginEmail); std::string getCallerType()const; void setCallerType(const std::string& callerType); std::string getAccessKeyId()const; void setAccessKeyId(const std::string& accessKeyId); std::string getSecurityToken()const; void setSecurityToken(const std::string& securityToken); std::string getRegionId()const; void setRegionId(const std::string& regionId); std::string getRequestContent()const; void setRequestContent(const std::string& requestContent); std::string getCallerBidEmail()const; void setCallerBidEmail(const std::string& callerBidEmail); std::string getBoardId()const; void setBoardId(const std::string& boardId); std::string getCallerUidEmail()const; void setCallerUidEmail(const std::string& callerUidEmail); long getCallerUid()const; void setCallerUid(long callerUid); std::string getApp_ip()const; void setApp_ip(const std::string& app_ip); std::string getPopProduct()const; void setPopProduct(const std::string& popProduct); std::string getAppUid()const; void setAppUid(const std::string& appUid); std::string getCallerBid()const; void setCallerBid(const std::string& callerBid); long getOwnerId()const; void setOwnerId(long ownerId); std::string getVersion()const; void setVersion(const std::string& version); bool getProxy_trust_transport_info()const; void setProxy_trust_transport_info(bool proxy_trust_transport_info); bool getAk_mfa_present()const; void setAk_mfa_present(bool ak_mfa_present); bool getSecurity_transport()const; void setSecurity_transport(bool security_transport); std::string getRequestId()const; void setRequestId(const std::string& requestId); std::string getAppId()const; void setAppId(const std::string& appId); private: long callerParentId_; bool proxy_original_security_transport_; std::string proxy_original_source_ip_; std::string ownerIdLoginEmail_; std::string callerType_; std::string accessKeyId_; std::string securityToken_; std::string regionId_; std::string requestContent_; std::string callerBidEmail_; std::string boardId_; std::string callerUidEmail_; long callerUid_; std::string app_ip_; std::string popProduct_; std::string appUid_; std::string callerBid_; long ownerId_; std::string version_; bool proxy_trust_transport_info_; bool ak_mfa_present_; bool security_transport_; std::string requestId_; std::string appId_; }; } } } #endif // !ALIBABACLOUD_LIVE_MODEL_APPLYBOARDTOKENREQUEST_H_
41790923f9a8d1e2caa0be25f5fd01a4cba4e8e4
9f9eb15cda314a467bbcb31b821a7aabee7a7e3d
/POx-TSL230_v3/POx-TSL230_v3.ino
09fa138198b8987fcfb2eee2ed3ddebd84a3c330
[]
no_license
89spartacus/pulseoximeter
6ad71a715e0424cf30dbe19c8a9345d9b0794168
527f976d386d9a26bd63988b0321a918cf34905a
refs/heads/master
2021-01-19T03:48:19.662238
2018-02-15T21:42:03
2018-02-15T21:42:03
64,842,970
0
0
null
2016-11-14T16:02:19
2016-08-03T12:04:15
null
UTF-8
C++
false
false
7,178
ino
//Pulse Oximeter based on TSL230 //Copyright by Andreas Faulhaber #include <TimerOne.h> //interrupts //Define Sensor (LED + PD) int redLED = 8; int irLED = 9; int TSL_Pin = 2; //TSL "digital" output int TSL_S0 = 3; int TSL_S1 = 4; int TSL_S2 = 5; int TSL_S3 = 6; int TSL_divider=2; int TSL_sensitiv=100; //Operands for sensor data aquisition (TM=Time) int readTM = 15; //sampling period of TSL unsigned long diffTM = 0; unsigned long currentTM = millis(); unsigned long startTM = currentTM; unsigned long pulse_cnt = 0; volatile unsigned long temp_pulse_cnt; //Operands/operator for Data processing volatile unsigned long maxTmp,minTmp,average,lastcnt,cnt,isrCnt; unsigned long Rmax, Rmin; float HR_freq,HR,R,SpO,Theta=0.6; unsigned int Heartrate,LastHeartrate; void setup(){ //Initialization block Serial.begin(9600); pinMode(redLED, OUTPUT); pinMode(irLED, OUTPUT); digitalWrite(redLED, HIGH); digitalWrite(irLED, LOW); attachInterrupt(digitalPinToInterrupt(2), add_pulse, RISING); //interrupt on changing Sensor value (PIN2) adding a pulse to counter //TIMERONE implementation to give sampling period to interrupt at a certain time period setISR(); Timer1.initialize(40000); //interrupt every 0.04 seconds Timer1.attachInterrupt(min_max_isr); LastHeartrate = 60;R=0;Rmax=0;Rmin=0;isrCnt=0; setupTSL(); Serial.println("Start..."); } void add_pulse() {//ISR adding a pulse count to every interrupt from sensor I/O pulse_cnt++; startTM = currentTM; currentTM = millis(); if( currentTM > startTM ) { diffTM += currentTM - startTM; } // if enough time has passed to do a new reading... if(diffTM >= readTM) {// once reaching sampling period - save value & reset the ms counter temp_pulse_cnt = pulse_cnt; pulse_cnt = 0; diffTM = 0; } } unsigned long readTSL(){//returns "freq" frequency/intensity from sensor //function or procedure to calculate the frequency from the called interrupt counter unsigned long freq = temp_pulse_cnt * TSL_divider; //multiply counts by the sensors divide-by factor to solve for frequency return(freq); } void led_state (int color){ //color: RED=1, IR=2, OFF=0 int Red_pin = HIGH; int IR_pin = LOW; switch(color){ case 0: Red_pin = LOW; IR_pin = LOW; break; case 1: Red_pin = HIGH; IR_pin = LOW; break; case 2: Red_pin = LOW; IR_pin = HIGH; break; default: return; } digitalWrite(redLED, Red_pin); digitalWrite(irLED, IR_pin); } void setISR(){//ISR values reset or initialize maxTmp=0; minTmp=10000; cnt=0; lastcnt=0; isrCnt=0; } void min_max_isr(){//ISR for reading sensor value and checking max_min lastcnt=cnt;//keep previous value cnt=readTSL();//read new value if(cnt>maxTmp) {//check if value is max maxTmp=cnt; } else if(cnt<minTmp){//check if value is min minTmp=cnt; } isrCnt++;//add ISR counter } void loop(){ led_state(2); //Serial.println(isrCnt); average=(maxTmp+minTmp)/2; if((lastcnt>average)&& (cnt<average)) { noInterrupts(); //average=(maxTmp+minTmp)/2; HR_freq = 1/(0.04*isrCnt); Rmax = maxTmp; Rmin = minTmp; interrupts(); HR = HR_freq * 60; R = (Rmax - Rmin); SpO = (R-180)*0.01 +97.838; String HRSPO = HR+String(" HR ")+SpO+String(" SpO2%"); Serial.println(HRSPO); delay(100); setISR(); } // while(!((lastcnt>average )&& (cnt<average)) ){} // noInterrupts(); // temporarily disabel interrupts, to be sure it will not change while we are reading // Rmax = maxTmp; Rmin = minTmp; // delay(40); // HR_freq = 1/(0.015*isrCnt); //isrCnt is the times of ISR in 1 second, // interrupts(); //enable interrupts // HR = HR_freq * 60; //// if(HR>40 && HR<150){ //// Heartrate = Theta*Heartrate + (1 - Theta)*LastHeartrate; //Use theta to smooth //// LastHeartrate = HR; //// } // //led_state(2); // R = (Rmax - Rmin); // SpO = (R-180)*0.01 +97.838; // String HRSPO = HR+String(" HR ")+SpO+String(" SpO2%"); // Serial.println(HRSPO); // delay(100); // setISR(); // // float raw_red = readTSL(TSL_sample); // led_state(0); // float amb = readTSL(TSL_sample); // led_state(2); // float raw_ir = readTSL(TSL_sample); // float red=raw_red-amb; // float ir= raw_ir-amb; // return red,ir; // get current frequency reading // unsigned long value = readTSL(); // Serial.println(value); // delay(100); //change_sensitivit() //true to increase, false to decrease sensitivity //use threshold to determine if change_sensitivity needs adjustment //max_thres; min_thres //set_scaling () //"2, 10, 100" as divide-by factors } void setupTSL(){ pinMode(TSL_S0, OUTPUT); pinMode(TSL_S1, OUTPUT); pinMode(TSL_S2, OUTPUT); pinMode(TSL_S3, OUTPUT); pinMode(TSL_Pin, INPUT); //configure initial sensitivity //S1 LOW | S0 HIGH: low 1x //S1 HIGH | S0 LOW: med 10x //S1 HIGH | S0 HIGH: high 100x digitalWrite(TSL_S1, HIGH); digitalWrite(TSL_S0, HIGH); //config initial scaling //S3 S2 SCALING (divide-by) //L L 1 //L H 2 //H L 10*default //H H 100x digitalWrite(TSL_S3, LOW); digitalWrite(TSL_S2, HIGH); } void change_sensitivity(/*unit8_t*/bool dir ) { /*Call function w/ HIGH or LOW to increase or decrease sensitivity level * need to measure what to divide freq by * 1x sensitivity = 10, * 10x sens = 100, * 100x sens = 1000 * adjust sensitivity in 3 steps of 10x either direction */ int pin_0; int pin_1; if( dir == true ) { // increasing sensitivity // -- already as high as we can get if( TSL_sensitiv == 1000 ) return; if( TSL_sensitiv == 100 ) { // move up to max sensitivity pin_0 = HIGH; pin_1 = HIGH; } else { // move up to med. sesitivity pin_0 = LOW; pin_1 = HIGH; } // increase sensitivity divider TSL_sensitiv *= 10; } else { // reducing sensitivity // already at lowest setting if( TSL_sensitiv == 10 ) return; if( TSL_sensitiv == 100 ) { // move to lowest setting pin_0 = HIGH; pin_1 = LOW; } else { // move to medium sensitivity pin_0 = LOW; pin_1 = HIGH; } // reduce sensitivity divider TSL_sensitiv = TSL_sensitiv / 10; } //chang pin states digitalWrite(TSL_S0, pin_0); digitalWrite(TSL_S1, pin_1); return; } void set_scaling ( int what ) { // set output frequency scaling // adjust frequency multiplier and set proper pin values // scale = 2 == TSL_divider = 2 // scale = 10 == TSL_divider = 10 // scale = 100 == TSL_divider = 100 int pin_2 = HIGH; int pin_3 = HIGH; switch( what ) { case 2: pin_3 = LOW; TSL_divider = 2; break; case 10: pin_2 = LOW; TSL_divider = 10; break; case 100: TSL_divider = 100; break; default: // don't do anything with levels // we don't recognize return; } // set the pins digitalWrite(TSL_S2, pin_2); digitalWrite(TSL_S3, pin_3); return; }
b361547758d14c7ac55d06529ebca3958a3ba9e9
ed91c77afaeb0e075da38153aa89c6ee8382d3fc
/mediasoup-client/deps/webrtc/src/media/base/video_broadcaster.h
2f4e5782241d509118d4fadbcb2bb3f939be28fd
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-google-patent-license-webrtc", "LicenseRef-scancode-google-patent-license-webm", "MIT" ]
permissive
whatisor/mediasoup-client-android
37bf1aeaadc8db642cff449a26545bf15da27539
dc3d812974991d9b94efbc303aa2deb358928546
refs/heads/master
2023-04-26T12:24:18.355241
2023-01-02T16:55:19
2023-01-02T16:55:19
243,833,549
0
0
MIT
2020-02-28T18:56:36
2020-02-28T18:56:36
null
UTF-8
C++
false
false
2,754
h
/* * Copyright (c) 2016 The WebRTC 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 in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifndef MEDIA_BASE_VIDEO_BROADCASTER_H_ #define MEDIA_BASE_VIDEO_BROADCASTER_H_ #include "api/scoped_refptr.h" #include "api/sequence_checker.h" #include "api/video/video_frame_buffer.h" #include "api/video/video_source_interface.h" #include "media/base/video_source_base.h" #include "rtc_base/synchronization/mutex.h" #include "rtc_base/thread_annotations.h" namespace rtc { // VideoBroadcaster broadcast video frames to sinks and combines VideoSinkWants // from its sinks. It does that by implementing rtc::VideoSourceInterface and // rtc::VideoSinkInterface. The class is threadsafe; methods may be called on // any thread. This is needed because VideoStreamEncoder calls AddOrUpdateSink // both on the worker thread and on the encoder task queue. class VideoBroadcaster : public VideoSourceBase, public VideoSinkInterface<webrtc::VideoFrame> { public: VideoBroadcaster(); ~VideoBroadcaster() override; void AddOrUpdateSink(VideoSinkInterface<webrtc::VideoFrame>* sink, const VideoSinkWants& wants) override; void RemoveSink(VideoSinkInterface<webrtc::VideoFrame>* sink) override; // Returns true if the next frame will be delivered to at least one sink. bool frame_wanted() const; // Returns VideoSinkWants a source is requested to fulfill. They are // aggregated by all VideoSinkWants from all sinks. VideoSinkWants wants() const; // This method ensures that if a sink sets rotation_applied == true, // it will never receive a frame with pending rotation. Our caller // may pass in frames without precise synchronization with changes // to the VideoSinkWants. void OnFrame(const webrtc::VideoFrame& frame) override; void OnDiscardedFrame() override; protected: void UpdateWants() RTC_EXCLUSIVE_LOCKS_REQUIRED(sinks_and_wants_lock_); const rtc::scoped_refptr<webrtc::VideoFrameBuffer>& GetBlackFrameBuffer( int width, int height) RTC_EXCLUSIVE_LOCKS_REQUIRED(sinks_and_wants_lock_); mutable webrtc::Mutex sinks_and_wants_lock_; VideoSinkWants current_wants_ RTC_GUARDED_BY(sinks_and_wants_lock_); rtc::scoped_refptr<webrtc::VideoFrameBuffer> black_frame_buffer_; bool previous_frame_sent_to_all_sinks_ RTC_GUARDED_BY(sinks_and_wants_lock_) = true; }; } // namespace rtc #endif // MEDIA_BASE_VIDEO_BROADCASTER_H_
8cf99af8ddf567ae2a12e15a40dc3cae7cb25608
7064724292a855652a7b7b59a7b9db360f5ecbcf
/src/world/environment/fx/RealFx.h
85df9d2def9d11dde53d0cf7c6c739ed98f1f112
[]
no_license
yunari5821/multiagent-systems-tmp
fcda8a0e15566809e9ca1244ca81c4830323b549
faea4594b01daf2b30fd7598ff1d0f0a190a4c33
refs/heads/master
2020-04-17T16:51:06.555684
2019-02-03T15:56:59
2019-02-03T15:56:59
166,758,614
0
0
null
null
null
null
UTF-8
C++
false
false
4,186
h
/* * RealFx.h * * Created on: 2019/01/28 * Author: naritomi */ #ifndef SRC_WORLD_ENVIRONMENT_REALFX_H_ #define SRC_WORLD_ENVIRONMENT_REALFX_H_ #include <fstream> #include <iostream> #include <vector> #include <string> #include <errorlog.h> #include <tracelog.h> #include <utility.h> using namespace std; class RealFx { int start; int end; char frequency; string name; string code; vector<int> date; vector<double> dollyen; vector<double> ln; vector<int> week; vector<double> rtn; public: RealFx(); RealFx(const string& fname, int start, int end ) : start(), end(), frequency() { tracelog::tag("FxData"); ifstream ifs( fname ); vector<string> strs; string str, str_date; string year, month, day; char buf1[1000], buf2[1000], buf3[1000]; /* start */ getline(ifs, str); strs = utility::split(str, '\t'); strs = utility::split(strs[1], '/'); sprintf(buf1, "%04d", atoi(strs[0].c_str())); sprintf(buf2, "%02d", atoi(strs[1].c_str())); sprintf(buf3, "%02d", atoi(strs[2].c_str())); year = buf1; month = buf2; day = buf3; str_date = year + month + day; int data_start = atoi( str_date.c_str() ); /* end */ getline(ifs, str); strs = utility::split(str, '\t'); strs = utility::split(strs[1], '/'); sprintf(buf1, "%04d", atoi(strs[0].c_str())); sprintf(buf2, "%02d", atoi(strs[1].c_str())); sprintf(buf3, "%02d", atoi(strs[2].c_str())); year = buf1; month = buf2; day = buf3; str_date = year + month + day; int data_end = atoi( str_date.c_str() ); /* frequency */ getline(ifs, str); strs = utility::split(str, '\t'); this->frequency = strs[1].c_str()[0]; /* Name */ getline(ifs, str); strs = utility::split(str, '\t'); this->name = strs[1]; /* Code */ getline(ifs, str); strs = utility::split(str, '\t'); this->code = strs[1]; /* Tag but skip */ getline(ifs, str); /* check and setting */ if ( start > 0 ) { if ( start < data_start ) { errorlog::error("data from specified start does not exist in " + fname); errorlog::abort(); } this->start = start; } else { this->start = data_start; } if ( end > 0 ) { if ( data_end < end ) { errorlog::error("data to specified end does not exist in " + fname); errorlog::abort(); } this->end = end; } else { this->end = data_end; } int cnt = 0; while( true ) { getline(ifs, str); /* break check */ if ( ifs.eof() ) break; vector<string> astrs = utility::split(str, '\t'); /* date */ strs = utility::split(astrs[0], '/'); sprintf(buf1, "%04d", atoi(strs[0].c_str())); sprintf(buf2, "%02d", atoi(strs[1].c_str())); sprintf(buf3, "%02d", atoi(strs[2].c_str())); year = buf1; month = buf2; day = buf3; str_date = year + month + day; int int_date = atoi( str_date.c_str() ); if ( this->start > int_date || int_date > this->end ) break; this->date.push_back( int_date ); /* doll yen */ this->dollyen.push_back( atof( astrs[1].c_str() ) ); /* the natural logarithm dollyen */ this->ln.push_back( atof( astrs[2].c_str() ) ); /* week */ this->week.push_back( atof( astrs[3].c_str() ) ); cnt++; } /* rtn */ this->rtn.clear(); this->rtn.push_back(0.0); for( int i = 1; i < this->ln.size(); i++ ) { this->rtn.push_back( this->ln[i] - this->ln[i-1] ); // cout << this->ln[i]-this->ln[i-1] << " " << this->ln[i] << " " << this->ln[i-1] << endl; } tracelog::keyvalue("start", to_string(this->start)); tracelog::keyvalue("end", to_string(this->end)); tracelog::keyvalue("count", to_string(cnt)); ifs.close(); } virtual ~RealFx(); /* getter */ vector<int>& getDate() { return this->date; } vector<double>& getRtn() { return this->rtn; } int getDate(unsigned int idx) { if ( this->date.size() <= idx ) return -1; return this->date[ idx ]; } double getLn(unsigned int idx) { return this->ln[ idx ]; } double getRtn(unsigned int idx) { return this->rtn[ idx ]; } int getID(int yyyymmdd) { for ( int i = 0; i < this->date.size(); i++ ) { if ( this->date[i] == yyyymmdd ) return i; } return -1; } }; #endif /* SRC_WORLD_ENVIRONMENT_REALFX_H_ */
f5088f70f71daa653a135877cb92b27d8d9ddb9d
9b40f4863166327b0d51a83459ed8e271b4e8e57
/Basic_Algorithm/sort.cpp
5dcae4c5dee0375c03515e02afb1d04e2aac4b80
[]
no_license
3378950/Algorithm-Template
20d576440eaca54d7497984112a1cc9174037ecb
115254c9c1a325afdcaea76db031c646cbcc6783
refs/heads/master
2022-11-25T04:37:28.968518
2020-08-05T06:43:37
2020-08-05T06:43:37
261,932,020
0
0
null
null
null
null
UTF-8
C++
false
false
1,267
cpp
#include <iostream> #include <algorithm> using namespace std; const int N = 1010; int a[N], tmp[N]; void quick_sort(int a[], int l, int r) { if(l >= r) return; int t = a[(l + r) >> 1], i = l - 1, j = r + 1; while(i < j) { do i++; while (a[i] < t); do j--; while (a[j] > t); if(i < j) swap(a[i], a[j]); } quick_sort(a, l, j); quick_sort(a, j + 1, r); } void merge_sort(int a[], int l, int r) { if(l >= r) return; // divide int mid = (l + r) >> 1; merge_sort(a, l, mid); merge_sort(a, mid + 1, r); int k = 0, i = l, j = mid + 1; while(i <= mid && j <= r) { if(a[i] < a[j]) tmp[k++] = a[i++]; else tmp[k++] = a[j++]; } while(i <= mid) tmp[k++] = a[i++]; while(j <= r) tmp[k++] = a[j++]; // merge for (int i = l, j = 0; i <= r; i++, j++) a[i] = tmp[j]; } int main() { int n; cin >> n; for (int i = 0; i < n; i++) cin >> a[i]; // quick_sort(a, 0, n - 1); // merge_sort(a, 0, n - 1); // sort(a, a + n); for (int i = 0; i < n; i++) cout << a[i] << " "; cout << endl; return 0; }
ab5b8f47213edc0b1b3775ae81f01adade74ecba
98b1e51f55fe389379b0db00365402359309186a
/homework_3/case_1/13/U
1c0ff09eded08e4eb393677b77871e79459ea16d
[]
no_license
taddyb/597-009
f14c0e75a03ae2fd741905c4c0bc92440d10adda
5f67e7d3910e3ec115fb3f3dc89a21dcc9a1b927
refs/heads/main
2023-01-23T08:14:47.028429
2020-12-03T13:24:27
2020-12-03T13:24:27
311,713,551
1
0
null
null
null
null
UTF-8
C++
false
false
3,914
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 8 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volVectorField; location "13"; object U; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 1 -1 0 0 0 0]; internalField nonuniform List<vector> 116 ( (0.000394659 -0.00158043 0) (-0.00469726 -0.00267923 0) (-0.00419279 -0.00198952 0) (-0.0175567 -0.00402847 0) (-0.0111805 0.0177606 0) (-0.0822582 0.0520567 0) (-0.00304061 0.00586365 0) (-0.0135981 0.00883122 0) (-0.0254652 0.0130337 0) (-0.0446134 0.0163727 0) (-0.0604024 0.0391623 0) (-0.0867152 0.053937 0) (-0.00199825 0.0137749 0) (-0.0105266 0.0197105 0) (-0.0212968 0.0250243 0) (-0.0357723 0.0321168 0) (-0.0493183 0.052411 0) (-0.0651341 0.0712329 0) (-0.00294546 0.0193191 0) (-0.0109955 0.0307445 0) (-0.0199799 0.0387035 0) (-0.0282526 0.0496862 0) (-0.0355608 0.0686764 0) (-0.0368567 0.0781194 0) (0.000958667 0.0268775 0) (-0.00238128 0.0352906 0) (-0.00973356 0.0409 0) (-0.0114263 0.044115 0) (-0.0171299 0.0596163 0) (-0.00523317 0.0603442 0) (-0.00303899 0.0200589 0) (-0.00294586 0.0420871 0) (-0.00421047 0.0493925 0) (-0.000583996 0.0582617 0) (-0.00333105 0.0687138 0) (0.0117119 0.0684281 0) (0.00394684 0.0357851 0) (-0.00050009 0.0364254 0) (-0.0103987 0.0397237 0) (-0.00253563 0.0388524 0) (-0.00525164 0.0443439 0) (0.0225794 0.0449059 0) (0.00425918 0.0124452 0) (0.0116885 0.0566008 0) (0.018321 0.0520857 0) (0.0232779 0.056712 0) (0.0167094 0.0505866 0) (0.0358393 0.0537495 0) (-0.0636213 0.0259455 0) (-0.0367401 0.0180063 0) (-0.0543873 0.028174 0) (-0.0274728 0.031884 0) (-0.0235567 0.0284574 0) (0.00734347 0.0324147 0) (0.0534163 0.0992515 0) (0.085632 0.0582366 0) (0.114613 0.0420654 0) (0.161832 0.0342947 0) (0.172219 0.0220712 0) (0.216378 0.0217143 0) (-0.0981798 0.128771 0) (-0.0941622 0.0504664 0) (-0.0624049 -0.0501417 0) (0.00681345 -0.162268 0) (-0.0882472 0.115427 0) (-0.0666917 0.0261614 0) (-0.0446256 -0.0925682 0) (-0.0158299 -0.195001 0) (-0.0628137 0.095355 0) (-0.0350068 0.00577673 0) (-0.0298887 -0.105839 0) (-0.00787151 -0.227158 0) (-0.034675 0.0887637 0) (-0.003283 -0.00247702 0) (-0.0170674 -0.108829 0) (0.0036082 -0.228108 0) (-0.00515625 0.0620249 0) (0.0171726 -0.0161901 0) (-0.0156807 -0.112174 0) (0.00185852 -0.243274 0) (0.00465399 0.0729167 0) (0.0370264 0.00881534 0) (-0.00912063 -0.0895389 0) (0.0180633 -0.24485 0) (0.0118946 0.0347699 0) (0.0600812 -0.00885154 0) (-0.0209759 -0.0963559 0) (0.0260049 -0.24063 0) (0.0186657 0.0483885 0) (0.0537794 0.0373168 0) (-0.0115736 -0.0400695 0) (0.0466145 -0.227858 0) (0.0123212 0.0125309 0) (0.05542 0.00840685 0) (0.0452101 -0.0972235 0) (0.0773484 -0.237936 0) (0.212699 0.0119555 0) (0.249566 0.000698882 0) (0.201155 -0.0247122 0) (0.153723 -0.0708328 0) (-0.00737123 0.00287722 0) (-0.0181058 -0.000940348 0) (-0.026458 -0.00211312 0) (-0.0175776 -0.0103827 0) (-0.0135625 0.0238314 0) (-0.0288147 0.0198697 0) (-0.0405967 0.00456329 0) (-0.0327627 -0.0337838 0) (-0.0235462 0.0469808 0) (-0.0459164 0.020118 0) (-0.066001 0.00572624 0) (-0.0355086 -0.0875537 0) (-0.0117317 0.0914493 0) (-0.0711971 0.0643149 0) (-0.0615911 0.000164739 0) (-0.0056005 -0.139052 0) ) ; boundaryField { movingWall { type fixedValue; value uniform (1 0 0); } fixedWalls { type noSlip; } frontAndBack { type empty; } } // ************************************************************************* //
ac2f6a526e52d0131af99667e0951e670baea791
c08a26d662bd1df1b2beaa36a36d0e9fecc1ebac
/classicui_plat/tsrc/bc/apps/S60_SDK3.2/bctestservicehandler/inc/bctestservicehandlerapp.h
d199e1c88ce86282bc5582e48f544d407c83d413
[]
no_license
SymbianSource/oss.FCL.sf.mw.classicui
9c2e2c31023256126bb2e502e49225d5c58017fe
dcea899751dfa099dcca7a5508cf32eab64afa7a
refs/heads/master
2021-01-11T02:38:59.198728
2010-10-08T14:24:02
2010-10-08T14:24:02
70,943,916
1
0
null
null
null
null
UTF-8
C++
false
false
1,439
h
/* * Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: Declares main application class. * */ #ifndef BCTESTSERVICEHANDLERAPP_H #define BCTESTSERVICEHANDLERAPP_H // INCLUDES #include <aknapp.h> // CONSTANTS const TUid KUidBCTestServiceHandler = { 0x20007628 }; // UID of the application. // CLASS DECLARATION /** * CBCTestServiceHandlerApp application class. * Provides factory to create concrete document object. */ class CBCTestServiceHandlerApp : public CAknApplication { private: // From CApaApplication /** * From CApaApplication, CreateDocumentL. * Creates CBCTestServiceHandlerDocument document object. * @return A pointer to the created document object. */ CApaDocument* CreateDocumentL(); /** * From CApaApplication, AppDllUid. * Returns application's UID ( KUidBCTestServiceHandler ). * @return The value of KUidBCTestServiceHandler. */ TUid AppDllUid() const; }; #endif // BCTESTSERVICEHANDLERAPP_H // End of File
b7fcdbb9faf58738e96f177fd42c4cfe2c77a4fd
e14fc9f61f69c9b48a4d5abcea44aeed81738fbc
/open_spiel/games/liars_dice.cc
d8060444f1e9cda6375828bb4d07cfb0e1479d3f
[ "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
permissive
srijanreddy98/open_spiel
396b0376138d1f674e3b567a128608201190ecff
1a7a972d39579e86cc30d415a4d0eda618173d53
refs/heads/master
2020-07-27T13:44:14.003383
2019-09-17T17:07:53
2019-09-17T17:07:53
209,111,424
0
0
null
2019-09-17T17:03:00
2019-09-17T17:03:00
null
UTF-8
C++
false
false
12,857
cc
// Copyright 2019 DeepMind Technologies Ltd. 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 "open_spiel/games/liars_dice.h" #include <algorithm> #include <array> #include <utility> namespace open_spiel { namespace liars_dice { namespace { // Default Parameters. constexpr int kDefaultPlayers = 2; constexpr int kDefaultNumDice = 1; constexpr int kDiceSides = 6; // Number of sides on the dice. constexpr int kInvalidOutcome = -1; constexpr int kInvalidBid = -1; // Facts about the game const GameType kGameType{ /*short_name=*/"liars_dice", /*long_name=*/"Liars Dice", GameType::Dynamics::kSequential, GameType::ChanceMode::kExplicitStochastic, GameType::Information::kImperfectInformation, GameType::Utility::kZeroSum, GameType::RewardModel::kTerminal, /*max_num_players=*/kDefaultPlayers, /*min_num_players=*/kDefaultPlayers, /*provides_information_state=*/true, /*provides_information_state_as_normalized_vector=*/true, /*provides_observation=*/false, /*provides_observation_as_normalized_vector=*/false, /*parameter_specification=*/ {{"players", {GameParameter::Type::kInt, false}}}}; std::unique_ptr<Game> Factory(const GameParameters& params) { return std::unique_ptr<Game>(new LiarsDiceGame(params)); } } // namespace REGISTER_SPIEL_GAME(kGameType, Factory); LiarsDiceState::LiarsDiceState(int num_distinct_actions, int num_players, int total_num_dice, int max_dice_per_player, const std::vector<int>& num_dice) : State(num_distinct_actions, num_players), cur_player_(kChancePlayerId), // chance starts cur_roller_(0), // first player starts rolling winner_(kInvalidPlayer), loser_(kInvalidPlayer), current_bid_(kInvalidBid), total_num_dice_(total_num_dice), total_moves_(0), calling_player_(0), bidding_player_(0), max_dice_per_player_(max_dice_per_player), dice_outcomes_(), num_dice_(num_dice), num_dice_rolled_(num_players, 0), bidseq_(), bidseq_str_() { for (int const& num_dices : num_dice_) { std::vector<int> initial_outcomes(num_dices, kInvalidOutcome); dice_outcomes_.push_back(initial_outcomes); } } std::string LiarsDiceState::ActionToString(int player, Action action_id) const { if (player != kChancePlayerId) { if (action_id == total_num_dice_ * kDiceSides) { return "Liar"; } else { auto bid = LiarsDiceGame::GetQuantityFace(action_id, total_num_dice_); return absl::StrCat(bid.first, "-", bid.second); } } return absl::StrCat("chance outcome ", action_id); } int LiarsDiceState::CurrentPlayer() const { if (IsTerminal()) { return kTerminalPlayerId; } else { return cur_player_; } } void LiarsDiceState::ResolveWinner() { std::pair<int, int> bid = LiarsDiceGame::GetQuantityFace(current_bid_, total_num_dice_); int quantity = bid.first, face = bid.second; int matches = 0; // Count all the matches among all dice from all the players // kDiceSides (e.g. 6) is wild, so it always matches. for (int p = 0; p < num_players_; p++) { for (int d = 0; d < num_dice_[p]; d++) { if (dice_outcomes_[p][d] == face || dice_outcomes_[p][d] == kDiceSides) { matches++; } } } // If the number of matches are at least the quantity bid, then the bidder // wins. Otherwise, the caller wins. if (matches >= quantity) { winner_ = bidding_player_; loser_ = calling_player_; } else { winner_ = calling_player_; loser_ = bidding_player_; } } void LiarsDiceState::DoApplyAction(Action action) { if (IsChanceNode()) { // Fill the next die roll for the current roller. SPIEL_CHECK_GE(cur_roller_, 0); SPIEL_CHECK_LT(cur_roller_, num_players_); SPIEL_CHECK_LT(num_dice_rolled_[cur_roller_], num_dice_[cur_roller_]); int slot = num_dice_rolled_[cur_roller_]; // Assign the roll. dice_outcomes_[cur_roller_][slot] = action; num_dice_rolled_[cur_roller_]++; // Check to see if we must change the roller. if (num_dice_rolled_[cur_roller_] == num_dice_[cur_roller_]) { cur_roller_++; if (cur_roller_ >= num_players_) { // Time to start playing! cur_player_ = 0; // Sort all players' rolls for (int p = 0; p < num_players_; p++) { std::sort(dice_outcomes_[p].begin(), dice_outcomes_[p].end()); } } } } else { // Check for legal actions. if (!bidseq_.empty() && action <= bidseq_.back()) { SpielFatalError(absl::StrCat("Illegal action. ", action, " should be strictly higher than ", bidseq_.back())); } if (action == total_num_dice_ * kDiceSides) { // This was the calling bid, game is over. bidseq_.push_back(action); calling_player_ = cur_player_; ResolveWinner(); } else { // Up the bid and move to the next player. bidseq_.push_back(action); current_bid_ = action; bidding_player_ = cur_player_; cur_player_ = NextPlayerRoundRobin(cur_player_, num_players_); } total_moves_++; } } std::vector<Action> LiarsDiceState::LegalActions() const { if (IsTerminal()) return {}; // A chance node is a single die roll. if (IsChanceNode()) { std::vector<Action> outcomes(kDiceSides); for (int i = 0; i < kDiceSides; i++) { outcomes[i] = 1 + i; } return outcomes; } std::vector<Action> actions; // Any move higher than the current bid is allowed. (Bids start at 0) for (int b = current_bid_ + 1; b < total_num_dice_ * kDiceSides; b++) { actions.push_back(b); } // Calling Liar is only available if at least one move has been made. if (total_moves_ > 0) { actions.push_back(total_num_dice_ * kDiceSides); } return actions; } std::vector<std::pair<Action, double>> LiarsDiceState::ChanceOutcomes() const { SPIEL_CHECK_TRUE(IsChanceNode()); std::vector<std::pair<Action, double>> outcomes; // A chance node is a single die roll. outcomes.reserve(kDiceSides); for (int i = 0; i < kDiceSides; i++) { outcomes.emplace_back(1 + i, 1.0 / kDiceSides); } return outcomes; } std::string LiarsDiceState::InformationState(int player) const { SPIEL_CHECK_GE(player, 0); SPIEL_CHECK_LT(player, num_players_); std::string result = absl::StrJoin(dice_outcomes_[player], ""); for (int b = 0; b < bidseq_.size(); b++) { if (bidseq_[b] == total_num_dice_ * kDiceSides) { absl::StrAppend(&result, " Liar"); } else { auto bid = LiarsDiceGame::GetQuantityFace(bidseq_[b], total_num_dice_); absl::StrAppend(&result, " ", bid.first, "-", bid.second); } } return result; } std::string LiarsDiceState::ToString() const { std::string result = ""; for (int p = 0; p < num_players_; p++) { if (p != 0) absl::StrAppend(&result, " "); for (int d = 0; d < num_dice_[p]; d++) { absl::StrAppend(&result, dice_outcomes_[p][d]); } } if (IsChanceNode()) { return absl::StrCat(result, " - chance node, current roller is player ", cur_roller_); } for (int b = 0; b < bidseq_.size(); b++) { if (bidseq_[b] == total_num_dice_ * kDiceSides) { absl::StrAppend(&result, " Liar"); } else { auto bid = LiarsDiceGame::GetQuantityFace(bidseq_[b], total_num_dice_); absl::StrAppend(&result, " ", bid.first, "-", bid.second); } } return result; } bool LiarsDiceState::IsTerminal() const { return winner_ != kInvalidPlayer; } std::vector<double> LiarsDiceState::Returns() const { std::vector<double> returns(num_players_, 0.0); if (winner_ != kInvalidPlayer) { returns[winner_] = 1.0; } if (loser_ != kInvalidPlayer) { returns[loser_] = -1.0; } return returns; } void LiarsDiceState::InformationStateAsNormalizedVector( int player, std::vector<double>* values) const { SPIEL_CHECK_GE(player, 0); SPIEL_CHECK_LT(player, num_players_); // One-hot encoding for player number. // One-hot encoding for each die (max_dice_per_player_ * sides). // One slot(bit) for each legal bid. // One slot(bit) for a call (needed by terminal state encoding). int offset = 0; values->resize(num_players_ + (max_dice_per_player_ * kDiceSides) + (total_num_dice_ * kDiceSides) + 1); (*values)[player] = 1; offset += num_players_; int my_num_dice = num_dice_[player]; for (int d = 0; d < my_num_dice; d++) { int outcome = dice_outcomes_[player][d]; if (outcome != kInvalidOutcome) { SPIEL_CHECK_GE(outcome, 1); SPIEL_CHECK_LE(outcome, kDiceSides); (*values)[offset + (outcome - 1)] = 1; } offset += kDiceSides; } // Skip to bidding part. If current player has fewer dice than the other // players, all the remaining entries are 0 for those dice. offset = num_players_ + max_dice_per_player_ * kDiceSides; for (int b = 0; b < bidseq_.size(); b++) { SPIEL_CHECK_GE(bidseq_[b], 0); SPIEL_CHECK_LE(bidseq_[b], total_num_dice_ * kDiceSides); (*values)[offset + bidseq_[b]] = 1; } } std::unique_ptr<State> LiarsDiceState::Clone() const { return std::unique_ptr<State>(new LiarsDiceState(*this)); } LiarsDiceGame::LiarsDiceGame(const GameParameters& params) : Game(kGameType, params) { num_players_ = ParameterValue<int>("players", kDefaultPlayers); SPIEL_CHECK_GE(num_players_, kGameType.min_num_players); SPIEL_CHECK_LE(num_players_, kGameType.max_num_players); int def_num_dice = ParameterValue<int>("numdice", kDefaultNumDice); // Compute the number of dice for each player based on parameters, // and set default outcomes of unknown face values (-1). total_num_dice_ = 0; num_dice_.resize(num_players_, 0); for (int p = 0; p < num_players_; p++) { std::string key = absl::StrCat("numdice", p); int my_num_dice = def_num_dice; if (IsParameterSpecified(game_parameters_, key)) { my_num_dice = ParameterValue<int>(key); } num_dice_[p] = my_num_dice; total_num_dice_ += my_num_dice; } // Compute max dice per player (used for observations.) max_dice_per_player_ = -1; for (int nd : num_dice_) { if (nd > max_dice_per_player_) { max_dice_per_player_ = nd; } } } int LiarsDiceGame::NumDistinctActions() const { return total_num_dice_ * kDiceSides + 1; } std::unique_ptr<State> LiarsDiceGame::NewInitialState() const { std::unique_ptr<LiarsDiceState> state( new LiarsDiceState(/*num_distinct_actions=*/NumDistinctActions(), /*num_players=*/num_players_, /*total_num_dice=*/total_num_dice_, /*max_dice_per_player=*/max_dice_per_player_, /*num_dice=*/num_dice_)); return state; } int LiarsDiceGame::MaxChanceOutcomes() const { return kDiceSides; } int LiarsDiceGame::MaxGameLength() const { // A bet for each side and number of total dice, plus "liar" action. return total_num_dice_ * kDiceSides + 1; } std::vector<int> LiarsDiceGame::InformationStateNormalizedVectorShape() const { // One-hot encoding for the player number. // One-hot encoding for each die (max_dice_per_player_ * sides). // One slot(bit) for each legal bid. // One slot(bit) for each call. (Needed by terminal state encodeding.) return {num_players_ + (max_dice_per_player_ * kDiceSides) + (total_num_dice_ * kDiceSides) + 1}; } std::pair<int, int> LiarsDiceGame::GetQuantityFace(int bidnum, int total_dice) { std::pair<int, int> bid; SPIEL_CHECK_NE(bidnum, kInvalidBid); // Bids have the form <quantity>-<face> // // E.g. for 3 dice, order is: // 1-1, 1-2, ... , 1-5, 1-*, 2-1, ... , 2-5, 2-*, 3-1, ... , 3-5, 3-*. // // So the mapping is: // bidnum = 0 -> 1-1 // bidnum = 1 -> 1-2 // . // . // . // bidnum = 17 -> 3-* // bidnum = 18 -> Liar // // The "*" is a 6 and means wild (matches any side). // bidnum starts at 0. bid.first = bidnum / kDiceSides + 1; bid.second = 1 + (bidnum % kDiceSides); if (bid.second == 0) { bid.second = kDiceSides; } return bid; } } // namespace liars_dice } // namespace open_spiel
19bc411c1258becfd2d5895bf7a2e9c0ed7e3078
0c5b852d142f83cb5906ace49db82d9a9edc68e2
/TCPComm/server.cpp
2b3584ffccf2c8e8efe83b5105d2ed8842ce7984
[]
no_license
yyli/snippettools
b3b307a26b3df14370f436d5cf423ed7e99503c4
871f2a10d57602f1d59401f8ea74dfb9fd8c855a
refs/heads/master
2021-01-13T01:30:10.598022
2014-11-22T20:56:48
2014-11-22T20:57:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
334
cpp
#include <iostream> #include <cstring> #include <unistd.h> #include "TCPComm.h" void print(TCPComm &comm, int sock, void *args) { while (1) { if (comm.write(sock, "hello\n", 6) < 0) return; } } int main(int, char**) { TCPComm tester(12345, 2, &print, NULL); while (1) { sleep(10); } }
0543197a39abf0ee5879b7b397d11b48dcae4ee5
53dc93e3c21a19a920254ad5cb4bdad3c345865c
/autonomousVehicleBasicCODE/autonomousVehicleCode/UltrasonicTest/Arduino/Arduino.ino
c50832378eeacaaa1be6e31197e6e971485a145d
[]
no_license
DrawingProcess/2019F_AutonomousVehicleSKKU
64f45f34516096f4d50033c25f10195cb1a7badb
85023141f638c7f197504acf20573e4413ed082a
refs/heads/master
2023-06-19T08:44:26.546153
2021-07-22T01:21:20
2021-07-22T01:21:20
213,651,181
1
0
null
null
null
null
UTF-8
C++
false
false
2,118
ino
// Pin map #define FC_TRIG 13 // 전방 초음파 센서 TRIG 핀 #define FC_ECHO 10 // 전방 초음파 센서 ECHO 핀 #define FL_TRIG A4 // 전방좌측 초음파 센서 TRIG 핀 #define FL_ECHO A3 // 전방좌측 초음파 센서 ECHO 핀 #define FR_TRIG 3 // 전방우측 초음파 센서 TRIG 핀 #define FR_ECHO 4 // 전방우측 초음파 센서 ECHO 핀 #define L_TRIG A2 // 좌측 초음파 센서 TRIG 핀 #define L_ECHO A1 // 좌측 초음파 센서 ECHO 핀 #define R_TRIG 2 // 우측 초음파 센서 TRIG 핀 #define R_ECHO A5 // 우측 초음파 센서 ECHO 핀 float f_center; float f_left; float f_right; float left; float right; float b_center; float GetDistance(int trig, int echo) { // Range: 3cm ~ 75cm digitalWrite(trig, LOW); delayMicroseconds(4); digitalWrite(trig, HIGH); delayMicroseconds(20); digitalWrite(trig, LOW); unsigned long duration = pulseIn(echo, HIGH, 5000); if(duration == 0) return 800; else return duration * 0.17; } void setup() { pinMode(FC_TRIG, OUTPUT); pinMode(FC_ECHO, INPUT); pinMode(FL_TRIG, OUTPUT); pinMode(FL_ECHO, INPUT); pinMode(FR_TRIG, OUTPUT); pinMode(FR_ECHO, INPUT); pinMode(L_TRIG, OUTPUT); pinMode(L_ECHO, INPUT); pinMode(R_TRIG, OUTPUT); pinMode(R_ECHO, INPUT); //pinMode(BC_TRIG, OUTPUT); //pinMode(BC_ECHO, INPUT); Serial.begin(9600); } void loop() { f_center = GetDistance(FC_TRIG, FC_ECHO); Serial.print("FC:"); Serial.print(f_center); Serial.print("\n"); f_left = GetDistance(FL_TRIG, FL_ECHO); Serial.print("FL:"); Serial.print(f_left); Serial.print("\n"); f_right = GetDistance(FR_TRIG, FR_ECHO); Serial.print("FR:"); Serial.print(f_right); Serial.print("\n"); left = GetDistance(L_TRIG, L_ECHO); Serial.print("L:"); Serial.print(left); Serial.print("\n"); right = GetDistance(R_TRIG, R_ECHO); Serial.print("R:"); Serial.print(right); Serial.print("\n"); // b_center = GetDistance(BC_TRIG, BC_ECHO); // Serial.print("BC:"); // Serial.print(b_center); // Serial.print("\n"); delay(100); }
249c8a0ba3c1874ca1f0223ed33765df6c0a4f0d
bf437a984f4176f99ff1a8c6a7f60a64259b2415
/src/inet/transportlayer/sctp/SCTPSendStream.h
0196b26d0425150f27cd40052378521d85337d57
[]
no_license
kvetak/ANSA
b8bcd25c9c04a09d5764177e7929f6d2de304e57
fa0f011b248eacf25f97987172d99b39663e44ce
refs/heads/ansainet-3.3.0
2021-04-09T16:36:26.173317
2017-02-16T12:43:17
2017-02-16T12:43:17
3,823,817
10
16
null
2017-02-16T12:43:17
2012-03-25T11:25:51
C++
UTF-8
C++
false
false
1,833
h
// // Copyright (C) 2008 Irene Ruengeler // Copyright (C) 2010-2012 Thomas Dreibholz // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, see <http://www.gnu.org/licenses/>. // #ifndef __INET_SCTPSENDSTREAM_H #define __INET_SCTPSENDSTREAM_H #include <list> #include "inet/common/INETDefs.h" #include "inet/transportlayer/sctp/SCTPAssociation.h" #include "inet/transportlayer/sctp/SCTPQueue.h" namespace inet { class SCTPCommand; namespace sctp { class SCTPMessage; class SCTPDataVariables; class INET_API SCTPSendStream : public cObject { protected: uint16 streamId; uint16 nextStreamSeqNum; cPacketQueue *streamQ; cPacketQueue *uStreamQ; public: SCTPSendStream(const uint16 id); ~SCTPSendStream(); inline cPacketQueue *getStreamQ() const { return streamQ; }; inline cPacketQueue *getUnorderedStreamQ() const { return uStreamQ; }; inline uint32 getNextStreamSeqNum() const { return nextStreamSeqNum; }; inline void setNextStreamSeqNum(const uint16 num) { nextStreamSeqNum = num; }; inline uint16 getStreamId() const { return streamId; }; inline void setStreamId(const uint16 id) { streamId = id; }; void deleteQueue(); }; } // namespace sctp } // namespace inet #endif // ifndef __INET_SCTPSENDSTREAM_H
2ae9e8479508cca14cc00df452be75cf5bcc11d5
0787dc98bf2d7275d3f9dc6dd829d0705f741612
/Classes/Reference/SchedulerRef.h
369bc597b1d9d7ce5de53810fd24f60e20eb60c5
[]
no_license
xingchen1106/ChaseLight
c76575fedfe4ab10fd03bf2ab73e1adaed93430a
f8e2e9868edfede1263b041cd1de808a6a78d9a1
refs/heads/master
2021-06-18T06:52:24.970330
2017-07-11T14:54:51
2017-07-11T14:54:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
521
h
// // SchedulerRef.h // RollingBall // // Created by Reyn-Mac on 2017/6/26. // // #ifndef SchedulerRef_h #define SchedulerRef_h namespace SchedulerCode { static const std::string OnceUpdatePhysicsWorld = "update_physics_world"; static const std::string OnceEnableLauchClick = "enable_journey_start_click"; static const std::string OnceEnableEndClick = "enable_journal_finish_click"; static const std::string MainStarEnergyDecrease = "main_star_energy_decrease"; } #endif /* SchedulerRef_h */
00442dc6f4bd191dae31fb4ed1e15178f3c67cb1
7c87ef2e59f55b28a9f66b6c875d40fc44029e9b
/src/Game/Tween/ProportionalScaleTween.h
ed0275d8ecd3843087a6b07d2b8ad1d1da269c59
[]
no_license
rosdyana/Miner-Speed
ea28873beac6b7d5e56da8b0cd402319702b0972
56d7e0843b82e9ee66111ae34097548696c4a03d
refs/heads/master
2020-03-18T09:51:14.739619
2018-05-30T09:00:00
2018-05-30T09:00:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
986
h
#pragma once #include "ITween.h" #include <king/Engine.h> #include <glm/glm.hpp> namespace MinerSpeed { class ProportionalScaleTween : public MinerSpeed::ITween { public: ProportionalScaleTween(King::Engine &engine, const King::Engine::Texture &texture, const glm::vec2 &pos, const float startScale, const float endScale, const float duration, const float acceleration); virtual ~ProportionalScaleTween(); public: virtual void Start(); virtual void Update(); virtual bool IsCompleted(); private: King::Engine *mEngine; private: glm::vec2 mPos; King::Engine::Texture mTexture; float mStartScale; float mEndScale; float mTime; float mDuration; float mAcceleration; float mCurrentVelocity; float mCurrentScale; float mScaleDirectionMask; bool mIsCompleted; }; } // namespace MinerSpeed
6b6251883202ba1f7c9f23375172194e9280631d
b04969e0f4a145b90789b1a839cc1336bac6eef4
/source/Irrlicht/CGUICheckBox.h
e81221c0a7671f80ede114d9782a06ec7eb1827b
[ "LicenseRef-scancode-other-permissive", "Zlib", "LicenseRef-scancode-unknown-license-reference" ]
permissive
hyyh619/irrlicht-1.8.3
cf70bb9cf308c116fc55dbebb139316cc728a53b
edc20ff80653da40f195d1f538a50b3fe8cacacd
refs/heads/master
2023-02-16T16:11:03.211729
2023-01-31T08:26:01
2023-01-31T08:26:01
47,589,569
2
0
null
null
null
null
UTF-8
C++
false
false
1,430
h
// Copyright (C) 2002-2012 Nikolaus Gebhardt // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #ifndef __C_GUI_CHECKBOX_H_INCLUDED__ #define __C_GUI_CHECKBOX_H_INCLUDED__ #include "IrrCompileConfig.h" #ifdef _IRR_COMPILE_WITH_GUI_ #include "IGUICheckBox.h" namespace irr { namespace gui { class CGUICheckBox : public IGUICheckBox { public: //! constructor CGUICheckBox(bool checked, IGUIEnvironment* environment, IGUIElement* parent, s32 id, core::rect<s32> rectangle); //! set if box is checked virtual void setChecked(bool checked); //! returns if box is checked virtual bool isChecked() const; //! called if an event happened. virtual bool OnEvent(const SEvent& event); //! draws the element and its children virtual void draw(); //! Writes attributes of the element. virtual void serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options) const; //! Reads attributes of the element virtual void deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options); private: u32 checkTime; bool Pressed; bool Checked; }; } // end namespace gui } // end namespace irr #endif // __C_GUI_CHECKBOX_H_INCLUDED__ #endif // _IRR_COMPILE_WITH_GUI_
65be6f4b53b47d6aae8cab37216528486cd28264
9a1761fe2c1788665b04a5f985a97aa40387bcd4
/src/Test/MRenderTest_MFC/MainFrm.cpp
2e6d7839417beb36317ec21eaf6a50f404fde66a
[ "Apache-2.0" ]
permissive
mousubin/M3D
548102d1120744915461bf803fab144afde1306f
4133691db1b41ba4f4550bbfa2bdd4f4d05aa6f8
refs/heads/master
2021-01-19T10:57:55.082402
2014-10-12T15:20:17
2014-10-12T15:20:17
null
0
0
null
null
null
null
GB18030
C++
false
false
6,353
cpp
// MainFrm.cpp : CMainFrame 类的实现 // #include "stdafx.h" #include "MRenderTest_MFC.h" #include "MainFrm.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CMainFrame IMPLEMENT_DYNAMIC(CMainFrame, CFrameWndEx) const int iMaxUserToolbars = 10; const UINT uiFirstUserToolBarId = AFX_IDW_CONTROLBAR_FIRST + 40; const UINT uiLastUserToolBarId = uiFirstUserToolBarId + iMaxUserToolbars - 1; BEGIN_MESSAGE_MAP(CMainFrame, CFrameWndEx) ON_WM_CREATE() ON_WM_SETFOCUS() ON_COMMAND(ID_VIEW_CUSTOMIZE, &CMainFrame::OnViewCustomize) ON_REGISTERED_MESSAGE(AFX_WM_CREATETOOLBAR, &CMainFrame::OnToolbarCreateNew) END_MESSAGE_MAP() static UINT indicators[] = { ID_SEPARATOR, // 状态行指示器 ID_INDICATOR_CAPS, ID_INDICATOR_NUM, ID_INDICATOR_SCRL, }; // CMainFrame 构造/析构 CMainFrame::CMainFrame() { // TODO: 在此添加成员初始化代码 } CMainFrame::~CMainFrame() { } int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CFrameWndEx::OnCreate(lpCreateStruct) == -1) return -1; BOOL bNameValid; // 设置用于绘制所有用户界面元素的视觉管理器 CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerVS2008)); if (!m_wndMenuBar.Create(this)) { TRACE0("未能创建菜单栏\n"); return -1; // 未能创建 } m_wndMenuBar.SetPaneStyle(m_wndMenuBar.GetPaneStyle() | CBRS_SIZE_DYNAMIC | CBRS_TOOLTIPS | CBRS_FLYBY); // 防止菜单栏在激活时获得焦点 CMFCPopupMenu::SetForceMenuFocus(FALSE); // 创建一个视图以占用框架的工作区 if (!m_wndView.Create(NULL, NULL, AFX_WS_DEFAULT_VIEW, CRect(0, 0, 0, 0), this, AFX_IDW_PANE_FIRST, NULL)) { TRACE0("未能创建视图窗口\n"); return -1; } if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) || !m_wndToolBar.LoadToolBar(theApp.m_bHiColorIcons ? IDR_MAINFRAME_256 : IDR_MAINFRAME)) { TRACE0("未能创建工具栏\n"); return -1; // 未能创建 } CString strToolBarName; bNameValid = strToolBarName.LoadString(IDS_TOOLBAR_STANDARD); ASSERT(bNameValid); m_wndToolBar.SetWindowText(strToolBarName); CString strCustomize; bNameValid = strCustomize.LoadString(IDS_TOOLBAR_CUSTOMIZE); ASSERT(bNameValid); m_wndToolBar.EnableCustomizeButton(TRUE, ID_VIEW_CUSTOMIZE, strCustomize); // 允许用户定义的工具栏操作: InitUserToolbars(NULL, uiFirstUserToolBarId, uiLastUserToolBarId); if (!m_wndStatusBar.Create(this)) { TRACE0("未能创建状态栏\n"); return -1; // 未能创建 } m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(UINT)); // TODO: 如果您不希望工具栏和菜单栏可停靠,请删除这五行 m_wndMenuBar.EnableDocking(CBRS_ALIGN_ANY); m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY); EnableDocking(CBRS_ALIGN_ANY); DockPane(&m_wndMenuBar); DockPane(&m_wndToolBar); // 启用 Visual Studio 2005 样式停靠窗口行为 CDockingManager::SetDockingMode(DT_SMART); // 启用 Visual Studio 2005 样式停靠窗口自动隐藏行为 EnableAutoHidePanes(CBRS_ALIGN_ANY); // 启用工具栏和停靠窗口菜单替换 EnablePaneMenu(TRUE, ID_VIEW_CUSTOMIZE, strCustomize, ID_VIEW_TOOLBAR); // 启用快速(按住 Alt 拖动)工具栏自定义 CMFCToolBar::EnableQuickCustomization(); if (CMFCToolBar::GetUserImages() == NULL) { // 加载用户定义的工具栏图像 if (m_UserImages.Load(_T(".\\UserImages.bmp"))) { CMFCToolBar::SetUserImages(&m_UserImages); } } // 启用菜单个性化(最近使用的命令) // TODO: 定义您自己的基本命令,确保每个下拉菜单至少有一个基本命令。 CList<UINT, UINT> lstBasicCommands; lstBasicCommands.AddTail(ID_APP_EXIT); lstBasicCommands.AddTail(ID_EDIT_CUT); lstBasicCommands.AddTail(ID_EDIT_PASTE); lstBasicCommands.AddTail(ID_EDIT_UNDO); lstBasicCommands.AddTail(ID_APP_ABOUT); lstBasicCommands.AddTail(ID_VIEW_STATUS_BAR); lstBasicCommands.AddTail(ID_VIEW_TOOLBAR); CMFCToolBar::SetBasicCommands(lstBasicCommands); return 0; } BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) { if( !CFrameWndEx::PreCreateWindow(cs) ) return FALSE; // TODO: 在此处通过修改 // CREATESTRUCT cs 来修改窗口类或样式 cs.dwExStyle &= ~WS_EX_CLIENTEDGE; cs.lpszClass = AfxRegisterWndClass(0); return TRUE; } // CMainFrame 诊断 #ifdef _DEBUG void CMainFrame::AssertValid() const { CFrameWndEx::AssertValid(); } void CMainFrame::Dump(CDumpContext& dc) const { CFrameWndEx::Dump(dc); } #endif //_DEBUG // CMainFrame 消息处理程序 void CMainFrame::OnSetFocus(CWnd* /*pOldWnd*/) { // 将焦点前移到视图窗口 m_wndView.SetFocus(); } BOOL CMainFrame::OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo) { // 让视图第一次尝试该命令 if (m_wndView.OnCmdMsg(nID, nCode, pExtra, pHandlerInfo)) return TRUE; // 否则,执行默认处理 return CFrameWnd::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo); } void CMainFrame::OnViewCustomize() { CMFCToolBarsCustomizeDialog* pDlgCust = new CMFCToolBarsCustomizeDialog(this, TRUE /* 扫描菜单*/); pDlgCust->EnableUserDefinedToolbars(); pDlgCust->Create(); } LRESULT CMainFrame::OnToolbarCreateNew(WPARAM wp,LPARAM lp) { LRESULT lres = CFrameWndEx::OnToolbarCreateNew(wp,lp); if (lres == 0) { return 0; } CMFCToolBar* pUserToolbar = (CMFCToolBar*)lres; ASSERT_VALID(pUserToolbar); BOOL bNameValid; CString strCustomize; bNameValid = strCustomize.LoadString(IDS_TOOLBAR_CUSTOMIZE); ASSERT(bNameValid); pUserToolbar->EnableCustomizeButton(TRUE, ID_VIEW_CUSTOMIZE, strCustomize); return lres; } BOOL CMainFrame::LoadFrame(UINT nIDResource, DWORD dwDefaultStyle, CWnd* pParentWnd, CCreateContext* pContext) { // 基类将执行真正的工作 if (!CFrameWndEx::LoadFrame(nIDResource, dwDefaultStyle, pParentWnd, pContext)) { return FALSE; } // 为所有用户工具栏启用自定义按钮 BOOL bNameValid; CString strCustomize; bNameValid = strCustomize.LoadString(IDS_TOOLBAR_CUSTOMIZE); ASSERT(bNameValid); for (int i = 0; i < iMaxUserToolbars; i ++) { CMFCToolBar* pUserToolbar = GetUserToolBarByIndex(i); if (pUserToolbar != NULL) { pUserToolbar->EnableCustomizeButton(TRUE, ID_VIEW_CUSTOMIZE, strCustomize); } } return TRUE; }
d65b12c9874c56915c0024f5bfca0a932656fba8
fb0c0d94b48415a3050e9dabcb3d79fc8a653780
/Flight controller/Arduino Mega/STAGE_1_setup/STAGE_1_setup.ino
81828ce04080728c0ddec6ef2fceb3dd2a26a0df
[]
no_license
Accidental-Engineer/Arduino_flight_controller
c0a5c5a4445b61982199c9c6a5994e7ccf2dd2ba
0ded7c406cfac576208152af2412f047189f0c98
refs/heads/master
2020-04-27T13:43:06.436598
2019-03-10T09:19:02
2019-03-10T09:19:02
174,380,774
0
0
null
null
null
null
UTF-8
C++
false
false
38,693
ino
/////////////////////////////////////////////////////////////////////////////////////// //----------THIS SOFTWARE IS MODIFIED BY ADITYA MITTAL AND TARUN KUMAR------------- //----------------------------------------------------------------------------------- //THE PROGRAM WAS FOR ARDUINO UNO (CREATED BY YMFC - http://www.brokking.net/ ) BUT WE HAVE MODIFIED IT FOR ARDUINO MEGA #include <Wire.h> //Include the Wire.h library so we can communicate with the gyro #include <EEPROM.h> //Include the EEPROM.h library so we can store information onto the EEPROM //Declaring Global Variables byte last_channel_1, last_channel_2, last_channel_3, last_channel_4; byte lowByte, highByte, type, gyro_address, error, clockspeed_ok; byte channel_1_assign, channel_2_assign, channel_3_assign, channel_4_assign; byte roll_axis, pitch_axis, yaw_axis; byte receiver_check_byte, gyro_check_byte; volatile int receiver_input_channel_1, receiver_input_channel_2, receiver_input_channel_3, receiver_input_channel_4; int center_channel_1, center_channel_2, center_channel_3, center_channel_4; int high_channel_1, high_channel_2, high_channel_3, high_channel_4; int low_channel_1, low_channel_2, low_channel_3, low_channel_4; int address, cal_int; unsigned long timer, timer_1, timer_2, timer_3, timer_4, current_time; float gyro_pitch, gyro_roll, gyro_yaw; float gyro_roll_cal, gyro_pitch_cal, gyro_yaw_cal; //Setup routine void setup(){ //Configure digital poort 41,42 and 43 as output. pinMode(41, OUTPUT); pinMode(42, OUTPUT); pinMode(43, OUTPUT); //Arduino (Atmega) pins default to inputs, so they don't need to be explicitly declared as inputs PCICR |= (1 << PCIE0); // set PCIE0 to enable PCMSK0 scan PCMSK0 |= (1 << PCINT0); // set PCINT0 (digital input 50 to 53) to trigger an interrupt on state change PCMSK0 |= (1 << PCINT1); // Thr=51 PCMSK0 |= (1 << PCINT2); PCMSK0 |= (1 << PCINT3); Wire.begin(); Serial.begin(57600); delay(250); } //Main program void loop(){ intro(); Serial.println(F("System check")); delay(1000); Serial.println(F("Checking I2C clock speed.")); delay(1000); TWBR = 12; //Set the I2C clock speed to 400kHz. #if F_CPU == 16000000L //If the clock speed is 16MHz include the next code line when compiling clockspeed_ok = 1; //Set clockspeed_ok to 1 #endif if(TWBR == 12 && clockspeed_ok){ Serial.println(F("I2C clock speed is correctly set to 400kHz.")); } else{ Serial.println(F("I2C clock speed is not set to 400kHz. (ERROR 8)")); error = 1; } if(error == 0){ Serial.println(F("")); Serial.println(F("*****************************************************")); Serial.println(F("Transmitter setup")); Serial.println(F("*****************************************************")); delay(1000); Serial.print(F("Checking for valid receiver signals.")); wait_for_receiver(); Serial.println(F("")); } if(error == 0){ delay(2000); Serial.println(F("Place all sticks and subtrims in the center position within 5 seconds.")); for(int i = 4;i > 0;i--){ delay(1000); Serial.print(i); Serial.print(" "); } Serial.println(" "); //Store the central stick positions center_channel_1 = receiver_input_channel_1; center_channel_2 = receiver_input_channel_2; center_channel_3 = receiver_input_channel_3; center_channel_4 = receiver_input_channel_4; Serial.println(F("")); Serial.println(F("Center positions stored.")); Serial.print(F("Digital input 08 = ")); Serial.println(receiver_input_channel_1); Serial.print(F("Digital input 09 = ")); Serial.println(receiver_input_channel_2); Serial.print(F("Digital input 10 = ")); Serial.println(receiver_input_channel_3); Serial.print(F("Digital input 11 = ")); Serial.println(receiver_input_channel_4); Serial.println(F("")); Serial.println(F("")); } if(error == 0){ Serial.println(F("Move the throttle stick to full throttle and back to center")); //Check for throttle movement check_receiver_inputs(1); Serial.print(F("Throttle is connected to digital input ")); Serial.println((channel_3_assign & 0b00000111) + 7); if(channel_3_assign & 0b10000000)Serial.println(F("Channel inverted = yes")); else Serial.println(F("Channel inverted = no")); wait_sticks_zero(); Serial.println(F("")); Serial.println(F("")); Serial.println(F("Move the roll stick to simulate left wing up and back to center")); //Check for throttle movement check_receiver_inputs(2); Serial.print(F("Roll is connected to digital input ")); Serial.println((channel_1_assign & 0b00000111) + 7); if(channel_1_assign & 0b10000000)Serial.println(F("Channel inverted = yes")); else Serial.println(F("Channel inverted = no")); wait_sticks_zero(); } if(error == 0){ Serial.println(F("")); Serial.println(F("")); Serial.println(F("Move the pitch stick to simulate nose up and back to center")); //Check for throttle movement check_receiver_inputs(3); Serial.print(F("Pitch is connected to digital input ")); Serial.println((channel_2_assign & 0b00000111) + 7); if(channel_2_assign & 0b10000000)Serial.println(F("Channel inverted = yes")); else Serial.println(F("Channel inverted = no")); wait_sticks_zero(); } if(error == 0){ Serial.println(F("")); Serial.println(F("")); Serial.println(F("Move the yaw stick to simulate nose right and back to center")); check_receiver_inputs(4); Serial.print(F("Yaw is connected to digital input ")); Serial.println((channel_4_assign & 0b00000111) + 7); if(channel_4_assign & 0b10000000)Serial.println(F("Channel inverted = yes")); else Serial.println(F("Channel inverted = no")); wait_sticks_zero(); } if(error == 0){ Serial.println(F("")); Serial.println(F("Gently move all the sticks simultaneously to their extends")); Serial.println(F("When ready put the sticks back in their center positions")); register_min_max(); Serial.println(F("")); Serial.println(F("")); Serial.println(F("High, low and center values found during setup")); Serial.print(F("Digital input 08 values:")); Serial.print(low_channel_1); Serial.print(F(" - ")); Serial.print(center_channel_1); Serial.print(F(" - ")); Serial.println(high_channel_1); Serial.print(F("Digital input 09 values:")); Serial.print(low_channel_2); Serial.print(F(" - ")); Serial.print(center_channel_2); Serial.print(F(" - ")); Serial.println(high_channel_2); Serial.print(F("Digital input 10 values:")); Serial.print(low_channel_3); Serial.print(F(" - ")); Serial.print(center_channel_3); Serial.print(F(" - ")); Serial.println(high_channel_3); Serial.print(F("Digital input 11 values:")); Serial.print(low_channel_4); Serial.print(F(" - ")); Serial.print(center_channel_4); Serial.print(F(" - ")); Serial.println(high_channel_4); Serial.println(F("Move stick 'nose up' and back to center to continue")); check_to_continue(); } if(error == 0){ //What gyro is connected Serial.println(F("")); Serial.println(F("*****************************************************")); Serial.println(F("Gyro search")); Serial.println(F("*****************************************************")); delay(2000); Serial.println(F("Searching for MPU-6050 on address 0x68/104")); delay(1000); if(search_gyro(0x68, 0x75) == 0x68){ Serial.println(F("MPU-6050 found on address 0x68")); type = 1; gyro_address = 0x68; } if(type == 0){ Serial.println(F("Searching for MPU-6050 on address 0x69/105")); delay(1000); if(search_gyro(0x69, 0x75) == 0x68){ Serial.println(F("MPU-6050 found on address 0x69")); type = 1; gyro_address = 0x69; } } if(type == 0){ Serial.println(F("Searching for L3G4200D on address 0x68/104")); delay(1000); if(search_gyro(0x68, 0x0F) == 0xD3){ Serial.println(F("L3G4200D found on address 0x68")); type = 2; gyro_address = 0x68; } } if(type == 0){ Serial.println(F("Searching for L3G4200D on address 0x69/105")); delay(1000); if(search_gyro(0x69, 0x0F) == 0xD3){ Serial.println(F("L3G4200D found on address 0x69")); type = 2; gyro_address = 0x69; } } if(type == 0){ Serial.println(F("Searching for L3GD20H on address 0x6A/106")); delay(1000); if(search_gyro(0x6A, 0x0F) == 0xD7){ Serial.println(F("L3GD20H found on address 0x6A")); type = 3; gyro_address = 0x6A; } } if(type == 0){ Serial.println(F("Searching for L3GD20H on address 0x6B/107")); delay(1000); if(search_gyro(0x6B, 0x0F) == 0xD7){ Serial.println(F("L3GD20H found on address 0x6B")); type = 3; gyro_address = 0x6B; } } if(type == 0){ Serial.println(F("No gyro device found!!! (ERROR 3)")); error = 1; } else{ delay(3000); Serial.println(F("")); Serial.println(F("===================================================")); Serial.println(F("Gyro register settings")); Serial.println(F("===================================================")); start_gyro(); //Setup the gyro for further use } } //If the gyro is found we can setup the correct gyro axes. if(error == 0){ delay(3000); Serial.println(F("")); Serial.println(F("*****************************************************")); Serial.println(F("Gyro calibration")); Serial.println(F("*****************************************************")); Serial.println(F("Don't move the quadcopter!! Calibration starts in 3 seconds")); delay(3000); Serial.println(F("Calibrating the gyro, this will take +/- 8 seconds")); Serial.print(F("Please wait")); //Let's take multiple gyro data samples so we can determine the average gyro offset (calibration). for (cal_int = 0; cal_int < 2000 ; cal_int ++){ //Take 2000 readings for calibration. if(cal_int % 100 == 0)Serial.print(F(".")); //Print dot to indicate calibration. gyro_signalen(); //Read the gyro output. gyro_roll_cal += gyro_roll; gyro_pitch_cal += gyro_pitch; gyro_yaw_cal += gyro_yaw; delay(4); } //Now that we have 2000 measures, we need to devide by 2000 to get the average gyro offset. gyro_roll_cal /= 2000; //Divide the roll total by 2000. gyro_pitch_cal /= 2000; gyro_yaw_cal /= 2000; //Show the calibration results Serial.println(F("")); Serial.print(F("Axis 1 offset=")); Serial.println(gyro_roll_cal); Serial.print(F("Axis 2 offset=")); Serial.println(gyro_pitch_cal); Serial.print(F("Axis 3 offset=")); Serial.println(gyro_yaw_cal); Serial.println(F("")); Serial.println(F("*****************************************************")); Serial.println(F("Gyro axes configuration")); Serial.println(F("*****************************************************")); //Detect the left wing up movement Serial.println(F("Lift the left side of the quadcopter to a 45 degree angle within 10 seconds")); //Check axis movement check_gyro_axes(1); if(error == 0){ Serial.println(F("OK!")); Serial.print(F("Angle detection = ")); Serial.println(roll_axis & 0b00000011); if(roll_axis & 0b10000000)Serial.println(F("Axis inverted = yes")); else Serial.println(F("Axis inverted = no")); Serial.println(F("Put the quadcopter back in its original position")); Serial.println(F("Move stick 'nose up' and back to center to continue")); check_to_continue(); //Detect the nose up movement Serial.println(F("")); Serial.println(F("")); Serial.println(F("Lift the nose of the quadcopter to a 45 degree angle within 10 seconds")); //Check axis movement check_gyro_axes(2); } if(error == 0){ Serial.println(F("OK!")); Serial.print(F("Angle detection = ")); Serial.println(pitch_axis & 0b00000011); if(pitch_axis & 0b10000000)Serial.println(F("Axis inverted = yes")); else Serial.println(F("Axis inverted = no")); Serial.println(F("Put the quadcopter back in its original position")); Serial.println(F("Move stick 'nose up' and back to center to continue")); check_to_continue(); //Detect the nose right movement Serial.println(F("")); Serial.println(F("")); Serial.println(F("Rotate the nose of the quadcopter 45 degree to the right within 10 seconds")); //Check axis movement check_gyro_axes(3); } if(error == 0){ Serial.println(F("OK!")); Serial.print(F("Angle detection = ")); Serial.println(yaw_axis & 0b00000011); if(yaw_axis & 0b10000000)Serial.println(F("Axis inverted = yes")); else Serial.println(F("Axis inverted = no")); Serial.println(F("Put the quadcopter back in its original position")); Serial.println(F("Move stick 'nose up' and back to center to continue")); check_to_continue(); } } if(error == 0){ Serial.println(F("")); Serial.println(F("*****************************************************")); Serial.println(F("LED test")); Serial.println(F("*****************************************************")); digitalWrite(43, HIGH); digitalWrite(42, HIGH); digitalWrite(41, HIGH); Serial.println(F("The LED should now be lit")); Serial.println(F("Move stick 'nose up' and back to center to continue")); check_to_continue(); digitalWrite(43, LOW); digitalWrite(42, LOW); digitalWrite(41, LOW); } Serial.println(F("")); if(error == 0){ Serial.println(F("*****************************************************")); Serial.println(F("Final setup check")); Serial.println(F("*****************************************************")); delay(1000); if(receiver_check_byte == 0b00001111){ Serial.println(F("Receiver channels ok")); } else{ Serial.println(F("Receiver channel verification failed!!! (ERROR 6)")); error = 1; } delay(1000); if(gyro_check_byte == 0b00000111){ Serial.println(F("Gyro axes ok")); } else{ Serial.println(F("Gyro exes verification failed!!! (ERROR 7)")); error = 1; } } if(error == 0){ Serial.println(F("")); Serial.println(F("*****************************************************")); Serial.println(F("Storing EEPROM information")); Serial.println(F("*****************************************************")); Serial.println(F("Writing EEPROM")); delay(1000); Serial.println(F("Done!")); EEPROM.write(0, center_channel_1 & 0b11111111); EEPROM.write(1, center_channel_1 >> 8); EEPROM.write(2, center_channel_2 & 0b11111111); EEPROM.write(3, center_channel_2 >> 8); EEPROM.write(4, center_channel_3 & 0b11111111); EEPROM.write(5, center_channel_3 >> 8); EEPROM.write(6, center_channel_4 & 0b11111111); EEPROM.write(7, center_channel_4 >> 8); EEPROM.write(8, high_channel_1 & 0b11111111); EEPROM.write(9, high_channel_1 >> 8); EEPROM.write(10, high_channel_2 & 0b11111111); EEPROM.write(11, high_channel_2 >> 8); EEPROM.write(12, high_channel_3 & 0b11111111); EEPROM.write(13, high_channel_3 >> 8); EEPROM.write(14, high_channel_4 & 0b11111111); EEPROM.write(15, high_channel_4 >> 8); EEPROM.write(16, low_channel_1 & 0b11111111); EEPROM.write(17, low_channel_1 >> 8); EEPROM.write(18, low_channel_2 & 0b11111111); EEPROM.write(19, low_channel_2 >> 8); EEPROM.write(20, low_channel_3 & 0b11111111); EEPROM.write(21, low_channel_3 >> 8); EEPROM.write(22, low_channel_4 & 0b11111111); EEPROM.write(23, low_channel_4 >> 8); EEPROM.write(24, channel_1_assign); EEPROM.write(25, channel_2_assign); EEPROM.write(26, channel_3_assign); EEPROM.write(27, channel_4_assign); EEPROM.write(28, roll_axis); EEPROM.write(29, pitch_axis); EEPROM.write(30, yaw_axis); EEPROM.write(31, type); EEPROM.write(32, gyro_address); //Write the EEPROM signature EEPROM.write(33, 'J'); EEPROM.write(34, 'M'); EEPROM.write(35, 'B'); //To make sure evrything is ok, verify the EEPROM data. Serial.println(F("Verify EEPROM data")); delay(1000); if(center_channel_1 != ((EEPROM.read(1) << 8) | EEPROM.read(0)))error = 1; if(center_channel_2 != ((EEPROM.read(3) << 8) | EEPROM.read(2)))error = 1; if(center_channel_3 != ((EEPROM.read(5) << 8) | EEPROM.read(4)))error = 1; if(center_channel_4 != ((EEPROM.read(7) << 8) | EEPROM.read(6)))error = 1; if(high_channel_1 != ((EEPROM.read(9) << 8) | EEPROM.read(8)))error = 1; if(high_channel_2 != ((EEPROM.read(11) << 8) | EEPROM.read(10)))error = 1; if(high_channel_3 != ((EEPROM.read(13) << 8) | EEPROM.read(12)))error = 1; if(high_channel_4 != ((EEPROM.read(15) << 8) | EEPROM.read(14)))error = 1; if(low_channel_1 != ((EEPROM.read(17) << 8) | EEPROM.read(16)))error = 1; if(low_channel_2 != ((EEPROM.read(19) << 8) | EEPROM.read(18)))error = 1; if(low_channel_3 != ((EEPROM.read(21) << 8) | EEPROM.read(20)))error = 1; if(low_channel_4 != ((EEPROM.read(23) << 8) | EEPROM.read(22)))error = 1; if(channel_1_assign != EEPROM.read(24))error = 1; if(channel_2_assign != EEPROM.read(25))error = 1; if(channel_3_assign != EEPROM.read(26))error = 1; if(channel_4_assign != EEPROM.read(27))error = 1; if(roll_axis != EEPROM.read(28))error = 1; if(pitch_axis != EEPROM.read(29))error = 1; if(yaw_axis != EEPROM.read(30))error = 1; if(type != EEPROM.read(31))error = 1; if(gyro_address != EEPROM.read(32))error = 1; if('J' != EEPROM.read(33))error = 1; if('M' != EEPROM.read(34))error = 1; if('B' != EEPROM.read(35))error = 1; if(error == 1)Serial.println(F("EEPROM verification failed!!! (ERROR 5)")); else Serial.println(F("Verification done")); } if(error == 0){ Serial.println(F("Setup is finished.")); Serial.println(F("You can now calibrate the esc's and upload the STAGE 2 code.")); } else{ Serial.println(F("The setup is aborted due to an error.")); } while(1); } //Search for the gyro and check the Who_am_I register byte search_gyro(int gyro_address, int who_am_i){ Wire.beginTransmission(gyro_address); Wire.write(who_am_i); Wire.endTransmission(); Wire.requestFrom(gyro_address, 1); timer = millis() + 100; while(Wire.available() < 1 && timer > millis()); lowByte = Wire.read(); address = gyro_address; return lowByte; } void start_gyro(){ //Setup the L3G4200D or L3GD20H if(type == 2 || type == 3){ Wire.beginTransmission(address); Wire.write(0x20); Wire.write(0x0F); //Set the register bits as 00001111 (Turn on the gyro and enable all axis) Wire.endTransmission(); Wire.beginTransmission(address); //Start communication with the gyro (adress 1101001) Wire.write(0x20); //Start reading @ register 28h and auto increment with every read Wire.endTransmission(); Wire.requestFrom(address, 1); //Request 6 bytes from the gyro while(Wire.available() < 1); Serial.print(F("Register 0x20 is set to:")); Serial.println(Wire.read(),BIN); Wire.beginTransmission(address); //Start communication with the gyro with the address found during search Wire.write(0x23); //We want to write to register 4 (23 hex) Wire.write(0x90); //Set the register bits as 10010000 (Block Data Update active & 500dps full scale) Wire.endTransmission(); Wire.beginTransmission(address); //Start communication with the gyro (adress 1101001) Wire.write(0x23); //Start reading @ register 28h and auto increment with every read Wire.endTransmission(); //End the transmission Wire.requestFrom(address, 1); //Request 6 bytes from the gyro while(Wire.available() < 1); Serial.print(F("Register 0x23 is set to:")); Serial.println(Wire.read(),BIN); } //Setup the MPU-6050 if(type == 1){ Wire.beginTransmission(address); //Start communication with the gyro Wire.write(0x6B); //PWR_MGMT_1 register Wire.write(0x00); //Set to zero to turn on the gyro Wire.endTransmission(); //End the transmission Wire.beginTransmission(address); //Start communication with the gyro Wire.write(0x6B); //Start reading @ register 28h and auto increment with every read Wire.endTransmission(); //End the transmission Wire.requestFrom(address, 1); //Request 1 bytes from the gyro while(Wire.available() < 1); //Wait until the 1 byte is received Serial.print(F("Register 0x6B is set to:")); Serial.println(Wire.read(),BIN); Wire.beginTransmission(address); //Start communication with the gyro Wire.write(0x1B); //GYRO_CONFIG register Wire.write(0x08); //Set the register bits as 00001000 (500dps full scale) Wire.endTransmission(); //End the transmission Wire.beginTransmission(address); //Start communication with the gyro (adress 1101001) Wire.write(0x1B); //Start reading @ register 28h and auto increment with every read Wire.endTransmission(); //End the transmission Wire.requestFrom(address, 1); //Request 1 bytes from the gyro while(Wire.available() < 1); //Wait until the 1 byte is received Serial.print(F("Register 0x1B is set to:")); Serial.println(Wire.read(),BIN); } } void gyro_signalen(){ if(type == 2 || type == 3){ Wire.beginTransmission(address); //Start communication with the gyro Wire.write(168); //Start reading @ register 28h and auto increment with every read Wire.endTransmission(); //End the transmission Wire.requestFrom(address, 6); //Request 6 bytes from the gyro while(Wire.available() < 6); //Wait until the 6 bytes are received lowByte = Wire.read(); //First received byte is the low part of the angular data highByte = Wire.read(); //Second received byte is the high part of the angular data gyro_roll = ((highByte<<8)|lowByte); //Multiply highByte by 256 (shift left by 8) and ad lowByte if(cal_int == 2000)gyro_roll -= gyro_roll_cal; //Only compensate after the calibration lowByte = Wire.read(); //First received byte is the low part of the angular data highByte = Wire.read(); //Second received byte is the high part of the angular data gyro_pitch = ((highByte<<8)|lowByte); //Multiply highByte by 256 (shift left by 8) and ad lowByte if(cal_int == 2000)gyro_pitch -= gyro_pitch_cal; //Only compensate after the calibration lowByte = Wire.read(); //First received byte is the low part of the angular data highByte = Wire.read(); //Second received byte is the high part of the angular data gyro_yaw = ((highByte<<8)|lowByte); //Multiply highByte by 256 (shift left by 8) and ad lowByte if(cal_int == 2000)gyro_yaw -= gyro_yaw_cal; //Only compensate after the calibration } if(type == 1){ Wire.beginTransmission(address); //Start communication with the gyro Wire.write(0x43); //Start reading @ register 43h and auto increment with every read Wire.endTransmission(); //End the transmission Wire.requestFrom(address,6); //Request 6 bytes from the gyro while(Wire.available() < 6); //Wait until the 6 bytes are received gyro_roll=Wire.read()<<8|Wire.read(); //Read high and low part of the angular data if(cal_int == 2000)gyro_roll -= gyro_roll_cal; //Only compensate after the calibration gyro_pitch=Wire.read()<<8|Wire.read(); //Read high and low part of the angular data if(cal_int == 2000)gyro_pitch -= gyro_pitch_cal; //Only compensate after the calibration gyro_yaw=Wire.read()<<8|Wire.read(); //Read high and low part of the angular data if(cal_int == 2000)gyro_yaw -= gyro_yaw_cal; //Only compensate after the calibration } } //Check if a receiver input value is changing within 30 seconds void check_receiver_inputs(byte movement){ byte trigger = 0; int pulse_length; timer = millis() + 30000; while(timer > millis() && trigger == 0){ delay(250); if(receiver_input_channel_1 > 1750 || receiver_input_channel_1 < 1250){ trigger = 1; receiver_check_byte |= 0b00000001; pulse_length = receiver_input_channel_1; } if(receiver_input_channel_2 > 1750 || receiver_input_channel_2 < 1250){ trigger = 2; receiver_check_byte |= 0b00000010; pulse_length = receiver_input_channel_2; } if(receiver_input_channel_3 > 1750 || receiver_input_channel_3 < 1250){ trigger = 3; receiver_check_byte |= 0b00000100; pulse_length = receiver_input_channel_3; } if(receiver_input_channel_4 > 1750 || receiver_input_channel_4 < 1250){ trigger = 4; receiver_check_byte |= 0b00001000; pulse_length = receiver_input_channel_4; } } if(trigger == 0){ error = 1; Serial.println(F("No stick movement detected in the last 30 seconds!!! (ERROR 2)")); } //Assign the stick to the function. else{ if(movement == 1){ channel_3_assign = trigger; if(pulse_length < 1250)channel_3_assign += 0b10000000; } if(movement == 2){ channel_1_assign = trigger; if(pulse_length < 1250)channel_1_assign += 0b10000000; } if(movement == 3){ channel_2_assign = trigger; if(pulse_length < 1250)channel_2_assign += 0b10000000; } if(movement == 4){ channel_4_assign = trigger; if(pulse_length < 1250)channel_4_assign += 0b10000000; } } } void check_to_continue(){ byte continue_byte = 0; while(continue_byte == 0){ if(channel_2_assign == 0b00000001 && receiver_input_channel_1 > center_channel_1 + 150)continue_byte = 1; if(channel_2_assign == 0b10000001 && receiver_input_channel_1 < center_channel_1 - 150)continue_byte = 1; if(channel_2_assign == 0b00000010 && receiver_input_channel_2 > center_channel_2 + 150)continue_byte = 1; if(channel_2_assign == 0b10000010 && receiver_input_channel_2 < center_channel_2 - 150)continue_byte = 1; if(channel_2_assign == 0b00000011 && receiver_input_channel_3 > center_channel_3 + 150)continue_byte = 1; if(channel_2_assign == 0b10000011 && receiver_input_channel_3 < center_channel_3 - 150)continue_byte = 1; if(channel_2_assign == 0b00000100 && receiver_input_channel_4 > center_channel_4 + 150)continue_byte = 1; if(channel_2_assign == 0b10000100 && receiver_input_channel_4 < center_channel_4 - 150)continue_byte = 1; delay(100); } wait_sticks_zero(); } //Check if the transmitter sticks are in the neutral position void wait_sticks_zero(){ byte zero = 0; while(zero < 15){ if(receiver_input_channel_1 < center_channel_1 + 20 && receiver_input_channel_1 > center_channel_1 - 20)zero |= 0b00000001; if(receiver_input_channel_2 < center_channel_2 + 20 && receiver_input_channel_2 > center_channel_2 - 20)zero |= 0b00000010; if(receiver_input_channel_3 < center_channel_3 + 20 && receiver_input_channel_3 > center_channel_3 - 20)zero |= 0b00000100; if(receiver_input_channel_4 < center_channel_4 + 20 && receiver_input_channel_4 > center_channel_4 - 20)zero |= 0b00001000; delay(100); } } //Checck if the receiver values are valid within 10 seconds void wait_for_receiver(){ byte zero = 0; timer = millis() + 10000; while(timer > millis() && zero < 15){ if(receiver_input_channel_1 < 2100 && receiver_input_channel_1 > 900)zero |= 0b00000001; if(receiver_input_channel_2 < 2100 && receiver_input_channel_2 > 900)zero |= 0b00000010; if(receiver_input_channel_3 < 2100 && receiver_input_channel_3 > 900)zero |= 0b00000100; if(receiver_input_channel_4 < 2100 && receiver_input_channel_4 > 900)zero |= 0b00001000; delay(500); Serial.print(F(".")); } if(zero == 0){ error = 1; Serial.println(F(".")); Serial.println(F("No valid receiver signals found!!! (ERROR 1)")); } else Serial.println(F(" OK")); } //Register the min and max receiver values and exit when the sticks are back in the neutral position void register_min_max(){ byte zero = 0; low_channel_1 = receiver_input_channel_1; low_channel_2 = receiver_input_channel_2; low_channel_3 = receiver_input_channel_3; low_channel_4 = receiver_input_channel_4; while(receiver_input_channel_1 < center_channel_1 + 20 && receiver_input_channel_1 > center_channel_1 - 20)delay(250); Serial.println(F("Measuring endpoints....")); while(zero < 15){ if(receiver_input_channel_1 < center_channel_1 + 20 && receiver_input_channel_1 > center_channel_1 - 20)zero |= 0b00000001; if(receiver_input_channel_2 < center_channel_2 + 20 && receiver_input_channel_2 > center_channel_2 - 20)zero |= 0b00000010; if(receiver_input_channel_3 < center_channel_3 + 20 && receiver_input_channel_3 > center_channel_3 - 20)zero |= 0b00000100; if(receiver_input_channel_4 < center_channel_4 + 20 && receiver_input_channel_4 > center_channel_4 - 20)zero |= 0b00001000; if(receiver_input_channel_1 < low_channel_1)low_channel_1 = receiver_input_channel_1; if(receiver_input_channel_2 < low_channel_2)low_channel_2 = receiver_input_channel_2; if(receiver_input_channel_3 < low_channel_3)low_channel_3 = receiver_input_channel_3; if(receiver_input_channel_4 < low_channel_4)low_channel_4 = receiver_input_channel_4; if(receiver_input_channel_1 > high_channel_1)high_channel_1 = receiver_input_channel_1; if(receiver_input_channel_2 > high_channel_2)high_channel_2 = receiver_input_channel_2; if(receiver_input_channel_3 > high_channel_3)high_channel_3 = receiver_input_channel_3; if(receiver_input_channel_4 > high_channel_4)high_channel_4 = receiver_input_channel_4; delay(100); } } //Check if the angular position of a gyro axis is changing within 10 seconds void check_gyro_axes(byte movement){ byte trigger_axis = 0; float gyro_angle_roll, gyro_angle_pitch, gyro_angle_yaw; //Reset all axes gyro_angle_roll = 0; gyro_angle_pitch = 0; gyro_angle_yaw = 0; gyro_signalen(); timer = millis() + 10000; while(timer > millis() && gyro_angle_roll > -30 && gyro_angle_roll < 30 && gyro_angle_pitch > -30 && gyro_angle_pitch < 30 && gyro_angle_yaw > -30 && gyro_angle_yaw < 30){ gyro_signalen(); if(type == 2 || type == 3){ gyro_angle_roll += gyro_roll * 0.00007; //0.00007 = 17.5 (md/s) / 250(Hz) gyro_angle_pitch += gyro_pitch * 0.00007; gyro_angle_yaw += gyro_yaw * 0.00007; } if(type == 1){ gyro_angle_roll += gyro_roll * 0.0000611; // 0.0000611 = 1 / 65.5 (LSB degr/s) / 250(Hz) gyro_angle_pitch += gyro_pitch * 0.0000611; gyro_angle_yaw += gyro_yaw * 0.0000611; } delayMicroseconds(3700); //Loop is running @ 250Hz. +/-300us is used for communication with the gyro } //Assign the moved axis to the orresponding function (pitch, roll, yaw) if((gyro_angle_roll < -30 || gyro_angle_roll > 30) && gyro_angle_pitch > -30 && gyro_angle_pitch < 30 && gyro_angle_yaw > -30 && gyro_angle_yaw < 30){ gyro_check_byte |= 0b00000001; if(gyro_angle_roll < 0)trigger_axis = 0b10000001; else trigger_axis = 0b00000001; } if((gyro_angle_pitch < -30 || gyro_angle_pitch > 30) && gyro_angle_roll > -30 && gyro_angle_roll < 30 && gyro_angle_yaw > -30 && gyro_angle_yaw < 30){ gyro_check_byte |= 0b00000010; if(gyro_angle_pitch < 0)trigger_axis = 0b10000010; else trigger_axis = 0b00000010; } if((gyro_angle_yaw < -30 || gyro_angle_yaw > 30) && gyro_angle_roll > -30 && gyro_angle_roll < 30 && gyro_angle_pitch > -30 && gyro_angle_pitch < 30){ gyro_check_byte |= 0b00000100; if(gyro_angle_yaw < 0)trigger_axis = 0b10000011; else trigger_axis = 0b00000011; } if(trigger_axis == 0){ error = 1; Serial.println(F("No angular motion is detected in the last 10 seconds!!! (ERROR 4)")); } else if(movement == 1)roll_axis = trigger_axis; if(movement == 2)pitch_axis = trigger_axis; if(movement == 3)yaw_axis = trigger_axis; } //This routine is called every time input 8, 9, 10 or 11 changed state ISR(PCINT0_vect){ current_time = micros(); //Channel 1========================================= if(PINB & B00000001){ //Is input 8 high? if(last_channel_1 == 0){ //Input 8 changed from 0 to 1 last_channel_1 = 1; //Remember current input state timer_1 = current_time; //Set timer_1 to current_time } } else if(last_channel_1 == 1){ //Input 8 is not high and changed from 1 to 0 last_channel_1 = 0; //Remember current input state receiver_input_channel_1 = current_time - timer_1; //Channel 1 is current_time - timer_1 } //Channel 2========================================= if(PINB & B00000010 ){ //Is input 9 high? if(last_channel_2 == 0){ //Input 9 changed from 0 to 1 last_channel_2 = 1; //Remember current input state timer_2 = current_time; //Set timer_2 to current_time } } else if(last_channel_2 == 1){ //Input 9 is not high and changed from 1 to 0 last_channel_2 = 0; //Remember current input state receiver_input_channel_2 = current_time - timer_2; //Channel 2 is current_time - timer_2 } //Channel 3========================================= if(PINB & B00000100 ){ //Is input 10 high? if(last_channel_3 == 0){ //Input 10 changed from 0 to 1 last_channel_3 = 1; //Remember current input state timer_3 = current_time; //Set timer_3 to current_time } } else if(last_channel_3 == 1){ //Input 10 is not high and changed from 1 to 0 last_channel_3 = 0; //Remember current input state receiver_input_channel_3 = current_time - timer_3; //Channel 3 is current_time - timer_3 } //Channel 4========================================= if(PINB & B00001000 ){ //Is input 11 high? if(last_channel_4 == 0){ //Input 11 changed from 0 to 1 last_channel_4 = 1; //Remember current input state timer_4 = current_time; //Set timer_4 to current_time } } else if(last_channel_4 == 1){ //Input 11 is not high and changed from 1 to 0 last_channel_4 = 0; //Remember current input state receiver_input_channel_4 = current_time - timer_4; //Channel 4 is current_time - timer_4 } } //Intro subroutine void intro(){ Serial.println(F("*****************************************************")); delay(1500); Serial.println(F("")); Serial.println(F("Your")); delay(500); Serial.println(F(" Multicopter")); delay(500); Serial.println(F(" Flight")); delay(500); Serial.println(F(" Controller")); delay(1000); Serial.println(F("")); Serial.println(F("QUARDCOPTER")); Serial.println(F("")); Serial.println(F("*****************************************************")); delay(1500); Serial.println(F("ALL THE BEST")); Serial.println(F("")); Serial.println(F("Have fun!")); }
9b8fbf33a7e0b250e8108f315e49e444f30a7983
04d4eac5203b5e9ced91918a7b9aa1819b00d2af
/Zoo_Managment_System - part 3/Giraffe.cpp
c845aeb8df63fa8d90496b71301ca4b29d84f202
[]
no_license
ZoharBergman/C-third-part
a5044cf52330a851257f012f2a4afeb0ac535e46
16f65cb6313de43f7da232f73b44c22fe18e9a68
refs/heads/master
2021-07-12T09:28:29.822512
2017-10-14T19:06:01
2017-10-14T19:06:01
106,165,776
0
0
null
null
null
null
UTF-8
C++
false
false
278
cpp
#include "Giraffe.h" Giraffe::Giraffe(const string& name, float weight, int birthYear, float lengthOfNeck) : Animal(weight, birthYear, name), lengthOfNeck(lengthOfNeck){} void Giraffe::toOs(ostream& os) const { os << ", Length of neck: " << this->getLengthOfNeck(); }
dbca746849c11a94652d6be16756de01682141fb
cdcae8b800d79a82bac3d0370038a02a0653f8ad
/SysProgram_using_CPP/1_FILE_Manage/Assignment_3/Assign3_11/accept.cpp
0c10f3a1d075e1bd571a1575bf76525e6b64a064
[]
no_license
Yuvraj-Takey/Linux-System-Programming
8739733f83216b0c217230c0ea394f9d9b04bd4d
fc28e2652204499bc2a6f0ba0a25bdc388662393
refs/heads/master
2021-10-11T15:35:40.253950
2019-01-27T20:04:04
2019-01-27T20:04:04
103,016,697
0
1
null
null
null
null
UTF-8
C++
false
false
1,682
cpp
#include "header.h" class Accept { private: int iFD_In; char my_File[MAXNAME]; public: struct stat fileStat; Accept(const char*); ~Accept(); void GetMaxFile(); }; Accept::Accept(const char* file_Name) { strcpy(my_File,file_Name); iFD_In = 0; // create new file for output if((iFD_In = open(my_File, O_RDONLY)) == INVALID_FD) { cout<<"[SORRY]: Unable to open give file"<<endl<<"Reason: "<<strerror(errno)<<endl; } else { cout<<"[DONE]: file is successfully opened"<<endl; } } void Accept::GetMaxFile() { if(iFD_In == INVALID_FD) { return; } FILEINFO stInfo; char cCheck; int iRet_Val = 0, iSize = 0; cout<<"[SEARCHING]: File name having size greater than 10 bytes.."<<endl<<endl; // traverse till input file not complete while((iRet_Val = read(iFD_In,&stInfo,sizeof(stInfo))) > 0) { iSize = stInfo.iFileLength; if(iSize > MAX_BYTE) // MAX_BYTE is the macro of '10' { cCheck = TRUE; cout<<iSize<<" Byte \t\t\t:"<<stInfo.cName<<endl; } lseek(iFD_In,iSize,SEEK_CUR); // skip the "file_data" section from Input file memset(&stInfo,0,sizeof(stInfo)); // flush the memory } if (!cCheck) { cout<<"[SORRY]: Unable to get file name having size greater then 10 byte"<<endl; } cout<<"[DONE]: Execution finished"<<endl; } Accept::~Accept() { if(iFD_In != INVALID_FD) { close(iFD_In); // close the file } } int main(int argc, char* argv[]) { if(argc != ARG_LIMIT) { cout<<"[ERROR]: Incorrect parameters,\nyour argument count is not matched"<<endl; cout<<"[Usage]: <executable_name> <file_name>"<<endl; return STATUS_FAILURE; } Accept obj(argv[1]); obj.GetMaxFile(); return STATUS_SUCCESS; }
7886d715691ec260dc5e1e3e33069717c329d273
8b1d01173776d1e70dcde89de90bc366f1c8d03f
/hellman_example/sort_on_disk.hpp
0a9543ef43888502b71f5e1f7dd58147ca971c8a
[ "Apache-2.0" ]
permissive
timkuijsten/chiapos
ccb7aefb3606dda8419215fcf22850cb95ed9962
2f889124e005d384ea29e05f9939264656dc3adc
refs/heads/main
2023-04-06T07:28:36.741151
2021-03-18T17:00:13
2021-03-18T18:58:07
349,409,767
0
0
Apache-2.0
2021-03-19T12:06:34
2021-03-19T12:06:33
null
UTF-8
C++
false
false
34,623
hpp
// Copyright 2018 Chia Network Inc // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef SRC_CPP_SORT_ON_DISK_HPP_ #define SRC_CPP_SORT_ON_DISK_HPP_ #define BUF_SIZE 262144 #include <vector> #include <iostream> #include <fstream> #include <string> #include <algorithm> #include "./util.hpp" class SortOnDiskUtils { public: /* * Given an array of bytes, extracts an unsigned 64 bit integer from the given * index, to the given index. */ inline static uint64_t ExtractNum(uint8_t* bytes, uint32_t len_bytes, uint32_t begin_bits, uint32_t take_bits) { uint32_t start_index = begin_bits / 8; uint32_t end_index; if ((begin_bits + take_bits) / 8 > len_bytes - 1) { take_bits = (len_bytes * 8) - begin_bits; } end_index = (begin_bits + take_bits) / 8; assert(take_bits <= 64); uint64_t sum = bytes[start_index] & ((1 << (8 - (begin_bits % 8))) - 1); for (uint32_t i = start_index + 1; i <= end_index; i++) { sum = (sum << 8) + bytes[i]; } return sum >> (8 - ((begin_bits + take_bits) % 8)); } /* * Like memcmp, but only compares starting at a certain bit. */ inline static int MemCmpBits(uint8_t* left_arr, uint8_t* right_arr, uint32_t len, uint32_t bits_begin) { uint32_t start_byte = bits_begin / 8; uint8_t mask = ((1 << (8 - (bits_begin % 8))) - 1); if ((left_arr[start_byte] & mask) != (right_arr[start_byte] & mask)) { return (left_arr[start_byte] & mask) - (right_arr[start_byte] & mask); } for (uint32_t i = start_byte + 1; i < len; i++) { if (left_arr[i] != right_arr[i]) return left_arr[i] - right_arr[i]; } return 0; } // The number of memory entries required to do the custom SortInMemory algorithm, given the total number of entries to be sorted. inline static uint64_t RoundSize(uint64_t size) { size *= 2; uint64_t result = 1; while (result < size) result *= 2; return result + 50; } inline static bool IsPositionEmpty(uint8_t* memory, uint32_t entry_len) { for (uint32_t i = 0; i < entry_len; i++) if (memory[i] != 0) return false; return true; } }; class Disk { public: virtual void Read(uint64_t begin, uint8_t* memcache, uint32_t length) = 0; virtual void Write(uint64_t begin, uint8_t* memcache, uint32_t length) = 0; virtual std::iostream* ReadHandle(uint64_t begin) = 0; virtual std::iostream* WriteHandle(uint64_t begin) = 0; }; class FileDisk : public Disk { public: inline explicit FileDisk(std::string filename) { Initialize(filename); } inline void Close() { f_.close(); } inline void Read(uint64_t begin, uint8_t* memcache, uint32_t length) { // Seek, read, and replace into memcache f_.seekg(begin); f_.read(reinterpret_cast<char*>(memcache), length); } inline void Write(uint64_t begin, uint8_t* memcache, uint32_t length) { // Seek and write from memcache f_.seekp(begin); f_.write(reinterpret_cast<char*>(memcache), length); } /** * Returns a read handle at the specified byte offset from the beginning */ inline std::iostream* ReadHandle(uint64_t begin) { f_.seekg(begin); return &f_; } inline std::iostream* WriteHandle(uint64_t begin) { f_.seekp(begin); return &f_; } inline std::string GetFileName() const { return filename_; } private: void Initialize(std::string filename) { filename_ = filename; // Creates the file if it does not exist std::fstream f; f.open(filename, std::fstream::out | std::fstream::app); f << std::flush; f.close(); // Opens the file for reading and writing f_.open(filename, std::fstream::out | std::fstream::in | std::fstream::binary); // Sets the buffer for batched reading and writing f_.rdbuf()->pubsetbuf(buf_, BUF_SIZE); if (!f_.is_open()) { std::cout << "Fialed to open" << std::endl; throw std::string("File not opened correct"); } } std::string filename_; char buf_[BUF_SIZE]; std::fstream f_; }; // Store values bucketed by their leading bits into an array-like memcache. // The memcache stores stacks of values, one for each bucket. // The stacks are broken into segments, where each segment has content // all from the same bucket, and a 4 bit pointer to its previous segment. // The most recent segment is the head segment of that bucket. // Additionally, empty segments form a linked list: 4 bit pointers of // empty segments point to the next empty segment in the memcache. // Each segment has size entries_per_seg * entry_len + 4, and consists of: // [4 bit pointer to segment id] + [entries of length entry_len]* class BucketStore { public: inline BucketStore(uint8_t* mem, uint64_t mem_len, uint32_t entry_len, uint32_t bits_begin, uint32_t bucket_log, uint64_t entries_per_seg) { mem_ = mem; mem_len_ = mem_len; entry_len_ = entry_len; bits_begin_ = bits_begin; bucket_log_ = bucket_log; entries_per_seg_ = entries_per_seg; for (uint64_t i = 0; i < pow(2, bucket_log); i++) { bucket_sizes_.push_back(0); } seg_size_ = 4 + entry_len_ * entries_per_seg; length_ = floor(mem_len / seg_size_); // Initially, all the segments are empty, store them as a linked list, // where a segment points to the next empty segment. for (uint64_t i = 0; i < length_; i++) { SetSegmentId(i, i + 1); } // The head of the empty segments list. first_empty_seg_id_ = 0; // Initially, all bucket lists contain no segments in it. for (uint64_t i = 0; i < bucket_sizes_.size(); i++) { bucket_head_ids_.push_back(length_); bucket_head_counts_.push_back(0); } } inline void SetSegmentId(uint64_t i, uint64_t v) { Util::IntToFourBytes(mem_ + i * seg_size_, v); } inline uint64_t GetSegmentId(uint64_t i) { return Util::FourBytesToInt(mem_ + i * seg_size_); } // Get the first empty position from the head segment of bucket b. inline uint64_t GetEntryPos(uint64_t b) { return bucket_head_ids_[b] * seg_size_ + 4 + bucket_head_counts_[b] * entry_len_; } inline void Audit() { uint64_t count = 0; uint64_t pos = first_empty_seg_id_; while (pos != length_) { ++count; pos = GetSegmentId(pos); } for (uint64_t pos2 : bucket_head_ids_) { while (pos2 != length_) { ++count; pos2 = GetSegmentId(pos2); } } assert(count == length_); } inline uint64_t NumFree() { uint64_t used = GetSegmentId(first_empty_seg_id_); return (bucket_sizes_.size() - used) * entries_per_seg_; } inline bool IsEmpty() { for (uint64_t s : bucket_sizes_) { if (s > 0) return false; } return true; } inline bool IsFull() { return first_empty_seg_id_ == length_; } inline void Store(uint8_t* new_val, uint64_t new_val_len) { assert(new_val_len == entry_len_); assert(first_empty_seg_id_ != length_); uint64_t b = SortOnDiskUtils::ExtractNum(new_val, new_val_len, bits_begin_, bucket_log_); bucket_sizes_[b] += 1; // If bucket b contains no segments, or the head segment of bucket b is full, append a new segment. if (bucket_head_ids_[b] == length_ || bucket_head_counts_[b] == entries_per_seg_) { uint64_t old_seg_id = bucket_head_ids_[b]; // Set the head of the bucket b with the first empty segment (thus appending a new segment to the bucket b). bucket_head_ids_[b] = first_empty_seg_id_; // Move the first empty segment to the next empty one // (which is linked with the first empty segment using id, since empty segments // form a linked list). first_empty_seg_id_ = GetSegmentId(first_empty_seg_id_); // Link the head of bucket b to the previous head (in the linked list, // the segment that will follow the new head will be the previous head). SetSegmentId(bucket_head_ids_[b], old_seg_id); bucket_head_counts_[b] = 0; } // Get the first empty position inside the head segment and write the entry there. uint64_t pos = GetEntryPos(b); memcpy(mem_ + pos, new_val, entry_len_); bucket_head_counts_[b] += 1; } inline uint64_t MaxBucket() { uint64_t max_bucket_size = bucket_sizes_[0]; uint64_t max_index = 0; for (uint64_t i = 1; i < bucket_sizes_.size(); i++) { if (bucket_sizes_[i] > max_bucket_size) { max_bucket_size = bucket_sizes_[i]; max_index = i; } } return max_index; } inline std::vector<uint64_t> BucketsBySize() { // Lukasz Wiklendt (https://stackoverflow.com/questions/1577475/c-sorting-and-keeping-track-of-indexes) std::vector<uint64_t> idx(bucket_sizes_.size()); iota(idx.begin(), idx.end(), 0); sort(idx.begin(), idx.end(), [this](uint64_t i1, uint64_t i2) {return bucket_sizes_[i1] > bucket_sizes_[i2];}); return idx; } // Similar to how 'Bits' class works, appends an entry to the entries list, such as all entries are stored into 128-bit blocks. // Bits class was avoided since it consumes more time than a uint128_t array. void AddBucketEntry(uint8_t* big_endian_bytes, uint64_t num_bytes, uint16_t size_bits, uint128_t* entries, uint64_t& cnt) { assert(size_bits / 8 >= num_bytes); uint16_t extra_space = size_bits - num_bytes * 8; uint64_t init_cnt = cnt; uint16_t last_size = 0; while (extra_space >= 128) { extra_space -= 128; entries[cnt++] = 0; last_size = 128; } if (extra_space > 0) { entries[cnt++] = 0; last_size = extra_space; } for (uint64_t i = 0; i < num_bytes; i += 16) { uint128_t val = 0; uint8_t bucket_size = 0; for (uint64_t j = i; j < i + 16 && j < num_bytes; j++) { val = (val << 8) + big_endian_bytes[j]; bucket_size += 8; } if (cnt == init_cnt || last_size == 128) { entries[cnt++] = val; last_size = bucket_size; } else { uint8_t free_space = 128 - last_size; if (free_space >= bucket_size) { entries[cnt - 1] = (entries[cnt - 1] << bucket_size) + val; last_size += bucket_size; } else { uint8_t suffix_size = bucket_size - free_space; uint128_t mask = (static_cast<uint128_t>(1)) << suffix_size; mask--; uint128_t suffix = (val & mask); uint128_t prefix = (val >> suffix_size); entries[cnt - 1] = (entries[cnt - 1] << free_space) + prefix; entries[cnt++] = suffix; last_size = suffix_size; } } } } // Extracts 'number_of_entries' from bucket b and empties memory of those from BucketStore. inline uint128_t* BucketHandle(uint64_t b, uint64_t number_of_entries, uint64_t& final_size) { uint32_t L = entry_len_; uint32_t entry_size = L / 16; if (L % 16) ++entry_size; uint64_t cnt = 0; uint64_t cnt_entries = 0; // Entry bytes will be compressed into uint128_t array. uint128_t* entries = new uint128_t[number_of_entries * entry_size]; // As long as we have a head segment in bucket b... while (bucket_head_ids_[b] != length_) { // ...extract the entries from it. uint64_t start_pos = GetEntryPos(b) - L; uint64_t end_pos = start_pos - bucket_head_counts_[b] * L; for (uint64_t pos = start_pos; pos > end_pos + L; pos -=L) { bucket_sizes_[b] -= 1; bucket_head_counts_[b] -= 1; AddBucketEntry(mem_ + pos, L, L*8, entries, cnt); ++cnt_entries; if (cnt_entries == number_of_entries) { final_size = cnt; return entries; } } // Move to the next segment from bucket b. uint64_t next_full_seg_id = GetSegmentId(bucket_head_ids_[b]); // The processed segment becomes now an empty segment. SetSegmentId(bucket_head_ids_[b], first_empty_seg_id_); first_empty_seg_id_ = bucket_head_ids_[b]; // Change the head of bucket b. bucket_head_ids_[b] = next_full_seg_id; if (next_full_seg_id == length_) { bucket_head_counts_[b] = 0; } else { bucket_head_counts_[b] = entries_per_seg_; } if (start_pos != end_pos) { bucket_sizes_[b] -= 1; AddBucketEntry(mem_ + end_pos + L, L, L*8, entries, cnt); ++cnt_entries; if (cnt_entries == number_of_entries) { final_size = cnt; return entries; } } } assert(bucket_sizes_[b] == 0); final_size = cnt; return entries; } private: uint8_t* mem_; uint64_t mem_len_; uint32_t bits_begin_; uint32_t entry_len_; uint32_t bucket_log_; uint64_t entries_per_seg_; std::vector<uint64_t> bucket_sizes_; uint64_t seg_size_; uint64_t length_; uint64_t first_empty_seg_id_; std::vector<uint64_t> bucket_head_ids_; std::vector<uint64_t> bucket_head_counts_; }; class Sorting { public: static void EntryToBytes(uint128_t* entries, uint32_t start_pos, uint32_t end_pos, uint8_t last_size, uint8_t buffer[]) { uint8_t shift = Util::ByteAlign(last_size) - last_size; uint128_t val = entries[end_pos - 1] << (shift); uint16_t cnt = 0; uint8_t iterations = last_size / 8; if (last_size % 8) iterations++; for (uint8_t i = 0; i < iterations; i++) { buffer[cnt++] = (val & 0xff); val >>= 8; } if (end_pos - start_pos >= 2) { for (int32_t i = end_pos - 2; i >= (int32_t) start_pos; i--) { uint128_t val = entries[i]; for (uint8_t j = 0; j < 16; j++) { buffer[cnt++] = (val & 0xff); val >>= 8; } } } uint32_t left = 0, right = cnt - 1; while (left <= right) { std::swap(buffer[left], buffer[right]); left++; right--; } } inline static void SortOnDisk(Disk& disk, uint64_t disk_begin, uint64_t spare_begin, uint32_t entry_len, uint32_t bits_begin, std::vector<uint64_t> bucket_sizes, uint8_t* mem, uint64_t mem_len, int quicksort = 0) { uint64_t length = floor(mem_len / entry_len); uint64_t total_size = 0; // bucket_sizes[i] represent how many entries start with the prefix i (from 0000 to 1111). // i.e. bucket_sizes[10] represents how many entries start with the prefix 1010. for (auto& n : bucket_sizes) total_size += n; uint64_t N_buckets = bucket_sizes.size(); assert(disk_begin + total_size * entry_len <= spare_begin); if (bits_begin >= entry_len * 8) { return; } // If we have enough memory to sort the entries, do it. // How much an entry occupies in memory, without the common prefix, in SortInMemory algorithm. uint32_t entry_len_memory = entry_len - bits_begin / 8; // Are we in Compress phrase 1 (quicksort=1) or is it the last bucket (quicksort=2)? Perform quicksort if it // fits in the memory (SortInMemory algorithm won't always perform well). if (quicksort > 0 && total_size <= length) { disk.Read(disk_begin, mem, total_size * entry_len); QuickSort(mem, entry_len, total_size, bits_begin); disk.Write(disk_begin, mem, total_size * entry_len); return ; } // Do SortInMemory algorithm if it fits in the memory // (number of entries required * entry_len_memory) <= total memory available if (quicksort == 0 && SortOnDiskUtils::RoundSize(total_size) * entry_len_memory <= mem_len) { SortInMemory(disk, disk_begin, mem, entry_len, total_size, bits_begin); return; } std::vector<uint64_t> bucket_begins; bucket_begins.push_back(0); uint64_t total = 0; // The beginning of each bucket. The first entry from bucket i will always be written on disk on position // disk_begin + bucket_begins[i] * entry_len, the second one will be written on position // disk_begin + (bucket_begins[i] + 1) * entry_len and so on. This way, when all entries are written back // to disk, they will be sorted by the first 4 bits (the bucket) at the end. for (uint64_t i = 0; i < N_buckets - 1; i++) { total += bucket_sizes[i]; bucket_begins.push_back(total); } uint32_t bucket_log = Util::GetSizeBits(N_buckets) - 1; // Move the beginning of each bucket into the spare. uint64_t spare_written = 0; std::vector<uint64_t> consumed_per_bucket(N_buckets, 0); // The spare stores about 5 * N_buckets * len(mem) entries. uint64_t unit = floor(length / static_cast<double>(N_buckets) * 5); for (uint32_t i = 0; i < bucket_sizes.size(); i++) { uint64_t b_size = bucket_sizes[i]; uint64_t to_consume = std::min(unit, b_size); while (to_consume > 0) { uint64_t next_amount = std::min(length, to_consume); disk.Read(disk_begin + (bucket_begins[i] + consumed_per_bucket[i]) * entry_len, mem, next_amount * entry_len); disk.Write(spare_begin + spare_written * entry_len, mem, next_amount * entry_len); to_consume -= next_amount; spare_written += next_amount; consumed_per_bucket[i] += next_amount; } } uint64_t spare_consumed = 0; BucketStore bstore = BucketStore(mem, mem_len, entry_len, bits_begin, bucket_log, 100); std::iostream* handle = disk.ReadHandle(spare_begin); uint8_t* buf = new uint8_t[entry_len]; // Populate BucketStore from spare. while (!bstore.IsFull() && spare_consumed < spare_written) { handle->read(reinterpret_cast<char*>(buf), entry_len); bstore.Store(buf, entry_len); spare_consumed += 1; } // subbuckets[i][j] represents how many entries starting with prefix i has the next prefix equal to j. // When we'll call recursively for all entries starting with the prefix i, bucket_sizes[] becomes // subbucket_sizes[i]. std::vector<uint64_t> written_per_bucket(N_buckets, 0); std::vector<std::vector<uint64_t> > subbucket_sizes; for (uint64_t i = 0; i < N_buckets; i++) { std::vector<uint64_t> col(N_buckets, 0); subbucket_sizes.push_back(col); } while (!bstore.IsEmpty()) { // Write from BucketStore the heaviest buckets first (so it empties faster) for (uint64_t b : bstore.BucketsBySize()) { if (written_per_bucket[b] >= consumed_per_bucket[b]) { continue; } // Write the content of the bucket in the right spot (beginning of the bucket + number of entries already written // in that bucket). handle = disk.WriteHandle(disk_begin + (bucket_begins[b] + written_per_bucket[b]) * entry_len); uint64_t size; // Don't extract from the bucket more entries than the difference between read and written entries (this avoids // overwritting entries that were not read yet). uint128_t* bucket_handle = bstore.BucketHandle(b, consumed_per_bucket[b] - written_per_bucket[b], size); uint32_t entry_size = entry_len / 16; uint8_t last_size = (entry_len * 8) % 128; if (last_size == 0) last_size = 128; if (entry_len % 16) ++entry_size; for (uint64_t i = 0; i < size; i += entry_size) { EntryToBytes(bucket_handle, i, i + entry_size, last_size, buf); handle->write(reinterpret_cast<char*>(buf), entry_len); written_per_bucket[b] += 1; subbucket_sizes[b][SortOnDiskUtils::ExtractNum(buf, entry_len, bits_begin + bucket_log, bucket_log)] += 1; } delete[] bucket_handle; } // Advance the read handle into buckets and move read entries to BucketStore. We read first from buckets // with the smallest difference between read and write handles. The goal is to increase the smaller differences. // The bigger the difference is, the better, as in the next step, we'll be able to extract more from the BucketStore. std::vector<uint64_t> idx(bucket_sizes.size()); iota(idx.begin(), idx.end(), 0); sort(idx.begin(), idx.end(), [&consumed_per_bucket, &written_per_bucket](uint64_t i1, uint64_t i2) { return (consumed_per_bucket[i1] - written_per_bucket[i1] < consumed_per_bucket[i2] - written_per_bucket[i2]); }); bool broke = false; for (uint64_t i : idx) { if (consumed_per_bucket[i] == bucket_sizes[i]) { continue; } std::iostream* handle2 = disk.ReadHandle( disk_begin + (bucket_begins[i] + consumed_per_bucket[i]) * entry_len); while (!bstore.IsFull() && consumed_per_bucket[i] < bucket_sizes[i]) { handle2->read(reinterpret_cast<char*>(buf), entry_len); bstore.Store(buf, entry_len); consumed_per_bucket[i] += 1; } if (bstore.IsFull()) { broke = true; break; } } // If BucketStore still isn't full and we've read all entries from buckets, start populating from the spare space. if (!broke) { std::iostream* handle3 = disk.ReadHandle( spare_begin + spare_consumed * entry_len); while (!bstore.IsFull() && spare_consumed < spare_written) { handle3->read(reinterpret_cast<char*>(buf), entry_len); bstore.Store(buf, entry_len); spare_consumed += 1; } } } delete[] buf; // The last bucket that contains at least one entry. uint8_t last_bucket = N_buckets - 1; while (last_bucket > 0) { bool all_zero = true; for (uint64_t i = 0; i < N_buckets; i++) if (subbucket_sizes[last_bucket][i] != 0) all_zero = false; if (!all_zero) break; last_bucket--; } for (uint32_t i = 0; i < bucket_sizes.size(); i++) { // Do we have to do quicksort for the new partition? int new_quicksort; // If quicksort = 1, means all partitions must do the quicksort as their final step. // Preserve that for the new call. if (quicksort == 1) { new_quicksort = 1; } else { // If this is not the last bucket, we use the SortInMemoryAlgorithm if (i != last_bucket) { new_quicksort = 0; } else { // ..otherwise, do quicksort, as the last bucket isn't guaranteed to have uniform distribution. new_quicksort = 2; } } // At this point, all entries are sorted in increasing order by their buckets (4 bits prefixes). // We recursively sort each chunk, this time starting with the next 4 bits to determine the buckets. // (i.e. firstly, we sort entries starting with 0000, then entries starting with 0001, ..., then entries // starting with 1111, at the end producing the correct ordering). SortOnDisk(disk, disk_begin + bucket_begins[i] * entry_len, spare_begin, entry_len, bits_begin + bucket_log, subbucket_sizes[i], mem, mem_len, new_quicksort); } } inline static void SortInMemory(Disk& disk, uint64_t disk_begin, uint8_t* memory, uint32_t entry_len, uint64_t num_entries, uint32_t bits_begin) { uint32_t entry_len_memory = entry_len - bits_begin / 8; uint64_t memory_len = SortOnDiskUtils::RoundSize(num_entries) * entry_len_memory; uint8_t* swap_space = new uint8_t[entry_len]; uint8_t* buffer = new uint8_t[BUF_SIZE]; uint8_t* common_prefix = new uint8_t[bits_begin / 8]; uint64_t bucket_length = 0; bool set_prefix = false; // The number of buckets needed (the smallest power of 2 greater than 2 * num_entries). while ((1ULL << bucket_length) < 2 * num_entries) bucket_length++; memset(memory, 0, sizeof(memory[0])*memory_len); std::iostream* read_handle = disk.ReadHandle(disk_begin); uint64_t buf_size = 0; uint64_t buf_ptr = 0; uint64_t swaps = 0; for (uint64_t i = 0; i < num_entries; i++) { if (buf_size == 0) { // If read buffer is empty, read from disk and refill it. buf_size = std::min((uint64_t) BUF_SIZE / entry_len, num_entries - i); buf_ptr = 0; read_handle->read(reinterpret_cast<char*>(buffer), buf_size * entry_len); if (set_prefix == false) { // We don't store the common prefix of all entries in memory, instead just append it every time // in write buffer. memcpy(common_prefix, buffer, bits_begin / 8); set_prefix = true; } } buf_size--; // First unique bits in the entry give the expected position of it in the sorted array. // We take 'bucket_length' bits starting with the first unique one. uint64_t pos = SortOnDiskUtils::ExtractNum(buffer + buf_ptr, entry_len, bits_begin, bucket_length) * entry_len_memory; // As long as position is occupied by a previous entry... while (SortOnDiskUtils::IsPositionEmpty(memory + pos, entry_len_memory) == false && pos < memory_len) { // ...store there the minimum between the two and continue to push the higher one. if (SortOnDiskUtils::MemCmpBits(memory + pos, buffer + buf_ptr + bits_begin / 8, entry_len_memory, 0) > 0) { // We always store the entry without the common prefix. memcpy(swap_space, memory + pos, entry_len_memory); memcpy(memory + pos, buffer + buf_ptr + bits_begin / 8, entry_len_memory); memcpy(buffer + buf_ptr + bits_begin / 8, swap_space, entry_len_memory); swaps++; } pos += entry_len_memory; } // Push the entry in the first free spot. memcpy(memory + pos, buffer + buf_ptr + bits_begin / 8, entry_len_memory); buf_ptr += entry_len; } uint64_t entries_written = 0; buf_size = 0; memset(buffer, 0, BUF_SIZE); std::iostream* write_handle = disk.WriteHandle(disk_begin); // Search the memory buffer for occupied entries. for (uint64_t pos = 0; entries_written < num_entries && pos < memory_len; pos += entry_len_memory) { if (SortOnDiskUtils::IsPositionEmpty(memory + pos, entry_len_memory) == false) { // We've fount an entry. if (buf_size + entry_len >= BUF_SIZE) { // Write buffer is full, write it and clean it. write_handle->write(reinterpret_cast<char*>(buffer), buf_size); entries_written += buf_size / entry_len; buf_size = 0; } // Write first the common prefix of all entries. memcpy(buffer + buf_size, common_prefix, bits_begin / 8); // Then the stored entry itself. memcpy(buffer + buf_size + bits_begin / 8, memory + pos, entry_len_memory); buf_size += entry_len; } } // We still have some entries left in the write buffer, write them as well. if (buf_size > 0) { write_handle->write(reinterpret_cast<char*>(buffer), buf_size); entries_written += buf_size / entry_len; } assert(entries_written == num_entries); delete[] swap_space; delete[] buffer; delete[] common_prefix; } inline static void QuickSort(uint8_t* memory, uint32_t entry_len, uint64_t num_entries, uint32_t bits_begin) { uint64_t memory_len = (uint64_t)entry_len * num_entries; uint8_t * pivot_space = new uint8_t[entry_len]; QuickSortInner(memory, memory_len, entry_len, bits_begin, 0, num_entries, pivot_space); delete[] pivot_space; } inline static void CheckSortOnDisk(Disk& disk, uint64_t disk_begin, uint64_t spare_begin, uint32_t entry_len, uint32_t bits_begin, std::vector<uint64_t> bucket_sizes, uint8_t* mem, uint64_t mem_len, bool quicksort = false) { uint64_t length = floor(mem_len / entry_len); uint64_t total_size = 0; for (auto& n : bucket_sizes) total_size += n; cout << "CheckSortOnDisk entry_len: " << entry_len << " length: " << length << " total size: " << total_size << endl; for(uint64_t chunkindex=0;chunkindex<(total_size+length-1)/length;chunkindex++) { disk.Read(disk_begin+(chunkindex*length*entry_len), mem, length * entry_len); uint64_t i=1; while(((chunkindex*length+i)<total_size)&&(i<length)) { if((chunkindex*length+i)%1000000==0) cout << (chunkindex*length+i) << ": " << Util::HexStr(mem + i * entry_len, entry_len) << endl; if(SortOnDiskUtils::MemCmpBits(mem + (i - 1) * entry_len, mem + i * entry_len, entry_len, 0) >= 0) { cout << "Bad sort!" << endl; } i++; } } cout << "CheckSortOnDisk OK" << endl; } private: inline static void QuickSortInner(uint8_t* memory, uint64_t memory_len, uint32_t L, uint32_t bits_begin, uint64_t begin, uint64_t end, uint8_t* pivot_space) { if (end - begin <= 5) { for (uint64_t i = begin + 1; i < end; i++) { uint64_t j = i; memcpy(pivot_space, memory + i * L, L); while (j > begin && SortOnDiskUtils::MemCmpBits(memory + (j - 1) * L, pivot_space, L, bits_begin) > 0) { memcpy(memory + j * L, memory + (j - 1) * L, L); j--; } memcpy(memory + j * L, pivot_space, L); } return ; } uint64_t lo = begin; uint64_t hi = end - 1; memcpy(pivot_space, memory + (hi * L), L); bool left_side = true; while (lo < hi) { if (left_side) { if (SortOnDiskUtils::MemCmpBits(memory + lo * L, pivot_space, L, bits_begin) < 0) { ++lo; } else { memcpy(memory + hi * L, memory + lo * L, L); --hi; left_side = false; } } else { if (SortOnDiskUtils::MemCmpBits(memory + hi * L, pivot_space, L, bits_begin) > 0) { --hi; } else { memcpy(memory + lo * L, memory + hi * L, L); ++lo; left_side = true; } } } memcpy(memory + lo * L, pivot_space, L); if (lo - begin <= end - lo) { QuickSortInner(memory, memory_len, L, bits_begin, begin, lo, pivot_space); QuickSortInner(memory, memory_len, L, bits_begin, lo + 1, end, pivot_space); } else { QuickSortInner(memory, memory_len, L, bits_begin, lo + 1, end, pivot_space); QuickSortInner(memory, memory_len, L, bits_begin, begin, lo, pivot_space); } } }; #endif // SRC_CPP_SORT_ON_DISK_HPP_
34181fb3980b541450984d184b096d5b0cbaa766
6478a03d65fe7e8c418c28e561cfa4f830fac972
/DirectX11EngineMK/StringHelper.h
12f2d203e0ce4bc275b055549d35b89c3b14d73b
[]
no_license
minkipro/DirectX11EngineMK
353e4fa8e6abaf41f4dcc849e24f27657b73fc88
892e928e418ea8c3e4b858c6c70678540269d7d3
refs/heads/master
2023-01-14T09:32:45.663205
2020-11-16T22:58:08
2020-11-16T22:58:08
303,265,602
0
0
null
null
null
null
UTF-8
C++
false
false
308
h
#pragma once #include <string> using namespace std; class StringHelper { public: static wstring StringToWide(string str); static string WideToString(wstring wstr); static std::string GetDirectoryFromPath(const std::string& filepath); static std::string GetFileExtension(const std::string& filename); };
96ea7b120f225217cc32cfb00db16ac564bd3641
4ecb7575a8110037ea00774040250b2e9d8abe56
/Old_Version/map_0.1.1(Sky box, sphere)/Base_3D/HeightMap.cpp
1ac21d5137f13e7bd40d5967df56100ad1a09b19
[]
no_license
naknaknak/3D_Game_Portfolio
1e46c5dca1637749f26986193b0b620b1fdb3390
12f4f8a9346e9199be55b0e1ad3549c44752a514
refs/heads/master
2020-05-21T17:47:38.252543
2017-02-20T00:16:14
2017-02-20T00:16:14
63,951,817
0
0
null
null
null
null
UHC
C++
false
false
6,667
cpp
#include "stdafx.h" #include "HeightMap.h" HeightMap::HeightMap() { } HeightMap::~HeightMap() { } void HeightMap::Initialize(char* mapFileName, char* textureFileName, int bitNum/*= 8*/) { D3DXMatrixIdentity(&world); texture = TextureManager::GetTexture(textureFileName); ZeroMemory(&material, sizeof(D3DMATERIAL9)); material.Ambient = D3DXCOLOR(0.7f, 0.7f, 0.7f, 1.0f); material.Diffuse = D3DXCOLOR(0.7f, 0.7f, 0.7f, 1.0f); material.Specular = D3DXCOLOR(0.7f, 0.7f, 0.7f, 1.0f); char fullPath[256]; strcpy_s(fullPath, HEIGHTMAP_DIRECTORY); strcat_s(fullPath, mapFileName); FILE* fp = nullptr; fopen_s(&fp, fullPath, "rb"); if (fp != nullptr) { fseek(fp, 0, SEEK_END); vertexCount = ftell(fp); fseek(fp, 0, SEEK_SET); //총 픽셀 개수 보정 vertexSizeCount = vertexCount / (bitNum / 8); mapSize = (int)(sqrt(vertexSizeCount)); assert(vertexSizeCount == mapSize*mapSize && "가로세로길이가 동일해야 합니다."); std::vector<unsigned char> fileData; fileData.reserve(vertexSizeCount); if ( bitNum == 24 ) { int d[3]; for ( int i = 0; i < vertexSizeCount; ++i ) { d[0] = fgetc(fp); d[1] = fgetc(fp) << 8; d[2] = fgetc(fp) << 16; int a = d[0] | d[1] | d[2]; fileData.push_back(a); } } else if ( bitNum == 16 ) { int d[2]; for ( int i = 0; i < vertexSizeCount; ++i ) { d[0] = fgetc(fp); d[1] = fgetc(fp) << 8; int a = d[0] | d[1]; fileData.push_back(a); } } else { for ( int i = 0; i < vertexSizeCount; ++i ) { fileData.push_back(fgetc(fp)); } } fclose(fp); tileCount = mapSize - 1; std::vector<FVF_PositionNormalTexture> fvfVertex; fvfVertex.reserve(vertexSizeCount); vertex.reserve(vertexSizeCount); for (int z = 0; z < mapSize; ++z) { for (int x = 0; x < mapSize; ++x) { int index = z * mapSize + x; FVF_PositionNormalTexture v; v.pos = D3DXVECTOR3((float)x, fileData[index] * 0.2f, (float)-z); v.normal = D3DXVECTOR3(0,1,0); v.tex = D3DXVECTOR2(x / (float)tileCount, z / (float)tileCount); fvfVertex.push_back(v); vertex.push_back(v.pos); } } //노말값들 갱신 //필요한건 벡터 4개 //왼쪽, 오른쪽, 위쪽, 아래쪽 for (int z = 1; z < tileCount; ++z) { for (int x = 1; x < tileCount; ++x) { int index = z * mapSize + x; D3DXVECTOR3 left = vertex[index - 1]; D3DXVECTOR3 right = vertex[index + 1]; D3DXVECTOR3 front = vertex[index - mapSize]; D3DXVECTOR3 rear = vertex[index + mapSize]; D3DXVECTOR3 leftToRight = right - left; D3DXVECTOR3 frontToRear = rear - front; D3DXVECTOR3 normal; D3DXVec3Cross(&normal, &leftToRight, &frontToRear); D3DXVec3Normalize(&normal, &normal); fvfVertex[index].normal = normal; } } //버벡스 버퍼, 인덱스 버퍼 만들기 std::vector<DWORD> indexData; triangleCount = tileCount * tileCount * 2; indexData.reserve(triangleCount * 3); for (int z = 0; z < tileCount; ++z) { for (int x = 0; x < tileCount; ++x) { int _0 = (x + 0) + (z + 0) * mapSize; int _1 = (x + 1) + (z + 0) * mapSize; int _2 = (x + 0) + (z + 1) * mapSize; int _3 = (x + 1) + (z + 1) * mapSize; indexData.push_back(_0); indexData.push_back(_1); indexData.push_back(_2); indexData.push_back(_3); indexData.push_back(_2); indexData.push_back(_1); } } int bufferSize = fvfVertex.size() * sizeof(FVF_PositionNormalTexture); GameManager::GetDevice()->CreateVertexBuffer( bufferSize, 0, FVF_PositionNormalTexture::FVF, D3DPOOL_MANAGED, &vertexBuffer, nullptr); LPVOID pV; vertexBuffer->Lock(0, 0, &pV, 0); memcpy_s(pV, bufferSize, &fvfVertex[0], bufferSize); vertexBuffer->Unlock(); bufferSize = indexData.size() * sizeof(DWORD); GameManager::GetDevice()->CreateIndexBuffer( bufferSize, 0, D3DFMT_INDEX32, D3DPOOL_MANAGED, &indexBuffer, nullptr); LPVOID pI; indexBuffer->Lock(0, 0, &pI, 0); memcpy_s(pI, bufferSize, &indexData[0], bufferSize); indexBuffer->Unlock(); } } void HeightMap::Destroy() { SAFE_RELEASE(vertexBuffer); SAFE_RELEASE(indexBuffer); texture = nullptr; } void HeightMap::Render() { GameManager::GetDevice()->SetTransform(D3DTS_WORLD, &world); GameManager::GetDevice()->SetRenderState(D3DRS_LIGHTING, true); GameManager::GetDevice()->SetMaterial(&material); GameManager::GetDevice()->SetTexture(0, texture); GameManager::GetDevice()->SetFVF(FVF_PositionNormalTexture::FVF); GameManager::GetDevice()->SetStreamSource(0, vertexBuffer, 0, sizeof(FVF_PositionNormalTexture)); GameManager::GetDevice()->SetIndices(indexBuffer); GameManager::GetDevice()->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, 0, vertexSizeCount, 0, triangleCount); } bool HeightMap::GetHeight(float & outHeight, float x, float z) { D3DXVECTOR3 p0, p1, p2, p3; D3DXVECTOR3 pos; int ox = (int)x; int oz = (int)z; float cmpx = x - (float)ox; float cmpz = z - (float)oz; p0 = vertex.at((ox + 0) + (oz + 0) * mapSize); p1 = vertex.at((ox + 1) + (oz + 0) * mapSize); p2 = vertex.at((ox + 0) + (oz + 1) * mapSize); p3 = vertex.at((ox + 1) + (oz + 1) * mapSize); if ( cmpx + cmpz < 1 ) { //012 pos = p0 + (p1 - p0) * cmpx + (p2 - p0) * cmpz; } else { //321 pos = p0 + (p3 - p2) * cmpx + (p3 - p1) * cmpz; } outHeight = pos.y; return false; } bool HeightMap::GetHeight(D3DXVECTOR3 & pos, float x, float z) { if ( -mapSize + 2 > z || z > 0) return false; if ( 0 > x || x > mapSize - 2 ) return false; int ox = (int)x; int oz = (int)z * -1; D3DXVECTOR3 p0, p1, p2, p3; float cmpx = fabsf(x - (float)ox); float cmpz = fabsf(-1 * z - (float)oz); p0 = vertex.at((ox + 0) + (oz + 0) * mapSize); p1 = vertex.at((ox + 1) + (oz + 0) * mapSize); p2 = vertex.at((ox + 0) + (oz + 1) * mapSize); p3 = vertex.at((ox + 1) + (oz + 1) * mapSize); if ( cmpx + cmpz < 1 ) { //012 //pos = p0 + (p1 - p0) * cmpx + (p2 - p0) * cmpz; OnTheGround(pos, p0, p1, p2); } else { //321 //pos = p2 + (p1 - p2) * cmpx + (p3 - p2) * cmpz; //pos = p3 - (p1 - p3) * cmpx + (p2 - p3) * cmpz; OnTheGround(pos, p3, p1, p2); } return true; } bool HeightMap::OnTheGround(D3DXVECTOR3& pos, const D3DXVECTOR3& p0, const D3DXVECTOR3& p1, const D3DXVECTOR3& p2) { bool find = false; D3DXVECTOR3 rayStart(pos.x, 1000.0f, pos.z); D3DXVECTOR3 rayDirection(0, -1, 0); float u, v, distance; find = D3DXIntersectTri( &p0, &p1, &p2, &rayStart, &rayDirection, &u, &v, &distance) != 0; if ( find == true ) { pos.y = 1000.0f - distance; //pos = p0 + (p1 - p0) * u + (p2 - p0) * v; } return find; }
f67bb035b50dfc3c044c3a35887dd2a447f917c0
b762aedb82990dbc8883136e82f8f24d5e6b2bd1
/Day 12.cpp
2fc6bf176160092440f35665c785e7f1b9c4c578
[]
no_license
Ayush-KS/August-LeetCoding-Challenge
06701a8233d8ece31ba3a35fcc180f2d675d9e64
5ff6c6bc37c8a34edc26ff3da232070675b221ad
refs/heads/master
2022-12-08T15:04:02.363038
2020-09-05T11:57:56
2020-09-05T11:57:56
284,634,717
0
0
null
null
null
null
UTF-8
C++
false
false
494
cpp
// Pascal's Triangle II class Solution { public: vector<int> getRow(int rowIndex) { vector<int> output; output.push_back(1); for(int i = 1; i <= rowIndex; i++) { int temp = output[0]; for(int j = 1; j < output.size(); j++) { int newTemp = output[j]; output[j] = output[j] + temp; temp = newTemp; } output.push_back(1); } return output; } };
cc63cfe58a8b663f62bba97e3d543ae1ac6866f1
be4737ec5e569506a3beea5cdfedafdd778e32e1
/moduloadd.cpp
965789da18229e424a46809cc7cd00aa4a27e4dd
[]
no_license
Samykakkar/DSA-practice
8fd49c690f9c6af56437cb09475e7796538df77b
d10938f34e9467688f178b6570ccc740d3cc4dff
refs/heads/master
2023-07-24T22:10:26.953125
2021-09-06T09:26:00
2021-09-06T09:26:00
392,998,137
0
1
null
2021-08-13T10:46:25
2021-08-05T10:21:28
C++
UTF-8
C++
false
false
268
cpp
#include <iostream> using namespace std; int moduloAdd(long long a, long long b, long long M) { return ((a %M )+(b % M)) % M; } int main() { long int a= 1000, b=2000; int M=1000000007; cout<<"Modulo addition "<<moduloAdd(a,b,M); return 0; }
b5e1269bb8eb9df646d4da03813b89b5986f4848
346efbc9dbbb1d656fd579400530c0269dfce56d
/kattis/keytocrypto.cpp
6fe62ffdcc238f6a2afd8aeb50fb4445542360cd
[]
no_license
lmun/competitiveProgramingSolutions
1c362e6433fc985e371afe88f08277268c46afde
06d62240e2b3c58dd9ee72e41a78f7246d966652
refs/heads/master
2023-08-24T04:52:04.218922
2021-10-29T15:06:28
2021-10-29T15:06:28
167,073,540
0
0
null
null
null
null
UTF-8
C++
false
false
930
cpp
#include <bits/stdc++.h> #include <cstdio> #include <cstring> #include <cmath> #include <cstring> #include <complex> #define endl "\n" #define ll long long int #define vi vector<int> #define vll vector<ll> #define vvi vector < vi > #define pii pair<int,int> #define pll pair<long long, long long> #define mod 1000000007 #define inf 1000000000000000001; #define all(c) c.begin(),c.end() #define mp(x,y) make_pair(x,y) #define mem(a,val) memset(a,val,sizeof(a)) #define eb emplace_back #define f first #define s second using namespace std; int main() { std::ios::sync_with_stdio(false); string msg,key; cin >> msg >> key; // cin.ignore(); must be there when using getline(cin, s) char ori[1500]; int ks=key.size(); strncpy(ori,key.c_str(),ks); for(int i=0;i< (int)msg.size();i++){ ori[i+ks]=msg[i]-ori[i]+'A'; if(ori[i+ks]<65){ ori[i+ks]+=26; } } ori[msg.size()+ks]=0; cout << ori+ks << endl; return 0; }
a6f9709b52a85019ab0c091d8057673a16322ab5
533039f833fc90eacad10ecba6fb93635b781564
/Source/OnlineGame/Environment/Lantern.h
c76cfc8cb7d7f5181f3b42ee490286da5a312fbc
[]
no_license
Lordmatics/OnlineGame
5c6b4f501cefcba8fab6e0042df5daf2bb2a1130
0cb7511c32d1fcf5a43a06c3ebe0f627627e10e5
refs/heads/master
2021-01-11T07:32:25.100665
2017-04-27T21:54:26
2017-04-27T21:54:26
80,136,316
3
0
null
null
null
null
UTF-8
C++
false
false
1,035
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "GameFramework/Actor.h" #include "Lantern.generated.h" UCLASS() class ONLINEGAME_API ALantern : public AActor { GENERATED_BODY() private: UPROPERTY(VisibleDefaultsOnly, Category = "C++ Component") USceneComponent* MyRoot; UPROPERTY(VisibleDefaultsOnly, Category = "C++ Component") UStaticMeshComponent* MyLantern; /** Looped Flames or something*/ UPROPERTY(VisibleDefaultsOnly, Category = "C++ Component") UParticleSystemComponent* ParticleSystemComponent; // Can Edit Material in Code UMaterialInstanceDynamic* DynMaterial; // Name of Parameter I want to manipulate UPROPERTY(EditAnywhere, Category = "Dynamic Material") FName DynMaterialParam = FName("Emissive"); public: // Sets default values for this actor's properties ALantern(); // Called when the game starts or when spawned virtual void BeginPlay() override; // Called every frame virtual void Tick( float DeltaSeconds ) override; };
f652a4758a6547ba36d4655e8302b0939b463a28
42f82f560416cb9099e24da232154c4b3c038d38
/src/main.cpp
1e97195b70cbb5b19d5e9ac2fe8529265850abf6
[]
no_license
rdidukh/text-analizer
c020c95c9c77617c64350fb7145ece59485446bc
d39a46bde4e96de9e3b719e6c28a2a26cb39a9a4
refs/heads/master
2021-05-26T18:31:18.605180
2012-09-18T12:46:33
2012-09-18T12:46:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,661
cpp
#include <iostream> #include <fstream> #include <cstdlib> #include <cstdio> #include <map> #include <Utf8Char.h> #include <Utf8Charset.h> #include <Utf8RussianAlphabetCharset.h> using namespace std; struct DoubleCharStruct { unicode_t first; unicode_t second; int count; }; struct OneCharStruct { public: unicode_t first; int count; }; int main(int argc, char **argv) { std::ifstream infile; infile.open(argv[1], std::ifstream::in | std::ifstream::binary); if(infile.fail()) { std::cout << "Can not open file " << argv[1] << std::endl; exit(EXIT_FAILURE); } infile.clear(); Utf8RussianAlphabetCharset utf8charset(true); std::map<unicode_t, int> unicodemap; Utf8Char utf8char; while(!infile.eof()) { infile >> utf8char; //std::cout << utf8char << std::endl; if (utf8char.notutf8()) { std::cout << "NOT UTF ENCODING. STOP." << std::endl; infile.close(); exit(EXIT_FAILURE); break; } if(utf8char.empty()) { break; } unicode_t unicode = utf8charset.findgroup(utf8char.getUnicode()); if (unicode != (unicode_t)-1) { if(unicodemap.count(unicode) > 0) { unicodemap[unicode] += 1; } else { unicodemap[unicode] = 1; } } } infile.close(); std::vector<OneCharStruct> onecharVector; for(std::map<unicode_t, int>::iterator i = unicodemap.begin(); i != unicodemap.end(); ++i) { OneCharStruct ocs; ocs.first = i->first; ocs.count = i->second; std::vector<OneCharStruct>::iterator j; for(j = onecharVector.begin(); j != onecharVector.end(); ++j) if(ocs.count > j->count) break; if(j != onecharVector.end()) onecharVector.insert(j, ocs); else onecharVector.push_back(ocs); } /*for(std::map<unicode_t, int>::iterator i = unicodemap.begin(); i != unicodemap.end(); ++i) { //utf8char.setUnicode(i->first); std::cout << utf8charset.tostring(i->first) << ": " << i->second << std::endl; }*/ int all_ones = 0; for(std::vector<OneCharStruct>::iterator i = onecharVector.begin(); i != onecharVector.end(); ++i) all_ones += i->count; int output_limit = 50; for(std::vector<OneCharStruct>::iterator i = onecharVector.begin(); i != onecharVector.end(); ++i) { // if(output_limit < 1) break; output_limit--; std::cout << utf8charset.tostring(i->first) << " : " << i->count << " = " << (100*(double)i->count)/all_ones << "%" << std::endl; } /* std::ifstream infile; infile.open(argv[1], std::ifstream::in | std::ifstream::binary); if(infile.fail()) { std::cout << "Can not open file " << argv[1] << std::endl; exit(EXIT_FAILURE); } infile.clear(); Utf8RussianAlphabetCharset utf8charset(true); std::map<std::pair<unicode_t, unicode_t>, int> unicodemap; Utf8Char utf8char1, utf8char2; infile >> utf8char2; while(!infile.eof()) { utf8char1 = utf8char2; infile >> utf8char2; if (utf8char1.notutf8() || utf8char2.notutf8()) { std::cout << "NOT UTF ENCODING. STOP." << std::endl; infile.close(); exit(EXIT_FAILURE); //break; } if(utf8char1.empty() || utf8char2.empty()) break; unicode_t unicode1 = utf8charset.findgroup(utf8char1.getUnicode()); unicode_t unicode2 = utf8charset.findgroup(utf8char2.getUnicode()); if (unicode1 != (unicode_t)-1 && unicode2 != (unicode_t)-1) { std::pair<unicode_t, unicode_t> doublechar = std::make_pair(unicode1, unicode2); if(unicodemap.count(doublechar) > 0) { unicodemap[doublechar] += 1; } else { unicodemap[doublechar] = 1; } } } infile.close(); std::vector<DoubleCharStruct> doublecharVector; for(std::map<std::pair<unicode_t, unicode_t>, int>::iterator i = unicodemap.begin(); i != unicodemap.end(); ++i) { DoubleCharStruct dcs; dcs.first = i->first.first; dcs.second = i->first.second; dcs.count = i->second; std::vector<DoubleCharStruct>::iterator j; for(j = doublecharVector.begin(); j != doublecharVector.end(); ++j) if(dcs.count > j->count) break; if(j != doublecharVector.end()) doublecharVector.insert(j, dcs); else doublecharVector.push_back(dcs); } int all_doubles = 0; for(std::vector<DoubleCharStruct>::iterator i = doublecharVector.begin(); i != doublecharVector.end(); ++i) all_doubles += i->count; int output_limit = 50; for(std::vector<DoubleCharStruct>::iterator i = doublecharVector.begin(); i != doublecharVector.end(); ++i) { // if(output_limit < 1) break; output_limit--; std::cout << "( " << utf8charset.tostring(i->first) << ", " << utf8charset.tostring(i->second) << " ) = " << i->count << " = " << (100*(double)i->count)/all_doubles << "%" << std::endl; } */ return EXIT_SUCCESS; }
3b3d29dce9e17db0fb17d0e5e3805a5c8d5cadc0
e1ee7f74625d5a6e0cd7606a1d4f353693941c50
/mem.cpp
4d3bd1ff82fe9dfec5bca1ba842b177160451b29
[]
no_license
noopz/PwnAdventureHack
5cb9f5b773df3309408284e7ec6e7bc9e2d08ec7
5d3c4f0e0b1fcdae5174d32f05d1d3d7d2e58957
refs/heads/master
2022-11-10T23:48:05.441276
2020-07-03T00:52:35
2020-07-03T00:52:35
276,773,636
0
0
null
null
null
null
UTF-8
C++
false
false
1,410
cpp
#include "mem.h" // Not used for PA3 void mem::Patch(BYTE* dst, BYTE* src, unsigned int size) { DWORD oldprotect; VirtualProtect(dst, size, PAGE_EXECUTE_READWRITE, &oldprotect); memcpy(dst, src, size); VirtualProtect(dst, size, oldprotect, &oldprotect); } void mem::Nop(BYTE* dst, unsigned int size) { DWORD oldprotect; VirtualProtect(dst, size, PAGE_EXECUTE_READWRITE, &oldprotect); memset(dst, 0x90, size); VirtualProtect(dst, size, oldprotect, &oldprotect); } void mem::PatchEx(BYTE* dst, BYTE* src, unsigned int size, HANDLE hProcess) { DWORD oldprotect; VirtualProtectEx(hProcess, dst, size, PAGE_EXECUTE_READWRITE, &oldprotect); WriteProcessMemory(hProcess, dst, src, size, nullptr); VirtualProtectEx(hProcess, dst, size, oldprotect, &oldprotect); } void mem::NopEx(BYTE* dst, unsigned int size, HANDLE hProcess) { BYTE* nopArray = new BYTE[size]; memset(nopArray, 0x90, size); PatchEx(dst, nopArray, size, hProcess); delete[] nopArray; } // Reads through multi level pointers // Similar to what Cheat engine does when given multiple offsets from a base pointer // Useful when needing to traverse a MLPtr without having access to the classes/getters uintptr_t mem::FindDMAAddy(uintptr_t ptr, std::vector<unsigned int> offsets) { uintptr_t addr = ptr; for (unsigned int i = 0; i < offsets.size(); ++i) { addr = *(uintptr_t*)addr; addr += offsets[i]; } return addr; }