blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2 values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905 values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 10.4M | extension stringclasses 115 values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ab19bc012e3e4f6d9c9c9f4b8896ff5b40b49d3e | 8dc84558f0058d90dfc4955e905dab1b22d12c08 | /ui/aura/mus/client_surface_embedder.cc | 74f31fd2e7007276b5d607f89f4ed7934282f3e2 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | meniossin/src | 42a95cc6c4a9c71d43d62bc4311224ca1fd61e03 | 44f73f7e76119e5ab415d4593ac66485e65d700a | refs/heads/master | 2022-12-16T20:17:03.747113 | 2020-09-03T10:43:12 | 2020-09-03T10:43:12 | 263,710,168 | 1 | 0 | BSD-3-Clause | 2020-05-13T18:20:09 | 2020-05-13T18:20:08 | null | UTF-8 | C++ | false | false | 4,053 | cc | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/aura/mus/client_surface_embedder.h"
#include "ui/aura/window.h"
#include "ui/gfx/geometry/dip_util.h"
namespace aura {
ClientSurfaceEmbedder::ClientSurfaceEmbedder(
Window* window,
bool inject_gutter,
const gfx::Insets& client_area_insets)
: window_(window),
inject_gutter_(inject_gutter),
client_area_insets_(client_area_insets) {
surface_layer_ = std::make_unique<ui::Layer>(ui::LAYER_TEXTURED);
surface_layer_->SetMasksToBounds(true);
// The frame provided by the parent window->layer() needs to show through
// the surface layer.
surface_layer_->SetFillsBoundsOpaquely(false);
window_->layer()->Add(surface_layer_.get());
// Window's layer may contain content from this client (the embedder), e.g.
// this is the case with window decorations provided by Window Manager.
// This content should appear underneath the content of the embedded client.
window_->layer()->StackAtTop(surface_layer_.get());
}
ClientSurfaceEmbedder::~ClientSurfaceEmbedder() = default;
void ClientSurfaceEmbedder::SetPrimarySurfaceId(
const viz::SurfaceId& surface_id) {
surface_layer_->SetShowPrimarySurface(
surface_id, window_->bounds().size(), SK_ColorWHITE,
cc::DeadlinePolicy::UseDefaultDeadline(),
false /* stretch_content_to_fill_bounds */);
}
void ClientSurfaceEmbedder::SetFallbackSurfaceInfo(
const viz::SurfaceInfo& surface_info) {
fallback_surface_info_ = surface_info;
surface_layer_->SetFallbackSurfaceId(surface_info.id());
UpdateSizeAndGutters();
}
void ClientSurfaceEmbedder::UpdateSizeAndGutters() {
surface_layer_->SetBounds(gfx::Rect(window_->bounds().size()));
if (!inject_gutter_)
return;
gfx::Size fallback_surface_size_in_dip;
if (fallback_surface_info_.is_valid()) {
float fallback_device_scale_factor =
fallback_surface_info_.device_scale_factor();
fallback_surface_size_in_dip = gfx::ConvertSizeToDIP(
fallback_device_scale_factor, fallback_surface_info_.size_in_pixels());
}
gfx::Rect window_bounds(window_->bounds());
if (!window_->transparent() &&
fallback_surface_size_in_dip.width() < window_bounds.width()) {
right_gutter_ = std::make_unique<ui::Layer>(ui::LAYER_SOLID_COLOR);
// TODO(fsamuel): Use the embedded client's background color.
right_gutter_->SetColor(SK_ColorWHITE);
int width = window_bounds.width() - fallback_surface_size_in_dip.width();
// The right gutter also includes the bottom-right corner, if necessary.
int height = window_bounds.height() - client_area_insets_.height();
right_gutter_->SetBounds(gfx::Rect(
client_area_insets_.left() + fallback_surface_size_in_dip.width(),
client_area_insets_.top(), width, height));
window_->layer()->Add(right_gutter_.get());
} else {
right_gutter_.reset();
}
// Only create a bottom gutter if a fallback surface is available. Otherwise,
// the right gutter will fill the whole window until a fallback is available.
if (!window_->transparent() && !fallback_surface_size_in_dip.IsEmpty() &&
fallback_surface_size_in_dip.height() < window_bounds.height()) {
bottom_gutter_ = std::make_unique<ui::Layer>(ui::LAYER_SOLID_COLOR);
// TODO(fsamuel): Use the embedded client's background color.
bottom_gutter_->SetColor(SK_ColorWHITE);
int width = fallback_surface_size_in_dip.width();
int height = window_bounds.height() - fallback_surface_size_in_dip.height();
bottom_gutter_->SetBounds(
gfx::Rect(0, fallback_surface_size_in_dip.height(), width, height));
window_->layer()->Add(bottom_gutter_.get());
} else {
bottom_gutter_.reset();
}
window_->layer()->StackAtTop(surface_layer_.get());
}
const viz::SurfaceId& ClientSurfaceEmbedder::GetPrimarySurfaceIdForTesting()
const {
return *surface_layer_->GetPrimarySurfaceId();
}
} // namespace aura
| [
"arnaud@geometry.ee"
] | arnaud@geometry.ee |
a41a531677a63c397a486711336a21b544fa4dac | 89a30d3f12799c05430a081e1d89d453e5481557 | /ex04/main.cpp | d068fb2bac22dff80a83d1c72db9febca3a7dca6 | [] | no_license | sasakiyudai/cpp03 | 3cb1840e630a399baee741c37bd7ee6a8feb416b | a944dc8ad9066e1fdb7deb49be64aea9ca648c2b | refs/heads/master | 2023-04-24T17:35:51.622589 | 2021-05-05T08:54:59 | 2021-05-05T08:54:59 | 355,207,763 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,600 | cpp | #include "FragTrap.hpp"
#include "ScavTrap.hpp"
#include "ClapTrap.hpp"
#include "NinjaTrap.hpp"
#include "SuperTrap.hpp"
int main()
{
std::srand(time(NULL));
FragTrap hikakin("hikakin");
ScavTrap seikin("seiikin");
ClapTrap youtube("youtube");
NinjaTrap nikoniko("nikoniko");
NinjaTrap nikoniko2("nikoniko2");
SuperTrap superman("superman");
hikakin.rangedAttack("seikin");
seikin.takeDamage(20);
seikin.meleeAttack("hikakin");
hikakin.takeDamage(20);
nikoniko.meleeAttack("hikakin");
hikakin.takeDamage(20);
hikakin.meleeAttack("seikin");
seikin.takeDamage(30);
seikin.rangedAttack("hikakin");
hikakin.takeDamage(15);
nikoniko.rangedAttack("seikin");
seikin.takeDamage(20);
hikakin.meleeAttack("seikin");
seikin.takeDamage(30);
seikin.rangedAttack("nikoniko");
nikoniko.takeDamage(15);
nikoniko.rangedAttack("seikin");
seikin.takeDamage(20);
hikakin.beRepaired(30);
seikin.beRepaired(40);
nikoniko.beRepaired(40);
hikakin.vaulthunter_dot_exe("seikin");
seikin.challengeNewcomer();
nikoniko.ninjaShoebox(hikakin);
hikakin.vaulthunter_dot_exe("seikin");
seikin.challengeNewcomer();
nikoniko.ninjaShoebox(seikin);
hikakin.vaulthunter_dot_exe("seikin");
seikin.challengeNewcomer();
nikoniko.ninjaShoebox(youtube);
nikoniko.ninjaShoebox(nikoniko2);
superman.meleeAttack("hikakin");
superman.rangedAttack("seikin");
superman.vaulthunter_dot_exe("nikoniko");
superman.vaulthunter_dot_exe("nikoniko2");
superman.ninjaShoebox(hikakin);
superman.ninjaShoebox(seikin);
superman.ninjaShoebox(youtube);
superman.ninjaShoebox(nikoniko2);
return (0);
}
| [
"you@example.com"
] | you@example.com |
4fdcf557e3798448e4e865c750ec24128a224992 | 9f9ac37f22333569ae3bec78075d0918c3ad2742 | /src/protocol/proto-types.cxx | fb85666838857c005630d51a1821e32a721234db | [
"MIT"
] | permissive | credativ/pg_backup_ctl-plus | 602bcd0ce2bcce1653dd340e7b134c3b8f92973d | d1655f9791be9227e17b60731829bbd8572e850b | refs/heads/master | 2023-03-20T22:15:21.159701 | 2021-03-16T18:08:53 | 2021-03-16T18:08:53 | 348,447,804 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,709 | cxx | #include <sstream>
#include <boost/log/trivial.hpp>
#include <pgsql-proto.hxx>
#include <proto-descr.hxx>
#include <server.hxx>
using namespace pgbckctl;
using namespace pgbckctl::pgprotocol;
/* ****************************************************************************
* PGProtoResultSet implementation
* ***************************************************************************/
PGProtoResultSet::PGProtoResultSet() {}
PGProtoResultSet::~PGProtoResultSet() {}
int PGProtoResultSet::calculateRowDescrSize() {
return MESSAGE_HDR_LENGTH_SIZE + sizeof(short) + row_descr_size;
}
int PGProtoResultSet::descriptor(ProtocolBuffer &buffer) {
/* reset rows iterator to start offset */
row_iterator = data_descr.row_values.begin();
return prepareSend(buffer, PGPROTO_ROW_DESCR_MESSAGE);
}
int PGProtoResultSet::data(ProtocolBuffer &buffer) {
/*
* NOTE: calling descriptor() before data() should have
* positioned the internal iterator to the first data row.
*/
return prepareSend(buffer, PGPROTO_DATA_DESCR_MESSAGE);
}
int PGProtoResultSet::prepareSend(ProtocolBuffer &buffer,
int type) {
int message_size = 0;
switch(type) {
case PGPROTO_DATA_DESCR_MESSAGE:
{
/*
* Check if we are positioned on the last element.
* If true, message_size will return 0, indicating the end of
* data row messages.
*/
if (row_iterator == data_descr.row_values.end()) {
BOOST_LOG_TRIVIAL(debug) << "result set iterator reached end of data rows";
break;
}
message_size = MESSAGE_HDR_SIZE + sizeof(short)
+ row_iterator->row_size;
buffer.allocate(message_size);
BOOST_LOG_TRIVIAL(debug) << "PG PROTO write data row size "
<< message_size
<< ", buffer size "
<< buffer.getSize();
/*
* Prepare message header.
*/
buffer.write_byte(DescribeMessage);
buffer.write_int(message_size - MESSAGE_HDR_BYTE);
/* Number of columns */
buffer.write_short(row_iterator->fieldCount());
BOOST_LOG_TRIVIAL(debug) << "PG PROTO data row message has "
<< row_iterator->values.size()
<< " columns";
/*
* NOTE: on the very first call to data(), we will
* find the iterator positioned on the very first
* data row, if descriptor() was called before.
*
* Just advance the iterator unless we have seen
* the last data row.
*/
/* Loop through the column values list */
for (auto &colval : row_iterator->values) {
BOOST_LOG_TRIVIAL(debug) << "PG PROTO write col data len "
<< colval.length << " bytes";
buffer.write_int(colval.length);
buffer.write_buffer(colval.data.c_str(), colval.length);
}
/*
* Position the data row iterator on the next data row.
*/
row_iterator++;
break;
}
case PGPROTO_ROW_DESCR_MESSAGE:
{
message_size = calculateRowDescrSize();
buffer.allocate(message_size + MESSAGE_HDR_BYTE);
BOOST_LOG_TRIVIAL(debug) << "PG PROTO buffer allocated "
<< buffer.getSize() << " bytes";
/*
* Prepare the message header.
*/
buffer.write_byte(RowDescriptionMessage);
buffer.write_int(message_size);
buffer.write_short(row_descr.fieldCount());
BOOST_LOG_TRIVIAL(debug) << "PG PROTO row descriptor has "
<< row_descr.count
<< " fields";
/* The header is prepared now, write the message contents */
for (auto &it : row_descr.column_list) {
buffer.write_buffer(it.name.c_str(), it.name.length());
buffer.write_byte('\0');
buffer.write_int(it.tableoid);
buffer.write_short(it.attnum);
buffer.write_int(it.typeoid);
buffer.write_short(it.typelen);
buffer.write_int(it.typemod);
buffer.write_short(it.format);
}
BOOST_LOG_TRIVIAL(debug) << "PG PROTO row descriptor buffer pos " << buffer.pos();
break;
}
}
return message_size;
}
void PGProtoResultSet::clear() {
row_descr_size = 0;
data_descr.row_values.clear();
row_descr.column_list.clear();
row_descr.count = 0;
}
void PGProtoResultSet::addColumn(std::string colname,
int tableoid,
short attnum,
int typeoid,
short typelen,
int typemod,
short format) {
PGProtoColumnDescr coldef;
coldef.name = colname;
coldef.tableoid = tableoid;
coldef.attnum = attnum;
coldef.typeoid = typeoid;
coldef.typemod = typemod;
coldef.format = format;
row_descr_size += coldef.name.length() + 1; /* NULL byte */
row_descr_size += sizeof(tableoid);
row_descr_size += sizeof(attnum);
row_descr_size += sizeof(typeoid);
row_descr_size += sizeof(typelen);
row_descr_size += sizeof(typemod);
row_descr_size += sizeof(format);
row_descr.column_list.push_back(coldef);
}
void PGProtoResultSet::addRow(std::vector<PGProtoColumnDataDescr> column_values) {
PGProtoColumns columns;
/*
* Sanity check, number of column values should be identical to
* number of column descriptors.
*/
if (row_descr.fieldCount() != column_values.size()) {
std::ostringstream oss;
oss << "number of colums("
<< column_values.size()
<< ") do not match number in row descriptor("
<< row_descr.fieldCount()
<< ")";
throw TCPServerFailure(oss.str());
}
/*
* Push column values to internal rows list
* and calculate new total row size.
*/
for (auto &col : column_values) {
columns.values.push_back(col);
/* The row size includes bytes of the column value _and_
* the 4 byte length value! */
columns.row_size += (sizeof(col.length) + col.length);
}
/* increase row counter */
row_descr.count++;
/* save columns to internal list */
data_descr.row_values.push_back(columns);
}
unsigned int PGProtoResultSet::rowCount() {
return row_descr.count;
}
/* ****************************************************************************
* PGProtoCmdDescr implementation
* ***************************************************************************/
void PGProtoCmdDescr::setCommandTag(ProtocolCommandTag const& tag) {
this->tag = tag;
}
| [
"bernd.helmle@credativ.de"
] | bernd.helmle@credativ.de |
6adc2d367850b26fccd6c1e40dffd5edb365a761 | 55f746a9916cd661176ffff64999c8b02ee6ae89 | /pred.h | b44b647e5122e7c1dd66b62a674f6386dc73d2b3 | [] | no_license | MyNameIsKodak/kuzyhook | 778fa7851ddcba267b2478f051a943307a249e9f | 7e1b8d3bbe290d6fe07303d5b204203cf7c28a5a | refs/heads/master | 2023-07-07T17:16:15.487295 | 2021-09-04T17:35:33 | 2021-09-04T17:35:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 792 | h | #pragma once
class InputPrediction {
public:
float m_curtime;
float m_frametime;
struct PredictionData_t {
int m_flUnpredictedFlags;
vec3_t m_vecUnpredictedVelocity;
vec3_t m_vecUnpredictedOrigin;
} PredictionData;
struct Variables_t {
float m_flFrametime;
float m_flCurtime;
float m_flVelocityModifier;
int m_fTickcount;
float m_flForwardMove;
float m_flSideMove;
vec3_t m_vecVelocity;
vec3_t m_vecOrigin;
int m_fFlags;
} m_stored_variables;
struct viewmodel_t {
float m_flViewmodelCycle;
float m_flViewmodelAnimTime;
} StoredViewmodel;
public:
void update();
void run();
void restore();
};
extern InputPrediction g_inputpred; | [
"somageller06@gmail.com"
] | somageller06@gmail.com |
c0ecd8088fb93609d3ce50eb565ab3b4ad664dc3 | a40e65eb1f6f494b3db0266ec1f7ed7f583927ab | /question42.cpp | 6524719bcff052359bd4e354f9067dbe5e49b868 | [] | no_license | Txiaobin/coding-interviews | d9dda4aca2376dc546c8370215735bb76d074158 | bb7862c481e415cc76b716f369f2b9de5ecf9496 | refs/heads/master | 2020-06-16T18:30:40.379944 | 2019-08-28T01:49:08 | 2019-08-28T01:49:08 | 195,665,059 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 788 | cpp | /*
输入一个整型数组,数组中有正数也有负数。数组中的一个或者连续多个整数组成一个子数组,求所有子数组的和的最大值。要求时间复杂度为 O(n)。
例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。
xiaobin9652@163.com;
Xiaobin Tian;
*/
#include<vector>
using namespace::std;
class Solution {
public:
int FindGreatestSumOfSubArray(vector<int> array) {
if(array.size() == 0)
return 0;
vector<int> sum;
int max = array[0];
for(int i = 0; i < array.size(); ++i){
int temp;
if(i == 0 || sum[i-1] < 0)
temp = array[i];
if(i != 0 && sum[i-1]>0)
temp = sum[i-1] + array[i];
sum.push_back(temp);
if(temp > max)
max = temp;
}
return max;
}
}; | [
"xiaobin9652@163.com"
] | xiaobin9652@163.com |
a624e116b58edf04976c18f7a91a67450d4f2fda | 481cba865f0fed25c929c0c874f8ef8b58d3d06f | /src/gui/collabwebgraph.cpp | a03a656c68537242ec8f5d90cb71fc069de2b566 | [
"MIT",
"BSD-3-Clause"
] | permissive | lssjByron/teamsirus | d4f3af6ae75aacff9675afb3a200a9198ebef672 | 21f5f26f410eb0262754006d7c4a024c160e6401 | refs/heads/master | 2020-03-22T22:38:14.548601 | 2018-07-12T20:38:16 | 2018-07-12T20:38:16 | 140,762,337 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,347 | cpp | #include "collabwebgraph.h"
#include "ui_collabwebgraph.h"
#include "math.h"
#include <iterator>
#include <QList>
#include <QPair>
#include <QDebug>
#include <QFileInfo>
#include "mainwindow.h"
#include <QGraphicsDropShadowEffect>
#include <QPointF>
#include <QObject>
#include <qobjectdefs.h>
#include <QStyle>
#include <QDesktopWidget>
#include <QSize>
#include <QRect>
#include <qsize.h>
CollabWebGraph::CollabWebGraph(QWidget *parent) :
QDialog(parent),
ui(new Ui::CollabWebGraph)
{
ui->setupUi(this);
QGraphicsDropShadowEffect* shadowEffect = new QGraphicsDropShadowEffect();
shadowEffect->setBlurRadius( 5 ); shadowEffect->setOffset(0.0); shadowEffect->setBlurRadius(25.0);
ui->frame->setGraphicsEffect(shadowEffect);
//this->setWindowFlags(Qt::Window | Qt:: FramelessWindowHint);
//this->showMaximized();
QSize availableSize = qApp->desktop()->availableGeometry().size();
int width = availableSize.width();
int height = availableSize.height();
//width = width*.8;
//height = height*.8;
QSize newSize(width,height);
this->setGeometry(
QStyle::alignedRect(
Qt::LeftToRight,
Qt::AlignCenter,
newSize,
qApp->desktop()->availableGeometry()
)
);
// qSize newSize(parentWidget()->width(),parentWidget()->height();
//this->setGeometry(QStyle::alignedRect(Qt::LeftToRight,Qt::AlignCenter, newSize,qApp->desktop()->availableGeometry()));
}
void CollabWebGraph::init(QList<CollabWebGraph::CollabData> allCollabData, QString pathName)
{
allCollaborationData = allCollabData; publicationPathName=pathName;
// (1): CREATE OUR nodeReferences (a "reference sheet" of unique author names and their corresponding node number)
int count=1; QList<QString> init;
foreach (CollabWebGraph::CollabData collabDataItem, allCollabData)
{
nodeReferences.append(qMakePair(collabDataItem.authName,count)); count++;
}
// (1.1):
//CREATE n NODES (n = allCollabData.length (ie. the number of authors that collaborated))
count = 0;
QList<int> collaborationTotals; //for tallying up total number of collaborations done by each author
foreach (CollabWebGraph::CollabData item, allCollabData)
{
QPushButton *btn = new QPushButton(QString::number(count+1), ui->widget); //Create a node for each CollabData item ie. each author (which is technically a button (that can be pressed by user to highlight node's connecting lines))
if (allCollabData.size()<20)
{
//SET STYLE OF NODES
btn->setMinimumHeight(NODE_SIZE);
btn->setMaximumHeight(NODE_SIZE);
btn->setMinimumWidth(NODE_SIZE);
btn->setMaximumWidth(NODE_SIZE);
//btn->setFlat(true);
btn->setCursor(Qt::PointingHandCursor); //btn->setFont();
btn->setStyleSheet("font-size: 24pt");
QGraphicsDropShadowEffect* shadowEffect = new QGraphicsDropShadowEffect(); //Add shadow to button
shadowEffect->setBlurRadius( 5 ); shadowEffect->setOffset(0.0); shadowEffect->setBlurRadius(35.0);
btn->setGraphicsEffect(shadowEffect);
//Get author's name to place in ToolTip label that displays when user hovers cursor over node
QString memberName = nodeReferences[count].first;
btn->setToolTip(memberName);
btn->setToolTipDuration(0);
//END OF NODE STYLING
mNodes.append(btn); count++;
}
else if (allCollabData.size()>=20 && allCollabData.size()<40)
{
//SET STYLE OF NODES
btn->setMinimumHeight(NODE_SIZE/2);
btn->setMaximumHeight(NODE_SIZE/2);
btn->setMinimumWidth(NODE_SIZE/2);
btn->setMaximumWidth(NODE_SIZE/2);
//btn->setFlat(true);
btn->setCursor(Qt::PointingHandCursor); //btn->setFont();
btn->setStyleSheet("font-size: 12pt");
QGraphicsDropShadowEffect* shadowEffect = new QGraphicsDropShadowEffect(); //Add shadow to button
shadowEffect->setBlurRadius( 5 ); shadowEffect->setOffset(0.0); shadowEffect->setBlurRadius(35.0);
btn->setGraphicsEffect(shadowEffect);
//Get author's name to place in ToolTip label that displays when user hovers cursor over node
QString memberName = nodeReferences[count].first;
btn->setToolTip(memberName);
btn->setToolTipDuration(0);
//END OF NODE STYLING
mNodes.append(btn); count++;
}
else if (allCollabData.size()>=40 && allCollabData.size()<80)
{
//SET STYLE OF NODES
btn->setMinimumHeight(NODE_SIZE/4);
btn->setMaximumHeight(NODE_SIZE/4);
btn->setMinimumWidth(NODE_SIZE/4);
btn->setMaximumWidth(NODE_SIZE/4);
//btn->setFlat(true);
btn->setCursor(Qt::PointingHandCursor); //btn->setFont();
btn->setStyleSheet("font-size: 6pt");
QGraphicsDropShadowEffect* shadowEffect = new QGraphicsDropShadowEffect(); //Add shadow to button
shadowEffect->setBlurRadius( 5 ); shadowEffect->setOffset(0.0); shadowEffect->setBlurRadius(35.0);
btn->setGraphicsEffect(shadowEffect);
//Get author's name to place in ToolTip label that displays when user hovers cursor over node
QString memberName = nodeReferences[count].first;
btn->setToolTip(memberName);
btn->setToolTipDuration(0);
//END OF NODE STYLING
mNodes.append(btn); count++;
}
else if (allCollabData.size()>=80 && allCollabData.size()<=160)
{
//SET STYLE OF NODES
btn->setMinimumHeight(NODE_SIZE/8);
btn->setMaximumHeight(NODE_SIZE/8);
btn->setMinimumWidth(NODE_SIZE/8);
btn->setMaximumWidth(NODE_SIZE/8);
//btn->setFlat(true);
btn->setCursor(Qt::PointingHandCursor); //btn->setFont();
btn->setStyleSheet("font-size: 3pt"); //Stylesheet styles
QGraphicsDropShadowEffect* shadowEffect = new QGraphicsDropShadowEffect(); //Add shadow to button
shadowEffect->setBlurRadius( 5 ); shadowEffect->setOffset(0.0); shadowEffect->setBlurRadius(35.0);
btn->setGraphicsEffect(shadowEffect);
//Get author's name to place in ToolTip label that displays when user hovers cursor over node
QString memberName = nodeReferences[count].first;
btn->setToolTip(memberName);
btn->setToolTipDuration(0);
//END OF NODE STYLING
mNodes.append(btn); count++;
}
else if (allCollabData.size()>160)
{
ui->label_WG_title->setText("The number of collaborations found in this file has exceeded NVIZION's ability to fit all collaboration data on this screen. Unfortunately, NVIZION is unable to display this collaboration web graph for you :(");
}
collaborationTotals.append(item.datails.size());
}
//CONNECT GENERATED NODE BUTTONS TO THE NODEPRESSED SLOT
//CALL CONNECT FUNCTION INSIDE A FOREACH LOOP TO CONNECT ALL GENERATED BUTTONS
foreach(QPushButton* btn, mNodes)
{
connect(btn,SIGNAL(clicked(bool)),this,SLOT(nodePressed()));
}
//CREATE EDGES (connecting lines between nodes that represent a collaboration between 2 authors)
// ALGORITHM B.3.a
// (2): BUILD A UNIQUE LIST OF AUTHOR NAMES THAT HAVE COLLABORATED WITH authName FOR EACH authName (building the 'authNodeConnections' QList of Qlist QStrings.
bool alreadyExists=false;
QList<QString> uniqueCollaborators;
foreach (CollabWebGraph::CollabData collabDataItem, allCollabData)
{
uniqueCollaborators.clear(); //Make a temp QList of unique author names that have collab'd with authName to be appended to authNodeConnections. The order of authNodeConnections's QLists is equal to the each author's Node number.
QList<QPair<QString,QString>> collabDataList = collabDataItem.datails; //Get the list of all collaborations for 'n' author
for (int i=0;i<collabDataList.count();++i) //Now, go through all collaborations and add only unique collaborators to "addedAuthCollaborators".
{
QString collaborator = collabDataList[i].first;
alreadyExists=false; //reset our "does-it-already-exist tracker"
foreach(QString addedUniqueCollaborator, uniqueCollaborators)
{
if(QString::compare(collaborator,addedUniqueCollaborator)==0) //"0" = they're equal, ie. not unqiue, so don't add it to the authNodeConnections QList because that author already exists in the list of unqiue authors.
{ alreadyExists=true; break; }
}
if(!alreadyExists) //if it doesn't exist, then it's is a unique author name so add it to the authNodeConnections QList
{ uniqueCollaborators.append(collaborator); }
}
authNodeConnections.append(uniqueCollaborators);
}
/*//CONFIRM RESULTS OF ALGORITHM B.3.a VIA QDEBUG:
QList<QString> debugList;
for (int j=0;j<authNodeConnections.length();++j)
{
qDebug() << "";
qDebug() << "M" << j+1 << "node connections:";
debugList = authNodeConnections[j];
for(int i=0;i<debugList.length();++i)
{ qDebug() << debugList[i]; }
}
*///END OF RESULT CHECKINGALGORITHM B.3.a
// ALGORITHM B.3.b
// (3): CHANGE EACH AUTHOR NAME TO ITS CORRESPONDING NODE NUMBER USING nodeReferences (this is done for each unique author name)
// for each authNodeConnections item, look up matched name in nodeReference and replace with index number
QList<QString> collaborators; QList<int> authNodeConnectionNumbers;
for(int i=0;i<authNodeConnections.length();++i)
{
authNodeConnectionNumbers.clear();
collaborators = authNodeConnections[i];
for(int j=0;j<collaborators.length();++j)
{
QString collaboratorName = collaborators[j];
for(int k=0;k<nodeReferences.length();++k)
{
if(QString::compare(collaboratorName,nodeReferences[k].first)==0) //"0" = a match has been found. Replace "collaborator" with k+1 (its corresponding node number)
{ authNodeConnectionNumbers.append((k+1)); break; }
}
}
authNodeConnectionsNumbers.append(authNodeConnectionNumbers);
authNodeConnections[i].clear(); //destroy redundant data from memory
}
/*//CONFIRM RESULTS OF ALGORITHM B.3.b VIA QDEBUG:
QList<int> debugList;
for (int j=0;j<authNodeConnectionsNumbers.length();++j)
{
qDebug() << "";
qDebug() << "(" << j+1 << ")" << "Node connections:";
qDebug() << "";
debugList = authNodeConnectionsNumbers[j];
for(int i=0;i<debugList.length();++i)
{ qDebug() << debugList[i]; }
}
*///END OF RESULT CHECKING ALGORITHM B.3.b
// ALGORITHM F.2.a (continued in webgraphwidget.cpp)
// (4): Building set of relationships between nodes
QList<int> collabNodelist;
for (int i=0;i<authNodeConnectionsNumbers.length();++i)
{
collabNodelist = authNodeConnectionsNumbers[i];
for(int j=0;j<collabNodelist.length();++j)
{
alreadyExists=false; //assume new relationship is not in nRelationships until proven otherwise
for(int k=0;k<nRelationships.length();++k)
{
if((nRelationships[k].first==i+1 && nRelationships[k].second==collabNodelist[j]) ||
(nRelationships[k].first==collabNodelist[j] && nRelationships[k].second==i+1) ||
(collabNodelist[j] == i+1))
{
alreadyExists=true; break; //this edge has been proven to already exit in nRelationships so do NOT add it
}
}
if(!alreadyExists) //evaluates to TRUE if this edge does not exist in nRelationships; so add it
{ nRelationships.append(QPair<int,int>(i+1,collabNodelist[j])); }
}
}
//eachNodeRelationships
//Alg F.2.b
collabNodelist.clear(); QList<QPair<int,int>> eachNode;
for (int i=0;i<authNodeConnectionsNumbers.length();++i)
{
eachNode.clear();
collabNodelist = authNodeConnectionsNumbers[i];
for(int j=0;j<collabNodelist.length();++j)
{
eachNode.append(QPair<int,int>(i+1,collabNodelist[j])); //qDebug() << i+1 << "," << collabNodelist[j] ;
}
eachNodeRelationships.append(eachNode);
//qDebug() << "";
}
/* debugging Alg F.2.b
for (int i=0;i<eachNodeRelationships.length();++i)
{
qDebug() << ""; qDebug() << "Node:" << i;
for (int j=0; j<eachNodeRelationships[i].length();++j)
{
qDebug() << (eachNodeRelationships[i])[j].first << "," << (eachNodeRelationships[i])[j].second;
}
}
/*
OLD CODE
QList<QList<QPair<int,int>>> nodeRelationships;
QList<QPair<int,int>> eachNodeRelationship;
QPair<int,int> coordinateData;
QList<int> collabNodelist;
for (int i=0;i<authNodeConnectionsNumbers.length();++i)
{
collabNodelist = authNodeConnectionsNumbers[i];
for(int j=0;j<collabNodelist.length();++j)
{
alreadyExists=false; //assume new relationship is not in nRelationships until proven otherwise
for(int k=0;k<nRelationships.length();++k)
{
if((nRelationships[k].first==i+1 && nRelationships[k].second==collabNodelist[j]) ||
(nRelationships[k].first==collabNodelist[j] && nRelationships[k].second==i+1) ||
(collabNodelist[j] == i+1))
{
alreadyExists=true; break; //this edge has been proven to already exit in nRelationships so do NOT add it
}
}
if(!alreadyExists) //evaluates to TRUE if this edge does not exist in nRelationships; so add it
{ nRelationships.append(QPair<int,int>(i+1,collabNodelist[j])); }
}
}
END OF OLD CODE
*/
/* //CONFIRM RESULTS OF ALGORITHM F.2 VIA QDEBUG:
qDebug() << "";qDebug() << "Size of nRelationships:" << nRelationships.size();qDebug() << "";
for (int j=0;j<nRelationships.length();++j)
{
qDebug() << "(" << nRelationships[j].first << "," << nRelationships[j].second << ")";
}
*///END OF RESULT CHECKING ALGORITHM F.2
// CALCULATING TOTAL COLLABORATIONS PARTICIPATED IN FOR EACH AUTHOR
// QList<int> collaborationTotals;
// for(int i=0;i<authNodeConnectionsNumbers.length();++i)
// {
// collaborationTotals.append(authNodeConnectionsNumbers[i].count());
// //qDebug() << collaborationTotals[i];
// }
//PASS ALL NEEDED DATA TO WEBGRAPHWIDGET
ui->widget->setData(mNodes,nRelationships,nodeReferences,allCollaborationData,collaborationTotals,eachNodeRelationships);
for (int i=0; i<nodeReferences.length(); i++)
{
QPair<QString,int> node = nodeReferences[i];
int collCount = collaborationTotals[i];
QString autherName = node.first;
int nodeIndex = node.second;
ui->table_WebGraph_author->insertRow(ui->table_WebGraph_author->rowCount());
QTableWidgetItem *item1 = new QTableWidgetItem();
item1->setData(Qt::EditRole,nodeIndex);
item1->setTextAlignment(Qt::AlignCenter);
QTableWidgetItem *item2 = new QTableWidgetItem(autherName);
item2->setTextAlignment(Qt::AlignCenter);
QTableWidgetItem *item3 = new QTableWidgetItem();
item3->setData(Qt::EditRole,collCount);
item3->setTextAlignment(Qt::AlignCenter);
ui->table_WebGraph_author->setItem(ui->table_WebGraph_author->rowCount()-1,
0, item1);
ui->table_WebGraph_author->setItem(ui->table_WebGraph_author->rowCount()-1,
1, item2);
ui->table_WebGraph_author->setItem(ui->table_WebGraph_author->rowCount()-1,
2, item3);
}
publicationPathName.replace(" > ","/");
QFileInfo publicationFilename(publicationPathName);
QString currentlyViewingFileName = publicationFilename.fileName();
currentlyViewingFileName.prepend("Currently Viewing: ");
ui->WG_FilePath->setText(currentlyViewingFileName);
}
CollabWebGraph::~CollabWebGraph()
{
delete ui;
}
//CREATE SINGLE SLOT TO HANLDE ALL NODE-BUTTON PRESSES
void CollabWebGraph::nodePressed()
{
ui->WG_Button_Reset->setEnabled(true);
QPushButton* nodeBtn = qobject_cast<QPushButton*>(sender());
int nodeNum=-1;
if(nodeBtn != NULL)
{
QString nodeNumber = nodeBtn->text();
nodeNum = nodeNumber.toInt();
//qDebug() << nodeNum;
}
ui->widget->passNodeClicked(nodeNum);
QString authName = nodeReferences[nodeNum-1].first;
authName.append(" collaborated with these members on these publications:");
ui->labal_selectedAuthor->setText(authName);
ui->label_WG_title->setText((nodeReferences[nodeNum-1].first));
ui->tableWidget->clear(); //make sure only clears data
while(ui->tableWidget->rowCount() > 0)
{
ui->tableWidget->removeRow(0);
}
CollabData selected = allCollaborationData[nodeNum -1];
QList<QPair<QString, QString> > details = selected.datails;
for (int i=0; i<details.length(); i++)
{
QPair<QString, QString> data = details[i];
QString authName = data.first;
QString pubTitle = data.second;
ui->tableWidget->insertRow(ui->tableWidget->rowCount());
QTableWidgetItem *item1 = new QTableWidgetItem(authName);
QTableWidgetItem *item2 = new QTableWidgetItem(pubTitle);
ui->tableWidget->setItem((ui->tableWidget->rowCount()-1),0,item1);
ui->tableWidget->setItem((ui->tableWidget->rowCount()-1),1,item2);
}
}
void CollabWebGraph::on_pushButton_5_clicked()
{
this->close();
}
void CollabWebGraph::on_WG_Button_Reset_clicked()
{
ui->WG_Button_Reset->setEnabled(false);
ui->widget->resetClicked();
ui->labal_selectedAuthor->setText("Selected author collaborated with:");
ui->label_WG_title->setText("");
}
// PDF Exporting
void CollabWebGraph::on_pushButton_2_clicked()
{
QString fileName = QFileDialog::getSaveFileName(this, tr("Export File"), QDir::homePath(), tr("PDF (*.pdf)"));
QPdfWriter writer(fileName);
//Setup each PDF page attributes (creator of PDF, pagae orientation)
writer.setCreator("NVIZION");
writer.setPageOrientation(QPageLayout::Portrait);
//Setup QPainter object that paints the widgets on the pages
QPainter painter;
painter.begin(&writer);
//paint the widgets:
//First page has the visualization and title:
//painter.scale(8,8);
ui->widget->render(&painter);
painter.scale(0.83, 0.83);
ui->label_WG_title->render(&painter);
//Second page has legend (which node represents which author and total collabs for each author
writer.newPage();
painter.scale(6, 6);
ui->table_WebGraph_author->render(&painter);
}
void CollabWebGraph::on_table_WebGraph_author_itemClicked(QTableWidgetItem *item)
{
int index = ui->table_WebGraph_author->currentColumn();
int selectedNodeNumber=-1;
if(index==0)
{
selectedNodeNumber=item->text().toInt();
QPushButton* buttonToPush = mNodes[selectedNodeNumber-1];
buttonToPush->click();
}
QString name;
if(index==1)
{
name = item->text();
for(int i=0;i<nodeReferences.length();++i)
{
if(QString::compare(nodeReferences[i].first,name)==0)
{
QPushButton* buttonToPush = mNodes[i];
buttonToPush->click();
}
}
}
}
| [
"byron@invaware.com"
] | byron@invaware.com |
b4aa82a4d96b1eb00cf23e073069108ef5a038e3 | 2b434fd4c0efa344cbce249f0ee0efde99c26cec | /fancyHeart/fancyHeart/Classes/xls/XGate.h | b716791f845f6889bbeed9cc1dfe52c55a72741e | [
"MIT"
] | permissive | PenpenLi/cocos2d-x-3.6 | 03f20c247ba0ee707c9141531f73ab7c581fe6c1 | fd6de11fde929718ddb8f22841d813133d96029e | refs/heads/master | 2021-05-31T12:01:55.879080 | 2016-04-12T06:39:13 | 2016-04-12T06:39:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 634 | h | //XGate自动生成类
#ifndef __fancyHeart__XGate__
#define __fancyHeart__XGate__
#include <iostream>
#include "external/json/document.h"
#include "cocos2d.h"
#include "extensions/cocos-ext.h"
USING_NS_CC;
class XGate{
private:
Value v;
public:
static XGate* record(Value v);
rapidjson::Document doc;
int getId();
std::string getName();
std::string getDesc();
std::string getDesc2();
/*Administrator:
1剧情
2精英
3活动
0秘境*/
int getType();
int getAvatorId();
int getMapId();
/*Administrator:
若关卡b是从关卡a进入的则关卡b的父id为关卡a*/
int getParentId();
};
#endif // defined(__dx__Data__)
| [
"fzcheng813@gmail.com"
] | fzcheng813@gmail.com |
b389e9eaa06f5242f48810cf5a68038ed4b739c9 | b439b8840237b26e42445e18a745318b4d794e27 | /DCFoundation/DCFoundation/Source/Base/DCFMutableData.h | c8952bb120c65c714598c10faecddf8093ec25ca | [] | no_license | Design-Complex/DCFoundation | dbf41154b98c80abc80b85262cd824a494664514 | 75aebbf2bf0cfa9e536fbcce898d4cba5b8c5fe7 | refs/heads/master | 2021-01-20T23:37:39.030177 | 2015-06-24T19:41:21 | 2015-06-24T19:41:21 | 32,950,964 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 382 | h | //
// DCFMutableData.h
// DCFoundation
//
// Created by Rob Dotson on 6/24/15.
// Copyright (c) 2015 Design Complex LLC. All rights reserved.
//
#ifndef _DCFMutableData_
#define _DCFMutableData_
#include <DCFoundation/DCFData.h>
DCF_NAMESPACE_BEGIN
class DCF_VISIBLE MutableData : public virtual DCFData {
}; // DCF::Data
DCF_NAMESPACE_END
#endif // _DCFMutableData_
| [
"rob@robdotson.info"
] | rob@robdotson.info |
6244451b2be96b658d9c50b571bd3c1b82bbca75 | b1aef802c0561f2a730ac3125c55325d9c480e45 | /src/ripple/beast/unity/beast_utility_unity.cpp | 71de0b8ceffb3add02bc159ef1a49dd99d49c656 | [] | no_license | sgy-official/sgy | d3f388cefed7cf20513c14a2a333c839aa0d66c6 | 8c5c356c81b24180d8763d3bbc0763f1046871ac | refs/heads/master | 2021-05-19T07:08:54.121998 | 2020-03-31T11:08:16 | 2020-03-31T11:08:16 | 251,577,856 | 6 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 141 | cpp |
#include <ripple/beast/utility/src/beast_Journal.cpp>
#include <ripple/beast/utility/src/beast_PropertyStream.cpp>
| [
"sgy-official@hotmail.com"
] | sgy-official@hotmail.com |
bc197a70da3d407451372f2b991dd4d226fd05f4 | e3b7d7960949a42948b4fe0a05301c8794daf0a3 | /projects/worker/server.cpp | 285c1ec689000173e187dbe44c9347479b34e5c6 | [] | no_license | masixian/RelayLive | d2ba6af6cddae8cc2e05507a3002d715db030f8d | 41e2c167da8bd6925d0e25524e22e7eeaf06eca1 | refs/heads/master | 2022-05-12T01:20:38.766811 | 2022-03-25T06:00:40 | 2022-03-25T06:00:40 | 196,906,055 | 0 | 0 | null | 2019-07-15T01:59:09 | 2019-07-15T01:59:08 | null | GB18030 | C++ | false | false | 15,884 | cpp | #include "server.h"
#include "sha1.h"
#include "base64.h"
#include "uv.h"
#include "util.h"
#include "utilc.h"
#include "easylog.h"
#include "worker.h"
#include <unordered_map>
#include <sstream>
using namespace util;
uv_loop_t uvLoopLive;
uv_tcp_t uvTcpServer;
class CLiveSession : public ILiveSession
{
public:
CLiveSession();
virtual ~CLiveSession();
virtual void AsyncSend(); //外部线程通知可以发送数据了
void OnRecv(char* data, int len);
void OnSend(); //发送数据
void OnClose();
bool ParseHeader(); //解析报文头
bool ParsePath(); //解析报文头中的uri
void WsAcceptKey(); //生成websocket应答的Sec-WebSocket-Accept字段
void WriteFailResponse(); //报文不合法时的应答
string strRemoteIP; //客户端IP地址
uint32_t nRemotePort; //客户端port
uv_tcp_t socket; //tcp连接
char readBuff[1024*1024]; //读取客户端内容缓存
string dataCatch; //读取到的数据
bool parseHeader; //是否解析协议头
bool connected;
int handlecount;
string method; //解析出请求的方法
string path; //解析出请求的uri
RequestParam Params; //uri中解析出参数
string version; //解析出请求的协议版本
string Connection; //报文头中的字段值
string Upgrade; //报文头中的字段值
string SecWebSocketKey; //websocket报文头中的字段值
string SecWebSocketAccept; //计算出websocket应答报文头的字段值
string xForwardedFor; //报文头中的字段值 代理流程
bool isWs; // 是否为websocket
CLiveWorker *pWorker; // worker对象
CNetStreamMaker wsBuff; //协议头数据
CNetStreamMaker writeBuff; //缓存要发送的数据
bool writing; //正在发送
uv_async_t asWrite; //外部通知有视频数据可以发送
uv_async_t asClose; //外部通知关闭连接
uv_write_t writeReq; //发送请求
};
//////////////////////////////////////////////////////////////////////////
static string url_decode(string str)
{
int len = str.size();
string dest;
for (int i=0; i<len; i++) {
char c = str[i];
if (c == '+') {
dest.push_back(' ');
} else if (c == '%' && i<len-2 && isxdigit((int)str[i+1]) && isxdigit((int)str[i+2])) {
char h1 = str[++i];
char h2 = str[++i];
char v = (h1>='a'?h1-'a'+10:(h1>='A'?h1-'A'+10:h1-'0'))*16 + (h2>='a'?h2-'a'+10:(h2>='A'?h2-'A'+10:h2-'0'));
dest.push_back(v);
} else {
dest.push_back(str[i]);
}
}
return dest;
}
static void on_close(uv_handle_t* handle) {
CLiveSession *skt = (CLiveSession*)handle->data;
skt->handlecount--;
if(skt->handlecount == 0 && !skt->connected) {
delete skt;
}
}
static void on_uv_close(uv_handle_t* handle) {
CLiveSession *skt = (CLiveSession*)handle->data;
Log::warning("on close client [%s:%u]", skt->strRemoteIP.c_str(), skt->nRemotePort);
skt->OnClose();
}
static void on_uv_shutdown(uv_shutdown_t* req, int status) {
CLiveSession *skt = (CLiveSession*)req->data;
Log::warning("on shutdown client [%s:%d]", skt->strRemoteIP.c_str(), skt->nRemotePort);
delete req;
uv_close((uv_handle_t*)&skt->socket, on_uv_close);
}
static void on_uv_alloc(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf){
CLiveSession *skt = (CLiveSession*)handle->data;
*buf = uv_buf_init(skt->readBuff, 1024*1024);
}
static void on_uv_read(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) {
CLiveSession *skt = (CLiveSession*)stream->data;
if(nread < 0) {
skt->connected = false;
if(nread == UV_ECONNRESET || nread == UV_EOF) {
//对端发送了FIN
Log::warning("remote close socket [%s:%u]", skt->strRemoteIP.c_str(), skt->nRemotePort);
uv_close((uv_handle_t*)&skt->socket, on_uv_close);
} else {
uv_shutdown_t* req = new uv_shutdown_t;
req->data = skt;
Log::error("Read error %s", uv_strerror((int)nread));
Log::warning("remote shutdown socket [%s:%u]", skt->strRemoteIP.c_str(), skt->nRemotePort);
uv_shutdown(req, stream, on_uv_shutdown);
}
return;
}
skt->OnRecv(buf->base, (int)nread);
}
static void on_uv_write(uv_write_t* req, int status) {
CLiveSession *skt = (CLiveSession*)req->data;
skt->writing = false;
skt->OnSend();
}
/** 接收到客户端发送来的连接 */
static void on_connection(uv_stream_t* server, int status) {
if(status != 0) {
Log::error("status:%d %s", status, uv_strerror(status));
return;
}
CLiveSession *sess = new CLiveSession();
int ret = uv_accept(server, (uv_stream_t*)(&sess->socket));
if(ret != 0) {
delete sess;
return;
}
//socket远端ip和端口
struct sockaddr peername;
int namelen = sizeof(struct sockaddr);
ret = uv_tcp_getpeername(&sess->socket, &peername, &namelen);
if(peername.sa_family == AF_INET) {
struct sockaddr_in* sin = (struct sockaddr_in*)&peername;
char addr[46] = {0};
uv_ip4_name(sin, addr, 46);
sess->strRemoteIP = addr;
sess->nRemotePort = sin->sin_port;
} else if(peername.sa_family == AF_INET6) {
struct sockaddr_in6* sin6 = (struct sockaddr_in6*)&peername;
char addr[46] = {0};
uv_ip6_name(sin6, addr, 46);
sess->strRemoteIP = addr;
sess->nRemotePort = sin6->sin6_port;
}
Log::warning("new remote socket [%s:%u]", sess->strRemoteIP.c_str(), sess->nRemotePort);
uv_read_start((uv_stream_t*)&sess->socket, on_uv_alloc, on_uv_read);
}
static void on_uv_async_write(uv_async_t* handle) {
CLiveSession *skt = (CLiveSession*)handle->data;
skt->OnSend();
}
static void on_uv_async_close(uv_async_t* handle) {
//CLiveSession *skt = (CLiveSession*)handle->data;
}
static void run_loop_thread(void* arg) {
uv_run(&uvLoopLive, UV_RUN_DEFAULT);
uv_loop_close(&uvLoopLive);
}
//////////////////////////////////////////////////////////////////////////
RequestParam::RequestParam()
: strType("flv")
, nWidth(0)
, nHeight(0)
, nProbSize(Settings::getValue("FFMPEG","probsize",25600))
, nProbTime(Settings::getValue("FFMPEG","probtime",1000))
, nInCatch(Settings::getValue("FFMPEG","incatch",1024*16))
, nOutCatch(Settings::getValue("FFMPEG","outcatch",1024*16))
{}
CLiveSession::CLiveSession()
: nRemotePort(0)
, parseHeader(false)
, connected(true)
, handlecount(2)
, isWs(false)
, pWorker(NULL)
, writing(false)
{
socket.data = this;
uv_tcp_init(&uvLoopLive, &socket);
asWrite.data = this;
uv_async_init(&uvLoopLive, &asWrite, on_uv_async_write);
asClose.data = this;
uv_async_init(&uvLoopLive, &asClose, on_uv_async_close);
writeReq.data = this;
}
CLiveSession::~CLiveSession() {
Log::debug("~CLiveSession()");
}
void CLiveSession::AsyncSend() {
uv_async_send(&asWrite);
}
void CLiveSession::OnRecv(char* data, int len) {
dataCatch.append(data, len);
// http头解析
if(!parseHeader && dataCatch.find("\r\n\r\n") != std::string::npos) {
if(!ParseHeader()) {
Log::error("error request");
WriteFailResponse();
return;
}
parseHeader = true;
if(!strcasecmp(Connection.c_str(), "Upgrade") && !strcasecmp(Upgrade.c_str(), "websocket")) {
isWs = true;
Log::debug("Websocket req: %s", path.c_str());
} else {
Log::debug("Http req: %s", path.c_str());
}
//解析请求
if(!ParsePath()) {
Log::error("error path:%s", path.c_str());
WriteFailResponse();
return;
}
//创建worker
string clientIP = xForwardedFor.empty()?strRemoteIP:xForwardedFor;
pWorker = CreatLiveWorker(Params, isWs, this, clientIP);
//发送应答
stringstream ss;
if(isWs){
WsAcceptKey();
ss << version << " 101 Switching Protocols\r\n"
"Upgrade: WebSocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Accept: " << SecWebSocketAccept << "\r\n"
"\r\n";
} else {
string mime;
if(Params.strType == "flv")
mime = "video/x-flv";
else if(Params.strType == "h264")
mime = "video/h264";
else if(Params.strType == "mp4")
mime = "video/mp4";
ss << version << " 200 OK\r\n"
"Connection: " << Connection << "\r\n"
"Transfer-Encoding: chunked\r\n"
"Access-Control-Allow-Origin: *\r\n"
"Content-Type: " << mime << "\r\n"
"Cache-Control: no-cache\r\n"
"Pragma: no-cache\r\n"
"Expires: -1\r\n"
"\r\n";
}
writeBuff.clear();
writeBuff.append_string(ss.str().c_str());
writing = true;
uv_buf_t buff = uv_buf_init(writeBuff.get(), writeBuff.size());
uv_write(&writeReq, (uv_stream_t*)&socket, &buff, 1, on_uv_write);
} else {
if(dataCatch.find("\r\n\r\n") != std::string::npos) {
Log::debug("%s", dataCatch.c_str());
}
}
}
void CLiveSession::OnSend() {
if(writing){
printf("== ");
return;
}
char *flv = NULL;
int len = pWorker->get_flv_frame(&flv);
if(len == 0)
return;
wsBuff.clear();
writeBuff.clear();
while (len) {
writeBuff.append_data(flv, len);
pWorker->next_flv_frame();
len = pWorker->get_flv_frame(&flv);
}
len = writeBuff.size();
if(isWs) {
if(len <= 125) {
wsBuff.append_byte(0x82); //10000010
wsBuff.append_byte(len);
} else if(len <= 65535) {
wsBuff.append_byte(0x82); //10000010
wsBuff.append_byte(126);
wsBuff.append_be16(len);
} else {
wsBuff.append_byte(0x82); //10000010
wsBuff.append_byte(127);
wsBuff.append_be64(len);
}
} else {
char chunk[20] = {0};
sprintf(chunk, "%x\r\n", len);
wsBuff.append_data(chunk, strlen(chunk));
writeBuff.append_string("\r\n");
}
writing = true;
uv_buf_t buff[] = {
uv_buf_init(wsBuff.get(), wsBuff.size()),
uv_buf_init(writeBuff.get(), writeBuff.size())
};
uv_write(&writeReq, (uv_stream_t*)&socket, buff, 2, on_uv_write);
}
void CLiveSession::OnClose() {
if(pWorker != NULL)
pWorker->close();
uv_close((uv_handle_t*)&asWrite, on_close);
uv_close((uv_handle_t*)&asClose, on_close);
if(connected) {
connected = false;
uv_shutdown_t* req = new uv_shutdown_t;
req->data = this;
uv_shutdown(req, (uv_stream_t*)&socket, on_uv_shutdown);
}
}
bool CLiveSession::ParseHeader() {
size_t pos1 = dataCatch.find("\r\n"); //第一行的结尾
size_t pos2 = dataCatch.find("\r\n\r\n"); //头的结尾位置
string reqline = dataCatch.substr(0, pos1); //第一行的内容
vector<string> reqlines = util::String::split(reqline, ' ');
if(reqlines.size() != 3)
return false;
method = reqlines[0].c_str();
path = reqlines[1];
version = reqlines[2].c_str();
string rawHeaders = dataCatch.substr(pos1+2, pos2-pos1);
dataCatch = dataCatch.substr(pos2+4, dataCatch.size()-pos2-4);
vector<string> headers = util::String::split(rawHeaders, "\r\n");
for(auto &hh : headers) {
string name, value;
bool b = false;
for(auto &c:hh){
if(!b) {
if(c == ':'){
b = true;
} else {
name.push_back(c);
}
} else {
if(!value.empty() || c != ' ')
value.push_back(c);
}
}
if(!strcasecmp(name.c_str(), "Connection")) {
Connection = value;
} else if(!strcasecmp(name.c_str(), "Upgrade")) {
Upgrade = value;
} else if(!strcasecmp(name.c_str(), "Sec-WebSocket-Key")) {
SecWebSocketKey = value;
} else if(!strcasecmp(name.c_str(), "x-forwarded-for")) {
xForwardedFor = value;
}
}
return true;
}
bool CLiveSession::ParsePath() {
vector<string> uri = util::String::split(path, '?');
if(uri.size() != 2)
return false;
vector<string> param = util::String::split(uri[1], '&');
for(auto p:param) {
vector<string> kv = util::String::split(p, '=');
if(kv.size() != 2)
continue;
if(kv[0] == "code")
Params.strCode = kv[1];
else if(kv[0] == "url")
Params.strUrl = url_decode(kv[1]);
else if(kv[0] == "host")
Params.strHost = kv[1];
else if(kv[0] == "port")
Params.nPort = stoi(kv[1]);
else if(kv[0] == "user")
Params.strUsr = kv[1];
else if(kv[0] == "pwd")
Params.strPwd = kv[1];
else if(kv[0] == "channel")
Params.nChannel = stoi(kv[1]);
else if(kv[0] == "type")
Params.strType = kv[1];
else if(kv[0] == "hw"){
string strHw = kv[1];
if(!strHw.empty() && strHw.find('*') != string::npos)
sscanf(strHw.c_str(), "%d*%d", &Params.nWidth, &Params.nHeight);
} else if(kv[0] == "probsize")
Params.nProbSize = stoi(kv[1]);
else if(kv[0] == "probtime")
Params.nProbTime = stoi(kv[1]);
else if(kv[0] == "incatch")
Params.nInCatch = stoi(kv[1]);
else if(kv[0] == "outcatch")
Params.nOutCatch = stoi(kv[1]);
else if(kv[0] == "begintime")
Params.strBeginTime = kv[1];
else if(kv[0] == "endtime")
Params.strEndTime = kv[1];
}
return true;
}
void CLiveSession::WsAcceptKey() {
SHA1 sha1;
string tmp = SecWebSocketKey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
tmp = (char*)sha1.Comput((uint8_t*)tmp.c_str(), tmp.size());
SecWebSocketAccept = Base64::Encode((uint8_t*)tmp.c_str(), tmp.size());
Log::debug("%s --> %s", SecWebSocketKey.c_str(), SecWebSocketAccept.c_str());
}
void CLiveSession::WriteFailResponse() {
stringstream ss;
ss << version << " 400 Bad request\r\n"
"Connection: " << Connection << "\r\n"
"Access-Control-Allow-Origin: *\r\n"
"Content-Length: 0\r\n"
"\r\n";
writeBuff.clear();
writeBuff.append_string(ss.str().c_str());
writing = true;
uv_buf_t buff = uv_buf_init(writeBuff.get(), writeBuff.size());
uv_write(&writeReq, (uv_stream_t*)&socket, &buff, 1, on_uv_write);
}
//////////////////////////////////////////////////////////////////////////
void start_service(uint32_t port) {
uv_loop_init(&uvLoopLive);
uv_tcp_init(&uvLoopLive, &uvTcpServer);
struct sockaddr_in addr;
uv_ip4_addr("0.0.0.0", port, &addr);
uv_tcp_bind(&uvTcpServer, (const sockaddr*)&addr, 0);
uv_listen((uv_stream_t*)&uvTcpServer, 512, on_connection);
uv_thread_t tid;
uv_thread_create(&tid, run_loop_thread, NULL);
}
namespace Server {
int Init(int port) {
start_service(port);
return 0;
}
int Cleanup() {
return 0;
}
} | [
"wlla@jiangsuits.com"
] | wlla@jiangsuits.com |
89702d6f979a0ffd634d0c5ddd8ab1b370479460 | 5b12e6a9bb6000fe14f758374e83269caf7c9c80 | /BamIterator.hpp | 77b3538611a43b28bcb19d4f7e468054ac6f0f49 | [] | no_license | escherba/asw-utils | 467a2dde329986ae02de50aa919ad5d5a5e3e7d5 | 27556de62e7228796bf2e105601287792cfb5cf4 | refs/heads/master | 2021-01-22T13:17:19.268682 | 2013-07-06T22:12:01 | 2013-07-06T22:12:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,469 | hpp | /*
* =====================================================================================
*
* Filename: BamIterator.hpp
*
* Description: A wrapper around BAM reading functions provided in samtools
*
* Version: 1.0
* Created: 04/08/2011 15:03:18
* Revision: none
* Compiler: gcc
*
* Author: Eugene Scherba (es), escherba@bu.edu
* Company: Boston University
*
* Copyright (c) 2011 Eugene Scherba
*
* 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.
* =====================================================================================
*/
class BamIterator;
/*
* =====================================================================================
* Class: BamHeader
* Description: A wrapper around Samtools bam_header_t type
* =====================================================================================
*/
class BamHeader
{
private:
bam_header_t *header;
// disallow copying and asignment by declaring the copy constructor and the
// assignment operator private
BamHeader(const BamHeader&);
BamHeader& operator=(const BamHeader&);
public:
/*
*--------------------------------------------------------------------------------------
* Class: BamHeader
* Method: BamHeader :: BamHeader
* Description: Default constructor
*--------------------------------------------------------------------------------------
*/
BamHeader(bamFile fp) :
header(bam_header_read(fp))
{}
BamHeader() :
header(NULL)
{}
/*
*--------------------------------------------------------------------------------------
* Class: BamHeader
* Method: BamHeader :: ~BamHeader
* Description: Default destructor
*--------------------------------------------------------------------------------------
*/
~BamHeader() {
if (header) bam_header_destroy(header);
}
bam_header_t* operator->() { return header; }
bam_header_t& operator*() { return *header; }
friend class BamIterator;
};
class BamIterator : public std::iterator<std::input_iterator_tag, bam1_t>
{
public:
// Copy Constuctor
BamIterator(const BamIterator& r) :
_is_owner(false),
_is_fp_owner(false),
_row_number(r._row_number),
_fp(r._fp),
_bam(r._bam),
_read_return(r._read_return)
{}
BamIterator() :
_is_owner(false),
_is_fp_owner(false),
_row_number(0u),
_fp(NULL),
_bam(NULL),
_read_return(0)
{}
BamIterator(char *path, BamHeader& bh) :
_is_owner(true),
_is_fp_owner(true),
_row_number(1u),
_fp(bam_open(path, "r")),
_bam(bam_init1()),
_read_return(0)
{
if (_fp == NULL) {
bam_destroy1(_bam);
exit(EXIT_FAILURE);
}
bh.header = bam_header_read(_fp);
_read_return = bam_read1(_fp, _bam);
if (_read_return <= 0) {
_row_number = 0u;
}
}
BamIterator(bamFile fp) :
_is_owner(true),
_is_fp_owner(false),
_row_number(1u),
_fp(fp),
_bam(bam_init1()),
_read_return(bam_read1(fp, _bam))
{
if (_read_return <= 0) {
_row_number = 0u;
}
}
~BamIterator() {
if (_is_fp_owner) bam_close(_fp);
if (_is_owner) bam_destroy1(_bam);
}
// --------------------------------
BamIterator& operator=(const BamIterator& r) {
// Treating self-asignment (this == &r) the same as assignment
_is_owner = false;
_is_fp_owner = r._is_fp_owner;
_row_number = r._row_number;
_fp = r._fp;
_bam = r._bam;
_read_return = r._read_return;
return *this;
}
BamIterator& operator++() { // pre-increment
_read_return = bam_read1(_fp, _bam);
if (_read_return > 0) {
++_row_number;
} else {
std::cerr << _row_number << " rows read" << std::endl;
_row_number = 0u;
}
return *this;
}
BamIterator operator++(int) { // post-increment
BamIterator tmp(*this);
operator++();
return tmp;
}
bool operator==(const BamIterator& r) {
return _row_number == r._row_number;
}
bool operator!=(const BamIterator& r) {
return _row_number != r._row_number;
}
bam1_t* operator->() { return _bam; }
bam1_t& operator*() { return *_bam; }
protected:
bool _is_owner; // whether to call bam_destroy1 upon object destruction
bool _is_fp_owner;
unsigned int _row_number;
bamFile _fp;
bam1_t* _bam;
int _read_return;
};
| [
"escherba@gmail.com"
] | escherba@gmail.com |
ea87206aaf224dfec59f15917547b6a4611a728e | 1ad39267d734f4236fb93d519a856fcdee7f8cc7 | /ACE_Event_Handler_Server/Client_Acceptor.h | ce45e274a6e2974b14e6e4393666cef410889e5f | [] | no_license | yoloo/ace_reactor | 328db469f321a6590cb28881c46bc60c06cb2ca5 | 151e706eae41ea4f6be0d6571e485de2b1ba9b46 | refs/heads/master | 2021-01-23T12:25:50.289879 | 2015-06-17T00:45:29 | 2015-06-17T00:45:29 | 37,563,815 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,112 | h | #ifndef _CLIENT_ACCEPTOR_H_
#define _CLIENT_ACCEPTOR_H_
#include "Client_Service.h"
/*ACE headers.*/
#include "ace/Reactor.h"
#include "ace/SOCK_Acceptor.h"
class ClientAcceptor : public ACE_Event_Handler
{
public:
ClientAcceptor();
explicit ClientAcceptor( const ACE_INET_Addr & addr );
virtual ~ClientAcceptor();
public:/*Interface.*/
/*Complete some initializations of server.*/
int open();
public:/*Tools.*/
/*Set listen address.*/
void set_listen_addr( const ACE_INET_Addr & addr );
/*Get listen address.*/
ACE_INET_Addr get_listen_addr() const;
public:/*Override.*/
/*Called by the reactor when an input event happens.*/
virtual int handle_input( ACE_HANDLE handle = ACE_INVALID_HANDLE );
virtual int handle_close( ACE_HANDLE handle, ACE_Reactor_Mask close_mask );
/*Called by the reactor to determine the underlying handle, such as the peer handle.*/
virtual ACE_HANDLE get_handle() const;
private:/*Data members.*/
ACE_SOCK_Acceptor m_acceptor;/*Passive connection object.*/
ACE_INET_Addr m_listenAddr;/*Listen address.*/
};
#endif | [
"yoloo0624@gmail.com"
] | yoloo0624@gmail.com |
53e4e397c8e1eeef63447fad3447cea8ede8c35c | 54046ec2ff1717d752798ed47bf5dfde6f52713d | /grades.cpp | 20123c91005cbaa8fa24927a828ef469dd36071d | [] | no_license | Surbhi050192/Detect-and-Remove-Collision-in-Hash-Table-using-LinkedList | aad23d4ac8be3005dbcd4a805a98aee37316e758 | da8a585e01d3b9f341c697ee833fb430e323c659 | refs/heads/master | 2021-01-23T05:24:17.529340 | 2018-01-31T21:57:31 | 2018-01-31T21:57:31 | 86,302,608 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,224 | cpp | // Name: Surbhi Goel
// Loginid: surbhigo
// CSCI 455 PA5
// Fall 2016
/*
* grades.cpp
* A program to test the Table class.
* How to run it:
* grades [hashSize]
*
* the optional argument hashSize is the size of hash table to use.
* if it's not given, the program uses default size (Table::HASH_SIZE)
*
*/
#include "Table.h"
#include<string>
// cstdlib needed for call to atoi
#include <cstdlib>
#include <locale> // std::locale, std::tolower
int spaceCommand (string inputCommand)
{
int i;
int spaceCount=0;
for(i=0;i<inputCommand.size();i++)
{
if(inputCommand[i]==' ')
{
spaceCount++;
}
}
return spaceCount;
}
void help()
{
cout<<"'insert name score' -> Insert this name and score in the grade table."<<endl;
cout<<"'change name newscore' -> Change the score for name"<<endl;
cout<<"'lookup name' -> Print out his or her score"<<endl;
cout<<"'remove name' -> Remove this student"<<endl;
cout<<"'print' -> Print all the entries"<<endl;
cout<<"'size' -> Prints out the number of entries"<<endl;
cout<<"'stats' -> Prints out statistics about the hash table at this point"<<endl;
cout<<"'help' -> Prints out a brief command summary"<<endl;
cout<<"'quit' -> Exits the program"<<endl;
}
int performCommands(Table* &mygrades,string command,string name,int score)
{//object pointer passed by reference
if(command=="insert")
{
mygrades->insert(name,score);
}
else if(command=="change")
{
mygrades->change(name,score);
}
else if(command=="lookup")
{
mygrades->lookup(name);
}
else if(command=="remove")
{
mygrades->remove(name);
}
else if(command=="print")
{
mygrades->printAll();
}
else if(command=="size")
{
cout<<mygrades->numEntries()<<endl;
}
else if(command=="stats")
{
mygrades->hashStats(cout);
}
else if(command=="help")
{
help();
}
else if(command=="quit")
{
return 1;
}
else
{
help();
}
return 0;
}
int stringToInt( const char * str )
{
int i = 0;
while( *str )
{
i = i*10 + (*str++ - '0');
}
return i;
}
int main(int argc, char * argv[]) {
string inputCommand;
string word1,word2;
int word3=0;
int spaceCount=0;
int firstSpace,secondSpace;
int exitOrNot;
// gets the hash table size from the command line
int hashSize = Table::HASH_SIZE;
Table * grades; // Table is dynamically allocated below, so we can call
// different constructors depending on input from the user.
if (argc > 1) {
hashSize = atoi(argv[1]); // atoi converts c-string to int
if (hashSize < 1) {
cout << "Command line argument (hashSize) must be a positive number"
<< endl;
return 1;
}
grades = new Table(hashSize);
}
else { // no command line args given -- use default table size
grades = new Table();
}
while(1)
{
getline(cin,inputCommand);
spaceCount=spaceCommand(inputCommand);
if(spaceCount==2)//3 word command
{ //word1
firstSpace=inputCommand.find(" ");
word1=inputCommand.substr(0,firstSpace);
//second word2
inputCommand=inputCommand.substr(firstSpace+1);
secondSpace=inputCommand.find(" ");
word2=inputCommand.substr(0,secondSpace);
//word3
inputCommand=inputCommand.substr(secondSpace+1);
char *charStr = new char[inputCommand.length() + 1];
strcpy(charStr, inputCommand.c_str());
// do stuff
word3 = stringToInt(charStr);
delete [] charStr;
////cout<<word3;
}
if(spaceCount==1)//2 word command
{ //word1
firstSpace=inputCommand.find(" ");
word1=inputCommand.substr(0,firstSpace);
//second word2
inputCommand=inputCommand.substr(firstSpace+1);
word2=inputCommand;
}
if(spaceCount==0)
{
word1=inputCommand;
}
//tolower
std::locale loc;
for (string::size_type i=0; i<word1.length(); ++i)
word1[i] = std::tolower(word1[i],loc);
for (string::size_type i=0; i<word2.length(); ++i)
word2[i] = std::tolower(word2[i],loc);
exitOrNot=performCommands(grades,word1,word2,word3);
if(exitOrNot==1)
{
break;
}
}
return 0;
}
| [
"surbhigo@usc.edu"
] | surbhigo@usc.edu |
67a59a9620eb8ef0b4e25f3b9ffd347dcd110215 | 49f88ff91aa582e1a9d5ae5a7014f5c07eab7503 | /gen/net/net_jni_headers/net/jni/X509Util_jni.h | e20565583b74720b0476f48d208a5815e79d43b7 | [] | no_license | AoEiuV020/kiwibrowser-arm64 | b6c719b5f35d65906ae08503ec32f6775c9bb048 | ae7383776e0978b945e85e54242b4e3f7b930284 | refs/heads/main | 2023-06-01T21:09:33.928929 | 2021-06-22T15:56:53 | 2021-06-22T15:56:53 | 379,186,747 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,606 | h | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is autogenerated by
// base/android/jni_generator/jni_generator.py
// For
// org/chromium/net/X509Util
#ifndef org_chromium_net_X509Util_JNI
#define org_chromium_net_X509Util_JNI
#include <jni.h>
#include "../../../../../../../base/android/jni_generator/jni_generator_helper.h"
// Step 1: Forward declarations.
JNI_REGISTRATION_EXPORT extern const char kClassPath_org_chromium_net_X509Util[];
const char kClassPath_org_chromium_net_X509Util[] = "org/chromium/net/X509Util";
// Leaking this jclass as we cannot use LazyInstance from some threads.
JNI_REGISTRATION_EXPORT base::subtle::AtomicWord g_org_chromium_net_X509Util_clazz = 0;
#ifndef org_chromium_net_X509Util_clazz_defined
#define org_chromium_net_X509Util_clazz_defined
inline jclass org_chromium_net_X509Util_clazz(JNIEnv* env) {
return base::android::LazyGetClass(env, kClassPath_org_chromium_net_X509Util,
&g_org_chromium_net_X509Util_clazz);
}
#endif
// Step 2: Constants (optional).
// Step 3: Method stubs.
namespace net {
static void JNI_X509Util_NotifyKeyChainChanged(JNIEnv* env, const
base::android::JavaParamRef<jclass>& jcaller);
JNI_GENERATOR_EXPORT void Java_org_chromium_net_X509Util_nativeNotifyKeyChainChanged(
JNIEnv* env,
jclass jcaller) {
return JNI_X509Util_NotifyKeyChainChanged(env, base::android::JavaParamRef<jclass>(env, jcaller));
}
} // namespace net
#endif // org_chromium_net_X509Util_JNI
| [
"aoeiuv020@gmail.com"
] | aoeiuv020@gmail.com |
d8ed28569bbc9fc759876880a0229199fd74ff7c | 1c895c003b270c53788d6422a2c71891d3f12d9c | /dacincubator/dacincubator.hpp | 87219ef8792da4d2ac87fdbb4a2ed15b2be2a57f | [] | no_license | eostry/kyubey-initial-bancor-offer-contract | 203a31a4a953d14322c52aeca3085de9c05086fe | 9be7f932f5496c200981c8b08fe9cb6ef7e19cfe | refs/heads/master | 2020-03-30T01:27:20.858673 | 2018-09-27T05:20:47 | 2018-09-27T05:20:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,820 | hpp | #include <eosiolib/currency.hpp>
#include <eosiolib/asset.hpp>
#include <math.h>
#include <string>
#include "kyubey.hpp"
#include "utils.hpp"
#define TOKEN_CONTRACT N(eosio.token)
using namespace eosio;
using namespace std;
typedef double real_type;
class dacincubator : public kyubey
{
public:
dacincubator(account_name self) :
kyubey(self),
global(_self, _self),
pendingtx(_self, _self) {
}
// @abi action
void init();
// @abi action
void clean();
// @abi action
void test();
// @abi action
void transfer(account_name from,
account_name to,
asset quantity,
string memo);
void onTransfer(account_name from,
account_name to,
asset quantity,
string memo);
// @abi table global i64
struct global {
uint64_t id = 0;
uint64_t defer_id = 0;
uint64_t primary_key() const { return id; }
EOSLIB_SERIALIZE(global, (id)(defer_id))
};
typedef eosio::multi_index<N(global), global> global_index;
global_index global;
// @abi table pendingtx i64
struct pendingtx {
uint64_t id = 0;
account_name from;
account_name to;
asset quantity;
string memo;
uint64_t primary_key() const { return id; }
void release() {
}
EOSLIB_SERIALIZE(pendingtx, (id)(from)(to)(quantity)(memo))
};
typedef eosio::multi_index<N(pendingtx), pendingtx> pendingtx_index;
pendingtx_index pendingtx;
// @abi table
struct rec {
account_name account;
asset quantity;
};
// @abi action
void receipt(const rec& recepit);
uint64_t get_next_defer_id() {
auto g = global.get(0);
global.modify(g, 0, [&](auto &g) {
g.defer_id += 1;
});
return g.defer_id;
}
template <typename... Args>
void send_defer_action(Args&&... args) {
transaction trx;
trx.actions.emplace_back(std::forward<Args>(args)...);
trx.send(get_next_defer_id(), _self, false);
}
};
extern "C"
{
void apply(uint64_t receiver, uint64_t code, uint64_t action)
{
auto self = receiver;
dacincubator thiscontract(self);
if ((code == N(eosio.token)) && (action == N(transfer))) {
execute_action(&thiscontract, &dacincubator::onTransfer);
return;
}
if (code != receiver) return;
switch (action) {EOSIO_API(dacincubator, (transfer)(init)(test))}
}
} | [
"lychees67@gmail.com"
] | lychees67@gmail.com |
1faa28603c5cf376387be0e6e091d187f20efa50 | 06d0a55bfdcdf17a1cc8a914fc19e8a535720cea | /Sorting/selection_sort.cpp | 9f4924fbc92832d400a165c308142a95c1b2ff31 | [] | no_license | luciandinu93/CPPAlgorithms | 8922492b1071e5861641ba54edd26cf495a63977 | 0e179e38a9c06a63c52062702a1d89d824a90f5e | refs/heads/master | 2020-04-23T11:42:04.986925 | 2020-04-02T05:47:24 | 2020-04-02T05:47:24 | 171,145,229 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 457 | cpp | #include <iostream>
using namespace std;
void selection_sort(int *A, int n) {
int temp, min = 0;
for(int i = 0; i < n-1; i++) {
min = i;
for(int j = i + 1; j < n; j++) {
if(A[min] > A[j])
min = j;
}
temp = A[i];
A[i] = A[min];
A[min] = temp;
}
}
int main() {
int n;
cin >> n;
int A[n];
for(int i = 0; i < n; i++) {
cin >> A[i];
}
selection_sort(A, n);
for(int i = 0; i < n; i++) {
cout << A[i] << " ";
}
cout << endl;
} | [
"lucian.dinu93@yahoo.com"
] | lucian.dinu93@yahoo.com |
0d5e5e65119fdbbaab6dbf7738e5a67e6627ff79 | f73b1c973666697607191ca08b165a485ac3c980 | /src/UIMode.cpp | 98d2d2749eb9ab727e829080afdf32c515c0675a | [
"BSD-2-Clause"
] | permissive | simonzty/RPi_Pico_WAV_Player | 1580f593ad4e1d132364530c8ce84e4e5b8b418a | 606d1cec8bfb7f5e55eab78f467c3541f0fff1fd | refs/heads/main | 2023-05-01T22:20:14.745081 | 2021-05-05T14:15:28 | 2021-05-05T14:15:28 | 378,089,434 | 1 | 0 | BSD-2-Clause | 2021-06-18T08:47:13 | 2021-06-18T08:47:13 | null | UTF-8 | C++ | false | false | 25,953 | cpp | /*------------------------------------------------------/
/ UIMode
/-------------------------------------------------------/
/ Copyright (c) 2020-2021, Elehobica
/ Released under the BSD-2-Clause
/ refer to https://opensource.org/licenses/BSD-2-Clause
/------------------------------------------------------*/
#include "UIMode.h"
#include <cstdio>
#include <cstring>
#include "ui_control.h"
#include "stack.h"
#include "PlayAudio/audio_codec.h"
TagRead tag;
const uint8_t *BLANK_LINE = ((uint8_t *) " ");
// UIMode class instances
button_action_t UIMode::btn_act;
//================================
// Implementation of UIMode class
//================================
UIMode::UIMode(const char *name, ui_mode_enm_t ui_mode_enm, UIVars *vars) : name(name), prevMode(NULL), ui_mode_enm(ui_mode_enm), vars(vars), idle_count(0)
{
}
void UIMode::entry(UIMode *prevMode)
{
this->prevMode = prevMode;
idle_count = 0;
if (ui_mode_enm == vars->init_dest_ui_mode) { // Reached desitination of initial UI mode
vars->init_dest_ui_mode = InitialMode;
}
ui_clear_btn_evt();
}
bool UIMode::isAudioFile(uint16_t idx)
{
if (file_menu_match_ext(idx, "wav", 3) || file_menu_match_ext(idx, "WAV", 3)) {
set_audio_codec(PlayAudio::AUDIO_CODEC_WAV);
return true;
}
set_audio_codec(PlayAudio::AUDIO_CODEC_NONE);
return false;
}
const char *UIMode::getName()
{
return name;
}
ui_mode_enm_t UIMode::getUIModeEnm()
{
return ui_mode_enm;
}
uint16_t UIMode::getIdleCount()
{
return idle_count;
}
//=======================================
// Implementation of UIInitialMode class
//=======================================
UIInitialMode::UIInitialMode(UIVars *vars) : UIMode("UIInitialMode", InitialMode, vars)
{
file_menu_open_dir("/");
if (file_menu_get_num() <= 1) {
//power_off("Card Read Error!", 1);
lcd.setMsg("Card Read Error!");
}
}
UIMode* UIInitialMode::update()
{
switch (vars->init_dest_ui_mode) {
case FileViewMode:
/*
case PlayMode:
return getUIMode(FileViewMode);
break;
*/
default:
if (idle_count++ > 100) {
return getUIMode(FileViewMode);
}
break;
}
idle_count++;
return this;
}
void UIInitialMode::entry(UIMode *prevMode)
{
UIMode::entry(prevMode);
lcd.switchToInitial();
}
void UIInitialMode::draw()
{
lcd.drawInitial();
}
//=========================================
// Implementation of UIFileViewMode class
//=========================================
UIFileViewMode::UIFileViewMode(UIVars *vars, stack_t *dir_stack) : UIMode("UIFileViewMode", FileViewMode, vars), dir_stack(dir_stack)
{
sft_val = new uint16_t[vars->num_list_lines];
for (int i = 0; i < vars->num_list_lines; i++) {
sft_val[i] = 0;
}
}
void UIFileViewMode::listIdxItems()
{
char str[256];
for (int i = 0; i < vars->num_list_lines; i++) {
if (vars->idx_head+i >= file_menu_get_num()) {
lcd.setListItem(i, ""); // delete
continue;
}
file_menu_get_fname(vars->idx_head+i, str, sizeof(str));
uint8_t icon = file_menu_is_dir(vars->idx_head+i) ? ICON16x16_FOLDER : ICON16x16_FILE;
lcd.setListItem(i, str, icon, (i == vars->idx_column));
}
}
uint16_t UIFileViewMode::getNumAudioFiles()
{
uint16_t num_tracks = 0;
num_tracks += file_menu_get_ext_num("wav", 3) + file_menu_get_ext_num("WAV", 3);
return num_tracks;
}
void UIFileViewMode::chdir()
{
stack_data_t item;
if (vars->idx_head+vars->idx_column == 0) { // upper ("..") dirctory
if (stack_get_count(dir_stack) > 0) {
if (vars->fs_type == FS_EXFAT) { // This is workaround for FatFs known bug for ".." in EXFAT
stack_t *temp_stack = stack_init();
while (stack_get_count(dir_stack) > 0) {
stack_pop(dir_stack, &item);
//printf("pop %d %d %d\n", stack_get_count(dir_stack), item.head, item.column);
stack_push(temp_stack, &item);
}
file_menu_close_dir();
file_menu_open_dir("/"); // Root directory
while (stack_get_count(temp_stack) > 1) {
stack_pop(temp_stack, &item);
//printf("pushA %d %d %d\n", stack_get_count(dir_stack), item.head, item.column);
file_menu_sort_entry(item.head+item.column, item.head+item.column+1);
file_menu_ch_dir(item.head+item.column);
stack_push(dir_stack, &item);
}
stack_pop(temp_stack, &item);
//printf("pushB %d %d %d\n", stack_get_count(dir_stack), item.head, item.column);
stack_push(dir_stack, &item);
stack_delete(temp_stack);
} else {
file_menu_ch_dir(vars->idx_head+vars->idx_column);
}
} else { // Already in top directory
file_menu_close_dir();
file_menu_open_dir("/"); // Root directory
item.head = 0;
item.column = 0;
stack_push(dir_stack, &item);
}
stack_pop(dir_stack, &item);
vars->idx_head = item.head;
vars->idx_column = item.column;
} else { // normal directory
item.head = vars->idx_head;
item.column = vars->idx_column;
stack_push(dir_stack, &item);
file_menu_ch_dir(vars->idx_head+vars->idx_column);
vars->idx_head = 0;
vars->idx_column = 0;
}
}
#if 0
UIMode *UIFileViewMode::nextPlay()
{
switch (USERCFG_PLAY_NEXT_ALBUM) {
case UserConfig::next_play_action_t::Sequential:
return sequentialSearch(false);
break;
case UserConfig::next_play_action_t::SequentialRepeat:
return sequentialSearch(true);
break;
case UserConfig::next_play_action_t::Repeat:
vars->idx_head = 0;
vars->idx_column = 0;
return getUIPlayMode();
case UserConfig::next_play_action_t::Random:
return randomSearch(USERCFG_PLAY_RAND_DEPTH);
break;
case UserConfig::next_play_action_t::Stop:
default:
return this;
break;
}
return this;
}
UIMode *UIFileViewMode::sequentialSearch(bool repeatFlg)
{
int stack_count;
uint16_t last_dir_idx;
printf("Sequential Search\n");
vars->idx_play = 0;
stack_count = stack_get_count(dir_stack);
if (stack_count < 1) { return this; }
{
vars->idx_head = 0;
vars->idx_column = 0;
chdir(); // cd ..;
}
vars->idx_head += vars->idx_column;
vars->idx_column = 0;
last_dir_idx = vars->idx_head;
while (1) {
{
if (file_menu_get_dir_num() == 0) { break; }
while (1) {
vars->idx_head++;
if (repeatFlg) {
// [Option 1] loop back to first album (don't take ".." directory)
if (vars->idx_head >= file_menu_get_num()) { vars->idx_head = 1; }
} else {
// [Option 2] stop at the bottom of albums
if (vars->idx_head >= file_menu_get_num()) {
// go back to last dir
vars->idx_head = last_dir_idx;
chdir();
return this;
}
}
file_menu_sort_entry(vars->idx_head, vars->idx_head+1);
if (file_menu_is_dir(vars->idx_head) > 0) { break; }
}
chdir();
}
// Check if Next Target Dir has Audio track files
if (stack_count == stack_get_count(dir_stack) && getNumAudioFiles() > 0) { break; }
// Otherwise, chdir to stack_count-depth and retry again
printf("Retry Sequential Search\n");
while (stack_count - 1 != stack_get_count(dir_stack)) {
vars->idx_head = 0;
vars->idx_column = 0;
chdir(); // cd ..;
}
}
return getUIPlayMode();
}
UIMode *UIFileViewMode::randomSearch(uint16_t depth)
{
int i;
int stack_count;
printf("Random Search\n");
vars->idx_play = 0;
stack_count = stack_get_count(dir_stack);
if (stack_count < depth) { return this; }
for (i = 0; i < depth; i++) {
vars->idx_head = 0;
vars->idx_column = 0;
chdir(); // cd ..;
}
while (1) {
for (i = 0; i < depth; i++) {
if (file_menu_get_dir_num() == 0) { break; }
while (1) {
vars->idx_head = random(1, file_menu_get_num());
file_menu_sort_entry(vars->idx_head, vars->idx_head+1);
if (file_menu_is_dir(vars->idx_head) > 0) { break; }
}
vars->idx_column = 0;
chdir();
}
// Check if Next Target Dir has Audio track files
if (stack_count == stack_get_count(dir_stack) && getNumAudioFiles() > 0) { break; }
// Otherwise, chdir to stack_count-depth and retry again
printf("Retry Random Search\n");
while (stack_count - depth != stack_get_count(dir_stack)) {
vars->idx_head = 0;
vars->idx_column = 0;
chdir(); // cd ..;
}
}
return getUIPlayMode();
}
#endif
void UIFileViewMode::idxInc(void)
{
if (vars->idx_head >= file_menu_get_num() - vars->num_list_lines && vars->idx_column == vars->num_list_lines-1) { return; }
if (vars->idx_head + vars->idx_column + 1 >= file_menu_get_num()) { return; }
vars->idx_column++;
if (vars->idx_column >= vars->num_list_lines) {
if (vars->idx_head + vars->num_list_lines >= file_menu_get_num() - vars->num_list_lines) {
vars->idx_column = vars->num_list_lines-1;
vars->idx_head++;
} else {
vars->idx_column = 0;
vars->idx_head += vars->num_list_lines;
}
}
}
void UIFileViewMode::idxDec(void)
{
if (vars->idx_head == 0 && vars->idx_column == 0) { return; }
if (vars->idx_column == 0) {
if (vars->idx_head < vars->num_list_lines) {
vars->idx_column = 0;
vars->idx_head--;
} else {
vars->idx_column = vars->num_list_lines-1;
vars->idx_head -= vars->num_list_lines;
}
} else {
vars->idx_column--;
}
}
void UIFileViewMode::idxFastInc(void)
{
if (vars->idx_head >= file_menu_get_num() - vars->num_list_lines && vars->idx_column == vars->num_list_lines-1) { return; }
if (vars->idx_head + vars->idx_column + 1 >= file_menu_get_num()) { return; }
if (file_menu_get_num() < vars->num_list_lines) {
idxInc();
} else if (vars->idx_head + vars->num_list_lines >= file_menu_get_num() - vars->num_list_lines) {
vars->idx_head = file_menu_get_num() - vars->num_list_lines;
idxInc();
} else {
vars->idx_head += vars->num_list_lines;
}
}
void UIFileViewMode::idxFastDec(void)
{
if (vars->idx_head == 0 && vars->idx_column == 0) { return; }
if (vars->idx_head < vars->num_list_lines) {
vars->idx_head = 0;
idxDec();
} else {
vars->idx_head -= vars->num_list_lines;
}
}
UIMode *UIFileViewMode::getUIPlayMode()
{
if (vars->idx_play == 0) {
vars->idx_play = vars->idx_head + vars->idx_column;
}
//file_menu_full_sort();
vars->num_tracks = getNumAudioFiles();
return getUIMode(PlayMode);
}
UIMode* UIFileViewMode::update()
{
vars->resume_ui_mode = ui_mode_enm;
/*
switch (vars->init_dest_ui_mode) {
case PlayMode:
return getUIPlayMode();
break;
default:
break;
}
*/
if (ui_get_btn_evt(&btn_act)) {
vars->do_next_play = None;
switch (btn_act) {
case ButtonCenterSingle:
if (file_menu_is_dir(vars->idx_head+vars->idx_column) > 0) { // Target is Directory
chdir();
listIdxItems();
} else { // Target is File
if (isAudioFile(vars->idx_head + vars->idx_column)) {
return getUIPlayMode();
}
}
break;
case ButtonCenterDouble:
// upper ("..") dirctory
vars->idx_head = 0;
vars->idx_column = 0;
chdir();
listIdxItems();
break;
case ButtonCenterTriple:
//return randomSearch(USERCFG_PLAY_RAND_DEPTH);
break;
case ButtonCenterLong:
//return getUIMode(ConfigMode);
break;
case ButtonCenterLongLong:
break;
case ButtonPlusSingle:
idxDec();
listIdxItems();
break;
case ButtonPlusLong:
idxFastDec();
listIdxItems();
break;
case ButtonMinusSingle:
idxInc();
listIdxItems();
break;
case ButtonMinusLong:
idxFastInc();
listIdxItems();
break;
default:
break;
}
idle_count = 0;
}
/*
switch (vars->do_next_play) {
case ImmediatePlay:
vars->do_next_play = None;
return randomSearch(USERCFG_PLAY_RAND_DEPTH);
break;
case TimeoutPlay:
if (idle_count > USERCFG_PLAY_TM_NXT_PLY*OneSec) {
vars->do_next_play = None;
return nextPlay();
}
break;
default:
break;
}
*/
/*
if (idle_count > USERCFG_GEN_TM_PWROFF*OneSec) {
return getUIMode(PowerOffMode);
} else if (idle_count > 5*OneSec) {
file_menu_idle(); // for background sort
}
lcd.setBatteryVoltage(vars->bat_mv);
*/
idle_count++;
return this;
}
void UIFileViewMode::entry(UIMode *prevMode)
{
UIMode::entry(prevMode);
listIdxItems();
lcd.switchToListView();
}
void UIFileViewMode::draw()
{
lcd.drawListView();
ui_clear_btn_evt();
}
//====================================
// Implementation of UIPlayMode class
//====================================
UIPlayMode::UIPlayMode(UIVars *vars) : UIMode("UIPlayMode", PlayMode, vars)
{
}
UIMode* UIPlayMode::update()
{
vars->resume_ui_mode = ui_mode_enm;
PlayAudio *codec = get_audio_codec();
if (ui_get_btn_evt(&btn_act)) {
switch (btn_act) {
case ButtonCenterSingle:
codec->pause(!codec->isPaused());
break;
case ButtonCenterDouble:
vars->idx_play = 0;
codec->stop();
vars->do_next_play = None;
return getUIMode(FileViewMode);
break;
case ButtonCenterTriple:
vars->do_next_play = ImmediatePlay;
return getUIMode(FileViewMode);
break;
case ButtonCenterLong:
//return getUIMode(ConfigMode);
break;
case ButtonCenterLongLong:
break;
case ButtonPlusSingle:
case ButtonPlusLong:
PlayAudio::volumeUp();
break;
case ButtonMinusSingle:
case ButtonMinusLong:
PlayAudio::volumeDown();
break;
default:
break;
}
idle_count = 0;
}
/*if (codec->isPaused() && idle_count > USERCFG_GEN_TM_PWROFF*OneSec) {
return getUIMode(PowerOffMode);
} else */if (!codec->isPlaying()) {
idle_count = 0;
while (++vars->idx_play < file_menu_get_num()) {
if (isAudioFile(vars->idx_play)) {
play();
return this;
}
}
vars->idx_play = 0;
codec->stop();
vars->do_next_play = TimeoutPlay;
return getUIMode(FileViewMode);
}
lcd.setVolume(PlayAudio::getVolume());
//lcd.setBitRate(codec->bitRate());
lcd.setPlayTime(codec->elapsedMillis()/1000, codec->totalMillis()/1000, codec->isPaused());
float levelL, levelR;
codec->getLevel(&levelL, &levelR);
lcd.setAudioLevel(levelL, levelR);
//lcd.setBatteryVoltage(vars->bat_mv);
idle_count++;
return this;
}
#if 0
audio_codec_enm_t UIPlayMode::getAudioCodec(MutexFsBaseFile *f)
{
audio_codec_enm_t audio_codec_enm = CodecNone;
bool flg = false;
int ofs = 0;
char str[256];
while (vars->idx_play + ofs < file_menu_get_num()) {
file_menu_get_obj(vars->idx_play + ofs, f);
f->getName(str, sizeof(str));
char* ext_pos = strrchr(str, '.');
if (ext_pos) {
if (strncmp(ext_pos, ".mp3", 4) == 0 || strncmp(ext_pos, ".MP3", 4) == 0) {
audio_codec_enm = CodecMp3;
flg = true;
break;
} else if (strncmp(ext_pos, ".wav", 4) == 0 || strncmp(ext_pos, ".WAV", 4) == 0) {
audio_codec_enm = CodecWav;
flg = true;
break;
} else if (strncmp(ext_pos, ".m4a", 4) == 0 || strncmp(ext_pos, ".M4A", 4) == 0) {
audio_codec_enm = CodecAac;
flg = true;
break;
} else if (strncmp(ext_pos, ".flac", 5) == 0 || strncmp(ext_pos, ".FLAC", 5) == 0) {
audio_codec_enm = CodecFlac;
flg = true;
break;
}
}
ofs++;
}
if (flg) {
file_menu_get_fname_UTF16(vars->idx_play + ofs, (char16_t *) str, sizeof(str)/2);
Serial.println(utf16_to_utf8((const char16_t *) str).c_str());
vars->idx_play += ofs;
} else {
vars->idx_play = 0;
}
return audio_codec_enm;
}
#endif
void UIPlayMode::readTag()
{
char str[256];
mime_t mime;
ptype_t ptype;
uint64_t img_pos;
size_t size;
bool is_unsync;
int img_cnt = 0;
// Read TAG
file_menu_get_fname(vars->idx_play, str, sizeof(str));
tag.loadFile(str);
// copy TAG text
if (tag.getUTF8Track(str, sizeof(str))) {
uint16_t track = atoi(str);
sprintf(str, "%d/%d", track, vars->num_tracks);
} else {
sprintf(str, "%d/%d", vars->idx_play, vars->num_tracks);
}
lcd.setTrack(str);
if (tag.getUTF8Title(str, sizeof(str))) {
lcd.setTitle(str);
} else { // display filename if no TAG
file_menu_get_fname(vars->idx_play, str, sizeof(str));
lcd.setTitle(str);
/*
file_menu_get_fname_UTF16(vars->idx_play, (char16_t *) str, sizeof(str)/2);
lcd.setTitle(utf16_to_utf8((const char16_t *) str).c_str(), utf8);
*/
}
if (tag.getUTF8Album(str, sizeof(str))) lcd.setAlbum(str); else lcd.setAlbum("");
if (tag.getUTF8Artist(str, sizeof(str))) lcd.setArtist(str); else lcd.setArtist("");
//if (tag.getUTF8Year(str, sizeof(str))) lcd.setYear(str); else lcd.setYear("");
uint16_t idx = 0;
while (idx < file_menu_get_num()) {
if (file_menu_match_ext(idx, "jpg", 3) || file_menu_match_ext(idx, "JPG", 3) ||
file_menu_match_ext(idx, "jpeg", 4) || file_menu_match_ext(idx, "JPEG", 4)) {
file_menu_get_fname(idx, str, sizeof(str));
lcd.setImageJpeg(str);
break;
}
idx++;
}
return;
// copy TAG image
//lcd.deleteAlbumArt();
for (int i = 0; i < tag.getPictureCount(); i++) {
if (tag.getPicturePos(i, &mime, &ptype, &img_pos, &size, &is_unsync)) {
if (mime == jpeg) { /*lcd.addAlbumArtJpeg(vars->idx_play, img_pos, size, is_unsync); */img_cnt++; }
else if (mime == png) { /*lcd.addAlbumArtPng(vars->idx_play, img_pos, size, is_unsync); */img_cnt++; }
}
}
// if no AlbumArt in TAG, use JPEG or PNG in current folder
if (img_cnt == 0) {
uint16_t idx = 0;
while (idx < file_menu_get_num()) {
if (file_menu_match_ext(idx, "jpg", 3) || file_menu_match_ext(idx, "JPG", 3) ||
file_menu_match_ext(idx, "jpeg", 4) || file_menu_match_ext(idx, "JPEG", 4)) {
file_menu_get_fname(idx, str, sizeof(str));
printf("JPEG %s\n", str);
//lcd.addAlbumArtJpeg(idx, 0, f.fileSize());
img_cnt++;
} else if (file_menu_match_ext(idx, "png", 3) || file_menu_match_ext(idx, "PNG", 3)) {
//ilcd.addAlbumArtPng(idx, 0, f.fileSize());
img_cnt++;
}
idx++;
}
}
}
void UIPlayMode::play()
{
char str[FF_MAX_LFN];
file_menu_get_fname(vars->idx_play, str, sizeof(str));
printf("%s\n", str);
PlayAudio *playAudio = get_audio_codec();
readTag();
playAudio->play(str);
}
void UIPlayMode::entry(UIMode *prevMode)
{
UIMode::entry(prevMode);
//if (prevMode->getUIModeEnm() != ConfigMode) {
play();
//}
lcd.switchToPlay();
}
void UIPlayMode::draw()
{
lcd.drawPlay();
ui_clear_btn_evt();
}
#if 0
//=======================================
// Implementation of UIConfigMode class
//=======================================
UIConfigMode::UIConfigMode(UIVars *vars) : UIMode("UIConfigMode", ConfigMode, vars),
path_stack(NULL), idx_head(0), idx_column(0)
{
path_stack = stack_init();
}
uint16_t UIConfigMode::getNum()
{
return (uint16_t) userConfig.getNum() + 1;
}
const char *UIConfigMode::getStr(uint16_t idx)
{
if (idx == 0) { return "[Back]"; }
return userConfig.getStr((int) idx-1);
}
const uint8_t *UIConfigMode::getIcon(uint16_t idx)
{
const uint8_t *icon = NULL;
if (idx == 0) {
icon = ICON16x16_LEFTARROW;
} else if (!userConfig.isSelection()) {
icon = ICON16x16_GEAR;
} else if (userConfig.selIdxMatched(idx-1)) {
icon = ICON16x16_CHECKED;
}
return icon;
}
void UIConfigMode::listIdxItems()
{
for (int i = 0; i < vars->num_list_lines; i++) {
if (idx_head+i >= getNum()) {
lcd.setListItem(i, ""); // delete
continue;
}
lcd.setListItem(i, getStr(idx_head+i), getIcon(idx_head+i), (i == idx_column));
}
}
void UIConfigMode::idxInc(void)
{
if (idx_head >= getNum() - vars->num_list_lines && idx_column == vars->num_list_lines-1) { return; }
if (idx_head + idx_column + 1 >= getNum()) { return; }
idx_column++;
if (idx_column >= vars->num_list_lines) {
if (idx_head + vars->num_list_lines >= getNum() - vars->num_list_lines) {
idx_column = vars->num_list_lines-1;
idx_head++;
} else {
idx_column = 0;
idx_head += vars->num_list_lines;
}
}
}
void UIConfigMode::idxDec(void)
{
if (idx_head == 0 && idx_column == 0) { return; }
if (idx_column == 0) {
if (idx_head < vars->num_list_lines) {
idx_column = 0;
idx_head--;
} else {
idx_column = vars->num_list_lines-1;
idx_head -= vars->num_list_lines;
}
} else {
idx_column--;
}
}
int UIConfigMode::select()
{
stack_data_t stack_data;
if (idx_head + idx_column == 0) {
if (userConfig.leave()) {
stack_pop(path_stack, &stack_data);
idx_head = stack_data.head;
idx_column = stack_data.column;
} else {
return 0; // exit from Config
}
} else {
if (userConfig.enter(idx_head + idx_column - 1)) {
stack_data.head = idx_head;
stack_data.column = idx_column;
stack_push(path_stack, &stack_data);
idx_head = 0;
idx_column = 0;
}
}
return 1;
}
UIMode* UIConfigMode::update()
{
if (ui_get_btn_evt(&btn_act)) {
vars->do_next_play = None;
switch (btn_act) {
case ButtonCenterSingle:
if (select()) {
listIdxItems();
} else {
return prevMode;
}
break;
case ButtonCenterDouble:
return prevMode;
break;
case ButtonCenterTriple:
break;
case ButtonCenterLong:
break;
case ButtonCenterLongLong:
return getUIMode(PowerOffMode);
break;
case ButtonPlusSingle:
case ButtonPlusLong:
idxDec();
listIdxItems();
break;
case ButtonMinusSingle:
case ButtonMinusLong:
idxInc();
listIdxItems();
break;
default:
break;
}
idle_count = 0;
}
if (idle_count > USERCFG_GEN_TM_CONFIG*OneSec) {
return prevMode;
}
idle_count++;
return this;
}
void UIConfigMode::entry(UIMode *prevMode)
{
UIMode::entry(prevMode);
listIdxItems();
lcd.switchToListView();
}
void UIConfigMode::draw()
{
lcd.drawListView();
ui_clear_btn_evt();
}
//=======================================
// Implementation of UIPowerOffMode class
//=======================================
UIPowerOffMode::UIPowerOffMode(UIVars *vars) : UIMode("UIPowerOffMode", PowerOffMode, vars)
{
}
UIMode* UIPowerOffMode::update()
{
return this;
}
void UIPowerOffMode::entry(UIMode *prevMode)
{
UIMode::entry(prevMode);
lcd.switchToPowerOff(vars->power_off_msg);
lcd.drawPowerOff();
ui_terminate(vars->resume_ui_mode);
}
void UIPowerOffMode::draw()
{
}
#endif | [
"elehobica@gmail.com"
] | elehobica@gmail.com |
cd56f02d67dce7a596cfaf5dee7b6119a9f33f41 | 097b2a0f8e5cefbaff31790a359d267bd978e480 | /Atcoder/ABC_s1/ABC_079/C-Train_Ticket.cpp | f37899ce059057bc72afda3204eeb6cfb96a33a9 | [] | no_license | Noiri/Competitive_Programming | 39667ae94d6b167b4d7b9e78a98b8cb53ff1884f | 25ec787f7f5a507f9d1713a1e88f198fd495ec01 | refs/heads/master | 2023-08-16T17:35:15.940860 | 2021-09-07T20:57:59 | 2021-09-07T20:57:59 | 161,947,108 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 669 | cpp | #include <bits/stdc++.h>
using namespace std;
int main(){
string s;
cin >> s;
for(int bit=0; bit<(1<<3); bit++){
int tmp = (int)(s[0] - '0');
char op[3];
for(int i=0; i<3; i++){
if(bit & (1<<i)){
tmp += (int)(s[i+1] - '0');
op[i] = '+';
}
else{
tmp -= (int)(s[i+1] - '0');
op[i] = '-';
}
}
if(tmp == 7){
cout << s[0];
for(int i=0; i<3; i++) cout << op[i] << s[i+1];
cout << "=7" << endl;
return 0;
}
}
return 0;
} | [
"suleipenn@gmail.com"
] | suleipenn@gmail.com |
018f5c74a9f51895d68557b5026600d9b25eecee | 160506cbb73a6328fdd5d60c02bf0e305b966b08 | /gstar/Master/dealCsv.cpp | 1e0561afa164b95b5fb3b1b0b03dfc30a0e0e9e4 | [] | no_license | paradiser/Gstar | 7938b0492f7d42e70408157b25a2dcb56c4782d5 | 7d341c343191a615984439b6303bfe73ecfbe4df | refs/heads/master | 2021-01-18T22:24:07.458062 | 2016-11-08T02:45:17 | 2016-11-08T02:45:17 | 72,499,182 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,725 | cpp | //
// Created by wbl on 16-7-29.
//
#include "dealCsv.h"
//const string csvfp = "/home/wbl/Desktop/1.csv";
vector<string> split(string rawString, char spliter)
{
vector<string> result;
string tmp="";
for(int i=0;i<rawString.length();i++)
{
if(rawString[i]==spliter){
result.push_back(tmp);
tmp="";
}
else
tmp += rawString[i];
}
result.push_back(tmp);
return result;
}
string join(vector<string> vec, char joiner)
{
string result="";
for(auto str:vec)
result+=str+joiner;
return result.substr(0,result.length()-1);
}
vector<vector<string>> readCsv(string filePath)
// read a csv file,
// return vector<vector<string>> contains strings if the file if success;
// return vector<vector\+0<string>> contains nothing if failed.
{
std::vector<vector<string>> context;
string line, field;
ifstream in(filePath);
if(in.is_open())
{
while(getline(in, line))
{
std::vector<string> rowContext=split(line, ',');
context.push_back(rowContext);
}
in.close();
}
else
cout<<"open csv error."<<endl;
return context;
}
bool writeCsv(string filePath, vector<vector<string>> content)
// save a vector<vector<string>> variable to the filePath(param);
// return success?true:false;
{
vector<vector<string>> old_content = readCsv(filePath);
if(content==old_content) return true;
ofstream out(filePath);
if(out.is_open())
{
int i;
for(i = 0; i < content.size(); i++) {
out << join(content[i], ',')<<'\n';
out.flush();
}
out.close();
return true;
}
cerr<<"failed to write to "<<filePath<<endl;
return false;
}
string getCsvValue(string filePath, int row, int col)
// if row and col are valid index
// return the string of the coordinate in the csv.
{
vector<vector<string>> context = readCsv(filePath);
if(row<context.size()&&col<context[row].size()) {
string result = context[row][col];
return result;
}
else{
cout<<"get value from "<<filePath<<" failed.";
return "";
}
}
bool setCsvValue(string filePath, int row, int col, string setValue)
// if row and col are valid index,
// set the string at the coordinate to the setValue.
{
vector<vector<string>> context = readCsv(filePath);
if(row<context.size()&&col<context[row].size()) {
context[row][col] = setValue;
return writeCsv(filePath, context);
}
else {
cout<<"failed to set value of "<<filePath<<"."<<endl;
cout<<"out of index"<<endl;
return false;
}
}
bool appendInfoToCsv(string filePath, string info)
//add a row(means a record) to the end of the file.
{
vector<vector<string>> old_content = readCsv(filePath);
vector<string> a_server;
a_server = split(info, ',');
old_content.push_back(a_server);
return writeCsv(filePath, old_content);
}
bool deleteInfoFromCsv(string filePath, string keyword)
//delete one row of the file by the kye word "keyword."
{
vector<vector<string>> old_content, content;
//old-content means the content of the file,
// delete one record and save the others in content.
old_content = readCsv(filePath);
for(auto serv:old_content)
if(serv[0] != keyword) content.push_back(serv);
return writeCsv(filePath, content);
}
int getIntValue(string filePath, string keyword, int location)
{
std::stringstream ss;
ss << getStringValue(filePath, keyword, location);
int result;
ss >> result; //string -> int
return result;
}
string getStringValue(string filePath, string keyword, int location)
{
vector<vector<string>> context = readCsv(filePath);
for(int i = 0; i < context.size(); i ++) {
if(getCsvValue(filePath, i, 0) == keyword) {
return getCsvValue(filePath, i, location);
}
}
return "false";
}
bool isRecordExisting(string filePath, string keyword)
{
vector<vector<string>> context = readCsv(filePath);
for(int i = 0; i < context.size(); i ++) {
if(context[i][0] == keyword) {
return true;
}
}
return false;
}
//bool initCsv(string filePath)
//{
// ofstream out(filePath);
// if(out.is_open())
// {
// out.close();
// return true;
// }
// else
// return false;
//}
/*int main()
{
bool status = deleteInfoFromCsv(csvfp, "a1");
if(status)
{
vector<vector<string>> context = readCsv(csvfp);
for(auto row:context)
for(auto field:row)
cout<<field<<endl;
}
return 0;
}
*/
| [
"paradiser@ubuntu.ubuntu-domain"
] | paradiser@ubuntu.ubuntu-domain |
304aa5a343f45e40c0f53bbcf4608bbd07a02737 | c64e539f641211a7593c8552c9e38ff443982a2d | /src/qt/sendcoinsentry.cpp | 6abf74a183ca3fd9b06ffbfc9c9fb8633a6fe866 | [
"MIT"
] | permissive | cryptolog/ARGUS | 1c38334bcf61017073e4b512936e7372f7a87a5b | fc17a26535069ee0cc12d7af5053fc5c5fc5a91d | refs/heads/master | 2020-06-02T23:19:24.322324 | 2019-06-21T08:58:18 | 2019-06-21T08:58:18 | 191,341,107 | 0 | 0 | MIT | 2019-06-11T09:42:04 | 2019-06-11T09:42:03 | null | UTF-8 | C++ | false | false | 4,617 | cpp | // Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "sendcoinsentry.h"
#include "ui_sendcoinsentry.h"
#include "guiutil.h"
#include "bitcoinunits.h"
#include "addressbookpage.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include <QApplication>
#include <QClipboard>
SendCoinsEntry::SendCoinsEntry(QWidget *parent) :
QFrame(parent),
ui(new Ui::SendCoinsEntry),
model(0)
{
ui->setupUi(this);
#ifdef Q_OS_MAC
ui->payToLayout->setSpacing(4);
#endif
#if QT_VERSION >= 0x040700
/* Do not move this to the XML file, Qt before 4.7 will choke on it */
ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book"));
ui->payTo->setPlaceholderText(tr("Enter a ARGUSCOIN address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)"));
#endif
setFocusPolicy(Qt::TabFocus);
setFocusProxy(ui->payTo);
GUIUtil::setupAddressWidget(ui->payTo, this);
}
SendCoinsEntry::~SendCoinsEntry()
{
delete ui;
}
void SendCoinsEntry::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->payTo->setText(QApplication::clipboard()->text());
}
void SendCoinsEntry::on_addressBookButton_clicked()
{
if(!model)
return;
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if(dlg.exec())
{
ui->payTo->setText(dlg.getReturnValue());
ui->payAmount->setFocus();
}
}
void SendCoinsEntry::on_payTo_textChanged(const QString &address)
{
if(!model)
return;
// Fill in label from address book, if address has an associated label
QString associatedLabel = model->getAddressTableModel()->labelForAddress(address);
if(!associatedLabel.isEmpty())
ui->addAsLabel->setText(associatedLabel);
}
void SendCoinsEntry::setModel(WalletModel *model)
{
this->model = model;
if(model && model->getOptionsModel())
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
connect(ui->payAmount, SIGNAL(textChanged()), this, SIGNAL(payAmountChanged()));
clear();
}
void SendCoinsEntry::setRemoveEnabled(bool enabled)
{
ui->deleteButton->setEnabled(enabled);
}
void SendCoinsEntry::clear()
{
ui->payTo->clear();
ui->addAsLabel->clear();
ui->payAmount->clear();
ui->payTo->setFocus();
// update the display unit, to not use the default ("BTC")
updateDisplayUnit();
}
void SendCoinsEntry::on_deleteButton_clicked()
{
emit removeEntry(this);
}
bool SendCoinsEntry::validate()
{
// Check input validity
bool retval = true;
if(!ui->payAmount->validate())
{
retval = false;
}
else
{
if(ui->payAmount->value() <= 0)
{
// Cannot send 0 coins or less
ui->payAmount->setValid(false);
retval = false;
}
}
if(!ui->payTo->hasAcceptableInput() ||
(model && !model->validateAddress(ui->payTo->text())))
{
ui->payTo->setValid(false);
retval = false;
}
return retval;
}
SendCoinsRecipient SendCoinsEntry::getValue()
{
SendCoinsRecipient rv;
rv.address = ui->payTo->text();
rv.label = ui->addAsLabel->text();
rv.amount = ui->payAmount->value();
return rv;
}
QWidget *SendCoinsEntry::setupTabChain(QWidget *prev)
{
QWidget::setTabOrder(prev, ui->payTo);
QWidget::setTabOrder(ui->payTo, ui->addressBookButton);
QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton);
QWidget::setTabOrder(ui->pasteButton, ui->deleteButton);
QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel);
return ui->payAmount->setupTabChain(ui->addAsLabel);
}
void SendCoinsEntry::setValue(const SendCoinsRecipient &value)
{
ui->payTo->setText(value.address);
ui->addAsLabel->setText(value.label);
ui->payAmount->setValue(value.amount);
}
void SendCoinsEntry::setAddress(const QString &address)
{
ui->payTo->setText(address);
ui->payAmount->setFocus();
}
bool SendCoinsEntry::isClear()
{
return ui->payTo->text().isEmpty();
}
void SendCoinsEntry::setFocus()
{
ui->payTo->setFocus();
}
void SendCoinsEntry::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
// Update payAmount with the current unit
ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
| [
"bitminer82@gmail.com"
] | bitminer82@gmail.com |
0c91f12f68904989d5447ebe505c896076a2c082 | a6376e1ada58384cdc0065ce5a4a96728e84f04f | /SDK/include/voreen/core/interaction/trackballnavigation.h | 2b68cbcc7ee099e2aa6deb3de12cf17923834586 | [] | no_license | widVE/Voreen | be02bac44896e869a6af083c61729d5e154c28f1 | c8a5c66f15d31f8177eeceefa19358f905870441 | refs/heads/master | 2021-08-17T23:46:19.556383 | 2020-06-22T20:21:11 | 2020-06-22T20:21:11 | 196,454,037 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 14,110 | h | /***********************************************************************************
* *
* Voreen - The Volume Rendering Engine *
* *
* Copyright (C) 2005-2013 University of Muenster, Germany. *
* Visualization and Computer Graphics Group <http://viscg.uni-muenster.de> *
* For a list of authors please refer to the file "CREDITS.txt". *
* *
* This file is part of the Voreen software package. Voreen is free software: *
* you can redistribute it and/or modify it under the terms of the GNU General *
* Public License version 2 as published by the Free Software Foundation. *
* *
* Voreen 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 in the file *
* "LICENSE.txt" along with this file. If not, see <http://www.gnu.org/licenses/>. *
* *
* For non-commercial academic use see the license exception specified in the file *
* "LICENSE-academic.txt". To get information about commercial licensing please *
* contact the authors. *
* *
***********************************************************************************/
#ifndef VRN_TRACKBALL_NAVIGATION_H
#define VRN_TRACKBALL_NAVIGATION_H
#include "tgt/event/eventlistener.h"
#include "tgt/vector.h"
#include "tgt/event/mouseevent.h"
#include "tgt/event/touchevent.h"
#include "tgt/event/touchpoint.h"
#include "tgt/glcanvas.h"
#include "voreen/core/interaction/voreentrackball.h"
#include "voreen/core/utils/voreenpainter.h"
namespace tgt {
class Camera;
}
namespace voreen {
class CameraProperty;
/**
* A class that makes it possible to use a trackball-metaphor to rotate, zoom, shift, roll a dataset.
*/
class VRN_CORE_API TrackballNavigation : public tgt::EventListener {
public:
enum Mode {
ROTATE_MODE,
ZOOM_MODE,
SHIFT_MODE,
ROLL_MODE
};
/**
* The Constructor.
*
* @param camera the camera property that is to be modified by the navigation
* @param minDist the minimum allowed orthogonal distance to the center of the trackball
* @param maxDist the maximum allowed orthogonal distance to the center of the trackball
*/
TrackballNavigation(CameraProperty* cameraProperty, Mode mode = ROTATE_MODE, float minDist = 0.01f);
virtual ~TrackballNavigation();
void setMode(Mode mode);
Mode getMode() const;
bool isTracking() {
return tracking_;
}
/**
* React to a press-Event.
*
* @param e The event to be processed.
*/
virtual void mousePressEvent(tgt::MouseEvent* e);
/**
* React to a touch press-Event.
*
* @param e The event to be processed.
*/
virtual void touchPressEvent(tgt::TouchEvent* e);
/**
* React to a touch release event.
*
* @param e The event to be processed.
*/
virtual void touchReleaseEvent(tgt::TouchEvent* e);
/**
* React to a touch move-Event. Actually this causes rotation or zoom.
*
* @param e The event to be processed.
*/
virtual void touchMoveEvent(tgt::TouchEvent* e);
/**
* React to a release event.
*
* @param e The event to be processed.
*/
virtual void mouseReleaseEvent(tgt::MouseEvent* e);
/**
* React to a move-Event. In this case, this actually causes the object to rotate.
*
* @param e The event to be processed.
*/
virtual void mouseMoveEvent(tgt::MouseEvent* e);
/**
* React to a double-click-Event.
*
* @param e The event to be processed.
*/
virtual void mouseDoubleClickEvent(tgt::MouseEvent* e);
/**
* React to a mouse-wheel-Event.
*
* @param e The event to be processed.
*/
virtual void wheelEvent(tgt::MouseEvent* e);
/**
* React to a time-Event. This does a number of things:
*
* - If necessary auto-spin the trackball.
* - If the mouse-wheel was used, switch coarseness off after a certain amount of time.
* - If auto-spinning of the trackball is active, don't spin the trackball if the user has
* waited too long after moving the mouse.
*
* @param e The event to be processed.
*/
virtual void timerEvent(tgt::TimeEvent* e);
/**
* React to key event.
*/
virtual void keyEvent(tgt::KeyEvent* e);
/**
* Returns the internally used trackball.
*/
VoreenTrackball* getTrackball();
/**
* Let trackball react on key pressures with rotating
* @param acuteness The per-keypress angle of rotation will be smaller at greater acuteness. Use acuteness = 0.f to disable key rotation.
* @param left, right, up, down keycode which should cause suitable rotation
* @param mod which modifiers must be set
* @param pressed rotate on key-pressed-event when true, on key-release-event when false
*
*/
void setKeyRotate(float acuteness = 10.f,
tgt::KeyEvent::KeyCode left = tgt::KeyEvent::K_LEFT,
tgt::KeyEvent::KeyCode right = tgt::KeyEvent::K_RIGHT,
tgt::KeyEvent::KeyCode up = tgt::KeyEvent::K_UP,
tgt::KeyEvent::KeyCode down = tgt::KeyEvent::K_DOWN,
int mod = tgt::Event::MODIFIER_NONE,
bool pressed = false);
/**
* Let trackball react on key presses with moving
* @param acuteness The per-keypress length of movement will be smaller at greater
* acuteness. Use acuteness = 0.f to disable key rotation.
* @param left, right, up, down keycode which should cause suitable movement
* @param mod which modifiers must be set
* @param pressed move on key-pressed-event when true, on key-release-event when false
*/
void setKeyMove(float acuteness = 100.f,
tgt::KeyEvent::KeyCode left = tgt::KeyEvent::K_LEFT,
tgt::KeyEvent::KeyCode right = tgt::KeyEvent::K_RIGHT,
tgt::KeyEvent::KeyCode up = tgt::KeyEvent::K_UP,
tgt::KeyEvent::KeyCode down = tgt::KeyEvent::K_DOWN,
int mod = tgt::Event::SHIFT,
bool pressed = false);
/**
* Defines the mouse zoom direction.
*
* @param zoomInDirection specifies in which direction mouse must be moved to zoom in.
* The greater the length of this vector, the longer the way the mouse must be moved
* to achieve a certain zoom factor.
*/
void setMouseZoom(tgt::vec2 zoomInDirection);
/**
* Defines mouse wheel zoom acuteness.
*
* @param acuteness The zoom factor will be smaller at greater acuteness. Use acuteness = 0.f to disable key rotation.
* @param wheelUpZoomIn zoom in on wheel up and out on wheel down when true, otherwise when false
*/
void setMouseWheelZoom(float acuteness = 10.f, bool wheelUpZoomIn = true);
/// @param acuteness The zoom factor will be smaller at greater acuteness. Use acuteness = 0.f to disable key rotation.
void setKeyZoom(float acuteness = 10.f,
tgt::KeyEvent::KeyCode in = tgt::KeyEvent::K_UP,
tgt::KeyEvent::KeyCode out = tgt::KeyEvent::K_DOWN,
int mod = tgt::Event::CTRL,
bool pressed = false);
/**
* Defines the mouse roll acuteness.
*
* @param acuteness greater the acuteness means less tiling
*/
void setMouseRoll(float acuteness);
/**
* Defines the mouse wheel roll acuteness and direction.
*
* @param acuteness Less tiling at greater acuteness. Use acuteness = 0.f to disable key rotation.
* @param wheelUpRollLeft roll left on wheel up and right on wheel down when true, otherwise when false
*/
void setMouseWheelRoll(float acuteness, bool wheelUpRollLeft = true);
/// @param acuteness Less tiling at greater acuteness. Use acuteness = 0.f to disable key rotation.
void setKeyRoll(float acuteness = 10.f,
tgt::KeyEvent::KeyCode left = tgt::KeyEvent::K_LEFT,
tgt::KeyEvent::KeyCode right = tgt::KeyEvent::K_RIGHT,
int mod = tgt::Event::ALT,
bool pressed = false);
protected:
void startMouseDrag(tgt::MouseEvent* eve);
void endMouseDrag(tgt::MouseEvent* eve);
/// The following functions may be used to rotate the Up-Vector about
/// the Strafe- and the Look-Vector. Use this with care since it may
/// leave the Camera with a "strange" orientation.
void rollCameraVert(float angle);
void rollCameraHorz(float angle);
void initializeEventHandling();
/// scale screen-coodinates of mouse to intervall [-1, 1]x[-1, 1]
tgt::vec2 scaleMouse(const tgt::ivec2& coords, const tgt::ivec2& viewport) const;
float getRotationAngle(float acuteness) const;
float getMovementLength(float acuteness) const;
float getZoomFactor(float acuteness, bool zoomIn) const;
float getRollAngle(float acuteness, bool left) const;
/// Resets position and orientation of the trackball's camera to the initial parameters the camera had
/// when passed to the trackball.
/// Projective parameters (frustum) are not touched.
virtual void resetTrackball();
CameraProperty* cameraProperty_; ///< Camera property that is modified
VoreenTrackball* trackball_; ///< The trackball that is modified when navigating
Mode mode_; ///< current trackball mode: rotate, zoom, shift, roll
/// Last mouse coordinates to allow calculation of the relative change.
/// Ought to be relative coordinates within range [-1, 1]x[-1, 1].
tgt::vec2 lastMousePosition_;
// Last distance between two TouchPoints to allow calculation of zoomFactor
float lastDistance_;
// Last connection vector between two touch points
tgt::vec2 lastConnection_;
//float minDistance_; ///< minimal allowed orthogonal distance to center of trackball
//float maxDistance_; ///< maximal allowed orthogonal distance to center of trackball (now retrieved from camera property)
int wheelCounter_; ///< Counts how many time-ticks have passed since the mouse-wheel was used.
int spinCounter_; ///< Counts how many time-ticks have passed since the trackball was spun.
int moveCounter_; ///< Counts how many time-ticks have passed since the user has moved the mouse.
int wheelID_;
int spinID_;
int moveID_;
int overlayTimerID_;
bool spinit_; ///< Helper member to control auto-spinning of trackball.
bool trackballEnabled_; ///< Is the trackball enabled?
bool tracking_; ///< Are we tracking mouse move events? Only when we received a mousePressEvent before.
/// used to store settings how to react on certain events
float keyRotateAcuteness_ ; ///< acuteness of rotation steps of key presses
tgt::KeyEvent::KeyCode keyRotateLeft_ ; ///< at which key code rotate left
tgt::KeyEvent::KeyCode keyRotateRight_ ; ///< at which key code rotate right
tgt::KeyEvent::KeyCode keyRotateUp_ ; ///< at which key code rotate up
tgt::KeyEvent::KeyCode keyRotateDown_ ; ///< at which key code rotate down
int keyRotateMod_ ; ///< at which modifiers to rotate by keys
bool keyRotatePressed_ ;
float keyMoveAcuteness_ ;
tgt::KeyEvent::KeyCode keyMoveLeft_ ;
tgt::KeyEvent::KeyCode keyMoveRight_ ;
tgt::KeyEvent::KeyCode keyMoveUp_ ;
tgt::KeyEvent::KeyCode keyMoveDown_ ;
int keyMoveMod_ ;
bool keyMovePressed_ ;
tgt::vec2 mouseZoomInDirection_ ;
float mouseWheelZoomAcuteness_ ;
bool mouseWheelUpZoomIn_ ;
float keyZoomAcuteness_ ;
tgt::KeyEvent::KeyCode keyZoomIn_ ;
tgt::KeyEvent::KeyCode keyZoomOut_ ;
int keyZoomMod_ ;
bool keyZoomPressed_ ;
float mouseRollAcuteness_ ;
float mouseWheelRollAcuteness_ ;
bool mouseWheelUpRollLeft_ ;
float keyRollAcuteness_ ;
tgt::KeyEvent::KeyCode keyRollLeft_ ;
tgt::KeyEvent::KeyCode keyRollRight_ ;
int keyRollMod_ ;
bool keyRollPressed_ ;
tgt::MouseEvent::MouseButtons resetButton_ ; ///< If this button is double-clicked, reset trackball to initial
/// position and orientation
static const std::string loggerCat_;
};
} // namespace
#endif //VRN_TRACKBALL_NAVIGATION_H
| [
"kalimi@wisc.edu"
] | kalimi@wisc.edu |
037613bd2d78379c84cfaac6b7a28e62a83d89cb | 9c9632cc91135b1bc7222f60bda99a5da4018f85 | /02.Product/Cloud/Cpp/Devmgr/tags/dev_crs_net/V4.2.5/build/linux/sredisdll/include/sredisdll.h | 7312f9fb957b378a084484b43669cf897dd88d3a | [] | no_license | lltxwdk/testgame | eb71624141f85f6aabcae85b417ab6aa286403fb | 1cc55d9d2a25594818cfe365c0dcc0b476e9053e | refs/heads/master | 2022-08-01T05:24:48.024701 | 2020-05-24T05:07:59 | 2020-05-24T05:07:59 | 187,604,627 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 5,701 | h | // The following ifdef block is the standard way of creating macros which make exporting
// from a DLL simpler. All files within this DLL are compiled with the SREDISDLL_EXPORTS
// symbol defined on the command line. this symbol should not be defined on any project
// that uses this DLL. This way any other project whose source files include this file see
// SREDISDLL_API functions as being imported from a DLL, whereas this DLL sees symbols
// defined with this macro as being exported.
#ifndef __SR_REDISDLL_I_H__
#define __SR_REDISDLL_I_H__
#include <vector>
#include <set>
#include <string.h>
#include <string>
#include <map>
using namespace std;
#ifdef __cplusplus
extern "C" {
#endif
#ifdef LINUX
#define __stdcall
#endif
#ifdef SREDISDLL_EXPORTS
#define SREDISDLL_API __declspec(dllexport)
#else
#define SREDISDLL_API
#endif
// This class is exported from the sredisdll.dll
namespace ISREDIS
{
typedef struct CNETMPLOAD
{
int deviceid;
unsigned long long load;
}CNetMpLoad;
typedef struct CVALUESCORE
{
char value[256];
char score[256];
}ValueScores;
typedef struct CHKEYS
{
char filed[256];
}CHKeys;
typedef struct CDEVICEID
{
int deviceid;
}CDeviceID;
//串口观察者接口
class ICsredisSink
{
public:
};
typedef struct REDIS_DATA_ITEM_
{
int type;
std::string str;
REDIS_DATA_ITEM_& operator=(const REDIS_DATA_ITEM_ &data)
{
type = data.type;
str = data.str;
return *this;
}
}RedisDataItem;
typedef std::vector<RedisDataItem> RedisReplyData;
typedef RedisReplyData RedisReplyArray;
typedef std::string REDISKEY;
typedef std::string REDISVALUE;
typedef std::vector<REDISKEY> REDISVKEYS;
typedef REDISVKEYS REDISFILEDS;
typedef std::vector<REDISVALUE> REDISVALUES;
typedef std::vector<std::string> REDISVDATA;
typedef std::set<std::string> REDISSETDATA;
typedef std::map<std::string, RedisDataItem> RedisReplyKeyValuePair;
class ICsredis {
public:
// TODO: add your methods here.
virtual bool connect(const char* host, int port = 6379) = 0;
virtual bool isconnectok() = 0;
virtual void disconnect() = 0;
virtual void flushall() = 0; //获取指定key值
virtual char* getvalue(const char* key) = 0; //获取指定key值
virtual char* getvalue(const char* key, const char* number) = 0; //获取指定key值
virtual bool setvalue(const char* key, const char* value) = 0; //设置指定key值
virtual bool setvalue(const char* key, const char* score, const char* number) = 0; //设定key sort set值
virtual bool sethashvalue(const char* key, const char* score, const char* number) = 0; //设定key sort set值
virtual char* gethashvalue(const char* key, const char* score) = 0;
virtual bool selectdb(const int dbnum) = 0; //切换数据库
virtual bool pingpong() = 0; // 探测连接是否正常
virtual bool deletevalue(const char* key) = 0; //删除值
virtual bool deletevalue(const char* key, const char* number) = 0; //删除值
virtual bool deletehashvalue(const char* key, const char* number) = 0; //删除值
virtual bool existsvalue(const char* key) = 0; //判断值是否存在
virtual long long getdbnum(const char* key) = 0; //获取指定数据库关键词内容长度
virtual int getdbdata(const char* key, int start, int stop, CNetMpLoad** load, const int getvcnum) = 0; //获取指定数据库关键词内容
virtual int getzsetdata(const char* key, int start, int stop, ValueScores** valuescores, const int getvcnum) = 0; //获取指定数据库关键词zset内容
virtual int getdbdata(const char* key, char* id, unsigned long long& load) = 0; //获取指定数据库关键词内容
virtual int getdbdata(const char* key, CDeviceID** id, const int getvcnum) = 0; //获取指定数据库关键词内容
virtual long long gethashfiledsnum(const char* key) = 0; //获取指定数据库关键词内容长度
virtual int gethashdbdata(const char* key, CHKeys** fileds, const int filedsnum) = 0; //获取指定数据库关键词内容
virtual bool listLPush(const char* key, const char* value) = 0;//
virtual char* listRPop(const char* key) = 0;
virtual long long listLLen(const char* key) = 0;
virtual bool hashHMSet(const string& key, const REDISVDATA& vData) = 0; // HMSET
virtual bool hashHMGet(const string& key, const REDISFILEDS& fileds, RedisReplyArray& rArray) = 0; // HMGET
virtual bool hashHMGet(const string& key, const REDISFILEDS& fileds, RedisReplyKeyValuePair& mPair) = 0; // HMGET
//virtual bool hashHGetAll(const string& key, RedisReplyArray& rArray) = 0; // HGETALL
virtual bool hashHGetAll(const char* key, RedisReplyArray& rArray) = 0;
virtual ~ICsredis(){}
};
/**
* @function CreateIRedis
* @abstract 创建对象
* @param
* @pSink
* @return ISREDIS*
*/
SREDISDLL_API ICsredis* CreateIRedis(ICsredisSink* pcSink);
/**
* @function CreateRedisInstanceList
* @abstract 创建对象
* @param
* @pSink
* @return ISREDIS*
*/
SREDISDLL_API ICsredis** CreateRedisInstanceList(ICsredisSink* pcSink, unsigned int uiRedisConnNum);
/**
* @function DeleteIRedis
* @abstract 删除对象
* @param
* @return 无
*/
SREDISDLL_API void DeleteIRedis(ICsredis* pIRedis);
/**
* @function DeleteRedisInstanceList
* @abstract 删除对象
* @param
* @return 无
*/
SREDISDLL_API void DeleteRedisInstanceList(ICsredis** pIRedis, unsigned int uiRedisConnNum);
}
#ifdef __cplusplus
}
#endif
#endif //__SR_REDISDLL_I_H__
| [
"375563752@qq.com"
] | 375563752@qq.com |
0b7d960a83cff6a7afa126115833cf2f5753ea48 | 3459ad2afff7ad28c99c0e6837755aedda7f5ff1 | /WarehouseControlSystem/ControlClass/externcommuincation/tcommtcpclient.cpp | 937a6a83f9cfd413293504be6df4ab34c2f703ca | [] | no_license | KorolWu/WCSFinal | 7fbe534114d8dae3f83f0e80897e7b3fc2683097 | ea0b8cd71f8ffc9da5d43ab9c511130039a9d32a | refs/heads/master | 2023-04-03T01:32:45.274632 | 2021-04-22T01:00:17 | 2021-04-22T01:00:17 | 360,348,654 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,277 | cpp | #include "tcommtcpclient.h"
#include <QDateTime>
#include "tcommtransceivermanager.h"
#include "UnitClass/c_systemlogmng.h"
TCommTCPclient::TCommTCPclient()
{
socket = nullptr;
m_connectStatus = false;
connect(this,&TCommTCPclient::signalSendHWdeviceData,this,&TCommTCPclient::write);
connect(this,&TCommTCPclient::signalClientconnectserver,this,&TCommTCPclient::reConnection);
}
TCommTCPclient::~TCommTCPclient()
{
if(socket == nullptr)
return;
socket->disconnectFromHost();
socket->close();
socket = nullptr;
}
void TCommTCPclient::SetCommParam(ComConfigStru paramstru)
{
m_config = paramstru.hwTcpstru;
creadTcpClient();
}
int TCommTCPclient::GetNameID()
{
return m_config.ID;
}
int TCommTCPclient::GetHWtype()
{
return m_config.hwtype;
}
int TCommTCPclient::GetHWprotype()
{
return KTcpClient;
}
void TCommTCPclient::CloseComm()
{
if(socket == nullptr)
return;
socket->disconnectFromHost();
socket->close();
}
uint recindex = 0;
bool TCommTCPclient::creadTcpClient()
{
this->m_ip = m_config.name;
this->m_port = m_config.port ;
// if( m_config.ID == 0)
// {
// this->m_ip = "10.0.1.68";
// this->m_port = 1883;
// }
// qDebug()<<"ip "<< m_config.name << m_config.port;
socket = new QTcpSocket(this);
connect(socket,&QTcpSocket::disconnected,this,&TCommTCPclient::onDisconnected);
connect(socket,&QTcpSocket::connected,
[=]()
{
m_connectStatus = true;
// qDebug()<<"ip "<< m_config.name << m_config.port << m_connectStatus ;
m_connectstate = 1;
} );
connect(socket,&QTcpSocket::readyRead,
[=]()
{
QByteArray array = socket->readAll();
// qDebug()<<"小车收到的数据包情况:"<<QDateTime::currentDateTime() << m_config.ID << m_config.port << array.toHex()<< array.length();
//测试部分收到的数据-----------------2020/11/07
if( m_config.ID == 1)
{
if(!(array.length() == 10 || array.length() == 74))
{
// qDebug()<< "!!!!小车收到的数据长度异常:" <<QDateTime::currentDateTime()<< array.length();
}
//分析报文类型
if(array.length() >= 10)
{
// int16_t nbr;//指令编号
// int16_t carnbr;//小车编号
// atoi16 nbrvalue;
// memcpy(nbrvalue.a,array.data(),2);
// nbr = nbrvalue.x;
atoi16 carrvalue;
memcpy(carrvalue.a,array.data()+2,2);
// carnbr = carrvalue.x;
recindex++;
if(array[4] == 'S' && array[5] == 'D'&&(array.size() >= 74))//详细报文数据
{
//qDebug()<<"收到:WCS收到小车发送详细数据报文:" << QDateTime::currentDateTime()<< array.length() << array.toHex() <<nbr << recindex ;
//解析详细数据内容
ReceCarDetailFrame detailstru;//详细数据报文
memcpy((char*)&detailstru,array.data(),74);
// qDebug()<<"收到:WCS收到小车发送详细数据报文解析内容准备状态:" << QDateTime::currentDateTime()<<";长度:" <<array.length() << "ready:"<<detailstru.info.bready <<"unready:"<<detailstru.info.bunready;
}
else {
//qDebug()<< "通讯对象中WCS收到小车发送动作数据或者粘包数据报文:"<<QDateTime::currentDateTime()<< array.length() <<array.toHex();
}
}
}
//测试部分收到的数据-----------------2020/11/07
emit signalReadHWdeviceData(m_config.ID,m_config.hwtype,array);
// qDebug()<<"收到流道数据内容"<<array.toHex() <<"id"<<m_config.ID;
});
bool connect = connectServer(m_ip,m_port);
emit signalHWDisconnect(m_config.ID,m_config.hwtype,m_connectStatus);
return connect;
}
bool TCommTCPclient::connectServer(QString ip, qint16 port)
{
if(socket == nullptr)
return false;
socket->connectToHost(QHostAddress(ip),port);
if(socket->waitForConnected(1000))
{
return true;
}
else
{
return false;
}
}
bool TCommTCPclient::reConnection()
{
if(m_connectstate)
return true;
m_connectStatus = connectServer(this->m_ip,this->m_port);
if(m_connectStatus)//连接成功发出成功状态
{
emit signalHWDisconnect(m_config.ID,m_config.hwtype,m_connectStatus);
m_connectstate = 1;
}
else{
m_connectstate = 0;
}
return m_connectStatus;
}
uint sendcnt = 0;
uint senaction = 0;
int TCommTCPclient::write(QByteArray array)
{
if(!m_connectStatus)//连接成功发出成功状态
return 1;
if(socket == nullptr)
return 1;
int iresultsize = 0;
iresultsize = socket->write(array);
if(iresultsize != 40 && m_config.ID == 1)
{
QString str = QString("数据发送失败当前发送成功数量:%1; send array:%2,发送时间:%3; 发送结果:iresultsize").arg(sendcnt).arg(QString(array.toHex())).arg(QDateTime::currentDateTime().toString());
qDebug()<< str<<QDateTime::currentDateTime();;
GetSystemLogObj()->writeLog(str,2);
}
// else{
// sendcnt++;
// if(m_config.ID == 1&&(!(array[32] == 0 && array[33] == 0)))
// {
// QString str = QString("WCS发送动作指令数据到小车ID:[%1],发送时间:%2,发送的数据16进制:%3;").arg(m_config.ID).arg(QDateTime::currentDateTime().toString()).arg(QString(array.toHex()));
// qDebug() << str;
// }
// if(m_config.ID == 1)
// {
// QString str = QString("WCS发送指令数据到小车ID:[%1],发送时间:%2,发送的数据16进制:%3;").arg(m_config.ID).arg(QDateTime::currentDateTime().toString()).arg(QString(array.toHex()));
// qDebug() << str;
// }
// }
return 0;
}
void TCommTCPclient::onDisconnected()
{
m_connectstate = 0;
m_connectStatus = false;
emit clientDisconnect(m_config.ID,m_config.hwtype);
emit signalHWDisconnect(m_config.ID,m_config.hwtype,m_connectStatus);
}
| [
"1050476035@qq.com"
] | 1050476035@qq.com |
50994871acb87e0cb9dcbf9b063267a380f40f82 | 709ceec684610f302a031806eea86e375031a726 | /PUBG_WeaponEquipmentSlotWidget_parameters.hpp | 7e9aa3c725ddce5d8b66e21fd6f92f8455b7850e | [] | no_license | denfrost/UE4_SDK_DUMP | 867df3a4fdc0a714ca04a52ba0f5d3d6dc7d6e22 | 05f3d9dd27c9148d3d41162db07d395074467d15 | refs/heads/master | 2020-03-25T08:02:35.815045 | 2017-12-28T03:26:29 | 2017-12-28T03:26:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,223 | hpp | #pragma once
// PLAYERUNKNOWN'S BATTLEGROUNDS (2.4.24) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace Classes
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.GetSlotItem
struct UWeaponEquipmentSlotWidget_C_GetSlotItem_Params
{
TScriptInterface<class USlotInterface> SlotItem; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.GetSlotContainer
struct UWeaponEquipmentSlotWidget_C_GetSlotContainer_Params
{
TScriptInterface<class USlotContainerInterface> SlotContainer; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.SetGamepadSelfPutAttachmentFocus
struct UWeaponEquipmentSlotWidget_C_SetGamepadSelfPutAttachmentFocus_Params
{
bool bFocus; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.InputB
struct UWeaponEquipmentSlotWidget_C_InputB_Params
{
bool ReturnValue; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_ReturnParm, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.OnChildSlotRefreshFocus
struct UWeaponEquipmentSlotWidget_C_OnChildSlotRefreshFocus_Params
{
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.GetFocusingChildWidget
struct UWeaponEquipmentSlotWidget_C_GetFocusingChildWidget_Params
{
class UUserWidget* ReturnValue; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_ReturnParm, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.Up
struct UWeaponEquipmentSlotWidget_C_Up_Params
{
bool ReturnValue; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_ReturnParm, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.Right
struct UWeaponEquipmentSlotWidget_C_Right_Params
{
bool ReturnValue; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_ReturnParm, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.Down
struct UWeaponEquipmentSlotWidget_C_Down_Params
{
bool ReturnValue; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_ReturnParm, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.Left
struct UWeaponEquipmentSlotWidget_C_Left_Params
{
bool ReturnValue; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_ReturnParm, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.GetChildRightFocusableWidget
struct UWeaponEquipmentSlotWidget_C_GetChildRightFocusableWidget_Params
{
class UUserWidget* RightWidget; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.GetChildLeftFocusableWidget
struct UWeaponEquipmentSlotWidget_C_GetChildLeftFocusableWidget_Params
{
class UUserWidget* LeftWidget; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.GetChildDownFocusableWidget
struct UWeaponEquipmentSlotWidget_C_GetChildDownFocusableWidget_Params
{
class UUserWidget* DownWidget; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.GetChildUpFocusableWidget
struct UWeaponEquipmentSlotWidget_C_GetChildUpFocusableWidget_Params
{
class UUserWidget* UpWidget; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.IsFocusable
struct UWeaponEquipmentSlotWidget_C_IsFocusable_Params
{
bool ReturnValue; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_ReturnParm, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.FindFirstFocusableWidget
struct UWeaponEquipmentSlotWidget_C_FindFirstFocusableWidget_Params
{
class UUserWidget* FocusableWidget; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.IsFocus
struct UWeaponEquipmentSlotWidget_C_IsFocus_Params
{
bool ReturnValue; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_ReturnParm, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.SetFocus
struct UWeaponEquipmentSlotWidget_C_SetFocus_Params
{
bool* NewFocus; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
bool ReturnValue; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_ReturnParm, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.On_FocusColorBG_Prepass_1
struct UWeaponEquipmentSlotWidget_C_On_FocusColorBG_Prepass_1_Params
{
class UWidget* BoundWidget; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.InputA
struct UWeaponEquipmentSlotWidget_C_InputA_Params
{
bool ReturnValue; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_ReturnParm, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.OnSpawnActorInSceneCaptureWorld
struct UWeaponEquipmentSlotWidget_C_OnSpawnActorInSceneCaptureWorld_Params
{
class AActor* SpawnedActor; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.GetDragDroppingEquipableItem
struct UWeaponEquipmentSlotWidget_C_GetDragDroppingEquipableItem_Params
{
class UEquipableItem* EquipableItem; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.FindEquipableWeaponPosition
struct UWeaponEquipmentSlotWidget_C_FindEquipableWeaponPosition_Params
{
struct FEquipPosition WeaponPosition; // (CPF_Parm, CPF_OutParm)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.UpdateWeaponGunInfo
struct UWeaponEquipmentSlotWidget_C_UpdateWeaponGunInfo_Params
{
class UWidget* BoundWidget; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.On_AmmoIcon_Prepass_1
struct UWeaponEquipmentSlotWidget_C_On_AmmoIcon_Prepass_1_Params
{
class UWidget* BoundWidget; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.GetAmmoName
struct UWeaponEquipmentSlotWidget_C_GetAmmoName_Params
{
struct FText ItemName; // (CPF_Parm, CPF_OutParm)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.GetAmmoIcon
struct UWeaponEquipmentSlotWidget_C_GetAmmoIcon_Params
{
struct FSlateBrush ReturnValue; // (CPF_Parm, CPF_OutParm, CPF_ReturnParm)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.GetHandOnUnLoadedAmmoCount
struct UWeaponEquipmentSlotWidget_C_GetHandOnUnLoadedAmmoCount_Params
{
int Count; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.GetHandOnLoadedAmmoCount
struct UWeaponEquipmentSlotWidget_C_GetHandOnLoadedAmmoCount_Params
{
int Count; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.On_AmmoName_Prepass_1
struct UWeaponEquipmentSlotWidget_C_On_AmmoName_Prepass_1_Params
{
class UWidget* BoundWidget; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.On_AmmoInfoLayer_Prepass_1
struct UWeaponEquipmentSlotWidget_C_On_AmmoInfoLayer_Prepass_1_Params
{
class UWidget* BoundWidget; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.On_WeaponHandsOnUnloadedAmmoCount_Prepass_1
struct UWeaponEquipmentSlotWidget_C_On_WeaponHandsOnUnloadedAmmoCount_Prepass_1_Params
{
class UWidget* BoundWidget; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.On_WeaponHandsOnLoadedAmmoCount_Prepass_1
struct UWeaponEquipmentSlotWidget_C_On_WeaponHandsOnLoadedAmmoCount_Prepass_1_Params
{
class UWidget* BoundWidget; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.On_WeaponName_Prepass_1
struct UWeaponEquipmentSlotWidget_C_On_WeaponName_Prepass_1_Params
{
class UWidget* BoundWidget; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.On_KeyName_Prepass_1
struct UWeaponEquipmentSlotWidget_C_On_KeyName_Prepass_1_Params
{
class UWidget* BoundWidget; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.OnUpdateWeapon
struct UWeaponEquipmentSlotWidget_C_OnUpdateWeapon_Params
{
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.On_WeaponCaptureImage_Prepass_1
struct UWeaponEquipmentSlotWidget_C_On_WeaponCaptureImage_Prepass_1_Params
{
class UWidget* BoundWidget; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.GetItem_Bp
struct UWeaponEquipmentSlotWidget_C_GetItem_Bp_Params
{
class UItem* Item; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.IsAttachmentSlotMouseOver
struct UWeaponEquipmentSlotWidget_C_IsAttachmentSlotMouseOver_Params
{
bool MouseOver; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.IsSlotMouseOver_Bp
struct UWeaponEquipmentSlotWidget_C_IsSlotMouseOver_Bp_Params
{
bool IsMouseOver; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.IsSlotSubOn_Bp
struct UWeaponEquipmentSlotWidget_C_IsSlotSubOn_Bp_Params
{
bool SubOn; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.IsSlotOn_Bp
struct UWeaponEquipmentSlotWidget_C_IsSlotOn_Bp_Params
{
bool IsOn; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.OnDrop
struct UWeaponEquipmentSlotWidget_C_OnDrop_Params
{
struct FGeometry* MyGeometry; // (CPF_Parm, CPF_IsPlainOldData)
struct FPointerEvent* PointerEvent; // (CPF_Parm)
class UDragDropOperation** Operation; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
bool ReturnValue; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_ReturnParm, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.GetWeaponSlotEquipId
struct UWeaponEquipmentSlotWidget_C_GetWeaponSlotEquipId_Params
{
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.MainPrepass_1
struct UWeaponEquipmentSlotWidget_C_MainPrepass_1_Params
{
class UWidget* BoundWidget; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.InitializeWeaponEquipSlot
struct UWeaponEquipmentSlotWidget_C_InitializeWeaponEquipSlot_Params
{
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.RefreshAttachmentSlot
struct UWeaponEquipmentSlotWidget_C_RefreshAttachmentSlot_Params
{
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.OnMouseButtonUp
struct UWeaponEquipmentSlotWidget_C_OnMouseButtonUp_Params
{
struct FGeometry* MyGeometry; // (CPF_Parm, CPF_IsPlainOldData)
struct FPointerEvent* MouseEvent; // (CPF_ConstParm, CPF_Parm, CPF_OutParm, CPF_ReferenceParm)
struct FEventReply ReturnValue; // (CPF_Parm, CPF_OutParm, CPF_ReturnParm)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.OnDragDetected
struct UWeaponEquipmentSlotWidget_C_OnDragDetected_Params
{
struct FGeometry* MyGeometry; // (CPF_Parm, CPF_IsPlainOldData)
struct FPointerEvent* PointerEvent; // (CPF_ConstParm, CPF_Parm, CPF_OutParm, CPF_ReferenceParm)
class UDragDropOperation* Operation; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.OnMouseButtonDown
struct UWeaponEquipmentSlotWidget_C_OnMouseButtonDown_Params
{
struct FGeometry* MyGeometry; // (CPF_Parm, CPF_IsPlainOldData)
struct FPointerEvent* MouseEvent; // (CPF_ConstParm, CPF_Parm, CPF_OutParm, CPF_ReferenceParm)
struct FEventReply ReturnValue; // (CPF_Parm, CPF_OutParm, CPF_ReturnParm)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.GetSlotVisibility
struct UWeaponEquipmentSlotWidget_C_GetSlotVisibility_Params
{
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.GetWeaponIcon
struct UWeaponEquipmentSlotWidget_C_GetWeaponIcon_Params
{
struct FSlateBrush ReturnValue; // (CPF_Parm, CPF_OutParm, CPF_ReturnParm)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.GetWeaponInfoText
struct UWeaponEquipmentSlotWidget_C_GetWeaponInfoText_Params
{
struct FText ReturnValue; // (CPF_Parm, CPF_OutParm, CPF_ReturnParm)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.Construct
struct UWeaponEquipmentSlotWidget_C_Construct_Params
{
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.OnUpdateEquip
struct UWeaponEquipmentSlotWidget_C_OnUpdateEquip_Params
{
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.OnDragEnter
struct UWeaponEquipmentSlotWidget_C_OnDragEnter_Params
{
struct FGeometry* MyGeometry; // (CPF_Parm, CPF_IsPlainOldData)
struct FPointerEvent* PointerEvent; // (CPF_Parm)
class UDragDropOperation** Operation; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.OnDragLeave
struct UWeaponEquipmentSlotWidget_C_OnDragLeave_Params
{
struct FPointerEvent* PointerEvent; // (CPF_Parm)
class UDragDropOperation** Operation; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.OnDragSlotEnter
struct UWeaponEquipmentSlotWidget_C_OnDragSlotEnter_Params
{
int SlotIndex; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.OnDragSlotLeave
struct UWeaponEquipmentSlotWidget_C_OnDragSlotLeave_Params
{
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.OnMouseEnter
struct UWeaponEquipmentSlotWidget_C_OnMouseEnter_Params
{
struct FGeometry* MyGeometry; // (CPF_Parm, CPF_IsPlainOldData)
struct FPointerEvent* MouseEvent; // (CPF_ConstParm, CPF_Parm, CPF_OutParm, CPF_ReferenceParm)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.OnMouseLeave
struct UWeaponEquipmentSlotWidget_C_OnMouseLeave_Params
{
struct FPointerEvent* MouseEvent; // (CPF_ConstParm, CPF_Parm, CPF_OutParm, CPF_ReferenceParm)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.OnUpdateItem
struct UWeaponEquipmentSlotWidget_C_OnUpdateItem_Params
{
class UItem** Item; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.UpdateDragDropObject
struct UWeaponEquipmentSlotWidget_C_UpdateDragDropObject_Params
{
class UTslItemDragDropOperation_C** DragDropObject; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.SetInventory
struct UWeaponEquipmentSlotWidget_C_SetInventory_Params
{
class UInventoryWidget_C** InventoryWidget; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.BndEvt__UpperRail_K2Node_ComponentBoundEvent_14_RefreshFocus__DelegateSignature
struct UWeaponEquipmentSlotWidget_C_BndEvt__UpperRail_K2Node_ComponentBoundEvent_14_RefreshFocus__DelegateSignature_Params
{
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.BndEvt__Muzzle_K2Node_ComponentBoundEvent_16_RefreshFocus__DelegateSignature
struct UWeaponEquipmentSlotWidget_C_BndEvt__Muzzle_K2Node_ComponentBoundEvent_16_RefreshFocus__DelegateSignature_Params
{
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.BndEvt__LowerRail_K2Node_ComponentBoundEvent_19_RefreshFocus__DelegateSignature
struct UWeaponEquipmentSlotWidget_C_BndEvt__LowerRail_K2Node_ComponentBoundEvent_19_RefreshFocus__DelegateSignature_Params
{
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.BndEvt__Magazine_K2Node_ComponentBoundEvent_23_RefreshFocus__DelegateSignature
struct UWeaponEquipmentSlotWidget_C_BndEvt__Magazine_K2Node_ComponentBoundEvent_23_RefreshFocus__DelegateSignature_Params
{
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.BndEvt__Stock_K2Node_ComponentBoundEvent_28_RefreshFocus__DelegateSignature
struct UWeaponEquipmentSlotWidget_C_BndEvt__Stock_K2Node_ComponentBoundEvent_28_RefreshFocus__DelegateSignature_Params
{
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.WidgetInputBPressed
struct UWeaponEquipmentSlotWidget_C_WidgetInputBPressed_Params
{
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.OnWidgetInputBReleased
struct UWeaponEquipmentSlotWidget_C_OnWidgetInputBReleased_Params
{
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.Tick
struct UWeaponEquipmentSlotWidget_C_Tick_Params
{
struct FGeometry* MyGeometry; // (CPF_Parm, CPF_IsPlainOldData)
float* InDeltaTime; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.OnSlotMoveUp
struct UWeaponEquipmentSlotWidget_C_OnSlotMoveUp_Params
{
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.OnSlotMoveDown
struct UWeaponEquipmentSlotWidget_C_OnSlotMoveDown_Params
{
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.SlotMoveLeft
struct UWeaponEquipmentSlotWidget_C_SlotMoveLeft_Params
{
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.OnSlotMoveRight
struct UWeaponEquipmentSlotWidget_C_OnSlotMoveRight_Params
{
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.CustomEvent_1
struct UWeaponEquipmentSlotWidget_C_CustomEvent_1_Params
{
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.OnWidgetInputX
struct UWeaponEquipmentSlotWidget_C_OnWidgetInputX_Params
{
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.CustomEvent_2
struct UWeaponEquipmentSlotWidget_C_CustomEvent_2_Params
{
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.OnInputWidgetInputB
struct UWeaponEquipmentSlotWidget_C_OnInputWidgetInputB_Params
{
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.ExecuteUbergraph_WeaponEquipmentSlotWidget
struct UWeaponEquipmentSlotWidget_C_ExecuteUbergraph_WeaponEquipmentSlotWidget_Params
{
int EntryPoint; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.OnDragLeaveWeaponSlot__DelegateSignature
struct UWeaponEquipmentSlotWidget_C_OnDragLeaveWeaponSlot__DelegateSignature_Params
{
int SlotIndex; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.OnDragEnterWeaponSlot__DelegateSignature
struct UWeaponEquipmentSlotWidget_C_OnDragEnterWeaponSlot__DelegateSignature_Params
{
int SlotIndex; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
};
// Function WeaponEquipmentSlotWidget.WeaponEquipmentSlotWidget_C.OnReleased__DelegateSignature
struct UWeaponEquipmentSlotWidget_C_OnReleased__DelegateSignature_Params
{
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"34903638+ColdStartEnthusiast@users.noreply.github.com"
] | 34903638+ColdStartEnthusiast@users.noreply.github.com |
3d4df29ce10f64949652539c76e6d6a32baae6fd | 8d291265155434ea3ddda7276a343911e3c1f7b1 | /Lecture 26/generic_graph.cpp | f926e314c2915e3564059e0c3e0bce493ccb332e | [] | no_license | sanjeetboora/Launchpad-Pitampura-10June | 497a1d6c85ca7c3c7797416be2f134eefff72960 | 73a2b3d347dc2aa24eabb5871e9cd132d6715ee7 | refs/heads/master | 2020-06-07T07:40:55.563462 | 2019-08-01T12:34:11 | 2019-08-01T12:34:11 | 192,963,671 | 1 | 0 | null | 2019-08-01T11:32:50 | 2019-06-20T17:45:55 | C++ | UTF-8 | C++ | false | false | 2,493 | cpp | #include <iostream>
#include <list>
#include <map>
#include <queue>
#include <climits>
using namespace std;
template <typename T>
class Graph{
map<T, list<T> > adjList;
void dfsHelper(T node,map<T,bool> &visited){
cout<<node<<" ";
visited[node] = true;
for(auto neighbour:adjList[node]){
if(!visited[neighbour]){
dfsHelper(neighbour,visited);
}
}
}
public:
void addEdge(T u,T v, bool bidir = true){
adjList[u].push_back(v);
if(bidir){
adjList[v].push_back(u);
}
}
void display(){
for(auto vertex:adjList){
cout<<vertex.first<<" -> ";
for(auto neighbour:vertex.second){
cout<<neighbour<<",";
}
cout<<endl;
}
}
void bfs(T src){
queue<T> q;
map<T,bool> visited;
q.push(src);
visited[src] = true;
while(!q.empty()){
T temp = q.front();
cout<<temp<<" ";
q.pop();
for(auto neighbour:adjList[temp]){
if(!visited[neighbour]){
q.push(neighbour);
visited[neighbour] = true;
}
}
}
cout<<endl;
}
void bfs_shortestPath(T src){
queue<T> q;
map<T,int> dist;
for(auto vertex:adjList){
dist[vertex.first] = INT_MAX;
}
dist[src] = 0;
q.push(src);
while(!q.empty()){
T temp = q.front();
q.pop();
for(auto neighbour:adjList[temp]){
if(dist[neighbour]==INT_MAX){
dist[neighbour] = dist[temp] + 1;
q.push(neighbour);
}
}
}
for(auto vertex:adjList){
cout<<"Distance of "<<vertex.first<<" from "<<src<<" is "<<dist[vertex.first]<<endl;
}
}
void dfs(T src){
map<T,bool> visited;
dfsHelper(src,visited);
cout<<endl;
}
bool isCyclicBFS(T src){
queue<T> q;
map<T,bool> visited;
map<T,T> parent;
q.push(src);
visited[src] = true;
parent[src] = src;
while(!q.empty()){
T temp = q.front();
q.pop();
for(auto neighbour:adjList[temp]){
if(visited[neighbour] and parent[temp] != neighbour){
return true;
}else if(!visited[neighbour]){
q.push(neighbour);
visited[neighbour] = true;
parent[neighbour] = temp;
}
}
}
return false;
}
};
int main(){
// Graph<int> g;
// g.addEdge(1,2);
// g.addEdge(1,3);
// g.addEdge(1,5);
// g.addEdge(2,3);
// g.addEdge(3,4);
// g.addEdge(4,5);
// g.display();
// g.bfs(1);
Graph<int> g;
g.addEdge(1,2);
g.addEdge(1,3);
g.addEdge(1,4);
g.addEdge(2,3);
g.addEdge(3,5);
g.addEdge(4,5);
g.addEdge(5,6);
cout<<g.isCyclicBFS(1)<<endl;
// g.display();
// g.bfs_shortestPath(1);
// g.dfs(1);
return 0;
}
| [
"pranav.khandelwal@lifcare.in"
] | pranav.khandelwal@lifcare.in |
c5f4bb56552416aa9db9d99b7896dc7fc227a559 | 7d7301514d34006d19b2775ae4f967a299299ed6 | /leetcode/tree/958.isCompleteTree.cpp | c812006aea9ade2ae62a7d4210abb205c6326bfc | [] | no_license | xmlb88/algorithm | ae83ff0e478ea01f37bc686de14f7d009d45731b | cf02d9099569e2638e60029b89fd7b384f3c1a68 | refs/heads/master | 2023-06-16T00:21:27.922428 | 2021-07-17T03:46:50 | 2021-07-17T03:46:50 | 293,984,271 | 1 | 0 | null | 2020-12-02T09:08:28 | 2020-09-09T02:44:20 | C++ | UTF-8 | C++ | false | false | 917 | cpp | #include <iostream>
#include <vector>
#include <cmath>
#include <queue>
#include "treeNode.h"
using namespace std;
bool isCompleteTree(TreeNode* root) {
queue<TreeNode*> q;
q.push(root);
int level = 0;
while (!q.empty()) {
int size = q.size();
bool has_null = false, has_next = false;
for (int i = 0; i < size; ++i) {
TreeNode* node = q.front();
q.pop();
if ((node -> left || node -> right) && has_null) return false;
if (!node -> left && node -> right) return false;
if (!node -> left || !node -> right) has_null = true;
if (node -> left || node -> right) has_next = true;
if (node -> left) q.push(node -> left);
if (node -> right) q.push(node -> right);
}
if (has_next && size != pow(2, level)) return false;
++level;
}
return true;
}
// TODO: | [
"xmlb@gmail.com"
] | xmlb@gmail.com |
b81b6d3f967d2b98682cc6784fa228a8ade24925 | 957a80ea22c5abb4f4670b250d55534d9db99108 | /src/library/compiler/reduce_arity.h | 75978588d42e0bc25ddd1e2328c2afef80b91f4f | [
"Apache-2.0"
] | permissive | GaloisInc/lean | aa1e64d604051e602fcf4610061314b9a37ab8cd | f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0 | refs/heads/master | 2020-06-15T06:35:09.807322 | 2017-09-05T15:13:07 | 2017-09-05T15:13:07 | 75,319,626 | 2 | 1 | Apache-2.0 | 2018-10-11T20:36:04 | 2016-12-01T18:15:04 | C++ | UTF-8 | C++ | false | false | 750 | h | /*
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#pragma once
#include "kernel/environment.h"
#include "library/compiler/procedure.h"
namespace lean {
/** \brief Try to reduce the arity of auxiliary declarations in procs.
It assumes all but the last entry are auxiliary declarations.
\remark This procedure assumes rec_fn_macro has already been eliminated.
The procedure erase_irrelevant can be used to accomplish that.
\remark This step does not rely on type information. That is,
the input expressions don't need to be type checkable. */
void reduce_arity(environment const & env, buffer<procedure> & procs);
}
| [
"leonardo@microsoft.com"
] | leonardo@microsoft.com |
482f4cae26b6ce88e30e5e850f9e4ff338c5e735 | f8770867dcbe75666fdbd68194d88c75935ab5a6 | /proves3/proves3/Point.h | c13f7195d78ed4e608cbd080e2f8142e648fbbc3 | [] | no_license | weprikjm/Point2D | f85c4005d8e4da5f716aa851ef1f3cf9c3833fc3 | afd6101d1d486c821eaeb0da3d251c4aaf9aca29 | refs/heads/master | 2020-06-10T17:06:17.693876 | 2015-10-05T15:55:39 | 2015-10-05T15:55:39 | 43,690,942 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 310 | h |
class Point
{
public:
int x,y;
Point operator=(Point& p);
bool operator==(Point& p)const;
bool operator!=(Point& p)const;
Point operator+=(Point& p);
Point operator-=(Point& p);
Point operator+(Point& p)const;
Point operator-(Point& p)const;
bool IsZero()const;
void SetZero();
void Negate();
}; | [
"ruben.idigora@gmail.com"
] | ruben.idigora@gmail.com |
e8d9645ec32dac680bb42dfcaeb42ee8c1d50db7 | 7f62f204ffde7fed9c1cb69e2bd44de9203f14c8 | /DboServer/Server/GameServer/BotAiCondition_ScanTarget.cpp | eeee73f2a1ef79a614ac589ab1ef799254fc5705 | [] | no_license | 4l3dx/DBOGLOBAL | 9853c49f19882d3de10b5ca849ba53b44ab81a0c | c5828b24e99c649ae6a2953471ae57a653395ca2 | refs/heads/master | 2022-05-28T08:57:10.293378 | 2020-05-01T00:41:08 | 2020-05-01T00:41:08 | 259,094,679 | 3 | 3 | null | 2020-04-29T17:06:22 | 2020-04-26T17:43:08 | null | UTF-8 | C++ | false | false | 1,914 | cpp | #include "stdafx.h"
#include "BotAiCondition_ScanTarget.h"
#include "ObjectManager.h"
#include "char.h"
#include "NtlPacketGU.h"
CBotAiCondition_ScanTarget::CBotAiCondition_ScanTarget(CNpc* pBot, CBotAiCondition_ScanTarget::eBOTAI_SMARTSCAN_TYPE eSmartScantype, BYTE bySmartLevel)
:CBotAiCondition(pBot, BOTCONTROL_CONDITION_SCAN_TARGET, "BOTCONTROL_CONDITION_SCAN_TARGET")
{
m_dwTime = 0;
m_bySmartScantype = (BYTE)eSmartScantype;
m_bySmartLevel = bySmartLevel;
}
CBotAiCondition_ScanTarget::~CBotAiCondition_ScanTarget()
{
}
void CBotAiCondition_ScanTarget::OnEnter()
{
this->m_dwTime = 1000;
}
int CBotAiCondition_ScanTarget::OnUpdate(DWORD dwTickDiff, float fMultiple)
{
m_dwTime = UnsignedSafeIncrease<DWORD>(m_dwTime, dwTickDiff);
if (m_dwTime >= 1000)
{
m_dwTime = 0;
if (ScanTarget(m_bySmartScantype == BOTAI_SMARTSCAN_UNDER))
return CHANGED;
}
return m_status;
}
bool CBotAiCondition_ScanTarget::ScanTarget(bool bSmartOffence)
{
HOBJECT hTarget = GetBot()->ConsiderScanTarget(INVALID_WORD);
if (hTarget == INVALID_HOBJECT)
return false;
CCharacter* pTargetBot = g_pObjectManager->GetChar(hTarget);
if (!pTargetBot)
return false;
if (bSmartOffence)
{
if (GetBot()->GetLevel() - m_bySmartLevel < pTargetBot->GetLevel())
return false;
}
if (GetBot()->GetTargetListManager()->GetAggroCount() == 0)
{
pTargetBot->ResetMeAttackBot();
CNtlPacket packet(sizeof(sGU_BOT_BOTCAUTION_NFY));
sGU_BOT_BOTCAUTION_NFY* res = (sGU_BOT_BOTCAUTION_NFY *)packet.GetPacketData();
res->wOpCode = GU_BOT_BOTCAUTION_NFY;
res->hBot = GetBot()->GetID();
packet.SetPacketLen(sizeof(sGU_BOT_BOTCAUTION_NFY));
GetBot()->Broadcast(&packet);
}
DWORD dwAggroPoint = GetBot()->GetTbldat()->wBasic_Aggro_Point + 1;
GetBot()->GetTargetListManager()->AddAggro(hTarget, dwAggroPoint, false);
GetBot()->GetBotController()->AddControlState_Fight(hTarget);
return true;
} | [
"64261665+dboguser@users.noreply.github.com"
] | 64261665+dboguser@users.noreply.github.com |
85b4638ab6121c25772d841d1e885976c205db22 | 144138ef6a25005fba1ff74ce20d490bbc5edc97 | /examples/node_modules/canvas/src/Canvas.h | f5b3740aa3c49de797fe0ddc58a7f93e66e036f1 | [
"MIT",
"WTFPL",
"BSD-2-Clause"
] | permissive | tmcw/k-means | 642965268ead937f10f3bb04b530b62cdc4e0375 | 7b8c4e40354ba46c381d1346c65bb4e647ba7604 | refs/heads/master | 2021-01-10T21:27:14.320170 | 2015-05-19T02:19:49 | 2015-05-19T02:19:49 | 5,286,199 | 15 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 2,269 | h |
//
// Canvas.h
//
// Copyright (c) 2010 LearnBoost <tj@learnboost.com>
//
#ifndef __NODE_CANVAS_H__
#define __NODE_CANVAS_H__
#include <v8.h>
#include <node.h>
#include <node_object_wrap.h>
#include <node_version.h>
#include <cairo/cairo.h>
using namespace v8;
using namespace node;
/*
* Maxmimum states per context.
* TODO: remove/resize
*/
#ifndef CANVAS_MAX_STATES
#define CANVAS_MAX_STATES 64
#endif
/*
* Canvas types.
*/
typedef enum {
CANVAS_TYPE_IMAGE,
CANVAS_TYPE_PDF
} canvas_type_t;
/*
* Canvas.
*/
class Canvas: public node::ObjectWrap {
public:
int width;
int height;
canvas_type_t type;
static Persistent<FunctionTemplate> constructor;
static void Initialize(Handle<Object> target);
static Handle<Value> New(const Arguments &args);
static Handle<Value> ToBuffer(const Arguments &args);
static Handle<Value> GetType(Local<String> prop, const AccessorInfo &info);
static Handle<Value> GetWidth(Local<String> prop, const AccessorInfo &info);
static Handle<Value> GetHeight(Local<String> prop, const AccessorInfo &info);
static void SetWidth(Local<String> prop, Local<Value> val, const AccessorInfo &info);
static void SetHeight(Local<String> prop, Local<Value> val, const AccessorInfo &info);
static Handle<Value> StreamPNGSync(const Arguments &args);
static Handle<Value> StreamJPEGSync(const Arguments &args);
static Local<Value> Error(cairo_status_t status);
#if NODE_VERSION_AT_LEAST(0, 6, 0)
static void ToBufferAsync(uv_work_t *req);
static void ToBufferAsyncAfter(uv_work_t *req);
#else
static
#if NODE_VERSION_AT_LEAST(0, 5, 4)
void
#else
int
#endif
EIO_ToBuffer(eio_req *req);
static int EIO_AfterToBuffer(eio_req *req);
#endif
inline bool isPDF(){ return CANVAS_TYPE_PDF == type; }
inline cairo_surface_t *surface(){ return _surface; }
inline void *closure(){ return _closure; }
inline uint8_t *data(){ return cairo_image_surface_get_data(_surface); }
inline int stride(){ return cairo_image_surface_get_stride(_surface); }
Canvas(int width, int height, canvas_type_t type);
void resurface(Handle<Object> canvas);
private:
~Canvas();
cairo_surface_t *_surface;
void *_closure;
};
#endif
| [
"tom@macwright.org"
] | tom@macwright.org |
c4f3fbda381fbb580302b53e1f581da67aece6a8 | b920e8e33d1ba49fbf04c619608f230f2ea6a23f | /nurbs2.cpp | 5108a4fea66ced4d78a4cf58ae873f8358056d09 | [] | no_license | qiuyingyue/project | 1ae349d70bf77edd0a20fdafb3d74419c70dbfe8 | 909d8498cf4e4fe2a3ef26b275180858a7fe5b67 | refs/heads/master | 2020-12-25T17:03:41.467017 | 2016-01-11T15:05:25 | 2016-01-11T15:05:25 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 3,624 | cpp |
//
// nurbs2.cpp
// opengltest
//
// Created by Victor Young on 1/10/16.
// Copyright (c) 2016 Victor Young. All rights reserved.
//
//see http://www.glprogramming.com/red/chapter12.html
#include"nurbs.h"
#include <stdlib.h>
#include"CGdrive.h"
GLfloat ctrlpoints[5][5][3] =
{ { { -5, 0, 0 }, { -3, 0, 0 }, {-1, 0, 0 }, { 1, 0, 0 }, { 3, 0, 0 } },
{ { -5, 0, -1 }, { -3, 0, -1 },{ -1, 0, -1 },{ 1, 0, -1 }, { 3, 0, -1 } },
{ { -5, 0, -2 }, { -3, 0, -2 },{ -1, 0, -2 },{ 1, 0, -2 }, { 3, 0, -2 } },
{ { -5, 0, -3 }, { -3, 0, -3 },{ -1, 0, -3 },{ 1, 0, -3 }, { 3, 0, -3 } },
{ { -5, 0, -4 }, { -3, 0, -4 },{ -1, 0, -4 },{ 1, 0, -4 }, { 3, 0, -4 } } };//
bool showPoints = false;
float initheta = 0;
GLUnurbsObj *theNurb;
void init_surface(void)
{
int u, v;
/* for (u = 0; u < 4; u++) {
for (v = 0; v < 4; v++) {
ctlpoints[u][v][0] = 2.0*((GLfloat)u - 1.5);
ctlpoints[u][v][1] = 2.0*((GLfloat)v - 1.5);
if ( (u == 1 || u == 2) && (v == 1 || v == 2))
ctlpoints[u][v][2] = 3.0;
else
ctlpoints[u][v][2] = -3.0;
}
}*/
//¿ØÖƵã
}
void wave(void){
initheta += 0.005;
float ph1 = 3.1415 /4; float ph2 = 3.1415 / 6;
//printf("%lf,", err);
if (initheta > 3.1415*2)initheta = 0;
for (int i = 0; i < 5; i++){
for (int j = 0; j < 5; j++){
float ratio = j / 5.0*1.5;
srand(time(0)*i*j);
float err = ((float)rand() / RAND_MAX);
ctrlpoints[i][j][1] = sin(initheta + ph1 *j + ph2*i + err)*(1+cos(initheta + ph1 *j + ph2*i + err))*ratio;
}
}
}
void initNurbs(void)
{
GLfloat mat_diffuse[] = { 0.7, 0.7, 0.7, 1.0 };
GLfloat mat_specular[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat mat_shininess[] = { 100.0 };
glClearColor (0.0, 0.0, 0.0, 0.0);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_DEPTH_TEST);
glEnable(GL_AUTO_NORMAL);
glEnable(GL_NORMALIZE);
init_surface();
theNurb = gluNewNurbsRenderer();
gluNurbsProperty(theNurb, GLU_SAMPLING_TOLERANCE, 25.0);
gluNurbsProperty(theNurb, GLU_DISPLAY_MODE, GLU_FILL);
//gluNurbsCallback(theNurb, GLU_ERROR,
// (GLvoid (*)()) nurbsError);
}
void drawNurb(void)
{
//GLfloat knots[6] = {0.0, 0.0, 0.0, 1.0, 1.0, 1.0};
GLfloat knots[10] = { 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0 };
int i, j;
//glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glRotatef(90.0, 1.,0.,0.);
//glTranslatef(5.0,0, 5.0);
glScalef (0.2, 0.2, 0.2);
gluBeginSurface(theNurb);
/* gluNurbsSurface(theNurb,
8, knots, 8, knots,
4 * 3, 3, &ctlpoints[0][0][0],
4, 4, GL_MAP2_VERTEX_3);*/
gluNurbsSurface(theNurb, 10, knots, 10, knots, 5 * 3, 3, &ctrlpoints[0][0][0], 5, 5, GL_MAP2_VERTEX_3);
//gluNurbsSurface(theNurb, 6, knots, 6, knots, 3 * 3, 3, &ctrlpoints[0][0][0], 3, 3, GL_MAP2_VERTEX_3);
gluEndSurface(theNurb);
if (showPoints) {
glPointSize(5.0);
glDisable(GL_LIGHTING);
glColor3f(1.0, 1.0, 0.0);
glBegin(GL_POINTS);
for (i = 0; i <5; i++) {
for (j = 0; j < 5; j++) {
glVertex3f(ctrlpoints[i][j][0],
ctrlpoints[i][j][1], ctrlpoints[i][j][2]);
}
}
glEnd();
glEnable(GL_LIGHTING);
}
glPopMatrix();
}
| [
"842752622@qq.com"
] | 842752622@qq.com |
943ffac4260a69a32c3d8c3900b5c09571053eec | 68113737651a9856a703860e8e81e4c9da5073cf | /Chess/Camera.h | 6c3a18df25145cbba43db7ea34d09667bba634ae | [] | no_license | stefano9o/chess_game | 2983dbfc30283d025e42f34eb017b9d46b8bdb3a | e00cbbe1654a24fc056290ad8f202de49e4b9bdb | refs/heads/master | 2021-01-17T23:55:30.448921 | 2017-03-13T20:08:32 | 2017-03-13T20:08:32 | 84,234,777 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,133 | h |
#ifndef CAMERA_H
#define CAMERA_H
// Std. Includes
#include <vector>
// GL Includes
#include <GL\glew.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
// Defines several possible options for camera movement. Used as abstraction to stay away from window-system specific input methods
enum Camera_Movement {
FORWARD,
BACKWARD,
LEFT,
RIGHT
};
// An abstract camera class that processes input and calculates the corresponding Eular Angles, Vectors and Matrices for use in OpenGL
class Camera{
public:
// Constructor with vectors
Camera(glm::vec3 position = glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f), GLfloat yaw = -90.0f, GLfloat pitch = 0.0f);
// Constructor with scalar values
Camera(GLfloat posX, GLfloat posY, GLfloat posZ, GLfloat upX, GLfloat upY, GLfloat upZ, GLfloat yaw, GLfloat pitch);
// Returns the view matrix calculated using Eular Angles and the LookAt Matrix
glm::mat4 getViewMatrix();
// Processes input received from any keyboard-like input system. Accepts input parameter in the form of camera defined ENUM (to abstract it from windowing systems)
void processKeyboard(Camera_Movement direction, GLfloat deltaTime);
// Processes input received from a mouse input system. Expects the offset value in both the x and y direction.
void processMouseMovement(GLfloat xoffset, GLfloat yoffset, GLboolean constrainPitch = true);
// Processes input received from a mouse scroll-wheel event. Only requires input on the vertical wheel-axis
void processMouseScroll(GLfloat yoffset);
GLfloat getZoom();
glm::vec3 getPosition();
void updateCamera(glm::vec3 position = glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f), GLfloat yaw = -90.0f, GLfloat pitch = 0.0f);
private:
// Calculates the front vector from the Camera's (updated) Eular Angles
void updateCameraVectors();
// Camera Attributes
glm::vec3 position;
glm::vec3 front;
glm::vec3 up;
glm::vec3 right;
glm::vec3 worldUp;
// Eular Angles
GLfloat yaw;
GLfloat pitch;
// Camera options
GLfloat movementSpeed;
GLfloat mouseSensitivity;
GLfloat zoom;
};
#endif | [
"stefano.galeano@gmail.com"
] | stefano.galeano@gmail.com |
c995c4f4a54b9abf6f68b9caef72e775fd282752 | 6d6ff3721a863e4fb980603f7045fedf43673af5 | /include/wdp/Depth.h | 97a0ae72c73d8b706b8ab916864bc1d94fb5c3b9 | [
"BSL-1.0"
] | permissive | lewis-revill/wheele-depth-perception | 833f31ed42fb2b67335b8fd99e833779a2832c6d | 9f92df089847e8d5b412dc50f21f301a68324312 | refs/heads/master | 2022-08-29T09:37:57.474273 | 2020-05-30T17:32:21 | 2020-05-30T17:32:21 | 263,041,932 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,839 | h | //===-------- Depth.h - Depth Perception Algorithms -------------*- C++ -*-===//
//
// Copyright © 2020 Lewis Revill
//
// Use, modification and distribution are subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE.txt or copy at
// https://www.boost.org/LICENSE_1_0.txt).
//
// SPDX-License-Identifier: BSL-1.0
//
//===----------------------------------------------------------------------===//
//
// This file defines functions which implement extraction of depth information
// from stereo images.
//
//===----------------------------------------------------------------------===//
#ifndef WDP_DEPTH_H
#define WDP_DEPTH_H
#include "Coordinates.h"
#include "Search.h"
#include <cmath>
namespace wdp {
struct DepthParameters {
double FocalLength;
double PixelScale;
double CameraDisplacement;
};
template <typename LHSImage, typename RHSImage>
double getDepth(const LHSImage &LHSImg, const RHSImage &RHSImg, Coordinates C,
const SearchParameters &SearchParams,
const DepthParameters &DepthParams) {
// LHSImg and RHSImg input arguments must be 2D images.
boost::function_requires<boost::gil::RandomAccess2DImageConcept<LHSImage>>();
boost::function_requires<boost::gil::RandomAccess2DImageConcept<RHSImage>>();
const Offset CentreOffset = getCentreOffset(LHSImg, C);
double TrueXCentreOffset = CentreOffset.x * DepthParams.PixelScale;
double Hypotenuse = sqrt(DepthParams.FocalLength * DepthParams.FocalLength +
TrueXCentreOffset * TrueXCentreOffset);
const Offset O = getOffset(LHSImg, RHSImg, C, SearchParams);
double TrueXOffset = -O.x * DepthParams.PixelScale;
double ScaleFactor = DepthParams.CameraDisplacement / TrueXOffset;
return ScaleFactor * Hypotenuse;
}
} // namespace wdp
#endif // WDP_DEPTH_H
| [
"lewis.revill@embecosm.com"
] | lewis.revill@embecosm.com |
472c889d379e6909ea101e25377f0b852f79a430 | f981bca58ad38cb0d79eff19f9e56fb58a5c8efe | /Stepper1/Stepper1.ino | c4554b0faeaece7648c969db2b1ef544fc65f8a7 | [] | no_license | andresmonsalvo/Arduino | 5b57487aeaa8506aa59416d6a56caf61c92a81d2 | f999b2744cd4114ca2d389496a0cf0911011b977 | refs/heads/main | 2023-05-24T12:11:14.439127 | 2021-06-02T00:27:05 | 2021-06-02T00:27:05 | 369,952,662 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 352 | ino | #include <Stepper.h>
int stepsPerRevolution=2048;
int motSpeed=3;
int dt=500;
Stepper myStepper(stepsPerRevolution, 8,10,9,11);
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
myStepper.setSpeed(motSpeed);
}
void loop() {
myStepper.step(stepsPerRevolution);
delay(dt);
myStepper.step(-stepsPerRevolution);
delay(dt);
}
| [
"andresmonsalvo@yahoo.ca"
] | andresmonsalvo@yahoo.ca |
de9b1777207cbdb3fe3e0b4d2bfd789680d545fd | a949ca5fd781f526ad292992fd47f4b8bd973d9e | /RAVULA/ARRAY/1.LINEAR SEARCH.cpp | b4d278a342700662fbb84b24ac9b5c268e70443d | [
"MIT"
] | permissive | scortier/Complete-DSA-Collection | 8f20e56b18e4a552aebd04964e8365e01eba5433 | 925a5cb148d9addcb32192fe676be76bfb2915c7 | refs/heads/main | 2023-05-14T14:24:21.678887 | 2021-06-06T18:59:01 | 2021-06-06T18:59:01 | 307,963,617 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,533 | cpp | // QUARANTINE DAYS..;)
#include <bits/stdc++.h>
using namespace std;
#define endl "\n"
#define test long long int tt;cin>>tt;while(tt--)
#define rep(i,a,b) for(long long int i=a;i<b;i++)
#define rev(i,a,b) for(long long int i=b-1;i>=a;i--)
#define reep(i,a,b) for(long long int i=a;i<=b;i++)
#define ll long long int
#define pb push_back
#define mp make_pair
#define f first
#define s second
#define MOD 1000000007
#define PI acos(-1.0)
#define assign(x,val) memset(x,val,sizeof(x))
#define prec(val, dig) fixed << setprecision(dig) << val
#define vec vector < ll >
#define vecpi vector < pair < ll, ll > >
#define pi pair < ll , ll >
#define lower(str) transform(str.begin(), str.end(), str.begin(), ::tolower);
#define upper(str) transform(str.begin(), str.end(), str.begin(), ::toupper);
#define mk(arr,n,type) type *arr=new type[n];
const int maxm = 2e6 + 10;
void fast() {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
/**********====================########################=================***********/
// TC:O(N)
// SC:O(N) due to array
int linearSearch(int a[], int n, int target)
{
for (int i = 0; i < n; i++)
{
if (a[i] == target)
return i;
}
return -1;
}
int32_t main()
{
fast();
int n, t; cin >> n >> t;
int arr[n];
rep(i, 0, n) cin >> arr[i];
cout << linearSearch(arr, n, t);
return 0;
}
| [
"onlytoaditya@gmail.com"
] | onlytoaditya@gmail.com |
82f57646a4c7f09646be0abcecfbf5fd2e13b246 | 9607d81d6126b04c75e197440a15c325a69d97a1 | /TradingSDI/TradingSDI/ADD_overview.cpp | 3f4a2696b880f9a212b9fca94ec7383f79751fcf | [] | no_license | FX-Misc/prasantsingh-trading | 0f6ef3ddac2fcb65002d6c1031ea0557c1155d9a | 755670edd6f964915a4f8c3675f2274b70d01c50 | refs/heads/master | 2021-05-05T17:18:47.658007 | 2017-01-19T11:06:16 | 2017-01-19T11:06:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,387 | cpp | // ADD_overview.cpp : implementation file
//
#include "stdafx.h"
#include "TradingSDI.h"
#include "ADD_overview.h"
#include "afxdialogex.h"
#include "tabControl.h"
IMPLEMENT_DYNAMIC(ADD_overview, CDialogEx)
ADD_overview::ADD_overview(CWnd* pParent /*=NULL*/)
: CDialogEx(ADD_overview::IDD, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
m_bInit = false;
p1=NULL;
p2=NULL;
p3=NULL;
p4=NULL;
}
ADD_overview::~ADD_overview()
{
}
void ADD_overview::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_TAB1, m_ctrlTAB);
}
BEGIN_MESSAGE_MAP(ADD_overview, CDialogEx)
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
//}}AFX_MSG_MAP
// ON_WM_MOVE()
ON_WM_CLOSE()
ON_WM_DESTROY()
//ON_WM_SHOWWINDOW()
ON_NOTIFY(NM_CLICK, IDC_TAB1, &ADD_overview::OnNMClickTab1)
END_MESSAGE_MAP()
BOOL ADD_overview::OnInitDialog()
{
CDialogEx::OnInitDialog();
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
//// TODO: Add extra initialization here
//p1 = new overview();
//p1->Create(IDD_TAB1,m_ctrlTAB.GetWindow(IDD_TAB1));
//p2 = new Tab2();
//p2->Create(IDD_TAB2,m_ctrlTAB.GetWindow(IDD_TAB2));
//p3= new tab3();
//p3->Create(IDD_TAB3,m_ctrlTAB.GetWindow(IDD_TAB3));
//p4= new tab4();
//p4->Create(IDD_TAB4,m_ctrlTAB.GetWindow(IDD_TAB4));
// m_ctrlTAB.AddTabPane(L"OverView",p1);
//m_ctrlTAB.AddTabPane(L"TradeCheck",p2);
//m_ctrlTAB.AddTabPane(L"TradeWiseAnalysis",p3);
//m_ctrlTAB.AddTabPane(L"StandingPosition",p4);
//// TODO: Add extra initialization here
m_ctrlTAB.InitDialogs();
m_ctrlTAB.InsertItem(0,L"OverView");
m_ctrlTAB.InsertItem(1,L"TradeCheck");
m_ctrlTAB.InsertItem(2,L"TradeWiseAnalysis");
m_ctrlTAB.InsertItem(3,L"StandingPosition");
//m_ctrlTAB.ActivateTabDialogs();
return TRUE; // return TRUE unless you set the focus to a control
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void ADD_overview::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialogEx::OnPaint();
}
}
// The system calls this function to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR ADD_overview::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
//void ADD_overview::OnMove(int x, int y)
//{
// m_ctrlTAB.OnMove(x,y);
//}
//void ADD_overview::OnShowWindow(BOOL bShow, UINT nStatus)
//{
// m_ctrlTAB.SetDefaultPane(1);
//
//}
// ADD_overview message handlers
void ADD_overview::OnClose()
{
// TODO: Add your message handler code here and/or call default
m_ctrlTAB.OnClose();
CDialogEx::OnClose();
}
BOOL ADD_overview::PreTranslateMessage(MSG* pMsg)
{
// TODO: Add your specialized code here and/or call the base class
return CDialogEx::PreTranslateMessage(pMsg);
}
void ADD_overview::OnDestroy()
{
p1->OnClose();
p2->OnClose();
p3->OnClose();
p4->OnClose();
delete(p3);
delete(p4);
//m_ctrlTAB.OnDestroy();
CDialogEx::OnDestroy();
// TODO: Add your message handler code here
}
//void ADD_overview::OnShowWindow(BOOL bShow, UINT nStatus)
//{
// CDialogEx::OnShowWindow(bShow, nStatus);
//
// // TODO: Add your message handler code here
//}
void ADD_overview::OnNMClickTab1(NMHDR *pNMHDR, LRESULT *pResult)
{
// TODO: Add your control notification handler code here
//p1->ShowWindow(SW_SHOW);
*pResult = 0;
} | [
"prasantsingh01@hotmail.com"
] | prasantsingh01@hotmail.com |
1a7a4b42dc989d21ffab293af44a63c9260fe8ee | 379d9b87abaa7781d3af96b0c295f106ab18c0d0 | /vector.cpp | 4f4602ace9af555113c930c0c80e6f06fe7b5363 | [] | no_license | JkUzumaki/C-_02_2020 | b2417737b74b5c662e3864699f23dfef797dfd4c | 376961b114d0834b92cdeb9e39cac17f84e3687a | refs/heads/master | 2020-12-28T18:39:52.629901 | 2020-02-28T07:39:49 | 2020-02-28T07:39:49 | 238,444,254 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,688 | cpp | // Self implementation of
// the Vector Class in C++
#include <bits/stdc++.h>
using namespace std;
class vectorClass {
// arr is the integer pointer
// which stores the address of our vector
int* arr;
// capacity is the total storage
// capacity of the vector
int capacity;
// current is the number of elements
// currently present in the vector
int current;
public:
// Default constructor to initialise
// an initial capacity of 1 element and
// allocating storage using dynamic allocation
vectorClass()
{
arr = new int[1];
capacity = 1;
current = 0;
}
// Function to add an element at the last
void push(int data)
{
// if the number of elements is equal to the capacity,
// that means we don't have space
// to accommodate more elements.
// We need to double the capacity
if (current == capacity) {
int* temp = new int[2 * capacity];
// copying old array elements to new array
for (int i = 0; i < capacity; i++) {
temp[i] = arr[i];
}
// deleting previous array
delete[] arr;
capacity *= 2;
arr = temp;
}
// Inserting data
arr[current] = data;
current++;
}
// function to add element at any index
void push(int data, int index)
{
// if index is equal to capacity then this
// function is same as push defined above
if (index == capacity)
push(data);
else
arr[index] = data;
}
// function to extract element at any index
int get(int index)
{
// if index is within the range
if (index < current)
return arr[index];
}
// function to delete last element
void pop()
{
current--;
}
// function to get size of the vector
int size()
{
return current;
}
// function to get capacity of the vector
int getcapacity()
{
return capacity;
}
// function to print array elements
void print()
{
for (int i = 0; i < current; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
};
// Driver code
int main()
{
vectorClass v;
v.push(10);
v.push(20);
v.push(30);
v.push(40);
v.push(50);
cout << "Vector size : "
<< v.size() << endl;
cout << "Vector capacity : "
<< v.getcapacity() << endl;
cout << "Vector elements : ";
v.print();
v.push(100, 1);
cout << "\nAfter updating 1st index"
<< endl;
cout << "Vector elements : ";
v.print();
cout << "Element at 1st index : "
<< v.get(1) << endl;
v.pop();
cout << "\nAfter deleting last element"
<< endl;
cout << "Vector size : "
<< v.size() << endl;
cout << "Vector capacity : "
<< v.getcapacity() << endl;
cout << "Vector elements : ";
v.print();
return 0;
}
| [
"jaikumar.1415@yahoo.com"
] | jaikumar.1415@yahoo.com |
1a3b60a5efab91fa77b99e409904690a655762a9 | 28dba754ddf8211d754dd4a6b0704bbedb2bd373 | /Codeforces/ProblemSet/33D.cpp | 41502b6f254c683e85fa14a302d9a088e8d533f3 | [] | no_license | zjsxzy/algo | 599354679bd72ef20c724bb50b42fce65ceab76f | a84494969952f981bfdc38003f7269e5c80a142e | refs/heads/master | 2023-08-31T17:00:53.393421 | 2023-08-19T14:20:31 | 2023-08-19T14:20:31 | 10,140,040 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,251 | cpp | /*
* Author : Yang Zhang
*/
#include <map>
#include <set>
#include <list>
#include <cmath>
#include <queue>
#include <stack>
#include <bitset>
#include <vector>
#include <cstdio>
#include <string>
#include <sstream>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define PB push_back
#define MP make_pair
#define SZ(v) ((int)(v).size())
#define abs(x) ((x) > 0 ? (x) : -(x))
typedef long long LL;
struct Point {
LL x, y;
}p[1111];
struct Circle {
LL x, y, r;
}c[1111];
bool adj[1005][1005];
int n, m, k;
int main() {
freopen("in", "r", stdin);
cin >> n >> m >> k;
for (int i = 0; i < n; i++)
cin >> p[i].x >> p[i].y;
for (int i = 0; i < m; i++)
cin >> c[i].r >> c[i].x >> c[i].y;
memset(adj, 0, sizeof(adj));
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
LL dx = (p[i].x - c[j].x) * (p[i].x - c[j].x);
LL dy = (p[i].y - c[j].y) * (p[i].y - c[j].y);
if (dx + dy < c[j].r * c[j].r)
adj[i][j] = true;
}
for (int i = 0; i < k; i++) {
int a, b;
cin >> a >> b;
a--; b--;
int ret = 0;
for (int j = 0; j < m; j++)
ret += adj[a][j] ^ adj[b][j];
cout << ret << endl;
}
return 0;
}
| [
"zjsxzy@gmail.com"
] | zjsxzy@gmail.com |
5aa5904da88ef161fa340740b3d2428bf52a864a | 8295c24e35f48205a308a64a216e673790be0f21 | /01cpp/day1_2.cpp | a8460ced96fde7836a367c43b59866f19cdd0844 | [] | no_license | kev-zheng/advent2016 | e6da8e13a492735079c1007f3dcda4ddd456717b | 56d6a3b6c818948dd1690b6c513ed1df63b9efd9 | refs/heads/master | 2021-01-12T07:31:37.981359 | 2016-12-29T20:00:51 | 2016-12-29T20:00:51 | 76,972,137 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,826 | cpp | #include <iostream>
#include <string>
#include <vector>
#include <typeinfo>
#include <cmath>
using namespace std;
int main(){
string instructions;
vector <char> directions;
vector <int> distances;
int currentX = 0;
int currentY = 0;
int currentDirection = 1;
int distance;
int totalDistance;
int posX = 1000;
int posY = 1000;
int bunnyDistance;
cout << "Enter data: " << endl;
while(cin >> instructions){
if(instructions[instructions.size()] == ','){
instructions.pop_back();
}
directions.push_back(instructions[0]);
instructions.erase(0,1);
distances.push_back(atoi(instructions.c_str()));
if(cin.peek() == '\n'){
break;
}
}
vector <int> gridLine(2000,0);
vector < vector <int> > grid;
for(int i = 0;i < 2000;i++){
grid.push_back(gridLine);
}
grid[posX][posY] = 1;
for(int i = 0;i < directions.size();i++){
if(directions[i] == 'L'){
currentDirection += 1;
currentDirection %= 4;
}
else if(directions[i] == 'R'){
currentDirection += 3;
currentDirection %= 4;
}
switch(currentDirection){
case 0:
currentX += distances[i];
for(int d = 0;d < distances[i];d++){
posX++;
grid[posX][posY] += 1;
if(grid[posX][posY] == 2){
cout << "crossed " << posX << " " << posY << endl;
bunnyDistance = abs(posX - 1000) + abs(posY - 1000);
cout << bunnyDistance << endl;
break;
}
}
break;
case 1:
currentY += distances[i];
for(int d = 0;d < distances[i];d++){
posY++;
grid[posX][posY] += 1;
if(grid[posX][posY] == 2){
cout << "crossed " << posX << " " << posY << endl;
bunnyDistance = abs(posX - 1000) + abs(posY - 1000);
cout << bunnyDistance << endl;
break;
}
}
break;
case 2:
currentX -= distances[i];
for(int d = 0;d < distances[i];d++){
posX--;
grid[posX][posY] += 1;
if(grid[posX][posY] == 2){
cout << "crossed " << posX << " " << posY << endl;
bunnyDistance = abs(posX - 1000) + abs(posY - 1000);
cout << bunnyDistance << endl;
break;
}
}
break;
case 3:
currentY -= distances[i];
for(int d = 0;d < distances[i];d++){
posY--;
grid[posX][posY] += 1;
if(grid[posX][posY] == 2){
cout << "crossed " << posX << " " << posY << endl;
bunnyDistance = abs(posX - 1000) + abs(posY - 1000);
cout << bunnyDistance << endl;
break;
}
}
break;
}
cout << "X: " << posX << endl;
cout << "Y: " << posY << endl;
}
totalDistance = abs(currentX) + abs(currentY);
cout << "Total Distance: " << totalDistance << " blocks away." << endl;
cout << "Bunny HQ: " << bunnyDistance << " blocks away. " << endl;
return 0;
}
| [
"Kevin@MacBook-Pro-4.local"
] | Kevin@MacBook-Pro-4.local |
f6ec07fcc96903e42e5b71b3a7cd07be0a8669d8 | 97f5bdd44c74c8480bac6ce6d235d1fd284e0316 | /inexlib/ourex/dcmtk/dcmimage/include/dcmtk/dcmimage/dihsvpxt.h | 5ee994ba5f1d41835ff5ab1039f35eb414acc68a | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0",
"BSD-3-Clause",
"BSD-4.3TAHOE",
"xlock",
"IJG",
"LicenseRef-scancode-other-permissive"
] | permissive | gbarrand/wall | b991d7cdf410d9fa8730407e0b56b27c5220e843 | 930a708134b3db2fc77d006d9bd4ccea7ebcdee1 | refs/heads/master | 2021-07-11T15:07:35.453757 | 2018-12-21T12:28:57 | 2018-12-21T12:28:57 | 162,569,670 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,351 | h | /*
*
* Copyright (C) 1996-2010, OFFIS e.V.
* All rights reserved. See COPYRIGHT file for details.
*
* This software and supporting documentation were developed by
*
* OFFIS e.V.
* R&D Division Health
* Escherweg 2
* D-26121 Oldenburg, Germany
*
*
* Module: dcmimage
*
* Author: Joerg Riesmeier
*
* Purpose: DicomHSVPixelTemplate (Header)
*
* Last Update: $Author: barrand $
* Update Date: $Date: 2013/07/02 07:15:11 $
* CVS/RCS Revision: $Revision: 1.2 $
* Status: $State: Exp $
*
* CVS/RCS Log at end of file
*
*/
#ifndef DIHSVPXT_H
#define DIHSVPXT_H
#include "dcmtk/config/osconfig.h"
#include "dcmtk/dcmimage/dicopxt.h"
#include "dcmtk/dcmimgle/diinpx.h" /* gcc 3.4 needs this */
/*---------------------*
* class declaration *
*---------------------*/
/** Template class to handle HSV pixel data
*/
template<class T1, class T2>
class DiHSVPixelTemplate
: public DiColorPixelTemplate<T2>
{
public:
/** constructor
*
** @param docu pointer to DICOM document
* @param pixel pointer to input pixel representation
* @param status reference to status variable
* @param planeSize number of pixels in a plane
* @param bits number of bits per sample
*/
DiHSVPixelTemplate(const DiDocument *docu,
const DiInputPixel *pixel,
EI_Status &status,
const unsigned long planeSize,
const int bits)
: DiColorPixelTemplate<T2>(docu, pixel, 3, status)
{
if ((pixel != NULL) && (this->Count > 0) && (status == EIS_Normal))
convert(OFstatic_cast(const T1 *, pixel->getData()) + pixel->getPixelStart(), planeSize, bits);
}
/** destructor
*/
virtual ~DiHSVPixelTemplate()
{
}
private:
/** convert input pixel data to intermediate representation
*
** @param pixel pointer to input pixel data
* @param planeSize number of pixels in a plane
* @param bits number of bits per sample
*/
void convert(const T1 *pixel,
const unsigned long planeSize,
const int bits)
{
if (DiColorPixelTemplate<T2>::Init(pixel)) //G.Barrand
{
/*G.Barrand register*/ T2 *r = this->Data[0];
/*G.Barrand register*/ T2 *g = this->Data[1];
/*G.Barrand register*/ T2 *b = this->Data[2];
const T2 maxvalue = OFstatic_cast(T2, DicomImageClass::maxval(bits));
const T1 offset = OFstatic_cast(T1, DicomImageClass::maxval(bits - 1));
// use the number of input pixels derived from the length of the 'PixelData'
// attribute), but not more than the size of the intermediate buffer
const unsigned long count = (this->InputCount < this->Count) ? this->InputCount : this->Count;
if (this->PlanarConfiguration)
{
/*
G_Barrand_register const T1 *h = pixel;
G_Barrand_register const T1 *s = h + this->InputCount;
G_Barrand_register const T1 *v = s + this->InputCount;
for (i = count; i != 0; --i)
convertValue(*(r++), *(g++), *(b++), removeSign(*(h++), offset), removeSign(*(s++), offset),
removeSign(*(v++), offset), maxvalue);
*/
/*G.Barrand register*/ unsigned long l;
/*G.Barrand register*/ unsigned long i = count;
/*G.Barrand register*/ const T1 *h = pixel;
/*G.Barrand register*/ const T1 *s = h + planeSize;
/*G.Barrand register*/ const T1 *v = s + planeSize;
while (i != 0)
{
/* convert a single frame */
for (l = planeSize; (l != 0) && (i != 0); --l, --i)
{
convertValue(*(r++), *(g++), *(b++), removeSign(*(h++), offset), removeSign(*(s++), offset),
removeSign(*(v++), offset), maxvalue);
}
/* jump to next frame start (skip 2 planes) */
h += 2 * planeSize;
s += 2 * planeSize;
v += 2 * planeSize;
}
}
else
{
/*G.Barrand register*/ const T1 *p = pixel;
/*G.Barrand register*/ T2 h;
/*G.Barrand register*/ T2 s;
/*G.Barrand register*/ T2 v;
/*G.Barrand register*/ unsigned long i;
for (i = count; i != 0; --i)
{
h = removeSign(*(p++), offset);
s = removeSign(*(p++), offset);
v = removeSign(*(p++), offset);
convertValue(*(r++), *(g++), *(b++), h, s, v, maxvalue);
}
}
}
}
/** convert a single HSV value to RGB
*/
void convertValue(T2 &red,
T2 &green,
T2 &blue,
const T2 hue,
const T2 saturation,
const T2 value,
const T2 maxvalue)
{
/*
* conversion algorithm taken from Foley et al.: 'Computer Graphics: Principles and Practice' (1990)
*/
if (saturation == 0)
{
red = value;
green = value;
blue = value;
}
else
{
const double h = (OFstatic_cast(double, hue) * 6) / (OFstatic_cast(double, maxvalue) + 1); // '... + 1' to assert h < 6
const double s = OFstatic_cast(double, saturation) / OFstatic_cast(double, maxvalue);
const double v = OFstatic_cast(double, value) / OFstatic_cast(double, maxvalue);
const T2 hi = OFstatic_cast(T2, h);
const double hf = h - hi;
const T2 p = OFstatic_cast(T2, maxvalue * v * (1 - s));
const T2 q = OFstatic_cast(T2, maxvalue * v * (1 - s * hf));
const T2 t = OFstatic_cast(T2, maxvalue * v * (1 - s * (1 - hf)));
switch (hi)
{
case 0:
red = value;
green = t;
blue = p;
break;
case 1:
red = q;
green = value;
blue = p;
break;
case 2:
red = p;
green = value;
blue = t;
break;
case 3:
red = p;
green = q;
blue = value;
break;
case 4:
red = t;
green = p;
blue = value;
break;
case 5:
red = value;
green = p;
blue = q;
break;
default:
DCMIMAGE_WARN("invalid value for 'hi' while converting HSV to RGB");
}
}
}
};
#endif
/*
*
* CVS/RCS Log:
* $Log: dihsvpxt.h,v $
* Revision 1.2 2013/07/02 07:15:11 barrand
* *** empty log message ***
*
* Revision 1.1.1.1 2013/04/16 19:23:56 barrand
*
*
* Revision 1.25 2010-10-14 13:16:29 joergr
* Updated copyright header. Added reference to COPYRIGHT file.
*
* Revision 1.24 2010-03-01 09:08:46 uli
* Removed some unnecessary include directives in the headers.
*
* Revision 1.23 2009-11-25 14:31:21 joergr
* Removed inclusion of header file "ofconsol.h".
*
* Revision 1.22 2009-10-14 10:25:14 joergr
* Fixed minor issues in log output. Also updated copyright date (if required).
*
* Revision 1.21 2009-10-13 14:08:33 uli
* Switched to logging mechanism provided by the "new" oflog module
*
* Revision 1.20 2006-08-15 16:35:01 meichel
* Updated the code in module dcmimage to correctly compile when
* all standard C++ classes remain in namespace std.
*
* Revision 1.19 2005/12/08 16:01:39 meichel
* Changed include path schema for all DCMTK header files
*
* Revision 1.18 2004/04/21 10:00:31 meichel
* Minor modifications for compilation with gcc 3.4.0
*
* Revision 1.17 2003/12/23 11:48:23 joergr
* Adapted type casts to new-style typecast operators defined in ofcast.h.
* Removed leading underscore characters from preprocessor symbols (reserved
* symbols). Updated copyright header.
* Replaced post-increment/decrement operators by pre-increment/decrement
* operators where appropriate (e.g. 'i++' by '++i').
*
* Revision 1.16 2002/06/26 16:18:10 joergr
* Enhanced handling of corrupted pixel data and/or length.
* Corrected decoding of multi-frame, planar images.
*
* Revision 1.15 2001/11/09 16:47:01 joergr
* Removed 'inline' specifier from certain methods.
*
* Revision 1.14 2001/06/01 15:49:30 meichel
* Updated copyright header
*
* Revision 1.13 2000/04/28 12:39:32 joergr
* DebugLevel - global for the module - now derived from OFGlobal (MF-safe).
*
* Revision 1.12 2000/04/27 13:15:13 joergr
* Dcmimage library code now consistently uses ofConsole for error output.
*
* Revision 1.11 2000/03/08 16:21:52 meichel
* Updated copyright header.
*
* Revision 1.10 2000/03/03 14:07:52 meichel
* Implemented library support for redirecting error messages into memory
* instead of printing them to stdout/stderr for GUI applications.
*
* Revision 1.9 1999/09/17 14:03:45 joergr
* Enhanced efficiency of some "for" loops.
*
* Revision 1.8 1999/04/28 12:47:04 joergr
* Introduced new scheme for the debug level variable: now each level can be
* set separately (there is no "include" relationship).
*
* Revision 1.7 1999/02/03 16:54:27 joergr
* Moved global functions maxval() and determineRepresentation() to class
* DicomImageClass (as static methods).
*
* Revision 1.6 1999/01/20 14:46:15 joergr
* Replaced invocation of getCount() by member variable Count where possible.
*
* Revision 1.5 1998/11/27 13:51:50 joergr
* Added copyright message.
*
* Revision 1.4 1998/05/11 14:53:16 joergr
* Added CVS/RCS header to each file.
*
*
*/
| [
"guy.barrand@gmail.com"
] | guy.barrand@gmail.com |
4cca9237f2ba51519a370b62f8504b5177ea13ab | 400d08ce40087beb18f59eefef794b403527aea6 | /test/test_detred_opadd.cpp | 51b096115d8c81aab482f122fef9958d44fd87d0 | [
"BSD-3-Clause"
] | permissive | sukhaj/CilkpubV2 | dd96e979f23579578d7820b4e00c9ffaf5509f29 | b494e0e463222c5571153eb1176664892df356b9 | refs/heads/master | 2021-05-15T10:49:50.837422 | 2017-10-24T02:59:54 | 2017-10-25T03:14:19 | 108,214,215 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,754 | cpp | /* test_detred_opadd.cpp -*-C++-*-
*
*************************************************************************
*
* Copyright (C) 2013, Intel Corporation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * 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 Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
* WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#include <assert.h>
#include <cstdio>
#include <cstdlib>
// TBD: Hack for now, until we fix this for real.
#define CILK_IGNORE_REDUCER_ALIGNMENT
#include <cilk/reducer_opadd.h>
#include <cilkpub/detred_opadd.h>
#include "cilktest_harness.h"
using namespace cilkpub;
template <typename T>
inline void tfprint(FILE* f, DetRedIview<T>& iview)
{
iview.fprint(f);
}
inline void tfprint(FILE* f, const pedigree& ped)
{
ped.fprint(f, "");
}
// void tfprint(FILE* f, det_reducer_opadd<double>* detred)
// {
// // detred->fprint(f);
// }
inline void pass_test() {
if (CILKTEST_NUM_ERRORS() == 0) {
CILKTEST_REMARK(1, "%s\n", "....PASSED");
}
else {
CILKTEST_REMARK(1, "%s\n", "....FAILED");
}
}
static bool within_tol(double sum, double expected) {
return ((sum - expected) * (sum - expected)) < 1.0e-12;
}
static bool within_tol(int sum, int expected)
{
return (sum == expected);
}
#define COMPLEX_ADD
void test_det_reducer_recursive_helper(cilk::reducer_opadd<double>* normal_red,
det_reducer_opadd<double>* det_red,
int start, int end) {
if ((end - start) <= 100) {
for (int j = start; j < end; ++j) {
#ifdef COMPLEX_ADD
double tmp = 2.54312 / (1.0 * (j+2));
#else
double tmp = 1.0;
#endif
(*normal_red) += tmp;
(*det_red) += tmp;
}
}
else {
int mid = (start + end)/2;
_Cilk_spawn test_det_reducer_recursive_helper(normal_red, det_red, start, mid);
if (mid % 10 == 3) {
#ifdef COMPLEX_ADD
double tmp = 1.32;
#else
double tmp = 1.0;
#endif
(*normal_red) += tmp;
(*det_red) += tmp;
}
test_det_reducer_recursive_helper(normal_red, det_red, mid, end);
_Cilk_sync;
}
}
void test_det_reducer_helper(double* normal_ans,
double* det_ans,
int NUM_TRIALS,
bool scope_test)
{
double starting_val = 1.321;
int LOOP_WIDTH = 10000;
for (int i = 0; i < NUM_TRIALS; ++i) {
cilk::reducer_opadd<double> normal_red(starting_val);
pedigree_scope current_scope;
det_reducer_opadd<double>* det_red;
if (scope_test) {
current_scope = pedigree_scope::current();
det_red = new det_reducer_opadd<double>(starting_val, current_scope);
}
else {
det_red = new det_reducer_opadd<double>(starting_val);
}
CILKTEST_PRINT(3, "Detred Initial View: ", det_red, "\n");
_Cilk_for(int j = 0; j < LOOP_WIDTH; ++j) {
double tmp = 2.45312 * j;
normal_red += tmp;
*det_red += tmp;
}
CILKTEST_PRINT(4, "Detred Initial View: ", det_red, "\n");
// NOTE: In order to get the exact same results between two
// different calls, I need to spawn this function. Otherwise,
// the initial pedigree of the first update to the reducer is
// shifted by the initial rank of function.
//
// (Really, this is a hack. What we need here is the same
// notion of a scoped pedigree that we used for DPRNG.)
test_det_reducer_recursive_helper(&normal_red, det_red, 0, LOOP_WIDTH);
normal_ans[i] = normal_red.get_value();
det_ans[i] = det_red->get_value();
CILKTEST_REMARK(3, "Iteration %d: \n", i);
CILKTEST_PRINT(3, "Detred View: ", det_red, "\n");
delete det_red;
}
}
void test_det_reducer() {
CILKTEST_REMARK(2, "test_det_reducer()...");
const int NUM_TRIALS = 15;
double normal_ans[NUM_TRIALS];
double det_ans[NUM_TRIALS];
_Cilk_spawn test_det_reducer_helper(normal_ans, det_ans, NUM_TRIALS, false);
_Cilk_sync;
test_det_reducer_helper(normal_ans, det_ans, NUM_TRIALS, false);
test_det_reducer_helper(normal_ans, det_ans, NUM_TRIALS, true);
CILKTEST_REMARK(2, "\nReducer: normal ans = %g, det ans = %g\n",
normal_ans[0], det_ans[0]);
for (int i = 1; i < NUM_TRIALS; ++i) {
CILKTEST_REMARK(2, "....Reducer diff: normal = %11g, det = %g\n",
(normal_ans[i] - normal_ans[0]),
(det_ans[i] - det_ans[0]));
TEST_ASSERT(within_tol(det_ans[i], normal_ans[i]));
TEST_ASSERT(det_ans[i] == det_ans[0]);
}
pass_test();
}
int main(int argc, char* argv[]) {
CILKTEST_PARSE_TEST_ARGS(argc, argv);
CILKTEST_BEGIN("Determinsitic reducer test");
test_det_reducer();
return CILKTEST_END("Determinsitic reducer test");
}
| [
"jsukha@CHAR.localdomain"
] | jsukha@CHAR.localdomain |
1e6adf16ee17a9a8d8f54d686683db04c9cef38b | 6676867d1b645bd6d8fc7c79d85d7e943a3a3550 | /ROS/skinny/src_does_not_compile/victor/src/victor_node.cpp | 99bd7da1437840332680c036f4fac47194c1d69f | [] | no_license | Razorbotz/RMC-Code-20-21 | 88604410293c5edb7a877365aa8bbf2a9cb4141b | f1a5a9c99a3af840188f8dc3a680c0453600ee02 | refs/heads/master | 2023-07-18T03:44:26.445419 | 2021-05-11T18:08:24 | 2021-05-11T18:08:24 | 336,593,274 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,632 | cpp | #include <string>
#include <iostream>
#include <chrono>
#include <thread>
#include <unistd.h>
#define Phoenix_No_WPI // remove WPI dependencies
#include <ctre/Phoenix.h>
#include <ctre/phoenix/platform/Platform.h>
#include <ctre/phoenix/unmanaged/Unmanaged.h>
#include <ros/ros.h>
#include <ros/console.h>
#include <std_msgs/Float32.h>
#include <std_msgs/Empty.h>
#include "messages/VictorOut.h"
using namespace ctre::phoenix;
using namespace ctre::phoenix::platform;
using namespace ctre::phoenix::motorcontrol;
using namespace ctre::phoenix::motorcontrol::can;
bool GO=false;
void stopCallback(std_msgs::Empty empty){
std::cout << "STOP" << std::endl;
GO=false;
}
void goCallback(std_msgs::Empty empty){
std::cout << "GO" << std::endl;
GO=true;
}
VictorSPX* victorSPX;
void speedCallback(const std_msgs::Float32 speed){
std::cout << speed.data << std::endl;
victorSPX->Set(ControlMode::PercentOutput, speed.data);
}
int main(int argc,char** argv){
std::cout << "Starting talon 3" << std::endl;
ros::init(argc,argv,"talon_node");
ros::NodeHandle nodeHandleP("~");
ros::NodeHandle nodeHandle;
int success;
std::string message;
success=nodeHandleP.getParam("message", message);
std::cout << success << "message " << message << std::endl;
int motorNumber=0;
success=nodeHandleP.getParam("motor_number", motorNumber);
std::cout << success << "motor_number: " << motorNumber << std::endl;
std::string infoTopic;
success=nodeHandleP.getParam("info_topic", infoTopic);
std::cout << success << "info_topic: " << infoTopic << std::endl;
std::string speedTopic;
success=nodeHandleP.getParam("speed_topic", speedTopic);
std::cout << success << "speed_topic: " << speedTopic << std::endl;
bool invertMotor=false;
success=nodeHandleP.getParam("invert_motor", invertMotor);
std::cout << success << "invert_motor: " << invertMotor << std::endl;
ctre::phoenix::platform::can::SetCANInterface("can0");
victorSPX=new VictorSPX(motorNumber);
victorSPX->SetInverted(invertMotor);
victorSPX->Set(ControlMode::PercentOutput, 0);
StatusFrame statusFrame;
messages::VictorOut victorOut;
ros::Publisher victorOutPublisher=nodeHandle.advertise<messages::VictorOut>(infoTopic.c_str(),1);
ros::Subscriber speedSubscriber=nodeHandle.subscribe(speedTopic.c_str(),1,speedCallback);
ros::Subscriber stopSubscriber=nodeHandle.subscribe("STOP",1,stopCallback);
ros::Subscriber goSubscriber=nodeHandle.subscribe("GO",1,goCallback);
auto start = std::chrono::high_resolution_clock::now();
while(ros::ok()){
if(GO)ctre::phoenix::unmanaged::FeedEnable(100);
auto finish = std::chrono::high_resolution_clock::now();
if(std::chrono::duration_cast<std::chrono::nanoseconds>(finish-start).count() > 250000000){
int deviceID=victorSPX->GetDeviceID();
double busVoltage=victorSPX->GetBusVoltage();
bool isInverted=victorSPX->GetInverted();
double motorOutputVoltage=victorSPX->GetMotorOutputVoltage();
double motorOutputPercent=victorSPX->GetMotorOutputPercent();
victorOut.deviceID=deviceID;
victorOut.busVoltage=busVoltage;
victorOut.outputVoltage=motorOutputVoltage;
victorOut.outputPercent=motorOutputPercent;
victorOutPublisher.publish(victorOut);
start = std::chrono::high_resolution_clock::now();
}
usleep(20);
ros::spinOnce();
}
}
| [
"andrewburroughs17@gmail.com"
] | andrewburroughs17@gmail.com |
7f0766975f6d910a4a909a1e762c0ab85402c537 | e13bddc546916ecba5b10721050d091da6df3993 | /helper.h | 7a2a11a422842ce7d1fd5684e0024697b211ef4d | [
"MIT"
] | permissive | aldemirenes/hagen | c7c278e1ea6f32f224d1edf2966869484061ce01 | e88385275fb9da82a6a132cd1e9a8f1cbacf3289 | refs/heads/master | 2021-04-27T18:36:14.526000 | 2018-02-21T15:41:02 | 2018-02-21T15:49:54 | 122,342,697 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 866 | h | #ifndef __HELPER__H__
#define __HELPER__H__
#include <iostream>
#include <string>
#include <fstream>
#include <jpeglib.h>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include "glm/glm.hpp" // GL Math library header
#include "glm/gtc/matrix_transform.hpp"
#include "glm/gtc/type_ptr.hpp"
#include "glm/gtx/rotate_vector.hpp"
extern GLuint idProgramShader;
extern GLuint idFragmentShader;
extern GLuint idVertexShader;
extern GLuint idJpegTexture;
using namespace std;
void initShaders();
GLuint initVertexShader(const string& filename);
GLuint initFragmentShader(const string& filename);
bool readDataFromFile(const string& fileName, string &data);
void initTexture(char *filename,int *w, int *h);
struct Camera
{
glm::vec3 position;
glm::vec3 gaze;
glm::vec3 up;
void rotateAroundUp(float);
void rotateAroundRight(float);
};
#endif
| [
"aldemirenes@live.com"
] | aldemirenes@live.com |
14c5bfbd6b79c3d51df3272baf2b606cbccf3536 | 394fd2a44126ae5607c30a58fe5593db1c6e5a02 | /src/QFrameDisplay.cpp | 9fc74e400994cfb7241bf2a7e5d919aa20c7f3f8 | [] | no_license | thx8411/qastrocam-g2 | 653b98463609737ab328f63929690f27d7f100eb | c1453cc8bc2e7719db21bae5bffe3340c66b42e0 | refs/heads/master | 2021-01-17T11:35:54.403879 | 2016-04-01T20:33:07 | 2016-04-01T20:33:07 | 40,839,897 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,918 | cpp | /******************************************************************
Qastrocam
Copyright (C) 2003-2009 Franck Sicard
Qastrocam-g2
Copyright (C) 2009-2013 Blaise-Florentin Collin
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License v2
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA.
*******************************************************************/
#include <Qt/qcolor.h>
#include <Qt/qpen.h>
#include <Qt/qpainter.h>
#include <QtGui/QPaintEvent>
#include "QFrameDisplay.hpp"
#include "QCamFrame.hpp"
QFrameDisplay::QFrameDisplay(QWidget * parent,const char * label) :
QWidget(parent) {
painter_ = new QPainter();
pen_=new QPen();
pen_->setStyle(Qt::DotLine);
pen_->setColor(QColor(255,0,0));
setAttribute(Qt::WA_NoBackground);
}
QFrameDisplay::~QFrameDisplay() {
delete pen_;
delete painter_;
}
void QFrameDisplay::frame(const QCamFrame &frame) {
frame_=frame;
setMinimumSize(frame_.size());
resize(frame_.size());
update();
}
void QFrameDisplay::paintEvent(QPaintEvent * ev) {
if (!frame_.empty()) {
painter_->begin(this);
painter_->setPen(*pen_);
painter_->setClipRegion(ev->region());
painter_->drawImage(0,0,frame_.colorImage());
painter_->drawLine(width()/2,0,
width()/2,height());
painter_->drawLine(0,height()/2,
width(),height()/2);
painter_->end();
}
}
| [
"thx8411@c1ec87e9-771e-51c6-fe90-2aeb2be771a7"
] | thx8411@c1ec87e9-771e-51c6-fe90-2aeb2be771a7 |
00beb681504f109e0f1ddec767cfeddab1d67135 | 47de1c3720ee7df453ce7904e1767798bbc5f1c7 | /src/mavencore/maven/Date.h | 49c42ad05ea64b259cea1a4be7270e53067e785f | [] | no_license | elliotchance/maven | 28a20058d8b83c0b364680f573b329941ad0573a | ea189bf5cea7cacf15ecfe071762d5560323d0ab | refs/heads/master | 2021-01-10T21:01:14.871430 | 2010-05-04T08:20:32 | 2010-05-04T08:20:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 377 | h | #ifndef MAVENCORE_MAVEN_DATE
#define MAVENCORE_MAVEN_DATE 1
#include "../mavencore.h"
namespace maven {
class Date extends maven::Object {
public_variable mshort year;
public_variable mbyte month;
public_variable mbyte day;
public_variable mbyte hour;
public_variable mbyte minute;
public_variable mbyte second;
public_constructor Date();
};
}
#endif
| [
"elliot@chancemedia.com"
] | elliot@chancemedia.com |
cd0a7558331d64c19e76f9b7c92347d366fa5179 | 7bb00eea506d129c94cede3001d437f4ebc4b16f | /20180327/Source/Api/ApiStd.cpp | d6e6a73e0efabece9527814af15750b126f5a3cf | [] | no_license | jhd41/ToolFrame | 3e5c82b5a5c41e1ba844b93c3df6dfc5a41572d9 | 250c7d4371eca95acc1a579f2b861a1c94dfe9e4 | refs/heads/master | 2020-03-15T03:04:58.371922 | 2018-05-03T03:01:10 | 2018-05-03T03:03:05 | 131,933,829 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 6,373 | cpp | #include "ApiStd.h"
#include "ToolStd.h"
void ApiStd::Trace( const std::string& msg )
{
#if MACRO_TARGET_VER == MACRO_VER_DEBUG
std::cout<<msg<<std::endl;
#endif // MACRO_VER_DEBUG
}
void ApiStd::OutPut( const std::string& msg )
{
std::cout<<msg<<std::endl;
}
void ApiStd::OutPutCerr( const std::string& msg )
{
std::cerr << msg << std::endl;
}
time_t ApiStd::GetNowTime()
{
return time(nullptr);
}
size_t ApiStd::GetFileLength( const std::string& sFileName )
{
if (sFileName.empty())return 0;
std::ifstream fStream;
//打开文件
if (!ToolFrame::OpenFile(fStream,sFileName))return 0;
return ToolFrame::GetFileLength(fStream);
}
bool ApiStd::LoadFile( const std::string& sFileName,void* pBuffer,size_t uLength )
{
if (sFileName.empty())return false;
if (!pBuffer)return false;
if (uLength <=0)return false;
std::ifstream fStream;
//打开文件
if (!ToolFrame::OpenFile(fStream,sFileName,std::ios::in|std::ios::binary))return false;
//检测文件长度
UINT uFileLen = ToolFrame::GetFileLength(fStream);
if(uFileLen == 0)return false;
//申请空间读取
if (uLength < uFileLen)return false;
//读取
fStream.read((char*)pBuffer, uFileLen);
fStream.close();
return true;
}
bool ApiStd::SaveFile( const std::string& sFileName,const void* pBuffer,size_t uLength)
{
if (sFileName.empty())return false;
if (!pBuffer)return false;
if (uLength <=0)return false;
//得到BUFF内存
std::ofstream fStream;
//打开文件
//打开文件
if (!ToolFrame::OpenFile(fStream,sFileName,std::ios::out|std::ios::binary))return false;
//写入
fStream.write((const char*)pBuffer,uLength);
fStream.close();
return true;
}
bool ApiStd::IsFileExist( const std::string& sFileName )
{
if (sFileName.empty())return false;
std::ifstream fStream;
//打开文件
fStream.open(sFileName.c_str());
return !!fStream;
}
bool ApiStd::CopyFile( const std::string& sPathSrc,const std::string& sPathDes )
{
if (sPathSrc.empty())return false;
if (sPathDes.empty())return false;
std::ifstream fInput;
if (!ToolFrame::OpenFile(fInput,sPathSrc,std::ios::binary))return false;//打开源文件
std::ofstream fOutPut;
if (!ToolFrame::OpenFile(fOutPut,sPathDes,std::ios::binary))return false;//创建目标文件
return ToolFrame::CopyFile(fOutPut,fInput);
}
bool ApiStd::RemoveFile( const std::string& sFileName )
{
if (sFileName.empty())return false;
return 0 == ::remove(sFileName.c_str());
}
bool ApiStd::RenameFile( const std::string& sPathSrc,const std::string& sPathDes )
{
if (sPathSrc.empty())return false;
if (sPathDes.empty())return false;
return 0 == ::rename(sPathSrc.c_str(),sPathDes.c_str());
}
bool ApiStd::MakePathVector( VectorString& vDes,const std::string& sPath )
{
if (sPath.empty())return false;
ToolFrame::SplitString(vDes,sPath,"/");
if (vDes.empty())return false;
if (ToolFrame::GetBack(vDes).empty())
ToolFrame::EraseBack(vDes);
return true;
}
std::string ApiStd::AbsPathToRelativePath( const std::string& sPath,const std::string& sCmpPath )
{
if (sPath.empty())return ToolFrame::EmptyString();
VectorString vCmpPath;
if (!MakePathVector(vCmpPath,StardPath(sCmpPath)))return ToolFrame::EmptyString();
return AbsPathToRelativePath(sPath,vCmpPath);
}
bool ApiStd::AbsPathToRelativePath( VectorString& vDes,const VectorString& vPath,const std::string& sCmpPath )
{
if (vPath.empty())return false;
if (ToolFrame::IsSelf(vDes,vPath))return false;
VectorString vCmpPath;
if (!MakePathVector(vCmpPath,StardPath(sCmpPath)))return false;
VectorString::const_iterator itr;
foreach(itr,vPath){
ToolFrame::PushBack(vDes,AbsPathToRelativePath(StardPath(*itr),vCmpPath));
if ( ToolFrame::EmptyString() == ToolFrame::GetBack(vDes))
return false;
}
return true;
}
std::string ApiStd::AbsPathToRelativePath( const std::string& sAbsPath,const VectorString& vCmpPath )
{
if (sAbsPath.empty())return ToolFrame::EmptyString();
VectorString vAbsPath;
if (!MakePathVector(vAbsPath,sAbsPath))return ToolFrame::EmptyString();
if (vAbsPath.empty() || vCmpPath.empty())return ToolFrame::EmptyString();
// aa/bb/c
// aa/c/d/c
//思路:找到路径不一样的地方,之后添加 被比较路径剩余部分 个 ../ 然后将绝对路径中剩下不同地方一起写入即可
//找到不一样的地方
size_t uDiff = -1;
size_t uMax = ToolFrame::Min(vAbsPath.size(),vCmpPath.size());
for (size_t uIndex = 0;uIndex<uMax;++uIndex)
{
if (vAbsPath[uIndex] != vCmpPath[uIndex])break;
uDiff = uIndex;
}
if (uDiff <= 0)return ToolFrame::EmptyString();
std::stringstream sStream;
//被比较路径剩余部分
for(size_t uIndex = uDiff + 1;uIndex<vCmpPath.size();++uIndex){
sStream<<"../";
}
//如果是当前目录
if (uDiff + 1 >= vCmpPath.size())
sStream<<"./";
//添加绝对路径不同部分
for(size_t uIndex = uDiff + 1;uIndex<vAbsPath.size();++uIndex){
sStream<<vAbsPath[uIndex];
if (uIndex != vAbsPath.size() - 1)
sStream<<"/";
}
return sStream.str();
}
std::string ApiStd::StardPath( const std::string& sPath )
{
if (sPath.empty())return ToolFrame::EmptyString();
std::string s = sPath;
ToolFrame::Replace(s,"\\","/");//Linux下只能读取"/"而不是"\"
return s;
}
std::string ApiStd::TrimPath( const std::string& sPath )
{
if (sPath.empty())return ToolFrame::EmptyString();
std::stringstream sStream;//返回值
//如果sPath是绝对路径开头先添加进去
if (ToolFrame::IsBeginWith(sPath,"/"))
{
sStream<<"/";
}
//然后拼接调整文件夹
{
VectorString vDes;
std::string s = sPath;
ToolFrame::Replace(s,"\\","/");
VectorString vString;
ToolFrame::SplitString(vString,s,"/");
VectorString::const_iterator itr;
foreach(itr,vString){
const std::string& sDirName = *itr;
if (sDirName == "")
{
continue;
}
if (sDirName == ".")
{
continue;
}
if (sDirName == "..")
{
if (vDes.empty() || vDes.back() == "..")
{
vDes.push_back("..");
}else
{
vDes.pop_back();
}
continue;
}
vDes.push_back(sDirName);
}
if (!vString.empty() && vString.back() == "")
{
vDes.push_back("");
}
//参考自 ToolFrame::ToString
{
bool bAttch= false;
VectorString::const_iterator itr;
foreach(itr,vDes){
if (bAttch)sStream << "/";
bAttch = true;
sStream << *itr;
}
}
}
return sStream.str();
}
| [
"jhd41@sina.com"
] | jhd41@sina.com |
2c0fde64edb5f672aa14b73fd0df0bbd5ac5e5e4 | 0f448094cf44550aa932011475a26360501b73b7 | /include/boost/asio/execution/detail/as_receiver.hpp | 3eefa5382f205b5411c256937211db34f0a3dfd0 | [] | no_license | DaiJason/asio | 0b1ca3bd3eba0143c6b9f509a26b03e8a32bd51a | b462d8fef2b64af3718c23141ec457821f5d44c1 | refs/heads/master | 2022-11-10T21:31:39.046058 | 2020-07-01T14:53:39 | 2020-07-01T14:53:39 | 276,620,049 | 0 | 0 | null | 2020-07-02T10:43:39 | 2020-07-02T10:43:39 | null | UTF-8 | C++ | false | false | 3,168 | hpp | //
// execution/detail/as_receiver.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef BOOST_ASIO_EXECUTION_DETAIL_AS_RECEIVER_HPP
#define BOOST_ASIO_EXECUTION_DETAIL_AS_RECEIVER_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/config.hpp>
#include <boost/asio/detail/type_traits.hpp>
#include <boost/asio/traits/set_done_member.hpp>
#include <boost/asio/traits/set_error_member.hpp>
#include <boost/asio/traits/set_value_member.hpp>
#include <boost/asio/detail/push_options.hpp>
namespace boost {
namespace asio {
namespace execution {
namespace detail {
template <typename Function, typename>
struct as_receiver
{
Function f_;
template <typename F>
explicit as_receiver(BOOST_ASIO_MOVE_ARG(F) f)
: f_(BOOST_ASIO_MOVE_CAST(F)(f))
{
}
void set_value()
BOOST_ASIO_NOEXCEPT_IF(noexcept(declval<Function&>()()))
{
f_();
}
template <typename E>
void set_error(E) BOOST_ASIO_NOEXCEPT
{
std::terminate();
}
void set_done() BOOST_ASIO_NOEXCEPT
{
}
};
template <typename T>
struct is_as_receiver : false_type
{
};
template <typename Function, typename T>
struct is_as_receiver<as_receiver<Function, T> > : true_type
{
};
} // namespace detail
} // namespace execution
namespace traits {
#if !defined(BOOST_ASIO_HAS_DEDUCED_SET_VALUE_MEMBER_TRAIT)
template <typename Function, typename T>
struct set_value_member<
boost::asio::execution::detail::as_receiver<Function, T>, void()>
{
BOOST_ASIO_STATIC_CONSTEXPR(bool, is_valid = true);
#if defined(BOOST_ASIO_HAS_NOEXCEPT)
BOOST_ASIO_STATIC_CONSTEXPR(bool,
is_noexcept = noexcept(declval<Function&>()()));
#else // defined(BOOST_ASIO_HAS_NOEXCEPT)
BOOST_ASIO_STATIC_CONSTEXPR(bool, is_noexcept = true);
#endif // defined(BOOST_ASIO_HAS_NOEXCEPT)
typedef void result_type;
};
#endif // !defined(BOOST_ASIO_HAS_DEDUCED_SET_VALUE_MEMBER_TRAIT)
#if !defined(BOOST_ASIO_HAS_DEDUCED_SET_ERROR_MEMBER_TRAIT)
template <typename Function, typename T, typename E>
struct set_error_member<
boost::asio::execution::detail::as_receiver<Function, T>, E>
{
BOOST_ASIO_STATIC_CONSTEXPR(bool, is_valid = true);
BOOST_ASIO_STATIC_CONSTEXPR(bool, is_noexcept = true);
typedef void result_type;
};
#endif // !defined(BOOST_ASIO_HAS_DEDUCED_SET_ERROR_MEMBER_TRAIT)
#if !defined(BOOST_ASIO_HAS_DEDUCED_SET_DONE_MEMBER_TRAIT)
template <typename Function, typename T>
struct set_done_member<
boost::asio::execution::detail::as_receiver<Function, T> >
{
BOOST_ASIO_STATIC_CONSTEXPR(bool, is_valid = true);
BOOST_ASIO_STATIC_CONSTEXPR(bool, is_noexcept = true);
typedef void result_type;
};
#endif // !defined(BOOST_ASIO_HAS_DEDUCED_SET_DONE_MEMBER_TRAIT)
} // namespace traits
} // namespace asio
} // namespace boost
#include <boost/asio/detail/pop_options.hpp>
#endif // BOOST_ASIO_EXECUTION_DETAIL_AS_RECEIVER_HPP
| [
"chris@kohlhoff.com"
] | chris@kohlhoff.com |
d722a4d7f890f2ae38bf79dde5ac0c3209af1306 | 274855d775a0a6ed8227ce0dfb36f84bb9acfa83 | /h5pp/include/h5pp/details/h5ppHdf5.h | 273640b8466ac3351a01e72e1ac3720b6916960f | [
"MIT"
] | permissive | sbreuils/h5pp | a8632278e0bbff498642e98c345a5ee3c959f6f1 | 33eede09f9b76e0163b38f0976747e74e3207260 | refs/heads/master | 2023-03-12T03:04:31.990324 | 2021-02-24T09:29:26 | 2021-02-24T09:44:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 179,176 | h | #pragma once
#include "h5ppEigen.h"
#include "h5ppEnums.h"
#include "h5ppFilesystem.h"
#include "h5ppHyperslab.h"
#include "h5ppInfo.h"
#include "h5ppLogger.h"
#include "h5ppPropertyLists.h"
#include "h5ppTypeSfinae.h"
#include "h5ppUtils.h"
#include <hdf5.h>
#include <map>
#include <typeindex>
#include <utility>
/*!
* \brief A collection of functions to create (or get information about) datasets and attributes in HDF5 files
*/
namespace h5pp::hdf5 {
[[nodiscard]] inline std::vector<std::string_view> pathCumulativeSplit(std::string_view path, std::string_view delim) {
// Here the resulting vector "output" will contain increasingly longer string_views, that are subsets of the path.
// Note that no string data is allocated here, these are simply views into a string allocated elsewhere.
// For example if path is "this/is/a/long/path, the vector will contain the following views
// [0]: this
// [1]: this/is
// [2]: this/is/a
// [3]: this/is/a/long
// [4]: this/is/a/long/path
// It is very important to note that the resulting views are not null terminate. Therefore, these vector elements
// **must not** be used as c-style arrays using their .data() member functions.
std::vector<std::string_view> output;
size_t currentPosition = 0;
while(currentPosition < path.size()) {
const auto foundPosition = path.find_first_of(delim, currentPosition);
if(currentPosition != foundPosition) { output.emplace_back(path.substr(0, foundPosition)); }
if(foundPosition == std::string_view::npos) break;
currentPosition = foundPosition + 1;
}
return output;
}
template<typename h5x, typename = std::enable_if_t<std::is_base_of_v<hid::hid_base<h5x>, h5x>>>
[[nodiscard]] std::string getName(const h5x &object) {
// Read about the buffer size inconsistency here
// http://hdf-forum.184993.n3.nabble.com/H5Iget-name-inconsistency-td193143.html
std::string buf;
ssize_t bufSize = H5Iget_name(object, nullptr, 0); // Size in bytes of the object name (NOT including \0)
if(bufSize > 0) {
buf.resize(static_cast<size_t>(bufSize) + 1); // We allocate space for the null terminator
H5Iget_name(object, buf.data(), bufSize);
}
return buf.c_str(); // Use .c_str() to get a "standard" std::string, i.e. one where .size() does not include \0
}
[[nodiscard]] inline int getRank(const hid::h5s &space) { return H5Sget_simple_extent_ndims(space); }
[[nodiscard]] inline int getRank(const hid::h5d &dset) {
hid::h5s space = H5Dget_space(dset);
return getRank(space);
}
[[nodiscard]] inline int getRank(const hid::h5a &attr) {
hid::h5s space = H5Aget_space(attr);
return getRank(space);
}
[[nodiscard]] inline hsize_t getSize(const hid::h5s &space) { return static_cast<hsize_t>(H5Sget_simple_extent_npoints(space)); }
[[nodiscard]] inline hsize_t getSize(const hid::h5d &dataset) {
hid::h5s space = H5Dget_space(dataset);
return getSize(space);
}
[[nodiscard]] inline hsize_t getSize(const hid::h5a &attribute) {
hid::h5s space = H5Aget_space(attribute);
return getSize(space);
}
[[nodiscard]] inline hsize_t getSizeSelected(const hid::h5s &space) { return static_cast<hsize_t>(H5Sget_select_npoints(space)); }
[[nodiscard]] inline std::vector<hsize_t> getDimensions(const hid::h5s &space) {
int ndims = H5Sget_simple_extent_ndims(space);
if(ndims < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error("Failed to get dimensions");
}
std::vector<hsize_t> dims(static_cast<size_t>(ndims));
H5Sget_simple_extent_dims(space, dims.data(), nullptr);
return dims;
}
[[nodiscard]] inline std::vector<hsize_t> getDimensions(const hid::h5d &dataset) {
hid::h5s space = H5Dget_space(dataset);
return getDimensions(space);
}
[[nodiscard]] inline std::vector<hsize_t> getDimensions(const hid::h5a &attribute) {
hid::h5s space = H5Aget_space(attribute);
return getDimensions(space);
}
[[nodiscard]] inline H5D_layout_t getLayout(const hid::h5p &dataset_creation_property_list) {
return H5Pget_layout(dataset_creation_property_list);
}
[[nodiscard]] inline H5D_layout_t getLayout(const hid::h5d &dataset) {
hid::h5p dcpl = H5Dget_create_plist(dataset);
return H5Pget_layout(dcpl);
}
[[nodiscard]] inline std::optional<std::vector<hsize_t>> getChunkDimensions(const hid::h5p &dsetCreatePropertyList) {
auto layout = H5Pget_layout(dsetCreatePropertyList);
if(layout != H5D_CHUNKED) return std::nullopt;
auto ndims = H5Pget_chunk(dsetCreatePropertyList, 0, nullptr);
if(ndims < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error("Failed to get chunk dimensions");
} else if(ndims > 0) {
std::vector<hsize_t> chunkDims(static_cast<size_t>(ndims));
H5Pget_chunk(dsetCreatePropertyList, ndims, chunkDims.data());
return chunkDims;
} else
return {};
}
[[nodiscard]] inline std::optional<std::vector<hsize_t>> getChunkDimensions(const hid::h5d &dataset) {
hid::h5p dcpl = H5Dget_create_plist(dataset);
return getChunkDimensions(dcpl);
}
[[nodiscard]] inline int getCompressionLevel(const hid::h5p &dsetCreatePropertyList) {
auto nfilter = H5Pget_nfilters(dsetCreatePropertyList);
H5Z_filter_t filter = H5Z_FILTER_NONE;
std::array<unsigned int, 1> cdval = {0};
std::array<size_t, 1> cdelm = {0};
for(int idx = 0; idx < nfilter; idx++) {
constexpr size_t size = 10;
filter = H5Pget_filter(dsetCreatePropertyList, idx, nullptr, cdelm.data(), cdval.data(), 0, nullptr, nullptr);
if(filter != H5Z_FILTER_DEFLATE) continue;
H5Pget_filter_by_id(dsetCreatePropertyList, filter, nullptr, cdelm.data(), cdval.data(), 0, nullptr, nullptr);
}
return cdval[0];
}
[[nodiscard]] inline std::optional<std::vector<hsize_t>> getMaxDimensions(const hid::h5s &space, H5D_layout_t layout) {
if(layout != H5D_CHUNKED) return std::nullopt;
if(H5Sget_simple_extent_type(space) != H5S_SIMPLE) return std::nullopt;
int rank = H5Sget_simple_extent_ndims(space);
if(rank < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error("Failed to get dimensions");
}
std::vector<hsize_t> dimsMax(static_cast<size_t>(rank));
H5Sget_simple_extent_dims(space, nullptr, dimsMax.data());
return dimsMax;
}
[[nodiscard]] inline std::optional<std::vector<hsize_t>> getMaxDimensions(const hid::h5d &dataset) {
hid::h5s space = H5Dget_space(dataset);
hid::h5p dcpl = H5Dget_create_plist(dataset);
return getMaxDimensions(space, getLayout(dcpl));
}
inline herr_t H5Dvlen_get_buf_size_safe(const hid::h5d &dset, const hid::h5t &type, const hid::h5s &space, hsize_t *vlen) {
*vlen = 0;
if(H5Tis_variable_str(type) <= 0) return -1;
if(H5Sget_simple_extent_type(space) != H5S_SCALAR) {
herr_t retval = H5Dvlen_get_buf_size(dset, type, space, vlen);
if(retval >= 0) return retval;
}
if(H5Dget_storage_size(dset) <= 0) return 0;
auto size = H5Sget_simple_extent_npoints(space);
std::vector<const char *> vdata{static_cast<size_t>(size)}; // Allocate for pointers for "size" number of strings
// HDF5 allocates space for each string
herr_t retval = H5Dread(dset, type, H5S_ALL, H5S_ALL, H5P_DEFAULT, vdata.data());
if(retval < 0) {
H5Eprint(H5E_DEFAULT, stderr);
return 0;
}
// Sum up the number of bytes
size_t maxLen = h5pp::constants::maxSizeCompact;
for(auto elem : vdata) {
if(elem == nullptr) continue;
*vlen += static_cast<hsize_t>(std::min(std::string_view(elem).size(), maxLen) + 1); // Add null-terminator
}
H5Dvlen_reclaim(type, space, H5P_DEFAULT, vdata.data());
return 1;
}
inline herr_t H5Avlen_get_buf_size_safe(const hid::h5a &attr, const hid::h5t &type, const hid::h5s &space, hsize_t *vlen) {
*vlen = 0;
if(H5Tis_variable_str(type) <= 0) return -1;
if(H5Aget_storage_size(attr) <= 0) return 0;
auto size = H5Sget_simple_extent_npoints(space);
std::vector<const char *> vdata{static_cast<size_t>(size)}; // Allocate pointers for "size" number of strings
// HDF5 allocates space for each string
herr_t retval = H5Aread(attr, type, vdata.data());
if(retval < 0) {
H5Eprint(H5E_DEFAULT, stderr);
return 0;
}
// Sum up the number of bytes
size_t maxLen = h5pp::constants::maxSizeCompact;
for(auto elem : vdata) {
if(elem == nullptr) continue;
*vlen += static_cast<hsize_t>(std::min(std::string_view(elem).size(), maxLen) + 1); // Add null-terminator
}
H5Dvlen_reclaim(type, space, H5P_DEFAULT, vdata.data());
return 1;
}
[[nodiscard]] inline size_t getBytesPerElem(const hid::h5t &h5Type) { return H5Tget_size(h5Type); }
[[nodiscard]] inline size_t getBytesTotal(const hid::h5s &space, const hid::h5t &type) {
return getBytesPerElem(type) * getSize(space);
}
[[nodiscard]] inline size_t getBytesTotal(const hid::h5d &dset, std::optional<hid::h5s> space, std::optional<hid::h5t> type) {
if(not type) type = H5Dget_type(dset);
if(not space) space = H5Dget_space(dset);
if(H5Tis_variable_str(type.value()) > 0) {
hsize_t vlen = 0;
herr_t err = H5Dvlen_get_buf_size_safe(dset, type.value(), space.value(), &vlen);
if(err >= 0)
return vlen; // Returns the total number of bytes required to store the dataset
else
return getBytesTotal(space.value(), type.value());
}
return getBytesTotal(space.value(), type.value());
}
[[nodiscard]] inline size_t getBytesTotal(const hid::h5a &attr, std::optional<hid::h5s> space, std::optional<hid::h5t> type) {
if(not type) type = H5Aget_type(attr);
if(not space) space = H5Aget_space(attr);
if(H5Tis_variable_str(type.value()) > 0) {
hsize_t vlen = 0;
herr_t err = H5Avlen_get_buf_size_safe(attr, type.value(), space.value(), &vlen);
if(err >= 0)
return vlen; // Returns the total number of bytes required to store the dataset
else
return getBytesTotal(space.value(), type.value());
}
return getBytesTotal(space.value(), type.value());
}
[[nodiscard]] inline size_t getBytesSelected(const hid::h5s &space, const hid::h5t &type) {
return getBytesPerElem(type) * getSizeSelected(space);
}
template<typename DataType>
void assertWriteBufferIsLargeEnough(const DataType &data, const hid::h5s &space, const hid::h5t &type) {
if(H5Tget_class(type) == H5T_STRING) {
if(H5Tis_variable_str(type)) return; // This transfers the string from memory until finding a null terminator
if constexpr(h5pp::type::sfinae::is_text_v<DataType>) {
auto hdf5Byte = H5Tget_size(type); // Chars including null-terminator. The memory buffer must fit this size. Also, these
// many bytes will participate in IO
auto hdf5Size = getSizeSelected(space);
auto dataByte = h5pp::util::getCharArraySize(data, false); // Allocated chars including null terminator
auto dataSize = h5pp::util::getSize(data);
if(dataByte < hdf5Byte)
throw std::runtime_error(
h5pp::format("The text buffer given for this write operation is smaller than the selected space in memory.\n"
"\t Data transfer would read from memory out of bounds\n"
"\t given : num strings {} | bytes {} = {} chars + '\\0'\n"
"\t selected : num strings {} | bytes {} = {} chars + '\\0'\n"
"\t type : [{}]",
dataSize,
dataByte,
dataByte - 1,
hdf5Size,
hdf5Byte,
hdf5Byte - 1,
h5pp::type::sfinae::type_name<DataType>()));
}
} else {
if constexpr(std::is_pointer_v<DataType>) return;
if constexpr(not h5pp::type::sfinae::has_size_v<DataType>) return;
auto hdf5Size = getSizeSelected(space);
auto hdf5Byte = h5pp::util::getBytesPerElem<DataType>() * hdf5Size;
auto dataByte = h5pp::util::getBytesTotal(data);
auto dataSize = h5pp::util::getSize(data);
if(dataByte < hdf5Byte)
throw std::runtime_error(
h5pp::format("The buffer given for this write operation is smaller than the selected space in memory.\n"
"\t Data transfer would read from memory out of bounds\n"
"\t given : size {} | bytes {}\n"
"\t selected: size {} | bytes {}\n"
"\t type : [{}]",
dataSize,
dataByte,
hdf5Size,
hdf5Byte,
h5pp::type::sfinae::type_name<DataType>()));
}
}
template<typename DataType>
void assertReadSpaceIsLargeEnough(const DataType &data, const hid::h5s &space, const hid::h5t &type) {
if(H5Tget_class(type) == H5T_STRING) {
if(H5Tis_variable_str(type)) return; // These are resized on the fly
if constexpr(h5pp::type::sfinae::is_text_v<DataType>) {
// The memory buffer must fit hdf5Byte: that's how many bytes will participate in IO
auto hdf5Byte = H5Tget_size(type); // Chars including null-terminator.
auto hdf5Size = getSizeSelected(space);
auto dataByte = h5pp::util::getCharArraySize(data) + 1; // Chars including null terminator
auto dataSize = h5pp::util::getSize(data);
if(dataByte < hdf5Byte)
throw std::runtime_error(h5pp::format(
"The text buffer allocated for this read operation is smaller than the string buffer found on the dataset.\n"
"\t Data transfer would write into memory out of bounds\n"
"\t allocated buffer: num strings {} | bytes {} = {} chars + '\\0'\n"
"\t selected buffer: num strings {} | bytes {} = {} chars + '\\0'\n"
"\t type : [{}]",
dataSize,
dataByte,
dataByte - 1,
hdf5Size,
hdf5Byte,
hdf5Byte - 1,
h5pp::type::sfinae::type_name<DataType>()));
}
} else {
if constexpr(std::is_pointer_v<DataType>) return;
if constexpr(not h5pp::type::sfinae::has_size_v<DataType>) return;
auto hdf5Size = getSizeSelected(space);
auto hdf5Byte = h5pp::util::getBytesPerElem<DataType>() * hdf5Size;
auto dataByte = h5pp::util::getBytesTotal(data);
auto dataSize = h5pp::util::getSize(data);
if(dataByte < hdf5Byte)
throw std::runtime_error(
h5pp::format("The buffer allocated for this read operation is smaller than the selected space in memory.\n"
"\t Data transfer would write into memory out of bounds\n"
"\t allocated : size {} | bytes {}\n"
"\t selected : size {} | bytes {}\n"
"\t type : [{}]",
dataSize,
dataByte,
hdf5Size,
hdf5Byte,
h5pp::type::sfinae::type_name<DataType>()));
}
}
template<typename userDataType>
[[nodiscard]] bool checkBytesPerElemMatch(const hid::h5t &h5Type) {
size_t dsetTypeSize = h5pp::hdf5::getBytesPerElem(h5Type);
size_t dataTypeSize = h5pp::util::getBytesPerElem<userDataType>();
if(H5Tget_class(h5Type) == H5T_STRING) dsetTypeSize = H5Tget_size(H5T_C_S1);
if(dataTypeSize != dsetTypeSize) {
// The dsetType may have been generated by H5Tpack, in which case we should check against the native type
size_t packedTypesize = dsetTypeSize;
hid::h5t nativetype = H5Tget_native_type(h5Type, H5T_DIR_ASCEND);
dsetTypeSize = h5pp::hdf5::getBytesPerElem(nativetype);
if(dataTypeSize != dsetTypeSize)
h5pp::logger::log->debug("Type size mismatch: dataset type {} bytes | given type {} bytes", dsetTypeSize, dataTypeSize);
else
h5pp::logger::log->warn(
"Detected packed HDF5 type: packed size {} bytes | native size {} bytes. This is not supported by h5pp yet!",
packedTypesize,
dataTypeSize);
}
return dataTypeSize == dsetTypeSize;
}
template<typename DataType, typename = std::enable_if_t<not std::is_base_of_v<hid::hid_base<DataType>, DataType>>>
void assertBytesPerElemMatch(const hid::h5t &h5Type) {
size_t dsetTypeSize = h5pp::hdf5::getBytesPerElem(h5Type);
size_t dataTypeSize = h5pp::util::getBytesPerElem<DataType>();
if(H5Tget_class(h5Type) == H5T_STRING) dsetTypeSize = H5Tget_size(H5T_C_S1);
if(dataTypeSize != dsetTypeSize) {
// The dsetType may have been generated by H5Tpack, in which case we should check against the native type
size_t packedTypesize = dsetTypeSize;
hid::h5t nativetype = H5Tget_native_type(h5Type, H5T_DIR_ASCEND);
dsetTypeSize = h5pp::hdf5::getBytesPerElem(nativetype);
if(dataTypeSize != dsetTypeSize)
throw std::runtime_error(h5pp::format(
"Type size mismatch: dataset type is [{}] bytes | Type of given data is [{}] bytes", dsetTypeSize, dataTypeSize));
else
h5pp::logger::log->warn(
"Detected packed HDF5 type: packed size {} bytes | native size {} bytes. This is not supported by h5pp yet!",
packedTypesize,
dataTypeSize);
}
}
template<typename DataType, typename = std::enable_if_t<not std::is_base_of_v<hid::hid_base<DataType>, DataType>>>
void assertReadTypeIsLargeEnough(const hid::h5t &h5Type) {
size_t dsetTypeSize = h5pp::hdf5::getBytesPerElem(h5Type);
size_t dataTypeSize = h5pp::util::getBytesPerElem<DataType>();
if(H5Tget_class(h5Type) == H5T_STRING) dsetTypeSize = H5Tget_size(H5T_C_S1);
if(dataTypeSize != dsetTypeSize) {
// The dsetType may have been generated by H5Tpack, in which case we should check against the native type
size_t packedTypesize = dsetTypeSize;
hid::h5t nativetype = H5Tget_native_type(h5Type, H5T_DIR_ASCEND);
dsetTypeSize = h5pp::hdf5::getBytesPerElem(nativetype);
if(dataTypeSize > dsetTypeSize)
h5pp::logger::log->debug(
"Given data-type is too large: elements of type [{}] are [{}] bytes (each) | target HDF5 type is [{}] bytes",
h5pp::type::sfinae::type_name<DataType>(), dataTypeSize, dsetTypeSize);
else if(dataTypeSize < dsetTypeSize)
throw std::runtime_error(h5pp::format(
"Given data-type is too small: elements of type [{}] are [{}] bytes (each) | target HDF5 type is [{}] bytes",
h5pp::type::sfinae::type_name<DataType>(), dataTypeSize, dsetTypeSize));
else
h5pp::logger::log->warn(
"Detected packed HDF5 type: packed size {} bytes | native size {} bytes. This is not supported by h5pp yet!",
packedTypesize,
dataTypeSize);
}
}
template<typename DataType>
inline void setStringSize(const DataType &data, hid::h5t &type, hsize_t &size, size_t &bytes, std::vector<hsize_t> &dims) {
H5T_class_t dataClass = H5Tget_class(type);
if(dataClass == H5T_STRING) {
// The datatype may either be text or a container of text.
// Examples of pure text are std::string or char[]
// Example of a container of text is std::vector<std::string>
// When
// 1) it is pure text and dimensions are {}
// * Space is H5S_SCALAR because dimensions are {}
// * Rank is 0 because dimensions are {}
// * Size is 1 because size = prod 1*dim(i) * dim(j)...
// * We set size H5T_VARIABLE
// 2) it is pure text and dimensions were specified other than {}
// * Space is H5S_SIMPLE
// * Rank is 1 or more because dimensions were given as {i,j,k...}
// * Size is n, because size = prod 1*dim(i) * dim(j)...
// * Here n is number of chars to get from the string buffer
// * We set the string size to n because each element is a char.
// * We set the dimension to {1}
// 3) it is a container of text
// * Space is H5S_SIMPLE
// * The rank is 1 or more
// * The space size is the number of strings in the container
// * We set size H5T_VARIABLE
// * The dimensions remain the size of the container
if(H5Tget_size(type) != 1) return; // String properties have already been set, probably by the user
herr_t retval = 0;
if constexpr(h5pp::type::sfinae::is_text_v<DataType>) {
if(dims.empty()) {
// Case 1
retval = H5Tset_size(type, H5T_VARIABLE);
bytes = h5pp::util::getBytesTotal(data);
} else {
// Case 2
hsize_t desiredSize = h5pp::util::getSizeFromDimensions(dims);
// Consider a case where the text is "this is a text"
// but the desired size is 12.
// The resulting string should be "this is a t'\0'",
// with 12 characters in total including the null terminator.
// HDF5 seems to do this automatically. From the manual:
// "If the short string is H5T_STR_NULLTERM, it is truncated
// and a null terminator is appended."
// Furthermore
// "The size set for a string datatype should include space for
// the null-terminator character, otherwise it will not be
// stored on (or retrieved from) disk"
retval = H5Tset_size(type, desiredSize); // Desired size should be num chars + null terminator
dims = {};
size = 1;
bytes = desiredSize;
}
} else if(h5pp::type::sfinae::has_text_v<DataType>) {
// Case 3
retval = H5Tset_size(type, H5T_VARIABLE);
bytes = h5pp::util::getBytesTotal(data);
}
if(retval < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error("Failed to set size on string");
}
// The following makes sure there is a single "\0" at the end of the string when written to file.
// Note however that bytes here is supposed to be the number of characters including null terminator.
retval = H5Tset_strpad(type, H5T_STR_NULLTERM);
if(retval < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error("Failed to set strpad");
}
// Sets the character set to UTF-8
retval = H5Tset_cset(type, H5T_cset_t::H5T_CSET_UTF8);
if(retval < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error("Failed to set char-set UTF-8");
}
}
}
template<typename h5x>
[[nodiscard]] inline bool checkIfLinkExists(const h5x &loc, std::string_view linkPath, const hid::h5p &linkAccess = H5P_DEFAULT) {
static_assert(h5pp::type::sfinae::is_h5_loc_or_hid_v<h5x>,
"Template function [h5pp::hdf5::checkIfLinkExists<h5x>(const h5x & loc, ...)] requires type h5x to be: "
"[h5pp::hid::h5f], [h5pp::hid::h5g], [h5pp::hid::h5o] or [hid_t]");
for(const auto &subPath : pathCumulativeSplit(linkPath, "/")) {
int exists = H5Lexists(loc, util::safe_str(subPath).c_str(), linkAccess);
if(exists == 0) {
h5pp::logger::log->trace("Checking if link exists [{}] ... false", linkPath);
return false;
}
if(exists < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(h5pp::format("Failed to check if link exists [{}]", linkPath));
}
}
h5pp::logger::log->trace("Checking if link exists [{}] ... true", linkPath);
return true;
}
template<typename h5x, typename h5x_loc>
[[nodiscard]] h5x openLink(const h5x_loc & loc,
std::string_view linkPath,
std::optional<bool> linkExists = std::nullopt,
const hid::h5p & linkAccess = H5P_DEFAULT) {
static_assert(h5pp::type::sfinae::is_h5_link_v<h5x>,
"Template function [h5pp::hdf5::openLink<h5x>(...)] requires type h5x to be: "
"[h5pp::hid::h5d], [h5pp::hid::h5g] or [h5pp::hid::h5o]");
static_assert(h5pp::type::sfinae::is_h5_loc_or_hid_v<h5x_loc>,
"Template function [h5pp::hdf5::openLink<h5x>(const h5x_loc & loc, ...)] requires type h5x_loc to be: "
"[h5pp::hid::h5f], [h5pp::hid::h5g], [h5pp::hid::h5o] or [hid_t]");
if(not linkExists) linkExists = checkIfLinkExists(loc, linkPath, linkAccess);
if(linkExists.value()) {
if constexpr(std::is_same_v<h5x, hid::h5d>) h5pp::logger::log->trace("Opening dataset [{}]", linkPath);
if constexpr(std::is_same_v<h5x, hid::h5g>) h5pp::logger::log->trace("Opening group [{}]", linkPath);
if constexpr(std::is_same_v<h5x, hid::h5o>) h5pp::logger::log->trace("Opening object [{}]", linkPath);
hid_t link;
if constexpr(std::is_same_v<h5x, hid::h5d>) link = H5Dopen(loc, util::safe_str(linkPath).c_str(), linkAccess);
if constexpr(std::is_same_v<h5x, hid::h5g>) link = H5Gopen(loc, util::safe_str(linkPath).c_str(), linkAccess);
if constexpr(std::is_same_v<h5x, hid::h5o>) link = H5Oopen(loc, util::safe_str(linkPath).c_str(), linkAccess);
if(link < 0) {
H5Eprint(H5E_DEFAULT, stderr);
if constexpr(std::is_same_v<h5x, hid::h5d>) throw std::runtime_error(h5pp::format("Failed to open dataset [{}]", linkPath));
if constexpr(std::is_same_v<h5x, hid::h5g>) throw std::runtime_error(h5pp::format("Failed to open group [{}]", linkPath));
if constexpr(std::is_same_v<h5x, hid::h5o>) throw std::runtime_error(h5pp::format("Failed to open object [{}]", linkPath));
} else {
return link;
}
} else {
throw std::runtime_error(h5pp::format("Link does not exist [{}]", linkPath));
}
}
template<typename h5x>
[[nodiscard]] inline bool checkIfAttrExists(const h5x &link, std::string_view attrName, const hid::h5p &linkAccess = H5P_DEFAULT) {
static_assert(h5pp::type::sfinae::is_h5_link_or_hid_v<h5x>,
"Template function [h5pp::hdf5::checkIfAttrExists<h5x>(const h5x & link, ...) requires type h5x to be: "
"[h5pp::hid::h5d], [h5pp::hid::h5g], [h5pp::hid::h5o] or [hid_t]");
// if(attrExists and attrExists.value()) return true;
h5pp::logger::log->trace("Checking if attribute [{}] exitst in link ...", attrName);
bool exists = H5Aexists_by_name(link, std::string(".").c_str(), util::safe_str(attrName).c_str(), linkAccess) > 0;
h5pp::logger::log->trace("Checking if attribute [{}] exitst in link ... {}", attrName, exists);
return exists;
}
template<typename h5x>
[[nodiscard]] inline bool checkIfAttrExists(const h5x & loc,
std::string_view linkPath,
std::string_view attrName,
std::optional<bool> linkExists = std::nullopt,
const hid::h5p & linkAccess = H5P_DEFAULT) {
static_assert(h5pp::type::sfinae::is_h5_loc_or_hid_v<h5x>,
"Template function [h5pp::hdf5::checkIfAttrExists<h5x>(const h5x & loc, ..., ...)] requires type h5x to be: "
"[h5pp::hid::h5d], [h5pp::hid::h5g], [h5pp::hid::h5o] or [hid_t]");
if(not linkExists) linkExists = checkIfLinkExists(loc, linkPath, linkAccess);
// If the link does not exist the attribute doesn't exist either
if(not linkExists.value()) return false;
// Otherwise we open the link and check
auto link = openLink<hid::h5o>(loc, linkPath, linkExists, linkAccess);
h5pp::logger::log->trace("Checking if attribute [{}] exitst in link [{}] ...", attrName, linkPath);
bool exists = H5Aexists_by_name(link, std::string(".").c_str(), util::safe_str(attrName).c_str(), linkAccess) > 0;
h5pp::logger::log->trace("Checking if attribute [{}] exitst in link [{}] ... {}", attrName, linkPath, exists);
return exists;
}
[[nodiscard]] inline bool H5Tequal_recurse(const hid::h5t &type1, const hid::h5t &type2) {
// If types are compound, check recursively that all members have equal types and names
H5T_class_t dataClass1 = H5Tget_class(type1);
H5T_class_t dataClass2 = H5Tget_class(type1);
if(dataClass1 == H5T_COMPOUND and dataClass2 == H5T_COMPOUND) {
size_t sizeType1 = H5Tget_size(type1);
size_t sizeType2 = H5Tget_size(type2);
if(sizeType1 != sizeType2) return false;
auto nMembers1 = H5Tget_nmembers(type1);
auto nMembers2 = H5Tget_nmembers(type2);
if(nMembers1 != nMembers2) return false;
for(auto idx = 0; idx < nMembers1; idx++) {
hid::h5t t1 = H5Tget_member_type(type1, static_cast<unsigned int>(idx));
hid::h5t t2 = H5Tget_member_type(type2, static_cast<unsigned int>(idx));
char * mem1 = H5Tget_member_name(type1, static_cast<unsigned int>(idx));
char * mem2 = H5Tget_member_name(type2, static_cast<unsigned int>(idx));
std::string_view n1 = mem1;
std::string_view n2 = mem2;
bool equal = n1 == n2;
H5free_memory(mem1);
H5free_memory(mem2);
if(not equal) return false;
if(not H5Tequal_recurse(t1, t2)) return false;
}
return true;
} else if(dataClass1 == dataClass2) {
if(dataClass1 == H5T_STRING)
return true;
else
return type1 == type2;
} else
return false;
}
[[nodiscard]] inline bool checkIfCompressionIsAvailable() {
/*
* Check if zlib compression is available and can be used for both
* compression and decompression. We do not throw errors because this
* filter is an optional part of the hdf5 library.
*/
htri_t zlibAvail = H5Zfilter_avail(H5Z_FILTER_DEFLATE);
if(zlibAvail) {
unsigned int filterInfo;
H5Zget_filter_info(H5Z_FILTER_DEFLATE, &filterInfo);
bool zlib_encode = (filterInfo & H5Z_FILTER_CONFIG_ENCODE_ENABLED);
bool zlib_decode = (filterInfo & H5Z_FILTER_CONFIG_DECODE_ENABLED);
return zlibAvail and zlib_encode and zlib_decode;
} else {
return false;
}
}
[[nodiscard]] inline unsigned int getValidCompressionLevel(std::optional<unsigned int> compressionLevel = std::nullopt) {
if(checkIfCompressionIsAvailable()) {
if(compressionLevel) {
if(compressionLevel.value() < 10) {
return compressionLevel.value();
} else {
h5pp::logger::log->debug("Given compression level {} is too high. Expected value 0 (min) to 9 (max). Returning 9");
return 9;
}
} else {
return 0;
}
} else {
h5pp::logger::log->debug("Compression is not available with this HDF5 library");
return 0;
}
}
[[nodiscard]] inline std::string getAttributeName(const hid::h5a &attribute) {
std::string buf;
ssize_t bufSize = H5Aget_name(attribute, 0ul, nullptr); // Returns number of chars excluding \0
if(bufSize >= 0) {
buf.resize(bufSize);
H5Aget_name(attribute, static_cast<size_t>(bufSize) + 1, buf.data()); // buf is guaranteed to have \0 at the end
} else {
H5Eprint(H5E_DEFAULT, stderr);
h5pp::logger::log->debug("Failed to get attribute names");
}
return buf.c_str();
}
template<typename h5x>
[[nodiscard]] inline std::vector<std::string> getAttributeNames(const h5x &link) {
static_assert(h5pp::type::sfinae::is_h5_link_or_hid_v<h5x>,
"Template function [h5pp::hdf5::getAttributeNames(const h5x & link, ...)] requires type h5x to be: "
"[h5pp::hid::h5d], [h5pp::hid::h5g], [h5pp::hid::h5o] or [hid_t]");
auto numAttrs = H5Aget_num_attrs(link);
std::vector<std::string> attrNames;
std::string buf;
for(auto i = 0; i < numAttrs; i++) {
hid::h5a attrId = H5Aopen_idx(link, static_cast<unsigned int>(i));
attrNames.emplace_back(getAttributeName(attrId));
}
return attrNames;
}
template<typename h5x>
[[nodiscard]] inline std::vector<std::string> getAttributeNames(const h5x & loc,
std::string_view linkPath,
std::optional<bool> linkExists = std::nullopt,
const hid::h5p & linkAccess = H5P_DEFAULT) {
static_assert(
h5pp::type::sfinae::is_h5_loc_or_hid_v<h5x>,
"Template function [h5pp::hdf5::getAttributeNames(const h5x & link, std::string_view linkPath)] requires type h5x to be: "
"[h5pp::hid::h5f], [h5pp::hid::h5g], [h5pp::hid::h5o] or [hid_t]");
auto link = openLink<hid::h5o>(loc, linkPath, linkExists, linkAccess);
return getAttributeNames(link);
}
template<typename T>
[[nodiscard]] std::tuple<std::type_index, std::string, size_t> getCppType() {
return {typeid(T), std::string(h5pp::type::sfinae::type_name<T>()), sizeof(T)};
}
[[nodiscard]] inline std::tuple<std::type_index, std::string, size_t> getCppType(const hid::h5t &type) {
using namespace h5pp::type::compound;
/* clang-format off */
if(H5Tequal(type, H5T_NATIVE_SHORT)) return getCppType<short>();
if(H5Tequal(type, H5T_NATIVE_INT)) return getCppType<int>();
if(H5Tequal(type, H5T_NATIVE_LONG)) return getCppType<long>();
if(H5Tequal(type, H5T_NATIVE_LLONG)) return getCppType<long long>();
if(H5Tequal(type, H5T_NATIVE_USHORT)) return getCppType<unsigned short>();
if(H5Tequal(type, H5T_NATIVE_UINT)) return getCppType<unsigned int>();
if(H5Tequal(type, H5T_NATIVE_ULONG)) return getCppType<unsigned long>();
if(H5Tequal(type, H5T_NATIVE_ULLONG)) return getCppType<unsigned long long>();
if(H5Tequal(type, H5T_NATIVE_DOUBLE)) return getCppType<double>();
if(H5Tequal(type, H5T_NATIVE_LDOUBLE)) return getCppType<long double>();
if(H5Tequal(type, H5T_NATIVE_FLOAT)) return getCppType<float>();
if(H5Tequal(type, H5T_NATIVE_HBOOL)) return getCppType<bool>();
if(H5Tequal(type, H5T_NATIVE_CHAR)) return getCppType<char>();
if(H5Tequal_recurse(type, H5Tcopy(H5T_C_S1))) return getCppType<std::string>();
if(H5Tequal_recurse(type, H5T_COMPLEX_SHORT)) return getCppType<std::complex<short>>();
if(H5Tequal_recurse(type, H5T_COMPLEX_INT)) return getCppType<std::complex<int>>();
if(H5Tequal_recurse(type, H5T_COMPLEX_LONG)) return getCppType<std::complex<long>>();
if(H5Tequal_recurse(type, H5T_COMPLEX_LLONG)) return getCppType<std::complex<long long>>();
if(H5Tequal_recurse(type, H5T_COMPLEX_USHORT)) return getCppType<std::complex<unsigned short>>();
if(H5Tequal_recurse(type, H5T_COMPLEX_UINT)) return getCppType<std::complex<unsigned int>>();
if(H5Tequal_recurse(type, H5T_COMPLEX_ULONG)) return getCppType<std::complex<unsigned long>>();
if(H5Tequal_recurse(type, H5T_COMPLEX_ULLONG)) return getCppType<std::complex<unsigned long long>>();
if(H5Tequal_recurse(type, H5T_COMPLEX_DOUBLE)) return getCppType<std::complex<double>>();
if(H5Tequal_recurse(type, H5T_COMPLEX_LDOUBLE)) return getCppType<std::complex<long double>>();
if(H5Tequal_recurse(type, H5T_COMPLEX_FLOAT)) return getCppType<std::complex<float>>();
if(H5Tequal_recurse(type, H5T_SCALAR2_SHORT)) return getCppType<H5T_SCALAR2<short>>();
if(H5Tequal_recurse(type, H5T_SCALAR2_INT)) return getCppType<H5T_SCALAR2<int>>();
if(H5Tequal_recurse(type, H5T_SCALAR2_LONG)) return getCppType<H5T_SCALAR2<long>>();
if(H5Tequal_recurse(type, H5T_SCALAR2_LLONG)) return getCppType<H5T_SCALAR2<long long>>();
if(H5Tequal_recurse(type, H5T_SCALAR2_USHORT)) return getCppType<H5T_SCALAR2<unsigned short>>();
if(H5Tequal_recurse(type, H5T_SCALAR2_UINT)) return getCppType<H5T_SCALAR2<unsigned int>>();
if(H5Tequal_recurse(type, H5T_SCALAR2_ULONG)) return getCppType<H5T_SCALAR2<unsigned long>>();
if(H5Tequal_recurse(type, H5T_SCALAR2_ULLONG)) return getCppType<H5T_SCALAR2<unsigned long long>>();
if(H5Tequal_recurse(type, H5T_SCALAR2_DOUBLE)) return getCppType<H5T_SCALAR2<double>>();
if(H5Tequal_recurse(type, H5T_SCALAR2_LDOUBLE)) return getCppType<H5T_SCALAR2<long double>>();
if(H5Tequal_recurse(type, H5T_SCALAR2_FLOAT)) return getCppType<H5T_SCALAR2<float>>();
if(H5Tequal_recurse(type, H5T_SCALAR3_SHORT)) return getCppType<H5T_SCALAR3<short>>();
if(H5Tequal_recurse(type, H5T_SCALAR3_INT)) return getCppType<H5T_SCALAR3<int>>();
if(H5Tequal_recurse(type, H5T_SCALAR3_LONG)) return getCppType<H5T_SCALAR3<long>>();
if(H5Tequal_recurse(type, H5T_SCALAR3_LLONG)) return getCppType<H5T_SCALAR3<long long>>();
if(H5Tequal_recurse(type, H5T_SCALAR3_USHORT)) return getCppType<H5T_SCALAR3<unsigned short>>();
if(H5Tequal_recurse(type, H5T_SCALAR3_UINT)) return getCppType<H5T_SCALAR3<unsigned int>>();
if(H5Tequal_recurse(type, H5T_SCALAR3_ULONG)) return getCppType<H5T_SCALAR3<unsigned long>>();
if(H5Tequal_recurse(type, H5T_SCALAR3_ULLONG)) return getCppType<H5T_SCALAR3<unsigned long long>>();
if(H5Tequal_recurse(type, H5T_SCALAR3_DOUBLE)) return getCppType<H5T_SCALAR3<double>>();
if(H5Tequal_recurse(type, H5T_SCALAR3_LDOUBLE)) return getCppType<H5T_SCALAR3<long double>>();
if(H5Tequal_recurse(type, H5T_SCALAR3_FLOAT)) return getCppType<H5T_SCALAR3<float>>();
/* clang-format on */
if(H5Tcommitted(type) > 0) {
H5Eprint(H5E_DEFAULT, stderr);
h5pp::logger::log->debug("No C++ type match for HDF5 type [{}]", getName(type));
} else {
h5pp::logger::log->debug("No C++ type match for non-committed HDF5 type");
}
std::string name = "UNKNOWN TYPE";
if(H5Tget_class(type) == H5T_class_t::H5T_INTEGER) name ="H5T_INTEGER";
else if(H5Tget_class(type) == H5T_class_t::H5T_FLOAT) name ="H5T_FLOAT";
else if(H5Tget_class(type) == H5T_class_t::H5T_TIME) name ="H5T_TIME";
else if(H5Tget_class(type) == H5T_class_t::H5T_STRING) name ="H5T_STRING";
else if(H5Tget_class(type) == H5T_class_t::H5T_BITFIELD) name ="H5T_BITFIELD";
else if(H5Tget_class(type) == H5T_class_t::H5T_OPAQUE) name ="H5T_OPAQUE";
else if(H5Tget_class(type) == H5T_class_t::H5T_COMPOUND) name ="H5T_COMPOUND";
else if(H5Tget_class(type) == H5T_class_t::H5T_REFERENCE) name ="H5T_REFERENCE";
else if(H5Tget_class(type) == H5T_class_t::H5T_ENUM) name ="H5T_ENUM";
else if(H5Tget_class(type) == H5T_class_t::H5T_VLEN) name ="H5T_VLEN";
else if(H5Tget_class(type) == H5T_class_t::H5T_ARRAY) name ="H5T_ARRAY";
return {typeid(nullptr), name, getBytesPerElem(type)};
}
[[nodiscard]] inline TypeInfo getTypeInfo(std::optional<std::string> objectPath,
std::optional<std::string> objectName,
const hid::h5s & h5Space,
const hid::h5t & h5Type) {
TypeInfo typeInfo;
typeInfo.h5Name = std::move(objectName);
typeInfo.h5Path = std::move(objectPath);
typeInfo.h5Type = h5Type;
typeInfo.h5Rank = h5pp::hdf5::getRank(h5Space);
typeInfo.h5Size = h5pp::hdf5::getSize(h5Space);
typeInfo.h5Dims = h5pp::hdf5::getDimensions(h5Space);
std::tie(typeInfo.cppTypeIndex, typeInfo.cppTypeName, typeInfo.cppTypeBytes) = getCppType(typeInfo.h5Type.value());
return typeInfo;
}
[[nodiscard]] inline TypeInfo getTypeInfo(const hid::h5d &dataset) {
auto dsetPath = h5pp::hdf5::getName(dataset);
h5pp::logger::log->trace("Collecting type info about dataset [{}]", dsetPath);
return getTypeInfo(dsetPath, std::nullopt, H5Dget_space(dataset), H5Dget_type(dataset));
}
template<typename h5x, typename = h5pp::type::sfinae::enable_if_is_h5_loc_or_hid_t<h5x>>
// enable_if so the compiler doesn't think it can use overload with std::string on first argument
[[nodiscard]] inline TypeInfo getTypeInfo(const h5x & loc,
std::string_view dsetName,
std::optional<bool> dsetExists = std::nullopt,
const hid::h5p & dsetAccess = H5P_DEFAULT) {
auto dataset = openLink<hid::h5d>(loc, dsetName, dsetExists, dsetAccess);
return getTypeInfo(dataset);
}
[[nodiscard]] inline TypeInfo getTypeInfo(const hid::h5a &attribute) {
auto attrName = getAttributeName(attribute);
auto linkPath = getName(attribute); // Returns the name of the link which has the attribute
h5pp::logger::log->trace("Collecting type info about attribute [{}] in link [{}]", attrName, linkPath);
return getTypeInfo(linkPath, attrName, H5Aget_space(attribute), H5Aget_type(attribute));
}
template<typename h5x>
[[nodiscard]] inline TypeInfo getTypeInfo(const h5x & loc,
std::string_view linkPath,
std::string_view attrName,
std::optional<bool> linkExists = std::nullopt,
std::optional<bool> attrExists = std::nullopt,
const hid::h5p & linkAccess = H5P_DEFAULT) {
if(not linkExists) linkExists = checkIfLinkExists(loc, linkPath, linkAccess);
if(not linkExists.value())
throw std::runtime_error(
h5pp::format("Attribute [{}] does not exist because its link does not exist: [{}]", attrName, linkPath));
auto link = openLink<hid::h5o>(loc, linkPath, linkExists, linkAccess);
if(not attrExists) attrExists = checkIfAttrExists(link, attrName, linkAccess);
if(attrExists.value()) {
hid::h5a attribute = H5Aopen_name(link, util::safe_str(attrName).c_str());
return getTypeInfo(attribute);
} else {
throw std::runtime_error(h5pp::format("Attribute [{}] does not exist in link [{}]", attrName, linkPath));
}
}
template<typename h5x>
[[nodiscard]] std::vector<TypeInfo> getTypeInfo_allAttributes(const h5x &link) {
static_assert(h5pp::type::sfinae::is_h5_link_or_hid_v<h5x>,
"Template function [h5pp::hdf5::getTypeInfo_allAttributes(const h5x & link)] requires type h5x to be: "
"[h5pp::hid::h5d], [h5pp::hid::h5g], [h5pp::hid::h5o] or [hid_t]");
std::vector<TypeInfo> allAttrInfo;
int num_attrs = H5Aget_num_attrs(link);
if(num_attrs < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error("Failed to get number of attributes in link");
}
for(int idx = 0; idx < num_attrs; idx++) {
hid::h5a attribute = H5Aopen_idx(link, static_cast<unsigned int>(idx));
allAttrInfo.emplace_back(getTypeInfo(attribute));
}
return allAttrInfo;
}
template<typename h5x>
[[nodiscard]] inline std::vector<TypeInfo> getTypeInfo_allAttributes(const h5x & loc,
std::string_view linkPath,
std::optional<bool> linkExists = std::nullopt,
const hid::h5p & linkAccess = H5P_DEFAULT) {
static_assert(h5pp::type::sfinae::is_h5_loc_or_hid_v<h5x>,
"Template function [h5pp::hdf5::getTypeInfo_allAttributes(const h5x & loc, ...)] requires type h5x to be: "
"[h5pp::hid::h5f], [h5pp::hid::h5g], [h5pp::hid::h5o] or [hid_t]");
auto link = openLink<hid::h5o>(loc, linkPath, linkExists, linkAccess);
return getTypeInfo_allAttributes(link);
}
template<typename h5x>
inline void createGroup(const h5x & loc,
std::string_view groupName,
std::optional<bool> linkExists = std::nullopt,
const PropertyLists &plists = PropertyLists()) {
static_assert(h5pp::type::sfinae::is_h5_loc_or_hid_v<h5x>,
"Template function [h5pp::hdf5::createGroup(const h5x & loc, ...)] requires type h5x to be: "
"[h5pp::hid::h5f], [h5pp::hid::h5g], [h5pp::hid::h5o] or [hid_t]");
// Check if group exists already
if(not linkExists) linkExists = checkIfLinkExists(loc, groupName, plists.linkAccess);
if(not linkExists.value()) {
h5pp::logger::log->trace("Creating group link [{}]", groupName);
hid_t gid = H5Gcreate(loc, util::safe_str(groupName).c_str(), plists.linkCreate, plists.groupCreate, plists.groupAccess);
if(gid < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(h5pp::format("Failed to create group link [{}]", groupName));
}
H5Gclose(gid);
} else
h5pp::logger::log->trace("Group exists already: [{}]", groupName);
}
template<typename h5x>
inline void writeSymbolicLink(const h5x & loc,
std::string_view srcPath,
std::string_view tgtPath,
std::optional<bool> linkExists = std::nullopt,
const PropertyLists &plists = PropertyLists()) {
static_assert(h5pp::type::sfinae::is_h5_loc_or_hid_v<h5x>,
"Template function [h5pp::hdf5::writeSymbolicLink(const h5x & loc, ...)] requires type h5x to be: "
"[h5pp::hid::h5f], [h5pp::hid::h5g], [h5pp::hid::h5o] or [hid_t]");
if(not linkExists) linkExists = checkIfLinkExists(loc, srcPath, plists.linkAccess);
if(not linkExists.value()) {
h5pp::logger::log->trace("Creating symbolic link [{}] --> [{}]", srcPath, tgtPath);
herr_t retval =
H5Lcreate_soft(util::safe_str(srcPath).c_str(), loc, util::safe_str(tgtPath).c_str(), plists.linkCreate, plists.linkAccess);
if(retval < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(h5pp::format("Failed to write symbolic link [{}] ", srcPath));
}
} else {
throw std::runtime_error(h5pp::format("Tried to write soft link to non-existing path [{}]", srcPath));
}
}
inline void setProperty_layout(DsetInfo &dsetInfo) {
if(not dsetInfo.h5PlistDsetCreate)
throw std::logic_error("Could not configure the H5D layout: the dataset creation property list has not been initialized");
if(not dsetInfo.h5Layout)
throw std::logic_error("Could not configure the H5D layout: the H5D layout parameter has not been initialized");
switch(dsetInfo.h5Layout.value()) {
case H5D_CHUNKED: h5pp::logger::log->trace("Setting layout H5D_CHUNKED"); break;
case H5D_COMPACT: h5pp::logger::log->trace("Setting layout H5D_COMPACT"); break;
case H5D_CONTIGUOUS: h5pp::logger::log->trace("Setting layout H5D_CONTIGUOUS"); break;
default:
throw std::runtime_error(
"Given invalid layout when creating dataset property list. Choose one of H5D_COMPACT,H5D_CONTIGUOUS,H5D_CHUNKED");
}
herr_t err = H5Pset_layout(dsetInfo.h5PlistDsetCreate.value(), dsetInfo.h5Layout.value());
if(err < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error("Could not set layout");
}
}
inline void setProperty_chunkDims(DsetInfo &dsetInfo) {
if(dsetInfo.h5Layout != H5D_CHUNKED and not dsetInfo.dsetChunk) return;
if(dsetInfo.h5Layout != H5D_CHUNKED and dsetInfo.dsetChunk) {
h5pp::logger::log->warn("Chunk dimensions {} ignored: The given dataset layout is not H5D_CHUNKED", dsetInfo.dsetChunk.value());
dsetInfo.dsetChunk = std::nullopt;
return;
}
if(H5Sget_simple_extent_type(dsetInfo.h5Space.value()) == H5S_SCALAR) {
h5pp::logger::log->warn("Chunk dimensions ignored: Space is H5S_SCALAR");
dsetInfo.dsetChunk = std::nullopt;
dsetInfo.dsetDimsMax = std::nullopt;
dsetInfo.h5Layout = H5D_CONTIGUOUS; // In case it's a big text
dsetInfo.resizePolicy = h5pp::ResizePolicy::DO_NOT_RESIZE;
setProperty_layout(dsetInfo);
return;
}
if(not dsetInfo.h5PlistDsetCreate)
throw std::logic_error("Could not configure chunk dimensions: the dataset creation property list has not been initialized");
if(not dsetInfo.dsetRank)
throw std::logic_error("Could not configure chunk dimensions: the dataset rank (n dims) has not been initialized");
if(not dsetInfo.dsetDims)
throw std::logic_error("Could not configure chunk dimensions: the dataset dimensions have not been initialized");
if(dsetInfo.dsetRank.value() != static_cast<int>(dsetInfo.dsetDims->size()))
throw std::logic_error(h5pp::format("Could not set chunk dimensions properties: Rank mismatch: dataset dimensions {} has "
"different number of elements than reported rank {}",
dsetInfo.dsetDims.value(),
dsetInfo.dsetRank.value()));
if(dsetInfo.dsetDims->size() != dsetInfo.dsetChunk->size())
throw std::logic_error(h5pp::format("Could not configure chunk dimensions: Rank mismatch: dataset dimensions {} and chunk "
"dimensions {} do not have the same number of elements",
dsetInfo.dsetDims->size(),
dsetInfo.dsetChunk->size()));
h5pp::logger::log->trace("Setting chunk dimensions {}", dsetInfo.dsetChunk.value());
herr_t err =
H5Pset_chunk(dsetInfo.h5PlistDsetCreate.value(), static_cast<int>(dsetInfo.dsetChunk->size()), dsetInfo.dsetChunk->data());
if(err < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error("Could not set chunk dimensions");
}
}
inline void setProperty_compression(DsetInfo &dsetInfo) {
if(not dsetInfo.compression) return;
if(not checkIfCompressionIsAvailable()) return;
if(not dsetInfo.h5PlistDsetCreate)
throw std::runtime_error("Could not configure compression: field h5_plist_dset_create has not been initialized");
if(not dsetInfo.h5Layout) throw std::logic_error("Could not configure compression: field h5_layout has not been initialized");
if(dsetInfo.h5Layout.value() != H5D_CHUNKED) {
h5pp::logger::log->trace("Compression ignored: Layout is not H5D_CHUNKED");
dsetInfo.compression = std::nullopt;
return;
}
if(dsetInfo.compression and dsetInfo.compression.value() > 9) {
h5pp::logger::log->warn("Compression level too high: [{}]. Reducing to [9]", dsetInfo.compression.value());
dsetInfo.compression = 9;
}
h5pp::logger::log->trace("Setting compression level {}", dsetInfo.compression.value());
herr_t err = H5Pset_deflate(dsetInfo.h5PlistDsetCreate.value(), dsetInfo.compression.value());
if(err < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error("Failed to set compression level. Check that your HDF5 version has zlib enabled.");
}
}
inline void selectHyperslab(hid::h5s &space, const Hyperslab &hyperSlab, std::optional<H5S_seloper_t> select_op_override = std::nullopt) {
if(hyperSlab.empty()) return;
int rank = H5Sget_simple_extent_ndims(space);
if(rank < 0) throw std::runtime_error("Failed to read space rank");
std::vector<hsize_t> dims(static_cast<size_t>(rank));
H5Sget_simple_extent_dims(space, dims.data(), nullptr);
// If one of slabOffset or slabExtent is given, then the other must also be given
if(hyperSlab.offset and not hyperSlab.extent)
throw std::logic_error("Could not setup hyperslab metadata: Given hyperslab offset but not extent");
if(not hyperSlab.offset and hyperSlab.extent)
throw std::logic_error("Could not setup hyperslab metadata: Given hyperslab extent but not offset");
// If given, ranks of slabOffset and slabExtent must be identical to each other and to the rank of the existing dataset
if(hyperSlab.offset and hyperSlab.extent and (hyperSlab.offset.value().size() != hyperSlab.extent.value().size()))
throw std::logic_error(
h5pp::format("Could not setup hyperslab metadata: Size mismatch in given hyperslab arrays: offset {} | extent {}",
hyperSlab.offset.value(),
hyperSlab.extent.value()));
if(hyperSlab.offset and hyperSlab.offset.value().size() != static_cast<size_t>(rank))
throw std::logic_error(
h5pp::format("Could not setup hyperslab metadata: Hyperslab arrays have different rank compared to the given space: "
"offset {} | extent {} | space dims {}",
hyperSlab.offset.value(),
hyperSlab.extent.value(),
dims));
// If given, slabStride must have the same rank as the dataset
if(hyperSlab.stride and hyperSlab.stride.value().size() != static_cast<size_t>(rank))
throw std::logic_error(
h5pp::format("Could not setup hyperslab metadata: Hyperslab stride has a different rank compared to the dataset: "
"stride {} | dataset dims {}",
hyperSlab.stride.value(),
dims));
// If given, slabBlock must have the same rank as the dataset
if(hyperSlab.blocks and hyperSlab.blocks.value().size() != static_cast<size_t>(rank))
throw std::logic_error(
h5pp::format("Could not setup hyperslab metadata: Hyperslab blocks has a different rank compared to the dataset: "
"blocks {} | dataset dims {}",
hyperSlab.blocks.value(),
dims));
if(not select_op_override) select_op_override = hyperSlab.select_oper;
if(H5Sget_select_type(space) != H5S_SEL_HYPERSLABS and select_op_override != H5S_SELECT_SET)
select_op_override = H5S_SELECT_SET; // First hyperslab selection must be H5S_SELECT_SET
herr_t retval = 0;
/* clang-format off */
if(hyperSlab.offset and hyperSlab.extent and hyperSlab.stride and hyperSlab.blocks)
retval = H5Sselect_hyperslab(space, select_op_override.value(), hyperSlab.offset.value().data(), hyperSlab.stride.value().data(), hyperSlab.extent.value().data(), hyperSlab.blocks.value().data());
else if (hyperSlab.offset and hyperSlab.extent and hyperSlab.stride)
retval = H5Sselect_hyperslab(space, select_op_override.value(), hyperSlab.offset.value().data(), hyperSlab.stride.value().data(), hyperSlab.extent.value().data(), nullptr);
else if (hyperSlab.offset and hyperSlab.extent and hyperSlab.blocks)
retval = H5Sselect_hyperslab(space, select_op_override.value(), hyperSlab.offset.value().data(), nullptr, hyperSlab.extent.value().data(), hyperSlab.blocks.value().data());
else if (hyperSlab.offset and hyperSlab.extent)
retval = H5Sselect_hyperslab(space, select_op_override.value(), hyperSlab.offset.value().data(), nullptr, hyperSlab.extent.value().data(), nullptr);
/* clang-format on */
if(retval < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(h5pp::format("Failed to select hyperslab"));
}
#if H5_VERSION_GE(1, 10, 0)
htri_t is_regular = H5Sis_regular_hyperslab(space);
if(is_regular < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(h5pp::format("Failed to check if Hyperslab selection is regular (non-rectangular)"));
} else if(is_regular == 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(h5pp::format("Hyperslab selection is irregular (non-rectangular).\n"
"This is not yet supported by h5pp"));
}
#endif
htri_t valid = H5Sselect_valid(space);
if(valid < 0) {
H5Eprint(H5E_DEFAULT, stderr);
Hyperslab slab(space);
throw std::runtime_error(
h5pp::format("Hyperslab selection is invalid. {} | space dims {}", getDimensions(space), slab.string()));
} else if(valid == 0) {
H5Eprint(H5E_DEFAULT, stderr);
Hyperslab slab(space);
throw std::runtime_error(h5pp::format(
"Hyperslab selection is not contained in the given space. {} | space dims {}", getDimensions(space), slab.string()));
}
}
inline void selectHyperslabs(hid::h5s & space,
const std::vector<Hyperslab> & hyperSlabs,
std::optional<std::vector<H5S_seloper_t>> hyperSlabSelectOps = std::nullopt) {
if(hyperSlabSelectOps and not hyperSlabSelectOps->empty()) {
if(hyperSlabs.size() != hyperSlabSelectOps->size())
for(const auto &slab : hyperSlabs) selectHyperslab(space, slab, hyperSlabSelectOps->at(0));
else
for(size_t num = 0; num < hyperSlabs.size(); num++) selectHyperslab(space, hyperSlabs[num], hyperSlabSelectOps->at(num));
} else
for(const auto &slab : hyperSlabs) selectHyperslab(space, slab, H5S_seloper_t::H5S_SELECT_OR);
}
inline void setSpaceExtent(const hid::h5s & h5Space,
const std::vector<hsize_t> & dims,
std::optional<std::vector<hsize_t>> dimsMax = std::nullopt) {
if(H5Sget_simple_extent_type(h5Space) == H5S_SCALAR) return;
if(dims.empty()) return;
herr_t err;
if(dimsMax) {
// Here dimsMax was given by the user and we have to do some sanity checks
// Check that the ranks match
if(dims.size() != dimsMax->size())
throw std::runtime_error(h5pp::format("Number of dimensions (rank) mismatch: dims {} | max dims {}\n"
"\t Hint: Dimension lists must have the same number of elements",
dims,
dimsMax.value()));
std::vector<long> dimsMaxPretty;
for(auto &dim : dimsMax.value()) {
if(dim == H5S_UNLIMITED)
dimsMaxPretty.emplace_back(-1);
else
dimsMaxPretty.emplace_back(static_cast<long>(dim));
}
h5pp::logger::log->trace("Setting dataspace extents: dims {} | max dims {}", dims, dimsMaxPretty);
err = H5Sset_extent_simple(h5Space, static_cast<int>(dims.size()), dims.data(), dimsMax->data());
if(err < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(h5pp::format("Failed to set extents on space: dims {} | max dims {}", dims, dimsMax.value()));
}
} else {
h5pp::logger::log->trace("Setting dataspace extents: dims {}", dims);
err = H5Sset_extent_simple(h5Space, static_cast<int>(dims.size()), dims.data(), nullptr);
if(err < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(h5pp::format("Failed to set extents on space. Dims {}", dims));
}
}
}
inline void setSpaceExtent(DsetInfo &dsetInfo) {
if(not dsetInfo.h5Space) throw std::logic_error("Could not set space extent: the space is not initialized");
if(not dsetInfo.h5Space->valid()) throw std::runtime_error("Could not set space extent. Space is not valid");
if(H5Sget_simple_extent_type(dsetInfo.h5Space.value()) == H5S_SCALAR) return;
if(not dsetInfo.dsetDims) throw std::runtime_error("Could not set space extent: dataset dimensions are not defined");
if(dsetInfo.h5Layout and dsetInfo.h5Layout.value() == H5D_CHUNKED and not dsetInfo.dsetDimsMax) {
// Chunked datasets are unlimited unless told explicitly otherwise
dsetInfo.dsetDimsMax = std::vector<hsize_t>(static_cast<size_t>(dsetInfo.dsetRank.value()), 0);
std::fill_n(dsetInfo.dsetDimsMax->begin(), dsetInfo.dsetDimsMax->size(), H5S_UNLIMITED);
}
try {
setSpaceExtent(dsetInfo.h5Space.value(), dsetInfo.dsetDims.value(), dsetInfo.dsetDimsMax);
} catch(const std::exception &err) {
throw std::runtime_error(h5pp::format("Failed to set extent on dataset {} \n Reason {}", dsetInfo.string(), err.what()));
}
}
inline void extendSpace(const hid::h5s &space, const int dim, const hsize_t extent) {
h5pp::logger::log->trace("Extending space dimension [{}] to extent [{}]", dim, extent);
// Retrieve the current extent of this space
const int oldRank = H5Sget_simple_extent_ndims(space);
std::vector<hsize_t> oldDims(static_cast<size_t>(oldRank));
H5Sget_simple_extent_dims(space, oldDims.data(), nullptr);
// We may need to change the rank, for instance, if we are appending a new column
// to a vector of size n, so it becomes an (n x 2) "matrix".
const int newRank = std::max(dim + 1, oldRank);
std::vector<hsize_t> newDims(static_cast<size_t>(newRank), 1);
std::copy(oldDims.begin(), oldDims.end(), newDims.begin());
newDims[static_cast<size_t>(dim)] = extent;
setSpaceExtent(space, newDims);
// H5Sset_extent_simple(space,newRank,newDims.data(),nullptr);
}
inline void extendDataset(const hid::h5d &dataset, const int dim, const hsize_t extent) {
// Retrieve the current size of the memSpace (act as if you don't know its size and want to append)
hid::h5s space = H5Dget_space(dataset);
extendSpace(space, dim, extent);
}
inline void extendDataset(const hid::h5d &dataset, const std::vector<hsize_t> &dims) {
if(H5Dset_extent(dataset, dims.data()) < 0) throw std::runtime_error("Failed to set extent on dataset");
}
template<typename h5x>
inline void extendDataset(const h5x & loc,
std::string_view datasetRelativeName,
const int dim,
const hsize_t extent,
std::optional<bool> linkExists = std::nullopt,
const hid::h5p & dsetAccess = H5P_DEFAULT) {
auto dataset = openLink<hid::h5d>(loc, datasetRelativeName, linkExists, dsetAccess);
extendDataset(dataset, dim, extent);
}
template<typename h5x, typename DataType>
void extendDataset(const h5x &loc, const DataType &data, std::string_view dsetPath) {
#ifdef H5PP_EIGEN3
if constexpr(h5pp::type::sfinae::is_eigen_core_v<DataType>) {
extendDataset(loc, dsetPath, 0, data.rows());
hid::h5d dataSet = openLink<hid::h5d>(loc, dsetPath);
hid::h5s fileSpace = H5Dget_space(dataSet);
int ndims = H5Sget_simple_extent_ndims(fileSpace);
std::vector<hsize_t> dims(static_cast<size_t>(ndims));
H5Sget_simple_extent_dims(fileSpace, dims.data(), nullptr);
H5Sclose(fileSpace);
if(dims[1] < static_cast<hsize_t>(data.cols())) extendDataset(loc, dsetPath, 1, data.cols());
} else
#endif
{
extendDataset(loc, dsetPath, 0, h5pp::util::getSize(data));
}
}
inline void extendDataset(DsetInfo &info, const std::vector<hsize_t> &appDimensions, size_t axis) {
// We use this function to EXTEND the dataset to APPEND given data
info.assertResizeReady();
int appRank = static_cast<int>(appDimensions.size());
if(H5Tis_variable_str(info.h5Type.value()) > 0) {
// These are resized on the fly
return;
} else {
// Sanity checks
if(info.dsetRank.value() <= static_cast<int>(axis))
throw std::runtime_error(h5pp::format(
"Could not append to dataset [{}] along axis {}: Dataset rank ({}) must be strictly larger than the given axis ({})",
info.dsetPath.value(),
axis,
info.dsetRank.value(),
axis));
if(info.dsetRank.value() < appRank)
throw std::runtime_error(h5pp::format("Cannot append to dataset [{}] along axis {}: Dataset rank {} < appended rank {}",
info.dsetPath.value(),
axis,
info.dsetRank.value(),
appRank));
// If we have a dataset with dimensions ijkl and we want to append along j, say, then the remaining
// ikl should be at least as large as the corresponding dimensions on the given data.
for(size_t idx = 0; idx < appDimensions.size(); idx++)
if(idx != axis and appDimensions[idx] > info.dsetDims.value()[idx])
throw std::runtime_error(
h5pp::format("Could not append to dataset [{}] along axis {}: Dimension {} size mismatch: data {} | dset {}",
info.dsetPath.value(),
axis,
idx,
appDimensions,
info.dsetDims.value()));
// Compute the new dset dimension. Note that dataRank <= dsetRank,
// For instance when we add a column to a matrix, the column may be an nx1 vector.
// Therefore we embed the data dimensions in a (possibly) higher-dimensional space
auto embeddedDims = std::vector<hsize_t>(static_cast<size_t>(info.dsetRank.value()), 1);
std::copy(appDimensions.begin(), appDimensions.end(), embeddedDims.begin()); // In the example above, we get nx1
auto oldAxisSize = info.dsetDims.value()[axis]; // Will need this later when drawing the hyperspace
auto newAxisSize = embeddedDims[axis]; // Will need this later when drawing the hyperspace
auto newDsetDims = info.dsetDims.value();
newDsetDims[axis] = oldAxisSize + newAxisSize;
// Set the new dimensions
std::string oldInfoStr = info.string(h5pp::logger::logIf(1));
herr_t err = H5Dset_extent(info.h5Dset.value(), newDsetDims.data());
if(err < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(h5pp::format("Failed to set extent {} on dataset [{}]", newDsetDims, info.dsetPath.value()));
}
// By default, all the space (old and new) is selected
info.dsetDims = newDsetDims;
info.h5Space = H5Dget_space(info.h5Dset->value()); // Needs to be refreshed after H5Dset_extent
info.dsetByte = h5pp::hdf5::getBytesTotal(info.h5Dset.value(), info.h5Space, info.h5Type);
info.dsetSize = h5pp::hdf5::getSize(info.h5Space.value());
info.dsetRank = h5pp::hdf5::getRank(info.h5Space.value());
// Now se select the space on the extended dataset where the given data will fit
// Draw the target space on a hyperslab
Hyperslab slab;
slab.extent = embeddedDims;
slab.offset = std::vector<hsize_t>(static_cast<size_t>(info.dsetRank.value()), 0);
slab.offset.value()[axis] = oldAxisSize;
h5pp::hdf5::selectHyperslab(info.h5Space.value(), slab);
h5pp::logger::log->debug("Extended dataset \n \t old: {} \n \t new: {}", oldInfoStr, info.string(h5pp::logger::logIf(1)));
}
}
inline void extendDataset(DsetInfo &dsetInfo, const DataInfo &dataInfo, size_t axis) {
// We use this function to EXTEND the dataset to APPEND given data
dataInfo.assertWriteReady();
extendDataset(dsetInfo, dataInfo.dataDims.value(), axis);
}
inline void
resizeDataset(DsetInfo &info, const std::vector<hsize_t> &newDimensions, std::optional<h5pp::ResizePolicy> policy = std::nullopt) {
if(info.resizePolicy == h5pp::ResizePolicy::DO_NOT_RESIZE) return;
if(not policy) policy = info.resizePolicy;
if(not policy and info.dsetSlab)
policy = h5pp::ResizePolicy::INCREASE_ONLY; // A hyperslab selection on the dataset has been made. Let's not shrink!
if(not policy) policy = h5pp::ResizePolicy::RESIZE_TO_FIT;
if(policy == h5pp::ResizePolicy::DO_NOT_RESIZE) return;
if(policy == h5pp::ResizePolicy::RESIZE_TO_FIT and info.dsetSlab){
bool outofbounds = false;
for(size_t idx = 0; idx < newDimensions.size(); idx++){
if(info.dsetSlab->extent and newDimensions[idx] < info.dsetSlab->extent->at(idx)){ outofbounds = true; break;}
if(info.dsetSlab->offset and newDimensions[idx] <= info.dsetSlab->offset->at(idx)){ outofbounds = true; break;}
}
if(outofbounds)
h5pp::logger::log->warn("A hyperslab selection was made on the dataset [{}{}]. "
"However, resize policy [RESIZE_TO_FIT] will resize this dataset to dimensions {}. "
"This is likely an error.", info.dsetPath.value(),info.dsetSlab->string(),newDimensions);
}
if(info.h5Layout and info.h5Layout.value() != H5D_CHUNKED) switch(info.h5Layout.value()) {
case H5D_COMPACT: throw std::runtime_error("Datasets with H5D_COMPACT layout cannot be resized");
case H5D_CONTIGUOUS: throw std::runtime_error("Datasets with H5D_CONTIGUOUS layout cannot be resized");
default: break;
}
if(not info.dsetPath) throw std::runtime_error("Could not resize dataset: Path undefined");
if(not info.h5Space)
throw std::runtime_error(h5pp::format("Could not resize dataset [{}]: info.h5Space undefined", info.dsetPath.value()));
if(not info.h5Type)
throw std::runtime_error(h5pp::format("Could not resize dataset [{}]: info.h5Type undefined", info.dsetPath.value()));
if(H5Sget_simple_extent_type(info.h5Space.value()) == H5S_SCALAR) return; // These are not supposed to be resized. Typically strings
if(H5Tis_variable_str(info.h5Type.value()) > 0) return; // These are resized on the fly
info.assertResizeReady();
// Return if there is no change compared to the current dimensions
if(info.dsetDims.value() == newDimensions) return;
// Compare ranks
if(info.dsetDims->size() != newDimensions.size())
throw std::runtime_error(
h5pp::format("Could not resize dataset [{}]: "
"Rank mismatch: "
"The given dimensions {} must have the same number of elements as the target dimensions {}",
info.dsetPath.value(),
info.dsetDims.value(),
newDimensions));
if(policy == h5pp::ResizePolicy::INCREASE_ONLY) {
bool allDimsAreSmaller = true;
for(size_t idx = 0; idx < newDimensions.size(); idx++)
if(newDimensions[idx] > info.dsetDims.value()[idx]) allDimsAreSmaller = false;
if(allDimsAreSmaller) return;
}
std::string oldInfoStr = info.string(h5pp::logger::logIf(1));
// Chunked datasets can shrink and grow in any direction
// Non-chunked datasets can't be resized at all
for(size_t idx = 0; idx < newDimensions.size(); idx++) {
if(newDimensions[idx] > info.dsetDimsMax.value()[idx])
throw std::runtime_error(h5pp::format(
"Could not resize dataset [{}]: "
"Dimension size error: "
"The target dimensions {} are larger than the maximum dimensions {} for this dataset. "
"Consider creating the dataset with larger maximum dimensions or use H5D_CHUNKED layout to enable unlimited resizing",
info.dsetPath.value(),
newDimensions,
info.dsetDimsMax.value()));
}
herr_t err = H5Dset_extent(info.h5Dset.value(), newDimensions.data());
if(err < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(h5pp::format(
"Failed to resize dataset [{}] from dimensions {} to {}", info.dsetPath.value(), info.dsetDims.value(), newDimensions));
}
// By default, all the space (old and new) is selected
info.dsetDims = newDimensions;
info.h5Space = H5Dget_space(info.h5Dset->value()); // Needs to be refreshed after H5Dset_extent
info.dsetByte = h5pp::hdf5::getBytesTotal(info.h5Dset.value(), info.h5Space, info.h5Type);
info.dsetSize = h5pp::hdf5::getSize(info.h5Space.value());
h5pp::logger::log->debug("Resized dataset \n \t old: {} \n \t new: {}", oldInfoStr, info.string(h5pp::logger::logIf(1)));
}
inline void resizeDataset(DsetInfo &dsetInfo, const DataInfo &dataInfo) {
// We use this function when writing to a dataset on file.
// Then we RESIZE the dataset to FIT given data.
// If there is a hyperslab selection on given data, we only need to take that into account.
// The new dataset dimensions should be dataInfo.dataDims, unless dataInfo.dataSlab.extent exists, which has priority.
// Note that the final dataset size is then determined by dsetInfo.resizePolicy
dataInfo.assertWriteReady();
if(dataInfo.dataSlab and dataInfo.dataSlab->extent) resizeDataset(dsetInfo, dataInfo.dataSlab->extent.value());
else resizeDataset(dsetInfo, dataInfo.dataDims.value());
}
template<typename DataType, typename = std::enable_if_t<not std::is_const_v<DataType>>>
inline void resizeData(DataType &data, const hid::h5s &space, const hid::h5t &type, size_t bytes) {
// This function is used when reading data from file into memory.
// It resizes the data so the space in memory can fit the data read from file.
// Note that this resizes the data to fit the bounding box of the data selected in the fileSpace.
// A selection of elements in memory space must occurr after calling this function.
if constexpr(std::is_pointer_v<DataType> or std::is_array_v<DataType>) return; // h5pp never uses malloc
if(bytes == 0) return;
if(H5Tget_class(type) == H5T_STRING) {
if constexpr(h5pp::type::sfinae::is_text_v<DataType>)
// Minus one: String resize allocates the null-terminator automatically, and bytes is the number of characters including
// null-terminator
h5pp::util::resizeData(data, {static_cast<hsize_t>(bytes) - 1});
else if constexpr(h5pp::type::sfinae::has_text_v<DataType> and h5pp::type::sfinae::is_iterable_v<DataType>) {
// We have a container such as std::vector<std::string> here, and the dataset may have multiple string elements
auto size = getSizeSelected(space);
h5pp::util::resizeData(data, {static_cast<hsize_t>(size)});
// In variable length arrays each string element is dynamically resized when read.
// For fixed-size we can resize already.
if(not H5Tis_variable_str(type)) {
auto fixedStringSize = H5Tget_size(type) - 1; // Subtract null terminator
for(auto &str : data) h5pp::util::resizeData(str, {static_cast<hsize_t>(fixedStringSize)});
}
} else {
throw std::runtime_error(h5pp::format("Could not resize given container for text data: Unrecognized type for text [{}]",
h5pp::type::sfinae::type_name<DataType>()));
}
} else if(H5Sget_simple_extent_type(space) == H5S_SCALAR)
h5pp::util::resizeData(data, {static_cast<hsize_t>(1)});
else {
int rank = H5Sget_simple_extent_ndims(space);
std::vector<hsize_t> extent(static_cast<size_t>(rank), 0); // This will have the bounding box containing the current selection
H5S_sel_type select_type = H5Sget_select_type(space);
if(select_type == H5S_sel_type::H5S_SEL_HYPERSLABS){
std::vector<hsize_t> start(static_cast<size_t>(rank), 0);
std::vector<hsize_t> end(static_cast<size_t>(rank), 0);
H5Sget_select_bounds(space,start.data(),end.data());
for(size_t idx = 0; idx < extent.size(); idx++) extent[idx] = std::max<hsize_t>(0,1 + end[idx] - start[idx]);
}else{
H5Sget_simple_extent_dims(space, extent.data(), nullptr);
}
h5pp::util::resizeData(data, extent);
if(bytes != h5pp::util::getBytesTotal(data))
h5pp::logger::log->debug(
"Size mismatch after resize: data [{}] bytes | dset [{}] bytes ", h5pp::util::getBytesTotal(data), bytes);
}
}
template<typename DataType, typename = std::enable_if_t<not std::is_const_v<DataType>>>
inline void resizeData(DataType &data, DataInfo & dataInfo, const DsetInfo &info) {
if constexpr(std::is_pointer_v<DataType> or std::is_array_v<DataType>) return; // h5pp never uses malloc
if(not info.h5Space)
throw std::runtime_error(h5pp::format("Could not resize given data container: DsetInfo field [h5Space] is not defined"));
if(not info.h5Type)
throw std::runtime_error(h5pp::format("Could not resize given data container: DsetInfo field [h5Type] is not defined"));
if(not info.dsetByte)
throw std::runtime_error(h5pp::format("Could not resize given data container: DsetInfo field [dsetByte] is not defined"));
auto oldDims = h5pp::util::getDimensions(data); // Store the old dimensions
resizeData(data, info.h5Space.value(), info.h5Type.value(), info.dsetByte.value()); // Resize the container
auto newDims = h5pp::util::getDimensions(data);
if(oldDims != newDims){
// Update the metadata
dataInfo.dataDims = h5pp::util::getDimensions(data); // Will fail if no dataDims passed on a pointer
dataInfo.dataSize = h5pp::util::getSizeFromDimensions(dataInfo.dataDims.value());
dataInfo.dataRank = h5pp::util::getRankFromDimensions(dataInfo.dataDims.value());
dataInfo.dataByte = dataInfo.dataSize.value() * h5pp::util::getBytesPerElem<DataType>();
dataInfo.h5Space = h5pp::util::getMemSpace(dataInfo.dataSize.value(), dataInfo.dataDims.value());
// Apply hyperslab selection if there is any
if(dataInfo.dataSlab) h5pp::hdf5::selectHyperslab(dataInfo.h5Space.value(), dataInfo.dataSlab.value());
}
}
template<typename DataType, typename = std::enable_if_t<not std::is_const_v<DataType>>>
inline void resizeData(DataType &data, DataInfo & dataInfo, const AttrInfo &attrInfo) {
if constexpr(std::is_pointer_v<DataType> or std::is_array_v<DataType>) return; // h5pp never uses malloc
if(not attrInfo.h5Space)
throw std::runtime_error(h5pp::format("Could not resize given data container: AttrInfo field [h5Space] is not defined"));
if(not attrInfo.h5Type)
throw std::runtime_error(h5pp::format("Could not resize given data container: AttrInfo field [h5Type] is not defined"));
if(not attrInfo.attrByte)
throw std::runtime_error(h5pp::format("Could not resize given data container: AttrInfo field [attrByte] is not defined"));
auto oldDims = h5pp::util::getDimensions(data); // Store the old dimensions
resizeData(data, attrInfo.h5Space.value(), attrInfo.h5Type.value(), attrInfo.attrByte.value()); // Resize the container
auto newDims = h5pp::util::getDimensions(data);
if(oldDims != newDims){
// Update the metadata
dataInfo.dataDims = h5pp::util::getDimensions(data); // Will fail if no dataDims passed on a pointer
dataInfo.dataSize = h5pp::util::getSizeFromDimensions(dataInfo.dataDims.value());
dataInfo.dataRank = h5pp::util::getRankFromDimensions(dataInfo.dataDims.value());
dataInfo.dataByte = dataInfo.dataSize.value() * h5pp::util::getBytesPerElem<DataType>();
dataInfo.h5Space = h5pp::util::getMemSpace(dataInfo.dataSize.value(), dataInfo.dataDims.value());
// Apply hyperslab selection if there is any
if(dataInfo.dataSlab) h5pp::hdf5::selectHyperslab(dataInfo.h5Space.value(), dataInfo.dataSlab.value());
}
}
inline std::string getSpaceString(const hid::h5s &space, bool enable = true) {
std::string msg;
if(not enable) return msg;
msg.append(h5pp::format(" | size {}", H5Sget_simple_extent_npoints(space)));
int rank = H5Sget_simple_extent_ndims(space);
std::vector<hsize_t> dims(static_cast<size_t>(rank), 0);
H5Sget_simple_extent_dims(space, dims.data(), nullptr);
msg.append(h5pp::format(" | rank {}", rank));
msg.append(h5pp::format(" | dims {}", dims));
if(H5Sget_select_type(space) == H5S_SEL_HYPERSLABS) {
Hyperslab slab(space);
msg.append(slab.string());
}
return msg;
}
inline void assertSpacesEqual(const hid::h5s &dataSpace, const hid::h5s &dsetSpace, const hid::h5t &h5Type) {
if(H5Tis_variable_str(h5Type) or H5Tget_class(h5Type) == H5T_STRING) {
// Strings are a special case, e.g. we can write multiple string elements into just one.
// Also space is allocated on the fly during read by HDF5.. so size comparisons are useless here.
return;
}
// if(h5_layout == H5D_CHUNKED) return; // Chunked layouts are allowed to differ
htri_t equal = H5Sextent_equal(dataSpace, dsetSpace);
if(equal == 0) {
H5S_sel_type dataSelType = H5Sget_select_type(dataSpace);
H5S_sel_type dsetSelType = H5Sget_select_type(dsetSpace);
if(dataSelType == H5S_sel_type::H5S_SEL_HYPERSLABS or dsetSelType == H5S_sel_type::H5S_SEL_HYPERSLABS) {
auto dataSelectedSize = getSizeSelected(dataSpace);
auto dsetSelectedSize = getSizeSelected(dsetSpace);
if(getSizeSelected(dataSpace) != getSizeSelected(dsetSpace)) {
auto msg1 = getSpaceString(dataSpace);
auto msg2 = getSpaceString(dsetSpace);
throw std::runtime_error(
h5pp::format("Hyperslab selections are not equal size. Selected elements: Data {} | Dataset {}"
"\n\t data space \t {} \n\t dset space \t {}",dataSelectedSize,dsetSelectedSize, msg1, msg2));
}
} else {
// Compare the dimensions
if(getDimensions(dataSpace) == getDimensions(dsetSpace)) return;
if(getSize(dataSpace) != getSize(dsetSpace)) {
auto msg1 = getSpaceString(dataSpace);
auto msg2 = getSpaceString(dsetSpace);
throw std::runtime_error(
h5pp::format("Spaces are not equal size \n\t data space \t {} \n\t dset space \t {}", msg1, msg2));
} else if(getDimensions(dataSpace) != getDimensions(dsetSpace)) {
h5pp::logger::log->debug("Spaces have different shape:");
h5pp::logger::log->debug(" data space {}", getSpaceString(dataSpace, h5pp::logger::logIf(1)));
h5pp::logger::log->debug(" dset space {}", getSpaceString(dsetSpace, h5pp::logger::logIf(1)));
}
}
} else if(equal < 0) {
throw std::runtime_error("Failed to compare space extents");
}
}
namespace internal {
inline long maxHits = -1;
inline long maxDepth = -1;
inline std::string searchKey;
template<H5O_type_t ObjType, typename InfoType>
inline herr_t matcher([[maybe_unused]] hid_t id, const char *name, [[maybe_unused]] const InfoType *info, void *opdata) {
// If object type is the one requested, and name matches the search key, then add it to the match list (a vector<string>)
// If the search depth is passed the depth specified, return immediately
// Return 0 to continue searching
// Return 1 to finish the search. Normally when we've reached max search hits.
std::string_view nameView(name);
if(maxDepth >= 0 and std::count(nameView.begin(), nameView.end(), '/') > maxDepth) return 0;
auto matchList = reinterpret_cast<std::vector<std::string> *>(opdata);
try {
if constexpr(std::is_same_v<InfoType, H5O_info_t>) {
if(info->type == ObjType or ObjType == H5O_TYPE_UNKNOWN) {
if(searchKey.empty() or nameView.find(searchKey) != std::string::npos) matchList->push_back(name);
}
}
else if constexpr(std::is_same_v<InfoType, H5L_info_t>) {
/* clang-format off */
// It is expensive to use H5Oopen to peek H5O_info_t::type.
// It is faster to populate H5O_info_t using
H5O_info_t oInfo;
#if defined(H5Oget_info_vers) && H5Oget_info_vers >= 2
H5Oget_info_by_name(id, name, &oInfo, H5O_INFO_BASIC, H5P_DEFAULT);
#else
H5Oget_info_by_name(id,name, &oInfo,H5P_DEFAULT);
#endif
/* clang-format on */
if(oInfo.type == ObjType or ObjType == H5O_TYPE_UNKNOWN) {
if(searchKey.empty() or nameView.find(searchKey) != std::string::npos) matchList->push_back(name);
}
} else {
if(searchKey.empty() or nameView.find(searchKey) != std::string::npos) { matchList->push_back(name); }
}
if(maxHits > 0 and static_cast<long>(matchList->size()) >= maxHits)
return 1;
else
return 0;
} catch(...) { throw std::logic_error(h5pp::format("Could not match object [{}] | loc_id [{}]", name, id)); }
}
template<H5O_type_t ObjType>
[[nodiscard]] inline constexpr std::string_view getObjTypeName() {
if constexpr(ObjType == H5O_type_t::H5O_TYPE_DATASET)
return "dataset";
else if constexpr(ObjType == H5O_type_t::H5O_TYPE_GROUP)
return "group";
else if constexpr(ObjType == H5O_type_t::H5O_TYPE_UNKNOWN)
return "unknown";
else if constexpr(ObjType == H5O_type_t::H5O_TYPE_NAMED_DATATYPE)
return "named datatype";
else if constexpr(ObjType == H5O_type_t::H5O_TYPE_NTYPES)
return "ntypes";
else
return "map"; // Only in HDF5 v 1.12
}
template<H5O_type_t ObjType, typename h5x>
herr_t H5L_custom_iterate_by_name(const h5x & loc,
std::string_view root,
std::vector<std::string> &matchList,
const hid::h5p & linkAccess = H5P_DEFAULT) {
H5Eset_auto(H5E_DEFAULT, nullptr, nullptr); // Silence the error we get from using index directly
constexpr size_t maxsize = 512;
char linkname[maxsize] = {};
H5O_info_t oInfo;
/* clang-format off */
for(hsize_t idx = 0; idx < 100000000; idx++) {
ssize_t namesize = H5Lget_name_by_idx(loc, util::safe_str(root).c_str(), H5_index_t::H5_INDEX_NAME,
H5_iter_order_t::H5_ITER_NATIVE, idx,linkname,maxsize,linkAccess);
if(namesize <= 0) {
H5Eclear(H5E_DEFAULT);
break;
}
std::string_view nameView(linkname, static_cast<size_t>(namesize));
if(ObjType == H5O_TYPE_UNKNOWN) {
// Accept based on name
if(searchKey.empty() or nameView.find(searchKey) != std::string::npos) matchList.emplace_back(linkname);
if(maxHits > 0 and static_cast<long>(matchList.size()) >= maxHits) return 0;
} else {
// Name is not enough to establish a match. Check type.
#if defined(H5Oget_info_by_idx_vers) && H5Oget_info_by_idx_vers >= 2
herr_t res = H5Oget_info_by_idx(loc, util::safe_str(root).c_str(),
H5_index_t::H5_INDEX_NAME, H5_iter_order_t::H5_ITER_NATIVE,
idx, &oInfo, H5O_INFO_BASIC,linkAccess );
#else
herr_t res = H5Oget_info_by_idx(loc, util::safe_str(root).c_str(),
H5_index_t::H5_INDEX_NAME, H5_iter_order_t::H5_ITER_NATIVE,
idx, &oInfo, linkAccess );
#endif
if(res < 0) {
H5Eclear(H5E_DEFAULT);
break;
}
if(oInfo.type == ObjType and (searchKey.empty() or nameView.find(searchKey) != std::string::npos))
matchList.emplace_back(linkname);
if(maxHits > 0 and static_cast<long>(matchList.size()) >= maxHits) return 0;
}
}
/* clang-format on */
return 0;
}
template<H5O_type_t ObjType, typename h5x>
inline herr_t visit_by_name(const h5x & loc,
std::string_view root,
std::vector<std::string> &matchList,
const hid::h5p & linkAccess = H5P_DEFAULT) {
static_assert(h5pp::type::sfinae::is_h5_loc_or_hid_v<h5x>,
"Template function [h5pp::hdf5::visit_by_name(const h5x & loc, ...)] requires type h5x to be: "
"[h5pp::hid::h5f], [h5pp::hid::h5g], [h5pp::hid::h5o] or [hid_t]");
if(internal::maxDepth == 0)
// Faster when we don't need to iterate recursively
return H5L_custom_iterate_by_name<ObjType>(loc, root, matchList, linkAccess);
// return H5Literate_by_name(loc,
// util::safe_str(root).c_str(),
// H5_index_t::H5_INDEX_NAME,
// H5_iter_order_t::H5_ITER_NATIVE,
// nullptr,
// internal::matcher<ObjType>,
// &matchList,
// linkAccess);
#if defined(H5Ovisit_by_name_vers) && H5Ovisit_by_name_vers >= 2
return H5Ovisit_by_name(loc,
util::safe_str(root).c_str(),
H5_INDEX_NAME,
H5_ITER_NATIVE,
internal::matcher<ObjType>,
&matchList,
H5O_INFO_BASIC,
linkAccess);
#else
return H5Ovisit_by_name(
loc, util::safe_str(root).c_str(), H5_INDEX_NAME, H5_ITER_NATIVE, internal::matcher<ObjType>, &matchList, linkAccess);
#endif
}
}
template<H5O_type_t ObjType, typename h5x>
[[nodiscard]] inline std::vector<std::string> findLinks(const h5x & loc,
std::string_view searchKey = "",
std::string_view searchRoot = "/",
long maxHits = -1,
long maxDepth = -1,
const hid::h5p & linkAccess = H5P_DEFAULT) {
h5pp::logger::log->trace("Search key: {} | target type: {} | search root: {} | max search hits {}",
searchKey,
internal::getObjTypeName<ObjType>(),
searchRoot,
maxHits);
std::vector<std::string> matchList;
internal::maxHits = maxHits;
internal::maxDepth = maxDepth;
internal::searchKey = searchKey;
herr_t err = internal::visit_by_name<ObjType>(loc, searchRoot, matchList, linkAccess);
if(err < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(h5pp::format(
"Failed to find links of type [{}] while iterating from root [{}]", internal::getObjTypeName<ObjType>(), searchRoot));
}
return matchList;
}
template<H5O_type_t ObjType, typename h5x>
[[nodiscard]] inline std::vector<std::string>
getContentsOfLink(const h5x &loc, std::string_view linkPath, long maxDepth = 1, const hid::h5p &linkAccess = H5P_DEFAULT) {
std::vector<std::string> contents;
internal::maxHits = -1;
internal::maxDepth = maxDepth;
internal::searchKey.clear();
herr_t err = internal::visit_by_name<ObjType>(loc, linkPath, contents, linkAccess);
if(err < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(
h5pp::format("Failed to iterate link [{}] of type [{}]", linkPath, internal::getObjTypeName<ObjType>()));
}
return contents;
}
inline void createDataset(h5pp::DsetInfo &dsetInfo, const PropertyLists &plists = PropertyLists()) {
// Here we create, the dataset id and set its properties before writing data to it.
dsetInfo.assertCreateReady();
if(dsetInfo.dsetExists and dsetInfo.dsetExists.value()) {
h5pp::logger::log->trace("No need to create dataset [{}]: exists already", dsetInfo.dsetPath.value());
return;
}
h5pp::logger::log->debug("Creating dataset {}", dsetInfo.string(h5pp::logger::logIf(1)));
hid_t dsetId = H5Dcreate(dsetInfo.getLocId(),
util::safe_str(dsetInfo.dsetPath.value()).c_str(),
dsetInfo.h5Type.value(),
dsetInfo.h5Space.value(),
plists.linkCreate,
dsetInfo.h5PlistDsetCreate.value(),
dsetInfo.h5PlistDsetAccess.value());
if(dsetId <= 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(h5pp::format("Failed to create dataset {}", dsetInfo.string()));
}
dsetInfo.h5Dset = dsetId;
dsetInfo.dsetExists = true;
}
inline void createAttribute(AttrInfo &attrInfo) {
// Here we create, or register, the attribute id and set its properties before writing data to it.
attrInfo.assertCreateReady();
if(attrInfo.attrExists and attrInfo.attrExists.value()) {
h5pp::logger::log->trace(
"No need to create attribute [{}] in link [{}]: exists already", attrInfo.attrName.value(), attrInfo.linkPath.value());
return;
}
h5pp::logger::log->trace("Creating attribute {}", attrInfo.string(h5pp::logger::logIf(0)));
hid_t attrId = H5Acreate(attrInfo.h5Link.value(),
util::safe_str(attrInfo.attrName.value()).c_str(),
attrInfo.h5Type.value(),
attrInfo.h5Space.value(),
attrInfo.h5PlistAttrCreate.value(),
attrInfo.h5PlistAttrAccess.value());
if(attrId <= 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(
h5pp::format("Failed to create attribute [{}] for link [{}]", attrInfo.attrName.value(), attrInfo.linkPath.value()));
}
attrInfo.h5Attr = attrId;
attrInfo.attrExists = true;
}
template<typename DataType>
[[nodiscard]] std::vector<const char *> getCharPtrVector(const DataType &data) {
std::vector<const char *> sv;
if constexpr(h5pp::type::sfinae::is_text_v<DataType> and h5pp::type::sfinae::has_data_v<DataType>) // Takes care of std::string
sv.push_back(data.data());
else if constexpr(h5pp::type::sfinae::is_text_v<DataType>) // Takes care of char pointers and arrays
sv.push_back(data);
else if constexpr(h5pp::type::sfinae::is_iterable_v<DataType>) // Takes care of containers with text
for(auto &elem : data) {
if constexpr(h5pp::type::sfinae::is_text_v<decltype(elem)> and
h5pp::type::sfinae::has_data_v<decltype(elem)>) // Takes care of containers with std::string
sv.push_back(elem.data());
else if constexpr(h5pp::type::sfinae::is_text_v<decltype(elem)>) // Takes care of containers of char pointers and arrays
sv.push_back(elem);
else
sv.push_back(&elem); // Takes care of other things?
}
else
throw std::runtime_error(
h5pp::format("Failed to get char pointer of datatype [{}]", h5pp::type::sfinae::type_name<DataType>()));
return sv;
}
template<typename DataType>
void writeDataset(const DataType & data,
const DataInfo & dataInfo,
const DsetInfo & dsetInfo,
const PropertyLists &plists = PropertyLists()) {
#ifdef H5PP_EIGEN3
if constexpr(h5pp::type::sfinae::is_eigen_colmajor_v<DataType> and not h5pp::type::sfinae::is_eigen_1d_v<DataType>) {
h5pp::logger::log->debug("Converting data to row-major storage order");
const auto tempRowm = eigen::to_RowMajor(data); // Convert to Row Major first;
h5pp::hdf5::writeDataset(tempRowm, dataInfo, dsetInfo, plists);
return;
}
#endif
dsetInfo.assertWriteReady();
dataInfo.assertWriteReady();
h5pp::logger::log->debug("Writing from memory {}", dataInfo.string(h5pp::logger::logIf(1)));
h5pp::logger::log->debug("Writing into dataset {}", dsetInfo.string(h5pp::logger::logIf(1)));
h5pp::hdf5::assertWriteBufferIsLargeEnough(data, dataInfo.h5Space.value(), dsetInfo.h5Type.value());
h5pp::hdf5::assertBytesPerElemMatch<DataType>(dsetInfo.h5Type.value());
h5pp::hdf5::assertSpacesEqual(dataInfo.h5Space.value(), dsetInfo.h5Space.value(), dsetInfo.h5Type.value());
herr_t retval = 0;
// Get the memory address to the data buffer
auto dataPtr = h5pp::util::getVoidPointer<const void *>(data);
if constexpr(h5pp::type::sfinae::is_text_v<DataType> or h5pp::type::sfinae::has_text_v<DataType>) {
auto vec = getCharPtrVector(data);
// When H5T_VARIABLE, this function expects [const char **], which is what we get from vec.data()
if(H5Tis_variable_str(dsetInfo.h5Type->value()) > 0)
retval = H5Dwrite(dsetInfo.h5Dset.value(),
dsetInfo.h5Type.value(),
dataInfo.h5Space.value(),
dsetInfo.h5Space.value(),
plists.dsetXfer,
vec.data());
else {
if(vec.size() == 1) {
retval = H5Dwrite(dsetInfo.h5Dset.value(),
dsetInfo.h5Type.value(),
dataInfo.h5Space.value(),
dsetInfo.h5Space.value(),
plists.dsetXfer,
*vec.data());
} else {
if constexpr(h5pp::type::sfinae::has_text_v<DataType> and h5pp::type::sfinae::is_iterable_v<DataType>) {
// We have a fixed-size string array now. We have to copy the strings to a contiguous array.
// vdata already contains the pointer to each string, and bytes should be the size of the whole array
// including null terminators. so
std::string strContiguous;
size_t bytesPerStr = H5Tget_size(dsetInfo.h5Type.value()); // Includes null term
strContiguous.resize(bytesPerStr * vec.size());
for(size_t i = 0; i < vec.size(); i++) {
auto start_src = strContiguous.data() + static_cast<long>(i * bytesPerStr);
// Construct a view of the null-terminated character string, not including the null character.
auto view = std::string_view(vec[i]); // view.size() will not include null term here!
std::copy_n(std::begin(view), std::min(view.size(),bytesPerStr - 1),start_src); // Do not copy null character
}
retval = H5Dwrite(dsetInfo.h5Dset.value(),
dsetInfo.h5Type.value(),
dataInfo.h5Space.value(),
dsetInfo.h5Space.value(),
plists.dsetXfer,
strContiguous.data());
} else {
// Assume contigous array and hope for the best
retval = H5Dwrite(dsetInfo.h5Dset.value(),
dsetInfo.h5Type.value(),
dataInfo.h5Space.value(),
dsetInfo.h5Space.value(),
plists.dsetXfer,
dataPtr);
}
}
}
} else
retval = H5Dwrite(dsetInfo.h5Dset.value(),
dsetInfo.h5Type.value(),
dataInfo.h5Space.value(),
dsetInfo.h5Space.value(),
plists.dsetXfer,
dataPtr);
if(retval < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(
h5pp::format("Failed to write into dataset \n\t {} \n from memory \n\t {}", dsetInfo.string(), dataInfo.string()));
}
}
template<typename DataType, typename = std::enable_if_t<not std::is_const_v<DataType>>>
void readDataset(DataType &data, const DataInfo &dataInfo, const DsetInfo &dsetInfo, const PropertyLists &plists = PropertyLists()) {
// Transpose the data container before reading
#ifdef H5PP_EIGEN3
if constexpr(h5pp::type::sfinae::is_eigen_colmajor_v<DataType> and not h5pp::type::sfinae::is_eigen_1d_v<DataType>) {
h5pp::logger::log->debug("Converting data to row-major storage order");
auto tempRowMajor = eigen::to_RowMajor(data); // Convert to Row Major first;
h5pp::hdf5::readDataset(tempRowMajor, dataInfo, dsetInfo, plists);
data = eigen::to_ColMajor(tempRowMajor);
return;
}
#endif
dsetInfo.assertReadReady();
dataInfo.assertReadReady();
h5pp::logger::log->debug("Reading into memory {}", dataInfo.string(h5pp::logger::logIf(1)));
h5pp::logger::log->debug("Reading from dataset {}", dsetInfo.string(h5pp::logger::logIf(1)));
h5pp::hdf5::assertReadTypeIsLargeEnough<DataType>(dsetInfo.h5Type.value());
h5pp::hdf5::assertReadSpaceIsLargeEnough(data, dataInfo.h5Space.value(), dsetInfo.h5Type.value());
h5pp::hdf5::assertSpacesEqual(dataInfo.h5Space.value(), dsetInfo.h5Space.value(), dsetInfo.h5Type.value());
// h5pp::hdf5::assertBytesPerElemMatch<DataType>(dsetInfo.h5Type.value());
herr_t retval = 0;
// Get the memory address to the data buffer
[[maybe_unused]] auto dataPtr = h5pp::util::getVoidPointer<void *>(data);
// Read the data
if constexpr(h5pp::type::sfinae::is_text_v<DataType> or h5pp::type::sfinae::has_text_v<DataType>) {
// When H5T_VARIABLE,
// 1) H5Dread expects [const char **], which is what we get from vdata.data().
// 2) H5Dread allocates memory on each const char * which has to be reclaimed later.
// Otherwise,
// 1) H5Dread expects [char *], i.e. *vdata.data()
// 2) Allocation on char * must be done before reading.
if(H5Tis_variable_str(dsetInfo.h5Type.value())) {
auto size = H5Sget_select_npoints(dsetInfo.h5Space.value());
std::vector<char *> vdata(static_cast<size_t>(size)); // Allocate pointers for "size" number of strings
// HDF5 allocates space for each string in vdata
retval = H5Dread(
dsetInfo.h5Dset.value(), dsetInfo.h5Type.value(), H5S_ALL, dsetInfo.h5Space.value(), plists.dsetXfer, vdata.data());
// Now vdata contains the whole dataset and we need to put the data into the user-given container.
if constexpr(std::is_same_v<DataType, std::string>) {
// A vector of strings (vdata) can be put into a single string (data) with entries separated by new-lines
data.clear();
for(size_t i = 0; i < vdata.size(); i++) {
if(!vdata.empty() and vdata[i] != nullptr) data.append(vdata[i]);
if(i < vdata.size() - 1) data.append("\n");
}
} else if constexpr(h5pp::type::sfinae::is_container_of_v<DataType, std::string> and
h5pp::type::sfinae::has_resize_v<DataType>) {
data.clear();
data.resize(vdata.size());
for(size_t i = 0; i < data.size(); i++) data[i] = std::string(vdata[i]);
} else {
throw std::runtime_error(
"To read text-data, please use std::string or a container of std::string like std::vector<std::string>");
}
// Free memory allocated by HDF5
H5Dvlen_reclaim(dsetInfo.h5Type.value(), dsetInfo.h5Space.value(), plists.dsetXfer, vdata.data());
} else {
// All the elements in the dataset have the same string size
// The whole dataset is read into a contiguous block of memory.
size_t bytesPerString = H5Tget_size(dsetInfo.h5Type.value()); // Includes null terminator
auto size = H5Sget_select_npoints(dsetInfo.h5Space.value());
std::string fdata;
fdata.resize(static_cast<size_t>(size) * bytesPerString);
retval = H5Dread(dsetInfo.h5Dset.value(),
dsetInfo.h5Type.value(),
dataInfo.h5Space.value(),
dsetInfo.h5Space.value(),
plists.dsetXfer,
fdata.data());
// Now fdata contains the whole dataset and we need to put the data into the user-given container.
if constexpr(std::is_same_v<DataType, std::string>) {
// A vector of strings (fdata) can be put into a single string (data) with entries separated by new-lines
data.clear();
for(size_t i = 0; i < static_cast<size_t>(size); i++) {
data.append(fdata.substr(i * bytesPerString, bytesPerString));
if(data.size() < fdata.size() - 1) data.append("\n");
}
data.erase(std::find(data.begin(), data.end(), '\0'), data.end()); // Prune all but the last null terminator
} else if constexpr(h5pp::type::sfinae::is_container_of_v<DataType, std::string> and
h5pp::type::sfinae::has_resize_v<DataType>) {
if(data.size() != static_cast<size_t>(size))
throw std::runtime_error(h5pp::format(
"Given container of strings has the wrong size: dset size {} | container size {}", size, data.size()));
for(size_t i = 0; i < static_cast<size_t>(size); i++) {
// Each data[i] has type std::string, so we can use the std::string constructor to copy data
data[i] = std::string(fdata.data()+i*bytesPerString,bytesPerString);
// Prune away all null terminators except the last one
data[i].erase(std::find(data[i].begin(), data[i].end(), '\0'),
data[i].end());
}
} else {
throw std::runtime_error(
"To read text-data, please use std::string or a container of std::string like std::vector<std::string>");
}
}
} else
retval = H5Dread(dsetInfo.h5Dset.value(),
dsetInfo.h5Type.value(),
dataInfo.h5Space.value(),
dsetInfo.h5Space.value(),
plists.dsetXfer,
dataPtr);
if(retval < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(
h5pp::format("Failed to read from dataset \n\t {} \n into memory \n\t {}", dsetInfo.string(), dataInfo.string()));
}
}
template<typename DataType>
void writeAttribute(const DataType &data, const DataInfo &dataInfo, const AttrInfo &attrInfo) {
#ifdef H5PP_EIGEN3
if constexpr(h5pp::type::sfinae::is_eigen_colmajor_v<DataType> and not h5pp::type::sfinae::is_eigen_1d_v<DataType>) {
h5pp::logger::log->debug("Converting attribute data to row-major storage order");
const auto tempRowm = eigen::to_RowMajor(data); // Convert to Row Major first;
h5pp::hdf5::writeAttribute(tempRowm, dataInfo, attrInfo);
return;
}
#endif
dataInfo.assertWriteReady();
attrInfo.assertWriteReady();
h5pp::logger::log->debug("Writing from memory {}", dataInfo.string(h5pp::logger::logIf(1)));
h5pp::logger::log->debug("Writing into attribute {}", attrInfo.string(h5pp::logger::logIf(1)));
h5pp::hdf5::assertWriteBufferIsLargeEnough(data, dataInfo.h5Space.value(), attrInfo.h5Type.value());
h5pp::hdf5::assertBytesPerElemMatch<DataType>(attrInfo.h5Type.value());
h5pp::hdf5::assertSpacesEqual(dataInfo.h5Space.value(), attrInfo.h5Space.value(), attrInfo.h5Type.value());
herr_t retval = 0;
// Get the memory address to the data buffer
[[maybe_unused]] auto dataPtr = h5pp::util::getVoidPointer<const void *>(data);
if constexpr(h5pp::type::sfinae::is_text_v<DataType> or h5pp::type::sfinae::has_text_v<DataType>) {
auto vec = getCharPtrVector(data);
if(H5Tis_variable_str(attrInfo.h5Type->value()) > 0)
retval = H5Awrite(attrInfo.h5Attr.value(), attrInfo.h5Type.value(), vec.data());
else
retval = H5Awrite(attrInfo.h5Attr.value(), attrInfo.h5Type.value(), *vec.data());
} else
retval = H5Awrite(attrInfo.h5Attr.value(), attrInfo.h5Type.value(), dataPtr);
if(retval < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(
h5pp::format("Failed to write into attribute \n\t {} \n from memory \n\t {}", attrInfo.string(), dataInfo.string()));
}
}
template<typename DataType, typename = std::enable_if_t<not std::is_const_v<DataType>>>
void readAttribute(DataType &data, const DataInfo &dataInfo, const AttrInfo &attrInfo) {
// Transpose the data container before reading
#ifdef H5PP_EIGEN3
if constexpr(h5pp::type::sfinae::is_eigen_colmajor_v<DataType> and not h5pp::type::sfinae::is_eigen_1d_v<DataType>) {
h5pp::logger::log->debug("Converting data to row-major storage order");
auto tempRowMajor = eigen::to_RowMajor(data); // Convert to Row Major first;
h5pp::hdf5::readAttribute(tempRowMajor, dataInfo, attrInfo);
data = eigen::to_ColMajor(tempRowMajor);
return;
}
#endif
dataInfo.assertReadReady();
attrInfo.assertReadReady();
h5pp::logger::log->debug("Reading into memory {}", dataInfo.string(h5pp::logger::logIf(1)));
h5pp::logger::log->debug("Reading from file {}", attrInfo.string(h5pp::logger::logIf(1)));
h5pp::hdf5::assertReadSpaceIsLargeEnough(data, dataInfo.h5Space.value(), attrInfo.h5Type.value());
h5pp::hdf5::assertBytesPerElemMatch<DataType>(attrInfo.h5Type.value());
h5pp::hdf5::assertSpacesEqual(dataInfo.h5Space.value(), attrInfo.h5Space.value(), attrInfo.h5Type.value());
herr_t retval = 0;
// Get the memory address to the data buffer
[[maybe_unused]] auto dataPtr = h5pp::util::getVoidPointer<void *>(data);
// Read the data
if constexpr(h5pp::type::sfinae::is_text_v<DataType> or h5pp::type::sfinae::has_text_v<DataType>) {
// When H5T_VARIABLE,
// 1) H5Aread expects [const char **], which is what we get from vdata.data().
// 2) H5Aread allocates memory on each const char * which has to be reclaimed later.
// Otherwise,
// 1) H5Aread expects [char *], i.e. *vdata.data()
// 2) Allocation on char * must be done before reading.
if(H5Tis_variable_str(attrInfo.h5Type.value()) > 0) {
auto size = H5Sget_select_npoints(attrInfo.h5Space.value());
std::vector<char *> vdata(static_cast<size_t>(size)); // Allocate pointers for "size" number of strings
// HDF5 allocates space for each string
retval = H5Aread(attrInfo.h5Attr.value(), attrInfo.h5Type.value(), vdata.data());
// Now vdata contains the whole dataset and we need to put the data into the user-given container.
if constexpr(std::is_same_v<DataType, std::string>) {
// A vector of strings (vdata) can be put into a single string (data) with entries separated by new-lines
data.clear();
for(size_t i = 0; i < vdata.size(); i++) {
if(!vdata.empty() and vdata[i] != nullptr) data.append(vdata[i]);
if(i < vdata.size() - 1) data.append("\n");
}
} else if constexpr(h5pp::type::sfinae::is_container_of_v<DataType, std::string> and
h5pp::type::sfinae::has_resize_v<DataType>) {
data.clear();
data.resize(vdata.size());
for(size_t i = 0; i < data.size(); i++) data[i] = std::string(vdata[i]);
} else {
throw std::runtime_error(
"To read text-data, please use std::string or a container of std::string like std::vector<std::string>");
}
// Free memory allocated by HDF5
H5Dvlen_reclaim(attrInfo.h5Type.value(), attrInfo.h5Space.value(), H5P_DEFAULT, vdata.data());
} else {
// All the elements in the dataset have the same string size
// The whole dataset is read into a contiguous block of memory.
size_t bytesPerString = H5Tget_size(attrInfo.h5Type.value()); // Includes null terminator
auto size = H5Sget_select_npoints(attrInfo.h5Space.value());
std::string fdata;
fdata.resize(static_cast<size_t>(size) * bytesPerString);
retval = H5Aread(attrInfo.h5Attr.value(), attrInfo.h5Type.value(), fdata.data());
// Now fdata contains the whole dataset and we need to put the data into the user-given container.
if constexpr(std::is_same_v<DataType, std::string>) {
// A vector of strings (fdata) can be put into a single string (data) with entries separated by new-lines
data.clear();
for(size_t i = 0; i < static_cast<size_t>(size); i++) {
data.append(fdata.substr(i * bytesPerString, bytesPerString));
if(data.size() < fdata.size() - 1) data.append("\n");
}
} else if constexpr(h5pp::type::sfinae::is_container_of_v<DataType, std::string> and
h5pp::type::sfinae::has_resize_v<DataType>) {
data.clear();
data.resize(static_cast<size_t>(size));
for(size_t i = 0; i < static_cast<size_t>(size); i++) data[i] = fdata.substr(i * bytesPerString, bytesPerString);
} else {
throw std::runtime_error(
"To read text-data, please use std::string or a container of std::string like std::vector<std::string>");
}
}
if constexpr(std::is_same_v<DataType, std::string>) {
data.erase(std::find(data.begin(), data.end(), '\0'), data.end()); // Prune all but the last null terminator
}
} else
retval = H5Aread(attrInfo.h5Attr.value(), attrInfo.h5Type.value(), dataPtr);
if(retval < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(
h5pp::format("Failed to read from attribute \n\t {} \n into memory \n\t {}", attrInfo.string(), dataInfo.string()));
}
}
[[nodiscard]] inline bool fileIsValid(const fs::path &filePath) {
return fs::exists(filePath) and H5Fis_hdf5(filePath.string().c_str()) > 0;
}
[[nodiscard]] inline fs::path getAvailableFileName(const fs::path &filePath) {
int i = 1;
fs::path newFileName = filePath;
while(fs::exists(newFileName)) {
newFileName.replace_filename(filePath.stem().string() + "-" + std::to_string(i++) + filePath.extension().string());
}
return newFileName;
}
[[nodiscard]] inline fs::path getBackupFileName(const fs::path &filePath) {
int i = 1;
fs::path newFilePath = filePath;
while(fs::exists(newFilePath)) { newFilePath.replace_extension(filePath.extension().string() + ".bak_" + std::to_string(i++)); }
return newFilePath;
}
[[nodiscard]] inline h5pp::FilePermission convertFileAccessFlags(unsigned int H5F_ACC_FLAGS) {
h5pp::FilePermission permission = h5pp::FilePermission::RENAME;
if((H5F_ACC_FLAGS & (H5F_ACC_TRUNC | H5F_ACC_EXCL)) == (H5F_ACC_TRUNC | H5F_ACC_EXCL))
throw std::runtime_error("File access modes H5F_ACC_EXCL and H5F_ACC_TRUNC are mutually exclusive");
if((H5F_ACC_FLAGS & H5F_ACC_RDONLY) == H5F_ACC_RDONLY) permission = h5pp::FilePermission::READONLY;
if((H5F_ACC_FLAGS & H5F_ACC_RDWR) == H5F_ACC_RDWR) permission = h5pp::FilePermission::READWRITE;
if((H5F_ACC_FLAGS & H5F_ACC_EXCL) == H5F_ACC_EXCL) permission = h5pp::FilePermission::COLLISION_FAIL;
if((H5F_ACC_FLAGS & H5F_ACC_TRUNC) == H5F_ACC_TRUNC) permission = h5pp::FilePermission::REPLACE;
return permission;
}
[[nodiscard]] inline unsigned int convertFileAccessFlags(h5pp::FilePermission permission) {
unsigned int H5F_ACC_MODE = H5F_ACC_RDONLY;
if(permission == h5pp::FilePermission::COLLISION_FAIL) H5F_ACC_MODE |= H5F_ACC_EXCL;
if(permission == h5pp::FilePermission::REPLACE) H5F_ACC_MODE |= H5F_ACC_TRUNC;
if(permission == h5pp::FilePermission::RENAME) H5F_ACC_MODE |= H5F_ACC_TRUNC;
if(permission == h5pp::FilePermission::READONLY) H5F_ACC_MODE |= H5F_ACC_RDONLY;
if(permission == h5pp::FilePermission::READWRITE) H5F_ACC_MODE |= H5F_ACC_RDWR;
return H5F_ACC_MODE;
}
[[nodiscard]] inline fs::path
createFile(const h5pp::fs::path &filePath_, const h5pp::FilePermission &permission, const PropertyLists &plists = PropertyLists()) {
fs::path filePath = fs::absolute(filePath_);
fs::path fileName = filePath_.filename();
if(fs::exists(filePath)) {
if(not fileIsValid(filePath)) h5pp::logger::log->debug("Pre-existing file may be corrupted [{}]", filePath.string());
if(permission == h5pp::FilePermission::READONLY) return filePath;
if(permission == h5pp::FilePermission::COLLISION_FAIL)
throw std::runtime_error(h5pp::format("[COLLISION_FAIL]: Previous file exists with the same name [{}]", filePath.string()));
if(permission == h5pp::FilePermission::RENAME) {
auto newFilePath = getAvailableFileName(filePath);
h5pp::logger::log->info("[RENAME]: Previous file exists. Choosing a new file name [{}] --> [{}]",
filePath.filename().string(),
newFilePath.filename().string());
filePath = newFilePath;
fileName = filePath.filename();
}
if(permission == h5pp::FilePermission::READWRITE) return filePath;
if(permission == h5pp::FilePermission::BACKUP) {
auto backupPath = getBackupFileName(filePath);
h5pp::logger::log->info(
"[BACKUP]: Backing up existing file [{}] --> [{}]", filePath.filename().string(), backupPath.filename().string());
fs::rename(filePath, backupPath);
}
if(permission == h5pp::FilePermission::REPLACE) {} // Do nothing
} else {
if(permission == h5pp::FilePermission::READONLY)
throw std::runtime_error(h5pp::format("[READONLY]: File does not exist [{}]", filePath.string()));
if(permission == h5pp::FilePermission::COLLISION_FAIL) {} // Do nothing
if(permission == h5pp::FilePermission::RENAME) {} // Do nothing
if(permission == h5pp::FilePermission::READWRITE) {} // Do nothing;
if(permission == h5pp::FilePermission::BACKUP) {} // Do nothing
if(permission == h5pp::FilePermission::REPLACE) {} // Do nothing
try {
if(fs::create_directories(filePath.parent_path()))
h5pp::logger::log->trace("Created directory: {}", filePath.parent_path().string());
else
h5pp::logger::log->trace("Directory already exists: {}", filePath.parent_path().string());
} catch(std::exception &ex) { throw std::runtime_error(h5pp::format("Failed to create directory: {}", ex.what())); }
}
// One last sanity check
if(permission == h5pp::FilePermission::READONLY)
throw std::logic_error("About to create/truncate a file even though READONLY was specified. This is a programming error!");
// Go ahead
hid_t file = H5Fcreate(filePath.string().c_str(), H5F_ACC_TRUNC, plists.fileCreate, plists.fileAccess);
if(file < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(h5pp::format("Failed to create file [{}]\n\t\t Check that you have the right permissions and that the "
"file is not locked by another program",
filePath.string()));
}
H5Fclose(file);
return fs::canonical(filePath);
}
inline void createTable(TableInfo &info, const PropertyLists &plists = PropertyLists()) {
info.assertCreateReady();
h5pp::logger::log->debug("Creating table [{}] | num fields {} | record size {} bytes",
info.tablePath.value(),
info.numFields.value(),
info.recordBytes.value());
if(not info.tableExists) info.tableExists = checkIfLinkExists(info.getLocId(), info.tablePath.value(), plists.linkAccess);
if(info.tableExists.value()) {
h5pp::logger::log->debug("Table [{}] already exists", info.tablePath.value());
return;
}
createGroup(info.getLocId(),
info.tableGroupName.value(),
std::nullopt,
plists); // The existence of the group has to be checked, unfortunately
// Copy member type data to a vector of hid_t for compatibility.
// Note that there is no need to close thes hid_t since info will close them.
std::vector<hid_t> fieldTypesHidT(info.fieldTypes.value().begin(), info.fieldTypes.value().end());
// Copy member name data to a vector of const char * for compatibility
std::vector<const char *> fieldNames;
for(auto &name : info.fieldNames.value()) fieldNames.push_back(name.c_str());
int compression = info.compressionLevel.value() == 0 ? 0 : 1; // Only true/false (1/0). Is set to level 6 in HDF5 sources
herr_t retval = H5TBmake_table(util::safe_str(info.tableTitle.value()).c_str(),
info.getLocId(),
util::safe_str(info.tablePath.value()).c_str(),
info.numFields.value(),
info.numRecords.value(),
info.recordBytes.value(),
fieldNames.data(),
info.fieldOffsets.value().data(),
fieldTypesHidT.data(),
info.chunkSize.value(),
nullptr,
compression,
nullptr);
if(retval < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(h5pp::format("Could not create table [{}]", info.tablePath.value()));
}
h5pp::logger::log->trace("Successfully created table [{}]", info.tablePath.value());
info.tableExists = true;
}
template<typename DataType, typename = std::enable_if_t<not std::is_const_v<DataType>>>
inline void readTableRecords(DataType & data,
const TableInfo & info,
std::optional<size_t> startIdx = std::nullopt,
std::optional<size_t> numReadRecords = std::nullopt) {
/*
* This function replaces H5TBread_records() and avoids creating expensive temporaries for the dataset id and type id for the
* compound table type.
*
*/
// If none of startIdx or numReadRecords are given:
// If data resizeable: startIdx = 0, numReadRecords = totalRecords
// If data not resizeable: startIdx = last record, numReadRecords = 1.
// If startIdx given but numReadRecords is not:
// If data resizeable -> read from startIdx to the end
// If data not resizeable -> read a single record starting from startIdx
// If numReadRecords given but startIdx is not -> read the last numReadRecords records
info.assertReadReady();
if constexpr(std::is_same_v<DataType, std::vector<std::byte>>) {
if(not numReadRecords)
throw std::runtime_error("Optional argument [numReadRecords] is required when reading std::vector<std::byte> from table");
}
if(not startIdx and not numReadRecords) {
if constexpr(h5pp::type::sfinae::has_resize_v<DataType>) {
startIdx = 0;
numReadRecords = info.numRecords.value();
} else {
startIdx = info.numRecords.value() - 1;
numReadRecords = 1;
}
} else if(startIdx and not numReadRecords) {
if(startIdx.value() > info.numRecords.value() - 1)
throw std::runtime_error(h5pp::format("Invalid start index {} for table [{}] | total records {}",
startIdx.value(),
info.tablePath.value(),
info.numRecords.value()));
if constexpr(h5pp::type::sfinae::has_resize_v<DataType>) {
numReadRecords = info.numRecords.value() - startIdx.value();
} else {
numReadRecords = 1;
}
} else if(numReadRecords and not startIdx) {
if(numReadRecords.value() > info.numRecords.value())
throw std::logic_error(h5pp::format("Cannot read {} records from table [{}] which only has {} records",
numReadRecords.value(),
info.tablePath.value(),
info.numRecords.value()));
startIdx = info.numRecords.value() - numReadRecords.value();
}
// Sanity check
if(numReadRecords.value() > info.numRecords.value())
throw std::logic_error(h5pp::format("Cannot read {} records from table [{}] which only has {} records",
numReadRecords.value(),
info.tablePath.value(),
info.numRecords.value()));
if(startIdx.value() + numReadRecords.value() > info.numRecords.value())
throw std::logic_error(h5pp::format("Cannot read {} records starting from index {} from table [{}] which only has {} records",
numReadRecords.value(),
startIdx.value(),
info.tablePath.value(),
info.numRecords.value()));
h5pp::logger::log->debug("Reading table [{}] | read from record {} | records to read {} | total records {} | record size {} bytes",
info.tablePath.value(),
startIdx.value(),
numReadRecords.value(),
info.numRecords.value(),
info.recordBytes.value());
if constexpr(not std::is_same_v<DataType, std::vector<std::byte>>) {
// Make sure the given container and the registered table record type have the same size.
// If there is a mismatch here it can cause horrible bugs/segfaults
size_t dataSize = 0;
if constexpr(h5pp::type::sfinae::has_value_type_v<DataType>)
dataSize = sizeof(typename DataType::value_type);
else if constexpr(h5pp::type::sfinae::has_data_v<DataType> and h5pp::type::sfinae::is_iterable_v<DataType>)
dataSize = sizeof(&data.data());
else
dataSize = sizeof(DataType);
if(dataSize != info.recordBytes.value())
throw std::runtime_error(h5pp::format("Could not read from table [{}]: "
"Size mismatch: "
"Given data container size is {} bytes per element | "
"Table is {} bytes per record",
info.tablePath.value(),
dataSize,
info.recordBytes.value()));
h5pp::util::resizeData(data, {numReadRecords.value()});
}
// Last sanity check. If there are no records to read, just return;
if(numReadRecords.value() == 0) return;
if(info.numRecords.value() == 0) return;
/* Step 1: Get the dataset and memory spaces */
hid::h5s dsetSpace = H5Dget_space(info.h5Dset.value()); /* get a copy of the new file data space for writing */
hid::h5s dataSpace = util::getMemSpace(numReadRecords.value(), {numReadRecords.value()}); /* create a simple memory data space */
/* Step 2: draw a hyperslab in the dataset */
h5pp::Hyperslab slab;
slab.offset = {startIdx.value()};
slab.extent = {numReadRecords.value()};
selectHyperslab(dsetSpace, slab, H5S_SELECT_SET);
/* Step 3: read the records */
// Get the memory address to the data buffer
auto dataPtr = h5pp::util::getVoidPointer<void *>(data);
herr_t retval = H5Dread(info.h5Dset.value(), info.h5Type.value(), dataSpace, dsetSpace, H5P_DEFAULT, dataPtr);
if(retval < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(h5pp::format("Failed to read data from table [{}]", info.tablePath.value()));
}
}
template<typename DataType>
inline void appendTableRecords(const DataType &data, TableInfo &info, std::optional<size_t> numNewRecords = std::nullopt) {
/*
* This function replaces H5TBappend_records() and avoids creating expensive temporaries for the dataset id and type id for the
* compound table type.
*
*/
if constexpr(std::is_same_v<DataType, std::vector<std::byte>>)
if(not numNewRecords)
throw std::runtime_error("Optional argument [numNewRecords] is required when appending std::vector<std::byte> to table");
if(not numNewRecords) numNewRecords = h5pp::util::getSize(data);
if(numNewRecords.value() == 0)
h5pp::logger::log->warn("Given 0 records to write to table [{}]. This is likely an error.", info.tablePath.value());
h5pp::logger::log->debug("Appending {} records to table [{}] | current num records {} | record size {} bytes",
numNewRecords.value(),
info.tablePath.value(),
info.numRecords.value(),
info.recordBytes.value());
info.assertWriteReady();
if constexpr(not std::is_same_v<DataType, std::vector<std::byte>>) {
// Make sure the given container and the registered table entry have the same size.
// If there is a mismatch here it can cause horrible bugs/segfaults
if constexpr(h5pp::type::sfinae::has_value_type_v<DataType>) {
if(sizeof(typename DataType::value_type) != info.recordBytes.value())
throw std::runtime_error(h5pp::format("Size mismatch: Given container of type {} has elements of {} bytes, but the "
"table records on file are {} bytes each ",
h5pp::type::sfinae::type_name<DataType>(),
sizeof(typename DataType::value_type),
info.recordBytes.value()));
} else if constexpr(h5pp::type::sfinae::has_data_v<DataType> and h5pp::type::sfinae::is_iterable_v<DataType>) {
if(sizeof(&data.data()) != info.recordBytes.value())
throw std::runtime_error(h5pp::format("Size mismatch: Given container of type {} has elements of {} bytes, but the "
"table records on file are {} bytes each ",
h5pp::type::sfinae::type_name<DataType>(),
sizeof(&data.data()),
info.recordBytes.value()));
} else {
if(sizeof(DataType) != info.recordBytes.value())
throw std::runtime_error(
h5pp::format("Size mismatch: Given data type {} is of {} bytes, but the table records on file are {} bytes each ",
h5pp::type::sfinae::type_name<DataType>(),
sizeof(DataType),
info.recordBytes.value()));
}
}
/* Step 1: extend the dataset */
extendDataset(info.h5Dset.value(), {numNewRecords.value() + info.numRecords.value()});
/* Step 2: Get the dataset and memory spaces */
hid::h5s dsetSpace = H5Dget_space(info.h5Dset.value()); /* get a copy of the new file data space for writing */
hid::h5s dataSpace = util::getMemSpace(numNewRecords.value(), {numNewRecords.value()}); /* create a simple memory data space */
/* Step 3: draw a hyperslab in the dataset */
h5pp::Hyperslab slab;
slab.offset = {info.numRecords.value()};
slab.extent = {numNewRecords.value()};
selectHyperslab(dsetSpace, slab, H5S_SELECT_SET);
/* Step 4: write the records */
// Get the memory address to the data buffer
auto dataPtr = h5pp::util::getVoidPointer<const void *>(data);
herr_t retval = H5Dwrite(info.h5Dset.value(), info.h5Type.value(), dataSpace, dsetSpace, H5P_DEFAULT, dataPtr);
if(retval < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(h5pp::format("Failed to append data to table [{}]", info.tablePath.value()));
}
/* Step 5: increment the number of records in the table */
info.numRecords.value() += numNewRecords.value();
}
template<typename DataType>
inline void writeTableRecords(const DataType & data,
TableInfo & info,
size_t startIdx = 0,
std::optional<size_t> numRecordsToWrite = std::nullopt) {
/*
* This function replaces H5TBwrite_records() and avoids creating expensive temporaries for the dataset id and type id for the
* compound table type. In addition, it has the ability to extend the existing the dataset if the incoming data larger than the
* current bound
*/
if constexpr(std::is_same_v<DataType, std::vector<std::byte>>) {
if(not numRecordsToWrite)
throw std::runtime_error(
"Optional argument [numRecordsToWrite] is required when writing std::vector<std::byte> into table");
}
if(not numRecordsToWrite) numRecordsToWrite = h5pp::util::getSize(data);
if(numRecordsToWrite.value() == 0)
h5pp::logger::log->warn("Given 0 records to write to table [{}]. This is likely an error.", info.tablePath.value());
info.assertWriteReady();
// Check that startIdx is smaller than the number of records on file, otherwise append the data
if(startIdx >= info.numRecords.value())
return h5pp::hdf5::appendTableRecords(data, info, numRecordsToWrite); // return appendTableRecords(data, info);
h5pp::logger::log->debug("Writing {} records to table [{}] | start from {} | current num records {} | record size {} bytes",
numRecordsToWrite.value(),
info.tablePath.value(),
startIdx,
info.numRecords.value(),
info.recordBytes.value());
if constexpr(not std::is_same_v<DataType, std::vector<std::byte>>) {
// Make sure the given data type size matches the table record type size.
// If there is a mismatch here it can cause horrible bugs/segfaults
if constexpr(h5pp::type::sfinae::has_value_type_v<DataType>) {
if(sizeof(typename DataType::value_type) != info.recordBytes.value())
throw std::runtime_error(h5pp::format("Size mismatch: Given container of type {} has elements of {} bytes, but the "
"table records on file are {} bytes each ",
h5pp::type::sfinae::type_name<DataType>(),
sizeof(typename DataType::value_type),
info.recordBytes.value()));
} else if constexpr(h5pp::type::sfinae::has_data_v<DataType> and h5pp::type::sfinae::is_iterable_v<DataType>) {
if(sizeof(&data.data()) != info.recordBytes.value())
throw std::runtime_error(h5pp::format("Size mismatch: Given container of type {} has elements of {} bytes, but the "
"table records on file are {} bytes each ",
h5pp::type::sfinae::type_name<DataType>(),
sizeof(&data.data()),
info.recordBytes.value()));
} else {
if(sizeof(DataType) != info.recordBytes.value())
throw std::runtime_error(
h5pp::format("Size mismatch: Given data type {} is of {} bytes, but the table records on file are {} bytes each ",
h5pp::type::sfinae::type_name<DataType>(),
sizeof(DataType),
info.recordBytes.value()));
}
}
/* Step 1: extend the dataset if necessary */
if(startIdx + numRecordsToWrite.value() > info.numRecords.value())
extendDataset(info.h5Dset.value(), {startIdx + numRecordsToWrite.value()});
/* Step 2: Get the dataset and memory spaces */
hid::h5s dsetSpace = H5Dget_space(info.h5Dset.value()); /* get a copy of the new file data space for writing */
hid::h5s dataSpace =
util::getMemSpace(numRecordsToWrite.value(), {numRecordsToWrite.value()}); /* create a simple memory data space */
/* Step 3: draw a hyperslab in the dataset */
h5pp::Hyperslab slab;
slab.offset = {startIdx};
slab.extent = {numRecordsToWrite.value()};
selectHyperslab(dsetSpace, slab, H5S_SELECT_SET);
/* Step 4: write the records */
// Get the memory address to the data buffer
auto dataPtr = h5pp::util::getVoidPointer<const void *>(data);
herr_t retval = H5Dwrite(info.h5Dset.value(), info.h5Type.value(), dataSpace, dsetSpace, H5P_DEFAULT, dataPtr);
if(retval < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(h5pp::format("Failed to append data to table [{}]", info.tablePath.value()));
}
info.numRecords.value() = std::max<size_t>(startIdx + numRecordsToWrite.value(), info.numRecords.value());
}
inline void copyTableRecords(const h5pp::TableInfo &srcInfo,
hsize_t srcStartIdx,
hsize_t numRecordsToCopy,
h5pp::TableInfo & tgtInfo,
hsize_t tgtStartIdx) {
srcInfo.assertReadReady();
tgtInfo.assertWriteReady();
// Sanity checks for table types
if(srcInfo.h5Type.value() != tgtInfo.h5Type.value())
throw std::runtime_error(h5pp::format("Failed to add table records: table type mismatch"));
if(srcInfo.recordBytes.value() != tgtInfo.recordBytes.value())
throw std::runtime_error(h5pp::format("Failed to copy table records: table record byte size mismatch src {} != tgt {}",
srcInfo.recordBytes.value(),
tgtInfo.recordBytes.value()));
if(srcInfo.fieldSizes.value() != tgtInfo.fieldSizes.value())
throw std::runtime_error(h5pp::format("Failed to copy table records: table field sizes mismatch src {} != tgt {}",
srcInfo.fieldSizes.value(),
tgtInfo.fieldSizes.value()));
if(srcInfo.fieldOffsets.value() != tgtInfo.fieldOffsets.value())
throw std::runtime_error(h5pp::format("Failed to copy table records: table field offsets mismatch src {} != tgt {}",
srcInfo.fieldOffsets.value(),
tgtInfo.fieldOffsets.value()));
// Sanity check for record ranges
if(srcInfo.numRecords.value() < srcStartIdx + numRecordsToCopy)
throw std::runtime_error(h5pp::format("Failed to copy table records: Requested records out of bound: src table nrecords {} | "
"src table start index {} | num records to copy {}",
srcInfo.numRecords.value(),
srcStartIdx,
numRecordsToCopy));
std::string fileLogInfo;
// TODO: this check is not very thorough, but checks with H5Iget_file_id are too expensive...
if(srcInfo.h5File.value() != tgtInfo.h5File.value()) fileLogInfo = "on different files";
h5pp::logger::log->debug("Copying records from table [{}] to table [{}] {} | src start at record {} ({} total) | tgt start at "
"record {} ({} total) | copy {} records | record size {} bytes",
srcInfo.tablePath.value(),
tgtInfo.tablePath.value(),
fileLogInfo,
srcStartIdx,
srcInfo.numRecords.value(),
tgtStartIdx,
tgtInfo.numRecords.value(),
numRecordsToCopy,
tgtInfo.recordBytes.value());
std::vector<std::byte> data(numRecordsToCopy * tgtInfo.recordBytes.value());
data.resize(numRecordsToCopy * tgtInfo.recordBytes.value());
h5pp::hdf5::readTableRecords(data, srcInfo, srcStartIdx, numRecordsToCopy);
h5pp::hdf5::writeTableRecords(data, tgtInfo, tgtStartIdx, numRecordsToCopy);
}
template<typename DataType, typename = std::enable_if_t<not std::is_const_v<DataType>>>
inline void readTableField(DataType & data,
const TableInfo & info,
const std::vector<size_t> &srcFieldIndices, // Field indices for the table on file
std::optional<size_t> startIdx = std::nullopt,
std::optional<size_t> numReadRecords = std::nullopt) {
// If none of startIdx or numReadRecords are given:
// If data resizeable: startIdx = 0, numReadRecords = totalRecords
// If data not resizeable: startIdx = last record index, numReadRecords = 1.
// If startIdx given but numReadRecords is not:
// If data resizeable -> read from startIdx to the end
// If data not resizeable -> read a single record starting from startIdx
// If numReadRecords given but startIdx is not -> read the last numReadRecords records
info.assertReadReady();
hsize_t totalRecords = info.numRecords.value();
if(not startIdx and not numReadRecords) {
if constexpr(h5pp::type::sfinae::has_resize_v<DataType>) {
startIdx = 0;
numReadRecords = totalRecords;
} else {
startIdx = totalRecords - 1;
numReadRecords = 1;
}
} else if(startIdx and not numReadRecords) {
if(startIdx.value() > totalRecords - 1)
throw std::runtime_error(h5pp::format(
"Invalid start record {} for table [{}] | total records [{}]", startIdx.value(), info.tablePath.value(), totalRecords));
if constexpr(h5pp::type::sfinae::has_resize_v<DataType>) {
numReadRecords = totalRecords - startIdx.value();
} else {
numReadRecords = 1;
}
} else if(numReadRecords and not startIdx) {
if(numReadRecords and numReadRecords.value() > totalRecords)
throw std::logic_error(h5pp::format("Cannot read {} records from table [{}] which only has {} records",
numReadRecords.value(),
info.tablePath.value(),
totalRecords));
startIdx = totalRecords - numReadRecords.value();
}
// Sanity check
if(numReadRecords.value() > totalRecords)
throw std::logic_error(h5pp::format("Cannot read {} records from table [{}] which only has {} records",
numReadRecords.value(),
info.tablePath.value(),
totalRecords));
if(startIdx.value() + numReadRecords.value() > totalRecords)
throw std::logic_error(h5pp::format("Cannot read {} records starting from index {} from table [{}] which only has {} records",
numReadRecords.value(),
startIdx.value(),
info.tablePath.value(),
totalRecords));
// Build the field sizes and offsets of the given read buffer based on the corresponding quantities on file
std::vector<size_t> srcFieldOffsets;
std::vector<size_t> tgtFieldOffsets;
std::vector<size_t> tgtFieldSizes;
std::vector<std::string> tgtFieldNames;
size_t tgtFieldSizeSum = 0;
for(const auto &idx : srcFieldIndices) {
srcFieldOffsets.emplace_back(info.fieldOffsets.value()[idx]);
tgtFieldOffsets.emplace_back(tgtFieldSizeSum);
tgtFieldSizes.emplace_back(info.fieldSizes.value()[idx]);
tgtFieldNames.emplace_back(info.fieldNames.value()[idx]);
tgtFieldSizeSum += tgtFieldSizes.back();
}
// Make sure the data type of the given read buffer matches the size computed above.
// If there is a mismatch here it can cause horrible bugs/segfaults
size_t dataSize = 0;
if constexpr(h5pp::type::sfinae::has_value_type_v<DataType>)
dataSize = sizeof(typename DataType::value_type);
else if constexpr(h5pp::type::sfinae::has_data_v<DataType> and h5pp::type::sfinae::is_iterable_v<DataType>)
dataSize = sizeof(&data.data());
else
dataSize = sizeof(DataType);
if(dataSize != tgtFieldSizeSum) {
std::string error_msg = h5pp::format("Could not read fields {} from table [{}]\n", tgtFieldNames, info.tablePath.value());
for(auto &idx : srcFieldIndices)
error_msg += h5pp::format(
"{:<10} Field index {:<6} {:<24} = {} bytes\n", " ", idx, info.fieldNames.value()[idx], info.fieldSizes.value()[idx]);
std::string dataTypeName;
if constexpr(h5pp::type::sfinae::has_value_type_v<DataType>)
dataTypeName = h5pp::type::sfinae::type_name<typename DataType::value_type>();
else if constexpr(h5pp::type::sfinae::has_data_v<DataType> and h5pp::type::sfinae::is_iterable_v<DataType>)
dataTypeName = h5pp::type::sfinae::type_name<decltype(&data.data())>();
else
dataTypeName = h5pp::type::sfinae::type_name<DataType>();
error_msg += h5pp::format("{:<8} + {:-^60}\n", " ", "");
error_msg += h5pp::format("{:<10} Fields total = {} bytes per record\n", " ", tgtFieldSizeSum);
error_msg += h5pp::format("{:<10} Given buffer = {} bytes per record <{}>\n", " ", dataSize, dataTypeName);
error_msg += h5pp::format("{:<10} Size mismatch\n", " ");
error_msg += h5pp::format("{:<10} Hint: The buffer type <{}> may have been padded by the compiler\n", " ", dataTypeName);
error_msg += h5pp::format("{:<10} Consider declaring <{}> with __attribute__((packed, aligned(1)))\n", " ", dataTypeName);
throw std::runtime_error(error_msg);
}
h5pp::util::resizeData(data, {numReadRecords.value()});
h5pp::logger::log->debug("Reading table [{}] | field names {} | read from "
"record {} | read num records {} | available "
"records {} | record size {} bytes",
info.tablePath.value(),
tgtFieldNames,
startIdx.value(),
numReadRecords.value(),
info.numRecords.value(),
info.recordBytes.value());
h5pp::logger::log->trace("Reading field indices {} sizes {} | offsets {} | offsets on dataset {}",
srcFieldIndices,
tgtFieldSizes,
tgtFieldOffsets,
srcFieldOffsets);
// Get the memory address to the data buffer
auto dataPtr = h5pp::util::getVoidPointer<void *>(data);
/* Step 1: Get the dataset and memory spaces */
hid::h5s dsetSpace = H5Dget_space(info.h5Dset.value()); /* get a copy of the new file data space for writing */
hid::h5s dataSpace = util::getMemSpace(numReadRecords.value(), {numReadRecords.value()}); /* create a simple memory data space */
/* Step 2: draw a hyperslab in the dataset */
h5pp::Hyperslab slab;
slab.offset = {startIdx.value()};
slab.extent = {numReadRecords.value()};
selectHyperslab(dsetSpace, slab, H5S_SELECT_SET);
/* Step 3: Create a special tgtTypeId for reading a subset of the record with the following properties:
* - tgtTypeId has the size of the given buffer type, i.e. dataSize.
* - only the fields to read are defined in it
* - the defined fields are converted to native types
* Then H5Dread will take care of only reading the relevant components of the record
*/
hid::h5t tgtTypeId = H5Tcreate(H5T_COMPOUND, dataSize);
for(size_t tgtIdx = 0; tgtIdx < srcFieldIndices.size(); tgtIdx++) {
size_t srcIdx = srcFieldIndices[tgtIdx];
hid::h5t temp_member_id = H5Tget_native_type(info.fieldTypes.value()[srcIdx], H5T_DIR_DEFAULT);
size_t temp_member_size = H5Tget_size(temp_member_id);
if(tgtFieldSizes[tgtIdx] != temp_member_size) H5Tset_size(temp_member_id, tgtFieldSizes[tgtIdx]);
H5Tinsert(tgtTypeId, tgtFieldNames[tgtIdx].c_str(), tgtFieldOffsets[tgtIdx], temp_member_id);
}
/* Read data */
herr_t retval = H5Dread(info.h5Dset.value(), tgtTypeId, dataSpace, dsetSpace, H5P_DEFAULT, dataPtr);
if(retval < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(h5pp::format("Could not read table fields {} on table [{}]", tgtFieldNames, info.tablePath.value()));
}
}
template<typename DataType, typename = std::enable_if_t<not std::is_const_v<DataType>>>
inline void readTableField(DataType & data,
const TableInfo & info,
const std::vector<std::string> &fieldNames,
std::optional<size_t> startIdx = std::nullopt,
std::optional<size_t> numReadRecords = std::nullopt) {
// Compute the field indices
std::vector<size_t> fieldIndices;
for(const auto &fieldName : fieldNames) {
auto it = std::find(info.fieldNames->begin(), info.fieldNames->end(), fieldName);
if(it == info.fieldNames->end())
throw std::runtime_error(h5pp::format("Could not find field [{}] in table [{}]: "
"Available field names are {}",
fieldName,
info.tablePath.value(),
info.fieldNames.value()));
else
fieldIndices.emplace_back(static_cast<size_t>(std::distance(info.fieldNames->begin(), it)));
}
readTableField(data, info, fieldIndices, startIdx, numReadRecords);
}
template<typename h5x_src,
typename h5x_tgt,
// enable_if so the compiler doesn't think it can use overload with std::string those arguments
typename = h5pp::type::sfinae::enable_if_is_h5_loc_or_hid_t<h5x_src>,
typename = h5pp::type::sfinae::enable_if_is_h5_loc_or_hid_t<h5x_tgt>>
inline void copyLink(const h5x_src & srcLocId,
std::string_view srcLinkPath,
const h5x_tgt & tgtLocId,
std::string_view tgtLinkPath,
const PropertyLists &plists = PropertyLists()) {
static_assert(h5pp::type::sfinae::is_h5_loc_or_hid_v<h5x_src>,
"Template function [h5pp::hdf5::copyLink(const h5x_src & srcLocId, ...)] requires type h5x_src to be: "
"[h5pp::hid::h5f], [h5pp::hid::h5g], [h5pp::hid::h5o] or [hid_t]");
static_assert(h5pp::type::sfinae::is_h5_loc_or_hid_v<h5x_tgt>,
"Template function [h5pp::hdf5::copyLink(..., ..., const h5x_tgt & tgtLocId, ...)] requires type h5x_tgt to be: "
"[h5pp::hid::h5f], [h5pp::hid::h5g], [h5pp::hid::h5o] or [hid_t]");
h5pp::logger::log->trace("Copying link [{}] --> [{}]", srcLinkPath, tgtLinkPath);
// Copy the link srcLinkPath to tgtLinkPath. Note that H5Ocopy does this recursively, so we don't need
// to iterate links recursively here.
auto retval = H5Ocopy(
srcLocId, util::safe_str(srcLinkPath).c_str(), tgtLocId, util::safe_str(tgtLinkPath).c_str(), H5P_DEFAULT, plists.linkCreate);
if(retval < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(h5pp::format("Could not copy link [{}] --> [{}]", srcLinkPath, tgtLinkPath));
}
}
template<typename h5x_src,
typename h5x_tgt,
// enable_if so the compiler doesn't think it can use overload with fs::path those arguments
typename = h5pp::type::sfinae::enable_if_is_h5_loc_or_hid_t<h5x_src>,
typename = h5pp::type::sfinae::enable_if_is_h5_loc_or_hid_t<h5x_tgt>>
inline void moveLink(const h5x_src & srcLocId,
std::string_view srcLinkPath,
const h5x_tgt & tgtLocId,
std::string_view tgtLinkPath,
LocationMode locationMode = LocationMode::DETECT,
const PropertyLists &plists = PropertyLists()) {
static_assert(h5pp::type::sfinae::is_h5_loc_or_hid_v<h5x_src>,
"Template function [h5pp::hdf5::moveLink(const h5x_src & srcLocId, ...)] requires type h5x_src to be: "
"[h5pp::hid::h5f], [h5pp::hid::h5g], [h5pp::hid::h5o] or [hid_t]");
static_assert(h5pp::type::sfinae::is_h5_loc_or_hid_v<h5x_tgt>,
"Template function [h5pp::hdf5::moveLink(..., ..., const h5x_tgt & tgtLocId, ...)] requires type h5x_tgt to be: "
"[h5pp::hid::h5f], [h5pp::hid::h5g], [h5pp::hid::h5o] or [hid_t]");
h5pp::logger::log->trace("Moving link [{}] --> [{}]", srcLinkPath, tgtLinkPath);
// Move the link srcLinkPath to tgtLinkPath. Note that H5Lmove only works inside a single file.
// For different files we should do H5Ocopy followed by H5Ldelete
bool sameFile = h5pp::util::onSameFile(srcLocId, tgtLocId, locationMode);
if(sameFile) {
// Same file
auto retval = H5Lmove(srcLocId,
util::safe_str(srcLinkPath).c_str(),
tgtLocId,
util::safe_str(tgtLinkPath).c_str(),
plists.linkCreate,
plists.linkAccess);
if(retval < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(h5pp::format("Could not copy link [{}] --> [{}]", srcLinkPath, tgtLinkPath));
}
} else {
// Different files
auto retval = H5Ocopy(srcLocId,
util::safe_str(srcLinkPath).c_str(),
tgtLocId,
util::safe_str(tgtLinkPath).c_str(),
H5P_DEFAULT,
plists.linkCreate);
if(retval < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(h5pp::format("Could not copy link [{}] --> [{}]", srcLinkPath, tgtLinkPath));
}
retval = H5Ldelete(srcLocId, util::safe_str(srcLinkPath).c_str(), plists.linkAccess);
if(retval < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(h5pp::format("Could not delete link after move [{}]", srcLinkPath));
}
}
}
inline void copyLink(const h5pp::fs::path &srcFilePath,
std::string_view srcLinkPath,
const h5pp::fs::path &tgtFilePath,
std::string_view tgtLinkPath,
FilePermission targetFileCreatePermission = FilePermission::READWRITE,
const PropertyLists & plists = PropertyLists()) {
h5pp::logger::log->trace("Copying link: source link [{}] | source file [{}] --> target link [{}] | target file [{}]",
srcLinkPath,
srcFilePath.string(),
tgtLinkPath,
tgtFilePath.string());
try {
auto srcPath = fs::absolute(srcFilePath);
if(not fs::exists(srcPath))
throw std::runtime_error(h5pp::format("Could not copy link [{}] from file [{}]: source file does not exist [{}]",
srcLinkPath,
srcFilePath.string(),
srcPath.string()));
auto tgtPath = h5pp::hdf5::createFile(tgtFilePath, targetFileCreatePermission, plists);
hid_t hidSrc = H5Fopen(srcPath.string().c_str(), H5F_ACC_RDONLY, plists.fileAccess);
hid_t hidTgt = H5Fopen(tgtPath.string().c_str(), H5F_ACC_RDWR, plists.fileAccess);
if(hidSrc < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(h5pp::format("Failed to open source file [{}] in read-only mode", srcPath.string()));
}
if(hidTgt < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(h5pp::format("Failed to open target file [{}] in read-write mode", tgtPath.string()));
}
hid::h5f srcFile = hidSrc;
hid::h5f tgtFile = hidTgt;
copyLink(srcFile, srcLinkPath, tgtFile, tgtLinkPath);
} catch(const std::exception &ex) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(
h5pp::format("Could not copy link [{}] from file [{}]: {}", srcLinkPath, srcFilePath.string(), ex.what()));
}
}
inline fs::path copyFile(const h5pp::fs::path &srcFilePath,
const h5pp::fs::path &tgtFilePath,
FilePermission permission = FilePermission::COLLISION_FAIL,
const PropertyLists & plists = PropertyLists()) {
h5pp::logger::log->trace("Copying file [{}] --> [{}]", srcFilePath.string(), tgtFilePath.string());
auto tgtPath = h5pp::hdf5::createFile(tgtFilePath, permission, plists);
auto srcPath = fs::absolute(srcFilePath);
try {
if(not fs::exists(srcPath))
throw std::runtime_error(h5pp::format("Could not copy file [{}] --> [{}]: source file does not exist [{}]",
srcFilePath.string(),
tgtFilePath.string(),
srcPath.string()));
if(tgtPath == srcPath)
h5pp::logger::log->debug("Skipped copying file: source and target files have the same path [{}]", srcPath.string());
hid_t hidSrc = H5Fopen(srcPath.string().c_str(), H5F_ACC_RDONLY, plists.fileAccess);
hid_t hidTgt = H5Fopen(tgtPath.string().c_str(), H5F_ACC_RDWR, plists.fileAccess);
if(hidSrc < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(h5pp::format("Failed to open source file [{}] in read-only mode", srcPath.string()));
}
if(hidTgt < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(h5pp::format("Failed to open target file [{}] in read-write mode", tgtPath.string()));
}
hid::h5f srcFile = hidSrc;
hid::h5f tgtFile = hidTgt;
// Copy all the groups in the file root recursively. Note that H5Ocopy does this recursively, so we don't need
// to iterate links recursively here. Therefore maxDepth = 0
long maxDepth = 0;
for(const auto &link : getContentsOfLink<H5O_TYPE_UNKNOWN>(srcFile, "/", maxDepth, plists.linkAccess)) {
if(link == ".") continue;
h5pp::logger::log->trace("Copying recursively: [{}]", link);
auto retval = H5Ocopy(srcFile, link.c_str(), tgtFile, link.c_str(), H5P_DEFAULT, plists.linkCreate);
if(retval < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(h5pp::format(
"Failed to copy file contents with H5Ocopy(srcFile,{},tgtFile,{},H5P_DEFAULT,link_create_propery_list)",
link,
link));
}
}
// ... Find out how to copy attributes that are written on the root itself
return tgtPath;
} catch(const std::exception &ex) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(
h5pp::format("Could not copy file [{}] --> [{}]: ", srcFilePath.string(), tgtFilePath.string(), ex.what()));
}
}
inline void moveLink(const h5pp::fs::path &srcFilePath,
std::string_view srcLinkPath,
const h5pp::fs::path &tgtFilePath,
std::string_view tgtLinkPath,
FilePermission targetFileCreatePermission = FilePermission::READWRITE,
const PropertyLists & plists = PropertyLists()) {
h5pp::logger::log->trace("Moving link: source link [{}] | source file [{}] --> target link [{}] | target file [{}]",
srcLinkPath,
srcFilePath.string(),
tgtLinkPath,
tgtFilePath.string());
try {
auto srcPath = fs::absolute(srcFilePath);
if(not fs::exists(srcPath))
throw std::runtime_error(
h5pp::format("Could not move link [{}] from file [{}]:\n\t source file with absolute path [{}] does not exist",
srcLinkPath,
srcFilePath.string(),
srcPath.string()));
auto tgtPath = h5pp::hdf5::createFile(tgtFilePath, targetFileCreatePermission, plists);
hid_t hidSrc = H5Fopen(srcPath.string().c_str(), H5F_ACC_RDWR, plists.fileAccess);
hid_t hidTgt = H5Fopen(tgtPath.string().c_str(), H5F_ACC_RDWR, plists.fileAccess);
if(hidSrc < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(h5pp::format("Failed to open source file [{}] in read-only mode", srcPath.string()));
}
if(hidTgt < 0) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(h5pp::format("Failed to open target file [{}] in read-write mode", tgtPath.string()));
}
hid::h5f srcFile = hidSrc;
hid::h5f tgtFile = hidTgt;
auto locMode = h5pp::util::getLocationMode(srcFilePath, tgtFilePath);
moveLink(srcFile, srcLinkPath, tgtFile, tgtLinkPath, locMode);
} catch(const std::exception &ex) {
H5Eprint(H5E_DEFAULT, stderr);
throw std::runtime_error(
h5pp::format("Could not move link [{}] from file [{}]: {}", srcLinkPath, srcFilePath.string(), ex.what()));
}
}
inline fs::path moveFile(const h5pp::fs::path &src,
const h5pp::fs::path &tgt,
FilePermission permission = FilePermission::COLLISION_FAIL,
const PropertyLists & plists = PropertyLists()) {
h5pp::logger::log->trace("Moving file by copy+remove: [{}] --> [{}]", src.string(), tgt.string());
auto tgtPath = copyFile(src, tgt, permission, plists); // Returns the path to the newly created file
auto srcPath = fs::absolute(src);
if(fs::exists(tgtPath)) {
h5pp::logger::log->trace("Removing file [{}]", srcPath.string());
try {
fs::remove(srcPath);
} catch(const std::exception &err) {
throw std::runtime_error(
h5pp::format("Remove failed. File may be locked [{}] | what(): {} ", srcPath.string(), err.what()));
}
return tgtPath;
} else
throw std::runtime_error(h5pp::format("Could not copy file [{}] to target [{}]", srcPath.string(), tgt.string()));
return tgtPath;
}
}
| [
"aceituno@kth.se"
] | aceituno@kth.se |
ca24226c5692fc523964e6e54bdc5448b8b18dd6 | 6f25c6660e770db7aa6c917834fa87ff3c784af3 | /cocos2d/cocos/2d/CCFontAtlas.h | 56a76bca29da441334d65c99a37b148f7ef82c07 | [
"MIT"
] | permissive | lfeng1420/BrickGame | 7c6808f7212211ad7dc12592063e505c95fdfadb | e4961a7454ae1adece6845c64a6ba8ac59856d68 | refs/heads/master | 2020-12-11T08:50:19.812761 | 2019-10-11T15:06:59 | 2019-10-11T15:06:59 | 49,433,572 | 42 | 14 | null | null | null | null | UTF-8 | C++ | false | false | 4,063 | h | /****************************************************************************
Copyright (c) 2013 Zynga Inc.
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef _CCFontAtlas_h_
#define _CCFontAtlas_h_
#include "base/CCPlatformMacros.h"
#include "base/CCRef.h"
#include "CCStdC.h"
#include <string>
#include <unordered_map>
NS_CC_BEGIN
//fwd
class Font;
class Texture2D;
class EventCustom;
class EventListenerCustom;
struct FontLetterDefinition
{
unsigned short letteCharUTF16;
float U;
float V;
float width;
float height;
float offsetX;
float offsetY;
int textureID;
bool validDefinition;
int xAdvance;
int clipBottom;
};
class CC_DLL FontAtlas : public Ref
{
public:
static const int CacheTextureWidth;
static const int CacheTextureHeight;
static const char* EVENT_PURGE_TEXTURES;
/**
* @js ctor
*/
FontAtlas(Font &theFont);
/**
* @js NA
* @lua NA
*/
virtual ~FontAtlas();
void addLetterDefinition(const FontLetterDefinition &letterDefinition);
bool getLetterDefinitionForChar(char16_t letteCharUTF16, FontLetterDefinition &outDefinition);
bool prepareLetterDefinitions(const std::u16string& utf16String);
inline const std::unordered_map<ssize_t, Texture2D*>& getTextures() const{ return _atlasTextures;}
void addTexture(Texture2D *texture, int slot);
float getCommonLineHeight() const;
void setCommonLineHeight(float newHeight);
Texture2D* getTexture(int slot);
const Font* getFont() const;
/** listen the event that renderer was recreated on Android/WP8
It only has effect on Android and WP8.
*/
void listenRendererRecreated(EventCustom *event);
/** Removes textures atlas.
It will purge the textures atlas and if multiple texture exist in the FontAtlas.
*/
void purgeTexturesAtlas();
/** sets font texture parameters:
- GL_TEXTURE_MIN_FILTER = GL_LINEAR
- GL_TEXTURE_MAG_FILTER = GL_LINEAR
*/
void setAntiAliasTexParameters();
/** sets font texture parameters:
- GL_TEXTURE_MIN_FILTER = GL_NEAREST
- GL_TEXTURE_MAG_FILTER = GL_NEAREST
*/
void setAliasTexParameters();
private:
void relaseTextures();
std::unordered_map<ssize_t, Texture2D*> _atlasTextures;
std::unordered_map<unsigned short, FontLetterDefinition> _fontLetterDefinitions;
float _commonLineHeight;
Font * _font;
// Dynamic GlyphCollection related stuff
int _currentPage;
unsigned char *_currentPageData;
int _currentPageDataSize;
float _currentPageOrigX;
float _currentPageOrigY;
float _letterPadding;
bool _makeDistanceMap;
int _fontAscender;
EventListenerCustom* _rendererRecreatedListener;
bool _antialiasEnabled;
bool _rendererRecreate;
};
NS_CC_END
#endif /* defined(__cocos2d_libs__CCFontAtlas__) */
| [
"lfeng1420@hotmail.com"
] | lfeng1420@hotmail.com |
6b993bfe7c387e1fbab7c68d7ea51e0d7445c668 | 4352b5c9e6719d762e6a80e7a7799630d819bca3 | /tutorials/eulerVortex.twitch/eulerVortex.cyclic.twitch.test.test/processor0/3.86/e | 363b0f75a1ce3c072ff18fc5cac325b11ad9931a | [] | no_license | dashqua/epicProject | d6214b57c545110d08ad053e68bc095f1d4dc725 | 54afca50a61c20c541ef43e3d96408ef72f0bcbc | refs/heads/master | 2022-02-28T17:20:20.291864 | 2019-10-28T13:33:16 | 2019-10-28T13:33:16 | 184,294,390 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 49,000 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 6
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "3.86";
object e;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 2 -2 0 0 0 0];
internalField nonuniform List<scalar>
5625
(
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.3
1006.3
1006.31
1006.31
1006.31
1006.31
1006.31
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.3
1006.3
1006.3
1006.31
1006.31
1006.31
1006.31
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.3
1006.3
1006.3
1006.31
1006.31
1006.31
1006.31
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.3
1006.3
1006.31
1006.31
1006.31
1006.31
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.3
1006.3
1006.31
1006.31
1006.31
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.3
1006.3
1006.31
1006.31
1006.31
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.3
1006.3
1006.3
1006.31
1006.31
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.3
1006.3
1006.31
1006.31
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.3
1006.3
1006.3
1006.31
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.28
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.3
1006.3
1006.31
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.3
1006.3
1006.3
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.28
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.3
1006.3
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.3
1006.3
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.3
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.28
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
)
;
boundaryField
{
emptyPatches_empt
{
type empty;
}
top_cyc
{
type cyclic;
}
bottom_cyc
{
type cyclic;
}
inlet_cyc
{
type cyclic;
}
outlet_cyc
{
type cyclic;
}
procBoundary0to1
{
type processor;
value nonuniform List<scalar>
75
(
1006.31
1006.31
1006.31
1006.31
1006.31
1006.31
1006.31
1006.31
1006.31
1006.31
1006.31
1006.31
1006.3
1006.3
1006.3
1006.3
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
)
;
}
procBoundary0to1throughinlet_cyc
{
type processorCyclic;
value nonuniform List<scalar>
75
(
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
)
;
}
procBoundary0to2
{
type processor;
value nonuniform List<scalar>
75
(
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.3
1006.3
1006.31
1006.31
1006.31
1006.32
1006.31
)
;
}
procBoundary0to2throughbottom_cyc
{
type processorCyclic;
value nonuniform List<scalar>
75
(
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
1006.29
)
;
}
}
// ************************************************************************* //
| [
"tdg@debian"
] | tdg@debian | |
8c1ec4445099e162a772d5db5ec84d9e358dafa2 | 21b99ea7396881e8a56f41b53e5672e689c805a7 | /omnetpp-5.2.1/tools/macosx/include/osgEarthUtil/TMSPackager | 1a170568066bfb5e20b7666541432052046b35b3 | [] | no_license | mohammedalasmar/omnetpp-data-transport-model-ndp | 7bf8863091345c0c7ce5b5e80052dc739baa8700 | cbede62fc2b375e8e0012421a4d60f70f1866d69 | refs/heads/master | 2023-06-27T06:17:57.433908 | 2020-10-09T11:30:02 | 2020-10-09T11:30:02 | 194,747,934 | 2 | 2 | null | 2021-08-02T17:03:56 | 2019-07-01T21:54:32 | HTML | UTF-8 | C++ | false | false | 6,227 | /* -*-c++-*- */
/* osgEarth - Dynamic map generation toolkit for OpenSceneGraph
* Copyright 2008-2013 Pelican Mapping
* http://osgearth.org
*
* osgEarth is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
#ifndef OSGEARTHUTIL_TMS_PACKAGER_H
#define OSGEARTHUTIL_TMS_PACKAGER_H
#include <osgEarthUtil/Common>
#include <osgEarth/ImageLayer>
#include <osgEarth/ElevationLayer>
#include <osgEarth/Profile>
#include <osgEarth/TaskService>
namespace osgEarth { namespace Util
{
/**
* Utility that reads tiles from an ImageLayer or ElevationLayer and stores
* the resulting data in a disk-based TMS (Tile Map Service) repository.
*
* See: http://wiki.osgeo.org/wiki/Tile_Map_Service_Specification
*/
class OSGEARTHUTIL_EXPORT TMSPackager
{
public:
/**
* Constructs a new packager.
* @param profile Profile of packaged tile data (required)
*/
TMSPackager( const Profile* outProfile, osgDB::Options* imageWriteOptions);
/** dtor */
virtual ~TMSPackager() { }
/**
* Whether to dump out progress messages
* default = false
*/
void setVerbose( bool value ) { _verbose = value; }
bool getVerbose() const { return _verbose; }
/**
* Whether to abort if a tile writing error is encountered
* default = true
*/
void setAbortOnError( bool value ) { _abortOnError = value; }
bool getAbortOnError() const { return _abortOnError; }
/**
* Maximum level of detail of tiles to package
*/
void setMaxLevel( unsigned value ) { _maxLevel = value; }
unsigned getMaxLevel() const { return _maxLevel; }
/**
* Whether to overwrite files that already exist in the repo
* default = false
*/
void setOverwrite( bool value ) { _overwrite = value; }
bool getOverwrite() const { return _overwrite; }
/**
* Whether to package empty image tiles. An empty tile is a tile
* that is fully transparent. By default, the packager discards
* them and does not subdivide past them.
* default = false
*/
void setKeepEmptyImageTiles( bool value ) { _keepEmptyImageTiles = value; }
bool getKeepEmptyImageTiles() const { return _keepEmptyImageTiles; }
/**
* Whether to subdivide single color image tiles. An single color tile is a tile
* that is filled with a single color. By default, the packager does not subdivide past them.
* default = false
*/
void setSubdivideSingleColorImageTiles( bool value ) { _subdivideSingleColorImageTiles = value; }
bool getSubdivideSingleColorImageTiles() const { return _subdivideSingleColorImageTiles; }
/**
* Bounding box to package
*/
void addExtent( const GeoExtent& value );
/**
* Result structure for method calls
*/
struct Result {
Result(int tasks=0) : ok(true), taskCount(tasks) { }
Result(const std::string& m) : message(m), ok(false), taskCount(0) { }
operator bool() const { return ok; }
bool ok;
std::string message;
int taskCount;
};
/**
* Packages an image layer as a TMS repository.
* @param layer Image layer to export
* @param rootFolder Root output folder of TMS repo
* @param imageExtension (optional) Force an image type extension (e.g., "jpg")
*/
Result package(
ImageLayer* layer,
const std::string& rootFolder,
osgEarth::ProgressCallback* progress=0L,
const std::string& imageExtension="png" );
/**
* Packages an elevation layer as a TMS repository.
* @param layer Image layer to
* @param rootFolder Root output folder of TMS repo
*/
Result package(
ElevationLayer* layer,
const std::string& rootFolder,
osgEarth::ProgressCallback* progress=0L );
protected:
int packageImageTile(
ImageLayer* layer,
const TileKey& key,
const std::string& rootDir,
const std::string& extension,
osgEarth::TaskRequestVector& tasks,
Threading::MultiEvent* semaphore,
osgEarth::ProgressCallback* progress,
unsigned& out_maxLevel );
int packageElevationTile(
ElevationLayer* layer,
const TileKey& key,
const std::string& rootDir,
const std::string& extension,
osgEarth::TaskRequestVector& tasks,
Threading::MultiEvent* semaphore,
osgEarth::ProgressCallback* progress,
unsigned& out_maxLevel );
bool shouldPackageKey(
const TileKey& key ) const;
protected:
bool _verbose;
bool _abortOnError;
bool _overwrite;
bool _keepEmptyImageTiles;
bool _subdivideSingleColorImageTiles;
unsigned _maxLevel;
std::vector<GeoExtent> _extents;
osg::ref_ptr<const Profile> _outProfile;
osg::ref_ptr<osgDB::Options> _imageWriteOptions;
};
} } // namespace osgEarth::Util
#endif // OSGEARTHUTIL_TMS_PACKAGER_H
| [
"mohammedzsalasmar@gmail.com"
] | mohammedzsalasmar@gmail.com | |
af055a368092d7521478d465d60346b2531911c9 | 452be58b4c62e6522724740cac332ed0fe446bb8 | /src/cobalt/speech/sandbox/speech_sandbox.h | 966ee3271282d609d6b6f65c0eb24776d06e7fe9 | [
"Apache-2.0"
] | permissive | blockspacer/cobalt-clone-cab7770533804d582eaa66c713a1582f361182d3 | b6e802f4182adbf6a7451a5d48dc4e158b395107 | 0b72f93b07285f3af3c8452ae2ceaf5860ca7c72 | refs/heads/master | 2020-08-18T11:32:21.458963 | 2019-10-17T13:09:35 | 2019-10-17T13:09:35 | 215,783,613 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,051 | h | // Copyright 2016 The Cobalt Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef COBALT_SPEECH_SANDBOX_SPEECH_SANDBOX_H_
#define COBALT_SPEECH_SANDBOX_SPEECH_SANDBOX_H_
#include <memory>
#include <string>
#include "base/files/file_path.h"
#include "base/threading/thread.h"
#include "cobalt/dom/dom_settings.h"
#include "cobalt/speech/sandbox/audio_loader.h"
#include "cobalt/speech/speech_recognition.h"
#include "cobalt/trace_event/scoped_trace_to_file.h"
namespace cobalt {
namespace speech {
namespace sandbox {
// This class is for speech sandbox application to experiment with voice search.
// It takes a wav audio as audio input for a fake microphone, and starts/stops
// speech recognition.
class SpeechSandbox {
public:
// The constructor takes a file path string for an audio input and a log path
// for tracing.
SpeechSandbox(const std::string& file_path_string,
const base::FilePath& trace_log_path);
~SpeechSandbox();
private:
void StartRecognition(const dom::DOMSettings::Options& dom_settings_options);
void OnLoadingDone(const uint8* data, int size);
std::unique_ptr<trace_event::ScopedTraceToFile> trace_to_file_;
std::unique_ptr<network::NetworkModule> network_module_;
std::unique_ptr<AudioLoader> audio_loader_;
scoped_refptr<SpeechRecognition> speech_recognition_;
DISALLOW_IMPLICIT_CONSTRUCTORS(SpeechSandbox);
};
} // namespace sandbox
} // namespace speech
} // namespace cobalt
#endif // COBALT_SPEECH_SANDBOX_SPEECH_SANDBOX_H_
| [
"trofimov_d_a@magnit.ru"
] | trofimov_d_a@magnit.ru |
0c5d6b45c2530fa80f2c1883d157ecb67937f87a | e34b28b281a189888f1481c58b37c8faf2757988 | /LeetCode/LeetCode_079.cpp | c02f489e6ea4436d0471c19b24fc9ce0db96dc9f | [] | no_license | reversed/C | aebafda0615c594a844dee1bb12fc683b9cd0c65 | f6edb643723457276d8542eb7b583addfb6f1a7f | refs/heads/master | 2020-04-10T22:05:26.689390 | 2019-06-22T02:56:26 | 2019-06-22T02:57:23 | 68,095,558 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,365 | cpp | class Solution {
public:
bool dfs(vector<vector<char>>& board, vector<vector<bool>>& map, int x, int y, string& word)
{
if (word.empty()) return true;
if (x >= board.size() || x < 0) return false;
if (y >= board[0].size() || y < 0) return false;
if (map[x][y] == true) return false;
char c = word.back();
if (board[x][y] != c) return false;
map[x][y] = true;
word.pop_back();
vector<pair<int, int>> step { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
for (auto p : step)
{
int tx = p.first + x;
int ty = p.second + y;
if (dfs(board, map, tx, ty, word)) return true;
}
map[x][y] = false;
word.push_back(c);
return false;
}
bool exist(vector<vector<char>>& board, string word) {
if (word.empty()) return true;
int row = board.size();
if (row == 0) return false;
int col = board[0].size();
reverse(word.begin(), word.end());
vector<vector<bool>> access_map(row, vector(col, false));
for (int i = 0; i < row; ++i)
{
for (int j = 0; j < col; ++j)
{
if (dfs(board, access_map, i, j, word)) return true;
}
}
return false;
}
};
| [
"leichen.usst@gmail.com"
] | leichen.usst@gmail.com |
3303c86e8479e67e404c7e8934d4b5574a83d3b1 | f5371e78a69065c7f12ad3c599b3ca72adf7b691 | /src/app/gui.cpp | b3c0c954b29dcb3c0a49fd14df60753854b3897d | [] | no_license | LennyHEVS/RealTime | 568e1cb2a03a0e16dd8d4ac0fdb0fca1f2c4f128 | e4ddf853fc6c2dd32d0c2256c52e048208d93104 | refs/heads/master | 2023-02-02T09:42:49.813805 | 2020-12-20T17:02:47 | 2020-12-20T17:02:47 | 317,564,799 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,823 | cpp | #include <string.h>
#include <assert.h>
#include "trace/trace.h"
#include "ui-gen/resources_manager.h"
#include "ui-gen/gui.h"
#include "gui.h"
#define TOUCH_THREAD_STACK_SIZE 2048
namespace oscilloscope {
GListener gl;
Gui::Gui() :
_pGuiObserver(nullptr),
_redLedOn(false),
_xAxisPixelsPerField(0)
{
}
void Gui::initialize()
{
// Initialize the uGFX library
gfxInit();
// Initialize the display
guiInit();
guiShowPage(DP_OSCILLOSCOPE);
// Some custom drawing options
{
// Set title background
gwinSetBgColor(ghLabelTitle, RGB2COLOR(12, 12, 12));
gwinClear(ghLabelTitle);
_xAxisPixelsPerField = gwinGetWidth(ghGraph) / observer().getTDivCount();
GGraphStyle graphStyle = {
{ GGRAPH_POINT_DOT, 3, GFX_WHITE }, // Point
{ GGRAPH_LINE_NONE, 1, GFX_WHITE }, // Line (change to GGRAPH_LINE_SOLIDE to show it)
{ GGRAPH_LINE_NONE, 0, GFX_BLACK }, // X axis
{ GGRAPH_LINE_NONE, 0, GFX_BLACK }, // Y axis
{ GGRAPH_LINE_DASH, 4, GFX_GRAY, _xAxisPixelsPerField }, // X grid
{ GGRAPH_LINE_NONE, 0, GFX_GRAY, 50 }, // Y grid
GWIN_GRAPH_STYLE_POSITIVE_AXIS_ARROWS // Flags
};
// Set graph style
gwinSetBgColor(ghGraph, RGB2COLOR(100, 100, 100));
gwinClear(ghGraph);
gwinGraphSetStyle(ghGraph, &graphStyle);
// Disable red LED
setRedLed(false);
}
// We want to listen for widget events
geventListenerInit(&gl);
gwinAttachListener(&gl);
}
bool Gui::registerObserver(interface::GuiObserver * pGuiObserver)
{
if (!_pGuiObserver and pGuiObserver)
{
_pGuiObserver = pGuiObserver;
return true;
}
return false;
}
void Gui::start()
{
createTouchThread();
startBehavior();
}
void Gui::drawGraphPoints(uint16_t * values, uint16_t count, float xScale /* = 1 */)
{
const coord_t Y_SPACE = 4; // Keep a little space left on top and bottom
const coord_t MAX_WIDTH = gwinGetWidth(ghGraph);
const coord_t MAX_HEIGHT = gwinGetHeight(ghGraph) - (2 * Y_SPACE);
if (ghGraph)
{
uint32_t MAX = count;
point * const points = (point *)gfxAlloc(sizeof(point) * MAX);
if (points)
{
gwinClear(ghGraph);
// Draw grid
gwinGraphDrawAxis(ghGraph);
gwinGraphStartSet(ghGraph);
// Push values into point array
for (uint32_t i = 0; i < MAX; i++)
{
points[i].x = i * xScale;
points[i].y = values[i] * MAX_HEIGHT / 4096; // Scaling
points[i].y += Y_SPACE; // y axis offset
//points[i].y = 0.5*i; // Generate fake data
// Check if we run out of boundaries
if (points[i].x > MAX_WIDTH)
{
MAX = i; // Adjust amount of points to draw
break;
}
}
// Draw signal values
gwinGraphDrawPoints(ghGraph, points, MAX);
gfxFree(points);
}
}
}
bool Gui::isRedLedEnabled() const
{
return _redLedOn;
}
void Gui::setRedLed(bool enable)
{
_redLedOn = enable;
if (enable)
{
gwinImageOpenFile(ghRedLed, gstudioGetImageFilePath(ledredon));
}
else
{
gwinImageOpenFile(ghRedLed, gstudioGetImageFilePath(ledredoff));
}
}
bool Gui::isOscilloscopePageEnabled() const
{
return gwinGetVisible(ghPageContainerDp_oscilloscope);
}
void Gui::setTimeDivisionText(std::string text)
{
gwinSetText(ghLabelTimeDiv, text.c_str(), true);
}
void Gui::setFreqGenWaveformText(std::string text)
{
gwinSetText(ghLabelSignalForm, text.c_str(), true);
}
void Gui::setFreqGenFrequencyText(std::string text)
{
gwinSetText(ghLabelSignalFrequ, text.c_str(), true);
}
XFEventStatus Gui::processEvent()
{
#if (PORT_IDF_STM32CUBE != 0)
GEN(XFNullTransition);
gfxYield(); // Switch to next thread
#endif
return XFEventStatus::Consumed;
}
static DECLARE_THREAD_STACK(touchThread, TOUCH_THREAD_STACK_SIZE);
DECLARE_THREAD_FUNCTION(touchThreadHandler, arg)
{
GEvent * pe;
Gui & gui = *(Gui *)arg;
while (TRUE)
{
pe = geventEventWait(&gl, TIME_INFINITE);
assert(pe); // May indicate that thread stack is too small!
switch(pe->type)
{
case GEVENT_GWIN_BUTTON:
{
GHandle buttonHandle = ((GEventGWinButton*)pe)->gwin;
if (buttonHandle == ghPushButtonTrigger)
{
Trace::out("Trigger button pressed");
gui.setRedLed(!gui.isRedLedEnabled());
}
else if (buttonHandle == ghPushButtonTimePlus)
{
gui.onButtonTimePlusPressed();
}
else if (buttonHandle == ghPushButtonTimeMinus)
{
gui.onButtonTimeMinusPressed();
}
}
break;
default:
break;
}
}
#if (GFX_USE_OS_RAW32 != GFXOFF)
return 0;
#endif // GFX_USE_OS_RAW32
}
void Gui::createTouchThread()
{
gfxThreadCreate(touchThread, TOUCH_THREAD_STACK_SIZE, 3 /*makeFreeRtosPriority(osPriorityNormal)*/, &touchThreadHandler, this);
}
void Gui::onButtonTimePlusPressed()
{
_pGuiObserver->onButtonTimePlusPressed();
}
void Gui::onButtonTimeMinusPressed()
{
_pGuiObserver->onButtonTimeMinusPressed();
}
} // namespace oscilloscope
| [
"lenny.favre@students.hevs.ch"
] | lenny.favre@students.hevs.ch |
a8fa877067e044a21f25010e9bfa9c3187623b45 | 8cc95381e7c810f0ee4921fb2e6140748dd3ea57 | /100_199/100_is_same_tree.h | 335e67776f67288732c9e4a6093fc7edff5c1f8e | [] | no_license | wangchenwc/leetcode_cpp | 5691fd6091050cd09ececfa94c02497f78b88293 | 6c0c847f25710781f40a2817cb0e0152002f1755 | refs/heads/master | 2020-04-22T02:36:02.836904 | 2018-11-08T06:13:00 | 2018-11-08T06:13:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 685 | h | //
// 100_is_same_tree.h
// cpp_code
//
// Created by zhongyingli on 2018/7/11.
// Copyright © 2018 zhongyingli. All rights reserved.
//
#ifndef _00_is_same_tree_h
#define _00_is_same_tree_h
//Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(!p && !q)
return true;
if(!p || !q)
return false;
return (p->val==q->val) && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
};
#endif /* _00_is_same_tree_h */
| [
"lizhongying@ofo.com"
] | lizhongying@ofo.com |
fa3544fb48cb3f5c2edf55fa302c9b1eee1fea95 | b8dbb9de51e58afb0dd81f14a302c1b7d4e9a80a | /src/TileLayer.cpp | 8f07676ac3cc4827c3754c913a704b83f2d36ed0 | [] | no_license | tonyellis69/3DEngine | a78425cecf6f0228d6bdc5cfcdf455f00edceefd | 927954300136e67a7fa120d4c5922fe212c07ff6 | refs/heads/master | 2023-07-19T20:07:05.971617 | 2023-07-10T15:01:04 | 2023-07-10T15:01:04 | 41,534,907 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,625 | cpp | #include "TileLayer.h"
#include <iostream> //cout
#include <fstream> //ifstream
#include "Config.h"
using namespace std;
void CSceneLayer::SetParallax(float val) {
Parallax = val;
}
CTileLayer::CTileLayer(void) {
ViewOrigin.x = 0; ViewOrigin.y = 0;
LeftmostViewCol = 1; BottomVisibleRow = 1;
Repeats = false;//true;
drawableTiles = noTile -1;
}
CTileLayer::~CTileLayer(void){
//if (TileData != NULL)
//;// delete TileData;
}
/** Prepare this layer for drawing. */
void CTileLayer::InitialiseDrawing() {
Drawn = false;
CurrentDrawCol = 0; //LeftmostViewCol;
CurrentDrawRow = 0;//BottomVisibleRow;
}
/** Calculates how many rows and columns of tiles are needed to fill a view of the current size.*/
void CTileLayer::Resize(float ViewWidth,float ViewHeight) {
ViewTotalCols = (int) (ViewWidth/TileSheet->TileWidth)+2;
ViewTotalRows = (int)(ViewHeight/TileSheet->TileHeight)+2;
CalcDrawExtents();
}
void CTileLayer::CalcDrawExtents() {
if (ViewOrigin.x < 0) {
LeftmostViewCol = (int) abs(ViewOrigin.x) / TileSheet->TileWidth;
xStart = 0 - (abs(ViewOrigin.x) - (LeftmostViewCol * TileSheet->TileWidth ) );
}
else {
xStart = ViewOrigin.x;
LeftmostViewCol = 0;
}
if (ViewOrigin.y < 0) {
BottomVisibleRow = (int)abs(ViewOrigin.y) / TileSheet->TileHeight;
yStart = 0 - (abs(ViewOrigin.y) - (BottomVisibleRow * TileSheet->TileHeight ) );
}
else {
yStart = ViewOrigin.y;
BottomVisibleRow = 0;
}
if (occlusionOn) {
TopmostDrawRow = BottomVisibleRow + ViewTotalRows;
if (TopmostDrawRow > TotalRows)
TopmostDrawRow = TotalRows;
RightmostDrawCol = LeftmostViewCol + ViewTotalCols;
if (RightmostDrawCol > TotalCols)
RightmostDrawCol = TotalCols;
}
else {
TopmostDrawRow = TotalRows - BottomVisibleRow;
RightmostDrawCol = TotalCols -LeftmostViewCol ;
}
}
/** Sets the position within the tile layer of the bottom-left corner of the screen. */
void CTileLayer::SetViewOffset(int x, int y) {
ViewOrigin.set((float) x, (float) y);
// SubTileOffset.set(fmod(ViewOrigin.x, (float)TileSheet->TileWidth), fmod(ViewOrigin.y, (float)TileSheet->TileHeight));
CalcDrawExtents();
}
/** Moves the relative view position within this tile layer. */
void CTileLayer::Scroll(float x, float y) {
ViewOrigin.x += (x*Parallax);
ViewOrigin.y += (y*Parallax);
CalcDrawExtents();
//SubTileOffset.set(fmod(-ViewOrigin.x, (float)TileSheet->TileWidth), fmod(-ViewOrigin.y, (float) TileSheet->TileHeight));
}
/** Returns the tile to be found at the given row and column of this layer. */
int CTileLayer::GetTile(int col, int row) {
//row = TotalRows - row;
/* if (Repeats) { //TO DO: probably just get rid of this
if (col < 0)
col = TotalCols + (col % TotalCols)-1;
else if (col >= TotalCols)
col = col % TotalCols;
if (row < 0 )
row = TotalRows + (row % TotalRows) - 1;
else if (row >= TotalRows)
row = row % TotalRows;
}
else */
if ((col < 0)||(row < 0) || (col >= TotalCols) || (row >= TotalRows))
return noTile;
int Pos = (row * TotalCols) + col;
return (unsigned char)TileData[Pos];
}
/** Return the tile at the given row and column of the current view.*/
int CTileLayer::GetVisibleTile(int ViewCol, int ViewRow) {
int row = TotalRows - (ViewRow+1+BottomVisibleRow);
int col = ViewCol;// + LeftmostViewCol;
return GetTile(col,row);
}
/** Return the row and column at the given point on the screen. */
void CTileLayer::getRowCol(float screenX,float screenY,int& col, int& row) {
float fcol = (screenX - ViewOrigin.x ) / TileSheet->TileWidth;
float frow = (screenY - ViewOrigin.y ) / TileSheet->TileWidth;
col = (int)fcol;
row = (int) frow;
}
/** Return the tile at the give screen coordinates.*/
int CTileLayer::getTileXY(float x, float y) {
int row, col;
getRowCol(x,y,col,row);
return GetTile(col,row);
}
/** Set the given tile to the given value. */
void CTileLayer::setTile(int col, int row, char value) {
TileData[(row * TotalCols) + col] = value;
}
/** Set this tile layer to use the given tilesheet. */
void CTileLayer::SetSheet( TSpriteSheet* Sheet) {
TileSheet = Sheet;
CalcDrawExtents();
}
/** Returns data to draw a visible tile in this layer. Call this function repeatedly to draw all the visible tiles in
the current view. */
void CTileLayer::GetDrawData(TRect& Rect, int& textureNo,float& x, float& y) {
unsigned char Tile;
do { //goes up in cols then rows, eg 1,0 2,0 3,0 ... 0,1 1,1 2,1...
//TO DO: goes too far, beyond final row, check why
Tile = GetTile(CurrentDrawCol +LeftmostViewCol ,CurrentDrawRow + BottomVisibleRow);
if (Tile <= drawableTiles) {
//textureHandle = TileSheet->textureHandle;
textureNo = TileSheet->textureNo;
Rect.Map = TileSheet->Tiles[Tile];
//Rect.XOff = (float)TileSheet->TileHalfWidth;
//Rect.YOff = (float)TileSheet->TileHalfHeight;
Rect.originX = (float)TileSheet->TileHalfWidth;
Rect.originY = (float)TileSheet->TileHalfHeight;
Rect.width = (float)TileSheet->TileWidth;
Rect.height = (float)TileSheet->TileHeight;
//calculate screen coords at which to draw tile:
// x = (TileSheet->TileWidth * (CurrentDrawCol + LeftmostViewCol)) - SubTileOffset.x;
x = (xStart ) + (TileSheet->TileWidth * CurrentDrawCol);// - SubTileOffset.x ;
//y = ((CurrentDrawRow + BottomVisibleRow) * TileSheet->TileHeight) + SubTileOffset.y;
y = (yStart ) + (TileSheet->TileHeight * CurrentDrawRow);
x += TileSheet->TileHalfWidth;
y += TileSheet->TileHalfHeight;
}
CurrentDrawCol++; //find next tile to draw, if any
if (CurrentDrawCol > RightmostDrawCol) {
CurrentDrawCol = 0;// LeftmostViewCol;
CurrentDrawRow++;
}
if (CurrentDrawRow >= TopmostDrawRow) {
Drawn = true;
//break;
}
} while ((Tile > drawableTiles) && !Drawn);
}
/** Change the total number of rows and columns. Tile data is lost if it falls outside the
new dimensions of the layer. */
void CTileLayer::resizeRowCol(int newCols, int newRows) {
unsigned char* newTileData = new unsigned char[newCols * newRows];
std::fill_n(newTileData,newCols * newRows,noTile);
for (int r=0;r<newRows && r<TotalRows;r++) {
for (int c=0;c<newCols && c<TotalCols;c++) {
newTileData[(r*newCols)+c] = TileData[(r*TotalCols)+c];
}
}
delete[] TileData;
TileData = newTileData;
TotalRows = newRows; TotalCols = newCols;
CalcDrawExtents();
}
/** Add the given image to this image layer. */
void CImageLayer::AddImage(int texture, float x, float y,int width, int height) {
CSceneImage Image;
Image.tileOrTexture = texture;
Image.PosX = x; Image.PosY = y;
Image.Rect.width = (float)width; Image.Rect.height = (float)height;
Image.Rect.originX = (float)width/2; Image.Rect.originY = (float)height/2;
ImageList.push_back(Image);
}
/** Add the given image tile to this image layer. */
void CImageLayer::addImageTile(int tileNo, float x, float y,int width, int height) {
CSceneImage Image;
Image.tileOrTexture = tileNo;
Image.PosX = x; Image.PosY = y;
Image.Rect.width = (float)width;
Image.Rect.height = (float)height;
Image.Rect.originX = (float)imageSheet->TileWidth/2;
Image.Rect.originY = (float)imageSheet->TileHeight/2;
ImageList.push_back(Image);
}
/** Prepare this layer for drawing. */
void CImageLayer::InitialiseDrawing() {
DrawNext = 0;
Drawn = false;
}
/** Provide drawing data for a rectangular element of this layer. Call this function repeatedly to iterate through
all the elements of this layer. */
void CImageLayer::GetDrawData(TRect& Rect,int& TextureNo, float& x, float& y) {
//find the next image in this layer to draw...
if (DrawNext < ImageList.size()) {
if (ImageList[DrawNext].Visible) {
x = ImageList[DrawNext].PosX + ViewOrigin.x;
y = ImageList[DrawNext].PosY + ViewOrigin.y;
Rect = ImageList[DrawNext].Rect;
if (imageSheet == NULL) {
TextureNo = ImageList[DrawNext].tileOrTexture;
}
else {
Rect.Map = imageSheet->Tiles[ImageList[DrawNext].tileOrTexture];
TextureNo = imageSheet->textureNo;
}
}
DrawNext++;
return;
}
//nothing left to draw? Declare this layer 'drawn'.
Drawn = true;
}
/** Scrolls the relative screen position within this image layer. */
void CImageLayer::Scroll(float x, float y) {
ViewOrigin.x += (x*Parallax);
ViewOrigin.y += (y*Parallax);
}
/** Remove the given image from this layer. */
void CImageLayer::removeItem(int itemNo) {
ImageList.erase(ImageList.begin() + itemNo);
}
CImageLayer::~CImageLayer() {
//for (int i=0;i<ImageList.size();i++)
// ;//delete (ImageList[i]);
}
#define _SCL_SECURE_NO_WARNINGS 1
/** Create a scrollable tiled backdrop that is empty of tiles. */
CTileLayer* CSceneObj::createEmptyTileLayer(int totalCols, int totalRows) {
unsigned char* tileData = new unsigned char[totalCols * totalRows];
std::fill_n(tileData,totalCols * totalRows,noTile);
CTileLayer* result = CreateTileLayer(tileData,totalCols,totalRows);
delete[] tileData;
return result;
}
/** Create a scrollable tiled backdrop using the given tile data. */
CTileLayer* CSceneObj::CreateTileLayer(unsigned char* TileData, int TotalCols, int TotalRows) {
CTileLayer* NewLayer = new CTileLayer;
NewLayer->TileData = new unsigned char [TotalCols*TotalRows];
memcpy(NewLayer->TileData,TileData,TotalCols*TotalRows);
NewLayer->TotalCols = TotalCols;
NewLayer->TotalRows = TotalRows;
NewLayer->Type = TILE_LAYER;
LayerList.push_back(NewLayer);
return (CTileLayer*) LayerList.back();
}
/** Create an image layer and add it to the scene's list of layers. */
CImageLayer* CSceneObj::CreateImageLayer() {
CImageLayer* ImageLayer = new CImageLayer;
ImageLayer->Type = IMAGE_LAYER;
LayerList.push_back(ImageLayer);
return ImageLayer;
}
/** Return the position and dimensions of the given image. */
CRect CImageLayer::getElementDimensions(int item) {
CRect image;
image.x = ImageList[item].PosX - ImageList[item].Rect.originX;
image.y = ImageList[item].PosY - ImageList[item].Rect.originY;
image.width = ImageList[item].Rect.width;
image.height = ImageList[item].Rect.height;
return image;
}
/** Ensure the backdrop layer's images fill the current view. */
void CBackdropLayer::Resize(float ViewWidth,float ViewHeight) {
for (size_t i=0;i<ImageList.size();i++) {
ImageList[i].PosX = ViewWidth/2;
ImageList[i].PosY = ViewHeight/2;
ImageList[i].Rect.originX = ViewWidth/2;
ImageList[i].Rect.originY = ViewHeight/2;
ImageList[i].Rect.width = ViewWidth;
ImageList[i].Rect.height = ViewHeight;
}
}
void CSceneObj::CreateBackdropLayer(int Texture) {
CBackdropLayer* BackLayer;
CSceneLayer* FrontLayer = NULL;
if (LayerList.size()){ //if list contains layers
FrontLayer = LayerList[0];
if (FrontLayer->Type != BACKDROP_LAYER) { //does a backdrop layer already exist?
BackLayer = new CBackdropLayer; //no
BackLayer->Type = BACKDROP_LAYER;
}
else //yes
BackLayer = (CBackdropLayer*)FrontLayer;
}
else { //no layers?
BackLayer = new CBackdropLayer;
BackLayer->Type = BACKDROP_LAYER;
}
BackLayer->AddImage(Texture,0,0,100,100);
LayerList.insert(LayerList.begin(),BackLayer); //ensure it goes at the front of the list
BackLayer->CurrentImage = 0;
}
void CSceneObj::Resize(float ViewWidth, float ViewHeight) {
for (size_t l=0;l<LayerList.size();l++) {
LayerList[l]->Resize(ViewWidth, ViewHeight);
}
}
/** Scroll the layers of the scene object by the given amount. */
C2DVector CSceneObj::Scroll(float x, float y) {
C2DVector result(0,0);
for (size_t l=0;l<LayerList.size();l++)
LayerList[l]->Scroll(x,y);
return result; //TO DO: put some kind of boundary check here?
}
/** Prepare to draw all the visible layers of this object. Call this every frame before Draw. */
void CSceneObj::InitialiseDrawing() {
for (size_t l=0;l<LayerList.size();l++)
LayerList[l]->InitialiseDrawing();
}
/** Provide data for drawing a rectangular element of this scene.
Call this function repeatedly to iterate through all the elements of all its layers. */
bool CSceneObj::GetDrawData(TRect& Rect,int& TextureNo, float& x, float& y, rgba& drawColour) {
int size = LayerList.size();
for (int l=0;l<size;l++) {
if (!LayerList[l]->visible)
continue;
LayerList[l]->GetDrawData(Rect,TextureNo,x,y);
drawColour = LayerList[l]->drawColour;
if (!LayerList[l]->Drawn) {
return true;
}
}
return false;
}
void CSceneObj::setBackdropLayer(int Texture) {
if (!LayerList.size())
return;
//get a handle on the backdrop layer
CSceneLayer* Layer = LayerList.front();
if (Layer->Type != BACKDROP_LAYER)
return;
CBackdropLayer* BackLayer = (CBackdropLayer*)Layer;
BackLayer->ImageList[BackLayer->CurrentImage].tileOrTexture = Texture;
}
void CSceneObj::setBackdropTiling( float u, float v, float s, float t) {
//get a handle on the backdrop layer
CSceneLayer* Layer = LayerList.front();
if (Layer->Type != BACKDROP_LAYER)
return;
CBackdropLayer* BackLayer = (CBackdropLayer*)Layer;
BackLayer->ImageList[BackLayer->CurrentImage].Rect.Map.u = u;
BackLayer->ImageList[BackLayer->CurrentImage].Rect.Map.v = v;
BackLayer->ImageList[BackLayer->CurrentImage].Rect.Map.s = s;
BackLayer->ImageList[BackLayer->CurrentImage].Rect.Map.t = t;
}
void CSceneObj::deleteLayer(int layerNo) {
if (LayerList[layerNo]->Type == TILE_LAYER) {
delete[] ( ((CTileLayer*)LayerList[layerNo])->TileData );
delete LayerList[layerNo];
}
if (LayerList[layerNo]->Type == IMAGE_LAYER)
delete( (CImageLayer*)LayerList[layerNo] );
if (LayerList[layerNo]->Type == BACKDROP_LAYER)
delete( (CBackdropLayer*)LayerList[layerNo] );
}
CSceneObj::~CSceneObj() {
int size = LayerList.size();
for (int l=0;l<size;l++) {
deleteLayer(l);
}
}
| [
"tonyellis69@gmail.com"
] | tonyellis69@gmail.com |
5ba95213d2bf67114ed9ba9e9d6c0c5030692243 | ef187d259d33e97c7b9ed07dfbf065cec3e41f59 | /work/atcoder/arc/arc063/D/answers/70562_amekin.cpp | e5030c1e4d972a33893292b681b042b3af5e6b75 | [] | no_license | kjnh10/pcw | 847f7295ea3174490485ffe14ce4cdea0931c032 | 8f677701bce15517fb9362cc5b596644da62dca8 | refs/heads/master | 2020-03-18T09:54:23.442772 | 2018-07-19T00:26:09 | 2018-07-19T00:26:09 | 134,586,379 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 948 | cpp | #define _USE_MATH_DEFINES
#include <cstdio>
#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <complex>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <bitset>
#include <numeric>
#include <limits>
#include <climits>
#include <cfloat>
#include <functional>
#include <iterator>
using namespace std;
const int INF = INT_MAX / 2;
int main()
{
int n, t;
cin >> n >> t;
vector<int> a(n);
for(int i=0; i<n; ++i)
cin >> a[i];
int aMin = INF;
int diffMax = -INF;
int cnt = 0;
for(int i=0; i<n; ++i){
int diff = a[i] - aMin;
if(diff == diffMax){
++ cnt;
}
else if(diffMax < diff){
diffMax = diff;
cnt = 1;
}
aMin = min(aMin, a[i]);
}
cout << cnt << endl;
return 0;
} | [
"kojinho10@gmail.com"
] | kojinho10@gmail.com |
d9d91288f9d7b3c31be719ef5437b0dad244d364 | 0a443dbaeab480c5d05c9553d5aea9fc0c0a2af8 | /src/util.h | 570cded79eaa890e7bfa9f43338b5f4774044591 | [] | no_license | thuskey/sidescroller | 3cce32ee13d9f0bdf6198e8af581d9666a67cfa7 | f5988a550a7deb9fd52691f157af75b9527a5257 | refs/heads/master | 2021-01-15T12:49:08.732698 | 2012-06-24T04:04:15 | 2012-06-24T04:04:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 267 | h | #ifndef UTIL_H
#define UTIL_H
#include <string>
namespace Base64
{
char *Decode(char *str, int *dbufsz);
char *Encode(char *str);
char *CleanString(char *str);
};
void ParseRGB(const char *str, int *r, int *g, int *b);
#endif // UTIL_H
| [
"zxmarcos@gmail.com"
] | zxmarcos@gmail.com |
46f770e2934fb79593e6ba638e8f4d9670bf6d7e | 06a7f45d1bea8ccbc358ee7e9c8a1c517666975b | /eviction.cc | 5bcbd992614b32c6ed124b34315870e93ec04b1b | [] | no_license | ezraschwaa/CS389-hw2 | 0d93703bf5ff0b3fb544de992150e4e679cd95e2 | dd8c178f620a136f77b73e384f544b5e8a7d6789 | refs/heads/master | 2020-04-08T23:21:25.251567 | 2018-12-02T07:57:33 | 2018-12-02T07:57:33 | 159,821,423 | 0 | 1 | null | 2018-12-02T04:13:14 | 2018-11-30T12:37:21 | C++ | UTF-8 | C++ | false | false | 8,410 | cc | //By Monica Moniot and Alyssa Riceman
#include <stdlib.h>
#include "eviction.h"
#include "book.h"
#include "types.h"
constexpr Bookmark INVALID_NODE = -1;
inline Evict_item* get_evict_item(Book* book, Bookmark item_i) {
return &read_book(book, item_i)->evict_item;
}
Node* get_node(Book* book, Bookmark item_i) {
return &get_evict_item(book, item_i)->node;
}
void remove (DLL* list, Bookmark item_i, Node* node, Book* book) {
auto next_i = node->next;
auto pre_i = node->pre;
if(list->head == item_i) {
if(next_i == item_i) {//all items have been removed
list->head = INVALID_NODE;
return;
}
list->head = next_i;
}
get_node(book, pre_i)->next = next_i;
get_node(book, next_i)->pre = pre_i;
}
void append (DLL* list, Bookmark item_i, Node* node, Book* book) {
auto head = list->head;
if(head == INVALID_NODE) {
list->head = item_i;
node->next = item_i;
node->pre = item_i;
} else {
Node* head_node = get_node(book, head);
auto last = head_node->pre;
Node* last_node = get_node(book, last);
last_node->next = item_i;
head_node->pre = item_i;
node->next = head;
node->pre = last;
}
}
void prepend (DLL* list, Bookmark item_i, Node* node, Book* book) {
auto head = list->head;
list->head = item_i;
if(head == INVALID_NODE) {
node->next = item_i;
node->pre = item_i;
} else {
Node* head_node = get_node(book, head);
auto first = head_node->next;
Node* first_node = get_node(book, first);
first_node->pre = item_i;
head_node->next = item_i;
node->next = first;
node->pre = head;
}
}
void set_last (DLL* list, Bookmark item_i, Node* node, Book* book) {
auto head = list->head;
auto head_node = get_node(book, head);
auto last = head_node->pre;
auto last_node = get_node(book, last);
auto next_i = node->next;
auto pre_i = node->pre;
if(item_i == head) {
list->head = head_node->next;
return;
} else if(item_i == last) {
return;
}
last_node->next = item_i;
head_node->pre = item_i;
node->next = head;
node->pre = last;
get_node(book, pre_i)->next = next_i;
get_node(book, next_i)->pre = pre_i;
}
void set_first(DLL* list, Bookmark item_i, Node* node, Book* book) {
auto head = list->head;
auto head_node = get_node(book, head);
list->head = item_i;
if(item_i == head) {
return;
}
auto first = head_node->next;
auto first_node = get_node(book, first);
auto next_i = node->next;
auto pre_i = node->pre;
first_node->pre = item_i;
head_node->next = item_i;
node->next = first;
node->pre = head;
get_node(book, pre_i)->next = next_i;
get_node(book, next_i)->pre = pre_i;
}
void create_evictor(Evictor* evictor, evictor_type policy) {
evictor->policy = policy;
if(policy == FIFO or policy == LIFO or policy == LRU or policy == MRU or policy == CLOCK) {
auto list = &evictor->data.list;
list->head = INVALID_NODE;
} else if(policy == SLRU) {
auto dlist = &evictor->data.dlist;
auto protect = &evictor->data.dlist.protect;
auto prohibate = &evictor->data.dlist.prohibate;
protect->head = INVALID_NODE;
prohibate->head = INVALID_NODE;
dlist->pp_delta = 0;
} else {//RANDOM
evictor->data.rand_data.total_items = 0;
}
}
void add_evict_item (Evictor* evictor, Bookmark item_i, Evict_item* item, Book* book) {
//item was created
//we must init "item"
auto policy = evictor->policy;
if(policy == FIFO or policy == LRU) {
auto node = &item->node;
append(&evictor->data.list, item_i, node, book);
} else if(policy == LIFO or policy == MRU) {
auto node = &item->node;
prepend(&evictor->data.list, item_i, node, book);
} else if(policy == CLOCK) {
auto node = &item->node;
node->rf_bit = false;
append(&evictor->data.list, item_i, node, book);
} else if(policy == SLRU) {
auto dlist = &evictor->data.dlist;
auto prohibate = &evictor->data.dlist.prohibate;
auto node = &item->node;
node->rf_bit = false;
dlist->pp_delta += 1;
append(prohibate, item_i, node, book);
} else {//RANDOM
auto data = &evictor->data.rand_data;
auto rand_items = static_cast<Bookmark*>(evictor->mem_arena);
item->rand_i = data->total_items;
rand_items[data->total_items] = item_i;
data->total_items += 1;
}
}
void remove_evict_item (Evictor* evictor, Bookmark item_i, Evict_item* item, Book* book) {
//item was removed
auto policy = evictor->policy;
if(policy == FIFO or policy == LIFO or policy == LRU or policy == MRU or policy == CLOCK) {
auto node = &item->node;
remove(&evictor->data.list, item_i, node, book);
} else if(policy == SLRU) {
auto dlist = &evictor->data.dlist;
auto protect = &evictor->data.dlist.protect;
auto prohibate = &evictor->data.dlist.prohibate;
auto node = &item->node;
if(node->rf_bit) {
dlist->pp_delta += 1;
remove(protect, item_i, node, book);
} else {
if(dlist->pp_delta == 0) {//evict from protected
auto p_item = protect->head;
auto p_node = get_node(book, p_item);
remove(protect, p_item, p_node, book);
append(prohibate, p_item, p_node, book);
dlist->pp_delta += 1;
} else {
dlist->pp_delta -= 1;
}
remove(prohibate, item_i, node, book);
}
} else {//RANDOM
auto data = &evictor->data.rand_data;
auto rand_items = static_cast<Bookmark*>(evictor->mem_arena);
//We need to delete from rand_items in place
//this requires us to relink some data objects
Bookmark rand_i0 = item->rand_i;
auto rand_i1 = data->total_items - 1;
data->total_items = rand_i1;
auto item_i1 = get_evict_item(book, rand_items[rand_i1]);
rand_items[rand_i0] = rand_items[rand_i1];
item_i1->rand_i = rand_i0;
}
}
void touch_evict_item (Evictor* evictor, Bookmark item_i, Evict_item* item, Book* book) {
//item was touched
auto policy = evictor->policy;
if(policy == FIFO or policy == LIFO) {
} else if(policy == LRU) {
auto node = &item->node;
set_last(&evictor->data.list, item_i, node, book);
} else if(policy == MRU) {
auto node = &item->node;
set_first(&evictor->data.list, item_i, node, book);
} else if(policy == CLOCK) {
auto node = &item->node;
node->rf_bit = true;
set_last(&evictor->data.list, item_i, node, book);
} else if(policy == SLRU) {
auto dlist = &evictor->data.dlist;
auto protect = &evictor->data.dlist.protect;
auto prohibate = &evictor->data.dlist.prohibate;
auto node = &item->node;
if(node->rf_bit) {
set_last(protect, item_i, node, book);
} else {
node->rf_bit = true;
remove(prohibate, item_i, node, book);
append(protect, item_i, node, book);
if(dlist->pp_delta <= 1) {//evict from protected
auto p_item = protect->head;
auto p_node = get_node(book, p_item);
remove(protect, p_item, p_node, book);
append(prohibate, p_item, p_node, book);
} else {
dlist->pp_delta -= 2;
}
}
} else {//RANDOM
}
}
Bookmark get_evict_item(Evictor* evictor, Book* book) {
//return item to evict
auto policy = evictor->policy;
Bookmark item_i = 0;
if(policy == FIFO or policy == LIFO or policy == LRU or policy == MRU) {
auto list = &evictor->data.list;
item_i = list->head;
remove(list, item_i, get_node(book, item_i), book);
} else if(policy == CLOCK) {
auto list = &evictor->data.list;
item_i = list->head;
auto node = get_node(book, item_i);
while(node->rf_bit) {
node->rf_bit = false;
item_i = get_node(book, item_i)->next;
list->head = item_i;
}
remove(list, item_i, node, book);
} else if(policy == SLRU) {
auto dlist = &evictor->data.dlist;
auto protect = &evictor->data.dlist.protect;
auto prohibate = &evictor->data.dlist.prohibate;
item_i = prohibate->head;
if(dlist->pp_delta == 0) {//evict from protected
auto p_item = protect->head;
auto p_node = get_node(book, p_item);
remove(protect, p_item, p_node, book);
append(prohibate, p_item, p_node, book);
dlist->pp_delta += 1;
} else {
dlist->pp_delta -= 1;
}
auto node = get_node(book, item_i);
remove(prohibate, item_i, node, book);
} else {//RANDOM
auto data = &evictor->data.rand_data;
auto rand_items = static_cast<Bookmark*>(evictor->mem_arena);
auto rand_i0 = rand()%data->total_items;
item_i = rand_items[rand_i0];
//We need to delete rand_i0 from rand_items in place
//this requires us to relink some data objects
auto rand_i1 = data->total_items - 1;
data->total_items = rand_i1;
auto item_i1 = get_evict_item(book, rand_items[rand_i1]);
rand_items[rand_i0] = rand_items[rand_i1];
item_i1->rand_i = rand_i0;
}
return item_i;
}
| [
"mmoniot2@gmail.com"
] | mmoniot2@gmail.com |
5a160ce85e1b0c75b3d8eb4af849020c7e13ef86 | 7cd9751c057fcb36b91f67e515aaab0a3e74a709 | /src/time_data/DT_Calculator_Exponential.cc | 50022cf0071c8d3d0230b2ae963ccf50e4928db4 | [
"MIT"
] | permissive | pgmaginot/DARK_ARTS | 5ce49db05f711835e47780677f0bf02c09e0f655 | f04b0a30dcac911ef06fe0916921020826f5c42b | refs/heads/master | 2016-09-06T18:30:25.652859 | 2015-06-12T19:00:40 | 2015-06-12T19:00:40 | 20,808,459 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 597 | cc | #include "DT_Calculator_Exponential.h"
DT_Calculator_Exponential::DT_Calculator_Exponential(const Input_Reader& input_reader)
:
V_DT_Calculator( input_reader ),
m_ratio{input_reader.get_time_start_exponential_ratio() } ,
m_step_max{ int(ceil( log(m_dt_max/m_dt_min) / log(m_ratio) )) }
{
}
double DT_Calculator_Exponential::calculate_dt(const int step, const double dt_old, const double adapt_criteria)
{
double dt;
if(step ==0)
{
dt = m_dt_min;
}
else
{
dt = dt_old*m_ratio;
}
if( dt > m_dt_max)
dt = m_dt_max;
return dt;
} | [
"pmaginot@tamu.edu"
] | pmaginot@tamu.edu |
e497dd29d2cdc8b67fb0273183975269144dd415 | 5053643ca7238f10af0e37db9d576816cbf6f3a2 | /Pkg/Pkg.HC | 84e7e2f32d5ccc4a3c4ac6edb877b23001fa472c | [] | no_license | K1ish/ReggieOS2 | 13de45f5d5b03cc5a31cb018200b2f9304cb699d | 123429de1941780de9f97884c7dd216a9eab5089 | refs/heads/master | 2020-04-14T12:53:45.369076 | 2019-01-02T16:16:18 | 2019-01-02T16:16:18 | 163,853,668 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 11,227 | hc | // vim: set ft=cpp:
#include "::/Adam/Net/Url"
#define PKG_EURL (-20001)
#define PKG_EMOUNT (-20002)
#define PKG_EMANIFEST (-20003)
#define PKG_EVERSION (-20004)
#define PKG_EOSVERSION (-20005)
#define PKG_EUNSUITABLE (-20006)
#define PKG_VERSION 11
static U8* PKG_BASE_URL = "http://shrineupd.clanweb.eu/packages";
static U8* PKG_LOCAL_REPO = "::/Misc/Packages";
static U8* PKG_TMP_DIR = "::/Tmp/PkgTmp";
class CPkgInfo {
U8* package_name;
I32 pkgmin;
I32 release;
I32 osmin;
I32 osmax;
I64 size;
U8* version;
U8* installdir;
U8* iso_c;
U8* post_install_doc;
};
// TODO: Is there a built-in for this?
static U8* StripDir(U8* file_path) {
U8* slash = StrLastOcc(file_path, "/");
if (slash)
return slash + 1;
else
return file_path;
}
U0 PkgInfoInit(CPkgInfo* pinf) {
pinf->package_name = 0;
pinf->pkgmin = 0x7fffffff;
pinf->release = 0;
pinf->osmin = 0;
pinf->osmax = 0x7fffffff;
pinf->size = 0;
pinf->version = 0;
pinf->installdir = 0;
pinf->iso_c = 0;
pinf->post_install_doc = 0;
}
U0 PkgInfoFree(CPkgInfo* pinf) {
Free(pinf->package_name);
Free(pinf->version);
Free(pinf->installdir);
Free(pinf->iso_c);
Free(pinf->post_install_doc);
PkgInfoInit(pinf);
}
// Returns 0 or error code
I64 PkgParseManifest(CPkgInfo* pinf, U8* manifest) {
U8* key = manifest;
while (*key) {
//"?%s", key;
U8* end = StrFirstOcc(key, "\n");
if (end) {
*end = 0;
end++;
}
else
end = key + StrLen(key);
U8* value = StrFirstOcc(key, "\t");
if (!value)
return PKG_EMANIFEST;
*value = 0;
value++;
//"%s=%s;\n", key, value;
if (0) {}
else if (!StrCmp(key, "name")) { Free(pinf->package_name); pinf->package_name = StrNew(value); }
else if (!StrCmp(key, "pkgmin")) { pinf->pkgmin = Str2I64(value); }
else if (!StrCmp(key, "release")) { pinf->release = Str2I64(value); }
else if (!StrCmp(key, "osmin")) { pinf->osmin = Str2I64(value); }
else if (!StrCmp(key, "osmax")) { pinf->osmax = Str2I64(value); }
else if (!StrCmp(key, "size")) { pinf->size = Str2I64(value); }
else if (!StrCmp(key, "version")) { Free(pinf->version); pinf->version = StrNew(value); }
else if (!StrCmp(key, "installdir")) { Free(pinf->installdir); pinf->installdir = StrNew(value); }
else if (!StrCmp(key, "iso.c")) { Free(pinf->iso_c); pinf->iso_c = StrNew(value); }
else if (!StrCmp(key, "post-install-doc")) { Free(pinf->post_install_doc); pinf->post_install_doc = StrNew(value); }
else { /* unrecognized keys are simply ignored */ }
key = end;
}
return 0;
}
I64 PkgWriteManifest(CPkgInfo* pinf, U8* path) {
// TODO: implement
no_warn pinf;
FileWrite(path, "", 0);
return 0;
}
// Downloads a package info from the repository.
// Returns 0 or error code
I64 PkgFetchManifest(CPkgInfo* pinf, U8* package_name) {
// Old packages didn't have to specify a name, so we'll keep this for now
pinf->package_name = StrNew(package_name);
U8* url = MStrPrint("%s/%s", PKG_BASE_URL, package_name);
U8* manifest = 0;
I64 size = 0;
I64 error = UrlGet(url, &manifest, &size);
if (error == 0)
error = PkgParseManifest(pinf, manifest);
Free(manifest);
Free(url);
return error;
}
// Get the URL of the package's ISO.C download.
// Returns NULL if N/A, otherwise must be Free()d.
U8* PkgAllocISOCUrl(CPkgInfo* pinf) {
if (!pinf->iso_c)
return NULL;
// A bit hacky, but will probably always work
if (StrFind("//", pinf->iso_c))
return StrNew(pinf->iso_c);
else
return MStrPrint("%s/%s", PKG_BASE_URL, pinf->iso_c);
}
// Check if the package metadata makes it viable for installation.
// You still need to do PkgCheckCompatibility, dependency resolution,
// and check for a suitable installable format.
Bool PkgIsInstallable(CPkgInfo* pinf) {
return pinf->package_name != NULL && pinf->version != NULL && pinf->installdir != NULL;
}
// Check if the package is compatible with this OS & Pkg version
I64 PkgCheckCompatibility(CPkgInfo* pinf) {
if (pinf->pkgmin > PKG_VERSION) {
"$FG,6$This package requires a more recent version of $FG,5$Pkg\n";
"$FG$Please update.\n";
return PKG_EVERSION;
}
I64 osver = ToI64(sys_os_version * 100);
if (osver < pinf->osmin) {
"$FG,6$This package requires a more recent system version.\n";
"$FG$Please update. (need %d, have %d)\n", pinf->osmin, osver;
return PKG_EOSVERSION;
}
if (osver > pinf->osmax) {
"$FG,6$This package is not compatible with your system version.\n";
"$FG$Last supported version is %d, you have %d.\n", pinf->osmax, osver;
return PKG_EOSVERSION;
}
return 0;
}
I64 PkgRegister(CPkgInfo* pinf) {
// TODO: this is very preliminary
if (pinf->package_name == NULL)
return PKG_EUNSUITABLE;
U8* path = MStrPrint("%s/%s", PKG_LOCAL_REPO, pinf->package_name);
PkgWriteManifest(pinf, path);
return 0;
}
// Install a package, using the provided ISO.C file.
// This will also register the package as installed.
I64 PkgInstallISOC(CPkgInfo* pinf, U8* iso_c) {
if (pinf->package_name == NULL || pinf->installdir == NULL)
return PKG_EUNSUITABLE;
I64 error = 0;
"Installing %s\n$FG,7$", pinf->package_name;
I64 letter = MountFile(iso_c);
if (letter) {
U8 src_path[8];
StrPrint(src_path, "%c:/", letter);
// StrLen check is a temporary hack to not complain about MkDir("::/");
if (StrLen(pinf->installdir) > 3)
DirMk(pinf->installdir);
CopyTree(src_path, pinf->installdir);
// Register package as installed
error = PkgRegister(pinf);
// Display post-install doc
if (pinf->post_install_doc) {
Ed(pinf->post_install_doc);
}
}
else
error = PKG_EMOUNT;
Unmount(letter);
"$FG$";
return error;
}
// Verify, download & install a single package
// All dependencies must have been installed at this point.
I64 PkgDownloadAndInstall(CPkgInfo* pinf) {
I64 error = PkgCheckCompatibility(pinf);
if (error) { return error; }
U8* iso_c_url = PkgAllocISOCUrl(pinf);
if (iso_c_url) {
U8* iso_data = 0;
I64 iso_size = 0;
"Downloading %s...\n", pinf->package_name;
error = UrlGetWithProgress(iso_c_url, &iso_data, &iso_size);
if (error == 0) {
U8* tmppath = "::/Tmp/Package.ISO.C";
FileWrite(tmppath, iso_data, iso_size);
error = PkgInstallISOC(pinf, tmppath);
}
Free(iso_data);
Free(iso_c_url);
}
else {
"$FG,6$No suitable download address. Package broken?\n";
error = PKG_EUNSUITABLE;
}
return error;
}
// Expected max length: 5 ("1023k")
static U8* FormatSize(I64 size) {
static U8 buf[16];
if (size > 0x40000000)
StrPrint(buf, "%dG", (size + 0x3fffffff) / 0x40000000);
else if (size > 0x100000)
StrPrint(buf, "%dM", (size + 0xfffff) / 0x100000);
else if (size > 0x400)
StrPrint(buf, "%dk", (size + 0x3ff) / 0x400);
else
StrPrint(buf, "%d", size);
return buf;
}
// Install a package using a local manifest file
public I64 PkgInstallFromFile(U8* manifest_path) {
DirMk(PKG_LOCAL_REPO);
CPkgInfo pinf;
PkgInfoInit(&pinf);
// Parse manifest
I64 manifest_size;
U8* manifest_file = FileRead(manifest_path, &manifest_size);
// This relies on FileRead returning a 0-terminated buffer.
// As of v502, this happens for all file systems
I64 error = PkgParseManifest(&pinf, manifest_file);
if (error == 0) {
error = PkgCheckCompatibility(&pinf);
if (!error) {
if (pinf.iso_c) {
PkgInstallISOC(&pinf, pinf.iso_c);
}
else {
"$FG,6$No suitable installable file. Package broken?\n";
error = PKG_EUNSUITABLE;
}
}
else {
"$FG,4$PkgCheckCompatibility error: %d\n$FG$", error;
}
}
else {
"$FG,4$PkgParseManifest error: %d\n$FG$", error;
}
PkgInfoFree(&pinf);
return error;
}
// Install a package from the repository
public I64 PkgInstall(U8* package_name) {
SocketInit();
DirMk(PKG_LOCAL_REPO);
CPkgInfo pinf;
PkgInfoInit(&pinf);
I64 error = PkgFetchManifest(&pinf, package_name);
if (error == 0) {
if (PkgIsInstallable(&pinf)) {
"$FG,8$ Package Ver \n"
"$FG,8$ Dir Size \n"
"$FG,8$============================\n"
"$FG,2$+ %-20s %-6s\n", package_name, pinf.version;
"$FG,2$ %-20s %-6s\n", pinf.installdir, FormatSize(pinf.size);
"\n"
"$FG$Is this ok? (y/n) ";
I64 ok = GetKey(NULL, TRUE);
"\n";
// TODO: verify all packages before we start downloading
if (ok == 'y') {
error = PkgDownloadAndInstall(&pinf);
if (error == 0) {
"$FG,2$Installed 1 package(s)\n";
}
else {
"$FG,4$PkgDownloadAndInstall error: %d\n$FG$", error;
}
}
}
else {
"$FG,4$PkgInstall: %s is not installable\n$FG$", package_name;
error = PKG_EUNSUITABLE;
}
}
else {
"$FG,4$PkgFetchManifest error: %d\n$FG$", error;
}
PkgInfoFree(&pinf);
return error;
}
// List packages available in the repository
public I64 PkgList() {
SocketInit();
U8* url = MStrPrint("%s/packages.list", PKG_BASE_URL);
U8* list = 0;
I64 size = 0;
I64 error = UrlGet(url, &list, &size);
if (error == 0) {
"$FG,2$%s\n", list;
/*U8* entry = list;
while (*entry) {
U8* end = StrFirstOcc(entry, "\n");
if (end) {
*end = 0;
end++;
}
else
end = value + StrLen(value);
"$FG,2$%s\n", entry;
entry = end;
}*/
}
else {
"$FG,4$UrlGet error: %d\n$FG$", error;
}
Free(list);
Free(url);
return error;
}
// Build a package from directory contents
public I64 PkgMakeFromDir(U8* manifest_path, U8* src_dir) {
CPkgInfo pinf;
PkgInfoInit(&pinf);
// Parse manifest
I64 manifest_size;
U8* manifest_file = FileRead(manifest_path, &manifest_size);
// This relies on FileRead returning a 0-terminated buffer.
// As of v502, this happens for all file systems
I64 error = PkgParseManifest(&pinf, manifest_file);
if (error == 0) {
// Build RedSea ISO
if (pinf.iso_c) {
U8* iso_path = pinf.iso_c;
// RedSeaISO doesn't return a proper error code
RedSeaISO(iso_path, src_dir);
// TODO: update & save manifest
/*CDirEntry* de;
if (FileFind(iso_path, &de)) {
pinf.size = de.size;
// Save updated manifest
PkgWriteManifest(&pinf, manifest_path);
Free(de->full_name);
}
else {
"$FG,6$Something went wrong, can't stat %s.\n", iso_path;
error = PKG_EMOUNT;
}*/
}
else {
"$FG,6$No output file defined.\n";
error = PKG_EUNSUITABLE;
}
}
else {
"$FG,4$PkgParseManifest error: %d\n$FG$", error;
}
PkgInfoFree(&pinf);
return error;
}
// Build a package using a single file
I64 PkgMakeFromFile(U8* manifest_path, U8* file_path) {
DelTree(PKG_TMP_DIR);
DirMk(PKG_TMP_DIR);
U8* tmppath = MStrPrint("%s/%s", PKG_TMP_DIR, StripDir(file_path));
Copy(file_path, tmppath);
I64 error = PkgMakeFromDir(manifest_path, PKG_TMP_DIR);
Free(tmppath);
return error;
}
| [
"minexew@gmail.com"
] | minexew@gmail.com |
3c543e257bd4ba8741f8f7fe4dabcfe2f68056fc | 03b5b626962b6c62fc3215154b44bbc663a44cf6 | /src/instruction/KXORW.cpp | 5a834ac449502fc204d5c2c6d801b2220b8dcc43 | [] | no_license | haochenprophet/iwant | 8b1f9df8ee428148549253ce1c5d821ece0a4b4c | 1c9bd95280216ee8cd7892a10a7355f03d77d340 | refs/heads/master | 2023-06-09T11:10:27.232304 | 2023-05-31T02:41:18 | 2023-05-31T02:41:18 | 67,756,957 | 17 | 5 | null | 2018-08-11T16:37:37 | 2016-09-09T02:08:46 | C++ | UTF-8 | C++ | false | false | 175 | cpp | #include "KXORW.h"
int CKXORW::my_init(void *p)
{
this->name = "CKXORW";
this->alias = "KXORW";
return 0;
}
CKXORW::CKXORW()
{
this->my_init();
}
CKXORW::~CKXORW()
{
}
| [
"hao__chen@sina.com"
] | hao__chen@sina.com |
ee458e9dfe3a5a4b32ca25aa8eee3348a21a77cf | 8dd39b654dde37c6cbde38a7e3a5c9838a237b51 | /Tiles/main.cpp | a47dca7498b5e5057a888a402a92e24d42e8476e | [] | no_license | Taohid0/C-and-C-Plus-Plus | 43726bdaa0dc74860c4170b729e34cea268008fd | d38fd51851cc489302ad4ef6725f1d19f7e72ec2 | refs/heads/master | 2021-07-19T17:30:26.875749 | 2017-10-28T09:49:51 | 2017-10-28T09:49:51 | 108,636,340 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 375 | cpp | #include <bits/stdc++.h>
using namespace std;
int main()
{
long long l,w,a,row = 0,col = 0;
scanf("%lld%lld%lld",&l,&w,&a);
if(l%a==0){
row = l/a;
}
else
{
row = l/a;
row++;
}
if(w%a==0){
col = w/a;
}
else
{
col = w/a;
col++;
}
printf("%lld\n",row*col);
return 0;
}
| [
"taohidulii@gmail.com"
] | taohidulii@gmail.com |
6e2e578b567ffb054e6353663991f748dfefa7e5 | b978831035e277137e807c522e9d300d802ca2df | /MARIO/Camera.cpp | 71aa011b2b5195f08d60b5a69aa55ae2383926e2 | [] | no_license | CathanBertram/SDLProject | fbb73857a4e4895b5e32fce3fa400e715829c5b4 | 688f36c6b357e02ce98bd42b5ea12a6b56f8331a | refs/heads/master | 2021-01-30T12:18:53.350154 | 2020-04-28T17:17:27 | 2020-04-28T17:17:27 | 243,498,874 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 597 | cpp | #include "Camera.h"
Camera::Camera(Rect2D startRect)
{
mRect = startRect;
}
Camera::~Camera()
{
}
void Camera::SetPosition(Rect2D rect)
{
mRect.x = (rect.x + rect.w / 2) - SCREEN_WIDTH / 2;
mRect.y = (rect.y + rect.h / 2) - SCREEN_WIDTH / 2;
}
void Camera::SetLevelDimensions(int w, int h)
{
levelWidth = w;
levelHeight = h;
}
void Camera::Update()
{
if (mRect.x < 0)
{
mRect.x = 0;
}
if (mRect.y < 0)
{
mRect.y = 0;
}
if (mRect.x > levelWidth - mRect.w)
{
mRect.x = levelWidth - mRect.w;
}
if (mRect.y > levelHeight - mRect.h)
{
mRect.y = levelHeight - mRect.h;
}
}
| [
"55544660+CathanBertram@users.noreply.github.com"
] | 55544660+CathanBertram@users.noreply.github.com |
aa279ae62b91140b13d05d86a2341a63a4dfc139 | ea4396937e4786340cf1ba67dfadd89599b09a3b | /EVENTS/GeoClawOpenFOAM/floatingbds.h | 82e01b8678accb01180ca78e3f5056f6e5e3825e | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | NHERI-SimCenter/HydroUQ | aca37869aba6d37b79b533bab36066a4ff8be163 | d4cbaed1a6f76057cb851a09e0e8996caa02e806 | refs/heads/master | 2023-08-30T08:21:21.471683 | 2023-08-23T06:58:32 | 2023-08-23T06:58:32 | 264,027,881 | 4 | 15 | NOASSERTION | 2023-08-22T21:50:41 | 2020-05-14T21:21:22 | C++ | UTF-8 | C++ | false | false | 403 | h | #ifndef FLOATINGBDS_H
#define FLOATINGBDS_H
#include <QFrame>
namespace Ui {
class floatingbds;
}
class floatingbds : public QFrame
{
Q_OBJECT
public:
explicit floatingbds(int, QWidget *parent = nullptr);
~floatingbds();
bool getData(QMap<QString, QString>&,int);
void refreshData(int);
private:
void hideshowelems(int);
Ui::floatingbds *ui;
};
#endif // FLOATINGBDS_H
| [
"fmckenna@berkeley.edu"
] | fmckenna@berkeley.edu |
42775ed50fe5656f0fd32c16d9e4b0f3f646fc85 | c845d539ce0cbe4d6b0f1e9bac5cb66697253e06 | /protos/combat/src/monster.h | 4b28b1a8ca6d71a4ad77b6a859e77f596a57b653 | [] | no_license | supermuumi/nultima | ea096cc56cc13263ba8cc8794d1f472695237752 | 6bb6fa9144932f5bac29661fd39b288d4a57144f | refs/heads/master | 2018-12-28T23:03:05.918638 | 2013-10-12T21:27:02 | 2013-10-12T21:27:02 | 12,048,244 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,016 | h | #include "vec3.h"
typedef struct
{
int x;
int y;
} Vec2;
class Player;
class Monster
{
public:
enum Stage
{
UNDECIDED,
WAITING,
MOVING,
MELEE_ATTACK,
END
};
typedef struct
{
Monster::Stage stage;
float duration;
} Strategy;
Monster(Vec2 position);
~Monster() {};
void render(bool isActive);
void tick();
void prepare();
void move();
void attack();
bool isActive() { return (m_stage != END); }
bool isAlive() { return m_hp > 0; }
Vec2 getPosition() { return m_position; }
private:
Player* findClosestPlayer(int& distance);
Vec2 m_position;
Vec3 m_color;
double m_lastColorChange;
int m_stage;
Strategy const* m_strategy;
double m_lastStageChange;
int m_strategyStep;
int m_hp;
Player* m_targetPlayer;
}; | [
"sampo@umbrasoftware.com"
] | sampo@umbrasoftware.com |
8cf26146ccce5b3c26d6f702f4a1f5c4c0dc3de7 | c1ff870879152fba2b54eddfb7591ec322eb3061 | /plugins/render/ogreRender/3rdParty/ogre/RenderSystems/GLES/include/EGL/OgreEGLContext.h | 85a9b426e284c84ea5b472c970d4f3a48ab7120a | [
"LicenseRef-scancode-free-unknown",
"MIT"
] | permissive | MTASZTAKI/ApertusVR | 1a9809fb7af81c3cd7fb732ed481ebe4ce66fefa | 424ec5515ae08780542f33cc4841a8f9a96337b3 | refs/heads/0.9 | 2022-12-11T20:03:42.926813 | 2019-10-11T09:29:45 | 2019-10-11T09:29:45 | 73,708,854 | 188 | 55 | MIT | 2022-12-11T08:53:21 | 2016-11-14T13:48:00 | C++ | UTF-8 | C++ | false | false | 2,402 | h | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2008 Renato Araujo Oliveira Filho <renatox@gmail.com>
Copyright (c) 2000-2014 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#ifndef __EGLContext_H__
#define __EGLContext_H__
#include "OgreGLESContext.h"
namespace Ogre {
class EGLSupport;
class _OgrePrivate EGLContext: public GLESContext
{
protected:
::EGLConfig mConfig;
const EGLSupport* mGLSupport;
::EGLSurface mDrawable;
::EGLContext mContext;
EGLDisplay mEglDisplay;
public:
EGLContext(EGLDisplay eglDisplay, const EGLSupport* glsupport, ::EGLConfig fbconfig, ::EGLSurface drawable);
virtual ~EGLContext();
virtual void _createInternalResources(EGLDisplay eglDisplay, ::EGLConfig glconfig, ::EGLSurface drawable, ::EGLContext shareContext);
virtual void _destroyInternalResources();
virtual void setCurrent();
virtual void endCurrent();
virtual GLESContext* clone() const = 0;
EGLSurface getDrawable() const;
};
}
#endif
| [
"peter.kovacs@sztaki.mta.hu"
] | peter.kovacs@sztaki.mta.hu |
47415f8da5c54b2ce37b4ba79be2e2db7b8487ac | 77444adf8e53fd71923f946864307664e61d8066 | /src_/SphMutexLock.cc | f3fe4ffc30b0088d5549dc635eff042ef633764b | [] | no_license | zhanMingming/MiniCacheServer | 17f1918fba8ec84649e3307ea1496516413d16e0 | 5b3a3480706760f27e11380d12a0e8f625d63323 | refs/heads/master | 2021-06-18T03:23:49.652665 | 2017-06-13T13:38:01 | 2017-06-13T13:38:01 | 94,216,047 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 677 | cc | #include"SphMutexLock.h"
#include"common.h"
namespace zhanmm {
SphMutexLock::SphMutexLock()
{
int ret = pthread_mutex_init(&m_mutex, NULL);
CHECK((ret == -1),"pthread_mutex_init");
}
void SphMutexLock::lock()
{
int ret = pthread_mutex_lock(&m_mutex);
CHECK((ret == -1),"pthread_mutex_lock");
}
void SphMutexLock::unlock()
{
int ret = pthread_mutex_unlock(&m_mutex);
CHECK((ret == -1), "pthread_mutex_unlock");
}
pthread_mutex_t* SphMutexLock::getMutexPtr()
{
return &m_mutex;
}
SphMutexLock::~SphMutexLock()
{
int ret = pthread_mutex_destroy(&m_mutex);
CHECK((ret == -1),"pthread_mutex_destroy");
}
} // namespace zhanmm
| [
"1358732502@qq.com"
] | 1358732502@qq.com |
7243f4c0c8d39b80454c5744141e3de515d27913 | 8739b721db20897c3729d3aa639f5d08e19b6a30 | /Leetcode-cpp-solution/57.cpp | 9f17e18ac8f0a5e4b486705f0d6493e2ead595fb | [] | no_license | Leetcode-W010/Answers | 817414ca101f2d17050ebc471153fbed81f67cd0 | b4fff77ff3093fab76534d96b40e6bf98bef42c5 | refs/heads/master | 2021-01-19T22:13:49.134513 | 2015-12-13T01:30:36 | 2015-12-13T01:30:36 | 40,616,166 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,285 | cpp | /*
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].
This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
*/
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
class Solution {
public:
vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
vector<Interval> rst;
int n = intervals.size();
int k = 0;
while(k<n && intervals[k].end < newInterval.start) rst.push_back(intervals[k++]);
if(k==n || newInterval.end < intervals[k].start) {
rst.push_back(newInterval);
rst.insert(rst.end(), intervals.begin()+k, intervals.end());
} else {
rst.push_back(Interval(min(newInterval.start, intervals[k].start), max(newInterval.end, intervals[k].end)));
int i = k+1;
while(i < n) {
if(intervals[i].start > rst.back().end)
break;
rst.back().end = max(rst.back().end, intervals[i++].end);
}
rst.insert(rst.end(), intervals.begin()+i, intervals.end());
}
return rst;
}
};
class Solution {
public:
vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
vector<Interval> rst;
int n = intervals.size();
int k = 0;
while(k<n && intervals[k].end < newInterval.start)
rst.push_back(intervals[k++]);
if(k<n)
newInterval.start = min(newInterval.start, intervals[k].start);
while(k<n && intervals[k].start <= newInterval.end)
newInterval.end = max(newInterval.end, intervals[k++].end);
rst.push_back(newInterval);
while(k<n)
rst.push_back(intervals[k++]);
return rst;
}
}; | [
"vincent.zhang.us@gmail.com"
] | vincent.zhang.us@gmail.com |
f5da90390f903fabf34f7f523b438d3ffedca1f4 | 88e378f925bbd8dddd271e19a51477a5201c32eb | /GRMFixes/ZenGin/Gothic_II_Addon/API/oViewDialogInventory.h | e89463977aa635383dd245309847dbc9f583725b | [
"MIT"
] | permissive | ThielHater/GRMFixes_Union | d71dcc71f77082feaf4036785acc32255fbeaaa9 | 4cfff09b5e7b1ecdbc13d903d44727eab52703ff | refs/heads/master | 2022-11-26T21:41:37.680547 | 2022-11-06T16:30:08 | 2022-11-06T16:30:08 | 240,788,948 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,121 | h | // Supported with union (c) 2018 Union team
#ifndef __OVIEW_DIALOG_INVENTORY_H__VER3__
#define __OVIEW_DIALOG_INVENTORY_H__VER3__
namespace Gothic_II_Addon {
class oCViewDialogInventory : public zCViewDialog {
public:
zCLASS_DECLARATION( oCViewDialogInventory )
enum oEInventoryAlignment {
oEInventoryAlignment_Left,
oEInventoryAlignment_Right
};
oEInventoryAlignment oTInventoryAlignment;
oEInventoryAlignment oTAlignmentInventory;
oCNpcInventory* Inventory;
oEInventoryAlignment Alignment;
void oCViewDialogInventory_OnInit() zCall( 0x00689020 );
oCViewDialogInventory() zInit( oCViewDialogInventory_OnInit() );
void __fastcall SetInventory( oCNpcInventory* ) zCall( 0x006890D0 );
void __fastcall SetAlignment( oEInventoryAlignment ) zCall( 0x00689100 );
oCItem* __fastcall GetSelectedItem() zCall( 0x00689110 );
int __fastcall GetSelectedItemCount() zCall( 0x00689130 );
oCItem* __fastcall RemoveSelectedItem() zCall( 0x00689150 );
void __fastcall InsertItem( oCItem* ) zCall( 0x006891E0 );
int __fastcall CanHandleLeft() zCall( 0x00689200 );
int __fastcall CanHandleRight() zCall( 0x00689210 );
static zCObject* _CreateNewInstance() zCall( 0x00688F30 );
/* for zCObject num : 15*/
virtual zCClassDef* _GetClassDef() const zCall( 0x00689010 );
virtual ~oCViewDialogInventory() zCall( 0x00689090 );
virtual void __fastcall Activate( int ) zCall( 0x006890B0 );
virtual void __fastcall StartSelection() zCall( 0x00689270 );
virtual void __fastcall StopSelection() zCall( 0x006892D0 );
/* for zCViewBase num : 9*/
/* for oCViewDialogInventory num : 1*/
virtual int HandleEvent( int ) zCall( 0x00689220 );
};
} // namespace Gothic_II_Addon
#endif // __OVIEW_DIALOG_INVENTORY_H__VER3__ | [
"pierre.beckmann@yahoo.de"
] | pierre.beckmann@yahoo.de |
49ac46ac43186db66e88cd234fd9e203d7e3de45 | 21bcedc4fa3f3b352f2a7952588d199a80f0d4a7 | /example/socks4a/socks4a.cpp | 7eccf7c6581e957df9a19f24af54b0acdafaf9fc | [
"BSD-3-Clause"
] | permissive | liyuan989/blink | c1a4ae4cb92a567ecdf4a12f1db0bec22a6f962a | 7a0d1367d800df78a404aeea13527cd9508fbf4d | refs/heads/master | 2016-09-05T11:13:37.503470 | 2015-04-14T11:35:40 | 2015-04-14T11:35:40 | 29,411,173 | 13 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 4,424 | cpp | #include <example/socks4a/tunnel.h>
#include <blink/Endian.h>
#include <netdb.h>
#include <stdio.h>
using namespace blink;
EventLoop* g_loop = NULL;
std::map<string, TunnelPtr> g_tunnels;
void onServerConnection(const TcpConnectionPtr& connection)
{
LOG_DEBUG << connection->name() << (connection->connected() ? " UP" : " DOWN");
if (connection->connected())
{
connection->setTcpNoDelay(true);
}
else
{
std::map<string, TunnelPtr>::iterator it = g_tunnels.find(connection->name());
if (it != g_tunnels.end())
{
it->second->disconnect();
g_tunnels.erase(it);
}
}
}
void onServerMessage(const TcpConnectionPtr& connection,
Buffer* buf,
Timestamp receive_time)
{
LOG_DEBUG << connection->name() << " " << buf->readableSize();
if (g_tunnels.find(connection->name()) == g_tunnels.end())
{
if (buf->readableSize() > 128)
{
connection->shutdown();
}
else if (buf->readableSize() > 8)
{
const char* begin = buf->peek() + 8;
const char* end = buf->peek() + buf->readableSize();
const char* where = std::find(begin, end, '\0');
if (where != end)
{
char ver = buf->peek()[0];
char cmd = buf->peek()[1];
const void* port = buf->peek() + 2;
const void* ip = buf->peek() + 4;
sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = *static_cast<const in_port_t*>(port);
addr.sin_addr.s_addr = *static_cast<const uint32_t*>(ip);
bool socks4a = sockets::networkToHost32(addr.sin_addr.s_addr) < 256;
bool okay = false;
if (socks4a)
{
const char* end_of_hostname = std::find(where + 1, end, '\0');
if (end_of_hostname != end)
{
string hostname = where + 1;
where = end_of_hostname;
LOG_INFO << "socks4a host name: " << hostname;
InetAddress temp;
if (InetAddress::resolve(hostname, &temp))
{
addr.sin_addr.s_addr = temp.ipNetEndian();
okay = true;
}
}
else
{
return;
}
}
else
{
okay = true;
}
InetAddress server_addr(addr);
if (ver == 4 && cmd == 1 && okay)
{
TunnelPtr tunnel(new Tunnel(g_loop, server_addr, connection));
tunnel->setup();
tunnel->connect();
g_tunnels[connection->name()] = tunnel;
buf->resetUntil(where + 1);
char response[] = "\000\x5aUVWXYZ";
memcpy(response + 2, &addr.sin_port, 2);
memcpy(response + 4, &addr.sin_addr.s_addr, 4);
connection->send(response, 8);
}
else
{
char response[] = "\000\x5bUVWXYZ";
connection->send(response, 8);
connection->shutdown();
}
}
}
}
else if (!connection->getContext().empty())
{
const TcpConnectionPtr& client_connection =
boost::any_cast<TcpConnectionPtr>(connection->getContext());
client_connection->send(buf);
}
}
int main(int argc, char* argv[])
{
if (argc < 2)
{
fprintf(stderr, "Usage: %s <listen_port>\n", argv[0]);
return 1;
}
LOG_INFO << "pid = " << getpid() << ", tid = " << current_thread::tid();
uint16_t port = static_cast<uint16_t>(atoi(argv[2]));
InetAddress listen_addr(port);
EventLoop loop;
g_loop = &loop;
TcpServer server(&loop, listen_addr, "Socks4a");
server.setConnectionCallback(onServerConnection);
server.setMessageCallback(onServerMessage);
server.start();
loop.loop();
return 0;
}
| [
"liyuan989@gmail.com"
] | liyuan989@gmail.com |
3d18f64fb5d59efd4dec079acec1f5568223df5d | 04c6d6a2534fa2e63aba918f2c038f45915ff828 | /动态规划/1692. Count Ways to Distribute Candies.cpp | 0bbae857363e0f2dce3f38ac449e717dac8e8c62 | [] | no_license | ttzztztz/leetcodeAlgorithms | 7fdc15267ba9e1304f7c817ea9d3f1bd881b004b | d2ee1c8fecb8fc07e3c7d67dc20b964a606e065c | refs/heads/master | 2023-08-19T10:50:40.340415 | 2023-08-02T03:00:38 | 2023-08-02T03:00:38 | 206,009,736 | 17 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 587 | cpp | class Solution {
public:
int waysToDistribute(int n, int k) {
memset(f, 0xff, sizeof f);
this->n = n, this->k = k;
return dfs(1, 1);
}
private:
const int mod = 1e9+7;
typedef long long ll;
ll f[1005][1005];
int n, k;
ll dfs(int i, int j) {
if (i == n) return (j == k) ? 1 : 0;
ll& val = f[i][j];
if (val != -1) return val;
ll ans = 0;
ans = (ans + j * dfs(i + 1, j)) % mod;
if (j + 1 <= k) ans = (ans + dfs(i + 1, j + 1)) % mod;
return val = ans;
}
};
| [
"ttzztztz@outlook.com"
] | ttzztztz@outlook.com |
0fe6e67180977feb868005c20c1a31f3355aaed8 | 3813382c4d9c2b252c3e3091d281c4fba900323f | /boost_asio/timer/using_a_timer_synchronously.cpp | d3e03cf504dea562605d18b97c8c82c522b554d5 | [] | no_license | sunooms/learn | 0f0073b7f7225232b3e300389fabeb5c3c4ed6e3 | 514bb14025d1865977254148d3571ce6bec01fab | refs/heads/master | 2021-01-17T18:35:50.774426 | 2018-01-30T04:33:03 | 2018-01-30T04:33:03 | 71,538,410 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 378 | cpp | #include <iostream>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
int main()
{
boost::asio::io_service io;
//boost::asio::deadline_timer t(io, boost::posix_time::second(2));
boost::asio::deadline_timer t(io, boost::posix_time::milliseconds(600));
t.wait();
std::cout << "Hello, world, xgm!" << std::endl;
return 0;
}
| [
"xgmlovebee@126.com"
] | xgmlovebee@126.com |
63892ce09de071b7d33fe9ee9d3dee112eaa43f5 | d73e4912c604f8073364df416f347f9f2c7a4775 | /acm/20180505/h.cpp | fe9fcf2cc4c2321ff93e5ac016d784590436df69 | [] | no_license | TachoMex/club-algoritmia-cutonala | 9a2efc2c19eae790558940759ba21e970a963752 | ddd28a22b127cda609310b429a3466795f970212 | refs/heads/master | 2020-03-15T17:34:56.771129 | 2018-05-06T18:08:03 | 2018-05-06T18:08:03 | 132,264,864 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 492 | cpp | #include <iostream>
#include <string>
using namespace std;
char cypher(char c, int k){
if(c >= 'A' && c <= 'Z'){
return ((c - 'A') + k) % 26 + 'A';
}
return c;
}
int main(){
cin.tie(0);
cin.sync_with_stdio(0);
int t;
cin >> t;
while(t--){
int n, k;
cin >> n >> k;
string s;
cin.ignore();
for(int i = 0; i < n; i++){
getline(cin, s);
for(char c: s){
cout << cypher(c, k);
}
cout << '\n';
}
}
return 0;
}
| [
"tachoguitar@gmail.com"
] | tachoguitar@gmail.com |
04fa135aab04185ae3f948be8be1d5f43a514754 | bb6ebff7a7f6140903d37905c350954ff6599091 | /components/plugins/renderer/webview_plugin.cc | 1e8399560f09b767cfc76cfb3f69ac336a70d1ae | [
"BSD-3-Clause"
] | permissive | PDi-Communication-Systems-Inc/lollipop_external_chromium_org | faa6602bd6bfd9b9b6277ce3cd16df0bd26e7f2f | ccadf4e63dd34be157281f53fe213d09a8c66d2c | refs/heads/master | 2022-12-23T18:07:04.568931 | 2016-04-11T16:03:36 | 2016-04-11T16:03:36 | 53,677,925 | 0 | 1 | BSD-3-Clause | 2022-12-09T23:46:46 | 2016-03-11T15:49:07 | C++ | UTF-8 | C++ | false | false | 7,773 | cc | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/plugins/renderer/webview_plugin.h"
#include "base/message_loop/message_loop.h"
#include "base/metrics/histogram.h"
#include "base/numerics/safe_conversions.h"
#include "content/public/renderer/web_preferences.h"
#include "skia/ext/platform_canvas.h"
#include "third_party/WebKit/public/platform/WebSize.h"
#include "third_party/WebKit/public/platform/WebURL.h"
#include "third_party/WebKit/public/platform/WebURLRequest.h"
#include "third_party/WebKit/public/platform/WebURLResponse.h"
#include "third_party/WebKit/public/web/WebDocument.h"
#include "third_party/WebKit/public/web/WebElement.h"
#include "third_party/WebKit/public/web/WebInputEvent.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "third_party/WebKit/public/web/WebPluginContainer.h"
#include "third_party/WebKit/public/web/WebView.h"
#include "webkit/common/webpreferences.h"
using blink::WebCanvas;
using blink::WebCursorInfo;
using blink::WebDragData;
using blink::WebDragOperationsMask;
using blink::WebImage;
using blink::WebInputEvent;
using blink::WebLocalFrame;
using blink::WebMouseEvent;
using blink::WebPlugin;
using blink::WebPluginContainer;
using blink::WebPoint;
using blink::WebRect;
using blink::WebSize;
using blink::WebString;
using blink::WebURLError;
using blink::WebURLRequest;
using blink::WebURLResponse;
using blink::WebVector;
using blink::WebView;
WebViewPlugin::WebViewPlugin(WebViewPlugin::Delegate* delegate,
const WebPreferences& preferences)
: delegate_(delegate),
container_(NULL),
web_view_(WebView::create(this)),
finished_loading_(false),
focused_(false) {
// ApplyWebPreferences before making a WebLocalFrame so that the frame sees a
// consistent view of our preferences.
content::ApplyWebPreferences(preferences, web_view_);
web_frame_ = WebLocalFrame::create(this);
web_view_->setMainFrame(web_frame_);
}
// static
WebViewPlugin* WebViewPlugin::Create(WebViewPlugin::Delegate* delegate,
const WebPreferences& preferences,
const std::string& html_data,
const GURL& url) {
WebViewPlugin* plugin = new WebViewPlugin(delegate, preferences);
plugin->web_view()->mainFrame()->loadHTMLString(html_data, url);
return plugin;
}
WebViewPlugin::~WebViewPlugin() {
web_view_->close();
web_frame_->close();
}
void WebViewPlugin::ReplayReceivedData(WebPlugin* plugin) {
if (!response_.isNull()) {
plugin->didReceiveResponse(response_);
size_t total_bytes = 0;
for (std::list<std::string>::iterator it = data_.begin(); it != data_.end();
++it) {
plugin->didReceiveData(
it->c_str(), base::checked_cast<int, size_t>(it->length()));
total_bytes += it->length();
}
UMA_HISTOGRAM_MEMORY_KB(
"PluginDocument.Memory",
(base::checked_cast<int, size_t>(total_bytes / 1024)));
UMA_HISTOGRAM_COUNTS(
"PluginDocument.NumChunks",
(base::checked_cast<int, size_t>(data_.size())));
}
// We need to transfer the |focused_| to new plugin after it loaded.
if (focused_) {
plugin->updateFocus(true);
}
if (finished_loading_) {
plugin->didFinishLoading();
}
if (error_) {
plugin->didFailLoading(*error_);
}
}
void WebViewPlugin::RestoreTitleText() {
if (container_)
container_->element().setAttribute("title", old_title_);
}
WebPluginContainer* WebViewPlugin::container() const { return container_; }
bool WebViewPlugin::initialize(WebPluginContainer* container) {
container_ = container;
if (container_)
old_title_ = container_->element().getAttribute("title");
return true;
}
void WebViewPlugin::destroy() {
if (delegate_) {
delegate_->PluginDestroyed();
delegate_ = NULL;
}
container_ = NULL;
base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
}
NPObject* WebViewPlugin::scriptableObject() { return NULL; }
struct _NPP* WebViewPlugin::pluginNPP() { return NULL; }
bool WebViewPlugin::getFormValue(WebString& value) { return false; }
void WebViewPlugin::paint(WebCanvas* canvas, const WebRect& rect) {
gfx::Rect paint_rect = gfx::IntersectRects(rect_, rect);
if (paint_rect.IsEmpty())
return;
paint_rect.Offset(-rect_.x(), -rect_.y());
canvas->translate(SkIntToScalar(rect_.x()), SkIntToScalar(rect_.y()));
canvas->save();
web_view_->layout();
web_view_->paint(canvas, paint_rect);
canvas->restore();
}
// Coordinates are relative to the containing window.
void WebViewPlugin::updateGeometry(const WebRect& frame_rect,
const WebRect& clip_rect,
const WebVector<WebRect>& cut_out_rects,
bool is_visible) {
if (static_cast<gfx::Rect>(frame_rect) != rect_) {
rect_ = frame_rect;
WebSize newSize(frame_rect.width, frame_rect.height);
web_view_->setFixedLayoutSize(newSize);
web_view_->resize(newSize);
}
}
void WebViewPlugin::updateFocus(bool focused) {
focused_ = focused;
}
bool WebViewPlugin::acceptsInputEvents() { return true; }
bool WebViewPlugin::handleInputEvent(const WebInputEvent& event,
WebCursorInfo& cursor) {
// For tap events, don't handle them. They will be converted to
// mouse events later and passed to here.
if (event.type == WebInputEvent::GestureTap)
return false;
if (event.type == WebInputEvent::ContextMenu) {
if (delegate_) {
const WebMouseEvent& mouse_event =
reinterpret_cast<const WebMouseEvent&>(event);
delegate_->ShowContextMenu(mouse_event);
}
return true;
}
current_cursor_ = cursor;
bool handled = web_view_->handleInputEvent(event);
cursor = current_cursor_;
return handled;
}
void WebViewPlugin::didReceiveResponse(const WebURLResponse& response) {
DCHECK(response_.isNull());
response_ = response;
}
void WebViewPlugin::didReceiveData(const char* data, int data_length) {
data_.push_back(std::string(data, data_length));
}
void WebViewPlugin::didFinishLoading() {
DCHECK(!finished_loading_);
finished_loading_ = true;
}
void WebViewPlugin::didFailLoading(const WebURLError& error) {
DCHECK(!error_.get());
error_.reset(new WebURLError(error));
}
bool WebViewPlugin::acceptsLoadDrops() { return false; }
void WebViewPlugin::setToolTipText(const WebString& text,
blink::WebTextDirection hint) {
if (container_)
container_->element().setAttribute("title", text);
}
void WebViewPlugin::startDragging(WebLocalFrame*,
const WebDragData&,
WebDragOperationsMask,
const WebImage&,
const WebPoint&) {
// Immediately stop dragging.
web_view_->dragSourceSystemDragEnded();
}
bool WebViewPlugin::allowsBrokenNullLayerTreeView() const {
return true;
}
void WebViewPlugin::didInvalidateRect(const WebRect& rect) {
if (container_)
container_->invalidateRect(rect);
}
void WebViewPlugin::didChangeCursor(const WebCursorInfo& cursor) {
current_cursor_ = cursor;
}
void WebViewPlugin::didClearWindowObject(WebLocalFrame* frame) {
if (delegate_)
delegate_->BindWebFrame(frame);
}
void WebViewPlugin::didReceiveResponse(WebLocalFrame* frame,
unsigned identifier,
const WebURLResponse& response) {
WebFrameClient::didReceiveResponse(frame, identifier, response);
}
| [
"mrobbeloth@pdiarm.com"
] | mrobbeloth@pdiarm.com |
ce2f8056236e9e2a6ab5aa43dd2c7b1db8395cbd | 41578b9248dc2f5671fbf6c793f88ae61f75014e | /TFT_Dispaly/Nova-Touch/Module-Development/scaleSetup/June-21/scaleSetup-12-06-21/commonGlobal.h | 4304a1936948dabebdb5ca52ce9575bcb801f179 | [] | no_license | axisElectronics/Axis_Company_Project | 89fb56de1c1cd0d5044a36b64369127e01cba1d2 | 089e3e0c63ce9156e888738fd9262124c9345c1c | refs/heads/master | 2023-08-26T19:41:18.505678 | 2021-11-08T09:33:26 | 2021-11-08T09:33:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,657 | h |
#ifndef __COMMONGLOBAL_H
#define __COMMONGLOBAL_H
#include "headerFiles.h"
#include <FS.h>
#include <SPIFFS.h>
/********* MACROs Decalration ***********/
// Serial_1 will be used for getting data from Arduino NANO for Keypad data.
#define RXD1 32
#define TXD1 33
// Serial_2 will be used for getting Weighing Scale data from machine.
#define RXD2 16
#define TXD2 17
#define rgb565(r,g,b) { digitHandler->digitColor[0] = r; digitHandler->digitColor[1] = g; digitHandler->digitColor[2] = b; }
#define findDotPosition( buf, dotpos) { while(buf[dotpos++] != '.'); dotpos--; }
/*************************** Defines ***************************/
#define basicImages(classX) { \
classX.weighingMode(); \
classX.batterySymbl(); \
classX.stableSymbl(0); \
classX.zeroSymbl(0); \
classX.tareweightSymbl(0); \
}
#define parshDateformat( dest, src ) { \
if ( src[1] == '/' ) { \
dest[0] = '0'; \
dest[1] = src[0]; \
dest[2] = '/'; \
\
if ( src[3] == '/' ) { \
dest[3] = '0'; \
dest[4] = src[2]; \
dest[5] = src[3]; \
dest[6] = src[6]; \
dest[7] = src[7]; \
dest[8] = '\0'; \
}else if ( src[4] == '/' ){\
dest[3] = src[2]; \
dest[4] = src[3]; \
dest[5] = src[4]; \
dest[6] = src[7]; \
dest[7] = src[8]; \
dest[8] = '\0'; \
} \
}else if ( src[2] == '/' ) {\
dest[0] = src[0]; \
dest[1] = src[1]; \
dest[2] = '/'; \
\
if( src[4] == '/' ){ \
dest[3] = '0'; \
dest[4] = src[3]; \
dest[5] = src[4]; \
dest[6] = src[5]; \
dest[7] = src[6]; \
dest[8] = '\0'; \
}else if( src[5] == '/' )\
{ \
dest[3] = src[3]; \
dest[4] = src[4]; \
dest[5] = src[5]; \
dest[6] = src[6]; \
dest[7] = src[7]; \
dest[8] = '\0'; \
} \
} \
}
#define parshTimeFormat(dest, src) { \
if ( src[1] == ':' ) { \
dest[0] = '0'; \
dest[1] = src[0]; \
dest[2] = ':'; \
}else if( src[2] == ':' ) \
{ \
dest[0] = src[0]; \
dest[1] = src[1]; \
dest[2] = ':'; \
} \
\
if ( src[3] == ':' ) { \
dest[3] = '0'; \
dest[4] = src[2]; \
dest[5] = '\0'; \
}else if ( src[4] == ':' ){ \
dest[3] = src[2]; \
dest[4] = src[3]; \
dest[5] = '\0'; \
}else if( src[5] == ':' ){ \
dest[3] = src[3]; \
dest[4] = src[4]; \
dest[5] = '\0'; \
} \
}
#define Enable_Text_Font() { \
tft.setTextSize( 1 ); \
tft.setFreeFont( (const GFXfont *)EUROSTILE_B20 ); \
tft.setTextColor(TFT_WHITE, TFT_BLACK); \
}
#define eliminateLeadingZeros(buf, dotpos, cnt) { \
for(uint8_t i=0; i < dotpos-1; i++) \
{ \
if( buf[i] == '0') \
++cnt; \
else \
{ \
break; \
} \
} \
\
}
#define bufferWithoutDot(dest, src) { \
for(uint8_t i=0, j=0; i < 7; ++i) \
{ \
if( src[i] != '.' ) \
dest[j++] = src[i]; \
} \
}
#define convertDoubleToCharArray(d_val, c_val) { \
char temp[8]; \
dtostrf(d_val,7,3,temp); \
memset(c_val, '0', 7); \
uint8_t idx = 0; \
findDotPosition(temp, idx); \
idx = dotpos - idx; \
strcpy( &c_val[idx], temp); \
for(uint8_t i=0; i < 7; i++ ) { if( c_val[i] == 32 ) c_val[i] = 48; } \
c_val[7] = '\0'; \
}
#define AdjustDot( buf ) { \
if( !(strstr(buf, ".") ) ) \
{ \
char temp[7] = {0}; \
uint8_t dotcnt = 0; \
memset(temp, '0', 7); \
findDotPosition( buf, dotcnt ); \
strcpy( &temp[digitHandler->dotpos - dotcnt], buf ); \
strcpy( buf, (const char *)temp); \
} \
}//End-AdjustDot
/* ==============================================================
Commands
=============================================================
1 @ CMD_STARTDATA :
--------------------
>> get continuous data from Machine.
2 @ CMD_STOPDATA :
-------------------
>> stop data coming from Weight machine
>> stop continuous data from machine SO that we didnot overflow buffer.
3 @ CMD_GETTARE :
-----------------
>> get TARE data from Machine
*/
#define CMD_STARTDATA { \
String StartCMD = "\2DT#1\3"; \
Serial2.print( StartCMD ); \
}
#define CMD_STOPDATA { \
String StopCMD = "\2DT#0\3"; \
Serial2.print(StopCMD); \
}
#define CMD_ZERODATA { \
String StopCMD = "\2Z\3"; \
Serial2.print(StopCMD); \
}
#define CMD_AUTOTARE { \
String StopCMD = "\2T\3"; \
Serial2.print(StopCMD); \
}
#define CMD_GETTARE { \
String StartCMD = "\2GT\3"; \
Serial2.print( StartCMD ); \
}
#define STOP_SERIAL1 Serial1.end();
#define START_SERIAL1 Serial1.begin(9600, SERIAL_8N1, RXD1, TXD1); // keypad
#define STOP_SERIAL2 Serial2.end();
#define START_SERIAL2 Serial2.begin(9600, SERIAL_8N1, RXD2, TXD2); // Weight Mechine
#define EMPTY_SERIALBUFFER { \
while ( Serial2.available() ) Serial2.read(); \
while ( Serial1.available() ) Serial1.read(); \
while ( Serial.available() ) Serial.read(); \
}
#define WQ 0
#define TQ 5
#define TareWeight 6
#define StopWeightData 12
#define StartWeightData 13
#define GetTareWeightData 14
#define Field_three_Touch ( ( (xAxis > 300) && (xAxis < 480) ) && ( ( yAxis > 160 ) && ( yAxis < 240 ) ) )
#define Field_Two_Touch ( ( (xAxis > 0) && (xAxis < 216) ) && ( ( yAxis > 160 ) && ( yAxis < 240 ) ) )
#define Taretouch_Auto ( ( (xAxis > 405) && (xAxis < 480) ) && ( ( yAxis > 259 ) && ( yAxis < 313 ) ) )
#define Zerotouch ( ( (xAxis > 300) && (xAxis < 385) ) && ( ( yAxis > 259 ) && ( yAxis < 313 ) ) )
#define ESC_Touch ( ( (xAxis > 0) && (xAxis < 85) ) && ( ( yAxis > 259 ) && ( yAxis < 313 ) ) )
#define makeCustomColor( red, green , blue ) (((red & 0xf8)<<8) + ((green & 0xfc)<<3)+(blue>>3))
/********************************************************************************************
Below MACROs are used to identify The Touch of STARTUP window.
User has few options Which are Listed below.
@ Weight Mode : After Touching This option, User is allowed to use functionality of Weighing Mechine.
@ Pricing Mode : After Touching This option, User is allowed to use functionality of Pricing Mechine.
@ Counting Mode : After Touching This option, User is allowed to use functionality of Counting Mechine.
@ Check Weighing Mode : After Touching This option, User is allowed to use functionality of Check Weighing Mechine.
@ Setting Mode : Setting Mode Allowed to User to change machine functionality as per Requirements.
After machine is configured by user. Next user can choose among 4 Modes.
@ Go Back -->>> Which is not Implimented Yet.
*********************************************************************************************/
#define x1Weighing 15
#define x2Weighing 108
#define y1Weighing 70
#define y2Weighing 230
#define xWeighingMode ( ( xAxis >= x1Weighing ) && (xAxis <= x2Weighing ) )
#define yWeighingMode ( ( yAxis >= y1Weighing ) && ( yAxis <= y2Weighing ) )
#define WeighingModeTouchEnable() ( xWeighingMode && yWeighingMode )
//#define WeighingModeTouchEnable() ( ( (xAxis > 15) && (xAxis < 108) ) && ( ( yAxis > 70 ) && ( yAxis < 230 ) ) )
/**********************************************************************************************/
#define x1Counting 135
#define x2Counting 222
#define y1Counting 70
#define y2Counting 230
#define xCountingMode ( ( xAxis >= x1Counting ) && ( xAxis <= x2Counting ) )
#define yCountingMode ( ( yAxis >= y1Counting ) && ( yAxis <= y2Counting ) )
#define CountingModeTouchEnable() ( xCountingMode && yCountingMode )
/**********************************************************************************************/
#define x1Priceing 251
#define x2Priceing 345
#define y1Priceing 70
#define y2Priceing 230
#define xPriceingMode ( ( xAxis >= x1Priceing ) && ( xAxis <= x2Priceing ) )
#define yPriceingMode ( ( yAxis >= y1Priceing ) && ( yAxis <= y2Priceing ) )
#define PriceingModeTouchEnable() ( xPriceingMode && yPriceingMode )
/**********************************************************************************************/
#define x1Checking 377
#define x2Checking 470
#define y1Checking 70
#define y2Checking 230
#define xCheckingMode ( ( xAxis >= x1Checking ) && ( xAxis <= x2Checking ) )
#define yCheckingMode ( ( yAxis >= y1Checking ) && ( yAxis <= y2Checking ) )
#define CheckingModeTouchEnable() ( xCheckingMode && yCheckingMode )
/**********************************************************************************************/
#define x1Setting 13
#define x2Setting 270
#define y1Setting 252
#define y2Setting 303
#define xSetting ( ( xAxis >= x1Setting ) && ( xAxis <= x2Setting ) )
#define ySetting ( ( yAxis >= y1Setting ) && ( yAxis <= y2Setting ) )
#define SettingTouchEnable() ( xSetting && ySetting )
/**********************************************************************************************/
#define x1GoBack 258
#define x2GoBack 460
#define y1GoBack 252
#define y2GoBack 303
#define xGoBack ( ( xAxis >= x1GoBack ) && ( xAxis <= x2GoBack ) )
#define yGoBack ( ( yAxis >= y1GoBack ) && ( yAxis <= y2GoBack ) )
/**********************************************************************************************/
enum _machine
{
keep_running = 0,
WeighingMachine = 1,
CountingMachine,
PricingMachine,
CheckWeighing,
Settings,
Go_Back
};
struct task_list
{
char CmdName[16];
char (*Task)(void);
};
char CmdWrite( struct task_list *CmdTaskHandler );
#define GROSS 0
#define NET 1
#define TARE 2
#define PRICE 1
#define perPCS 2
class WeighingHandle : public settings
{
public :
uint8_t flags;
double FromMachine[3];
char FromMachineArray[3][10];
char maxvalue[10];
char minvalue[10];
struct _imageAttri
{
bool (*ModeHeader)(void);
bool (*stableUnstableFlag)(bool showHide);
bool (*tareFlag)(bool showHide);
bool (*zeroFlag)(bool showHide);
};
struct _showDigits
{
int8_t selectWindow;
int8_t digitFontSize;
const void *digitFontStyle;
char preValue[3][10];
char currentValue[10];
uint8_t dotPosition;
uint16_t fontDigitColor;
uint16_t backDigitColor;
int8_t cntBlankRect;
bool spclFlag = 0;
} showDigits;
struct _digithandler
{
enum _machine machineMode;
struct _imageAttri imageCallback;
struct s_setting *basesetting;
} handler;
struct rtcvar {
uint8_t hour;
uint8_t minute;
uint8_t second;
uint8_t mday;
uint8_t mon;
uint16_t year;
uint8_t wday;
} RTCHandler;
void drawJpeg(const char *filename, int xpos, int ypos);
void jpegRender(int xpos, int ypos);
void jpegInfo();
/******************************************
>>>> common function <<<<
******************************************/
void initTFTHandler( );
void initWeighingTFT( );
String handleFlags( char *Weight );
void windowOne( );
void windowTwo( );
void windowThree( );
/* Basic images required for all 4 Modes */
bool weighingMode();
bool BootingImage();
bool startUPImage();
bool numKeypad();
bool tareweightSymbl(uint8_t flag);
bool batterySymbl();
bool zeroSymbl(uint8_t flag);
bool stableSymbl(uint8_t flag);
bool cross(uint16_t x, uint16_t y);
void readyAxisScales();
/******************************************
>>>> Weight function <<<<
******************************************/
int8_t startWeighing();
String _readbufWeight( );
void _updateTareWeight( char *Temp );
void _updateGrossWeight( );
void _updateNetWeight( char *Temp );
void _updateWindow( uint8_t win );
void handleTareCommand( char *Weight );
bool printStringWeight( );
int8_t handleTouchFuncationality_Weight();
bool weightStripImage();
/******************************************
>>>> Price computing function <<<<
******************************************/
int8_t startPriceComputing();
void _updateWindowPricing( uint8_t win );
void _updateTotalWeight( char *Temp );
void _updateWeightPrice();
void _updateWeightperPrice( char *Temp );
int8_t handleTouchFuncationality_PRICE();
String _readbufPrice( );
bool printStringPrice( );
bool priceStripImage();
/******************************************
>>>> COUNT computing function <<<<
******************************************/
int8_t startCountComputing();
void _updateWindowCOUNT( uint8_t win );
void _updateTotalWeightCOUNT( char *Temp );
void updateTotalPcsWindow();
void _updateWeightCOUNT();
void _updateWeightperCOUNT( char *Temp );
int8_t handleTouchFuncationality_COUNT();
String _readbufCOUNT( );
bool printStringCOUNT( );
bool countStripImage();
/******************************************
>>>> Check Weighing function <<<<
******************************************/
int8_t startCheckWeighing();
void _updateWindowCHECK( uint8_t win );
int8_t handleTouchFuncationality_CHECK();
String _readbufCHECK( );
void _updateWeightWindowCHECK( char *Temp, uint8_t win);
void _updateTotalWeightCHECK( char *Temp );
void _maxWin(char * maxValue );
void _minWin(char * minValue );
bool printStringCHECK( );
void windowOneCHECK( );
/*******************************************
>>>> RTC Module <<<<<
*******************************************/
void intitRTC();
void updateRTCVariable();
void setRTCValue();
};
char nullfunc();
#define x1Zero 343
#define x2Zero 415
#define y1Zero 240
#define y2Zero 304
#define xZero ( ( xAxis >= x1Zero ) && (xAxis <= x2Zero ) )
#define yZero ( ( yAxis >= y1Zero ) && ( yAxis <= y2Zero ) )
/**********************************************************************************************/
#define x1One 255
#define x2One 320
#define y1One 150
#define y2One 210
#define xOne ( ( xAxis >= x1One ) && ( xAxis <= x2One ) )
#define yOne ( ( yAxis >= y1One ) && ( yAxis <= y2One ) )
/**********************************************************************************************/
#define x1Two 345
#define x2Two 415
#define y1Two 150
#define y2Two 210
#define xTwo ( ( xAxis >= x1Two ) && (xAxis <= x2Two ) )
#define yTwo ( ( yAxis >= y1Two ) && ( yAxis <= y2Two ) )
/**********************************************************************************************/
#define x1Three 429
#define x2Three 480
#define y1Three 150
#define y2Three 210
#define xThree ( ( xAxis >= x1Three ) && (xAxis <= x2Three ) )
#define yThree ( ( yAxis >= y1Three ) && ( yAxis <= y2Three ) )
/**********************************************************************************************/
#define x1Four 255
#define x2Four 320
#define y1Four 70
#define y2Four 120
#define xFour ( ( xAxis >= x1Four ) && (xAxis <= x2Four ) )
#define yFour ( ( yAxis >= y1Four ) && ( yAxis <= y2Four ) )
/**********************************************************************************************/
#define x1Five 345
#define x2Five 415
#define y1Five 70
#define y2Five 120
#define xFive ( ( xAxis >= x1Five ) && (xAxis <= x2Five ) )
#define yFive ( ( yAxis >= y1Five ) && ( yAxis <= y2Five ) )
/**********************************************************************************************/
#define x1Six 429
#define x2Six 480
#define y1Six 70
#define y2Six 120
#define xSix ( ( xAxis >= x1Six ) && (xAxis <= x2Six ) )
#define ySix ( ( yAxis >= y1Six ) && ( yAxis <= y2Six ) )
/**********************************************************************************************/
#define x1Seven 255
#define x2Seven 320
#define y1Seven 0
#define y2Seven 50
#define xSeven ( ( xAxis >= x1Seven ) && (xAxis <= x2Seven ) )
#define ySeven ( ( yAxis >= y1Seven ) && ( yAxis <= y2Seven ) )
/**********************************************************************************************/
#define x1Eight 345
#define x2Eight 415
#define y1Eight 0
#define y2Eight 50
#define xEight ( ( xAxis >= x1Eight ) && (xAxis <= x2Eight ) )
#define yEight ( ( yAxis >= y1Eight ) && ( yAxis <= y2Eight ) )
/**********************************************************************************************/
#define x1Nine 429
#define x2Nine 480
#define y1Nine 0
#define y2Nine 50
#define xNine ( ( xAxis >= x1Nine ) && (xAxis <= x2Nine ) )
#define yNine ( ( yAxis >= y1Nine ) && ( yAxis <= y2Nine ) )
/**********************************************************************************************/
#define x1Dot 255
#define x2Dot 320
#define y1Dot 240
#define y2Dot 303
#define xDot ( ( xAxis >= x1Dot ) && ( xAxis <= x2Dot ) )
#define yDot ( ( yAxis >= y1Dot ) && ( yAxis <= y2Dot ) )
/******************************************************************************/
#define x1Del 165
#define x2Del 240
#define y1Del 240
#define y2Del 304
#define xDel ( ( xAxis >= x1Del ) && ( xAxis <= x2Del ) )
#define yDel ( ( yAxis >= y1Del ) && ( yAxis <= y2Del ) )
/******************************************************************************/
#define x1Clear 165
#define x2Clear 240
#define y1Clear 150
#define y2Clear 210
#define xClear ( ( xAxis >= x1Clear ) && ( xAxis <= x2Clear ) )
#define yClear ( ( yAxis >= y1Clear ) && ( yAxis <= y2Clear ) )
/******************************************************************************/
#define x1Ent 429
#define x2Ent 480
#define y1Ent 240
#define y2Ent 304
#define xEnt ( ( xAxis >= x1Ent ) && ( xAxis <= x2Ent ) )
#define yEnt ( ( yAxis >= y1Ent ) && ( yAxis <= y2Ent ) )
/******************************************************************************/
#define x1Del 255
#define x2Del 320
#define y1Del 240
#define y2Del 303
#define xDel ( ( xAxis >= x1Del ) && ( xAxis <= x2Del ) )
#define yDel ( ( yAxis >= y1Del ) && ( yAxis <= y2Del ) )
/******************************************************************************/
#endif
| [
"viveky1794@gmail.com"
] | viveky1794@gmail.com |
ad9b21017a47f197801482d82b3f0ae22887270f | c7120eeec717341240624c7b8a731553494ef439 | /src/cplusplus/freezone-samp/src/npc_dev.cpp | 82131045a610163017c7ffb65507a1f5fabfeaad | [] | no_license | neverm1ndo/gta-paradise-sa | d564c1ed661090336621af1dfd04879a9c7db62d | 730a89eaa6e8e4afc3395744227527748048c46d | refs/heads/master | 2020-04-27T22:00:22.221323 | 2010-09-04T19:02:28 | 2010-09-04T19:02:28 | 174,719,907 | 1 | 0 | null | 2019-03-09T16:44:43 | 2019-03-09T16:44:43 | null | WINDOWS-1251 | C++ | false | false | 16,350 | cpp | #include "config.hpp"
#include "npc_dev.hpp"
#include "core/module_c.hpp"
#include "core/npcs.hpp"
#include "vehicles.hpp"
#include "weapons.hpp"
#include "player_money.hpp"
#include <fstream>
#include <boost/filesystem.hpp>
REGISTER_IN_APPLICATION(npc_dev);
npc_dev::npc_dev()
:play_npc_name("npc_dev_play")
,play_record_vehicle_id(0)
{
}
npc_dev::~npc_dev() {
}
void npc_dev::create() {
command_add("npc_dev_record", std::tr1::bind(&npc_dev::cmd_record, this, std::tr1::placeholders::_1, std::tr1::placeholders::_2, std::tr1::placeholders::_3, std::tr1::placeholders::_4, std::tr1::placeholders::_5), cmd_game, std::tr1::bind(&npc_dev::access_checker, this, std::tr1::placeholders::_1, std::tr1::placeholders::_2));
command_add("npc_dev_play", std::tr1::bind(&npc_dev::cmd_play, this, std::tr1::placeholders::_1, std::tr1::placeholders::_2, std::tr1::placeholders::_3, std::tr1::placeholders::_4, std::tr1::placeholders::_5), cmd_game, std::tr1::bind(&npc_dev::access_checker, this, std::tr1::placeholders::_1, std::tr1::placeholders::_2));
command_add("npc_dev_create_vehicle", std::tr1::bind(&npc_dev::cmd_create_vehicle, this, std::tr1::placeholders::_1, std::tr1::placeholders::_2, std::tr1::placeholders::_3, std::tr1::placeholders::_4, std::tr1::placeholders::_5), cmd_game, std::tr1::bind(&npc_dev::access_checker, this, std::tr1::placeholders::_1, std::tr1::placeholders::_2));
}
void npc_dev::configure_pre() {
is_enable = false;
recording_vehicle_health = 1000.0f;
acceleration_multiplier = 1.2f;
deceleration_multiplier = 0.8f;
}
void npc_dev::configure(buffer::ptr const& buff, def_t const& def) {
SERIALIZE_ITEM(is_enable);
SERIALIZE_ITEM(recording_vehicle_health);
SERIALIZE_ITEM(acceleration_multiplier);
SERIALIZE_ITEM(deceleration_multiplier);
}
void npc_dev::configure_post() {
}
void npc_dev::on_connect(player_ptr_t const& player_ptr) {
npc_dev_player_item::ptr item(new npc_dev_player_item(*this), &player_item::do_delete);
player_ptr->add_item(item);
}
void npc_dev::on_npc_connect(npc_ptr_t const& npc_ptr) {
if (play_npc_name == npc_ptr->name_get()) {
// Это наш бот для проигрования :)
npc_dev_npc_item::ptr item(new npc_dev_npc_item(*this), &npc_item::do_delete);
npc_ptr->add_item(item);
}
}
bool npc_dev::access_checker(player_ptr_t const& player_ptr, std::string const& cmd_name) {
return is_enable;
}
command_arguments_rezult npc_dev::cmd_record(player_ptr_t const& player_ptr, std::string const& arguments, messages_pager& pager, messages_sender const& sender, messages_params& params) {
npc_dev_player_item::ptr npc_dev_player_item_ptr = player_ptr->get_item<npc_dev_player_item>();
npc_dev_player_item_ptr->is_wait_recording = !npc_dev_player_item_ptr->is_wait_recording;
if (npc_dev_player_item_ptr->is_wait_recording) {
if (arguments.empty()) {
npc_dev_player_item_ptr->recording_prefix = "record";
}
else {
npc_dev_player_item_ptr->recording_prefix = arguments;
}
player_ptr->get_item<weapons_item>()->weapon_reset();
player_ptr->get_item<player_money_item>()->reset();
params("prefix", npc_dev_player_item_ptr->recording_prefix);
pager("$(cmd_npc_dev_record_on_player)");
sender("$(cmd_npc_dev_record_on_log)", msg_log);
}
else {
if (npc_dev_player_item_ptr->is_recording) {
npc_dev_player_item_ptr->recording_stop();
}
pager("$(cmd_npc_dev_record_off_player)");
sender("$(cmd_npc_dev_record_off_log)", msg_log);
}
return cmd_arg_ok;
}
command_arguments_rezult npc_dev::cmd_play(player_ptr_t const& player_ptr, std::string const& arguments, messages_pager& pager, messages_sender const& sender, messages_params& params) {
if (arguments.empty()) {
return cmd_arg_syntax_error;
}
{
int vehicle_id;
int model_id;
bool is_driver;
if (player_ptr->get_vehicle(vehicle_id, model_id, is_driver)) {
play_record_vehicle_id = vehicle_id;
}
else {
play_record_vehicle_id = 0;
}
}
play_record_name = arguments;
npcs::instance()->add_npc(play_npc_name);
params("record_name", play_record_name);
pager("$(cmd_npc_dev_play_player)");
sender("$(cmd_npc_dev_play_log)", msg_log);
return cmd_arg_ok;
}
command_arguments_rezult npc_dev::cmd_create_vehicle(player_ptr_t const& player_ptr, std::string const& arguments, messages_pager& pager, messages_sender const& sender, messages_params& params) {
int model_id;
{ // Парсинг
if (!vehicles::instance()->get_model_id_by_name(arguments, model_id)) {
std::istringstream iss(arguments);
iss>>model_id;
if (iss.fail() || !iss.eof()) {
return cmd_arg_syntax_error;
}
}
}
{ // Проверяем, находится ли игрок в транспорте
int vehicle_id = samp::api::instance()->get_player_vehicle_id(player_ptr->get_id());
int model_id = samp::api::instance()->get_vehicle_model(vehicle_id);
if (0 != model_id) {
pager("$(npc_dev_create_vehicle_error_invehicle)");
return cmd_arg_process_error;
}
}
pos4 pos = player_ptr->get_item<player_position_item>()->pos_get();
int vehicle_id = vehicles::instance()->vehicle_create(pos_vehicle(model_id, pos.x, pos.y, pos.z + 1.5f, pos.interior, pos.world, pos.rz, -1, -1));
samp::api::instance()->put_player_in_vehicle(player_ptr->get_id(), vehicle_id, 0);
params
("model_id", model_id)
("vehicle_id", vehicle_id)
;
pager("$(npc_dev_create_vehicle_done_player)");
sender("$(npc_dev_create_vehicle_done_log)", msg_log);
return cmd_arg_ok;
}
npc_dev_player_item::npc_dev_player_item(npc_dev& manager)
:manager(manager)
,is_wait_recording(false)
,is_recording(false)
,recording_vehicle_id(-1)
,recording_time_start(0)
,is_accelerate(false)
{
}
npc_dev_player_item::~npc_dev_player_item() {
}
void npc_dev_player_item::on_timer250() {
if (!is_recording || 0 == recording_vehicle_id || !is_accelerate) {
return;
}
int vehicle_id;
int model_id;
bool is_driver;
if (get_root()->get_vehicle(vehicle_id, model_id, is_driver) && is_driver) {
samp::api::ptr api_ptr = samp::api::instance();
float x, y, z;
int keys;
int updown;
int leftright;
api_ptr->get_vehicle_velocity(vehicle_id, x, y, z);
api_ptr->get_player_keys(get_root()->get_id(), keys, updown, leftright);
if (keys & vehicle_accelerate) {
api_ptr->set_vehicle_velocity(vehicle_id, accelerate(x), accelerate(y), accelerate(z));
}
else if (keys & vehicle_decelerate) {
api_ptr->set_vehicle_velocity(vehicle_id, decelerate(x), decelerate(y), decelerate(z));
}
}
}
void npc_dev_player_item::on_keystate_change(int keys_new, int keys_old) {
if (!is_wait_recording) {
return;
}
if (is_recording && 0 != recording_vehicle_id) {
if (recording_is_can_use_nitro) {
if (is_key_just_down(mouse_lbutton, keys_new, keys_old)) {
if (vehicle_ptr_t vehicle_ptr = vehicles::instance()->get_vehicle(recording_vehicle_id)) {
// Можем поставить нитро :)
vehicle_ptr->add_component("nto_b_tw");
}
}
else if (is_key_just_down(KEY_SUBMISSION, keys_new, keys_old)) {
if (vehicle_ptr_t vehicle_ptr = vehicles::instance()->get_vehicle(recording_vehicle_id)) {
// Убираем нитро
vehicle_ptr->remove_component("nto_b_tw");
}
}
}
if (is_key_just_down(KEY_ACTION, keys_new, keys_old)) {
is_accelerate = true;
}
else if (is_key_just_up(KEY_ACTION, keys_new, keys_old)) {
is_accelerate = false;
}
}
if (is_key_just_down(KEY_LOOK_BEHIND, keys_new, keys_old) && !get_root()->vehicle_is_driver()) {
// Запуск/остановка записи пешком
if (is_recording) {
recording_stop();
}
else {
recording_start(false);
}
}
else if (is_key_just_down(KEY_LOOK_RIGHT | KEY_LOOK_LEFT, keys_new, keys_old) && get_root()->vehicle_is_driver()) {
// Запуск/остановка записи на транспорте
if (is_recording) {
recording_stop();
}
else {
recording_start(true);
}
}
}
bool npc_dev_player_item::on_update() {
if (is_recording) {
samp::api::ptr api_ptr = samp::api::instance();
int vehicle_id;
int model_id;
bool is_driver;
if (get_root()->get_vehicle(vehicle_id, model_id, is_driver) && is_driver) {
if (manager.recording_vehicle_health != api_ptr->get_vehicle_health(vehicle_id)) {
//api_ptr->set_vehicle_health(vehicle_id, manager.recording_vehicle_health);
api_ptr->repair_vehicle(vehicle_id);
}
}
else {
}
}
return true;
}
void npc_dev_player_item::recording_start(bool is_vehicle) {
if (is_recording) {
assert(false);
return;
}
recording_name = get_next_recording_filename();
recording_desc = npc_recording_desc_t();
recording_vehicle_id = 0;
recording_is_can_use_nitro = false;
is_accelerate = false;
samp::api::ptr api_ptr = samp::api::instance();
recording_desc.skin_id = api_ptr->get_player_skin(get_root()->get_id());
if (is_vehicle) {
bool is_driver;
int model_id;
get_root()->get_vehicle(recording_vehicle_id, model_id, is_driver);
api_ptr->get_vehicle_pos(recording_vehicle_id, recording_desc.point_begin.x, recording_desc.point_begin.y, recording_desc.point_begin.z);
recording_desc.point_begin.rz = api_ptr->get_vehicle_zangle(recording_vehicle_id);
if (vehicle_ptr_t vehicle_ptr = vehicles::instance()->get_vehicle(recording_vehicle_id)) {
if (vehicle_def_cptr_t vehicle_def_cptr = vehicle_ptr->get_def()) {
recording_desc.model_name = vehicle_def_cptr->sys_name;
}
recording_is_can_use_nitro = vehicle_ptr->is_valid_component("nto_b_tw");
}
api_ptr->repair_vehicle(recording_vehicle_id);
}
else {
int player_id = get_root()->get_id();
api_ptr->get_player_pos(player_id, recording_desc.point_begin.x, recording_desc.point_begin.y, recording_desc.point_begin.z);
recording_desc.point_begin.rz = api_ptr->get_player_facing_angle(player_id);
}
recording_desc.point_begin.interior = api_ptr->get_player_interior(get_root()->get_id());
messages_item msg_item;
msg_item.get_params()
("player_name", get_root()->name_get_full())
("recording_name", recording_name)
;
if (is_vehicle) {
if (recording_is_can_use_nitro) {
msg_item.get_sender()
("$(npc_dev_recordind_vehicle_nitro_start_player)", msg_player(get_root()))
("$(npc_dev_recordind_vehicle_nitro_start_log)", msg_log);
}
else {
msg_item.get_sender()
("$(npc_dev_recordind_vehicle_start_player)", msg_player(get_root()))
("$(npc_dev_recordind_vehicle_start_log)", msg_log);
}
api_ptr->start_recording_player_data(get_root()->get_id(), samp::api::PLAYER_RECORDING_TYPE_DRIVER, recording_name);
}
else {
msg_item.get_sender()
("$(npc_dev_recordind_onfoot_start_player)", msg_player(get_root()))
("$(npc_dev_recordind_onfoot_start_log)", msg_log);
api_ptr->start_recording_player_data(get_root()->get_id(), samp::api::PLAYER_RECORDING_TYPE_ONFOOT, recording_name);
}
recording_time_start = time_base::tick_count_milliseconds();
is_recording = true;
}
void npc_dev_player_item::recording_stop() {
if (!is_recording) {
assert(false);
return;
}
samp::api::ptr api_ptr = samp::api::instance();
time_base::millisecond_t recording_time_stop = time_base::tick_count_milliseconds();
api_ptr->stop_recording_player_data(get_root()->get_id());
is_recording = false;
if (recording_desc.is_on_vehicle()) {
api_ptr->get_vehicle_pos(recording_vehicle_id, recording_desc.point_end.x, recording_desc.point_end.y, recording_desc.point_end.z);
recording_desc.point_end.rz = api_ptr->get_vehicle_zangle(recording_vehicle_id);
}
else {
int player_id = get_root()->get_id();
api_ptr->get_player_pos(player_id, recording_desc.point_end.x, recording_desc.point_end.y, recording_desc.point_end.z);
recording_desc.point_end.rz = api_ptr->get_player_facing_angle(player_id);
}
recording_desc.duration = (recording_time_stop - recording_time_start);
{ // Сохраняем файл с методанными
std::ofstream meta_file(recording_get_meta_filename(recording_name).c_str());
if (meta_file) {
meta_file << recording_desc;
}
}
messages_item msg_item;
msg_item.get_params()
("player_name", get_root()->name_get_full())
("recording_name", recording_name)
("recording_desc", boost::format("%1%") % recording_desc)
;
msg_item.get_sender()
("$(npc_dev_recordind_stop_player)", msg_player(get_root()))
("$(npc_dev_recordind_stop_log)", msg_log);
}
std::string npc_dev_player_item::get_next_recording_filename() const {
/*
if (!boost::filesystem::exists(recording_get_rec_filename(recording_prefix))) {
// В начале пытаемся имя без цифрового суфикса
return recording_prefix;
}
*/
for (int i = 0; i < 1000; ++i) {
std::string name = (boost::format("%1%%2$02d") % recording_prefix % i).str();
if (!boost::filesystem::exists(recording_get_rec_filename(name))) {
return name;
}
}
assert(false);
return "fuck";
}
std::string npc_dev_player_item::recording_get_meta_filename(std::string const& recording_name) {
return "scriptfiles/" + recording_name + ".meta";
}
std::string npc_dev_player_item::recording_get_rec_filename(std::string const& recording_name) {
return "scriptfiles/" + recording_name + ".rec";
}
float npc_dev_player_item::accelerate(float val) const {
return val * manager.acceleration_multiplier;
}
float npc_dev_player_item::decelerate(float val) const {
return val * manager.deceleration_multiplier;
}
npc_dev_npc_item::npc_dev_npc_item(npc_dev& manager)
:manager(manager)
{
}
npc_dev_npc_item::~npc_dev_npc_item() {
}
void npc_dev_npc_item::on_connect() {
get_root()->set_spawn_info(11, pos4(1958.3783f, 1343.1572f, 15.3746f, 0, 0, 90.0f));
get_root()->set_color(0xff000020);
}
void npc_dev_npc_item::on_spawn() {
if (manager.play_record_vehicle_id) {
// Сажаем в транспорт
get_root()->put_to_vehicle(manager.play_record_vehicle_id);
}
else {
// Включаем запись просто
get_root()->playback_start(npc::playback_type_onfoot, manager.play_record_name);
}
}
void npc_dev_npc_item::on_enter_vehicle(int vehicle_id) {
if (manager.play_record_vehicle_id) {
get_root()->playback_start(npc::playback_type_driver, manager.play_record_name);
}
}
void npc_dev_npc_item::on_playback_end() {
get_root()->kick();
}
void npc_dev_npc_item::on_disconnect(samp::player_disconnect_reason reason) {
}
| [
"dimonml@19848965-7475-ded4-60a4-26152d85fbc5"
] | dimonml@19848965-7475-ded4-60a4-26152d85fbc5 |
4a6434d982ea8b1e7f96e55ad195bd6a2baabf11 | e112299d9dd49af971a95b65f84d3684c1b76beb | /4.1 Tree/33) createLevelLinkedList.cpp | b45bc2e4ef7e90e5098a2e28d17efb1a7f709e64 | [] | no_license | kaili302/Leetcode-CPP-exercises | 3c47be20bfc982ece07632b64e64d5e67e355a4c | 4de5c5b5265fd1fdad2dfdad7120472cfcc0d269 | refs/heads/master | 2021-08-27T16:15:03.089910 | 2016-11-20T15:58:29 | 2016-11-20T15:58:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 509 | cpp | struct TreeNode{
int val;
TreeNode* left;
TreeNode* right;
};
void createLevelLinkedList(TreeNode* pNode, int level, vector<list<TreeNode>>& ret){
if (!pNode) return;
while (ret.size() <= level)
ret.push_back({});
ret[level].push_back(pNode);
createLevelLinkedList(pNode->left, level + 1, ret);
createLevelLinkedList(pNode->right, level + 1, ret);
}
vector<list<TreeNode>> createLevelLinkedList(TreeNode* pRoot){
vector<list<TreeNode>> ret;
createLevelLinkedList(pRoot, 0, ret);
return ret;
}
| [
"kai_li@outlook.com"
] | kai_li@outlook.com |
da76f577d2d38a868eb4ec05d51ffb01f4fc2103 | 902e56e5eb4dcf96da2b8c926c63e9a0cc30bf96 | /LibsExternes/Includes/boost/iostreams/detail/adapter/range_adapter.hpp | e7f2874dc2a3c0b10a37e90e2a0c7be6b8f64fe6 | [
"BSD-3-Clause"
] | permissive | benkaraban/anima-games-engine | d4e26c80f1025dcef05418a071c0c9cbd18a5670 | 8aa7a5368933f1b82c90f24814f1447119346c3b | refs/heads/master | 2016-08-04T18:31:46.790039 | 2015-03-22T08:13:55 | 2015-03-22T08:13:55 | 32,633,432 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,603 | hpp | // (C) Copyright 2008 CodeRage, LLC (turkanis at coderage dot com)
// (C) Copyright 2003-2007 Jonathan Turkanis
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.)
// See http://www.boost.org/libs/iostreams for documentation.
#ifndef BOOST_IOSTREAMS_DETAIL_RANGE_ADAPTER_HPP_INCLUDED
#define BOOST_IOSTREAMS_DETAIL_RANGE_ADAPTER_HPP_INCLUDED
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
#include <algorithm> // min.
#include <cassert>
#include <cstddef> // ptrdiff_t.
#include <iosfwd> // streamsize, streamoff.
#include <boost/detail/iterator.hpp> // boost::iterator_traits.
#include <boost/iostreams/categories.hpp>
#include <boost/iostreams/detail/error.hpp>
#include <boost/iostreams/positioning.hpp>
#include <boost/mpl/if.hpp>
#include <boost/throw_exception.hpp>
#include <boost/type_traits/is_convertible.hpp>
#include <boost/utility/enable_if.hpp>
// Must come last.
#include <boost/iostreams/detail/config/disable_warnings.hpp> // MSVC.
namespace boost { namespace iostreams { namespace detail {
// Used for simulated tag dispatch.
template<typename Traversal> struct range_adapter_impl;
//
// Template name: range_adapter
// Description: Device based on an instance of boost::iterator_range.
// Template paramters:
// Mode - A mode tag.
// Range - An instance of iterator_range.
//
template<typename Mode, typename Range>
class range_adapter {
private:
typedef typename Range::iterator iterator;
typedef boost::detail::iterator_traits<iterator> iter_traits;
typedef typename iter_traits::iterator_category iter_cat;
public:
typedef typename Range::value_type char_type;
struct category : Mode, device_tag { };
typedef typename
mpl::if_<
is_convertible<
iter_cat,
std::random_access_iterator_tag
>,
std::random_access_iterator_tag,
std::forward_iterator_tag
>::type tag;
typedef range_adapter_impl<tag> impl;
explicit range_adapter(const Range& rng);
range_adapter(iterator first, iterator last);
std::streamsize read(char_type* s, std::streamsize n);
std::streamsize write(const char_type* s, std::streamsize n);
std::streampos seek(stream_offset off, BOOST_IOS::seekdir way);
private:
iterator first_, cur_, last_;
};
//------------------Implementation of range_adapter---------------------------//
template<typename Mode, typename Range>
range_adapter<Mode, Range>::range_adapter(const Range& rng)
: first_(rng.begin()), cur_(rng.begin()), last_(rng.end()) { }
template<typename Mode, typename Range>
range_adapter<Mode, Range>::range_adapter(iterator first, iterator last)
: first_(first), cur_(first), last_(last) { }
template<typename Mode, typename Range>
inline std::streamsize range_adapter<Mode, Range>::read
(char_type* s, std::streamsize n)
{ return impl::read(cur_, last_, s, n); }
template<typename Mode, typename Range>
inline std::streamsize range_adapter<Mode, Range>::write
(const char_type* s, std::streamsize n)
{ return impl::write(cur_, last_, s, n); }
template<typename Mode, typename Range>
std::streampos range_adapter<Mode, Range>::seek
(stream_offset off, BOOST_IOS::seekdir way)
{
impl::seek(first_, cur_, last_, off, way);
return offset_to_position(cur_ - first_);
}
//------------------Implementation of range_adapter_impl----------------------//
template<>
struct range_adapter_impl<std::forward_iterator_tag> {
template<typename Iter, typename Ch>
static std::streamsize read
(Iter& cur, Iter& last, Ch* s,std::streamsize n)
{
std::streamsize rem = n; // No. of chars remaining.
while (cur != last && rem-- > 0) *s++ = *cur++;
return n - rem != 0 ? n - rem : -1;
}
template<typename Iter, typename Ch>
static std::streamsize write
(Iter& cur, Iter& last, const Ch* s, std::streamsize n)
{
while (cur != last && n-- > 0) *cur++ = *s++;
if (cur == last && n > 0)
boost::throw_exception(write_area_exhausted());
return n;
}
};
template<>
struct range_adapter_impl<std::random_access_iterator_tag> {
template<typename Iter, typename Ch>
static std::streamsize read
(Iter& cur, Iter& last, Ch* s,std::streamsize n)
{
std::streamsize result =
(std::min)(static_cast<std::streamsize>(last - cur), n);
if (result)
std::copy(cur, cur + result, s);
cur += result;
return result != 0 ? result : -1;
}
template<typename Iter, typename Ch>
static std::streamsize write
(Iter& cur, Iter& last, const Ch* s, std::streamsize n)
{
std::streamsize count =
(std::min)(static_cast<std::streamsize>(last - cur), n);
std::copy(s, s + count, cur);
cur += count;
if (count < n)
boost::throw_exception(write_area_exhausted());
return n;
}
template<typename Iter>
static void seek
( Iter& first, Iter& cur, Iter& last, stream_offset off,
BOOST_IOS::seekdir way )
{
using namespace std;
switch (way) {
case BOOST_IOS::beg:
if (off > last - first || off < 0)
boost::throw_exception(bad_seek());
cur = first + off;
break;
case BOOST_IOS::cur:
{
std::ptrdiff_t newoff = cur - first + off;
if (newoff > last - first || newoff < 0)
boost::throw_exception(bad_seek());
cur += off;
break;
}
case BOOST_IOS::end:
if (last - first + off < 0 || off > 0)
boost::throw_exception(bad_seek());
cur = last + off;
break;
default:
assert(0);
}
}
};
} } } // End namespaces detail, iostreams, boost.
#include <boost/iostreams/detail/config/enable_warnings.hpp> // MSVC.
#endif // #ifndef BOOST_IOSTREAMS_DETAIL_RANGE_ADAPTER_HPP_INCLUDED //---------------//
| [
"contact@anima-games.com@bd273c4a-bd8d-77bb-0e36-6aa87360798c"
] | contact@anima-games.com@bd273c4a-bd8d-77bb-0e36-6aa87360798c |
8ec3ae167cb5d310cef5847acafb6e790ba793ee | 181841bfa62a45d123db5696913ed9ae62c17998 | /C06/ex01/main.cpp | aaff0b56d57fb98fe36d2b2ee408fd663b276f4c | [] | no_license | PennyBlack2008/CPP_Practice | fadaaaa9f28abe5bfc673de88b47a1940a3b6378 | ee2a7fe13f97427645061ab8fe35cab0f95121f5 | refs/heads/master | 2023-04-03T11:30:33.525216 | 2021-04-20T11:20:02 | 2021-04-20T11:20:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,053 | cpp | #include <string>
#include <iostream>
struct Data
{
std::string s1;
int n;
std::string s2;
};
// 8글자인 랜덤 문자열(알파벳or숫자) + 랜덤 int형 변수+ 8글자인 랜덤 문자열(알파벳or숫자)
// 데이터를 직렬화함
void *serialize(void)
{
std::string s1 = "";
std::string s2 = "";
char *ptr;
char alphanum[] = "0123456789abcdefghijklmnopqrstuvwxyz";
int integer;
srand(clock()); // 난수를 위해 사용하는 함수
for (int i = 0; i < 8; i++)
{
s1 += alphanum[rand() % 35]; // 8글자의 랜덤 문자열(알파벳or숫자)
s2 += alphanum[rand() % 35]; // 8글자의 랜덤 문자열(알파벳or숫자)
}
integer = rand(); // 랜덤 int형변수를 반환하는 함수
ptr = new char[sizeof(s1) + sizeof(integer) + sizeof(s2)]; // 문자열2개의 크기와 int형변수의 크기만큼 메모리 할당
std::cout<<"s1 : "<<s1<<'\n';
std::cout<<"integer : "<<integer<<'\n';
std::cout<<"s2 : "<<s2<<'\n';
memcpy(ptr, &s1, 24); // ptr = s1
memcpy(ptr + 24, &integer, 4); // ptr = s1 + integer
memcpy(ptr + 28, &s2, 24); // ptr = s1 + integer + s2
return (ptr);
}
// 데이터를 역직렬화함
Data *deserialize(void *raw)
{
Data *dd = new Data;
// reinterpret_cast<char*>(raw) 해도됨
dd->s1 = static_cast<char*>(raw); // raw 가리키기
// 8byte만큼 이동하기위해 먼저 static_cast<char*>(raw)
// dd->n = *static_cast<int*>(static_cast<char*>(raw) + 24); // 에러
dd->n = *reinterpret_cast<int*>(static_cast<char*>(raw) + 24); // raw+24 이후로 int 크기만큼 데이터 담기
dd->s2 = static_cast<char*>(raw) + 28; // raw+28 가리키기
return (dd);
}
int main(void)
{
char *ptr = static_cast<char*>(serialize()); // 랜덤데이터의 직렬화
Data *des = deserialize(ptr); // 랜덤데이터를 역직렬화
std::cout << des->s1 << std::endl;
std::cout << des->n << std::endl;
std::cout << des->s2 << std::endl;
delete des;
} | [
"jikang@c6r10s6.42seoul.kr"
] | jikang@c6r10s6.42seoul.kr |
528422c0f4913fa1c0d31a565704bb0ac5a7feb0 | bc893922087e0894dbe3f0963fbda231c6b7af61 | /Monitor/widget.h | 903c005d8f2ef40403c238a1a73e228fc9a710c9 | [] | no_license | FreiheitZZ/BusLogTool | 1946e3eb74e15804f0a02a9f7d0b0a0953a38e4f | 8b5c85b23b39a09f641f4d82215e563da813bb62 | refs/heads/master | 2021-01-09T14:13:37.592845 | 2020-02-22T12:16:03 | 2020-02-22T12:16:03 | 242,331,759 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,152 | h | #ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QComboBox>
#include <QPushButton>
#include <QTextEdit>
#include <QTextCursor>
#include <QTextCharFormat>
#include <QTimer>
#define USB_VAL_DLE 0x9F
#define USB_VAL_STX 0x02
#define USB_VAL_ETX 0x03
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
void initUI();
void USB_sendData(unsigned char * pData, unsigned char size);
QStringList getPortNameList();//获取所有可用的串口列表
void openPort();//打开串口
void update_com_num();
public slots:
void receiveInfo();
// void BaudRateChange();
void timerUpDate();
private:
Ui::Widget *ui;
QSerialPort* m_serialPort; //串口类
QStringList m_portNameList;
QComboBox* m_PortNameComboBox;
QComboBox* m_BaudRateComboBox;
QComboBox* m_StopBitsComboBox;
QComboBox* m_ParityComboBox;
QComboBox* m_DataBitsComboBox;
QPushButton* m_OpenPortButton;
QTextEdit *textEdit;
QTimer *timer;
};
#endif // WIDGET_H
| [
"791326847@qq.com"
] | 791326847@qq.com |
66dd1063c993c3e46e269a0e9f36e6a12314d1fe | 594b8ec2e0f3f088c8c77da2cd339e9d7c6b012c | /software/test_dir/teensy_test/src/main.cpp | 96249a59fc0a36cabebffcec7c2b30badb6146ca | [
"MIT"
] | permissive | benoitlx/SpotAI | 7f820bb90c6544637b3a02b1335ebcff07e8db54 | 2b546c1f341a32519a21befc6eec43932fc85d36 | refs/heads/main | 2023-07-06T09:53:25.716792 | 2021-08-10T13:21:56 | 2021-08-10T13:21:56 | 384,997,174 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,011 | cpp | #include <Arduino.h>
#include <ArduinoJson.h>
#include "Wire.h"
#include <Adafruit_PWMServoDriver.h>
#include <MPU6050_light.h>
#include <tof10120.h>
#include <servos.h>
/* I2C adresses */
#define LID_ADR 0x52
#define LID1_ADR 0x54
#define DRV_ADR 0x40
#define PWM_FREQ 50.0
/* Instanciation */
MPU6050 mpu(Wire);
TOF10120 lid(Wire, LID_ADR);
TOF10120 lid1(Wire, LID1_ADR);
Adafruit_PWMServoDriver driver = Adafruit_PWMServoDriver(DRV_ADR, Wire);
Servos servo(driver, PWM_FREQ);
long timer = 0;
void sendSerial(){
StaticJsonDocument<192> data;
data[F("dist0")] = lid.getDistance();
data[F("dist1")] = lid1.getDistance();
data["temp"] = mpu.getTemp();
JsonObject acc = data.createNestedObject("acc");
acc["x"] = mpu.getAccX();
acc["y"] = mpu.getAccY();
acc["z"] = mpu.getAccZ();
JsonObject gyro = data.createNestedObject("gyro");
gyro["x"] = mpu.getGyroX();
gyro["y"] = mpu.getGyroY();
gyro["z"] = mpu.getGyroZ();
JsonObject acc_angle = data.createNestedObject("acc_angle");
acc_angle["x"] = mpu.getAccAngleX();
acc_angle["y"] = mpu.getAccAngleY();
JsonObject angle = data.createNestedObject("angle");
angle["x"] = mpu.getAngleX();
angle["y"] = mpu.getAngleY();
angle["z"] = mpu.getAngleZ();
serializeJson(data, Serial);
}
/* Setup */
void setup() {
// Initialize Serial
Serial.begin(9600);
while(!Serial){;} // wait for usb to be connected
// Initialize I2C
Wire.begin();
// Initialize Accelerometer and gyroscope
byte status = mpu.begin();
// while(status!=0){ } // stop everything if could not connect to MPU6050
delay(1000);
mpu.calcOffsets(true,true); // gyro and accelero
// Initialize Servo Driver
servo.begin(); // start servo driver
}
/* Loop */
void loop() { //9.3%
if(millis() - timer > 250){ // print data every second
mpu.update();
lid.update();
lid1.update();
sendSerial();
timer = millis();
}
// loop to run neural network (every 1ms) and apply changes on the servos
}
| [
"benoitleroux41@gmail.com"
] | benoitleroux41@gmail.com |
3575c98b38fed5aa22f0a31add46d666c419fe6c | f78fe5ddcad822fb7e484cc3ffa5df6b9305cb6c | /src/Nodes/Dynamics/Shaper.h | b2e6d8190493d098525d2e10cdc06216b46f9e4b | [
"MIT"
] | permissive | potrepka/DSP | 5c993fda13f0a28aa8debca1930771bdecaa2ac8 | 0ffe314196efcd016cdb4ffff27ada0f326e50c3 | refs/heads/master | 2023-05-28T01:49:34.453472 | 2021-06-20T05:36:52 | 2021-06-20T05:36:52 | 270,168,511 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 732 | h | #pragma once
#include "../Core/Transformer.h"
namespace dsp {
class Shaper : public Transformer {
public:
struct Mode {
static const int MIN = 0;
static const int MAX = 1;
static const int HYPERBOLIC = 0;
static const int RATIONAL = 1;
};
Shaper(Space space = Space::TIME);
std::shared_ptr<Input> getDrive() const;
std::shared_ptr<Input> getMode() const;
Sample getOutputSignal(size_t channel, Sample input);
protected:
void processNoLock() override;
private:
const std::shared_ptr<Input> drive;
const std::shared_ptr<Input> mode;
static Sample getOutputSignal(const Sample &input, const Sample &drive, const Sample &mode);
};
} // namespace dsp
| [
"nspotrepka@gmail.com"
] | nspotrepka@gmail.com |
242dd4c0996bf1cce1a9c1ef549f49d097cba497 | bf45a308e128c876bce597e3b3bfd96c22e53d08 | /src/config.hpp | 8de11fa16750fb1757e7c84c77dfe77b970ebacd | [] | no_license | madmongo1/amytest | b5a23dfe1160add95e689145e308555f4341a84d | 3791da905e9c469e61f40d31a28c4c11c3cab0c4 | refs/heads/master | 2021-01-19T21:24:47.319874 | 2017-04-21T14:40:45 | 2017-04-21T14:40:45 | 88,656,429 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 177 | hpp | #include <boost/asio.hpp>
namespace amytest {
namespace asio = boost::asio;
using tcp_endpoint = asio::ip::tcp::endpoint;
using ip_address = asio::ip::address;
}
| [
"hodges.r@gmail.com"
] | hodges.r@gmail.com |
eff5a5c9a919bd99db0e2bb30be0cb2060033c79 | 9f6bcff0c65df44a6ba3a31b852b8446edc01d96 | /code/cpp/engine/system/TouchDefines.h | 50cdd409d3ba56065d6e4b0820badf9aaa6b3d30 | [] | no_license | eddietree/FunkEngine-Public | 15cdf6b50d610c6f476df97449cc9282df790117 | ed1401c77a4696843ea2abcd5a49c2ceac644f8f | refs/heads/master | 2021-03-12T22:44:18.187011 | 2014-01-05T05:04:58 | 2014-01-05T05:04:58 | 15,035,148 | 21 | 2 | null | 2014-01-05T05:04:59 | 2013-12-09T01:26:30 | C | UTF-8 | C++ | false | false | 1,967 | h |
#pragma once
#include <math/v2.h>
#include <math/v3.h>
#include <math/v4.h>
#include <math/matrix.h>
#include <math/Box3.h>
#include <gm/gmVariable.h>
#include <stdint.h>
namespace funk
{
enum TouchEventType
{
TOUCHEVENT_BEGIN,
TOUCHEVENT_MOVE,
TOUCHEVENT_STATIONARY,
TOUCHEVENT_END,
TOUCHEVENT_CANCEL,
// used for counting
TOUCHEVENT_COUNT,
};
enum TouchCollisionType
{
COLLISIONTYPE_BOX,
COLLISIONTYPE_SPHERE,
COLLISIONTYPE_PLANE,
COLLISIONTYPE_TRIANGLE,
COLLISIONTYPE_DISK,
COLLISIONTYPE_QUAD,
// used for counting
COLLISIONTYPE_COUNT,
};
enum TouchLayer
{
TOUCHLAYER_HUD,
TOUCHLAYER_SCENE,
TOUCHLAYER_BG,
// used for counting
TOUCHLAYER_COUNT,
};
struct TouchInput
{
uint32_t id;
float timestamp_begin;
float timestamp;
TouchEventType state;
int tap_count;
v2 pos; // current position
v2 pos_prev; // previous movement (not previous frame)
v2 pos_start; // on touch start
};
// users must register callbacks and provide collision data
struct TouchListenerCallBack
{
// callback: obj_this:callback(intersect_pt, callback_param)
gmVariable callback_obj;
gmVariable callback_func;
gmVariable callback_param;
TouchLayer layer;
TouchEventType event;
// collision
union CollisionDataUnion
{
struct
{
v3 box_center;
v3 box_dimen;
};
struct // Plane (Ax+By+Cz+D=0)
{
v4 plane;
};
struct // Sphere
{
v3 sphere_center;
float sphere_radius;
};
struct // Disk
{
v3 disk_center;
v3 disk_normal;
float disk_radius;
};
struct // Triangle
{
v3 tri_pt0;
v3 tri_pt1;
v3 tri_pt2;
};
struct // Quad
{
v3 quad_pt0;
v3 quad_pt1;
v3 quad_pt2;
v3 quad_pt3;
};
CollisionDataUnion(){}
} collision_data;
TouchCollisionType collision_type;
// no scaling!!
matrix collision_model_matrix;
};
}
| [
"eddie@illogictree.com"
] | eddie@illogictree.com |
7812743dbfc8bb589efd58f41925244eb9941427 | a2ef78c8fdb96bb059e5cebe6a9a71531256f059 | /widgetset/style.cpp | d82b1c559ebab51f97960bf6f20307226113b07b | [] | no_license | zsombi/kuemelappz | ed9151251525d520cf38bfb12372d7ac873873f3 | 3e695b3f89773755002dd60643287c081261df29 | refs/heads/master | 2021-01-22T02:34:19.001582 | 2012-06-04T18:59:08 | 2012-06-04T18:59:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,866 | cpp | /**
Style - non-visual element that defines the basic proeprties of a style element.
The element serves as type identification helper.
A style element is identified by a name and the layout type. The element can be
used in defining component styles aswell as defining local styles (see StyledItem
for local styles). Component style elements can define component specific proeprties,
which will be passed to the components upon use.
Properties:
proeprty name: string
Defines the style name.
property type: StyleTypes
Defines the style type. This can be a combination of the following values:
Style.Normal - normal layout
Style.Pressed - pressed layout
Style.Dimmed - dimmed (disabled) layout
Style.Highlighted - higlighted layout, e.g. used when mouse hovering over
the component
Style.Expanded - expanded layout, used in expand/collapse type components
*/
#include "style.h"
#include "globaldefs.h"
//#define TRACE_STYLE
Style::Style(QObject *parent) :
QObject(parent),
m_name(""),
m_type(Undefined)
{
}
Style::~Style()
{
#ifdef TRACE_STYLE
qDebug() << "clearing" << m_name << "type" << m_type;
#endif
}
// name property getter/setter
QString Style::name() const
{
return m_name;
}
void Style::setName(const QString &name)
{
if (name != m_name) {
m_name = name;
// set the type to Normal if it hasn't been set yet
if (!m_name.isEmpty() && (m_type == Undefined))
m_type = Normal;
emit nameChanged();
}
}
// type proeprty getter/setter
Style::StyleTypes Style::type() const
{
return m_type;
}
void Style::setType(Style::StyleTypes set)
{
if (set != m_type) {
m_type = set;
emit typeChanged();
}
}
| [
"zsombor.egri@gmail.com"
] | zsombor.egri@gmail.com |
ca8b5f046685d36bab5c498850fe5e4361eefc3c | 8389913a078ce370f05624321b16bfe9c9f1febf | /C++/training.cpp | 96e5a478b0fd9a94eb973dc3654c35b8da339e9e | [] | no_license | lvodoleyl/Algorithm_Rocchio | 75ba09324e5709b98b2bb57d523b2bc295b89bda | 2a23865f19bc2b4150ce390172d85cc17f6c4878 | refs/heads/main | 2023-02-10T12:51:53.654113 | 2021-01-06T19:21:24 | 2021-01-06T19:21:24 | 327,407,580 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,309 | cpp | #include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>
#include <iterator>
#include <cmath>
#include <math.h>
//#define TRAIN_CSV_PATH "D:\\Uchoba\\Kocheshkov\\Curs\\Data\\data_train.csv"
#define TRAIN_CSV_PATH "D:\\Uchoba\\Kocheshkov\\Curs\\Data\\test_time.csv"
#define ROCCHIO_CSV_PATH "D:\\Uchoba\\Kocheshkov\\Curs\\Data\\model_rocchio.csv"
using namespace std;
struct Document
{
public:
vector<string> tokens;
string _class;
};
struct Tokens
{
public:
string token;
int count;
};
struct Centroids
{
public:
string _class;
vector<double> centr;
};
int main(int argc, char* argv[])
{
// на какой выборке тестируемся?
size_t train_doc;
if (argc > 1) train_doc = atoi(argv[1]);
else train_doc = -1;
vector<Document> DOCS;
vector<string> CLASSES;
vector<Centroids> CENTR;
vector<Tokens> TOKENS;
bool flag;
size_t count_doc;
//vector<Centroids> result;
ifstream csvFile;
string file_name = TRAIN_CSV_PATH;
string line, str;
//Читаем файл, и считываем документы
csvFile.open(file_name.c_str());
if (!csvFile.is_open())
{
cout << "Error in PATH input file!" << endl;
exit(1);
}
while(getline(csvFile, line))
{
//считываем один документ
if (line.empty()) continue;
if (train_doc-- == 0) break;
line.pop_back();
count_doc++;
Document *d = new Document;
stringstream lineStream(line);
getline(lineStream,d->_class,',');
while (getline(lineStream, str, ','))
{
d->tokens.push_back(str);
//Считаем df
flag = true;
for(size_t i = 0; i < d->tokens.size()-1; i++)
{
flag = flag && (d->tokens[i] != str);
}
for(size_t i = 0; i < TOKENS.size(); i++)
{
if ((TOKENS[i].token == str)&&(flag))
{
TOKENS[i].count++;
flag = false;
break;
}
}
if (flag)
{
Tokens tok;
tok.token = str;
tok.count = 1;
TOKENS.push_back(tok);
}
}
//есть ли там наш класс?
flag = true;
for(size_t i = 0; i < CLASSES.size(); i++)
{
if (CLASSES[i] == d->_class) flag = false;
}
if (flag) CLASSES.push_back(d->_class);
DOCS.push_back(*d);
}
csvFile.close();
//Основные вычисления
for (size_t _class = 0; _class < CLASSES.size(); _class++)
{
vector<double> sum_vector_class(TOKENS.size());
size_t num_doc_class = 0;
for (size_t _doc = 0; _doc < DOCS.size(); _doc++)
{
if (DOCS[_doc]._class == CLASSES[_class])
{
num_doc_class++;
vector<double> vector_of_weights;
for(size_t tok = 0; tok < TOKENS.size(); tok++)
{
size_t tf = 0;
for(size_t i = 0; i < DOCS[_doc].tokens.size(); i++)
{
if (DOCS[_doc].tokens[i] ==TOKENS[tok].token) tf++;
}
double w = tf * log2(count_doc / TOKENS[tok].count);
vector_of_weights.push_back(w);
}
double llwll = 0;
for(size_t weight = 0; weight < vector_of_weights.size();weight++)
{
llwll += vector_of_weights[weight]*vector_of_weights[weight];
}
llwll = sqrt(llwll);
for(size_t weight = 0; weight < vector_of_weights.size();weight++)
{
sum_vector_class[weight] += vector_of_weights[weight] / llwll;
}
}
}
for(size_t i = 0; i < sum_vector_class.size();i++)
{
sum_vector_class[i] = sum_vector_class[i] / num_doc_class;
}
Centroids _centr;
_centr._class = CLASSES[_class];
_centr.centr = sum_vector_class;
CENTR.push_back(_centr);
}
//Осталось записать!
fstream csvFile_model;
string file_model = ROCCHIO_CSV_PATH;
csvFile_model.open(file_model.c_str(), ios::out);
if (!csvFile_model.is_open())
{
ofstream ofs(ROCCHIO_CSV_PATH);
csvFile.open(file_model.c_str());
}
csvFile_model << count_doc << ',';
for(size_t _tok = 0; _tok < TOKENS.size(); _tok++)
csvFile_model << TOKENS[_tok].token << ',';
csvFile_model << endl;
for(size_t _tok = 0; _tok < TOKENS.size(); _tok++)
csvFile_model << TOKENS[_tok].count << ',';
csvFile_model << endl;
for(size_t _c_ = 0; _c_ < CENTR.size(); _c_++)
{
csvFile_model << CENTR[_c_]._class << ',';
for(size_t val = 0; val < CENTR[_c_].centr.size(); val++)
csvFile_model << CENTR[_c_].centr[val] << ',';
csvFile_model << endl;
}
csvFile_model.close();
} | [
"abrosimov.kirill.1999@mail.ru"
] | abrosimov.kirill.1999@mail.ru |
fb8adbc2e4613abdb5fcc5633423b485306ddcee | bc6cd18a13992f425bb97406c5c5e7e3b8d8cb03 | /src/robot/motion_command_filter.h | 91040da3ba22daaaba0f2978868f9926fcd4505d | [
"MIT"
] | permissive | collinej/Vulcan | 4ef1e2fc1b383b2b3a9ee59d78dc3c027d4cae24 | fa314bca7011d81b9b83f44edc5a51b617d68261 | refs/heads/master | 2022-09-19T01:59:45.905392 | 2022-09-18T02:41:22 | 2022-09-18T02:41:22 | 186,317,314 | 3 | 3 | NOASSERTION | 2022-04-29T02:06:12 | 2019-05-13T00:04:38 | C++ | UTF-8 | C++ | false | false | 3,113 | h | /* Copyright (C) 2010-2019, The Regents of The University of Michigan.
All rights reserved.
This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab
under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an
MIT-style License that can be found at "https://github.com/h2ssh/Vulcan".
*/
/**
* \file motion_command_validator.h
* \author Jong Jin Park
*
* Declaration of MotionCommandFilter.
*/
#ifndef ROBOT_MOTION_COMMAND_FILTER_H
#define ROBOT_MOTION_COMMAND_FILTER_H
#include "robot/commands.h"
#include "robot/params.h"
namespace vulcan
{
namespace robot
{
/**
* MotionCommandFilter is used to determine whether an incoming motion command is valid and can
* be issued to the wheelchair. Each motion command has an associated source. A high-level arbiter
* determines the active motion command based on user and control inputs. The filter then marks
* as valid only those commands coming from the active source.
*
* An active source either latches for all time or has an associated timeout interval. A source times
* out if it doesn't receive a command within the specified timeout interval. Once the active source
* has timed out, then no commands are accepted.
*
* Currently, the timeout value is not being used. It may be added in the future, but its utility needs
* to be thought through more carefully in the context of the full system.
*
* The MotionCommandFilter accepts change_command_source_message_t to determine the currently active
* command. To check if a command is valid, use the validMotionCommand() method.
*
* Currently, the MotionCommandFilter acts as its own arbiter, determing who has command. Eventually,
* this capability will be pulled out and placed in a separate arbiter module. Right now, the control
* is determined by these rules:
*
* 0) Manual control immediately overrides all other controls.
* 1) Manual control expires after a period of time, allowing any control method afterward.
*/
class MotionCommandFilter
{
public:
/**
* Constructor for MotionCommandFilter.
*
* \param params Parameters controlling the filter
*/
MotionCommandFilter(const command_filter_params_t& params);
/**
* validMotionCommand checks to see if a motion command is valid based on the currently active command source.
*
* \param command Command to be validated
* \return True if the command is valid and should be issued to the wheelchair.
*/
bool validMotionCommand(const motion_command_t& command);
private:
void activateSource(command_source_t source, int64_t commandTime, int64_t timeout);
void deactivateCurrentSource(void);
bool hasSourceTimedOut(int64_t commandTime) const;
bool isValidCommand(const motion_command_t& command) const;
command_source_t activeSource;
int64_t lastValidCommandTime;
int64_t sourceTimeoutInterval;
command_filter_params_t params;
};
} // namespace robot
} // namespace vulcan
#endif // ROBOT_MOTION_COMMAND_VALIDATOR_H
| [
"collinej@umich.edu"
] | collinej@umich.edu |
66550b521456b8c701c794fd3bb13bb216bb269f | 619054eaea6b93fb3ad354606029363817088285 | /rai/common/parameters.hpp | 96c194dcaabdcd179d00ead1132780ca9858807b | [
"MIT"
] | permissive | raicoincommunity/Raicoin | e3d1047b30cde66706b994a3b31e0b541b07c79f | ebc480caca04caebdedbc3afb4a8a0f60a8c895f | refs/heads/master | 2023-09-03T00:39:00.762688 | 2023-08-29T17:01:09 | 2023-08-29T17:01:09 | 210,498,091 | 99 | 16 | MIT | 2023-08-29T17:01:11 | 2019-09-24T02:52:27 | C++ | UTF-8 | C++ | false | false | 5,261 | hpp | #pragma once
#include <string>
#include <rai/common/numbers.hpp>
#include <rai/common/chain.hpp>
namespace rai
{
#define XSTR(x) VER_STR(x)
#define VER_STR(x) #x
const char * const RAI_VERSION_STRING = XSTR(TAG_VERSION_STRING);
enum class RaiNetworks
{
// Low work parameters, publicly known genesis key, test IP ports
TEST,
// Normal work parameters, secret beta genesis key, beta IP ports
BETA,
// Normal work parameters, secret live key, live IP ports
LIVE,
};
rai::RaiNetworks constexpr RAI_NETWORK = rai::RaiNetworks::ACTIVE_NETWORK;
std::string NetworkString();
uint64_t constexpr TEST_EPOCH_TIMESTAMP = 1577836800;
uint64_t constexpr TEST_GENESIS_BALANCE = 10000000; //unit: RAI
const std::string TEST_PRIVATE_KEY =
"34F0A37AAD20F4A260F0A5B3CB3D7FB50673212263E58A380BC10474BB039CE4";
// rai_3e3j5tkog48pnny9dmfzj1r16pg8t1e76dz5tmac6iq689wyjfpiij4txtdo
const std::string TEST_PUBLIC_KEY =
"B0311EA55708D6A53C75CDBF88300259C6D018522FE3D4D0A242E431F9E8B6D0";
const std::string TEST_GENESIS_BLOCK = R"%%%({
"type": "transaction",
"opcode": "receive",
"credit": "512",
"counter": "1",
"timestamp": "1577836800",
"height": "0",
"account": "rai_3e3j5tkog48pnny9dmfzj1r16pg8t1e76dz5tmac6iq689wyjfpiij4txtdo",
"previous": "0000000000000000000000000000000000000000000000000000000000000000",
"representative": "rai_1nwbq4dzmo7oe8kzz6ox3bdp75n6chhfrd344yforc8bo4n9mbi66oswoac9",
"balance": "10000000000000000",
"link": "B0311EA55708D6A53C75CDBF88300259C6D018522FE3D4D0A242E431F9E8B6D0",
"signature": "67DF01C204603C0715CAA3B1CB01B1CE1ED84E499F3432D85D01B1509DE9C51D4267FEAB2E376903A625B106818B0129FAC19B78C2F5631F8CAB48A7DF502602"
})%%%";
uint64_t constexpr BETA_EPOCH_TIMESTAMP = 1585699200;
uint64_t constexpr BETA_GENESIS_BALANCE = 10010000; //unit: RAI
const std::string BETA_PUBLIC_KEY =
"4681DC26DA5C34B59D5B320D8053D957D5FC824CE39B239B101892658F180F08";
const std::string BETA_GENESIS_BLOCK = R"%%%({
"type": "transaction",
"opcode": "receive",
"credit": "512",
"counter": "1",
"timestamp": "1585699200",
"height": "0",
"account": "rai_1jn3uimfnq3nppgopeifi3bxkoyozk36srwu6gfj186kep9ji5rawm6ok3rr",
"previous": "0000000000000000000000000000000000000000000000000000000000000000",
"representative": "rai_1jngsd4mnzfb4h5j8eji5ynqbigaz16dmjjdz8us6run1ziyzuqfhz8yz3uf",
"balance": "10010000000000000",
"link": "4681DC26DA5C34B59D5B320D8053D957D5FC824CE39B239B101892658F180F08",
"signature": "D265320853B6D9533EEB48E857E0C68DF3E32C5CF1B1178236EB2E0453A68B8F927415ACE8FC1E5C16C8DEB7C11DD43EFD86CA3DDB826243400AAF85DCC8D506"
})%%%";
uint64_t constexpr LIVE_EPOCH_TIMESTAMP = 1595894400;
uint64_t constexpr LIVE_GENESIS_BALANCE = 10010000; //unit: RAI
const std::string LIVE_PUBLIC_KEY =
"0EF328F20F9B722A42A5A0873D7F4F05620E8E9D9C5BF0F61403B98022448828";
const std::string LIVE_GENESIS_BLOCK = R"%%%({
"type": "transaction",
"opcode": "receive",
"credit": "512",
"counter": "1",
"timestamp": "1595894400",
"height": "0",
"account": "rai_15qm75s1z8uk7b3cda699ozny3d43t9bu94uy5u3a1xsi1j6b43apftwsfs9",
"previous": "0000000000000000000000000000000000000000000000000000000000000000",
"representative": "rai_3h5s5bgaf1jp1rofe5umxan84kiwxj3ppeuyids7zzaxahsohzchcyxqzwp6",
"balance": "10010000000000000",
"link": "0EF328F20F9B722A42A5A0873D7F4F05620E8E9D9C5BF0F61403B98022448828",
"signature": "ACA0AC37F02B2C9D40929EAD69FAE1828E89728896FB06EEA8274852CDA647E9F9AB9D5868DB379253CAD2E0D011BEC4EA4FF2BBC9A369354D4D8154C796920F"
})%%%";
uint64_t constexpr MAX_TIMESTAMP_DIFF = 300;
uint64_t constexpr MIN_CONFIRM_INTERVAL = 10;
uint32_t constexpr TRANSACTIONS_PER_CREDIT = 20;
uint32_t constexpr ORDERS_PER_CREDIT = 1;
uint64_t constexpr SWAPS_PER_CREDIT = 1;
uint64_t constexpr EXTRA_FORKS_PER_CREDIT = 1;
uint16_t constexpr MAX_ACCOUNT_CREDIT = 65535;
uint32_t constexpr MAX_ACCOUNT_DAILY_TRANSACTIONS =
MAX_ACCOUNT_CREDIT * TRANSACTIONS_PER_CREDIT;
uint32_t constexpr CONFIRM_WEIGHT_PERCENTAGE = 80;
uint32_t constexpr FORK_ELECTION_ROUNDS_THRESHOLD = 5;
uint32_t constexpr AIRDROP_ACCOUNTS = 10000;
uint64_t constexpr AIRDROP_INVITED_ONLY_DURATION = 180 * 86400;
uint64_t constexpr AIRDROP_DURATION = 4 * 360 * 86400;
size_t constexpr MAX_EXTENSIONS_SIZE = 256;
uint64_t constexpr SWAP_PING_PONG_INTERVAL = 60;
uint64_t constexpr BASE_ALLOWED_BINDINGS = 16;
uint64_t constexpr EXTRA_BINDINGS_PER_CREDIT = 1;
uint32_t constexpr CROSS_CHAIN_EPOCH_INTERVAL = 3 * 24 * 60 * 60;
// Votes from qualified representatives will be broadcasted
const rai::Amount QUALIFIED_REP_WEIGHT = rai::Amount(256 * rai::RAI);
uint64_t EpochTimestamp();
std::string GenesisPublicKey();
rai::Amount GenesisBalance();
std::string GenesisBlock();
rai::Amount CreditPrice(uint64_t);
rai::Amount RewardRate(uint64_t);
rai::Amount RewardAmount(const rai::Amount&, uint64_t, uint64_t);
uint64_t RewardTimestamp(uint64_t, uint64_t);
uint16_t BaseAllowedForks(uint64_t);
uint64_t MaxAllowedForks(uint64_t, uint32_t);
uint64_t AllowedBindings(uint32_t);
rai::Chain CurrentChain();
uint32_t CrossChainEpoch(uint64_t);
uint64_t CrossChainEpochTimestamp(uint32_t);
} // namespace rai
| [
"bitharu7@gmail.com"
] | bitharu7@gmail.com |
1d066af50a4e7613d294320c768eb77467e31cf9 | 2e313b54926cf2b4d00a8a2a035f9d1176118479 | /Backtracking/nQueen/nQueen/nQueen.cpp | 693b26017a1b8670e1b55cddbaac50a68f9cb42a | [] | no_license | nvthanh1994/Data-Structure-and-Algorithm-IT3010 | 8dccbad82dece9be417f3a7744cf0978a71b4e12 | 253a7ce7669aeb99c2b4da1b10cb64a1e305e8c2 | refs/heads/master | 2020-04-06T04:25:20.166477 | 2015-01-13T06:27:12 | 2015-01-13T06:27:12 | 29,175,743 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,910 | cpp | #include <iostream>
#include <cstdio>
#include <cmath>
#include <ctime>
using namespace std;
#define MAX 10
int n;
int numOfSolution;
int x[MAX];
bool check(int row, int tempCol){
for(int prevRow=1;prevRow<row;prevRow++){
if(x[prevRow]==tempCol || (abs(tempCol-x[prevRow])==abs(row-prevRow))) return false;
}
return true;
}
void printSolution(){
printf("%-4d %d",numOfSolution,x[1]);
for(int i=2;i<=n;i++){
printf(" %d",x[i]);
}
printf("\n");
}
void Backtrack(int i){
if(numOfSolution>=1) return;
for(int tempCol=1;tempCol<=n;tempCol++){
if(check(i,tempCol)){
x[i]=tempCol;
if(i==n){
++numOfSolution;
printSolution();
return;
}
else Backtrack(i+1);
}
}
}
void BacktrackOne(int i){
if(numOfSolution>=1) return;
for(int tempCol=1;tempCol<=n;tempCol++){
if(check(i,tempCol)){
x[i]=tempCol;
if(i==n){
++numOfSolution;
printSolution();
return;
}
else BacktrackOne(i+1);
}
}
}
int main(){
//freopen("res.txt","r",stdout);
cin >> n;
numOfSolution=0;
printf("SOL Position\n");
printf("# ");
for(int i=1;i<=n;i++){
printf("%d ",i);
if(i==n) printf("\n");
}
printf("-----------------------\n");
clock_t timeStart=clock();
//Backtrack(1);
BacktrackOne(1);
printf("\nTotal solution found : %d\nTime taken : %.4f s\n",numOfSolution, (double)(clock()-timeStart)/CLOCKS_PER_SEC);
return 0;
}
/**
Người dùng nhập vào n, chương trình tính toán và in ra số lời giải + tất cả lời giải
- n là số quân hậu
- x_i là chỉ số cột của con hậu ở hàng i. x_i \in {1->8}
*/
| [
"nvthanh1994@gmail.com"
] | nvthanh1994@gmail.com |
4cb5e987f9ba79b363ca88f3f3e129a2a5532aa9 | 5088f525434b6fca617bccee472ac52cf5158ade | /Engine/Win32Project1/App.h | 9b3233344fb5655e3bb592a7e2be315d7c9a038a | [] | no_license | GrooshBene/2015_GameProject | 5f4112ddd84fd40d50a2c6d915952562eea46a8a | 7a273bba9f7dd7a73a92ae6d85c8bf307717297d | refs/heads/master | 2020-05-18T01:23:39.093389 | 2015-08-11T14:16:44 | 2015-08-11T14:16:44 | 40,545,679 | 0 | 1 | null | null | null | null | UHC | C++ | false | false | 1,456 | h | #pragma once
#include "windows.h"
#include "atlstr.h"
#include <d3dx9.h>
#include "SceneManager.h"
#include "ResourceManager.h"
#include "InputManager.h"
class App
{
private:
static LARGE_INTEGER LInterval, RInterval, Frequency;
static App *instance;
static void InitWindow(); // 윈도우를 초기화
static void FloatWindow(int nCmdShow); // 윈도우를 띄움
static void InitD3D(); // DX 장치설정
static CString title;
public:
App();
~App();
static const int WIDTH = 800;
static const int HEIGHT = 600;
static HINSTANCE hInstance;
static HWND hWnd;
static LPDIRECT3D9 g_pD3D; // 그래픽카드를 생성
static LPDIRECT3DDEVICE9 g_pd3dDevice; // 생성한 그래픽카드 정보를 받아서 사용할 수 있게 해주는 변수
static LPD3DXSPRITE g_pSprite; // 그래픽카드와 연결해서 2D이미지를 출력할 수 있게 해줌
static D3DPRESENT_PARAMETERS d3dpp; // 화면출력의 세부사항을 담고있음
static CSceneManager *g_pSceneManager;
static CResourceManager *g_pResourceManager;
static CInputManager *g_pInputManager;
static int DoLoop(); // 메시지를 처리하며 무한루프
static LRESULT CALLBACK WndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam); // 메시지 처리 프로시저
static void Initialize(HINSTANCE inst, int nCmdShow, CString str);
static void Destroy();
static App* GetInstance();
static float GetElapsedTime();
};
| [
"wltn000129@gmail.com"
] | wltn000129@gmail.com |
346a45db8ee3c5a4b8c93ff00f64bc5445bb81d9 | d7d66364f6e9867ba76bf2cbd7718def2644c4c2 | /CodeMap/Code2Pos1.cpp | c9eca2ada17f8f8a79cf74c767b5e58d9bcc6757 | [] | no_license | lwzswufe/CppCode | ca61b2f410cca758c8968359234ae28c559e9683 | dc9ee87b573acba4f59d26ef1f52b2b92b0982c1 | refs/heads/master | 2023-07-06T22:36:10.692762 | 2023-06-22T15:09:02 | 2023-06-22T15:09:02 | 105,245,499 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,768 | cpp | #include <string.h>
#include "Code2Pos1.h"
namespace Code2Pos1
{
int CODEARRSIZE{40000};
int CODESIZE{7};
int* CODEARR{nullptr};
}
int Code2Pos1::FindCode(const char * code)
{ // 证券代码字符串转化为数组坐标 效率是map<string,int>的5倍
if (code == NULL || strlen(code) < CODESIZE - 1)
return 0;
int base, pos;
// char s[LOGSIZE];
switch (code[0])
{
case '0': // 00X
if(code[1] == '0')
base = 0;
else
return 0;
break;
case '3': // 30X
if(code[1] == '0')
base = 10000;
else
return 0;
break;
case '6':
{
switch (code[1])
{
case '0': base = 20000; break; // 60X;
case '8': base = 30000; break; // 68X;
default:
return 0; break;
}
break;
}
default:
return 0; // 返回0表示未找到
// sprintf(s, "%s error code:%s out of range[0, %d]\n", __func__, code, CODEARRSIZE);
// throw range_error(s);
// printf(s);
}
pos = base + (code[2] - 48) * 1000
+ (code[3] - 48) * 100
+ (code[4] - 48) * 10
+ (code[5] - 48);
if (pos < 0 || pos > CODEARRSIZE)
return 0;
else
return CODEARR[pos];
}
void Code2Pos1::InitialSearchTable()
{
CODEARR = new int[CODEARRSIZE];
memset(CODEARR, 0, sizeof(int) * CODEARRSIZE);
}
void Code2Pos1::ReleaseSearchTable()
{
if (CODEARR != nullptr)
{
delete[] CODEARR;
CODEARR = nullptr;
}
} | [
"lwzswufe@foxmail.com"
] | lwzswufe@foxmail.com |
8751752470b80f8013824afbf9a217aa8c7d8683 | 860fc0c4195dc36abd76919c2926a759aa7b69da | /Search Algorithms/binarysearch_recursive.cpp | 83bc6ac3e14ac396e565112f59bbc0bcc2aaa903 | [] | no_license | Ankush-Kamboj/Algorithms-Cpp | d9584695b645c68b70c4010a71ac4cce1fdcb457 | 9ee63f83445ab0b2c6d12a27cad0d0d28a728a87 | refs/heads/master | 2022-12-26T14:18:00.276464 | 2020-09-21T03:29:38 | 2020-09-21T03:29:38 | 296,233,965 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,183 | cpp | // Binary Search - Recursive
#include <iostream>
using namespace std;
int binarySearch(int arr[], int low, int high, int ele)
{
if (high >= low){
int mid = low + (high - low)/2;
// if element is at the middle
if (arr[mid] == ele){
return mid+1;
}
// if element is smaller than mid, move to left subarray
else if (arr[mid] > ele){
high = mid-1;
return binarySearch(arr, low, high, ele);
}
// if element is larger than mid, move to right subarray
else{
low = mid+1;
return binarySearch(arr, low, high, ele);
}
}
else{
return -1;
}
}
int main(){
int arr[] = {18, 23, 56, 63, 78}; // Binary search takes sorted array
int ele = 18; // element to search
int size = sizeof(arr)/sizeof(arr[0]); // finding size of array
int low = 0;
int high = size - 1;
int result = binarySearch(arr, low, high, ele);
if (result != -1){
cout<<"Position of element is "<<result;
}
else{
cout<<"Element not present";
}
return 0;
} | [
"ankushak2000@gmail.com"
] | ankushak2000@gmail.com |
2ec1d71fe12182de2b2fd18e5b30884cf49ff4a4 | 8d5923162f4ae0abf2dffca969a95dbd49e40220 | /include/PoolObjectAuth.h | 7141ce39302973d9d4dc88c022d43a87870d2512 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | sutthipongl/one5.2.0 | 00a662d8372679b006d4cd30914d5772edeb4be2 | ec756a13ced38f3b2ba70bae043dd1cc734b7a01 | refs/heads/master | 2021-04-26T13:10:30.964344 | 2017-05-18T21:34:35 | 2017-05-18T21:34:35 | 77,481,442 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,805 | h | /* -------------------------------------------------------------------------- */
/* Copyright 2002-2016, OpenNebula Project, OpenNebula Systems */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may */
/* not use this file except in compliance with the License. You may obtain */
/* a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* -------------------------------------------------------------------------- */
#ifndef POOL_OBJECT_AUTH_H_
#define POOL_OBJECT_AUTH_H_
#include "PoolObjectSQL.h"
class AclRule;
/**
* This class abstracts the authorization attributes of a PoolObject. It is
* used to check permissions and access rights of requests
*/
class PoolObjectAuth
{
public:
/* ------------------- Constructor and Methods -------------------------- */
PoolObjectAuth():
oid(-1),
uid(-1),
gid(-1),
owner_u(1),
owner_m(1),
owner_a(0),
group_u(0),
group_m(0),
group_a(0),
other_u(0),
other_m(0),
other_a(0),
disable_all_acl(false),
disable_cluster_acl(false),
disable_group_acl(false) {};
void get_acl_rules(AclRule& owner_rule,
AclRule& group_rule,
AclRule& other_rule,
int zone_id) const;
string type_to_str() const
{
return PoolObjectSQL::type_to_str(obj_type);
};
/* --------------------------- Attributes ------------------------------- */
PoolObjectSQL::ObjectType obj_type;
int oid;
int uid;
int gid;
set<int> cids;
int owner_u;
int owner_m;
int owner_a;
int group_u;
int group_m;
int group_a;
int other_u;
int other_m;
int other_a;
bool disable_all_acl; // All objects of this type (e.g. NET/*)
bool disable_cluster_acl; // All objects in a cluster (e.g. NET/%100)
bool disable_group_acl; // All objects own by this group (e.g. NET/@101)
};
#endif /*POOL_OBJECT_AUTH_H_*/
| [
"Tor@Sutthipongs-MacBook-Pro.local"
] | Tor@Sutthipongs-MacBook-Pro.local |
aa0a665b1e3a8c590c2af0cdb3112692c4a16ce5 | 1044aa34448f85f7b5075501297dd82bb1357266 | /Room.hpp | dcd0979c589cd4fba28e7b95cd7be60b063d0585 | [] | no_license | rustushki/lastdoor | 347bb49079578612b713129bc63a308e92d10ff9 | 4a84f76a504ca5ca01f58c1b7631e77f812266f5 | refs/heads/master | 2021-01-23T01:46:41.043419 | 2017-05-01T01:52:45 | 2017-05-01T01:52:45 | 92,893,136 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 310 | hpp | #ifndef ROOM_HPP
#define ROOM_HPP
#include <string>
#include <vector>
#include "Inventory.hpp"
class Room {
private:
std::string description;
Inventory inventory;
public:
Room(std::string description, Inventory inventory);
std::string getDescription();
Inventory& getInventory();
};
#endif//ROOM_HPP
| [
"russ.adams@gmail.com"
] | russ.adams@gmail.com |
f1c638fc4582256f865ff11fcb5d4398d527de12 | 3ad968797a01a4e4b9a87e2200eeb3fb47bf269a | /dsoundwc_src/Source/Sounder.h | a181d5ead0fadeacd660d6db160f7b75af7624fc | [] | no_license | LittleDrogon/MFC-Examples | 403641a1ae9b90e67fe242da3af6d9285698f10b | 1d8b5d19033409cd89da3aba3ec1695802c89a7a | refs/heads/main | 2023-03-20T22:53:02.590825 | 2020-12-31T09:56:37 | 2020-12-31T09:56:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,286 | h | // Sounder.h : main header file for the SOUNDER application
//
#if !defined(AFX_SOUNDER_H__A14C6329_9447_433F_B74D_0D8727A76C05__INCLUDED_)
#define AFX_SOUNDER_H__A14C6329_9447_433F_B74D_0D8727A76C05__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#ifndef __AFXWIN_H__
#error include 'stdafx.h' before including this file for PCH
#endif
#include "resource.h" // main symbols
/////////////////////////////////////////////////////////////////////////////
// CSounderApp:
// See Sounder.cpp for the implementation of this class
//
class CSounderApp : public CWinApp
{
public:
CSounderApp();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CSounderApp)
public:
virtual BOOL InitInstance();
//}}AFX_VIRTUAL
// Implementation
//{{AFX_MSG(CSounderApp)
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_SOUNDER_H__A14C6329_9447_433F_B74D_0D8727A76C05__INCLUDED_)
| [
"pkedpekr@gmail.com"
] | pkedpekr@gmail.com |
b04cf01b3fdc79d8ab0fbdf269f1f33a8814292e | 6ab32e95c9a32b38fbd7564c2ac8884c31b67203 | /include/savr/rfm69_const.h | 68b8f0ae87c98f53a7771d170453da2cbfd1896f | [
"MIT"
] | permissive | srfilipek/savr | a3c10f8082d8daaa3abe41ae015c8f2843fd6785 | 8c6e461863373117f09fb2cdc3e60adc685761d9 | refs/heads/master | 2021-07-03T01:27:48.403569 | 2020-07-03T19:35:05 | 2020-07-03T19:35:05 | 32,104,735 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,768 | h | /*******************************************************************************
Copyright (C) 2018 by Stefan Filipek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*******************************************************************************/
#ifndef _savr_rfm69_const_h_included_
#define _savr_rfm69_const_h_included_
/**
* @file rfm69_const.h
*/
#include <stdint.h>
#include <stddef.h>
#include <avr/sfr_defs.h>
#include <savr/utils.h>
namespace savr {
namespace rfm69 {
using savr::utils::Bitfield;
/**
* Constants regarding the external RFM69 module
*/
/// Oscillator frequency in Hz
constexpr float F_XOSC = 32000000.0;
/// Frequency granularity: F_XOSC / 2^19
constexpr float F_STEP = static_cast<float>(F_XOSC) / (static_cast<uint32_t>(1) << 19);
/// Maximum frequency deviation setting (14bits x F_STEP)
constexpr uint32_t F_DEV_MAX = static_cast<uint32_t>(F_STEP * 0x3FFF);
/**
* General register addresses
*/
enum Reg : uint8_t {
REG_FIFO = 0x00,
REG_OP_MODE = 0x01,
REG_DATA_MODUL = 0X02,
REG_BITRATE_MSB = 0x03,
REG_BITRATE_LSB = 0x04,
REG_FDEV_MSB = 0x05,
REG_FDEV_LSB = 0x06,
REG_FRF_MSB = 0x07,
REG_FRF_MID = 0x08,
REG_FRF_LSB = 0x09,
REG_OSC_1 = 0x0a,
REG_AFC_CTRL = 0x0b,
REG_LISTEN_1 = 0x0d,
REG_LISTEN_2 = 0x0e,
REG_LISTEN_3 = 0x0f,
REG_VERSION = 0x10,
REG_PA_LEVEL = 0x11,
REG_PA_RAMP = 0x12,
REG_OCP = 0x13,
REG_LNA = 0x18,
REG_RX_BW = 0x19,
REG_AFC_BW = 0x1a,
REG_OOK_PEAK = 0x1b,
REG_OOK_AVG = 0x1c,
REG_OOK_FIX = 0x1d,
REG_AFC_FEI = 0x1e,
REG_AFC_MSB = 0x1f,
REG_AFC_LSB = 0x20,
REG_FEI_MSB = 0x21,
REG_FEI_LSB = 0x22,
REG_RSSI_CONFIG = 0x23,
REG_RSSI_VALUE = 0x24,
REG_DIO_MAP_1 = 0x25,
REG_DIO_MAP_2 = 0x26,
REG_IRQ_FLAGS_1 = 0x27,
REG_IRQ_FLAGS_2 = 0x28,
REG_RSSI_THRESH = 0x29,
REG_RX_TIMEOUT_1 = 0x2a,
REG_RX_TIMEOUT_2 = 0x2b,
REG_PREAMBLE_MSB = 0x2c,
REG_PREAMBLE_LSB = 0x2d,
REG_SYNC_CONFIG = 0x2e,
REG_SYNC_VALUE_1 = 0x2f,
REG_SYNC_VALUE_2 = 0x30,
REG_SYNC_VALUE_3 = 0x31,
REG_SYNC_VALUE_4 = 0x32,
REG_SYNC_VALUE_5 = 0x33,
REG_SYNC_VALUE_6 = 0x34,
REG_SYNC_VALUE_7 = 0x35,
REG_SYNC_VALUE_8 = 0x36,
REG_PACKET_CONFIG_1 = 0x37,
REG_PAYLOAD_LENGTH = 0x38,
REG_NODE_ADRS = 0x39,
REG_BROADCAST_ADRS = 0x3a,
REG_AUTO_MODES = 0x3b,
REG_FIFO_THRESH = 0x3c,
REG_PACKET_CONFIG_2 = 0x3d,
REG_AES_KEY_1 = 0x3e,
REG_AES_KEY_2 = 0x3f,
REG_AES_KEY_3 = 0x40,
REG_AES_KEY_4 = 0x41,
REG_AES_KEY_5 = 0x42,
REG_AES_KEY_6 = 0x43,
REG_AES_KEY_7 = 0x44,
REG_AES_KEY_8 = 0x45,
REG_AES_KEY_9 = 0x46,
REG_AES_KEY_11 = 0x47,
REG_AES_KEY_12 = 0x48,
REG_AES_KEY_13 = 0x4a,
REG_AES_KEY_14 = 0x4b,
REG_AES_KEY_15 = 0x4c,
REG_AES_KEY_16 = 0x4d,
REG_TEMP_1 = 0x4e,
REG_TEMP_2 = 0x4f,
REG_TEST_LNA = 0x58,
REG_TEST_PA_1 = 0x5a,
REG_TEST_PA_2 = 0x5c,
REG_TEST_DAGC = 0x6f,
REG_TEST_AFC = 0x71,
};
const uint8_t REG_WRITE = _BV(7);
/**
* For REG_OP_MODE
*/
class SEQUENCER : public Bitfield<7, 1>{};
const uint8_t SEQUENCER_ON = SEQUENCER::set(0);
const uint8_t SEQUENCER_OFF = SEQUENCER::set(1);
class LISTEN : public Bitfield<6, 1>{};
const uint8_t LISTEN_ON = LISTEN::set(1);
const uint8_t LISTEN_OFF = LISTEN::set(0);
const uint8_t LISTEN_ABORT = _BV(5);
class MODE : public Bitfield<2, 3>{};
const uint8_t MODE_SLEEP = MODE::set(0x00);
const uint8_t MODE_STDBY = MODE::set(0x01);
const uint8_t MODE_FS = MODE::set(0x02);
const uint8_t MODE_TX = MODE::set(0x03);
const uint8_t MODE_RX = MODE::set(0x04);
/**
* For REG_DATA_MODUL
*/
class DATA_MODE : public Bitfield<5, 2>{};
const uint8_t DATA_MODE_PACKET = DATA_MODE::set(0x00);
const uint8_t DATA_MODE_CONT_SYNC = DATA_MODE::set(0x02);
const uint8_t DATA_MODE_CONT_NO_SYNC = DATA_MODE::set(0x03);
class MOD_TYPE : public Bitfield<3, 2>{};
const uint8_t MOD_TYPE_FSK = MOD_TYPE::set(0x00);
const uint8_t MOD_TYPE_OOK = MOD_TYPE::set(0x01);
class MOD_SHAPE : public Bitfield<0, 2>{};
const uint8_t MOD_SHAPE_FSK_NONE = MOD_SHAPE::set(0x00);
const uint8_t MOD_SHAPE_FSK_GAUS_BT_10 = MOD_SHAPE::set(0x01);
const uint8_t MOD_SHAPE_FSK_GAUS_BT_05 = MOD_SHAPE::set(0x02);
const uint8_t MOD_SHAPE_FSK_GAUS_BT_03 = MOD_SHAPE::set(0x03);
const uint8_t MOD_SHAPE_OOK_NONE = MOD_SHAPE::set(0x00);
const uint8_t MOD_SHAPE_OOK_CUTOFF_BR = MOD_SHAPE::set(0x01);
const uint8_t MOD_SHAPE_OOK_CUTOFF_2BR = MOD_SHAPE::set(0x02);
/**
* For REG_OSC_1
*/
const uint8_t RC_CAL_START = _BV(7);
const uint8_t RC_CAL_DONE = _BV(6);
/**
* For REG_AFC_CTRL
*/
const uint8_t AFC_LOW_BETA_ON = _BV(5);
/**
* For REG_LISTEN_1
*/
class LISTEN_RESOL_IDLE : public Bitfield<6, 2>{};
const uint8_t LISTEN_RESOL_IDLE_64_US = LISTEN_RESOL_IDLE::set(0x01);
const uint8_t LISTEN_RESOL_IDLE_4100_US = LISTEN_RESOL_IDLE::set(0x02);
const uint8_t LISTEN_RESOL_IDLE_262000_US = LISTEN_RESOL_IDLE::set(0x03);
class LISTEN_RESOL_RX : public Bitfield<4, 2>{};
const uint8_t LISTEN_RESOL_RX_64_US = LISTEN_RESOL_RX::set(0x01);
const uint8_t LISTEN_RESOL_RX_4100_US = LISTEN_RESOL_RX::set(0x02);
const uint8_t LISTEN_RESOL_RX_262000_US = LISTEN_RESOL_RX::set(0x03);
class LISTEN_CRITERIA : public Bitfield<3, 1>{};
const uint8_t LISTEN_CRITERIA_RSSI = LISTEN_CRITERIA::set(0);
const uint8_t LISTEN_CRITERIA_RSSI_ADDR = LISTEN_CRITERIA::set(1);
class LISTEN_END : public Bitfield<0, 1>{};
const uint8_t LISTEN_END_TO_RX = LISTEN_END::set(0);
const uint8_t LISTEN_END_TO_MODE = LISTEN_END::set(0x01);
const uint8_t LISTEN_END_TO_IDLE = LISTEN_END::set(0x02);
/**
* For REG_PA_LEVEL
*/
class PA0_FIELD : public Bitfield<7, 1>{};
class PA1_FIELD : public Bitfield<6, 1>{};
class PA2_FIELD : public Bitfield<5, 1>{};
const uint8_t PA0_ON = _BV(7);
const uint8_t PA0_OFF = 0;
const uint8_t PA1_ON = _BV(6);
const uint8_t PA1_OFF = 0;
const uint8_t PA2_ON = _BV(5);
const uint8_t PA2_OFF = 0;
class OUTPUT_POWER : public Bitfield<0, 5>{};
/**
* For REG_PA_RAMP
*/
class PA_RAMP : public Bitfield<0, 4>{};
const uint8_t PA_RAMP_3400_US = PA_RAMP::set(0x00);
const uint8_t PA_RAMP_2000_US = PA_RAMP::set(0x01);
const uint8_t PA_RAMP_1000_US = PA_RAMP::set(0x02);
const uint8_t PA_RAMP_500_US = PA_RAMP::set(0x03);
const uint8_t PA_RAMP_250_US = PA_RAMP::set(0x04);
const uint8_t PA_RAMP_125_US = PA_RAMP::set(0x05);
const uint8_t PA_RAMP_100_US = PA_RAMP::set(0x06);
const uint8_t PA_RAMP_62_US = PA_RAMP::set(0x07);
const uint8_t PA_RAMP_50_US = PA_RAMP::set(0x08);
const uint8_t PA_RAMP_40_US = PA_RAMP::set(0x09);
const uint8_t PA_RAMP_31_US = PA_RAMP::set(0x0a);
const uint8_t PA_RAMP_25_US = PA_RAMP::set(0x0b);
const uint8_t PA_RAMP_20_US = PA_RAMP::set(0x0c);
const uint8_t PA_RAMP_15_US = PA_RAMP::set(0x0d);
const uint8_t PA_RAMP_12_US = PA_RAMP::set(0x0e);
const uint8_t PA_RAMP_10_US = PA_RAMP::set(0x0f);
/**
* For REG_OCP_ON
*/
class OCP : public Bitfield<4, 1>{};
const uint8_t OCP_ON = OCP::set(1);
const uint8_t OCP_OFF = OCP::set(0);
class OCP_TRIM : public Bitfield<0, 4>{};
/**
* For REG_LNA
*/
class LNA_ZIN : public Bitfield<7, 1>{};
const uint8_t LNA_ZIN_50_OHM = LNA_ZIN::set(0);
const uint8_t LNA_ZIN_200_OHM = LNA_ZIN::set(1);
class LNA_CURRENT_GAIN : public Bitfield<3, 3>{};
class LNA_GAIN_SELECT : public Bitfield<0, 3>{};
const uint8_t LNA_GAIN_AUTO = LNA_GAIN_SELECT::set(0x00);
const uint8_t LNA_GAIN_HIGH = LNA_GAIN_SELECT::set(0x01);
const uint8_t LNA_GAIN_MINUS_6 = LNA_GAIN_SELECT::set(0x02);
const uint8_t LNA_GAIN_MINUS_12 = LNA_GAIN_SELECT::set(0x03);
const uint8_t LNA_GAIN_MINUS_24 = LNA_GAIN_SELECT::set(0x04);
const uint8_t LNA_GAIN_MINUS_36 = LNA_GAIN_SELECT::set(0x05);
const uint8_t LNA_GAIN_MINUS_48 = LNA_GAIN_SELECT::set(0x06);
/**
* For REG_RX_BW
*/
class DCC_FREQ : public Bitfield<5, 3>{};
const uint8_t DCC_FREQ_16 = DCC_FREQ::set(0x00);
const uint8_t DCC_FREQ_8 = DCC_FREQ::set(0x01);
const uint8_t DCC_FREQ_4 = DCC_FREQ::set(0x02);
const uint8_t DCC_FREQ_2 = DCC_FREQ::set(0x03);
const uint8_t DCC_FREQ_1 = DCC_FREQ::set(0x04);
const uint8_t DCC_FREQ_0p5 = DCC_FREQ::set(0x05);
const uint8_t DCC_FREQ_0p25 = DCC_FREQ::set(0x06);
const uint8_t DCC_FREQ_0p125 = DCC_FREQ::set(0x07);
class RX_BW_MANT : public Bitfield<3, 2>{};
const uint8_t RX_BW_MANT_16 = RX_BW_MANT::set(0x00);
const uint8_t RX_BW_MANT_20 = RX_BW_MANT::set(0x01);
const uint8_t RX_BW_MANT_24 = RX_BW_MANT::set(0x02);
class RX_BW_EXP : public Bitfield<0, 3>{};
const uint8_t RX_BW_EXP_0 = RX_BW_EXP::set(0x00);
const uint8_t RX_BW_EXP_1 = RX_BW_EXP::set(0x01);
const uint8_t RX_BW_EXP_2 = RX_BW_EXP::set(0x02);
const uint8_t RX_BW_EXP_3 = RX_BW_EXP::set(0x03);
const uint8_t RX_BW_EXP_4 = RX_BW_EXP::set(0x04);
const uint8_t RX_BW_EXP_5 = RX_BW_EXP::set(0x05);
const uint8_t RX_BW_EXP_6 = RX_BW_EXP::set(0x06);
const uint8_t RX_BW_EXP_7 = RX_BW_EXP::set(0x07);
/**
* For REG_AFC_BW
*/
class DCC_FREQ_AFC : public Bitfield<5, 3>{};
class RX_BW_MANT_AFC : public Bitfield<3, 2>{};
class RX_BW_EXP_AFC : public Bitfield<0, 3>{};
/**
* For REG_AFC_FEI
*/
const uint8_t FEI_DONE = _BV(6);
const uint8_t FEI_START = _BV(5);
const uint8_t AFC_DONE = _BV(4);
class AFC_AUTOCLEAR : public Bitfield<3, 1>{};
const uint8_t AFC_AUTOCLEAR_ON = AFC_AUTOCLEAR::set(1);
const uint8_t AFC_AUTOCLEAR_OFF = AFC_AUTOCLEAR::set(0);
class AFC_AUTO : public Bitfield<2, 1>{};
const uint8_t AFC_AUTO_ON = AFC_AUTO::set(1);
const uint8_t AFC_AUTO_OFF = AFC_AUTO::set(0);
const uint8_t AFC_CLEAR = _BV(1);
const uint8_t AFC_START = _BV(0);
/**
* For REG_RSSI_CONFIG
*/
const uint8_t RSSI_DONE = _BV(1);
const uint8_t RSSI_START = _BV(0);
/**
* For REG_DIO_MAP_1
*/
class DIO0_MAPPING : public Bitfield<6, 2>{};
const uint8_t DIO0_CONT_ANY_MODE_READY = DIO0_MAPPING::set(0b11);
const uint8_t DIO0_CONT_FS_PLL_LOCK = DIO0_MAPPING::set(0b00);
const uint8_t DIO0_CONT_RX_SYNC_ADDRESS = DIO0_MAPPING::set(0b00);
const uint8_t DIO0_CONT_RX_TIMEOUT = DIO0_MAPPING::set(0b01);
const uint8_t DIO0_CONT_RX_RSSI = DIO0_MAPPING::set(0b10);
const uint8_t DIO0_CONT_TX_PLL_LOCK = DIO0_MAPPING::set(0b00);
const uint8_t DIO0_CONT_TX_TX_READY = DIO0_MAPPING::set(0b01);
const uint8_t DIO0_PKT_FS_PLL_LOCK = DIO0_MAPPING::set(0b11);
const uint8_t DIO0_PKT_RX_CRC_OK = DIO0_MAPPING::set(0b00);
const uint8_t DIO0_PKT_RX_PAYLOAD_READY = DIO0_MAPPING::set(0b01);
const uint8_t DIO0_PKT_RX_SYNC_ADDR = DIO0_MAPPING::set(0b10);
const uint8_t DIO0_PKT_RX_RSSI = DIO0_MAPPING::set(0b11);
const uint8_t DIO0_PKT_TX_PACKET_SENT = DIO0_MAPPING::set(0b00);
const uint8_t DIO0_PKT_TX_TX_READY = DIO0_MAPPING::set(0b01);
const uint8_t DIO0_PKT_TX_PLL_LOCK = DIO0_MAPPING::set(0b11);
class DIO1_MAPPING : public Bitfield<4, 2>{};
class DIO2_MAPPING : public Bitfield<2, 2>{};
class DIO3_MAPPING : public Bitfield<0, 2>{};
/**
* For REG_DIO_MAP_2
*/
class DIO4_MAPPING : public Bitfield<6, 2>{};
class DIO5_MAPPING : public Bitfield<4, 2>{};
class CLK_OUT : public Bitfield<0, 3>{};
const uint8_t CLK_OUT_F_XOSC = CLK_OUT::set(0x00);
const uint8_t CLK_OUT_F_XOSC_2 = CLK_OUT::set(0x01);
const uint8_t CLK_OUT_F_XOSC_4 = CLK_OUT::set(0x02);
const uint8_t CLK_OUT_F_XOSC_8 = CLK_OUT::set(0x03);
const uint8_t CLK_OUT_F_XOSC_16 = CLK_OUT::set(0x04);
const uint8_t CLK_OUT_F_XOSC_32 = CLK_OUT::set(0x05);
const uint8_t CLK_OUT_RC = CLK_OUT::set(0x06);
const uint8_t CLK_OUT_OFF = CLK_OUT::set(0x07);
/**
* For REG_IRQ_FLAGS_1
*/
const uint8_t IRQ_1_MODE_READY = _BV(7);
const uint8_t IRQ_1_RX_READY = _BV(6);
const uint8_t IRQ_1_TX_READY = _BV(5);
const uint8_t IRQ_1_PLL_LOCK = _BV(4);
const uint8_t IRQ_1_RSSI = _BV(3);
const uint8_t IRQ_1_TIMEOUT = _BV(2);
const uint8_t IRQ_1_AUTO_MODE = _BV(1);
const uint8_t IRQ_1_SYNC_ADDR_MATCH = _BV(0);
/**
* For REG_IRQ_FLAGS_2
*/
const uint8_t IRQ_2_FIFO_FULL = _BV(7);
const uint8_t IRQ_2_FIFO_NOT_EMPTY = _BV(6);
const uint8_t IRQ_2_FIFO_LEVEL = _BV(5);
const uint8_t IRQ_2_FIFO_OVERRUN = _BV(4);
const uint8_t IRQ_2_PACKET_SENT = _BV(3);
const uint8_t IRQ_2_PAYLOAD_READY = _BV(2);
const uint8_t IRQ_2_CRC_OK = _BV(1);
/**
* For REG_SYNC_CONFIG
*/
class SYNC : public Bitfield<7, 1>{};
const uint8_t SYNC_ON = SYNC::set(1);
const uint8_t SYNC_OFF = SYNC::set(0);
class FIFO_FILL : public Bitfield<6, 1>{};
const uint8_t FIFO_FILL_IF_SYNC_ADDR = FIFO_FILL::set(0);
const uint8_t FIFO_FILL_IF_FILL_COND = FIFO_FILL::set(1);
class SYNC_SIZE : public Bitfield<3, 3>{};
class SYNC_ERROR_TOL : public Bitfield<0, 3>{};
/**
* For REG_PACKET_CONFIG_1
*/
class PACKET_LENGTH : public Bitfield<7, 1>{};
const uint8_t PACKET_LENGTH_FIXED = PACKET_LENGTH::set(0);
const uint8_t PACKET_LENGTH_VARIABLE = PACKET_LENGTH::set(1);
class PACKET_DC_FREE : public Bitfield<5, 2>{};
const uint8_t PACKET_DC_FREE_NONE = PACKET_DC_FREE::set(0x00);
const uint8_t PACKET_DC_FREE_MANCHESTER = PACKET_DC_FREE::set(0x01);
const uint8_t PACKET_DC_FREE_WHITENING = PACKET_DC_FREE::set(0x02);
class PACKET_CRC : public Bitfield<4, 1>{};
const uint8_t PACKET_CRC_ON = PACKET_CRC::set(1);
const uint8_t PACKET_CRC_OFF = PACKET_CRC::set(0);
class PACKET_CRC_AUTO_CLEAR : public Bitfield<3, 1>{};
const uint8_t PACKET_CRC_AUTO_CLEAR_ON = PACKET_CRC_AUTO_CLEAR::set(0);
const uint8_t PACKET_CRC_AUTO_CLEAR_OFF = PACKET_CRC_AUTO_CLEAR::set(1);
class PACKET_ADDR_FILTER : public Bitfield<1, 2>{};
const uint8_t PACKET_ADDR_FILTER_OFF = PACKET_ADDR_FILTER::set(0x00);
const uint8_t PACKET_ADDR_FILTER_NODE = PACKET_ADDR_FILTER::set(0x01);
const uint8_t PACKET_ADDR_FILTER_NODE_BROADCAST = PACKET_ADDR_FILTER::set(0x02);
/**
* For REG_AUTO_MODES
*/
class ENTER_COND : public Bitfield<5, 3>{};
const uint8_t ENTER_COND_NONE = ENTER_COND::set(0x00);
const uint8_t ENTER_COND_FIFO_NOT_EMPTY = ENTER_COND::set(0x01);
const uint8_t ENTER_COND_FIFO_LEVEL = ENTER_COND::set(0x02);
const uint8_t ENTER_COND_CRC_OK = ENTER_COND::set(0x03);
const uint8_t ENTER_COND_PAYLOAD_READY = ENTER_COND::set(0x04);
const uint8_t ENTER_COND_SYNC_ADDRESS = ENTER_COND::set(0x05);
const uint8_t ENTER_COND_PACKET_SENT = ENTER_COND::set(0x06);
const uint8_t ENTER_COND_FIFO_EMPTY = ENTER_COND::set(0x07);
class EXIT_COND : public Bitfield<2, 3>{};
const uint8_t EXIT_COND_NONE = EXIT_COND::set(0x00);
const uint8_t EXIT_COND_FIFO_NOT_EMPTY = EXIT_COND::set(0x01);
const uint8_t EXIT_COND_FIFO_LEVEL = EXIT_COND::set(0x02);
const uint8_t EXIT_COND_CRC_OK = EXIT_COND::set(0x03);
const uint8_t EXIT_COND_PAYLOAD_READY = EXIT_COND::set(0x04);
const uint8_t EXIT_COND_SYNC_ADDRESS = EXIT_COND::set(0x05);
const uint8_t EXIT_COND_PACKET_SENT = EXIT_COND::set(0x06);
const uint8_t EXIT_COND_FIFO_EMPTY = EXIT_COND::set(0x07);
class INTER_MODE : public Bitfield<0, 2>{};
const uint8_t INTER_MODE_SLEEP = 0x00;
const uint8_t INTER_MODE_STDBY = 0x01;
const uint8_t INTER_MODE_RX = 0x02;
const uint8_t INTER_MODE_TX = 0x03;
/**
* For REG_FIFO_THRESH
*/
const uint8_t TX_START_COND_FIFO_LEVEL = 0;
const uint8_t TX_START_COND_FIFO_NOT_EMPTY = _BV(7);
class FIFO_THRESH : public Bitfield<0, 7>{};
/**
* For REG_PACKET_CONFIG_2
*/
class INTER_PACKET_RX_DELAY : public Bitfield<4, 4>{};
const uint8_t RESTART_RX = _BV(2);
class AUTO_RESTART_RX : public Bitfield<1, 1>{};
const uint8_t AUTO_RX_RESTART_ON = _BV(1);
const uint8_t AUTO_RX_RESTART_OFF = 0;
class AES : public Bitfield<0, 1>{};
const uint8_t AES_ON = _BV(0);
const uint8_t AES_OFF = 0;
}
}
#endif
| [
"srfilipek@gmail.com"
] | srfilipek@gmail.com |
350b07954d3c0977fe4cabda40da3f64602f0601 | e60c7658cd254538ecaed0d7a803ee58460c8f9b | /3scan-scope-master aux1.56/auxbox/BallValve.cpp | 3dd3beb375178402fb796fdb501c79056c8550d6 | [] | no_license | skolk/AUX | 0915866108ddd905a4f57acba054b49ef3ffb25c | 3e9ee60270c05f1459a0f54183e003dd93eb3140 | refs/heads/master | 2016-09-06T09:10:07.002305 | 2016-01-13T15:50:39 | 2016-01-13T15:50:39 | 30,661,533 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 925 | cpp | #include "BallValve.h"
BallValve::BallValve(uint8_t pinOpen, uint8_t pinClose) {
_pinOpen = pinOpen;
_pinClose = pinClose;
pinMode(_pinOpen, OUTPUT);
pinMode(_pinClose, OUTPUT);
// On startup, we don't know what the state of the system is.
// We won't know until we call either open() or close().
_hasBeenSet = false;
_isOpen = false;
}
void BallValve::open() {
digitalWrite(_pinOpen, LOW);
digitalWrite(_pinClose, HIGH);
_hasBeenSet = true;
_isOpen = true;
}
void BallValve::close() {
digitalWrite(_pinOpen, HIGH);
digitalWrite(_pinClose, LOW);
_hasBeenSet = true;
_isOpen = false;
}
void BallValve::setState(boolean _open) {
if (_open) {
open();
} else {
close();
}
}
void BallValve::hold() {
digitalWrite(_pinOpen, HIGH);
digitalWrite(_pinClose, HIGH);
}
boolean BallValve::isOpen() {
return _isOpen;
}
boolean BallValve::hasBeenSet() {
return _hasBeenSet;
} | [
"sean.kolk@gmail.com"
] | sean.kolk@gmail.com |
ddaf2cb7b649a003d371f109e0da829a4fc5d2ce | 0e457eda72fe89e8690396734fbf12b5cea94e98 | /DONE/CF 1181G.cpp | 12a854d74c6a3706030c4e3f681079a72126cd34 | [] | no_license | Li-Dicker/OI-Workspace | 755f12b0383a41bfb92572b843e99ae27401891c | 92e1385a7cffd465e8d01d03424307ac2767b200 | refs/heads/master | 2023-01-23T05:55:53.510072 | 2020-12-12T08:33:50 | 2020-12-12T08:33:50 | 305,936,883 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 214 | cpp | #include<bits/stdc++.h>
#define int long long
#define M (1<<20)
#define INF 0x3f3f3f3f
using namespace std;
int T,n;
signed main()
{
scanf("%lld %lld",&n,&T);
for (int i=1;i<=n;i++)
return 0;
} | [
"Li_Dicker@qq.com"
] | Li_Dicker@qq.com |
3c121af99a4456b0a0c7a0589b6c145c89210a26 | 0651168677127e9c4ccbe185dc865227144bc825 | /src/node_request.cpp | 415d27d82e73cc443a4ca10d34b451ffc16e8044 | [] | no_license | ezhangle/node-mapbox-gl-native | 9f5904d8755d29bc54bd02f4a34d4625c5b661ac | ffc937b18476304a4833ba6728a94c5f6f178973 | refs/heads/master | 2021-01-17T04:23:39.769651 | 2015-03-15T03:25:46 | 2015-03-15T03:25:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,891 | cpp | #include "node_request.hpp"
#include "node_file_source.hpp"
#include <mbgl/storage/default/request.hpp>
#include <mbgl/storage/response.hpp>
#include <cmath>
namespace node_mbgl {
////////////////////////////////////////////////////////////////////////////////////////////////
// Static Node Methods
v8::Persistent<v8::FunctionTemplate> NodeRequest::constructorTemplate;
void NodeRequest::Init(v8::Handle<v8::Object> target) {
NanScope();
v8::Local<v8::FunctionTemplate> t = NanNew<v8::FunctionTemplate>(New);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(NanNew("Request"));
NODE_SET_PROTOTYPE_METHOD(t, "respond", Respond);
NanAssignPersistent(constructorTemplate, t);
target->Set(NanNew("Request"), t->GetFunction());
}
NAN_METHOD(NodeRequest::New) {
NanScope();
// Extract the pointer from the first argument
if (args.Length() < 2 || !NanHasInstance(NodeFileSource::constructorTemplate, args[0]) || !args[1]->IsExternal()) {
return NanThrowTypeError("Cannot create Request objects explicitly");
}
auto source = v8::Persistent<v8::Object>::New(args[0]->ToObject());
auto request = reinterpret_cast<mbgl::Request *>(args[1].As<v8::External>()->Value());
auto req = new NodeRequest(source, request);
req->Wrap(args.This());
NanReturnValue(args.This());
}
v8::Handle<v8::Object> NodeRequest::Create(v8::Handle<v8::Object> source, mbgl::Request *request) {
NanScope();
v8::Local<v8::Value> argv[] = { v8::Local<v8::Object>::New(source), NanNew<v8::External>(request) };
auto instance = constructorTemplate->GetFunction()->NewInstance(2, argv);
instance->Set(NanNew("url"), NanNew(request->resource.url), v8::ReadOnly);
instance->Set(NanNew("kind"), NanNew<v8::Integer>(int(request->resource.kind)), v8::ReadOnly);
NanReturnValue(instance);
}
NAN_METHOD(NodeRequest::Respond) {
NanScope();
auto nodeRequest = ObjectWrap::Unwrap<NodeRequest>(args.Holder());
if (!nodeRequest->request) {
return NanThrowError("Request has already been responded to, or was canceled.");
}
auto source = ObjectWrap::Unwrap<NodeFileSource>(nodeRequest->source);
auto request = nodeRequest->request;
nodeRequest->request = nullptr;
if (args.Length() < 1) {
return NanThrowTypeError("First argument must be an error object");
} else if (args[0]->BooleanValue()) {
auto response = std::make_shared<mbgl::Response>();
response->status = mbgl::Response::Error;
// Store the error string.
const NanUtf8String message { args[0]->ToString() };
response->message = std::string { *message, size_t(message.length()) };
source->notify(request, response);
} else if (args.Length() < 2 || !args[1]->IsObject()) {
return NanThrowTypeError("Second argument must be a response object");
} else {
auto response = std::make_shared<mbgl::Response>();
auto res = args[1]->ToObject();
response->status = mbgl::Response::Successful;
if (res->Has(NanNew("modified"))) {
const double modified = res->Get(NanNew("modified"))->ToNumber()->Value();
if (!std::isnan(modified)) {
response->modified = modified / 1000; // JS timestamps are milliseconds
}
}
if (res->Has(NanNew("expires"))) {
const double expires = res->Get(NanNew("expires"))->ToNumber()->Value();
if (!std::isnan(expires)) {
response->expires = expires / 1000; // JS timestamps are milliseconds
}
}
if (res->Has(NanNew("etag"))) {
auto etagHandle = res->Get(NanNew("etag"));
if (etagHandle->BooleanValue()) {
const NanUtf8String etag { etagHandle->ToString() };
response->etag = std::string { *etag, size_t(etag.length()) };
}
}
if (res->Has(NanNew("data"))) {
auto dataHandle = res->Get(NanNew("data"));
if (node::Buffer::HasInstance(dataHandle)) {
response->data = std::string {
node::Buffer::Data(dataHandle),
node::Buffer::Length(dataHandle)
};
} else {
return NanThrowTypeError("Response data must be a Buffer");
}
}
// Send the response object to the NodeFileSource object
source->notify(request, response);
}
NanReturnUndefined();
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Instance
NodeRequest::NodeRequest(v8::Persistent<v8::Object> source_, mbgl::Request *request_)
: source(source_), request(request_) {
}
NodeRequest::~NodeRequest() {
source.Dispose();
}
void NodeRequest::cancel() {
request = nullptr;
}
}
| [
"mail@kkaefer.com"
] | mail@kkaefer.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.