hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
108
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8ea9435ee69f6139fa6d3430ace8728bd50421b8
| 1,795
|
cpp
|
C++
|
src/one_tree.cpp
|
LukasErlenbach/tsp_solver
|
016a1e794de7b58f666b3635977e39aeadb46c99
|
[
"MIT"
] | null | null | null |
src/one_tree.cpp
|
LukasErlenbach/tsp_solver
|
016a1e794de7b58f666b3635977e39aeadb46c99
|
[
"MIT"
] | null | null | null |
src/one_tree.cpp
|
LukasErlenbach/tsp_solver
|
016a1e794de7b58f666b3635977e39aeadb46c99
|
[
"MIT"
] | null | null | null |
#include "branching_node.hpp"
/**
* @file one_tree.hpp
* @brief Implementation of class @c OneTree.
* **/
namespace Core {
/////////////////////////////////////////////
//! \c OneTree definitions
/////////////////////////////////////////////
OneTree::OneTree(const PredVec &preds, const Degrees °rees, const double cost)
: _preds(preds), _degrees(degrees), _cost(cost) {}
// this test is sufficient since PredVecs are assumed to be connected (since
// they encode OneTrees)
bool OneTree::is_tour() const {
for (Degree d : _degrees) {
if (d != 2) {
return false;
}
}
return true;
}
// greedily finds a node with degree > 2
NodeId OneTree::hd_node() const {
for (NodeId node_id = 0; node_id < _degrees.size(); ++node_id) {
if (_degrees[node_id] > 2) {
return node_id;
}
}
// this case should never occur, we only call this after checking with
// is_tour()
throw std::runtime_error("Error in OneTree::hd_node(): No node with degree > 2.");
return invalid_node_id;
}
NodeIds OneTree::neighbors(const NodeId node_id) const {
NodeIds neighbors = {};
neighbors.reserve(_degrees[node_id]);
if (node_id == 0) {
// -> first 2 entrys are neighbors
neighbors.push_back(_preds[0]);
neighbors.push_back(_preds[1]);
}
if (node_id == _preds[0] or node_id == _preds[1]) {
// -> adjacent to node 0
neighbors.push_back(0);
}
for (NodeId other_id = 2; other_id < _preds.size(); ++other_id) {
if (_preds[other_id] == node_id) {
// -> other_id is successor in the OneTree
neighbors.push_back(other_id);
continue;
}
if (other_id == node_id) {
// -> other_id is predecessor in the OneTree
neighbors.push_back(_preds[node_id]);
}
}
return neighbors;
}
} // namespace Core
| 26.397059
| 84
| 0.615042
|
LukasErlenbach
|
8eaa13d41994856cf8f60f3702734dace09604e2
| 1,619
|
hpp
|
C++
|
src/rpcz/sync_call_handler.hpp
|
jinq0123/rpcz
|
d273dc1a8de770cb4c2ddee98c17ce60c657d6ca
|
[
"Apache-2.0"
] | 4
|
2015-06-14T13:38:40.000Z
|
2020-11-07T02:29:59.000Z
|
src/rpcz/sync_call_handler.hpp
|
jinq0123/rpcz
|
d273dc1a8de770cb4c2ddee98c17ce60c657d6ca
|
[
"Apache-2.0"
] | 1
|
2015-06-19T07:54:53.000Z
|
2015-11-12T10:38:21.000Z
|
src/rpcz/sync_call_handler.hpp
|
jinq0123/rpcz
|
d273dc1a8de770cb4c2ddee98c17ce60c657d6ca
|
[
"Apache-2.0"
] | 3
|
2015-06-15T02:28:39.000Z
|
2018-10-18T11:02:59.000Z
|
// Licensed under the Apache License, Version 2.0 (the "License");
// Author: Jin Qing (http://blog.csdn.net/jq0123)
#ifndef RPCZ_SYNC_CALL_HANDLER_HPP
#define RPCZ_SYNC_CALL_HANDLER_HPP
#include <boost/noncopyable.hpp>
#include <boost/optional.hpp>
#include <google/protobuf/message.h>
#include <rpcz/common.hpp> // for scoped_ptr
#include <rpcz/rpc_error.hpp>
#include <rpcz/sync_event.hpp>
namespace rpcz {
class rpc_error;
// Handler to simulate sync call.
class sync_call_handler : boost::noncopyable {
public:
inline explicit sync_call_handler(
google::protobuf::Message* response)
: response_(response) {}
inline ~sync_call_handler(void) {}
public:
inline void operator()(const rpc_error* error,
const void* data, size_t size);
inline void wait() { sync_.wait(); }
inline const rpc_error* get_rpc_error() const {
return error_.get_ptr();
}
private:
void handle_error(const rpc_error& err);
void handle_invalid_message();
inline void signal() { sync_.signal(); }
private:
sync_event sync_;
google::protobuf::Message* response_;
boost::optional<rpc_error> error_;
};
inline void sync_call_handler::operator()(
const rpc_error* error,
const void* data, size_t size) {
if (error) {
handle_error(*error);
signal();
return;
}
BOOST_ASSERT(data);
if (NULL == response_) {
signal();
return;
}
if (response_->ParseFromArray(data, size)) {
BOOST_ASSERT(!error_);
signal();
return;
}
// invalid message
handle_invalid_message();
signal();
}
} // namespace rpcz
#endif // RPCZ_SYNC_CALL_HANDLER_HPP
| 22.486111
| 66
| 0.696726
|
jinq0123
|
8eacff5f5ccdf66cba37be123d641ee40280087a
| 1,618
|
cc
|
C++
|
src/plugin/graphics/text/src/font/bitmapfontmanager.cc
|
motor-dev/Motor
|
98cb099fe1c2d31e455ed868cc2a25eae51e79f0
|
[
"BSD-3-Clause"
] | null | null | null |
src/plugin/graphics/text/src/font/bitmapfontmanager.cc
|
motor-dev/Motor
|
98cb099fe1c2d31e455ed868cc2a25eae51e79f0
|
[
"BSD-3-Clause"
] | null | null | null |
src/plugin/graphics/text/src/font/bitmapfontmanager.cc
|
motor-dev/Motor
|
98cb099fe1c2d31e455ed868cc2a25eae51e79f0
|
[
"BSD-3-Clause"
] | null | null | null |
/* Motor <motor.devel@gmail.com>
see LICENSE for detail */
#include <motor/plugin.graphics.text/stdafx.h>
#include <bitmapfontmanager.hh>
#include <fontlist.hh>
namespace Motor {
BitmapFontManager::BitmapFontManager(weak< Resource::ResourceManager > manager,
weak< FreetypeLibrary > freetype,
weak< const FontList > fontList)
: m_manager(manager)
, m_freetype(freetype)
, m_fontList(fontList)
{
}
BitmapFontManager::~BitmapFontManager()
{
}
void BitmapFontManager::load(weak< const Resource::IDescription > /*description*/,
Resource::Resource& /*resource*/)
{
motor_info("loading bitmap font");
}
void BitmapFontManager::reload(weak< const Resource::IDescription > /*oldDescription*/,
weak< const Resource::IDescription > /*newDescription*/,
Resource::Resource& /*resource*/)
{
motor_info("reloading bitmap font");
}
void BitmapFontManager::unload(weak< const Resource::IDescription > /*description*/,
Resource::Resource& /*resource*/)
{
motor_info("unloading bitmap font");
}
void BitmapFontManager::onTicketLoaded(weak< const Resource::IDescription > /*description*/,
Resource::Resource& /*resource*/,
const minitl::Allocator::Block< u8 >& /*buffer*/,
LoadType /*type*/)
{
motor_info("bitmap font file done loading");
}
} // namespace Motor
| 31.72549
| 92
| 0.57911
|
motor-dev
|
8eb1fb99e1744279d9305287c855c2e611b06c83
| 2,294
|
hpp
|
C++
|
SDK/ARKSurvivalEvolved_PrimalItem_Spawner_Exosuit_parameters.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 10
|
2020-02-17T19:08:46.000Z
|
2021-07-31T11:07:19.000Z
|
SDK/ARKSurvivalEvolved_PrimalItem_Spawner_Exosuit_parameters.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 9
|
2020-02-17T18:15:41.000Z
|
2021-06-06T19:17:34.000Z
|
SDK/ARKSurvivalEvolved_PrimalItem_Spawner_Exosuit_parameters.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 3
|
2020-07-22T17:42:07.000Z
|
2021-06-19T17:16:13.000Z
|
#pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_PrimalItem_Spawner_Exosuit_classes.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function PrimalItem_Spawner_Exosuit.PrimalItem_Spawner_Exosuit_C.BPCanUse
struct UPrimalItem_Spawner_Exosuit_C_BPCanUse_Params
{
bool* bIgnoreCooldown; // (Parm, ZeroConstructor, IsPlainOldData)
bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
};
// Function PrimalItem_Spawner_Exosuit.PrimalItem_Spawner_Exosuit_C.GetStatDisplayString
struct UPrimalItem_Spawner_Exosuit_C_GetStatDisplayString_Params
{
TEnumAsByte<EPrimalCharacterStatusValue>* Stat; // (Parm, ZeroConstructor, IsPlainOldData)
int* Value; // (Parm, ZeroConstructor, IsPlainOldData)
int* StatConvertMapIndex; // (Parm, ZeroConstructor, IsPlainOldData)
class FString StatDisplay; // (Parm, OutParm, ZeroConstructor)
class FString ValueDisplay; // (Parm, OutParm, ZeroConstructor)
bool ShowInTooltip; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function PrimalItem_Spawner_Exosuit.PrimalItem_Spawner_Exosuit_C.ExecuteUbergraph_PrimalItem_Spawner_Exosuit
struct UPrimalItem_Spawner_Exosuit_C_ExecuteUbergraph_PrimalItem_Spawner_Exosuit_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 49.869565
| 173
| 0.493897
|
2bite
|
8eb26e68f715d0be03e3215e8627694528f16e18
| 78
|
cpp
|
C++
|
escos/src/common/unittest.cpp
|
OSADP/MMITSS_THEA
|
53ef55d0622f230002c75046db6af295592dbf0a
|
[
"Apache-2.0"
] | null | null | null |
escos/src/common/unittest.cpp
|
OSADP/MMITSS_THEA
|
53ef55d0622f230002c75046db6af295592dbf0a
|
[
"Apache-2.0"
] | null | null | null |
escos/src/common/unittest.cpp
|
OSADP/MMITSS_THEA
|
53ef55d0622f230002c75046db6af295592dbf0a
|
[
"Apache-2.0"
] | null | null | null |
#ifdef C2X_UNIT_TESTS
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#endif
| 11.142857
| 25
| 0.794872
|
OSADP
|
8eb6f8cf6456ebf20008a16a6ab8ad1306d4ed87
| 6,935
|
cpp
|
C++
|
smaug/core/tensor.cpp
|
mrbeann/smaug
|
01ef7892bb25cb08c13cea6125efc1528a8de260
|
[
"BSD-3-Clause"
] | 50
|
2020-06-12T19:53:37.000Z
|
2022-03-30T15:05:34.000Z
|
smaug/core/tensor.cpp
|
mrbeann/smaug
|
01ef7892bb25cb08c13cea6125efc1528a8de260
|
[
"BSD-3-Clause"
] | 37
|
2020-06-23T17:28:42.000Z
|
2021-10-21T05:30:36.000Z
|
smaug/core/tensor.cpp
|
mrbeann/smaug
|
01ef7892bb25cb08c13cea6125efc1528a8de260
|
[
"BSD-3-Clause"
] | 18
|
2020-06-17T19:59:23.000Z
|
2022-02-15T07:40:47.000Z
|
#include "smaug/core/tensor.h"
#include "smaug/core/tensor_utils.h"
#include "smaug/core/globals.h"
#include "smaug/utility/thread_pool.h"
namespace smaug {
TensorShapeProto* TensorShape::asTensorShapeProto() {
TensorShapeProto* shapeProto = new TensorShapeProto();
*shapeProto->mutable_dims() = { dims_.begin(), dims_.end() };
shapeProto->set_layout(layout);
shapeProto->set_alignment(alignment);
return shapeProto;
}
TensorProto* Tensor::asTensorProto() {
TensorProto* tensorProto = new TensorProto();
tensorProto->set_name(name);
tensorProto->set_data_type(dataType);
tensorProto->set_allocated_shape(shape.asTensorShapeProto());
tensorProto->set_data_format(dataFormat);
// Copy the tensor data into the proto.
TensorData* protoData = new TensorData();
void* rawPtr = tensorData.get();
switch (dataType) {
case Float16:
// Add 1 to cover the case when the storage size is odd.
protoData->mutable_half_data()->Resize(
(shape.storageSize() + 1) / 2, 0);
memcpy(protoData->mutable_half_data()->mutable_data(), rawPtr,
shape.storageSize() * sizeof(float16));
break;
case Float32:
protoData->mutable_float_data()->Resize(shape.storageSize(), 0);
memcpy(protoData->mutable_float_data()->mutable_data(), rawPtr,
shape.storageSize() * sizeof(float));
break;
case Float64:
protoData->mutable_double_data()->Resize(shape.storageSize(), 0);
memcpy(protoData->mutable_double_data()->mutable_data(), rawPtr,
shape.storageSize() * sizeof(double));
break;
case Int32:
protoData->mutable_int_data()->Resize(shape.storageSize(), 0);
memcpy(protoData->mutable_int_data()->mutable_data(), rawPtr,
shape.storageSize() * sizeof(int));
break;
case Int64:
protoData->mutable_int64_data()->Resize(shape.storageSize(), 0);
memcpy(protoData->mutable_int64_data()->mutable_data(), rawPtr,
shape.storageSize() * sizeof(int64_t));
break;
case Bool:
protoData->mutable_bool_data()->Resize(shape.storageSize(), 0);
memcpy(protoData->mutable_bool_data()->mutable_data(), rawPtr,
shape.storageSize() * sizeof(bool));
break;
default:
assert(false && "Unknown data type!");
}
tensorProto->set_allocated_data(protoData);
return tensorProto;
}
Tensor* TiledTensor::getTileWithData(int index) {
Tile* tile = &tiles[index];
copyDataToTile(tile);
return tile->tensor;
}
void TiledTensor::setTile(int index,
const std::vector<int>& origin,
Tensor* tensor,
bool copyData) {
Tile* tile = &tiles[index];
tile->tensor = tensor;
tile->origin = origin;
tile->hasOrigin = true;
if (copyData)
copyDataToTile(tile);
}
void* TiledTensor::tileCopyWorker(void* _args) {
auto args = reinterpret_cast<CopyTilesArgs*>(_args);
TiledTensor* tiledTensor = args->tiledTensor;
int start = args->start;
int numTiles = args->numTiles;
TileDataOperation op = args->op;
for (int i = start; i < start + numTiles; i++) {
Tile* tile = tiledTensor->getTile(i);
if (op == Scatter)
tiledTensor->copyDataToTile(tile);
else if (op == Gather)
tiledTensor->gatherDataFromTile(tile);
}
delete args;
return nullptr;
}
void TiledTensor::parallelCopyTileData(TileDataOperation op) {
int totalNumTiles = tiles.size();
int numTilesPerThread = std::ceil(totalNumTiles * 1.0 / threadPool->size());
int remainingTiles = totalNumTiles;
while (remainingTiles > 0) {
int numTiles = std::min(numTilesPerThread, remainingTiles);
auto args = new CopyTilesArgs(
this, totalNumTiles - remainingTiles, numTiles, op);
int cpuid =
threadPool->dispatchThread(tileCopyWorker, (void*)args);
assert(cpuid != -1 && "Failed to dispatch thread!");
remainingTiles -= numTiles;
}
threadPool->joinThreadPool();
}
void TiledTensor::copyDataToAllTiles() {
// Don't copy if all the tiles have data filled.
if (dataFilled)
return;
assert(origTensor != nullptr &&
"TiledTensor must have the original tensor to copy data from!");
if (fastForwardMode || !threadPool || tiles.size() == 1) {
for (auto index = startIndex(); !index.end(); ++index)
copyDataToTile(&tiles[index]);
} else {
parallelCopyTileData(Scatter);
}
dataFilled = true;
}
void TiledTensor::copyDataToTile(Tile* tile) {
// Don't copy if the tile already has data, or if the tile is the original
// tensor (we have only one tile).
if (tile->hasData || tile->tensor == origTensor)
return;
// Perform the data copy.
assert(tile->hasOrigin &&
"Must set the tile's origin in the original tensor!");
if (useRawTensor) {
// Use the raw tensor copy function for the unary tile.
copyRawTensorData(tile->tensor, origTensor, 0, tile->origin[0],
tile->tensor->getShape().storageSize());
} else {
std::vector<int> dstOrigin(tile->tensor->ndims(), 0);
copyTensorRegion(tile->tensor, origTensor, dstOrigin, tile->origin,
tile->tensor->getShape().dims());
}
tile->hasData = true;
}
void TiledTensor::untile() {
assert(origTensor != nullptr &&
"TiledTensor must have the original tensor to copy data to!");
const TensorShape& tensorShape = origTensor->getShape();
int ndims = tensorShape.ndims();
if (tiles.size() == 1) {
// No need to copy data if the tile is the original tensor.
return;
}
if (fastForwardMode || !threadPool) {
for (auto index = startIndex(); !index.end(); ++index)
gatherDataFromTile(&tiles[index]);
} else {
parallelCopyTileData(Gather);
}
}
void TiledTensor::gatherDataFromTile(Tile* tile) {
// Perform the data copy.
assert(tile->hasOrigin &&
"Must set the tile's origin in the original tensor!");
if (useRawTensor) {
// Use the raw tensor copy function for the unary tile.
copyRawTensorData(origTensor, tile->tensor, tile->origin[0], 0,
tile->tensor->getShape().storageSize());
} else {
std::vector<int> srcOrigin(tile->tensor->ndims(), 0);
copyTensorRegion(origTensor,
tile->tensor,
tile->origin,
srcOrigin,
tile->tensor->getShape().dims());
}
}
} // namespace smaug
| 36.5
| 80
| 0.603317
|
mrbeann
|
8eb80589d93faf35ad4eb82fda45dc979a250a07
| 1,207
|
cpp
|
C++
|
test/delegate/test_bad_delegate_call.cpp
|
rmettler/cpp_delegates
|
8557a1731eccbad9608f3111c5599f666b74750e
|
[
"BSL-1.0"
] | 4
|
2020-01-30T19:17:57.000Z
|
2020-04-02T13:03:13.000Z
|
test/delegate/test_bad_delegate_call.cpp
|
rmettler/cpp_delegates
|
8557a1731eccbad9608f3111c5599f666b74750e
|
[
"BSL-1.0"
] | null | null | null |
test/delegate/test_bad_delegate_call.cpp
|
rmettler/cpp_delegates
|
8557a1731eccbad9608f3111c5599f666b74750e
|
[
"BSL-1.0"
] | null | null | null |
//
// Project: C++ delegates
//
// Copyright Roger Mettler 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE or copy at
// https://www.boost.org/LICENSE_1_0.txt)
//
#include <doctest.h>
#include <rome/detail/bad_delegate_call.hpp>
#include <type_traits>
TEST_SUITE_BEGIN("header file: rome/bad_delegate_call.hpp");
TEST_CASE("rome::bad_delegate_call") {
static_assert(std::is_nothrow_default_constructible<rome::bad_delegate_call>::value, "");
static_assert(std::is_nothrow_copy_constructible<rome::bad_delegate_call>::value, "");
static_assert(std::is_nothrow_copy_assignable<rome::bad_delegate_call>::value, "");
static_assert(std::is_nothrow_move_constructible<rome::bad_delegate_call>::value, "");
static_assert(std::is_nothrow_move_assignable<rome::bad_delegate_call>::value, "");
static_assert(std::is_nothrow_destructible<rome::bad_delegate_call>::value, "");
static_assert(std::is_base_of<std::exception, rome::bad_delegate_call>::value, "");
CHECK_THROWS_WITH_AS(
throw rome::bad_delegate_call{}, "rome::bad_delegate_call", rome::bad_delegate_call);
}
TEST_SUITE_END(); // rome/bad_delegate_call.hpp
| 40.233333
| 93
| 0.754764
|
rmettler
|
8ebd11dc81d5d857155b39acd498a54c06eaf01b
| 1,487
|
hpp
|
C++
|
discregrid/include/Discregrid/acceleration/bounding_sphere_hierarchy.hpp
|
lasagnaphil/Discregrid
|
83bec4b39445e7ed62229e6f84d94c0cfcc1136b
|
[
"MIT"
] | null | null | null |
discregrid/include/Discregrid/acceleration/bounding_sphere_hierarchy.hpp
|
lasagnaphil/Discregrid
|
83bec4b39445e7ed62229e6f84d94c0cfcc1136b
|
[
"MIT"
] | null | null | null |
discregrid/include/Discregrid/acceleration/bounding_sphere_hierarchy.hpp
|
lasagnaphil/Discregrid
|
83bec4b39445e7ed62229e6f84d94c0cfcc1136b
|
[
"MIT"
] | null | null | null |
#pragma once
#include "types.hpp"
#include "bounding_sphere.hpp"
#include "kd_tree.hpp"
#include <span.hpp>
namespace Discregrid
{
class TriangleMeshBSH : public KDTree<BoundingSphere>
{
public:
using super = KDTree<BoundingSphere>;
TriangleMeshBSH(std::span<const Vector3r> vertices,
std::span<const Eigen::Vector3i> faces);
Vector3r const& entityPosition(int i) const final;
void computeHull(int b, int n, BoundingSphere& hull) const final;
private:
std::span<const Vector3r> m_vertices;
std::span<const Eigen::Vector3i> m_faces;
std::vector<Vector3r> m_tri_centers;
};
class TriangleMeshBBH : public KDTree<AlignedBox3r>
{
public:
using super = KDTree<AlignedBox3r>;
TriangleMeshBBH(std::span<const Vector3r> vertices,
std::span<const Eigen::Vector3i> faces);
Vector3r const& entityPosition(int i) const final;
void computeHull(int b, int n, AlignedBox3r& hull) const final;
private:
std::span<const Vector3r> m_vertices;
std::span<const Eigen::Vector3i> m_faces;
std::vector<Vector3r> m_tri_centers;
};
class PointCloudBSH : public KDTree<BoundingSphere>
{
public:
using super = KDTree<BoundingSphere>;
PointCloudBSH();
PointCloudBSH(std::span<const Vector3r> vertices);
Vector3r const& entityPosition(int i) const final;
void computeHull(int b, int n, BoundingSphere& hull)
const final;
private:
std::span<const Vector3r> m_vertices;
};
}
| 19.826667
| 67
| 0.705447
|
lasagnaphil
|
8ebde15b22131d13eebeffbf14d860e37bc7ed26
| 4,173
|
cpp
|
C++
|
src/mirrage/net/src/server.cpp
|
lowkey42/mirrage
|
2527537989a548062d0bbca8370d063fc6b81a18
|
[
"MIT"
] | 14
|
2017-10-26T08:45:54.000Z
|
2021-04-06T11:44:17.000Z
|
src/mirrage/net/src/server.cpp
|
lowkey42/mirrage
|
2527537989a548062d0bbca8370d063fc6b81a18
|
[
"MIT"
] | 17
|
2017-10-09T20:11:58.000Z
|
2018-11-08T22:05:14.000Z
|
src/mirrage/net/src/server.cpp
|
lowkey42/mirrage
|
2527537989a548062d0bbca8370d063fc6b81a18
|
[
"MIT"
] | 1
|
2018-09-26T23:10:06.000Z
|
2018-09-26T23:10:06.000Z
|
#include <mirrage/net/server.hpp>
#include <mirrage/net/error.hpp>
#include <mirrage/utils/container_utils.hpp>
#include <enet/enet.h>
namespace mirrage::net {
Server_builder::Server_builder(Host_type type,
std::string hostname,
std::uint16_t port,
const Channel_definitions& channels)
: _type(type), _hostname(std::move(hostname)), _port(port), _channels(channels)
{
}
auto Server_builder::create() -> Server
{
return {_type,
_hostname,
_port,
_channels,
_max_clients,
_max_in_bandwidth,
_max_out_bandwidth,
_on_connect,
_on_disconnect};
}
namespace {
auto open_server_host(Server_builder::Host_type type,
const std::string& hostname,
std::uint16_t port,
std::size_t channel_count,
int max_clients,
int max_in_bandwidth,
int max_out_bandwidth)
{
ENetAddress address;
address.port = port;
switch(type) {
case Server_builder::Host_type::any: address.host = ENET_HOST_ANY; break;
case Server_builder::Host_type::broadcast:
#ifdef WIN32
address.host = ENET_HOST_ANY;
#else
address.host = ENET_HOST_BROADCAST;
#endif
break;
case Server_builder::Host_type::named:
auto ec = enet_address_set_host(&address, hostname.c_str());
if(ec != 0) {
const auto msg = "Couldn't resolve host \"" + hostname + "\".";
LOG(plog::warning) << msg;
throw std::system_error(Net_error::unknown_host, msg);
}
break;
}
auto host = enet_host_create(&address,
gsl::narrow<size_t>(max_clients),
channel_count,
gsl::narrow<enet_uint32>(max_in_bandwidth),
gsl::narrow<enet_uint32>(max_out_bandwidth));
if(!host) {
constexpr auto msg = "Couldn't create the host data structure (out of memory?)";
LOG(plog::warning) << msg;
throw std::system_error(Net_error::unspecified_network_error, msg);
}
return std::unique_ptr<ENetHost, void (*)(ENetHost*)>(host, &enet_host_destroy);
}
} // namespace
Server::Server(Server_builder::Host_type type,
const std::string& hostname,
std::uint16_t port,
const Channel_definitions& channels,
int max_clients,
int max_in_bandwidth,
int max_out_bandwidth,
Connected_callback on_connected,
Disconnected_callback on_disconnected)
: Connection(
open_server_host(
type, hostname, port, channels.size(), max_clients, max_in_bandwidth, max_out_bandwidth),
channels,
std::move(on_connected),
std::move(on_disconnected))
{
}
auto Server::broadcast_channel(util::Str_id channel) -> Channel
{
auto&& c = _channels.by_name(channel);
if(c.is_nothing()) {
const auto msg = "Unknown channel \"" + channel.str() + "\".";
LOG(plog::warning) << msg;
throw std::system_error(Net_error::unknown_channel, msg);
}
return Channel(_host.get(), c.get_or_throw());
}
auto Server::client_channel(util::Str_id channel, Client_handle client) -> Channel
{
auto&& c = _channels.by_name(channel);
if(c.is_nothing()) {
const auto msg = "Unknown channel \"" + channel.str() + "\".";
LOG(plog::warning) << msg;
throw std::system_error(Net_error::unknown_channel, msg);
}
return Channel(client, c.get_or_throw());
}
void Server::_on_connected(Client_handle client) { _clients.emplace_back(client); }
void Server::_on_disconnected(Client_handle client, std::uint32_t) { util::erase_fast(_clients, client); }
} // namespace mirrage::net
| 32.348837
| 108
| 0.565061
|
lowkey42
|
8ebee5f2aa9ebe853f989c65ce409b121fc4bd7a
| 8,870
|
hpp
|
C++
|
include/libndgpp/network_byte_order.hpp
|
goodfella/libndgpp
|
2e3d4b993a04664905c1e257fb2af3a5faab5296
|
[
"MIT"
] | null | null | null |
include/libndgpp/network_byte_order.hpp
|
goodfella/libndgpp
|
2e3d4b993a04664905c1e257fb2af3a5faab5296
|
[
"MIT"
] | null | null | null |
include/libndgpp/network_byte_order.hpp
|
goodfella/libndgpp
|
2e3d4b993a04664905c1e257fb2af3a5faab5296
|
[
"MIT"
] | null | null | null |
#ifndef LIBNDGPP_NETWORK_BYTE_ORDER_HPP
#define LIBNDGPP_NETWORK_BYTE_ORDER_HPP
#include <algorithm>
#include <array>
#include <cstring>
#include <type_traits>
#include <utility>
#include <ostream>
#include <libndgpp/network_byte_order_ops.hpp>
namespace ndgpp
{
/** Stores a native type value in network byte order
*
* The ndgpp::network_byte_order class is a regular type that
* will seemlessly represent a native type value in network byte
* order.
*
* @tparam T The native type i.e. uint16_t, uint32_t, uint64_t
*/
template <class T>
class network_byte_order
{
static_assert(std::is_integral<T>::value, "T is not an integral type");
static_assert(!std::is_signed<T>::value, "T is not unsigned");
public:
using value_type = T;
constexpr
network_byte_order() noexcept;
/** Constructs a network_byte_order instance with the specified value
*
* @param value An instance of type T in host byte order
*/
explicit
constexpr
network_byte_order(const T value) noexcept;
constexpr
network_byte_order(const network_byte_order & other) noexcept;
network_byte_order(network_byte_order && other) noexcept;
/** Assigns this to the value of rhs
*
* @param rhs An instance of type T in host byte order
*/
network_byte_order & operator= (const T rhs) noexcept;
network_byte_order & operator= (const network_byte_order & rhs) noexcept;
network_byte_order & operator= (network_byte_order && rhs) noexcept;
/// Returns the stored value in host byte order
constexpr
operator value_type () const noexcept;
/** Returns the address of the underlying value
*
* This is useful for sending the value over a socket:
*
* \code
* const int ret = send(&v, v.size());
*/
value_type const * operator &() const noexcept;
value_type * operator &() noexcept;
/// Returns the size of the underlying value
constexpr std::size_t size() const noexcept;
void swap(network_byte_order<T> & other) noexcept;
private:
value_type value_;
friend bool operator== <> (const network_byte_order<T>, const network_byte_order<T>);
friend bool operator!= <> (const network_byte_order<T>, const network_byte_order<T>);
friend bool operator< <> (const network_byte_order<T>, const network_byte_order<T>);
friend bool operator> <> (const network_byte_order<T>, const network_byte_order<T>);
friend bool operator<= <> (const network_byte_order<T>, const network_byte_order<T>);
friend bool operator>= <> (const network_byte_order<T>, const network_byte_order<T>);
};
template <class T>
inline
bool operator== (const network_byte_order<T> lhs,
const network_byte_order<T> rhs)
{
return lhs.value_ == rhs.value_;
}
template <class T>
inline
bool operator!= (const network_byte_order<T> lhs,
const network_byte_order<T> rhs)
{
return !(lhs == rhs);
}
template <class T>
inline
bool operator< (const network_byte_order<T> lhs,
const network_byte_order<T> rhs)
{
return lhs.value_ < rhs.value_;
}
template <class T>
inline
bool operator> (const network_byte_order<T> lhs,
const network_byte_order<T> rhs)
{
return rhs < lhs;
}
template <class T>
inline
bool operator<= (const network_byte_order<T> lhs,
const network_byte_order<T> rhs)
{
return !(rhs < lhs);
}
template <class T>
inline
bool operator>= (const network_byte_order<T> lhs,
const network_byte_order<T> rhs)
{
return !(lhs < rhs);
}
inline uint16_t host_to_network(const uint16_t val) noexcept
{
alignas(std::alignment_of<uint16_t>::value) std::array<uint8_t, 2> buf;
buf[0] = static_cast<uint8_t>((val & 0xff00) >> 8);
buf[1] = static_cast<uint8_t>((val & 0x00ff));
return *reinterpret_cast<uint16_t*>(buf.data());
}
inline uint32_t host_to_network(const uint32_t val) noexcept
{
alignas(std::alignment_of<uint32_t>::value) std::array<uint8_t, 4> buf;
buf[0] = static_cast<uint8_t>((val & 0xff000000) >> 24);
buf[1] = static_cast<uint8_t>((val & 0x00ff0000) >> 16);
buf[2] = static_cast<uint8_t>((val & 0x0000ff00) >> 8);
buf[3] = static_cast<uint8_t>((val & 0x000000ff));
return *reinterpret_cast<uint32_t*>(buf.data());
}
inline uint64_t host_to_network(const uint64_t val) noexcept
{
alignas(std::alignment_of<uint64_t>::value) std::array<uint8_t, 8> buf;
buf[0] = static_cast<uint8_t>((val & 0xff00000000000000) >> 56);
buf[1] = static_cast<uint8_t>((val & 0x00ff000000000000) >> 48);
buf[2] = static_cast<uint8_t>((val & 0x0000ff0000000000) >> 40);
buf[3] = static_cast<uint8_t>((val & 0x000000ff00000000) >> 32);
buf[4] = static_cast<uint8_t>((val & 0x00000000ff000000) >> 24);
buf[5] = static_cast<uint8_t>((val & 0x0000000000ff0000) >> 16);
buf[6] = static_cast<uint8_t>((val & 0x000000000000ff00) >> 8);
buf[7] = static_cast<uint8_t>((val & 0x00000000000000ff));
return *reinterpret_cast<uint64_t*>(buf.data());
}
inline uint16_t network_to_host(const uint16_t val)
{
std::array<uint8_t, 2> buf;
std::memcpy(buf.data(), &val, sizeof(val));
return
static_cast<uint16_t>(buf[0]) << 8 |
static_cast<uint16_t>(buf[1]);
}
inline uint32_t network_to_host(const uint32_t val) noexcept
{
std::array<uint8_t, 4> buf;
std::memcpy(buf.data(), &val, sizeof(val));
return
static_cast<uint32_t>(buf[0]) << 24 |
static_cast<uint32_t>(buf[1]) << 16 |
static_cast<uint32_t>(buf[2]) << 8 |
static_cast<uint32_t>(buf[3]);
}
inline uint64_t network_to_host(const uint64_t val) noexcept
{
std::array<uint8_t, 8> buf;
std::memcpy(buf.data(), &val, sizeof(val));
return
static_cast<uint64_t>(buf[0]) << 56 |
static_cast<uint64_t>(buf[1]) << 48 |
static_cast<uint64_t>(buf[2]) << 40 |
static_cast<uint64_t>(buf[3]) << 32 |
static_cast<uint64_t>(buf[4]) << 24 |
static_cast<uint64_t>(buf[5]) << 16 |
static_cast<uint64_t>(buf[6]) << 8 |
static_cast<uint64_t>(buf[7]);
}
template <class T>
void swap(network_byte_order<T> & lhs, network_byte_order<T> & rhs)
{
lhs.swap(rhs);
}
template <class T>
inline
std::ostream & operator <<(std::ostream & out, const network_byte_order<T> val)
{
out << static_cast<T>(val);
return out;
}
}
template <class T>
inline
constexpr
ndgpp::network_byte_order<T>::network_byte_order() noexcept = default;
template <class T>
inline
constexpr
ndgpp::network_byte_order<T>::network_byte_order(const ndgpp::network_byte_order<T>& other) noexcept = default;
template <class T>
inline
ndgpp::network_byte_order<T>::network_byte_order(ndgpp::network_byte_order<T>&& other) noexcept = default;
template <class T>
inline
ndgpp::network_byte_order<T> & ndgpp::network_byte_order<T>::operator= (const ndgpp::network_byte_order<T>& other) noexcept = default;
template <class T>
inline
ndgpp::network_byte_order<T> & ndgpp::network_byte_order<T>::operator= (ndgpp::network_byte_order<T>&& other) noexcept = default;
template <class T>
inline
constexpr
ndgpp::network_byte_order<T>::network_byte_order(const T value) noexcept:
value_(ndgpp::host_to_network(value))
{}
template <class T>
inline
ndgpp::network_byte_order<T> & ndgpp::network_byte_order<T>::operator= (const T value) noexcept
{
this->value_ = ndgpp::host_to_network(value);
return *this;
}
template <class T>
inline
constexpr
ndgpp::network_byte_order<T>::operator T() const noexcept
{
return ndgpp::network_to_host(this->value_);
}
template <class T>
inline
T const * ndgpp::network_byte_order<T>::operator &() const noexcept
{
return &this->value_;
}
template <class T>
inline
T * ndgpp::network_byte_order<T>::operator &() noexcept
{
return &this->value_;
}
template <class T>
inline
constexpr
std::size_t ndgpp::network_byte_order<T>::size() const noexcept
{
return sizeof(T);
}
template <class T>
inline
void ndgpp::network_byte_order<T>::swap(ndgpp::network_byte_order<T> & other) noexcept
{
std::swap(this->value_, other.value_);
}
#endif
| 29.966216
| 134
| 0.632131
|
goodfella
|
8ec65e548000a175fbe13b174fa34c2fce1336aa
| 116
|
cpp
|
C++
|
C++/KY/call.cpp
|
WhitePhosphorus4/xh-learning-code
|
025e31500d9f46d97ea634d7fd311c65052fd78e
|
[
"Apache-2.0"
] | null | null | null |
C++/KY/call.cpp
|
WhitePhosphorus4/xh-learning-code
|
025e31500d9f46d97ea634d7fd311c65052fd78e
|
[
"Apache-2.0"
] | null | null | null |
C++/KY/call.cpp
|
WhitePhosphorus4/xh-learning-code
|
025e31500d9f46d97ea634d7fd311c65052fd78e
|
[
"Apache-2.0"
] | null | null | null |
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
cout<<"hello world"<<endl;
return 0;
}
| 14.5
| 30
| 0.655172
|
WhitePhosphorus4
|
8ecca67a112fa7fab1224acf1833c07ebef08c75
| 2,361
|
cpp
|
C++
|
source/main-http.cpp
|
janjongboom/mbed-os-example-fota-http
|
20ef030aa95052a82c31c0eaece154dbc408de75
|
[
"MIT"
] | 6
|
2017-10-11T08:56:32.000Z
|
2022-02-24T14:09:30.000Z
|
source/main-http.cpp
|
janjongboom/mbed-os-example-fota-http
|
20ef030aa95052a82c31c0eaece154dbc408de75
|
[
"MIT"
] | 2
|
2017-08-28T16:08:36.000Z
|
2018-06-20T20:07:54.000Z
|
source/main-http.cpp
|
janjongboom/mbed-os-example-fota-http
|
20ef030aa95052a82c31c0eaece154dbc408de75
|
[
"MIT"
] | 5
|
2018-03-27T08:59:23.000Z
|
2022-01-26T21:08:50.000Z
|
#include "mbed.h"
#include "easy-connect.h"
#include "http_request.h"
#include "SDBlockDevice.h"
#include "FATFileSystem.h"
#define SD_MOUNT_PATH "sd"
#define FULL_UPDATE_FILE_PATH "/" SD_MOUNT_PATH "/" MBED_CONF_APP_UPDATE_FILE
//Pin order: MOSI, MISO, SCK, CS
SDBlockDevice sd(MBED_CONF_APP_SD_CARD_MOSI, MBED_CONF_APP_SD_CARD_MISO,
MBED_CONF_APP_SD_CARD_SCK, MBED_CONF_APP_SD_CARD_CS);
FATFileSystem fs(SD_MOUNT_PATH);
NetworkInterface* network;
EventQueue queue;
InterruptIn btn(SW0);
FILE* file;
size_t received = 0;
size_t received_packets = 0;
void store_fragment(const char* buffer, size_t size) {
fwrite(buffer, 1, size, file);
received += size;
received_packets++;
if (received_packets % 20 == 0) {
printf("Received %u bytes\n", received);
}
}
void check_for_update() {
btn.fall(NULL); // remove the button listener
file = fopen(FULL_UPDATE_FILE_PATH, "wb");
HttpRequest* req = new HttpRequest(network, HTTP_GET, "http://192.168.0.105:8000/update.bin", &store_fragment);
HttpResponse* res = req->send();
if (!res) {
printf("HttpRequest failed (error code %d)\n", req->get_error());
return;
}
printf("Done downloading: %d - %s\n", res->get_status_code(), res->get_status_message().c_str());
fclose(file);
delete req;
printf("Rebooting...\n\n");
NVIC_SystemReset();
}
DigitalOut led(LED1);
void blink_led() {
led = !led;
}
int main() {
printf("Hello from THE ORIGINAL application\n");
Thread eventThread;
eventThread.start(callback(&queue, &EventQueue::dispatch_forever));
queue.call_every(500, &blink_led);
btn.mode(PullUp); // PullUp mode on the ODIN W2 EVK
btn.fall(queue.event(&check_for_update));
int r;
if ((r = sd.init()) != 0) {
printf("Could not initialize SD driver (%d)\n", r);
return 1;
}
if ((r = fs.mount(&sd)) != 0) {
printf("Could not mount filesystem, is the SD card formatted as FAT? (%d)\n", r);
return 1;
}
// Connect to the network (see mbed_app.json for the connectivity method used)
network = easy_connect(true);
if (!network) {
printf("Cannot connect to the network, see serial output\n");
return 1;
}
printf("Press SW0 to check for update\n");
wait(osWaitForever);
}
| 25.117021
| 115
| 0.650148
|
janjongboom
|
8ecfa08d7f74ed2312be0182606f1b456a6efff4
| 17,900
|
cpp
|
C++
|
src/remotecommandhandler.cpp
|
hrxcodes/cbftp
|
bf2784007dcc4cc42775a2d40157c51b80383f81
|
[
"MIT"
] | 8
|
2019-04-30T00:37:00.000Z
|
2022-02-03T13:35:31.000Z
|
src/remotecommandhandler.cpp
|
Xtravaganz/cbftp
|
31a3465e2cd539f6cf35a5d9a0bb9c5c2f639cd5
|
[
"MIT"
] | 2
|
2019-11-19T12:46:13.000Z
|
2019-12-20T22:13:57.000Z
|
src/remotecommandhandler.cpp
|
Xtravaganz/cbftp
|
31a3465e2cd539f6cf35a5d9a0bb9c5c2f639cd5
|
[
"MIT"
] | 9
|
2020-01-15T02:38:36.000Z
|
2022-02-15T20:05:20.000Z
|
#include "remotecommandhandler.h"
#include <vector>
#include <list>
#include "core/tickpoke.h"
#include "core/iomanager.h"
#include "core/types.h"
#include "crypto.h"
#include "globalcontext.h"
#include "engine.h"
#include "eventlog.h"
#include "util.h"
#include "sitelogicmanager.h"
#include "sitelogic.h"
#include "uibase.h"
#include "sitemanager.h"
#include "site.h"
#include "race.h"
#include "localstorage.h"
#include "httpserver.h"
#define DEFAULT_PASS "DEFAULT"
#define RETRY_DELAY 30000
namespace {
enum RaceType {
RACE,
DISTRIBUTE,
PREPARE
};
std::list<std::shared_ptr<SiteLogic> > getSiteLogicList(const std::string & sitestring) {
std::list<std::shared_ptr<SiteLogic> > sitelogics;
std::list<std::string> sites;
if (sitestring == "*") {
std::vector<std::shared_ptr<Site> >::const_iterator it;
for (it = global->getSiteManager()->begin(); it != global->getSiteManager()->end(); it++) {
if (!(*it)->getDisabled()) {
sites.push_back((*it)->getName());
}
}
}
else {
sites = util::trim(util::split(sitestring, ","));
}
std::list<std::string> notfoundsites;
for (std::list<std::string>::const_iterator it = sites.begin(); it != sites.end(); it++) {
const std::shared_ptr<SiteLogic> sl = global->getSiteLogicManager()->getSiteLogic(*it);
if (!sl) {
notfoundsites.push_back(*it);
continue;
}
sitelogics.push_back(sl);
}
if (sitelogics.empty()) {
for (std::vector<std::shared_ptr<Site> >::const_iterator it = global->getSiteManager()->begin(); it != global->getSiteManager()->end(); ++it) {
if ((*it)->hasSection(sitestring) && !(*it)->getDisabled()) {
std::shared_ptr<SiteLogic> sl = global->getSiteLogicManager()->getSiteLogic((*it)->getName());
sitelogics.push_back(sl);
}
}
}
if (!notfoundsites.empty()) {
std::string notfound = util::join(notfoundsites, ",");
if (sites.size() == 1) {
global->getEventLog()->log("RemoteCommandHandler", "Site or section not found: " + notfound);
}
else {
global->getEventLog()->log("RemoteCommandHandler", "Sites not found: " + notfound);
}
}
return sitelogics;
}
bool useOrSectionTranslate(Path& path, const std::shared_ptr<Site>& site) {
if (path.isRelative()) {
path.level(0);
std::string section = path.level(0).toString();
if (site->hasSection(section)) {
path = site->getSectionPath(section) / path.cutLevels(-1);
}
else {
global->getEventLog()->log("RemoteCommandHandler", "Path must be absolute or a section name on " +
site->getName() + ": " + path.toString());
return false;
}
}
return true;
}
}
RemoteCommandHandler::RemoteCommandHandler() :
enabled(false),
encrypted(true),
password(DEFAULT_PASS),
port(DEFAULT_API_PORT),
retrying(false),
connected(false),
notify(RemoteCommandNotify::DISABLED) {
}
bool RemoteCommandHandler::isEnabled() const {
return enabled;
}
bool RemoteCommandHandler::isEncrypted() const {
return encrypted;
}
int RemoteCommandHandler::getUDPPort() const {
return port;
}
std::string RemoteCommandHandler::getPassword() const {
return password;
}
void RemoteCommandHandler::setPassword(const std::string & newpass) {
password = newpass;
}
void RemoteCommandHandler::setPort(int newport) {
bool reopen = !(port == newport || !enabled);
port = newport;
if (reopen) {
setEnabled(false);
setEnabled(true);
}
}
RemoteCommandNotify RemoteCommandHandler::getNotify() const {
return notify;
}
void RemoteCommandHandler::setNotify(RemoteCommandNotify notify) {
this->notify = notify;
}
void RemoteCommandHandler::connect() {
int udpport = getUDPPort();
sockid = global->getIOManager()->registerUDPServerSocket(this, udpport);
if (sockid >= 0) {
connected = true;
global->getEventLog()->log("RemoteCommandHandler", "Listening on UDP port " + std::to_string(udpport));
}
else {
int delay = RETRY_DELAY / 1000;
global->getEventLog()->log("RemoteCommandHandler", "Retrying in " + std::to_string(delay) + " seconds.");
retrying = true;
global->getTickPoke()->startPoke(this, "RemoteCommandHandler", RETRY_DELAY, 0);
}
}
void RemoteCommandHandler::FDData(int sockid, char * data, unsigned int datalen) {
std::string message;
if (encrypted) {
Core::BinaryData encrypted(datalen);
memcpy(encrypted.data(), data, datalen);
Core::BinaryData decrypted;
Core::BinaryData key(password.begin(), password.end());
Crypto::decrypt(encrypted, key, decrypted);
if (!Crypto::isMostlyASCII(decrypted)) {
global->getEventLog()->log("RemoteCommandHandler", "Received " + std::to_string(datalen) + " bytes of garbage or wrongly encrypted data");
return;
}
message = std::string(decrypted.begin(), decrypted.end());
}
else {
message = std::string(data, datalen);
}
handleMessage(message);
}
void RemoteCommandHandler::handleMessage(const std::string & message) {
std::string trimmedmessage = util::trim(message);
std::vector<std::string> tokens = util::splitVec(trimmedmessage);
if (tokens.size() < 2) {
global->getEventLog()->log("RemoteCommandHandler", "Bad message format: " + trimmedmessage);
return;
}
std::string & pass = tokens[0];
bool passok = pass == password;
if (passok) {
for (unsigned int i = 0; i < pass.length(); i++) {
pass[i] = '*';
}
}
global->getEventLog()->log("RemoteCommandHandler", "Received: " + util::join(tokens));
if (!passok) {
global->getEventLog()->log("RemoteCommandHandler", "Invalid password.");
return;
}
std::string command = tokens[1];
std::vector<std::string> remainder(tokens.begin() + 2, tokens.end());
bool notification = notify == RemoteCommandNotify::ALL_COMMANDS;
if (command == "race") {
bool started = commandRace(remainder);
if (started && notify >= RemoteCommandNotify::JOBS_ADDED) {
notification = true;
}
}
else if (command == "distribute") {
bool started = commandDistribute(remainder) && notify >= RemoteCommandNotify::JOBS_ADDED;
if (started && notify >= RemoteCommandNotify::JOBS_ADDED) {
notification = true;
}
}
else if (command == "prepare") {
bool created = commandPrepare(remainder);
if (created && notify >= RemoteCommandNotify::ACTION_REQUESTED) {
notification = true;
}
}
else if (command == "raw") {
commandRaw(remainder);
}
else if (command == "rawwithpath") {
commandRawWithPath(remainder);
}
else if (command == "fxp") {
bool started = commandFXP(remainder);
if (started && notify >= RemoteCommandNotify::JOBS_ADDED) {
notification = true;
}
}
else if (command == "download") {
bool started = commandDownload(remainder);
if (started && notify >= RemoteCommandNotify::JOBS_ADDED) {
notification = true;
}
}
else if (command == "upload") {
bool started = commandUpload(remainder);
if (started && notify >= RemoteCommandNotify::JOBS_ADDED) {
notification = true;
}
}
else if (command == "idle") {
commandIdle(remainder);
}
else if (command == "abort") {
commandAbort(remainder);
}
else if (command == "delete") {
commandDelete(remainder);
}
else if (command == "abortdeleteincomplete") {
commandAbortDeleteIncomplete(remainder);
}
else if(command == "reset") {
commandReset(remainder, false);
}
else if(command == "hardreset") {
commandReset(remainder, true);
}
else {
global->getEventLog()->log("RemoteCommandHandler", "Invalid remote command: " + util::join(tokens));
return;
}
if (notification) {
global->getUIBase()->notify();
}
}
bool RemoteCommandHandler::commandRace(const std::vector<std::string> & message) {
return parseRace(message, RACE);
}
bool RemoteCommandHandler::commandDistribute(const std::vector<std::string> & message) {
return parseRace(message, DISTRIBUTE);
}
bool RemoteCommandHandler::commandPrepare(const std::vector<std::string> & message) {
return parseRace(message, PREPARE);
}
void RemoteCommandHandler::commandRaw(const std::vector<std::string> & message) {
if (message.size() < 2) {
global->getEventLog()->log("RemoteCommandHandler", "Bad remote raw command format: " + util::join(message));
return;
}
std::string sitestring = message[0];
std::string rawcommand = util::join(std::vector<std::string>(message.begin() + 1, message.end()));
std::list<std::shared_ptr<SiteLogic> > sites = getSiteLogicList(sitestring);
for (std::list<std::shared_ptr<SiteLogic> >::const_iterator it = sites.begin(); it != sites.end(); it++) {
(*it)->requestRawCommand(nullptr, rawcommand);
}
}
void RemoteCommandHandler::commandRawWithPath(const std::vector<std::string> & message) {
if (message.size() < 3) {
global->getEventLog()->log("RemoteCommandHandler", "Bad remote rawwithpath command format: " + util::join(message));
return;
}
std::string sitestring = message[0];
std::string pathstr = message[1];
std::string rawcommand = util::join(std::vector<std::string>(message.begin() + 2, message.end()));
std::list<std::shared_ptr<SiteLogic> > sites = getSiteLogicList(sitestring);
for (std::list<std::shared_ptr<SiteLogic> >::const_iterator it = sites.begin(); it != sites.end(); it++) {
Path path(pathstr);
if (!useOrSectionTranslate(path, (*it)->getSite())) {
continue;
}
(*it)->requestRawCommand(nullptr, path, rawcommand);
}
}
bool RemoteCommandHandler::commandFXP(const std::vector<std::string> & message) {
if (message.size() < 5) {
global->getEventLog()->log("RemoteCommandHandler", "Bad remote fxp command format: " + util::join(message));
return false;
}
std::shared_ptr<SiteLogic> srcsl = global->getSiteLogicManager()->getSiteLogic(message[0]);
std::shared_ptr<SiteLogic> dstsl = global->getSiteLogicManager()->getSiteLogic(message[3]);
if (!srcsl) {
global->getEventLog()->log("RemoteCommandHandler", "Bad site name: " + message[0]);
return false;
}
if (!dstsl) {
global->getEventLog()->log("RemoteCommandHandler", "Bad site name: " + message[3]);
return false;
}
std::string dstfile = message.size() > 5 ? message[5] : message[2];
Path srcpath(message[1]);
if (!useOrSectionTranslate(srcpath, srcsl->getSite())) {
return false;
}
Path dstpath(message[4]);
if (!useOrSectionTranslate(dstpath, dstsl->getSite())) {
return false;
}
global->getEngine()->newTransferJobFXP(message[0], srcpath, message[2], message[3], dstpath, dstfile);
return true;
}
bool RemoteCommandHandler::commandDownload(const std::vector<std::string> & message) {
if (message.size() < 2) {
global->getEventLog()->log("RemoteCommandHandler", "Bad download command format: " + util::join(message));
return false;
}
std::shared_ptr<SiteLogic> srcsl = global->getSiteLogicManager()->getSiteLogic(message[0]);
if (!srcsl) {
global->getEventLog()->log("RemoteCommandHandler", "Bad site name: " + message[0]);
return false;
}
Path srcpath = message[1];
if (!useOrSectionTranslate(srcpath, srcsl->getSite())) {
return false;
}
std::string file = srcpath.baseName();
if (message.size() == 2) {
srcpath = srcpath.dirName();
}
else {
file = message[2];
}
global->getEngine()->newTransferJobDownload(message[0], srcpath, file, global->getLocalStorage()->getDownloadPath(), file);
return true;
}
bool RemoteCommandHandler::commandUpload(const std::vector<std::string> & message) {
if (message.size() < 3) {
global->getEventLog()->log("RemoteCommandHandler", "Bad upload command format: " + util::join(message));
return false;
}
Path srcpath = message[0];
std::string file = srcpath.baseName();
std::string dstsite;
Path dstpath;
if (message.size() == 3) {
srcpath = srcpath.dirName();
dstsite = message[1];
dstpath = message[2];
}
else {
file = message[1];
dstsite = message[2];
dstpath = message[3];
}
std::shared_ptr<SiteLogic> dstsl = global->getSiteLogicManager()->getSiteLogic(dstsite);
if (!dstsl) {
global->getEventLog()->log("RemoteCommandHandler", "Bad site name: " + dstsite);
return false;
}
if (!useOrSectionTranslate(dstpath, dstsl->getSite())) {
return false;
}
global->getEngine()->newTransferJobUpload(srcpath, file, dstsite, dstpath, file);
return true;
}
void RemoteCommandHandler::commandIdle(const std::vector<std::string> & message) {
if (message.empty()) {
global->getEventLog()->log("RemoteCommandHandler", "Bad idle command format: " + util::join(message));
return;
}
int idletime;
std::string sitestring;
if (message.size() < 2) {
sitestring = message[0];
idletime = 0;
}
else {
sitestring = message[0];
idletime = std::stoi(message[1]);
}
std::list<std::shared_ptr<SiteLogic> > sites = getSiteLogicList(sitestring);
for (std::list<std::shared_ptr<SiteLogic> >::const_iterator it = sites.begin(); it != sites.end(); it++) {
(*it)->requestAllIdle(nullptr, idletime);
}
}
void RemoteCommandHandler::commandAbort(const std::vector<std::string> & message) {
if (message.empty()) {
global->getEventLog()->log("RemoteCommandHandler", "Bad abort command format: " + util::join(message));
return;
}
std::shared_ptr<Race> race = global->getEngine()->getRace(message[0]);
if (!race) {
global->getEventLog()->log("RemoteCommandHandler", "No matching race: " + message[0]);
return;
}
global->getEngine()->abortRace(race);
}
void RemoteCommandHandler::commandDelete(const std::vector<std::string> & message) {
if (message.empty()) {
global->getEventLog()->log("RemoteCommandHandler", "Bad delete command format: " + util::join(message));
return;
}
std::string release = message[0];
std::string sitestring;
if (message.size() >= 2) {
sitestring = message[1];
}
std::shared_ptr<Race> race = global->getEngine()->getRace(release);
if (!race) {
global->getEventLog()->log("RemoteCommandHandler", "No matching race: " + release);
return;
}
if (!sitestring.length()) {
global->getEngine()->deleteOnAllSites(race, false, true);
return;
}
std::list<std::shared_ptr<SiteLogic> > sitelogics = getSiteLogicList(sitestring);
std::list<std::shared_ptr<Site> > sites;
for (std::list<std::shared_ptr<SiteLogic> >::const_iterator it = sitelogics.begin(); it != sitelogics.end(); it++) {
sites.push_back((*it)->getSite());
}
global->getEngine()->deleteOnSites(race, sites, false);
}
void RemoteCommandHandler::commandAbortDeleteIncomplete(const std::vector<std::string> & message) {
if (message.empty()) {
global->getEventLog()->log("RemoteCommandHandler", "Bad abortdeleteincomplete command format: " + util::join(message));
return;
}
std::string release = message[0];
std::shared_ptr<Race> race = global->getEngine()->getRace(release);
if (!race) {
global->getEventLog()->log("RemoteCommandHandler", "No matching race: " + release);
return;
}
global->getEngine()->deleteOnAllSites(race, false, false);
}
void RemoteCommandHandler::commandReset(const std::vector<std::string> & message, bool hard) {
if (message.empty()) {
global->getEventLog()->log("RemoteCommandHandler", "Bad reset command format: " + util::join(message));
return;
}
std::shared_ptr<Race> race = global->getEngine()->getRace(message[0]);
if (!race) {
global->getEventLog()->log("RemoteCommandHandler", "No matching race: " + message[0]);
return;
}
global->getEngine()->resetRace(race, hard);
}
bool RemoteCommandHandler::parseRace(const std::vector<std::string> & message, int type) {
if (message.size() < 3) {
global->getEventLog()->log("RemoteCommandHandler", "Bad remote race command format: " + util::join(message));
return false;
}
std::string section = message[0];
std::string release = message[1];
std::string sitestring = message[2];
std::list<std::string> sites;
if (sitestring == "*") {
for (std::vector<std::shared_ptr<Site> >::const_iterator it = global->getSiteManager()->begin(); it != global->getSiteManager()->end(); it++) {
if ((*it)->hasSection(section) && !(*it)->getDisabled()) {
sites.push_back((*it)->getName());
}
}
}
else {
sites = util::trim(util::split(sitestring, ","));
}
std::list<std::string> dlonlysites;
if (message.size() >= 4) {
std::string dlonlysitestring = message[3];
dlonlysites = util::trim(util::split(dlonlysitestring, ","));
}
if (type == RACE) {
return !!global->getEngine()->newRace(release, section, sites, false, dlonlysites);
}
else if (type == DISTRIBUTE){
return !!global->getEngine()->newDistribute(release, section, sites, false, dlonlysites);
}
else {
return global->getEngine()->prepareRace(release, section, sites, false, dlonlysites);
}
}
void RemoteCommandHandler::FDFail(int sockid, const std::string & message) {
global->getEventLog()->log("RemoteCommandHandler", "UDP binding on port " +
std::to_string(getUDPPort()) + " failed: " + message);
}
void RemoteCommandHandler::disconnect() {
if (connected) {
global->getIOManager()->closeSocket(sockid);
global->getEventLog()->log("RemoteCommandHandler", "Closing UDP socket");
connected = false;
}
}
void RemoteCommandHandler::setEnabled(bool enabled) {
if (this->enabled == enabled) {
return;
}
if (retrying) {
stopRetry();
}
if (enabled) {
connect();
}
else {
disconnect();
}
this->enabled = enabled;
}
void RemoteCommandHandler::setEncrypted(bool encrypted) {
this->encrypted = encrypted;
}
void RemoteCommandHandler::stopRetry() {
if (retrying) {
global->getTickPoke()->stopPoke(this, 0);
retrying = false;
}
}
void RemoteCommandHandler::tick(int) {
stopRetry();
if (enabled) {
connect();
}
}
| 31.458699
| 147
| 0.662011
|
hrxcodes
|
8ed04f1821a61c8d2ef1152f7dc235c1047a0bff
| 1,076
|
hpp
|
C++
|
lib/STL+/strings/string_hash.hpp
|
knela96/Game-Engine
|
06659d933c4447bd8d6c8536af292825ce4c2ab1
|
[
"Unlicense"
] | 3
|
2018-05-07T19:09:23.000Z
|
2019-05-03T14:19:38.000Z
|
deps/stlplus/strings/string_hash.hpp
|
evpo/libencryptmsg
|
fa1ea59c014c0a9ce339d7046642db4c80fc8701
|
[
"BSD-2-Clause-FreeBSD",
"BSD-3-Clause"
] | null | null | null |
deps/stlplus/strings/string_hash.hpp
|
evpo/libencryptmsg
|
fa1ea59c014c0a9ce339d7046642db4c80fc8701
|
[
"BSD-2-Clause-FreeBSD",
"BSD-3-Clause"
] | null | null | null |
#ifndef STLPLUS_STRING_HASH
#define STLPLUS_STRING_HASH
////////////////////////////////////////////////////////////////////////////////
// Author: Andy Rushton
// Copyright: (c) Southampton University 1999-2004
// (c) Andy Rushton 2004 onwards
// License: BSD License, see ../docs/license.html
// Generate a string representation of a hash
////////////////////////////////////////////////////////////////////////////////
#include "strings_fixes.hpp"
#include "hash.hpp"
#include <string>
////////////////////////////////////////////////////////////////////////////////
namespace stlplus
{
template<typename K, typename T, typename H, typename E, typename KS, typename TS>
std::string hash_to_string(const hash<K,T,H,E>& values,
KS key_to_string_fn,
TS value_to_string_fn,
const std::string& pair_separator = ":",
const std::string& separator = ",");
} // end namespace stlplus
#include "string_hash.tpp"
#endif
| 32.606061
| 84
| 0.47026
|
knela96
|
8ed0c0c06675abb85c55c453b94dfbcf52485e1f
| 10,646
|
hpp
|
C++
|
AeroKernel/parameter.hpp
|
brandonbraun653/AeroKernel
|
23a9a8da7a735ac2d5e1b5d7b59231b8a78a2fd9
|
[
"MIT"
] | null | null | null |
AeroKernel/parameter.hpp
|
brandonbraun653/AeroKernel
|
23a9a8da7a735ac2d5e1b5d7b59231b8a78a2fd9
|
[
"MIT"
] | 2
|
2019-05-04T13:39:41.000Z
|
2019-05-04T16:48:24.000Z
|
AeroKernel/parameter.hpp
|
brandonbraun653/AeroKernel
|
23a9a8da7a735ac2d5e1b5d7b59231b8a78a2fd9
|
[
"MIT"
] | null | null | null |
/********************************************************************************
* File Name:
* parameter.hpp
*
* Description:
* Implements the Aerospace Kernel Parameter Manager. This module allows a
* system to pass information around in a thread safe manner without the
* producers and consumers knowing implementation details of each other. The
* main benefit of this is decoupling of system modules so that different
* implementations can be swapped in/out without breaking the code. In its
* simplest form, this is just a glorified database.
*
* Usage Example:
* An AHRS (Attitude Heading and Reference System) module is producing raw
* 9-axis data from an IMU (Inertial Measurement Unit) containing gyroscope,
* accelerometer, and magnetometer data. Somehow this data needs to be filtered
* and transformed into a state estimation of a quadrotor, but the team wants to
* try out a couple of different algorithms. The mighty parameter manager is
* called upon as a buffer to safely abstract away the AHRS interface so that
* they only need to query the registered parameters for their latest data.
* The AHRS code will register itself with the Manager as a producer of data
* without knowing who will use it, and the state estimation code will consume
* the data without knowing who produced it. Decoupling of the two systems has
* been achieved! Hurray. Now the software engineers can rest easy knowing they
* can swap out the implementation of either side without breaking the code base.
*
* Requirements Documentation:
* Repository: https://github.com/brandonbraun653/AeroKernelDev
* Location: doc/requirements/parameter_manager.req
*
* 2019 | Brandon Braun | brandonbraun653@gmail.com
********************************************************************************/
#pragma once
#ifndef AERO_KERNEL_PARAMETER_MANAGER_HPP
#define AERO_KERNEL_PARAMETER_MANAGER_HPP
/* C++ Includes */
#include <cstdint>
#include <string>
#include <memory>
#include <functional>
/* Hash Map Include */
#include <sparsepp/spp.h>
/* Chimera Includes */
#include <Chimera/modules/memory/device.hpp>
#include <Chimera/threading.hpp>
namespace AeroKernel::Parameter
{
enum class StorageType : uint8_t
{
INTERNAL_SRAM,
INTERNAL_FLASH,
EXTERNAL_FLASH0,
EXTERNAL_FLASH1,
EXTERNAL_FLASH2,
EXTERNAL_SRAM0,
EXTERNAL_SRAM1,
EXTERNAL_SRAM2,
NONE,
MAX_STORAGE_OPTIONS = NONE
};
using UpdateCallback_t = std::function<bool( const std::string_view &key )>;
/**
* Data structure that fully describes a parameter that is stored
* somewhere in memory. This could be volatile or non-volatile
* memory, it does not matter. The actual data is not stored in
* this block, only the meta information describing it.
*
* @requirement PM002.2
*/
struct ControlBlock
{
/**
* The size of the data this control block describes.
*/
size_t size = std::numeric_limits<size_t>::max();
/**
* The address in memory the data should be stored at. Whether
* or not the address is valid is highly dependent upon the
* storage sink used.
*/
size_t address = std::numeric_limits<size_t>::max();
/**
* Configuration Options:
* Bits 0-2: Memory Storage Location, see MemoryLocation
*
* @requirement PM002.2.1, PM002.2.2, PM002.2.3
*/
size_t config = std::numeric_limits<size_t>::max();
/**
* Optional function that can be used by client applications
* to request an update of the parameter. This allows fresh
* data to be acquired on demand.
*
* @requirement PM002.3
*/
UpdateCallback_t update = nullptr;
};
using ParamCtrlBlk_sPtr = std::shared_ptr<ControlBlock>;
using ParamCtrlBlk_uPtr = std::unique_ptr<ControlBlock>;
/**
* A generator for the control block data structure. Currently
* it's quite simple, but the data type is likely to change in
* the future and necessitates a common interface.
*/
class ControlBlockFactory
{
public:
ControlBlockFactory();
~ControlBlockFactory();
/**
* Compiles all the current settings and returns the fully
* configured control block.
*
* @return AeroKernel::Parameter::ControlBlock
*/
ControlBlock build();
/**
* Clears all current settings and resets the factory to default
*
* @return void
*/
void clear();
/**
* Encodes the sizing information associated with the parameter this
* control block describes.
*
* @param[in] size The size of the parameter
* @return void
*/
void setSize( const size_t size );
/**
* Encodes the address information
*
* @param[in] address The address the parameter will be stored at in NVM
* @return void
*/
void setAddress( const size_t address );
/**
* Encodes the storage device for the actual parameter data
*
* @param[in] type Where the parameter data will be stored
* @return void
*/
void setStorage( const StorageType type );
/**
* Attaches an optional update function
*
* @param[in] callback The update function to attach
* @return void
*/
void setUpdateCallback( UpdateCallback_t callback );
private:
ControlBlock mold;
};
/**
* A static class that interprets the control block configuration
* and can return back non-encoded data. Currently this is just a
* simple wrapper, but the control block data structure may change
* in the future, necessitating a common interface.
*/
class ControlBlockInterpreter
{
public:
ControlBlockInterpreter() = default;
~ControlBlockInterpreter() = default;
static StorageType getStorage( const ControlBlock &ctrlBlk );
static size_t getAddress( const ControlBlock &ctrlBlk );
static size_t getSize( const ControlBlock &ctrlBlk );
static UpdateCallback_t getUpdateCallback( const ControlBlock &ctrlBlk );
};
/**
* Parameter Manager Implementation
*/
class Manager : public Chimera::Threading::Lockable
{
public:
/**
* Initialize the parameter manager instance
*
* @param[in] lockTimeout_mS How long to wait for the manager to be available
* @return Manager
*/
Manager( const size_t lockTimeout_mS = 50 );
~Manager();
/**
* Initializes the parameter manager to a default configuration and allocates
* the given number of parameters that can be actively registered. Ideally this
* is only performed once at startup and should not be called again to avoid
* dynamic memory allocation. If your system can handle that, then go wild.
*
* @requirement PM001
*
* @param[in] numParameters How many parameters can be managed by this class
* @return bool
*/
bool init( const size_t numParameters );
/**
* Registers a new parameter into the manager
*
* @requirement PM002, PM002.1
*
* @param[in] key The parameter's name
* @param[in] controlBlock Information describing where the parameter lives in memory
* @return bool
*/
bool registerParameter( const std::string_view &key, const ControlBlock &controlBlock );
/**
* Removes a parameter from the manager
*
* @requirement PM006
*
* @param[in] key The parameter's name
* @return bool
*/
bool unregisterParameter( const std::string_view &key );
/**
* Checks if the given parameter has been registered
*
* @requirement PM003
*
* @param[in] key The parameter's name
* @return bool
*/
bool isRegistered( const std::string_view &key );
/**
* Read the parameter data from wherever it has been stored
*
* @requirement PM004
*
* @param[in] key The parameter's name
* @param[in] param Where to place the read data
* @return bool
*/
bool read( const std::string_view &key, void *const param );
/**
* Write the parameter data to wherever it is stored
*
* @requirement PM005
*
* @param[in] key The parameter's name
* @param[in] param Where to write data from
* @return bool
*/
bool write( const std::string_view &key, const void *const param );
/**
* If registered, executes the parameter's update method
*
* @requirement PM0011
*
* @param[in] key The parameter's name
* @return bool
*/
bool update( const std::string_view &key );
/**
* Registers a memory sink with the manager backend
*
* @requirement PM010
*
* @param[in] storage The type of storage the driver represents as defined in the Location namespace
* @param[in] driver A fully configured instance of a memory driver
* @return bool
*/
bool registerMemoryDriver( const StorageType storage, Chimera::Modules::Memory::Device_sPtr &driver );
/**
* Allows the user to assign virtual memory specifications to a
* registered memory driver. This allows for partitioning the regions
* that the Parameter manager is allowed access to.
*
* @requirement PM009
*
* @param[in] storage The type of storage the driver represents as defined in the Location namespace
* @param[in] specs Memory configuration specs
* @return bool
*/
bool registerMemorySpecs( const StorageType storage, const Chimera::Modules::Memory::Descriptor &specs );
/**
* Gets the control block associated with a given parameter
*
* @requirement PM012
*
* @param[in] key The parameter's name
* @return const AeroKernel::Parameter::ParamCtrlBlk &
*/
const ControlBlock &getControlBlock( const std::string_view &key );
protected:
bool initialized;
size_t lockTimeout_mS;
spp::sparse_hash_map<std::string_view, ControlBlock> params;
std::array<Chimera::Modules::Memory::Device_sPtr, static_cast<size_t>( StorageType::MAX_STORAGE_OPTIONS )> memoryDriver;
std::array<Chimera::Modules::Memory::Descriptor, static_cast<size_t>( StorageType::MAX_STORAGE_OPTIONS )> memorySpecs;
};
using Manager_sPtr = std::shared_ptr<Manager>;
using Manager_uPtr = std::unique_ptr<Manager>;
} // namespace AeroKernel::Parameter
#endif /* !AERO_KERNEL_PARAMETER_MANAGER_HPP */
| 31.874251
| 124
| 0.652546
|
brandonbraun653
|
8ed99072c5824ac16f4a579bfc9832b3a4202f97
| 198
|
cpp
|
C++
|
qfb-messenger/src/network_reply_handler.cpp
|
NickCis/harbour-facebook-messenger
|
b2c2305fdcec27321893c3230bbd9e724773bd7d
|
[
"MIT"
] | 1
|
2015-05-05T22:45:11.000Z
|
2015-05-05T22:45:11.000Z
|
qfb-messenger/src/network_reply_handler.cpp
|
NickCis/harbour-facebook-messenger
|
b2c2305fdcec27321893c3230bbd9e724773bd7d
|
[
"MIT"
] | null | null | null |
qfb-messenger/src/network_reply_handler.cpp
|
NickCis/harbour-facebook-messenger
|
b2c2305fdcec27321893c3230bbd9e724773bd7d
|
[
"MIT"
] | null | null | null |
#include "network_reply_handler.h"
NetworkReplyHandler::NetworkReplyHandler(QNetworkReply* r) :
QObject(r),
reply(r)
{
connect(this->reply, SIGNAL(finished()), this, SLOT(replyFinished()));
}
| 18
| 71
| 0.737374
|
NickCis
|
8eda40c7ef81d7a9161be254020ec7fa33e68e6e
| 801
|
cpp
|
C++
|
HW1Submit/main.cpp
|
manamhr/ITP365
|
616ea8f4074e05fd26eb8ece712b2df6aa70111f
|
[
"MIT"
] | null | null | null |
HW1Submit/main.cpp
|
manamhr/ITP365
|
616ea8f4074e05fd26eb8ece712b2df6aa70111f
|
[
"MIT"
] | null | null | null |
HW1Submit/main.cpp
|
manamhr/ITP365
|
616ea8f4074e05fd26eb8ece712b2df6aa70111f
|
[
"MIT"
] | null | null | null |
// ITP 365 Spring 2017
// HW1 - Sieve of Eratosthenes
// Name: Mana Mehraein
// Email: mehraein@usc.edu
// Platform: Mac
#include <iostream>
#include "gwindow.h"
#include "sieve.h"
#include <string>
#include "vector.h"
#include "strlib.h"
int main(int argc, char** argv)
{
// Create a 500x500 window
GWindow gw(500, 500);
Vector<int> number;
Vector<NumberType> type;
// Call initVectors in main
initVectors (number, type);
// drawGrid
drawGrid(gw,number,type);
int index=2;
// loop to find prime numbers and composites
while (calcNextPrime(number, type, index)!=-1)
{
drawGrid(gw,number,type);
pause(1000.0);
index++;
}
return 0;
}
| 18.627907
| 51
| 0.561798
|
manamhr
|
8edd65aebe7ac2a9a4c04604b60008f586d0ae7b
| 239
|
hh
|
C++
|
mimosa/rpc/http-call.hh
|
abique/mimosa
|
42c0041b570b55a24c606a7da79c70c9933c07d4
|
[
"MIT"
] | 24
|
2015-01-19T16:38:24.000Z
|
2022-01-15T01:25:30.000Z
|
mimosa/rpc/http-call.hh
|
abique/mimosa
|
42c0041b570b55a24c606a7da79c70c9933c07d4
|
[
"MIT"
] | 2
|
2017-01-07T10:47:06.000Z
|
2018-01-16T07:19:57.000Z
|
mimosa/rpc/http-call.hh
|
abique/mimosa
|
42c0041b570b55a24c606a7da79c70c9933c07d4
|
[
"MIT"
] | 7
|
2015-01-19T16:38:31.000Z
|
2020-12-12T19:10:30.000Z
|
#pragma once
#include "json.hh"
namespace mimosa
{
namespace rpc
{
bool httpCall(const std::string &url,
const google::protobuf::Message &request,
google::protobuf::Message *response);
}
}
| 17.071429
| 57
| 0.589958
|
abique
|
8ede1878426df41d8ee00964ca039bddd4c4dd65
| 7,365
|
hpp
|
C++
|
src/vm/objects/function.hpp
|
mbeckem/tiro
|
b3d729fce46243f25119767c412c6db234c2d938
|
[
"MIT"
] | 10
|
2020-01-23T20:41:19.000Z
|
2021-12-28T20:24:44.000Z
|
src/vm/objects/function.hpp
|
mbeckem/tiro
|
b3d729fce46243f25119767c412c6db234c2d938
|
[
"MIT"
] | 22
|
2021-03-25T16:22:08.000Z
|
2022-03-17T12:50:38.000Z
|
src/vm/objects/function.hpp
|
mbeckem/tiro
|
b3d729fce46243f25119767c412c6db234c2d938
|
[
"MIT"
] | null | null | null |
#ifndef TIRO_VM_OBJECTS_FUNCTION_HPP
#define TIRO_VM_OBJECTS_FUNCTION_HPP
#include "common/adt/span.hpp"
#include "vm/handles/handle.hpp"
#include "vm/object_support/layout.hpp"
#include "vm/objects/value.hpp"
namespace tiro::vm {
/// Represents executable byte code, typically used to
/// represents the instructions within a function.
///
/// TODO: Need a bytecode validation routine.
/// TODO: Code should not be movable on the heap.
class Code final : public HeapValue {
public:
using Layout = BufferLayout<byte, alignof(byte)>;
static Code make(Context& ctx, Span<const byte> code);
explicit Code(Value v)
: HeapValue(v, DebugCheck<Code>()) {}
const byte* data();
size_t size();
Span<const byte> view() { return {data(), size()}; }
Layout* layout() const { return access_heap<Layout>(); }
};
/// Represents the table of exception handlers for a function.
class HandlerTable final : public HeapValue {
public:
struct Entry {
u32 from; // start pc (inclusive)
u32 to; // end pc (exclusive)
u32 target; // target pc
bool operator==(const Entry& other) const {
return from == other.from && to == other.to && target == other.target;
}
bool operator!=(const Entry& other) const { return !(*this == other); }
};
using Layout = BufferLayout<Entry, alignof(Entry)>;
/// Creates a new table with the given set of entries.
/// \pre `entries` must be sorted. The individual entries must not overlap.
static HandlerTable make(Context& ctx, Span<const Entry> entries);
explicit HandlerTable(Value v)
: HeapValue(v, DebugCheck<HandlerTable>()) {}
const Entry* data();
size_t size();
Span<const Entry> view() { return {data(), size()}; }
/// Returns the appropriate table entry for the given program counter.
/// Returns nullptr if no such entry exists.
const Entry* find_entry(u32 pc);
Layout* layout() const { return access_heap<Layout>(); }
};
/// Represents a function prototype.
///
/// Function prototypes contain the static properties of functions and are referenced
/// by the actual function instances. Function prototypes are a necessary implementation
/// detail because actual functions (i.e. with closures) share all static properties
/// but have different closure variables each.
class CodeFunctionTemplate final : public HeapValue {
private:
struct Payload {
u32 params;
u32 locals;
};
enum Slots {
NameSlot,
ModuleSlot,
CodeSlot,
HandlersSlot,
SlotCount_,
};
public:
using Layout = StaticLayout<StaticSlotsPiece<SlotCount_>, StaticPayloadPiece<Payload>>;
static CodeFunctionTemplate make(Context& ctx, Handle<String> name, Handle<Module> module,
u32 params, u32 locals, Span<const HandlerTable::Entry> handlers, Span<const byte> code);
explicit CodeFunctionTemplate(Value v)
: HeapValue(v, DebugCheck<CodeFunctionTemplate>()) {}
/// The name of the function.
String name();
/// The module the function belongs to.
Module module();
/// The executable byte code of this function.
Code code();
/// Exception handler table for this function.
Nullable<HandlerTable> handlers();
/// The (minimum) number of required parameters.
u32 params();
/// The number of local variables used by the function. These must be allocated
/// on the stack before the function may execute.
u32 locals();
Layout* layout() const { return access_heap<Layout>(); }
};
/// Represents captured variables from an upper scope captured by a nested function.
/// ClosureContexts point to their parent (or null if they are at the root).
class Environment final : public HeapValue {
private:
enum Slots {
ParentSlot,
SlotCount_,
};
public:
using Layout = FixedSlotsLayout<Value, StaticSlotsPiece<SlotCount_>>;
static Environment make(Context& ctx, size_t size, MaybeHandle<Environment> parent);
explicit Environment(Value v)
: HeapValue(v, DebugCheck<Environment>()) {}
Nullable<Environment> parent();
Value* data();
size_t size();
Span<Value> values() { return {data(), size()}; }
/// Reads the value at the specified index.
/// \pre `index() < size()`
Value get(size_t index);
/// Writes the value at the specified index.
/// \pre `index() < size()`
void set(size_t index, Value value);
// level == 0 -> return *this. Returns null in the unlikely case that the level is invalid.
Nullable<Environment> parent(size_t level);
Layout* layout() const { return access_heap<Layout>(); }
};
/// Represents a function value.
///
/// A function can be thought of a pair of a closure context and a function template:
///
/// - The function template contains the static properties (parameter declarations, bytecode, ...)
/// and is never null. All closure function that are constructed by the same function declaration
/// share a common function template instance.
/// - The closure context contains the captured variables bound to this function object
/// and can be null.
/// - The function combines the two.
///
/// Only the function type is exposed within the language.
class CodeFunction final : public HeapValue {
private:
enum Slots {
TmplSlot,
ClosureSlot,
SlotCount_,
};
public:
using Layout = StaticLayout<StaticSlotsPiece<SlotCount_>>;
static CodeFunction
make(Context& ctx, Handle<CodeFunctionTemplate> tmpl, MaybeHandle<Environment> closure);
explicit CodeFunction(Value v)
: HeapValue(v, DebugCheck<CodeFunction>()) {}
CodeFunctionTemplate tmpl();
Nullable<Environment> closure();
Layout* layout() const { return access_heap<Layout>(); }
};
/// A function where the first parameter ("this") has been bound
/// and will be automatically passed as the first argument
/// of the wrapped function.
class BoundMethod final : public HeapValue {
private:
enum Slots {
FunctionSlot,
ObjectSlot,
SlotCount_,
};
public:
using Layout = StaticLayout<StaticSlotsPiece<SlotCount_>>;
static BoundMethod make(Context& ctx, Handle<Value> function, Handle<Value> object);
explicit BoundMethod(Value v)
: HeapValue(v, DebugCheck<BoundMethod>()) {}
Value function();
Value object();
Layout* layout() const { return access_heap<Layout>(); }
};
/// For functions that rely on runtime magic, which is implemented in the
/// interpreter itself.
///
/// TODO: This class should eventually be replaced by
/// coroutine-style native functions, which are not available yet.
class MagicFunction final : public HeapValue {
public:
enum Which {
Catch,
};
private:
struct Data {
Which which;
};
public:
using Layout = StaticLayout<StaticPayloadPiece<Data>>;
static MagicFunction make(Context& ctx, Which which);
explicit MagicFunction(Value v)
: HeapValue(v, DebugCheck<MagicFunction>()) {}
Which which();
Layout* layout() const { return access_heap<Layout>(); }
};
std::string_view to_string(MagicFunction::Which);
} // namespace tiro::vm
TIRO_ENABLE_FREE_TO_STRING(tiro::vm::MagicFunction::Which);
#endif // TIRO_VM_OBJECTS_FUNCTION_HPP
| 29.22619
| 100
| 0.677529
|
mbeckem
|
8edf2cc62dde1c74a2e30859cf5d18206771b2eb
| 184
|
cpp
|
C++
|
judger/uoj_judger/tests/newer/answer14.cpp
|
contropist/uoj
|
114ebf690dcfb22ec899cbdc3d3cb77a30b46285
|
[
"MIT"
] | null | null | null |
judger/uoj_judger/tests/newer/answer14.cpp
|
contropist/uoj
|
114ebf690dcfb22ec899cbdc3d3cb77a30b46285
|
[
"MIT"
] | null | null | null |
judger/uoj_judger/tests/newer/answer14.cpp
|
contropist/uoj
|
114ebf690dcfb22ec899cbdc3d3cb77a30b46285
|
[
"MIT"
] | null | null | null |
#pragma GCC optimize ("O0")
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
for (int i = 0; i < (1 << 5); i++)
new int[1 << 20]();
return 0;
}
| 15.333333
| 38
| 0.538043
|
contropist
|
8ee250a474a297cfa9773bc8ee3176d49ab97767
| 1,935
|
cpp
|
C++
|
BasiliskII/src/BeOS/xpram_beos.cpp
|
jvernet/macemu
|
c616a0dae0f451fc15016765c896175fae3f46cf
|
[
"Intel",
"X11"
] | 940
|
2015-01-04T12:20:10.000Z
|
2022-03-29T12:35:27.000Z
|
BasiliskII/src/BeOS/xpram_beos.cpp
|
Seanpm2001-virtual-machines/macemu
|
c616a0dae0f451fc15016765c896175fae3f46cf
|
[
"Intel",
"X11"
] | 163
|
2015-02-10T09:08:10.000Z
|
2022-03-13T05:48:10.000Z
|
BasiliskII/src/BeOS/xpram_beos.cpp
|
Seanpm2001-virtual-machines/macemu
|
c616a0dae0f451fc15016765c896175fae3f46cf
|
[
"Intel",
"X11"
] | 188
|
2015-01-07T19:46:11.000Z
|
2022-03-26T19:06:00.000Z
|
/*
* xpram_beos.cpp - XPRAM handling, BeOS specific stuff
*
* Basilisk II (C) 1997-2008 Christian Bauer
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <StorageKit.h>
#include <unistd.h>
#include "sysdeps.h"
#include "xpram.h"
// XPRAM file name and path
#if POWERPC_ROM
const char XPRAM_FILE_NAME[] = "SheepShaver_NVRAM";
#else
const char XPRAM_FILE_NAME[] = "BasiliskII_XPRAM";
#endif
static BPath xpram_path;
/*
* Load XPRAM from settings file
*/
void LoadXPRAM(const char *vmdir)
{
// Construct XPRAM path
find_directory(B_USER_SETTINGS_DIRECTORY, &xpram_path, true);
xpram_path.Append(XPRAM_FILE_NAME);
// Load XPRAM from settings file
int fd;
if ((fd = open(xpram_path.Path(), O_RDONLY)) >= 0) {
read(fd, XPRAM, XPRAM_SIZE);
close(fd);
}
}
/*
* Save XPRAM to settings file
*/
void SaveXPRAM(void)
{
if (xpram_path.InitCheck() != B_NO_ERROR)
return;
int fd;
if ((fd = open(xpram_path.Path(), O_WRONLY | O_CREAT, 0666)) >= 0) {
write(fd, XPRAM, XPRAM_SIZE);
close(fd);
}
}
/*
* Delete PRAM file
*/
void ZapPRAM(void)
{
// Construct PRAM path
find_directory(B_USER_SETTINGS_DIRECTORY, &xpram_path, true);
xpram_path.Append(XPRAM_FILE_NAME);
// Delete file
unlink(xpram_path.Path());
}
| 22.764706
| 77
| 0.710078
|
jvernet
|
8ee65978c71f54b000ca8db80dcf15b9bcd191ff
| 11,443
|
cpp
|
C++
|
jmax/Window.cpp
|
JeanGamain/jmax
|
1d4aee47c7fad25b9c4d9a678b84c5f4aad98c04
|
[
"MIT"
] | null | null | null |
jmax/Window.cpp
|
JeanGamain/jmax
|
1d4aee47c7fad25b9c4d9a678b84c5f4aad98c04
|
[
"MIT"
] | null | null | null |
jmax/Window.cpp
|
JeanGamain/jmax
|
1d4aee47c7fad25b9c4d9a678b84c5f4aad98c04
|
[
"MIT"
] | null | null | null |
#include "Window.hpp"
#include "jmax.hpp"
#include "math.h"
#include "shader/Shader.hpp"
#include <map>
#include <stdexcept>
#include <string>
#include <utility>
namespace jmax {
Window::Window(unsigned int width, unsigned int height)
: view(width, height)
, _windowIO()
, _resizeAction(
std::string("window_resize"), std::string("Resize window image buffer"), IO_INPUT_FWINDOW, actionResizeWindow)
, _fileDropAction(
std::string("window_filedrop"),
std::string("Process files drag&drop as new model to import"),
IO_INPUT_FWINDOW,
actionFileDropImport)
, _renderTimer()
, _background(NULL)
, _somvp("omvp")
, _sgCameraLocalPos("gCameraLocalPos")
, _globalLight(vec3(0.6f))
, _simpleUniDirectLight(vec3(0.0f, -1.0f, 0.15f), vec3(0.4f))
, _materialUniform(Material::getUniform())
, _simpleUniDirectLightUniform(UniDirectionalLight::getUniform())
, _mainShaderProg(NULL)
, _guiShaderProg(NULL)
, _mainVs(NULL)
, _mainFs(NULL)
, _maxFps(0)
, _vsync(true)
, _fps(0)
// GUI stuff
, _guiInit(false)
, _guiEnable(false)
, _modelPickerEnable(false)
, _selectionBuffer(0)
, _selectionIds{0}
, _selectedModel(NULL)
, _selectedMaterialId(0)
, _guiFpsStats()
, _guiFs(NULL)
{
const char* error;
if ((error = jmax::init()) != NULL) {
throw new std::runtime_error(error);
}
initRender(width, height, "JMAX");
setupRenderSettings();
initInputBind();
setupSceneRender();
setMaxFps(222);
}
Window::~Window()
{
delete _materialUniform;
delete _simpleUniDirectLightUniform;
disableBackgroundSurface();
for (jmax::Model* model : _models) {
delete model;
}
if (_mainShaderProg) delete _mainShaderProg;
if (_guiShaderProg) delete _guiShaderProg;
if (_mainVs) delete _mainVs;
if (_mainFs) delete _mainFs;
// UI
if (_guiFs) delete _guiFs;
if (_guiInit) gui::deleteUI();
glfwDestroyWindow(_window);
glfwTerminate();
}
void Window::initRender(unsigned int width, unsigned height, char* windowsTitle)
{
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, true); // DEBUG
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, JMAX_GLVERSION_MAJOR);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, JMAX_GLVERSION_MINOR);
glfwWindowHint(GLFW_OPENGL_PROFILE, JMAX_GLVERSION_TYPE);
const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor());
glfwWindowHint(GLFW_RED_BITS, mode->redBits);
glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits);
glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits);
glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate);
if (!(_window = glfwCreateWindow(width, height, windowsTitle, NULL, NULL))) {
fprintf(stderr, "Error glfwCreateWindow()");
}
glfwMakeContextCurrent(_window);
glfwSwapInterval(_vsync ? 1 : 0);
jmax::setGLDebug();
}
void Window::setClearColor(vec4 color)
{
GLclampf Red = color.x, Green = color.y, Blue = color.z, Alpha = color.w;
glClearColor(Red, Green, Blue, Alpha);
}
void Window::setupRenderSettings()
{
setClearColor();
glEnable(GL_CULL_FACE);
/*
glFrontFace(GL_CW);
glCullFace(GL_BACK);
*/
glFrontFace(GL_CW);
glCullFace(GL_FRONT);
glEnable(GL_MULTISAMPLE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// GUI model/material picker
glGenBuffers(1, &_selectionBuffer);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, _selectionBuffer);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, _selectionBuffer);
glBufferStorage(GL_SHADER_STORAGE_BUFFER, sizeof(_selectionIds), &_selectionIds[0], GL_MAP_READ_BIT);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
}
void Window::setupSceneRender()
{
_mainVs = new Shader("../jmax/shader/shader.vs");
_mainFs = new Shader("../jmax/shader/shader.fs");
_guiFs = new Shader("../jmax/shader/gui_shader.fs");
_mainShaderProg = new jmax::ShaderProgram({_mainVs, _mainFs});
_guiShaderProg = new jmax::ShaderProgram({_mainVs, _guiFs});
_mainShaderProg->enable();
_scene.scale = vec3(1.0f);
_scene.position = vec3(0.0f, 0.0f, 2.0f);
_scene.rotation = vec3(0.0f, 0.01f, 0.0f);
}
void Window::initInputBind()
{
_input = new IO::InputActionManager(_window, this);
_input->addInput(&_windowIO);
_windowIO.bindAction(&_resizeAction, jmax::IO::WindowEvent(IO::WindowEvent::RESIZE));
_windowIO.bindAction(&_fileDropAction, jmax::IO::WindowEvent(IO::WindowEvent::FILEDROP));
}
void Window::render()
{
makeCurrent();
applyFpsControls();
_input->sync(1);
_renderTimer.reset();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
mat4 omvp;
mat4 mprojection = view.getProjection();
mat4 mview = view.getView();
mat4 mmodel = _scene.getMatrix();
mat4 mvp = mprojection * mview * mmodel;
view.bindUniform();
vec4 camLocPos =
_scene.getReversedRotationMatrix() * _scene.getReversedTranslationMatrix() * vec4(view.getPosition(), 1.0f);
glUniform3f(_sgCameraLocalPos(), camLocPos.x, camLocPos.y, camLocPos.z);
if (_background) {
_background->render(_somvp, _materialUniform);
}
glEnable(GL_DEPTH_TEST);
for (jmax::Model* model : _models) {
// sun
_simpleUniDirectLight.calcDirection(mmodel * mat4(mat3(model->getTransformation())));
_simpleUniDirectLight.bind(_simpleUniDirectLightUniform);
// global light
_globalLight.bind();
omvp = mvp * model->getTransformation();
glUniformMatrix4fv(_somvp(), 1, GL_FALSE, glm::value_ptr(omvp));
model->render(_materialUniform);
}
glDisable(GL_DEPTH_TEST);
renderGUI();
}
void Window::renderGUI()
{
gui::fpsStatsCalc(&_guiFpsStats, glfwGetTime(), _fps);
if (!_guiEnable || !_guiInit) {
return;
}
gui::newFrame();
ImGui::Begin("JMAX");
if (ImGui::CollapsingHeader("Render")) {
gui::LabelText("Render", "%s", (const char*)glGetString(GL_RENDERER));
gui::LabelText("Version", "%s", (const char*)glGetString(GL_VERSION));
gui::fpsStatsHistogram(&_guiFpsStats);
ImGui::Separator();
gui::Label("Vsync");
if (gui::ToggleSwitchBool(&_vsync)) {
setVSync(_vsync, true);
}
gui::SliderFloat("MAX", &_maxFps, 0.0f, _maxFpsMax, "%.1f fps");
}
if (ImGui::CollapsingHeader("Scene")) {
static_cast<Entity3d&>(_scene).drawUI();
if (ImGui::TreeNode("Light")) {
_globalLight.drawUI();
_simpleUniDirectLight.drawUI();
ImGui::TreePop();
}
if (ImGui::TreeNode("Background")) {
_background->drawUI();
ImGui::TreePop();
}
}
if (ImGui::CollapsingHeader("Camera")) {
view.drawUI();
}
if (ImGui::CollapsingHeader("Model")) {
gui::Label("Model picker");
if (gui::ToggleSwitchBool(&_modelPickerEnable) && !_modelPickerEnable) {
_selectedMaterialId = 0;
}
if (_modelPickerEnable) {
glBindBuffer(GL_SHADER_STORAGE_BUFFER, _selectionBuffer);
glGetBufferSubData(GL_SHADER_STORAGE_BUFFER, 0, sizeof(_selectionIds), &_selectionIds[0]);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
_selectedModel = getModel(_selectionIds[0]);
_selectedMaterialId = _selectionIds[1];
}
gui::Label("Model");
const char* current_item = _selectedModel ? _selectedModel->getName().c_str() : NULL;
ImGui::PushItemWidth(ImGui::CalcItemWidth());
if (ImGui::BeginCombo("##Model combo", current_item)) {
int n = 0;
for (jmax::Model* model : _models) {
const char* item = model->getName().c_str();
bool is_selected = (current_item == item);
if (ImGui::Selectable(item, is_selected)) {
_selectedModel = model;
_selectedMaterialId = 0;
_modelPickerEnable = false;
}
if (is_selected) ImGui::SetItemDefaultFocus();
++n;
}
ImGui::EndCombo();
}
ImGui::PopItemWidth();
if (_selectedModel) {
_selectedModel->drawUI(_selectedMaterialId);
}
}
ImGui::End();
gui::render();
}
void Window::swapBuffer()
{
glfwSwapBuffers(_window);
}
void Window::renderLoop()
{
while (!shouldClose()) {
render();
swapBuffer();
pollEvents();
}
}
Model* Window::getModel(unsigned int id) const
{
if (id < 1) {
return NULL;
}
for (jmax::Model* model : _models) {
if (model->id == id) {
return model;
}
}
return NULL;
}
double Window::getDelta()
{
return _renderTimer();
}
float Window::getfDelta()
{
return (float)_renderTimer();
}
void Window::setVSync(bool enable, bool force)
{
if (_vsync == enable && !force) {
return;
}
_vsync = enable;
glfwSwapInterval(_vsync ? 1 : 0);
// ifdef WIN32
/* if (wglSwapIntervalEXT != nullptr) {
_vsync = enable;
if (enable) {
wglSwapIntervalEXT(1);
} else {
wglSwapIntervalEXT(0);
}
} else {
_vsync = false;
}
*/
}
bool Window::getVSync()
{
bool vsyncEnable = _vsync;
/*
if (wglGetSwapIntervalEXT != nullptr) {
vsyncEnable = wglGetSwapIntervalEXT() > 0;
}*/
return vsyncEnable;
}
void Window::makeCurrent()
{
glfwMakeContextCurrent(_window);
}
bool Window::shouldClose() const
{
return glfwWindowShouldClose(_window);
}
void Window::pollEvents()
{
glfwPollEvents();
}
void Window::enableBackgroundSurface(Texture* surfacePath)
{
if (!_background) {
makeCurrent();
_background = new BackgroundSurface(surfacePath);
}
}
void Window::disableBackgroundSurface()
{
if (_background) {
delete _background;
_background = NULL;
}
}
Model* Window::addModel(const char* modelPath)
{
const char* error;
printf("Adding model \"%s\"\n", modelPath);
makeCurrent();
Model* newObject = new Model();
if ((error = newObject->import(modelPath)) != NULL) {
printf("%s", error);
delete newObject;
return NULL;
}
_models.push_back(newObject);
// delete newObject;
return newObject;
}
void Window::setMaxFps(float fps)
{
_maxFps = (fps < _maxFpsMin || fps > _maxFpsMax) ? 0.0f : fps;
}
void Window::applyFpsControls()
{
double time = _renderTimer.getSecond();
if (_maxFps > 0.0f) {
double minTime = 1;
minTime /= _maxFps;
while (minTime > time) {
// glfwPollEvents();
time = _renderTimer.getSecond();
}
}
_fps = static_cast<float>(1. / time);
}
IO::InputActionManager* Window::getInputManager()
{
return _input;
}
void Window::setGuiEnable(bool enable)
{
_guiEnable = enable;
if (_guiEnable) {
if (!_guiInit) {
gui::newUI(_window);
_guiInit = true;
}
_guiShaderProg->enable();
} else {
_mainShaderProg->enable();
}
}
bool Window::getGuiEnable() const
{
return _guiEnable;
}
void Window::actionResizeWindow(Window* window, IO::IInput* input, void* userContext)
{
IO::Window* windowIO = (IO::Window*)input;
ivec2 size = windowIO->getResizeData();
if (size.x == 0 || size.y == 0) {
return;
}
window->makeCurrent();
// glfwGetFramebufferSize(me->window, &size.x, &size.y);
window->view.resize(size.x, size.y);
glViewport(0, 0, size.x, size.y);
}
/*
void Engine::hRefresh(GLFWwindow* window)
{
Engine* me = (Engine*)jmax::IO::InputActionManager::getAppContext(window);
me->render();
}
*/
void Window::actionFileDropImport(Window* window, IO::IInput* input, void* userContext)
{
IO::Window* windowIO = (IO::Window*)input;
const std::list<std::string>& files = windowIO->getFileDropsData();
for (auto const& file : files) {
window->addModel(file.c_str());
}
windowIO->clearFileDropsData();
}
} // namespace jmax
| 24.450855
| 120
| 0.672289
|
JeanGamain
|
8ee690a8f8a24b61111ea21d5c0190700cbe681f
| 955
|
hpp
|
C++
|
include/cores/pdump_log.hpp
|
dotcom/QDPDK
|
9f430f9b0cef36228d14f763a023d0ff13f6a8a8
|
[
"MIT"
] | 1
|
2022-02-17T03:56:57.000Z
|
2022-02-17T03:56:57.000Z
|
include/cores/pdump_log.hpp
|
dotcom/QDPDK
|
9f430f9b0cef36228d14f763a023d0ff13f6a8a8
|
[
"MIT"
] | null | null | null |
include/cores/pdump_log.hpp
|
dotcom/QDPDK
|
9f430f9b0cef36228d14f763a023d0ff13f6a8a8
|
[
"MIT"
] | null | null | null |
#pragma once
#include "qdpdk.hpp"
#define BURST_SIZE 32
template<class FROM, class TO>
class CorePdumpLog{
protected:
QDPDK::DeqInterface<FROM> from;
QDPDK::EnqInterface<TO> to;
public:
CorePdumpLog(FROM deq, TO enq) : from(deq), to(enq){};
void FirstCycle(){}
void LastCycle(){}
void Cycle() {
rte_mbuf *bufs[BURST_SIZE];
int nb_rx = from.Dequeue((rte_mbuf **)bufs, BURST_SIZE);
if (unlikely(nb_rx == 0))
return;
for (int n = 0; n < nb_rx; n++){
int len = bufs[n]->data_len;
auto pkt = rte_pktmbuf_mtod(bufs[n], char*);
char str[ETHER_MAX_LEN*5] = "";
for (int i=0;i<len;i++){
sprintf(str, "%s 0x%02x", str, 0x000000ff & pkt[i]);
}
rte_log(RTE_LOG_INFO, RTE_LOGTYPE_USER3, "==== PDUMP LOG ==== %u\n %s\n", rte_lcore_id(), str);
}
to.Enqueue((rte_mbuf **)bufs, nb_rx);
}
};
| 27.285714
| 107
| 0.548691
|
dotcom
|
8ee6c42df047eec64719e4e26ad5122ca0b407fd
| 2,541
|
cpp
|
C++
|
morse/DotNet/D3DVisualizator/DisplayableCoordinateSystem.cpp
|
jonnyzzz/phd-project
|
beab8615585bd52ef9ee1c19d1557e8c933c047a
|
[
"Apache-2.0"
] | 1
|
2019-12-24T15:52:45.000Z
|
2019-12-24T15:52:45.000Z
|
morse/DotNet/D3DVisualizator/DisplayableCoordinateSystem.cpp
|
jonnyzzz/phd-project
|
beab8615585bd52ef9ee1c19d1557e8c933c047a
|
[
"Apache-2.0"
] | null | null | null |
morse/DotNet/D3DVisualizator/DisplayableCoordinateSystem.cpp
|
jonnyzzz/phd-project
|
beab8615585bd52ef9ee1c19d1557e8c933c047a
|
[
"Apache-2.0"
] | null | null | null |
#include "StdAfx.h"
#include ".\displayablecoordinatesystem.h"
const DWORD DisplayableCoordinateSystem::POINTVERTEX::FVF = D3DFVF_XYZ | D3DFVF_DIFFUSE;
DisplayableCoordinateSystem::DisplayableCoordinateSystem(void)
{
vb = NULL;
axisColor[0] = 0xff0000;
axisColor[1] = 0x00ff00;
axisColor[2] = 0x0000ff;
}
DisplayableCoordinateSystem::~DisplayableCoordinateSystem(void)
{
Dispose();
}
HRESULT DisplayableCoordinateSystem::Create(LPDIRECT3DDEVICE8 d3d_device, D3DXVECTOR3 x[3]) {
this->x[0] = x[0];
this->x[1] = x[1];
this->x[2] = x[2];
this->d3d_device = d3d_device;
return CreateVertexBuffer();
}
void DisplayableCoordinateSystem::Dispose() {
if (vb != NULL) {
vb->Release();
}
}
/////////////////////////////////////////////////////////////////////////////////////
HRESULT DisplayableCoordinateSystem::Render() {
HRESULT hr = initDevice();
if (FAILED(hr)) return hr;
hr = render();
if (FAILED(hr)) return hr;
return S_OK;
}
HRESULT DisplayableCoordinateSystem::initDevice() {
HRESULT hr;
hr = d3d_device->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );
if (FAILED(hr)) return hr;
hr = d3d_device->SetRenderState( D3DRS_LIGHTING, FALSE );
if (FAILED(hr)) return hr;
return S_OK;
}
HRESULT DisplayableCoordinateSystem::render() {
HRESULT hr;
printf("Coordinated Render Started\n");
hr = d3d_device->SetStreamSource(0, vb, sizeof(POINTVERTEX));
if (FAILED(hr)) return hr;
hr = d3d_device->SetVertexShader(POINTVERTEX::FVF);
if (FAILED(hr)) return hr;
hr = d3d_device->DrawPrimitive(D3DPT_LINELIST, 0, 3);
if (FAILED(hr)) return hr;
return S_OK;
}
///////////////////////////////////////////////////////////////////////////////////
HRESULT DisplayableCoordinateSystem::CreateVertexBuffer() {
const int factor = 6;
HRESULT hr;
POINTVERTEX* pv = NULL;
hr = d3d_device->CreateVertexBuffer( factor * sizeof(POINTVERTEX),
D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY | D3DUSAGE_POINTS,
POINTVERTEX::FVF, D3DPOOL_DEFAULT, &vb );
if (FAILED(hr)) {
printf("Creation Failed: Parameters Of Creation: number = %d\n", factor);
return hr;
}
hr = vb->Lock( 0, factor * sizeof(POINTVERTEX),
(BYTE**) &pv, D3DLOCK_DISCARD );
if (FAILED(hr)) {
printf("Failed to create Lock created VertexBuffer\n");
vb->Release();
vb = NULL;
return hr;
}
for (int i=0; i<3; i++) {
pv->v = D3DXVECTOR3(0.0f, 0.0f, 0.0f);
pv->color = axisColor[i];
pv++;
pv->v = D3DXVECTOR3(x[i][0], x[i][1], x[i][2])*100;
pv->color = axisColor[i];
pv++;
}
hr = vb->Unlock();
return hr;
}
| 21.717949
| 93
| 0.645415
|
jonnyzzz
|
8ee818419c7f2148571b8a8d244209147662bd80
| 749
|
cc
|
C++
|
Source/VM/Source/instruction.cc
|
DylanEHolland/liz
|
50f030896fcca272d4e0f2186e84896d7b93ca40
|
[
"BSD-3-Clause"
] | null | null | null |
Source/VM/Source/instruction.cc
|
DylanEHolland/liz
|
50f030896fcca272d4e0f2186e84896d7b93ca40
|
[
"BSD-3-Clause"
] | 1
|
2022-02-21T04:58:44.000Z
|
2022-02-21T05:14:14.000Z
|
Source/VM/Source/instruction.cc
|
DylanEHolland/liz
|
50f030896fcca272d4e0f2186e84896d7b93ca40
|
[
"BSD-3-Clause"
] | null | null | null |
/**
* @file instruction.cc
* @author Dylan E. Holland (salinson1138@gmail.com)
* @brief
* @version 0.1
* @date 2022-03-16
*
* @copyright Copyright (c) 2022
*
*/
#include <VM/Include/instruction.h>
#include <Common/Include/output.h>
namespace liz::vm {
Instruction::Instruction() {
}
Instruction::~Instruction() {
}
void Instruction::toByteCode() {
}
void Instruction::fromIntermediate(struct intermediateInstruction *ins) {
//ins->opcode
}
class Instruction *fromByteCodeInstruction() {
class Instruction *buffer = new Instruction();
return buffer;
}
void intermediateInstructionToBytes(struct intermediateInstruction *ins) {
}
}
| 18.268293
| 78
| 0.624833
|
DylanEHolland
|
8eebfa9caf8a5e3d6fecfa5e877de0fd423374bd
| 224
|
cpp
|
C++
|
core/src/task/semaphore.cpp
|
ExaBerries/spruce
|
85845244f7d6cd5a662f0dbc9b4079a1230d9a4b
|
[
"MIT"
] | null | null | null |
core/src/task/semaphore.cpp
|
ExaBerries/spruce
|
85845244f7d6cd5a662f0dbc9b4079a1230d9a4b
|
[
"MIT"
] | null | null | null |
core/src/task/semaphore.cpp
|
ExaBerries/spruce
|
85845244f7d6cd5a662f0dbc9b4079a1230d9a4b
|
[
"MIT"
] | null | null | null |
#include <task/semaphore.h>
namespace spruce {
void semaphore::lock() noexcept {
locked = true;
}
void semaphore::unlock() noexcept {
locked = false;
}
void semaphore::wait() noexcept {
while (locked) {};
}
}
| 14
| 36
| 0.647321
|
ExaBerries
|
8ef370a2a057895eb2c6f29c4b72e2fbe7035c89
| 109
|
cpp
|
C++
|
src/add.cpp
|
JacknJo/JacksHome
|
b1b2d0d7683eb1a8adcfdd02380c6b620e567fe2
|
[
"MIT"
] | null | null | null |
src/add.cpp
|
JacknJo/JacksHome
|
b1b2d0d7683eb1a8adcfdd02380c6b620e567fe2
|
[
"MIT"
] | null | null | null |
src/add.cpp
|
JacknJo/JacksHome
|
b1b2d0d7683eb1a8adcfdd02380c6b620e567fe2
|
[
"MIT"
] | null | null | null |
#include "add.hpp"
namespace jhm
{
add::add() = default;
add::~add() = default;
} // namespace jhm.
| 15.571429
| 26
| 0.577982
|
JacknJo
|
8ef5895790d79b560e252c6e6e7f40634ccff4a0
| 2,574
|
cpp
|
C++
|
01-dda-chessboard/DDA_Chessboard.cpp
|
ChetanaHegde/vtu-mca-sem3-cg
|
92667bef2b89726d6a272cd6425217257d47846d
|
[
"MIT"
] | 2
|
2020-10-08T10:36:40.000Z
|
2021-05-11T16:23:19.000Z
|
01-dda-chessboard/DDA_Chessboard.cpp
|
ChetanaHegde/vtu-mca-sem3-cg
|
92667bef2b89726d6a272cd6425217257d47846d
|
[
"MIT"
] | null | null | null |
01-dda-chessboard/DDA_Chessboard.cpp
|
ChetanaHegde/vtu-mca-sem3-cg
|
92667bef2b89726d6a272cd6425217257d47846d
|
[
"MIT"
] | 2
|
2017-01-25T13:43:09.000Z
|
2019-03-18T12:03:40.000Z
|
/* Program 1: Write a program to implement Chessboard using DDA Line drawing algorithm.
Coded by: Basavaraju R, Assistant Professor, RNSIT, Bangalore
Email: basavaraju dot revanna at gmail dot com
*/
#include<gl\glut.h>
#include<math.h>
GLint start_x=50,start_y=40,end_x=start_x+80,end_y=start_y+80;
void setPixel(GLint, GLint);
void init();
void display();
void lineDDA(GLint,GLint,GLint,GLint);
void fillRow(GLint,GLint,GLint,GLint,GLfloat);
void main(int argc, char** argv)
{
glutInit(&argc, argv); //initialize GLUT
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); //initialize display mode
glutInitWindowPosition(250,100); //set display-window upper-left position
glutInitWindowSize(600,500); //set display-window width & height
glutCreateWindow("Chess Board using DDA Line Algorithm"); //create display-window with a title
init(); //initialize window prpperties
glutDisplayFunc(display); //call graphics to be displayed on the window
glutMainLoop(); //display everything and wait
}
inline int round(const float a)
{
return int(a+0.5);
}
void setPixel(GLint xCoordinate, GLint yCoordinate)
{
glBegin(GL_POINTS);
glVertex2i(xCoordinate,yCoordinate);
glEnd();
glFlush(); //executes all OpenGL functions as quickly as possible
}
void init(void)
{
glClearColor(0.0,0.5,0.5,0.0);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0.0,200.0,0.0,150.0);
}
//DDA line drawing procedure
void lineDDA(GLint x0,GLint y0, GLint xe, GLint ye)
{
GLint dx=xe-x0, dy=ye-y0, steps, k;
GLfloat xinc, yinc, x=x0, y=y0;
if(abs(dx)>abs(dy))
steps=abs(dx);
else
steps=abs(dy);
xinc=float(dx)/float(steps);
yinc=float(dy)/float(steps);
setPixel(round(x),round(y));
for(k=0;k<steps;k++)
{
x+=xinc;
y+=yinc;
setPixel(round(x), round(y));
}
}
//Function fills one row of chessbord with alternate black and white color
void fillRow(GLint x1,GLint y1,GLint x2,GLint y2,GLfloat c)
{
while(x1<end_x)
{
glColor3f(c,c,c);
glRecti(x1,y1,x2,y2);
x1=x2;
x2+=10;
if(c==0.0)
c=1.0;
else
c=0.0;
}
}
void display(void)
{
GLint i=0,a,b;
a=start_x;
b=start_y;
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0,0.0,0.0);
while(i<9)
{
lineDDA(a,start_y,a,end_y);
a+=10;
lineDDA(start_x,b,end_x,b);
b+=10;
i++;
}
GLint x1=start_x,y1=end_y,x2=start_x+10,y2=end_y-10;
GLfloat cl=0.0;
while(y1>start_y)
{
fillRow(x1,y1,x2,y2,cl);
if(cl==0.0)
cl=1.0;
else
cl=0.0;
y1=y2;
y2-=10;
}
glFlush();
}
| 22.578947
| 97
| 0.661616
|
ChetanaHegde
|
8ef60977c3acc029e6540d17f9aef44f5f3376c5
| 13,949
|
cpp
|
C++
|
source/test/mp-integer-unsigned-arithmetic-test.cpp
|
CaptainCrowbar/rs-sci
|
40768e7665c555f28e4b0ca2b1c2d1fa2da9775a
|
[
"BSL-1.0"
] | null | null | null |
source/test/mp-integer-unsigned-arithmetic-test.cpp
|
CaptainCrowbar/rs-sci
|
40768e7665c555f28e4b0ca2b1c2d1fa2da9775a
|
[
"BSL-1.0"
] | null | null | null |
source/test/mp-integer-unsigned-arithmetic-test.cpp
|
CaptainCrowbar/rs-sci
|
40768e7665c555f28e4b0ca2b1c2d1fa2da9775a
|
[
"BSL-1.0"
] | null | null | null |
#include "rs-sci/mp-integer.hpp"
#include "rs-format/format.hpp"
#include "rs-unit-test.hpp"
#include <string>
#include <vector>
using namespace RS::Format;
using namespace RS::Sci;
namespace {
using ByteVector = std::vector<uint8_t>;
std::string hexdump(const ByteVector& v) {
std::string s(reinterpret_cast<const char*>(v.data()), v.size());
return format_string(s, "x");
}
}
void test_rs_sci_mp_integer_unsigned_arithmetic() {
MPN x, y, z, q, r;
std::string s;
TRY(x = 0);
TEST_EQUAL(x.bits(), 0u);
TRY(s = x.str("b")); TEST_EQUAL(s, "0");
TRY(s = x.str("n")); TEST_EQUAL(s, "0");
TRY(s = x.str("x")); TEST_EQUAL(s, "0");
TRY(y = x + 15);
TEST_EQUAL(y.bits(), 4u);
TRY(s = to_string(y)); TEST_EQUAL(s, "15");
TRY(s = y.str("x")); TEST_EQUAL(s, "f");
TRY(y = 15 - x);
TEST_EQUAL(y.bits(), 4u);
TRY(s = to_string(y)); TEST_EQUAL(s, "15");
TRY(s = y.str("x")); TEST_EQUAL(s, "f");
TRY(x = 0x123456789abcdef0ull);
TRY(y = 0xffffffffffffffffull);
TEST_EQUAL(x.bits(), 61u);
TEST_EQUAL(y.bits(), 64u);
TRY(s = to_string(x)); TEST_EQUAL(s, "1311768467463790320");
TRY(s = to_string(y)); TEST_EQUAL(s, "18446744073709551615");
TRY(z = x + 15);
TEST_EQUAL(z.bits(), 61u);
TRY(s = to_string(z)); TEST_EQUAL(s, "1311768467463790335");
TRY(s = z.str("x")); TEST_EQUAL(s, "123456789abcdeff");
TRY(z = x + y);
TEST_EQUAL(z.bits(), 65u);
TRY(s = to_string(z)); TEST_EQUAL(s, "19758512541173341935");
TRY(s = z.str("x")); TEST_EQUAL(s, "1123456789abcdeef");
TRY(z = y - 15);
TEST_EQUAL(z.bits(), 64u);
TRY(s = to_string(z)); TEST_EQUAL(s, "18446744073709551600");
TRY(s = z.str("x")); TEST_EQUAL(s, "fffffffffffffff0");
TRY(z = y - x);
TEST_EQUAL(z.bits(), 64u);
TRY(s = to_string(z)); TEST_EQUAL(s, "17134975606245761295");
TRY(s = z.str("x")); TEST_EQUAL(s, "edcba9876543210f");
TRY(z = x * y);
TEST_EQUAL(z.bits(), 125u);
TRY(s = to_string(z)); TEST_EQUAL(s, "24197857203266734862169780735577366800");
TRY(s = z.str("x")); TEST_EQUAL(s, "123456789abcdeefedcba98765432110");
TRY(x = MPN("123456789123456789123456789123456789123456789"));
TRY(y = MPN("123456789123456789123456789123456789"));
TRY(z = x - y);
TEST_EQUAL(z, MPN("123456789000000000000000000000000000000000000"));
TRY(y = MPN("123456789123456789123456789123456789000000000"));
TRY(z = x - y);
TEST_EQUAL(z, MPN("123456789"));
TRY(x = MPN("123456789123456789123456789123456789123456789"));
TRY(y = MPN("1357913579135791357913579"));
TRY(z = x - y);
TEST_EQUAL(z, MPN("123456789123456789122098875544320997765543210"));
TRY(x = MPN("123456789123456789123456789123456789123456789"));
TRY(y = MPN("123456789"));
TRY(q = x / y);
TRY(r = x % y);
TEST_EQUAL(q, MPN("1000000001000000001000000001000000001"));
TEST_EQUAL(r, MPN("0"));
TRY(y = MPN("987654321"));
TRY(q = x / y);
TRY(r = x % y);
TEST_EQUAL(q, MPN("124999998985937499000175780249997801"));
TEST_EQUAL(r, MPN("725308668"));
TRY(y = MPN("987654321987654321987654321987654321987654321"));
TRY(q = x / y);
TRY(r = x % y);
TEST_EQUAL(q, MPN("0"));
TEST_EQUAL(r, MPN("123456789123456789123456789123456789123456789"));
TRY(y = {});
}
void test_rs_sci_mp_integer_unsigned_arithmetic_powers() {
MPN x, y;
std::string s;
TRY(x = 0); TRY(y = x.pow(0)); TEST_EQUAL(y.str(), "1");
TRY(x = 0); TRY(y = x.pow(1)); TEST_EQUAL(y.str(), "0");
TRY(x = 0); TRY(y = x.pow(2)); TEST_EQUAL(y.str(), "0");
TRY(x = 0); TRY(y = x.pow(3)); TEST_EQUAL(y.str(), "0");
TRY(x = 1); TRY(y = x.pow(0)); TEST_EQUAL(y.str(), "1");
TRY(x = 1); TRY(y = x.pow(1)); TEST_EQUAL(y.str(), "1");
TRY(x = 1); TRY(y = x.pow(2)); TEST_EQUAL(y.str(), "1");
TRY(x = 1); TRY(y = x.pow(3)); TEST_EQUAL(y.str(), "1");
TRY(x = 10); TRY(y = x.pow(0)); TEST_EQUAL(y.str(), "1");
TRY(x = 10); TRY(y = x.pow(1)); TEST_EQUAL(y.str(), "10");
TRY(x = 10); TRY(y = x.pow(2)); TEST_EQUAL(y.str(), "100");
TRY(x = 10); TRY(y = x.pow(3)); TEST_EQUAL(y.str(), "1000");
TRY(x = 10); TRY(y = x.pow(4)); TEST_EQUAL(y.str(), "10000");
TRY(x = 10); TRY(y = x.pow(5)); TEST_EQUAL(y.str(), "100000");
TRY(x = 10); TRY(y = x.pow(6)); TEST_EQUAL(y.str(), "1000000");
TRY(x = 10); TRY(y = x.pow(7)); TEST_EQUAL(y.str(), "10000000");
TRY(x = 10); TRY(y = x.pow(8)); TEST_EQUAL(y.str(), "100000000");
TRY(x = 10); TRY(y = x.pow(9)); TEST_EQUAL(y.str(), "1000000000");
TRY(x = 10); TRY(y = x.pow(10)); TEST_EQUAL(y.str(), "10000000000");
TRY(x = 10); TRY(y = x.pow(11)); TEST_EQUAL(y.str(), "100000000000");
TRY(x = 10); TRY(y = x.pow(12)); TEST_EQUAL(y.str(), "1000000000000");
TRY(x = 10); TRY(y = x.pow(13)); TEST_EQUAL(y.str(), "10000000000000");
TRY(x = 10); TRY(y = x.pow(14)); TEST_EQUAL(y.str(), "100000000000000");
TRY(x = 10); TRY(y = x.pow(15)); TEST_EQUAL(y.str(), "1000000000000000");
TRY(x = 10); TRY(y = x.pow(16)); TEST_EQUAL(y.str(), "10000000000000000");
TRY(x = 10); TRY(y = x.pow(17)); TEST_EQUAL(y.str(), "100000000000000000");
TRY(x = 10); TRY(y = x.pow(18)); TEST_EQUAL(y.str(), "1000000000000000000");
TRY(x = 10); TRY(y = x.pow(19)); TEST_EQUAL(y.str(), "10000000000000000000");
TRY(x = 10); TRY(y = x.pow(20)); TEST_EQUAL(y.str(), "100000000000000000000");
TRY(x = 10); TRY(y = x.pow(21)); TEST_EQUAL(y.str(), "1000000000000000000000");
TRY(x = 10); TRY(y = x.pow(22)); TEST_EQUAL(y.str(), "10000000000000000000000");
TRY(x = 10); TRY(y = x.pow(23)); TEST_EQUAL(y.str(), "100000000000000000000000");
TRY(x = 10); TRY(y = x.pow(24)); TEST_EQUAL(y.str(), "1000000000000000000000000");
TRY(x = 10); TRY(y = x.pow(25)); TEST_EQUAL(y.str(), "10000000000000000000000000");
TRY(x = 10); TRY(y = x.pow(26)); TEST_EQUAL(y.str(), "100000000000000000000000000");
TRY(x = 10); TRY(y = x.pow(27)); TEST_EQUAL(y.str(), "1000000000000000000000000000");
TRY(x = 10); TRY(y = x.pow(28)); TEST_EQUAL(y.str(), "10000000000000000000000000000");
TRY(x = 10); TRY(y = x.pow(29)); TEST_EQUAL(y.str(), "100000000000000000000000000000");
TRY(x = 10); TRY(y = x.pow(30)); TEST_EQUAL(y.str(), "1000000000000000000000000000000");
}
void test_rs_sci_mp_integer_unsigned_bit_operations() {
MPN x, y, z;
std::string s;
TEST_EQUAL(x.bits_set(), 0u);
TEST(x.is_even());
TEST(! x.is_odd());
TRY(x = 0x123456789abcdef0ull);
TRY(y = 0xffffffffffffffffull);
TEST_EQUAL(x.bits(), 61u);
TEST_EQUAL(y.bits(), 64u);
TEST_EQUAL(x.bits_set(), 32u);
TEST_EQUAL(y.bits_set(), 64u);
TEST(x.is_even());
TEST(! x.is_odd());
TEST(! y.is_even());
TEST(y.is_odd());
TRY(s = to_string(x)); TEST_EQUAL(s, "1311768467463790320");
TRY(s = to_string(y)); TEST_EQUAL(s, "18446744073709551615");
TRY(z = x & y);
TEST_EQUAL(z.bits(), 61u);
TRY(s = to_string(z)); TEST_EQUAL(s, "1311768467463790320");
TRY(s = z.str("x")); TEST_EQUAL(s, "123456789abcdef0");
TRY(z = x | y);
TEST_EQUAL(z.bits(), 64u);
TRY(s = to_string(z)); TEST_EQUAL(s, "18446744073709551615");
TRY(s = z.str("x")); TEST_EQUAL(s, "ffffffffffffffff");
TRY(z = x ^ y);
TEST_EQUAL(z.bits(), 64u);
TRY(s = to_string(z)); TEST_EQUAL(s, "17134975606245761295");
TRY(s = z.str("x")); TEST_EQUAL(s, "edcba9876543210f");
TRY(z = x >> 0); TRY(s = z.str("x")); TEST_EQUAL(s, "123456789abcdef0");
TRY(z = x >> 1); TRY(s = z.str("x")); TEST_EQUAL(s, "91a2b3c4d5e6f78");
TRY(z = x >> 2); TRY(s = z.str("x")); TEST_EQUAL(s, "48d159e26af37bc");
TRY(z = x >> 3); TRY(s = z.str("x")); TEST_EQUAL(s, "2468acf13579bde");
TRY(z = x >> 31); TRY(s = z.str("x")); TEST_EQUAL(s, "2468acf1");
TRY(z = x >> 32); TRY(s = z.str("x")); TEST_EQUAL(s, "12345678");
TRY(z = x >> 33); TRY(s = z.str("x")); TEST_EQUAL(s, "91a2b3c");
TRY(z = x >> 58); TRY(s = z.str("x")); TEST_EQUAL(s, "4");
TRY(z = x >> 59); TRY(s = z.str("x")); TEST_EQUAL(s, "2");
TRY(z = x >> 60); TRY(s = z.str("x")); TEST_EQUAL(s, "1");
TRY(z = x >> 61); TRY(s = z.str("x")); TEST_EQUAL(s, "0");
TRY(z = x >> 62); TRY(s = z.str("x")); TEST_EQUAL(s, "0");
TRY(z = x >> 63); TRY(s = z.str("x")); TEST_EQUAL(s, "0");
TRY(z = x >> 64); TRY(s = z.str("x")); TEST_EQUAL(s, "0");
TRY(z = x >> 65); TRY(s = z.str("x")); TEST_EQUAL(s, "0");
TRY(z = x << 0); TRY(s = z.str("x")); TEST_EQUAL(s, "123456789abcdef0");
TRY(z = x << 1); TRY(s = z.str("x")); TEST_EQUAL(s, "2468acf13579bde0");
TRY(z = x << 2); TRY(s = z.str("x")); TEST_EQUAL(s, "48d159e26af37bc0");
TRY(z = x << 3); TRY(s = z.str("x")); TEST_EQUAL(s, "91a2b3c4d5e6f780");
TRY(z = x << 4); TRY(s = z.str("x")); TEST_EQUAL(s, "123456789abcdef00");
TRY(z = x << 5); TRY(s = z.str("x")); TEST_EQUAL(s, "2468acf13579bde00");
TRY(z = x << 6); TRY(s = z.str("x")); TEST_EQUAL(s, "48d159e26af37bc00");
TRY(z = x << 7); TRY(s = z.str("x")); TEST_EQUAL(s, "91a2b3c4d5e6f7800");
TRY(z = x << 8); TRY(s = z.str("x")); TEST_EQUAL(s, "123456789abcdef000");
TRY(z = x << 9); TRY(s = z.str("x")); TEST_EQUAL(s, "2468acf13579bde000");
TRY(z = x << 10); TRY(s = z.str("x")); TEST_EQUAL(s, "48d159e26af37bc000");
TRY(z = x << 11); TRY(s = z.str("x")); TEST_EQUAL(s, "91a2b3c4d5e6f78000");
TRY(z = x << 12); TRY(s = z.str("x")); TEST_EQUAL(s, "123456789abcdef0000");
TRY(z = x << 13); TRY(s = z.str("x")); TEST_EQUAL(s, "2468acf13579bde0000");
TRY(z = x << 14); TRY(s = z.str("x")); TEST_EQUAL(s, "48d159e26af37bc0000");
TRY(z = x << 15); TRY(s = z.str("x")); TEST_EQUAL(s, "91a2b3c4d5e6f780000");
TRY(z = x << 16); TRY(s = z.str("x")); TEST_EQUAL(s, "123456789abcdef00000");
TRY(z = x << 17); TRY(s = z.str("x")); TEST_EQUAL(s, "2468acf13579bde00000");
TRY(z = x << 18); TRY(s = z.str("x")); TEST_EQUAL(s, "48d159e26af37bc00000");
TRY(z = x << 19); TRY(s = z.str("x")); TEST_EQUAL(s, "91a2b3c4d5e6f7800000");
TRY(z = x << 20); TRY(s = z.str("x")); TEST_EQUAL(s, "123456789abcdef000000");
TRY(x = {});
TEST(! x.get_bit(0));
TEST(! x.get_bit(100));
TRY(x.set_bit(16));
TEST_EQUAL(x, MPN("0x10000"));
TEST(! x.get_bit(15));
TEST(x.get_bit(16));
TEST(! x.get_bit(17));
TRY(x.set_bit(80));
TEST_EQUAL(x, MPN("0x100000000000000010000"));
TEST(! x.get_bit(79));
TEST(x.get_bit(80));
TEST(! x.get_bit(81));
TRY(x.set_bit(80, false));
TEST_EQUAL(x, MPN("0x10000"));
TEST(! x.get_bit(80));
TRY(x.flip_bit(80));
TEST_EQUAL(x, MPN("0x100000000000000010000"));
TEST(x.get_bit(80));
TRY(x.flip_bit(80));
TEST_EQUAL(x, MPN("0x10000"));
TEST(! x.get_bit(80));
}
void test_rs_sci_mp_integer_unsigned_byte_operations() {
MPN a, b;
ByteVector v;
TEST_EQUAL(a.bytes(), 0u);
TRY(a = MPN("0x12")); TEST_EQUAL(a.bytes(), 1u);
TRY(a = MPN("0x1234")); TEST_EQUAL(a.bytes(), 2u);
TRY(a = MPN("0x123456")); TEST_EQUAL(a.bytes(), 3u);
TRY(a = MPN("0x12345678")); TEST_EQUAL(a.bytes(), 4u);
TRY(a = MPN("0x123456789a")); TEST_EQUAL(a.bytes(), 5u);
TRY(a = MPN("0x123456789abc")); TEST_EQUAL(a.bytes(), 6u);
TRY(a = MPN("0x123456789abcde")); TEST_EQUAL(a.bytes(), 7u);
TRY(a = MPN("0x123456789abcdef1")); TEST_EQUAL(a.bytes(), 8u);
TRY(a = MPN("0x123456789abcdef123")); TEST_EQUAL(a.bytes(), 9u);
TRY(a = MPN("0x123456789abcdef12345")); TEST_EQUAL(a.bytes(), 10u);
TEST_EQUAL(a.get_byte(0), 0x45);
TEST_EQUAL(a.get_byte(1), 0x23);
TEST_EQUAL(a.get_byte(2), 0xf1);
TEST_EQUAL(a.get_byte(3), 0xde);
TEST_EQUAL(a.get_byte(4), 0xbc);
TEST_EQUAL(a.get_byte(5), 0x9a);
TEST_EQUAL(a.get_byte(6), 0x78);
TEST_EQUAL(a.get_byte(7), 0x56);
TEST_EQUAL(a.get_byte(8), 0x34);
TEST_EQUAL(a.get_byte(9), 0x12);
TEST_EQUAL(a.get_byte(10), 0u);
TEST_EQUAL(a.get_byte(11), 0u);
TEST_EQUAL(a.get_byte(12), 0u);
TEST_EQUAL(a.get_byte(13), 0u);
TEST_EQUAL(a.get_byte(14), 0u);
TEST_EQUAL(a.get_byte(15), 0u);
TEST_EQUAL(a.get_byte(16), 0u);
TRY(a.set_byte(1, 0xff)); TEST_EQUAL(a.str("x"), "123456789abcdef1ff45");
TRY(a.set_byte(3, 0xff)); TEST_EQUAL(a.str("x"), "123456789abcfff1ff45");
TRY(a.set_byte(5, 0xff)); TEST_EQUAL(a.str("x"), "12345678ffbcfff1ff45");
TRY(a.set_byte(7, 0xff)); TEST_EQUAL(a.str("x"), "1234ff78ffbcfff1ff45");
TRY(a.set_byte(9, 0xff)); TEST_EQUAL(a.str("x"), "ff34ff78ffbcfff1ff45");
TRY(a.set_byte(11, 0xff)); TEST_EQUAL(a.str("x"), "ff00ff34ff78ffbcfff1ff45");
TRY(a.set_byte(13, 0xff)); TEST_EQUAL(a.str("x"), "ff00ff00ff34ff78ffbcfff1ff45");
TRY(a.set_byte(15, 0xff)); TEST_EQUAL(a.str("x"), "ff00ff00ff00ff34ff78ffbcfff1ff45");
TRY(a = 0);
TRY(b = MPN("0x123456789abcdef12345"));
v.resize(7);
TRY(a.write_be(v.data(), v.size())); TEST_EQUAL(hexdump(v), "00 00 00 00 00 00 00");
TRY(b.write_be(v.data(), v.size())); TEST_EQUAL(hexdump(v), "78 9a bc de f1 23 45");
TRY(a.write_le(v.data(), v.size())); TEST_EQUAL(hexdump(v), "00 00 00 00 00 00 00");
TRY(b.write_le(v.data(), v.size())); TEST_EQUAL(hexdump(v), "45 23 f1 de bc 9a 78");
v = {0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0xaa,0xbb,0xcc,0xdd,0xee,0xff};
TRY(a = MPN::read_be(v.data(), v.size())); TEST_EQUAL(a.str("x"), "112233445566778899aabbccddeeff");
TRY(a = MPN::read_le(v.data(), v.size())); TEST_EQUAL(a.str("x"), "ffeeddccbbaa998877665544332211");
}
| 43.590625
| 105
| 0.577246
|
CaptainCrowbar
|
8ef7b6a4a6cc310bccf1b00824337df2b9ff2966
| 411
|
hpp
|
C++
|
libs/parse/include/fcppt/parse/tag.hpp
|
freundlich/fcppt
|
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
|
[
"BSL-1.0"
] | 13
|
2015-02-21T18:35:14.000Z
|
2019-12-29T14:08:29.000Z
|
libs/parse/include/fcppt/parse/tag.hpp
|
cpreh/fcppt
|
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
|
[
"BSL-1.0"
] | 5
|
2016-08-27T07:35:47.000Z
|
2019-04-21T10:55:34.000Z
|
libs/parse/include/fcppt/parse/tag.hpp
|
freundlich/fcppt
|
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
|
[
"BSL-1.0"
] | 8
|
2015-01-10T09:22:37.000Z
|
2019-12-01T08:31:12.000Z
|
// Copyright Carl Philipp Reh 2009 - 2021.
// 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 FCPPT_PARSE_TAG_HPP_INCLUDED
#define FCPPT_PARSE_TAG_HPP_INCLUDED
namespace fcppt::parse
{
/**
\brief The tag parsers derive from.
\ingroup fcpptparse
*/
struct tag
{
};
}
#endif
| 18.681818
| 61
| 0.717762
|
freundlich
|
8ef8d27920731249682d2403bb0520863b51bbcd
| 2,849
|
hpp
|
C++
|
lib/libcpp/Perulangan/Perulangan/iterativesolvervisitorinterface.hpp
|
beckerrh/simfemsrc
|
d857eb6f6f8627412d4f9d89a871834c756537db
|
[
"MIT"
] | null | null | null |
lib/libcpp/Perulangan/Perulangan/iterativesolvervisitorinterface.hpp
|
beckerrh/simfemsrc
|
d857eb6f6f8627412d4f9d89a871834c756537db
|
[
"MIT"
] | 1
|
2019-01-31T10:59:11.000Z
|
2019-01-31T10:59:11.000Z
|
lib/libcpp/Perulangan/Perulangan/iterativesolvervisitorinterface.hpp
|
beckerrh/simfemsrc
|
d857eb6f6f8627412d4f9d89a871834c756537db
|
[
"MIT"
] | null | null | null |
#ifndef __Perulangan_IterativeSolverVisitorInterface_h
#define __Perulangan_IterativeSolverVisitorInterface_h
#include "Alat/interfacebase.hpp"
#include "Alat/armadillo.hpp"
/*--------------------------------------------------------------------------*/
namespace alat
{
class GhostLinearSolver;
class GhostMatrix;
class GhostVector;
class StringVector;
}
namespace perulangan
{
class IterativeSolverVisitorInterface : public alat::InterfaceBase
{
protected:
std::string getInterfaceName() const;
public:
~IterativeSolverVisitorInterface();
IterativeSolverVisitorInterface();
IterativeSolverVisitorInterface( const IterativeSolverVisitorInterface& iterativesolvervisitorinterface);
IterativeSolverVisitorInterface& operator=( const IterativeSolverVisitorInterface& iterativesolvervisitorinterface);
std::string getClassName() const;
perulangan::IterativeSolverVisitorInterface* clone() const;
// virtual void basicInit(const alat::ParameterFile* parameterfile, std::string blockname);
virtual std::ostream& printLoopInformation(std::ostream& os) const;
virtual std::string getVectorType() const;
// virtual int getVectorLevel() const=0;
virtual void newVector(alat::GhostVector* u) = 0;
virtual void vectorEqual(alat::GhostVector& r, const alat::GhostVector& f) const;
virtual void vectorZero(alat::GhostVector& v) const;
virtual void vectorAdd(alat::GhostVector& p, double d, const alat::GhostVector& q) const;
virtual void vectorScale(alat::GhostVector& r, double d) const;
virtual double vectorDot(const alat::GhostVector& gu, const alat::GhostVector& gv) const;
virtual double vectorNorm(const alat::GhostVector& r) const;
virtual void residual(const alat::GhostMatrix& A, alat::GhostVector& r, const alat::GhostVector& u, const alat::GhostVector& f) const;
virtual void matrixVectorProduct(const alat::GhostMatrix& A, alat::GhostVector& r, const alat::GhostVector& u, double d) const;
virtual void postProcess(alat::GhostVector& u) const;
// virtual const alat::armaivec& getDomainsPermutation(int iteration) const;
// virtual void solveOnDomain(int idomain, const alat::GhostLinearSolver& linearsolverdomain, const alat::GhostMatrix& ghostmatrix, alat::GhostVector& u, const alat::GhostVector& f) const;
// virtual void vectorEqualOnDomain(int idomain, alat::GhostVector& u, const alat::GhostVector& f) const;
// virtual void matrixVectorProductCoupling(int i, const alat::GhostMatrix& ghostmatrix, alat::GhostVector& u, const alat::GhostVector& f, double d) const;
// virtual void smoothInterface(int idomain, alat::GhostVector& u) const;
// virtual void smoothInterfaceOnLevel(int level, alat::GhostVector& u) const;
};
}
/*--------------------------------------------------------------------------*/
#endif
| 47.483333
| 192
| 0.724465
|
beckerrh
|
8efc12a8115c48f8f4862cafa92222aa80df25a8
| 896
|
cpp
|
C++
|
lib/PointerAnalysis/MemoryModel/PointerLayout.cpp
|
grievejia/tpa
|
8a7aa4c7d41c266fcf3a5e2011ff324bcddf5816
|
[
"MIT"
] | 16
|
2016-08-03T12:09:19.000Z
|
2022-02-20T08:22:12.000Z
|
lib/PointerAnalysis/MemoryModel/PointerLayout.cpp
|
grievejia/tpa
|
8a7aa4c7d41c266fcf3a5e2011ff324bcddf5816
|
[
"MIT"
] | 1
|
2016-12-14T08:42:19.000Z
|
2016-12-21T08:21:20.000Z
|
lib/PointerAnalysis/MemoryModel/PointerLayout.cpp
|
grievejia/tpa
|
8a7aa4c7d41c266fcf3a5e2011ff324bcddf5816
|
[
"MIT"
] | 6
|
2016-08-19T14:17:06.000Z
|
2019-08-05T08:34:47.000Z
|
#include "PointerAnalysis/MemoryModel/Type/PointerLayout.h"
namespace tpa
{
const PointerLayout* PointerLayout::getEmptyLayout()
{
return emptyLayout;
}
const PointerLayout* PointerLayout::getSinglePointerLayout()
{
return singlePointerLayout;
}
const PointerLayout* PointerLayout::getLayout(SetType&& set)
{
auto itr = layoutSet.insert(PointerLayout(std::move(set))).first;
return &(*itr);
}
const PointerLayout* PointerLayout::getLayout(std::initializer_list<size_t> ilist)
{
SetType set(ilist);
return getLayout(std::move(set));
}
const PointerLayout* PointerLayout::merge(const PointerLayout* lhs, const PointerLayout* rhs)
{
assert(lhs != nullptr && rhs != nullptr);
if (lhs == rhs)
return lhs;
if (lhs->empty())
return rhs;
if (rhs->empty())
return lhs;
SetType newSet(lhs->validOffsets);
newSet.merge(rhs->validOffsets);
return getLayout(std::move(newSet));
}
}
| 20.363636
| 93
| 0.739955
|
grievejia
|
8eff0a67d91b7eb211ff45a1703d34d455e17e9e
| 3,951
|
cpp
|
C++
|
duds/data/Unit.cpp
|
jjackowski/duds
|
0fc4eec0face95c13575672f2a2d8625517c9469
|
[
"BSD-2-Clause"
] | null | null | null |
duds/data/Unit.cpp
|
jjackowski/duds
|
0fc4eec0face95c13575672f2a2d8625517c9469
|
[
"BSD-2-Clause"
] | null | null | null |
duds/data/Unit.cpp
|
jjackowski/duds
|
0fc4eec0face95c13575672f2a2d8625517c9469
|
[
"BSD-2-Clause"
] | null | null | null |
/*
* This file is part of the DUDS project. It is subject to the BSD-style
* license terms in the LICENSE file found in the top-level directory of this
* distribution and at https://github.com/jjackowski/duds/blob/master/LICENSE.
* No part of DUDS, including this file, may be copied, modified, propagated,
* or distributed except according to the terms contained in the LICENSE file.
*
* Copyright (C) 2017 Jeff Jackowski
*/
#include <duds/data/Unit.hpp>
#include <duds/general/Errors.hpp>
namespace duds { namespace data {
void Unit::setAmpere(int e) {
int v = general::SignExtend<4>(e);
if (v != e) {
DUDS_THROW_EXCEPTION(UnitRangeError() << BadUnitExponent(e) <<
BadUnit("Ampere"));
}
u = (u & 0xFFFFFFF0) | v;
}
void Unit::setCandela(int e) {
int v = general::SignExtend<4>(e);
if (v != e) {
DUDS_THROW_EXCEPTION(UnitRangeError() << BadUnitExponent(e) <<
BadUnit("Candela"));
}
u = (u & 0xFFFFFF0F) | (v << 4);
}
void Unit::setKelvin(int e) {
int v = general::SignExtend<4>(e);
if (v != e) {
DUDS_THROW_EXCEPTION(UnitRangeError() << BadUnitExponent(e) <<
BadUnit("Kelvin"));
}
u = (u & 0xFFFFF0FF) | (v << 8);
}
void Unit::setKilogram(int e) {
int v = general::SignExtend<4>(e);
if (v != e) {
DUDS_THROW_EXCEPTION(UnitRangeError() << BadUnitExponent(e) <<
BadUnit("Kilogram"));
}
u = (u & 0xFFFF0FFF) | (v << 12);
}
void Unit::setMeter(int e) {
int v = general::SignExtend<4>(e);
if (v != e) {
DUDS_THROW_EXCEPTION(UnitRangeError() << BadUnitExponent(e) <<
BadUnit("Meter"));
}
u = (u & 0xFFF0FFFF) | (v << 16);
}
void Unit::setMole(int e) {
int v = general::SignExtend<4>(e);
if (v != e) {
DUDS_THROW_EXCEPTION(UnitRangeError() << BadUnitExponent(e) <<
BadUnit("Mole"));
}
u = (u & 0xFF0FFFFF) | (v << 20);
}
void Unit::setSecond(int e) {
int v = general::SignExtend<4>(e);
if (v != e) {
DUDS_THROW_EXCEPTION(UnitRangeError() << BadUnitExponent(e) <<
BadUnit("Second"));
}
u = (u & 0xF0FFFFFF) | (v << 24);
}
void Unit::setRadian(int e) {
int v = general::SignExtend<2>(e);
if (v != e) {
DUDS_THROW_EXCEPTION(UnitRangeError() << BadUnitExponent(e) <<
BadUnit("Radian"));
}
u = (u & 0xCFFFFFFF) | (v << 28);
}
void Unit::setSteradian(int e) {
int v = general::SignExtend<2>(e);
if (v != e) {
DUDS_THROW_EXCEPTION(UnitRangeError() << BadUnitExponent(e) <<
BadUnit("Steradian"));
}
u = (u & 0x3FFFFFFF) | (v << 30);
}
Unit::Unit(int A, int cd, int K, int kg, int m, int mol, int s,
int rad, int sr) {
setAmpere(A);
setCandela(cd);
setKelvin(K);
setKilogram(kg);
setMeter(m);
setMole(mol);
setSecond(s);
setRadian(rad);
setSteradian(sr);
}
const Unit Unit::operator * (const Unit &U) const {
// the result
Unit r;
// set the result; may fail with exception
r.setAmpere(ampere() + U.ampere());
r.setCandela(candela() + U.candela());
r.setKelvin(kelvin() + U.kelvin());
r.setKilogram(kilogram() + U.kilogram());
r.setMeter(meter() + U.meter());
r.setMole(mole() + U.mole());
r.setSecond(second() + U.second());
r.setRadian(radian() + U.radian());
r.setSteradian(steradian() + U.steradian());
// return the result
return r;
}
const Unit Unit::operator / (const Unit &U) const {
// the result
Unit r;
// set the result; may fail with exception
r.setAmpere(ampere() - U.ampere());
r.setCandela(candela() - U.candela());
r.setKelvin(kelvin() - U.kelvin());
r.setKilogram(kilogram() - U.kilogram());
r.setMeter(meter() - U.meter());
r.setMole(mole() - U.mole());
r.setSecond(second() - U.second());
r.setRadian(radian() - U.radian());
r.setSteradian(steradian() - U.steradian());
// return the result
return r;
}
Unit &Unit::operator *= (const Unit &U) {
// a temporary
Unit n(*this * U); // may throw
// keep the new value
u = n.value();
return *this;
}
Unit &Unit::operator /= (const Unit &U) {
// a temporary
Unit n(*this / U); // may throw
// keep the new value
u = n.value();
return *this;
}
} }
| 24.69375
| 78
| 0.632498
|
jjackowski
|
f102ceb88409595e3e0ee48f71065afc42677212
| 829
|
hpp
|
C++
|
PrEngineSwitch/Game_Engine/include/SpriteLayer.hpp
|
aprithul/Prengine
|
7aff20bb73ab21e9e11dda1985e6b22992479f0d
|
[
"BSD-3-Clause"
] | 1
|
2019-10-08T05:20:30.000Z
|
2019-10-08T05:20:30.000Z
|
PrEngineSwitch/Game_Engine/include/SpriteLayer.hpp
|
aprithul/PrEngine
|
7aff20bb73ab21e9e11dda1985e6b22992479f0d
|
[
"BSD-3-Clause"
] | null | null | null |
PrEngineSwitch/Game_Engine/include/SpriteLayer.hpp
|
aprithul/PrEngine
|
7aff20bb73ab21e9e11dda1985e6b22992479f0d
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef SPRITE_LAYER_HPP
#define SPRITE_LAYER_HPP
#include "GlAssert.hpp"
#include "RenderLayer.hpp"
#include "Graphics.hpp"
#include "EntityManagementSystemModule.hpp"
#include "DirectionalLight.hpp"
#include "Camera3D.hpp"
#include "Matrix4x4f.hpp"
#include <vector>
#include "Sprite.hpp"
#include "Transform3D.hpp"
namespace PrEngine
{
void insertion_sort(std::vector<Sprite*>& arr, Int_32 n);
//extern RendererOpenGL2D* renderer;
class SpriteLayer : public RenderLayer
{
public:
SpriteLayer();
~SpriteLayer() override;
void start() override;
void update() override;
void end() override;
std::vector<Sprite*> sprite_list;
private:
void UpdateTransforms(Transform3D* transform);
};
} // namespace Pringin
#endif
| 21.815789
| 61
| 0.670688
|
aprithul
|
f102e7e7ec1cf25062fb7fa4946df2b2ed4b3e87
| 232
|
hh
|
C++
|
build/ARM/debug/VIO9PData.hh
|
msharmavikram/gem5_experiments
|
87353d28df55b9a6a5be6cbb19bce87a500ab3b4
|
[
"BSD-3-Clause"
] | 5
|
2019-12-12T16:26:09.000Z
|
2022-03-17T03:23:33.000Z
|
build/X86/debug/VIO9PData.hh
|
zhoushuxin/impl_of_HPCA2018
|
594d807fb0c0712bb7766122c4efe3321d012687
|
[
"BSD-3-Clause"
] | 1
|
2020-08-20T05:53:30.000Z
|
2020-08-20T05:53:30.000Z
|
build/X86/debug/VIO9PData.hh
|
zhoushuxin/impl_of_HPCA2018
|
594d807fb0c0712bb7766122c4efe3321d012687
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* DO NOT EDIT THIS FILE! Automatically generated by SCons.
*/
#ifndef __DEBUG_VIO9PData_HH__
#define __DEBUG_VIO9PData_HH__
namespace Debug {
class SimpleFlag;
extern SimpleFlag VIO9PData;
}
#endif // __DEBUG_VIO9PData_HH__
| 16.571429
| 59
| 0.788793
|
msharmavikram
|
f10648e5e4555887d3f3edb4cf771ecf7b04e628
| 13,938
|
inl
|
C++
|
source/bsys/geometry/geometry_vertex_3.inl
|
bluebackblue/brownie
|
917fcc71e5b0a807c0a8dab22a9ca7f3b0d60917
|
[
"MIT"
] | null | null | null |
source/bsys/geometry/geometry_vertex_3.inl
|
bluebackblue/brownie
|
917fcc71e5b0a807c0a8dab22a9ca7f3b0d60917
|
[
"MIT"
] | null | null | null |
source/bsys/geometry/geometry_vertex_3.inl
|
bluebackblue/brownie
|
917fcc71e5b0a807c0a8dab22a9ca7f3b0d60917
|
[
"MIT"
] | null | null | null |
#pragma once
/**
* Copyright (c) blueback
* Released under the MIT License
* https://github.com/bluebackblue/brownie/blob/master/LICENSE.txt
* http://bbbproject.sakura.ne.jp/wordpress/mitlicense
* @brief ジオメトリ。
*/
/** include
*/
#pragma warning(push)
#pragma warning(disable:4464)
#include "../types/types.h"
#pragma warning(pop)
/** include
*/
#include "./geometry_vector.h"
/** NBsys::NGeometry
*/
#if(BSYS_GEOMETRY_ENABLE)
#pragma warning(push)
#pragma warning(disable:4514 4710)
namespace NBsys{namespace NGeometry
{
/** x
*/
inline const f32& Geometry_Vector3::x() const
{
return this->raw.v.xx;
}
/** x
*/
inline f32& Geometry_Vector3::x()
{
return this->raw.v.xx;
}
/** y
*/
inline const f32& Geometry_Vector3::y() const
{
return this->raw.v.yy;
}
/** y
*/
inline f32& Geometry_Vector3::y()
{
return this->raw.v.yy;
}
/** z
*/
inline const f32& Geometry_Vector3::z() const
{
return this->raw.v.zz;
}
/** z
*/
inline f32& Geometry_Vector3::z()
{
return this->raw.v.zz;
}
/** constructor
*/
inline Geometry_Vector3::Geometry_Vector3() noexcept
{
}
/** constructor
*/
inline Geometry_Vector3::Geometry_Vector3(f32 a_xx,f32 a_yy,f32 a_zz) noexcept
{
this->raw.v.xx = a_xx;
this->raw.v.yy = a_yy;
this->raw.v.zz = a_zz;
}
/** constructor
*/
inline Geometry_Vector3::Geometry_Vector3(f32 a_value) noexcept
{
this->raw.v.xx = a_value;
this->raw.v.yy = a_value;
this->raw.v.zz = a_value;
}
/** constructor
*/
inline Geometry_Vector3::Geometry_Vector3(const f32* a_value_pointer) noexcept
{
this->raw.v.xx = a_value_pointer[0];
this->raw.v.yy = a_value_pointer[1];
this->raw.v.zz = a_value_pointer[2];
}
/** copy constructor
*/
inline Geometry_Vector3::Geometry_Vector3(const Geometry_Vector3& a_vector) noexcept
{
this->raw.v.xx = a_vector.raw.v.xx;
this->raw.v.yy = a_vector.raw.v.yy;
this->raw.v.zz = a_vector.raw.v.zz;
}
/** constructor
*/
inline Geometry_Vector3::Geometry_Vector3(const Geometry_Identity_Type& /*a_identity*/) noexcept
{
this->Set_Zero();
}
/** destructor
*/
inline Geometry_Vector3::~Geometry_Vector3()
{
}
/** t_1 = t_2;
*/
inline Geometry_Vector3& Geometry_Vector3::operator =(const Geometry_Vector3& a_right)
{
this->raw.v.xx = a_right.raw.v.xx;
this->raw.v.yy = a_right.raw.v.yy;
this->raw.v.zz = a_right.raw.v.zz;
return *this;
}
/** t_1 = +t_2;
*/
inline Geometry_Vector3 Geometry_Vector3::operator +() const
{
return *this;
}
/** t_1 = -t_2;
*/
inline Geometry_Vector3 Geometry_Vector3::operator -() const
{
return Geometry_Vector3(-this->raw.v.xx,-this->raw.v.yy,-this->raw.v.zz);
}
/** t_1 += t_2;
*/
inline Geometry_Vector3& Geometry_Vector3::operator +=(const Geometry_Vector3& a_right)
{
this->raw.v.xx += a_right.raw.v.xx;
this->raw.v.yy += a_right.raw.v.yy;
this->raw.v.zz += a_right.raw.v.zz;
return *this;
}
/** t_1 -= t_2;
*/
inline Geometry_Vector3& Geometry_Vector3::operator -=(const Geometry_Vector3& a_right)
{
this->raw.v.xx -= a_right.raw.v.xx;
this->raw.v.yy -= a_right.raw.v.yy;
this->raw.v.zz -= a_right.raw.v.zz;
return *this;
}
/** t_1 *= t_2;
*/
inline Geometry_Vector3& Geometry_Vector3::operator *=(const Geometry_Vector3& a_right)
{
this->raw.v.xx *= a_right.raw.v.xx;
this->raw.v.yy *= a_right.raw.v.yy;
this->raw.v.zz *= a_right.raw.v.zz;
return *this;
}
/** t_1 /= t_2;
*/
inline Geometry_Vector3& Geometry_Vector3::operator /=(const Geometry_Vector3& a_right)
{
this->raw.v.xx /= a_right.raw.v.xx;
this->raw.v.yy /= a_right.raw.v.yy;
this->raw.v.zz /= a_right.raw.v.zz;
return *this;
}
/** t_1 = 2;
*/
inline Geometry_Vector3& Geometry_Vector3::operator =(f32 a_right_value)
{
this->raw.v.xx = a_right_value;
this->raw.v.yy = a_right_value;
this->raw.v.zz = a_right_value;
return *this;
}
/** t_1 += 2;
*/
inline Geometry_Vector3& Geometry_Vector3::operator +=(f32 a_right_value)
{
this->raw.v.xx += a_right_value;
this->raw.v.yy += a_right_value;
this->raw.v.zz += a_right_value;
return *this;
}
/** t_1 -= 2;
*/
inline Geometry_Vector3& Geometry_Vector3::operator -=(f32 a_right_value)
{
this->raw.v.xx -= a_right_value;
this->raw.v.yy -= a_right_value;
this->raw.v.zz -= a_right_value;
return *this;
}
/** t_1 *= 2;
*/
inline Geometry_Vector3& Geometry_Vector3::operator *=(f32 a_right_value)
{
this->raw.v.xx *= a_right_value;
this->raw.v.yy *= a_right_value;
this->raw.v.zz *= a_right_value;
return *this;
}
/** t_1 /= 2;
*/
inline Geometry_Vector3& Geometry_Vector3::operator /=(f32 a_right_value)
{
this->raw.v.xx /= a_right_value;
this->raw.v.yy /= a_right_value;
this->raw.v.zz /= a_right_value;
return *this;
}
/** [static]Zero。
*/
inline const Geometry_Vector3& Geometry_Vector3::Zero()
{
static const NGeometry::Geometry_Vector3 s_zero(0.0f,0.0f,0.0f);
return s_zero;
}
/** [static]One。
*/
inline const Geometry_Vector3& Geometry_Vector3::One()
{
static const NGeometry::Geometry_Vector3 s_one(1.0f,1.0f,1.0f);
return s_one;
}
/** [設定]。
*/
inline Geometry_Vector3& Geometry_Vector3::Set(f32 a_xx,f32 a_yy,f32 a_zz)
{
this->raw.v.xx = a_xx;
this->raw.v.yy = a_yy;
this->raw.v.zz = a_zz;
return *this;
}
/** [設定]。
*/
inline Geometry_Vector3& Geometry_Vector3::Set_X(f32 a_xx)
{
this->raw.v.xx = a_xx;
return *this;
}
/** [設定]。
*/
inline Geometry_Vector3& Geometry_Vector3::Set_Y(f32 a_yy)
{
this->raw.v.yy = a_yy;
return *this;
}
/** [設定]。
*/
inline Geometry_Vector3& Geometry_Vector3::Set_Z(f32 a_zz)
{
this->raw.v.zz = a_zz;
return *this;
}
/** [設定]。
*/
inline Geometry_Vector3& Geometry_Vector3::Set(const Geometry_Vector3& a_vector)
{
this->raw.v.xx = a_vector.raw.v.xx;
this->raw.v.yy = a_vector.raw.v.yy;
this->raw.v.zz = a_vector.raw.v.zz;
return *this;
}
/** [設定]Set_Zero。
*/
inline Geometry_Vector3& Geometry_Vector3::Set_Zero()
{
*this = Geometry_Vector3::Zero();
return *this;
}
/** [取得]。
*/
inline f32 Geometry_Vector3::Get_X()
{
return this->raw.v.xx;
}
/** [取得]。
*/
inline f32 Geometry_Vector3::Get_Y()
{
return this->raw.v.yy;
}
/** [取得]。
*/
inline f32 Geometry_Vector3::Get_Z()
{
return this->raw.v.zz;
}
/** [作成]外積。
*/
inline Geometry_Vector3 Geometry_Vector3::Make_Cross(const Geometry_Vector3& a_vector) const
{
Geometry_Vector3 t_temp;
{
t_temp.raw.v.xx = (this->raw.v.yy * a_vector.raw.v.zz) - (this->raw.v.zz * a_vector.raw.v.yy);
t_temp.raw.v.yy = (this->raw.v.zz * a_vector.raw.v.xx) - (this->raw.v.xx * a_vector.raw.v.zz);
t_temp.raw.v.zz = (this->raw.v.xx * a_vector.raw.v.yy) - (this->raw.v.yy * a_vector.raw.v.xx);
}
return t_temp;
}
/** [設定]外積。
*/
inline Geometry_Vector3& Geometry_Vector3::Set_Cross(const Geometry_Vector3& a_vector)
{
f32 t_temp_x = (this->raw.v.yy * a_vector.raw.v.zz) - (this->raw.v.zz * a_vector.raw.v.yy);
f32 t_temp_y = (this->raw.v.zz * a_vector.raw.v.xx) - (this->raw.v.xx * a_vector.raw.v.zz);
f32 t_temp_z = (this->raw.v.xx * a_vector.raw.v.yy) - (this->raw.v.yy * a_vector.raw.v.xx);
this->raw.v.xx = t_temp_x;
this->raw.v.yy = t_temp_y;
this->raw.v.zz = t_temp_z;
return *this;
}
/** [設定]外積。
*/
inline Geometry_Vector3& Geometry_Vector3::Set_Cross(const Geometry_Vector3& a_vector_1,const Geometry_Vector3& a_vector_2)
{
f32 t_temp_x = (a_vector_1.raw.v.yy * a_vector_2.raw.v.zz) - (a_vector_1.raw.v.zz * a_vector_2.raw.v.yy);
f32 t_temp_y = (a_vector_1.raw.v.zz * a_vector_2.raw.v.xx) - (a_vector_1.raw.v.xx * a_vector_2.raw.v.zz);
f32 t_temp_z = (a_vector_1.raw.v.xx * a_vector_2.raw.v.yy) - (a_vector_1.raw.v.yy * a_vector_2.raw.v.xx);
this->raw.v.xx = t_temp_x;
this->raw.v.yy = t_temp_y;
this->raw.v.zz = t_temp_z;
return *this;
}
/** [設定]正規化。
*/
inline Geometry_Vector3& Geometry_Vector3::Set_Normalize()
{
f32 t_value = this->SquareLength();
ASSERT(t_value != 0.0f);
t_value = NMath::sqrt_f(t_value);
ASSERT(t_value != 0.0f);
t_value = 1.0f / t_value;
this->raw.v.xx *= t_value;
this->raw.v.yy *= t_value;
this->raw.v.zz *= t_value;
return *this;
}
/** [設定]正規化。
*/
inline Geometry_Vector3& Geometry_Vector3::Set_Normalize_Safe(const Geometry_Vector3& a_vector_safe)
{
f32 t_value = this->SquareLength();
if(t_value == 0.0f){
*this = a_vector_safe;
return *this;
}
t_value = NMath::sqrt_f(t_value);
if(t_value == 0.0f){
*this = a_vector_safe;
return *this;
}
t_value = 1.0f / t_value;
this->raw.v.xx *= t_value;
this->raw.v.yy *= t_value;
this->raw.v.zz *= t_value;
return *this;
}
/** [設定]正規化。
*/
inline f32 Geometry_Vector3::Set_Normalize_GetLength()
{
f32 t_value = this->SquareLength();
if(t_value == 0.0f){
return 0.0f;
}
t_value = NMath::sqrt_f(t_value);
if(t_value == 0.0f){
return 0.0f;
}
f32 t_length = t_value;
t_value = 1.0f / t_value;
this->raw.v.xx *= t_value;
this->raw.v.yy *= t_value;
this->raw.v.zz *= t_value;
return t_length;
}
/** [作成]正規化。
*/
inline Geometry_Vector3 Geometry_Vector3::Make_Normalize() const
{
Geometry_Vector3 t_temp;
{
f32 t_value = this->SquareLength();
ASSERT(t_value != 0.0f);
t_value = NMath::sqrt_f(t_value);
ASSERT(t_value != 0.0f);
t_value = 1.0f / t_value;
t_temp.raw.v.xx = this->raw.v.xx * t_value;
t_temp.raw.v.yy = this->raw.v.yy * t_value;
t_temp.raw.v.zz = this->raw.v.zz * t_value;
}
return t_temp;
}
/** [作成]正規化。
*/
inline Geometry_Vector3 Geometry_Vector3::Make_Normalize_Safe(const Geometry_Vector3& a_vector_safe) const
{
Geometry_Vector3 t_temp;
{
f32 t_value = this->SquareLength();
if(t_value == 0.0f){
return a_vector_safe;
}
t_value = NMath::sqrt_f(t_value);
if(t_value == 0.0f){
return a_vector_safe;
}
t_value = 1.0f / t_value;
t_temp.raw.v.xx = this->raw.v.xx * t_value;
t_temp.raw.v.yy = this->raw.v.yy * t_value;
t_temp.raw.v.zz = this->raw.v.zz * t_value;
}
return t_temp;
}
/** [内積]length(this)*length(a_vector)*cos(θ)。
*/
inline f32 Geometry_Vector3::Dot(const Geometry_Vector3& a_vector) const
{
f32 t_value = (this->raw.v.xx * a_vector.raw.v.xx) + (this->raw.v.yy * a_vector.raw.v.yy) + (this->raw.v.zz * a_vector.raw.v.zz);
return t_value;
}
/** [チェック]。
*/
inline bool Geometry_Vector3::IsZero() const
{
return (this->raw.v.xx == 0.0f)&&(this->raw.v.yy == 0.0f)&&(this->raw.v.zz == 0.0f);
}
/** [作成]長さ。
*/
inline f32 Geometry_Vector3::Length() const
{
f32 t_value = this->SquareLength();
t_value = NMath::sqrt_f(t_value);
return t_value;
}
/** [作成]長さの2乗。
*/
inline f32 Geometry_Vector3::SquareLength() const
{
return (this->raw.v.xx * this->raw.v.xx) + (this->raw.v.yy * this->raw.v.yy) + (this->raw.v.zz * this->raw.v.zz);
}
/** [作成]2点間の距離の2乗。
*/
inline f32 Geometry_Vector3::SquareDistance(const Geometry_Vector3& a_vector) const
{
f32 t_temp_x = (this->raw.v.xx - a_vector.raw.v.xx);
f32 t_temp_y = (this->raw.v.yy - a_vector.raw.v.yy);
f32 t_temp_z = (this->raw.v.zz - a_vector.raw.v.zz);
f32 t_value = (t_temp_x * t_temp_x) + (t_temp_y * t_temp_y) + (t_temp_z * t_temp_z);
return t_value;
}
/** [作成]Make_Lerp。
a_per = 0.0f : return = this
a_per = 1.0f : return = a_vector
*/
inline Geometry_Vector3 Geometry_Vector3::Make_Lerp(const Geometry_Vector3& a_vector,f32 a_per) const
{
Geometry_Vector3 t_temp;
{
t_temp.raw.v.xx = this->raw.v.xx + (a_vector.raw.v.xx - this->raw.v.xx) * a_per;
t_temp.raw.v.yy = this->raw.v.yy + (a_vector.raw.v.yy - this->raw.v.yy) * a_per;
t_temp.raw.v.zz = this->raw.v.zz + (a_vector.raw.v.zz - this->raw.v.zz) * a_per;
}
return t_temp;
}
/** [static][作成]Lerp
a_per = 0.0f : return = this
a_per = 1.0f : return = a_vector
*/
inline Geometry_Vector3 Geometry_Vector3::Make_Lerp(const Geometry_Vector3& a_vector_1,const Geometry_Vector3& a_vector_2,f32 a_per)
{
Geometry_Vector3 t_temp;
{
t_temp.raw.v.xx = a_vector_1.raw.v.xx + (a_vector_2.raw.v.xx - a_vector_1.raw.v.xx) * a_per;
t_temp.raw.v.yy = a_vector_1.raw.v.yy + (a_vector_2.raw.v.yy - a_vector_1.raw.v.yy) * a_per;
t_temp.raw.v.zz = a_vector_1.raw.v.zz + (a_vector_2.raw.v.zz - a_vector_1.raw.v.zz) * a_per;
}
return t_temp;
}
/** [設定]Set_Lerp。
a_per = 0.0f : this = this
a_per = 1.0f : this = a_vector
*/
inline void Geometry_Vector3::Set_Lerp(const Geometry_Vector3& a_vector,f32 a_per)
{
this->raw.v.xx += (a_vector.raw.v.xx - this->raw.v.xx) * a_per;
this->raw.v.yy += (a_vector.raw.v.yy - this->raw.v.yy) * a_per;
this->raw.v.zz += (a_vector.raw.v.zz - this->raw.v.zz) * a_per;
}
/** [設定]Lerp。
a_per = 0.0f : this = a_vector_1
a_per = 1.0f : this = a_vector_2
*/
inline void Geometry_Vector3::Set_Lerp(const Geometry_Vector3& a_vector_1,const Geometry_Vector3& a_vector_2,f32 a_per)
{
this->raw.v.xx = a_vector_1.raw.v.xx + (a_vector_2.raw.v.xx - a_vector_1.raw.v.xx) * a_per;
this->raw.v.yy = a_vector_1.raw.v.yy + (a_vector_2.raw.v.yy - a_vector_1.raw.v.yy) * a_per;
this->raw.v.zz = a_vector_1.raw.v.zz + (a_vector_2.raw.v.zz - a_vector_1.raw.v.zz) * a_per;
}
}}
#pragma warning(pop)
#endif
| 21.054381
| 134
| 0.617305
|
bluebackblue
|
f1064af791209147bd47565f3703d6aeab1c6d83
| 914
|
cpp
|
C++
|
ststring.cpp
|
ohmyjons/SPOJ-1
|
870ae3b072a3fbc89149b35fe5649a74512a8f60
|
[
"Unlicense"
] | 264
|
2015-01-08T10:07:01.000Z
|
2022-03-26T04:11:51.000Z
|
ststring.cpp
|
ohmyjons/SPOJ-1
|
870ae3b072a3fbc89149b35fe5649a74512a8f60
|
[
"Unlicense"
] | 17
|
2016-04-15T03:38:07.000Z
|
2020-10-30T00:33:57.000Z
|
ststring.cpp
|
ohmyjons/SPOJ-1
|
870ae3b072a3fbc89149b35fe5649a74512a8f60
|
[
"Unlicense"
] | 127
|
2015-01-08T04:56:44.000Z
|
2022-02-25T18:40:37.000Z
|
// 2008-10-22
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
void inc(char* s)
{
int cur=0;
bool ok=false;
while (!ok)
{
s[cur]++;
if (s[cur]=='K')
s[cur++]='A';
else
ok=true;
}
if (s[cur]==1)
{
s[cur]='A';
s[cur+1]=0;
}
}
int ok(char* s)
{
int i=1;
while (s[i])
{
if (s[i]==s[i-1]||s[i]==s[i-1]-1||s[i]==s[i-1]+1)
return 0;
i++;
}
return 1;
}
int hash(char* s)
{
int x=1;
int i=0;
int res=0;
while (s[i])
{
res+=x*(s[i++]-'A'+1);
x*=11;
}
return res;
}
int ans[2000000];
int main()
{
//precompute answers
char s1[10]="A",s2[10]="AAAAAAA";
int sum=0;
while (strcmp(s1,s2))
{
if (ok(s1))
sum++;
ans[hash(s1)]=sum;
inc(s1);
}
for(;;)
{
s1[0]=0;
scanf("%s %s",s1,s2);
if (!s1[0]) return 0;
reverse(s1,s1+strlen(s1));
reverse(s2,s2+strlen(s2));
printf("%d\n",max(ans[hash(s2)]-ans[hash(s1)]-ok(s2),0));
}
}
| 13.057143
| 59
| 0.514223
|
ohmyjons
|
f1071f2a2259d40223c641fdcc79d9d6fc9e2942
| 1,700
|
cpp
|
C++
|
leetcode_0721_unionfind.cpp
|
xiaoxiaoxiang-Wang/01-leetcode
|
5a9426dd70c3dd6725444783aaa8cefc27196779
|
[
"MIT"
] | 3
|
2021-01-18T06:26:10.000Z
|
2021-01-29T07:52:49.000Z
|
leetcode_0721_unionfind.cpp
|
xiaoxiaoxiang-Wang/leetcode
|
5a9426dd70c3dd6725444783aaa8cefc27196779
|
[
"MIT"
] | null | null | null |
leetcode_0721_unionfind.cpp
|
xiaoxiaoxiang-Wang/leetcode
|
5a9426dd70c3dd6725444783aaa8cefc27196779
|
[
"MIT"
] | null | null | null |
class Solution {
public:
vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {
vector<pair<string, int>> emails;
for (int i = 0; i < accounts.size(); i++) {
for (int j = 1; j < accounts[i].size(); j++) {
emails.push_back({ accounts[i][j],i });
}
}
sort(emails.begin(), emails.end());
vector<int> uf(accounts.size(),-1);
unordered_map<int, int> um;
for (int i = 0; i < emails.size() - 1; i++){
if (emails[i].first == emails[i + 1].first) {
unionFind(uf, emails[i].second, emails[i+1].second);
}
}
int idx = 0;
for (int i = 0; i < accounts.size(); i++) {
setIndex(uf, um, i, idx);
}
vector<vector<string>> res(idx);
emails.push_back({ "",0 });
for (int i = 0; i<emails.size() - 1; i++) {
if (res[um[emails[i].second]].empty()) {
// 插入名字
res[um[emails[i].second]].push_back(accounts[emails[i].second][0]);
}
if (emails[i].first == emails[i + 1].first) {
auto iter2 = um.find(emails[i + 1].second);
if (iter2 == um.end()) {
um[emails[i+1].second] = um[emails[i].second];
}
}
else {
// 插入元素
res[um[emails[i].second]].push_back(emails[i].first);
}
}
return res;
}
int unionFind(vector<int>& uf, int a,int b) {
a = find(uf,a);
b = find(uf,b);
if (a == b) {
return false;
}
uf[a] = b;
return true;
}
int find(vector<int>& uf, int a) {
while (uf[a] != -1) {
a = uf[a];
}
return a;
}
int setIndex(vector<int>& uf, unordered_map<int, int>& um,int i,int& idx) {
auto iter = um.find(i);
if (iter != um.end()) {
return iter->second;
}
if (uf[i] == -1) {
um[i] = idx;
return idx++;
}
return um[i] = setIndex(uf, um, uf[i], idx);
}
};
| 23.943662
| 76
| 0.545294
|
xiaoxiaoxiang-Wang
|
f1088921c111614dc731eba6e955608389cbe272
| 982
|
cpp
|
C++
|
src/Utils.cpp
|
bsmithcompsci/Experiment-EmbedSystems-Playground
|
fcf72d6e3500c8cfea9446fcbc777be3e28cd86f
|
[
"MIT"
] | null | null | null |
src/Utils.cpp
|
bsmithcompsci/Experiment-EmbedSystems-Playground
|
fcf72d6e3500c8cfea9446fcbc777be3e28cd86f
|
[
"MIT"
] | null | null | null |
src/Utils.cpp
|
bsmithcompsci/Experiment-EmbedSystems-Playground
|
fcf72d6e3500c8cfea9446fcbc777be3e28cd86f
|
[
"MIT"
] | null | null | null |
#include "global/Utils.h"
std::vector<std::string> splitStrs(const std::string &_str, char _delimiter)
{
std::vector<std::string> output;
std::string::size_type prev_pos = 0, cur_pos = 0;
while ((cur_pos = _str.find(_delimiter, cur_pos)) != std::string::npos)
{
std::string substring(_str.substr(prev_pos, cur_pos - prev_pos));
output.push_back(substring);
prev_pos = ++cur_pos;
}
output.push_back(_str.substr(prev_pos, cur_pos - prev_pos)); // Catch the last bits.
return output;
}
std::vector<int> splitInts(const std::string &_str, char _delimiter)
{
std::vector<int> output;
std::string::size_type prev_pos = 0, cur_pos = 0;
while ((cur_pos = _str.find(_delimiter, cur_pos)) != std::string::npos)
{
std::string substring(_str.substr(prev_pos, cur_pos - prev_pos));
output.push_back(atoi(substring.c_str()));
prev_pos = ++cur_pos;
}
output.push_back(atoi(_str.substr(prev_pos, cur_pos - prev_pos).c_str())); // Catch the last bits.
return output;
}
| 30.6875
| 99
| 0.705703
|
bsmithcompsci
|
f1094fbea6cdbe832dff1f5bd659025df443c301
| 1,970
|
hpp
|
C++
|
src/registry.hpp
|
rcabot/codscape
|
5619b40d7857066818c8409d3db4371d3c8f758c
|
[
"Unlicense"
] | null | null | null |
src/registry.hpp
|
rcabot/codscape
|
5619b40d7857066818c8409d3db4371d3c8f758c
|
[
"Unlicense"
] | null | null | null |
src/registry.hpp
|
rcabot/codscape
|
5619b40d7857066818c8409d3db4371d3c8f758c
|
[
"Unlicense"
] | null | null | null |
#ifndef REGISTRY_H
#define REGISTRY_H
#pragma once
#include "dialogue_initiator.hpp"
#include "Map.h"
#include "Person.h"
#include "interactable.hpp"
#include "dialogue_ui.hpp"
#include "rect_transform.hpp"
#include <sstream>
#include <limits>
template<typename T>
using uvector = std::vector<std::unique_ptr<T>>;
class registry
{
private:
public:
uvector<Map> maps_;
uvector<person> people_;
std::vector<interactable> interactables_;
player_state_machine player_state_machine_;
dialogue_state dialogue_state_;
dialogue_initiator dialogue_initiator_;
dialogue_ui dialogue_ui_;
rect_transform dialogue_ui_transform_;
registry() :
maps_{},
people_{},
interactables_{},
player_state_machine_{},
dialogue_state_{*this},
dialogue_initiator_{player_state_machine_, dialogue_state_},
dialogue_ui_transform_{} ,
dialogue_ui_{*this,dialogue_ui_transform_,dialogue_state_}
{}
void add_new_person_at(const Vector2& position, const std::string name, int map_index_)
{
auto start_dialogue_with_person = std::function([name](registry& r){
r.dialogue_initiator_.start_dialogue_with(name);
});
people_.emplace_back(std::make_unique<person>(name, maps_[map_index_].get(), position));
interactables_.emplace_back(position,std::move(start_dialogue_with_person),*this);
}
template<class...Params>
void add_map(Params&&... args)
{
maps_.emplace_back(std::make_unique<Map>(args...));
}
interactable* try_get_nearest_interactable_object_in_radius(const Vector2 center, const float radius)
{
interactable* nearest_interactable = nullptr;
float min_distance{std::numeric_limits<float>::max()};
for(auto& interactable : interactables_)
{
float distance = center.distance(interactable.position_);
if(radius > distance && distance < min_distance)
{
min_distance = distance;
nearest_interactable = &interactable;
}
}
return nearest_interactable;
}
};
#endif
| 25.25641
| 102
| 0.744162
|
rcabot
|
f10c6af1132219f183e8088cef1ee69cee874021
| 22
|
cpp
|
C++
|
library/containers/flat_hash/lib/probings.cpp
|
ZhekehZ/catboost
|
3f774da539b8e57cca25686b89c473cbd1f61a6c
|
[
"Apache-2.0"
] | 6,989
|
2017-07-18T06:23:18.000Z
|
2022-03-31T15:58:36.000Z
|
library/cpp/containers/flat_hash/lib/probings.cpp
|
birichie/catboost
|
de75c6af12cf490700e76c22072fbdc15b35d679
|
[
"Apache-2.0"
] | 1,978
|
2017-07-18T09:17:58.000Z
|
2022-03-31T14:28:43.000Z
|
library/cpp/containers/flat_hash/lib/probings.cpp
|
birichie/catboost
|
de75c6af12cf490700e76c22072fbdc15b35d679
|
[
"Apache-2.0"
] | 1,228
|
2017-07-18T09:03:13.000Z
|
2022-03-29T05:57:40.000Z
|
#include "probings.h"
| 11
| 21
| 0.727273
|
ZhekehZ
|
f10cd8557ccd76ef1c08f38c105009ce9e26196e
| 650
|
cpp
|
C++
|
Spline/Source.cpp
|
Fahersto/Spline
|
cbe4645aedd9b6e53c9c3393b1c7f2fc0040666d
|
[
"MIT"
] | null | null | null |
Spline/Source.cpp
|
Fahersto/Spline
|
cbe4645aedd9b6e53c9c3393b1c7f2fc0040666d
|
[
"MIT"
] | null | null | null |
Spline/Source.cpp
|
Fahersto/Spline
|
cbe4645aedd9b6e53c9c3393b1c7f2fc0040666d
|
[
"MIT"
] | null | null | null |
#include "ParametricSpline.h"
int main()
{
ParametricSpline parametricSpline = ParametricSpline();
const int VALUE_COUNT = 3;
double* x = new double[VALUE_COUNT]{ 0, 1, 2 };
double* y = new double[VALUE_COUNT]{ 0, 3, 0 };
double* z = new double[VALUE_COUNT]{ 1, 2, 3 };
parametricSpline.Compute(x, y, z, VALUE_COUNT);
const int STEPS = 10;
for (int i = 0; i < parametricSpline.GetSegmentCount(); i++)
{
for (int j = 0; j < STEPS; j++)
{
double t = i + (double)j / (STEPS);
double* position = parametricSpline.eval(t);
printf("new Vector3(%ff, %ff, %ff),\n", position[0], position[1], position[2]);
}
}
return 0;
}
| 21.666667
| 82
| 0.629231
|
Fahersto
|
f10f1c8509669062f615ca8b59fe48ba8955c30e
| 1,443
|
cc
|
C++
|
project/core/id/test/SequentialIdGenerator.cc
|
letsmake-games/engine
|
b40559037353e000adf2f18ca9ead16529f932c6
|
[
"MIT"
] | null | null | null |
project/core/id/test/SequentialIdGenerator.cc
|
letsmake-games/engine
|
b40559037353e000adf2f18ca9ead16529f932c6
|
[
"MIT"
] | null | null | null |
project/core/id/test/SequentialIdGenerator.cc
|
letsmake-games/engine
|
b40559037353e000adf2f18ca9ead16529f932c6
|
[
"MIT"
] | null | null | null |
//
// (c) LetsMakeGames 2019
// http://www.letsmake.games
//
#include "core/id/IdClass.hh"
#include "core/id/SequentialIdGenerator.hh"
#include "gtest/gtest.h"
//
// types //////////////////////////////////////////////////////////////////////
//
DECLARE_IDCLASS(BasicId, uint8_t);
//
// Generator //////////////////////////////////////////////////////////////////
//
TEST(Test_SequentialIdGenerator, Generation )
{
//
// generate an id
//
Engine::SequentialIdGenerator<BasicId> generator;
BasicId id1 = generator.next();
EXPECT_NE(id1, BasicId::InvalidId);
EXPECT_EQ(id1.getRawId(), 0);
//
// the last id should be the id we just generated
//
BasicId id1_2 = generator.prev();
EXPECT_EQ(id1, id1_2);
//
// generate another id
//
BasicId id2 = generator.next();
EXPECT_NE(id2, BasicId::InvalidId);
EXPECT_NE(id1, id2);
//
// once we run out of numbers, we generate only InvalidIds
//
for(size_t i = 0; i != 256; ++i )
{
generator.next();
}
EXPECT_EQ(generator.next(), BasicId::InvalidId);
EXPECT_EQ(generator.next(), BasicId::InvalidId);
//
// prev always returns the last VALID id
//
EXPECT_EQ(BasicId(BasicId::InvalidValue-1), generator.prev());
//
// we can reset a generator to recycle old ids
//
generator.reset();
BasicId id1_3 = generator.next();
EXPECT_EQ(id1, id1_3);
}
| 21.220588
| 79
| 0.559252
|
letsmake-games
|
f10fe3c7b0a9556130f2361f133bf535c6bd8706
| 5,361
|
hpp
|
C++
|
contrib/backends/nntpchan-daemon/libnntpchan/kqueue.hpp
|
majestrate/nntpchan
|
f92f68c3cdce4b7ce6d4121ca4356b36ebcd933f
|
[
"MIT"
] | 233
|
2015-08-06T02:51:52.000Z
|
2022-02-14T11:29:13.000Z
|
contrib/backends/nntpchan-daemon/libnntpchan/kqueue.hpp
|
Revivify/nntpchan
|
0d555bb88a2298dae9aacf11348e34c52befa3d8
|
[
"MIT"
] | 98
|
2015-09-19T22:29:00.000Z
|
2021-06-12T09:43:13.000Z
|
contrib/backends/nntpchan-daemon/libnntpchan/kqueue.hpp
|
Revivify/nntpchan
|
0d555bb88a2298dae9aacf11348e34c52befa3d8
|
[
"MIT"
] | 49
|
2015-08-06T02:51:55.000Z
|
2020-03-11T04:23:56.000Z
|
#include <nntpchan/event.hpp>
#include <sys/types.h>
#include <sys/event.h>
#include <iostream>
#include <cstring>
#include <errno.h>
namespace nntpchan
{
namespace ev
{
template<size_t bufsz>
struct KqueueLoop : public Loop
{
int kfd;
size_t conns;
char readbuf[bufsz];
KqueueLoop() : kfd(kqueue()), conns(0)
{
};
virtual ~KqueueLoop()
{
::close(kfd);
}
virtual bool TrackConn(ev::io * handler)
{
struct kevent event;
short filter = 0;
if(handler->readable() || handler->acceptable())
{
filter |= EVFILT_READ;
}
if(handler->writeable())
{
filter |= EVFILT_WRITE;
}
EV_SET(&event, handler->fd, filter, EV_ADD | EV_CLEAR, 0, 0, handler);
int ret = kevent(kfd, &event, 1, nullptr, 0, nullptr);
if(ret == -1) return false;
if(event.flags & EV_ERROR)
{
std::cerr << "KqueueLoop::TrackConn() kevent failed: " << strerror(event.data) << std::endl;
return false;
}
++conns;
return true;
}
virtual void UntrackConn(ev::io * handler)
{
struct kevent event;
short filter = 0;
if(handler->readable() || handler->acceptable())
{
filter |= EVFILT_READ;
}
if(handler->writeable())
{
filter |= EVFILT_WRITE;
}
EV_SET(&event, handler->fd, filter, EV_DELETE, 0, 0, handler);
int ret = kevent(kfd, &event, 1, nullptr, 0, nullptr);
if(ret == -1 || event.flags & EV_ERROR)
std::cerr << "KqueueLoop::UntrackConn() kevent failed: " << strerror(event.data) << std::endl;
else
--conns;
}
virtual void Run()
{
struct kevent events[512];
struct kevent * event;
io * handler;
int ret, idx;
do
{
idx = 0;
ret = kevent(kfd, nullptr, 0, events, 512, nullptr);
if(ret > 0)
{
while(idx < ret)
{
event = &events[idx++];
handler = static_cast<io *>(event->udata);
if(event->flags & EV_EOF)
{
handler->close();
delete handler;
continue;
}
if(event->filter & EVFILT_READ && handler->acceptable())
{
int backlog = event->data;
while(backlog)
{
handler->accept();
--backlog;
}
}
if(event->filter & EVFILT_READ && handler->readable())
{
int readed = 0;
size_t readnum = event->data;
while(readnum > sizeof(readbuf))
{
int r = handler->read(readbuf, sizeof(readbuf));
if(r > 0)
{
readnum -= r;
readed += r;
}
else
readnum = 0;
}
if(readnum && readed != -1)
{
int r = handler->read(readbuf, readnum);
if(r > 0)
readed += r;
else
readed = r;
}
}
if(event->filter & EVFILT_WRITE && handler->writeable())
{
int writespace = 1024;
int written = handler->write(writespace);
if(written == -1)
{
if (errno == EAGAIN || errno == EWOULDBLOCK)
{
// blocking
}
else
{
perror("write()");
handler->close();
delete handler;
continue;
}
}
}
if(!handler->keepalive())
{
handler->close();
delete handler;
}
}
}
}
while(ret != -1);
}
};
}
}
| 33.092593
| 110
| 0.320463
|
majestrate
|
f111b50b2ed434352fe1d8198b05939082989892
| 1,215
|
cpp
|
C++
|
Tree/589-n-ary-tree-preorder-traversal.cpp
|
wandsX/LeetCodeExperience
|
8502e6e8ce911045f45f0075bcf3ee751a4558c7
|
[
"MIT"
] | null | null | null |
Tree/589-n-ary-tree-preorder-traversal.cpp
|
wandsX/LeetCodeExperience
|
8502e6e8ce911045f45f0075bcf3ee751a4558c7
|
[
"MIT"
] | null | null | null |
Tree/589-n-ary-tree-preorder-traversal.cpp
|
wandsX/LeetCodeExperience
|
8502e6e8ce911045f45f0075bcf3ee751a4558c7
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
using namespace std;
//leetcode submit region begin(Prohibit modification and deletion)
class Solution
{
public:
vector<int> preorder(Node *root)
{
stack < Node * > s;
std::vector<int> ans;
Node *cur = nullptr;
if (root != nullptr)
{ s.push(root); }
while(!s.empty())
{
cur = s.top();
s.pop();
ans.emplace_back(cur->val);
for (int i = cur->children.size() - 1; i >= 0; --i)
s.push(cur->children[i]);
}
return ans;
}
};
// 递归
class Solution1
{
public:
vector<int> preorder(Node *root)
{
std::vector<int> ans;
traverse(root, ans);
return ans;
}
void traverse(Node *cur, vector<int> &ans)
{
if (cur == nullptr)
{ return; }
ans.push_back(cur->val);
for (auto &e : cur->children)
{
traverse(e, ans);
}
}
};
//leetcode submit region end(Prohibit modification and deletion)
| 19.596774
| 67
| 0.443621
|
wandsX
|
47dbd807a98370edc068e9a4687d752e159c0fea
| 2,389
|
cpp
|
C++
|
LeetCode/200/148.cpp
|
K-ona/C-_Training
|
d54970f7923607bdc54fc13677220d1b3daf09e5
|
[
"Apache-2.0"
] | null | null | null |
LeetCode/200/148.cpp
|
K-ona/C-_Training
|
d54970f7923607bdc54fc13677220d1b3daf09e5
|
[
"Apache-2.0"
] | null | null | null |
LeetCode/200/148.cpp
|
K-ona/C-_Training
|
d54970f7923607bdc54fc13677220d1b3daf09e5
|
[
"Apache-2.0"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode* next) : val(x), next(next) {}
};
class Solution {
tuple<ListNode*, ListNode*> partition(ListNode* begin, ListNode* end) {
int sep = begin->val;
ListNode* res = begin;
ListNode* head = begin;
ListNode* tail = begin;
while (begin != end) {
// cout << begin->val << " ";
auto next = begin->next;
if (begin->val <= sep) {
begin->next = head;
head = begin;
} else {
begin->next = nullptr;
tail->next = begin;
tail = begin;
}
begin = next;
}
// cout << endl;
tail->next = end;
return {res, head};
}
tuple<ListNode*, ListNode*> quick_sort(ListNode* begin, ListNode* end) {
if (begin->next == end) return {begin, begin};
auto [sep, head] = partition(begin, end);
if (sep == head) {
auto [h, t] = quick_sort(sep->next, end);
sep->next = h;
return {sep, t};
}
auto [h1, t1] = quick_sort(head, sep);
if (sep->next != end) {
auto [h2, t2] = quick_sort(sep->next, end);
t1->next = sep;
sep->next = h2;
return {h1, t2};
} else {
t1->next = sep;
return {h1, sep};
}
}
public:
ListNode* sortList(ListNode* head) {
if (head)
return std::get<0>(quick_sort(head, nullptr));
return nullptr;
}
};
class Solution {
public:
ListNode* sortList(ListNode* head) {
if (!head || !head->next) return head;
auto slow = head, fast = head;
while (fast->next && fast->next->next)
slow = slow->next, fast = fast->next->next;
// 切链
fast = slow->next, slow->next = nullptr;
return merge(sortList(head), sortList(fast));
}
private:
ListNode* merge(ListNode* l1, ListNode* l2) {
ListNode sub(0), *ptr = ⊂
while (l1 && l2) {
auto &node = l1->val < l2->val ? l1 : l2;
ptr = ptr->next = node, node = node->next;
}
ptr->next = l1 ? l1 : l2;
return sub.next;
}
};
int main() {
ListNode e(0);
ListNode d(4, &e);
ListNode c(3, &d);
ListNode b(5, &c);
ListNode a(-1, &b);
Solution().sortList(&a);
}
| 23.421569
| 74
| 0.518627
|
K-ona
|
47e158798760a23cd391c2952c00eed2e8f5ee4c
| 265
|
cpp
|
C++
|
libs/core/render/src/vulkan/detail/bksge_core_render_vulkan_detail_cull_mode.cpp
|
myoukaku/bksge
|
0f8b60e475a3f1709723906e4796b5e60decf06e
|
[
"MIT"
] | 4
|
2018-06-10T13:35:32.000Z
|
2021-06-03T14:27:41.000Z
|
libs/core/render/src/vulkan/detail/bksge_core_render_vulkan_detail_cull_mode.cpp
|
myoukaku/bksge
|
0f8b60e475a3f1709723906e4796b5e60decf06e
|
[
"MIT"
] | 566
|
2017-01-31T05:36:09.000Z
|
2022-02-09T05:04:37.000Z
|
libs/core/render/src/vulkan/detail/bksge_core_render_vulkan_detail_cull_mode.cpp
|
myoukaku/bksge
|
0f8b60e475a3f1709723906e4796b5e60decf06e
|
[
"MIT"
] | 1
|
2018-07-05T04:40:53.000Z
|
2018-07-05T04:40:53.000Z
|
/**
* @file bksge_core_render_vulkan_detail_cull_mode.cpp
*
* @brief CullMode クラスの定義
*
* @author myoukaku
*/
#include <bksge/fnd/config.hpp>
#if !defined(BKSGE_HEADER_ONLY)
#include <bksge/core/render/vulkan/detail/inl/cull_mode_inl.hpp>
#endif
| 20.384615
| 65
| 0.713208
|
myoukaku
|
47e22f8b52fb7c6425212e051080062f04e3f07e
| 5,905
|
cpp
|
C++
|
src/mercury.cpp
|
darkedge/mercury
|
5bdf857b38f68b2a8c6ae1455f7623313ad0af71
|
[
"MIT"
] | null | null | null |
src/mercury.cpp
|
darkedge/mercury
|
5bdf857b38f68b2a8c6ae1455f7623313ad0af71
|
[
"MIT"
] | null | null | null |
src/mercury.cpp
|
darkedge/mercury
|
5bdf857b38f68b2a8c6ae1455f7623313ad0af71
|
[
"MIT"
] | null | null | null |
#include <codeanalysis/warnings.h>
#pragma warning( push, 0 )
#pragma warning( disable : ALL_CODE_ANALYSIS_WARNINGS )
#include "glad/glad.h"
#include "glad.c"
#include "GLFW/glfw3.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#include <stdint.h>
// ImGui
#include "imgui.cpp"
#include "imgui_demo.cpp"
#include "imgui_draw.cpp"
#pragma warning( pop )
#include "mercury.h"
#include "mercury_imgui.cpp"
#include "mercury_input.cpp"
#include "mercury_game.cpp"
#include "mercury_program.cpp"
#include "mercury_math.cpp"
// Tell Optimus to use the high-performance NVIDIA processor
// option if it's on auto-select (we cannot override it)
extern "C" {
_declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
}
static GLFWwindow *s_window;
static float s_deltaTime = 0.0f;
static int32_t s_width = 1280;
static int32_t s_height = 720;
static const char *s_name = "Hello World!";
inline float GetDeltaTime() {
return s_deltaTime;
}
inline GLFWwindow *GetWindow() {
return s_window;
}
inline int32_t GetWindowWidth() {
return s_width;
}
inline int32_t GetWindowHeight() {
return s_height;
}
void CALLBACK debugCallbackARB( GLenum source, GLenum type, GLuint id, GLenum severity,
GLsizei length, const GLchar *message, GLvoid *userParam ) {
if (type == GL_DEBUG_TYPE_OTHER) return;
Log("Type: ");
switch (type)
{
case GL_DEBUG_TYPE_ERROR:
Log("ERROR");
break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
Log("DEPRECATED_BEHAVIOR");
break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
Log("UNDEFINED_BEHAVIOR");
break;
case GL_DEBUG_TYPE_PORTABILITY:
Log("PORTABILITY");
break;
case GL_DEBUG_TYPE_PERFORMANCE:
Log("PERFORMANCE");
break;
case GL_DEBUG_TYPE_OTHER:
Log("OTHER");
break;
}
Log(" - id: %d", id);
Log(" - Severity: ");
switch (severity)
{
case GL_DEBUG_SEVERITY_LOW:
Log("LOW");
break;
case GL_DEBUG_SEVERITY_MEDIUM:
Log("MEDIUM");
break;
case GL_DEBUG_SEVERITY_HIGH:
Log("HIGH");
break;
}
Log(" - %s\n", message);
}
void GlfwErrorCallback( int32_t, const char *description ) {
Log("%s\n", description);
}
void GlfwKeyCallBack( GLFWwindow* window, int32_t key, int32_t scancode, int32_t action, int32_t mods ) {
if ( key == GLFW_KEY_ESCAPE && action == GLFW_PRESS ) {
glfwSetWindowShouldClose( window, GL_TRUE );
}
if ( action == GLFW_PRESS ) {
Input::SetKey( key, true );
}
if ( action == GLFW_RELEASE ) {
Input::SetKey( key, false );
}
ImGui_ImplGlfwGL3_KeyCallback(window, key, scancode, action, mods);
}
void GlfwMouseButtonCallback( GLFWwindow *window, int32_t button, int32_t action, int32_t mods ) {
if ( action == GLFW_PRESS ) {
Input::SetMouseButton( button, true );
}
if ( action == GLFW_RELEASE ) {
Input::SetMouseButton( button, false );
}
if(!Input::IsMouseGrabbed()) {
ImGui_ImplGlfwGL3_MouseButtonCallback(window, button, action, mods);
}
}
void GlfwScrollCallback( GLFWwindow *window, double xoffset, double yoffset ) {
ImGui_ImplGlfwGL3_ScrollCallback(window, xoffset, yoffset);
}
void GlfwCharCallback( GLFWwindow *window, uint32_t codepoint ) {
ImGui_ImplGlfwGL3_CharCallback(window, codepoint);
}
void GlfwCursorPosCallback( GLFWwindow *window, double xpos, double ypos ) {
Input::SetMousePosition( float2 { (float) xpos, (float) ypos } );
}
void GlfwWindowSizeCallBack( GLFWwindow *window, int32_t width, int32_t height ) {
// TODO
//Application::SetWidth( width );
//Application::SetHeight( height );
}
void EnterWindowLoop() {
Init(); // Slow
double lastTime = glfwGetTime();
while ( !glfwWindowShouldClose( s_window ) )
{
double now = glfwGetTime();
s_deltaTime = (float) ( now - lastTime );
lastTime = now;
glfwPollEvents();
Input::Tick();
Tick();
Input::PostTick();
glfwSwapBuffers( s_window );
}
glfwDestroyWindow( s_window );
glfwTerminate();
std::exit( EXIT_SUCCESS );
}
int CALLBACK WinMain(
_In_ HINSTANCE hInstance,
_In_ HINSTANCE hPrevInstance,
_In_ LPSTR lpCmdLine,
_In_ int nCmdShow
) {
glfwSetErrorCallback( GlfwErrorCallback );
if ( glfwInit() ) {
// Window hints
glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR, 4 );
glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, 5 );
glfwWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE );
s_window = glfwCreateWindow( s_width, s_height, s_name, nullptr, nullptr );
glfwMakeContextCurrent( s_window );
// TODO: Callbacks
glfwSetKeyCallback( s_window, GlfwKeyCallBack );
glfwSetMouseButtonCallback( s_window, GlfwMouseButtonCallback );
glfwSetScrollCallback( s_window, GlfwScrollCallback );
glfwSetCharCallback( s_window, GlfwCharCallback );
glfwSetCursorPosCallback( s_window, GlfwCursorPosCallback );
glfwSetWindowSizeCallback( s_window, GlfwWindowSizeCallBack );
ImGui_ImplGlfwGL3_Init(s_window, false);
// Sync to monitor refresh rate
glfwSwapInterval( 1 );
/************************************************************************/
/* OpenGL */
/************************************************************************/
if ( gladLoadGLLoader((GLADloadproc) glfwGetProcAddress) ) {
Log("OpenGL %d.%d\n", GLVersion.major, GLVersion.minor);
glEnable( GL_BLEND );
glEnable( GL_MULTISAMPLE );
glEnable( GL_CULL_FACE );
glEnable( GL_DEPTH_TEST );
glClearColor( 0.192156862745098f, 0.3019607843137255f, 0.4745098039215686f, 1.0f );
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
glDepthFunc( GL_LEQUAL );
// https://www.opengl.org/wiki/Debug_Output
glDebugMessageCallback( (GLDEBUGPROC) debugCallbackARB, nullptr );
glEnable( GL_DEBUG_OUTPUT );
glEnable( GL_DEBUG_OUTPUT_SYNCHRONOUS );
EnterWindowLoop();
} else {
printf( "Failed to init glad!\n" );
std::exit( EXIT_FAILURE );
}
} else {
printf( "Failed to init GLFW!\n" );
std::exit( EXIT_FAILURE );
}
}
| 25.343348
| 105
| 0.695512
|
darkedge
|
47e9bfdb27625f3517d82ddced901e0cc185a5da
| 182
|
cpp
|
C++
|
docs/mfc/codesnippet/CPP/cfontdialog-class_8.cpp
|
jmittert/cpp-docs
|
cea5a8ee2b4764b2bac4afe5d386362ffd64e55a
|
[
"CC-BY-4.0",
"MIT"
] | 14
|
2018-01-28T18:10:55.000Z
|
2021-11-16T13:21:18.000Z
|
docs/mfc/codesnippet/CPP/cfontdialog-class_8.cpp
|
jmittert/cpp-docs
|
cea5a8ee2b4764b2bac4afe5d386362ffd64e55a
|
[
"CC-BY-4.0",
"MIT"
] | null | null | null |
docs/mfc/codesnippet/CPP/cfontdialog-class_8.cpp
|
jmittert/cpp-docs
|
cea5a8ee2b4764b2bac4afe5d386362ffd64e55a
|
[
"CC-BY-4.0",
"MIT"
] | 2
|
2018-11-01T12:33:08.000Z
|
2021-11-16T13:21:19.000Z
|
// Is the selected font bold?
CFontDialog dlg;
if (dlg.DoModal() == IDOK)
{
BOOL bold = dlg.IsBold();
TRACE(_T("Is the selected font bold? %d\n"), bold);
}
| 26
| 57
| 0.56044
|
jmittert
|
47ea21529b3531fee3ea9b666be608dbeac4ac54
| 25,678
|
cpp
|
C++
|
released_plugins/v3d_plugins/bigneuron_LinGU_LCM_boost/components.cpp
|
zzhmark/vaa3d_tools
|
3ca418add85a59ac7e805d55a600b78330d7e53d
|
[
"MIT"
] | 1
|
2021-12-27T19:14:03.000Z
|
2021-12-27T19:14:03.000Z
|
released_plugins/v3d_plugins/bigneuron_LinGU_LCM_boost/components.cpp
|
zzhmark/vaa3d_tools
|
3ca418add85a59ac7e805d55a600b78330d7e53d
|
[
"MIT"
] | 1
|
2016-12-03T05:33:13.000Z
|
2016-12-03T05:33:13.000Z
|
released_plugins/v3d_plugins/bigneuron_LinGU_LCM_boost/components.cpp
|
zzhmark/vaa3d_tools
|
3ca418add85a59ac7e805d55a600b78330d7e53d
|
[
"MIT"
] | null | null | null |
/*
* components.cpp
*
* Created on: May 20, 2015
* Author: gulin
*/
# include <cstdlib>
# include <iostream>
# include <iomanip>
# include <fstream>
# include <ctime>
# include <cmath>
# include <cstring>
using namespace std;
# include "components.hpp"
//****************************************************************************80
int file_column_count ( string filename )
//****************************************************************************80
//
// Purpose:
//
// FILE_COLUMN_COUNT counts the columns in the first line of a file.
//
// Discussion:
//
// The file is assumed to be a simple text file.
//
// Most lines of the file are presumed to consist of COLUMN_NUM words,
// separated by spaces. There may also be some blank lines, and some
// comment lines, which have a "#" in column 1.
//
// The routine tries to find the first non-comment non-blank line and
// counts the number of words in that line.
//
// If all lines are blanks or comments, it goes back and tries to analyze
// a comment line.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 05 July 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, string FILENAME, the name of the file.
//
// Output, int FILE_COLUMN_COUNT, the number of columns assumed
// to be in the file.
//
{
int column_num;
ifstream input;
bool got_one;
string text;
//
// Open the file.
//
input.open ( filename.c_str ( ) );
if ( !input )
{
column_num = -1;
cerr << "\n";
cerr << "FILE_COLUMN_COUNT - Fatal error!\n";
cerr << " Could not open the file:\n";
cerr << " \"" << filename << "\"\n";
exit ( 1 );
}
//
// Read one line, but skip blank lines and comment lines.
//
got_one = false;
for ( ; ; )
{
getline ( input, text );
if ( input.eof ( ) )
{
break;
}
if ( s_len_trim ( text ) <= 0 )
{
continue;
}
if ( text[0] == '#' )
{
continue;
}
got_one = true;
break;
}
if ( !got_one )
{
input.close ( );
input.open ( filename.c_str ( ) );
for ( ; ; )
{
input >> text;
if ( input.eof ( ) )
{
break;
}
if ( s_len_trim ( text ) == 0 )
{
continue;
}
got_one = true;
break;
}
}
input.close ( );
if ( !got_one )
{
cerr << "\n";
cerr << "FILE_COLUMN_COUNT - Warning!\n";
cerr << " The file does not seem to contain any data.\n";
return -1;
}
column_num = s_word_count ( text );
return column_num;
}
//****************************************************************************80
int file_row_count ( string input_filename )
//****************************************************************************80
//
// Purpose:
//
// FILE_ROW_COUNT counts the number of row records in a file.
//
// Discussion:
//
// It does not count lines that are blank, or that begin with a
// comment symbol '#'.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 23 February 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, string INPUT_FILENAME, the name of the input file.
//
// Output, int FILE_ROW_COUNT, the number of rows found.
//
{
//int bad_num;
int comment_num;
ifstream input;
// int i;
string line;
int record_num;
int row_num;
row_num = 0;
comment_num = 0;
record_num = 0;
//bad_num = 0;
input.open ( input_filename.c_str ( ) );
if ( !input )
{
cerr << "\n";
cerr << "FILE_ROW_COUNT - Fatal error!\n";
cerr << " Could not open the input file: \"" << input_filename << "\"\n";
exit ( 1 );
}
for ( ; ; )
{
getline ( input, line );
if ( input.eof ( ) )
{
break;
}
record_num = record_num + 1;
if ( line[0] == '#' )
{
comment_num = comment_num + 1;
continue;
}
if ( s_len_trim ( line ) == 0 )
{
comment_num = comment_num + 1;
continue;
}
row_num = row_num + 1;
}
input.close ( );
return row_num;
}
//****************************************************************************80
int i4_min ( int i1, int i2 )
//****************************************************************************80
//
// Purpose:
//
// I4_MIN returns the minimum of two I4's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 13 October 1998
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int I1, I2, two integers to be compared.
//
// Output, int I4_MIN, the smaller of I1 and I2.
//
{
int value;
if ( i1 < i2 )
{
value = i1;
}
else
{
value = i2;
}
return value;
}
//****************************************************************************80
int i4block_components ( int l, int m, int n, int *a, int *c )
//****************************************************************************80
//
// Purpose:
//
// I4BLOCK_COMPONENTS assigns contiguous nonzero pixels to a common component.
//
// Discussion:
//
// On input, the A array contains values of 0 or 1.
//
// The 0 pixels are to be ignored. The 1 pixels are to be grouped
// into connected components.
//
// The pixel A(I,J,K) is "connected" to the pixels:
//
// A(I-1,J, K ), A(I+1,J, K ),
// A(I, J-1,K ), A(I, J+1,K ),
// A(I, J, K-1), A(I, J, K+1),
//
// so most pixels have 6 neighbors.
//
// On output, COMPONENT_NUM reports the number of components of nonzero
// data, and the array C contains the component assignment for
// each nonzero pixel, and is 0 for zero pixels.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 February 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int L, M, N, the order of the array.
//
// Input, int A[L*M*N], the pixel array.
//
// Output, int C[L*M*N], the component array.
//
// Output, int I4BLOCK_COMPONENTS, the number of components
// of nonzero data.
//
{
int b;
int c1;
// int c2;
int component;
int component_num;
int i;
int j;
int k;
int north;
int *p;
int *q;
int up;
int west;
//
// Initialization.
//
for ( k = 0; k < n; k++ )
{
for ( j = 0; j < m; j++ )
{
for ( i = 0; i < l; i++ )
{
c[i+j*l+k*l*m] = 0;
}
}
}
component_num = 0;
//
// P is simply used to store the component labels. The dimension used
// here is, of course, usually an absurd overestimate.
//
p = new int[l*m*n+1];
for ( i = 0; i <= l * m * n; i++ )
{
p[i] = i;
}
//
// "Read" the array one pixel at a time. If a (nonzero) pixel has a north or
// west neighbor with a label, the current pixel inherits it.
// In case the labels disagree, we need to adjust the P array so we can
// later deal with the fact that the two labels need to be merged.
//
for ( i = 0; i < l; i++ )
{
for ( j = 0; j < m; j++ )
{
for ( k = 0; k < n; k++ )
{
if ( i == 0 )
{
north = 0;
}
else
{
north = c[i-1+j*l+k*l*m];
}
if ( j == 0 )
{
west = 0;
}
else
{
west = c[i+(j-1)*l+k*l*m];
}
if ( k == 0 )
{
up = 0;
}
else
{
up = c[i+j*l+(k-1)*l*m];
}
if ( a[i+j*l+k*l*m] != 0 )
{
//
// New component?
//
if ( north == 0 && west == 0 && up == 0 )
{
component_num = component_num + 1;
c[i+j*l+k*l*m] = component_num;
}
//
// One predecessor is labeled.
//
else if ( north != 0 && west == 0 && up == 0 )
{
c[i+j*l+k*l*m] = north;
}
else if ( north == 0 && west != 0 && up == 0 )
{
c[i+j*l+k*l*m] = west;
}
else if ( north == 0 && west == 0 && up != 0 )
{
c[i+j*l+k*l*m] = up;
}
//
// Two predecessors are labeled.
//
else if ( north == 0 && west != 0 && up != 0 )
{
c[i+j*l+k*l*m] = i4_min ( west, up );
c1 = i4_min ( p[west], p[up] );
p[west] = c1;
p[up] = c1;
}
else if ( north != 0 && west == 0 && up != 0 )
{
c[i+j*l+k*l*m] = i4_min ( north, up );
c1 = i4_min ( p[north], p[up] );
p[north] = c1;
p[up] = c1;
}
else if ( north != 0 && west != 0 && up == 0 )
{
c[i+j*l+k*l*m] = i4_min ( north, west );
c1 = i4_min ( p[north], p[west] );
p[north] = c1;
p[west] = c1;
}
//
// Three predecessors are labeled.
//
else if ( north != 0 && west != 0 && up != 0 )
{
c[i+j*l+k*l*m] = i4_min ( north, i4_min ( west, up ) );
c1 = i4_min ( p[north], i4_min ( p[west], p[up] ) );
p[north] = c1;
p[west] = c1;
p[up] = c1;
}
}
}
}
}
//
// When a component has multiple labels, have the higher labels
// point to the lowest one.
//
for ( component = component_num; 1 <= component; component-- )
{
b = component;
while ( p[b] != b )
{
b = p[b];
}
p[component] = b;
}
//
// Locate the minimum label for each component.
// Assign these mininum labels new consecutive indices.
//
q = new int[component_num+1];
for ( j = 0; j <= component_num; j++ )
{
q[j] = 0;
}
i = 0;
for ( component = 1; component <= component_num; component++ )
{
if ( p[component] == component )
{
i = i + 1;
q[component] = i;
}
}
component_num = i;
//
// Replace the labels by consecutive labels.
//
for ( i = 0; i < l; i++ )
{
for ( j = 0; j < m; j++ )
{
for ( k = 0; k < n; k++ )
{
c[i+j*l+k*l*m] = q [ p [ c[i+j*l+k*l*m] ] ];
}
}
}
delete [] p;
delete [] q;
return component_num;
}
//****************************************************************************80
int i4mat_components ( int m, int n, int a[], int c[] )
//****************************************************************************80
//
// Purpose:
//
// I4MAT_COMPONENTS assigns contiguous nonzero pixels to a common component.
//
// Discussion:
//
// On input, the A array contains values of 0 or 1.
//
// The 0 pixels are to be ignored. The 1 pixels are to be grouped
// into connected components.
//
// The pixel A(I,J) is "connected" to the pixels A(I-1,J), A(I+1,J),
// A(I,J-1) and A(I,J+1), so most pixels have 4 neighbors.
//
// (Another choice would be to assume that a pixel was connected
// to the other 8 pixels in the 3x3 block containing it.)
//
// On output, COMPONENT_NUM reports the number of components of nonzero
// data, and the array C contains the component assignment for
// each nonzero pixel, and is 0 for zero pixels.
//
// Picture:
//
// Input A:
//
// 0 2 0 0 17 0 3
// 0 0 3 0 1 0 4
// 1 0 4 8 8 0 7
// 3 0 6 45 0 0 0
// 3 17 0 5 9 2 5
//
// Output:
//
// COMPONENT_NUM = 4
//
// C:
//
// 0 1 0 0 2 0 3
// 0 0 2 0 2 0 3
// 4 0 2 2 2 0 3
// 4 0 2 2 0 0 0
// 4 4 0 2 2 2 2
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 March 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the order of the array.
//
// Input, int A[M*N], the pixel array.
//
// Output, int C[M*N], the component array.
//
// Output, int I4MAT_COMPONENTS, the number of components
// of nonzero data.
//
{
int b;
int component;
int component_num;
int i;
int j;
int north;
int *p;
int *q;
int west;
//
// Initialization.
//
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
c[i+j*m] = 0;
}
}
component_num = 0;
//
// P is simply used to store the component labels. The dimension used
// here is, of course, usually an absurd overestimate.
//
p = new int[m*n+1];
for ( i = 0; i <= m * n; i++ )
{
p[i] = i;
}
//
// "Read" the array one pixel at a time. If a (nonzero) pixel has a north or
// west neighbor with a label, the current pixel inherits it.
// In case the labels disagree, we need to adjust the P array so we can
// later deal with the fact that the two labels need to be merged.
//
for ( i = 0; i < m; i++ )
{
for ( j = 0; j < n; j++ )
{
if ( i == 0 )
{
north = 0;
}
else
{
north = c[i-1+j*m];
}
if ( j == 0 )
{
west = 0;
}
else
{
west = c[i+(j-1)*m];
}
if ( a[i+j*m] != 0 )
{
if ( north == 0 )
{
if ( west == 0 )
{
component_num = component_num + 1;
c[i+j*m] = component_num;
}
else
{
c[i+j*m] = west;
}
}
else if ( north != 0 )
{
if ( west == 0 || west == north )
{
c[i+j*m] = north;
}
else
{
c[i+j*m] = i4_min ( north, west );
if ( north < west )
{
p[west] = north;
}
else
{
p[north] = west;
}
}
}
}
}
}
//
// When a component has multiple labels, have the higher labels
// point to the lowest one.
//
for ( component = component_num; 1 <= component; component-- )
{
b = component;
while ( p[b] != b )
{
b = p[b];
}
p[component] = b;
}
//
// Locate the minimum label for each component.
// Assign these mininum labels new consecutive indices.
//
q = new int[component_num+1];
for ( j = 0; j <= component_num; j++ )
{
q[j] = 0;
}
i = 0;
for ( component = 1; component <= component_num; component++ )
{
if ( p[component] == component )
{
i = i + 1;
q[component] = i;
}
}
component_num = i;
//
// Replace the labels by consecutive labels.
//
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
c[i+j*m] = q [ p [ c[i+j*m] ] ];
}
}
delete [] p;
delete [] q;
return component_num;
}
//****************************************************************************80
int *i4mat_data_read ( string input_filename, int m, int n )
//****************************************************************************80
//
// Purpose:
//
// I4MAT_DATA_READ reads data from an I4MAT file.
//
// Discussion:
//
// An I4MAT is an array of I4's.
//
// The file is assumed to contain one record per line.
//
// Records beginning with '#' are comments, and are ignored.
// Blank lines are also ignored.
//
// Each line that is not ignored is assumed to contain exactly (or at least)
// M real numbers, representing the coordinates of a point.
//
// There are assumed to be exactly (or at least) N such records.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 23 February 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, string INPUT_FILENAME, the name of the input file.
//
// Input, int M, the number of spatial dimensions.
//
// Input, int N, the number of points. The program
// will stop reading data once N values have been read.
//
// Output, int I4MAT_DATA_READ[M*N], the data.
//
{
bool error;
ifstream input;
int i;
int j;
string line;
int *table;
int *x;
input.open ( input_filename.c_str ( ) );
if ( !input )
{
cerr << "\n";
cerr << "I4MAT_DATA_READ - Fatal error!\n";
cerr << " Could not open the input file: \"" << input_filename << "\"\n";
exit ( 1 );
}
table = new int[m*n];
x = new int[m];
j = 0;
while ( j < n )
{
getline ( input, line );
if ( input.eof ( ) )
{
break;
}
if ( line[0] == '#' || s_len_trim ( line ) == 0 )
{
continue;
}
error = s_to_i4vec ( line, m, x );
if ( error )
{
continue;
}
for ( i = 0; i < m; i++ )
{
table[i+j*m] = x[i];
}
j = j + 1;
}
input.close ( );
delete [] x;
return table;
}
//****************************************************************************80
void i4mat_header_read ( string input_filename, int *m, int *n )
//****************************************************************************80
//
// Purpose:
//
// I4MAT_HEADER_READ reads the header from an I4MAT file.
//
// Discussion:
//
// An I4MAT is an array of I4's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 23 February 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, string INPUT_FILENAME, the name of the input file.
//
// Output, int *M, the number of spatial dimensions.
//
// Output, int *N, the number of points
//
{
*m = file_column_count ( input_filename );
if ( *m <= 0 )
{
cerr << "\n";
cerr << "I4MAT_HEADER_READ - Fatal error!\n";
cerr << " FILE_COLUMN_COUNT failed.\n";
exit ( 1 );
}
*n = file_row_count ( input_filename );
if ( *n <= 0 )
{
cerr << "\n";
cerr << "I4MAT_HEADER_READ - Fatal error!\n";
cerr << " FILE_ROW_COUNT failed.\n";
exit ( 1 );
}
return;
}
//****************************************************************************80
int i4vec_components ( int n, int a[], int c[] )
//****************************************************************************80
//
// Purpose:
//
// I4VEC_COMPONENTS assigns contiguous nonzero pixels to a common component.
//
// Discussion:
//
// This calculation is trivial compared to the 2D problem, and is included
// primarily for comparison.
//
// On input, the A array contains values of 0 or 1.
//
// The 0 pixels are to be ignored. The 1 pixels are to be grouped
// into connected components.
//
// The pixel A(I) is "connected" to the pixels A(I-1) and A(I+1).
//
// On output, COMPONENT_NUM reports the number of components of nonzero
// data, and the array C contains the component assignment for
// each nonzero pixel, and is 0 for zero pixels.
//
// Picture:
//
// Input A:
//
// 0 0 1 2 4 0 0 4 0 0 0 8 9 9 1 2 3 0 0 5 0 1 6 0 0 0 4 0
//
// Output:
//
// COMPONENT_NUM = 6
//
// C:
//
// 0 0 1 1 1 0 0 2 0 0 0 3 3 3 3 3 3 0 0 4 0 5 5 0 0 0 6 0
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 March 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the order of the vector.
//
// Input, int A(N), the pixel array.
//
// Output, int C[N], the component array.
//
// Output, int I4VEC_COMPONENTS, the number of components
// of nonzero data.
//
{
int component_num;
int j;
int west;
//
// Initialization.
//
for ( j = 0; j < n; j++ )
{
c[j] = 0;
}
component_num = 0;
//
// "Read" the array one pixel at a time. If a (nonzero) pixel has a west
// neighbor with a label, the current pixel inherits it. Otherwise, we have
// begun a new component.
//
west = 0;
for ( j = 0; j < n; j++ )
{
if ( a[j] != 0 )
{
if ( west == 0 )
{
component_num = component_num + 1;
}
c[j] = component_num;
}
west = c[j];
}
return component_num;
}
//****************************************************************************80
int s_len_trim ( string s )
//****************************************************************************80
//
// Purpose:
//
// S_LEN_TRIM returns the length of a string to the last nonblank.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 05 July 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, string S, a string.
//
// Output, int S_LEN_TRIM, the length of the string to the last nonblank.
// If S_LEN_TRIM is 0, then the string is entirely blank.
//
{
int n;
n = s.length ( );
while ( 0 < n )
{
if ( s[n-1] != ' ' )
{
return n;
}
n = n - 1;
}
return n;
}
//****************************************************************************80
int s_to_i4 ( string s, int *last, bool *error )
//****************************************************************************80
//
// Purpose:
//
// S_TO_I4 reads an I4 from a string.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 05 July 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, string S, a string to be examined.
//
// Output, int *LAST, the last character of S used to make IVAL.
//
// Output, bool *ERROR is TRUE if an error occurred.
//
// Output, int *S_TO_I4, the integer value read from the string.
// If the string is blank, then IVAL will be returned 0.
//
{
char c;
int i;
int isgn;
int istate;
int ival;
*error = false;
istate = 0;
isgn = 1;
i = 0;
ival = 0;
for ( ; ; )
{
c = s[i];
i = i + 1;
//
// Haven't read anything.
//
if ( istate == 0 )
{
if ( c == ' ' )
{
}
else if ( c == '-' )
{
istate = 1;
isgn = -1;
}
else if ( c == '+' )
{
istate = 1;
isgn = + 1;
}
else if ( '0' <= c && c <= '9' )
{
istate = 2;
ival = c - '0';
}
else
{
*error = true;
return ival;
}
}
//
// Have read the sign, expecting digits.
//
else if ( istate == 1 )
{
if ( c == ' ' )
{
}
else if ( '0' <= c && c <= '9' )
{
istate = 2;
ival = c - '0';
}
else
{
*error = true;
return ival;
}
}
//
// Have read at least one digit, expecting more.
//
else if ( istate == 2 )
{
if ( '0' <= c && c <= '9' )
{
ival = 10 * (ival) + c - '0';
}
else
{
ival = isgn * ival;
*last = i - 1;
return ival;
}
}
}
//
// If we read all the characters in the string, see if we're OK.
//
if ( istate == 2 )
{
ival = isgn * ival;
*last = s_len_trim ( s );
}
else
{
*error = true;
*last = 0;
}
return ival;
}
//****************************************************************************80
bool s_to_i4vec ( string s, int n, int ivec[] )
//****************************************************************************80
//
// Purpose:
//
// S_TO_I4VEC reads an I4VEC from a string.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 05 July 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, string S, the string to be read.
//
// Input, int N, the number of values expected.
//
// Output, int IVEC[N], the values read from the string.
//
// Output, bool S_TO_I4VEC, is TRUE if an error occurred.
//
{
int begin;
bool error;
int i;
int lchar;
int length;
begin = 0;
length = s.length ( );
error = 0;
for ( i = 0; i < n; i++ )
{
ivec[i] = s_to_i4 ( s.substr(begin,length), &lchar, &error );
if ( error )
{
return error;
}
begin = begin + lchar;
length = length - lchar;
}
return error;
}
//****************************************************************************80
int s_word_count ( string s )
//****************************************************************************80
//
// Purpose:
//
// S_WORD_COUNT counts the number of "words" in a string.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 05 July 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, string S, the string to be examined.
//
// Output, int S_WORD_COUNT, the number of "words" in the string.
// Words are presumed to be separated by one or more blanks.
//
{
bool blank;
int char_count;
int i;
int word_count;
word_count = 0;
blank = true;
char_count = s.length ( );
for ( i = 0; i < char_count; i++ )
{
if ( isspace ( s[i] ) )
{
blank = true;
}
else if ( blank )
{
word_count = word_count + 1;
blank = false;
}
}
return word_count;
}
//****************************************************************************80
void timestamp ( )
//****************************************************************************80
//
// Purpose:
//
// TIMESTAMP prints the current YMDHMS date as a time stamp.
//
// Example:
//
// 31 May 2001 09:45:54 AM
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 08 July 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// None
//
{
# define TIME_SIZE 40
static char time_buffer[TIME_SIZE];
const struct std::tm *tm_ptr;
//size_t len;
std::time_t now;
now = std::time ( NULL );
tm_ptr = std::localtime ( &now );
//len = std::strftime ( time_buffer, TIME_SIZE, "%d %B %Y %I:%M:%S %p", tm_ptr );
std::cout << time_buffer << "\n";
return;
# undef TIME_SIZE
}
| 19.162687
| 83
| 0.467404
|
zzhmark
|
47ea935abdcb6cafecbcd071877e2c7547f5d0c5
| 17,028
|
cpp
|
C++
|
partman/loader.cpp
|
XplosiveLugnut/3d-pinball-space-cadet
|
5bf9b86f379a3d28321a4d29df03965ff1245fad
|
[
"MIT"
] | 1
|
2021-04-23T12:50:21.000Z
|
2021-04-23T12:50:21.000Z
|
partman/loader.cpp
|
XplosiveLugnut/3d-pinball-space-cadet
|
5bf9b86f379a3d28321a4d29df03965ff1245fad
|
[
"MIT"
] | null | null | null |
partman/loader.cpp
|
XplosiveLugnut/3d-pinball-space-cadet
|
5bf9b86f379a3d28321a4d29df03965ff1245fad
|
[
"MIT"
] | null | null | null |
//
// Created by neo on 2019-08-15.
//
#include "../pinball.h"
//----- (01008F7A) --------------------------------------------------------
signed int loader_error(int a1, int a2)
{
int v2; // eax
const CHAR *v3; // esi
const CHAR *v4; // edi
int v5; // edx
int v6; // ecx
v2 = loader_errors[0];
v3 = 0;
v4 = 0;
v5 = 0;
if ( loader_errors[0] < 0 )
goto LABEL_13;
v6 = 0;
do
{
if ( a1 == v2 )
v3 = off_10235FC[v6];
if ( a2 == v2 )
v4 = off_10235FC[v6];
v6 = 2 * ++v5;
v2 = loader_errors[2 * v5];
}
while ( v2 >= 0 );
if ( !v3 )
LABEL_13:
v3 = off_10235FC[2 * v5];
MessageBoxA(0, v3, v4, 0x2000u);
return -1;
}
// 10235F8: using guessed type int loader_errors[];
//----- (01008FE0) --------------------------------------------------------
DWORD *loader_default_vsi(DWORD *a1)
{
DWORD *result; // eax
result = a1;
a1[13] = 0;
a1[5] = 1369940824;
a1[12] = 0;
*a1 = 1064514355;
a1[1] = 1058642330;
a1[2] = 0;
a1[4] = 0;
a1[16] = 0;
a1[17] = 0;
a1[15] = 0;
a1[14] = 0;
return result;
}
//----- (0100901F) --------------------------------------------------------
signed int loader_get_sound_id(int a1)
{
signed int v1; // dx
signed int v2; // eax
signed int result; // eax
signed int v4; // edi
int v5; // esi
int v6; // eax
WORD *v7; // eax
const CHAR *lpName; // ST18_4
HFILE hFile; // ST1C_4
int v10; // [esp+10h] [ebp+8h]
v1 = 1;
if ( sound_count <= 1 )
{
LABEL_5:
loader_error(25, 26);
result = -1;
}
else
{
v2 = 1;
while ( dword_1027C24[5 * v2] != a1 )
{
v2 = ++v1;
if ( v1 >= sound_count )
goto LABEL_5;
}
v4 = v1;
v5 = 5 * v1;
if ( !dword_1027C28[v5] && !sound_list[v5] )
{
v6 = dword_1027C24[v5];
*(float *)&algn_1027C2C[20 * v1] = 0.0;
v10 = v6;
if ( v6 > 0 && !play_midi_music )
{
v7 = (WORD *)partman_field(loader_table, v6, 0);
if ( v7 )
{
if ( *v7 == 202 )
{
lpName = (const CHAR *)partman_field(loader_table, v10, 9);
hFile = _lopen(lpName, 0);
*(float *)(v5 * 4 + 16940076) = (double)_llseek(hFile, 0, 2) * 0.0000909090909090909;
_lclose(hFile);
sound_list[v5] = (int)Sound_LoadWaveFile(lpName);
}
}
}
}
++dword_1027C28[v5];
result = v4;
}
return result;
}
// 10236D8: using guessed type int sound_count;
// 102556C: using guessed type int play_midi_music;
// 1027C20: using guessed type int sound_list[];
// 1027C24: using guessed type int dword_1027C24[];
// 1027C28: using guessed type int dword_1027C28[];
//----- (0100911D) --------------------------------------------------------
void loader_unload()
{
signed int v0; // esi
LPCVOID *v1; // edi
v0 = 1;
if ( sound_count > 1 )
{
v1 = (LPCVOID *)&unk_1027C34;
do
{
Sound_FreeSound(*v1);
++v0;
v1 += 5;
}
while ( v0 < sound_count );
}
if ( dword_1027C30[5 * v0] )
memoryfree(dword_1027C30[5 * v0]);
sound_count = 1;
}
// 10236D8: using guessed type int sound_count;
// 1027C30: using guessed type int dword_1027C30[];
//----- (0100916A) --------------------------------------------------------
int loader_loadfrom(WORD *a1)
{
WORD *v1; // edx
int v2; // di
WORD *v3; // eax
int result; // eax
int v5; // ecx
v1 = a1;
v2 = 0;
loader_table = (int)a1;
if ( *a1 <= 0 )
{
result = sound_count;
}
else
{
do
{
v3 = (WORD *)partman_field((int)v1, v2, 0);
v1 = (WORD *)loader_table;
if ( v3 && *v3 == 202 )
{
result = sound_count;
sound_record_table = loader_table;
if ( sound_count < 65 )
{
v5 = 5 * sound_count;
sound_list[v5] = 0;
++result;
dword_1027C24[v5] = v2;
sound_count = result;
}
}
else
{
result = sound_count;
}
++v2;
}
while ( v2 < *v1 );
}
loader_sound_count = result;
return result;
}
// 10236D8: using guessed type int sound_count;
// 1027C10: using guessed type int sound_record_table;
// 1027C20: using guessed type int sound_list[];
// 1027C24: using guessed type int dword_1027C24[];
// 1028134: using guessed type int loader_sound_count;
//----- (010091EB) --------------------------------------------------------
int loader_query_handle(const char * lpString)
{
return partman_record_labeled(loader_table, lpString);
}
//----- (01009207) --------------------------------------------------------
signed int loader_query_visual_states(int a1)
{
signed int result; // eax
WORD *v2; // eax
if ( a1 < 0 )
return loader_error(0, 17);
v2 = (WORD *)partman_field(loader_table, a1, 10);
if ( v2 && *v2 == 100 )
result = (signed int)v2[1];
else
result = 1;
return result;
}
//----- (01009249) --------------------------------------------------------
signed int loader_material(int a1, DWORD *a2)
{
int v2; // edi
WORD *v4; // eax
float *v5; // esi
unsigned int v6; // ebx
double v7; // st7
DWORD *v8; // esi
double v9; // st7
signed __int64 v10; // rax
int v11; // [esp+1Ch] [ebp+8h]
int v12; // [esp+1Ch] [ebp+8h]
v2 = a1;
if ( a1 < 0 )
return loader_error(0, 21);
v4 = (WORD *)partman_field(loader_table, a1, 0);
if ( !v4 )
return loader_error(1, 21);
if ( *v4 == 300 )
{
v5 = (float *)partman_field(loader_table, a1, 11);
if ( !v5 )
return loader_error(11, 21);
v11 = 0;
v6 = (unsigned int)partman_field_size(loader_table, v2, 11) >> 2;
if ( (signed int)v6 <= 0 )
return 0;
while ( 1 )
{
v7 = *v5;
v8 = v5 + 1;
v12 = v11 + 1;
v9 = _floor(v7);
switch ( (signed int)(signed __int64)v9 )
{
case 301:
*a2 = *v8;
break;
case 302:
a2[1] = *v8;
break;
case 304:
v10 = (signed __int64)_floor(*(float *)v8);
a2[4] = loader_get_sound_id((signed int)v10);
break;
default:
return loader_error(9, 21);
}
v5 = (float *)(v8 + 1);
v11 = v12 + 1;
if ( (signed int)v11 >= (signed int)v6 )
return 0;
}
}
return loader_error(3, 21);
}
//----- (01009349) --------------------------------------------------------
signed int loader_kicker(int a1, DWORD *a2)
{
WORD *v3; // eax
float *v4; // esi
double v5; // st7
DWORD *v6; // esi
double v7; // st7
signed __int64 v8; // rax
int v9; // eax
DWORD *v10; // esi
int v11; // eax
int v12; // eax
unsigned int v13; // [esp+14h] [ebp-4h]
int v14; // [esp+20h] [ebp+8h]
int v15; // [esp+20h] [ebp+8h]
if ( a1 < 0 )
return loader_error(0, 20);
v3 = (WORD *)partman_field(loader_table, a1, 0);
if ( !v3 )
return loader_error(1, 20);
if ( *v3 != 400 )
return loader_error(4, 20);
v4 = (float *)partman_field(loader_table, a1, 11);
if ( !v4 )
return loader_error(11, 20);
v13 = (unsigned int)partman_field_size(loader_table, a1, 11) >> 2;
v14 = 0;
if ( (signed int)v13 <= 0 )
return 0;
while ( 1 )
{
v5 = *v4;
v6 = v4 + 1;
v15 = v14 + 1;
v7 = _floor(v5);
switch ( (signed int)(signed __int64)v7 )
{
case 401:
*a2 = *v6;
goto LABEL_24;
case 402:
a2[1] = *v6;
goto LABEL_24;
case 403:
a2[2] = *v6;
goto LABEL_24;
}
if ( (signed int)(signed __int64)v7 != 404 )
break;
v9 = *v6;
v10 = v6 + 1;
a2[3] = v9;
v11 = *v10;
++v10;
a2[4] = v11;
v12 = *v10;
v4 = (float *)(v10 + 1);
v14 = v15 + 3;
a2[5] = v12;
LABEL_25:
if ( (signed int)v14 >= (signed int)v13 )
return 0;
}
if ( (signed int)(signed __int64)v7 == 405 )
{
a2[6] = *v6;
goto LABEL_24;
}
if ( (signed int)(signed __int64)v7 == 406 )
{
v8 = (signed __int64)_floor(*(float *)v6);
a2[7] = loader_get_sound_id((signed int)v8);
LABEL_24:
v4 = (float *)(v6 + 1);
v14 = v15 + 1;
goto LABEL_25;
}
return loader_error(10, 20);
}
//----- (01009486) --------------------------------------------------------
signed int loader_state_id(int a1, signed int a2)
{
int v2; // esi
int v3; // di
WORD *v5; // eax
WORD *v6; // eax
v2 = a1;
v3 = loader_query_visual_states(a1);
if ( v3 <= 0 )
return loader_error(12, 24);
v5 = (WORD *)partman_field(loader_table, a1, 0);
if ( !v5 )
return loader_error(1, 24);
if ( *v5 != 200 )
return loader_error(5, 24);
if ( a2 > v3 )
return loader_error(12, 24);
if ( !a2 )
return v2;
v2 = a2 + a1;
v6 = (WORD *)partman_field(loader_table, a2 + a1, 0);
if ( !v6 )
return loader_error(1, 24);
if ( *v6 == 201 )
return v2;
return loader_error(6, 24);
}
//----- (0100950A) --------------------------------------------------------
signed int loader_query_visual(int a1, signed int a2, DWORD *a3)
{
DWORD *v3; // edi
int v5; // eax
int v6; // ebx
int v7; // eax
signed int *v8; // esi
unsigned int v9; // eax
int v10; // ebx
signed int v11; // ecx
_BYTE *v12; // esi
int v13; // ebx
int v14; // ecx
int v15; // ecx
int v16; // ecx
int v17; // ecx
int v18; // ecx
int v19; // ecx
float *v20; // eax
float *v21; // esi
signed __int64 v22; // rax
int v23; // esi
int v24; // [esp+1Ch] [ebp+8h]
unsigned int v25; // [esp+24h] [ebp+10h]
v3 = a3;
loader_default_vsi(a3);
if ( a1 < 0 )
return loader_error(0, 18);
v5 = loader_state_id(a1, a2);
v6 = v5;
v24 = v5;
if ( v5 < 0 )
return loader_error(16, 18);
a3[16] = partman_field(loader_table, v5, 1);
v7 = partman_field(loader_table, v6, 12);
a3[17] = v7;
if ( v7 )
{
*(DWORD *)(v7 + 6) = v7 + 14;
*(DWORD *)(a3[17] + 10) = *(DWORD *)(a3[17] + 6);
}
v8 = (signed int *)partman_field(loader_table, v6, 10);
if ( v8 )
{
v9 = partman_field_size(loader_table, v6, 10);
v10 = 0;
v25 = v9 >> 1;
if ( (signed int)(v9 >> 1) > 0 )
{
while ( 1 )
{
v11 = *v8;
v12 = v8 + 1;
v13 = v10 + 1;
if ( v11 <= 406 )
{
if ( v11 == 406 )
{
v3[12] = loader_get_sound_id(*(signed int *)v12);
}
else
{
v14 = v11 - 100;
if ( v14 )
{
v15 = v14 - 200;
if ( v15 )
{
v16 = v15 - 4;
if ( v16 )
{
if ( v16 != 96 )
return loader_error(9, 18);
if ( loader_kicker(*(signed int *)v12, v3 + 5) )
return loader_error(14, 18);
}
else
{
v3[4] = loader_get_sound_id(*(signed int *)v12);
}
}
else if ( loader_material(*(signed int *)v12, v3) )
{
return loader_error(15, 18);
}
}
else if ( a2 )
{
return loader_error(7, 18);
}
}
goto LABEL_32;
}
v17 = v11 - 602;
if ( !v17 )
{
v3[13] |= 1 << *v12;
goto LABEL_32;
}
v18 = v17 - 498;
if ( !v18 )
break;
v19 = v18 - 1;
if ( !v19 )
{
v3[15] = loader_get_sound_id(*(signed int *)v12);
LABEL_32:
v8 = (signed int *)(v12 + 2);
v10 = v13 + 1;
goto LABEL_33;
}
if ( v19 != 399 )
return loader_error(9, 18);
v8 = (signed int *)(v12 + 16);
v10 = v13 + 8;
LABEL_33:
if ( (signed int)v10 >= (signed int)v25 )
goto LABEL_34;
}
v3[14] = loader_get_sound_id(*(signed int *)v12);
goto LABEL_32;
}
}
LABEL_34:
if ( !v3[13] )
v3[13] = 1;
v20 = (float *)partman_field(loader_table, v24, 11);
if ( !v20 )
return 0;
v21 = v20 + 1;
if ( *v20 != 600.0 )
return 0;
v3[2] = (signed int)((unsigned int)partman_field_size(loader_table, v24, 11) >> 2) / 2 - 2;
v22 = (signed __int64)(_floor(*v21) - 1.0);
v23 = (int)(v21 + 1);
if ( !(WORD)v22 )
{
v3[2] = 1;
LABEL_40:
v3[3] = v23;
return 0;
}
if ( (WORD)v22 == 1 )
{
v3[2] = 2;
goto LABEL_40;
}
if ( (signed int)v22 == v3[2] )
goto LABEL_40;
return loader_error(8, 18);
}
//----- (0100975D) --------------------------------------------------------
int loader_query_name(int a1)
{
if ( a1 >= 0 )
return partman_field(loader_table, a1, 3);
loader_error(0, 19);
return 0;
}
//----- (0100978E) --------------------------------------------------------
int loader_query_float_attribute(int a1, signed int a2, int a3)
{
int v3; // bx
int result; // eax
int v5; // edi
float *v6; // eax
float *v7; // esi
v3 = 0;
if ( a1 >= 0 )
{
v5 = loader_state_id(a1, a2);
if ( v5 >= 0 )
{
while ( 1 )
{
v6 = (float *)partman_field_nth(loader_table, v5, 11, v3);
v7 = v6;
if ( !v6 )
break;
if ( (signed int)(signed __int64)_floor(*v6) == a3 )
return (int)(v7 + 1);
++v3;
}
loader_error(13, 22);
result = 0;
}
else
{
loader_error(16, 22);
result = 0;
}
}
else
{
loader_error(0, 22);
result = 0;
}
return result;
}
//----- (0100981A) --------------------------------------------------------
int loader_query_iattribute(int a1, int a2, DWORD *a3)
{
int v3; // di
int result; // eax
signed int *v5; // eax
signed int *v6; // esi
v3 = 0;
if ( a1 >= 0 )
{
while ( 1 )
{
v5 = (signed int *)partman_field_nth(loader_table, a1, 10, v3);
v6 = v5;
if ( !v5 )
break;
if ( *v5 == a2 )
{
*a3 = partman_field_size(loader_table, a1, 10) / 2 - 1;
return (int)(v6 + 1);
}
++v3;
}
loader_error(2, 23);
*a3 = 0;
result = 0;
}
else
{
loader_error(0, 22);
result = 0;
}
return result;
}
//----- (01009895) --------------------------------------------------------
double loader_play_sound(int a1)
{
if ( a1 <= 0 )
return 0.0;
Sound_PlaySound(sound_list[5 * a1], 0, 7, 5u, 0);
return *(float *)&algn_1027C2C[20 * a1];
}
// 1027C20: using guessed type int sound_list[];
| 26.4
| 109
| 0.401926
|
XplosiveLugnut
|
47eadaeebabcd54b782d7438128de912c2bfdfbd
| 3,217
|
hh
|
C++
|
src/BGL/BGLLine.hh
|
revarbat/Mandoline
|
1aafd7e6702ef740bcac6ab8c8c43282a104c60a
|
[
"BSD-2-Clause-FreeBSD"
] | 17
|
2015-01-07T10:32:06.000Z
|
2021-07-06T11:00:38.000Z
|
src/BGL/BGLLine.hh
|
revarbat/Mandoline
|
1aafd7e6702ef740bcac6ab8c8c43282a104c60a
|
[
"BSD-2-Clause-FreeBSD"
] | 2
|
2017-08-17T17:44:42.000Z
|
2018-06-14T23:39:04.000Z
|
src/BGL/BGLLine.hh
|
revarbat/Mandoline
|
1aafd7e6702ef740bcac6ab8c8c43282a104c60a
|
[
"BSD-2-Clause-FreeBSD"
] | 3
|
2015-01-07T10:32:06.000Z
|
2019-03-22T16:56:51.000Z
|
//
// BGLLine.hh
// Part of the Belfry Geometry Library
//
// Created by GM on 10/13/10.
// Copyright 2010 Belfry Software. All rights reserved.
//
#ifndef BGL_LINE_H
#define BGL_LINE_H
#include <math.h>
#include <iostream>
#include <list>
#include "BGLCommon.hh"
#include "BGLAffine.hh"
#include "BGLIntersection.hh"
#include "BGLPoint.hh"
using namespace std;
namespace BGL {
class Line {
public:
// Member variables
Point startPt;
Point endPt;
int flags;
double temperature;
double extrusionWidth;
// Constructors
Line() :
startPt(),
endPt(),
flags(0),
temperature(0),
extrusionWidth(0)
{
}
Line(const Point& p1, const Point& p2) :
startPt(p1),
endPt(p2),
flags(0),
temperature(0),
extrusionWidth(0)
{
}
Line(const Line& ln) :
startPt(ln.startPt),
endPt(ln.endPt),
flags(ln.flags),
temperature(ln.temperature),
extrusionWidth(ln.extrusionWidth)
{
}
// Assignment operator
Line& operator=(const Line &rhs);
// Compound assignment operators
Line& operator+=(const Point &rhs);
Line& operator-=(const Point &rhs);
Line& operator*=(double rhs);
Line& operator*=(const Point &rhs);
Line& operator/=(double rhs);
Line& operator/=(const Point &rhs);
// Binary arithmetic operators
const Line operator+(const Point &rhs) const;
const Line operator-(const Point &rhs) const;
const Line operator*(double rhs) const;
const Line operator*(const Point &rhs) const;
const Line operator/(double rhs) const;
const Line operator/(const Point &rhs) const;
// Comparison operators
bool operator==(const Line &rhs) const;
bool operator!=(const Line &rhs) const;
bool hasEndPoint(const Point& pt) const;
// Transformations
Line& scale(double scale);
Line& scale(const Point& vect);
Line& scaleAroundPoint(const Point& center, double scale);
Line& scaleAroundPoint(const Point& center, const Point& vect);
Line& rotate(double angle);
void quantize(double quanta);
void quantize();
// Calculations
double length() const;
double angle() const;
double angleDelta(const Line& ln) const;
bool isLeftOf(const Point &pt) const;
bool isLeftOfNormal(const Point &pt) const;
// Misc
Line& reverse();
Line& reverseIfRightOfNormal(const Point &pt);
bool isLinearWith(const Point& pt) const;
bool hasInBounds(const Point &pt) const;
bool contains(const Point &pt) const;
Point closestSegmentPointTo(const Point &pt) const;
Point closestExtendedLinePointTo(const Point &pt) const;
double minimumSegmentDistanceFromPoint(const Point &pt) const;
double minimumExtendedLineDistanceFromPoint(const Point &pt) const;
Intersection intersectionWithSegment(const Line &ln) const;
Intersection intersectionWithExtendedLine(const Line &ln) const;
Line& leftOffset(double offsetby);
// Friend functions
friend ostream& operator <<(ostream &os,const Line &pt);
};
typedef list<Line> Lines;
}
#endif
// vim: set ts=4 sw=4 nowrap expandtab: settings
| 23.654412
| 71
| 0.660242
|
revarbat
|
47ed68f919d084e86deeb009c4dcdffcbf520811
| 50,330
|
cpp
|
C++
|
includes/mfbt/tests/TestTextUtils.cpp
|
gregtatum/spec-cpp
|
ebd40fa119a302f82ab10a2b8ddd52671f92e2ef
|
[
"MIT"
] | 5
|
2018-02-01T18:25:35.000Z
|
2018-02-12T14:09:22.000Z
|
includes/mfbt/tests/TestTextUtils.cpp
|
gregtatum/spec-cpp
|
ebd40fa119a302f82ab10a2b8ddd52671f92e2ef
|
[
"MIT"
] | null | null | null |
includes/mfbt/tests/TestTextUtils.cpp
|
gregtatum/spec-cpp
|
ebd40fa119a302f82ab10a2b8ddd52671f92e2ef
|
[
"MIT"
] | 1
|
2019-03-15T06:01:40.000Z
|
2019-03-15T06:01:40.000Z
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "./Assertions.h"
#include "./TextUtils.h"
using mozilla::AsciiAlphanumericToNumber;
using mozilla::IsAscii;
using mozilla::IsAsciiAlpha;
using mozilla::IsAsciiAlphanumeric;
using mozilla::IsAsciiDigit;
using mozilla::IsAsciiLowercaseAlpha;
using mozilla::IsAsciiNullTerminated;
using mozilla::IsAsciiUppercaseAlpha;
static void TestIsAscii() {
// char
static_assert(!IsAscii(char(-1)), "char(-1) isn't ASCII");
static_assert(IsAscii('\0'), "nul is ASCII");
static_assert(IsAscii('A'), "'A' is ASCII");
static_assert(IsAscii('B'), "'B' is ASCII");
static_assert(IsAscii('M'), "'M' is ASCII");
static_assert(IsAscii('Y'), "'Y' is ASCII");
static_assert(IsAscii('Z'), "'Z' is ASCII");
static_assert(IsAscii('['), "'[' is ASCII");
static_assert(IsAscii('`'), "'`' is ASCII");
static_assert(IsAscii('a'), "'a' is ASCII");
static_assert(IsAscii('b'), "'b' is ASCII");
static_assert(IsAscii('m'), "'m' is ASCII");
static_assert(IsAscii('y'), "'y' is ASCII");
static_assert(IsAscii('z'), "'z' is ASCII");
static_assert(IsAscii('{'), "'{' is ASCII");
static_assert(IsAscii('5'), "'5' is ASCII");
static_assert(IsAscii('\x7F'), "'\\x7F' is ASCII");
static_assert(!IsAscii('\x80'), "'\\x80' isn't ASCII");
// char16_t
static_assert(!IsAscii(char16_t(-1)), "char16_t(-1) isn't ASCII");
static_assert(IsAscii(u'\0'), "nul is ASCII");
static_assert(IsAscii(u'A'), "u'A' is ASCII");
static_assert(IsAscii(u'B'), "u'B' is ASCII");
static_assert(IsAscii(u'M'), "u'M' is ASCII");
static_assert(IsAscii(u'Y'), "u'Y' is ASCII");
static_assert(IsAscii(u'Z'), "u'Z' is ASCII");
static_assert(IsAscii(u'['), "u'[' is ASCII");
static_assert(IsAscii(u'`'), "u'`' is ASCII");
static_assert(IsAscii(u'a'), "u'a' is ASCII");
static_assert(IsAscii(u'b'), "u'b' is ASCII");
static_assert(IsAscii(u'm'), "u'm' is ASCII");
static_assert(IsAscii(u'y'), "u'y' is ASCII");
static_assert(IsAscii(u'z'), "u'z' is ASCII");
static_assert(IsAscii(u'{'), "u'{' is ASCII");
static_assert(IsAscii(u'5'), "u'5' is ASCII");
static_assert(IsAscii(u'\x7F'), "u'\\x7F' is ASCII");
static_assert(!IsAscii(u'\x80'), "u'\\x80' isn't ASCII");
// char32_t
static_assert(!IsAscii(char32_t(-1)), "char32_t(-1) isn't ASCII");
static_assert(IsAscii(U'\0'), "nul is ASCII");
static_assert(IsAscii(U'A'), "U'A' is ASCII");
static_assert(IsAscii(U'B'), "U'B' is ASCII");
static_assert(IsAscii(U'M'), "U'M' is ASCII");
static_assert(IsAscii(U'Y'), "U'Y' is ASCII");
static_assert(IsAscii(U'Z'), "U'Z' is ASCII");
static_assert(IsAscii(U'['), "U'[' is ASCII");
static_assert(IsAscii(U'`'), "U'`' is ASCII");
static_assert(IsAscii(U'a'), "U'a' is ASCII");
static_assert(IsAscii(U'b'), "U'b' is ASCII");
static_assert(IsAscii(U'm'), "U'm' is ASCII");
static_assert(IsAscii(U'y'), "U'y' is ASCII");
static_assert(IsAscii(U'z'), "U'z' is ASCII");
static_assert(IsAscii(U'{'), "U'{' is ASCII");
static_assert(IsAscii(U'5'), "U'5' is ASCII");
static_assert(IsAscii(U'\x7F'), "U'\\x7F' is ASCII");
static_assert(!IsAscii(U'\x80'), "U'\\x80' isn't ASCII");
}
static void TestIsAsciiNullTerminated() {
// char
constexpr char allChar[] =
"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\0x0C\x0D\x0E\x0F"
"\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\0x1C\x1D\x1E\x1F"
"\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\0x2C\x2D\x2E\x2F"
"\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\0x3C\x3D\x3E\x3F"
"\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\0x4C\x4D\x4E\x4F"
"\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\0x5C\x5D\x5E\x5F"
"\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\0x6C\x6D\x6E\x6F"
"\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\0x7C\x7D\x7E\x7F";
static_assert(IsAsciiNullTerminated(allChar), "allChar is ASCII");
constexpr char loBadChar[] = "\x80";
static_assert(!IsAsciiNullTerminated(loBadChar), "loBadChar isn't ASCII");
constexpr char hiBadChar[] = "\xFF";
static_assert(!IsAsciiNullTerminated(hiBadChar), "hiBadChar isn't ASCII");
// char16_t
constexpr char16_t allChar16[] =
u"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\0x0C\x0D\x0E\x0F"
"\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\0x1C\x1D\x1E\x1F"
"\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\0x2C\x2D\x2E\x2F"
"\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\0x3C\x3D\x3E\x3F"
"\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\0x4C\x4D\x4E\x4F"
"\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\0x5C\x5D\x5E\x5F"
"\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\0x6C\x6D\x6E\x6F"
"\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\0x7C\x7D\x7E\x7F";
static_assert(IsAsciiNullTerminated(allChar16), "allChar16 is ASCII");
constexpr char16_t loBadChar16[] = u"\x80";
static_assert(!IsAsciiNullTerminated(loBadChar16), "loBadChar16 isn't ASCII");
constexpr char16_t hiBadChar16[] = u"\xFF";
static_assert(!IsAsciiNullTerminated(hiBadChar16), "hiBadChar16 isn't ASCII");
constexpr char16_t highestChar16[] = u"\uFFFF";
static_assert(!IsAsciiNullTerminated(highestChar16),
"highestChar16 isn't ASCII");
// char32_t
constexpr char32_t allChar32[] =
U"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\0x0C\x0D\x0E\x0F"
"\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\0x1C\x1D\x1E\x1F"
"\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\0x2C\x2D\x2E\x2F"
"\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\0x3C\x3D\x3E\x3F"
"\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\0x4C\x4D\x4E\x4F"
"\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\0x5C\x5D\x5E\x5F"
"\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\0x6C\x6D\x6E\x6F"
"\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\0x7C\x7D\x7E\x7F";
static_assert(IsAsciiNullTerminated(allChar32), "allChar32 is ASCII");
constexpr char32_t loBadChar32[] = U"\x80";
static_assert(!IsAsciiNullTerminated(loBadChar32), "loBadChar32 isn't ASCII");
constexpr char32_t hiBadChar32[] = U"\xFF";
static_assert(!IsAsciiNullTerminated(hiBadChar32), "hiBadChar32 isn't ASCII");
constexpr char32_t highestChar32[] = {static_cast<char32_t>(-1), 0};
static_assert(!IsAsciiNullTerminated(highestChar32),
"highestChar32 isn't ASCII");
}
static void TestIsAsciiAlpha() {
// char
static_assert(!IsAsciiAlpha('@'), "'@' isn't ASCII alpha");
static_assert('@' == 0x40, "'@' has value 0x40");
static_assert('A' == 0x41, "'A' has value 0x41");
static_assert(IsAsciiAlpha('A'), "'A' is ASCII alpha");
static_assert(IsAsciiAlpha('B'), "'B' is ASCII alpha");
static_assert(IsAsciiAlpha('M'), "'M' is ASCII alpha");
static_assert(IsAsciiAlpha('Y'), "'Y' is ASCII alpha");
static_assert(IsAsciiAlpha('Z'), "'Z' is ASCII alpha");
static_assert('Z' == 0x5A, "'Z' has value 0x5A");
static_assert('[' == 0x5B, "'[' has value 0x5B");
static_assert(!IsAsciiAlpha('['), "'[' isn't ASCII alpha");
static_assert(!IsAsciiAlpha('`'), "'`' isn't ASCII alpha");
static_assert('`' == 0x60, "'`' has value 0x60");
static_assert('a' == 0x61, "'a' has value 0x61");
static_assert(IsAsciiAlpha('a'), "'a' is ASCII alpha");
static_assert(IsAsciiAlpha('b'), "'b' is ASCII alpha");
static_assert(IsAsciiAlpha('m'), "'m' is ASCII alpha");
static_assert(IsAsciiAlpha('y'), "'y' is ASCII alpha");
static_assert(IsAsciiAlpha('z'), "'z' is ASCII alpha");
static_assert('z' == 0x7A, "'z' has value 0x7A");
static_assert('{' == 0x7B, "'{' has value 0x7B");
static_assert(!IsAsciiAlpha('{'), "'{' isn't ASCII alpha");
static_assert(!IsAsciiAlpha('5'), "'5' isn't ASCII alpha");
// char16_t
static_assert(!IsAsciiAlpha(u'@'), "u'@' isn't ASCII alpha");
static_assert(u'@' == 0x40, "u'@' has value 0x40");
static_assert(u'A' == 0x41, "u'A' has value 0x41");
static_assert(IsAsciiAlpha(u'A'), "u'A' is ASCII alpha");
static_assert(IsAsciiAlpha(u'B'), "u'B' is ASCII alpha");
static_assert(IsAsciiAlpha(u'M'), "u'M' is ASCII alpha");
static_assert(IsAsciiAlpha(u'Y'), "u'Y' is ASCII alpha");
static_assert(IsAsciiAlpha(u'Z'), "u'Z' is ASCII alpha");
static_assert(u'Z' == 0x5A, "u'Z' has value 0x5A");
static_assert(u'[' == 0x5B, "u'[' has value 0x5B");
static_assert(!IsAsciiAlpha(u'['), "u'[' isn't ASCII alpha");
static_assert(!IsAsciiAlpha(u'`'), "u'`' isn't ASCII alpha");
static_assert(u'`' == 0x60, "u'`' has value 0x60");
static_assert(u'a' == 0x61, "u'a' has value 0x61");
static_assert(IsAsciiAlpha(u'a'), "u'a' is ASCII alpha");
static_assert(IsAsciiAlpha(u'b'), "u'b' is ASCII alpha");
static_assert(IsAsciiAlpha(u'm'), "u'm' is ASCII alpha");
static_assert(IsAsciiAlpha(u'y'), "u'y' is ASCII alpha");
static_assert(IsAsciiAlpha(u'z'), "u'z' is ASCII alpha");
static_assert(u'z' == 0x7A, "u'z' has value 0x7A");
static_assert(u'{' == 0x7B, "u'{' has value 0x7B");
static_assert(!IsAsciiAlpha(u'{'), "u'{' isn't ASCII alpha");
static_assert(!IsAsciiAlpha(u'5'), "u'5' isn't ASCII alpha");
// char32_t
static_assert(!IsAsciiAlpha(U'@'), "U'@' isn't ASCII alpha");
static_assert(U'@' == 0x40, "U'@' has value 0x40");
static_assert(U'A' == 0x41, "U'A' has value 0x41");
static_assert(IsAsciiAlpha(U'A'), "U'A' is ASCII alpha");
static_assert(IsAsciiAlpha(U'B'), "U'B' is ASCII alpha");
static_assert(IsAsciiAlpha(U'M'), "U'M' is ASCII alpha");
static_assert(IsAsciiAlpha(U'Y'), "U'Y' is ASCII alpha");
static_assert(IsAsciiAlpha(U'Z'), "U'Z' is ASCII alpha");
static_assert(U'Z' == 0x5A, "U'Z' has value 0x5A");
static_assert(U'[' == 0x5B, "U'[' has value 0x5B");
static_assert(!IsAsciiAlpha(U'['), "U'[' isn't ASCII alpha");
static_assert(!IsAsciiAlpha(U'`'), "U'`' isn't ASCII alpha");
static_assert(U'`' == 0x60, "U'`' has value 0x60");
static_assert(U'a' == 0x61, "U'a' has value 0x61");
static_assert(IsAsciiAlpha(U'a'), "U'a' is ASCII alpha");
static_assert(IsAsciiAlpha(U'b'), "U'b' is ASCII alpha");
static_assert(IsAsciiAlpha(U'm'), "U'm' is ASCII alpha");
static_assert(IsAsciiAlpha(U'y'), "U'y' is ASCII alpha");
static_assert(IsAsciiAlpha(U'z'), "U'z' is ASCII alpha");
static_assert(U'z' == 0x7A, "U'z' has value 0x7A");
static_assert(U'{' == 0x7B, "U'{' has value 0x7B");
static_assert(!IsAsciiAlpha(U'{'), "U'{' isn't ASCII alpha");
static_assert(!IsAsciiAlpha(U'5'), "U'5' isn't ASCII alpha");
}
static void TestIsAsciiUppercaseAlpha() {
// char
static_assert(!IsAsciiUppercaseAlpha('@'), "'@' isn't ASCII alpha uppercase");
static_assert('@' == 0x40, "'@' has value 0x40");
static_assert('A' == 0x41, "'A' has value 0x41");
static_assert(IsAsciiUppercaseAlpha('A'), "'A' is ASCII alpha uppercase");
static_assert(IsAsciiUppercaseAlpha('B'), "'B' is ASCII alpha uppercase");
static_assert(IsAsciiUppercaseAlpha('M'), "'M' is ASCII alpha uppercase");
static_assert(IsAsciiUppercaseAlpha('Y'), "'Y' is ASCII alpha uppercase");
static_assert(IsAsciiUppercaseAlpha('Z'), "'Z' is ASCII alpha uppercase");
static_assert('Z' == 0x5A, "'Z' has value 0x5A");
static_assert('[' == 0x5B, "'[' has value 0x5B");
static_assert(!IsAsciiUppercaseAlpha('['), "'[' isn't ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha('`'), "'`' isn't ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha('a'), "'a' is ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha('b'), "'b' is ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha('m'), "'m' is ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha('y'), "'y' is ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha('z'), "'z' is ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha('{'), "'{' isn't ASCII alpha uppercase");
// char16_t
static_assert(!IsAsciiUppercaseAlpha(u'@'),
"u'@' isn't ASCII alpha uppercase");
static_assert(u'@' == 0x40, "u'@' has value 0x40");
static_assert(u'A' == 0x41, "u'A' has value 0x41");
static_assert(IsAsciiUppercaseAlpha(u'A'), "u'A' is ASCII alpha uppercase");
static_assert(IsAsciiUppercaseAlpha(u'B'), "u'B' is ASCII alpha uppercase");
static_assert(IsAsciiUppercaseAlpha(u'M'), "u'M' is ASCII alpha uppercase");
static_assert(IsAsciiUppercaseAlpha(u'Y'), "u'Y' is ASCII alpha uppercase");
static_assert(IsAsciiUppercaseAlpha(u'Z'), "u'Z' is ASCII alpha uppercase");
static_assert(u'Z' == 0x5A, "u'Z' has value 0x5A");
static_assert(u'[' == 0x5B, "u'[' has value 0x5B");
static_assert(!IsAsciiUppercaseAlpha(u'['),
"u'[' isn't ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha(u'`'),
"u'`' isn't ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha(u'a'), "u'a' is ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha(u'b'), "u'b' is ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha(u'm'), "u'm' is ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha(u'y'), "u'y' is ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha(u'z'), "u'z' is ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha(u'{'),
"u'{' isn't ASCII alpha uppercase");
// char32_t
static_assert(!IsAsciiUppercaseAlpha(U'@'),
"U'@' isn't ASCII alpha uppercase");
static_assert(U'@' == 0x40, "U'@' has value 0x40");
static_assert(U'A' == 0x41, "U'A' has value 0x41");
static_assert(IsAsciiUppercaseAlpha(U'A'), "U'A' is ASCII alpha uppercase");
static_assert(IsAsciiUppercaseAlpha(U'B'), "U'B' is ASCII alpha uppercase");
static_assert(IsAsciiUppercaseAlpha(U'M'), "U'M' is ASCII alpha uppercase");
static_assert(IsAsciiUppercaseAlpha(U'Y'), "U'Y' is ASCII alpha uppercase");
static_assert(IsAsciiUppercaseAlpha(U'Z'), "U'Z' is ASCII alpha uppercase");
static_assert(U'Z' == 0x5A, "U'Z' has value 0x5A");
static_assert(U'[' == 0x5B, "U'[' has value 0x5B");
static_assert(!IsAsciiUppercaseAlpha(U'['),
"U'[' isn't ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha(U'`'),
"U'`' isn't ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha(U'a'), "U'a' is ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha(U'b'), "U'b' is ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha(U'm'), "U'm' is ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha(U'y'), "U'y' is ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha(U'z'), "U'z' is ASCII alpha uppercase");
static_assert(!IsAsciiUppercaseAlpha(U'{'),
"U'{' isn't ASCII alpha uppercase");
}
static void TestIsAsciiLowercaseAlpha() {
// char
static_assert(!IsAsciiLowercaseAlpha('`'), "'`' isn't ASCII alpha lowercase");
static_assert('`' == 0x60, "'`' has value 0x60");
static_assert('a' == 0x61, "'a' has value 0x61");
static_assert(IsAsciiLowercaseAlpha('a'), "'a' is ASCII alpha lowercase");
static_assert(IsAsciiLowercaseAlpha('b'), "'b' is ASCII alpha lowercase");
static_assert(IsAsciiLowercaseAlpha('m'), "'m' is ASCII alpha lowercase");
static_assert(IsAsciiLowercaseAlpha('y'), "'y' is ASCII alpha lowercase");
static_assert(IsAsciiLowercaseAlpha('z'), "'z' is ASCII alpha lowercase");
static_assert('z' == 0x7A, "'z' has value 0x7A");
static_assert('{' == 0x7B, "'{' has value 0x7B");
static_assert(!IsAsciiLowercaseAlpha('{'), "'{' isn't ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha('@'), "'@' isn't ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha('A'), "'A' is ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha('B'), "'B' is ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha('M'), "'M' is ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha('Y'), "'Y' is ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha('Z'), "'Z' is ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha('['), "'[' isn't ASCII alpha lowercase");
// char16_t
static_assert(!IsAsciiLowercaseAlpha(u'`'),
"u'`' isn't ASCII alpha lowercase");
static_assert(u'`' == 0x60, "u'`' has value 0x60");
static_assert(u'a' == 0x61, "u'a' has value 0x61");
static_assert(IsAsciiLowercaseAlpha(u'a'), "u'a' is ASCII alpha lowercase");
static_assert(IsAsciiLowercaseAlpha(u'b'), "u'b' is ASCII alpha lowercase");
static_assert(IsAsciiLowercaseAlpha(u'm'), "u'm' is ASCII alpha lowercase");
static_assert(IsAsciiLowercaseAlpha(u'y'), "u'y' is ASCII alpha lowercase");
static_assert(IsAsciiLowercaseAlpha(u'z'), "u'z' is ASCII alpha lowercase");
static_assert(u'z' == 0x7A, "u'z' has value 0x7A");
static_assert(u'{' == 0x7B, "u'{' has value 0x7B");
static_assert(!IsAsciiLowercaseAlpha(u'{'),
"u'{' isn't ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha(u'@'),
"u'@' isn't ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha(u'A'), "u'A' is ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha(u'B'), "u'B' is ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha(u'M'), "u'M' is ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha(u'Y'), "u'Y' is ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha(u'Z'), "u'Z' is ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha(u'['),
"u'[' isn't ASCII alpha lowercase");
// char32_t
static_assert(!IsAsciiLowercaseAlpha(U'`'),
"U'`' isn't ASCII alpha lowercase");
static_assert(U'`' == 0x60, "U'`' has value 0x60");
static_assert(U'a' == 0x61, "U'a' has value 0x61");
static_assert(IsAsciiLowercaseAlpha(U'a'), "U'a' is ASCII alpha lowercase");
static_assert(IsAsciiLowercaseAlpha(U'b'), "U'b' is ASCII alpha lowercase");
static_assert(IsAsciiLowercaseAlpha(U'm'), "U'm' is ASCII alpha lowercase");
static_assert(IsAsciiLowercaseAlpha(U'y'), "U'y' is ASCII alpha lowercase");
static_assert(IsAsciiLowercaseAlpha(U'z'), "U'z' is ASCII alpha lowercase");
static_assert(U'z' == 0x7A, "U'z' has value 0x7A");
static_assert(U'{' == 0x7B, "U'{' has value 0x7B");
static_assert(!IsAsciiLowercaseAlpha(U'{'),
"U'{' isn't ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha(U'@'),
"U'@' isn't ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha(U'A'), "U'A' is ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha(U'B'), "U'B' is ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha(U'M'), "U'M' is ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha(U'Y'), "U'Y' is ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha(U'Z'), "U'Z' is ASCII alpha lowercase");
static_assert(!IsAsciiLowercaseAlpha(U'['),
"U'[' isn't ASCII alpha lowercase");
}
static void TestIsAsciiAlphanumeric() {
// char
static_assert(!IsAsciiAlphanumeric('/'), "'/' isn't ASCII alphanumeric");
static_assert('/' == 0x2F, "'/' has value 0x2F");
static_assert('0' == 0x30, "'0' has value 0x30");
static_assert(IsAsciiAlphanumeric('0'), "'0' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric('1'), "'1' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric('5'), "'5' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric('8'), "'8' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric('9'), "'9' is ASCII alphanumeric");
static_assert('9' == 0x39, "'9' has value 0x39");
static_assert(':' == 0x3A, "':' has value 0x3A");
static_assert(!IsAsciiAlphanumeric(':'), "':' isn't ASCII alphanumeric");
static_assert(!IsAsciiAlphanumeric('@'), "'@' isn't ASCII alphanumeric");
static_assert('@' == 0x40, "'@' has value 0x40");
static_assert('A' == 0x41, "'A' has value 0x41");
static_assert(IsAsciiAlphanumeric('A'), "'A' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric('B'), "'B' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric('M'), "'M' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric('Y'), "'Y' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric('Z'), "'Z' is ASCII alphanumeric");
static_assert('Z' == 0x5A, "'Z' has value 0x5A");
static_assert('[' == 0x5B, "'[' has value 0x5B");
static_assert(!IsAsciiAlphanumeric('['), "'[' isn't ASCII alphanumeric");
static_assert(!IsAsciiAlphanumeric('`'), "'`' isn't ASCII alphanumeric");
static_assert('`' == 0x60, "'`' has value 0x60");
static_assert('a' == 0x61, "'a' has value 0x61");
static_assert(IsAsciiAlphanumeric('a'), "'a' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric('b'), "'b' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric('m'), "'m' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric('y'), "'y' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric('z'), "'z' is ASCII alphanumeric");
static_assert('z' == 0x7A, "'z' has value 0x7A");
static_assert('{' == 0x7B, "'{' has value 0x7B");
static_assert(!IsAsciiAlphanumeric('{'), "'{' isn't ASCII alphanumeric");
// char16_t
static_assert(!IsAsciiAlphanumeric(u'/'), "u'/' isn't ASCII alphanumeric");
static_assert(u'/' == 0x2F, "u'/' has value 0x2F");
static_assert(u'0' == 0x30, "u'0' has value 0x30");
static_assert(IsAsciiAlphanumeric(u'0'), "u'0' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(u'1'), "u'1' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(u'5'), "u'5' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(u'8'), "u'8' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(u'9'), "u'9' is ASCII alphanumeric");
static_assert(u'9' == 0x39, "u'9' has value 0x39");
static_assert(u':' == 0x3A, "u':' has value 0x3A");
static_assert(!IsAsciiAlphanumeric(u':'), "u':' isn't ASCII alphanumeric");
static_assert(!IsAsciiAlphanumeric(u'@'), "u'@' isn't ASCII alphanumeric");
static_assert(u'@' == 0x40, "u'@' has value 0x40");
static_assert(u'A' == 0x41, "u'A' has value 0x41");
static_assert(IsAsciiAlphanumeric(u'A'), "u'A' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(u'B'), "u'B' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(u'M'), "u'M' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(u'Y'), "u'Y' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(u'Z'), "u'Z' is ASCII alphanumeric");
static_assert(u'Z' == 0x5A, "u'Z' has value 0x5A");
static_assert(u'[' == 0x5B, "u'[' has value 0x5B");
static_assert(!IsAsciiAlphanumeric(u'['), "u'[' isn't ASCII alphanumeric");
static_assert(!IsAsciiAlphanumeric(u'`'), "u'`' isn't ASCII alphanumeric");
static_assert(u'`' == 0x60, "u'`' has value 0x60");
static_assert(u'a' == 0x61, "u'a' has value 0x61");
static_assert(IsAsciiAlphanumeric(u'a'), "u'a' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(u'b'), "u'b' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(u'm'), "u'm' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(u'y'), "u'y' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(u'z'), "u'z' is ASCII alphanumeric");
static_assert(u'z' == 0x7A, "u'z' has value 0x7A");
static_assert(u'{' == 0x7B, "u'{' has value 0x7B");
static_assert(!IsAsciiAlphanumeric(u'{'), "u'{' isn't ASCII alphanumeric");
// char32_t
static_assert(!IsAsciiAlphanumeric(U'/'), "U'/' isn't ASCII alphanumeric");
static_assert(U'/' == 0x2F, "U'/' has value 0x2F");
static_assert(U'0' == 0x30, "U'0' has value 0x30");
static_assert(IsAsciiAlphanumeric(U'0'), "U'0' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(U'1'), "U'1' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(U'5'), "U'5' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(U'8'), "U'8' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(U'9'), "U'9' is ASCII alphanumeric");
static_assert(U'9' == 0x39, "U'9' has value 0x39");
static_assert(U':' == 0x3A, "U':' has value 0x3A");
static_assert(!IsAsciiAlphanumeric(U':'), "U':' isn't ASCII alphanumeric");
static_assert(!IsAsciiAlphanumeric(U'@'), "U'@' isn't ASCII alphanumeric");
static_assert(U'@' == 0x40, "U'@' has value 0x40");
static_assert(U'A' == 0x41, "U'A' has value 0x41");
static_assert(IsAsciiAlphanumeric(U'A'), "U'A' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(U'B'), "U'B' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(U'M'), "U'M' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(U'Y'), "U'Y' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(U'Z'), "U'Z' is ASCII alphanumeric");
static_assert(U'Z' == 0x5A, "U'Z' has value 0x5A");
static_assert(U'[' == 0x5B, "U'[' has value 0x5B");
static_assert(!IsAsciiAlphanumeric(U'['), "U'[' isn't ASCII alphanumeric");
static_assert(!IsAsciiAlphanumeric(U'`'), "U'`' isn't ASCII alphanumeric");
static_assert(U'`' == 0x60, "U'`' has value 0x60");
static_assert(U'a' == 0x61, "U'a' has value 0x61");
static_assert(IsAsciiAlphanumeric(U'a'), "U'a' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(U'b'), "U'b' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(U'm'), "U'm' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(U'y'), "U'y' is ASCII alphanumeric");
static_assert(IsAsciiAlphanumeric(U'z'), "U'z' is ASCII alphanumeric");
static_assert(U'z' == 0x7A, "U'z' has value 0x7A");
static_assert(U'{' == 0x7B, "U'{' has value 0x7B");
static_assert(!IsAsciiAlphanumeric(U'{'), "U'{' isn't ASCII alphanumeric");
}
static void TestAsciiAlphanumericToNumber() {
// When AsciiAlphanumericToNumber becomes constexpr, make sure to convert all
// these to just static_assert.
// char
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('0') == 0, "'0' converts to 0");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('1') == 1, "'1' converts to 1");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('2') == 2, "'2' converts to 2");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('3') == 3, "'3' converts to 3");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('4') == 4, "'4' converts to 4");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('5') == 5, "'5' converts to 5");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('6') == 6, "'6' converts to 6");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('7') == 7, "'7' converts to 7");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('8') == 8, "'8' converts to 8");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('9') == 9, "'9' converts to 9");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('A') == 10,
"'A' converts to 10");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('B') == 11,
"'B' converts to 11");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('C') == 12,
"'C' converts to 12");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('D') == 13,
"'D' converts to 13");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('E') == 14,
"'E' converts to 14");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('F') == 15,
"'F' converts to 15");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('G') == 16,
"'G' converts to 16");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('H') == 17,
"'H' converts to 17");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('I') == 18,
"'I' converts to 18");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('J') == 19,
"'J' converts to 19");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('K') == 20,
"'K' converts to 20");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('L') == 21,
"'L' converts to 21");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('M') == 22,
"'M' converts to 22");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('N') == 23,
"'N' converts to 23");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('O') == 24,
"'O' converts to 24");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('P') == 25,
"'P' converts to 25");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('Q') == 26,
"'Q' converts to 26");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('R') == 27,
"'R' converts to 27");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('S') == 28,
"'S' converts to 28");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('T') == 29,
"'T' converts to 29");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('U') == 30,
"'U' converts to 30");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('V') == 31,
"'V' converts to 31");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('W') == 32,
"'W' converts to 32");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('X') == 33,
"'X' converts to 33");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('Y') == 34,
"'Y' converts to 34");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('Z') == 35,
"'Z' converts to 35");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('a') == 10,
"'a' converts to 10");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('b') == 11,
"'b' converts to 11");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('c') == 12,
"'c' converts to 12");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('d') == 13,
"'d' converts to 13");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('e') == 14,
"'e' converts to 14");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('f') == 15,
"'f' converts to 15");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('g') == 16,
"'g' converts to 16");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('h') == 17,
"'h' converts to 17");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('i') == 18,
"'i' converts to 18");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('j') == 19,
"'j' converts to 19");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('k') == 20,
"'k' converts to 20");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('l') == 21,
"'l' converts to 21");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('m') == 22,
"'m' converts to 22");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('n') == 23,
"'n' converts to 23");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('o') == 24,
"'o' converts to 24");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('p') == 25,
"'p' converts to 25");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('q') == 26,
"'q' converts to 26");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('r') == 27,
"'r' converts to 27");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('s') == 28,
"'s' converts to 28");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('t') == 29,
"'t' converts to 29");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('u') == 30,
"'u' converts to 30");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('v') == 31,
"'v' converts to 31");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('w') == 32,
"'w' converts to 32");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('x') == 33,
"'x' converts to 33");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('y') == 34,
"'y' converts to 34");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('z') == 35,
"'z' converts to 35");
// char16_t
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'0') == 0,
"u'0' converts to 0");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'1') == 1,
"u'1' converts to 1");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'2') == 2,
"u'2' converts to 2");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'3') == 3,
"u'3' converts to 3");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'4') == 4,
"u'4' converts to 4");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'5') == 5,
"u'5' converts to 5");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'6') == 6,
"u'6' converts to 6");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'7') == 7,
"u'7' converts to 7");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'8') == 8,
"u'8' converts to 8");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'9') == 9,
"u'9' converts to 9");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'A') == 10,
"u'A' converts to 10");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'B') == 11,
"u'B' converts to 11");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'C') == 12,
"u'C' converts to 12");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'D') == 13,
"u'D' converts to 13");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'E') == 14,
"u'E' converts to 14");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'F') == 15,
"u'F' converts to 15");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'G') == 16,
"u'G' converts to 16");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'H') == 17,
"u'H' converts to 17");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'I') == 18,
"u'I' converts to 18");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'J') == 19,
"u'J' converts to 19");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'K') == 20,
"u'K' converts to 20");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'L') == 21,
"u'L' converts to 21");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'M') == 22,
"u'M' converts to 22");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'N') == 23,
"u'N' converts to 23");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'O') == 24,
"u'O' converts to 24");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'P') == 25,
"u'P' converts to 25");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'Q') == 26,
"u'Q' converts to 26");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'R') == 27,
"u'R' converts to 27");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'S') == 28,
"u'S' converts to 28");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'T') == 29,
"u'T' converts to 29");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'U') == 30,
"u'U' converts to 30");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'V') == 31,
"u'V' converts to 31");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'W') == 32,
"u'W' converts to 32");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'X') == 33,
"u'X' converts to 33");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'Y') == 34,
"u'Y' converts to 34");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'Z') == 35,
"u'Z' converts to 35");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'a') == 10,
"u'a' converts to 10");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'b') == 11,
"u'b' converts to 11");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'c') == 12,
"u'c' converts to 12");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'd') == 13,
"u'd' converts to 13");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'e') == 14,
"u'e' converts to 14");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'f') == 15,
"u'f' converts to 15");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'g') == 16,
"u'g' converts to 16");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'h') == 17,
"u'h' converts to 17");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'i') == 18,
"u'i' converts to 18");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'j') == 19,
"u'j' converts to 19");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'k') == 20,
"u'k' converts to 20");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'l') == 21,
"u'l' converts to 21");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'm') == 22,
"u'm' converts to 22");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'n') == 23,
"u'n' converts to 23");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'o') == 24,
"u'o' converts to 24");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'p') == 25,
"u'p' converts to 25");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'q') == 26,
"u'q' converts to 26");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'r') == 27,
"u'r' converts to 27");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u's') == 28,
"u's' converts to 28");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u't') == 29,
"u't' converts to 29");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'u') == 30,
"u'u' converts to 30");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'v') == 31,
"u'v' converts to 31");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'w') == 32,
"u'w' converts to 32");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'x') == 33,
"u'x' converts to 33");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'y') == 34,
"u'y' converts to 34");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'z') == 35,
"u'z' converts to 35");
// char32_t
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'0') == 0,
"U'0' converts to 0");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'1') == 1,
"U'1' converts to 1");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'2') == 2,
"U'2' converts to 2");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'3') == 3,
"U'3' converts to 3");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'4') == 4,
"U'4' converts to 4");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'5') == 5,
"U'5' converts to 5");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'6') == 6,
"U'6' converts to 6");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'7') == 7,
"U'7' converts to 7");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'8') == 8,
"U'8' converts to 8");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'9') == 9,
"U'9' converts to 9");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'A') == 10,
"U'A' converts to 10");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'B') == 11,
"U'B' converts to 11");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'C') == 12,
"U'C' converts to 12");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'D') == 13,
"U'D' converts to 13");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'E') == 14,
"U'E' converts to 14");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'F') == 15,
"U'F' converts to 15");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'G') == 16,
"U'G' converts to 16");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'H') == 17,
"U'H' converts to 17");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'I') == 18,
"U'I' converts to 18");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'J') == 19,
"U'J' converts to 19");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'K') == 20,
"U'K' converts to 20");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'L') == 21,
"U'L' converts to 21");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'M') == 22,
"U'M' converts to 22");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'N') == 23,
"U'N' converts to 23");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'O') == 24,
"U'O' converts to 24");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'P') == 25,
"U'P' converts to 25");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'Q') == 26,
"U'Q' converts to 26");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'R') == 27,
"U'R' converts to 27");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'S') == 28,
"U'S' converts to 28");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'T') == 29,
"U'T' converts to 29");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'U') == 30,
"U'U' converts to 30");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'V') == 31,
"U'V' converts to 31");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'W') == 32,
"U'W' converts to 32");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'X') == 33,
"U'X' converts to 33");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'Y') == 34,
"U'Y' converts to 34");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'Z') == 35,
"U'Z' converts to 35");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'a') == 10,
"U'a' converts to 10");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'b') == 11,
"U'b' converts to 11");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'c') == 12,
"U'c' converts to 12");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'd') == 13,
"U'd' converts to 13");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'e') == 14,
"U'e' converts to 14");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'f') == 15,
"U'f' converts to 15");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'g') == 16,
"U'g' converts to 16");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'h') == 17,
"U'h' converts to 17");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'i') == 18,
"U'i' converts to 18");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'j') == 19,
"U'j' converts to 19");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'k') == 20,
"U'k' converts to 20");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'l') == 21,
"U'l' converts to 21");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'm') == 22,
"U'm' converts to 22");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'n') == 23,
"U'n' converts to 23");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'o') == 24,
"U'o' converts to 24");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'p') == 25,
"U'p' converts to 25");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'q') == 26,
"U'q' converts to 26");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'r') == 27,
"U'r' converts to 27");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U's') == 28,
"U's' converts to 28");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U't') == 29,
"U't' converts to 29");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'u') == 30,
"U'u' converts to 30");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'v') == 31,
"U'v' converts to 31");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'w') == 32,
"U'w' converts to 32");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'x') == 33,
"U'x' converts to 33");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'y') == 34,
"U'y' converts to 34");
MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'z') == 35,
"U'z' converts to 35");
}
static void TestIsAsciiDigit() {
// char
static_assert(!IsAsciiDigit('/'), "'/' isn't an ASCII digit");
static_assert('/' == 0x2F, "'/' has value 0x2F");
static_assert('0' == 0x30, "'0' has value 0x30");
static_assert(IsAsciiDigit('0'), "'0' is an ASCII digit");
static_assert(IsAsciiDigit('1'), "'1' is an ASCII digit");
static_assert(IsAsciiDigit('5'), "'5' is an ASCII digit");
static_assert(IsAsciiDigit('8'), "'8' is an ASCII digit");
static_assert(IsAsciiDigit('9'), "'9' is an ASCII digit");
static_assert('9' == 0x39, "'9' has value 0x39");
static_assert(':' == 0x3A, "':' has value 0x3A");
static_assert(!IsAsciiDigit(':'), "':' isn't an ASCII digit");
static_assert(!IsAsciiDigit('@'), "'@' isn't an ASCII digit");
static_assert(!IsAsciiDigit('A'), "'A' isn't an ASCII digit");
static_assert(!IsAsciiDigit('B'), "'B' isn't an ASCII digit");
static_assert(!IsAsciiDigit('M'), "'M' isn't an ASCII digit");
static_assert(!IsAsciiDigit('Y'), "'Y' isn't an ASCII digit");
static_assert(!IsAsciiDigit('Z'), "'Z' isn't an ASCII digit");
static_assert(!IsAsciiDigit('['), "'[' isn't an ASCII digit");
static_assert(!IsAsciiDigit('`'), "'`' isn't an ASCII digit");
static_assert(!IsAsciiDigit('a'), "'a' isn't an ASCII digit");
static_assert(!IsAsciiDigit('b'), "'b' isn't an ASCII digit");
static_assert(!IsAsciiDigit('m'), "'m' isn't an ASCII digit");
static_assert(!IsAsciiDigit('y'), "'y' isn't an ASCII digit");
static_assert(!IsAsciiDigit('z'), "'z' isn't an ASCII digit");
static_assert(!IsAsciiDigit('{'), "'{' isn't an ASCII digit");
// char16_t
static_assert(!IsAsciiDigit(u'/'), "u'/' isn't an ASCII digit");
static_assert(u'/' == 0x2F, "u'/' has value 0x2F");
static_assert(u'0' == 0x30, "u'0' has value 0x30");
static_assert(IsAsciiDigit(u'0'), "u'0' is an ASCII digit");
static_assert(IsAsciiDigit(u'1'), "u'1' is an ASCII digit");
static_assert(IsAsciiDigit(u'5'), "u'5' is an ASCII digit");
static_assert(IsAsciiDigit(u'8'), "u'8' is an ASCII digit");
static_assert(IsAsciiDigit(u'9'), "u'9' is an ASCII digit");
static_assert(u'9' == 0x39, "u'9' has value 0x39");
static_assert(u':' == 0x3A, "u':' has value 0x3A");
static_assert(!IsAsciiDigit(u':'), "u':' isn't an ASCII digit");
static_assert(!IsAsciiDigit(u'@'), "u'@' isn't an ASCII digit");
static_assert(!IsAsciiDigit(u'A'), "u'A' isn't an ASCII digit");
static_assert(!IsAsciiDigit(u'B'), "u'B' isn't an ASCII digit");
static_assert(!IsAsciiDigit(u'M'), "u'M' isn't an ASCII digit");
static_assert(!IsAsciiDigit(u'Y'), "u'Y' isn't an ASCII digit");
static_assert(!IsAsciiDigit(u'Z'), "u'Z' isn't an ASCII digit");
static_assert(!IsAsciiDigit(u'['), "u'[' isn't an ASCII digit");
static_assert(!IsAsciiDigit(u'`'), "u'`' isn't an ASCII digit");
static_assert(!IsAsciiDigit(u'a'), "u'a' isn't an ASCII digit");
static_assert(!IsAsciiDigit(u'b'), "u'b' isn't an ASCII digit");
static_assert(!IsAsciiDigit(u'm'), "u'm' isn't an ASCII digit");
static_assert(!IsAsciiDigit(u'y'), "u'y' isn't an ASCII digit");
static_assert(!IsAsciiDigit(u'z'), "u'z' isn't an ASCII digit");
static_assert(!IsAsciiDigit(u'{'), "u'{' isn't an ASCII digit");
// char32_t
static_assert(!IsAsciiDigit(U'/'), "U'/' isn't an ASCII digit");
static_assert(U'/' == 0x2F, "U'/' has value 0x2F");
static_assert(U'0' == 0x30, "U'0' has value 0x30");
static_assert(IsAsciiDigit(U'0'), "U'0' is an ASCII digit");
static_assert(IsAsciiDigit(U'1'), "U'1' is an ASCII digit");
static_assert(IsAsciiDigit(U'5'), "U'5' is an ASCII digit");
static_assert(IsAsciiDigit(U'8'), "U'8' is an ASCII digit");
static_assert(IsAsciiDigit(U'9'), "U'9' is an ASCII digit");
static_assert(U'9' == 0x39, "U'9' has value 0x39");
static_assert(U':' == 0x3A, "U':' has value 0x3A");
static_assert(!IsAsciiDigit(U':'), "U':' isn't an ASCII digit");
static_assert(!IsAsciiDigit(U'@'), "U'@' isn't an ASCII digit");
static_assert(!IsAsciiDigit(U'A'), "U'A' isn't an ASCII digit");
static_assert(!IsAsciiDigit(U'B'), "U'B' isn't an ASCII digit");
static_assert(!IsAsciiDigit(U'M'), "U'M' isn't an ASCII digit");
static_assert(!IsAsciiDigit(U'Y'), "U'Y' isn't an ASCII digit");
static_assert(!IsAsciiDigit(U'Z'), "U'Z' isn't an ASCII digit");
static_assert(!IsAsciiDigit(U'['), "U'[' isn't an ASCII digit");
static_assert(!IsAsciiDigit(U'`'), "U'`' isn't an ASCII digit");
static_assert(!IsAsciiDigit(U'a'), "U'a' isn't an ASCII digit");
static_assert(!IsAsciiDigit(U'b'), "U'b' isn't an ASCII digit");
static_assert(!IsAsciiDigit(U'm'), "U'm' isn't an ASCII digit");
static_assert(!IsAsciiDigit(U'y'), "U'y' isn't an ASCII digit");
static_assert(!IsAsciiDigit(U'z'), "U'z' isn't an ASCII digit");
static_assert(!IsAsciiDigit(U'{'), "U'{' isn't an ASCII digit");
}
int main() {
TestIsAscii();
TestIsAsciiNullTerminated();
TestIsAsciiAlpha();
TestIsAsciiUppercaseAlpha();
TestIsAsciiLowercaseAlpha();
TestIsAsciiAlphanumeric();
TestAsciiAlphanumericToNumber();
TestIsAsciiDigit();
}
| 47.258216
| 80
| 0.63638
|
gregtatum
|
47f21e4f6679cab3af02c95b4f10ba36b13abc46
| 1,280
|
cpp
|
C++
|
src/Example/CubeExample.cpp
|
slicgun/ray_tracing
|
913f8a03887c20ca4fbad1fb38395b9f70fe54d4
|
[
"Apache-2.0"
] | null | null | null |
src/Example/CubeExample.cpp
|
slicgun/ray_tracing
|
913f8a03887c20ca4fbad1fb38395b9f70fe54d4
|
[
"Apache-2.0"
] | null | null | null |
src/Example/CubeExample.cpp
|
slicgun/ray_tracing
|
913f8a03887c20ca4fbad1fb38395b9f70fe54d4
|
[
"Apache-2.0"
] | null | null | null |
#include "CubeExample.h"
#include<vector>
#include<glm/geometric.hpp>
#include"Log.h"
std::vector<Material> mat;
Vertex v1 = {0, {0, 1, -3}, {0, 0, 1}, {0, 0}};
Vertex v2 = {0, {-1, 1, -3}, {0, 0, 1}, {0, 0}};
Vertex v3 = {0, {0, 0, -3}, {0, 0, 1}, {0, 0}};
CubeExample::CubeExample(Image& img)
:Example(img, "res/models/cube/cube.obj", {0, 0, 3}, 1, 3), m_texture("res/textures/test.png"), m_triangle(v1, v2, v3, mat)
{
m_camera.position = {0, 0, 0};
m_camera.target = {0, 0, -1};
m_camera.lookAt = glm::normalize(m_camera.target - m_camera.position);
m_camera.right = glm::normalize(glm::cross({0, 1, 0}, m_camera.lookAt));
m_camera.up = glm::cross(m_camera.lookAt, m_camera.right);
}
void CubeExample::draw()
{
for(unsigned y = 0; y < m_image.height; y++)
for(unsigned x = 0; x < m_image.width; x++)
{
glm::ivec2 pixel;
Ray r = getRayThroughPixel(pixel.x, pixel.y);
float u, v, t;
if(m_triangle.intersection(r, t, u, v))
{
float depth = r(t).z;
int depthBufferIndex = index(pixel.x, pixel.y);
glm::vec3 color = {1, 1, 1}; //m_texture.getColor((1 - v - u) * m_triangle[0].uv + u * m_triangle[1].uv + v * m_triangle[2].uv);
setPixelColor(x, y, color);
}
}
writeImage("cube");
}
| 28.444444
| 133
| 0.585938
|
slicgun
|
47f22170c5228eac4b407b78897ae5c4e93e9d35
| 3,772
|
cpp
|
C++
|
source/common/lua/performance.cpp
|
xiaobodu/breeze
|
e74f0cd680274fd431118104d1fdb45926da6328
|
[
"Apache-2.0"
] | 1
|
2020-08-13T08:10:15.000Z
|
2020-08-13T08:10:15.000Z
|
source/common/lua/performance.cpp
|
xiaobodu/breeze
|
e74f0cd680274fd431118104d1fdb45926da6328
|
[
"Apache-2.0"
] | null | null | null |
source/common/lua/performance.cpp
|
xiaobodu/breeze
|
e74f0cd680274fd431118104d1fdb45926da6328
|
[
"Apache-2.0"
] | 1
|
2017-04-30T14:25:25.000Z
|
2017-04-30T14:25:25.000Z
|
/*
* zsummerX License
* -----------
*
* zsummerX is licensed under the terms of the MIT license reproduced below.
* This means that zsummerX is free software and can be used for both academic
* and commercial purposes at absolutely no cost.
*
*
* ===============================================================================
*
* Copyright (C) 2010-2015 YaweiZhang <yawei.zhang@foxmail.com>.
*
* 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.
*
* ===============================================================================
*
* (end of COPYRIGHT)
*/
#include "performance.h"
static void hook_run_fn(lua_State *L, lua_Debug *ar);
static int newindex(lua_State * L)
{
lua_pushvalue(L, 1);
lua_pushvalue(L, 2);
lua_pushvalue(L, 3);
lua_rawset(L, 4);
lua_pop(L, 1);
const char * key = luaL_checkstring(L, 2);
const char * v = luaL_typename(L, 3);
std::stringstream ss;
ss << "catch one operation that it's set a global value. key=" << key << ", type(v)=" << v << ", is it correct ?";
if (lua_getglobal(L, "summer") == LUA_TTABLE && lua_getfield(L, -1, "logw") == LUA_TFUNCTION)
{
lua_pushstring(L, ss.str().c_str());
lua_pcall(L, 1, 0, 0);
}
else if (lua_getglobal(L, "print") == LUA_TFUNCTION)
{
lua_pushstring(L, ss.str().c_str());
lua_pcall(L, 1, 0, 0);
}
lua_pop(L, lua_gettop(L) - 3);
return 0;
}
zsummer::Performence __perf;
void luaopen_performence(lua_State * L)
{
//lua_Hook oldhook = lua_gethook(L);
//int oldmask = lua_gethookmask(L);
lua_sethook(L, &hook_run_fn, LUA_MASKCALL | LUA_MASKRET, 0);
lua_getglobal(L, "_G");
lua_newtable(L);
lua_pushcclosure(L, newindex, 0);
lua_setfield(L, -2, "__newindex");
lua_setmetatable(L, -2);
}
void hook_run_fn(lua_State *L, lua_Debug *ar)
{
// 获取Lua调用信息
lua_getinfo(L, "Snl", ar);
std::string key;
if (ar->source)
{
key += ar->source;
}
key += "_";
if (ar->what)
{
key += ar->what;
}
key += "_";
if (ar->namewhat)
{
key += ar->namewhat;
}
key += "_";
if (ar->name)
{
key += ar->name;
}
if (ar->event == LUA_HOOKCALL)
{
__perf._stack.push(key, lua_gc(L, LUA_GCCOUNT, 0) * 1024 + lua_gc(L, LUA_GCCOUNTB, 0));
}
else if (ar->event == LUA_HOOKRET)
{
//lua_gc(L, LUA_GCCOLLECT, 0);
auto t = __perf._stack.pop(key, lua_gc(L, LUA_GCCOUNT, 0) * 1024 + lua_gc(L, LUA_GCCOUNTB, 0));
if (std::get<0>(t))
{
__perf.call(key, std::get<1>(t), std::get<2>(t));
}
if (__perf.expire(50000.0))
{
__perf.dump(100);
}
}
}
| 30.176
| 118
| 0.595175
|
xiaobodu
|
47f7e140f4798a78082e3cbee4103984473522bd
| 1,021
|
cpp
|
C++
|
src/atomic.cpp
|
sriramch/thirdparty-libcxx
|
a97a7380c76346c22bb67b93695bed19592afad2
|
[
"Apache-2.0"
] | 2
|
2020-09-03T03:36:36.000Z
|
2020-09-03T08:09:10.000Z
|
src/atomic.cpp
|
sriramch/thirdparty-libcxx
|
a97a7380c76346c22bb67b93695bed19592afad2
|
[
"Apache-2.0"
] | 1
|
2019-12-27T02:42:26.000Z
|
2019-12-27T02:42:26.000Z
|
src/atomic.cpp
|
sriramch/thirdparty-libcxx
|
a97a7380c76346c22bb67b93695bed19592afad2
|
[
"Apache-2.0"
] | 3
|
2019-09-25T21:43:35.000Z
|
2020-03-27T19:12:47.000Z
|
//===------------------------- atomic.cpp ---------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifdef _LIBCPP_SIMT
#include <details/__config>
#else
#include "__config"
#endif
#ifndef _LIBCPP_HAS_NO_THREADS
#ifdef _LIBCPP_SIMT
#include <simt/atomic>
#else
#include "atomic"
#endif
_LIBCPP_BEGIN_NAMESPACE_STD
#if !defined(_LIBCPP_HAS_NO_THREAD_CONTENTION_TABLE)
__libcpp_contention_t __libcpp_contention_state_[ 256 /* < there's no magic in this number */ ];
_LIBCPP_FUNC_VIS
__libcpp_contention_t * __libcpp_contention_state(void const volatile * p) _NOEXCEPT {
return __libcpp_contention_state_ + ((std::uintptr_t)p & 255);
}
#endif //_LIBCPP_HAS_NO_THREAD_CONTENTION_TABLE
_LIBCPP_END_NAMESPACE_STD
#endif //_LIBCPP_HAS_NO_THREADS
| 26.868421
| 96
| 0.676787
|
sriramch
|
47f9627eb40dc250db2fe29a5e7e3c98b5bc0974
| 7,058
|
cpp
|
C++
|
test_samd21/dma_spi/program.cpp
|
azydevelopment/test-samd21
|
8442606d6909ada67a29f1f83c9ba3e7da16fd90
|
[
"MIT"
] | null | null | null |
test_samd21/dma_spi/program.cpp
|
azydevelopment/test-samd21
|
8442606d6909ada67a29f1f83c9ba3e7da16fd90
|
[
"MIT"
] | null | null | null |
test_samd21/dma_spi/program.cpp
|
azydevelopment/test-samd21
|
8442606d6909ada67a29f1f83c9ba3e7da16fd90
|
[
"MIT"
] | null | null | null |
#include "program.h"
#include <azydev/embedded/bus/spi/atmel/samd21/bus.h>
#include <azydev/embedded/bus/spi/atmel/samd21/device.h>
#include <azydev/embedded/clock/atmel/samd21/clock.h>
#include <azydev/embedded/dma/atmel/samd21/engine.h>
#include <azydev/embedded/dma/common/pool.h>
/* FILE SCOPED STATICS */
static const uint8_t SPI_BUS_ID = 0;
static const uint8_t NUM_SPI_BUS_DEVICES = 1;
static const uint8_t SPI_BUS_DEVICE_0_ID = 0;
static const uint8_t SPI_BUS_DEVICE_0_SS_PIN = PIN_PA05;
static const uint16_t NUM_BYTES = 4;
/* PUBLIC */
CProgram::CProgram()
: m_dma_clock(nullptr)
, m_dma_engine(nullptr)
, m_dma_pool(nullptr)
, m_dma_transfer(nullptr)
, m_spi_clock(nullptr)
, m_spi_bus(nullptr)
, m_spi_device(nullptr)
, m_pins(CPinsAtmelSAMD21()) {
}
CProgram::~CProgram() {
}
void CProgram::Main() {
OnInit();
while (1) {
OnUpdate();
}
}
void CProgram::OnInit() {
// init system
system_init();
// init DMA clock
{
CClockAtmelSAMD21::DESC desc = {};
desc.id = 0;
desc.clock_ahb = CClockAtmelSAMD21::CLOCK_AHB::CLOCK_DMAC;
desc.clock_apbb = CClockAtmelSAMD21::CLOCK_APBB::CLOCK_DMAC;
m_dma_clock = new CClockAtmelSAMD21(desc);
// no additional config needed
// leave clock enabled
m_dma_clock->SetEnabled(true);
}
// init DMA engine
{
CDMAEngineAtmelSAMD21<uint8_t>::DESC desc = {};
// create DMA engine
m_dma_engine = new CDMAEngineAtmelSAMD21<uint8_t>(desc);
// enable DMA engine
m_dma_engine->SetEnabled(true);
}
// init DMA pool
{
CDMAPool<uint8_t>::DESC descPool = {};
descPool.num_allocations_max = 1;
descPool.num_beats_max = NUM_BYTES;
m_dma_pool = new CDMAPool<uint8_t>(descPool);
}
// init DMA transfer object
{
CDMATransferAtmelSAMD21<uint8_t>::DESC desc = {};
desc.id_initial = 0;
desc.num_steps_max = 1;
// create DMA transfer
m_dma_transfer = new CDMATransferAtmelSAMD21<uint8_t>(desc);
}
// init SPI clock
{
CClockAtmelSAMD21::DESC desc = {};
desc.id = 0;
desc.clock_gclk = CClockAtmelSAMD21::CLOCK_GCLK::CLOCK_SERCOM2_CORE;
desc.clock_apbc = CClockAtmelSAMD21::CLOCK_APBC::CLOCK_SERCOM2;
m_spi_clock = new CClockAtmelSAMD21(desc);
CClockAtmelSAMD21::CONFIG_DESC config = {};
config.gclk_generator = CClockAtmelSAMD21::GCLK_GENERATOR::GEN0;
m_spi_clock->SetConfig(config);
// leave clock enabled
m_spi_clock->SetEnabled(true);
}
// init SPI target device
{
// init pin config
CSPIDeviceAtmelSAMD21::PIN_CONFIG_DESC pinConfig = {};
{ pinConfig.ss = SPI_BUS_DEVICE_0_SS_PIN; }
CSPIDeviceAtmelSAMD21::DESC desc = {};
desc.id = SPI_BUS_DEVICE_0_ID;
desc.pin_config = pinConfig;
// create SPI target device
// TODO HACK: Usage of 'new'
m_spi_device = new CSPIDeviceAtmelSAMD21(desc, m_pins);
}
// create SPI bus
{
// setup pin config
CSPIBusAtmelSAMD21::PIN_CONFIG_DESC pinConfig = {};
{
// TODO IMPLEMENT
pinConfig.pad0 = PINMUX_PA08D_SERCOM2_PAD0;
pinConfig.pad1 = PINMUX_UNUSED;
pinConfig.pad2 = PINMUX_PA10D_SERCOM2_PAD2;
pinConfig.pad3 = PINMUX_PA11D_SERCOM2_PAD3;
pinConfig.data_in_pinout = CSPIBusAtmelSAMD21::DATA_IN_PINOUT::PAD_0;
pinConfig.data_out_pinout =
CSPIBusAtmelSAMD21::DATA_OUT_PINOUT::DO_PAD2_SCK_PAD3_SS_PAD1;
}
CSPIBusAtmelSAMD21::DESC desc = {};
desc.id = SPI_BUS_ID;
desc.pin_config = pinConfig;
desc.sercomSpi = &(SERCOM2->SPI);
desc.num_devices = NUM_SPI_BUS_DEVICES;
desc.devices = &m_spi_device;
// create SPI bus
m_spi_bus = new CSPIBusAtmelSAMD21(desc, m_pins);
}
// configure SPI bus
{
// create config
CSPIBusAtmelSAMD21::CONFIG_DESC busConfig = {};
{
busConfig.endianness = CSPIBusAtmelSAMD21::ENDIANNESS::BIG;
busConfig.duplex_mode_intial = CSPIBusAtmelSAMD21::DUPLEX_MODE::FULL;
busConfig.clock_polarity = CSPIBusAtmelSAMD21::CLOCK_POLARITY::IDLE_LOW;
busConfig.clock_phase = CSPIBusAtmelSAMD21::CLOCK_PHASE::SAMPLE_TRAILING;
busConfig.frame_format = CSPIBusAtmelSAMD21::FRAME_FORMAT::SPI;
busConfig.immediate_buffer_overflow_notification = false;
busConfig.run_in_standby = false;
busConfig.address_mode = CSPIBusAtmelSAMD21::ADDRESS_MODE::MASK;
busConfig.enable_manager_worker_select = false;
busConfig.enable_worker_select_low_detect = false;
busConfig.enable_worker_data_preload = false;
busConfig.baud_rate = 128;
busConfig.enable_interrupt_error = false;
busConfig.enable_interrupt_worker_select_low = false;
busConfig.enable_interrupt_receive_complete = false;
busConfig.enable_interrupt_transmit_complete = false;
busConfig.enable_interrupt_data_register_empty = false;
// DMA
busConfig.dma_transfer_id = 0;
busConfig.dma_engine = m_dma_engine;
busConfig.dma_transfer = m_dma_transfer;
}
// set role
m_spi_bus->SetRole(CSPIEntity::ROLE::MANAGER);
// set config
m_spi_bus->SetConfig(busConfig);
// enable SPI
m_spi_bus->SetEnabled(true);
}
m_spi_bus->SetDeviceRole(SPI_BUS_DEVICE_0_ID, CSPIEntity::ROLE::WORKER);
}
void CProgram::OnUpdate() {
// reset DMA pool
m_dma_pool->PopAllocation();
// prepare transfer node
const IDMANode<uint8_t>* nodeSrc = nullptr;
{
// prepare source node
uint8_t allocationId = 0;
m_dma_pool->PushAllocation(allocationId);
for (uint32_t j = 0; j < NUM_BYTES; j++) {
m_dma_pool->RecordWrite(j);
}
nodeSrc = m_dma_pool->GetAllocationDMANode(allocationId);
}
// execute the SPI transfer
{
m_spi_bus->Start(SPI_BUS_DEVICE_0_ID);
// uint16_t data;
// m_spi_bus->Read(data);
// data = 0;
CSPIBusAtmelSAMD21* spiBusSAMD21 = static_cast<CSPIBusAtmelSAMD21*>(m_spi_bus);
spiBusSAMD21->Write(*nodeSrc, NUM_BYTES);
m_spi_bus->Stop();
}
}
| 31.792793
| 100
| 0.590536
|
azydevelopment
|
47fbba07d41575b11562d65477c18a9b23314a7b
| 173
|
cpp
|
C++
|
assec-renderer/src/renderer/shader.cpp
|
TeamVistic/assec-renderer
|
5c6fc9a46fc3f6302471a22bfd2bdf2942b794db
|
[
"Apache-2.0"
] | null | null | null |
assec-renderer/src/renderer/shader.cpp
|
TeamVistic/assec-renderer
|
5c6fc9a46fc3f6302471a22bfd2bdf2942b794db
|
[
"Apache-2.0"
] | null | null | null |
assec-renderer/src/renderer/shader.cpp
|
TeamVistic/assec-renderer
|
5c6fc9a46fc3f6302471a22bfd2bdf2942b794db
|
[
"Apache-2.0"
] | null | null | null |
#include "pch.h"
#include "shader.h"
namespace assec::renderer
{
shader::shader(const std::wstring& source, SHADER_TYPE type) : m_source(source), m_shader_type(type) {}
}
| 21.625
| 104
| 0.728324
|
TeamVistic
|
47fcb01c73b270ea1521ab1a777cd3884b6cb43c
| 3,137
|
cpp
|
C++
|
libraries/utilities/example/cmdline1.cpp
|
tneele/mCRL2
|
8f2d730d650ffec15130d6419f69c50f81e5125c
|
[
"BSL-1.0"
] | null | null | null |
libraries/utilities/example/cmdline1.cpp
|
tneele/mCRL2
|
8f2d730d650ffec15130d6419f69c50f81e5125c
|
[
"BSL-1.0"
] | null | null | null |
libraries/utilities/example/cmdline1.cpp
|
tneele/mCRL2
|
8f2d730d650ffec15130d6419f69c50f81e5125c
|
[
"BSL-1.0"
] | null | null | null |
// Author(s): Wieger Wesselink
// Copyright: see the accompanying file COPYING or copy at
// https://github.com/mCRL2org/mCRL2/blob/master/COPYING
//
// 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)
//
/// \file cmdline1.cpp
/// \brief CLI example
#include <iostream>
#include <stdexcept>
#include <string>
#include <utility>
#include "mcrl2/utilities/input_output_tool.h"
using namespace mcrl2;
using utilities::command_line_parser;
using utilities::interface_description;
using utilities::make_optional_argument;
using utilities::tools::tool;
/// The pbesinst tool.
class my_tool: public tool
{
protected:
typedef tool super;
std::string synopsis() const
{
return "[OPTION]... [FIRST]\n";
}
/// Parse the non-default options.
void parse_options(const command_line_parser& parser)
{
super::parse_options(parser);
std::string s = parser.option_argument("option1");
std::cout << "option o: " << s << std::endl;
int i = parser.option_argument_as<int>("option2");
std::cout << "option i: " << i << std::endl;
bool b = parser.option_argument_as<bool>("option3");
std::cout << "option b: " << std::boolalpha << b << std::endl;
bool a = parser.options.count("option4") > 0;
std::cout << "option a: " << std::boolalpha << a << std::endl;
if (0 < parser.arguments.size())
{
std::string s = parser.arguments[0];
std::cout << "positional option 1: " << s << std::endl;
}
std::cout << "--- parser arguments ---" << std::endl;
for (const auto & option : parser.options)
{
std::cout << option.first << " -> " << option.second << std::endl;
}
}
void add_options(interface_description& desc)
{
super::add_options(desc);
desc
/// string option with default value 'name1'
.add_option("option1",
make_optional_argument("NAME", "name1"),
"string option NAME:\n"
" 'name1' (default),\n"
" 'name2', or\n"
" 'name3'.",
'o')
/// integer option with default value 1
.add_option("option2",
make_optional_argument("NAME", "1"),
"integer option",
'i')
/// boolean option with default value true
.add_option("option3",
make_optional_argument("NAME", "1"),
"boolean option",
'b')
/// boolean flag (default off)
.add_option("option4",
"boolean option",
'a')
;
}
public:
/// Constructor.
my_tool()
: super(
"My tool",
"John Doe",
"One line description",
"First line of the long description. "
"Second line of the long description."
)
{}
/// Runs the tool.
bool run()
{
return true;
}
};
int main(int argc, char* argv[])
{
return my_tool().execute(argc, argv);
}
| 26.584746
| 74
| 0.559133
|
tneele
|
47fded78073828b55b3a98e9ff8bda0d3caa6284
| 37,799
|
cpp
|
C++
|
src/bitname/bitname_channel.cpp
|
gcbpay/R9-VRBcoinShares
|
2b77f7a77b9254e20250cdcd99c7a289fd0c3ca4
|
[
"Unlicense"
] | 2
|
2016-10-21T22:54:50.000Z
|
2017-11-08T07:06:46.000Z
|
src/bitname/bitname_channel.cpp
|
gcbpay/R9-VRBcoinShares
|
2b77f7a77b9254e20250cdcd99c7a289fd0c3ca4
|
[
"Unlicense"
] | 7
|
2016-10-23T12:26:43.000Z
|
2017-09-01T09:35:28.000Z
|
src/bitname/bitname_channel.cpp
|
gcbpay/R9-VRBcoinShares
|
2b77f7a77b9254e20250cdcd99c7a289fd0c3ca4
|
[
"Unlicense"
] | null | null | null |
#include <bts/bitname/bitname_channel.hpp>
#include <bts/bitname/bitname_messages.hpp>
#include <bts/bitname/bitname_db.hpp>
#include <bts/bitname/bitname_fork_db.hpp>
#include <bts/bitname/bitname_hash.hpp>
#include <bts/blockchain/fork_tree.hpp>
#include <bts/network/server.hpp>
#include <bts/network/channel.hpp>
#include <bts/network/broadcast_manager.hpp>
#include <bts/difficulty.hpp>
#include <fc/reflect/variant.hpp>
#include <fc/crypto/hex.hpp>
#include <fc/thread/thread.hpp>
#include <fc/log/logger.hpp>
#include <unordered_map>
namespace bts { namespace bitname {
using namespace bts::network;
namespace detail
{
class chan_data : public network::channel_data
{
public:
broadcast_manager<name_hash_type,name_header>::channel_data trxs_mgr;
broadcast_manager<name_id_type,name_block_index>::channel_data block_mgr;
fc::optional<fc::time_point> requested_headers;
fc::optional<fc::time_point> requested_block;
/** tracks the block ids this connection has reported to us */
std::unordered_set<name_id_type> available_blocks;
/// the head block as reported by the remote node
name_id_type recv_head_block_id;
/// the head block as we have reported to the remote node
name_id_type sent_head_block_id;
};
struct block_index_download_manager
{
name_block incomplete;
name_block_index index;
/** map short id to incomplete.name_trxs index */
std::unordered_map<short_name_id_type,uint32_t> unknown;
bool try_complete( const name_header& n )
{
auto itr = unknown.find(n.short_id());
if( itr != unknown.end() )
{
incomplete.name_trxs[itr->second] = n;
unknown.erase(itr);
}
return unknown.size() == 0;
}
};
struct fetch_loop_state
{
bool synchronizing;
};
class name_channel_impl : public bts::network::channel
{
public:
name_channel_impl()
:_delegate(nullptr),_new_block_info(true){}
name_channel_delegate* _delegate;
/** set this flag anytime the fork database has new info that
* might change what blocks to fetch.
*/
bool _new_block_info;
bts::peer::peer_channel_ptr _peers;
network::channel_id _chan_id;
name_db _name_db;
fork_db _fork_db;
fetch_loop_state _fetch_state;
fc::future<void> _fetch_loop;
// TODO: on connection disconnect, check to see if there was a pending fetch and
// cancel it so we can get it from someone else.
fc::optional<fc::time_point> _pending_block_fetch;
broadcast_manager<short_name_id_type,name_header> _trx_broadcast_mgr;
broadcast_manager<name_id_type,name_block_index> _block_index_broadcast_mgr;
std::vector<block_index_download_manager> _block_downloads;
void fetch_block_from_index( const name_block_index& index )
{
block_index_download_manager block_idx_downloader;
block_idx_downloader.incomplete = name_block(index.header);
block_idx_downloader.index = index;
block_idx_downloader.incomplete.name_trxs.resize( index.name_trxs.size() );
for( uint32_t i = 0; i < index.name_trxs.size(); ++i )
{
auto val = _trx_broadcast_mgr.get_value( index.name_trxs[i] );
if( val )
{
block_idx_downloader.incomplete.name_trxs[i] = *val;
}
else
{
FC_ASSERT( block_idx_downloader.unknown.find(index.name_trxs[i]) ==
block_idx_downloader.unknown.end() ); // checks for duplicates
block_idx_downloader.unknown[index.name_trxs[i]] = i;
}
}
if( block_idx_downloader.unknown.size() == 0 )
{
submit_block( block_idx_downloader.incomplete );
}
else
{
_block_downloads.push_back( block_idx_downloader );
fetch_unknown_name_trxs( _block_downloads.back() );
}
}
void fetch_unknown_name_trxs( const block_index_download_manager& dlmgr )
{
for( auto itr = dlmgr.unknown.begin(); itr != dlmgr.unknown.end(); ++itr )
{
// TODO: fetch missing from various hosts..
}
}
void update_block_index_downloads( const name_header& trx )
{
for( auto itr = _block_downloads.begin(); itr != _block_downloads.end(); )
{
if( itr->try_complete( trx) )
{
try {
submit_block( itr->incomplete );
}
catch ( fc::exception& e )
{
// TODO: how do we punish block that sent us this...
// what was the reason we couldn't submit it... peraps
// it is just too old and another block beat it to the
// punch...
wlog( "unable to submit block after download\n${e}",
("e",e.to_detail_string() ) );
}
itr = _block_downloads.erase(itr);
}
else
{
++itr;
}
}
}
void fetch_next_from_fork_db()
{ try {
if( _pending_block_fetch &&
(fc::time_point::now() - *_pending_block_fetch) < fc::seconds( BITNAME_BLOCK_FETCH_TIMEOUT_SEC ) )
{
return;
}
if( _new_block_info )
{
_new_block_info = false;
auto valid_head_num = _name_db.head_block_num();
//ilog( "valid_head_num: ${v}", ("v",valid_head_num) );
if( valid_head_num >= _fork_db.best_fork_height() )
{
return;
}
meta_header next_best = _fork_db.best_fork_fetch_at( valid_head_num + 1);
//ilog( "next_best: ${v}", ("v",next_best) );
//ilog( "head_block_id: ${v}", ("v",_name_db.head_block_id()) );
while( next_best.prev != _name_db.head_block_id() )
{
wlog( "pop back!" );
_name_db.pop_block();
next_best = _fork_db.fetch_header( next_best.prev );
ilog( "next_best: ${v}", ("v",next_best) );
}
fc::optional<name_block> next_block = _fork_db.fetch_block( next_best.id() );
if( next_block )
{
try {
_name_db.push_block( *next_block );
}
catch ( const fc::exception& e )
{
elog( "error applying block from this fork, this fork must be invalid\n${e}", ( "e", e.to_detail_string() ) );
_fork_db.set_valid( next_block->id(), false );
}
_new_block_info = true; // attempt another block on next call
}
else
{
auto cons = _peers->get_connections( _chan_id );
if( cons.size() != 0 )
{
fetch_block_from_best_connection( cons, next_best.id() );
}
}
}
} FC_RETHROW_EXCEPTIONS( warn , "" ) }
/**
* The fetch loop has several modes:
* 1) synchronize mode.
* 2) maitenance mode.
*
* In Synchronize mode the client is not conserned with inventory
* notices from other nodes. In fact, other nodes probably shouldn't
* bother broadcasting inv notices to us until we have finished sync.
*
* The client stays in synchronize mode until it has determined that it
* is on the proper chain. When a client first connects it sends a request
* for new block headers and it will get a response that may include
* a potential chain reorganization though this should be relatively
* rare.
*
*/
void fetch_loop()
{
try
{
while( !_fetch_loop.canceled() )
{
broadcast_inv();
fetch_next_from_fork_db();
short_name_id_type trx_query = 0;
if( _trx_broadcast_mgr.find_next_query( trx_query ) )
{
auto cons = _peers->get_connections( _chan_id );
fetch_name_from_best_connection( cons, trx_query );
_trx_broadcast_mgr.item_queried( trx_query );
}
name_id_type blk_idx_query;
if( _block_index_broadcast_mgr.find_next_query( blk_idx_query ) )
{
auto cons = _peers->get_connections( _chan_id );
fetch_block_idx_from_best_connection( cons, blk_idx_query );
_block_index_broadcast_mgr.item_queried( blk_idx_query );
}
/* By using a random sleep we give other peers the oppotunity to find
* out about messages before we pick who to fetch from.
* TODO: move constants to config.hpp
*
* TODO: fetch set your fetch order based upon how many times we have received
* an inv regarding a particular item.
*
* TODO: make sure we seed rand()
*/
fc::usleep( fc::microseconds( (rand() % 20000) + 100) );
}
}
catch ( const fc::exception& e )
{
elog( "fetch loop threw... something bad happened\n${e}", ("e", e.to_detail_string()) );
// TODO: bitname will hang if we don't find some way to recover or report this
// to the user...
}
}
void request_latest_blocks()
{
auto cons = _peers->get_connections( _chan_id );
for( auto c = cons.begin(); c != cons.end(); ++c )
{
request_block_headers( *c );
}
}
/**
* Send any new inventory items that we have received since the last
* broadcast to all connections that do not know about the inv item.
*/
void broadcast_inv()
{ try {
if( _trx_broadcast_mgr.has_new_since_broadcast() || _block_index_broadcast_mgr.has_new_since_broadcast() )
{
auto cons = _peers->get_connections( _chan_id );
if( _trx_broadcast_mgr.has_new_since_broadcast() )
{
for( auto c = cons.begin(); c != cons.end(); ++c )
{
name_inv_message inv_msg;
chan_data& con_data = get_channel_data( *c );
inv_msg.name_trxs = _trx_broadcast_mgr.get_inventory( con_data.trxs_mgr );
if( inv_msg.name_trxs.size() )
{
(*c)->send( network::message(inv_msg,_chan_id) );
}
con_data.trxs_mgr.update_known( inv_msg.name_trxs );
}
_trx_broadcast_mgr.set_new_since_broadcast(false);
}
if( _block_index_broadcast_mgr.has_new_since_broadcast() )
{
for( auto c = cons.begin(); c != cons.end(); ++c )
{
block_inv_message inv_msg;
chan_data& con_data = get_channel_data( *c );
inv_msg.block_ids = _block_index_broadcast_mgr.get_inventory( con_data.block_mgr );
if( inv_msg.block_ids.size() )
{
(*c)->send( network::message(inv_msg,_chan_id) );
}
con_data.block_mgr.update_known( inv_msg.block_ids );
}
_block_index_broadcast_mgr.set_new_since_broadcast(false);
}
}
} FC_RETHROW_EXCEPTIONS( warn, "error broadcasting bitname inventory") } // broadcast_inv
/**
* For any given message id, there are many potential hosts from which it could be fetched. We
* want to distribute the load across all hosts equally and therefore, the best one to fetch from
* is the host that we have fetched the least from and that has fetched the most from us.
*/
void fetch_name_from_best_connection( const std::vector<connection_ptr>& cons, uint64_t id )
{ try {
ilog( "${id}", ("id",id) );
// if request is made, move id from unknown_names to requested_msgs
// TODO: update this algorithm to be something better.
for( uint32_t i = 0; i < cons.size(); ++i )
{
ilog( "con ${i}", ("i",i) );
chan_data& chan_data = get_channel_data(cons[i]);
if( chan_data.trxs_mgr.knows( id ) && !chan_data.trxs_mgr.has_pending_request() )
{
chan_data.trxs_mgr.requested(id);
get_name_header_message request( id );
ilog( "request ${msg}", ("msg",request) );
cons[i]->send( network::message( request, _chan_id ) );
return;
}
}
} FC_RETHROW_EXCEPTIONS( warn, "error fetching name ${name_hash}", ("name_hash",id) ) }
void fetch_block_from_best_connection( const std::vector<connection_ptr>& cons, const name_id_type& id )
{ try {
ilog( "${id}", ("id",id) );
// if request is made, move id from unknown_names to requested_msgs
// TODO: update this algorithm to be something better.
for( uint32_t i = 0; i < cons.size(); ++i )
{
ilog( "con ${i}", ("i",i) );
chan_data& chan_data = get_channel_data(cons[i]);
if( chan_data.available_blocks.find(id) != chan_data.available_blocks.end() )
{
ilog( "request ${msg}", ("msg",get_block_message(id)) );
_pending_block_fetch = fc::time_point::now();
get_channel_data( cons[i] ).requested_block = *_pending_block_fetch;
// TODO: track how many blocks I have requested from this connection...
// and perform soem load balancing...
cons[i]->send( network::message( get_block_message(id), _chan_id ) );
return;
}
else
{
}
}
} FC_RETHROW_EXCEPTIONS( warn, "error fetching name ${name_hash}", ("name_hash",id) ) }
void fetch_block_idx_from_best_connection( const std::vector<connection_ptr>& cons, const name_id_type& id )
{ try {
ilog( "${id}", ("id",id) );
// if request is made, move id from unknown_names to requested_msgs
// TODO: update this algorithm to be something better.
for( uint32_t i = 0; i < cons.size(); ++i )
{
ilog( "con ${i}", ("i",i) );
chan_data& chan_data = get_channel_data(cons[i]);
if( chan_data.block_mgr.knows(id) && !chan_data.block_mgr.has_pending_request() )
{
ilog( "request ${msg}", ("msg",get_block_index_message(id)) );
chan_data.block_mgr.requested(id);
// TODO: track how many blocks I have requested from this connection...
// and perform soem load balancing...
cons[i]->send( network::message( get_block_index_message(id), _chan_id ) );
return;
}
}
} FC_RETHROW_EXCEPTIONS( warn, "error fetching name ${name_hash}", ("name_hash",id) ) }
/**
* Get or create the bitchat channel data for this connection and return
* a reference to the result.
*/
chan_data& get_channel_data( const connection_ptr& c )
{
auto cd = c->get_channel_data( _chan_id );
if( !cd )
{
cd = std::make_shared<chan_data>();
c->set_channel_data( _chan_id, cd );
}
chan_data& cdat = cd->as<chan_data>();
return cdat;
}
virtual void handle_subscribe( const connection_ptr& c )
{
get_channel_data(c); // creates it...
request_latest_blocks();
}
virtual void handle_unsubscribe( const connection_ptr& c )
{
c->set_channel_data( _chan_id, nullptr );
}
/* ===================================================== */
void handle_message( const connection_ptr& con, const message& m )
{
try {
chan_data& cdat = get_channel_data(con);
ilog( "${msg_type}", ("msg_type", (bitname::message_type)m.msg_type ) );
switch( (bitname::message_type)m.msg_type )
{
case name_inv_msg:
handle_name_inv( con, cdat, m.as<name_inv_message>() );
break;
case block_inv_msg:
handle_block_inv( con, cdat, m.as<block_inv_message>() );
break;
case get_name_inv_msg:
handle_get_name_inv( con, cdat, m.as<get_name_inv_message>() );
break;
case get_headers_msg:
handle_get_headers( con, cdat, m.as<get_headers_message>() );
break;
case get_block_msg:
handle_get_block( con, cdat, m.as<get_block_message>() );
break;
case get_block_index_msg:
handle_get_block_index( con, cdat, m.as<get_block_index_message>() );
break;
case get_name_header_msg:
handle_get_name( con, cdat, m.as<get_name_header_message>() );
break;
case name_header_msg:
handle_name( con, cdat, m.as<name_header_message>() );
break;
case block_index_msg:
handle_block_index( con, cdat, m.as<block_index_message>() );
break;
case block_msg:
handle_block( con, cdat, m.as<block_message>() );
break;
case headers_msg:
handle_headers( con, cdat, m.as<headers_message>() );
break;
default:
FC_THROW_EXCEPTION( exception, "unknown bitname message type ${msg_type}", ("msg_type", m.msg_type ) );
}
}
catch ( fc::exception& e )
{
wlog( "${e} ${from}", ("e",e.to_detail_string())("from",con->remote_endpoint()) );
}
} // handle_message
/* ===================================================== */
void request_block_headers( const connection_ptr& con )
{
chan_data& cdat = get_channel_data(con);
FC_ASSERT( !cdat.requested_headers );
ilog( "requesting block headers from ${ep}", ("ep",con->remote_endpoint() ));
get_headers_message request;
const std::vector<name_id_type>& ids = _name_db.get_header_ids();
uint32_t delta = 1;
for( int32_t i = ids.size() - 1; i >= 0; )
{
request.locator_hashes.push_back(ids[i]);
i -= delta;
delta *= 2;
}
cdat.requested_headers = fc::time_point::now();
con->send( network::message(request,_chan_id) );
}
/* ===================================================== */
void handle_name_inv( const connection_ptr& con, chan_data& cdat, const name_inv_message& msg )
{
ilog( "inv: ${msg}", ("msg",msg) );
for( auto itr = msg.name_trxs.begin(); itr != msg.name_trxs.end(); ++itr )
{
_trx_broadcast_mgr.received_inventory_notice( *itr );
}
cdat.trxs_mgr.update_known( msg.name_trxs );
}
/* ===================================================== */
void handle_block_inv( const connection_ptr& con, chan_data& cdat, const block_inv_message& msg )
{
ilog( "inv: ${msg}", ("msg",msg) );
for( auto itr = msg.block_ids.begin(); itr != msg.block_ids.end(); ++itr )
{
_block_index_broadcast_mgr.received_inventory_notice( *itr );
}
cdat.block_mgr.update_known( msg.block_ids );
}
/* ===================================================== */
void handle_get_name_inv( const connection_ptr& con, chan_data& cdat, const get_name_inv_message& msg )
{
name_inv_message reply;
reply.name_trxs = _trx_broadcast_mgr.get_inventory( cdat.trxs_mgr );
cdat.trxs_mgr.update_known( reply.name_trxs );
con->send( network::message(reply,_chan_id) );
}
/* ===================================================== */
void handle_get_headers( const connection_ptr& con, chan_data& cdat, const get_headers_message& msg )
{ try {
// TODO: prevent abuse of this message... only allow it at a limited rate and take notice
// when the remote node starts abusing it.
uint32_t start_block = 0;
for( uint32_t i = 0; i < msg.locator_hashes.size(); ++i )
{
try {
start_block = _name_db.get_block_num( msg.locator_hashes[i] );
break;
}
catch ( const fc::exception& e )
{
// TODO: should I do something other than log this exception?
wlog( "apparently this node is on a different fork, error fetching ${id}\n${e}",
("id", msg.locator_hashes[i] )("e",e.to_detail_string()) );
}
}
const std::vector<name_id_type>& ids = _name_db.get_header_ids();
uint32_t end = std::min<uint32_t>(start_block+2000, ids.size() );
headers_message reply;
reply.first_block_num = start_block;
reply.first = _name_db.fetch_block_header(start_block);
reply.headers.reserve( end - start_block - 1 );
for( auto i = start_block+1; i < end; ++i )
{
reply.headers.push_back( _name_db.fetch_block_header(ids[i]) );
}
reply.head_block_num = ids.size() - 1;
reply.head_block_id = ids.back();
con->send( network::message( reply, _chan_id ) );
} FC_RETHROW_EXCEPTIONS( warn, "", ("msg",msg) ) }
/* ===================================================== */
void handle_get_block_index( const connection_ptr& con, chan_data& cdat, const get_block_index_message& msg )
{ try {
ilog( "${msg}", ("msg",msg) );
const fc::optional<name_block_index>& trx = _block_index_broadcast_mgr.get_value( msg.block_id );
if( !trx ) // must be a db
{
auto debug_str = _block_index_broadcast_mgr.debug();
FC_ASSERT( !"Name block index not in broadcast cache", "${str}", ("str",debug_str) );
}
con->send( network::message( block_index_message( *trx ), _chan_id ) );
} FC_RETHROW_EXCEPTIONS( warn, "", ("msg",msg) ) }
/* ===================================================== */
void handle_get_block( const connection_ptr& con, chan_data& cdat, const get_block_message& msg )
{ try {
// TODO: charge POW for this...
auto block = _name_db.fetch_block( msg.block_id );
con->send( network::message( block_message( std::move(block) ), _chan_id ) );
} FC_RETHROW_EXCEPTIONS( warn, "", ("msg",msg) ) }
/* ===================================================== */
void handle_get_name( const connection_ptr& con, chan_data& cdat, const get_name_header_message& msg )
{
ilog( "${msg}", ("msg",msg) );
const fc::optional<name_header>& trx = _trx_broadcast_mgr.get_value( msg.name_trx_id );
if( !trx ) // must be a db
{
auto debug_str = _trx_broadcast_mgr.debug();
FC_ASSERT( !"Name transaction not in broadcast cache", "${str}", ("str",debug_str) );
/*
... we should not allow fetching of individual name trx from our db...
this would require a huge index
name_header trx = _name_db.fetch_trx_header( msg.name_trx_id );
con->send( network::message( name_header_message( trx ), _chan_id ) );
*/
}
else
{
con->send( network::message( name_header_message( *trx ), _chan_id ) );
}
}
void handle_block_index( const connection_ptr& con, chan_data& cdat, const block_index_message& msg )
{
ilog( "${msg}", ("msg",msg) );
cdat.block_mgr.received_response( msg.index.header.id() );
_fork_db.cache_header( msg.index.header );
_new_block_info = true;
if( msg.index.name_trxs.size() == 0 )
{
submit_block( msg.index.header );
}
else
{
_block_downloads.push_back( block_index_download_manager() );
block_index_download_manager& dlmgr = _block_downloads.back();
dlmgr.incomplete = name_block(msg.index.header);
dlmgr.index = msg.index;
dlmgr.incomplete.name_trxs.resize( msg.index.name_trxs.size() );
for( uint32_t i = 0; i < msg.index.name_trxs.size(); ++i )
{
auto opt_trx = _trx_broadcast_mgr.get_value( msg.index.name_trxs[i] );
if( opt_trx )
{
dlmgr.incomplete.name_trxs[i] = *opt_trx;
}
else
{
dlmgr.unknown[msg.index.name_trxs[i]] = i;
_trx_broadcast_mgr.received_inventory_notice( msg.index.name_trxs[i] );
cdat.trxs_mgr.update_known( msg.index.name_trxs[i] );
}
}
if( dlmgr.unknown.size() == 0 )
{
submit_block( dlmgr.incomplete );
_block_downloads.pop_back();
}
}
}
void handle_name( const connection_ptr& con, chan_data& cdat, const name_header_message& msg )
{ try {
ilog( "${msg}", ("msg",msg) );
auto short_id = msg.trx.short_id();
cdat.trxs_mgr.received_response( short_id );
try {
// attempt to complete blocks without validating the trx so that
// we can then mark the block as 'complete' and then invalidate it
update_block_index_downloads( msg.trx );
submit_name( msg.trx );
}
catch ( fc::exception& e )
{
// TODO: connection just sent us an invalid trx... what do we do...
// log it and ignore it because it was probably for the prior
// block that they haven't received yet... we should note it though.
//
// it may be valid because we are not yet synced...
_trx_broadcast_mgr.validated( short_id, msg.trx, false );
// FC_RETHROW_EXCEPTION( e, warn, "" );
}
} FC_RETHROW_EXCEPTIONS( warn, "", ("msg", msg) ) }
void handle_block( const connection_ptr& con, chan_data& cdat, const block_message& msg )
{ try {
FC_ASSERT( !!cdat.requested_block );
// TODO: make sure that I requrested this block...
_fork_db.cache_block( msg.block );
_new_block_info = true;
cdat.requested_block.reset();
_pending_block_fetch.reset();
try {
submit_block(msg.block); //_name_db.push_block( msg.block );
}
catch( const fc::exception& e )
{
// don't try to fetch this or any of its decendants again..
//_fork_tree.set_valid_state( _name_db.head_block_num()+1, msg.block.id(), false );
throw;
}
} FC_RETHROW_EXCEPTIONS( warn,"handling block ${block}", ("block",msg) ) }
/**
* Received in response to get_headers message, we should certify that we requested this.
*/
void handle_headers( const connection_ptr& con, chan_data& cdat, const headers_message& msg )
{ try {
FC_ASSERT( !!cdat.requested_headers );
cdat.requested_headers.reset();
// TODO: validate that all ids reported have the min proof of work for a name.
ilog( "received ${msg}", ("msg",msg) );
_fork_db.cache_header( msg.first );
_new_block_info = true;
name_id_type prev_id = msg.first.id();
for( auto itr = msg.headers.begin(); itr != msg.headers.end(); ++itr )
{
name_header next_head( *itr, prev_id );
ilog( "${id} = ${next_head}", ("id",next_head.id())("next_head",next_head) );
_fork_db.cache_header( next_head );
prev_id = next_head.id();
cdat.available_blocks.insert(prev_id);
}
if( prev_id != msg.head_block_id )
{
cdat.requested_headers = fc::time_point::now();
get_headers_message request;
request.locator_hashes.push_back( prev_id );
con->send( network::message( request, _chan_id ) );
}
} FC_RETHROW_EXCEPTIONS( warn, "", ("msg",msg) ) }
void submit_name( const name_header& new_name_trx )
{ try {
_name_db.validate_trx( new_name_trx );
_trx_broadcast_mgr.validated( new_name_trx.short_id(), new_name_trx, true );
if( _delegate )
{
try {
_delegate->pending_name_trx( new_name_trx );
}
catch ( const fc::exception& e )
{
// This could fail if the head block was replaced between the start of the last
// mining round and the discovery of a name... perhaps catch this earlier rather than
// waiting until we get here!
wlog( "delegate threw exception... it shouldn't do that!\n ${e}", ("e", e.to_detail_string() ) );
}
}
} FC_RETHROW_EXCEPTIONS( warn, "error submitting name", ("new_name_trx", new_name_trx) ) }
void submit_block( const name_block& block )
{ try {
_fork_db.cache_block( block );
_new_block_info = true;
_name_db.push_block( block ); // this throws on error
_trx_broadcast_mgr.invalidate_all(); // current inventory is now invalid
_block_index_broadcast_mgr.clear_old_inventory(); // we can clear old inventory
_trx_broadcast_mgr.clear_old_inventory(); // this inventory no longer matters
_block_index_broadcast_mgr.validated( block.id(), block, true );
_name_db.dump(); // DEBUG
if( _delegate ) _delegate->name_block_added( block );
} FC_RETHROW_EXCEPTIONS( warn, "error submitting block", ("block", block) ) }
};
} // namespace detail
name_channel::name_channel( const bts::peer::peer_channel_ptr& n )
:my( new detail::name_channel_impl() )
{
my->_peers = n;
my->_chan_id = channel_id(network::name_proto,0);
my->_peers->subscribe_to_channel( my->_chan_id, my );
}
name_channel::~name_channel()
{
my->_peers->unsubscribe_from_channel( my->_chan_id );
my->_delegate = nullptr;
try {
if( my->_fetch_loop.valid() )
{
my->_fetch_loop.cancel();
my->_fetch_loop.wait();
}
}
catch ( ... )
{
wlog( "unexpected exception ${e}", ("e", fc::except_str()));
}
}
void name_channel::configure( const name_channel::config& c )
{
fc::create_directories( c.name_db_dir / "forks" );
my->_name_db.open( c.name_db_dir, true/*create*/ );
my->_fork_db.open( c.name_db_dir / "forks" , true/*create*/ );
my->_fetch_loop = fc::async( [=](){ my->fetch_loop(); } );
// TODO: connect to the network and attempt to download the chain...
// * what if no peers on on the name channel ?? *
// I guess when I do connect to a peer on this channel they will
// learn that I am subscribed to this channel...
}
void name_channel::set_delegate( name_channel_delegate* d )
{
my->_delegate = d;
}
void name_channel::submit_name( const name_header& new_name_trx )
{
my->submit_name( new_name_trx );
}
void name_channel::submit_block( const name_block& block_to_submit )
{
auto id = block_to_submit.id();
uint64_t block_difficulty = bts::difficulty(id);
//ilog( "target: ${target} block ${block}", ("target",my->_name_db.target_difficulty())("block",block_difficulty) );
if( block_difficulty >= my->_name_db.target_difficulty() )
{
my->submit_block( block_to_submit );
}
else
{
submit_name( block_to_submit );
}
}
/**
* Performs a lookup in the internal database
*/
fc::optional<name_record> name_channel::lookup_name( const std::string& name )
{ try {
try {
name_trx last_trx = my->_name_db.fetch_trx( name_hash( name ) );
name_record name_rec;
name_rec.last_update = last_trx.utc_sec;
name_rec.pub_key = last_trx.key;
name_rec.age = last_trx.age;
name_rec.repute = my->_name_db.fetch_repute( name_hash(name) ); //last_trx.repute_points;
name_rec.revoked = last_trx.key == fc::ecc::public_key_data();
name_rec.name_hash = fc::to_hex((char*)&last_trx.name_hash, sizeof(last_trx.name_hash));
name_rec.name = name;
return name_rec;
}
catch ( const fc::key_not_found_exception& )
{
// expected, convert to null optional, all other errors should be
// thrown up the chain
}
return fc::optional<name_record>();
} FC_RETHROW_EXCEPTIONS( warn, "name: ${name}", ("name",name) ) }
uint32_t name_channel::get_head_block_number()const
{
return my->_name_db.head_block_num();
}
name_id_type name_channel::get_head_block_id()const
{
return my->_name_db.head_block_id();
}
std::vector<name_header> name_channel::get_pending_name_trxs()const
{
return my->_trx_broadcast_mgr.get_inventory_values();
}
} } // bts::bitname
| 42.710734
| 135
| 0.500966
|
gcbpay
|
9a0b33f2d7300aa1b7233ff1b54c5f6a5b33909c
| 2,812
|
cc
|
C++
|
o3d/plugin/cross/blacklist.cc
|
rwatson/chromium-capsicum
|
b03da8e897f897c6ad2cda03ceda217b760fd528
|
[
"BSD-3-Clause"
] | 11
|
2015-03-20T04:08:08.000Z
|
2021-11-15T15:51:36.000Z
|
o3d/plugin/cross/blacklist.cc
|
changbai1980/chromium
|
c4625eefca763df86471d798ee5a4a054b4716ae
|
[
"BSD-3-Clause"
] | null | null | null |
o3d/plugin/cross/blacklist.cc
|
changbai1980/chromium
|
c4625eefca763df86471d798ee5a4a054b4716ae
|
[
"BSD-3-Clause"
] | 1
|
2020-04-13T05:45:10.000Z
|
2020-04-13T05:45:10.000Z
|
/*
* Copyright 2009, Google 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 Google 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.
*/
#include <iostream>
#include <fstream>
#include "plugin/cross/config.h"
#include "base/logging.h"
namespace o3d {
// Checks the driver GUID against the blacklist file. Returns true if there's a
// match [this driver is blacklisted] or if an IO error occurred. Check the
// state of input_file to determine which it was.
//
// Note that this function always returns false if the guid is 0, since it will
// be zero if we had a failure in reading it, and the user will already have
// been warned.
bool IsDriverBlacklisted(std::ifstream *input_file, unsigned int guid) {
if (!guid) {
return false;
}
*input_file >> std::ws;
while (input_file->good()) {
if (input_file->peek() == '#') {
char comment[256];
input_file->getline(comment, 256);
// If the line was too long for this to work, it'll set the failbit.
} else {
unsigned int id;
*input_file >> std::hex >> id;
if (id == guid) {
return true;
}
}
*input_file >> std::ws; // Skip whitespace here, to catch EOF cleanly.
}
if (input_file->fail()) {
LOG(ERROR) << "Failed to read the blacklisted driver file completely.";
return true;
}
CHECK(input_file->eof());
return false;
}
} // namespace o3d
| 38
| 80
| 0.713371
|
rwatson
|
9a0bfaff0340d3a2b1aca283326d460b206a3dcf
| 5,158
|
cpp
|
C++
|
webrtc-jni/src/main/cpp/src/media/video/VideoTrackDesktopSource.cpp
|
preciate/webrtc-java
|
9073e12b57a74e8c89ed0950d41d29ab7f5cc691
|
[
"Apache-2.0"
] | null | null | null |
webrtc-jni/src/main/cpp/src/media/video/VideoTrackDesktopSource.cpp
|
preciate/webrtc-java
|
9073e12b57a74e8c89ed0950d41d29ab7f5cc691
|
[
"Apache-2.0"
] | null | null | null |
webrtc-jni/src/main/cpp/src/media/video/VideoTrackDesktopSource.cpp
|
preciate/webrtc-java
|
9073e12b57a74e8c89ed0950d41d29ab7f5cc691
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2019 Alex Andres
*
* 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 "media/video/VideoTrackDesktopSource.h"
#include "Exception.h"
#include "api/video/i420_buffer.h"
#include "libyuv/convert.h"
#include "modules/desktop_capture/cropping_window_capturer.h"
#include "modules/desktop_capture/desktop_capture_options.h"
#include "modules/video_capture/video_capture_factory.h"
#include "third_party/libyuv/include/libyuv/video_common.h"
#include "system_wrappers/include/sleep.h"
#include "modules/desktop_capture/desktop_capturer.h"
#include "modules/desktop_capture/desktop_and_cursor_composer.h"
#include "modules/desktop_capture/mouse_cursor_monitor.h"
namespace jni
{
VideoTrackDesktopSource::VideoTrackDesktopSource() :
AdaptedVideoTrackSource(),
frameRate(20),
isCapturing(false),
sourceState(kInitializing),
sourceId(-1),
sourceIsWindow(false)
{
}
VideoTrackDesktopSource::~VideoTrackDesktopSource()
{
stop();
}
void VideoTrackDesktopSource::setSourceId(webrtc::DesktopCapturer::SourceId source, bool isWindow)
{
this->sourceId = source;
this->sourceIsWindow = isWindow;
}
void VideoTrackDesktopSource::setFrameRate(const uint16_t frameRate)
{
this->frameRate = frameRate;
}
void VideoTrackDesktopSource::start()
{
isCapturing = true;
captureThread = rtc::Thread::Create();
captureThread->Start();
captureThread->PostTask(RTC_FROM_HERE, [&] { capture(); });
}
void VideoTrackDesktopSource::stop()
{
if (isCapturing) {
isCapturing = false;
captureThread->Stop();
captureThread.reset();
}
}
bool VideoTrackDesktopSource::is_screencast() const {
return true;
}
absl::optional<bool> VideoTrackDesktopSource::needs_denoising() const {
return false;
}
webrtc::MediaSourceInterface::SourceState VideoTrackDesktopSource::state() const {
return sourceState;
}
bool VideoTrackDesktopSource::remote() const {
return false;
}
void VideoTrackDesktopSource::OnCaptureResult(webrtc::DesktopCapturer::Result result, std::unique_ptr<webrtc::DesktopFrame> frame)
{
if (result != webrtc::DesktopCapturer::Result::SUCCESS) {
return;
}
int width = frame->size().width();
int height = frame->size().height();
int64_t time = rtc::TimeMicros();
int adapted_width;
int adapted_height;
int crop_width;
int crop_height;
int crop_x;
int crop_y;
if (!AdaptFrame(width, height, time, &adapted_width, &adapted_height, &crop_width, &crop_height, &crop_x, &crop_y)) {
// Drop frame in order to respect frame rate constraint.
return;
}
if (!buffer || buffer->width() != width || buffer->height() != height) {
buffer = webrtc::I420Buffer::Create(width, height);
}
const int conversionResult = libyuv::ARGBToI420(frame->data(), frame->stride(),
buffer->MutableDataY(), buffer->StrideY(),
buffer->MutableDataU(), buffer->StrideU(),
buffer->MutableDataV(), buffer->StrideV(),
width, height);
if (conversionResult >= 0) {
if (adapted_width != width || adapted_height != height) {
// Video adapter has requested a down-scale. Allocate a new buffer and return scaled version.
rtc::scoped_refptr<webrtc::I420Buffer> scaled_buffer = webrtc::I420Buffer::Create(adapted_width, adapted_height);
scaled_buffer->ScaleFrom(*buffer);
OnFrame(webrtc::VideoFrame::Builder()
.set_video_frame_buffer(scaled_buffer)
.set_rotation(webrtc::kVideoRotation_0)
.set_timestamp_us(time)
.build());
}
else {
// No adaptations needed, just return the frame as is.
OnFrame(webrtc::VideoFrame::Builder()
.set_video_frame_buffer(buffer)
.set_rotation(webrtc::kVideoRotation_0)
.set_timestamp_us(time)
.build());
}
}
}
void VideoTrackDesktopSource::capture()
{
auto options = webrtc::DesktopCaptureOptions::CreateDefault();
// Enable desktop effects.
options.set_disable_effects(false);
#if defined(WEBRTC_WIN)
options.set_allow_directx_capturer(true);
options.set_allow_use_magnification_api(true);
#endif
std::unique_ptr<webrtc::DesktopCapturer> capturer;
if (sourceIsWindow) {
capturer.reset(new webrtc::DesktopAndCursorComposer(
webrtc::DesktopCapturer::CreateWindowCapturer(options),
options));
}
else {
capturer.reset(new webrtc::DesktopAndCursorComposer(
webrtc::DesktopCapturer::CreateScreenCapturer(options),
options));
}
if (!capturer->SelectSource(sourceId)) {
return;
}
capturer->Start(this);
sourceState = kLive;
int msPerFrame = 1000 / frameRate;
while (isCapturing) {
capturer->CaptureFrame();
webrtc::SleepMs(msPerFrame);
}
sourceState = kEnded;
}
}
| 26.587629
| 131
| 0.727995
|
preciate
|
9a0d0b8acd952408bbe78205d4948eb94fb02aa4
| 13,907
|
cxx
|
C++
|
pandatool/src/xfile/xFileDataObject.cxx
|
kestred/panda3d
|
16bfd3750f726a8831771b81649d18d087917fd5
|
[
"PHP-3.01",
"PHP-3.0"
] | 3
|
2018-03-09T12:07:29.000Z
|
2021-02-25T06:50:25.000Z
|
pandatool/src/xfile/xFileDataObject.cxx
|
Sinkay/panda3d
|
16bfd3750f726a8831771b81649d18d087917fd5
|
[
"PHP-3.01",
"PHP-3.0"
] | null | null | null |
pandatool/src/xfile/xFileDataObject.cxx
|
Sinkay/panda3d
|
16bfd3750f726a8831771b81649d18d087917fd5
|
[
"PHP-3.01",
"PHP-3.0"
] | null | null | null |
// Filename: xFileDataObject.cxx
// Created by: drose (03Oct04)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University. All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license. You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////
#include "xFileDataObject.h"
#include "xFileTemplate.h"
#include "xFile.h"
#include "xFileDataNodeTemplate.h"
#include "xFileDataObjectInteger.h"
#include "xFileDataObjectDouble.h"
#include "xFileDataObjectString.h"
#include "config_xfile.h"
#include "indent.h"
TypeHandle XFileDataObject::_type_handle;
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::Destructor
// Access: Public, Virtual
// Description:
////////////////////////////////////////////////////////////////////
XFileDataObject::
~XFileDataObject() {
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::is_complex_object
// Access: Public, Virtual
// Description: Returns true if this kind of data object is a complex
// object that can hold nested data elements, false
// otherwise.
////////////////////////////////////////////////////////////////////
bool XFileDataObject::
is_complex_object() const {
return false;
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::get_type_name
// Access: Public, Virtual
// Description: Returns a string that represents the type of object
// this data object represents.
////////////////////////////////////////////////////////////////////
string XFileDataObject::
get_type_name() const {
return get_type().get_name();
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::add_int
// Access: Public
// Description: Appends a new integer value to the data object, if it
// makes sense to do so. Normally, this is valid only
// for a DataObjectArray, or in certain special cases for
// a DataNodeTemplate.
////////////////////////////////////////////////////////////////////
XFileDataObject &XFileDataObject::
add_int(int int_value) {
XFileDataObject *object =
new XFileDataObjectInteger(get_data_def(), int_value);
add_element(object);
return *object;
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::add_double
// Access: Public
// Description: Appends a new floating-point value to the data
// object, if it makes sense to do so. Normally, this
// is valid only for a DataObjectArray, or in certain
// special cases for a DataNodeTemplate.
////////////////////////////////////////////////////////////////////
XFileDataObject &XFileDataObject::
add_double(double double_value) {
XFileDataObject *object =
new XFileDataObjectDouble(get_data_def(), double_value);
add_element(object);
return *object;
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::add_string
// Access: Public
// Description: Appends a new string value to the data object, if it
// makes sense to do so. Normally, this is valid only
// for a DataObjectArray, or in certain special cases for
// a DataNodeTemplate.
////////////////////////////////////////////////////////////////////
XFileDataObject &XFileDataObject::
add_string(const string &string_value) {
XFileDataObject *object =
new XFileDataObjectString(get_data_def(), string_value);
add_element(object);
return *object;
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::add_Vector
// Access: Public
// Description: Appends a new Vector instance.
////////////////////////////////////////////////////////////////////
XFileDataObject &XFileDataObject::
add_Vector(XFile *x_file, const LVecBase3d &vector) {
XFileTemplate *xtemplate = XFile::find_standard_template("Vector");
nassertr(xtemplate != (XFileTemplate *)NULL, *this);
XFileDataNodeTemplate *node =
new XFileDataNodeTemplate(x_file, "", xtemplate);
add_element(node);
node->zero_fill();
node->set(vector);
return *node;
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::add_MeshFace
// Access: Public
// Description: Appends a new MeshFace instance.
////////////////////////////////////////////////////////////////////
XFileDataObject &XFileDataObject::
add_MeshFace(XFile *x_file) {
XFileTemplate *xtemplate = XFile::find_standard_template("MeshFace");
nassertr(xtemplate != (XFileTemplate *)NULL, *this);
XFileDataNodeTemplate *node =
new XFileDataNodeTemplate(x_file, "", xtemplate);
add_element(node);
node->zero_fill();
return *node;
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::add_IndexedColor
// Access: Public
// Description: Appends a new IndexedColor instance.
////////////////////////////////////////////////////////////////////
XFileDataObject &XFileDataObject::
add_IndexedColor(XFile *x_file, int index, const LColor &color) {
XFileTemplate *xtemplate = XFile::find_standard_template("IndexedColor");
nassertr(xtemplate != (XFileTemplate *)NULL, *this);
XFileDataNodeTemplate *node =
new XFileDataNodeTemplate(x_file, "", xtemplate);
add_element(node);
node->zero_fill();
(*node)["index"] = index;
(*node)["indexColor"] = LCAST(double, color);
return *node;
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::add_Coords2d
// Access: Public
// Description: Appends a new Coords2d instance.
////////////////////////////////////////////////////////////////////
XFileDataObject &XFileDataObject::
add_Coords2d(XFile *x_file, const LVecBase2d &coords) {
XFileTemplate *xtemplate = XFile::find_standard_template("Coords2d");
nassertr(xtemplate != (XFileTemplate *)NULL, *this);
XFileDataNodeTemplate *node =
new XFileDataNodeTemplate(x_file, "", xtemplate);
add_element(node);
node->zero_fill();
node->set(coords);
return *node;
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::add_element
// Access: Public, Virtual
// Description: Adds the indicated element as a nested data element,
// if this data object type supports it. Returns true
// if added successfully, false if the data object type
// does not support nested data elements.
////////////////////////////////////////////////////////////////////
bool XFileDataObject::
add_element(XFileDataObject *element) {
return false;
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::output_data
// Access: Public, Virtual
// Description: Writes a suitable representation of this node to an
// .x file in text mode.
////////////////////////////////////////////////////////////////////
void XFileDataObject::
output_data(ostream &out) const {
out << "(" << get_type() << "::output_data() not implemented.)";
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::write_data
// Access: Public, Virtual
// Description: Writes a suitable representation of this node to an
// .x file in text mode.
////////////////////////////////////////////////////////////////////
void XFileDataObject::
write_data(ostream &out, int indent_level, const char *) const {
indent(out, indent_level)
<< "(" << get_type() << "::write_data() not implemented.)\n";
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::set_int_value
// Access: Protected, Virtual
// Description: Sets the object's value as an integer, if this is
// legal.
////////////////////////////////////////////////////////////////////
void XFileDataObject::
set_int_value(int int_value) {
xfile_cat.error()
<< get_type_name() << " does not support integer values.\n";
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::set_double_value
// Access: Protected, Virtual
// Description: Sets the object's value as a floating-point number,
// if this is legal.
////////////////////////////////////////////////////////////////////
void XFileDataObject::
set_double_value(double double_value) {
xfile_cat.error()
<< get_type_name() << " does not support floating-point values.\n";
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::set_string_value
// Access: Protected, Virtual
// Description: Sets the object's value as a string, if this is
// legal.
////////////////////////////////////////////////////////////////////
void XFileDataObject::
set_string_value(const string &string_value) {
xfile_cat.error()
<< get_type_name() << " does not support string values.\n";
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::store_double_array
// Access: Protected
// Description: Stores the indicated array of doubles in the nested
// elements within this object. There must be exactly
// the indicated number of nested values, and they must
// all accept a double.
////////////////////////////////////////////////////////////////////
void XFileDataObject::
store_double_array(int num_elements, const double *values) {
if (get_num_elements() != num_elements) {
xfile_cat.error()
<< get_type_name() << " does not accept "
<< num_elements << " values.\n";
return;
}
for (int i = 0; i < num_elements; i++) {
get_element(i)->set_double_value(values[i]);
}
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::get_int_value
// Access: Protected, Virtual
// Description: Returns the object's representation as an integer, if
// it has one.
////////////////////////////////////////////////////////////////////
int XFileDataObject::
get_int_value() const {
return 0;
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::get_double_value
// Access: Protected, Virtual
// Description: Returns the object's representation as a double, if
// it has one.
////////////////////////////////////////////////////////////////////
double XFileDataObject::
get_double_value() const {
return 0.0;
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::get_string_value
// Access: Protected, Virtual
// Description: Returns the object's representation as a string, if
// it has one.
////////////////////////////////////////////////////////////////////
string XFileDataObject::
get_string_value() const {
return string();
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::get_double_array
// Access: Protected
// Description: Fills the indicated array of doubles with the values
// from the nested elements within this object. There
// must be exactly the indicated number of nested
// values, and they must all return a double.
////////////////////////////////////////////////////////////////////
void XFileDataObject::
get_double_array(int num_elements, double *values) const {
if (get_num_elements() != num_elements) {
xfile_cat.error()
<< get_type_name() << " does not contain "
<< num_elements << " values.\n";
return;
}
for (int i = 0; i < num_elements; i++) {
values[i] = ((XFileDataObject *)this)->get_element(i)->get_double_value();
}
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::get_num_elements
// Access: Protected, Virtual
// Description: Returns the number of nested data elements within the
// object. This may be, e.g. the size of the array, if
// it is an array.
////////////////////////////////////////////////////////////////////
int XFileDataObject::
get_num_elements() const {
return 0;
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::get_element
// Access: Protected, Virtual
// Description: Returns the nth nested data element within the
// object.
////////////////////////////////////////////////////////////////////
XFileDataObject *XFileDataObject::
get_element(int n) {
xfile_cat.warning()
<< "Looking for [" << n << "] within data object of type "
<< get_type_name() << ", does not support nested objects.\n";
return NULL;
}
////////////////////////////////////////////////////////////////////
// Function: XFileDataObject::get_element
// Access: Protected, Virtual
// Description: Returns the nested data element within the
// object that has the indicated name.
////////////////////////////////////////////////////////////////////
XFileDataObject *XFileDataObject::
get_element(const string &name) {
xfile_cat.warning()
<< "Looking for [\"" << name << "\"] within data object of type "
<< get_type_name() << ", does not support nested objects.\n";
return NULL;
}
| 37.485175
| 78
| 0.511829
|
kestred
|
9a0df3b530d67be768a82f6b0b440593cccdff56
| 11,699
|
hpp
|
C++
|
src/vanillaswap.hpp
|
quantlibnode/quantlibnode
|
b50348131af77a2b6c295f44ef3245daf05c4afc
|
[
"MIT"
] | 27
|
2016-11-19T16:51:21.000Z
|
2021-09-08T16:44:15.000Z
|
src/vanillaswap.hpp
|
quantlibnode/quantlibnode
|
b50348131af77a2b6c295f44ef3245daf05c4afc
|
[
"MIT"
] | 1
|
2016-12-28T16:38:38.000Z
|
2017-02-17T05:32:13.000Z
|
src/vanillaswap.hpp
|
quantlibnode/quantlibnode
|
b50348131af77a2b6c295f44ef3245daf05c4afc
|
[
"MIT"
] | 10
|
2016-12-28T02:31:38.000Z
|
2021-06-15T09:02:07.000Z
|
/*
Copyright (C) 2016 -2017 Jerry Jin
*/
#ifndef vanillaswap_h
#define vanillaswap_h
#include <nan.h>
#include <string>
#include <queue>
#include <utility>
#include "../quantlibnode.hpp"
#include <oh/objecthandler.hpp>
using namespace node;
using namespace v8;
using namespace std;
class VanillaSwapWorker : public Nan::AsyncWorker {
public:
string mObjectID;
string mPayerReceiver;
double mNominal;
string mFixSchedule;
double mFixedRate;
string mFixDayCounter;
string mFloatingLegSchedule;
string mIborIndex;
double mSpread;
string mFloatingLegDayCounter;
string mPaymentConvention;
string mReturnValue;
string mError;
VanillaSwapWorker(
Nan::Callback *callback
,string ObjectID
,string PayerReceiver
,double Nominal
,string FixSchedule
,double FixedRate
,string FixDayCounter
,string FloatingLegSchedule
,string IborIndex
,double Spread
,string FloatingLegDayCounter
,string PaymentConvention
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
,mPayerReceiver(PayerReceiver)
,mNominal(Nominal)
,mFixSchedule(FixSchedule)
,mFixedRate(FixedRate)
,mFixDayCounter(FixDayCounter)
,mFloatingLegSchedule(FloatingLegSchedule)
,mIborIndex(IborIndex)
,mSpread(Spread)
,mFloatingLegDayCounter(FloatingLegDayCounter)
,mPaymentConvention(PaymentConvention)
{
};
//~VanillaSwapWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class MakeVanillaSwapWorker : public Nan::AsyncWorker {
public:
string mObjectID;
ObjectHandler::property_t mSettlDays;
string mSwapTenor;
string mIborIndex;
double mFixedRate;
string mForwardStart;
string mFixDayCounter;
double mSpread;
string mPricingEngineID;
string mReturnValue;
string mError;
MakeVanillaSwapWorker(
Nan::Callback *callback
,string ObjectID
,ObjectHandler::property_t SettlDays
,string SwapTenor
,string IborIndex
,double FixedRate
,string ForwardStart
,string FixDayCounter
,double Spread
,string PricingEngineID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
,mSettlDays(SettlDays)
,mSwapTenor(SwapTenor)
,mIborIndex(IborIndex)
,mFixedRate(FixedRate)
,mForwardStart(ForwardStart)
,mFixDayCounter(FixDayCounter)
,mSpread(Spread)
,mPricingEngineID(PricingEngineID)
{
};
//~MakeVanillaSwapWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class MakeIMMSwapWorker : public Nan::AsyncWorker {
public:
string mObjectID;
string mSwapTenor;
string mIborIndex;
double mFixedRate;
ObjectHandler::property_t mFirstImmDate;
string mFixDayCounter;
double mSpread;
string mPricingEngineID;
string mReturnValue;
string mError;
MakeIMMSwapWorker(
Nan::Callback *callback
,string ObjectID
,string SwapTenor
,string IborIndex
,double FixedRate
,ObjectHandler::property_t FirstImmDate
,string FixDayCounter
,double Spread
,string PricingEngineID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
,mSwapTenor(SwapTenor)
,mIborIndex(IborIndex)
,mFixedRate(FixedRate)
,mFirstImmDate(FirstImmDate)
,mFixDayCounter(FixDayCounter)
,mSpread(Spread)
,mPricingEngineID(PricingEngineID)
{
};
//~MakeIMMSwapWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapFromSwapIndexWorker : public Nan::AsyncWorker {
public:
string mObjectID;
string mSwapIndex;
ObjectHandler::property_t mFixingDate;
string mReturnValue;
string mError;
VanillaSwapFromSwapIndexWorker(
Nan::Callback *callback
,string ObjectID
,string SwapIndex
,ObjectHandler::property_t FixingDate
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
,mSwapIndex(SwapIndex)
,mFixingDate(FixingDate)
{
};
//~VanillaSwapFromSwapIndexWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapFromSwapRateHelperWorker : public Nan::AsyncWorker {
public:
string mObjectID;
string mSwapRateHelper;
string mReturnValue;
string mError;
VanillaSwapFromSwapRateHelperWorker(
Nan::Callback *callback
,string ObjectID
,string SwapRateHelper
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
,mSwapRateHelper(SwapRateHelper)
{
};
//~VanillaSwapFromSwapRateHelperWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapFixedLegBPSWorker : public Nan::AsyncWorker {
public:
string mObjectID;
double mReturnValue;
string mError;
VanillaSwapFixedLegBPSWorker(
Nan::Callback *callback
,string ObjectID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
{
};
//~VanillaSwapFixedLegBPSWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapFixedLegNPVWorker : public Nan::AsyncWorker {
public:
string mObjectID;
double mReturnValue;
string mError;
VanillaSwapFixedLegNPVWorker(
Nan::Callback *callback
,string ObjectID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
{
};
//~VanillaSwapFixedLegNPVWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapFairRateWorker : public Nan::AsyncWorker {
public:
string mObjectID;
double mReturnValue;
string mError;
VanillaSwapFairRateWorker(
Nan::Callback *callback
,string ObjectID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
{
};
//~VanillaSwapFairRateWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapFloatingLegBPSWorker : public Nan::AsyncWorker {
public:
string mObjectID;
double mReturnValue;
string mError;
VanillaSwapFloatingLegBPSWorker(
Nan::Callback *callback
,string ObjectID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
{
};
//~VanillaSwapFloatingLegBPSWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapFloatingLegNPVWorker : public Nan::AsyncWorker {
public:
string mObjectID;
double mReturnValue;
string mError;
VanillaSwapFloatingLegNPVWorker(
Nan::Callback *callback
,string ObjectID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
{
};
//~VanillaSwapFloatingLegNPVWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapFairSpreadWorker : public Nan::AsyncWorker {
public:
string mObjectID;
double mReturnValue;
string mError;
VanillaSwapFairSpreadWorker(
Nan::Callback *callback
,string ObjectID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
{
};
//~VanillaSwapFairSpreadWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapTypeWorker : public Nan::AsyncWorker {
public:
string mObjectID;
string mReturnValue;
string mError;
VanillaSwapTypeWorker(
Nan::Callback *callback
,string ObjectID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
{
};
//~VanillaSwapTypeWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapNominalWorker : public Nan::AsyncWorker {
public:
string mObjectID;
double mReturnValue;
string mError;
VanillaSwapNominalWorker(
Nan::Callback *callback
,string ObjectID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
{
};
//~VanillaSwapNominalWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapFixedRateWorker : public Nan::AsyncWorker {
public:
string mObjectID;
double mReturnValue;
string mError;
VanillaSwapFixedRateWorker(
Nan::Callback *callback
,string ObjectID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
{
};
//~VanillaSwapFixedRateWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapFixedDayCountWorker : public Nan::AsyncWorker {
public:
string mObjectID;
string mReturnValue;
string mError;
VanillaSwapFixedDayCountWorker(
Nan::Callback *callback
,string ObjectID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
{
};
//~VanillaSwapFixedDayCountWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapSpreadWorker : public Nan::AsyncWorker {
public:
string mObjectID;
double mReturnValue;
string mError;
VanillaSwapSpreadWorker(
Nan::Callback *callback
,string ObjectID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
{
};
//~VanillaSwapSpreadWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapFloatingDayCountWorker : public Nan::AsyncWorker {
public:
string mObjectID;
string mReturnValue;
string mError;
VanillaSwapFloatingDayCountWorker(
Nan::Callback *callback
,string ObjectID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
{
};
//~VanillaSwapFloatingDayCountWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapPaymentConventionWorker : public Nan::AsyncWorker {
public:
string mObjectID;
string mReturnValue;
string mError;
VanillaSwapPaymentConventionWorker(
Nan::Callback *callback
,string ObjectID
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
{
};
//~VanillaSwapPaymentConventionWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapFixedLegAnalysisWorker : public Nan::AsyncWorker {
public:
string mObjectID;
ObjectHandler::property_t mAfterDate;
std::vector< std::vector<string> > mReturnValue;
string mError;
VanillaSwapFixedLegAnalysisWorker(
Nan::Callback *callback
,string ObjectID
,ObjectHandler::property_t AfterDate
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
,mAfterDate(AfterDate)
{
};
//~VanillaSwapFixedLegAnalysisWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
class VanillaSwapFloatingLegAnalysisWorker : public Nan::AsyncWorker {
public:
string mObjectID;
ObjectHandler::property_t mAfterDate;
std::vector< std::vector<string> > mReturnValue;
string mError;
VanillaSwapFloatingLegAnalysisWorker(
Nan::Callback *callback
,string ObjectID
,ObjectHandler::property_t AfterDate
):
Nan::AsyncWorker(callback)
,mObjectID(ObjectID)
,mAfterDate(AfterDate)
{
};
//~VanillaSwapFloatingLegAnalysisWorker();
//void Destroy();
void Execute();
void HandleOKCallback();
};
#endif
| 17.409226
| 70
| 0.651081
|
quantlibnode
|
9a15237559ffecc8d6c93fc1ef2ed229aca7c43e
| 981
|
cpp
|
C++
|
src/apps/processors/envelope/EnvelopeController.cpp
|
pigatron-industries/xen_filter
|
10de7c617b59e02c29b448764d60f503f14dd564
|
[
"Unlicense"
] | null | null | null |
src/apps/processors/envelope/EnvelopeController.cpp
|
pigatron-industries/xen_filter
|
10de7c617b59e02c29b448764d60f503f14dd564
|
[
"Unlicense"
] | null | null | null |
src/apps/processors/envelope/EnvelopeController.cpp
|
pigatron-industries/xen_filter
|
10de7c617b59e02c29b448764d60f503f14dd564
|
[
"Unlicense"
] | null | null | null |
#include "EnvelopeController.h"
#define LEFT 0
#define RIGHT 1
void EnvelopeController::init(float sampleRate) {
envelope.init(sampleRate, 3, 1, false);
envelope.setPoint(0, deprecated::Point(0, 0));
envelope.setPoint(1, deprecated::Point(1, 1));
envelope.setPoint(2, deprecated::Point(2, 0));
displayPage.initTitle("Envelope", "ENV ");
}
void EnvelopeController::update() {
if(gateInput.update()) {
if(gateInput.isTriggeredOn()) {
envelope.trigger();
}
}
if(attackTimeInput.update()) {
envelope.setSegmentLength(0, attackTimeInput.getValue());
}
if(decayTimeInput.update()) {
envelope.setSegmentLength(1, decayTimeInput.getValue());
}
}
void EnvelopeController::process(float **in, float **out, size_t size) {
for (size_t i = 0; i < size; i++) {
float gain = envelope.process();
out[LEFT][i] = in[LEFT][i] * gain;
out[RIGHT][i] = in[RIGHT][i] * gain;
}
}
| 27.25
| 72
| 0.622834
|
pigatron-industries
|
9a17d8c1302934c72bf6ee801a894a9858b13368
| 2,505
|
cpp
|
C++
|
src/logic/torrentdetailscontentview.cpp
|
herokukuki/ydyd
|
942a98158e139f0bb00a837b762492bdaaffb94c
|
[
"MIT"
] | null | null | null |
src/logic/torrentdetailscontentview.cpp
|
herokukuki/ydyd
|
942a98158e139f0bb00a837b762492bdaaffb94c
|
[
"MIT"
] | null | null | null |
src/logic/torrentdetailscontentview.cpp
|
herokukuki/ydyd
|
942a98158e139f0bb00a837b762492bdaaffb94c
|
[
"MIT"
] | null | null | null |
#include "torrentdetailscontentview.h"
#include <QMenu>
#include <QFileInfo>
#include <QDir>
#include "utilities/utils.h"
#include "utilities/filesystem_utils.h"
#include "torrentcontentmodel.h"
#include "global_functions.h"
TorrentDetailsContentView::TorrentDetailsContentView(QWidget* parent /*= 0*/): QTreeView(parent)
{
setContextMenuPolicy(Qt::CustomContextMenu);
VERIFY(connect(this, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(on_showTreeTorentContextMenu(const QPoint&))));
}
void TorrentDetailsContentView::setModel(TorrentContentFilterModel* a_model)
{
QTreeView::setModel(a_model);
VERIFY(connect(this, SIGNAL(doubleClicked(const QModelIndex&)), this, SLOT(on_ItemOpenFolder())));
}
TorrentContentFilterModel* TorrentDetailsContentView::model()
{
return static_cast<TorrentContentFilterModel*>(QTreeView::model());
}
void TorrentDetailsContentView::on_showTreeTorentContextMenu(const QPoint& pos)
{
QModelIndex index = indexAt(pos);
if (index.isValid())
{
QMenu menu;
menu.setObjectName(QStringLiteral("TorrentDetailsContextMenu"));
menu.addAction(QIcon(), tr("Open in folder"), this, SLOT(on_ItemOpenFolder()));
menu.addAction(QIcon(), tr("Open File"), this, SLOT(on_ItemOpenFile()));
menu.exec(QCursor::pos());
}
}
void TorrentDetailsContentView::on_ItemOpenFolder()
{
QModelIndex curr_index = selectionModel()->currentIndex();
if (!curr_index.isValid())
{
return;
}
TorrentContentModelItem* torrentItem = model()->getTorrentContentModelItem(curr_index);
QString pathFile = torrentItem->getPath();
if (pathFile.isEmpty())
{
pathFile = torrentItem->getName();
}
QString savePath = model()->model()->getSavePath();
QString filename = savePath + pathFile;
QFileInfo downloadFile(filename);
utilities::SelectFile(downloadFile.absoluteFilePath(), downloadFile.dir().path());
}
void TorrentDetailsContentView::on_ItemOpenFile()
{
QModelIndex curr_index = selectionModel()->currentIndex();
if (!curr_index.isValid())
{
return;
}
TorrentContentModelItem* torrentItem = model()->getTorrentContentModelItem(curr_index);
QString pathFile = torrentItem->getPath();
QString savePath = model()->model()->getSavePath();
QString filename = savePath + pathFile;
if (torrentItem->isFolder() || !QFile::exists(filename))
{
return;
}
global_functions::openFile(filename);
}
| 30.54878
| 134
| 0.712974
|
herokukuki
|
9a184ea67dbdf0c85121b89294df837fce391a3a
| 4,618
|
hh
|
C++
|
include/LACE/LpcResiduals.hh
|
petrmanek/LACE
|
5e189bb871a47972490fe2888a60df876cb6b120
|
[
"BSL-1.0"
] | 1
|
2019-03-14T13:13:34.000Z
|
2019-03-14T13:13:34.000Z
|
include/LACE/LpcResiduals.hh
|
petrmanek/LACE
|
5e189bb871a47972490fe2888a60df876cb6b120
|
[
"BSL-1.0"
] | null | null | null |
include/LACE/LpcResiduals.hh
|
petrmanek/LACE
|
5e189bb871a47972490fe2888a60df876cb6b120
|
[
"BSL-1.0"
] | 2
|
2018-04-19T21:29:46.000Z
|
2019-03-14T13:37:26.000Z
|
// Copyright University of Warwick 2014
// 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)
// Authors:
// John Back
/*! \file LpcResiduals.hh
\brief File containing the declaration of the LpcResiduals class
*/
/*! \class LpcResiduals
\brief Class that stores the lpc-to-hit residuals
*/
#ifndef LPC_RESIDUALS_HH
#define LPC_RESIDUALS_HH
#include <Eigen/Dense>
#include <vector>
class LpcResiduals {
public:
//! Constructor using residual arrays stored as Eigen vector objects
/*!
\param [in] lpcResiduals the average residual over all hits for each lpc point
\param [in] hitResiduals the residual of the nearest lpc point for each hit
\param [in] lpcWeightRes the average weighted residual over all hits for each lpc point
\param [in] hitWeightRes the weighted residual of the nearest lpc point for each hit
\param [in] hitNearestLpc the nearest lpc point index number for each hit
*/
LpcResiduals(const Eigen::VectorXd& lpcResiduals,
const Eigen::VectorXd& hitResiduals,
const Eigen::VectorXd& lpcWeightRes,
const Eigen::VectorXd& hitWeightRes,
const Eigen::VectorXi& hitNearestLpc);
//! Default, empty constructor
LpcResiduals();
//! Copy constructor
/*!
\param [in] other The LpcResiduals object to copy
*/
LpcResiduals(const LpcResiduals& other);
//! Assignment operator
/*!
\param [in] other The LpcResiduals used for the assignment
*/
LpcResiduals& operator=(const LpcResiduals& other);
//! Destructor
virtual ~LpcResiduals();
// Accessors
//! Get the average residual over all hits for each lpc point
/*!
\returns an Eigen VectorXd of the average residual with the hits per lpc point
*/
Eigen::VectorXd getLpcResiduals() const {return lpcResiduals_;}
//! Get the residual of the nearest lpc point for each hit
/*!
\returns an Eigen VectorXd of the residual of the nearest lpc point for each hit
*/
Eigen::VectorXd getHitResiduals() const {return hitResiduals_;}
//! Get the average weighted residual over all hits for each lpc point
/*!
\returns an Eigen VectorXd of the average weighted residual with the hits per lpc point
*/
Eigen::VectorXd getWeightedLpcResiduals() const {return lpcWeightRes_;}
//! Get the weighted residual of the nearest lpc point for each hit
/*!
\returns an Eigen VectorXd of the weighted residual of the nearest lpc point for each hit
*/
Eigen::VectorXd getWeightedHitResiduals() const {return hitWeightRes_;}
//! Get the nearest lpc point index number for each hit
/*!
\returns an Eigen VectorXi of the index number of the nearest lpc point for each hit
*/
Eigen::VectorXi getHitNearestLpc() const {return hitNearestLpc_;}
// STL vector versions of the above access functions
//! Get the average residual over all hits for each lpc point
/*!
\returns a STL vector of the average residual with the hits per lpc point
*/
std::vector<double> getLpcResVector() const;
//! Get the residual of the nearest lpc point for each hit
/*!
\returns a STL vector of the residual of the nearest lpc point for each hit
*/
std::vector<double> getHitResVector() const;
//! Get the average weighted residual over all hits for each lpc point
/*!
\returns a STL vector of the average weighted residual with the hits per lpc point
*/
std::vector<double> getWeightedLpcResVector() const;
//! Get the weighted residual of the nearest lpc point for each hit
/*!
\returns a STL vector of the weighted residual of the nearest lpc point for each hit
*/
std::vector<double> getWeightedHitResVector() const;
//! Get the nearest lpc point index number for each hit
/*!
\returns a STL vector of the index number of the nearest lpc point for each hit
*/
std::vector<int> getHitNearestLpcVector() const;
protected:
private:
//! The average residual over all hits for each lpc point
Eigen::VectorXd lpcResiduals_;
//! The residual of the nearest lpc point for each hit
Eigen::VectorXd hitResiduals_;
//! The average weighted residual over all hits for each lpc point
Eigen::VectorXd lpcWeightRes_;
//! The weighted residual of the nearest lpc point for each hit
Eigen::VectorXd hitWeightRes_;
//! The nearest lpc point index number for each hit
Eigen::VectorXi hitNearestLpc_;
};
#endif
| 31.630137
| 95
| 0.699654
|
petrmanek
|
9a18a9a0f986855045c83f581bcf07ec3460d0a4
| 7,376
|
cpp
|
C++
|
server.cpp
|
AnuragDPawar/Centralized-Multi-User-Concurrent-Bank-Account-Manager
|
c7a8f0b7a61636855c1207f50f82ab554fe89a5f
|
[
"MIT"
] | null | null | null |
server.cpp
|
AnuragDPawar/Centralized-Multi-User-Concurrent-Bank-Account-Manager
|
c7a8f0b7a61636855c1207f50f82ab554fe89a5f
|
[
"MIT"
] | null | null | null |
server.cpp
|
AnuragDPawar/Centralized-Multi-User-Concurrent-Bank-Account-Manager
|
c7a8f0b7a61636855c1207f50f82ab554fe89a5f
|
[
"MIT"
] | null | null | null |
#include <arpa/inet.h>
#include <libexplain/read.h>
#include <netdb.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <fstream>
#include <iomanip> //to format the float value
#include <iostream>
#include <sstream> //for appending operations
#include <string>
#define MAX 200
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
using namespace std;
int s_accout_number[MAX];
float s_amount[MAX];
string name[MAX];
char *c_ip;
int filectr;
void *calculate_interest(void *arg) {
while (true) {
sleep(60);
cout << "\nAdding 10% Interest in every account after every 60 seconds\n";
for (int i = 0; i < filectr; i++) {
pthread_mutex_lock(&lock);
s_amount[i] = s_amount[i] * 1.1;
pthread_mutex_unlock(&lock);
}
}
}
void *operations(void *arg) {
stringstream amt_stream;
stringstream amt_stream1;
int *client_socket = (int *)arg;
int accout_number;
int timestamp;
int amount;
char transaction_type[1];
char buff[4096];
string msg_to_client;
cout << "Client connected"
<< " " << *client_socket << " "
<< "Thread ID"
<< " " << pthread_self() << endl;
int n;
bzero(buff, 4096);
int locked = 0;
while (n = read(*client_socket, buff, 4096))
{
if (n < 0)
{
cout << "Error" << endl;
break;
}
c_ip = strtok(buff, " ");
if (c_ip)
{
timestamp = atoi(c_ip);
}
c_ip = strtok(NULL, " ");
if (c_ip)
{
accout_number = atoi(c_ip);
}
c_ip = strtok(NULL, " ");
if (c_ip)
{
strcpy(transaction_type, c_ip);
}
c_ip = strtok(NULL, " ");
if (c_ip)
{
amount = stof(c_ip);
}
int current_account = -1;
for (int i = 0; i < filectr; i++)
{
if (s_accout_number[i] == accout_number)
{
current_account = i;
break;
}
}
pthread_mutex_lock(&lock);
if (current_account != -1)
{
if (strcmp(transaction_type, "d") == 0)
{
s_amount[current_account] = s_amount[current_account] + amount;
string amt;
string msg;
amt.clear();
msg.clear();
std::stringstream stream;
stream << std::fixed << std::setprecision(2) << s_amount[current_account];
std::string s = stream.str();
amt = s;
msg = "Updated balence after deposite: \n";
msg_to_client = msg+amt;
write(*client_socket, msg_to_client.c_str(), msg_to_client.size() + 1);
}
else if (strcmp(transaction_type, "w") == 0)
{
if ((s_amount[current_account] - amount) < 0)
{
msg_to_client = "Insufficient balence\n";
write(*client_socket, msg_to_client.c_str(), msg_to_client.size() + 1);
}
else
{
s_amount[current_account] = s_amount[current_account] - amount;
string amt;
string msg;
amt.clear();
msg.clear();
std::stringstream stream;
stream << std::fixed << std::setprecision(2) << s_amount[current_account];
std::string s = stream.str();
amt = s;
msg = "Updated balence after withdrawal: \n";
msg_to_client = msg+amt;
write(*client_socket, msg_to_client.c_str(), msg_to_client.size() + 1);
}
}
else
{
msg_to_client = "Invalid transaction type\n";
write(*client_socket, msg_to_client.c_str(), msg_to_client.size() + 1);
}
}
else
{
msg_to_client = "Account number doesn't exist\n";
write(*client_socket, msg_to_client.c_str(), msg_to_client.size() + 1);
}
pthread_mutex_unlock(&lock);
}
}
int main() { //For socket part I have referred below video
//https://www.youtube.com/watch?v=cNdlrbZSkyQ
pthread_t newthread[200];
//Reading the file
fstream accounts;
accounts.open("./accounts");
if (accounts.fail()) {
cout << "Unable to read the file\n"
<< endl;
exit(1);
}
string line;
filectr = 0;
while (getline(accounts, line)) {
filectr++;
}
accounts.close();
accounts.open("./accounts");
for (size_t i = 0; i < filectr; i++) {
accounts >> s_accout_number[i];
accounts >> name[i];
accounts >> s_amount[i];
}
accounts.close();
//Create a server socket
int listening = 0;
listening = socket(AF_INET, SOCK_STREAM, 0);
if (listening == -1) {
cerr << "socket not created\n";
}
else {
cout << "Socket created with FD: " << listening << "\n";
}
int reuse_address = 1;
//Below code is referred from: https://pubs.opengroup.org/onlinepubs/000095399/functions/setsockopt.html
//To reuse the address
/*if(setsockopt(listening, SOL_SOCKET, SO_REUSEADDR, &reuse_address, sizeof(reuse_address)) != 0){
cout<<"Failed to reuse the address"<<endl;
}*/
//To reuse the port
if (setsockopt(listening, SOL_SOCKET, SO_REUSEPORT, &reuse_address, sizeof(reuse_address)) != 0) {
cout << "Failed to reuse the port" << endl;
}
//Bind socket on ip & port
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(54004);
inet_pton(AF_INET, "127.0.0.1", &hint.sin_addr);
if (bind(listening, (sockaddr *)&hint, sizeof(hint)) == -1) {
cerr << "Binding failed\n";
}
//Make the socket listen
if (listen(listening, 4) == -1) {
cerr << "Listening failed\n";
}
//accpet the connection
sockaddr_in client;
socklen_t clientsize = sizeof(client);
char host[NI_MAXHOST];
char svc[NI_MAXSERV];
int clientsocket[200];
for (int j =0; j < 200; j++) {
clientsocket[j] = 0;
}
pthread_t interest;
int i = 0;
pthread_create(&interest, NULL, calculate_interest, NULL);
while (true) {
while (clientsocket[i] = accept(listening, (struct sockaddr *)&client, (socklen_t *)&clientsize)) {
if (clientsocket[i] == -1) {
cerr << "Unable to connect with client\n";
continue;
} else {
pthread_create(&newthread[i], NULL, operations, &clientsocket[i]);
i++;
}
}
cout << "closing " << clientsocket << endl;
close(clientsocket[i]);
close(listening);
}
return 0;
}
| 30.229508
| 119
| 0.50583
|
AnuragDPawar
|
9a1957eed44c4ed8c755bd0da4386a401e71db85
| 4,444
|
cc
|
C++
|
stapl_release/tools/mtl-2.0/test/src/matrix_row_col_test.cc
|
parasol-ppl/PPL_utils
|
92728bb89692fda1705a0dee436592d97922a6cb
|
[
"BSD-3-Clause"
] | null | null | null |
stapl_release/tools/mtl-2.0/test/src/matrix_row_col_test.cc
|
parasol-ppl/PPL_utils
|
92728bb89692fda1705a0dee436592d97922a6cb
|
[
"BSD-3-Clause"
] | null | null | null |
stapl_release/tools/mtl-2.0/test/src/matrix_row_col_test.cc
|
parasol-ppl/PPL_utils
|
92728bb89692fda1705a0dee436592d97922a6cb
|
[
"BSD-3-Clause"
] | null | null | null |
// -*- c++ -*-
//
// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a
// component of the Texas A&M University System.
//
// All rights reserved.
//
// The information and source code contained herein is the exclusive
// property of TEES and may not be disclosed, examined or reproduced
// in whole or in part without explicit written authorization from TEES.
//
// Copyright 1997, 1998, 1999 University of Notre Dame.
// Authors: Andrew Lumsdaine, Jeremy G. Siek, Lie-Quan Lee
//
// This file is part of the Matrix Template Library
//
// You should have received a copy of the License Agreement for the
// Matrix Template Library along with the software; see the
// file LICENSE. If not, contact Office of Research, University of Notre
// Dame, Notre Dame, IN 46556.
//
// Permission to modify the code and to distribute modified code is
// granted, provided the text of this NOTICE is retained, a notice that
// the code was modified is included with the above COPYRIGHT NOTICE and
// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE
// file is distributed with the modified code.
//
// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.
// By way of example, but not limitation, Licensor MAKES NO
// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY
// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS
// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS
// OR OTHER RIGHTS.
//
//===========================================================================
#include "mtl/utils.h"
#include "mtl/matrix.h"
#include "matrix_test.h"
#include "iter_ij_test.h"
// matrix_attr.h is generated by make_and_test.pl and defines
// NUMTYPE, SHAPE, STORAGE, ORIEN, and TESTNAME
// you can create your own for testing purposes
#include "matrix_attr.h"
template <class Matrix, class Shape>
bool rows_test(const Matrix& A, std::string test_name, Shape, row_tag)
{
return iterator_operator_ij_test(A, test_name);
}
template <class Matrix>
bool rows_test(const Matrix& A, std::string test_name,
rectangle_tag, column_tag)
{
return strided_iterator_operator_ij_test(A, test_name);
}
template <class Matrix, class Shape>
bool columns_test(const Matrix& A, std::string test_name, Shape, row_tag)
{
return strided_iterator_operator_ij_test(A, test_name);
}
template <class Matrix>
bool columns_test(const Matrix& A, std::string test_name,
rectangle_tag, column_tag)
{
return iterator_operator_ij_test(A, test_name);
}
template <class Matrix>
bool rows_columns_test(Matrix& A, std::string test_name, strideable)
{
using mtl::rows;
using mtl::columns;
typedef typename mtl::matrix_traits<Matrix>::shape Shape;
typedef typename mtl::matrix_traits<Matrix>::orientation Orien;
bool ret1 = mtl::matrix_equal(rows(A), columns(A));
bool ret2 = rows_test(rows(A), test_name, Shape(), Orien());
bool ret3 = columns_test(columns(A), test_name, Shape(), Orien());
if (ret1 && ret2 && ret3)
std::cout << test_name.c_str() << " passed rows & columns test" << std::endl;
return ret1 && ret2 && ret3;
}
template <class Matrix>
bool rows_columns_test(Matrix&, std::string test_name, not_strideable)
{
std::cout << test_name.c_str() << " skipping rows & columns test" << std::endl;
return true;
}
template <class Matrix>
bool rows_columns_test(Matrix& A, std::string test_name)
{
typedef typename mtl::matrix_traits<Matrix>::strideability Stridable;
return rows_columns_test(A, test_name, Stridable());
}
template <class Matrix>
void
do_test(Matrix& A, std::string test_name)
{
using namespace mtl;
typedef typename mtl::matrix_traits<Matrix>::value_type T;
typedef typename mtl::matrix_traits<Matrix>::size_type Int;
matrix_fill(A);
rows_columns_test(A, test_name);
}
int
main(int argc, char* argv[])
{
if (argc < 5) {
std::cerr << "matrix_test <M> <N> <SUB> <SUPER>" << std::endl;
return -1;
}
using namespace mtl;
using std::string;
const int M = atoi(argv[1]);
const int N = atoi(argv[2]);
const int SUB = atoi(argv[3]);
const int SUP = atoi(argv[4]);
std::cout << "M: " << M << " N: " << N
<< " SUB: " << SUB << " SUPER: " << SUP << std::endl;
typedef matrix<NUMTYPE, SHAPE, STORAGE, ORIEN>::type Matrix;
string test_name = TESTNAME;
Matrix* a = 0;
create_and_run(M, N, SUB, SUP, test_name, a, Matrix::shape());
return 0;
}
| 30.027027
| 81
| 0.70387
|
parasol-ppl
|
9a1a2b02e904868e53e4ad156e1936048ba7c46c
| 1,050
|
cpp
|
C++
|
libs/camera/src/camera/coordinate_system/identity.cpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | 2
|
2016-01-27T13:18:14.000Z
|
2018-05-11T01:11:32.000Z
|
libs/camera/src/camera/coordinate_system/identity.cpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | null | null | null |
libs/camera/src/camera/coordinate_system/identity.cpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | 3
|
2018-05-11T01:11:34.000Z
|
2021-04-24T19:47:45.000Z
|
// Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <sge/camera/coordinate_system/forward.hpp>
#include <sge/camera/coordinate_system/identity.hpp>
#include <sge/camera/coordinate_system/object.hpp>
#include <sge/camera/coordinate_system/position.hpp>
#include <sge/camera/coordinate_system/right.hpp>
#include <sge/camera/coordinate_system/up.hpp>
#include <sge/renderer/vector3.hpp>
sge::camera::coordinate_system::object sge::camera::coordinate_system::identity()
{
return sge::camera::coordinate_system::object(
sge::camera::coordinate_system::right(sge::renderer::vector3(1.0F, 0.0F, 0.0F)),
sge::camera::coordinate_system::up(sge::renderer::vector3(0.0F, 1.0F, 0.0F)),
sge::camera::coordinate_system::forward(sge::renderer::vector3(0.0F, 0.0F, 1.0F)),
sge::camera::coordinate_system::position(sge::renderer::vector3(0.0F, 0.0F, 0.0F)));
}
| 47.727273
| 90
| 0.730476
|
cpreh
|
9a1a6dd25cc40f9ff5700fd28e8824579e224b29
| 10,728
|
cpp
|
C++
|
avogadro/io/cjsonformat.cpp
|
AlbertDeFusco/avogadrolibs
|
572aad6d16295c91da684d180b6b2705070549c1
|
[
"BSD-3-Clause"
] | null | null | null |
avogadro/io/cjsonformat.cpp
|
AlbertDeFusco/avogadrolibs
|
572aad6d16295c91da684d180b6b2705070549c1
|
[
"BSD-3-Clause"
] | null | null | null |
avogadro/io/cjsonformat.cpp
|
AlbertDeFusco/avogadrolibs
|
572aad6d16295c91da684d180b6b2705070549c1
|
[
"BSD-3-Clause"
] | null | null | null |
/******************************************************************************
This source file is part of the Avogadro project.
Copyright 2012 Kitware, Inc.
This source code is released under the New BSD License, (the "License").
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 "cjsonformat.h"
#include <avogadro/core/crystaltools.h>
#include <avogadro/core/elements.h>
#include <avogadro/core/molecule.h>
#include <avogadro/core/unitcell.h>
#include <jsoncpp.cpp>
using Avogadro::Core::Molecule;
namespace Avogadro {
namespace Io {
using std::string;
using Core::Elements;
using Core::Atom;
using Core::Bond;
using Core::Variant;
CjsonFormat::CjsonFormat()
{
}
CjsonFormat::~CjsonFormat()
{
}
bool CjsonFormat::read(std::istream &file, Core::Molecule &molecule)
{
Json::Value root;
Json::Reader reader;
bool ok = reader.parse(file, root);
if (!ok) {
appendError("Error parsing JSON: " + reader.getFormatedErrorMessages());
return false;
}
if (!root.isObject()) {
appendError("Error: Input is not a JSON object.");
return false;
}
Json::Value value = root["chemical json"];
if (value.empty()) {
appendError("Error: no \"chemical json\" key found.");
return false;
}
// It looks like a valid Chemical JSON file - attempt to read data.
value = root["name"];
if (!value.empty() && value.isString())
molecule.setData("name", value.asString());
value = root["inchi"];
if (!value.empty() && value.isString())
molecule.setData("inchi", value.asString());
value = root["unit cell"];
if (value.type() == Json::objectValue) {
if (!value["a"].isNumeric() ||
!value["b"].isNumeric() ||
!value["c"].isNumeric() ||
!value["alpha"].isNumeric() ||
!value["beta"].isNumeric() ||
!value["gamma"].isNumeric()) {
appendError("Invalid unit cell specification: a, b, c, alpha, beta, gamma"
" must be present and numeric.");
return false;
}
Real a = static_cast<Real>(value["a"].asDouble());
Real b = static_cast<Real>(value["b"].asDouble());
Real c = static_cast<Real>(value["c"].asDouble());
Real alpha = static_cast<Real>(value["alpha"].asDouble()) * DEG_TO_RAD;
Real beta = static_cast<Real>(value["beta" ].asDouble()) * DEG_TO_RAD;
Real gamma = static_cast<Real>(value["gamma"].asDouble()) * DEG_TO_RAD;
Core::UnitCell *unitCell = new Core::UnitCell(a, b, c, alpha, beta, gamma);
molecule.setUnitCell(unitCell);
}
// Read in the atomic data.
Json::Value atoms = root["atoms"];
if (atoms.empty()) {
appendError("Error: no \"atom\" key found");
return false;
}
else if (atoms.type() != Json::objectValue) {
appendError("Error: \"atom\" is not of type object");
return false;
}
value = atoms["elements"];
if (value.empty()) {
appendError("Error: no \"atoms.elements\" key found");
return false;
}
else if (value.type() != Json::objectValue) {
appendError("Error: \"atoms.elements\" is not of type object");
return false;
}
value = value["number"];
if (value.empty()) {
appendError("Error: no \"atoms.elements.number\" key found");
return false;
}
Index atomCount(0);
if (value.isArray()) {
atomCount = static_cast<Index>(value.size());
for (Index i = 0; i < atomCount; ++i)
molecule.addAtom(static_cast<unsigned char>(value.get(i, 0).asInt()));
}
else {
appendError("Error: \"atoms.elements.number\" is not of type array");
return false;
}
Json::Value coords = atoms["coords"];
if (!coords.empty()) {
value = coords["3d"];
if (value.isArray()) {
if (value.size() && atomCount != static_cast<Index>(value.size() / 3)) {
appendError("Error: number of elements != number of 3D coordinates.");
return false;
}
for (Index i = 0; i < atomCount; ++i) {
Atom a = molecule.atom(i);
a.setPosition3d(Vector3(value.get(3 * i + 0, 0).asDouble(),
value.get(3 * i + 1, 0).asDouble(),
value.get(3 * i + 2, 0).asDouble()));
}
}
value = coords["2d"];
if (value.isArray()) {
if (value.size() && atomCount != static_cast<Index>(value.size() / 2)) {
appendError("Error: number of elements != number of 2D coordinates.");
return false;
}
for (Index i = 0; i < atomCount; ++i) {
Atom a = molecule.atom(i);
a.setPosition2d(Vector2(value.get(2 * i + 0, 0).asDouble(),
value.get(2 * i + 1, 0).asDouble()));
}
}
value = coords["3d fractional"];
if (value.type() == Json::arrayValue) {
if (!molecule.unitCell()) {
appendError("Cannot interpret fractional coordinates without "
"unit cell.");
return false;
}
if (value.size() && atomCount != static_cast<size_t>(value.size() / 3)) {
appendError("Error: number of elements != number of fractional "
"coordinates.");
return false;
}
Core::Array<Vector3> fcoords;
fcoords.reserve(atomCount);
for (Index i = 0; i < atomCount; ++i) {
fcoords.push_back(
Vector3(static_cast<Real>(value.get(i * 3 + 0, 0).asDouble()),
static_cast<Real>(value.get(i * 3 + 1, 0).asDouble()),
static_cast<Real>(value.get(i * 3 + 2, 0).asDouble())));
}
Core::CrystalTools::setFractionalCoordinates(molecule, fcoords);
}
}
// Now for the bonding data.
Json::Value bonds = root["bonds"];
if (!bonds.empty()) {
value = bonds["connections"];
if (value.empty()) {
appendError("Error: no \"bonds.connections\" key found");
return false;
}
value = value["index"];
Index bondCount(0);
if (value.isArray()) {
bondCount = static_cast<Index>(value.size() / 2);
for (Index i = 0; i < bondCount * 2; i += 2) {
molecule.addBond(
molecule.atom(static_cast<Index>(value.get(i + 0, 0).asInt())),
molecule.atom(static_cast<Index>(value.get(i + 1, 0).asInt())));
}
}
else {
appendError("Warning, no bonding information found.");
}
value = bonds["order"];
if (value.isArray()) {
if (bondCount != static_cast<Index>(value.size())) {
appendError("Error: number of bonds != number of bond orders.");
return false;
}
for (Index i = 0; i < bondCount; ++i)
molecule.bond(i).setOrder(
static_cast<unsigned char>(value.get(i, 1).asInt()));
}
}
return true;
}
bool CjsonFormat::write(std::ostream &file, const Core::Molecule &molecule)
{
Json::StyledStreamWriter writer(" ");
Json::Value root;
root["chemical json"] = 0;
if (molecule.data("name").type() == Variant::String)
root["name"] = molecule.data("name").toString().c_str();
if (molecule.data("inchi").type() == Variant::String)
root["inchi"] = molecule.data("inchi").toString().c_str();
if (molecule.unitCell()) {
Json::Value unitCell = Json::Value(Json::objectValue);
unitCell["a"] = molecule.unitCell()->a();
unitCell["b"] = molecule.unitCell()->b();
unitCell["c"] = molecule.unitCell()->c();
unitCell["alpha"] = molecule.unitCell()->alpha() * RAD_TO_DEG;
unitCell["beta"] = molecule.unitCell()->beta() * RAD_TO_DEG;
unitCell["gamma"] = molecule.unitCell()->gamma() * RAD_TO_DEG;
root["unit cell"] = unitCell;
}
// Create and populate the atom arrays.
if (molecule.atomCount()) {
Json::Value elements(Json::arrayValue);
for (Index i = 0; i < molecule.atomCount(); ++i)
elements.append(molecule.atom(i).atomicNumber());
root["atoms"]["elements"]["number"] = elements;
// 3d positions:
if (molecule.atomPositions3d().size() == molecule.atomCount()) {
if (molecule.unitCell()) {
Json::Value coordsFractional(Json::arrayValue);
Core::Array<Vector3> fcoords;
Core::CrystalTools::fractionalCoordinates(*molecule.unitCell(),
molecule.atomPositions3d(),
fcoords);
for (std::vector<Vector3>::const_iterator it = fcoords.begin(),
itEnd = fcoords.end(); it != itEnd; ++it) {
coordsFractional.append(it->x());
coordsFractional.append(it->y());
coordsFractional.append(it->z());
}
root["atoms"]["coords"]["3d fractional"] = coordsFractional;
}
else {
Json::Value coords3d(Json::arrayValue);
for (std::vector<Vector3>::const_iterator
it = molecule.atomPositions3d().begin(),
itEnd = molecule.atomPositions3d().end(); it != itEnd; ++it) {
coords3d.append(it->x());
coords3d.append(it->y());
coords3d.append(it->z());
}
root["atoms"]["coords"]["3d"] = coords3d;
}
}
// 2d positions:
if (molecule.atomPositions2d().size() == molecule.atomCount()) {
Json::Value coords2d(Json::arrayValue);
for (std::vector<Vector2>::const_iterator
it = molecule.atomPositions2d().begin(),
itEnd = molecule.atomPositions2d().end(); it != itEnd; ++it) {
coords2d.append(it->x());
coords2d.append(it->y());
}
root["atoms"]["coords"]["2d"] = coords2d;
}
}
// Create and populate the bond arrays.
if (molecule.bondCount()) {
Json::Value connections(Json::arrayValue);
Json::Value order(Json::arrayValue);
for (Index i = 0; i < molecule.bondCount(); ++i) {
Bond bond = molecule.bond(i);
connections.append(static_cast<Json::Value::UInt>(bond.atom1().index()));
connections.append(static_cast<Json::Value::UInt>(bond.atom2().index()));
order.append(bond.order());
}
root["bonds"]["connections"]["index"] = connections;
root["bonds"]["order"] = order;
}
writer.write(file, root);
return true;
}
std::vector<std::string> CjsonFormat::fileExtensions() const
{
std::vector<std::string> ext;
ext.push_back("cjson");
return ext;
}
std::vector<std::string> CjsonFormat::mimeTypes() const
{
std::vector<std::string> mime;
mime.push_back("chemical/x-cjson");
return mime;
}
} // end Io namespace
} // end Avogadro namespace
| 32.216216
| 80
| 0.584452
|
AlbertDeFusco
|
9a1a9315aa9fb37f48c00f2e5dea109306c5e6f6
| 3,691
|
cc
|
C++
|
api/video/test/i444_buffer_unittest.cc
|
wyshen2020/webrtc
|
b93e2240f1653b82e24553e092bbab84337774af
|
[
"BSD-3-Clause"
] | 2
|
2022-03-10T01:47:56.000Z
|
2022-03-31T12:51:46.000Z
|
api/video/test/i444_buffer_unittest.cc
|
wyshen2020/webrtc
|
b93e2240f1653b82e24553e092bbab84337774af
|
[
"BSD-3-Clause"
] | null | null | null |
api/video/test/i444_buffer_unittest.cc
|
wyshen2020/webrtc
|
b93e2240f1653b82e24553e092bbab84337774af
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright (c) 2021 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "api/video/i444_buffer.h"
#include "api/video/i420_buffer.h"
#include "test/frame_utils.h"
#include "test/gmock.h"
#include "test/gtest.h"
namespace webrtc {
namespace {
int GetY(rtc::scoped_refptr<I444BufferInterface> buf, int col, int row) {
return buf->DataY()[row * buf->StrideY() + col];
}
int GetU(rtc::scoped_refptr<I444BufferInterface> buf, int col, int row) {
return buf->DataU()[row * buf->StrideU() + col];
}
int GetV(rtc::scoped_refptr<I444BufferInterface> buf, int col, int row) {
return buf->DataV()[row * buf->StrideV() + col];
}
void FillI444Buffer(rtc::scoped_refptr<I444Buffer> buf) {
const uint8_t Y = 1;
const uint8_t U = 2;
const uint8_t V = 3;
for (int row = 0; row < buf->height(); ++row) {
for (int col = 0; col < buf->width(); ++col) {
buf->MutableDataY()[row * buf->StrideY() + col] = Y;
buf->MutableDataU()[row * buf->StrideU() + col] = U;
buf->MutableDataV()[row * buf->StrideV() + col] = V;
}
}
}
} // namespace
TEST(I444BufferTest, InitialData) {
constexpr int stride = 3;
constexpr int width = 3;
constexpr int height = 3;
rtc::scoped_refptr<I444Buffer> i444_buffer(I444Buffer::Create(width, height));
EXPECT_EQ(width, i444_buffer->width());
EXPECT_EQ(height, i444_buffer->height());
EXPECT_EQ(stride, i444_buffer->StrideY());
EXPECT_EQ(stride, i444_buffer->StrideU());
EXPECT_EQ(stride, i444_buffer->StrideV());
EXPECT_EQ(3, i444_buffer->ChromaWidth());
EXPECT_EQ(3, i444_buffer->ChromaHeight());
}
TEST(I444BufferTest, ReadPixels) {
constexpr int width = 3;
constexpr int height = 3;
rtc::scoped_refptr<I444Buffer> i444_buffer(I444Buffer::Create(width, height));
// Y = 1, U = 2, V = 3.
FillI444Buffer(i444_buffer);
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
EXPECT_EQ(1, GetY(i444_buffer, col, row));
EXPECT_EQ(2, GetU(i444_buffer, col, row));
EXPECT_EQ(3, GetV(i444_buffer, col, row));
}
}
}
TEST(I444BufferTest, ToI420) {
constexpr int width = 3;
constexpr int height = 3;
constexpr int size_y = width * height;
constexpr int size_u = (width + 1) / 2 * (height + 1) / 2;
constexpr int size_v = (width + 1) / 2 * (height + 1) / 2;
rtc::scoped_refptr<I420Buffer> reference(I420Buffer::Create(width, height));
memset(reference->MutableDataY(), 8, size_y);
memset(reference->MutableDataU(), 4, size_u);
memset(reference->MutableDataV(), 2, size_v);
rtc::scoped_refptr<I444Buffer> i444_buffer(I444Buffer::Create(width, height));
// Convert the reference buffer to I444.
memset(i444_buffer->MutableDataY(), 8, size_y);
memset(i444_buffer->MutableDataU(), 4, size_y);
memset(i444_buffer->MutableDataV(), 2, size_y);
// Confirm YUV values are as expected.
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
EXPECT_EQ(8, GetY(i444_buffer, col, row));
EXPECT_EQ(4, GetU(i444_buffer, col, row));
EXPECT_EQ(2, GetV(i444_buffer, col, row));
}
}
rtc::scoped_refptr<I420BufferInterface> i420_buffer(i444_buffer->ToI420());
EXPECT_EQ(height, i420_buffer->height());
EXPECT_EQ(width, i420_buffer->width());
EXPECT_TRUE(test::FrameBufsEqual(reference, i420_buffer));
}
} // namespace webrtc
| 32.663717
| 80
| 0.674614
|
wyshen2020
|
9a1dbe88c0e383142c322bd3b1d423c0cad52185
| 67,275
|
cxx
|
C++
|
Modules/Loadable/SubjectHierarchy/Widgets/qMRMLSubjectHierarchyTreeView.cxx
|
forfullstack/slicersources-src
|
91bcecf037a27f3fad4c0ab57e8286fc258bb0f5
|
[
"Apache-2.0"
] | null | null | null |
Modules/Loadable/SubjectHierarchy/Widgets/qMRMLSubjectHierarchyTreeView.cxx
|
forfullstack/slicersources-src
|
91bcecf037a27f3fad4c0ab57e8286fc258bb0f5
|
[
"Apache-2.0"
] | null | null | null |
Modules/Loadable/SubjectHierarchy/Widgets/qMRMLSubjectHierarchyTreeView.cxx
|
forfullstack/slicersources-src
|
91bcecf037a27f3fad4c0ab57e8286fc258bb0f5
|
[
"Apache-2.0"
] | null | null | null |
/*==============================================================================
Program: 3D Slicer
Copyright (c) Laboratory for Percutaneous Surgery (PerkLab)
Queen's University, Kingston, ON, Canada. All Rights Reserved.
See COPYRIGHT.txt
or http://www.slicer.org/copyright/copyright.txt for details.
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.
This file was originally developed by Csaba Pinter, PerkLab, Queen's University
and was supported through the Applied Cancer Research Unit program of Cancer Care
Ontario with funds provided by the Ontario Ministry of Health and Long-Term Care
==============================================================================*/
// Qt includes
#include <QHeaderView>
#include <QAction>
#include <QActionGroup>
#include <QMenu>
#include <QMouseEvent>
#include <QKeyEvent>
#include <QInputDialog>
#include <QMessageBox>
#include <QDebug>
#include <QToolTip>
#include <QBuffer>
#include <QApplication>
// SubjectHierarchy includes
#include "qMRMLSubjectHierarchyTreeView.h"
#include "qMRMLSubjectHierarchyModel.h"
#include "qMRMLSortFilterSubjectHierarchyProxyModel.h"
#include "qMRMLTransformItemDelegate.h"
#include "vtkSlicerSubjectHierarchyModuleLogic.h"
#include "qSlicerSubjectHierarchyPluginHandler.h"
#include "qSlicerSubjectHierarchyAbstractPlugin.h"
#include "qSlicerSubjectHierarchyDefaultPlugin.h"
// Terminologies includes
#include "qSlicerTerminologyItemDelegate.h"
// MRML includes
#include <vtkMRMLScene.h>
#include <vtkMRMLScalarVolumeNode.h>
// qMRML includes
#include "qMRMLItemDelegate.h"
// VTK includes
#include <vtkIdList.h>
//------------------------------------------------------------------------------
/// \ingroup Slicer_QtModules_SubjectHierarchy
class qMRMLSubjectHierarchyTreeViewPrivate
{
Q_DECLARE_PUBLIC(qMRMLSubjectHierarchyTreeView);
protected:
qMRMLSubjectHierarchyTreeView* const q_ptr;
public:
qMRMLSubjectHierarchyTreeViewPrivate(qMRMLSubjectHierarchyTreeView& object);
virtual void init();
/// Setup all actions for tree view
void setupActions();
/// Get list of enabled plugins \sa PluginWhitelist \sa PluginBlacklist
QList<qSlicerSubjectHierarchyAbstractPlugin*> enabledPlugins();
public:
qMRMLSubjectHierarchyModel* Model;
qMRMLSortFilterSubjectHierarchyProxyModel* SortFilterModel;
bool ShowRootItem;
vtkIdType RootItemID;
bool ContextMenuEnabled;
bool EditActionVisible;
bool SelectRoleSubMenuVisible;
QMenu* NodeMenu;
QAction* RenameAction;
QAction* DeleteAction;
QAction* EditAction;
QAction* ToggleVisibilityAction;
QList<QAction*> SelectPluginActions;
QMenu* SelectPluginSubMenu;
QActionGroup* SelectPluginActionGroup;
QAction* ExpandToDepthAction;
QMenu* SceneMenu;
QMenu* VisibilityMenu;
QStringList PluginWhitelist;
QStringList PluginBlacklist;
qMRMLTransformItemDelegate* TransformItemDelegate;
/// Subject hierarchy node
vtkWeakPointer<vtkMRMLSubjectHierarchyNode> SubjectHierarchyNode;
/// Flag determining whether to highlight items referenced by DICOM. Storing DICOM references:
/// Referenced SOP instance UIDs (in attribute named vtkMRMLSubjectHierarchyConstants::GetDICOMReferencedInstanceUIDsAttributeName())
/// -> SH node instance UIDs (serialized string lists in subject hierarchy UID vtkMRMLSubjectHierarchyConstants::GetDICOMInstanceUIDName())
bool HighlightReferencedItems;
/// Cached list of selected items to return the current selection
QList<vtkIdType> SelectedItems;
/// List of selected items to restore at the end of batch processing (the whole tree is rebuilt and selection is lost)
QList<vtkIdType> SelectedItemsToRestore;
/// Cached list of highlighted items to speed up clearing highlight after new selection
QList<vtkIdType> HighlightedItems;
};
//------------------------------------------------------------------------------
qMRMLSubjectHierarchyTreeViewPrivate::qMRMLSubjectHierarchyTreeViewPrivate(qMRMLSubjectHierarchyTreeView& object)
: q_ptr(&object)
, Model(nullptr)
, SortFilterModel(nullptr)
, ShowRootItem(false)
, RootItemID(vtkMRMLSubjectHierarchyNode::INVALID_ITEM_ID)
, ContextMenuEnabled(true)
, EditActionVisible(true)
, SelectRoleSubMenuVisible(false)
, NodeMenu(nullptr)
, RenameAction(nullptr)
, DeleteAction(nullptr)
, EditAction(nullptr)
, ToggleVisibilityAction(nullptr)
, SelectPluginSubMenu(nullptr)
, SelectPluginActionGroup(nullptr)
, ExpandToDepthAction(nullptr)
, SceneMenu(nullptr)
, VisibilityMenu(nullptr)
, TransformItemDelegate(nullptr)
, SubjectHierarchyNode(nullptr)
, HighlightReferencedItems(true)
{
}
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeViewPrivate::init()
{
Q_Q(qMRMLSubjectHierarchyTreeView);
// Set up scene model and sort and proxy model
this->Model = new qMRMLSubjectHierarchyModel(q);
QObject::connect( this->Model, SIGNAL(requestExpandItem(vtkIdType)), q, SLOT(expandItem(vtkIdType)) );
QObject::connect( this->Model, SIGNAL(requestCollapseItem(vtkIdType)), q, SLOT(collapseItem(vtkIdType)) );
QObject::connect( this->Model, SIGNAL(requestSelectItems(QList<vtkIdType>)), q, SLOT(setCurrentItems(QList<vtkIdType>)) );
QObject::connect( this->Model, SIGNAL(subjectHierarchyUpdated()), q, SLOT(updateRootItem()) );
this->SortFilterModel = new qMRMLSortFilterSubjectHierarchyProxyModel(q);
q->QTreeView::setModel(this->SortFilterModel);
QObject::connect( q->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
q, SLOT(onSelectionChanged(QItemSelection,QItemSelection)) );
this->SortFilterModel->setParent(q);
this->SortFilterModel->setSourceModel(this->Model);
// Set up headers
q->resetColumnSizesToDefault();
if (this->Model->descriptionColumn()>=0)
{
q->setColumnHidden(this->Model->descriptionColumn(), true);
}
// Set generic MRML item delegate
q->setItemDelegate(new qMRMLItemDelegate(q));
// Create default menu actions
this->NodeMenu = new QMenu(q);
this->NodeMenu->setObjectName("nodeMenuTreeView");
this->RenameAction = new QAction("名前の変更", this->NodeMenu);
this->NodeMenu->addAction(this->RenameAction);
QObject::connect(this->RenameAction, SIGNAL(triggered()), q, SLOT(renameCurrentItem()));
this->DeleteAction = new QAction("削除", this->NodeMenu);
this->NodeMenu->addAction(this->DeleteAction);
QObject::connect(this->DeleteAction, SIGNAL(triggered()), q, SLOT(deleteSelectedItems()));
this->EditAction = new QAction("Edit properties...", this->NodeMenu);
this->NodeMenu->addAction(this->EditAction);
QObject::connect(this->EditAction, SIGNAL(triggered()), q, SLOT(editCurrentItem()));
this->ToggleVisibilityAction = new QAction("Toggle visibility", this->NodeMenu);
this->NodeMenu->addAction(this->ToggleVisibilityAction);
QObject::connect(this->ToggleVisibilityAction, SIGNAL(triggered()), q, SLOT(toggleVisibilityOfSelectedItems()));
this->SceneMenu = new QMenu(q);
this->SceneMenu->setObjectName("sceneMenuTreeView");
this->VisibilityMenu = new QMenu(q);
this->VisibilityMenu->setObjectName("visibilityMenuTreeView");
// Set item delegate for color column
q->setItemDelegateForColumn(this->Model->colorColumn(), new qSlicerTerminologyItemDelegate(q));
// Set item delegate for transform column (that creates widgets for certain types of data)
this->TransformItemDelegate = new qMRMLTransformItemDelegate(q);
this->TransformItemDelegate->setMRMLScene(q->mrmlScene());
q->setItemDelegateForColumn(this->Model->transformColumn(), this->TransformItemDelegate);
QObject::connect( this->TransformItemDelegate, SIGNAL(removeTransformsFromBranchOfCurrentItem()),
this->Model, SLOT(onRemoveTransformsFromBranchOfCurrentItem()) );
QObject::connect( this->TransformItemDelegate, SIGNAL(hardenTransformOnBranchOfCurrentItem()),
this->Model, SLOT(onHardenTransformOnBranchOfCurrentItem()) );
q->setContextMenuPolicy(Qt::CustomContextMenu);
QObject::connect(q, SIGNAL(customContextMenuRequested(const QPoint&)), q, SLOT(onCustomContextMenu(const QPoint&)));
// Make connections
QObject::connect( this->Model, SIGNAL(invalidateFilter()), this->SortFilterModel, SLOT(invalidate()) );
QObject::connect( q, SIGNAL(expanded(const QModelIndex&)), q, SLOT(onItemExpanded(const QModelIndex&)) );
QObject::connect( q, SIGNAL(collapsed(const QModelIndex&)), q, SLOT(onItemCollapsed(const QModelIndex&)) );
// Set up scene and node actions for the tree view
this->SceneMenu->setVisible(false);
this->setupActions();
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::resetColumnSizesToDefault()
{
Q_D(qMRMLSubjectHierarchyTreeView);
// Set up headers
this->header()->setStretchLastSection(false);
if (this->header()->count() <= 0)
{
return;
}
if (d->Model->nameColumn() >= 0)
{
this->header()->setSectionResizeMode(d->Model->nameColumn(), QHeaderView::Stretch);
}
if (d->Model->descriptionColumn() >= 0)
{
this->header()->setSectionResizeMode(d->Model->descriptionColumn(), QHeaderView::Interactive);
}
if (d->Model->visibilityColumn() >= 0)
{
this->header()->setSectionResizeMode(d->Model->visibilityColumn(), QHeaderView::ResizeToContents);
}
if (d->Model->colorColumn() >= 0)
{
this->header()->setSectionResizeMode(d->Model->colorColumn(), QHeaderView::ResizeToContents);
}
if (d->Model->transformColumn() >= 0)
{
this->header()->setSectionResizeMode(d->Model->transformColumn(), QHeaderView::ResizeToContents);
}
if (d->Model->idColumn() >= 0)
{
this->header()->setSectionResizeMode(d->Model->idColumn(), QHeaderView::ResizeToContents);
}
}
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeViewPrivate::setupActions()
{
Q_Q(qMRMLSubjectHierarchyTreeView);
// Set up expand to level action and its menu
this->ExpandToDepthAction = new QAction("Expand tree to level...", this->NodeMenu);
//this->SceneMenu->addAction(this->ExpandToDepthAction);
QMenu* expandToDepthSubMenu = new QMenu();
this->ExpandToDepthAction->setMenu(expandToDepthSubMenu);
QAction* expandToDepth_1 = new QAction("1",q);
QObject::connect(expandToDepth_1, SIGNAL(triggered()), q, SLOT(expandToDepthFromContextMenu()));
expandToDepthSubMenu->addAction(expandToDepth_1);
this->ExpandToDepthAction->setMenu(expandToDepthSubMenu);
QAction* expandToDepth_2 = new QAction("2",q);
QObject::connect(expandToDepth_2, SIGNAL(triggered()), q, SLOT(expandToDepthFromContextMenu()));
expandToDepthSubMenu->addAction(expandToDepth_2);
this->ExpandToDepthAction->setMenu(expandToDepthSubMenu);
QAction* expandToDepth_3 = new QAction("3",q);
QObject::connect(expandToDepth_3, SIGNAL(triggered()), q, SLOT(expandToDepthFromContextMenu()));
expandToDepthSubMenu->addAction(expandToDepth_3);
this->ExpandToDepthAction->setMenu(expandToDepthSubMenu);
QAction* expandToDepth_4 = new QAction("4",q);
QObject::connect(expandToDepth_4, SIGNAL(triggered()), q, SLOT(expandToDepthFromContextMenu()));
expandToDepthSubMenu->addAction(expandToDepth_4);
//this->ExpandToDepthAction->hide();
// Perform tasks needed for all plugins
int index = 0; // Index used to insert actions before default tree actions
foreach (qSlicerSubjectHierarchyAbstractPlugin* plugin, qSlicerSubjectHierarchyPluginHandler::instance()->allPlugins())
{
// Add node context menu actions
foreach (QAction* action, plugin->itemContextMenuActions())
{
this->NodeMenu->insertAction(this->NodeMenu->actions()[index++], action);
}
// Add scene context menu actions
foreach (QAction* action, plugin->sceneContextMenuActions())
{
this->SceneMenu->addAction(action);
}
// Add visibility context menu actions
foreach (QAction* action, plugin->visibilityContextMenuActions())
{
this->VisibilityMenu->addAction(action);
}
// Connect plugin events to be handled by the tree view
QObject::connect( plugin, SIGNAL(requestExpandItem(vtkIdType)), q, SLOT(expandItem(vtkIdType)) );
QObject::connect( plugin, SIGNAL(requestInvalidateFilter()), q->model(), SIGNAL(invalidateFilter()) );
}
// Create a plugin selection action for each plugin in a sub-menu
this->SelectPluginSubMenu = this->NodeMenu->addMenu("Select role");
this->SelectPluginActionGroup = new QActionGroup(q);
foreach (qSlicerSubjectHierarchyAbstractPlugin* plugin, qSlicerSubjectHierarchyPluginHandler::instance()->allPlugins())
{
QAction* selectPluginAction = new QAction(plugin->name(),q);
selectPluginAction->setCheckable(true);
selectPluginAction->setActionGroup(this->SelectPluginActionGroup);
selectPluginAction->setData(QVariant(plugin->name()));
this->SelectPluginSubMenu->addAction(selectPluginAction);
QObject::connect(selectPluginAction, SIGNAL(triggered()), q, SLOT(selectPluginForCurrentItem()));
this->SelectPluginActions << selectPluginAction;
}
// Update actions in owner plugin sub-menu when opened
QObject::connect( this->SelectPluginSubMenu, SIGNAL(aboutToShow()), q, SLOT(updateSelectPluginActions()) );
}
//------------------------------------------------------------------------------
QList<qSlicerSubjectHierarchyAbstractPlugin*> qMRMLSubjectHierarchyTreeViewPrivate::enabledPlugins()
{
QList<qSlicerSubjectHierarchyAbstractPlugin*> enabledPluginList;
foreach (qSlicerSubjectHierarchyAbstractPlugin* plugin, qSlicerSubjectHierarchyPluginHandler::instance()->allPlugins())
{
QString pluginName = plugin->name();
bool whitelisted = (this->PluginWhitelist.isEmpty() || this->PluginWhitelist.contains(pluginName));
bool blacklisted = (!this->PluginBlacklist.isEmpty() && this->PluginBlacklist.contains(pluginName));
if ((whitelisted && !blacklisted) || !pluginName.compare("Default"))
{
enabledPluginList << plugin;
}
}
return enabledPluginList;
}
//------------------------------------------------------------------------------
// qMRMLSubjectHierarchyTreeView
//------------------------------------------------------------------------------
qMRMLSubjectHierarchyTreeView::qMRMLSubjectHierarchyTreeView(QWidget *parent)
: QTreeView(parent)
, d_ptr(new qMRMLSubjectHierarchyTreeViewPrivate(*this))
{
Q_D(qMRMLSubjectHierarchyTreeView);
d->init();
}
//------------------------------------------------------------------------------
qMRMLSubjectHierarchyTreeView::~qMRMLSubjectHierarchyTreeView() = default;
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setSubjectHierarchyNode(vtkMRMLSubjectHierarchyNode* shNode)
{
Q_D(qMRMLSubjectHierarchyTreeView);
d->SubjectHierarchyNode = shNode;
qvtkReconnect( shNode, vtkMRMLSubjectHierarchyNode::SubjectHierarchyItemModifiedEvent,
this, SLOT( onSubjectHierarchyItemModified(vtkObject*,void*) ) );
if (!shNode)
{
d->Model->setMRMLScene(nullptr);
d->TransformItemDelegate->setMRMLScene(nullptr);
return;
}
vtkMRMLScene* scene = shNode->GetScene();
if (!scene)
{
qCritical() << Q_FUNC_INFO << ": Given subject hierarchy node is not in a MRML scene";
}
d->Model->setMRMLScene(scene);
d->TransformItemDelegate->setMRMLScene(scene);
this->setRootItem(shNode->GetSceneItemID());
this->expandToDepth(4);
}
//------------------------------------------------------------------------------
vtkMRMLSubjectHierarchyNode* qMRMLSubjectHierarchyTreeView::subjectHierarchyNode()const
{
Q_D(const qMRMLSubjectHierarchyTreeView);
return d->SubjectHierarchyNode;
}
//------------------------------------------------------------------------------
vtkMRMLScene* qMRMLSubjectHierarchyTreeView::mrmlScene()const
{
Q_D(const qMRMLSubjectHierarchyTreeView);
return d->Model ? d->Model->mrmlScene() : nullptr;
}
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setMRMLScene(vtkMRMLScene* scene)
{
if (this->mrmlScene() == scene)
{
return;
}
this->setSubjectHierarchyNode(scene ? vtkMRMLSubjectHierarchyNode::GetSubjectHierarchyNode(scene) : nullptr);
// Connect scene close ended event so that subject hierarchy can be cleared
qvtkReconnect( scene, vtkMRMLScene::EndCloseEvent, this, SLOT( onMRMLSceneCloseEnded(vtkObject*) ) );
qvtkReconnect( scene, vtkMRMLScene::StartBatchProcessEvent, this, SLOT( onMRMLSceneStartBatchProcess(vtkObject*) ) );
qvtkReconnect( scene, vtkMRMLScene::EndBatchProcessEvent, this, SLOT( onMRMLSceneEndBatchProcess(vtkObject*) ) );
}
//------------------------------------------------------------------------------
vtkIdType qMRMLSubjectHierarchyTreeView::currentItem()const
{
Q_D(const qMRMLSubjectHierarchyTreeView);
return d->SelectedItems.count() ? d->SelectedItems[0] : vtkMRMLSubjectHierarchyNode::INVALID_ITEM_ID;
}
//------------------------------------------------------------------------------
vtkMRMLNode* qMRMLSubjectHierarchyTreeView::currentNode()const
{
Q_D(const qMRMLSubjectHierarchyTreeView);
vtkIdType itemID = currentItem();
if (itemID == vtkMRMLSubjectHierarchyNode::INVALID_ITEM_ID || !d->SubjectHierarchyNode)
{
return nullptr;
}
return d->SubjectHierarchyNode->GetItemDataNode(itemID);
}
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setCurrentItem(vtkIdType itemID)
{
Q_D(const qMRMLSubjectHierarchyTreeView);
if (!d->SortFilterModel)
{
qCritical() << Q_FUNC_INFO << ": Invalid data model";
return;
}
QModelIndex itemIndex = d->SortFilterModel->indexFromSubjectHierarchyItem(itemID);
this->selectionModel()->select(itemIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
}
//------------------------------------------------------------------------------
QList<vtkIdType> qMRMLSubjectHierarchyTreeView::currentItems()
{
Q_D(const qMRMLSubjectHierarchyTreeView);
return d->SelectedItems;
}
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::currentItems(vtkIdList* selectedItems)
{
Q_D(const qMRMLSubjectHierarchyTreeView);
if (!selectedItems)
{
qCritical() << Q_FUNC_INFO << ": Invalid item list";
return;
}
foreach (vtkIdType item, d->SelectedItems)
{
selectedItems->InsertNextId(item);
}
}
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setCurrentItems(QList<vtkIdType> items)
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SortFilterModel)
{
qCritical() << Q_FUNC_INFO << ": Invalid data model";
return;
}
this->clearSelection();
foreach (long itemID, items)
{
QModelIndex itemIndex = d->SortFilterModel->indexFromSubjectHierarchyItem(vtkIdType(itemID));
if (itemIndex.isValid())
{
this->selectionModel()->select(itemIndex, QItemSelectionModel::Select | QItemSelectionModel::Rows);
}
}
}
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setCurrentItems(vtkIdList* items)
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SortFilterModel)
{
qCritical() << Q_FUNC_INFO << ": Invalid data model";
return;
}
if (!items)
{
qCritical() << Q_FUNC_INFO << ": Invalid item list";
return;
}
this->clearSelection();
for (int index=0; index<items->GetNumberOfIds(); ++index)
{
QModelIndex itemIndex = d->SortFilterModel->indexFromSubjectHierarchyItem(items->GetId(index));
if (itemIndex.isValid())
{
this->selectionModel()->select(itemIndex, QItemSelectionModel::Select | QItemSelectionModel::Rows);
}
}
}
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setCurrentNode(vtkMRMLNode* node)
{
Q_D(const qMRMLSubjectHierarchyTreeView);
if (!node || !d->SubjectHierarchyNode)
{
return;
}
vtkIdType itemID = d->SubjectHierarchyNode->GetItemByDataNode(node);
if (!itemID)
{
qCritical() << Q_FUNC_INFO << ": Unable to find subject hierarchy item by data node " << node->GetName();
return;
}
this->setCurrentItem(itemID);
}
//--------------------------------------------------------------------------
qMRMLSortFilterSubjectHierarchyProxyModel* qMRMLSubjectHierarchyTreeView::sortFilterProxyModel()const
{
Q_D(const qMRMLSubjectHierarchyTreeView);
if (!d->SortFilterModel)
{
qCritical() << Q_FUNC_INFO << ": Invalid sort filter proxy model";
}
return d->SortFilterModel;
}
//--------------------------------------------------------------------------
qMRMLSubjectHierarchyModel* qMRMLSubjectHierarchyTreeView::model()const
{
Q_D(const qMRMLSubjectHierarchyTreeView);
if (!d->Model)
{
qCritical() << Q_FUNC_INFO << ": Invalid data model";
}
return d->Model;
}
//--------------------------------------------------------------------------
int qMRMLSubjectHierarchyTreeView::displayedItemCount()const
{
Q_D(const qMRMLSubjectHierarchyTreeView);
int count = this->sortFilterProxyModel()->acceptedItemCount(this->rootItem());
if (d->ShowRootItem)
{
count++;
}
return count;
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setShowRootItem(bool show)
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (d->ShowRootItem == show)
{
return;
}
vtkIdType oldRootItemID = this->rootItem();
d->ShowRootItem = show;
this->setRootItem(oldRootItemID);
}
//--------------------------------------------------------------------------
bool qMRMLSubjectHierarchyTreeView::showRootItem()const
{
Q_D(const qMRMLSubjectHierarchyTreeView);
return d->ShowRootItem;
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setRootItem(vtkIdType rootItemID)
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SubjectHierarchyNode)
{
return;
}
qMRMLSubjectHierarchyModel* sceneModel = qobject_cast<qMRMLSubjectHierarchyModel*>(this->model());
// Reset item in unaffiliated filter (that hides all siblings and their children)
this->sortFilterProxyModel()->setHideItemsUnaffiliatedWithItemID(vtkMRMLSubjectHierarchyNode::INVALID_ITEM_ID);
QModelIndex treeRootIndex;
if (!rootItemID)
{
treeRootIndex = sceneModel->invisibleRootItem()->index();
}
else if (rootItemID == d->SubjectHierarchyNode->GetSceneItemID())
{
if (d->ShowRootItem)
{
// Scene is a special item, so it needs to be shown, then the invisible root item needs to be root
treeRootIndex = sceneModel->invisibleRootItem()->index();
}
else
{
treeRootIndex = this->sortFilterProxyModel()->subjectHierarchySceneIndex();
}
}
else
{
treeRootIndex = this->sortFilterProxyModel()->indexFromSubjectHierarchyItem(rootItemID);
if (d->ShowRootItem)
{
// Hide the siblings of the root item and their children
this->sortFilterProxyModel()->setHideItemsUnaffiliatedWithItemID(rootItemID);
// The parent of the root node becomes the root for QTreeView.
treeRootIndex = treeRootIndex.parent();
rootItemID = this->sortFilterProxyModel()->subjectHierarchyItemFromIndex(treeRootIndex);
}
}
//TODO: Connect SH node's item modified event if necessary
//qvtkReconnect(this->rootItem(), rootItemID, vtkCommand::ModifiedEvent,
// this, SLOT(updateRootItem(vtkObject*)));
d->RootItemID = rootItemID;
this->setRootIndex(treeRootIndex);
}
//--------------------------------------------------------------------------
vtkIdType qMRMLSubjectHierarchyTreeView::rootItem()const
{
Q_D(const qMRMLSubjectHierarchyTreeView);
if (!d->SubjectHierarchyNode)
{
return vtkMRMLSubjectHierarchyNode::INVALID_ITEM_ID;
}
vtkIdType treeRootItemID = this->sortFilterProxyModel()->subjectHierarchyItemFromIndex(this->rootIndex());
if (d->ShowRootItem)
{
if (d->RootItemID == d->SubjectHierarchyNode->GetSceneItemID())
{
// Scene is a special item, so it needs to be shown, then the invisible root item needs to be root.
// So in that case no checks are performed
return d->RootItemID;
}
else if (this->sortFilterProxyModel()->hideItemsUnaffiliatedWithItemID())
{
treeRootItemID = this->sortFilterProxyModel()->hideItemsUnaffiliatedWithItemID();
}
}
// Check if stored root item ID matches the actual root item in the tree view.
// If the tree is empty (e.g. due to filters), then treeRootItemID is invalid, and then it's not an error
if (treeRootItemID && d->RootItemID != treeRootItemID)
{
qCritical() << Q_FUNC_INFO << ": Root item mismatch";
}
return d->RootItemID;
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::updateRootItem()
{
Q_D(qMRMLSubjectHierarchyTreeView);
// The scene might have been updated, need to update root item as well to restore view
this->setRootItem(d->RootItemID);
}
//--------------------------------------------------------------------------
bool qMRMLSubjectHierarchyTreeView::highlightReferencedItems()const
{
Q_D(const qMRMLSubjectHierarchyTreeView);
return d->HighlightReferencedItems;
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setHighlightReferencedItems(bool highlightOn)
{
Q_D(qMRMLSubjectHierarchyTreeView);
d->HighlightReferencedItems = highlightOn;
}
//--------------------------------------------------------------------------
bool qMRMLSubjectHierarchyTreeView::contextMenuEnabled()const
{
Q_D(const qMRMLSubjectHierarchyTreeView);
return d->ContextMenuEnabled;
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setContextMenuEnabled(bool enabled)
{
Q_D(qMRMLSubjectHierarchyTreeView);
d->ContextMenuEnabled = enabled;
}
//--------------------------------------------------------------------------
bool qMRMLSubjectHierarchyTreeView::editMenuActionVisible()const
{
Q_D(const qMRMLSubjectHierarchyTreeView);
return d->EditActionVisible;
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setEditMenuActionVisible(bool visible)
{
Q_D(qMRMLSubjectHierarchyTreeView);
d->EditActionVisible = visible;
}
//--------------------------------------------------------------------------
bool qMRMLSubjectHierarchyTreeView::selectRoleSubMenuVisible()const
{
Q_D(const qMRMLSubjectHierarchyTreeView);
return d->SelectRoleSubMenuVisible;
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setSelectRoleSubMenuVisible(bool visible)
{
Q_D(qMRMLSubjectHierarchyTreeView);
d->SelectRoleSubMenuVisible = visible;
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setAttributeFilter(const QString& attributeName, const QVariant& attributeValue/*=QVariant()*/)
{
this->sortFilterProxyModel()->setAttributeNameFilter(attributeName);
this->sortFilterProxyModel()->setAttributeValueFilter(attributeValue.toString());
// Reset root item, as it may have been corrupted, when tree became empty due to the filter
this->setRootItem(this->rootItem());
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setAttributeNameFilter(const QString& attributeName)
{
this->sortFilterProxyModel()->setAttributeNameFilter(attributeName);
// Reset root item, as it may have been corrupted, when tree became empty due to the filter
this->setRootItem(this->rootItem());
}
//--------------------------------------------------------------------------
QString qMRMLSubjectHierarchyTreeView::attributeNameFilter()const
{
return this->sortFilterProxyModel()->attributeNameFilter();
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setAttributeValueFilter(const QString& attributeValue)
{
this->sortFilterProxyModel()->setAttributeValueFilter(attributeValue);
// Reset root item, as it may have been corrupted, when tree became empty due to the filter
this->setRootItem(this->rootItem());
}
//--------------------------------------------------------------------------
QString qMRMLSubjectHierarchyTreeView::attributeValueFilter()const
{
return this->sortFilterProxyModel()->attributeValueFilter();
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::removeAttributeFilter()
{
this->sortFilterProxyModel()->setAttributeNameFilter(QString());
this->sortFilterProxyModel()->setAttributeValueFilter(QString());
// Reset root item, as it may have been corrupted, when tree became empty due to the filter
this->setRootItem(this->rootItem());
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setLevelFilter(QStringList &levelFilter)
{
this->sortFilterProxyModel()->setLevelFilter(levelFilter);
// Reset root item, as it may have been corrupted, when tree became empty due to the filter
this->setRootItem(this->rootItem());
}
//--------------------------------------------------------------------------
QStringList qMRMLSubjectHierarchyTreeView::levelFilter()const
{
return this->sortFilterProxyModel()->levelFilter();
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setNameFilter(QString &nameFilter)
{
this->sortFilterProxyModel()->setNameFilter(nameFilter);
// Reset root item, as it may have been corrupted, when tree became empty due to the filter
this->setRootItem(this->rootItem());
}
//--------------------------------------------------------------------------
QString qMRMLSubjectHierarchyTreeView::nameFilter()const
{
return this->sortFilterProxyModel()->nameFilter();
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setNodeTypes(const QStringList& types)
{
this->sortFilterProxyModel()->setNodeTypes(types);
// Reset root item, as it may have been corrupted, when tree became empty due to the filter
this->setRootItem(this->rootItem());
}
//--------------------------------------------------------------------------
QStringList qMRMLSubjectHierarchyTreeView::nodeTypes()const
{
return this->sortFilterProxyModel()->nodeTypes();
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setHideChildNodeTypes(const QStringList& types)
{
this->sortFilterProxyModel()->setHideChildNodeTypes(types);
// Reset root item, as it may have been corrupted, when tree became empty due to the filter
this->setRootItem(this->rootItem());
}
//--------------------------------------------------------------------------
QStringList qMRMLSubjectHierarchyTreeView::hideChildNodeTypes()const
{
return this->sortFilterProxyModel()->hideChildNodeTypes();
}
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::toggleSubjectHierarchyItemVisibility(vtkIdType itemID)
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SubjectHierarchyNode)
{
return;
}
if (!itemID)
{
return;
}
// If more than 10 item visibilities are changed, then enter in batch processing state
vtkNew<vtkIdList> childItemsList;
d->SubjectHierarchyNode->GetItemChildren(itemID, childItemsList, true);
bool batchProcessing = (childItemsList->GetNumberOfIds() > 10);
if (batchProcessing)
{
d->SubjectHierarchyNode->GetScene()->StartState(vtkMRMLScene::BatchProcessState);
}
qSlicerSubjectHierarchyAbstractPlugin* ownerPlugin =
qSlicerSubjectHierarchyPluginHandler::instance()->getOwnerPluginForSubjectHierarchyItem(itemID);
if (!ownerPlugin)
{
qCritical() << Q_FUNC_INFO << ": Subject hierarchy item " << itemID << " (named "
<< d->SubjectHierarchyNode->GetItemName(itemID).c_str() << ") is not owned by any plugin";
return;
}
int visible = (ownerPlugin->getDisplayVisibility(itemID) > 0 ? 0 : 1);
ownerPlugin->setDisplayVisibility(itemID, visible);
if (batchProcessing)
{
d->SubjectHierarchyNode->GetScene()->EndState(vtkMRMLScene::BatchProcessState);
}
// Trigger view update for the modified item
d->SubjectHierarchyNode->ItemModified(itemID);
}
//------------------------------------------------------------------------------
bool qMRMLSubjectHierarchyTreeView::clickDecoration(QMouseEvent* e)
{
Q_D(qMRMLSubjectHierarchyTreeView);
QModelIndex index = this->indexAt(e->pos());
QStyleOptionViewItem opt = this->viewOptions();
opt.rect = this->visualRect(index);
qobject_cast<qMRMLItemDelegate*>(this->itemDelegate())->initStyleOption(&opt,index);
QRect decorationElement = this->style()->subElementRect(QStyle::SE_ItemViewItemDecoration, &opt, this);
if (!decorationElement.contains(e->pos()))
{
// Mouse event is not within an item decoration
return false;
}
QModelIndex sourceIndex = this->sortFilterProxyModel()->mapToSource(index);
if (!(sourceIndex.flags() & Qt::ItemIsEnabled))
{
// Item is disabled
return false;
}
// Visibility and color columns
if ( sourceIndex.column() == this->model()->visibilityColumn()
|| sourceIndex.column() == this->model()->colorColumn() )
{
vtkIdType itemID = d->SortFilterModel->subjectHierarchyItemFromIndex(index);
if (!itemID)
{
// Valid item is needed for visibility actions
return false;
}
if (e->button() == Qt::LeftButton && sourceIndex.column() == this->model()->visibilityColumn())
{
// Toggle simple visibility
this->toggleSubjectHierarchyItemVisibility(itemID);
}
return true;
}
return false;
}
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::mousePressEvent(QMouseEvent* e)
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SubjectHierarchyNode)
{
return;
}
// Perform default mouse press event (make selections etc.)
this->QTreeView::mousePressEvent(e);
if (e->button() == Qt::LeftButton)
{
// Custom left button action for item decorations (i.e. icon): simple visibility toggle
if (this->clickDecoration(e))
{
return;
}
}
}
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::keyPressEvent(QKeyEvent* e)
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (e->key() == Qt::Key_Space)
{
// Show/hide current item(s) using space
QList<vtkIdType> currentItemIDs = d->SelectedItems;
foreach (vtkIdType itemID, currentItemIDs)
{
this->toggleSubjectHierarchyItemVisibility(itemID);
}
}
this->QTreeView::keyPressEvent(e);
}
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::onSelectionChanged(const QItemSelection& selected, const QItemSelection& deselected)
{
Q_UNUSED(selected);
Q_UNUSED(deselected);
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SortFilterModel || !d->SubjectHierarchyNode || this->mrmlScene()->IsBatchProcessing())
{
return;
}
// Collect selected subject hierarchy items
QList<vtkIdType> selectedShItems;
QList<QModelIndex> selectedIndices = this->selectedIndexes();
foreach (QModelIndex index, selectedIndices)
{
// Only consider the first column to avoid duplicates
if (index.column() != 0)
{
continue;
}
vtkIdType itemID = this->sortFilterProxyModel()->subjectHierarchyItemFromIndex(index);
if (itemID)
{
selectedShItems << itemID;
}
}
// If no item was selected, then the scene is considered to be selected
if (selectedShItems.count() == 0)
{
selectedShItems << d->SubjectHierarchyNode->GetSceneItemID();
}
// Set current item(s) to plugin handler
qSlicerSubjectHierarchyPluginHandler::instance()->setCurrentItems(selectedShItems);
// Cache selected item(s) so that currentItem and currentItems can return them quickly
d->SelectedItems = selectedShItems;
// Highlight items referenced by DICOM in case of single-selection
// Referenced SOP instance UIDs (in attribute named vtkMRMLSubjectHierarchyConstants::GetDICOMReferencedInstanceUIDsAttributeName())
// -> SH item instance UIDs (serialized string lists in subject hierarchy UID vtkMRMLSubjectHierarchyConstants::GetDICOMInstanceUIDName())
if (this->highlightReferencedItems())
{
this->applyReferenceHighlightForItems(selectedShItems);
}
// Emit current item changed signal
vtkIdType newCurrentItemID = vtkMRMLSubjectHierarchyNode::INVALID_ITEM_ID;
if (selectedIndices.count() > 0)
{
newCurrentItemID = d->SortFilterModel->subjectHierarchyItemFromIndex(selectedIndices[0]);
}
emit currentItemChanged(newCurrentItemID);
emit currentItemsChanged(selectedShItems);
}
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::onItemExpanded(const QModelIndex &expandedItemIndex)
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SubjectHierarchyNode || !d->SortFilterModel)
{
return;
}
vtkIdType expandedShItemID = d->SortFilterModel->subjectHierarchyItemFromIndex(expandedItemIndex);
if (expandedShItemID)
{
d->SubjectHierarchyNode->SetItemExpanded(expandedShItemID, true);
}
}
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::onItemCollapsed(const QModelIndex &collapsedItemIndex)
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SubjectHierarchyNode || !d->SortFilterModel)
{
return;
}
vtkIdType collapsedShItemID = d->SortFilterModel->subjectHierarchyItemFromIndex(collapsedItemIndex);
if (collapsedShItemID)
{
d->SubjectHierarchyNode->SetItemExpanded(collapsedShItemID, false);
}
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::populateContextMenuForItem(vtkIdType itemID)
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SubjectHierarchyNode)
{
qCritical() << Q_FUNC_INFO << ": Invalid subject hierarchy";
return;
}
// Have all plugins hide all context menu actions
foreach (qSlicerSubjectHierarchyAbstractPlugin* plugin, qSlicerSubjectHierarchyPluginHandler::instance()->allPlugins())
{
plugin->hideAllContextMenuActions();
}
// Show multi-selection context menu if there are more than one selected items,
// and right-click didn't happen on the scene or the empty area
if ( d->SelectedItems.size() > 1
&& itemID && itemID != d->SubjectHierarchyNode->GetSceneItemID() )
{
// Multi-selection: only show delete and toggle visibility actions
d->EditAction->setVisible(false);
d->RenameAction->setVisible(false);
d->ToggleVisibilityAction->setVisible(true);
d->SelectPluginSubMenu->menuAction()->setVisible(false);
return;
}
// Single selection
vtkIdType currentItemID = this->currentItem();
// If clicked item is the scene or the empty area, then show scene menu regardless the selection
if (!itemID || itemID == d->SubjectHierarchyNode->GetSceneItemID())
{
currentItemID = d->SubjectHierarchyNode->GetSceneItemID();
}
// Do not show certain actions for the scene or empty area
if (!currentItemID || currentItemID == d->SubjectHierarchyNode->GetSceneItemID())
{
d->EditAction->setVisible(false);
d->RenameAction->setVisible(false);
d->ToggleVisibilityAction->setVisible(false);
d->SelectPluginSubMenu->menuAction()->setVisible(false);
}
else
{
d->EditAction->setVisible(d->EditActionVisible);
d->RenameAction->setVisible(true);
d->ToggleVisibilityAction->setVisible(false);
d->SelectPluginSubMenu->menuAction()->setVisible(d->SelectRoleSubMenuVisible);
}
// Have all enabled plugins show context menu actions for current item
foreach (qSlicerSubjectHierarchyAbstractPlugin* plugin, d->enabledPlugins())
{
plugin->showContextMenuActionsForItem(currentItemID);
}
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::populateVisibilityContextMenuForItem(vtkIdType itemID)
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SubjectHierarchyNode)
{
qCritical() << Q_FUNC_INFO << ": Invalid subject hierarchy";
return;
}
if (!itemID || itemID == d->SubjectHierarchyNode->GetSceneItemID())
{
qWarning() << Q_FUNC_INFO << ": Invalid subject hierarchy item for visibility context menu: " << itemID;
return;
}
// Have all plugins hide all visibility context menu actions
foreach (qSlicerSubjectHierarchyAbstractPlugin* plugin, qSlicerSubjectHierarchyPluginHandler::instance()->allPlugins())
{
plugin->hideAllContextMenuActions();
}
// Have all enabled plugins show visibility context menu actions for current item
foreach (qSlicerSubjectHierarchyAbstractPlugin* plugin, d->enabledPlugins())
{
plugin->showVisibilityContextMenuActionsForItem(itemID);
}
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::expandItem(vtkIdType itemID)
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (itemID)
{
QModelIndex itemIndex = d->SortFilterModel->indexFromSubjectHierarchyItem(itemID);
if (itemIndex.isValid())
{
this->expand(itemIndex);
}
}
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::collapseItem(vtkIdType itemID)
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (itemID)
{
QModelIndex itemIndex = d->SortFilterModel->indexFromSubjectHierarchyItem(itemID);
if (itemIndex.isValid())
{
this->collapse(itemIndex);
}
}
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::selectPluginForCurrentItem()
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SubjectHierarchyNode)
{
qCritical() << Q_FUNC_INFO << ": Invalid subject hierarchy";
return;
}
vtkIdType currentItemID = this->currentItem();
if (!currentItemID)
{
qCritical() << Q_FUNC_INFO << ": Invalid current item for manually selecting role";
return;
}
QString selectedPluginName = d->SelectPluginActionGroup->checkedAction()->data().toString();
if (selectedPluginName.isEmpty())
{
qCritical() << Q_FUNC_INFO << ": No owner plugin found for item " << d->SubjectHierarchyNode->GetItemName(currentItemID).c_str();
return;
}
else if (!selectedPluginName.compare(d->SubjectHierarchyNode->GetItemOwnerPluginName(currentItemID).c_str()))
{
// Do nothing if the owner plugin stays the same
return;
}
// Set new owner plugin
d->SubjectHierarchyNode->SetItemOwnerPluginName(currentItemID, selectedPluginName.toUtf8().constData());
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::updateSelectPluginActions()
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SubjectHierarchyNode)
{
qCritical() << Q_FUNC_INFO << ": Invalid subject hierarchy";
return;
}
vtkIdType currentItemID = this->currentItem();
if (!currentItemID)
{
qCritical() << Q_FUNC_INFO << ": Invalid current item";
return;
}
QString ownerPluginName = QString(d->SubjectHierarchyNode->GetItemOwnerPluginName(currentItemID).c_str());
QList<qSlicerSubjectHierarchyAbstractPlugin*> enabledPluginsList = d->enabledPlugins();
foreach (QAction* currentSelectPluginAction, d->SelectPluginActions)
{
// Check select plugin action if it's the owner
bool isOwner = !(currentSelectPluginAction->data().toString().compare(ownerPluginName));
// Get confidence numbers and show the plugins with non-zero confidence
qSlicerSubjectHierarchyAbstractPlugin* currentPlugin =
qSlicerSubjectHierarchyPluginHandler::instance()->pluginByName( currentSelectPluginAction->data().toString() );
double confidenceNumber = currentPlugin->canOwnSubjectHierarchyItem(currentItemID);
// Do not show plugin in list if confidence is 0, or if it's disabled (by whitelist or blacklist).
// Always show owner plugin.
if ( (confidenceNumber <= 0.0 || !enabledPluginsList.contains(currentPlugin))
&& !isOwner )
{
currentSelectPluginAction->setVisible(false);
}
else
{
// Set text to display for the role
QString role = currentPlugin->roleForPlugin();
QString currentSelectPluginActionText = QString("%1: '%2', (%3%)").arg(
role).arg(currentPlugin->displayedItemName(currentItemID)).arg(confidenceNumber*100.0, 0, 'f', 0);
currentSelectPluginAction->setText(currentSelectPluginActionText);
currentSelectPluginAction->setVisible(true);
}
currentSelectPluginAction->setChecked(isOwner);
}
}
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::renameCurrentItem()
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SubjectHierarchyNode)
{
qCritical() << Q_FUNC_INFO << ": Invalid subject hierarchy";
return;
}
vtkIdType currentItemID = this->currentItem();
if (!currentItemID)
{
qCritical() << Q_FUNC_INFO << ": Invalid current item";
return;
}
// Pop up an entry box for the new name, with the old name as default
QString oldName = QString(d->SubjectHierarchyNode->GetItemName(currentItemID).c_str());
bool ok = false;
QString newName = QInputDialog::getText(this, "Rename " + oldName, "New name:", QLineEdit::Normal, oldName, &ok);
if (!ok)
{
return;
}
d->SubjectHierarchyNode->SetItemName(currentItemID, newName.toUtf8().constData());
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::editCurrentItem()
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SubjectHierarchyNode)
{
qCritical() << Q_FUNC_INFO << ": Invalid subject hierarchy";
return;
}
vtkIdType currentItemID = this->currentItem();
if (!currentItemID)
{
qCritical() << Q_FUNC_INFO << ": Invalid current item";
return;
}
qSlicerSubjectHierarchyAbstractPlugin* ownerPlugin =
qSlicerSubjectHierarchyPluginHandler::instance()->getOwnerPluginForSubjectHierarchyItem(currentItemID);
ownerPlugin->editProperties(currentItemID);
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::deleteSelectedItems()
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SubjectHierarchyNode)
{
qCritical() << Q_FUNC_INFO << ": Invalid subject hierarchy";
return;
}
// Remove each selected item
QList<vtkIdType> currentItemIDs = d->SelectedItems;
foreach (vtkIdType itemID, currentItemIDs)
{
if (itemID == d->SubjectHierarchyNode->GetSceneItemID())
{
// Do not delete scene (if no item is selected then the scene will be marked as selected)
continue;
}
// Ask the user whether to delete all the item's children
bool deleteChildren = false;
QMessageBox::StandardButton answer = QMessageBox::Yes;
if ( currentItemIDs.count() > 1
&& !qSlicerSubjectHierarchyPluginHandler::instance()->autoDeleteSubjectHierarchyChildren() )
{
answer =
QMessageBox::question(nullptr, tr("Delete subject hierarchy branch?"),
tr("The deleted subject hierarchy item has children. "
"Do you want to remove those too?\n\n"
"If you choose yes, the whole branch will be deleted, including all children.\n"
"If you choose Yes to All, this question never appears again, and all subject hierarchy children "
"are automatically deleted. This can be later changed in Application Settings."),
QMessageBox::Yes | QMessageBox::No | QMessageBox::YesToAll,
QMessageBox::No);
}
// Delete branch if the user chose yes
if (answer == QMessageBox::Yes || answer == QMessageBox::YesToAll)
{
deleteChildren = true;
}
// Save auto-creation flag in settings
if (answer == QMessageBox::YesToAll)
{
qSlicerSubjectHierarchyPluginHandler::instance()->setAutoDeleteSubjectHierarchyChildren(true);
}
// Remove item (and if requested its children) and its associated data node if any
if (!d->SubjectHierarchyNode->RemoveItem(itemID, true, deleteChildren))
{
qWarning() << Q_FUNC_INFO << ": Failed to remove subject hierarchy item (ID:"
<< itemID << ", name:" << d->SubjectHierarchyNode->GetItemName(itemID).c_str() << ")";
}
}
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::toggleVisibilityOfSelectedItems()
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SubjectHierarchyNode)
{
qCritical() << Q_FUNC_INFO << ": Invalid subject hierarchy";
return;
}
// Remove items from the list whose ancestor item is also contained
// to prevent toggling visibility multiple times on the same item
QList<vtkIdType> consolidatedItemIDs(d->SelectedItems);
foreach (vtkIdType itemID, d->SelectedItems)
{
// Get children recursively for current item
std::vector<vtkIdType> childItemIDs;
d->SubjectHierarchyNode->GetItemChildren(itemID, childItemIDs, true);
// If any of the current item's children is also in the list,
// then remove that child item from the consolidated list
std::vector<vtkIdType>::iterator childIt;
for (childIt=childItemIDs.begin(); childIt!=childItemIDs.end(); ++childIt)
{
vtkIdType childItemID = (*childIt);
if (d->SelectedItems.contains(childItemID))
{
consolidatedItemIDs.removeOne(childItemID);
}
}
}
// Toggle visibility on the remaining items
foreach (vtkIdType itemID, consolidatedItemIDs)
{
this->toggleSubjectHierarchyItemVisibility(itemID);
}
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::expandToDepthFromContextMenu()
{
QAction* senderAction = qobject_cast<QAction*>(this->sender());
if (!senderAction)
{
qCritical() << Q_FUNC_INFO << ": Unable to get sender action";
return;
}
int depth = senderAction->text().toInt();
this->expandToDepth(depth);
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::applyReferenceHighlightForItems(QList<vtkIdType> itemIDs)
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SubjectHierarchyNode)
{
qCritical() << Q_FUNC_INFO << ": Invalid subject hierarchy";
return;
}
vtkMRMLScene* scene = this->mrmlScene();
if (!scene)
{
qCritical() << Q_FUNC_INFO << ": Invalid MRML scene";
return;
}
if (scene->IsImporting())
{
return;
}
// Get scene model and column to highlight
qMRMLSubjectHierarchyModel* sceneModel = qobject_cast<qMRMLSubjectHierarchyModel*>(this->model());
int nameColumn = sceneModel->nameColumn();
// Clear highlight for previously highlighted items
foreach (vtkIdType highlightedItemID, d->HighlightedItems)
{
QStandardItem* item = sceneModel->itemFromSubjectHierarchyItem(highlightedItemID, nameColumn);
if (item)
{
item->setBackground(Qt::transparent);
}
}
d->HighlightedItems.clear();
// Go through all given items
foreach (vtkIdType itemID, itemIDs)
{
if (itemID == d->SubjectHierarchyNode->GetSceneItemID())
{
continue;
}
vtkMRMLNode* node = d->SubjectHierarchyNode->GetItemDataNode(itemID);
// Get items referenced recursively by argument node by MRML
vtkSmartPointer<vtkCollection> recursivelyReferencedNodes;
recursivelyReferencedNodes.TakeReference(scene->GetReferencedNodes(node));
// Get items referenced by argument node by DICOM
std::vector<vtkIdType> directlyReferencedItems = d->SubjectHierarchyNode->GetItemsReferencedFromItemByDICOM(itemID);
// Get items referenced directly by argument node by MRML
if (node)
{
vtkSmartPointer<vtkCollection> referencedNodes;
referencedNodes.TakeReference(scene->GetReferencedNodes(node, false));
for (int index=0; index!=referencedNodes->GetNumberOfItems(); ++index)
{
vtkIdType nodeItemID = d->SubjectHierarchyNode->GetItemByDataNode(
vtkMRMLNode::SafeDownCast(referencedNodes->GetItemAsObject(index)) );
if ( nodeItemID && nodeItemID != itemID
&& (std::find(directlyReferencedItems.begin(), directlyReferencedItems.end(), nodeItemID) == directlyReferencedItems.end()) )
{
directlyReferencedItems.push_back(nodeItemID);
}
}
}
// Get items referencing the argument node by DICOM
std::vector<vtkIdType> referencingItems = d->SubjectHierarchyNode->GetItemsReferencingItemByDICOM(itemID);
// Get items referencing the argument node by MRML
if (node)
{
std::vector<vtkMRMLNode*> referencingNodes;
scene->GetReferencingNodes(node, referencingNodes);
for (std::vector<vtkMRMLNode*>::iterator refNodeIt=referencingNodes.begin(); refNodeIt!=referencingNodes.end(); refNodeIt++)
{
vtkIdType nodeItemID = d->SubjectHierarchyNode->GetItemByDataNode(*refNodeIt);
if ( nodeItemID && nodeItemID != itemID
&& (std::find(referencingItems.begin(), referencingItems.end(), nodeItemID) == referencingItems.end()) )
{
referencingItems.push_back(nodeItemID);
}
}
}
// Highlight recursively referenced items
for (int index=0; index!=recursivelyReferencedNodes->GetNumberOfItems(); ++index)
{
vtkIdType referencedItem = d->SubjectHierarchyNode->GetItemByDataNode(
vtkMRMLNode::SafeDownCast(recursivelyReferencedNodes->GetItemAsObject(index)) );
if (referencedItem && referencedItem != itemID)
{
QStandardItem* item = sceneModel->itemFromSubjectHierarchyItem(referencedItem, nameColumn);
if (item && !d->HighlightedItems.contains(referencedItem))
{
item->setBackground(QColor::fromRgb(255, 255, 170));
d->HighlightedItems.append(referencedItem);
}
}
}
// Highlight directly referenced items
std::vector<vtkIdType>::iterator itemIt;
for (itemIt=directlyReferencedItems.begin(); itemIt!=directlyReferencedItems.end(); ++itemIt)
{
vtkIdType referencedItem = (*itemIt);
QStandardItem* item = sceneModel->itemFromSubjectHierarchyItem(referencedItem, nameColumn);
if (item) // Note: these items have been added as the recursively referenced items already
{
item->setBackground(Qt::yellow);
}
}
// Highlight referencing items
for (itemIt=referencingItems.begin(); itemIt!=referencingItems.end(); ++itemIt)
{
vtkIdType referencingItem = (*itemIt);
QStandardItem* item = sceneModel->itemFromSubjectHierarchyItem(referencingItem, nameColumn);
if (item && !d->HighlightedItems.contains(referencingItem))
{
item->setBackground(QColor::fromRgb(69, 204, 69));
d->HighlightedItems.append(referencingItem);
}
}
}
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setMultiSelection(bool multiSelectionOn)
{
if (multiSelectionOn)
{
this->setSelectionMode(QAbstractItemView::ExtendedSelection);
}
else
{
this->setSelectionMode(QAbstractItemView::SingleSelection);
}
}
//-----------------------------------------------------------------------------
bool qMRMLSubjectHierarchyTreeView::multiSelection()
{
return (this->selectionMode() == QAbstractItemView::ExtendedSelection);
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setPluginWhitelist(QStringList whitelist)
{
Q_D(qMRMLSubjectHierarchyTreeView);
d->PluginWhitelist = whitelist;
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::setPluginBlacklist(QStringList blacklist)
{
Q_D(qMRMLSubjectHierarchyTreeView);
d->PluginBlacklist = blacklist;
}
//--------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::disablePlugin(QString plugin)
{
Q_D(qMRMLSubjectHierarchyTreeView);
d->PluginBlacklist << plugin;
}
//-----------------------------------------------------------------------------
vtkIdType qMRMLSubjectHierarchyTreeView::firstSelectedSubjectHierarchyItemInBranch(vtkIdType itemID)
{
Q_D(qMRMLSubjectHierarchyTreeView);
// Check if item itself is selected
if (d->SelectedItems.contains(itemID))
{
return itemID;
}
// Look for selected item in children recursively
std::vector<vtkIdType> childItemIDs;
d->SubjectHierarchyNode->GetItemChildren(itemID, childItemIDs, true);
for (std::vector<vtkIdType>::iterator childIt=childItemIDs.begin(); childIt!=childItemIDs.end(); ++childIt)
{
vtkIdType selectedId = this->firstSelectedSubjectHierarchyItemInBranch(*childIt);
if (selectedId != vtkMRMLSubjectHierarchyNode::INVALID_ITEM_ID)
{
return selectedId;
}
}
// That item is not selected and does not have
// any children items selected
return vtkMRMLSubjectHierarchyNode::INVALID_ITEM_ID;
}
//-----------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::onSubjectHierarchyItemModified(vtkObject *caller, void *callData)
{
Q_D(qMRMLSubjectHierarchyTreeView);
vtkMRMLSubjectHierarchyNode* shNode = vtkMRMLSubjectHierarchyNode::SafeDownCast(caller);
if (!shNode)
{
qCritical() << Q_FUNC_INFO << ": Failed to access subject hierarchy node";
return;
}
// Get item ID
vtkIdType itemID = vtkMRMLSubjectHierarchyNode::INVALID_ITEM_ID;
if (callData)
{
vtkIdType* itemIdPtr = reinterpret_cast<vtkIdType*>(callData);
itemID = *itemIdPtr;
}
// Highlight items referenced by DICOM in case of single-selection
// Referenced SOP instance UIDs (in attribute named vtkMRMLSubjectHierarchyConstants::GetDICOMReferencedInstanceUIDsAttributeName())
// -> SH item instance UIDs (serialized string lists in subject hierarchy UID vtkMRMLSubjectHierarchyConstants::GetDICOMInstanceUIDName())
if (this->highlightReferencedItems() && d->SelectedItems.count() == 1)
{
this->applyReferenceHighlightForItems(d->SelectedItems);
}
// Forward `currentItemModified` if the modified item or one of
// its children was selected, to adequately update other widgets
// that use that modified item such as qMRMLSubjectHierarchyComboBox
vtkIdType selectedId = this->firstSelectedSubjectHierarchyItemInBranch(itemID);
if (selectedId != vtkMRMLSubjectHierarchyNode::INVALID_ITEM_ID)
{
emit currentItemModified(selectedId);
}
}
//-----------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::onMRMLSceneCloseEnded(vtkObject* sceneObject)
{
vtkMRMLScene* scene = vtkMRMLScene::SafeDownCast(sceneObject);
if (!scene)
{
return;
}
Q_D(qMRMLSubjectHierarchyTreeView);
// Remove selection
QList<vtkIdType> emptySelection;
this->setCurrentItems(emptySelection);
d->SelectedItems.clear();
d->HighlightedItems.clear();
// Get new subject hierarchy node (or if not created yet then trigger creating it, because
// scene close removed the pseudo-singleton subject hierarchy node), and set it to the tree view
this->setSubjectHierarchyNode(vtkMRMLSubjectHierarchyNode::ResolveSubjectHierarchy(scene));
}
//-----------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::onMRMLSceneStartBatchProcess(vtkObject* sceneObject)
{
vtkMRMLScene* scene = vtkMRMLScene::SafeDownCast(sceneObject);
if (!scene)
{
return;
}
Q_D(qMRMLSubjectHierarchyTreeView);
d->SelectedItemsToRestore = d->SelectedItems;
}
//-----------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::onMRMLSceneEndBatchProcess(vtkObject* sceneObject)
{
vtkMRMLScene* scene = vtkMRMLScene::SafeDownCast(sceneObject);
if (!scene)
{
return;
}
Q_D(qMRMLSubjectHierarchyTreeView);
this->setCurrentItems(d->SelectedItemsToRestore);
d->SelectedItemsToRestore.clear();
}
//------------------------------------------------------------------------------
bool qMRMLSubjectHierarchyTreeView::showContextMenuHint(bool visibility/*=false*/)
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->SubjectHierarchyNode)
{
qCritical() << Q_FUNC_INFO << ": Invalid subject hierarchy";
return false;
}
// Get current item
vtkIdType itemID = this->currentItem();
if (!itemID || !d->SubjectHierarchyNode->GetDisplayNodeForItem(itemID))
{
// If current item is not displayable, then find first displayable leaf item
itemID = vtkMRMLSubjectHierarchyNode::INVALID_ITEM_ID;
std::vector<vtkIdType> childItems;
d->SubjectHierarchyNode->GetItemChildren(d->SubjectHierarchyNode->GetSceneItemID(), childItems, true);
for (std::vector<vtkIdType>::iterator childIt=childItems.begin(); childIt!=childItems.end(); ++childIt)
{
std::vector<vtkIdType> currentChildItems;
d->SubjectHierarchyNode->GetItemChildren(*childIt, currentChildItems);
if ( (currentChildItems.empty() || d->SubjectHierarchyNode->IsItemVirtualBranchParent(*childIt)) // Leaf
&& ( d->SubjectHierarchyNode->GetDisplayNodeForItem(*childIt) // Displayable
|| vtkMRMLScalarVolumeNode::SafeDownCast(d->SubjectHierarchyNode->GetItemDataNode(*childIt)) ) ) // Volume
{
itemID = (*childIt);
break;
}
}
}
if (!itemID)
{
// No displayable item in subject hierarchy
return false;
}
// Create information icon
QIcon icon = QApplication::style()->standardIcon(QStyle::SP_MessageBoxInformation);
QPixmap pixmap = icon.pixmap(32,32);
QByteArray data;
QBuffer buffer(&data);
pixmap.save(&buffer, "PNG", 100);
QString iconHtml = QString("<img src='data:image/png;base64, %0'>").arg(QString(data.toBase64()));
if (!visibility)
{
// Get name cell position
QModelIndex nameIndex = this->sortFilterProxyModel()->indexFromSubjectHierarchyItem(
itemID, this->model()->nameColumn() );
QRect nameRect = this->visualRect(nameIndex);
// Show name tooltip
QString nameTooltip = QString(
"<div align=\"left\" style=\"font-size:10pt;\"><!--↑<br/>-->Right-click an item<br/>to access additional<br/>options</div><br/>")
+ iconHtml;
QToolTip::showText(
this->mapToGlobal( QPoint( nameRect.x() + nameRect.width()/6, nameRect.y() + nameRect.height() ) ),
nameTooltip );
}
else
{
// Get visibility cell position
QModelIndex visibilityIndex = this->sortFilterProxyModel()->indexFromSubjectHierarchyItem(
itemID, this->model()->visibilityColumn() );
QRect visibilityRect = this->visualRect(visibilityIndex);
// Show visibility tooltip
QString visibilityTooltip = QString(
"<div align=\"left\" style=\"font-size:10pt;\"><!--↑<br/>-->Right-click the visibility<br/>"
"button of an item to<br/>access additional<br/>visibility options</div><br/>")
+ iconHtml;
QToolTip::showText( this->mapToGlobal( QPoint( visibilityRect.x() + visibilityRect.width()/2, visibilityRect.y() + visibilityRect.height() ) ),
visibilityTooltip );
}
return true;
}
//------------------------------------------------------------------------------
void qMRMLSubjectHierarchyTreeView::onCustomContextMenu(const QPoint& point)
{
Q_D(qMRMLSubjectHierarchyTreeView);
if (!d->ContextMenuEnabled)
{
// Context menu not enabled, ignore the event
return;
}
QPoint globalPoint = this->viewport()->mapToGlobal(point);
// Custom right button actions for item decorations (i.e. icon): visibility context menu
QModelIndex index = this->indexAt(point);
QStyleOptionViewItem opt = this->viewOptions();
opt.rect = this->visualRect(index);
qobject_cast<qMRMLItemDelegate*>(this->itemDelegate())->initStyleOption(&opt, index);
QRect decorationElement = this->style()->subElementRect(QStyle::SE_ItemViewItemDecoration, &opt, this);
if (decorationElement.contains(point))
{
// Mouse event is within an item decoration
QModelIndex sourceIndex = this->sortFilterProxyModel()->mapToSource(index);
if (sourceIndex.flags() & Qt::ItemIsEnabled)
{
// Item is enabled
if (sourceIndex.column() == this->model()->visibilityColumn()
|| sourceIndex.column() == this->model()->colorColumn())
{
vtkIdType itemID = d->SortFilterModel->subjectHierarchyItemFromIndex(index);
if (itemID) // Valid item is needed for visibility actions
{
// If multiple items are selected then show the node menu instead of the visibility menu
if (d->SelectedItems.size() > 1)
{
this->populateContextMenuForItem(itemID);
d->NodeMenu->exec(globalPoint);
}
else
{
// Populate then show visibility context menu if only one item is selected
this->populateVisibilityContextMenuForItem(itemID);
d->VisibilityMenu->exec(globalPoint);
}
return;
}
}
}
}
// Get subject hierarchy item at mouse click position
vtkIdType itemID = this->sortFilterProxyModel()->subjectHierarchyItemFromIndex(index);
// Populate context menu for the current item
this->populateContextMenuForItem(itemID);
// Show context menu
if (!itemID || itemID == d->SubjectHierarchyNode->GetSceneItemID())
{
d->SceneMenu->exec(globalPoint);
}
else
{
d->NodeMenu->exec(globalPoint);
}
}
| 35.88
| 147
| 0.656306
|
forfullstack
|
9a2384ae83b1d714ddd87a6d08e4748e933a5918
| 20,891
|
cc
|
C++
|
FreeBSD/cddl/usr.sbin/zfsd/tests/zfsd_unittest.cc
|
TigerBSD/FreeBSD-Custom-ThinkPad
|
3d092f261b362f73170871403397fc5d6b89d1dc
|
[
"0BSD"
] | 4
|
2016-08-22T22:02:55.000Z
|
2017-03-04T22:56:44.000Z
|
FreeBSD/cddl/usr.sbin/zfsd/tests/zfsd_unittest.cc
|
TigerBSD/FreeBSD-Custom-ThinkPad
|
3d092f261b362f73170871403397fc5d6b89d1dc
|
[
"0BSD"
] | 21
|
2016-08-11T09:43:43.000Z
|
2017-01-29T12:52:56.000Z
|
FreeBSD/cddl/usr.sbin/zfsd/tests/zfsd_unittest.cc
|
TigerBSD/TigerBSD
|
3d092f261b362f73170871403397fc5d6b89d1dc
|
[
"0BSD"
] | null | null | null |
/*-
* Copyright (c) 2012, 2013, 2014 Spectra Logic Corporation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
*
* NO WARRANTY
* 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 MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR 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 DAMAGES.
*
* Authors: Alan Somers (Spectra Logic Corporation)
*/
#include <sys/cdefs.h>
#include <stdarg.h>
#include <syslog.h>
#include <libnvpair.h>
#include <libzfs.h>
#include <list>
#include <map>
#include <sstream>
#include <string>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <devdctl/guid.h>
#include <devdctl/event.h>
#include <devdctl/event_factory.h>
#include <devdctl/exception.h>
#include <devdctl/consumer.h>
#include <zfsd/callout.h>
#include <zfsd/vdev_iterator.h>
#include <zfsd/zfsd_event.h>
#include <zfsd/case_file.h>
#include <zfsd/vdev.h>
#include <zfsd/zfsd.h>
#include <zfsd/zfsd_exception.h>
#include <zfsd/zpool_list.h>
#include "libmocks.h"
__FBSDID("$FreeBSD$");
/*================================== Macros ==================================*/
#define NUM_ELEMENTS(x) (sizeof(x) / sizeof(*x))
/*============================ Namespace Control =============================*/
using std::string;
using std::stringstream;
using DevdCtl::Event;
using DevdCtl::EventBuffer;
using DevdCtl::EventFactory;
using DevdCtl::EventList;
using DevdCtl::Guid;
using DevdCtl::NVPairMap;
/* redefine zpool_handle here because libzfs_impl.h is not includable */
struct zpool_handle
{
libzfs_handle_t *zpool_hdl;
zpool_handle_t *zpool_next;
char zpool_name[ZPOOL_MAXNAMELEN];
int zpool_state;
size_t zpool_config_size;
nvlist_t *zpool_config;
nvlist_t *zpool_old_config;
nvlist_t *zpool_props;
diskaddr_t zpool_start_block;
};
class MockZfsEvent : public ZfsEvent
{
public:
MockZfsEvent(Event::Type, NVPairMap&, const string&);
virtual ~MockZfsEvent() {}
static BuildMethod MockZfsEventBuilder;
MOCK_CONST_METHOD0(ProcessPoolEvent, void());
static EventFactory::Record s_buildRecords[];
};
EventFactory::Record MockZfsEvent::s_buildRecords[] =
{
{ Event::NOTIFY, "ZFS", &MockZfsEvent::MockZfsEventBuilder }
};
MockZfsEvent::MockZfsEvent(Event::Type type, NVPairMap& map,
const string& str)
: ZfsEvent(type, map, str)
{
}
Event *
MockZfsEvent::MockZfsEventBuilder(Event::Type type,
NVPairMap &nvpairs,
const string &eventString)
{
return (new MockZfsEvent(type, nvpairs, eventString));
}
/*
* A dummy Vdev class used for testing other classes
*/
class MockVdev : public Vdev
{
public:
MockVdev(nvlist_t *vdevConfig);
virtual ~MockVdev() {}
MOCK_CONST_METHOD0(GUID, Guid());
MOCK_CONST_METHOD0(PoolGUID, Guid());
MOCK_CONST_METHOD0(State, vdev_state());
MOCK_CONST_METHOD0(PhysicalPath, string());
};
MockVdev::MockVdev(nvlist_t *vdevConfig)
: Vdev(vdevConfig)
{
}
/*
* A CaseFile class with side effects removed, for testing
*/
class TestableCaseFile : public CaseFile
{
public:
static TestableCaseFile &Create(Vdev &vdev);
TestableCaseFile(Vdev &vdev);
virtual ~TestableCaseFile() {}
MOCK_METHOD0(Close, void());
MOCK_METHOD1(RegisterCallout, void(const Event &event));
MOCK_METHOD0(RefreshVdevState, bool());
MOCK_METHOD1(ReEvaluate, bool(const ZfsEvent &event));
bool RealReEvaluate(const ZfsEvent &event)
{
return (CaseFile::ReEvaluate(event));
}
/*
* This splices the event lists, a procedure that would normally be done
* by OnGracePeriodEnded, but we don't necessarily call that in the
* unit tests
*/
void SpliceEvents();
/*
* Used by some of our expectations. CaseFile does not publicize this
*/
static int getActiveCases()
{
return (s_activeCases.size());
}
};
TestableCaseFile::TestableCaseFile(Vdev &vdev)
: CaseFile(vdev)
{
}
TestableCaseFile &
TestableCaseFile::Create(Vdev &vdev)
{
TestableCaseFile *newCase;
newCase = new TestableCaseFile(vdev);
return (*newCase);
}
void
TestableCaseFile::SpliceEvents()
{
m_events.splice(m_events.begin(), m_tentativeEvents);
}
/*
* Test class ZfsdException
*/
class ZfsdExceptionTest : public ::testing::Test
{
protected:
virtual void SetUp()
{
ASSERT_EQ(0, nvlist_alloc(&poolConfig, NV_UNIQUE_NAME, 0));
ASSERT_EQ(0, nvlist_add_string(poolConfig,
ZPOOL_CONFIG_POOL_NAME, "unit_test_pool"));
ASSERT_EQ(0, nvlist_add_uint64(poolConfig,
ZPOOL_CONFIG_POOL_GUID, 0x1234));
ASSERT_EQ(0, nvlist_alloc(&vdevConfig, NV_UNIQUE_NAME, 0));
ASSERT_EQ(0, nvlist_add_uint64(vdevConfig,
ZPOOL_CONFIG_GUID, 0x5678));
bzero(&poolHandle, sizeof(poolHandle));
poolHandle.zpool_config = poolConfig;
}
virtual void TearDown()
{
nvlist_free(poolConfig);
nvlist_free(vdevConfig);
}
nvlist_t *poolConfig;
nvlist_t *vdevConfig;
zpool_handle_t poolHandle;
};
TEST_F(ZfsdExceptionTest, StringConstructorNull)
{
ZfsdException ze("");
EXPECT_STREQ("", ze.GetString().c_str());
}
TEST_F(ZfsdExceptionTest, StringConstructorFormatted)
{
ZfsdException ze(" %d %s", 55, "hello world");
EXPECT_STREQ(" 55 hello world", ze.GetString().c_str());
}
TEST_F(ZfsdExceptionTest, LogSimple)
{
ZfsdException ze("unit test w/o vdev or pool");
ze.Log();
EXPECT_EQ(LOG_ERR, syslog_last_priority);
EXPECT_STREQ("unit test w/o vdev or pool\n", syslog_last_message);
}
TEST_F(ZfsdExceptionTest, Pool)
{
const char msg[] = "Exception with pool name";
char expected[4096];
sprintf(expected, "Pool unit_test_pool: %s\n", msg);
ZfsdException ze(poolConfig, msg);
ze.Log();
EXPECT_STREQ(expected, syslog_last_message);
}
TEST_F(ZfsdExceptionTest, PoolHandle)
{
const char msg[] = "Exception with pool handle";
char expected[4096];
sprintf(expected, "Pool unit_test_pool: %s\n", msg);
ZfsdException ze(&poolHandle, msg);
ze.Log();
EXPECT_STREQ(expected, syslog_last_message);
}
/*
* Test class Vdev
*/
class VdevTest : public ::testing::Test
{
protected:
virtual void SetUp()
{
ASSERT_EQ(0, nvlist_alloc(&m_poolConfig, NV_UNIQUE_NAME, 0));
ASSERT_EQ(0, nvlist_add_uint64(m_poolConfig,
ZPOOL_CONFIG_POOL_GUID,
0x1234));
ASSERT_EQ(0, nvlist_alloc(&m_vdevConfig, NV_UNIQUE_NAME, 0));
ASSERT_EQ(0, nvlist_add_uint64(m_vdevConfig, ZPOOL_CONFIG_GUID,
0x5678));
}
virtual void TearDown()
{
nvlist_free(m_poolConfig);
nvlist_free(m_vdevConfig);
}
nvlist_t *m_poolConfig;
nvlist_t *m_vdevConfig;
};
TEST_F(VdevTest, StateFromConfig)
{
vdev_stat_t vs;
vs.vs_state = VDEV_STATE_OFFLINE;
ASSERT_EQ(0, nvlist_add_uint64_array(m_vdevConfig,
ZPOOL_CONFIG_VDEV_STATS,
(uint64_t*)&vs,
sizeof(vs) / sizeof(uint64_t)));
Vdev vdev(m_poolConfig, m_vdevConfig);
EXPECT_EQ(VDEV_STATE_OFFLINE, vdev.State());
}
TEST_F(VdevTest, StateFaulted)
{
ASSERT_EQ(0, nvlist_add_uint64(m_vdevConfig, ZPOOL_CONFIG_FAULTED, 1));
Vdev vdev(m_poolConfig, m_vdevConfig);
EXPECT_EQ(VDEV_STATE_FAULTED, vdev.State());
}
/*
* Test that we can construct a Vdev from the label information that is stored
* on an available spare drive
*/
TEST_F(VdevTest, ConstructAvailSpare)
{
nvlist_t *labelConfig;
ASSERT_EQ(0, nvlist_alloc(&labelConfig, NV_UNIQUE_NAME, 0));
ASSERT_EQ(0, nvlist_add_uint64(labelConfig, ZPOOL_CONFIG_GUID,
1948339428197961030));
ASSERT_EQ(0, nvlist_add_uint64(labelConfig, ZPOOL_CONFIG_POOL_STATE,
POOL_STATE_SPARE));
EXPECT_NO_THROW(Vdev vdev(labelConfig));
nvlist_free(labelConfig);
}
/* Available spares will always show the HEALTHY state */
TEST_F(VdevTest, AvailSpareState) {
nvlist_t *labelConfig;
ASSERT_EQ(0, nvlist_alloc(&labelConfig, NV_UNIQUE_NAME, 0));
ASSERT_EQ(0, nvlist_add_uint64(labelConfig, ZPOOL_CONFIG_GUID,
1948339428197961030));
ASSERT_EQ(0, nvlist_add_uint64(labelConfig, ZPOOL_CONFIG_POOL_STATE,
POOL_STATE_SPARE));
Vdev vdev(labelConfig);
EXPECT_EQ(VDEV_STATE_HEALTHY, vdev.State());
nvlist_free(labelConfig);
}
/* Test the Vdev::IsSpare method */
TEST_F(VdevTest, IsSpare) {
Vdev notSpare(m_poolConfig, m_vdevConfig);
EXPECT_EQ(false, notSpare.IsSpare());
ASSERT_EQ(0, nvlist_add_uint64(m_vdevConfig, ZPOOL_CONFIG_IS_SPARE, 1));
Vdev isSpare(m_poolConfig, m_vdevConfig);
EXPECT_EQ(true, isSpare.IsSpare());
}
/*
* Test class ZFSEvent
*/
class ZfsEventTest : public ::testing::Test
{
protected:
virtual void SetUp()
{
m_eventFactory = new EventFactory();
m_eventFactory->UpdateRegistry(MockZfsEvent::s_buildRecords,
NUM_ELEMENTS(MockZfsEvent::s_buildRecords));
m_event = NULL;
}
virtual void TearDown()
{
delete m_eventFactory;
delete m_event;
}
EventFactory *m_eventFactory;
Event *m_event;
};
TEST_F(ZfsEventTest, ProcessPoolEventGetsCalled)
{
string evString("!system=ZFS "
"subsystem=ZFS "
"type=misc.fs.zfs.vdev_remove "
"pool_name=foo "
"pool_guid=9756779504028057996 "
"vdev_guid=1631193447431603339 "
"vdev_path=/dev/da1 "
"timestamp=1348871594");
m_event = Event::CreateEvent(*m_eventFactory, evString);
MockZfsEvent *mock_event = static_cast<MockZfsEvent*>(m_event);
EXPECT_CALL(*mock_event, ProcessPoolEvent()).Times(1);
mock_event->Process();
}
/*
* Test class CaseFile
*/
class CaseFileTest : public ::testing::Test
{
protected:
virtual void SetUp()
{
m_eventFactory = new EventFactory();
m_eventFactory->UpdateRegistry(MockZfsEvent::s_buildRecords,
NUM_ELEMENTS(MockZfsEvent::s_buildRecords));
m_event = NULL;
nvlist_alloc(&m_vdevConfig, NV_UNIQUE_NAME, 0);
ASSERT_EQ(0, nvlist_add_uint64(m_vdevConfig,
ZPOOL_CONFIG_GUID, 0xbeef));
m_vdev = new MockVdev(m_vdevConfig);
ON_CALL(*m_vdev, GUID())
.WillByDefault(::testing::Return(Guid(123)));
ON_CALL(*m_vdev, PoolGUID())
.WillByDefault(::testing::Return(Guid(456)));
ON_CALL(*m_vdev, State())
.WillByDefault(::testing::Return(VDEV_STATE_HEALTHY));
m_caseFile = &TestableCaseFile::Create(*m_vdev);
ON_CALL(*m_caseFile, ReEvaluate(::testing::_))
.WillByDefault(::testing::Invoke(m_caseFile, &TestableCaseFile::RealReEvaluate));
return;
}
virtual void TearDown()
{
delete m_caseFile;
nvlist_free(m_vdevConfig);
delete m_vdev;
delete m_event;
delete m_eventFactory;
}
nvlist_t *m_vdevConfig;
MockVdev *m_vdev;
TestableCaseFile *m_caseFile;
Event *m_event;
EventFactory *m_eventFactory;
};
/*
* A Vdev with no events should not be degraded or faulted
*/
TEST_F(CaseFileTest, HealthyVdev)
{
EXPECT_FALSE(m_caseFile->ShouldDegrade());
EXPECT_FALSE(m_caseFile->ShouldFault());
}
/*
* A Vdev with only one event should not be degraded or faulted
* For performance reasons, RefreshVdevState should not be called.
*/
TEST_F(CaseFileTest, HealthyishVdev)
{
string evString("!system=ZFS "
"class=ereport.fs.zfs.io "
"ena=12091638756982918145 "
"parent_guid=13237004955564865395 "
"parent_type=raidz "
"pool=testpool.4415 "
"pool_context=0 "
"pool_failmode=wait "
"pool_guid=456 "
"subsystem=ZFS "
"timestamp=1348867914 "
"type=ereport.fs.zfs.io "
"vdev_guid=123 "
"vdev_path=/dev/da400 "
"vdev_type=disk "
"zio_blkid=622 "
"zio_err=1 "
"zio_level=-2 "
"zio_object=0 "
"zio_objset=37 "
"zio_offset=25598976 "
"zio_size=1024");
m_event = Event::CreateEvent(*m_eventFactory, evString);
ZfsEvent *zfs_event = static_cast<ZfsEvent*>(m_event);
EXPECT_CALL(*m_caseFile, RefreshVdevState())
.Times(::testing::Exactly(0));
EXPECT_TRUE(m_caseFile->ReEvaluate(*zfs_event));
EXPECT_FALSE(m_caseFile->ShouldDegrade());
EXPECT_FALSE(m_caseFile->ShouldFault());
}
/* The case file should be closed when its pool is destroyed */
TEST_F(CaseFileTest, PoolDestroy)
{
string evString("!system=ZFS "
"pool_name=testpool.4415 "
"pool_guid=456 "
"subsystem=ZFS "
"timestamp=1348867914 "
"type=misc.fs.zfs.pool_destroy ");
m_event = Event::CreateEvent(*m_eventFactory, evString);
ZfsEvent *zfs_event = static_cast<ZfsEvent*>(m_event);
EXPECT_CALL(*m_caseFile, Close());
EXPECT_TRUE(m_caseFile->ReEvaluate(*zfs_event));
}
/*
* A Vdev with a very large number of IO errors should fault
* For performance reasons, RefreshVdevState should be called at most once
*/
TEST_F(CaseFileTest, VeryManyIOErrors)
{
EXPECT_CALL(*m_caseFile, RefreshVdevState())
.Times(::testing::AtMost(1))
.WillRepeatedly(::testing::Return(true));
for(int i=0; i<100; i++) {
stringstream evStringStream;
evStringStream <<
"!system=ZFS "
"class=ereport.fs.zfs.io "
"ena=12091638756982918145 "
"parent_guid=13237004955564865395 "
"parent_type=raidz "
"pool=testpool.4415 "
"pool_context=0 "
"pool_failmode=wait "
"pool_guid=456 "
"subsystem=ZFS "
"timestamp=";
evStringStream << i << " ";
evStringStream <<
"type=ereport.fs.zfs.io "
"vdev_guid=123 "
"vdev_path=/dev/da400 "
"vdev_type=disk "
"zio_blkid=622 "
"zio_err=1 "
"zio_level=-2 "
"zio_object=0 "
"zio_objset=37 "
"zio_offset=25598976 "
"zio_size=1024";
Event *event(Event::CreateEvent(*m_eventFactory,
evStringStream.str()));
ZfsEvent *zfs_event = static_cast<ZfsEvent*>(event);
EXPECT_TRUE(m_caseFile->ReEvaluate(*zfs_event));
delete event;
}
m_caseFile->SpliceEvents();
EXPECT_FALSE(m_caseFile->ShouldDegrade());
EXPECT_TRUE(m_caseFile->ShouldFault());
}
/*
* A Vdev with a very large number of checksum errors should degrade
* For performance reasons, RefreshVdevState should be called at most once
*/
TEST_F(CaseFileTest, VeryManyChecksumErrors)
{
EXPECT_CALL(*m_caseFile, RefreshVdevState())
.Times(::testing::AtMost(1))
.WillRepeatedly(::testing::Return(true));
for(int i=0; i<100; i++) {
stringstream evStringStream;
evStringStream <<
"!system=ZFS "
"bad_cleared_bits=03000000000000803f50b00000000000 "
"bad_range_clears=0000000e "
"bad_range_sets=00000000 "
"bad_ranges=0000000000000010 "
"bad_ranges_min_gap=8 "
"bad_set_bits=00000000000000000000000000000000 "
"class=ereport.fs.zfs.checksum "
"ena=12272856582652437505 "
"parent_guid=5838204195352909894 "
"parent_type=raidz pool=testpool.7640 "
"pool_context=0 "
"pool_failmode=wait "
"pool_guid=456 "
"subsystem=ZFS timestamp=";
evStringStream << i << " ";
evStringStream <<
"type=ereport.fs.zfs.checksum "
"vdev_guid=123 "
"vdev_path=/mnt/tmp/file1.7702 "
"vdev_type=file "
"zio_blkid=0 "
"zio_err=0 "
"zio_level=0 "
"zio_object=3 "
"zio_objset=0 "
"zio_offset=16896 "
"zio_size=512";
Event *event(Event::CreateEvent(*m_eventFactory,
evStringStream.str()));
ZfsEvent *zfs_event = static_cast<ZfsEvent*>(event);
EXPECT_TRUE(m_caseFile->ReEvaluate(*zfs_event));
delete event;
}
m_caseFile->SpliceEvents();
EXPECT_TRUE(m_caseFile->ShouldDegrade());
EXPECT_FALSE(m_caseFile->ShouldFault());
}
/*
* Test CaseFile::ReEvaluateByGuid
*/
class ReEvaluateByGuidTest : public ::testing::Test
{
protected:
virtual void SetUp()
{
m_eventFactory = new EventFactory();
m_eventFactory->UpdateRegistry(MockZfsEvent::s_buildRecords,
NUM_ELEMENTS(MockZfsEvent::s_buildRecords));
m_event = Event::CreateEvent(*m_eventFactory, s_evString);
nvlist_alloc(&m_vdevConfig, NV_UNIQUE_NAME, 0);
ASSERT_EQ(0, nvlist_add_uint64(m_vdevConfig,
ZPOOL_CONFIG_GUID, 0xbeef));
m_vdev456 = new ::testing::NiceMock<MockVdev>(m_vdevConfig);
m_vdev789 = new ::testing::NiceMock<MockVdev>(m_vdevConfig);
ON_CALL(*m_vdev456, GUID())
.WillByDefault(::testing::Return(Guid(123)));
ON_CALL(*m_vdev456, PoolGUID())
.WillByDefault(::testing::Return(Guid(456)));
ON_CALL(*m_vdev456, State())
.WillByDefault(::testing::Return(VDEV_STATE_HEALTHY));
ON_CALL(*m_vdev789, GUID())
.WillByDefault(::testing::Return(Guid(123)));
ON_CALL(*m_vdev789, PoolGUID())
.WillByDefault(::testing::Return(Guid(789)));
ON_CALL(*m_vdev789, State())
.WillByDefault(::testing::Return(VDEV_STATE_HEALTHY));
m_caseFile456 = NULL;
m_caseFile789 = NULL;
return;
}
virtual void TearDown()
{
delete m_caseFile456;
delete m_caseFile789;
nvlist_free(m_vdevConfig);
delete m_vdev456;
delete m_vdev789;
delete m_event;
delete m_eventFactory;
}
static string s_evString;
nvlist_t *m_vdevConfig;
::testing::NiceMock<MockVdev> *m_vdev456;
::testing::NiceMock<MockVdev> *m_vdev789;
TestableCaseFile *m_caseFile456;
TestableCaseFile *m_caseFile789;
Event *m_event;
EventFactory *m_eventFactory;
};
string ReEvaluateByGuidTest::s_evString(
"!system=ZFS "
"pool_guid=16271873792808333580 "
"pool_name=foo "
"subsystem=ZFS "
"timestamp=1360620391 "
"type=misc.fs.zfs.config_sync");
/*
* Test the ReEvaluateByGuid method on an empty list of casefiles.
* We must create one event, even though it never gets used, because it will
* be passed by reference to ReEvaluateByGuid
*/
TEST_F(ReEvaluateByGuidTest, ReEvaluateByGuid_empty)
{
ZfsEvent *zfs_event = static_cast<ZfsEvent*>(m_event);
EXPECT_EQ(0, TestableCaseFile::getActiveCases());
CaseFile::ReEvaluateByGuid(Guid(456), *zfs_event);
EXPECT_EQ(0, TestableCaseFile::getActiveCases());
}
/*
* Test the ReEvaluateByGuid method on a list of CaseFiles that contains only
* one CaseFile, which doesn't match the criteria
*/
TEST_F(ReEvaluateByGuidTest, ReEvaluateByGuid_oneFalse)
{
m_caseFile456 = &TestableCaseFile::Create(*m_vdev456);
ZfsEvent *zfs_event = static_cast<ZfsEvent*>(m_event);
EXPECT_EQ(1, TestableCaseFile::getActiveCases());
EXPECT_CALL(*m_caseFile456, ReEvaluate(::testing::_))
.Times(::testing::Exactly(0));
CaseFile::ReEvaluateByGuid(Guid(789), *zfs_event);
EXPECT_EQ(1, TestableCaseFile::getActiveCases());
}
/*
* Test the ReEvaluateByGuid method on a list of CaseFiles that contains only
* one CaseFile, which does match the criteria
*/
TEST_F(ReEvaluateByGuidTest, ReEvaluateByGuid_oneTrue)
{
m_caseFile456 = &TestableCaseFile::Create(*m_vdev456);
ZfsEvent *zfs_event = static_cast<ZfsEvent*>(m_event);
EXPECT_EQ(1, TestableCaseFile::getActiveCases());
EXPECT_CALL(*m_caseFile456, ReEvaluate(::testing::_))
.Times(::testing::Exactly(1))
.WillRepeatedly(::testing::Return(false));
CaseFile::ReEvaluateByGuid(Guid(456), *zfs_event);
EXPECT_EQ(1, TestableCaseFile::getActiveCases());
}
/*
* Test the ReEvaluateByGuid method on a long list of CaseFiles that contains a
* few cases which meet the criteria
*/
TEST_F(ReEvaluateByGuidTest, ReEvaluateByGuid_five)
{
TestableCaseFile *CaseFile1 = &TestableCaseFile::Create(*m_vdev456);
TestableCaseFile *CaseFile2 = &TestableCaseFile::Create(*m_vdev789);
TestableCaseFile *CaseFile3 = &TestableCaseFile::Create(*m_vdev456);
TestableCaseFile *CaseFile4 = &TestableCaseFile::Create(*m_vdev789);
TestableCaseFile *CaseFile5 = &TestableCaseFile::Create(*m_vdev789);
ZfsEvent *zfs_event = static_cast<ZfsEvent*>(m_event);
EXPECT_EQ(5, TestableCaseFile::getActiveCases());
EXPECT_CALL(*CaseFile1, ReEvaluate(::testing::_))
.Times(::testing::Exactly(1))
.WillRepeatedly(::testing::Return(false));
EXPECT_CALL(*CaseFile3, ReEvaluate(::testing::_))
.Times(::testing::Exactly(1))
.WillRepeatedly(::testing::Return(false));
EXPECT_CALL(*CaseFile2, ReEvaluate(::testing::_))
.Times(::testing::Exactly(0));
EXPECT_CALL(*CaseFile4, ReEvaluate(::testing::_))
.Times(::testing::Exactly(0));
EXPECT_CALL(*CaseFile5, ReEvaluate(::testing::_))
.Times(::testing::Exactly(0));
CaseFile::ReEvaluateByGuid(Guid(456), *zfs_event);
EXPECT_EQ(5, TestableCaseFile::getActiveCases());
delete CaseFile1;
delete CaseFile2;
delete CaseFile3;
delete CaseFile4;
delete CaseFile5;
}
| 27.060881
| 87
| 0.724475
|
TigerBSD
|
9a2386687d9ee5240b21cf272e063af465e06284
| 1,097
|
cpp
|
C++
|
ConsoleGameEngine/KeyEvents.cpp
|
sirjavlux/ConsoleGameEngine
|
04ece4053d7ad4566aef356fdb6e76233e8dd714
|
[
"MIT"
] | 3
|
2021-01-03T12:44:08.000Z
|
2021-01-08T14:02:50.000Z
|
ConsoleGameEngine/KeyEvents.cpp
|
sirjavlux/ConsoleGameEngine
|
04ece4053d7ad4566aef356fdb6e76233e8dd714
|
[
"MIT"
] | null | null | null |
ConsoleGameEngine/KeyEvents.cpp
|
sirjavlux/ConsoleGameEngine
|
04ece4053d7ad4566aef356fdb6e76233e8dd714
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include "SEngine.h"
using namespace std;
void keyAUpdateEvent(KeyState state, SEngine* engine) {
if (state == KeyState::down) {
if (engine->hasCameraObjectAttatched()) {
GameObject* obj = engine->getCameraFollowObject();
Vector2D vel(-1, 0);
obj->addForce(vel);
}
}
}
void keyWUpdateEvent(KeyState state, SEngine* engine) {
if (state == KeyState::down) {
if (engine->hasCameraObjectAttatched()) {
GameObject* obj = engine->getCameraFollowObject();
Vector2D vel(0, 1);
obj->addForce(vel);
}
}
}
void keySUpdateEvent(KeyState state, SEngine* engine) {
if (state == KeyState::down) {
if (engine->hasCameraObjectAttatched()) {
GameObject* obj = engine->getCameraFollowObject();
Vector2D vel(0, -1);
obj->addForce(vel);
}
}
}
void keyDUpdateEvent(KeyState state, SEngine* engine) {
if (state == KeyState::down) {
if (engine->hasCameraObjectAttatched()) {
GameObject* obj = engine->getCameraFollowObject();
Vector2D vel(1, 0);
obj->addForce(vel);
}
}
}
void keySPACEUpdateEvent(KeyState state, SEngine* engine) {
}
| 22.387755
| 59
| 0.68186
|
sirjavlux
|
9a25fd85c68799a05aab142cdb513e6773fda2da
| 10,852
|
hpp
|
C++
|
src/compiler/lib/Solution.hpp
|
gperrotta/yask
|
a35aa5a6f52bb5a11c182045c469a55a84fa9b36
|
[
"MIT"
] | null | null | null |
src/compiler/lib/Solution.hpp
|
gperrotta/yask
|
a35aa5a6f52bb5a11c182045c469a55a84fa9b36
|
[
"MIT"
] | null | null | null |
src/compiler/lib/Solution.hpp
|
gperrotta/yask
|
a35aa5a6f52bb5a11c182045c469a55a84fa9b36
|
[
"MIT"
] | null | null | null |
/*****************************************************************************
YASK: Yet Another Stencil Kit
Copyright (c) 2014-2019, 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.
*****************************************************************************/
// Base class for defining stencil equations.
#pragma once
// Generation code.
#include "ExprUtils.hpp"
#include "Settings.hpp"
#include "Eqs.hpp"
using namespace std;
namespace yask {
class PrinterBase;
// A base class for whole stencil solutions. This is used by solutions
// defined in C++ that are inherited from StencilBase as well as those
// defined via the stencil-compiler API.
class StencilSolution :
public virtual yc_solution {
protected:
// Simple name for the stencil soln. Must be a legal C++ var name.
string _name;
// Longer descriptive string.
string _long_name;
// Debug output.
yask_output_ptr _debug_output;
ostream* _dos = &std::cout; // just a handy pointer to an ostream.
// All vars accessible by the kernel.
Vars _vars;
// All equations defined in this solution.
Eqs _eqs;
// Settings for the solution.
CompilerSettings _settings;
// Code extensions.
vector<string> _kernel_code;
vector<output_hook_t> _output_hooks;
private:
// Intermediate data needed to format output.
Dimensions _dims; // various dimensions.
PrinterBase* _printer = 0;
EqBundles* _eqBundles = 0; // eq-bundles for scalar and vector.
EqBundlePacks* _eqBundlePacks = 0; // packs of bundles w/o inter-dependencies.
EqBundles* _clusterEqBundles = 0; // eq-bundles for scalar and vector.
// Create the intermediate data.
void analyze_solution(int vlen,
bool is_folding_efficient);
// Free allocated objs.
void _free(bool free_printer);
public:
StencilSolution(const string& name) :
_name(name) {
yask_output_factory ofac;
auto so = ofac.new_stdout_output();
set_debug_output(so);
}
virtual ~StencilSolution() { _free(true); }
// Identification.
virtual const string& getName() const { return _name; }
virtual const string& getLongName() const {
return _long_name.length() ? _long_name : _name;
}
// Simple accessors.
virtual Vars& getVars() { return _vars; }
virtual Eqs& getEqs() { return _eqs; }
virtual CompilerSettings& getSettings() { return _settings; }
virtual void setSettings(const CompilerSettings& settings) {
_settings = settings;
}
virtual const Dimensions& getDims() { return _dims; }
virtual const vector<string>& getKernelCode() { return _kernel_code; }
// Get the messsage output stream.
virtual std::ostream& get_ostr() const {
assert(_dos);
return *_dos;
}
// Make a new var.
virtual yc_var_ptr newVar(const std::string& name,
bool isScratch,
const std::vector<yc_index_node_ptr>& dims);
// stencil_solution APIs.
// See yask_stencil_api.hpp for documentation.
virtual void set_debug_output(yask_output_ptr debug) override {
_debug_output = debug; // to share ownership of referent.
_dos = &_debug_output->get_ostream();
}
virtual yask_output_ptr get_debug_output() const {
return _debug_output;
}
virtual void set_name(std::string name) override {
_name = name;
}
virtual void set_description(std::string str) override {
_long_name = str;
}
virtual std::string get_name() const override {
return _name;
}
virtual std::string get_description() const override {
return getLongName();
}
virtual yc_var_ptr new_var(const std::string& name,
const std::vector<yc_index_node_ptr>& dims) override {
return newVar(name, false, dims);
}
virtual yc_var_ptr new_var(const std::string& name,
const std::initializer_list<yc_index_node_ptr>& dims) override {
std::vector<yc_index_node_ptr> dim_vec(dims);
return newVar(name, false, dim_vec);
}
virtual yc_var_ptr new_scratch_var(const std::string& name,
const std::vector<yc_index_node_ptr>& dims) override {
return newVar(name, true, dims);
}
virtual yc_var_ptr new_scratch_var(const std::string& name,
const std::initializer_list<yc_index_node_ptr>& dims) override {
std::vector<yc_index_node_ptr> dim_vec(dims);
return newVar(name, true, dim_vec);
}
virtual int get_num_vars() const override {
return int(_vars.size());
}
virtual yc_var_ptr get_var(const std::string& name) override {
for (int i = 0; i < get_num_vars(); i++)
if (_vars.at(i)->getName() == name)
return _vars.at(i);
return nullptr;
}
virtual std::vector<yc_var_ptr> get_vars() override {
std::vector<yc_var_ptr> gv;
for (int i = 0; i < get_num_vars(); i++)
gv.push_back(_vars.at(i));
return gv;
}
virtual int get_num_equations() const override {
return _eqs.getNum();
}
virtual std::vector<yc_equation_node_ptr> get_equations() override {
std::vector<yc_equation_node_ptr> ev;
for (int i = 0; i < get_num_equations(); i++)
ev.push_back(_eqs.getAll().at(i));
return ev;
}
virtual void
call_after_new_solution(const string& code) override {
_kernel_code.push_back(code);
}
virtual int
get_prefetch_dist(int level) override ;
virtual void
set_prefetch_dist(int level,
int distance) override;
virtual void add_flow_dependency(yc_equation_node_ptr from,
yc_equation_node_ptr to) override {
auto fp = dynamic_pointer_cast<EqualsExpr>(from);
assert(fp);
auto tp = dynamic_pointer_cast<EqualsExpr>(to);
assert(tp);
_eqs.getDeps().set_imm_dep_on(fp, tp);
}
virtual void clear_dependencies() override {
_eqs.getDeps().clear_deps();
}
virtual void set_fold_len(const yc_index_node_ptr, int len) override;
virtual bool is_folding_set() override {
return _settings._foldOptions.size() > 0;
}
virtual void clear_folding() override {
_settings._foldOptions.clear();
}
virtual void set_cluster_mult(const yc_index_node_ptr, int mult) override;
virtual bool is_clustering_set() override {
return _settings._clusterOptions.size() > 0;
}
virtual void clear_clustering() override {
_settings._clusterOptions.clear();
}
virtual bool is_target_set() override {
return _settings._target.length() > 0;
}
virtual std::string get_target() override {
if (!is_target_set())
THROW_YASK_EXCEPTION("Error: call to get_target() before set_target()");
return _settings._target;
}
virtual void set_target(const std::string& format) override;
virtual void set_element_bytes(int nbytes) override {
_settings._elem_bytes = nbytes;
}
virtual int get_element_bytes() const override {
return _settings._elem_bytes;
}
virtual bool is_dependency_checker_enabled() const override {
return _settings._findDeps;
}
virtual void set_dependency_checker_enabled(bool enable) override {
_settings._findDeps = enable;
}
virtual void output_solution(yask_output_ptr output) override;
virtual void
call_before_output(output_hook_t hook_fn) override {
_output_hooks.push_back(hook_fn);
}
virtual void
set_domain_dims(const std::vector<yc_index_node_ptr>& dims) override {
_settings._domainDims.clear();
for (auto& d : dims) {
auto dp = dynamic_pointer_cast<IndexExpr>(d);
assert(dp);
auto& dname = d->get_name();
if (dp->getType() != DOMAIN_INDEX)
THROW_YASK_EXCEPTION("Error: set_domain_dims() called with non-domain index '" +
dname + "'");
_settings._domainDims.push_back(dname);
}
}
virtual void
set_domain_dims(const std::initializer_list<yc_index_node_ptr>& dims) override {
vector<yc_index_node_ptr> vdims(dims);
set_domain_dims(vdims);
}
virtual void
set_step_dim(const yc_index_node_ptr dim) override {
auto dp = dynamic_pointer_cast<IndexExpr>(dim);
assert(dp);
auto& dname = dim->get_name();
if (dp->getType() != STEP_INDEX)
THROW_YASK_EXCEPTION("Error: set_step_dim() called with non-step index '" +
dname + "'");
_settings._stepDim = dname;
}
};
} // namespace yask.
| 38.34629
| 109
| 0.588555
|
gperrotta
|
9a263a6528831a76724fa8d442bd37b186de73c3
| 15,769
|
cpp
|
C++
|
CurrencyRecognition/src/ImageAnalysis/ImageDetector.cpp
|
vogt31337/Currency-Recognition
|
05198cb002d854d650479d97d6b4e7538f670965
|
[
"MIT"
] | 42
|
2015-08-20T06:57:50.000Z
|
2021-04-30T17:52:27.000Z
|
CurrencyRecognition/src/ImageAnalysis/ImageDetector.cpp
|
vogt31337/Currency-Recognition
|
05198cb002d854d650479d97d6b4e7538f670965
|
[
"MIT"
] | 3
|
2016-11-17T14:55:43.000Z
|
2019-05-20T21:01:19.000Z
|
CurrencyRecognition/src/ImageAnalysis/ImageDetector.cpp
|
vogt31337/Currency-Recognition
|
05198cb002d854d650479d97d6b4e7538f670965
|
[
"MIT"
] | 27
|
2016-01-29T05:41:26.000Z
|
2020-11-09T12:58:42.000Z
|
#include "ImageDetector.h"
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <ImageDetector> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
ImageDetector::ImageDetector(Ptr<FeatureDetector> featureDetector, Ptr<DescriptorExtractor> descriptorExtractor, Ptr<DescriptorMatcher> descriptorMatcher, Ptr<ImagePreprocessor> imagePreprocessor,
const string& configurationTags, const string& selectorTags, const vector<string>& referenceImagesDirectories,
bool useInliersGlobalMatch,
const string& referenceImagesListPath, const string& testImagesListPath) :
_featureDetector(featureDetector), _descriptorExtractor(descriptorExtractor), _descriptorMatcher(descriptorMatcher),
_imagePreprocessor(imagePreprocessor), _configurationTags(configurationTags), _selectorTags(selectorTags),
_referenceImagesDirectories(referenceImagesDirectories), _referenceImagesListPath(referenceImagesListPath), _testImagesListPath(testImagesListPath),
_contourAspectRatioRange(-1, -1), _contourCircularityRange(-1, -1) {
setupTargetDB(referenceImagesListPath, useInliersGlobalMatch);
setupTargetsShapesRanges();
}
ImageDetector::~ImageDetector() {}
bool ImageDetector::setupTargetDB(const string& referenceImagesListPath, bool useInliersGlobalMatch) {
_targetDetectors.clear();
ifstream imgsList(referenceImagesListPath);
if (imgsList.is_open()) {
string configurationLine;
vector<string> configurations;
while (getline(imgsList, configurationLine)) {
configurations.push_back(configurationLine);
}
int numberOfFiles = configurations.size();
cout << " -> Initializing recognition database with " << numberOfFiles << " reference images and with " << _referenceImagesDirectories.size() << " levels of detail..." << endl;
PerformanceTimer performanceTimer;
performanceTimer.start();
//#pragma omp parallel for schedule(dynamic)
for (int configIndex = 0; configIndex < numberOfFiles; ++configIndex) {
string filename;
size_t targetTag;
string separator;
Scalar color;
stringstream ss(configurations[configIndex]);
ss >> filename >> separator >> targetTag >> separator >> color[2] >> color[1] >> color[0];
TargetDetector targetDetector(_featureDetector, _descriptorExtractor, _descriptorMatcher, targetTag, color, useInliersGlobalMatch);
for (size_t i = 0; i < _referenceImagesDirectories.size(); ++i) {
string referenceImagesDirectory = _referenceImagesDirectories[i];
Mat targetImage;
stringstream referenceImgePath;
referenceImgePath << REFERENCE_IMGAGES_DIRECTORY << referenceImagesDirectory << "/" << filename;
cout << " => Adding reference image " << referenceImgePath.str() << endl;
if (_imagePreprocessor->loadAndPreprocessImage(referenceImgePath.str(), targetImage, CV_LOAD_IMAGE_GRAYSCALE, false)) {
string filenameWithoutExtension = ImageUtils::getFilenameWithoutExtension(filename);
stringstream maskFilename;
maskFilename << REFERENCE_IMGAGES_DIRECTORY << referenceImagesDirectory << "/" << filenameWithoutExtension << MASK_TOKEN << MASK_EXTENSION;
Mat targetROIs;
if (ImageUtils::loadBinaryMask(maskFilename.str(), targetROIs)) {
targetDetector.setupTargetRecognition(targetImage, targetROIs);
vector<KeyPoint>& targetKeypoints = targetDetector.getTargetKeypoints();
stringstream imageKeypointsFilename;
imageKeypointsFilename << REFERENCE_IMGAGES_ANALYSIS_DIRECTORY << filenameWithoutExtension << "_" << referenceImagesDirectory << _selectorTags << IMAGE_OUTPUT_EXTENSION;
if (targetKeypoints.empty()) {
imwrite(imageKeypointsFilename.str(), targetImage);
} else {
Mat imageKeypoints;
cv::drawKeypoints(targetImage, targetKeypoints, imageKeypoints, TARGET_KEYPOINT_COLOR);
imwrite(imageKeypointsFilename.str(), imageKeypoints);
}
}
}
}
//#pragma omp critical
_targetDetectors.push_back(targetDetector);
}
cout << " -> Finished initialization of targets database in " << performanceTimer.getElapsedTimeFormated() << "\n" << endl;
return !_targetDetectors.empty();
} else {
return false;
}
}
void ImageDetector::setupTargetsShapesRanges(const string& maskPath) {
Mat shapeROIs;
if (ImageUtils::loadBinaryMask(maskPath, shapeROIs)) {
vector< vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours(shapeROIs, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
int contoursSize = (int)contours.size();
#pragma omp parallel for
for (int i = 0; i < contoursSize; ++i) {
double contourAspectRatio = ImageUtils::computeContourAspectRatio(contours[i]);
double contourCircularity = ImageUtils::computeContourCircularity(contours[i]);
#pragma omp critical
if (_contourAspectRatioRange[0] == -1 || contourAspectRatio < _contourAspectRatioRange[0]) {
_contourAspectRatioRange[0] = contourAspectRatio;
}
#pragma omp critical
if (_contourAspectRatioRange[1] == -1 || contourAspectRatio > _contourAspectRatioRange[1]) {
_contourAspectRatioRange[1] = contourAspectRatio;
}
#pragma omp critical
if (_contourCircularityRange[0] == -1 || contourCircularity < _contourCircularityRange[0]) {
_contourCircularityRange[0] = contourCircularity;
}
#pragma omp critical
if (_contourCircularityRange[1] == -1 || contourCircularity > _contourCircularityRange[1]) {
_contourCircularityRange[1] = contourCircularity;
}
}
}
}
Ptr< vector< Ptr<DetectorResult> > > ImageDetector::detectTargets(Mat& image, float minimumMatchAllowed, float minimumTargetAreaPercentage,
float maxDistanceRatio, float reprojectionThresholdPercentage, double confidence, int maxIters, size_t minimumNumberInliers) {
Ptr< vector< Ptr<DetectorResult> > > detectorResults(new vector< Ptr<DetectorResult> >());
vector<KeyPoint> keypointsQueryImage;
_featureDetector->detect(image, keypointsQueryImage);
if (keypointsQueryImage.size() < 4) { return detectorResults; }
Mat descriptorsQueryImage;
_descriptorExtractor->compute(image, keypointsQueryImage, descriptorsQueryImage);
cv::drawKeypoints(image, keypointsQueryImage, image, NONTARGET_KEYPOINT_COLOR);
float bestMatch = 0;
Ptr<DetectorResult> bestDetectorResult;
int targetDetectorsSize = _targetDetectors.size();
bool validDetection = true;
float reprojectionThreshold = image.cols * reprojectionThresholdPercentage;
//float reprojectionThreshold = 3.0;
do {
bestMatch = 0;
#pragma omp parallel for schedule(dynamic)
for (int i = 0; i < targetDetectorsSize; ++i) {
_targetDetectors[i].updateCurrentLODIndex(image);
Ptr<DetectorResult> detectorResult = _targetDetectors[i].analyzeImage(keypointsQueryImage, descriptorsQueryImage, maxDistanceRatio, reprojectionThreshold, confidence, maxIters, minimumNumberInliers);
if (detectorResult->getBestROIMatch() > minimumMatchAllowed) {
float contourArea = (float)cv::contourArea(detectorResult->getTargetContour());
float imageArea = (float)(image.cols * image.rows);
float contourAreaPercentage = contourArea / imageArea;
if (contourAreaPercentage > minimumTargetAreaPercentage) {
double contourAspectRatio = ImageUtils::computeContourAspectRatio(detectorResult->getTargetContour());
if (contourAspectRatio > _contourAspectRatioRange[0] && contourAspectRatio < _contourAspectRatioRange[1]) {
double contourCircularity = ImageUtils::computeContourCircularity(detectorResult->getTargetContour());
if (contourCircularity > _contourCircularityRange[0] && contourCircularity < _contourCircularityRange[1]) {
if (cv::isContourConvex(detectorResult->getTargetContour())) {
#pragma omp critical
{
if (detectorResult->getBestROIMatch() > bestMatch) {
bestMatch = detectorResult->getBestROIMatch();
bestDetectorResult = detectorResult;
}
}
}
}
}
}
}
}
validDetection = bestMatch > minimumMatchAllowed && bestDetectorResult->getInliers().size() > minimumNumberInliers;
if (bestDetectorResult.obj != NULL && validDetection) {
detectorResults->push_back(bestDetectorResult);
// remove inliers of best match to detect more occurrences of targets
ImageUtils::removeInliersFromKeypointsAndDescriptors(bestDetectorResult->getInliers(), keypointsQueryImage, descriptorsQueryImage);
}
} while (validDetection);
return detectorResults;
}
vector<size_t> ImageDetector::detectTargetsAndOutputResults(Mat& image, const string& imageFilename, bool useHighGUI) {
Mat imageBackup = image.clone();
Ptr< vector< Ptr<DetectorResult> > > detectorResultsOut = detectTargets(image);
vector<size_t> results;
stringstream imageInliersOutputFilename;
imageInliersOutputFilename << TEST_OUTPUT_DIRECTORY << imageFilename << FILENAME_SEPARATOR << _configurationTags << FILENAME_SEPARATOR << INLIERS_MATCHES << FILENAME_SEPARATOR;
for (size_t i = 0; i < detectorResultsOut->size(); ++i) {
Ptr<DetectorResult> detectorResult = (*detectorResultsOut)[i];
results.push_back(detectorResult->getTargetValue());
cv::drawKeypoints(image, detectorResult->getInliersKeypoints(), image, TARGET_KEYPOINT_COLOR);
stringstream ss;
ss << detectorResult->getTargetValue();
Mat imageMatchesSingle = imageBackup.clone();
Mat matchesInliers = detectorResult->getInliersMatches(imageMatchesSingle);
try {
Rect boundingBox = cv::boundingRect(detectorResult->getTargetContour());
ImageUtils::correctBoundingBox(boundingBox, image.cols, image.rows);
GUIUtils::drawLabelInCenterOfROI(ss.str(), image, boundingBox);
GUIUtils::drawLabelInCenterOfROI(ss.str(), matchesInliers, boundingBox);
ImageUtils::drawContour(image, detectorResult->getTargetContour(), detectorResult->getContourColor());
ImageUtils::drawContour(matchesInliers, detectorResult->getTargetContour(), detectorResult->getContourColor());
} catch (...) {
std::cerr << "!!! Drawing outside image !!!" << endl;
}
if (useHighGUI) {
stringstream windowName;
windowName << "Target inliers matches (window " << i << ")";
cv::namedWindow(windowName.str(), CV_WINDOW_KEEPRATIO);
cv::imshow(windowName.str(), matchesInliers);
cv::waitKey(10);
}
stringstream imageOutputFilenameFull;
imageOutputFilenameFull << imageInliersOutputFilename.str() << i << IMAGE_OUTPUT_EXTENSION;
imwrite(imageOutputFilenameFull.str(), matchesInliers);
}
sort(results.begin(), results.end());
cout << " -> Detected " << results.size() << (results.size() != 1 ? " targets" : " target");
size_t globalResult = 0;
stringstream resultsSS;
if (!results.empty()) {
resultsSS << " (";
for (size_t i = 0; i < results.size(); ++i) {
size_t resultValue = results[i];
resultsSS << " " << resultValue;
globalResult += resultValue;
}
resultsSS << " )";
cout << resultsSS.str();
}
cout << endl;
stringstream globalResultSS;
globalResultSS << "Global result: " << globalResult << resultsSS.str();
Rect globalResultBoundingBox(0, 0, image.cols, image.rows);
GUIUtils::drawImageLabel(globalResultSS.str(), image, globalResultBoundingBox);
stringstream imageOutputFilename;
imageOutputFilename << TEST_OUTPUT_DIRECTORY << imageFilename << FILENAME_SEPARATOR << _configurationTags << IMAGE_OUTPUT_EXTENSION;
imwrite(imageOutputFilename.str(), image);
return results;
}
DetectorEvaluationResult ImageDetector::evaluateDetector(const string& testImgsList, bool saveResults) {
double globalPrecision = 0;
double globalRecall = 0;
double globalAccuracy = 0;
size_t numberTestImages = 0;
stringstream resultsFilename;
resultsFilename << TEST_OUTPUT_DIRECTORY << _configurationTags << FILENAME_SEPARATOR << RESULTS_FILE;
ofstream resutlsFile(resultsFilename.str());
ifstream imgsList(testImgsList);
if (resutlsFile.is_open() && imgsList.is_open()) {
resutlsFile << RESULTS_FILE_HEADER << "\n" << endl;
string filename;
vector<string> imageFilenames;
vector< vector<size_t> > expectedResults;
while (getline(imgsList, filename)) {
imageFilenames.push_back(filename);
vector<size_t> expectedResultFromTest;
extractExpectedResultsFromFilename(filename, expectedResultFromTest);
expectedResults.push_back(expectedResultFromTest);
}
int numberOfTests = imageFilenames.size();
cout << " -> Evaluating detector with " << numberOfTests << " test images..." << endl;
PerformanceTimer globalPerformanceTimer;
globalPerformanceTimer.start();
//#pragma omp parallel for schedule(dynamic)
for (int i = 0; i < numberOfTests; ++i) {
PerformanceTimer testPerformanceTimer;
testPerformanceTimer.start();
string imageFilename = imageFilenames[i];
//string imageFilename = ImageUtils::getFilenameWithoutExtension("");
string imageFilenameWithPath = TEST_IMGAGES_DIRECTORY + imageFilenames[i];
stringstream detectorEvaluationResultSS;
DetectorEvaluationResult detectorEvaluationResult;
Mat imagePreprocessed;
cout << "\n -> Evaluating image " << imageFilename << " (" << (i + 1) << "/" << numberOfTests << ")" << endl;
if (_imagePreprocessor->loadAndPreprocessImage(imageFilenameWithPath, imagePreprocessed, CV_LOAD_IMAGE_GRAYSCALE, false)) {
vector<size_t> results = detectTargetsAndOutputResults(imagePreprocessed, imageFilename, false);
detectorEvaluationResult = DetectorEvaluationResult(results, expectedResults[i]);
globalPrecision += detectorEvaluationResult.getPrecision();
globalRecall += detectorEvaluationResult.getRecall();
globalAccuracy += detectorEvaluationResult.getAccuracy();
detectorEvaluationResultSS << PRECISION_TOKEN << ": " << detectorEvaluationResult.getPrecision() << " | " << RECALL_TOKEN << ": " << detectorEvaluationResult.getRecall() << " | " << ACCURACY_TOKEN << ": " << detectorEvaluationResult.getAccuracy();
++numberTestImages;
if (saveResults) {
resutlsFile << imageFilename << " -> " << detectorEvaluationResultSS.str() << endl;
}
}
cout << " -> Evaluation of image " << imageFilename << " finished in " << testPerformanceTimer.getElapsedTimeFormated() << endl;
cout << " -> " << detectorEvaluationResultSS.str() << endl;
}
globalPrecision /= (double)numberTestImages;
globalRecall /= (double)numberTestImages;
globalAccuracy /= (double)numberTestImages;
stringstream detectorEvaluationGloablResultSS;
detectorEvaluationGloablResultSS << GLOBAL_PRECISION_TOKEN << ": " << globalPrecision << " | " << GLOBAL_RECALL_TOKEN << ": " << globalRecall << " | " << GLOBAL_ACCURACY_TOKEN << ": " << globalAccuracy;
resutlsFile << "\n\n" << RESULTS_FILE_FOOTER << endl;
resutlsFile << " ==> " << detectorEvaluationGloablResultSS.str() << endl;
cout << "\n -> Finished evaluation of detector in " << globalPerformanceTimer.getElapsedTimeFormated() << " || " << detectorEvaluationGloablResultSS.str() << "\n" << endl;
}
return DetectorEvaluationResult(globalPrecision, globalRecall, globalAccuracy);
}
void ImageDetector::extractExpectedResultsFromFilename(string filename, vector<size_t>& expectedResultFromTestOut) {
for (size_t i = 0; i < filename.size(); ++i) {
char letter = filename[i];
if (letter == '-') {
filename[i] = ' ';
} else if (letter == '.' || letter == '_') {
filename = filename.substr(0, i);
break;
}
}
stringstream ss(filename);
size_t number;
while (ss >> number) {
expectedResultFromTestOut.push_back(number);
}
}
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> </ImageDetector> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
| 42.850543
| 251
| 0.722684
|
vogt31337
|
9a2c88ddbed7605526dca4235c577809eba1b6b2
| 28,057
|
cpp
|
C++
|
Src/Value.cpp
|
draede/cx
|
f3ce4aec9b99095760481b1507e383975b2827e3
|
[
"MIT"
] | 1
|
2016-08-28T18:29:17.000Z
|
2016-08-28T18:29:17.000Z
|
Src/Value.cpp
|
draede/cx
|
f3ce4aec9b99095760481b1507e383975b2827e3
|
[
"MIT"
] | null | null | null |
Src/Value.cpp
|
draede/cx
|
f3ce4aec9b99095760481b1507e383975b2827e3
|
[
"MIT"
] | null | null | null |
/*
* CX - C++ framework for general purpose development
*
* https://github.com/draede/cx
*
* Copyright (C) 2014 - 2021 draede - draede [at] outlook [dot] com
*
* Released under the MIT License.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "CX/precomp.hpp"
#include "CX/Value.hpp"
#include "CX/IO/MemInputStream.hpp"
#include "CX/IO/MemOutputStream.hpp"
namespace CX
{
class VarJSONSAXParserObserver : public Data::JSON::ISAXParserObserver
{
public:
Bool m_bInit;
Value *m_pRoot;
Value *m_pCurrent;
String m_sKey;
virtual Bool OnBeginParse()
{
return True;
}
virtual Bool OnEndParse()
{
return True;
}
virtual Bool OnBeginObject()
{
if (m_bInit)
{
if (m_pCurrent->SetAsObject().IsNOK())
{
return False;
}
m_bInit = False;
}
else
{
Value *pValue = new (std::nothrow) Value(Value::Type_Object);
if (NULL == pValue)
{
return False;
}
if (m_pCurrent->IsObject())
{
m_pCurrent->AddMember(m_sKey, pValue);
m_pCurrent = pValue;
}
else
{
m_pCurrent->AddItem(pValue);
m_pCurrent = pValue;
}
}
return True;
}
virtual Bool OnEndObject()
{
m_pCurrent = &m_pCurrent->GetParent();
return True;
}
virtual Bool OnBeginArray()
{
if (m_bInit)
{
if (m_pCurrent->SetAsArray().IsNOK())
{
return False;
}
m_bInit = False;
}
else
{
Value *pValue = new (std::nothrow) Value(Value::Type_Array);
if (NULL == pValue)
{
return False;
}
if (m_pCurrent->IsObject())
{
m_pCurrent->AddMember(m_sKey, pValue);
m_pCurrent = pValue;
}
else
{
m_pCurrent->AddItem(pValue);
m_pCurrent = pValue;
}
}
return True;
}
virtual Bool OnEndArray()
{
m_pCurrent = &m_pCurrent->GetParent();
return True;
}
virtual Bool OnKey(const Char *pBuffer, Size cLen)
{
m_sKey.assign(pBuffer, cLen);
return True;
}
virtual Bool OnNullValue()
{
if (m_pCurrent->IsObject())
{
(*m_pCurrent)[m_sKey].SetNull();
}
else
{
(*m_pCurrent)[-1].SetNull();
}
return True;
}
virtual Bool OnBoolValue(Bool bBool)
{
if (m_pCurrent->IsObject())
{
(*m_pCurrent)[m_sKey].SetBool(bBool);
}
else
{
(*m_pCurrent)[-1].SetBool(bBool);
}
return True;
}
virtual Bool OnIntValue(Int64 nInt)
{
if (m_pCurrent->IsObject())
{
(*m_pCurrent)[m_sKey].SetInt(nInt);
}
else
{
(*m_pCurrent)[-1].SetInt(nInt);
}
return True;
}
virtual Bool OnUIntValue(UInt64 uInt)
{
if (m_pCurrent->IsObject())
{
(*m_pCurrent)[m_sKey].SetUInt(uInt);
}
else
{
(*m_pCurrent)[-1].SetUInt(uInt);
}
return True;
}
virtual Bool OnRealValue(Double lfReal)
{
if (m_pCurrent->IsObject())
{
(*m_pCurrent)[m_sKey].SetReal(lfReal);
}
else
{
(*m_pCurrent)[-1].SetReal(lfReal);
}
return True;
}
virtual Bool OnStringValue(const Char *pBuffer, Size cLen)
{
if (m_pCurrent->IsObject())
{
(*m_pCurrent)[m_sKey].SetString(String(pBuffer, cLen));
}
else
{
(*m_pCurrent)[-1].SetString(String(pBuffer, cLen));
}
return True;
}
};
Value Value::INVALID_VALUE(NULL, NULL, NULL);
const Double Value::DEFAULT_REAL = 0.0;
const String Value::DEFAULT_STRING;
Value::Value()
{
m_nType = Type_Null;
m_pParent = NULL;
}
Value::Value(void *pDummy1, void *pDummy2, void *pDummy3)
{
CX_UNUSED(pDummy1);
CX_UNUSED(pDummy2);
CX_UNUSED(pDummy3);
m_nType = Type_Invalid;
m_pParent = NULL;
}
Value::Value(Value *pParent)
{
m_nType = Type_Null;
m_pParent = pParent;
}
Value::Value(Type nType)
{
m_nType = Type_Null;
m_pParent = NULL;
switch (nType)
{
case Type_Bool: SetBool(DEFAULT_BOOL); break;
case Type_Int: SetInt(DEFAULT_INT); break;
case Type_UInt: SetUInt(DEFAULT_UINT); break;
case Type_Real: SetReal(DEFAULT_REAL); break;
case Type_String: SetString(DEFAULT_STRING); break;
case Type_Object: SetAsObject(); break;
case Type_Array: SetAsArray(); break;
default:
{
}
}
}
Value::Value(Bool bValue)
{
m_nType = Type_Null;
m_pParent = NULL;
SetBool(bValue);
}
Value::Value(Int64 nValue)
{
m_nType = Type_Null;
m_pParent = NULL;
SetInt(nValue);
}
Value::Value(UInt64 uValue)
{
m_nType = Type_Null;
m_pParent = NULL;
SetUInt(uValue);
}
Value::Value(Double lfValue)
{
m_nType = Type_Null;
m_pParent = NULL;
SetReal(lfValue);
}
Value::Value(const String &sValue)
{
m_nType = Type_Null;
m_pParent = NULL;
SetString(sValue);
}
Value::Value(const Value &value)
{
m_nType = Type_Null;
Copy(value);
}
Value::~Value()
{
if (!IsInvalid())
{
FreeMem();
m_nType = Type_Null;
m_pParent = NULL;
}
}
void Value::FreeMem()
{
if (IsInvalid())
{
return;
}
if (Type_String == m_nType)
{
delete m_psString;
}
else
if (Type_Object == m_nType)
{
for (Object::iterator iter = m_pObject->begin(); iter != m_pObject->end(); ++iter)
{
delete iter->second;
}
delete m_pObject;
}
else
if (Type_Array == m_nType)
{
for (Array::iterator iter = m_pArray->begin(); iter != m_pArray->end(); ++iter)
{
delete *iter;
}
delete m_pArray;
}
}
Value &Value::operator=(const Value &value)
{
if (IsInvalid())
{
return *this;
}
Copy(value);
return *this;
}
Status Value::Copy(const Value &value)
{
if (IsInvalid())
{
return Status_InvalidCall;
}
switch (value.m_nType)
{
case Type_Null: return SetNull();
case Type_Bool: return SetBool(value.GetBool());
case Type_Int: return SetInt(value.GetInt());
case Type_UInt: return SetUInt(value.GetUInt());
case Type_Real: return SetReal(value.GetReal());
case Type_String: return SetString(value.GetString());
case Type_Object:
{
Status status;
if ((status = SetAsObject()).IsNOK())
{
return status;
}
for (Object::iterator iter = value.m_pObject->begin(); iter != value.m_pObject->end(); ++iter)
{
if ((status = AddMember(iter->first, iter->second)).IsNOK())
{
return status;
}
}
return Status();
}
break;
case Type_Array:
{
Status status;
if ((status = SetAsArray()).IsNOK())
{
return status;
}
for (Array::iterator iter = value.m_pArray->begin(); iter != value.m_pArray->end(); ++iter)
{
if ((status = AddItem(*iter)).IsNOK())
{
return status;
}
}
return Status();
}
break;
default:
{
return Status_InvalidArg;
}
}
}
Bool Value::HasParent()
{
return (NULL != m_pParent);
}
const Value &Value::GetParent() const
{
if (NULL != m_pParent)
{
return *m_pParent;
}
else
{
return INVALID_VALUE;
}
}
Value &Value::GetParent()
{
if (NULL != m_pParent)
{
return *m_pParent;
}
else
{
return INVALID_VALUE;
}
}
Value::Type Value::GetType() const
{
return m_nType;
}
Bool Value::IsInvalid() const
{
return (Type_Invalid == GetType());
}
Bool Value::IsNull() const
{
return (Type_Null == GetType());
}
Bool Value::IsBool() const
{
return (Type_Bool == GetType());
}
Bool Value::IsInt() const
{
return (Type_Int == GetType());
}
Bool Value::IsUInt() const
{
return (Type_UInt == GetType());
}
Bool Value::IsReal() const
{
return (Type_Real == GetType());
}
Bool Value::IsString() const
{
return (Type_String == GetType());
}
Bool Value::IsObject() const
{
return (Type_Object == GetType());
}
Bool Value::IsArray() const
{
return (Type_Array == GetType());
}
Bool Value::GetNull(Status *pStatus/* = NULL*/) const
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return False;
}
if (IsNull())
{
if (NULL != pStatus)
{
*pStatus = Status_OK;
}
return True;
}
else
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return False;
}
}
Status Value::SetNull()
{
if (IsInvalid())
{
return Status_InvalidCall;
}
FreeMem();
m_nType = Type_Null;
return Status();
}
Bool Value::GetBool(Bool bDefault/* = DEFAULT_BOOL*/, Status *pStatus/* = NULL*/) const
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return bDefault;
}
if (IsBool())
{
if (NULL != pStatus)
{
*pStatus = Status_OK;
}
return m_bBool;
}
else
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return bDefault;
}
}
Status Value::SetBool(Bool bValue)
{
if (IsInvalid())
{
return Status_InvalidCall;
}
FreeMem();
m_nType = Type_Bool;
m_bBool = bValue;
return Status();
}
Int64 Value::GetInt(Int64 nDefault/* = DEFAULT_INT*/, Status *pStatus/* = NULL*/) const
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return nDefault;
}
if (IsInt())
{
if (NULL != pStatus)
{
*pStatus = Status_OK;
}
return m_nInt;
}
else
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return nDefault;
}
}
Status Value::SetInt(Int64 nValue)
{
if (IsInvalid())
{
return Status_InvalidCall;
}
FreeMem();
m_nType = Type_Int;
m_nInt = nValue;
return Status();
}
UInt64 Value::GetUInt(UInt64 uDefault/* = DEFAULT_UINT*/, Status *pStatus/* = NULL*/) const
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return uDefault;
}
if (IsUInt())
{
if (NULL != pStatus)
{
*pStatus = Status_OK;
}
return m_uInt;
}
else
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return uDefault;
}
}
Status Value::SetUInt(UInt64 uValue)
{
if (IsInvalid())
{
return Status_InvalidCall;
}
FreeMem();
m_nType = Type_UInt;
m_uInt = uValue;
return Status();
}
Double Value::GetReal(Double lfDefault/* = DEFAULT_DOUBLE*/, Status *pStatus/* = NULL*/) const
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return lfDefault;
}
if (IsReal())
{
if (NULL != pStatus)
{
*pStatus = Status_OK;
}
return m_lfReal;
}
else
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return lfDefault;
}
}
Status Value::SetReal(Double lfValue)
{
if (IsInvalid())
{
return Status_InvalidCall;
}
FreeMem();
m_nType = Type_Real;
m_lfReal = lfValue;
return Status();
}
const String &Value::GetString(const String &sDefault/* = DEFAULT_STRING*/, Status *pStatus/* = NULL*/) const
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return sDefault;
}
if (IsString())
{
if (NULL != pStatus)
{
*pStatus = Status_OK;
}
return *m_psString;
}
else
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return sDefault;
}
}
Status Value::SetString(const String &sValue)
{
if (IsInvalid())
{
return Status_InvalidCall;
}
String *psValue;
if (NULL == (psValue = new (std::nothrow) String(sValue)))
{
return Status_MemAllocFailed;
}
FreeMem();
m_nType = Type_String;
m_psString = psValue;
return Status();
}
Status Value::SetAsArray()
{
if (IsInvalid())
{
return Status_InvalidCall;
}
Array *pArray;
if (NULL == (pArray = new (std::nothrow) Array()))
{
return Status_MemAllocFailed;
}
FreeMem();
m_nType = Type_Array;
m_pArray = pArray;
return Status();
}
Status Value::SetAsObject()
{
if (IsInvalid())
{
return Status_InvalidCall;
}
Object *pObject;
if (NULL == (pObject = new (std::nothrow) Object()))
{
return Status_MemAllocFailed;
}
FreeMem();
m_nType = Type_Object;
m_pObject = pObject;
return Status();
}
Size Value::GetItemsCount(Status *pStatus/* = NULL*/) const
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return 0;
}
if (IsArray())
{
if (NULL != pStatus)
{
*pStatus = Status_OK;
}
return m_pArray->size();
}
else
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return 0;
}
}
Value &Value::AddItem(Status *pStatus/* = NULL*/)
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return INVALID_VALUE;
}
if (!IsArray())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return INVALID_VALUE;
}
Value *pValue;
if (NULL == (pValue = new (std::nothrow) Value(this)))
{
return INVALID_VALUE;
}
m_pArray->push_back(pValue);
return *pValue;
}
Status Value::AddItem(Value *pValue)
{
if (IsInvalid())
{
return Status_InvalidCall;
}
if (!IsArray())
{
return Status_InvalidArg;
}
if (NULL != pValue->m_pParent)
{
return Status_InvalidArg;
}
pValue->m_pParent = this;
m_pArray->push_back(pValue);
return Status();
}
Value &Value::InsertItem(int cIndex, Status *pStatus/* = NULL*/)
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return INVALID_VALUE;
}
if (!IsArray())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return INVALID_VALUE;
}
if (0 > cIndex)
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return INVALID_VALUE;
}
if (cIndex >= (int)m_pArray->size())
{
return AddItem(pStatus);
}
Value *pValue;
if (NULL == (pValue = new (std::nothrow) Value(this)))
{
return INVALID_VALUE;
}
Array::iterator iter = m_pArray->begin() + cIndex;
m_pArray->insert(iter, pValue);
return *pValue;
}
Status Value::InsertItem(int cIndex, Value *pValue)
{
if (IsInvalid())
{
return Status_InvalidCall;
}
if (!IsArray())
{
return Status_InvalidArg;
}
if (NULL == pValue->m_pParent)
{
return Status_InvalidArg;
}
if (0 > cIndex)
{
return Status_InvalidArg;
}
if (cIndex >= (int)m_pArray->size())
{
return AddItem(pValue);
}
pValue->m_pParent = this;
Array::iterator iter = m_pArray->begin() + cIndex;
m_pArray->insert(iter, pValue);
return Status();
}
Status Value::RemoveItem(int cIndex)
{
if (IsInvalid())
{
return Status_InvalidCall;
}
if (!IsArray())
{
return Status_InvalidArg;
}
if (cIndex >= (int)m_pArray->size())
{
return Status_InvalidArg;
}
Array::iterator iter = m_pArray->begin() + cIndex;
delete *iter;
m_pArray->erase(iter);
return Status();
}
Status Value::RemoveAllItems()
{
if (IsInvalid())
{
return Status_InvalidCall;
}
if (!IsArray())
{
return Status_InvalidArg;
}
for (Array::iterator iter = m_pArray->begin(); iter != m_pArray->end(); ++iter)
{
delete *iter;
}
m_pArray->clear();
return Status();
}
const Value &Value::GetItem(int cIndex, Status *pStatus/* = NULL*/) const
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return INVALID_VALUE;
}
if (!IsArray())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return INVALID_VALUE;
}
if (0 > cIndex || cIndex >= (int)m_pArray->size())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return INVALID_VALUE;
}
return *(*m_pArray)[cIndex];
}
Value &Value::GetItem(int cIndex, Status *pStatus/* = NULL*/) //-1 will create a new value at the end
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return INVALID_VALUE;
}
if (!IsArray())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return INVALID_VALUE;
}
if (-1 == cIndex)
{
return AddItem(pStatus);
}
if (0 > cIndex || cIndex >= (int)m_pArray->size())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return INVALID_VALUE;
}
return *(*m_pArray)[cIndex];
}
const Value &Value::operator[](int cIndex) const
{
return GetItem(cIndex);
}
Value &Value::operator[](int cIndex) //a non existing member will be created
{
return GetItem(cIndex);
}
Size Value::GetMembersCount(Status *pStatus/* = NULL*/) const
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return 0;
}
if (!IsObject())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return 0;
}
return m_pObject->size();
}
Bool Value::Exists(const String &sName, Status *pStatus/* = NULL*/) const
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return False;
}
if (!IsObject())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return False;
}
return (m_pObject->end() != m_pObject->find(sName));
}
Value &Value::AddMember(const String &sName, Status *pStatus/* = NULL*/)
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return INVALID_VALUE;
}
if (!IsObject())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return INVALID_VALUE;
}
Object::iterator iter = m_pObject->find(sName);
if (m_pObject->end() != iter)
{
return *iter->second;
}
Value *pValue;
if (NULL == (pValue = new (std::nothrow) Value(this)))
{
return INVALID_VALUE;
}
(*m_pObject)[sName] = pValue;
return *pValue;
}
Status Value::AddMember(const String &sName, Value *pValue)
{
if (IsInvalid())
{
return Status_InvalidCall;
}
if (!IsObject())
{
return Status_InvalidArg;
}
Object::iterator iter = m_pObject->find(sName);
if (m_pObject->end() != iter)
{
return Status_InvalidArg;
}
if (NULL != pValue->m_pParent)
{
return Status_InvalidArg;
}
pValue->m_pParent = this;
(*m_pObject)[sName] = pValue;
return Status();
}
Status Value::RemoveMember(const String &sName)
{
if (IsInvalid())
{
return Status_InvalidCall;
}
if (!IsObject())
{
return Status_InvalidArg;
}
Object::iterator iter = m_pObject->find(sName);
if (m_pObject->end() == iter)
{
return Status_NotFound;
}
m_pObject->erase(iter);
return Status();
}
Status Value::RemoveAllMembers()
{
if (IsInvalid())
{
return Status_InvalidCall;
}
if (!IsObject())
{
return Status_InvalidArg;
}
for (Object::iterator iter = m_pObject->begin(); iter != m_pObject->end(); ++iter)
{
delete iter->second;
}
m_pObject->clear();
return Status();
}
Value &Value::GetMemberByIndex(Size cIndex, String *psName/* = NULL*/, Status *pStatus/* = NULL*/)
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return INVALID_VALUE;
}
if (!IsObject())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return INVALID_VALUE;
}
if (cIndex >= m_pObject->size())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return INVALID_VALUE;
}
Object::iterator iter = m_pObject->begin();
while (0 < cIndex)
{
++iter;
cIndex--;
}
if (NULL != psName)
{
*psName = iter->first;
}
return *iter->second;
}
const Value &Value::GetMemberByIndex(Size cIndex, String *psName/* = NULL*/, Status *pStatus/* = NULL*/) const
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return INVALID_VALUE;
}
if (!IsObject())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return INVALID_VALUE;
}
if (cIndex >= m_pObject->size())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return INVALID_VALUE;
}
Object::const_iterator iter = m_pObject->begin();
while (0 < cIndex)
{
++iter;
cIndex--;
}
if (NULL != psName)
{
*psName = iter->first;
}
return *iter->second;
}
const Value &Value::GetMember(const String &sName, Status *pStatus/* = NULL*/) const
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return INVALID_VALUE;
}
if (!IsObject())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return INVALID_VALUE;
}
Object::const_iterator iter = m_pObject->find(sName);
if (m_pObject->end() == iter)
{
if (NULL != pStatus)
{
*pStatus = Status_NotFound;
}
return INVALID_VALUE;
}
return *iter->second;
}
Value &Value::GetMember(const String &sName, Status *pStatus/* = NULL*/) //a non existing member will be created
{
if (IsInvalid())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidCall;
}
return INVALID_VALUE;
}
if (!IsObject())
{
if (NULL != pStatus)
{
*pStatus = Status_InvalidArg;
}
return INVALID_VALUE;
}
Object::iterator iter = m_pObject->find(sName);
if (m_pObject->end() == iter)
{
return AddMember(sName, pStatus);
}
return *iter->second;
}
const Value &Value::operator[](const String &sName) const
{
return GetMember(sName);
}
Value &Value::operator[](const String &sName) //a non existing member will be created
{
return GetMember(sName);
}
const Value &Value::operator[](const Char *szName) const
{
return GetMember(szName);
}
Value &Value::operator[](const Char *szName) //a non existing member will be created
{
return GetMember(szName);
}
Value &Value::operator=(Bool bBool)
{
SetBool(bBool);
return *this;
}
Value &Value::operator=(Int64 nInt)
{
SetInt(nInt);
return *this;
}
Value &Value::operator=(UInt64 uInt)
{
SetUInt(uInt);
return *this;
}
Value &Value::operator=(Double lfReal)
{
SetReal(lfReal);
return *this;
}
Value &Value::operator=(const String &sString)
{
SetString(sString);
return *this;
}
Value &Value::operator=(const Char *szString)
{
SetString(szString);
return *this;
}
Value::operator Bool () const
{
return GetBool();
}
Value::operator Int64 () const
{
return GetInt();
}
Value::operator UInt64 () const
{
return GetUInt();
}
Value::operator Double () const
{
return GetReal();
}
Value::operator const String & () const
{
return GetString();
}
Value::operator const Char * () const
{
return GetString().c_str();
}
Status Value::Read(IO::IInputStream *pInputStream)
{
Data::JSON::SAXParser parser;
VarJSONSAXParserObserver observer;
Status status;
observer.m_pRoot = observer.m_pCurrent = this;
observer.m_bInit = True;
if ((status = parser.AddObserver(&observer)).IsNOK())
{
return status;
}
return parser.ParseStream(pInputStream);
}
Status Value::Read(const void *pData, Size cbSize)
{
IO::MemInputStream mis(pData, cbSize);
return Read(&mis);
}
Status Value::Read(const String &sData)
{
return Read(sData.c_str(), sData.size());
}
Status Value::Read(const Char *szData)
{
return Read(String(szData));
}
int Value::Compare(const Value &v) const
{
struct Node
{
const Value *pV1;
const Value *pV2;
int cIndex;
};
typedef Stack<Node>::Type NodesStack;
NodesStack stackNodes;
const Value *pV1 = this;
const Value *pV2 = &v;
bool bReady;
Status status;
for (;;)
{
if (!stackNodes.empty())
{
stackNodes.top().cIndex++;
if (stackNodes.top().pV1->IsObject())
{
String sName;
if ((Size)stackNodes.top().cIndex < stackNodes.top().pV1->GetMembersCount())
{
pV1 = &stackNodes.top().pV1->GetMemberByIndex((Size)stackNodes.top().cIndex, &sName, &status);
if (!status)
{
return status;
}
pV2 = &stackNodes.top().pV2->GetMember(sName, &status);
if (!status)
{
return status;
}
}
else
{
stackNodes.pop();
if (stackNodes.empty())
{
break;
}
else
{
continue;
}
}
}
else
{
if ((Size)stackNodes.top().cIndex < stackNodes.top().pV1->GetItemsCount())
{
pV1 = &stackNodes.top().pV1->GetItem((Size)stackNodes.top().cIndex, &status);
if (!status)
{
return status;
}
pV2 = &stackNodes.top().pV2->GetItem((Size)stackNodes.top().cIndex, &status);
if (!status)
{
return status;
}
}
else
{
stackNodes.pop();
if (stackNodes.empty())
{
break;
}
else
{
continue;
}
}
}
}
bReady = false;
if (pV1->IsInt())
{
if (pV2->IsUInt())
{
if (0 > pV1->GetInt())
{
return -1;
}
else
{
if ((UInt64)pV1->GetInt() < pV2->GetUInt())
{
return -1;
}
else
if ((UInt64)pV1->GetInt() > pV2->GetUInt())
{
return 1;
}
}
bReady = true;
}
else
if (pV2->IsReal())
{
if ((double)pV1->GetInt() < pV2->GetReal())
{
return -1;
}
else
if ((double)pV1->GetInt() > pV2->GetReal())
{
return 1;
}
bReady = true;
}
}
else
if (pV1->IsUInt())
{
if (pV2->IsInt())
{
if (0 > pV2->GetInt())
{
return 1;
}
else
{
if (pV1->GetUInt() < (UInt64)pV2->GetInt())
{
return -1;
}
else
if (pV1->GetUInt() > (UInt64)pV2->GetInt())
{
return 1;
}
}
bReady = true;
}
else
if (pV2->IsReal())
{
if ((double)pV1->GetUInt() < pV2->GetReal())
{
return -1;
}
else
if ((double)pV1->GetUInt() > pV2->GetReal())
{
return 1;
}
bReady = true;
}
}
else
if (pV1->IsReal())
{
if (pV2->IsInt())
{
if (pV1->GetReal() < (double)pV2->GetInt())
{
return -1;
}
else
if (pV1->GetReal() > (double)pV2->GetInt())
{
return 1;
}
bReady = true;
}
else
if (pV2->IsUInt())
{
if (pV1->GetReal() < (double)pV2->GetUInt())
{
return -1;
}
else
if (pV1->GetReal() > (double)pV2->GetUInt())
{
return 1;
}
bReady = true;
}
}
if (!bReady)
{
if (pV1->GetType() < pV2->GetType())
{
return -1;
}
else
if (pV1->GetType() > pV2->GetType())
{
return 1;
}
else
{
if (pV1->IsNull())
{
//nothing to do
}
else
if (pV1->IsBool())
{
if (pV1->GetBool() < pV2->GetBool())
{
return -1;
}
else
if (pV1->GetBool() > pV2->GetBool())
{
return 1;
}
}
else
if (pV1->IsInt())
{
if (pV1->GetInt() < pV2->GetInt())
{
return -1;
}
if (pV1->GetInt() > pV2->GetInt())
{
return 1;
}
}
else
if (pV1->IsUInt())
{
if (pV1->GetUInt() < pV2->GetUInt())
{
return -1;
}
if (pV1->GetUInt() > pV2->GetUInt())
{
return 1;
}
}
else
if (pV1->IsReal())
{
if (pV1->GetReal() < pV2->GetReal())
{
return -1;
}
if (pV1->GetReal() > pV2->GetReal())
{
return 1;
}
}
else
if (pV1->IsString())
{
int nCmp = cx_strcmp(pV1->GetString().c_str(), pV2->GetString().c_str());
if (0 != nCmp)
{
return nCmp;
}
}
else
if (pV1->IsObject())
{
if (pV1->GetMembersCount() < pV2->GetMembersCount())
{
return -1;
}
else
if (pV1->GetMembersCount() > pV2->GetMembersCount())
{
return 1;
}
Node node;
node.pV1 = pV1;
node.pV2 = pV2;
node.cIndex = -1;
stackNodes.push(node);
}
else
if (pV1->IsArray())
{
if (pV1->GetItemsCount() < pV2->GetItemsCount())
{
return -1;
}
else
if (pV1->GetItemsCount() > pV2->GetItemsCount())
{
return 1;
}
Node node;
node.pV1 = pV1;
node.pV2 = pV2;
node.cIndex = -1;
stackNodes.push(node);
}
else
{
return -1;
}
}
}
if (stackNodes.empty())
{
break;
}
}
return 0;
}
}//namespace CX
| 14.651175
| 112
| 0.602559
|
draede
|
9a2d05e47bd44d6d79b0bff50eda108f63beb5b2
| 473
|
cpp
|
C++
|
fboss/agent/hw/sai/store/SaiObjectEventPublisher.cpp
|
nathanawmk/fboss
|
9f36dbaaae47202f9131598560c65715334a9a83
|
[
"BSD-3-Clause"
] | 834
|
2015-03-10T18:12:28.000Z
|
2022-03-31T20:16:17.000Z
|
fboss/agent/hw/sai/store/SaiObjectEventPublisher.cpp
|
nathanawmk/fboss
|
9f36dbaaae47202f9131598560c65715334a9a83
|
[
"BSD-3-Clause"
] | 82
|
2015-04-07T08:48:29.000Z
|
2022-03-11T21:56:58.000Z
|
fboss/agent/hw/sai/store/SaiObjectEventPublisher.cpp
|
nathanawmk/fboss
|
9f36dbaaae47202f9131598560c65715334a9a83
|
[
"BSD-3-Clause"
] | 296
|
2015-03-11T03:45:37.000Z
|
2022-03-14T22:54:22.000Z
|
// Copyright 2004-present Facebook. All Rights Reserved.
#include "fboss/agent/hw/sai/store/SaiObjectEventPublisher.h"
#include <folly/Singleton.h>
namespace {
struct singleton_tag_type {};
} // namespace
namespace facebook::fboss {
static folly::Singleton<SaiObjectEventPublisher, singleton_tag_type>
kSingleton{};
std::shared_ptr<SaiObjectEventPublisher>
SaiObjectEventPublisher::getInstance() {
return kSingleton.try_get();
}
} // namespace facebook::fboss
| 21.5
| 68
| 0.778013
|
nathanawmk
|
9a2fb0628aefad8b7f0559296a58049cf8c5d057
| 1,245
|
hpp
|
C++
|
include/Pomdog/Graphics/InputLayoutHelper.hpp
|
bis83/pomdog
|
133a9262958d539ae6d93664e6cb2207b5b6c7ff
|
[
"MIT"
] | null | null | null |
include/Pomdog/Graphics/InputLayoutHelper.hpp
|
bis83/pomdog
|
133a9262958d539ae6d93664e6cb2207b5b6c7ff
|
[
"MIT"
] | null | null | null |
include/Pomdog/Graphics/InputLayoutHelper.hpp
|
bis83/pomdog
|
133a9262958d539ae6d93664e6cb2207b5b6c7ff
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2013-2015 mogemimi.
// Distributed under the MIT license. See LICENSE.md file for details.
#ifndef POMDOG_INPUTLAYOUTHELPER_A6C6ACE6_HPP
#define POMDOG_INPUTLAYOUTHELPER_A6C6ACE6_HPP
#include "detail/ForwardDeclarations.hpp"
#include "InputElementFormat.hpp"
#include "InputElement.hpp"
#include "InputLayoutDescription.hpp"
#include "Pomdog/Basic/Export.hpp"
#include <cstdint>
namespace Pomdog {
class POMDOG_EXPORT InputLayoutHelper final {
public:
InputLayoutHelper & PushBack(InputElementFormat format);
InputLayoutHelper & Byte4();
InputLayoutHelper & Float();
InputLayoutHelper & Float2();
InputLayoutHelper & Float3();
InputLayoutHelper & Float4();
InputLayoutHelper & Int4();
InputLayoutHelper & AddInputSlot();
InputLayoutHelper & AddInputSlot(InputClassification slotClass,
std::uint16_t instanceStepRate);
InputLayoutDescription CreateInputLayout();
private:
std::vector<InputElement> elements;
std::uint16_t inputSlot = 0;
std::uint16_t byteOffset = 0;
std::uint16_t instanceStepRate = 0;
InputClassification slotClass = InputClassification::InputPerVertex;
};
} // namespace Pomdog
#endif // POMDOG_INPUTLAYOUTHELPER_A6C6ACE6_HPP
| 24.9
| 72
| 0.759839
|
bis83
|
9a2fb48bc643b588adf33c4b65b984ac3fbbd498
| 7,800
|
cpp
|
C++
|
include/et/rendering/vulkan/vulkan_textureset.cpp
|
sergeyreznik/et-engine
|
a95fe4b9c5db0e873361f36908de284d0ae4b6d6
|
[
"BSD-3-Clause"
] | 55
|
2015-01-13T22:50:36.000Z
|
2022-02-26T01:55:02.000Z
|
include/et/rendering/vulkan/vulkan_textureset.cpp
|
sergeyreznik/et-engine
|
a95fe4b9c5db0e873361f36908de284d0ae4b6d6
|
[
"BSD-3-Clause"
] | 4
|
2015-01-17T01:57:42.000Z
|
2016-07-29T07:49:27.000Z
|
include/et/rendering/vulkan/vulkan_textureset.cpp
|
sergeyreznik/et-engine
|
a95fe4b9c5db0e873361f36908de284d0ae4b6d6
|
[
"BSD-3-Clause"
] | 10
|
2015-01-17T18:46:44.000Z
|
2021-05-21T09:19:13.000Z
|
/*
* This file is part of `et engine`
* Copyright 2009-2016 by Sergey Reznik
* Please, modify content only if you know what are you doing.
*
*/
#pragma once
#include <et/rendering/vulkan/vulkan_textureset.h>
#include <et/rendering/vulkan/vulkan_texture.h>
#include <et/rendering/vulkan/vulkan_sampler.h>
#include <et/rendering/vulkan/vulkan_renderer.h>
#include <et/rendering/vulkan/vulkan.h>
namespace et
{
class VulkanTextureSetPrivate : public VulkanNativeTextureSet
{
public:
VulkanTextureSetPrivate(VulkanState& v) :
vulkan(v) { }
VulkanState& vulkan;
};
VulkanTextureSet::VulkanTextureSet(VulkanRenderer* renderer, VulkanState& vulkan, const Description& desc)
{
ET_PIMPL_INIT(VulkanTextureSet, vulkan);
const uint32_t MaxObjectsCount = 32;
std::array<VkDescriptorSetLayoutBinding, MaxObjectsCount> texturesBindings = {};
std::array<VkWriteDescriptorSet, MaxObjectsCount> texturesWriteSet = {};
std::array<VkDescriptorImageInfo, MaxObjectsCount> texturesInfos = {};
std::array<VkDescriptorSetLayoutBinding, MaxObjectsCount> imagesBindings = {};
std::array<VkWriteDescriptorSet, MaxObjectsCount> imagesWriteSet = {};
std::array<VkDescriptorImageInfo, MaxObjectsCount> imagesInfos = {};
std::array<VkDescriptorSetLayoutBinding, MaxObjectsCount> samplersBindings = {};
std::array<VkWriteDescriptorSet, MaxObjectsCount> samplersWriteSet = {};
std::array<VkDescriptorImageInfo, MaxObjectsCount> samplersInfos = {};
bool allowEmptySet = false;
uint32_t texturesCount = 0;
uint32_t samplersCount = 0;
uint32_t imagesCount = 0;
for (const auto& entry : desc)
{
allowEmptySet |= entry.second.allowEmptySet;
VkShaderStageFlagBits stageFlags = vulkan::programStageValue(entry.first);
for (const auto& e : entry.second.textures)
{
VkDescriptorSetLayoutBinding& binding = texturesBindings[texturesCount];
binding.binding = e.first;
binding.descriptorCount = 1;
binding.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
binding.stageFlags = stageFlags;
VkDescriptorImageInfo& info = texturesInfos[texturesCount];
info.imageView = VulkanTexture::Pointer(e.second.image)->nativeTexture().imageView(e.second.range);
info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
VkWriteDescriptorSet& ws = texturesWriteSet[texturesCount];
ws.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
ws.descriptorCount = binding.descriptorCount;
ws.descriptorType = binding.descriptorType;
ws.dstBinding = binding.binding;
ws.pImageInfo = texturesInfos.data() + texturesCount;
++texturesCount;
ET_ASSERT(texturesCount < MaxObjectsCount);
}
for (const auto& e : entry.second.images)
{
VkDescriptorSetLayoutBinding& binding = imagesBindings[imagesCount];
binding.binding = e.first;
binding.descriptorCount = 1;
binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
binding.stageFlags = stageFlags;
// TODO : use range for images (instead of whole range)
VkDescriptorImageInfo& info = imagesInfos[imagesCount];
info.imageView = VulkanTexture::Pointer(e.second)->nativeTexture().imageView(ResourceRange::whole);
info.imageLayout = VK_IMAGE_LAYOUT_GENERAL;
VkWriteDescriptorSet& ws = imagesWriteSet[imagesCount];
ws.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
ws.descriptorCount = binding.descriptorCount;
ws.descriptorType = binding.descriptorType;
ws.dstBinding = binding.binding;
ws.pImageInfo = imagesInfos.data() + imagesCount;
++imagesCount;
ET_ASSERT(imagesCount < MaxObjectsCount);
}
for (const auto& e : entry.second.samplers)
{
VkDescriptorSetLayoutBinding& binding = samplersBindings[samplersCount];
binding.binding = e.first;
binding.descriptorCount = 1;
binding.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER;
binding.stageFlags = stageFlags;
VkDescriptorImageInfo& info = samplersInfos[samplersCount];
info.sampler = VulkanSampler::Pointer(e.second)->nativeSampler().sampler;
VkWriteDescriptorSet& ws = samplersWriteSet[samplersCount];
ws.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
ws.descriptorCount = binding.descriptorCount;
ws.descriptorType = binding.descriptorType;
ws.dstBinding = binding.binding;
ws.pImageInfo = samplersInfos.data() + samplersCount;
++samplersCount;
ET_ASSERT(samplersCount < MaxObjectsCount);
}
}
if ((imagesCount > 0) || allowEmptySet)
{
VkDescriptorSetLayoutCreateInfo createInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO };
createInfo.bindingCount = imagesCount;
createInfo.pBindings = imagesBindings.data();
VULKAN_CALL(vkCreateDescriptorSetLayout(vulkan.device, &createInfo, nullptr, &_private->imagesSetLayout));
VkDescriptorSetAllocateInfo allocInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO };
allocInfo.descriptorPool = vulkan.descriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &_private->imagesSetLayout;
VULKAN_CALL(vkAllocateDescriptorSets(vulkan.device, &allocInfo, &_private->imagesSet));
for (uint32_t i = 0; i < imagesCount; ++i)
imagesWriteSet[i].dstSet = _private->imagesSet;
vkUpdateDescriptorSets(vulkan.device, imagesCount, imagesWriteSet.data(), 0, nullptr);
}
if ((samplersCount > 0) || allowEmptySet)
{
VkDescriptorSetLayoutCreateInfo createInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO };
createInfo.bindingCount = samplersCount;
createInfo.pBindings = samplersBindings.data();
VULKAN_CALL(vkCreateDescriptorSetLayout(vulkan.device, &createInfo, nullptr, &_private->samplersSetLayout));
VkDescriptorSetAllocateInfo allocInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO };
allocInfo.descriptorPool = vulkan.descriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &_private->samplersSetLayout;
VULKAN_CALL(vkAllocateDescriptorSets(vulkan.device, &allocInfo, &_private->samplersSet));
for (uint32_t i = 0; i < samplersCount; ++i)
samplersWriteSet[i].dstSet = _private->samplersSet;
vkUpdateDescriptorSets(vulkan.device, samplersCount, samplersWriteSet.data(), 0, nullptr);
}
if ((texturesCount > 0) || allowEmptySet)
{
VkDescriptorSetLayoutCreateInfo createInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO };
createInfo.bindingCount = texturesCount;
createInfo.pBindings = texturesBindings.data();
VULKAN_CALL(vkCreateDescriptorSetLayout(vulkan.device, &createInfo, nullptr, &_private->texturesSetLayout));
VkDescriptorSetAllocateInfo allocInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO };
allocInfo.descriptorPool = vulkan.descriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &_private->texturesSetLayout;
VULKAN_CALL(vkAllocateDescriptorSets(vulkan.device, &allocInfo, &_private->texturesSet));
for (uint32_t i = 0; i < texturesCount; ++i)
texturesWriteSet[i].dstSet = _private->texturesSet;
vkUpdateDescriptorSets(vulkan.device, texturesCount, texturesWriteSet.data(), 0, nullptr);
}
}
VulkanTextureSet::~VulkanTextureSet()
{
VULKAN_CALL(vkFreeDescriptorSets(_private->vulkan.device, _private->vulkan.descriptorPool, 1, &_private->texturesSet));
vkDestroyDescriptorSetLayout(_private->vulkan.device, _private->texturesSetLayout, nullptr);
VULKAN_CALL(vkFreeDescriptorSets(_private->vulkan.device, _private->vulkan.descriptorPool, 1, &_private->samplersSet));
vkDestroyDescriptorSetLayout(_private->vulkan.device, _private->samplersSetLayout, nullptr);
VULKAN_CALL(vkFreeDescriptorSets(_private->vulkan.device, _private->vulkan.descriptorPool, 1, &_private->imagesSet));
vkDestroyDescriptorSetLayout(_private->vulkan.device, _private->imagesSetLayout, nullptr);
ET_PIMPL_FINALIZE(VulkanTextureSet);
}
const VulkanNativeTextureSet& VulkanTextureSet::nativeSet() const
{
return *(_private);
}
}
| 38.613861
| 120
| 0.782821
|
sergeyreznik
|
9a317db3c774b45f8f4c3e1a3770092005b5f11b
| 2,482
|
cpp
|
C++
|
lab_01/lab1_fixed.cpp
|
pwestrich/csc_2110
|
ed56c0ccdc7aeb55e6f0711a958b8c1fff691bd5
|
[
"MIT"
] | null | null | null |
lab_01/lab1_fixed.cpp
|
pwestrich/csc_2110
|
ed56c0ccdc7aeb55e6f0711a958b8c1fff691bd5
|
[
"MIT"
] | null | null | null |
lab_01/lab1_fixed.cpp
|
pwestrich/csc_2110
|
ed56c0ccdc7aeb55e6f0711a958b8c1fff691bd5
|
[
"MIT"
] | null | null | null |
// -------------------------------------------------------
//
// lab1.cpp
//
// Program to read a 3 X 3 matrix of integers mat and an integer item, and
// search mat to see if it contains item.
//
// Add your name here and other info requested by your instructor.
//
// -------------------------------------------------------
#include <iostream>
const int SIZE = 3; // Set Matrix size
typedef int Matrix[SIZE][SIZE];
bool matrixSearch(Matrix &mat, int n, int item);
// -------------------------------------------------------
// Search the n X n matrix mat in row-wise order for item.
//
// Precondition:
// Matrix mat is an n X n matrix of integers with n > 0.
// Postcondition:
// True is returned if item is found in mat, else false.
// -------------------------------------------------------
int main()
{
Matrix mat;
// Enter the matrix Matrix mat;
std::cout << "Enter the elements of the " << SIZE << " X " <<
SIZE << " matrix row-wise:" << std::endl;
for (int i = 0; i < SIZE; i++)
for (int j = 0; j < SIZE; j++)
std::cin >> mat[i][j];
// Search mat for various items mt itemToFind;
char response;
int itemToFind;
do {
std::cout << "Enter integer to search for: ";
std::cin >> itemToFind;
if (matrixSearch(mat, SIZE, itemToFind))
std::cout << "item found" << std::endl;
else
std::cout << "item not found" << std::endl;
std::cout << std::endl << "More items to search for (Y or N)? ";
std::cin >> response;
} while (response == 'Y' || response == 'y');
}
//-- (-- Incorrect --) Definition of matrixSearch()
// -------------------------------------------------------
// Search the n X n matrix mat in row-wise order for item
//
// Precondition:
// Matrix mat is an n X n matrix of integers with n > 0.
//
// Postcondition:
// True is returned if item is found in mat, else false.
//
// NOTE:
// mat[row] [col] denotes the entry of the matrix in the
// (horizontal) row numbered row (counting from 0) and the
// (vertical) column numbered col.
// --------------------------------------------------------
bool matrixSearch(Matrix & mat, int n, int item)
{
bool found = false;
for (int row = 0; row < n; row++){
for (int col = 0; col < n; col++) {
if (mat[row][col] == item) {
found = true;
}
}
}
return found;
}
| 30.641975
| 76
| 0.485093
|
pwestrich
|
9a389690742920a2c94fc47c069346cc422bf1d7
| 4,502
|
cpp
|
C++
|
tests/manipulating_values.cpp
|
whiterabbit963/tomlplusplus
|
6b8fa1bef546664b1031d4f0d32c77df5d8d94c1
|
[
"MIT"
] | null | null | null |
tests/manipulating_values.cpp
|
whiterabbit963/tomlplusplus
|
6b8fa1bef546664b1031d4f0d32c77df5d8d94c1
|
[
"MIT"
] | null | null | null |
tests/manipulating_values.cpp
|
whiterabbit963/tomlplusplus
|
6b8fa1bef546664b1031d4f0d32c77df5d8d94c1
|
[
"MIT"
] | null | null | null |
// This file is a part of toml++ and is subject to the the terms of the MIT license.
// Copyright (c) 2019-2020 Mark Gillard <mark.gillard@outlook.com.au>
// See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text.
// SPDX-License-Identifier: MIT
#include "tests.h"
#ifdef _WIN32
TOML_PUSH_WARNINGS
TOML_DISABLE_ALL_WARNINGS
#include <Windows.h>
TOML_POP_WARNINGS
#endif
// TOML_PUSH_WARNINGS
// TOML_DISABLE_ARITHMETIC_WARNINGS
template <typename T>
static constexpr T one = static_cast<T>(1);
TEST_CASE("values - construction")
{
#define CHECK_VALUE_INIT2(initializer, target_type, equiv) \
do { \
auto v = value{ initializer }; \
static_assert(std::is_same_v<decltype(v), value<target_type>>); \
CHECK(v == equiv); \
CHECK(equiv == v); \
CHECK(*v == equiv); \
CHECK(v.get() == equiv); \
} while (false)
#define CHECK_VALUE_INIT(initializer, target_type) \
CHECK_VALUE_INIT2(initializer, target_type, initializer)
CHECK_VALUE_INIT(one<signed char>, int64_t);
CHECK_VALUE_INIT(one<signed short>, int64_t);
CHECK_VALUE_INIT(one<signed int>, int64_t);
CHECK_VALUE_INIT(one<signed long>, int64_t);
CHECK_VALUE_INIT(one<signed long long>, int64_t);
CHECK_VALUE_INIT2(one<unsigned char>, int64_t, 1u);
CHECK_VALUE_INIT2(one<unsigned short>, int64_t, 1u);
CHECK_VALUE_INIT2(one<unsigned int>, int64_t, 1u);
CHECK_VALUE_INIT2(one<unsigned long>, int64_t, 1u);
CHECK_VALUE_INIT2(one<unsigned long long>, int64_t, 1u);
CHECK_VALUE_INIT(true, bool);
CHECK_VALUE_INIT(false, bool);
CHECK_VALUE_INIT("kek", std::string);
CHECK_VALUE_INIT("kek"s, std::string);
CHECK_VALUE_INIT("kek"sv, std::string);
CHECK_VALUE_INIT2("kek"sv.data(), std::string, "kek"sv);
#ifdef __cpp_lib_char8_t
CHECK_VALUE_INIT2(u8"kek", std::string, "kek"sv);
CHECK_VALUE_INIT2(u8"kek"s, std::string, "kek"sv);
CHECK_VALUE_INIT2(u8"kek"sv, std::string, "kek"sv);
CHECK_VALUE_INIT2(u8"kek"sv.data(), std::string, "kek"sv);
#endif
#ifdef _WIN32
CHECK_VALUE_INIT(one<BOOL>, int64_t);
CHECK_VALUE_INIT(one<SHORT>, int64_t);
CHECK_VALUE_INIT(one<INT>, int64_t);
CHECK_VALUE_INIT(one<LONG>, int64_t);
CHECK_VALUE_INIT(one<INT_PTR>, int64_t);
CHECK_VALUE_INIT(one<LONG_PTR>, int64_t);
CHECK_VALUE_INIT2(one<USHORT>, int64_t, 1u);
CHECK_VALUE_INIT2(one<UINT>, int64_t, 1u);
CHECK_VALUE_INIT2(one<ULONG>, int64_t, 1u);
CHECK_VALUE_INIT2(one<UINT_PTR>, int64_t, 1u);
CHECK_VALUE_INIT2(one<ULONG_PTR>, int64_t, 1u);
CHECK_VALUE_INIT2(one<WORD>, int64_t, 1u);
CHECK_VALUE_INIT2(one<DWORD>, int64_t, 1u);
CHECK_VALUE_INIT2(one<DWORD32>, int64_t, 1u);
CHECK_VALUE_INIT2(one<DWORD64>, int64_t, 1u);
CHECK_VALUE_INIT2(one<DWORDLONG>, int64_t, 1u);
#if TOML_WINDOWS_COMPAT
CHECK_VALUE_INIT2(L"kek", std::string, "kek"sv);
CHECK_VALUE_INIT2(L"kek"s, std::string, "kek"sv);
CHECK_VALUE_INIT2(L"kek"sv, std::string, "kek"sv);
CHECK_VALUE_INIT2(L"kek"sv.data(), std::string, "kek"sv);
#endif // TOML_WINDOWS_COMPAT
#endif
}
// TOML_POP_WARNINGS
TEST_CASE("values - printing")
{
static constexpr auto print_value = [](auto&& raw)
{
auto val = toml::value{ std::forward<decltype(raw)>(raw) };
std::stringstream ss;
ss << val;
return ss.str();
};
CHECK(print_value(1) == "1");
CHECK(print_value(1.0f) == "1.0");
CHECK(print_value(1.0) == "1.0");
CHECK(print_value(1.5f) == "1.5");
CHECK(print_value(1.5) == "1.5");
CHECK(print_value(10) == "10");
CHECK(print_value(10.0f) == "10.0");
CHECK(print_value(10.0) == "10.0");
CHECK(print_value(100) == "100");
CHECK(print_value(100.0f) == "100.0");
CHECK(print_value(100.0) == "100.0");
CHECK(print_value(1000) == "1000");
CHECK(print_value(1000.0f) == "1000.0");
CHECK(print_value(1000.0) == "1000.0");
CHECK(print_value(10000) == "10000");
CHECK(print_value(10000.0f) == "10000.0");
CHECK(print_value(10000.0) == "10000.0");
CHECK(print_value(std::numeric_limits<double>::infinity()) == "inf");
CHECK(print_value(-std::numeric_limits<double>::infinity()) == "-inf");
CHECK(print_value(std::numeric_limits<double>::quiet_NaN()) == "nan");
// only integers for large values;
// large floats might get output as scientific notation and that's fine
CHECK(print_value(10000000000) == "10000000000");
CHECK(print_value(100000000000000) == "100000000000000");
}
| 33.849624
| 92
| 0.683696
|
whiterabbit963
|
9a3ba4e009c36026703baa2c7cd1c15a6daabbd1
| 530
|
cpp
|
C++
|
uva/11889_0.cpp
|
larc/competitive_programming
|
deccd7152a14adf217c58546d1cf8ac6b45f1c52
|
[
"MIT"
] | 1
|
2019-05-23T19:05:39.000Z
|
2019-05-23T19:05:39.000Z
|
uva/11889_0.cpp
|
larc/oremor
|
deccd7152a14adf217c58546d1cf8ac6b45f1c52
|
[
"MIT"
] | null | null | null |
uva/11889_0.cpp
|
larc/oremor
|
deccd7152a14adf217c58546d1cf8ac6b45f1c52
|
[
"MIT"
] | null | null | null |
// 11889 - Benefit
#include <cstdio>
int gcd(const int & a, const int & b)
{
if(!b) return a;
return gcd(b, a % b);
}
// gcd and lcm solution
int main()
{
int a, b, c, n;
scanf("%d", &n);
while(n-- && scanf("%d %d", &a, &c))
{
if(c % a != 0) printf("NO SOLUTION\n");
else
{
b = c;
for(int i = 1; i * i <= c; ++i)
if(c % i == 0)
{
if(i < b && (a / gcd(a, i)) * i == c)
b = i;
if(c / i < b && a == gcd(a, c / i) * i)
b = c / i;
}
printf("%d\n", b);
}
}
return 0;
}
| 13.25
| 44
| 0.40566
|
larc
|
9a3dc57ae50cc8948a2e03f3e3e135080d576bb3
| 1,410
|
cpp
|
C++
|
test/SliceTest.cpp
|
jerryzhenleicai/Streams
|
e699eb1767bc96a50098a148eafe4fc09a559d51
|
[
"MIT"
] | 494
|
2015-01-06T14:56:51.000Z
|
2022-01-31T23:09:30.000Z
|
test/SliceTest.cpp
|
jerryzhenleicai/Streams
|
e699eb1767bc96a50098a148eafe4fc09a559d51
|
[
"MIT"
] | 9
|
2015-04-07T15:27:41.000Z
|
2017-01-11T05:54:40.000Z
|
test/SliceTest.cpp
|
jerryzhenleicai/Streams
|
e699eb1767bc96a50098a148eafe4fc09a559d51
|
[
"MIT"
] | 54
|
2018-07-06T02:09:27.000Z
|
2021-11-10T08:42:50.000Z
|
#include <Stream.h>
#include <gmock/gmock.h>
using namespace testing;
using namespace stream;
using namespace stream::op;
TEST(SliceTest, Slice) {
EXPECT_THAT(MakeStream::range(0, 10) | slice(0, 5) | to_vector(),
ElementsAre(0, 1, 2, 3, 4));
EXPECT_THAT(MakeStream::range(0, 10) | slice(2, 8, 2) | to_vector(),
ElementsAre(2, 4, 6));
EXPECT_THAT(MakeStream::range(0, 10) | slice(1, 8, 2) | to_vector(),
ElementsAre(1, 3, 5, 7));
}
TEST(SliceTest, SliceToEnd) {
EXPECT_THAT(MakeStream::range(1, 11) | slice_to_end(5, 2) | to_vector(),
ElementsAre(6, 8, 10));
EXPECT_THAT(MakeStream::range(0, 5) | slice_to_end(7, 10) | to_vector(),
IsEmpty());
}
TEST(SliceTest, Skip) {
EXPECT_THAT(MakeStream::range(1, 8) | skip(3) | to_vector(),
ElementsAre(4, 5, 6, 7));
EXPECT_THAT(MakeStream::range(1, 5) | skip(10) | to_vector(),
IsEmpty());
EXPECT_THAT(MakeStream::empty<int>() | skip(5) | to_vector(),
IsEmpty());
}
TEST(SliceTest, Limit) {
EXPECT_THAT(MakeStream::counter(0) | limit(5) | to_vector(),
ElementsAre(0, 1, 2, 3, 4));
EXPECT_THAT(MakeStream::range(0, 3) | limit(5) | to_vector(),
ElementsAre(0, 1, 2));
EXPECT_THAT(MakeStream::empty<int>() | limit(20) | to_vector(),
IsEmpty());
}
| 33.571429
| 76
| 0.570922
|
jerryzhenleicai
|
9a3f18d4595fd1fa3a7f1e6b3ca075b5012eb67e
| 1,810
|
cc
|
C++
|
ash/accelerators/accelerator_dispatcher_win.cc
|
gavinp/chromium
|
681563ea0f892a051f4ef3d5e53438e0bb7d2261
|
[
"BSD-3-Clause"
] | 1
|
2016-03-10T09:13:57.000Z
|
2016-03-10T09:13:57.000Z
|
ash/accelerators/accelerator_dispatcher_win.cc
|
gavinp/chromium
|
681563ea0f892a051f4ef3d5e53438e0bb7d2261
|
[
"BSD-3-Clause"
] | 1
|
2022-03-13T08:39:05.000Z
|
2022-03-13T08:39:05.000Z
|
ash/accelerators/accelerator_dispatcher_win.cc
|
gavinp/chromium
|
681563ea0f892a051f4ef3d5e53438e0bb7d2261
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/accelerators/accelerator_dispatcher.h"
#include "ash/accelerators/accelerator_controller.h"
#include "ash/ime/event.h"
#include "ash/shell.h"
#include "ui/aura/env.h"
#include "ui/aura/event.h"
#include "ui/aura/root_window.h"
#include "ui/base/accelerators/accelerator.h"
#include "ui/base/events.h"
namespace ash {
namespace {
const int kModifierMask = (ui::EF_SHIFT_DOWN |
ui::EF_CONTROL_DOWN |
ui::EF_ALT_DOWN);
} // namespace
bool AcceleratorDispatcher::Dispatch(const MSG& msg) {
// TODO(oshima): Consolidate win and linux. http://crbug.com/116282
if (!associated_window_)
return false;
if (!ui::IsNoopEvent(msg) && !associated_window_->CanReceiveEvents())
return aura::Env::GetInstance()->GetDispatcher()->Dispatch(msg);
if (msg.message == WM_KEYDOWN || msg.message == WM_SYSKEYDOWN ||
msg.message == WM_KEYUP || msg.message == WM_SYSKEYUP) {
ash::AcceleratorController* accelerator_controller =
ash::Shell::GetInstance()->accelerator_controller();
if (accelerator_controller) {
ui::Accelerator accelerator(ui::KeyboardCodeFromNative(msg),
ui::EventFlagsFromNative(msg) & kModifierMask);
if (msg.message == WM_KEYUP || msg.message == WM_SYSKEYUP)
accelerator.set_type(ui::ET_KEY_RELEASED);
if (accelerator_controller->Process(accelerator))
return true;
accelerator.set_type(TranslatedKeyEvent(msg, false).type());
if (accelerator_controller->Process(accelerator))
return true;
}
}
return nested_dispatcher_->Dispatch(msg);
}
} // namespace ash
| 34.150943
| 73
| 0.69116
|
gavinp
|
9a4001b994da872b3f169344c8f06a215cecc3ec
| 1,058
|
cpp
|
C++
|
MovieRental/main.cpp
|
SonicYeager/CppPractice
|
05b80ac918648ba733ec5fce969eac4b2ae79b58
|
[
"MIT"
] | null | null | null |
MovieRental/main.cpp
|
SonicYeager/CppPractice
|
05b80ac918648ba733ec5fce969eac4b2ae79b58
|
[
"MIT"
] | 9
|
2020-10-26T10:14:46.000Z
|
2020-10-27T12:13:51.000Z
|
MovieRental/main.cpp
|
SonicYeager/CppPractice
|
05b80ac918648ba733ec5fce969eac4b2ae79b58
|
[
"MIT"
] | null | null | null |
#include "Customer.h"
#include <iostream>
#include <sstream>
int main()
{
Customer paul("Paul"), jana("Jana");
paul.AddRental({{"Planet Erde", Movie::REGULAR}, 3});
paul.AddRental({{"Planet der Affen", Movie::NEW_RELEASE}, 5});
paul.AddRental({{"HowTo MAGIX", Movie::NEW_RELEASE}, 1});
jana.AddRental({{"Der kleine Zwerg", Movie::CHILDRENS}, 2});
jana.AddRental({{"Murx der Arzt", Movie::CHILDRENS}, 5});
std::ostringstream out;
out << paul.Statement() << '\n' << jana.Statement() << '\n';
const std::string expected = R"(Rental Record for Paul
Planet Erde 3.5
Planet der Affen 15
HowTo MAGIX 3
Amount owed is 21.5
You earned 4 frequent renter points
Rental Record for Jana
Der kleine Zwerg 1.5
Murx der Arzt 4.5
Amount owed is 6
You earned 2 frequent renter points
)";
const std::string actual = out.str();
if(actual != expected)
{
std::cout << "actual:\n" << actual << "\ndiffers from expected:\n" << expected;
}
else
{
std::cout << "programm runs fine\n";
}
system("pause");
return 0;
}
| 26.45
| 82
| 0.643667
|
SonicYeager
|
9a422b4a5bfcbd31df6cd0e7cb09e588cd3e83cc
| 8,902
|
cpp
|
C++
|
apps/ncv_benchmark_optimizers.cpp
|
0x0all/nanocv
|
dc58dea6b4eb7be2089b168d39c2b02aa2730741
|
[
"MIT"
] | null | null | null |
apps/ncv_benchmark_optimizers.cpp
|
0x0all/nanocv
|
dc58dea6b4eb7be2089b168d39c2b02aa2730741
|
[
"MIT"
] | null | null | null |
apps/ncv_benchmark_optimizers.cpp
|
0x0all/nanocv
|
dc58dea6b4eb7be2089b168d39c2b02aa2730741
|
[
"MIT"
] | 1
|
2018-08-02T02:41:37.000Z
|
2018-08-02T02:41:37.000Z
|
#include "nanocv/timer.h"
#include "nanocv/logger.h"
#include "nanocv/minimize.h"
#include "nanocv/tabulator.h"
#include "nanocv/math/abs.hpp"
#include "nanocv/math/clamp.hpp"
#include "nanocv/math/stats.hpp"
#include "nanocv/math/random.hpp"
#include "nanocv/math/numeric.hpp"
#include "nanocv/math/epsilon.hpp"
#include "nanocv/thread/loopi.hpp"
#include "nanocv/functions/function_trid.h"
#include "nanocv/functions/function_beale.h"
#include "nanocv/functions/function_booth.h"
#include "nanocv/functions/function_sphere.h"
#include "nanocv/functions/function_matyas.h"
#include "nanocv/functions/function_powell.h"
#include "nanocv/functions/function_mccormick.h"
#include "nanocv/functions/function_himmelblau.h"
#include "nanocv/functions/function_rosenbrock.h"
#include "nanocv/functions/function_3hump_camel.h"
#include "nanocv/functions/function_sum_squares.h"
#include "nanocv/functions/function_dixon_price.h"
#include "nanocv/functions/function_goldstein_price.h"
#include "nanocv/functions/function_rotated_ellipsoid.h"
#include <map>
#include <tuple>
using namespace ncv;
const size_t trials = 1024;
struct optimizer_stat_t
{
stats_t<scalar_t> m_time;
stats_t<scalar_t> m_crits;
stats_t<scalar_t> m_fails;
stats_t<scalar_t> m_iters;
stats_t<scalar_t> m_fvals;
stats_t<scalar_t> m_grads;
};
std::map<string_t, optimizer_stat_t> optimizer_stats;
static void check_problem(
const string_t& problem_name,
const opt_opsize_t& fn_size, const opt_opfval_t& fn_fval, const opt_opgrad_t& fn_grad,
const std::vector<std::pair<vector_t, scalar_t>>&)
{
const size_t iterations = 1024;
const scalar_t epsilon = 1e-6;
const size_t dims = fn_size();
// generate fixed random trials
vectors_t x0s;
for (size_t t = 0; t < trials; t ++)
{
random_t<scalar_t> rgen(-1.0, +1.0);
vector_t x0(dims);
rgen(x0.data(), x0.data() + x0.size());
x0s.push_back(x0);
}
// optimizers to try
const auto optimizers =
{
// optim::batch_optimizer::GD,
// optim::batch_optimizer::CGD_CD,
// optim::batch_optimizer::CGD_DY,
// optim::batch_optimizer::CGD_FR,
// optim::batch_optimizer::CGD_HS,
// optim::batch_optimizer::CGD_LS,
// optim::batch_optimizer::CGD_DYCD,
optim::batch_optimizer::CGD_DYHS,
optim::batch_optimizer::CGD_PRP,
optim::batch_optimizer::CGD_N,
optim::batch_optimizer::LBFGS
};
const auto ls_initializers =
{
optim::ls_initializer::unit,
optim::ls_initializer::quadratic,
optim::ls_initializer::consistent
};
const auto ls_strategies =
{
optim::ls_strategy::backtrack_armijo,
optim::ls_strategy::backtrack_wolfe,
optim::ls_strategy::backtrack_strong_wolfe,
optim::ls_strategy::interpolation,
optim::ls_strategy::cg_descent
};
tabulator_t table(text::resize(problem_name, 32));
table.header() << "cost"
<< "time [us]"
<< "|grad|/|fval|"
<< "#fails"
<< "#iters"
<< "#fvals"
<< "#grads";
thread_pool_t pool;
thread_pool_t::mutex_t mutex;
for (optim::batch_optimizer optimizer : optimizers)
for (optim::ls_initializer ls_initializer : ls_initializers)
for (optim::ls_strategy ls_strategy : ls_strategies)
{
stats_t<scalar_t> times;
stats_t<scalar_t> crits;
stats_t<scalar_t> fails;
stats_t<scalar_t> iters;
stats_t<scalar_t> fvals;
stats_t<scalar_t> grads;
thread_loopi(trials, pool, [&] (size_t t)
{
const vector_t& x0 = x0s[t];
// check gradients
const opt_problem_t problem(fn_size, fn_fval, fn_grad);
if (problem.grad_accuracy(x0) > math::epsilon2<scalar_t>())
{
const thread_pool_t::lock_t lock(mutex);
log_error() << "invalid gradient for problem [" << problem_name << "]!";
}
// optimize
const ncv::timer_t timer;
const opt_state_t state = ncv::minimize(
fn_size, fn_fval, fn_grad, nullptr, nullptr, nullptr,
x0, optimizer, iterations, epsilon, ls_initializer, ls_strategy);
const scalar_t crit = state.convergence_criteria();
// update stats
const thread_pool_t::lock_t lock(mutex);
times(timer.microseconds());
crits(crit);
iters(state.n_iterations());
fvals(state.n_fval_calls());
grads(state.n_grad_calls());
fails(!state.converged(epsilon) ? 1.0 : 0.0);
});
// update per-problem table
const string_t name =
text::to_string(optimizer) + "[" +
text::to_string(ls_initializer) + "][" +
text::to_string(ls_strategy) + "]";
table.append(name)
<< static_cast<int>(fvals.sum() + 2 * grads.sum()) / trials
<< times.avg()
<< crits.avg()
<< static_cast<int>(fails.sum())
<< iters.avg()
<< fvals.avg()
<< grads.avg();
// update global statistics
optimizer_stat_t& stat = optimizer_stats[name];
stat.m_time(times.avg());
stat.m_crits(crits.avg());
stat.m_fails(fails.sum());
stat.m_iters(iters.avg());
stat.m_fvals(fvals.avg());
stat.m_grads(grads.avg());
}
// print stats
table.sort_as_number(2, tabulator_t::sorting::ascending);
table.print(std::cout);
}
static void check_problems(const std::vector<ncv::function_t>& funcs)
{
for (const ncv::function_t& func : funcs)
{
check_problem(func.m_name, func.m_opsize, func.m_opfval, func.m_opgrad, func.m_solutions);
}
}
int main(int, char* [])
{
using namespace ncv;
// check_problems(ncv::make_beale_funcs());
check_problems(ncv::make_booth_funcs());
check_problems(ncv::make_matyas_funcs());
check_problems(ncv::make_trid_funcs(128));
check_problems(ncv::make_sphere_funcs(128));
check_problems(ncv::make_powell_funcs(128));
check_problems(ncv::make_mccormick_funcs());
check_problems(ncv::make_himmelblau_funcs());
check_problems(ncv::make_rosenbrock_funcs(7));
check_problems(ncv::make_3hump_camel_funcs());
check_problems(ncv::make_dixon_price_funcs(128));
check_problems(ncv::make_sum_squares_funcs(128));
// check_problems(ncv::make_goldstein_price_funcs());
check_problems(ncv::make_rotated_ellipsoid_funcs(128));
// show global statistics
tabulator_t table(text::resize("optimizer", 32));
table.header() << "cost"
<< "time [us]"
<< "|grad|/|fval|"
<< "#fails"
<< "#iters"
<< "#fvals"
<< "#grads";
for (const auto& it : optimizer_stats)
{
const string_t& name = it.first;
const optimizer_stat_t& stat = it.second;
table.append(name) << static_cast<int>(stat.m_fvals.sum() + 2 * stat.m_grads.sum())
<< stat.m_time.sum()
<< stat.m_crits.avg()
<< static_cast<int>(stat.m_fails.sum())
<< stat.m_iters.sum()
<< stat.m_fvals.sum()
<< stat.m_grads.sum();
}
table.sort_as_number(2, tabulator_t::sorting::ascending);
table.print(std::cout);
// OK
log_info() << done;
return EXIT_SUCCESS;
}
| 36.040486
| 106
| 0.526174
|
0x0all
|
9a44bd53683b19536e69b70574d6793589cbb5aa
| 7,010
|
cc
|
C++
|
components/drive/search_metadata_unittest.cc
|
zealoussnow/chromium
|
fd8a8914ca0183f0add65ae55f04e287543c7d4a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668
|
2015-01-01T01:57:10.000Z
|
2022-03-31T23:33:32.000Z
|
components/drive/search_metadata_unittest.cc
|
zealoussnow/chromium
|
fd8a8914ca0183f0add65ae55f04e287543c7d4a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113
|
2015-05-04T09:58:14.000Z
|
2022-01-31T19:35:03.000Z
|
components/drive/search_metadata_unittest.cc
|
zealoussnow/chromium
|
fd8a8914ca0183f0add65ae55f04e287543c7d4a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941
|
2015-01-02T11:32:21.000Z
|
2022-03-31T16:35:46.000Z
|
// 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.
#include "components/drive/chromeos/search_metadata.h"
#include <stddef.h>
#include <stdint.h>
#include <memory>
#include <vector>
#include "base/i18n/string_search.h"
#include "base/strings/utf_string_conversions.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace drive {
namespace internal {
namespace {
// A simple wrapper for testing FindAndHighlightWrapper(). It just converts the
// query text parameter to FixedPatternStringSearchIgnoringCaseAndAccents.
bool FindAndHighlightWrapper(
const std::string& text,
const std::string& query_text,
std::string* highlighted_text) {
std::vector<std::unique_ptr<
base::i18n::FixedPatternStringSearchIgnoringCaseAndAccents>>
queries;
queries.push_back(std::make_unique<
base::i18n::FixedPatternStringSearchIgnoringCaseAndAccents>(
base::UTF8ToUTF16(query_text)));
return FindAndHighlight(text, queries, highlighted_text);
}
} // namespace
TEST(SearchMetadataSimpleTest, FindAndHighlight_ZeroMatches) {
std::string highlighted_text;
EXPECT_FALSE(FindAndHighlightWrapper("text", "query", &highlighted_text));
}
TEST(SearchMetadataSimpleTest, FindAndHighlight_EmptyText) {
std::string highlighted_text;
EXPECT_FALSE(FindAndHighlightWrapper("", "query", &highlighted_text));
}
TEST(SearchMetadataSimpleTest, FindAndHighlight_EmptyQuery) {
std::vector<std::unique_ptr<
base::i18n::FixedPatternStringSearchIgnoringCaseAndAccents>>
queries;
std::string highlighted_text;
EXPECT_TRUE(FindAndHighlight("hello", queries, &highlighted_text));
EXPECT_EQ("hello", highlighted_text);
}
TEST(SearchMetadataSimpleTest, FindAndHighlight_FullMatch) {
std::string highlighted_text;
EXPECT_TRUE(FindAndHighlightWrapper("hello", "hello", &highlighted_text));
EXPECT_EQ("<b>hello</b>", highlighted_text);
}
TEST(SearchMetadataSimpleTest, FindAndHighlight_StartWith) {
std::string highlighted_text;
EXPECT_TRUE(FindAndHighlightWrapper("hello, world", "hello",
&highlighted_text));
EXPECT_EQ("<b>hello</b>, world", highlighted_text);
}
TEST(SearchMetadataSimpleTest, FindAndHighlight_EndWith) {
std::string highlighted_text;
EXPECT_TRUE(FindAndHighlightWrapper("hello, world", "world",
&highlighted_text));
EXPECT_EQ("hello, <b>world</b>", highlighted_text);
}
TEST(SearchMetadataSimpleTest, FindAndHighlight_InTheMiddle) {
std::string highlighted_text;
EXPECT_TRUE(FindAndHighlightWrapper("yo hello, world", "hello",
&highlighted_text));
EXPECT_EQ("yo <b>hello</b>, world", highlighted_text);
}
TEST(SearchMetadataSimpleTest, FindAndHighlight_MultipeMatches) {
std::string highlighted_text;
EXPECT_TRUE(FindAndHighlightWrapper("yoyoyoyoy", "yoy", &highlighted_text));
// Only the first match is highlighted.
EXPECT_EQ("<b>yoy</b>oyoyoy", highlighted_text);
}
TEST(SearchMetadataSimpleTest, FindAndHighlight_IgnoreCase) {
std::string highlighted_text;
EXPECT_TRUE(FindAndHighlightWrapper("HeLLo", "hello", &highlighted_text));
EXPECT_EQ("<b>HeLLo</b>", highlighted_text);
}
TEST(SearchMetadataSimpleTest, FindAndHighlight_IgnoreCaseNonASCII) {
std::string highlighted_text;
// Case and accent ignorance in Greek. Find "socra" in "Socra'tes".
EXPECT_TRUE(FindAndHighlightWrapper(
"\xCE\xA3\xCF\x89\xCE\xBA\xCF\x81\xCE\xAC\xCF\x84\xCE\xB7\xCF\x82",
"\xCF\x83\xCF\x89\xCE\xBA\xCF\x81\xCE\xB1", &highlighted_text));
EXPECT_EQ(
"<b>\xCE\xA3\xCF\x89\xCE\xBA\xCF\x81\xCE\xAC</b>\xCF\x84\xCE\xB7\xCF\x82",
highlighted_text);
// In Japanese characters.
// Find Hiragana "pi" + "(small)ya" in Katakana "hi" + semi-voiced-mark + "ya"
EXPECT_TRUE(FindAndHighlightWrapper(
"\xE3\x81\xB2\xE3\x82\x9A\xE3\x82\x83\xE3\x83\xBC",
"\xE3\x83\x94\xE3\x83\xA4",
&highlighted_text));
EXPECT_EQ(
"<b>\xE3\x81\xB2\xE3\x82\x9A\xE3\x82\x83</b>\xE3\x83\xBC",
highlighted_text);
}
TEST(SearchMetadataSimpleTest, MultiTextBySingleQuery) {
std::vector<std::unique_ptr<
base::i18n::FixedPatternStringSearchIgnoringCaseAndAccents>>
queries;
queries.push_back(std::make_unique<
base::i18n::FixedPatternStringSearchIgnoringCaseAndAccents>(
u"hello"));
std::string highlighted_text;
EXPECT_TRUE(FindAndHighlight("hello", queries, &highlighted_text));
EXPECT_EQ("<b>hello</b>", highlighted_text);
EXPECT_FALSE(FindAndHighlight("goodbye", queries, &highlighted_text));
EXPECT_TRUE(FindAndHighlight("1hello2", queries, &highlighted_text));
EXPECT_EQ("1<b>hello</b>2", highlighted_text);
}
TEST(SearchMetadataSimpleTest, FindAndHighlight_MetaChars) {
std::string highlighted_text;
EXPECT_TRUE(FindAndHighlightWrapper("<hello>", "hello", &highlighted_text));
EXPECT_EQ("<<b>hello</b>>", highlighted_text);
}
TEST(SearchMetadataSimpleTest, FindAndHighlight_MoreMetaChars) {
std::string highlighted_text;
EXPECT_TRUE(FindAndHighlightWrapper("a&b&c&d", "b&c", &highlighted_text));
EXPECT_EQ("a&<b>b&c</b>&d", highlighted_text);
}
TEST(SearchMetadataSimpleTest, FindAndHighlight_SurrogatePair) {
std::string highlighted_text;
// \xF0\x9F\x98\x81 (U+1F601) is a surrogate pair for smile icon of emoji.
EXPECT_TRUE(FindAndHighlightWrapper("hi\xF0\x9F\x98\x81hello",
"i\xF0\x9F\x98\x81", &highlighted_text));
EXPECT_EQ("h<b>i\xF0\x9F\x98\x81</b>hello", highlighted_text);
}
TEST(SearchMetadataSimpleTest, FindAndHighlight_MultipleQueries) {
std::vector<std::unique_ptr<
base::i18n::FixedPatternStringSearchIgnoringCaseAndAccents>>
queries;
queries.push_back(std::make_unique<
base::i18n::FixedPatternStringSearchIgnoringCaseAndAccents>(
u"hello"));
queries.push_back(
std::make_unique<
base::i18n::FixedPatternStringSearchIgnoringCaseAndAccents>(u"good"));
std::string highlighted_text;
EXPECT_TRUE(
FindAndHighlight("good morning, hello", queries, &highlighted_text));
EXPECT_EQ("<b>good</b> morning, <b>hello</b>", highlighted_text);
}
TEST(SearchMetadataSimpleTest, FindAndHighlight_OverlappingHighlights) {
std::vector<std::unique_ptr<
base::i18n::FixedPatternStringSearchIgnoringCaseAndAccents>>
queries;
queries.push_back(std::make_unique<
base::i18n::FixedPatternStringSearchIgnoringCaseAndAccents>(
u"morning"));
queries.push_back(
std::make_unique<
base::i18n::FixedPatternStringSearchIgnoringCaseAndAccents>(u"ing,"));
std::string highlighted_text;
EXPECT_TRUE(
FindAndHighlight("good morning, hello", queries, &highlighted_text));
EXPECT_EQ("good <b>morning,</b> hello", highlighted_text);
}
} // namespace internal
} // namespace drive
| 36.321244
| 80
| 0.727817
|
zealoussnow
|
9a487b9a7ccac9f34b2618dcad4491cc3fcc14ec
| 5,047
|
cpp
|
C++
|
ares/fc/cartridge/board/konami-vrc2.cpp
|
moon-chilled/Ares
|
909fb098c292f8336d0502dc677050312d8b5c81
|
[
"0BSD"
] | 7
|
2020-07-25T11:44:39.000Z
|
2021-01-29T13:21:31.000Z
|
ares/fc/cartridge/board/konami-vrc2.cpp
|
jchw-forks/ares
|
d78298a1e95fd0ce65feabfd4f13b60e31210a7a
|
[
"0BSD"
] | null | null | null |
ares/fc/cartridge/board/konami-vrc2.cpp
|
jchw-forks/ares
|
d78298a1e95fd0ce65feabfd4f13b60e31210a7a
|
[
"0BSD"
] | 1
|
2021-03-22T16:15:30.000Z
|
2021-03-22T16:15:30.000Z
|
struct KonamiVRC2 : Interface {
Memory::Readable<uint8> programROM;
Memory::Writable<uint8> programRAM;
Memory::Readable<uint8> characterROM;
Memory::Writable<uint8> characterRAM;
using Interface::Interface;
auto load(Markup::Node document) -> void override {
auto board = document["game/board"];
Interface::load(programROM, board["memory(type=ROM,content=Program)"]);
Interface::load(programRAM, board["memory(type=RAM,content=Save)"]);
Interface::load(characterROM, board["memory(type=ROM,content=Character)"]);
Interface::load(characterRAM, board["memory(type=RAM,content=Character)"]);
pinA0 = 1 << board["chip(type=VRC2)/pinout/a0"].natural();
pinA1 = 1 << board["chip(type=VRC2)/pinout/a1"].natural();
}
auto save(Markup::Node document) -> void override {
auto board = document["game/board"];
Interface::save(programRAM, board["memory(type=RAM,content=Save)"]);
Interface::save(characterRAM, board["memory(type=RAM,content=Character)"]);
}
auto readPRG(uint address) -> uint8 {
if(address < 0x6000) return cpu.mdr();
if(address < 0x8000) {
if(!programRAM && (address & 0xf000) == 0x6000) return cpu.mdr() | latch;
if(!programRAM) return cpu.mdr();
return programRAM.read((uint13)address);
}
uint5 bank, banks = programROM.size() >> 13;
switch(address & 0xe000) {
case 0x8000: bank = programBank[0]; break;
case 0xa000: bank = programBank[1]; break;
case 0xc000: bank = banks - 2; break;
case 0xe000: bank = banks - 1; break;
}
address = bank << 13 | (uint13)address;
return programROM.read(address);
}
auto writePRG(uint address, uint8 data) -> void {
if(address < 0x6000) return;
if(address < 0x8000) {
if(!programRAM && (address & 0xf000) == 0x6000) latch = data.bit(0);
if(!programRAM) return;
return programRAM.write((uint13)address, data);
}
bool a0 = address & pinA0;
bool a1 = address & pinA1;
address &= 0xf000;
address |= a0 << 0 | a1 << 1;
switch(address) {
case 0x8000: case 0x8001: case 0x8002: case 0x8003:
programBank[0] = data.bit(0,4);
break;
case 0x9000: case 0x9001: case 0x9002: case 0x9003:
mirror = data.bit(0,1);
break;
case 0xa000: case 0xa001: case 0xa002: case 0xa003:
programBank[1] = data.bit(0,4);
break;
case 0xb000: characterBank[0].bit(0,3) = data.bit(0,3); break;
case 0xb001: characterBank[0].bit(4,7) = data.bit(0,3); break;
case 0xb002: characterBank[1].bit(0,3) = data.bit(0,3); break;
case 0xb003: characterBank[1].bit(4,7) = data.bit(0,3); break;
case 0xc000: characterBank[2].bit(0,3) = data.bit(0,3); break;
case 0xc001: characterBank[2].bit(4,7) = data.bit(0,3); break;
case 0xc002: characterBank[3].bit(0,3) = data.bit(0,3); break;
case 0xc003: characterBank[3].bit(4,7) = data.bit(0,3); break;
case 0xd000: characterBank[4].bit(0,3) = data.bit(0,3); break;
case 0xd001: characterBank[4].bit(4,7) = data.bit(0,3); break;
case 0xd002: characterBank[5].bit(0,3) = data.bit(0,3); break;
case 0xd003: characterBank[5].bit(4,7) = data.bit(0,3); break;
case 0xe000: characterBank[6].bit(0,3) = data.bit(0,3); break;
case 0xe001: characterBank[6].bit(4,7) = data.bit(0,3); break;
case 0xe002: characterBank[7].bit(0,3) = data.bit(0,3); break;
case 0xe003: characterBank[7].bit(4,7) = data.bit(0,3); break;
}
}
auto addressCIRAM(uint address) const -> uint {
switch(mirror) {
case 0: return address >> 0 & 0x0400 | address & 0x03ff; //vertical mirroring
case 1: return address >> 1 & 0x0400 | address & 0x03ff; //horizontal mirroring
case 2: return 0x0000 | address & 0x03ff; //one-screen mirroring (first)
case 3: return 0x0400 | address & 0x03ff; //one-screen mirroring (second)
}
unreachable;
}
auto addressCHR(uint address) const -> uint {
uint8 bank = characterBank[address >> 10];
return bank << 10 | (uint10)address;
}
auto readCHR(uint address) -> uint8 {
if(address & 0x2000) return ppu.readCIRAM(addressCIRAM(address));
if(characterROM) return characterROM.read(addressCHR(address));
if(characterRAM) return characterRAM.read(addressCHR(address));
return 0x00;
}
auto writeCHR(uint address, uint8 data) -> void {
if(address & 0x2000) return ppu.writeCIRAM(addressCIRAM(address), data);
if(characterRAM) return characterRAM.write(addressCHR(address), data);
}
auto power() -> void {
for(auto& bank : programBank) bank = 0;
for(auto& bank : characterBank) bank = 0;
mirror = 0;
latch = 0;
}
auto serialize(serializer& s) -> void {
programRAM.serialize(s);
characterRAM.serialize(s);
s.integer(pinA0);
s.integer(pinA1);
s.array(programBank);
s.array(characterBank);
s.integer(mirror);
s.integer(latch);
}
uint8 pinA0;
uint8 pinA1;
uint5 programBank[2];
uint8 characterBank[8];
uint2 mirror;
uint1 latch;
};
| 36.05
| 93
| 0.644938
|
moon-chilled
|
9a487e6564783f51cf469c2a1abd163251228c67
| 8,829
|
cpp
|
C++
|
QuantLib-Ext/qlext/termstructures/yield/ratehelpers.cpp
|
ChinaQuants/qlengine
|
6f40f8204df9b5c46eec6c6bb5cae6cde9b1455d
|
[
"BSD-3-Clause"
] | 17
|
2017-09-24T13:25:43.000Z
|
2021-08-31T13:14:45.000Z
|
QuantLib-Ext/qlext/termstructures/yield/ratehelpers.cpp
|
Bralzer/ExoticOptionPriceEngine
|
55650eee29b054b2e3d5083eb42a81419960901f
|
[
"BSD-3-Clause"
] | null | null | null |
QuantLib-Ext/qlext/termstructures/yield/ratehelpers.cpp
|
Bralzer/ExoticOptionPriceEngine
|
55650eee29b054b2e3d5083eb42a81419960901f
|
[
"BSD-3-Clause"
] | 6
|
2017-09-25T01:29:35.000Z
|
2021-09-01T05:14:17.000Z
|
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2017 Cheng Li
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
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 license for more details.
*/
#include <boost/make_shared.hpp>
#include <ql/cashflows/iborcoupon.hpp>
#include <ql/indexes/ibor/shibor.hpp>
#include <ql/pricingengines/swap/discountingswapengine.hpp>
#include <ql/time/calendars/china.hpp>
#include <ql/utilities/null_deleter.hpp>
#include <qlext/instruments/shiborswap.hpp>
#include <qlext/instruments/subperiodsswap.hpp>
#include <qlext/termstructures/yield/ratehelpers.hpp>
namespace QuantLib {
ShiborSwapRateHelper::ShiborSwapRateHelper(const Handle<Quote>& rate, const Period& swapTenor, Frequency fixedFreq,
const boost::shared_ptr<Shibor>& shiborIndex, const Period& fwdStart,
const Handle<YieldTermStructure>& discountingCurve)
: RelativeDateRateHelper(rate), tenor_(swapTenor), fixedFrequency_(fixedFreq), fwdStart_(fwdStart),
discountHandle_(discountingCurve) {
settlementDays_ = shiborIndex->fixingDays();
shiborIndex_ = boost::dynamic_pointer_cast<Shibor>(shiborIndex->clone(termStructureHandle_));
shiborIndex_->unregisterWith(termStructureHandle_);
registerWith(shiborIndex_);
registerWith(discountHandle_);
initializeDates();
}
void ShiborSwapRateHelper::initializeDates() {
Date refDate = Settings::instance().evaluationDate();
China floatCalendar(China::IB);
refDate = floatCalendar.adjust(refDate);
Date spotDate = floatCalendar.advance(refDate, settlementDays_ * Days);
Date startDate = spotDate + fwdStart_;
if (fwdStart_.length() < 0)
startDate = floatCalendar.adjust(startDate, Preceding);
else
startDate = floatCalendar.adjust(startDate, Following);
swap_ = boost::make_shared<ShiborSwap>(VanillaSwap::Payer, 1., startDate, tenor_, Period(fixedFrequency_), 0.,
shiborIndex_);
bool includeSettlementDateFlows = false;
boost::shared_ptr<PricingEngine> engine(
new DiscountingSwapEngine(discountRelinkableHandle_, includeSettlementDateFlows));
swap_->setPricingEngine(engine);
earliestDate_ = swap_->startDate();
maturityDate_ = swap_->maturityDate();
boost::shared_ptr<IborCoupon> lastCoupon = boost::dynamic_pointer_cast<IborCoupon>(swap_->floatingLeg().back());
latestRelevantDate_ = std::max(maturityDate_, lastCoupon->fixingEndDate());
latestDate_ = maturityDate_;
}
void ShiborSwapRateHelper::accept(AcyclicVisitor& v) {
Visitor<ShiborSwapRateHelper>* v1 = dynamic_cast<Visitor<ShiborSwapRateHelper>*>(&v);
if (v1 != 0)
v1->visit(*this);
else
RateHelper::accept(v);
}
Real ShiborSwapRateHelper::impliedQuote() const {
QL_REQUIRE(termStructure_ != 0, "term structure not set");
// we didn't register as observers - force calculation
swap_->recalculate();
// weak implementation... to be improved
static const Spread basisPoint = 1.0e-4;
Real floatingLegNPV = swap_->floatingLegNPV();
Real totNPV = -floatingLegNPV;
Real result = totNPV / (swap_->fixedLegBPS() / basisPoint);
return result;
}
void ShiborSwapRateHelper::setTermStructure(YieldTermStructure* t) {
// do not set the relinkable handle as an observer -
// force recalculation when needed---the index is not lazy
bool observer = false;
boost::shared_ptr<YieldTermStructure> temp(t, null_deleter());
termStructureHandle_.linkTo(temp, observer);
if (discountHandle_.empty())
discountRelinkableHandle_.linkTo(temp, observer);
else
discountRelinkableHandle_.linkTo(*discountHandle_, observer);
RelativeDateRateHelper::setTermStructure(t);
}
SubPeriodsSwapRateHelper::SubPeriodsSwapRateHelper(
const Handle<Quote>& rate, const Period& swapTenor, Frequency fixedFreq, const Calendar& fixedCalendar,
const DayCounter& fixedDayCount, BusinessDayConvention fixedConvention, const Period& floatPayTenor,
const boost::shared_ptr<IborIndex>& iborIndex, const DayCounter& floatingDayCount, DateGeneration::Rule rule,
Ext::SubPeriodsCoupon::Type type, const Period& fwdStart, const Handle<YieldTermStructure>& discountingCurve)
: RelativeDateRateHelper(rate), tenor_(swapTenor), fixedFrequency_(fixedFreq), fixedCalendar_(fixedCalendar),
fixedDayCount_(fixedDayCount), fixedConvention_(fixedConvention), floatPayTenor_(floatPayTenor),
floatingDayCount_(floatingDayCount), rule_(rule), type_(type), fwdStart_(fwdStart),
discountHandle_(discountingCurve) {
settlementDays_ = iborIndex->fixingDays();
iborIndex_ = boost::dynamic_pointer_cast<IborIndex>(iborIndex->clone(termStructureHandle_));
iborIndex_->unregisterWith(termStructureHandle_);
registerWith(iborIndex_);
registerWith(discountHandle_);
initializeDates();
}
void SubPeriodsSwapRateHelper::initializeDates() {
Date refDate = Settings::instance().evaluationDate();
Calendar floatCalendar = iborIndex_->fixingCalendar();
refDate = floatCalendar.adjust(refDate);
Date spotDate = floatCalendar.advance(refDate, settlementDays_ * Days);
Date startDate = spotDate + fwdStart_;
if (fwdStart_.length() < 0)
startDate = floatCalendar.adjust(startDate, Preceding);
else
startDate = floatCalendar.adjust(startDate, Following);
swap_ = boost::shared_ptr<SubPeriodsSwap>(new SubPeriodsSwap(startDate, 1., tenor_, true, Period(fixedFrequency_), 0.,
fixedCalendar_, fixedDayCount_, fixedConvention_, floatPayTenor_,
iborIndex_, floatingDayCount_, rule_, type_));
bool includeSettlementDateFlows = false;
boost::shared_ptr<PricingEngine> engine(
new DiscountingSwapEngine(discountRelinkableHandle_, includeSettlementDateFlows));
swap_->setPricingEngine(engine);
earliestDate_ = swap_->startDate();
maturityDate_ = swap_->maturityDate();
Leg floatLeg = swap_->floatLeg();
boost::shared_ptr<Ext::SubPeriodsCoupon> lastCoupon =
boost::dynamic_pointer_cast<Ext::SubPeriodsCoupon>(floatLeg[floatLeg.size() - 1]);
latestRelevantDate_ = std::max(latestDate_, lastCoupon->latestRelevantDate());
latestDate_ = maturityDate_;
}
void SubPeriodsSwapRateHelper::accept(AcyclicVisitor& v) {
Visitor<SubPeriodsSwapRateHelper>* v1 = dynamic_cast<Visitor<SubPeriodsSwapRateHelper>*>(&v);
if (v1 != 0)
v1->visit(*this);
else
RateHelper::accept(v);
}
Real SubPeriodsSwapRateHelper::impliedQuote() const {
QL_REQUIRE(termStructure_ != 0, "term structure not set");
// we didn't register as observers - force calculation
swap_->recalculate();
// weak implementation... to be improved
static const Spread basisPoint = 1.0e-4;
Real floatingLegNPV = swap_->floatLegNPV();
Real totNPV = -floatingLegNPV;
Real result = totNPV / (swap_->fixedLegBPS() / basisPoint);
return result;
}
void SubPeriodsSwapRateHelper::setTermStructure(YieldTermStructure* t) {
// do not set the relinkable handle as an observer -
// force recalculation when needed---the index is not lazy
bool observer = false;
boost::shared_ptr<YieldTermStructure> temp(t, null_deleter());
termStructureHandle_.linkTo(temp, observer);
if (discountHandle_.empty())
discountRelinkableHandle_.linkTo(temp, observer);
else
discountRelinkableHandle_.linkTo(*discountHandle_, observer);
RelativeDateRateHelper::setTermStructure(t);
}
} // namespace QuantLib
| 42.859223
| 126
| 0.680372
|
ChinaQuants
|
9a4d816ed7e9a880ed798674b6969d2a8b5aa9a7
| 4,079
|
cpp
|
C++
|
user/tests/wiring/no_fixture/system.cpp
|
zsoltmazlo/indoor-controller2
|
5fde9f40b30d087af03f6cccdb97821719941955
|
[
"MIT"
] | 1
|
2019-02-24T07:13:51.000Z
|
2019-02-24T07:13:51.000Z
|
user/tests/wiring/no_fixture/system.cpp
|
zsoltmazlo/indoor-controller2
|
5fde9f40b30d087af03f6cccdb97821719941955
|
[
"MIT"
] | 1
|
2018-05-29T19:27:53.000Z
|
2018-05-29T19:27:53.000Z
|
user/tests/wiring/no_fixture/system.cpp
|
zsoltmazlo/indoor-controller2
|
5fde9f40b30d087af03f6cccdb97821719941955
|
[
"MIT"
] | null | null | null |
#include "application.h"
#include "unit-test/unit-test.h"
#if PLATFORM_ID >= 3
test(SYSTEM_01_freeMemory)
{
// this test didn't work on the core attempting to allocate the current value of
// freeMemory(), presumably because of fragmented heap from
// relatively large allocations during the handshake, so the request was satisfied
// without calling _sbrk()
// 4096 was chosen to be small enough to allocate, but large enough to force _sbrk() to be called.)
uint32_t free1 = System.freeMemory();
if (free1>128) {
void* m1 = malloc(1024*6);
uint32_t free2 = System.freeMemory();
free(m1);
assertLess(free2, free1);
}
}
#endif
test(SYSTEM_02_version)
{
uint32_t versionNumber = System.versionNumber();
// Serial.println(System.versionNumber()); // 328193 -> 0x00050201
// Serial.println(System.version().c_str()); // 0.5.2-rc.1
char expected[20];
if (SYSTEM_VERSION & 0xFF)
sprintf(expected, "%d.%d.%d-rc.%d", (int)BYTE_N(versionNumber,3), (int)BYTE_N(versionNumber,2), (int)BYTE_N(versionNumber,1), (int)BYTE_N(versionNumber,0));
else
sprintf(expected, "%d.%d.%d", (int)BYTE_N(versionNumber,3), (int)BYTE_N(versionNumber,2), (int)BYTE_N(versionNumber,1));
assertTrue(strcmp(expected,System.version().c_str())==0);
}
// todo - use platform feature flags
#if defined(STM32F2XX)
// subtract 4 bytes for signature (3068 bytes)
#define USER_BACKUP_RAM ((1024*3)-4)
#endif // defined(STM32F2XX)
#if defined(USER_BACKUP_RAM)
STARTUP(System.enableFeature(FEATURE_RETAINED_MEMORY));
static retained uint8_t app_backup[USER_BACKUP_RAM];
static uint8_t app_ram[USER_BACKUP_RAM];
test(SYSTEM_03_user_backup_ram)
{
int total_backup = 0;
int total_ram = 0;
for (unsigned i=0; i<(sizeof(app_backup)/sizeof(app_backup[0])); i++) {
app_backup[i] = 1;
app_ram[i] = 1;
total_backup += app_backup[i];
total_ram += app_ram[i];
}
// Serial.printlnf("app_backup(0x%x), app_ram(0x%x)", &app_backup, &app_ram);
// Serial.printlnf("total_backup: %d, total_ram: %d", total_backup, total_ram);
assertTrue(total_backup==(USER_BACKUP_RAM));
assertTrue(total_ram==(USER_BACKUP_RAM));
if (int(&app_backup) < 0x40024000) {
Serial.printlnf("ERROR: expected app_backup in user backup memory, but was at %x", &app_backup);
}
assertTrue(int(&app_backup)>=0x40024000);
if (int(&app_ram) >= 0x40024000) {
Serial.printlnf("ERROR: expected app_ram in user sram memory, but was at %x", &app_ram);
}
assertTrue(int(&app_ram)<0x40024000);
}
#endif // defined(USER_BACKUP_RAM)
#if defined(BUTTON1_MIRROR_SUPPORTED)
static int s_button_clicks = 0;
static void onButtonClick(system_event_t ev, int data) {
s_button_clicks = data;
}
test(SYSTEM_04_button_mirror)
{
// Known bug:
// events posted from an ISR might not be delivered to the application queue
// when threading is enabled
if (system_thread_get_state(nullptr) == spark::feature::ENABLED) {
skip();
return;
}
System.buttonMirror(D1, FALLING, false);
auto pinmap = HAL_Pin_Map();
System.on(button_click, onButtonClick);
// "Click" setup button 3 times
// First click
pinMode(D1, INPUT_PULLDOWN);
// Just in case manually trigger EXTI interrupt
EXTI_GenerateSWInterrupt(pinmap[D1].gpio_pin);
delay(300);
pinMode(D1, INPUT_PULLUP);
delay(100);
// Second click
pinMode(D1, INPUT_PULLDOWN);
// Just in case manually trigger EXTI interrupt
EXTI_GenerateSWInterrupt(pinmap[D1].gpio_pin);
delay(300);
pinMode(D1, INPUT_PULLUP);
delay(100);
// Third click
pinMode(D1, INPUT_PULLDOWN);
// Just in case manually trigger EXTI interrupt
EXTI_GenerateSWInterrupt(pinmap[D1].gpio_pin);
delay(300);
pinMode(D1, INPUT_PULLUP);
delay(300);
assertEqual(s_button_clicks, 3);
}
test(SYSTEM_05_button_mirror_disable)
{
System.disableButtonMirror(false);
}
#endif // defined(BUTTON1_MIRROR_SUPPORTED)
| 31.137405
| 164
| 0.683256
|
zsoltmazlo
|
9a51c4f477a971b0aac14e517d23c8ae2cd5a1a5
| 6,234
|
hpp
|
C++
|
ModelData/InstableCPUcoreOperationDetection.hpp
|
st-gb/CPUinfoAndControl
|
5e93d4a195b4692d147bb05cfef534e38d7f8b64
|
[
"MIT"
] | null | null | null |
ModelData/InstableCPUcoreOperationDetection.hpp
|
st-gb/CPUinfoAndControl
|
5e93d4a195b4692d147bb05cfef534e38d7f8b64
|
[
"MIT"
] | null | null | null |
ModelData/InstableCPUcoreOperationDetection.hpp
|
st-gb/CPUinfoAndControl
|
5e93d4a195b4692d147bb05cfef534e38d7f8b64
|
[
"MIT"
] | 1
|
2021-07-16T21:01:26.000Z
|
2021-07-16T21:01:26.000Z
|
/*
* InstableCPUcoreOperationDetection.hpp
*
* Created on: 22.04.2012
* Author: Stefan
*/
#ifndef INSTABLECPUCOREVOLTAGEDETECTION_HPP_
#define INSTABLECPUCOREVOLTAGEDETECTION_HPP_
//#include "VoltageAndFreq.hpp" //class VoltageAndFreq
#include <Controller/multithread/thread_type.hpp>
//THREAD_PROC_CALLING_CONVENTION
#include <preprocessor_macros/thread_proc_calling_convention.h>
#include <preprocessor_macros/logging_preprocessor_macros.h>
//struct external_caller, StartInstableVoltageDetectionFunctionPointer,
// StopInstableVoltageDetectionFunctionPointer
#include <InstableCPUcoreVoltageDefintions.h>
#include <UserInterface/UserInterface.hpp>
#include <Controller/multithread/condition_type.hpp>
//#include ""
//Forward decl.
class CPUcoreData;
class I_CPUcontroller;
/** Used for displaying the progress of finding the lowest voltage for an
* instable CPU operation detection status in GUI. */
struct InstableCPUoperationDetectionData
{
//protected:
public:
unsigned m_secondsUntilCPUcoreVoltageDecrease;
float m_fCPUcoreUsageOfDynLibThread;
};
class wxX86InfoAndControlApp;
class InstableCPUcoreOperationDetection
: public InstableCPUoperationDetectionData
{
public:
/** Set to true if executable was called by instable CPU core op detection dyn lib */
volatile bool m_bVoltageWasTooLowCalled;
volatile bool m_bStopFindingLowestStableCPUcoreVoltageRequestedViaUI;
//Is set to true when "VoltageTooLow" was called.
volatile bool m_vbExitFindLowestStableVoltage;
static InstableCPUcoreOperationDetection * s_p_instableCPUcoreOperationDetection;
uint32_t m_ui32CPUcoreMask;
CPUcoreData & m_r_cpucoredata;
I_CPUcontroller * m_p_cpucontroller;
// float m_fCPUcoreUsageOfDynLibThread;
/** Use unsigned datatype because same bit width as CPU arch.->fast. */
unsigned m_secondsUntilVoltageDecrease;
unsigned m_milliSecondsToWaitBeforeSecondsCountDown;
#ifdef _WIN32
//TODO replace with wxDynLib
typedef HMODULE dynlibType;
#else
typedef int dynlibType;
#endif
typedef wxX86InfoAndControlApp userinterface_type;
//UserInterface * m_p_userinterface;
userinterface_type * m_p_userinterface;
dynlibType m_hmoduleUnstableVoltageDetectionDynLib;
StartInstableVoltageDetectionFunctionPointer
m_pfnStartInstableCPUcoreVoltageDetection;
StopInstableVoltageDetectionFunctionPointer
m_pfnStopInstableCPUcoreVoltageDetection;
struct external_caller m_external_caller;
condition_type m_conditionFindLowestStableVoltage;
//http://forums.wxwidgets.org/viewtopic.php?t=4824:
// wxMutex m_wxmutexFindLowestStableVoltage;
// wxCondition m_wxconditionFindLowestStableVoltage;
x86IandC::thread_type m_x86iandc_threadFindLowestStableVoltage;
x86IandC::thread_type m_x86iandc_threadFindLowestStableCPUcoreOperationInDLL;
unsigned m_uiNumberOfSecondsToWaitUntilVoltageIsReduced;
//std::wstring m_std_wstrInstableCPUcoreVoltageDynLibPath;
std::wstring m_std_wstrDynLibPath;
// VoltageAndFreq m_lastSetVoltageAndFreq;
//TODO if the reference clock changes after starting to find an unstable
//CPU core voltage then (if the ref. clock in heightened) it can be still
//instable. But on the other hand: if the calculation of the ref. clock is
//inaccurate then it is better to set to the same multiplier as at start of
//find lowest voltage.
//Use separate values for both multi and ref clock rather than a single
//composed value for the frequency. because the mult
float m_lastSetCPUcoreMultiplier;
float m_lastSetCPUcoreVoltageInVolt;
float m_fReferenceClockInMHz;
/** min CPU core usage for unstable CPU operation detection thread needed */
float m_fMinCPUcoreUsage;
InstableCPUcoreOperationDetection(/*UserInterface * p_ui*/
CPUcoreData & r_cpucoredata);
/** Must be virtual because else g++ warning:
* `class InstableCPUcoreOperationDetection' has virtual functions
* but non-virtual destructor */
virtual ~InstableCPUcoreOperationDetection() {}
void CountSecondsDown();
float DecreaseVoltageStepByStep(
unsigned wCPUcoreVoltageArrayIndex, const float fMultiplier);
bool DynLibAccessInitialized()
{
return m_hmoduleUnstableVoltageDetectionDynLib &&
m_pfnStartInstableCPUcoreVoltageDetection &&
m_pfnStopInstableCPUcoreVoltageDetection;
}
void ExitFindLowestStableVoltageThread()
{
//Exit the "find lowest stable voltage" thread.
m_vbExitFindLowestStableVoltage = true;
// wxGetApp().m_wxconditionFindLowestStableVoltage.Signal();
LOGN( "signalling the condition to end finding the"
" lowest stable voltage thread")
//Wake up all threads waiting on the condition.
m_conditionFindLowestStableVoltage.Broadcast();
LOGN( "after signalling the condition to end finding the"
" lowest stable voltage thread")
}
virtual dynlibType LoadDynLib() = 0;
bool DynLibSuccessFullyLoaded()
{
return m_hmoduleUnstableVoltageDetectionDynLib != NULL;
}
static DWORD THREAD_PROC_CALLING_CONVENTION FindLowestStableVoltage_ThreadProc(
void * p_v );
DWORD FindLowestStableVoltage();
virtual /*ULONG64*/ unsigned long long GetThreadUserModeStartTime(/*void **/) = 0;
virtual float GetCPUcoreUsageForDynLibThread() = 0;
void HandleVoltageTooLow();
bool IsRunning()
{
return m_x86iandc_threadFindLowestStableVoltage.IsRunning();
}
void SetStopRequestedViaGUI(bool b)
{
m_bStopFindingLowestStableCPUcoreVoltageRequestedViaUI = b;
}
void SetUserInterface(/*UserInterface * p_ui*/ userinterface_type * p_ui);
const x86IandC::thread_type & StartInDynLibInSeparateThread();
void StartInDynLib(/*uint16_t m_ui32CPUcoreMask*/);
/** Must be static as thread proc. */
static DWORD THREAD_PROC_CALLING_CONVENTION
StartInDynLib_ThreadProc(void * p_v );
void Stop();
virtual void UnloadDynLib() = 0;
void ShowMessage(const wchar_t * const msg);
BYTE Start();
virtual StartInstableVoltageDetectionFunctionPointer AssignStartFunctionPointer() = 0;
virtual StopInstableVoltageDetectionFunctionPointer AssignStopFunctionPointer() = 0;
/** Called by "instable CPU core operation" dyn lib */
static void VoltageTooLow();
};
#endif /* INSTABLECPUCOREVOLTAGEDETECTION_HPP_ */
| 34.441989
| 88
| 0.796118
|
st-gb
|
9a5463c61acadf9034e5c0698b86f19004fbdeb8
| 949
|
cpp
|
C++
|
graphics-library/src/illumination/directional_light.cpp
|
thetorine/opengl3-library
|
3904d857fd1085ba2c57c4289eb0e0d123f11a14
|
[
"MIT"
] | null | null | null |
graphics-library/src/illumination/directional_light.cpp
|
thetorine/opengl3-library
|
3904d857fd1085ba2c57c4289eb0e0d123f11a14
|
[
"MIT"
] | null | null | null |
graphics-library/src/illumination/directional_light.cpp
|
thetorine/opengl3-library
|
3904d857fd1085ba2c57c4289eb0e0d123f11a14
|
[
"MIT"
] | null | null | null |
#include <string>
#include "engine/shader_controller.hpp"
#include "illumination/directional_light.hpp"
namespace gl::illumination {
DirectionalLight::DirectionalLight(const glm::vec3 &dir, const glm::vec3 &color, float intensity)
: m_dir(dir), m_color(color), m_intensity(intensity) {
}
DirectionalLight::~DirectionalLight() {
}
void DirectionalLight::setShaderParams(int index) {
char buffer[22];
snprintf(buffer, sizeof(buffer), "directionalLights[%d]", index);
std::string structName { buffer };
engine::ShaderController::getInstance()->setVec3(structName + ".dir", m_dir);
engine::ShaderController::getInstance()->setVec3(structName + ".color", m_color);
engine::ShaderController::getInstance()->setFloat(structName + ".intensity", m_intensity);
engine::ShaderController::getInstance()->setInt(structName + ".on", true);
}
}
| 36.5
| 102
| 0.667018
|
thetorine
|
9a5890fa0da18e461b3e74a85105ea2216cb4fff
| 6,755
|
cc
|
C++
|
Code/Components/Analysis/analysis/current/sourcefitting/CurvatureMapCreator.cc
|
rtobar/askapsoft
|
6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e
|
[
"BSL-1.0",
"Apache-2.0",
"OpenSSL"
] | null | null | null |
Code/Components/Analysis/analysis/current/sourcefitting/CurvatureMapCreator.cc
|
rtobar/askapsoft
|
6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e
|
[
"BSL-1.0",
"Apache-2.0",
"OpenSSL"
] | null | null | null |
Code/Components/Analysis/analysis/current/sourcefitting/CurvatureMapCreator.cc
|
rtobar/askapsoft
|
6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e
|
[
"BSL-1.0",
"Apache-2.0",
"OpenSSL"
] | null | null | null |
/// @file
///
/// XXX Notes on program XXX
///
/// @copyright (c) 2011 CSIRO
/// Australia Telescope National Facility (ATNF)
/// Commonwealth Scientific and Industrial Research Organisation (CSIRO)
/// PO Box 76, Epping NSW 1710, Australia
/// atnf-enquiries@csiro.au
///
/// This file is part of the ASKAP software distribution.
///
/// The ASKAP software distribution is free software: you can redistribute it
/// and/or modify it under the terms of the GNU General Public License as
/// published by the Free Software Foundation; either version 2 of the License,
/// or (at your option) any later version.
///
/// This program is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/// GNU General Public License for more details.
///
/// You should have received a copy of the GNU General Public License
/// along with this program; if not, write to the Free Software
/// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
///
/// @author XXX XXX <XXX.XXX@csiro.au>
///
#include <sourcefitting/CurvatureMapCreator.h>
#include <askap_analysis.h>
#include <askap/AskapLogging.h>
#include <askap/AskapError.h>
#include <askapparallel/AskapParallel.h>
#include <Common/ParameterSet.h>
#include <string>
#include <casacore/casa/Arrays/Array.h>
#include <casacore/casa/Arrays/ArrayMath.h>
#include <outputs/DistributedImageWriter.h>
#include <casainterface/CasaInterface.h>
#include <analysisparallel/SubimageDef.h>
#include <casacore/scimath/Mathematics/Convolver.h>
#include <duchamp/Cubes/cubes.hh>
#include <casacore/images/Images/PagedImage.h>
#include <casacore/images/Images/SubImage.h>
#include <casacore/images/Images/ImageOpener.h>
#include <casacore/images/Images/FITSImage.h>
#include <casacore/images/Images/MIRIADImage.h>
#include <casainterface/CasaInterface.h>
///@brief Where the log messages go.
ASKAP_LOGGER(logger, ".curvaturemap");
namespace askap {
namespace analysis {
CurvatureMapCreator::CurvatureMapCreator(askap::askapparallel::AskapParallel &comms,
const LOFAR::ParameterSet &parset):
itsComms(&comms), itsParset(parset)
{
itsFilename = parset.getString("curvatureImage", "");
ASKAPLOG_DEBUG_STR(logger, "Define a CurvatureMapCreator to write to image " <<
itsFilename);
}
CurvatureMapCreator::CurvatureMapCreator(const CurvatureMapCreator& other)
{
this->operator=(other);
}
CurvatureMapCreator& CurvatureMapCreator::operator= (const CurvatureMapCreator& other)
{
if (this == &other) return *this;
itsComms = other.itsComms;
itsParset = other.itsParset;
itsFilename = other.itsFilename;
itsArray = other.itsArray;
itsSigmaCurv = other.itsSigmaCurv;
return *this;
}
void CurvatureMapCreator::initialise(duchamp::Cube &cube, analysisutilities::SubimageDef &subdef)
{
itsCube = &cube;
itsSubimageDef = &subdef;
casa::Slicer slicer = analysisutilities::subsectionToSlicer(cube.pars().section());
analysisutilities::fixSlicer(slicer, cube.header().getWCS());
const boost::shared_ptr<SubImage<Float> > sub =
analysisutilities::getSubImage(cube.pars().getImageFile(), slicer);
itsShape = sub->shape();
duchamp::Section sec = itsSubimageDef->section(itsComms->rank() - 1);
sec.parse(itsShape.asStdVector());
duchamp::Section secMaster = itsSubimageDef->section(-1);
secMaster.parse(itsShape.asStdVector());
itsLocation = casa::IPosition(sec.getStartList());
ASKAPLOG_DEBUG_STR(logger, "Initialised CurvatureMapCreator with shape=" <<
itsShape << " and location=" << itsLocation);
}
void CurvatureMapCreator::calculate()
{
casa::Array<float> inputArray(itsShape, itsCube->getArray(), casa::SHARE);
casa::IPosition kernelShape(2, 3, 3);
casa::Array<float> kernel(kernelShape, 1.);
kernel(casa::IPosition(2, 1, 1)) = -8.;
ASKAPLOG_DEBUG_STR(logger, "Defined a kernel for the curvature map calculations: " << kernel);
casa::Convolver<float> convolver(kernel, itsShape);
ASKAPLOG_DEBUG_STR(logger, "Defined a convolver");
itsArray = casa::Array<float>(itsShape);
ASKAPLOG_DEBUG_STR(logger, "About to convolve");
convolver.linearConv(itsArray, inputArray);
ASKAPLOG_DEBUG_STR(logger, "Convolving done.");
this->findSigma();
this->maskBorders();
}
void CurvatureMapCreator::findSigma()
{
itsSigmaCurv = madfm(itsArray, False, False, False) / Statistics::correctionFactor;
ASKAPLOG_DEBUG_STR(logger, "Found sigma_curv = " << itsSigmaCurv);
}
void CurvatureMapCreator::maskBorders()
{
int nsubx = itsSubimageDef->nsubx();
int nsuby = itsSubimageDef->nsuby();
int overlapx = itsSubimageDef->overlapx() / 2;
int overlapy = itsSubimageDef->overlapy() / 2;
int rank = itsComms->rank() - 1;
int xminOffset = (rank % nsubx == 0) ? 0 : overlapx;
int xmaxOffset = (rank % nsubx == (nsubx - 1)) ? 0 : overlapx;
int yminOffset = (rank / nsubx == 0) ? 0 : overlapy;
int ymaxOffset = (rank / nsubx == (nsuby - 1)) ? 0 : overlapy;
ASKAPLOG_DEBUG_STR(logger, "xminOffset=" << xminOffset <<
", xmaxOffset=" << xmaxOffset <<
", yminOffset=" << yminOffset <<
", ymaxOffset=" << ymaxOffset);
ASKAPLOG_DEBUG_STR(logger, "Starting with location=" << itsLocation <<
" and shape=" << itsShape);
casa::IPosition blc(itsLocation), trc(itsShape - 1);
blc[0] = xminOffset;
blc[1] = yminOffset;
trc[0] -= xmaxOffset;
trc[1] -= ymaxOffset;
casa::Slicer arrSlicer(blc, trc, Slicer::endIsLast);
ASKAPLOG_DEBUG_STR(logger, "Defined a masking Slicer " << arrSlicer);
casa::Array<float> newArr = itsArray(arrSlicer);
ASKAPLOG_DEBUG_STR(logger, "Have extracted a subarray of shape " << newArr.shape());
itsArray.assign(newArr);
itsLocation += blc;
itsShape = trc - blc + 1;
ASKAPLOG_DEBUG_STR(logger, "Now have location=" << itsLocation <<
" and shape=" << itsShape);
}
void CurvatureMapCreator::write()
{
if (itsFilename != "") {
ASKAPLOG_DEBUG_STR(logger, "In CurvatureMapCreator::write()");
DistributedImageWriter writer(*itsComms, itsParset, itsCube, itsFilename);
ASKAPLOG_DEBUG_STR(logger, "Creating the output image " << itsFilename);
writer.create();
ASKAPLOG_DEBUG_STR(logger, "Writing curvature map of shape " <<
itsArray.shape() << " to " << itsFilename);
writer.write(itsArray, itsLocation, true);
ASKAPLOG_DEBUG_STR(logger, "Curvature image written");
}
}
}
}
| 34.116162
| 98
| 0.687491
|
rtobar
|
9a58b8685fc78db29f02005c77e7a87db6265711
| 6,229
|
cpp
|
C++
|
windows/advcore/ctf/aimm1.2/win32/funcprv.cpp
|
npocmaka/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 17
|
2020-11-13T13:42:52.000Z
|
2021-09-16T09:13:13.000Z
|
windows/advcore/ctf/aimm1.2/win32/funcprv.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 2
|
2020-10-19T08:02:06.000Z
|
2020-10-19T08:23:18.000Z
|
windows/advcore/ctf/aimm1.2/win32/funcprv.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 14
|
2020-11-14T09:43:20.000Z
|
2021-08-28T08:59:57.000Z
|
//
// funcprv.cpp
//
#include "private.h"
#include "helpers.h"
#include "immxutil.h"
#include "funcprv.h"
#include "cresstr.h"
#include "resource.h"
//////////////////////////////////////////////////////////////////////////////
//
// CFunctionProvider
//
//////////////////////////////////////////////////////////////////////////////
//+---------------------------------------------------------------------------
//
// ctor
//
//----------------------------------------------------------------------------
CFunctionProvider::CFunctionProvider(ImmIfIME *pImmIfIME, TfClientId tid) : CFunctionProviderBase(tid)
{
Init(CLSID_CAImmLayer, L"AIMM12 Function Provider");
_ImmIfIME = pImmIfIME;
}
//+---------------------------------------------------------------------------
//
// GetFunction
//
//----------------------------------------------------------------------------
STDAPI CFunctionProvider::GetFunction(REFGUID rguid, REFIID riid, IUnknown **ppunk)
{
*ppunk = NULL;
if (!IsEqualIID(rguid, GUID_NULL))
return E_NOINTERFACE;
if (IsEqualIID(riid, IID_IAImmFnDocFeed))
{
*ppunk = new CFnDocFeed(this);
}
if (*ppunk)
return S_OK;
return E_NOINTERFACE;
}
//////////////////////////////////////////////////////////////////////////////
//
// CFnDocFeed
//
//////////////////////////////////////////////////////////////////////////////
//+---------------------------------------------------------------------------
//
// IUnknown
//
//----------------------------------------------------------------------------
STDAPI CFnDocFeed::QueryInterface(REFIID riid, void **ppvObj)
{
*ppvObj = NULL;
if (IsEqualIID(riid, IID_IUnknown) ||
IsEqualIID(riid, IID_IAImmFnDocFeed))
{
*ppvObj = SAFECAST(this, CFnDocFeed *);
}
if (*ppvObj)
{
AddRef();
return S_OK;
}
return E_NOINTERFACE;
}
STDAPI_(ULONG) CFnDocFeed::AddRef()
{
return InterlockedIncrement(&_cRef);
}
STDAPI_(ULONG) CFnDocFeed::Release()
{
long cr;
cr = InterlockedDecrement(&_cRef);
Assert(cr >= 0);
if (cr == 0)
{
delete this;
}
return cr;
}
//+---------------------------------------------------------------------------
//
// ctor
//
//----------------------------------------------------------------------------
CFnDocFeed::CFnDocFeed(CFunctionProvider *pFuncPrv)
{
_cRef = 1;
_pFuncPrv = pFuncPrv;
_pFuncPrv->AddRef();
}
//+---------------------------------------------------------------------------
//
// dtor
//
//----------------------------------------------------------------------------
CFnDocFeed::~CFnDocFeed()
{
_pFuncPrv->Release();
}
//+---------------------------------------------------------------------------
//
// dtor
//
//----------------------------------------------------------------------------
STDAPI CFnDocFeed::GetDisplayName(BSTR *pbstrName)
{
if (!pbstrName)
return E_INVALIDARG;
*pbstrName = SysAllocString(CRStr2(IDS_FUNCPRV_CONVERSION));
if (!*pbstrName)
return E_OUTOFMEMORY;
return S_OK;
}
//+---------------------------------------------------------------------------
//
// dtor
//
//----------------------------------------------------------------------------
STDAPI CFnDocFeed::IsEnabled(BOOL *pfEnable)
{
if (!pfEnable)
return E_INVALIDARG;
*pfEnable = TRUE;
return S_OK;
}
//+---------------------------------------------------------------------------
//
// CFnDocFeed::DocFeed
//
//----------------------------------------------------------------------------
STDAPI CFnDocFeed::DocFeed()
{
IMTLS *ptls = IMTLS_GetOrAlloc();
if (ptls == NULL)
return E_FAIL;
IMCLock imc(ptls->hIMC);
if (imc.Invalid())
return E_FAIL;
CAImeContext* pAImeContext = imc->m_pAImeContext;
if (!pAImeContext)
return E_FAIL;
Assert(_pFuncPrv);
_pFuncPrv->_ImmIfIME->SetupDocFeedString(pAImeContext->GetInputContext(), imc);
return S_OK;
}
//+---------------------------------------------------------------------------
//
// CFnDocFeed::ClearDocFeedBuffer
//
//----------------------------------------------------------------------------
STDAPI CFnDocFeed::ClearDocFeedBuffer()
{
IMTLS *ptls = IMTLS_GetOrAlloc();
if (ptls == NULL)
return E_FAIL;
IMCLock imc(ptls->hIMC);
if (imc.Invalid())
return E_FAIL;
CAImeContext* pAImeContext = imc->m_pAImeContext;
if (!pAImeContext)
return E_FAIL;
Assert(_pFuncPrv);
_pFuncPrv->_ImmIfIME->ClearDocFeedBuffer(pAImeContext->GetInputContext(), imc);
return S_OK;
}
//+---------------------------------------------------------------------------
//
// CFnDocFeed::StartReconvert
//
//----------------------------------------------------------------------------
STDAPI CFnDocFeed::StartReconvert()
{
IMTLS *ptls = IMTLS_GetOrAlloc();
if (ptls == NULL)
return E_FAIL;
IMCLock imc(ptls->hIMC);
if (imc.Invalid())
return E_FAIL;
CAImeContext* pAImeContext = imc->m_pAImeContext;
if (!pAImeContext)
return E_FAIL;
Assert(_pFuncPrv);
pAImeContext->SetupReconvertString();
pAImeContext->EndReconvertString();
return S_OK;
}
//+---------------------------------------------------------------------------
//
// CFnDocFeed::StartUndoCompositionString
//
//----------------------------------------------------------------------------
STDAPI CFnDocFeed::StartUndoCompositionString()
{
IMTLS *ptls = IMTLS_GetOrAlloc();
if (ptls == NULL)
return E_FAIL;
IMCLock imc(ptls->hIMC);
if (imc.Invalid())
return E_FAIL;
CAImeContext* pAImeContext = imc->m_pAImeContext;
if (!pAImeContext)
return E_FAIL;
Assert(_pFuncPrv);
pAImeContext->SetupUndoCompositionString();
pAImeContext->EndUndoCompositionString();
return S_OK;
}
| 22.98524
| 103
| 0.396693
|
npocmaka
|
9a5bea3fff59bbd804be55fc3bae91234f087268
| 267
|
cpp
|
C++
|
Day2/zadanie2.cpp
|
majkel84/kurs_cpp_podstawowy
|
eddaffb310c6132304aa26dc87ec04ddfc09c541
|
[
"MIT"
] | 1
|
2022-03-03T14:07:57.000Z
|
2022-03-03T14:07:57.000Z
|
Day2/zadanie2.cpp
|
majkel84/kurs_cpp_podstawowy
|
eddaffb310c6132304aa26dc87ec04ddfc09c541
|
[
"MIT"
] | 2
|
2020-05-22T22:01:52.000Z
|
2020-05-30T09:24:42.000Z
|
Day2/zadanie2.cpp
|
majkel84/kurs_cpp_podstawowy
|
eddaffb310c6132304aa26dc87ec04ddfc09c541
|
[
"MIT"
] | null | null | null |
#include <iostream>
void foo(int* ptr) {
*ptr = 10;
}
void bar(int* ptr) {
*ptr = 20;
}
int main() {
int number = 5;
std::cout << number << '\n';
foo(&number);
std::cout << number << '\n';
bar(&number);
std::cout << number << '\n';
return 0;
}
| 12.714286
| 30
| 0.505618
|
majkel84
|
9a5c8fa10db7b514eb5979e451ad60d3e6ff69a5
| 4,060
|
cpp
|
C++
|
ImdViewerV2/plugins/efbbox/efbbox.cpp
|
olivierchatry/iri3d
|
cae98c61d9257546d0fc81e69709297d04a17a14
|
[
"MIT"
] | 2
|
2022-01-02T08:12:29.000Z
|
2022-02-12T22:15:11.000Z
|
ImdViewerV2/plugins/efbbox/efbbox.cpp
|
olivierchatry/iri3d
|
cae98c61d9257546d0fc81e69709297d04a17a14
|
[
"MIT"
] | null | null | null |
ImdViewerV2/plugins/efbbox/efbbox.cpp
|
olivierchatry/iri3d
|
cae98c61d9257546d0fc81e69709297d04a17a14
|
[
"MIT"
] | 1
|
2022-01-02T08:09:51.000Z
|
2022-01-02T08:09:51.000Z
|
#include "stdafx.h"
#include "efbbox.h"
#include "magic/MgcBox3.h"
#include "magic/MgcVector3.h"
static imdviewer_plugin_info_t plugins_info =
{
"Epifighter BoundingBox generator.",
"Generate bounding box around bones.",
"Chatry Oliver, Julien Barbier.",
true // display box for octree.
};
BOOL APIENTRY DllMain(HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
void PluginEfBox::PluginDestroy()
{
if (_bbox)
delete _bbox;
_bbox = 0;
_bbox_count = 0;
}
#define DEFAULT_FILE_NAME "\\bones_bbox.dat"
#define NB_POINTS_PER_BBOX 8
#define NB_COORD_PER_POINT 3
void PluginEfBox::SaveToFile(const char *path)
{
int i;
std::string file_name(path);
file_name += DEFAULT_FILE_NAME;
FILE *fd = fopen(file_name.c_str(), "wb");
if (fd == NULL)
return;
fwrite(&_bbox_count, sizeof(_bbox_count), 1, fd);
for (i = 0; i < _bbox_count; i++)
fwrite(&_bbox[i], sizeof(_bbox[i]), 1, fd);
fclose(fd);
}
bool PluginEfBox::PluginGo(const char *path, imd2_object_t *object, imd2_bone_file_t *bones)
{
if (object == 0 || !object->imd2_object_header.have_skin)
return false;
PluginDestroy();
_bbox = new BoundingBox[object->imd2_object_header.num_bones];
_bbox_count = object->imd2_object_header.num_bones;
for (int bi = 0; bi < _bbox_count; bi++)
{
std::vector<Mgc::Vector3> mesh_point;
mesh_point.clear();
for (int mi = 0; mi < object->imd2_object_header.num_mesh; mi++)
{
imd2_mesh_t *mesh = object->imd2_mesh + mi;
if (mesh->imd2_mesh_header.have_skin)
{
for (int vi = 0; vi < mesh->imd2_mesh_header.num_vertex; vi++)
{
imd2_skin_t *skin = mesh->imd2_skin + vi;
imd2_vertex_t *vertex = mesh->imd2_vertex + vi;
int bone_index = -1;
float max_weight = 0.0f;
for (int wi = 0; wi < skin->num_bones_assigned; wi++)
{
imd2_weight_t *weight = skin->weight + wi;
if (weight->weight > max_weight)
{
bone_index = weight->bone_index;
max_weight = weight->weight;
}
}
if (bone_index != -1 && bone_index == bi)
{
Mgc::Vector3 v(vertex->pos);
mesh_point.push_back(v);
}
}
}
}
size_t count = mesh_point.size();
Mgc::Vector3 *pt = new Mgc::Vector3[count];
for (size_t i = 0; i < count; ++i)
pt[i] = mesh_point[i];
// compute bounding box.
Mgc::Box3 magic_bbox;
BoundingBox *bbox = _bbox + bi;
if (mesh_point.size() > 0)
{
bbox->box = ContOrientedBox((int)mesh_point.size(), pt);
bbox->bone_index = bi;
}
else
bbox->bone_index = -1;
delete pt;
}
SaveToFile(path);
return false;
}
void PluginEfBox::PluginInit()
{
_bbox = 0;
_bbox_count = 0;
}
void PluginEfBox::PluginRender(unsigned int current_anim, imd2_bone_file_t *bones)
{
for (int i = 0; i < _bbox_count; ++i)
{
BoundingBox *bbox = _bbox + i;
int pair[] = {3, 2, 2, 1, 1, 0, 0, 3, 1, 5, 2, 6, 3, 7, 0, 4, 4, 7, 7, 6, 6, 5, 5, 4};
Mgc::Vector3 p[8];
bbox->box.ComputeVertices(p);
// search for bone index
glPushMatrix();
if (bones)
for (int i = 0; i < bones->imd2_bone_file_header.bone_count; ++i)
{
if (bones->bones[i].imd2_bone_header.bone_index == bbox->bone_index)
{
glMultMatrixf(bones->bones[i].imd2_bone_anim[current_anim].matrix);
continue;
}
}
glBegin(GL_LINES);
for (int i = 0; i < 24; i += 2)
{
glVertex3fv(p[pair[i]]);
glVertex3fv(p[pair[i + 1]]);
}
glEnd();
glPopMatrix();
}
}
DLLAPI imdviewer_plugin_info_t *GetPluginInfo()
{
return &plugins_info;
}
DLLAPI ImdViewerPlugins *CreateInstance()
{
return new PluginEfBox;
}
| 25.061728
| 92
| 0.599015
|
olivierchatry
|
9a5e005d2f388ea2c62ff109bd5bc7fc4f0d0c44
| 8,320
|
cpp
|
C++
|
source/examples/states/main.cpp
|
citron0xa9/globjects
|
53a1de45f3c177fbd805610f274d3ffb1b97843a
|
[
"MIT"
] | null | null | null |
source/examples/states/main.cpp
|
citron0xa9/globjects
|
53a1de45f3c177fbd805610f274d3ffb1b97843a
|
[
"MIT"
] | null | null | null |
source/examples/states/main.cpp
|
citron0xa9/globjects
|
53a1de45f3c177fbd805610f274d3ffb1b97843a
|
[
"MIT"
] | 2
|
2020-10-01T04:10:51.000Z
|
2021-07-01T07:45:45.000Z
|
#include <iostream>
#include <algorithm>
#include <cpplocate/cpplocate.h>
#include <cpplocate/ModuleInfo.h>
#include <glm/vec2.hpp>
#include <glbinding/gl/gl.h>
#include <glbinding/ContextInfo.h>
#include <glbinding/Version.h>
#include <GLFW/glfw3.h>
#include <globjects/globjects.h>
#include <globjects/base/File.h>
#include <globjects/logging.h>
#include <globjects/Buffer.h>
#include <globjects/Program.h>
#include <globjects/Shader.h>
#include <globjects/VertexArray.h>
#include <globjects/VertexAttributeBinding.h>
#include <globjects/State.h>
#include "datapath.inl"
using namespace gl;
namespace
{
std::unique_ptr<globjects::Program> g_shaderProgram = nullptr;
std::unique_ptr<globjects::File> g_vertexShaderSource = nullptr;
std::unique_ptr<globjects::AbstractStringSource> g_vertexShaderTemplate = nullptr;
std::unique_ptr<globjects::Shader> g_vertexShader = nullptr;
std::unique_ptr<globjects::File> g_fragmentShaderSource = nullptr;
std::unique_ptr<globjects::AbstractStringSource> g_fragmentShaderTemplate = nullptr;
std::unique_ptr<globjects::Shader> g_fragmentShader = nullptr;
std::unique_ptr<globjects::VertexArray> g_vao = nullptr;
std::unique_ptr<globjects::Buffer> g_buffer = nullptr;
std::unique_ptr<globjects::State> g_thinnestPointSizeState = nullptr;
std::unique_ptr<globjects::State> g_thinPointSizeState = nullptr;
std::unique_ptr<globjects::State> g_normalPointSizeState = nullptr;
std::unique_ptr<globjects::State> g_thickPointSizeState = nullptr;
std::unique_ptr<globjects::State> g_disableRasterizerState = nullptr;
std::unique_ptr<globjects::State> g_enableRasterizerState = nullptr;
std::unique_ptr<globjects::State> g_defaultPointSizeState = nullptr;
auto g_size = glm::ivec2{};
}
void initialize()
{
// Initialize OpenGL objects
g_defaultPointSizeState = globjects::State::create();
g_defaultPointSizeState->pointSize(globjects::getFloat(GL_POINT_SIZE));
g_thinnestPointSizeState = globjects::State::create();
g_thinnestPointSizeState->pointSize(2.0f);
g_thinPointSizeState = globjects::State::create();
g_thinPointSizeState->pointSize(5.0f);
g_normalPointSizeState = globjects::State::create();
g_normalPointSizeState->pointSize(10.0f);
g_thickPointSizeState = globjects::State::create();
g_thickPointSizeState->pointSize(20.0f);
g_disableRasterizerState = globjects::State::create();
g_disableRasterizerState->enable(GL_RASTERIZER_DISCARD);
g_enableRasterizerState = globjects::State::create();
g_enableRasterizerState->disable(GL_RASTERIZER_DISCARD);
g_vao = globjects::VertexArray::create();
g_buffer = globjects::Buffer::create();
g_shaderProgram = globjects::Program::create();
const auto dataPath = common::retrieveDataPath("globjects", "dataPath");
g_vertexShaderSource = globjects::Shader::sourceFromFile(dataPath + "states/standard.vert");
g_vertexShaderTemplate = globjects::Shader::applyGlobalReplacements(g_vertexShaderSource.get());
g_vertexShader = globjects::Shader::create(GL_VERTEX_SHADER, g_vertexShaderTemplate.get());
g_fragmentShaderSource = globjects::Shader::sourceFromFile(dataPath + "states/standard.frag");
g_fragmentShaderTemplate = globjects::Shader::applyGlobalReplacements(g_fragmentShaderSource.get());
g_fragmentShader = globjects::Shader::create(GL_FRAGMENT_SHADER, g_fragmentShaderTemplate.get());
g_shaderProgram->attach(g_vertexShader.get(), g_fragmentShader.get());
static auto data = std::vector<glm::vec2>();
if (data.empty())
{
for (auto y = 0.8f; y > -1.f; y -= 0.2f)
for (auto x = -0.8f; x < 1.f; x += 0.4f)
data.push_back(glm::vec2(x, y));
}
g_buffer->setData(data, GL_STATIC_DRAW );
g_vao->binding(0)->setAttribute(0);
g_vao->binding(0)->setBuffer(g_buffer.get(), 0, sizeof(glm::vec2));
g_vao->binding(0)->setFormat(2, GL_FLOAT);
g_vao->enable(0);
}
void deinitialize()
{
g_shaderProgram.reset(nullptr);
g_vertexShaderSource.reset(nullptr);
g_vertexShaderTemplate.reset(nullptr);
g_vertexShader.reset(nullptr);
g_fragmentShaderSource.reset(nullptr);
g_fragmentShaderTemplate.reset(nullptr);
g_fragmentShader.reset(nullptr);
g_vao.reset(nullptr);
g_buffer.reset(nullptr);
g_thinnestPointSizeState.reset(nullptr);
g_thinPointSizeState.reset(nullptr);
g_normalPointSizeState.reset(nullptr);
g_thickPointSizeState.reset(nullptr);
g_disableRasterizerState.reset(nullptr);
g_enableRasterizerState.reset(nullptr);
g_defaultPointSizeState.reset(nullptr);
}
void draw()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glViewport(0, 0, g_size.x, g_size.y);
g_shaderProgram->use();
g_defaultPointSizeState->apply();
g_vao->drawArrays(GL_POINTS, 0, 5);
g_thinnestPointSizeState->apply();
g_vao->drawArrays(GL_POINTS, 5, 5);
g_thinPointSizeState->apply();
g_vao->drawArrays(GL_POINTS, 10, 5);
g_normalPointSizeState->apply();
g_vao->drawArrays(GL_POINTS, 15, 5);
g_thickPointSizeState->apply();
g_vao->drawArrays(GL_POINTS, 20, 1);
g_disableRasterizerState->apply();
g_vao->drawArrays(GL_POINTS, 21, 1);
g_enableRasterizerState->apply();
g_vao->drawArrays(GL_POINTS, 22, 1);
g_disableRasterizerState->apply();
g_vao->drawArrays(GL_POINTS, 23, 1);
g_enableRasterizerState->apply();
g_vao->drawArrays(GL_POINTS, 24, 1);
g_normalPointSizeState->apply();
g_vao->drawArrays(GL_POINTS, 25, 5);
g_thinPointSizeState->apply();
g_vao->drawArrays(GL_POINTS, 30, 5);
g_thinnestPointSizeState->apply();
g_vao->drawArrays(GL_POINTS, 35, 5);
g_defaultPointSizeState->apply();
g_vao->drawArrays(GL_POINTS, 35, 5);
g_shaderProgram->release();
}
void error(int errnum, const char * errmsg)
{
globjects::critical() << errnum << ": " << errmsg << std::endl;
}
void framebuffer_size_callback(GLFWwindow * /*window*/, int width, int height)
{
g_size = glm::ivec2{ width, height };
}
void key_callback(GLFWwindow * window, int key, int /*scancode*/, int action, int /*modes*/)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE)
glfwSetWindowShouldClose(window, true);
if (key == GLFW_KEY_F5 && action == GLFW_RELEASE)
{
g_vertexShaderSource->reload();
g_fragmentShaderSource->reload();
}
}
int main(int /*argc*/, char * /*argv*/[])
{
// Initialize GLFW
if (!glfwInit())
return 1;
glfwSetErrorCallback(error);
glfwDefaultWindowHints();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, true);
// Create a context and, if valid, make it current
GLFWwindow * window = glfwCreateWindow(640, 480, "globjects States", NULL, NULL);
if (window == nullptr)
{
globjects::critical() << "Context creation failed. Terminate execution.";
glfwTerminate();
return -1;
}
glfwSetKeyCallback(window, key_callback);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glfwMakeContextCurrent(window);
// Initialize globjects (internally initializes glbinding, and registers the current context)
globjects::init();
std::cout << std::endl
<< "OpenGL Version: " << glbinding::ContextInfo::version() << std::endl
<< "OpenGL Vendor: " << glbinding::ContextInfo::vendor() << std::endl
<< "OpenGL Renderer: " << glbinding::ContextInfo::renderer() << std::endl << std::endl;
globjects::info() << "Press F5 to reload shaders." << std::endl << std::endl;
glfwGetFramebufferSize(window, &g_size[0], &g_size[1]);
initialize();
// Main loop
while (!glfwWindowShouldClose(window))
{
glfwPollEvents();
draw();
glfwSwapBuffers(window);
}
deinitialize();
// Properly shutdown GLFW
glfwTerminate();
return 0;
}
| 32.885375
| 105
| 0.683774
|
citron0xa9
|
9a5f5c33216fd13f253f598c1e49cd75cc8c66df
| 559
|
cpp
|
C++
|
dev/assem.cpp
|
jordanjohnston/manseglib
|
00723792c9b16f6518e25095569d77f2ed7b6d22
|
[
"MIT"
] | null | null | null |
dev/assem.cpp
|
jordanjohnston/manseglib
|
00723792c9b16f6518e25095569d77f2ed7b6d22
|
[
"MIT"
] | null | null | null |
dev/assem.cpp
|
jordanjohnston/manseglib
|
00723792c9b16f6518e25095569d77f2ed7b6d22
|
[
"MIT"
] | 1
|
2020-06-09T18:48:14.000Z
|
2020-06-09T18:48:14.000Z
|
#include <iostream>
#include "../manseglib.hpp"
int main()
{
constexpr int size = 1000;
ManSeg::ManSegArray a(size);
ManSeg::ManSegArray b(size);
// double a[size];
// double b[size];
std::cout << "filling\n";
for(int i = 0; i < size; ++i)
{
b.pairs[i] = 0;
a.pairs[i] = i;
}
std::cout << "now copying\n";
for(int i = 0; i < size; ++i)
{
for(int j = 0; j < size; ++j) b.pairs[i] += a.pairs[j];
}
std::cout << "finished copying\n";
for(int i = 0; i < size; ++i)
std::cout << b.pairs[i] << " ";
std::cout << std::endl;
return 0;
}
| 17.46875
| 57
| 0.543828
|
jordanjohnston
|