hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
5f3d6887aeba89c27f8cd0eaa2fe4b7d778f677d
1,206
cpp
C++
bistro/cron/CrontabItem.cpp
jiazerojia/bistro
95c8d9cf9786ff87d845d7732622a46d90de5f58
[ "BSD-3-Clause" ]
1
2021-05-19T23:02:04.000Z
2021-05-19T23:02:04.000Z
bistro/cron/CrontabItem.cpp
jiazerojia/bistro
95c8d9cf9786ff87d845d7732622a46d90de5f58
[ "BSD-3-Clause" ]
null
null
null
bistro/cron/CrontabItem.cpp
jiazerojia/bistro
95c8d9cf9786ff87d845d7732622a46d90de5f58
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "bistro/bistro/cron/CrontabItem.h" #include <memory> #include <stdexcept> #include <folly/dynamic.h> #include "bistro/bistro/cron/EpochCrontabItem.h" #include "bistro/bistro/cron/StandardCrontabItem.h" // Add stateful Cron support for more robustness, see README for a design. using namespace folly; using namespace std; namespace facebook { namespace bistro { unique_ptr<const CrontabItem> CrontabItem::fromDynamic( const dynamic& d, boost::local_time::time_zone_ptr tz) { if (!d.isObject()) { throw runtime_error("CrontabItem must be an object"); } if (d.find("epoch") != d.items().end()) { return unique_ptr<CrontabItem>(new detail_cron::EpochCrontabItem(d, tz)); } return unique_ptr<CrontabItem>(new detail_cron::StandardCrontabItem(d, tz)); } string CrontabItem::getPrintable() const { throw logic_error("getPrintable not implemented"); } }}
27.409091
79
0.733002
jiazerojia
5f3f4dbdbd0d86200cf91e34683a668528a77d4a
2,744
cpp
C++
models/Point.cpp
1Lorde/crypto
6138472c1fba850158502312001eaf6584aa255c
[ "MIT" ]
null
null
null
models/Point.cpp
1Lorde/crypto
6138472c1fba850158502312001eaf6584aa255c
[ "MIT" ]
null
null
null
models/Point.cpp
1Lorde/crypto
6138472c1fba850158502312001eaf6584aa255c
[ "MIT" ]
null
null
null
// // created by Vlad Savchuk on 11/12/2020. // #include <cmath> #include <ModularArithmetic.h> #include <NoSpecifiedEllipticCurveException.h> #include "Point.h" Point::Point(long long x, long long y) { this->name = "P"; this->x = x; this->y = y; this->ellipticCurve = nullptr; } Point::Point(std::string name, long long x, long long y) { this->name = name; this->x = x; this->y = y; } Point::Point(std::string name, long long int x, long long int y, EllipticCurve *curve) { this->name = name; this->x = x; this->y = y; this->ellipticCurve = curve; } Point operator+(Point p, Point q) { long long Xp = p.x; long long Yp = p.y; long long Xq = q.x; long long Yq = q.y; long long A, modulo; if (p.ellipticCurve != nullptr){ A = p.ellipticCurve->getA(); modulo = p.ellipticCurve->getP(); } else if (q.ellipticCurve != nullptr){ A = q.ellipticCurve->getA(); modulo = q.ellipticCurve->getP(); } else{ throw NoSpecifiedEllipticCurveException(); } long long S, Xr, Yr; if (Xp != Xq) { //condition (Xp != Xq) --> R = -(P + Q). S = (Yp - Yq) * ModularArithmetic::findInverseElement(Xp - Xq, modulo); S = ModularArithmetic::unsignedMod(S, modulo); Xr = pow(S, 2) - Xp - Xq; Yr = -Yp + S * (Xp - Xr); } else { if (Yp == -Yq) { //Condition (Yp = Yq = 0) --> P + P = O. return Point("O", 0, 0); } else if (Yp == Yq != 0) { //condition (Yp = Yq != 0) --> R = -(P + P) = -2P = -2Q. S = (3 * pow(Xp, 2) + A) * ModularArithmetic::findInverseElement(2 * Yp, modulo); S = ModularArithmetic::unsignedMod(S, modulo); Xr = pow(S, 2) - 2 * Xp; Yr = -Yp + S * (Xp - Xr); } } Xr = ModularArithmetic::unsignedMod(Xr, modulo); Yr = ModularArithmetic::unsignedMod(Yr, modulo); return Point("R", Xr, Yr, p.ellipticCurve); } Point operator*(long long k, Point p) { if (k == 0){ return Point("O", 0, 0); }else if (k == 1){ return p; }else if (k % 2 == 1){ return p + (k-1) * p; }else { return (k/2) * (p+p); } } bool Point::isOnEllipticCurve(EllipticCurve curve) { long long leftSide = ModularArithmetic::unsignedMod(pow(y, 2), curve.getP()); long long rightSide = ModularArithmetic::unsignedMod(pow(x, 3) + curve.getA() * x + curve.getB(), curve.getP()); if (leftSide == rightSide){ return true; } return false; } std::ostream &operator<<(std::ostream &os, const Point &point) { os << point.name << " = (" << point.x << ", " << point.y << ")."; return os; }
26.901961
116
0.529883
1Lorde
5f3f6e57bd25a9f84975ffcae87ddcc1b522466e
757
hpp
C++
Explit/Explit/sdk/interfaces/valve/i_base_client_dll.hpp
patrykkolodziej/Explit
155a35e4b8951764e6bedb8847d3196561a4255c
[ "MIT" ]
18
2019-05-09T10:24:53.000Z
2021-05-17T04:39:47.000Z
Explit/Explit/sdk/interfaces/valve/i_base_client_dll.hpp
danielkrupinski/Expl
74124b67361cd29dd34389d692e43df86f83d072
[ "MIT" ]
6
2019-05-09T16:26:01.000Z
2019-05-14T11:30:18.000Z
Explit/Explit/sdk/interfaces/valve/i_base_client_dll.hpp
patrykkolodziej/Explit
155a35e4b8951764e6bedb8847d3196561a4255c
[ "MIT" ]
8
2019-05-08T17:28:24.000Z
2021-03-25T09:52:44.000Z
#pragma once #include "i_global_vars.hpp" #include "../../misc/valve/client_class.hpp" #include "../../misc/valve/i_app_system.hpp" class i_base_client_dll { public: virtual int connect(createinterfacefn app_system_factory, i_global_vars_base *p_globals) = 0; virtual int disconnect(void) = 0; virtual int init(createinterfacefn app_system_factory, i_global_vars_base *p_globals) = 0; virtual void post_init() = 0; virtual void shutdown(void) = 0; virtual void level_init_pre_entity(char const* p_map_name) = 0; virtual void level_init_post_entity() = 0; virtual void level_shutdown(void) = 0; virtual client_class* get_all_classes(void) = 0; };
42.055556
107
0.667107
patrykkolodziej
5f3f78d4cc8e7c4b773fff444541a7cc366b55de
441
cpp
C++
modules/logic/src/Logic/Cv/gmLogicCvBase.cpp
GraphMIC/GraphMIC
8fc2aeb0143ee1292c6757f010fc9e8c68823e2b
[ "BSD-3-Clause" ]
43
2016-04-11T11:34:05.000Z
2022-03-31T03:37:57.000Z
modules/logic/src/Logic/Cv/gmLogicCvBase.cpp
kevinlq/GraphMIC
8fc2aeb0143ee1292c6757f010fc9e8c68823e2b
[ "BSD-3-Clause" ]
1
2016-05-17T12:58:16.000Z
2016-05-17T12:58:16.000Z
modules/logic/src/Logic/Cv/gmLogicCvBase.cpp
kevinlq/GraphMIC
8fc2aeb0143ee1292c6757f010fc9e8c68823e2b
[ "BSD-3-Clause" ]
14
2016-05-13T20:23:16.000Z
2021-12-20T10:33:19.000Z
#include "gmLogicCvBase.hpp" namespace gm { namespace Logic { namespace Cv { Base::Base(const QString& name) : Logic::Base("cv", name) { log_trace(Log::New); this->setRunnable(true); this->setUseTimer(true); } Base::~Base() { log_trace(Log::Del); } } } }
19.173913
69
0.394558
GraphMIC
5f414de234732722d05c50fc338e610a8d84e190
2,363
hpp
C++
y2018/utils/udpClientServer.hpp
valkyrierobotics/vision2018
aa82e936c5481b7cc43a46ff5f6e68702c2166c2
[ "BSD-2-Clause" ]
2
2016-08-06T06:21:02.000Z
2017-01-10T05:45:13.000Z
y2018/utils/udpClientServer.hpp
valkyrierobotics/vision2018
aa82e936c5481b7cc43a46ff5f6e68702c2166c2
[ "BSD-2-Clause" ]
1
2017-04-15T20:54:59.000Z
2017-04-15T20:54:59.000Z
y2018/utils/udpClientServer.hpp
valkyrierobotics/vision2018
aa82e936c5481b7cc43a46ff5f6e68702c2166c2
[ "BSD-2-Clause" ]
3
2016-07-30T06:19:55.000Z
2017-02-07T01:55:05.000Z
// UDP Client Server -- send/receive UDP packets // Copyright (C) 2013 Made to Order Software Corp. // // 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, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef UDP_CLIENT_SERVER_H #define UDP_CLIENT_SERVER_H #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdexcept> #include <errno.h> #include <stdio.h> namespace udp_client_server { class udp_client_server_runtime_error : public std::runtime_error { public: udp_client_server_runtime_error(const char *w) : std::runtime_error(w) {} }; class udp_client { public: udp_client(const std::string& addr, int port); ~udp_client(); int get_socket() const; int get_port() const; std::string get_addr() const; int send(const char *msg, size_t size); private: int f_socket; int f_port; std::string f_addr; struct addrinfo * f_addrinfo; }; class udp_server { public: udp_server(const std::string& addr, int port); ~udp_server(); int get_socket() const; int get_port() const; std::string get_addr() const; int recv(char *msg, size_t max_size); int timed_recv(char *msg, size_t max_size, int max_wait_ms); private: int f_socket; int f_port; std::string f_addr; struct addrinfo * f_addrinfo; }; } // namespace udp_client_server #endif // UDP_CLIENT_SERVER_H
29.5375
81
0.60474
valkyrierobotics
5f46daa42fe39ef1fe8b159c68bb772198b6bd95
195
hpp
C++
src/components/resource/VkMeshRes.hpp
wicast/CreviceEngine
2d49b51aad7c2c6984bccc2c0628e75dfc0462a7
[ "MIT" ]
10
2021-01-19T04:36:11.000Z
2021-09-17T08:37:21.000Z
src/components/resource/VkMeshRes.hpp
wicast/CreviceEngine
2d49b51aad7c2c6984bccc2c0628e75dfc0462a7
[ "MIT" ]
null
null
null
src/components/resource/VkMeshRes.hpp
wicast/CreviceEngine
2d49b51aad7c2c6984bccc2c0628e75dfc0462a7
[ "MIT" ]
1
2022-02-08T04:21:28.000Z
2022-02-08T04:21:28.000Z
#pragma once #include "common/Resource.h" #include "graphic/vk_render/resource/VkMesh.hpp" #include "stl/CreviceSharedPtr.h" struct VkMeshRes { RID rid; crevice::SharedPtr<VkMesh> mesh; };
17.727273
48
0.748718
wicast
5f4b0db7e754be422bc7951f5cf621ed8fab7015
3,458
cpp
C++
widgets/demos/ex-translucent-clock/clock.cpp
sfaure-witekio/qt-training-material
d166e4ed9cc5f5faab85b0337c5844c4cdcb206e
[ "BSD-3-Clause" ]
16
2017-01-11T17:28:03.000Z
2021-09-27T16:12:01.000Z
widgets/demos/ex-translucent-clock/clock.cpp
sfaure-witekio/qt-training-material
d166e4ed9cc5f5faab85b0337c5844c4cdcb206e
[ "BSD-3-Clause" ]
null
null
null
widgets/demos/ex-translucent-clock/clock.cpp
sfaure-witekio/qt-training-material
d166e4ed9cc5f5faab85b0337c5844c4cdcb206e
[ "BSD-3-Clause" ]
4
2017-03-17T02:44:32.000Z
2021-01-22T07:57:34.000Z
/************************************************************************* * * Copyright (c) 2016 The Qt Company * All rights reserved. * * See the LICENSE.txt file shipped along with this file for the license. * *************************************************************************/ #include <QtGui> #include <QtWidgets> #include "clock.h" Clock::Clock(QWidget *parent) : QWidget(parent, Qt::FramelessWindowHint | Qt::WindowSystemMenuHint) { QTimer *timer = new QTimer(this); connect(timer, &QTimer::timeout, this, static_cast<void (Clock::*)()>(&Clock::update)); timer->start(1000); QAction *quitAction = new QAction(tr("E&xit"), this); quitAction->setShortcut(tr("Ctrl+Q")); connect(quitAction, &QAction::triggered, qApp, &QApplication::quit); addAction(quitAction); setAttribute(Qt::WA_TranslucentBackground); setContextMenuPolicy(Qt::ActionsContextMenu); setToolTip(tr("Drag the clock with the left mouse button.\n" "Use the right mouse button to open a context menu.")); setWindowTitle(tr("Analog Clock")); } void Clock::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { dragPosition = event->globalPos() - frameGeometry().topLeft(); event->accept(); } } void Clock::mouseMoveEvent(QMouseEvent *event) { if (event->buttons() & Qt::LeftButton) { move(event->globalPos() - dragPosition); event->accept(); } } void Clock::paintEvent(QPaintEvent *) { static const QPoint hourHand[3] = { QPoint(7, 8), QPoint(-7, 8), QPoint(0, -40) }; static const QPoint minuteHand[3] = { QPoint(7, 8), QPoint(-7, 8), QPoint(0, -70) }; QColor hourColor(191, 0, 0); QColor minuteColor(0, 0, 191, 191); int side = qMin(width(), height()); QTime time = QTime::currentTime(); QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); painter.translate(width() / 2, height() / 2); QRadialGradient gradient(0.0, 0.0, side*0.5, 0.0, 0.0); gradient.setColorAt(0.0, QColor(255, 255, 255, 255)); gradient.setColorAt(0.1, QColor(255, 255, 255, 31)); gradient.setColorAt(0.7, QColor(255, 255, 255, 31)); gradient.setColorAt(0.8, QColor(0, 31, 0, 31)); gradient.setColorAt(0.9, QColor(255, 255, 255, 255)); gradient.setColorAt(1.0, QColor(255, 255, 255, 255)); painter.setPen(QColor(0, 0, 0, 32)); painter.setBrush(gradient); painter.drawEllipse(-side/2.0 + 1, -side/2.0 + 1, side - 2, side - 2); painter.scale(side / 200.0, side / 200.0); painter.setPen(Qt::NoPen); painter.setBrush(hourColor); painter.save(); painter.rotate(30.0 * ((time.hour() + time.minute() / 60.0))); painter.drawConvexPolygon(hourHand, 3); painter.restore(); painter.setPen(hourColor); for (int i = 0; i < 12; ++i) { painter.drawLine(88, 0, 96, 0); painter.rotate(30.0); } painter.setPen(Qt::NoPen); painter.setBrush(minuteColor); painter.save(); painter.rotate(6.0 * (time.minute() + time.second() / 60.0)); painter.drawConvexPolygon(minuteHand, 3); painter.restore(); painter.setPen(minuteColor); for (int j = 0; j < 60; ++j) { if ((j % 5) != 0) painter.drawLine(92, 0, 96, 0); painter.rotate(6.0); } } QSize Clock::sizeHint() const { return QSize(200, 200); }
27.664
91
0.588201
sfaure-witekio
5f4d34bace6ee9cd7d0e379eafef77ab8e33cbb0
7,687
hh
C++
saphIR/include/ir/types.hh
balayette/saphIR-project
18da494ac21e5433fdf1c646be02c9bf25177d7d
[ "MIT" ]
14
2020-07-31T09:35:23.000Z
2021-11-15T11:18:35.000Z
saphIR/include/ir/types.hh
balayette/saphIR-project
18da494ac21e5433fdf1c646be02c9bf25177d7d
[ "MIT" ]
null
null
null
saphIR/include/ir/types.hh
balayette/saphIR-project
18da494ac21e5433fdf1c646be02c9bf25177d7d
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <vector> #include "utils/assert.hh" #include "utils/scoped.hh" #include "ir/ops.hh" #include "utils/symbol.hh" #include "utils/ref.hh" #define DEFAULT_SIZE (42) namespace mach { struct target; } namespace types { enum class type { INT, STRING, VOID, INVALID }; enum class signedness { INVALID, SIGNED, UNSIGNED }; struct ty { virtual ~ty() = default; ty(mach::target &target) : target_(target) {} virtual std::string to_string() const = 0; // t can be assigned to this virtual bool assign_compat(const ty *t) const = 0; // this can be cast to t virtual bool cast_compat(const ty *) const { return false; } // return the resulting type if this BINOP t is correctly typed, // nullptr otherwise. // TODO: This is where implicit type conversions would be handled virtual utils::ref<ty> binop_compat(ops::binop binop, const ty *t) const = 0; // return the resulting type if UNARYOP this is correctly typed, // nullptr otherwise. virtual utils::ref<ty> unaryop_type(ops::unaryop unaryop) const = 0; virtual ty *clone() const = 0; virtual bool size_modifier(size_t sz) { return sz == DEFAULT_SIZE; } virtual size_t size() const { UNREACHABLE("size() on type " + to_string() + " with no size"); } virtual signedness get_signedness() const { return signedness::INVALID; } virtual void set_signedness(types::signedness) { UNREACHABLE("Trying to set signedness on type {}", to_string()); } /* * Structs and arrays have a size which is different from the size * that the codegen uses to manipulate them: they're actually * pointers */ virtual size_t assem_size() const { return size(); } mach::target &target() { return target_; } protected: mach::target &target_; }; bool operator==(const ty *ty, const type &t); bool operator!=(const ty *ty, const type &t); struct builtin_ty : public ty { builtin_ty(mach::target &target); builtin_ty(type t, signedness is_signed, mach::target &target); builtin_ty(type t, size_t size, signedness is_signed, mach::target &target); std::string to_string() const override; bool assign_compat(const ty *t) const override; bool cast_compat(const ty *t) const override; utils::ref<ty> binop_compat(ops::binop binop, const ty *t) const override; utils::ref<ty> unaryop_type(ops::unaryop binop) const override; virtual builtin_ty *clone() const override { return new builtin_ty(ty_, size_, size_modif_, is_signed_, target_); } size_t size() const override; bool size_modifier(size_t sz) override; type ty_; virtual signedness get_signedness() const override { return is_signed_; } virtual void set_signedness(types::signedness sign) override { is_signed_ = sign; } private: builtin_ty(type t, size_t size, size_t size_modif, signedness is_signed, mach::target &target); size_t size_; size_t size_modif_; signedness is_signed_; }; struct pointer_ty : public ty { private: pointer_ty(utils::ref<ty> ty, unsigned ptr); public: pointer_ty(utils::ref<ty> ty); std::string to_string() const override; bool assign_compat(const ty *t) const override; bool cast_compat(const ty *t) const override; utils::ref<ty> binop_compat(ops::binop binop, const ty *t) const override; utils::ref<ty> unaryop_type(ops::unaryop binop) const override; virtual pointer_ty *clone() const override { return new pointer_ty(ty_, ptr_); } virtual signedness get_signedness() const override { return ty_->get_signedness(); } size_t size() const override; size_t pointed_size() const; utils::ref<ty> ty_; unsigned ptr_; }; bool is_scalar(const ty *ty); utils::ref<ty> deref_pointer_type(utils::ref<ty> ty); bool is_integer(const ty *ty); struct composite_ty : public ty { composite_ty(mach::target &target) : ty(target) {} }; struct array_ty : public composite_ty { array_ty(utils::ref<types::ty> type, size_t n); std::string to_string() const override; size_t size() const override; bool assign_compat(const ty *t) const override; bool cast_compat(const ty *t) const override; utils::ref<ty> binop_compat(ops::binop binop, const ty *t) const override; utils::ref<ty> unaryop_type(ops::unaryop binop) const override; virtual array_ty *clone() const override { return new array_ty(ty_, n_); } virtual signedness get_signedness() const override { return signedness::UNSIGNED; } virtual size_t assem_size() const override { return 8; } utils::ref<types::ty> ty_; size_t n_; }; struct braceinit_ty : public composite_ty { braceinit_ty(const std::vector<utils::ref<types::ty>> &types); std::string to_string() const override; bool assign_compat(const ty *t) const override; utils::ref<ty> binop_compat(ops::binop binop, const ty *t) const override; utils::ref<ty> unaryop_type(ops::unaryop binop) const override; virtual braceinit_ty *clone() const override { return new braceinit_ty(types_); } std::vector<utils::ref<types::ty>> types_; }; struct struct_ty : public composite_ty { struct_ty(const symbol &name, const std::vector<symbol> &names, const std::vector<utils::ref<types::ty>> &types); std::string to_string() const override; bool assign_compat(const ty *t) const override; utils::ref<ty> binop_compat(ops::binop binop, const ty *t) const override; utils::ref<ty> unaryop_type(ops::unaryop binop) const override; virtual struct_ty *clone() const override { return new struct_ty(name_, names_, types_); } virtual size_t assem_size() const override { return 8; } std::optional<size_t> member_index(const symbol &name); size_t member_offset(const symbol &name); utils::ref<ty> member_ty(const symbol &name); size_t size() const override; virtual signedness get_signedness() const override { // structs behave as pointers return signedness::UNSIGNED; } std::vector<utils::ref<types::ty>> types_; symbol name_; std::vector<symbol> names_; private: size_t size_; }; struct fun_ty : public ty { fun_ty(utils::ref<types::ty> ret_ty, const std::vector<utils::ref<types::ty>> &arg_tys, bool variadic); std::string to_string() const override; bool assign_compat(const ty *t) const override; utils::ref<ty> binop_compat(ops::binop binop, const ty *t) const override; utils::ref<ty> unaryop_type(ops::unaryop binop) const override; virtual fun_ty *clone() const override { return new fun_ty(ret_ty_, arg_tys_, variadic_); } virtual signedness get_signedness() const override { return signedness::INVALID; } virtual size_t assem_size() const override { return 8; } utils::ref<types::ty> ret_ty_; std::vector<utils::ref<types::ty>> arg_tys_; bool variadic_; }; /* * The parser outputs named_ty everywhere a type is used, and they are replaced * by pointers to actual types during semantic analysis. * This is necessary because of type declarations that the parser doesn't track. */ struct named_ty : public ty { named_ty(const symbol &name, mach::target &target, size_t sz = DEFAULT_SIZE); std::string to_string() const override; bool assign_compat(const ty *t) const override; utils::ref<ty> binop_compat(ops::binop binop, const ty *t) const override; utils::ref<ty> unaryop_type(ops::unaryop binop) const override; virtual named_ty *clone() const override { return new named_ty(name_, target_, sz_); } size_t size() const override; symbol name_; private: int sz_; }; utils::ref<ty> concretize_type(utils::ref<ty> &t, utils::scoped_map<symbol, utils::ref<ty>> tmap); utils::ref<fun_ty> normalize_function_pointer(utils::ref<ty> ty); } // namespace types
24.877023
80
0.712372
balayette
5f4e977688d2c5ad1e3983e8f2baa255ffa0e0e3
1,208
cpp
C++
algorithm/OPG/test/OPGTest.cpp
Zx55/compiler-principle
31c4dda19fdd7e48bbd616e29cf6f8ea28ea1b5b
[ "MIT" ]
null
null
null
algorithm/OPG/test/OPGTest.cpp
Zx55/compiler-principle
31c4dda19fdd7e48bbd616e29cf6f8ea28ea1b5b
[ "MIT" ]
null
null
null
algorithm/OPG/test/OPGTest.cpp
Zx55/compiler-principle
31c4dda19fdd7e48bbd616e29cf6f8ea28ea1b5b
[ "MIT" ]
null
null
null
/* * LexParser.h * Test of OPG Parser. * Copyright (c) zx5. All rights reserved. */ #define CATCH_CONFIG_MAIN #include <iostream> #include <fstream> #include <sstream> #include <string> #include "../OPG.h" #include "../../../include/catch.hpp" using namespace std; using namespace Compiler; const string TEST_FILE_PATH = "compiler-principle/oj/OPG/test/o"; const int TEST_FILE_TOTAL = 2; string parse(int no) { auto inFile = ifstream(TEST_FILE_PATH + to_string(no) + "/in.txt"); int t; OPG grammar; string line; stringstream ss; inFile >> grammar; auto parser = Parser(grammar); for (inFile >> t, getline(inFile, line); t != 0; --t) { getline(inFile, line); if (parser.isValiad(line)) { ss << "T\n"; } else { ss << "F\n"; } } return ss.str(); } string ans(int no) { auto ansFile = ifstream(TEST_FILE_PATH + to_string(no) + "/ans.txt"); stringstream ss; string line; while (ansFile >> line) { ss << line << "\n"; } return ss.str(); } TEST_CASE("OPG Parser", "[opg]") { for (int i = 1; i <= TEST_FILE_TOTAL; ++i) { REQUIRE(parse(i) == ans(i)); } }
19.174603
73
0.575331
Zx55
5f50400050ef6c699fba96e7dd2fb852bc2ea6b4
186
cpp
C++
Dataset/Leetcode/train/58/223.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/58/223.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/58/223.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
class Solution { public: int XXX(string s) { stringstream it(s); string tmp; while (it >> tmp) { } return tmp.size(); } };
14.307692
27
0.424731
kkcookies99
5f519bc1c25c34290477e9ce07ed8842754151f5
10,370
cpp
C++
src/audio/CBasicSound.cpp
JackCarlson/Avara
2d79f6a21855759e427e13ee2d791257bc8c8c71
[ "MIT" ]
77
2016-10-30T18:37:14.000Z
2022-02-13T05:02:55.000Z
src/audio/CBasicSound.cpp
tra/Avara
5a6b5a4f2cf29e8b2ddf7dd3f422579f37a14dab
[ "MIT" ]
135
2018-09-09T06:46:04.000Z
2022-01-29T19:33:12.000Z
src/audio/CBasicSound.cpp
tra/Avara
5a6b5a4f2cf29e8b2ddf7dd3f422579f37a14dab
[ "MIT" ]
19
2018-09-09T02:02:46.000Z
2022-03-16T08:21:08.000Z
/* Copyright ©1994-1996, Juri Munkki All rights reserved. File: CBasicSound.c Created: Friday, December 23, 1994, 10:57 Modified: Tuesday, September 3, 1996, 21:27 */ #include "CBasicSound.h" #include "CSoundHub.h" #include "CSoundMixer.h" #include <assert.h> void CBasicSound::Release() { if (itsHub) { if (motionLink) itsHub->ReleaseLink(motionLink); if (controlLink) itsHub->ReleaseLink(controlLink); itsHub->Restock(this); } } void CBasicSound::SetLoopCount(short count) { loopCount[0] = loopCount[1] = count; } void CBasicSound::SetRate(Fixed theRate) { // Not applicable } Fixed CBasicSound::GetSampleRate() { return itsMixer->samplingRate; } void CBasicSound::SetSoundLength(Fixed seconds) { int numSamples; numSamples = FMul(seconds >> 8, GetSampleRate() >> 8); numSamples -= sampleLen; if (numSamples > 0 && loopEnd > loopStart) { loopCount[0] = numSamples / (loopEnd - loopStart); loopCount[1] = loopCount[0]; } else { loopCount[0] = 0; loopCount[1] = 0; } } void CBasicSound::Start() { itsMixer->AddSound(this); } void CBasicSound::SetVolume(Fixed vol) { masterVolume = vol; volumes[0] = masterVolume >> (17 - VOLUMEBITS); volumes[1] = volumes[0]; } void CBasicSound::SetDirectVolumes(Fixed vol0, Fixed vol1) { volumes[0] = vol0 >> (17 - VOLUMEBITS); volumes[1] = vol1 >> (17 - VOLUMEBITS); } void CBasicSound::StopSound() { stopNow = true; } void CBasicSound::CheckSoundLink() { SoundLink *aLink; Fixed *s, *d; Fixed timeConversion; Fixed t; aLink = motionLink; timeConversion = itsMixer->timeConversion; s = aLink->nSpeed; d = aLink->speed; *d++ = FMul(*s++, timeConversion); *d++ = FMul(*s++, timeConversion); *d++ = FMul(*s++, timeConversion); s = aLink->nLoc; d = aLink->loc; *d++ = *s++; *d++ = *s++; *d++ = *s++; s = aLink->speed; d = aLink->loc; t = aLink->t; *d++ -= *s++ * t; *d++ -= *s++ * t; *d++ -= *s++ * t; aLink->meta = metaNoData; } void CBasicSound::SetSoundLink(SoundLink *linkPtr) { if (linkPtr) linkPtr->refCount++; if (motionLink) itsHub->ReleaseLink(motionLink); motionLink = linkPtr; } void CBasicSound::SetControlLink(SoundLink *linkPtr) { if (linkPtr) linkPtr->refCount++; if (controlLink) itsHub->ReleaseLink(controlLink); controlLink = linkPtr; } void CBasicSound::Reset() { motionLink = NULL; controlLink = NULL; itsSamples = NULL; sampleLen = 0; sampleData = NULL; loopStart = 0; loopEnd = 0; loopCount[0] = loopCount[1] = 0; stopNow = false; volumeMax = VOLUMERANGE >> 1; distanceDelay = true; } void CBasicSound::UseSamplePtr(Sample *samples, int numSamples) { currentCount[0].i = 0; currentCount[0].f = 0; currentCount[1].i = 0; currentCount[1].f = 0; sampleLen = numSamples; sampleData = samples; loopStart = 0; loopEnd = 0; loopCount[0] = loopCount[1] = 0; // Don't loop. } void CBasicSound::UseSamples(SampleHeaderHandle theSample) { if (theSample) { itsSamples = theSample; UseSamplePtr(sizeof(SampleHeader) + (Sample *)*theSample, (*theSample)->len); loopStart = (*itsSamples)->loopStart; loopEnd = (*itsSamples)->loopEnd; loopCount[0] = loopCount[1] = (*itsSamples)->loopCount; } else { UseSamplePtr(NULL, 0); } } void CBasicSound::CalculatePosition(int t) { CSoundMixer *m; SoundLink *s; short i; m = itsMixer; s = motionLink; squareAcc[0] = squareAcc[1] = 0; for (i = 0; i < 3; i++) { relPos[i] = s->loc[i] - m->motion.loc[i] + (s->speed[i] - m->motion.speed[i]) * t; FSquareAccumulate(relPos[i], squareAcc); } if (0x007Fffff < (unsigned int)squareAcc[0]) dSquare = 0x7FFFffff; else dSquare = ((squareAcc[0] & 0x00FFFFFF) << 8) | ((squareAcc[1] & 0xFF000000) >> 24); } void CBasicSound::SanityCheck() { if (loopStart == loopEnd) { loopCount[0] = loopCount[1] = 0; } } void CBasicSound::FirstFrame() { SanityCheck(); if (motionLink && distanceDelay) { int delta; if (motionLink->meta == metaNewData) CheckSoundLink(); CalculatePosition(itsMixer->frameStartTime); delta = FMul(FSqroot(squareAcc), itsMixer->distanceToSamples); currentCount[0].i -= delta; currentCount[1].i -= delta; } } void CBasicSound::CalculateMotionVolume() { Fixed rightDot; CSoundMixer *m = itsMixer; Fixed adjustedVolume; if (motionLink->meta == metaNewData) CheckSoundLink(); CalculatePosition(m->frameStartTime); if (dSquare == 0) dSquare = m->distanceAdjust >> 2; adjustedVolume = FMulDivNZ(masterVolume, m->distanceAdjust, dSquare); if (adjustedVolume > m->maxAdjustedVolume) adjustedVolume = m->maxAdjustedVolume; if (m->stereo) { distance = FSqroot(squareAcc); if (distance > 0) { rightDot = FMul(relPos[0], m->rightVector[0]); rightDot += FMul(relPos[1], m->rightVector[1]); rightDot += FMul(relPos[2], m->rightVector[2]); rightDot = FDiv(rightDot, distance); } else { rightDot = 0; // Middle, if distance = 0 } if (m->strongStereo) { // "Hard" stereo effect for loudspeakers users. // Sound position LEFT MIDDLE RIGHT // Left channel 1.0 0.5 0.0 // Right channel 0.0 0.5 1.0 volumes[0] = FMul(FIX(1) - rightDot, adjustedVolume) >> (18 - VOLUMEBITS); volumes[1] = FMul(FIX(1) + rightDot, adjustedVolume) >> (18 - VOLUMEBITS); } else { // "Soft" stereo effect for headphones users. // Sound position LEFT MIDDLE RIGHT // Left channel 1.0 0.66 0.33 // Right channel 0.33 0.66 1.0 adjustedVolume /= 3; volumes[0] = FMul(FIX(2) - rightDot, adjustedVolume) >> (18 - VOLUMEBITS); volumes[1] = FMul(FIX(2) + rightDot, adjustedVolume) >> (18 - VOLUMEBITS); // With headphones, it is irritating, if one headphone is producing // sound (pressure) and the other one is not. For these cases, the // volume of the otherwise silent channel is set to 1 to avoid the problem. if (!volumes[0] ^ !volumes[1]) { if (!volumes[0]) volumes[0] = 1; if (!volumes[1]) volumes[1] = 1; } } balance = rightDot; } else { volumes[0] = adjustedVolume >> (17 - VOLUMEBITS); volumes[1] = volumes[0]; balance = 0; } if (volumes[0] > volumeMax) volumes[0] = volumeMax; if (volumes[1] > volumeMax) volumes[1] = volumeMax; } short CBasicSound::CalcVolume(short theChannel) { if (controlLink) { if (controlLink->meta == metaSuspend) return 0; else if (controlLink->meta == metaFade) { loopCount[0] = 0; loopCount[1] = 0; } } if (motionLink && motionLink->meta == metaFade) { loopCount[0] = 0; loopCount[1] = 0; } if (currentCount[0].i <= -itsMixer->soundBufferSize) { volumes[theChannel] = 0; } else if (motionLink && theChannel == 0) { CalculateMotionVolume(); } return volumes[theChannel]; } void CBasicSound::WriteFrame(short theChannel, short volumeAllowed) { Sample *s; WordSample *d; SampleConvert *converter; int thisCount; int remaining; int baseCount = currentCount[0].i; int loopCopy = loopCount[0]; converter = &itsMixer->volumeLookup[volumeAllowed - 1]; d = itsMixer->mixTo[theChannel]; if (baseCount >= 0) { thisCount = itsMixer->soundBufferSize; } else { d -= baseCount; thisCount = itsMixer->soundBufferSize + baseCount; baseCount = 0; } do { s = sampleData + baseCount; remaining = baseCount + thisCount - loopEnd; if (loopCopy && remaining > 0) { if (loopCopy > 0) // Negative loopCount will loop forever. loopCopy--; thisCount -= remaining; baseCount = loopStart; } else { remaining = 0; } if (thisCount + baseCount > sampleLen) { thisCount = sampleLen - baseCount; remaining = 0; } assert(0 && "port asm"); /* TODO: port asm { clr.w D0 move.l converter,A0 subq.w #1,thisCount bmi.s @nothing @loop move.b (s)+,D0 move.w 0(A0,D0.w*2),D1 add.w D1,(d)+ dbra thisCount,@loop @nothing } */ thisCount = remaining; } while (thisCount); } Boolean CBasicSound::EndFrame() { if (stopNow || (motionLink && motionLink->meta == metaKillNow) || (controlLink && controlLink->meta == metaKillNow)) { stopNow = true; } else { if (controlLink && controlLink->meta == metaSuspend) { return false; } if (loopCount[0]) { int thisCount = itsMixer->soundBufferSize; int remaining; do { if (loopCount[0]) { remaining = currentCount[0].i + thisCount - loopEnd; if (remaining > 0) { if (loopCount[0] > 0) // Negative loopCount will loop forever. loopCount[0]--; currentCount[0].i = loopStart; thisCount -= remaining; } else remaining = 0; } else remaining = 0; currentCount[0].i += thisCount; thisCount = remaining; } while (thisCount); } else { currentCount[0].i += itsMixer->soundBufferSize; } } if (loopCount[0] == 0 && currentCount[0].i >= sampleLen) stopNow = true; return stopNow; }
25.73201
91
0.548987
JackCarlson
34fc3eca1e3505b2d07896cb4ecee2a367e95d62
5,408
cpp
C++
src/core/renderer/shader.cpp
mdsitton/LudumDare38
afa00173cf245fef215aa10024bf397c01711f53
[ "BSD-2-Clause" ]
null
null
null
src/core/renderer/shader.cpp
mdsitton/LudumDare38
afa00173cf245fef215aa10024bf397c01711f53
[ "BSD-2-Clause" ]
1
2017-04-22T21:38:20.000Z
2017-04-22T21:38:20.000Z
src/core/renderer/shader.cpp
mdsitton/LudumDare38
afa00173cf245fef215aa10024bf397c01711f53
[ "BSD-2-Clause" ]
null
null
null
#include "config.hpp" #include <iostream> #include <stdexcept> #include <spdlog/spdlog.h> #include <glad/glad.h> #include "vfs.hpp" #include "shader.hpp" namespace ORCore { static std::shared_ptr<spdlog::logger> logger; static int _programCount = 0; Shader::Shader(ShaderInfo _info): info(_info) { logger = spdlog::get("default"); init_gl(); } void Shader::init_gl() { shader = glCreateShader(info.type); std::string data {read_file(info.path)}; const char *c_str = data.c_str(); glShaderSource(shader, 1, &c_str, nullptr); glCompileShader(shader); } Shader::~Shader() { glDeleteShader(shader); } void Shader::check_error() { GLint status; glGetShaderiv(shader, GL_COMPILE_STATUS, &status); // TODO - probably need to make a custom exception class for this.. if (status != GL_TRUE) { GLint length; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length); auto logData = std::make_unique<GLchar[]>(length+1); logData[length] = '\0'; // Make sure it is null terminated. glGetShaderInfoLog(shader, length, nullptr, logData.get()); logger->error(logData.get()); throw std::runtime_error("Shader compilation failed."); } else { logger->info("Shader compiled sucessfully."); } } ShaderProgram::ShaderProgram(Shader& vertex, Shader& fragment) : m_vertex(vertex), m_fragment(fragment) { logger = spdlog::get("default"); _programCount++; m_programID = _programCount; m_program = glCreateProgram(); glAttachShader(m_program, m_vertex.shader); glAttachShader(m_program, m_fragment.shader); glLinkProgram(m_program); } ShaderProgram::~ShaderProgram() { glDeleteProgram(m_program); } int ShaderProgram::get_id() { return m_programID; } void ShaderProgram::check_error() { // We want to check the compile/link status of the shaders all at once. // At some place that isn't right after the shader compilation step. // That way the drivers can better parallelize shader compilation. m_vertex.check_error(); m_fragment.check_error(); GLint status; glGetProgramiv(m_program, GL_LINK_STATUS, &status); // TODO - probably need to make a custom exception class for this.. if (status != GL_TRUE) { GLint length; glGetProgramiv(m_program, GL_INFO_LOG_LENGTH, &length); auto logData = std::make_unique<GLchar[]>(length+1); logData[length] = '\0'; // Make sure it is null terminated. glGetProgramInfoLog(m_program, length, nullptr, logData.get()); logger->error(logData.get()); throw std::runtime_error("Shader linkage failed."); } else { logger->info("Shader linked sucessfully."); } } void ShaderProgram::use() { glUseProgram(m_program); } void ShaderProgram::disuse() { glUseProgram(0); } int ShaderProgram::vertex_attribute(std::string name) { return glGetAttribLocation(m_program, name.c_str()); } int ShaderProgram::uniform_attribute(std::string name) { return glGetUniformLocation(m_program, name.c_str()); } void ShaderProgram::set_uniform(int uniform, int value) { glUniform1i(uniform, value); } void ShaderProgram::set_uniform(int uniform, float value) { glUniform1f(uniform, value); } void ShaderProgram::set_uniform(int uniform, const glm::vec2& value) { glUniform2fv(uniform, 1, &value[0]); } void ShaderProgram::set_uniform(int uniform, const glm::vec3& value) { glUniform3fv(uniform, 1, &value[0]); } void ShaderProgram::set_uniform(int uniform, const glm::vec4& value) { glUniform4fv(uniform, 1, &value[0]); } void ShaderProgram::set_uniform(int uniform, const glm::mat2& value) { glUniformMatrix2fv(uniform, 1, GL_FALSE, &value[0][0]); } void ShaderProgram::set_uniform(int uniform, const glm::mat3& value) { glUniformMatrix3fv(uniform, 1, GL_FALSE, &value[0][0]); } void ShaderProgram::set_uniform(int uniform, const glm::mat4& value) { glUniformMatrix4fv(uniform, 1, GL_FALSE, &value[0][0]); } void ShaderProgram::set_uniform(int uniform, const std::array<float, 2>& value) { glUniform2fv(uniform, 1, &value[0]); } void ShaderProgram::set_uniform(int uniform, const std::array<float, 3>& value) { glUniform3fv(uniform, 1, &value[0]); } void ShaderProgram::set_uniform(int uniform, const std::array<float, 4>& value) { glUniform4fv(uniform, 1, &value[0]); } void ShaderProgram::set_uniform(int uniform, const std::array<int, 2>& value) { glUniform2iv(uniform, 1, &value[0]); } void ShaderProgram::set_uniform(int uniform, const std::array<int, 3>& value) { glUniform3iv(uniform, 1, &value[0]); } void ShaderProgram::set_uniform(int uniform, const std::array<int, 4>& value) { glUniform4iv(uniform, 1, &value[0]); } } // namespace ORCore
25.271028
83
0.611686
mdsitton
34fd456783bdd58cf5a710c3a4f029c2aeba3313
321
hpp
C++
src/rpcz/request_handler_ptr.hpp
jinq0123/rpcz
d273dc1a8de770cb4c2ddee98c17ce60c657d6ca
[ "Apache-2.0" ]
4
2015-06-14T13:38:40.000Z
2020-11-07T02:29:59.000Z
src/rpcz/request_handler_ptr.hpp
jinq0123/rpcz
d273dc1a8de770cb4c2ddee98c17ce60c657d6ca
[ "Apache-2.0" ]
1
2015-06-19T07:54:53.000Z
2015-11-12T10:38:21.000Z
src/rpcz/request_handler_ptr.hpp
jinq0123/rpcz
d273dc1a8de770cb4c2ddee98c17ce60c657d6ca
[ "Apache-2.0" ]
3
2015-06-15T02:28:39.000Z
2018-10-18T11:02:59.000Z
// Author: Jin Qing (http://blog.csdn.net/jq0123) #ifndef RPCZ_REQUEST_HANDLER_PTR_H #define RPCZ_REQUEST_HANDLER_PTR_H #include <boost/shared_ptr.hpp> namespace rpcz { class request_handler; typedef boost::shared_ptr<request_handler> request_handler_ptr; } // namespace rpcz #endif // RPCZ_REQUEST_HANDLER_PTR_H
20.0625
63
0.797508
jinq0123
34ff834048322fd5351a65e34660fef871d798db
719
cc
C++
src/lsp-protocol/static-data.cc
roflcopter4/electromechanical-lsp-client
553e4eeeac749986725046083abe6e4ca5eddb19
[ "MIT" ]
null
null
null
src/lsp-protocol/static-data.cc
roflcopter4/electromechanical-lsp-client
553e4eeeac749986725046083abe6e4ca5eddb19
[ "MIT" ]
null
null
null
src/lsp-protocol/static-data.cc
roflcopter4/electromechanical-lsp-client
553e4eeeac749986725046083abe6e4ca5eddb19
[ "MIT" ]
null
null
null
#include "Common.hh" #include "static-data.hh" namespace emlsp::rpc::lsp::data { #if 0 std::string const initialization_message = R"({ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "trace": "on", "locale": "en_US.UTF8", "clientInfo": { "name": ")" MAIN_PROJECT_NAME R"(", "version": ")" MAIN_PROJECT_VERSION_STRING R"(" }, "capabilities": { "textDocument.documentHighlight.dynamicRegistration": true } } })"s; #endif } // namespace emlsp::rpc::lsp::data namespace emlsp::test { NOINLINE void test01() { } } // namespace emlsp::test
20.542857
76
0.513213
roflcopter4
5502c9b9825deb1d0594bfef07db2cc22ef09594
3,642
cpp
C++
MonoNative.Tests/mscorlib/System/mscorlib_System_OverflowException_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
7
2015-03-10T03:36:16.000Z
2021-11-05T01:16:58.000Z
MonoNative.Tests/mscorlib/System/mscorlib_System_OverflowException_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
1
2020-06-23T10:02:33.000Z
2020-06-24T02:05:47.000Z
MonoNative.Tests/mscorlib/System/mscorlib_System_OverflowException_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
null
null
null
// Mono Native Fixture // Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // Namespace: System // Name: OverflowException // C++ Typed Name: mscorlib::System::OverflowException #include <gtest/gtest.h> #include <mscorlib/System/mscorlib_System_OverflowException.h> #include <mscorlib/System/Reflection/mscorlib_System_Reflection_MethodBase.h> #include <mscorlib/System/Runtime/Serialization/mscorlib_System_Runtime_Serialization_SerializationInfo.h> #include <mscorlib/System/Runtime/Serialization/mscorlib_System_Runtime_Serialization_StreamingContext.h> #include <mscorlib/System/mscorlib_System_Type.h> namespace mscorlib { namespace System { //Constructors Tests //OverflowException() TEST(mscorlib_System_OverflowException_Fixture,DefaultConstructor) { mscorlib::System::OverflowException *value = new mscorlib::System::OverflowException(); EXPECT_NE(NULL, value->GetNativeObject()); } //OverflowException(mscorlib::System::String message) TEST(mscorlib_System_OverflowException_Fixture,Constructor_2) { mscorlib::System::OverflowException *value = new mscorlib::System::OverflowException(); EXPECT_NE(NULL, value->GetNativeObject()); } //OverflowException(mscorlib::System::String message, mscorlib::System::Exception innerException) TEST(mscorlib_System_OverflowException_Fixture,Constructor_3) { mscorlib::System::OverflowException *value = new mscorlib::System::OverflowException(); EXPECT_NE(NULL, value->GetNativeObject()); } //Public Methods Tests //Public Properties Tests // Property InnerException // Return Type: mscorlib::System::Exception // Property Get Method TEST(mscorlib_System_OverflowException_Fixture,get_InnerException_Test) { } // Property HelpLink // Return Type: mscorlib::System::String // Property Get Method TEST(mscorlib_System_OverflowException_Fixture,get_HelpLink_Test) { } // Property HelpLink // Return Type: mscorlib::System::String // Property Set Method TEST(mscorlib_System_OverflowException_Fixture,set_HelpLink_Test) { } // Property HResult // Return Type: mscorlib::System::Int32 // Property Get Method TEST(mscorlib_System_OverflowException_Fixture,get_HResult_Test) { } // Property HResult // Return Type: mscorlib::System::Int32 // Property Set Method TEST(mscorlib_System_OverflowException_Fixture,set_HResult_Test) { } // Property Message // Return Type: mscorlib::System::String // Property Get Method TEST(mscorlib_System_OverflowException_Fixture,get_Message_Test) { } // Property Source // Return Type: mscorlib::System::String // Property Get Method TEST(mscorlib_System_OverflowException_Fixture,get_Source_Test) { } // Property Source // Return Type: mscorlib::System::String // Property Set Method TEST(mscorlib_System_OverflowException_Fixture,set_Source_Test) { } // Property StackTrace // Return Type: mscorlib::System::String // Property Get Method TEST(mscorlib_System_OverflowException_Fixture,get_StackTrace_Test) { } // Property TargetSite // Return Type: mscorlib::System::Reflection::MethodBase // Property Get Method TEST(mscorlib_System_OverflowException_Fixture,get_TargetSite_Test) { } // Property Data // Return Type: mscorlib::System::Collections::IDictionary // Property Get Method TEST(mscorlib_System_OverflowException_Fixture,get_Data_Test) { } } }
22.7625
106
0.731466
brunolauze
5504cb8775368b3998df85f1df1ca63775176fd7
223
hh
C++
src/ast/Decl.hh
walecome/seal
204b2dbad9f0bf3ac77f5e32173de39ef1fb81c1
[ "MIT" ]
1
2020-01-06T09:43:56.000Z
2020-01-06T09:43:56.000Z
src/ast/Decl.hh
walecome/seal
204b2dbad9f0bf3ac77f5e32173de39ef1fb81c1
[ "MIT" ]
null
null
null
src/ast/Decl.hh
walecome/seal
204b2dbad9f0bf3ac77f5e32173de39ef1fb81c1
[ "MIT" ]
null
null
null
#pragma once #include "Statement.hh" // @TODO: Derive from something else class Decl : public Statement { MAKE_NONMOVABLE(Decl) MAKE_NONCOPYABLE(Decl) AST_NODE_NAME(Decl) protected: Decl() = default; };
18.583333
36
0.695067
walecome
550727d7b0ea51da785f910de3f02bb59e994fbc
746
hpp
C++
engine/source/util/util.hpp
aegooby/videosaurus
20e2dc52e3b06b15d546c8f0d4bba1f2c8b215ad
[ "Apache-2.0" ]
1
2021-02-19T13:02:23.000Z
2021-02-19T13:02:23.000Z
engine/source/util/util.hpp
aegooby/videosaurus
20e2dc52e3b06b15d546c8f0d4bba1f2c8b215ad
[ "Apache-2.0" ]
16
2021-02-11T04:23:48.000Z
2021-02-19T05:37:30.000Z
engine/source/util/util.hpp
aegooby/videosaurus
20e2dc52e3b06b15d546c8f0d4bba1f2c8b215ad
[ "Apache-2.0" ]
null
null
null
#pragma once #include "../__common.hpp" namespace vs { namespace util { template<typename type> void print_arg(const type& arg) { std::cout << arg; } template<> void print_arg(const bool& arg) { std::cout << termcolor::bold << termcolor::yellow << (arg ? "true" : "false") << termcolor::reset; } template<> void print_arg(const std::string& arg) { std::cout << termcolor::magenta << "\"" << arg << "\"" << termcolor::reset; } void print_args() { } template<typename type, typename... types> void print_args(type&& arg, types&&... args) { print_arg(std::forward<type>(arg)); if constexpr (sizeof...(types)) std::cout << ", "; print_args(std::forward<types>(args)...); } } // namespace util } // namespace vs
21.941176
79
0.621984
aegooby
550915e6b36470976148ac116d6c97b7a88ddbe9
1,464
hpp
C++
src/sip-0x/parser/tokens/messageheaders/TokenSIPMessageHeader_From.hpp
zanfire/sip-0x
de38b3ff782d2a63b69d7f785e2bd9ce7674abd5
[ "Apache-2.0" ]
1
2021-06-03T15:56:32.000Z
2021-06-03T15:56:32.000Z
src/sip-0x/parser/tokens/messageheaders/TokenSIPMessageHeader_From.hpp
zanfire/sip-0x
de38b3ff782d2a63b69d7f785e2bd9ce7674abd5
[ "Apache-2.0" ]
1
2015-08-05T05:51:49.000Z
2015-08-05T05:51:49.000Z
src/sip-0x/parser/tokens/messageheaders/TokenSIPMessageHeader_From.hpp
zanfire/sip-0x
de38b3ff782d2a63b69d7f785e2bd9ce7674abd5
[ "Apache-2.0" ]
null
null
null
#if !defined(SIP0X_PARSER_TOKENSIPMESSAGEHEADER_FROM_HPP__) #define SIP0X_PARSER_TOKENSIPMESSAGEHEADER_FROM_HPP__ #include "parser/tokens/TokenAbstract.hpp" #include "parser/tokens/Operators.hpp" #include "parser/tokens/TokenRegex.hpp" #include "parser/tokens/TokenNameAddr.hpp" #include "parser/tokens/TokenGenericParam.hpp" #include "parser/tokens/messageheaders/TokenSIPMessageHeader_base.hpp" namespace sip0x { namespace parser { // From = ( "From" / "f" ) HCOLON from-spec // from-spec = ( name-addr / addr-spec ) *( SEMI from-param ) // from-param = tag-param / generic-param // tag-param = "tag" EQUAL token class TokenSIPMessageHeader_From : public TokenSIPMessageHeader_base < Sequence<Alternative<TokenNameAddr, TokenAddrSpec>, Occurrence<Sequence<TokenSEMI, TokenGenericParam>>> > { public: TokenSIPMessageHeader_From() : TokenSIPMessageHeader_base("From", "(From)|(f)", Sequence<Alternative<TokenNameAddr, TokenAddrSpec>, Occurrence<Sequence<TokenSEMI, TokenGenericParam>>> ( Alternative<TokenNameAddr, TokenAddrSpec>( TokenNameAddr(), TokenAddrSpec() ), Occurrence<Sequence<TokenSEMI, TokenGenericParam>> ( Sequence<TokenSEMI, TokenGenericParam>(TokenSEMI(), TokenGenericParam()), 0, -1) ) ) { } }; } } #endif // SIP0X_PARSER_TOKENSIPMESSAGEHEADER_FROM_HPP__
34.857143
182
0.686475
zanfire
55093c0a05392e2151d3204f2e5fe7810db874f7
1,298
cpp
C++
rasprobotd/src/main.cpp
sea-kg/php-rasp-robot
c404a46c48db6e5865a47fbcd0f02d8869cc71a5
[ "MIT" ]
null
null
null
rasprobotd/src/main.cpp
sea-kg/php-rasp-robot
c404a46c48db6e5865a47fbcd0f02d8869cc71a5
[ "MIT" ]
null
null
null
rasprobotd/src/main.cpp
sea-kg/php-rasp-robot
c404a46c48db6e5865a47fbcd0f02d8869cc71a5
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <iostream> #include <sys/stat.h> #include <sys/types.h> #include <sys/time.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #include <syslog.h> #include <QtCore> #include <QFile> #include <QString> #include "websocketserver.h" int main(int argc, char** argv) { QCoreApplication app(argc, argv); QCoreApplication a(argc, argv); QCommandLineParser parser; parser.setApplicationDescription("Rasp Robot Daemon"); parser.addHelpOption(); QCommandLineOption dbgOption(QStringList() << "d" << "debug", QCoreApplication::translate("main", "Debug output [default: off].")); parser.addOption(dbgOption); QCommandLineOption portOption(QStringList() << "p" << "port", QCoreApplication::translate("main", "Port for Rasp Robot Daemon ws [default: 1234]."), QCoreApplication::translate("main", "port"), QLatin1Literal("1234")); parser.addOption(portOption); parser.process(a); bool debug = parser.isSet(dbgOption); int port = parser.value(portOption).toInt(); WebSocketServer *server = new WebSocketServer(port, debug); QObject::connect(server, &WebSocketServer::closed, &a, &QCoreApplication::quit); return app.exec(); }
30.186047
135
0.690293
sea-kg
55096fa25ddc42207a712250b4c5fd9d67d95038
773
cpp
C++
trainings/2015-10-13-Sichuan-Province-2012/A.cpp
HcPlu/acm-icpc
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
[ "MIT" ]
9
2017-10-07T13:35:45.000Z
2021-06-07T17:36:55.000Z
trainings/2015-10-13-Sichuan-Province-2012/A.cpp
zhijian-liu/acm-icpc
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
[ "MIT" ]
null
null
null
trainings/2015-10-13-Sichuan-Province-2012/A.cpp
zhijian-liu/acm-icpc
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
[ "MIT" ]
3
2018-04-24T05:27:21.000Z
2019-04-25T06:06:00.000Z
#include <iostream> using namespace std; int a[10], used[22][22][22]; void solve() { for (int i = 1; i <= 3; i++) { scanf("%d", &a[i]); } sort(a + 1, a + 4); memset(used, 0, sizeof(used)); for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { for (int k = 1; k <= 3; k++) { if (i != j && j != k && i != k) { if (!used[a[i]][a[j]][a[k]]) { printf("%d %d %d\n", a[i], a[j], a[k]); used[a[i]][a[j]][a[k]] = 1; } } } } } } int main() { int tests; scanf("%d", &tests); for (int i = 1; i <= tests; i++) { printf("Case #%d:\n", i); solve(); } }
22.735294
63
0.315653
HcPlu
550aa8d1a5439a4dfa72d97d3345ac219f405660
3,494
cpp
C++
main.cpp
picorro/VulkanEngine
eca00b4332783a44692207ac4f057f292ca07328
[ "MIT" ]
null
null
null
main.cpp
picorro/VulkanEngine
eca00b4332783a44692207ac4f057f292ca07328
[ "MIT" ]
null
null
null
main.cpp
picorro/VulkanEngine
eca00b4332783a44692207ac4f057f292ca07328
[ "MIT" ]
null
null
null
/******************************************************************* ** This code is part of Breakout. ** ** Breakout is free software: you can redistribute it and/or modify ** it under the terms of the CC BY 4.0 license as published by ** Creative Commons, either version 4 of the License, or (at your ** option) any later version. ******************************************************************/ #include <glad.h> #include <glfw3.h> #include "game.h" #include "resourceManager.h" #include <iostream> // GLFW function declerations void framebuffer_size_callback(GLFWwindow* window, int width, int height); void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode); // The Width of the screen const unsigned int SCREEN_WIDTH = 1080; // The height of the screen const unsigned int SCREEN_HEIGHT = 720; Game game(SCREEN_WIDTH, SCREEN_HEIGHT); int main(int argc, char* argv[]) { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif glfwWindowHint(GLFW_RESIZABLE, false); GLFWwindow* window = glfwCreateWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "Engine", nullptr, nullptr); glfwMakeContextCurrent(window); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } glfwSetKeyCallback(window, key_callback); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); // OpenGL configuration // -------------------- glViewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // initialize game // --------------- game.Init(); // deltaTime variables // ------------------- float deltaTime = 0.0f; float lastFrame = 0.0f; // start game within menu state // ---------------------------- game.State = GAME_MENU; while (!glfwWindowShouldClose(window)) { // calculate delta time // -------------------- float currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; glfwPollEvents(); // manage user input // ----------------- game.ProcessInput(); // update game state // ----------------- game.Update(deltaTime); // render // ------ glClearColor(0.0f, 0.0f, 0.4f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); game.Render(); glfwSwapBuffers(window); } // delete all resources as loaded using the resource manager // --------------------------------------------------------- ResourceManager::Clear(); glfwTerminate(); return 0; } void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) { // when a user presses the escape key, we set the WindowShouldClose property to true, closing the application if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, true); if (key >= 0 && key < 1024) { if (action == GLFW_PRESS) game.Keys[key] = true; else if (action == GLFW_RELEASE) game.Keys[key] = false; } } void framebuffer_size_callback(GLFWwindow* window, int width, int height) { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); }
27.952
110
0.653692
picorro
550d4bfc530fd0ba42f49bed4131585a505fe65e
18,389
cc
C++
include/windows/google/protobuf/any_test.pb.cc
Thanalan/GameBookServer-master
506b4fe1eece1a3c0bd1100fe14764b63885b2bf
[ "MIT" ]
83
2019-12-03T08:42:15.000Z
2022-03-30T13:22:37.000Z
include/windows/google/protobuf/any_test.pb.cc
Thanalan/GameBookServer-master
506b4fe1eece1a3c0bd1100fe14764b63885b2bf
[ "MIT" ]
1
2021-08-06T10:40:57.000Z
2021-08-09T06:33:43.000Z
include/windows/google/protobuf/any_test.pb.cc
Thanalan/GameBookServer-master
506b4fe1eece1a3c0bd1100fe14764b63885b2bf
[ "MIT" ]
45
2020-05-29T03:22:48.000Z
2022-03-21T16:19:01.000Z
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/any_test.proto #include "google/protobuf/any_test.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/wire_format_lite.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fany_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_Any_google_2fprotobuf_2fany_2eproto; namespace protobuf_unittest { class TestAnyDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<TestAny> _instance; } _TestAny_default_instance_; } // namespace protobuf_unittest static void InitDefaultsscc_info_TestAny_google_2fprotobuf_2fany_5ftest_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::protobuf_unittest::_TestAny_default_instance_; new (ptr) ::protobuf_unittest::TestAny(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } ::protobuf_unittest::TestAny::InitAsDefaultInstance(); } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_TestAny_google_2fprotobuf_2fany_5ftest_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsscc_info_TestAny_google_2fprotobuf_2fany_5ftest_2eproto}, { &scc_info_Any_google_2fprotobuf_2fany_2eproto.base,}}; static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_google_2fprotobuf_2fany_5ftest_2eproto[1]; static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2fany_5ftest_2eproto = nullptr; static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fany_5ftest_2eproto = nullptr; const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_google_2fprotobuf_2fany_5ftest_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::protobuf_unittest::TestAny, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::protobuf_unittest::TestAny, int32_value_), PROTOBUF_FIELD_OFFSET(::protobuf_unittest::TestAny, any_value_), PROTOBUF_FIELD_OFFSET(::protobuf_unittest::TestAny, repeated_any_value_), }; static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, sizeof(::protobuf_unittest::TestAny)}, }; static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::protobuf_unittest::_TestAny_default_instance_), }; const char descriptor_table_protodef_google_2fprotobuf_2fany_5ftest_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = "\n\036google/protobuf/any_test.proto\022\021protob" "uf_unittest\032\031google/protobuf/any.proto\"y" "\n\007TestAny\022\023\n\013int32_value\030\001 \001(\005\022\'\n\tany_va" "lue\030\002 \001(\0132\024.google.protobuf.Any\0220\n\022repea" "ted_any_value\030\003 \003(\0132\024.google.protobuf.An" "yb\006proto3" ; static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_google_2fprotobuf_2fany_5ftest_2eproto_deps[1] = { &::descriptor_table_google_2fprotobuf_2fany_2eproto, }; static ::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase*const descriptor_table_google_2fprotobuf_2fany_5ftest_2eproto_sccs[1] = { &scc_info_TestAny_google_2fprotobuf_2fany_5ftest_2eproto.base, }; static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_google_2fprotobuf_2fany_5ftest_2eproto_once; static bool descriptor_table_google_2fprotobuf_2fany_5ftest_2eproto_initialized = false; const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fany_5ftest_2eproto = { &descriptor_table_google_2fprotobuf_2fany_5ftest_2eproto_initialized, descriptor_table_protodef_google_2fprotobuf_2fany_5ftest_2eproto, "google/protobuf/any_test.proto", 209, &descriptor_table_google_2fprotobuf_2fany_5ftest_2eproto_once, descriptor_table_google_2fprotobuf_2fany_5ftest_2eproto_sccs, descriptor_table_google_2fprotobuf_2fany_5ftest_2eproto_deps, 1, 1, schemas, file_default_instances, TableStruct_google_2fprotobuf_2fany_5ftest_2eproto::offsets, file_level_metadata_google_2fprotobuf_2fany_5ftest_2eproto, 1, file_level_enum_descriptors_google_2fprotobuf_2fany_5ftest_2eproto, file_level_service_descriptors_google_2fprotobuf_2fany_5ftest_2eproto, }; // Force running AddDescriptors() at dynamic initialization time. static bool dynamic_init_dummy_google_2fprotobuf_2fany_5ftest_2eproto = ( ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fany_5ftest_2eproto), true); namespace protobuf_unittest { // =================================================================== void TestAny::InitAsDefaultInstance() { ::protobuf_unittest::_TestAny_default_instance_._instance.get_mutable()->any_value_ = const_cast< PROTOBUF_NAMESPACE_ID::Any*>( PROTOBUF_NAMESPACE_ID::Any::internal_default_instance()); } class TestAny::_Internal { public: static const PROTOBUF_NAMESPACE_ID::Any& any_value(const TestAny* msg); }; const PROTOBUF_NAMESPACE_ID::Any& TestAny::_Internal::any_value(const TestAny* msg) { return *msg->any_value_; } void TestAny::clear_any_value() { if (GetArenaNoVirtual() == nullptr && any_value_ != nullptr) { delete any_value_; } any_value_ = nullptr; } void TestAny::clear_repeated_any_value() { repeated_any_value_.Clear(); } TestAny::TestAny() : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:protobuf_unittest.TestAny) } TestAny::TestAny(const TestAny& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr), repeated_any_value_(from.repeated_any_value_) { _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_any_value()) { any_value_ = new PROTOBUF_NAMESPACE_ID::Any(*from.any_value_); } else { any_value_ = nullptr; } int32_value_ = from.int32_value_; // @@protoc_insertion_point(copy_constructor:protobuf_unittest.TestAny) } void TestAny::SharedCtor() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_TestAny_google_2fprotobuf_2fany_5ftest_2eproto.base); ::memset(&any_value_, 0, static_cast<size_t>( reinterpret_cast<char*>(&int32_value_) - reinterpret_cast<char*>(&any_value_)) + sizeof(int32_value_)); } TestAny::~TestAny() { // @@protoc_insertion_point(destructor:protobuf_unittest.TestAny) SharedDtor(); } void TestAny::SharedDtor() { if (this != internal_default_instance()) delete any_value_; } void TestAny::SetCachedSize(int size) const { _cached_size_.Set(size); } const TestAny& TestAny::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_TestAny_google_2fprotobuf_2fany_5ftest_2eproto.base); return *internal_default_instance(); } void TestAny::Clear() { // @@protoc_insertion_point(message_clear_start:protobuf_unittest.TestAny) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; repeated_any_value_.Clear(); if (GetArenaNoVirtual() == nullptr && any_value_ != nullptr) { delete any_value_; } any_value_ = nullptr; int32_value_ = 0; _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* TestAny::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // int32 int32_value = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { int32_value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // .google.protobuf.Any any_value = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { ptr = ctx->ParseMessage(mutable_any_value(), ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated .google.protobuf.Any repeated_any_value = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(add_repeated_any_value(), ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 26); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool TestAny::MergePartialFromCodedStream( ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:protobuf_unittest.TestAny) for (;;) { ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // int32 int32_value = 1; case 1: { if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (8 & 0xFF)) { DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32>( input, &int32_value_))); } else { goto handle_unusual; } break; } // .google.protobuf.Any any_value = 2; case 2: { if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (18 & 0xFF)) { DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, mutable_any_value())); } else { goto handle_unusual; } break; } // repeated .google.protobuf.Any repeated_any_value = 3; case 3: { if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (26 & 0xFF)) { DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_repeated_any_value())); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:protobuf_unittest.TestAny) return true; failure: // @@protoc_insertion_point(parse_failure:protobuf_unittest.TestAny) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void TestAny::SerializeWithCachedSizes( ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:protobuf_unittest.TestAny) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // int32 int32_value = 1; if (this->int32_value() != 0) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32(1, this->int32_value(), output); } // .google.protobuf.Any any_value = 2; if (this->has_any_value()) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 2, _Internal::any_value(this), output); } // repeated .google.protobuf.Any repeated_any_value = 3; for (unsigned int i = 0, n = static_cast<unsigned int>(this->repeated_any_value_size()); i < n; i++) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 3, this->repeated_any_value(static_cast<int>(i)), output); } if (_internal_metadata_.have_unknown_fields()) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:protobuf_unittest.TestAny) } ::PROTOBUF_NAMESPACE_ID::uint8* TestAny::InternalSerializeWithCachedSizesToArray( ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:protobuf_unittest.TestAny) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // int32 int32_value = 1; if (this->int32_value() != 0) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(1, this->int32_value(), target); } // .google.protobuf.Any any_value = 2; if (this->has_any_value()) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( 2, _Internal::any_value(this), target); } // repeated .google.protobuf.Any repeated_any_value = 3; for (unsigned int i = 0, n = static_cast<unsigned int>(this->repeated_any_value_size()); i < n; i++) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( 3, this->repeated_any_value(static_cast<int>(i)), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:protobuf_unittest.TestAny) return target; } size_t TestAny::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:protobuf_unittest.TestAny) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated .google.protobuf.Any repeated_any_value = 3; { unsigned int count = static_cast<unsigned int>(this->repeated_any_value_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->repeated_any_value(static_cast<int>(i))); } } // .google.protobuf.Any any_value = 2; if (this->has_any_value()) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *any_value_); } // int32 int32_value = 1; if (this->int32_value() != 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->int32_value()); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void TestAny::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:protobuf_unittest.TestAny) GOOGLE_DCHECK_NE(&from, this); const TestAny* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<TestAny>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:protobuf_unittest.TestAny) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:protobuf_unittest.TestAny) MergeFrom(*source); } } void TestAny::MergeFrom(const TestAny& from) { // @@protoc_insertion_point(class_specific_merge_from_start:protobuf_unittest.TestAny) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; repeated_any_value_.MergeFrom(from.repeated_any_value_); if (from.has_any_value()) { mutable_any_value()->PROTOBUF_NAMESPACE_ID::Any::MergeFrom(from.any_value()); } if (from.int32_value() != 0) { set_int32_value(from.int32_value()); } } void TestAny::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:protobuf_unittest.TestAny) if (&from == this) return; Clear(); MergeFrom(from); } void TestAny::CopyFrom(const TestAny& from) { // @@protoc_insertion_point(class_specific_copy_from_start:protobuf_unittest.TestAny) if (&from == this) return; Clear(); MergeFrom(from); } bool TestAny::IsInitialized() const { return true; } void TestAny::InternalSwap(TestAny* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); CastToBase(&repeated_any_value_)->InternalSwap(CastToBase(&other->repeated_any_value_)); swap(any_value_, other->any_value_); swap(int32_value_, other->int32_value_); } ::PROTOBUF_NAMESPACE_ID::Metadata TestAny::GetMetadata() const { return GetMetadataStatic(); } // @@protoc_insertion_point(namespace_scope) } // namespace protobuf_unittest PROTOBUF_NAMESPACE_OPEN template<> PROTOBUF_NOINLINE ::protobuf_unittest::TestAny* Arena::CreateMaybeMessage< ::protobuf_unittest::TestAny >(Arena* arena) { return Arena::CreateInternal< ::protobuf_unittest::TestAny >(arena); } PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc>
38.795359
203
0.73805
Thanalan
550de8d47b5f9f69b204979617fe7276bf2d5fba
11,501
cpp
C++
node/node.cpp
catenocrypt/tcpserver-libuv-sample
ad847ce3bb89adb92b6adf24e14a8f806580b7f1
[ "MIT" ]
1
2020-04-29T07:29:27.000Z
2020-04-29T07:29:27.000Z
node/node.cpp
catenocrypt/tcpserver-libuv-sample
ad847ce3bb89adb92b6adf24e14a8f806580b7f1
[ "MIT" ]
null
null
null
node/node.cpp
catenocrypt/tcpserver-libuv-sample
ad847ce3bb89adb92b6adf24e14a8f806580b7f1
[ "MIT" ]
null
null
null
#include "node.hpp" #include "peer_conn.hpp" #include "endpoint.hpp" #include "../lib/net_handler.hpp" #include "../lib/net_client.hpp" #include <cassert> #include <iostream> using namespace sample; using namespace std; NodeApp::PeerCandidateInfo::PeerCandidateInfo(std::string host_in, int port_in, int toTry_in) : myHost(host_in), myPort(port_in), myToTry(toTry_in), myConnTryCount(0), myConnectedCount(0) { } void NodeApp::PeerInfo::setClient(std::shared_ptr<NetClientBase>& client_in) { myClient = client_in; } void NodeApp::PeerInfo::resetClient() { myClient = nullptr; } NodeApp::NodeApp() : ServerApp() { myNetHandler = new NetHandler(this); } void NodeApp::start(AppParams const & appParams_in) { // add constant peer candidates, for localhost int n = 2; for (int i = 0; i < n; ++i) { addOutPeerCandidate("localhost", 5000 + i, 1); } // add extra peer candidates if (appParams_in.extraPeers.size() > 0) { for(int i = 0; i < appParams_in.extraPeers.size(); ++i) { if (appParams_in.extraPeers[i].length() > 0) { Endpoint extraPeerEp(appParams_in.extraPeers[i]); addOutPeerCandidate(extraPeerEp.getHost(), extraPeerEp.getPort(), 1000000); } } } myNetHandler->startWithListen(appParams_in.listenPort, appParams_in.listenPortRange); } void NodeApp::listenStarted(int port) { cout << "App: Listening on port " << port << endl; myName = ":" + to_string(port); // try to connect to clients tryOutConnections(); } void NodeApp::addOutPeerCandidate(std::string host_in, int port_in, int toTry_in) { PeerCandidateInfo pc = PeerCandidateInfo(host_in, port_in, toTry_in); string key = host_in + ":" + to_string(port_in); if (myPeerCands.find(key) != myPeerCands.end()) { // already present myPeerCands[key].myToTry = toTry_in + myPeerCands[key].myConnTryCount; return; } myPeerCands[key] = pc; cout << "App: Added peer candidate " << key << " " << myPeerCands.size() << endl; //debugPrintPeerCands(); } void NodeApp::debugPrintPeerCands() { cout << "PeerCands: " << myPeerCands.size() << " "; for (auto i = myPeerCands.begin(); i != myPeerCands.end(); ++i) { cout << "[" << i->first << " " << i->second.myToTry << " " << i->second.myConnTryCount << ":" << i->second.myConnectedCount << "] "; } cout << endl; } void NodeApp::debugPrintPeers() { cout << "Peers: " << myPeers.size() << " "; for (auto i = myPeers.begin(); i != myPeers.end(); ++i) { cout << "["; if (i->myClient == nullptr) cout << "n"; else cout << i->myClient->getPeerAddr() << " " << i->myClient->getCanonPeerAddr() << " " << (i->myClient->isConnected() ? "Y" : "N") << "] "; } cout << endl; } void NodeApp::tryOutConnections() { //cout << "NodeApp::tryOutConnections" << endl; // try to connect to clients for (auto i = myPeerCands.begin(); i != myPeerCands.end(); ++i) { //cout << i->second.myOutFlag << " " << i->second.myStickyFlag << " " << i->second.myConnTryCount << " " << (i->second.myOutClient == nullptr) << " " << i->second.myEndpoint.getEndpoint() << endl; if (i->second.myConnTryCount == 0 || i->second.myConnTryCount < i->second.myToTry) { if (!isPeerConnected(i->first, true)) { // try outgoing connection ++i->second.myConnTryCount; int res = tryOutConnection(i->second.myHost, i->second.myPort); if (!res) { // success ++i->second.myConnectedCount; } } } } } bool NodeApp::isPeerConnected(string peerAddr_in, bool outDir_in) { for(auto i = myPeers.begin(); i != myPeers.end(); ++i) { if (i->myOutFlag == outDir_in) { if (i->myClient != nullptr) { if (i->myClient->getPeerAddr() == peerAddr_in || i->myClient->getCanonPeerAddr() == peerAddr_in) { return true; } } } } return false; } int NodeApp::tryOutConnection(std::string host_in, int port_in) { // exclude localhost connections to self if ((":" + to_string(port_in)) == myName) { if (host_in == "localhost" || host_in == "127.0.0.1" || host_in == "::1" || host_in == "[::1]") { //cerr << "Ignoring peer candidate to self (" << host_in << ":" << port_in << ")" << endl; return 0; } } // try outgoing connection Endpoint ep = Endpoint(host_in, port_in); string key = ep.getEndpoint(); //cout << "Trying outgoing conn to " << key << endl; auto peerout = make_shared<PeerClientOut>(this, host_in, port_in); auto peerBase = dynamic_pointer_cast<NetClientBase>(peerout); PeerInfo p; p.setClient(peerBase); p.myOutFlag = true; myPeers.push_back(p); int res = peerout->connect(); if (res) { cerr << "Error from peer connect, " << res << endl; return res; } //debugPrintPeers(); return 0; } void NodeApp::stop() { myNetHandler->stop(); } void NodeApp::inConnectionReceived(std::shared_ptr<NetClientBase>& client_in) { assert(client_in != nullptr); string cliaddr = client_in->getPeerAddr(); cout << "App: New incoming connection: " << cliaddr << endl; PeerInfo p; p.setClient(client_in); p.myOutFlag = false; myPeers.push_back(p); //debugPrintPeers(); } void NodeApp::connectionClosed(NetClientBase* client_in) { assert(client_in != nullptr); string cliaddr = client_in->getPeerAddr(); cout << "App: Connection done: " << cliaddr << " " << myPeers.size() << endl; for(auto i = myPeers.begin(); i != myPeers.end(); ++i) { if (i->myClient != nullptr) { if (i->myClient.get() == client_in || i->myClient->getPeerAddr() == cliaddr) { cout << "Removing disconnected client " << myPeers.size() << " " << i->myClient->getPeerAddr() << endl; i->resetClient(); } } } // remove disconnected clients bool changed = true; while (changed) { changed = false; for(auto i = myPeers.begin(); i != myPeers.end(); ++i) { if (i->myClient.get() == nullptr) { myPeers.erase(i); changed = true; break; // for } } } } void NodeApp::messageReceived(NetClientBase & client_in, BaseMessage const & msg_in) { if (msg_in.getType() != MessageType::OtherPeer) { cout << "App: Received: from " << client_in.getNicePeerAddr() << " '" << msg_in.toString() << "'" << endl; } switch (msg_in.getType()) { case MessageType::Handshake: { HandshakeMessage const & hsMsg = dynamic_cast<HandshakeMessage const &>(msg_in); //cout << "Handshake message received, '" << hsMsg.getMyAddr() << "'" << endl; if (hsMsg.getMyVersion() != "V01") { cerr << "Wrong version ''" << hsMsg.getMyVersion() << "'" << endl; client_in.close(); return; } string peerEp = client_in.getPeerAddr(); if (!isPeerConnected(peerEp, false)) { cerr << "Error: cannot find client in peers list " << peerEp << endl; return; } HandshakeResponseMessage resp("V01", myName, peerEp); client_in.sendMessage(resp); // find canonical name of this peer: host is actual connected ip, port is reported by peer int peerPort = Endpoint(peerEp).getPort(); string canonHost = Endpoint(peerEp).getHost(); int canonPort = peerPort; string reportedPeerName = hsMsg.getMyAddr(); if (reportedPeerName.substr(0, 1) != ":") { cerr << "Could not retrieve listening port of incoming peer " << client_in.getPeerAddr() << " " << reportedPeerName << endl; } else { canonPort = stoi(reportedPeerName.substr(1)); string canonEp = canonHost + ":" + to_string(canonPort); if (canonEp != peerEp) { // canonical is different cout << "Canonical peer of " << peerEp << " is " << canonEp << endl; client_in.setCanonPeerAddr(canonEp); // try to connect ougoing too (to canonical peer addr) addOutPeerCandidate(canonHost, canonPort, 1); tryOutConnections(); } } sendOtherPeers(client_in); } break; case MessageType::Ping: { PingMessage const & pingMsg = dynamic_cast<PingMessage const &>(msg_in); //cout << "Ping message received, '" << pingMsg.getText() << "'" << endl; PingResponseMessage resp("Resp_from_" + myName + "_to_" + pingMsg.getText()); client_in.sendMessage(resp); } break; case MessageType::OtherPeer: { OtherPeerMessage const & peerMsg = dynamic_cast<OtherPeerMessage const &>(msg_in); //cout << "OtherPeer message received, " << peerMsg.getHost() << ":" << peerMsg.getPort() << " " << peerMsg.toString() << endl; addOutPeerCandidate(peerMsg.getHost(), peerMsg.getPort(), 1); tryOutConnections(); } break; case MessageType::HandshakeResponse: case MessageType::PingResponse: // OK, noop break; default: assert(false); } } void NodeApp::sendOtherPeers(NetClientBase & client_in) { // send current outgoing connection addresses auto peers = getConnectedPeers(); //cout << "NodeApp::sendOtherPeers " << peers.size() << " " << client_in.getPeerAddr() << endl; for(auto i = peers.begin(); i != peers.end(); ++i) { if (!client_in.isConnected()) { return; } string ep = i->getEndpoint(); //cout << ep << " " << client_in.getPeerAddr() << endl; if (ep != client_in.getPeerAddr()) { //cout << "sendOtherPeers " << client_in.getPeerAddr() << " " << i->getEndpoint() << endl; client_in.sendMessage(OtherPeerMessage(i->getHost(), i->getPort())); } } } vector<Endpoint> NodeApp::getConnectedPeers() const { // collect in a map to discard duplicates map<string, int> peers; for(auto i = myPeers.begin(); i != myPeers.end(); ++i) { if (i->myClient != nullptr && i->myClient->isConnected() && i->myClient->getCanonPeerAddr().length() > 0) { peers[i->myClient->getCanonPeerAddr()] = 1; } } // convert to vector vector<Endpoint> vec; for(auto i = peers.begin(); i != peers.end(); ++i) { vec.push_back(Endpoint(i->first)); } return vec; }
31.683196
204
0.536388
catenocrypt
550ed484a943b7c9c3414be1c5063ee32f77b838
965
cpp
C++
source/BinaryTree/144. Binary Tree Preorder Traversal.cpp
Tridu33/myclionarch
d4e41b3465a62a83cbf6c7119401c05009f4b636
[ "MIT" ]
null
null
null
source/BinaryTree/144. Binary Tree Preorder Traversal.cpp
Tridu33/myclionarch
d4e41b3465a62a83cbf6c7119401c05009f4b636
[ "MIT" ]
null
null
null
source/BinaryTree/144. Binary Tree Preorder Traversal.cpp
Tridu33/myclionarch
d4e41b3465a62a83cbf6c7119401c05009f4b636
[ "MIT" ]
null
null
null
//递归解法: class Solution { public: void prebintree(TreeNode * root,vector<int> &res){//记得传地址而不是传值&res if(root == nullptr) { return; } res.push_back(root->val); prebintree(root->left,res); prebintree(root->right,res); return; } vector<int> preorderTraversal(TreeNode* root) { vector <int> res; prebintree(root,res); return res; } }; //iter solution class Solution { public: vector<int> preorderTraversal(TreeNode* root) { if(root == nullptr) return {}; vector <int> res; stack <TreeNode*> stk; stk.emplace(root); while(!stk.empty()){ TreeNode* node = stk.top(); res.emplace_back(node->val); stk.pop(); if(node->right != nullptr) stk.emplace(node->right); if(node->left != nullptr) stk.emplace(node->left); } return res; } }; //Morris 遍历
22.44186
70
0.533679
Tridu33
55131cf89a253821832354b7d53c2f3b0a84d1ea
436
cpp
C++
old/src/channel/BufferWrapper.cpp
edwino-stein/elrond-common
145909bb883e9877e9de3325d2a9002639271200
[ "Apache-2.0" ]
null
null
null
old/src/channel/BufferWrapper.cpp
edwino-stein/elrond-common
145909bb883e9877e9de3325d2a9002639271200
[ "Apache-2.0" ]
47
2019-12-30T22:14:04.000Z
2022-03-26T02:04:06.000Z
old/src/channel/BufferWrapper.cpp
edwino-stein/elrond-common
145909bb883e9877e9de3325d2a9002639271200
[ "Apache-2.0" ]
null
null
null
#include "channel/BufferWrapper.hpp" using elrond::channel::BufferWrapper; /* **************************************************************************** ************** elrond::channel::BufferWrapper Implementation *************** ****************************************************************************/ BufferWrapper::BufferWrapper(elrond::byte* const data, const elrond::sizeT length): data(data), length(length) {}
39.636364
83
0.431193
edwino-stein
55138f897795896970b5bc19224bd50389607a67
5,112
hpp
C++
Support/Modules/GSRoot/ThreadMonitor.hpp
graphisoft-python/TextEngine
20c2ff53877b20fdfe2cd51ce7abdab1ff676a70
[ "Apache-2.0" ]
3
2019-07-15T10:54:54.000Z
2020-01-25T08:24:51.000Z
Support/Modules/GSRoot/ThreadMonitor.hpp
graphisoft-python/GSRoot
008fac2c6bf601ca96e7096705e25b10ba4d3e75
[ "Apache-2.0" ]
null
null
null
Support/Modules/GSRoot/ThreadMonitor.hpp
graphisoft-python/GSRoot
008fac2c6bf601ca96e7096705e25b10ba4d3e75
[ "Apache-2.0" ]
1
2020-09-26T03:17:22.000Z
2020-09-26T03:17:22.000Z
// ***************************************************************************** // // Declaration of ThreadMonitor class // // Module: GSRoot // Namespace: GS // Contact person: SN // // ***************************************************************************** #ifndef GS_THREADMONITOR_HPP #define GS_THREADMONITOR_HPP #pragma once // --- Includes ---------------------------------------------------------------- #include "ThreadMonitorImpl.hpp" #include "Timeout.hpp" // --- ThreadMonitor class ----------------------------------------------------- namespace GS { class ThreadMonitor { // Data members: private: ThreadMonitorImpl* m_impl; // The underlying implementation of the thread monitor // Construction / destruction: public: explicit ThreadMonitor (ThreadMonitorImpl* impl); private: ThreadMonitor (const ThreadMonitor&); // Disabled public: ~ThreadMonitor (); // Operator overloading: private: const ThreadMonitor& operator = (const ThreadMonitor&); // Disabled // Operations: public: void Acquire (); bool TryAcquire (); void Release (); ThreadMonitorState Wait (UInt32 timeout, bool interruptible); ThreadMonitorState Wait (bool interruptible); bool Notify (); bool IsInterrupted () const; bool Interrupted (); void Interrupt (); bool IsCanceled () const; bool Canceled (); void Cancel (); void BlockOn (Interruptible* blocker); }; //////////////////////////////////////////////////////////////////////////////// // ThreadMonitor inlines //////////////////////////////////////////////////////////////////////////////// // Operations //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // Acquire // ----------------------------------------------------------------------------- inline void ThreadMonitor::Acquire () { m_impl->Acquire (); } // ----------------------------------------------------------------------------- // TryAcquire // ----------------------------------------------------------------------------- inline bool ThreadMonitor::TryAcquire () { return m_impl->TryAcquire (); } // ----------------------------------------------------------------------------- // Release // ----------------------------------------------------------------------------- inline void ThreadMonitor::Release () { m_impl->Release (); } // ----------------------------------------------------------------------------- // Wait // ----------------------------------------------------------------------------- inline ThreadMonitorState ThreadMonitor::Wait (UInt32 timeout, bool interruptible) { return m_impl->Wait (timeout, interruptible); } // ----------------------------------------------------------------------------- // Wait // ----------------------------------------------------------------------------- inline ThreadMonitorState ThreadMonitor::Wait (bool interruptible) { return m_impl->Wait (interruptible); } // ----------------------------------------------------------------------------- // Notify // ----------------------------------------------------------------------------- inline bool ThreadMonitor::Notify () { return m_impl->Notify (); } // ----------------------------------------------------------------------------- // IsInterrupted // ----------------------------------------------------------------------------- inline bool ThreadMonitor::IsInterrupted () const { return m_impl->IsInterrupted (); } // ----------------------------------------------------------------------------- // Interrupted // ----------------------------------------------------------------------------- inline bool ThreadMonitor::Interrupted () { return m_impl->Interrupted (); } // ----------------------------------------------------------------------------- // Interrupt // ----------------------------------------------------------------------------- inline void ThreadMonitor::Interrupt () { m_impl->Interrupt (); } // ----------------------------------------------------------------------------- // IsCanceled // ----------------------------------------------------------------------------- inline bool ThreadMonitor::IsCanceled () const { return m_impl->IsCanceled (); } // ----------------------------------------------------------------------------- // Canceled // ----------------------------------------------------------------------------- inline bool ThreadMonitor::Canceled () { return m_impl->Canceled (); } // ----------------------------------------------------------------------------- // Cancel // ----------------------------------------------------------------------------- inline void ThreadMonitor::Cancel () { m_impl->Cancel (); } // ----------------------------------------------------------------------------- // BlockOn // ----------------------------------------------------------------------------- inline void ThreadMonitor::BlockOn (Interruptible* blocker) { m_impl->BlockOn (blocker); } } #endif // GS_THREADMONITOR_HPP
26.081633
84
0.339593
graphisoft-python
55146f745ab25defa0d51dc9e47174d30cf93ccd
8,270
hpp
C++
utility/convert.hpp
MIPS/external-parameter-framework
7f346c9058f39a533a2eaadc9ebc4001397c6ff9
[ "BSD-3-Clause" ]
null
null
null
utility/convert.hpp
MIPS/external-parameter-framework
7f346c9058f39a533a2eaadc9ebc4001397c6ff9
[ "BSD-3-Clause" ]
null
null
null
utility/convert.hpp
MIPS/external-parameter-framework
7f346c9058f39a533a2eaadc9ebc4001397c6ff9
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2011-2014, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include <limits> #include <sstream> #include <string> #include <stdint.h> #include <cmath> /* details namespace is here to hide implementation details to header end user. It * is NOT intended to be used outside. */ namespace details { /** Helper class to limit instantiation of templates */ template<typename T> struct ConvertionAllowed; /* List of allowed types for conversion */ template<> struct ConvertionAllowed<bool> {}; template<> struct ConvertionAllowed<uint64_t> {}; template<> struct ConvertionAllowed<int64_t> {}; template<> struct ConvertionAllowed<uint32_t> {}; template<> struct ConvertionAllowed<int32_t> {}; template<> struct ConvertionAllowed<uint16_t> {}; template<> struct ConvertionAllowed<int16_t> {}; template<> struct ConvertionAllowed<float> {}; template<> struct ConvertionAllowed<double> {}; template<typename T> static inline bool convertTo(const std::string &str, T &result) { /* Check that conversion to that type is allowed. * If this fails, this means that this template was not intended to be used * with this type, thus that the result is undefined. */ ConvertionAllowed<T>(); if (str.find_first_of(std::string("\r\n\t\v ")) != std::string::npos) { return false; } /* Check for a '-' in string. If type is unsigned and a - is found, the * parsing fails. This is made necessary because "-1" is read as 65535 for * uint16_t, for example */ if (str.find("-") != std::string::npos && !std::numeric_limits<T>::is_signed) { return false; } std::stringstream ss(str); /* Sadly, the stream conversion does not handle hexadecimal format, thus * check is done manually */ if (str.substr(0, 2) == "0x") { if (std::numeric_limits<T>::is_integer) { ss >> std::hex >> result; } else { /* Conversion undefined for non integers */ return false; } } else { ss >> result; } return ss.eof() && !ss.fail() && !ss.bad(); } } // namespace details /** * Convert a string to a given type. * * This template function read the value of the type T in the given string. * The function does not allow to have white spaces around the value to parse * and tries to parse the whole string, which means that if some bytes were not * read in the string, the function fails. * Hexadecimal representation (ie numbers starting with 0x) is supported only * for integral types conversions. * Result may be modified, even in case of failure. * * @param[in] str the string to parse. * @param[out] result reference to object where to store the result. * * @return true if conversion was successful, false otherwise. */ template<typename T> static inline bool convertTo(const std::string &str, T &result) { return details::convertTo<T>(str, result); } /** * Specialization for int16_t of convertTo template function. * * This function follows the same paradigm than it's generic version. * * The specific implementation is made necessary because the stlport version of * string streams is bugged and does not fail when giving overflowed values. * This specialisation can be safely removed when stlport behaviour is fixed. * * @param[in] str the string to parse. * @param[out] result reference to object where to store the result. * * @return true if conversion was successful, false otherwise. */ template<> inline bool convertTo<int16_t>(const std::string &str, int16_t &result) { int64_t res; if (!convertTo<int64_t>(str, res)) { return false; } if (res > std::numeric_limits<int16_t>::max() || res < std::numeric_limits<int16_t>::min()) { return false; } result = static_cast<int16_t>(res); return true; } /** * Specialization for float of convertTo template function. * * This function follows the same paradigm than it's generic version and is * based on it but makes furthers checks on the returned value. * * The specific implementation is made necessary because the stlport conversion * from string to float behaves differently than GNU STL: overflow produce * +/-Infinity rather than an error. * * @param[in] str the string to parse. * @param[out] result reference to object where to store the result. * * @return true if conversion was successful, false otherwise. */ template<> inline bool convertTo<float>(const std::string &str, float &result) { if (!details::convertTo(str, result)) { return false; } if (std::abs(result) == std::numeric_limits<float>::infinity() || result == std::numeric_limits<float>::quiet_NaN()) { return false; } return true; } /** * Specialization for double of convertTo template function. * * This function follows the same paradigm than it's generic version and is * based on it but makes furthers checks on the returned value. * * The specific implementation is made necessary because the stlport conversion * from string to double behaves differently than GNU STL: overflow produce * +/-Infinity rather than an error. * * @param[in] str the string to parse. * @param[out] result reference to object where to store the result. * * @return true if conversion was successful, false otherwise. */ template<> inline bool convertTo<double>(const std::string &str, double &result) { if (!details::convertTo(str, result)) { return false; } if (std::abs(result) == std::numeric_limits<double>::infinity() || result == std::numeric_limits<double>::quiet_NaN()) { return false; } return true; } /** * Specialization for boolean of convertTo template function. * * This function follows the same paradigm than it's generic version. * This function accepts to parse boolean as "0/1" or "false/true" or * "FALSE/TRUE". * The specific implementation is made necessary because the behaviour of * string streams when parsing boolean values is not sufficient to fit our * requirements. Indeed, parsing "true" will correctly parse the value, but the * end of stream is not reached which makes the ss.eof() fails in the generic * implementation. * * @param[in] str the string to parse. * @param[out] result reference to object where to store the result. * * @return true if conversion was successful, false otherwise. */ template<> inline bool convertTo<bool>(const std::string &str, bool &result) { if (str == "0" || str == "FALSE" || str == "false") { result = false; return true; } if (str == "1" || str == "TRUE" || str == "true") { result = true; return true; } return false; }
33.893443
97
0.69867
MIPS
55156c345ef50bf7727bbde804a325a7ba4bd841
1,553
hpp
C++
src/morda/widgets/proxy/click_proxy.hpp
igagis/morda
dd7b58f7cb2689d56b7796cc9b6b9302aad1a529
[ "MIT" ]
69
2016-12-07T05:56:53.000Z
2020-11-27T20:59:05.000Z
src/morda/widgets/proxy/click_proxy.hpp
igagis/morda
dd7b58f7cb2689d56b7796cc9b6b9302aad1a529
[ "MIT" ]
103
2015-07-10T14:42:21.000Z
2020-09-09T16:16:21.000Z
src/morda/widgets/proxy/click_proxy.hpp
igagis/morda
dd7b58f7cb2689d56b7796cc9b6b9302aad1a529
[ "MIT" ]
18
2016-11-22T14:41:37.000Z
2020-04-22T18:16:10.000Z
/* morda - GUI framework Copyright (C) 2012-2021 Ivan Gagis <igagis@gmail.com> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ================ LICENSE END ================ */ #pragma once #include "../widget.hpp" namespace morda{ class click_proxy : virtual public widget{ bool is_pressed_ = false; bool deferred_release_ret; public: click_proxy(std::shared_ptr<morda::context> c, const treeml::forest& desc); click_proxy(const click_proxy&) = delete; click_proxy& operator=(const click_proxy&) = delete; bool on_mouse_button(const mouse_button_event& event)override; void on_hover_change(unsigned pointer_id)override; bool is_pressed()const noexcept{ return this->is_pressed_; } /** * @brief Handler for mouse press state changes. */ std::function<bool(click_proxy& w)> press_change_handler; /** * @brief Handler for clicked event. */ std::function<void(click_proxy& w)> click_handler; }; }
27.732143
79
0.714746
igagis
55164e1e221b2c4199fa953565a2f8df20edc4c7
936
cpp
C++
training/1-1-7-beads/cpp11/main.cpp
hsun324/usaco-solutions
27f77911971513a4d2b1b820eaa09802acadfefa
[ "MIT" ]
2
2015-12-26T21:20:12.000Z
2017-12-19T00:11:45.000Z
training/1-1-7-beads/cpp11/main.cpp
hsun324/usaco-solutions
27f77911971513a4d2b1b820eaa09802acadfefa
[ "MIT" ]
null
null
null
training/1-1-7-beads/cpp11/main.cpp
hsun324/usaco-solutions
27f77911971513a4d2b1b820eaa09802acadfefa
[ "MIT" ]
null
null
null
/* ID: <ID HERE> LANG: C++11 TASK: beads */ #include <fstream> #include <string> using namespace std; template <typename iterator> int get_stretch(iterator begin, iterator end) { auto iter = begin; auto current_type = *iter; while (iter++ != end) { if (*iter == 'w') continue; if (current_type == 'w') current_type = *iter; if (current_type != *iter) break; } return iter - begin; } int main() { ifstream cin("beads.in"); ofstream cout("beads.out"); int necklace_length; cin >> necklace_length; cin.ignore(1); string necklace; necklace.reserve(necklace_length * 2); cin >> necklace; necklace += necklace; int max_length = 0; auto iter = necklace.begin(), end = necklace.end(); auto riter = necklace.rend(), rend = necklace.rend(); while (iter != end) max_length = max(max_length, get_stretch(riter--, rend) + get_stretch(iter++, end)); cout << min(max_length, necklace_length) << endl; return 0; }
19.5
86
0.666667
hsun324
5517c8062ce0660d358616c3c258be1ce9fb3327
54
hpp
C++
include/EnvironmentHider.hpp
Raemien/CustomBackgroundsQuest
40ad901b33075420f63d6088f0280013cc5321c1
[ "MIT" ]
4
2021-02-03T08:53:53.000Z
2022-03-14T06:02:35.000Z
include/EnvironmentHider.hpp
Raemien/CustomBackgroundsQuest
40ad901b33075420f63d6088f0280013cc5321c1
[ "MIT" ]
1
2021-09-14T17:45:34.000Z
2021-09-15T13:51:39.000Z
include/EnvironmentHider.hpp
Raemien/CustomBackgroundsQuest
40ad901b33075420f63d6088f0280013cc5321c1
[ "MIT" ]
2
2021-09-09T01:21:23.000Z
2022-02-13T09:14:11.000Z
extern void HideMenuEnv(); extern void HideGameEnv();
18
26
0.777778
Raemien
55184abb4520a516bff065baa04688408fb61ed1
3,525
hpp
C++
demos/TIMDemo/skin/MaskSkin.hpp
wzaen/soui2
30735bbb84184fc26f0e70edbfede889e24fba5b
[ "MIT" ]
33
2018-07-04T09:38:12.000Z
2021-06-19T06:11:45.000Z
demos/TIMDemo/skin/MaskSkin.hpp
wzaen/soui2
30735bbb84184fc26f0e70edbfede889e24fba5b
[ "MIT" ]
null
null
null
demos/TIMDemo/skin/MaskSkin.hpp
wzaen/soui2
30735bbb84184fc26f0e70edbfede889e24fba5b
[ "MIT" ]
13
2018-07-01T01:55:17.000Z
2021-08-03T10:55:45.000Z
#ifndef __MASK_SKIN_HPP_ #define __MASK_SKIN_HPP_ #include "core/SSkin.h" //************************************ // 这个是 mask 遮罩 皮肤 头像 在skin.xml 里配置 需要 3个值 // src 和 imglist 一样 // mask_a 设置透明值 的rgb a // .a=3 .r=0 .g=1 .b=2 // mask 设置遮罩 图片 // <masklist name="default" src="image:default" mask_a="1" mask="image:mask_42" /> // 还提供了 //************************************ class SSkinMask: public SSkinImgList { SOUI_CLASS_NAME(SSkinMask, L"masklist") public: SSkinMask() : m_bmpMask(NULL) , m_bmpCache(NULL) , m_iMaskChannel(0) { } virtual ~SSkinMask() { } public: // protected: virtual void _Draw(IRenderTarget *pRT, LPCRECT rcDraw, DWORD dwState, BYTE byAlpha) { if(!m_pImg) return; SIZE sz = GetSkinSize(); RECT rcSrc={0,0,sz.cx,sz.cy}; if(m_bVertical) OffsetRect(&rcSrc,0, dwState * sz.cy); else OffsetRect(&rcSrc, dwState * sz.cx, 0); if(m_bmpCache) { RECT rcSrcEx = { 0, 0, m_bmpCache->Size().cx, m_bmpCache->Size().cy }; pRT->DrawBitmapEx(rcDraw, m_bmpCache, &rcSrcEx, GetExpandMode(), byAlpha); } else { RECT rcSrcEx = { 0, 0, m_pImg->Size().cx, m_pImg->Size().cy }; pRT->DrawBitmapEx(rcDraw, m_pImg, &rcSrcEx, GetExpandMode(), byAlpha); } //MakeCacheApha(pRT, rcDraw, rcSrc, byAlpha); } private: CAutoRefPtr<IBitmap> m_bmpMask; CAutoRefPtr<IBitmap> m_bmpCache; int m_iMaskChannel; // 对应 mask 的rgb a // .a=3 .r=0 .g=1 .b=2 protected: SOUI_ATTRS_BEGIN() ATTR_CUSTOM(L"src", OnAttrSrc) ATTR_INT(L"mask_a", m_iMaskChannel, FALSE) // 要先设置这个 不然就用默认 ATTR_CUSTOM(L"mask", OnAttrMask) //image.a SOUI_ATTRS_END() protected: HRESULT OnAttrSrc(const SStringW& strValue, BOOL bLoading) { m_pImg = LOADIMAGE2(strValue); if(NULL == m_pImg) return E_FAIL; if(NULL != m_bmpMask) MakeCacheApha(); return bLoading ? S_OK : S_FALSE; } HRESULT OnAttrMask(const SStringW& strValue, BOOL bLoading) { IBitmap* pImg = NULL; pImg = LOADIMAGE2(strValue); if (!pImg) { return E_FAIL; } m_bmpMask = pImg; pImg->Release(); m_bmpCache = NULL; GETRENDERFACTORY->CreateBitmap(&m_bmpCache); m_bmpCache->Init(m_bmpMask->Width(),m_bmpMask->Height()); if(NULL != m_pImg) MakeCacheApha(); return S_OK; } void MakeCacheApha() { SASSERT(m_bmpMask && m_bmpCache); CAutoRefPtr<IRenderTarget> pRTDst; GETRENDERFACTORY->CreateRenderTarget(&pRTDst, 0, 0); CAutoRefPtr<IRenderObj> pOldBmp; pRTDst->SelectObject(m_bmpCache, &pOldBmp); CRect rc(CPoint(0, 0), m_bmpCache->Size()); CRect rcSrc(CPoint(0, 0), m_pImg->Size()); pRTDst->DrawBitmapEx(rc, m_pImg, &rcSrc, GetExpandMode()); pRTDst->SelectObject(pOldBmp); //从mask的指定channel中获得alpha通道 LPBYTE pBitCache = (LPBYTE)m_bmpCache->LockPixelBits(); LPBYTE pBitMask = (LPBYTE)m_bmpMask->LockPixelBits(); LPBYTE pDst = pBitCache; LPBYTE pSrc = pBitMask + m_iMaskChannel; int nPixels = m_bmpCache->Width()*m_bmpCache->Height(); for(int i=0; i<nPixels; i++) { BYTE byAlpha = *pSrc; pSrc += 4; //源半透明,mask不透明时使用源的半透明属性 if(pDst[3] == 0xff || (pDst[3]!=0xFF &&byAlpha == 0)) {//源不透明,或者mask全透明 *pDst++ = ((*pDst) * byAlpha)>>8;//做premultiply *pDst++ = ((*pDst) * byAlpha)>>8;//做premultiply *pDst++ = ((*pDst) * byAlpha)>>8;//做premultiply *pDst++ = byAlpha; } } m_bmpCache->UnlockPixelBits(pBitCache); m_bmpMask->UnlockPixelBits(pBitMask); } }; ////////////////////////////////////////////////////////////////////////// #endif // __WINFILE_ICON_SKIN_HPP_
24.143836
84
0.63461
wzaen
5519511b177d6bb29e019d6aaec7cb1ec9265209
2,679
cpp
C++
vcf/VCFBuilder2/SelectionManager.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
46
2015-12-04T17:12:58.000Z
2022-03-11T04:30:49.000Z
vcf/VCFBuilder2/SelectionManager.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
null
null
null
vcf/VCFBuilder2/SelectionManager.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
23
2016-10-24T09:18:14.000Z
2022-02-25T02:11:35.000Z
//SelectionManager.h #include "ApplicationKit.h" #include "SelectionManager.h" #include <algorithm> using namespace VCF; using namespace VCFBuilder; SelectionManager SelectionManager::selectionMgrInstance; SelectionManager::SelectionManager() { init(); } SelectionManager::~SelectionManager() { m_scheduledControlsToBeDeleted.clear(); m_controlsToBeDeleted.clear(); } void SelectionManager::init() { INIT_EVENT_HANDLER_LIST(SelectionChanged) m_selectionContainer.initContainer( m_selectionSet ); } Enumerator<Component*>* SelectionManager::getSelectionSet() { return m_selectionContainer.getEnumerator(); } bool SelectionManager::isComponentInSelectionSet( Component* component ) { bool result = false; std::vector<Component*>::iterator found = std::find( m_selectionSet.begin(), m_selectionSet.end() , component ); result = ( found != m_selectionSet.end() ); return result; } void SelectionManager::addToSelectionSet( Component* component ) { m_selectionSet.push_back( component ); SelectionManagerEvent event( this, SELECTION_MGR_ITEM_ADDED ); fireOnSelectionChanged( &event ); } void SelectionManager::removeFromSelectionSet( Component* component ) { std::vector<Component*>::iterator found = std::find( m_selectionSet.begin(), m_selectionSet.end() , component ); if ( found != m_selectionSet.end() ) { SelectionManagerEvent event( this, SELECTION_MGR_ITEM_REMOVED ); fireOnSelectionChanged( &event ); m_selectionSet.erase( found ); } } SelectionManager* SelectionManager::getSelectionMgr() { return &SelectionManager::selectionMgrInstance; } void SelectionManager::clearSelectionSet() { SelectionManagerEvent event( this, SELECTION_MGR_ITEMS_CLEARED ); fireOnSelectionChanged( &event ); m_selectionSet.clear(); } void SelectionManager::scheduleControlForDeletion( Control* control ) { m_scheduledControlsToBeDeleted.push_back( control ); } void SelectionManager::cleanUpDeletableControls() { std::vector<Control*>::iterator it = m_scheduledControlsToBeDeleted.begin(); while ( it != m_scheduledControlsToBeDeleted.end() ) { Control* control = *it; control->setComponentState( CS_DESTROYING ); it ++; } it = m_controlsToBeDeleted.begin(); while ( it != m_controlsToBeDeleted.end() ) { Control* control = *it; delete control; control = NULL; it ++; } m_controlsToBeDeleted.clear(); it = m_scheduledControlsToBeDeleted.begin(); while ( it != m_scheduledControlsToBeDeleted.end() ) { Control* control = *it; m_controlsToBeDeleted.push_back( control ); it ++; } m_scheduledControlsToBeDeleted.clear(); }
24.577982
114
0.736096
tharindusathis
551bf1e59d207439ecad87f4c13dd45bf661eff0
3,519
hpp
C++
3rdParty/boost/1.71.0/libs/parameter/test/deduced.hpp
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
12,278
2015-01-29T17:11:33.000Z
2022-03-31T21:12:00.000Z
3rdParty/boost/1.71.0/libs/parameter/test/deduced.hpp
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
9,469
2015-01-30T05:33:07.000Z
2022-03-31T16:17:21.000Z
3rdParty/boost/1.71.0/libs/parameter/test/deduced.hpp
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
892
2015-01-29T16:26:19.000Z
2022-03-20T07:44:30.000Z
// Copyright Daniel Wallin 2006. // Copyright Cromwell D. Enage 2017. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_DEDUCED_060920_HPP #define BOOST_DEDUCED_060920_HPP #include <boost/parameter/config.hpp> #include "basics.hpp" #if defined(BOOST_PARAMETER_CAN_USE_MP11) #include <boost/mp11/map.hpp> #include <boost/mp11/algorithm.hpp> #else #include <boost/mpl/bool.hpp> #include <boost/mpl/if.hpp> #include <boost/mpl/for_each.hpp> #include <boost/mpl/assert.hpp> #include <boost/type_traits/is_same.hpp> #endif namespace test { struct not_present_tag { }; not_present_tag not_present; template <typename E, typename ArgPack> class assert_expected { E const& _expected; ArgPack const& _args; public: assert_expected(E const& e, ArgPack const& args_) : _expected(e), _args(args_) { } template <typename T> static bool check_not_present(T const&) { #if defined(BOOST_PARAMETER_CAN_USE_MP11) static_assert( std::is_same<T,test::not_present_tag>::value , "T == test::not_present_tag" ); #else BOOST_MPL_ASSERT(( typename boost::mpl::if_< boost::is_same<T,test::not_present_tag> , boost::mpl::true_ , boost::mpl::false_ >::type )); #endif return true; } template <typename K> bool check1(K const& k, test::not_present_tag const& t, long) const { return assert_expected<E,ArgPack>::check_not_present( this->_args[k | t] ); } template <typename K, typename Expected> bool check1(K const& k, Expected const& e, int) const { return test::equal(this->_args[k], e); } template <typename K> #if defined(BOOST_PARAMETER_CAN_USE_MP11) void operator()(K&&) const #else void operator()(K) const #endif { boost::parameter::keyword<K> const& k = boost::parameter::keyword<K>::instance; BOOST_TEST(this->check1(k, this->_expected[k], 0L)); } }; template <typename E, typename A> void check0(E const& e, A const& args) { #if defined(BOOST_PARAMETER_CAN_USE_MP11) boost::mp11::mp_for_each<boost::mp11::mp_map_keys<E> >( test::assert_expected<E,A>(e, args) ); #else boost::mpl::for_each<E>(test::assert_expected<E,A>(e, args)); #endif } #if defined(BOOST_PARAMETER_HAS_PERFECT_FORWARDING) template <typename P, typename E, typename ...Args> void check(E const& e, Args const&... args) { test::check0(e, P()(args...)); } #else template <typename P, typename E, typename A0> void check(E const& e, A0 const& a0) { test::check0(e, P()(a0)); } template <typename P, typename E, typename A0, typename A1> void check(E const& e, A0 const& a0, A1 const& a1) { test::check0(e, P()(a0, a1)); } template <typename P, typename E, typename A0, typename A1, typename A2> void check(E const& e, A0 const& a0, A1 const& a1, A2 const& a2) { test::check0(e, P()(a0, a1, a2)); } #endif // BOOST_PARAMETER_HAS_PERFECT_FORWARDING } // namespace test #endif // include guard
26.659091
76
0.596476
rajeev02101987
55210b4c09d6343a045c00f1aab3c56a53b7accc
842
cpp
C++
30days/day26.cpp
sagi-z/hackerrank
ba6c75947626adb8b0fc89868cb3cb86f60aaa14
[ "MIT" ]
null
null
null
30days/day26.cpp
sagi-z/hackerrank
ba6c75947626adb8b0fc89868cb3cb86f60aaa14
[ "MIT" ]
null
null
null
30days/day26.cpp
sagi-z/hackerrank
ba6c75947626adb8b0fc89868cb3cb86f60aaa14
[ "MIT" ]
null
null
null
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <iterator> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int d1, m1, y1; int d2, m2, y2; istream_iterator<int> iter(cin); d1 = *iter++; m1 = *iter++; y1 = *iter++; d2 = *iter++; m2 = *iter++; y2 = *iter; int factor = 0; int baseFine = 0; if (y1 > y2) { baseFine = 10000; factor = 1; } else if (y1 == y2) { if (m1 > m2) { baseFine = 500; factor = m1 - m2; } else if (m1 == m2) { if (d1 > d2) { baseFine = 15; factor = d1 - d2; } } } cout << baseFine * factor << endl; return 0; }
18.711111
80
0.465558
sagi-z
55258619dc7b0fa1b8366e9eafff443d00ac4825
552
cpp
C++
classeA.cpp
RafaelNatsu/Projeto_Rafael_Natsu
71360db1788a2d3aa7d57de41ff90bff9e48f8bb
[ "MIT" ]
null
null
null
classeA.cpp
RafaelNatsu/Projeto_Rafael_Natsu
71360db1788a2d3aa7d57de41ff90bff9e48f8bb
[ "MIT" ]
null
null
null
classeA.cpp
RafaelNatsu/Projeto_Rafael_Natsu
71360db1788a2d3aa7d57de41ff90bff9e48f8bb
[ "MIT" ]
null
null
null
#include "classeA.hpp" classeA::classeA() { A1 = 0; A2 = 0; } classeA::~classeA(){} void classeA::MA1() { std::cout << "Metodo MA1" << std::endl; } void classeA::MA2() { std::cout << "Metodo MA2" << std::endl; } void classeA::MA3() { std::cout << "Alteração a classe A partir do clone" << std::endl; } int classeA::getA1() { return A1; } void classeA::setA1(int _a1) { A1 = _a1; } float classeA::getA2() { return A2; } void classeA::setA2(float _a2) { A2= _a2; }
12.266667
70
0.519928
RafaelNatsu
552cc14700be68dce24bfb788e63b032eb9147b9
5,737
cpp
C++
wznmcmbd/CrdWznmOpx/PnlWznmOpxDetail_evals.cpp
mpsitech/wznm-WhizniumSBE
4911d561b28392d485c46e98fb915168d82b3824
[ "MIT" ]
3
2020-09-20T16:24:48.000Z
2021-12-01T19:44:51.000Z
wznmcmbd/CrdWznmOpx/PnlWznmOpxDetail_evals.cpp
mpsitech/wznm-WhizniumSBE
4911d561b28392d485c46e98fb915168d82b3824
[ "MIT" ]
null
null
null
wznmcmbd/CrdWznmOpx/PnlWznmOpxDetail_evals.cpp
mpsitech/wznm-WhizniumSBE
4911d561b28392d485c46e98fb915168d82b3824
[ "MIT" ]
null
null
null
/** * \file PnlWznmOpxDetail_evals.cpp * job handler for job PnlWznmOpxDetail (implementation of availability/activation evaluation) * \copyright (C) 2016-2020 MPSI Technologies GmbH * \author Alexander Wirthmueller (auto-generation) * \date created: 28 Nov 2020 */ // IP header --- ABOVE using namespace std; using namespace Sbecore; using namespace Xmlio; bool PnlWznmOpxDetail::evalButSaveAvail( DbsWznm* dbswznm ) { // pre.ixCrdaccOpxIncl(edit) vector<bool> args; bool a; a = false; a = (xchg->getIxPreset(VecWznmVPreset::PREWZNMIXCRDACCOPX, jref) & VecWznmWAccess::EDIT); args.push_back(a); return(args.back()); }; bool PnlWznmOpxDetail::evalButSaveActive( DbsWznm* dbswznm ) { // dirty() vector<bool> args; bool a; a = false; a = dirty; args.push_back(a); return(args.back()); }; bool PnlWznmOpxDetail::evalTxtSrfActive( DbsWznm* dbswznm ) { // pre.ixCrdaccOpxIncl(edit) vector<bool> args; bool a; a = false; a = (xchg->getIxPreset(VecWznmVPreset::PREWZNMIXCRDACCOPX, jref) & VecWznmWAccess::EDIT); args.push_back(a); return(args.back()); }; bool PnlWznmOpxDetail::evalTxtOpkActive( DbsWznm* dbswznm ) { // pre.ixCrdaccOpxIncl(edit) vector<bool> args; bool a; a = false; a = (xchg->getIxPreset(VecWznmVPreset::PREWZNMIXCRDACCOPX, jref) & VecWznmWAccess::EDIT); args.push_back(a); return(args.back()); }; bool PnlWznmOpxDetail::evalButOpkViewAvail( DbsWznm* dbswznm ) { // opx.opkEq(0)|(pre.ixCrdaccOpk()&pre.refVer()) vector<bool> args; bool a, b; a = false; a = (recOpx.refWznmMOppack == 0); args.push_back(a); a = false; a = (xchg->getIxPreset(VecWznmVPreset::PREWZNMIXCRDACCOPK, jref) != 0); args.push_back(a); a = false; a = (xchg->getRefPreset(VecWznmVPreset::PREWZNMREFVER, jref) != 0); args.push_back(a); b = args.back(); args.pop_back(); a = args.back(); args.pop_back(); args.push_back(a && b); b = args.back(); args.pop_back(); a = args.back(); args.pop_back(); args.push_back(a || b); return(args.back()); }; bool PnlWznmOpxDetail::evalButOpkViewActive( DbsWznm* dbswznm ) { // !opx.opkEq(0) vector<bool> args; bool a; a = false; a = (recOpx.refWznmMOppack == 0); args.push_back(a); a = args.back(); args.pop_back(); args.push_back(!a); return(args.back()); }; bool PnlWznmOpxDetail::evalChkShdActive( DbsWznm* dbswznm ) { // pre.ixCrdaccOpxIncl(edit) vector<bool> args; bool a; a = false; a = (xchg->getIxPreset(VecWznmVPreset::PREWZNMIXCRDACCOPX, jref) & VecWznmWAccess::EDIT); args.push_back(a); return(args.back()); }; bool PnlWznmOpxDetail::evalTxfCmtActive( DbsWznm* dbswznm ) { // pre.ixCrdaccOpxIncl(edit) vector<bool> args; bool a; a = false; a = (xchg->getIxPreset(VecWznmVPreset::PREWZNMIXCRDACCOPX, jref) & VecWznmWAccess::EDIT); args.push_back(a); return(args.back()); }; bool PnlWznmOpxDetail::evalButSqkNewAvail( DbsWznm* dbswznm ) { // pre.ixCrdaccOpxIncl(edit)&opx.sqkEq(0) vector<bool> args; bool a, b; a = false; a = (xchg->getIxPreset(VecWznmVPreset::PREWZNMIXCRDACCOPX, jref) & VecWznmWAccess::EDIT); args.push_back(a); a = false; a = (recOpx.refWznmMSquawk == 0); args.push_back(a); b = args.back(); args.pop_back(); a = args.back(); args.pop_back(); args.push_back(a && b); return(args.back()); }; bool PnlWznmOpxDetail::evalButSqkDeleteAvail( DbsWznm* dbswznm ) { // pre.ixCrdaccOpxIncl(edit)&!opx.sqkEq(0) vector<bool> args; bool a, b; a = false; a = (xchg->getIxPreset(VecWznmVPreset::PREWZNMIXCRDACCOPX, jref) & VecWznmWAccess::EDIT); args.push_back(a); a = false; a = (recOpx.refWznmMSquawk == 0); args.push_back(a); a = args.back(); args.pop_back(); args.push_back(!a); b = args.back(); args.pop_back(); a = args.back(); args.pop_back(); args.push_back(a && b); return(args.back()); }; bool PnlWznmOpxDetail::evalPupSqkJtiAvail( DbsWznm* dbswznm ) { // !opx.sqkEq(0) vector<bool> args; bool a; a = false; a = (recOpx.refWznmMSquawk == 0); args.push_back(a); a = args.back(); args.pop_back(); args.push_back(!a); return(args.back()); }; bool PnlWznmOpxDetail::evalPupSqkJtiActive( DbsWznm* dbswznm ) { // pre.ixCrdaccOpxIncl(edit) vector<bool> args; bool a; a = false; a = (xchg->getIxPreset(VecWznmVPreset::PREWZNMIXCRDACCOPX, jref) & VecWznmWAccess::EDIT); args.push_back(a); return(args.back()); }; bool PnlWznmOpxDetail::evalButSqkJtiEditAvail( DbsWznm* dbswznm ) { // pre.ixCrdaccOpxIncl(edit) vector<bool> args; bool a; a = false; a = (xchg->getIxPreset(VecWznmVPreset::PREWZNMIXCRDACCOPX, jref) & VecWznmWAccess::EDIT); args.push_back(a); return(args.back()); }; bool PnlWznmOpxDetail::evalTxtSqkTitAvail( DbsWznm* dbswznm ) { // !opx.sqkEq(0) vector<bool> args; bool a; a = false; a = (recOpx.refWznmMSquawk == 0); args.push_back(a); a = args.back(); args.pop_back(); args.push_back(!a); return(args.back()); }; bool PnlWznmOpxDetail::evalTxtSqkTitActive( DbsWznm* dbswznm ) { // pre.ixCrdaccOpxIncl(edit) vector<bool> args; bool a; a = false; a = (xchg->getIxPreset(VecWznmVPreset::PREWZNMIXCRDACCOPX, jref) & VecWznmWAccess::EDIT); args.push_back(a); return(args.back()); }; bool PnlWznmOpxDetail::evalTxfSqkExaAvail( DbsWznm* dbswznm ) { // !opx.sqkEq(0) vector<bool> args; bool a; a = false; a = (recOpx.refWznmMSquawk == 0); args.push_back(a); a = args.back(); args.pop_back(); args.push_back(!a); return(args.back()); }; bool PnlWznmOpxDetail::evalTxfSqkExaActive( DbsWznm* dbswznm ) { // pre.ixCrdaccOpxIncl(edit) vector<bool> args; bool a; a = false; a = (xchg->getIxPreset(VecWznmVPreset::PREWZNMIXCRDACCOPX, jref) & VecWznmWAccess::EDIT); args.push_back(a); return(args.back()); };
20.41637
101
0.682587
mpsitech
552e4bb200ddc0eb455b2eca6355e0bac53347f8
13,531
cpp
C++
decoder/YAIK_Alpha.cpp
KLab/YAIK
55ecf9b8eac0b2b67c4cb52b997e81930e94f9bf
[ "MIT" ]
4
2020-05-26T02:21:35.000Z
2022-01-13T12:05:28.000Z
decoder/YAIK_Alpha.cpp
KLab/YAIK
55ecf9b8eac0b2b67c4cb52b997e81930e94f9bf
[ "MIT" ]
null
null
null
decoder/YAIK_Alpha.cpp
KLab/YAIK
55ecf9b8eac0b2b67c4cb52b997e81930e94f9bf
[ "MIT" ]
null
null
null
#include "YAIK_functions.h" // memset, memcpy #include <memory.h> /* ----------------------------------------------------------------------------- 2. Decompression technique for Alpha ----------------------------------------------------------------------------- */ bool CheckInBound2D(YAIK_Instance* pCtx, BoundingBox& bbox) { // Check that all values are POSITIVE. if ((bbox.x|bbox.y|bbox.w|bbox.h) < 0) { return false; } // Check that X0,Y0 is inside image. (Included) if ((bbox.x >= pCtx->width) || (bbox.y >= pCtx->height)) { return false; } // Check that X1,Y1 are inside image.(Excluded) if (((bbox.x+bbox.w) > pCtx->width) || ((bbox.y+bbox.h) > pCtx->height)) { return false; } } bool Decompress1BitMaskAlign8NoMask(YAIK_Instance* pCtx, BoundingBox& header_bbox, u8* data_uncompressed, u32 data_size) { BoundingBox& bbox = header_bbox; u32 width = pCtx->width; u32 height = pCtx->height; // Match file width/height if (!CheckInBound2D(pCtx, bbox)) { return false; } // Check before doing allocation. if (data_size < ((bbox.w>>3)*bbox.h)) { return false; } if ((bbox.h > 0) && (bbox.w > 0)) { //Heap Temp Allocator // [Alloc for stream decompression of size] pCtx->alphaChannel = (u8*)AllocateMem(&pCtx->allocCtx, width * height); if (pCtx->alphaChannel == NULL) { return false; } // No empty surface allowed. // 8 pixel aligned. kassert((bbox.x & 7) == 0); kassert((bbox.w & 7) == 0); /* Fill mask with optimization to the length and call count to memset and memcpy. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAA.................BBBBBBBB BBBBBB.................BBBBBBBB BBBBBB.................CCCCCCCC CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC */ u8* pDst = pCtx->alphaChannel; // Section [AAAA] int stepA = (bbox.x + (bbox.y * width)); // Section [....] int stepD = bbox.w; // Section [BBBB] int stepB = (width - bbox.w); // Section [CCCC] int endY1 = (bbox.y + bbox.h); int stepC = ((width - (bbox.x + bbox.w))) + (((height - (endY1)) * width)); if (stepA) { memset(pDst, 0, stepA); pDst += stepA; } int blkCnt = stepD >> 3; // By 8 pixel each. // TODO OPTIMIZE [Could optimize loop using ptr] int endY = endY1 - 1; for (int y = bbox.y; y <= endY; y++) { // Section [....] // [TODO] Fill with bitmap 1 bit -> 8 bit. memcpy(pDst, mipmapMaskStream, stepD); int cnt = blkCnt; while (--cnt) { int v = *data_uncompressed++; *pDst++ = ((v & 0x01) << 31) >> 31; // 0 or 255 write. *pDst++ = ((v & 0x02) << 30) >> 31; // 0 or 255 write. *pDst++ = ((v & 0x04) << 29) >> 31; // 0 or 255 write. *pDst++ = ((v & 0x08) << 28) >> 31; // 0 or 255 write. *pDst++ = ((v & 0x10) << 27) >> 31; // 0 or 255 write. *pDst++ = ((v & 0x20) << 26) >> 31; // 0 or 255 write. *pDst++ = ((v & 0x40) << 25) >> 31; // 0 or 255 write. *pDst++ = ((v & 0x80) << 24) >> 31; // 0 or 255 write. } // Section [BBBB] or [CCCC] (last) int stepDo = (y != endY) ? stepB : stepC; memset(pDst, 0, stepDo); pDst += stepDo; } return true; } else { return false; } } bool Decompress6BitTo8BitAlphaNoMask(YAIK_Instance* pCtx, AlphaHeader* header, bool useInverseValues, u8* data_uncompressed, u32 data_size) { BoundingBox& bbox = header->bbox; // Match file width/height if (!CheckInBound2D(pCtx, bbox)) { return false; } // Check before doing allocation. if (data_size < ((bbox.w>>3)*bbox.h)) { return false; } if ((header->bbox.h > 0) && (header->bbox.w > 0)) { u32 width = pCtx->width; u32 height = pCtx->height; // No empty surface allowed. // Heap Buffer Allocator : // [Target Buffer Mask w*h] pCtx->alphaChannel = (u8*)AllocateMem(&pCtx->allocCtx, width * height); if (pCtx->alphaChannel == NULL) { return false; } u8* alphaChannel = pCtx->alphaChannel; u8* alphaMaskStream = data_uncompressed; int dstWidth = pCtx->width; /* Fill mask with optimization to the length and call count to memset and memcpy. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAA.................BBBBBBBB BBBBBB.................BBBBBBBB BBBBBB.................CCCCCCCC CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC */ u8* pDst = alphaChannel; // Section [AAAA] int stepA = (bbox.x + (bbox.y * dstWidth)); // Section [....] int stepD = bbox.w; // Section [BBBB] int stepB = (dstWidth - bbox.w); // Section [CCCC] int endY1 = (bbox.y + bbox.h); int stepC = ((dstWidth - (bbox.x + bbox.w))) + (((pCtx->height - (endY1)) * dstWidth)); if (stepA) { memset(pDst, 0, stepA); pDst += stepA; } int endY = endY1 - 1; int state = 0; int blockPerLine = bbox.w >> 2; // div 4 kassert((bbox.w & 3) == 0); u8 workV; // TODO OPTIMIZE [Could optimize loop using ptr for Y...] for (int y = bbox.y; y <= endY; y++) { // Decompress by block of 4 pixels u8* endBlk = &alphaMaskStream[blockPerLine * 3]; if (useInverseValues) { /** Decompress single line of 4 value blocks. Stream is array of 6 bit with inverted values (0=>31, 31=>0) Value is then upscaled from 6 bit to 8 bit (proper mathematically correct : [abcdef] -> [abcdefab] => Same as (v * 255 / 31) */ while (alphaMaskStream < endBlk) { // bbaaaaaa u8 v = *alphaMaskStream++; workV = 63 - (v & 0x3F); // aaaaaa *pDst++ = (workV << 2) | (workV >> 4); // 6 -> 8 bit. // ccccbbbb u8 v2 = *alphaMaskStream++; workV = 63 - ((v >> 6) | ((v2 & 0xF) << 2)); // bbbb.bb *pDst++ = (workV << 2) | (workV >> 4); // 6 -> 8 bit. // ddddddcc v = *alphaMaskStream++; workV = 63 - ((v2 >> 4) | ((v & 3) << 4)); // cc.cccc *pDst++ = (workV << 2) | (workV >> 4); // 6 -> 8 bit. workV = 63 - (v >> 2); // dddddd *pDst++ = (workV << 2) | (workV >> 4); // 6 -> 8 bit. } } else { /* Same as previous block, except that 6 bit values are NOT inverted inside the stream. */ while (alphaMaskStream < endBlk) { // bbaaaaaa u8 v = *alphaMaskStream++; workV = (v & 0x3F); // aaaaaa *pDst++ = (workV << 2) | (workV >> 4); // 6 -> 8 bit. // ccccbbbb u8 v2 = *alphaMaskStream++; workV = ((v >> 6) | ((v2 & 0xF) << 2)); // bbbb.bb *pDst++ = (workV << 2) | (workV >> 4); // 6 -> 8 bit. // ddddddcc v = *alphaMaskStream++; workV = ((v2 >> 4) | ((v & 3) << 4)); // cc.cccc *pDst++ = (workV << 2) | (workV >> 4); // 6 -> 8 bit. workV = (v >> 2); // dddddd *pDst++ = (workV << 2) | (workV >> 4); // 6 -> 8 bit. } } // Section [BBBB] or [CCCC] (last) int stepDo = (y != endY) ? stepB : stepC; memset(pDst, 0, stepDo); pDst += stepDo; } } return true; } bool Decompress6BitTo8BitAlphaUsingMipmapMask(YAIK_Instance* pCtx, AlphaHeader* header, bool useInverseValues, u8* data_uncompressed, u32 data_size) { if ((header->bbox.h > 0) && (header->bbox.w > 0)) { u32 width = pCtx->width; u32 height = pCtx->height; // No empty surface allowed. // Heap Buffer Allocator : // [Target Buffer Mask w*h] pCtx->alphaChannel = (u8*)AllocateMem(&pCtx->allocCtx, width * height); if (pCtx->alphaChannel == NULL) { return false; } u8* alphaChannel = pCtx->alphaChannel; u8* mipmapChannel = pCtx->mipMapMask; // Different bounding box !!! u32 strideMipmap = pCtx->maskBBox.w; BoundingBox alphaBBox = header->bbox; // Tricky : mipmap parsing in mipmap space is using alpha bounding box ! u32 mipmapPos = (alphaBBox.x - pCtx->maskBBox.x) + (strideMipmap * (alphaBBox.y - pCtx->maskBBox.y)); u8* alphaMaskStream = data_uncompressed; BoundingBox bbox = header->bbox; int dstWidth = pCtx->width; /* Fill mask with optimization to the length and call count to memset and memcpy. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAA.................BBBBBBBB BBBBBB.................BBBBBBBB BBBBBB.................CCCCCCCC CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC */ u8* pDst = alphaChannel; // Section [AAAA] int stepA = (bbox.x + (bbox.y * dstWidth)); // Section [....] int stepD = bbox.w; // Section [BBBB] int stepB = (dstWidth - bbox.w); // Section [CCCC] int endY1 = (bbox.y + bbox.h); int stepC = ((dstWidth - (bbox.x + bbox.w))) + (((pCtx->height - (endY1)) * dstWidth)); if (stepA) { memset(pDst, 0, stepA); pDst += stepA; } int endY = endY1 - 1; u8 workV; int state = 0; for (int y = bbox.y; y <= endY; y++) { u8 v,v2, writeV; int backupMipmapPos = mipmapPos; int mipmapPosE = mipmapPos + bbox.w; // [TODO] Possible optimization using left/right span if (useInverseValues) { do { u8 mipV = mipmapChannel[mipmapPos >> 3] & (1 << (mipmapPos & 7)); if (mipV == 0) { *pDst++ = 0; } else { switch (state & 3) { case 0: v = *alphaMaskStream++; workV = 63 - (v & 0x3F); // aaaaaa writeV = (workV << 2) | (workV >> 4); // 6 -> 8 bit. break; case 1: v2 = *alphaMaskStream++; workV = 63 - ((v >> 6) | ((v2 & 0xF) << 2)); // bbbb.bb writeV = (workV << 2) | (workV >> 4); // 6 -> 8 bit. break; case 2: v = *alphaMaskStream++; workV = 63 - ((v2 >> 4) | ((v & 0x3) << 4)); // cc.cccc writeV = (workV << 2) | (workV >> 4); // 6 -> 8 bit. break; case 3: workV = 63 - (v >> 2); // dddddd writeV = (workV << 2) | (workV >> 4); // 6 -> 8 bit. break; } *pDst++ = writeV; state++; } mipmapPos++; } while (mipmapPos != mipmapPosE); } else { do { u8 mipV = mipmapChannel[mipmapPos >> 3] & (1 << (mipmapPos & 7)); if (mipV == 0) { *pDst++ = 0; } else { switch (state & 3) { case 0: v = *alphaMaskStream++; workV = (v & 0x3F); // aaaaaa writeV = (workV << 2) | (workV >> 4); // 6 -> 8 bit. break; case 1: v2 = *alphaMaskStream++; workV = ((v >> 6) | ((v2 & 0xF) << 2)); // bbbb.bb writeV = (workV << 2) | (workV >> 4); // 6 -> 8 bit. break; case 2: v = *alphaMaskStream++; workV = ((v2 >> 4) | ((v & 0x3) << 4)); // cc.cccc writeV = (workV << 2) | (workV >> 4); // 6 -> 8 bit. break; case 3: workV = (v >> 2); // dddddd writeV = (workV << 2) | (workV >> 4); // 6 -> 8 bit. break; } *pDst++ = writeV; state++; } mipmapPos++; } while (mipmapPos != mipmapPosE); } mipmapPos = backupMipmapPos + strideMipmap; // Section [BBBB] or [CCCC] (last) int stepDo = (y != endY) ? stepB : stepC; memset(pDst, 0, stepDo); pDst += stepDo; } } return true; } bool Decompress8BitTo8BitAlphaNoMask(YAIK_Instance* pCtx, AlphaHeader* header, u8* data_uncompressed, u32 data_size) { // TODO : Reuse from previous alpha stuff. // Support only through memcpy. if ((header->bbox.h > 0) && (header->bbox.w > 0)) { u32 width = pCtx->width; u32 height = pCtx->height; // No empty surface allowed. // Heap Buffer Allocator : // [Target Buffer Mask w*h] pCtx->alphaChannel = (u8*)AllocateMem(&pCtx->allocCtx, width * height); if (pCtx->alphaChannel == NULL) { return false; } u8* alphaChannel = pCtx->alphaChannel; u8* alphaMaskStream = data_uncompressed; BoundingBox bbox = header->bbox; int dstWidth = pCtx->width; /* Fill mask with optimization to the length and call count to memset and memcpy. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAA.................BBBBBBBB BBBBBB.................BBBBBBBB BBBBBB.................CCCCCCCC CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC */ u8* pDst = alphaChannel; // Section [AAAA] int stepA = (bbox.x + (bbox.y * dstWidth)); // Section [....] int stepD = bbox.w; // Section [BBBB] int stepB = (dstWidth - bbox.w); // Section [CCCC] int endY1 = (bbox.y + bbox.h); int stepC = ((dstWidth - (bbox.x + bbox.w))) + (((pCtx->height - (endY1)) * dstWidth)); if (stepA) { memset(pDst, 0, stepA); pDst += stepA; } int endY = endY1 - 1; int state = 0; int blockPerLine = bbox.w >> 2; // div 4 kassert((bbox.w & 3) == 0); // TODO OPTIMIZE [Could optimize loop using ptr for Y...] for (int y = bbox.y; y <= endY; y++) { // Decompress by block of 4 pixels memcpy(pDst, alphaMaskStream, stepD); pDst += stepD; alphaMaskStream += stepD; // Section [BBBB] or [CCCC] (last) int stepDo = (y != endY) ? stepB : stepC; memset(pDst, 0, stepDo); pDst += stepDo; } } return true; }
30.406742
151
0.538319
KLab
552ea5a5d0dee8d6d27ee878bf7c75c1e22c1589
10,777
cpp
C++
evs/src/v2/model/SnapshotDetails.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
5
2021-03-03T08:23:43.000Z
2022-02-16T02:16:39.000Z
evs/src/v2/model/SnapshotDetails.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
null
null
null
evs/src/v2/model/SnapshotDetails.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
7
2021-02-26T13:53:35.000Z
2022-03-18T02:36:43.000Z
#include "huaweicloud/evs/v2/model/SnapshotDetails.h" namespace HuaweiCloud { namespace Sdk { namespace Evs { namespace V2 { namespace Model { SnapshotDetails::SnapshotDetails() { id_ = ""; idIsSet_ = false; status_ = ""; statusIsSet_ = false; name_ = ""; nameIsSet_ = false; description_ = ""; descriptionIsSet_ = false; createdAt_ = ""; createdAtIsSet_ = false; updatedAt_ = ""; updatedAtIsSet_ = false; metadataIsSet_ = false; volumeId_ = ""; volumeIdIsSet_ = false; size_ = 0; sizeIsSet_ = false; osExtendedSnapshotAttributesprojectId_ = ""; osExtendedSnapshotAttributesprojectIdIsSet_ = false; osExtendedSnapshotAttributesprogress_ = ""; osExtendedSnapshotAttributesprogressIsSet_ = false; } SnapshotDetails::~SnapshotDetails() = default; void SnapshotDetails::validate() { } web::json::value SnapshotDetails::toJson() const { web::json::value val = web::json::value::object(); if(idIsSet_) { val[utility::conversions::to_string_t("id")] = ModelBase::toJson(id_); } if(statusIsSet_) { val[utility::conversions::to_string_t("status")] = ModelBase::toJson(status_); } if(nameIsSet_) { val[utility::conversions::to_string_t("name")] = ModelBase::toJson(name_); } if(descriptionIsSet_) { val[utility::conversions::to_string_t("description")] = ModelBase::toJson(description_); } if(createdAtIsSet_) { val[utility::conversions::to_string_t("created_at")] = ModelBase::toJson(createdAt_); } if(updatedAtIsSet_) { val[utility::conversions::to_string_t("updated_at")] = ModelBase::toJson(updatedAt_); } if(metadataIsSet_) { val[utility::conversions::to_string_t("metadata")] = ModelBase::toJson(metadata_); } if(volumeIdIsSet_) { val[utility::conversions::to_string_t("volume_id")] = ModelBase::toJson(volumeId_); } if(sizeIsSet_) { val[utility::conversions::to_string_t("size")] = ModelBase::toJson(size_); } if(osExtendedSnapshotAttributesprojectIdIsSet_) { val[utility::conversions::to_string_t("os-extended-snapshot-attributes:project_id")] = ModelBase::toJson(osExtendedSnapshotAttributesprojectId_); } if(osExtendedSnapshotAttributesprogressIsSet_) { val[utility::conversions::to_string_t("os-extended-snapshot-attributes:progress")] = ModelBase::toJson(osExtendedSnapshotAttributesprogress_); } return val; } bool SnapshotDetails::fromJson(const web::json::value& val) { bool ok = true; if(val.has_field(utility::conversions::to_string_t("id"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("id")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setId(refVal); } } if(val.has_field(utility::conversions::to_string_t("status"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("status")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setStatus(refVal); } } if(val.has_field(utility::conversions::to_string_t("name"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("name")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setName(refVal); } } if(val.has_field(utility::conversions::to_string_t("description"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("description")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setDescription(refVal); } } if(val.has_field(utility::conversions::to_string_t("created_at"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("created_at")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setCreatedAt(refVal); } } if(val.has_field(utility::conversions::to_string_t("updated_at"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("updated_at")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setUpdatedAt(refVal); } } if(val.has_field(utility::conversions::to_string_t("metadata"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("metadata")); if(!fieldValue.is_null()) { Object refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setMetadata(refVal); } } if(val.has_field(utility::conversions::to_string_t("volume_id"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("volume_id")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setVolumeId(refVal); } } if(val.has_field(utility::conversions::to_string_t("size"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("size")); if(!fieldValue.is_null()) { int32_t refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setSize(refVal); } } if(val.has_field(utility::conversions::to_string_t("os-extended-snapshot-attributes:project_id"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("os-extended-snapshot-attributes:project_id")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setOsExtendedSnapshotAttributesprojectId(refVal); } } if(val.has_field(utility::conversions::to_string_t("os-extended-snapshot-attributes:progress"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("os-extended-snapshot-attributes:progress")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setOsExtendedSnapshotAttributesprogress(refVal); } } return ok; } std::string SnapshotDetails::getId() const { return id_; } void SnapshotDetails::setId(const std::string& value) { id_ = value; idIsSet_ = true; } bool SnapshotDetails::idIsSet() const { return idIsSet_; } void SnapshotDetails::unsetid() { idIsSet_ = false; } std::string SnapshotDetails::getStatus() const { return status_; } void SnapshotDetails::setStatus(const std::string& value) { status_ = value; statusIsSet_ = true; } bool SnapshotDetails::statusIsSet() const { return statusIsSet_; } void SnapshotDetails::unsetstatus() { statusIsSet_ = false; } std::string SnapshotDetails::getName() const { return name_; } void SnapshotDetails::setName(const std::string& value) { name_ = value; nameIsSet_ = true; } bool SnapshotDetails::nameIsSet() const { return nameIsSet_; } void SnapshotDetails::unsetname() { nameIsSet_ = false; } std::string SnapshotDetails::getDescription() const { return description_; } void SnapshotDetails::setDescription(const std::string& value) { description_ = value; descriptionIsSet_ = true; } bool SnapshotDetails::descriptionIsSet() const { return descriptionIsSet_; } void SnapshotDetails::unsetdescription() { descriptionIsSet_ = false; } std::string SnapshotDetails::getCreatedAt() const { return createdAt_; } void SnapshotDetails::setCreatedAt(const std::string& value) { createdAt_ = value; createdAtIsSet_ = true; } bool SnapshotDetails::createdAtIsSet() const { return createdAtIsSet_; } void SnapshotDetails::unsetcreatedAt() { createdAtIsSet_ = false; } std::string SnapshotDetails::getUpdatedAt() const { return updatedAt_; } void SnapshotDetails::setUpdatedAt(const std::string& value) { updatedAt_ = value; updatedAtIsSet_ = true; } bool SnapshotDetails::updatedAtIsSet() const { return updatedAtIsSet_; } void SnapshotDetails::unsetupdatedAt() { updatedAtIsSet_ = false; } Object SnapshotDetails::getMetadata() const { return metadata_; } void SnapshotDetails::setMetadata(const Object& value) { metadata_ = value; metadataIsSet_ = true; } bool SnapshotDetails::metadataIsSet() const { return metadataIsSet_; } void SnapshotDetails::unsetmetadata() { metadataIsSet_ = false; } std::string SnapshotDetails::getVolumeId() const { return volumeId_; } void SnapshotDetails::setVolumeId(const std::string& value) { volumeId_ = value; volumeIdIsSet_ = true; } bool SnapshotDetails::volumeIdIsSet() const { return volumeIdIsSet_; } void SnapshotDetails::unsetvolumeId() { volumeIdIsSet_ = false; } int32_t SnapshotDetails::getSize() const { return size_; } void SnapshotDetails::setSize(int32_t value) { size_ = value; sizeIsSet_ = true; } bool SnapshotDetails::sizeIsSet() const { return sizeIsSet_; } void SnapshotDetails::unsetsize() { sizeIsSet_ = false; } std::string SnapshotDetails::getOsExtendedSnapshotAttributesprojectId() const { return osExtendedSnapshotAttributesprojectId_; } void SnapshotDetails::setOsExtendedSnapshotAttributesprojectId(const std::string& value) { osExtendedSnapshotAttributesprojectId_ = value; osExtendedSnapshotAttributesprojectIdIsSet_ = true; } bool SnapshotDetails::osExtendedSnapshotAttributesprojectIdIsSet() const { return osExtendedSnapshotAttributesprojectIdIsSet_; } void SnapshotDetails::unsetosExtendedSnapshotAttributesprojectId() { osExtendedSnapshotAttributesprojectIdIsSet_ = false; } std::string SnapshotDetails::getOsExtendedSnapshotAttributesprogress() const { return osExtendedSnapshotAttributesprogress_; } void SnapshotDetails::setOsExtendedSnapshotAttributesprogress(const std::string& value) { osExtendedSnapshotAttributesprogress_ = value; osExtendedSnapshotAttributesprogressIsSet_ = true; } bool SnapshotDetails::osExtendedSnapshotAttributesprogressIsSet() const { return osExtendedSnapshotAttributesprogressIsSet_; } void SnapshotDetails::unsetosExtendedSnapshotAttributesprogress() { osExtendedSnapshotAttributesprogressIsSet_ = false; } } } } } }
25.00464
153
0.673286
yangzhaofeng
55307bf0b102da1dcbeca82bac7ed73adf53a86a
8,215
cpp
C++
MyProcessInjectControl/MFCMyProcCtlUI/MFCMyProcCtlUIDlg.cpp
shc0743/CLearn
e6580588102bb66fb76903deb6699f19b38f4676
[ "MIT" ]
null
null
null
MyProcessInjectControl/MFCMyProcCtlUI/MFCMyProcCtlUIDlg.cpp
shc0743/CLearn
e6580588102bb66fb76903deb6699f19b38f4676
[ "MIT" ]
null
null
null
MyProcessInjectControl/MFCMyProcCtlUI/MFCMyProcCtlUIDlg.cpp
shc0743/CLearn
e6580588102bb66fb76903deb6699f19b38f4676
[ "MIT" ]
null
null
null
 // MFCMyProcCtlUIDlg.cpp: 实现文件 // #include "pch.h" #include "framework.h" #include "MFCMyProcCtlUI.h" #include "MFCMyProcCtlUIDlg.h" #include "afxdialogex.h" #ifdef _DEBUG #define new DEBUG_NEW #endif #include <TlHelp32.h> using namespace std; CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // CMFCMyProcCtlUIDlg 对话框 CMFCMyProcCtlUIDlg::CMFCMyProcCtlUIDlg(CWnd* pParent /*=nullptr*/) : CDialogEx(IDD_MFCMYPROCCTLUI_DIALOG, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); hThread_refresh = NULL; //pImageList = new CImageList; //pImageList->Create(32, 32, ILC_COLOR32, 0, 1); } CMFCMyProcCtlUIDlg::~CMFCMyProcCtlUIDlg() { //delete pImageList; } void CMFCMyProcCtlUIDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Control(pDX, IDC_LIST_PROCS, m_list_procs); } BEGIN_MESSAGE_MAP(CMFCMyProcCtlUIDlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_BUTTON_REFRESH_PROCS, &CMFCMyProcCtlUIDlg::OnBnClickedButtonRefreshProcs) ON_BN_CLICKED(IDC_BUTTON_ATTACH_CONTROLLER, &CMFCMyProcCtlUIDlg::OnBnClickedButtonAttachController) ON_BN_CLICKED(IDC_BUTTON_DETACH_CONTROLLER, &CMFCMyProcCtlUIDlg::OnBnClickedButtonDetachController) END_MESSAGE_MAP() // CMFCMyProcCtlUIDlg 消息处理程序 DWORD __stdcall CMFCMyProcCtlUIDlg::Thread_RefreshList(PVOID arg) { CMFCMyProcCtlUIDlg* pobj = (CMFCMyProcCtlUIDlg*)arg; if (!pobj) return ERROR_INVALID_PARAMETER; pobj->GetDlgItem(IDC_BUTTON_ATTACH_CONTROLLER)->EnableWindow(0); pobj->GetDlgItem(IDC_BUTTON_DETACH_CONTROLLER)->EnableWindow(0); pobj->GetDlgItem(IDC_BUTTON_REFRESH_PROCS)->EnableWindow(0); pobj->m_list_procs.DeleteAllItems(); HANDLE hsnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (INVALID_HANDLE_VALUE == hsnap) return false; PROCESSENTRY32 pe = {0}; pe.dwSize = sizeof(PROCESSENTRY32); Process32First(hsnap, &pe); int index = 0; do { //HANDLE hProcess = // OpenProcess(pe.th32ProcessID, FALSE, PROCESS_QUERY_INFORMATION); //BOOL ok = FALSE; //if (hProcess) { // TCHAR buffer[2048] = { 0 }; DWORD size = 2047; // QueryFullProcessImageName(hProcess, 0, buffer, &size); // CloseHandle(hProcess); // HMODULE hMod = LoadLibrary(buffer); // if (hMod) { // pobj->pImageList->Add(LoadIcon(hMod, IDI_APPLICATION)); // ok = true; // } //} //if (!ok) { // pobj->pImageList->Add(LoadIcon(NULL, IDI_APPLICATION)); //} pobj->m_list_procs.InsertItem(index, to_wstring(pe.th32ProcessID).c_str()); pobj->m_list_procs.SetItemText(index, 1, pe.szExeFile); index++; } while (::Process32Next(hsnap, &pe)); ::CloseHandle(hsnap); if (pobj->cl.getopt(L"service-name")) { pobj->GetDlgItem(IDC_BUTTON_ATTACH_CONTROLLER)->EnableWindow(); pobj->GetDlgItem(IDC_BUTTON_DETACH_CONTROLLER)->EnableWindow(); } pobj->GetDlgItem(IDC_BUTTON_REFRESH_PROCS)->EnableWindow(); return 0; } BOOL CMFCMyProcCtlUIDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // 将“关于...”菜单项添加到系统菜单中。 // IDM_ABOUTBOX 必须在系统命令范围内。 ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != nullptr) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // 设置此对话框的图标。 当应用程序主窗口不是对话框时,框架将自动 // 执行此操作 SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 // TODO: 在此添加额外的初始化代码 m_list_procs.InsertColumn(0, L"PID", 0, 80, 0); m_list_procs.InsertColumn(1, L"Image Name", 0, 200, 0); m_list_procs.InsertItem(0, L"Loading"); m_list_procs.SetItemText(0, 1, L"Loading datas..."); //m_list_procs.SetImageList(pImageList, LVSIL_NORMAL); cl.parse(GetCommandLineW()); if (cl.getopt(L"service-name", ServiceName)) { CString wt; GetWindowText(wt); SetWindowTextW((L"[" + ServiceName + L"] - " + wt.GetBuffer()).c_str()); } try_create_reflush_thread: hThread_refresh = CreateThread(0, 0, Thread_RefreshList, this, 0, 0); if (hThread_refresh) { CloseHandle(hThread_refresh); } else { if (IDRETRY == MessageBox(L"CANNOT CREATE THREAD", 0, MB_ICONHAND | MB_RETRYCANCEL | MB_DEFBUTTON2)) goto try_create_reflush_thread; else EndDialog(-1); } return TRUE; // 除非将焦点设置到控件,否则返回 TRUE } void CMFCMyProcCtlUIDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialogEx::OnSysCommand(nID, lParam); } } // 如果向对话框添加最小化按钮,则需要下面的代码 // 来绘制该图标。 对于使用文档/视图模型的 MFC 应用程序, // 这将由框架自动完成。 void CMFCMyProcCtlUIDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // 用于绘制的设备上下文 SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // 使图标在工作区矩形中居中 int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // 绘制图标 dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } //当用户拖动最小化窗口时系统调用此函数取得光标 //显示。 HCURSOR CMFCMyProcCtlUIDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CMFCMyProcCtlUIDlg::OnBnClickedButtonRefreshProcs() { try_create_reflush_thread: hThread_refresh = CreateThread(0, 0, Thread_RefreshList, this, 0, 0); if (hThread_refresh) { CloseHandle(hThread_refresh); } else { if (IDRETRY == MessageBox(L"Cannot create thread", 0, MB_ICONHAND | MB_RETRYCANCEL | MB_DEFBUTTON2)) goto try_create_reflush_thread; } } bool CMFCMyProcCtlUIDlg::CheckAdminPriv() { if (!IsRunAsAdmin()) { if (IDRETRY == MessageBoxW(L"Administrator privileges are required to " "complete this operation.\nClick [Retry] to retry as an administrator.", L"Access is Denied", MB_ICONHAND | MB_RETRYCANCEL)) { if ((INT_PTR)ShellExecuteW(m_hWnd, L"runas", s2wc(GetProgramDir()), (L"/runas "s + GetCommandLineW()).c_str(), 0, 1) > 32) EndDialog(0); } return false; } return true; } void CMFCMyProcCtlUIDlg::OnBnClickedButtonAttachController() { if (!CheckAdminPriv()) return; POSITION pos = m_list_procs.GetFirstSelectedItemPosition(); if (pos != NULL) { while (pos) { int nItem = m_list_procs.GetNextSelectedItem(pos); // nItem是所选中行的序号 CString text = m_list_procs.GetItemText(nItem, 0); DWORD pid = atol(ws2c(text.GetBuffer())); HANDLE hPipe = NULL; WCHAR pipe_name[256]{ 0 }; DWORD tmp = 0; LoadStringW(NULL, IDS_STRING_SVC_CTRLPIPE, pipe_name, 255); wcscat_s(pipe_name, L"\\"); wcscat_s(pipe_name, ServiceName.c_str()); if (::WaitNamedPipeW(pipe_name, 10000)) { #pragma warning(push) #pragma warning(disable: 6001) hPipe = ::CreateFileW(pipe_name, GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if (!hPipe || hPipe == INVALID_HANDLE_VALUE) { MessageBoxW(LastErrorStrW().c_str(), NULL, MB_ICONHAND); break; } DWORD dwMode = PIPE_READMODE_MESSAGE; (VOID)SetNamedPipeHandleState( hPipe, // pipe handle &dwMode, // new pipe mode NULL, // don't set maximum bytes NULL); // don't set maximum time string str = "Attach-Process-Control /pid=" + to_string(pid); ::WriteFile(hPipe, str.c_str(), (DWORD)str.length(), &tmp, NULL); auto _sub1 = [&] { MessageBox((_T("Error: "s) + ErrorCodeToString(atol(ws2s(pipe_name).c_str())) + TEXT("\nRaw data:") + pipe_name) .c_str(), 0, MB_ICONHAND); }; if (ReadFile(hPipe, pipe_name, 255, &tmp, 0)) { if (0 == wcscmp(L"0", pipe_name)) { MessageBox(ErrorCodeToString(0).c_str(), 0, MB_ICONINFORMATION); } else _sub1(); } else _sub1(); ::CloseHandle(hPipe); #pragma warning(pop) } else { MessageBoxW(ErrorCodeToStringW(ERROR_TIMEOUT).c_str(), 0, MB_ICONHAND); } } } } void CMFCMyProcCtlUIDlg::OnBnClickedButtonDetachController() { if (!CheckAdminPriv()) return; }
26.246006
79
0.709677
shc0743
5530e9403ac3d0816100568113bbfd0b164ef4e4
721
cpp
C++
test/smoke/fast_fp_atomics/fast_fp_atomics.cpp
raramakr/aomp
9a224fe01ca8eff4209b8b79aa1fa15a18da65db
[ "Apache-2.0" ]
null
null
null
test/smoke/fast_fp_atomics/fast_fp_atomics.cpp
raramakr/aomp
9a224fe01ca8eff4209b8b79aa1fa15a18da65db
[ "Apache-2.0" ]
null
null
null
test/smoke/fast_fp_atomics/fast_fp_atomics.cpp
raramakr/aomp
9a224fe01ca8eff4209b8b79aa1fa15a18da65db
[ "Apache-2.0" ]
null
null
null
#include<stdio.h> #include<omp.h> int main() { double sum = 0.0; int n = 10000; #pragma omp target teams distribute parallel for map(tofrom:sum) for(int i = 0; i < n; i++) { #pragma omp atomic hint(AMD_safe_fp_atomics) sum+=1.0; } int err = 0; if (sum != (double) n) { printf("Error with safe fp atomics, got %lf, expected %lf", sum, (double) n); err = 1; } sum = 0.0; #pragma omp target teams distribute parallel for map(tofrom:sum) for(int i = 0; i < n; i++) { #pragma omp atomic hint(AMD_fast_fp_atomics) sum+=1.0; } if (sum != (double) n) { printf("Error with unsafe fp atomics, got %lf, expected %lf", sum, (double) n); err = 1; } return err; }
20.6
83
0.590846
raramakr
5530faf5a36ee97a940185b4620737dd2bc95ae6
2,491
cpp
C++
POO/Seminar 2/S2p2claseImplicit.cpp
ParaschivAlex/FMI-Thangs
26d8a13b08344744ee6ab56f088dd4adb665980e
[ "MIT" ]
null
null
null
POO/Seminar 2/S2p2claseImplicit.cpp
ParaschivAlex/FMI-Thangs
26d8a13b08344744ee6ab56f088dd4adb665980e
[ "MIT" ]
null
null
null
POO/Seminar 2/S2p2claseImplicit.cpp
ParaschivAlex/FMI-Thangs
26d8a13b08344744ee6ab56f088dd4adb665980e
[ "MIT" ]
null
null
null
#include <cstdlib> #include <iostream> using namespace std; class Complex { float re,im; public: void f(); }; /* pentru orice clasa compilatorul asigura implicit - un constructor de initializare -fara parametrii, - un constructor de copiere - un operator de atribuire - un destructor -constructorul de initializare se apeleaza -cind se aloca zona de memorie pt un obiect -constructorul de copiere se apeleaza -cind se aloca zona de memorie pt un obiect si se initializeaza cu un obiect existent -operatorul de atribuire se apeleaza cind se executa operatia de atribuire -destructorul se apeleaza cind se elibereaza zona de memorie a unui obiect */ int main() { Complex C1; /* se apeleaza constructorul de initializare putem gandi ca C1.Complex()*/ Complex *p;// nu se apeleaza constructorul -nu se aloca zona pt obiect p= new Complex; // se apeleaza constructorul de initializare -se aloca zona pt obiect Complex v[2]; // se apeleaza construtorul de initializare de 2 ori Complex C2=C1; // se apeleaza constructorul de copiere // putem gandi C2.Complex(C1); p=new Complex(C1);// se apeleaza constructorul de copiere C2=C1; // se apeleaza opereatorul de atribuire -obiectele deja create // C2.operator=(C1); {Complex C3;}// se apeleaza mai intai constructorul de initializare si mai apoi destructorul // putem gandi C3.~Complex() delete p; // se apeleaza destructorul } /* constructorul de copiere si operatorul de atribuire impliciti copiaza BIT CU BIT datele obiectului sursa in datele obiectului destinatie daca scriem un constructor de initializare - nu mai exista constructor de initializare implicit daca scriem un constructor de copiere -nu mai exista -constructor de initializare implicit -constructor de copiere implicit */ /* constructorul de copiere se apeleaza 1. la declararea cu initializare ex: Complex C2=C1; 2. la transmiterea unui obiect prin valoare intr-o functie: void f(Complex op){} f(C1); 3. la intoarcerea unui obiect prin valoare dintr-o functie Complex f1(){ Complex ol; return ol;} f1(); Atentie ! -la transmiterea unui obiect prin referinta -nu se apeleaza constructorul de copiere -la intoarcerea unui obiect prin referinta -nu se apeleaza constructorul de copiere */
38.921875
125
0.69169
ParaschivAlex
553345d2e3f5d662bb794c85bfdcafd0b77fc691
8,688
cpp
C++
Source/Qurses/util.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
9
2016-05-27T01:00:39.000Z
2021-04-01T08:54:46.000Z
Source/Qurses/util.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
1
2016-03-03T22:54:08.000Z
2016-03-03T22:54:08.000Z
Source/Qurses/util.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
4
2016-05-27T01:00:43.000Z
2018-08-19T08:47:49.000Z
/* Public Domain Curses */ #include "Qurses/curspriv.h" RCSID("$Id: util.c,v 1.71 2008/07/13 16:08:18 wmcbrine Exp $") /*man-start************************************************************** Name: util Synopsis: char *unctrl(chtype c); void filter(void); void use_env(bool x); int delay_output(int ms); int getcchar(const cchar_t *wcval, wchar_t *wch, attr_t *attrs, short *color_pair, void *opts); int setcchar(cchar_t *wcval, const wchar_t *wch, const attr_t attrs, short color_pair, const void *opts); wchar_t *wunctrl(cchar_t *wc); int PDC_mbtowc(wchar_t *pwc, const char *s, size_t n); size_t PDC_mbstowcs(wchar_t *dest, const char *src, size_t n); size_t PDC_wcstombs(char *dest, const wchar_t *src, size_t n); Description: unctrl() expands the text portion of the chtype c into a printable string. Control characters are changed to the "^X" notation; others are passed through. wunctrl() is the wide- character version of the function. filter() and use_env() are no-ops in PDCurses. delay_output() inserts an ms millisecond pause in output. getcchar() works in two modes: When wch is not NULL, it reads the cchar_t pointed to by wcval and stores the attributes in attrs, the color pair in color_pair, and the text in the wide-character string wch. When wch is NULL, getcchar() merely returns the number of wide characters in wcval. In either mode, the opts argument is unused. setcchar constructs a cchar_t at wcval from the wide-character text at wch, the attributes in attr and the color pair in color_pair. The opts argument is unused. Currently, the length returned by getcchar() is always 1 or 0. Similarly, setcchar() will only take the first wide character from wch, and ignore any others that it "should" take (i.e., combining characters). Nor will it correctly handle any character outside the basic multilingual plane (UCS-2). Return Value: unctrl() and wunctrl() return NULL on failure. delay_output() always returns OK. getcchar() returns the number of wide characters wcval points to when wch is NULL; when it's not, getcchar() returns OK or ERR. setcchar() returns OK or ERR. Portability X/Open BSD SYS V unctrl Y Y Y filter Y - 3.0 use_env Y - 4.0 delay_output Y Y Y getcchar Y setcchar Y wunctrl Y PDC_mbtowc - - - PDC_mbstowcs - - - PDC_wcstombs - - - **man-end****************************************************************/ #if __QOR_UNICODE # ifdef PDC_FORCE_UTF8 # include <string.h> # else # include <stdlib.h> # endif #endif //------------------------------------------------------------------------------ char* unctrl( chtype c ) { __QCS_FCONTEXT( "unctrl" ); static char strbuf[3] = {0, 0, 0}; chtype ic; ic = c & A_CHARTEXT; if (ic >= 0x20 && ic != 0x7f) /* normal characters */ { strbuf[0] = (char)ic; strbuf[1] = '\0'; return strbuf; } strbuf[0] = '^'; /* '^' prefix */ if (ic == 0x7f) /* 0x7f == DEL */ strbuf[1] = '?'; else /* other control */ strbuf[1] = (char)(ic + '@'); return strbuf; } //------------------------------------------------------------------------------ void filter(void) { __QCS_FCONTEXT( "filter" ); } //------------------------------------------------------------------------------ void use_env(bool x) { __QCS_FCONTEXT( "use_env" ); } //------------------------------------------------------------------------------ int delay_output(int ms) { __QCS_FCONTEXT( "delay_output" ); return napms( ms ); } #if __QOR_UNICODE //------------------------------------------------------------------------------ int getcchar( const cchar_t* wcval, wchar_t* wch, attr_t* attrs, short* color_pair, void* opts ) { __QCS_FCONTEXT( "getchar" ); if (!wcval) return ERR; if (wch) { if (!attrs || !color_pair) return ERR; *wch = (*wcval & A_CHARTEXT); *attrs = (*wcval & (A_ATTRIBUTES & ~A_COLOR)); *color_pair = PAIR_NUMBER(*wcval & A_COLOR); if (*wch) *++wch = L'\0'; return 0; } else return ((*wcval & A_CHARTEXT) != L'\0'); } //------------------------------------------------------------------------------ int setcchar( cchar_t* wcval, const wchar_t* wch, const attr_t attrs, short color_pair, const void* opts ) { __QCS_FCONTEXT( "setcchar" ); if (!wcval || !wch) return ERR; *wcval = *wch | attrs | COLOR_PAIR(color_pair); return 0; } //------------------------------------------------------------------------------ wchar_t* wunctrl( cchar_t* wc ) { __QCS_FCONTEXT( "wunctrl" ); static wchar_t strbuf[3] = {0, 0, 0}; cchar_t ic; PDC_LOG(("wunctrl() - called\n")); ic = *wc & A_CHARTEXT; if (ic >= 0x20 && ic != 0x7f) /* normal characters */ { strbuf[0] = (wchar_t)ic; strbuf[1] = L'\0'; return strbuf; } strbuf[0] = '^'; /* '^' prefix */ if (ic == 0x7f) /* 0x7f == DEL */ strbuf[1] = '?'; else /* other control */ strbuf[1] = (wchar_t)(ic + '@'); return strbuf; } //------------------------------------------------------------------------------ int PDC_mbtowc(wchar_t *pwc, const char *s, size_t n) { __QCS_FCONTEXT( "PDC_mbtowc" ); # ifdef PDC_FORCE_UTF8 wchar_t key; int i = -1; const unsigned char *string; if (!s || (n < 1)) return -1; if (!*s) return 0; string = (const unsigned char *)s; key = string[0]; /* Simplistic UTF-8 decoder -- only does the BMP, minimal validation */ if (key & 0x80) { if ((key & 0xe0) == 0xc0) { if (1 < n) { key = ((key & 0x1f) << 6) | (string[1] & 0x3f); i = 2; } } else if ((key & 0xe0) == 0xe0) { if (2 < n) { key = ((key & 0x0f) << 12) | ((string[1] & 0x3f) << 6) | (string[2] & 0x3f); i = 3; } } } else i = 1; if (i) *pwc = key; return i; # else return mbtowc(pwc, s, n); # endif } //------------------------------------------------------------------------------ size_t PDC_mbstowcs(wchar_t *dest, const char *src, size_t n) { __QCS_FCONTEXT( "PDC_mbstowcs" ); # ifdef PDC_FORCE_UTF8 size_t i = 0, len; if (!src || !dest) return 0; len = strlen(src); while (*src && i < n) { int retval = PDC_mbtowc(dest + i, src, len); if (retval < 1) return -1; src += retval; len -= retval; i++; } # else size_t i = mbstowcs(dest, src, n); # endif dest[i] = 0; return i; } //------------------------------------------------------------------------------ size_t PDC_wcstombs(char *dest, const wchar_t *src, size_t n) { __QCS_FCONTEXT( "PDC_wcstombs" ); # ifdef PDC_FORCE_UTF8 size_t i = 0; if (!src || !dest) return 0; while (*src && i < n) { chtype code = *src++; if (code < 0x80) { dest[i] = code; i++; } else if (code < 0x800) { dest[i] = ((code & 0x07c0) >> 6) | 0xc0; dest[i + 1] = (code & 0x003f) | 0x80; i += 2; } else { dest[i] = ((code & 0xf000) >> 12) | 0xe0; dest[i + 1] = ((code & 0x0fc0) >> 6) | 0x80; dest[i + 2] = (code & 0x003f) | 0x80; i += 3; } } # else size_t i = wcstombs(dest, src, n); # endif dest[i] = '\0'; return i; } #endif
26.487805
106
0.436119
mfaithfull
553c6630e13e876b18e0421953c8a53c297bc302
3,945
hpp
C++
threadsafe/queue/spsc_queue.hpp
AVasK/core
e8f73f2b92be1ac0a98bda2824682181c5575748
[ "MIT" ]
null
null
null
threadsafe/queue/spsc_queue.hpp
AVasK/core
e8f73f2b92be1ac0a98bda2824682181c5575748
[ "MIT" ]
null
null
null
threadsafe/queue/spsc_queue.hpp
AVasK/core
e8f73f2b92be1ac0a98bda2824682181c5575748
[ "MIT" ]
null
null
null
#pragma once #include <atomic> #include "../../cpu.hpp" // cacheline_size #include "../../range.hpp" #include "../auxiliary/tagged.hpp" // TaggedData #include "io_descriptors.hpp" // core::{queue_reader, queue_writer} #include <vector> template <typename T, typename size_type=unsigned> class spsc_queue { friend core::queue_reader<spsc_queue>; friend core::queue_writer<spsc_queue>; struct too_many_readers : std::exception {}; struct too_many_writers : std::exception {}; public: using value_type = T; static constexpr core::u8 max_writers = 1; static constexpr core::u8 max_readers = 1; spsc_queue(size_t size=2048) : ring(size), _size(size) { for (auto& elem : ring) { elem.tag.store(false); } } core::queue_reader<spsc_queue> reader() { if (n_readers < 1) return {*this}; else throw too_many_readers{}; } core::queue_writer<spsc_queue> writer() { if (n_writers < 1) return {*this}; else throw too_many_writers{}; } bool try_pop(T & data) { auto index = read_from + 1; auto& slot = ring[index % _size]; auto filled = slot.tag.load(std::memory_order_acquire); if ( filled ) { data = std::move(slot.data); slot.tag.store(false, std::memory_order_release); read_from = index; return true; } return false; } bool try_push(T const& data) { auto index = write_to + 1; auto& slot = ring[index % _size]; auto filled = slot.tag.load(std::memory_order_acquire); if ( !filled ) { slot.data = data; slot.tag.store(true, std::memory_order_release); write_to = index; return true; } return false; } bool try_push(T && data) { auto index = write_to + 1; auto& slot = ring[index % _size]; auto filled = slot.tag.load(std::memory_order_acquire); if ( !filled ) { slot.data = std::move(data); slot.tag.store(true, std::memory_order_release); write_to = index; return true; } return false; } void push(T const& data) { constexpr size_t n_spinwaits = 1;//100000; // std::cerr << "push...\n"; for (;;) { // std::cerr << "."; for (size_t _ : core::range(n_spinwaits)) { if (try_push(data)) return; } std::this_thread::yield(); } } void close() { active.store(false, std::memory_order_release); } bool closed() const { return !active.load(std::memory_order_acquire); } bool empty() const { return write_to == read_from; } explicit operator bool () const { return !(closed() && empty()); } void print_state() const { std::cerr << "Q: [" << read_from/*.load()*/ << " -> " << write_to/*.load()*/ << "] | active: " << std::boolalpha << active.load() << "\n"; std::cerr << "[ " << bool(*this) << " ]\n"; } void debug_ring() const { for (auto i : core::range(ring.size()) ) { auto& elem = ring[i]; char sym; auto filled = elem.tag.load(); if ( filled ) sym = '#'; else sym = ' '; if ( filled ) { std::cout << "[" << sym << "| " << elem.data << "]" << " @ " << i << "/" << ring.size() << "\n"; } } } private: std::vector< core::TaggedData<T, std::atomic<bool>> > ring; const size_type _size; alignas(core::device::CPU::cacheline_size) std::atomic<bool> active {true}; alignas(core::device::CPU::cacheline_size) size_type read_from {0}; unsigned n_readers {0}; alignas(core::device::CPU::cacheline_size) size_type write_to {0}; unsigned n_writers {0}; };
26.836735
146
0.532573
AVasK
553fa9919d6f85475b1ce52b5cd98398731f4ede
29,505
cpp
C++
libs/odbc/binder.cpp
hajokirchhoff/litwindow
7f574d4e80ee8339ac11c35f075857c20391c223
[ "MIT", "BSD-3-Clause" ]
null
null
null
libs/odbc/binder.cpp
hajokirchhoff/litwindow
7f574d4e80ee8339ac11c35f075857c20391c223
[ "MIT", "BSD-3-Clause" ]
1
2017-01-07T09:44:20.000Z
2017-01-07T09:44:20.000Z
libs/odbc/binder.cpp
hajokirchhoff/litwindow
7f574d4e80ee8339ac11c35f075857c20391c223
[ "MIT", "BSD-3-Clause" ]
null
null
null
/* * Copyright 2005-2006, Hajo Kirchhoff - Lit Window Productions, http://www.litwindow.com * This file is part of the Lit Window ODBC Library. All use of this material - copying * in full or part, including in other works, using in non-profit or for-profit work * and other uses - is governed by the licence contained in the Lit Window ODBC Library * distribution, file LICENCE.TXT * $Id: binder.cpp,v 1.10 2007/10/18 11:13:17 Hajo Kirchhoff Exp $ */ #include "stdafx.h" #include <sqlext.h> #include <litwindow/dataadapter.h> #include <litwindow/logging.h> #include <boost/bind.hpp> #include <boost/spirit/include/classic.hpp> #include <boost/spirit/include/classic_actor.hpp> #include <set> #include <iomanip> #include "litwindow/odbc/statement.h" #include <boost/uuid/uuid.hpp> #define new DEBUG_NEW using boost::uuids::uuid; template <> litwindow::tstring litwindow::converter<TIME_STRUCT>::to_string(const TIME_STRUCT &v) { basic_stringstream<TCHAR> out; if (v.hour<=23 && v.minute<=59 && v.second<=59) { const TCHAR *fmt=_T("%X"); struct tm t; memset(&t, 0, sizeof(t)); t.tm_hour=v.hour; t.tm_min=v.minute; t.tm_sec=v.second; use_facet<time_put<TCHAR> >(locale()).put(out.rdbuf(), out, _T(' '), &t, fmt, fmt+sizeof(fmt)/sizeof(*fmt)); } else { out << _T("time_invalid"); } return out.str(); } namespace { using namespace boost::spirit::classic; template <typename NumberValue> bool parse_time(const litwindow::tstring &newValue, NumberValue &hours, NumberValue &minutes, NumberValue &seconds) { hours=0; minutes=0; seconds=0; return parse( newValue.begin(), newValue.end(), limit_d(0u, 23u)[uint_parser<NumberValue, 10, 1, 2>()[assign_a(hours)]] >> !( limit_d(0u, 59u)[uint_parser<NumberValue, 10, 2, 2>()[assign_a(minutes)]] >> !limit_d(0u,59u)[uint_parser<NumberValue, 10, 2, 2>()[assign_a(seconds)]] ) >> !(as_lower_d[str_p(_T("am")) | str_p(_T("pm"))]) , space_p | chset_p(_T(":.-")) ).full; } }; template <> size_t litwindow::converter<TIME_STRUCT>::from_string(const litwindow::tstring &newValue, TIME_STRUCT &v) { ios_base::iostate st = 0; struct tm t; memset(&t, 0, sizeof(t)); { basic_istringstream<TCHAR> in(newValue); use_facet<time_get<TCHAR > >(locale()).get_time(in.rdbuf(), basic_istream<TCHAR>::_Iter(0), in, st, &t); } if (st & ios_base::failbit) { size_t hours=0, minutes=0, seconds=0; if (parse_time(newValue, hours, minutes, seconds)==false) { v.hour=v.minute=v.second=0; throw lwbase_error("invalid time format"); } else { v.hour=SQLUSMALLINT(hours); v.minute=SQLUSMALLINT(minutes); v.second=SQLUSMALLINT(seconds); } } else { v.hour=t.tm_hour; v.minute=t.tm_min; v.second=t.tm_sec; } return sizeof(TIME_STRUCT); } LWL_IMPLEMENT_ACCESSOR(TIME_STRUCT) namespace litwindow { namespace odbc {; #ifndef SQL_TVARCHAR #ifdef UNICODE #define SQL_TVARCHAR SQL_WVARCHAR #else #define SQL_TVARCHAR SQL_VARCHAR #endif #endif //#region binder public interface sqlreturn binder::bind_parameter(SQLUSMALLINT position, SQLSMALLINT in_out, SQLSMALLINT c_type, SQLSMALLINT sql_type, SQLULEN column_size, SQLSMALLINT decimal_digits, SQLPOINTER buffer, SQLLEN length, SQLLEN *len_ind) { bind_task bi; data_type_info &info=bi.m_bind_info; info.m_c_type=c_type; info.m_column_size=column_size; info.m_decimal=decimal_digits; info.m_len_ind_p=len_ind; info.m_position=position; info.m_sql_type=sql_type; info.m_target_ptr=buffer; info.m_target_size=length; info.m_type=0; bi.m_by_position=position; bi.m_in_out=in_out; m_parameters.add(bi); return sqlreturn(SQL_SUCCESS); } sqlreturn binder::bind_parameter(const bind_task &task) { m_parameters.add(task); return sqlreturn(SQL_SUCCESS); } sqlreturn binder::bind_parameter(SQLUSMALLINT pposition, const accessor &a, SQLSMALLINT in_out, SQLLEN *len_ind) { bind_task bi; sqlreturn rc=get_bind_info(a, bi.m_bind_info); if (rc.ok()) { bi.m_bind_info.m_len_ind_p=len_ind; bi.m_by_position=pposition; bi.m_in_out=in_out; m_parameters.add(bi); } return rc; } sqlreturn binder::bind_parameter(const tstring &name, const accessor &a, SQLLEN *len_ind) { bind_task bi; sqlreturn rc=get_bind_info(a, bi.m_bind_info); if (rc.ok()) { bi.m_bind_info.m_len_ind_p=len_ind; bi.m_by_name=name; bi.m_in_out=unknown_bind_type; m_parameters.add(bi); } return rc; } sqlreturn binder::bind_parameter(const aggregate &a, solve_nested_names_enum solver) { return bind_aggregate(a, tstring(), solver, false); } sqlreturn binder::bind_column(SQLSMALLINT col, SQLSMALLINT c_type, SQLPOINTER target_ptr, SQLINTEGER size, SQLLEN* len_ind) { bind_task bi; bi.m_bind_info.m_c_type=c_type; bi.m_bind_info.m_target_ptr=target_ptr; bi.m_bind_info.m_target_size=size; bi.m_bind_info.m_position=col; bi.m_bind_info.m_len_ind_p=len_ind; bi.m_by_position=col; m_columns.add(bi); return sqlreturn(SQL_SUCCESS); } sqlreturn binder::bind_column(SQLSMALLINT col, const accessor &a, SQLLEN *len_ind) { bind_task bi; sqlreturn rc=get_bind_info(a, bi.m_bind_info); if (rc.ok()) { bi.m_by_position=col; if (len_ind) bi.m_bind_info.m_len_ind_p=len_ind; m_columns.add(bi); } return rc; } sqlreturn binder::bind_column(const tstring &column_name, const accessor &a, SQLLEN *len_ind) { bind_task bi; sqlreturn rc=get_bind_info(a, bi.m_bind_info); if (rc.ok()) { bi.m_by_name=column_name; if (len_ind) bi.m_bind_info.m_len_ind_p=len_ind; m_columns.add(bi); } return rc; } sqlreturn binder::bind_column(const aggregate &a, const tstring &table, solve_nested_names_enum solver) { return bind_aggregate(a, table, solver, true); } //#endregion sqlreturn binder::build_insert_statement_and_bind(tstring &sql, const tstring &table_name, statement *bind_to) const { tstring bind_parameters; size_t i; sqlreturn rc; if (m_columns.size()>0) { size_t last_element=m_columns.size()-1; SQLUSMALLINT parameter_index=0; for (i=0; i<=last_element && rc; ++i) { const bind_task &b(m_columns.get_bind_task(i)); if (b.m_bind_info.m_len_ind_p==0 || (*b.m_bind_info.m_len_ind_p!=SQL_IGNORE && *b.m_bind_info.m_len_ind_p!=SQL_DEFAULT)) { // bind values only if they are neither SQL_IGNORE or SQL_DEFAULT if (sql.length()==0) sql=_T("INSERT INTO ")+table_name+_T(" ("); else sql+=_T(", "); sql+= b.m_by_name; bind_parameters+= bind_parameters.length()>0 ? _T(", ?") : _T(") VALUES (?"); if (bind_to) { if (b.m_bind_info.m_accessor.is_valid()) rc=bind_to->bind_parameter_accessor(++parameter_index, SQL_PARAM_INPUT, b.m_bind_info.m_accessor, b.m_bind_info.m_len_ind_p); else rc=bind_to->bind_parameter(++parameter_index, SQL_PARAM_INPUT, b.m_bind_info.m_c_type, b.m_bind_info.m_sql_type, b.m_bind_info.m_column_size, b.m_bind_info.m_decimal, b.m_bind_info.m_target_ptr, b.m_bind_info.m_target_size, b.m_bind_info.m_len_ind_p); } } } } if (sql.length()==0) { return sqlreturn (_T("Table has no columns or all columns are being SQL_IGNORE-d. Cannot build insert statement."), err_logic_error); } sql+=bind_parameters + _T(")"); if (rc && bind_to) bind_to->set_statement(sql); return rc; } tstring binder::make_column_name(const tstring &c_identifier) { if (c_identifier.substr(0, 2)==_T("m_")) return c_identifier.substr(2); return c_identifier; } sqlreturn binder::bind_aggregate(const aggregate &a, size_t level, const tstring &prefix, solve_nested_names_enum solver, bool bind_to_columns) { sqlreturn rc; aggregate::iterator i; for (i=a.begin(); i!=a.end() && rc.ok(); ++i) { tstring column_name(make_column_name(s2tstring(i->get_name()))); tstring full_column_name; if ((solver & use_nested_levels)!=0 && prefix.length()>0) full_column_name=prefix+m_aggregate_scope_separator_char+column_name; else full_column_name=column_name; // attempt to bind the member as it is (completely) to a column. if (bind_to_columns) rc=bind_column(full_column_name, *i); else rc=bind_parameter(full_column_name, *i); if (rc.ok()==false) { // member could not be bound directly. See if it is an aggregate itself and bind its individual members if it is. if (i->is_aggregate()) { tstring new_prefix; if (i->is_inherited() && (solver&inheritance_as_nested)==0) new_prefix=prefix; else new_prefix=full_column_name; rc=bind_aggregate(i->get_aggregate(), level+1, new_prefix, solver, bind_to_columns); } } } return rc; } /// bind an aggregate adapter to the result columns sqlreturn binder::bind_aggregate(const aggregate &a, const tstring &prefix, solve_nested_names_enum solver, bool bind_to_columns) { tstring use_name; if (is_null(prefix)) use_name=s2tstring(a.get_class_name()); else use_name=prefix; return bind_aggregate(a, 0, use_name, solver, bind_to_columns); } sqlreturn binder::get_bind_info(const accessor &a, data_type_info &p_desc) { sqlreturn rc=data_type_lookup().get(a.get_type(), p_desc); if (rc.ok()) { p_desc.m_accessor=a; p_desc.m_target_ptr=a.get_member_ptr(); if (p_desc.m_target_size==0) p_desc.m_target_size=(SQLINTEGER)a.get_sizeof(); } return rc; } sqlreturn binder::do_bind_parameter(bind_task &b, statement &s) const { const parameter *p=s.get_parameter(b.m_by_position); if (p) { if (b.m_in_out==unknown_bind_type) { b.m_in_out=p->m_bind_type; } else if (b.m_in_out!=p->m_bind_type) { return sqlreturn(_("bind type used in the statement is different from bind parameter used in the C++ source")+b.m_by_name, odbc::err_logic_error); } } // else no parameter marker in statement sqlreturn rc=s.do_bind_parameter(b.m_by_position, b.m_in_out, b.m_bind_info.m_c_type, b.m_bind_info.m_sql_type, b.m_bind_info.m_column_size, b.m_bind_info.m_decimal, b.m_bind_info.m_target_ptr, b.m_bind_info.m_target_size, b.m_bind_info.m_len_ind_p); return rc; } sqlreturn binder::do_bind_column(bind_task &b, statement &s) const { sqlreturn rc=s.do_bind_column(b.m_by_position, b.m_bind_info.m_c_type, b.m_bind_info.m_target_ptr, b.m_bind_info.m_target_size, b.m_bind_info.m_len_ind_p); return rc; } /** bind all parameters in the 'to bind' list to the statement. */ sqlreturn binder::do_bind_parameters(statement &s) { return m_parameters.prepare_binding(s, false); } sqlreturn binder::do_bind_columns(statement &s) { return m_columns.prepare_binding(s, true, s.get_column_count()); } sqlreturn binder::binder_lists::reset_bind_task_state(size_t pos, SQLINTEGER len_ind) { bind_task &b(m_elements[pos]); if (len_ind==statement::use_defaults) { if (b.m_bind_info.m_helper) // use the bind helper { *b.m_bind_info.m_len_ind_p= b.m_bind_info.m_helper->get_length(b.m_bind_info); } else if (b.m_bind_info.m_accessor.is_c_vector() && // use SQL_NTS if it is a char or wchar_t vector (old style C string) ((is_type<wchar_t>(b.m_bind_info.m_type) && b.m_bind_info.m_accessor.get_sizeof()>sizeof(wchar_t)) || (is_type<char>(b.m_bind_info.m_type) && b.m_bind_info.m_accessor.get_sizeof()>sizeof(char))) ) { *b.m_bind_info.m_len_ind_p=SQL_NTS; } else // use target_size as default size { *b.m_bind_info.m_len_ind_p=b.m_bind_info.m_target_size; } } else *b.m_bind_info.m_len_ind_p=len_ind; return sqlreturn(SQL_SUCCESS); } sqlreturn binder::binder_lists::reset_states(SQLINTEGER len_ind) { size_t i; for (i=0; i<m_elements.size(); ++i) { reset_bind_task_state(i, len_ind); } return sqlreturn(SQL_SUCCESS); } sqlreturn binder::binder_lists::set_column_state(SQLUSMALLINT col, SQLLEN len_ind) { if (col>=m_index.size()) return sqlreturn(_("no such column."), odbc::err_no_such_column); *m_index[col]->m_bind_info.m_len_ind_p=len_ind; return sqlreturn(SQL_SUCCESS); } sqlreturn binder::binder_lists::put() { sqlreturn rc; size_t i; for (i=0; i<m_elements.size() && rc; ++i) { bind_task &b(m_elements[i]); if (b.m_bind_info.m_helper) { rc=b.m_bind_info.m_helper->put_data(b.m_bind_info); } } return rc; } struct reset_intermediate_buffer_pointers { reset_intermediate_buffer_pointers(const unsigned char *buffer, SQLULEN size) { begin_ptr=buffer; if (buffer) end_ptr=buffer+size; else end_ptr=0; } const unsigned char *begin_ptr, *end_ptr; void operator()(SQLPOINTER &p) const { if ((const unsigned char*)p>=begin_ptr && (const unsigned char*)p<end_ptr) p=0; } void operator()(SQLINTEGER * &p) const { if ((const unsigned char*)p>=begin_ptr && (const unsigned char*)p<end_ptr) p=0; } #ifdef _WIN64 void operator()(SQLLEN * &p) const { if ((const unsigned char*)p>=begin_ptr && (const unsigned char*)p<end_ptr) p=0; } #endif }; sqlreturn binder::binder_lists::prepare_binding(statement &s, bool bind_as_columns, size_t columns_to_expect) { if (columns_to_expect) m_index.resize(columns_to_expect+1, 0); sqlreturn rc; m_needs_bind=false; fill(m_index.begin(), m_index.end(), static_cast<bind_task*>(0)); // the 'intermediate' buffer will be reset in this method // some pointers (cache, len_ind_p) might point into the intermediate buffer // to find and reset them, store beginning and end of the intermediate buffer reset_intermediate_buffer_pointers reset_ptrs((const unsigned char*)m_intermediate_buffer.get(), m_intermediate_buffer_size); m_intermediate_buffer_size=0; size_t i; for (i=0; i<m_elements.size(); ++i) { bind_task &b(m_elements[i]); if (m_intermediate_buffer.get()) { // reset pointers if they point into an existing intermediate buffer reset_ptrs(b.m_bind_info.m_len_ind_p); reset_ptrs(b.m_bind_info.m_target_ptr); reset_ptrs(b.m_cache); reset_ptrs(b.m_cache_len_ind_p); } if (b.m_by_position==-1) { SQLSMALLINT p; if (bind_as_columns) { p=s.find_column(b.m_by_name); } else { p=s.find_parameter(b.m_by_name); if (p!=-1) { const parameter *para=s.get_parameter(p); if (b.m_in_out==unknown_bind_type) { b.m_in_out=para->m_bind_type; } else if (b.m_in_out!=para->m_bind_type) { return sqlreturn(_("bind type used in the statement is different from bind parameter used in the C++ source")+b.m_by_name, odbc::err_logic_error); } } } if (p==-1) { return sqlreturn(tstring(_("no such "))+(bind_as_columns ? _("column ") : _("parameter "))+b.m_by_name, bind_as_columns ? err_no_such_column : err_no_such_parameter); } b.m_by_position=p; } else { tstringstream str; str << _("#:") << b.m_by_position; b.m_by_name=str.str(); } if (b.m_by_position>=(SQLSMALLINT)m_index.size()) m_index.resize(b.m_by_position+1, 0); m_index[b.m_by_position]=&m_elements[i]; b.m_bind_info.m_position=b.m_by_position; if (b.m_bind_info.m_helper) { // this is an extended binder, prepare the intermediate buffer if neccessary m_intermediate_buffer_size+=b.m_bind_info.m_helper->prepare_bind_buffer(b.m_bind_info, s, bind_as_columns ? bindto : bind_type(b.m_in_out)); } if (bind_as_columns==false && (b.m_bind_info.m_column_size==0 || b.m_bind_info.m_column_size==SQL_NTS) && b.m_bind_info.m_accessor.is_valid()) { // no column size specified. Try to calculate it. if (is_type<char>(b.m_bind_info.m_accessor)) b.m_bind_info.m_column_size=SQLUINTEGER(b.m_bind_info.m_accessor.get_sizeof()/sizeof(char)-1); else if (is_type<wchar_t>(b.m_bind_info.m_accessor)) b.m_bind_info.m_column_size=SQLUINTEGER(b.m_bind_info.m_accessor.get_sizeof()/sizeof(wchar_t)-1); } if (b.m_bind_info.m_len_ind_p==0) { m_intermediate_buffer_size+=sizeof(SQLLEN); } if (has_cache() && b.m_bind_info.m_target_size) { m_intermediate_buffer_size+=b.m_bind_info.m_target_size+sizeof(SQLLEN); } } m_intermediate_buffer.reset(m_intermediate_buffer_size>0 ? new unsigned char[m_intermediate_buffer_size] : 0); unsigned char *buffer=m_intermediate_buffer.get(); m_needs_get=m_needs_put=false; SQLULEN size_left=m_intermediate_buffer_size; for (i=0; i<m_elements.size() && rc.ok(); ++i) { bind_task &b(m_elements[i]); if (b.m_bind_info.m_helper && b.m_bind_info.m_target_ptr==0 && b.m_bind_info.m_target_size>0) { if (b.m_bind_info.m_target_size>size_left) { return sqlreturn(_("extended bind helper requesting more buffer space than is available"), odbc::err_logic_error); } b.m_bind_info.m_target_ptr=buffer; buffer+=b.m_bind_info.m_target_size; size_left-=b.m_bind_info.m_target_size; if (bind_as_columns) m_needs_put=m_needs_get=true; else { m_needs_put= b.m_in_out==SQL_PARAM_INPUT || b.m_in_out==SQL_PARAM_INPUT_OUTPUT; m_needs_get= b.m_in_out==SQL_PARAM_INPUT_OUTPUT || b.m_in_out==SQL_PARAM_OUTPUT; } } if (b.m_bind_info.m_len_ind_p==0) { b.m_bind_info.m_len_ind_p=(SQLLEN*)buffer; reset_bind_task_state(i, statement::use_defaults); //*b.m_bind_info.m_len_ind_p=b.m_bind_info.m_target_size; buffer+=sizeof(SQLLEN); size_left-=sizeof(SQLLEN); } if (has_cache() && b.m_bind_info.m_target_size) { b.m_cache=(SQLPOINTER)buffer; buffer+=b.m_bind_info.m_target_size; b.m_cache_len_ind_p=(SQLLEN*)buffer; buffer+=sizeof(SQLLEN); m_needs_get=true; size_left-=sizeof(SQLLEN)+b.m_bind_info.m_target_size; } else { b.m_cache=0; b.m_cache_len_ind_p=0; } if (b.m_bind_info.m_target_size>0 && b.m_bind_info.m_target_ptr!=0) { if (bind_as_columns) { rc=s.do_bind_column(b.m_by_position, b.m_bind_info.m_c_type, b.m_bind_info.m_target_ptr, b.m_bind_info.m_target_size, b.m_bind_info.m_len_ind_p); } else { if (b.m_bind_info.m_column_size==0) m_needs_bind=true; // dynamic column size needs rebinding every time rc=s.do_bind_parameter(b.m_by_position, b.m_in_out, b.m_bind_info.m_c_type, b.m_bind_info.m_sql_type, b.m_bind_info.m_column_size, b.m_bind_info.m_decimal, b.m_bind_info.m_target_ptr, b.m_bind_info.m_target_size, b.m_bind_info.m_len_ind_p); } } } return rc; } void binder::binder_lists::fix_SQL_NTS_len_ind_parameter_workaround(fix_workaround_enum action) { size_t pos; for (pos=0; pos<m_elements.size(); ++pos) { bind_task &b(m_elements[pos]); if (action==set_length) { b.m_bind_info.m_reset_len_ind_to_SQL_NTS_after_execute=false; if (b.m_in_out!=out && b.m_bind_info.m_len_ind_p && *b.m_bind_info.m_len_ind_p==SQL_NTS) { if (b.m_bind_info.m_c_type==SQL_C_CHAR) *b.m_bind_info.m_len_ind_p=(SQLINTEGER)strlen((const char*)b.m_bind_info.m_target_ptr) * sizeof(char); else if (b.m_bind_info.m_c_type==SQL_C_WCHAR) *b.m_bind_info.m_len_ind_p=(SQLINTEGER)wcslen((const wchar_t*)b.m_bind_info.m_target_ptr) * sizeof(wchar_t); b.m_bind_info.m_reset_len_ind_to_SQL_NTS_after_execute=true; } } else if (action==reset_length && b.m_bind_info.m_reset_len_ind_to_SQL_NTS_after_execute && b.m_in_out==in) { *b.m_bind_info.m_len_ind_p=SQL_NTS; } } } void binder::fix_SQL_NTS_len_ind_parameter_workaround(fix_workaround_enum action) { m_parameters.fix_SQL_NTS_len_ind_parameter_workaround(action); } SQLSMALLINT binder::find_column_or_parameter_by_target(const binder_lists &list, const const_accessor &a) const { size_t i; for (i=0; i<list.size() && a.is_alias_of(list.get_bind_task(i).m_bind_info.m_accessor)==false; ++i) ; return i<list.size() ? list.get_bind_task(i).m_by_position : -1; } SQLSMALLINT binder::find_column_by_target(const const_accessor &a) const { return find_column_or_parameter_by_target(m_columns, a); } sqlreturn binder::do_put_parameters(statement &s) { return m_parameters.put(); } sqlreturn binder::do_get_parameters(statement &s) { return sqlreturn(SQL_ERROR); } sqlreturn binder::binder_lists::do_get_columns_or_parameters(statement &s, bool type_is_columns) { if (type_is_columns==false) DebugBreak(); //TODO: get_parameters not implemented yet!!! size_t i; sqlreturn rc; for (i=0; i<m_elements.size() && rc.ok(); ++i) { bind_task &b(m_elements[i]); if (b.m_bind_info.m_helper) { rc=b.m_bind_info.m_helper->get_data(b.m_bind_info, s); } if (b.m_cache) { memcpy(b.m_cache, b.m_bind_info.m_target_ptr, b.m_bind_info.m_target_size); *b.m_cache_len_ind_p=*b.m_bind_info.m_len_ind_p; } } return rc; } sqlreturn binder::do_get_columns(statement &s) { return m_columns.do_get_columns_or_parameters(s, true); } data_type_info no_column; tstring binder::dump_columns(TCHAR quote_char) const { size_t i; tstring rc; for (i=0; i<m_columns.size(); ++i) { if (rc.length()>0) rc.append(_T(", ")); if (quote_char) rc.append(1, quote_char); rc.append(m_columns.get_bind_task(i).m_by_name); if (quote_char) rc.append(1, quote_char); } return rc; } const data_type_info &binder::get_column(SQLSMALLINT pos) const { return m_columns.is_valid_column_index(pos) ? m_columns.get_bind_task_for_column(pos)->m_bind_info : no_column; } sqlreturn binder::get_column_length(SQLSMALLINT pos, SQLLEN &value) const { const data_type_info i=get_column(pos); if (&i==&no_column) return sqlreturn(_("no such column"), odbc::err_no_such_column); else if (i.m_len_ind_p==0) return sqlreturn(_("column not bound"), odbc::err_column_not_bound); value=*i.m_len_ind_p; return sqlreturn(SQL_SUCCESS); } //-----------------------------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------------------// // look up types typedef vector<data_type_info> data_type_info_register; data_type_info_register &get_data_type_info_register() { static data_type_info_register s_map; return s_map; } data_type_info_register::const_iterator find_data_type_info(prop_t type) { data_type_info_register::const_iterator rc=find(get_data_type_info_register().begin(), get_data_type_info_register().end(), type); return rc; } void data_type_lookup::add(const data_type_info &i, const data_type_registrar *) { #ifdef REGISTER_IS_A_SET pair<data_type_info_register::iterator, bool> insertion=get_data_type_info_register().insert(i); if (insertion.second==false) { lw_err() << _("Type cannot be inserted twice! ") << litwindow::s2tstring(i.m_type->get_type_name()) << endl; } #endif get_data_type_info_register().push_back(i); } sqlreturn data_type_lookup::get(prop_t type, data_type_info &i) { data_type_info_register &the_map(get_data_type_info_register()); data_type_info_register::const_iterator data=find_data_type_info(type); if (data==the_map.end()) data=find_if(the_map.begin(), the_map.end(), boost::bind(&data_type_info::can_handle, _1, type)); if (data==the_map.end()) return sqlreturn(_("There is no registered SQL binder for type ")+s2tstring(type->get_type_name()), odbc::err_no_such_type); i=*data; return sqlreturn(SQL_SUCCESS); } data_type_info::data_type_info(prop_t type, SQLSMALLINT c_type, SQLSMALLINT sql_type, size_t col_size, extended_bind_helper *bhelper) { m_sql_type=sql_type; m_c_type=c_type; m_type=type; m_helper=bhelper; m_column_size=(SQLUINTEGER)col_size; } namespace { static register_data_type<long> tlong(SQL_C_SLONG, SQL_INTEGER); static register_data_type<int> tint(SQL_C_SLONG, SQL_INTEGER); static register_data_type<short> tshort(SQL_C_SSHORT, SQL_INTEGER); static register_data_type<unsigned long> tulong(SQL_C_ULONG, SQL_INTEGER); static register_data_type<unsigned int>tuint(SQL_C_ULONG, SQL_INTEGER); static register_data_type<unsigned short> tushort(SQL_C_USHORT, SQL_INTEGER); #define LWODBC_SQL_C_BOOL SQL_C_CHAR static register_data_type<bool> tbool(/*LWODBC_SQL_C_BOOL*/SQL_C_BIT, SQL_CHAR); static register_data_type<char> tchar(SQL_C_CHAR, SQL_VARCHAR, 0); static register_data_type<wchar_t> twchar(SQL_C_WCHAR, SQL_WVARCHAR, 0); static register_data_type<TIMESTAMP_STRUCT> ttimestampstruct(SQL_C_TIMESTAMP, SQL_TIMESTAMP); static register_data_type<float> tfloat(SQL_C_FLOAT, SQL_REAL); static register_data_type<double> tdouble(SQL_C_DOUBLE, SQL_DOUBLE); static register_data_type<double> tdouble2(SQL_C_DOUBLE, SQL_FLOAT); static register_data_type<TIME_STRUCT> ttime_struct(SQL_C_TIME, SQL_TIME); struct tuuid_bind_helper:public extended_bind_helper { // unfortunately for us, uuid stores the uuid bytes in a different order // than used by ODBC (under Windows at least) virtual SQLULEN prepare_bind_buffer(data_type_info &info, statement &s, bind_type bind_howto) const { info.m_target_ptr=0; info.m_target_size=16; return 16; } virtual sqlreturn get_data(data_type_info &info, statement &s) const { typed_accessor<uuid> a=dynamic_cast_accessor<uuid>(info.m_accessor); if (info.m_len_ind_p && (*info.m_len_ind_p==SQL_NULL_DATA || *info.m_len_ind_p==0)) { a.set(uuid()); } else { boost::uint8_t guiddata[16]; boost::uint8_t *p=guiddata; const boost::uint8_t *g=(const boost::uint8_t*)info.m_target_ptr; *p++=g[3]; *p++=g[2]; *p++=g[1]; *p++=g[0]; *p++=g[5]; *p++=g[4]; *p++=g[7]; *p++=g[6]; memcpy(p, g+8, 8); uuid temp; std::copy(guiddata+0, guiddata+16, temp.begin()); a.set(temp); } return sqlreturn(SQL_SUCCESS); } sqlreturn put_data(data_type_info &info) const { if (info.m_len_ind_p==0 || (*info.m_len_ind_p!=SQL_NULL_DATA && *info.m_len_ind_p!=SQL_DEFAULT_PARAM)) { typed_accessor<uuid> a=dynamic_cast_accessor<uuid>(info.m_accessor); if (info.m_target_size<16) return sqlreturn(_("String data right truncation (tstring)"), err_data_right_truncated, _T("22001")); uuid val(a.get()); uuid::iterator src=val.begin(); boost::uint8_t *dst=(boost::uint8_t*)info.m_target_ptr; dst[3]=*src++; dst[2]=*src++; dst[1]=*src++; dst[0]=*src++; dst[5]=*src++; dst[4]=*src++; dst[7]=*src++; dst[6]=*src++; memcpy(dst+8, src, 8); } return sqlreturn(SQL_SUCCESS); } SQLINTEGER get_length(data_type_info &info) const { return 16; } } g_uuid_bind_helper; static register_data_type<uuid> tuuid(SQL_C_GUID, SQL_GUID, 0, &g_uuid_bind_helper); struct tstring_bind_helper:public extended_bind_helper { virtual SQLULEN prepare_bind_buffer(data_type_info &info, statement &s, bind_type bind_howto) const { SQLSMALLINT pos=info.m_position; SQLULEN sz; info.m_target_ptr=0; // tell the binder we need an intermediate buffer sqlreturn rc; if (bind_howto==bindto) { if (info.m_sql_type==SQL_TVARCHAR) sz=maximum_text_column_length_retrieved; else { rc=s.get_column_size(pos, sz); if (sz==0) sz=maximum_text_column_length_retrieved; // use default maximum size } } else { if (info.m_column_size==0) { typed_const_accessor<tstring> ta=dynamic_cast_accessor<tstring>(info.m_accessor); sz=SQLINTEGER(ta.get_ptr() ? ta.get_ptr()->length() : ta.get().length()); } else sz=info.m_column_size; } sz+=1; // trailing \0 character sz*=sizeof(TCHAR); // might be unicode representation info.m_target_size=rc.ok() ? sz : 0; // tell the binder the size of the intermediate buffer return sz; } virtual sqlreturn get_data(data_type_info &info, statement &s) const { sqlreturn rc; typed_accessor<tstring> a=dynamic_cast_accessor<tstring>(info.m_accessor); if (info.m_len_ind_p && (*info.m_len_ind_p==SQL_NULL_DATA || *info.m_len_ind_p==0)) a.set(_T("")); else a.set(tstring((const TCHAR*)info.m_target_ptr)); return sqlreturn(SQL_SUCCESS); } sqlreturn put_data(data_type_info &info) const { bool data_truncated=false; // if (info.m_len_ind_p) // *info.m_len_ind_p=SQL_NTS; if (info.m_len_ind_p==0 || (*info.m_len_ind_p!=SQL_NULL_DATA && *info.m_len_ind_p!=SQL_DEFAULT_PARAM)) { typed_accessor<tstring> a=dynamic_cast_accessor<tstring>(info.m_accessor); tstring *s=a.get_ptr(); size_t required_length; if (s) { required_length=s->length()*sizeof(TCHAR)+sizeof(TCHAR); if (required_length>info.m_target_size) { required_length=info.m_target_size; data_truncated=true; } memcpy(info.m_target_ptr, s->c_str(), required_length); } else { // needs temporary tstring tstring temp; a.get(temp); required_length=temp.length()*sizeof(TCHAR)+sizeof(TCHAR); if (required_length>info.m_target_size) { required_length=info.m_target_size; data_truncated=true; } memcpy(info.m_target_ptr, temp.c_str(), required_length); } } return data_truncated ? sqlreturn(_("String data right truncation (tstring)"), err_data_right_truncated, _T("22001")) : sqlreturn(SQL_SUCCESS); } SQLINTEGER get_length(data_type_info &info) const { return SQL_NTS; } } g_tstring_bind_helper; static register_data_type<tstring> ttstring(SQL_C_TCHAR, SQL_TVARCHAR, 0, &g_tstring_bind_helper); }; }; }; using namespace std; template <> litwindow::tstring litwindow::converter<TIMESTAMP_STRUCT>::to_string(const TIMESTAMP_STRUCT &v) { tstringstream str; str << setfill(_T('0')) << setw(4) << v.year << _T('-') << setw(2) << (unsigned)v.month << _T('-') << setw(2) << (unsigned)v.day << _T(' ') << setw(2) << (unsigned)v.hour << _T(':') << setw(2) << (unsigned)v.minute << _T(':') << setw(2) << (unsigned)v.second << _T('.') << v.fraction; return str.str(); } LWL_IMPLEMENT_ACCESSOR(TIMESTAMP_STRUCT);
35
285
0.716624
hajokirchhoff
55418e97647308bed166a7a209cf7c44021f8800
560
cpp
C++
main/find-triplets-with-zero-sum/find-triplets-with-zero-sum.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
main/find-triplets-with-zero-sum/find-triplets-with-zero-sum.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
main/find-triplets-with-zero-sum/find-triplets-with-zero-sum.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
/*You are required to complete the function below*/ bool findTriplets(int *const a, const int n) { sort(a, a + n); for (auto i = 0; i != n; ++i) { const auto target = -a[i]; for (auto j = 0, k = n - 1; j < k; ) { const auto cur = a[j] + a[k]; if (cur < target) ++j; else if (cur != target) --k; else if (j == i) ++j; else if (k == i) --k; else return true; } } return false; }
25.454545
51
0.376786
EliahKagan
554449e60a821f16c728c8c7d5f120483a2d48bd
3,792
cpp
C++
Example/Example.cpp
davemc0/Particle
04d9bbe19e21b9024c81eb21708425e4a1ebc361
[ "CC0-1.0" ]
1
2022-03-26T01:48:11.000Z
2022-03-26T01:48:11.000Z
Example/Example.cpp
davemc0/Particle
04d9bbe19e21b9024c81eb21708425e4a1ebc361
[ "CC0-1.0" ]
null
null
null
Example/Example.cpp
davemc0/Particle
04d9bbe19e21b9024c81eb21708425e4a1ebc361
[ "CC0-1.0" ]
null
null
null
// Example.cpp - An example of the Particle System API in OpenGL // // Copyright 1999-2006, 2022 by David K. McAllister #include "Particle/pAPI.h" using namespace PAPI; // OpenGL #include "GL/glew.h" // This needs to come after GLEW #include "GL/freeglut.h" // For C++17 execution policy to get parallelism of particle actions #include <execution> ParticleContext_t P; // A water fountain spraying upward void ComputeParticles() { // Set the state of the new particles to be generated pSourceState S; S.Velocity(PDCylinder(pVec(0.0f, -0.01f, 0.25f), pVec(0.0f, -0.01f, 0.27f), 0.021f, 0.019f)); S.Color(PDLine(pVec(0.8f, 0.9f, 1.0f), pVec(1.0f, 1.0f, 1.0f))); // Generate particles along a very small line in the nozzle P.Source(200, PDLine(pVec(0.f, 0.f, 0.f), pVec(0.f, 0.f, 0.4f)), S); P.ParticleLoop(std::execution::par_unseq, [&](Particle_t& p_) { // Gravity P.Gravity(p_, pVec(0.f, 0.f, -0.01f)); // Bounce particles off a disc of radius 5 P.Bounce(p_, 0.f, 0.5f, 0.f, PDDisc(pVec(0.f, 0.f, 0.f), pVec(0.f, 0.f, 1.f), 5.f)); // Kill particles below Z=-3 P.Sink(p_, false, PDPlane(pVec(0.f, 0.f, -3.f), pVec(0.f, 0.f, 1.f))); // Move particles to their new positions P.Move(p_, true, false); }); P.CommitKills(); } // Draw each particle as a point using vertex arrays // To draw as textured point sprites just call glEnable(GL_POINT_SPRITE) before calling this function. void DrawGroupAsPoints() { size_t cnt = P.GetGroupCount(); if (cnt < 1) return; const float* ptr; size_t flstride, pos3Ofs, posB3Ofs, size3Ofs, vel3Ofs, velB3Ofs, color3Ofs, alpha1Ofs, age1Ofs, up3Ofs, rvel3Ofs, upB3Ofs, mass1Ofs, data1Ofs; cnt = P.GetParticlePointer(ptr, flstride, pos3Ofs, posB3Ofs, size3Ofs, vel3Ofs, velB3Ofs, color3Ofs, alpha1Ofs, age1Ofs, up3Ofs, rvel3Ofs, upB3Ofs, mass1Ofs, data1Ofs); if (cnt < 1) return; glEnable(GL_POINT_SMOOTH); glPointSize(4); glEnableClientState(GL_COLOR_ARRAY); glColorPointer(4, GL_FLOAT, int(flstride) * sizeof(float), ptr + color3Ofs); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, int(flstride) * sizeof(float), ptr + pos3Ofs); glDrawArrays(GL_POINTS, 0, (GLsizei)cnt); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); } void Draw() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Set up the view glLoadIdentity(); gluLookAt(0, -12, 3, 0, 0, 0, 0, 0, 1); // Draw the ground glColor3ub(0, 115, 0); glPushMatrix(); glTranslatef(0, 0, -1); glutSolidCylinder(5, 1, 20, 20); glPopMatrix(); // Do what the particles do ComputeParticles(); // Draw the particles DrawGroupAsPoints(); glutSwapBuffers(); } void Reshape(int w, int h) { glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(40, w / double(h), 1, 100); glMatrixMode(GL_MODELVIEW); } int main(int argc, char** argv) { glutInit(&argc, argv); // Make a standard 3D window glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE); glutInitWindowSize(800, 800); glutCreateWindow("Particle Example"); glutDisplayFunc(Draw); glutIdleFunc(Draw); glutReshapeFunc(Reshape); // We want depth buffering, etc. glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); // Make a particle group int particleHandle = P.GenParticleGroups(1, 50000); P.CurrentGroup(particleHandle); P.TimeStep(0.1f); try { glutMainLoop(); } catch (PError_t& Er) { std::cerr << "Particle API exception: " << Er.ErrMsg << std::endl; throw Er; } return 0; }
26.893617
151
0.64847
davemc0
55454bd5de6af9932b41977d05db0d82cd96ccc2
6,908
cpp
C++
libraries/RTIMULib/utility/RTPressureMS5803.cpp
uutzinger/RTIMULib2-Teensy
0901af6b69399b0f107c8bf1012e6361e3029b94
[ "MIT" ]
1
2021-05-16T16:24:27.000Z
2021-05-16T16:24:27.000Z
libraries/RTIMULib/utility/RTPressureMS5803.cpp
uutzinger/RTIMULib2-Teensy
0901af6b69399b0f107c8bf1012e6361e3029b94
[ "MIT" ]
null
null
null
libraries/RTIMULib/utility/RTPressureMS5803.cpp
uutzinger/RTIMULib2-Teensy
0901af6b69399b0f107c8bf1012e6361e3029b94
[ "MIT" ]
7
2016-09-04T23:01:26.000Z
2020-05-08T06:00:46.000Z
//////////////////////////////////////////////////////////////////////////// // // This file is part of RTIMULib // // Copyright (c) 2014-2015, richards-tech // // 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. // UU: This is new driver for RTIMULib #include "RTPressureMS5803.h" RTPressureMS5803::RTPressureMS5803(RTIMUSettings *settings) : RTPressure(settings) { } RTPressureMS5803::~RTPressureMS5803() { } int RTPressureMS5803::pressureGetPollInterval() { // return (400 / 122); // available: 0.54 / 1.06 / 2.08 / 4.13 / 8.22 ms // osr 4096 takes 8.22ms return (3); } bool RTPressureMS5803::reset() // Reset device I2C { unsigned char cmd = MS5611_CMD_RESET; if (!m_settings->HALRead(m_pressureAddr, cmd, 0, 0, "Failed to reset MS5803")) { return false; } else { return true; } } bool RTPressureMS5803::pressureInit() { unsigned char cmd = MS5611_CMD_PROM; unsigned char data[2]; m_pressureAddr = m_settings->m_I2CPressureAddress; // get calibration data // skip first and last entry in PROM table // C0= 0 // C1= 44428 // C2= 40264 // C3= 27988 // C4= 27027 // C5= 32849 // C6= 28630 // C7= 5 for (int i = 0; i <= 7; i++) { if (!m_settings->HALRead(m_pressureAddr, cmd, 2, data, "Failed to read MS5803 calibration data")) return false; m_calData[i] = (((uint16_t)data[0]) << 8) | ((uint16_t)data[1]); //printf("Cal index: %d, data: %d\n", i, m_calData[i]); cmd += 2; } m_state = MS5803_STATE_IDLE; return true; } bool RTPressureMS5803::pressureRead() { uint8_t data[3]; int32_t deltaT; int32_t temperature; int64_t offset; int64_t sens; int64_t T2; int64_t offset2; int64_t sens2; bool validReadings = false; switch (m_state) { case MS5803_STATE_IDLE: // start pressure conversion with maximum precision 4096 if (!m_settings->HALWrite(m_pressureAddr, MS5611_CMD_CONV_D1, 0, 0, "Failed to start MS5803 pressure conversion")) { return false; } else { m_state = MS5803_STATE_PRESSURE; m_timer = RTMath::currentUSecsSinceEpoch(); } break; case MS5803_STATE_PRESSURE: if ((RTMath::currentUSecsSinceEpoch() - m_timer) < 9040) // need to wait 10ms until conversion complete at highest precision return false; // not time yet if (!m_settings->HALRead(m_pressureAddr, MS5611_CMD_ADC, 3, data, "Failed to read MS5803 pressure")) { return false; } m_D1 = ((uint32_t)data[0] << 16) + ((uint32_t)data[1] << 8) + (uint32_t)data[2]; //printf("D1: %ld\n", m_D1); // start temperature conversion if (!m_settings->HALWrite(m_pressureAddr, MS5611_CMD_CONV_D2, 0, 0, "Failed to start MS5803 temperature conversion")) { return false; } else { m_state = MS5803_STATE_TEMPERATURE; m_timer = RTMath::currentUSecsSinceEpoch(); } break; case MS5803_STATE_TEMPERATURE: if ((RTMath::currentUSecsSinceEpoch() - m_timer) < 9040) // takes 10ms until conversion at highest precision return false; // not time yet if (!m_settings->HALRead(m_pressureAddr, MS5611_CMD_ADC, 3, data, "Failed to read MS58031 temperature")) { return false; } m_D2 = ((uint32_t)data[0] << 16) + ((uint32_t)data[1] << 8) + (uint32_t)data[2]; //printf("D2: %ld\n", m_D2); // now calculate temperature deltaT = m_D2 - ((int32_t)m_calData[5] << 8); temperature = (((int64_t)deltaT * m_calData[6]) >> 23) + 2000; //printf("deltaT: %ld\n", deltaT); //printf("temperature: %ld\n", temperature); // do second order temperature compensation if (temperature < 2000) { // low temperature below 20C T2 = 3 * (((int64_t)deltaT * deltaT) >> 33); offset2 = 3 * ((temperature - 2000) * (temperature - 2000)) / 2; sens2 = 5 * ((temperature - 2000) * (temperature - 2000)) / 8; if (temperature < -1500) { // below -15C offset2 = offset2 + 7 * ((temperature + 1500) * (temperature + 1500)); sens2 = sens2 + 4 * ((temperature + 1500) * (temperature + 1500)); } } else { // above 20C T2 = 7 * ((uint64_t)deltaT * deltaT)/pow(2,37); offset2 = (temperature - 2000) * (temperature - 2000) / 16; sens2 = 0; } // Now bring all together and apply offsets offset = ((int64_t)m_calData[2] << 16) + (((m_calData[4] * (int64_t)deltaT)) >> 7); sens = ((int64_t)m_calData[1] << 15) + (((m_calData[3] * (int64_t)deltaT)) >> 8); //printf("T2: %lld\n", T2); //printf("offset2: %lld\n", offset2); //printf("sens2: %lld\n", sens2); temperature = temperature - T2; offset = offset - offset2; sens = sens - sens2; //printf("temperature calib: %lld\n", temperature); //printf("offset calib: %lld\n", offset); //printf("sens calib: %lld\n", sens); // now lets calculate temperature compensated pressure m_pressureData.pressure = (RTFLOAT)(((m_D1 * sens)/ 2097152 - offset) / 32768) / 10.0; m_pressureData.temperature = (RTFLOAT)temperature/100.0; m_pressureData.temperatureValid = true; m_pressureData.pressureValid = true; m_pressureData.timestamp = RTMath::currentUSecsSinceEpoch(); //printf("Temp: %f, pressure: %f\n", m_pressureData.temperature, m_pressureData.pressure); validReadings = true; m_state = MS5803_STATE_IDLE; break; } if (validReadings) { return true; } else { return false; } }
34.713568
132
0.604661
uutzinger
5545628e382e2f84e9ad33d63a872f72b56334fc
1,281
hpp
C++
include/cql/cql_uuid.hpp
ncbi/cassandra-cpp-driver
b2259e9b13849c98fc6b6485f2433c97c1fa4b9f
[ "Apache-2.0" ]
3
2016-02-24T09:22:16.000Z
2021-04-06T03:04:21.000Z
include/cql/cql_uuid.hpp
ncbi/cassandra-cpp-driver
b2259e9b13849c98fc6b6485f2433c97c1fa4b9f
[ "Apache-2.0" ]
null
null
null
include/cql/cql_uuid.hpp
ncbi/cassandra-cpp-driver
b2259e9b13849c98fc6b6485f2433c97c1fa4b9f
[ "Apache-2.0" ]
6
2015-04-26T07:16:44.000Z
2020-11-23T06:31:07.000Z
/* * File: cql_uuid_t.hpp * Author: mc * * Created on September 26, 2013, 12:35 PM */ #ifndef CQL_UUID_HPP_ #define CQL_UUID_HPP_ #include <functional> namespace cql { class cql_uuid_t; } namespace std { // template<> // struct hash<cql::cql_uuid_t>; } namespace cql { class cql_uuid_t { public: // TODO: This is currently implemented as simple long // but soon we switch to official UUID implementation // as described here: // http://www.ietf.org/rfc/rfc4122.txt static cql_uuid_t create(); friend bool operator <(const cql_uuid_t& left, const cql_uuid_t& right); private: cql_uuid_t(unsigned long uuid): _uuid(uuid) { } unsigned long _uuid; // friend struct std::hash<cql_uuid_t>; }; } // namespace std { // template<> // struct hash<cql::cql_uuid_t> { // public: // typedef // cql::cql_uuid_t // argument_type; // typedef // size_t // result_type; // size_t // operator ()(const cql::cql_uuid_t& id) const { // return // ((id._uuid * 3169) << 16) + // ((id._uuid * 23) << 8) + // id._uuid; // } // }; // } #endif /* CQL_UUID_HPP_ */
18.042254
64
0.551132
ncbi
5546642ce4eec804341472684f579415e01994e1
641
cpp
C++
simplefvm/src/FVMSolver/CoeffsPartsCommon/DataExchanger/DataExchangerP.cpp
artvns/SimpleFvm
5a8eca332d6780e738c0bc6c8c2b787b47b5b20d
[ "MIT" ]
4
2022-01-03T08:45:55.000Z
2022-01-06T19:57:11.000Z
simplefvm/src/FVMSolver/CoeffsPartsCommon/DataExchanger/DataExchangerP.cpp
artvns/SimpleFvm
5a8eca332d6780e738c0bc6c8c2b787b47b5b20d
[ "MIT" ]
null
null
null
simplefvm/src/FVMSolver/CoeffsPartsCommon/DataExchanger/DataExchangerP.cpp
artvns/SimpleFvm
5a8eca332d6780e738c0bc6c8c2b787b47b5b20d
[ "MIT" ]
null
null
null
#include "DataExchangerP.h" namespace fvmsolver { DataExchangerP::DataExchangerP(uPtrDataPort spData) : spData_(std::move(spData)), data_(*spData_) { } void DataExchangerP::assignCurrentCellValues(size_t step) { size_t numUw_ = data_.getNumUStarW(step) - 1; size_t numUe_ = data_.getNumUStarE(step) - 1; size_t numVn_ = data_.getNumVStarN(step) - 1; size_t numVs_ = data_.getNumVStarS(step) - 1; dw_var_ = data_.get_deU(numUw_); de_var_ = data_.get_deU(numUe_); dn_var_ = data_.get_deV(numVn_); ds_var_ = data_.get_deV(numVs_); } }
27.869565
63
0.631825
artvns
554761e1a836a0c8b0f900513094b1f845556219
5,192
cpp
C++
src/physics/ycolshape.cpp
sivarajankumar/smoothernity
a4c7d290ca601bddf680ef040f3235dc7b029a6b
[ "MIT" ]
null
null
null
src/physics/ycolshape.cpp
sivarajankumar/smoothernity
a4c7d290ca601bddf680ef040f3235dc7b029a6b
[ "MIT" ]
null
null
null
src/physics/ycolshape.cpp
sivarajankumar/smoothernity
a4c7d290ca601bddf680ef040f3235dc7b029a6b
[ "MIT" ]
null
null
null
#include "yphysres.h" #include "ycolshape.hpp" #include "pmem.hpp" struct ycolshapes_t { int count; ycolshape_t *pool; }; static ycolshapes_t g_ycolshapes; int ycolshape_init(int count) { size_t size_max, align_max; ycolshape_t *cs; #define FIND_SIZES(t) \ if (sizeof(t) > size_max) size_max = sizeof(t); \ if (PMEM_ALIGNOF(t) > align_max) align_max = PMEM_ALIGNOF(t); size_max = align_max = 0; FIND_SIZES(btBoxShape); FIND_SIZES(btHeightfieldTerrainShape); FIND_SIZES(btCompoundShape); FIND_SIZES(btSphereShape); #undef FIND_SIZES g_ycolshapes.count = count; g_ycolshapes.pool = (ycolshape_t*)pmem_alloc(PMEM_ALIGNOF(ycolshape_t), sizeof(ycolshape_t) * count); if (!g_ycolshapes.pool) return YPHYSRES_CANNOT_INIT; for (int i = 0; i < count; ++i ) { cs = ycolshape_get(i); cs->vacant = 1; cs->shape_box = 0; cs->shape_sphere = 0; cs->shape_hmap = 0; cs->shape_comp = 0; cs->shape_convex = 0; cs->shape = 0; cs->data = 0; cs->comp = cs->comp_children = cs->comp_next = cs->comp_prev = 0; cs->vehs = 0; cs->rbs = 0; } for (int i = 0; i < count; ++i) if (!(ycolshape_get(i)->data = (char*)pmem_alloc(align_max, size_max))) return YPHYSRES_CANNOT_INIT; return YPHYSRES_OK; } void ycolshape_done(void) { ycolshape_t *cs; if (!g_ycolshapes.pool) return; for (int i = 0; i < g_ycolshapes.count; ++i) { cs = ycolshape_get(i); if (cs->data) { ycolshape_free(cs); pmem_free(cs->data); } } pmem_free(g_ycolshapes.pool); g_ycolshapes.pool = 0; } ycolshape_t * ycolshape_get(int colshapei) { if (colshapei >= 0 && colshapei < g_ycolshapes.count) return g_ycolshapes.pool + colshapei; else return 0; } int ycolshape_free(ycolshape_t *cs) { if (cs->vacant == 1) return YPHYSRES_INVALID_CS; if (cs->comp_children || cs->vehs || cs->rbs) return YPHYSRES_CS_HAS_REFS; cs->vacant = 1; if (cs->comp) { try { cs->comp->shape_comp->removeChildShape(cs->shape); } catch (...) { return YPHYSRES_INTERNAL; } if (cs->comp->comp_children == cs) cs->comp->comp_children = cs->comp_next; if (cs->comp_prev) cs->comp_prev->comp_next = cs->comp_next; if (cs->comp_next) cs->comp_next->comp_prev = cs->comp_prev; cs->comp = 0; cs->comp_prev = 0; cs->comp_next = 0; } if (cs->shape) { try { cs->shape->~btCollisionShape(); } catch (...) { return YPHYSRES_INTERNAL; } } cs->shape = 0; cs->shape_convex = 0; cs->shape_box = 0; cs->shape_hmap = 0; cs->shape_comp = 0; return YPHYSRES_OK; } int ycolshape_alloc_box(ycolshape_t *cs, float *size) { if (!cs->vacant) return YPHYSRES_INVALID_CS; cs->vacant = 0; try { cs->shape_box = new (cs->data) btBoxShape(btVector3(size[0], size[1], size[2])); } catch (...) { return YPHYSRES_INTERNAL; } cs->shape = cs->shape_box; cs->shape_convex = cs->shape_box; return YPHYSRES_OK; } int ycolshape_alloc_sphere(ycolshape_t *cs, float r) { if (!cs->vacant) return YPHYSRES_INVALID_CS; cs->vacant = 0; try { cs->shape_sphere = new (cs->data) btSphereShape(r); } catch (...) { return YPHYSRES_INTERNAL; } cs->shape = cs->shape_sphere; cs->shape_convex = cs->shape_sphere; return YPHYSRES_OK; } int ycolshape_alloc_hmap(ycolshape_t *cs, float *hmap, int width, int length, float hmin, float hmax, float *scale) { if (!cs->vacant) return YPHYSRES_INVALID_CS; cs->vacant = 0; try { cs->shape_hmap = new (cs->data) btHeightfieldTerrainShape(width, length, hmap, 1, hmin, hmax, 1, PHY_FLOAT, false); } catch (...) { return YPHYSRES_INTERNAL; } cs->shape_hmap->setLocalScaling(btVector3(scale[0], scale[1], scale[2])); cs->shape = cs->shape_hmap; return YPHYSRES_OK; } int ycolshape_alloc_comp(ycolshape_t *cs) { if (!cs->vacant) return YPHYSRES_INVALID_CS; cs->vacant = 0; try { cs->shape_comp = new (cs->data) btCompoundShape(); } catch (...) { return YPHYSRES_INTERNAL; } cs->shape = cs->shape_comp; return YPHYSRES_OK; } int ycolshape_comp_add(ycolshape_t *prt, float *matrix, ycolshape_t *chd) { if (!prt->shape_comp || !chd->shape || chd->shape_comp || chd->comp) return YPHYSRES_INVALID_CS; chd->comp = prt; chd->comp_next = prt->comp_children; if (prt->comp_children) prt->comp_children->comp_prev = chd; prt->comp_children = chd; try { btTransform tm; tm.setFromOpenGLMatrix(matrix); prt->shape_comp->addChildShape(tm, chd->shape); } catch (...) { return YPHYSRES_INTERNAL; } return YPHYSRES_OK; }
27.764706
79
0.578005
sivarajankumar
554a6cc43c83e5ad46f4ae32c3288a1875b434a5
782
cpp
C++
src/client/src/ImagingException.cpp
don-reba/peoples-note
c22d6963846af833c55f4294dd0474e83344475d
[ "BSD-2-Clause" ]
null
null
null
src/client/src/ImagingException.cpp
don-reba/peoples-note
c22d6963846af833c55f4294dd0474e83344475d
[ "BSD-2-Clause" ]
null
null
null
src/client/src/ImagingException.cpp
don-reba/peoples-note
c22d6963846af833c55f4294dd0474e83344475d
[ "BSD-2-Clause" ]
null
null
null
#include "stdafx.h" #include "ImagingException.h" #include "Tools.h" using namespace std; using namespace Tools; ImagingException::ImagingException(HRESULT result) : error (::GetLastError()) , result (result) { DWORD flags (FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_FROM_HMODULE|FORMAT_MESSAGE_IGNORE_INSERTS); HMODULE source (GetModuleHandle(L"imaging.dll")); vector<wchar_t> buffer(100); ::FormatMessage ( flags // dwFlags , source // lpSource , error // dwMessageId , 0 // dwLanguageId , &buffer[0] // pBuffer , buffer.size() // nSize , NULL // Arguments ); message = ConvertToAnsi(&buffer[0]); } const char * ImagingException::what() const { return message.c_str(); }
24.4375
104
0.643223
don-reba
554cc503f4f76c472445fe6d598a53bf39690230
571
cpp
C++
CONTESTS/CODEFORCES/div2 844/A.cpp
priojeetpriyom/competitive-programming
0024328972d4e14c04c0fd5d6dd3cdf131d84f9d
[ "MIT" ]
1
2021-11-22T02:26:43.000Z
2021-11-22T02:26:43.000Z
CONTESTS/CODEFORCES/div2 844/A.cpp
priojeetpriyom/competitive-programming
0024328972d4e14c04c0fd5d6dd3cdf131d84f9d
[ "MIT" ]
null
null
null
CONTESTS/CODEFORCES/div2 844/A.cpp
priojeetpriyom/competitive-programming
0024328972d4e14c04c0fd5d6dd3cdf131d84f9d
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long ll; int vis[200]; int main() { // freopen("in.txt", "r", stdin); // freopen("out.txt", "w", stdout); std::ios_base::sync_with_stdio(false); cin.tie(0); int k; string s; cin>>s>>k; if(k>s.size()) cout<<"impossible"<<endl; else { int cnt=0; for(int i=0; i<s.size(); i++) if(!vis[s[i]]) { vis[s[i]] =1; cnt++; } cout<<max(0, k-cnt)<<endl; } return 0; }
14.641026
45
0.436077
priojeetpriyom
55500631f687f3ca724aa7dc4096cbb61ef2bf1b
1,385
cpp
C++
src/main.cpp
marangisto/dro
d5c7ff5a3d4a321f75288f4dc1417dc30cdca854
[ "MIT" ]
null
null
null
src/main.cpp
marangisto/dro
d5c7ff5a3d4a321f75288f4dc1417dc30cdca854
[ "MIT" ]
null
null
null
src/main.cpp
marangisto/dro
d5c7ff5a3d4a321f75288f4dc1417dc30cdca854
[ "MIT" ]
null
null
null
#include <gpio.h> #include <textio.h> #include <usart.h> #include <hardware/tm1637.h> #include <button.h> static const pin_t LED = PA5; static const pin_t PROBE = PA8; static const int SERIAL_USART = 2; static const pin_t SERIAL_TX = PA2; static const pin_t SERIAL_RX = PA3; static const interrupt_t SERIAL_ISR = interrupt::USART2; static const int AUX_TIMER_NO = 7; static const interrupt_t AUX_TIMER_ISR = interrupt::TIM7; using led = output_t<LED>; using probe = output_t<PROBE>; using aux = tim_t<AUX_TIMER_NO>; using disp0 = tm1637_t<4, 1, 1, PC6, PC8>; using disp1 = tm1637_t<4, 1, 2, PA11, PA12>; using disp2 = tm1637_t<4, 1, 3, PB11, PB12>; using serial = usart_t<SERIAL_USART, SERIAL_TX, SERIAL_RX>; template<typename DISPLAY> void write(float x) { char str[8]; sprintf(str, "%7.4f", x); DISPLAY::write_string(str); } int main() { led::setup(); probe::setup(); serial::setup<230400>(); interrupt::set<SERIAL_ISR>(); interrupt::enable(); printf<serial>("DRO Version 0.1\n"); disp0::setup<10000>(); disp1::setup<10000>(); disp2::setup<10000>(); for (uint16_t i = 0;; ++i) { write<disp0>(static_cast<float>(i) * 0.1239); write<disp1>(static_cast<float>(i) * 3.12378); write<disp2>(static_cast<float>(i) * 17.08); } }
23.083333
60
0.625993
marangisto
5552af8f77f4820aa092974e975ca5b5c22bb4bd
2,269
cc
C++
src/sampler/random_sampler.cc
TheTimmy/decord
67bfd14e4ae50b2751e7b92b73c6d73df35cbdaf
[ "Apache-2.0" ]
762
2020-01-16T02:44:50.000Z
2022-03-30T10:03:36.000Z
src/sampler/random_sampler.cc
TheTimmy/decord
67bfd14e4ae50b2751e7b92b73c6d73df35cbdaf
[ "Apache-2.0" ]
161
2020-01-20T07:47:38.000Z
2022-03-11T15:19:10.000Z
src/sampler/random_sampler.cc
TheTimmy/decord
67bfd14e4ae50b2751e7b92b73c6d73df35cbdaf
[ "Apache-2.0" ]
77
2020-01-23T17:47:20.000Z
2022-03-28T10:12:19.000Z
/*! * Copyright (c) 2019 by Contributors if not otherwise specified * \file random_file_order_sampler.cc * \brief Randomly shuffle file order but not internal frame order */ #include "random_sampler.h" #include <algorithm> #include <dmlc/logging.h> namespace decord { namespace sampler { RandomSampler::RandomSampler(std::vector<int64_t> lens, std::vector<int64_t> range, int bs, int interval, int skip) : bs_(bs), curr_(0) { CHECK(range.size() % 2 == 0) << "Range (begin, end) size incorrect, expected: " << lens.size() * 2; CHECK_EQ(lens.size(), range.size() / 2) << "Video reader size mismatch with range: " << lens.size() << " vs " << range.size() / 2; // output buffer samples_.resize(bs); // visit order for shuffling visit_order_.clear(); for (size_t i = 0; i < lens.size(); ++i) { auto begin = range[i*2]; auto end = range[i*2 + 1]; if (end < 0) { // allow negative indices, e.g., -20 means total_frame - 20 end = lens[i] - end; } CHECK_GE(end, 0) << "Video{" << i << "} has range end smaller than 0: " << end; CHECK(begin < end) << "Video{" << i << "} has invalid begin and end config: " << begin << "->" << end; CHECK(end < lens[i]) << "Video{" << i <<"} has range end larger than # frames: " << lens[i]; int64_t bs_skip = bs * (1 + interval) - interval + skip; int64_t bs_length = bs_skip - skip; for (int64_t b = begin; b + bs_length < end; b += bs_skip) { int offset = 0; for (int j = 0; j < bs; ++j) { samples_[j] = std::make_pair(i, b + offset); offset += interval + 1; } visit_order_.emplace_back(samples_); } } } void RandomSampler::Reset() { // shuffle orders std::random_shuffle(visit_order_.begin(), visit_order_.end()); // reset visit idx curr_ = 0; } bool RandomSampler::HasNext() const { return curr_ < visit_order_.size(); } const Samples& RandomSampler::Next() { CHECK(HasNext()); CHECK_EQ(samples_.size(), bs_); samples_ = visit_order_[curr_++]; return samples_; } size_t RandomSampler::Size() const { return visit_order_.size(); } } // sampler } // decord
31.513889
134
0.578228
TheTimmy
55554a9d591a8c787954592b1ccf0f098e863c22
695
cpp
C++
src/samarium/physics/Spring.cpp
strangeQuark1041/samarium
7e4d107e719d54b55b16d63707595a27f357fb6d
[ "MIT" ]
1
2021-12-25T16:37:53.000Z
2021-12-25T16:37:53.000Z
src/samarium/physics/Spring.cpp
strangeQuark1041/samarium
7e4d107e719d54b55b16d63707595a27f357fb6d
[ "MIT" ]
1
2022-03-07T11:46:27.000Z
2022-03-07T11:46:27.000Z
src/samarium/physics/Spring.cpp
strangeQuark1041/samarium
7e4d107e719d54b55b16d63707595a27f357fb6d
[ "MIT" ]
null
null
null
/* * SPDX-License-Identifier: MIT * Copyright (c) 2022 Jai Bellare * See <https://opensource.org/licenses/MIT/> or LICENSE.md * Project homepage: https://github.com/strangeQuark1041/samarium */ #include "Spring.hpp" namespace sm { [[nodiscard]] auto Spring::length() const noexcept -> f64 { return math::distance(p1.pos, p2.pos); } void Spring::update() noexcept { const auto vec = p2.pos - p1.pos; const auto spring = (vec.length() - rest_length) * stiffness; auto damp = Vector2::dot(vec.normalized(), p2.vel - p1.vel) * damping; const auto force = vec.with_length(spring + damp); p1.apply_force(force); p2.apply_force(-force); } } // namespace sm
26.730769
100
0.666187
strangeQuark1041
55566650381b23567922169592f96bac20617ea6
948
cpp
C++
Leetcode/Day019/unique_path_obstacle.cpp
SujalAhrodia/Practice_2020
59b371ada245ed8253d12327f18deee3e47f31d6
[ "MIT" ]
null
null
null
Leetcode/Day019/unique_path_obstacle.cpp
SujalAhrodia/Practice_2020
59b371ada245ed8253d12327f18deee3e47f31d6
[ "MIT" ]
null
null
null
Leetcode/Day019/unique_path_obstacle.cpp
SujalAhrodia/Practice_2020
59b371ada245ed8253d12327f18deee3e47f31d6
[ "MIT" ]
null
null
null
class Solution { public: int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { int m = obstacleGrid.size(); int n = obstacleGrid[0].size(); vector<vector<unsigned int>> dp(m, vector<unsigned int> (n,0)); if(obstacleGrid[0][0] == 1) return 0; dp[0][0]=1; //first row for(int i=1; i<n; i++) { if(obstacleGrid[0][i] == 0 && dp[0][i-1]==1) dp[0][i]=1; } //first column for(int i=1; i<m; i++) { if(obstacleGrid[i][0] == 0 && dp[i-1][0]==1) dp[i][0]=1; } for(int i=1; i<m; i++) { for(int j=1; j<n; j++) { if(obstacleGrid[i][j] == 0) dp[i][j] = dp[i-1][j] + dp[i][j-1]; } } return dp[m-1][n-1]; } };
23.7
71
0.369198
SujalAhrodia
555e005b05ac3829addccd594298ddd68e224ec4
14,462
cpp
C++
renderdoc/driver/gl/gl_replay_win32.cpp
yangzhengxing/renderdoc
214450227ea96df0b2b079632b1f20e23a3fd8fe
[ "MIT" ]
null
null
null
renderdoc/driver/gl/gl_replay_win32.cpp
yangzhengxing/renderdoc
214450227ea96df0b2b079632b1f20e23a3fd8fe
[ "MIT" ]
null
null
null
renderdoc/driver/gl/gl_replay_win32.cpp
yangzhengxing/renderdoc
214450227ea96df0b2b079632b1f20e23a3fd8fe
[ "MIT" ]
null
null
null
/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2015-2017 Baldur Karlsson * Copyright (c) 2014 Crytek * * 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 "gl_replay.h" #include "gl_driver.h" #include "gl_resources.h" PFNWGLCREATECONTEXTATTRIBSARBPROC createContextAttribs = NULL; PFNWGLGETPIXELFORMATATTRIBIVARBPROC getPixelFormatAttrib = NULL; typedef PROC(WINAPI *WGLGETPROCADDRESSPROC)(const char *); typedef HGLRC(WINAPI *WGLCREATECONTEXTPROC)(HDC); typedef BOOL(WINAPI *WGLMAKECURRENTPROC)(HDC, HGLRC); typedef BOOL(WINAPI *WGLDELETECONTEXTPROC)(HGLRC); WGLGETPROCADDRESSPROC wglGetProc = NULL; WGLCREATECONTEXTPROC wglCreateRC = NULL; WGLMAKECURRENTPROC wglMakeCurrentProc = NULL; WGLDELETECONTEXTPROC wglDeleteRC = NULL; void GLReplay::MakeCurrentReplayContext(GLWindowingData *ctx) { static GLWindowingData *prev = NULL; if(wglMakeCurrentProc && ctx && ctx != prev) { prev = ctx; wglMakeCurrentProc(ctx->DC, ctx->ctx); m_pDriver->ActivateContext(*ctx); } } void GLReplay::SwapBuffers(GLWindowingData *ctx) { ::SwapBuffers(ctx->DC); } void GLReplay::CloseReplayContext() { if(wglDeleteRC) { wglMakeCurrentProc(NULL, NULL); wglDeleteRC(m_ReplayCtx.ctx); ReleaseDC(m_ReplayCtx.wnd, m_ReplayCtx.DC); ::DestroyWindow(m_ReplayCtx.wnd); } } uint64_t GLReplay::MakeOutputWindow(WindowingSystem system, void *data, bool depth) { RDCASSERT(system == eWindowingSystem_Win32 || system == eWindowingSystem_Unknown, system); HWND w = (HWND)data; if(w == NULL) w = CreateWindowEx(WS_EX_CLIENTEDGE, L"renderdocGLclass", L"", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, GetModuleHandle(NULL), NULL); HDC DC = GetDC(w); PIXELFORMATDESCRIPTOR pfd = {0}; int attrib = eWGL_NUMBER_PIXEL_FORMATS_ARB; int value = 1; getPixelFormatAttrib(DC, 1, 0, 1, &attrib, &value); int pf = 0; int numpfs = value; for(int i = 1; i <= numpfs; i++) { // verify that we have the properties we want attrib = eWGL_DRAW_TO_WINDOW_ARB; getPixelFormatAttrib(DC, i, 0, 1, &attrib, &value); if(value == 0) continue; attrib = eWGL_ACCELERATION_ARB; getPixelFormatAttrib(DC, i, 0, 1, &attrib, &value); if(value == eWGL_NO_ACCELERATION_ARB) continue; attrib = eWGL_SUPPORT_OPENGL_ARB; getPixelFormatAttrib(DC, i, 0, 1, &attrib, &value); if(value == 0) continue; attrib = eWGL_DOUBLE_BUFFER_ARB; getPixelFormatAttrib(DC, i, 0, 1, &attrib, &value); if(value == 0) continue; attrib = eWGL_PIXEL_TYPE_ARB; getPixelFormatAttrib(DC, i, 0, 1, &attrib, &value); if(value != eWGL_TYPE_RGBA_ARB) continue; // we have an opengl-capable accelerated RGBA context. // we use internal framebuffers to do almost all rendering, so we just need // RGB (color bits > 24) and SRGB buffer. attrib = eWGL_COLOR_BITS_ARB; getPixelFormatAttrib(DC, i, 0, 1, &attrib, &value); if(value < 24) continue; attrib = WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB; getPixelFormatAttrib(DC, i, 0, 1, &attrib, &value); if(value == 0) continue; // this one suits our needs, choose it pf = i; break; } if(pf == 0) { ReleaseDC(w, DC); RDCERR("Couldn't choose pixel format"); return NULL; } BOOL res = DescribePixelFormat(DC, pf, sizeof(pfd), &pfd); if(res == FALSE) { ReleaseDC(w, DC); RDCERR("Couldn't describe pixel format"); return NULL; } res = SetPixelFormat(DC, pf, &pfd); if(res == FALSE) { ReleaseDC(w, DC); RDCERR("Couldn't set pixel format"); return NULL; } int attribs[64] = {0}; int i = 0; attribs[i++] = WGL_CONTEXT_MAJOR_VERSION_ARB; attribs[i++] = GLCoreVersion / 10; attribs[i++] = WGL_CONTEXT_MINOR_VERSION_ARB; attribs[i++] = GLCoreVersion % 10; attribs[i++] = WGL_CONTEXT_FLAGS_ARB; #if ENABLED(RDOC_DEVEL) attribs[i++] = WGL_CONTEXT_DEBUG_BIT_ARB; #else attribs[i++] = 0; #endif attribs[i++] = WGL_CONTEXT_PROFILE_MASK_ARB; attribs[i++] = WGL_CONTEXT_CORE_PROFILE_BIT_ARB; HGLRC rc = createContextAttribs(DC, m_ReplayCtx.ctx, attribs); if(rc == NULL) { ReleaseDC(w, DC); RDCERR("Couldn't create %d.%d context - something changed since creation", GLCoreVersion / 10, GLCoreVersion % 10); return 0; } OutputWindow win; win.DC = DC; win.ctx = rc; win.wnd = w; RECT rect = {0}; GetClientRect(w, &rect); win.width = rect.right - rect.left; win.height = rect.bottom - rect.top; m_pDriver->RegisterContext(win, m_ReplayCtx.ctx, true, true); InitOutputWindow(win); CreateOutputWindowBackbuffer(win, depth); uint64_t ret = m_OutputWindowID++; m_OutputWindows[ret] = win; return ret; } void GLReplay::DestroyOutputWindow(uint64_t id) { auto it = m_OutputWindows.find(id); if(id == 0 || it == m_OutputWindows.end()) return; OutputWindow &outw = it->second; MakeCurrentReplayContext(&outw); WrappedOpenGL &gl = *m_pDriver; gl.glDeleteFramebuffers(1, &outw.BlitData.readFBO); wglMakeCurrentProc(NULL, NULL); wglDeleteRC(outw.ctx); ReleaseDC(outw.wnd, outw.DC); m_OutputWindows.erase(it); } void GLReplay::GetOutputWindowDimensions(uint64_t id, int32_t &w, int32_t &h) { if(id == 0 || m_OutputWindows.find(id) == m_OutputWindows.end()) return; OutputWindow &outw = m_OutputWindows[id]; RECT rect = {0}; GetClientRect(outw.wnd, &rect); w = rect.right - rect.left; h = rect.bottom - rect.top; } bool GLReplay::IsOutputWindowVisible(uint64_t id) { if(id == 0 || m_OutputWindows.find(id) == m_OutputWindows.end()) return false; return (IsWindowVisible(m_OutputWindows[id].wnd) == TRUE); } const GLHookSet &GetRealGLFunctions(); ReplayCreateStatus GL_CreateReplayDevice(const char *logfile, IReplayDriver **driver) { RDCDEBUG("Creating an OpenGL replay device"); HMODULE lib = NULL; lib = LoadLibraryA("opengl32.dll"); if(lib == NULL) { RDCERR("Failed to load opengl32.dll"); return eReplayCreate_APIInitFailed; } GLInitParams initParams; RDCDriver driverType = RDC_OpenGL; string driverName = "OpenGL"; uint64_t machineIdent = 0; if(logfile) { auto status = RenderDoc::Inst().FillInitParams(logfile, driverType, driverName, machineIdent, (RDCInitParams *)&initParams); if(status != eReplayCreate_Success) return status; } PIXELFORMATDESCRIPTOR pfd = {0}; if(wglGetProc == NULL) { wglGetProc = (WGLGETPROCADDRESSPROC)GetProcAddress(lib, "wglGetProcAddress"); wglCreateRC = (WGLCREATECONTEXTPROC)GetProcAddress(lib, "wglCreateContext"); wglMakeCurrentProc = (WGLMAKECURRENTPROC)GetProcAddress(lib, "wglMakeCurrent"); wglDeleteRC = (WGLDELETECONTEXTPROC)GetProcAddress(lib, "wglDeleteContext"); if(wglGetProc == NULL || wglCreateRC == NULL || wglMakeCurrentProc == NULL || wglDeleteRC == NULL) { RDCERR("Couldn't get wgl function addresses"); return eReplayCreate_APIInitFailed; } WNDCLASSEX wc; RDCEraseEl(wc); wc.style = CS_OWNDC; wc.cbSize = sizeof(WNDCLASSEX); wc.lpfnWndProc = DefWindowProc; wc.hInstance = GetModuleHandle(NULL); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.lpszClassName = L"renderdocGLclass"; if(!RegisterClassEx(&wc)) { RDCERR("Couldn't register GL window class"); return eReplayCreate_APIInitFailed; } RDCEraseEl(pfd); pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); pfd.nVersion = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; pfd.iLayerType = PFD_MAIN_PLANE; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 32; pfd.cDepthBits = 24; pfd.cStencilBits = 0; } HWND w = CreateWindowEx(WS_EX_CLIENTEDGE, L"renderdocGLclass", L"", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, GetModuleHandle(NULL), NULL); HDC dc = GetDC(w); int pf = ChoosePixelFormat(dc, &pfd); if(pf == 0) { RDCERR("Couldn't choose pixel format"); return eReplayCreate_APIInitFailed; } BOOL res = SetPixelFormat(dc, pf, &pfd); if(res == FALSE) { RDCERR("Couldn't set pixel format"); return eReplayCreate_APIInitFailed; } HGLRC rc = wglCreateRC(dc); if(rc == NULL) { RDCERR("Couldn't create simple RC"); return eReplayCreate_APIInitFailed; } res = wglMakeCurrentProc(dc, rc); if(res == FALSE) { RDCERR("Couldn't make simple RC current"); return eReplayCreate_APIInitFailed; } createContextAttribs = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProc("wglCreateContextAttribsARB"); getPixelFormatAttrib = (PFNWGLGETPIXELFORMATATTRIBIVARBPROC)wglGetProc("wglGetPixelFormatAttribivARB"); if(createContextAttribs == NULL || getPixelFormatAttrib == NULL) { RDCERR("RenderDoc requires WGL_ARB_create_context and WGL_ARB_pixel_format"); return eReplayCreate_APIHardwareUnsupported; } wglMakeCurrentProc(NULL, NULL); wglDeleteRC(rc); ReleaseDC(w, dc); DestroyWindow(w); GLReplay::PreContextInitCounters(); // we don't use the default framebuffer (backbuffer) for anything, so we make it // tiny and with no depth/stencil bits pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 24; pfd.cDepthBits = 0; pfd.cStencilBits = 0; w = CreateWindowEx(WS_EX_CLIENTEDGE, L"renderdocGLclass", L"RenderDoc replay window", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 32, 32, NULL, NULL, GetModuleHandle(NULL), NULL); dc = GetDC(w); pf = ChoosePixelFormat(dc, &pfd); if(pf == 0) { RDCERR("Couldn't choose pixel format"); ReleaseDC(w, dc); GLReplay::PostContextShutdownCounters(); return eReplayCreate_APIInitFailed; } res = SetPixelFormat(dc, pf, &pfd); if(res == FALSE) { RDCERR("Couldn't set pixel format"); ReleaseDC(w, dc); GLReplay::PostContextShutdownCounters(); return eReplayCreate_APIInitFailed; } int attribs[64] = {0}; int i = 0; attribs[i++] = WGL_CONTEXT_MAJOR_VERSION_ARB; int &major = attribs[i]; attribs[i++] = 0; attribs[i++] = WGL_CONTEXT_MINOR_VERSION_ARB; int &minor = attribs[i]; attribs[i++] = 0; attribs[i++] = WGL_CONTEXT_FLAGS_ARB; #if ENABLED(RDOC_DEVEL) attribs[i++] = WGL_CONTEXT_DEBUG_BIT_ARB; #else attribs[i++] = 0; #endif attribs[i++] = WGL_CONTEXT_PROFILE_MASK_ARB; attribs[i++] = WGL_CONTEXT_CORE_PROFILE_BIT_ARB; // try to create all versions from 4.5 down to 3.2 in order to get the // highest versioned context we can struct { int major; int minor; } versions[] = { {4, 5}, {4, 4}, {4, 3}, {4, 2}, {4, 1}, {4, 0}, {3, 3}, {3, 2}, }; rc = NULL; for(size_t v = 0; v < ARRAY_COUNT(versions); v++) { major = versions[v].major; minor = versions[v].minor; rc = createContextAttribs(dc, NULL, attribs); if(rc) break; } if(rc == NULL) { RDCERR("Couldn't create 3.2 RC - RenderDoc requires OpenGL 3.2 availability"); ReleaseDC(w, dc); GLReplay::PostContextShutdownCounters(); return eReplayCreate_APIHardwareUnsupported; } GLCoreVersion = major * 10 + minor; res = wglMakeCurrentProc(dc, rc); if(res == FALSE) { RDCERR("Couldn't make 3.2 RC current"); wglMakeCurrentProc(NULL, NULL); wglDeleteRC(rc); ReleaseDC(w, dc); GLReplay::PostContextShutdownCounters(); return eReplayCreate_APIInitFailed; } PFNGLGETINTEGERVPROC getInt = (PFNGLGETINTEGERVPROC)GetProcAddress(lib, "glGetIntegerv"); PFNGLGETSTRINGPROC getStr = (PFNGLGETSTRINGPROC)GetProcAddress(lib, "glGetString"); PFNGLGETSTRINGIPROC getStri = (PFNGLGETSTRINGIPROC)wglGetProc("glGetStringi"); if(getInt == NULL || getStr == NULL || getStri == NULL) { RDCERR("Couldn't get glGetIntegerv (%p), glGetString (%p) or glGetStringi (%p) entry points", getInt, getStr, getStri); wglMakeCurrentProc(NULL, NULL); wglDeleteRC(rc); ReleaseDC(w, dc); GLReplay::PostContextShutdownCounters(); return eReplayCreate_APIInitFailed; } bool missingExt = CheckReplayContext(getStr, getInt, getStri); if(missingExt) { wglMakeCurrentProc(NULL, NULL); wglDeleteRC(rc); ReleaseDC(w, dc); GLReplay::PostContextShutdownCounters(); return eReplayCreate_APIInitFailed; } const GLHookSet &real = GetRealGLFunctions(); bool extensionsValidated = ValidateFunctionPointers(real); if(!extensionsValidated) { wglMakeCurrentProc(NULL, NULL); wglDeleteRC(rc); ReleaseDC(w, dc); GLReplay::PostContextShutdownCounters(); return eReplayCreate_APIInitFailed; } WrappedOpenGL *gl = new WrappedOpenGL(logfile, real); gl->Initialise(initParams); if(gl->GetSerialiser()->HasError()) { delete gl; return eReplayCreate_FileIOFailed; } RDCLOG("Created device."); GLReplay *replay = gl->GetReplay(); replay->SetProxy(logfile == NULL); GLWindowingData data; data.DC = dc; data.ctx = rc; data.wnd = w; replay->SetReplayData(data); *driver = (IReplayDriver *)replay; return eReplayCreate_Success; }
27.704981
102
0.679021
yangzhengxing
555eb04b23df36f8bbe34884d1adb71ad6759a83
2,712
cpp
C++
src/camera/CameraParams.cpp
huskyroboticsteam/PY2020
cd6368d85866204dbdca6aefacac69059e780aa2
[ "Apache-2.0" ]
11
2019-10-03T01:17:16.000Z
2020-10-25T02:38:32.000Z
src/camera/CameraParams.cpp
huskyroboticsteam/PY2020
cd6368d85866204dbdca6aefacac69059e780aa2
[ "Apache-2.0" ]
53
2019-10-03T02:11:04.000Z
2021-06-05T03:11:55.000Z
src/camera/CameraParams.cpp
huskyroboticsteam/Resurgence
649f78103b6d76709fdf55bb38d08c0ff50da140
[ "Apache-2.0" ]
3
2019-09-20T04:09:29.000Z
2020-08-18T22:25:20.000Z
#include "CameraParams.h" #include <opencv2/core.hpp> namespace cam { ////////////// CONSTRUCTORS ////////////// CameraParams::CameraParams() { } void CameraParams::init(const cv::Mat& camera_matrix, const cv::Mat& dist_coeff, cv::Size image_size) { if (camera_matrix.size() != cv::Size(3, 3)) { throw std::invalid_argument("Camera matrix must be 3x3"); } int n_coeffs = dist_coeff.rows * dist_coeff.cols; if (!(n_coeffs == 4 || n_coeffs == 5 || n_coeffs == 8 || n_coeffs == 12 || n_coeffs == 14)) { throw std::invalid_argument( "Number of distortion coefficients must be 4, 5, 8, 12, or 14"); } if (image_size.empty()) { throw std::invalid_argument("Image size must not be empty"); } dist_coeff.reshape(1, {n_coeffs, 1}).copyTo(this->_dist_coeff); camera_matrix.copyTo(this->_camera_matrix); this->_image_size = image_size; } CameraParams::CameraParams(const cv::Mat& camera_matrix, const cv::Mat& dist_coeff, cv::Size image_size) { init(camera_matrix, dist_coeff, image_size); } CameraParams::CameraParams(const CameraParams& other) { cv::Mat newCam, newDist; other._camera_matrix.copyTo(newCam); other._dist_coeff.copyTo(newDist); this->_camera_matrix = newCam; this->_dist_coeff = newDist; this->_image_size = other._image_size; } bool CameraParams::empty() const { return _camera_matrix.empty() || _dist_coeff.empty() || _image_size.empty(); } ////////////// ACCESSORS ///////////////// cv::Mat CameraParams::getCameraMatrix() const { return _camera_matrix; } cv::Mat CameraParams::getDistCoeff() const { return _dist_coeff; } cv::Size CameraParams::getImageSize() const { return _image_size; } ////////////// SERIALIZATION ////////////// void CameraParams::readFromFileNode(const cv::FileNode& file_node) { cv::Mat cam, dist; file_node[KEY_CAMERA_MATRIX] >> cam; file_node[KEY_DIST_COEFFS] >> dist; int w, h; w = (int)file_node[KEY_IMAGE_WIDTH]; h = (int)file_node[KEY_IMAGE_HEIGHT]; cv::Size size(w, h); // call init to do validation init(cam, dist, size); } void CameraParams::writeToFileStorage(cv::FileStorage& file_storage) const { file_storage << "{"; file_storage << KEY_IMAGE_WIDTH << _image_size.width; file_storage << KEY_IMAGE_HEIGHT << _image_size.height; file_storage << KEY_CAMERA_MATRIX << _camera_matrix; file_storage << KEY_DIST_COEFFS << _dist_coeff; file_storage << "}"; } void read(const cv::FileNode& node, CameraParams& params, const CameraParams& default_value) { if (node.empty()) { params = default_value; } else { params.readFromFileNode(node); } } void write(cv::FileStorage& fs, const std::string& name, const CameraParams& params) { params.writeToFileStorage(fs); } } // namespace cam
26.851485
94
0.696165
huskyroboticsteam
5561aca0f75c7279a4e60441e8f0e6ae404732fd
9,253
cpp
C++
src/heuristics/rcHeuristics/RCModelFactory.cpp
Songtuan-Lin/pandaPIengine
be019b16fec6f679fa3db31b97ccbe9491769d65
[ "BSD-3-Clause" ]
5
2021-04-06T22:06:47.000Z
2021-07-20T14:56:13.000Z
src/heuristics/rcHeuristics/RCModelFactory.cpp
Songtuan-Lin/pandaPIengine
be019b16fec6f679fa3db31b97ccbe9491769d65
[ "BSD-3-Clause" ]
2
2021-04-07T12:17:39.000Z
2021-09-03T10:30:26.000Z
src/heuristics/rcHeuristics/RCModelFactory.cpp
Songtuan-Lin/pandaPIengine
be019b16fec6f679fa3db31b97ccbe9491769d65
[ "BSD-3-Clause" ]
6
2021-06-16T13:41:06.000Z
2022-03-30T07:13:18.000Z
/* * RCModelFactory.cpp * * Created on: 09.02.2020 * Author: dh */ #include "RCModelFactory.h" namespace progression { RCModelFactory::RCModelFactory(Model* htn) { this->htn = htn; } RCModelFactory::~RCModelFactory() { // TODO Auto-generated destructor stub } Model* RCModelFactory::getRCmodelSTRIPS() { return this->getRCmodelSTRIPS(1); } Model* RCModelFactory::getRCmodelSTRIPS(int costsMethodActions) { Model* rc = new Model(); rc->isHtnModel = false; rc->numStateBits = htn->numStateBits + htn->numActions + htn->numTasks; rc->numVars = htn->numVars + htn->numActions + htn->numTasks; // first part might be SAS+ rc->numActions = htn->numActions + htn->numMethods; rc->numTasks = rc->numActions; rc->precLists = new int*[rc->numActions]; rc->addLists = new int*[rc->numActions]; rc->delLists = new int*[rc->numActions]; rc->numPrecs = new int[rc->numActions]; rc->numAdds = new int[rc->numActions]; rc->numDels = new int[rc->numActions]; // add new prec and add effect to actions for(int i = 0; i < htn->numActions; i++) { rc->numPrecs[i] = htn->numPrecs[i] + 1; rc->precLists[i] = new int[rc->numPrecs[i]]; for(int j = 0; j < rc->numPrecs[i] - 1; j++) { rc->precLists[i][j] = htn->precLists[i][j]; } rc->precLists[i][rc->numPrecs[i] - 1] = t2tdr(i); rc->numAdds[i] = htn->numAdds[i] + 1; rc->addLists[i] = new int[rc->numAdds[i]]; for(int j = 0; j < rc->numAdds[i] - 1; j++) { rc->addLists[i][j] = htn->addLists[i][j]; } rc->addLists[i][rc->numAdds[i] - 1] = t2bur(i); rc->numDels[i] = htn->numDels[i]; rc->delLists[i] = new int[rc->numDels[i]]; for(int j = 0; j < rc->numDels[i]; j++) { rc->delLists[i][j] = htn->delLists[i][j]; } } // create actions for methods for(int im = 0; im < htn->numMethods; im++) { int ia = htn->numActions + im; rc->numPrecs[ia] = htn->numDistinctSTs[im]; rc->precLists[ia] = new int[rc->numPrecs[ia]]; for(int ist = 0; ist < htn->numDistinctSTs[im]; ist++) { int st = htn->sortedDistinctSubtasks[im][ist]; rc->precLists[ia][ist] = t2bur(st); } rc->numAdds[ia] = 1; rc->addLists[ia] = new int[1]; rc->addLists[ia][0] = t2bur(htn->decomposedTask[im]); rc->numDels[ia] = 0; rc->delLists[ia] = nullptr; } // set names of state features rc->factStrs = new string[rc->numStateBits]; for(int i = 0; i < htn->numStateBits; i++) { rc->factStrs[i] = htn->factStrs[i]; } for(int i = 0; i < htn->numActions; i++) { rc->factStrs[t2tdr(i)] = "tdr-" + htn->taskNames[i]; } for(int i = 0; i < htn->numTasks; i++) { rc->factStrs[t2bur(i)] = "bur-" + htn->taskNames[i]; } // set action names rc->taskNames = new string[rc->numTasks]; for(int i = 0; i < htn->numActions; i++) { rc->taskNames[i] = htn->taskNames[i]; } for(int im = 0; im < htn->numMethods; im++) { int ia = htn->numActions + im; rc->taskNames[ia] = htn->methodNames[im] + "@" + htn->taskNames[htn->decomposedTask[im]]; } // set variable names rc->varNames = new string[rc->numVars]; for(int i = 0; i < htn->numVars; i++) { rc->varNames[i] = htn->varNames[i]; } for(int i = 0; i < htn->numActions; i++) { // todo: the index transformation does not use the functions // defined above and needs to be redone when changing them int inew = htn->numVars + i; rc->varNames[inew] = "tdr-" + htn->taskNames[i]; } for(int i = 0; i < htn->numTasks; i++) { // todo: transformation needs to be redone when changing them int inew = htn->numVars + htn->numActions + i; rc->varNames[inew] = "bur-" + htn->taskNames[i]; } // set indices of first and last bit rc->firstIndex = new int[rc->numVars]; rc->lastIndex = new int[rc->numVars]; for(int i = 0; i < htn->numVars; i++) { rc->firstIndex[i] = htn->firstIndex[i]; rc->lastIndex[i] = htn->lastIndex[i]; } for(int i = htn->numVars; i < rc->numVars; i++) { rc->firstIndex[i] = rc->lastIndex[i - 1] + 1; rc->lastIndex[i] = rc->firstIndex[i]; } // set action costs rc->actionCosts = new int[rc->numActions]; for(int i = 0; i < htn->numActions; i++) { rc->actionCosts[i] = htn->actionCosts[i]; } for(int i = htn->numActions; i < rc->numActions; i++) { rc->actionCosts[i] = costsMethodActions; } set<int> precless; for(int i = 0; i < rc->numActions; i++) { if (rc->numPrecs[i] == 0) { precless.insert(i); } } rc->numPrecLessActions = precless.size(); rc->precLessActions = new int[rc->numPrecLessActions]; int j = 0; for(int pl : precless) { rc->precLessActions[j++] = pl; } rc->isPrimitive = new bool[rc->numActions]; for(int i = 0; i < rc->numActions; i++) rc->isPrimitive[i] = true; createInverseMappings(rc); set<int> s; for(int i = 0; i < htn->s0Size; i++) { s.insert(htn->s0List[i]); } for(int i = 0; i < htn->numActions; i++) { s.insert(t2tdr(i)); } rc->s0Size = s.size(); rc->s0List = new int[rc->s0Size]; int i = 0; for (int f : s) { rc->s0List[i++] = f; } rc->gSize = 1 + htn->gSize; rc->gList = new int[rc->gSize]; for(int i = 0; i < htn->gSize; i++) { rc->gList[i] = htn->gList[i]; } rc->gList[rc->gSize - 1] = t2bur(htn->initialTask); #ifndef NDEBUG for(int i = 0; i < rc->numActions; i++) { set<int> prec; for(int j = 0; j < rc->numPrecs[i]; j++) { prec.insert(rc->precLists[i][j]); } assert(prec.size() == rc->numPrecs[i]); // precondition contained twice? set<int> add; for(int j = 0; j < rc->numAdds[i]; j++) { add.insert(rc->addLists[i][j]); } assert(add.size() == rc->numAdds[i]); // add contained twice? set<int> del; for(int j = 0; j < rc->numDels[i]; j++) { del.insert(rc->delLists[i][j]); } assert(del.size() == rc->numDels[i]); // del contained twice? } // are subtasks represented in preconditions? for(int i = 0; i < htn->numMethods; i++) { for(int j = 0; j < htn->numSubTasks[i]; j++) { int f = t2bur(htn->subTasks[i][j]); bool contained = false; int mAction = htn->numActions + i; for(int k = 0; k < rc->numPrecs[mAction]; k++) { if(rc->precLists[mAction][k] == f) { contained = true; break; } } assert(contained); // is subtask contained in the respective action's preconditions? } } // are preconditions represented in subtasks? for(int i = htn->numActions; i < rc->numActions; i++) { int m = i - htn->numActions; for(int j = 0; j < rc->numPrecs[i]; j++) { int f = rc->precLists[i][j]; int task = f - (htn->numStateBits + htn->numActions); bool contained = false; for(int k = 0; k < htn->numSubTasks[m]; k++) { int subtask = htn->subTasks[m][k]; if(subtask == task) { contained = true; break; } } assert(contained); } } #endif return rc; } void RCModelFactory::createInverseMappings(Model* c){ set<int>* precToActionTemp = new set<int>[c->numStateBits]; for (int i = 0; i < c->numActions; i++) { for (int j = 0; j < c->numPrecs[i]; j++) { int f = c->precLists[i][j]; precToActionTemp[f].insert(i); } } c->precToActionSize = new int[c->numStateBits]; c->precToAction = new int*[c->numStateBits]; for (int i = 0; i < c->numStateBits; i++) { c->precToActionSize[i] = precToActionTemp[i].size(); c->precToAction[i] = new int[c->precToActionSize[i]]; int cur = 0; for (int ac : precToActionTemp[i]) { c->precToAction[i][cur++] = ac; } } delete[] precToActionTemp; } /* * The original state bits are followed by one bit per action that is set iff * the action is reachable from the top. Then, there is one bit for each task * indicating that task has been reached bottom-up. */ int RCModelFactory::t2tdr(int task) { return htn->numStateBits + task; } int RCModelFactory::t2bur(int task) { return htn->numStateBits + htn->numActions + task; } pair<int, int> RCModelFactory::rcStateFeature2HtnIndex(string s) { //cout << "searching index for \"" << s << "\"" << endl; s = s.substr(0, s.length() - 2); // ends with "()" due to grounded representation int type = -1; int index = -1; if((s.rfind("bur-", 0) == 0)) { type = fTask; s = s.substr(4, s.length() - 4); for(int i = 0; i < htn->numTasks; i++) { if(s.compare(su.toLowerString(su.cleanStr(htn->taskNames[i]))) == 0) { index = i; #ifndef NDEBUG // the name has been cleaned, check whether it is unique for(int j = i + 1; j < htn->numTasks; j++) { assert(s.compare(su.toLowerString(su.cleanStr(htn->taskNames[j]))) != 0); } #endif break; } } } else { type = fFact; for(int i = 0; i < htn->numStateBits; i++) { if(s.compare(su.toLowerString(su.cleanStr(htn->factStrs[i]))) == 0) { index = i; #ifndef NDEBUG // the name has been cleaned, check whether it is unique for(int j = i + 1; j < htn->numStateBits; j++) { assert(s.compare(su.toLowerString(su.cleanStr(htn->factStrs[j]))) != 0); } #endif break; } } } //cout << "Type " << type << endl; //cout << "Index " << index << endl; return make_pair(type, index); } } /* namespace progression */
28.915625
93
0.584675
Songtuan-Lin
5563e17227c0e9ac9e3f36e11978115c10de87cf
3,764
cpp
C++
src/vismethods/boxplot.cpp
jakobtroidl/Barrio
55c447325f2e83a21b39c54cdca37b2779d0569c
[ "MIT" ]
null
null
null
src/vismethods/boxplot.cpp
jakobtroidl/Barrio
55c447325f2e83a21b39c54cdca37b2779d0569c
[ "MIT" ]
3
2021-11-02T22:24:04.000Z
2021-11-29T18:01:51.000Z
src/vismethods/boxplot.cpp
jakobtroidl/Barrio
55c447325f2e83a21b39c54cdca37b2779d0569c
[ "MIT" ]
null
null
null
#include "boxplot.h" Boxplot::Boxplot(Boxplot* boxplot) { m_datacontainer = boxplot->m_datacontainer; m_global_vis_parameters = boxplot->m_global_vis_parameters; } Boxplot::Boxplot(GlobalVisParameters* visparams, DataContainer* datacontainer) { m_global_vis_parameters = visparams; m_datacontainer = datacontainer; } Boxplot::~Boxplot() { } QString Boxplot::createJSONString(QList<int>* selectedObjects) { QJsonArray document; for (auto i : *selectedObjects) { Object* mito = m_datacontainer->getObject(i); std::vector<int>* mito_indices = mito->get_indices_list(); std::vector<VertexData>* vertices = m_datacontainer->getMesh()->getVerticesList(); QJsonObject mito_json; QJsonArray mito_distances; for (auto j : *mito_indices) { VertexData vertex = vertices->at(j); double distance_to_cell = vertex.distance_to_cell; if (distance_to_cell < 1000.0) { mito_distances.push_back(QJsonValue::fromVariant(distance_to_cell)); } } mito_json.insert("key", mito->getName().c_str()); mito_json.insert("value", mito_distances); document.push_back(mito_json); } QJsonDocument doc(document); return doc.toJson(QJsonDocument::Indented); } QWebEngineView* Boxplot::initVisWidget(int ID, SpecificVisParameters params) { m_settings = params.settings; bool normalized = m_settings.value("normalized").toBool(); QString json = createJSONString(&m_global_vis_parameters->selected_objects); m_data = new BoxplotData(json, m_datacontainer, m_global_vis_parameters, normalized); setSpecificVisParameters(params); m_web_engine_view = new QWebEngineView(); QWebChannel* channel = new QWebChannel(m_web_engine_view->page()); m_web_engine_view->page()->setWebChannel(channel); channel->registerObject(QStringLiteral("boxplot_data"), m_data); m_web_engine_view->load(getHTMLPath(m_index_filename)); return m_web_engine_view; } QWebEngineView* Boxplot::getWebEngineView() { return m_web_engine_view; } bool Boxplot::update() { QString json = createJSONString(&m_global_vis_parameters->selected_objects); m_data->setJSONString(json); return true; } Boxplot* Boxplot::clone() { return new Boxplot(this); } bool Boxplot::update_needed() { return true; } VisType Boxplot::getType() { return VisType::BOXPLOT; } void Boxplot::setSpecificVisParameters(SpecificVisParameters params) { m_data->setColors(params.colors); } BoxplotData::BoxplotData(QString json_data, DataContainer* data_container, GlobalVisParameters* global_vis_parameters, bool normalized) { m_json_string = json_data; m_datacontainer = data_container; m_global_vis_parameters = global_vis_parameters; m_normalized = normalized; } BoxplotData::~BoxplotData() { } Q_INVOKABLE QString BoxplotData::getData() { return Q_INVOKABLE m_json_string; } Q_INVOKABLE QString BoxplotData::getColormap() { return Q_INVOKABLE m_colors; } Q_INVOKABLE bool BoxplotData::getNormalized() { return Q_INVOKABLE m_normalized; } Q_INVOKABLE void BoxplotData::setHighlightedFrame(const QString& name) { int hvgx = m_datacontainer->getIndexByName(name); if (!m_global_vis_parameters->highlighted_group_boxes.contains(hvgx)) { m_global_vis_parameters->highlighted_group_boxes.append(hvgx); } m_global_vis_parameters->needs_update = true; return Q_INVOKABLE void(); } Q_INVOKABLE void BoxplotData::removeHighlightedFrame(const QString& name_to_remove) { int hvgx_id = m_datacontainer->getIndexByName(name_to_remove); QVector<int>* highlighted = &m_global_vis_parameters->highlighted_group_boxes; if (highlighted->contains(hvgx_id)) { QMutableVectorIterator<int> it(*highlighted); while (it.hasNext()) { if (it.next() == hvgx_id) { it.remove(); } } } m_global_vis_parameters->needs_update = true; return Q_INVOKABLE void(); }
24.283871
135
0.772848
jakobtroidl
5568cae4112ad35a5722916126cef4f92baa52be
5,227
hpp
C++
libmikroxml/mikroxml/mikroxml.hpp
rantingmong/svgrenderer
082879b448a2c241f69e383620b59e307298bb77
[ "MIT" ]
1
2021-03-29T19:30:47.000Z
2021-03-29T19:30:47.000Z
libmikroxml/mikroxml/mikroxml.hpp
rantingmong/svgrenderer
082879b448a2c241f69e383620b59e307298bb77
[ "MIT" ]
null
null
null
libmikroxml/mikroxml/mikroxml.hpp
rantingmong/svgrenderer
082879b448a2c241f69e383620b59e307298bb77
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <utki/Buf.hpp> #include <utki/Exc.hpp> namespace mikroxml{ class Parser{ enum class State_e{ IDLE, TAG, TAG_SEEK_GT, TAG_EMPTY, DECLARATION, DECLARATION_END, COMMENT, COMMENT_END, ATTRIBUTES, ATTRIBUTE_NAME, ATTRIBUTE_SEEK_TO_EQUALS, ATTRIBUTE_SEEK_TO_VALUE, ATTRIBUTE_VALUE, CONTENT, REF_CHAR, DOCTYPE, DOCTYPE_BODY, DOCTYPE_TAG, DOCTYPE_ENTITY_NAME, DOCTYPE_ENTITY_SEEK_TO_VALUE, DOCTYPE_ENTITY_VALUE, DOCTYPE_SKIP_TAG, SKIP_UNKNOWN_EXCLAMATION_MARK_CONSTRUCT } state = State_e::IDLE; void parseIdle(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseTag(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseTagEmpty(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseTagSeekGt(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseDeclaration(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseDeclarationEnd(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseComment(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseCommentEnd(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseAttributes(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseAttributeName(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseAttributeSeekToEquals(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseAttributeSeekToValue(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseAttributeValue(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseContent(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseRefChar(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseDoctype(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseDoctypeBody(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseDoctypeTag(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseDoctypeSkipTag(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseDoctypeEntityName(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseDoctypeEntitySeekToValue(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseDoctypeEntityValue(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseSkipUnknownExclamationMarkConstruct(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void handleAttributeParsed(); void processParsedTagName(); void processParsedRefChar(); std::vector<char> buf; std::vector<char> name; //general variable for storing name of something (attribute name, entity name, etc.) std::vector<char> refCharBuf; char attrValueQuoteChar; State_e stateAfterRefChar; unsigned lineNumber = 1; std::map<std::string, std::vector<char>> doctypeEntities; public: Parser(); class Exc : public utki::Exc{ public: Exc(const std::string& message) : utki::Exc(message){} }; class MalformedDocumentExc : public Exc{ public: MalformedDocumentExc(unsigned lineNumber, const std::string& message); }; virtual void onElementStart(const utki::Buf<char> name) = 0; /** * @brief Element end. * @param name - name of the element which has ended. Name is empty if empty element has ended. */ virtual void onElementEnd(const utki::Buf<char> name) = 0; /** * @brief Attributes section end notification. * This callback is called when all attributes of the last element have been parsed. * @param isEmptyElement - indicates weather the element is empty element or not. */ virtual void onAttributesEnd(bool isEmptyElement) = 0; /** * @brief Attribute parsed notification. * This callback may be called after 'onElementStart' notification. It can be called several times, once for each parsed attribute. * @param name - name of the parsed attribute. * @param value - value of the parsed attribute. */ virtual void onAttributeParsed(const utki::Buf<char> name, const utki::Buf<char> value) = 0; /** * @brief Content parsed notification. * This callback may be called after 'onAttributesEnd' notification. * @param str - parsed content. */ virtual void onContentParsed(const utki::Buf<char> str) = 0; /** * @brief feed UTF-8 data to parser. * @param data - data to be fed to parser. */ void feed(const utki::Buf<char> data); /** * @brief feed UTF-8 data to parser. * @param data - data to be fed to parser. */ void feed(const utki::Buf<std::uint8_t> data){ this->feed(utki::wrapBuf(reinterpret_cast<const char*>(&*data.begin()), data.size())); } /** * @brief Parse in string. * @param str - string to parse. */ void feed(const std::string& str); /** * @brief Finalize parsing after all data has been fed. */ void end(); virtual ~Parser()noexcept{} }; }
35.080537
132
0.726229
rantingmong
556b6070e185d3ad180455bf7f53800ef7ee2f7e
165
cpp
C++
319-bulb-switcher/319-bulb-switcher.cpp
shreydevep/DSA
688af414c1fada1b82a4b4e9506747352007c894
[ "MIT" ]
null
null
null
319-bulb-switcher/319-bulb-switcher.cpp
shreydevep/DSA
688af414c1fada1b82a4b4e9506747352007c894
[ "MIT" ]
null
null
null
319-bulb-switcher/319-bulb-switcher.cpp
shreydevep/DSA
688af414c1fada1b82a4b4e9506747352007c894
[ "MIT" ]
null
null
null
class Solution { public: int bulbSwitch(int n) { int cnt = 0; for(int i=1;i*i<=n;++i){ cnt++; } return cnt; } };
15
31
0.406061
shreydevep
556cc6b2535fd02c5d18fa71c1b6111a7f3fc091
6,003
cc
C++
webkit/fileapi/media/picasa/pmp_column_reader_unittest.cc
codenote/chromium-test
0637af0080f7e80bf7d20b29ce94c5edc817f390
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
webkit/fileapi/media/picasa/pmp_column_reader_unittest.cc
codenote/chromium-test
0637af0080f7e80bf7d20b29ce94c5edc817f390
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
webkit/fileapi/media/picasa/pmp_column_reader_unittest.cc
codenote/chromium-test
0637af0080f7e80bf7d20b29ce94c5edc817f390
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-11-04T07:25:45.000Z
2020-11-04T07:25:45.000Z
// 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 <algorithm> #include <vector> #include "base/file_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "webkit/fileapi/media/picasa/pmp_column_reader.h" #include "webkit/fileapi/media/picasa/pmp_constants.h" #include "webkit/fileapi/media/picasa/pmp_test_helper.h" namespace { using picasaimport::PmpColumnReader; using picasaimport::PmpTestHelper; // Overridden version of Read method to make test code templatable. bool DoRead(const PmpColumnReader* reader, uint32 row, std::string* target) { return reader->ReadString(row, target); } bool DoRead(const PmpColumnReader* reader, uint32 row, uint32* target) { return reader->ReadUInt32(row, target); } bool DoRead(const PmpColumnReader* reader, uint32 row, double* target) { return reader->ReadDouble64(row, target); } bool DoRead(const PmpColumnReader* reader, uint32 row, uint8* target) { return reader->ReadUInt8(row, target); } bool DoRead(const PmpColumnReader* reader, uint32 row, uint64* target) { return reader->ReadUInt64(row, target); } // TestValid template<class T> void TestValid(const picasaimport::PmpFieldType field_type, const std::vector<T>& elems) { PmpTestHelper test_helper; ASSERT_TRUE(test_helper.Init()); PmpColumnReader reader; uint32 rows_read = 0xFF; std::vector<uint8> data = PmpTestHelper::MakeHeaderAndBody(field_type, elems.size(), elems); ASSERT_TRUE(test_helper.InitColumnReaderFromBytes(&reader, data, &rows_read)); EXPECT_EQ(elems.size(), rows_read); for (uint32 i = 0; i < elems.size() && i < rows_read; i++) { T target; EXPECT_TRUE(DoRead(&reader, i, &target)); EXPECT_EQ(elems[i], target); } } template<class T> void TestMalformed(const picasaimport::PmpFieldType field_type, const std::vector<T>& elems) { PmpTestHelper test_helper; ASSERT_TRUE(test_helper.Init()); PmpColumnReader reader1, reader2, reader3, reader4; std::vector<uint8> data_too_few_declared_rows = PmpTestHelper::MakeHeaderAndBody(field_type, elems.size()-1, elems); EXPECT_FALSE(test_helper.InitColumnReaderFromBytes( &reader1, data_too_few_declared_rows, NULL)); std::vector<uint8> data_too_many_declared_rows = PmpTestHelper::MakeHeaderAndBody(field_type, elems.size()+1, elems); EXPECT_FALSE(test_helper.InitColumnReaderFromBytes( &reader2, data_too_many_declared_rows, NULL)); std::vector<uint8> data_truncated = PmpTestHelper::MakeHeaderAndBody(field_type, elems.size(), elems); data_truncated.resize(data_truncated.size()-10); EXPECT_FALSE(test_helper.InitColumnReaderFromBytes( &reader3, data_truncated, NULL)); std::vector<uint8> data_padded = PmpTestHelper::MakeHeaderAndBody(field_type, elems.size(), elems); data_padded.resize(data_padded.size()+10); EXPECT_FALSE(test_helper.InitColumnReaderFromBytes( &reader4, data_padded, NULL)); } template<class T> void TestPrimitive(const picasaimport::PmpFieldType field_type) { // Make an ascending vector of the primitive. uint32 n = 100; std::vector<T> data(n, 0); for (uint32 i = 0; i < n; i++) { data[i] = i*3; } TestValid<T>(field_type, data); TestMalformed<T>(field_type, data); } TEST(PmpColumnReaderTest, HeaderParsingAndValidation) { PmpTestHelper test_helper; ASSERT_TRUE(test_helper.Init()); PmpColumnReader reader1, reader2, reader3, reader4, reader5; // Good header. uint32 rows_read = 0xFF; std::vector<uint8> good_header = PmpTestHelper::MakeHeader( picasaimport::PMP_TYPE_STRING, 0); ASSERT_TRUE(test_helper.InitColumnReaderFromBytes( &reader1, good_header, &rows_read)); EXPECT_EQ(0U, rows_read) << "Read non-zero rows from header-only data."; // Botch up elements of the header. std::vector<uint8> bad_magic_byte = PmpTestHelper::MakeHeader( picasaimport::PMP_TYPE_STRING, 0); bad_magic_byte[0] = 0xff; EXPECT_FALSE(test_helper.InitColumnReaderFromBytes( &reader2, bad_magic_byte, NULL)); // Corrupt means the type fields don't agree. std::vector<uint8> corrupt_type = PmpTestHelper::MakeHeader( picasaimport::PMP_TYPE_STRING, 0); corrupt_type[picasaimport::kPmpFieldType1Offset] = 0xff; EXPECT_FALSE(test_helper.InitColumnReaderFromBytes( &reader3, corrupt_type, NULL)); std::vector<uint8> invalid_type = PmpTestHelper::MakeHeader( picasaimport::PMP_TYPE_STRING, 0); invalid_type[picasaimport::kPmpFieldType1Offset] = 0xff; invalid_type[picasaimport::kPmpFieldType2Offset] = 0xff; EXPECT_FALSE(test_helper.InitColumnReaderFromBytes( &reader4, invalid_type, NULL)); std::vector<uint8> incomplete_header = PmpTestHelper::MakeHeader( picasaimport::PMP_TYPE_STRING, 0); incomplete_header.resize(10); EXPECT_FALSE(test_helper.InitColumnReaderFromBytes( &reader5, incomplete_header, NULL)); } TEST(PmpColumnReaderTest, StringParsing) { std::vector<std::string> empty_strings(100, ""); // Test empty strings read okay. TestValid(picasaimport::PMP_TYPE_STRING, empty_strings); std::vector<std::string> mixed_strings; mixed_strings.push_back(""); mixed_strings.push_back("Hello"); mixed_strings.push_back("World"); mixed_strings.push_back(""); mixed_strings.push_back("123123"); mixed_strings.push_back("Q"); mixed_strings.push_back(""); // Test that a mixed set of strings read correctly. TestValid(picasaimport::PMP_TYPE_STRING, mixed_strings); // Test with the data messed up in a variety of ways. TestMalformed(picasaimport::PMP_TYPE_STRING, mixed_strings); } TEST(PmpColumnReaderTest, PrimitiveParsing) { TestPrimitive<uint32>(picasaimport::PMP_TYPE_UINT32); TestPrimitive<double>(picasaimport::PMP_TYPE_DOUBLE64); TestPrimitive<uint8>(picasaimport::PMP_TYPE_UINT8); TestPrimitive<uint64>(picasaimport::PMP_TYPE_UINT64); } } // namespace
33.35
80
0.746294
codenote
5571b7ca836a9d01adde6967d32f705483a08ef8
5,851
cpp
C++
tests/unit_tests/libKitsunemimiCommon/statemachine_test.cpp
kitsudaiki/libKitsunemimiCommon
65c60deddf9fb813035fc2f3251c5ae5c8f7423f
[ "MIT" ]
null
null
null
tests/unit_tests/libKitsunemimiCommon/statemachine_test.cpp
kitsudaiki/libKitsunemimiCommon
65c60deddf9fb813035fc2f3251c5ae5c8f7423f
[ "MIT" ]
49
2020-08-24T18:09:35.000Z
2022-02-13T22:19:39.000Z
tests/unit_tests/libKitsunemimiCommon/statemachine_test.cpp
tobiasanker/libKitsunemimiCommon
d40d1314db0a6d7e04afded09cb4934e01828ac4
[ "MIT" ]
1
2020-08-29T14:30:41.000Z
2020-08-29T14:30:41.000Z
/** * @file statemachine_test.cpp * * @author Tobias Anker <tobias.anker@kitsunemimi.moe> * * @copyright MIT License */ #include "statemachine_test.h" #include <libKitsunemimiCommon/statemachine.h> namespace Kitsunemimi { Statemachine_Test::Statemachine_Test() : Kitsunemimi::CompareTestHelper("Statemachine_Test") { createNewState_test(); addTransition_test(); goToNextState_test(); setInitialChildState_test(); addChildState_test(); getCurrentStateId_test(); isInState_test(); } /** * createNewState_test */ void Statemachine_Test::createNewState_test() { Statemachine statemachine; TEST_EQUAL(statemachine.createNewState(SOURCE_STATE), true); TEST_EQUAL(statemachine.createNewState(SOURCE_STATE), false); } /** * setCurrentState_test */ void Statemachine_Test::setCurrentState_test() { Statemachine statemachine; statemachine.createNewState(SOURCE_STATE); statemachine.createNewState(NEXT_STATE); TEST_EQUAL(statemachine.setCurrentState(SOURCE_STATE), true); TEST_EQUAL(statemachine.setCurrentState(FAIL), false); } /** * addTransition_test */ void Statemachine_Test::addTransition_test() { Statemachine statemachine; statemachine.createNewState(SOURCE_STATE); statemachine.createNewState(NEXT_STATE); TEST_EQUAL(statemachine.addTransition(SOURCE_STATE, GO, NEXT_STATE), true); TEST_EQUAL(statemachine.addTransition(FAIL, GO, NEXT_STATE), false); TEST_EQUAL(statemachine.addTransition(SOURCE_STATE, GO, FAIL), false); TEST_EQUAL(statemachine.addTransition(SOURCE_STATE, GO, NEXT_STATE), false); } /** * goToNextState_test */ void Statemachine_Test::goToNextState_test() { Statemachine statemachine; statemachine.createNewState(SOURCE_STATE); statemachine.createNewState(NEXT_STATE); statemachine.addTransition(SOURCE_STATE, GO, NEXT_STATE); TEST_EQUAL(statemachine.goToNextState(FAIL), false); TEST_EQUAL(statemachine.goToNextState(GO), true); TEST_EQUAL(statemachine.goToNextState(GO), false); } /** * setInitialChildState_test */ void Statemachine_Test::setInitialChildState_test() { Statemachine statemachine; statemachine.createNewState(SOURCE_STATE); statemachine.createNewState(NEXT_STATE); TEST_EQUAL(statemachine.setInitialChildState(SOURCE_STATE, NEXT_STATE), true); TEST_EQUAL(statemachine.setInitialChildState(FAIL, NEXT_STATE), false); TEST_EQUAL(statemachine.setInitialChildState(SOURCE_STATE, FAIL), false); } /** * addChildState_test */ void Statemachine_Test::addChildState_test() { Statemachine statemachine; statemachine.createNewState(SOURCE_STATE); statemachine.createNewState(NEXT_STATE); TEST_EQUAL(statemachine.addChildState(SOURCE_STATE, NEXT_STATE), true); TEST_EQUAL(statemachine.addChildState(FAIL, NEXT_STATE), false); TEST_EQUAL(statemachine.addChildState(SOURCE_STATE, FAIL), false); } /** * getCurrentStateId_test */ void Statemachine_Test::getCurrentStateId_test() { Statemachine statemachine; TEST_EQUAL(statemachine.getCurrentStateId(), 0); // init state statemachine.createNewState(SOURCE_STATE); statemachine.createNewState(NEXT_STATE); statemachine.createNewState(CHILD_STATE); statemachine.createNewState(TARGET_STATE); // build state-machine statemachine.addChildState(NEXT_STATE, CHILD_STATE); statemachine.setInitialChildState(NEXT_STATE, CHILD_STATE); statemachine.addTransition(SOURCE_STATE, GO, NEXT_STATE); statemachine.addTransition(NEXT_STATE, GOGO, TARGET_STATE); TEST_EQUAL(statemachine.getCurrentStateId(), SOURCE_STATE); statemachine.goToNextState(GO); TEST_EQUAL(statemachine.getCurrentStateId(), CHILD_STATE); statemachine.goToNextState(GOGO); TEST_EQUAL(statemachine.getCurrentStateId(), TARGET_STATE); } /** * @brief getCurrentStateName_test */ void Statemachine_Test::getCurrentStateName_test() { Statemachine statemachine; TEST_EQUAL(statemachine.getCurrentStateId(), 0); // init state statemachine.createNewState(SOURCE_STATE, "SOURCE_STATE"); statemachine.createNewState(NEXT_STATE, "NEXT_STATE"); statemachine.createNewState(CHILD_STATE, "CHILD_STATE"); statemachine.createNewState(TARGET_STATE, "TARGET_STATE"); // build state-machine statemachine.addChildState(NEXT_STATE, CHILD_STATE); statemachine.setInitialChildState(NEXT_STATE, CHILD_STATE); statemachine.addTransition(SOURCE_STATE, GO, NEXT_STATE); statemachine.addTransition(NEXT_STATE, GOGO, TARGET_STATE); TEST_EQUAL(statemachine.getCurrentStateId(), SOURCE_STATE); statemachine.goToNextState(GO); TEST_EQUAL(statemachine.getCurrentStateName(), "CHILD_STATE"); statemachine.goToNextState(GOGO); TEST_EQUAL(statemachine.getCurrentStateName(), "TARGET_STATE"); } /** * isInState_test */ void Statemachine_Test::isInState_test() { Statemachine statemachine; TEST_EQUAL(statemachine.getCurrentStateId(), 0); // init state statemachine.createNewState(SOURCE_STATE); statemachine.createNewState(NEXT_STATE); statemachine.createNewState(CHILD_STATE); statemachine.createNewState(TARGET_STATE); // build state-machine statemachine.addChildState(NEXT_STATE, CHILD_STATE); statemachine.setInitialChildState(NEXT_STATE, CHILD_STATE); statemachine.addTransition(SOURCE_STATE, GO, NEXT_STATE); statemachine.addTransition(NEXT_STATE, GOGO, TARGET_STATE); TEST_EQUAL(statemachine.isInState(SOURCE_STATE), true); TEST_EQUAL(statemachine.isInState(FAIL), false); statemachine.goToNextState(GO); TEST_EQUAL(statemachine.isInState(CHILD_STATE), true); TEST_EQUAL(statemachine.isInState(NEXT_STATE), true); TEST_EQUAL(statemachine.isInState(SOURCE_STATE), false); } } // namespace Kitsunemimi
26.595455
82
0.766194
kitsudaiki
5574c5de3bab02af2bbfed26f5cfe2ba8ae4a69e
5,927
cpp
C++
globe/globe_shader.cpp
MarkY-LunarG/LunarGlobe
d32a6145eebc68ad4d7e28bdd4fab88cbdd33545
[ "Apache-2.0" ]
2
2018-06-20T15:19:38.000Z
2018-07-13T15:13:30.000Z
globe/globe_shader.cpp
MarkY-LunarG/LunarGlobe
d32a6145eebc68ad4d7e28bdd4fab88cbdd33545
[ "Apache-2.0" ]
25
2018-07-27T23:02:01.000Z
2019-03-15T17:00:05.000Z
globe/globe_shader.cpp
MarkY-LunarG/LunarGravity
d32a6145eebc68ad4d7e28bdd4fab88cbdd33545
[ "Apache-2.0" ]
null
null
null
// // Project: LunarGlobe // SPDX-License-Identifier: Apache-2.0 // // File: globe/globe_shader.cpp // Copyright(C): 2018-2019; LunarG, Inc. // Author(s): Mark Young <marky@lunarg.com> // #include <cstring> #include <fstream> #include <string> #include <sstream> #include "globe_logger.hpp" #include "globe_event.hpp" #include "globe_submit_manager.hpp" #include "globe_shader.hpp" #include "globe_texture.hpp" #include "globe_resource_manager.hpp" #include "globe_app.hpp" #if defined(VK_USE_PLATFORM_WIN32_KHR) const char directory_symbol = '\\'; #else const char directory_symbol = '/'; #endif static const char main_shader_func_name[] = "main"; GlobeShader* GlobeShader::LoadFromFile(VkDevice vk_device, const std::string& shader_name, const std::string& directory) { GlobeShaderStageInitData shader_data[GLOBE_SHADER_STAGE_ID_NUM_STAGES] = {{}, {}, {}, {}, {}, {}}; for (uint32_t stage = 0; stage < GLOBE_SHADER_STAGE_ID_NUM_STAGES; ++stage) { std::string full_shader_name = directory; full_shader_name += directory_symbol; full_shader_name += shader_name; switch (stage) { case GLOBE_SHADER_STAGE_ID_VERTEX: full_shader_name += "-vs.spv"; break; case GLOBE_SHADER_STAGE_ID_TESSELLATION_CONTROL: full_shader_name += "-cs.spv"; break; case GLOBE_SHADER_STAGE_ID_TESSELLATION_EVALUATION: full_shader_name += "-es.spv"; break; case GLOBE_SHADER_STAGE_ID_GEOMETRY: full_shader_name += "-gs.spv"; break; case GLOBE_SHADER_STAGE_ID_FRAGMENT: full_shader_name += "-fs.spv"; break; case GLOBE_SHADER_STAGE_ID_COMPUTE: full_shader_name += "-cp.spv"; break; default: continue; } std::ifstream* infile = nullptr; std::string line; std::stringstream strstream; size_t shader_spv_size; infile = new std::ifstream(full_shader_name.c_str(), std::ifstream::in | std::ios::binary); if (nullptr == infile || infile->fail()) { continue; } strstream << infile->rdbuf(); infile->close(); delete infile; // Read the file contents shader_spv_size = strstream.str().size(); shader_data[stage].spirv_content.resize((shader_spv_size / sizeof(uint32_t))); memcpy(shader_data[stage].spirv_content.data(), strstream.str().c_str(), shader_spv_size); shader_data[stage].valid = true; } return new GlobeShader(vk_device, shader_name, shader_data); } GlobeShader::GlobeShader(VkDevice vk_device, const std::string& shader_name, const GlobeShaderStageInitData shader_data[GLOBE_SHADER_STAGE_ID_NUM_STAGES]) : _initialized(true), _vk_device(vk_device), _shader_name(shader_name) { GlobeLogger& logger = GlobeLogger::getInstance(); uint32_t num_loaded_shaders = 0; for (uint32_t stage = 0; stage < GLOBE_SHADER_STAGE_ID_NUM_STAGES; ++stage) { if (shader_data[stage].valid) { _shader_data[stage].vk_shader_flag = static_cast<VkShaderStageFlagBits>(1 << stage); VkShaderModuleCreateInfo shader_module_create_info; shader_module_create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; shader_module_create_info.pNext = nullptr; shader_module_create_info.codeSize = shader_data[stage].spirv_content.size() * sizeof(uint32_t); shader_module_create_info.pCode = shader_data[stage].spirv_content.data(); shader_module_create_info.flags = 0; VkResult vk_result = vkCreateShaderModule(vk_device, &shader_module_create_info, NULL, &_shader_data[stage].vk_shader_module); if (VK_SUCCESS != vk_result) { _initialized = false; _shader_data[stage].valid = false; std::string error_msg = "GlobeTexture::Read failed to read shader "; error_msg += shader_name; error_msg += " with error "; error_msg += vk_result; logger.LogError(error_msg); } else { num_loaded_shaders++; _shader_data[stage].valid = true; } } else { _shader_data[stage].valid = false; } } if (num_loaded_shaders == 0 && _initialized) { _initialized = false; } } GlobeShader::~GlobeShader() { if (_initialized) { for (uint32_t stage = 0; stage < GLOBE_SHADER_STAGE_ID_NUM_STAGES; ++stage) { if (_shader_data[stage].valid) { vkDestroyShaderModule(_vk_device, _shader_data[stage].vk_shader_module, nullptr); _shader_data[stage].valid = false; _shader_data[stage].vk_shader_module = VK_NULL_HANDLE; } } _initialized = false; } } bool GlobeShader::GetPipelineShaderStages(std::vector<VkPipelineShaderStageCreateInfo>& pipeline_stages) const { if (!_initialized) { return false; } VkPipelineShaderStageCreateInfo cur_stage_create_info = {}; cur_stage_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; cur_stage_create_info.pName = main_shader_func_name; for (uint32_t stage = 0; stage < GLOBE_SHADER_STAGE_ID_NUM_STAGES; ++stage) { if (_shader_data[stage].valid) { cur_stage_create_info.stage = _shader_data[stage].vk_shader_flag; cur_stage_create_info.module = _shader_data[stage].vk_shader_module; pipeline_stages.push_back(cur_stage_create_info); } } return true; }
40.047297
112
0.62578
MarkY-LunarG
55769a005a140f772cd2ea9a01a12416aa6e3b4f
15,261
cpp
C++
software/imageread/xi_input_image.cpp
yhyoung/CHaiDNN
1877a81e0d1b44773af455b0eab4399636bbc181
[ "Apache-2.0" ]
288
2018-03-23T01:41:40.000Z
2022-03-03T08:52:54.000Z
software/imageread/xi_input_image.cpp
yhyoung/CHaiDNN
1877a81e0d1b44773af455b0eab4399636bbc181
[ "Apache-2.0" ]
171
2018-03-25T11:03:23.000Z
2022-01-29T14:16:59.000Z
software/imageread/xi_input_image.cpp
yhyoung/CHaiDNN
1877a81e0d1b44773af455b0eab4399636bbc181
[ "Apache-2.0" ]
154
2018-03-23T01:31:33.000Z
2022-03-04T14:26:40.000Z
/*---------------------------------------------------- Copyright 2017 Xilinx, 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. ----------------------------------------------------*/ #include "xi_input_image.hpp" void loadMeanTXT(float *ptrRetArray, const char* path, int nElems) { FILE* fp = fopen(path, "r"); if(fp == NULL) { printf("\n** Cannot open mean file (or) No mean file : %s **\n", path); //return NULL; } for(int i = 0; i < nElems; i++) { fscanf(fp, "%f ", ptrRetArray+i); } fclose(fp); } //int loadAndPrepareImage(cv::Mat &frame, short *inptr, float* mean_data, int img_w, int img_h, int img_channel, int resize_h, int resize_w, const char *mean_path, int mean_status) int loadAndPrepareImage(cv::Mat &frame, xChangeLayer *xChangeHostInpLayer) { short *in_ptr = (short *)xChangeHostInpLayer->in_ptrs[2]; short *mean_ptr = (short *)xChangeHostInpLayer->mean; int *params_ptr = (int *)xChangeHostInpLayer->params; int height = params_ptr[0]; int width = params_ptr[1]; int img_channel = params_ptr[5]; int resize_h = xChangeHostInpLayer->resize_h;//params_ptr[0]; //?? how to handle int resize_w = xChangeHostInpLayer->resize_w;//params_ptr[1]; //?? int mean_sub_flag = params_ptr[26]; int scale = 1; int h_off = 0; int w_off = 0; int mean_idx = 0; int fbits_input = xChangeHostInpLayer->qf_format.ip_fbits;//7;//convLayer_precision[0].in_fbits; cv::Mat cv_img[1], cv_cropped_img[1]; if((resize_h != frame.rows) || (resize_w != frame.cols)) { cv::resize(frame, cv_img[0], cv::Size(resize_h, resize_w)); if(resize_h > height) { h_off = (resize_h - height) / 2; w_off = (resize_w - width) / 2; cv::Rect roi(w_off, h_off, height, width); cv_cropped_img[0] = cv_img[0](roi); } else cv_cropped_img[0] = cv_img[0]; } else { frame.copyTo(cv_cropped_img[0]); } #if FILE_WRITE FILE *fp = fopen("input.txt", "w"); #endif //float pixel; uchar pixel; int input_index=0; float float_val; short fxval; for (int h = 0; h < height; ++h) { const uchar* ptr = cv_cropped_img[0].ptr<uchar>(h);//data; int img_index = 0; for (int w = 0; w < width; ++w) { //TODO : Generic for 4 for (int ch = 0; ch < 4; ++ch) { if(ch < img_channel) { //pixel = static_cast<float>(ptr[img_index++]); pixel = ptr[img_index++]; short pixel1 = (short)pixel << fbits_input; if(mean_sub_flag == 1) mean_idx = ch; else mean_idx = (ch * resize_h + h + h_off) * resize_w + w + w_off; //float_val = (pixel - mean_ptr[mean_idx]) * scale; //short ival = (short)float_val; //fxval = ConvertToFP(float_val, ival, fbits_input); fxval = pixel1 - mean_ptr[mean_idx]; } else { float_val = 0; fxval = 0; in_ptr[input_index] = 0; } in_ptr[input_index] = fxval; #if FILE_WRITE float_val = ((float)fxval)/(1 << fbits_input); fprintf(fp,"%f ", float_val); #endif input_index++; }// Channels }// Image width #if FILE_WRITE fprintf(fp,"\n"); #endif }// Image Height #if FILE_WRITE fclose(fp); #endif } // loadAndPrepareImage #if 0 int loadMeanSubtractedImage(cv::Mat &frame, xChangeLayer *xChangeHostInpLayer) { short *in_ptr = (short *)xChangeHostInpLayer->in_ptrs[2]; float *mean_ptr = (float *)xChangeHostInpLayer->mean; float *variance_ptr = (float *)xChangeHostInpLayer->variance; int *params_ptr = (int *)xChangeHostInpLayer->params; int height = params_ptr[0]; int width = params_ptr[1]; int img_channel = params_ptr[5]; int resize_h = xChangeHostInpLayer->resize_h;//params_ptr[0]; //?? how to handle int resize_w = xChangeHostInpLayer->resize_w;//params_ptr[1]; //?? int mean_sub_flag = params_ptr[26]; int scale = 1; int h_off = 0; int w_off = 0; int mean_idx = 0; int fbits_input = xChangeHostInpLayer->qf_format.ip_fbits;//7;//convLayer_precision[0].in_fbits; cv::Mat cv_img[1], cv_cropped_img[1]; if((resize_h != frame.rows) || (resize_w != frame.cols)) { cv::resize(frame, cv_img[0], cv::Size(resize_h, resize_w)); if(resize_h > height) { h_off = (resize_h - height) / 2; w_off = (resize_w - width) / 2; cv::Rect roi(w_off, h_off, height, width); cv_cropped_img[0] = cv_img[0](roi); } else cv_cropped_img[0] = cv_img[0]; } else { frame.copyTo(cv_cropped_img[0]); } #if FILE_WRITE FILE *fp = fopen("input.txt", "w"); #endif //float pixel; uchar pixel; int input_index=0; float float_val; short fxval; for (int h = 0; h < height; ++h) { const uchar* ptr = cv_cropped_img[0].ptr<uchar>(h);//data; int img_index = 0; for (int w = 0; w < width; ++w) { //TODO : Generic for 4 for (int ch = 0; ch < 4; ++ch) { if(ch < img_channel) { //pixel = static_cast<float>(ptr[img_index++]); pixel = ptr[img_index++]; float in_val = pixel/255.0; float mean_val = mean_ptr[mean_idx]; int var_idx = (ch * resize_h + h + h_off) * resize_w + w + w_off; float var_val = variance_ptr[var_idx]; in_val = (in_val - mean_val)/var_val; short ival = (short)float_val; fxval = ConvertToFP(float_val, ival, fbits_input); } else { float_val = 0; fxval = 0; in_ptr[input_index] = 0; } in_ptr[input_index] = fxval; #if FILE_WRITE float_val = ((float)fxval)/(1 << fbits_input); fprintf(fp,"%f ", float_val); #endif input_index++; }// Channels }// Image width #if FILE_WRITE fprintf(fp,"\n"); #endif }// Image Height #if FILE_WRITE fclose(fp); #endif } // loadAndPrepareImage #endif //int loadImage(cv::Mat &frame, char *inptr, float* mean_data, int img_w, int img_h, int img_channel, int resize_h, int resize_w, const char *mean_path, int mean_status) int loadImage(cv::Mat &frame, xChangeLayer *xChangeHostInpLayer) { char *in_ptr = (char *)xChangeHostInpLayer->in_ptrs[2]; float *mean_ptr = (float *)xChangeHostInpLayer->mean; int *params_ptr = (int *)xChangeHostInpLayer->params; int height = params_ptr[0]; int width = params_ptr[1]; int img_channel = params_ptr[5]; int resize_h = xChangeHostInpLayer->resize_h;//params_ptr[0]; //?? how to handle int resize_w = xChangeHostInpLayer->resize_w;//params_ptr[1]; //?? int fbits_input = xChangeHostInpLayer->qf_format.ip_fbits;//7;//convLayer_precision[0].in_fbits; int h_off = 0; int w_off = 0; cv::Mat cv_img[1], cv_cropped_img[1]; if((resize_h != frame.rows) || (resize_w != frame.cols)) { cv::resize(frame, cv_img[0], cv::Size(resize_h, resize_w)); if(resize_h > height) { h_off = (resize_h - height) / 2; w_off = (resize_w - width) / 2; cv::Rect roi(w_off, h_off, height, width); cv_cropped_img[0] = cv_img[0](roi); } else cv_cropped_img[0] = cv_img[0]; } else { frame.copyTo(cv_cropped_img[0]); } #if FILE_WRITE FILE *fp = fopen("input.txt", "w"); #endif char pixel; int input_index=0; for (int h = 0; h < height; ++h) { const uchar* ptr = cv_cropped_img[0].ptr<uchar>(h); int img_index = 0; for (int w = 0; w < width; ++w) { //TODO : Generic for 4 for (int c = 0; c < 4; ++c) { if(c < img_channel) { pixel = static_cast<char>(ptr[img_index++]); } else { pixel = 0; } in_ptr[input_index] = pixel; #if FILE_WRITE fprintf(fp,"%d ", pixel); #endif input_index++; }// Channels }// Image width #if FILE_WRITE fprintf(fp,"\n"); #endif }// Image Height #if FILE_WRITE fclose(fp); #endif } //loadImage int loadImagetoBuffptr1(const char *img_path, unsigned char *buff_ptr, int height, int width, int img_channel, int resize_h, int resize_w) { cv::Mat frame; frame = imread(img_path, 1); if(!frame.data) { std :: cout << "[ERROR] Image read failed - " << img_path << std :: endl; //fprintf(stderr,"image read failed\n"); //return -1; } int h_off = 0; int w_off = 0; cv::Mat cv_img[1], cv_cropped_img[1]; if((resize_h != frame.rows) || (resize_w != frame.cols)) { cv::resize(frame, cv_img[0], cv::Size(resize_h, resize_w)); if(resize_h > height) { h_off = (resize_h - height) / 2; w_off = (resize_w - width) / 2; cv::Rect roi(w_off, h_off, height, width); cv_cropped_img[0] = cv_img[0](roi); } else cv_cropped_img[0] = cv_img[0]; } else { frame.copyTo(cv_cropped_img[0]); } const uchar* ptr = cv_cropped_img[0].ptr<uchar>(0); for (int ind = 0; ind < height*width*img_channel; ind++) { buff_ptr[ind] = ptr[ind]; } } //loadImage int loadImagefromBuffptr(unsigned char *buff_ptr, xChangeLayer *xChangeHostInpLayer) { char *in_ptr = (char *)xChangeHostInpLayer->in_ptrs[2]; int *params_ptr = (int *)xChangeHostInpLayer->params; int height = params_ptr[0]; int width = params_ptr[1]; int img_channel = params_ptr[5]; #if FILE_WRITE FILE *fp = fopen("input.txt", "w"); #endif char pixel; int input_index=0; int img_index = 0; for (int h = 0; h < height; ++h) { for (int w = 0; w < width; ++w) { //TODO : Generic for 4 for (int c = 0; c < 4; ++c) { if(c < img_channel) { pixel = buff_ptr[img_index++]; } else { pixel = 0; } in_ptr[input_index] = pixel; #if FILE_WRITE fprintf(fp,"%d ", pixel); #endif input_index++; }// Channels }// Image width #if FILE_WRITE fprintf(fp,"\n"); #endif }// Image Height #if FILE_WRITE fclose(fp); #endif } //loadImagefromBuffptr int loadDatafromBuffptr(short *buff_ptr, xChangeLayer *xChangeHostInpLayer) { short *in_ptr = (short *)xChangeHostInpLayer->in_ptrs[2]; int *params_ptr = (int *)xChangeHostInpLayer->params; int height = params_ptr[0]; int width = params_ptr[1]; int img_channel = params_ptr[5]; params_ptr[26] = 0; //mean_sub_flag #if FILE_WRITE FILE *fp = fopen("input.txt", "w"); #endif short pixel; int input_index=0; int img_index = 0; for (int h = 0; h < height; ++h) { for (int w = 0; w < width; ++w) { //TODO : Generic for 4 for (int c = 0; c < 4; ++c) { if(c < img_channel) { pixel = buff_ptr[img_index++]; } else { pixel = 0; } in_ptr[input_index] = pixel; #if FILE_WRITE fprintf(fp,"%d ", pixel); #endif input_index++; }// Channels }// Image width #if FILE_WRITE fprintf(fp,"\n"); #endif }// Image Height #if FILE_WRITE fclose(fp); #endif } //loadDatafromBuffptr int loadData(const char *img_data_path, xChangeLayer *xChangeHostInpLayer) { short *in_ptr = (short *)xChangeHostInpLayer->in_ptrs[2]; int *params_ptr = (int *)xChangeHostInpLayer->params; int height = params_ptr[0]; int width = params_ptr[1]; int img_channel = params_ptr[5]; params_ptr[26] = 0; //making mean_sub_flag = 0; FILE* fp_img = fopen(img_data_path, "r"); if(fp_img == NULL) { fprintf(stderr, "\n** Cannot open mean file (or) No mean file : %s **\n", img_data_path); //return NULL; } int size_of_input = height*width*img_channel; short *in_buf = (short *)malloc(size_of_input*sizeof(short)); int fbits_input = xChangeHostInpLayer->qf_format.ip_fbits; float float_val; short fxval; for(int i = 0; i < height*width*img_channel; i++) { fscanf(fp_img, "%f ", &float_val); short ival = (short)float_val; fxval = ConvertToFP(float_val, ival, fbits_input); in_buf[i] = fxval; } fclose(fp_img); #if FILE_WRITE FILE *fp = fopen("input.txt", "w"); #endif short pixel; int input_index=0; int img_index1 = 0; int img_index = 0; for (int h = 0; h < height; ++h) { for (int w = 0; w < width; ++w) { img_index1 = h*width + w; //TODO : Generic for 4 for (int c = 0; c < 4; ++c) { img_index = img_index1 + c*(height*width); if(c < img_channel) { pixel = in_buf[img_index]; } else { pixel = 0; } in_ptr[input_index] = pixel; #if FILE_WRITE fprintf(fp,"%d ", pixel); #endif input_index++; }// Channels }// Image width #if FILE_WRITE fprintf(fp,"\n"); #endif }// Image Height #if FILE_WRITE fclose(fp); #endif } //loadData int loadDatatoBuffptr1(const char *img_data_path, float *inp_buff, int height, int width, int img_channel) { FILE* fp_img = fopen(img_data_path, "r"); if(fp_img == NULL) { fprintf(stderr, "\n** Cannot open mean file (or) No mean file : %s **\n", img_data_path); //return NULL; } float float_val; for(int i = 0; i < height*width*img_channel; i++) { fscanf(fp_img, "%f ", &float_val); inp_buff[i] = float_val; } fclose(fp_img); } //loadDatatoBuffptr int loadDatafromBuffptr1(short *inp_buff, xChangeLayer *xChangeHostInpLayer) { short *in_ptr = (short *)xChangeHostInpLayer->in_ptrs[2]; int *params_ptr = (int *)xChangeHostInpLayer->params; int height = params_ptr[0]; int width = params_ptr[1]; int img_channel = params_ptr[5]; params_ptr[26] = 0; //making mean_sub_flag = 0; int size_of_input = height*width*img_channel; #if FILE_WRITE FILE *fp = fopen("input.txt", "w"); #endif short pixel; int input_index=0; int img_index1 = 0; int img_index = 0; for (int h = 0; h < height; ++h) { for (int w = 0; w < width; ++w) { img_index1 = h*width + w; //TODO : Generic for 4 for (int c = 0; c < 4; ++c) { img_index = img_index1 + c*(height*width); if(c < img_channel) { pixel = inp_buff[img_index]; } else { pixel = 0; } in_ptr[input_index] = pixel; #if FILE_WRITE fprintf(fp,"%d ", pixel); #endif input_index++; }// Channels }// Image width #if FILE_WRITE fprintf(fp,"\n"); #endif }// Image Height #if FILE_WRITE fclose(fp); #endif } //loadDatafromBuffptr void inputImageRead(const char *img_path, xChangeLayer *xChangeHostInpLayer) //void inputImageRead(FILE **file_list, xChangeLayer *xChangeHostInpLayer) { #if EN_IO_PRINT cout<< "inputImageRead : " <<endl; #endif //char img_path[500]; //fscanf(*file_list, "%s", img_path); int num_mean_values; //read from params int status; //xChangeLayer *xChangeHostInpLayer = &lay_obj[imgId][layerId];// = &xChangeHostLayers[0]; //xChangeHostInpLayer.in_ptrs[0] = (char*)create_sdsalloc_mem(mem_size); //xChangeHostInpLayer.params = (char*)create_sdsalloc_mem(params_mem_size); int *scalar_conv_args = (int *)xChangeHostInpLayer->params; int mean_sub_flag = scalar_conv_args[26]; cv::Mat in_frame, out_frame; out_frame = imread(img_path, 1); if(!out_frame.data) { std :: cout << "[ERROR] Image read failed - " << img_path << std :: endl; //fprintf(stderr,"image read failed\n"); //return -1; } if(mean_sub_flag) { status = loadImage(out_frame, xChangeHostInpLayer); } else { status = loadAndPrepareImage(out_frame, xChangeHostInpLayer); } #if EN_IO_PRINT cout<< "inputImageRead done: " <<endl; #endif }
22.085384
180
0.636393
yhyoung
557844a4a767c4a1fe9f3add0d55c0b5b9079a2f
3,571
hh
C++
include/sot/tools/kinematic-planner.hh
Rascof/sot-tools
e529611574d12fc2239bd0cfcd83749243de8bc6
[ "BSD-2-Clause" ]
null
null
null
include/sot/tools/kinematic-planner.hh
Rascof/sot-tools
e529611574d12fc2239bd0cfcd83749243de8bc6
[ "BSD-2-Clause" ]
11
2017-02-01T19:26:29.000Z
2021-11-03T08:25:35.000Z
include/sot/tools/kinematic-planner.hh
Rascof/sot-tools
e529611574d12fc2239bd0cfcd83749243de8bc6
[ "BSD-2-Clause" ]
12
2015-01-21T08:21:23.000Z
2020-11-27T14:35:29.000Z
// // Copyright (C) 2016 LAAS-CNRS // // Author: Rohan Budhiraja // #ifndef SOT_TOOLS_KINEMATIC_PLANNER_HH #define SOT_TOOLS_KINEMATIC_PLANNER_HH /* STD */ #include <string> #include <sstream> #include <list> #include <complex> /* dynamic-graph */ #include <dynamic-graph/entity.h> #include <dynamic-graph/factory.h> #include <dynamic-graph/signal-base.h> #include <dynamic-graph/signal-ptr.h> #include <dynamic-graph/signal-time-dependent.h> #include <dynamic-graph/linear-algebra.h> #include <sot/core/debug.hh> /*Eigen*/ #include <Eigen/StdVector> #include <unsupported/Eigen/FFT> #include <unsupported/Eigen/Splines> #include <unsupported/Eigen/MatrixFunctions> /* BOOST */ //#include <boost/filesystem.hpp> namespace dynamicgraph { namespace sot { namespace tools { using dynamicgraph::Entity; class KinematicPlanner : public Entity { public: DYNAMIC_GRAPH_ENTITY_DECL(); typedef std::vector<Eigen::ArrayXd, Eigen::aligned_allocator<Eigen::ArrayXd> > stdVectorofArrayXd; typedef std::vector<Eigen::ArrayXXd, Eigen::aligned_allocator<Eigen::ArrayXXd> > stdVectorofArrayXXd; /*-----SIGNALS--------*/ typedef int Dummy; /* dynamicgraph::SignalPtr<double,int> distToDrawerSIN; dynamicgraph::SignalPtr<double,int> objectPositionInDrawerSIN; dynamicgraph::SignalTimeDependent<Dummy,int> trajectoryReadySINTERN; dynamicgraph::SignalTimeDependent<dynamicgraph::Matrix, int> upperBodyJointPositionSOUT; dynamicgraph::SignalTimeDependent<dynamicgraph::Matrix, int> upperBodyJointVelocitySOUT; dynamicgraph::SignalTimeDependent<dynamicgraph::Matrix, int> freeFlyerVelocitySOUT; */ /* --- CONSTRUCTOR --- */ KinematicPlanner(const std::string& name); virtual ~KinematicPlanner(void); // Sources Eigen::ArrayXd npSource; Eigen::ArrayXXd pSource1; Eigen::ArrayXXd pSource2; stdVectorofArrayXXd pSourceDelayed1; stdVectorofArrayXXd pSourceDelayed2; // Delays Eigen::ArrayXXd pDelay1; Eigen::ArrayXXd pDelay2; // Non Periodic Weights Eigen::ArrayXXd wNonPeriodic; // Eigen::Array<double, 480,4> // Periodic Weights stdVectorofArrayXXd wPeriodic1; stdVectorofArrayXXd wPeriodic2; // Mean joint angles Eigen::ArrayXXd mJointAngle; // Number of Trajectories Created // int nTrajectories; //30 int nJoints; // 16 int nGaitCycles; // 4 int nTimeSteps; // 160 int nSources1; // 5 int nSources2; // 4 /*! @} */ std::list<dynamicgraph::SignalBase<int>*> genericSignalRefs; // Load Motion Capture outputs template <typename Derived> void read2DArray(std::string& fileName, Eigen::DenseBase<Derived>& outArr); void setParams(const double& _distanceToDrawer, const double& _objectPositionInDrawer, const std::string& dir); void loadSourceDelays(const std::string& dir); void loadTrainingParams(const std::string& dir, dynamicgraph::Matrix& q, dynamicgraph::Matrix& beta3, Eigen::ArrayXd& mwwn, double& sigma2, int& N, int& K); dynamicgraph::Vector createSubGoals(double D, double P); void delaySources(); void blending(); void smoothEnds(Eigen::Ref<Eigen::ArrayXd> tr); void bSplineInterpolate(Eigen::ArrayXXd& tr, int factor); int& runKinematicPlanner(int& dummy, int time); void goalAdaption(dynamicgraph::Vector& goals, const std::string&); void savitzkyGolayFilter(Eigen::Ref<Eigen::ArrayXXd> allJointTraj, int polyOrder, int frameSize); bool parametersSet; }; // class KinematicPlanner } // namespace tools } // namespace sot } // namespace dynamicgraph #endif // SOT_TOOLS_KINEMATIC_PLANNER_HH
30.262712
113
0.738169
Rascof
5578bfbd80af35e8b15a9510717a5a0cce4ba4cf
101
cc
C++
example/memcache/Item.cc
Conzxy/kanon
3440b0966153a0b8469e90b2a52df317aa4fe723
[ "MIT" ]
null
null
null
example/memcache/Item.cc
Conzxy/kanon
3440b0966153a0b8469e90b2a52df317aa4fe723
[ "MIT" ]
null
null
null
example/memcache/Item.cc
Conzxy/kanon
3440b0966153a0b8469e90b2a52df317aa4fe723
[ "MIT" ]
null
null
null
#include "Item.h" namespace memcache { std::atomic<u64> Item::s_cas_(0); } // namespace memcache
12.625
34
0.683168
Conzxy
5579482f0ec6190139c6f85f8691a06d2de5ff42
863
hpp
C++
plugins/opengl/include/sge/opengl/xrandr/set_resolution.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
plugins/opengl/include/sge/opengl/xrandr/set_resolution.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
plugins/opengl/include/sge/opengl/xrandr/set_resolution.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_OPENGL_XRANDR_SET_RESOLUTION_HPP_INCLUDED #define SGE_OPENGL_XRANDR_SET_RESOLUTION_HPP_INCLUDED #include <sge/opengl/xrandr/configuration_fwd.hpp> #include <sge/opengl/xrandr/mode_index.hpp> #include <sge/opengl/xrandr/optional_refresh_rate_fwd.hpp> #include <sge/opengl/xrandr/rotation.hpp> #include <awl/backends/x11/window/base_fwd.hpp> namespace sge::opengl::xrandr { void set_resolution( awl::backends::x11::window::base const &, sge::opengl::xrandr::configuration const &, sge::opengl::xrandr::mode_index, sge::opengl::xrandr::rotation, sge::opengl::xrandr::optional_refresh_rate const &); } #endif
30.821429
61
0.74971
cpreh
557a792be377471c08aeae8d211267379bea0f15
3,257
hpp
C++
tuo_units/TUO_Reg_Units_OPF_F.hpp
bc036/A3-TUO-Units
157f4f45317a19cf90d3f28b017b43de737f5bb3
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
tuo_units/TUO_Reg_Units_OPF_F.hpp
bc036/A3-TUO-Units
157f4f45317a19cf90d3f28b017b43de737f5bb3
[ "Naumen", "Condor-1.1", "MS-PL" ]
44
2019-09-24T17:11:29.000Z
2021-08-14T18:37:15.000Z
tuo_units/TUO_Reg_Units_OPF_F.hpp
bc036/A3-TUO-Units
157f4f45317a19cf90d3f28b017b43de737f5bb3
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
class O_T_TUO_Reg_Base_F:B_T_TUO_Reg_base_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_T_OPF_F"; }; class O_A_TUO_Reg_base_F:B_A_TUO_Reg_base_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_A_OPF_F"; }; class O_W_TUO_Reg_Base_F:B_W_TUO_Reg_base_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_W_OPF_F"; }; class O_T_TUO_Rifleman_F:B_T_TUO_Rifleman_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_T_OPF_F"; }; class O_A_TUO_Rifleman_F:B_A_TUO_Rifleman_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_A_OPF_F"; }; class O_W_TUO_Rifleman_F:B_W_TUO_Rifleman_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_W_OPF_F"; }; class O_T_TUO_Rifleman_AT_F:B_T_TUO_Rifleman_AT_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_T_OPF_F"; }; class O_A_TUO_Rifleman_AT_F:B_A_TUO_Rifleman_AT_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_A_OPF_F"; }; class O_W_TUO_Rifleman_AT_F:B_W_TUO_Rifleman_AT_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_W_OPF_F"; }; class O_T_TUO_Mark_F:B_T_TUO_Mark_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_T_OPF_F"; }; class O_A_TUO_Mark_F:B_A_TUO_Mark_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_A_OPF_F"; }; class O_W_TUO_Mark_F:B_W_TUO_Mark_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_W_OPF_F"; }; class O_T_TUO_Engineer_F:B_T_TUO_Engineer_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_T_OPF_F"; }; class O_A_TUO_Engineer_F:B_A_TUO_Engineer_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_A_OPF_F"; }; class O_W_TUO_Engineer_F:B_W_TUO_Engineer_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_W_OPF_F"; }; class O_T_TUO_Medic_F:B_T_TUO_Medic_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_T_OPF_F"; }; class O_A_TUO_Medic_F:B_A_TUO_Medic_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_A_OPF_F"; }; class O_W_TUO_Medic_F:B_W_TUO_Medic_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_W_OPF_F"; }; class O_T_TUO_Leader_F:B_T_TUO_Leader_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_T_OPF_F"; }; class O_A_TUO_Leader_F:B_A_TUO_Leader_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_A_OPF_F"; }; class O_W_TUO_Leader_F:B_W_TUO_Leader_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_W_OPF_F"; }; class O_T_TUO_Autorifleman_F:B_T_TUO_Autorifleman_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_T_OPF_F"; }; class O_A_TUO_Autorifleman_F:B_A_TUO_Autorifleman_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_A_OPF_F"; }; class O_W_TUO_Autorifleman_F:B_W_TUO_Autorifleman_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_W_OPF_F"; }; class O_T_TUO_Heavy_Gunner_F:B_T_TUO_Heavy_Gunner_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_T_OPF_F"; }; class O_A_TUO_Heavy_Gunner_F:B_A_TUO_Heavy_Gunner_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_A_OPF_F"; }; class O_W_TUO_Heavy_Gunner_F:B_W_TUO_Heavy_Gunner_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_W_OPF_F"; }; class O_T_TUO_Grenadier_F:B_T_TUO_Grenadier_F { side=2; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_T_IND_F"; }; class O_A_TUO_Grenadier_F:B_A_TUO_Grenadier_F { side=2; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_A_IND_F"; }; class O_W_TUO_Grenadier_F:B_W_TUO_Grenadier_F { side=2; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_W_IND_F"; };
21.713333
51
0.760823
bc036
557b88c28caf8c1a8e0b49aea2e46c1ae215bf71
1,675
cpp
C++
test/cli/minions_coverage_test.cpp
seqan/minions
58339454f992264b73197f1bf8c94e8f4b1c3c2f
[ "BSD-3-Clause" ]
null
null
null
test/cli/minions_coverage_test.cpp
seqan/minions
58339454f992264b73197f1bf8c94e8f4b1c3c2f
[ "BSD-3-Clause" ]
16
2021-09-29T13:00:06.000Z
2022-03-07T13:34:16.000Z
test/cli/minions_coverage_test.cpp
MitraDarja/Comparison
58339454f992264b73197f1bf8c94e8f4b1c3c2f
[ "BSD-3-Clause" ]
1
2022-01-09T22:36:43.000Z
2022-01-09T22:36:43.000Z
#include "cli_test.hpp" TEST_F(cli_test, no_options) { cli_test_result result = execute_app("minions coverage"); std::string expected { "minions-coverage\n" "================\n" " Try -h or --help for more information.\n" }; EXPECT_EQ(result.exit_code, 0); EXPECT_EQ(result.out, expected); EXPECT_EQ(result.err, std::string{}); } TEST_F(cli_test, minimiser) { cli_test_result result = execute_app("minions coverage --method minimiser -k 19 -w 19 ", data("example1.fasta")); EXPECT_EQ(result.exit_code, 0); EXPECT_EQ(result.out, std::string{}); EXPECT_EQ(result.err, std::string{}); } TEST_F(cli_test, gapped_minimiser) { cli_test_result result = execute_app("minions coverage --method minimiser -k 19 -w 19 --shape 524223", data("example1.fasta")); EXPECT_EQ(result.exit_code, 0); EXPECT_EQ(result.out, std::string{}); EXPECT_EQ(result.err, std::string{}); } TEST_F(cli_test, modmer) { cli_test_result result = execute_app("minions coverage --method modmer -k 19 -w 2 ", data("example1.fasta")); EXPECT_EQ(result.exit_code, 0); EXPECT_EQ(result.out, std::string{}); EXPECT_EQ(result.err, std::string{}); } TEST_F(cli_test, wrong_method) { cli_test_result result = execute_app("minions coverage --method submer -k 19", data("example1.fasta")); std::string expected { "Error. Incorrect command line input for coverage. Validation failed " "for option --method: Value submer is not one of [kmer,minimiser,modmer].\n" }; EXPECT_EQ(result.exit_code, 0); EXPECT_EQ(result.err, expected); EXPECT_EQ(result.out, std::string{}); }
31.018519
131
0.665672
seqan
5353d7e9a41855906455824ecb59c9d4b6db1312
2,145
cpp
C++
Project3/assign3.cpp
jehalladay/Theory-of-Algorithms
fa35ed1a3c40e45a3b97c93a44e96532b91fb1b5
[ "MIT" ]
null
null
null
Project3/assign3.cpp
jehalladay/Theory-of-Algorithms
fa35ed1a3c40e45a3b97c93a44e96532b91fb1b5
[ "MIT" ]
null
null
null
Project3/assign3.cpp
jehalladay/Theory-of-Algorithms
fa35ed1a3c40e45a3b97c93a44e96532b91fb1b5
[ "MIT" ]
null
null
null
/* Project 3 - Hashtable and Heapsort James Halladay Theory of Algorithms 10/9/2021 This program will render a program that expect a command line argument being an input text file and an output text file name. The program will read the data in the input file (strings) and write to the output file the sorted contents of the input We will scan the file and store the words in the hashtable while recording their frequencies. After the file is finished, we will input the words and their frequencies into the heap. The heap is a maxheap, so once the heap is full, the we will remove the root node until it is empty into a vector. The input file is sorted through this process and then is written to the output file specified by the second command line argument. */ #include <iostream> #include <string> #include <fstream> #include "hash.h" #include "heap.h" #include "utility.h" using namespace std; const string MODIFY_DATE = "10-24-21"; const string FILE_NAME = "A Scandal In Bohemia.txt"; void arg_check(int argc, char* argv[]); void maintest(); void write_file(string file_name, vector<element>& sorted); int main(int argc, char* argv[]) { arg_check(argc, argv); maintest(); Hashtable ht = read_file(argv[1], .65); vector<element> sorted = Heap().heap_sort(ht); write_file(argv[2], sorted); return 0; } void arg_check(int argc, char* argv[]) { if (argc < 2 || argc > 3) { cout << "Incorrect number of arguments" << endl; throw; } cout << "argc: " << argc << endl; for(int i = 0; i < argc; i++) { cout << "argv[" << i << "]: " << argv[i] << endl; } } void write_file(string file_name, vector<element>& sorted) { ofstream outfile; outfile.open(file_name); for(int i = 0; i < (int)sorted.size(); i++) { outfile << sorted[i].entry << "\t\t" << sorted[i].frequency << endl; } outfile.close(); } void maintest() { cout << endl << "Hello, World! from inside assign3.cpp" << "\tLast Modified: " << MODIFY_DATE << endl; }
26.8125
107
0.634499
jehalladay
5355b6e7c24675c87cabae20b628a3dd5351c293
479
cpp
C++
linux/cmd.cpp
Universefei/f8snippet
408ae26cf666861e3aa0f58fbdd89a93b3fb1a4a
[ "Apache-2.0" ]
null
null
null
linux/cmd.cpp
Universefei/f8snippet
408ae26cf666861e3aa0f58fbdd89a93b3fb1a4a
[ "Apache-2.0" ]
null
null
null
linux/cmd.cpp
Universefei/f8snippet
408ae26cf666861e3aa0f58fbdd89a93b3fb1a4a
[ "Apache-2.0" ]
null
null
null
string exe_cmd(const string& cmd) { int t_ret = 0; string t_result = ""; t_result.resize(1024); FILE* fp = popen(cmd.c_str(), "r"); fgets(&t_result[0], t_result.capacity(), fp); pclose(fp); return t_result; } string get_md5(const string& file) { char buf[128] = {'\0'}; string cmd = "md5sum "; cmd.append(file); cmd.append(" | awk '{printf $1}'"); FILE* fp = popen(cmd.c_str(), "r"); fgets(buf, sizeof(buf), fp); pclose(fp); return string(buf); }
21.772727
47
0.605428
Universefei
535bd9c0458dc7dabf8371038d09169b5407e1f7
456
hpp
C++
net/include/HttpSecWebSocketKey.hpp
wangsun1983/Obotcha
2464e53599305703f5150df72bf73579a39d8ef4
[ "MIT" ]
27
2019-04-27T00:51:22.000Z
2022-03-30T04:05:44.000Z
net/include/HttpSecWebSocketKey.hpp
wangsun1983/Obotcha
2464e53599305703f5150df72bf73579a39d8ef4
[ "MIT" ]
9
2020-05-03T12:17:50.000Z
2021-10-15T02:18:47.000Z
net/include/HttpSecWebSocketKey.hpp
wangsun1983/Obotcha
2464e53599305703f5150df72bf73579a39d8ef4
[ "MIT" ]
1
2019-04-16T01:45:36.000Z
2019-04-16T01:45:36.000Z
#ifndef __OBOTCHA_HTTP_SEC_WEB_SOCKET_KEY_HPP__ #define __OBOTCHA_HTTP_SEC_WEB_SOCKET_KEY_HPP__ #include "Object.hpp" #include "StrongPointer.hpp" #include "String.hpp" #include "ArrayList.hpp" namespace obotcha { DECLARE_CLASS(HttpSecWebSocketKey) { public: _HttpSecWebSocketKey(); _HttpSecWebSocketKey(String); void import(String); String get(); void set(String); String toString(); private: String key; }; } #endif
14.709677
47
0.739035
wangsun1983
53660adb81cba86ca028a0122741d62a476cbbb9
1,342
cpp
C++
C++/HeapSort.cpp
patres270/AlgoLib
8b697e1e9348c559dcabdb6665e1031264c1032a
[ "MIT" ]
222
2016-07-17T17:28:19.000Z
2022-03-27T02:57:39.000Z
C++/HeapSort.cpp
patres270/AlgoLib
8b697e1e9348c559dcabdb6665e1031264c1032a
[ "MIT" ]
197
2016-10-24T16:47:42.000Z
2021-08-29T08:12:31.000Z
C++/HeapSort.cpp
patres270/AlgoLib
8b697e1e9348c559dcabdb6665e1031264c1032a
[ "MIT" ]
206
2016-05-18T17:08:14.000Z
2022-01-16T04:08:47.000Z
#include<bits/stdc++.h> using namespace std; #define rep(i,a,b,c) for(i=a;i<b;i+=c) #define repp(i,a,b,c) for(i=a;i>b;i+=c) //--------------------------------------Heapify void max_heapify(int *a, int i, int n) { int l=2*i+1; int r=2*i+2; int largest=0; if(l<=n and a[l]>a[i]) largest=l; else largest=i; if(r<=n and a[r]>a[largest]) largest=r; if(largest!=i) { swap(a[largest],a[i]); max_heapify(a,largest,n); } } //---------------------------------Build max Heap void build_maxheap(int *a, int n) { int i; repp(i,n/2,-1,-1) { max_heapify(a,i,n); } } //-----------------------------------HeapSort void heapsort(int *a, int n) { int i; build_maxheap(a,n); repp(i,n,-1,-1) { swap(a[0],a[i]); n--; max_heapify(a,0,n); } } int main() { int n, i, x; cout<<"Enter no of elements of array\n"; cin>>n; //Dynamic Memory Allocation int *dynamic; dynamic = new int[n]; //Input Of Elements cout<<"Enter the elements of array :\n"; rep(i,0,n,1) cin>>dynamic[i]; heapsort(dynamic,n-1); //Sorted Array using heap sort cout<< "Sorted Sequence is : " ; rep(i,0,n,1) cout<< dynamic[i]<<"\t"; delete []dynamic; }
19.449275
49
0.467213
patres270
5368e5f9756762633f750c5c0ff8ef6f9882060e
1,151
cpp
C++
c++/zigzag_conversion.cpp
SongZhao/leetcode
4a2b4f554e91f6a2167b336f8a69b80fa9f3f920
[ "Apache-2.0" ]
null
null
null
c++/zigzag_conversion.cpp
SongZhao/leetcode
4a2b4f554e91f6a2167b336f8a69b80fa9f3f920
[ "Apache-2.0" ]
null
null
null
c++/zigzag_conversion.cpp
SongZhao/leetcode
4a2b4f554e91f6a2167b336f8a69b80fa9f3f920
[ "Apache-2.0" ]
null
null
null
/* The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows: string convert(string text, int nRows); convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". */ /* * */ #include "helper.h" class Solution { public: string convert(string s, int nRows) { if (nRows <= 1) { return s; } vector<string> strs(nRows); string res; int row = 0, step = 1; for (char c: s) { strs[row].push_back(c); if (row == 0) { step = 1; } else if (row == nRows - 1) { step = -1; } row += step; } for (int j = 0; j < nRows; ++j) { res.append(strs[j]); } return res; } }; int main() { Solution s; cout << s.convert("PAYPALISHIRING", 3) << endl; return 0; }
20.192982
120
0.529105
SongZhao
536b253989e4c9c91ccb838702940a731c4b1c28
4,577
hpp
C++
include/foonathan/lex/token.hpp
foonathan/lex
2d0177d453f8c36afc78392065248de0b48c1e7d
[ "BSL-1.0" ]
142
2018-10-16T16:41:09.000Z
2021-12-13T20:04:50.000Z
include/foonathan/lex/token.hpp
foonathan/lex
2d0177d453f8c36afc78392065248de0b48c1e7d
[ "BSL-1.0" ]
null
null
null
include/foonathan/lex/token.hpp
foonathan/lex
2d0177d453f8c36afc78392065248de0b48c1e7d
[ "BSL-1.0" ]
10
2018-10-16T19:08:36.000Z
2021-03-19T14:36:29.000Z
// Copyright (C) 2018-2019 Jonathan Müller <jonathanmueller.dev@gmail.com> // This file is subject to the license terms in the LICENSE file // found in the top-level directory of this distribution. #ifndef FOONATHAN_LEX_TOKEN_HPP_INCLUDED #define FOONATHAN_LEX_TOKEN_HPP_INCLUDED #include <foonathan/lex/spelling.hpp> #include <foonathan/lex/token_kind.hpp> namespace foonathan { namespace lex { template <class TokenSpec> class tokenizer; template <class TokenSpec> class token { public: constexpr token() noexcept : ptr_(nullptr), size_(0), kind_() {} constexpr token_kind<TokenSpec> kind() const noexcept { return kind_; } explicit constexpr operator bool() const noexcept { return !!kind(); } template <class Token> constexpr bool is(Token token = {}) const noexcept { return kind_.is(token); } template <template <typename> class Category> constexpr bool is_category() const noexcept { return kind_.template is_category<Category>(); } constexpr const char* name() const noexcept { return kind_.name(); } constexpr token_spelling spelling() const noexcept { return token_spelling(ptr_, size_); } constexpr std::size_t offset(const tokenizer<TokenSpec>& tokenizer) const noexcept { return static_cast<std::size_t>(ptr_ - tokenizer.begin_ptr()); } private: explicit constexpr token(token_kind<TokenSpec> kind, const char* ptr, std::size_t size) noexcept : ptr_(ptr), size_(size), kind_(kind) {} const char* ptr_; std::size_t size_; token_kind<TokenSpec> kind_; friend tokenizer<TokenSpec>; }; template <class Token, class Payload = void> class static_token; template <class Token> class static_token<Token, void> { static_assert(is_token<Token>::value, "must be a token"); public: template <class TokenSpec> explicit constexpr static_token(const token<TokenSpec>& token) : spelling_(token.spelling()) { FOONATHAN_LEX_PRECONDITION(token.is(Token{}), "token kind must match"); } constexpr operator Token() const noexcept { return Token{}; } template <class TokenSpec> constexpr token_kind<TokenSpec> kind() const noexcept { return token_kind<TokenSpec>::template of<Token>(); } explicit constexpr operator bool() const noexcept { return std::is_same<Token, error_token>::value; } template <class Other> constexpr bool is(Other = {}) const noexcept { return std::is_same<Token, Other>::value; } template <template <typename> class Category> constexpr bool is_category() const noexcept { return Category<Token>::value; } constexpr const char* name() const noexcept { return Token::name; } constexpr token_spelling spelling() const noexcept { return spelling_; } template <class TokenSpec> constexpr std::size_t offset(const tokenizer<TokenSpec>& tokenizer) const noexcept { return static_cast<std::size_t>(spelling_.data() - tokenizer.begin_ptr()); } private: token_spelling spelling_; }; template <class Token, class Payload> class static_token : public static_token<Token, void> { public: template <class TokenSpec> explicit constexpr static_token(const token<TokenSpec>& token, Payload payload) : static_token<Token, void>(token), payload_(static_cast<Payload&&>(payload)) {} constexpr Payload& value() & noexcept { return payload_; } constexpr const Payload& value() const& noexcept { return payload_; } constexpr Payload&& value() && noexcept { return static_cast<Payload&&>(payload_); } constexpr const Payload&& value() const&& noexcept { return static_cast<const Payload&&>(payload_); } private: Payload payload_; }; } // namespace lex } // namespace foonathan #endif // FOONATHAN_LEX_TOKEN_HPP_INCLUDED
26.923529
100
0.59078
foonathan
5378c2f15156a210d5184f7c0bf57ad0c60a2e74
195
hpp
C++
include/elasty/algorithm-type.hpp
yuki-koyama/elasty
67c7a15c1483fe1979b8b3af64be4f34e110c760
[ "MIT" ]
176
2019-04-27T00:45:37.000Z
2022-03-26T03:15:45.000Z
include/elasty/algorithm-type.hpp
yuki-koyama/elasty
67c7a15c1483fe1979b8b3af64be4f34e110c760
[ "MIT" ]
28
2019-04-27T00:00:49.000Z
2021-08-30T07:01:12.000Z
include/elasty/algorithm-type.hpp
yuki-koyama/elasty
67c7a15c1483fe1979b8b3af64be4f34e110c760
[ "MIT" ]
15
2019-04-27T01:09:58.000Z
2022-02-09T13:30:41.000Z
#ifndef ELASTY_ALGORITHM_TYPE_HPP #define ELASTY_ALGORITHM_TYPE_HPP namespace elasty { enum class AlgorithmType { Pbd, Xpbd }; } #endif // ELASTY_ALGORITHM_TYPE_HPP
13.928571
35
0.697436
yuki-koyama
537be64c75a2acd632f61bb9e80b6d443b077e80
2,219
cpp
C++
Filesystem/Problem36/main.cpp
vegemil/ModernCppChallengeStudy
52c2bb22c76ae3f3a883ae479cd70ac27513e78d
[ "MIT" ]
null
null
null
Filesystem/Problem36/main.cpp
vegemil/ModernCppChallengeStudy
52c2bb22c76ae3f3a883ae479cd70ac27513e78d
[ "MIT" ]
null
null
null
Filesystem/Problem36/main.cpp
vegemil/ModernCppChallengeStudy
52c2bb22c76ae3f3a883ae479cd70ac27513e78d
[ "MIT" ]
null
null
null
// 36. Deleting files older than a given date // Write a function that, given the path to a directory and a duration, deletes all // the entries (files or subdirectories) older than the specified duration, in a // recursive manner. The duration can represent anything, such as days, hours, // minutes, seconds, and so on, or a combination of that, such as one hour and // twenty minutes. If the specified directory is itself older than the given duration, // it should be deleted entirely. // 36. 특정 날짜보다 오래된 파일들을 지우기 // 어떤 디렉토리에 대한 경로와 기간을 받아서, 정해진 기간보다 오래된 모든 것(파일들 또는 서브 // 디렉토리들)을 재귀적으로 삭제하는 함수를 작성하라. 기간은 일, 시간, 분, 초, 그외 등등, 또는 // 이 것 들의 조합인 한시간 그리고 이십분과 같이 어떤 것으로도 나타낼 수 있다. 만약에 특정 디렉 // 토리가 정해진 기간보다 오래 됐으면, 이 디렉토리 전체가 지워져야 한다 #include "gsl/gsl" // create `main` function for catch #define CATCH_CONFIG_MAIN #include "catch2/catch.hpp" // Redirect CMake's #define to C++ constexpr string constexpr auto TestName = PROJECT_NAME_STRING; #include <experimental/filesystem> #include <ctime> bool checkModifyDate(std::tm* time, const std::experimental::filesystem::path & p) { auto fileTime = std::experimental::filesystem::last_write_time(p); std::time_t cftime = decltype(fileTime)::clock::to_time_t(fileTime); std::time_t mtime = std::mktime(time); // time_t 형식으로 변경. std::cout << p.generic_string() << " "; if (cftime < mtime) { if (std::experimental::filesystem::remove(p) == false) { std::cout << "ERROR REMOVE FILE!" << std::endl; } else { std::cout << "REMOVE FILE SUCCESS!" << std::endl; } return false; } else { std::cout << "FILE SURVIVE!" << std::endl; return true; } } void checkDirectory(std::tm* time, const std::experimental::filesystem::path & p) { if (std::experimental::filesystem::is_directory(p)) { if (false == checkModifyDate(time, p)) { return; } } if (true == checkModifyDate(time, p)) { for (auto& p : std::experimental::filesystem::recursive_directory_iterator(p)) { checkModifyDate(time, p); } } } TEST_CASE("Deleting files older than a given date") { std::istringstream s("2018-10-01"); std::tm x = { 0, }; s >> std::get_time(&x, "%Y-%m-%d"); checkDirectory(&x, "C:\\Users\\euna501\\Downloads\\LINE WORKS"); }
28.448718
86
0.679585
vegemil
537cb69b0923b19595b35018463da84a46573bfc
472
cpp
C++
Engine/Source/Misc/Singleton.cpp
wdrDarx/DEngine3
27e2de3b56b6d4c8705e8a0e36f5911d8651caa2
[ "MIT" ]
2
2022-01-11T21:15:31.000Z
2022-02-22T21:14:33.000Z
Engine/Source/Misc/Singleton.cpp
wdrDarx/DEngine3
27e2de3b56b6d4c8705e8a0e36f5911d8651caa2
[ "MIT" ]
null
null
null
Engine/Source/Misc/Singleton.cpp
wdrDarx/DEngine3
27e2de3b56b6d4c8705e8a0e36f5911d8651caa2
[ "MIT" ]
null
null
null
#include "Singleton.h" void SingletonCache::Store(const std::type_index& type, void* ptr) { //return; //using auto registers breaks this whole thing m_PointerCache[type] = ptr; } void* SingletonCache::Find(const std::type_index& type) { if(m_PointerCache.empty()) return nullptr; for (auto& pair : m_PointerCache) { if (pair.first == type) return pair.second; } return nullptr; } std::unordered_map<std::type_index, void*> SingletonCache::m_PointerCache;
20.521739
74
0.724576
wdrDarx
537e955672b76efb287ccd96dea5e70143e09d32
3,574
hpp
C++
chapter20/uncommentedString.hpp
not-sponsored/Sams-Cpp-in-24hrs-Exercises
2e63e2ca31f5309cc1d593f29c8b47037be150fb
[ "Fair" ]
2
2022-01-08T03:31:25.000Z
2022-03-09T01:21:54.000Z
chapter20/uncommentedString.hpp
not-sponsored/Sams-Cpp-in-24hrs-Exercises
2e63e2ca31f5309cc1d593f29c8b47037be150fb
[ "Fair" ]
null
null
null
chapter20/uncommentedString.hpp
not-sponsored/Sams-Cpp-in-24hrs-Exercises
2e63e2ca31f5309cc1d593f29c8b47037be150fb
[ "Fair" ]
1
2022-03-09T01:26:01.000Z
2022-03-09T01:26:01.000Z
/********************************************************* * * Part of the answer to exercise 1 in chapter 20 * * Modified 20.3 from Sams Teach Yourself C++ in 24 Hours by Rogers Cadenhead * and Jesse Liberty * * Compiled with g++ (GCC) 11.1.0 * *********************************************************/ #include <iostream> #include <string.h> using std::cout; using std::cin; class String { public: // constructors String(); String(const char *const); String(const String&); ~String(); // overloaded operators char& operator[](int offset); char operator[](int offset) const; String operator+(const String&); void operator+=(const String&); String& operator=(const String &); // general accessors int getLen() const { return len; } const char* getString() const { return value; } static int constructorCount; private: String(int); // private constructor char* value; int len; }; // default constructor creates 0 byte string String::String() { value = new char[1]; value[0] = '\0'; len = 0; cout << "\tDefault string constructor\n"; constructorCount++; } // private helper constructor only for class functions // creates a string of required size, null filled String::String(int len) { value = new char[len + 1]; int i; for (i = 0; i < len; i++) value[i] = '\0'; len = len; cout << "\tString(int) constructor\n"; constructorCount++; } String::String(const char* const cString) { len = strlen(cString); value = new char[len + 1]; int i; for (i = 0; i < len; i++) value[i] = cString[i]; value[len] = '\0'; cout << "\tString(char*) constructor\n"; constructorCount++; } String::String(const String& rhs) { len = rhs.getLen(); value = new char[len + 1]; int i; for (i = 0; i < len; i++) value[i] = rhs[i]; value[len] = '\0'; cout << "\tString(String&) constructor\n"; constructorCount++; } String::~String() { delete [] value; len = 0; cout << "\tString destructor\n"; } // operator equals, frees existing memory and copies string and size String& String::operator=(const String &rhs) { if (this == &rhs) return *this; delete [] value; len = rhs.getLen(); value = new char[len + 1]; int i; for (i = 0; i < len; i++) value[i] = rhs[i]; value[len] = '\0'; return *this; cout << "\tString operator=\n"; } // non-constant offset operator returns reference to character to be changed char& String::operator[](int offset) { if (offset > len) return value[len - 1]; else if (offset < 0 && abs(offset) <= len) return value[len + offset]; else if (offset < 0) return value[0]; else return value[offset]; } // constant offset operator for use on const objects (see copy constructor) char String::operator[](int offset) const { if (offset > len) return value[len - 1]; else if (offset < 0 && abs(offset) <= len) return value[len + offset]; else if (offset < 0) return value[0]; else return value[offset]; } // new string by adding current string to rhs String String::operator+(const String& rhs) { int totalLen = len + rhs.getLen(); int i, j; String temp(totalLen); for (i = 0; i < len; i++) temp[i] = value[i]; for (j = 0; j < rhs.getLen(); j++) temp[i] = rhs[j]; temp[totalLen] = '\0'; return temp; } // changes current string, returns nothing void String::operator+=(const String& rhs) { int rhsLen = rhs.getLen(); int totalLen = len + rhsLen; int i, j; String temp(totalLen); for (i = 0; i < len; i++) temp[i] = value[i]; for (j = 0; j < rhs.getLen(); j++) temp[i] = rhs[i - len]; temp[totalLen] = '\0'; *this = temp; } int String::constructorCount = 0;
21.023529
77
0.618355
not-sponsored
538125a28def421e2038c7a531a082af2d91a2a8
4,127
cpp
C++
private/shell/cpls/srvwiz/dllreg.cpp
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
11
2017-09-02T11:27:08.000Z
2022-01-02T15:25:24.000Z
private/shell/cpls/srvwiz/dllreg.cpp
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
null
null
null
private/shell/cpls/srvwiz/dllreg.cpp
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
14
2019-01-16T01:01:23.000Z
2022-02-20T15:54:27.000Z
// dllreg.cpp -- autmatic registration and unregistration // #include "priv.h" #include <advpub.h> #include <comcat.h> // helper macros // ADVPACK will return E_UNEXPECTED if you try to uninstall (which does a registry restore) // on an INF section that was never installed. We uninstall sections that may never have // been installed, so this MACRO will quiet these errors. #define QuietInstallNoOp(hr) ((E_UNEXPECTED == hr) ? S_OK : hr) BOOL UnregisterTypeLibrary(const CLSID* piidLibrary) { TCHAR szScratch[GUIDSTR_MAX]; HKEY hk; BOOL fResult = FALSE; // convert the libid into a string. // SHStringFromGUID(*piidLibrary, szScratch, ARRAYSIZE(szScratch)); if (RegOpenKey(HKEY_CLASSES_ROOT, TEXT("TypeLib"), &hk) == ERROR_SUCCESS) { fResult = RegDeleteKey(hk, szScratch); RegCloseKey(hk); } return fResult; } HRESULT RegisterTypeLib(void) { HRESULT hr = S_OK; ITypeLib *pTypeLib; DWORD dwPathLen; TCHAR szTmp[MAX_PATH]; #ifdef UNICODE WCHAR *pwsz = szTmp; #else WCHAR pwsz[MAX_PATH]; #endif // Load and register our type library. // dwPathLen = GetModuleFileName(HINST_THISDLL, szTmp, ARRAYSIZE(szTmp)); #ifndef UNICODE if (SHAnsiToUnicode(szTmp, pwsz, MAX_PATH)) #endif { hr = LoadTypeLib(pwsz, &pTypeLib); if (SUCCEEDED(hr)) { // call the unregister type library as we had some old junk that // was registered by a previous version of OleAut32, which is now causing // the current version to not work on NT... UnregisterTypeLibrary(&LIBID_SrvWizLib); hr = RegisterTypeLib(pTypeLib, pwsz, NULL); if (FAILED(hr)) { } pTypeLib->Release(); } else { } } #ifndef UNICODE else { hr = E_FAIL; } #endif return hr; } /*---------------------------------------------------------- Purpose: Calls the ADVPACK entry-point which executes an inf file section. Returns: Cond: -- */ HRESULT CallRegInstall(HINSTANCE hinstSrvWiz, LPSTR szSection) { HRESULT hr = E_FAIL; HINSTANCE hinstAdvPack = LoadLibrary(TEXT("ADVPACK.DLL")); if (hinstAdvPack) { REGINSTALL pfnri = (REGINSTALL)GetProcAddress(hinstAdvPack, "RegInstall"); if (pfnri) { char szThisDLL[MAX_PATH]; // Get the location of this DLL from the HINSTANCE if ( !GetModuleFileNameA(hinstSrvWiz, szThisDLL, ARRAYSIZE(szThisDLL)) ) { // Failed, just say "srvwiz.dll" lstrcpyA(szThisDLL, "srvwiz.dll"); } STRENTRY seReg[] = { { "THISDLL", szThisDLL }, // These two NT-specific entries must be at the end { "25", "%SystemRoot%" }, { "11", "%SystemRoot%\\system32" }, }; STRTABLE stReg = { ARRAYSIZE(seReg), seReg }; hr = pfnri(g_hinst, szSection, &stReg); } FreeLibrary(hinstAdvPack); } return hr; } STDAPI DllRegisterServer(void) { HRESULT hr; // Delete any old registration entries, then add the new ones. // Keep ADVPACK.DLL loaded across multiple calls to RegInstall. // (The inf engine doesn't guarantee DelReg/AddReg order, that's // why we explicitly unreg and reg here.) // HINSTANCE hinstSrvWiz = GetModuleHandle(TEXT("SRVWIZ.DLL")); hr = CallRegInstall(hinstSrvWiz, "RegDll"); RegisterTypeLib(); return hr; } STDAPI DllUnregisterServer(void) { HRESULT hr; HINSTANCE hinstSrvWiz = GetModuleHandle(TEXT("SRVWIZ.DLL")); // UnInstall the registry values hr = CallRegInstall(hinstSrvWiz, "UnregDll"); UnregisterTypeLibrary(&LIBID_SrvWizLib); return hr; } STDAPI DllInstall(BOOL bInstall, LPCWSTR pszCmdLine) { return S_OK; }
25.012121
92
0.580082
King0987654
53830346afd4c02fa7869d8037de73ed1ec97ef6
11,459
cpp
C++
Plugins/SimpleMaterialUI/Source/SimpleMaterialUIEditor/Private/SmMarginCustomization.cpp
dfyzy/StealthTest
ff48d800ef073abd559048d81df7efd014c91cb7
[ "MIT" ]
null
null
null
Plugins/SimpleMaterialUI/Source/SimpleMaterialUIEditor/Private/SmMarginCustomization.cpp
dfyzy/StealthTest
ff48d800ef073abd559048d81df7efd014c91cb7
[ "MIT" ]
null
null
null
Plugins/SimpleMaterialUI/Source/SimpleMaterialUIEditor/Private/SmMarginCustomization.cpp
dfyzy/StealthTest
ff48d800ef073abd559048d81df7efd014c91cb7
[ "MIT" ]
null
null
null
#include "SmMarginCustomization.h" #include "PropertyHandle.h" #include "DetailLayoutBuilder.h" #include "Widgets/Input/SNumericEntryBox.h" #include "Editor.h" bool FSmMarginIdentifier::IsPropertyTypeCustomized(const IPropertyHandle& PropertyHandle) const { return PropertyHandle.IsValidHandle() && PropertyHandle.GetMetaDataProperty()->HasMetaData("SmMargin"); } void FSmMarginCustomization::GetSortedChildren(TSharedRef<IPropertyHandle> StructPropertyHandle, TArray<TSharedRef<IPropertyHandle>>& OutChildren) { OutChildren.Add(StructPropertyHandle->GetChildHandle(TEXT("Left")).ToSharedRef()); OutChildren.Add(StructPropertyHandle->GetChildHandle(TEXT("Top")).ToSharedRef()); OutChildren.Add(StructPropertyHandle->GetChildHandle(TEXT("Right")).ToSharedRef()); OutChildren.Add(StructPropertyHandle->GetChildHandle(TEXT("Bottom")).ToSharedRef()); } TSharedRef<SWidget> FSmMarginCustomization::MakeChildWidget(TSharedRef<IPropertyHandle>& StructurePropertyHandle, TSharedRef<IPropertyHandle>& PropertyHandle) { TOptional<float> MinValue, MaxValue, SliderMinValue, SliderMaxValue; float SliderExponent, Delta; int32 ShiftMouseMovePixelPerDelta = 1; bool SupportDynamicSliderMaxValue = false; bool SupportDynamicSliderMinValue = false; { FProperty* Property = PropertyHandle->GetProperty(); const FString& MetaUIMinString = Property->GetMetaData(TEXT("UIMin")); const FString& MetaUIMaxString = Property->GetMetaData(TEXT("UIMax")); const FString& SliderExponentString = Property->GetMetaData(TEXT("SliderExponent")); const FString& DeltaString = Property->GetMetaData(TEXT("Delta")); const FString& ShiftMouseMovePixelPerDeltaString = Property->GetMetaData(TEXT("ShiftMouseMovePixelPerDelta")); const FString& SupportDynamicSliderMaxValueString = Property->GetMetaData(TEXT("SupportDynamicSliderMaxValue")); const FString& SupportDynamicSliderMinValueString = Property->GetMetaData(TEXT("SupportDynamicSliderMinValue")); const FString& ClampMinString = Property->GetMetaData(TEXT("ClampMin")); const FString& ClampMaxString = Property->GetMetaData(TEXT("ClampMax")); // If no UIMin/Max was specified then use the clamp string const FString& UIMinString = MetaUIMinString.Len() ? MetaUIMinString : ClampMinString; const FString& UIMaxString = MetaUIMaxString.Len() ? MetaUIMaxString : ClampMaxString; float ClampMin = TNumericLimits<float>::Lowest(); float ClampMax = TNumericLimits<float>::Max(); if (!ClampMinString.IsEmpty()) { TTypeFromString<float>::FromString(ClampMin, *ClampMinString); } if (!ClampMaxString.IsEmpty()) { TTypeFromString<float>::FromString(ClampMax, *ClampMaxString); } float UIMin = TNumericLimits<float>::Lowest(); float UIMax = TNumericLimits<float>::Max(); TTypeFromString<float>::FromString(UIMin, *UIMinString); TTypeFromString<float>::FromString(UIMax, *UIMaxString); SliderExponent = float(1); if (SliderExponentString.Len()) { TTypeFromString<float>::FromString(SliderExponent, *SliderExponentString); } Delta = float(0); if (DeltaString.Len()) { TTypeFromString<float>::FromString(Delta, *DeltaString); } ShiftMouseMovePixelPerDelta = 1; if (ShiftMouseMovePixelPerDeltaString.Len()) { TTypeFromString<int32>::FromString(ShiftMouseMovePixelPerDelta, *ShiftMouseMovePixelPerDeltaString); //The value should be greater or equal to 1 // 1 is neutral since it is a multiplier of the mouse drag pixel if (ShiftMouseMovePixelPerDelta < 1) { ShiftMouseMovePixelPerDelta = 1; } } if (ClampMin >= ClampMax && (ClampMinString.Len() || ClampMaxString.Len())) { //UE_LOG(LogPropertyNode, Warning, TEXT("Clamp Min (%s) >= Clamp Max (%s) for Ranged Numeric"), *ClampMinString, *ClampMaxString); } const float ActualUIMin = FMath::Max(UIMin, ClampMin); const float ActualUIMax = FMath::Min(UIMax, ClampMax); MinValue = ClampMinString.Len() ? ClampMin : TOptional<float>(); MaxValue = ClampMaxString.Len() ? ClampMax : TOptional<float>(); SliderMinValue = (UIMinString.Len()) ? ActualUIMin : TOptional<float>(); SliderMaxValue = (UIMaxString.Len()) ? ActualUIMax : TOptional<float>(); if (ActualUIMin >= ActualUIMax && (MetaUIMinString.Len() || MetaUIMaxString.Len())) { //UE_LOG(LogPropertyNode, Warning, TEXT("UI Min (%s) >= UI Max (%s) for Ranged Numeric"), *UIMinString, *UIMaxString); } SupportDynamicSliderMaxValue = SupportDynamicSliderMaxValueString.Len() > 0 && SupportDynamicSliderMaxValueString.ToBool(); SupportDynamicSliderMinValue = SupportDynamicSliderMinValueString.Len() > 0 && SupportDynamicSliderMinValueString.ToBool(); } TWeakPtr<IPropertyHandle> WeakHandlePtr = PropertyHandle; return SNew(SNumericEntryBox<float>) .IsEnabled(this, &FMathStructCustomization::IsValueEnabled, WeakHandlePtr) .EditableTextBoxStyle(&FCoreStyle::Get().GetWidgetStyle<FEditableTextBoxStyle>("NormalEditableTextBox")) .Value(this, &FSmMarginCustomization::OnGetValue, WeakHandlePtr) .Font(IDetailLayoutBuilder::GetDetailFont()) .UndeterminedString(NSLOCTEXT("PropertyEditor", "MultipleValues", "Multiple Values")) .OnValueCommitted(this, &FSmMarginCustomization::OnValueCommitted, WeakHandlePtr) .OnValueChanged(this, &FSmMarginCustomization::OnValueChanged, WeakHandlePtr) .OnBeginSliderMovement(this, &FSmMarginCustomization::OnBeginSliderMovement) .OnEndSliderMovement(this, &FSmMarginCustomization::OnEndSliderMovement) .LabelVAlign(VAlign_Center) // Only allow spin on handles with one object. Otherwise it is not clear what value to spin .AllowSpin(PropertyHandle->GetNumOuterObjects() < 2) .ShiftMouseMovePixelPerDelta(ShiftMouseMovePixelPerDelta) .SupportDynamicSliderMaxValue(SupportDynamicSliderMaxValue) .SupportDynamicSliderMinValue(SupportDynamicSliderMinValue) .OnDynamicSliderMaxValueChanged(this, &FSmMarginCustomization::OnDynamicSliderMaxValueChanged) .OnDynamicSliderMinValueChanged(this, &FSmMarginCustomization::OnDynamicSliderMinValueChanged) .MinValue(MinValue) .MaxValue(MaxValue) .MinSliderValue(SliderMinValue) .MaxSliderValue(SliderMaxValue) .SliderExponent(SliderExponent) .Delta(Delta); } void FSmMarginCustomization::SetValue(float NewValue, EPropertyValueSetFlags::Type Flags, TWeakPtr<IPropertyHandle> WeakHandlePtr) { if (bPreserveScaleRatio) { // Get the value for each object for the modified component TArray<FString> OldValues; if (WeakHandlePtr.Pin()->GetPerObjectValues(OldValues) == FPropertyAccess::Success) { // Loop through each object and scale based on the new ratio for each object individually for (int32 OutputIndex = 0; OutputIndex < OldValues.Num(); ++OutputIndex) { float OldValue; TTypeFromString<float>::FromString(OldValue, *OldValues[OutputIndex]); // Account for the previous scale being zero. Just set to the new value in that case? float Ratio = OldValue == 0 ? NewValue : NewValue / OldValue; if (Ratio == 0) { Ratio = NewValue; } // Loop through all the child handles (each component of the math struct, like X, Y, Z...etc) for (int32 ChildIndex = 0; ChildIndex < SortedChildHandles.Num(); ++ChildIndex) { // Ignore scaling our selves. TSharedRef<IPropertyHandle> ChildHandle = SortedChildHandles[ChildIndex]; if (ChildHandle != WeakHandlePtr.Pin()) { // Get the value for each object. TArray<FString> ObjectChildValues; if (ChildHandle->GetPerObjectValues(ObjectChildValues) == FPropertyAccess::Success) { // Individually scale each object's components by the same ratio. for (int32 ChildOutputIndex = 0; ChildOutputIndex < ObjectChildValues.Num(); ++ChildOutputIndex) { float ChildOldValue; TTypeFromString<float>::FromString(ChildOldValue, *ObjectChildValues[ChildOutputIndex]); float ChildNewValue = ChildOldValue * Ratio; ObjectChildValues[ChildOutputIndex] = TTypeToString<float>::ToSanitizedString(ChildNewValue); } ChildHandle->SetPerObjectValues(ObjectChildValues); } } } } } } WeakHandlePtr.Pin()->SetValue(NewValue, Flags); } TOptional<float> FSmMarginCustomization::OnGetValue(TWeakPtr<IPropertyHandle> WeakHandlePtr) const { float NumericVal = 0; if (WeakHandlePtr.Pin()->GetValue(NumericVal) == FPropertyAccess::Success) { return TOptional<float>(NumericVal); } // Value couldn't be accessed. Return an unset value return TOptional<float>(); } void FSmMarginCustomization::OnValueCommitted(float NewValue, ETextCommit::Type CommitType, TWeakPtr<IPropertyHandle> WeakHandlePtr) { EPropertyValueSetFlags::Type Flags = EPropertyValueSetFlags::DefaultFlags; SetValue(NewValue, Flags, WeakHandlePtr); } void FSmMarginCustomization::OnValueChanged(float NewValue, TWeakPtr<IPropertyHandle> WeakHandlePtr) { if (bIsUsingSlider) { EPropertyValueSetFlags::Type Flags = EPropertyValueSetFlags::InteractiveChange; SetValue(NewValue, Flags, WeakHandlePtr); } } void FSmMarginCustomization::OnBeginSliderMovement() { bIsUsingSlider = true; GEditor->BeginTransaction(NSLOCTEXT("FMathStructCustomization", "SetVectorProperty", "Set Vector Property")); } void FSmMarginCustomization::OnEndSliderMovement(float NewValue) { bIsUsingSlider = false; GEditor->EndTransaction(); } void FSmMarginCustomization::OnDynamicSliderMaxValueChanged(float NewMaxSliderValue, TWeakPtr<SWidget> InValueChangedSourceWidget, bool IsOriginator, bool UpdateOnlyIfHigher) { for (TWeakPtr<SWidget>& Widget : NumericEntryBoxWidgetList) { TSharedPtr<SNumericEntryBox<float>> NumericBox = StaticCastSharedPtr<SNumericEntryBox<float>>(Widget.Pin()); if (NumericBox.IsValid()) { TSharedPtr<SSpinBox<float>> SpinBox = StaticCastSharedPtr<SSpinBox<float>>(NumericBox->GetSpinBox()); if (SpinBox.IsValid()) { if (SpinBox != InValueChangedSourceWidget) { if ((NewMaxSliderValue > SpinBox->GetMaxSliderValue() && UpdateOnlyIfHigher) || !UpdateOnlyIfHigher) { // Make sure the max slider value is not a getter otherwise we will break the link! verifySlow(!SpinBox->IsMaxSliderValueBound()); SpinBox->SetMaxSliderValue(NewMaxSliderValue); } } } } } if (IsOriginator) { OnNumericEntryBoxDynamicSliderMaxValueChanged.Broadcast((float)NewMaxSliderValue, InValueChangedSourceWidget, false, UpdateOnlyIfHigher); } } void FSmMarginCustomization::OnDynamicSliderMinValueChanged(float NewMinSliderValue, TWeakPtr<SWidget> InValueChangedSourceWidget, bool IsOriginator, bool UpdateOnlyIfLower) { for (TWeakPtr<SWidget>& Widget : NumericEntryBoxWidgetList) { TSharedPtr<SNumericEntryBox<float>> NumericBox = StaticCastSharedPtr<SNumericEntryBox<float>>(Widget.Pin()); if (NumericBox.IsValid()) { TSharedPtr<SSpinBox<float>> SpinBox = StaticCastSharedPtr<SSpinBox<float>>(NumericBox->GetSpinBox()); if (SpinBox.IsValid()) { if (SpinBox != InValueChangedSourceWidget) { if ((NewMinSliderValue < SpinBox->GetMinSliderValue() && UpdateOnlyIfLower) || !UpdateOnlyIfLower) { // Make sure the min slider value is not a getter otherwise we will break the link! verifySlow(!SpinBox->IsMinSliderValueBound()); SpinBox->SetMinSliderValue(NewMinSliderValue); } } } } } if (IsOriginator) { OnNumericEntryBoxDynamicSliderMinValueChanged.Broadcast((float)NewMinSliderValue, InValueChangedSourceWidget, false, UpdateOnlyIfLower); } }
38.844068
174
0.761498
dfyzy
5384176a24be9a050c35188a1a18a9ebb667084b
9,232
cpp
C++
betteryao/OTExtension/util/Miracl/zzn3.cpp
bt3ze/pcflib
c66cdc5957818cd5b3754430046cad91ce1a921d
[ "BSD-2-Clause" ]
null
null
null
betteryao/OTExtension/util/Miracl/zzn3.cpp
bt3ze/pcflib
c66cdc5957818cd5b3754430046cad91ce1a921d
[ "BSD-2-Clause" ]
null
null
null
betteryao/OTExtension/util/Miracl/zzn3.cpp
bt3ze/pcflib
c66cdc5957818cd5b3754430046cad91ce1a921d
[ "BSD-2-Clause" ]
null
null
null
/*************************************************************************** * Copyright 2013 CertiVox IOM Ltd. * * This file is part of CertiVox MIRACL Crypto SDK. * * The CertiVox MIRACL Crypto SDK provides developers with an * extensive and efficient set of cryptographic functions. * For further information about its features and functionalities please * refer to http://www.certivox.com * * * The CertiVox MIRACL Crypto SDK is free software: you can * redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the * Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * * The CertiVox MIRACL Crypto SDK 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 Affero General Public License for more details. * * * You should have received a copy of the GNU Affero General Public * License along with CertiVox MIRACL Crypto SDK. * If not, see <http://www.gnu.org/licenses/>. * * You can be released from the requirements of the license by purchasing * a commercial license. Buying such a license is mandatory as soon as you * develop commercial activities involving the CertiVox MIRACL Crypto SDK * without disclosing the source code of your own applications, or shipping * the CertiVox MIRACL Crypto SDK with a closed source product. * * ***************************************************************************/ /* * MIRACL C++ Implementation file zzn3.cpp * * AUTHOR : M. Scott * * PURPOSE : Implementation of class ZZn3 (Arithmetic over n^3) * * WARNING: This class has been cobbled together for a specific use with * the MIRACL library. It is not complete, and may not work in other * applications * * Assumes p=1 mod 3 and p NOT 1 mod 8 * Irreducible is x^3+cnr (cubic non-residue) * */ #include "zzn3.h" using namespace std; // First find a cubic non-residue cnr, which is also a quadratic non-residue // X is precalculated sixth root of unity (cnr)^(p-1)/6 void ZZn3::get(ZZn& x,ZZn& y,ZZn& z) const {copy(fn.a,x.getzzn()); copy(fn.b,y.getzzn()); copy(fn.c,z.getzzn());} void ZZn3::get(ZZn& x) const {{copy(fn.a,x.getzzn());}} ZZn3& ZZn3::operator/=(const ZZn& x) { ZZn t=(ZZn)1/x; zzn3_smul(&fn,t.getzzn(),&fn); return *this; } ZZn3& ZZn3::operator/=(int i) { if (i==2) {zzn3_div2(&fn); return *this;} ZZn t=one()/i; zzn3_smul(&fn,t.getzzn(),&fn); return *this; } ZZn3& ZZn3::operator/=(const ZZn3& x) { *this*=inverse(x); return *this; } ZZn3 inverse(const ZZn3& w) {ZZn3 i=w; zzn3_inv(&i.fn); return i;} ZZn3 operator+(const ZZn3& x,const ZZn3& y) {ZZn3 w=x; w+=y; return w; } ZZn3 operator+(const ZZn3& x,const ZZn& y) {ZZn3 w=x; w+=y; return w; } ZZn3 operator-(const ZZn3& x,const ZZn3& y) {ZZn3 w=x; w-=y; return w; } ZZn3 operator-(const ZZn3& x,const ZZn& y) {ZZn3 w=x; w-=y; return w; } ZZn3 operator-(const ZZn3& x) {ZZn3 w; zzn3_negate((zzn3 *)&x.fn,&w.fn); return w; } ZZn3 operator*(const ZZn3& x,const ZZn3& y) { ZZn3 w=x; if (&x==&y) w*=w; else w*=y; return w; } ZZn3 operator*(const ZZn3& x,const ZZn& y) {ZZn3 w=x; w*=y; return w;} ZZn3 operator*(const ZZn& y,const ZZn3& x) {ZZn3 w=x; w*=y; return w;} ZZn3 operator*(const ZZn3& x,int y) {ZZn3 w=x; w*=y; return w;} ZZn3 operator*(int y,const ZZn3& x) {ZZn3 w=x; w*=y; return w;} ZZn3 operator/(const ZZn3& x,const ZZn3& y) {ZZn3 w=x; w/=y; return w;} ZZn3 operator/(const ZZn3& x,const ZZn& y) {ZZn3 w=x; w/=y; return w;} ZZn3 operator/(const ZZn3& x,int i) {ZZn3 w=x; w/=i; return w;} #ifndef MR_NO_RAND ZZn3 randn3(void) {ZZn3 w; zzn3_from_zzns(randn().getzzn(),randn().getzzn(),randn().getzzn(),&w.fn); return w;} #endif ZZn3 rhs(const ZZn3& x) { ZZn3 w; miracl *mip=get_mip(); int twist=mip->TWIST; int qnr=mip->cnr; // the cubic non-residue is also a quadratic non-residue w=x*x*x; if (twist) { if (twist==MR_QUARTIC_M) { w+=tx((ZZn3)getA())*x; } if (twist==MR_QUARTIC_D) { w+=txd((ZZn3)getA())*x; } if (twist==MR_SEXTIC_M || twist==MR_CUBIC_M) { w+=tx((ZZn3)getB()); } if (twist==MR_SEXTIC_D || twist==MR_CUBIC_D) { w+=txd((ZZn3)getB()); } if (twist==MR_QUADRATIC) { w+=qnr*qnr*getA()*x+(qnr*qnr*qnr)*getB(); } } else { w+=getA()*x+getB(); } return w; } BOOL is_on_curve(const ZZn3& x) { ZZn3 w; if (qr(rhs(x))) return TRUE; return FALSE; } BOOL qr(const ZZn3& x) { Big p=get_modulus(); ZZn3 r,t; t=r=x; t.powq(); r*=t; t.powq(); r*=t; // check x^[(p^3-1)/2] = 1 if (pow(r,(p-1)/2)==1) return TRUE; else return FALSE; } ZZn3 sqrt(const ZZn3& x) { ZZn3 r,w,t; Big p=get_modulus(); if (!qr(x)) return r; // oh boy this is clever! switch (get_mip()->pmod8) { case 5: r=(x+x); r.powq(); w=r*r; t=w*r; w*=t; r.powq(); r*=(w*(x+x)); r=pow(r,(p-5)/8); r*=t; w=r*r; w*=x; w+=w; r*=x; r*=(w-(ZZn)1); break; case 3: case 7: r=x; r.powq(); t=r*r; w=t*r; r.powq(); r*=(w*x); r=pow(r,(p-3)/4); r*=(t*x); break; default: break; } return r; } ZZn3 tx(const ZZn3& w) { ZZn3 u=w; zzn3_timesi(&u.fn); return u; } ZZn3 tx2(const ZZn3& w) { ZZn3 u=w; zzn3_timesi2(&u.fn); return u; } ZZn3 txd(const ZZn3& w) { ZZn3 u; ZZn wa,wb,wc; w.get(wa,wb,wc); u.set(wb,wc,(wa/get_mip()->cnr)); return u; } // regular ZZn3 powering ZZn3 pow(const ZZn3& x,const Big& k) { int i,j,nb,n,nbw,nzs; ZZn3 u,u2,t[16]; if (k==0) return (ZZn3)1; u=x; if (k==1) return u; // // Prepare table for windowing // u2=(u*u); t[0]=u; for (i=1;i<16;i++) t[i]=u2*t[i-1]; // Left to right method - with windows nb=bits(k); if (nb>1) for (i=nb-2;i>=0;) { n=window(k,i,&nbw,&nzs,5); for (j=0;j<nbw;j++) u*=u; if (n>0) u*=t[n/2]; i-=nbw; if (nzs) { for (j=0;j<nzs;j++) u*=u; i-=nzs; } } return u; } ZZn3 powl(const ZZn3& x,const Big& k) { ZZn3 A,B,two,y; int j,nb; two=(ZZn)2; y=two*x; // y=x; if (k==0) return (ZZn3)two; if (k==1) return y; // w8=two; // w9=y; A=y; B=y*y-two; nb=bits(k); //cout << "nb= " << nb << endl; for (j=nb-1;j>=1;j--) { if (bit(k,j-1)) { A*=B; A-=y; B*=B; B-=two; } else { B*=A; B-=y; A*=A; A-=two; } //cout << "1. int A= " << A << endl; } //cout << "1. B= " << B << endl; return A/2; // return (w8/2); } // double exponention - see Schoenmaker's method from Stam's thesis ZZn3 powl(const ZZn3& x,const Big& n,const ZZn3& y,const Big& m,const ZZn3& a) { ZZn3 A,B,C,T,two,vk,vl,va; int j,nb; two=(ZZn)2; vk=x+x; vl=y+y; va=a+a; nb=bits(n); if (bits(m)>nb) nb=bits(m); //cout << "nb= " << nb << endl; A=two; B=vk; C=vl; /* cout << "A= " << A << endl; cout << "B= " << B << endl; cout << "C= " << C << endl; cout << "vk= " << vk << endl; cout << "vl= " << vl << endl; cout << "va= " << va << endl; cout << "va*va-2= " << va*va-two << endl; */ for (j=nb;j>=1;j--) { if (bit(n,j-1)==0 && bit(m,j-1)==0) { B*=A; B-=vk; C*=A; C-=vl; A*=A; A-=two; } if (bit(n,j-1)==1 && bit(m,j-1)==0) { A*=B; A-=vk; C*=B; C-=va; B*=B; B-=two; } if (bit(n,j-1)==0 && bit(m,j-1)==1) { A*=C; A-=vl; B*=C; B-=va; C*=C; C-=two; } if (bit(n,j-1)==1 && bit(m,j-1)==1) { T=B*C-va; B*=A; B-=vk; C*=A; C-=vl; A=T; T=A*vl-B; B=A*vk-C; C=T; } } // return A; return (A/2); } #ifndef MR_NO_STANDARD_IO ostream& operator<<(ostream& s,const ZZn3& xx) { ZZn3 b=xx; ZZn x,y,z; b.get(x,y,z); s << "[" << x << "," << y << "," << z << "]"; return s; } #endif
23.313131
93
0.476603
bt3ze
5388a234101dcf52c200eecd8a41f23fcd7d8291
843
cpp
C++
ThreeCharacters/CPP/main.cpp
hecate-xw/Miscellaneous
57c5ade630f1f1af2a5aae7f2541638380fc4876
[ "MIT" ]
null
null
null
ThreeCharacters/CPP/main.cpp
hecate-xw/Miscellaneous
57c5ade630f1f1af2a5aae7f2541638380fc4876
[ "MIT" ]
null
null
null
ThreeCharacters/CPP/main.cpp
hecate-xw/Miscellaneous
57c5ade630f1f1af2a5aae7f2541638380fc4876
[ "MIT" ]
1
2020-02-13T00:48:17.000Z
2020-02-13T00:48:17.000Z
#include <iostream> #include "PowMatrix.h" using namespace std; int main() { int n; cin >> n; /* // Method 1 int dp[n][2]; dp[0][0] = 3; dp[0][1] = 0; for(int i = 1; i < n; i++) { dp[i][0] = dp[i-1][0]*2 + dp[i-1][1]*2; dp[i][1] = dp[i-1][0]; } int sum = dp[n-1][0] + dp[n-1][1]; */ /* // Method 2 int dp0 = 3; int dp1 = 0; for(int i = 1; i < n; i++) { int temp = dp0; dp0 = 2*dp0 + 2*dp1; dp1 = temp; } int sum = dp0+dp1; */ // Method 3 int dimension = 2; int matrix[2*2] = {2,2,1,0}; PowMatrix powMatrix(dimension); powMatrix.setMatrix(matrix); int count = n-1; powMatrix.pow(count); int* result = powMatrix.getResult(); int sum = 3 * result[0] + 3 * result[2]; cout << sum << endl; return 0; }
15.327273
47
0.465006
hecate-xw
538a0884ca5e025ad80b5788b0faa5f47e118860
10,353
cpp
C++
Tools/GHGUITool/GHGUITool/GTGUINavigator.cpp
GoldenHammerSoftware/GH
757213f479c0fc80ed1a0f59972bf3e9d92b7526
[ "MIT" ]
null
null
null
Tools/GHGUITool/GHGUITool/GTGUINavigator.cpp
GoldenHammerSoftware/GH
757213f479c0fc80ed1a0f59972bf3e9d92b7526
[ "MIT" ]
null
null
null
Tools/GHGUITool/GHGUITool/GTGUINavigator.cpp
GoldenHammerSoftware/GH
757213f479c0fc80ed1a0f59972bf3e9d92b7526
[ "MIT" ]
null
null
null
// Copyright 2010 Golden Hammer Software #include "GTGUINavigator.h" #include "GTIdentifiers.h" #include "GHUtils/GHEventMgr.h" #include "GHUtils/GHMessage.h" #include "GHGUIMgr.h" #include "GHUtils/GHResourceFactory.h" #include "GHXMLObjFactory.h" #include "GHGUIPanel.h" #include "GHXMLNode.h" #include "GHGUIWidgetRenderer.h" #include "GHUtils/GHPropertyContainer.h" #include "GTChange.h" #include "GHMath/GHRandom.h" #include "GTUtil.h" #include "GHUtils/GHUtilsIdentifiers.h" #include "GTMetadataList.h" #include "GTChangePusher.h" #include "GTMoveType.h" #include "GHMath/GHFloat.h" #include "GHGUIText.h" GTGUINavigator::GTGUINavigator(GHEventMgr& eventMgr, GHGUIWidgetResource& topLevelGUI, GHGUIWidgetResource*& currentSelectionPtr, GTUtil& util, GTMetadataList& metadataList, GHPropertyContainer& properties, const GHGUIRectMaker& rectMaker, const GHScreenInfo& screenInfo) : mEventMgr(eventMgr) , mTopPanel(topLevelGUI) , mCurrentPanel(currentSelectionPtr) , mProperties(properties) , mPosDescConverter(rectMaker, screenInfo) , mUtil(util) , mMetadataList(metadataList) , mMoveType(GTMoveType::OFFSET) { mEventMgr.registerListener(GTIdentifiers::M_CREATEPANEL, *this); mEventMgr.registerListener(GTIdentifiers::M_DELETEPANEL, *this); mEventMgr.registerListener(GTIdentifiers::M_SELECTPANEL, *this); mEventMgr.registerListener(GTIdentifiers::M_MOVEPANEL, *this); mEventMgr.registerListener(GTIdentifiers::M_MOVEEND, *this); mEventMgr.registerListener(GTIdentifiers::M_SETCOLOR, *this); mEventMgr.registerListener(GTIdentifiers::M_SETTEXTURE, *this); mEventMgr.registerListener(GTIdentifiers::M_SHIFTPRESSED, *this); mEventMgr.registerListener(GTIdentifiers::M_SHIFTRELEASED, *this); mEventMgr.registerListener(GTIdentifiers::M_SETMOVETYPE, *this); } GTGUINavigator::~GTGUINavigator(void) { mEventMgr.unregisterListener(GTIdentifiers::M_SETMOVETYPE, *this); mEventMgr.unregisterListener(GTIdentifiers::M_SHIFTRELEASED, *this); mEventMgr.unregisterListener(GTIdentifiers::M_SHIFTPRESSED, *this); mEventMgr.unregisterListener(GTIdentifiers::M_SETTEXTURE, *this); mEventMgr.unregisterListener(GTIdentifiers::M_SETCOLOR, *this); mEventMgr.unregisterListener(GTIdentifiers::M_MOVEEND, *this); mEventMgr.unregisterListener(GTIdentifiers::M_MOVEPANEL, *this); mEventMgr.unregisterListener(GTIdentifiers::M_SELECTPANEL, *this); mEventMgr.unregisterListener(GTIdentifiers::M_DELETEPANEL, *this); mEventMgr.unregisterListener(GTIdentifiers::M_CREATEPANEL, *this); } void GTGUINavigator::handleMessage(const GHMessage& message) { if (message.getType() == GTIdentifiers::M_CREATEPANEL) { bool createAsChild = message.getPayload().getProperty(GTIdentifiers::MP_CREATEASCHILD); createPanel(createAsChild); } else if (message.getType() == GTIdentifiers::M_DELETEPANEL) { deletePanel(); } else if (message.getType() == GTIdentifiers::M_SELECTPANEL) { const GHPoint2* selectPt = (const GHPoint2*)message.getPayload().getProperty(GTIdentifiers::MP_SELECTPOINT); if (selectPt) { if (!selectChildren(mTopPanel, *selectPt)) { mCurrentPanel = 0; } } bringSelectionToFront(); } else if (message.getType() == GTIdentifiers::M_MOVEPANEL) { const GHPoint2* delta = (const GHPoint2*)message.getPayload().getProperty(GTIdentifiers::MP_MOVEDELTA); if (delta) { movePanel(*delta); } } else if (message.getType() == GTIdentifiers::M_MOVEEND) { if (mCurrentPanel) { const GHGUIPosDesc& newDesc = mCurrentPanel->get()->getPosDesc(); if (newDesc != mPosBeforeMove) { GTChangePusher changePusher(mEventMgr, mMetadataList, mCurrentPanel); GTMetadata* metadata = changePusher.createMetadataClone(); metadata->mPosDesc = newDesc; changePusher.pushChange(metadata); } } } else if (message.getType() == GTIdentifiers::M_SETCOLOR) { GHPoint4* color = message.getPayload().getProperty(GTIdentifiers::MP_COLOR); if (color && mCurrentPanel && mCurrentPanel->get()) { GTChangePusher changePusher(mEventMgr, mMetadataList, mCurrentPanel); mUtil.setColor(*mCurrentPanel, *color, &changePusher); } } else if (message.getType() == GTIdentifiers::M_SETTEXTURE) { if (mCurrentPanel && mCurrentPanel->get()) { const char* filename = message.getPayload().getProperty(GHUtilsIdentifiers::FILEPATH); GTChangePusher changePusher(mEventMgr, mMetadataList, mCurrentPanel); mUtil.setTexture(*mCurrentPanel, filename, changePusher); } } else if (message.getType() == GTIdentifiers::M_SHIFTPRESSED) { mMoveData.shiftPressed = true; } else if (message.getType() == GTIdentifiers::M_SHIFTRELEASED) { mMoveData.shiftPressed = false; } else if (message.getType() == GTIdentifiers::M_SETMOVETYPE) { int moveType = (int)message.getPayload().getProperty(GHUtilsIdentifiers::VAL); mMoveType = moveType; } } void GTGUINavigator::createPanel(bool asChild) { GHGUIWidgetResource* parent = &mTopPanel; if (asChild && mCurrentPanel) { parent = mCurrentPanel; } GHGUIWidgetResource* panel = panel = mUtil.createPanel(); //default vals GHGUIPosDesc posDesc; posDesc.mXFill = GHFillType::FT_PIXELS; posDesc.mYFill = GHFillType::FT_PIXELS; posDesc.mAlign.setCoords(.5, .5); posDesc.mOffset.setCoords(0, 0); posDesc.mSize.setCoords(300, 67.5); //menu button posDesc.mSizeAlign[0] = GHAlign::A_CENTER; posDesc.mSizeAlign[1] = GHAlign::A_CENTER; panel->get()->setPosDesc(posDesc); //GHXMLNode* matNode = createTextureMatNode("bgrect.png", GHString::CHT_REFERENCE); mCurrentPanel = panel; mUtil.setRandomColor(*mCurrentPanel); parent->get()->addChild(panel); pushCreation(parent); bringSelectionToFront(); } void GTGUINavigator::deletePanel(void) { if (!mCurrentPanel) { return; } GHGUIWidgetResource* parent = mUtil.findParent(mTopPanel, *mCurrentPanel); if (parent) { mCurrentPanel->acquire(); parent->get()->removeChild(mCurrentPanel); pushDeletion(parent); mCurrentPanel->release(); mCurrentPanel = 0; } } void GTGUINavigator::pushCreation(GHGUIWidgetResource* parent) { GTChangePusher pusher(mEventMgr, mMetadataList, mCurrentPanel); GTMetadata* newData = new GTMetadata(mCurrentPanel->get()->getId(), parent->get()->getId(), mCurrentPanel->get()->getPosDesc(), 0, 0); pusher.pushChange(0, newData); } void GTGUINavigator::pushDeletion(GHGUIWidgetResource* parent) { GTChangePusher pusher(mEventMgr, mMetadataList, mCurrentPanel); pusher.pushChange(0); } void GTGUINavigator::bringSelectionToFront(void) { if (mCurrentPanel) { mPosBeforeMove = mCurrentPanel->get()->getPosDesc(); GHGUIWidgetResource* parent = findCurrentParent(mTopPanel); if (parent) { mCurrentPanel->acquire(); parent->get()->removeChild(mCurrentPanel); static float staticInsertionPriority = 0; parent->get()->addChild(mCurrentPanel, ++staticInsertionPriority); mCurrentPanel->release(); } } } GHGUIWidgetResource* GTGUINavigator::findCurrentParent(GHGUIWidgetResource& potentialParent) { if (!mCurrentPanel) { return 0; } return GTUtil::findParent(potentialParent, *mCurrentPanel); } bool GTGUINavigator::selectChildren(GHGUIWidgetResource& panel, const GHPoint2& selectPt) { size_t numChildren = panel.get()->getNumChildren(); for (int i = numChildren - 1; i >= 0; --i) { GHGUIWidgetResource* child = panel.get()->getChildAtIndex(i); if (selectPanel(*child, selectPt)) { return true; } } return false; } bool GTGUINavigator::selectPanel(GHGUIWidgetResource& panel, const GHPoint2& selectPt) { bool ret = false; //exclude guitext children from selection (they are not considered manipulatable panels in the tool) if (panel.get()->getId() == mUtil.getIdForAllTexts()) { return false; } const GHRect<float, 2>& rect = panel.get()->getScreenPos(); if (rect.containsPoint(selectPt)) { const static float kLocalEps = .01f; MoveData moveData; if (rect.mMax[0] - selectPt[0] < kLocalEps) { moveData.edgeHeld[0] = 1; } if (rect.mMax[1] - selectPt[1] < kLocalEps) { moveData.edgeHeld[1] = 1; } if (selectPt[0] - rect.mMin[0] < kLocalEps) { moveData.edgeHeld[0] = -1; } if (selectPt[1] - rect.mMin[1] < kLocalEps) { moveData.edgeHeld[1] = -1; } mMoveData = moveData; mCurrentPanel = &panel; ret = true; } ret = selectChildren(panel, selectPt) || ret; return ret; } void GTGUINavigator::movePanel(const GHPoint2& delta) { if (!mCurrentPanel || !mCurrentPanel->get()) { return; } GHGUIPosDesc posDesc = mCurrentPanel->get()->getPosDesc(); //delta is always in fullscreen pct GHPoint2 convertedDelta; convertedDelta[0] = mPosDescConverter.convertPCTToLocalCoord(*mCurrentPanel->get(), delta[0], 0); convertedDelta[1] = mPosDescConverter.convertPCTToLocalCoord(*mCurrentPanel->get(), delta[1], 1); GHPoint2 localPctDelta; localPctDelta[0] = mPosDescConverter.convertPCTToLocalPCT(*mCurrentPanel->get(), delta[0], 0); localPctDelta[1] = mPosDescConverter.convertPCTToLocalPCT(*mCurrentPanel->get(), delta[1], 1); if (mMoveData) { GHPoint2i sizeAlignDir; sizeAlignDir[0] = posDesc.mSizeAlign[0] == GHAlign::A_LEFT ? -1 : (posDesc.mSizeAlign[0] == GHAlign::A_RIGHT ? 1 : 0); sizeAlignDir[1] = posDesc.mSizeAlign[1] == GHAlign::A_TOP ? -1 : (posDesc.mSizeAlign[1] == GHAlign::A_BOTTOM ? 1 : 0); for (int i = 0; i < 2; ++i) { if (posDesc.mSize[i] + convertedDelta[i] * mMoveData.edgeHeld[i] < 0) { convertedDelta[i] = -posDesc.mSize[i] * mMoveData.edgeHeld[i]; } posDesc.mSize[i] += convertedDelta[i] * mMoveData.edgeHeld[i]; localPctDelta[i] = mPosDescConverter.convertLocalCoordToLocalPCT(*mCurrentPanel->get(), convertedDelta[i], i); GHPoint2* ptToChange = &posDesc.mOffset; GHPoint2* deltaToRead = &convertedDelta; if (mMoveType == GTMoveType::ALIGN) { ptToChange = &posDesc.mAlign; deltaToRead = &localPctDelta; } if (mMoveData.edgeHeld[i]) { if (sizeAlignDir[i] == 0) { (*ptToChange)[i] += (*deltaToRead)[i] * .5f; } else if (mMoveData.edgeHeld[i] != sizeAlignDir[i]) { (*ptToChange)[i] += (*deltaToRead)[i]; } } } } else { if (mMoveType == GTMoveType::ALIGN) { posDesc.mAlign += localPctDelta; } else { posDesc.mOffset += convertedDelta; } } mCurrentPanel->get()->setPosDesc(posDesc); mCurrentPanel->get()->updatePosition(); }
30.8125
120
0.729354
GoldenHammerSoftware
538caf7ead7dbf6749f84be2863944b174f89479
8,738
cc
C++
be/src/runtime/row-batch.cc
wangxnhit/impala
d7a37f00a515d6942ca28bd8cd84380bc8c93c5a
[ "Apache-2.0" ]
1
2016-06-08T06:22:28.000Z
2016-06-08T06:22:28.000Z
be/src/runtime/row-batch.cc
boorad/impala
108c5d8d39c45d49edfca98cd2d858352cd44d51
[ "Apache-2.0" ]
null
null
null
be/src/runtime/row-batch.cc
boorad/impala
108c5d8d39c45d49edfca98cd2d858352cd44d51
[ "Apache-2.0" ]
null
null
null
// Copyright 2012 Cloudera 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. #include "runtime/row-batch.h" #include <stdint.h> // for intptr_t #include <snappy.h> #include "runtime/string-value.h" #include "runtime/tuple-row.h" #include "gen-cpp/Data_types.h" DEFINE_bool(compress_rowbatches, true, "if true, compresses tuple data in Serialize"); using namespace std; namespace impala { RowBatch::~RowBatch() { delete [] tuple_ptrs_; for (int i = 0; i < io_buffers_.size(); ++i) { io_buffers_[i]->Return(); } } int RowBatch::Serialize(TRowBatch* output_batch) { // why does Thrift not generate a Clear() function? output_batch->row_tuples.clear(); output_batch->tuple_offsets.clear(); output_batch->is_compressed = false; output_batch->num_rows = num_rows_; row_desc_.ToThrift(&output_batch->row_tuples); output_batch->tuple_offsets.reserve(num_rows_ * num_tuples_per_row_); int size = TotalByteSize(); output_batch->tuple_data.resize(size); // Copy tuple data, including strings, into output_batch (converting string // pointers into offsets in the process) int offset = 0; // current offset into output_batch->tuple_data char* tuple_data = const_cast<char*>(output_batch->tuple_data.c_str()); for (int i = 0; i < num_rows_; ++i) { TupleRow* row = GetRow(i); const vector<TupleDescriptor*>& tuple_descs = row_desc_.tuple_descriptors(); vector<TupleDescriptor*>::const_iterator desc = tuple_descs.begin(); for (int j = 0; desc != tuple_descs.end(); ++desc, ++j) { if (row->GetTuple(j) == NULL) { // NULLs are encoded as -1 output_batch->tuple_offsets.push_back(-1); continue; } // Record offset before creating copy (which increments offset and tuple_data) output_batch->tuple_offsets.push_back(offset); row->GetTuple(j)->DeepCopy(**desc, &tuple_data, &offset, /* convert_ptrs */ true); DCHECK_LE(offset, size); } } DCHECK_EQ(offset, size); if (FLAGS_compress_rowbatches && size > 0) { // Try compressing tuple_data to compression_scratch_, swap if compressed data is // smaller int max_compressed_size = snappy::MaxCompressedLength(size); if (compression_scratch_.size() < max_compressed_size) { compression_scratch_.resize(max_compressed_size); } size_t compressed_size; char* compressed_output = const_cast<char*>(compression_scratch_.c_str()); snappy::RawCompress(output_batch->tuple_data.c_str(), size, compressed_output, &compressed_size); if (LIKELY(compressed_size < size)) { compression_scratch_.resize(compressed_size); output_batch->tuple_data.swap(compression_scratch_); output_batch->is_compressed = true; } VLOG_ROW << "uncompressed size: " << size << ", compressed size: " << compressed_size; } // The size output_batch would be if we didn't compress tuple_data (will be equal to // actual batch size if tuple_data isn't compressed) return GetBatchSize(*output_batch) - output_batch->tuple_data.size() + size; } // TODO: we want our input_batch's tuple_data to come from our (not yet implemented) // global runtime memory segment; how do we get thrift to allocate it from there? // maybe change line (in Data_types.cc generated from Data.thrift) // xfer += iprot->readString(this->tuple_data[_i9]); // to allocated string data in special mempool // (change via python script that runs over Data_types.cc) RowBatch::RowBatch(const RowDescriptor& row_desc, const TRowBatch& input_batch) : has_in_flight_row_(false), num_rows_(input_batch.num_rows), capacity_(num_rows_), num_tuples_per_row_(input_batch.row_tuples.size()), row_desc_(row_desc), tuple_ptrs_(new Tuple*[num_rows_ * input_batch.row_tuples.size()]), tuple_data_pool_(new MemPool()) { if (input_batch.is_compressed) { // Decompress tuple data into data pool const char* compressed_data = input_batch.tuple_data.c_str(); size_t compressed_size = input_batch.tuple_data.size(); size_t uncompressed_size; bool success = snappy::GetUncompressedLength(compressed_data, compressed_size, &uncompressed_size); DCHECK(success) << "snappy::GetUncompressedLength failed"; char* data = reinterpret_cast<char*>(tuple_data_pool_->Allocate(uncompressed_size)); success = snappy::RawUncompress(compressed_data, compressed_size, data); DCHECK(success) << "snappy::RawUncompress failed"; } else { // Tuple data uncompressed, copy directly into data pool uint8_t* data = tuple_data_pool_->Allocate(input_batch.tuple_data.size()); memcpy(data, input_batch.tuple_data.c_str(), input_batch.tuple_data.size()); } // convert input_batch.tuple_offsets into pointers int tuple_idx = 0; for (vector<int32_t>::const_iterator offset = input_batch.tuple_offsets.begin(); offset != input_batch.tuple_offsets.end(); ++offset) { if (*offset == -1) { tuple_ptrs_[tuple_idx++] = NULL; } else { tuple_ptrs_[tuple_idx++] = reinterpret_cast<Tuple*>(tuple_data_pool_->GetDataPtr(*offset)); } } // check whether we have string slots // TODO: do that during setup (part of RowDescriptor c'tor?) bool has_string_slots = false; const vector<TupleDescriptor*>& tuple_descs = row_desc_.tuple_descriptors(); for (int i = 0; i < tuple_descs.size(); ++i) { if (!tuple_descs[i]->string_slots().empty()) { has_string_slots = true; break; } } if (!has_string_slots) return; // convert string offsets contained in tuple data into pointers for (int i = 0; i < num_rows_; ++i) { TupleRow* row = GetRow(i); vector<TupleDescriptor*>::const_iterator desc = tuple_descs.begin(); for (int j = 0; desc != tuple_descs.end(); ++desc, ++j) { if ((*desc)->string_slots().empty()) continue; Tuple* t = row->GetTuple(j); if (t == NULL) continue; vector<SlotDescriptor*>::const_iterator slot = (*desc)->string_slots().begin(); for (; slot != (*desc)->string_slots().end(); ++slot) { DCHECK_EQ((*slot)->type(), TYPE_STRING); StringValue* string_val = t->GetStringSlot((*slot)->tuple_offset()); string_val->ptr = reinterpret_cast<char*>( tuple_data_pool_->GetDataPtr(reinterpret_cast<intptr_t>(string_val->ptr))); } } } } int RowBatch::GetBatchSize(const TRowBatch& batch) { int result = batch.tuple_data.size(); result += batch.row_tuples.size() * sizeof(TTupleId); result += batch.tuple_offsets.size() * sizeof(int32_t); return result; } void RowBatch::Swap(RowBatch* other) { DCHECK(row_desc_.Equals(other->row_desc_)); DCHECK_EQ(num_tuples_per_row_, other->num_tuples_per_row_); DCHECK_EQ(tuple_ptrs_size_, other->tuple_ptrs_size_); // The destination row batch should be empty. DCHECK(!has_in_flight_row_); DCHECK(io_buffers_.empty()); DCHECK_EQ(tuple_data_pool_->GetTotalChunkSizes(), 0); std::swap(has_in_flight_row_, other->has_in_flight_row_); std::swap(num_rows_, other->num_rows_); std::swap(capacity_, other->capacity_); std::swap(tuple_ptrs_, other->tuple_ptrs_); std::swap(io_buffers_, other->io_buffers_); tuple_data_pool_.swap(other->tuple_data_pool_); } // TODO: consider computing size of batches as they are built up int RowBatch::TotalByteSize() { int result = 0; for (int i = 0; i < num_rows_; ++i) { TupleRow* row = GetRow(i); const vector<TupleDescriptor*>& tuple_descs = row_desc_.tuple_descriptors(); vector<TupleDescriptor*>::const_iterator desc = tuple_descs.begin(); for (int j = 0; desc != tuple_descs.end(); ++desc, ++j) { Tuple* tuple = row->GetTuple(j); if (tuple == NULL) continue; result += (*desc)->byte_size(); vector<SlotDescriptor*>::const_iterator slot = (*desc)->string_slots().begin(); for (; slot != (*desc)->string_slots().end(); ++slot) { DCHECK_EQ((*slot)->type(), TYPE_STRING); if (tuple->IsNull((*slot)->null_indicator_offset())) continue; StringValue* string_val = tuple->GetStringSlot((*slot)->tuple_offset()); result += string_val->len; } } } return result; } }
39.718182
90
0.690776
wangxnhit
538f7a95ec0fc797cd6c48bc656ddfa4e735e33c
2,837
hh
C++
deps/live555/include/MPEG2TransportStreamFramer.hh
robort-yuan/AI-EXPRESS
56f86d03afbb09f42c21958c8cd9f2f1c6437f48
[ "BSD-2-Clause" ]
98
2020-09-11T13:52:44.000Z
2022-03-23T11:52:02.000Z
deps/live555/include/MPEG2TransportStreamFramer.hh
robort-yuan/AI-EXPRESS
56f86d03afbb09f42c21958c8cd9f2f1c6437f48
[ "BSD-2-Clause" ]
8
2020-10-19T14:23:30.000Z
2022-03-16T01:00:07.000Z
deps/live555/include/MPEG2TransportStreamFramer.hh
robort-yuan/AI-EXPRESS
56f86d03afbb09f42c21958c8cd9f2f1c6437f48
[ "BSD-2-Clause" ]
28
2020-09-17T14:20:35.000Z
2022-01-10T16:26:00.000Z
/********** This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.) This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********/ // "liveMedia" // Copyright (c) 1996-2017 Live Networks, Inc. All rights reserved. // A filter that passes through (unchanged) chunks that contain an integral number // of MPEG-2 Transport Stream packets, but returning (in "fDurationInMicroseconds") // an updated estimate of the time gap between chunks. // C++ header #ifndef _MPEG2_TRANSPORT_STREAM_FRAMER_HH #define _MPEG2_TRANSPORT_STREAM_FRAMER_HH #ifndef _FRAMED_FILTER_HH #include "FramedFilter.hh" #endif #ifndef _HASH_TABLE_HH #include "HashTable.hh" #endif class MPEG2TransportStreamFramer: public FramedFilter { public: static MPEG2TransportStreamFramer* createNew(UsageEnvironment& env, FramedSource* inputSource); u_int64_t tsPacketCount() const { return fTSPacketCount; } void changeInputSource(FramedSource* newInputSource) { fInputSource = newInputSource; } void clearPIDStatusTable(); void setNumTSPacketsToStream(unsigned long numTSRecordsToStream); void setPCRLimit(float pcrLimit); protected: MPEG2TransportStreamFramer(UsageEnvironment& env, FramedSource* inputSource); // called only by createNew() virtual ~MPEG2TransportStreamFramer(); private: // Redefined virtual functions: virtual void doGetNextFrame(); virtual void doStopGettingFrames(); private: static void afterGettingFrame(void* clientData, unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned durationInMicroseconds); void afterGettingFrame1(unsigned frameSize, struct timeval presentationTime); Boolean updateTSPacketDurationEstimate(unsigned char* pkt, double timeNow); private: u_int64_t fTSPacketCount; double fTSPacketDurationEstimate; HashTable* fPIDStatusTable; u_int64_t fTSPCRCount; Boolean fLimitNumTSPacketsToStream; unsigned long fNumTSPacketsToStream; // used iff "fLimitNumTSPacketsToStream" is True Boolean fLimitTSPacketsToStreamByPCR; float fPCRLimit; // used iff "fLimitTSPacketsToStreamByPCR" is True }; #endif
35.911392
90
0.767712
robort-yuan
53901f30edf43af56736ef423811ad9ee2e3fdb5
2,728
cpp
C++
uppdev/MyDbase/dbRecordSet.cpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
2
2016-04-07T07:54:26.000Z
2020-04-14T12:37:34.000Z
uppdev/MyDbase/dbRecordSet.cpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
null
null
null
uppdev/MyDbase/dbRecordSet.cpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
null
null
null
#include "dbase.h" dbRecordSet::dbRecordSet() { ptr = 0; } void dbRecordSet::Reset() { recordSet.Clear(); ptr = 0; } void dbRecordSet::Add(int record, dbRecord &rec, Array<String> &orderField, Array<unsigned int> &ordStyle) { unsigned int j, n, f, l, p, k; k = orderField.GetCount(); #ifdef _WITH_DEBUG RLOG("# keys: " + FormatInt(k)); #endif // sorting the new record in the correct position with three key (field) level bool s; f=0; l=recordSet.GetCount(), p=l; for(n=0; n<k; n++) { s=true; for(j=f; j<l; j++) { if(ordStyle[n] == MTDB_ASC && s) { if(IsBiggerEqual(recordSet[j].Get(orderField[n]), AsString(rec.GetValue(orderField[n])))) { p = j; f = j; s = false; } } if(ordStyle[n] == MTDB_DESC && s) { if(IsSmallerEqual(recordSet[j].Get(orderField[n]), AsString(rec.GetValue(orderField[n])))) { p = j; f = j; s = false; } } if(!s) { if(!IsEqual(recordSet[j].Get(orderField[n]), AsString(rec.GetValue(orderField[n])))) { l = j; } } } if(s) { p=l; f=l; } } recordSet.Insert((int)p, record, rec.Get()); return; } bool dbRecordSet::Next() { if(recordSet.GetCount()>0 && ptr<(recordSet.GetCount()-1)) { ptr++; return true; } return false; } bool dbRecordSet::Previous() { if(recordSet.GetCount()>0 && ptr>0) { ptr--; return true; } return false; } bool dbRecordSet::GoTo(int recno) { int q; if((q = recordSet.Find(recno)) >= 0) { ptr = q; return true; } return false; } Value& dbRecordSet::GetValue(int field) { VectorMap<String, Value> &rec = recordSet[ptr]; Value &res = rec[field]; return res; } Value dbRecordSet::GetValue(const String &field) { VectorMap<String, Value> &rec = recordSet[ptr]; int q = rec.Find(field); if(q >= 0) { Value res = rec[q]; return res; } else return Nuller(); } const Value dbRecordSet::GetValue(const String &field) const { return GetValue(field); } Value dbRecordSet::GetValue(int record, const String &field) { VectorMap<String, Value> &rec = recordSet.Get(record); int q = rec.Find(field); Value res = rec[q]; return res; } const Value dbRecordSet::GetValue(int record, const String &field) const { return GetValue(record, field); } Value& dbRecordSet::GetValue(int record, int field) { //VectorMap<String, Value> &rec = recordSet.Get(record); //return rec[field]; int q = recordSet.Find(record); if(q < 0) { VectorMap<String, Value> r; recordSet.GetAdd(record, r); q = recordSet.GetCount()-1; } VectorMap<String, Value> &rec = recordSet[q]; return rec[field]; }
22.360656
109
0.595674
dreamsxin
5393b719ef0294534bff4c75e8f68335bc127ddb
5,424
cpp
C++
SmallWorld/LibCpp/Graph.cpp
pchaigno/smallworld
8a22099753166b4fea0bf93a1a7298fed51fef8c
[ "MIT" ]
1
2018-11-08T17:20:56.000Z
2018-11-08T17:20:56.000Z
SmallWorld/LibCpp/Graph.cpp
pchaigno/smallworld
8a22099753166b4fea0bf93a1a7298fed51fef8c
[ "MIT" ]
null
null
null
SmallWorld/LibCpp/Graph.cpp
pchaigno/smallworld
8a22099753166b4fea0bf93a1a7298fed51fef8c
[ "MIT" ]
null
null
null
#include "Graph.h" /** * @returns The size of the graph. */ int Graph::size() const { return this->succs.size(); } /** * Checks if an unit can go from one point to all others of the map. * @param map The map. * @param size The size of the map. * @returns True if all squares of the map are accessible from one. */ bool Graph::isConnectedGraph(Tile** map, int size) { Graph graph = Graph(map, size); vector<Point> composant = graph.getConnectedComposant(graph.getKeys()[0]); return composant.size() == graph.size(); } /** * Converts the map to a graph. * Squares are vertices if they're not sea. * Two squares are connected if they're adjacent (an unit can go from one to the other in one move). * Note: Sea is represented by 1. * @param map The map randomly generated. * @param size The size of the map. * @returns The graph as a map of adjacent vertices by vertex. */ Graph::Graph(Tile** map, int size) { for(int i=0; i<size; i++) { for(int j=0; j<size; j++) { Point pos = Point(i, j); if(!pos.isSea(map)) { vector<Point> adjacents; Point adjacent; for(int x=i-1; x<=i+1; x+=2) { adjacent = Point(x, j); if(x>=0 && x<size && !adjacent.isSea(map)) { adjacents.push_back(adjacent); } } for(int y=j-1; y<=j+1; y+=2) { adjacent = Point(i, y); if(y>=0 && y<size && !adjacent.isSea(map)) { adjacents.push_back(adjacent); } } this->succs.insert(make_pair(pos, adjacents)); } } } } /** * Tarjan algorithm to find a connected composant from a starting vertex. * @param vertex The vertex to start. * @returns The connected composant containing vertex. */ vector<Point> Graph::getConnectedComposant(const Point& vertex) const { // Attributes integers to each vertex: Point* vertices = new Point[this->size()]; int j=0; for(map<Point, vector<Point>>::const_iterator it = this->succs.begin(); it!=this->succs.end(); ++it) { vertices[j] = it->first; j++; } // Initialization: int* p = new int[this->succs.size()]; int* d = new int[this->succs.size()]; int* n = new int[this->succs.size()]; int* num = new int[this->succs.size()]; int numA = -1; for(int i=0; i<this->succs.size(); i++) { num[i] = -1; p[i] = -1; d[i] = this->succs.at(vertices[i]).size(); n[i] = -1; if(vertices[i] == vertex) { numA = i; } } int index = numA; int k = 0; num[numA] = 0; p[numA] = numA; // Core of the algorithm: while(n[index]+1!=d[index] || index!=numA) { if(n[index]+1 == d[index]) { index = p[index]; } else { n[index]++; Point pt = this->succs.at(vertices[index])[n[index]]; j = Graph::getIndex(pt, vertices, this->size()); if(p[j] == -1) { p[j] = index; index = j; k++; num[index] = k; } } } // Check if the graph is connected: if(k+1 == this->size()) { return this->getKeys(); } vector<Point> connectedVertices; for(int i=0; i<this->size(); i++) { if(num[i]<=k && num[i]!=-1) { connectedVertices.push_back(vertices[i]); } } return connectedVertices; } /** * @returns The keys of the graph object. */ vector<Point> Graph::getKeys() const { vector<Point> keys; for(map<Point, vector<Point>>::const_iterator it = this->succs.begin(); it!=this->succs.end(); ++it) { keys.push_back(it->first); } return keys; } /** * @returns The keys of the graph object. */ Point* Graph::getKeysAsArray() const { Point* keys = new Point[this->size()]; int i = 0; for(map<Point, vector<Point>>::const_iterator it = this->succs.begin(); it!=this->succs.end(); ++it) { keys[i] = it->first; i++; } return keys; } /** * Roy-Marshall algorithm to find the best cost routing in a graph. * @param vertices The vertices as an array (to associate a Point to a number). * @returns The matrix with the best cost for each origin-destination couple. */ int** Graph::getBestCostRouting(Point* vertices) const { // Initialization: int** routes = new int*[this->size()]; int** costs = new int*[this->size()]; for(int i=0; i<this->size(); i++) { routes[i] = new int[this->size()]; costs[i] = new int[this->size()]; for(int j=0; j<this->size(); j++) { if(inArray(vertices[j], this->succs.at(vertices[i]))) { routes[i][j] = j; costs[i][j] = 1; } else { routes[i][j] = -1; costs[i][j] = INT_MAX; } } } // Roy-Marshall's algorithm: for(int i=0; i<this->size(); i++) { for(int x=0; x<this->size(); x++) { if(routes[x][i] != -1) { for(int y=0; y<this->size(); y++) { if(routes[i][y] != -1) { if(costs[x][y] > costs[x][i]+costs[i][y]) { costs[x][y] = costs[x][i] + costs[i][y]; routes[x][y] = routes[x][i]; } } } } } } return costs; } /** * Checks if a point if in a vector of points. * @param pt The point. * @param points The vector of points. * @returns True if pt is in points. */ bool Graph::inArray(const Point& pt, const vector<Point>& points) { for(int i=0; i<points.size(); i++) { if(pt == points[i]) { return true; } } return false; } /** * Checks if a point if in a vector of points. * @param pt The point. * @param points The array of points. * @param nbPoints The number of points in the array. * @returns The index of pt in points or -1 if pt is not in points. */ int Graph::getIndex(const Point& pt, Point* points, int nbPoints) { for(int i=0; i<nbPoints; i++) { if(pt == points[i]) { return i; } } return -1; }
25.111111
103
0.599558
pchaigno
5396350bb63761ed2223415e6eb90979556befc4
45,917
cxx
C++
main/sal/qa/osl/socket/osl_Socket2.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/sal/qa/osl/socket/osl_Socket2.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/sal/qa/osl/socket/osl_Socket2.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sal.hxx" /** test coder preface: 1. the BSD socket function will meet "unresolved external symbol error" on Windows platform if you are not including ws2_32.lib in makefile.mk, the including format will be like this: .IF "$(GUI)" == "WNT" SHL1STDLIBS += $(SOLARLIBDIR)$/cppunit.lib SHL1STDLIBS += ws2_32.lib .ENDIF likewise on Solaris platform. .IF "$(GUI)" == "UNX" SHL1STDLIBS+=$(SOLARLIBDIR)$/libcppunit$(DLLPOSTFIX).a SHL1STDLIBS += -lsocket -ldl -lnsl .ENDIF 2. since the Socket implementation of osl is only IPv4 oriented, our test are mainly focus on IPv4 category. 3. some fragment of Socket source implementation are lack of comment so it is hard for testers guess what the exact functionality or usage of a member. Hope the Socket section's comment will be added. 4. following functions are declared but not implemented: inline sal_Bool SAL_CALL operator== (const SocketAddr & Addr) const; */ //------------------------------------------------------------------------ // include files //------------------------------------------------------------------------ #include "gtest/gtest.h" //#include "osl_Socket_Const.h" #include "sockethelper.hxx" using namespace osl; using namespace rtl; #define IP_PORT_FTP 21 #define IP_PORT_TELNET 23 #define IP_PORT_HTTP2 8080 #define IP_PORT_INVAL 99999 #define IP_PORT_POP3 110 #define IP_PORT_NETBIOS 139 #define IP_PORT_MYPORT 8881 #define IP_PORT_MYPORT1 8882 #define IP_PORT_MYPORT5 8886 #define IP_PORT_MYPORT6 8887 #define IP_PORT_MYPORT7 8895 #define IP_PORT_MYPORT8 8896 #define IP_PORT_MYPORT9 8897 //------------------------------------------------------------------------ // helper functions //------------------------------------------------------------------------ // just used to test socket::close() when accepting class AcceptorThread : public Thread { ::osl::AcceptorSocket asAcceptorSocket; ::rtl::OUString aHostIP; sal_Bool bOK; protected: void SAL_CALL run( ) { ::osl::SocketAddr saLocalSocketAddr( aHostIP, IP_PORT_MYPORT9 ); ::osl::StreamSocket ssStreamConnection; asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //integer not sal_Bool : sal_True); sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr ); if ( sal_True != bOK1 ) { printf("# AcceptorSocket bind address failed.\n" ) ; return; } sal_Bool bOK2 = asAcceptorSocket.listen( 1 ); if ( sal_True != bOK2 ) { printf("# AcceptorSocket listen address failed.\n" ) ; return; } asAcceptorSocket.enableNonBlockingMode( sal_False ); oslSocketResult eResult = asAcceptorSocket.acceptConnection( ssStreamConnection ); if (eResult != osl_Socket_Ok ) { bOK = sal_True; printf("AcceptorThread: acceptConnection failed! \n"); } } public: AcceptorThread(::osl::AcceptorSocket & asSocket, ::rtl::OUString const& aBindIP ) : asAcceptorSocket( asSocket ), aHostIP( aBindIP ) { bOK = sal_False; } sal_Bool isOK() { return bOK; } ~AcceptorThread( ) { if ( isRunning( ) ) { asAcceptorSocket.shutdown(); printf("# error: Acceptor thread not terminated.\n" ); } } }; namespace osl_Socket { /** testing the methods: inline Socket( ); inline Socket( const Socket & socket ); inline Socket( oslSocket socketHandle ); inline Socket( oslSocket socketHandle, __sal_NoAcquire noacquire ); */ /** test writer's comment: class Socket can not be initialized by its protected constructor, though the protected constructor is the most convenient way to create a new socket. it only allow the method of C function osl_createSocket like: ::osl::Socket sSocket( osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ) ); the use of C method lost some of the transparent of tester using C++ wrapper. */ class ctors : public ::testing::Test { public: oslSocket sHandle; // initialization void SetUp( ) { sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); } void TearDown( ) { sHandle = NULL; } }; // class ctors TEST_F(ctors, ctors_none) { /// Socket constructor. // ::osl::Socket sSocket(); ASSERT_TRUE(1 == 1) << "test for ctors_none constructor function: check if the socket was created successfully, if no exception occurred"; } TEST_F(ctors, ctors_acquire) { /// Socket constructor. ::osl::Socket sSocket( sHandle ); ASSERT_TRUE(osl_Socket_TypeStream == sSocket.getType( )) << "test for ctors_acquire constructor function: check if the socket was created successfully"; } TEST_F(ctors, ctors_no_acquire) { /// Socket constructor. ::osl::Socket sSocket( sHandle, SAL_NO_ACQUIRE ); ASSERT_TRUE(osl_Socket_TypeStream == sSocket.getType( )) << " test for ctors_no_acquire constructor function: check if the socket was created successfully"; } TEST_F(ctors, ctors_copy_ctor) { ::osl::Socket sSocket( sHandle ); /// Socket copy constructor. ::osl::Socket copySocket( sSocket ); ASSERT_TRUE(osl_Socket_TypeStream == copySocket.getType( )) << " test for ctors_copy_ctor constructor function: create new Socket instance using copy constructor"; } TEST_F(ctors, ctors_TypeRaw) { #ifdef WNT oslSocket sHandleRaw = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeRaw, osl_Socket_ProtocolIp ); // LLA: ? ::osl::Socket sSocket( sHandleRaw ); ASSERT_TRUE(sHandleRaw != NULL) << " type osl_Socket_TypeRaw socket create failed on UNX "; #else oslSocket sHandleRaw = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeRaw, osl_Socket_ProtocolIp ); ASSERT_TRUE(sHandleRaw == NULL) << " can't create socket with type osl_Socket_TypeRaw within UNX is ok."; #endif } TEST_F(ctors, ctors_family_Ipx) { oslSocket sHandleIpx = osl_createSocket( osl_Socket_FamilyIpx, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); ASSERT_TRUE(sHandleIpx != NULL) << " family osl_Socket_FamilyIpx socket create failed! "; ::osl::Socket sSocket( sHandleIpx ); //, SAL_NO_ACQUIRE ); printf("#Type is %d \n", sSocket.getType( ) ); ASSERT_TRUE(osl_Socket_TypeStream == sSocket.getType( )) << " test for create new Socket instance that family is osl_Socket_FamilyIpx"; } /** testing the methods: inline Socket& SAL_CALL operator= ( oslSocket socketHandle); inline Socket& SAL_CALL operator= (const Socket& sock); inline sal_Bool SAL_CALL operator==( const Socket& rSocket ) const ; inline sal_Bool SAL_CALL operator==( const oslSocket socketHandle ) const; */ class operators : public ::testing::Test { public: oslSocket sHandle; // initialization void SetUp( ) { sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); } void TearDown( ) { sHandle = NULL; } }; // class operators /** test writer's comment: the assignment operator does not support direct assinment like: ::osl::Socket sSocket = sHandle. */ TEST_F(operators, operators_assignment_handle) { ::osl::Socket sSocket(sHandle); ::osl::Socket assignSocket = sSocket.getHandle(); ASSERT_TRUE(osl_Socket_TypeStream == assignSocket.getType( )) << "test for operators_assignment_handle function: test the assignment operator."; } TEST_F(operators, operators_assignment) { ::osl::Socket sSocket( sHandle ); ::osl::Socket assignSocket = sSocket; ASSERT_TRUE(osl_Socket_TypeStream == assignSocket.getType( )) << "test for operators_assignment function: assignment operator"; } TEST_F(operators, operators_equal_handle_001) { /// Socket constructor. ::osl::Socket sSocket( sHandle ); ::osl::Socket equalSocket = sSocket; ASSERT_TRUE(equalSocket == sHandle) << " test for operators_equal_handle_001 function: check equal."; } TEST_F(operators, operators_equal_handle_002) { /// Socket constructor. ::osl::Socket equalSocket( osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeDgram, osl_Socket_ProtocolIp ) ); ASSERT_TRUE(!( equalSocket == sHandle )) << " test for operators_equal_handle_001 function: check unequal."; } TEST_F(operators, operators_equal_001) { ::osl::Socket sSocket( sHandle ); /// Socket copy constructor. ::osl::Socket equalSocket( sSocket ); ASSERT_TRUE(equalSocket == sSocket) << " test for operators_equal function: check equal."; } TEST_F(operators, operators_equal_002) { ::osl::Socket sSocket( sHandle ); /// Socket copy constructor. ::osl::Socket equalSocket( osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeDgram, osl_Socket_ProtocolIp ) ); ASSERT_TRUE(!( equalSocket == sSocket )) << " test for operators_equal_002 function: check unequal."; } /** testing the methods: inline void SAL_CALL shutdown( oslSocketDirection Direction = osl_Socket_DirReadWrite ); inline void SAL_CALL close(); */ class close : public ::testing::Test { public: oslSocket sHandle; // initialization void SetUp( ) { sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); } void TearDown( ) { sHandle = NULL; } }; // class close TEST_F(close, close_001) { ::osl::Socket sSocket(sHandle); sSocket.close(); ASSERT_TRUE(sSocket.getHandle() == sHandle) << "test for close_001 function: this function is reserved for test."; } TEST_F(close, close_002) { // This blocks forever on FreeBSD #if defined(LINUX) ::osl::AcceptorSocket asSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); AcceptorThread myAcceptorThread( asSocket, rtl::OUString::createFromAscii("127.0.0.1") ); myAcceptorThread.create(); thread_sleep( 1 ); //when accepting, close the socket, the thread will not block for accepting //man close:Any locks held on the file it was associated with, and owned by the process, are removed asSocket.close(); //thread_sleep( 2 ); myAcceptorThread.join(); ASSERT_TRUE(myAcceptorThread.isOK() == sal_True) << "test for close when is accepting: the socket will quit accepting status."; #endif } // to cover "if ( pSockAddrIn->sin_addr.s_addr == htonl(INADDR_ANY) )" in osl_closeSocket( ) TEST_F(close, close_003) { // This blocks forever on FreeBSD #if defined(LINUX) ::osl::AcceptorSocket asSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream ); AcceptorThread myAcceptorThread( asSocket, rtl::OUString::createFromAscii("0.0.0.0") ); myAcceptorThread.create(); thread_sleep( 1 ); asSocket.close(); myAcceptorThread.join(); ASSERT_TRUE(myAcceptorThread.isOK() == sal_True) << "test for close when is accepting: the socket will quit accepting status."; #endif } /** testing the method: inline void SAL_CALL getLocalAddr( SocketAddr &Addr ) const; */ class getLocalAddr : public ::testing::Test { public: oslSocket sHandle; // initialization void SetUp( ) { sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); } void TearDown( ) { sHandle = NULL; } }; // class getLocalAddr // get the Address of the local end of the socket TEST_F(getLocalAddr, getLocalAddr_001) { ::osl::Socket sSocket(sHandle); ::osl::SocketAddr saBindSocketAddr( rtl::OUString::createFromAscii("127.0.0.1"), IP_PORT_MYPORT8 ); ::osl::SocketAddr saLocalSocketAddr; sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); sal_Bool bOK1 = sSocket.bind( saBindSocketAddr ); ::rtl::OUString suError1 = ::rtl::OUString::createFromAscii("Socket bind fail:") + sSocket.getErrorAsString(); ASSERT_TRUE(sal_True == bOK1) << suError1.pData; sSocket.getLocalAddr( saLocalSocketAddr ); sal_Bool bOK = compareUString( saLocalSocketAddr.getHostname( 0 ), sSocket.getLocalHost() ) ; ASSERT_TRUE(sal_True == bOK) << "test for getLocalAddr function: first create a new socket, then a socket address, bind them, and check the address."; } /** testing the method: inline sal_Int32 SAL_CALL getLocalPort() const; */ class getLocalPort : public ::testing::Test { public: oslSocket sHandle; // initialization void SetUp( ) { sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); } void TearDown( ) { sHandle = NULL; } }; // class getLocalPort TEST_F(getLocalPort, getLocalPort_001) { ::osl::Socket sSocket(sHandle); ::osl::SocketAddr saBindSocketAddr( rtl::OUString::createFromAscii("127.0.0.1"), IP_PORT_MYPORT7 ); // aHostIp1 localhost ::osl::SocketAddr saLocalSocketAddr; sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); sal_Bool bOK1 = sSocket.bind( saBindSocketAddr ); ::rtl::OUString suError1 = ::rtl::OUString::createFromAscii("Socket bind fail:") + sSocket.getErrorAsString(); ASSERT_TRUE(sal_True == bOK1) << suError1.pData; sal_Bool bOK = ( IP_PORT_MYPORT7 == sSocket.getLocalPort( ) ); ASSERT_TRUE(sal_True == bOK) << "test for getLocalPort function: first create a new socket, then a socket address, bind them, and check the port."; } /** test writer's comment: the invalid port number can not be set by giving invalid port number such as 99999 or -1, it will convert to ( x mod 65535 ), so it will always be valid, the only instance that the getLocalPort returns OSL_INVALID_PORT is when saSocketAddr itself is an invalid one, that is , the IP or host name can not be found, then the created socket address is not valid. */ TEST_F(getLocalPort, getLocalPort_002) { ::osl::SocketAddr saBindSocketAddr( rtl::OUString::createFromAscii("123.45.67.89"), IP_PORT_TELNET); #ifdef WNT ::osl::Socket sSocket(sHandle); sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); // sal_True); sSocket.bind( saBindSocketAddr ); //Invalid IP, so bind should fail ::rtl::OUString suError = outputError(::rtl::OUString::valueOf(sSocket.getLocalPort( )), ::rtl::OUString::valueOf((sal_Int32)OSL_INVALID_PORT), "test for getLocalPort function: first create a new socket, then an invalid socket address, bind them, and check the port assigned."); sal_Bool bOK = ( OSL_INVALID_PORT == sSocket.getLocalPort( ) ); (void)bOK; #else //on Unix, if Addr is not an address of type osl_Socket_FamilyInet, it returns OSL_INVALID_PORT ::rtl::OUString suError = ::rtl::OUString::createFromAscii( "on Unix, if Addr is not an address of type osl_Socket_FamilyInet, it returns OSL_INVALID_PORT, but can not create Addr of that case"); #endif ASSERT_TRUE(sal_False) << suError.pData; } TEST_F(getLocalPort, getLocalPort_003) { ::osl::Socket sSocket(sHandle); ::osl::SocketAddr saBindSocketAddr( getLocalIP(), IP_PORT_INVAL); sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); sal_Bool bOK1 = sSocket.bind( saBindSocketAddr ); ::rtl::OUString suError1 = ::rtl::OUString::createFromAscii("Socket bind fail:") + sSocket.getErrorAsString(); ASSERT_TRUE(sal_True == bOK1) << suError1.pData; ::rtl::OUString suError = outputError(::rtl::OUString::valueOf(sSocket.getLocalPort( )), ::rtl::OUString::createFromAscii("34463"), "test for getLocalPort function: first create a new socket, then an invalid socket address, bind them, and check the port assigned"); sal_Bool bOK = ( sSocket.getLocalPort( ) >= 1 && sSocket.getLocalPort( ) <= 65535); ASSERT_TRUE(sal_True == bOK) << suError.pData; } /** testing the method: inline ::rtl::OUString SAL_CALL getLocalHost() const; Mindyliu: on Linux, at first it will check the binded in /etc/hosts, if it has the binded IP, it will return the hostname in it; else if the binded IP is "127.0.0.1", it will return "localhost", if it's the machine's ethernet ip such as "129.158.217.90", it will return hostname of current processor such as "aegean.PRC.Sun.COM" */ class getLocalHost : public ::testing::Test { public: oslSocket sHandle; // initialization void SetUp( ) { sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); } void TearDown( ) { sHandle = NULL; } }; // class getLocalHost TEST_F(getLocalHost, getLocalHost_001) { ::osl::Socket sSocket(sHandle); //port number from IP_PORT_HTTP1 to IP_PORT_MYPORT6, mindyliu ::osl::SocketAddr saBindSocketAddr( rtl::OUString::createFromAscii("127.0.0.1"), IP_PORT_MYPORT6 ); sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); sal_Bool bOK1 = sSocket.bind( saBindSocketAddr ); ::rtl::OUString suError1 = ::rtl::OUString::createFromAscii("Socket bind fail:") + sSocket.getErrorAsString(); ASSERT_TRUE(sal_True == bOK1) << suError1.pData; sal_Bool bOK; ::rtl::OUString suError; #ifdef WNT bOK = compareUString( sSocket.getLocalHost( ), getThisHostname( ) ) ; suError = outputError(sSocket.getLocalHost( ), getThisHostname( ), "test for getLocalHost function: create localhost socket and check name"); #else ::rtl::OUString aUString = ::rtl::OUString::createFromAscii( (const sal_Char *) "localhost" ); sal_Bool bRes1, bRes2; bRes1 = compareUString( sSocket.getLocalHost( ), aUString ) ; bRes2 = compareUString( sSocket.getLocalHost( ), saBindSocketAddr.getHostname(0) ) ; bOK = bRes1 || bRes2; suError = outputError(sSocket.getLocalHost( ), aUString, "test for getLocalHost function: create localhost socket and check name"); #endif ASSERT_TRUE(sal_True == bOK) << suError.pData; } TEST_F(getLocalHost, getLocalHost_002) { ::osl::Socket sSocket(sHandle); ::osl::SocketAddr saBindSocketAddr( rtl::OUString::createFromAscii("123.45.67.89"), IP_PORT_POP3); ::osl::SocketAddr saLocalSocketAddr; sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); sSocket.bind( saBindSocketAddr ); //Invalid IP, so bind should fail sal_Bool bOK = compareUString( sSocket.getLocalHost( ), rtl::OUString::createFromAscii("") ) ; ::rtl::OUString suError = outputError(sSocket.getLocalHost( ), rtl::OUString::createFromAscii(""), "test for getLocalHost function: getLocalHost with invalid SocketAddr"); ASSERT_TRUE(sal_True == bOK) << suError.pData; } /** testing the methods: inline void SAL_CALL getPeerAddr( SocketAddr & Addr) const; inline sal_Int32 SAL_CALL getPeerPort() const; inline ::rtl::OUString SAL_CALL getPeerHost() const; */ class getPeer : public ::testing::Test { public: oslSocket sHandle; TimeValue *pTimeout; ::osl::AcceptorSocket asAcceptorSocket; ::osl::ConnectorSocket csConnectorSocket; // initialization void SetUp( ) { pTimeout = ( TimeValue* )malloc( sizeof( TimeValue ) ); pTimeout->Seconds = 3; pTimeout->Nanosec = 0; sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); } void TearDown( ) { free( pTimeout ); sHandle = NULL; asAcceptorSocket.close( ); csConnectorSocket.close( ); } }; // class getPeer TEST_F(getPeer, getPeer_001) { ::osl::SocketAddr saLocalSocketAddr( rtl::OUString::createFromAscii("127.0.0.1"), IP_PORT_MYPORT ); ::osl::SocketAddr saTargetSocketAddr( rtl::OUString::createFromAscii("127.0.0.1"), IP_PORT_MYPORT ); ::osl::SocketAddr saPeerSocketAddr( rtl::OUString::createFromAscii("129.158.217.202"), IP_PORT_FTP ); ::osl::StreamSocket ssConnection; asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); /// launch server socket sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr ); ASSERT_TRUE(sal_True == bOK1) << "AcceptorSocket bind '127.0.0.1' address failed."; sal_Bool bOK2 = asAcceptorSocket.listen( 1 ); ASSERT_TRUE(sal_True == bOK2) << "AcceptorSocket listen failed."; asAcceptorSocket.enableNonBlockingMode( sal_True ); asAcceptorSocket.acceptConnection(ssConnection); /// waiting for incoming connection... /// launch client socket csConnectorSocket.connect( saTargetSocketAddr, pTimeout ); /// connecting to server... /// get peer information csConnectorSocket.getPeerAddr( saPeerSocketAddr );/// connected. sal_Int32 peerPort = csConnectorSocket.getPeerPort( ); ::rtl::OUString peerHost = csConnectorSocket.getPeerHost( ); ASSERT_TRUE(( sal_True == compareSocketAddr( saPeerSocketAddr, saLocalSocketAddr ) )&& ( sal_True == compareUString( peerHost, saLocalSocketAddr.getHostname( 0 ) ) ) && ( peerPort == saLocalSocketAddr.getPort( ) )) << "test for getPeer function: setup a connection and then get the peer address, port and host from client side."; } /** testing the methods: inline sal_Bool SAL_CALL bind(const SocketAddr& LocalInterface); */ class bind : public ::testing::Test { public: oslSocket sHandle; // initialization void SetUp( ) { sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); } void TearDown( ) { sHandle = NULL; } }; // class bind TEST_F(bind, bind_001) { ::osl::Socket sSocket(sHandle); //bind must use local IP address ---mindyliu ::osl::SocketAddr saBindSocketAddr( getLocalIP(), IP_PORT_MYPORT5 ); sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); sal_Bool bOK1 = sSocket.bind( saBindSocketAddr ); ASSERT_TRUE(sal_True == bOK1) << "Socket bind fail."; sal_Bool bOK2 = compareUString( sSocket.getLocalHost( ), saBindSocketAddr.getHostname( ) ) ; sSocket.close(); ASSERT_TRUE(sal_True == bOK2) << "test for bind function: bind a valid address."; } TEST_F(bind, bind_002) { ::osl::Socket sSocket(sHandle); ::osl::SocketAddr saBindSocketAddr( rtl::OUString::createFromAscii("123.45.67.89"), IP_PORT_NETBIOS ); ::osl::SocketAddr saLocalSocketAddr; sSocket.setOption( osl_Socket_OptionReuseAddr, 1); // sal_True); sal_Bool bOK1 = sSocket.bind( saBindSocketAddr ); sal_Bool bOK2 = compareUString( sSocket.getLocalHost( ), getThisHostname( ) ) ; ASSERT_TRUE(( sal_False == bOK1 ) && ( sal_False == bOK2 )) << "test for bind function: bind a valid address."; } /** testing the methods: inline sal_Bool SAL_CALL isRecvReady(const TimeValue *pTimeout = 0) const; */ class isRecvReady : public ::testing::Test { public: oslSocket sHandle; TimeValue *pTimeout; ::osl::AcceptorSocket asAcceptorSocket; ::osl::ConnectorSocket csConnectorSocket; // initialization void SetUp( ) { pTimeout = ( TimeValue* )malloc( sizeof( TimeValue ) ); pTimeout->Seconds = 3; pTimeout->Nanosec = 0; sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); } void TearDown( ) { free( pTimeout ); sHandle = NULL; asAcceptorSocket.close( ); csConnectorSocket.close( ); } }; // class isRecvReady TEST_F(isRecvReady, isRecvReady_001) { ::osl::SocketAddr saLocalSocketAddr( rtl::OUString::createFromAscii("127.0.0.1"), IP_PORT_MYPORT1 ); ::osl::SocketAddr saTargetSocketAddr( rtl::OUString::createFromAscii("127.0.0.1"), IP_PORT_MYPORT1 ); ::osl::SocketAddr saPeerSocketAddr( rtl::OUString::createFromAscii("129.158.217.202"), IP_PORT_FTP ); ::osl::StreamSocket ssConnection; /// launch server socket asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); // sal_True); sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr ); ASSERT_TRUE(sal_True == bOK1) << "AcceptorSocket bind address failed."; sal_Bool bOK2 = asAcceptorSocket.listen( 1 ); ASSERT_TRUE(sal_True == bOK2) << "AcceptorSocket listen failed."; asAcceptorSocket.enableNonBlockingMode( sal_True ); asAcceptorSocket.acceptConnection(ssConnection); /// waiting for incoming connection... /// launch client socket csConnectorSocket.connect( saTargetSocketAddr, pTimeout ); /// connecting to server... /// is receive ready? sal_Bool bOK3 = asAcceptorSocket.isRecvReady( pTimeout ); ASSERT_TRUE(( sal_True == bOK3 )) << "test for isRecvReady function: setup a connection and then check if it can transmit data."; } /** testing the methods: inline sal_Bool SAL_CALL isSendReady(const TimeValue *pTimeout = 0) const; */ class isSendReady : public ::testing::Test { public: oslSocket sHandle; TimeValue *pTimeout; ::osl::AcceptorSocket asAcceptorSocket; ::osl::ConnectorSocket csConnectorSocket; // initialization void SetUp( ) { pTimeout = ( TimeValue* )malloc( sizeof( TimeValue ) ); pTimeout->Seconds = 3; pTimeout->Nanosec = 0; sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); } void TearDown( ) { free( pTimeout ); sHandle = NULL; asAcceptorSocket.close( ); csConnectorSocket.close( ); } }; // class isSendReady TEST_F(isSendReady, isSendReady_001) { ::osl::SocketAddr saLocalSocketAddr( rtl::OUString::createFromAscii("127.0.0.1"), IP_PORT_MYPORT ); ::osl::SocketAddr saTargetSocketAddr( rtl::OUString::createFromAscii("127.0.0.1"), IP_PORT_MYPORT ); ::osl::SocketAddr saPeerSocketAddr( rtl::OUString::createFromAscii("129.158.217.202"), IP_PORT_FTP ); ::osl::StreamSocket ssConnection; /// launch server socket asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr ); ASSERT_TRUE(sal_True == bOK1) << "AcceptorSocket bind address failed."; sal_Bool bOK2 = asAcceptorSocket.listen( 1 ); ASSERT_TRUE(sal_True == bOK2) << "AcceptorSocket listen failed."; asAcceptorSocket.enableNonBlockingMode( sal_True ); asAcceptorSocket.acceptConnection(ssConnection); /// waiting for incoming connection... /// launch client socket csConnectorSocket.connect( saTargetSocketAddr, pTimeout ); /// connecting to server... /// is send ready? sal_Bool bOK3 = csConnectorSocket.isSendReady( pTimeout ); ASSERT_TRUE(( sal_True == bOK3 )) << "test for isSendReady function: setup a connection and then check if it can transmit data."; } /** testing the methods: inline oslSocketType SAL_CALL getType() const; */ class getType : public ::testing::Test { public: oslSocket sHandle; // initialization void SetUp( ) { } void TearDown( ) { sHandle = NULL; } }; // class getType TEST_F(getType, getType_001) { sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); ::osl::Socket sSocket(sHandle); ASSERT_TRUE(osl_Socket_TypeStream == sSocket.getType( )) << "test for getType function: get type of socket."; } TEST_F(getType, getType_002) { sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeDgram, osl_Socket_ProtocolIp ); ::osl::Socket sSocket(sHandle); ASSERT_TRUE(osl_Socket_TypeDgram == sSocket.getType( )) << "test for getType function: get type of socket."; } #ifdef UNX // mindy: since on LINUX and SOLARIS, Raw type socket can not be created, so do not test getType() here // mindy: and add one test case to test creating Raw type socket--> ctors_TypeRaw() TEST_F(getType, getType_003) { ASSERT_TRUE(sal_True) << "test for getType function: get type of socket.this is not passed in (LINUX, SOLARIS), the osl_Socket_TypeRaw, type socket can not be created."; } #else TEST_F(getType, getType_003) { sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeRaw, osl_Socket_ProtocolIp ); ::osl::Socket sSocket(sHandle); ASSERT_TRUE(osl_Socket_TypeRaw == sSocket.getType( )) << "test for getType function: get type of socket."; } #endif /** testing the methods: inline sal_Int32 SAL_CALL getOption( oslSocketOption Option, void* pBuffer, sal_uInt32 BufferLen, oslSocketOptionLevel Level= osl_Socket_LevelSocket) const; inline sal_Int32 getOption( oslSocketOption option ) const; */ class getOption : public ::testing::Test { public: oslSocket sHandle; // initialization void SetUp( ) { } void TearDown( ) { sHandle = NULL; } }; // class getOption /** test writer's comment: in oslSocketOption, the osl_Socket_OptionType denote 1 as osl_Socket_TypeStream. 2 as osl_Socket_TypeDgram, etc which is not mapping the oslSocketType enum. differ in 1. */ TEST_F(getOption, getOption_001) { sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); ::osl::Socket sSocket(sHandle); sal_Int32 * pType = ( sal_Int32 * )malloc( sizeof ( sal_Int32 ) ); *pType = 0; sSocket.getOption( osl_Socket_OptionType, pType, sizeof ( sal_Int32 ) ); sal_Bool bOK = ( SOCK_STREAM == *pType ); // there is a TypeMap(socket.c) which map osl_Socket_TypeStream to SOCK_STREAM on UNX, and SOCK_STREAM != osl_Socket_TypeStream //sal_Bool bOK = ( TYPE_TO_NATIVE(osl_Socket_TypeStream) == *pType ); free( pType ); ASSERT_TRUE(sal_True == bOK) << "test for getOption function: get type option of socket."; } // getsockopt error TEST_F(getOption, getOption_004) { sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeDgram, osl_Socket_ProtocolIp ); ::osl::Socket sSocket(sHandle); sal_Bool * pbDontRoute = ( sal_Bool * )malloc( sizeof ( sal_Bool ) ); sal_Int32 nRes = sSocket.getOption( osl_Socket_OptionInvalid, pbDontRoute, sizeof ( sal_Bool ) ); free( pbDontRoute ); ASSERT_TRUE(nRes == -1) << "test for getOption function: get invalid option of socket, should return -1."; } TEST_F(getOption, getOption_simple_001) { sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeDgram, osl_Socket_ProtocolIp ); ::osl::Socket sSocket(sHandle); sal_Bool bOK = ( sal_False == sSocket.getOption( osl_Socket_OptionDontRoute ) ); ASSERT_TRUE(sal_True == bOK) << "test for getOption function: get debug option of socket."; } TEST_F(getOption, getOption_simple_002) { sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeDgram, osl_Socket_ProtocolIp ); ::osl::Socket sSocket(sHandle); sal_Bool bOK = ( sal_False == sSocket.getOption( osl_Socket_OptionDebug ) ); ASSERT_TRUE(sal_True == bOK) << "test for getOption function: get debug option of socket."; } /** testing the methods: inline sal_Bool SAL_CALL setOption( oslSocketOption Option, void* pBuffer, sal_uInt32 BufferLen, oslSocketOptionLevel Level= osl_Socket_LevelSocket ) const; */ class setOption : public ::testing::Test { public: TimeValue *pTimeout; // LLA: maybe there is an error in the source, // as long as I remember, if a derived class do not overload all ctors there is a problem. ::osl::AcceptorSocket asAcceptorSocket; void SetUp( ) { } void TearDown( ) { asAcceptorSocket.close( ); } }; // class setOption // LLA: // getSocketOption returns BufferLen, or -1 if something failed // setSocketOption returns sal_True, if option could stored // else sal_False TEST_F(setOption, setOption_001) { /// set and get option. int nBufferLen = sizeof ( sal_Int32); // LLA: SO_DONTROUTE expect an integer boolean, what ever it is, it's not sal_Bool! sal_Int32 * pbDontRouteSet = ( sal_Int32 * )malloc( sizeof ( sal_Int32 ) ); *pbDontRouteSet = 1; // sal_True; sal_Int32 * pGetBuffer = ( sal_Int32 * )malloc( sizeof ( sal_Int32 ) ); *pGetBuffer = 0; // maybe asAcceptorSocket is not right initialized sal_Bool b1 = asAcceptorSocket.setOption( osl_Socket_OptionDontRoute, pbDontRouteSet, nBufferLen ); ASSERT_TRUE(( sal_True == b1 )) << "setOption function failed."; sal_Int32 n2 = asAcceptorSocket.getOption( osl_Socket_OptionDontRoute, pGetBuffer, nBufferLen ); ASSERT_TRUE(( n2 == nBufferLen )) << "getOption function failed."; // on Linux, the value of option is 1, on Solaris, it's 16, but it's not important the exact value, // just judge it is zero or not! sal_Bool bOK = ( 0 != *pGetBuffer ); printf("#setOption_001: getOption is %d \n", *pGetBuffer); // toggle check, set to 0 *pbDontRouteSet = 0; sal_Bool b3 = asAcceptorSocket.setOption( osl_Socket_OptionDontRoute, pbDontRouteSet, sizeof ( sal_Int32 ) ); ASSERT_TRUE(( sal_True == b3 )) << "setOption function failed."; sal_Int32 n4 = asAcceptorSocket.getOption( osl_Socket_OptionDontRoute, pGetBuffer, nBufferLen ); ASSERT_TRUE(( n4 == nBufferLen )) << "getOption (DONTROUTE) function failed."; sal_Bool bOK2 = ( 0 == *pGetBuffer ); printf("#setOption_001: getOption is %d \n", *pGetBuffer); // LLA: sal_Bool * pbDontTouteSet = ( sal_Bool * )malloc( sizeof ( sal_Bool ) ); // LLA: *pbDontTouteSet = sal_True; // LLA: sal_Bool * pbDontTouteGet = ( sal_Bool * )malloc( sizeof ( sal_Bool ) ); // LLA: *pbDontTouteGet = sal_False; // LLA: asAcceptorSocket.setOption( osl_Socket_OptionDontRoute, pbDontTouteSet, sizeof ( sal_Bool ) ); // LLA: asAcceptorSocket.getOption( osl_Socket_OptionDontRoute, pbDontTouteGet, sizeof ( sal_Bool ) ); // LLA: ::rtl::OUString suError = outputError(::rtl::OUString::valueOf((sal_Int32)*pbDontTouteGet), // LLA: ::rtl::OUString::valueOf((sal_Int32)*pbDontTouteSet), // LLA: "test for setOption function: set osl_Socket_OptionDontRoute and then check"); // LLA: // LLA: sal_Bool bOK = ( sal_True == *pbDontTouteGet ); // LLA: free( pbDontTouteSet ); // LLA: free( pbDontTouteGet ); ASSERT_TRUE(( sal_True == bOK ) && (sal_True == bOK2)) << "test for setOption function: set option of a socket and then check."; free( pbDontRouteSet ); free( pGetBuffer ); // LLA: ASSERT_TRUE(sal_True == bOK) << suError; } TEST_F(setOption, setOption_002) { /// set and get option. // sal_Int32 * pbLingerSet = ( sal_Int32 * )malloc( nBufferLen ); // *pbLingerSet = 7; // sal_Int32 * pbLingerGet = ( sal_Int32 * )malloc( nBufferLen ); /* struct */linger aLingerSet; sal_Int32 nBufferLen = sizeof( struct linger ); aLingerSet.l_onoff = 1; aLingerSet.l_linger = 7; linger aLingerGet; asAcceptorSocket.setOption( osl_Socket_OptionLinger, &aLingerSet, nBufferLen ); sal_Int32 n1 = asAcceptorSocket.getOption( osl_Socket_OptionLinger, &aLingerGet, nBufferLen ); ASSERT_TRUE(( n1 == nBufferLen )) << "getOption (SO_LINGER) function failed."; //printf("#setOption_002: getOption is %d \n", aLingerGet.l_linger); sal_Bool bOK = ( 7 == aLingerGet.l_linger ); ASSERT_TRUE(sal_True == bOK) << "test for setOption function: set option of a socket and then check. "; } TEST_F(setOption, setOption_003) { linger aLingerSet; aLingerSet.l_onoff = 1; aLingerSet.l_linger = 7; sal_Bool b1 = asAcceptorSocket.setOption( osl_Socket_OptionLinger, &aLingerSet, 0 ); printUString( asAcceptorSocket.getErrorAsString( ) ); ASSERT_TRUE(( b1 == sal_False )) << "setOption (SO_LINGER) function failed for optlen is 0."; } TEST_F(setOption, setOption_simple_001) { /// set and get option. asAcceptorSocket.setOption( osl_Socket_OptionDontRoute, 1 ); //sal_True ); sal_Bool bOK = ( 0 != asAcceptorSocket.getOption( osl_Socket_OptionDontRoute ) ); printf("setOption_simple_001(): getoption is %d \n", asAcceptorSocket.getOption( osl_Socket_OptionDontRoute ) ); ASSERT_TRUE(( sal_True == bOK )) << "test for setOption function: set option of a socket and then check."; } TEST_F(setOption, setOption_simple_002) { /// set and get option. // LLA: this does not work, due to the fact that SO_LINGER is a structure // LLA: asAcceptorSocket.setOption( osl_Socket_OptionLinger, 7 ); // LLA: sal_Bool bOK = ( 7 == asAcceptorSocket.getOption( osl_Socket_OptionLinger ) ); // LLA: ASSERT_TRUE(// LLA: ( sal_True == bOK )) << "test for setOption function: set option of a socket and then check."; } /** testing the method: inline sal_Bool SAL_CALL enableNonBlockingMode( sal_Bool bNonBlockingMode); */ class enableNonBlockingMode : public ::testing::Test { public: ::osl::AcceptorSocket asAcceptorSocket; }; // class enableNonBlockingMode TEST_F(enableNonBlockingMode, enableNonBlockingMode_001) { ::osl::SocketAddr saLocalSocketAddr( rtl::OUString::createFromAscii("127.0.0.1"), IP_PORT_MYPORT ); ::osl::StreamSocket ssConnection; /// launch server socket asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr ); ASSERT_TRUE(sal_True == bOK1) << "AcceptorSocket bind address failed."; sal_Bool bOK2 = asAcceptorSocket.listen( 1 ); ASSERT_TRUE(sal_True == bOK2) << "AcceptorSocket listen failed."; asAcceptorSocket.enableNonBlockingMode( sal_True ); asAcceptorSocket.acceptConnection(ssConnection); /// waiting for incoming connection... /// if reach this statement, it is non-blocking mode, since acceptConnection will blocked by default. sal_Bool bOK = sal_True; asAcceptorSocket.close( ); ASSERT_TRUE(( sal_True == bOK )) << "test for enableNonBlockingMode function: launch a server socket and make it non blocking. if it can pass the acceptConnection statement, it is non-blocking"; } /** testing the method: inline sal_Bool SAL_CALL isNonBlockingMode() const; */ class isNonBlockingMode : public ::testing::Test { public: ::osl::AcceptorSocket asAcceptorSocket; }; // class isNonBlockingMode TEST_F(isNonBlockingMode, isNonBlockingMode_001) { ::osl::SocketAddr saLocalSocketAddr( rtl::OUString::createFromAscii("127.0.0.1"), IP_PORT_MYPORT ); ::osl::StreamSocket ssConnection; /// launch server socket asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); // sal_True); sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr ); ASSERT_TRUE(sal_True == bOK1) << "AcceptorSocket bind address failed."; sal_Bool bOK2 = asAcceptorSocket.listen( 1 ); ASSERT_TRUE(sal_True == bOK2) << "AcceptorSocket listen failed."; sal_Bool bOK3 = asAcceptorSocket.isNonBlockingMode( ); asAcceptorSocket.enableNonBlockingMode( sal_True ); asAcceptorSocket.acceptConnection(ssConnection); /// waiting for incoming connection... /// if reach this statement, it is non-blocking mode, since acceptConnection will blocked by default. sal_Bool bOK4 = asAcceptorSocket.isNonBlockingMode( ); asAcceptorSocket.close( ); ASSERT_TRUE(( sal_False == bOK3 ) && ( sal_True == bOK4 )) << "test for isNonBlockingMode function: launch a server socket and make it non blocking. it is expected to change from blocking mode to non-blocking mode."; } /** testing the method: inline void SAL_CALL clearError() const; */ class clearError : public ::testing::Test { public: oslSocket sHandle; // initialization void SetUp( ) { sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); } void TearDown( ) { sHandle = NULL; } }; // class clearError TEST_F(clearError, clearError_001) { ::osl::Socket sSocket(sHandle); ::osl::SocketAddr saBindSocketAddr( rtl::OUString::createFromAscii("123.45.67.89"), IP_PORT_HTTP2 ); ::osl::SocketAddr saLocalSocketAddr; sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); sSocket.bind( saBindSocketAddr );//build an error "osl_Socket_E_AddrNotAvail" oslSocketError seBind = sSocket.getError( ); sSocket.clearError( ); ASSERT_TRUE(osl_Socket_E_None == sSocket.getError( ) && seBind != osl_Socket_E_None) << "test for clearError function: trick an error called sSocket.getError( ), and then clear the error states, check the result."; } /** testing the methods: inline oslSocketError getError() const; inline ::rtl::OUString getErrorAsString( ) const; */ class getError : public ::testing::Test { public: oslSocket sHandle; // initialization void SetUp( ) { sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); } void TearDown( ) { sHandle = NULL; } }; // class getError TEST_F(getError, getError_001) { ::osl::Socket sSocket(sHandle); ::osl::SocketAddr saBindSocketAddr( rtl::OUString::createFromAscii("127.0.0.1"), IP_PORT_FTP ); ::osl::SocketAddr saLocalSocketAddr; ASSERT_TRUE(osl_Socket_E_None == sSocket.getError( )) << "test for getError function: should get no error."; } TEST_F(getError, getError_002) { ::osl::Socket sSocket(sHandle); ::osl::SocketAddr saBindSocketAddr( rtl::OUString::createFromAscii("123.45.67.89"), IP_PORT_FTP ); ::osl::SocketAddr saLocalSocketAddr; sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True); sSocket.bind( saBindSocketAddr );//build an error "osl_Socket_E_AddrNotAvail" //on Solaris, the error no is EACCES, but it has no mapped value, so getError() returned osl_Socket_E_InvalidError. #if defined(SOLARIS) ASSERT_TRUE(osl_Socket_E_InvalidError == sSocket.getError( )) << "trick an error called sSocket.getError( ), check the getError result.Failed on Solaris, returned osl_Socket_E_InvalidError because no entry to map the errno EACCES. "; #else //while on Linux & Win32, the errno is EADDRNOTAVAIL, getError returned osl_Socket_E_AddrNotAvail. ASSERT_TRUE(osl_Socket_E_AddrNotAvail == sSocket.getError( )) << "trick an error called sSocket.getError( ), check the getError result.Failed on Solaris, returned osl_Socket_E_InvalidError because no entry to map the errno EACCES. Passed on Linux & Win32"; #endif } /** testing the methods: inline oslSocket getHandle() const; */ class getHandle : public ::testing::Test { public: oslSocket sHandle; // initialization void SetUp( ) { sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp ); } void TearDown( ) { sHandle = NULL; } }; // class getHandle TEST_F(getHandle, getHandle_001) { ::osl::Socket sSocket(sHandle); ::osl::Socket assignSocket = sSocket.getHandle(); ASSERT_TRUE(osl_Socket_TypeStream == assignSocket.getType( )) << "test for operators_assignment_handle function: test the assignment operator."; } TEST_F(getHandle, getHandle_002) { ::osl::Socket sSocket( sHandle ); ::osl::Socket assignSocket ( sSocket.getHandle( ) ); ASSERT_TRUE(osl_Socket_TypeStream == assignSocket.getType( )) << "test for operators_assignment function: assignment operator"; } } // namespace osl_Socket int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
36.616427
264
0.673106
Grosskopf
53988aa7ba416ddd19afa84395af5a3fae8bd86d
1,714
cpp
C++
test/quiver/disjoint_set.cpp
Fytch/Quiver
572c59bbc7aaef0e61318d6d0feaf5771b38cfdb
[ "MIT" ]
null
null
null
test/quiver/disjoint_set.cpp
Fytch/Quiver
572c59bbc7aaef0e61318d6d0feaf5771b38cfdb
[ "MIT" ]
1
2018-11-28T12:55:50.000Z
2018-11-28T12:55:50.000Z
test/quiver/disjoint_set.cpp
Fytch/Quiver
572c59bbc7aaef0e61318d6d0feaf5771b38cfdb
[ "MIT" ]
1
2018-08-19T16:48:23.000Z
2018-08-19T16:48:23.000Z
/* * Quiver - A graph theory library * Copyright (C) 2018 Josua Rieder (josua.rieder1996@gmail.com) * Distributed under the MIT License. * See the enclosed file LICENSE.txt for further information. */ #include <catch2/catch.hpp> #include <quiver.hpp> using namespace quiver; TEST_CASE("disjoint_set", "[quiver][fundamentals]") { const std::size_t N = 10; disjoint_set<> set(N); CHECK(set.sets() == N); for(std::size_t i = 0; i < N; ++i) { CHECK(set.find(i) == i); CHECK(set.cardinality(i) == 1); } set.unite(1, 2); set.unite(2, 3); set.unite(7, 6); set.unite(5, 6); CHECK(set.sets() == N - 4); CHECK(set.cardinality(0) == 1); CHECK(set.cardinality(1) == 3); CHECK(set.cardinality(2) == 3); CHECK(set.cardinality(3) == 3); CHECK(set.find(1) == set.find(2)); CHECK(set.find(1) == set.find(3)); CHECK(set.cardinality(4) == 1); CHECK(set.cardinality(5) == 3); CHECK(set.cardinality(6) == 3); CHECK(set.cardinality(7) == 3); CHECK(set.find(5) == set.find(6)); CHECK(set.find(5) == set.find(7)); CHECK(set.cardinality(8) == 1); CHECK(set.cardinality(9) == 1); set.unite(7, 2); set.unite(3, 9); CHECK(set.sets() == N - 6); CHECK(set.cardinality(0) == 1); CHECK(set.cardinality(4) == 1); CHECK(set.cardinality(8) == 1); CHECK(set.cardinality(1) == 7); CHECK(set.cardinality(2) == 7); CHECK(set.cardinality(3) == 7); CHECK(set.cardinality(5) == 7); CHECK(set.cardinality(6) == 7); CHECK(set.cardinality(7) == 7); CHECK(set.cardinality(9) == 7); CHECK(set.find(1) == set.find(2)); CHECK(set.find(1) == set.find(3)); CHECK(set.find(1) == set.find(5)); CHECK(set.find(1) == set.find(6)); CHECK(set.find(1) == set.find(7)); CHECK(set.find(1) == set.find(9)); }
23.805556
63
0.620187
Fytch
5398b26338a516064b89ca836a8e8e18f2bf5567
2,366
hpp
C++
include/xtr/detail/align.hpp
uilianries/xtr
b1dccc51b024369e6c1a2f6d3fcf5f405735289b
[ "MIT" ]
10
2021-09-25T10:40:55.000Z
2022-03-19T01:05:05.000Z
include/xtr/detail/align.hpp
uilianries/xtr
b1dccc51b024369e6c1a2f6d3fcf5f405735289b
[ "MIT" ]
2
2021-09-24T12:59:08.000Z
2021-09-24T19:17:47.000Z
include/xtr/detail/align.hpp
uilianries/xtr
b1dccc51b024369e6c1a2f6d3fcf5f405735289b
[ "MIT" ]
1
2021-09-24T13:45:29.000Z
2021-09-24T13:45:29.000Z
// Copyright 2014, 2019 Chris E. Holloway // // 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. #ifndef XTR_DETAIL_ALIGN_HPP #define XTR_DETAIL_ALIGN_HPP #include <bit> #include <cassert> #include <cstddef> #include <cstdint> #include <type_traits> namespace xtr::detail { // value is unchanged if it is already aligned template<typename T> constexpr T align(T value, T alignment) noexcept { static_assert(std::is_unsigned_v<T>, "value must be unsigned"); assert(std::has_single_bit(alignment)); return (value + (alignment - 1)) & ~(alignment - 1); } // Align is only a template argument to allow it to be used with // assume_aligned. Improvement: Make Align a plain argument if it is // possible to do so while still marking the return value as aligned. template<std::size_t Align, typename T> __attribute__((assume_aligned(Align))) T* align(T* ptr) noexcept { static_assert( std::is_same_v<std::remove_cv_t<T>, std::byte> || std::is_same_v<std::remove_cv_t<T>, char> || std::is_same_v<std::remove_cv_t<T>, unsigned char> || std::is_same_v<std::remove_cv_t<T>, signed char>, "value must be a char or byte pointer"); return reinterpret_cast<T*>(align(std::uintptr_t(ptr), Align)); } } #endif
40.793103
81
0.707946
uilianries
539a24d2037b6ea2b2309ec0dd0fdbb5473e839d
1,118
cpp
C++
src/gmp_integer_vector.cpp
dhruvdcoder/poly-metic
c8ec0ba30dd052c6b41a0cdeb58318d063cf9eac
[ "Apache-2.0" ]
1
2021-12-14T16:16:12.000Z
2021-12-14T16:16:12.000Z
src/gmp_integer_vector.cpp
dhruvdcoder/poly-metic
c8ec0ba30dd052c6b41a0cdeb58318d063cf9eac
[ "Apache-2.0" ]
3
2018-09-02T04:38:52.000Z
2018-09-09T20:14:16.000Z
src/gmp_integer_vector.cpp
dhruvdcoder/poly-metic
c8ec0ba30dd052c6b41a0cdeb58318d063cf9eac
[ "Apache-2.0" ]
null
null
null
// Copyright 2018 Dhruvesh Nikhilkumar Patel // // 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 <gmpxx.h> #include <iostream> #include <vector> int main() { std::vector<std::vector<mpz_class>> Integers {{1,2},{34,45}}; // Integers.push_back(1); // Integers.push_back(2); // Integers.push_back(34); // Integers.push_back(45); std::cout<<"Integers = ("; size_t i =0; for (;i<2;i++) { std::cout<< "("; for(size_t j=0;j<2;j++) { std::cout<<Integers[i][j]<<","; } std::cout<<")"; } std::cout<<")"<<std::endl; return 0; }
29.421053
77
0.635957
dhruvdcoder
539b28bd3fd509a516e0026b76ec38fb73d66154
795
cpp
C++
demo/ref_object.cpp
bianc2018/Sim
8c37f65d28b99598c1c75a650e4da36a460cf600
[ "MIT" ]
1
2021-01-19T15:25:25.000Z
2021-01-19T15:25:25.000Z
demo/ref_object.cpp
bianc2018/Sim
8c37f65d28b99598c1c75a650e4da36a460cf600
[ "MIT" ]
null
null
null
demo/ref_object.cpp
bianc2018/Sim
8c37f65d28b99598c1c75a650e4da36a460cf600
[ "MIT" ]
null
null
null
#include "Logger.hpp" #include "TaskPool.hpp" #include "RefObject.hpp" class faketype { public: faketype() { SIM_LINFO("faketype() "<<SIM_HEX(this)); } ~faketype() { SIM_LINFO("~faketype " << SIM_HEX(this)); } }; sim::RefObject<faketype> temp; void* run(void* pd) { sim::RefObject<faketype> ref = temp; SIM_LINFO("ref count=" << ref.getcount()); return NULL; } int main(int argc, char* argv[]) { SIM_LOG_CONSOLE(sim::LInfo); SIM_FUNC_DEBUG(); sim::RefObject<faketype> ref(new faketype()); SIM_LINFO("ref count=" << ref.getcount()); sim::RefObject<faketype> ref1 = ref; temp = ref1; sim::TaskPool pool(8); for (int i = 0; i < 10000; ++i) pool.Post(run, NULL, NULL); while (ref.getcount() >3) { SIM_LINFO("ref count=" << ref.getcount()); } getchar(); return 0; }
17.666667
46
0.642767
bianc2018
53a00aa768d7073cafbf71f51d524ea23faded2c
669
cpp
C++
RapyutaTest.cpp
abhis2007/Algorithms-1
7637209c5aa52c1afd8be1884d018673d26f5c1f
[ "MIT" ]
26
2019-04-05T07:10:15.000Z
2022-01-08T02:35:19.000Z
RapyutaTest.cpp
abhis2007/Algorithms-1
7637209c5aa52c1afd8be1884d018673d26f5c1f
[ "MIT" ]
2
2019-04-25T15:47:54.000Z
2019-09-03T06:46:05.000Z
RapyutaTest.cpp
abhis2007/Algorithms-1
7637209c5aa52c1afd8be1884d018673d26f5c1f
[ "MIT" ]
8
2019-04-05T08:58:50.000Z
2020-07-03T01:53:58.000Z
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int arr[n + 1]; for (int i = 1; i <= n; ++i) { cin >> arr[i]; } int dp[n + 1][n + 1]; memset(dp, sizeof(dp), 0); int res = INT_MIN; dp[1][0] = 0; dp[1][1] = arr[1]; for (int i = 2; i <= n; ++i) { for (int j = 0; j <= i; ++j) { if(j == 0){ dp[i][j] = 0; continue; } if(j == i) { dp[i][j] = arr[i] * j + dp[i - 1][j - 1]; } else { dp[i][j] = max(dp[i - 1][j], arr[i] * j + dp[i - 1][j - 1]); } res = max(res, dp[i][j]); } } cout << res; return 0; }
19.114286
73
0.355755
abhis2007
53a23198e743b9d58184647433429dd85d8499a8
5,867
cpp
C++
cpgf/src/scriptbind/gscriptbind.cpp
mousepawmedia/libdeps
b004d58d5b395ceaf9fdc993cfb00e91334a5d36
[ "BSD-3-Clause" ]
null
null
null
cpgf/src/scriptbind/gscriptbind.cpp
mousepawmedia/libdeps
b004d58d5b395ceaf9fdc993cfb00e91334a5d36
[ "BSD-3-Clause" ]
null
null
null
cpgf/src/scriptbind/gscriptbind.cpp
mousepawmedia/libdeps
b004d58d5b395ceaf9fdc993cfb00e91334a5d36
[ "BSD-3-Clause" ]
null
null
null
#include "cpgf/scriptbind/gscriptbind.h" #include "cpgf/gglobal.h" #include "../pinclude/gbindcommon.h" #include "../pinclude/gscriptbindapiimpl.h" namespace cpgf { GScriptObject::GScriptObject(const GScriptConfig & config) : config(config), owner(nullptr) { } GScriptObject::GScriptObject(const GScriptObject & other) : config(other.config), owner(nullptr) { } GScriptObject::~GScriptObject() { } GScriptValue GScriptObject::getValue(const char * name) { return this->doGetValue(name); } extern int Error_ScriptBinding_CantSetScriptValue; void GScriptObject::setValue(const char * name, const GScriptValue & value) { switch(value.getType()) { // We can't set any script object back to script engine, // otherwise, cross module portability will be broken. case GScriptValue::typeScriptObject: case GScriptValue::typeScriptFunction: case GScriptValue::typeScriptArray: raiseCoreException(Error_ScriptBinding_CantSetScriptValue); break; default: this->doSetValue(name, value); break; } } void GScriptObject::bindClass(const char * name, IMetaClass * metaClass) { this->setValue(name, GScriptValue::fromClass(metaClass)); } void GScriptObject::bindEnum(const char * name, IMetaEnum * metaEnum) { this->setValue(name, GScriptValue::fromEnum(metaEnum)); } void GScriptObject::bindFundamental(const char * name, const GVariant & value) { this->setValue(name, GScriptValue::fromFundamental(value)); } void GScriptObject::bindAccessible(const char * name, void * instance, IMetaAccessible * accessible) { this->setValue(name, GScriptValue::fromAccessible(instance, accessible)); } void GScriptObject::bindString(const char * stringName, const char * s) { this->setValue(stringName, GScriptValue::fromString(s)); } void GScriptObject::bindObject(const char * objectName, void * instance, IMetaClass * type, bool transferOwnership) { this->setValue(objectName, GScriptValue::fromObject(instance, type, transferOwnership)); } void GScriptObject::bindRaw(const char * name, const GVariant & value) { this->setValue(name, GScriptValue::fromRaw(value)); } void GScriptObject::bindMethod(const char * name, void * instance, IMetaMethod * method) { this->setValue(name, GScriptValue::fromMethod(instance, method)); } void GScriptObject::bindMethodList(const char * name, IMetaList * methodList) { this->setValue(name, GScriptValue::fromOverloadedMethods(methodList)); } void GScriptObject::bindCoreService(const char * name, IScriptLibraryLoader * libraryLoader) { this->doBindCoreService(name, libraryLoader); } IMetaClass * GScriptObject::getClass(const char * className) { return this->getValue(className).toClass(); } IMetaEnum * GScriptObject::getEnum(const char * enumName) { return this->getValue(enumName).toEnum(); } GVariant GScriptObject::getFundamental(const char * name) { return this->getValue(name).toFundamental(); } std::string GScriptObject::getString(const char * stringName) { return this->getValue(stringName).toString(); } void * GScriptObject::getObject(const char * objectName) { return this->getValue(objectName).toObjectAddress(nullptr, nullptr); } GVariant GScriptObject::getRaw(const char * name) { return this->getValue(name).toRaw(); } IMetaMethod * GScriptObject::getMethod(const char * methodName, void ** outInstance) { return this->getValue(methodName).toMethod(outInstance); } IMetaList * GScriptObject::getMethodList(const char * methodName) { return this->getValue(methodName).toOverloadedMethods(); } GScriptValue::Type GScriptObject::getType(const char * name, IMetaTypedItem ** outMetaTypeItem) { GScriptValue value(this->getValue(name)); if(outMetaTypeItem != nullptr) { *outMetaTypeItem = getTypedItemFromScriptValue(value); } return value.getType(); } bool GScriptObject::valueIsNull(const char * name) { return this->getValue(name).isNull(); } void GScriptObject::nullifyValue(const char * name) { this->setValue(name, GScriptValue::fromNull()); } const GScriptConfig & GScriptObject::getConfig() const { return this->config; } GScriptObject * GScriptObject::getOwner() const { return this->owner; } void GScriptObject::setOwner(GScriptObject * newOwner) { this->owner = newOwner; } bool GScriptObject::isGlobal() const { return this->owner == nullptr; } const char * GScriptObject::getName() const { return this->name.c_str(); } void GScriptObject::setName(const std::string & newName) { this->name = newName; } GScriptValue GScriptObject::createScriptObject(const char * name) { GScriptObject * object = nullptr; const int delimiter = '.'; if(strchr(name, delimiter) == nullptr) { object = this->doCreateScriptObject(name); } else { size_t len = strlen(name); GScopedArray<char> tempName(new char[len + 1]); memmove(tempName.get(), name, len + 1); char * next; char * head = tempName.get(); GScopedPointer<GScriptObject> scriptObject; for(;;) { next = strchr(head, delimiter); if(next != nullptr) { *next = '\0'; } GScriptObject * obj = scriptObject.get(); if(obj == nullptr) { obj = this; } scriptObject.reset(obj->doCreateScriptObject(head)); if(! scriptObject) { break; } if(next == nullptr) { break; } ++next; head = next; } object = scriptObject.take(); } if(object == nullptr) { return GScriptValue(); } else { GScopedInterface<IScriptObject> scriptObject(new ImplScriptObject(object, true)); return GScriptValue::fromScriptObject(scriptObject.get()); } } void GScriptObject::holdObject(IObject * object) { this->objectHolder.push_back(GSharedInterface<IObject>(object)); } } // namespace cpgf
24.344398
116
0.705642
mousepawmedia
53a33854d47f89f9ee86688a4019783b5cf36ffc
569
cpp
C++
qt-creator-opensource-src-4.6.1/src/shared/qbs/tests/auto/blackbox/testdata-qt/auto-qrc/main.cpp
kevinlq/Qt-Creator-Opensource-Study
b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f
[ "MIT" ]
5
2018-12-22T14:49:13.000Z
2022-01-13T07:21:46.000Z
Src/shared/qbs/tests/auto/blackbox/testdata-qt/auto-qrc/main.cpp
kevinlq/QSD
b618fc63dc3aa5a18701c5b23e3ea3cdd253e89a
[ "MIT" ]
null
null
null
Src/shared/qbs/tests/auto/blackbox/testdata-qt/auto-qrc/main.cpp
kevinlq/QSD
b618fc63dc3aa5a18701c5b23e3ea3cdd253e89a
[ "MIT" ]
8
2018-07-17T03:55:48.000Z
2021-12-22T06:37:53.000Z
#include <QFile> #include <iostream> int main() { QFile resource1(":/thePrefix/resource1.txt"); if (!resource1.open(QIODevice::ReadOnly)) return 1; QFile resource2(":/thePrefix/resource2.txt"); if (!resource2.open(QIODevice::ReadOnly)) return 2; QFile resource3(":/theOtherPrefix/resource3.txt"); if (!resource3.open(QIODevice::ReadOnly)) return 3; std::cout << "resource data: " << resource1.readAll().constData() << resource2.readAll().constData() << resource3.readAll().constData() << std::endl; }
29.947368
97
0.636204
kevinlq
53a6d540c52e63dc58070a971baff80f27fd0f77
2,388
cpp
C++
client/include/game/CCheckpoints.cpp
MayconFelipeA/sampvoiceatt
3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff
[ "MIT" ]
368
2015-01-01T21:42:00.000Z
2022-03-29T06:22:22.000Z
client/include/game/CCheckpoints.cpp
MayconFelipeA/sampvoiceatt
3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff
[ "MIT" ]
92
2019-01-23T23:02:31.000Z
2022-03-23T19:59:40.000Z
client/include/game/CCheckpoints.cpp
MayconFelipeA/sampvoiceatt
3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff
[ "MIT" ]
179
2015-02-03T23:41:17.000Z
2022-03-26T08:27:16.000Z
/* Plugin-SDK (Grand Theft Auto San Andreas) source file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #include "CCheckpoints.h" unsigned int MAX_NUM_CHECKPOINTS = 32; unsigned int &CCheckpoints::NumActiveCPts = *(unsigned int *)0xC7C6D4; CCheckpoint *CCheckpoints::m_aCheckPtArray = (CCheckpoint *)0xC7F158; // Converted from cdecl void CCheckpoints::DeleteCP(uint id,ushort type) 0x722FC0 void CCheckpoints::DeleteCP(unsigned int id, unsigned short type) { plugin::Call<0x722FC0, unsigned int, unsigned short>(id, type); } // Converted from cdecl void CCheckpoints::Init(void) 0x722880 void CCheckpoints::Init() { plugin::Call<0x722880>(); } // Converted from cdecl CCheckpoint* CCheckpoints::PlaceMarker(uint id,ushort type,CVector &posn,CVector &direction,float size,uchar red,uchar green,uchar blue,uchar alpha,ushort pulsePeriod,float pulseFraction,short rotateRate) 0x722C40 CCheckpoint* CCheckpoints::PlaceMarker(unsigned int id, unsigned short type, CVector& posn, CVector& direction, float size, unsigned char red, unsigned char green, unsigned char blue, unsigned char alpha, unsigned short pulsePeriod, float pulseFraction, short rotateRate) { return plugin::CallAndReturn<CCheckpoint*, 0x722C40, unsigned int, unsigned short, CVector&, CVector&, float, unsigned char, unsigned char, unsigned char, unsigned char, unsigned short, float, short>(id, type, posn, direction, size, red, green, blue, alpha, pulsePeriod, pulseFraction, rotateRate); } // Converted from cdecl void CCheckpoints::Render(void) 0x726060 void CCheckpoints::Render() { plugin::Call<0x726060>(); } // Converted from cdecl void CCheckpoints::SetHeading(uint id,float angle) 0x722970 void CCheckpoints::SetHeading(unsigned int id, float angle) { plugin::Call<0x722970, unsigned int, float>(id, angle); } // Converted from cdecl void CCheckpoints::Shutdown(void) 0x7228F0 void CCheckpoints::Shutdown() { plugin::Call<0x7228F0>(); } // Converted from cdecl void CCheckpoints::Update(void) 0x7229C0 void CCheckpoints::Update() { plugin::Call<0x7229C0>(); } // Converted from cdecl void CCheckpoints::UpdatePos(uint id,CVector &posn) 0x722900 void CCheckpoints::UpdatePos(unsigned int id, CVector& posn) { plugin::Call<0x722900, unsigned int, CVector&>(id, posn); }
45.923077
302
0.760888
MayconFelipeA
53b09b21c521c6d5830ca64f950aa53d5bd17b6e
4,064
cc
C++
airec/src/model/ListItemsResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
airec/src/model/ListItemsResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
airec/src/model/ListItemsResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * 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. */ #include <alibabacloud/airec/model/ListItemsResult.h> #include <json/json.h> using namespace AlibabaCloud::Airec; using namespace AlibabaCloud::Airec::Model; ListItemsResult::ListItemsResult() : ServiceResult() {} ListItemsResult::ListItemsResult(const std::string &payload) : ServiceResult() { parse(payload); } ListItemsResult::~ListItemsResult() {} void ListItemsResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto resultNode = value["result"]; auto alldetailNode = resultNode["detail"]["detailItem"]; for (auto resultNodedetaildetailItem : alldetailNode) { Result::DetailItem detailItemObject; if(!resultNodedetaildetailItem["author"].isNull()) detailItemObject.author = resultNodedetaildetailItem["author"].asString(); if(!resultNodedetaildetailItem["brandId"].isNull()) detailItemObject.brandId = resultNodedetaildetailItem["brandId"].asString(); if(!resultNodedetaildetailItem["categoryPath"].isNull()) detailItemObject.categoryPath = resultNodedetaildetailItem["categoryPath"].asString(); if(!resultNodedetaildetailItem["channel"].isNull()) detailItemObject.channel = resultNodedetaildetailItem["channel"].asString(); if(!resultNodedetaildetailItem["duration"].isNull()) detailItemObject.duration = resultNodedetaildetailItem["duration"].asString(); if(!resultNodedetaildetailItem["expireTime"].isNull()) detailItemObject.expireTime = resultNodedetaildetailItem["expireTime"].asString(); if(!resultNodedetaildetailItem["itemId"].isNull()) detailItemObject.itemId = resultNodedetaildetailItem["itemId"].asString(); if(!resultNodedetaildetailItem["itemType"].isNull()) detailItemObject.itemType = resultNodedetaildetailItem["itemType"].asString(); if(!resultNodedetaildetailItem["pubTime"].isNull()) detailItemObject.pubTime = resultNodedetaildetailItem["pubTime"].asString(); if(!resultNodedetaildetailItem["shopId"].isNull()) detailItemObject.shopId = resultNodedetaildetailItem["shopId"].asString(); if(!resultNodedetaildetailItem["status"].isNull()) detailItemObject.status = resultNodedetaildetailItem["status"].asString(); if(!resultNodedetaildetailItem["title"].isNull()) detailItemObject.title = resultNodedetaildetailItem["title"].asString(); result_.detail.push_back(detailItemObject); } auto totalNode = resultNode["total"]; if(!totalNode["instanceRecommendItem"].isNull()) result_.total.instanceRecommendItem = std::stol(totalNode["instanceRecommendItem"].asString()); if(!totalNode["queryCount"].isNull()) result_.total.queryCount = std::stol(totalNode["queryCount"].asString()); if(!totalNode["sceneRecommendItem"].isNull()) result_.total.sceneRecommendItem = std::stol(totalNode["sceneRecommendItem"].asString()); if(!totalNode["sceneWeightItem"].isNull()) result_.total.sceneWeightItem = std::stol(totalNode["sceneWeightItem"].asString()); if(!totalNode["totalCount"].isNull()) result_.total.totalCount = std::stol(totalNode["totalCount"].asString()); if(!totalNode["weightItem"].isNull()) result_.total.weightItem = std::stol(totalNode["weightItem"].asString()); if(!value["requestId"].isNull()) requestId_ = value["requestId"].asString(); } std::string ListItemsResult::getRequestId()const { return requestId_; } ListItemsResult::Result ListItemsResult::getResult()const { return result_; }
40.237624
97
0.762549
aliyun