blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
91ab5412cd4404f5356206ef429fc122e5501366 | 0ecf2d067e8fe6cdec12b79bfd68fe79ec222ffd | /ash/public/cpp/app_menu_constants.h | 21d4356287609e6a5021feeebdac3ed7cfe25cf1 | [
"BSD-3-Clause"
] | permissive | yachtcaptain23/browser-android-tabs | e5144cee9141890590d6d6faeb1bdc5d58a6cbf1 | a016aade8f8333c822d00d62738a922671a52b85 | refs/heads/master | 2021-04-28T17:07:06.955483 | 2018-09-26T06:22:11 | 2018-09-26T06:22:11 | 122,005,560 | 0 | 0 | NOASSERTION | 2019-05-17T19:37:59 | 2018-02-19T01:00:10 | null | UTF-8 | C++ | false | false | 2,211 | h | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ASH_PUBLIC_CPP_APP_MENU_CONSTANTS_H_
#define ASH_PUBLIC_CPP_APP_MENU_CONSTANTS_H_
namespace ash {
// Defines command ids used in Shelf and AppList app context menus. These are
// used in histograms, do not remove/renumber entries. If you're adding to this
// enum with the intention that it will be logged, add checks to ensure
// stability of the enum and update the ChromeOSUICommands enum listing in
// tools/metrics/histograms/enums.xml.
// TODO(newcomer): Deprecate duplicate CommandIds after the Touchable App
// Context Menu launch. Delay deprecating these because it will disrupt
// histograms. https://crbug.com/854433
enum CommandId {
// Used by LauncherContextMenu.
MENU_OPEN_NEW = 0,
MENU_CLOSE = 1,
MENU_PIN = 2,
LAUNCH_TYPE_PINNED_TAB = 3,
LAUNCH_TYPE_REGULAR_TAB = 4,
LAUNCH_TYPE_FULLSCREEN = 5,
LAUNCH_TYPE_WINDOW = 6,
MENU_NEW_WINDOW = 7,
MENU_NEW_INCOGNITO_WINDOW = 8,
// Used by AppMenuModelAdapter.
NOTIFICATION_CONTAINER = 9,
// Used by AppContextMenu.
LAUNCH_NEW = 100,
TOGGLE_PIN = 101,
SHOW_APP_INFO = 102,
OPTIONS = 103,
UNINSTALL = 104,
REMOVE_FROM_FOLDER = 105,
APP_CONTEXT_MENU_NEW_WINDOW = 106,
APP_CONTEXT_MENU_NEW_INCOGNITO_WINDOW = 107,
INSTALL = 108,
USE_LAUNCH_TYPE_COMMAND_START = 200,
USE_LAUNCH_TYPE_PINNED = USE_LAUNCH_TYPE_COMMAND_START,
USE_LAUNCH_TYPE_REGULAR = 201,
USE_LAUNCH_TYPE_FULLSCREEN = 202,
USE_LAUNCH_TYPE_WINDOW = 203,
USE_LAUNCH_TYPE_COMMAND_END,
// Range of command ids reserved for launching app shortcuts from context
// menu for Android app. Used by AppContextMenu and LauncherContextMenu.
LAUNCH_APP_SHORTCUT_FIRST = 1000,
LAUNCH_APP_SHORTCUT_LAST = 1999,
COMMAND_ID_COUNT
};
// Minimum padding for children of NotificationMenuView in dips.
constexpr int kNotificationHorizontalPadding = 16;
constexpr int kNotificationVerticalPadding = 8;
// Height of the NotificationItemView in dips.
constexpr int kNotificationItemViewHeight = 48;
} // namespace ash
#endif // ASH_PUBLIC_CPP_APP_MENU_CONSTANTS_H_
| [
"artem@brave.com"
] | artem@brave.com |
81a4e2af4729bd4de7a04de2bf20a5555f0ae0cf | e34b28b281a189888f1481c58b37c8faf2757988 | /LeetCode/LeetCode_096.cpp | 35850e0e9233f1ac9714e750fc20bbb68cc0b263 | [] | no_license | reversed/C | aebafda0615c594a844dee1bb12fc683b9cd0c65 | f6edb643723457276d8542eb7b583addfb6f1a7f | refs/heads/master | 2020-04-10T22:05:26.689390 | 2019-06-22T02:56:26 | 2019-06-22T02:57:23 | 68,095,558 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 383 | cpp | class Solution {
public:
int numTrees(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
vector<int> dp(n+1, 0);
dp[0] = 1; dp[1] = 1;
for (int i = 2; i <= n; ++i)
{
for (int j = 0; j < i; ++j)
{
dp[i] += dp[j] * dp[i-j-1];
}
}
return dp[n];
}
};
| [
"leichen.usst@gmail.com"
] | leichen.usst@gmail.com |
8637f2a2448f6f4d0d458a48d03663f7c0574024 | 28b4979073dfa53705c3993d1fb2ace26461cb19 | /programs/lrw/RwtMgr.h | 3c9a4c07719f5c1c592bdf4bc68a95a7e071b0bc | [] | no_license | yusuke-matsunaga/ym-apps | 51c826e510a91d7c4f6e5c4252a2afb91a5f30ce | 185c9aa876a95fcad4772db2ba270ba8fd53e1ac | refs/heads/master | 2016-09-16T15:38:13.272565 | 2015-11-01T04:33:49 | 2015-11-01T04:33:49 | 38,557,898 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,920 | h | #ifndef RWTMGR_H
#define RWTMGR_H
/// @file RwtMgr.h
/// @brief RwtMgr のヘッダファイル
/// @author Yusuke Matsunaga (松永 裕介)
///
/// Copyright (C) 2005-2012 Yusuke Matsunaga
/// All rights reserved.
#include "YmTools.h"
BEGIN_NAMESPACE_YM
class RwtNode;
//////////////////////////////////////////////////////////////////////
/// @class RwtMgr RwtMgr.h "RwtMgr.h"
/// @brief RwtNode をセットアップするためのクラス
//////////////////////////////////////////////////////////////////////
class RwtMgr
{
public:
/// @brief コンストラクタ
RwtMgr();
/// @brief デストラクタ
~RwtMgr();
public:
/// @brief 初期化する.
void
init();
/// @brief 関数に対するノードを返す.
RwtNode*
find_node(ymuint16 func) const;
/// @brief ノード数を得る.
ymuint
node_num() const;
/// @brief ノードを得る.
/// @param[in] pos 位置番号 ( 0 <= pos < node_num() )
RwtNode*
node(ymuint pos) const;
/// @brief 内容をダンプする.
void
dump(ostream& s) const;
private:
//////////////////////////////////////////////////////////////////////
// 内部で用いられる関数
//////////////////////////////////////////////////////////////////////
/// @brief ノードを設定する.
void
set_node(ymuint id,
ymuint16 func,
bool xor_flag,
RwtNode* child0,
RwtNode* child1,
bool inv0,
bool inv1,
ymuint level,
ymuint volume);
private:
//////////////////////////////////////////////////////////////////////
// データメンバ
//////////////////////////////////////////////////////////////////////
// ノード数
ymuint32 mNodeNum;
// ノードの配列
RwtNode* mNodeArray;
// 関数ベクタをキーにしてノードを納めた連想配列
unordered_map<ymuint16, RwtNode*> mFuncHash;
};
END_NAMESPACE_YM
#endif // RWTMGR_H
| [
"yusuke_matsunaga@ieee.org"
] | yusuke_matsunaga@ieee.org |
26df9b17d9a7583d233a0c72be9c70d13a777a72 | 6bb851f5d8c743ab3e7037bcea033b0e3430eddb | /data/Submission/75 Sort Colors/Sort Colors_2.cpp | 4a222db8d84b62a67cf9100823731ec6d4c3ca06 | [] | no_license | CJHMPower/Fetch_Leetcode | 96f67ca8609955524f01124f17cb570361ea835f | 5dbd1d0ff56f8ab38fe3587519a973a3d712e758 | refs/heads/master | 2020-03-24T04:26:02.829710 | 2018-07-26T14:31:36 | 2018-07-26T14:31:36 | 142,452,783 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 968 | cpp | //-*- coding:utf-8 -*-
// Generated by the Fetch-Leetcode project on the Github
// https://github.com/CJHMPower/Fetch-Leetcode/
// 75 Sort Colors
// https://leetcode.com//problems/sort-colors/description/
// Fetched at 2018-07-24
// Submitted 2 years ago
// Runtime: 4 ms
// This solution defeats 4.71% cpp solutions
class Solution {
public:
void sortColors(vector<int>& nums) {
int count0 = 0, count1 = 0, count2 = 0;
for (auto v : nums) {
switch (v) {
case 0:
count0++;
break;
case 1:
count1++;
break;
case 2:
count2++;
break;
}
}
int i = 0;
while (i < count0) {
nums[i] = 0;
i++;
}
int j = 0;
while (j + count0 < nums.size() && j < count1) {
nums[j + count0] = 1;
j++;
}
j = 0;
while (j < count2 && j + count0 + count1 < nums.size()) {
nums[count0 + count1 + j] = 2;
j++;
}
}
}; | [
"1120798947@qq.com"
] | 1120798947@qq.com |
6da68b4ae40decb59badd720895f06854ab427a7 | 462663467e57fb2517cfc972417d74fd53209410 | /FK2DEngine2/Include/UI/Controls/FKCanvas.h | 1522094476e2dea7f1a39035a5669a4858e5bfc6 | [] | no_license | duzhi5368/FKTheLostLand | 43f741fdef53aaca18b73f3353423545215c4479 | 5c5ab1f31d955c383e73297dc09095509782f681 | refs/heads/master | 2021-12-13T17:09:03.124167 | 2017-03-16T07:54:04 | 2017-03-16T07:54:04 | 85,167,409 | 1 | 2 | null | null | null | null | GB18030 | C++ | false | false | 2,637 | h | /**
* created: 2013-4-11 19:44
* filename: FKCanvas
* author: FreeKnight
* Copyright (C):
* purpose:
*/
//------------------------------------------------------------------------
#pragma once
//------------------------------------------------------------------------
#include <set>
#include "FKBase.h"
#include "../FKInputHandler.h"
//------------------------------------------------------------------------
namespace FK2DEngine2
{
namespace Controls
{
class FK_EXPORT Canvas : public Base
{
public:
typedef Controls::Base BaseClass;
Canvas( Skin::Base* pSkin );
virtual ~Canvas();
// 初始化
virtual void Initialize() {};
// 绘制Canvas
virtual void RenderCanvas();
// 每帧调用一次,进行输入处理
virtual void DoThink();
// 判断 / 设置 一个面板是否需要重新绘制
virtual bool NeedsRedraw() { return m_bNeedsRedraw; }
virtual void Redraw() { m_bNeedsRedraw = true; }
// 内部函数,不建议调用
virtual void Render( Skin::Base* pRender );
// 子面板可以不停调用 parent->GetCanvas() 直到最顶层父类面板
virtual Controls::Canvas* GetCanvas() { return this; }
virtual void SetScale( float f );
virtual float Scale() const { return m_fScale; }
virtual void OnBoundsChanged( FK2DEngine2::Rect oldBounds );
// 释放全部子面板【注:本函数在析构已调用】
virtual void ReleaseChildren();
// 延迟删除
virtual void AddDelayedDelete( Controls::Base* pControl );
virtual void ProcessDelayedDeletes();
Controls::Base* FirstTab;
Controls::Base* NextTab;
// 输入处理
virtual bool InputMouseMoved( int x, int y, int deltaX, int deltaY );
virtual bool InputMouseButton( int iButton, bool bDown );
virtual bool InputKey( int iKey, bool bDown );
virtual bool InputCharacter( FK2DEngine2::UnicodeChar chr );
virtual bool InputMouseWheel( int val );
virtual bool InputQuit() { return true; };
// 背景处理
virtual void SetBackgroundColor( const FK2DEngine2::Color & color ) { m_BackgroundColor = color; }
virtual void SetDrawBackground( bool bShouldDraw ) { m_bDrawBackground = bShouldDraw; }
protected:
bool m_bNeedsRedraw;
bool m_bAnyDelete;
float m_fScale;
Controls::Base::List m_DeleteList;
std::set< Controls::Base* > m_DeleteSet;
friend class Controls::Base;
void PreDeleteCanvas( Controls::Base* );
bool m_bDrawBackground;
FK2DEngine2::Color m_BackgroundColor;
};
}
}
//------------------------------------------------------------------------ | [
"duzhi5368@163.com"
] | duzhi5368@163.com |
8e0bde58fba57887c810b4f448670b3396788383 | d0779fdf8203cbf9f1d18c5e43e8045f7c3d9c2e | /ROS/catkin_ws/src/cartographer/cartographer/mapping/internal/2d/local_trajectory_builder_2d.cc | 54eb61480d7d94e7cb5ce6eb74a2c3ca09a6b794 | [
"Apache-2.0"
] | permissive | raikaDial/vslidar | 24f3a2ca88a938d61568487c1ef4aac13fea3743 | 12cb55f7706a2f066b25d6cc6a0201473f482fae | refs/heads/master | 2021-09-20T09:39:50.459318 | 2018-08-07T23:09:25 | 2018-08-07T23:09:25 | 127,962,193 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,914 | cc | /*
* Copyright 2016 The Cartographer Authors
*
* 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 "cartographer/mapping/internal/2d/local_trajectory_builder_2d.h"
#include <limits>
#include <memory>
#include "cartographer/common/make_unique.h"
#include "cartographer/metrics/family_factory.h"
#include "cartographer/sensor/range_data.h"
namespace cartographer {
namespace mapping {
static auto* kLocalSlamLatencyMetric = metrics::Gauge::Null();
static auto* kFastCorrelativeScanMatcherScoreMetric =
metrics::Histogram::Null();
static auto* kCeresScanMatcherCostMetric = metrics::Histogram::Null();
static auto* kScanMatcherResidualDistanceMetric = metrics::Histogram::Null();
static auto* kScanMatcherResidualAngleMetric = metrics::Histogram::Null();
LocalTrajectoryBuilder2D::LocalTrajectoryBuilder2D(
const proto::LocalTrajectoryBuilderOptions2D& options)
: options_(options),
active_submaps_(options.submaps_options()),
motion_filter_(options_.motion_filter_options()),
real_time_correlative_scan_matcher_(
options_.real_time_correlative_scan_matcher_options()),
ceres_scan_matcher_(options_.ceres_scan_matcher_options()) {}
LocalTrajectoryBuilder2D::~LocalTrajectoryBuilder2D() {}
sensor::RangeData
LocalTrajectoryBuilder2D::TransformToGravityAlignedFrameAndFilter(
const transform::Rigid3f& transform_to_gravity_aligned_frame,
const sensor::RangeData& range_data) const {
const sensor::RangeData cropped =
sensor::CropRangeData(sensor::TransformRangeData(
range_data, transform_to_gravity_aligned_frame),
options_.min_z(), options_.max_z());
return sensor::RangeData{
cropped.origin,
sensor::VoxelFilter(options_.voxel_filter_size()).Filter(cropped.returns),
sensor::VoxelFilter(options_.voxel_filter_size()).Filter(cropped.misses)};
}
std::unique_ptr<transform::Rigid2d> LocalTrajectoryBuilder2D::ScanMatch(
const common::Time time, const transform::Rigid2d& pose_prediction,
const sensor::RangeData& gravity_aligned_range_data) {
std::shared_ptr<const Submap2D> matching_submap =
active_submaps_.submaps().front();
// The online correlative scan matcher will refine the initial estimate for
// the Ceres scan matcher.
transform::Rigid2d initial_ceres_pose = pose_prediction;
sensor::AdaptiveVoxelFilter adaptive_voxel_filter(
options_.adaptive_voxel_filter_options());
const sensor::PointCloud filtered_gravity_aligned_point_cloud =
adaptive_voxel_filter.Filter(gravity_aligned_range_data.returns);
if (filtered_gravity_aligned_point_cloud.empty()) {
return nullptr;
}
if (options_.use_online_correlative_scan_matching()) {
double score = real_time_correlative_scan_matcher_.Match(
pose_prediction, filtered_gravity_aligned_point_cloud,
matching_submap->probability_grid(), &initial_ceres_pose);
kFastCorrelativeScanMatcherScoreMetric->Observe(score);
}
auto pose_observation = common::make_unique<transform::Rigid2d>();
ceres::Solver::Summary summary;
ceres_scan_matcher_.Match(pose_prediction.translation(), initial_ceres_pose,
filtered_gravity_aligned_point_cloud,
matching_submap->probability_grid(),
pose_observation.get(), &summary);
if (pose_observation) {
kCeresScanMatcherCostMetric->Observe(summary.final_cost);
double residual_distance =
(pose_observation->translation() - pose_prediction.translation())
.norm();
kScanMatcherResidualDistanceMetric->Observe(residual_distance);
double residual_angle = std::abs(pose_observation->rotation().angle() -
pose_prediction.rotation().angle());
kScanMatcherResidualAngleMetric->Observe(residual_angle);
}
return pose_observation;
}
std::unique_ptr<LocalTrajectoryBuilder2D::MatchingResult>
LocalTrajectoryBuilder2D::AddRangeData(
const common::Time time, const sensor::TimedRangeData& range_data) {
// Initialize extrapolator now if we do not ever use an IMU.
if (!options_.use_imu_data()) {
InitializeExtrapolator(time);
}
if (extrapolator_ == nullptr) {
// Until we've initialized the extrapolator with our first IMU message, we
// cannot compute the orientation of the rangefinder.
LOG(INFO) << "Extrapolator not yet initialized.";
return nullptr;
}
CHECK(!range_data.returns.empty());
CHECK_EQ(range_data.returns.back()[3], 0);
const common::Time time_first_point =
time + common::FromSeconds(range_data.returns.front()[3]);
if (time_first_point < extrapolator_->GetLastPoseTime()) {
LOG(INFO) << "Extrapolator is still initializing.";
return nullptr;
}
if (num_accumulated_ == 0) {
accumulation_started_ = std::chrono::steady_clock::now();
}
std::vector<transform::Rigid3f> range_data_poses;
range_data_poses.reserve(range_data.returns.size());
bool warned = false;
for (const Eigen::Vector4f& hit : range_data.returns) {
common::Time time_point = time + common::FromSeconds(hit[3]);
if (time_point < extrapolator_->GetLastExtrapolatedTime()) {
if (!warned) {
LOG(ERROR)
<< "Timestamp of individual range data point jumps backwards from "
<< extrapolator_->GetLastExtrapolatedTime() << " to " << time_point;
warned = true;
}
time_point = extrapolator_->GetLastExtrapolatedTime();
}
range_data_poses.push_back(
extrapolator_->ExtrapolatePose(time_point).cast<float>());
}
if (num_accumulated_ == 0) {
// 'accumulated_range_data_.origin' is uninitialized until the last
// accumulation.
accumulated_range_data_ = sensor::RangeData{{}, {}, {}};
}
// Drop any returns below the minimum range and convert returns beyond the
// maximum range into misses.
for (size_t i = 0; i < range_data.returns.size(); ++i) {
const Eigen::Vector4f& hit = range_data.returns[i];
const Eigen::Vector3f origin_in_local =
range_data_poses[i] * range_data.origin;
const Eigen::Vector3f hit_in_local = range_data_poses[i] * hit.head<3>();
const Eigen::Vector3f delta = hit_in_local - origin_in_local;
const float range = delta.norm();
if (range >= options_.min_range()) {
if (range <= options_.max_range()) {
accumulated_range_data_.returns.push_back(hit_in_local);
} else {
accumulated_range_data_.misses.push_back(
origin_in_local +
options_.missing_data_ray_length() / range * delta);
}
}
}
++num_accumulated_;
if (num_accumulated_ >= options_.num_accumulated_range_data()) {
num_accumulated_ = 0;
const transform::Rigid3d gravity_alignment = transform::Rigid3d::Rotation(
extrapolator_->EstimateGravityOrientation(time));
accumulated_range_data_.origin =
range_data_poses.back() * range_data.origin;
return AddAccumulatedRangeData(
time,
TransformToGravityAlignedFrameAndFilter(
gravity_alignment.cast<float>() * range_data_poses.back().inverse(),
accumulated_range_data_),
gravity_alignment);
}
return nullptr;
}
std::unique_ptr<LocalTrajectoryBuilder2D::MatchingResult>
LocalTrajectoryBuilder2D::AddAccumulatedRangeData(
const common::Time time,
const sensor::RangeData& gravity_aligned_range_data,
const transform::Rigid3d& gravity_alignment) {
if (gravity_aligned_range_data.returns.empty()) {
LOG(WARNING) << "Dropped empty horizontal range data.";
return nullptr;
}
// Computes a gravity aligned pose prediction.
const transform::Rigid3d non_gravity_aligned_pose_prediction =
extrapolator_->ExtrapolatePose(time);
const transform::Rigid2d pose_prediction = transform::Project2D(
non_gravity_aligned_pose_prediction * gravity_alignment.inverse());
// local map frame <- gravity-aligned frame
std::unique_ptr<transform::Rigid2d> pose_estimate_2d =
ScanMatch(time, pose_prediction, gravity_aligned_range_data);
if (pose_estimate_2d == nullptr) {
LOG(WARNING) << "Scan matching failed.";
return nullptr;
}
const transform::Rigid3d pose_estimate =
transform::Embed3D(*pose_estimate_2d) * gravity_alignment;
extrapolator_->AddPose(time, pose_estimate);
sensor::RangeData range_data_in_local =
TransformRangeData(gravity_aligned_range_data,
transform::Embed3D(pose_estimate_2d->cast<float>()));
std::unique_ptr<InsertionResult> insertion_result =
InsertIntoSubmap(time, range_data_in_local, gravity_aligned_range_data,
pose_estimate, gravity_alignment.rotation());
auto duration = std::chrono::steady_clock::now() - accumulation_started_;
kLocalSlamLatencyMetric->Set(
std::chrono::duration_cast<std::chrono::seconds>(duration).count());
return common::make_unique<MatchingResult>(
MatchingResult{time, pose_estimate, std::move(range_data_in_local),
std::move(insertion_result)});
}
std::unique_ptr<LocalTrajectoryBuilder2D::InsertionResult>
LocalTrajectoryBuilder2D::InsertIntoSubmap(
const common::Time time, const sensor::RangeData& range_data_in_local,
const sensor::RangeData& gravity_aligned_range_data,
const transform::Rigid3d& pose_estimate,
const Eigen::Quaterniond& gravity_alignment) {
if (motion_filter_.IsSimilar(time, pose_estimate)) {
return nullptr;
}
// Querying the active submaps must be done here before calling
// InsertRangeData() since the queried values are valid for next insertion.
std::vector<std::shared_ptr<const Submap2D>> insertion_submaps;
for (const std::shared_ptr<Submap2D>& submap : active_submaps_.submaps()) {
insertion_submaps.push_back(submap);
}
active_submaps_.InsertRangeData(range_data_in_local);
sensor::AdaptiveVoxelFilter adaptive_voxel_filter(
options_.loop_closure_adaptive_voxel_filter_options());
const sensor::PointCloud filtered_gravity_aligned_point_cloud =
adaptive_voxel_filter.Filter(gravity_aligned_range_data.returns);
return common::make_unique<InsertionResult>(InsertionResult{
std::make_shared<const TrajectoryNode::Data>(TrajectoryNode::Data{
time,
gravity_alignment,
filtered_gravity_aligned_point_cloud,
{}, // 'high_resolution_point_cloud' is only used in 3D.
{}, // 'low_resolution_point_cloud' is only used in 3D.
{}, // 'rotational_scan_matcher_histogram' is only used in 3D.
pose_estimate}),
std::move(insertion_submaps)});
}
void LocalTrajectoryBuilder2D::AddImuData(const sensor::ImuData& imu_data) {
CHECK(options_.use_imu_data()) << "An unexpected IMU packet was added.";
InitializeExtrapolator(imu_data.time);
extrapolator_->AddImuData(imu_data);
}
void LocalTrajectoryBuilder2D::AddOdometryData(
const sensor::OdometryData& odometry_data) {
if (extrapolator_ == nullptr) {
// Until we've initialized the extrapolator we cannot add odometry data.
LOG(INFO) << "Extrapolator not yet initialized.";
return;
}
extrapolator_->AddOdometryData(odometry_data);
}
void LocalTrajectoryBuilder2D::InitializeExtrapolator(const common::Time time) {
if (extrapolator_ != nullptr) {
return;
}
// We derive velocities from poses which are at least 1 ms apart for numerical
// stability. Usually poses known to the extrapolator will be further apart
// in time and thus the last two are used.
constexpr double kExtrapolationEstimationTimeSec = 0.001;
// TODO(gaschler): Consider using InitializeWithImu as 3D does.
extrapolator_ = common::make_unique<PoseExtrapolator>(
::cartographer::common::FromSeconds(kExtrapolationEstimationTimeSec),
options_.imu_gravity_time_constant());
extrapolator_->AddPose(time, transform::Rigid3d::Identity());
}
void LocalTrajectoryBuilder2D::RegisterMetrics(
metrics::FamilyFactory* family_factory) {
auto* latency = family_factory->NewGaugeFamily(
"/mapping/internal/2d/local_trajectory_builder/latency",
"Duration from first incoming point cloud in accumulation to local slam "
"result");
kLocalSlamLatencyMetric = latency->Add({});
auto score_boundaries = metrics::Histogram::FixedWidth(0.05, 20);
auto* scores = family_factory->NewHistogramFamily(
"/mapping/internal/2d/local_trajectory_builder/scores",
"Local scan matcher scores", score_boundaries);
kFastCorrelativeScanMatcherScoreMetric =
scores->Add({{"scan_matcher", "fast_correlative"}});
auto cost_boundaries = metrics::Histogram::ScaledPowersOf(2, 0.01, 100);
auto* costs = family_factory->NewHistogramFamily(
"/mapping/internal/2d/local_trajectory_builder/costs",
"Local scan matcher costs", cost_boundaries);
kCeresScanMatcherCostMetric = costs->Add({{"scan_matcher", "ceres"}});
auto distance_boundaries = metrics::Histogram::ScaledPowersOf(2, 0.01, 10);
auto* residuals = family_factory->NewHistogramFamily(
"/mapping/internal/2d/local_trajectory_builder/residuals",
"Local scan matcher residuals", distance_boundaries);
kScanMatcherResidualDistanceMetric =
residuals->Add({{"component", "distance"}});
kScanMatcherResidualAngleMetric = residuals->Add({{"component", "angle"}});
}
} // namespace mapping
} // namespace cartographer
| [
"ryker.dial@gmail.com"
] | ryker.dial@gmail.com |
bf95934874cf5c1900f477930b8d0482e692e00a | 064c812442ce0cedfc400827d1fa2f8f4c4bb438 | /AutoDownloaded Codes/sshstamref/1003/1003.cpp11.cpp | 6a8bec4f9f80e4398ed00e3ab73d3eb4a890da77 | [] | no_license | TAMREF/problem-solving-storage | c1845571179771d33263cf03f3a26bff0cd75d53 | cab7bbe00343bd1bc4fe32a984a574f86aac545e | refs/heads/master | 2022-03-21T04:30:18.318602 | 2019-11-13T03:21:35 | 2019-11-13T03:21:35 | 78,931,251 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 342 | cpp | #include <cstdio>
long long numz[50], numo[50];
int main()
{
numz[0]=1;
numo[1]=1;
int C, N;
scanf("%d\n",&C);
for(int i=2;i<=50;i++)
{
numz[i]=numz[i-1]+numz[i-2];
numo[i]=numo[i-1]+numo[i-2];
}
for(int i=0;i<C;i++)
{
scanf("%d",&N);
printf("%lld %lld\n",numz[N],numo[N]);
}
}
| [
"sluggeryck@naver.com"
] | sluggeryck@naver.com |
0a18d225d593f82086bb4a3518e657e1b9e82358 | 65a99d0c9a0d4feeff49ceb5c2cffdef370f6185 | /prominiextender/prominiextender.ino | c98fd08e0f5f702c37f3cd891d98478fe45feade | [] | no_license | sker65/tiltaudio-extensions | ff3cc918ff48ba596eb8f07def8cdb8e674e504f | a1d96f31b3e9c3596fada3e540348540ddfb713c | refs/heads/master | 2022-01-26T15:18:12.743567 | 2022-01-14T22:02:42 | 2022-01-14T22:02:42 | 210,176,615 | 2 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 3,108 | ino | /*
* ***************************************************************************************************************************\
* Arduino project "ESP Easy" � Copyright www.esp8266.nu
*
* 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 received a copy of the GNU General Public License along with this program in file 'License.txt'.
*
* IDE download : https://www.arduino.cc/en/Main/Software
* ESP8266 Package : https://github.com/esp8266/Arduino
*
* Source Code : https://sourceforge.net/projects/espeasy/
* Support : http://www.esp8266.nu
* Discussion : http://www.esp8266.nu/forum/
*
* Additional information about licensing can be found at : http://www.gnu.org/licenses
**************************************************************************************************************************/
// This file is to be loaded onto an Arduino Pro Mini so it will act as a simple IO extender to the ESP module.
// Communication between ESP and Arduino is using the I2C bus, so only two wires needed.
// It best to run the Pro Mini on 3V3, although the 16MHz versions do not officially support this voltage level on this frequency.
// That way, you can skip levelconverters on I2C.
// Arduino Mini Pro uses A4 and A5 for I2C bus. ESP I2C can be configured but they are on GPIO-4 and GPIO-5 by default.
#include <Wire.h>
#define I2C_MSG_IN_SIZE 4
#define I2C_MSG_OUT_SIZE 4
#define CMD_DIGITAL_WRITE 1
#define CMD_DIGITAL_READ 2
#define CMD_ANALOG_WRITE 3
#define CMD_ANALOG_READ 4
volatile uint8_t sendBuffer[I2C_MSG_OUT_SIZE];
void setup()
{
Wire.begin(0x7f);
Wire.onReceive(receiveEvent);
Wire.onRequest(requestEvent);
}
void loop() {}
void receiveEvent(int count)
{
if (count == I2C_MSG_IN_SIZE)
{
byte cmd = Wire.read();
byte port = Wire.read();
int value = Wire.read();
value += Wire.read()*256;
switch(cmd)
{
case CMD_DIGITAL_WRITE:
pinMode(port,OUTPUT);
digitalWrite(port,value);
break;
case CMD_DIGITAL_READ:
pinMode(port,INPUT_PULLUP);
clearSendBuffer();
sendBuffer[0] = digitalRead(port);
break;
case CMD_ANALOG_WRITE:
analogWrite(port,value);
break;
case CMD_ANALOG_READ:
clearSendBuffer();
int valueRead = analogRead(port);
sendBuffer[0] = valueRead & 0xff;
sendBuffer[1] = valueRead >> 8;
break;
}
}
}
void clearSendBuffer()
{
for(byte x=0; x < sizeof(sendBuffer); x++)
sendBuffer[x]=0;
}
void requestEvent()
{
Wire.write((const uint8_t*)sendBuffer,sizeof(sendBuffer));
} | [
"sker65@gmail.com"
] | sker65@gmail.com |
14f6a76a441cddbcb5bec8671018cf3123518593 | fb7817c071c37fed603e1b46df1327175ee031b1 | /App/Lib/Bal/Tool/Build/ShaderConverter/ShaderArchiver/Archiver.cpp | 7cd4d281837259f3700c13849a9a223c2b49d38f | [
"MIT"
] | permissive | belmayze/bal | af22ecf42ae1491843c4e84f74af75be92b64ed3 | 710a96d011855fdab4e4b6962a2ba5b6b6b35aae | refs/heads/master | 2021-08-18T04:04:42.151990 | 2021-07-03T22:29:42 | 2021-07-03T22:29:42 | 240,271,882 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,761 | cpp | /*!
* @file balApiEntry.cpp
* @brief
* @author belmayze
*
* Copyright (c) 2020 belmayze. All rights reserved.
*/
// app
#include "Archiver.h"
namespace app
{
// ----------------------------------------------------------------------------
void Archiver::initialize(const InitializeArg& arg)
{
mHeader.mNumPrograms = arg.mNumShader;
mTags = bal::make_unique<bal::ShaderArchive::Tag[]>(nullptr, mHeader.mNumPrograms);
mShaders = bal::make_unique<ShaderContainer[]>(nullptr, mHeader.mNumPrograms);
}
// ----------------------------------------------------------------------------
void Archiver::setShader(const ShaderArg& arg)
{
ShaderContainer& container = mShaders[arg.mShaderIndex];
bal::ShaderArchive::Tag& tag = mTags[arg.mShaderIndex];
// プログラム名
container.mProgramName = bal::StringBuffer(arg.mShaderName.c_str(), arg.mShaderName.size());
tag.mNameSize = static_cast<uint32_t>(container.mProgramName.size() + 1);
// ファイル読み込み
if (!arg.mVertexShaderFilepath.isEmpty())
{
container.mVertexShader.loadFromFile(arg.mVertexShaderFilepath);
tag.mVertexShaderSize = static_cast<uint32_t>(container.mVertexShader.getBufferSize());
}
if (!arg.mGeometryShaderFilepath.isEmpty())
{
container.mGeometryShader.loadFromFile(arg.mGeometryShaderFilepath);
tag.mGeometryShaderSize = static_cast<uint32_t>(container.mGeometryShader.getBufferSize());
}
if (!arg.mPixelShaderFilepath.isEmpty())
{
container.mPixelShader.loadFromFile(arg.mPixelShaderFilepath);
tag.mPixelShaderSize = static_cast<uint32_t>(container.mPixelShader.getBufferSize());
}
if (!arg.mComputeShaderFilepath.isEmpty())
{
container.mComputeShader.loadFromFile(arg.mComputeShaderFilepath);
tag.mComputeShaderSize = static_cast<uint32_t>(container.mComputeShader.getBufferSize());
}
if (!arg.mDomainShaderFilepath.isEmpty())
{
container.mDomainShader.loadFromFile(arg.mDomainShaderFilepath);
tag.mDomainShaderSize = static_cast<uint32_t>(container.mDomainShader.getBufferSize());
}
if (!arg.mHullShaderFilepath.isEmpty())
{
container.mHullShader.loadFromFile(arg.mHullShaderFilepath);
tag.mHullShaderSize = static_cast<uint32_t>(container.mHullShader.getBufferSize());
}
if (!arg.mAmplificationShaderFilepath.isEmpty())
{
container.mAmplificationShader.loadFromFile(arg.mAmplificationShaderFilepath);
tag.mAmplificationShaderSize = static_cast<uint32_t>(container.mAmplificationShader.getBufferSize());
}
if (!arg.mMeshShaderFilepath.isEmpty())
{
container.mMeshShader.loadFromFile(arg.mMeshShaderFilepath);
tag.mMeshShaderSize = static_cast<uint32_t>(container.mMeshShader.getBufferSize());
}
}
// ----------------------------------------------------------------------------
void Archiver::archive(const bal::StringPtr& output_path)
{
// ファイルサイズを計算
size_t memory_size = sizeof(bal::ShaderArchive::Header)
+ sizeof(bal::ShaderArchive::Tag) * mHeader.mNumPrograms;
for (int i_program = 0; i_program < mHeader.mNumPrograms; ++i_program)
{
// オフセット計算しつつ、メモリーサイズも求める
bal::ShaderArchive::Tag& tag = mTags[i_program];
tag.mOffset = static_cast<uint32_t>(memory_size);
memory_size += tag.mNameSize
+ tag.mVertexShaderSize
+ tag.mGeometryShaderSize
+ tag.mPixelShaderSize
+ tag.mComputeShaderSize
+ tag.mDomainShaderSize
+ tag.mHullShaderSize
+ tag.mAmplificationShaderSize
+ tag.mMeshShaderSize;
}
// ファイルバッファを確保
std::unique_ptr<uint8_t[]> buffer = bal::make_unique<uint8_t[]>(nullptr, memory_size);
// ヘッダー書き出し
uint8_t* ptr = buffer.get();
std::memcpy(ptr, &mHeader, sizeof(bal::ShaderArchive::Header));
ptr += sizeof(bal::ShaderArchive::Header);
std::memcpy(ptr, mTags.get(), sizeof(bal::ShaderArchive::Tag) * mHeader.mNumPrograms);
ptr += sizeof(bal::ShaderArchive::Tag) * mHeader.mNumPrograms;
// シェーダー書き出し
for (int i_program = 0; i_program < mHeader.mNumPrograms; ++i_program)
{
const ShaderContainer& container = mShaders[i_program];
const bal::ShaderArchive::Tag& tag = mTags[i_program];
// 名前
std::memcpy(ptr, container.mProgramName.c_str(), tag.mNameSize);
ptr += tag.mNameSize;
if (tag.mVertexShaderSize > 0)
{
std::memcpy(ptr, container.mVertexShader.getBuffer(), container.mVertexShader.getBufferSize());
ptr += container.mVertexShader.getBufferSize();
}
if (tag.mGeometryShaderSize > 0)
{
std::memcpy(ptr, container.mGeometryShader.getBuffer(), container.mGeometryShader.getBufferSize());
ptr += container.mGeometryShader.getBufferSize();
}
if (tag.mPixelShaderSize > 0)
{
std::memcpy(ptr, container.mPixelShader.getBuffer(), container.mPixelShader.getBufferSize());
ptr += container.mPixelShader.getBufferSize();
}
if (tag.mComputeShaderSize > 0)
{
std::memcpy(ptr, container.mComputeShader.getBuffer(), container.mComputeShader.getBufferSize());
ptr += container.mComputeShader.getBufferSize();
}
if (tag.mDomainShaderSize > 0)
{
std::memcpy(ptr, container.mDomainShader.getBuffer(), container.mDomainShader.getBufferSize());
ptr += container.mDomainShader.getBufferSize();
}
if (tag.mHullShaderSize > 0)
{
std::memcpy(ptr, container.mHullShader.getBuffer(), container.mHullShader.getBufferSize());
ptr += container.mHullShader.getBufferSize();
}
if (tag.mAmplificationShaderSize > 0)
{
std::memcpy(ptr, container.mAmplificationShader.getBuffer(), container.mAmplificationShader.getBufferSize());
ptr += container.mAmplificationShader.getBufferSize();
}
if (tag.mMeshShaderSize > 0)
{
std::memcpy(ptr, container.mMeshShader.getBuffer(), container.mMeshShader.getBufferSize());
ptr += container.mMeshShader.getBufferSize();
}
}
// ファイル書き出し
bal::File::WriteToFile(output_path, buffer.get(), memory_size);
}
// ----------------------------------------------------------------------------
}
| [
"belmayze@hotmail.co.jp"
] | belmayze@hotmail.co.jp |
440e48a5482efc59f5107c038b151538bb2af5c9 | 8e1334bd97b8fe92ada1c9ca00beb342c52ba122 | /code blocks/BinaryIndexedTree.cpp | 0a02368d9fca403ca33d7243029e1ae39e10829e | [] | no_license | chetan-anand/codechef | 39922197ec2d61da44106fa38f2414b3fcec72e1 | 03c4da7684aa8e129e05dc9509e1e3b5e9cc213a | refs/heads/master | 2020-04-16T07:59:08.735276 | 2014-03-04T20:48:45 | 2014-03-04T20:48:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 325 | cpp | /* This contain the basic implimentation of binary indexed tree. As we already know
Binary Indexed Trees are used for problem involving frequent queries which include update and extraction.
Moreover, it is much easier to code binary indexed trees than segment trees*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
| [
"chetan98351@gmail.com"
] | chetan98351@gmail.com |
9807b91dc76eb598291e335f78ee9ab9b0ce64bd | 2c60ab1041d60f2c4d0a92cb35f074a1f0a18cc9 | /term2/Unscented-Kalman-Filter/CarND-Unscented-Kalman-Filter-Project-master/src/ukf.cpp | 257a6b05dc78cf92e5f7ab34d198b9df72b46d42 | [
"MIT"
] | permissive | haopo2005/SelfDrivingCar_Udacity | 12f964fa28d68326da6e851fe54ac40b9a6c2eaa | 70f8b7f3aba5128e40774773977af019476cbcb9 | refs/heads/master | 2020-03-28T08:54:17.842482 | 2018-12-29T05:49:30 | 2018-12-29T05:49:30 | 147,997,999 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,149 | cpp | #include "ukf.h"
#include "Eigen/Dense"
#include <iostream>
using namespace std;
using Eigen::MatrixXd;
using Eigen::VectorXd;
using std::vector;
/**
* Initializes Unscented Kalman filter
* This is scaffolding, do not modify
*/
UKF::UKF() {
// if this is false, laser measurements will be ignored (except during init)
use_laser_ = true;
// if this is false, radar measurements will be ignored (except during init)
use_radar_ = true;
// initial state vector
x_ = VectorXd(5);
// initial covariance matrix
P_ = MatrixXd(5, 5);
// Process noise standard deviation longitudinal acceleration in m/s^2
std_a_ = 5;
// Process noise standard deviation yaw acceleration in rad/s^2
std_yawdd_ = 0.5;
//DO NOT MODIFY measurement noise values below these are provided by the sensor manufacturer.
// Laser measurement noise standard deviation position1 in m
std_laspx_ = 0.15;
// Laser measurement noise standard deviation position2 in m
std_laspy_ = 0.15;
// Radar measurement noise standard deviation radius in m
std_radr_ = 0.3;
// Radar measurement noise standard deviation angle in rad
std_radphi_ = 0.03;
// Radar measurement noise standard deviation radius change in m/s
std_radrd_ = 0.3;
//DO NOT MODIFY measurement noise values above these are provided by the sensor manufacturer.
/**
TODO:
Complete the initialization. See ukf.h for other member properties.
Hint: one or more values initialized above might be wildly off...
*/
is_initialized_ = false;
time_us_ = 0;
n_x_ = 5;
n_aug_ = 7;
lambda_ = 3 - n_aug_;
Xsig_pred_ = MatrixXd(n_x_, 2*n_aug_+1);
// set weights
weights_ = VectorXd(2*n_aug_+1);
double weight_0 = lambda_/(lambda_+n_aug_);
weights_(0) = weight_0;
for (int i=1; i<2*n_aug_+1; i++) { //2n+1 weights
double weight = 0.5/(n_aug_+lambda_);
weights_(i) = weight;
}
}
UKF::~UKF() {}
/**
* @param {MeasurementPackage} meas_package The latest measurement data of
* either radar or laser.
*/
void UKF::ProcessMeasurement(MeasurementPackage meas_package) {
/**
TODO:
Complete this function! Make sure you switch between lidar and radar
measurements.
*/
if (!is_initialized_) {
cout << "UKF: " << endl;
x_ << 0, 0, 0, 0, 0;
P_ << 1, 0, 0, 0, 0,
0, 1, 0, 0, 0,
0, 0, 1, 0, 0,
0, 0, 0, 1, 0,
0, 0, 0, 0, 1;
if (meas_package.sensor_type_ == MeasurementPackage::RADAR) {
// Convert radar from polar to cartesian coordinates and initialize state.
float rho = meas_package.raw_measurements_(0);
float phi = meas_package.raw_measurements_(1);
float rhodot = meas_package.raw_measurements_(2);
float px = rho * cos(phi);
float py = rho * sin(phi);
float vx = rhodot * cos(phi);
float vy = rhodot * sin(phi);
x_ << px,py,sqrt(vx*vx +vy*vy),0,0;
}else{
x_(0) = meas_package.raw_measurements_[0];
x_(1) = meas_package.raw_measurements_[1];
}
time_us_ = meas_package.timestamp_;
is_initialized_ = true;
return;
}
float dt = (meas_package.timestamp_ - time_us_) / 1000000.0; //dt - expressed in seconds
time_us_ = meas_package.timestamp_;
std::cout<<"Prediction"<<std::endl;
Prediction(dt);
if (meas_package.sensor_type_ == MeasurementPackage::RADAR) {
std::cout<<"UpdateRadar"<<std::endl;
UpdateRadar(meas_package);
}else{
std::cout<<"UpdateLidar"<<std::endl;
UpdateLidar(meas_package);
}
// print the output
//cout << "x_ = " << x_ << endl;
//cout << "P_ = " << P_ << endl;
}
/**
* Predicts sigma points, the state, and the state covariance matrix.
* @param {double} delta_t the change in time (in seconds) between the last
* measurement and this one.
*/
void UKF::Prediction(double delta_t) {
/**
TODO:
Complete this function! Estimate the object's location. Modify the state
vector, x_. Predict sigma points, the state, and the state covariance matrix.
*/
/*1.generate sigma points with process noise*/
//create augmented mean vector
VectorXd x_aug = VectorXd(n_aug_);
//create augmented state covariance
MatrixXd P_aug = MatrixXd(n_aug_, n_aug_);
//create augmented mean state
x_aug << x_, 0, 0;
//create augmented covariance matrix
P_aug.block(0,0,n_x_,n_x_) = P_;
P_aug.block(0,n_x_,n_x_,n_aug_-n_x_) = MatrixXd::Zero(n_x_,n_aug_-n_x_);
P_aug.block(n_x_,0,n_aug_-n_x_,n_x_) = MatrixXd::Zero(n_aug_-n_x_,n_x_);
P_aug.block(n_x_,n_x_,n_aug_-n_x_,n_aug_-n_x_) << std_a_*std_a_,0,0,std_yawdd_*std_yawdd_;
//create square root matrix
MatrixXd A = P_aug.llt().matrixL();
//create sigma point matrix
MatrixXd Xsig_aug = MatrixXd(n_aug_, 2 * n_aug_ + 1);
//create augmented sigma points
Xsig_aug.col(0) = x_aug;
for(int i=0;i<n_aug_;i++)
{
Xsig_aug.col(i+1) = x_aug + sqrt(lambda_+n_aug_)*A.col(i);
Xsig_aug.col(i+n_aug_+1) = x_aug - sqrt(lambda_+n_aug_)*A.col(i);
}
/*2.predict sigma points(projected them into process model equation)*/
//avoid division by zero
//write predicted sigma points into right column
//predict sigma points
for (int i = 0; i< 2*n_aug_+1; i++)
{
//extract values for better readability
double p_x = Xsig_aug(0,i);
double p_y = Xsig_aug(1,i);
double v = Xsig_aug(2,i);
double yaw = Xsig_aug(3,i);
double yawd = Xsig_aug(4,i);
double nu_a = Xsig_aug(5,i);
double nu_yawdd = Xsig_aug(6,i);
//predicted state values
double px_p, py_p;
//avoid division by zero
if (fabs(yawd) > 0.001) {
px_p = p_x + v/yawd * ( sin (yaw + yawd*delta_t) - sin(yaw));
py_p = p_y + v/yawd * ( cos(yaw) - cos(yaw+yawd*delta_t) );
}
else {
px_p = p_x + v*delta_t*cos(yaw);
py_p = p_y + v*delta_t*sin(yaw);
}
double v_p = v;
double yaw_p = yaw + yawd*delta_t;
double yawd_p = yawd;
//add noise
px_p = px_p + 0.5*nu_a*delta_t*delta_t * cos(yaw);
py_p = py_p + 0.5*nu_a*delta_t*delta_t * sin(yaw);
v_p = v_p + nu_a*delta_t;
yaw_p = yaw_p + 0.5*nu_yawdd*delta_t*delta_t;
yawd_p = yawd_p + nu_yawdd*delta_t;
//write predicted sigma point into right column
Xsig_pred_(0,i) = px_p;
Xsig_pred_(1,i) = py_p;
Xsig_pred_(2,i) = v_p;
Xsig_pred_(3,i) = yaw_p;
Xsig_pred_(4,i) = yawd_p;
}
/*3.compute or update the state mean and the state covariance matrix*/
//predicted state mean
x_.fill(0.0);
for (int i = 0; i < 2 * n_aug_ + 1; i++) { //iterate over sigma points
x_ = x_+ weights_(i) * Xsig_pred_.col(i);
}
//predicted state covariance matrix
P_.fill(0.0);
for (int i = 0; i < 2 * n_aug_ + 1; i++) { //iterate over sigma points
// state difference
VectorXd x_diff = Xsig_pred_.col(i) - x_;
//angle normalization
while (x_diff(3)> M_PI) x_diff(3)-=2.*M_PI;
while (x_diff(3)<-M_PI) x_diff(3)+=2.*M_PI;
P_ = P_ + weights_(i) * x_diff * x_diff.transpose() ;
}
}
/**
* Updates the state and the state covariance matrix using a laser measurement.
* @param {MeasurementPackage} meas_package
*/
void UKF::UpdateLidar(MeasurementPackage meas_package) {
/**
TODO:
Complete this function! Use lidar data to update the belief about the object's
position. Modify the state vector, x_, and covariance, P_.
You'll also need to calculate the lidar NIS.
*/
/*0.parse the measurement data*/
VectorXd z(2);
z << meas_package.raw_measurements_[0],meas_package.raw_measurements_[1];
/*1.predict radra measurement(project the ctrv posterior state [sigma points] into lidar coordinate)*/
//set measurement dimension, lidar can measure x and y position
int n_z = 2;
//create matrix for sigma points in measurement space
MatrixXd Zsig = MatrixXd(n_z, 2 * n_aug_ + 1);
//transform sigma points into measurement space
for (int i = 0; i < 2 * n_aug_ + 1; i++) { //2n+1 simga points
// extract values for better readibility
double p_x = Xsig_pred_(0,i);
double p_y = Xsig_pred_(1,i);
// measurement model
Zsig(0,i) = p_x; //x
Zsig(1,i) = p_y; //y
}
/*2.compute these projected sigma points' mean and convariance*/
//mean predicted measurement
VectorXd z_pred = VectorXd(n_z);
z_pred.fill(0.0);
for (int i=0; i < 2*n_aug_+1; i++) {
z_pred = z_pred + weights_(i) * Zsig.col(i);
}
//measurement covariance matrix S
MatrixXd S = MatrixXd(n_z,n_z);
S.fill(0.0);
for (int i = 0; i < 2 * n_aug_ + 1; i++) { //2n+1 simga points
//residual
VectorXd z_diff = Zsig.col(i) - z_pred;
S = S + weights_(i) * z_diff * z_diff.transpose();
}
//add measurement noise covariance matrix
MatrixXd R = MatrixXd(n_z,n_z);
R << std_laspx_*std_laspx_, 0,
0, std_laspy_*std_laspy_;
S = S + R;
/*3.measurement update with observation*/
//create matrix for cross correlation Tc
MatrixXd Tc = MatrixXd(n_x_, n_z);
//calculate cross correlation matrix
Tc.fill(0);
for (int i = 0; i < 2 * n_aug_ + 1; i++) { //2n+1 simga points
//residual
VectorXd z_diff = Zsig.col(i) - z_pred;
// state difference
VectorXd x_diff = Xsig_pred_.col(i) - x_;
Tc = Tc + weights_(i) * x_diff * z_diff.transpose();
}
//calculate Kalman gain K;
MatrixXd K = Tc * S.inverse();
//update state mean and covariance matrix
VectorXd z_diff = z - z_pred;
x_ = x_ + K * z_diff;
P_ = P_ - K * S * K.transpose();
/*4.compute NIS*/
//NIS should seldomly be larger than 7.81 [5% chance]
VectorXd z_nis_diff = z - z_pred;
float NIS = z_nis_diff.transpose()*S.inverse()*z_nis_diff;
std::cout<<"NIS: "<<NIS<<std::endl;
}
/**
* Updates the state and the state covariance matrix using a radar measurement.
* @param {MeasurementPackage} meas_package
*/
void UKF::UpdateRadar(MeasurementPackage meas_package) {
/**
TODO:
Complete this function! Use radar data to update the belief about the object's
position. Modify the state vector, x_, and covariance, P_.
You'll also need to calculate the radar NIS.
*/
/*0.parse the measurement data*/
VectorXd z(3);
z << meas_package.raw_measurements_[0],meas_package.raw_measurements_[1],meas_package.raw_measurements_[2];
/*1.predict radra measurement(project the ctrv posterior state [sigma points] into radar coordinate)*/
//set measurement dimension, radar can measure r, phi, and r_dot
int n_z = 3;
//create matrix for sigma points in measurement space
MatrixXd Zsig = MatrixXd(n_z, 2 * n_aug_ + 1);
//transform sigma points into measurement space
for (int i = 0; i < 2 * n_aug_ + 1; i++) { //2n+1 simga points
// extract values for better readibility
double p_x = Xsig_pred_(0,i);
double p_y = Xsig_pred_(1,i);
double v = Xsig_pred_(2,i);
double yaw = Xsig_pred_(3,i);
double v1 = cos(yaw)*v;
double v2 = sin(yaw)*v;
// measurement model
Zsig(0,i) = sqrt(p_x*p_x + p_y*p_y); //r
Zsig(1,i) = atan2(p_y,p_x); //phi
Zsig(2,i) = (p_x*v1 + p_y*v2 ) / sqrt(p_x*p_x + p_y*p_y); //r_dot
}
/*2.compute these projected sigma points' mean and convariance*/
//mean predicted measurement
VectorXd z_pred = VectorXd(n_z);
z_pred.fill(0.0);
for (int i=0; i < 2*n_aug_+1; i++) {
z_pred = z_pred + weights_(i) * Zsig.col(i);
}
//measurement covariance matrix S
MatrixXd S = MatrixXd(n_z,n_z);
S.fill(0.0);
for (int i = 0; i < 2 * n_aug_ + 1; i++) { //2n+1 simga points
//residual
VectorXd z_diff = Zsig.col(i) - z_pred;
//angle normalization
while (z_diff(1)> M_PI) z_diff(1)-=2.*M_PI;
while (z_diff(1)<-M_PI) z_diff(1)+=2.*M_PI;
S = S + weights_(i) * z_diff * z_diff.transpose();
}
//add measurement noise covariance matrix
MatrixXd R = MatrixXd(n_z,n_z);
R << std_radr_*std_radr_, 0, 0,
0, std_radphi_*std_radphi_, 0,
0, 0,std_radrd_*std_radrd_;
S = S + R;
/*3.measurement update with observation*/
//create matrix for cross correlation Tc
MatrixXd Tc = MatrixXd(n_x_, n_z);
//calculate cross correlation matrix
Tc.fill(0);
for (int i = 0; i < 2 * n_aug_ + 1; i++) { //2n+1 simga points
//residual
VectorXd z_diff = Zsig.col(i) - z_pred;
//angle normalization
while (z_diff(1)> M_PI) z_diff(1)-=2.*M_PI;
while (z_diff(1)<-M_PI) z_diff(1)+=2.*M_PI;
// state difference
VectorXd x_diff = Xsig_pred_.col(i) - x_;
//angle normalization
while (x_diff(3)> M_PI) x_diff(3)-=2.*M_PI;
while (x_diff(3)<-M_PI) x_diff(3)+=2.*M_PI;
Tc = Tc + weights_(i) * x_diff * z_diff.transpose();
}
//calculate Kalman gain K;
MatrixXd K = Tc * S.inverse();
//update state mean and covariance matrix
VectorXd z_diff = z - z_pred;
while (z_diff(1)> M_PI) z_diff(1)-=2.*M_PI;
while (z_diff(1)<-M_PI) z_diff(1)+=2.*M_PI;
x_ = x_ + K * z_diff;
P_ = P_ - K * S * K.transpose();
/*4.compute NIS*/
//NIS should seldomly be larger than 7.81 [5% chance]
VectorXd z_nis_diff = z - z_pred;
float NIS = z_nis_diff.transpose()*S.inverse()*z_nis_diff;
std::cout<<"NIS: "<<NIS<<std::endl;
}
| [
"haopo_2005@sina.com"
] | haopo_2005@sina.com |
3157a448eca04cfd8683165663638b156e76fbb1 | a3634de7800ae5fe8e68532d7c3a7570b9c61c5b | /codechef/lepermut.cpp | 4af2de8795df434237d57d7c34ed9ec485d92ece | [] | no_license | MayankChaturvedi/competitive-coding | a737a2a36b8aa7aea1193f2db4b32b081f78e2ba | 9e9bd21de669c7b7bd29a262b29965ecc80ad621 | refs/heads/master | 2020-03-18T01:39:29.447631 | 2018-02-19T15:04:32 | 2018-02-19T15:04:32 | 134,152,930 | 0 | 1 | null | 2018-05-20T13:27:35 | 2018-05-20T13:27:34 | null | UTF-8 | C++ | false | false | 384 | cpp | #include<iostream>
using namespace std;
int main()
{ int t;
cin>>t;
while(t--)
{ int n;
cin>>n;
int inp[n];
for(int i=0; i<n; i++)
cin>>inp[i];
bool ans=true;
for(int i=0; i<n; i++)
{ for(int j=i+2; j<n; j++)
{ if(inp[i]>inp[j])
ans=false;
}
}
if(ans)
cout<<"YES\n";
else
cout<<"NO\n";
}
return 0;
}
| [
"f20160006@goa.bits-pilani.ac.in"
] | f20160006@goa.bits-pilani.ac.in |
e6e3cadd0b83955d75cd069c44c18f1783a212fb | 44032e513ddb1f8cb6cff80a7b25a14121a1923c | /llvm/lib/Target/GenX/GenXIntrinsics.h | 90ec5ca802ada8a7da4f2594a26596978ffc749a | [
"MIT",
"NCSA"
] | permissive | nineties/cm-compiler | 85e6e1a191a813d7daf7e9ccb0d7046156b075c2 | 9c185da27df6b655c9e1268a6e374c4cbc141255 | refs/heads/master | 2020-04-18T05:14:04.925839 | 2019-01-16T21:13:12 | 2019-01-16T21:19:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,003 | h | /*
* Copyright (c) 2018, Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
//===----------------------------------------------------------------------===//
//
// This file declares a class to access a table of extra information about the
// llvm.genx.* intrinsics, used by the vISA register allocator and function
// writer to decide exactly what operand type to use. The more usual approach
// in an LLVM target is to have an intrinsic map to an instruction in
// instruction selection, then have register category information on the
// instruction. But we are not using the target independent code generator, we
// are generating code directly from LLVM IR.
//
//===----------------------------------------------------------------------===//
#ifndef GENXINTRINSICS_H
#define GENXINTRINSICS_H
#include "GenXVisa.h"
#define GENX_ITR_CATVAL(v) ((v) << CATBASE)
#define GENX_ITR_FLAGENUM(o, v) ((v) << ((o) + FLAGBASE))
#define GENX_ITR_FLAGMASK(o, w) (((1 << (w)) - 1) << ((o) + FLAGBASE))
#define GENX_ITR_FLAGVAL(o) GENX_ITR_FLAGENUM(o, 1)
namespace llvm {
class CallInst;
class GenXIntrinsicInfo {
public:
typedef uint32_t DescrElementType;
private:
const DescrElementType *Args;
static const DescrElementType Table[];
public:
enum {
// General format of intrinsic descriptor words:
// Bits 31..24: Category enumeration
// Bits 23..8: Flags, if any, meaning and layout depends on category
// Bits 7..0: Operand or literal, if any
//
// One exception to the above is LITERAL, where everything that isn't
// the category field is assumed to be the literal value.
//
// If you want to re-apportion space in the descriptor word (typically
// because you need another flag and you can't express what you need to
// do without creating one) then just modify FLAGBASE and FLAGWIDTH
// below, and everything else will shake itself out appropriately.
// Currently 8 bits are allocated for the category enumaration bitfield,
// although the actual enumeration values defined only require 6 bits -
// and there is still plenty of space left over even within that.
// Similarly, there are 8 bits allocated to the operand bitfield, and
// currently the maximum needed is 5.
//
// At the moment, the GENERAL category has 5 unused flag bits available
// to it, the RAW category has 13 unused bits, and the ARGCOUNT category
// has 13 unused bits. No other categories make use of the flags yet,
// so it should be a good while yet before it's necessary to resize
// the bitfields.
FLAGBASE = 8,
FLAGWIDTH = 16,
CATBASE = FLAGBASE + FLAGWIDTH,
CATMASK = ~((1 << CATBASE) - 1),
FLAGMASK = ((~((1 << FLAGBASE) - 1)) ^ CATMASK),
OPNDMASK = ~(CATMASK | FLAGMASK),
// A field that does not contain an operand number or literal value:
END = 0, // end of instruction description
IMPLICITPRED = GENX_ITR_CATVAL(0x01), // implicit predication field
NULLRAW = GENX_ITR_CATVAL(0x02), // null raw operand
ISBARRIER = GENX_ITR_CATVAL(0x03), // intrinsic is barrier: suppress nobarrier attribute
EXECSIZE = GENX_ITR_CATVAL(0x04), // execution size
EXECSIZE_GE2 = GENX_ITR_CATVAL(0x05), // execution size (must be >= 2)
EXECSIZE_GE4 = GENX_ITR_CATVAL(0x06), // execution size (must be >= 4)
EXECSIZE_GE8 = GENX_ITR_CATVAL(0x07), // execution size (must be >= 8)
EXECSIZE_NOT2 = GENX_ITR_CATVAL(0x08), // execution size (cannot be 2)
// A field that contains a literal value the operand field
LITERAL = GENX_ITR_CATVAL(0x09), // literal byte (usually opcode)
LITMASK = ~CATMASK,
// A field that contains an operand number, other than general:
FIRST_OPERAND = GENX_ITR_CATVAL(0x10),
LOG2OWORDS = GENX_ITR_CATVAL(0x10), // log2 number of owords
NUMGRFS = GENX_ITR_CATVAL(0x11), // rounded up number of GRFs
EXECSIZE_FROM_ARG = GENX_ITR_CATVAL(0x12), // exec_size field inferred from width of
// predication arg
SVMGATHERBLOCKSIZE = GENX_ITR_CATVAL(0x13), // svm gather block size, inferred from data type
LOG2OWORDS_PLUS_8 = GENX_ITR_CATVAL(0x14), // log2 number of owords, plus 8
GATHERNUMELTS = GENX_ITR_CATVAL(0x15), // gather/scatter "num elements" field
TRANSPOSEHEIGHT = GENX_ITR_CATVAL(0x16), // block_height field in transpose
LOG2ELTSIZE = GENX_ITR_CATVAL(0x17), // log2 element size in gather/scatter
ARGCOUNT = GENX_ITR_CATVAL(0x18), // Byte containing number of non-undef operands
ARGCOUNTMASK = GENX_ITR_FLAGMASK(0, 3), // Space for minumum argument count
ARGCOUNTMIN1 = GENX_ITR_FLAGENUM(0, 1), // Must have at least one argument
// A field that contains an operand number, other than general, and it
// is the "real" use of the operand, rather than an auxiliary use
// such as a "number of GRFs" field relating to this operand.
FIRST_REAL_OPERAND = GENX_ITR_CATVAL(0x20),
BYTE = GENX_ITR_CATVAL(0x20), // constant byte operand
SHORT = GENX_ITR_CATVAL(0x21), // constant short operand
INT = GENX_ITR_CATVAL(0x22), // constant int operand
ADDRESS = GENX_ITR_CATVAL(0x23), // address operand
PREDICATE = GENX_ITR_CATVAL(0x24), // predicate operand
SAMPLER = GENX_ITR_CATVAL(0x25), // sampler operand
SURFACE = GENX_ITR_CATVAL(0x26), // surface operand
VME = GENX_ITR_CATVAL(0x27), // vme operand
// byte height of media 2D block, inferred from the width operand
// pointed at and the size of the return type or final operand type
MEDIAHEIGHT = GENX_ITR_CATVAL(0x28),
// predication control field from explicit predicate arg
PREDICATION = GENX_ITR_CATVAL(0x29),
// chmask field in load/sample, with exec size bit
SAMPLECHMASK = GENX_ITR_CATVAL(0x2a),
// does not appear in the vISA output, but needs to be two address
// coalesced with result
TWOADDR = GENX_ITR_CATVAL(0x2b),
CONSTVI1ASI32 = GENX_ITR_CATVAL(0x2c), // constant vXi1 written as i32 (used in setp)
RAW = GENX_ITR_CATVAL(0x2d), // raw operand or result,
// Raw descriptor flags, 3 bits used
RAW_UNSIGNED = GENX_ITR_FLAGVAL(0), // raw operand/result must be unsigned
RAW_SIGNED = GENX_ITR_FLAGVAL(1), // raw operand/result must be signed
RAW_NULLALLOWED = GENX_ITR_FLAGVAL(2), // raw operand or result can be null (V0)
URAW = RAW | RAW_UNSIGNED,
SRAW = RAW | RAW_SIGNED,
// A general operand
GENERAL = GENX_ITR_CATVAL(0x30),
// Modifiers for destination or source, 7 bits used
UNSIGNED = GENX_ITR_FLAGVAL(0), // int type forced to unsigned
SIGNED = GENX_ITR_FLAGVAL(1), // int type forced to signed
OWALIGNED = GENX_ITR_FLAGVAL(2), // must be oword aligned
GRFALIGNED = GENX_ITR_FLAGVAL(3), // must be grf aligned
RESTRICTION = GENX_ITR_FLAGMASK(4, 3), // field with operand width restriction
FIXED4 = GENX_ITR_FLAGENUM(4, 1), // operand is fixed size 4 vector and contiguous
CONTIGUOUS = GENX_ITR_FLAGENUM(4, 2), // operand must be contiguous
SCALARORCONTIGUOUS = GENX_ITR_FLAGENUM(4, 3), // operand must be stride 0 or contiguous
TWICEWIDTH = GENX_ITR_FLAGENUM(4, 4), // operand is twice the execution width
STRIDE1 = GENX_ITR_FLAGENUM(4, 5), // horizontal stride must be 1
// Modifiers for destination only, 2 bits used
SATURATION = GENX_ITR_FLAGMASK(7, 2),
SATURATION_DEFAULT = GENX_ITR_FLAGENUM(7, 0), // saturation default: not saturated, fp is
// allowed to bale in to saturate inst
SATURATION_SATURATE = GENX_ITR_FLAGENUM(7, 1), // saturated
SATURATION_NOSAT = GENX_ITR_FLAGENUM(7, 2), // fp not allowed to bale in to saturate inst
SATURATION_INTALLOWED = GENX_ITR_FLAGENUM(7, 3), // int is allowed to bale in to saturate,
// because inst cannot overflow so
// saturation only required on destination
// truncation
// Modifiers for source only, 3 bits used
NOIMM = GENX_ITR_FLAGVAL(7), // source not allowed to be immediate
MODIFIER = GENX_ITR_FLAGMASK(8, 2),
MODIFIER_DEFAULT = GENX_ITR_FLAGENUM(8, 0), // src modifier default: none
MODIFIER_ARITH = GENX_ITR_FLAGENUM(8, 1), // src modifier: arithmetic
MODIFIER_LOGIC = GENX_ITR_FLAGENUM(8, 2), // src modifier: logic
MODIFIER_EXTONLY = GENX_ITR_FLAGENUM(8, 3), // src modifier: extend only
};
struct ArgInfo {
unsigned Info;
// Default constructor, used in GenXBaling to construct an ArgInfo that
// represents an arg of a non-call instruction.
ArgInfo() : Info(GENERAL) {}
// Construct from a field read from the intrinsics info table.
ArgInfo(unsigned Info) : Info(Info) {}
// getCategory : return field category
unsigned getCategory() { return Info & CATMASK; }
// getLogAlignment : get any special alignment requirement, else 0
unsigned getLogAlignment() {
if (isGeneral()) {
if (Info & GRFALIGNED)
return 5;
if (Info & OWALIGNED)
return 4;
return 0;
}
if (isRaw())
return 5;
return 0;
}
// isGeneral : test whether this is a general operand
bool isGeneral() { return getCategory() == GENERAL; }
bool needsSigned() {
if (isGeneral())
return Info & SIGNED;
if (isRaw())
return Info & RAW_SIGNED;
return false;
}
bool needsUnsigned() {
if (isGeneral())
return Info & UNSIGNED;
if (isRaw())
return Info & RAW_UNSIGNED;
return false;
}
bool rawNullAllowed() {
assert(isRaw());
return Info & RAW_NULLALLOWED;
}
// isArgOrRet : test whether this field has an arg index
bool isArgOrRet() {
if (isGeneral()) return true;
if ((Info & CATMASK) >= FIRST_OPERAND)
return true;
return false;
}
// isRealArgOrRet : test whether this field has an arg index, and is
// a "real" use of the arg
bool isRealArgOrRet() {
if (isGeneral()) return true;
if ((Info & CATMASK) >= FIRST_REAL_OPERAND)
return true;
return false;
}
// getArgCountMin : return minimum number of arguments
int getArgCountMin() {
assert(getCategory() == ARGCOUNT);
return (Info & ARGCOUNTMASK) >> FLAGBASE;
}
// getArgIdx : return argument index for this field, or -1 for return value
// (assuming isArgOrRet())
int getArgIdx() { assert(isArgOrRet()); return (Info & OPNDMASK) - 1; }
// getLiteral : for a LITERAL or EXECSIZE field, return the literal value
unsigned getLiteral() { return Info & LITMASK; }
// isRet : test whether this is the field for the return value
// (assuming isArgOrRet())
bool isRet() { return getArgIdx() < 0; }
// isRaw : test whether this is a raw arg or return value
bool isRaw() { return getCategory() == RAW; }
// getSaturation : return saturation info for the arg
unsigned getSaturation() { return Info & SATURATION; }
// getRestriction : return operand width/region restriction, one of
// 0 (no restriction), FIXED4, CONTIGUOUS, TWICEWIDTH
unsigned getRestriction() { return Info & RESTRICTION; }
// isImmediateDisallowed : test whether immediate disallowed
// (assuming isArgOrRet())
bool isImmediateDisallowed() {
assert(isArgOrRet());
if (isGeneral())
return Info & NOIMM;
if (isRaw())
return true;
switch (Info & CATMASK) {
case TWOADDR:
case PREDICATION:
case SURFACE:
case SAMPLER:
case VME:
return true;
default: break;
}
return false;
}
// getModifier : get what source modifier is allowed
unsigned getModifier() {
assert(isGeneral() && isArgOrRet() && !isRet());
return Info & MODIFIER;
}
};
// GenXIntrinsics::iterator : iterate through the fields
class iterator {
const DescrElementType *p;
public:
iterator(const DescrElementType *p) : p(p) {}
iterator &operator++() { ++p; if (*p == END) p = 0; return *this; }
ArgInfo operator*() { return ArgInfo(*p); }
bool operator!=(iterator i) { return p != i.p; }
};
iterator begin() {
assert(isNotNull() && "iterating an intrinsic without info");
return iterator(Args);
}
iterator end() { return iterator(0); }
// Construct a GenXIntrinsicInfo for a particular intrinsic
GenXIntrinsicInfo(unsigned IntrinId);
bool isNull() const { return *getInstDesc() == GenXIntrinsicInfo::END; }
bool isNotNull() const { return !isNull(); }
// Return instruction description.
const DescrElementType *getInstDesc() const { return Args; }
// Get the category and modifier for an arg idx
ArgInfo getArgInfo(int Idx);
// Get the trailing null zone, if any.
unsigned getTrailingNullZoneStart(CallInst *CI);
// Get the category and modifier for the return value
ArgInfo getRetInfo() { return getArgInfo(-1); }
// Get bitmap of allowed execution sizes
unsigned getExecSizeAllowedBits();
// Determine if a predicated destination mask is permitted
bool getPredAllowed();
};
} // namespace llvm
#endif // ndef GENXINTRINSICS_H
| [
"gang.y.chen@intel.com"
] | gang.y.chen@intel.com |
e249c90f3d6575b3eca0059609f90c73312571e4 | 05c1039487d53711217e58eec3a3baa7d98e970c | /HW/3/C_Mindist_2/main.cpp | da76fa055d1f8c6ca924ab0edb038ddc10718240 | [] | no_license | makci97/algo_tinkoff | a388cd9294a36020313f1ee1ca48908f87d4dda1 | 211ec75ace46c5be3cab85f7efafae364461d42a | refs/heads/master | 2020-03-28T19:36:04.547933 | 2018-12-09T14:32:55 | 2018-12-09T14:32:55 | 148,983,628 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,674 | cpp | #include <algorithm>
#include <iostream>
#include <fstream>
#include <sstream>
#include <list>
#include <vector>
#include <stack>
#include <queue>
#include <bitset>
const int MAX_VER = 50000;
std::vector<std::list<int> > read_pairs_graph(
int n, int m, std::ifstream& in_stream
)
{
int u, v;
std::vector<std::list<int> > graph(n + 1);
for (int i = 0; i < m; ++i)
{
in_stream >> u >> v;
graph[u].push_back(v);
graph[v].push_back(u);
}
return graph;
}
int main() {
int n, m, a, b, v;
std::ifstream in_stream;
std::ofstream out_stream;
in_stream.open("mindist2.in");
out_stream.open("mindist2.out");
// read graph
in_stream >> n >> m;
in_stream >> a >> b;
auto graph = read_pairs_graph(n, m, in_stream);
// prepare data containers
std::bitset<MAX_VER + 1> used(false);
std::vector<std::pair<int, int> > dist(n + 1, {-1, -1});
std::queue<int> q;
// start values
used[b] = true;
dist[b] = {0, -1};
q.push(b);
// BFS
while (!q.empty() && !used[a])
{
v = q.front();
q.pop();
for (int neigh: graph[v])
{
if (used[neigh])
continue;
used[neigh] = true;
dist[neigh] = {dist[v].first + 1, v};
q.push(neigh);
}
}
// output
out_stream << dist[a].first;
if (dist[a].first != -1)
{
out_stream << std::endl;
while (a != b)
{
out_stream << a << ' ';
a = dist[a].second;
}
out_stream << b;
}
in_stream.close();
out_stream.close();
return 0;
} | [
"makci.97@mail.ru"
] | makci.97@mail.ru |
637e8511de9d96ac6c05b72e6eb49eb82f996234 | b22588340d7925b614a735bbbde1b351ad657ffc | /athena/Trigger/TrigFTK/TrigFTKSim/src/FTKRawHit.cxx | 8a6253405b741e44b5100669c30fa7e0faded278 | [] | no_license | rushioda/PIXELVALID_athena | 90befe12042c1249cbb3655dde1428bb9b9a42ce | 22df23187ef85e9c3120122c8375ea0e7d8ea440 | refs/heads/master | 2020-12-14T22:01:15.365949 | 2020-01-19T03:59:35 | 2020-01-19T03:59:35 | 234,836,993 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,159 | cxx | /*
Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
*/
#include "TrigFTKSim/FTKRawHit.h"
#include "TrigFTKSim/FTKHit.h"
#include "TrigFTKSim/FTKSplitEncoder.h"
#include "TrigFTKSim/FTKSetup.h"
// needed to read SCTtrk tracks (Constantinos case)
#include "TrigFTKSim/FTKTrackInput.h"
#include "TrigFTKSim/FTKRoad.h"
#include "TrigFTKSim/FTKRoadInput.h"
#include "TrigFTKSim/FTKTrack.h"
#include <fstream>
#include <cmath> // needed for floor()
using namespace std;
FTKRawHit::FTKRawHit()
: TObject(), m_truth(nullptr), m_channels()
{
// nothing to do
reset();
}
/* Special constructor for SCTtrk hits*/
FTKRawHit::FTKRawHit(const FTKTrack* trk, int) :
TObject(), m_truth(nullptr), m_channels()
{
reset();
m_x = trk->getPhi();
m_y = trk->getCotTheta();
m_z = trk->getHalfInvPt();
m_hitType = ftk::SCTtrk;
m_moduleType = ftk::MODULETYPE_INVALID; // set to invalid until it is correctly set
m_layer_disk = 0; // for the scttrk case
// store information about 8L SCT road and track into unused variables:
setBankID(trk->getBankID());
setRoadID(trk->getRoadID());
setTrackID(trk->getTrackID());
// dummy truth, will be replaced by 8L truth
m_truth = new MultiTruth();
}
FTKRawHit::FTKRawHit(const FTKRawHit &cpy) :
TObject(cpy),
m_x(cpy.m_x), m_y(cpy.m_y), m_z(cpy.m_z),
m_hitType(cpy.m_hitType),
m_moduleType(cpy.m_moduleType),
m_IdentifierHash(cpy.m_IdentifierHash),
m_barrel_ec(cpy.m_barrel_ec),
m_layer_disk(cpy.m_layer_disk),
m_phi_module(cpy.m_phi_module),
m_eta_module(cpy.m_eta_module),
m_pi_side(cpy.m_pi_side),
m_ei_strip(cpy.m_ei_strip),
m_n_strips(cpy.m_n_strips),
m_etaWidth(cpy.m_etaWidth),
m_phiWidth(cpy.m_phiWidth),
m_dPhi(cpy.m_dPhi),
m_dEta(cpy.m_dEta),
m_hw_word(cpy.m_hw_word),
m_includesGangedHits(cpy.m_includesGangedHits),
m_eventindex(cpy.m_eventindex),
m_barcode(cpy.m_barcode),
m_barcode_pt(cpy.m_barcode_pt),
m_parentage_mask(cpy.m_parentage_mask),
m_channels(cpy.m_channels)
{
if (cpy.m_truth)
m_truth = new MultiTruth(*(cpy.m_truth));
else
m_truth = nullptr;
}
FTKRawHit::~FTKRawHit()
{
if (m_truth) delete m_truth;
}
// shallow copy - MultiTruth did not used to be copied, but is now!
FTKRawHit& FTKRawHit::operator=(const FTKRawHit &cpy)
{
#ifdef PROTECT_SA // speedup
if (this != &cpy)
#endif
{
m_x = cpy.m_x; m_y = cpy.m_y; m_z = cpy.m_z;
m_hitType = cpy.m_hitType;
m_moduleType = cpy.m_moduleType;
m_IdentifierHash = cpy.m_IdentifierHash;
m_barrel_ec = cpy.m_barrel_ec;
m_layer_disk = cpy.m_layer_disk;
m_phi_module = cpy.m_phi_module;
m_eta_module = cpy.m_eta_module;
m_pi_side = cpy.m_pi_side;
m_ei_strip = cpy.m_ei_strip;
m_n_strips = cpy.m_n_strips;
m_etaWidth = cpy.m_etaWidth;
m_phiWidth = cpy.m_phiWidth;
m_dPhi = cpy.m_dPhi;
m_dEta = cpy.m_dEta;
m_includesGangedHits = cpy.m_includesGangedHits;
m_eventindex = cpy.m_eventindex;
m_barcode = cpy.m_barcode;
m_barcode_pt = cpy.m_barcode_pt;
m_parentage_mask = cpy.m_parentage_mask;
m_hw_word = cpy.m_hw_word;
m_truth = nullptr;
m_channels.assign(cpy.m_channels.begin(),cpy.m_channels.end());
if (cpy.m_truth)
m_truth = new MultiTruth(*(cpy.m_truth));
///
}
return *this;
}
void FTKRawHit::reset()
{
m_x = 0.;
m_y = 0.;
m_z = 0.;
m_hitType = 0;
m_moduleType = ftk::MODULETYPE_INVALID;
m_IdentifierHash = 0;
m_barrel_ec = 0;
m_layer_disk = 0;
m_phi_module = 0;
m_eta_module = 0;
m_pi_side = 0;
m_ei_strip = 0;
m_n_strips = 0;
m_etaWidth = 0;
m_phiWidth = 0;
m_dPhi = 0.;
m_dEta = 0.;
m_includesGangedHits = false;
m_barcode = -1;
m_eventindex = -1;
m_barcode_pt = 0.;
m_parentage_mask = 0;
m_hw_word = 0;
if( m_truth ) {
delete m_truth;
m_truth = 0;
}
m_channels.clear();
}
ostream &operator<<(std::ostream& out,const FTKRawHit& hit)
{
out << "S" << "\t" << hit.m_x << "\t" << hit.m_y << "\t" << hit.m_z << "\t";
out << hit.m_hitType << "\t" << hit.m_barrel_ec << "\t" << hit.m_layer_disk << "\t";
out << hit.m_phi_module << "\t" << hit.m_eta_module << "\t";
out << hit.m_pi_side << "\t" << hit.m_ei_strip << "\t" << hit.m_n_strips;
return out;
}
istream& operator>>(istream &input, FTKRawHit &hit)
{
int dummy;
input >> hit.m_x >> hit.m_y >> hit.m_z;
input >> hit.m_hitType >> hit.m_barrel_ec;
input >> hit.m_layer_disk >> hit.m_phi_module >> hit.m_eta_module;
input >> hit.m_pi_side >> hit.m_ei_strip;
input >> hit.m_n_strips;
if (!input) {
// is a very old format w/o the number of consecutive strips
hit.m_n_strips = 1;
} else {
// June 2009 format: remaining fields are the UniqueBarcode and the highest pt contributing to the channel, in that order.
// August 2009 format: remaing fields are event_index, barcode, highest pt, parentage mask.
streampos position = input.tellg();
input >> hit.m_barcode;
if( input ) {
// is not an old format w/o geant truth info
input >> hit.m_barcode_pt;
// Check for August 2009
input >> dummy;
if( input ) {
// August 2009 - need to go back and re-read
input.seekg(position);
input >> hit.m_eventindex;
input >> hit.m_barcode;
input >> hit.m_barcode_pt;
input >> hit.m_parentage_mask;
}
else {
// June 2009 -- set barcode and event index to new format.
hit.m_eventindex = hit.m_barcode/100000;
hit.m_barcode %= 100000;
hit.m_parentage_mask = 0;
}
}
}
input >> hit.m_IdentifierHash;
// change the layer id according the FTK use
hit.normalizeLayerID();
return input;
}
istream& clusterP( istream &input , FTKRawHit &hit )
{
// added March, 2012
input >> hit.m_x >> hit.m_y >> hit.m_z;
hit.setHitType(ftk::PIXEL);
hit.setModuleType(ftk::MODULETYPE_PIXEL);
input >> hit.m_barrel_ec;
input >> hit.m_layer_disk;
input >> hit.m_phi_module >> hit.m_eta_module;
input >> hit.m_pi_side >> hit.m_ei_strip;
input >> hit.m_dPhi >> hit.m_dEta;
// The wrapper is filled with m_pi_side + dPhi, for example, so correct back...
hit.m_dPhi -= hit.m_pi_side;
hit.m_dEta -= hit.m_ei_strip;
input >> hit.m_phiWidth >> hit.m_etaWidth;
input >> hit.m_n_strips;
input >> hit.m_eventindex;
input >> hit.m_barcode;
input >> hit.m_barcode_pt;
input >> hit.m_parentage_mask;
// Since clustering is already done, there should only be 1 barcode per "hit".
// Instead of doing anything too complicated for m_truth, we can just store the one barcode.
//hit.m_truth = new MultiTruth( std::make_pair(hit.m_barcode,hit.m_eventindex) );
hit.m_truth = new MultiTruth( std::make_pair(hit.m_eventindex,hit.m_barcode) );
// change the layer id according the FTK use
hit.normalizeLayerID();
return input;
}
istream& clusterC( istream &input , FTKRawHit &hit ) {
// added March, 2012
input >> hit.m_x >> hit.m_y >> hit.m_z;
input >> hit.m_hitType;
input >> hit.m_barrel_ec;
input >> hit.m_layer_disk;
input >> hit.m_phi_module >> hit.m_eta_module;
input >> hit.m_pi_side >> hit.m_ei_strip;
input >> hit.m_dPhi;
// The wrapper is filled with m_pi_side + dPhi, so correct back...
hit.m_dPhi -= hit.m_ei_strip;
input >> hit.m_n_strips;
if( hit.m_n_strips < 1 ) { FTKSetup::PrintMessageFmt(ftk::sevr,"Found a C line (SCT cluster) in wrapper with n_strips < 1 (%d)\n",hit.m_n_strips); }
input >> hit.m_eventindex;
input >> hit.m_barcode;
input >> hit.m_barcode_pt;
input >> hit.m_parentage_mask;
// Since clustering is already done, there should only be 1 barcode per "hit".
// Instead of doing anything too complicated for m_truth, we can just store the one barcode.
//hit.m_truth = new MultiTruth( std::make_pair(hit.m_barcode,hit.m_eventindex) );
hit.m_truth = new MultiTruth( std::make_pair(hit.m_eventindex,hit.m_barcode) );
// change the layer id according the FTK use
hit.normalizeLayerID();
return input;
}
/** This function change the layer id, how it comes from the atlas numbering
method, from the id used in FTK pmap. This method update the
m_layer_disk field for the SCT, doesn't affect the pixels
*/
void FTKRawHit::normalizeLayerID()
{
if (m_hitType != ftk::SCT ) {
return;
}
else if( FTKSetup::getFTKSetup().getITkMode() ) {
m_layer_disk = (2*m_layer_disk) + m_pi_side;
}
else if (m_barrel_ec == 0){ // is barrel
if (m_layer_disk==0 && m_pi_side == 1) m_layer_disk = 0;
else if(m_layer_disk==0 && m_pi_side == 0) m_layer_disk = 1;
else if(m_layer_disk==1 && m_pi_side == 0) m_layer_disk = 2;
else if(m_layer_disk==1 && m_pi_side == 1) m_layer_disk = 3;
else if(m_layer_disk==2 && m_pi_side == 1) m_layer_disk = 4;
else if(m_layer_disk==2 && m_pi_side == 0) m_layer_disk = 5;
else if(m_layer_disk==3 && m_pi_side == 0) m_layer_disk = 6;
else if(m_layer_disk==3 && m_pi_side == 1) m_layer_disk = 7;
}
else {
/* this is complicated. */
/* First, figure out if we're on the inside or outside in z, and inner or outer ring */
int outside = 0;
int inner_ring = 0;
if (m_eta_module > 0) inner_ring = 1;
if ((m_eta_module == 0 || m_eta_module == 2) && m_pi_side == 1) outside = 1;
if (m_eta_module == 1 && m_pi_side == 0) outside = 1;
/* disk 8 flipped: special case */
if (m_layer_disk == 8 && m_pi_side == 1) outside = 0;
if (m_layer_disk == 8 && m_pi_side == 0) outside = 1;
/* split the disks up by inner/outer, and by side */
m_layer_disk = 4*m_layer_disk + 2*inner_ring + outside;
/* aaaaand fix eta index */
if (inner_ring) m_eta_module = m_eta_module - 1;
if (FTKSetup::getFTKSetup().getVerbosity() > 3) {
printf("Converted disk %d eta %d side %d to split disk %d eta %d\n",
m_layer_disk, m_eta_module, m_pi_side,
m_layer_disk, m_eta_module);
}
}
}
/** this function convert an hit in the format that has all
the information needed to be linked in the ATLAS geometry, to
the simple hit codified in the mode internally used by the AM */
FTKHit FTKRawHit::getFTKHit(const FTKPlaneMap *pmap) const {
// retrieve layer info from the pmap
FTKPlaneSection &pinfo = pmap->getMap(m_hitType,!(m_barrel_ec==0),m_layer_disk);
int plane = pinfo.getPlane();
int section = pinfo.getSection();
int sector;
if( FTKSetup::getFTKSetup().getITkMode() ) {
// Working at least for SCT barrel
// Ranges from dumping detector info --
// phi_modules in [0,..,72]
// eta_modules in [-56,..,56]
// m_barrel_ec in [-2,0,2] (C-side,B,A-side)
sector = (m_phi_module*100000) + ((m_eta_module+60)*100) + ((m_barrel_ec+2)*10) + section;
}
else if (m_barrel_ec) {
// is in the end-caps
int ieta = m_eta_module;
const int NEGEC (-2);
int code = (ieta+1)*20 + (m_barrel_ec == NEGEC)*10 + section;
sector = m_phi_module*1000+code;
}
else if (FTKSetup::getFTKSetup().getIBLMode()==1 && m_layer_disk==0 && m_hitType==ftk::PIXEL && m_barrel_ec==0 ){
// this is an IBL module, without 3d sensors, only possible case up to the TDAQ TDR
sector = m_phi_module*1000+m_eta_module+8; // ibl was 6
}
else if (FTKSetup::getFTKSetup().getIBLMode()==2 && m_layer_disk==0 && m_hitType==ftk::PIXEL && m_barrel_ec==0 ){
// this is an IBL module with 3d sensors, 20 modules in total instead of 16
sector = m_phi_module*1000+m_eta_module+10;
}
else {
// is a generic module of the barrel region
sector = m_phi_module*1000+m_eta_module+6;
}
// retrieve information
int ndim = pmap->getPlane(plane,section).getNDimension();
FTKHit reshit(ndim);
reshit.setITkMode( FTKSetup::getFTKSetup().getITkMode() );
reshit.setIdentifierHash(getIdentifierHash());
reshit.setPlane(plane);
reshit.setSector(sector);
reshit.setHwWord(m_hw_word);
if (m_moduleType == ftk::MODULETYPE_SCT){
reshit.setScalingCoordToHWCoord(0,SCT_row_scaling);
reshit.setScalingCoordToHWCoord(1,0);
}
else if (m_moduleType == ftk::MODULETYPE_PIXEL) {
reshit.setScalingCoordToHWCoord(0,PIX_row_scaling);
reshit.setScalingCoordToHWCoord(1,PIX_column_scaling);
}
else if (m_moduleType == ftk::MODULETYPE_IBL_PLANAR) {
reshit.setScalingCoordToHWCoord(0,IBL_planar_row_scaling);
reshit.setScalingCoordToHWCoord(1,IBL_planar_column_scaling);
}
else if (m_moduleType == ftk::MODULETYPE_IBL3D) {
reshit.setScalingCoordToHWCoord(0,IBL_3D_row_scaling);
reshit.setScalingCoordToHWCoord(1,IBL_3D_column_scaling);
}
else {// don't think i should be here!
reshit.setScalingCoordToHWCoord(0,0);
reshit.setScalingCoordToHWCoord(1,0);
}
switch (m_hitType) {
case ftk::PIXEL:
reshit.setEtaWidth(getEtaWidth());
reshit.setPhiWidth(getPhiWidth());
reshit.getCoord().setIncludesGanged(getIncludesGanged());
reshit.setNStrips(getNStrips());
reshit[0] = m_pi_side+m_dPhi;
reshit[1] = m_ei_strip+m_dEta;
break;
case ftk::SCT:
// reshit[0] = m_ei_strip+(m_n_strips-1.)/2.;
reshit[0] = m_ei_strip+m_dPhi;
reshit.setNStrips(getNStrips());
reshit.setEtaWidth(getEtaWidth());
reshit.setPhiWidth(getPhiWidth());
break;
case ftk::SCTtrk:
// cy to adjust 8L track pars if they exceed thresholds
double mod_x = ( m_x > ftk::PI ? ftk::PI : (m_x < -ftk::PI ? -ftk::PI : m_x) );
double mod_y = ( m_y > ftk::COTTMAX ? ftk::COTTMAX : (m_y < -ftk::COTTMAX ? -ftk::COTTMAX : m_y) );
double mod_z = ( m_z > ftk::CURVMAX ? ftk::CURVMAX : (m_z < -ftk::CURVMAX ? -ftk::CURVMAX : m_z) );
// FlagAK: changed all int() conversions to floor() - this is needed for FTKSSMap to correctly guess module offset
int phiMod=static_cast<int>(floor(mod_x/(2*ftk::PI)*(pmap->getPlane(plane,section).getNumFi())));
if(phiMod < 0) phiMod+=pmap->getPlane(plane,section).getNumFi();
#ifdef SPLIT_OLDCTHETA
int cottMod=static_cast<int>(floor((ftk::COTTMAX+mod_y)/(2*ftk::COTTMAX)*(pmap->getPlane(plane,section).getNumCott())));
#else
// for cot(theta), we now use a hardooded table - see FTKSplitEncoder.{h,cxx}
int cottMod=FTKSplitEncoder::get().cthetaIndex(mod_y);
#endif
int curvMod=static_cast<int>(floor((ftk::CURVMAX+mod_z)/(2*ftk::CURVMAX)*(pmap->getPlane(plane,section).getNumCurv())));
sector = phiMod*10000+cottMod*100+curvMod;
//cout << "mod_x: " << mod_x << "\tphiMod: " << phiMod << endl; // cy debug
//cout << "sector: " << sector << "\tplane: " << plane << endl; // cy debug
reshit.setSector(sector);
reshit.setBankID(getBankID());
reshit.setRoadID(getRoadID());
reshit.setTrackID(getTrackID());
reshit[0] = mod_x;
reshit[1] = mod_y;
reshit[2] = mod_z;
break;
}
// convert also the eventual channels
vector<FTKRawHit>::const_iterator ichannel = m_channels.begin();
vector<FTKRawHit>::const_iterator ichannel_end = m_channels.end();
for (;ichannel!=ichannel_end;++ichannel) {
reshit.addChannel((*ichannel).getFTKHit(pmap));
}
return reshit;
}
void FTKRawHit::setTruth(const MultiTruth& v)
{
if(m_truth) {
*m_truth = v;
} else {
m_truth = new MultiTruth(v);
}
}
| [
"rushioda@lxplus754.cern.ch"
] | rushioda@lxplus754.cern.ch |
0e232882e4e54b8d7a1bdb097d469475dbecf1e5 | 85221a64ad699e9f4d4d3bc508fa776c6b2e1d16 | /DummyClients/DummyClients/include/aws/core/client/AWSError.h | 9155c0f1156803bc838b0324ad16fb24620ece00 | [
"MIT"
] | permissive | joonhochoi/GameLift | bf6dbabcba868540bd9cf834623b189c65628b39 | 81bbad1e922d977bd885cdaa37f2e05d4fe2b966 | refs/heads/master | 2020-12-24T12:06:37.600884 | 2016-10-27T06:47:53 | 2016-10-27T06:47:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,397 | h | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/core/Core_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
namespace Aws
{
namespace Client
{
enum class CoreErrors;
/**
* Container for Error enumerations with additional exception information. Name, message, retryable etc....
*/
template<typename ERROR_TYPE>
class AWSError
{
public:
/**
* Initializes AWSError object as empty with the error not being retryable.
*/
AWSError() : m_isRetryable(false) {}
/**
* Initializes AWSError object with errorType, exceptionName, message, and retryable flag.
*/
AWSError(ERROR_TYPE errorType, Aws::String exceptionName, const Aws::String message, bool isRetryable) :
m_errorType(errorType), m_exceptionName(exceptionName), m_message(message), m_isRetryable(isRetryable) {}
/**
* Initializes AWSError object with errorType and retryable flag. ExceptionName and message are empty.
*/
AWSError(ERROR_TYPE errorType, bool isRetryable) :
m_errorType(errorType), m_isRetryable(isRetryable) {}
//by policy we enforce all clients to contain a CoreErrors alignment for their Errors.
AWSError(const AWSError<CoreErrors>& rhs) :
m_errorType(static_cast<ERROR_TYPE>(rhs.GetErrorType())), m_exceptionName(rhs.GetExceptionName()), m_message(rhs.GetMessage()), m_isRetryable(rhs.ShouldRetry())
{}
/**
* Gets underlying errorType.
*/
inline const ERROR_TYPE GetErrorType() const { return m_errorType; }
/**
* Gets the underlying ExceptionName.
*/
inline const Aws::String& GetExceptionName() const { return m_exceptionName; }
/**
*Sets the underlying ExceptionName.
*/
inline void SetExceptionName(const Aws::String& exceptionName) { m_exceptionName = exceptionName; }
/**
* Gets the error message.
*/
inline const Aws::String& GetMessage() const { return m_message; }
/**
* Sets the error message
*/
inline void SetMessage(const Aws::String& message) { m_message = message; }
/**
* returns whether or not this error is eligible for retry.
*/
inline bool ShouldRetry() const { return m_isRetryable; }
private:
ERROR_TYPE m_errorType;
Aws::String m_exceptionName;
Aws::String m_message;
bool m_isRetryable;
};
} // namespace Client
} // namespace Aws
| [
"spacesun@naver.com"
] | spacesun@naver.com |
0a3939775c310c2d9d9bd51db54bea24bd5cf4be | be18dc7b41b872575eade0697bea8ad84c212776 | /cocos2d/external/bullet/include/bullet/BulletCollision/CollisionShapes/btConvexShape.h | 243c0b89564ddf02484593c6c0dd57eae30fa0c5 | [] | no_license | YaumenauPavel/Cocos2d-x-Snake | 4cbe10b365abf34cc7e938258ceffaff834d0e5f | 3c048b63ee6846ac23c14c89f06fc4fb22fba05e | refs/heads/master | 2023-07-09T20:30:51.867670 | 2021-03-18T08:52:34 | 2021-03-18T08:52:34 | 255,822,723 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,437 | h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_CONVEX_SHAPE_INTERFACE1
#define BT_CONVEX_SHAPE_INTERFACE1
#include "btCollisionShape.h"
#include "LinearMath/btVector3.h"
#include "LinearMath/btTransform.h"
#include "LinearMath/btMatrix3x3.h"
#include "btCollisionMargin.h"
#include "LinearMath/btAlignedAllocator.h"
#define MAX_PREFERRED_PENETRATION_DIRECTIONS 10
/// The btConvexShape is an abstract shape interface, implemented by all convex shapes such as btBoxShape, btConvexHullShape etc.
/// It describes general convex shapes using the localGetSupportingVertex interface, used by collision detectors such as btGjkPairDetector.
ATTRIBUTE_ALIGNED16(class) btConvexShape : public btCollisionShape
{
public:
BT_DECLARE_ALIGNED_ALLOCATOR();
btConvexShape();
virtual ~btConvexShape();
virtual btVector3 localGetSupportingVertex(const btVector3 &vec) const = 0;
////////
#ifndef __SPU__
virtual btVector3 localGetSupportingVertexWithoutMargin(const btVector3 &vec) const = 0;
#endif //#ifndef __SPU__
btVector3 localGetSupportVertexWithoutMarginNonVirtual(const btVector3 &vec) const;
btVector3 localGetSupportVertexNonVirtual(const btVector3 &vec) const;
btScalar getMarginNonVirtual() const;
void getAabbNonVirtual(const btTransform &t, btVector3 &aabbMin, btVector3 &aabbMax) const;
virtual void project(const btTransform &trans, const btVector3 &dir, btScalar &min, btScalar &max) const;
//notice that the vectors should be unit length
virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,
btVector3* supportVerticesOut,
int numVectors) const = 0;
///getAabb's default implementation is brute force, expected derived classes to implement a fast dedicated version
void getAabb(const btTransform &t, btVector3 &aabbMin, btVector3 &aabbMax) const = 0;
virtual void getAabbSlow(const btTransform &t, btVector3 &aabbMin, btVector3 &aabbMax) const = 0;
virtual void setLocalScaling(const btVector3 &scaling) = 0;
virtual const btVector3 &getLocalScaling() const = 0;
virtual void setMargin(btScalar margin) = 0;
virtual btScalar getMargin() const = 0;
virtual int getNumPreferredPenetrationDirections() const = 0;
virtual void getPreferredPenetrationDirection(int index, btVector3 &penetrationVector) const = 0;
};
#endif //BT_CONVEX_SHAPE_INTERFACE1
| [
"evmenov.pavel@gmail.com"
] | evmenov.pavel@gmail.com |
66e1f6a8fa048589cf9d0f1979641f7c04447475 | 29054be5fd8893c79e5f899f8bcf85f0ce767a2e | /p4/jugador.h | 7529b38baee7fa7ed8a6c2fdc23d4d7584adc84c | [] | no_license | hromero99/CPP-OOP-Practices | 5cf4f6f8f83bf9bd13935cfcf7ab2ecb38e15bd7 | 0bcff6769e2c7575fbdcee2466677d746de615a0 | refs/heads/master | 2020-09-26T19:56:47.480091 | 2019-12-12T23:58:35 | 2019-12-12T23:58:35 | 226,332,014 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 933 | h | #ifndef _JUGADOR_H_
#define _JUGADOR_H_
#include "persona.h"
#include <list>
#include <fstream>
typedef struct apuesta{
int tipo;
std::string valor;
int cantidad;
} Apuesta;
class Jugador : public Persona{
private:
int dinero_;
std::string codigo_;
std::list<Apuesta> apuestas_;
public:
Jugador(const std::string & dni,const std::string & codigo, const std::string & nombre="", const std::string & apellidos ="", int edad=0, \
const std::string & direccion="", const std::string &localidad="",const std::string & provincia="",const std::string & pais="");
inline void setDinero(int newDinero){dinero_ = newDinero;}
inline int getDinero()const { return dinero_;}
inline void setCodigo(std::string newCodigo){codigo_ = newCodigo;}
inline std::string getCodigo() {return codigo_;}
inline std::list<Apuesta> getApuestas(){return apuestas_;}
void setApuestas();
};
#endif | [
"hromerolopez@protonmail.com"
] | hromerolopez@protonmail.com |
dd0f4bace41155d25b697d55887e622e15c7b2ee | 8018f269727b5d698afe0b9dc5eb1680b2eaf1e4 | /Codeforces/273/D.cpp | 9f53fd84b315205f10586b5097ac086730e7e11c | [
"MIT"
] | permissive | Mindjolt2406/Competitive-Programming | 1c68a911669f4abb7ca124f84b2b75355795651a | 54e8efafe426585ef0937637da18b7aaf0fef5e5 | refs/heads/master | 2022-03-20T14:43:37.791926 | 2022-01-29T11:34:45 | 2022-01-29T11:34:45 | 157,658,857 | 2 | 0 | null | 2019-02-10T08:48:25 | 2018-11-15T05:50:05 | C++ | UTF-8 | C++ | false | false | 2,171 | cpp | #include<bits/stdc++.h>
#define mt make_tuple
#define mp make_pair
#define pu push_back
#define INF 1000000001
#define MOD 1000000007
#define ll long long int
#define ld long double
#define vi vector<int>
#define vll vector<long long int>
#define fi first
#define se second
#define sc(n) scanf("%d",&n);
#define scll(n) scanf("%lld",&n);
#define scld(n) scanf("%Lf",&n);
#define scr(s) {char temp[1000000];scanf("%s",temp);s = temp;}
#define t1(x) cerr<<#x<<" : "<<x<<endl
#define t2(x, y) cerr<<#x<<" : "<<x<<" "<<#y<<" : "<<y<<endl
#define t3(x, y, z) cerr<<#x<<" :" <<x<<" "<<#y<<" : "<<y<<" "<<#z<<" : "<<z<<endl
#define t4(a,b,c,d) cerr<<#a<<" : "<<a<<" "<<#b<<" : "<<b<<" "<<#c<<" : "<<c<<" "<<#d<<" : "<<d<<endl
#define t5(a,b,c,d,e) cerr<<#a<<" : "<<a<<" "<<#b<<" : "<<b<<" "<<#c<<" : "<<c<<" "<<#d<<" : "<<d<<" "<<#e<<" : "<<e<<endl
#define t6(a,b,c,d,e,f) cerr<<#a<<" : "<<a<<" "<<#b<<" : "<<b<<" "<<#c<<" : "<<c<<" "<<#d<<" : "<<d<<" "<<#e<<" : "<<e<<" "<<#f<<" : "<<f<<endl
#define GET_MACRO(_1,_2,_3,_4,_5,_6,NAME,...) NAME
#define t(...) GET_MACRO(__VA_ARGS__,t6, t5, t4, t3, t2, t1)(__VA_ARGS__)
#define _ cout<<"here"<<endl;
using namespace std;
ll dp[1000][1000] = {0};
ll recur(int i,int j,int count,int r,int g,int max1)
{
t(i,j,count,r,g);
ll a = 0,b = 0;
if(dp[i][j]!=-1) return dp[i][j];
if(r<0 || g<0) {dp[i][j] = 0;return 0;}
if(count==0) {dp[i][j] = 1;return 1;}
dp[i][j] = 0;
dp[i+1][j] = recur(i+1,j,count-1,r-count,g,max1);
dp[i][j+1] = recur(i,j+1,count-1,r,g-count,max1);
if(dp[i+1][j] >=0) dp[i][j]+=dp[i+1][j];dp[i][j]%=MOD;
if(dp[i][j+1]>=0)dp[i][j]+=dp[i][j+1];dp[i][j]%=MOD;
t(i,j,count,r,g,dp[i][j]);
return dp[i][j];
}
int main()
{
int r,g;
sc(r);sc(g);
int max1 = 1;
for(int i=1;i<=1000;i++)
{
int c = i*i+i;
if(c<2*(r+g)) {max1 = i;}
else if(c==2*(r+g)) {max1 = i;break;}
else break;
}
for(int i=0;i<=max1;i++)
{
for(int j=0;j<=max1;j++) dp[i][j] = -1;
}
ll c = recur(0,0,max1,r,g,max1);
cout<<c<<endl;
for(int i=0;i<=max1;i++) for(int j=0;j<=max1;j++) t(i,j,dp[i][j]);
return 0;
}
| [
"rathin7@gmail.com"
] | rathin7@gmail.com |
c52e63848c1889b23c6e8c6eb053f5823a5d27d8 | f177993b13e97f9fecfc0e751602153824dfef7e | /ImPro/ImProFilters/AR2WarpController/BoardCastOutputPin.cpp | cef0fce7e8083cb42f8c0cbcee40a676734ecad8 | [] | no_license | svn2github/imtophooksln | 7bd7412947d6368ce394810f479ebab1557ef356 | bacd7f29002135806d0f5047ae47cbad4c03f90e | refs/heads/master | 2020-05-20T04:00:56.564124 | 2010-09-24T09:10:51 | 2010-09-24T09:10:51 | 11,787,598 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,668 | cpp | #include "StdAfx.h"
#include "BoardCastOutputPin.h"
CBoardCastOutputPin::CBoardCastOutputPin(
__in_opt LPCTSTR pObjectName,
__inout CMuxTransformFilter *pTransformFilter,
__inout HRESULT * phr,
__in_opt LPCWSTR pPinName)
: CMuxTransformOutputPin(pObjectName, pTransformFilter, phr, pPinName)
{
}
#ifdef UNICODE
CBoardCastOutputPin::CBoardCastOutputPin(
__in_opt LPCSTR pObjectName,
__inout CMuxTransformFilter *pTransformFilter,
__inout HRESULT * phr,
__in_opt LPCWSTR pPinName)
: CMuxTransformOutputPin(pObjectName, pTransformFilter, phr, pPinName)
{
}
#endif
// destructor
CBoardCastOutputPin::~CBoardCastOutputPin()
{
}
HRESULT
CBoardCastOutputPin::CheckConnect(IPin *pPin)
{
HRESULT hr = m_pTransformFilter->CheckConnect(PINDIR_OUTPUT,this, pPin);
if (FAILED(hr)) {
return hr;
}
return CBaseOutputPin::CheckConnect(pPin);
}
// check a given transform - must have selected input type first
HRESULT
CBoardCastOutputPin::CheckMediaType(const CMediaType* pmtOut)
{
// must have selected input first
return m_pTransformFilter->CheckOutputType(pmtOut, this);
}
// return a specific media type indexed by iPosition
HRESULT
CBoardCastOutputPin::GetMediaType(
int iPosition,
__inout CMediaType *pMediaType)
{
return m_pTransformFilter->GetMediaType(iPosition,this, pMediaType);
}
HRESULT
CBoardCastOutputPin::CompleteConnect(IPin *pReceivePin)
{
HRESULT hr = m_pTransformFilter->CompleteConnect(PINDIR_OUTPUT, this, pReceivePin);
if (FAILED(hr)) {
return hr;
}
//for (int i=0; i< m_pOu
return DecideAllocator(m_pInputPin, &m_pAllocator);
} | [
"ndhumuscle@fa729b96-8d43-11de-b54f-137c5e29c83a"
] | ndhumuscle@fa729b96-8d43-11de-b54f-137c5e29c83a |
20e4d2e082a146daf5f1d216399b8051c02b3468 | c231ff2970daaf1283c4b4336bbc42e4cd4eda42 | /ExperimentalITK/Algorithms/itkMultiLabelSTAPLEImageFilter.h | 225029bea51c466e6baa3857e1d2ba06a18d2b26 | [] | no_license | ntustison/Utilities | e1b39c01545f73e7f233d67f52507f9558c06d60 | bd50b9856e8d78db5f9b1881e92171a493ed3fe2 | refs/heads/master | 2021-10-23T16:25:15.197722 | 2021-10-21T00:32:28 | 2021-10-21T00:32:28 | 1,518,882 | 11 | 11 | null | null | null | null | UTF-8 | C++ | false | false | 10,926 | h | /*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: $RCSfile: itkMultiLabelSTAPLEImageFilter.h,v $
Language: C++
Date: $Date: 2004/03/01 19:44:21 $
Version: $Revision: 1.1 $
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#ifndef __itkMultiLabelSTAPLEImageFilter_h
#define __itkMultiLabelSTAPLEImageFilter_h
#include "itkImage.h"
#include "itkImageToImageFilter.h"
#include "itkImageRegionIterator.h"
#include "itkImageRegionConstIterator.h"
#include "vector"
#include "itkArray.h"
#include "itkArray2D.h"
namespace itk
{
/** \class MultiLabelSTAPLEImageFilter
*
* \brief This filter performs a pixelwise combination of an arbitrary number
* of input images, where each of them represents a segmentation of the same
* scene (i.e., image).
*
* The labelings in the images are weighted relative to each other based on
* their "performance" as estimated by an expectation-maximization
* algorithm. In the process, a ground truth segmentation is estimated, and
* the estimated performances of the individual segmentations are relative to
* this estimated ground truth.
*
* The algorithm is based on the binary STAPLE algorithm by Warfield et al. as
* published originally in
*
* S. Warfield, K. Zou, W. Wells, "Validation of image segmentation and expert
* quality with an expectation-maximization algorithm" in MICCAI 2002: Fifth
* International Conference on Medical Image Computing and Computer-Assisted
* Intervention, Springer-Verlag, Heidelberg, Germany, 2002, pp. 298-306
*
* The multi-label algorithm implemented here is described in detail in
*
* T. Rohlfing, D. B. Russakoff, and C. R. Maurer, Jr., "Performance-based
* classifier combination in atlas-based image segmentation using
* expectation-maximization parameter estimation," IEEE Transactions on
* Medical Imaging, vol. 23, pp. 983-994, Aug. 2004.
*
* \par INPUTS
* All input volumes to this filter must be segmentations of an image,
* that is, they must have discrete pixel values where each value represents
* a different segmented object.
*
* Input volumes must all contain the same size RequestedRegions. Not all
* input images must contain all possible labels, but all label values must
* have the same meaning in all images.
*
* The filter can optionally be provided with estimates for the a priori class
* probabilities through the SetPriorProbabilities function. If no estimate is
* provided, one is automatically generated by analyzing the relative
* frequencies of the labels in the input images.
*
* \par OUTPUTS
* The filter produces a single output volume. Each output pixel
* contains the label that has the highest probability of being the correct
* label, based on the performance models of the individual segmentations.
* If the maximum probaility is not unique, i.e., if more than one label have
* a maximum probability, then an "undecided" label is assigned to that output
* pixel.
*
* By default, the label used for undecided pixels is the maximum label value
* used in the input images plus one. Since it is possible for an image with
* 8 bit pixel values to use all 256 possible label values, it is permissible
* to combine 8 bit (i.e., byte) images into a 16 bit (i.e., short) output
* image.
*
* In addition to the combined image, the estimated confusion matrices for
* each of the input segmentations can be obtained through the
* GetConfusionMatrix member function.
*
* \par PARAMETERS
* The label used for "undecided" labels can be set using
* SetLabelForUndecidedPixels. This functionality can be unset by calling
* UnsetLabelForUndecidedPixels.
*
* A termination threshold for the EM iteration can be defined by calling
* SetTerminationUpdateThreshold. The iteration terminates once no single
* parameter of any confusion matrix changes by less than this
* threshold. Alternatively, a maximum number of iterations can be specified
* by calling SetMaximumNumberOfIterations. The algorithm may still terminate
* after a smaller number of iterations if the termination threshold criterion
* is satisfied.
*
* \par EVENTS
* This filter invokes IterationEvent() at each iteration of the E-M
* algorithm. Setting the AbortGenerateData() flag will cause the algorithm to
* halt after the current iteration and produce results just as if it had
* converged. The algorithm makes no attempt to report its progress since the
* number of iterations needed cannot be known in advance.
*
* \author Torsten Rohlfing, SRI International, Neuroscience Program
*/
template <typename TInputImage, typename TOutputImage = TInputImage,
typename TWeights = float >
class ITK_EXPORT MultiLabelSTAPLEImageFilter :
public ImageToImageFilter< TInputImage, TOutputImage >
{
public:
/** Standard class typedefs. */
typedef MultiLabelSTAPLEImageFilter Self;
typedef ImageToImageFilter< TInputImage, TOutputImage > Superclass;
typedef SmartPointer<Self> Pointer;
typedef SmartPointer<const Self> ConstPointer;
/** Method for creation through the object factory. */
itkNewMacro(Self);
/** Run-time type information (and related methods) */
itkTypeMacro(MultiLabelSTAPLEImageFilter, ImageToImageFilter);
/** Extract some information from the image types. Dimensionality
* of the two images is assumed to be the same. */
typedef typename TOutputImage::PixelType OutputPixelType;
typedef typename TInputImage::PixelType InputPixelType;
/** Extract some information from the image types. Dimensionality
* of the two images is assumed to be the same. */
itkStaticConstMacro(ImageDimension, unsigned int,
TOutputImage::ImageDimension);
/** Image typedef support */
typedef TInputImage InputImageType;
typedef TOutputImage OutputImageType;
typedef typename InputImageType::Pointer InputImagePointer;
typedef typename OutputImageType::Pointer OutputImagePointer;
/** Superclass typedefs. */
typedef typename Superclass::OutputImageRegionType OutputImageRegionType;
/** Iterator types. */
typedef ImageRegionConstIterator< TInputImage > InputConstIteratorType;
typedef ImageRegionIterator< TOutputImage> OutputIteratorType;
/** Confusion matrix typedefs. */
typedef TWeights WeightsType;
typedef Array2D<WeightsType> ConfusionMatrixType;
typedef Array<WeightsType> PriorProbabilitiesType;
/** Set maximum number of iterations.
*/
void SetMaximumNumberOfIterations( const unsigned int mit )
{
this->m_MaximumNumberOfIterations = mit;
this->m_HasMaximumNumberOfIterations = true;
this->Modified();
}
/** Unset label value for undecided pixels and turn on automatic selection.
*/
void UnsetMaximumNumberOfIterations()
{
if ( this->m_HasMaximumNumberOfIterations )
{
this->m_HasMaximumNumberOfIterations = false;
this->Modified();
}
}
/** Set termination threshold based on confusion matrix parameter updates.
*/
void SetTerminationUpdateThreshold( const TWeights thresh )
{
this->m_TerminationUpdateThreshold = thresh;
this->Modified();
}
/** Set label value for undecided pixels.
*/
void SetLabelForUndecidedPixels( const OutputPixelType l )
{
this->m_LabelForUndecidedPixels = l;
this->m_HasLabelForUndecidedPixels = true;
this->Modified();
}
/** Get label value used for undecided pixels.
* After updating the filter, this function returns the actual label value
* used for undecided pixels in the current output. Note that this value
* is overwritten when SetLabelForUndecidedPixels is called and the new
* value only becomes effective upon the next filter update.
*/
OutputPixelType GetLabelForUndecidedPixels() const
{
return this->m_LabelForUndecidedPixels;
}
/** Unset label value for undecided pixels and turn on automatic selection.
*/
void UnsetLabelForUndecidedPixels()
{
if ( this->m_HasLabelForUndecidedPixels )
{
this->m_HasLabelForUndecidedPixels = false;
this->Modified();
}
}
/** Set label value for undecided pixels.
*/
void SetPriorProbabilities( const PriorProbabilitiesType& ppa )
{
this->m_PriorProbabilities = ppa;
this->m_HasPriorProbabilities = true;
this->Modified();
}
/** Get prior class probabilities.
* After updating the filter, this function returns the actual prior class
* probabilities. If these were not previously set by a call to
* SetPriorProbabilities, then they are estimated from the input
* segmentations and the result is available through this function.
*/
PriorProbabilitiesType GetPriorProbabilities() const
{
return this->m_PriorProbabilities;
}
/** Unset prior class probabilities and turn on automatic estimation.
*/
void UnsetPriorProbabilities()
{
if ( this->m_HasPriorProbabilities )
{
this->m_HasPriorProbabilities = false;
this->Modified();
}
}
/** Get confusion matrix for the i-th input segmentation.
*/
ConfusionMatrixType GetConfusionMatrix( const unsigned int i )
{
return this->m_ConfusionMatrixArray[i];
}
protected:
MultiLabelSTAPLEImageFilter()
{
this->m_HasLabelForUndecidedPixels = false;
this->m_HasPriorProbabilities = false;
this->m_HasMaximumNumberOfIterations = false;
this->m_TerminationUpdateThreshold = 1e-5;
}
virtual ~MultiLabelSTAPLEImageFilter() {}
void GenerateData();
void PrintSelf(std::ostream&, Indent) const;
/** Determine maximum value among all input images' pixels */
typename TInputImage::PixelType ComputeMaximumInputValue();
private:
MultiLabelSTAPLEImageFilter(const Self&); //purposely not implemented
void operator=(const Self&); //purposely not implemented
InputPixelType m_TotalLabelCount;
OutputPixelType m_LabelForUndecidedPixels;
bool m_HasLabelForUndecidedPixels;
bool m_HasPriorProbabilities;
PriorProbabilitiesType m_PriorProbabilities;
void InitializePriorProbabilities();
std::vector<ConfusionMatrixType> m_ConfusionMatrixArray;
std::vector<ConfusionMatrixType> m_UpdatedConfusionMatrixArray;
void AllocateConfusionMatrixArray();
void InitializeConfusionMatrixArrayFromVoting();
bool m_HasMaximumNumberOfIterations;
unsigned int m_MaximumNumberOfIterations;
TWeights m_TerminationUpdateThreshold;
};
} // end namespace itk
#ifndef ITK_MANUAL_INSTANTIATION
#include "itkMultiLabelSTAPLEImageFilter.hxx"
#endif
#endif
| [
"ntustison@gmail.com"
] | ntustison@gmail.com |
2ca4dc8f07ee0116bdadb93fad9c6ccd6a9424e0 | d33e4a1e243432ab8e3531b6f1c63e8baf05fec0 | /embroidermodder2/undo-editor.cpp | 6bc23ab5af10356e2b08fac76656c22ccc364e66 | [
"Zlib"
] | permissive | petersonca/Embroidermodder | 78b8a9a13868b8ee9a12242252643247c8f4bc38 | 4a6468aa843f58600696e185fd38b370a99278bc | refs/heads/master | 2020-04-06T06:25:22.126467 | 2013-11-21T11:35:54 | 2013-11-21T11:35:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,475 | cpp | #include <QUndoGroup>
#include <QUndoStack>
#include <QUndoView>
#include <QKeyEvent>
#include "undo-editor.h"
#include "undo-commands.h"
UndoEditor::UndoEditor(const QString& iconDirectory, QWidget* widgetToFocus, QWidget* parent, Qt::WindowFlags flags) : QDockWidget(parent, flags)
{
iconDir = iconDirectory;
iconSize = 16;
setMinimumSize(100,100);
undoGroup = new QUndoGroup(this);
undoView = new QUndoView(undoGroup, this);
undoView->setEmptyLabel("New");
undoView->setCleanIcon(QIcon(iconDir + "/" + "new" + ".png")); //TODO: new.png for new drawings, open.png for opened drawings, save.png for saved/cleared drawings?
setWidget(undoView);
setWindowTitle(tr("History"));
setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
this->setFocusProxy(widgetToFocus);
undoView->setFocusProxy(widgetToFocus);
}
UndoEditor::~UndoEditor()
{
}
void UndoEditor::addStack(QUndoStack* stack)
{
undoGroup->addStack(stack);
}
bool UndoEditor::canUndo() const
{
return undoGroup->canUndo();
}
bool UndoEditor::canRedo() const
{
return undoGroup->canRedo();
}
QString UndoEditor::undoText() const
{
return undoGroup->undoText();
}
QString UndoEditor::redoText() const
{
return undoGroup->redoText();
}
void UndoEditor::undo()
{
undoGroup->undo();
}
void UndoEditor::redo()
{
undoGroup->redo();
}
/* kate: bom off; indent-mode cstyle; indent-width 4; replace-trailing-space-save on; */
| [
"Embroidermodder@gmail.com"
] | Embroidermodder@gmail.com |
94fb7a72fe3bd4d4d7f1646aa68590c3911c8678 | 0e1cc5feca087788a3d8dfcc00da1deff9e1ede3 | /compiler/parser/token.h | df5588eb003a61a181aa1e26a09a0960082eef4a | [
"MIT"
] | permissive | cosocaf/Pick | 9b989e558ddc7bc2b011b8f0299eb3806044eac0 | e21a3ff204e8cf60a40985ebda73d90f087205a9 | refs/heads/master | 2023-08-02T13:35:58.018478 | 2021-08-05T09:13:57 | 2021-08-05T09:13:57 | 294,849,764 | 9 | 0 | MIT | 2020-11-11T12:48:03 | 2020-09-12T01:55:57 | C++ | UTF-8 | C++ | false | false | 4,004 | h | #ifndef PICKC_PARSER_TOKEN_H_
#define PICKC_PARSER_TOKEN_H_
#include <vector>
#include <string>
#include <fstream>
#include "utils/result.h"
#include "utils/option.h"
namespace pickc::parser
{
enum struct TokenKind
{
DefKeyword, // def
MutKeyword, // mut
FnKeyword, // fn
ClassKeyword, // class
TypeKeyword, // type
ExternKeyword, // extern
ImportKeyword, // import
ReturnKeyword, // return
IfKeyword, // if
ElseKeyword, // else
WhileKeyword, // while
ForKeyword, // for
LoopKeyword, // loop
BreakKeyword, // break
ContinueKeyword, // continue
PubKeyword, // pub
PriKeyword, // pri
ConstructKeyword, // construct
DestructKeyword, // destruct
I8Keyword, // i8
I16Keyword, // i16
I32Keyword, // i32
I64Keyword, // i64
U8Keyword, // u8
U16Keyword, // u16
U32Keyword, // u32
U64Keyword, // u64
F32Keyword, // f32
F64Keyword, // f64
VoidKeyword, // void
BoolKeyword, // bool
CharKeyword, // char
PtrKeyword, // ptr
LParen, // (
RParen, // )
LBrace, // {
RBrase, // }
LBracket, // [
RBracket, // ]
Semicolon, // ;
Plus, // +
Minus, // -
Asterisk, // *
Slash, // /
Percent, // %
Inc, // ++
Dec, // --
BitAnd, // &
BitOr, // |
BitXor, // ^
BitNot, // ~
LShift, // <<
RShift, // >>
Asign, // =
AddAsign, // +=
SubAsign, // -=
MulAsign, // *=
DivAsign, // /=
ModAsign, // %=
BitAndAsign, // &=
BitOrAsign, // |=
BitXorAsign, // ^=
LShiftAsign, // <<=
RShiftAsign, // >>=
LogicalAnd, // &&
LogicalOr, // ||
LogicalNot, // !
Equal, // ==
NotEqual, // !=
LessThan, // <
LessEqual, // <=
GreaterThan, // >
GreaterEqual, // >=
Dot, // .
Range, // ..
Colon, // :
Scope, // ::
Comma, // ,
Copy, // @
LineComment, // //
Integer, // [0-9]+
I8, // [0-9]+i8
I16, // [0-9]+i16
I32, // [0-9]+i32
I64, // [0-9]+i64
U8, // [0-9]+u8
U16, // [0-9]+u16
U32, // [0-9]+u32
U64, // [0-9]+u64
Float, // [0-9].[0-9]
F32, // [0-9].[0-9]+f32
F64, // [0-9].[0-9]+f64
Bool, // true|false
Null, // null
Char, // 'x'
String, // "xxx"
This, // this
Identify, // xxx
};
struct Token
{
TokenKind kind;
std::string value;
size_t line;
size_t letter;
Token(TokenKind kind, const std::string& value, size_t line, size_t letter);
Token(const Token& token);
Token(Token&& token);
Token& operator=(const Token& token);
Token& operator=(Token&& token);
};
struct TokenSequence
{
std::string file;
std::vector<std::string> rawFileData;
std::vector<Token> tokens;
std::string toOutputString(size_t line) const;
};
class Tokenizer
{
TokenSequence sequence;
std::vector<std::string> errors;
std::ifstream stream;
bool done;
Result<Option<Token>, std::string> findToken(std::string& str, size_t& line, size_t& letter);
public:
Tokenizer(const std::string& path);
Result<TokenSequence, std::vector<std::string>> tokenize();
};
}
#endif // PICKC_PARSER_TOKEN_H_ | [
"cosocaf@gmail.com"
] | cosocaf@gmail.com |
75a6e06decdcfb8fc27f73310976d2a4dbcb919e | 5ebd5cee801215bc3302fca26dbe534e6992c086 | /blaze/util/constraints/SameType.h | 95dc8d335b61b8d77c6ebd3ca82ae076187cd512 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | mhochsteger/blaze | c66d8cf179deeab4f5bd692001cc917fe23e1811 | fd397e60717c4870d942055496d5b484beac9f1a | refs/heads/master | 2020-09-17T01:56:48.483627 | 2019-11-20T05:40:29 | 2019-11-20T05:41:35 | 223,951,030 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,995 | h | //=================================================================================================
/*!
// \file blaze/util/constraints/SameType.h
// \brief Data type constraint
//
// Copyright (C) 2012-2019 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
#ifndef _BLAZE_UTIL_CONSTRAINTS_SAMETYPE_H_
#define _BLAZE_UTIL_CONSTRAINTS_SAMETYPE_H_
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <blaze/util/typetraits/IsSame.h>
namespace blaze {
//=================================================================================================
//
// MUST_BE_SAME_TYPE CONSTRAINT
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Data type constraint.
// \ingroup constraints
//
// In case the two types \a A and \a B are not the same (ignoring all cv-qualifiers of both data
// types), a compilation error is created. The following example illustrates the behavior of this
// constraint:
\code
BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( double, double ); // No compilation error
BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( double, const double ); // No compilation error (only cv-qualifiers differ)
BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE( double, float ); // Compilation error, different data types!
\endcode
// In case the cv-qualifiers should not be ignored (e.g. 'double' and 'const double' should be
// considered to be unequal), use the blaze::BLAZE_CONSTRAINT_MUST_BE_STRICTLY_SAME_TYPE constraint.
*/
#define BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE(A,B) \
static_assert( ::blaze::IsSame_v<A,B>, "Non-matching types detected" )
//*************************************************************************************************
//=================================================================================================
//
// MUST_NOT_BE_SAME_TYPE CONSTRAINT
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Data type constraint.
// \ingroup constraints
//
// In case the two types \a A and \a B are the same (ignoring all cv-qualifiers of both data
// types), a compilation error is created. The following example illustrates the behavior of
// this constraint:
\code
BLAZE_CONSTRAINT_MUST_NOT_BE_SAME_TYPE( double, float ); // No compilation error, different data types
BLAZE_CONSTRAINT_MUST_NOT_BE_SAME_TYPE( double, const double ); // Compilation error (only cv-qualifiers differ)
BLAZE_CONSTRAINT_MUST_NOT_BE_SAME_TYPE( double, double ); // Compilation error, same data type!
\endcode
// In case the cv-qualifiers should not be ignored (e.g. 'double' and 'const double' should
// be considered to be unequal), use the blaze::BLAZE_CONSTRAINT_MUST_NOT_BE_STRICTLY_SAME_TYPE
// constraint.
*/
#define BLAZE_CONSTRAINT_MUST_NOT_BE_SAME_TYPE(A,B) \
static_assert( !::blaze::IsSame_v<A,B>, "Matching types detected" )
//*************************************************************************************************
//=================================================================================================
//
// MUST_BE_STRICTLY_SAME_TYPE CONSTRAINT
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Data type constraint.
// \ingroup constraints
//
// In case the two types \a A and \a B are not the same, a compilation error is created. Note
// that this constraint even considers two types as unequal if the cv-qualifiers differ, e.g.
\code
BLAZE_CONSTRAINT_MUST_BE_STRICTLY_SAME_TYPE( double, double ); // No compilation error
BLAZE_CONSTRAINT_MUST_BE_STRICTLY_SAME_TYPE( double, const double ); // Compilation error, different cv-qualifiers!
BLAZE_CONSTRAINT_MUST_BE_STRICTLY_SAME_TYPE( double, float ); // Compilation error, different data types!
\endcode
// In case the cv-qualifiers should be ignored (e.g. 'double' and 'const double' should be
// considered to be equal), use the blaze::BLAZE_CONSTRAINT_MUST_BE_SAME_TYPE constraint.
*/
#define BLAZE_CONSTRAINT_MUST_BE_STRICTLY_SAME_TYPE(A,B) \
static_assert( ::blaze::IsStrictlySame_v<A,B>, "Non-matching types detected" )
//*************************************************************************************************
//=================================================================================================
//
// MUST_NOT_BE_STRICTLY_SAME_TYPE CONSTRAINT
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Data type constraint.
// \ingroup constraints
//
// In case the two types \a A and \a B are the same, a compilation error is created. Note that
// this constraint even considers two types as unequal if the cv-qualifiers differ, e.g.
\code
BLAZE_CONSTRAINT_MUST_NOT_BE_STRICTLY_SAME_TYPE( double, float ); // No compilation error, different data types
BLAZE_CONSTRAINT_MUST_NOT_BE_STRICTLY_SAME_TYPE( double, const double ); // No compilation error, different cv-qualifiers!
BLAZE_CONSTRAINT_MUST_NOT_BE_STRICTLY_SAME_TYPE( double, double ); // Compilation error, same data type!
\endcode
// In case the cv-qualifiers should be ignored (e.g. 'double' and 'const double' should be
// considered to be equal), use the blaze::BLAZE_CONSTRAINT_MUST_NOT_BE_SAME_TYPE constraint.
*/
#define BLAZE_CONSTRAINT_MUST_NOT_BE_STRICTLY_SAME_TYPE(A,B) \
static_assert( !::blaze::IsStrictlySame_v<A,B>, "Matching types detected" )
//*************************************************************************************************
} // namespace blaze
#endif
| [
"klaus.iglberger@gmail.com"
] | klaus.iglberger@gmail.com |
f4be898949f951a6af2283425b147ea8e7be3452 | 1889fd0dbae7969d67e98288c61be34902586555 | /appsrc/FinderUI.h | 3444acd39ede601414d88649724d353e3bd8ca0f | [] | no_license | Gabriele91/Merging-Meshs | 6b98689720c1926f838e2674f9afe0a434fca6a4 | ca84b3ebf3fb4d7bf3eb8c70b35edf918fe96513 | refs/heads/master | 2016-09-01T22:06:11.315691 | 2014-09-23T17:16:04 | 2014-09-23T17:16:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,929 | h | //
// FinderUI.h
// Merging Meshs
//
// Created by Gabriele Di Bari on 18/09/14.
// Copyright (c) 2014 Gabriele Di Bari. All rights reserved.
//
#ifndef FINDERUI_H
#define FINDERUI_H
#include <Config.h>
#include <Application.h>
#include <Utility.h>
#include "gui.h"
namespace Easy3D
{
class FinderOpenOff
{
public:
//public atributes
bool visible{false};
//contructor
FinderOpenOff(const String& name);
//draw
void draw();
void setName(const String& argname);
void setCallBackLoad(DFUNCTION<void (const String& path)> fun);
private:
String name;
String windowName;
String windowChildName;
Utility::Path currentPath;
int citem{ 0 };
//temps
std::vector<String> subDirs;
struct FileInfo{String path; String file;};
std::vector<FileInfo> offsFiles;
String superPathsList;
//cb load
DFUNCTION<void (const String& path)> cbLoad{ nullptr };
void listDirs(std::vector<String>& dirs);
String getPathFromListPaths();
void buildPathsList();
void buildDirsList();
};
class FinderSaveOff
{
public:
//public atributes
bool visible{false};
//contructor
FinderSaveOff(const String& name);
//draw
void draw();
void setName(const String& argname);
void setCallBackSave(DFUNCTION<void (const String& path)> fun);
private:
char text[255];
String name;
String windowName;
String windowChildName;
Utility::Path currentPath;
int citem{ 0 };
//temps
std::vector<String> subDirs;
struct FileInfo{String path; String file;};
std::vector<FileInfo> offsFiles;
String superPathsList;
//cb load
DFUNCTION<void (const String& path)> cbSave{ nullptr };
void listDirs(std::vector<String>& dirs);
String getPathFromListPaths();
void buildPathsList();
void buildDirsList();
};
};
#endif
| [
"dbgabri@gmail.com"
] | dbgabri@gmail.com |
55232ab7e20c47f214c053f7b7ea8bf21f7d0fd6 | aaafa161d2f507249dfb984a1d322f803c927177 | /src/processor/chains.h | 07d5cf95cd9280ece607a565b38b94f7338330b4 | [
"MIT"
] | permissive | shramov/tll | 4daf76af334c877b99a3f964a66536a1072aa3e7 | 72338ff3dcc351666ed86a814ebf093491820dc1 | refs/heads/master | 2023-08-17T13:06:39.833241 | 2023-08-16T08:12:10 | 2023-08-17T06:40:47 | 204,337,361 | 7 | 2 | MIT | 2021-11-04T19:54:37 | 2019-08-25T18:59:54 | C++ | UTF-8 | C++ | false | false | 1,113 | h | /*
* Copyright (c)2020-2021 Pavel Shramov <shramov@mexmat.net>
*
* tll is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See LICENSE for details.
*/
#ifndef _PROCESSOR_CHAINS_H
#define _PROCESSOR_CHAINS_H
#include <set>
#include "tll/channel/prefix.h"
namespace tll::processor::_ {
class Chains : public tll::channel::Prefix<Chains>
{
public:
static constexpr std::string_view channel_protocol() { return "ppp-chains+"; }
struct Object
{
std::string name;
tll::Config config;
std::set<std::string> depends;
};
struct Level
{
std::string name;
std::set<std::string> join;
std::set<std::string> spawn;
std::map<std::string, Object> objects;
};
struct Chain
{
std::string name;
std::list<Level> levels;
std::optional<std::string> spawned;
};
int _init(const tll::Channel::Url &, tll::Channel *);
template <typename Log>
std::optional<Level> parse_level(Log &, tll::Config &cfg);
std::optional<Chain> parse_chain(std::string_view name, tll::Config &cfg);
};
} // namespace tll::processor::_
#endif//_PROCESSOR_CHAINS_H
| [
"psha@nguni.psha.org.ru"
] | psha@nguni.psha.org.ru |
de3319366ca9a5c0202f453b29bdb7647faa2158 | 7eb0edf56c64386b3bd3b6b083865301cb58e47e | /src/backend/cpu/kernel/convolve.hpp | 79d684dd6423f1c49606f394f59b8bac2044d883 | [
"MIT",
"BSD-3-Clause",
"Zlib",
"BSL-1.0",
"Apache-2.0"
] | permissive | mchandra/arrayfire | bebb4bfb453ca9f9b276dd4d688dc8f0fe2e044e | 2ecff9818f23c2b0fd35ab992d4e00f17fa039b9 | refs/heads/devel | 2021-01-15T15:53:00.157270 | 2016-03-17T20:42:43 | 2016-03-17T20:42:43 | 43,915,613 | 1 | 0 | null | 2015-10-08T20:51:12 | 2015-10-08T20:51:11 | null | UTF-8 | C++ | false | false | 10,120 | hpp | /*******************************************************
* Copyright (c) 2015, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#pragma once
#include <af/defines.h>
#include <Array.hpp>
namespace cpu
{
namespace kernel
{
template<typename InT, typename AccT, bool Expand>
void one2one_1d(InT *optr, InT const * const iptr, AccT const * const fptr, af::dim4 const & oDims,
af::dim4 const & sDims, af::dim4 const & fDims, af::dim4 const & sStrides)
{
dim_t start = (Expand ? 0 : fDims[0]/2);
dim_t end = (Expand ? oDims[0] : start + sDims[0]);
for(dim_t i=start; i<end; ++i) {
AccT accum = 0.0;
for(dim_t f=0; f<fDims[0]; ++f) {
dim_t iIdx = i-f;
InT s_val = ((iIdx>=0 &&iIdx<sDims[0])? iptr[iIdx*sStrides[0]] : InT(0));
accum += AccT(s_val * fptr[f]);
}
optr[i-start] = InT(accum);
}
}
template<typename InT, typename AccT, bool Expand>
void one2one_2d(InT *optr, InT const * const iptr, AccT const * const fptr, af::dim4 const & oDims,
af::dim4 const & sDims, af::dim4 const & fDims, af::dim4 const & oStrides,
af::dim4 const & sStrides, af::dim4 const & fStrides)
{
dim_t jStart = (Expand ? 0 : fDims[1]/2);
dim_t jEnd = (Expand ? oDims[1] : jStart + sDims[1]);
dim_t iStart = (Expand ? 0 : fDims[0]/2);
dim_t iEnd = (Expand ? oDims[0] : iStart + sDims[0]);
for(dim_t j=jStart; j<jEnd; ++j) {
dim_t joff = (j-jStart)*oStrides[1];
for(dim_t i=iStart; i<iEnd; ++i) {
AccT accum = AccT(0);
for(dim_t wj=0; wj<fDims[1]; ++wj) {
dim_t jIdx = j-wj;
dim_t w_joff = wj*fStrides[1];
dim_t s_joff = jIdx * sStrides[1];
bool isJValid = (jIdx>=0 && jIdx<sDims[1]);
for(dim_t wi=0; wi<fDims[0]; ++wi) {
dim_t iIdx = i-wi;
InT s_val = InT(0);
if ( isJValid && (iIdx>=0 && iIdx<sDims[0])) {
s_val = iptr[s_joff+iIdx*sStrides[0]];
}
accum += AccT(s_val * fptr[w_joff+wi*fStrides[0]]);
}
}
optr[joff+i-iStart] = InT(accum);
}
}
}
template<typename InT, typename AccT, bool Expand>
void one2one_3d(InT *optr, InT const * const iptr, AccT const * const fptr, af::dim4 const & oDims,
af::dim4 const & sDims, af::dim4 const & fDims, af::dim4 const & oStrides,
af::dim4 const & sStrides, af::dim4 const & fStrides)
{
dim_t kStart = (Expand ? 0 : fDims[2]/2);
dim_t kEnd = (Expand ? oDims[2] : kStart + sDims[2]);
dim_t jStart = (Expand ? 0 : fDims[1]/2);
dim_t jEnd = (Expand ? oDims[1] : jStart + sDims[1]);
dim_t iStart = (Expand ? 0 : fDims[0]/2);
dim_t iEnd = (Expand ? oDims[0] : iStart + sDims[0]);
for(dim_t k=kStart; k<kEnd; ++k) {
dim_t koff = (k-kStart)*oStrides[2];
for(dim_t j=jStart; j<jEnd; ++j) {
dim_t joff = (j-jStart)*oStrides[1];
for(dim_t i=iStart; i<iEnd; ++i) {
AccT accum = AccT(0);
for(dim_t wk=0; wk<fDims[2]; ++wk) {
dim_t kIdx = k-wk;
dim_t w_koff = wk*fStrides[2];
dim_t s_koff = kIdx * sStrides[2];
bool isKValid = (kIdx>=0 && kIdx<sDims[2]);
for(dim_t wj=0; wj<fDims[1]; ++wj) {
dim_t jIdx = j-wj;
dim_t w_joff = wj*fStrides[1];
dim_t s_joff = jIdx * sStrides[1];
bool isJValid = (jIdx>=0 && jIdx<sDims[1]);
for(dim_t wi=0; wi<fDims[0]; ++wi) {
dim_t iIdx = i-wi;
InT s_val = InT(0);
if ( isKValid && isJValid && (iIdx>=0 && iIdx<sDims[0])) {
s_val = iptr[s_koff+s_joff+iIdx*sStrides[0]];
}
accum += AccT(s_val * fptr[w_koff+w_joff+wi*fStrides[0]]);
}
}
}
optr[koff+joff+i-iStart] = InT(accum);
} //i loop ends here
} // j loop ends here
} // k loop ends here
}
template<typename InT, typename AccT, dim_t baseDim, bool Expand>
void convolve_nd(Array<InT> out, Array<InT> const signal, Array<AccT> const filter, ConvolveBatchKind kind)
{
InT * optr = out.get();
InT const * const iptr = signal.get();
AccT const * const fptr = filter.get();
af::dim4 const oDims = out.dims();
af::dim4 const sDims = signal.dims();
af::dim4 const fDims = filter.dims();
af::dim4 const oStrides = out.strides();
af::dim4 const sStrides = signal.strides();
af::dim4 const fStrides = filter.strides();
dim_t out_step[4] = {0, 0, 0, 0}; /* first value is never used, and declared for code simplicity */
dim_t in_step[4] = {0, 0, 0, 0}; /* first value is never used, and declared for code simplicity */
dim_t filt_step[4] = {0, 0, 0, 0}; /* first value is never used, and declared for code simplicity */
dim_t batch[4] = {0, 1, 1, 1}; /* first value is never used, and declared for code simplicity */
for (dim_t i=1; i<4; ++i) {
switch(kind) {
case CONVOLVE_BATCH_SIGNAL:
out_step[i] = oStrides[i];
in_step[i] = sStrides[i];
if (i>=baseDim) batch[i] = sDims[i];
break;
case CONVOLVE_BATCH_SAME:
out_step[i] = oStrides[i];
in_step[i] = sStrides[i];
filt_step[i] = fStrides[i];
if (i>=baseDim) batch[i] = sDims[i];
break;
case CONVOLVE_BATCH_KERNEL:
out_step[i] = oStrides[i];
filt_step[i] = fStrides[i];
if (i>=baseDim) batch[i] = fDims[i];
break;
default:
break;
}
}
for (dim_t b3=0; b3<batch[3]; ++b3) {
for (dim_t b2=0; b2<batch[2]; ++b2) {
for (dim_t b1=0; b1<batch[1]; ++b1) {
InT * out = optr + b1 * out_step[1] + b2 * out_step[2] + b3 * out_step[3];
InT const *in = iptr + b1 * in_step[1] + b2 * in_step[2] + b3 * in_step[3];
AccT const *filt = fptr + b1 *filt_step[1] + b2 *filt_step[2] + b3 *filt_step[3];
switch(baseDim) {
case 1: one2one_1d<InT, AccT, Expand>(out, in, filt, oDims, sDims, fDims, sStrides); break;
case 2: one2one_2d<InT, AccT, Expand>(out, in, filt, oDims, sDims, fDims, oStrides, sStrides, fStrides); break;
case 3: one2one_3d<InT, AccT, Expand>(out, in, filt, oDims, sDims, fDims, oStrides, sStrides, fStrides); break;
}
}
}
}
}
template<typename InT, typename AccT, dim_t conv_dim, bool Expand>
void convolve2_separable(InT *optr, InT const * const iptr, AccT const * const fptr,
af::dim4 const & oDims, af::dim4 const & sDims, af::dim4 const & orgDims, dim_t fDim,
af::dim4 const & oStrides, af::dim4 const & sStrides, dim_t fStride)
{
for(dim_t j=0; j<oDims[1]; ++j) {
dim_t jOff = j*oStrides[1];
dim_t cj = j + (conv_dim==1)*(Expand ? 0: fDim>>1);
for(dim_t i=0; i<oDims[0]; ++i) {
dim_t iOff = i*oStrides[0];
dim_t ci = i + (conv_dim==0)*(Expand ? 0 : fDim>>1);
AccT accum = scalar<AccT>(0);
for(dim_t f=0; f<fDim; ++f) {
InT f_val = fptr[f];
InT s_val;
if (conv_dim==0) {
dim_t offi = ci - f;
bool isCIValid = offi>=0 && offi<sDims[0];
bool isCJValid = cj>=0 && cj<sDims[1];
s_val = (isCJValid && isCIValid ? iptr[cj*sDims[0]+offi] : scalar<InT>(0));
} else {
dim_t offj = cj - f;
bool isCIValid = ci>=0 && ci<sDims[0];
bool isCJValid = offj>=0 && offj<sDims[1];
s_val = (isCJValid && isCIValid ? iptr[offj*sDims[0]+ci] : scalar<InT>(0));
}
accum += AccT(s_val * f_val);
}
optr[iOff+jOff] = InT(accum);
}
}
}
template<typename InT, typename AccT, bool Expand>
void convolve2(Array<InT> out, Array<InT> const signal,
Array<AccT> const c_filter, Array<AccT> const r_filter,
af::dim4 const tDims)
{
Array<InT> temp = createEmptyArray<InT>(tDims);
dim_t cflen = (dim_t)c_filter.elements();
dim_t rflen = (dim_t)r_filter.elements();
auto oDims = out.dims();
auto sDims = signal.dims();
auto oStrides = out.strides();
auto sStrides = signal.strides();
auto tStrides = temp.strides();
for (dim_t b3=0; b3<oDims[3]; ++b3) {
dim_t i_b3Off = b3*sStrides[3];
dim_t t_b3Off = b3*tStrides[3];
dim_t o_b3Off = b3*oStrides[3];
for (dim_t b2=0; b2<oDims[2]; ++b2) {
InT const * const iptr = signal.get()+ b2*sStrides[2] + i_b3Off;
InT *tptr = temp.get() + b2*tStrides[2] + t_b3Off;
InT *optr = out.get() + b2*oStrides[2] + o_b3Off;
convolve2_separable<InT, AccT, 0, Expand>(tptr, iptr, c_filter.get(),
tDims, sDims, sDims, cflen,
tStrides, sStrides, c_filter.strides()[0]);
convolve2_separable<InT, AccT, 1, Expand>(optr, tptr, r_filter.get(),
oDims, tDims, sDims, rflen,
oStrides, tStrides, r_filter.strides()[0]);
}
}
}
}
}
| [
"pradeep@arrayfire.com"
] | pradeep@arrayfire.com |
500423d537769c569b96fa5adbffddd74641c102 | 62234928086510d6e7ac4fa317a4cf75898915f0 | /client/include/cryptopp/speck-simd.cpp | 58d680dd11c6adf81855558e91efc37983a4eaff | [
"BSL-1.0",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | zbl2018/RobotServer | 22699474d33b3c6586627aae320c61991645be6e | b8a1482e55dbc270a7b3c1a282a009822ed805d3 | refs/heads/master | 2020-03-11T18:10:22.528946 | 2018-07-13T07:24:41 | 2018-07-13T07:24:41 | 130,169,554 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 35,860 | cpp | // speck-simd.cpp - written and placed in the public domain by Jeffrey Walton
//
// This source file uses intrinsics and built-ins to gain access to
// SSSE3, ARM NEON and ARMv8a, and Power7 Altivec instructions. A separate
// source file is needed because additional CXXFLAGS are required to enable
// the appropriate instructions sets in some build configurations.
#include "pch.h"
#include "config.h"
#include "speck.h"
#include "misc.h"
#include "adv-simd.h"
// Uncomment for benchmarking C++ against SSE or NEON.
// Do so in both speck.cpp and speck-simd.cpp.
// #undef CRYPTOPP_SSSE3_AVAILABLE
// #undef CRYPTOPP_SSE41_AVAILABLE
// #undef CRYPTOPP_ARM_NEON_AVAILABLE
#if (CRYPTOPP_SSSE3_AVAILABLE)
# include <pmmintrin.h>
# include <tmmintrin.h>
#endif
#if (CRYPTOPP_SSE41_AVAILABLE)
# include <smmintrin.h>
#endif
#if defined(__AVX512F__) && defined(__AVX512VL__)
# define CRYPTOPP_AVX512_ROTATE 1
# include <immintrin.h>
#endif
#if (CRYPTOPP_ARM_NEON_AVAILABLE)
# include <arm_neon.h>
#endif
// Can't use CRYPTOPP_ARM_XXX_AVAILABLE because too many
// compilers don't follow ACLE conventions for the include.
#if defined(CRYPTOPP_ARM_ACLE_AVAILABLE)
# include <stdint.h>
# include <arm_acle.h>
#endif
// https://www.spinics.net/lists/gcchelp/msg47735.html and
// https://www.spinics.net/lists/gcchelp/msg47749.html
#if (CRYPTOPP_GCC_VERSION >= 40900)
# define GCC_NO_UBSAN __attribute__ ((no_sanitize_undefined))
#else
# define GCC_NO_UBSAN
#endif
ANONYMOUS_NAMESPACE_BEGIN
using CryptoPP::byte;
using CryptoPP::word32;
using CryptoPP::word64;
// *************************** ARM NEON ************************** //
#if defined(CRYPTOPP_ARM_NEON_AVAILABLE)
template <class T>
inline T UnpackHigh32(const T& a, const T& b)
{
const uint32x2_t x(vget_high_u32((uint32x4_t)a));
const uint32x2_t y(vget_high_u32((uint32x4_t)b));
const uint32x2x2_t r = vzip_u32(x, y);
return (T)vcombine_u32(r.val[0], r.val[1]);
}
template <class T>
inline T UnpackLow32(const T& a, const T& b)
{
const uint32x2_t x(vget_low_u32((uint32x4_t)a));
const uint32x2_t y(vget_low_u32((uint32x4_t)b));
const uint32x2x2_t r = vzip_u32(x, y);
return (T)vcombine_u32(r.val[0], r.val[1]);
}
template <unsigned int R>
inline uint32x4_t RotateLeft32(const uint32x4_t& val)
{
const uint32x4_t a(vshlq_n_u32(val, R));
const uint32x4_t b(vshrq_n_u32(val, 32 - R));
return vorrq_u32(a, b);
}
template <unsigned int R>
inline uint32x4_t RotateRight32(const uint32x4_t& val)
{
const uint32x4_t a(vshlq_n_u32(val, 32 - R));
const uint32x4_t b(vshrq_n_u32(val, R));
return vorrq_u32(a, b);
}
#if defined(__aarch32__) || defined(__aarch64__)
// Faster than two Shifts and an Or. Thanks to Louis Wingers and Bryan Weeks.
template <>
inline uint32x4_t RotateLeft32<8>(const uint32x4_t& val)
{
#if defined(CRYPTOPP_BIG_ENDIAN)
const uint8_t maskb[16] = { 14,13,12,15, 10,9,8,11, 6,5,4,7, 2,1,0,3 };
const uint8x16_t mask = vld1q_u8(maskb);
#else
const uint8_t maskb[16] = { 3,0,1,2, 7,4,5,6, 11,8,9,10, 15,12,13,14 };
const uint8x16_t mask = vld1q_u8(maskb);
#endif
return vreinterpretq_u32_u8(
vqtbl1q_u8(vreinterpretq_u8_u32(val), mask));
}
// Faster than two Shifts and an Or. Thanks to Louis Wingers and Bryan Weeks.
template <>
inline uint32x4_t RotateRight32<8>(const uint32x4_t& val)
{
#if defined(CRYPTOPP_BIG_ENDIAN)
const uint8_t maskb[16] = { 12,15,14,13, 8,11,10,9, 4,7,6,5, 0,3,2,1 };
const uint8x16_t mask = vld1q_u8(maskb);
#else
const uint8_t maskb[16] = { 1,2,3,0, 5,6,7,4, 9,10,11,8, 13,14,15,12 };
const uint8x16_t mask = vld1q_u8(maskb);
#endif
return vreinterpretq_u32_u8(
vqtbl1q_u8(vreinterpretq_u8_u32(val), mask));
}
#endif // Aarch32 or Aarch64
inline void SPECK64_Enc_Block(uint32x4_t &block0, uint32x4_t &block1,
const word32 *subkeys, unsigned int rounds)
{
// Rearrange the data for vectorization. The incoming data was read into
// a little-endian word array. Depending on the number of blocks it needs to
// be permuted to the following.
// [A1 A2 A3 A4][B1 B2 B3 B4] ... => [A1 A3 B1 B3][A2 A4 B2 B4] ...
uint32x4_t x1 = vuzpq_u32(block0, block1).val[1];
uint32x4_t y1 = vuzpq_u32(block0, block1).val[0];
for (int i=0; i < static_cast<int>(rounds); ++i)
{
const uint32x4_t rk = vdupq_n_u32(subkeys[i]);
x1 = RotateRight32<8>(x1);
x1 = vaddq_u32(x1, y1);
x1 = veorq_u32(x1, rk);
y1 = RotateLeft32<3>(y1);
y1 = veorq_u32(y1, x1);
}
// [A1 A3 B1 B3][A2 A4 B2 B4] => [A1 A2 A3 A4][B1 B2 B3 B4]
block0 = UnpackLow32(y1, x1);
block1 = UnpackHigh32(y1, x1);
}
inline void SPECK64_Dec_Block(uint32x4_t &block0, uint32x4_t &block1,
const word32 *subkeys, unsigned int rounds)
{
// Rearrange the data for vectorization. The incoming data was read into
// a little-endian word array. Depending on the number of blocks it needs to
// be permuted to the following.
// [A1 A2 A3 A4][B1 B2 B3 B4] ... => [A1 A3 B1 B3][A2 A4 B2 B4] ...
uint32x4_t x1 = vuzpq_u32(block0, block1).val[1];
uint32x4_t y1 = vuzpq_u32(block0, block1).val[0];
for (int i = static_cast<int>(rounds-1); i >= 0; --i)
{
const uint32x4_t rk = vdupq_n_u32(subkeys[i]);
y1 = veorq_u32(y1, x1);
y1 = RotateRight32<3>(y1);
x1 = veorq_u32(x1, rk);
x1 = vsubq_u32(x1, y1);
x1 = RotateLeft32<8>(x1);
}
// [A1 A3 B1 B3][A2 A4 B2 B4] => [A1 A2 A3 A4][B1 B2 B3 B4]
block0 = UnpackLow32(y1, x1);
block1 = UnpackHigh32(y1, x1);
}
inline void SPECK64_Enc_6_Blocks(uint32x4_t &block0, uint32x4_t &block1,
uint32x4_t &block2, uint32x4_t &block3, uint32x4_t &block4, uint32x4_t &block5,
const word32 *subkeys, unsigned int rounds)
{
// Rearrange the data for vectorization. The incoming data was read into
// a little-endian word array. Depending on the number of blocks it needs to
// be permuted to the following. If only a single block is available then
// a Zero block is provided to promote vectorizations.
// [A1 A2 A3 A4][B1 B2 B3 B4] ... => [A1 A3 B1 B3][A2 A4 B2 B4] ...
uint32x4_t x1 = vuzpq_u32(block0, block1).val[1];
uint32x4_t y1 = vuzpq_u32(block0, block1).val[0];
uint32x4_t x2 = vuzpq_u32(block2, block3).val[1];
uint32x4_t y2 = vuzpq_u32(block2, block3).val[0];
uint32x4_t x3 = vuzpq_u32(block4, block5).val[1];
uint32x4_t y3 = vuzpq_u32(block4, block5).val[0];
for (int i=0; i < static_cast<int>(rounds); ++i)
{
const uint32x4_t rk = vdupq_n_u32(subkeys[i]);
x1 = RotateRight32<8>(x1);
x2 = RotateRight32<8>(x2);
x3 = RotateRight32<8>(x3);
x1 = vaddq_u32(x1, y1);
x2 = vaddq_u32(x2, y2);
x3 = vaddq_u32(x3, y3);
x1 = veorq_u32(x1, rk);
x2 = veorq_u32(x2, rk);
x3 = veorq_u32(x3, rk);
y1 = RotateLeft32<3>(y1);
y2 = RotateLeft32<3>(y2);
y3 = RotateLeft32<3>(y3);
y1 = veorq_u32(y1, x1);
y2 = veorq_u32(y2, x2);
y3 = veorq_u32(y3, x3);
}
// [A1 A3 B1 B3][A2 A4 B2 B4] => [A1 A2 A3 A4][B1 B2 B3 B4]
block0 = UnpackLow32(y1, x1);
block1 = UnpackHigh32(y1, x1);
block2 = UnpackLow32(y2, x2);
block3 = UnpackHigh32(y2, x2);
block4 = UnpackLow32(y3, x3);
block5 = UnpackHigh32(y3, x3);
}
inline void SPECK64_Dec_6_Blocks(uint32x4_t &block0, uint32x4_t &block1,
uint32x4_t &block2, uint32x4_t &block3, uint32x4_t &block4, uint32x4_t &block5,
const word32 *subkeys, unsigned int rounds)
{
// Rearrange the data for vectorization. The incoming data was read into
// a little-endian word array. Depending on the number of blocks it needs to
// be permuted to the following. If only a single block is available then
// a Zero block is provided to promote vectorizations.
// [A1 A2 A3 A4][B1 B2 B3 B4] ... => [A1 A3 B1 B3][A2 A4 B2 B4] ...
uint32x4_t x1 = vuzpq_u32(block0, block1).val[1];
uint32x4_t y1 = vuzpq_u32(block0, block1).val[0];
uint32x4_t x2 = vuzpq_u32(block2, block3).val[1];
uint32x4_t y2 = vuzpq_u32(block2, block3).val[0];
uint32x4_t x3 = vuzpq_u32(block4, block5).val[1];
uint32x4_t y3 = vuzpq_u32(block4, block5).val[0];
for (int i = static_cast<int>(rounds-1); i >= 0; --i)
{
const uint32x4_t rk = vdupq_n_u32(subkeys[i]);
y1 = veorq_u32(y1, x1);
y2 = veorq_u32(y2, x2);
y3 = veorq_u32(y3, x3);
y1 = RotateRight32<3>(y1);
y2 = RotateRight32<3>(y2);
y3 = RotateRight32<3>(y3);
x1 = veorq_u32(x1, rk);
x2 = veorq_u32(x2, rk);
x3 = veorq_u32(x3, rk);
x1 = vsubq_u32(x1, y1);
x2 = vsubq_u32(x2, y2);
x3 = vsubq_u32(x3, y3);
x1 = RotateLeft32<8>(x1);
x2 = RotateLeft32<8>(x2);
x3 = RotateLeft32<8>(x3);
}
// [A1 A3 B1 B3][A2 A4 B2 B4] => [A1 A2 A3 A4][B1 B2 B3 B4]
block0 = UnpackLow32(y1, x1);
block1 = UnpackHigh32(y1, x1);
block2 = UnpackLow32(y2, x2);
block3 = UnpackHigh32(y2, x2);
block4 = UnpackLow32(y3, x3);
block5 = UnpackHigh32(y3, x3);
}
#endif // CRYPTOPP_ARM_NEON_AVAILABLE
#if defined(CRYPTOPP_ARM_NEON_AVAILABLE)
template <class T>
inline T UnpackHigh64(const T& a, const T& b)
{
const uint64x1_t x(vget_high_u64((uint64x2_t)a));
const uint64x1_t y(vget_high_u64((uint64x2_t)b));
return (T)vcombine_u64(x, y);
}
template <class T>
inline T UnpackLow64(const T& a, const T& b)
{
const uint64x1_t x(vget_low_u64((uint64x2_t)a));
const uint64x1_t y(vget_low_u64((uint64x2_t)b));
return (T)vcombine_u64(x, y);
}
template <unsigned int R>
inline uint64x2_t RotateLeft64(const uint64x2_t& val)
{
const uint64x2_t a(vshlq_n_u64(val, R));
const uint64x2_t b(vshrq_n_u64(val, 64 - R));
return vorrq_u64(a, b);
}
template <unsigned int R>
inline uint64x2_t RotateRight64(const uint64x2_t& val)
{
const uint64x2_t a(vshlq_n_u64(val, 64 - R));
const uint64x2_t b(vshrq_n_u64(val, R));
return vorrq_u64(a, b);
}
#if defined(__aarch32__) || defined(__aarch64__)
// Faster than two Shifts and an Or. Thanks to Louis Wingers and Bryan Weeks.
template <>
inline uint64x2_t RotateLeft64<8>(const uint64x2_t& val)
{
#if defined(CRYPTOPP_BIG_ENDIAN)
const uint8_t maskb[16] = { 14,13,12,11, 10,9,8,15, 6,5,4,3, 2,1,0,7 };
const uint8x16_t mask = vld1q_u8(maskb);
#else
const uint8_t maskb[16] = { 7,0,1,2, 3,4,5,6, 15,8,9,10, 11,12,13,14 };
const uint8x16_t mask = vld1q_u8(maskb);
#endif
return vreinterpretq_u64_u8(
vqtbl1q_u8(vreinterpretq_u8_u64(val), mask));
}
// Faster than two Shifts and an Or. Thanks to Louis Wingers and Bryan Weeks.
template <>
inline uint64x2_t RotateRight64<8>(const uint64x2_t& val)
{
#if defined(CRYPTOPP_BIG_ENDIAN)
const uint8_t maskb[16] = { 8,15,14,13, 12,11,10,9, 0,7,6,5, 4,3,2,1 };
const uint8x16_t mask = vld1q_u8(maskb);
#else
const uint8_t maskb[16] = { 1,2,3,4, 5,6,7,0, 9,10,11,12, 13,14,15,8 };
const uint8x16_t mask = vld1q_u8(maskb);
#endif
return vreinterpretq_u64_u8(
vqtbl1q_u8(vreinterpretq_u8_u64(val), mask));
}
#endif
inline void SPECK128_Enc_Block(uint64x2_t &block0, uint64x2_t &block1,
const word64 *subkeys, unsigned int rounds)
{
// Rearrange the data for vectorization. The incoming data was read into
// a little-endian word array. Depending on the number of blocks it needs to
// be permuted to the following.
// [A1 A2][B1 B2] ... => [A1 B1][A2 B2] ...
uint64x2_t x1 = UnpackHigh64(block0, block1);
uint64x2_t y1 = UnpackLow64(block0, block1);
for (int i=0; i < static_cast<int>(rounds); ++i)
{
const uint64x2_t rk = vld1q_dup_u64(subkeys+i);
x1 = RotateRight64<8>(x1);
x1 = vaddq_u64(x1, y1);
x1 = veorq_u64(x1, rk);
y1 = RotateLeft64<3>(y1);
y1 = veorq_u64(y1, x1);
}
// [A1 B1][A2 B2] ... => [A1 A2][B1 B2] ...
block0 = UnpackLow64(y1, x1);
block1 = UnpackHigh64(y1, x1);
}
inline void SPECK128_Enc_6_Blocks(uint64x2_t &block0, uint64x2_t &block1,
uint64x2_t &block2, uint64x2_t &block3, uint64x2_t &block4, uint64x2_t &block5,
const word64 *subkeys, unsigned int rounds)
{
// Rearrange the data for vectorization. The incoming data was read into
// a little-endian word array. Depending on the number of blocks it needs to
// be permuted to the following.
// [A1 A2][B1 B2] ... => [A1 B1][A2 B2] ...
uint64x2_t x1 = UnpackHigh64(block0, block1);
uint64x2_t y1 = UnpackLow64(block0, block1);
uint64x2_t x2 = UnpackHigh64(block2, block3);
uint64x2_t y2 = UnpackLow64(block2, block3);
uint64x2_t x3 = UnpackHigh64(block4, block5);
uint64x2_t y3 = UnpackLow64(block4, block5);
for (int i=0; i < static_cast<int>(rounds); ++i)
{
const uint64x2_t rk = vld1q_dup_u64(subkeys+i);
x1 = RotateRight64<8>(x1);
x2 = RotateRight64<8>(x2);
x3 = RotateRight64<8>(x3);
x1 = vaddq_u64(x1, y1);
x2 = vaddq_u64(x2, y2);
x3 = vaddq_u64(x3, y3);
x1 = veorq_u64(x1, rk);
x2 = veorq_u64(x2, rk);
x3 = veorq_u64(x3, rk);
y1 = RotateLeft64<3>(y1);
y2 = RotateLeft64<3>(y2);
y3 = RotateLeft64<3>(y3);
y1 = veorq_u64(y1, x1);
y2 = veorq_u64(y2, x2);
y3 = veorq_u64(y3, x3);
}
// [A1 B1][A2 B2] ... => [A1 A2][B1 B2] ...
block0 = UnpackLow64(y1, x1);
block1 = UnpackHigh64(y1, x1);
block2 = UnpackLow64(y2, x2);
block3 = UnpackHigh64(y2, x2);
block4 = UnpackLow64(y3, x3);
block5 = UnpackHigh64(y3, x3);
}
inline void SPECK128_Dec_Block(uint64x2_t &block0, uint64x2_t &block1,
const word64 *subkeys, unsigned int rounds)
{
// Rearrange the data for vectorization. The incoming data was read into
// a little-endian word array. Depending on the number of blocks it needs to
// be permuted to the following.
// [A1 A2][B1 B2] ... => [A1 B1][A2 B2] ...
uint64x2_t x1 = UnpackHigh64(block0, block1);
uint64x2_t y1 = UnpackLow64(block0, block1);
for (int i = static_cast<int>(rounds-1); i >= 0; --i)
{
const uint64x2_t rk = vld1q_dup_u64(subkeys+i);
y1 = veorq_u64(y1, x1);
y1 = RotateRight64<3>(y1);
x1 = veorq_u64(x1, rk);
x1 = vsubq_u64(x1, y1);
x1 = RotateLeft64<8>(x1);
}
// [A1 B1][A2 B2] ... => [A1 A2][B1 B2] ...
block0 = UnpackLow64(y1, x1);
block1 = UnpackHigh64(y1, x1);
}
inline void SPECK128_Dec_6_Blocks(uint64x2_t &block0, uint64x2_t &block1,
uint64x2_t &block2, uint64x2_t &block3, uint64x2_t &block4, uint64x2_t &block5,
const word64 *subkeys, unsigned int rounds)
{
// Rearrange the data for vectorization. The incoming data was read into
// a little-endian word array. Depending on the number of blocks it needs to
// be permuted to the following.
// [A1 A2][B1 B2] ... => [A1 B1][A2 B2] ...
uint64x2_t x1 = UnpackHigh64(block0, block1);
uint64x2_t y1 = UnpackLow64(block0, block1);
uint64x2_t x2 = UnpackHigh64(block2, block3);
uint64x2_t y2 = UnpackLow64(block2, block3);
uint64x2_t x3 = UnpackHigh64(block4, block5);
uint64x2_t y3 = UnpackLow64(block4, block5);
for (int i = static_cast<int>(rounds-1); i >= 0; --i)
{
const uint64x2_t rk = vld1q_dup_u64(subkeys+i);
y1 = veorq_u64(y1, x1);
y2 = veorq_u64(y2, x2);
y3 = veorq_u64(y3, x3);
y1 = RotateRight64<3>(y1);
y2 = RotateRight64<3>(y2);
y3 = RotateRight64<3>(y3);
x1 = veorq_u64(x1, rk);
x2 = veorq_u64(x2, rk);
x3 = veorq_u64(x3, rk);
x1 = vsubq_u64(x1, y1);
x2 = vsubq_u64(x2, y2);
x3 = vsubq_u64(x3, y3);
x1 = RotateLeft64<8>(x1);
x2 = RotateLeft64<8>(x2);
x3 = RotateLeft64<8>(x3);
}
// [A1 B1][A2 B2] ... => [A1 A2][B1 B2] ...
block0 = UnpackLow64(y1, x1);
block1 = UnpackHigh64(y1, x1);
block2 = UnpackLow64(y2, x2);
block3 = UnpackHigh64(y2, x2);
block4 = UnpackLow64(y3, x3);
block5 = UnpackHigh64(y3, x3);
}
#endif // CRYPTOPP_ARM_NEON_AVAILABLE
// ***************************** IA-32 ***************************** //
#if defined(CRYPTOPP_SSSE3_AVAILABLE)
// Clang __m128i casts, http://bugs.llvm.org/show_bug.cgi?id=20670
#ifndef M128_CAST
# define M128_CAST(x) ((__m128i *)(void *)(x))
#endif
#ifndef CONST_M128_CAST
# define CONST_M128_CAST(x) ((const __m128i *)(const void *)(x))
#endif
// GCC double casts, https://www.spinics.net/lists/gcchelp/msg47735.html
#ifndef DOUBLE_CAST
# define DOUBLE_CAST(x) ((double *)(void *)(x))
#endif
#ifndef CONST_DOUBLE_CAST
# define CONST_DOUBLE_CAST(x) ((const double *)(const void *)(x))
#endif
#if defined(CRYPTOPP_AVX512_ROTATE)
template <unsigned int R>
inline __m128i RotateLeft64(const __m128i& val)
{
return _mm_rol_epi64(val, R);
}
template <unsigned int R>
inline __m128i RotateRight64(const __m128i& val)
{
return _mm_ror_epi64(val, R);
}
#else
template <unsigned int R>
inline __m128i RotateLeft64(const __m128i& val)
{
return _mm_or_si128(
_mm_slli_epi64(val, R), _mm_srli_epi64(val, 64-R));
}
template <unsigned int R>
inline __m128i RotateRight64(const __m128i& val)
{
return _mm_or_si128(
_mm_slli_epi64(val, 64-R), _mm_srli_epi64(val, R));
}
// Faster than two Shifts and an Or. Thanks to Louis Wingers and Bryan Weeks.
template <>
inline __m128i RotateLeft64<8>(const __m128i& val)
{
const __m128i mask = _mm_set_epi8(14,13,12,11, 10,9,8,15, 6,5,4,3, 2,1,0,7);
return _mm_shuffle_epi8(val, mask);
}
// Faster than two Shifts and an Or. Thanks to Louis Wingers and Bryan Weeks.
template <>
inline __m128i RotateRight64<8>(const __m128i& val)
{
const __m128i mask = _mm_set_epi8(8,15,14,13, 12,11,10,9, 0,7,6,5, 4,3,2,1);
return _mm_shuffle_epi8(val, mask);
}
#endif // CRYPTOPP_AVX512_ROTATE
inline void GCC_NO_UBSAN SPECK128_Enc_Block(__m128i &block0, __m128i &block1,
const word64 *subkeys, unsigned int rounds)
{
// Rearrange the data for vectorization. The incoming data was read into
// a little-endian word array. Depending on the number of blocks it needs to
// be permuted to the following.
// [A1 A2][B1 B2] ... => [A1 B1][A2 B2] ...
__m128i x1 = _mm_unpackhi_epi64(block0, block1);
__m128i y1 = _mm_unpacklo_epi64(block0, block1);
for (int i=0; i < static_cast<int>(rounds); ++i)
{
const __m128i rk = _mm_castpd_si128(
_mm_loaddup_pd(CONST_DOUBLE_CAST(subkeys+i)));
x1 = RotateRight64<8>(x1);
x1 = _mm_add_epi64(x1, y1);
x1 = _mm_xor_si128(x1, rk);
y1 = RotateLeft64<3>(y1);
y1 = _mm_xor_si128(y1, x1);
}
// [A1 B1][A2 B2] ... => [A1 A2][B1 B2] ...
block0 = _mm_unpacklo_epi64(y1, x1);
block1 = _mm_unpackhi_epi64(y1, x1);
}
inline void GCC_NO_UBSAN SPECK128_Enc_6_Blocks(__m128i &block0, __m128i &block1,
__m128i &block2, __m128i &block3, __m128i &block4, __m128i &block5,
const word64 *subkeys, unsigned int rounds)
{
// Rearrange the data for vectorization. The incoming data was read into
// a little-endian word array. Depending on the number of blocks it needs to
// be permuted to the following.
// [A1 A2][B1 B2] ... => [A1 B1][A2 B2] ...
__m128i x1 = _mm_unpackhi_epi64(block0, block1);
__m128i y1 = _mm_unpacklo_epi64(block0, block1);
__m128i x2 = _mm_unpackhi_epi64(block2, block3);
__m128i y2 = _mm_unpacklo_epi64(block2, block3);
__m128i x3 = _mm_unpackhi_epi64(block4, block5);
__m128i y3 = _mm_unpacklo_epi64(block4, block5);
for (int i=0; i < static_cast<int>(rounds); ++i)
{
const __m128i rk = _mm_castpd_si128(
_mm_loaddup_pd(CONST_DOUBLE_CAST(subkeys+i)));
x1 = RotateRight64<8>(x1);
x2 = RotateRight64<8>(x2);
x3 = RotateRight64<8>(x3);
x1 = _mm_add_epi64(x1, y1);
x2 = _mm_add_epi64(x2, y2);
x3 = _mm_add_epi64(x3, y3);
x1 = _mm_xor_si128(x1, rk);
x2 = _mm_xor_si128(x2, rk);
x3 = _mm_xor_si128(x3, rk);
y1 = RotateLeft64<3>(y1);
y2 = RotateLeft64<3>(y2);
y3 = RotateLeft64<3>(y3);
y1 = _mm_xor_si128(y1, x1);
y2 = _mm_xor_si128(y2, x2);
y3 = _mm_xor_si128(y3, x3);
}
// [A1 B1][A2 B2] ... => [A1 A2][B1 B2] ...
block0 = _mm_unpacklo_epi64(y1, x1);
block1 = _mm_unpackhi_epi64(y1, x1);
block2 = _mm_unpacklo_epi64(y2, x2);
block3 = _mm_unpackhi_epi64(y2, x2);
block4 = _mm_unpacklo_epi64(y3, x3);
block5 = _mm_unpackhi_epi64(y3, x3);
}
inline void GCC_NO_UBSAN SPECK128_Dec_Block(__m128i &block0, __m128i &block1,
const word64 *subkeys, unsigned int rounds)
{
// Rearrange the data for vectorization. The incoming data was read into
// a little-endian word array. Depending on the number of blocks it needs to
// be permuted to the following.
// [A1 A2][B1 B2] ... => [A1 B1][A2 B2] ...
__m128i x1 = _mm_unpackhi_epi64(block0, block1);
__m128i y1 = _mm_unpacklo_epi64(block0, block1);
for (int i = static_cast<int>(rounds-1); i >= 0; --i)
{
const __m128i rk = _mm_castpd_si128(
_mm_loaddup_pd(CONST_DOUBLE_CAST(subkeys+i)));
y1 = _mm_xor_si128(y1, x1);
y1 = RotateRight64<3>(y1);
x1 = _mm_xor_si128(x1, rk);
x1 = _mm_sub_epi64(x1, y1);
x1 = RotateLeft64<8>(x1);
}
// [A1 B1][A2 B2] ... => [A1 A2][B1 B2] ...
block0 = _mm_unpacklo_epi64(y1, x1);
block1 = _mm_unpackhi_epi64(y1, x1);
}
inline void GCC_NO_UBSAN SPECK128_Dec_6_Blocks(__m128i &block0, __m128i &block1,
__m128i &block2, __m128i &block3, __m128i &block4, __m128i &block5,
const word64 *subkeys, unsigned int rounds)
{
// Rearrange the data for vectorization. The incoming data was read into
// a little-endian word array. Depending on the number of blocks it needs to
// be permuted to the following.
// [A1 A2][B1 B2] ... => [A1 B1][A2 B2] ...
__m128i x1 = _mm_unpackhi_epi64(block0, block1);
__m128i y1 = _mm_unpacklo_epi64(block0, block1);
__m128i x2 = _mm_unpackhi_epi64(block2, block3);
__m128i y2 = _mm_unpacklo_epi64(block2, block3);
__m128i x3 = _mm_unpackhi_epi64(block4, block5);
__m128i y3 = _mm_unpacklo_epi64(block4, block5);
for (int i = static_cast<int>(rounds-1); i >= 0; --i)
{
const __m128i rk = _mm_castpd_si128(
_mm_loaddup_pd(CONST_DOUBLE_CAST(subkeys+i)));
y1 = _mm_xor_si128(y1, x1);
y2 = _mm_xor_si128(y2, x2);
y3 = _mm_xor_si128(y3, x3);
y1 = RotateRight64<3>(y1);
y2 = RotateRight64<3>(y2);
y3 = RotateRight64<3>(y3);
x1 = _mm_xor_si128(x1, rk);
x2 = _mm_xor_si128(x2, rk);
x3 = _mm_xor_si128(x3, rk);
x1 = _mm_sub_epi64(x1, y1);
x2 = _mm_sub_epi64(x2, y2);
x3 = _mm_sub_epi64(x3, y3);
x1 = RotateLeft64<8>(x1);
x2 = RotateLeft64<8>(x2);
x3 = RotateLeft64<8>(x3);
}
// [A1 B1][A2 B2] ... => [A1 A2][B1 B2] ...
block0 = _mm_unpacklo_epi64(y1, x1);
block1 = _mm_unpackhi_epi64(y1, x1);
block2 = _mm_unpacklo_epi64(y2, x2);
block3 = _mm_unpackhi_epi64(y2, x2);
block4 = _mm_unpacklo_epi64(y3, x3);
block5 = _mm_unpackhi_epi64(y3, x3);
}
#endif // CRYPTOPP_SSSE3_AVAILABLE
#if defined(CRYPTOPP_SSE41_AVAILABLE)
template <unsigned int R>
inline __m128i RotateLeft32(const __m128i& val)
{
return _mm_or_si128(
_mm_slli_epi32(val, R), _mm_srli_epi32(val, 32-R));
}
template <unsigned int R>
inline __m128i RotateRight32(const __m128i& val)
{
return _mm_or_si128(
_mm_slli_epi32(val, 32-R), _mm_srli_epi32(val, R));
}
// Faster than two Shifts and an Or. Thanks to Louis Wingers and Bryan Weeks.
template <>
inline __m128i RotateLeft32<8>(const __m128i& val)
{
const __m128i mask = _mm_set_epi8(14,13,12,15, 10,9,8,11, 6,5,4,7, 2,1,0,3);
return _mm_shuffle_epi8(val, mask);
}
// Faster than two Shifts and an Or. Thanks to Louis Wingers and Bryan Weeks.
template <>
inline __m128i RotateRight32<8>(const __m128i& val)
{
const __m128i mask = _mm_set_epi8(12,15,14,13, 8,11,10,9, 4,7,6,5, 0,3,2,1);
return _mm_shuffle_epi8(val, mask);
}
inline void GCC_NO_UBSAN SPECK64_Enc_Block(__m128i &block0, __m128i &block1,
const word32 *subkeys, unsigned int rounds)
{
// Rearrange the data for vectorization. The incoming data was read into
// a little-endian word array. Depending on the number of blocks it needs to
// be permuted to the following. Thanks to Peter Cordes for help with the
// SSE permutes below.
// [A1 A2 A3 A4][B1 B2 B3 B4] ... => [A1 A3 B1 B3][A2 A4 B2 B4] ...
const __m128 t0 = _mm_castsi128_ps(block0);
const __m128 t1 = _mm_castsi128_ps(block1);
__m128i x1 = _mm_castps_si128(_mm_shuffle_ps(t0, t1, _MM_SHUFFLE(3,1,3,1)));
__m128i y1 = _mm_castps_si128(_mm_shuffle_ps(t0, t1, _MM_SHUFFLE(2,0,2,0)));
for (int i=0; i < static_cast<int>(rounds); ++i)
{
const __m128i rk = _mm_set1_epi32(subkeys[i]);
x1 = RotateRight32<8>(x1);
x1 = _mm_add_epi32(x1, y1);
x1 = _mm_xor_si128(x1, rk);
y1 = RotateLeft32<3>(y1);
y1 = _mm_xor_si128(y1, x1);
}
// The is roughly the SSE equivalent to ARM vzp32
// [A1 A3 B1 B3][A2 A4 B2 B4] => [A1 A2 A3 A4][B1 B2 B3 B4]
block0 = _mm_unpacklo_epi32(y1, x1);
block1 = _mm_unpackhi_epi32(y1, x1);
}
inline void GCC_NO_UBSAN SPECK64_Dec_Block(__m128i &block0, __m128i &block1,
const word32 *subkeys, unsigned int rounds)
{
// Rearrange the data for vectorization. The incoming data was read into
// a little-endian word array. Depending on the number of blocks it needs to
// be permuted to the following. Thanks to Peter Cordes for help with the
// SSE permutes below.
// [A1 A2 A3 A4][B1 B2 B3 B4] ... => [A1 A3 B1 B3][A2 A4 B2 B4] ...
const __m128 t0 = _mm_castsi128_ps(block0);
const __m128 t1 = _mm_castsi128_ps(block1);
__m128i x1 = _mm_castps_si128(_mm_shuffle_ps(t0, t1, _MM_SHUFFLE(3,1,3,1)));
__m128i y1 = _mm_castps_si128(_mm_shuffle_ps(t0, t1, _MM_SHUFFLE(2,0,2,0)));
for (int i = static_cast<int>(rounds-1); i >= 0; --i)
{
const __m128i rk = _mm_set1_epi32(subkeys[i]);
y1 = _mm_xor_si128(y1, x1);
y1 = RotateRight32<3>(y1);
x1 = _mm_xor_si128(x1, rk);
x1 = _mm_sub_epi32(x1, y1);
x1 = RotateLeft32<8>(x1);
}
// The is roughly the SSE equivalent to ARM vzp32
// [A1 A3 B1 B3][A2 A4 B2 B4] => [A1 A2 A3 A4][B1 B2 B3 B4]
block0 = _mm_unpacklo_epi32(y1, x1);
block1 = _mm_unpackhi_epi32(y1, x1);
}
inline void GCC_NO_UBSAN SPECK64_Enc_6_Blocks(__m128i &block0, __m128i &block1,
__m128i &block2, __m128i &block3, __m128i &block4, __m128i &block5,
const word32 *subkeys, unsigned int rounds)
{
// Rearrange the data for vectorization. The incoming data was read into
// a little-endian word array. Depending on the number of blocks it needs to
// be permuted to the following. Thanks to Peter Cordes for help with the
// SSE permutes below.
// [A1 A2 A3 A4][B1 B2 B3 B4] ... => [A1 A3 B1 B3][A2 A4 B2 B4] ...
const __m128 t0 = _mm_castsi128_ps(block0);
const __m128 t1 = _mm_castsi128_ps(block1);
__m128i x1 = _mm_castps_si128(_mm_shuffle_ps(t0, t1, _MM_SHUFFLE(3,1,3,1)));
__m128i y1 = _mm_castps_si128(_mm_shuffle_ps(t0, t1, _MM_SHUFFLE(2,0,2,0)));
const __m128 t2 = _mm_castsi128_ps(block2);
const __m128 t3 = _mm_castsi128_ps(block3);
__m128i x2 = _mm_castps_si128(_mm_shuffle_ps(t2, t3, _MM_SHUFFLE(3,1,3,1)));
__m128i y2 = _mm_castps_si128(_mm_shuffle_ps(t2, t3, _MM_SHUFFLE(2,0,2,0)));
const __m128 t4 = _mm_castsi128_ps(block4);
const __m128 t5 = _mm_castsi128_ps(block5);
__m128i x3 = _mm_castps_si128(_mm_shuffle_ps(t4, t5, _MM_SHUFFLE(3,1,3,1)));
__m128i y3 = _mm_castps_si128(_mm_shuffle_ps(t4, t5, _MM_SHUFFLE(2,0,2,0)));
for (int i=0; i < static_cast<int>(rounds); ++i)
{
const __m128i rk = _mm_set1_epi32(subkeys[i]);
x1 = RotateRight32<8>(x1);
x2 = RotateRight32<8>(x2);
x3 = RotateRight32<8>(x3);
x1 = _mm_add_epi32(x1, y1);
x2 = _mm_add_epi32(x2, y2);
x3 = _mm_add_epi32(x3, y3);
x1 = _mm_xor_si128(x1, rk);
x2 = _mm_xor_si128(x2, rk);
x3 = _mm_xor_si128(x3, rk);
y1 = RotateLeft32<3>(y1);
y2 = RotateLeft32<3>(y2);
y3 = RotateLeft32<3>(y3);
y1 = _mm_xor_si128(y1, x1);
y2 = _mm_xor_si128(y2, x2);
y3 = _mm_xor_si128(y3, x3);
}
// The is roughly the SSE equivalent to ARM vzp32
// [A1 A3 B1 B3][A2 A4 B2 B4] => [A1 A2 A3 A4][B1 B2 B3 B4]
block0 = _mm_unpacklo_epi32(y1, x1);
block1 = _mm_unpackhi_epi32(y1, x1);
block2 = _mm_unpacklo_epi32(y2, x2);
block3 = _mm_unpackhi_epi32(y2, x2);
block4 = _mm_unpacklo_epi32(y3, x3);
block5 = _mm_unpackhi_epi32(y3, x3);
}
inline void GCC_NO_UBSAN SPECK64_Dec_6_Blocks(__m128i &block0, __m128i &block1,
__m128i &block2, __m128i &block3, __m128i &block4, __m128i &block5,
const word32 *subkeys, unsigned int rounds)
{
// Rearrange the data for vectorization. The incoming data was read into
// a little-endian word array. Depending on the number of blocks it needs to
// be permuted to the following. Thanks to Peter Cordes for help with the
// SSE permutes below.
// [A1 A2 A3 A4][B1 B2 B3 B4] ... => [A1 A3 B1 B3][A2 A4 B2 B4] ...
const __m128 t0 = _mm_castsi128_ps(block0);
const __m128 t1 = _mm_castsi128_ps(block1);
__m128i x1 = _mm_castps_si128(_mm_shuffle_ps(t0, t1, _MM_SHUFFLE(3,1,3,1)));
__m128i y1 = _mm_castps_si128(_mm_shuffle_ps(t0, t1, _MM_SHUFFLE(2,0,2,0)));
const __m128 t2 = _mm_castsi128_ps(block2);
const __m128 t3 = _mm_castsi128_ps(block3);
__m128i x2 = _mm_castps_si128(_mm_shuffle_ps(t2, t3, _MM_SHUFFLE(3,1,3,1)));
__m128i y2 = _mm_castps_si128(_mm_shuffle_ps(t2, t3, _MM_SHUFFLE(2,0,2,0)));
const __m128 t4 = _mm_castsi128_ps(block4);
const __m128 t5 = _mm_castsi128_ps(block5);
__m128i x3 = _mm_castps_si128(_mm_shuffle_ps(t4, t5, _MM_SHUFFLE(3,1,3,1)));
__m128i y3 = _mm_castps_si128(_mm_shuffle_ps(t4, t5, _MM_SHUFFLE(2,0,2,0)));
for (int i = static_cast<int>(rounds-1); i >= 0; --i)
{
const __m128i rk = _mm_set1_epi32(subkeys[i]);
y1 = _mm_xor_si128(y1, x1);
y2 = _mm_xor_si128(y2, x2);
y3 = _mm_xor_si128(y3, x3);
y1 = RotateRight32<3>(y1);
y2 = RotateRight32<3>(y2);
y3 = RotateRight32<3>(y3);
x1 = _mm_xor_si128(x1, rk);
x2 = _mm_xor_si128(x2, rk);
x3 = _mm_xor_si128(x3, rk);
x1 = _mm_sub_epi32(x1, y1);
x2 = _mm_sub_epi32(x2, y2);
x3 = _mm_sub_epi32(x3, y3);
x1 = RotateLeft32<8>(x1);
x2 = RotateLeft32<8>(x2);
x3 = RotateLeft32<8>(x3);
}
// The is roughly the SSE equivalent to ARM vzp32
// [A1 A3 B1 B3][A2 A4 B2 B4] => [A1 A2 A3 A4][B1 B2 B3 B4]
block0 = _mm_unpacklo_epi32(y1, x1);
block1 = _mm_unpackhi_epi32(y1, x1);
block2 = _mm_unpacklo_epi32(y2, x2);
block3 = _mm_unpackhi_epi32(y2, x2);
block4 = _mm_unpacklo_epi32(y3, x3);
block5 = _mm_unpackhi_epi32(y3, x3);
}
#endif // CRYPTOPP_SSE41_AVAILABLE
ANONYMOUS_NAMESPACE_END
///////////////////////////////////////////////////////////////////////
NAMESPACE_BEGIN(CryptoPP)
// *************************** ARM NEON **************************** //
#if defined(CRYPTOPP_ARM_NEON_AVAILABLE)
size_t SPECK64_Enc_AdvancedProcessBlocks_NEON(const word32* subKeys, size_t rounds,
const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags)
{
return AdvancedProcessBlocks64_6x2_NEON(SPECK64_Enc_Block, SPECK64_Enc_6_Blocks,
subKeys, rounds, inBlocks, xorBlocks, outBlocks, length, flags);
}
size_t SPECK64_Dec_AdvancedProcessBlocks_NEON(const word32* subKeys, size_t rounds,
const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags)
{
return AdvancedProcessBlocks64_6x2_NEON(SPECK64_Dec_Block, SPECK64_Dec_6_Blocks,
subKeys, rounds, inBlocks, xorBlocks, outBlocks, length, flags);
}
#endif
#if (CRYPTOPP_ARM_NEON_AVAILABLE)
size_t SPECK128_Enc_AdvancedProcessBlocks_NEON(const word64* subKeys, size_t rounds,
const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags)
{
return AdvancedProcessBlocks128_6x2_NEON(SPECK128_Enc_Block, SPECK128_Enc_6_Blocks,
subKeys, rounds, inBlocks, xorBlocks, outBlocks, length, flags);
}
size_t SPECK128_Dec_AdvancedProcessBlocks_NEON(const word64* subKeys, size_t rounds,
const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags)
{
return AdvancedProcessBlocks128_6x2_NEON(SPECK128_Dec_Block, SPECK128_Dec_6_Blocks,
subKeys, rounds, inBlocks, xorBlocks, outBlocks, length, flags);
}
#endif // CRYPTOPP_ARM_NEON_AVAILABLE
// ***************************** IA-32 ***************************** //
#if defined(CRYPTOPP_SSE41_AVAILABLE)
size_t SPECK64_Enc_AdvancedProcessBlocks_SSE41(const word32* subKeys, size_t rounds,
const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags)
{
return AdvancedProcessBlocks64_6x2_SSE(SPECK64_Enc_Block, SPECK64_Enc_6_Blocks,
subKeys, rounds, inBlocks, xorBlocks, outBlocks, length, flags);
}
size_t SPECK64_Dec_AdvancedProcessBlocks_SSE41(const word32* subKeys, size_t rounds,
const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags)
{
return AdvancedProcessBlocks64_6x2_SSE(SPECK64_Dec_Block, SPECK64_Dec_6_Blocks,
subKeys, rounds, inBlocks, xorBlocks, outBlocks, length, flags);
}
#endif
#if defined(CRYPTOPP_SSSE3_AVAILABLE)
size_t SPECK128_Enc_AdvancedProcessBlocks_SSSE3(const word64* subKeys, size_t rounds,
const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags)
{
return AdvancedProcessBlocks128_6x2_SSE(SPECK128_Enc_Block, SPECK128_Enc_6_Blocks,
subKeys, rounds, inBlocks, xorBlocks, outBlocks, length, flags);
}
size_t SPECK128_Dec_AdvancedProcessBlocks_SSSE3(const word64* subKeys, size_t rounds,
const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags)
{
return AdvancedProcessBlocks128_6x2_SSE(SPECK128_Dec_Block, SPECK128_Dec_6_Blocks,
subKeys, rounds, inBlocks, xorBlocks, outBlocks, length, flags);
}
#endif // CRYPTOPP_SSSE3_AVAILABLE
NAMESPACE_END
| [
"191904554@qq.com"
] | 191904554@qq.com |
4103af0829cfe05cbdf639211c0a2de4f5d18e36 | 833177e49475ed3e4cb56db328d613f8d79827ae | /week_02/10-25/10.cpp | 302b7c03e7df5f0706b6461aa367b5d82f2e8e14 | [] | no_license | greenfox-zerda-sparta/nmate91 | 7b5e62b341541cea50eb163ffe415bc7516d1d17 | 079a699c86524c6f34c606cefd1d281afded8c45 | refs/heads/master | 2021-01-17T18:20:55.082949 | 2017-02-21T13:57:35 | 2017-02-21T13:57:35 | 71,350,439 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 251 | cpp | #include <iostream>
#include <string>
// create a function that doubles it's input
// double j with it
using namespace std;
int sayNumber(int number) {
cout << 2*number;
return 2*number;
}
int main() {
int j = 123;
sayNumber(j);
return 0;
}
| [
"nmate91@gmail.com"
] | nmate91@gmail.com |
197886825bbfc79929ea026580970b9343100f97 | f9f932fceeb14fa08843d5fca8e2153570a90990 | /WLTriangleMeshBuffer.cpp | a441dbc232494c04dae7237af3b9a6141d3e6d34 | [] | no_license | znr1976/WorldLib | b0d7394e40adf32788fdb0bd4136844282e8225d | d27a30195abd771392777eb97abc69df0b04e9e2 | refs/heads/master | 2021-01-01T18:29:21.694442 | 2010-06-01T15:36:11 | 2010-06-01T15:36:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,851 | cpp | /*
* WLTriangleMeshBuffer.cpp
* GLSandbox
*
* Created by zen1976
*/
#include "WLTriangleMeshBuffer.h"
#include <stdlib.h>
void WLTriangleMeshBuffer::readOneLineFromFile( FILE* fp, char* string )
{
do
{
fgets( string, 255, fp );
} while( ( string[ 0 ] == '/' ) || ( string[ 0 ] == '\n' ) );
return;
}
WLTriangleMeshBuffer::WLTriangleMeshBuffer( char* fileName ): triangles(0)
{
FILE *filein;
char oneline[ 255 ];
int triloop, vertloop;
float x, y, z, u, v;
filein = fopen( fileName, "rt" );
if( !filein )
{
printf("cannot find file: %s\n", fileName);
return;
}
readOneLineFromFile( filein, oneline );
sscanf( oneline, "NUMPOLLIES %d\n", &numTriangles );
triangles = (WLTriangle*) calloc( numTriangles, sizeof( WLTriangle ) );
// Step through each triangle in sector
for( triloop = 0; triloop < numTriangles; triloop++ )
{
readOneLineFromFile( filein, oneline );
sscanf(oneline, "Tri %d", &(triangles[triloop].textureNumber) );
// Step through each vertex in triangle
for( vertloop = 0; vertloop < 3; vertloop++ )
{
readOneLineFromFile( filein, oneline );
sscanf( oneline, "%f %f %f %f %f", &x, &y, &z, &u, &v );
// Store values into respective vertices
triangles[ triloop ].vertex[ vertloop ].point.x = x;
triangles[ triloop ].vertex[ vertloop ].point.y = y;
triangles[ triloop ].vertex[ vertloop ].point.z = z;
triangles[ triloop ].vertex[ vertloop ].textCoord.x = u;
triangles[ triloop ].vertex[ vertloop ].textCoord.y = v;
}
}
fclose( filein );
return;
}
WLTriangleMeshBuffer::~WLTriangleMeshBuffer()
{
if( triangles != 0 )
{
free( triangles );
}
}
| [
"zen@zen1976.com"
] | zen@zen1976.com |
1c2001cca1d47cf931fccb9042b59083952a2a64 | ec98c3ff6cf5638db5c590ea9390a04b674f8f99 | /genfile/include/genfile/FileUtils.hpp | 172d5dc276901a6bcafd55bcd16e7e311f9ead30 | [
"GPL-1.0-or-later",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
] | permissive | gavinband/qctool | 37e1122d61555a39e1ae6504e4ca1c4d75f371e9 | 8d8adb45151c91f953fe4a9af00498073b1132ba | refs/heads/master | 2023-06-22T07:16:36.897058 | 2021-11-13T00:12:26 | 2021-11-13T00:12:26 | 351,933,501 | 6 | 2 | BSL-1.0 | 2023-06-12T14:13:57 | 2021-03-26T23:04:52 | C++ | UTF-8 | C++ | false | false | 2,290 | hpp |
// Copyright Gavin Band 2008 - 2012.
// 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 GENFILE_FILE_UTILS_HPP
#define GENFILE_FILE_UTILS_HPP
#include <string>
#include <memory>
#include "genfile/Chromosome.hpp"
namespace genfile {
struct CompressionType {
CompressionType( char const* type ) ;
CompressionType( std::string const& type ) ;
CompressionType( CompressionType const& other ) ;
CompressionType& operator=( CompressionType const& other ) ;
bool operator==( CompressionType const& other ) const ;
private:
std::string m_type ;
void check_type() const ;
} ;
CompressionType get_compression_type_indicated_by_filename( std::string const& filename ) ;
Chromosome get_chromosome_indicated_by_filename( std::string const& filename ) ;
std::pair< std::string, std::string > uniformise( std::string filename ) ;
std::string get_gen_file_extension_if_present( std::string const& filename ) ;
std::string strip_gen_file_extension_if_present( std::string const& filename ) ;
std::pair< std::string, std::string > split_extension( std::string const& filename ) ;
std::string replace_or_add_extension( std::string const& filename, std::string const& new_extension ) ;
std::string create_temporary_filename() ;
std::auto_ptr< std::istream > open_text_file_for_input( std::string filename, CompressionType compression_type ) ;
std::auto_ptr< std::istream > open_text_file_for_input( std::string filename ) ;
std::auto_ptr< std::ostream > open_text_file_for_output( std::string filename, CompressionType compression_type ) ;
std::auto_ptr< std::ostream > open_text_file_for_output( std::string filename ) ;
std::auto_ptr< std::istream > open_binary_file_for_input( std::string filename, CompressionType compression_type ) ;
std::auto_ptr< std::istream > open_binary_file_for_input( std::string filename ) ;
std::auto_ptr< std::ostream > open_binary_file_for_output( std::string filename, CompressionType compression_type ) ;
std::auto_ptr< std::ostream > open_binary_file_for_output( std::string filename ) ;
std::size_t count_lines_left_in_stream( std::istream& aStream, bool allow_empty_lines = false ) ;
}
#endif
| [
"gavin.band@well.ox.ac.uk@noemail.net"
] | gavin.band@well.ox.ac.uk@noemail.net |
510fdcf7890ef7169c4c3a170c2b71dd7c09650d | fa52e63e1e6a76be636ff6745599c0941c3d59da | /wurov_messages/install/auv/include/auv/msg/detail/joystick_chaos__builder.hpp | d46316cf5d6f5b4410694bd6691f884c1d881b11 | [] | no_license | WIT-IEEE-MATE-ROV/wurov_ros2 | 687d7dc20df0a4a9e1766d0435d2196ae8cb2247 | 49acd2c64f03be7f1e83bfb6294899ab66e1c50a | refs/heads/master | 2023-01-02T12:19:29.402804 | 2020-10-25T22:29:11 | 2020-10-25T22:29:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,533 | hpp | // generated from rosidl_generator_cpp/resource/idl__builder.hpp.em
// with input from auv:msg/JoystickChaos.idl
// generated code does not contain a copyright notice
#ifndef AUV__MSG__DETAIL__JOYSTICK_CHAOS__BUILDER_HPP_
#define AUV__MSG__DETAIL__JOYSTICK_CHAOS__BUILDER_HPP_
#include "auv/msg/detail/joystick_chaos__struct.hpp"
#include <rosidl_runtime_cpp/message_initialization.hpp>
#include <algorithm>
#include <utility>
namespace auv
{
namespace msg
{
namespace builder
{
class Init_JoystickChaos_thruster
{
public:
explicit Init_JoystickChaos_thruster(::auv::msg::JoystickChaos & msg)
: msg_(msg)
{}
::auv::msg::JoystickChaos thruster(::auv::msg::JoystickChaos::_thruster_type arg)
{
msg_.thruster = std::move(arg);
return std::move(msg_);
}
private:
::auv::msg::JoystickChaos msg_;
};
class Init_JoystickChaos_unkill_thruster
{
public:
explicit Init_JoystickChaos_unkill_thruster(::auv::msg::JoystickChaos & msg)
: msg_(msg)
{}
Init_JoystickChaos_thruster unkill_thruster(::auv::msg::JoystickChaos::_unkill_thruster_type arg)
{
msg_.unkill_thruster = std::move(arg);
return Init_JoystickChaos_thruster(msg_);
}
private:
::auv::msg::JoystickChaos msg_;
};
class Init_JoystickChaos_kill_thruster
{
public:
explicit Init_JoystickChaos_kill_thruster(::auv::msg::JoystickChaos & msg)
: msg_(msg)
{}
Init_JoystickChaos_unkill_thruster kill_thruster(::auv::msg::JoystickChaos::_kill_thruster_type arg)
{
msg_.kill_thruster = std::move(arg);
return Init_JoystickChaos_unkill_thruster(msg_);
}
private:
::auv::msg::JoystickChaos msg_;
};
class Init_JoystickChaos_lag_seconds
{
public:
explicit Init_JoystickChaos_lag_seconds(::auv::msg::JoystickChaos & msg)
: msg_(msg)
{}
Init_JoystickChaos_kill_thruster lag_seconds(::auv::msg::JoystickChaos::_lag_seconds_type arg)
{
msg_.lag_seconds = std::move(arg);
return Init_JoystickChaos_kill_thruster(msg_);
}
private:
::auv::msg::JoystickChaos msg_;
};
class Init_JoystickChaos_magnitude_lever_correction
{
public:
explicit Init_JoystickChaos_magnitude_lever_correction(::auv::msg::JoystickChaos & msg)
: msg_(msg)
{}
Init_JoystickChaos_lag_seconds magnitude_lever_correction(::auv::msg::JoystickChaos::_magnitude_lever_correction_type arg)
{
msg_.magnitude_lever_correction = std::move(arg);
return Init_JoystickChaos_lag_seconds(msg_);
}
private:
::auv::msg::JoystickChaos msg_;
};
class Init_JoystickChaos_magnitude_twist_correction
{
public:
explicit Init_JoystickChaos_magnitude_twist_correction(::auv::msg::JoystickChaos & msg)
: msg_(msg)
{}
Init_JoystickChaos_magnitude_lever_correction magnitude_twist_correction(::auv::msg::JoystickChaos::_magnitude_twist_correction_type arg)
{
msg_.magnitude_twist_correction = std::move(arg);
return Init_JoystickChaos_magnitude_lever_correction(msg_);
}
private:
::auv::msg::JoystickChaos msg_;
};
class Init_JoystickChaos_magnitude_vertical_correction
{
public:
explicit Init_JoystickChaos_magnitude_vertical_correction(::auv::msg::JoystickChaos & msg)
: msg_(msg)
{}
Init_JoystickChaos_magnitude_twist_correction magnitude_vertical_correction(::auv::msg::JoystickChaos::_magnitude_vertical_correction_type arg)
{
msg_.magnitude_vertical_correction = std::move(arg);
return Init_JoystickChaos_magnitude_twist_correction(msg_);
}
private:
::auv::msg::JoystickChaos msg_;
};
class Init_JoystickChaos_magnitude_horizontal_correction
{
public:
explicit Init_JoystickChaos_magnitude_horizontal_correction(::auv::msg::JoystickChaos & msg)
: msg_(msg)
{}
Init_JoystickChaos_magnitude_vertical_correction magnitude_horizontal_correction(::auv::msg::JoystickChaos::_magnitude_horizontal_correction_type arg)
{
msg_.magnitude_horizontal_correction = std::move(arg);
return Init_JoystickChaos_magnitude_vertical_correction(msg_);
}
private:
::auv::msg::JoystickChaos msg_;
};
class Init_JoystickChaos_shift_lever_correction
{
public:
explicit Init_JoystickChaos_shift_lever_correction(::auv::msg::JoystickChaos & msg)
: msg_(msg)
{}
Init_JoystickChaos_magnitude_horizontal_correction shift_lever_correction(::auv::msg::JoystickChaos::_shift_lever_correction_type arg)
{
msg_.shift_lever_correction = std::move(arg);
return Init_JoystickChaos_magnitude_horizontal_correction(msg_);
}
private:
::auv::msg::JoystickChaos msg_;
};
class Init_JoystickChaos_shift_twist_correction
{
public:
explicit Init_JoystickChaos_shift_twist_correction(::auv::msg::JoystickChaos & msg)
: msg_(msg)
{}
Init_JoystickChaos_shift_lever_correction shift_twist_correction(::auv::msg::JoystickChaos::_shift_twist_correction_type arg)
{
msg_.shift_twist_correction = std::move(arg);
return Init_JoystickChaos_shift_lever_correction(msg_);
}
private:
::auv::msg::JoystickChaos msg_;
};
class Init_JoystickChaos_shift_vertical_correction
{
public:
explicit Init_JoystickChaos_shift_vertical_correction(::auv::msg::JoystickChaos & msg)
: msg_(msg)
{}
Init_JoystickChaos_shift_twist_correction shift_vertical_correction(::auv::msg::JoystickChaos::_shift_vertical_correction_type arg)
{
msg_.shift_vertical_correction = std::move(arg);
return Init_JoystickChaos_shift_twist_correction(msg_);
}
private:
::auv::msg::JoystickChaos msg_;
};
class Init_JoystickChaos_shift_horizontal_correction
{
public:
explicit Init_JoystickChaos_shift_horizontal_correction(::auv::msg::JoystickChaos & msg)
: msg_(msg)
{}
Init_JoystickChaos_shift_vertical_correction shift_horizontal_correction(::auv::msg::JoystickChaos::_shift_horizontal_correction_type arg)
{
msg_.shift_horizontal_correction = std::move(arg);
return Init_JoystickChaos_shift_vertical_correction(msg_);
}
private:
::auv::msg::JoystickChaos msg_;
};
class Init_JoystickChaos_header
{
public:
Init_JoystickChaos_header()
: msg_(::rosidl_runtime_cpp::MessageInitialization::SKIP)
{}
Init_JoystickChaos_shift_horizontal_correction header(::auv::msg::JoystickChaos::_header_type arg)
{
msg_.header = std::move(arg);
return Init_JoystickChaos_shift_horizontal_correction(msg_);
}
private:
::auv::msg::JoystickChaos msg_;
};
} // namespace builder
} // namespace msg
template<typename MessageType>
auto build();
template<>
inline
auto build<::auv::msg::JoystickChaos>()
{
return auv::msg::builder::Init_JoystickChaos_header();
}
} // namespace auv
#endif // AUV__MSG__DETAIL__JOYSTICK_CHAOS__BUILDER_HPP_
| [
"mrivnak86@gmail.com"
] | mrivnak86@gmail.com |
c1bdb816dbdd1f4171b266b07c6309d9dc69e382 | 9b7197187ff4beb4efdab509502ee0a2b99672db | /C++_Solutions/Problems/USACO/2014-2016 USACO Training/USACO Contests/Gold/2016-2017/December/checklist.cpp | b6296d985291c521b0e5a56e1b043389a02cdfa7 | [] | no_license | j316chuck/Competitive-Programming | 0c0dfede3e9cbd435301b2b3de7b19cdfff6888f | eabf4d32590fcc423b5a0dab9cdc23ba85fae79f | refs/heads/master | 2020-05-23T07:54:23.806710 | 2018-06-01T03:04:14 | 2018-06-01T03:04:14 | 80,460,910 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,486 | cpp | /*ID: j316chuck
PROG: checklist
LANG: C++
*/
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cctype>
#include <stack>
#include <queue>
#include <list>
#include <vector>
#include <map>
#include <sstream>
#include <cmath>
#include <bitset>
#include <utility>
#include <set>
#include <numeric>
#include <ctime>
#include <climits>
#include <cstdlib>
const double Pi=acos(-1.0);
typedef long long LL;
#define Set(a, s) memset(a, s, sizeof (a))
#define Rd(r) freopen(r, "r", stdin)
#define Wt(w) freopen(w, "w", stdout)
#define pii pair<int, int>
using namespace std;
int graph[1005][1005];
int dist(int x1, int x2, int y1, int y2){
return (x1-x2) * (x1-x2) + (y1-y2) * (y1-y2);
}
int main(){
Rd("checklist.in");
Wt("checklist.out");
int h, g;
cin>>h>>g;
vector< pair<int, int> > H;
vector< pair<int, int> > G;
pair<int, int> a;
H.push_back(make_pair(0, 0));
for(int i = 0; i < h; i++){
cin>>a.first>>a.second;
H.push_back(a);
}G.push_back(make_pair(0, 0));
for(int i = 0; i < g; i++){
cin>>a.first>>a.second;
G.push_back(a);
}
for(int i = 0; i <= g; i++){
graph[0][i] = 0;
}
graph[1][0] = 0;
for(int i = 2; i <= h; i++){
graph[i][0] = graph[i-1][0]+dist(H[i].first, H[i-1].first, H[i].second, H[i-1].second);
}
graph[1][1] = dist(G[1].first, H[1].first, G[1].second, H[1].second);
for(int i = 2; i <= g; i++){
graph[1][i] = graph[1][i-1] + dist(G[i].first, G[i-1].first, G[i].second, G[i-1].second);
}
for(int i = 0; i <= g; i++){
graph[h][i] = INT_MAX;
}
for(int i = 2; i < h; i++){
for(int j = 1; j <= g; j++){
int top = graph[i-1][j] + dist(H[i].first, G[j].first, H[i].second, G[j].second);
int left = graph[i][j-1] + dist(H[i].first, H[i-1].first, H[i].second, H[i-1].second);
if(j == 1 && i == 2){
graph[i][j] = top;
}else if(j == 1 && i!=2){
graph[i][j] = left;
}else{
graph[i][j] = min(top, left);
}
//cout<<graph[i][j]<<' ';
}//cout<<endl;
}
/*for(int i = 0; i <= h; i++){
for(int j = 0; j <=g; j++){
cout<<graph[i][j]<<' ';
}cout<<endl;
}*/
graph[h][g] = graph[h-1][g] + dist(H[h].first, H[h-1].first, H[h].second, H[h-1].second);
cout<<graph[h][g]<<endl;
}
| [
"chuck.tang98@gmail.com"
] | chuck.tang98@gmail.com |
9a55dad6d3b240ea44a558eef2f45f0e21355c9e | 2b6cbe01dca6f4f97ae8b560e69c7cc44086cecc | /src/Trafalgar/Trafalgar_4_2.cpp | f3a9a35551c5d39232dad4a4b90a01c0e08850de | [
"MIT"
] | permissive | HulinCedric/trafalgar-simulator | cf0cc6a67b3a12b7d203fe6be22a874fc896e71e | c383887cfaf4dfbb4a3afb268c7a8b5a9f8e13b6 | refs/heads/master | 2022-05-28T12:08:42.866518 | 2020-05-03T09:45:48 | 2020-05-03T09:50:07 | 260,871,586 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,159 | cpp | //
// IUT de Nice / Departement informatique / Module APO-C++
// Annee 2008_2009 - Package _Trafalgar
//
// Classe Trafalgar - Service deplacer
//
// Auteur : C. Hulin, C. Fouco, L. Souquet
//
#include "Trafalgar.h"
// --- Deplacement de tous les navires en jeu
//
void Trafalgar::deplacer ()
{
// Controler que la simulation temps reel est active
//
if (m_status == false) throw -3.1;
// Allouer un tableau dynamique de toutes les iles
//
int cardinal= nombreIles();
Ile** pIles= new Ile*[cardinal + 1];
if (pIles == NULL) throw -1.0;
// Renseigner les elements du tableau
//
map<string, Ile*>::iterator i;
int e;
for (i=m_pIles.begin(), e=0; i != m_pIles.end(); i++, e++)
{
// Faire progresser le navire courant suivant son vecteur vitesse
//
pIles[e]=i->second;
}
// Marquer la fin du tableau
//
pIles[cardinal]= NULL;
// Parcourir l'ensemble des navires
//
map<string, Navire*>::iterator k;
for (k=m_pNavires.begin(); k != m_pNavires.end(); k++)
{
// Faire progresser le navire courant suivant son vecteur vitesse
//
(k->second)->deplacer(pIles);
}
// Liberer le tableau de travail
//
delete[] pIles;
} | [
"hulin.cedric@gmail.com"
] | hulin.cedric@gmail.com |
fd2eb983365d9f4388591832a133150b6c3a4cd9 | 02ce8a5d3386aa639ef1c2c2fdd6da8d0de158f9 | /ACE-5.6.1/ACE_wrappers/apps/JAWS3/jaws3/Reactive_IO.h | 58a15213b3a113031f0020a3785065bf6da9668d | [] | no_license | azraelly/knetwork | 932e27a22b1ee621742acf57618083ecab23bca1 | 69e30ee08d0c8e66c1cfb00d7ae3ba6983ff935c | refs/heads/master | 2021-01-20T13:48:24.909756 | 2010-07-03T13:59:39 | 2010-07-03T13:59:39 | 39,634,314 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,882 | h | /* -*- c++ -*- */
// $Id: Reactive_IO.h 63968 2005-02-14 23:33:37Z shuston $
#ifndef JAWS_REACTIVE_IO_H
#define JAWS_REACTIVE_IO_H
#include "ace/Message_Block.h"
#include "ace/Singleton.h"
#include "ace/Synch_Traits.h"
#include "ace/Time_Value.h"
#include "jaws3/Export.h"
#include "jaws3/IO.h"
#include "jaws3/Event_Result.h"
class JAWS_Reactive_IO;
class JAWS_Export JAWS_Reactive_IO : public JAWS_IO_Impl
{
public:
static JAWS_Reactive_IO * instance (void)
{
return ACE_Singleton<JAWS_Reactive_IO, ACE_SYNCH_MUTEX>::instance ();
}
void send ( ACE_HANDLE handle
, ACE_Message_Block *mb
, JAWS_Event_Completer *completer
, void *act = 0
);
void recv ( ACE_HANDLE handle
, ACE_Message_Block *mb
, JAWS_Event_Completer *completer
, void *act = 0
);
void transmit ( ACE_HANDLE handle
, ACE_HANDLE source
, JAWS_Event_Completer *completer
, void *act = 0
, ACE_Message_Block *header = 0
, ACE_Message_Block *trailer = 0
);
void send ( ACE_HANDLE handle
, ACE_Message_Block *mb
, JAWS_Event_Completer *completer
, const ACE_Time_Value &tv
, void *act = 0
);
void recv ( ACE_HANDLE handle
, ACE_Message_Block *mb
, JAWS_Event_Completer *completer
, const ACE_Time_Value &tv
, void *act = 0
);
void transmit ( ACE_HANDLE handle
, ACE_HANDLE source
, JAWS_Event_Completer *completer
, const ACE_Time_Value &tv
, void *act = 0
, ACE_Message_Block *header = 0
, ACE_Message_Block *trailer = 0
);
};
#endif /* JAWS_REACTIVE_IO_H */
| [
"yuwuxiong2010@gmail.com"
] | yuwuxiong2010@gmail.com |
75cb4fa0683408802e82794d497c897180a3ea92 | 5ebd5cee801215bc3302fca26dbe534e6992c086 | /blaze/math/traits/ReduceTrait.h | 454c2e1a45929499669b120c1b49179dc0db95ca | [
"BSD-3-Clause"
] | permissive | mhochsteger/blaze | c66d8cf179deeab4f5bd692001cc917fe23e1811 | fd397e60717c4870d942055496d5b484beac9f1a | refs/heads/master | 2020-09-17T01:56:48.483627 | 2019-11-20T05:40:29 | 2019-11-20T05:41:35 | 223,951,030 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,912 | h | //=================================================================================================
/*!
// \file blaze/math/traits/ReduceTrait.h
// \brief Header file for the reduce trait
//
// Copyright (C) 2012-2019 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
#ifndef _BLAZE_MATH_TRAITS_REDUCETRAIT_H_
#define _BLAZE_MATH_TRAITS_REDUCETRAIT_H_
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <utility>
#include <blaze/math/Aliases.h>
#include <blaze/util/InvalidType.h>
#include <blaze/util/Types.h>
namespace blaze {
//=================================================================================================
//
// CLASS DEFINITION
//
//=================================================================================================
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
template< typename, typename, size_t... > struct ReduceTrait;
template< typename, typename, typename = void > struct TotalReduceTraitEval1;
template< typename, typename, typename = void > struct TotalReduceTraitEval2;
template< typename, typename, size_t, typename = void > struct PartialReduceTraitEval1;
template< typename, typename, size_t, typename = void > struct PartialReduceTraitEval2;
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
template< size_t RF, typename T, typename OP >
auto evalReduceTrait( T&, OP )
-> typename PartialReduceTraitEval1<T,OP,RF>::Type;
template< typename T, typename OP >
auto evalReduceTrait( T&, OP )
-> typename TotalReduceTraitEval1<T,OP>::Type;
template< size_t RF, typename T, typename OP >
auto evalReduceTrait( const T&, OP )
-> typename ReduceTrait<T,OP,RF>::Type;
template< typename T, typename OP >
auto evalReduceTrait( const T&, OP )
-> typename ReduceTrait<T,OP>::Type;
template< size_t RF, typename T, typename OP >
auto evalReduceTrait( const volatile T&, OP )
-> typename ReduceTrait<T,OP,RF>::Type;
template< typename T, typename OP >
auto evalReduceTrait( const volatile T&, OP )
-> typename ReduceTrait<T,OP>::Type;
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Base template for the ReduceTrait class.
// \ingroup math_traits
//
// \section reducetrait_general General
//
// The ReduceTrait class template offers the possibility to select the resulting data type of
// a generic reduction operation on the given type \a T. ReduceTrait defines the nested type
// \a Type, which represents the resulting data type of the reduction operation. In case no
// result type can be determined for the type \a T, the resulting data type \a Type is set to
// \a INVALID_TYPE. Note that \c const and \c volatile qualifiers and reference modifiers are
// generally ignored.
//
//
// \n \section reducetrait_specializations Creating custom specializations
//
// ReduceTrait is guaranteed to work for all vector and matrix types of the Blaze library
// (including views and adaptors) and all data types that work in combination with the provided
// reduction operation \a OP. In order to add support for user-defined data types or in order to
// adapt to special cases it is possible to specialize the ReduceTrait template. The following
// examples shows the according specialization for total and partial reduction operations with
// a dynamic matrix, respectively:
\code
template< typename T, bool SO, typename OP >
struct ReduceTrait< DynamicMatrix<T,SO>, OP >
{
using Type = T;
};
\endcode
\code
template< typename T, bool SO, typename OP >
struct ReduceTrait< DynamicMatrix<T,SO>, OP, 0UL >
{
using Type = DynamicVector<T,rowVector>;
};
template< typename T, bool SO, typename OP >
struct ReduceTrait< DynamicMatrix<T,SO>, OP, 1UL >
{
using Type = DynamicVector<T,columnVector>;
};
\endcode
*/
template< typename T // Type of the operand
, typename OP // Type of the reduction operation
, size_t... RF > // Reduction flag
struct ReduceTrait
{
public:
//**********************************************************************************************
/*! \cond BLAZE_INTERNAL */
using Type = decltype( evalReduceTrait<RF...>( std::declval<T&>(), std::declval<OP>() ) );
/*! \endcond */
//**********************************************************************************************
};
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Auxiliary alias declaration for the ReduceTrait class template.
// \ingroup math_traits
//
// The ReduceTrait_t alias declaration provides a convenient shortcut to access the nested
// \a Type of the ReduceTrait class template. For instance, given the type \a T and the custom
// operation type \a OP the following two type definitions are identical:
\code
using Type1 = typename blaze::ReduceTrait<T,OP>::Type;
using Type2 = blaze::ReduceTrait_t<T,OP>;
\endcode
*/
template< typename T // Type of the operand
, typename OP // Type of the reduction operation
, size_t... RF > // Reduction flag
using ReduceTrait_t = typename ReduceTrait<T,OP,RF...>::Type;
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Auxiliary helper struct for the ReduceTrait type trait.
// \ingroup math_traits
*/
template< typename T // Type of the operand
, typename OP // Type of the custom operation
, typename > // Restricting condition
struct TotalReduceTraitEval1
{
public:
//**********************************************************************************************
using Type = typename TotalReduceTraitEval2<T,OP>::Type;
//**********************************************************************************************
};
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Auxiliary helper struct for the ReduceTrait type trait.
// \ingroup math_traits
*/
template< typename T // Type of the operand
, typename OP // Type of the custom operation
, typename > // Restricting condition
struct TotalReduceTraitEval2
{
public:
//**********************************************************************************************
using Type = ElementType_t<T>;
//**********************************************************************************************
};
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Auxiliary helper struct for the ReduceTrait type trait.
// \ingroup math_traits
*/
template< typename T // Type of the operand
, typename OP // Type of the custom operation
, size_t RF // Reduction flag
, typename > // Restricting condition
struct PartialReduceTraitEval1
{
public:
//**********************************************************************************************
using Type = typename PartialReduceTraitEval2<T,OP,RF>::Type;
//**********************************************************************************************
};
/*! \endcond */
//*************************************************************************************************
//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Auxiliary helper struct for the ReduceTrait type trait.
// \ingroup math_traits
*/
template< typename T // Type of the operand
, typename OP // Type of the custom operation
, size_t RF // Reduction flag
, typename > // Restricting condition
struct PartialReduceTraitEval2
{
public:
//**********************************************************************************************
using Type = INVALID_TYPE;
//**********************************************************************************************
};
/*! \endcond */
//*************************************************************************************************
} // namespace blaze
#endif
| [
"klaus.iglberger@gmail.com"
] | klaus.iglberger@gmail.com |
8197df0446099ea1fd3b5b9eb854ec3588d5784f | b7f3edb5b7c62174bed808079c3b21fb9ea51d52 | /chrome/browser/payments/ssl_validity_checker.h | 7cd70d5a34cfd343484b7e02599841c45b7504ea | [
"BSD-3-Clause"
] | permissive | otcshare/chromium-src | 26a7372773b53b236784c51677c566dc0ad839e4 | 64bee65c921db7e78e25d08f1e98da2668b57be5 | refs/heads/webml | 2023-03-21T03:20:15.377034 | 2020-11-16T01:40:14 | 2020-11-16T01:40:14 | 209,262,645 | 18 | 21 | BSD-3-Clause | 2023-03-23T06:20:07 | 2019-09-18T08:52:07 | null | UTF-8 | C++ | false | false | 1,329 | h | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_PAYMENTS_SSL_VALIDITY_CHECKER_H_
#define CHROME_BROWSER_PAYMENTS_SSL_VALIDITY_CHECKER_H_
#include <string>
#include "base/macros.h"
namespace content {
class WebContents;
}
namespace payments {
class SslValidityChecker {
public:
// Returns a developer-facing error message for invalid SSL certificate state
// or an empty string when the SSL certificate is valid. Only SECURE and
// SECURE_WITH_POLICY_INSTALLED_CERT are considered valid for web payments,
// unless --ignore-certificate-errors is specified on the command line.
//
// The |web_contents| parameter should not be null. A null
// |web_contents| parameter will return an "Invalid certificate" error
// message.
static std::string GetInvalidSslCertificateErrorMessage(
content::WebContents* web_contents);
// Whether the given page should be allowed to be displayed in a payment
// handler window.
static bool IsValidPageInPaymentHandlerWindow(
content::WebContents* web_contents);
private:
DISALLOW_IMPLICIT_CONSTRUCTORS(SslValidityChecker);
};
} // namespace payments
#endif // CHROME_BROWSER_PAYMENTS_SSL_VALIDITY_CHECKER_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
b9d89a0434d54dc79e9d4dbe10fdbe28fcac0a09 | 8c235bb46348737ded744a9afc73b6786bd03872 | /ch01/ex1_2/ex1_2/main.cpp | 00e8ede1326ff07c1fbce43a304d7f6c7d0a2843 | [] | no_license | yanmengk/CppPrimer | 5b45ae79838b0d6a515c71f2b0749e6285c72b79 | 7107ec33b3ca2f1214456639138cc0f001aab209 | refs/heads/master | 2020-04-02T02:20:35.006339 | 2018-10-23T13:45:29 | 2018-10-23T13:45:29 | 153,904,243 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 182 | cpp | //
// main.cpp
// ex1_2
//
// Created by 闫梦奎 on 2018/10/22.
// Copyright © 2018年 com.yanmk. All rights reserved.
//
#include <iostream>
int main() {
return -1;
}
| [
"yanmengk@foxmail.com"
] | yanmengk@foxmail.com |
596e12b89f9ff8a013e5038bc7853844407d0d48 | 027836e14779ecc9ac036c39b622bf5d6a31c71b | /addons/misc/CfgVehicles.hpp | 0e165d4376db47e263ab943a415e181046829b87 | [
"MIT"
] | permissive | kellerkompanie/kellerkompanie-medical | 33d5cf8b5c1532e309ff2c8f4cee0ca16fa37781 | b66076217c1c08b6464ec19c15eef72c91bb5cfb | refs/heads/master | 2022-02-16T18:13:01.188420 | 2022-01-28T20:00:41 | 2022-01-28T20:00:41 | 177,442,305 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,751 | hpp | class CfgVehicles {
#include "vehicle_stretcher.hpp"
class Land_IntravenStand_01_base_F;
class Land_IntravenStand_01_empty_F: Land_IntravenStand_01_base_F {
ace_cargo_size = 2;
ace_cargo_canLoad = 1;
// Dragging
ace_dragging_canDrag = 1;
ace_dragging_dragPosition[] = {0, 1.2, 1};
ace_dragging_dragDirection = 0;
// Carrying
ace_dragging_canCarry = 1;
ace_dragging_carryPosition[] = {0, 1.2, 1};
ace_dragging_carryDirection = 0;
};
class Land_IntravenStand_01_1bag_F: Land_IntravenStand_01_base_F {
ace_cargo_size = 2;
ace_cargo_canLoad = 1;
// Dragging
ace_dragging_canDrag = 1;
ace_dragging_dragPosition[] = {0, 1.2, 1};
ace_dragging_dragDirection = 0;
// Carrying
ace_dragging_canCarry = 1;
ace_dragging_carryPosition[] = {0, 1.2, 1};
ace_dragging_carryDirection = 0;
};
class Land_IntravenStand_01_2bags_F: Land_IntravenStand_01_base_F {
ace_cargo_size = 2;
ace_cargo_canLoad = 1;
// Dragging
ace_dragging_canDrag = 1;
ace_dragging_dragPosition[] = {0, 1.2, 1};
ace_dragging_dragDirection = 0;
// Carrying
ace_dragging_canCarry = 1;
ace_dragging_carryPosition[] = {0, 1.2, 1};
ace_dragging_carryDirection = 0;
};
class weapon_bag_base;
class keko_stretcherBag: weapon_bag_base {
class assembleInfo {
displayName = "Stretcher";
assembleTo = "keko_stretcher";
base = "";
primary = 1;
dissasembleTo[] = {};
};
author = "Katalam";
scope = 2;
editorCategory = "EdCat_Equipment";
editorSubcategory = "EdSubcat_DismantledWeapons";
displayName = "Stretcher (Packed)";
mass = 60;
};
class Tank_F;
class keko_stretcher: Tank_F {
explosionEffect = "";
fuelExplosionPower = 0;
editorForceEmpty = 1;
editorSubcategory = "edSubcat_Storage";
crew = "C_man_1";
icon = "iconObject_1x1";
hasDriver = 0;
scope = 2;
side = 3;
faction = "CIV_F";
accuracy = 0.001;
camouflage = 10;
armor = 20;
displayName = "Stretcher";
model = QPATHTOF(models\stretcher\vurtual_stretcher.p3d);
simulation = "tankX";
crewVulnerable = 1;
explosionShielding = 0;
irTarget = 0;
allowTabLock = 0;
memoryPointsGetInCargo = "pos cargo";
memoryPointsGetInCargoDir = "pos cargo dir";
cargoAction[] = {"keko_stretcher"};
tf_isolatedAmount = 0;
numberPhysicalWheels = 0;
hideProxyInCombat = 0;
hideWeaponsCargo = true;
ejectDeadCargo = 0;
class Damage {
tex[] = {};
mat[] = {
QPATHTOF(models\stretcher\seat.rvmat),
QPATHTOF(models\stretcher\seat_destruct.rvmat)
};
};
class animationSources {
class seat_hide {
source = "user";
initPhase = 0;
animPeriod = 0.1;
displayName = "Hide Stretcher";
forceAnimatePhase = 1;
forceAnimate[] = {"legs_hide", 1};
};
};
maximumLoad = 0;
transportMaxBackpacks = 0;
transportMaxMagazines = 64;
class TransportItems;
class CargoTurret;
class Turrets {
class MainTurret: CargoTurret {
gunnerAction = "passenger_inside_2";
gunnerInAction = "passenger_inside_2"; //fixes standing up in steat
memoryPointsGetInGunner = "pos cargo";
memoryPointsGetInGunnerDir = "pos cargo dir";
gunnerName = "Armchair Warrior";
gunnerCompartments = "Compartment1";
proxyIndex = 1;
isPersonTurret = 1;
forceHideGunner = 1; //fixes being turned out in seat
maxElev = 75;
minElev = -75;
maxTurn = 95;
minTurn = -95;
stabilizedInAxes = 3;
primaryGunner = 1;
dontCreateAI = 0;
ejectDeadGunner = 0;
};
};
transportSoldier = 1;
ace_cargo_canLoad = 0;
ace_Cargo_hasCargo = 0;
ace_dragging_canDrag = 1;
ace_dragging_canCarry = 1;
ace_dragging_dragPosition[] = {0,1.7,0};
ace_dragging_carryPosition[] = {0, 1.7, 0};
ace_dragging_dragDirection = 0;
ace_Carry_carryDirection = 0;
ace_cookoff_probability = 0;
slingLoadCargoMemoryPoints[] = {"SlingLoadCargo1", "SlingLoadCargo2", "SlingLoadCargo3", "SlingLoadCargo4"};
destrType = "destructDefault";
fuelCapacity = 0;
//pretend static weapon since some mods don't like unconscious people in static weapons
nameSound = "veh_static_s";
vehicleClass = "static";
unitInfoType = "RscUnitInfoStatic";
crewExplosionProtection = 0;
class DestructionEffects {};
class VehicleTransport {
class Cargo {
parachuteClass = "B_Parachute_02_F";
parachuteHeightLimit = 5;
canBeTransported = 1;
dimensions[] = {"VTV_Cargo_Base", "VTV_Cargo_Corner"};
};
};
class EventHandlers {
init = QUOTE(_this call FUNC(stretcher));
};
};
class Land_Stretcher_01_base_F;
class Land_Stretcher_01_olive_F: Land_Stretcher_01_base_F {
ace_cargo_canLoad = 1;
ace_Cargo_hasCargo = 0;
ace_dragging_canDrag = 1;
ace_dragging_canCarry = 1;
ace_dragging_dragPosition[] = {0,1.7,0};
ace_dragging_carryPosition[] = {0, 1.7, 0};
ace_dragging_dragDirection = 0;
ace_Carry_carryDirection = 0;
ace_cookoff_probability = 0;
class VehicleTransport {
class Cargo {
parachuteClass = "B_Parachute_02_F";
parachuteHeightLimit = 5;
canBeTransported = 1;
dimensions[] = {"VTV_Cargo_Base", "VTV_Cargo_Corner"};
};
};
};
class Man;
class CAManBase: Man {
class ACE_Actions {
class ACE_Torso {
class FieldDressing;
class LimitWounds {
displayName = CSTRING(LIMITWOUNDS_Display);
condition = "[_player, _target, 'hand_l', 'LimitWounds'] call ace_medical_fnc_canTreatCached";
statement = "[_player, _target, 'hand_l', 'LimitWounds'] call ace_medical_fnc_treatment";
icon = "";
};
};
class ACE_ArmLeft {
class SalineIV;
class SalineIV_Stand: SalineIV {
displayName = CSTRING(Display_IVStand);
condition = "[_player, _target, 'hand_l', 'SalineIV_Stand'] call ace_medical_fnc_canTreatCached";
statement = "[_player, _target, 'hand_l', 'SalineIV_Stand'] call ace_medical_fnc_treatment";
};
class SalineIV_Stand_500: SalineIV {
displayName = CSTRING(Display_IVStand_500);
condition = "[_player, _target, 'hand_l', 'SalineIV_Stand_500'] call ace_medical_fnc_canTreatCached";
statement = "[_player, _target, 'hand_l', 'SalineIV_Stand_500'] call ace_medical_fnc_treatment";
};
class SalineIV_Stand_250: SalineIV {
displayName = CSTRING(Display_IVStand_250);
condition = "[_player, _target, 'hand_l', 'SalineIV_Stand_250'] call ace_medical_fnc_canTreatCached";
statement = "[_player, _target, 'hand_l', 'SalineIV_Stand_250'] call ace_medical_fnc_treatment";
};
};
class ACE_ArmRight {
class SalineIV;
class SalineIV_Stand: SalineIV {
displayName = CSTRING(Display_IVStand);
condition = "[_player, _target, 'hand_r', 'SalineIV_Stand'] call ace_medical_fnc_canTreatCached";
statement = "[_player, _target, 'hand_r', 'SalineIV_Stand'] call ace_medical_fnc_treatment";
};
class SalineIV_Stand_500: SalineIV {
displayName = CSTRING(Display_IVStand_500);
condition = "[_player, _target, 'hand_r', 'SalineIV_Stand_500'] call ace_medical_fnc_canTreatCached";
statement = "[_player, _target, 'hand_r', 'SalineIV_Stand_500'] call ace_medical_fnc_treatment";
};
class SalineIV_Stand_250: SalineIV {
displayName = CSTRING(Display_IVStand_250);
condition = "[_player, _target, 'hand_r', 'SalineIV_Stand_250'] call ace_medical_fnc_canTreatCached";
statement = "[_player, _target, 'hand_r', 'SalineIV_Stand_250'] call ace_medical_fnc_treatment";
};
};
class ACE_LegLeft {
class SalineIV;
class SalineIV_Stand: SalineIV {
displayName = CSTRING(Display_IVStand);
condition = "[_player, _target, 'leg_l', 'SalineIV_Stand'] call ace_medical_fnc_canTreatCached";
statement = "[_player, _target, 'leg_l', 'SalineIV_Stand'] call ace_medical_fnc_treatment";
};
class SalineIV_Stand_500: SalineIV {
displayName = CSTRING(Display_IVStand_500);
condition = "[_player, _target, 'leg_l', 'SalineIV_Stand_500'] call ace_medical_fnc_canTreatCached";
statement = "[_player, _target, 'leg_l', 'SalineIV_Stand_500'] call ace_medical_fnc_treatment";
};
class SalineIV_Stand_250: SalineIV {
displayName = CSTRING(Display_IVStand_250);
condition = "[_player, _target, 'leg_l', 'SalineIV_Stand_250'] call ace_medical_fnc_canTreatCached";
statement = "[_player, _target, 'leg_l', 'SalineIV_Stand_250'] call ace_medical_fnc_treatment";
};
};
class ACE_LegRight {
class SalineIV;
class SalineIV_Stand: SalineIV {
displayName = CSTRING(Display_IVStand);
condition = "[_player, _target, 'leg_r', 'SalineIV_Stand'] call ace_medical_fnc_canTreatCached";
statement = "[_player, _target, 'leg_r', 'SalineIV_Stand'] call ace_medical_fnc_treatment";
};
class SalineIV_Stand_500: SalineIV {
displayName = CSTRING(Display_IVStand_500);
condition = "[_player, _target, 'leg_r', 'SalineIV_Stand_500'] call ace_medical_fnc_canTreatCached";
statement = "[_player, _target, 'leg_r', 'SalineIV_Stand_500'] call ace_medical_fnc_treatment";
};
class SalineIV_Stand_250: SalineIV {
displayName = CSTRING(Display_IVStand_250);
condition = "[_player, _target, 'leg_r', 'SalineIV_Stand_250'] call ace_medical_fnc_canTreatCached";
statement = "[_player, _target, 'leg_r', 'SalineIV_Stand_250'] call ace_medical_fnc_treatment";
};
};
};
};
};
| [
"tom.ryan@posteo.de"
] | tom.ryan@posteo.de |
4b2c688fa2eabbadf91beb4a38d1c3941b5b55f1 | 0827212dfe463561f4f47f10babe2dcb3cc7a97e | /src/delaunay/gDel2D/GPU/MemoryManager.h | 7027eb06a793dc58375bdd8fa16407037f1224c7 | [] | no_license | kiyeong/CUDA-Stereo-Matching | 13dc77f205fd2d462761637db1a4842ffd85f272 | 0b341890182a47d9de1817a87efaa41417735328 | refs/heads/master | 2022-04-09T04:28:40.556454 | 2020-03-06T09:42:13 | 2020-03-06T09:42:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,324 | h | #pragma once
#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include <thrust/device_malloc.h>
#include "CudaWrapper.h"
#include "../../../Utils.h"
////////////////////////////////////////////////////////////////// DevVector //
template< typename T >
class DevVector
{
public:
// Types
typedef typename thrust::device_ptr< T > iterator;
// Properties
thrust::device_ptr< T > _ptr;
size_t _size;
size_t _capacity;
bool _owned;
DevVector( ) : _size( 0 ), _capacity( 0 ){}
DevVector( size_t n ) : _size( 0 ), _capacity( 0 )
{
resize( n );
return;
}
DevVector( size_t n, T value ) : _size( 0 ), _capacity( 0 )
{
assign( n, value );
return;
}
~DevVector()
{
free();
return;
}
void free()
{
if ( _capacity > 0 && _owned )
CudaSafeCall( cudaFree( _ptr.get() ) );
_size = 0;
_capacity = 0;
return;
}
// Use only for cases where new size is within capacity
// So, old data remains in-place
void expand( size_t n )
{
assert( ( _capacity >= n ) && "New size not within current capacity! Use resize!" );
_size = n;
}
// Resize with data remains
void grow( size_t n )
{
assert( ( n >= _size ) && "New size not larger than old size." );
if ( _capacity >= n )
{
_size = n;
return;
}
DevVector< T > tempVec( n );
thrust::copy( begin(), end(), tempVec.begin() );
swapAndFree( tempVec );
}
void resize( size_t n )
{
if ( _capacity >= n )
{
_size = n;
return;
}
if ( !_owned && _capacity > 0 )
{
std::cerr << "WARNING: Resizing a DevVector with borrowing pointer!" << std::endl;
}
free();
_size = n;
_capacity = ( n == 0 ) ? 1 : n;
_owned = true;
try
{
_ptr = thrust::device_malloc< T >( _capacity );
}
catch( ... )
{
// output an error message and exit
const int OneMB = ( 1 << 20 );
std::cerr << "thrust::device_malloc failed to allocate " << ( sizeof( T ) * _capacity ) / OneMB << " MB!" << std::endl;
std::cerr << "size = " << _size << " sizeof(T) = " << sizeof( T ) << std::endl;
exit( -1 );
}
return;
}
void assign( size_t n, const T& value )
{
resize( n );
thrust::fill_n( begin(), n, value );
return;
}
size_t size() const { return _size; }
size_t capacity() const { return _capacity; }
thrust::device_reference< T > operator[] ( const size_t index ) const
{
return _ptr[ index ];
}
const iterator begin() const { return _ptr; }
const iterator end() const { return _ptr + _size; }
void erase( const iterator& first, const iterator& last )
{
if ( last == end() )
{
_size -= (last - first);
}
else
{
assert( false && "Not supported right now!" );
}
return;
}
void swap( DevVector< T >& arr )
{
size_t tempSize = _size;
size_t tempCap = _capacity;
bool tempOwned = _owned;
T* tempPtr = ( _capacity > 0 ) ? _ptr.get() : 0;
_size = arr._size;
_capacity = arr._capacity;
_owned = arr._owned;
if ( _capacity > 0 )
{
_ptr = thrust::device_ptr< T >( arr._ptr.get() );
}
arr._size = tempSize;
arr._capacity = tempCap;
arr._owned = tempOwned;
if ( tempCap > 0 )
{
arr._ptr = thrust::device_ptr< T >( tempPtr );
}
return;
}
// Input array is freed
void swapAndFree( DevVector< T >& inArr )
{
swap( inArr );
inArr.free();
return;
}
void copyFrom( const DevVector< T >& inArr )
{
resize( inArr.size() );
thrust::copy( inArr.begin(), inArr.end(), begin() );
return;
}
void fill( const T& value )
{
thrust::fill_n( _ptr, _size, value );
return;
}
void copyToHost( thrust::host_vector< T >& dest ) const
{
dest.insert( dest.begin(), begin(), end() );
return;
}
// Do NOT remove! Useful for debugging.
void copyFromHost( const thrust::host_vector< T >& inArr )
{
resize( inArr.size() );
thrust::copy( inArr.begin(), inArr.end(), begin() );
return;
}
void copyFromHost( const T* h_ptr, size_t size)
{
resize( size );
thrust::copy (h_ptr, h_ptr+size, begin() );
}
DevVector& operator =(DevVector other){
DevVector<T>::swap(other);
return *this;
}
};
template< typename T >
class Dev2DVector : public DevVector<T>
{
public:
Dev2DVector() : DevVector<T>(), _width(0), _height(0) {}
Dev2DVector(int32_t width_, int32_t height_ )
: DevVector<T>(width_*height_),
_width(width_),
_height(height_)
{
}
Dev2DVector(int32_t width_, int32_t height_, T value_ )
: DevVector<T>(width_*height_, value_),
_width(width_),
_height(height_)
{
}
Dev2DVector& operator =(Dev2DVector other){
DevVector<T>::swap(other);
std::swap(_width, other._width);
std::swap(_height, other._height);
return *this;
}
int32_t width() const { return _width; }
int32_t height() const { return _height; }
private:
int32_t _width;
int32_t _height;
};
//////////////////////////////////////////////////////////// Memory pool //
struct Buffer
{
void* ptr;
size_t sizeInBytes;
bool avail;
};
class MemoryPool
{
private:
std::vector< Buffer > _memPool; // Two items
public:
MemoryPool() {}
~MemoryPool()
{
free();
}
void free( bool report = false )
{
for ( int i = 0; i < _memPool.size(); ++i )
{
if ( report )
std::cout << "MemoryPool: [" << i << "]" << _memPool[i].sizeInBytes << std::endl;
if ( false == _memPool[ i ].avail )
std::cerr << "WARNING: MemoryPool item not released!" << std::endl;
else
CudaSafeCall( cudaFree( _memPool[i].ptr ) );
}
_memPool.clear();
}
template<typename T>
int reserve( size_t size )
{
DevVector<T> vec( size );
vec._owned = false;
Buffer buf = {
( void* ) vec._ptr.get(),
size * sizeof(T),
true
};
_memPool.push_back( buf );
return _memPool.size() - 1;
}
template<typename T>
DevVector<T> allocateAny( size_t size, bool tempOnly = false )
{
// Find best fit block
size_t sizeInBytes = size * sizeof(T);
int bufIdx = -1;
for ( int i = 0; i < _memPool.size(); ++i )
if ( _memPool[i].avail && _memPool[i].sizeInBytes >= sizeInBytes )
if ( bufIdx == -1 || _memPool[i].sizeInBytes < _memPool[bufIdx].sizeInBytes )
bufIdx = i;
if ( bufIdx == -1 )
{
std::cout << "MemoryPool: Allocating " << sizeInBytes << std::endl;
bufIdx = reserve<T>( size );
}
DevVector<T> vec;
vec._ptr = thrust::device_ptr<T>( (T*) _memPool[ bufIdx ].ptr );
vec._capacity = _memPool[ bufIdx ].sizeInBytes / sizeof(T);
vec._size = 0;
vec._owned = false;
//std::cout << "MemoryPool: Requesting "
// << sizeInBytes << ", giving " << _memPool[ bufIdx ].sizeInBytes << std::endl;
// Disable the buffer in the pool
if ( !tempOnly )
_memPool[ bufIdx ].avail = false;
return vec;
}
template<typename T>
void release( DevVector<T>& vec )
{
for ( int i = 0; i < _memPool.size(); ++i )
if ( _memPool[i].ptr == (void*) vec._ptr.get() )
{
assert( !_memPool[i].avail );
assert( !vec._owned );
// Return the buffer to the pool
_memPool[i].avail = true;
//std::cout << "MemoryPool: Returning " << _memPool[i].sizeInBytes << std::endl;
// Reset the vector to 0 size
vec.free();
return ;
}
std::cerr << "WARNING: Releasing a DevVector not in the MemoryPool!" << std::endl;
// Release the vector
vec._owned = true; // Set this to true so it releases itself.
vec.free();
return ;
}
};
| [
"felix.rodau@gmail.com"
] | felix.rodau@gmail.com |
fac18e363f78bee79a180d23881ea94e38642243 | f4ee50b024286ad54d96b3757a97df44eeb8e9bf | /C++/Qt/RackProject/systemrack.h | d315d9d836672dcf1100e4c72a38deb31b916daf | [
"MIT"
] | permissive | aadshalshihry/sandbox | db89548ad0338c6efd66e62f28fb9f403e30c6c7 | 87650335d8a9cfe7d4612592180d3d22de8f3dcb | refs/heads/master | 2021-08-30T07:36:26.281667 | 2017-12-16T19:18:09 | 2017-12-16T19:18:09 | 112,149,976 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 437 | h | #ifndef SYSTEMRACK_H
#define SYSTEMRACK_H
#include <QMainWindow>
#include <QVBoxLayout>
#include <QGroupBox>
#include <QScrollArea>
#include <QPalette>
#include "rackwidget.h"
namespace Ui {
class SystemRack;
}
class SystemRack : public QMainWindow
{
Q_OBJECT
public:
explicit SystemRack(QWidget *parent = 0);
~SystemRack();
private:
Ui::SystemRack *ui;
RackWidget *createRack();
};
#endif // SYSTEMRACK_H
| [
"aalshehri08@hotmail.com"
] | aalshehri08@hotmail.com |
b16ffc1511e7aa042751b93460248b7da7e5ebb3 | ba20f31f54af0bce4a3bbf507e5d5e782bb862fa | /src/chainparams.cpp | ce04844cacc4876910db329b27f1c01fc373ac8e | [
"MIT"
] | permissive | ruevers/Tecax | fdd4b231a518d313a1e200f636cff8ef58ded050 | f1b738a12b9d0c8e3159407533cd335d2cc2ae04 | refs/heads/master | 2020-03-19T18:25:20.194283 | 2018-03-25T08:08:09 | 2018-03-25T08:08:09 | 136,808,532 | 0 | 0 | null | 2018-06-10T12:51:04 | 2018-06-10T12:51:04 | null | UTF-8 | C++ | false | false | 22,182 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Tecax Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparams.h"
#include "consensus/merkle.h"
#include "tinyformat.h"
#include "util.h"
#include "utilstrencodings.h"
#include <assert.h>
#include <boost/assign/list_of.hpp>
#include "chainparamsseeds.h"
static CBlock CreateGenesisBlock(const char* pszTimestamp, const CScript& genesisOutputScript, uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward)
{
CMutableTransaction txNew;
txNew.nVersion = 1;
txNew.vin.resize(1);
txNew.vout.resize(1);
txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << std::vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
txNew.vout[0].nValue = genesisReward;
txNew.vout[0].scriptPubKey = genesisOutputScript;
CBlock genesis;
genesis.nTime = nTime;
genesis.nBits = nBits;
genesis.nNonce = nNonce;
genesis.nVersion = nVersion;
genesis.vtx.push_back(txNew);
genesis.hashPrevBlock.SetNull();
genesis.hashMerkleRoot = BlockMerkleRoot(genesis);
return genesis;
}
/**
* Build the genesis block. Note that the output of its generation
* transaction cannot be spent since it did not originally exist in the
* database.
*
* CBlock(hash=00000ffd590b14, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=e0028e, nTime=1390095618, nBits=1e0ffff0, nNonce=28917698, vtx=1)
* CTransaction(hash=e0028e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
* CTxIn(COutPoint(000000, -1), coinbase 04ffff001d01044c5957697265642030392f4a616e2f3230313420546865204772616e64204578706572696d656e7420476f6573204c6976653a204f76657273746f636b2e636f6d204973204e6f7720416363657074696e6720426974636f696e73)
* CTxOut(nValue=50.00000000, scriptPubKey=0xA9037BAC7050C479B121CF)
* vMerkleTree: e0028e
*/
static CBlock CreateGenesisBlock(uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward)
{
const char* pszTimestamp = "NASA confirms DNA change";
const CScript genesisOutputScript = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
return CreateGenesisBlock(pszTimestamp, genesisOutputScript, nTime, nNonce, nBits, nVersion, genesisReward);
}
/**
* Main network
*/
/**
* What makes a good checkpoint block?
* + Is surrounded by blocks with reasonable timestamps
* (no blocks before with a timestamp after, none after with
* timestamp before)
* + Contains no strange transactions
*/
class CMainParams : public CChainParams {
public:
CMainParams() {
strNetworkID = "main";
consensus.nSubsidyHalvingInterval = 525600; // Note: actual number of blocks per calendar year with DGW v3 is ~200700 (for example 449750 - 249050)
consensus.nMasternodePaymentsStartBlock = 100; // not true, but it's ok as long as it's less then nMasternodePaymentsIncreaseBlock
consensus.nMasternodePaymentsIncreaseBlock = 158000; // actual historical value
consensus.nMasternodePaymentsIncreasePeriod = 576*30; // 17280 - actual historical value
consensus.nInstantSendKeepLock = 24;
consensus.nBudgetPaymentsStartBlock = 1000; // actual historical value
consensus.nBudgetPaymentsCycleBlocks = 43200; // ~(60*24*30)/2.6, actual number of blocks per month is 200700 / 12 = 16725
consensus.nBudgetPaymentsWindowBlocks = 100;
consensus.nBudgetProposalEstablishingTime = 60 * 60 * 24;
consensus.nSuperblockStartBlock = 614820; // The block at which 12.1 goes live (end of final 12.0 budget cycle)
consensus.nSuperblockCycle = 16616; // ~(60*24*30)/2.6, actual number of blocks per month is 200700 / 12 = 16725
consensus.nGovernanceMinQuorum = 10;
consensus.nGovernanceFilterElements = 20000;
consensus.nMasternodeMinimumConfirmations = 15;
consensus.nMajorityEnforceBlockUpgrade = 750;
consensus.nMajorityRejectBlockOutdated = 950;
consensus.nMajorityWindow = 1000;
consensus.BIP34Height = 1;
consensus.BIP34Hash = uint256S("0x001");
consensus.powLimit = uint256S("00000fffff000000000000000000000000000000000000000000000000000000");
consensus.nPowTargetTimespan = 60 * 60; // Tecax: 1 day
consensus.nPowTargetSpacing = 1 * 60; // Tecax: 1 minutes
consensus.fPowAllowMinDifficultyBlocks = false;
consensus.fPowNoRetargeting = false;
consensus.nRuleChangeActivationThreshold = 1916; // 95% of 2016
consensus.nMinerConfirmationWindow = 2016; // nPowTargetTimespan / nPowTargetSpacing
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; // January 1, 2008
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; // December 31, 2008
// Deployment of BIP68, BIP112, and BIP113.
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0;
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 1486252800; // Feb 5th, 2017
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 1517788800; // Feb 5th, 2018
// Deployment of DIP0001
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].bit = 1;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].nStartTime = 1508025600; // Oct 15th, 2017
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].nTimeout = 1539561600; // Oct 15th, 2018
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].nWindowSize = 4032;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].nThreshold = 3226; // 80% of 4032
// The best chain should have at least this much work.
consensus.nMinimumChainWork = uint256S("0x0000000000000000000000000000000000000000000000000000000000b000b0"); // 10
// By default assume that the signatures in ancestors of this block are valid.
consensus.defaultAssumeValid = uint256S("0x0000045607b2420ed3a47e3869673cc6b19df00a142a29d144f2218fe7bcb9be"); // 10
/**
* The message start string is designed to be unlikely to occur in normal data.
* The characters are rarely used upper ASCII, not valid as UTF-8, and produce
* a large 32-bit integer with any alignment.
*/
pchMessageStart[0] = 0x73;
pchMessageStart[1] = 0x1a;
pchMessageStart[2] = 0x1e;
pchMessageStart[3] = 0x3e;
vAlertPubKey = ParseHex("045e714c0958459a3ce9ea9040542c801c92c39afbd9875731a3d94f22a812a2041481f4c4b9f59ff1781c553085eaf772ed536a8cbeea1519059fdc97dfe5ad3d");
nDefaultPort = 6347;
nMaxTipAge = 6 * 60 * 60; // ~144 blocks behind -> 2 x fork detection time, was 24 * 60 * 60 in bitcoin
nDelayGetHeadersTime = 24 * 60 * 60;
nPruneAfterHeight = 100000;
genesis = CreateGenesisBlock(1521207896, 3477342, 0x1e0ffff0, 1, 50 * COIN);
consensus.hashGenesisBlock = genesis.GetHash();
assert(consensus.hashGenesisBlock == uint256S("0x00000abc8b35c77237a26e49937c6b2ddc4884aa21c53752a731e88bd4d967b5"));
assert(genesis.hashMerkleRoot == uint256S("0xfddf55f85bae19fd129362e268310e3bd034abb1bb21f6d24c2f826bcf56f8cb"));
//vFixedSeeds.clear();
//vSeeds.clear();
vSeeds.push_back(CDNSSeedData("tecaxcrypto.com", "dnsseed.tecaxcrypto.com"));
// Tecax addresses start with 'S'
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,65);
// Tecax script addresses start with '7'
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,16);
// Tecax private keys start with '7' or 'X'
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,15);
// Tecax BIP32 pubkeys start with 'xpub' (Bitcoin defaults)
base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container<std::vector<unsigned char> >();
// Tecax BIP32 prvkeys start with 'xprv' (Bitcoin defaults)
base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container<std::vector<unsigned char> >();
// Tecax BIP44 coin type is '5'
nExtCoinType = 5;
vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_main, pnSeed6_main + ARRAYLEN(pnSeed6_main));
fMiningRequiresPeers = true;
fDefaultConsistencyChecks = false;
fRequireStandard = true;
fMineBlocksOnDemand = false;
fTestnetToBeDeprecatedFieldRPC = false;
nPoolMaxTransactions = 3;
nFulfilledRequestExpireTime = 1 * 60 * 60; // fulfilled requests expire in 1 hour
strSporkPubKey = "045d58bbcdcac30c0463230a277acc05e7ea2a323d2db468031ab6ff00b154540f06b40d5d3b1dfc623fff5068b49b491404ff5d06af179ddd75cd484b138c3787";
checkpointData = (CCheckpointData) {
boost::assign::map_list_of
( 0, uint256S("0x00000abc8b35c77237a26e49937c6b2ddc4884aa21c53752a731e88bd4d967b5"))
( 1, uint256S("0x000006e25d4d0dcdeb6deaae90869c1562e3c1627cb7e70232d5118b34ed0a48"))
( 105, uint256S("0x0000070f95ed6938ce98a5578e07600a66e4855cac4a82959e8a5e0aa1baca48")),
1521296280, // * UNIX timestamp of last checkpoint block
105, // * total number of transactions between genesis and last checkpoint
// (the tx=... number in the SetBestChain debug.log lines)
2800 // * estimated number of transactions per day after checkpoint
};
}
};
static CMainParams mainParams;
/**
* Testnet (v3)
*/
class CTestNetParams : public CChainParams {
public:
CTestNetParams() {
strNetworkID = "test";
consensus.nSubsidyHalvingInterval = 210240;
consensus.nMasternodePaymentsStartBlock = 4010; // not true, but it's ok as long as it's less then nMasternodePaymentsIncreaseBlock
consensus.nMasternodePaymentsIncreaseBlock = 4030;
consensus.nMasternodePaymentsIncreasePeriod = 10;
consensus.nInstantSendKeepLock = 6;
consensus.nBudgetPaymentsStartBlock = 4100;
consensus.nBudgetPaymentsCycleBlocks = 50;
consensus.nBudgetPaymentsWindowBlocks = 10;
consensus.nBudgetProposalEstablishingTime = 60 * 20;
consensus.nSuperblockStartBlock = 4200; // NOTE: Should satisfy nSuperblockStartBlock > nBudgetPeymentsStartBlock
consensus.nSuperblockCycle = 24; // Superblocks can be issued hourly on testnet
consensus.nGovernanceMinQuorum = 1;
consensus.nGovernanceFilterElements = 500;
consensus.nMasternodeMinimumConfirmations = 1;
consensus.nMajorityEnforceBlockUpgrade = 51;
consensus.nMajorityRejectBlockOutdated = 75;
consensus.nMajorityWindow = 100;
consensus.BIP34Height = 1;
consensus.BIP34Hash = uint256S("0x001");
consensus.powLimit = uint256S("00000fffff000000000000000000000000000000000000000000000000000000");
consensus.nPowTargetTimespan = 24 * 60 * 60; // Tecax: 1 day
consensus.nPowTargetSpacing = 2.5 * 60; // Tecax: 2.5 minutes
consensus.fPowAllowMinDifficultyBlocks = true;
consensus.fPowNoRetargeting = false;
consensus.nRuleChangeActivationThreshold = 1512; // 75% for testchains
consensus.nMinerConfirmationWindow = 2016; // nPowTargetTimespan / nPowTargetSpacing
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; // January 1, 2008
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; // December 31, 2008
// Deployment of BIP68, BIP112, and BIP113.
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0;
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 1506556800; // September 28th, 2017
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 1538092800; // September 28th, 2018
// Deployment of DIP0001
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].bit = 1;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].nStartTime = 1505692800; // Sep 18th, 2017
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].nTimeout = 1537228800; // Sep 18th, 2018
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].nWindowSize = 100;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].nThreshold = 50; // 50% of 100
// The best chain should have at least this much work.
consensus.nMinimumChainWork = uint256S("0x00000000000000000000000000000000000000000000000000000003cd72a542"); //4000
// By default assume that the signatures in ancestors of this block are valid.
consensus.defaultAssumeValid = uint256S("0x00000ce22113f3eb8636e225d6a1691e132fdd587aed993e1bc9b07a0235eea4"); //4000
pchMessageStart[0] = 0x29;
pchMessageStart[1] = 0x7c;
pchMessageStart[2] = 0x21;
pchMessageStart[3] = 0x20;
vAlertPubKey = ParseHex("044818a8163fd2d10960fb1cbfdcd4a7c2eb12142c2d38a9ecc24d76e8218796ca99ba3d2272f8fd3a857749f3288437a8b3ac1a994bb54ee6a700e0e039244137");
nDefaultPort = 19992;
nMaxTipAge = 0x7fffffff; // allow mining on top of old blocks for testnet
nDelayGetHeadersTime = 24 * 60 * 60;
nPruneAfterHeight = 1000;
genesis = CreateGenesisBlock(1521207896, 3477342, 0x1e0ffff0, 1, 50 * COIN);
consensus.hashGenesisBlock = genesis.GetHash();
assert(consensus.hashGenesisBlock == uint256S("0x00000abc8b35c77237a26e49937c6b2ddc4884aa21c53752a731e88bd4d967b5"));
assert(genesis.hashMerkleRoot == uint256S("0xfddf55f85bae19fd129362e268310e3bd034abb1bb21f6d24c2f826bcf56f8cb"));
vFixedSeeds.clear();
vSeeds.clear();
vSeeds.push_back(CDNSSeedData("test.tecaxcrypto.com", "testnet.tecaxcrypto.com"));
// Testnet Tecax addresses start with 'y'
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,140);
// Testnet Tecax script addresses start with '8' or '9'
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,19);
// Testnet private keys start with '9' or 'c' (Bitcoin defaults)
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,239);
// Testnet Tecax BIP32 pubkeys start with 'tpub' (Bitcoin defaults)
base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >();
// Testnet Tecax BIP32 prvkeys start with 'tprv' (Bitcoin defaults)
base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >();
// Testnet Tecax BIP44 coin type is '1' (All coin's testnet default)
nExtCoinType = 1;
vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_test, pnSeed6_test + ARRAYLEN(pnSeed6_test));
fMiningRequiresPeers = true;
fDefaultConsistencyChecks = false;
fRequireStandard = false;
fMineBlocksOnDemand = false;
fTestnetToBeDeprecatedFieldRPC = true;
nPoolMaxTransactions = 3;
nFulfilledRequestExpireTime = 5 * 60; // fulfilled requests expire in 5 minutes
strSporkPubKey = "0497de3baba74a72532625504d20920fbc5190bdf9a9c1922b6eddfb2040bab3fb1ab28fc23c940909b5cc4df92dd637fbfa101126d586958f6b26fbe81ddbc516";
checkpointData = (CCheckpointData) {
boost::assign::map_list_of
( 0, uint256S("0x00000abc8b35c77237a26e49937c6b2ddc4884aa21c53752a731e88bd4d967b5")),
1521207896, // * UNIX timestamp of last checkpoint block
0, // * total number of transactions between genesis and last checkpoint
// (the tx=... number in the SetBestChain debug.log lines)
500 // * estimated number of transactions per day after checkpoint
};
}
};
static CTestNetParams testNetParams;
/**
* Regression test
*/
class CRegTestParams : public CChainParams {
public:
CRegTestParams() {
strNetworkID = "regtest";
consensus.nSubsidyHalvingInterval = 150;
consensus.nMasternodePaymentsStartBlock = 240;
consensus.nMasternodePaymentsIncreaseBlock = 350;
consensus.nMasternodePaymentsIncreasePeriod = 10;
consensus.nInstantSendKeepLock = 6;
consensus.nBudgetPaymentsStartBlock = 1000;
consensus.nBudgetPaymentsCycleBlocks = 50;
consensus.nBudgetPaymentsWindowBlocks = 10;
consensus.nBudgetProposalEstablishingTime = 60*20;
consensus.nSuperblockStartBlock = 1500;
consensus.nSuperblockCycle = 10;
consensus.nGovernanceMinQuorum = 1;
consensus.nGovernanceFilterElements = 100;
consensus.nMasternodeMinimumConfirmations = 1;
consensus.nMajorityEnforceBlockUpgrade = 750;
consensus.nMajorityRejectBlockOutdated = 950;
consensus.nMajorityWindow = 1000;
consensus.BIP34Height = -1; // BIP34 has not necessarily activated on regtest
consensus.BIP34Hash = uint256();
consensus.powLimit = uint256S("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
consensus.nPowTargetTimespan = 24 * 60 * 60; // Tecax: 1 day
consensus.nPowTargetSpacing = 2.5 * 60; // Tecax: 2.5 minutes
consensus.fPowAllowMinDifficultyBlocks = true;
consensus.fPowNoRetargeting = true;
consensus.nRuleChangeActivationThreshold = 108; // 75% for testchains
consensus.nMinerConfirmationWindow = 144; // Faster than normal for regtest (144 instead of 2016)
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 0;
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 999999999999ULL;
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0;
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 0;
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 999999999999ULL;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].bit = 1;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].nStartTime = 0;
consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].nTimeout = 999999999999ULL;
// The best chain should have at least this much work.
consensus.nMinimumChainWork = uint256S("0");
// By default assume that the signatures in ancestors of this block are valid.
consensus.defaultAssumeValid = uint256S("0");
pchMessageStart[0] = 0xeb;
pchMessageStart[1] = 0xa2;
pchMessageStart[2] = 0xf2;
pchMessageStart[3] = 0xae;
nMaxTipAge = 6 * 60 * 60; // ~144 blocks behind -> 2 x fork detection time, was 24 * 60 * 60 in bitcoin
nDelayGetHeadersTime = 0; // never delay GETHEADERS in regtests
nDefaultPort = 19987;
nPruneAfterHeight = 1000;
genesis = CreateGenesisBlock(1521207896, 3477342, 0x1e0ffff0, 1, 50 * COIN);
consensus.hashGenesisBlock = genesis.GetHash();
assert(consensus.hashGenesisBlock == uint256S("0x00000abc8b35c77237a26e49937c6b2ddc4884aa21c53752a731e88bd4d967b5"));
assert(genesis.hashMerkleRoot == uint256S("0xfddf55f85bae19fd129362e268310e3bd034abb1bb21f6d24c2f826bcf56f8cb"));
vFixedSeeds.clear(); //! Regtest mode doesn't have any fixed seeds.
vSeeds.clear(); //! Regtest mode doesn't have any DNS seeds.
fMiningRequiresPeers = false;
fDefaultConsistencyChecks = true;
fRequireStandard = false;
fMineBlocksOnDemand = true;
fTestnetToBeDeprecatedFieldRPC = false;
nFulfilledRequestExpireTime = 5 * 60; // fulfilled requests expire in 5 minutes
checkpointData = (CCheckpointData){
boost::assign::map_list_of
( 0, uint256S("0x00000abc8b35c77237a26e49937c6b2ddc4884aa21c53752a731e88bd4d967b5")),
1521207896,
0,
0
};
// Regtest Tecax addresses start with 'y'
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,140);
// Regtest Tecax script addresses start with '8' or '9'
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,19);
// Regtest private keys start with '9' or 'c' (Bitcoin defaults)
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,239);
// Regtest Tecax BIP32 pubkeys start with 'tpub' (Bitcoin defaults)
base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >();
// Regtest Tecax BIP32 prvkeys start with 'tprv' (Bitcoin defaults)
base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >();
// Regtest Tecax BIP44 coin type is '1' (All coin's testnet default)
nExtCoinType = 1;
}
};
static CRegTestParams regTestParams;
static CChainParams *pCurrentParams = 0;
const CChainParams &Params() {
assert(pCurrentParams);
return *pCurrentParams;
}
CChainParams& Params(const std::string& chain)
{
if (chain == CBaseChainParams::MAIN)
return mainParams;
else if (chain == CBaseChainParams::TESTNET)
return testNetParams;
else if (chain == CBaseChainParams::REGTEST)
return regTestParams;
else
throw std::runtime_error(strprintf("%s: Unknown chain %s.", __func__, chain));
}
void SelectParams(const std::string& network)
{
SelectBaseParams(network);
pCurrentParams = &Params(network);
}
| [
"tecaxproject@gmail.com"
] | tecaxproject@gmail.com |
a20348d36693c0c852433359f6d464fd8e99d49c | aeac025c3c39744d5e35df4b05e017c6846cedb0 | /C++ Primer/第3章练习/3.5.cpp | 884246e2114109424c4b1464068cdb644d61b598 | [] | no_license | Rookie35/C-plus-plus-practice | 8d774a5b551f6adefb8ca8a89503575e56d9622d | bd30c9861090479b9b62aa1905ee7d531d675220 | refs/heads/master | 2020-05-01T09:26:09.636329 | 2019-04-14T12:12:55 | 2019-04-14T12:12:55 | 177,400,130 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 388 | cpp | /*
*
*/
/*
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str;
string sumstr;
while(getline(cin,str))
{
sumstr+=str;
cout<<sumstr<<endl;
}
return 0;
}
*/
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str;
string sumstr;
while(getline(cin,str))
{
sumstr=sumstr+str+" ";
cout<<sumstr<<endl;
}
return 0;
}
| [
"754119201@qq.com"
] | 754119201@qq.com |
e7030c83364c76991ad2a9683ff6e17979c0f0d2 | 81f6c6eac9ee2c5165ac4123a6b1ec5e8157e4fa | /dz na 11/dz na 11/dz11.cpp | 683eae790e803b91304c113d879640642844bcd9 | [] | no_license | ArtemiyMaslov1/DZ_NA_11 | 6adfeb4dd02d9507814650796f45fcc7324722ab | 6db6e337f930fd7797c8e4a9fe6c1c0e1fc247d7 | refs/heads/main | 2023-08-01T12:51:35.552444 | 2021-09-10T12:05:06 | 2021-09-10T12:05:06 | 405,065,301 | 0 | 0 | null | null | null | null | MacCyrillic | C++ | false | false | 1,599 | cpp | #include <iostream>
using namespace std;
int main()
{
setlocale(LC_ALL, "Rus");
int tovar;
cout << "¬ведите число товаров ";
cin >> tovar;
//проверка
if (tovar > 1000)
{
cout << "ќшибка!!! ¬ведите число меньше 1000\n";
while (tovar > 1000)
{
cout << "¬ведите число товаров ";
cin >> tovar;
}
}
//создание и заполнение массива
int* array = new int[tovar];
for (int i = 0; i < tovar; i++)
{
cout << "¬ведите цену " << i + 1 << " - ого товара ";
cin >> array[i];
}
//вывод массива
for (int i = 0; i < tovar; i++)
{
cout << array[i] << " ";
}
//сортировка массива
for (int i = 1; i < tovar; i++)
{
int a = array[i];
int j = i - 1;
while (j >= 0 && array[j] < a)
{
array[j + 1] = array[j];
array[j] = a;
j--;
}
}
cout << "\n";
//растановка чисел больш. меньш. больш. ...
int* arraysort = new int[tovar];
int f = 0;
for (int i = 0; i < tovar; i++,f++)
{
arraysort[i] = array[i/2];
for (int j = 0; j < 1; j++)
{
arraysort[i+1] = array[tovar - 1 - f];
}
i += 1;
}
//суммирование
int sum = 0;
for (int i = 0; i < tovar; i++)
{
if (i % 2 == 0)
{
sum += arraysort[i];
}
}
//вывод
for (int i = 0; i < tovar; i++)
{
cout << arraysort[i] << " ";
}
cout << "\n";
cout << "—умма покупки: " << sum;
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
75c1ac9d575f9cb2e1712b9922c27a7afb26ded6 | f710700465ee92a0f091e7a4f4a8ac31d8961963 | /WS01/in_lab/seneGraph.cpp | 384ca0357714730a624a623055454df1225b3d4a | [] | no_license | LiChingCheng/OOP244 | 8dd30823dc3c0aa02498cd99c31b202ddcd439f2 | e49b2fe0ebd40e8fa0c6cf628d9186d894669695 | refs/heads/master | 2023-01-08T07:10:04.578882 | 2020-11-06T21:55:58 | 2020-11-06T21:55:58 | 310,713,220 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,120 | cpp | /*
Name: Cheng, Li-Ching
Student number: 143292175
Email: lcheng49@myseneca.ca
Section: SAB
*/
#include <iostream>
#include "graph.h"
#include "tools.h"
using namespace std;
using namespace sict;
// SeneGraph program
int main() {
int noOfSamples = 0;
int samples[MAX_NO_OF_SAMPLES] = { 0 };
bool done = false;
cout << "Welcome to SeneGraph" << endl;
while (!done) {
cout << "No Of Samples: " << noOfSamples << endl;
switch (menu()) {
case 1:
cout << "Enter number of samples on hand: ";
noOfSamples = getInt(1, MAX_NO_OF_SAMPLES);
break;
case 2:
if (noOfSamples == 0) {
cout << "First enter the number of Samples." << endl;
}
else {
cout << "Please enter the sample values: " << endl;
getSamples(samples, noOfSamples);
}
break;
case 3:
if (noOfSamples == 0) {
cout << "First enter the number of Samples." << endl;
}
else if (samples[0] == 0) {
cout << "Firt enter the samples." << endl;
}
else {
printGraph(samples, noOfSamples);
}
break;
case 0:
cout << "Thanks for using SeneGraph" << endl;
done = true;
}
}
return 0;
}
| [
"hyalinelove1991@gmail.com"
] | hyalinelove1991@gmail.com |
2a4616aa6ee6e7513e0afb76d34a6fe07bf4966a | 4ef69f0044f45be4fbce54f7b7c0319e4c5ec53d | /include/cv/core/cmd/out/zlaqr4.inl | 670cbb31bf367015f5e09193cf08d08d0a200806 | [] | no_license | 15831944/cstd | c6c3996103953ceda7c06625ee1045127bf79ee8 | 53b7e5ba73cbdc9b5bbc61094a09bf3d5957f373 | refs/heads/master | 2021-09-15T13:44:37.937208 | 2018-06-02T10:14:16 | 2018-06-02T10:14:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 436 | inl | #ifndef __zlaqr4__
#define __zlaqr4__
#define c__13 c__13_zlaqr4
#define c__15 c__15_zlaqr4
#define c_n1 c_n1_zlaqr4
#define c__12 c__12_zlaqr4
#define c__14 c__14_zlaqr4
#define c__16 c__16_zlaqr4
#define c_false c_false_zlaqr4
#define c__1 c__1_zlaqr4
#define c__3 c__3_zlaqr4
#include "zlaqr4.c"
#undef c__13
#undef c__15
#undef c_n1
#undef c__12
#undef c__14
#undef c__16
#undef c_false
#undef c__1
#undef c__3
#endif // __zlaqr4__
| [
"31720406@qq.com"
] | 31720406@qq.com |
4c236245604bd4aeae6a7986a7ea15c38d3fb016 | 8380b5eb12e24692e97480bfa8939a199d067bce | /Carberp Botnet/source - absource/pro/all source/BJWJ/source/Misc/FakeDllInstaller.cpp | b10c139201b79f784bb843f1079bc97da49e350c | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | RamadhanAmizudin/malware | 788ee745b5bb23b980005c2af08f6cb8763981c2 | 62d0035db6bc9aa279b7c60250d439825ae65e41 | refs/heads/master | 2023-02-05T13:37:18.909646 | 2023-01-26T08:43:18 | 2023-01-26T08:43:18 | 53,407,812 | 873 | 291 | null | 2023-01-26T08:43:19 | 2016-03-08T11:44:21 | C++ | WINDOWS-1251 | C++ | false | false | 24,460 | cpp | //---------------------------------------------------------------------------
#include "Modules.h"
#ifdef FakeDllInstallerH
//=============================================================================
#include <windows.h>
#include <shlobj.h>
#include "BotCore.h"
#include "Loader.h"
#include "Utils.h"
#include "Task.h"
#include "StrConsts.h"
#include "FakeDllInstaller.h"
#include "BotDebug.h"
namespace FKI_DEBUGER
{
#include "DbgTemplates.h"
}
#define FKIDBG FKI_DEBUGER::DBGOutMessage<>
//-----------------------------------------------------------
// Массив ссылок исомых анализатором истории навигации
// Строки должны быть разделены нулевым символом и
// завершаться пустой строкой
//-----------------------------------------------------------
#ifndef DEBUGCONFIG
// Рабочий массив
char HISANALIZER_LINKS[BOTPARAM_SIZE_HISANALIZERLINKS] = BOTPARAM_HISANALIZERLINKS;
#else
// Для отладки
char HISANALIZER_LINKS[] = "yandex\0mail.ru\0bsi.dll\0\0";
#endif
//-----------------------------------------------------------
/*
const PCHAR HisFileItem = "file:";
const DWORD MaxSearchFromConfigFileseTime = 10*60*1009;
//---------------------------------------------------------------------------
bool CompareSites(PStrings S, PCHAR Site)
{
// Сравнивает сайты из списка S с сайтом Site
DWORD Count = Strings::Count(S);
PCHAR Line;
for (DWORD i = 0; i < Count; i++)
{
Line = Strings::GetItem(S, i, false);
if (STR::Pos(Site, Line) >= 0)
return true;
}
return false;
}
//---------------------------------------------------------------------------
bool FindItem(PCHAR Buffer, PCHAR Site, DWORD BufSize)
{
if (Buffer == NULL || Site == NULL || BufSize == 0)
return false;
DWORD SiteLen = StrCalcLength(Site);
DWORD Max = BufSize - SiteLen;
PCHAR TMP = Buffer;
for (DWORD i = 0; i < Max; i++)
{
if (StrSame(TMP, Site, true, SiteLen))
return true;
TMP++;
}
return false;
}
bool ReadIEHistoryFile(PCHAR FileName, PStrings S)
{
PCHAR FileCopy = STR::New(2, FileName, "_copy");
if (FileCopy == NULL)
return false;
bool Result = false;
// Копируем файл
pCopyFileA(FileName, FileCopy, FALSE);
// Читаем файл в буффер
HANDLE File = (HANDLE)pCreateFileA(FileCopy,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (File != INVALID_HANDLE_VALUE)
{
DWORD H = 0;
DWORD FileSize = (DWORD)pGetFileSize(File, &H);
if (FileSize > 0)
{
// Мапируем файл в память
HANDLE MapFile = (HANDLE)pCreateFileMappingW(File, 0, PAGE_READONLY, 0, FileSize, 0 );
if (MapFile != INVALID_HANDLE_VALUE)
{
PCHAR Buffer = (PCHAR)pMapViewOfFile(MapFile, FILE_MAP_READ, 0, 0, 0 );
// Ищем совпадения
DWORD Count = Strings::Count(S);
PCHAR Line;
for (DWORD i = 0; i < Count; i++)
{
Line = Strings::GetItem(S, i, false);
if (FindItem(Buffer, Line, FileSize))
{
Result = true;
break;
}
}
pUnmapViewOfFile(Buffer);
pCloseHandle(MapFile);
}
}
}
pCloseHandle(File);
pDeleteFileA(FileCopy);
return Result;
}
void SearchIEHistoryCallBack(PFindData Find, PCHAR FileName, LPVOID Data, bool &Cancel)
{
// Функйия обратной связи поиска файлов и директории
PHistoryConfig Config = (PHistoryConfig)Data;
if (ReadIEHistoryFile(FileName, Config->Sites))
{
Cancel = true;
Config->ContainsURL = true;
}
}
bool SearchInIEHistory(PHistoryConfig Config)
{
// Ищем совпадения в кукисахIE
PCHAR Path = STR::Alloc(MAX_PATH);
if (Path == NULL)
return false;
// Определяем путь к директории пользователя
if (!pSHGetSpecialFolderPathA(NULL, Path, CSIDL_HISTORY, FALSE))
{
STR::Free(Path);
return false;
}
// Ищем файлы
StrConcat(Path, "\\");
SearchFiles(Path, "*.dat", true, FA_ANY_FILES, Config, SearchIEHistoryCallBack);
//
STR::Free(Path);
return Config->ContainsURL;
}
//---------------------------------------------------------------------------
void SearchCallBack(PFindData Find, PCHAR FileName, LPVOID Data, bool &Cancel)
{
// Функйия обратной связи поиска файлов и директории
PHistoryConfig Config = (PHistoryConfig)Data;
if (CompareSites(Config->Sites, Find->cFileName))
{
Cancel = true;
Config->ContainsURL = true;
}
}
//---------------------------------------------------------------------------
bool SearchInIECookies(PHistoryConfig Config)
{
// Ищем совпадения в кукисахIE
PCHAR Path = STR::Alloc(MAX_PATH);
if (Path == NULL)
return false;
// Определяем путь к директории пользователя
if (!pSHGetSpecialFolderPathA(NULL, Path, CSIDL_COOKIES, FALSE))
{
STR::Free(Path);
return false;
}
// Ищем файлы
StrConcat(Path, "\\");
SearchFiles(Path, "*.txt", false, FA_ANY_FILES, Config, SearchCallBack);
//
STR::Free(Path);
return Config->ContainsURL;
}
//---------------------------------------------------------------------------
bool SearchFlashPlayerCookies(PHistoryConfig Config)
{
// Ищем совпадения в кукисахIE
PCHAR Path = STR::Alloc(MAX_PATH);
if (Path == NULL)
return false;
// Определяем путь к директории пользователя
if (!pSHGetSpecialFolderPathA(NULL, Path, CSIDL_APPDATA, FALSE))
{
STR::Free(Path);
return false;
}
// Ищем файлы
SearchFiles(Path, "*.*", true, FA_DIRECTORY, Config, SearchCallBack);
//
STR::Free(Path);
return Config->ContainsURL;
}
//---------------------------------------------------------------------------
// HisUtils - Вспомогательнве утилиты анализатора истории
//---------------------------------------------------------------------------
namespace HisUtils
{
//------------------------------------------------------------------------
void ExtractFileItems(PHistoryConfig Config)
{
// изылечь элементы поиска файлов из списка ссылок
if (Config == NULL || Config->Sites == NULL) return;
PCHAR S;
PCHAR FileName;
DWORD Len = StrCalcLength(HisFileItem);
DWORD i = 0;
while (i < Strings::Count(Config->Sites))
{
S = Strings::GetItem(Config->Sites, i, false);
// проверяем начинается ли элемент с префикса элемента файла
if (!StrSame(S, HisFileItem, false, Len))
{
// Элемент не является файлом, игнорируем его
i++;
continue;
}
// Элемент является файлом, извлекаем имя файла
FileName = STR::IgnoreSpaces(S + Len);
if (!STR::IsEmpty(FileName))
{
if (Config->Files == NULL)
Config->Files = Strings::Create();
Strings::Add(Config->Files, FileName);
}
Strings::Delete(Config->Sites, i);
}
}
//------------------------------------------------------------------------
// Структура поиска файлов из конфига
typedef struct TFileSearch
{
// Стандартные пути поиска
PCHAR ProgramFiles;
PCHAR Windows;
PStrings AllPaths;
DWORD StartTime;
DWORD MaxSearch;
bool TimeCompleted;
bool Finded;
} *PFileSearch;
//------------------------------------------------------------------------
PCHAR GetSpecPath(int CSIDL)
{
// Функция возвращает некторый путь
PCHAR Buf = STR::Alloc(MAX_PATH);
PCHAR Result = NULL;
if (pSHGetSpecialFolderPathA(NULL, Buf, CSIDL, FALSE))
{
Result = STR::New(2, Buf, "\\");
}
STR::Free(Buf);
return Result;
}
void InitSearchCallBack(PFindData Search, PCHAR FileName, LPVOID Data, bool &Cancel)
{
// Директория найдена, добавляем её в список
PFileSearch S = (PFileSearch)Data;
Strings::Add(S->AllPaths, FileName);
}
PFileSearch StartSearch()
{
// Функция инициализирует поиск файлов
PFileSearch S = CreateStruct(TFileSearch);
S->ProgramFiles = GetSpecPath(CSIDL_PROGRAM_FILES);
S->Windows = GetSpecPath(CSIDL_WINDOWS);
// Определяем корневые директории системмного диска
S->AllPaths = Strings::Create();
PCHAR Drive = STR::GetLeftStr(S->Windows, ":\\", true);
SearchFiles(Drive, "*.*", false, FA_DIRECTORY, S, InitSearchCallBack);
STR::Free(Drive);
Strings::Remove(S->AllPaths, S->ProgramFiles);
Strings::Remove(S->AllPaths, S->Windows);
S->MaxSearch = MaxSearchFromConfigFileseTime;
S->StartTime = (DWORD)pGetTickCount();
return S;
}
//------------------------------------------------------------------------
void CloseSearch(PFileSearch S)
{
// Уничтожить данные поиска
if (S == NULL) return;
STR::Free(S->Windows);
STR::Free(S->ProgramFiles);
Strings::Free(S->AllPaths);
FreeStruct(S);
}
//------------------------------------------------------------------------
void UpdateSearchTime(PFileSearch S)
{
if (S->MaxSearch == 0) return;
S->TimeCompleted = ((DWORD)pGetTickCount() - S->StartTime) >= S->MaxSearch;
}
//------------------------------------------------------------------------
void SearchCallBack(PFindData Search, PCHAR FileName, LPVOID Data, bool &Cancel)
{
PFileSearch S = (PFileSearch)Data;
S->Finded = true;
Cancel = true;
}
bool RealSearchFile(PHistoryConfig Config, PFileSearch S, PCHAR Path)
{
// Функция ищет файл по маске Mask по пути Path
if (S->Finded || S->TimeCompleted) return true;
DWORD Count = Strings::Count(Config->Files);
for (DWORD i = 0; i < Count; i++)
{
SearchFiles(Path, Strings::GetItem(Config->Files, i, false), true, FA_ANY_FILES, S, SearchCallBack);
UpdateSearchTime(S);
if (S->Finded || S->TimeCompleted) break;
}
return S->Finded;
}
//------------------------------------------------------------------------
bool SearchFilesFromConfig(PHistoryConfig Config)
{
// Функция ищет файлы указанные в конфигурационном файле
// инициализируем поиск
PFileSearch S = StartSearch();
// Ищем файлы
RealSearchFile(Config, S, S->ProgramFiles);
if (!S->Finded && !S->TimeCompleted)
{
// Ищем файлы во всех директориях системмного диска
for (DWORD i = 0; i < Strings::Count(S->AllPaths); i++)
{
RealSearchFile(Config, S, Strings::GetItem(S->AllPaths, i));
if (S->Finded || S->TimeCompleted) break;
}
}
if (!S->Finded && !S->TimeCompleted)
RealSearchFile(Config, S, S->Windows);
// Закрываем поиск
bool Result = S->Finded;
CloseSearch(S);
return Result;
}
}
//---------------------------------------------------------------------------
bool HisAnalizer::Download(PCHAR URL, PHistoryConfig &Config)
{
// Загрузить конфигурационный файл
Config = NULL;
if (STR::IsEmpty(URL)) return false;
// Загружаем конфиг в файл
LPBYTE Buffer = NULL;
DWORD BufSize = 0;
if (!DownloadInMem(URL, &Buffer, &BufSize))
return false;
// Расшифровываем конфиг
const static char Signature[] = {'B', 'J', 'B', 0};
PCHAR Lines = (PCHAR)XORCrypt::DecodeBuffer((PCHAR)Signature, Buffer, BufSize);
if (Lines == NULL || BufSize == 0)
{
MemFree(Buffer);
return false;
}
// Парсим конфиг
Config = CreateStruct(THistoryConfig);
if (Config == NULL) return false;
bool Result = Parse(Lines, Config);
MemFree(Buffer);
if (!Result)
{
ClearConfig(Config);
FreeStruct(Config);
Config = NULL;
}
return Result;
}
//---------------------------------------------------------------------------
bool HisAnalizer::Parse(PCHAR Lines, PHistoryConfig Config)
{
// Разобрать список строк конфигурационного файла
if (STR::IsEmpty(Lines))
return false;
PStrings S = Strings::Create();
Strings::SetText(S, Lines);
bool Result = false;
// Парсим список
if (Strings::Count(S) > 1)
{
PCHAR Cmd = Strings::GetItem(S, 0);
Strings::Delete(S, 0);
Config->Command1 = STR::GetLeftStr(Cmd, "|");
if (Config->Command1 != NULL)
{
Config->Command2 = STR::GetRightStr(Cmd, "|");
STR::Free(Cmd);
}
else
Config->Command1 = Cmd;
Result = Config->Command1 != NULL;
}
if (Result)
{
// Отделяем сайты от файлов
Config->Sites = S;
HisUtils::ExtractFileItems(Config);
}
else
Strings::Free(S);
return Result;
}
//---------------------------------------------------------------------------
void HisAnalizer::Execute(PHistoryConfig Config)
{
// Выполнить поиск по истории посещения сайтов
// и на этой основе выполнить необходимую команду
if (Config == NULL) return;
bool Contain = SearchInIEHistory(Config) ||
SearchInIECookies(Config) ||
SearchFlashPlayerCookies(Config) ||
HisUtils::SearchFilesFromConfig(Config);
if (Contain)
ExecuteCommand(NULL, Config->Command1, false);
else
ExecuteCommand(NULL, Config->Command2, false);
}
//---------------------------------------------------------------------------
void HisAnalizer::DownloadAndExecute(PCHAR URL)
{
// Загрузить и выполнить команду из конфигурационного файла
PHistoryConfig Config = NULL;
if (Download(URL, Config))
{
Execute(Config);
FreeConfig(Config);
}
}
//---------------------------------------------------------------------------
void HisAnalizer::ClearConfig(PHistoryConfig Config)
{
STR::Free2(Config->Command1);
STR::Free2(Config->Command2);
Strings::Free(Config->Sites);
Strings::Free(Config->Files);
ClearStruct(*Config);
}
//---------------------------------------------------------------------------
void HisAnalizer::FreeConfig(PHistoryConfig Config)
{
// Уничтожить конфиг
if (Config == NULL) return;
ClearConfig(Config);
FreeStruct(Config);
}
//---------------------------------------------------------------------------
DWORD WINAPI AnalyzerThreadProc(LPVOID Data)
{
PCHAR URL = (PCHAR)Data;
HisAnalizer::DownloadAndExecute(URL);
STR::Free(URL);
pExitThread(0);
return 0;
}
void HisAnalizer::StartAnalizerThread(PCHAR URL)
{
if (!STR::IsEmpty(URL))
StartThread(AnalyzerThreadProc, STR::New(URL));
}
*/
//*****************************************************************************
// Методы поиска следов на компьютере с целью проверки необходимости
// установки Fake DLL
//*****************************************************************************
namespace FDI
{
//--------------------------------------------------
// Функция загружает список обрабатываемых ссылок
//--------------------------------------------------
void ReadLinks(TBotStrings &Links)
{
TStrEnum L(HISANALIZER_LINKS,
BOTPARAM_ENCRYPTED_HISANALIZERLINKS,
BOTPARAM_HASH_HISANALIZERLINKS);
while (L.Next())
Links.Add(L.Line());
}
//--------------------------------------------------
struct TSearchData
{
TBotStrings *Links;
bool Contain;
};
void CheckIEHistory(PFindData Find, PCHAR FileName, LPVOID SearchData, bool &Cancel)
{
// Ищем вхождение ссылок в найденном файле истории
TSearchData* Data = (TSearchData*)SearchData;
DWORD Size = 0;
LPBYTE Buf = File::ReadToBufferA(FileName, Size);
if (Buf)
{
int Count = Data->Links->Count();
for (int i = 0; i < Count; i++)
{
string Link = Data->Links->GetItem(i);
int P = STR::Pos((PCHAR)Buf, Link.t_str(), Size, true);
if (P >= 0)
{
Cancel = true;
Data->Contain = true;
FKIDBG("FakeDLLInstaller", "Надена нужная ссылка в истории навигации [%s]", Link.t_str());
break;
}
}
MemFree(Buf);
}
}
//--------------------------------------------------
// Функция ищет совпадения в истории навигации
// Интернет эксплорера
//--------------------------------------------------
bool CheckIEHistory(TBotStrings &Links)
{
if (Links.Count())
{
FKIDBG("FakeDLLInstaller", "Проверяем историю навигации ИЕ");
string Path = GetSpecialFolderPathA(CSIDL_HISTORY, NULL);
if (!Path.IsEmpty())
{
// Перебираем все файлы в директории истории
TSearchData Data;
Data.Links = &Links;
Data.Contain = false;
SearchFiles(Path.t_str(), "*.dat", true, FA_ANY_FILES, &Data, CheckIEHistory);
return Data.Contain;
}
}
return false;
}
//-------------------------------------------------------------------------
bool CheckFileHash(DWORD Hash)
{
// Функция сравнивает хэш имени файла с именами прописанными в массиве
const static DWORD Hashes[] ={0xD61CFB13, /* cbank.exe */
0xFE0E05F6, /* cbmain.ex */
0x702FB20, /* cbmain.ex_ */
0};
int i = 0;
while (Hashes[i])
{
if (Hash == Hashes[i])
return true;
i++;
}
return false;
}
//-------------------------------------------------------------------------
bool SearchProcesses()
{
// Функция проверяет запущенные процессы в поиске нужных
FKIDBG("FakeDLLInstaller", "Проверяем запущенные процессы");
bool Result = false;
LPVOID Buf = GetInfoTable( SystemProcessInformation );
PSYSTEM_PROCESS_INFORMATION pProcess = (PSYSTEM_PROCESS_INFORMATION)Buf;
DWORD dwSessionId = 0;
if (pProcess != NULL)
{
dwSessionId = GetCurrentSessionId();
do
{
if ( dwSessionId == pProcess->uSessionId )
{
if ( pProcess->usName.Length )
{
DWORD ProcessHash = STRW::Hash(pProcess->usName.Buffer, 0, true);
if (CheckFileHash(ProcessHash))
{
FKIDBG("FakeDLLInstaller", "Найден процесс %s", pProcess->usName.Buffer);
Result = true;
break;
}
}
}
pProcess = (PSYSTEM_PROCESS_INFORMATION)((DWORD)pProcess + pProcess->uNext);
} while ( pProcess->uNext != 0 );
}
MemFree(Buf);
return Result;
}
//-------------------------------------------------------------------------
bool IBankInstalled()
{
// Функция проверяет наличие наличие файла или ключей реестра
// сигнализирующих об установленном,
// на машине пользователя IBank
FKIDBG("FakeDLLInstaller", "Проверяем инсталяцию банков");
// Проверяем наличие файла
string FileNameName = GetSpecialFolderPathA(CSIDL_PROFILE, GetStr(EStrIBankFileName));
bool Result = File::IsExists(FileNameName.t_str());
if (!Result)
{
// Проверяем реестр
FKIDBG("FakeDLLInstaller", "Проверяем ключи реестра");
string Tmp = GetStr(EStrSberRegistryKey);
Result = Registry::IsKeyExist(HKEY_LOCAL_MACHINE, GetStr(EStrIBankRegistryPath).t_str()) ||
Registry::IsKeyExist(HKEY_LOCAL_MACHINE, Tmp.t_str()) ||
Registry::IsKeyExist(HKEY_CURRENT_USER, Tmp.t_str());
}
if (Result)
{
FKIDBG("FakeDLLInstaller", "Найдено присутствие ИБанка");
// При включенном фва патчере запускаем установку
#ifdef JAVS_PATCHERHvd
JavaPatcherSignal(NULL);
#endif
}
return Result;
}
//-------------------------------------------------------------------------
void CheckFile(PFindData Find, PCHAR FileName, LPVOID SearchData, bool &Cancel)
{
// Проверяем файл
DWORD Hash = STRA::Hash(Find->cFileName, 0, true);
if (CheckFileHash(Hash))
{
FKIDBG("FakeDLLInstaller", "Найден файл %s", FileName);
Cancel = true;
*((bool*)SearchData) = true;
}
pSleep(1);
}
//-------------------------------------------------------------------------
bool CheckFiles()
{
// Функция ищет вхождение нужных файлов
FKIDBG("FakeDLLInstaller", "Проверяем файлы на диске");
TMemory Path(MAX_PATH);
pGetSystemDirectoryA(Path.AsStr(), MAX_PATH);
PCHAR S = Path.AsStr();
PCHAR End = STRA::Scan(S, '\\');
if (End) *(End + 1) = 0;
bool Result = false;
SearchFiles(S, "*.*", true, FA_ANY_FILES, &Result, CheckFile);
return Result;
}
//--------------------------------------------------
// Функция потока анализа истории навигации
//--------------------------------------------------
DWORD WINAPI DoExecute(LPVOID)
{
// В данны момент в эту часть вставляем проверку
// ключей реестра сигнализирующих об установленном,
// на машине пользователя IBank
FKIDBG("FakeDLLInstaller", "Определяем необхдимость установки FakeDll");
bool Executed = IBankInstalled() ||
SearchProcesses();
// Проверяем историю навигации ие
if (!Executed)
{
TBotStrings Links;
// Читаем ссылки
ReadLinks(Links);
// Анализируем историю навигации
Executed = CheckIEHistory(Links);
}
// Последним этапом ищем файлы на диске
if (!Executed)
Executed = CheckFiles();
// В случае обнаружения вхождений, выполняем команду
if (Executed)
{
Install();
}
return 0;
}
//-------------------------------------------------------------------------
}
//------------------------------------------------------
// Execute - Фуекция запускает анализ истории навигации
//------------------------------------------------------
void FDI::Execute()
{
if (!BOT::FakeDllInstalled())
StartThread(DoExecute, 0);
else
FKIDBG("FakeDLLInstaller", "Fake DLL уже установлена");
}
//------------------------------------------------------
// Функция запускает установку Fake DLL
//------------------------------------------------------
void FDI::Install()
{
FKIDBG("FakeDLLInstaller", "Устанавливаем Fake DLL");
#ifndef AGENTFULLTEST
ExecuteCommand(NULL, GetStr(EStrCommandInstallFakeDLL).t_str(), NULL , false);
#endif
}
//=============================================================================
#endif
| [
"fdiskyou@users.noreply.github.com"
] | fdiskyou@users.noreply.github.com |
8e398b23512f75cec3e9b1c27a112c05c6dce1e1 | 9362ac2be59f1ee986be2f30ac980b565ce87d4b | /libs/pcl/include/pcl-1.6/pcl/segmentation/impl/sac_segmentation.hpp | 27ba77cdd4c7d6e1a48a0e2cdca89e13a01a440c | [] | no_license | ganterd/dissertation | 30028d112625968f807695685ab8a671ef7aad04 | 406e9351f99b48e4b5ba56e572d79f4c0257ea69 | refs/heads/master | 2016-09-11T10:16:03.262257 | 2014-11-14T12:26:51 | 2014-11-14T12:26:51 | 8,930,889 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 23,000 | hpp | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id: sac_segmentation.hpp 6155 2012-07-04 23:10:00Z aichim $
*
*/
#ifndef PCL_SEGMENTATION_IMPL_SAC_SEGMENTATION_H_
#define PCL_SEGMENTATION_IMPL_SAC_SEGMENTATION_H_
#include <pcl/segmentation/sac_segmentation.h>
// Sample Consensus methods
#include <pcl/sample_consensus/sac.h>
#include <pcl/sample_consensus/lmeds.h>
#include <pcl/sample_consensus/mlesac.h>
#include <pcl/sample_consensus/msac.h>
#include <pcl/sample_consensus/ransac.h>
#include <pcl/sample_consensus/rmsac.h>
#include <pcl/sample_consensus/rransac.h>
#include <pcl/sample_consensus/prosac.h>
// Sample Consensus models
#include <pcl/sample_consensus/sac_model.h>
#include <pcl/sample_consensus/sac_model_circle.h>
#include <pcl/sample_consensus/sac_model_cylinder.h>
#include <pcl/sample_consensus/sac_model_cone.h>
#include <pcl/sample_consensus/sac_model_line.h>
#include <pcl/sample_consensus/sac_model_normal_plane.h>
#include <pcl/sample_consensus/sac_model_normal_sphere.h>
#include <pcl/sample_consensus/sac_model_parallel_plane.h>
#include <pcl/sample_consensus/sac_model_normal_parallel_plane.h>
#include <pcl/sample_consensus/sac_model_parallel_line.h>
#include <pcl/sample_consensus/sac_model_perpendicular_plane.h>
#include <pcl/sample_consensus/sac_model_plane.h>
#include <pcl/sample_consensus/sac_model_sphere.h>
#include <pcl/sample_consensus/sac_model_stick.h>
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::SACSegmentation<PointT>::segment (PointIndices &inliers, ModelCoefficients &model_coefficients)
{
// Copy the header information
inliers.header = model_coefficients.header = input_->header;
if (!initCompute ())
{
inliers.indices.clear (); model_coefficients.values.clear ();
return;
}
// Initialize the Sample Consensus model and set its parameters
if (!initSACModel (model_type_))
{
PCL_ERROR ("[pcl::%s::segment] Error initializing the SAC model!\n", getClassName ().c_str ());
deinitCompute ();
inliers.indices.clear (); model_coefficients.values.clear ();
return;
}
// Initialize the Sample Consensus method and set its parameters
initSAC (method_type_);
if (!sac_->computeModel (0))
{
PCL_ERROR ("[pcl::%s::segment] Error segmenting the model! No solution found.\n", getClassName ().c_str ());
deinitCompute ();
inliers.indices.clear (); model_coefficients.values.clear ();
return;
}
// Get the model inliers
sac_->getInliers (inliers.indices);
// Get the model coefficients
Eigen::VectorXf coeff;
sac_->getModelCoefficients (coeff);
// If the user needs optimized coefficients
if (optimize_coefficients_)
{
Eigen::VectorXf coeff_refined;
model_->optimizeModelCoefficients (inliers.indices, coeff, coeff_refined);
model_coefficients.values.resize (coeff_refined.size ());
memcpy (&model_coefficients.values[0], &coeff_refined[0], coeff_refined.size () * sizeof (float));
// Refine inliers
model_->selectWithinDistance (coeff_refined, threshold_, inliers.indices);
}
else
{
model_coefficients.values.resize (coeff.size ());
memcpy (&model_coefficients.values[0], &coeff[0], coeff.size () * sizeof (float));
}
deinitCompute ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> bool
pcl::SACSegmentation<PointT>::initSACModel (const int model_type)
{
if (model_)
model_.reset ();
// Build the model
switch (model_type)
{
case SACMODEL_PLANE:
{
PCL_DEBUG ("[pcl::%s::initSACModel] Using a model of type: SACMODEL_PLANE\n", getClassName ().c_str ());
model_.reset (new SampleConsensusModelPlane<PointT> (input_, *indices_));
break;
}
case SACMODEL_LINE:
{
PCL_DEBUG ("[pcl::%s::initSACModel] Using a model of type: SACMODEL_LINE\n", getClassName ().c_str ());
model_.reset (new SampleConsensusModelLine<PointT> (input_, *indices_));
break;
}
case SACMODEL_STICK:
{
PCL_DEBUG ("[pcl::%s::initSACModel] Using a model of type: SACMODEL_STICK\n", getClassName ().c_str ());
model_.reset (new SampleConsensusModelStick<PointT> (input_, *indices_));
double min_radius, max_radius;
model_->getRadiusLimits (min_radius, max_radius);
if (radius_min_ != min_radius && radius_max_ != max_radius)
{
PCL_DEBUG ("[pcl::%s::initSACModel] Setting radius limits to %f/%f\n", getClassName ().c_str (), radius_min_, radius_max_);
model_->setRadiusLimits (radius_min_, radius_max_);
}
break;
}
case SACMODEL_CIRCLE2D:
{
PCL_DEBUG ("[pcl::%s::initSACModel] Using a model of type: SACMODEL_CIRCLE2D\n", getClassName ().c_str ());
model_.reset (new SampleConsensusModelCircle2D<PointT> (input_, *indices_));
typename SampleConsensusModelCircle2D<PointT>::Ptr model_circle = boost::static_pointer_cast<SampleConsensusModelCircle2D<PointT> > (model_);
double min_radius, max_radius;
model_circle->getRadiusLimits (min_radius, max_radius);
if (radius_min_ != min_radius && radius_max_ != max_radius)
{
PCL_DEBUG ("[pcl::%s::initSACModel] Setting radius limits to %f/%f\n", getClassName ().c_str (), radius_min_, radius_max_);
model_circle->setRadiusLimits (radius_min_, radius_max_);
}
break;
}
case SACMODEL_SPHERE:
{
PCL_DEBUG ("[pcl::%s::initSACModel] Using a model of type: SACMODEL_SPHERE\n", getClassName ().c_str ());
model_.reset (new SampleConsensusModelSphere<PointT> (input_, *indices_));
typename SampleConsensusModelSphere<PointT>::Ptr model_sphere = boost::static_pointer_cast<SampleConsensusModelSphere<PointT> > (model_);
double min_radius, max_radius;
model_sphere->getRadiusLimits (min_radius, max_radius);
if (radius_min_ != min_radius && radius_max_ != max_radius)
{
PCL_DEBUG ("[pcl::%s::initSACModel] Setting radius limits to %f/%f\n", getClassName ().c_str (), radius_min_, radius_max_);
model_sphere->setRadiusLimits (radius_min_, radius_max_);
}
break;
}
case SACMODEL_PARALLEL_LINE:
{
PCL_DEBUG ("[pcl::%s::initSACModel] Using a model of type: SACMODEL_PARALLEL_LINE\n", getClassName ().c_str ());
model_.reset (new SampleConsensusModelParallelLine<PointT> (input_, *indices_));
typename SampleConsensusModelParallelLine<PointT>::Ptr model_parallel = boost::static_pointer_cast<SampleConsensusModelParallelLine<PointT> > (model_);
if (axis_ != Eigen::Vector3f::Zero () && model_parallel->getAxis () != axis_)
{
PCL_DEBUG ("[pcl::%s::initSACModel] Setting the axis to %f, %f, %f\n", getClassName ().c_str (), axis_[0], axis_[1], axis_[2]);
model_parallel->setAxis (axis_);
}
if (eps_angle_ != 0.0 && model_parallel->getEpsAngle () != eps_angle_)
{
PCL_DEBUG ("[pcl::%s::initSACModel] Setting the epsilon angle to %f (%f degrees)\n", getClassName ().c_str (), eps_angle_, eps_angle_ * 180.0 / M_PI);
model_parallel->setEpsAngle (eps_angle_);
}
break;
}
case SACMODEL_PERPENDICULAR_PLANE:
{
PCL_DEBUG ("[pcl::%s::initSACModel] Using a model of type: SACMODEL_PERPENDICULAR_PLANE\n", getClassName ().c_str ());
model_.reset (new SampleConsensusModelPerpendicularPlane<PointT> (input_, *indices_));
typename SampleConsensusModelPerpendicularPlane<PointT>::Ptr model_perpendicular = boost::static_pointer_cast<SampleConsensusModelPerpendicularPlane<PointT> > (model_);
if (axis_ != Eigen::Vector3f::Zero () && model_perpendicular->getAxis () != axis_)
{
PCL_DEBUG ("[pcl::%s::initSACModel] Setting the axis to %f, %f, %f\n", getClassName ().c_str (), axis_[0], axis_[1], axis_[2]);
model_perpendicular->setAxis (axis_);
}
if (eps_angle_ != 0.0 && model_perpendicular->getEpsAngle () != eps_angle_)
{
PCL_DEBUG ("[pcl::%s::initSACModel] Setting the epsilon angle to %f (%f degrees)\n", getClassName ().c_str (), eps_angle_, eps_angle_ * 180.0 / M_PI);
model_perpendicular->setEpsAngle (eps_angle_);
}
break;
}
case SACMODEL_PARALLEL_PLANE:
{
PCL_DEBUG ("[pcl::%s::initSACModel] Using a model of type: SACMODEL_PARALLEL_PLANE\n", getClassName ().c_str ());
model_.reset (new SampleConsensusModelParallelPlane<PointT> (input_, *indices_));
typename SampleConsensusModelParallelPlane<PointT>::Ptr model_parallel = boost::static_pointer_cast<SampleConsensusModelParallelPlane<PointT> > (model_);
if (axis_ != Eigen::Vector3f::Zero () && model_parallel->getAxis () != axis_)
{
PCL_DEBUG ("[pcl::%s::initSACModel] Setting the axis to %f, %f, %f\n", getClassName ().c_str (), axis_[0], axis_[1], axis_[2]);
model_parallel->setAxis (axis_);
}
if (eps_angle_ != 0.0 && model_parallel->getEpsAngle () != eps_angle_)
{
PCL_DEBUG ("[pcl::%s::initSACModel] Setting the epsilon angle to %f (%f degrees)\n", getClassName ().c_str (), eps_angle_, eps_angle_ * 180.0 / M_PI);
model_parallel->setEpsAngle (eps_angle_);
}
break;
}
default:
{
PCL_ERROR ("[pcl::%s::initSACModel] No valid model given!\n", getClassName ().c_str ());
return (false);
}
}
if (samples_radius_ > 0. )
{
PCL_DEBUG ("[pcl::%s::initSAC] Setting the maximum distance to %f\n", getClassName ().c_str (), samples_radius_);
// Set maximum distance for radius search during random sampling
model_->setSamplesMaxDist(samples_radius_, samples_radius_search_);
}
return (true);
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::SACSegmentation<PointT>::initSAC (const int method_type)
{
if (sac_)
sac_.reset ();
// Build the sample consensus method
switch (method_type)
{
case SAC_RANSAC:
default:
{
PCL_DEBUG ("[pcl::%s::initSAC] Using a method of type: SAC_RANSAC with a model threshold of %f\n", getClassName ().c_str (), threshold_);
sac_.reset (new RandomSampleConsensus<PointT> (model_, threshold_));
break;
}
case SAC_LMEDS:
{
PCL_DEBUG ("[pcl::%s::initSAC] Using a method of type: SAC_LMEDS with a model threshold of %f\n", getClassName ().c_str (), threshold_);
sac_.reset (new LeastMedianSquares<PointT> (model_, threshold_));
break;
}
case SAC_MSAC:
{
PCL_DEBUG ("[pcl::%s::initSAC] Using a method of type: SAC_MSAC with a model threshold of %f\n", getClassName ().c_str (), threshold_);
sac_.reset (new MEstimatorSampleConsensus<PointT> (model_, threshold_));
break;
}
case SAC_RRANSAC:
{
PCL_DEBUG ("[pcl::%s::initSAC] Using a method of type: SAC_RRANSAC with a model threshold of %f\n", getClassName ().c_str (), threshold_);
sac_.reset (new RandomizedRandomSampleConsensus<PointT> (model_, threshold_));
break;
}
case SAC_RMSAC:
{
PCL_DEBUG ("[pcl::%s::initSAC] Using a method of type: SAC_RMSAC with a model threshold of %f\n", getClassName ().c_str (), threshold_);
sac_.reset (new RandomizedMEstimatorSampleConsensus<PointT> (model_, threshold_));
break;
}
case SAC_MLESAC:
{
PCL_DEBUG ("[pcl::%s::initSAC] Using a method of type: SAC_MLESAC with a model threshold of %f\n", getClassName ().c_str (), threshold_);
sac_.reset (new MaximumLikelihoodSampleConsensus<PointT> (model_, threshold_));
break;
}
case SAC_PROSAC:
{
PCL_DEBUG ("[pcl::%s::initSAC] Using a method of type: SAC_PROSAC with a model threshold of %f\n", getClassName ().c_str (), threshold_);
sac_.reset (new ProgressiveSampleConsensus<PointT> (model_, threshold_));
break;
}
}
// Set the Sample Consensus parameters if they are given/changed
if (sac_->getProbability () != probability_)
{
PCL_DEBUG ("[pcl::%s::initSAC] Setting the desired probability to %f\n", getClassName ().c_str (), probability_);
sac_->setProbability (probability_);
}
if (max_iterations_ != -1 && sac_->getMaxIterations () != max_iterations_)
{
PCL_DEBUG ("[pcl::%s::initSAC] Setting the maximum number of iterations to %d\n", getClassName ().c_str (), max_iterations_);
sac_->setMaxIterations (max_iterations_);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> bool
pcl::SACSegmentationFromNormals<PointT, PointNT>::initSACModel (const int model_type)
{
if (!input_ || !normals_)
{
PCL_ERROR ("[pcl::%s::initSACModel] Input data (XYZ or normals) not given! Cannot continue.\n", getClassName ().c_str ());
return (false);
}
// Check if input is synced with the normals
if (input_->points.size () != normals_->points.size ())
{
PCL_ERROR ("[pcl::%s::initSACModel] The number of points inthe input point cloud differs than the number of points in the normals!\n", getClassName ().c_str ());
return (false);
}
if (model_)
model_.reset ();
// Build the model
switch (model_type)
{
case SACMODEL_CYLINDER:
{
PCL_DEBUG ("[pcl::%s::initSACModel] Using a model of type: SACMODEL_CYLINDER\n", getClassName ().c_str ());
model_.reset (new SampleConsensusModelCylinder<PointT, PointNT > (input_, *indices_));
typename SampleConsensusModelCylinder<PointT, PointNT>::Ptr model_cylinder = boost::static_pointer_cast<SampleConsensusModelCylinder<PointT, PointNT> > (model_);
// Set the input normals
model_cylinder->setInputNormals (normals_);
double min_radius, max_radius;
model_cylinder->getRadiusLimits (min_radius, max_radius);
if (radius_min_ != min_radius && radius_max_ != max_radius)
{
PCL_DEBUG ("[pcl::%s::initSACModel] Setting radius limits to %f/%f\n", getClassName ().c_str (), radius_min_, radius_max_);
model_cylinder->setRadiusLimits (radius_min_, radius_max_);
}
if (distance_weight_ != model_cylinder->getNormalDistanceWeight ())
{
PCL_DEBUG ("[pcl::%s::initSACModel] Setting normal distance weight to %f\n", getClassName ().c_str (), distance_weight_);
model_cylinder->setNormalDistanceWeight (distance_weight_);
}
if (axis_ != Eigen::Vector3f::Zero () && model_cylinder->getAxis () != axis_)
{
PCL_DEBUG ("[pcl::%s::initSACModel] Setting the axis to %f, %f, %f\n", getClassName ().c_str (), axis_[0], axis_[1], axis_[2]);
model_cylinder->setAxis (axis_);
}
if (eps_angle_ != 0.0 && model_cylinder->getEpsAngle () != eps_angle_)
{
PCL_DEBUG ("[pcl::%s::initSACModel] Setting the epsilon angle to %f (%f degrees)\n", getClassName ().c_str (), eps_angle_, eps_angle_ * 180.0 / M_PI);
model_cylinder->setEpsAngle (eps_angle_);
}
break;
}
case SACMODEL_NORMAL_PLANE:
{
PCL_DEBUG ("[pcl::%s::initSACModel] Using a model of type: SACMODEL_NORMAL_PLANE\n", getClassName ().c_str ());
model_.reset (new SampleConsensusModelNormalPlane<PointT, PointNT> (input_, *indices_));
typename SampleConsensusModelNormalPlane<PointT, PointNT>::Ptr model_normals = boost::static_pointer_cast<SampleConsensusModelNormalPlane<PointT, PointNT> > (model_);
// Set the input normals
model_normals->setInputNormals (normals_);
if (distance_weight_ != model_normals->getNormalDistanceWeight ())
{
PCL_DEBUG ("[pcl::%s::initSACModel] Setting normal distance weight to %f\n", getClassName ().c_str (), distance_weight_);
model_normals->setNormalDistanceWeight (distance_weight_);
}
break;
}
case SACMODEL_NORMAL_PARALLEL_PLANE:
{
PCL_DEBUG ("[pcl::%s::initSACModel] Using a model of type: SACMODEL_NORMAL_PARALLEL_PLANE\n", getClassName ().c_str ());
model_.reset (new SampleConsensusModelNormalParallelPlane<PointT, PointNT> (input_, *indices_));
typename SampleConsensusModelNormalParallelPlane<PointT, PointNT>::Ptr model_normals = boost::static_pointer_cast<SampleConsensusModelNormalParallelPlane<PointT, PointNT> > (model_);
// Set the input normals
model_normals->setInputNormals (normals_);
if (distance_weight_ != model_normals->getNormalDistanceWeight ())
{
PCL_DEBUG ("[pcl::%s::initSACModel] Setting normal distance weight to %f\n", getClassName ().c_str (), distance_weight_);
model_normals->setNormalDistanceWeight (distance_weight_);
}
if (distance_from_origin_ != model_normals->getDistanceFromOrigin ())
{
PCL_DEBUG ("[pcl::%s::initSACModel] Setting the distance to origin to %f\n", getClassName ().c_str (), distance_from_origin_);
model_normals->setDistanceFromOrigin (distance_from_origin_);
}
if (axis_ != Eigen::Vector3f::Zero () && model_normals->getAxis () != axis_)
{
PCL_DEBUG ("[pcl::%s::initSACModel] Setting the axis to %f, %f, %f\n", getClassName ().c_str (), axis_[0], axis_[1], axis_[2]);
model_normals->setAxis (axis_);
}
if (eps_angle_ != 0.0 && model_normals->getEpsAngle () != eps_angle_)
{
PCL_DEBUG ("[pcl::%s::initSACModel] Setting the epsilon angle to %f (%f degrees)\n", getClassName ().c_str (), eps_angle_, eps_angle_ * 180.0 / M_PI);
model_normals->setEpsAngle (eps_angle_);
}
break;
}
case SACMODEL_CONE:
{
PCL_DEBUG ("[pcl::%s::initSACModel] Using a model of type: SACMODEL_CONE\n", getClassName ().c_str ());
model_.reset (new SampleConsensusModelCone<PointT, PointNT > (input_, *indices_));
typename SampleConsensusModelCone<PointT, PointNT>::Ptr model_cone = boost::static_pointer_cast<SampleConsensusModelCone<PointT, PointNT> > (model_);
// Set the input normals
model_cone->setInputNormals (normals_);
double min_angle, max_angle;
model_cone->getMinMaxOpeningAngle(min_angle, max_angle);
if (min_angle_ != min_angle && max_angle_ != max_angle)
{
PCL_DEBUG ("[pcl::%s::initSACModel] Setting minimum and maximum opening angle to %f and %f \n", getClassName ().c_str (), min_angle_, max_angle_);
model_cone->setMinMaxOpeningAngle (min_angle_, max_angle_);
}
if (distance_weight_ != model_cone->getNormalDistanceWeight ())
{
PCL_DEBUG ("[pcl::%s::initSACModel] Setting normal distance weight to %f\n", getClassName ().c_str (), distance_weight_);
model_cone->setNormalDistanceWeight (distance_weight_);
}
if (axis_ != Eigen::Vector3f::Zero () && model_cone->getAxis () != axis_)
{
PCL_DEBUG ("[pcl::%s::initSACModel] Setting the axis to %f, %f, %f\n", getClassName ().c_str (), axis_[0], axis_[1], axis_[2]);
model_cone->setAxis (axis_);
}
if (eps_angle_ != 0.0 && model_cone->getEpsAngle () != eps_angle_)
{
PCL_DEBUG ("[pcl::%s::initSACModel] Setting the epsilon angle to %f (%f degrees)\n", getClassName ().c_str (), eps_angle_, eps_angle_ * 180.0 / M_PI);
model_cone->setEpsAngle (eps_angle_);
}
break;
}
case SACMODEL_NORMAL_SPHERE:
{
PCL_DEBUG ("[pcl::%s::initSACModel] Using a model of type: SACMODEL_NORMAL_SPHERE\n", getClassName ().c_str ());
model_.reset (new SampleConsensusModelNormalSphere<PointT, PointNT> (input_, *indices_));
typename SampleConsensusModelNormalSphere<PointT, PointNT>::Ptr model_normals_sphere = boost::static_pointer_cast<SampleConsensusModelNormalSphere<PointT, PointNT> > (model_);
// Set the input normals
model_normals_sphere->setInputNormals (normals_);
double min_radius, max_radius;
model_normals_sphere->getRadiusLimits (min_radius, max_radius);
if (radius_min_ != min_radius && radius_max_ != max_radius)
{
PCL_DEBUG ("[pcl::%s::initSACModel] Setting radius limits to %f/%f\n", getClassName ().c_str (), radius_min_, radius_max_);
model_normals_sphere->setRadiusLimits (radius_min_, radius_max_);
}
if (distance_weight_ != model_normals_sphere->getNormalDistanceWeight ())
{
PCL_DEBUG ("[pcl::%s::initSACModel] Setting normal distance weight to %f\n", getClassName ().c_str (), distance_weight_);
model_normals_sphere->setNormalDistanceWeight (distance_weight_);
}
break;
}
// If nothing else, try SACSegmentation
default:
{
return (pcl::SACSegmentation<PointT>::initSACModel (model_type));
}
}
if (SACSegmentation<PointT>::samples_radius_ > 0. )
{
PCL_DEBUG ("[pcl::%s::initSAC] Setting the maximum distance to %f\n", getClassName ().c_str (), SACSegmentation<PointT>::samples_radius_);
// Set maximum distance for radius search during random sampling
model_->setSamplesMaxDist(SACSegmentation<PointT>::samples_radius_, SACSegmentation<PointT>::samples_radius_search_);
}
return (true);
}
#define PCL_INSTANTIATE_SACSegmentation(T) template class PCL_EXPORTS pcl::SACSegmentation<T>;
#define PCL_INSTANTIATE_SACSegmentationFromNormals(T,NT) template class PCL_EXPORTS pcl::SACSegmentationFromNormals<T,NT>;
#endif // PCL_SEGMENTATION_IMPL_SAC_SEGMENTATION_H_
| [
"ganterd@tcd.ie"
] | ganterd@tcd.ie |
eef017423ed8e8c3157b9d5e238773670a5222f4 | b095158e129dfab484b17314fbae9d7aa81af4e5 | /source/EliteQuant/Brokers/IB/Official/EClientSocket.h | a370ece7e820b79bd21fa0bd584729abda82fa02 | [
"Apache-2.0"
] | permissive | njuxdj/EliteQuant_Cpp | aca5098baf6f0b7f802c91532d7650fd848b0cc9 | b792e8b72ec49fdca99d389f4cfe9671dff0bb6d | refs/heads/master | 2021-05-09T02:51:23.968524 | 2018-03-17T14:39:06 | 2018-03-17T14:39:06 | 119,224,763 | 1 | 0 | null | 2018-01-28T03:37:59 | 2018-01-28T03:37:58 | null | UTF-8 | C++ | false | false | 1,695 | h | /* Copyright (C) 2013 Interactive Brokers LLC. All rights reserved. This code is subject to the terms
* and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable. */
#pragma once
#ifndef eposixclientsocket_def
#define eposixclientsocket_def
#include "EClient.h"
#include "EClientMsgSink.h"
#include "ESocket.h"
namespace IBOfficial {
class EWrapper;
class EReaderSignal;
class TWSAPIDLLEXP EClientSocket : public EClient, public EClientMsgSink
{
protected:
virtual void prepareBufferImpl(std::ostream&) const;
virtual void prepareBuffer(std::ostream&) const;
virtual bool closeAndSend(std::string msg, unsigned offset = 0);
public:
explicit EClientSocket(EWrapper *ptr, EReaderSignal *pSignal = 0);
~EClientSocket();
bool eConnect(const char *host, unsigned int port, int clientId = 0, bool extraAuth = false);
// override virtual funcs from EClient
void eDisconnect();
bool isSocketOK() const;
int fd() const;
bool asyncEConnect() const;
void asyncEConnect(bool val);
ESocket *getTransport();
private:
bool eConnectImpl(int clientId, bool extraAuth, ConnState* stateOutPt);
private:
void encodeMsgLen(std::string& msg, unsigned offset) const;
public:
bool handleSocketError();
int receive(char* buf, size_t sz);
public:
// callback from socket
void onSend();
void onError();
private:
void onClose();
private:
int m_fd;
bool m_allowRedirect;
const char* m_hostNorm;
bool m_asyncEConnect;
EReaderSignal *m_pSignal;
//EClientMsgSink implementation
public:
void serverVersion(int version, const char *time);
void redirect(const char *host, int port);
};
}
#endif
| [
"contact@elitequant.com"
] | contact@elitequant.com |
257d7b7d6195c078ea04c8e79182a03c105bd9ad | 9e15ecabaaedbf21090ce8542558df9ea1c8d868 | /Plugin_MultiTrack/src/ofxRulr/Nodes/MultiTrack/Publisher.h | cb0836f80a939b7308a268f049ee7e60fc7fb514 | [] | no_license | elliotwoods/ofxRulr | a6948cfffa4419ee9c3367c6a3f1bb9ae0af17ae | 5f9033cd42841dcab5063878bcab788d05921e19 | refs/heads/master | 2023-09-04T11:00:31.464347 | 2023-08-30T05:46:03 | 2023-08-30T05:46:03 | 19,885,267 | 106 | 19 | null | 2016-03-19T06:45:43 | 2014-05-17T11:41:48 | C++ | UTF-8 | C++ | false | false | 1,550 | h | #pragma once
#include "ofxRulr/Nodes/Item/IDepthCamera.h"
#include "ofxMultiTrack.h"
#include "ofxRulr/Utils/ControlSocket.h"
namespace ofxRulr {
namespace Nodes {
namespace MultiTrack {
class Publisher : public Nodes::Base {
public:
Publisher();
string getTypeName() const override;
void init();
void update();
void populateInspector(ofxCvGui::InspectArguments &);
void serialize(Json::Value &);
void deserialize(const Json::Value &);
shared_ptr<ofxMultiTrack::Publisher> getPublisher();
protected:
void buildControlSocket();
struct : ofParameterGroup {
struct : ofParameterGroup {
ofParameter<int> port{ "Port", ofxMultiTrack::Ports::NodeControl };
ofParameter<bool> enabled{ "Enabled", false };
PARAM_DECLARE("Control Socket", port);
} controlSocket;
struct : ofParameterGroup {
ofParameter<int> port{ "Port", 2147 };
PARAM_DECLARE("Data Socket", port);
} dataSocket;
struct : ofParameterGroup {
ofParameter<int> packetSize{ "Packet size", 4096, 1024, 1e9 };
ofParameter<int> maxSocketBufferSize{ "Max socket buffer size", 300, 0, 10000 };
PARAM_DECLARE("Squash Buddies", packetSize, maxSocketBufferSize);
} squashBuddies;
PARAM_DECLARE("Publisher", controlSocket, dataSocket, squashBuddies);
} parameters;
shared_ptr<ofxMultiTrack::Publisher> publisher;
unique_ptr<Utils::ControlSocket> controlSocket;
bool droppedFrame;
};
}
}
} | [
"prisonerjohn@gmail.com"
] | prisonerjohn@gmail.com |
42a8637821b058f6807e85171405b416d006191a | 0f7a4119185aff6f48907e8a5b2666d91a47c56b | /sstd_utility/windows_boost/boost/metaparse/transform_error.hpp | d8f38cd991a364133174411285efb0fd7958257d | [] | no_license | jixhua/QQmlQuickBook | 6636c77e9553a86f09cd59a2e89a83eaa9f153b6 | 782799ec3426291be0b0a2e37dc3e209006f0415 | refs/heads/master | 2021-09-28T13:02:48.880908 | 2018-11-17T10:43:47 | 2018-11-17T10:43:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 458 | hpp | #ifndef BOOST_METAPARSE_TRANSFORM_ERROR_HPP
#define BOOST_METAPARSE_TRANSFORM_ERROR_HPP
// Copyright Abel Sinkovics (abel@sinkovics.hu) 2015.
// 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)
#include <boost/metaparse/v1/transform_error.hpp>
namespace boost
{
namespace metaparse
{
using v1::transform_error;
}
}
#endif
| [
"nanguazhude@vip.qq.com"
] | nanguazhude@vip.qq.com |
d8ea14204b0f820a0dcb4afbe061c5ff847ca679 | 7e167301a49a7b7ac6ff8b23dc696b10ec06bd4b | /prev_work/opensource/fMRI/FSL/fsl/extras/include/boost/boost/mpl/front_fwd.hpp | 40456af7bfb4c60b79de9977b8a6dd62b05f5304 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Sejik/SignalAnalysis | 6c6245880b0017e9f73b5a343641065eb49e5989 | c04118369dbba807d99738accb8021d77ff77cb6 | refs/heads/master | 2020-06-09T12:47:30.314791 | 2019-09-06T01:31:16 | 2019-09-06T01:31:16 | 193,439,385 | 5 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 644 | hpp |
#ifndef BOOST_MPL_FRONT_FWD_HPP_INCLUDED
#define BOOST_MPL_FRONT_FWD_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2000-2004
//
// 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)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Source: /usr/local/share/sources/boost/boost/mpl/front_fwd.hpp,v $
// $Date: 2007/06/12 15:03:23 $
// $Revision: 1.1.1.1 $
namespace boost { namespace mpl {
template< typename Tag > struct front_impl;
template< typename Sequence > struct front;
}}
#endif // BOOST_MPL_FRONT_FWD_HPP_INCLUDED
| [
"sejik6307@gmail.com"
] | sejik6307@gmail.com |
55ad2323015c89c831da9888a7f998b4a99a0580 | b9dba82a5496b5c49c27fa4094ec12391271f0ad | /mainwindow.h | c801ba03c957704e917de97dbb608a42265b46a1 | [] | no_license | Anusis/Gobang | 60937a731e7be27b73790a9ab1f051bac63ed5b8 | 759de3281131c3848dadc0914787817e75ef70f5 | refs/heads/master | 2020-03-22T21:23:18.307819 | 2018-07-12T08:23:45 | 2018-07-12T08:23:45 | 140,371,075 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 658 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QPainter>
#include <QPaintEvent>
#include <QMouseEvent>
#include "board.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void paintEvent(QPaintEvent *p);
void mousePressEvent(QMouseEvent *m);
static int order;
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
void on_pushButton_3_clicked();
void on_pushButton_4_clicked();
private:
Ui::MainWindow *ui;
Board _game;
};
#endif // MAINWINDOW_H
| [
"18811610809@ruc.edu.cn"
] | 18811610809@ruc.edu.cn |
a3a7e2e859c39cd005b196dd524e39de55f740dc | ea1f4b774578f2a9c340a5388e2505b8d7fdbe4e | /csg/TesselatorRat.cpp | 1c75bed5ae0175f97cab60ecc7f5450a3416d837 | [
"Apache-2.0"
] | permissive | ehtick/Apex-VSIX | e9ad7e4c88f8bbbf3bec86e8b2291b6f2f6ade74 | 966c7a281c208343a08fd39f5f4840fb113823c9 | refs/heads/master | 2023-06-14T19:11:12.468476 | 2021-07-07T05:59:45 | 2021-07-07T05:59:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,517 | cpp | #include "pch.h"
#include "TesselatorRat.h"
HRESULT CTesselatorRat::get_Mode(CSG_TESS* p)
{
*p = mode; return 0;
}
HRESULT CTesselatorRat::put_Mode(CSG_TESS newVal)
{
mode = newVal; return 0;
}
HRESULT CTesselatorRat::SetNormal(CSGVAR n)
{
double v[3]; conv(v, 3, n);
int i = abs(v[0]) >= abs(v[1]) && abs(v[0]) >= abs(v[2]) ? 0 : abs(v[1]) >= abs(v[2]) ? 1 : 2;
int s = v[i] < 0 ? -1 : +1;
mode = (CSG_TESS)((mode & (CSG_TESS)0xffff) | ((int)CSG_TESS_NORMX << i) | (s & (int)CSG_TESS_NORMNEG));
return 0;
}
HRESULT CTesselatorRat::BeginPolygon()
{
np = 0; return 0;
}
HRESULT CTesselatorRat::BeginContour()
{
fi = np; return 0;
}
HRESULT CTesselatorRat::AddVertex(CSGVAR v)
{
if (np == pp.n) resize(64);
if (np != fi) pp[np - 1].next = np;
auto a = &pp[np++]; a->next = fi;
conv(&a->x, 3, v); return 0;
}
HRESULT CTesselatorRat::EndContour()
{
return 0;
}
HRESULT CTesselatorRat::EndPolygon()
{
auto pro = project(0);
ns = nl = this->ni = 0; int np = snp = this->np, shv = 1; if (!np) return 0; worstcase:
for (int i = 0; i < this->np; i++) { auto p = &pp[i]; p->y = 0 | p->y + p->x / kill; }
memset(dict.p, 0, hash * sizeof(int)); int ni = 0;
for (int i = 0; i < np; i++)
{
auto a = &pp[i]; auto b = &pp[a->next];
Rational::mach m = 0; m.fetch();
auto dx = b->x - a->x; auto dy = b->y - a->y; int d;
if ((d = dy.sign()) == 0) { m.dispose(); if (dx.sign() == 0) continue; shv++; goto worstcase; }
a->f = m | a->x - a->y * (a->a = m | dx / dy); m.dispose();
a->x2 = d > 0 ? a->x : b->x;
kk[ni++] = ab(i, d > 0 ? i : a->next); a->line = -1; addpt(a->x, a->y, i);
}
qsort_s(kk.p, ni, sizeof(ab), cmp1, this);
Rational y1, y2; int active = 0, nfl = 0;
for (int l = 0; l < ni;)
{
for (y1 = pp[kk[l].b].y; ;)
{
kk[active++] = kk[l];
if (++l == ni || (y2 = pp[kk[l].b].y) != y1) break;
}
for (auto y3 = y2; ; y1 = y2, y2 = y3)
{
for (int t = active, j; t-- != 0;)
{
auto next = pp[j = kk[t].a].next;
if (next < 0)
{
pp[j].x1 = pp[j].x2; if (pp[j].line != -1) { pp[nfl++].fl = j | (pp[j].line << 16); pp[j].line = -1; }
active--; for (int s = t; s < active; s++) kk[s] = kk[s + 1]; goto next;
}
const auto& y = pp[j != kk[t].b ? j : next].y;
if (l != ni) { if (y < y2) y2 = y; continue; }
if (y > y3) y3 = y;
next:
if (t == 0 && l == ni) { y2 = y3; t = active; l++; }
}
////////////
for (int t = 0; t < active; t++)
{
auto a = &pp[kk[t].a];
a->x1 = a->x2;
a->x2 = 0 | a->f + y2 * a->a;
}
qsort_s(kk.p, active, sizeof(ab), cmp2, this);
int nc = 0, e = active;
for (int i = 1; i < active; i++)
{
auto a = &pp[kk[i - 1].a]; auto b = &pp[kk[i].a];
if (a->x2 <= b->x2) continue;
Rational::mach m = 0; m.fetch();
auto y = (b->f - a->f) / (a->a - b->a);
if (y < y2) { y2 = m | y; e = 0; }
m.dispose();
}
for (; e < active; e++)
{
auto a = &pp[kk[e].a]; a->x2 = 0 | a->f + y2 * a->a;
}
for (int i = 0, k = 0, dir = 0, t; i < active; i++)
{
auto b = &pp[t = kk[i].a]; auto d = t != kk[i].b;
if ((d ? b->y : pp[b->next].y) == y2) b->next = -1 - b->next;
auto old = dir; dir += d ? +1 : -1;
switch ((CSG_TESS)((int)mode & 0xff))
{
case CSG_TESS_EVENODD:
if ((old & 1) == 0 && (dir & 1) == 1) { k = i; continue; }
if ((old & 1) == 1 && (dir & 1) == 0) break;
goto skip;
case CSG_TESS_POSITIVE:
if (dir == +1 && old == 0) { k = i; continue; }
if (old == +1 && dir == 0) break;
goto skip;
case CSG_TESS_NEGATIVE:
if (dir == -1 && old == 0) { k = i; continue; }
if (old == -1 && dir == 0) break;
goto skip;
case CSG_TESS_NONZERO:
if (old == 0) { k = i; continue; }
if (dir == 0) break;
goto skip;
case CSG_TESS_ABSGEQTWO:
if (abs(old) == 1 && abs(dir) == 2) { k = i; continue; }
if (abs(old) == 2 && abs(dir) == 1) break;
goto skip;
case CSG_TESS_GEQTHREE:
if (old == 2 && dir == 3) { k = i; continue; }
if (old == 3 && dir == 2) break;
goto skip;
}
auto a = &pp[kk[k].a];
if (a->x1 == b->x1 && a->x2 == b->x2)
{
if (a->line != -1) { pp[nfl++].fl = kk[k].a | (a->line << 16); a->line = -1; }
if (b->line != -1) goto skip;
continue;
}
if (nc != 0)
{
auto c = &pp[pp[nc - 1].ic];
if (c->x1 == a->x1 && c->x2 == a->x2) //xor
{
if (a->line != -1) { pp[nfl++].fl = (kk[k].a) | (a->line << 16); a->line = -1; }
if (c->line != -1) { pp[nfl++].fl = pp[nc - 1].ic | (c->line << 16); c->line = -1; }
nc--; goto m1;
}
}
pp[nc++].ic = kk[k].a; m1:
pp[nc++].ic = t;
continue; skip: if (b->line != -1) { pp[nfl++].fl = t | (b->line << 16); b->line = -1; }
}
for (int i = 0, j; i < nc; i++)
{
if (this->np + 4 >= (int)pp.n) resize();
auto b = &pp[j = pp[i].ic];
bool f1 = false, f2 = false;
for (int k = i - 1; k <= i + 1; k += 2)
{
if ((UINT)k >= (UINT)nc) continue;
auto c = &pp[pp[k].ic];
if (!f1 && b->x1 == c->x1) f1 = true;
if (!f2 && b->x2 == c->x2) f2 = true;
}
if (!f1)
{
if (b->line == -1)
for (int t = 0; t < nfl; t++)
{
auto c = &pp[pp[t].fl & 0xffff];
if (b->f != c->f || b->a != c->a) continue;
b->line = pp[t].fl >> 16; pp[t].fl = pp[i].ic | (b->line << 16);
for (nfl--; t < nfl; t++) pp[t].fl = pp[t + 1].fl; break;
}
if (b->line != -1)
{
if ((i & 1) != 0)
{
if (ii[b->line].b == -1) { if (f2) { ii[b->line].b = addpt(b->x2, y2, -1 - j); b->line = -1; } continue; }
ii[b->line].a = addpt(b->x1, y1, -1 - j);
}
else
{
if (ii[b->line].a == -1) { if (f2) { ii[b->line].a = addpt(b->x2, y2, -1 - j); b->line = -1; } continue; }
ii[b->line].b = addpt(b->x1, y1, -1 - j);
}
}
}
auto k1 = addpt(b->x1, y1, -1 - j);
if (f1 && b->line != -1) { if (ii[b->line].a == -1) ii[b->line].a = k1; else ii[b->line].b = k1; }
auto k2 = f2 ? addpt(b->x2, y2, -1 - j) : -1;
b->line = f2 ? -1 : this->ni; if (this->ni == ii.n) ii.setsize(max((int)pp.n, this->ni << 1));
ii[this->ni++] = (i & 1) != 0 ? ab(k1, k2) : ab(k2, k1);
}
for (int i = 0, j; i < nfl; i++)
{
auto c = &pp[j = pp[i].fl & 0xffff];
auto line = pp[i].fl >> 16; auto t = addpt(c->x1, y1, -1 - j);
if (ii[line].a == -1) ii[line].a = t; else ii[line].b = t;
}
nfl = 0;
////////////
if (y2 == y3) break;
}
}
for (int i = 0, j; i < active; i++)
{
auto c = &pp[j = kk[i].a]; if (c->line == -1) continue;
auto t = addpt(c->x2, y2, -1 - j); if (ii[c->line].a == -1) ii[c->line].a = t; else ii[c->line].b = t;
}
if ((mode & (CSG_TESS_FILLFAST | CSG_TESS_FILL)) != 0) fill();
if ((mode & CSG_TESS_INDEXONLY) == 0)
{
auto f = shv != 1 ? kill * shv : kill;
for (int i = 0; i < this->np; i++) { auto p = &pp[i]; p->y = 0 | p->y - p->x / f; }
}
if ((mode & (CSG_TESS_OUTLINE | CSG_TESS_OUTLINEPRECISE)) != 0) outline();
if ((mode & CSG_TESS_NOTRIM) == 0) trim();
if ((mode & CSG_TESS_FILL) != 0) optimize();
if ((mode & CSG_TESS_INDEXONLY) != 0) { this->np = 0; return 0; }
if (pro != 0) project(pro << 2);
return 0;
}
HRESULT CTesselatorRat::get_VertexCount(UINT* p)
{
*p = np; return 0;
}
HRESULT CTesselatorRat::GetVertex(UINT i, CSGVAR v)
{
if (i >= (UINT)np) return E_INVALIDARG;
conv(v, &pp[i].x, 3); return 0;
}
HRESULT CTesselatorRat::get_IndexCount(UINT* p)
{
*p = ns; return 0;
}
HRESULT CTesselatorRat::GetIndex(UINT i, UINT* p)
{
if (i >= (UINT)ns) return E_INVALIDARG;
*p = ss[i]; return 0;
}
HRESULT CTesselatorRat::get_OutlineCount(UINT* p)
{
*p = nl; return 0;
}
HRESULT CTesselatorRat::GetOutline(UINT i, UINT* p)
{
if (i >= (UINT)nl) return E_INVALIDARG;
*p = ll[i]; return 0;
}
| [
"c.ohle@superkabel.de"
] | c.ohle@superkabel.de |
94397131c211cbe9cf6ee13c96220d6cfa610121 | 94dbfcf94dd0a61d7cd197cf996602d5a2acdda7 | /tree/lc_543_diameter-of-binary-tree.cpp | 33424b92b3b882d730193548fdde6f882c8a5cba | [] | no_license | PengJi/Algorithms | 46ac90691cc20b0f769374ac3d848a26766965b1 | 6aa26240679bc209a6fd69580b9c7994cef51b54 | refs/heads/master | 2023-07-21T05:57:50.637703 | 2023-07-07T10:16:48 | 2023-07-09T10:17:10 | 243,935,787 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,014 | cpp | /**
* 543. 二叉树的直径
* https://leetcode-cn.com/problems/diameter-of-binary-tree/
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int ans;
int diameterOfBinaryTree(TreeNode* root) {
ans = 1;
dfs(root);
return ans - 1;
}
int dfs(TreeNode* root) {
if(root == NULL) {
return 0;
}
int L = dfs(root->left);
int R = dfs(root->right);
ans = max(ans, L+R+1);
return max(L, R) + 1;
}
};
class Solution {
public:
int res = 0;
int diameterOfBinaryTree(TreeNode* root) {
dfs(root);
return res;
}
int dfs(TreeNode* root) {
if(!root) return 0;
int left = dfs(root->left), right = dfs(root->right);
res = max(res, left + right);
return max(left, right) + 1;
}
};
| [
"jipengpro@gmail.com"
] | jipengpro@gmail.com |
45db55b431e8cf6a50ff69f95a060542769ab9f4 | e41e78cc4b8d010ebdc38bc50328e7bba2d5a3fd | /SDK/Mordhau_BP_RoyalFlatTop_classes.hpp | be85afefeb81df6409c70cd1435e733192793194 | [] | no_license | Mentos-/Mordhau_SDK | a5e4119d60988dca9063e75e2563d1169a2924b8 | aacf020e6d4823a76787177eac2f8f633f558ec2 | refs/heads/master | 2020-12-13T10:36:47.589320 | 2020-01-03T18:06:38 | 2020-01-03T18:06:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 710 | hpp | #pragma once
// Mordhau (Dumped by Hinnie) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BP_RoyalFlatTop.BP_RoyalFlatTop_C
// 0x0000 (0x01C0 - 0x01C0)
class UBP_RoyalFlatTop_C : public UBP_Tier2HeadWearable_C
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_RoyalFlatTop.BP_RoyalFlatTop_C");
return ptr;
}
void UserConstructionScript();
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"hsibma02@gmail.com"
] | hsibma02@gmail.com |
f61272f3fafd6914dac60770c5b2704912194f89 | 00add89b1c9712db1a29a73f34864854a7738686 | /packages/data/core/test/tstThermalNuclearDataProperties.cpp | b75939bfe577facf856c5d69abf427507e1498f6 | [
"BSD-3-Clause"
] | permissive | FRENSIE/FRENSIE | a4f533faa02e456ec641815886bc530a53f525f9 | 1735b1c8841f23d415a4998743515c56f980f654 | refs/heads/master | 2021-11-19T02:37:26.311426 | 2021-09-08T11:51:24 | 2021-09-08T11:51:24 | 7,826,404 | 11 | 6 | NOASSERTION | 2021-09-08T11:51:25 | 2013-01-25T19:03:09 | C++ | UTF-8 | C++ | false | false | 2,892 | cpp | //---------------------------------------------------------------------------//
//!
//! \file Data_ThermalNuclearDataProperties.cpp
//! \author Alex Robinson
//! \brief Thermal nuclear data properties class unit tests
//!
//---------------------------------------------------------------------------//
// Std Lib Includes
#include <iostream>
#include <sstream>
// FRENSIE Includes
#include "Data_ThermalNuclearDataProperties.hpp"
#include "Utility_UnitTestHarnessWithMain.hpp"
#include "ArchiveTestHelpers.hpp"
//---------------------------------------------------------------------------//
// Testing Types
//---------------------------------------------------------------------------//
typedef TestArchiveHelper::TestArchives TestArchives;
//---------------------------------------------------------------------------//
// Tests.
//---------------------------------------------------------------------------//
// Check that a ThermalNuclearDataProperties::FileType can be archived
FRENSIE_UNIT_TEST_TEMPLATE_EXPAND( ThermalNuclearDataProperties,
FileType_archive,
TestArchives )
{
FETCH_TEMPLATE_PARAM( 0, RawOArchive );
FETCH_TEMPLATE_PARAM( 1, RawIArchive );
typedef typename std::remove_pointer<RawOArchive>::type OArchive;
typedef typename std::remove_pointer<RawIArchive>::type IArchive;
std::string archive_base_name( "test_photoatomic_file_type" );
std::ostringstream archive_ostream;
{
std::unique_ptr<OArchive> oarchive;
createOArchive( archive_base_name, archive_ostream, oarchive );
Data::ThermalNuclearDataProperties::FileType type_1 =
Data::ThermalNuclearDataProperties::STANDARD_ACE_FILE;
Data::ThermalNuclearDataProperties::FileType type_2 =
Data::ThermalNuclearDataProperties::MCNP6_ACE_FILE;
FRENSIE_REQUIRE_NO_THROW( (*oarchive) << BOOST_SERIALIZATION_NVP( type_1 ) );
FRENSIE_REQUIRE_NO_THROW( (*oarchive) << BOOST_SERIALIZATION_NVP( type_2 ) );
}
// Copy the archive ostream to an istream
std::istringstream archive_istream( archive_ostream.str() );
// Load the archived distributions
std::unique_ptr<IArchive> iarchive;
createIArchive( archive_istream, iarchive );
Data::ThermalNuclearDataProperties::FileType type_1;
FRENSIE_REQUIRE_NO_THROW( (*iarchive) >> BOOST_SERIALIZATION_NVP( type_1 ) );
FRENSIE_CHECK_EQUAL( type_1, Data::ThermalNuclearDataProperties::STANDARD_ACE_FILE );
Data::ThermalNuclearDataProperties::FileType type_2;
FRENSIE_REQUIRE_NO_THROW( (*iarchive) >> BOOST_SERIALIZATION_NVP( type_2 ) );
FRENSIE_CHECK_EQUAL( type_2, Data::ThermalNuclearDataProperties::MCNP6_ACE_FILE );
}
//---------------------------------------------------------------------------//
// end tstThermalNuclearDataProperties.cpp
//---------------------------------------------------------------------------//
| [
"aprobinson@wisc.edu"
] | aprobinson@wisc.edu |
c3c3bafb7ccba287c563779a6808b7e899c92208 | 27c1cb57c1608b65639c6194dc945a440df25473 | /cg_exercise_01/cglib/lib/glm/glm/gtx/associated_min_max.inl | cff9fdf4f8306f9d51eb3bb9113f3632690c59e1 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"LicenseRef-scancode-happy-bunny"
] | permissive | brankyy/CG | 41c7de721ffdba2aefda48db823521fb0d409710 | 217960504e0c723b73dab664e6ca0ccf3aeeeec8 | refs/heads/master | 2020-04-05T00:36:27.888286 | 2019-01-06T22:02:49 | 2019-01-06T22:02:49 | 156,395,913 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,993 | inl | /// @ref gtx_associated_min_max
/// @file glm/gtx/associated_min_max.inl
namespace glm{
// Min comparison between 2 variables
template<typename T, typename U, qualifier Q>
GLM_FUNC_QUALIFIER U associatedMin(T x, U a, T y, U b)
{
return x < y ? a : b;
}
template<length_t L, typename T, typename U, qualifier Q>
GLM_FUNC_QUALIFIER vec<2, U, Q> associatedMin
(
vec<L, T, Q> const& x, vec<L, U, Q> const& a,
vec<L, T, Q> const& y, vec<L, U, Q> const& b
)
{
vec<L, U, Q> Result;
for(length_t i = 0, n = Result.length(); i < n; ++i)
Result[i] = x[i] < y[i] ? a[i] : b[i];
return Result;
}
template<length_t L, typename T, typename U, qualifier Q>
GLM_FUNC_QUALIFIER vec<L, U, Q> associatedMin
(
T x, const vec<L, U, Q>& a,
T y, const vec<L, U, Q>& b
)
{
vec<L, U, Q> Result;
for(length_t i = 0, n = Result.length(); i < n; ++i)
Result[i] = x < y ? a[i] : b[i];
return Result;
}
template<length_t L, typename T, typename U, qualifier Q>
GLM_FUNC_QUALIFIER vec<L, U, Q> associatedMin
(
vec<L, T, Q> const& x, U a,
vec<L, T, Q> const& y, U b
)
{
vec<L, U, Q> Result;
for(length_t i = 0, n = Result.length(); i < n; ++i)
Result[i] = x[i] < y[i] ? a : b;
return Result;
}
// Min comparison between 3 variables
template<typename T, typename U>
GLM_FUNC_QUALIFIER U associatedMin
(
T x, U a,
T y, U b,
T z, U c
)
{
U Result = x < y ? (x < z ? a : c) : (y < z ? b : c);
return Result;
}
template<length_t L, typename T, typename U, qualifier Q>
GLM_FUNC_QUALIFIER vec<L, U, Q> associatedMin
(
vec<L, T, Q> const& x, vec<L, U, Q> const& a,
vec<L, T, Q> const& y, vec<L, U, Q> const& b,
vec<L, T, Q> const& z, vec<L, U, Q> const& c
)
{
vec<L, U, Q> Result;
for(length_t i = 0, n = Result.length(); i < n; ++i)
Result[i] = x[i] < y[i] ? (x[i] < z[i] ? a[i] : c[i]) : (y[i] < z[i] ? b[i] : c[i]);
return Result;
}
// Min comparison between 4 variables
template<typename T, typename U>
GLM_FUNC_QUALIFIER U associatedMin
(
T x, U a,
T y, U b,
T z, U c,
T w, U d
)
{
T Test1 = min(x, y);
T Test2 = min(z, w);;
U Result1 = x < y ? a : b;
U Result2 = z < w ? c : d;
U Result = Test1 < Test2 ? Result1 : Result2;
return Result;
}
// Min comparison between 4 variables
template<length_t L, typename T, typename U, qualifier Q>
GLM_FUNC_QUALIFIER vec<L, U, Q> associatedMin
(
vec<L, T, Q> const& x, vec<L, U, Q> const& a,
vec<L, T, Q> const& y, vec<L, U, Q> const& b,
vec<L, T, Q> const& z, vec<L, U, Q> const& c,
vec<L, T, Q> const& w, vec<L, U, Q> const& d
)
{
vec<L, U, Q> Result;
for(length_t i = 0, n = Result.length(); i < n; ++i)
{
T Test1 = min(x[i], y[i]);
T Test2 = min(z[i], w[i]);
U Result1 = x[i] < y[i] ? a[i] : b[i];
U Result2 = z[i] < w[i] ? c[i] : d[i];
Result[i] = Test1 < Test2 ? Result1 : Result2;
}
return Result;
}
// Min comparison between 4 variables
template<length_t L, typename T, typename U, qualifier Q>
GLM_FUNC_QUALIFIER vec<L, U, Q> associatedMin
(
T x, vec<L, U, Q> const& a,
T y, vec<L, U, Q> const& b,
T z, vec<L, U, Q> const& c,
T w, vec<L, U, Q> const& d
)
{
T Test1 = min(x, y);
T Test2 = min(z, w);
vec<L, U, Q> Result;
for(length_t i = 0, n = Result.length(); i < n; ++i)
{
U Result1 = x < y ? a[i] : b[i];
U Result2 = z < w ? c[i] : d[i];
Result[i] = Test1 < Test2 ? Result1 : Result2;
}
return Result;
}
// Min comparison between 4 variables
template<length_t L, typename T, typename U, qualifier Q>
GLM_FUNC_QUALIFIER vec<L, U, Q> associatedMin
(
vec<L, T, Q> const& x, U a,
vec<L, T, Q> const& y, U b,
vec<L, T, Q> const& z, U c,
vec<L, T, Q> const& w, U d
)
{
vec<L, U, Q> Result;
for(length_t i = 0, n = Result.length(); i < n; ++i)
{
T Test1 = min(x[i], y[i]);
T Test2 = min(z[i], w[i]);;
U Result1 = x[i] < y[i] ? a : b;
U Result2 = z[i] < w[i] ? c : d;
Result[i] = Test1 < Test2 ? Result1 : Result2;
}
return Result;
}
// Max comparison between 2 variables
template<typename T, typename U>
GLM_FUNC_QUALIFIER U associatedMax(T x, U a, T y, U b)
{
return x > y ? a : b;
}
// Max comparison between 2 variables
template<length_t L, typename T, typename U, qualifier Q>
GLM_FUNC_QUALIFIER vec<2, U, Q> associatedMax
(
vec<L, T, Q> const& x, vec<L, U, Q> const& a,
vec<L, T, Q> const& y, vec<L, U, Q> const& b
)
{
vec<L, U, Q> Result;
for(length_t i = 0, n = Result.length(); i < n; ++i)
Result[i] = x[i] > y[i] ? a[i] : b[i];
return Result;
}
// Max comparison between 2 variables
template<length_t L, typename T, typename U, qualifier Q>
GLM_FUNC_QUALIFIER vec<L, T, Q> associatedMax
(
T x, vec<L, U, Q> const& a,
T y, vec<L, U, Q> const& b
)
{
vec<L, U, Q> Result;
for(length_t i = 0, n = Result.length(); i < n; ++i)
Result[i] = x > y ? a[i] : b[i];
return Result;
}
// Max comparison between 2 variables
template<length_t L, typename T, typename U, qualifier Q>
GLM_FUNC_QUALIFIER vec<L, U, Q> associatedMax
(
vec<L, T, Q> const& x, U a,
vec<L, T, Q> const& y, U b
)
{
vec<L, T, Q> Result;
for(length_t i = 0, n = Result.length(); i < n; ++i)
Result[i] = x[i] > y[i] ? a : b;
return Result;
}
// Max comparison between 3 variables
template<typename T, typename U>
GLM_FUNC_QUALIFIER U associatedMax
(
T x, U a,
T y, U b,
T z, U c
)
{
U Result = x > y ? (x > z ? a : c) : (y > z ? b : c);
return Result;
}
// Max comparison between 3 variables
template<length_t L, typename T, typename U, qualifier Q>
GLM_FUNC_QUALIFIER vec<L, U, Q> associatedMax
(
vec<L, T, Q> const& x, vec<L, U, Q> const& a,
vec<L, T, Q> const& y, vec<L, U, Q> const& b,
vec<L, T, Q> const& z, vec<L, U, Q> const& c
)
{
vec<L, U, Q> Result;
for(length_t i = 0, n = Result.length(); i < n; ++i)
Result[i] = x[i] > y[i] ? (x[i] > z[i] ? a[i] : c[i]) : (y[i] > z[i] ? b[i] : c[i]);
return Result;
}
// Max comparison between 3 variables
template<length_t L, typename T, typename U, qualifier Q>
GLM_FUNC_QUALIFIER vec<L, T, Q> associatedMax
(
T x, vec<L, U, Q> const& a,
T y, vec<L, U, Q> const& b,
T z, vec<L, U, Q> const& c
)
{
vec<L, U, Q> Result;
for(length_t i = 0, n = Result.length(); i < n; ++i)
Result[i] = x > y ? (x > z ? a[i] : c[i]) : (y > z ? b[i] : c[i]);
return Result;
}
// Max comparison between 3 variables
template<length_t L, typename T, typename U, qualifier Q>
GLM_FUNC_QUALIFIER vec<L, U, Q> associatedMax
(
vec<L, T, Q> const& x, U a,
vec<L, T, Q> const& y, U b,
vec<L, T, Q> const& z, U c
)
{
vec<L, T, Q> Result;
for(length_t i = 0, n = Result.length(); i < n; ++i)
Result[i] = x[i] > y[i] ? (x[i] > z[i] ? a : c) : (y[i] > z[i] ? b : c);
return Result;
}
// Max comparison between 4 variables
template<typename T, typename U>
GLM_FUNC_QUALIFIER U associatedMax
(
T x, U a,
T y, U b,
T z, U c,
T w, U d
)
{
T Test1 = max(x, y);
T Test2 = max(z, w);;
U Result1 = x > y ? a : b;
U Result2 = z > w ? c : d;
U Result = Test1 > Test2 ? Result1 : Result2;
return Result;
}
// Max comparison between 4 variables
template<length_t L, typename T, typename U, qualifier Q>
GLM_FUNC_QUALIFIER vec<L, U, Q> associatedMax
(
vec<L, T, Q> const& x, vec<L, U, Q> const& a,
vec<L, T, Q> const& y, vec<L, U, Q> const& b,
vec<L, T, Q> const& z, vec<L, U, Q> const& c,
vec<L, T, Q> const& w, vec<L, U, Q> const& d
)
{
vec<L, U, Q> Result;
for(length_t i = 0, n = Result.length(); i < n; ++i)
{
T Test1 = max(x[i], y[i]);
T Test2 = max(z[i], w[i]);
U Result1 = x[i] > y[i] ? a[i] : b[i];
U Result2 = z[i] > w[i] ? c[i] : d[i];
Result[i] = Test1 > Test2 ? Result1 : Result2;
}
return Result;
}
// Max comparison between 4 variables
template<length_t L, typename T, typename U, qualifier Q>
GLM_FUNC_QUALIFIER vec<L, U, Q> associatedMax
(
T x, vec<L, U, Q> const& a,
T y, vec<L, U, Q> const& b,
T z, vec<L, U, Q> const& c,
T w, vec<L, U, Q> const& d
)
{
T Test1 = max(x, y);
T Test2 = max(z, w);
vec<L, U, Q> Result;
for(length_t i = 0, n = Result.length(); i < n; ++i)
{
U Result1 = x > y ? a[i] : b[i];
U Result2 = z > w ? c[i] : d[i];
Result[i] = Test1 > Test2 ? Result1 : Result2;
}
return Result;
}
// Max comparison between 4 variables
template<length_t L, typename T, typename U, qualifier Q>
GLM_FUNC_QUALIFIER vec<L, U, Q> associatedMax
(
vec<L, T, Q> const& x, U a,
vec<L, T, Q> const& y, U b,
vec<L, T, Q> const& z, U c,
vec<L, T, Q> const& w, U d
)
{
vec<L, U, Q> Result;
for(length_t i = 0, n = Result.length(); i < n; ++i)
{
T Test1 = max(x[i], y[i]);
T Test2 = max(z[i], w[i]);;
U Result1 = x[i] > y[i] ? a : b;
U Result2 = z[i] > w[i] ? c : d;
Result[i] = Test1 > Test2 ? Result1 : Result2;
}
return Result;
}
}//namespace glm
// CG_REVISION 719c9337e18b5a8d331f5b5580d53f2438ab503f
| [
"brankyy@gmail.com"
] | brankyy@gmail.com |
87d41b45beb678f9e40674ad1ac9a3b21a29725c | 3e568740df6c5db6c2d3574c081b39765f52f0a1 | /DummyChoosers.hpp | 99097156edba3c58eb9d30d770ecc3880a52d602 | [] | no_license | peleg122/BullPgia | 41e07918e4ee8eae60528580d16c11c31c961fb9 | 2b2315f902ac1217fb7871fc0590b05ca8898425 | refs/heads/master | 2020-05-18T11:58:34.431475 | 2019-05-01T19:43:46 | 2019-05-01T19:43:46 | 182,073,772 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 721 | hpp | //
// Created by peleg on 17-Apr-19.
//
#ifndef EX4_DUMMYCHOOSERS_HPP
#define EX4_DUMMYCHOOSERS_HPP
#endif //EX4_DUMMYCHOOSERS_HPP
#pragma once
#include "Chooser.hpp"
using std::string;
/**
* ConstantChooser is a chooser that always chooses the same string.
*/
class ConstantChooser: public bullpgia::Chooser {
string myConstantString;
public:
ConstantChooser(const string& constantString) { myConstantString = constantString; }
string choose(uint length) override {
return myConstantString;
}
};
/**
* RandomChooser is a chooser that chooses a random string.
*/
class RandomChooser: public bullpgia::Chooser {
string choose(uint length) override;
};
| [
"noreply@github.com"
] | noreply@github.com |
f2730e23897bf8420cdca8dc23e1b7679199c31a | 25acc085ba82f786c3f05e43ddc7ceda146d5486 | /interface/src/renderer/VoxelShader.h | 33e8ea0073015b7a19224bd23e1aa69a04680ea8 | [] | no_license | ddobrev/hifi | e4ba44a9b50a1098c0f8d71b82f902e18aa524f6 | 716858e6f69c1487cf6dae3be793a9e8bb4d3412 | refs/heads/master | 2020-04-06T06:43:45.969951 | 2014-04-03T16:45:46 | 2014-04-03T17:09:54 | 17,596,734 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 914 | h | //
// VoxelShader.h
// interface
//
// Created by Brad Hefta-Gaub on 9/23/13.
// Copyright (c) 2013 High Fidelity, Inc. All rights reserved.
//
#ifndef __interface__VoxelShader__
#define __interface__VoxelShader__
#include <QObject>
class ProgramObject;
/// A generic full screen glow effect.
class VoxelShader : public QObject {
Q_OBJECT
public:
VoxelShader();
~VoxelShader();
void init();
/// Starts using the voxel geometry shader effect.
void begin();
/// Stops using the voxel geometry shader effect.
void end();
/// Gets access to attributes from the shader program
int attributeLocation(const char * name) const;
static ProgramObject* createGeometryShaderProgram(const QString& name);
public slots:
private:
bool _initialized;
ProgramObject* _program;
};
#endif /* defined(__interface__VoxelShader__) */
| [
"bradh@konamoxt.com"
] | bradh@konamoxt.com |
6d946242e1bd9497001ffcd232268cbf76434a83 | 694ee82fd32e76c5941c7e64b1406e0ca34e4778 | /isFibo.cpp | 7694fa0b2198a3d24c31338c753121de5abe4255 | [] | no_license | Sri-Vishnu-Kumar-K/CppCode | be788a0748f52ac7428f2aaca5c3b713cb35f3b5 | d49903eb9db38ecbd61d029ce78e526e39b243de | refs/heads/master | 2021-01-21T04:28:17.480447 | 2016-07-05T02:30:31 | 2016-07-05T02:30:31 | 46,414,400 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 402 | cpp | #include<iostream>
using namespace std;
int main(){
int t;
cin>>t;
while(t>0){
int n;
cin>>n;
int a=-1,b=1;
int c=a+b;
while(c<n){
c = a+b;
a = b;
b = c;
}
if(c==n){
cout<<"IsFibo"<<endl;
}else{
cout<<"IsNotFibo"<<endl;
}
t--;
}
return 0;
}
| [
"srivishnukumar.k@gmail.com"
] | srivishnukumar.k@gmail.com |
2615216ce24cffeebcd4ad293fd16b1b5e4b75ec | 0b3f5eea6c5cf7ee1e87c5d59f1d8cf97caa6853 | /src/query/ops/xgrid/XgridArray.cpp | 796cb79110164a025b6d150f0ab0c833bda01549 | [] | no_license | jonghunDB/SciDB | fc04533c9eddd00bcf10ea83b2d0838637daa518 | 20ec3b7785e8e7b149c9b9876c240ab135eed068 | refs/heads/master | 2020-05-07T06:12:21.093476 | 2019-04-17T10:28:07 | 2019-04-17T10:28:07 | 180,303,383 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,713 | cpp | /*
**
* BEGIN_COPYRIGHT
*
* Copyright (C) 2008-2018 SciDB, Inc.
* All Rights Reserved.
*
* SciDB is free software: you can redistribute it and/or modify
* it under the terms of the AFFERO GNU General Public License as published by
* the Free Software Foundation.
*
* SciDB is distributed "AS-IS" AND WITHOUT ANY WARRANTY OF ANY KIND,
* INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* NON-INFRINGEMENT, OR FITNESS FOR A PARTICULAR PURPOSE. See
* the AFFERO GNU General Public License for the complete license terms.
*
* You should have received a copy of the AFFERO GNU General Public License
* along with SciDB. If not, see <http://www.gnu.org/licenses/agpl-3.0.html>
*
* END_COPYRIGHT
*/
/**
* @file XgridArray.cpp
*
* @brief Xgrid array implementation
*
* @author Konstantin Knizhnik <knizhnik@garret.ru>
*/
#include <system/Exceptions.h>
#include "XgridArray.h"
using namespace boost;
using namespace std;
namespace scidb
{
//
// Xgrid chunk iterator methods
//
int XgridChunkIterator::getMode() const
{
return mode;
}
void XgridChunkIterator::restart()
{
outPos = first;
outPos[outPos.size()-1] -= 1;
hasCurrent = true;
++(*this);
}
void XgridChunkIterator::operator++()
{
size_t nDims = outPos.size();
while (true) {
size_t i = nDims-1;
while (++outPos[i] > last[i]) {
if (i == 0) {
hasCurrent = false;
return;
}
outPos[i] = first[i];
i -= 1;
}
array.out2in(outPos, inPos);
if (inputIterator->setPosition(inPos)) {
hasCurrent = true;
return;
}
}
}
bool XgridChunkIterator::setPosition(Coordinates const& newPos)
{
array.out2in(newPos, inPos);
outPos = newPos;
if (inputIterator->setPosition(inPos)) {
return hasCurrent = true;
}
return hasCurrent = false;
}
Coordinates const& XgridChunkIterator::getPosition()
{
if (!hasCurrent)
throw USER_EXCEPTION(SCIDB_SE_EXECUTION, SCIDB_LE_NO_CURRENT_ELEMENT);
return outPos;
}
Value const& XgridChunkIterator::getItem()
{
if (!hasCurrent)
throw USER_EXCEPTION(SCIDB_SE_EXECUTION, SCIDB_LE_NO_CURRENT_ELEMENT);
return inputIterator->getItem();
}
bool XgridChunkIterator::end()
{
return !hasCurrent;
}
bool XgridChunkIterator::isEmpty() const
{
if (!hasCurrent)
throw USER_EXCEPTION(SCIDB_SE_EXECUTION, SCIDB_LE_NO_CURRENT_ELEMENT);
return inputIterator->isEmpty();
}
ConstChunk const& XgridChunkIterator::getChunk()
{
return chunk;
}
XgridChunkIterator::XgridChunkIterator(XgridArray const& arr, XgridChunk const& chk, int iterationMode)
: array(arr),
chunk(chk),
outPos(arr.getArrayDesc().getDimensions().size()),
inPos(outPos.size()),
first(chunk.getFirstPosition(!(iterationMode & IGNORE_OVERLAPS))),
last(chunk.getLastPosition(!(iterationMode & IGNORE_OVERLAPS))),
inputIterator(chunk.getArrayIterator().getInputIterator()->getChunk().getConstIterator(iterationMode & ~INTENDED_TILE_MODE)),
mode(iterationMode)
{
restart();
}
//
// Xgrid chunk methods
//
std::shared_ptr<ConstChunkIterator> XgridChunk::getConstIterator(int iterationMode) const
{
return std::shared_ptr<ConstChunkIterator>(new XgridChunkIterator(array, *this, iterationMode));
}
void XgridChunk::initialize(Coordinates const& pos)
{
ArrayDesc const& desc = array.getArrayDesc();
Address addr(attrID, pos);
chunk.initialize(&array, &desc, addr, desc.getAttributes()[attrID].getDefaultCompressionMethod());
setInputChunk(chunk);
}
XgridChunk::XgridChunk(XgridArray const& arr, DelegateArrayIterator const& iterator, AttributeID attrID)
: DelegateChunk(arr, iterator, attrID, false),
array(arr)
{
}
//
// Xgrid array iterator
//
ConstChunk const& XgridArrayIterator::getChunk()
{
if (!chunkInitialized) {
((XgridChunk&)*chunk).initialize(getPosition());
chunkInitialized = true;
}
return *chunk;
}
Coordinates const& XgridArrayIterator::getPosition()
{
array.in2out(inputIterator->getPosition(), outPos);
return outPos;
}
bool XgridArrayIterator::setPosition(Coordinates const& newPos)
{
chunkInitialized = false;
outPos = newPos;
array.getArrayDesc().getChunkPositionFor(outPos);
array.out2in(outPos, inPos);
return inputIterator->setPosition(inPos);
}
XgridArrayIterator::XgridArrayIterator(XgridArray const& arr,
AttributeID attrID,
std::shared_ptr<ConstArrayIterator> inputIterator)
: DelegateArrayIterator(arr, attrID, inputIterator),
array(arr),
inPos(arr.getArrayDesc().getDimensions().size()),
outPos(inPos.size())
{
}
//
// Xgrid array methods
//
void XgridArray::out2in(Coordinates const& outPos, Coordinates& inPos) const
{
Dimensions const& dims = desc.getDimensions();
for (size_t i = 0, n = outPos.size(); i < n; i++) {
inPos[i] = dims[i].getStartMin() + (outPos[i] - dims[i].getStartMin()) / scale[i];
}
}
void XgridArray::in2out(Coordinates const& inPos, Coordinates& outPos) const
{
Dimensions const& dims = desc.getDimensions();
for (size_t i = 0, n = inPos.size(); i < n; i++) {
outPos[i] = dims[i].getStartMin() + (inPos[i] - dims[i].getStartMin()) * scale[i];
}
}
DelegateChunk* XgridArray::createChunk(DelegateArrayIterator const* iterator, AttributeID id) const
{
return new XgridChunk(*this, *iterator, id);
}
DelegateArrayIterator* XgridArray::createArrayIterator(AttributeID id) const
{
return new XgridArrayIterator(*this, id, inputArray->getConstIterator(id));
}
XgridArray::XgridArray(ArrayDesc const& desc, std::shared_ptr<Array> const& array)
: DelegateArray(desc, array),
scale(desc.getDimensions().size())
{
Dimensions const& oldDims = array->getArrayDesc().getDimensions();
Dimensions const& newDims = desc.getDimensions();
for (size_t i = 0, n = newDims.size(); i < n; i++) {
scale[i] = newDims[i].getLength() / oldDims[i].getLength();
}
}
std::shared_ptr<Array> XgridArray::create(ArrayDesc const& partlyScaledDesc,
std::vector<int32_t> const& scaleFactors,
std::shared_ptr<Array>& inputArray)
{
// Easy case: no late scaling to perform.
if (scaleFactors.empty()) {
return std::shared_ptr<Array>(new XgridArray(partlyScaledDesc, inputArray));
}
// Need to build a new set of scaled dimensions. We rely on scaleFactors being all 1 for
// already-scaled dimensions.
//
Dimensions const& psDims = partlyScaledDesc.getDimensions();
Dimensions const& inputDims = inputArray->getArrayDesc().getDimensions();
size_t const nDims = psDims.size();
Dimensions newDims(nDims);
int64_t chunkInterval;
for (size_t i = 0; i < nDims; ++i) {
newDims[i] = psDims[i];
if (scaleFactors[i] == 1) {
// This is one of the already-scaled dimensions.
chunkInterval = psDims[i].getChunkInterval();
} else {
// Late scaling needed for this autochunked dimension.
SCIDB_ASSERT(psDims[i].isAutochunked());
chunkInterval = inputDims[i].getChunkInterval() * scaleFactors[i];
}
newDims[i].setChunkInterval(chunkInterval);
}
return std::shared_ptr<Array>(new XgridArray(ArrayDesc(
partlyScaledDesc.getName(),
partlyScaledDesc.getAttributes(),
newDims,
partlyScaledDesc.getDistribution(),
partlyScaledDesc.getResidency()),
inputArray));
}
} // namespace
| [
"jonghun2931@gmail.com"
] | jonghun2931@gmail.com |
246182de4b0c5ccc6e86e8995b7a813216af591a | d651cc5259ca8918d7260a367c1ba1abe04b4329 | /Offwind.App/Offwind.Sowfa/Constant/TurbineArrayPropertiesFAST/TemplateGeneral | fa772b1b4b6c26a79fd86ceea72814084e6e09b8 | [] | no_license | OffWind/offwind | 856e5e8224d8be1d76a84e3a8f08fc4ee8b1deb3 | 5078db4518ff10b3a3a17eaa0e5856ed0a5797dd | refs/heads/master | 2020-03-29T11:51:27.803974 | 2015-04-02T03:35:49 | 2015-04-02T03:35:49 | 6,810,740 | 4 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 1,180 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 1.6 |
| \\ / A nd | Web: http://www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class dictionary;
object turbineArrayProperties;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
general
{
yawAngle ({[[yawAngle]]});
numberofBld ({[[numberofBld]]});
numberofBldPts ({[[numberofBldPts]]});
rotorDiameter ({[[rotorDiameter]]});
epsilon ({[[epsilon]]});
smearRadius ({[[smearRadius]]});
effectiveRadiusFactor ({[[effectiveRadiusFactor]]});
pointInterpType ({[[pointInterpType]]});
}
| [
"vlad.ogay@nrg-soft.com"
] | vlad.ogay@nrg-soft.com | |
987240b4f2217921d49bb73173968adfa8fa02b3 | 277cd50676b8f06f048387c615ffaa5ca6657e64 | /paddle/gserver/tests/test_MKLDNN.cpp | 1bfbbde4246a10eaf86693a6a2f237f390966db3 | [
"Apache-2.0"
] | permissive | AI-books/Paddle | b0793a3fdd6443181f94e9de01616bd51a593146 | 5b5f4f514047975ac09ec42b31e46dabf235e7dd | refs/heads/develop | 2021-07-03T19:39:20.265770 | 2017-09-24T17:42:18 | 2017-09-24T17:42:18 | 104,689,849 | 0 | 1 | null | 2017-09-25T01:29:11 | 2017-09-25T01:29:10 | null | UTF-8 | C++ | false | false | 8,434 | cpp | /* Copyright (c) 2017 PaddlePaddle Authors. All Rights Reserve.
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 <gtest/gtest.h>
#include <string>
#include <vector>
#include "MKLDNNTester.h"
#include "ModelConfig.pb.h"
#include "paddle/gserver/activations/MKLDNNActivation.h"
#include "paddle/math/MathUtils.h"
using namespace paddle; // NOLINT
DECLARE_bool(thread_local_rand_use_global_seed);
DECLARE_bool(use_gpu);
DECLARE_bool(use_mkldnn);
#define RUN_MKLDNN_TEST(DNN_CONFIG, REF_CONFIG, DESC) \
MKLDNNTester tester; \
for (auto bs : {DESC.bs, 1}) { \
tester.run(DNN_CONFIG, REF_CONFIG, bs, DESC.ih, DESC.iw); \
}
#define RUN_MKLDNN_TEST_LAYER(DNN_CONFIG, REF_TYPE, DESC) \
TestConfig ref = DNN_CONFIG; \
ref.layerConfig.set_type(REF_TYPE); \
RUN_MKLDNN_TEST(DNN_CONFIG, ref, DESC)
struct testFcDesc {
int bs;
int ic;
int oc;
int ih, iw; // oh == ow == 1
};
static void getMKLDNNFcConfig(TestConfig& cfg, const testFcDesc& pm) {
cfg.layerConfig.set_type("mkldnn_fc");
cfg.layerConfig.set_size(pm.oc);
cfg.inputDefs.push_back(
{INPUT_DATA,
"layer_0",
/* size of input layer= */ size_t(pm.ic * pm.ih * pm.iw),
/* size of weight= */ size_t(pm.oc * pm.ic * pm.ih * pm.iw)});
cfg.layerConfig.add_inputs();
}
void testFcLayer(const testFcDesc& pm) {
TestConfig dnnConfig;
getMKLDNNFcConfig(dnnConfig, pm);
for (auto biasSize : {pm.oc, 0}) {
dnnConfig.biasSize = biasSize;
RUN_MKLDNN_TEST_LAYER(dnnConfig, "fc", pm)
}
}
TEST(MKLDNNLayer, FcLayer) {
/* bs, ic, ih, iw, oc */
testFcLayer({2, 2, 1, 1, 3});
testFcLayer({3, 7, 1, 1, 19});
testFcLayer({8, 16, 13, 13, 32});
testFcLayer({4, 12, 13, 13, 18});
testFcLayer({2, 64, 16, 16, 32});
testFcLayer({15, 3, 16, 16, 6});
}
struct testConvDesc {
int bs, gp;
int ic, ih, iw;
int oc, oh, ow;
int fh, fw;
int ph, pw;
int sh, sw;
int dh, dw;
};
static void getMKLDNNConvConfig(TestConfig& cfg, const testConvDesc& pm) {
cfg.layerConfig.set_type("mkldnn_conv");
cfg.layerConfig.set_num_filters(pm.oc);
cfg.layerConfig.set_size(pm.oc * pm.oh * pm.ow);
cfg.layerConfig.set_shared_biases(true);
cfg.inputDefs.push_back(
{INPUT_DATA,
"layer_0",
/* size of input layer= */ size_t(pm.ic * pm.ih * pm.iw),
/* size of weight= */ size_t(pm.oc * pm.ic * pm.fh * pm.fw / pm.gp)});
LayerInputConfig* input = cfg.layerConfig.add_inputs();
ConvConfig* conv = input->mutable_conv_conf();
conv->set_groups(pm.gp);
conv->set_img_size(pm.iw);
conv->set_img_size_y(pm.ih);
conv->set_output_x(pm.ow);
conv->set_output_y(pm.oh);
conv->set_filter_size(pm.fw);
conv->set_filter_size_y(pm.fh);
conv->set_channels(pm.ic);
conv->set_padding(pm.pw);
conv->set_padding_y(pm.ph);
conv->set_stride(pm.sw);
conv->set_stride_y(pm.sh);
conv->set_dilation(pm.dw);
conv->set_dilation_y(pm.dh);
conv->set_caffe_mode(true);
conv->set_filter_channels(conv->channels() / conv->groups());
CHECK_EQ(conv->filter_channels() * pm.gp, conv->channels())
<< "it is indivisible";
int fh = (pm.fh - 1) * pm.dh + 1;
int fw = (pm.fw - 1) * pm.dw + 1;
int ow = outputSize(pm.iw, fw, pm.pw, pm.sw, true);
int oh = outputSize(pm.ih, fh, pm.ph, pm.sh, true);
CHECK_EQ(ow, pm.ow) << "output size check failed";
CHECK_EQ(oh, pm.oh) << "output size check failed";
}
void testConvLayer(const testConvDesc& pm) {
TestConfig dnnConfig;
getMKLDNNConvConfig(dnnConfig, pm);
for (auto biasSize : {pm.oc, 0}) {
dnnConfig.biasSize = biasSize;
RUN_MKLDNN_TEST_LAYER(dnnConfig, "exconv", pm)
}
}
TEST(MKLDNNLayer, ConvLayer) {
/* bs, gp, ic, ih, iw, oc, oh, ow, fh, fw, ph, pw, sh, sw, dh, dw */
testConvLayer({2, 1, 3, 32, 32, 16, 32, 32, 3, 3, 1, 1, 1, 1, 1, 1});
testConvLayer({2, 1, 8, 16, 16, 8, 16, 16, 3, 3, 1, 1, 1, 1, 1, 1});
testConvLayer({3, 1, 16, 32, 32, 3, 32, 32, 3, 3, 1, 1, 1, 1, 1, 1});
testConvLayer({8, 1, 16, 18, 18, 32, 18, 18, 3, 3, 1, 1, 1, 1, 1, 1});
testConvLayer({16, 1, 1, 42, 31, 32, 23, 11, 4, 5, 3, 2, 2, 3, 1, 1});
testConvLayer({2, 1, 8, 16, 16, 8, 8, 8, 3, 3, 1, 1, 2, 2, 1, 1});
testConvLayer({3, 1, 8, 13, 13, 8, 7, 7, 3, 3, 1, 1, 2, 2, 1, 1});
// with groups
testConvLayer({2, 2, 4, 5, 5, 8, 5, 5, 3, 3, 1, 1, 1, 1, 1, 1});
testConvLayer({2, 3, 3, 5, 5, 3, 5, 5, 3, 3, 1, 1, 1, 1, 1, 1});
testConvLayer({4, 4, 16, 3, 3, 16, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1});
}
struct testPoolDesc {
int bs, ic; // input channel and output channel are the same
int ih, iw;
int oh, ow;
int fh, fw;
int ph, pw;
int sh, sw;
};
static void getMKLDNNPoolConfig(TestConfig& cfg, const testPoolDesc& pm) {
cfg.layerConfig.set_type("mkldnn_pool");
cfg.layerConfig.set_size(pm.ic * pm.oh * pm.ow);
cfg.inputDefs.push_back(
{INPUT_DATA,
"layer_0",
/* size of input layer= */ size_t(pm.ic * pm.ih * pm.iw),
0});
LayerInputConfig* input = cfg.layerConfig.add_inputs();
PoolConfig* pool = input->mutable_pool_conf();
pool->set_pool_type("avg-projection");
pool->set_channels(pm.ic);
pool->set_img_size(pm.iw);
pool->set_img_size_y(pm.ih);
pool->set_output_x(pm.ow);
pool->set_output_y(pm.oh);
pool->set_size_x(pm.fw);
pool->set_size_y(pm.fh);
pool->set_padding(pm.pw);
pool->set_padding_y(pm.ph);
pool->set_stride(pm.sw);
pool->set_stride_y(pm.sh);
int oh = outputSize(pm.ih, pm.fh, pm.ph, pm.sh, false);
int ow = outputSize(pm.iw, pm.fw, pm.pw, pm.sw, false);
CHECK_EQ(ow, pm.ow) << "output size check failed";
CHECK_EQ(oh, pm.oh) << "output size check failed";
}
void testPoolLayer(const testPoolDesc& pm) {
TestConfig dnnConfig;
getMKLDNNPoolConfig(dnnConfig, pm);
LayerInputConfig* input = dnnConfig.layerConfig.mutable_inputs(0);
PoolConfig* pool = input->mutable_pool_conf();
for (auto type : {"max-projection", "avg-projection"}) {
pool->set_pool_type(type);
RUN_MKLDNN_TEST_LAYER(dnnConfig, "pool", pm)
}
}
TEST(MKLDNNLayer, PoolLayer) {
/* bs, ch, ih, iw, oh, ow, fh, fw, ph, pw, sh, sw */
testPoolLayer({2, 1, 4, 4, 2, 2, 3, 3, 0, 0, 2, 2});
testPoolLayer({10, 8, 16, 16, 8, 8, 2, 2, 0, 0, 2, 2});
testPoolLayer({4, 2, 5, 5, 3, 3, 3, 3, 1, 1, 2, 2});
testPoolLayer({8, 16, 56, 56, 28, 28, 3, 3, 0, 0, 2, 2});
testPoolLayer({8, 16, 14, 14, 7, 7, 3, 3, 0, 0, 2, 2});
testPoolLayer({4, 16, 7, 7, 1, 1, 7, 7, 0, 0, 1, 1});
testPoolLayer({4, 2, 5, 5, 3, 3, 5, 5, 1, 1, 1, 1});
testPoolLayer({2, 8, 56, 56, 29, 29, 3, 3, 1, 1, 2, 2});
}
struct testActDesc {
int bs, ic, ih, iw;
};
static void getAddtoConfig(TestConfig& cfg, const testActDesc& pm) {
cfg.biasSize = 0;
cfg.layerConfig.set_type("addto");
size_t layerSize = pm.ih * pm.ih * pm.iw;
cfg.layerConfig.set_size(layerSize);
cfg.inputDefs.push_back({INPUT_DATA, "layer_0", layerSize, 0});
cfg.layerConfig.add_inputs();
}
void testActivation(std::string& actType, const testActDesc& pm) {
// TODO(TJ): mkldnn_softmax not implemented, paddle do not have elu activation
if (actType == "mkldnn_softmax" || actType == "mkldnn_elu") {
return;
}
const std::string compareTypes[] = {actType, actType.erase(0, 7)};
TestConfig cfg;
getAddtoConfig(cfg, pm);
TestConfig ref = cfg;
cfg.layerConfig.set_active_type(compareTypes[0]);
ref.layerConfig.set_active_type(compareTypes[1]);
RUN_MKLDNN_TEST(cfg, ref, pm)
}
TEST(MKLDNNActivation, Activations) {
auto types = MKLDNNActivation::getAllRegisteredTypes();
for (auto type : types) {
/* bs, c, h, w*/
testActivation(type, {16, 64, 32, 32});
}
}
// TODO(TJ): add branch test
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
FLAGS_use_gpu = false;
FLAGS_use_mkldnn = true;
initMain(argc, argv);
FLAGS_thread_local_rand_use_global_seed = true;
srand(1);
return RUN_ALL_TESTS();
}
| [
"jian.j.tang@intel.com"
] | jian.j.tang@intel.com |
37a660977e7a18c81322e6a2ea8e20974c852d54 | fafdffb04c55fffdcb874ee24224daac0ed4f435 | /src/qt/forms/ui_overviewpage.h | 5e948862e0c81cd932a734bd8257b903a351950b | [
"MIT"
] | permissive | yarsanich/divi-coin | 1c251ccb3506734b387bf60520f16f12a0098d92 | d3371db472c6b37c0b76c4d9aac172b2e636e625 | refs/heads/master | 2021-01-01T17:35:51.022921 | 2017-07-23T16:13:56 | 2017-07-23T16:13:56 | 98,109,658 | 0 | 0 | null | 2017-07-23T16:08:53 | 2017-07-23T16:08:53 | null | UTF-8 | C++ | false | false | 32,194 | h | /********************************************************************************
** Form generated from reading UI file 'overviewpage.ui'
**
** Created by: Qt User Interface Compiler version 5.9.1
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_OVERVIEWPAGE_H
#define UI_OVERVIEWPAGE_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QFormLayout>
#include <QtWidgets/QFrame>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QListView>
#include <QtWidgets/QProgressBar>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_OverviewPage
{
public:
QVBoxLayout *topLayout;
QLabel *labelAlerts;
QHBoxLayout *horizontalLayout;
QVBoxLayout *verticalLayout_2;
QFrame *frame;
QVBoxLayout *verticalLayout_4;
QHBoxLayout *horizontalLayout_4;
QLabel *label_5;
QLabel *labelWalletStatus;
QSpacerItem *horizontalSpacer_3;
QGridLayout *gridLayout;
QLabel *labelWatchPending;
QLabel *labelUnconfirmed;
QLabel *labelWatchImmature;
QFrame *lineSpendableBalance;
QFrame *lineWatchBalance;
QLabel *labelTotalText;
QLabel *labelImmature;
QSpacerItem *horizontalSpacer_2;
QLabel *labelImmatureText;
QLabel *labelTotal;
QLabel *labelWatchTotal;
QLabel *labelWatchonly;
QLabel *labelBalanceText;
QLabel *labelBalance;
QLabel *labelWatchAvailable;
QLabel *labelPendingText;
QLabel *labelSpendable;
QFrame *frameObfuscation;
QWidget *formLayoutWidget;
QFormLayout *formLayout;
QLabel *label_6;
QLabel *label_7;
QProgressBar *obfuscationProgress;
QLabel *labelAnonymizedText;
QLabel *labelAnonymized;
QLabel *label_8;
QLabel *labelAmountRounds;
QLabel *label_9;
QLabel *labelSubmittedDenom;
QLabel *obfuscationEnabled;
QPushButton *runAutoDenom;
QPushButton *toggleObfuscation;
QFrame *lineLastMessage;
QLabel *obfuscationStatus;
QPushButton *obfuscationAuto;
QPushButton *obfuscationReset;
QWidget *layoutWidget;
QHBoxLayout *horizontalLayout_5;
QLabel *label_2;
QLabel *labelObfuscationSyncStatus;
QSpacerItem *horizontalSpacer_4;
QSpacerItem *verticalSpacer;
QVBoxLayout *verticalLayout_3;
QFrame *frame_2;
QVBoxLayout *verticalLayout;
QSpacerItem *verticalSpacer_3;
QHBoxLayout *horizontalLayout_2;
QLabel *label_4;
QLabel *labelTransactionsStatus;
QSpacerItem *horizontalSpacer;
QListView *listTransactions;
QSpacerItem *verticalSpacer_2;
void setupUi(QWidget *OverviewPage)
{
if (OverviewPage->objectName().isEmpty())
OverviewPage->setObjectName(QStringLiteral("OverviewPage"));
OverviewPage->resize(960, 615);
OverviewPage->setMinimumSize(QSize(960, 0));
topLayout = new QVBoxLayout(OverviewPage);
topLayout->setObjectName(QStringLiteral("topLayout"));
labelAlerts = new QLabel(OverviewPage);
labelAlerts->setObjectName(QStringLiteral("labelAlerts"));
labelAlerts->setVisible(false);
labelAlerts->setStyleSheet(QStringLiteral("background-color: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0, stop:0 #F0D0A0, stop:1 #F8D488); color:#000000;"));
labelAlerts->setWordWrap(true);
labelAlerts->setMargin(3);
topLayout->addWidget(labelAlerts);
horizontalLayout = new QHBoxLayout();
horizontalLayout->setObjectName(QStringLiteral("horizontalLayout"));
verticalLayout_2 = new QVBoxLayout();
verticalLayout_2->setObjectName(QStringLiteral("verticalLayout_2"));
frame = new QFrame(OverviewPage);
frame->setObjectName(QStringLiteral("frame"));
frame->setFrameShape(QFrame::StyledPanel);
frame->setFrameShadow(QFrame::Raised);
verticalLayout_4 = new QVBoxLayout(frame);
verticalLayout_4->setObjectName(QStringLiteral("verticalLayout_4"));
horizontalLayout_4 = new QHBoxLayout();
horizontalLayout_4->setObjectName(QStringLiteral("horizontalLayout_4"));
label_5 = new QLabel(frame);
label_5->setObjectName(QStringLiteral("label_5"));
QFont font;
font.setBold(true);
font.setWeight(75);
label_5->setFont(font);
horizontalLayout_4->addWidget(label_5);
labelWalletStatus = new QLabel(frame);
labelWalletStatus->setObjectName(QStringLiteral("labelWalletStatus"));
labelWalletStatus->setCursor(QCursor(Qt::WhatsThisCursor));
labelWalletStatus->setStyleSheet(QStringLiteral("QLabel { color: red; }"));
labelWalletStatus->setText(QStringLiteral("(out of sync)"));
labelWalletStatus->setAlignment(Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter);
horizontalLayout_4->addWidget(labelWalletStatus);
horizontalSpacer_3 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_4->addItem(horizontalSpacer_3);
verticalLayout_4->addLayout(horizontalLayout_4);
gridLayout = new QGridLayout();
gridLayout->setSpacing(12);
gridLayout->setObjectName(QStringLiteral("gridLayout"));
labelWatchPending = new QLabel(frame);
labelWatchPending->setObjectName(QStringLiteral("labelWatchPending"));
labelWatchPending->setFont(font);
labelWatchPending->setCursor(QCursor(Qt::IBeamCursor));
labelWatchPending->setText(QString::fromUtf8("0.000\342\200\211000\342\200\21100 BTC"));
labelWatchPending->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);
labelWatchPending->setTextInteractionFlags(Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse);
gridLayout->addWidget(labelWatchPending, 2, 2, 1, 1);
labelUnconfirmed = new QLabel(frame);
labelUnconfirmed->setObjectName(QStringLiteral("labelUnconfirmed"));
labelUnconfirmed->setFont(font);
labelUnconfirmed->setCursor(QCursor(Qt::IBeamCursor));
labelUnconfirmed->setText(QString::fromUtf8("0.000\342\200\211000\342\200\21100 BTC"));
labelUnconfirmed->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);
labelUnconfirmed->setTextInteractionFlags(Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse);
gridLayout->addWidget(labelUnconfirmed, 2, 1, 1, 1);
labelWatchImmature = new QLabel(frame);
labelWatchImmature->setObjectName(QStringLiteral("labelWatchImmature"));
labelWatchImmature->setFont(font);
labelWatchImmature->setCursor(QCursor(Qt::IBeamCursor));
labelWatchImmature->setText(QString::fromUtf8("0.000\342\200\211000\342\200\21100 BTC"));
labelWatchImmature->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);
labelWatchImmature->setTextInteractionFlags(Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse);
gridLayout->addWidget(labelWatchImmature, 3, 2, 1, 1);
lineSpendableBalance = new QFrame(frame);
lineSpendableBalance->setObjectName(QStringLiteral("lineSpendableBalance"));
lineSpendableBalance->setFrameShape(QFrame::HLine);
lineSpendableBalance->setFrameShadow(QFrame::Sunken);
gridLayout->addWidget(lineSpendableBalance, 4, 0, 1, 2);
lineWatchBalance = new QFrame(frame);
lineWatchBalance->setObjectName(QStringLiteral("lineWatchBalance"));
QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(lineWatchBalance->sizePolicy().hasHeightForWidth());
lineWatchBalance->setSizePolicy(sizePolicy);
lineWatchBalance->setMinimumSize(QSize(140, 0));
lineWatchBalance->setFrameShape(QFrame::HLine);
lineWatchBalance->setFrameShadow(QFrame::Sunken);
gridLayout->addWidget(lineWatchBalance, 4, 2, 1, 1);
labelTotalText = new QLabel(frame);
labelTotalText->setObjectName(QStringLiteral("labelTotalText"));
gridLayout->addWidget(labelTotalText, 5, 0, 1, 1);
labelImmature = new QLabel(frame);
labelImmature->setObjectName(QStringLiteral("labelImmature"));
labelImmature->setFont(font);
labelImmature->setCursor(QCursor(Qt::IBeamCursor));
labelImmature->setText(QString::fromUtf8("0.000\342\200\211000\342\200\21100 BTC"));
labelImmature->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);
labelImmature->setTextInteractionFlags(Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse);
gridLayout->addWidget(labelImmature, 3, 1, 1, 1);
horizontalSpacer_2 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
gridLayout->addItem(horizontalSpacer_2, 2, 3, 1, 1);
labelImmatureText = new QLabel(frame);
labelImmatureText->setObjectName(QStringLiteral("labelImmatureText"));
gridLayout->addWidget(labelImmatureText, 3, 0, 1, 1);
labelTotal = new QLabel(frame);
labelTotal->setObjectName(QStringLiteral("labelTotal"));
labelTotal->setFont(font);
labelTotal->setCursor(QCursor(Qt::IBeamCursor));
labelTotal->setText(QString::fromUtf8("0.000\342\200\211000\342\200\21100 BTC"));
labelTotal->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);
labelTotal->setTextInteractionFlags(Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse);
gridLayout->addWidget(labelTotal, 5, 1, 1, 1);
labelWatchTotal = new QLabel(frame);
labelWatchTotal->setObjectName(QStringLiteral("labelWatchTotal"));
labelWatchTotal->setFont(font);
labelWatchTotal->setCursor(QCursor(Qt::IBeamCursor));
labelWatchTotal->setText(QString::fromUtf8("0.000\342\200\211000\342\200\21100 BTC"));
labelWatchTotal->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);
labelWatchTotal->setTextInteractionFlags(Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse);
gridLayout->addWidget(labelWatchTotal, 5, 2, 1, 1);
labelWatchonly = new QLabel(frame);
labelWatchonly->setObjectName(QStringLiteral("labelWatchonly"));
labelWatchonly->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);
gridLayout->addWidget(labelWatchonly, 0, 2, 1, 1);
labelBalanceText = new QLabel(frame);
labelBalanceText->setObjectName(QStringLiteral("labelBalanceText"));
gridLayout->addWidget(labelBalanceText, 1, 0, 1, 1);
labelBalance = new QLabel(frame);
labelBalance->setObjectName(QStringLiteral("labelBalance"));
labelBalance->setFont(font);
labelBalance->setCursor(QCursor(Qt::IBeamCursor));
labelBalance->setText(QString::fromUtf8("0.000\342\200\211000\342\200\21100 BTC"));
labelBalance->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);
labelBalance->setTextInteractionFlags(Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse);
gridLayout->addWidget(labelBalance, 1, 1, 1, 1);
labelWatchAvailable = new QLabel(frame);
labelWatchAvailable->setObjectName(QStringLiteral("labelWatchAvailable"));
labelWatchAvailable->setFont(font);
labelWatchAvailable->setCursor(QCursor(Qt::IBeamCursor));
labelWatchAvailable->setText(QString::fromUtf8("0.000\342\200\211000\342\200\21100 BTC"));
labelWatchAvailable->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);
labelWatchAvailable->setTextInteractionFlags(Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse);
gridLayout->addWidget(labelWatchAvailable, 1, 2, 1, 1);
labelPendingText = new QLabel(frame);
labelPendingText->setObjectName(QStringLiteral("labelPendingText"));
gridLayout->addWidget(labelPendingText, 2, 0, 1, 1);
labelSpendable = new QLabel(frame);
labelSpendable->setObjectName(QStringLiteral("labelSpendable"));
labelSpendable->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);
gridLayout->addWidget(labelSpendable, 0, 1, 1, 1);
verticalLayout_4->addLayout(gridLayout);
verticalLayout_2->addWidget(frame);
frameObfuscation = new QFrame(OverviewPage);
frameObfuscation->setObjectName(QStringLiteral("frameObfuscation"));
frameObfuscation->setMinimumSize(QSize(0, 350));
frameObfuscation->setLayoutDirection(Qt::LeftToRight);
frameObfuscation->setFrameShape(QFrame::StyledPanel);
frameObfuscation->setFrameShadow(QFrame::Raised);
formLayoutWidget = new QWidget(frameObfuscation);
formLayoutWidget->setObjectName(QStringLiteral("formLayoutWidget"));
formLayoutWidget->setGeometry(QRect(10, 40, 451, 161));
formLayout = new QFormLayout(formLayoutWidget);
formLayout->setObjectName(QStringLiteral("formLayout"));
formLayout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow);
formLayout->setHorizontalSpacing(11);
formLayout->setVerticalSpacing(12);
formLayout->setContentsMargins(0, 0, 0, 0);
label_6 = new QLabel(formLayoutWidget);
label_6->setObjectName(QStringLiteral("label_6"));
formLayout->setWidget(0, QFormLayout::LabelRole, label_6);
label_7 = new QLabel(formLayoutWidget);
label_7->setObjectName(QStringLiteral("label_7"));
formLayout->setWidget(1, QFormLayout::LabelRole, label_7);
obfuscationProgress = new QProgressBar(formLayoutWidget);
obfuscationProgress->setObjectName(QStringLiteral("obfuscationProgress"));
obfuscationProgress->setMaximumSize(QSize(154, 16777215));
obfuscationProgress->setValue(0);
formLayout->setWidget(1, QFormLayout::FieldRole, obfuscationProgress);
labelAnonymizedText = new QLabel(formLayoutWidget);
labelAnonymizedText->setObjectName(QStringLiteral("labelAnonymizedText"));
formLayout->setWidget(2, QFormLayout::LabelRole, labelAnonymizedText);
labelAnonymized = new QLabel(formLayoutWidget);
labelAnonymized->setObjectName(QStringLiteral("labelAnonymized"));
labelAnonymized->setFont(font);
labelAnonymized->setText(QStringLiteral("0 PIV"));
formLayout->setWidget(2, QFormLayout::FieldRole, labelAnonymized);
label_8 = new QLabel(formLayoutWidget);
label_8->setObjectName(QStringLiteral("label_8"));
formLayout->setWidget(3, QFormLayout::LabelRole, label_8);
labelAmountRounds = new QLabel(formLayoutWidget);
labelAmountRounds->setObjectName(QStringLiteral("labelAmountRounds"));
formLayout->setWidget(3, QFormLayout::FieldRole, labelAmountRounds);
label_9 = new QLabel(formLayoutWidget);
label_9->setObjectName(QStringLiteral("label_9"));
formLayout->setWidget(4, QFormLayout::LabelRole, label_9);
labelSubmittedDenom = new QLabel(formLayoutWidget);
labelSubmittedDenom->setObjectName(QStringLiteral("labelSubmittedDenom"));
formLayout->setWidget(4, QFormLayout::FieldRole, labelSubmittedDenom);
obfuscationEnabled = new QLabel(formLayoutWidget);
obfuscationEnabled->setObjectName(QStringLiteral("obfuscationEnabled"));
formLayout->setWidget(0, QFormLayout::FieldRole, obfuscationEnabled);
runAutoDenom = new QPushButton(frameObfuscation);
runAutoDenom->setObjectName(QStringLiteral("runAutoDenom"));
runAutoDenom->setGeometry(QRect(251, 17, 1, 1));
QPalette palette;
QBrush brush(QColor(0, 0, 0, 255));
brush.setStyle(Qt::SolidPattern);
palette.setBrush(QPalette::Active, QPalette::WindowText, brush);
QBrush brush1(QColor(239, 238, 238, 255));
brush1.setStyle(Qt::SolidPattern);
palette.setBrush(QPalette::Active, QPalette::Button, brush1);
QBrush brush2(QColor(255, 255, 255, 255));
brush2.setStyle(Qt::SolidPattern);
palette.setBrush(QPalette::Active, QPalette::Light, brush2);
QBrush brush3(QColor(247, 246, 246, 255));
brush3.setStyle(Qt::SolidPattern);
palette.setBrush(QPalette::Active, QPalette::Midlight, brush3);
QBrush brush4(QColor(119, 119, 119, 255));
brush4.setStyle(Qt::SolidPattern);
palette.setBrush(QPalette::Active, QPalette::Dark, brush4);
QBrush brush5(QColor(159, 159, 159, 255));
brush5.setStyle(Qt::SolidPattern);
palette.setBrush(QPalette::Active, QPalette::Mid, brush5);
palette.setBrush(QPalette::Active, QPalette::Text, brush);
palette.setBrush(QPalette::Active, QPalette::BrightText, brush2);
palette.setBrush(QPalette::Active, QPalette::ButtonText, brush);
palette.setBrush(QPalette::Active, QPalette::Base, brush2);
palette.setBrush(QPalette::Active, QPalette::Window, brush1);
palette.setBrush(QPalette::Active, QPalette::Shadow, brush);
palette.setBrush(QPalette::Active, QPalette::AlternateBase, brush3);
QBrush brush6(QColor(255, 255, 220, 255));
brush6.setStyle(Qt::SolidPattern);
palette.setBrush(QPalette::Active, QPalette::ToolTipBase, brush6);
palette.setBrush(QPalette::Active, QPalette::ToolTipText, brush);
palette.setBrush(QPalette::Inactive, QPalette::WindowText, brush);
palette.setBrush(QPalette::Inactive, QPalette::Button, brush1);
palette.setBrush(QPalette::Inactive, QPalette::Light, brush2);
palette.setBrush(QPalette::Inactive, QPalette::Midlight, brush3);
palette.setBrush(QPalette::Inactive, QPalette::Dark, brush4);
palette.setBrush(QPalette::Inactive, QPalette::Mid, brush5);
palette.setBrush(QPalette::Inactive, QPalette::Text, brush);
palette.setBrush(QPalette::Inactive, QPalette::BrightText, brush2);
palette.setBrush(QPalette::Inactive, QPalette::ButtonText, brush);
palette.setBrush(QPalette::Inactive, QPalette::Base, brush2);
palette.setBrush(QPalette::Inactive, QPalette::Window, brush1);
palette.setBrush(QPalette::Inactive, QPalette::Shadow, brush);
palette.setBrush(QPalette::Inactive, QPalette::AlternateBase, brush3);
palette.setBrush(QPalette::Inactive, QPalette::ToolTipBase, brush6);
palette.setBrush(QPalette::Inactive, QPalette::ToolTipText, brush);
palette.setBrush(QPalette::Disabled, QPalette::WindowText, brush4);
palette.setBrush(QPalette::Disabled, QPalette::Button, brush1);
palette.setBrush(QPalette::Disabled, QPalette::Light, brush2);
palette.setBrush(QPalette::Disabled, QPalette::Midlight, brush3);
palette.setBrush(QPalette::Disabled, QPalette::Dark, brush4);
palette.setBrush(QPalette::Disabled, QPalette::Mid, brush5);
palette.setBrush(QPalette::Disabled, QPalette::Text, brush4);
palette.setBrush(QPalette::Disabled, QPalette::BrightText, brush2);
palette.setBrush(QPalette::Disabled, QPalette::ButtonText, brush4);
palette.setBrush(QPalette::Disabled, QPalette::Base, brush1);
palette.setBrush(QPalette::Disabled, QPalette::Window, brush1);
palette.setBrush(QPalette::Disabled, QPalette::Shadow, brush);
palette.setBrush(QPalette::Disabled, QPalette::AlternateBase, brush1);
palette.setBrush(QPalette::Disabled, QPalette::ToolTipBase, brush6);
palette.setBrush(QPalette::Disabled, QPalette::ToolTipText, brush);
runAutoDenom->setPalette(palette);
runAutoDenom->setFocusPolicy(Qt::NoFocus);
runAutoDenom->setAutoFillBackground(true);
runAutoDenom->setFlat(true);
toggleObfuscation = new QPushButton(frameObfuscation);
toggleObfuscation->setObjectName(QStringLiteral("toggleObfuscation"));
toggleObfuscation->setGeometry(QRect(120, 250, 221, 56));
QSizePolicy sizePolicy1(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);
sizePolicy1.setHorizontalStretch(0);
sizePolicy1.setVerticalStretch(0);
sizePolicy1.setHeightForWidth(toggleObfuscation->sizePolicy().hasHeightForWidth());
toggleObfuscation->setSizePolicy(sizePolicy1);
lineLastMessage = new QFrame(frameObfuscation);
lineLastMessage->setObjectName(QStringLiteral("lineLastMessage"));
lineLastMessage->setGeometry(QRect(10, 200, 441, 16));
lineLastMessage->setFrameShape(QFrame::HLine);
lineLastMessage->setFrameShadow(QFrame::Sunken);
obfuscationStatus = new QLabel(frameObfuscation);
obfuscationStatus->setObjectName(QStringLiteral("obfuscationStatus"));
obfuscationStatus->setGeometry(QRect(10, 220, 451, 61));
obfuscationStatus->setMinimumSize(QSize(288, 43));
obfuscationStatus->setAlignment(Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop);
obfuscationStatus->setWordWrap(true);
obfuscationAuto = new QPushButton(frameObfuscation);
obfuscationAuto->setObjectName(QStringLiteral("obfuscationAuto"));
obfuscationAuto->setGeometry(QRect(10, 310, 221, 28));
sizePolicy1.setHeightForWidth(obfuscationAuto->sizePolicy().hasHeightForWidth());
obfuscationAuto->setSizePolicy(sizePolicy1);
obfuscationReset = new QPushButton(frameObfuscation);
obfuscationReset->setObjectName(QStringLiteral("obfuscationReset"));
obfuscationReset->setGeometry(QRect(230, 310, 221, 28));
sizePolicy1.setHeightForWidth(obfuscationReset->sizePolicy().hasHeightForWidth());
obfuscationReset->setSizePolicy(sizePolicy1);
obfuscationReset->setAutoFillBackground(false);
layoutWidget = new QWidget(frameObfuscation);
layoutWidget->setObjectName(QStringLiteral("layoutWidget"));
layoutWidget->setGeometry(QRect(10, 10, 431, 22));
horizontalLayout_5 = new QHBoxLayout(layoutWidget);
horizontalLayout_5->setObjectName(QStringLiteral("horizontalLayout_5"));
horizontalLayout_5->setContentsMargins(0, 0, 0, 0);
label_2 = new QLabel(layoutWidget);
label_2->setObjectName(QStringLiteral("label_2"));
label_2->setFont(font);
horizontalLayout_5->addWidget(label_2);
labelObfuscationSyncStatus = new QLabel(layoutWidget);
labelObfuscationSyncStatus->setObjectName(QStringLiteral("labelObfuscationSyncStatus"));
labelObfuscationSyncStatus->setStyleSheet(QStringLiteral("QLabel { color: red; }"));
labelObfuscationSyncStatus->setText(QStringLiteral("(out of sync)"));
labelObfuscationSyncStatus->setAlignment(Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter);
horizontalLayout_5->addWidget(labelObfuscationSyncStatus);
horizontalSpacer_4 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_5->addItem(horizontalSpacer_4);
verticalLayout_2->addWidget(frameObfuscation);
verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
verticalLayout_2->addItem(verticalSpacer);
horizontalLayout->addLayout(verticalLayout_2);
verticalLayout_3 = new QVBoxLayout();
verticalLayout_3->setObjectName(QStringLiteral("verticalLayout_3"));
frame_2 = new QFrame(OverviewPage);
frame_2->setObjectName(QStringLiteral("frame_2"));
frame_2->setFrameShape(QFrame::StyledPanel);
frame_2->setFrameShadow(QFrame::Raised);
verticalLayout = new QVBoxLayout(frame_2);
verticalLayout->setObjectName(QStringLiteral("verticalLayout"));
verticalSpacer_3 = new QSpacerItem(20, 75, QSizePolicy::Minimum, QSizePolicy::Fixed);
verticalLayout->addItem(verticalSpacer_3);
horizontalLayout_2 = new QHBoxLayout();
horizontalLayout_2->setObjectName(QStringLiteral("horizontalLayout_2"));
label_4 = new QLabel(frame_2);
label_4->setObjectName(QStringLiteral("label_4"));
label_4->setFont(font);
horizontalLayout_2->addWidget(label_4);
labelTransactionsStatus = new QLabel(frame_2);
labelTransactionsStatus->setObjectName(QStringLiteral("labelTransactionsStatus"));
labelTransactionsStatus->setCursor(QCursor(Qt::WhatsThisCursor));
labelTransactionsStatus->setStyleSheet(QStringLiteral("QLabel { color: red; }"));
labelTransactionsStatus->setText(QStringLiteral("(out of sync)"));
labelTransactionsStatus->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);
horizontalLayout_2->addWidget(labelTransactionsStatus);
horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_2->addItem(horizontalSpacer);
verticalLayout->addLayout(horizontalLayout_2);
listTransactions = new QListView(frame_2);
listTransactions->setObjectName(QStringLiteral("listTransactions"));
listTransactions->setStyleSheet(QStringLiteral("QListView { background: transparent; }"));
listTransactions->setFrameShape(QFrame::NoFrame);
listTransactions->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
listTransactions->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
listTransactions->setSelectionMode(QAbstractItemView::NoSelection);
verticalLayout->addWidget(listTransactions);
verticalLayout_3->addWidget(frame_2);
verticalSpacer_2 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
verticalLayout_3->addItem(verticalSpacer_2);
horizontalLayout->addLayout(verticalLayout_3);
horizontalLayout->setStretch(0, 1);
horizontalLayout->setStretch(1, 1);
topLayout->addLayout(horizontalLayout);
retranslateUi(OverviewPage);
QMetaObject::connectSlotsByName(OverviewPage);
} // setupUi
void retranslateUi(QWidget *OverviewPage)
{
OverviewPage->setWindowTitle(QApplication::translate("OverviewPage", "Form", Q_NULLPTR));
label_5->setText(QApplication::translate("OverviewPage", "Balances", Q_NULLPTR));
#ifndef QT_NO_TOOLTIP
labelWalletStatus->setToolTip(QApplication::translate("OverviewPage", "The displayed information may be out of date. Your wallet automatically synchronizes with the DIVI network after a connection is established, but this process has not completed yet.", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
#ifndef QT_NO_TOOLTIP
labelWatchPending->setToolTip(QApplication::translate("OverviewPage", "Unconfirmed transactions to watch-only addresses", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
#ifndef QT_NO_TOOLTIP
labelUnconfirmed->setToolTip(QApplication::translate("OverviewPage", "Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
#ifndef QT_NO_TOOLTIP
labelWatchImmature->setToolTip(QApplication::translate("OverviewPage", "Staked or masternode rewards in watch-only addresses that has not yet matured", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
labelTotalText->setText(QApplication::translate("OverviewPage", "Total:", Q_NULLPTR));
#ifndef QT_NO_TOOLTIP
labelImmature->setToolTip(QApplication::translate("OverviewPage", "Staked or masternode rewards that has not yet matured", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
labelImmatureText->setText(QApplication::translate("OverviewPage", "Immature:", Q_NULLPTR));
#ifndef QT_NO_TOOLTIP
labelTotal->setToolTip(QApplication::translate("OverviewPage", "Your current total balance", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
#ifndef QT_NO_TOOLTIP
labelWatchTotal->setToolTip(QApplication::translate("OverviewPage", "Current total balance in watch-only addresses", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
labelWatchonly->setText(QApplication::translate("OverviewPage", "Watch-only:", Q_NULLPTR));
labelBalanceText->setText(QApplication::translate("OverviewPage", "Available:", Q_NULLPTR));
#ifndef QT_NO_TOOLTIP
labelBalance->setToolTip(QApplication::translate("OverviewPage", "Your current spendable balance", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
#ifndef QT_NO_TOOLTIP
labelWatchAvailable->setToolTip(QApplication::translate("OverviewPage", "Your current balance in watch-only addresses", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
labelPendingText->setText(QApplication::translate("OverviewPage", "Pending:", Q_NULLPTR));
labelSpendable->setText(QApplication::translate("OverviewPage", "Spendable:", Q_NULLPTR));
label_6->setText(QApplication::translate("OverviewPage", "Status:", Q_NULLPTR));
label_7->setText(QApplication::translate("OverviewPage", "Completion:", Q_NULLPTR));
labelAnonymizedText->setText(QApplication::translate("OverviewPage", "Obfuscation Balance:", Q_NULLPTR));
label_8->setText(QApplication::translate("OverviewPage", "Amount and Rounds:", Q_NULLPTR));
labelAmountRounds->setText(QApplication::translate("OverviewPage", "0 PIV / 0 Rounds", Q_NULLPTR));
label_9->setText(QApplication::translate("OverviewPage", "Submitted Denom:", Q_NULLPTR));
#ifndef QT_NO_TOOLTIP
labelSubmittedDenom->setToolTip(QApplication::translate("OverviewPage", "The denominations you submitted to the Masternode.<br>To mix, other users must submit the exact same denominations.", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
labelSubmittedDenom->setText(QApplication::translate("OverviewPage", "n/a", Q_NULLPTR));
obfuscationEnabled->setText(QApplication::translate("OverviewPage", "Enabled/Disabled", Q_NULLPTR));
runAutoDenom->setText(QString());
toggleObfuscation->setText(QApplication::translate("OverviewPage", "Start/Stop Mixing", Q_NULLPTR));
obfuscationStatus->setText(QApplication::translate("OverviewPage", "(Last Message)", Q_NULLPTR));
#ifndef QT_NO_TOOLTIP
obfuscationAuto->setToolTip(QApplication::translate("OverviewPage", "Try to manually submit a Obfuscation request.", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
obfuscationAuto->setText(QApplication::translate("OverviewPage", "Try Mix", Q_NULLPTR));
#ifndef QT_NO_TOOLTIP
obfuscationReset->setToolTip(QApplication::translate("OverviewPage", "Reset the current status of Obfuscation (can interrupt Obfuscation if it's in the process of Mixing, which can cost you money!)", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
obfuscationReset->setText(QApplication::translate("OverviewPage", "Reset", Q_NULLPTR));
label_2->setText(QApplication::translate("OverviewPage", "Obfuscation", Q_NULLPTR));
#ifndef QT_NO_TOOLTIP
labelObfuscationSyncStatus->setToolTip(QApplication::translate("OverviewPage", "The displayed information may be out of date. Your wallet automatically synchronizes with the DIVI network after a connection is established, but this process has not completed yet.", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
label_4->setText(QApplication::translate("OverviewPage", "Recent transactions", Q_NULLPTR));
#ifndef QT_NO_TOOLTIP
labelTransactionsStatus->setToolTip(QApplication::translate("OverviewPage", "The displayed information may be out of date. Your wallet automatically synchronizes with the DIVI network after a connection is established, but this process has not completed yet.", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
} // retranslateUi
};
namespace Ui {
class OverviewPage: public Ui_OverviewPage {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_OVERVIEWPAGE_H
| [
"divicoingit@gmail.com"
] | divicoingit@gmail.com |
0d905cfba165bfe2a52bcf6d448bdfa73003378c | 0aca9ec0a5e9e450bf54195aeec03428762c27d2 | /src/qt/transactiontablemodel.cpp | fe345dc1e79af4196820e5f71e4f79a19034b849 | [
"MIT"
] | permissive | unitedworldmoney/unitedworldmoney-source | 1bc593a348376555979f00bdb8dfe13c3d2661a3 | 4229d64f48ac7c7e622595cf9ffe9a08878c9252 | refs/heads/main | 2023-07-18T06:31:02.082512 | 2021-09-06T14:26:43 | 2021-09-06T14:26:43 | 403,652,373 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,480 | cpp | // Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2016 The Dash developers
// Copyright (c) 2016-2019 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "transactiontablemodel.h"
#include "addresstablemodel.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "transactiondesc.h"
#include "transactionrecord.h"
#include "walletmodel.h"
#include "main.h"
#include "sync.h"
#include "uint256.h"
#include "util.h"
#include "wallet/wallet.h"
#include <QColor>
#include <QDateTime>
#include <QDebug>
#include <QIcon>
#include <QList>
// Amount column is right-aligned it contains numbers
static int column_alignments[] = {
Qt::AlignLeft | Qt::AlignVCenter, /* status */
Qt::AlignLeft | Qt::AlignVCenter, /* watchonly */
Qt::AlignLeft | Qt::AlignVCenter, /* date */
Qt::AlignLeft | Qt::AlignVCenter, /* type */
Qt::AlignLeft | Qt::AlignVCenter, /* address */
Qt::AlignRight | Qt::AlignVCenter /* amount */
};
// Comparison operator for sort/binary search of model tx list
struct TxLessThan {
bool operator()(const TransactionRecord& a, const TransactionRecord& b) const
{
return a.hash < b.hash;
}
bool operator()(const TransactionRecord& a, const uint256& b) const
{
return a.hash < b;
}
bool operator()(const uint256& a, const TransactionRecord& b) const
{
return a < b.hash;
}
};
// Private implementation
class TransactionTablePriv
{
public:
TransactionTablePriv(CWallet* wallet, TransactionTableModel* parent) : wallet(wallet),
parent(parent)
{
}
CWallet* wallet;
TransactionTableModel* parent;
/* Local cache of wallet.
* As it is in the same order as the CWallet, by definition
* this is sorted by sha256.
*/
QList<TransactionRecord> cachedWallet;
/* Query entire wallet anew from core.
*/
void refreshWallet()
{
qDebug() << "TransactionTablePriv::refreshWallet";
cachedWallet.clear();
{
LOCK2(cs_main, wallet->cs_wallet);
for (std::map<uint256, CWalletTx>::iterator it = wallet->mapWallet.begin(); it != wallet->mapWallet.end(); ++it) {
if (TransactionRecord::showTransaction(it->second))
cachedWallet.append(TransactionRecord::decomposeTransaction(wallet, it->second));
}
}
}
/* Update our model of the wallet incrementally, to synchronize our model of the wallet
with that of the core.
Call with transaction that was added, removed or changed.
*/
void updateWallet(const uint256& hash, int status, bool showTransaction)
{
qDebug() << "TransactionTablePriv::updateWallet : " + QString::fromStdString(hash.ToString()) + " " + QString::number(status);
// Find bounds of this transaction in model
QList<TransactionRecord>::iterator lower = qLowerBound(
cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan());
QList<TransactionRecord>::iterator upper = qUpperBound(
cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan());
int lowerIndex = (lower - cachedWallet.begin());
int upperIndex = (upper - cachedWallet.begin());
bool inModel = (lower != upper);
if (status == CT_UPDATED) {
if (showTransaction && !inModel)
status = CT_NEW; /* Not in model, but want to show, treat as new */
if (!showTransaction && inModel)
status = CT_DELETED; /* In model, but want to hide, treat as deleted */
}
qDebug() << " inModel=" + QString::number(inModel) +
" Index=" + QString::number(lowerIndex) + "-" + QString::number(upperIndex) +
" showTransaction=" + QString::number(showTransaction) + " derivedStatus=" + QString::number(status);
switch (status) {
case CT_NEW:
if (inModel) {
qWarning() << "TransactionTablePriv::updateWallet : Warning: Got CT_NEW, but transaction is already in model";
break;
}
if (showTransaction) {
LOCK2(cs_main, wallet->cs_wallet);
// Find transaction in wallet
std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(hash);
if (mi == wallet->mapWallet.end()) {
qWarning() << "TransactionTablePriv::updateWallet : Warning: Got CT_NEW, but transaction is not in wallet";
break;
}
// Added -- insert at the right position
QList<TransactionRecord> toInsert =
TransactionRecord::decomposeTransaction(wallet, mi->second);
if (!toInsert.isEmpty()) /* only if something to insert */
{
parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex + toInsert.size() - 1);
int insert_idx = lowerIndex;
foreach (const TransactionRecord& rec, toInsert) {
cachedWallet.insert(insert_idx, rec);
insert_idx += 1;
}
parent->endInsertRows();
}
}
break;
case CT_DELETED:
if (!inModel) {
qWarning() << "TransactionTablePriv::updateWallet : Warning: Got CT_DELETED, but transaction is not in model";
break;
}
// Removed -- remove entire transaction from table
parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex - 1);
cachedWallet.erase(lower, upper);
parent->endRemoveRows();
break;
case CT_UPDATED:
// Miscellaneous updates -- nothing to do, status update will take care of this, and is only computed for
// visible transactions.
break;
}
}
int size()
{
return cachedWallet.size();
}
TransactionRecord* index(int idx)
{
if (idx >= 0 && idx < cachedWallet.size()) {
TransactionRecord* rec = &cachedWallet[idx];
// Get required locks upfront. This avoids the GUI from getting
// stuck if the core is holding the locks for a longer time - for
// example, during a wallet rescan.
//
// If a status update is needed (blocks came in since last check),
// update the status of this transaction from the wallet. Otherwise,
// simply re-use the cached status.
TRY_LOCK(cs_main, lockMain);
if (lockMain) {
TRY_LOCK(wallet->cs_wallet, lockWallet);
if (lockWallet && rec->statusUpdateNeeded()) {
std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(rec->hash);
if (mi != wallet->mapWallet.end()) {
rec->updateStatus(mi->second);
}
}
}
return rec;
}
return 0;
}
QString describe(TransactionRecord* rec, int unit)
{
{
LOCK2(cs_main, wallet->cs_wallet);
std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(rec->hash);
if (mi != wallet->mapWallet.end()) {
return TransactionDesc::toHTML(wallet, mi->second, rec, unit);
}
}
return QString();
}
};
TransactionTableModel::TransactionTableModel(CWallet* wallet, WalletModel* parent) : QAbstractTableModel(parent),
wallet(wallet),
walletModel(parent),
priv(new TransactionTablePriv(wallet, this)),
fProcessingQueuedTransactions(false)
{
columns << QString() << QString() << tr("Date") << tr("Type") << tr("Address") << BitcoinUnits::getAmountColumnTitle(walletModel->getOptionsModel()->getDisplayUnit());
priv->refreshWallet();
connect(walletModel->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
subscribeToCoreSignals();
}
TransactionTableModel::~TransactionTableModel()
{
unsubscribeFromCoreSignals();
delete priv;
}
/** Updates the column title to "Amount (DisplayUnit)" and emits headerDataChanged() signal for table headers to react. */
void TransactionTableModel::updateAmountColumnTitle()
{
columns[Amount] = BitcoinUnits::getAmountColumnTitle(walletModel->getOptionsModel()->getDisplayUnit());
emit headerDataChanged(Qt::Horizontal, Amount, Amount);
}
void TransactionTableModel::updateTransaction(const QString& hash, int status, bool showTransaction)
{
uint256 updated;
updated.SetHex(hash.toStdString());
priv->updateWallet(updated, status, showTransaction);
}
void TransactionTableModel::updateConfirmations()
{
// Blocks came in since last poll.
// Invalidate status (number of confirmations) and (possibly) description
// for all rows. Qt is smart enough to only actually request the data for the
// visible rows.
emit dataChanged(index(0, Status), index(priv->size() - 1, Status));
emit dataChanged(index(0, ToAddress), index(priv->size() - 1, ToAddress));
}
int TransactionTableModel::rowCount(const QModelIndex& parent) const
{
Q_UNUSED(parent);
return priv->size();
}
int TransactionTableModel::columnCount(const QModelIndex& parent) const
{
Q_UNUSED(parent);
return columns.length();
}
QString TransactionTableModel::formatTxStatus(const TransactionRecord* wtx) const
{
QString status;
switch (wtx->status.status) {
case TransactionStatus::OpenUntilBlock:
status = tr("Open for %n more block(s)", "", wtx->status.open_for);
break;
case TransactionStatus::OpenUntilDate:
status = tr("Open until %1").arg(GUIUtil::dateTimeStr(wtx->status.open_for));
break;
case TransactionStatus::Offline:
status = tr("Offline");
break;
case TransactionStatus::Unconfirmed:
status = tr("Unconfirmed");
break;
case TransactionStatus::Confirming:
status = tr("Confirming (%1 of %2 recommended confirmations)").arg(wtx->status.depth).arg(TransactionRecord::RecommendedNumConfirmations);
break;
case TransactionStatus::Confirmed:
status = tr("Confirmed (%1 confirmations)").arg(wtx->status.depth);
break;
case TransactionStatus::Conflicted:
status = tr("Conflicted");
break;
case TransactionStatus::Immature:
status = tr("Immature (%1 confirmations, will be available after %2)").arg(wtx->status.depth).arg(wtx->status.depth + wtx->status.matures_in);
break;
case TransactionStatus::MaturesWarning:
status = tr("This block was not received by any other nodes and will probably not be accepted!");
break;
case TransactionStatus::NotAccepted:
status = tr("Orphan Block - Generated but not accepted. This does not impact your holdings.");
break;
}
return status;
}
QString TransactionTableModel::formatTxDate(const TransactionRecord* wtx) const
{
if (wtx->time) {
return GUIUtil::dateTimeStr(wtx->time);
}
return QString();
}
/* Look up address in address book, if found return label (address)
otherwise just return (address)
*/
QString TransactionTableModel::lookupAddress(const std::string& address, bool tooltip) const
{
QString label = walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(address));
QString description;
if (!label.isEmpty()) {
description += label;
}
if (label.isEmpty() || tooltip) {
description += QString(" (") + QString::fromStdString(address) + QString(")");
}
return description;
}
QString TransactionTableModel::formatTxType(const TransactionRecord* wtx) const
{
switch (wtx->type) {
case TransactionRecord::RecvWithAddress:
return tr("Received with");
case TransactionRecord::MNReward:
return tr("Masternode Reward");
case TransactionRecord::RecvFromOther:
return tr("Received from");
case TransactionRecord::RecvWithObfuscation:
return tr("Received via Obfuscation");
case TransactionRecord::SendToAddress:
case TransactionRecord::SendToOther:
return tr("Sent to");
case TransactionRecord::SendToSelf:
return tr("Payment to yourself");
case TransactionRecord::StakeMint:
return tr("UWM Stake");
case TransactionRecord::StakeZUWM:
return tr("zUWM Stake");
case TransactionRecord::Generated:
return tr("Mined");
case TransactionRecord::ObfuscationDenominate:
return tr("Obfuscation Denominate");
case TransactionRecord::ObfuscationCollateralPayment:
return tr("Obfuscation Collateral Payment");
case TransactionRecord::ObfuscationMakeCollaterals:
return tr("Obfuscation Make Collateral Inputs");
case TransactionRecord::ObfuscationCreateDenominations:
return tr("Obfuscation Create Denominations");
case TransactionRecord::Obfuscated:
return tr("Obfuscated");
case TransactionRecord::ZerocoinMint:
return tr("Converted UWM to zUWM");
case TransactionRecord::ZerocoinSpend:
return tr("Spent zUWM");
case TransactionRecord::RecvFromZerocoinSpend:
return tr("Received UWM from zUWM");
case TransactionRecord::ZerocoinSpend_Change_zPiv:
return tr("Minted Change as zUWM from zUWM Spend");
case TransactionRecord::ZerocoinSpend_FromMe:
return tr("Converted zUWM to UWM");
default:
return QString();
}
}
QVariant TransactionTableModel::txAddressDecoration(const TransactionRecord* wtx) const
{
switch (wtx->type) {
case TransactionRecord::Generated:
case TransactionRecord::StakeMint:
case TransactionRecord::StakeZUWM:
case TransactionRecord::MNReward:
return QIcon(":/icons/tx_mined");
case TransactionRecord::RecvWithObfuscation:
case TransactionRecord::RecvWithAddress:
case TransactionRecord::RecvFromOther:
case TransactionRecord::RecvFromZerocoinSpend:
return QIcon(":/icons/tx_input");
case TransactionRecord::SendToAddress:
case TransactionRecord::SendToOther:
case TransactionRecord::ZerocoinSpend:
return QIcon(":/icons/tx_output");
default:
return QIcon(":/icons/tx_inout");
}
}
QString TransactionTableModel::formatTxToAddress(const TransactionRecord* wtx, bool tooltip) const
{
QString watchAddress;
if (tooltip) {
// Mark transactions involving watch-only addresses by adding " (watch-only)"
watchAddress = wtx->involvesWatchAddress ? QString(" (") + tr("watch-only") + QString(")") : "";
}
switch (wtx->type) {
case TransactionRecord::RecvFromOther:
return QString::fromStdString(wtx->address) + watchAddress;
case TransactionRecord::RecvWithAddress:
case TransactionRecord::MNReward:
case TransactionRecord::RecvWithObfuscation:
case TransactionRecord::SendToAddress:
case TransactionRecord::Generated:
case TransactionRecord::StakeMint:
case TransactionRecord::ZerocoinSpend:
case TransactionRecord::ZerocoinSpend_FromMe:
case TransactionRecord::RecvFromZerocoinSpend:
return lookupAddress(wtx->address, tooltip);
case TransactionRecord::Obfuscated:
return lookupAddress(wtx->address, tooltip) + watchAddress;
case TransactionRecord::SendToOther:
return QString::fromStdString(wtx->address) + watchAddress;
case TransactionRecord::ZerocoinMint:
case TransactionRecord::ZerocoinSpend_Change_zPiv:
return tr("Anonymous (zUWM Transaction)");
case TransactionRecord::StakeZUWM:
return tr("Anonymous (zUWM Stake)");
case TransactionRecord::SendToSelf:
default:
return tr("(n/a)") + watchAddress;
}
}
QVariant TransactionTableModel::addressColor(const TransactionRecord* wtx) const
{
switch (wtx->type) {
// Show addresses without label in a less visible color
case TransactionRecord::RecvWithAddress:
case TransactionRecord::SendToAddress:
case TransactionRecord::Generated:
case TransactionRecord::MNReward: {
QString label = walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(wtx->address));
if (label.isEmpty())
return COLOR_BAREADDRESS;
}
case TransactionRecord::SendToSelf:
default:
// To avoid overriding above conditional formats a default text color for this QTableView is not defined in stylesheet,
// so we must always return a color here
return COLOR_BLACK;
}
}
QString TransactionTableModel::formatTxAmount(const TransactionRecord* wtx, bool showUnconfirmed, BitcoinUnits::SeparatorStyle separators) const
{
QString str = BitcoinUnits::format(walletModel->getOptionsModel()->getDisplayUnit(), wtx->credit + wtx->debit, false, separators);
if (showUnconfirmed) {
if (!wtx->status.countsForBalance) {
str = QString("[") + str + QString("]");
}
}
return QString(str);
}
QVariant TransactionTableModel::txStatusDecoration(const TransactionRecord* wtx) const
{
switch (wtx->status.status) {
case TransactionStatus::OpenUntilBlock:
case TransactionStatus::OpenUntilDate:
return COLOR_TX_STATUS_OPENUNTILDATE;
case TransactionStatus::Offline:
return COLOR_TX_STATUS_OFFLINE;
case TransactionStatus::Unconfirmed:
return QIcon(":/icons/transaction_0");
case TransactionStatus::Confirming:
switch (wtx->status.depth) {
case 1:
return QIcon(":/icons/transaction_1");
case 2:
return QIcon(":/icons/transaction_2");
case 3:
return QIcon(":/icons/transaction_3");
case 4:
return QIcon(":/icons/transaction_4");
default:
return QIcon(":/icons/transaction_5");
};
case TransactionStatus::Confirmed:
return QIcon(":/icons/transaction_confirmed");
case TransactionStatus::Conflicted:
return QIcon(":/icons/transaction_conflicted");
case TransactionStatus::Immature: {
int total = wtx->status.depth + wtx->status.matures_in;
int part = (wtx->status.depth * 5 / total) + 1;
return QIcon(QString(":/icons/transaction_%1").arg(part));
}
case TransactionStatus::MaturesWarning:
case TransactionStatus::NotAccepted:
return QIcon(":/icons/transaction_0");
default:
return COLOR_BLACK;
}
}
QVariant TransactionTableModel::txWatchonlyDecoration(const TransactionRecord* wtx) const
{
if (wtx->involvesWatchAddress)
return QIcon(":/icons/eye");
else
return QVariant();
}
QString TransactionTableModel::formatTooltip(const TransactionRecord* rec) const
{
QString tooltip = formatTxStatus(rec) + QString("\n") + formatTxType(rec);
if (rec->type == TransactionRecord::RecvFromOther || rec->type == TransactionRecord::SendToOther ||
rec->type == TransactionRecord::SendToAddress || rec->type == TransactionRecord::RecvWithAddress || rec->type == TransactionRecord::MNReward) {
tooltip += QString(" ") + formatTxToAddress(rec, true);
}
return tooltip;
}
QVariant TransactionTableModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid())
return QVariant();
TransactionRecord* rec = static_cast<TransactionRecord*>(index.internalPointer());
switch (role) {
case Qt::DecorationRole:
switch (index.column()) {
case Status:
return txStatusDecoration(rec);
case Watchonly:
return txWatchonlyDecoration(rec);
case ToAddress:
return txAddressDecoration(rec);
}
break;
case Qt::DisplayRole:
switch (index.column()) {
case Date:
return formatTxDate(rec);
case Type:
return formatTxType(rec);
case ToAddress:
return formatTxToAddress(rec, false);
case Amount:
return formatTxAmount(rec, true, BitcoinUnits::separatorAlways);
}
break;
case Qt::EditRole:
// Edit role is used for sorting, so return the unformatted values
switch (index.column()) {
case Status:
return QString::fromStdString(rec->status.sortKey);
case Date:
return rec->time;
case Type:
return formatTxType(rec);
case Watchonly:
return (rec->involvesWatchAddress ? 1 : 0);
case ToAddress:
return formatTxToAddress(rec, true);
case Amount:
return qint64(rec->credit + rec->debit);
}
break;
case Qt::ToolTipRole:
return formatTooltip(rec);
case Qt::TextAlignmentRole:
return column_alignments[index.column()];
case Qt::ForegroundRole:
// Minted
if (rec->type == TransactionRecord::Generated || rec->type == TransactionRecord::StakeMint ||
rec->type == TransactionRecord::StakeZUWM || rec->type == TransactionRecord::MNReward) {
if (rec->status.status == TransactionStatus::Conflicted || rec->status.status == TransactionStatus::NotAccepted)
return COLOR_ORPHAN;
else
return COLOR_STAKE;
}
// Conflicted tx
if (rec->status.status == TransactionStatus::Conflicted || rec->status.status == TransactionStatus::NotAccepted) {
return COLOR_CONFLICTED;
}
// Unconfimed or immature
if ((rec->status.status == TransactionStatus::Unconfirmed) || (rec->status.status == TransactionStatus::Immature)) {
return COLOR_UNCONFIRMED;
}
if (index.column() == Amount && (rec->credit + rec->debit) < 0) {
return COLOR_NEGATIVE;
}
if (index.column() == ToAddress) {
return addressColor(rec);
}
// To avoid overriding above conditional formats a default text color for this QTableView is not defined in stylesheet,
// so we must always return a color here
return COLOR_BLACK;
case TypeRole:
return rec->type;
case DateRole:
return QDateTime::fromTime_t(static_cast<uint>(rec->time));
case WatchonlyRole:
return rec->involvesWatchAddress;
case WatchonlyDecorationRole:
return txWatchonlyDecoration(rec);
case LongDescriptionRole:
return priv->describe(rec, walletModel->getOptionsModel()->getDisplayUnit());
case AddressRole:
return QString::fromStdString(rec->address);
case LabelRole:
return walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(rec->address));
case AmountRole:
return qint64(rec->credit + rec->debit);
case TxIDRole:
return rec->getTxID();
case TxHashRole:
return QString::fromStdString(rec->hash.ToString());
case ConfirmedRole:
return rec->status.countsForBalance;
case FormattedAmountRole:
// Used for copy/export, so don't include separators
return formatTxAmount(rec, false, BitcoinUnits::separatorNever);
case StatusRole:
return rec->status.status;
}
return QVariant();
}
QVariant TransactionTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal) {
if (role == Qt::DisplayRole) {
return columns[section];
} else if (role == Qt::TextAlignmentRole) {
return column_alignments[section];
} else if (role == Qt::ToolTipRole) {
switch (section) {
case Status:
return tr("Transaction status. Hover over this field to show number of confirmations.");
case Date:
return tr("Date and time that the transaction was received.");
case Type:
return tr("Type of transaction.");
case Watchonly:
return tr("Whether or not a watch-only address is involved in this transaction.");
case ToAddress:
return tr("Destination address of transaction.");
case Amount:
return tr("Amount removed from or added to balance.");
}
}
}
return QVariant();
}
QModelIndex TransactionTableModel::index(int row, int column, const QModelIndex& parent) const
{
Q_UNUSED(parent);
TransactionRecord* data = priv->index(row);
if (data) {
return createIndex(row, column, priv->index(row));
}
return QModelIndex();
}
void TransactionTableModel::updateDisplayUnit()
{
// emit dataChanged to update Amount column with the current unit
updateAmountColumnTitle();
emit dataChanged(index(0, Amount), index(priv->size() - 1, Amount));
}
// queue notifications to show a non freezing progress dialog e.g. for rescan
struct TransactionNotification {
public:
TransactionNotification() {}
TransactionNotification(uint256 hash, ChangeType status, bool showTransaction) : hash(hash), status(status), showTransaction(showTransaction) {}
void invoke(QObject* ttm)
{
QString strHash = QString::fromStdString(hash.GetHex());
qDebug() << "NotifyTransactionChanged : " + strHash + " status= " + QString::number(status);
QMetaObject::invokeMethod(ttm, "updateTransaction", Qt::QueuedConnection,
Q_ARG(QString, strHash),
Q_ARG(int, status),
Q_ARG(bool, showTransaction));
}
private:
uint256 hash;
ChangeType status;
bool showTransaction;
};
static bool fQueueNotifications = false;
static std::vector<TransactionNotification> vQueueNotifications;
static void NotifyTransactionChanged(TransactionTableModel* ttm, CWallet* wallet, const uint256& hash, ChangeType status)
{
// Find transaction in wallet
std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(hash);
// Determine whether to show transaction or not (determine this here so that no relocking is needed in GUI thread)
bool inWallet = mi != wallet->mapWallet.end();
bool showTransaction = (inWallet && TransactionRecord::showTransaction(mi->second));
TransactionNotification notification(hash, status, showTransaction);
if (fQueueNotifications) {
vQueueNotifications.push_back(notification);
return;
}
notification.invoke(ttm);
}
static void ShowProgress(TransactionTableModel* ttm, const std::string& title, int nProgress)
{
if (nProgress == 0)
fQueueNotifications = true;
if (nProgress == 100) {
fQueueNotifications = false;
if (vQueueNotifications.size() > 10) // prevent balloon spam, show maximum 10 balloons
QMetaObject::invokeMethod(ttm, "setProcessingQueuedTransactions", Qt::QueuedConnection, Q_ARG(bool, true));
for (unsigned int i = 0; i < vQueueNotifications.size(); ++i) {
if (vQueueNotifications.size() - i <= 10)
QMetaObject::invokeMethod(ttm, "setProcessingQueuedTransactions", Qt::QueuedConnection, Q_ARG(bool, false));
vQueueNotifications[i].invoke(ttm);
}
std::vector<TransactionNotification>().swap(vQueueNotifications); // clear
}
}
void TransactionTableModel::subscribeToCoreSignals()
{
// Connect signals to wallet
wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
wallet->ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2));
}
void TransactionTableModel::unsubscribeFromCoreSignals()
{
// Disconnect signals from wallet
wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
wallet->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2));
}
| [
"34356906+unitedworldmoney@users.noreply.github.com"
] | 34356906+unitedworldmoney@users.noreply.github.com |
2e1253792556d23e9f3290a7eb11c3063b171b4a | afa8675e536666df43653ca8fe3850998d1935a9 | /B - Serval and Toy Bricks.cpp | dc6edf52b1efd0c108a391e4d62b184878f91587 | [] | no_license | Saurav-Paul/Codeforces-Problem-Solution-By-Saurav-Paul | 0b7fdabaf87c30ac9e9e6f6e8ee4f36435a9f77e | e9cba8190d562061f1b4c26e76005b79e335d4d9 | refs/heads/master | 2022-10-21T18:40:31.822162 | 2022-09-14T15:44:26 | 2022-09-14T15:44:26 | 122,532,942 | 93 | 37 | null | 2020-10-03T09:45:07 | 2018-02-22T20:42:53 | C++ | UTF-8 | C++ | false | false | 2,187 | cpp | #include<bits/stdc++.h>
#define endl '\n'
#define ll long long int
#define loop(i,a,b) for(ll i=a;i<=b;++i)
#define pb push_back
#define F first
#define S second
#define mp make_pair
#define clr(x) x.clear()
#define MOD 1000000007
#define itoc(c) ((char)(((int)'0')+c))
#define vl vector<ll>
#define SZ(x) (x).size()
#define all(p) p.begin(),p.end()
#define mid(s,e) (s+(e-s)/2)
#define sv() ll t,n; scanf("%lld",&t);n=t; while(t--)
#define tcase() ll t,n; cin>>t;n=t; while(t--)
#define iscn(num) scanf("%d",&num);
#define scn(num) scanf("%lld ",&num);
#define dbg(n) cout<<(n)<<endl;
using namespace std;
const ll INF = 2e18 + 99;
typedef pair<ll,ll> Pair;
typedef vector<ll> vec;
bool file=0,rt=1;
clock_t tStart ;
void FAST_IO();
////////////////////////
int main()
{
FAST_IO();
////////////////////////
ll len,wid,height; scn(len); scn(wid); scn(height);
vec width,high;
ll temp;
for(int i=0; i<wid ; i++){
scn(temp);
width.pb(temp);
}
for(int i=0;i<len ; i++){
scn(temp);
high.pb(temp);
}
int matrix[len][wid];
for(int i=0; i<len ; i++){
for(int j=0; j<wid ; j++){
iscn(matrix[i][j]);
if(matrix[i][j]){
matrix[i][j]=min(width[j],high[i]);
}
}
}
for(int i=0; i<len ; i++){
for(int j=0; j<wid ; j++){
cout<<matrix[i][j]<<" ";
}
cout<<endl;
}
////////////////////////
if(rt && file){
printf("\nTime taken: %.6fs", (double)(clock() - tStart)/CLOCKS_PER_SEC);
}
return 0;
}
void FAST_IO()
{
// ios_base::sync_with_stdio(0);
//cin.tie(NULL);
//cout.tie(NULL);
//cout.setf(ios::fixed);
//cout.precision(2);
if(rt && file){ tStart = clock(); }
if(file){
#ifndef _offline
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
}
| [
"noreply@github.com"
] | noreply@github.com |
acf334e98fe43892ecdf916542233093b67476b2 | 3af68b32aaa9b7522a1718b0fc50ef0cf4a704a9 | /cpp/E/C/D/A/D/AECDAD.h | a7b7ae207acf4ec889c9c4d66ac01af78d4fc5a9 | [] | no_license | devsisters/2021-NDC-ICECREAM | 7cd09fa2794cbab1ab4702362a37f6ab62638d9b | ac6548f443a75b86d9e9151ff9c1b17c792b2afd | refs/heads/master | 2023-03-19T06:29:03.216461 | 2021-03-10T02:53:14 | 2021-03-10T02:53:14 | 341,872,233 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 67 | h | #ifndef AECDAD_H
namespace AECDAD {
std::string run();
}
#endif | [
"nakhyun@devsisters.com"
] | nakhyun@devsisters.com |
ddaec8d2310a960a1844e613f05c2818395c9ae6 | 0a5058bff1961f6564c662224362995ee8fa3944 | /chrome/browser/prerender/isolated/isolated_prerender_origin_prober.cc | f326f063cda9d7a124acef311c4c9506e847aa7b | [
"BSD-3-Clause"
] | permissive | DongKai/chromium | d0208df711d2bad1e4324ca3b10a261c336758a0 | b7bb401aedab4fbe5af173a5baeaf91c8dbe726a | refs/heads/master | 2022-12-05T17:16:47.586163 | 2020-09-02T23:37:00 | 2020-09-02T23:37:00 | 292,435,006 | 0 | 0 | BSD-3-Clause | 2020-09-03T01:31:29 | 2020-09-03T01:31:28 | null | UTF-8 | C++ | false | false | 17,298 | cc | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/prerender/isolated/isolated_prerender_origin_prober.h"
#include "base/bind.h"
#include "base/feature_list.h"
#include "base/no_destructor.h"
#include "base/task/post_task.h"
#include "chrome/browser/availability/availability_prober.h"
#include "chrome/browser/prerender/isolated/isolated_prerender_params.h"
#include "chrome/browser/profiles/profile.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/storage_partition.h"
#include "mojo/public/cpp/bindings/callback_helpers.h"
#include "mojo/public/cpp/bindings/self_owned_receiver.h"
#include "net/base/host_port_pair.h"
#include "net/base/isolation_info.h"
#include "net/base/network_isolation_key.h"
#include "services/network/public/mojom/host_resolver.mojom.h"
#include "services/network/public/mojom/network_context.mojom.h"
#include "services/network/public/mojom/tls_socket.mojom.h"
#include "url/origin.h"
namespace {
net::NetworkTrafficAnnotationTag GetProbingTrafficAnnotation() {
return net::DefineNetworkTrafficAnnotation("isolated_prerender_probe", R"(
semantics {
sender: "Isolated Prerender Probe Loader"
description:
"Verifies the end to end connection between Chrome and the "
"origin site that the user is currently navigating to. This is "
"done during a navigation that was previously prerendered over a "
"proxy to check that the site is not blocked by middleboxes. "
"Such prerenders will be used to prefetch render-blocking "
"content before being navigated by the user without impacting "
"privacy."
trigger:
"Used for sites off of Google SRPs (Search Result Pages) only "
"for Lite mode users when the experimental feature flag is "
"enabled."
data: "None."
destination: WEBSITE
}
policy {
cookies_allowed: NO
setting:
"Users can control Lite mode on Android via the settings menu. "
"Lite mode is not available on iOS, and on desktop only for "
"developer testing."
policy_exception_justification: "Not implemented."
})");
}
class DNSProber : public network::mojom::ResolveHostClient {
public:
using OnDNSResultsCallback = base::OnceCallback<
void(int, const base::Optional<net::AddressList>& resolved_addresses)>;
explicit DNSProber(OnDNSResultsCallback callback)
: callback_(std::move(callback)) {
DCHECK(callback_);
}
~DNSProber() override {
if (callback_) {
// Indicates some kind of mojo error. Play it safe and return no success.
std::move(callback_).Run(net::ERR_FAILED, base::nullopt);
}
}
// network::mojom::ResolveHostClient:
void OnTextResults(const std::vector<std::string>&) override {}
void OnHostnameResults(const std::vector<net::HostPortPair>&) override {}
void OnComplete(
int32_t error,
const net::ResolveErrorInfo& resolve_error_info,
const base::Optional<net::AddressList>& resolved_addresses) override {
if (callback_) {
std::move(callback_).Run(error, resolved_addresses);
}
}
private:
OnDNSResultsCallback callback_;
};
void TLSDropHandler(base::OnceClosure ui_only_callback) {
content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE,
std::move(ui_only_callback));
}
class TLSProber {
public:
TLSProber(const GURL& url,
IsolatedPrerenderOriginProber::OnProbeResultCallback callback)
: url_(url), callback_(std::move(callback)) {}
~TLSProber() { DCHECK(!callback_); }
network::mojom::NetworkContext::CreateTCPConnectedSocketCallback
GetOnTCPConnectedCallback() {
network::mojom::NetworkContext::CreateTCPConnectedSocketCallback
tcp_handler = base::BindOnce(&TLSProber::OnTCPConnected,
weak_factory_.GetWeakPtr());
return mojo::WrapCallbackWithDropHandler(std::move(tcp_handler),
GetDropHandler());
}
mojo::PendingReceiver<network::mojom::TCPConnectedSocket>
GetTCPSocketReceiver() {
return tcp_socket_.BindNewPipeAndPassReceiver();
}
private:
void OnTCPConnected(int result,
const base::Optional<net::IPEndPoint>& local_addr,
const base::Optional<net::IPEndPoint>& peer_addr,
mojo::ScopedDataPipeConsumerHandle receive_stream,
mojo::ScopedDataPipeProducerHandle send_stream) {
if (result != net::OK) {
HandleFailure();
return;
}
network::mojom::TCPConnectedSocket::UpgradeToTLSCallback tls_handler =
base::BindOnce(&TLSProber::OnUpgradeToTLS, weak_factory_.GetWeakPtr());
tcp_socket_->UpgradeToTLS(
net::HostPortPair::FromURL(url_), /*options=*/nullptr,
net::MutableNetworkTrafficAnnotationTag(GetProbingTrafficAnnotation()),
tls_socket_.BindNewPipeAndPassReceiver(),
/*observer=*/mojo::NullRemote(),
mojo::WrapCallbackWithDropHandler(std::move(tls_handler),
GetDropHandler()));
}
void OnUpgradeToTLS(int result,
mojo::ScopedDataPipeConsumerHandle receive_stream,
mojo::ScopedDataPipeProducerHandle send_stream,
const base::Optional<net::SSLInfo>& ssl_info) {
std::move(callback_).Run(result == net::OK);
delete this;
}
base::OnceClosure GetDropHandler() {
// The drop handler is not guaranteed to be run on the original thread. Use
// the anon method above to fix that.
return base::BindOnce(
&TLSDropHandler,
base::BindOnce(&TLSProber::HandleFailure, weak_factory_.GetWeakPtr()));
}
void HandleFailure() {
std::move(callback_).Run(false);
delete this;
}
// The URL of the resource being probed. Only the host:port is used.
const GURL url_;
// The callback to run when the probe is complete.
IsolatedPrerenderOriginProber::OnProbeResultCallback callback_;
// Mojo sockets. We only test that both can be connected.
mojo::Remote<network::mojom::TCPConnectedSocket> tcp_socket_;
mojo::Remote<network::mojom::TLSClientSocket> tls_socket_;
base::WeakPtrFactory<TLSProber> weak_factory_{this};
};
void HTTPProbeHelper(
std::unique_ptr<AvailabilityProber> prober,
IsolatedPrerenderOriginProber::OnProbeResultCallback callback,
bool success) {
std::move(callback).Run(success);
}
class CanaryCheckDelegate : public AvailabilityProber::Delegate {
public:
CanaryCheckDelegate() = default;
~CanaryCheckDelegate() = default;
bool ShouldSendNextProbe() override { return true; }
bool IsResponseSuccess(net::Error net_error,
const network::mojom::URLResponseHead* head,
std::unique_ptr<std::string> body) override {
return net_error == net::OK && head && head->headers &&
head->headers->response_code() == 200 && body && *body == "OK";
}
};
class OriginProbeDelegate : public AvailabilityProber::Delegate {
public:
OriginProbeDelegate() = default;
~OriginProbeDelegate() = default;
bool ShouldSendNextProbe() override { return true; }
bool IsResponseSuccess(net::Error net_error,
const network::mojom::URLResponseHead* head,
std::unique_ptr<std::string> body) override {
return net_error == net::OK;
}
};
CanaryCheckDelegate* GetCanaryCheckDelegate() {
static base::NoDestructor<CanaryCheckDelegate> delegate;
return delegate.get();
}
OriginProbeDelegate* GetOriginProbeDelegate() {
static base::NoDestructor<OriginProbeDelegate> delegate;
return delegate.get();
}
// Allows probing to start after a delay so that browser start isn't slowed.
void StartCanaryCheck(base::WeakPtr<AvailabilityProber> canary_checker) {
// If there is no previously cached result for this network then one should be
// started. If the previous result is stale, the prober will start a probe
// during |LastProbeWasSuccessful|.
if (!canary_checker->LastProbeWasSuccessful().has_value()) {
canary_checker->SendNowIfInactive(false);
}
}
} // namespace
IsolatedPrerenderOriginProber::IsolatedPrerenderOriginProber(Profile* profile)
: profile_(profile) {
if (!IsolatedPrerenderProbingEnabled())
return;
if (!IsolatedPrerenderCanaryCheckEnabled())
return;
net::NetworkTrafficAnnotationTag traffic_annotation =
net::DefineNetworkTrafficAnnotation("isolated_prerender_canary_check", R"(
semantics {
sender: "Isolated Prerender Canary Checker"
description:
"Sends a request over HTTP to a known host in order to determine "
"if the network is subject to web filtering. If this request is "
"blocked, the Isolated Prerender feature will check that a "
"navigated site is not blocked by the network before using "
"proxied resources."
trigger:
"Used at browser startup for Lite mode users when the feature is "
"enabled."
data: "None."
destination: GOOGLE_OWNED_SERVICE
}
policy {
cookies_allowed: NO
setting:
"Users can control Lite mode on Android via the settings menu. "
"Lite mode is not available on iOS, and on desktop only for "
"developer testing."
policy_exception_justification: "Not implemented."
})");
AvailabilityProber::TimeoutPolicy timeout_policy;
timeout_policy.base_timeout = IsolatedPrerenderProbeTimeout();
AvailabilityProber::RetryPolicy retry_policy;
retry_policy.max_retries = 0;
canary_check_ = std::make_unique<AvailabilityProber>(
GetCanaryCheckDelegate(),
content::BrowserContext::GetDefaultStoragePartition(profile_)
->GetURLLoaderFactoryForBrowserProcess(),
profile_->GetPrefs(),
AvailabilityProber::ClientName::kIsolatedPrerenderCanaryCheck,
IsolatedPrerenderCanaryCheckURL(), AvailabilityProber::HttpMethod::kGet,
net::HttpRequestHeaders(), retry_policy, timeout_policy,
traffic_annotation, 10 /* max_cache_entries */,
IsolatedPrerenderCanaryCheckCacheLifetime());
// This code is running at browser startup. Start the canary check when we get
// the chance, but there's no point in it being ready for the first navigation
// since the check won't be done by then anyways.
content::GetUIThreadTaskRunner({base::TaskPriority::BEST_EFFORT})
->PostDelayedTask(
FROM_HERE,
base::BindOnce(&StartCanaryCheck, canary_check_->AsWeakPtr()),
base::TimeDelta::FromSeconds(1));
}
IsolatedPrerenderOriginProber::~IsolatedPrerenderOriginProber() = default;
bool IsolatedPrerenderOriginProber::ShouldProbeOrigins() {
if (!IsolatedPrerenderProbingEnabled()) {
return false;
}
if (!IsolatedPrerenderCanaryCheckEnabled()) {
return true;
}
DCHECK(canary_check_);
base::Optional<bool> result = canary_check_->LastProbeWasSuccessful();
if (!result.has_value()) {
// The canary check hasn't completed yet, so this request must probe.
return true;
}
// If the canary check was successful, no probing is needed.
return !result.value();
}
void IsolatedPrerenderOriginProber::
SetProbeURLOverrideDelegateOverrideForTesting(
ProbeURLOverrideDelegate* delegate) {
override_delegate_ = delegate;
}
bool IsolatedPrerenderOriginProber::IsCanaryCheckCompleteForTesting() const {
return canary_check_ && canary_check_->LastProbeWasSuccessful().has_value();
}
void IsolatedPrerenderOriginProber::Probe(const GURL& url,
OnProbeResultCallback callback) {
DCHECK(ShouldProbeOrigins());
GURL probe_url = url;
if (override_delegate_) {
probe_url = override_delegate_->OverrideProbeURL(probe_url);
}
switch (IsolatedPrerenderOriginProbeMechanism()) {
case IsolatedPrerenderOriginProbeType::kDns:
DNSProbe(probe_url, std::move(callback));
return;
case IsolatedPrerenderOriginProbeType::kHttpHead:
HTTPProbe(probe_url, std::move(callback));
return;
case IsolatedPrerenderOriginProbeType::kTls:
TLSProbe(probe_url, std::move(callback));
return;
}
}
void IsolatedPrerenderOriginProber::DNSProbe(const GURL& url,
OnProbeResultCallback callback) {
StartDNSResolution(url, std::move(callback), /*also_do_tls_connect=*/false);
}
void IsolatedPrerenderOriginProber::TLSProbe(const GURL& url,
OnProbeResultCallback callback) {
StartDNSResolution(url, std::move(callback), /*also_do_tls_connect=*/true);
}
void IsolatedPrerenderOriginProber::StartDNSResolution(
const GURL& url,
OnProbeResultCallback callback,
bool also_do_tls_connect) {
net::NetworkIsolationKey nik =
net::IsolationInfo::CreateForInternalRequest(url::Origin::Create(url))
.network_isolation_key();
network::mojom::ResolveHostParametersPtr resolve_host_parameters =
network::mojom::ResolveHostParameters::New();
// This action is navigation-blocking, so use the highest priority.
resolve_host_parameters->initial_priority = net::RequestPriority::HIGHEST;
mojo::PendingRemote<network::mojom::ResolveHostClient> client_remote;
mojo::MakeSelfOwnedReceiver(std::make_unique<DNSProber>(base::BindOnce(
&IsolatedPrerenderOriginProber::OnDNSResolved,
weak_factory_.GetWeakPtr(), url,
std::move(callback), also_do_tls_connect)),
client_remote.InitWithNewPipeAndPassReceiver());
content::BrowserContext::GetDefaultStoragePartition(profile_)
->GetNetworkContext()
->ResolveHost(net::HostPortPair::FromURL(url), nik,
std::move(resolve_host_parameters),
std::move(client_remote));
}
void IsolatedPrerenderOriginProber::HTTPProbe(const GURL& url,
OnProbeResultCallback callback) {
AvailabilityProber::TimeoutPolicy timeout_policy;
timeout_policy.base_timeout = IsolatedPrerenderProbeTimeout();
AvailabilityProber::RetryPolicy retry_policy;
retry_policy.max_retries = 0;
std::unique_ptr<AvailabilityProber> prober =
std::make_unique<AvailabilityProber>(
GetOriginProbeDelegate(),
content::BrowserContext::GetDefaultStoragePartition(profile_)
->GetURLLoaderFactoryForBrowserProcess(),
nullptr /* pref_service */,
AvailabilityProber::ClientName::kIsolatedPrerenderOriginCheck, url,
AvailabilityProber::HttpMethod::kHead, net::HttpRequestHeaders(),
retry_policy, timeout_policy, GetProbingTrafficAnnotation(),
0 /* max_cache_entries */,
base::TimeDelta::FromSeconds(0) /* revalidate_cache_after */);
AvailabilityProber* prober_ptr = prober.get();
// Transfer ownership of the prober to the callback so that the class instance
// is automatically destroyed when the probe is complete.
OnProbeResultCallback owning_callback =
base::BindOnce(&HTTPProbeHelper, std::move(prober), std::move(callback));
prober_ptr->SetOnCompleteCallback(base::BindOnce(std::move(owning_callback)));
prober_ptr->SendNowIfInactive(false /* send_only_in_foreground */);
}
void IsolatedPrerenderOriginProber::OnDNSResolved(
const GURL& url,
OnProbeResultCallback callback,
bool also_do_tls_connect,
int net_error,
const base::Optional<net::AddressList>& resolved_addresses) {
bool successful = net_error == net::OK && resolved_addresses &&
!resolved_addresses->empty();
// A TLS connection needs the resolved addresses, so it also fails here.
if (!successful) {
std::move(callback).Run(false);
return;
}
if (!also_do_tls_connect) {
std::move(callback).Run(true);
return;
}
DoTLSProbeAfterDNSResolution(url, std::move(callback), *resolved_addresses);
}
void IsolatedPrerenderOriginProber::DoTLSProbeAfterDNSResolution(
const GURL& url,
OnProbeResultCallback callback,
const net::AddressList& addresses) {
DCHECK(!addresses.empty());
std::unique_ptr<TLSProber> prober =
std::make_unique<TLSProber>(url, std::move(callback));
content::BrowserContext::GetDefaultStoragePartition(profile_)
->GetNetworkContext()
->CreateTCPConnectedSocket(
/*local_addr=*/base::nullopt, addresses,
/*tcp_connected_socket_options=*/nullptr,
net::MutableNetworkTrafficAnnotationTag(
GetProbingTrafficAnnotation()),
prober->GetTCPSocketReceiver(),
/*observer=*/mojo::NullRemote(), prober->GetOnTCPConnectedCallback());
// |prober| manages its own lifetime, using the mojo pipes.
prober.release();
}
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
91a9299245071f2ead621973b622a981e424578d | c8ebfe6d26ff01c3350a3a1e6321cba05babf3cb | /september/bubbleSort.cpp | 9b1f8e6327bc744abf72b140a949e1cfbbbe9938 | [] | no_license | kanishkcoe/cppLectures12 | a91a572b01de1ed217b3004b527e11d209b6c5d3 | befccaecc2f5612c439660e96df147cb51879c03 | refs/heads/master | 2021-04-06T00:56:23.165153 | 2019-02-03T17:27:33 | 2019-02-03T17:27:33 | 125,235,578 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,032 | cpp | #include <iostream>
#include <bits/stdc++.h>
using namespace std;
void printArray(int a[], int start, int end)
{
cout << "-----------------------------------------------" << endl;
for(int i = start; i < end; i++)
cout << a[i] << " ";
cout << endl;
cout << "-----------------------------------------------" << endl;
}
void swap(int &a, int &b)
{
int temp;
temp = a;
a = b;
b = temp;
}
void ascBubbleSort(int a[], int size)
{
for(int pass = 1; pass < size; pass++)
{
printArray(a, 0, size);
for(int j = 0; j < size - pass; j++)
{
if(a[j] > a[j+1])
{
swap(a[j], a[j+1]);
}
}
}
}
void descBubbleSort(int a[], int size)
{
for(int pass = 1; pass < size; pass++)
{
printArray(a, 0, size);
for(int j = 0; j < size - pass; j++)
{
if(a[j] < a[j+1])
{
swap(a[j], a[j+1]);
}
}
}
}
int main()
{
int a[] = {8, 1, 3, 0, 6, 9, 2};
int size = sizeof(a) / sizeof(a[0]);
descBubbleSort(a, size);
return 0;
}
| [
"32832273+kanishkcoe@users.noreply.github.com"
] | 32832273+kanishkcoe@users.noreply.github.com |
889776450ddc934f5ef4d3c39d6198acdca3eb1c | c9f9c4e008cea597488f0dba82bd4bc688284a84 | /cpptraining/ch1/Algorithm/Bit Shift/BitShift_NumToBit.cpp | f0cdb0df44798b346bf4b2015f454b79f5e6c414 | [] | no_license | gkagm2/cpppractise | fa9cba7d04d6e7cafd2e516bfb9fa94dad0e2aa4 | b2cb2b448919cbe0703894e7652ed5cd0479137c | refs/heads/master | 2023-06-27T13:04:55.392088 | 2023-06-20T14:20:20 | 2023-06-20T14:20:20 | 174,601,490 | 0 | 3 | null | null | null | null | UHC | C++ | false | false | 3,945 | cpp | #include <iostream>
using namespace std;
void PrintBit(const int &num, const int &bitSize) {
cout << "number : " << num << " -> \tbit : ";
for (int i = bitSize - 1; i >= 0; --i) {
if (num & (1 << i)) cout << "1";
else cout << "0";
}
cout << "\n";
}
// The formula x & ~(1 << k) sets the kth bit of x to zero,
int BitToZero(const int &num, const int &zeroSettingBit) {
int number = num & ~(1 << zeroSettingBit);
PrintBit(number, 32);
return number;
}
// The formula x | (1 << k) sets the kth bit of x to one
int BitToOne(const int &num, const int &oneSettingBit) {
int number = num | (1 << oneSettingBit);
PrintBit(number, 32);
return 0;
}
// formula x ^ (1 << k) inverts the kth bit of x.
int InvertBit(const int &num, const int &kThBit) {
int number = num ^ (1 << kThBit);
PrintBit(number, 32);
return number;
}
// The formula x & (x¡1) sets the last one bit of x to zero
int LastOneBitToZero(const int &num) {
int number = num & (num - 1);
PrintBit(number, 32);
return number;
}
// The formula x & -x sets all the one bit to zero, except for the last one bit.
int AllTheOneBitToZero(const int &num) {
int number = num % -num;
PrintBit(number, 32);
return number;
}
// The formula x | (x - 1) inverts all the bits after the last one bit
int InvertsAllTheBitsAfterLastOneBit(const int &num) {
int number = num | (num - 1);
PrintBit(number, 32);
return number;
}
// A positive number x is a power of two exactly when x & (x - 1) == 0
// 양수 x는 x & (x - 1) == 0 일 때 2의 거듭 제곱
void CheckPowerOfTwo(const int &num) {
int checkNum = num & (num - 1);
if (checkNum == 0) cout << num << "is power of two\n";
else cout << num << "isn't power of two\n";
PrintBit(num & (num - 1), 32);
}
// Prints all elements that belong to the set
void PrintsAllElements(const int &num) {
for (int i = 0; i < 32; ++i) {
if (num & (1 << i))
cout << i << "|";
}
cout << "\n";
}
int GetOneCountFromBit(const int &num) {
int oneCnt = 0;
for (int i = 0; i < 32; ++i) {
if ((num & (1 << i)))
++oneCnt;
}
return oneCnt;
}
int GetZeroCountFromBit(const int &num) {
int zeroCnt = 0;
for (int i = 0; i < 32; ++i) {
if (!(num & (1 << i)))
++zeroCnt;
}
return zeroCnt;
}
// Iterating through subsets
// The following code goes through the subsets of {0,1,...,n¡1}
void Iterating1(const int &n) {
for (int b = 0; b < (1 << n); ++b) {
PrintBit(b, n);
}
cout << "\n";
}
// The following code goes through the subsets with exactly k elements
void Iterating2(const int &n, const int &k) {
for (int b = 0; b < (1 << n); ++b) {
if (GetOneCountFromBit(b) == k) {
PrintBit(b, n);
}
}
cout << "\n";
}
// The following code goes through the subsets of a set x
void Iterating3(const int &x) {
int b = 0;
do {
PrintBit(b, x);
} while (b = (b - x) & x);
cout << "\n";
}
int main() {
int num = 9;
cout << "Original bit\n";
PrintBit(num, 32);
cout << "Change zero\n";
BitToZero(num, 1);
BitToZero(num, 2);
cout << "Change one\n";
BitToOne(num, 1);
BitToOne(num, 0);
cout << "Invert bit\n";
InvertBit(num, 1);
InvertBit(num, 0);
cout << "LastOneBitToZero\n";
LastOneBitToZero(num);
cout << "AllTheOneBitToZero\n";
AllTheOneBitToZero(num);
cout << "InvertsAllBitsLastOneBit\n";
InvertsAllTheBitsAfterLastOneBit(num);
cout << "~~~~~~\n";
CheckPowerOfTwo(num);
cout << "Prints all elements that belong to set\n";
PrintsAllElements(num);
cout << "Counts the number of bits set to zero.\n";
cout << GetZeroCountFromBit(num) << "\n";
cout << "Counts the number of bits set to one.\n";
cout << GetOneCountFromBit(num) << "\n";
/////////////// Iterating
cout << "The following code goes through the subsets of {0,1,...,n¡1}\n";
Iterating1(4);
cout << "The following code goes through the subsets with exactly k elements\n";
Iterating2(4, 3);
cout << "The following code goes through the subsets of a set x\n";
Iterating3(60);
return 0;
} | [
"gkagm2@gmail.com"
] | gkagm2@gmail.com |
883ca54531699024b5c935af0a50c060bd469118 | 00484c76b7737829b753130986fcccb921baf5ec | /Broker/include/logger.hpp | da65f3c43985c4786b0cfe1905b281cb37bca9e3 | [] | no_license | ylztf/LWI | 94072b14ec211b32cc3fe8a7b28cfb153eedd18e | 553d2ff4521056e9fd31fb79774f0b96b232faaf | refs/heads/master | 2021-01-20T23:32:26.739808 | 2012-01-27T16:11:00 | 2012-01-27T16:11:00 | 2,710,309 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,097 | hpp | #ifndef __LOGGER_HPP__
#define __LOGGER_HPP__
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <iostream>
#include <string>
using namespace boost::posix_time;
namespace Logger {
class Log : public boost::iostreams::sink
{
public:
Log( int level_, const char * name_, std::ostream *out_= &std::clog ) :
m_level(level_), m_name( name_ ), m_ostream( out_ )
{
};
std::streamsize write( const char* s, std::streamsize n)
{
if( m_filter >= m_level ){
*m_ostream << microsec_clock::local_time() << " : "
<< m_name << "(" << m_level << "):\t";
boost::iostreams::write( *m_ostream, s, n);
}
return n;
};
static void setLevel( const int p_level )
{
m_filter = p_level;
}
private:
static int m_filter;
const int m_level;
const std::string m_name;
std::ostream *m_ostream;
};
}
#define CREATE_LOG( level, name ) \
boost::iostreams::stream<Logger::Log> name( level, #name )
#define CREATE_EXTERN_LOG( level, name ) \
boost::iostreams::stream<Logger::Log> name
#define CREATE_STD_LOGS() \
namespace Logger { \
CREATE_LOG(7, Debug); \
CREATE_LOG(6, Info); \
CREATE_LOG(5, Notice); \
CREATE_LOG(4, Warn); \
CREATE_LOG(3, Error); \
CREATE_LOG(2, Critical); \
CREATE_LOG(1, Alert); \
CREATE_LOG(0, Fatal); \
int Log::m_filter=0; \
}
#ifndef CREATE_EXTERN_STD_LOGS
#define CREATE_EXTERN_STD_LOGS() \
namespace Logger { \
extern CREATE_EXTERN_LOG(7, Debug); \
extern CREATE_EXTERN_LOG(6, Info); \
extern CREATE_EXTERN_LOG(5, Notice); \
extern CREATE_EXTERN_LOG(4, Warn); \
extern CREATE_EXTERN_LOG(3, Error); \
extern CREATE_EXTERN_LOG(2, Critical); \
extern CREATE_EXTERN_LOG(1, Alert); \
extern CREATE_EXTERN_LOG(0, Fatal); \
}
#else
#undef CREATE_EXTERN_STD_LOGS
#define CREATE_EXTERN_STD_LOGS()
#endif
#endif // __LOGGER_HPP__
| [
"scj7t4@mst.edu"
] | scj7t4@mst.edu |
38e320708a0fcaca9e28a0356473ee571d352428 | cb5b061a07eaaaef65aaf674a82d82fbb4eea0c0 | /depends/sdk/include/nsIConsoleListener.h | ef1dd5bb5b2bbf22e0f765253860d2dd8789151d | [] | no_license | shwneo/MonacoIDE | 5a5831a1553b2af10844aa5649e302c701fd4fb4 | 6d5d08733c2f144d60abc4aeb7b6a1a3d5e349d5 | refs/heads/master | 2016-09-06T07:34:03.315445 | 2014-06-01T15:06:34 | 2014-06-01T15:06:34 | 17,567,104 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,545 | h | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM d:/xulrunner-24.0.source/mozilla-release/xpcom/base/nsIConsoleListener.idl
*/
#ifndef __gen_nsIConsoleListener_h__
#define __gen_nsIConsoleListener_h__
#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif
#ifndef __gen_nsIConsoleMessage_h__
#include "nsIConsoleMessage.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
/* starting interface: nsIConsoleListener */
#define NS_ICONSOLELISTENER_IID_STR "eaaf61d6-1dd1-11b2-bc6e-8fc96480f20d"
#define NS_ICONSOLELISTENER_IID \
{0xeaaf61d6, 0x1dd1, 0x11b2, \
{ 0xbc, 0x6e, 0x8f, 0xc9, 0x64, 0x80, 0xf2, 0x0d }}
class NS_NO_VTABLE nsIConsoleListener : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_ICONSOLELISTENER_IID)
/* void observe (in nsIConsoleMessage aMessage); */
NS_IMETHOD Observe(nsIConsoleMessage *aMessage) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIConsoleListener, NS_ICONSOLELISTENER_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSICONSOLELISTENER \
NS_IMETHOD Observe(nsIConsoleMessage *aMessage);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSICONSOLELISTENER(_to) \
NS_IMETHOD Observe(nsIConsoleMessage *aMessage) { return _to Observe(aMessage); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSICONSOLELISTENER(_to) \
NS_IMETHOD Observe(nsIConsoleMessage *aMessage) { return !_to ? NS_ERROR_NULL_POINTER : _to->Observe(aMessage); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsConsoleListener : public nsIConsoleListener
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSICONSOLELISTENER
nsConsoleListener();
private:
~nsConsoleListener();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsConsoleListener, nsIConsoleListener)
nsConsoleListener::nsConsoleListener()
{
/* member initializers and constructor code */
}
nsConsoleListener::~nsConsoleListener()
{
/* destructor code */
}
/* void observe (in nsIConsoleMessage aMessage); */
NS_IMETHODIMP nsConsoleListener::Observe(nsIConsoleMessage *aMessage)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIConsoleListener_h__ */
| [
"shwneo@gmail.com"
] | shwneo@gmail.com |
34d22130ce93e10d25a4fb7a3329c030526a3af0 | cbb13682934e5694137b430d915ff42d14f5f9eb | /qt_pc_tool/dialogportconfig.cpp | 8d3cc8723ea4e56ed621ea0f40550600cc7416fb | [] | no_license | pandarong/epaper_price_tag_mod | 62f60af07177b7bf241a977f85ebc0b4fad582be | beea4f5493816d6e0d99a918edb4bfe7fd3d5d34 | refs/heads/master | 2023-01-13T11:33:47.352350 | 2020-11-20T04:06:22 | 2020-11-20T04:06:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,410 | cpp | #include "dialogportconfig.h"
#include "ui_dialogportconfig.h"
#include <QDebug>
DialogPortConfig::DialogPortConfig(QWidget *parent) :
QDialog(parent),
ui(new Ui::DialogPortConfig)
{
ui->setupUi(this);
refreshPortList();
}
DialogPortConfig::~DialogPortConfig()
{
delete ui;
}
//void DialogPortConfig::setPortName(QString &name)
//{
// qDebug() << __PRETTY_FUNCTION__ << " not implemented";
//}
QString DialogPortConfig::getPortName()
{
return selectedPortName;
}
void DialogPortConfig::on_pushButtonRefresh_clicked()
{
refreshPortList();
updateComboPortSelection(selectedPortName);
}
void DialogPortConfig::refreshPortList()
{
ui->comboBoxPorts->clear();
ui->labelPortName->setText("");
ui->labelPortManufact->setText("");
ui->labelPortDesc->setText("");
portInfos = QSerialPortInfo::availablePorts();
qDebug() << "available ports: " << portInfos.size();
foreach(QSerialPortInfo portInfo, portInfos) {
qDebug() << "portName:" << portInfo.portName();
qDebug() << "manufacturer: " << portInfo.manufacturer();
qDebug() << "desceiption: " << portInfo.description();
qDebug() << "------------------------------------";
ui->comboBoxPorts->addItem(portInfo.portName());
}
}
void DialogPortConfig::updateComboPortSelection(QString &portName)
{
for (int i = 0; i < ui->comboBoxPorts->count(); i++) {
if (selectedPortName == ui->comboBoxPorts->itemText(i)) {
ui->comboBoxPorts->setCurrentIndex(i);
break;
}
}
}
void DialogPortConfig::on_comboBoxPorts_currentIndexChanged(int index)
{
if (index < 0 || index >= portInfos.size()) {
qDebug() << "invalid index, ignore";
return;
}
QSerialPortInfo info = portInfos[index];
ui->labelPortName->setText(info.portName());
ui->labelPortManufact->setText(info.manufacturer());
ui->labelPortDesc->setText(info.description());
}
void DialogPortConfig::accept()
{
qDebug() << __PRETTY_FUNCTION__;
if (ui->comboBoxPorts->count()) {
selectedPortName = ui->comboBoxPorts->currentText();
} else {
selectedPortName = "";
}
QDialog::accept();
}
void DialogPortConfig::reject()
{
qDebug() << __PRETTY_FUNCTION__;
// restore previous selected port name
updateComboPortSelection(selectedPortName);
QDialog::reject();
}
| [
"muyuchl@gmail.com"
] | muyuchl@gmail.com |
32e6dfb8c515b6626a8af5951dc8edbb2f8b6dc1 | d5ea515c05675f85c8cde30692f413508afe3955 | /models/dcmtk/ofstd/include/dcmtk/ofstd/offile.h | 05748ba842ca745244b5596c1b911ed738299c0f | [
"MIT"
] | permissive | VB6Hobbyst7/raccoon | 6b2ac98e535f8c6e82c2ca9a4f0a4f15e17816b0 | a7a65051be14dddb2544aa34cc411133ac0272e6 | refs/heads/main | 2023-06-19T11:17:07.927356 | 2021-07-10T09:24:13 | 2021-07-10T09:24:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 41,143 | h | /*
*
* Copyright (C) 2006-2021, OFFIS e.V.
* All rights reserved. See COPYRIGHT file for details.
*
* This software and supporting documentation were developed by
*
* OFFIS e.V.
* R&D Division Health
* Escherweg 2
* D-26121 Oldenburg, Germany
*
*
* Module: ofstd
*
* Author: Marco Eichelberg, Joerg Riesmeier
*
* Purpose: C++ wrapper class for stdio FILE functions and
* wide character filenames
*
*/
#ifndef OFFILE_H
#define OFFILE_H
#include "dcmtk/config/osconfig.h"
#include "dcmtk/ofstd/oftypes.h" /* for class OFBool */
#include "dcmtk/ofstd/ofstring.h" /* for class OFString */
#include "dcmtk/ofstd/ofstd.h" /* for class OFStandard */
#define INCLUDE_UNISTD
#define INCLUDE_CSTDIO
#define INCLUDE_CSTRING
#define INCLUDE_CSTDARG
#define INCLUDE_CERRNO
//#define INCLUDE_CWCHAR /* not yet implemented in "ofstdinc.h" */
#include "dcmtk/ofstd/ofstdinc.h"
BEGIN_EXTERN_C
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h> /* needed for struct _stati64 on Win32 */
#endif
END_EXTERN_C
#ifdef HAVE_UNIX_H
#include <unix.h> /* needed for setlinebuf() on QNX */
#endif
/* HP-UX has clearerr both as macro and as a function definition. We have to
* undef the macro so that we can define a function called "clearerr".
*/
#if defined(__hpux) && defined(clearerr)
#undef clearerr
#endif
/* When using the ISO C++ include files such as <cstdio>, <cstdarg> etc.,
* all ANSI C functions like fopen() are declared in namespace std,
* (e.g. we have to use std::fopen()), but non-ANSI Posix functions remain
* in global namespace, e.g. we have to use ::fopen64().
* To make things even more difficult, not all compilers really declare
* ANSI C functions in namespace std in accordance with the C++ standard.
* Yes, this is ugly.
*/
/* Find out whether to use explicit LFS function calls to handle
* large file support
*/
#if defined(DCMTK_ENABLE_LFS) && DCMTK_ENABLE_LFS == DCMTK_LFS64
#define EXPLICIT_LFS_64
// Use POSIX 64 bit file position type when available
#ifdef HAVE_FPOS64_T
typedef fpos64_t offile_fpos_t;
#else // Otherwise this should be sufficient
typedef fpos_t offile_fpos_t;
#endif
// Use POSIX 64 bit file offset type when available
#ifdef HAVE_OFF64_T
typedef off64_t offile_off_t;
#elif !defined(OF_NO_SINT64) // Otherwise use a 64 bit integer
typedef Sint64 offile_off_t;
#else // Cry when 64 LFS is required but no 64 bit integer exists
#error \
Could not find a suitable offset-type for LFS64 support.
#endif
#else // Implicit LFS or no LFS
#if defined(DCMTK_ENABLE_LFS) && DCMTK_ENABLE_LFS == DCMTK_LFS
#if defined(SIZEOF_FPOS_T) && (!defined(SIZEOF_OFF_T) || SIZEOF_FPOS_T > SIZEOF_OFF_T)
// strange Windows LFS where sizeof(fpos_t) == 8 but sizeof(off_t) == 4
#ifndef OF_NO_SINT64 // Use a 64 bit integer
typedef Sint64 offile_off_t;
#else // Cry when LFS is required but no 64 bit integer exists
#error \
Could not find a suitable offset-type for LFS support.
#endif
#else
typedef off_t offile_off_t;
#endif
#elif defined(HAVE_FSEEKO)
typedef off_t offile_off_t;
#else
typedef long offile_off_t;
#endif
typedef fpos_t offile_fpos_t;
#endif // basic type definitions
// the type we use to store the last error.
typedef int offile_errno_t;
// forward declarations
class OFpath;
/** class for managing filenames consisting either of conventional (8-bit) or
* wide (e.g.\ 16-bit) characters. The wide character support is currently
* Windows-specific because most other operating systems use UTF-8, which is
* compatible with conventional 8-bit character strings.
*/
class DCMTK_OFSTD_EXPORT OFFilename
{
public:
/** default constructor
*/
OFFilename();
/** constructor expecting a conventional character string
* @param filename filename to be stored (8-bit characters, e.g. UTF-8)
* @param convert convert given filename to wide character encoding as an
* alternative representation. Only works on Windows systems.
*/
OFFilename(const char *filename,
const OFBool convert = OFFalse);
/** constructor expecting a character string as an OFString instance
* @param filename filename to be stored (8-bit characters, e.g. UTF-8)
* @param convert convert given filename to wide character encoding as an
* alternative representation. Only works on Windows systems.
*/
OFFilename(const OFString &filename,
const OFBool convert = OFFalse);
/** constructor expecting an OFpath instance
* @param path OFpath instance storing a filename in native format
* (currently, identical to an 8-bit character string)
* @param convert convert given filename to wide character encoding as an
* alternative representation. Only works on Windows systems.
*/
OFFilename(const OFpath &path,
const OFBool convert = OFFalse);
#if (defined(WIDE_CHAR_FILE_IO_FUNCTIONS) || defined(WIDE_CHAR_MAIN_FUNCTION)) && defined(_WIN32)
/** constructor expecting a wide character string
* @remark This constructor is only available if DCMTK is compiled on Windows
* Operating Systems with wide chars enabled (defining _WIN32 as well as
* WIDE_CHAR_FILE_IO_FUNCTIONS or WIDE_CHAR_MAIN_FUNCTION).
* @param filename filename to be stored (e.g. 16-bit characters)
* @param convert convert given filename to UTF-8 encoding as an
* alternative representation. Only works on Windows systems.
*/
OFFilename(const wchar_t *filename,
const OFBool convert = OFTrue);
#endif
/** copy constructor
* @param arg filename object to be copied
*/
OFFilename(const OFFilename &arg);
/** destructor. Frees memory.
*/
~OFFilename();
/** assignment operator
* @param arg filename object to be copied
* @return reference to this filename object
*/
OFFilename &operator=(const OFFilename &arg);
/** clear currently stored filename
*/
void clear();
/** fast, non-throwing swap function. The time complexity of this function
* is constant.
* @param arg filename object to swap with
*/
void swap(OFFilename &arg);
/** check whether this object stores an empty filename
* @return OFTrue if the filename is empty, OFFalse otherwise
*/
OFBool isEmpty() const;
/** check whether this object stores a wide character filename
* @return OFTrue if the filename uses wide characters, OFFalse otherwise
*/
inline OFBool usesWideChars() const
{
#if (defined(WIDE_CHAR_FILE_IO_FUNCTIONS) || defined(WIDE_CHAR_MAIN_FUNCTION)) && defined(_WIN32)
return (wfilename_ != NULL);
#else
return OFFalse;
#endif
}
/** get stored filename consisting of conventional characters
* @return filename (might be NULL if none is stored)
*/
inline const char *getCharPointer() const
{
return filename_;
}
#if (defined(WIDE_CHAR_FILE_IO_FUNCTIONS) || defined(WIDE_CHAR_MAIN_FUNCTION)) && defined(_WIN32)
/** get stored filename consisting of wide characters
* @remark This method is only available if DCMTK is compiled on Windows
* Operating Systems with wide chars enabled (defining _WIN32 as well as
* WIDE_CHAR_FILE_IO_FUNCTIONS or WIDE_CHAR_MAIN_FUNCTION).
* @return wide char filename (might be NULL if none is stored)
*/
inline const wchar_t *getWideCharPointer() const
{
return wfilename_;
}
#endif
/** check whether the standard input or output streams should be used by
* comparing the filename with "-"
* @return OFTrue if stdin or stdout should be used, OFFalse otherwise
*/
OFBool isStandardStream() const
{
OFBool result = OFFalse;
#if defined(WIDE_CHAR_FILE_IO_FUNCTONS) && defined(_WIN32)
if (usesWideChars())
{
result = (wcscmp(getWideCharPointer(), L"-") == 0);
} else
#endif
if (getCharPointer() != NULL)
{
result = (strcmp(getCharPointer(), "-") == 0);
}
return result;
}
/** replace currently stored filename by given value
* @param filename filename to be stored (8-bit characters, e.g. UTF-8)
* @param convert convert given filename to wide character encoding as an
* alternative representation. Only works on Windows systems.
*/
void set(const char *filename,
const OFBool convert = OFFalse);
/** replace currently stored filename by given value
* @param filename filename to be stored (8-bit characters, e.g. UTF-8)
* @param convert convert given filename to wide character encoding as an
* alternative representation). Only works on Windows systems.
*/
void set(const OFString &filename,
const OFBool convert = OFFalse);
/** replace currently stored filename by given value
* @param OFpath OFpath instance storing a filename in native format
* (currently, identical to an 8-bit character string)
* @param convert convert given filename to wide character encoding as an
* alternative representation). Only works on Windows systems.
*/
void set(const OFpath &path,
const OFBool convert = OFFalse);
#if (defined(WIDE_CHAR_FILE_IO_FUNCTIONS) || defined(WIDE_CHAR_MAIN_FUNCTION)) && defined(_WIN32)
/** replace currently stored filename by given value
* @remark This method is only available if DCMTK is compiled on Windows
* Operating Systems with wide chars enabled (defining _WIN32 as well as
* WIDE_CHAR_FILE_IO_FUNCTIONS or WIDE_CHAR_MAIN_FUNCTION).
* @param filename filename to be stored (e.g. 16-bit characters)
* @param convert convert given filename to UTF-8 encoding as an alternative
* representation. Only works on Windows systems.
*/
void set(const wchar_t *filename,
const OFBool convert = OFTrue);
#endif
private:
/// filename consisting of conventional characters (8-bit, e.g.\ UTF-8)
char *filename_;
#if (defined(WIDE_CHAR_FILE_IO_FUNCTIONS) || defined(WIDE_CHAR_MAIN_FUNCTION)) && defined(_WIN32)
/// filename consisting of wide characters (e.g. 16-bit on Windows)
/// @remark This member is only available if DCMTK is compiled on Windows
/// Operating Systems with wide chars enabled (defining _WIN32 as well as
/// WIDE_CHAR_FILE_IO_FUNCTIONS or WIDE_CHAR_MAIN_FUNCTION).
wchar_t *wfilename_;
#endif
};
/** swap function for OFFilename class. The time complexity of this function
* is constant.
* @param lhs left-hand side filename
* @param rhs right-hand side filename
*/
inline void swap(OFFilename &lhs, OFFilename &rhs)
{
lhs.swap(rhs);
}
/** output filename to the given stream.
* Only the string of conventional characters (e.g. ASCII or UTF-8) is printed since
* we do not expect the output stream (console or logger) to support wide characters.
* @param stream output stream
* @param filename OFFilename object to print
* @return reference to the output stream
*/
DCMTK_OFSTD_EXPORT STD_NAMESPACE ostream &operator<<(STD_NAMESPACE ostream &stream, const OFFilename &filename);
/** this class provides a simple C++ encapsulation layer for stdio FILE pointers.
* All stdio functions on files are directly mapped into member functions.
* The handling of large files (64 bit file systems) is transparent. Instead
* of type off_t, fseek() and ftell() use offile_off_t which is a 64 bit type
* if available on the underlying platform. Similarly, getpos() and setpos() use
* type offile_fpos_t, which is defined appropriately.
* This class provides both fclose() and pclose(), but these are equivalent -
* the code always closes pipes with pclose() and files with fclose().
* Finally, an abstraction for errno is provided. Error codes should always
* be retrieves using methods getLastError() and getLastErrorString() which
* on Unix platforms are based on errno and strerror/strerror_r, but may be based
* on other mechanisms on platforms where errno does not exist.
*/
class OFFile
{
public:
/// default constructor, creates an object that is not associated with any file.
OFFile(): file_(NULL), popened_(OFFalse), lasterror_(0) {}
/** create object for given stdio FILE
* @param f stdio FILE
*/
OFFile(FILE *f): file_(f), popened_(OFFalse), lasterror_(0) {}
/// destructor. Closes file if still open.
~OFFile()
{
if (file_) fclose();
}
/** opens the file whose name is the string pointed to by path and associates
* a stream with it.
* @param filename path to file
* @param modes "r", "w" or "a" with possible modifiers "+", "b"
* @return true if stream was successfully created, false otherwise, in which
* case the error code is set.
*/
OFBool fopen(const char *filename, const char *modes)
{
if (file_) fclose();
#ifdef EXPLICIT_LFS_64
file_ = :: fopen64(filename, modes);
#else
file_ = STDIO_NAMESPACE fopen(filename, modes);
#endif
if (file_) popened_ = OFFalse; else storeLastError();
return (file_ != NULL);
}
#if defined(WIDE_CHAR_FILE_IO_FUNCTIONS) && defined(_WIN32)
/** opens the file whose name is the wide character string pointed to by path and
* associates a stream with it.
* @remark This member is only available if DCMTK is compiled on Windows
* Operating Systems with wide chars enabled (defining _WIN32 as well as
* WIDE_CHAR_FILE_IO_FUNCTIONS).
* @param filename Unicode filename path to file
* @param modes "r", "w" or "a" with possible modifiers "+", "b", as a wide
* character string
* @return true if stream was successfully created, false otherwise, in which case
* the error code is set.
*/
OFBool wfopen(const wchar_t *filename, const wchar_t *modes)
{
if (file_) fclose();
file_ = _wfopen(filename, modes);
if (file_) popened_ = OFFalse; else storeLastError();
return (file_ != NULL);
}
#endif
/** opens the file whose name is a conventional or wide character string pointed to
* by path and associates. The wide character support is currently Windows-specific.
* @param filename object containing the filename path to file
* @param modes "r", "w" or "a" with possible modifiers "+", "b"
* @return true if stream was successfully created, false otherwise, in which case
* the error code is set.
*/
OFBool fopen(const OFFilename &filename, const char *modes)
{
OFBool result = OFFalse;
#if defined(WIDE_CHAR_FILE_IO_FUNCTIONS) && defined(_WIN32)
if (filename.usesWideChars())
{
// convert file mode to wide char string
const size_t length = strlen(modes) + 1;
wchar_t *wmodes = new wchar_t[length];
if (wmodes != NULL)
{
for (size_t i = 0; i < length; ++i)
{
// conversion of ASCII codes (7-bit) is easy
wmodes[i] = OFstatic_cast(wchar_t, modes[i]);
}
result = wfopen(filename.getWideCharPointer(), wmodes);
}
delete[] wmodes;
} else
#endif
result = fopen(filename.getCharPointer(), modes);
return result;
}
/** associates a stream with the existing file descriptor 'fd'. The mode of
* the stream (one of the values "r", "r+", "w", "w+", "a", "a+") must be
* compatible with the mode of the file descriptor. The file position
* indicator of the new stream is set to that belonging to 'fd', and the
* error and end-of-file indicators are cleared. Modes "w" or "w+" do not
* cause truncation of the file. The file descriptor is not dup'ed, and
* will be closed when the stream created by fdopen is closed. The result
* of applying fdopen to a shared memory object is undefined.
* @param fd file descriptor
* @param modes "r", "w" or "a" with possible modifiers "+", "b"
* @return true if stream was successfully created, false otherwise, in
* which case the error code is set.
*/
OFBool fdopen(int fd, const char *modes)
{
if (file_) fclose();
file_ = :: fdopen(fd, modes);
if (file_) popened_ = OFFalse; else storeLastError();
return (file_ != NULL);
}
/** opens a process by creating a pipe, forking, and invoking the shell.
* Since a pipe is by definition unidirectional, the type argument may
* specify only reading or writing, not both; the resulting stream is
* correspondingly read-only or write-only. If the object was already
* associated with another file or pipe, that one is closed.
* @param command shell command line
* @param modes "r" or "w"
* @return true if pipe was successfully created, false otherwise
*/
OFBool popen(const char *command, const char *modes)
{
if (file_) fclose();
#ifdef HAVE_POPEN
file_ = :: popen(command, modes);
#else
file_ = _popen(command, modes);
#endif
if (file_) popened_ = OFTrue; else storeLastError();
return (file_ != NULL);
}
/** opens the file whose name is the string pointed to by path and associates
* the stream pointed maintained by this object with it. The original stream
* (if it exists) is closed. The mode argument is used just as in the fopen
* function. The primary use of the freopen function is to change the file
* associated with a standard text stream (stderr, stdin, or stdout).
* @param filename path to file
* @param modes "r", "w" or "a" with possible modifiers "+", "b"
* @return true if stream was successfully created, false otherwise, in
* which case the error code is set.
*/
OFBool freopen(const char *filename, const char *modes)
{
#if defined(EXPLICIT_LFS_64) && ! defined(__MINGW32__)
// MinGW has EXPLICIT_LFS_64 but no freopen64()
file_ = :: freopen64(filename, modes, file_);
#else
file_ = STDIO_NAMESPACE freopen(filename, modes, file_);
#endif
if (file_) popened_ = OFFalse; else storeLastError();
return (file_ != NULL);
}
/** generates a unique temporary filename. The temporary file is then opened
* in binary read/write (w+b) mode. The file will be automatically deleted
* when it is closed or the program terminates normally.
* @return true if stream was successfully created, false otherwise, in
* which case the error code is set.
*/
OFBool tmpfile()
{
if (file_) fclose();
#if defined(EXPLICIT_LFS_64) && ! defined(__MINGW32__)
// MinGW has EXPLICIT_LFS_64 but no tmpfile64()
file_ = :: tmpfile64();
#else
file_ = STDIO_NAMESPACE tmpfile();
#endif
if (file_) popened_ = OFFalse; else storeLastError();
return (file_ != NULL);
}
/** dissociates the named stream from its underlying file or set of functions.
* If the stream was being used for output, any buffered data is written
* first, using fflush. Independent of the return value of this method,
* any further access (including another call to fclose()) to the stream
* maintained by this object results in undefined behaviour.
* @return 0 upon success, EOF otherwise, in which case the error code is set.
*/
int fclose()
{
int result = 0;
if (file_)
{
if (popened_)
{
#ifdef HAVE_PCLOSE
result = :: pclose(file_);
#else
result = _pclose(file_);
#endif
}
else
{
result = STDIO_NAMESPACE fclose(file_);
}
// After calling fclose() once, the FILE* is gone even if fclose() failed.
file_ = NULL;
}
if (result) storeLastError();
return result;
}
/** waits for the associated process (created with popen) to terminate and
* returns the exit status of the command as returned by wait4.
* In this implementation, fclose and pclose can be used synonymously.
* @return process ID of the child which exited, or -1 on error, in which
* case the error code is set
*/
int pclose() { return fclose(); }
/** writes n elements of data, each size bytes long, to the stream, obtaining
* them from the location given by ptr. Returns the number of items successfully written
* (i.e., not the number of characters). If an error occurs the return value is a short
* item count (or zero).
* @param ptr pointer to buffer
* @param size size of item
* @param n number of items
* @return number of items written
*/
size_t fwrite(const void *ptr, size_t size, size_t n)
{
return STDIO_NAMESPACE fwrite(ptr, size, n, file_);
}
/** reads n elements of data, each size bytes long, from the stream, storing
* them at the location given by ptr. Returns the number of items successfully
* read (i.e., not the number of characters). If an error occurs, or the
* end-of-file is reached, the return value is a short item count (or zero).
* fread does not distinguish between end-of-file and error, and callers must
* use feof and ferror to determine which occurred.
* @param ptr pointer to buffer
* @param size size of item
* @param n number of items
* @return number of items read
*/
size_t fread(void *ptr, size_t size, size_t n)
{
return STDIO_NAMESPACE fread(ptr, size, n, file_);
}
/** forces a write of all user-space buffered data for the given output or
* update stream via the stream's underlying write function. The open status
* of the stream is unaffected.
* @return 0 upon success, EOF otherwise, in which case the error code is set.
*/
int fflush()
{
int result = STDIO_NAMESPACE fflush(file_);
if (result) storeLastError();
return result;
}
/** reads the next character from stream and returns it as an unsigned char
* cast to an int, or EOF on end of file or error.
* @return next character from stream or EOF
*/
int fgetc() { return STDIO_NAMESPACE fgetc(file_); }
/** The three types of buffering available are unbuffered, block buffered, and
* line buffered. When an output stream is unbuffered, information appears on
* the destination file or terminal as soon as written; when it is block
* buffered many characters are saved up and written as a block; when it is
* line buffered characters are saved up until a newline is output or input
* is read from any stream attached to a terminal device (typically stdin).
* Normally all files are block buffered. if a stream refers to a terminal
* (as stdout normally does) it is line buffered. The standard error stream
* stderr is always unbuffered by default. this function allows to set the
* mode of the stream to line buffered.
* @return 0 upon success, nonzero otherwise, in which case the error code may be set
*
*/
void setlinebuf()
{
#if defined(_WIN32) || defined(__hpux)
this->setvbuf(NULL, _IOLBF, 0);
#else
:: setlinebuf(file_);
#endif
}
/** sets the file position indicator for the stream pointed to by stream to
* the beginning of the file. This is equivalent to fseek(0, SEEK_SET)
* except that the error indicator for the stream is also cleared.
*/
void rewind()
{
#if defined(_WIN32) || defined(__CYGWIN__)
/* On these platforms rewind() fails after reading to the end of file
* if the file is read-only. Using fseek() instead.
*/
(void) this->fseek(0L, SEEK_SET);
#else
STDIO_NAMESPACE rewind(file_);
#endif
}
/** clears the end-of-file and error indicators for the stream
*/
void clearerr() { STDIO_NAMESPACE clearerr(file_); }
/** tests the end-of-file indicator for the stream, returning non-zero if it
* is set. The end-of-file indicator can only be cleared by the function
* clearerr. This method is called eof, not feof, because feof() is a macro
* on some systems and, therefore, cannot be used as a method name.
* @return non-zero if EOF, zero otherwise
*/
int eof() const
{
#ifdef feof
// feof is a macro on some systems. Macros never have namespaces.
return feof(file_);
#else
return STDIO_NAMESPACE feof(file_);
#endif
}
/** tests the error indicator for the stream, returning non-zero if it is set.
* This method is named error, not ferror, because ferror() is a macro
* on some systems and, therefore, cannot be used as a method name.
* The error indicator can only be reset by the clearerr function.
* @return non-zero if error flag is set, zero otherwise
*/
int error()
{
#ifdef ferror
// ferror is a macro on some systems. Macros never have namespaces.
return ferror(file_);
#else
return STDIO_NAMESPACE ferror(file_);
#endif
}
/** returns the low-level file descriptor associated with the stream.
* The spelling of this member function is different from stdio fileno()
* because on some systems (such as MinGW) fileno() is a macro
* and, therefore, cannot be used as a method name.
* @return low-level file descriptor associated with stream
*/
#ifdef fileno
int fileNo() { return fileno(file_); }
#else
int fileNo() { return :: fileno(file_); }
#endif
/** The three types of buffering available are unbuffered, block buffered, and
* line buffered. When an output stream is unbuffered, information appears on
* the destination file or terminal as soon as written; when it is block
* buffered many characters are saved up and written as a block; when it is
* line buffered characters are saved up until a newline is output or input
* is read from any stream attached to a terminal device (typically stdin).
* Normally all files are block buffered. if a stream refers to a terminal
* (as stdout normally does) it is line buffered. The standard error stream
* stderr is always unbuffered by default. This function allows to set the
* mode of the stream to unbuffered (if buf is NULL) or block buffered.
* @param buf pointer to buffer of size BUFSIZ as declared in cstdio, or NULL
* @return 0 upon success, nonzero otherwise, in which case the error code may be set
*/
void setbuf(char *buf) { STDIO_NAMESPACE setbuf(file_, buf); }
/** The three types of buffering available are unbuffered, block buffered, and
* line buffered. When an output stream is unbuffered, information appears on
* the destination file or terminal as soon as written; when it is block
* buffered many characters are saved up and written as a block; when it is
* line buffered characters are saved up until a newline is output or input
* is read from any stream attached to a terminal device (typically stdin).
* Normally all files are block buffered. if a stream refers to a terminal
* (as stdout normally does) it is line buffered. The standard error stream
* stderr is always unbuffered by default. This function allows to set the
* stream mode.
* @param buf pointer to buffer, may be NULL
* @param modes _IONBF (unbuffered) _IOLBF (line buffered) or _IOFBF (fully buffered)
* @param n size of buffer, in bytes
* @return 0 upon success, nonzero otherwise, in which case the error code may be set
*/
int setvbuf(char * buf, int modes, size_t n)
{
int result = STDIO_NAMESPACE setvbuf(file_, buf, modes, n);
if (result) storeLastError();
return result;
}
/** The three types of buffering available are unbuffered, block buffered, and
* line buffered. When an output stream is unbuffered, information appears on
* the destination file or terminal as soon as written; when it is block
* buffered many characters are saved up and written as a block; when it is
* line buffered characters are saved up until a newline is output or input
* is read from any stream attached to a terminal device (typically stdin).
* Normally all files are block buffered. if a stream refers to a terminal
* (as stdout normally does) it is line buffered. The standard error stream
* stderr is always unbuffered by default. This function allows to set the
* mode of the stream to unbuffered (if buf is NULL) or block buffered.
* @param buf pointer to buffer
* @param size size of buffer, in bytes
* @return 0 upon success, nonzero otherwise, in which case the error code may be set
*/
void setbuffer(char *buf, size_t size)
{
#if defined(_WIN32) || defined(__hpux)
this->setvbuf(NULL, buf ? _IOFBF : _IONBF, size);
#else
:: setbuffer(file_, buf, size);
#endif
}
/** writes the character c, cast to an unsigned char, to stream.
* @param c character
* @return the character written as an unsigned char cast to an int or EOF on error
*/
int fputc(int c) { return STDIO_NAMESPACE fputc(c, file_); }
/** reads in at most one less than n characters from stream and stores them
* into the buffer pointed to by s. Reading stops after an EOF or a newline.
* If a newline is read, it is stored into the buffer. A '@\0' is stored after
* the last character in the buffer.
* @param s pointer to buffer of size n
* @param n buffer size
* @return pointer to string
*/
char *fgets(char *s, int n) { return STDIO_NAMESPACE fgets(s, n, file_); }
/** writes the string s to stream, without its trailing '@\0'.
* @param s string to be written
* @return a non-negative number on success, or EOF on error.
*/
int fputs(const char *s) { return STDIO_NAMESPACE fputs(s, file_); }
/** pushes c back to stream, cast to unsigned char, where it is available for
* subsequent read operations. Pushed - back characters will be returned in
* reverse order; only one pushback is guaranteed.
* @param c character to push back
* @return c on success, or EOF on error.
*/
int ungetc(int c) { return STDIO_NAMESPACE ungetc(c, file_); }
/** sets the file position indicator for the stream pointed to by stream. The
* new position, measured in bytes, is obtained by adding offset bytes to the
* position specified by whence. If whence is set to SEEK_SET, SEEK_CUR, or
* SEEK_END, the offset is relative to the start of the file, the current
* position indicator, or end-of-file, respectively. A successful call to the
* fseek function clears the end-of- file indicator for the stream and undoes
* any effects of the ungetc function on the same stream.
* @param off offset to seek to
* @param whence SEEK_SET, SEEK_CUR, or SEEK_END
* @return 0 upon success, -1 otherwise in which case the error code is set.
*/
int fseek(offile_off_t off, int whence)
{
int result;
#ifdef _WIN32
// Windows does not have a 64-bit fseek.
// We emulate fseek through fsetpos, which does exist on Windows.
// fpos_t is (hopefully always) defined as __int64 on this platform
offile_fpos_t off2 = off;
fpos_t pos;
struct _stati64 buf;
switch (whence)
{
case SEEK_END:
// flush write buffer, if any, so that the file size is correct
STDIO_NAMESPACE fflush(file_);
#if 0
// Python implementation based on _lseeki64(). May be unsafe because
// there is no guarantee that fflush also empties read buffers.
STDIO_NAMESPACE fflush(file_);
#ifdef fileno
if (_lseeki64( fileno(file_), 0, 2) == -1)
#else
if (_lseeki64(:: fileno(file_), 0, 2) == -1)
#endif
{
storeLastError();
return -1;
}
// fall through
#else
// determine file size (using underlying file descriptor). This should be safe.
#ifdef fileno
if (_fstati64( fileno(file_), &buf) == -1)
#else
if (_fstati64(:: fileno(file_), &buf) == -1)
#endif
{
storeLastError();
return -1;
}
// fsetpos position is offset + file size.
off2 += buf.st_size;
break;
#endif
case SEEK_CUR:
if (STDIO_NAMESPACE fgetpos(file_, &pos) != 0)
{
storeLastError();
return -1;
}
off2 += pos;
break;
case SEEK_SET:
/* do nothing */
break;
}
result = this->fsetpos(&off2);
#elif defined(__BEOS__)
result = :: _fseek(file_, off, whence);
#else
#ifdef HAVE_FSEEKO
#ifdef EXPLICIT_LFS_64
result = :: fseeko64(file_, off, whence);
#else
result = :: fseeko(file_, off, whence);
#endif
#else
result = STDIO_NAMESPACE fseek(file_, off, whence);
#endif
#endif
if (result) storeLastError();
return result;
}
/** obtains the current value of the file position indicator for the stream pointed to by the stream.
* @return current file position
*/
offile_off_t ftell()
{
offile_off_t result;
#ifdef _WIN32
// Windows does not have a 64-bit ftell, and _telli64 cannot be used
// because it operates on file descriptors and ignores FILE buffers.
// We emulate ftell through fgetpos, which does exist on Windows.
// fpos_t is (hopefully always) defined as __int64 on this platform.
offile_fpos_t pos;
if (this->fgetpos(&pos) != 0)
{
storeLastError();
return -1;
}
return pos;
#else
#ifdef HAVE_FSEEKO
#ifdef EXPLICIT_LFS_64
result = :: ftello64(file_);
#else
result = :: ftello(file_);
#endif
#else
result = STDIO_NAMESPACE ftell(file_);
#endif
#endif
if (result < 0) storeLastError();
return result;
}
/** alternate interface equivalent to ftell, storing the current value of the
* file offset into the object referenced by pos. On some non-UNIX systems an
* fpos_t object may be a complex object and these routines may be the only
* way to portably reposition a text stream.
* @param pos pointer to offile_fpos_t structure
* @return 0 upon success, -1 otherwise in which case the error code is set.
*/
int fgetpos(offile_fpos_t *pos)
{
int result;
#if defined(EXPLICIT_LFS_64) && ! defined(__MINGW32__) && ! defined(__QNX__)
// MinGW and QNX have EXPLICIT_LFS_64 but no fgetpos64()
result = :: fgetpos64(file_, pos);
#else
result = STDIO_NAMESPACE fgetpos(file_, pos);
#endif
if (result) storeLastError();
return result;
}
/** alternate interface equivalent to fseek (with whence set to SEEK_SET),
* setting the current value of the file offset from the object referenced by
* pos. On some non-UNIX systems an fpos_t object may be a complex object and
* these routines may be the only way to portably reposition a text stream.
* @param pos pointer to offile_fpos_t structure
* @return 0 upon success, -1 otherwise in which case the error code is set.
*/
int fsetpos(offile_fpos_t *pos)
{
int result;
#if defined(EXPLICIT_LFS_64) && ! defined(__MINGW32__) && ! defined(__QNX__)
// MinGW and QNX have EXPLICIT_LFS_64 but no fsetpos64()
result = :: fsetpos64(file_, pos);
#else
result = STDIO_NAMESPACE fsetpos(file_, pos);
#endif
if (result) storeLastError();
return result;
}
/** print formatted string into stream, see printf(3)
* @param format format string
* @param ... further parameters according to format string
* @return number of characters printed
*/
int fprintf(const char *format, ...)
{
int result = 0;
va_list ap;
va_start(ap, format);
result = STDIO_NAMESPACE vfprintf(file_, format, ap);
va_end(ap);
return result;
}
/** print formatted string into stream, see printf(3)
* @param format format string
* @param arg list of further parameters according to format string
* @return number of characters printed
*/
int vfprintf(const char *format, va_list arg)
{
return STDIO_NAMESPACE vfprintf(file_, format, arg);
}
// we cannot emulate fscanf because we would need vfscanf for this
// purpose, which does not exist, e.g. on Win32.
/** return FILE pointer managed by this object. This allows the user
* to call some stdio functions that are not encapsulated in this class
* (but possibly should be).
* @return pointer to FILE structure managed by this object
*/
FILE *file() { return file_; }
/** return true if this object is currently associated with a stream, false otherwise
* @return true if this object is currently associated with a stream, false otherwise
*/
OFBool open() const { return file_ != NULL; }
/** return last error code for this stream
* @return last error code for this stream
*/
offile_errno_t getLastError() const { return lasterror_; }
/** return string describing last error code for this stream
* @param s string describing last error code for this stream returned in this parameter
*/
void getLastErrorString(OFString& s) const
{
char buf[1000];
s = OFStandard::strerror(lasterror_, buf, 1000);
}
// wide character functions (disabled by default, since currently not used within DCMTK)
#ifdef WIDE_CHAR_FILE_IO_FUNCTIONS
/** When mode is zero, the fwide function determines the current orientation
* of stream. It returns a value > 0 if stream is wide-character oriented,
* i.e. if wide character I/O is permitted but char I/O is disallowed. It
* returns a value < 0 if stream is byte oriented, i.e. if char I/O is
* permitted but wide character I/O is disallowed. It returns zero if stream
* has no orientation yet; in this case the next I/O operation might change
* the orientation (to byte oriented if it is a char I/O operation, or to
* wide-character oriented if it is a wide character I/O operation).
* Once a stream has an orientation, it cannot be changed and persists until
* the stream is closed.
* When mode is non-zero, the fwide function first attempts to set stream's
* orientation (to wide-character oriented if mode > 0, or to byte oriented
* if mode < 0). It then returns a value denoting the current orientation, as
* above.
* @param mode mode of operation for fwide
* @return orientation of stream
*/
int fwide(int mode)
{
return STDIO_NAMESPACE fwide(file_, mode);
}
/** reads a wide character from stream and returns it. If the end of stream is
* reached, or if ferror(stream) becomes true, it returns WEOF. If a wide
* character conversion error occurs, it sets the error code to EILSEQ and returns
* WEOF.
* @return next character from stream or WEOF
*/
wint_t fgetwc()
{
wint_t result = STDIO_NAMESPACE fgetwc(file_);
if (result == WEOF) storeLastError();
return result;
}
/** writes the wide character wc to stream. If ferror(stream) becomes true, it returns WEOF.
* If a wide character conversion error occurs, it sets the error code to EILSEQ and returns WEOF.
* Otherwise it returns wc.
* @param wc wide character to write to stream
* @return character written or WEOF
*/
wint_t fputwc(wchar_t wc)
{
wint_t result = STDIO_NAMESPACE fputwc(wc, file_);
if (result == WEOF) storeLastError();
return result;
}
/** pushes back a wide character onto stream and returns it. If wc is WEOF, it
* returns WEOF. If wc is an invalid wide character, it sets errno to EILSEQ
* and returns WEOF. If wc is a valid wide character, it is pushed back onto
* the stream and thus becomes available for future wide character read
* operations. The file-position indicator is decremented by one or more.
* The end-of-file indicator is cleared. The backing storage of the file is
* not affected. Note: wc need not be the last wide character read from the
* stream; it can be any other valid wide character. If the implementation
* supports multiple push-back operations in a row, the pushed-back wide
* characters will be read in reverse order; however, only one level of
* push-back is guaranteed.
* @param wc wide character to put back to stream
* @return character put back or WEOF
*/
wint_t ungetwc(wint_t wc)
{
wint_t result = STDIO_NAMESPACE ungetwc(wc, file_);
if (result == WEOF) storeLastError();
return result;
}
/** print formatted wide string into stream, see wprintf(3)
* @param format format string
* @param ... further parameters according to format string
* @return number of characters printed
*/
int fwprintf(const wchar_t *format, ...)
{
int result = 0;
va_list ap;
va_start(ap, format);
result = STDIO_NAMESPACE vfwprintf(file_, format, ap);
va_end(ap);
return result;
}
/** print formatted wide string into stream, see printf(3)
* @param format format string
* @param arg list of further parameters according to format string
* @return number of characters printed
*/
int vfwprintf(const wchar_t *format, va_list arg)
{
return STDIO_NAMESPACE vfwprintf(file_, format, arg);
}
// we cannot emulate fwscanf because we would need vfwscanf for this
// purpose, which does not exist, e.g. on Win32.
#endif /* WIDE_CHAR_FILE_IO_FUNCTIONS */
private:
// private undefined copy constructor
OFFile(const OFFile &arg);
// private undefined assignment operator
OFFile &operator=(const OFFile &arg);
/// the file maintained by this object
FILE *file_;
/// a flag indicating whether or not this object was created with popen().
OFBool popened_;
/// the last error code for operations of this stream
offile_errno_t lasterror_;
/// store last error code. For now we simply store the content of errno.
inline void storeLastError()
{
lasterror_ = errno;
}
};
#endif
| [
"a5566qq2581@gmail.com"
] | a5566qq2581@gmail.com |
6a94640d9687f8bf207624df50ae79912f919127 | 2e4d3e7e4c6952229d22ca5f492348bb3ecb8b5d | /DEM/Low/src/Util/PerlinNoise.cpp | df4e7e0f6696eef6748296c341ed065a5b96ceff | [
"MIT"
] | permissive | niello/deusexmachina | 7b3debcb927b63ad3609317796949f306dcf35c3 | a0a78df3181cab1b27c55f51e379a52f80796099 | refs/heads/master | 2023-08-31T03:49:12.424320 | 2023-03-20T10:23:52 | 2023-03-20T10:23:52 | 42,160,038 | 22 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 4,773 | cpp | #include <Util/UtilFwd.h>
#include <Math/Math.h>
// Perlin CPerlinNoise class.
// See http://mrl.nyu.edu/~perlin/CPerlinNoise/ for details.
// (C) 2004 RadonLabs GmbH
// Permutation table
static const int PNPerm[512] =
{
151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225,
140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148,
247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32,
57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175,
74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122,
60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54,
65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169,
200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64,
52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212,
207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213,
119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9,
129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104,
218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241,
81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157,
184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93,
222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180,
// repeats from here on?
151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225,
140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148,
247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32,
57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175,
74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122,
60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54,
65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169,
200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64,
52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212,
207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213,
119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9,
129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104,
218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241,
81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157,
184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93,
222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180,
};
static inline float PNFade(float t)
{
return t * t * t * (t * (t * 6.f - 15.f) + 10.f);
}
//---------------------------------------------------------------------
static inline float PNGrad(int hash, float x, float y, float z)
{
int h = hash & 15;
float u = h < 8 ? x : y;
float v = h < 4 ? y : ((h == 12) || (h==14)) ? x : z;
return ((h & 1) == 0 ? u : -u) + ((h & 2) == 0 ? v : -v);
}
//---------------------------------------------------------------------
float GeneratePerlinNoise(float x, float y, float z)
{
float floorX = floorf(x);
float floorY = floorf(y);
float floorZ = floorf(z);
// find unit cube that contains point
int X = int(floorX) & 255;
int Y = int(floorY) & 255;
int Z = int(floorZ) & 255;
// find relative x,y,z of point in cube
x -= floorX;
y -= floorY;
z -= floorZ;
// compute PNFade curves for x, y, z
float u = PNFade(x);
float v = PNFade(y);
float w = PNFade(z);
// hash coords of 8 cube corners
int A = PNPerm[X] + Y;
int AA = PNPerm[A] + Z;
int AB = PNPerm[A+1] + Z;
int B = PNPerm[X+1] + Y;
int BA = PNPerm[B] + Z;
int BB = PNPerm[B+1] + Z;
// add blended results from 8 corners of cube
return n_lerp(w, n_lerp(v, n_lerp(u, PNGrad(PNPerm[AA ], x , y , z ),
PNGrad(PNPerm[BA ], x-1, y , z )),
n_lerp(u, PNGrad(PNPerm[AB ], x , y-1, z ),
PNGrad(PNPerm[BB ], x-1, y-1, z ))),
n_lerp(v, n_lerp(u, PNGrad(PNPerm[AA+1], x , y , z-1),
PNGrad(PNPerm[BA+1], x-1, y , z-1)),
n_lerp(u, PNGrad(PNPerm[AB+1], x , y-1, z-1),
PNGrad(PNPerm[BB+1], x-1, y-1, z-1))));
}
//---------------------------------------------------------------------
| [
"vladimir.orlov@playrix.com"
] | vladimir.orlov@playrix.com |
4fe600e74dc6cf683ce98da1c0e32b16b313466a | 78d3b0621ad1b5122f550e914aa61fec20683610 | /csapex_core_plugins/src/display/output_display_adapter.h | 2f2b6ddd64663e4c6ffc286606230aeee2d7ac85 | [] | no_license | wpfhtl/csapex_core_plugins | 6049cb5e8f52123ac02df79e160e021e35c7ec1c | 7fcb9e01197c32f09743051af238a32bab652949 | refs/heads/master | 2021-05-04T07:35:30.757633 | 2016-10-08T23:12:36 | 2016-10-08T23:16:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,193 | h | #ifndef OUTPUD_DISPLAY_ADAPTER_H
#define OUTPUD_DISPLAY_ADAPTER_H
/// PROJECT
#include <csapex/view/node/default_node_adapter.h>
/// COMPONENT
#include "output_display.h"
/// SYSTEM
#include <QGraphicsView>
#include <QLabel>
#include <yaml-cpp/yaml.h>
namespace csapex {
class ImageWidget;
class OutputDisplayAdapter : public QObject, public DefaultNodeAdapter
{
Q_OBJECT
public:
OutputDisplayAdapter(NodeHandleWeakPtr worker, NodeBox* parent, std::weak_ptr<OutputDisplay> node);
~OutputDisplayAdapter();
virtual MementoPtr getState() const override;
virtual void setParameterState(Memento::Ptr memento) override;
virtual void setupUi(QBoxLayout* layout) override;
virtual void setManualResize(bool manual) override;
virtual bool isResizable() const override;
public Q_SLOTS:
void display(const QImage& img);
void fitInView();
Q_SIGNALS:
void displayRequest(QImage img);
protected:
bool eventFilter(QObject* o, QEvent* e);
void resize();
std::weak_ptr<OutputDisplay> wrapped_;
struct State : public Memento {
int width;
int height;
State()
: width(100), height(100)
{}
virtual void writeYaml(YAML::Node& out) const {
out["width"] = width;
out["height"] = height;
}
virtual void readYaml(const YAML::Node& node) {
width = node["width"].as<int>();
height = node["height"].as<int>();
}
};
private:
QSize last_size_;
State state;
ImageWidget* label_view_;
};
class ImageWidget : public QWidget
{
Q_OBJECT
public:
explicit ImageWidget(QWidget *parent = 0);
const QPixmap* pixmap() const;
void setManualResize(bool manual);
void setSize(const QSize& size);
void setSize(int w, int h);
virtual QSize sizeHint() const override;
virtual QSize minimumSizeHint() const override;
public Q_SLOTS:
void setPixmap(const QPixmap&);
protected:
void paintEvent(QPaintEvent *) override;
void resizeEvent(QResizeEvent*) override;
private:
QPixmap pix;
QSize size;
bool manual_resize_;
};
}
#endif // OUTPUD_DISPLAY_ADAPTER_H
| [
"sebastian.buck@uni-tuebingen.de"
] | sebastian.buck@uni-tuebingen.de |
edf7bafa0691369f0b8dce4e132a3ac511584221 | 740ca5e602d1050942ae8c908cfced17aee76cc9 | /rumus E=mc.cpp | 239af35e9146a3c9a819f371ce84c14b65535fff | [] | no_license | dickychandra21/tugas-ke12 | 71be6f86d814150031ad87bbda327241e7f98868 | 9a2688df98b90f03bef202c292ee8ee464a73bc7 | refs/heads/master | 2020-04-12T14:31:33.048704 | 2018-12-20T09:15:00 | 2018-12-20T09:15:00 | 162,554,987 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 334 | cpp | #include <stdio.h>
#include <conio.h>
int main()
{
float c=89.88,m,E;
printf("PROGRAM PERHITUNGAN MENGGUNAKAN RUMUS E=mc2 \n");
printf("INSTITUT PELITA BANGSA. TEKNIK INFORMATIKA\n\n");
printf("Masukkan massa (Kg) : ");scanf("%f", &m);
E=m*c*c;
printf("E = %.2f * %.2f * %.2f = %.2f J",m,c,c,E);
getch();
}
| [
"noreply@github.com"
] | noreply@github.com |
98315ee6ea9aa3da66e0236a11a04b95bf48a13a | d8446827771cd79eb13242d21b0ca103035c467d | /day08/ex00/main.cpp | bdb813be740031b18319ca7ac2a6c400d09bd112 | [] | no_license | vuslysty/piscineCPP | e3ef3aabbef053eca29e1fad0695eeda85bc00c2 | 91a583ed4a0352c904fa485202752f8105230520 | refs/heads/master | 2020-06-20T19:16:15.561261 | 2019-07-16T15:51:59 | 2019-07-16T15:51:59 | 197,219,556 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,482 | cpp | //
// Created by Vladyslav USLYSTYI on 2019-07-05.
//
#include <vector>
#include <iostream>
#include <array>
#include <list>
#include "easyfind.hpp"
int main()
{
std::vector<int > vec;
std::array<int, 42> arr;
std::list<int> list;
for (int i = -10; i < 10; i++)
vec.push_back(i);
for (unsigned int i = 0; i < 10; i++)
arr.at(i) = static_cast<int>(i);
for (unsigned int i = 0; i < 100; i++)
list.push_front(static_cast<int>(i));
std::vector<int >::iterator findVec;
std::array<int, 42>::iterator findArr;
std::list<int>::iterator findList;
std::cout << "Vector:" << std::endl;
try
{
findVec = easyfind(vec, -10);
std::cout << "You element " << *findVec << " was found" << std::endl;
}
catch (std::exception &e)
{
std::cout << e.what() << std::endl;
}
std::cout << "Array:" << std::endl;
try
{
findArr = easyfind(arr, 0);
std::cout << "You element " << *findArr << " was found" << std::endl;
}
catch (std::exception &e)
{
std::cout << e.what() << std::endl;
}
std::cout << "List:" << std::endl;
try
{
findList = easyfind(list, 36);
std::cout << "You element " << *findList << " was found" << std::endl;
}
catch (std::exception &e)
{
std::cout << e.what() << std::endl;
}
std::cout << "List:" << std::endl;
try
{
findList = easyfind(list, 123);
std::cout << "You element " << *findList << " was found" << std::endl;
}
catch (std::exception &e)
{
std::cout << e.what() << std::endl;
}
return (0);
} | [
"vuslysty@e2r11p11.unit.ua"
] | vuslysty@e2r11p11.unit.ua |
6bceb795633f2d34ec40dbe6815419535149d912 | 58f46a28fc1b58f9cd4904c591b415c29ab2842f | /chromium-courgette-redacted-29.0.1547.57/chrome/browser/extensions/api/sync_file_system/sync_file_system_api_helpers.h | 16bb54750b423aaede2a3b2f603255f9b56f009f | [
"BSD-3-Clause"
] | permissive | bbmjja8123/chromium-1 | e739ef69d176c636d461e44d54ec66d11ed48f96 | 2a46d8855c48acd51dafc475be7a56420a716477 | refs/heads/master | 2021-01-16T17:50:45.184775 | 2015-03-20T18:38:11 | 2015-03-20T18:42:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,399 | h | // Copyright (c) 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.
#ifndef CHROME_BROWSER_EXTENSIONS_API_SYNC_FILE_SYSTEM_SYNC_FILE_SYSTEM_API_HELPERS_H_
#define CHROME_BROWSER_EXTENSIONS_API_SYNC_FILE_SYSTEM_SYNC_FILE_SYSTEM_API_HELPERS_H_
#include "chrome/browser/sync_file_system/conflict_resolution_policy.h"
#include "chrome/browser/sync_file_system/sync_service_state.h"
#include "chrome/common/extensions/api/sync_file_system.h"
#include "webkit/browser/fileapi/syncable/sync_action.h"
#include "webkit/browser/fileapi/syncable/sync_direction.h"
#include "webkit/browser/fileapi/syncable/sync_file_status.h"
#include "webkit/browser/fileapi/syncable/sync_file_type.h"
namespace fileapi {
class FileSystemURL;
}
namespace base {
class DictionaryValue;
}
namespace extensions {
// extensions::api::sync_file_system <-> sync_file_system enum conversion
// functions.
api::sync_file_system::ServiceStatus SyncServiceStateToExtensionEnum(
sync_file_system::SyncServiceState state);
api::sync_file_system::FileStatus SyncFileStatusToExtensionEnum(
sync_file_system::SyncFileStatus status);
api::sync_file_system::SyncAction SyncActionToExtensionEnum(
sync_file_system::SyncAction action);
api::sync_file_system::SyncDirection SyncDirectionToExtensionEnum(
sync_file_system::SyncDirection direction);
api::sync_file_system::ConflictResolutionPolicy
ConflictResolutionPolicyToExtensionEnum(
sync_file_system::ConflictResolutionPolicy policy);
sync_file_system::ConflictResolutionPolicy
ExtensionEnumToConflictResolutionPolicy(
api::sync_file_system::ConflictResolutionPolicy);
// Creates a dictionary for FileSystem Entry from given |url|.
// This will create a dictionary which has 'fileSystemType', 'fileSystemName',
// 'rootUrl', 'filePath' and 'isDirectory' fields.
// The returned dictionary is supposed to be interpreted
// in the renderer's customer binding to create a FileEntry object.
// This returns NULL if the given |url| is not valid or |file_type| is
// SYNC_FILE_TYPE_UNKNOWN.
base::DictionaryValue* CreateDictionaryValueForFileSystemEntry(
const fileapi::FileSystemURL& url,
sync_file_system::SyncFileType file_type);
} // namespace extensions
#endif // CHROME_BROWSER_EXTENSIONS_API_SYNC_FILE_SYSTEM_SYNC_FILE_SYSTEM_API_HELPERS_H_
| [
"Khilan.Gudka@cl.cam.ac.uk"
] | Khilan.Gudka@cl.cam.ac.uk |
31486d4540a6d372f1d5b3c86966a6d2e0ce80c9 | 708b8b9f4b6435adf8a12d6048223d6ecd2ffb9c | /assignment 3/Postfix.h | b9df01ba7d77ea4fe68e0ae1f0b00595f183732d | [] | no_license | baderhosny/CSC363_Calculator | a00ebbb319daa3e8b059c69069279a99a7a87ce1 | 8426a94fc193101bed66fddd9a599d2a379f3e44 | refs/heads/main | 2023-04-26T06:30:49.680976 | 2021-05-21T20:50:14 | 2021-05-21T20:50:14 | 369,648,803 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 526 | h | #ifndef _POSTFIX_H_
#define _POSTFIX_H_
#include <iostream>
#include <sstream>
#include "Concrete_Factory.h"
#include "Expr_Command.h"
#include "Stack.h"
class Postfix
{
public:
Postfix(void);
~Postfix();
int importance(std::string infix)
void evaluate_postfix(Array<Expr_Command *> postfix);
std::string in_post_conversion(const std::string input & infix, Concrete_Factory & factory, Array <Expr_Command *> postfix);
} | [
"noreply@github.com"
] | noreply@github.com |
76e39cf4bed12b9f5f6ef884010f4d156ee26d5a | 23e393f8c385a4e0f8f3d4b9e2d80f98657f4e1f | /Win32 Programming/Win32API/ControlExplorer/Loggable.cpp | 1b57e3af4ea28ce7c98bd658fab7186ef71e4ba3 | [] | no_license | IgorYunusov/Mega-collection-cpp-1 | c7c09e3c76395bcbf95a304db6462a315db921ba | 42d07f16a379a8093b6ddc15675bf777eb10d480 | refs/heads/master | 2020-03-24T10:20:15.783034 | 2018-06-12T13:19:05 | 2018-06-12T13:19:05 | 142,653,486 | 3 | 1 | null | 2018-07-28T06:36:35 | 2018-07-28T06:36:35 | null | WINDOWS-1252 | C++ | false | false | 40,096 | cpp | // loggable.cpp : implementation file
//
#include "stdafx.h"
#include "ControlExplorer.h"
#include "ixable.h"
#include "msglog.h"
#include "loggable.h"
#include "xform.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#ifdef UNICODE
#define HEXCHAR _T("%04x")
#else
#define HEXCHAR _T("%02x")
#endif
/////////////////////////////////////////////////////////////////////////////
// CLoggingPage property page
IMPLEMENT_DYNCREATE(CLoggingPage, CIndexablePage)
CLoggingPage::CLoggingPage(int idd) : CIndexablePage(idd)
{
}
CLoggingPage::CLoggingPage() : CIndexablePage((int)0) // should never call default constructor!
{
//{{AFX_DATA_INIT(CLoggingPage)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
}
CLoggingPage::~CLoggingPage()
{
}
void CLoggingPage::DoDataExchange(CDataExchange* pDX)
{
CIndexablePage::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CLoggingPage)
// NOTE: the ClassWizard will add DDX and DDV calls here
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CLoggingPage, CIndexablePage)
//{{AFX_MSG_MAP(CLoggingPage)
// NOTE: the ClassWizard will add message map macros here
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/*****************************************************************************
The naming convention:
ShowResult_w_l_r where 'w' is the wParam value flag, l is the lParam
value flag, and 'r' is the result value flag. The
flags are defined as below:
b - Boolean
B - "Buffer", the string "&b" to indicate a buffer argument
c - character
CBERR - used only in the result position, will print a value
as either its integer value or as "-1 (CB_ERR)"
d - value as decimal number
DW - value as a DWORD in hex with LOWORD and HIWORD display decimal
LBERR - used only in the result position, will print a value
as either its integer value or as "-1 (LB_ERR)"
N - no value present
R - "Rectangle", the string "&r" to indicate a RECT argument
s - string
x - value as hex number
Given the values possible, we have |w| * |l| * |r| possible functions
where |x| indicates the count of the number of flags valid for the
position. At the moment, |w|==|l| and |w|+1==|r|. Note that we do
not currently support every possible permutation of values.
The question may arise: why didn't I use overloading in C++? The
answer is that overload resolution is too weak to distinguish wanting
to print values of the same type in different formats (since it doesn't
have, for example, the "branded types" of more sophisticated class
models such as Modula-3). This was the best compromise; the alternative
was to use overloading for some cases and different function names
for other cases, which introduced a level of complexity I did not feel
like dealing with.
*****************************************************************************/
/////////////////////////////////////////////////////////////////////////////
// CLoggingPage message handlers
/****************************************************************************
* CLoggginPage::errstr
* Inputs:
* int result: result value
* Result: CString
* "-1 (LB_ERR)"
****************************************************************************/
CString CLoggingPage::errstr(int result, int errid)
{
CString s;
CString err;
err.LoadString(errid);
if(result == LB_ERR || result == CB_ERR)
s.Format(_T("%d (%s)"), result, err);
else
s.Format(_T("%d"), result);
return s;
}
/****************************************************************************
* CLoggingPage::showResult_b_DW_N
* Inputs:
* int msg: Message id
* BOOL b: wParam flag
* DWORD lParam: Doubleword value
* Result: void
*
* Effect:
* ²
****************************************************************************/
void CLoggingPage::showResult_b_DW_N(int msg, BOOL b, DWORD lParam)
{
CString t;
t.LoadString(msg);
CString bstr;
if(b)
bstr.LoadString(IDS_TRUE);
else
bstr.LoadString(IDS_FALSE);
CString s;
s.Format(_T("%s(%s, %08x=(%d, %d))"), t, bstr, lParam,
LOWORD(lParam), HIWORD(lParam));
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_b_d_N
* Inputs:
* int msg: Message id
* BOOL b: wParam flag
* int lParam:
* Result: void
*
* Effect:
* ²
****************************************************************************/
void CLoggingPage::showResult_b_d_N(int msg, BOOL b, int lParam)
{
CString t;
t.LoadString(msg);
CString bstr;
if(b)
bstr.LoadString(IDS_TRUE);
else
bstr.LoadString(IDS_FALSE);
CString s;
s.Format(_T("%s(%s, %d)"), t, bstr, lParam);
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_b_N_N
* Inputs:
* int msg: Message id
* BOOL b: wParam flag
* Result: void
*
* Effect:
* ²
****************************************************************************/
void CLoggingPage::showResult_b_N_N(int msg, BOOL b)
{
CString t;
t.LoadString(msg);
CString bstr;
if(b)
bstr.LoadString(IDS_TRUE);
else
bstr.LoadString(IDS_FALSE);
CString s;
s.Format(_T("%s(%s)"), t, bstr);
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_N_N_DW
* Inputs:
* int msg: Message id
* DWORD result: DWORD that is to be shown as two integers
* Result: void
*
* Effect:
* Displays a DWORD-returning message of no arguments, where the
* value is a DWORD with a HIWORD and LOWORD component
****************************************************************************/
void CLoggingPage::showResult_N_N_DW(int msg, DWORD result)
{
CString t;
t.LoadString(msg);
CString s;
s.Format(_T("%s =>0x%08x (%d, %d)"), t, result, LOWORD(result), HIWORD(result));
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_N_DW_ERR
* Inputs:
* int msg: Message id
* DWORD lparam: DWORD that is to be shown as two integers
* int result: Result code
* int err: Error code
* Result: void
*
* Effect:
* Displays the message
****************************************************************************/
void CLoggingPage::showResult_N_DW_ERR(int msg, DWORD lParam, int result, int err)
{
CString t;
t.LoadString(msg);
CString s;
s.Format(_T("%s(0, 0x%08x (%d, %d))"), t, lParam,
LOWORD(lParam), HIWORD(lParam),
errstr(result, err));
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_N_N_d
* Inputs:
* int msg: Message ID
* int result: Result id
* Result: void
*
* Effect:
* Displays a message of no parameters that returns an int
****************************************************************************/
void CLoggingPage::showResult_N_N_d(int msg, int result)
{
CString t;
t.LoadString(msg);
CString s;
s.Format(_T("%s => %d"), t, result);
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_N_R_N
* Inputs:
* int msg: Message ID
* LPRECT r: Rectangle pointer
* Result: void
*
* Effect:
* Displays a message of no parameters that returns void; shows the
* rectangle as well
****************************************************************************/
void CLoggingPage::showResult_N_R_N(int msg, LPRECT r)
{
CString t;
t.LoadString(msg);
CString s;
s.Format(_T("%s(&r); r=>[%d, %d, %d, %d]"), t, r->left, r->top,
r->right, r->bottom);
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_b_R_b
* Inputs:
* int msg: Message ID
* BOOL w: wParam avlue
* LPRECT r: Rectangle pointer
* BOOL result: Result
* Result: void
*
* Effect:
* Displays a message of no parameters that returns void; shows the
* rectangle as well
****************************************************************************/
void CLoggingPage::showResult_b_R_b(int msg, BOOL w, LPRECT r, BOOL result)
{
CString t;
t.LoadString(msg);
CString ws;
ws.LoadString(w ? IDS_TRUE : IDS_FALSE);
CString rs;
rs.LoadString(result ? IDS_TRUE : IDS_FALSE);
CString s;
s.Format(_T("%s(%s, &r) => %s; r=>[%d, %d, %d, %d]"),
t, ws, rs,
r->left, r->top,
r->right, r->bottom);
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_N_N_s
* Inputs:
* int msg: Message ID
* CString result: Result value as string
* Result: void
*
* Effect:
* Displays a message of no parameters that returns a value which is
* reformatted by the caller into a string
****************************************************************************/
void CLoggingPage::showResult_N_N_s(int msg, CString result)
{
CString t;
t.LoadString(msg);
CString s;
s.Format(_T("%s => %s"), t, result);
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_d_B_s
* Inputs:
* int msg: Message ID
* CString result: Result value as string
* Result: void
*
* Effect:
* Displays a message of wParam and a buffer pointer that returns a value
* which is reformatted by the caller into a string
****************************************************************************/
void CLoggingPage::showResult_d_B_s(int msg, int w, CString result)
{
CString t;
t.LoadString(msg);
CString s;
s.Format(_T("%s(%d, &b) => %s"), t, w, result);
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_d_B_d
* Inputs:
* int msg: Message ID
* int w: WPARAM value
* int result: Result value
* Result: void
*
* Effect:
* Displays a message of wParam and a buffer pointer that returns a value
* which is reformatted by the caller into a string
****************************************************************************/
void CLoggingPage::showResult_d_B_d(int msg, int w, int result)
{
CString t;
t.LoadString(msg);
CString s;
s.Format(_T("%s(%d, &b) => %d"), t, w, result);
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_d_B_ERR
* Inputs:
* int msg: Message ID
* int w: wParam value
* int result: Result value as string
* int err: IDS_LB_ERR or IDS_CB_ERR
* Result: void
*
* Effect:
* Displays a message of wParam and a buffer pointer that returns a value
* which can be LB_ERR
****************************************************************************/
void CLoggingPage::showResult_d_B_ERR(int msg, int w, int result, int err)
{
showResult_d_B_s(msg, w, errstr(result, err));
}
/****************************************************************************
* CLoggingPage::showResult_d_d_b
* Inputs:
* int msg: ID of message
* int w: value of wParam
* int l: Value of lParam
* BOOL result: Result
* Result: void
*
* Effect:
* Displays a message of two params that returns a Boolean result
****************************************************************************/
void CLoggingPage::showResult_d_d_b(int msg, int w, int l, BOOL result)
{
CString t;
t.LoadString(msg);
CString val;
val.LoadString(result ? IDS_TRUE : IDS_FALSE);
CString s;
s.Format(_T("%s(%d, %d) => %s"), t, w, l, val);
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_d_d_d
* Inputs:
* int msg: ID of message
* int w: value of wParam
* int l: Value of lParam
* int result: Result
* Result: void
*
* Effect:
* Displays a message of two params that returns an integer result
****************************************************************************/
void CLoggingPage::showResult_d_d_d(int msg, int w, int l, int result)
{
CString t;
t.LoadString(msg);
CString s;
s.Format(_T("%s(%d, %d) => %d"), t, w, l, result);
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_d_d_pt
* Inputs:
* int msg: ID of message
* int w: value of wParam
* int l: Value of lParam
* DWORD result: Result
* Result: void
*
* Effect:
* Displays a message of two params that returns a POINTS result
****************************************************************************/
void CLoggingPage::showResult_d_d_pt(int msg, int w, int l, DWORD result)
{
CString t;
t.LoadString(msg);
CString s;
s.Format(_T("%s(%d, %d) => (x: %d, y: %d)"), t, w, l,
(int)(short)LOWORD(result),
(int)(short)HIWORD(result));
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_d_d_N
* Inputs:
* int msg: ID of message
* int w: value of wParam
* int l: Value of lParam
* Result: void
*
* Effect:
* Displays a message of two params that returns an integer result
****************************************************************************/
void CLoggingPage::showResult_d_d_N(int msg, int w, int l)
{
CString t;
t.LoadString(msg);
CString s;
s.Format(_T("%s(%d, %d)"), t, w, l);
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_d_d_s
* Inputs:
* int msg: ID of message
* int w: value of wParam
* int l: Value of lParam
* CString result: Result
* Result: void
*
* Effect:
* Displays a message of two params that returns an result that has
* been reformatted.
****************************************************************************/
void CLoggingPage::showResult_d_d_s(int msg, int w, int l, CString result)
{
CString t;
t.LoadString(msg);
CString s;
s.Format(_T("%s(%d, %d) => %s"), t, w, l, result);
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_d_s_s
* Inputs:
* int msg: ID of message
* int w: value of wParam
* CString l: Value of lParam
* CString result: Result
* Result: void
*
* Effect:
* Displays a message of two params that returns an result that has
* been reformatted.
****************************************************************************/
void CLoggingPage::showResult_d_s_s(int msg, int w, CString l, CString result)
{
CString t;
t.LoadString(msg);
CString s;
s.Format(_T("%s(%d, %s) => %s"), t, w, l, result);
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_d_s_b
* Inputs:
* int msg: ID of message
* int w: value of wParam
* CString l: Value of lParam
* BOOL result: Result
* Result: void
*
* Effect:
* Displays a message of two params that returns a Boolean result
****************************************************************************/
void CLoggingPage::showResult_d_s_b(int msg, int w, CString l, BOOL result)
{
CString t;
t.LoadString(msg);
CString rstr;
rstr.LoadString(result ? IDS_TRUE : IDS_FALSE);
CString s;
s.Format(_T("%s(%d, %s) => %s"), t, w, l, rstr);
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_N_i_b
* Inputs:
* int id: Message id
* BOOL result: result code
* Result: void
*
* Effect:
* Displays the result
****************************************************************************/
void CLoggingPage::showResult_N_i_b(int id, BOOL result)
{
showResult_d_s_b(id, 0, _T("&item"), result);
}
/****************************************************************************
* CLoggingPage::showResult_N_i_d
* Inputs:
* int id: ID
* int result: Result code
* Result: void
*
* Effect:
* ²
****************************************************************************/
void CLoggingPage::showResult_N_i_d(int id, int result)
{
showResult_d_s_d(id, 0, _T("&item"), result);
}
/****************************************************************************
* CLoggingPage::showResult_s_N_s
* Inputs:
* int msg: ID of message
* CString w: value of wParam
* CString result: Result
* Result: void
*
* Effect:
* Displays a message of two params that returns an result that has
* been reformatted.
****************************************************************************/
void CLoggingPage::showResult_s_N_s(int msg, CString w, CString result)
{
CString t;
t.LoadString(msg);
CString s;
s.Format(_T("%s(%s, 0) => %s"), t, w, result);
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_b_N_b
* Inputs:
* int msg: Message id
* BOOL w: wParam value
* BOOL result: Result value
* Result: void
*
* Effect:
* Displays the message
****************************************************************************/
void CLoggingPage::showResult_b_N_b(int msg, BOOL w, BOOL result)
{
CString ws;
CString res;
ws.LoadString(w ? IDS_TRUE : IDS_FALSE);
res.LoadString(result ? IDS_TRUE : IDS_FALSE);
showResult_s_N_s(msg, ws, res);
}
/****************************************************************************
* CLoggingPage::showResult_d_N_s
* Inputs:
* int msg: ID of message
* int w: value of wParam
* CString result: Result
* Result: void
*
* Effect:
* Displays a message of two params that returns an result that has
* been reformatted.
****************************************************************************/
void CLoggingPage::showResult_d_N_s(int msg, int w, CString result)
{
showResult_d_d_s(msg, w, 0, result);
}
/****************************************************************************
* CLoggingPage::showResult_d_N_N
* Inputs:
* int msg: ID of message
* int w: wParam value
* Result: void
*
* Effect:
* Displays the fact that a void-returning message of wParam was sent
****************************************************************************/
void CLoggingPage::showResult_d_N_N(int msg, int w)
{
CString t;
t.LoadString(msg);
CString s;
s.Format(_T("%s(%d, 0)"), t, w);
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_c_N_N
* Inputs:
* int msg: ID of message
* TCHAR w: wParam value
* Result: void
*
* Effect:
* Displays the fact that a void-returning message of wParam was sent
****************************************************************************/
void CLoggingPage::showResult_c_N_N(int msg, TCHAR w)
{
CString t;
t.LoadString(msg);
CString s;
s.Format(_T("%s('%s', 0)"), t, charToStr(w));
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_d_N_d
* Inputs:
* int msg: ID of message
* int w: wParam value
* Result: void
*
* Effect:
* Displays the fact that an int-returning message of wParam was sent
****************************************************************************/
void CLoggingPage::showResult_d_N_d(int msg, int w, int result)
{
CString t;
t.LoadString(msg);
CString s;
s.Format(_T("%s(%d, 0) => %d"), t, w, result);
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_N_N_N
* Inputs:
* int msg: ID of message
* Result: void
*
* Effect:
* Displays the fact that a void-returning message of no params was sent
****************************************************************************/
void CLoggingPage::showResult_N_N_N(int msg)
{
CString s;
s.LoadString(msg);
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_N_N_c
* Inputs:
* int msg: ID to use for message
* TCHAR ch: Character code
* Result: void
*
* Effect:
* msg => '%c' (0x%02x)
****************************************************************************/
void CLoggingPage::showResult_N_N_c(int msg, TCHAR ch)
{
CString t;
t.LoadString(msg);
CString chstr = charToStr(ch);
CString s;
s.Format(_T("%s => '%s' (" HEXCHAR ")"), t, chstr, ch);
addMessage(s);
}
/****************************************************************************
* CLoggingPage::addMessage
* Inputs:
* CString s: String to format
* Result: void
*
* Effect:
* ASSERT(FALSE). This is supposed to be implemented by each of the
* subclasses and should never be called directly.
****************************************************************************/
void CLoggingPage::addMessage(CString s)
{
ASSERT(FALSE); // this must be implemented in derived classes
}
/****************************************************************************
* CLoggingPage::showResult_N_N_ERR
* Inputs:
* int msg: ID of message
* int result: Result code of message
* int err: ID of either LB_ERR or CB_ERR string
* Result: void
*
* Effect:
* Shows the result either as a number or, if -1, as the string "-1
* (LBERR)"
****************************************************************************/
void CLoggingPage::showResult_N_N_ERR(int msg, int result, int err)
{
showResult_N_N_s(msg, errstr(result, err));
}
/****************************************************************************
* CLoggingPage::showResult_d_d_ERR
* Inputs:
* int msg: ID of message
* int result: Result code of message
* int err: IDS_LB_ERR or IDS_CB_ERR
* Result: void
*
* Effect:
* Shows the wParam and lParam, and displays the result either as a
* number or, if -1, as the string "-1 ([LC]BERR)"
****************************************************************************/
void CLoggingPage::showResult_d_d_ERR(int msg, int w, int l, int result, int err)
{
showResult_d_d_s(msg, w, l, errstr(result, err));
}
/****************************************************************************
* CLoggingPage::showResult_d_N_ERR
* Inputs:
* int msg: ID of message
* int result: Result code of message
* int err: IDS_LB_ERR or IDS_CB_ERR
* Result: void
*
* Effect:
* Shows the wParam and lParam, and displays the result either as a
* number or, if -1, as the string "-1 ([LC]BERR)"
****************************************************************************/
void CLoggingPage::showResult_d_N_ERR(int msg, int w, int result, int err)
{
showResult_d_N_s(msg, w, errstr(result, err));
}
/****************************************************************************
* CLoggingPage::showResult_N_s_ERR
* Inputs:
* int msg:
* CString s: LPARAM string value
* int result: Result, possibly LB_ERR
* int err: IDS_LB_ERR or IDS_CB_ERR
* Result: void
*
* Effect:
* ²
****************************************************************************/
void CLoggingPage::showResult_N_s_ERR(int msg, CString s, int result, int err)
{
showResult_N_s_s(msg, s, errstr(result, err));
}
/****************************************************************************
* CLoggingPage::showResult_N_s_d
* Inputs:
* int msg: ID of message
* CString l: Value of lParam
* int result: Result
* Result: void
*
* Effect:
* Displays a message of a string lParam that returns an integer result
****************************************************************************/
void CLoggingPage::showResult_N_s_d(int msg, CString l, int result)
{
showResult_d_s_d(msg, 0, l, result);
}
/****************************************************************************
* CLoggingPage::showResult_N_s_b
* Inputs:
* int msg: ID of message
* CString l: Value of lParam
* BOOL result: Result
* Result: void
*
* Effect:
* Displays a message of a string lParam that returns an integer result
****************************************************************************/
void CLoggingPage::showResult_N_s_b(int msg, CString l, BOOL result)
{
CString s;
s.LoadString(result ? IDS_TRUE : IDS_FALSE);
showResult_d_s_s(msg, 0, l, s);
}
/****************************************************************************
* CLoggingPage::showResult_N_s_s
* Inputs:
* int msg: ID of message
* CString l: Value of lParam
* CString result: Result
* Result: void
*
* Effect:
* Displays a message of a string lParam that returns an integer result
****************************************************************************/
void CLoggingPage::showResult_N_s_s(int msg, CString l, CString result)
{
showResult_d_s_s(msg, 0, l, result);
}
/****************************************************************************
* CLoggingPage::showResult_d_s_d
* Inputs:
* int msg: ID of message
* int w: value of wParam
* CString l: Value of lParam
* int result: Result
* Result: void
*
* Effect:
* Displays a message of two params that returns an integer result
****************************************************************************/
void CLoggingPage::showResult_d_s_d(int msg, int w, CString l, int result)
{
CString t;
t.LoadString(msg);
CString s;
s.Format(_T("%s(%d, %s) => %d"), t, w, l, result);
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_N_s_x
* Inputs:
* int msg: ID of message
* CString l: Value of lParam
* DWORD result: Result
* Result: void
*
* Effect:
* Displays a message of lParam that returns an integer result to be
* shown in hex (e.g., an HWND)
****************************************************************************/
void CLoggingPage::showResult_N_s_x(int msg, CString l, DWORD result)
{
CString t;
t.LoadString(msg);
CString s;
s.Format(_T("%s(0, %s) => %08x"), t, l, result);
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_d_s_ERR
* Inputs:
* int msg: ID of message
* int w: value of wParam
* CString l: Value of lParam
* int result: Result
* int err: IDS_LB_ERR or IDS_CB_ERR
* Result: void
*
* Effect:
* Displays a message of two params that returns an integer result
****************************************************************************/
void CLoggingPage::showResult_d_s_ERR(int msg, int w, CString l, int result, int err)
{
showResult_d_s_s(msg, w, l, errstr(result, err));
}
/****************************************************************************
* CLoggingPage::showResult_s_s_s
* Inputs:
* int msg:
* CString w:
* CString l:
* CString result:
* Result: void
*
* Effect:
* ²
****************************************************************************/
void CLoggingPage::showResult_s_s_s(int msg, CString w, CString l, CString result)
{
CString t;
t.LoadString(msg);
CString s;
s.Format(_T("%s(%s, %s) => %s"), t, w, l, result);
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_s_s_b
* Inputs:
* int msg:
* CString w:
* CString l:
* BOOL result:
* Result: void
*
* Effect:
* ²
****************************************************************************/
void CLoggingPage::showResult_s_s_b(int msg, CString w, CString l, BOOL result)
{
CString s;
s.LoadString(result ? IDS_TRUE : IDS_FALSE);
showResult_s_s_s(msg, w, l, s);
}
/****************************************************************************
* CLoggingPage::showResult_x_s_ERR
* Inputs:
* int msg: ID of message
* int w: value of wParam
* CString l: Value of lParam
* int result: Result
* int err: IDS_LB_ERR or IDS_CB_ERR
* Result: void
*
* Effect:
* Displays a message of two params that returns an integer result. If
* the result is LB_ERR or CB_ERR the annotation is also displayed.
****************************************************************************/
void CLoggingPage::showResult_x_s_ERR(int msg, int w, CString l, int result, int err)
{
showResult_x_s_s(msg, w, l, errstr(result, err));
}
/****************************************************************************
* CLoggingPage::showResult_x_s_d
* Inputs:
* int msg: ID of message
* int w: value of wParam, displayed in hex
* CString l: Value of lParam
* int result: Result
* Result: void
*
* Effect:
* Displays a message of two params that returns an integer result
****************************************************************************/
void CLoggingPage::showResult_x_s_d(int msg, int w, CString l, int result)
{
CString t;
t.LoadString(msg);
CString s;
s.Format(_T("%s(0x%04x, %s) => %d"), t, w, l, result);
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_x_s_s
* Inputs:
* int msg: ID of message
* int w: value of wParam, displayed in 04x format
* CString l: Value of lParam
* CString result: Result
* Result: void
*
* Effect:
* Displays a message of two params that returns an result that has
* been reformatted.
****************************************************************************/
void CLoggingPage::showResult_x_s_s(int msg, int w, CString l, CString result)
{
CString t;
t.LoadString(msg);
CString s;
s.Format(_T("%s(0x%04x, %s) => %s"), t, w, l, result);
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_d_DW_ERR
* Inputs:
* int msg: message name ID
* int w: wParam value
* DWORD l: lParam value
* int result: Result of the message
* int err: IDS_LB_ERR or IDS_CB_ERR
* Result: void
*
* Effect:
* Displays the lParam as hex and decimal
****************************************************************************/
void CLoggingPage::showResult_d_DW_ERR(int msg, int w, DWORD l, int result, int err)
{
CString t;
t.LoadString(msg);
CString s;
s.Format(_T("%s(%d, 0x%08x=(%d,%d)) => %s"), t, w, l, LOWORD(l),
HIWORD(l),
errstr(result, err));
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_d_DW_N
* Inputs:
* int msg: message name ID
* int w: wParam value
* DWORD l: lParam value
* Result: void
*
* Effect:
* Displays the lParam as hex and decimal
****************************************************************************/
void CLoggingPage::showResult_d_DW_N(int msg, int w, DWORD l)
{
CString t;
t.LoadString(msg);
CString s;
s.Format(_T("%s(%d, 0x%08x=(%d,%d))"), t, w, l, LOWORD(l),
HIWORD(l));
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_d_DW_d
* Inputs:
* int msg: message name ID
* int w: wParam value
* DWORD l: lParam value
* int result: Result of the message
* Result: void
*
* Effect:
* Displays the lParam as hex and decimal
****************************************************************************/
void CLoggingPage::showResult_d_DW_d(int msg, int w, DWORD l, int result)
{
CString t;
t.LoadString(msg);
CString s;
s.Format(_T("%s(%d, 0x%08x=(%d,%d)) => %d"), t, w, l, LOWORD(l),
HIWORD(l),
result);
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_DW_N_DW
* Inputs:
* int msg: Message id
* DWORD locale: new locale version that was set
* DWORD result: old locale version that was returned
* int err: IDS_LB_ERR or IDS_CB_ERR
* Result: void
*
* Effect:
* ²
****************************************************************************/
void CLoggingPage::showResult_DW_N_DW(int msg, DWORD locale, DWORD result, int err)
{
CString t;
t.LoadString(msg);
CString s;
if(result == LB_ERR)
s.Format(_T("%s(0x%08x=(%d,%d)) => %s"), t, locale,
LOWORD(locale),
HIWORD(locale),
errstr(result, err));
else
s.Format(_T("%s(0x%08x=(%d,%d)) => 0x%08x=(%d,%d)"),
t, locale, LOWORD(locale), HIWORD(locale),
result, LOWORD(result), HIWORD(result));
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_d_DW_DW
* Inputs:
* int msg: Message id
* int wParam: wParam value
* int lParam: lParam value
* DWORD result: result of message
* Result: void
*
* Effect:
* ²
****************************************************************************/
void CLoggingPage::showResult_d_DW_DW(int msg, int wParam, DWORD lParam, DWORD result)
{
CString t;
t.LoadString(msg);
CString s;
s.Format(_T("%s(%d, 0x%08x=(%d,%d)) => 0x%08x=(%d,%d)"),
t, wParam, lParam, LOWORD(lParam), HIWORD(lParam),
result, LOWORD(result), HIWORD(result));
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_DW_d_d
* Inputs:
* int DW: WPARAM, DWORD pair of integers
* int d: LPARAM, decimal
* int result: Result, decimal
* Result: void
*
* Effect:
* ²
****************************************************************************/
void CLoggingPage::showResult_DW_d_d(int msg, WPARAM wParam, int lParam, int result)
{
CString t;
t.LoadString(msg);
CString s;
s.Format(_T("%s(0x%08x=(%d,%d)) => %d"), t,
LOWORD(wParam),
HIWORD(wParam),
lParam,
result);
addMessage(s);
}
/****************************************************************************
* CLoggingPage::showResult_d_R_ERR
* Inputs:
* int msg: message name ID
* int w: wParam value
* LPRECT r: lParam value
* int result: the result value of the message
* int err: IDS_LB_ERR or IDS_CB_ERR
* Result: void
*
* Effect:
* Displays the LPARAM as a Rect
****************************************************************************/
void CLoggingPage::showResult_d_R_ERR(int msg, int w, LPRECT r, int result, int err)
{
CString t;
t.LoadString(msg);
CString s;
s.Format(_T("%s(%d, [%d, %d, %d, %d]) => %s"), t, w,
r->left, r->top, r->right, r->bottom,
errstr(result, err));
addMessage(s);
}
| [
"wyrover@gmail.com"
] | wyrover@gmail.com |
43614fb20a09044aae8198a1653a649721aa5e90 | 9a58f6b2de14443b02dfa086355be8478e887f51 | /GOSX Lite/source/Engine/FeatureManager/Features/FlashReducer.cpp | 8a26dedb814bd7f0a587045d8115de7c3e3dc237 | [
"Apache-2.0"
] | permissive | mxwll1/GO-SX-Internal-Lite | 4564869859fc47e1d5eecc03a397f9cbb5f84249 | 63a1f5735c99ef6a24142c659158e1406e1a7328 | refs/heads/master | 2021-01-18T18:14:38.151199 | 2017-03-30T10:51:13 | 2017-03-30T10:51:13 | 86,851,954 | 13 | 7 | null | 2017-03-31T19:08:47 | 2017-03-31T19:08:47 | null | UTF-8 | C++ | false | false | 577 | cpp | //
// FlashReducer.cpp
// GOSX Pro
//
// Created by Andre Kalisch on 22.02.17.
// Copyright © 2017 Andre Kalisch. All rights reserved.
//
#include "FlashReducer.h"
CFlashReducer::CFlashReducer() {}
void CFlashReducer::apply() {
C_CSPlayer* LocalPlayer = C_CSPlayer::GetLocalPlayer();
if(!LocalPlayer || !LocalPlayer->IsValidLivePlayer()) {
return;
}
float maxFlashAlpha = INIGET_FLOAT("Improvements", "maxflashalpha");
if(*LocalPlayer->GetMaxFlashAlpha() > maxFlashAlpha) {
*LocalPlayer->GetMaxFlashAlpha() = maxFlashAlpha;
}
}
| [
"aka@rissc.com"
] | aka@rissc.com |
e0b95abada032d612474a420c335a2f77971f9cf | 9515e3321c33709258e4686a7cd71e98a8c3a03e | /3p/VTK/ThirdParty/vtkm/vtk-m/vtkm/Swap.h | 233266ad2ad2a2692451330aeaabf3f13e1f77a3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | Mason-Wmx/ViewFramework | f9bc534df86f5cf640a9dbf963b9ea17a8e93562 | d8117adc646c369ad29d64477788514c7a75a797 | refs/heads/main | 2023-06-29T04:12:37.042638 | 2021-07-28T09:26:55 | 2021-07-28T09:26:55 | 374,267,631 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,445 | h | //============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
// Copyright 2018 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
// Copyright 2018 UT-Battelle, LLC.
// Copyright 2018 Los Alamos National Security.
//
// Under the terms of Contract DE-NA0003525 with NTESS,
// the U.S. Government retains certain rights in this software.
//
// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National
// Laboratory (LANL), the U.S. Government retains certain rights in
// this software.
//============================================================================
#ifndef vtk_m_Swap_h
#define vtk_m_Swap_h
#include <vtkm/internal/ExportMacros.h>
#ifdef __CUDACC__
#include <thrust/swap.h>
#else
#include <algorithm>
#endif
namespace vtkm
{
/// Performs a swap operation. Safe to call from cuda code.
#ifdef __CUDACC__
template <typename T>
VTKM_EXEC_CONT void Swap(T& a, T& b)
{
using namespace thrust;
swap(a, b);
}
#else
template <typename T>
VTKM_EXEC_CONT void Swap(T& a, T& b)
{
using namespace std;
swap(a, b);
}
#endif
} // end namespace vtkm
#endif //vtk_m_Swap_h
| [
"mingxin.wang@peraglobal.com"
] | mingxin.wang@peraglobal.com |
22f48aa7f16857cffbc98902ba639e89364eae7d | 38795814e06242bcb3f4836cda1c9b3282115460 | /README.md | 1da4cf48351c88d166d0f8f9180ea43aede90f2d | [] | no_license | puneetkpopli/c-for-loop-program | 33b79c4bd773a609a81e09dde8d096f1db001e0e | b2be3ce10b222b2973f61a644bc44b0655e9e657 | refs/heads/master | 2020-12-11T14:51:03.830724 | 2020-01-14T15:49:41 | 2020-01-14T15:49:41 | 233,876,905 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 189 | md | #include <iostream>
using namespace std;
int main () {
// for loop execution
for( int a = 10; a < 20; a = a + 1 ) {
cout << "value of a: " << a << endl;
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
b32bbffb1b1768c804f46c066749c712c322cdc6 | 119e8cd1ebf73adfe66dc8dc38ef9f359c25bdf3 | /src/CanWalk.h | b38ab9be6ae1c247ab025831d1e25b2ded1db54b | [] | no_license | csguth/DecoratorState | 3cdb8d6b1b2474228ba35e9f3b9afdb3a21eb365 | 37de1a6d08662af0e8866b4a6871f20bb0551484 | refs/heads/master | 2016-09-05T22:30:15.852909 | 2015-08-24T12:47:46 | 2015-08-24T12:47:46 | 41,277,725 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 359 | h | /*
* CanWalk.h
*
* Created on: 24 de ago de 2015
* Author: csguth
*/
#ifndef CANWALK_H_
#define CANWALK_H_
#include "BomberManStateDecorator.h"
class CanWalk: public BomberManStateDecorator {
public:
CanWalk(BomberManState * state);
virtual BomberManState * handleInput(Bomberman & bomberman, const Input & input);
};
#endif /* CANWALK_H_ */
| [
"csguth@gmail.com"
] | csguth@gmail.com |
fef3cda462662ed0849802fefd08b964d20aabab | 8bdf93e236c931ba546a3664947651724979fc63 | /CSensors.cpp | 0a09da12f03917e066d8dcde054f1efdc8b0a946 | [] | no_license | Jeanrenet/WarpMQTTSensor1 | 08eaad13281e71b2163b20b0b7e004f447c37b08 | fd2bee7246ff89ffbefaad17bef641f0773d0ef5 | refs/heads/master | 2020-04-02T14:11:37.262989 | 2018-10-30T12:32:00 | 2018-10-30T12:32:00 | 154,514,645 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,860 | cpp | #include "CSensors.h"
#include <QFile>
#include <QString>
#include <QDebug>
double stringToValue(QString path)
{
double value = 0;
QFile file(path);
if (file.exists())
{
if (file.open(QIODevice::ReadOnly))
{
QByteArray array = file.readAll().trimmed();
value = array.toDouble();
file.close();
}
}
return value;
}
CSensors::CSensors()
{
//récupération des échelles
m_accelerometerScale = stringToValue(ACCEL_SCALE);
m_magnetometerScale = stringToValue(MAGNET_SCALE);
m_barometerScale = stringToValue(PRESSURE_SCALE);
m_temperatureScale = stringToValue(TEMP_SCALE);
m_gyroscopeScale = stringToValue(GYRO_SCALE);
}
CSensors::~CSensors()
{
}
void CSensors::readData()
{
//lecture des données et application de l'échelle
m_accelerometerX = stringToValue(ACCEL_X) * m_accelerometerScale;
m_accelerometerY = stringToValue(ACCEL_Y) * m_accelerometerScale;
m_accelerometerZ = stringToValue(ACCEL_Z) * m_accelerometerScale;
m_magnetometerX = stringToValue(MAGNET_X) * m_magnetometerScale;
m_magnetometerY = stringToValue(MAGNET_Y) * m_magnetometerScale;
m_magnetometerZ = stringToValue(MAGNET_Z) * m_magnetometerScale;
//m_pressure = stringToValue(PRESSURE_RAW) * m_barometerScale;
m_temperature = stringToValue(TEMP_RAW) * m_temperatureScale;
m_gyroscopeX = stringToValue(GYRO_X) * m_gyroscopeScale;
m_gyroscopeY = stringToValue(GYRO_Y) * m_gyroscopeScale;
m_gyroscopeZ = stringToValue(GYRO_Z) * m_gyroscopeScale;
}
qreal CSensors::temperature() const
{
return m_temperature;
}
qreal CSensors::accelerometerZ() const
{
return m_accelerometerZ;
}
qreal CSensors::accelerometerY() const
{
return m_accelerometerY;
}
qreal CSensors::accelerometerX() const
{
return m_accelerometerX;
}
| [
"jchabrerie@gmail.com"
] | jchabrerie@gmail.com |
5122305b799c27c150e2c4b1ba046f20f57a67ef | bb94e2a568ee508e386a660392e853cd54dd1012 | /source/CopyingProcessor_Ganged_OpenCL.h | aba2a7e38653b52c15cc2d82bdde0c111e2e68a6 | [] | no_license | felidadae/dsp_opencl_gpu | 45a4ef4b39c2c78e79dfb81e952ee465dc35fef9 | 2d3ca22b9cf182b0c3fcbca4fb01356339b994ea | refs/heads/master | 2021-01-10T11:28:21.834496 | 2015-05-23T11:41:39 | 2015-05-23T11:41:39 | 36,120,776 | 12 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 916 | h | //
// CopyingProcessor_Ganged_OpenCL.h
// GPUProcessingTesting
//
// Created by kadlubek47 on 17.06.2013.
// Copyright (c) 2013 kadlubek47. All rights reserved.
//
#ifndef __GPUProcessingTesting__CopyingProcessor_Ganged_OpenCL__
#define __GPUProcessingTesting__CopyingProcessor_Ganged_OpenCL__
#include "OpenCLProcessorWithBuffersInOutBase.h"
#include "IProcess.h"
#include "Timer.h"
//Multi channel testing processor - one buffer for all channels
class CopyingProcessor_Ganged_OpenCL: public OpenCLProcessorWithBuffersInOutBase<float>, public IProcess<float> {
public:
CopyingProcessor_Ganged_OpenCL();
~CopyingProcessor_Ganged_OpenCL();
void process( AudioInOutBuffers<float>& audioBlocks );
private:
//Kernel
static const char kernelPath_[];
cl_kernel inOutKernel_;
//.
};
#endif /* defined(__GPUProcessingTesting__CopyingProcessor_Ganged_OpenCL__) */
| [
"felidadae@gmail.com"
] | felidadae@gmail.com |
6a863ffaa47cf68f207246182dab0a1c6e5c9e0c | bed303d9bbe09c3418dea2925604c9f85017f854 | /Algorithm/sort/HeapSort/HeapSort.cpp | 0a53e43f7879244b2dcf67ce0b7427019661ea94 | [
"MIT"
] | permissive | NicoleRobin/algorithm | ba4f9425f160904d7a86c91fee42bd2492a8f0da | 7d275b44889676da3e8a4a00fef990b844058510 | refs/heads/master | 2023-01-06T09:59:18.465931 | 2023-01-05T12:29:19 | 2023-01-05T12:29:19 | 40,276,880 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,171 | cpp | #include <stdio.h>
#include <stdlib.h>
void Print(int a[], int len)
{
for (int i = 0; i < len; i++)
{
printf("%d ", a[i]);
}
printf("\n");
}
// 调整某一个元素
void AdjustHeap(int a[], int i, int len)
{
int nChild = 2 * i + 1;
int nTemp = a[i];
while (nChild < len)
{
// 找到子节点中较大的一个
if (nChild + 1 < len && a[nChild] < a[nChild + 1])
{
nChild++;
}
if (nTemp < a[nChild])
{
a[i] = a[nChild];
a[nChild] = nTemp;
i = nChild;
nChild = 2 * nChild + 1;
}
else
{
break;
}
}
}
// 初始化堆
void InitHeap(int a[], int len)
{
for (int i = (len - 1) / 2; i >= 0; i--)
{
AdjustHeap(a, i, len);
}
}
// 堆排序
void HeapSort(int a[], int len)
{
// 初始堆
InitHeap(a, len);
// 排序
int nTemp = 0;
for (int i = len - 1; i > 0; i--)
{
// 交换第一个元素和最后一个元素
nTemp = a[i]; a[i] = a[0]; a[0] = nTemp;
// 调整堆
AdjustHeap(a, 0, i);
}
}
int main(void)
{
int a[] = { 9, 7, 2, 6, 5, 3, 10, 0, 1, 4 };
Print(a, 10);
// select sort
HeapSort(a, 10);
Print(a, 10);
return 0;
} | [
"lit050528@gmail.com"
] | lit050528@gmail.com |
75ba84384951441342314ea5a1008fced063f0f0 | 2f4cee019d13607191758faedddc8b88130be52d | /Paradis_Hydrogen/ParadisJHU06012020/ParadisJHU06012020/ezmath/BSPTreeNode.h | ecdebcf6d461b8bbb6ef3cb1ef16a622ce0f2db8 | [] | no_license | JinnyJingLuo/Expanse | ee0ed9f448fb230a09af049ac673c26d3397a76a | 207059c02868a6e1881a6748396e248e16d2e995 | refs/heads/master | 2023-05-06T13:17:38.859013 | 2021-05-26T07:11:04 | 2021-05-26T07:11:04 | 370,536,257 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,878 | h | //Ahmed Hussein
//ahussei4@jhu.edu
#ifndef BSPTREENODE_H_
#define BSPTREENODE_H_
#include "list"
#include "Plane.h"
#include "Tools.h"
using namespace std;
using namespace SupportSystem;
template <typename Type> class BSPTreeNode
{
public:
BSPTreeNode()
{
Initialize();
}
BSPTreeNode(const BSPTreeNode& oNode)
{
*this = oNode;
}
~BSPTreeNode()
{
Collapse();
}
BSPTreeNode& operator=(const BSPTreeNode& oNode)
{
m_poLeftChild = oNode.m_poLeftChild;
m_poRightChild = oNode.m_poRightChild;
m_loItems = oNode.m_loItems;
m_dSeparationValue = oNode.m_dSeparationValue;
m_iDimension = oNode.m_iDimension;
return *this;
}
void Collapse()
{
if(m_poLeftChild != NULL)
{
m_poLeftChild->Collapse();
delete m_poLeftChild;
}
if(m_poRightChild != NULL)
{
m_poRightChild->Collapse();
delete m_poRightChild;
}
m_poLeftChild = NULL;
m_poRightChild = NULL;
m_loItems.clear();
m_dSeparationValue = 0.0;
m_iDimension = 3;
}
void Initialize()
{
m_poLeftChild = NULL;
m_poRightChild = NULL;
m_loItems.clear();
m_dSeparationValue = 0.0;
m_iDimension = 3;
}
void SetLeftChild(BSPTreeNode<Type>* poChild)
{
if(poChild == NULL)
{
return;
}
m_poLeftChild = poChild;
}
void SetRightChild(BSPTreeNode<Type>* poChild)
{
if(poChild == NULL)
{
return;
}
m_poRightChild = poChild;
}
BSPTreeNode<Type>* GetLeftChild() const
{
return m_poLeftChild;
}
BSPTreeNode<Type>* GetRightChild() const
{
return m_poRightChild;
}
void AddItem(Type oItem)
{
m_loItems.push_back(oItem);
}
list<Type>* GetItems()
{
return &m_loItems;
}
void SetSeparator(vector<Point>* pvoPoints,const unsigned int& iDimensionIndex)
{
vector<double> vdData;
unsigned int iSize = (unsigned int)pvoPoints->size();
vdData.resize(iSize);
unsigned int i = 0;
for(i = 0 ; i < iSize ; i++)
{
vdData[i] = pvoPoints->at(i).GetComponent(iDimensionIndex);
}
QuickSort(vdData);
vector<Point> voPoints;
voPoints.resize(iSize);
if(iSize%2 == 0)
{
m_dSeparationValue = 0.5*(vdData[iSize/2] + vdData[iSize/2 + 1]);
}
else
{
m_dSeparationValue = vdData[iSize/2 + 1];
}
m_iDimension = iDimensionIndex;
}
int Classify(const Point& oPoint)
{
return Classify((Point*)&oPoint);
}
int Classify(Point* oPoint)
{
double dValue = oPoint->GetComponent(m_iDimension);
if(dValue > m_dSeparationValue)
{
return 1;
}
else if(dValue < m_dSeparationValue)
{
return -1;
}
return 0;
}
int ClassifyBox(AxisAlignedBoundingBox* poBox)
{
double dXMin = poBox->GetXMin();
double dXMax = poBox->GetXMax();
double dYMin = poBox->GetYMin();
double dYMax = poBox->GetYMax();
double dZMin = poBox->GetZMin();
double dZMax = poBox->GetZMax();
int iSum = 0;
iSum = iSum + Classify(Point(dXMin,dYMin,dZMin));
iSum = iSum + Classify(Point(dXMax,dYMin,dZMin));
iSum = iSum + Classify(Point(dXMax,dYMax,dZMin));
iSum = iSum + Classify(Point(dXMin,dYMax,dZMin));
iSum = iSum + Classify(Point(dXMin,dYMin,dZMax));
iSum = iSum + Classify(Point(dXMax,dYMin,dZMax));
iSum = iSum + Classify(Point(dXMax,dYMax,dZMax));
iSum = iSum + Classify(Point(dXMin,dYMax,dZMax));
if(iSum == 8)
{
return 1;
}
else if(iSum == -8)
{
return -1;
}
return 0;
}
bool IsLeaf()
{
if((m_poLeftChild == NULL) && (m_poRightChild == NULL))
{
return true;
}
return false;
}
double GetSeparator()
{
return m_dSeparationValue;
}
unsigned int GetDimension()
{
return m_iDimension;
}
private:
protected:
BSPTreeNode<Type>* m_poLeftChild;
BSPTreeNode<Type>* m_poRightChild;
list<Type> m_loItems;
double m_dSeparationValue;
unsigned int m_iDimension;
};
#endif
| [
"jluo32@login02.expanse.sdsc.edu"
] | jluo32@login02.expanse.sdsc.edu |
29cd9aea9de55015f9ab5b1df7d5bf8649e8534a | f1ae851f93202a4d34c1b8aa0a7db719ddf873c2 | /Best Time to Buy and Sell Stock with Cooldown.cpp | dd709577f478f09078da067dde618dab9f157fe6 | [] | no_license | sarahHe/LeetCode-solution | 331e5984eb238d54c76f3d5ad24443792087f5ff | f9b17c41f094c7188030dec70fce243456ff65ad | refs/heads/master | 2020-12-24T16:23:55.252447 | 2016-03-08T20:22:00 | 2016-03-08T20:22:00 | 28,280,816 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,237 | cpp | //Say you have an array for which the ith element is the price of a given stock on day i.
//Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
//You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
//After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
//Example:
//prices = [1, 2, 3, 0, 2]
//maxProfit = 3
//transactions = [buy, sell, cooldown, buy, sell]
//buy[i] = max(rest[i-1] - price, buy[i-1]);
//sell[i] = max(buy[i-1] + price, sell[i-1]);
//rest[i] = max(sell[i-1] - buy[i-1], rest[i-1]);
//because buy[i] <= rest[i] so that rest[i] = max(sell[i-1], rest[i-1])
//since we have cooldown, so that rest[i] = sell[i-1];
//buy[i] = max(sell[i-2] - price, buy[i-1]);
//sell[i] = max(buy[i-1] + price, sell[i-1]);
int maxProfit(vector<int>& prices) {
int buy = INT_MIN, pre_buy = 0, sell = 0, pre_sell = 0;
for (auto price : prices) {
pre_buy = buy;
buy = max(pre_sell - price, buy);
pre_sell = sell;
sell = max(sell + price, sell);
}
return sell;
}
| [
"hesha@umich.edu"
] | hesha@umich.edu |
6062d572c857a737d25fd33ba0421a21fd2b2040 | 26d3688d1839717de6edec3aa6fa60fb1fe3483d | /external/boost_1_60_0/qsboost/mpl/aux_/preprocessed/msvc70/or.hpp | 9d8a870d73b698ef9903a5baaa42e1b2eb031d98 | [
"MIT"
] | permissive | wouterboomsma/quickstep | 7d91c8070dca9f0d1d5ac30a38a9e159224a5e13 | a33447562eca1350c626883f21c68125bd9f776c | refs/heads/master | 2021-01-22T19:25:45.689105 | 2017-04-19T09:25:23 | 2017-04-19T09:25:23 | 88,726,115 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,389 | hpp |
// Copyright Aleksey Gurtovoy 2000-2004
//
// 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)
//
// Preprocessed version of "boost/mpl/or.hpp" header
// -- DO NOT modify by hand!
namespace qsboost { namespace mpl {
namespace aux {
template< bool C_ > struct or_impl
{
template<
typename T1, typename T2, typename T3, typename T4
>
struct result_
: true_
{
};
};
template<> struct or_impl<false>
{
template<
typename T1, typename T2, typename T3, typename T4
>
struct result_
: or_impl<
QSBOOST_MPL_AUX_NESTED_TYPE_WKND(T1)::value
>::template result_< T2,T3,T4,false_ >
{
};
template<> struct result_< false_,false_,false_,false_ >
: false_
{
};
};
} // namespace aux
template<
typename QSBOOST_MPL_AUX_NA_PARAM(T1)
, typename QSBOOST_MPL_AUX_NA_PARAM(T2)
, typename T3 = false_, typename T4 = false_, typename T5 = false_
>
struct or_
: aux::or_impl<
QSBOOST_MPL_AUX_NESTED_TYPE_WKND(T1)::value
>::template result_< T2,T3,T4,T5 >
{
QSBOOST_MPL_AUX_LAMBDA_SUPPORT(
5
, or_
, ( T1, T2, T3, T4, T5)
)
};
QSBOOST_MPL_AUX_NA_SPEC2(
2
, 5
, or_
)
}}
| [
"wb@di.ku.dk"
] | wb@di.ku.dk |
2c667a4dfe16383e4ae53024dabb750c2870d0ad | 0c3326033bc8552f184955f6e635c1eb731def89 | /GameClientMobile/StoryOfEren/Classes/CaptionLayer.cpp | 3c205f0c62417c534894ea4d138e2005246b9a88 | [] | no_license | EdCornejo/GameClient | ab0cf62c90a6c2d43755fa9f9c324a82d32b4f36 | 2cbcd60e5da92e69c2725cfa99130e7d45a092e9 | refs/heads/master | 2021-05-28T13:38:36.741256 | 2013-11-18T06:11:01 | 2013-11-18T06:11:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,203 | cpp | //
// CaptionLayer.cpp
// GameClientMobile
//
// Created by SungJinYoo on 3/24/13.
//
//
#include "Headers.pch"
CaptionLayer::CaptionLayer() : m_StageType(StageType_NONE), m_CaptionLabel(nullptr), m_NameLabel(nullptr), m_CharacterImage(nullptr), m_CaptionInfoList(), m_Tier(0), m_CaptionInfoListIndex(0), m_CaptionIndex(0)
{
}
CaptionLayer::~CaptionLayer()
{
CC_SAFE_RELEASE(this->m_CaptionLabel);
CC_SAFE_RELEASE(this->m_NameLabel);
CC_SAFE_RELEASE(this->m_CharacterImage);
std::for_each(this->m_CaptionInfoList.begin(), this->m_CaptionInfoList.end(), [](CaptionInfo* info){
delete info;
});
this->m_CaptionInfoList.clear();
}
bool CaptionLayer::init()
{
if(!BaseLayer::init())
{
return false;
}
// TODO : for test loaded tutorial script
bool result = this->LoadCaptionInfoFromFile(this->GetCaptionInfoFileName(this->m_StageType).c_str(), this->m_Tier);
if(!result) return false;
CCSprite* background = CCSprite::create("ui/textbox/background.png");
background->setAnchorPoint(CCPointLowerLeft);
this->addChild(background);
// set position of background? if needed
CCSize backgroundSize = background->getContentSize();
CCSize captionLabelSize = backgroundSize;
captionLabelSize.width -= 20;
captionLabelSize.height -= 20;
this->m_CaptionLabel = CCLabelTTF::create("", "thonburi", 20, captionLabelSize, kCCTextAlignmentLeft);
this->m_CaptionLabel->retain();
this->m_CaptionLabel->setAnchorPoint(CCPointLowerLeft);
this->m_CaptionLabel->setPosition(ccp(20, 0));
// set position of caption label
background->addChild(this->m_CaptionLabel);
background->setZOrder(1);
// set position of nameBox
CCSprite* nameBox = CCSprite::create("ui/textbox/namebox.png");
nameBox->setAnchorPoint(CCPointLowerLeft);
nameBox->setPosition(ccp(20, backgroundSize.height - 20));
this->addChild(nameBox);
CCSize nameBoxSize = nameBox->getContentSize();
nameBoxSize.width -= 10;
nameBoxSize.height -= 10;
this->m_NameLabel = CCLabelTTF::create("", "thonburi", 20, nameBoxSize, kCCTextAlignmentCenter, kCCVerticalTextAlignmentCenter);
this->m_NameLabel->retain();
this->m_NameLabel->setAnchorPoint(CCPointLowerLeft);
nameBox->addChild(this->m_NameLabel);
nameBox->setZOrder(2);
CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, kCCMenuHandlerPriority - 10, true);
this->setTouchEnabled(true);
return true;
}
CaptionLayer* CaptionLayer::create(const flownet::StageType stageType, const int tier)
{
CaptionLayer* captionLayer = new CaptionLayer();
captionLayer->m_StageType = stageType;
captionLayer->m_Tier = tier;
if(captionLayer && captionLayer->init())
{
captionLayer->autorelease();
return captionLayer;
}
else
{
delete captionLayer;
captionLayer = nullptr;
return nullptr;
}
}
bool CaptionLayer::ccTouchBegan(CCTouch* touch, CCEvent* event)
{
CC_UNUSED_PARAM(touch);
CC_UNUSED_PARAM(event);
int captionInfoListSize = this->m_CaptionInfoList.size();
ASSERT_DEBUG(this->m_CaptionInfoListIndex <= captionInfoListSize);
if(captionInfoListSize == this->m_CaptionInfoListIndex)
{
// NOTE : the caption is ended
this->runAction(CCCallFunc::create(this, callfunc_selector(CaptionLayer::CaptionEnded)));
return true;
}
CaptionInfo* currentCaptionInfo = this->m_CaptionInfoList[this->m_CaptionInfoListIndex];
ASSERT_DEBUG(currentCaptionInfo);
int captionListSize = currentCaptionInfo->m_CaptionList.size();
ASSERT_DEBUG(this->m_CaptionIndex <= captionListSize);
std::string currentCaption = currentCaptionInfo->m_CaptionList[this->m_CaptionIndex++];
// NOTE : display the character illust
if(this->m_CharacterImage)
{
this->m_CharacterImage->removeFromParent();
this->m_CharacterImage->release();
}
std::string characterImageFileName = "illust/";
if(currentCaptionInfo->m_Name.compare("player") == 0) {
Player* actor = GameClient::Instance().GetClientStage()->FindPlayer(GameClient::Instance().GetMyActorID());
if(!actor || actor->GetGender() == Gender_Female)
{
characterImageFileName += "blank";
}
else
{
characterImageFileName += "blank";
}
}
else {
characterImageFileName += currentCaptionInfo->m_Name;
}
characterImageFileName += ".png";
this->m_CharacterImage = CCSprite::create(characterImageFileName.c_str());
this->m_CharacterImage->retain();
this->m_CharacterImage->setZOrder(0);
CCPoint characterPosition;
if(currentCaptionInfo->m_CharacterPosition == CaptionCharacterPosition_LEFT)
{
const CCPoint leftSideIllustPosition = ccp(100, 160);
characterPosition = leftSideIllustPosition;
}
else
{
const CCPoint rightSideIllustPosition = ccp(380, 160);
characterPosition = rightSideIllustPosition;
}
this->m_CharacterImage->setPosition(characterPosition);
this->addChild(this->m_CharacterImage);
// NOTE : end of displaying character illust
// NOTE : process the reserved keyword for text
this->m_NameLabel->setString(this->ReplaceReservedKeyword(currentCaptionInfo->m_DisplayName).c_str());
this->m_CaptionLabel->setString(this->ReplaceReservedKeyword(currentCaption).c_str());
if(captionListSize == this->m_CaptionIndex)
{
this->m_CaptionInfoListIndex++;
this->m_CaptionIndex = 0;
}
return true;
}
void CaptionLayer::OnLoad()
{
BaseLayer::OnLoad();
// NOTE : for initialize force call ccTouchEnded
this->ccTouchBegan(nullptr, nullptr);
}
std::string CaptionLayer::GetCaptionInfoFileName(flownet::StageType stageType)
{
std::string captionFileName = "script/";
switch (stageType) {
case flownet::StageType_Intro:
captionFileName += "intro";
break;
default:
break;
}
captionFileName += ".plist";
return captionFileName;
}
// TODO : make return type of caption info
bool CaptionLayer::LoadCaptionInfoFromFile(const char * fileName, int tier)
{
CaptionCharacterPosition m_CharacterPosition;
std::string m_Name;
std::string m_DisplayName;
std::string m_State;
CaptionList m_CaptionList;
std::string m_AfterEvent;
CCDictionary* dict = CCDictionary::createWithContentsOfFile(fileName);
if(dict->count() == 0) return false;
CCDictionary* captionsDict = static_cast<CCDictionary*>(dict->objectForKey("captions"));
std::stringstream ss;
ss << tier;
std::string s = ss.str().c_str();
CCArray* captionInfos = static_cast<CCArray*>(captionsDict->objectForKey(s.c_str()));
CCObject* object;
CCARRAY_FOREACH(captionInfos, object)
{
CCDictionary* captionInfoDict = static_cast<CCDictionary*>(object);
// TO DO : multi region support comes here
CaptionInfo* captionInfo = new CaptionInfo();
captionInfo->m_CharacterPosition = static_cast<CaptionCharacterPosition>(atoi(static_cast<CCString*>(captionInfoDict->objectForKey("position"))->getCString()));
captionInfo->m_Name = static_cast<CCString*>(captionInfoDict->objectForKey("name"))->getCString();
captionInfo->m_DisplayName = static_cast<CCString*>(captionInfoDict->objectForKey("display_name_kr"))->getCString();
captionInfo->m_State = static_cast<CCString*>(captionInfoDict->objectForKey("state"))->getCString();
captionInfo->m_State = static_cast<CCString*>(captionInfoDict->objectForKey("state"))->getCString();
CCArray* captions = static_cast<CCArray*>(captionInfoDict->objectForKey("caption_kr"));
CCObject* captionObject;
CCARRAY_FOREACH(captions, captionObject)
{
captionInfo->m_CaptionList.push_back(static_cast<CCString*>(captionObject)->getCString());
}
if(captionInfoDict->objectForKey("after_event"))
{
captionInfo->m_AfterEvent = static_cast<CCString*>(captionInfoDict->objectForKey("after_event"))->getCString();
}
this->m_CaptionInfoList.push_back(captionInfo);
}
delete dict;
return true;
}
void CaptionLayer::CaptionEnded()
{
this->removeFromParent();
}
std::string CaptionLayer::ReplaceReservedKeyword(std::string contentString)
{
// NOTE : current reserved keywords are $PlayerName
Vector<std::string>::type reservedKeywordList = {"$PlayerName", };
Player* player = GameClient::Instance().GetClientStage()->FindPlayer(GameClient::Instance().GetMyActorID());
ASSERT_DEBUG(player);
std::string::size_type foundIndex = std::string::npos;
while((foundIndex = contentString.find("$PlayerName")) != std::string::npos)
{
contentString = contentString.replace(foundIndex, std::string("$PlayerName").size() , player->GetPlayerName().c_str());
}
return contentString;
} | [
"dosm123@gmail.com"
] | dosm123@gmail.com |
483e98d13a7efd3431eaf31f929abe06c7866bdc | 80ce0a9e84fc3148791e010ef84dd65bf5842ffb | /Brute-force/BOJ_1018.cpp | a5a35d63aa6e7068cadc1d06ff9ff91d52e889b3 | [] | no_license | HoYoungChun/Algorithm_PS | ba45ef61a58e4023b1573119a26209b94ec857ea | 475d1a7c9c66d0a6ed17d32fbfaecda5076a40fd | refs/heads/master | 2023-06-30T14:41:41.263701 | 2021-08-09T07:13:01 | 2021-08-09T07:13:01 | 279,521,952 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 864 | cpp | #include<iostream>
using namespace std;
int main(void)
{
char arr[51][51];
int cnt = 0;
int res = 3000;
int N,M;
cin >> N >> M;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
cin >> arr[i][j];
}
}
//입력받기 완료
for (int i = 0; i <= N - 8; i++) {
for (int j = 0; j <= M - 8; j++) {
//8x8의 맨왼쪽위는 arr[i][j]
cnt = 0;//다시칠해야할 개수
for (int k = i; k < i + 8; k++) {
for (int p = j; p < j + 8; p++) {
//맨왼쪽위가 W일 때 기준으로
if (((k - i) + (p - j)) % 2 == 0) {
//W이어야하는 위치
if (arr[k][p] != 'W')
cnt++;
}
else {
//B이어야하는 위치
if (arr[k][p] != 'B')
cnt++;
}
}
}
if (cnt > 64 - cnt)
cnt = 64 - cnt;
if (cnt < res)
res = cnt;
}
}
cout << res;
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
bc2b22b87755157d14d66991b99ea2df214b53fa | 4baf7c83cc4eca8717728c1fece4582814999365 | /test/horizontal_median_test.cpp | c5e49680cba0e5db118d6675d438eb9852e6aeeb | [
"Apache-2.0"
] | permissive | ogsdave/segmentation-sgm | 769a42c1b32fe6451abde046b5faf969f7317685 | ca1b09a0b70a8bab24937a5b624bc48f1f494748 | refs/heads/master | 2022-03-31T18:43:00.736958 | 2020-01-30T10:10:11 | 2020-01-30T10:10:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,844 | cpp | #include <gtest/gtest.h>
#include <opencv2/highgui.hpp>
#include "test_utility.h"
#include "reference.h"
#include "internal.h"
TEST(HorizontalMedianTest, RandomU8)
{
using disp_type = uchar;
using Mat = cv::Mat_<disp_type>;
const int segmentWidth = 10;
const int width = 1024;
const int height = 333;
Mat src = randomMat<disp_type>(height, width);
Mat dst1, dst2;
ref::horizontalMedian(src, dst1, segmentWidth);
sgm::horizontalMedian(src, dst2, segmentWidth);
EXPECT_TRUE(equals(dst1, dst2));
}
TEST(HorizontalMedianTest, RandomU16)
{
using disp_type = ushort;
using Mat = cv::Mat_<disp_type>;
const int segmentWidth = 10;
const int width = 1024;
const int height = 333;
Mat src = randomMat<disp_type>(height, width);
Mat dst1, dst2;
ref::horizontalMedian(src, dst1, segmentWidth);
sgm::horizontalMedian(src, dst2, segmentWidth);
EXPECT_TRUE(equals(dst1, dst2));
}
TEST(HorizontalMedianTest, FromFile)
{
const int segmentWidth = 10;
// Load data
const std::string testDataDir(TEST_DATA_DIR);
cv::Mat1b src = cv::imread(testDataDir + "/disparity.png");
cv::Mat1b dst1, dst2;
ref::horizontalMedian(src, dst1, segmentWidth);
sgm::horizontalMedian(src, dst2, segmentWidth);
EXPECT_TRUE(equals(dst1, dst2));
}
class HorizontalMedianSegmentWidthTest : public ::testing::TestWithParam<int> {};
INSTANTIATE_TEST_CASE_P(TestDataIntRange, HorizontalMedianSegmentWidthTest, ::testing::Range(3, 10, 1));
TEST_P(HorizontalMedianSegmentWidthTest, RangeTest)
{
using disp_type = ushort;
using Mat = cv::Mat_<disp_type>;
const int segmentWidth = GetParam();
const int width = 1024;
const int height = 333;
Mat src = randomMat<disp_type>(height, width);
Mat dst1, dst2;
ref::horizontalMedian(src, dst1, segmentWidth);
sgm::horizontalMedian(src, dst2, segmentWidth);
EXPECT_TRUE(equals(dst1, dst2));
}
| [
"akihiro.takagi@fixstars.com"
] | akihiro.takagi@fixstars.com |
3dad61a185029b1616ec591e2a46e653687f79ef | 85fb94fb7659f860d3299f887845c9979063afee | /interpretador.h | aba78dfe927e730809611b53ba21987254e213a7 | [] | no_license | eduardogarciazaccharias/Projeto_Unidade2_Parte_02 | 15bd45d5c35903ec6ae790cf6def3a9e7e715cd7 | e296d0cf015504c36983406f6de9d117811e6f46 | refs/heads/main | 2023-01-31T02:45:45.613633 | 2020-12-15T00:29:19 | 2020-12-15T00:29:19 | 321,506,394 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 404 | h | #ifndef INTERPRETADOR_H
#define INTERPRETADOR_H
#include <vector>
#include "figurageometrica.h"
#include "sculptor.h"
#include <string>
class interpretador{
int dimx, dimy, dimz;
float r, g, b, a;
public:
interpretador();
std::vector<Figurageometrica *> parse(std::string filename);
int getDimx();
int getDimy();
int getDimz();
};
#endif // INTERPRETADOR_H
| [
"noreply@github.com"
] | noreply@github.com |
fcc0d320d40ee9dc52fb9d237c2e79ea3738bd83 | 35e79b51f691b7737db254ba1d907b2fd2d731ef | /AtCoder/Marathon/intro-heuristics/B.cpp | f43a34760c06d3869949cd8faebf7d367aa80414 | [] | no_license | rodea0952/competitive-programming | 00260062d00f56a011f146cbdb9ef8356e6b69e4 | 9d7089307c8f61ea1274a9f51d6ea00d67b80482 | refs/heads/master | 2022-07-01T02:25:46.897613 | 2022-06-04T08:44:42 | 2022-06-04T08:44:42 | 202,485,546 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,609 | cpp | #pragma GCC optimize("O3")
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <string>
#include <cstring>
#include <deque>
#include <list>
#include <queue>
#include <stack>
#include <vector>
#include <utility>
#include <algorithm>
#include <map>
#include <set>
#include <complex>
#include <cmath>
#include <limits>
#include <cfloat>
#include <climits>
#include <ctime>
#include <cassert>
#include <numeric>
#include <fstream>
#include <functional>
#include <bitset>
using namespace std;
using ll = long long;
using P = pair<int, int>;
using T = tuple<int, int, int>;
template <class T> inline T chmax(T &a, const T b) {return a = (a < b) ? b : a;}
template <class T> inline T chmin(T &a, const T b) {return a = (a > b) ? b : a;}
constexpr int MOD = 1e9 + 7;
constexpr int inf = 1e9;
constexpr long long INF = 1e18;
#define all(a) (a).begin(), (a).end()
int dx[] = {1, 0, -1, 0};
int dy[] = {0, 1, 0, -1};
int main(){
cin.tie(0);
ios::sync_with_stdio(false);
int d; cin >> d;
vector<int> c(26);
vector<vector<int>> s(d, vector<int>(26));
vector<int> t(d);
for(int i=0; i<26; i++) cin >> c[i];
for(int i=0; i<d; i++){
for(int j=0; j<26; j++) cin >> s[i][j];
}
for(int i=0; i<d; i++) cin >> t[i], t[i]--;
int score = 0;
vector<int> lst(26, -1);
for(int i=0; i<d; i++){
score += s[i][t[i]];
lst[t[i]] = i;
for(int j=0; j<26; j++){
score -= c[j] * (i - lst[j]);
}
cout << score << endl;
}
return 0;
} | [
"dragondoor0912@yahoo.co.jp"
] | dragondoor0912@yahoo.co.jp |
25ed4fec0d017db8e6e5107ce537518bd9bf18f5 | b5a9d42f7ea5e26cd82b3be2b26c324d5da79ba1 | /tensorflow/core/kernels/cudnn_pooling_gpu.cc | 8027c4915d23f7055e179f5591448f6e58e2775c | [
"Apache-2.0"
] | permissive | uve/tensorflow | e48cb29f39ed24ee27e81afd1687960682e1fbef | e08079463bf43e5963acc41da1f57e95603f8080 | refs/heads/master | 2020-11-29T11:30:40.391232 | 2020-01-11T13:43:10 | 2020-01-11T13:43:10 | 230,088,347 | 0 | 0 | Apache-2.0 | 2019-12-25T10:49:15 | 2019-12-25T10:49:14 | null | UTF-8 | C++ | false | false | 11,018 | cc | /* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#define USE_EIGEN_TENSOR
#define EIGEN_USE_THREADS
#include <array>
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/kernels/conv_2d.h"
#include "tensorflow/core/kernels/conv_3d.h"
#include "tensorflow/core/kernels/conv_ops_gpu.h"
#include "tensorflow/core/kernels/cudnn_pooling_gpu.h"
typedef Eigen::GpuDevice GPUDevice;
namespace tensorflow {
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
template <typename T>
void DnnPooling3dOp<T>::Compute(OpKernelContext* context,
se::dnn::PoolingMode pooling_mode,
const std::array<int64, 3>& window,
const std::array<int64, 3>& stride,
const std::array<int64, 3>& padding,
TensorFormat data_format,
const Tensor& tensor_in, Tensor* output) {
const auto in_shape = tensor_in.shape();
const auto out_shape = output->shape();
const int64 in_batch = GetTensorDim(tensor_in, data_format, 'N');
const int64 in_features = GetTensorDim(tensor_in, data_format, 'C');
Tensor transformed_input;
if (data_format == FORMAT_NHWC) {
OP_REQUIRES_OK(context, context->allocate_temp(
DataTypeToEnum<T>::value,
ShapeFromFormat(FORMAT_NCHW, tensor_in.shape(),
data_format),
&transformed_input));
functor::NHWCToNCHW<GPUDevice, T, 5>()(context->eigen_device<GPUDevice>(),
tensor_in.tensor<T, 5>(),
transformed_input.tensor<T, 5>());
} else {
transformed_input = tensor_in;
}
Tensor transformed_output;
if (data_format == FORMAT_NHWC) {
OP_REQUIRES_OK(context,
context->allocate_temp(
DataTypeToEnum<T>::value,
ShapeFromFormat(FORMAT_NCHW, out_shape, data_format),
&transformed_output));
} else {
transformed_output = *output;
}
se::dnn::PoolingDescriptor pooling_desc(3);
pooling_desc.set_pooling_mode(pooling_mode);
se::dnn::BatchDescriptor input_desc(3);
input_desc.set_count(in_batch)
.set_feature_map_count(in_features)
.set_layout(se::dnn::DataLayout::kBatchDepthYX);
se::dnn::BatchDescriptor output_desc(3);
output_desc.set_count(in_batch)
.set_feature_map_count(in_features)
.set_layout(se::dnn::DataLayout::kBatchDepthYX);
for (size_t i = 0; i < window.size(); ++i) {
const auto dim_i = static_cast<se::dnn::DimIndex>(i);
pooling_desc.set_window(dim_i, window[i]);
pooling_desc.set_stride(dim_i, stride[i]);
pooling_desc.set_padding(dim_i, padding[i]);
input_desc.set_spatial_dim(dim_i,
GetTensorDim(tensor_in, data_format, '2' - i));
output_desc.set_spatial_dim(dim_i,
GetTensorDim(out_shape, data_format, '2' - i));
}
auto input_data = AsDeviceMemory(transformed_input.template flat<T>().data(),
transformed_input.template flat<T>().size());
auto output_data =
AsDeviceMemory(transformed_output.template flat<T>().data(),
transformed_output.template flat<T>().size());
auto* stream = context->op_device_context()->stream();
OP_REQUIRES(context, stream, errors::Internal("No GPU stream available."));
bool status = stream
->ThenPoolForward(pooling_desc, input_desc, input_data,
output_desc, &output_data)
.ok();
OP_REQUIRES(context, status,
errors::Internal("dnn PoolForward launch failed"));
if (data_format == FORMAT_NHWC) {
auto toConstTensor = [](const Tensor& x) -> const Tensor { return x; };
functor::NCHWToNHWC<GPUDevice, T, 5>()(
context->eigen_device<GPUDevice>(),
toConstTensor(transformed_output).template tensor<T, 5>(),
output->tensor<T, 5>());
}
}
template <typename T>
void DnnPooling3dGradOp<T>::Compute(
OpKernelContext* context, se::dnn::PoolingMode pooling_mode,
const std::array<int64, 3>& window, const std::array<int64, 3>& stride,
const std::array<int64, 3>& padding,
const std::array<int64, 3>& output_size, TensorFormat data_format,
const Tensor& out_backprop, const TensorShape& tensor_in_shape,
const Tensor* tensor_in, const Tensor* tensor_out, Tensor* input_backprop) {
CHECK((pooling_mode != se::dnn::PoolingMode::kMaximum) ||
(tensor_in && tensor_out))
<< "For MaxPoolGrad, both tensor_in and tensor_out needs to be "
"specified";
const int64 in_batch = GetTensorDim(tensor_in_shape, data_format, 'N');
const int64 in_features = GetTensorDim(tensor_in_shape, data_format, 'C');
Tensor transformed_input;
TensorShape transformed_input_shape;
if (data_format == FORMAT_NHWC || tensor_in == nullptr) {
transformed_input_shape =
ShapeFromFormat(FORMAT_NCHW, tensor_in_shape, data_format);
OP_REQUIRES_OK(context, context->allocate_temp(DataTypeToEnum<T>::value,
transformed_input_shape,
&transformed_input));
} else {
transformed_input = *tensor_in;
}
Tensor transformed_output;
TensorShape transformed_output_shape;
if (data_format == FORMAT_NHWC || tensor_out == nullptr) {
transformed_output_shape =
ShapeFromFormat(FORMAT_NCHW, out_backprop.shape(), data_format);
OP_REQUIRES_OK(context, context->allocate_temp(DataTypeToEnum<T>::value,
transformed_output_shape,
&transformed_output));
} else {
transformed_output = *tensor_out;
}
Tensor transformed_input_backprop;
if (data_format == FORMAT_NHWC) {
OP_REQUIRES_OK(context,
context->allocate_temp(DataTypeToEnum<T>::value,
transformed_input_shape,
&transformed_input_backprop));
} else {
transformed_input_backprop = *input_backprop;
}
Tensor transformed_output_backprop;
if (data_format == FORMAT_NHWC) {
OP_REQUIRES_OK(context,
context->allocate_temp(DataTypeToEnum<T>::value,
transformed_output_shape,
&transformed_output_backprop));
} else {
transformed_output_backprop = out_backprop;
}
if (data_format == FORMAT_NHWC) {
if (tensor_in != nullptr) {
functor::NHWCToNCHW<GPUDevice, T, 5>()(context->eigen_device<GPUDevice>(),
tensor_in->tensor<T, 5>(),
transformed_input.tensor<T, 5>());
}
if (tensor_out != nullptr) {
functor::NHWCToNCHW<GPUDevice, T, 5>()(context->eigen_device<GPUDevice>(),
tensor_out->tensor<T, 5>(),
transformed_output.tensor<T, 5>());
}
functor::NHWCToNCHW<GPUDevice, T, 5>()(
context->eigen_device<GPUDevice>(), out_backprop.tensor<T, 5>(),
transformed_output_backprop.tensor<T, 5>());
}
se::dnn::PoolingDescriptor pooling_desc(3);
pooling_desc.set_pooling_mode(pooling_mode);
se::dnn::BatchDescriptor orig_output_desc(3);
orig_output_desc.set_count(in_batch)
.set_feature_map_count(in_features)
.set_layout(se::dnn::DataLayout::kBatchDepthYX);
se::dnn::BatchDescriptor orig_input_desc(3);
orig_input_desc.set_count(in_batch)
.set_feature_map_count(in_features)
.set_layout(se::dnn::DataLayout::kBatchDepthYX);
for (size_t i = 0; i < window.size(); ++i) {
const auto dim_i = static_cast<se::dnn::DimIndex>(i);
pooling_desc.set_window(dim_i, window[i]);
pooling_desc.set_stride(dim_i, stride[i]);
pooling_desc.set_padding(dim_i, padding[i]);
orig_input_desc.set_spatial_dim(
dim_i, GetTensorDim(tensor_in_shape, data_format, '2' - i));
orig_output_desc.set_spatial_dim(dim_i, output_size[i]);
}
auto orig_output_data =
AsDeviceMemory(transformed_output.template flat<T>().data(),
transformed_output.template flat<T>().size());
auto orig_input_data =
AsDeviceMemory(transformed_input.template flat<T>().data(),
transformed_input.template flat<T>().size());
auto output_backprop_data =
AsDeviceMemory(transformed_output_backprop.template flat<T>().data(),
transformed_output_backprop.template flat<T>().size());
auto input_backprop_data =
AsDeviceMemory(transformed_input_backprop.template flat<T>().data(),
transformed_input_backprop.template flat<T>().size());
auto* stream = context->op_device_context()->stream();
OP_REQUIRES(context, stream, errors::Internal("No GPU stream available."));
bool status =
stream
->ThenPoolBackward(pooling_desc, orig_input_desc, orig_input_data,
orig_output_desc, orig_output_data,
output_backprop_data, &input_backprop_data)
.ok();
OP_REQUIRES(context, status,
errors::Internal("dnn PoolBackward launch failed"));
if (data_format == FORMAT_NHWC) {
auto toConstTensor = [](const Tensor& x) -> const Tensor { return x; };
functor::NCHWToNHWC<GPUDevice, T, 5>()(
context->eigen_device<GPUDevice>(),
toConstTensor(transformed_input_backprop).template tensor<T, 5>(),
input_backprop->tensor<T, 5>());
}
}
#define DEFINE_DNN_OPS(T) \
template class DnnPooling3dOp<T>; \
template class DnnPooling3dGradOp<T>;
TF_CALL_float(DEFINE_DNN_OPS) TF_CALL_half(DEFINE_DNN_OPS)
#undef DEFINE_DNN_OPS
#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
} // namespace tensorflow
| [
"v-grniki@microsoft.com"
] | v-grniki@microsoft.com |
6af732c9cae4070c84e348d27259a3d66053c4d6 | 7cdf190d7ea9d8f7307dc358bb70eb382c977f41 | /utilities.cpp | 1189b97febe1d422e2a19f431d37949fdced2abc | [] | no_license | mauricerizat/64-Bit-RSA-Encryption-and-Signing | 424e5162555bf9530810b20ecd1d58f421f3d60e | 2af84a7dfb7dd024bf58b27f9359a319e69ddfa0 | refs/heads/master | 2022-12-18T13:42:28.132738 | 2020-09-22T22:45:10 | 2020-09-22T22:45:10 | 297,789,307 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,008 | cpp | /*
RSA ENCRYPTION PROGRAM
*/
#include "header.h"
//Wites given content to given file
void writeFile(string content, string fileName)
{
ofstream fileWriter;
fileWriter.open ("data/" + fileName);
fileWriter << content << endl;
fileWriter.close();
}
//Reads from given file and returns corresponding content
string readFile(string fileName)
{
string content = "";
ifstream fileReader("data/" + fileName); //File to be located in "data" sub-folder
if (!(fileReader.is_open())) //Input file cannot be opened or does not exist
{
cout << "\n\tFile named \"" << fileName;
cout << "\" cannot be opened or does not exist.";
cout << "\n\tPlease try again with a valid file name.\n" << endl;
return 0;
}
else //Input file exists
{
//Reading Input file
try
{
string line;
while (getline(fileReader, line))
content += (line + "\n");
content = content.substr(0, content.size()-1);
fileReader.close();
}
catch (exception& e) //Handles errors that occurs during file reading
{
cout << "An error occured while reading file. Please try again.\n" << endl;
return 0;
}
}
return content;
}
//Calculate inverse of a modulo b using Extended Euclidean Algorithm
uint64_t aInverseModb(uint64_t a, uint64_t b)
{
uint64_t n1 = b;
uint64_t n2 = a;
long long int a1 = 1;
long long int b1 = 0;
long long int a2 = 0;
long long int b2 = 1;
long long int q = n1 / n2;
long long int r = n1 % n2;
while (r > 0)
{
n1 = n2;
n2 = r;
long long int t = a2;
a2 = a1 - q*a2;
a1 = t;
t = b2;
b2 = b1 - q*b2;
b1 = t;
q = n1 / n2;
r = n1 % n2;
}
if (b2 < 0)
b2 = b + b2;
return b2;
}
//Calculate gcd or two values using Euclidean Algorithm
uint64_t gcd(uint64_t a, uint64_t b)
{
if (a == 0 || b == 0)
return 0;
if (a < b)
{
uint64_t t = a;
a = b;
b = t;
}
uint64_t rem = a%b;
while (rem > 0)
{
a = b;
b = rem;
rem = a % b;
}
return b;
}
//Check if given number is prime
bool isPrime(uint64_t n)
{
if (n == 1 || n == 0)
return false;
for (int i = 2; i <= pow(n, 0.5); ++i)
{
if (n%i == 0)
return false;
}
return true;
}
//Check if given string contains only Integers
bool isInteger(string num)
{
for (int i = 0; i < num.length(); ++i)
{
if (num[i] < '0' || num[i] > '9')
return false;
}
return true;
}
//Perform modular multiplication
uint64_t modular_mul(uint64_t a, uint64_t b, uint64_t mod)
{
uint64_t result = 0;
for (uint64_t current_term = a; b; b >>= 1)
{
if (b & 1)
{
result = (result + current_term) % mod;
}
current_term = 2 * current_term % mod;
}
return result;
}
//Perform modular exponentiation
uint64_t modular_pow(uint64_t base, uint64_t exp, uint64_t mod)
{
uint64_t result = 1;
for (uint64_t current_factor = base; exp; exp >>= 1)
{
if (exp & 1)
{
result = modular_mul(result, current_factor, mod);
}
current_factor = modular_mul(current_factor, current_factor, mod);
}
return result;
}
| [
"noreply@github.com"
] | noreply@github.com |
6d90304985e1c48ce9c134e5d31f2fffdc1751f2 | 4cb0f2cfb9ec3ec8c851f83ff3ea73ca5a62aa70 | /democodebase/pt/boost/optional.h | 7e0c36bf4537f3def4088e34e530f834cb543ce2 | [] | no_license | Codarki/Pyrotech_2016 | 99733bb543621d755dc0451cee86e3988021a1e2 | 5e7a71b9ec751061285f3f784e861ac8f2726ee1 | refs/heads/main | 2023-05-30T08:11:30.626406 | 2021-06-24T23:13:53 | 2021-06-24T23:13:53 | 380,065,207 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 168 | h | #ifndef PT_BOOST_OPTIONAL_H
#define PT_BOOST_OPTIONAL_H
#include "auto_link.h"
#include <boost/optional.hpp>
namespace pt {
//using ::boost::optional;
}
#endif
| [
"pietila.kimmo@gmail.com"
] | pietila.kimmo@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.