blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
3a86799a3e0782931286816d9da01b7c588c3677
efb1e3bd4f1bf79f5c2bc90a34bb33bf171f5f43
/drake/automotive/maliput/monolane/test/monolane_road_geometry_test.cc
162973bb150efbf98749c70507851cf80855f1a6
[ "BSD-3-Clause" ]
permissive
martiwer/drake
dab2278d41fc4197ccc13a518c4327caa57040b1
709171b00b92e79557920329346f5500718a2caf
refs/heads/master
2021-05-16T09:44:48.965884
2017-09-22T01:25:43
2017-09-22T01:25:43
104,477,877
6
1
null
null
null
null
UTF-8
C++
false
false
10,249
cc
monolane_road_geometry_test.cc
/* clang-format off to disable clang-format-includes */ #include "drake/automotive/maliput/monolane/road_geometry.h" /* clang-format on */ #include <cmath> #include <gtest/gtest.h> #include "drake/automotive/maliput/api/test/maliput_types_compare.h" #include "drake/automotive/maliput/monolane/builder.h" namespace drake { namespace maliput { namespace monolane { using api::RBounds; using api::HBounds; using monolane::ArcOffset; const double kVeryExact = 1e-11; const double kWidth{2.}; // Lane and drivable width. const double kHeight{5.}; // Elevation bound. const api::Lane* GetLaneByJunctionId(const api::RoadGeometry& rg, const std::string& junction_id) { for (int i = 0; i < rg.num_junctions(); ++i) { if (rg.junction(i)->id() == api::JunctionId(junction_id)) { return rg.junction(i)->segment(0)->lane(0); } } throw std::runtime_error("No matching junction name in the road network"); } GTEST_TEST(MonolaneLanesTest, DoToRoadPosition) { // Define a serpentine road with multiple segments and branches. std::unique_ptr<monolane::Builder> rb( new monolane::Builder(RBounds(-kWidth, kWidth), RBounds(-kWidth, kWidth), HBounds(0., kHeight), 0.01, /* linear tolerance */ 0.01 * M_PI /* angular tolerance */)); // Initialize the road from the origin. const monolane::EndpointXy kOriginXy{0., 0., 0.}; const monolane::EndpointZ kFlatZ{0., 0., 0., 0.}; const monolane::Endpoint kRoadOrigin{kOriginXy, kFlatZ}; // Define the lanes and connections. const double kArcDeltaTheta{M_PI / 2.}; const double kArcRadius{50.}; const double kLength{50.}; const auto& lane0 = rb->Connect( "lane0", kRoadOrigin, ArcOffset(kArcRadius, -kArcDeltaTheta), kFlatZ); const auto& lane1 = rb->Connect("lane1", lane0->end(), kLength, kFlatZ); const auto& lane2 = rb->Connect( "lane2", lane1->end(), ArcOffset(kArcRadius, kArcDeltaTheta), kFlatZ); rb->Connect("lane3a", lane2->end(), kLength, kFlatZ); rb->Connect("lane3b", lane2->end(), ArcOffset(kArcRadius, kArcDeltaTheta), kFlatZ); rb->Connect("lane3c", lane2->end(), ArcOffset(kArcRadius, -kArcDeltaTheta), kFlatZ); std::unique_ptr<const api::RoadGeometry> rg = rb->Build(api::RoadGeometryId{"multi_lane_with_branches"}); // Place a point at the middle of lane1. api::GeoPosition geo_pos{kArcRadius, -kArcRadius - kLength / 2., 0.}; api::GeoPosition nearest_position{}; double distance; api::RoadPosition actual_position = rg->ToRoadPosition(geo_pos, nullptr, &nearest_position, &distance); // Expect to locate the point centered within lane1 (straight segment). EXPECT_TRUE(api::test::IsLanePositionClose( actual_position.pos, api::LanePosition(kLength / 2. /* s */, 0. /* r */, 0. /* h */), kVeryExact)); EXPECT_EQ(actual_position.lane->id(), api::LaneId("l:lane1")); EXPECT_EQ(distance, 0.); EXPECT_TRUE(api::test::IsGeoPositionClose( nearest_position, api::GeoPosition(geo_pos.x(), geo_pos.y(), geo_pos.z()), kVeryExact)); // Tests the integrity of ToRoadPosition() with various other null argument // combinations for the case where the point is within a lane. EXPECT_NO_THROW( rg->ToRoadPosition(geo_pos, nullptr, &nearest_position, nullptr)); EXPECT_NO_THROW(rg->ToRoadPosition(geo_pos, nullptr, nullptr, &distance)); EXPECT_NO_THROW(rg->ToRoadPosition(geo_pos, nullptr, nullptr, nullptr)); // Place a point halfway to the end of lane1, just to the outside (left side) // of the lane bounds. geo_pos = api::GeoPosition(kArcRadius + 2. * kWidth, -kArcRadius - kLength / 2., 0.); actual_position = rg->ToRoadPosition(geo_pos, nullptr, &nearest_position, &distance); // Expect to locate the point just outside (to the left) of lane1, by an // amount kWidth. EXPECT_TRUE(api::test::IsLanePositionClose( actual_position.pos, api::LanePosition(kLength / 2. /* s */, kWidth /* r */, 0. /* h */), kVeryExact)); EXPECT_EQ(actual_position.lane->id(), api::LaneId("l:lane1")); EXPECT_EQ(distance, kWidth); EXPECT_TRUE(api::test::IsGeoPositionClose( nearest_position, api::GeoPosition(geo_pos.x() - kWidth, geo_pos.y(), geo_pos.z()), kVeryExact)); // Tests the integrity of ToRoadPosition() with various other null argument // combinations for the case where the point is outside all lanes. EXPECT_NO_THROW( rg->ToRoadPosition(geo_pos, nullptr, &nearest_position, nullptr)); EXPECT_NO_THROW(rg->ToRoadPosition(geo_pos, nullptr, nullptr, &distance)); EXPECT_NO_THROW(rg->ToRoadPosition(geo_pos, nullptr, nullptr, nullptr)); // Place a point at the middle of lane3a (straight segment). geo_pos = api::GeoPosition(2. * kArcRadius + kLength / 2., -2. * kArcRadius - kLength, 0.); actual_position = rg->ToRoadPosition(geo_pos, nullptr, &nearest_position, &distance); // Expect to locate the point centered within lane3a. EXPECT_TRUE(api::test::IsLanePositionClose( actual_position.pos, api::LanePosition(kLength / 2. /* s */, 0. /* r */, 0. /* h */), kVeryExact)); EXPECT_EQ(actual_position.lane->id(), api::LaneId("l:lane3a")); EXPECT_EQ(distance, 0.); EXPECT_TRUE(api::test::IsGeoPositionClose( nearest_position, api::GeoPosition(geo_pos.x(), geo_pos.y(), geo_pos.z()), kVeryExact)); // Place a point high above the middle of lane3a (straight segment). geo_pos = api::GeoPosition(2. * kArcRadius + kLength / 2., -2. * kArcRadius - kLength, 50.); actual_position = rg->ToRoadPosition(geo_pos, nullptr, &nearest_position, &distance); // Expect to locate the point centered above lane3a. EXPECT_TRUE(api::test::IsLanePositionClose( actual_position.pos, api::LanePosition(kLength / 2. /* s */, 0. /* r */, kHeight /* h */), kVeryExact)); EXPECT_EQ(actual_position.lane->id(), api::LaneId("l:lane3a")); EXPECT_EQ(distance, 50. - kHeight); EXPECT_TRUE(api::test::IsGeoPositionClose( nearest_position, api::GeoPosition(geo_pos.x(), geo_pos.y(), kHeight), kVeryExact)); // Place a point at the end of lane3b (arc segment). geo_pos = api::GeoPosition(2. * kArcRadius + kLength, -kArcRadius - kLength, 0.); actual_position = rg->ToRoadPosition(geo_pos, nullptr, &nearest_position, &distance); // Expect to locate the point at the end of lane3b. EXPECT_TRUE(api::test::IsLanePositionClose( actual_position.pos, api::LanePosition(kArcRadius * M_PI / 2. /* s */, 0. /* r */, 0. /* h */), kVeryExact)); EXPECT_EQ(actual_position.lane->id(), api::LaneId("l:lane3b")); EXPECT_EQ(distance, 0.); EXPECT_TRUE(api::test::IsGeoPositionClose( nearest_position, api::GeoPosition(geo_pos.x(), geo_pos.y(), geo_pos.z()), kVeryExact)); // Supply a hint with a position at the start of lane3c to try and determine // the RoadPosition for a point at the end of lane3b. api::RoadPosition hint{GetLaneByJunctionId(*rg, "j:lane3c"), {0., 0., 0.}}; actual_position = rg->ToRoadPosition(geo_pos, &hint, &nearest_position, &distance); // Expect to locate the point outside of lanes lane3c (and ongoing adjacent // lanes), since lane3b is not ongoing from lane3c. EXPECT_EQ(actual_position.lane->id(), api::LaneId("l:lane3c")); EXPECT_GT(distance, 0.); // geo_pos is not within this lane. // Supply a hint with a position at the start of lane2 to try and determine // the RoadPosition for a point at the end of lane3b. hint = api::RoadPosition{GetLaneByJunctionId(*rg, "j:lane2"), {0., 0., 0.}}; actual_position = rg->ToRoadPosition(geo_pos, &hint, &nearest_position, &distance); // Expect to traverse to lane3b (an ongoing lane) and then locate the point // within lane lane3b. EXPECT_EQ(actual_position.lane->id(), api::LaneId("l:lane3b")); EXPECT_EQ(distance, 0.); // geo_pos is inside lane3b. EXPECT_TRUE(api::test::IsGeoPositionClose( nearest_position, api::GeoPosition(geo_pos.x(), geo_pos.y(), geo_pos.z()), kVeryExact)); } GTEST_TEST(MonolaneLanesTest, HintWithDisconnectedLanes) { // Define a road with two disconnected, diverging lanes such that there are no // ongoing lanes. This tests the pathological case when a `hint` is provided // in a topologically isolated lane, so the code returns the default road // position given by the hint. std::unique_ptr<monolane::Builder> rb( new monolane::Builder(RBounds(-kWidth, kWidth), RBounds(-kWidth, kWidth), HBounds(0., kHeight), 0.01, /* linear tolerance */ 0.01 * M_PI /* angular tolerance */)); // Initialize the road from the origin. const monolane::EndpointXy kOriginXy0{0., 0., 0.}; const monolane::EndpointXy kOriginXy1{0., 100., 0.}; const monolane::EndpointZ kFlatZ{0., 0., 0., 0.}; const monolane::Endpoint kRoadOrigin0{kOriginXy0, kFlatZ}; const monolane::Endpoint kRoadOrigin1{kOriginXy1, kFlatZ}; // Define the lanes and connections. rb->Connect("lane0", kRoadOrigin0, ArcOffset(50., -M_PI / 2.), kFlatZ); rb->Connect("lane1", kRoadOrigin1, ArcOffset(50., M_PI / 2.), kFlatZ); std::unique_ptr<const api::RoadGeometry> rg = rb->Build(api::RoadGeometryId{"disconnected_lanes"}); // Place a point at the middle of lane0. api::GeoPosition geo_pos{50. * std::sqrt(2.) / 2., -50. * std::sqrt(2.) / 2., 0.}; // Supply a hint with a position at the start of lane1. double distance; api::RoadPosition hint = api::RoadPosition{GetLaneByJunctionId(*rg, "j:lane1"), {0., 0., 0.}}; api::RoadPosition actual_position{}; EXPECT_NO_THROW(actual_position = rg->ToRoadPosition(geo_pos, &hint, nullptr, &distance)); // The search is confined to lane1. EXPECT_EQ(actual_position.lane->id(), api::LaneId("l:lane1")); // lane1 does not contain the point. EXPECT_GT(distance, 0.); } } // namespace monolane } // namespace maliput } // namespace drake
9a6d589cc1132020f181f3e085bddffdc1f3f700
22eb20dfa5bf05630d398829e72d971f7fad38ac
/myValueControl/myphotoview.cpp
547b3f125846ddcf3723f36a02563f6c123ffa94
[]
no_license
zhoajianjun/QT
634e984f365679e21047f59817ee5f46ca9d25c9
32e9362b088ffb150fe2fda036d8472edb4a1346
refs/heads/master
2016-09-12T21:05:12.316379
2016-04-25T06:40:06
2016-04-25T06:40:06
56,022,827
3
0
null
null
null
null
UTF-8
C++
false
false
8,013
cpp
myphotoview.cpp
#include "myphotoview.h" PYNum::PYNum(QWidget* parent):QWidget(parent) { m_opacity = 0.0; setWindowOpacity(PYN_FIN_OPACITY); m_fadeTimer = new QTimer(this); m_fadeTimer->setInterval(PYN_TIMER_INTERVAL); connect(m_fadeTimer,SIGNAL(timeout()),this,SLOT(DoFading())); m_hideTimer = new QTimer(this); m_hideTimer->setInterval(PYN_TIMER_INTERVAL); connect(m_hideTimer,SIGNAL(timeout()),this,SLOT(DoHiding())); m_holdTimer = new QTimer(this); m_holdTimer->setInterval(PYN_HOLD_DURATION); m_holdTimer->setSingleShot(true); connect(m_holdTimer,SIGNAL(timeout()),m_hideTimer,SLOT(start())); m_nTotal = 0; m_nValue = 0; setFixedHeight(PYN_MAX_HEIGHT); setWindowFlags(Qt::FramelessWindowHint); setAttribute(Qt::WA_TranslucentBackground); } void PYNum::paintEvent(QPaintEvent *) { QPainter painter(this); painter.setRenderHints(QPainter::Antialiasing|QPainter::HighQualityAntialiasing); drawBg(&painter); drawText(&painter); } void PYNum::drawBg(QPainter *painter) { painter->save(); painter->setPen(Qt::NoPen); QLinearGradient BgGradient(QPoint(0,0),QPoint(0,height())); BgGradient.setColorAt(0.0,PYN_BG_START_COLOR); BgGradient.setColorAt(1.0,PYN_BG_END_COLOR); painter->setBrush(BgGradient); painter->drawRoundedRect(rect(),PYN_RECT_RADIUS,PYN_RECT_RADIUS); painter->restore(); } void PYNum::drawText(QPainter *painter) { painter->save(); QString strText ; strText = tr("%1/%2").arg(m_nValue).arg(m_nTotal); qreal TextLength = fontMetrics().width(strText); qreal ThisWidth = TextLength * PYN_WIDTH_FACTOR; painter->setPen(PYN_TEXT_COLOR); QFont TextFont; TextFont.setBold(true); painter->setFont(TextFont); painter->drawText(rect(),strText,Qt::AlignVCenter|Qt::AlignHCenter); setFixedWidth(ThisWidth); painter->restore(); } void PYNum::showEvent(QShowEvent *) { m_opacity = 0.0; setWindowOpacity(m_opacity); m_fadeTimer->start(); } void PYNum::DoFading() { m_opacity += PYN_OPACITY_INCREMENT; if(m_opacity > PYN_FIN_OPACITY) { m_opacity = PYN_FIN_OPACITY; m_fadeTimer->stop(); m_holdTimer->start(); } setWindowOpacity(m_opacity); } void PYNum::DoHiding() { m_opacity -= PYN_OPACITY_INCREMENT; if(m_opacity < 0.0) { m_opacity = 0.0; m_hideTimer->stop(); } setWindowOpacity(m_opacity); } void PYNum::setTotal(int totalNum) { m_nTotal = totalNum; update(); } void PYNum::setValue(int value) { m_nValue = value; update(); } myPhotoView::myPhotoView(QWidget *parent) : QWidget(parent) { this->initVariables(); } void myPhotoView::initVariables() { m_currImage = 0; m_nTotal = 0; m_nCurrIndex = 0; num = new PYNum(this); connect(this,SIGNAL(sig_setTotal(int)),num,SLOT(setTotal(int))); connect(this,SIGNAL(sig_setValue(int)),num,SLOT(setValue(int))); prevButton = new QToolButton(this); nextButton = new QToolButton(this); prevButton->setIcon(QIcon(":/images/prev.png")); nextButton->setIcon(QIcon(":/images/next.png")); prevButton->setIconSize(PYP_BUTTON_SIZE); nextButton->setIconSize(PYP_BUTTON_SIZE); prevButton->setFixedSize(PYP_BUTTON_SIZE); nextButton->setFixedSize(PYP_BUTTON_SIZE); prevButton->setAutoRaise(true); nextButton->setAutoRaise(true); connect(prevButton,SIGNAL(clicked()),this,SLOT(showPrevious())); connect(nextButton,SIGNAL(clicked()),this,SLOT(showNext())); calcGeo(); #ifdef PYP_IMAGE_FADE_TIMER_INTERVAL m_imageOpacity = 0.0; m_imageFadeTimer = new QTimer(this); m_imageFadeTimer->setInterval(PYP_IMAGE_FADE_TIMER_INTERVAL); connect(m_imageFadeTimer,SIGNAL(timeout()),this,SLOT(DoImageFading())); #endif } void myPhotoView::calcGeo() { /// RESIZE AND MOVE PREVBUTTON QPoint PrevMovePot(PYP_LEFT_SPACE,height() - PYP_TOP_SPACE - PYP_BUTTON_SIZE.height()); prevButton->move(PrevMovePot); prevButton->show(); /// RESIZE AND MOVE NEXTBUTTON QPoint NextMovePot(width() - PYP_LEFT_SPACE - PYP_BUTTON_SIZE.width(),height() - PYP_TOP_SPACE -PYP_BUTTON_SIZE.height()); nextButton->move(NextMovePot); nextButton->show(); /// RESIZE AND MOVE NUM qreal NumX = (qreal)width()/2 - (qreal)num->width()/2; qreal NumY = height() - PYP_TOP_SPACE - PYP_BUTTON_SIZE.height()/2 - num->height()/2; QPointF NumMovePot(NumX,NumY); num->move(NumMovePot.toPoint()); } void myPhotoView::paintEvent(QPaintEvent *) { QPainter painter(this); painter.setRenderHints(QPainter::Antialiasing|QPainter::HighQualityAntialiasing|QPainter::SmoothPixmapTransform); drawBg(&painter); drawImage(&painter); } void myPhotoView::showEvent(QShowEvent *) { calcGeo(); } void myPhotoView::resizeEvent(QResizeEvent *) { calcGeo(); } void myPhotoView::drawBg(QPainter *painter) { painter->save(); painter->setPen(Qt::NoPen); QLinearGradient BgGradient(QPoint(0,0),QPoint(0,height())); BgGradient.setColorAt(0.0,PYP_BG_START_COLOR); BgGradient.setColorAt(1.0,PYP_BG_END_COLOR); painter->setBrush(BgGradient); painter->drawRect(rect()); painter->restore(); } void myPhotoView::drawImage(QPainter *painter) { painter->save(); #ifdef PYP_IMAGE_MOTION_PATTERN_FADE painter->setOpacity(m_imageOpacity); qreal imageWidth = m_currImage->width(); qreal imageHeight = m_currImage->height(); qreal ImageX = rect().center().x() - imageWidth/2; qreal ImageY = rect().center().y() - imageHeight/2; QPointF ImagePot(ImageX,ImageY); painter->drawImage(ImagePot,*m_currImage); #endif painter->restore(); } #ifdef PYP_IMAGE_FADE_TIMER_INTERVAL void myPhotoView::DoImageFading() { m_imageOpacity += PYP_IMAGE_OPACITY_INCREMENT; if(m_imageOpacity > 1.0) { m_imageOpacity = 1.0; m_imageFadeTimer->stop(); } update(); } #endif void myPhotoView::load(const QString &strFolder) { m_strFolder = strFolder; QDir imageFolder(strFolder); if (imageFolder.exists()) { QStringList ImageList = imageFolder.entryList(PYP_IMAGE_SUFFIX); if (ImageList.count()>0) { QString strFullPath ; m_ImageVec.clear(); foreach(const QString strImage,ImageList) { strFullPath = tr("%1/%2").arg(strFolder).arg(strImage); QImage* img = new QImage(strFullPath); m_ImageVec.push_back(img); } if(m_ImageVec.size() > 0) { m_currImage = m_ImageVec.at(0); m_nCurrIndex = 0; } emit sig_setTotal(ImageList.count()); #ifdef PYP_IMAGE_MOTION_PATTERN_FADE m_imageFadeTimer->start(); #endif } } } void myPhotoView::showNext() { if(m_ImageVec.isEmpty()) { return ; } m_nCurrIndex++; if(m_nCurrIndex >= m_ImageVec.count()) { m_nCurrIndex = m_ImageVec.count() -1; } m_currImage = m_ImageVec.at(m_nCurrIndex); #ifdef PYP_IMAGE_MOTION_PATTERN_FADE m_imageOpacity = 0.0; m_imageFadeTimer->start(); #endif emit sig_setValue(m_nCurrIndex + 1); calcGeo(); } void myPhotoView::showPrevious() { if(m_ImageVec.isEmpty()) { return ; } m_nCurrIndex--; if(m_nCurrIndex < 0) { m_nCurrIndex = 0; } m_currImage = m_ImageVec.at(m_nCurrIndex); #ifdef PYP_IMAGE_MOTION_PATTERN_FADE m_imageOpacity = 0.0; m_imageFadeTimer->start(); #endif emit sig_setValue(m_nCurrIndex + 1); calcGeo(); }
55eab91165063bc1135ed9bafe61b6b3b878f0cd
fb2d3702450ae18d2d5e2796e8f22f5dff60b4f2
/engine/Fury/Matrix4.h
23eec3b9f2bf5b71a33bb40f35b58989a0ac78fc
[ "MIT" ]
permissive
fireword/fury3d
d15b56be504bc441372b207deb2457279f99e27f
a280c276e59fa758b269ca605a95aee5f3ed78c9
refs/heads/master
2021-01-13T07:39:40.584122
2016-10-11T13:39:15
2016-10-11T13:39:15
71,447,923
1
0
null
2016-10-20T09:40:19
2016-10-20T09:40:18
null
UTF-8
C++
false
false
1,968
h
Matrix4.h
#ifndef _FURY_MATRIX4_H_ #define _FURY_MATRIX4_H_ #include <string> #include <initializer_list> #include "Macros.h" namespace fury { class BoxBounds; class Quaternion; class Vector4; class Plane; /** * Matrix stores position info in Raw[12, 13, 14] like opengl. * 0 4 8 12 * 1 5 9 13 * 2 6 10 14 * 3 7 11 15 */ class FURY_API Matrix4 { public: static std::string PROJECTION_MATRIX; static std::string INVERT_VIEW_MATRIX; static std::string WORLD_MATRIX; float Raw[16]; Matrix4(); Matrix4(const float raw[]); Matrix4(std::initializer_list<float> raw); Matrix4(const Matrix4 &other); void Identity(); void Translate(Vector4 position); void AppendTranslation(Vector4 position); void PrependTranslation(Vector4 position); void Rotate(Quaternion rotation); void AppendRotation(Quaternion rotation); void PrependRotation(Quaternion rotation); void Scale(Vector4 scale); void AppendScale(Vector4 scale); void PrependScale(Vector4 scale); void PerspectiveFov(float fov, float ratio, float near, float far); void PerspectiveOffCenter(float left, float right, float bottom, float top, float near, float far); void OrthoOffCenter(float left, float right, float bottom, float top, float near, float far); void LookAt(Vector4 eye, Vector4 at, Vector4 up); Matrix4 Transpose() const; Vector4 Multiply(Vector4 data) const; Quaternion Multiply(Quaternion data) const; BoxBounds Multiply(const BoxBounds &data) const; Plane Multiply(const Plane &data) const; // No projection term Matrix4 Inverse() const; Matrix4 Clone() const; bool operator == (const Matrix4 &other) const; bool operator != (const Matrix4 &other) const; Matrix4 &operator = (const Matrix4 &other); Matrix4 operator * (const Matrix4 &other) const; }; } #endif // _FURY_MATRIX4_H_
e2b9fa46eeec22f7763b7cebee9043c2cac39829
0d8d848ee3bdf343dcc5da6d2b361cf595f5e4b5
/game/game/BackInvis.cpp
e991d50928b6df13da46409eb7aa623d37444091
[]
no_license
HanL-XX/Mario-bros-3
8b0074367c91821daec34e27b73b89ab6def4491
930b9d63df9f380730e084892de1b5eb3e5f17e0
refs/heads/master
2023-01-23T20:32:53.136243
2020-12-06T16:41:46
2020-12-06T16:41:46
303,575,250
0
0
null
null
null
null
UTF-8
C++
false
false
189
cpp
BackInvis.cpp
#include "BackInvis.h" void CBackInvis::Render() { animation_set->at(0)->Render(x, y); RenderBoundingBox(); } void CBackInvis::GetBoundingBox(float& l, float& t, float& r, float& b) { }
41b3f6c41b01c34b8381af81f58d4b7090db6457
221e5bf40534fcf3f661f4de3669e4fafd1fd788
/MOBJFile.cpp
04b357e695e07224f193b59d22fbcf1a5ef592fd
[]
no_license
BlueSpud/Spud-Model-Converter
9dda57770098ff25ab172e3b498f0b647cab686f
3768b7c64a12ec890353167ebba9e7bb411c93d7
refs/heads/master
2021-01-09T06:01:13.740165
2017-02-25T16:13:46
2017-02-25T16:13:46
80,876,168
0
0
null
null
null
null
UTF-8
C++
false
false
5,031
cpp
MOBJFile.cpp
#include "MOBJFile.h" /****************************************************************************** * Function for loading * ******************************************************************************/ void MOBJFile::loadFile(const QString& path) { std::ifstream in_file_stream(path.toStdString()); std::string line; std::vector<glm::vec3>_positions; std::vector<glm::vec3>_normals; std::vector<glm::vec2>_tex_coords; vertices = std::map<size_t, MVertex>(); // Storage and required objects for indicy parsing std::map<std::string, std::vector<std::string>> indices_map; // Create something if no materials were included indices_map["Generated_Material_0"] = std::vector<std::string>(); std::string current_material = "Generated_Material_0"; // WARNING: // .obj indicies start at one and therefore we need to add 1 to every one we parse _positions.push_back(glm::vec3()); _normals.push_back(glm::vec3()); _tex_coords.push_back(glm::vec2()); // Itterate over every line in the file while (std::getline(in_file_stream, line, '\n')) { // Parse materials if (line.compare(0, 7, "usemtl ") == 0) { // The current material was changed here, so we get the name and hash it std::string material_name = line.substr(7, line.length() - 7); // If this is the first time add it to the map if (!indices_map.count(material_name)) indices_map[material_name] = std::vector<std::string>(); current_material = material_name; } // Parse verticies if (line.compare(0, 2, "v ") == 0) { glm::vec3 v; sscanf(line.c_str(), "v %f %f %f",&v.x,&v.y,&v.z); _positions.push_back(v); } // Parse normals if (line.compare(0, 2, "vn") == 0) { glm::vec3 n; sscanf(line.c_str(), "vn %f %f %f",&n.x,&n.y,&n.z); _normals.push_back(n); } // Parse texture coordinates if (line.compare(0, 2, "vt") == 0) { glm::vec2 t; sscanf(line.c_str(), "vt %f %f",&t.x,&t.y); // Flip y for dds t.y = 1.0 - t.y; _tex_coords.push_back(t); } // Parse indicies if (line.compare(0, 1, "f") == 0) { // Add it to the current material indices_map[current_material].push_back(line); total_face_count++; } } // Close the file stream in_file_stream.close(); // If we didnt use the default array scrap it if (!indices_map["Generated_Material_0"].size()) indices_map.erase("Generated_Material_0"); // Now we put together everything, we do it with an indexed mesh std::map<std::string, std::vector<std::string>>::iterator i = indices_map.begin(); while (i != indices_map.end()) { // Create a new vector to store the indicies in std::vector<MIndex> indicies_vector; // Create a material MMaterial new_material; new_material.material_domain_name = i->first; materials.push_back(new_material); for (int j = 0; j < i->second.size(); j++) { MIndex new_indicies; // Get the data in .obj format for indicies glm::ivec3 indicies_vertex, indicies_normal, indicies_tex; sscanf(i->second[j].c_str(), "f %i/%i/%i %i/%i/%i %i/%i/%i", &indicies_vertex.x, &indicies_tex.x, &indicies_normal.x, &indicies_vertex.y, &indicies_tex.y, &indicies_normal.y, &indicies_vertex.z, &indicies_tex.z, &indicies_normal.z); // Get the verticies, these will be indexed new_indicies.x = getVertexIndex(_positions[indicies_vertex.x], _normals[indicies_normal.x], _tex_coords[indicies_tex.x]); new_indicies.y = getVertexIndex(_positions[indicies_vertex.y], _normals[indicies_normal.y], _tex_coords[indicies_tex.y]); new_indicies.z = getVertexIndex(_positions[indicies_vertex.z], _normals[indicies_normal.z], _tex_coords[indicies_tex.z]); // Calculate the tangent calculateTangent(new_indicies); indicies_vector.push_back(new_indicies); } indicies.push_back(indicies_vector); i++; } // Finalize the tangents finalizeTangents(); std::cout << "Read " << _positions.size() << " vertex positions from .obj\n"; std::cout << "Needed a total of " << vertices.size() << " unique verticies\n"; std::cout << "Had " << indicies.size() << " materials\n"; std::cout << "Had " << total_face_count << " faces\n"; }
bbf5a9c1f433191ba00d129e433981a661bc80b3
c8cfe03f33cbe3f6622c31f3f94000d249d9d7df
/Maze Game 1/Maze Game 1/mazeClass.cpp
b43ed023b140334be20d0c63097f16923a445283
[]
no_license
jeremyc61298/Maze-Game
a7dfd9a48c5099b46575df0847e873d67ba4f7c1
0f6a9d04a1e7fe7b6e64bdad1c3592045c28b011
refs/heads/master
2021-03-27T09:40:34.631867
2018-09-30T03:34:07
2018-09-30T03:34:07
123,033,646
0
0
null
null
null
null
UTF-8
C++
false
false
9,995
cpp
mazeClass.cpp
/* mazeClass.cpp */ // Author: Jeremy Campbell // Implementation file for mazeClass #include "mazeClass.h" #include <iostream> #include <cstdlib> #include <ctime> #include <windows.h> using std::cout; using std::endl; Maze::Maze() { buildMaze(); printMaze(); } Maze::~Maze() { } void Maze::buildMaze() { srand(time(NULL)); // Fill the array with walls for (int i = 0; i < GRIDROWS; i++) { for (int j = 0; j < GRIDCOLUMNS; j++) { grid[i][j] = WALL; } } initalizeStartCoordinate(); grid[currentLocation.row][currentLocation.column] = PATH; do { if (checkForValidDirections()) { pastLocations.push(currentLocation); pickRandomDirection(); } else { // Backtrack - take the new currentLocation from the // top of the stack currentLocation = pastLocations.top(); pastLocations.pop(); } } while (!pastLocations.empty()); grid[startLocation.row][startLocation.column] = START; initializeDestinationCoordinate(); } void Maze::printMaze() { for (int i = 0; i < GRIDROWS; i++) { for (int j = 0; j < GRIDCOLUMNS; j++) { setTextColor(grid[i][j]); cout << grid[i][j]; } cout << endl; } } // This function sets specific colors to specific characters to be printed. void Maze::setTextColor(char charToPrint) { if (charToPrint == WALL) { // light grey SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 8); } else if (charToPrint == START) { // green SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 2); } else if (charToPrint == DESTINATION) { // red SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 4); } else if (charToPrint == PLAYER) { // yellow SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 14); } else if (charToPrint == BREADCRUMB) { // light blue SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 11); } else { // white, default SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 15); } } // Randomly choose a destination coordinate that is odd,odd void Maze::initalizeStartCoordinate() { int column; int row; do { row = rand() % GRIDROWS; } while (row % 2 == 0); do { column = rand() % GRIDCOLUMNS; } while (column % 2 == 0); currentLocation.row = row; currentLocation.column = column; startLocation = currentLocation; } // Randomly choose a destination coordinate on the Path void Maze::initializeDestinationCoordinate() { coordinate destination; do { destination.row = rand() % GRIDROWS; destination.column = rand() % GRIDCOLUMNS; } while (grid[destination.row][destination.column] != PATH); grid[destination.row][destination.column] = DESTINATION; } // Test each direction, but do not actually dig. bool Maze::checkForValidDirections() { bool possibleValidMove = false; bool dig = false; if (testNorthCoordinate(dig) || testSouthCoordinate(dig) || testEastCoordinate(dig) || testWestCoordinate(dig)) { possibleValidMove = true; } return possibleValidMove; } bool Maze::testNorthCoordinate(bool dig) { bool isValidMove = false; coordinate northCoordinate; northCoordinate.row = currentLocation.row - 2; northCoordinate.column = currentLocation.column; if (grid[northCoordinate.row][northCoordinate.column] != PATH && northCoordinate.row > 0) { // Simply test the direction if dig is false. If true, dig in that direction. isValidMove = true; if (dig) { digNorth(); currentLocation = northCoordinate; } } return isValidMove; } bool Maze::testSouthCoordinate(bool dig) { bool isValidMove = false; coordinate southCoordinate; southCoordinate.row = currentLocation.row + 2; southCoordinate.column = currentLocation.column; if (grid[southCoordinate.row][southCoordinate.column] != PATH && southCoordinate.row < GRIDROWS) { // Simply test the direction if dig is false. If true, dig in that direction. isValidMove = true; if (dig) { digSouth(); currentLocation = southCoordinate; } } return isValidMove; } bool Maze::testEastCoordinate(bool dig) { bool isValidMove = false; coordinate eastCoordinate; eastCoordinate.row = currentLocation.row; eastCoordinate.column = currentLocation.column + 2; if (grid[eastCoordinate.row][eastCoordinate.column] != PATH && eastCoordinate.column < GRIDCOLUMNS) { // Simply test the direction if dig is false. If true, dig in that direction. isValidMove = true; if (dig) { digEast(); currentLocation = eastCoordinate; } } return isValidMove; } bool Maze::testWestCoordinate(bool dig) { bool isValidMove = false; coordinate westCoordinate; westCoordinate.row = currentLocation.row; westCoordinate.column = currentLocation.column - 2; if (grid[westCoordinate.row][westCoordinate.column] != PATH && westCoordinate.column > 0) { // Simply test the direction if dig is false. If true, dig in that direction. isValidMove = true; if (dig) { digWest(); currentLocation = westCoordinate; } } return isValidMove; } void Maze::pickRandomDirection() { // Dig will test the test functions to actually // change currentLocation bool dig = true; bool moved = false; while (!moved) { int whichFunction = 1 + rand() % 4; switch (whichFunction) { case 1: if (testNorthCoordinate(dig)) { moved = true; } break; case 2: if (testSouthCoordinate(dig)) { moved = true; } break; case 3: if (testEastCoordinate(dig)) { moved = true; } break; case 4: if (testWestCoordinate(dig)) { moved = true; } break; } } } void Maze::digNorth() { for (int i = currentLocation.row - 1; i >= currentLocation.row - 2; i--) { grid[i][currentLocation.column] = PATH; } } void Maze::digSouth() { for (int i = currentLocation.row + 1; i <= currentLocation.row + 2; i++) { grid[i][currentLocation.column] = PATH; } } void Maze::digEast() { for (int i = currentLocation.column + 1; i <= currentLocation.column + 2; i++) { grid[currentLocation.row][i] = PATH; } } void Maze::digWest() { for (int i = currentLocation.column - 1; i >= currentLocation.column - 2; i--) { grid[currentLocation.row][i] = PATH; } } //This function was written by Dr. Steil int Maze::getKey() { int result = 0; while (result == 0) { short MAX_SHORT = 0x7FFF; //111111111111111 if (GetAsyncKeyState(VK_LEFT) & MAX_SHORT) { result = VK_LEFT; } else if (GetAsyncKeyState(VK_UP) & MAX_SHORT) { result = VK_UP; } else if (GetAsyncKeyState(VK_RIGHT) & MAX_SHORT) { result = VK_RIGHT; } else if (GetAsyncKeyState(VK_DOWN) & MAX_SHORT) { result = VK_DOWN; } else if (GetAsyncKeyState(VK_ESCAPE) & MAX_SHORT) { result = VK_ESCAPE; } } return result; } //This function, playGame, was given by Dr.Steil, and modified by myself, Jeremy C. void Maze::playGame() { int row = startLocation.row; int column = startLocation.column; int key = getKey(); COORD oldCoord = { column, row }; COORD firstCoord = { column, row }; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), firstCoord); while (key != VK_ESCAPE) { if (key == VK_LEFT && column > 0 && grid[row][column - 1] != WALL) { column--; } else if (key == VK_RIGHT && grid[row][column + 1] != WALL) { column++; } else if (key == VK_UP && row > 0 && grid[row - 1][column] != WALL) { row--; } else if (key == VK_DOWN && grid[row + 1][column] != WALL) { row++; } COORD newCoord = { column, row }; // This will display to the screen where the user's current location // is on the grid, but in memory it will store a breadcrumb at their // current location. replaceOldCoordinate(oldCoord, newCoord); movePlayer(oldCoord, newCoord); oldCoord = newCoord; key = getKey(); } //Did not solve the maze endGame(false); } void Maze::movePlayer(COORD oldCoord, COORD newCoord) { // If the maze has been solved, endGame. Keep playing if not. // The player will disappear, showing the completed maze if (grid[newCoord.Y][newCoord.X] == DESTINATION) { SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), oldCoord); endGame(true); } SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), newCoord); setTextColor(PLAYER); cout << PLAYER; } // Upon moving, this will replace the character where the player previously was on the grid, // in memory, and on the screen. Start will never change in memory. void Maze::replaceOldCoordinate(COORD oldCoord, COORD newCoord) { SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), oldCoord); // If player is stepping off the startLocation if (grid[oldCoord.Y][oldCoord.X] == grid[startLocation.row][startLocation.column]) { setTextColor(START); cout << START; } // If the player is stepping on anything besides a Path else if (grid[newCoord.Y][newCoord.X] != PATH) { grid[oldCoord.Y][oldCoord.X] = PATH; cout << PATH; } // If the player is stepping on the Path and not the startLocation else if (grid[oldCoord.Y][oldCoord.X] != grid[startLocation.row][startLocation.column]) { grid[oldCoord.Y][oldCoord.X] = BREADCRUMB; setTextColor(BREADCRUMB); cout << BREADCRUMB; } } void Maze::endGame(bool won) { COORD endMessageLocation = { 0, GRIDROWS + 1 }; if (won) { //Drop the last breadcrumb setTextColor(BREADCRUMB); cout << BREADCRUMB; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), endMessageLocation); setTextColor('W'); cout << "You've solved the maze!" << endl; } else { SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), endMessageLocation); setTextColor('W'); cout << "Nice try" << endl; } exit(0); }
883f5d0500b11ed0747aea7b063b4f17a5055aef
5715bb8eaa97d3ea609ddd4043ced71dd2d602d4
/src/Main.cpp
0ab4667973a335b560d10cca62888f28c1b39a45
[ "MIT" ]
permissive
InversePalindrome/Chess
832a9b40d718a2bd326a521c07dc66902ec0ff85
191a02693865805309dd09e1d75dc23566509eed
refs/heads/master
2020-04-29T09:47:16.789853
2019-12-29T19:51:38
2019-12-29T19:51:38
176,038,214
1
0
null
null
null
null
UTF-8
C++
false
false
704
cpp
Main.cpp
/* Copyright (c) 2019 Inverse Palindrome Chess - Main.cpp https://inversepalindrome.com/ */ #include "MainWindow.hpp" #include <QTimer> #include <QApplication> #include <QSplashScreen> int main(int argc, char* argv[]) { QApplication a(argc, argv); auto* splashScreen = new QSplashScreen(QPixmap(":/Resources/InversePalindromeLogo.jpg"), Qt::WindowStaysOnTopHint); splashScreen->show(); MainWindow mainWindow; mainWindow.setWindowTitle("Chess"); mainWindow.setFixedSize(1600, 1600); const auto SPLASH_TIME = 2000; QTimer::singleShot(SPLASH_TIME, splashScreen, SLOT(close())); QTimer::singleShot(SPLASH_TIME, &mainWindow, SLOT(show())); return a.exec(); }
8e47fa8e562100e92edb921c396e5e991afd589e
628f60ea185d57334e350a6e3bbbb6eac6f77bd0
/Framework/Engine/Resources/Code/RcAlphaTex.cpp
96d2ad2acb27d1c8e1c514fbb4f34b7e5f92f01e
[]
no_license
ems789/Wizard-of-Legend-2.5D-Team-Project
e31a2a50e1971f88b8ec1d9320332f1f5608d16d
345136dc7a76dc66b9b864945804dddabf88be8e
refs/heads/master
2022-05-26T12:41:44.766735
2020-04-29T01:24:52
2020-04-29T01:24:52
252,634,747
0
0
null
null
null
null
UTF-8
C++
false
false
2,036
cpp
RcAlphaTex.cpp
#include "RcAlphaTex.h" USING(Engine) Engine::CRcAlphaTex::CRcAlphaTex(LPDIRECT3DDEVICE9 pGraphicDev) : CVIBuffer(pGraphicDev) { } Engine::CRcAlphaTex::CRcAlphaTex(const CRcAlphaTex& rhs) : CVIBuffer(rhs) { } Engine::CRcAlphaTex::~CRcAlphaTex() { } HRESULT Engine::CRcAlphaTex::Ready_Buffer(const D3DXCOLOR& d3dColor) { m_d3dColor = d3dColor; m_dwVtxSize = sizeof(VTXCOLTEX); m_dwVtxCnt = 4; m_dwVtxFVF = FVF_COLTEX; m_dwTriCnt = 2; m_dwIdxSize = sizeof(INDEX16); m_IdxFmt = D3DFMT_INDEX16; FAILED_CHECK_RETURN(CVIBuffer::Ready_Buffer(), E_FAIL); VTXCOLTEX* pVertex = nullptr; m_pVB->Lock(0, 0, (void**)&pVertex, 0); pVertex[0].vPos = _vec3(-0.5f, 0.5f, 0.f); pVertex[0].dwColor = d3dColor; pVertex[0].vTexUV = _vec2(0.f, 0.f); pVertex[1].vPos = _vec3(0.5f, 0.5f, 0.f); pVertex[1].dwColor = d3dColor; pVertex[1].vTexUV = _vec2(1.f, 0.f); pVertex[2].vPos = _vec3(0.5f, -0.5f, 0.f); pVertex[2].dwColor = d3dColor; pVertex[2].vTexUV = _vec2(1.f, 1.f); pVertex[3].vPos = _vec3(-0.5f, -0.5f, 0.f); pVertex[3].dwColor = d3dColor; pVertex[3].vTexUV = _vec2(0.f, 1.f); m_pVB->Unlock(); INDEX16* pIndex = nullptr; m_pIB->Lock(0, 0, (void**)&pIndex, 0); // 0 pIndex[0]._0 = 0; pIndex[0]._1 = 1; pIndex[0]._2 = 2; // 1 pIndex[1]._0 = 0; pIndex[1]._1 = 2; pIndex[1]._2 = 3; m_pIB->Unlock(); return S_OK; } void CRcAlphaTex::Set_Color(const D3DXCOLOR & d3dColor) { VTXCOLTEX* pVertex = nullptr; m_pVB->Lock(0, 0, (void**)&pVertex, 0); pVertex[0].dwColor = d3dColor; pVertex[1].dwColor = d3dColor; pVertex[2].dwColor = d3dColor; pVertex[3].dwColor = d3dColor; m_pVB->Unlock(); } Engine::CRcAlphaTex* Engine::CRcAlphaTex::Create(LPDIRECT3DDEVICE9 pGraphicDev, const D3DXCOLOR& d3dColor) { CRcAlphaTex* pInst = new CRcAlphaTex(pGraphicDev); if (FAILED(pInst->Ready_Buffer(d3dColor))) Safe_Release(pInst); return pInst; } Engine::CResources* Engine::CRcAlphaTex::Clone() { return new CRcAlphaTex(*this); } void Engine::CRcAlphaTex::Free() { CVIBuffer::Free(); }
1df7751360a7f3fa47add66bd27261c327e2fc58
2007c9f6cb68dcfd0a24c7c9ff8533e0c08a2240
/#StayHome/challenge.hpp
7b9b5e6078d6ea20caa4d0cc30c4f0fa66953db6
[]
no_license
ivon99/Smaller_Projects
de75532c87054b5481d94ac210c8ea27378eb073
505b6635fad74b9eda831c2d77dbd1f159197ec0
refs/heads/main
2023-06-25T10:54:06.679894
2021-07-21T13:07:02
2021-07-21T13:07:02
388,109,467
0
0
null
null
null
null
UTF-8
C++
false
false
1,135
hpp
challenge.hpp
#ifndef _CHALLENGE_HPP_ #define _CHALLENGE_HPP_ class Challenge { //represented under 40 bytes static const int MAX_TAG_SIZE = 31; static const int MAX_STATUS_SIZE = 20; char *m_tag; //уникално, започва с # и е до 31 символа ??? char *m_status; //0--new, 2-10 --quite recently, >11-- old unsigned short int m_numchallenged; //up to 65535 float m_rating; // [-5.00,10.0] int m_orderadded; //used for listing void copyFrom(const Challenge &other); void clean(); public: //The big 4 Challenge(); Challenge(char *); Challenge(const Challenge &); Challenge &operator=(const Challenge &); ~Challenge(); //setters bool setTag(char *); void setOrderAdded(int); void setStatus(); //changes status:{new,quite recently,old} void setNumChallenged(); //changes num challenged void setRating(float new_rating); //getters const char *getTag(); unsigned short int getNumCh() const; const char *getStatus() const; float getRating() const; void printChallenge() const; }; #endif
9badb10f06d441dfd688ca90b697e567b6f711f9
c5f1a804dbd1f5de123469dd5432633633e80597
/BarrelDrop2/HighScores.cpp
5b517b09f809913b0165e5ef46e249aa4e49eaaa
[]
no_license
brosell/HTS-Games
2d03a8988adc5c613dba1e249a7e0b409593ff11
3c7c1cc2ec4fe0ba7865f6eec5cec905faab5a3f
refs/heads/master
2021-01-22T21:23:38.681074
2020-01-12T15:41:47
2020-01-12T15:41:47
85,423,760
0
0
null
null
null
null
UTF-8
C++
false
false
1,991
cpp
HighScores.cpp
#pragma warning (disable : 4786 4503 4530) #include "HighScores.h" #include "IniFile.h" #include "Log.h" #include "Convert.h" #include "boost/format.hpp" HighScores::HighScores(): m_justAdded(-1) { // for (int x=0; x<10; x++) // { // m_scores[x].name = ""; // m_scores[x].level = 0; // m_scores[x].score = 0; // } } HighScores::~HighScores() { } void HighScores::load(string filename) { IniFile ini(filename); ini.read(); char buf[255]; for (int x=0; x<10; x++) { sprintf(buf, "HighScore%02d", x); m_scores[x].name = ini[buf]["Name"]; if (m_scores[x].name == "") { m_scores[x].name = "nobody"; } m_scores[x].level = ini.getInt(buf, "Level"); m_scores[x].score = ini.getInt(buf, "Score"); m_scores[x].skill = ini[buf]["Skill"]; m_scores[x].survivor = ini.getInt(buf, "Survivor"); } } void HighScores::save(string filename) { IniFile ini(filename); char buf[255]; // char val[255]; for (int x=0; x<10; x++) { sprintf(buf, "HighScore%02d", x); string sect(buf); ini[sect]["Name"] = m_scores[x].name; ini[sect]["Level"] = toString(m_scores[x].level); ini[sect]["Score"] = toString(m_scores[x].score); ini[sect]["Skill"] = m_scores[x].skill; ini[sect]["Survivor"] = toString(m_scores[x].survivor); } ini.write(); } HighScore HighScores::getScore(int num) { return m_scores[num]; } bool HighScores::isHighScore(int score) { return (score > m_scores[9].score); } void HighScores::addScore(string name, int level, int s, string skill, int survivor) { HighScore score; score.name = name; score.level = level; score.score = s; score.skill = skill; score.survivor = survivor; lassert(s >= m_scores[9].score); for (int c=0; c<10; c++) { if (s >= m_scores[c].score) { // insert it here for (int d=8; d>=c; d--) { m_scores[d+1] = m_scores[d]; } m_scores[c] = score; m_justAdded = c; return; } } }
f4d38474fcb7d07076c54abf8ef923af3d8b62da
32709d5de776d864df9581b1a9c2d9d966c3c31f
/isaac/08_06_Isaac_Room/Door.cpp
7cb28f2b5a9eed472bc76ceb4fba46786d6a21eb
[]
no_license
dadm8473/DirectX_Class
76010b18e490306cd44c21554cc8ab31f53df1ce
34dd319d39d93c1f73a7c7dd6c2047aa20694e69
refs/heads/master
2022-03-16T05:30:41.434207
2019-11-10T12:45:37
2019-11-10T12:45:37
186,415,853
0
0
null
null
null
null
UHC
C++
false
false
1,196
cpp
Door.cpp
#include "DXUT.h" #include "Door.h" Door::Door() { } Door::~Door() { } void Door::Start() { type = BG_DOOR; // 스프라이트 렌더러 추가 renderer = new CSpriteRenderer(L"Door", L"Assets/Images/BG/BossDoor_", L"png", true, 2, 2, 0); renderer->SetIndex(0, 0, 1, false); // 닫힌 문 renderer->SetIndex(1, 1, 1, false); // 열린 문 pivot.y = 0.33; CreateCollider(CL_NONE, 50); SetCollision(CL_PLAYER); bCollision = false; switch (dir) { case DOWN: scale.y *= -1; break; case RIGHT: fRot = 90; break; case UP: break; case LEFT: fRot = -90; break; default: break; } } void Door::OnCollision(CGameObject * CollisionObject) { //char temp[100]; //memset(temp, 0, sizeof(temp)); //sprintf(temp, "GAME CLEAR. CLEAR TIME : %.2lf", g_Game.TimeScore); //MessageBoxA(DXUTGetHWND(), temp, "TryWorld MSG Box", MB_OK); //g_OpenScene->bNextScene = true; D3DXVECTOR2 vtemp = nextRoom - position; D3DXVec2Normalize(&vtemp, &vtemp); CollisionObject->position += vtemp * 150; g_OpenScene->MoveCamera(nextRoom, 3000); for each (CGameObject * var in g_OpenScene->m_ObjectList) { if (var->type == BG_ROOM) { ((Room*)var)->CheckPlayer(); } } }
e311e730f2c8e1f30a2e33265e101606cffbca8d
a46d634a4e862eb34a080e97edc9547a231b857a
/V4l2CameraControl.cpp
1a9d4c0541a2cb43afe7f59a2cf18cbe455f21cf
[]
no_license
yexiaopeng/QHLCamera
b446f2e6fab12bac9f50f33ba4e90927d919b066
c7af2b05223655f58de3bb2661c325eee7bb1eb3
refs/heads/master
2020-03-19T09:31:02.443167
2018-06-12T11:40:52
2018-06-12T11:40:52
136,295,724
0
0
null
null
null
null
UTF-8
C++
false
false
3,485
cpp
V4l2CameraControl.cpp
#include "V4l2CameraControl.h" #include "QDateTime" // int V4l2GetJpg(char *camserId, char * jpgpatch, int pictureCcount) { int fd_video; FILE* fp_jpg; struct buffer *buffers; fd_video = open(camserId,O_RDWR); if(fd_video < 0 ){ printf("\r\n # 1 error: %s open error ",camserId); return -1; } //设置视频的格式,720P JPEG struct v4l2_format s_fmt; s_fmt.fmt.pix.width = 1280; s_fmt.fmt.pix.height = 960; s_fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_MJPEG; printf("s_fmt.fmt.pix.pixelformat:%d\n",s_fmt.fmt.pix.pixelformat); s_fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; int flag= ioctl(fd_video,VIDIOC_S_FMT,&s_fmt); if(flag != 0) { printf("set format error\n"); return -1; } //creat 3 picture for(int i = 0; i < pictureCcount;i++){ //QDateTime current_date_time =QDateTime::currentDateTime(); //QString current_date =current_date_time.toString("yyyy.MM.dd_hh:mm:ss.zzz"); QString current_date = QString::number(i)+".jpg"; fp_jpg = fopen(current_date.toLatin1().data() ,"wb+"); //申请1个缓冲区 struct v4l2_requestbuffers req; req.count=1; req.type=V4L2_BUF_TYPE_VIDEO_CAPTURE; req.memory=V4L2_MEMORY_MMAP; ioctl(fd_video,VIDIOC_REQBUFS,&req); //缓冲区与应用程序关联 //申请1个struct buffer空间 buffers = (struct buffer*)calloc (req.count, sizeof (struct buffer)); if (!buffers) { perror ("Out of memory"); exit (EXIT_FAILURE); } unsigned int n_buffers; for (n_buffers = 0; n_buffers < req.count; n_buffers++) { struct v4l2_buffer buf; memset(&buf,0,sizeof(buf)); buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; buf.memory = V4L2_MEMORY_MMAP; buf.index = n_buffers; if (-1 == ioctl (fd_video, VIDIOC_QUERYBUF, &buf)) exit(-1); buffers[n_buffers].length = buf.length; buffers[n_buffers].start = mmap (NULL, buf.length,PROT_READ | PROT_WRITE ,MAP_SHARED,fd_video, buf.m.offset); if (MAP_FAILED == buffers[n_buffers].start) exit(-1); } enum v4l2_buf_type type; for (n_buffers = 0; n_buffers < req.count; n_buffers++) { struct v4l2_buffer buf; buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; buf.memory = V4L2_MEMORY_MMAP; buf.index = n_buffers; ioctl (fd_video, VIDIOC_QBUF, &buf); } //开始捕获图像 type = V4L2_BUF_TYPE_VIDEO_CAPTURE; ioctl (fd_video, VIDIOC_STREAMON, &type); struct v4l2_buffer buf; memset(&(buf), 0, sizeof(buf)); buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; buf.memory = V4L2_MEMORY_MMAP; //取出图像数据 ioctl (fd_video, VIDIOC_DQBUF, &buf); //保存图像 fwrite(buffers[buf.index].start,1,buffers[buf.index].length,fp_jpg);//mjpeg fflush(fp_jpg); //放回缓冲区 ioctl (fd_video,VIDIOC_QBUF,&buf); for (n_buffers = 0; n_buffers < req.count; n_buffers++) munmap(buffers[n_buffers].start, buffers[n_buffers].length); free(buffers); fclose(fp_jpg); } close(fd_video); printf("capture jpg finish..\n"); }
c5580e95f923a456c8eac3ea7a00a77452febb65
790e33cd347a90e90ed93a3db9c408e58a6c90c4
/algorithmclass/wordcreator.cpp
a385df0ee6b94858652f19a54e4b3edddbfa6328
[]
no_license
garetroy/AlgorithmPractice
7bcaa68a7288d68c2e00d7fda9d21ea3b8880308
6572c70447b9c2d026c16120f4cdc8daca083889
refs/heads/master
2021-01-22T17:39:32.156674
2018-01-04T17:20:26
2018-01-04T17:20:26
85,026,342
0
0
null
null
null
null
UTF-8
C++
false
false
2,993
cpp
wordcreator.cpp
#include <algorithm> #include <unordered_set> #include <iostream> #include <fstream> #include <sstream> #include <string> using namespace std; string get_string(bool memo, int *location, string instring) { string outstring = ""; if(!memo){ outstring = "No, cannot be split\n"; }else{ outstring = "Yes, can be split\n"; for(int i = 0; i < instring.size() - 1; i++){ outstring += instring.substr(i,location[i]+1) + " "; i = location[i]; } } return outstring; } /*bool recursive_find(unordered_set<string>&dictionary, bool *memo, int *location, string instring, int i=0) { if(i == instring.size()) return true; if(memo[i]) return memo[i]; memo[i] = false; for(int j = i; i < instring.size(); j++) if((dictionary.find(instring.substr(i,j+1)) != dictionary.end()) && recursive_find(dictionary,memo,location,instring,j+1)){ memo[i] = true; location[i] = j; } return memo[i]; }*/ string iterative_find(unordered_set<string>&dictionary, string instring) { bool memo[instring.size()+1]; int location[instring.size()+1]; string outstring(""); string substring(""); memo[instring.size()] = true; for(int i = instring.size()-1; i >= 0; i--){ memo[i] = false; for(int j = i; j < instring.size(); j++) if((dictionary.find(instring.substr(i,j+1)) != dictionary.end()) && memo[j+1]){ memo[i] = true; location[i] = j; } } return get_string(memo[0],location,instring); } void initialize_array(bool* memo, int *location, int size) { for(int i = 0; i < size; i++){ memo[i] = false; location[i] = 0; } } int main() { unordered_set<string> dictionary(58114); ifstream myfile("diction10k.txt"); int numphrase(0); bool found(false); string in(""); //init dictionary while(getline(myfile, in)){ istringstream iss(in); iss >> in; dictionary.emplace(in); } cin >> numphrase; string phrases[numphrase]; for(int i = 0; i < numphrase; i++) cin >> phrases[i]; for(int i = 0; i < numphrase; i++){ cout << "phrase number: 1" << endl; cout << phrases[i] << endl << endl; cout << "iterative attempt:" << endl; cout << iterative_find(dictionary,phrases[i]) << endl; cout << "memoized attempt:" << endl; // int location[phrases[i].size()+1]; // bool memo[phrases[i].size()+1]; // initialize_array(memo,location,phrases[i].size()+1); // found = recursive_find(dictionary,memo,location,phrases[i]); // for(int i = 0; i < phrases[i].size();i++) // cout << location[i]; // cout << get_string(found,location,phrases[i]) << endl << endl; } myfile.close(); return 1; }
69b449ae2642d09242f1ce9f0400bf4c1d5c81de
4a7073455f0c5184ad22fccbfbdbe5659abb77e4
/board.cpp
93f88f559d188f7607f2ed1078e2605b4257c910
[]
no_license
Bhaumik-Tandan/CPP_playground
a45e0bdcaf5d5d727f44d9407b69936828762231
d00be2ad79071e7bbb8fcefaedce08542e8c81e0
refs/heads/master
2023-08-24T15:10:25.210847
2021-04-09T07:55:23
2021-04-09T07:55:23
351,698,021
0
0
null
null
null
null
UTF-8
C++
false
false
259
cpp
board.cpp
#include <iostream> using namespace std; class A { public: A() { cout<<"First Line\n"; } ~A() { cout<<"\nThird Line"; } }; //First line //Second line //Third line main() { A j; cout<<"Second line"; }
f89181a926691d6951cba30e1fac0bcbb311224b
7ccfb888013ea5442d0b35fceb5b281c00c0a809
/DES_DEC_Vivado_HLS/DES_DEC/qB1_5/syn/systemc/des_dec.h
6706c313c3ab9cc736c6a1259a202f00c92c335a
[]
no_license
Deepsavani/DES-Decryption-Implemented-in-Vivado-HLS
d60b77e5f03b981596470a541b158a76f106eb98
6712279402d8ea80aef2d1285005483de962a002
refs/heads/master
2023-03-08T12:22:19.224436
2021-02-23T06:10:11
2021-02-23T06:10:11
341,445,708
1
0
null
null
null
null
UTF-8
C++
false
false
31,370
h
des_dec.h
// ============================================================== // RTL generated by Vivado(TM) HLS - High-Level Synthesis from C, C++ and SystemC // Version: 2019.1 // Copyright (C) 1986-2019 Xilinx, Inc. All Rights Reserved. // // =========================================================== #ifndef _des_dec_HH_ #define _des_dec_HH_ #include "systemc.h" #include "AESL_pkg.h" #include "des_dec_PC2.h" #include "des_dec_E.h" #include "des_dec_S.h" #include "des_dec_P.h" #include "des_dec_PI.h" #include "des_dec_sub_key.h" namespace ap_rtl { struct des_dec : public sc_module { // Port declarations 9 sc_in_clk ap_clk; sc_in< sc_logic > ap_rst; sc_in< sc_logic > ap_start; sc_out< sc_logic > ap_done; sc_out< sc_logic > ap_idle; sc_out< sc_logic > ap_ready; sc_in< sc_lv<64> > input_r; sc_in< sc_lv<64> > key; sc_out< sc_lv<64> > ap_return; // Module declarations des_dec(sc_module_name name); SC_HAS_PROCESS(des_dec); ~des_dec(); sc_trace_file* mVcdFile; ofstream mHdltvinHandle; ofstream mHdltvoutHandle; des_dec_PC2* PC2_U; des_dec_E* E_U; des_dec_S* S_U; des_dec_P* P_U; des_dec_PI* PI_U; des_dec_sub_key* sub_key_U; sc_signal< sc_lv<17> > ap_CS_fsm; sc_signal< sc_logic > ap_CS_fsm_state1; sc_signal< sc_lv<6> > PC2_address0; sc_signal< sc_logic > PC2_ce0; sc_signal< sc_lv<6> > PC2_q0; sc_signal< sc_lv<6> > E_address0; sc_signal< sc_logic > E_ce0; sc_signal< sc_lv<6> > E_q0; sc_signal< sc_lv<9> > S_address0; sc_signal< sc_logic > S_ce0; sc_signal< sc_lv<4> > S_q0; sc_signal< sc_lv<5> > P_address0; sc_signal< sc_logic > P_ce0; sc_signal< sc_lv<6> > P_q0; sc_signal< sc_lv<6> > PI_address0; sc_signal< sc_logic > PI_ce0; sc_signal< sc_lv<7> > PI_q0; sc_signal< sc_lv<32> > L_fu_1038_p33; sc_signal< sc_lv<32> > L_reg_2434; sc_signal< sc_lv<32> > R_fu_1106_p33; sc_signal< sc_lv<32> > R_reg_2439; sc_signal< sc_lv<5> > i_1_fu_1758_p2; sc_signal< sc_lv<5> > i_1_reg_2447; sc_signal< sc_logic > ap_CS_fsm_state2; sc_signal< sc_lv<4> > sub_key_addr_reg_2455; sc_signal< sc_lv<1> > icmp_ln192_fu_1752_p2; sc_signal< sc_lv<56> > tmp_11_fu_1920_p3; sc_signal< sc_lv<56> > tmp_11_reg_2467; sc_signal< sc_logic > ap_CS_fsm_state3; sc_signal< sc_lv<6> > j_4_fu_1934_p2; sc_signal< sc_lv<6> > j_4_reg_2475; sc_signal< sc_logic > ap_CS_fsm_state4; sc_signal< sc_lv<1> > icmp_ln216_fu_1928_p2; sc_signal< sc_lv<63> > trunc_ln218_1_fu_1945_p1; sc_signal< sc_lv<63> > trunc_ln218_1_reg_2485; sc_signal< sc_lv<64> > or_ln_fu_1968_p3; sc_signal< sc_logic > ap_CS_fsm_state5; sc_signal< sc_lv<5> > i_5_fu_1981_p2; sc_signal< sc_lv<5> > i_5_reg_2498; sc_signal< sc_logic > ap_CS_fsm_state6; sc_signal< sc_lv<64> > pre_output_fu_1987_p3; sc_signal< sc_lv<64> > pre_output_reg_2503; sc_signal< sc_lv<1> > icmp_ln223_fu_1975_p2; sc_signal< sc_lv<6> > j_fu_2001_p2; sc_signal< sc_lv<6> > j_reg_2511; sc_signal< sc_logic > ap_CS_fsm_state7; sc_signal< sc_lv<1> > icmp_ln227_fu_1995_p2; sc_signal< sc_lv<64> > s_input_fu_2047_p3; sc_signal< sc_logic > ap_CS_fsm_state8; sc_signal< sc_lv<47> > xor_ln232_fu_2071_p2; sc_signal< sc_lv<47> > xor_ln232_reg_2531; sc_signal< sc_logic > ap_CS_fsm_state9; sc_signal< sc_lv<48> > xor_ln232_1_fu_2077_p2; sc_signal< sc_lv<48> > xor_ln232_1_reg_2536; sc_signal< sc_lv<4> > j_5_fu_2089_p2; sc_signal< sc_lv<4> > j_5_reg_2544; sc_signal< sc_logic > ap_CS_fsm_state10; sc_signal< sc_lv<7> > sub_ln240_fu_2125_p2; sc_signal< sc_lv<7> > sub_ln240_reg_2549; sc_signal< sc_lv<1> > icmp_ln235_fu_2083_p2; sc_signal< sc_lv<6> > sub_ln240_2_fu_2149_p2; sc_signal< sc_lv<6> > sub_ln240_2_reg_2554; sc_signal< sc_lv<6> > sub_ln243_1_fu_2161_p2; sc_signal< sc_lv<6> > sub_ln243_1_reg_2559; sc_signal< sc_lv<11> > add_ln246_1_fu_2290_p2; sc_signal< sc_lv<11> > add_ln246_1_reg_2564; sc_signal< sc_logic > ap_CS_fsm_state11; sc_signal< sc_logic > ap_CS_fsm_state12; sc_signal< sc_lv<6> > j_6_fu_2323_p2; sc_signal< sc_lv<6> > j_6_reg_2577; sc_signal< sc_logic > ap_CS_fsm_state14; sc_signal< sc_lv<1> > icmp_ln252_fu_2317_p2; sc_signal< sc_lv<31> > trunc_ln254_1_fu_2334_p1; sc_signal< sc_lv<31> > trunc_ln254_1_reg_2587; sc_signal< sc_lv<32> > R_1_fu_2338_p2; sc_signal< sc_lv<32> > f_function_res_fu_2364_p3; sc_signal< sc_logic > ap_CS_fsm_state15; sc_signal< sc_lv<7> > i_fu_2377_p2; sc_signal< sc_lv<7> > i_reg_2605; sc_signal< sc_logic > ap_CS_fsm_state16; sc_signal< sc_lv<1> > icmp_ln267_fu_2371_p2; sc_signal< sc_lv<63> > trunc_ln270_1_fu_2388_p1; sc_signal< sc_lv<63> > trunc_ln270_1_reg_2615; sc_signal< sc_lv<64> > inv_init_perm_res_fu_2411_p3; sc_signal< sc_logic > ap_CS_fsm_state17; sc_signal< sc_lv<4> > sub_key_address0; sc_signal< sc_logic > sub_key_ce0; sc_signal< sc_logic > sub_key_we0; sc_signal< sc_lv<64> > sub_key_q0; sc_signal< sc_lv<5> > i_2_reg_375; sc_signal< sc_lv<64> > sub_key_load_1_reg_386; sc_signal< sc_lv<6> > j_0_reg_398; sc_signal< sc_lv<32> > temp_reg_409; sc_signal< sc_lv<32> > L_0_reg_419; sc_signal< sc_lv<5> > i_3_reg_430; sc_signal< sc_lv<64> > s_input_0_reg_442; sc_signal< sc_lv<6> > j_1_reg_454; sc_signal< sc_lv<4> > j_2_reg_465; sc_signal< sc_logic > ap_CS_fsm_state13; sc_signal< sc_lv<32> > f_function_res_0_reg_477; sc_signal< sc_lv<6> > j_3_reg_488; sc_signal< sc_lv<7> > i_4_reg_499; sc_signal< sc_lv<64> > inv_init_perm_res_0_reg_510; sc_signal< sc_lv<64> > zext_ln214_fu_1910_p1; sc_signal< sc_lv<64> > zext_ln218_fu_1940_p1; sc_signal< sc_lv<64> > zext_ln229_fu_2007_p1; sc_signal< sc_lv<64> > zext_ln232_fu_2018_p1; sc_signal< sc_lv<64> > sext_ln246_3_fu_2296_p1; sc_signal< sc_lv<64> > zext_ln254_fu_2329_p1; sc_signal< sc_lv<64> > zext_ln270_1_fu_2383_p1; sc_signal< sc_lv<28> > C_1_fu_264; sc_signal< sc_lv<28> > C_fu_1622_p29; sc_signal< sc_lv<28> > C_2_fu_1820_p3; sc_signal< sc_lv<1> > empty_13_fu_1800_p2; sc_signal< sc_lv<28> > C_3_fu_1872_p3; sc_signal< sc_lv<28> > D_1_fu_268; sc_signal< sc_lv<28> > D_fu_1682_p29; sc_signal< sc_lv<28> > D_2_fu_1842_p3; sc_signal< sc_lv<28> > D_3_fu_1892_p3; sc_signal< sc_lv<32> > s_output_1_fu_276; sc_signal< sc_lv<32> > s_output_fu_2304_p3; sc_signal< sc_lv<1> > tmp_3_fu_538_p3; sc_signal< sc_lv<1> > tmp_2_fu_530_p3; sc_signal< sc_lv<1> > tmp_4_fu_546_p3; sc_signal< sc_lv<1> > tmp_5_fu_554_p3; sc_signal< sc_lv<1> > tmp_6_fu_562_p3; sc_signal< sc_lv<1> > tmp_7_fu_570_p3; sc_signal< sc_lv<1> > tmp_8_fu_578_p3; sc_signal< sc_lv<1> > tmp_9_fu_586_p3; sc_signal< sc_lv<1> > tmp_10_fu_594_p3; sc_signal< sc_lv<1> > tmp_12_fu_602_p3; sc_signal< sc_lv<1> > tmp_13_fu_610_p3; sc_signal< sc_lv<1> > tmp_14_fu_618_p3; sc_signal< sc_lv<1> > tmp_16_fu_626_p3; sc_signal< sc_lv<1> > tmp_18_fu_634_p3; sc_signal< sc_lv<1> > tmp_19_fu_642_p3; sc_signal< sc_lv<1> > tmp_21_fu_650_p3; sc_signal< sc_lv<1> > tmp_22_fu_658_p3; sc_signal< sc_lv<1> > tmp_23_fu_666_p3; sc_signal< sc_lv<1> > tmp_26_fu_674_p3; sc_signal< sc_lv<1> > tmp_27_fu_682_p3; sc_signal< sc_lv<1> > tmp_28_fu_690_p3; sc_signal< sc_lv<1> > tmp_29_fu_698_p3; sc_signal< sc_lv<1> > tmp_30_fu_706_p3; sc_signal< sc_lv<1> > tmp_31_fu_714_p3; sc_signal< sc_lv<1> > trunc_ln174_fu_722_p1; sc_signal< sc_lv<1> > tmp_32_fu_726_p3; sc_signal< sc_lv<1> > tmp_33_fu_734_p3; sc_signal< sc_lv<1> > tmp_34_fu_742_p3; sc_signal< sc_lv<1> > tmp_35_fu_750_p3; sc_signal< sc_lv<1> > tmp_36_fu_758_p3; sc_signal< sc_lv<1> > tmp_37_fu_766_p3; sc_signal< sc_lv<1> > tmp_38_fu_774_p3; sc_signal< sc_lv<1> > tmp_39_fu_782_p3; sc_signal< sc_lv<1> > tmp_40_fu_790_p3; sc_signal< sc_lv<1> > tmp_41_fu_798_p3; sc_signal< sc_lv<1> > tmp_42_fu_806_p3; sc_signal< sc_lv<1> > tmp_43_fu_814_p3; sc_signal< sc_lv<1> > tmp_44_fu_822_p3; sc_signal< sc_lv<1> > tmp_45_fu_830_p3; sc_signal< sc_lv<1> > tmp_46_fu_838_p3; sc_signal< sc_lv<1> > tmp_47_fu_846_p3; sc_signal< sc_lv<1> > tmp_48_fu_854_p3; sc_signal< sc_lv<1> > tmp_49_fu_862_p3; sc_signal< sc_lv<1> > tmp_50_fu_870_p3; sc_signal< sc_lv<1> > tmp_51_fu_878_p3; sc_signal< sc_lv<1> > tmp_52_fu_886_p3; sc_signal< sc_lv<1> > tmp_53_fu_894_p3; sc_signal< sc_lv<1> > tmp_54_fu_902_p3; sc_signal< sc_lv<1> > tmp_55_fu_910_p3; sc_signal< sc_lv<1> > tmp_56_fu_918_p3; sc_signal< sc_lv<1> > tmp_57_fu_926_p3; sc_signal< sc_lv<1> > tmp_58_fu_934_p3; sc_signal< sc_lv<1> > tmp_59_fu_942_p3; sc_signal< sc_lv<1> > tmp_60_fu_950_p3; sc_signal< sc_lv<1> > tmp_61_fu_958_p3; sc_signal< sc_lv<1> > tmp_62_fu_966_p3; sc_signal< sc_lv<1> > tmp_63_fu_974_p3; sc_signal< sc_lv<1> > tmp_64_fu_982_p3; sc_signal< sc_lv<1> > tmp_65_fu_990_p3; sc_signal< sc_lv<1> > tmp_66_fu_998_p3; sc_signal< sc_lv<1> > tmp_67_fu_1006_p3; sc_signal< sc_lv<1> > tmp_68_fu_1014_p3; sc_signal< sc_lv<1> > tmp_69_fu_1022_p3; sc_signal< sc_lv<1> > tmp_70_fu_1030_p3; sc_signal< sc_lv<1> > tmp_73_fu_1190_p3; sc_signal< sc_lv<1> > tmp_72_fu_1182_p3; sc_signal< sc_lv<1> > tmp_74_fu_1198_p3; sc_signal< sc_lv<1> > tmp_75_fu_1206_p3; sc_signal< sc_lv<1> > tmp_76_fu_1214_p3; sc_signal< sc_lv<1> > tmp_77_fu_1222_p3; sc_signal< sc_lv<1> > tmp_78_fu_1230_p3; sc_signal< sc_lv<1> > tmp_79_fu_1238_p3; sc_signal< sc_lv<1> > tmp_71_fu_1174_p3; sc_signal< sc_lv<1> > tmp_80_fu_1246_p3; sc_signal< sc_lv<1> > tmp_81_fu_1254_p3; sc_signal< sc_lv<1> > tmp_82_fu_1262_p3; sc_signal< sc_lv<1> > tmp_83_fu_1270_p3; sc_signal< sc_lv<1> > tmp_84_fu_1278_p3; sc_signal< sc_lv<1> > tmp_85_fu_1286_p3; sc_signal< sc_lv<1> > tmp_86_fu_1294_p3; sc_signal< sc_lv<1> > tmp_87_fu_1302_p3; sc_signal< sc_lv<1> > tmp_88_fu_1310_p3; sc_signal< sc_lv<1> > tmp_89_fu_1318_p3; sc_signal< sc_lv<1> > tmp_90_fu_1326_p3; sc_signal< sc_lv<1> > tmp_91_fu_1334_p3; sc_signal< sc_lv<1> > tmp_92_fu_1342_p3; sc_signal< sc_lv<1> > tmp_93_fu_1350_p3; sc_signal< sc_lv<1> > tmp_94_fu_1358_p3; sc_signal< sc_lv<1> > tmp_95_fu_1366_p3; sc_signal< sc_lv<1> > tmp_96_fu_1374_p3; sc_signal< sc_lv<1> > tmp_97_fu_1382_p3; sc_signal< sc_lv<1> > tmp_98_fu_1390_p3; sc_signal< sc_lv<1> > tmp_99_fu_1398_p3; sc_signal< sc_lv<1> > tmp_100_fu_1406_p3; sc_signal< sc_lv<1> > tmp_101_fu_1414_p3; sc_signal< sc_lv<1> > tmp_102_fu_1422_p3; sc_signal< sc_lv<1> > tmp_103_fu_1430_p3; sc_signal< sc_lv<1> > tmp_104_fu_1438_p3; sc_signal< sc_lv<1> > tmp_105_fu_1446_p3; sc_signal< sc_lv<1> > tmp_106_fu_1454_p3; sc_signal< sc_lv<1> > tmp_107_fu_1462_p3; sc_signal< sc_lv<1> > tmp_108_fu_1470_p3; sc_signal< sc_lv<1> > tmp_109_fu_1478_p3; sc_signal< sc_lv<1> > tmp_110_fu_1486_p3; sc_signal< sc_lv<1> > tmp_111_fu_1494_p3; sc_signal< sc_lv<1> > tmp_112_fu_1502_p3; sc_signal< sc_lv<1> > tmp_113_fu_1510_p3; sc_signal< sc_lv<1> > tmp_114_fu_1518_p3; sc_signal< sc_lv<1> > tmp_115_fu_1526_p3; sc_signal< sc_lv<1> > tmp_116_fu_1534_p3; sc_signal< sc_lv<1> > tmp_117_fu_1542_p3; sc_signal< sc_lv<1> > tmp_118_fu_1550_p3; sc_signal< sc_lv<1> > tmp_119_fu_1558_p3; sc_signal< sc_lv<1> > tmp_120_fu_1566_p3; sc_signal< sc_lv<1> > tmp_121_fu_1574_p3; sc_signal< sc_lv<1> > tmp_122_fu_1582_p3; sc_signal< sc_lv<1> > tmp_123_fu_1590_p3; sc_signal< sc_lv<1> > tmp_124_fu_1598_p3; sc_signal< sc_lv<1> > tmp_125_fu_1606_p3; sc_signal< sc_lv<1> > tmp_126_fu_1614_p3; sc_signal< sc_lv<1> > empty_8_fu_1770_p2; sc_signal< sc_lv<1> > empty_7_fu_1764_p2; sc_signal< sc_lv<1> > empty_10_fu_1782_p2; sc_signal< sc_lv<1> > empty_9_fu_1776_p2; sc_signal< sc_lv<1> > empty_12_fu_1794_p2; sc_signal< sc_lv<1> > empty_11_fu_1788_p2; sc_signal< sc_lv<26> > trunc_ln203_fu_1806_p1; sc_signal< sc_lv<2> > tmp_s_fu_1810_p4; sc_signal< sc_lv<26> > trunc_ln204_fu_1828_p1; sc_signal< sc_lv<2> > tmp_17_fu_1832_p4; sc_signal< sc_lv<27> > trunc_ln197_fu_1868_p1; sc_signal< sc_lv<1> > tmp_127_fu_1860_p3; sc_signal< sc_lv<27> > trunc_ln198_fu_1888_p1; sc_signal< sc_lv<1> > tmp_128_fu_1880_p3; sc_signal< sc_lv<6> > sub_ln218_fu_1949_p2; sc_signal< sc_lv<56> > zext_ln218_1_fu_1955_p1; sc_signal< sc_lv<56> > lshr_ln218_fu_1959_p2; sc_signal< sc_lv<1> > trunc_ln218_fu_1964_p1; sc_signal< sc_lv<5> > sub_ln232_fu_2012_p2; sc_signal< sc_lv<6> > sub_ln229_fu_2023_p2; sc_signal< sc_lv<32> > zext_ln229_1_fu_2029_p1; sc_signal< sc_lv<32> > lshr_ln229_fu_2033_p2; sc_signal< sc_lv<63> > trunc_ln229_1_fu_2043_p1; sc_signal< sc_lv<1> > trunc_ln229_fu_2039_p1; sc_signal< sc_lv<47> > trunc_ln232_3_fu_2067_p1; sc_signal< sc_lv<47> > trunc_ln232_2_fu_2063_p1; sc_signal< sc_lv<48> > trunc_ln232_1_fu_2059_p1; sc_signal< sc_lv<48> > trunc_ln232_fu_2055_p1; sc_signal< sc_lv<3> > trunc_ln240_fu_2095_p1; sc_signal< sc_lv<6> > shl_ln_fu_2099_p3; sc_signal< sc_lv<4> > shl_ln240_fu_2111_p2; sc_signal< sc_lv<7> > zext_ln240_fu_2107_p1; sc_signal< sc_lv<7> > zext_ln240_2_fu_2121_p1; sc_signal< sc_lv<5> > shl_ln240_1_fu_2131_p3; sc_signal< sc_lv<6> > zext_ln240_1_fu_2117_p1; sc_signal< sc_lv<6> > sub_ln240_1_fu_2143_p2; sc_signal< sc_lv<6> > zext_ln240_5_fu_2139_p1; sc_signal< sc_lv<6> > sub_ln243_fu_2155_p2; sc_signal< sc_lv<32> > sext_ln240_fu_2167_p1; sc_signal< sc_lv<48> > zext_ln240_4_fu_2174_p1; sc_signal< sc_lv<48> > lshr_ln240_fu_2178_p2; sc_signal< sc_lv<48> > and_ln240_fu_2184_p2; sc_signal< sc_lv<48> > zext_ln240_6_fu_2189_p1; sc_signal< sc_lv<48> > lshr_ln240_1_fu_2192_p2; sc_signal< sc_lv<1> > tmp_129_fu_2202_p3; sc_signal< sc_lv<1> > trunc_ln240_1_fu_2198_p1; sc_signal< sc_lv<47> > zext_ln240_3_fu_2170_p1; sc_signal< sc_lv<47> > lshr_ln243_fu_2226_p2; sc_signal< sc_lv<47> > and_ln243_fu_2232_p2; sc_signal< sc_lv<47> > zext_ln243_fu_2237_p1; sc_signal< sc_lv<3> > tmp_15_fu_2216_p4; sc_signal< sc_lv<1> > or_ln241_fu_2210_p2; sc_signal< sc_lv<8> > tmp_20_fu_2246_p4; sc_signal< sc_lv<47> > lshr_ln243_1_fu_2240_p2; sc_signal< sc_lv<8> > trunc_ln246_fu_2260_p1; sc_signal< sc_lv<9> > sext_ln246_1_fu_2264_p1; sc_signal< sc_lv<9> > sext_ln246_fu_2256_p1; sc_signal< sc_lv<9> > add_ln246_fu_2268_p2; sc_signal< sc_lv<10> > tmp_24_fu_2278_p3; sc_signal< sc_lv<11> > sext_ln246_2_fu_2274_p1; sc_signal< sc_lv<11> > zext_ln246_fu_2286_p1; sc_signal< sc_lv<28> > trunc_ln246_1_fu_2300_p1; sc_signal< sc_lv<6> > sub_ln254_fu_2344_p2; sc_signal< sc_lv<32> > zext_ln254_1_fu_2350_p1; sc_signal< sc_lv<32> > lshr_ln254_fu_2354_p2; sc_signal< sc_lv<1> > trunc_ln254_fu_2360_p1; sc_signal< sc_lv<7> > sub_ln270_fu_2392_p2; sc_signal< sc_lv<64> > zext_ln270_fu_2398_p1; sc_signal< sc_lv<64> > lshr_ln270_fu_2402_p2; sc_signal< sc_lv<1> > trunc_ln270_fu_2407_p1; sc_signal< sc_lv<17> > ap_NS_fsm; static const sc_logic ap_const_logic_1; static const sc_logic ap_const_logic_0; static const sc_lv<17> ap_ST_fsm_state1; static const sc_lv<17> ap_ST_fsm_state2; static const sc_lv<17> ap_ST_fsm_state3; static const sc_lv<17> ap_ST_fsm_state4; static const sc_lv<17> ap_ST_fsm_state5; static const sc_lv<17> ap_ST_fsm_state6; static const sc_lv<17> ap_ST_fsm_state7; static const sc_lv<17> ap_ST_fsm_state8; static const sc_lv<17> ap_ST_fsm_state9; static const sc_lv<17> ap_ST_fsm_state10; static const sc_lv<17> ap_ST_fsm_state11; static const sc_lv<17> ap_ST_fsm_state12; static const sc_lv<17> ap_ST_fsm_state13; static const sc_lv<17> ap_ST_fsm_state14; static const sc_lv<17> ap_ST_fsm_state15; static const sc_lv<17> ap_ST_fsm_state16; static const sc_lv<17> ap_ST_fsm_state17; static const sc_lv<32> ap_const_lv32_0; static const sc_lv<32> ap_const_lv32_1; static const sc_lv<1> ap_const_lv1_0; static const sc_lv<32> ap_const_lv32_2; static const sc_lv<32> ap_const_lv32_3; static const sc_lv<32> ap_const_lv32_4; static const sc_lv<32> ap_const_lv32_5; static const sc_lv<1> ap_const_lv1_1; static const sc_lv<32> ap_const_lv32_6; static const sc_lv<32> ap_const_lv32_7; static const sc_lv<32> ap_const_lv32_8; static const sc_lv<32> ap_const_lv32_9; static const sc_lv<32> ap_const_lv32_A; static const sc_lv<32> ap_const_lv32_B; static const sc_lv<32> ap_const_lv32_D; static const sc_lv<32> ap_const_lv32_E; static const sc_lv<32> ap_const_lv32_F; static const sc_lv<32> ap_const_lv32_10; static const sc_lv<5> ap_const_lv5_0; static const sc_lv<64> ap_const_lv64_0; static const sc_lv<6> ap_const_lv6_0; static const sc_lv<4> ap_const_lv4_0; static const sc_lv<32> ap_const_lv32_C; static const sc_lv<7> ap_const_lv7_0; static const sc_lv<32> ap_const_lv32_16; static const sc_lv<32> ap_const_lv32_1E; static const sc_lv<32> ap_const_lv32_26; static const sc_lv<32> ap_const_lv32_2E; static const sc_lv<32> ap_const_lv32_36; static const sc_lv<32> ap_const_lv32_3E; static const sc_lv<32> ap_const_lv32_14; static const sc_lv<32> ap_const_lv32_1C; static const sc_lv<32> ap_const_lv32_24; static const sc_lv<32> ap_const_lv32_2C; static const sc_lv<32> ap_const_lv32_34; static const sc_lv<32> ap_const_lv32_3C; static const sc_lv<32> ap_const_lv32_12; static const sc_lv<32> ap_const_lv32_1A; static const sc_lv<32> ap_const_lv32_22; static const sc_lv<32> ap_const_lv32_2A; static const sc_lv<32> ap_const_lv32_32; static const sc_lv<32> ap_const_lv32_3A; static const sc_lv<32> ap_const_lv32_18; static const sc_lv<32> ap_const_lv32_20; static const sc_lv<32> ap_const_lv32_28; static const sc_lv<32> ap_const_lv32_30; static const sc_lv<32> ap_const_lv32_38; static const sc_lv<32> ap_const_lv32_17; static const sc_lv<32> ap_const_lv32_1F; static const sc_lv<32> ap_const_lv32_27; static const sc_lv<32> ap_const_lv32_2F; static const sc_lv<32> ap_const_lv32_37; static const sc_lv<32> ap_const_lv32_3F; static const sc_lv<32> ap_const_lv32_15; static const sc_lv<32> ap_const_lv32_1D; static const sc_lv<32> ap_const_lv32_25; static const sc_lv<32> ap_const_lv32_2D; static const sc_lv<32> ap_const_lv32_35; static const sc_lv<32> ap_const_lv32_3D; static const sc_lv<32> ap_const_lv32_13; static const sc_lv<32> ap_const_lv32_1B; static const sc_lv<32> ap_const_lv32_23; static const sc_lv<32> ap_const_lv32_2B; static const sc_lv<32> ap_const_lv32_33; static const sc_lv<32> ap_const_lv32_3B; static const sc_lv<32> ap_const_lv32_11; static const sc_lv<32> ap_const_lv32_19; static const sc_lv<32> ap_const_lv32_21; static const sc_lv<32> ap_const_lv32_29; static const sc_lv<32> ap_const_lv32_31; static const sc_lv<32> ap_const_lv32_39; static const sc_lv<5> ap_const_lv5_10; static const sc_lv<5> ap_const_lv5_1; static const sc_lv<5> ap_const_lv5_F; static const sc_lv<5> ap_const_lv5_8; static const sc_lv<6> ap_const_lv6_30; static const sc_lv<6> ap_const_lv6_1; static const sc_lv<6> ap_const_lv6_38; static const sc_lv<6> ap_const_lv6_20; static const sc_lv<4> ap_const_lv4_8; static const sc_lv<4> ap_const_lv4_1; static const sc_lv<3> ap_const_lv3_0; static const sc_lv<2> ap_const_lv2_0; static const sc_lv<6> ap_const_lv6_2A; static const sc_lv<6> ap_const_lv6_2B; static const sc_lv<48> ap_const_lv48_840000000000; static const sc_lv<47> ap_const_lv47_780000000000; static const sc_lv<7> ap_const_lv7_40; static const sc_lv<7> ap_const_lv7_1; static const bool ap_const_boolean_1; // Thread declarations void thread_ap_clk_no_reset_(); void thread_C_2_fu_1820_p3(); void thread_C_3_fu_1872_p3(); void thread_C_fu_1622_p29(); void thread_D_2_fu_1842_p3(); void thread_D_3_fu_1892_p3(); void thread_D_fu_1682_p29(); void thread_E_address0(); void thread_E_ce0(); void thread_L_fu_1038_p33(); void thread_PC2_address0(); void thread_PC2_ce0(); void thread_PI_address0(); void thread_PI_ce0(); void thread_P_address0(); void thread_P_ce0(); void thread_R_1_fu_2338_p2(); void thread_R_fu_1106_p33(); void thread_S_address0(); void thread_S_ce0(); void thread_add_ln246_1_fu_2290_p2(); void thread_add_ln246_fu_2268_p2(); void thread_and_ln240_fu_2184_p2(); void thread_and_ln243_fu_2232_p2(); void thread_ap_CS_fsm_state1(); void thread_ap_CS_fsm_state10(); void thread_ap_CS_fsm_state11(); void thread_ap_CS_fsm_state12(); void thread_ap_CS_fsm_state13(); void thread_ap_CS_fsm_state14(); void thread_ap_CS_fsm_state15(); void thread_ap_CS_fsm_state16(); void thread_ap_CS_fsm_state17(); void thread_ap_CS_fsm_state2(); void thread_ap_CS_fsm_state3(); void thread_ap_CS_fsm_state4(); void thread_ap_CS_fsm_state5(); void thread_ap_CS_fsm_state6(); void thread_ap_CS_fsm_state7(); void thread_ap_CS_fsm_state8(); void thread_ap_CS_fsm_state9(); void thread_ap_done(); void thread_ap_idle(); void thread_ap_ready(); void thread_ap_return(); void thread_empty_10_fu_1782_p2(); void thread_empty_11_fu_1788_p2(); void thread_empty_12_fu_1794_p2(); void thread_empty_13_fu_1800_p2(); void thread_empty_7_fu_1764_p2(); void thread_empty_8_fu_1770_p2(); void thread_empty_9_fu_1776_p2(); void thread_f_function_res_fu_2364_p3(); void thread_i_1_fu_1758_p2(); void thread_i_5_fu_1981_p2(); void thread_i_fu_2377_p2(); void thread_icmp_ln192_fu_1752_p2(); void thread_icmp_ln216_fu_1928_p2(); void thread_icmp_ln223_fu_1975_p2(); void thread_icmp_ln227_fu_1995_p2(); void thread_icmp_ln235_fu_2083_p2(); void thread_icmp_ln252_fu_2317_p2(); void thread_icmp_ln267_fu_2371_p2(); void thread_inv_init_perm_res_fu_2411_p3(); void thread_j_4_fu_1934_p2(); void thread_j_5_fu_2089_p2(); void thread_j_6_fu_2323_p2(); void thread_j_fu_2001_p2(); void thread_lshr_ln218_fu_1959_p2(); void thread_lshr_ln229_fu_2033_p2(); void thread_lshr_ln240_1_fu_2192_p2(); void thread_lshr_ln240_fu_2178_p2(); void thread_lshr_ln243_1_fu_2240_p2(); void thread_lshr_ln243_fu_2226_p2(); void thread_lshr_ln254_fu_2354_p2(); void thread_lshr_ln270_fu_2402_p2(); void thread_or_ln241_fu_2210_p2(); void thread_or_ln_fu_1968_p3(); void thread_pre_output_fu_1987_p3(); void thread_s_input_fu_2047_p3(); void thread_s_output_fu_2304_p3(); void thread_sext_ln240_fu_2167_p1(); void thread_sext_ln246_1_fu_2264_p1(); void thread_sext_ln246_2_fu_2274_p1(); void thread_sext_ln246_3_fu_2296_p1(); void thread_sext_ln246_fu_2256_p1(); void thread_shl_ln240_1_fu_2131_p3(); void thread_shl_ln240_fu_2111_p2(); void thread_shl_ln_fu_2099_p3(); void thread_sub_key_address0(); void thread_sub_key_ce0(); void thread_sub_key_we0(); void thread_sub_ln218_fu_1949_p2(); void thread_sub_ln229_fu_2023_p2(); void thread_sub_ln232_fu_2012_p2(); void thread_sub_ln240_1_fu_2143_p2(); void thread_sub_ln240_2_fu_2149_p2(); void thread_sub_ln240_fu_2125_p2(); void thread_sub_ln243_1_fu_2161_p2(); void thread_sub_ln243_fu_2155_p2(); void thread_sub_ln254_fu_2344_p2(); void thread_sub_ln270_fu_2392_p2(); void thread_tmp_100_fu_1406_p3(); void thread_tmp_101_fu_1414_p3(); void thread_tmp_102_fu_1422_p3(); void thread_tmp_103_fu_1430_p3(); void thread_tmp_104_fu_1438_p3(); void thread_tmp_105_fu_1446_p3(); void thread_tmp_106_fu_1454_p3(); void thread_tmp_107_fu_1462_p3(); void thread_tmp_108_fu_1470_p3(); void thread_tmp_109_fu_1478_p3(); void thread_tmp_10_fu_594_p3(); void thread_tmp_110_fu_1486_p3(); void thread_tmp_111_fu_1494_p3(); void thread_tmp_112_fu_1502_p3(); void thread_tmp_113_fu_1510_p3(); void thread_tmp_114_fu_1518_p3(); void thread_tmp_115_fu_1526_p3(); void thread_tmp_116_fu_1534_p3(); void thread_tmp_117_fu_1542_p3(); void thread_tmp_118_fu_1550_p3(); void thread_tmp_119_fu_1558_p3(); void thread_tmp_11_fu_1920_p3(); void thread_tmp_120_fu_1566_p3(); void thread_tmp_121_fu_1574_p3(); void thread_tmp_122_fu_1582_p3(); void thread_tmp_123_fu_1590_p3(); void thread_tmp_124_fu_1598_p3(); void thread_tmp_125_fu_1606_p3(); void thread_tmp_126_fu_1614_p3(); void thread_tmp_127_fu_1860_p3(); void thread_tmp_128_fu_1880_p3(); void thread_tmp_129_fu_2202_p3(); void thread_tmp_12_fu_602_p3(); void thread_tmp_13_fu_610_p3(); void thread_tmp_14_fu_618_p3(); void thread_tmp_15_fu_2216_p4(); void thread_tmp_16_fu_626_p3(); void thread_tmp_17_fu_1832_p4(); void thread_tmp_18_fu_634_p3(); void thread_tmp_19_fu_642_p3(); void thread_tmp_20_fu_2246_p4(); void thread_tmp_21_fu_650_p3(); void thread_tmp_22_fu_658_p3(); void thread_tmp_23_fu_666_p3(); void thread_tmp_24_fu_2278_p3(); void thread_tmp_26_fu_674_p3(); void thread_tmp_27_fu_682_p3(); void thread_tmp_28_fu_690_p3(); void thread_tmp_29_fu_698_p3(); void thread_tmp_2_fu_530_p3(); void thread_tmp_30_fu_706_p3(); void thread_tmp_31_fu_714_p3(); void thread_tmp_32_fu_726_p3(); void thread_tmp_33_fu_734_p3(); void thread_tmp_34_fu_742_p3(); void thread_tmp_35_fu_750_p3(); void thread_tmp_36_fu_758_p3(); void thread_tmp_37_fu_766_p3(); void thread_tmp_38_fu_774_p3(); void thread_tmp_39_fu_782_p3(); void thread_tmp_3_fu_538_p3(); void thread_tmp_40_fu_790_p3(); void thread_tmp_41_fu_798_p3(); void thread_tmp_42_fu_806_p3(); void thread_tmp_43_fu_814_p3(); void thread_tmp_44_fu_822_p3(); void thread_tmp_45_fu_830_p3(); void thread_tmp_46_fu_838_p3(); void thread_tmp_47_fu_846_p3(); void thread_tmp_48_fu_854_p3(); void thread_tmp_49_fu_862_p3(); void thread_tmp_4_fu_546_p3(); void thread_tmp_50_fu_870_p3(); void thread_tmp_51_fu_878_p3(); void thread_tmp_52_fu_886_p3(); void thread_tmp_53_fu_894_p3(); void thread_tmp_54_fu_902_p3(); void thread_tmp_55_fu_910_p3(); void thread_tmp_56_fu_918_p3(); void thread_tmp_57_fu_926_p3(); void thread_tmp_58_fu_934_p3(); void thread_tmp_59_fu_942_p3(); void thread_tmp_5_fu_554_p3(); void thread_tmp_60_fu_950_p3(); void thread_tmp_61_fu_958_p3(); void thread_tmp_62_fu_966_p3(); void thread_tmp_63_fu_974_p3(); void thread_tmp_64_fu_982_p3(); void thread_tmp_65_fu_990_p3(); void thread_tmp_66_fu_998_p3(); void thread_tmp_67_fu_1006_p3(); void thread_tmp_68_fu_1014_p3(); void thread_tmp_69_fu_1022_p3(); void thread_tmp_6_fu_562_p3(); void thread_tmp_70_fu_1030_p3(); void thread_tmp_71_fu_1174_p3(); void thread_tmp_72_fu_1182_p3(); void thread_tmp_73_fu_1190_p3(); void thread_tmp_74_fu_1198_p3(); void thread_tmp_75_fu_1206_p3(); void thread_tmp_76_fu_1214_p3(); void thread_tmp_77_fu_1222_p3(); void thread_tmp_78_fu_1230_p3(); void thread_tmp_79_fu_1238_p3(); void thread_tmp_7_fu_570_p3(); void thread_tmp_80_fu_1246_p3(); void thread_tmp_81_fu_1254_p3(); void thread_tmp_82_fu_1262_p3(); void thread_tmp_83_fu_1270_p3(); void thread_tmp_84_fu_1278_p3(); void thread_tmp_85_fu_1286_p3(); void thread_tmp_86_fu_1294_p3(); void thread_tmp_87_fu_1302_p3(); void thread_tmp_88_fu_1310_p3(); void thread_tmp_89_fu_1318_p3(); void thread_tmp_8_fu_578_p3(); void thread_tmp_90_fu_1326_p3(); void thread_tmp_91_fu_1334_p3(); void thread_tmp_92_fu_1342_p3(); void thread_tmp_93_fu_1350_p3(); void thread_tmp_94_fu_1358_p3(); void thread_tmp_95_fu_1366_p3(); void thread_tmp_96_fu_1374_p3(); void thread_tmp_97_fu_1382_p3(); void thread_tmp_98_fu_1390_p3(); void thread_tmp_99_fu_1398_p3(); void thread_tmp_9_fu_586_p3(); void thread_tmp_s_fu_1810_p4(); void thread_trunc_ln174_fu_722_p1(); void thread_trunc_ln197_fu_1868_p1(); void thread_trunc_ln198_fu_1888_p1(); void thread_trunc_ln203_fu_1806_p1(); void thread_trunc_ln204_fu_1828_p1(); void thread_trunc_ln218_1_fu_1945_p1(); void thread_trunc_ln218_fu_1964_p1(); void thread_trunc_ln229_1_fu_2043_p1(); void thread_trunc_ln229_fu_2039_p1(); void thread_trunc_ln232_1_fu_2059_p1(); void thread_trunc_ln232_2_fu_2063_p1(); void thread_trunc_ln232_3_fu_2067_p1(); void thread_trunc_ln232_fu_2055_p1(); void thread_trunc_ln240_1_fu_2198_p1(); void thread_trunc_ln240_fu_2095_p1(); void thread_trunc_ln246_1_fu_2300_p1(); void thread_trunc_ln246_fu_2260_p1(); void thread_trunc_ln254_1_fu_2334_p1(); void thread_trunc_ln254_fu_2360_p1(); void thread_trunc_ln270_1_fu_2388_p1(); void thread_trunc_ln270_fu_2407_p1(); void thread_xor_ln232_1_fu_2077_p2(); void thread_xor_ln232_fu_2071_p2(); void thread_zext_ln214_fu_1910_p1(); void thread_zext_ln218_1_fu_1955_p1(); void thread_zext_ln218_fu_1940_p1(); void thread_zext_ln229_1_fu_2029_p1(); void thread_zext_ln229_fu_2007_p1(); void thread_zext_ln232_fu_2018_p1(); void thread_zext_ln240_1_fu_2117_p1(); void thread_zext_ln240_2_fu_2121_p1(); void thread_zext_ln240_3_fu_2170_p1(); void thread_zext_ln240_4_fu_2174_p1(); void thread_zext_ln240_5_fu_2139_p1(); void thread_zext_ln240_6_fu_2189_p1(); void thread_zext_ln240_fu_2107_p1(); void thread_zext_ln243_fu_2237_p1(); void thread_zext_ln246_fu_2286_p1(); void thread_zext_ln254_1_fu_2350_p1(); void thread_zext_ln254_fu_2329_p1(); void thread_zext_ln270_1_fu_2383_p1(); void thread_zext_ln270_fu_2398_p1(); void thread_ap_NS_fsm(); void thread_hdltv_gen(); }; } using namespace ap_rtl; #endif
f6d277f18a13a5d25a0fe8f1e950e5b0bfe59710
77d1bd5ae4f8423bfea3119c3260b3b34de1f652
/AnalyzeNystagmus2.cpp
54d968bbb751d0d609b1168316fcb31563f4b318
[]
no_license
dlsyaim/sm-eye-app
c6b20303e10c8f42c12f64a767d77a2cbac9f8f3
3058da8998683c4453f1470a1f5e4c047ba837a1
refs/heads/master
2016-09-06T05:28:48.892101
2013-04-17T20:53:33
2013-04-17T20:53:33
37,705,615
0
0
null
null
null
null
UHC
C++
false
false
16,114
cpp
AnalyzeNystagmus2.cpp
#include "StdAfx.h" #include ".\analyzenystagmus2.h" #include "corwldefines.h" #include "math.h" CAnalyzeNystagmus2::CAnalyzeNystagmus2(void) { } CAnalyzeNystagmus2::~CAnalyzeNystagmus2(void) { this->deleteAllNystagmus(); } void CAnalyzeNystagmus2::deleteAllNystagmus() { if(!m_listNystagmus.IsEmpty()) { POSITION pos1, pos2; double val = 0; for(pos1 = this->m_listNystagmus.GetHeadPosition(); (pos2 = pos1) != NULL; ) { structNystag* pNys = m_listNystagmus.GetNext(pos1); if(pNys) delete pNys; } this->m_listNystagmus.RemoveAll(); } } void CAnalyzeNystagmus2::analyze(double* pEye, unsigned long count) { EA_Nystagmus analNys; analNys.init(); int nRtn; //list 초기화 this->deleteAllNystagmus(); int nysCount = 0; for(unsigned long i=0; i<count; i++) { nRtn = analNys.putSignal(pEye[i]); if(nRtn) { nysCount++; structNystag* pNys = new structNystag; *pNys = analNys.m_structCurrentNystag; this->m_listNystagmus.AddTail(pNys); i = pNys->endI+1; } } } void CAnalyzeNystagmus2::analyze2(double* pEye, unsigned long count) { //list 초기화 this->deleteAllNystagmus(); int idx = 0, endIdx = 0, startIdx = 0; double maxD = 0; double thresRatio = 2, thres = 0; unsigned long prevEndIdx = 0; for(int i=10; i<count-10; i++) { /////////////////////////////positive slow phase if( (pEye[i-1] < pEye[i]) && (pEye[i] >= pEye[i+1]) ) { idx = i; maxD = 0; // fast phase의 negative가 끝나는 곳을 찾는다. while( (pEye[idx] >= pEye[idx+1]) && (idx<count-4)) { // 그 중 diff가 max가 되는 곳을 찾는다. if (maxD < -1*(pEye[idx+2]-pEye[idx]) ) maxD = -1*(pEye[idx+2]-pEye[idx]); idx = idx+1; } endIdx = idx; // fast phase가 2point 이상 지속된다면 idx = i; if(endIdx-i >= 2) { // 반대방향으로 search한다. // slow phase의 끝을 찾는다. thres = maxD/thresRatio; while( (fabs(pEye[idx]-pEye[idx-2]) < thres) && (idx>3) ) idx = idx-1; } startIdx = idx; //slow phase가 충분히 지속되고, slow phase와 fast phase의 부호가 다르다면 if( (i-startIdx > 10) && ((pEye[endIdx]-pEye[i])*(pEye[i]-pEye[startIdx])<0) && (startIdx > prevEndIdx)) // 이전 nystagmus end와 겹치지 않아야 한다. { structNystag* pNys = new structNystag; //양쪽 10%씩 잘라준다. pNys->vel = (pEye[i]-pEye[startIdx]) / (i-startIdx) * 120; pNys->startI = startIdx + int((i-startIdx)*0.1); pNys->endI = i - int((i-startIdx)*0.1); this->m_listNystagmus.AddTail(pNys); prevEndIdx = pNys->endI; } } /////////////////////////////negative slow phase if( (pEye[i-1] > pEye[i]) && (pEye[i] >= pEye[i+1]) ) { idx = i; maxD = 0; // fast phase의 positive가 끝나는 곳을 찾는다. while( (pEye[idx] <= pEye[idx+1]) && (idx<count-4)) { // 그 중 diff가 max가 되는 곳을 찾는다. if (maxD < pEye[idx+2]-pEye[idx] ) maxD = pEye[idx+2]-pEye[idx]; idx = idx+1; } endIdx = idx; // fast phase가 2point 이상 지속된다면 idx = i; if(endIdx-i >= 2) { // 반대방향으로 search한다. // slow phase의 끝을 찾는다. thres = maxD/thresRatio; while( (fabs(pEye[idx]-pEye[idx-2]) < thres) && (idx>3) ) idx = idx-1; } startIdx = idx; //slow phase가 충분히 지속되고, slow phase와 fast phase의 부호가 다르다면 if( (i-startIdx > 20) && ((pEye[endIdx]-pEye[i])*(pEye[i]-pEye[startIdx])<0) && (startIdx > prevEndIdx)) // 이전 nystagmus end와 겹치지 않아야 한다.) { structNystag* pNys = new structNystag; //양쪽 10%씩 잘라준다. pNys->vel = (pEye[i]-pEye[startIdx]) / (i-startIdx) * 120; pNys->startI = startIdx + int((i-startIdx)*0.1); pNys->endI = i - int((i-startIdx)*0.1); this->m_listNystagmus.AddTail(pNys); prevEndIdx = pNys->endI; } } } } CString CAnalyzeNystagmus2::getResultString() { CString strResult; return strResult; } int CAnalyzeNystagmus2::getCount(int nysType) { int count = 0; POSITION pos1, pos2; switch(nysType) { case ALL: count = int(this->m_listNystagmus.GetCount()); break; case POSI: for(pos1 = m_listNystagmus.GetHeadPosition(); (pos2 = pos1) != NULL; ) { structNystag* pNys = m_listNystagmus.GetNext(pos1); if(pNys->vel > 0) count++; } break; case NEGA: for(pos1 = m_listNystagmus.GetHeadPosition(); (pos2 = pos1) != NULL; ) { structNystag* pNys = m_listNystagmus.GetNext(pos1); if(pNys->vel < 0) count++; } break; default: break; } return count; } double CAnalyzeNystagmus2::getMean(int nysType) { double rtn = 0; POSITION pos1, pos2; double s = 0; int n = 0; switch(nysType) { case ALL: for(pos1 = m_listNystagmus.GetHeadPosition(); (pos2 = pos1) != NULL; ) { structNystag* pNys = m_listNystagmus.GetNext(pos1); s += pNys->vel; n++; } break; case POSI: for(pos1 = m_listNystagmus.GetHeadPosition(); (pos2 = pos1) != NULL; ) { structNystag* pNys = m_listNystagmus.GetNext(pos1); if(pNys->vel > 0) { s += pNys->vel; n++; } } break; case NEGA: for(pos1 = m_listNystagmus.GetHeadPosition(); (pos2 = pos1) != NULL; ) { structNystag* pNys = m_listNystagmus.GetNext(pos1); if(pNys->vel < 0) { s += pNys->vel; n++; } } break; default: break; } if(n) rtn = s/n; else rtn = 0; return rtn; } double CAnalyzeNystagmus2::getMax(int nysType) { double rtn = 0; POSITION pos1, pos2; double m = -1000000000; switch(nysType) { case ALL: for(pos1 = m_listNystagmus.GetHeadPosition(); (pos2 = pos1) != NULL; ) { structNystag* pNys = m_listNystagmus.GetNext(pos1); if(m < pNys->vel ) m = pNys->vel; } break; case POSI: for(pos1 = m_listNystagmus.GetHeadPosition(); (pos2 = pos1) != NULL; ) { structNystag* pNys = m_listNystagmus.GetNext(pos1); if((pNys->vel > 0) && (m < pNys->vel)) m = pNys->vel; } break; case NEGA: for(pos1 = m_listNystagmus.GetHeadPosition(); (pos2 = pos1) != NULL; ) { structNystag* pNys = m_listNystagmus.GetNext(pos1); if((pNys->vel < 0) && (m < pNys->vel)) m = pNys->vel; } break; default: break; } return m; } double CAnalyzeNystagmus2::getMin(int nysType) { double rtn = 0; POSITION pos1, pos2; double m = 100000; switch(nysType) { case ALL: for(pos1 = m_listNystagmus.GetHeadPosition(); (pos2 = pos1) != NULL; ) { structNystag* pNys = m_listNystagmus.GetNext(pos1); if(m > pNys->vel ) m = pNys->vel; } break; case POSI: for(pos1 = m_listNystagmus.GetHeadPosition(); (pos2 = pos1) != NULL; ) { structNystag* pNys = m_listNystagmus.GetNext(pos1); if((pNys->vel > 0) && (m > pNys->vel)) m = pNys->vel; } break; case NEGA: for(pos1 = m_listNystagmus.GetHeadPosition(); (pos2 = pos1) != NULL; ) { structNystag* pNys = m_listNystagmus.GetNext(pos1); if((pNys->vel < 0) && (m > pNys->vel)) m = pNys->vel; } break; default: break; } return m; } bool CAnalyzeNystagmus2::load(CString fname) { bool bRtn = false; CFile file; if(file.Open(fname, CFile::modeRead)) { //현재 DATA를 모두 지운다. this->deleteAllNystagmus(); unsigned char buf[256]; ::ZeroMemory(buf, 256); unsigned int count = (unsigned int)(file.GetLength()/256); for(unsigned int i=0; i<count; i++) { structNystag* pNystag = new structNystag; file.Read(buf, 256); ::memcpy(pNystag, buf, sizeof(structNystag)); this->m_listNystagmus.AddTail(pNystag); } file.Close(); bRtn = true; } return bRtn; } bool CAnalyzeNystagmus2::save(CString fname) { bool bRtn = false; CFile file; if(file.Open(fname, CFile::modeWrite | CFile::modeCreate)) { unsigned char buf[256]; ::ZeroMemory(buf, 256); POSITION pos1, pos2; double val = 0; for(pos1 = this->m_listNystagmus.GetHeadPosition(); (pos2 = pos1) != NULL; ) { structNystag* pNystag= m_listNystagmus.GetNext(pos1); memcpy(buf, pNystag, sizeof(structNystag)); file.Write(buf, 256); } file.Close(); bRtn = true; } return bRtn; } unsigned long CAnalyzeNystagmus2::getClosestNystagmus(double t) { //t에 가장 가까운 위치의 pursuit index를 return한다. unsigned long idx = -1; double m = 1000000000000; unsigned long count = 0; if(m_listNystagmus.GetCount()) { POSITION pos1, pos2; double val = 0; for(pos1 = this->m_listNystagmus.GetHeadPosition(); (pos2 = pos1) != NULL; ) { structNystag* pNys = m_listNystagmus.GetNext(pos1); double d = fabs(t*FRAMERATE-(pNys->startI+pNys->endI)/2); if(d < m) { m = d; idx = count; } count++; } } return idx; } unsigned long CAnalyzeNystagmus2::addNystagmus2(unsigned long idx, double* pEye, unsigned long count) { //좌우의 nystagmus를 찾아 fast phase의 속도를 찾는다. // fast phase 를 threshold로 주어진 위치 좌우의 fast phase 를 찾는다. // 위치를 찾는다. //POSITION posPrev, posNext; POSITION pos; POSITION posNext; structNystag* pNysPrev = NULL; structNystag* pNysNext = NULL; structNystag* pNys = NULL; int nysIdx = 0; if(int nysCount = m_listNystagmus.GetCount()) { pos = m_listNystagmus.GetHeadPosition(); for(int i=0; i<nysCount; i++) { pNys = m_listNystagmus.GetNext(pos); if( (pNys->startI < idx ) && (idx < pNys->endI) ) { ::AfxMessageBox("Overlapped"); return -1; } } double val = 0; pos = m_listNystagmus.GetHeadPosition(); for(int i=0; i<nysCount; i++) { pNys = m_listNystagmus.GetNext(pos); //이전 nystagmus를 찾는다. if( pNys->endI < idx) { //전에 찾아진게 있다면 위치를 비교한다. if(pNysPrev) { if(pNys->endI > pNysPrev->endI) { pNysPrev = pNys ; //넣을 위치 posNext = pos; } } // 없다면 이전 nystagmus로 등록 else { pNysPrev = pNys; posNext = pos; } nysIdx++; } //이후 nystagmus를 찾는다. if( idx < pNys->startI) { // 전에 찾아진게 있다면 if(pNysNext) { if(pNys->startI < pNysNext->startI) pNysNext = pNys; } else pNysNext = pNys; } //그 위치에 nystamus가 있는지도 확인한다. if((pNys->startI < idx) && (idx<pNys->endI)) return -1; } } // fast phase의 속도를 구한다. int M = 2; double prevFPV = 0, nextFPV = 0; if(pNysPrev) { for(int i=pNysPrev->endI; i<min(pNysPrev->endI + 30, count-M-5); i++) { if(abs(pEye[i+M]-pEye[i]) > prevFPV) prevFPV = abs(pEye[i+M]-pEye[i]); } } if(pNysNext) { for(int i=pNysNext->endI; i<min(pNysNext->endI + 30, count-M-5); i++) { if(abs(pEye[i+M]-pEye[i]) > nextFPV) nextFPV = abs(pEye[i+M]-pEye[i]); } } //threshold 값을 결정 structNystag* pNysFound = NULL; double thres = 0; if(prevFPV || nextFPV) { thres = 0.3*max(prevFPV ? prevFPV : 0, nextFPV ? nextFPV : 0); //thres = 0.3*min(prevFPV ? prevFPV : 100000, nextFPV ? nextFPV : 100000); //double thresHigh = min(prevFPV ? prevFPV : 100000, nextFPV ? nextFPV : 100000); double thresHigh = max(prevFPV ? prevFPV : 0, nextFPV ? nextFPV : 0); //nystagmus를 찾을 때까지 threshol값을 올린다. //너무 높아지면 중지 while (!pNysFound && (thres < thresHigh*0.95)) { //주어진 위치 좌우에서 threshod를 넘는 위치까지 찾는다. unsigned long startIdx = 0, endIdx = 0; //startIdx를 찾는다. for(int i=idx; i> max(idx-100, M+5); i--) { if(abs(pEye[i] - pEye[i-M]) > thres) { startIdx = i; break; } } for(int i=idx; i< min(idx+ 100, count-M-5); i++) { if(abs(pEye[i+M] - pEye[i]) > thres) { endIdx = i; break; } } //이전과 이후 위치와 비교하여 사이에 있는지 확인 if( ( pNysPrev ? startIdx > pNysPrev->endI : true) && (pNysNext ? endIdx < pNysNext->startI : true) && (endIdx-startIdx > 10) && //최소 길이 (endIdx-startIdx<120)) //최대 길이 { int len = endIdx-startIdx; startIdx += int(len*0.1 +0.5); endIdx -= int(len*0.1 + 0.5); //nystagmus를 만든다. pNysFound = new structNystag; pNysFound->startI = startIdx; pNysFound->endI = endIdx; pNysFound->vel = (pEye[endIdx] - pEye[startIdx]) / (double(endIdx-startIdx)/FRAMERATE); } thres = thres*1.1; } } //못찾았다면 click된 위치 좌우 11개로 만든다. if(!pNysFound) { unsigned long startIdx = pNysPrev ? max(idx-5, pNysPrev->endI + 4) : max(idx-5, 0); unsigned long endIdx = pNysNext ? min(idx+5, pNysNext->startI -4) : min(idx+5, count-1); if(startIdx < endIdx) { pNysFound = new structNystag; pNysFound->startI = startIdx; pNysFound->endI = endIdx; pNysFound->vel = (pEye[endIdx] - pEye[startIdx]) / (double(endIdx-startIdx)/FRAMERATE); } else nysIdx = -1; } if(!pNysPrev) //가장 앞이라면 m_listNystagmus.AddHead(pNysFound); else if(!pNysNext) //가장 뒤라면 m_listNystagmus.AddTail(pNysFound); else if(pNysPrev && pNysNext) m_listNystagmus.InsertBefore(posNext, pNysFound); return nysIdx; } unsigned long CAnalyzeNystagmus2::addNystagmus(unsigned long idx, double* pEye, unsigned long count) { unsigned long nysIdx = 0; //위치를 찾는다. //POSITION posPrev, posNext; POSITION pos1, pos2; structNystag* pNysPrev = NULL; structNystag* pNysNext = NULL; if(m_listNystagmus.GetCount()) { double val = 0; for(pos1 = this->m_listNystagmus.GetHeadPosition(); (pos2 = pos1) != NULL; ) { pNysNext = m_listNystagmus.GetNext(pos1); if((!pNysNext) || (pNysNext->endI+pNysNext->startI)/2 > idx) break; nysIdx++; pNysPrev = pNysNext; } } //양쪽 nystagmus와 겹치지 않도록 한다. unsigned long prevMax = pNysPrev ? pNysPrev->endI : 0; unsigned long nextMin = pNysNext ? pNysNext->startI : count-1; //nystagmus를 만든다. structNystag* pNys = new structNystag; //startI를 찾는다. int M = 3; //EA_Nystagmus::m_paramDerivM double velTh = 40; double vel = 0; unsigned long i=0; for(i=idx; i>i-24; i--) //최대200ms { if(i-M<=0) break; vel = (pEye[i] - pEye[i-M])/(double(M)/FRAMERATE); if(fabs(vel) > velTh) break; } pNys->startI = max((i+3), prevMax); for(i=idx; i<i+24; i++) { if(i == count-1) break; vel = (pEye[i]-pEye[i-M])/(double(M)/FRAMERATE); if(fabs(vel) > velTh) break; } pNys->endI = min(i-3, nextMin); //제대로 만들어졌으면 if(pNys->endI>pNys->startI) pNys->vel = (pEye[pNys->endI] - pEye[pNys->startI]) / (double(pNys->endI-pNys->startI)/FRAMERATE); else nysIdx = -1; if(nysIdx == -1) { delete pNys; } else { //list에 추가한다. m_listNystagmus.InsertBefore(pos2, pNys); } return nysIdx; } void CAnalyzeNystagmus2::deleteNysWithDirection(int direction) { int count = this->m_listNystagmus.GetCount(); POSITION oldPos; POSITION pos = this->m_listNystagmus.GetHeadPosition(); structNystag* pNys = NULL; for(int i=0; i<count; i++) { oldPos = pos; pNys = m_listNystagmus.GetNext(pos); if(pNys && direction*pNys->vel > 0) { delete pNys; m_listNystagmus.RemoveAt(oldPos); } } }
db0e1d6de9221750cb4eef02f8a32d0df084666b
1e1b124f7c55e28477203f22e82627bf0784c558
/common/halfBeat.cpp
b3edcd0b1ce36a2ae38912518937ac4526596302
[]
no_license
jcowles/effects-salad
4a5349dd9ddb9079accc9e1560dd38a695e2143d
52b9259ffc0b5a3095bfcaf8c232efad51cb7bc1
refs/heads/master
2021-01-21T00:00:34.678815
2012-10-18T02:47:14
2012-10-18T02:47:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
582
cpp
halfBeat.cpp
#include "common/halfBeat.h" HalfBeat::HalfBeat() { _previousBeatTime = 0; _currentBeatInterval = 0; _downBeat = false; _multiplier = 2.0f; } bool HalfBeat::Update(bool beat, float time) { if (beat) { _currentBeatInterval = time - _previousBeatTime; _previousBeatTime = time; _downBeat = false; return true; } if (_downBeat) { return false; } float dt = time - _previousBeatTime; if (dt * _multiplier > _currentBeatInterval) { _downBeat = true; return true; } return false; }
34dd1180e4acb5f9b3d6f64192fbfff1ee9a41b3
8436a2f8e2d51dc1d4a2c013de2526b69c88ab58
/main.h
248eba659b594814695b1762ec099741ffee711f
[]
no_license
kpanek206/base-converter
88fb93f14edadc8d8b63f03b8ec0184939774692
71a62486b72adda7f5b2a743b6305e90fddadcf2
refs/heads/master
2022-11-12T23:02:03.848855
2020-07-01T17:02:38
2020-07-01T17:02:38
276,434,699
0
0
null
null
null
null
UTF-8
C++
false
false
250
h
main.h
#include <vector> #include <string> using namespace std; char to_char(int a); int to_int(char a); void change_parameter(); pair<vector<int>, vector<int>> conversion(pair<vector<int>, vector<int>> number); void handle_input(string input); int main();
3ae838278bc7914d4709e6a791e7e6f82cebe0ef
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/printscan/faxsrv/com/win2k/faxtiff.h
a861195bbf7dc3f569178debdc4d04c15d3c45a6
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
2,490
h
faxtiff.h
/*++ Copyright (c) 1997 Microsoft Corporation Module Name: faxtiff.h Abstract: This file contains the class definition for the faxtiff object. Author: Wesley Witt (wesw) 13-May-1997 Environment: User Mode --*/ #ifndef __FAXTIFF_H_ #define __FAXTIFF_H_ #include "resource.h" // main symbols #include "tiff.h" #include "faxutil.h" class ATL_NO_VTABLE CFaxTiff : public CComObjectRootEx<CComSingleThreadModel>, public CComCoClass<CFaxTiff, &CLSID_FaxTiff>, public ISupportErrorInfo, public IDispatchImpl<IFaxTiff, &IID_IFaxTiff, &LIBID_FAXCOMLib> { public: CFaxTiff(); ~CFaxTiff(); DECLARE_REGISTRY_RESOURCEID(IDR_FAXTIFF) BEGIN_COM_MAP(CFaxTiff) COM_INTERFACE_ENTRY(IFaxTiff) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY(ISupportErrorInfo) END_COM_MAP() // ISupportsErrorInfo STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid); // IFaxTiff public: STDMETHOD(get_Tsid)(/*[out, retval]*/ BSTR *pVal); STDMETHOD(get_Csid)(/*[out, retval]*/ BSTR *pVal); STDMETHOD(get_CallerId)(/*[out, retval]*/ BSTR *pVal); STDMETHOD(get_Routing)(/*[out, retval]*/ BSTR *pVal); STDMETHOD(get_SenderName)(/*[out, retval]*/ BSTR *pVal); STDMETHOD(get_RecipientName)(/*[out, retval]*/ BSTR *pVal); STDMETHOD(get_RecipientNumber)(/*[out, retval]*/ BSTR *pVal); STDMETHOD(get_Image)(/*[out, retval]*/ BSTR *pVal); STDMETHOD(put_Image)(/*[in]*/ BSTR newVal); STDMETHOD(get_ReceiveTime)(/*[out, retval]*/ BSTR *pVal); STDMETHOD(get_RawReceiveTime)(/*[out, retval]*/ VARIANT *pVal); STDMETHOD(get_TiffTagString)(/*[in]*/ int tagID, /*[out, retval]*/ BSTR* pVal); private: LPWSTR GetStringTag(WORD TagId); DWORD GetDWORDTag(WORD TagId); DWORDLONG GetQWORDTag(WORD TagId); BSTR GetString( LPCTSTR ResStr ) { return SysAllocString(ResStr); } LPWSTR AnsiStringToUnicodeString(LPSTR AnsiString); LPSTR UnicodeStringToAnsiString(LPWSTR UnicodeString); private: WCHAR m_wszTiffFileName[MAX_PATH+1]; WCHAR m_wszStrBuf[128]; HANDLE m_hFile; HANDLE m_hMap; LPBYTE m_pfPtr; PTIFF_HEADER m_TiffHeader; DWORD m_dwNumDirEntries; UNALIGNED TIFF_TAG* m_TiffTags; }; #endif //__FAXTIFF_H_
8f003c498e092095fd3154816cfb53bba8e7f0ad
05db601940f6f1da845bdab5a30fa06942c67d90
/645div2/C.cpp
99831b34a3a503cf106983070880061f3ebf3772
[]
no_license
NeoClear/codeforce
184875c33828645cede2d1da39f48a6f44565508
0522b194a7b964b4b96f552d89edebc6d6939c5b
refs/heads/master
2022-09-04T04:39:40.155809
2020-05-28T21:30:49
2020-05-28T21:30:49
267,700,857
1
0
null
null
null
null
UTF-8
C++
false
false
444
cpp
C.cpp
#include <bits/stdc++.h> typedef long long ll; using namespace std; ll T; ll a1, a2, b1, b2; int main() { cin >> T; while (T--) { cin >> a1 >> b1 >> a2 >> b2; ll dx = a2 - a1; ll dy = b2 - b1; ll ans = 0; ll K = min(dx, dy); ll V = max(dx, dy) - K; ans += K * (K - 1); ans += K * (V + 1); cout << ans + 1 << endl; } return 0; }
c2ad413fd0d29c5c413c43df15e9435ff47ac118
689d20b714e1a4fec0a9b179f8c13f1e7f871b33
/BinarySortTree/TreeNode.cpp
f2446d53fa30076d3e810b1b037633dc131b6ec1
[]
no_license
gyuqian/BinarySortTree
b4c769382341cd6eece054bf64e1e7cb60945f41
3618cc3a9c4b31c9275a4bccc41d75642db59186
refs/heads/master
2023-03-24T05:57:33.685927
2021-03-15T05:35:52
2021-03-15T05:35:52
321,879,232
0
0
null
null
null
null
GB18030
C++
false
false
1,287
cpp
TreeNode.cpp
/*********************************************** * Auther: gyuqian * Data: 2020/12/15 * Last-modified: 2020/12/18 * File: 二叉节点类声明的具体实现 ************************************************/ #pragma once #include "TreeNode.h" #include "iostream" /*********************************************** * Auther: gyuqian * Data: 2020/12/15 * Last-modified: 2020/12/18 * Func: 构造函数,初始化对象 ************************************************/ TreeNode::TreeNode() { left = NULL; //初始化左子树指针 right = NULL; //初始化右子树指针 root = -1; //初始化根 } /*********************************************** * Auther: gyuqian * Data: 2020/12/15 * Last-modified: 2020/12/18 * Func: 改变根节点值 * Input: noderoot:根节点要被改变的值 * * Output: NO OUTPUT ************************************************/ void TreeNode::changeRoot(int noderoot) { root = noderoot; } /*********************************************** * Auther: gyuqian * Data: 2020/12/15 * Last-modified: 2020/12/18 * Func: 获取根节点值 * Input: NO INPUT * Output: root,返回根节点值 ************************************************/ int TreeNode::getRoot() { return root; }
99057d754ee67e2238fa880a70165448f1a5819a
c8023d5ac12f074e4a33c750e3a4fccac616522d
/Blatt2_Parallel/src/solver.cpp
b3bb8a510321bae6df59ef11c827c564f9cc1f5c
[]
no_license
MrHankey/NumSim
2ae5a4258a603de9a7262692cdc21c4a629b949f
2f84712a412c68c505a27cb28d7f003031f19bf2
refs/heads/master
2021-01-15T12:41:28.506103
2015-12-19T09:34:39
2015-12-19T09:34:39
44,682,550
0
1
null
null
null
null
UTF-8
C++
false
false
4,489
cpp
solver.cpp
/* * Copyright (C) 2015 Raphael Leiteriz, Sebastian Reuschen, Hamzeh Kraus * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "solver.hpp" #include "grid.hpp" #include "geometry.hpp" #include "iterator.hpp" #include <cmath> #include <iostream> /// Constructor of the abstract Solver class // @param geom get field geometry Solver::Solver(const Geometry* geom) { _geom = geom; } /// Destructor of the Solver Class Solver::~Solver() {} /// Returns the residual at [it] for the pressure-Poisson equation // @param it calls iterator // @param grid get grid values // @return localRes return residual real_t Solver::localRes(const Iterator& it, const Grid* grid, const Grid* rhs) const { return fabs(grid->dxx(it) + grid->dyy(it) - rhs->Cell(it)); } /* SOR solver */ /// Concrete SOR solver // @param geom get geometry // @param omega get scaling factor SOR::SOR(const Geometry* geom, const real_t& omega) : Solver(geom) { _geom = geom; _omega = omega; } /// Destructor SOR::~SOR() {} void SOR::PoissonStep(Grid* grid, const Grid* rhs, Iterator it) const { real_t dx = _geom->Mesh()[0]*_geom->Mesh()[0]; real_t dy = _geom->Mesh()[1]*_geom->Mesh()[1]; real_t norm = 0.5*(dx*dy)/(dx + dy); real_t corr = norm*(grid->dxx(it) + grid->dyy(it) - rhs->Cell(it)); grid->Cell(it) += _omega * corr; } /// Returns the total residual and executes a solver cycle of SOR // @param grid get grid values // @param rhs get right hand side of equation // @return Cycle calculate all new p_ij for one cycle real_t SOR::Cycle(Grid* grid, const Grid* rhs) const { // Initialize InteriorIterator it = InteriorIterator(_geom); real_t n, res; n = 0.0; res = 0.0; // Cycle through all cells while(it.Valid()) { // Initialize n++; PoissonStep(grid, rhs, (Iterator)it); // Calculate and summ residual real_t lRes = localRes(it,grid,rhs); res += lRes; // Next cell it.Next(); } // Norm residual return res/n; } //--------------------------------------------------------------------------------------------------- /* SOR solver */ /// Concrete SOR solver // @param geom get geometry // @param omega get scaling factor RedOrBlackSOR::RedOrBlackSOR(const Geometry* geom, const real_t& omega) : SOR(geom,omega) { _geom = geom; _omega = omega; } /// Destructor RedOrBlackSOR::~RedOrBlackSOR() {} /// Returns the total residual and executes a solver cycle of SOR // @param grid get grid values // @param rhs get right hand side of equation // @return Cycle calculate all new p_ij for one cycle real_t RedOrBlackSOR::RedCycle(Grid* grid, const Grid* rhs) const { // Initialize InteriorIterator it = InteriorIterator(_geom); real_t n, res; n = 0.0; res = 0.0; // Cycle through all cells while(it.Valid()) { // Initialize n++; PoissonStep(grid, rhs, (Iterator)it); // Calculate and summ residual real_t lRes = localRes(it,grid,rhs); if(res<=lRes){ res=lRes;//max statt bisher mean } //res += lRes; // Next cell it.Next(); it.Next(); } // Norm residual //return res/n; return res; } /// Returns the total residual and executes a solver cycle of SOR // @param grid get grid values // @param rhs get right hand side of equation // @return Cycle calculate all new p_ij for one cycle real_t RedOrBlackSOR::BlackCycle(Grid* grid, const Grid* rhs) const { // Initialize InteriorIterator it = InteriorIterator(_geom); real_t n, res; it.Next(); n = 0; res = 0; // Cycle through all cells while(it.Valid()) { // Initialize n++; PoissonStep(grid, rhs, (Iterator)it); // Calculate and summ residual real_t lRes = localRes(it,grid,rhs); if(res<lRes){ res=lRes;//max statt bisher mean } //res += lRes; // Next cell it.Next(); it.Next(); } // Norm residual //return res/n; //max statt bisher mean return res; }
77852a9216e4c6b8d361112f0f6613b0a8083efa
88949f2ef38ed853a1749d6394a92eb3e97bf8fd
/1_year/2_term/3/3-2/main.cpp
2b50cc89bbc97bc7a52148d1474f9101a10a9ba2
[]
no_license
TanVD/SpbSU-Homeworks
c64f6d3a812492daff1df058d178f34fab292613
18ec404eee91df47a264942a08637113e06abefa
refs/heads/master
2021-01-21T04:36:49.194487
2016-05-20T14:25:49
2016-05-20T14:25:49
30,809,072
0
1
null
2016-05-20T14:25:49
2015-02-14T21:17:11
C++
UTF-8
C++
false
false
801
cpp
main.cpp
#include <QtTest/QTest> #include <QtCore/QObject> #include "testBypassMatrix.h" #include <iostream> #include "fileOut.h" int main() { BypassMatrixTest test; QTest::qExec(&test); std::cout << "This program will print your matrix spiral way.\nEnter size of matrix: "; int size = 0; std::cin >> size; Matrix *matrix = new Matrix(size); std::cout << "Do you want to print to the file or to the console?\n1 - console\n2 - file\nEnter mode: "; int mode = 0; std::cin >> mode; if (mode == 1) { OutputInterface* outInt = new ConsoleOut(matrix); outInt->out(); delete outInt; } else if (mode == 2) { OutputInterface* outInt = new FileOut(matrix); outInt->out(); delete outInt; } delete matrix; }
27e1ab44b2a72706ff75bacf8762e25c03c8f3e1
196ef01aec42275e1d922c080afb57eab36390a6
/DoctorBLib/Searcher.cpp
8d5c8269a713f942be2de3a8bc3b6466d96e2667
[ "MIT" ]
permissive
hiblom/DoctorB
6b13760c225b72d4a468ffc57b40345fb1dd2783
c874ed54a7a20392b6f0aff19fb5bb412938c2b6
refs/heads/master
2021-06-20T22:20:54.156440
2021-06-13T15:28:53
2021-06-13T15:28:53
217,548,446
2
0
MIT
2021-06-10T20:11:21
2019-10-25T14:11:50
C++
UTF-8
C++
false
false
2,047
cpp
Searcher.cpp
#include "stdafx.h" #include "Searcher.h" #include <iostream> #include <chrono> #include <algorithm> #include "MoveGenerator.h" #include "Evaluator.h" #include "AlphaBetaOrder.h" #include "Options.h" #include "Polyglot.h" #include "Globals.h" using namespace std; Searcher::Searcher(const Position& base_position, const HistoryMap& history) : base_position_(base_position), history_(history), node_count(0) { } void Searcher::goDepth(int depth) { if (bookMove()) return; AlphaBetaOrder search_algorithm = AlphaBetaOrder(base_position_, history_); Move best_move = search_algorithm.goDepth(depth); cout << "bestmove " << best_move.toString() << endl; } void Searcher::goTime(uint64_t wtime, uint64_t btime, uint64_t winc, uint64_t binc, uint64_t movestogo) { if (bookMove()) return; uint64_t max_duration = getMaxDuration(wtime, btime, winc, binc, movestogo); AlphaBetaOrder search_algorithm = AlphaBetaOrder(base_position_, history_); Move best_move = search_algorithm.goTime(max_duration); cout << "bestmove " << best_move.toString() << endl; } Searcher::~Searcher() { } uint64_t Searcher::getMaxDuration(uint64_t wtime, uint64_t btime, uint64_t winc, uint64_t binc, uint64_t movestogo) { if (movestogo == 0) movestogo = 30; //be extra careful when moves to go is approaching 1 int duration_multiplier = movestogo < 5 ? 1 : 2; //subtract 50 ms from time left to be on the safe side wtime = wtime > 60 ? wtime - 50 : 10; btime = btime > 60 ? btime - 50 : 10; if (base_position_.getActiveColor() == Piece::COLOR_WHITE) return min((wtime + winc * movestogo) * duration_multiplier / movestogo, wtime); else return min((btime + binc * movestogo) * duration_multiplier / movestogo, btime); } bool Searcher::bookMove() { if (!Options::OwnBook || Globals::out_of_book) return false; Move move = Polyglot::getInstance().getMove(base_position_.getHashKey()); if (move.isValid()) { cout << "bestmove " << move.toString() << endl; return true; } else { Globals::out_of_book = true; return false; } }
9bd6e8f326c13ae25a748eda1a5164fcd5e0a1e5
fad392b7b1533103a0ddcc18e059fcd2e85c0fda
/build/px4_msgs/rosidl_generator_cpp/px4_msgs/msg/parameter_update.hpp
f216ab69faa359695c25a039edc3114231f1e4c3
[]
no_license
adamdai/px4_ros_com_ros2
bee6ef27559a3a157d10c250a45818a5c75f2eff
bcd7a1bd13c318d69994a64215f256b9ec7ae2bb
refs/heads/master
2023-07-24T18:09:24.817561
2021-08-23T21:47:18
2021-08-23T21:47:18
399,255,215
0
0
null
null
null
null
UTF-8
C++
false
false
360
hpp
parameter_update.hpp
// generated from rosidl_generator_cpp/resource/idl.hpp.em // generated code does not contain a copyright notice #ifndef PX4_MSGS__MSG__PARAMETER_UPDATE_HPP_ #define PX4_MSGS__MSG__PARAMETER_UPDATE_HPP_ #include "px4_msgs/msg/parameter_update__struct.hpp" #include "px4_msgs/msg/parameter_update__traits.hpp" #endif // PX4_MSGS__MSG__PARAMETER_UPDATE_HPP_
08e10ed2e8f58805f40637b008cd1b4658b70455
aafcc55c71c0716724d68867f98f92e019417524
/Wrapper.hpp
d05525046ef166c458225cd54414494f990dac3d
[ "Apache-2.0" ]
permissive
GuillaumeGomez/Wrapper-RS232-COM-PORT
709eb0200daf3e43bcb20f001b39420fd58f91b7
c7fa7bb2261e3eef351806ad719dd473f1bea4ca
refs/heads/master
2020-04-06T04:03:05.191301
2014-11-26T10:05:19
2014-11-26T10:05:19
16,872,547
2
0
null
null
null
null
UTF-8
C++
false
false
1,345
hpp
Wrapper.hpp
#ifndef Wrapper_H #define Wrapper_H #include <cstdlib> #include <iostream> #include <stdio.h> #include <stdlib.h> #include <map> #include <string> #include <string.h> #if defined (WIN32) #include <windows.h> #include <conio.h> #define RX_SIZE 4096 // in buffer size #define TX_SIZE 4096 // out buffer size #define MAX_WAIT_READ 5000 // max waiting time (in ms) #else #include <termios.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #define BPS9600 0 #define BPS4800 1 #define BPS2400 2 #define BPS19200 3 #define BIT8 0 #define BIT7 1 #define BIT6 2 #define BIT5 3 #define STOP1 0 #define STOP2 1 #define NO_PARITY 0 #define PAIR_PARITY 1 #define ODD_PARITY 2 #define OK 0 #define ERREUR -1 #define TIMEOUT -2 #define NOTHING 1 #endif class Wrapper { public : Wrapper(); virtual ~Wrapper(); bool OpenCOM(std::string s); bool ReadCOM(char* buffer, unsigned int nBytesToRead, unsigned int *pBytesRead); bool WriteCOM(const char *buffer, unsigned int nBytesToWrite, unsigned int *pBytesWritten); bool CloseCOM(); private : #if defined (WIN32) HANDLE g_hCOM; COMMTIMEOUTS g_cto; DCB g_dcb; void InitCOM(); #else termios Config; int fd; bool Configure(const char *pPort, int speed, int NbBits, int parity, int NbStop); #endif }; #endif
b80db45ad1cb420097cb2d1c1f94247772252aa5
f122c8f7f0ec239c3a19c679ccf3c23ae758a097
/test/core/casts/storage.cpp
00c03e95b16c3fdf63915c4486f2fd5ecb7798a9
[ "AFL-3.0", "AFL-2.1", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Qznec/vrm_core
305773c7682deb3d4fe7168ae4e23e61afa55a09
f5119841892fc4244b261dddf80dea1fb4e1889a
refs/heads/master
2022-06-24T04:41:25.678978
2022-06-03T10:11:21
2022-06-03T10:11:21
126,380,398
0
0
null
2018-03-22T18:42:58
2018-03-22T18:42:58
null
UTF-8
C++
false
false
612
cpp
storage.cpp
#include "../../utils/test_utils.hpp" #include <utility> #include <vrm/core/casts/storage.hpp> TEST_MAIN() { using namespace vrm::core; using st = std::aligned_storage_t<sizeof(float), alignof(float)>; st s; new(&s) float(100.f); TEST_ASSERT(storage_cast<float>(s) == 100.f); TEST_ASSERT(*(storage_cast<float>(&s)) == 100.f); const auto& cs(s); TEST_ASSERT(storage_cast<float>(cs) == 100.f); TEST_ASSERT(*(storage_cast<float>(&cs)) == 100.f); SA_TYPE((storage_cast<float>(s)), (float&)); SA_TYPE((storage_cast<float>(std::move(s))), (float&&)); return 0; }
cf1e857e34b1056cd65366d230150eec7d6d2eec
548cb8f04bf7bedb805d689d956d7f9578789b1a
/realphysics/physics/management/inc/PostStepActionStage.h
5cc6cad166b7e71400b18d84b8a90bf5d4219d69
[]
no_license
Radiation-Physics-Group-of-Alexandria/GeantV
0d57918dacbde0468f55568558fb60cb651b955e
f22382017671286bab1a50cd9636dec7d2c12d31
refs/heads/master
2021-05-07T22:46:41.503813
2017-10-13T13:45:38
2017-10-13T13:45:38
107,283,199
1
0
null
null
null
null
UTF-8
C++
false
false
1,357
h
PostStepActionStage.h
#ifndef POSTSTEPACTIONSTAGE_H #define POSTSTEPACTIONSTAGE_H // from geantV #include "SimulationStage.h" // from geantV namespace Geant { inline namespace GEANT_IMPL_NAMESPACE { class GeantPropagator; class GeantTrack; class GeantTaskData; class Handler; } } namespace geantphysics { /** * @brief Simulation stage to select particles that post-step action (discrete interaction) need to be invoked. * @class PostStepActionStage * @author M Novak * @date May 2017 */ class PostStepActionStage : public Geant::SimulationStage { public: /** @brief ctr */ PostStepActionStage() {} /** @brief ctr */ PostStepActionStage(Geant::GeantPropagator *prop); /** @brief dtr */ ~PostStepActionStage(); /** @brief Get simulation stage name */ virtual const char *GetName() { return "PostStepActionStage"; } /** @brief Interface to create all handlers for the simulation stage * @return Number of handlers created */ virtual int CreateHandlers(); /** @brief Interface to select the handler matching a track */ virtual Geant::Handler *Select(Geant::GeantTrack *track, Geant::GeantTaskData *td); private: PostStepActionStage(const PostStepActionStage &) = delete; PostStepActionStage &operator=(const PostStepActionStage &) = delete; }; } // namespace geantphysics #endif // POSTSTEPACTIONSTAGE_H
948c47709ad8cb04e740fb5367b89967c4363aff
bbda507ac43fab77865378e33b7238c425485d86
/gvb/lex.h
a83821ebde4c2b9ed09df7f0fcdc47bd22336201
[ "MIT" ]
permissive
arucil/gvbasic-simulator4cpp
6f5a4d3f8ea438f2c77359397831efd44916f39f
7f8416e7d4999a0b5dd4813ac38194c60bd7e2c4
refs/heads/master
2022-09-30T12:01:20.087517
2022-08-30T01:33:36
2022-08-30T01:33:36
47,590,707
32
7
null
null
null
null
UTF-8
C++
false
false
1,086
h
lex.h
#ifndef GVBASIC_LEX_H #define GVBASIC_LEX_H #include <string> #include <cstdio> #include <unordered_map> namespace gvbsim { struct Token { enum { TOKEN_FIRST = 256, ID, INT, REAL, STRING, DIM, LET, SWAP, GOTO, IF, THEN, ELSE, ON, FOR, TO, NEXT, STEP, WHILE, WEND, DEF, FN, GOSUB, RETURN, AND, OR, NOT, READ, DATA, RESTORE, INPUT, PRINT, LOCATE, INVERSE, INKEY, PLAY, BEEP, GRAPH, TEXT, DRAW, LINE, BOX, CIRCLE, ELLIPSE, OPEN, CLOSE, PUT, GET, LSET, RSET, CONT, POP, REM, CLEAR, WRITE, AS, POKE, CALL, CLS, FIELD, END, GE, LE, NEQ, TAB, SPC, SLEEP, PAINT, LOAD, FPUTC, FREAD, FWRITE, FSEEK, TOKEN_LAST }; static const char *toString(int tok); }; class Lexer { public: typedef int NumberFormatError; public: int32_t ival; double rval; std::string sval; public: int getc(); void skipSpace(); int getToken(); Lexer(FILE *); private: int m_c; FILE *m_fp; static const std::unordered_map<std::string, int> s_kwmap; private: int peek(); bool peek(int); }; } #endif //GVBASIC_LEXER_H
25a2535658041d02148633ff488578ce9a1b40ba
c6b35f785b69ffaacfcf28c08d6fda05d562a054
/PathExtractor.cpp
da3f3552b6ff6ecf92ca3d45d65a92b7d0dda9e6
[]
no_license
cbrunschen/MorphPlot
a67f1465d3561c2d7391969febfab6c851decd57
2e3c1724e23d45afc5109d35dcb8a0291b8995d1
refs/heads/master
2021-01-17T08:48:39.422858
2016-04-09T15:57:10
2016-04-09T15:57:10
17,036,406
0
0
null
null
null
null
UTF-8
C++
false
false
2,519
cpp
PathExtractor.cpp
/* * PathExtractor.cpp * Morph * * Created by Christian Brunschen on 27/11/2011. * Copyright 2011 Christian Brunschen. All rights reserved. * */ #include "PathExtractor.h" namespace Extraction { #if 0 } #endif ostream &preparePS(ostream &out, int width, int height) { out << "%!PS-Adobe-3.0" << endl; out << "%%BoundingBox: 0 0 " << width << " " << height << endl; out << "%%Page: only 1" << endl; out << "gsave initclip clippath pathbbox grestore" << endl; out << "/ury exch def /urx exch def /lly exch def /llx exch def" << endl; out << "/W urx llx sub def /H ury lly sub def" << endl; out << "/w " << width << " def /h " << height << " def" << endl; out << "/xs W w div def /ys H h div def" << endl; out << "/s xs ys lt { xs } { ys } ifelse def" << endl; out << "llx urx add 2 div lly ury add 2 div translate" << endl; out << "s dup scale w 2 div neg h 2 div translate 1 -1 scale" << endl; out << "1 setlinejoin 1 setlinecap" << endl; return out; } ostream &drawChainPixels(ostream &out, Chains &chains) { out << "[" << endl; int n = 200; for (Chains::iterator j = chains.begin(); j != chains.end(); ++j) { for (Chain::iterator k = j->begin(); k != j->end(); ++k) { out << k->x() << " " << k->y() << " 1 1 " ; if (--n == 0) { out << " ] dup 0.8 setgray rectfill 0.3 setgray rectstroke [ " << endl; n = 200; } } } out << " ] dup 0.8 setgray rectfill 0.3 setgray rectstroke" << endl; out << "0 setgray 0.5 0.5 translate 0.2 setlinewidth" << endl; return out; } ostream &strokeChains(ostream &out, Chains chains) { for (Chains::iterator j = chains.begin(); j != chains.end(); ++j) { Chain::iterator k = j->begin(); out << k->x() << " " << k->y() << " moveto currentpoint lineto "; out << "gsave currentpoint translate newpath -0.3 -0.3 0.6 0.6 rectfill grestore "; for (++k; k != j->end(); ++k) { out << k->x() << " " << k->y() << " lineto "; } out << "stroke" << endl << flush; } return out; } ostream &strokeBetween(ostream &out, Chains chains) { Chains::iterator j = chains.begin(); IPoint &prev = j->back(); for (++j; j != chains.end(); ++j) { out << prev.x() << " " << prev.y() << " moveto "; out << j->front().x() << " " << j->front().y() << " lineto "; prev = j->back(); } out << "stroke" << endl << flush; return out; } void finishPS(ostream &out) { out << endl << "showpage" << endl; } #if 0 { #endif }
9794107ac33695e91e1412019554eea8f95e065e
3de81993057b267a31b4928a7a54697ea71ad165
/MYSTRING.CPP
fa9c8791795dd37a1d5a2b5a8093242286322838
[]
no_license
YNazar/Mystring
3bf3f743418489df56288afb647e0938d19461ee
346115b9e54b04740047b6dba3790c0f755a57df
refs/heads/master
2021-01-25T09:54:13.302170
2014-09-27T16:56:15
2014-09-27T16:56:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,844
cpp
MYSTRING.CPP
#include "MYSTRING.HPP" #include <iostream> #include <limits> using namespace std; Mystring::Mystring():siz(0) { str=new char[1]; str[0]='\0'; } Mystring::Mystring(size_t ins): siz (ins) { str=new char[siz+1]; for (size_t i=0; i<ins; i++) str[i]='0'; str[ins]='\0'; } Mystring::Mystring(Mystring &rhs):siz(rhs.siz) { str=new char[siz]; for (size_t i=0; i<rhs.siz; i++) str[i]=rhs.str[i]; } Mystring Mystring::operator=(const Mystring& rhs) { if (this==&rhs) return *this; delete[] str; siz=rhs.siz; str=new char[siz]; for (size_t i=0; i<siz; i++) str[i]=rhs.str[i]; return *this; } size_t Mystring::get_size () const { return siz; } char* Mystring::get_str()const { char*tmp=new char[siz]; for (size_t i=0;i<siz;i++) tmp[i]=str[i]; return tmp; } const char& Mystring::operator[](size_t idx)const { return str[idx]; } char& Mystring::operator [] (size_t idx) { return str[idx]; } Mystring::Mystring ( const char *str1) { siz=0; while (*(str1++)!='\0') siz++; str =new char[siz]; for (size_t i=0; i<siz; i++) str[i]=str1[i-siz-1]; } void Mystring::printstr() { for (size_t i=0; i<siz; i++) std::cout << str[i]<<" "; std::cout << std::endl; std::cout <<"Elementiv :" <<siz<<std::endl; } void Mystring::scanstr() { cout << "Enter string and | 0 | to break "<< endl; delete[] str; siz=0; str=new char[siz+1]; while(true) { cin>>str[siz]; if (str[siz]=='0') { str[siz]='\0'; break; } siz++; this->resiz(siz); } } void Mystring::resiz(size_t newsiz) { char*tmp=new char [newsiz]; for (size_t i=0; i<siz; i++) tmp[i]=str[i]; delete[] str; siz=newsiz; str = tmp; } Mystring operator+ (const Mystring& a,const Mystring& b) { Mystring res; res=a; res+=b; return res; } void Mystring::operator+=(const Mystring&rhs) { char*res=new char[siz+rhs.siz]; for(size_t i=0;i<siz;i++) res[i]=str[i]; for(size_t i=0;i<rhs.siz;i++) res[siz+i]=rhs.str[i]; delete[] str; siz=siz+rhs.siz; str=res; } void Mystring:: deletchr( char a) { size_t lich=0,n=0; for(size_t i=0; i<siz; i++) { if (str[i]==a) lich++; } siz-=lich; char *tmp=new char[siz]; for (size_t i=0; i<(siz+lich); i++) { if (str[i]!=a) { tmp[n]=str[i]; n++; } } str=tmp; } size_t Mystring::findchr(const char *str, char a) { size_t res=0; for (size_t i=0; str[i]!='\0'; i++) { if (str[i]==a) return i; else res=numeric_limits <size_t>::max(); } return res; }
4b8e0bbae55fd56165638f69c18602154bdb1569
be1e241c8960f999c46b0c79aa7ec624aff9d2d0
/include/private/DumpFormatter.hpp
39d502579d07cc20c9cccf4f35f4d49a4f4b676a
[]
no_license
jiajuwu/bb_eventloop
983feeb01e777053124da3ec2f9fe125cd229f5a
2436732833cc5688283a68bbd113ed60bbea9a87
refs/heads/master
2021-01-10T09:08:11.589533
2015-12-11T12:27:11
2015-12-11T12:27:11
47,827,806
0
1
null
null
null
null
UTF-8
C++
false
false
1,136
hpp
DumpFormatter.hpp
#ifndef EVENTLOOP_DUMPFORMATTER_HEADER #define EVENTLOOP_DUMPFORMATTER_HEADER #include <ostream> #include <boost/iostreams/stream.hpp> #include <boost/iostreams/concepts.hpp> namespace EventLoop { namespace Detail { class DumpFormatterSink: public boost::iostreams::sink { public: DumpFormatterSink() = delete; explicit DumpFormatterSink(std::ostream &target); ~DumpFormatterSink(); std::streamsize write(const char *s, std::streamsize n); private: void indentIfNeeded(); std::ostream &target; int level; bool indentNext; }; }; class DumpFormatter: public boost::iostreams::stream<Detail::DumpFormatterSink> { public: DumpFormatter() = delete; explicit DumpFormatter(std::ostream &target); ~DumpFormatter(); DumpFormatter(const DumpFormatter &) = delete; DumpFormatter &operator = (const DumpFormatter &) = delete; private: Detail::DumpFormatterSink sink; }; } #endif /* !EVENTLOOP_DUMPFORMATTER_HEADER */
4b405019f3cc855d8ec101c3c79782460eefe66d
402511d388ad7b4f3633d44975c6037bd770a73c
/2056(직업)/2056(직업)/2056.cpp
651f19a930d012497db2e588dafc66321bffeedd
[]
no_license
hg010303/Baekjoon
33c9747f2b2adea66c5ac07fe5f444a4d1457dcc
28b1df13aec07823d7ad0990bb94e4988e962094
refs/heads/master
2023-06-19T18:20:49.576626
2021-07-12T14:24:08
2021-07-12T14:24:08
278,156,857
0
0
null
null
null
null
UTF-8
C++
false
false
621
cpp
2056.cpp
#include<iostream> #include<algorithm> #include<queue> using namespace std; int time[10010]; int num[10010]; int gp[10010][103]; int ans[10010]; int main() { int n; cin >> n; queue<int> q; for (int i = 1; i <= n; i++) { cin >> time[i] >> num[i]; for (int j = 0; j < num[i]; j++) cin >> gp[i][j]; if (num[i] == 0) { q.push(i); ans[i] = time[i]; } } while (q.size()!=0) { int a = q.front(); q.pop(); for (int i = 0; i < num[a]; i++) { if (ans[gp[num[a]][i]] == 0) ans[gp[num[a]][i]] = ans[a] + time[i]; else ans[gp[num[a]][i]] = max(ans[gp[num[a]][i]], ans[a] + time[i]); } } }
f1f2d1e4056eff0e1ddba25dfaf466f5161a9a9d
47b0b89a88039c099448968e014b441cf2d15ec5
/不规则vector数组.cpp
3c86a1c2307f3f5a626540648da9485114496906
[]
no_license
MengQingguo377/C-tips
271dfa4664b608eaf2cc55e971df268acc220978
62d220008a84342f919344f56c1273337cc7407b
refs/heads/master
2023-01-18T20:16:43.923020
2020-11-20T00:32:03
2020-11-20T00:32:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
344
cpp
不规则vector数组.cpp
#include<iostream> #include<vector> using namespace std; int main() { vector<vector<int> >arr; arr.push_back({1,2,3,4}); arr.push_back({5,6,7}); arr.push_back({8,9}); for(int i = 0; i < arr.size(); i++) { for(int j = 0; j < arr[i].size(); j++) cout << arr[i][j] << " "; cout << endl; } }
a901bb017609679d809133ca75030ec258490895
68bfa9d7a6b267f52354415fc72fada1ddfdc9ab
/src/gennylib/include/gennylib/PhaseLoop.hpp
bfb3871c82fa925536fdacd8911bdca1d2192718
[ "Apache-2.0" ]
permissive
mongodb/genny
5aa3c3be01d8bd8e5b7c9a9d019c5b206d7e97fb
788eaf26e3b8b08d76c71d54fb0013befee9b032
refs/heads/master
2023-09-06T09:25:21.933670
2023-09-05T15:59:07
2023-09-05T15:59:07
121,291,048
44
76
Apache-2.0
2023-09-14T16:50:21
2018-02-12T19:23:44
C++
UTF-8
C++
false
false
29,314
hpp
PhaseLoop.hpp
// Copyright 2019-present MongoDB Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef HEADER_10276107_F885_4F2C_B99B_014AF3B4504A_INCLUDED #define HEADER_10276107_F885_4F2C_B99B_014AF3B4504A_INCLUDED #include <cassert> #include <chrono> #include <iterator> #include <optional> #include <sstream> #include <thread> #include <type_traits> #include <unordered_map> #include <utility> #include <boost/exception/exception.hpp> #include <boost/throw_exception.hpp> #include <gennylib/GlobalRateLimiter.hpp> #include <gennylib/InvalidConfigurationException.hpp> #include <gennylib/Orchestrator.hpp> #include <gennylib/context.hpp> #include <gennylib/v1/Sleeper.hpp> /** * @file * This file provides the `PhaseLoop<T>` type and the collaborator classes that make it iterable. * See extended example on the PhaseLoop class docs. */ namespace genny { /* * Reminder: the v1 namespace types are *not* intended to be used directly. */ namespace v1 { /** * Determine the conditions for continuing to iterate a given Phase. * * One of these is constructed for each `ActorPhase<T>` (below) * using a PhaseContext's `Repeat` and `Duration` keys. It is * then passed to the downstream `ActorPhaseIterator` which * actually keeps track of the current state of the iteration in * `for(auto _ : phase)` loops. The `ActorPhaseIterator` keeps track * of how many iterations have been completed and, if necessary, * when the iterations started. These two values (# iterations and * iteration start time) are passed into the IterationCompletionCheck * to determine if the loop should continue iterating. */ class IterationChecker final { public: IterationChecker(std::optional<TimeSpec> minDuration, std::optional<IntegerSpec> minIterations, bool isNop, TimeSpec sleepBefore, TimeSpec sleepAfter, std::optional<RateSpec> rateSpec) : _minDuration{minDuration}, // If it is a nop then should iterate 0 times. _minIterations{isNop ? IntegerSpec(0l) : minIterations}, _doesBlock{_minIterations || _minDuration}, _sleepUntil{SteadyClock::now()} { if (minDuration && minDuration->count() < 0) { std::stringstream str; str << "Need non-negative duration. Gave " << minDuration->count() << " milliseconds"; throw InvalidConfigurationException(str.str()); } if (minIterations && *minIterations < 0) { std::stringstream str; str << "Need non-negative number of iterations. Gave " << *minIterations; throw InvalidConfigurationException(str.str()); } if ((sleepBefore || sleepAfter) && rateSpec) { throw InvalidConfigurationException( "GlobalRate must *not* be specified alongside either sleepBefore or sleepAfter. " "genny cannot enforce the global rate when there are mandatory sleeps in" "each thread"); } _sleeper.emplace(sleepBefore, sleepAfter); } explicit IterationChecker(PhaseContext& phaseContext) : IterationChecker(phaseContext["Duration"].maybe<TimeSpec>(), phaseContext["Repeat"].maybe<IntegerSpec>(), phaseContext.isNop(), phaseContext["SleepBefore"].maybe<TimeSpec>().value_or(TimeSpec{}), phaseContext["SleepAfter"].maybe<TimeSpec>().value_or(TimeSpec{}), phaseContext["GlobalRate"].maybe<RateSpec>()) { if (!phaseContext.isNop() && !phaseContext["Duration"] && !phaseContext["Repeat"] && phaseContext["Blocking"].maybe<std::string>() != "None") { std::stringstream msg; msg << "Must specify 'Blocking: None' for Actors in Phases that don't block " "completion with a Repeat or Duration value. In Phase " << phaseContext.path() << ". Gave"; msg << " Duration:" << phaseContext["Duration"].maybe<std::string>().value_or("undefined"); msg << " Repeat:" << phaseContext["Repeat"].maybe<std::string>().value_or("undefined"); msg << " Blocking:" << phaseContext["Blocking"].maybe<std::string>().value_or("undefined"); throw InvalidConfigurationException(msg.str()); } const auto rateSpec = phaseContext["GlobalRate"].maybe<RateSpec>(); const auto rateLimiterName = phaseContext["RateLimiterName"].maybe<std::string>().value_or("defaultRateLimiter"); if (rateSpec) { std::ostringstream defaultRLName; defaultRLName << phaseContext.actor()["Name"] << phaseContext.getPhaseNumber(); const auto rateLimiterName = phaseContext["RateLimiterName"].maybe<std::string>().value_or(defaultRLName.str()); _rateLimiter = phaseContext.workload().getRateLimiter(rateLimiterName, rateSpec.value()); } } constexpr void limitRate(const SteadyClock::time_point referenceStartingPoint, const int64_t currentIteration, Orchestrator& orchestrator, const PhaseNumber inPhase) { if (_rateLimiter) { while (true) { const auto now = SteadyClock::now(); auto success = _rateLimiter->consumeIfWithinRate(now); // If we don't block, we can trust the sleeper to check if the phase ended. bool phaseStillGoing = !_doesBlock || !isDone(referenceStartingPoint, currentIteration, now); if (!success && phaseStillGoing) { // Don't sleep for more than 1 second (1e9 nanoseconds). Otherwise rates // specified in seconds or lower resolution can cause the workloads to // run visibly longer than the specified duration. const auto rate = _rateLimiter->getRate() > 1e9 ? 1e9 : _rateLimiter->getRate(); // Add ±5% jitter to avoid threads waking up at once. _sleeper->sleepFor(orchestrator, inPhase, std::chrono::nanoseconds(int64_t( rate * (0.95 + 0.1 * (double(rand()) / RAND_MAX)))), !_doesBlock); continue; } break; } _rateLimiter->notifyOfIteration(); } } constexpr SteadyClock::time_point computeReferenceStartingPoint() const { // avoid doing now() if no minDuration configured return _minDuration ? SteadyClock::now() : SteadyClock::time_point::min(); } constexpr bool isDone(SteadyClock::time_point startedAt, int64_t currentIteration, SteadyClock::time_point wouldBeDoneAtTime) { return (!_minIterations || currentIteration >= _minIterations->value) && (!_minDuration || (*_minDuration).value <= wouldBeDoneAtTime - startedAt); } constexpr bool operator==(const IterationChecker& other) const { return _minDuration == other._minDuration && _minIterations == other._minIterations; } constexpr bool doesBlockCompletion() const { return _doesBlock; } // Set the minimum timepoint before continuning again constexpr void setSleepUntil(SteadyClock::time_point sleepUntil) { _sleepUntil = sleepUntil; } // Perform the sleep to get to specified timepoint, but ending phase if timepoint would be after // the end of the phase. void sleepForActor(Orchestrator& o, SteadyClock::time_point startedAt, int64_t currentIteration, const PhaseNumber pn) { if (!o.continueRunning()) return; // don't sleep if the orchestrator says to stop auto now = SteadyClock::now(); if (_sleepUntil <= now) return; // if phase would end before delay, call await end if (doesBlockCompletion() && isDone(startedAt, currentIteration, _sleepUntil)) { _sleepUntil = (_minDuration ? (startedAt + _minDuration->value) // Shorten sleepUntil duration. : now); } // Don't block completion and wouldn't otherwise be done at _sleepUntil. o.sleepUntilOrPhaseEnd(_sleepUntil, pn); } constexpr void sleepBefore(const Orchestrator& o, const PhaseNumber pn) const { _sleeper->before(o, pn); } constexpr void sleepAfter(const Orchestrator& o, const PhaseNumber pn) const { _sleeper->after(o, pn); } private: // Debatable about whether this should also track the current iteration and // referenceStartingPoint time (versus having those in the ActorPhaseIterator). BUT: even // the .end() iterator needs an instance of this, so it's weird const std::optional<TimeSpec> _minDuration; const std::optional<IntegerSpec> _minIterations; // The rate limiter is owned by the workload context. GlobalRateLimiter* _rateLimiter = nullptr; const bool _doesBlock; // Computed/cached value. Computed at ctor time. std::optional<v1::Sleeper> _sleeper; SteadyClock::time_point _sleepUntil; }; /** * The iterator used in `for(auto _ : cfg)` and returned from * `ActorPhase::begin()` and `ActorPhase::end()`. * * Configured with {@link IterationCompletionCheck} and will continue * iterating until configured #iterations or duration are done * or, if non-blocking, when Orchestrator says phase has changed. */ class ActorPhaseIterator final { public: // Normally we'd use const IterationChecker& (ref rather than *) // but we actually *want* nullptr for the end iterator. This is a bit of // an over-optimization, but it adds very little complexity at the benefit // of not having to construct a useless object. ActorPhaseIterator(Orchestrator& orchestrator, IterationChecker* iterationCheck, PhaseNumber inPhase, bool isEndIterator) : _orchestrator{std::addressof(orchestrator)}, _iterationCheck{iterationCheck}, _referenceStartingPoint{isEndIterator ? SteadyClock::time_point::min() : _iterationCheck->computeReferenceStartingPoint()}, _inPhase{inPhase}, _isEndIterator{isEndIterator}, _currentIteration{0} { // iterationCheck should only be null if we're end() iterator. assert(isEndIterator == (iterationCheck == nullptr)); } // iterator concept value-type // intentionally empty; most compilers will elide any actual storage struct Value {}; Value operator*() const { return Value(); } constexpr ActorPhaseIterator& operator++() { if (_iterationCheck) { _iterationCheck->sleepAfter(*_orchestrator, _inPhase); } ++_currentIteration; return *this; } bool operator==(const ActorPhaseIterator& rhs) const { if (_iterationCheck) { _iterationCheck->sleepBefore(*_orchestrator, _inPhase); _iterationCheck->limitRate( _referenceStartingPoint, _currentIteration, *_orchestrator, _inPhase); _iterationCheck->sleepForActor( *_orchestrator, _referenceStartingPoint, _currentIteration, _inPhase); } // clang-format off return // we're comparing against the .end() iterator (the common case) (rhs._isEndIterator && !this->_isEndIterator && (!_orchestrator->continueRunning() || // ↑ orchestrator says we stop // ...or... // if we block, then check to see if we're done in current phase // else check to see if current phase has expired (_iterationCheck->doesBlockCompletion() ? _iterationCheck->isDone(_referenceStartingPoint, _currentIteration, SteadyClock::now()) : _orchestrator->currentPhase() != _inPhase))) // Below checks are mostly for pure correctness; // "well-formed" code will only use this iterator in range-based for-loops and will thus // never use these conditions. // // Could probably put these checks under a debug-build flag or something? // this == this || (this == &rhs) // neither is end iterator but have same fields || (!rhs._isEndIterator && !_isEndIterator && _referenceStartingPoint == rhs._referenceStartingPoint && _currentIteration == rhs._currentIteration && _iterationCheck == rhs._iterationCheck) // both .end() iterators (all .end() iterators are ==) || (_isEndIterator && rhs._isEndIterator) // we're .end(), so 'recurse' but flip the args so 'this' is rhs || (_isEndIterator && rhs == *this); } // clang-format on // Iterator concepts only require !=, but the logic is much easier to reason about // for ==, so just negate that logic 😎 (compiler should inline it) const bool operator!=(const ActorPhaseIterator& rhs) const { return !(*this == rhs); } private: Orchestrator* _orchestrator; IterationChecker* _iterationCheck; const SteadyClock::time_point _referenceStartingPoint; const PhaseNumber _inPhase; const bool _isEndIterator; int64_t _currentIteration; public: // <iterator-concept> typedef std::forward_iterator_tag iterator_category; typedef Value value_type; typedef Value reference; typedef Value pointer; typedef std::ptrdiff_t difference_type; // </iterator-concept> }; /** * Represents an Actor's configuration for a particular Phase. * * Its iterator, `ActorPhaseIterator`, lets Actors do an operation in a loop * for a pre-determined number of iterations or duration or, * if the Phase is non-blocking for the Actor, as long as the * Phase is held open by other Actors. * * This type can be used as a `T*` through its implicit conversion * and by its operator-overloads. * * This is intended to be used via `PhaseLoop` below. */ template <class T> class ActorPhase final { public: /** * `args` are forwarded as the T value's constructor-args */ template <class... Args> ActorPhase(Orchestrator& orchestrator, std::unique_ptr<IterationChecker> iterationCheck, PhaseNumber currentPhase, Args&&... args) : _orchestrator{orchestrator}, _currentPhase{currentPhase}, _value{std::make_unique<T>(std::forward<Args>(args)...)}, _iterationCheck{std::move(iterationCheck)} { static_assert(std::is_constructible_v<T, Args...>); } /** * `args` are forwarded as the T value's constructor-args */ template <class... Args> ActorPhase(Orchestrator& orchestrator, PhaseContext& phaseContext, PhaseNumber currentPhase, Args&&... args) : _orchestrator{orchestrator}, _currentPhase{currentPhase}, _value{!phaseContext.isNop() ? std::make_unique<T>(std::forward<Args>(args)...) : nullptr}, _iterationCheck{std::make_unique<IterationChecker>(phaseContext)} { static_assert(std::is_constructible_v<T, Args...>); } ActorPhaseIterator begin() { return ActorPhaseIterator{_orchestrator, _iterationCheck.get(), _currentPhase, false}; } ActorPhaseIterator end() { return ActorPhaseIterator{_orchestrator, nullptr, _currentPhase, true}; }; // Used by PhaseLoopIterator::doesBlockCompletion() constexpr bool doesBlock() const { return _iterationCheck->doesBlockCompletion(); } // Checks if the actor is performing a nullOp. Used only for testing. constexpr bool isNop() const { return !_value; } // Could use `auto` for return-type of operator-> and operator*, but // IDE auto-completion likes it more if it's spelled out. // // - `remove_reference_t` is to handle the case when it's `T&` // (which it theoretically can be in deduced contexts). // - `remove_reference_t` is idempotent so it's also just defensive-programming // - `add_pointer_t` ensures it's a pointer :) // // BUT: this is just duplicated from the signature of `std::unique_ptr<T>::operator->()` // so we trust the STL to do the right thing™️ typename std::add_pointer_t<std::remove_reference_t<T>> operator->() const noexcept { #ifndef NDEBUG if (!_value) { BOOST_THROW_EXCEPTION(std::logic_error("Trying to dereference via -> in a Nop phase.")); } #endif return _value.operator->(); } // Could use `auto` for return-type of operator-> and operator*, but // IDE auto-completion likes it more if it's spelled out. // // - `add_lvalue_reference_t` to ensure that we indicate we're a ref not a value // // BUT: this is just duplicated from the signature of `std::unique_ptr<T>::operator*()` // so we trust the STL to do the right thing™️ typename std::add_lvalue_reference_t<T> operator*() const { #ifndef NDEBUG if (!_value) { BOOST_THROW_EXCEPTION(std::logic_error("Trying to dereference via * in a Nop phase.")); } #endif return _value.operator*(); } // Allow ActorPhase<T> to be used as a T* through implicit conversion. operator std::add_pointer_t<std::remove_reference_t<T>>() { #ifndef NDEBUG if (!_value) { BOOST_THROW_EXCEPTION(std::logic_error("Trying to dereference via * in a Nop phase.")); } #endif return _value.operator->(); } PhaseNumber phaseNumber() const { return _currentPhase; } /** * Set a sleep to be used in the iteration checker in the Phase Loop. Does not sleep * immediately, but will not start the next iteration before this amount of time has passed. */ void sleepNonBlocking(Duration timeout) { _iterationCheck->setSleepUntil(SteadyClock::now() + timeout); } private: Orchestrator& _orchestrator; const PhaseNumber _currentPhase; const std::unique_ptr<T> _value; // nullptr iff operation is Nop const std::unique_ptr<IterationChecker> _iterationCheck; }; // class ActorPhase /** * Maps from PhaseNumber to the ActorPhase<T> to be used in that PhaseNumber. */ template <class T> using PhaseMap = std::unordered_map<PhaseNumber, v1::ActorPhase<T>>; /** * The iterator used by `for(auto&& config : phaseLoop)`. * * @attention Don't use this outside of range-based for loops. * Other STL algorithms like `std::advance` etc. are not supported to work. * * @tparam T the per-Phase type that will be exposed for each Phase. * * Iterates over all phases and will correctly call * `awaitPhaseStart()` and `awaitPhaseEnd()` in the * correct operators. */ template <class T> class PhaseLoopIterator final { public: PhaseLoopIterator(Orchestrator& orchestrator, PhaseMap<T>& phaseMap, bool isEnd) : _orchestrator{orchestrator}, _phaseMap{phaseMap}, _isEnd{isEnd}, _currentPhase{0}, _awaitingPlusPlus{false} {} ActorPhase<T>& operator*() /* cannot be const */ { assert(!_awaitingPlusPlus); // Intentionally don't bother with cases where user didn't call operator++() // between invocations of operator*() and vice-versa. _currentPhase = this->_orchestrator.awaitPhaseStart(); if (!this->doesBlockOn(_currentPhase)) { this->_orchestrator.awaitPhaseEnd(false); } _awaitingPlusPlus = true; auto&& found = _phaseMap.find(_currentPhase); if (found == _phaseMap.end()) { // We're (incorrectly) constructed outside of the conventional flow, // i.e., the `PhaseLoop(ActorContext&)` ctor. Could also happen if Actors // are configured with different sets of Phase numbers. std::stringstream msg; msg << "No phase config found for PhaseNumber=[" << _currentPhase << "]"; throw InvalidConfigurationException(msg.str()); } return found->second; } PhaseLoopIterator& operator++() { assert(_awaitingPlusPlus); // Intentionally don't bother with cases where user didn't call operator++() // between invocations of operator*() and vice-versa. if (this->doesBlockOn(_currentPhase)) { this->_orchestrator.awaitPhaseEnd(true); } _awaitingPlusPlus = false; return *this; } constexpr bool operator!=(const PhaseLoopIterator& other) const { // Intentionally don't handle self-equality or other "normal" cases. return !(other._isEnd && !this->morePhases()); } private: constexpr bool morePhases() const { return this->_orchestrator.morePhases(); } constexpr bool doesBlockOn(PhaseNumber phase) const { if (auto item = _phaseMap.find(phase); item != _phaseMap.end()) { return item->second.doesBlock(); } return true; } Orchestrator& _orchestrator; PhaseMap<T>& _phaseMap; // cannot be const; owned by PhaseLoop const bool _isEnd; // can't just always look this up from the Orchestrator. When we're // doing operator++() we need to know what the value of the phase // was during operator*() so we can check if it was blocking or not. // If we don't store the value during operator*() the Phase value // may have changed already. PhaseNumber _currentPhase; // helps detect accidental mis-use. General contract // of this iterator (as used by range-based for) is that // the user will alternate between operator*() and operator++() // (starting with operator*()), so we flip this back-and-forth // in operator*() and operator++() and assert the correct value. // If the user calls operator*() twice without calling operator++() // between, we'll fail (and similarly for operator++()). bool _awaitingPlusPlus; // These are intentionally commented-out because this type // should not be used by any std algorithms that may rely on them. // This type should only be used by range-based for loops (which doesn't // rely on these typedefs). This should *hopefully* prevent some cases of // accidental mis-use. // // Decided to leave this code commented-out rather than deleting it // partially to document this shortcoming explicitly but also in case // we want to support the full concept in the future. // https://en.cppreference.com/w/cpp/named_req/InputIterator // // <iterator-concept> // typedef std::forward_iterator_tag iterator_category; // typedef PhaseNumber value_type; // typedef PhaseNumber reference; // typedef PhaseNumber pointer; // typedef std::ptrdiff_t difference_type; // </iterator-concept> }; // class PhaseLoopIterator } // namespace v1 /** * @return an object that iterates over all configured Phases, calling `awaitPhaseStart()` * and `awaitPhaseEnd()` at the appropriate times. The value-type, `ActorPhase`, * is also iterable so your Actor can loop for the entire duration of the Phase. * * Note that `PhaseLoop`s are relatively expensive to construct and should be constructed * at actor-constructor time. * * Example usage: * * ```c++ * struct MyActor : public Actor { * * private: * // Actor-private struct that the Actor uses to determine what * // to do for each Phase. Likely holds Expressions or other * // expensive-to-construct objects. PhaseLoop will construct these * // at Actor setup time rather than at runtime. * struct MyActorConfig { * int _myImportantThing; * // Must have a ctor that takes a PhaseContext& as first arg. * // Other ctor args are forwarded from PhaseLoop ctor. * MyActorConfig(PhaseContext& phaseConfig) * : _myImportantThing{phaseConfig.get<int>("ImportantThing")} {} * }; * * PhaseLoop<MyActorConfig> _loop; * * public: * MyActor(ActorContext& actorContext) * : _loop{actorContext} {} * // if your MyActorConfig takes other ctor args, pass them through * // here e.g. _loop{actorContext, someOtherParam} * * void run() { * for(auto&& [phaseNum, actorPhase] : _loop) { // (1) * // Access the MyActorConfig for the Phase * // by using operator->() or operator*(). * auto importantThingForThisPhase = actorPhase->_myImportantThing; * * // The actorPhase itself is iterable * // this loop will continue running as long * // as required per configuration conventions. * for(auto&& _ : actorPhase) { // (2) * doOperation(actorPhase); * } * } * } * }; * ``` * * Internal note: * (1) is implemented using PhaseLoop and PhaseLoopIterator. * (2) is implemented using ActorPhase and ActorPhaseIterator. * */ template <class T> class PhaseLoop final { public: template <class... Args> explicit PhaseLoop(ActorContext& context, Args&&... args) : PhaseLoop(context.orchestrator(), std::move(constructPhaseMap(context, std::forward<Args>(args)...))) { // Some of these static_assert() calls are redundant. This is to help // users more easily track down compiler errors. // // Don't do this at the class level because tests want to be able to // construct a simple PhaseLoop<int>. static_assert(std::is_constructible_v<T, PhaseContext&, Args...>); } // Only visible for testing PhaseLoop(Orchestrator& orchestrator, v1::PhaseMap<T> phaseMap) : _orchestrator{orchestrator}, _phaseMap{std::move(phaseMap)} { // propagate this Actor's set up PhaseNumbers to Orchestrator } v1::PhaseLoopIterator<T> begin() { return v1::PhaseLoopIterator<T>{this->_orchestrator, this->_phaseMap, false}; } v1::PhaseLoopIterator<T> end() { return v1::PhaseLoopIterator<T>{this->_orchestrator, this->_phaseMap, true}; } private: template <class... Args> static v1::PhaseMap<T> constructPhaseMap(ActorContext& actorContext, Args&&... args) { // clang-format off static_assert(std::is_constructible_v<T, PhaseContext&, Args...>); // kinda redundant with ↑ but may help error-handling static_assert(std::is_constructible_v<v1::ActorPhase<T>, Orchestrator&, PhaseContext&, PhaseNumber, PhaseContext&, Args...>); // clang-format on v1::PhaseMap<T> out; for (auto&& [num, phaseContext] : actorContext.phases()) { auto [it, success] = out.try_emplace( // key num, // args to ActorPhase<T> ctor: actorContext.orchestrator(), *phaseContext, num, // last arg(s) get forwarded to T ctor (via forward inside of make_unique) *phaseContext, std::forward<Args>(args)...); if (!success) { // This should never happen because genny::ActorContext::constructPhaseContexts // ensures we can't configure duplicate Phases. std::stringstream msg; msg << "Duplicate phase " << num; throw InvalidConfigurationException(msg.str()); } } return out; } Orchestrator& _orchestrator; v1::PhaseMap<T> _phaseMap; // _phaseMap cannot be const since we don't want to enforce // the wrapped unique_ptr<T> in ActorPhase<T> to be const. }; // class PhaseLoop } // namespace genny #endif // HEADER_10276107_F885_4F2C_B99B_014AF3B4504A_INCLUDED
3628be87a05bb989935e87d05ab92f02154ed9a2
0de0000dca1e26313d24e90f311a0bbedc272dd7
/codecs/json/codec.hpp
d92563f0529371840fad36a7a68167e8ce2e62a1
[ "MIT" ]
permissive
garettbass/reflect
efbd06032ac3fe0b155738dcecf415063649bc72
e3618446e62ebc53e2066eeea3bbb07b25eeb9e6
refs/heads/master
2021-12-15T08:59:12.283769
2021-12-02T19:10:39
2021-12-02T19:10:39
115,894,990
58
5
null
null
null
null
UTF-8
C++
false
false
103
hpp
codec.hpp
#pragma once namespace reflect { template<typename Decoder, typename Encoder> struct codec }
1286c1b3e488c7c8823e319ddab48dd93d23d213
3f7028cc89a79582266a19acbde0d6b066a568de
/mobile/library/common/extensions/filters/http/local_error/config.h
5132e5e79768f73048a2afc5ec87dbb243adb9b8
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
envoyproxy/envoy
882d3c7f316bf755889fb628bee514bb2f6f66f0
72f129d273fa32f49581db3abbaf4b62e3e3703c
refs/heads/main
2023-08-31T09:20:01.278000
2023-08-31T08:58:36
2023-08-31T08:58:36
65,214,191
21,404
4,756
Apache-2.0
2023-09-14T21:56:37
2016-08-08T15:07:24
C++
UTF-8
C++
false
false
1,030
h
config.h
#include <string> #include "source/extensions/filters/http/common/factory_base.h" #include "library/common/extensions/filters/http/local_error/filter.pb.h" #include "library/common/extensions/filters/http/local_error/filter.pb.validate.h" namespace Envoy { namespace Extensions { namespace HttpFilters { namespace LocalError { /** * Config registration for the local_error filter. @see NamedHttpFilterConfigFactory. */ class LocalErrorFilterFactory : public Common::FactoryBase<envoymobile::extensions::filters::http::local_error::LocalError> { public: LocalErrorFilterFactory() : FactoryBase("local_error") {} private: ::Envoy::Http::FilterFactoryCb createFilterFactoryFromProtoTyped( const envoymobile::extensions::filters::http::local_error::LocalError& config, const std::string& stats_prefix, Server::Configuration::FactoryContext& context) override; }; DECLARE_FACTORY(LocalErrorFilterFactory); } // namespace LocalError } // namespace HttpFilters } // namespace Extensions } // namespace Envoy
1e8b664460e385260ae2072caa3bea2752d0f92a
5f7469de7ba2aab1f89adac8c4c2fc6bcecc93a7
/Algorithm/1181.cpp
355c718cab2fd18a39e6dccd99399968ca07f016
[]
no_license
SeoMuseong/Algorithm
cf65f3ec8093258cc7d6ac12f579d52167a0e1db
055551ab12d03fd6938054484de3aced5a2da827
refs/heads/master
2023-08-23T16:15:30.523002
2021-10-20T16:55:54
2021-10-20T16:55:54
414,271,613
0
0
null
null
null
null
UTF-8
C++
false
false
558
cpp
1181.cpp
#include <iostream> #include <vector> #include <algorithm> #include <string> using namespace std; int N; string* str = nullptr; bool comp(string s1, string s2) { if (s1.length() < s2.length()) return true; else if(s1.length() == s2.length()) return s1 < s2; return false; } int main() { cin >> N; str = new string[N]; string ans2; for (int i = 0; i < N; i++) { cin >> str[i]; } sort(str, str + N, comp); for (int i = 0; i < N; i++) { if (ans2 != str[i]) { ans2 = str[i]; cout << ans2 << '\n'; } } delete[] str; return 0; }
bdd18b5cf4b16b1316c23db96aaaf20bba0b5719
7bb11750e13e2bbc63b3db83d178cfdced0531ef
/src/utils.cpp
3d2c54413c5c75644499ad6ad1bebfa09b77270c
[ "MIT" ]
permissive
jltsiren/gcsa2
3b3b0e749526dca0cb57c21fabfe10cdbf0de1e9
d246cfd5dbe0d45546f28213c0245aa308bdb462
refs/heads/master
2023-08-03T04:08:05.205238
2023-08-02T11:21:51
2023-08-02T11:21:51
32,087,454
77
13
MIT
2023-08-02T11:21:53
2015-03-12T16:20:15
C++
UTF-8
C++
false
false
7,221
cpp
utils.cpp
/* Copyright (c) 2018, 2019 Jouni Siren Copyright (c) 2015, 2016, 2017 Genome Research Ltd. Author: Jouni Siren <jouni.siren@iki.fi> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <gcsa/utils.h> #include <cstdio> #include <cstdlib> #include <set> #include <sstream> #include <sys/resource.h> #include <unistd.h> #include <gcsa/internal.h> namespace gcsa { //------------------------------------------------------------------------------ // Numerical class constants. constexpr size_type Verbosity::SILENT; constexpr size_type Verbosity::BASIC; constexpr size_type Verbosity::EXTENDED; constexpr size_type Verbosity::DEFAULT; constexpr size_type Verbosity::FULL; constexpr size_type Version::MAJOR_VERSION; constexpr size_type Version::MINOR_VERSION; constexpr size_type Version::PATCH_VERSION; constexpr size_type Version::GCSA_VERSION; constexpr size_type Version::LCP_VERSION; //------------------------------------------------------------------------------ // Other class variables. size_type Verbosity::level = Verbosity::DEFAULT; //------------------------------------------------------------------------------ void Verbosity::set(size_type new_level) { level = Range::bound(new_level, SILENT, FULL); } std::string Verbosity::levelName() { switch(level) { case SILENT: return "silent"; break; case BASIC: return "basic"; break; case EXTENDED: return "extended"; break; case FULL: return "full"; break; } return "unknown"; } //------------------------------------------------------------------------------ std::string Version::str(bool verbose) { std::ostringstream ss; if(verbose) { ss << "GCSA2 version "; } else { ss << "v"; } ss << MAJOR_VERSION << "." << MINOR_VERSION << "." << PATCH_VERSION; if(verbose) { ss << " (GCSA version " << GCSA_VERSION << ", LCP version " << LCP_VERSION << ")"; } return ss.str(); } void Version::print(std::ostream& out, const std::string& tool_name, bool verbose, size_type new_lines) { out << tool_name; if(verbose) { out << std::endl; } else { out << " "; } out << str(verbose); for(size_type i = 0; i < new_lines; i++) { out << std::endl; } } //------------------------------------------------------------------------------ void printHeader(const std::string& header, size_type indent) { std::string padding; if(header.length() + 1 < indent) { padding = std::string(indent - 1 - header.length(), ' '); } std::cout << header << ":" << padding; } void printTime(const std::string& header, size_type queries, double seconds, size_type indent) { printHeader(header, indent); std::cout << queries << " queries in " << seconds << " seconds (" << inMicroseconds(seconds / queries) << " µs/query)" << std::endl; } //------------------------------------------------------------------------------ double readTimer() { return omp_get_wtime(); } size_type memoryUsage() { rusage usage; getrusage(RUSAGE_SELF, &usage); #if defined(__APPLE__) && defined(__MACH__) return usage.ru_maxrss; #else return KILOBYTE * usage.ru_maxrss; #endif } size_type readVolume() { return DiskIO::read_volume; } size_type writeVolume() { return DiskIO::write_volume; } //------------------------------------------------------------------------------ namespace TempFile { size_type counter = 0; const std::string DEFAULT_TEMP_DIR = "."; std::string temp_dir = DEFAULT_TEMP_DIR; // By storing the filenames in a static object, we can delete the remaining // temporary files when std::exit() is called. struct Handler { std::set<std::string> filenames; ~Handler() { for(auto& filename : this->filenames) { std::remove(filename.c_str()); } } } handler; void setDirectory(const std::string& directory) { if(directory.empty()) { temp_dir = DEFAULT_TEMP_DIR; } else if(directory[directory.length() - 1] != '/') { temp_dir = directory; } else { temp_dir = directory.substr(0, directory.length() - 1); } } std::string getName(const std::string& name_part) { char hostname[32]; gethostname(hostname, 32); hostname[31] = 0; std::string filename = temp_dir + '/' + name_part + '_' + std::string(hostname) + '_' + sdsl::util::to_string(sdsl::util::pid()) + '_' + sdsl::util::to_string(counter); handler.filenames.insert(filename); counter++; return filename; } void remove(std::string& filename) { if(!(filename.empty())) { std::remove(filename.c_str()); handler.filenames.erase(filename); filename.clear(); } } void forget() { handler.filenames.clear(); counter = 0; } } // namespace TempFile size_type readRows(const std::string& filename, std::vector<std::string>& rows, bool skip_empty_rows) { std::ifstream input(filename.c_str(), std::ios_base::binary); if(!input) { std::cerr << "readRows(): Cannot open input file " << filename << std::endl; return 0; } size_type chars = 0; while(input) { std::string buf; std::getline(input, buf); if(skip_empty_rows && buf.empty()) { continue; } rows.push_back(buf); chars += buf.length(); } input.close(); return chars; } size_type fileSize(std::ifstream& file) { std::streamoff curr = file.tellg(); file.seekg(0, std::ios::end); std::streamoff size = file.tellg(); file.seekg(0, std::ios::beg); size -= file.tellg(); file.seekg(curr, std::ios::beg); return size; } size_type fileSize(std::ofstream& file) { std::streamoff curr = file.tellp(); file.seekp(0, std::ios::end); std::streamoff size = file.tellp(); file.seekp(0, std::ios::beg); size -= file.tellp(); file.seekp(curr, std::ios::beg); return size; } //------------------------------------------------------------------------------ size_type getChunkSize(size_type n, size_type min_size) { size_type threads = omp_get_max_threads(); size_type chunks = std::max(threads, (size_type)8) * threads; size_type chunk_size = n / chunks; return std::max(chunk_size, min_size); } //------------------------------------------------------------------------------ } // namespace gcsa
c25008be14b720a7de80bddc6ddd12d23799a7d9
bb60ffdb40f49222d269f745c2699741d8f367c9
/objects/Building.h
e081863e919f1b1f7c820b46f84395d9b63375ef
[]
no_license
regality/opengl-turret
28f446d2a9d56837b07675a3997e9243f42694da
46086b298e0027b3a291fa8b71779207d2bb1c06
refs/heads/master
2021-01-01T06:34:02.098499
2011-10-11T08:50:31
2011-10-11T08:50:31
2,551,320
1
0
null
null
null
null
UTF-8
C++
false
false
350
h
Building.h
#ifndef Building_h #define Building_h #include <cmath> #include <GL/glut.h> #include <GL/gl.h> #include "Cube.h" class Building : public Cube { private: float pos[3]; float height; float width; public: Building(float x, float z, float h, float w); float posX(); float posZ(); void draw(); }; #endif
2704dce90c1d65c8db7c2585197415c55a904e24
dd8714a71c05e387e239ff6e5d52c09219fdc624
/module/mpc-be/SRC/src/filters/parser/AudioSplitter/MPC7File.cpp
9e0268884132f68b6af6897c5196f602c3d29ff9
[ "MIT" ]
permissive
dbyoung720/PBox
bbd6a77bad5bd7673f4c9dcbf2eec024ff01e0ce
d71740d858896dceee74f7412afad26a0eb56324
refs/heads/master
2023-01-23T01:39:29.638523
2023-01-03T06:01:07
2023-01-03T06:01:07
303,229,311
35
29
null
null
null
null
UTF-8
C++
false
false
4,696
cpp
MPC7File.cpp
/* * (C) 2020 see Authors.txt * * This file is part of MPC-BE. * * MPC-BE is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * MPC-BE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "stdafx.h" #include "MPC7File.h" #define MPC_FRAMESAMPLES 1152 #define ID3v1_TAG_SIZE 128 // // CMPC7File // CMPC7File::CMPC7File() : CAudioFile() { m_channels = 2; m_bitdepth = 16; m_subtype = MEDIASUBTYPE_MPC7; m_wFormatTag = 0x504d; } CMPC7File::~CMPC7File() { SAFE_DELETE(m_pID3Tag); } void CMPC7File::SetProperties(IBaseFilter* pBF) { __super::SetProperties(pBF); if (!m_pAPETag && m_pID3Tag) { SetID3TagProperties(pBF, m_pID3Tag); } } static const int freq[] = { 44100, 48000, 37800, 32000 }; HRESULT CMPC7File::Open(CBaseSplitterFile* pFile) { m_pFile = pFile; m_pFile->Seek(0); if (m_pFile->GetLength() <= 24) { return E_FAIL; } DWORD id = 0; if (m_pFile->ByteRead((BYTE*)&id, 4) != S_OK || (id & 0x00ffffff) != FCC('MP+\0') || ((id >> 24) & 0x0f) != 0x7) { return E_FAIL; } if (m_pFile->ByteRead((BYTE*)&m_frames_cnt, 4) != S_OK || !m_frames_cnt) { return E_FAIL; } if ((uint64_t)m_frames_cnt * sizeof(mpc_frame_t) >= UINT_MAX) { return E_FAIL; } m_extrasize = 16; m_extradata = (BYTE*)malloc(m_extrasize); if (m_pFile->ByteRead(m_extradata, m_extrasize) != S_OK) { return E_FAIL; } const auto samplerateidx = m_extradata[2] & 3; m_samplerate = freq[samplerateidx]; m_rtduration = llMulDiv(UNITS, (int64_t)m_frames_cnt * MPC_FRAMESAMPLES, m_samplerate, 0); m_startpos = m_pFile->GetPos(); m_endpos = m_pFile->GetLength(); size_t tag_size; if (ReadApeTag(tag_size)) { m_endpos -= tag_size; } else if (m_startpos + ID3v1_TAG_SIZE < m_endpos) { m_pFile->Seek(m_endpos - ID3v1_TAG_SIZE); if (m_pFile->BitRead(24) == 'TAG') { m_pID3Tag = DNew CID3Tag(); tag_size = ID3v1_TAG_SIZE - 3; std::unique_ptr<BYTE[]> ptr(new(std::nothrow) BYTE[tag_size]); if (ptr && m_pFile->ByteRead(ptr.get(), tag_size) == S_OK) { m_pID3Tag->ReadTagsV1(ptr.get(), tag_size); } m_endpos -= ID3v1_TAG_SIZE; if (m_pID3Tag->TagItems.empty()) { SAFE_DELETE(m_pID3Tag); } } } m_pFile->Seek(m_startpos); m_frames.resize(m_frames_cnt); uint32_t stream_curbits = 8; for (auto& frame : m_frames) { const auto pos = m_pFile->GetPos(); uint32_t tmp, size2, curbits; if (m_pFile->ByteRead((BYTE*)&tmp, 4) != S_OK) { return E_FAIL; } curbits = stream_curbits; if (curbits <= 12) { size2 = (tmp >> (12 - curbits)) & 0xFFFFF; } else { uint32_t tmp2; if (m_pFile->ByteRead((BYTE*)&tmp2, 4) != S_OK) { return E_FAIL; } size2 = (tmp << (curbits - 12) | tmp2 >> (44 - curbits)) & 0xFFFFF; } curbits += 20; m_pFile->Seek(pos); uint32_t size = ((size2 + curbits + 31) & ~31) >> 3; stream_curbits = (curbits + size2) & 0x1F; frame.pos = pos; frame.size = size + 4; frame.curbits = curbits; m_pFile->Seek(pos + size); if (stream_curbits) { m_pFile->Seek(m_pFile->GetPos() - 4); } } m_pFile->Seek(m_startpos); return S_OK; } REFERENCE_TIME CMPC7File::Seek(REFERENCE_TIME rt) { if (rt <= UNITS) { m_currentframe = 0; m_pFile->Seek(m_frames.front().size); return 0; } const auto pos = llMulDiv(rt - UNITS, m_samplerate, UNITS, 0); m_currentframe = pos / MPC_FRAMESAMPLES; if (m_currentframe >= m_frames.size()) { m_currentframe = m_frames.size() - 1; } rt = llMulDiv(UNITS, (uint64_t)m_currentframe * MPC_FRAMESAMPLES, m_samplerate, 0); return rt; } int CMPC7File::GetAudioFrame(CPacket* packet, REFERENCE_TIME rtStart) { if (m_currentframe >= m_frames.size()) { return 0; } const auto& frame = m_frames[m_currentframe]; packet->SetCount(frame.size); packet->data()[0] = frame.curbits; if (m_currentframe == m_frames.size() - 1) { packet->data()[1] = 1; } m_pFile->Seek(frame.pos); if (m_pFile->ByteRead(packet->data() + 4, frame.size - 4) != S_OK) { return 0; } packet->rtStart = llMulDiv(UNITS, (uint64_t)m_currentframe * MPC_FRAMESAMPLES, m_samplerate, 0); m_currentframe++; packet->rtStop = llMulDiv(UNITS, (uint64_t)m_currentframe * MPC_FRAMESAMPLES, m_samplerate, 0); return frame.size; }
792210153b4fda381448a1807a7ccfda2b6b85a2
e0edbd7b0bdc1e5554137fe5d9886f1e4e9efcd6
/contest46/661Image Smoother.cpp
630e17227bf6701ca6025da05c042f6f45e3e2a7
[]
no_license
ucas-joy/weekly-contest
c09d3e6e5f3d8125d5ebc9207ff34dfae79d9856
2fc3ebe9e1e9a7f49bb7f63dcbdb5a3e33e45103
refs/heads/master
2021-01-22T19:22:29.338357
2017-08-20T03:26:59
2017-08-20T03:26:59
100,775,310
0
0
null
null
null
null
UTF-8
C++
false
false
1,444
cpp
661Image Smoother.cpp
#include<iostream> #include<vector> using namespace std; class Solution { public: vector<vector<int>> imageSmoother(vector<vector<int>>& M) { vector<vector<int>>res; int row = M.size(); int col = M[0].size(); for (int i = 0; i < row; ++i) { vector<int>tmp; for (int j = 0; j < col; ++j) { int count = 1; int sum = M[i][j]; if (i - 1 >= 0) { sum += M[i - 1][j]; count++; } if (j - 1 >= 0) { sum += M[i][j - 1]; count++; } if (i - 1 >= 0 && j - 1 >= 0) { sum += M[i - 1][j - 1]; count++; } if (i + 1 < row) { sum += M[i + 1][j]; count++; } if (j + 1 < col) { sum += M[i][j + 1]; count++; } if (i + 1 < row && j + 1 < col) { sum += M[i + 1][j + 1]; count++; } if (i - 1 >= 0 && j + 1 < col) { sum += M[i - 1][j + 1]; ++count; } if (i + 1 < row && j - 1 >= 0) { sum += M[i + 1][j - 1]; ++count; } sum = sum / count; tmp.push_back(sum); } res.push_back(tmp); } return res; } }; int main661() { vector<vector<int>>a{ {2,3,4}, {5,6,7}, {8,9,10}, {11,12,13}, {14,15,16} }; Solution s; vector<vector<int>>res = s.imageSmoother(a); for (int i = 0; i < res.size(); ++i) { for (int j = 0; j < res[0].size(); ++j) { cout << res[i][j] << " "; } cout << endl; } return 0; }
2b25a18768724ceb452408c7b79c8fed65ba2a5b
c1b2e1fb29092cf7ac0827cb373a76f014fd5c69
/rover_simulation/src/nodes/controller_server/ControllerServerMain.cpp
7c930cd287fb7b644cc0487883595742cbd71677
[]
no_license
pwalczykk/phobos_simulation
15d13da021f869e506d7c356f78b0b84fa998990
cc0d7a94809198779f58a1e5a3dd618daee522de
refs/heads/master
2021-06-15T14:14:18.202193
2016-08-16T16:48:02
2016-08-16T16:48:02
58,233,332
1
0
null
null
null
null
UTF-8
C++
false
false
439
cpp
ControllerServerMain.cpp
#include "ControllerServer.hpp" int main(int argc, char** argv) { ros::init(argc, argv, "ControllerServer"); double Kp = atof(argv[argc-4]); double Ki = atof(argv[argc-3]); double Kd = atof(argv[argc-2]); ControllerServer server(argv[argc-1], Kp,Ki,Kd); // Jako argument przyjmuje topic dla nastawów regulatora ROS_ERROR("%f %f %f", Kp, Ki, Kd); server.SetPID(Kp, Ki, Kd); ros::spin(); return 0; }
aba9829259f72da7ff09c581c16039445e9b0c11
44b3e2ca9777e6b8186b8b2eb7c390d1c4c4c8bc
/src/librearcam/NX_CDeinterlaceFilter.h
422d6b387ccfc7a08c0ec27076c08199a43323cf
[]
no_license
NexellCorp/linux_apps_NxQuickRearCam
78d7f40599e91965d8877cd11f34925121f9f240
df7a25f077b714ac1e24501e48d26cad666175c5
refs/heads/master
2021-07-11T02:33:50.861562
2020-06-12T04:29:23
2020-06-12T06:14:42
170,825,661
0
1
null
null
null
null
UTF-8
C++
false
false
4,891
h
NX_CDeinterlaceFilter.h
//------------------------------------------------------------------------------ // // Copyright (C) 2016 Nexell Co. All Rights Reserved // Nexell Co. Proprietary & Confidential // // NEXELL INFORMS THAT THIS CODE AND INFORMATION IS PROVIDED "AS IS" BASE // AND WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING // BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS // FOR A PARTICULAR PURPOSE. // // Module : // File : // Description : // Author : // Export : // History : // //------------------------------------------------------------------------------ #ifndef __NX_CDEINTERLACEFILTER_H__ #define __NX_CDEINTERLACEFILTER_H__ #ifdef __cplusplus #include <NX_CBaseFilter.h> //#include <nx_video_api.h> #include <nxp_video_alloc.h> #ifdef ANDROID_SURF_RENDERING #include <NX_CAndroidRenderer.h> #endif enum nx_deinter_engine { NON_SW_DEINTERLACER = 0, NEXELL_SW_DEINTERLACER, THUNDER_SW_DEINTERLACER, DEINTERLACER_ENGINE_MAX }; typedef struct NX_DEINTERLACE_INFO { int32_t width; int32_t height; int32_t engineSel; int32_t corr; } NX_DEINTERLACE_INFO; class NX_CDeiniterlaceInputPin; class NX_CDeiniterlaceOutputPin; //------------------------------------------------------------------------------ class NX_CDeinterlaceFilter : public NX_CBaseFilter { public: NX_CDeinterlaceFilter(); virtual ~NX_CDeinterlaceFilter(); public: virtual void* FindInterface( const char* pFilterId, const char* pFilterName, const char* pInterfaceId ); virtual NX_CBasePin* FindPin( int32_t iDirection, int32_t iIndex ); virtual void GetFilterInfo( NX_FILTER_INFO *pInfo ); virtual int32_t Run( void ); virtual int32_t Stop( void ); virtual int32_t Pause( int32_t ); virtual int32_t Capture( int32_t iQuality ); virtual void RegFileNameCallback( int32_t (*cbFunc)(uint8_t*, uint32_t) ); int32_t Init( void ); int32_t Deinit( void ); #ifdef ANDROID_SURF_RENDERING int32_t SetConfig (NX_DEINTERLACE_INFO *pDeinterInf, NX_CAndroidRenderer *m_pAndroidRender); NX_CAndroidRenderer *m_pAndroidRender; #else int32_t SetConfig (NX_DEINTERLACE_INFO *pDeinterInf); #endif void SetDeviceFD(int32_t mem_dev_fd); private: static void *ThreadStub( void *pObj ); void ThreadProc( void ); int32_t Deinterlace( NX_CSample *pInSample, NX_CSample *pOutSample ); private: //enum { MAX_INPUT_NUM = 256, MAX_OUTPUT_NUM = 8 }; enum { MAX_INPUT_NUM = 256, MAX_OUTPUT_NUM = 4 }; enum { MAX_FILENAME_SIZE = 1024 }; NX_CDeiniterlaceInputPin *m_pInputPin; NX_CDeiniterlaceOutputPin *m_pOutputPin; pthread_t m_hThread; pthread_attr_t thread_attrs; int32_t m_bThreadRun; NX_CMutex m_hLock; void *hDeInterlace; NX_DEINTERLACE_INFO m_DeinterInfo; private: int32_t m_bCapture; int32_t m_iCaptureQuality; char* m_pFileName; int32_t (*FileNameCallbackFunc)( uint8_t *pBuf, uint32_t iBufSize ); int32_t m_MemDevFd; private: NX_CDeinterlaceFilter (const NX_CDeinterlaceFilter &Ref); NX_CDeinterlaceFilter &operator=(const NX_CDeinterlaceFilter &Ref); }; //------------------------------------------------------------------------------ class NX_CDeiniterlaceInputPin : public NX_CBaseInputPin { public: NX_CDeiniterlaceInputPin(); virtual ~NX_CDeiniterlaceInputPin(); public: virtual int32_t Receive( NX_CSample *pSample ); virtual int32_t GetSample( NX_CSample **ppSample ); virtual int32_t Flush( void ); virtual int32_t PinNegotiation( NX_CBaseOutputPin *pOutPin ); int32_t AllocateBuffer( int32_t iNumOfBuffer ); void FreeBuffer( void ); void ResetSignal( void ); private: NX_CSampleQueue *m_pSampleQueue; NX_CSemaphore *m_pSemQueue; private: NX_CDeiniterlaceInputPin (const NX_CDeiniterlaceInputPin &Ref); NX_CDeiniterlaceInputPin &operator=(const NX_CDeiniterlaceInputPin &Ref); }; //------------------------------------------------------------------------------ class NX_CDeiniterlaceOutputPin : public NX_CBaseOutputPin { public: NX_CDeiniterlaceOutputPin(); virtual ~NX_CDeiniterlaceOutputPin(); public: virtual int32_t ReleaseSample( NX_CSample *pSample ); virtual int32_t GetDeliverySample( NX_CSample **ppSample ); void SetDeviceFD(int32_t mem_dev_fd); #ifndef ANDROID_SURF_RENDERING int32_t AllocateVideoBuffer(int32_t iNumOfBuffer); #else int32_t AllocateVideoBuffer( int32_t iNumOfBuffer, NX_CAndroidRenderer *pAndroidRender); #endif int32_t AllocateBuffer( int32_t iNumOfBuffer ); void FreeVideoBuffer(); void FreeBuffer( void ); void ResetSignal( void ); private: NX_CSampleQueue *m_pSampleQueue; NX_CSemaphore *m_pSemQueue; NX_VID_MEMORY_HANDLE *m_hVideoMemory; int32_t m_iNumOfBuffer; int32_t m_MemDevFd; private: NX_CDeiniterlaceOutputPin (const NX_CDeiniterlaceOutputPin &Ref); NX_CDeiniterlaceOutputPin &operator=(const NX_CDeiniterlaceOutputPin &Ref); }; #endif // __cplusplus #endif // __NX_CDEINTERLACEFILTER_H__
a47f93e032593fa7a8b9d2f8ab28b2ff4508a20b
fb6343f8a1e2a4922b02f4413a80020549dc6d64
/17/17.11/两组连加.cpp
a62d493e1dffd3b7ecaadba8c66fcdc99b1338f2
[]
no_license
xzbat/learn-c
daa3edb2bec1bea358020d119a4b311d348d8524
3819340d025df318535e68c3d136be5a275ad55b
refs/heads/master
2020-03-07T10:28:27.576496
2018-04-24T07:25:10
2018-04-24T07:25:10
127,432,320
1
0
null
null
null
null
UTF-8
C++
false
false
204
cpp
两组连加.cpp
#include<stdio.h> int main() { long a, b, i, j; scanf("%ld%ld",&a,&b); long s1=0, s2=0; for(i=1;i<a;i++) { s1=s1+i; } for(j=1;j<b;j++) { s2=s2+j; } printf("%ld\n%d\n",s1,s2); return 0; }
1b3d44af1b854db9d4a7db1148c57ed719b00680
1d16fdcbd5fbd91d8325170cb74115a045cf24bb
/CSCommon/Include/MAsyncDBJob_InsertGamePlayerLog.h
9442dc0d141e1452d1cf0a9efd7e931d24aa5d35
[]
no_license
kooksGame/life-marvelous
fc06a3c4e987dc5fbdb5275664e06f2934409b90
82b6dcb107346e980d5df31daf4bb14452e3450d
refs/heads/master
2021-01-10T08:32:53.353758
2013-07-28T18:15:09
2013-07-28T18:15:09
35,994,219
1
1
null
null
null
null
UTF-8
C++
false
false
574
h
MAsyncDBJob_InsertGamePlayerLog.h
#pragma once #include "MAsyncDBJob.h" class MAsyncDBJob_InsertGamePlayerLog : public MAsyncJob { protected: // Input Argument int m_nGameLogID; int m_nCID; int m_nPlayTime; int m_nKills; int m_nDeaths; int m_nXP; int m_nBP; protected: // Output Result public: MAsyncDBJob_InsertGamePlayerLog() : MAsyncJob(MASYNCJOB_INSERTGAMEPLAYERLOG, MUID(0, 0)) {} virtual ~MAsyncDBJob_InsertGamePlayerLog() {} bool Input(int nGameLogID, int nCID, int nPlayTime, int nKills, int nDeaths, int nXP, int nBP); virtual void Run(void* pContext); };
739a2c3674cfc7ca66f572c6c06aafdb896e575d
618734c07c3cd262c67bd54d7f10e70c32545ad7
/Source/print.cpp
75018636c1ffcd0624f652d9cadd8f3b1c1b85e7
[]
no_license
Caspila/GUInity
c9e97ed2e0ad4c9c9a9afb3b036cdef2ac4ad204
0fe75e767fd0913ebb00f76afd3d181caa215efd
refs/heads/master
2021-01-22T07:32:47.297635
2015-07-13T07:46:38
2015-07-13T07:46:38
28,250,903
2
3
null
null
null
null
UTF-8
C++
false
false
1,980
cpp
print.cpp
#include "print.hpp" #include "Transform.hpp" #include "Math.hpp" ostream& operator<<(ostream& os, const glm::vec4& vec3) { os << '(' << vec3.x << ',' << vec3.y << ',' << vec3.z << ',' << vec3.w << ')'; return os; } ostream& operator<<(ostream& os, const glm::vec3& vec3) { os << '(' << vec3.x << ',' << vec3.y << ',' << vec3.z << ')'; return os; } ostream& operator<<(ostream& os, const glm::vec2& vec2) { os << '(' << vec2.x << ',' << vec2.y <<')'; return os; } ostream& operator<<(ostream& os, const PxVec3& vec3) { os << '(' << vec3.x << ',' << vec3.y << ',' << vec3.z << ')'; return os; } ostream& operator<<(ostream& os, const Ray& ray) { os << "Origin: " << ray.origin << " Direction: " << ray.direction << endl; return os; } ostream& operator<<(ostream& os, const PxQuat& quat) { os << '(' << quat.x << ',' << quat.y << ',' << quat.z << ',' << quat.w << ')'; return os; } ostream& operator<<(ostream& os, const glm::quat& quat) { os << '(' << quat.x << ',' << quat.y << ',' << quat.z << ',' << quat.w << ')'; return os; } void printVertex(const glm::vec3& vec3) { cout << '(' << vec3.x << ',' << vec3.y << ',' << vec3.z << ')'; } void printVertex(const glm::vec2& vec2) { cout << '(' << vec2.x << ',' << vec2.y << ')'; } //PxVec3 glmVec3ToPhysXVec3(const glm::vec3& vec3) //{ // return PxVec3(vec3.x, vec3.y, vec3.z); //} // //PxQuat glmQuatToPhysXQuat(const glm::quat& quat) //{ // return PxQuat(quat.x, quat.y, quat.z, quat.w); //} // //glm::vec3 PhysXVec3ToglmVec3(const PxVec3& vec3) //{ // return glm::vec3(vec3.x, vec3.y, vec3.z); //} // //glm::quat PhysXQuatToglmQuat(const PxQuat& quat) //{ // //cout << quat.x << "." << quat.y << "." << quat.z << "." << quat.w << "." << endl; // // return glm::quat(quat.x,quat.y,quat.z,quat.w); //} //PxTransform physXTransformToTransform(PxTransform& transform) //{ // return PxTransform(glmVec3ToPhysXVec3(actor->transform->position), glmQuatToPhysXQuat(actor->transform->rotationQuat)); //}
0d2eca388a8c3eadb5f2e281347fd9acaddec1e5
263bfa7db19012c2b6ea9114f957bd9cee7d9cf7
/Document_Search/test/libraryIndexerTest.cpp
f087c2c21203e591fa9afe67fd81e973daba99ee
[]
no_license
akifyilmaz/Document-Search-Software
28785f9d21517ba512d20797e9c1626a0acabe6e
70925f7900bbbd06c5efb3917ce424e1bb8196b6
refs/heads/main
2023-01-18T16:01:42.651282
2020-12-16T20:23:50
2020-12-16T20:23:50
322,092,303
0
0
null
null
null
null
UTF-8
C++
false
false
1,221
cpp
libraryIndexerTest.cpp
/* * libraryIndexerTest.cpp * * Created on: Dec 16, 2020 * Author: akifdev18 */ #include "gtest/gtest.h" #include "libraryIndexer.h" #include <fstream> namespace { class libraryIndexerTest : public ::testing::Test { protected: libraryIndexer library_Indexer; std::vector<std::string> file_path_vector = {"/home/akifdev18/dir/dir2/file1.txt"}; std::vector<std::string> db = {"not: /home/akifdev18/dir/dir2/file1.txt (1) ", "or: /home/akifdev18/dir/dir2/file1.txt (1) ", "to: /home/akifdev18/dir/dir2/file1.txt (2) ", "be: /home/akifdev18/dir/dir2/file1.txt (2) "}; }; }; TEST_F(libraryIndexerTest, libraryIndexer) { // check the inverted index table for the file1.txt which path is "/home/akifdev18/dir/dir2/". library_Indexer.setFileList(file_path_vector); library_Indexer.createInvertedIndex(); int counter = 0; std::ifstream file; char* home = getenv("HOME"); std::string homedir(home); std::string file_path; file_path = homedir + "/database.dat"; file.open(file_path.c_str()); std::string str; while (std::getline(file,str)) { ASSERT_TRUE(str.compare(db[counter])==0); counter++; } }
2c236230e5e6295ee55122c7ff28a02d0adb13f4
95acf4f6e07ab10c1fb4f95a816e5b61d1c30e3c
/godel_surface_detection/src/nodes/robot_scan_node.cpp
6f674b854d05d73dc023b999c1d0f9e22eaa6f5f
[]
no_license
Jmeyer1292/godel
a0470f4c39264fe69c14523d02653f4e11a566bf
6793ccc2cc4105034287af71612aee11b929b62f
refs/heads/hydro-devel
2020-04-04T19:15:52.227607
2016-01-05T20:53:28
2016-01-05T20:53:28
30,308,164
1
3
null
2017-03-22T21:49:26
2015-02-04T16:20:33
C++
UTF-8
C++
false
false
4,544
cpp
robot_scan_node.cpp
/* Copyright Apr 15, 2014 Southwest Research Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <godel_surface_detection/scan/robot_scan.h> #include <godel_surface_detection/detection/surface_detection.h> #include <godel_surface_detection/interactive/interactive_surface_server.h> #include <pcl/console/parse.h> using namespace godel_surface_detection; // constants const std::string HELP_TEXT = "\n-h Help information\n-m <move mode only (0|1)>\n"; const std::string SEGMENTS_CLOUD_TOPIC = "segments_cloud"; const std::string DISPLAY_TRAJECTORY_TOPIC = "scan_trajectory"; const std::string HOME_POSITION = "home_asus"; // robot scan instance godel_surface_detection::scan::RobotScan RobotScan; // surface detection instance godel_surface_detection::detection::SurfaceDetection SurfDetect; // marker server instance godel_surface_detection::interactive::InteractiveSurfaceServer SurfServer; // defaults const bool DEFAULT_MOVE_ONLY_MODE = true; struct CmdArgs { bool move_mode_only_; }; // functions bool parse_arguments(int argc,char** argv,CmdArgs& args) { //filling defaults args.move_mode_only_ = true; if(argc > 1) { if(pcl::console::find_switch(argc,argv,"-h")) { ROS_INFO_STREAM(HELP_TEXT); return false; } if(pcl::console::find_switch(argc,argv,"-m") && pcl::console::parse(argc,argv,"-m",args.move_mode_only_)>=0) { ROS_INFO_STREAM("arg 'move mode only (-m)': "<<(args.move_mode_only_ ? "true" : "false")); } } return true; } bool init() { // load parameters for all objects bool succeeded = SurfDetect.load_parameters("~/surface_detection") && SurfServer.load_parameters("") && RobotScan.load_parameters("~/robot_scan"); if(succeeded) { ROS_INFO_STREAM("Parameters loaded"); ROS_INFO_STREAM("Robot Scan Parameters: \n"<<RobotScan.params_); if(SurfDetect.init() && SurfServer.init() && RobotScan.init()) { // starting server SurfServer.run(); // adding callbacks to robot scan scan::RobotScan::ScanCallback cb = boost::bind(&detection::SurfaceDetection::add_cloud,&SurfDetect,_1); RobotScan.add_scan_callback(cb); } } else { ROS_ERROR_STREAM("Parameters did not load"); } return succeeded; } int main(int argc,char** argv) { ros::init(argc,argv,"RobotScan_node"); ros::AsyncSpinner spinner(2); spinner.start(); ros::NodeHandle nh; // publishers ros::Publisher point_cloud_publisher = nh.advertise<sensor_msgs::PointCloud2>( SEGMENTS_CLOUD_TOPIC,1); // parsing arguments CmdArgs args; if(!parse_arguments(argc,argv,args)) { return 0; } // initializing all objects if(init()) { // moving to home position RobotScan.get_move_group()->setNamedTarget(HOME_POSITION); if(!RobotScan.get_move_group()->move()) { ROS_ERROR_STREAM("Robot failed to move home"); return 0; } // publish poses RobotScan.publish_scan_poses(DISPLAY_TRAJECTORY_TOPIC); // moving through each pose (do not scan) int reached_points = RobotScan.scan(args.move_mode_only_); ROS_INFO_STREAM("Scan points reached: "<<reached_points); // moving back to home position RobotScan.get_move_group()->setNamedTarget(HOME_POSITION); if(!RobotScan.get_move_group()->move()) { ROS_ERROR_STREAM("Robot failed to move home"); return 0; } // finding surfaces if(SurfDetect.find_surfaces()) { ROS_INFO_STREAM("Publishing segments visuals"); sensor_msgs::PointCloud2 cloud_msg; std::vector<pcl::PolygonMesh> meshes; SurfDetect.get_meshes(meshes); SurfDetect.get_region_colored_cloud(cloud_msg); // adding markers to server for(int i =0;i < meshes.size();i++) { SurfServer.add_surface(meshes[i]); } ros::Duration loop_rate(0.5f); while(ros::ok() ) { point_cloud_publisher.publish(cloud_msg); ros::spinOnce(); loop_rate.sleep(); } point_cloud_publisher.shutdown(); } else { ROS_WARN_STREAM("No surfaces were found, exiting"); } } else { ROS_ERROR_STREAM("Robot scan object did not initialized property"); } spinner.stop(); return 0; }
7108fefebd0c820de33fafc15ee31f0d6e9d0406
5d60c1a4a769b4911791c07297ab4e60b1fb9f04
/Course/StreamFormatting/StreamFormatting/main.cpp
1cac5b6e68f35554f5d605ac505e997e97a3064c
[]
no_license
alernerdev/CPlusPlus
ec39a1d02c04b6b4347bb43a9f66a75f763b80d8
27d184ffbb966ae6f276a26b4586e07a55bb3153
refs/heads/master
2020-03-27T06:27:16.717179
2018-09-22T16:10:27
2018-09-22T16:10:27
146,107,197
0
0
null
null
null
null
UTF-8
C++
false
false
902
cpp
main.cpp
#include <iostream> using std::cout; using std::endl; #include <iomanip> using std::setw; // right justified column width using std::setprecision; // at most floating point precision using std::fixed; // display floating numbers as fixed even if there is no floating point portion #include <cmath> // the old math.h header file where old C math functions are wrapped in std namespace using std::pow; int main() { double amount; double principal = 1000.0; double rate = 0.05; // headers // setw is a NON sticky manipulator -- it applies just once to the very next argument cout << "Year" << setw(21) << "Amount of deposit" << endl; // data // these are sticky -- once set, they are set cout << fixed << setprecision(2); for (int year = 1; year <= 10; year++) { amount = principal * pow(1.0 + rate, year); cout << setw(4) << year << setw(21) << amount << endl; } return 0; }
fb31ac0fb1f17a6747fb08956d5e7e5ebffa6c85
843807ac71c1d935ccb5a4d54456663000f21f8d
/wifi_screen.ino
dcbe1e888ae7eb8972ab172396a7b26d34b0b6ea
[]
no_license
ognjetina/wifi_screen
4e3f39e448a659bcb2773d7de3f3e38d1d677cd8
058fd15be41df1eb37985985d580584f5d3f5fa2
refs/heads/master
2021-05-01T15:14:22.017861
2018-03-06T07:22:42
2018-03-06T07:22:42
121,032,898
0
0
null
null
null
null
UTF-8
C++
false
false
5,377
ino
wifi_screen.ino
#include <ESP8266WiFi.h> #include <WiFiClient.h> #include <ESP8266WebServer.h> #include <ESP8266mDNS.h> #include <ArduinoOTA.h> #include <LiquidCrystal_I2C.h> #include <EEPROM.h> #include <ESP8266HTTPClient.h> #include <ArduinoJson.h> StaticJsonBuffer<200> jsonBuffer; const char* username = "admin"; char password[32] = ""; char wifi[32]; char wifi_pass[32]; bool shouldPing = false; int refreshRate = 3000; String pingAddress = ""; LiquidCrystal_I2C lcd(0x27, 16, 2); ESP8266WebServer server(80); void writeToDisplay(String line1, String line2) { lcd.clear(); lcd.print(line1); lcd.setCursor(0, 1); lcd.print(line2); } void handleDisplay() { if (!server.authenticate(username, password)) return server.requestAuthentication(); if (server.arg("line1") == "" && server.arg("line2") == "") { server.send(400, "text/plain", "Error"); } else { server.send(200, "text/plain", "Lines recived"); writeToDisplay(server.arg("line1"), server.arg("line2")); } } void handlePingStop() { if (!server.authenticate(username, password)) return server.requestAuthentication(); lcd.clear(); shouldPing = false; server.send(200, "text/plain", "Ping stop."); } void handlePing() { if (!server.authenticate(username, password)) return server.requestAuthentication(); if (server.arg("pingAddress") == "" && server.arg("refreshRate") == "") { server.send(400, "text/plain", "Error"); } else { pingAddress = server.arg("pingAddress"); refreshRate = server.arg("refreshRate").toInt(); shouldPing = true; server.send(200, "text/plain", "Ping start."); } } void handleDestroy() { if (!server.authenticate(username, password)) return server.requestAuthentication(); destroyConfiguration(); server.send(200, "text/plain", "Configuration destroyed"); } void handleNotFound() { server.send(404, "text/plain", "nothing to do here..."); } void setup(void) { Serial.begin(9600); //destroyConfiguration(); lcd.begin(); lcd.backlight(); lcd.clear(); if (isConfigured()) { Serial.println("Reading config"); get_wifi().toCharArray(wifi, 32); get_wifi_pass().toCharArray(wifi_pass, 32); get_password().toCharArray(password, 32); lcd.clear(); lcd.print("Connecting to:"); lcd.setCursor(0, 1); lcd.print(wifi); } else { writeToDisplay("Device is not", "configured!"); Serial.println("Waiting for configuration"); bool configured = false; String configurationTemp = ""; String questions[4] = {"Input device password:", "Input wifi:", "Input wifi password:"}; while (!configured) { Serial.println("Expecting configuration: device password,wifi,wifi_pass"); for (int i = 0; i < 3; i++) { Serial.println(questions[i]); while (Serial.available() == 0) { } configurationTemp = Serial.readString(); configurationTemp.trim(); if (configurationTemp.length() < 1) { Serial.println("Invalid input"); i--; } else { Serial.print("You have inputed: "); Serial.println(configurationTemp); switch (i) { case 0: configurationTemp.toCharArray(password, 32); break; case 1: configurationTemp.toCharArray(wifi, 32); break; case 2: configurationTemp.toCharArray(wifi_pass, 32); configured = true; break; default: Serial.println("This is imposiburu!"); } } } Serial.println("------------------------"); Serial.println("Configuration done."); Serial.print("Device Password: "); Serial.println(password); Serial.print("Wifi: "); Serial.println(wifi); Serial.print("Wifi password: "); Serial.println(wifi_pass); Serial.println("------------------------"); } Serial.println("Saving data to eeprom"); set_password(password); set_wifi(String(wifi)); set_wifi_pass(String(wifi_pass)); setToConfigured(); Serial.println("------------------------"); } WiFi.begin(wifi, wifi_pass); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(); Serial.println("Connected"); lcd.clear(); lcd.print(wifi); lcd.setCursor(0, 1); lcd.print(WiFi.localIP()); server.on("/display", handleDisplay); server.on("/destroy", handleDestroy); server.on("/ping", handlePing); server.on("/pingStop", handlePingStop); server.onNotFound(handleNotFound); server.begin(); } void loop(void) { ArduinoOTA.handle(); server.handleClient(); while (shouldPing) { Serial.print("Pinging: "); Serial.println(pingAddress); Serial.print("At rate: "); Serial.println(refreshRate); HTTPClient http; http.begin(pingAddress); int httpCode = http.GET(); if (httpCode = 200) { JsonObject& root = jsonBuffer.parseObject(http.getString()); if (!root.success()) { Serial.println("Serial parse failed"); return; } else { writeToDisplay(root["line1"], root["line2"]); jsonBuffer.clear(); } } else { writeToDisplay("Something went", "wrong!!!"); } http.end(); delay(refreshRate); ArduinoOTA.handle(); server.handleClient(); } }
4503fc2c1458def1100458f52fcc2b60df3e2899
5eb01b2eff25fb0d8fbbb00b02961e565ac3f415
/inst/util/MsgEncryptionUtil.h
9d17a02411ee0981f5995cbc0b66aa150d7367ec
[]
no_license
biglone/LT-PureCodes
3ca6fc47731e2d566cd1c5389cce93e55768933a
22d7ec1a1414bc99a16a050800a2cc9259546b9a
refs/heads/master
2020-05-04T10:29:03.603664
2019-04-02T14:23:40
2019-04-02T14:23:40
179,088,457
0
0
null
null
null
null
UTF-8
C++
false
false
401
h
MsgEncryptionUtil.h
#ifndef _MSG_ENCRYPTION_UTIL_H_ #define _MSG_ENCRYPTION_UTIL_H_ #include <QString> #include <QByteArray> class MsgEncryptionUtil { public: static QByteArray generatePassword(const QString &seed); static QByteArray encrypt(const QByteArray &text, const QByteArray &password); static QByteArray decrypt(const QByteArray &secret, const QByteArray &password); }; #endif // _MSG_ENCRYPTION_UTIL_H_
1fd77e863b6138b1e5aee497aa098ae1355798ca
292861d73519f2ecd0d531c403d2ae3e41de2de0
/het_cpp/FACT_CON.CPP
b2b5e05dd09bf90abf3e6a714826d68bbc4ad3f6
[]
no_license
hetsthr/cpp_cdac
0bcbda19179ab105f5a41dd0e0ad924bd3589ffe
24d497459441d1685f9f8c82c0e3edf6f041b256
refs/heads/master
2020-06-18T17:58:00.264992
2019-07-11T12:37:53
2019-07-11T12:37:53
196,390,782
0
0
null
null
null
null
UTF-8
C++
false
false
318
cpp
FACT_CON.CPP
#include<iostream.h> #include<conio.h> class fact { public: int k,i; fact(int j) { k=1; for(i=1;i<=j;i++) { k=k*i; } cout<<"Fctorial is "<<k; } }; void main() { int b; clrscr(); cout<<"Enter no to find factorial:"; cin>>b; fact a1(b); getch(); }
48a71635ce6cf907ef2936f69e16e25f8176c7cc
a87cb0f806b44a853050dc18962779bc83610f74
/Simulator/mainwindow.cpp
e2d6e86a402590e4e65cacef321a5e693bcfcefe
[]
no_license
IngyN/AssemblyProject
e5c5c7baa1ad75b74653b515727cc3fe6db06202
440b884026dea8d76eee0b6ef6b9ad8a2726fe49
refs/heads/master
2021-01-19T13:26:50.467837
2015-04-15T15:29:05
2015-04-15T15:29:05
32,596,343
0
0
null
null
null
null
UTF-8
C++
false
false
2,616
cpp
mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include <Simulator.h> #include <QMessageBox> #include <iostream> #include <simulatorwindow.h> SimulatorWindow * w0=NULL; MainWindow::MainWindow(QWidget *parent, Simulator * S) : QMainWindow(parent), ui(new Ui::MainWindow) { this->S=S; ui->setupUi(this); ui->memoryFile->setVisible(false); // if(argc>3) // { // cout <<"Error: too many arguments"<<endl; // } // else if(argc==3) // { // // name and textFile and Memory // Simulator S; // if (S.readTextFromFile(argv[1])) // { // if(S.readMemoryFromFile(argv[2])) // S.run(); // } // } // else if(argc==2) // { // // name and textFile // Simulator S; // string s=""; // if(S.readTextFromFile(argv[1])) // { // S.readMemoryFromFile(s); // S.run(); // } // } // else if (argc==1) // { // cout << "Error: too few arguments"<<endl; // string s=""; // Simulator S; // if(S.readTextFromFile(s)) // { // S.readMemoryFromFile(s); // S.run(); // } // else // { // cout <<"\n\nError invalid file\n"<<endl; // } // } } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_clicked() { QMessageBox error(this); QString textSource=ui->textFile->text(); // check file validity bool textOpened=S->readTextFromFile(textSource.toStdString()); bool memOpened=true; //std::cout <<"Shit"<<textOpened<<endl; // If they entered a memory file path if(ui->checkBox->isChecked()) { QString memorySource= ui->memoryFile->text(); memOpened=S->readMemoryFromFile(memorySource.toStdString()); } if(!textOpened) { // Error dialog cannot access text Segment file error.critical(0,"Input error","Cannot access Text Segment file"); error.show(); } if(!memOpened) { cout << "Mem"; // Error dialog cannot access memory file error.critical(0,"Input error","Cannot access memory file"); error.show(); } if(textOpened && memOpened) { // call disassembler. // SimulatorWindow w0 (this, S); // w0.show(); if(!w0) {w0 = new SimulatorWindow(this, S);} if(w0) { w0->show(); this->hide(); } } } void MainWindow::on_checkBox_toggled(bool checked) { ui->memoryFile->setHidden(!checked); }
9655ed595bdcf3a643b20cd149689466c941644c
bed336fc87b09834348f6c3de364953c7558d8bb
/src/stack.cpp
796ace65fd78fb06becffecf4e1de8d05b0b1ab7
[]
no_license
keleslab/mosaics
7bc6b95376d8b8a78427194ef3181be67020de40
786f5db1438015aaa6bac6c423e7b3655e5df946
refs/heads/master
2021-07-14T18:00:09.109482
2020-02-27T00:37:56
2020-02-27T00:37:56
38,325,192
1
0
null
2016-05-02T17:50:57
2015-06-30T18:11:55
R
UTF-8
C++
false
false
586
cpp
stack.cpp
// Calculate score function to obtain updated mu (Rcpp) #include <Rcpp.h> RcppExport SEXP cpp_stack( SEXP S, SEXP E, SEXP minx, SEXP maxx ) { using namespace Rcpp; Rcpp::IntegerVector SVec(S), EVec(E); int minxValue = Rcpp::as<int>(minx); int maxxValue = Rcpp::as<int>(maxx); Rcpp::NumericVector yvar( (maxxValue - minxValue + 1) ); for (int i = 0; i < yvar.size(); i++ ) { yvar[i] = 0; } for (int i = 0; i < SVec.size(); i++ ) { for (int j = SVec[i]; j <= EVec[i]; j++ ) { yvar[j-minxValue] += 1; } } return yvar; }
5f0c7a1245eccbae31eee784a571b45b9166e6ec
24221ab2cbbc5605e7c2648633fb009d3901ccd1
/lib/lb_xplane_ui/widgets/spacer.h
e961f69b2323d5dd2c91d56ecd35ae0726187c41
[ "MIT" ]
permissive
leecbaker/datareftool
843565a18283bfefbb26954bd74fa7d62e2c818a
a2b238838a130b8d0df1908c72300b22fb837323
refs/heads/master
2022-11-15T20:00:30.812405
2022-10-24T05:24:57
2022-10-24T05:24:57
29,484,885
143
41
MIT
2022-09-18T20:25:35
2015-01-19T18:23:22
C
UTF-8
C++
false
false
274
h
spacer.h
#pragma once class Widget11Spacer : public Widget11 { Size min_size; public: Widget11Spacer(Size min_size = {0,0}) : min_size(min_size) { } virtual Size getWidgetMinimumSize() const override { return min_size; } virtual void draw(Rect) override {} };
9d34d5cbef7cfd849b8c6c3fd58ee40ec80f032b
f01194e047dd38a8568cddf9565e54411fd17596
/Practice Codes/toughest.cpp
4c45f3afc86b77baa4fb5837e6aefc0f3f4ad761
[]
no_license
2012ankitkmr/My-works
118df8cf651785d19b962ee9afc2278d12d5a69a
910e5425e2ded2fb59a3613d33d3468dc1be1158
refs/heads/master
2020-04-05T23:08:29.182573
2017-02-24T12:19:03
2017-02-24T12:19:03
52,659,326
1
0
null
null
null
null
UTF-8
C++
false
false
297
cpp
toughest.cpp
#include<iostream> #define d 1000000037 int main(){ short t,x; long unsigned int a,b,w,h,n,y,p,q,j; cin>>t; for(i=0;i<t;i++){ cin>>a>>b>>n; long unsigned int arr[a][b]; for(j=0;j<n;j++) p=0; q=0; while(){ if(arr[p][q]==) } cout<<endl; } return 0; }
9e0bd37b68fe6a2d8c168cbb082ebd8830ca6047
761e340eea8e982766afd850590d05c22f357cda
/tmp_/code/src/query_parser/QueryEncoder.h
9a871a91dd6690eda5648c4ef361d82208572134
[]
no_license
fjamour/MAGiQ
70d421121f1d7f880077d7e13def42c4a0c85e2a
92886e2b7b215799082b399712d0222bbf8557cb
refs/heads/master
2023-03-09T09:40:24.211580
2023-02-28T05:19:38
2023-02-28T05:19:38
166,398,618
3
2
null
null
null
null
UTF-8
C++
false
false
5,250
h
QueryEncoder.h
/* * File: QueryEncoder.h * Author: abdelai * * Created on November 13, 2017, 3:10 PM */ #ifndef QUERYENCODER_H #define QUERYENCODER_H #include <cstdlib> #include "utils.h" #include <iostream> #include <dirent.h> #include <errno.h> #include "SPARQLLexer.hpp" #include "SPARQLParser.hpp" #include "utils.h" using namespace std; int encoded_queries = 0; void encode_query(SPARQLParser & parser, ofstream &stream, boost::unordered_map<string, long long>& predicate_map, boost::unordered_map<string, long long>& subj_map, long long max_predicate, long long max_verts) { boost::unordered_map<string, long long>::iterator it; stream<<"SELECT "; for(unsigned i = 0 ; i < parser.projection.size() ;i++){ stream<<"?"<<parser.getVariableName(parser.projection[i])<<" "; } stream<<"WHERE {"<<endl; for(unsigned i= 0; i < parser.patterns.patterns.size(); i++){ if(parser.patterns.patterns[i].subject.type == SPARQLParser::Element::Variable){ stream<<"\t?"<<parser.getVariableName(parser.patterns.patterns[i].subject.id)<<" "; } else if(parser.patterns.patterns[i].subject.type == SPARQLParser::Element::IRI){ it = subj_map.find(parser.patterns.patterns[i].subject.value); if (it == subj_map.end()) { stream<<"\t<"<<max_verts<<"> "; } else stream<<"\t<"<<it->second<<"> "; } else{ it = subj_map.find(parser.patterns.patterns[i].subject.value); if (it == subj_map.end()) { stream<<"\t\""<<max_verts<<"\" "; } else stream<<"\t\""<<it->second<<"\" "; } it = predicate_map.find(parser.patterns.patterns[i].predicate.value); if (it == predicate_map.end()) { stream<<"<"<<max_predicate<<"> "; } else stream<<"<"<<it->second<<"> "; if(parser.patterns.patterns[i].object.type == SPARQLParser::Element::Variable){ stream<<"?"<<parser.getVariableName(parser.patterns.patterns[i].object.id)<<" ."<<endl; } else if(parser.patterns.patterns[i].object.type == SPARQLParser::Element::IRI){ it = subj_map.find(parser.patterns.patterns[i].object.value); if (it == subj_map.end()) { stream<<"<"<<max_verts<<"> ."<<endl; } else stream<<"<"<<it->second<<"> ."<<endl; } else{ it = subj_map.find(parser.patterns.patterns[i].object.value); if (it == subj_map.end()) { stream<<"\""<<max_verts<<"\" ."<<endl; } else stream<<"\""<<it->second<<"\" ."<<endl; } } stream<<"}\n#EOQ#"<<endl; } void load_encode_queries(string queryFile, boost::unordered_map<string, long long>& predicate_map, boost::unordered_map<string, long long>& subj_map, long long max_predicate, long long max_verts) { ifstream queryIn(queryFile.c_str()); string outputFileName = queryFile+"_encoded"; ofstream queryOut(outputFileName.c_str()); string querystring, str; if (!queryIn) { throwException("Query file '" + queryFile + "' was not found. Please try again!\n"); } // read the query string querystring = ""; int counter = 0; while (true) { getline(queryIn,str); if(str!=query_delim){ querystring+=str; if (!queryIn.good()) break; querystring+='\n'; } else if ((str == query_delim || queryIn.eof()) && !querystring.empty()) { /*if(counter>2802102*/ cout<<"query#"<<counter<<"\n"<<querystring<<endl; counter++; SPARQLLexer lexer(querystring); SPARQLParser parser(lexer); try { parser.parse(); } catch (const SPARQLParser::ParserException& e) { cerr << "parse error: " << e.message << endl; return; } if(parser.variableCount != 0){ if(parser.patterns.patterns.size() > 0){ encode_query(parser, queryOut, predicate_map, subj_map, max_predicate, max_verts); encoded_queries++; } } querystring = ""; } } queryIn.close(); queryOut.close(); } int main_q_encoder(int argc, const char** argv) { if (argc < 4) { throwException("Usage: QueryLoadEncoder <predicate_map_file> <subj_map_file> <query_files_directory>"); } string line, directory = string(argv[3]); vector<string> files = vector<string>(); boost::unordered_map<string, long long> verts_map, preds_map; long long id, max_predicate = numeric_limits<long long>::min(), max_verts = numeric_limits<long long>::min(); char value[1000000]; FILE * pFile; getdir(directory,files); cout<<"Will encode "<<(files.size())<<" query files."<<endl; //Reading predicates dictionary pFile = fopen(argv[1], "r"); while(fscanf(pFile, "%lld %[^\r\n] ", &id, value)==2){ if(id>max_predicate) max_predicate = id+1; preds_map[value] = id; } fclose(pFile); id = -1; value[0] = '\0'; //Reading vertices dictionary pFile = fopen (argv[2],"r"); while(fscanf(pFile, "%lld %[^\r\n] ", &id, value)==2){ if(id>max_verts){ max_verts = id+1; } verts_map[value] = id; } fclose(pFile); cout<<"Number of vertices: "<<max_verts<<", Number of Predicates: "<<max_predicate<<endl; for(unsigned q = 0 ; q < files.size(); q++){ cout << "reading parsing and encoding queries from file: " << files[q] << endl; load_encode_queries(directory+files[q], preds_map, verts_map, max_predicate, max_verts); cout << "done" << endl; cout.flush(); } return 0; } #endif /* QUERYENCODER_H */
e07e83dc3ca7b400b46ac348b2392b6996b33745
ad73f24307fa65781818fba6819c60e6fcfc3523
/Examples_3/Unit_Tests/src/09_LightShadowPlayground/SDFVolumeData.cpp
23dd542d88c0c45fba765a4bffcdfa7f282def84
[ "Apache-2.0" ]
permissive
ValtoLibraries/The-Forge
786d0960f9a721bd944fc5e69acf7c3496f57522
56edfc8828bdb31da60e3386478334d8f95c2b8e
refs/heads/master
2020-03-28T09:59:58.183716
2019-08-11T00:41:57
2019-08-11T00:41:57
148,074,785
0
0
Apache-2.0
2019-08-11T00:41:58
2018-09-09T23:34:40
C++
UTF-8
C++
false
false
14,368
cpp
SDFVolumeData.cpp
#include "SDFVolumeData.h" #include "Intersection.h" #include "Ray.h" #include "Geometry.h" #include "BVHTree.h" #include "../../../../Common_3/OS/Interfaces/IThread.h" #include "../../../../Common_3/OS/Core/ThreadSystem.h" #include "../../../../Common_3/OS/Interfaces/IFileSystem.h" #include <sys/stat.h> #ifdef _WIN32 #include <io.h> #define access _access_s #else #include <unistd.h> #endif SDFVolumeTextureNode::SDFVolumeTextureNode(SDFVolumeData* sdfVolumeData, SDFMesh* mainMesh, SDFMeshInstance* meshInstance) :mSDFVolumeData(sdfVolumeData), mAtlasAllocationCoord(-1, -1, -1), mMainMesh(mainMesh), mMeshInstance(meshInstance), mHasBeenAdded(false) { } SDFVolumeData::SDFVolumeData(SDFMesh* mainMesh, SDFMeshInstance* meshInstance) :mSDFVolumeSize(0), mLocalBoundingBox(), mDistMinMax(FLT_MAX, FLT_MIN), mIsTwoSided(false), mSDFVolumeTextureNode(this, mainMesh, meshInstance), mTwoSidedWorldSpaceBias(0.f), mSubMeshName("") { } SDFVolumeData::SDFVolumeData() :mSDFVolumeSize(0), mLocalBoundingBox(), mDistMinMax(FLT_MAX, FLT_MIN), mIsTwoSided(false), mSDFVolumeTextureNode(this, NULL, NULL), mTwoSidedWorldSpaceBias(0.f), mSubMeshName("") { } SDFVolumeData::~SDFVolumeData() { } void GenerateSampleDirections(int32_t thetaSteps, int32_t phiSteps, SDFVolumeData::SampleDirectionsList& outDirectionsList, int32_t finalThetaModifier = 1) { for (int32_t theta = 0; theta < thetaSteps; ++theta) { for (int32_t phi = 0; phi < phiSteps; ++phi) { float random1 = Helper::GenerateRandomFloat(); float random2 = Helper::GenerateRandomFloat(); float thetaFrac = (theta + random1) / (float)thetaSteps; float phiFrac = (phi + random2) / (float)phiSteps; float rVal = sqrt(1.0f - thetaFrac * thetaFrac); const float finalPhi = 2.0f * (float)PI * phiFrac; outDirectionsList.push_back(vec3(cos(finalPhi) * rVal, sin(finalPhi) * rVal, thetaFrac * finalThetaModifier)); } } } struct CalculateMeshSDFTask { const SDFVolumeData::SampleDirectionsList* mDirectionsList; const SDFVolumeData::TriangeList* mMeshTrianglesList; const AABBox* mSDFVolumeBounds; const ivec3* mSDFVolumeDimension; int32_t mZIndex; float mSDFVolumeMaxDist; BVHTree* mBVHTree; SDFVolumeData::SDFVolumeList* mSDFVolumeList; bool mIsTwoSided; }; void DoCalculateMeshSDFTask(void* dataPtr, uintptr_t index) { CalculateMeshSDFTask* task = (CalculateMeshSDFTask*)(dataPtr); const AABBox& sdfVolumeBounds = *task->mSDFVolumeBounds; const ivec3& sdfVolumeDimension = *task->mSDFVolumeDimension; int32_t zIndex = task->mZIndex; float sdfVolumeMaxDist = task->mSDFVolumeMaxDist; const SDFVolumeData::SampleDirectionsList& directionsList = *task->mDirectionsList; //const SDFVolumeData::TriangeList& meshTrianglesList = *task->mMeshTrianglesList; SDFVolumeData::SDFVolumeList& sdfVolumeList = *task->mSDFVolumeList; BVHTree* bvhTree = task->mBVHTree; vec3 sdfVoxelSize ( Helper::Piecewise_Division ( sdfVolumeBounds.GetSize(), vec3((float)sdfVolumeDimension.getX(), (float)sdfVolumeDimension.getY(), (float)sdfVolumeDimension.getZ()) ) ); float voxelDiameterSquared = dot(sdfVoxelSize, sdfVoxelSize); for (int32_t yIndex = 0; yIndex < sdfVolumeDimension.getY(); ++yIndex) { for (int32_t xIndex = 0; xIndex < sdfVolumeDimension.getX(); ++xIndex) { vec3 voxelPos = Helper::Piecewise_Prod ( vec3((float)(xIndex)+0.5f, float(yIndex) + 0.5f, float(zIndex) + 0.5f) , sdfVoxelSize ) + sdfVolumeBounds.m_min; int32 outIndex = (zIndex * sdfVolumeDimension.getY() * sdfVolumeDimension.getX() + yIndex * sdfVolumeDimension.getX() + xIndex); float minDistance = sdfVolumeMaxDist; int32 hit = 0; int32 hitBack = 0; for (int32_t sampleIndex = 0; sampleIndex < directionsList.size(); ++sampleIndex) { vec3 rayDir = directionsList[sampleIndex]; vec3 endPos = voxelPos + rayDir * sdfVolumeMaxDist; Ray newRay(voxelPos, rayDir); Intersection intersectData; sdfVolumeBounds.Intersect(newRay, intersectData); //if we pass the cheap bbox testing if (intersectData.mIsIntersected) { Intersection meshTriangleIntersect; //optimized version bvhTree->IntersectRay(newRay, meshTriangleIntersect); if (meshTriangleIntersect.mIsIntersected) { ++hit; const vec3& hitNormal = meshTriangleIntersect.mHittedNormal; if (dot(rayDir, hitNormal) > 0 && !task->mIsTwoSided) { ++hitBack; } const vec3 finalEndPos = newRay.Eval( meshTriangleIntersect.mIntersection_TVal); float newDist = length(newRay.mStartPos - finalEndPos); if (newDist < minDistance) { minDistance = newDist; } } } } // float unsignedDist = minDistance; //if 50% hit backface, we consider the voxel sdf value to be inside the mesh minDistance *= (hit == 0 || hitBack < (directionsList.size() * 0.5f)) ? 1 : -1; //if we are very close to the surface and 95% of our rays hit backfaces, the sdf value //is inside the mesh if ((unsignedDist * unsignedDist) < voxelDiameterSquared && hitBack > 0.95f * hit) { minDistance = -unsignedDist; } minDistance = fmin(minDistance, sdfVolumeMaxDist); float volumeSpaceDist = minDistance / Helper::GetMaxElem(sdfVolumeBounds.GetExtent()); sdfVolumeList[outIndex] = volumeSpaceDist; } } } bool doesFileExist(const eastl::string& name) { struct stat buffer; return (stat(name.c_str(), &buffer) == 0); } bool FileExists(const eastl::string &Filename) { return access(Filename.c_str(), 0) == 0; } eastl::string SDFVolumeData::GetFullDirBakedFileName(const eastl::string& fileName) { return gGeneratedSDFBinaryDir + GetBakedFileName(fileName); } eastl::string SDFVolumeData::GetBakedFileName(const eastl::string& fileName) { eastl::string newCompleteCacheFileName = "Baked_" + fileName + ".bin"; return newCompleteCacheFileName; } bool SDFVolumeData::GenerateVolumeData(SDFVolumeData** outVolumeDataPP, const eastl::string& toCheckFullFileName, const eastl::string& fileName, float twoSidedWorldSpaceBias) { if (!FileExists(toCheckFullFileName)) { return false; } *outVolumeDataPP = conf_new(SDFVolumeData); SDFVolumeData& outVolumeData = **outVolumeDataPP; File newBakedFile; newBakedFile.Open(fileName, FM_ReadBinary, FSR_OtherFiles); outVolumeData.mSDFVolumeSize.setX(newBakedFile.ReadInt()); outVolumeData.mSDFVolumeSize.setY(newBakedFile.ReadInt()); outVolumeData.mSDFVolumeSize.setZ(newBakedFile.ReadInt()); uint32_t finalSDFVolumeDataCount = outVolumeData.mSDFVolumeSize.getX() * outVolumeData.mSDFVolumeSize.getY() * outVolumeData.mSDFVolumeSize.getZ(); outVolumeData.mSDFVolumeList.resize (finalSDFVolumeDataCount); newBakedFile.Read(&outVolumeData.mSDFVolumeList[0], (unsigned int)(finalSDFVolumeDataCount * sizeof(float))); outVolumeData.mLocalBoundingBox.m_min = f3Tov3(newBakedFile.ReadVector3()); outVolumeData.mLocalBoundingBox.m_max = f3Tov3(newBakedFile.ReadVector3()); outVolumeData.mIsTwoSided = newBakedFile.ReadBool(); //outVolumeData.mTwoSidedWorldSpaceBias = newBakedFile.ReadFloat(); outVolumeData.mTwoSidedWorldSpaceBias = twoSidedWorldSpaceBias; /* only uses the minimum & maximum of SDF if we ever want to quantized the SDF data for (int32 index = 0; index < outVolumeData.mSDFVolumeList.size(); ++index) { const float volumeSpaceDist = outVolumeData.mSDFVolumeList[index]; outVolumeData.mDistMinMax.setX(fmin(volumeSpaceDist, outVolumeData.mDistMinMax.getX())); outVolumeData.mDistMinMax.setY(fmax(volumeSpaceDist, outVolumeData.mDistMinMax.getY())); }*/ newBakedFile.Close(); LOGF(LogLevel::eINFO, "SDF binary data for %s found & parsed", toCheckFullFileName.c_str()); return true; } void SDFVolumeData::GenerateVolumeData(ThreadSystem* threadSystem, SDFMesh* mainMesh, SDFMeshInstance* subMesh, float sdfResolutionScale, bool generateAsIfTwoSided, SDFVolumeData** outVolumeDataPP, const eastl::string& cacheFileNameToCheck, float twoSidedWorldSpaceBias, const ivec3& specialMaxVoxelValue) { eastl::string newCompleteCacheFileName = SDFVolumeData::GetBakedFileName(cacheFileNameToCheck); eastl::string toCheckCacheFileName = SDFVolumeData::GetFullDirBakedFileName(cacheFileNameToCheck); if (GenerateVolumeData(outVolumeDataPP, toCheckCacheFileName, newCompleteCacheFileName, twoSidedWorldSpaceBias)) { return; } LOGF(LogLevel::eINFO, "Generating SDF binary data for %s", cacheFileNameToCheck.c_str()); *outVolumeDataPP = conf_new(SDFVolumeData, mainMesh, subMesh); SDFVolumeData& outVolumeData = **outVolumeDataPP; //for now assume all triangles are valid and useable ivec3 maxNumVoxelsOneDimension; ivec3 minNumVoxelsOneDimension; if (specialMaxVoxelValue.getX() == 0.f || specialMaxVoxelValue.getY() == 0.f || specialMaxVoxelValue.getZ() == 0.f) { maxNumVoxelsOneDimension = ivec3( SDF_MAX_VOXEL_ONE_DIMENSION_X, SDF_MAX_VOXEL_ONE_DIMENSION_Y, SDF_MAX_VOXEL_ONE_DIMENSION_Z); minNumVoxelsOneDimension = ivec3( SDF_MIN_VOXEL_ONE_DIMENSION_X, SDF_MIN_VOXEL_ONE_DIMENSION_Y, SDF_MIN_VOXEL_ONE_DIMENSION_Z); } else { maxNumVoxelsOneDimension = specialMaxVoxelValue; minNumVoxelsOneDimension = specialMaxVoxelValue; } const float voxelDensity = 1.0f; const float numVoxelPerLocalSpaceUnit = voxelDensity * sdfResolutionScale; AABBox subMeshBBox; subMeshBBox = subMesh->mLocalBoundingBox; float maxExtentSize = Helper::GetMaxElem(subMeshBBox.GetExtent()); vec3 minNewExtent(0.2f* maxExtentSize); vec3 dynamicNewExtent(Helper::Piecewise_Division(4.f * subMeshBBox.GetExtent(), Helper::ivec3ToVec3f(minNumVoxelsOneDimension))); vec3 finalNewExtent = subMeshBBox.GetExtent() + Helper::Max_Vec3(minNewExtent, dynamicNewExtent); AABBox newSDFVolumeBound(subMeshBBox.GetCenter() - finalNewExtent, subMeshBBox.GetCenter() + finalNewExtent); float newSDFVolumeMaxDistance = length(newSDFVolumeBound.GetExtent()); vec3 dynamicDimension = Helper::Piecewise_Prod( newSDFVolumeBound.GetSize(), vec3(numVoxelPerLocalSpaceUnit)); ivec3 finalSDFVolumeDimension ( clamp((int32_t)(dynamicDimension.getX()), minNumVoxelsOneDimension.getX(), maxNumVoxelsOneDimension.getX()), clamp((int32_t)(dynamicDimension.getY()), minNumVoxelsOneDimension.getY(), maxNumVoxelsOneDimension.getY()), clamp((int32_t)(dynamicDimension.getZ()), minNumVoxelsOneDimension.getZ(), maxNumVoxelsOneDimension.getZ()) ); unsigned int finalSDFVolumeDataCount = finalSDFVolumeDimension.getX() * finalSDFVolumeDimension.getY() * finalSDFVolumeDimension.getZ(); outVolumeData.mSDFVolumeList.resize ( finalSDFVolumeDimension.getX() * finalSDFVolumeDimension.getY() * finalSDFVolumeDimension.getZ() ); BVHTree bvhTree; bvhTree.AddMeshInstanceToBBOX(mat4::identity(), mainMesh, subMesh); bvhTree.mRootNode = bvhTree.CreateBVHNodeSHA(0, (int32_t)bvhTree.mBBOXDataList.size() - 1, FLT_MAX); // here we begin our stratified sampling calculation const uint32_t numVoxelDistanceSample = SDF_STRATIFIED_DIRECTIONS_NUM; SDFVolumeData::SampleDirectionsList sampleDirectionsList; int32_t thetaStep = (int32_t)floor((sqrt((float)numVoxelDistanceSample / (PI * 2.f)))); int32 phiStep = (int32_t)floor((float)thetaStep * PI); sampleDirectionsList.reserve(thetaStep * phiStep * 2); GenerateSampleDirections(thetaStep, phiStep, sampleDirectionsList); SDFVolumeData::SampleDirectionsList otherHemisphereSampleDirectionList; GenerateSampleDirections(thetaStep, phiStep, sampleDirectionsList, -1); CalculateMeshSDFTask calculateMeshSDFTask = {}; calculateMeshSDFTask.mDirectionsList = &sampleDirectionsList; // calculateMeshSDFTask.mMeshTrianglesList = &triangleList; calculateMeshSDFTask.mSDFVolumeBounds = &newSDFVolumeBound; calculateMeshSDFTask.mSDFVolumeDimension = &finalSDFVolumeDimension; calculateMeshSDFTask.mSDFVolumeMaxDist = newSDFVolumeMaxDistance; calculateMeshSDFTask.mSDFVolumeList = &outVolumeData.mSDFVolumeList; calculateMeshSDFTask.mBVHTree = &bvhTree; calculateMeshSDFTask.mIsTwoSided = generateAsIfTwoSided; eastl::vector<CalculateMeshSDFTask*> taskList; taskList.reserve(finalSDFVolumeDimension.getZ()); for (int32_t zIndex = 0; zIndex < finalSDFVolumeDimension.getZ(); ++zIndex) { CalculateMeshSDFTask* individualTask = (CalculateMeshSDFTask*)conf_malloc(sizeof(CalculateMeshSDFTask)); *individualTask = calculateMeshSDFTask; individualTask->mZIndex = zIndex; taskList.push_back(individualTask); DoCalculateMeshSDFTask(individualTask, 0); //addThreadSystemTask(threadSystem, DoCalculateMeshSDFTask, individualTask, 0); } //waitThreadSystemIdle(threadSystem); for (uint32_t i = 0; i < taskList.size(); ++i) { conf_free(taskList[i]); } BVHTree::DeleteBVHTree(bvhTree.mRootNode); File portDataFile; portDataFile.Open(newCompleteCacheFileName, FM_WriteBinary, FSR_OtherFiles); portDataFile.WriteInt(finalSDFVolumeDimension.getX()); portDataFile.WriteInt(finalSDFVolumeDimension.getY()); portDataFile.WriteInt(finalSDFVolumeDimension.getZ()); portDataFile.Write(&outVolumeData.mSDFVolumeList[0], (unsigned int)(finalSDFVolumeDataCount * sizeof(float))); portDataFile.WriteVector3(v3ToF3(newSDFVolumeBound.m_min)); portDataFile.WriteVector3(v3ToF3(newSDFVolumeBound.m_max)); portDataFile.WriteBool(generateAsIfTwoSided); //portDataFile.WriteFloat(twoSidedWorldSpaceBias); portDataFile.Close(); float minVolumeDist = 1.0f; float maxVolumeDist = -1.0f; //we can probably move the calculation of the minimum & maximum distance of the SDF value //into the CalculateMeshSDFValue function for (int32 index = 0; index < outVolumeData.mSDFVolumeList.size(); ++index) { const float volumeSpaceDist = outVolumeData.mSDFVolumeList[index]; minVolumeDist = fmin(volumeSpaceDist, minVolumeDist); maxVolumeDist = fmax(volumeSpaceDist, maxVolumeDist); } //TODO, not every mesh is going to be closed //do the check sometime in the future outVolumeData.mIsTwoSided = generateAsIfTwoSided; outVolumeData.mSDFVolumeSize = finalSDFVolumeDimension; outVolumeData.mLocalBoundingBox = newSDFVolumeBound; outVolumeData.mDistMinMax = vec2(minVolumeDist, maxVolumeDist); outVolumeData.mTwoSidedWorldSpaceBias = twoSidedWorldSpaceBias; LOGF(LogLevel::eINFO, "Generated SDF binary data for %s successfully!", cacheFileNameToCheck.c_str()); }
772a1ca330672a510129db7ea94d9728771df9d6
d1cad1a0fc1cbd3ea75291e09de94d583cc7a30a
/display/font.cc
3294b162215e06578a9c4cfd5727389a15117a2d
[ "Artistic-1.0" ]
permissive
vladki77/simutrans-extended
c8e2157e2647ea5b7af815a103ee7ef64c447b17
7641da8ed5603fc9154e3009a556b2b23747f523
refs/heads/master
2022-12-31T17:39:37.578712
2020-10-25T15:13:31
2020-10-25T15:13:31
106,965,323
2
0
null
2019-04-10T19:14:22
2017-10-14T21:50:06
C++
UTF-8
C++
false
false
13,680
cc
font.cc
/* * This file is part of the Simutrans-Extended project under the Artistic License. * (see LICENSE.txt) */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "../simtypes.h" #include "../simmem.h" #include "../simdebug.h" #include "../macros.h" #include "font.h" #include "../utils/simstring.h" /* if defined, for the old .fnt files a .bdf core will be generated */ //#define DUMP_OLD_FONTS static int nibble(sint8 c) { return (c > '9') ? 10 + c - 'A' : c - '0'; } /** * Decodes a single line of a character */ static void dsp_decode_bdf_data_row(uint8 *target, int y, int xoff, int g_width, char *str) { uint16 data; char buf[3]; buf[0] = str[0]; buf[1] = str[1]; buf[2] = '\0'; data = (uint16)strtol(buf, NULL, 16)<<8; // read second byte but use only first nibble if (g_width > 8) { buf[0] = str[2]; buf[1] = str[3]; buf[2] = '\0'; data |= strtol(buf, NULL, 16); } data >>= xoff; // now store them, and the second nibble store interleaved target[y] = data>>8; if(g_width+xoff>8) { target[y+CHARACTER_HEIGHT] = data; } } /** * Reads a single character. * @returns index of character successfully read, or -1 on error */ static sint32 dsp_read_bdf_glyph(FILE *fin, uint8 *data, uint8 *screen_w, int char_limit, int f_height, int f_desc) { uint32 char_nr = 0; int g_width, h, g_desc; int d_width = -1; int xoff = 0; while (!feof(fin)) { char str[256]; fgets(str, sizeof(str), fin); // encoding (sint8 number) in decimal if (strstart(str, "ENCODING")) { char_nr = atoi(str + 8); if (char_nr == 0 || (sint32)char_nr >= char_limit) { fprintf(stderr, "Unexpected character (%i) for %i character font!\n", char_nr, char_limit); char_nr = 0; } memset( data+CHARACTER_LEN*char_nr, 0, CHARACTER_LEN ); continue; } // information over size and coding if (strstart(str, "BBX")) { sscanf(str + 3, "%d %d %d %d", &g_width, &h, &xoff, &g_desc); continue; } // information over size and coding if (strstart(str, "DWIDTH")) { d_width = atoi(str + 6); continue; } // start if bitmap data if (strstart(str, "BITMAP")) { const int top = f_height + f_desc - h - g_desc; int y; // maximum size CHARACTER_HEIGHT pixels h += top; if (h > CHARACTER_HEIGHT) { h = CHARACTER_HEIGHT; } // read for height times for (y = top; y < h; y++) { fgets(str, sizeof(str), fin); if( y>=0 ) { dsp_decode_bdf_data_row(data + char_nr*CHARACTER_LEN, y, xoff, g_width, str); } } continue; } // finally add width information (width = 0: not there!) if (strstart(str, "ENDCHAR")) { uint8 start_h=0, i; // find the start offset for( i=0; i<23; i++ ) { if(data[CHARACTER_LEN*char_nr + i]==0 && data[CHARACTER_LEN*char_nr+CHARACTER_HEIGHT+i]==0) { start_h++; } else { break; } } if(start_h==CHARACTER_HEIGHT) { g_width = 0; } data[CHARACTER_LEN*char_nr + CHARACTER_LEN-2] = start_h; data[CHARACTER_LEN*char_nr + CHARACTER_LEN-1] = g_width; if (d_width == -1) { #ifdef MSG_LEVEL // no screen width: should not happen, but we can recover fprintf(stderr, "BDF warning: %i has no screen width assigned!\n", char_nr); #endif d_width = g_width + 1; } screen_w[char_nr] = d_width; // finished return char_nr; } } return -1; } /** * Reads a bdf font character */ static bool dsp_read_bdf_font(FILE* fin, font_type* font) { uint8* screen_widths = NULL; uint8* data = NULL; int f_height; int f_desc; int f_chars = 0; sint32 max_glyph = 0; while (!feof(fin)) { char str[256]; fgets(str, sizeof(str), fin); if (strstart(str, "FONTBOUNDINGBOX")) { sscanf(str + 15, "%*d %d %*d %d", &f_height, &f_desc); continue; } if (strstart(str, "CHARS") && str[5] <= ' ') { // the characters 0xFFFF and 0xFFFE are guaranteed to be non-unicode characters f_chars = atoi(str + 5) <= 256 ? 256 : 65534; data = (uint8*)calloc(f_chars, CHARACTER_LEN); if (data == NULL) { fprintf(stderr, "No enough memory for font allocation!\n"); return false; } screen_widths = (uint8*)malloc(f_chars); memset( screen_widths, 0xFF, f_chars ); if (screen_widths == NULL) { free(data); fprintf(stderr, "No enough memory for font allocation!\n"); return false; } data[32 * CHARACTER_LEN] = 0; // screen width of space screen_widths[32] = clamp(f_height / 2, 3, 23); continue; } if (strstart(str, "STARTCHAR") && f_chars > 0) { sint32 chr = dsp_read_bdf_glyph(fin, data, screen_widths, f_chars, f_height, f_desc); if( chr > max_glyph ) { max_glyph = chr; } continue; } } // ok, was successful? if (f_chars > 0) { int h; // init default char for missing characters (just a box) screen_widths[0] = 8; data[0] = 0; data[1] = 0x7E; const int real_font_height = ( f_height>CHARACTER_HEIGHT ? CHARACTER_HEIGHT : f_height ); for(h = 2; h < real_font_height - 2; h++) { data[h] = 0x42; } data[h++] = 0x7E; for (; h < CHARACTER_LEN-2; h++) { data[h] = 0; } data[CHARACTER_LEN-2] = 1; // y-offset data[CHARACTER_LEN-1] = 7; // real width font->screen_width = screen_widths; font->char_data = data; font->height = f_height; font->descent = f_desc; font->num_chars = max_glyph+1; // Use only needed amount font->char_data = (uint8 *)realloc( font->char_data, font->num_chars*CHARACTER_LEN ); return true; } return false; } #ifdef USE_FREETYPE #include "../gui/gui_theme.h" #include "../sys/simsys.h" #include <ft2build.h> #include FT_FREETYPE_H #include FT_GLYPH_H #include FT_TRUETYPE_TABLES_H FT_Library ft_library = NULL; bool load_FT_font( font_type* fnt, const char* short_name, int pixel_height ) { int error; if( !ft_library && FT_Init_FreeType(&ft_library) != FT_Err_Ok ) { ft_library = NULL; return false; } // for now we assume we know the filename, this is system dependent const char *fname = dr_query_fontpath( short_name ); // Ok, we guessed something abou the finename, now actually load it FT_Face face; error = FT_New_Face( ft_library, fname, 0, &face );/* create face object */ if( error ) { dbg->error( "load_FT_font", "Cannot load %s", fname ); FT_Done_FreeType( ft_library ); ft_library = NULL; return false; } FT_Set_Pixel_Sizes( face, 0, pixel_height ); fnt->char_data = (uint8 *)calloc( 65536, CHARACTER_LEN ); fnt->screen_width = (uint8 *)malloc( 65536 ); sint16 ascent = face->size->metrics.ascender/64; fnt->height = min( face->size->metrics.height/64, 23 ); fnt->descent = face->size->metrics.descender/64; fnt->num_chars = 0; tstrncpy( fnt->fname, short_name, lengthof(fnt->fname) ); for( uint32 char_nr=0; char_nr<65535; char_nr++ ) { if( char_nr!=0 && !FT_Get_Char_Index( face, char_nr ) ) { // character not there ... fnt->screen_width[char_nr] = 255; continue; } /* load glyph image into the slot (erase previous one) */ error = FT_Load_Char( face, char_nr, FT_LOAD_RENDER | FT_LOAD_MONOCHROME ); if( error ) { // character not there ... fnt->screen_width[char_nr] = 255; continue; } error = FT_Render_Glyph( face->glyph, FT_RENDER_MODE_MONO ); if( error || face->glyph->bitmap.pitch == 0 ) { // character not there ... fnt->screen_width[char_nr] = 255; continue; } // use only needed amount fnt->num_chars = char_nr+1; /* now render into cache * the bitmap is at slot->bitmap * the character base is at slot->bitmap_left, CELL_HEIGHT - slot->bitmap_top */ // if the character is too high int y_off = ascent - face->glyph->bitmap_top; int by_off = 0; if( y_off < 0 ) { by_off -= y_off; y_off = 0; } // asked for monocrome so slot->pixel_mode == FT_PIXEL_MODE_MONO for( int y = y_off, by = by_off; y < CHARACTER_HEIGHT && by < face->glyph->bitmap.rows; y++, by++ ) { fnt->char_data[(char_nr*CHARACTER_LEN)+y] = face->glyph->bitmap.buffer[by * face->glyph->bitmap.pitch]; } if( face->glyph->bitmap.width > 8 ) { // render second row for( int y = y_off, by = by_off; y < CHARACTER_HEIGHT && by < face->glyph->bitmap.rows; y++, by++ ) { fnt->char_data[(char_nr*CHARACTER_LEN)+CHARACTER_HEIGHT+y] = face->glyph->bitmap.buffer[by * face->glyph->bitmap.pitch+1]; } } fnt->screen_width[char_nr] = face->glyph->bitmap.width+1; fnt->char_data[CHARACTER_LEN * char_nr + CHARACTER_LEN-2] = y_off; // h_offset fnt->char_data[CHARACTER_LEN * char_nr + CHARACTER_LEN-1] = max(16,face->glyph->bitmap.width); } // Use only needed amount fnt->char_data = (uint8 *)realloc( fnt->char_data, fnt->num_chars*CHARACTER_LEN ); fnt->screen_width[' '] = fnt->screen_width['n']; FT_Done_Face( face ); FT_Done_FreeType( ft_library ); ft_library = NULL; return true; } #endif void debug_font( font_type* fnt) { dbg->debug("debug_font", "Loaded font %s with %i characters\n", fnt->fname, fnt->num_chars); dbg->debug("debug_font", "height: %i, descent: %i", fnt->height, fnt->descent ); for( int char_nr = 32; char_nr<128; char_nr ++ ) { char msg[1024], *c; c = msg + sprintf( msg,"char %c: width %i, top %i\n", char_nr, fnt->char_data[(char_nr*CHARACTER_LEN)+CHARACTER_LEN-1], fnt->char_data[(char_nr*CHARACTER_LEN)+CHARACTER_LEN-2] ); for( int y = 0; y < CHARACTER_HEIGHT; y++ ) { for( int x = 0; x < 8 && x < fnt->char_data[(char_nr*CHARACTER_LEN)+CHARACTER_LEN-1]; x++ ) { *c++ = (fnt->char_data[(char_nr*CHARACTER_LEN)+y] >> (7-x)) & 1 ? '*' : ' '; } *c++ = '\n'; } *c++ = 0; dbg->debug("character data", msg ); } } bool load_font(font_type* fnt, const char* fname) { FILE* f = fopen(fname, "rb"); int c; #ifdef USE_FREETYPE if( load_FT_font( fnt, fname, gui_theme_t::request_linespace ) ) { debug_font( fnt ); return true; } #endif if (f == NULL) { fprintf(stderr, "Error: Cannot open '%s'\n", fname); return false; } c = getc(f); if(c<0) { fprintf(stderr, "Error: Cannot parse font '%s'\n", fname); fclose(f); return false; } // binary => the assume dumpe prop file if (c < 32) { // read classical prop font uint8 npr_fonttab[3072]; int i; rewind(f); fprintf(stdout, "Loading font '%s'\n", fname); if (fread(npr_fonttab, sizeof(npr_fonttab), 1, f) != 1) { fprintf(stderr, "Error: %s wrong size for old format prop font!\n", fname); fclose(f); return false; } fclose(f); #ifdef DUMP_OLD_FONTS f = fopen("C:\\prop.bdf","w"); #endif // convert to new standard font fnt->screen_width = MALLOCN(uint8, 256); fnt->char_data = MALLOCN(uint8, CHARACTER_LEN * 256); fnt->num_chars = 256; fnt->height = 11; fnt->descent = -2; for (i = 0; i < 256; i++) { int j; uint8 start_h; fnt->screen_width[i] = npr_fonttab[256 + i]; if( fnt->screen_width[i] == 0 ) { // undefined char fnt->screen_width[i] = -1; } for (j = 0; j < 10; j++) { fnt->char_data[i * CHARACTER_LEN + j] = npr_fonttab[512 + i * 10 + j]; } for (; j < CHARACTER_LEN-2; j++) { fnt->char_data[i * CHARACTER_LEN + j] = 0; } // find the start offset for( start_h=0; fnt->char_data[CHARACTER_LEN*i + start_h]==0 && start_h<10; start_h++ ) ; fnt->char_data[CHARACTER_LEN * i + CHARACTER_LEN-2] = start_h; fnt->char_data[CHARACTER_LEN * i + CHARACTER_LEN-1] = npr_fonttab[i]; #ifdef DUMP_OLD_FONTS //try to make bdf if(start_h<10) { // find bounding box int h=10; while(h>start_h && fnt->char_data[CHARACTER_LEN*i + h-1]==0) { h--; } // emulate character fprintf( f, "STARTCHAR char%0i\n", i ); fprintf( f, "ENCODING %i\n", i ); fprintf( f, "SWIDTH %i 0\n", (int)(0.5+77.875*(double)fnt->screen_width[i]) ); fprintf( f, "DWIDTH %i\n", fnt->screen_width[i] ); fprintf( f, "BBX %i %i %i %i\n", fnt->screen_width[i], h-start_h, 0, 8-h ); fprintf( f, "BITMAP\n" ); for( j=start_h; j<h; j++ ) { fprintf( f, "%02x\n", fnt->char_data[CHARACTER_LEN*i + j] ); } fprintf( f, "ENDCHAR\n" ); } #endif } #ifdef DUMP_OLD_FONTS fclose(f); #endif fnt->screen_width[32] = 4; fnt->char_data[CHARACTER_LEN*32 + CHARACTER_LEN-1] = 0; // space width fprintf(stderr, "%s successfully loaded as old format prop font!\n", fname); return true; } // load old hex font format if (c == '0') { uint8 dr_4x7font[7 * 256]; char buf[80]; int i; fprintf(stderr, "Reading hex-font %s.\n", fname ); rewind(f); while (fgets(buf, sizeof(buf), f) != NULL) { const char* p; int line; int n; sscanf(buf, "%4x", &n); p = buf + 5; for (line = 0; line < 7; line++) { int val = nibble(p[0]) * 16 + nibble(p[1]); dr_4x7font[n * 7 + line] = val; p += 2; } } fclose(f); // convert to new standard font fnt->screen_width = MALLOCN(uint8, 256); fnt->char_data = MALLOCN(uint8, CHARACTER_LEN * 256); fnt->num_chars = 256; fnt->height = 7; fnt->descent = -1; for (i = 0; i < 256; i++) { int j; fnt->screen_width[i] = 4; for (j = 0; j < 7; j++) { fnt->char_data[i * CHARACTER_LEN + j] = dr_4x7font[i * 7 + j]; } for (; j < 15; j++) { fnt->char_data[i * CHARACTER_LEN + j] = 0; } fnt->char_data[i * CHARACTER_LEN + CHARACTER_LEN-2] = 0; fnt->char_data[i * CHARACTER_LEN + CHARACTER_LEN-1] = 3; } fprintf(stderr, "%s successfully loaded as old format hex font!\n", fname); return true; } fprintf(stderr, "Loading BDF font '%s'\n", fname); if (dsp_read_bdf_font(f, fnt)) { debug_font( fnt ); fclose(f); return true; } fclose(f); return false; }
38d0a01c66bb328c603f8a0866c817cdfe18dfe6
936bd76dd3cc6bd422b93388fede4469f87f1bab
/shiftregister/shiftregister.ino
c229834ac1aaf33e6d83ae5decb17d583f21a909
[]
no_license
procastino/shiftRegisterArduino
1e18302e62bbfa19e75bbbff1006446c5c96dc06
99c7aab30a72ed332e8bc6b96685b37cb92f926d
refs/heads/master
2021-03-12T22:49:44.058580
2013-06-17T10:15:35
2013-06-17T10:15:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,164
ino
shiftregister.ino
/* From Adafruit lesson, improved to patterned LED lights controlled by two pushbuttons */ //definimos botons e variables precisas int pinBotons[]={3,2}; int ultimoEstadoBoton[]={LOW,LOW}; int estadoBoton[]={LOW,LOW}; long ultimoDebounce=0; long retardoDebounce=20; //variables para as saídas do arduino para o 74HC595 int latchPin = 5; int clockPin = 6; int dataPin = 4; int programa=0; byte leds = 0; void setup() { for (int i=0;i<2;i++) { pinMode(pinBotons[i],INPUT); } pinMode(latchPin, OUTPUT); pinMode(dataPin, OUTPUT); pinMode(clockPin, OUTPUT); Serial.begin(9600); } //O loop consiste en facer a lectura dos botóns e chamar ao programa correspondente void loop() { lecturaBotons(); switch (programa) { case 0: apagados(); break; case 1: acesos(); break; case 2: encendidoProgresivo(); break; case 3: encendidoProgresivoInverso(); break; case 4: encendidoAlterno(); break; case 5: kitt(); break; case 6: alternativoTodos(); break; default: apagados(); break; } } //función de lectura dos botóns con Debounce void lecturaBotons() { for (int i=0;i<2;i++) { int lectura=digitalRead(pinBotons[i]); if (lectura!=ultimoEstadoBoton[i]) { ultimoDebounce=millis(); } if ((millis()-ultimoDebounce)>retardoDebounce) { if (lectura!=estadoBoton[i]) { estadoBoton[i]=lectura; if (estadoBoton[i]==HIGH) { if (i==0) { programa=programa+1; if (programa>6) { programa=0; } } if(i==1) { programa=programa-1; if (programa<0) { programa=6; } } Serial.println("programa"); Serial.println(programa); } } } ultimoEstadoBoton[i]=lectura; } } //función que manda os datos do byte leds ao shiftregister para que este defina o estado dos LED void updateShiftRegister() { digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, LSBFIRST, leds); digitalWrite(latchPin, HIGH); } // funcións para os patróns, explícanse por si mesmas co nome void apagados() { leds=0; updateShiftRegister(); } void acesos() { leds=255; updateShiftRegister(); } void encendidoProgresivo() { leds = 0; updateShiftRegister(); delay(100); for (int i = 0; i < 8; i++) { lecturaBotons(); bitSet(leds, i); updateShiftRegister(); delay(100); } } void encendidoProgresivoInverso() { leds = 0; updateShiftRegister(); delay(100); for (int i = 0; i < 8; i++) { lecturaBotons(); bitSet(leds, 7-i); updateShiftRegister(); delay(100); } } void encendidoAlterno() { leds = B10101010; updateShiftRegister(); delay(100); leds=B01010101; updateShiftRegister(); delay(100); } void kitt() { for (int i = 0; i < 8; i++) { lecturaBotons(); leds=0; bitSet(leds, i); updateShiftRegister(); delay(100); } for (int i = 1; i < 7; i++) { lecturaBotons(); leds=0; bitSet(leds, 7-i); updateShiftRegister(); delay(100); } } void alternativoTodos() { leds=B11111111; updateShiftRegister(); delay(100); leds=B00000000; updateShiftRegister(); delay(100); }
e49aadd7d0808b9b4b22a7f2a97a0fab200ef89a
f721566b16077f9445e1f6edd3b9f0c52e88478c
/plugins/PrimaryVertexSelector.cc
c65d2d8634f1b1c3df3857174370a99823edd1c2
[]
no_license
horace-cl/BParkCinves
147cdf6de55f2ed0c2bcd6734dce2c331107d8db
58c948202f1b7907ad1d8d8b4e8fe64a19d9a3c4
refs/heads/master
2023-02-26T07:59:39.077760
2020-09-16T02:00:12
2020-09-16T02:00:12
260,793,130
0
0
null
null
null
null
UTF-8
C++
false
false
4,206
cc
PrimaryVertexSelector.cc
#include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/Framework/interface/global/EDProducer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h" #include "FWCore/ParameterSet/interface/ParameterSetDescription.h" #include "FWCore/Utilities/interface/InputTag.h" #include "DataFormats/BeamSpot/interface/BeamSpot.h" #include "TrackingTools/TransientTrack/interface/TransientTrack.h" #include "CommonTools/CandUtils/interface/Booster.h" #include "Math/GenVector/Boost.h" #include "DataFormats/PatCandidates/interface/Muon.h" #include "DataFormats/NanoAOD/interface/FlatTable.h" #include <vector> #include <memory> #include <map> #include <string> #include "DataFormats/PatCandidates/interface/PackedCandidate.h" #include "CommonTools/Utils/interface/StringCutObjectSelector.h" #include "DataFormats/PatCandidates/interface/CompositeCandidate.h" #include "DataFormats/Math/interface/deltaR.h" #include "CommonTools/Statistics/interface/ChiSquaredProbability.h" #include "helper.h" #include <limits> #include <algorithm> #include "KinVtxFitter.h" #include <Math/VectorUtil.h> class PrimaryVertexSelector : public edm::global::EDProducer<> { public: explicit PrimaryVertexSelector(const edm::ParameterSet &cfg): bMesons_(consumes<pat::CompositeCandidateCollection>( cfg.getParameter<edm::InputTag>("bMesons") )), trgMuonToken_(consumes<pat::MuonCollection>(cfg.getParameter<edm::InputTag>("trgMuon"))), vertexSrc_( consumes<reco::VertexCollection> ( cfg.getParameter<edm::InputTag>( "vertexCollection" ) ) ), dzCut_(cfg.getParameter<double>("dzCut")){ produces<nanoaod::FlatTable>(); } ~PrimaryVertexSelector() override {} void produce(edm::StreamID, edm::Event&, const edm::EventSetup&) const override; //virtual void produce(edm::Event&, const edm::EventSetup&); static void fillDescriptions(edm::ConfigurationDescriptions &descriptions) {} private: const edm::EDGetTokenT<pat::CompositeCandidateCollection> bMesons_; const edm::EDGetTokenT<pat::MuonCollection> trgMuonToken_; const edm::EDGetTokenT<reco::VertexCollection> vertexSrc_; const double dzCut_; }; //void PrimaryVertexSelector::produce(edm::Event& evt, const edm::EventSetup& iSetup) { void PrimaryVertexSelector::produce(edm::StreamID, edm::Event &evt, edm::EventSetup const &) const { //input edm::Handle<pat::CompositeCandidateCollection> bMesons; evt.getByToken(bMesons_, bMesons); edm::Handle<reco::VertexCollection> vertexHandle; evt.getByToken(vertexSrc_, vertexHandle); edm::Handle<pat::MuonCollection> trgMuons; evt.getByToken(trgMuonToken_, trgMuons); std::vector<float> vx,vy,vz, dzTrgMu;// ,dlenSig,pAngle; dzTrgMu.push_back(fabs(vertexHandle->front().position().z()-trgMuons->front().vz())); vx.push_back(vertexHandle->front().position().x()); vy.push_back(vertexHandle->front().position().y()); vz.push_back(vertexHandle->front().position().z()); int nv = 0; for(size_t i=1;i < (*vertexHandle).size(); i++){ for (const pat::Muon & trgmu : *trgMuons){ if(nv==4) break; if(fabs((*vertexHandle)[i].position().z()-trgmu.vz())<dzCut_) { dzTrgMu.push_back(fabs((*vertexHandle)[i].position().z()-trgmu.vz())); vx.push_back((*vertexHandle)[i].position().x()); vy.push_back((*vertexHandle)[i].position().y()); vz.push_back((*vertexHandle)[i].position().z()); nv++; } } } // output auto pvTable = std::make_unique<nanoaod::FlatTable>(dzTrgMu.size(),"PV",false); pvTable->addColumn<float>("dzTrgMu",dzTrgMu,"abs(vz-trgMuon.vz)",nanoaod::FlatTable::FloatColumn,10); pvTable->addColumn<float>("vx",vx,"vx in cm",nanoaod::FlatTable::FloatColumn,10); pvTable->addColumn<float>("vy",vy,"vy in cm",nanoaod::FlatTable::FloatColumn,10); pvTable->addColumn<float>("vz",vz,"vz in cm",nanoaod::FlatTable::FloatColumn,10); // std::cout << "B Mesons: "<< bMesons->size() << "\n"; // std::cout << "Vertices: "<< vertexHandle->size() << "\n"; // std::cout << "Trg muons: "<< trgMuons->size() << "\n"; evt.put(std::move(pvTable)); } DEFINE_FWK_MODULE(PrimaryVertexSelector);
d626d5cf72a952cc4085322ecee6eb82243972be
f3a61097296d888e64067e837cb52641316a6487
/Unreal4XBook/Source/Unreal4XBook/Chapter06/Warrior_CH6.cpp
cc5636756de2dbda417d99419ecf5e9239b09f18
[]
no_license
klauth86/Scripting-with-UE4X
be3c66bc5de7fc5fa6c69cb95d2f3cf2981b26af
0bdfeed473932af27066c2722f5dd417a5b8e5a0
refs/heads/master
2020-09-13T08:42:24.061941
2019-12-07T14:24:44
2019-12-07T14:24:44
222,715,613
0
0
null
null
null
null
UTF-8
C++
false
false
2,754
cpp
Warrior_CH6.cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "Warrior_CH6.h" #include "Components/CapsuleComponent.h" // Sets default values AWarrior_CH6::AWarrior_CH6() { // Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; lastInput = FVector2D::ZeroVector; } // Called when the game starts or when spawned void AWarrior_CH6::BeginPlay() { Super::BeginPlay(); } // Called every frame void AWarrior_CH6::Tick(float DeltaTime) { Super::Tick(DeltaTime); float len = lastInput.Size(); // If the player's input is greater than 1, normalize it if (len > 1.f) { lastInput /= len; } AddMovementInput(GetActorForwardVector(), lastInput.Y); AddMovementInput(GetActorRightVector(), lastInput.X); // Zero off last input values lastInput = FVector2D::ZeroVector; } // Called to bind functionality to input void AWarrior_CH6::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); check(PlayerInputComponent); PlayerInputComponent->BindAxis("Forward", this, &AWarrior_CH6::Forward); PlayerInputComponent->BindAxis("Back", this, &AWarrior_CH6::Back); PlayerInputComponent->BindAxis("Right", this, &AWarrior_CH6::Right); PlayerInputComponent->BindAxis("Left", this, &AWarrior_CH6::Left); PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &AWarrior_CH6::Jump); // Calling function for HotKey PlayerInputComponent->BindAction("HotKey_UIButton_Spell", IE_Pressed, this, &AWarrior_CH6::ButtonClicked); } void AWarrior_CH6::Forward(float amount) { lastInput.Y += amount; } void AWarrior_CH6::Back(float amount) { lastInput.Y -= amount; } void AWarrior_CH6::Right(float amount) { lastInput.X += amount; } void AWarrior_CH6::Left(float amount) { lastInput.X -= amount; } void AWarrior_CH6::OnOverlapsBegin1_Implementation(UPrimitiveComponent* Comp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult&SweepResult) { UE_LOG(LogTemp, Warning, TEXT("Overlaps warrior began")); } void AWarrior_CH6::OnOverlapsEnd1_Implementation(UPrimitiveComponent* Comp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex) { UE_LOG(LogTemp, Warning, TEXT("Overlaps warrior ended")); } void AWarrior_CH6::PostInitializeComponents() { Super::PostInitializeComponents(); if (RootComponent) { // Attach contact function to all bounding components. GetCapsuleComponent()->OnComponentBeginOverlap.AddDynamic(this, &AWarrior_CH6::OnOverlapsBegin1); GetCapsuleComponent()->OnComponentEndOverlap.AddDynamic(this, &AWarrior_CH6::OnOverlapsEnd1); } }
bb10d141a9d74aab666d3814b801d07d96f28cec
4a51af77ee7bfd76d120d914599ff05d36d4e605
/engine/include/opengl/GLVertexArray.h
e3e6b35bb7ecd2d04c7fd73d6bf4e184ed37bdf5
[]
no_license
vic4key/flyEngine
6929a3b4d60a7cf4f32191af9b76c296bcb8bfaf
2ed68f8cd022849fbc7d93d1f42c12bfcd0de098
refs/heads/master
2020-03-13T20:45:12.909031
2018-04-26T12:40:21
2018-04-26T12:40:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
231
h
GLVertexArray.h
#ifndef GLVERTEXARRAY_H #define GLVERTEXARRAY_H #include <GL/glew.h> namespace fly { class GLVertexArray { public: GLVertexArray(); ~GLVertexArray(); void bind() const; private: GLuint _id; }; } #endif
a99442ee572c32dc88de9abe0f4e950dfddddaaf
d43b226bee2aae82b13171b6b912483c5197d341
/Problem Solving/UVa/272.cpp
e84f0cbf827df4d7ef4172a0f34d7c558ec4a227
[]
no_license
AshHasib/my-last-stand
2d6c4d220e41fe4aa651511c01d963ad34ec4fde
f618d959a08861f89424c789ffbf8bf4126d8dc3
refs/heads/master
2020-06-23T09:32:49.105969
2020-01-01T18:47:04
2020-01-01T18:47:04
198,585,504
0
0
null
null
null
null
UTF-8
C++
false
false
628
cpp
272.cpp
#include<bits/stdc++.h> using namespace std; int main() { //freopen("input.txt", "r", stdin); char S[100000]; while(gets(S)) { long sz= strlen(S); long p=0; //int c1=0,c2=0; for(long i=0;i<sz;i++) { if(S[i]=='"') { p++; if(p%2==1) { printf("``"); } else { printf("''"); } } else { printf("%c", S[i]); } } printf("\n"); } return 0; }
253812cf5837b8483906f0eb8e5d521d3e662bb0
11e62f23bd66c0455b6e7c0e96375ae5a9a33468
/src/Projection3D.h
b921d5d4dfd084c0a8dc3c086f08d56157fbed7e
[]
no_license
Tomas-Homola/PG_cv8
1d0b872e25d99d814c721b8be90ce6f3895ef539
d8237cad6bd4004a240b038fb9c3be4051b1d416
refs/heads/master
2023-04-30T15:59:37.160495
2021-05-21T17:37:41
2021-05-21T17:37:41
365,853,229
0
0
null
null
null
null
UTF-8
C++
false
false
2,178
h
Projection3D.h
#pragma once #include "qmath.h" #include "qcolor.h" #include "structs.h" #include "qvector3d.h" // napad pre tuto triedu mi poradil Alex Filip class Projection3D { private: int projectionType = 0; int shadingType = 0; double zenit = M_PI_2; double azimut = 0.0; double clipNearDistance = 0.0; double clipFarDistance = 220.0; double scaleValue = 100.0; double cameraDistance = 10.0; QVector3D n; QVector3D u; QVector3D v; void recalculateVector_n(); void recalculateVector_u(); void recalculateVector_v(); void recalculateVectors() { recalculateVector_n(); recalculateVector_u(); recalculateVector_v(); } public: Projection3D(); enum ProjectionType { ParallelProjection = 0, PerspectiveProjection = 1 }; enum Shading { ConstantShading = 0, GouraudShading = 1 }; // set functions void setProjectionType(int projectionType) { this->projectionType = projectionType; } void setShadingType(int shadingType) { this->shadingType = shadingType; } void setZenit(double zenit) { this->zenit = zenit; recalculateVectors(); } void setAzimut(double azimut) { this->azimut = azimut; recalculateVectors(); } void setClipNearDistance(double clipNearDistance) { this->clipNearDistance = clipNearDistance; } void setClipFarDistance(double clipFarDistance) { this->clipFarDistance = clipFarDistance; } void setScaleValue(double scaleValue) { this->scaleValue = scaleValue; } void setCameraDistance(double cameraDistance) { this->cameraDistance = cameraDistance; } // get functions int getProjectionType() { return projectionType; } int getShadingType() { return shadingType; } double getZenit() { return zenit; } double getAzimut() { return azimut; } double getClipNearDistance() { return clipNearDistance; } double getClipFarDistance() { return clipFarDistance; } double getScaleValue() { return scaleValue; } double getCameraDistance() { return cameraDistance; } QVector3D getVector_n() { return n; } QVector3D getVector_u() { return u; } QVector3D getVector_v() { return v; } QString getCoordinatesVector_n(int precision = 6); QString getCoordinatesVector_u(int precision = 6); QString getCoordinatesVector_v(int precision = 6); };
0e43e32230bd69a3967e28ad2507cf420647ea04
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
/graphics/libgltf/files/patch-src_Shaders.cpp
a5a68b445ed9590a09c5952303b4ee2705ee289a
[ "BSD-2-Clause" ]
permissive
freebsd/freebsd-ports
86f2e89d43913412c4f6b2be3e255bc0945eac12
605a2983f245ac63f5420e023e7dce56898ad801
refs/heads/main
2023-08-30T21:46:28.720924
2023-08-30T19:33:44
2023-08-30T19:33:44
1,803,961
916
918
NOASSERTION
2023-09-08T04:06:26
2011-05-26T11:15:35
null
UTF-8
C++
false
false
310
cpp
patch-src_Shaders.cpp
--- src/Shaders.cpp.orig 2014-10-01 18:31:43 UTC +++ src/Shaders.cpp @@ -175,7 +175,7 @@ bool ShaderProgram::compileShader(const char* pShader, }; const GLint aSizes[] = { - strlen("#version 130\n"), + sizeof("#version 130\n") - 1, iGLSize, };
e236f9ea0be62a7f65e024212851e70f3e5591f0
6da981a79c000e383b18fca44a25c4eb6595101e
/src/plugins/Pie/commands.cpp
6c204baa3d85b8af52aef7e41361c48e59986e77
[]
no_license
Artanidos/AnimationMaker
bb48aa2166e6c70a7768ffe71dc4ff9cf0f6f03c
9b34fea1182e11708e21c6fc568712992bb9e7ee
refs/heads/master
2022-06-30T04:39:35.996533
2022-06-09T16:25:33
2022-06-09T16:25:33
79,568,692
137
21
null
2021-06-22T20:24:26
2017-01-20T15:05:26
C++
UTF-8
C++
false
false
2,823
cpp
commands.cpp
/**************************************************************************** ** Copyright (C) 2017 Olaf Japp ** ** This file is part of AnimationMaker. ** ** AnimationMaker is free software: you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation, either version 3 of the License, or ** (at your option) any later version. ** ** AnimationMaker 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 AnimationMaker. If not, see <http://www.gnu.org/licenses/>. ** ****************************************************************************/ #include "commands.h" #include "animationscene.h" ChangeStartAngleCommand::ChangeStartAngleCommand(int newValue, int oldValue, AnimationScene *scene, Pie *pie, QUndoCommand *parent) : QUndoCommand(parent) { m_oldValue = oldValue; m_newValue = newValue; m_pie = pie; m_time = scene->playheadPosition(); m_autokeyframes = scene->autokeyframes(); m_autotransition = scene->autotransition(); m_keyframe = nullptr; setText("Change Pie Start Angle"); } void ChangeStartAngleCommand::undo() { m_pie->setStartAngle(m_oldValue); m_pie->adjustKeyframes("startAngle", QVariant(m_oldValue), m_time, m_autokeyframes, m_autotransition, &m_keyframe, true); emit m_pie->startAngleChanged(m_oldValue); } void ChangeStartAngleCommand::redo() { m_pie->setStartAngle(m_newValue); m_pie->adjustKeyframes("startAngle", QVariant(m_newValue), m_time, m_autokeyframes, m_autotransition, &m_keyframe, false); emit m_pie->startAngleChanged(m_newValue); } ChangeSpanAngleCommand::ChangeSpanAngleCommand(int newValue, int oldValue, AnimationScene *scene, Pie *pie, QUndoCommand *parent) : QUndoCommand(parent) { m_oldValue = oldValue; m_newValue = newValue; m_pie = pie; m_time = scene->playheadPosition(); m_autokeyframes = scene->autokeyframes(); m_autotransition = scene->autotransition(); m_keyframe = nullptr; setText("Change Pie Span Angle"); } void ChangeSpanAngleCommand::undo() { m_pie->setSpanAngle(m_oldValue); m_pie->adjustKeyframes("spanAngle", QVariant(m_oldValue), m_time, m_autokeyframes, m_autotransition, &m_keyframe, true); emit m_pie->spanAngleChanged(m_oldValue); } void ChangeSpanAngleCommand::redo() { m_pie->setSpanAngle(m_newValue); m_pie->adjustKeyframes("spanAngle", QVariant(m_newValue), m_time, m_autokeyframes, m_autotransition, &m_keyframe, false); emit m_pie->spanAngleChanged(m_newValue); }
5078dacd12939bcab218704bcdf47137348edea7
85c604d8cfba6b60ab8297b1288536344006d926
/CodeChef/Easy/ANUBTG.cpp
9076107189f8e7e08b94c37a5ee6445c20ef4d8b
[]
no_license
bhuvi99/SPOJ
6f693e65e29b279e5e7b6a854e1538210f1c86ea
9f2c209165ea8c3f08bed07ae9e85ab64e65d195
refs/heads/master
2021-07-04T23:19:45.194740
2017-09-26T11:58:29
2017-09-26T11:58:29
104,072,207
0
0
null
null
null
null
UTF-8
C++
false
false
358
cpp
ANUBTG.cpp
#include<iostream> #include<algorithm> #define rep(i,a,n) for(int i=(a);i<n;i++) using namespace std; int main(){ ios::sync_with_stdio(0); cin.tie(0); int t,n,cost; cin>>t; while(t--){ cin>>n; int k[n]; rep(i,0,n) cin>>k[i]; sort(k,k+n);cost=0; for(int i=n-1;i>=0;i-=4){ cost+=k[i]; if(i) cost+=k[i-1]; } cout<<cost<<endl; } }
d011134202824aae13126cf53ca4e10c55c1a2b6
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5634947029139456_0/C++/Darsein/a.cpp
8ef06a96143a577b843af096f6861bac59fd974e
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
1,207
cpp
a.cpp
#include<iostream> #include<string> #include<algorithm> #include<stack> #include<queue> #include<set> #include<complex> #include<map> #include<list> #include<deque> #include<cstdio> #include<cstdlib> #include<cmath> #include<cstring> #define rep(i,n) for(int i=0;i<(int)(n);i++) using namespace std; typedef long long ll; ll bin(string s){ ll res = 0; rep(i,s.size()){ if(s[i]=='1')res |= 1LL<<i; } return res; } int main(){ int testcase; int ans; cin >> testcase; for(int casenum=1;casenum<=testcase;casenum++){ ans = 1e8; int n,l; cin >> n >> l; string o[200],d[200]; set<ll> s; rep(i,n)cin >> o[i]; rep(i,n){ cin >> d[i]; s.insert(bin(d[i])); } rep(i,n)rep(j,n){ string swc; int num = 0; rep(x,l){ if(o[i][x] != d[j][x])swc += '1', num++; else swc += '0'; } if(num>=ans)continue; bool f = true; rep(k,n){ ll bin = 0; rep(x,l){ if(o[k][x] != swc[x])bin |= 1LL<<x; } if(s.find(bin)==s.end()){ f = false; break; } } if(f)ans = num; } cout << "Case #" << casenum << ": "; if(ans<1e8)cout << ans << endl; else cout << "NOT POSSIBLE" << endl; } }
e9cba1201f5ab20c28d421bc89e790ed04027f21
e753edbd9a55616fa123b7f4b116891cb43cef6c
/player.h
34ee5c9536c87700350a0411cad9151a8810d038
[]
no_license
JulieMckenna/BattleShip-game
26538df5392b6fcfdabf077a94b5a9a75c9fef40
6581491d63f97b4de15c819c1752e32ef2436bf0
refs/heads/master
2022-10-13T17:26:15.948176
2020-06-09T15:05:59
2020-06-09T15:05:59
271,033,374
0
0
null
null
null
null
UTF-8
C++
false
false
6,242
h
player.h
#include "board.h" #include <sstream> #include <limits> class player_c{ private: //each boat hit they get a point int score; string name; int hitsAgainst; vector<string> gueses; board myShips; board myMoves; player_c *enemy; public: player_c(){ //cout << "Made an empty player please fill it.\n"; } player_c(int sc, string na, int ha){ score = sc; name = na; hitsAgainst = ha; } int getScore(){return score;} string getName(){return name;} int getHitsAgainst(){return hitsAgainst;} void setScore(int newscore){score = newscore;} void setName(string newName){name = newName;} void setHitsAginst(int ha){hitsAgainst = ha;} //used to tell other functions which board to check when shooting void setEnemy(player_c *opponent){ enemy = opponent; } //to get the user input for the row shot and ensuring they type an integer int getUserRow(){ bool valid = 0; int row = -1; do{ cout << "What row?" << endl; cin >> row; if(cin.good()){ if(row <= 10 && row >= 1){ valid = 1; }else{ cout << "That is outside of the range of this board, try again" << endl; } }else{ //something went wrong, we reset the buffer's state to good cin.clear(); //and empty it cin.ignore(numeric_limits<streamsize>::max(),'\n'); cout << "Invalid Integer, Please re-enter." << endl; } }while(!valid); return row-1; } //to get the user input for the column shot and ensuring they type a valid letter int getUserColumn(){ bool valid = 0; int col = -1; char column; do{ cout << "What column?(lowercase letters only)" << endl; cin >> column; col = myShips.charToNum(column); if(cin.good()){ if(col <= 9 && col >= 0){ valid = 1; }else{ cout << "That is outside of the range of this board (use lowercase)" << endl; } }else{ //something went wrong, we reset the buffer's state to good cin.clear(); //and empty it cin.ignore(numeric_limits<streamsize>::max(),'\n'); cout << "Invalid character, Please re-enter (lowercase)." << endl; } }while(!valid); return col; } //asks the user for a row and column and fires. bool fire(){ cout << endl; cout << "Legend:" << endl; cout << "1 is where your boats are" << endl; cout << "2 is where your boats where hit" << endl; cout << "and 3 is where your oponent missed your boats" << endl << endl; cout << "Here is the board where you can see your hits and misses" << endl; myMoves.printBoard(); cout << "Here is where your boats are and their condition" << endl; myShips.printBoard(); int row; char col; int r,c; bool repeat = 0; bool hit = 0; do{ if(repeat){ cout << "You already shot there" << endl; } r = getUserRow(); c = getUserColumn(); cout << endl; repeat = 1; }while(myMoves.getValue(r, c) != EMPTY); //check to see if we hit a boat if(enemy->myShips.getValue(r, c)){ //if true, we hit the boat. we put a pin in it and player2's board should update myMoves.changeValue(r, c, HIT); enemy->myShips.editBoat(r,c); hit = 1; }else{ //if false then we need to keep track of this miss myMoves.changeValue(r, c, MISS); enemy->myShips.changeValue(r,c, MISS); hit = 0; } //returning if we hit the ship or not so we know if we have to switch turns return hit; } //asks a player where they would like to place their boat void askForBoats(){ int size, r, c;//holds info about where the boat should go and how big it is string direction;//holds the direction the ship will be oriented for(int i = 0; i < 5; ){//loops through boat of size 1-6 myShips.printBoard();//prints board so the player can see where they want to place size = i+1;//we want a boat of size 1-5 cout << "Now placing boat " << size << endl; r = getUserRow();//this function ensures the entered values is an int and returns it c = getUserColumn();//this function ensures the user enters a character and converts it to the proper int cout << "what direcion will the boat face? (vertical - ship runs down from point, horizontal - ship runs right from point)" <<endl; cin >> direction; cout << "the direction is " << direction << " at " << r << "," << c << endl; //tests to see if the placement of the boat is valid if(!myShips.isSpace(size, direction, r, c)){ //cant place a boat there, dont increment to the next boat cout << "not valid" << endl; }else{ //that is a good spot, add the boat and make sure to increment to the next boat myShips.addBoat(size, direction, r, c); i++; } } } //fills the bottom 5 rows with boats of size one for testing void testBoats(){ for(int i = 5; i < 6; i++){ for(int j =2; j < 7; j++){ myShips.addBoat(1,"vertical",i,j); } } myShips.printBoard(); } //checks to see if a player has lost 6 boats yet bool lost(){ if(myShips.numBoatsLost() > 4){ return 1; }else{ return 0; } } };
6616d2435b6eb7488fb80174ee11a3df844cc2da
1a2796041b763f7176427d53cb895cec59efb1a3
/UdemyNotes/Complete_Modern_C++/lvaluervalue.cpp
464a922d8af489d9e7766f198da384598b9cfd86
[]
no_license
vineethkartha/Notes
2e20bf2494f76f2cd43a111022cc5d5096497a3b
1ec70129e6fddac8dad4ff62466d7fbb230596a8
refs/heads/master
2021-06-16T22:00:18.192608
2021-02-18T10:45:00
2021-02-18T10:45:00
158,053,119
0
0
null
null
null
null
UTF-8
C++
false
false
207
cpp
lvaluervalue.cpp
#include <iostream> int foo(int &a) { std::cout<<"This is lvalue overload\n"; } int foo(int &&a) { std::cout<<"This is rvalue overload\n"; } int main() { int a =5; foo(a); foo(5); return 0; }
a0e70b83b91908ac6998d8d507aa17f141d9ed2d
6d088ec295b33db11e378212d42d40d5a190c54c
/contrib/mul/mbl/mbl_minimum_spanning_tree.h
cc4fd8205fe10df3fa11913cee5c1995cba30572
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
vxl/vxl
29dffd5011f21a67e14c1bcbd5388fdbbc101b29
594ebed3d5fb6d0930d5758630113e044fee00bc
refs/heads/master
2023-08-31T03:56:24.286486
2023-08-29T17:53:12
2023-08-29T17:53:12
9,819,799
224
126
null
2023-09-14T15:52:32
2013-05-02T18:32:27
C++
UTF-8
C++
false
false
1,659
h
mbl_minimum_spanning_tree.h
#ifndef mbl_minimum_spanning_tree_h_ #define mbl_minimum_spanning_tree_h_ //: // \file // \author Tim Cootes // \brief Functions to compute minimum spanning trees from distance data #include <vector> #include <iostream> #include <utility> #include <vnl/vnl_matrix.h> #include <vgl/vgl_point_2d.h> #include <vgl/vgl_point_3d.h> #ifdef _MSC_VER # include <vcl_msvc_warnings.h> #endif //: Compute the minimum spanning tree given a distance matrix // \param pairs[0].first is the root node // Tree defined by pairs. // \param pairs[i].second is linked to \param pairs[i].first // We compute the minimum spanning tree of the graph using Prim's algorithm. void mbl_minimum_spanning_tree(const vnl_matrix<double>& D, std::vector<std::pair<int,int> >& pairs); //: Compute the minimum spanning tree of given points // \param pairs[0].first is the root node // Tree defined by pairs. // \param pairs[i].second is linked to \param pairs[i].first // We compute the minimum spanning tree of the graph using Prim's algorithm. void mbl_minimum_spanning_tree(const std::vector<vgl_point_2d<double> >& pts, std::vector<std::pair<int,int> >& pairs); //: Compute the minimum spanning tree of given points // \param pairs[0].first is the root node // Tree defined by pairs. // \param pairs[i].second is linked to \param pairs[i].first // We compute the minimum spanning tree of the graph using Prim's algorithm. void mbl_minimum_spanning_tree(const std::vector<vgl_point_3d<double> >& pts, std::vector<std::pair<int,int> >& pairs); #endif // mbl_minimum_spanning_tree_h_
d9e67b3044abe2206a1e5fe9bea14ccbda936fb0
72ed63c92ff6b2c66eb26f9bb8fe42f9c30b6dcc
/PAT test/050 algorithm中的常用函数.cpp
4cc22f5bafa29ebfcab16986a120a3289817e97a
[]
no_license
wangjunjie1107/CodeTesting
ceee7adbf73d357cb3b93e751682e05b83b54328
2e614831877f30db109e5b669a1d77bb17208a5a
refs/heads/master
2020-07-15T04:59:36.138974
2019-10-30T00:39:29
2019-10-30T00:39:29
205,484,180
0
0
null
null
null
null
GB18030
C++
false
false
882
cpp
050 algorithm中的常用函数.cpp
#define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<stdio.h> #include<stdlib.h> #include<set> #include<vector> #include<string> #include<map> //map和multimap的头文件 #include<unordered_map> //unordered_map #include<queue> #include<utility> #include<algorithm> using namespace std; void test01() { //最大值 最小值 绝对值 cout << max(1, -1) << endl; cout << min(10, -11) << endl; cout << abs(-100) << endl; //交换两个变量的值 int x = 10; int y = -20; swap(x, y); cout << x << " " << y << endl; //反转 反转一个字符串 string str = "wnagjuneieagr"; reverse(str.begin(), str.end()); cout << str << endl; //fill 将一个区间赋值任意一个值 string str2 = "waggfertdyjyhg"; fill(str2.begin() + 3, str2.end(), 'w'); cout << str2 << endl; } int main() { test01(); system("pause"); return EXIT_SUCCESS; }
55f0c9ff832504b5fcbcc0733936d45f21fe0bad
efb87e4ac44f9cc98eab0dc162266fa1b99b7e5a
/Codeforces/CF100283-Gym-C.cpp
116a318dc803fa64024037887e618168fd9af04f
[]
no_license
farmerboy95/CompetitiveProgramming
fe4eef85540d3e91c42ff6ec265a3262e5b97d1f
1998d5ae764d47293f2cd71020bec1dbf5b470aa
refs/heads/master
2023-08-29T16:42:28.109183
2023-08-24T07:00:19
2023-08-24T07:00:19
206,353,615
12
1
null
null
null
null
UTF-8
C++
false
false
5,748
cpp
CF100283-Gym-C.cpp
/* Author: Nguyen Tan Bao Status: AC Idea: - At each second, for each position (i,j), calculate number of thieves that would be asked by other thieves to get treasure. - More formally, let a[t][i][j] = sum(a[t+1][u][v]) (the distance between (u, v) and (i, j) is smaller than t) (t >= 1, t is the remaining time) - Result would be sum(a[1][i][j] * gold[i][j]) - First, at each second k, calculate a[k][1][1], then move it right or down, add and subtract corresponding boundary diamond shape of it. - Use prefix sum to get diagonal sum. */ #include <bits/stdc++.h> #define FI first #define SE second #define EPS 1e-9 #define ALL(a) a.begin(),a.end() #define SZ(a) int((a).size()) #define MS(s, n) memset(s, n, sizeof(s)) #define FOR(i,a,b) for (int i = (a); i <= (b); i++) #define FORE(i,a,b) for (int i = (a); i >= (b); i--) #define FORALL(it, a) for (__typeof((a).begin()) it = (a).begin(); it != (a).end(); it++) #define WHATIS(x) cout << #x << " is " << x << endl; #define ERROR(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); } //__builtin_ffs(x) return 1 + index of least significant 1-bit of x //__builtin_clz(x) return number of leading zeros of x //__builtin_ctz(x) return number of trailing zeros of x using namespace std; using ll = long long; using ld = double; typedef pair<int, int> II; typedef pair<II, int> III; typedef complex<ld> cd; typedef vector<cd> vcd; void err(istream_iterator<string> it) {} template<typename T, typename... Args> void err(istream_iterator<string> it, T a, Args... args) { cout << *it << " = " << a << endl; err(++it, args...); } const ll MODBASE = 1000000007LL; const int MAXN = 110; const int MAXM = 200010; const int MAXK = 110; const int MAXQ = 200010; int t, n, m, s; ll a[MAXN][MAXN], gold[MAXN][MAXN], b[MAXN][MAXN], sum[2][MAXN*2][MAXN]; void init() { int x, y; cin >> n >> m >> s >> x >> y; FOR(i,1,n) FOR(j,1,m) cin >> gold[i][j]; FOR(i,1,n) FOR(j,1,m) a[i][j] = 0; a[x][y] = 1; } ll get(int arrNum, int u, int l, int r) { if (u < 1 || u > n+m) return 0; l = max(l, 1); r = min(r, m); if (l > r) return 0; return (sum[arrNum][u][r] - sum[arrNum][u][l-1] + MODBASE) % MODBASE; } bool isInside(int i, int j) { return i >= 1 && i <= n && j >= 1 && j <= m; } /* get all elements that have Manhattan distance from # to X (i, j) is k, and this diamond shape is above X ..#.. .#.#. #.X.# ..... ..... */ ll getUpperSum(int i, int j, int k) { int lef = j - k; int rig = j + k; ll res = (get(0, i+lef, lef, j) + get(1, i-rig+m, j, rig)) % MODBASE; if (isInside(i-k, j)) res = (res - a[i-k][j] + MODBASE) % MODBASE; return res; } /* get all elements that have Manhattan distance from # to X (i, j) is k, and this diamond shape is below X ..... ..... #.X.# .#.#. ..#.. */ ll getLowerSum(int i, int j, int k) { int lef = j - k; int rig = j + k; ll res = (get(1, i-lef+m, lef, j) + get(0, i+rig, j, rig)) % MODBASE; if (isInside(i+k, j)) res = (res - a[i+k][j] + MODBASE) % MODBASE; return res; } /* get all elements that have Manhattan distance from # to X (i, j) is k, and this diamond shape is to the left of X ..#.. .#... #.X.. .#... ..#.. */ ll getLeftSum(int i, int j, int k) { int upp = i - k; int low = i + k; ll res = (get(0, upp+j, j-k, j) + get(1, low-j+m, j-k, j)) % MODBASE; if (isInside(i, j-k)) res = (res - a[i][j-k] + MODBASE) % MODBASE; return res; } /* get all elements that have Manhattan distance from # to X (i, j) is k, and this diamond shape is to the right of X ..#.. ...#. ..X.# ...#. ..#.. */ ll getRightSum(int i, int j, int k) { int upp = i - k; int low = i + k; ll res = (get(1, upp-j+m, j, j+k) + get(0, low+j, j, j+k)) % MODBASE; if (isInside(i, j+k)) res = (res - a[i][j+k] + MODBASE) % MODBASE; return res; } void solve() { FORE(k,s-1,1) { // get prefix sum of all diagonal lines FOR(i,1,n+m) FOR(j,0,m) sum[0][i][j] = sum[1][i][j] = 0; FOR(i,1,n) FOR(j,1,m) { sum[0][i+j][j] = a[i][j]; sum[1][i-j+m][j] = a[i][j]; } FOR(i,1,n+m) { FOR(j,1,m) { sum[0][i][j] = (sum[0][i][j] + sum[0][i][j-1]) % MODBASE; sum[1][i][j] = (sum[1][i][j] + sum[1][i][j-1]) % MODBASE; } } // calc b[1][1] b[1][1] = 0; FOR(u,-k,k) { int remain = k - abs(u); FOR(v,-remain,remain) { if (!isInside(u+1, v+1)) continue; b[1][1] = (b[1][1] + a[u+1][v+1]) % MODBASE; } } // calc all other position of array b FOR(i,1,n) FOR(j,1,m) { if (i == 1 && j == 1) continue; if (i > 1) { b[i][j] = ((b[i-1][j] - getUpperSum(i-1, j, k) + MODBASE) % MODBASE + getLowerSum(i, j, k)) % MODBASE; } else { b[i][j] = ((b[i][j-1] - getLeftSum(i, j-1, k) + MODBASE) % MODBASE + getRightSum(i, j, k)) % MODBASE; } } // move array b to a FOR(i,1,n) FOR(j,1,m) a[i][j] = b[i][j]; } // calc result ll res = 0; FOR(i,1,n) FOR(j,1,m) res = (res + gold[i][j] * a[i][j] % MODBASE) % MODBASE; cout << res << "\n"; } int main() { ios::sync_with_stdio(0); cin.tie(nullptr); freopen("treasures.in", "r", stdin); cin >> t; FOR(o,1,t) { cout << "Case " << o << ": "; init(); solve(); } return 0; }
1eb3bcea42a4b09f6e45906c2fb41144dc130b9c
d0f5a31932b49ac1a80d61d308bd43490631b1a3
/1.4 Array/int.cpp
b1b61fe9558dc5f39cc54ea6dd9ceb456fa736c4
[ "MIT" ]
permissive
arryaaas/Programming-Algorithms
2930d9ee7768f4a3f975d692abc60baf189567f8
f469431830cbe528feb297abd47d2d6c08e0781a
refs/heads/master
2023-07-10T12:39:46.704085
2021-08-10T23:21:08
2021-08-10T23:21:08
316,120,041
0
0
null
null
null
null
UTF-8
C++
false
false
713
cpp
int.cpp
#include <iostream> using namespace std; int main() { int tabInt[5], jumlah; cout << "Array integer berisi 5 elemen" << endl; cout << "Elemen ke-1 : "; cin >> tabInt[0]; cout << "Elemen ke-2 : "; cin >> tabInt[1]; cout << "Elemen ke-3 : "; cin >> tabInt[2]; cout << "Elemen ke-4 : "; cin >> tabInt[3]; cout << "Elemen ke-5 : "; cin >> tabInt[4]; cout << endl; jumlah = tabInt[0] + tabInt[1] + tabInt[2] + tabInt[3] + tabInt[4]; cout << "Hasil penjumlahan ke-5 elemen adalah " << jumlah << endl; return 0; } /* Array berisi 5 elemen bertipe integer. Buat masukan untuk mengisi ke-5 elemen tersebut dan kemudian tamplikan hasil penjumlahan ke-5 elemen tersebut! */
c50973186b854834a37084db4281a69723548f43
3f94fde265e466368ca72a9b26c7a404cf2fba8f
/Engine/src/trace/tracescene.cpp
92ea3709b5cbff68dc1052fe6c4532cad8e28d09
[]
no_license
HanfeiChen/ray-tracer
f0c3937525a81205281ce19b90fe4d250003dd94
83657818d45cb4f495c2068dc9595960bc0bf1f0
refs/heads/master
2022-11-10T06:38:25.432149
2020-06-26T21:22:27
2020-06-26T21:22:27
275,250,143
0
0
null
null
null
null
UTF-8
C++
false
false
5,674
cpp
tracescene.cpp
#include "tracescene.h" #include <scene/scene.h> #include <scene/sceneobject.h> #include <scene/components/triangleface.h> TraceScene::TraceScene(Scene *scene, bool use_acceleration) { AddSceneObjects(&(scene->GetSceneRoot()), glm::mat4()); if (!use_acceleration) { for (auto obj : bounded_objects) { unbounded_objects.push_back(obj); } bounded_objects.clear(); } tree = new TreeBox(bounded_objects); } TraceScene::~TraceScene() { for (auto obj : bounded_objects) delete obj; bounded_objects.clear(); for (auto obj : unbounded_objects) delete obj; unbounded_objects.clear(); for (auto light : lights) delete light; lights.clear(); delete tree; } void TraceScene::AddSceneObjects(SceneObject* obj, glm::mat4 model_matrix) { if (obj->IsInternal() || !obj->IsEnabled()) { return; } model_matrix = model_matrix * obj->GetTransform().GetMatrix(); Geometry* geo = obj->GetComponent<Geometry>(); if (geo != nullptr && geo->RenderMaterial.Get() != nullptr && geo->RenderMaterial.Get()->PrepareToTrace()) { if (geo->UseCustomTrace()) { TraceGeometry* tso = new TraceGeometry(geo, model_matrix); if (tso->world_bbox == nullptr) { unbounded_objects.push_back(tso); } else { bounded_objects.push_back(tso); } } else { Mesh* mesh = geo->GetRenderMesh(); if (mesh != nullptr) { glm::mat4 world2local = glm::inverse(model_matrix); glm::mat3 normallocal2world = glm::transpose(glm::mat3(world2local)); std::vector<unsigned int> tris = mesh->GetTriangles(); std::vector<float> positions = mesh->GetPositions(); std::vector<float> uvs = mesh->GetUVs(); std::vector<float> normals = mesh->GetNormals(); for (size_t i=0; i<tris.size(); i+=3) { //cringe Geometry* tgeo = new TriangleFace( glm::vec3(model_matrix*glm::vec4(positions[tris[i]*3],positions[tris[i]*3+1],positions[tris[i]*3+2],1)), glm::vec3(model_matrix*glm::vec4(positions[tris[i+1]*3],positions[tris[i+1]*3+1],positions[tris[i+1]*3+2],1)), glm::vec3(model_matrix*glm::vec4(positions[tris[i+2]*3],positions[tris[i+2]*3+1],positions[tris[i+2]*3+2],1)), normals.size()>0 ? normallocal2world*glm::vec3(normals[tris[i]*3],normals[tris[i]*3+1],normals[tris[i]*3+2]) : glm::vec3(0,1,0), normals.size()>0 ? normallocal2world*glm::vec3(normals[tris[i+1]*3],normals[tris[i+1]*3+1],normals[tris[i+1]*3+2]) : glm::vec3(0,1,0), normals.size()>0 ? normallocal2world*glm::vec3(normals[tris[i+2]*3],normals[tris[i+2]*3+1],normals[tris[i+2]*3+2]) : glm::vec3(0,1,0), uvs.size()>0 ? glm::vec2(uvs[tris[i]*2],uvs[tris[i]*2+1]) : glm::vec2(0,0), uvs.size()>0 ? glm::vec2(uvs[tris[i+1]*2],uvs[tris[i+1]*2+1]) : glm::vec2(0,0), uvs.size()>0 ? glm::vec2(uvs[tris[i+2]*2],uvs[tris[i+2]*2+1]) : glm::vec2(0,0), normals.size()>0 ); tgeo->RenderMaterial.Set(geo->RenderMaterial.Get()); bounded_objects.push_back(new TraceGeometry(tgeo, true)); } } } } Light* light = obj->GetComponent<Light>(); if (light != nullptr) { TraceLight* tso = new TraceLight(light, model_matrix); lights.push_back(tso); if (glm::length2(light->Ambient.GetRGB()) > 0.f) { uses_blinn_phong_ambient = true; } } for(SceneObject* child : obj->GetChildren()) { AddSceneObjects(child, model_matrix); } } bool TraceScene::Intersect(const Ray& r, Intersection& i) const { bool intersect_found = false; Intersection cur; // try the non-bounded objects for (auto j = unbounded_objects.begin(); j != unbounded_objects.end(); j++) { if( (*j)->Intersect( r, cur ) && cur.t>0) { if( !intersect_found || (cur.t < i.t) ) { i = cur; intersect_found = true; } } } // Use the BSP tree to quickly intersect the ray with bounded objects if (tree->Intersect(r, cur)) { if (!intersect_found || (cur.t < i.t) ) { i = cur; intersect_found = true; } } // go over the BSP tree's objects without using the BSP tree to do so (SLOW) /* for (auto j = bounded_objects.begin(); j != bounded_objects.end(); j++) { Intersection cur; if( (*j)->Intersect( r, cur ) && cur.t>0 ) { if( !intersect_found || (cur.t < i.t) ) { i = cur; intersect_found = true; } } } */ // TODO: This is where you can get an amazing speed-up by // using an acceleration data structure to make intersection testing // more efficient! // Test for intersection with each object in the scene // for( iter j = objects.begin(); j != objects.end(); ++j ) { // isect cur; // if( (*j)->intersect( r, cur ) ) { // if( !have_one || (cur.t < i.t) ) { // i = cur; // have_one = true; // } // } // } if(!intersect_found) i.t = (-100); // if debugging, // if (Settings.Debugging) intersectCache.push_back(std::make_pair(r, i)); return intersect_found; }
d030925899cb4cdc17f0667f11f84280b654dd67
fa0a4154da274110436f5eeacdd5309e084b6325
/timing/timing.cc
85222a6f04035b1206d8858ad65fe5ad5434982b
[ "Apache-2.0" ]
permissive
MollyDream/grpc
3755e22e98314454997205bc6a88517e13e1770e
d2c4e593d1cf04445cd9bb5eb0de548c958af6f9
refs/heads/master
2020-07-09T22:33:26.413790
2019-08-24T05:40:02
2019-08-24T05:40:02
204,096,600
0
0
Apache-2.0
2019-08-24T02:16:42
2019-08-24T02:16:41
null
UTF-8
C++
false
false
2,483
cc
timing.cc
#include <iostream> #include <chrono> #include <array> #include <vector> #include <math.h> #include <cassert> #include <pthread.h> #include <unistd.h> using namespace std; using namespace chrono; enum ProfType {k_init, k_alloc, k_sched, k_run, k_other}; class TimingReference { public: using D = duration<int,nano>; vector<string> names {"Init", "Alloc", "Sched", "Run", "Other"}; ProfType cur; array<long long unsigned, 5> times; array<long long unsigned, 5> times_sq; time_point<high_resolution_clock> last; int recs {0}; TimingReference() { for (int i=0; i<times.size(); i++) { times[i] = 0; times_sq[i] = 0; } ReInit(k_other); } void ReInit(ProfType t) { cur = t; last = high_resolution_clock::now(); } void StartNew(ProfType t) { _fin(); cur = t; } void Finish() { _fin(); for (int i=0; i<times.size(); i++) { times_sq[i] = times[i]*times[i]; } } void Add(TimingReference &t) { for (int i=0; i<times.size(); i++) { times[i] += t.times[i]; t.times[i] = 0; times_sq[i] += t.times_sq[i]; t.times_sq[i] = 0; } recs += t.recs; } void Print() { cout << "Captured profiling data from " << recs << " traces" << endl; printf("%16s %16s %16s\n", "", "mean", "Pop. SD"); for (int i=0; i<times.size(); i++) { int sd = sqrt((times_sq[i]-times[i]*times[i]/recs)/recs); printf("%16s: %16d ns +/- %16d ns\n", names[i].c_str(), times[i]/recs, sd); } } private: void _fin() { auto next = high_resolution_clock::now(); //D elapsed = duration_cast(next - last); D elapsed = next - last; times[cur] += elapsed.count(); last = next; assert(recs == 0 || recs == 1); recs = 1; } }; void *threadfunc(void *p) { cout << "Hello from thread: " << *(int*)p << endl; delete (int*)p; return NULL; } int main(int argc, char **argv) { cout << "Clock duration " << endl; TimingReference a; for (int i=0; i<1000; i++) { TimingReference r; r.ReInit(k_alloc); vector<pthread_t> threads; for (int i=0; i<10; i++) { int *p = new int; *p = i; threads.emplace_back(); int tmp = pthread_create(&threads.back(), NULL, threadfunc, (void*)p); } r.StartNew(k_run); for (auto &t : threads) { pthread_join(t, NULL); } r.StartNew(k_other); cout << "All threads joined" << endl; r.Finish(); a.Add(r); } a.Print(); }
2d009d8cf3e04ec9a212463f9b1cc84d04cf94bb
dff19e230b4ce0175d84d18c9844aa097b11c019
/BoardSpace.cpp
fcb0dc9ec4c285450c942989c552089f1425eeb1
[]
no_license
LordMotas/OnitamaAI
b882de3b7bbc288cce11129e053b40b876897dd3
40c6b149f2c620fdab18bd0ab6f18c70078a8cad
refs/heads/master
2020-06-10T20:31:02.886677
2016-12-12T17:55:34
2016-12-12T17:55:34
75,882,421
1
0
null
null
null
null
UTF-8
C++
false
false
210
cpp
BoardSpace.cpp
#include "BoardSpace.h" BoardSpace::BoardSpace(Piece spacePiece, int onmyo) { piece = spacePiece; isOnmyoSpace = onmyo; } BoardSpace::BoardSpace(Piece spacePiece) { piece = spacePiece; isOnmyoSpace = 0; }
f60c233efb6bd05b5081c49e99a2cd251b9a2dbe
ed480e5030ec091da42401b204345da285f74620
/sdr-cxx/src/AUBasicStream.cpp
8bfb18f8c1c89f72092360eecb20c9a003ed163e
[ "BSD-3-Clause" ]
permissive
jdstmporter/SDRAudio
d1d0679d479ec6886b732ad23909e7c7161094ad
40392ab443de2e565f8e6b448af6cc3012c906db
refs/heads/master
2023-01-13T12:59:07.632630
2020-11-20T01:00:20
2020-11-20T01:00:20
310,144,111
0
0
null
null
null
null
UTF-8
C++
false
false
870
cpp
AUBasicStream.cpp
/* * AUBasicStream.cpp * * Created on: 10 Nov 2020 * Author: julianporter */ #include "AUBasicStream.hpp" namespace audio { AUBasicStream::~AUBasicStream() { if(stream!=nullptr) { try { Pa_CloseStream(stream); stream=nullptr; } catch(...) {} } } void AUBasicStream::open() { PaStream *stream_; PaStreamParameters p=params.streamParameters(device); AUError::check(Pa_OpenStream(&stream_,nullptr,&p,params.rate,fpb,paNoFlag,nullptr,nullptr)); stream=stream_; } void AUBasicStream::start() { if(stream==nullptr) { open(); AUError::check(Pa_StartStream(stream)); } } void AUBasicStream::stop() { if(stream!=nullptr) { AUError::check(Pa_StopStream(stream)); stream=nullptr; } } void AUBasicStream::forceStop() { if(stream!=nullptr) { AUError::check(Pa_AbortStream(stream)); stream=nullptr; } } } /* namespace audio */
1acf3824e1938004cd550a3e906cff47ecc6bada
7020ea489625e4cfa14bebe16c324e331b9641a1
/Utilities/_Source/MemoryPool/MemoryPool.inl
f943975b9b9fbfa830527be460800042a37680dd
[]
no_license
fredlim/GameEngine
fe129b2042357f03d4a3415b5c80bab2af519e8e
1ba2f86b321082a8e8f6159bd90dcaab738e5c59
refs/heads/master
2021-01-24T20:54:00.445552
2014-09-23T03:37:36
2014-09-23T03:37:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,236
inl
MemoryPool.inl
/** **************************************************************************************************** * \file MemoryPool.inl * \brief The inline functions implementation of MemoryPool class **************************************************************************************************** */ #include <assert.h> #include "../UtilitiesTypes.h" /** **************************************************************************************************** \fn const UINT32 Size( void ) const \brief Get size of each memory pool element \param NONE \return NONE **************************************************************************************************** */ const UINT32 Utilities::MemoryPool::Size( void ) const { FUNCTION_START; FUNCTION_FINISH; return _u32Size; } /** **************************************************************************************************** \fn const UINT8 Count( void ) const \brief Get total element in memory pool \param NONE \return NONE **************************************************************************************************** */ const UINT32 Utilities::MemoryPool::Count( void ) const { FUNCTION_START; FUNCTION_FINISH; return _u32NumElements; }
875d2efbb39c9473cf78593149d26c7808f94646
4e57ad279fb04b17f0b024dba780cbd7c0f14ec7
/lib/armadillo-11.4.1/include/armadillo_bits/SpSubview_bones.hpp
da60d972e5842a7f0369f8ea76f8e9ed4d6e8afd
[ "Apache-2.0" ]
permissive
dcajasn/Riskfolio-Lib
b9ed51b8da93c648f0e255bc7bc20e17d1290cfa
06dfe24745dd8ab40665621e72cfeb40a80c2b2e
refs/heads/master
2023-08-09T16:11:47.258143
2023-08-01T20:05:00
2023-08-01T20:05:00
244,460,835
2,266
403
BSD-3-Clause
2023-06-20T04:04:38
2020-03-02T19:49:06
C++
UTF-8
C++
false
false
16,453
hpp
SpSubview_bones.hpp
// SPDX-License-Identifier: Apache-2.0 // // Copyright 2008-2016 Conrad Sanderson (http://conradsanderson.id.au) // Copyright 2008-2016 National ICT Australia (NICTA) // // 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. // ------------------------------------------------------------------------ //! \addtogroup SpSubview //! @{ template<typename eT> class SpSubview : public SpBase< eT, SpSubview<eT> > { public: const SpMat<eT>& m; typedef eT elem_type; typedef typename get_pod_type<elem_type>::result pod_type; static constexpr bool is_row = false; static constexpr bool is_col = false; static constexpr bool is_xvec = false; const uword aux_row1; const uword aux_col1; const uword n_rows; const uword n_cols; const uword n_elem; const uword n_nonzero; protected: inline SpSubview(const SpMat<eT>& in_m, const uword in_row1, const uword in_col1, const uword in_n_rows, const uword in_n_cols); public: inline ~SpSubview(); inline SpSubview() = delete; inline SpSubview(const SpSubview& in); inline SpSubview( SpSubview&& in); inline const SpSubview& operator+= (const eT val); inline const SpSubview& operator-= (const eT val); inline const SpSubview& operator*= (const eT val); inline const SpSubview& operator/= (const eT val); inline const SpSubview& operator=(const SpSubview& x); template<typename T1> inline const SpSubview& operator= (const Base<eT, T1>& x); template<typename T1> inline const SpSubview& operator+=(const Base<eT, T1>& x); template<typename T1> inline const SpSubview& operator-=(const Base<eT, T1>& x); template<typename T1> inline const SpSubview& operator*=(const Base<eT, T1>& x); template<typename T1> inline const SpSubview& operator%=(const Base<eT, T1>& x); template<typename T1> inline const SpSubview& operator/=(const Base<eT, T1>& x); template<typename T1> inline const SpSubview& operator_equ_common(const SpBase<eT, T1>& x); template<typename T1> inline const SpSubview& operator= (const SpBase<eT, T1>& x); template<typename T1> inline const SpSubview& operator+=(const SpBase<eT, T1>& x); template<typename T1> inline const SpSubview& operator-=(const SpBase<eT, T1>& x); template<typename T1> inline const SpSubview& operator*=(const SpBase<eT, T1>& x); template<typename T1> inline const SpSubview& operator%=(const SpBase<eT, T1>& x); template<typename T1> inline const SpSubview& operator/=(const SpBase<eT, T1>& x); /* inline static void extract(SpMat<eT>& out, const SpSubview& in); inline static void plus_inplace(Mat<eT>& out, const subview& in); inline static void minus_inplace(Mat<eT>& out, const subview& in); inline static void schur_inplace(Mat<eT>& out, const subview& in); inline static void div_inplace(Mat<eT>& out, const subview& in); */ template<typename functor> inline void for_each(functor F); template<typename functor> inline void for_each(functor F) const; template<typename functor> inline void transform(functor F); inline void replace(const eT old_val, const eT new_val); inline void clean(const pod_type threshold); inline void clamp(const eT min_val, const eT max_val); inline void fill(const eT val); inline void zeros(); inline void ones(); inline void eye(); inline void randu(); inline void randn(); arma_hot inline SpSubview_MapMat_val<eT> operator[](const uword i); arma_hot inline eT operator[](const uword i) const; arma_hot inline SpSubview_MapMat_val<eT> operator()(const uword i); arma_hot inline eT operator()(const uword i) const; arma_hot inline SpSubview_MapMat_val<eT> operator()(const uword in_row, const uword in_col); arma_hot inline eT operator()(const uword in_row, const uword in_col) const; arma_hot inline SpSubview_MapMat_val<eT> at(const uword i); arma_hot inline eT at(const uword i) const; arma_hot inline SpSubview_MapMat_val<eT> at(const uword in_row, const uword in_col); arma_hot inline eT at(const uword in_row, const uword in_col) const; inline bool check_overlap(const SpSubview& x) const; inline bool is_vec() const; inline SpSubview_row<eT> row(const uword row_num); inline const SpSubview_row<eT> row(const uword row_num) const; inline SpSubview_col<eT> col(const uword col_num); inline const SpSubview_col<eT> col(const uword col_num) const; inline SpSubview rows(const uword in_row1, const uword in_row2); inline const SpSubview rows(const uword in_row1, const uword in_row2) const; inline SpSubview cols(const uword in_col1, const uword in_col2); inline const SpSubview cols(const uword in_col1, const uword in_col2) const; inline SpSubview submat(const uword in_row1, const uword in_col1, const uword in_row2, const uword in_col2); inline const SpSubview submat(const uword in_row1, const uword in_col1, const uword in_row2, const uword in_col2) const; inline SpSubview submat(const span& row_span, const span& col_span); inline const SpSubview submat(const span& row_span, const span& col_span) const; inline SpSubview operator()(const uword row_num, const span& col_span); inline const SpSubview operator()(const uword row_num, const span& col_span) const; inline SpSubview operator()(const span& row_span, const uword col_num); inline const SpSubview operator()(const span& row_span, const uword col_num) const; inline SpSubview operator()(const span& row_span, const span& col_span); inline const SpSubview operator()(const span& row_span, const span& col_span) const; inline void swap_rows(const uword in_row1, const uword in_row2); inline void swap_cols(const uword in_col1, const uword in_col2); // Forward declarations. class iterator_base; class const_iterator; class iterator; class const_row_iterator; class row_iterator; // Similar to SpMat iterators but automatically iterates past and ignores values not in the subview. class iterator_base { public: inline iterator_base(const SpSubview& in_M); inline iterator_base(const SpSubview& in_M, const uword col, const uword pos); arma_inline uword col() const { return internal_col; } arma_inline uword pos() const { return internal_pos; } arma_aligned const SpSubview* M; arma_aligned uword internal_col; arma_aligned uword internal_pos; typedef std::bidirectional_iterator_tag iterator_category; typedef eT value_type; typedef std::ptrdiff_t difference_type; // TODO: not certain on this one typedef const eT* pointer; typedef const eT& reference; }; class const_iterator : public iterator_base { public: inline const_iterator(const SpSubview& in_M, uword initial_pos = 0); inline const_iterator(const SpSubview& in_M, uword in_row, uword in_col); inline const_iterator(const SpSubview& in_M, uword in_row, uword in_col, uword in_pos, uword skip_pos); inline const_iterator(const const_iterator& other); arma_inline eT operator*() const; // Don't hold location internally; call "dummy" methods to get that information. arma_inline uword row() const { return iterator_base::M->m.row_indices[iterator_base::internal_pos + skip_pos] - iterator_base::M->aux_row1; } inline arma_hot const_iterator& operator++(); inline arma_warn_unused const_iterator operator++(int); inline arma_hot const_iterator& operator--(); inline arma_warn_unused const_iterator operator--(int); inline arma_hot bool operator!=(const const_iterator& rhs) const; inline arma_hot bool operator==(const const_iterator& rhs) const; inline arma_hot bool operator!=(const typename SpMat<eT>::const_iterator& rhs) const; inline arma_hot bool operator==(const typename SpMat<eT>::const_iterator& rhs) const; inline arma_hot bool operator!=(const const_row_iterator& rhs) const; inline arma_hot bool operator==(const const_row_iterator& rhs) const; inline arma_hot bool operator!=(const typename SpMat<eT>::const_row_iterator& rhs) const; inline arma_hot bool operator==(const typename SpMat<eT>::const_row_iterator& rhs) const; arma_aligned uword skip_pos; // not used in row_iterator or const_row_iterator }; class iterator : public const_iterator { public: inline iterator(SpSubview& in_M, const uword initial_pos = 0) : const_iterator(in_M, initial_pos) { } inline iterator(SpSubview& in_M, const uword in_row, const uword in_col) : const_iterator(in_M, in_row, in_col) { } inline iterator(SpSubview& in_M, const uword in_row, const uword in_col, const uword in_pos, const uword in_skip_pos) : const_iterator(in_M, in_row, in_col, in_pos, in_skip_pos) { } inline iterator(const iterator& other) : const_iterator(other) { } inline arma_hot SpValProxy< SpSubview<eT> > operator*(); // overloads needed for return type correctness inline arma_hot iterator& operator++(); inline arma_warn_unused iterator operator++(int); inline arma_hot iterator& operator--(); inline arma_warn_unused iterator operator--(int); // This has a different value_type than iterator_base. typedef SpValProxy< SpSubview<eT> > value_type; typedef const SpValProxy< SpSubview<eT> >* pointer; typedef const SpValProxy< SpSubview<eT> >& reference; }; class const_row_iterator : public iterator_base { public: inline const_row_iterator(); inline const_row_iterator(const SpSubview& in_M, uword initial_pos = 0); inline const_row_iterator(const SpSubview& in_M, uword in_row, uword in_col); inline const_row_iterator(const const_row_iterator& other); inline arma_hot const_row_iterator& operator++(); inline arma_warn_unused const_row_iterator operator++(int); inline arma_hot const_row_iterator& operator--(); inline arma_warn_unused const_row_iterator operator--(int); uword internal_row; // Hold row internally because we use internal_pos differently. uword actual_pos; // Actual position in subview's parent matrix. arma_inline eT operator*() const { return iterator_base::M->m.values[actual_pos]; } arma_inline uword row() const { return internal_row; } inline arma_hot bool operator!=(const const_iterator& rhs) const; inline arma_hot bool operator==(const const_iterator& rhs) const; inline arma_hot bool operator!=(const typename SpMat<eT>::const_iterator& rhs) const; inline arma_hot bool operator==(const typename SpMat<eT>::const_iterator& rhs) const; inline arma_hot bool operator!=(const const_row_iterator& rhs) const; inline arma_hot bool operator==(const const_row_iterator& rhs) const; inline arma_hot bool operator!=(const typename SpMat<eT>::const_row_iterator& rhs) const; inline arma_hot bool operator==(const typename SpMat<eT>::const_row_iterator& rhs) const; }; class row_iterator : public const_row_iterator { public: inline row_iterator(SpSubview& in_M, uword initial_pos = 0) : const_row_iterator(in_M, initial_pos) { } inline row_iterator(SpSubview& in_M, uword in_row, uword in_col) : const_row_iterator(in_M, in_row, in_col) { } inline row_iterator(const row_iterator& other) : const_row_iterator(other) { } inline arma_hot SpValProxy< SpSubview<eT> > operator*(); // overloads needed for return type correctness inline arma_hot row_iterator& operator++(); inline arma_warn_unused row_iterator operator++(int); inline arma_hot row_iterator& operator--(); inline arma_warn_unused row_iterator operator--(int); // This has a different value_type than iterator_base. typedef SpValProxy< SpSubview<eT> > value_type; typedef const SpValProxy< SpSubview<eT> >* pointer; typedef const SpValProxy< SpSubview<eT> >& reference; }; inline iterator begin(); inline const_iterator begin() const; inline const_iterator cbegin() const; inline iterator begin_col(const uword col_num); inline const_iterator begin_col(const uword col_num) const; inline row_iterator begin_row(const uword row_num = 0); inline const_row_iterator begin_row(const uword row_num = 0) const; inline iterator end(); inline const_iterator end() const; inline const_iterator cend() const; inline row_iterator end_row(); inline const_row_iterator end_row() const; inline row_iterator end_row(const uword row_num); inline const_row_iterator end_row(const uword row_num) const; //! don't use this unless you're writing internal Armadillo code arma_inline bool is_alias(const SpMat<eT>& X) const; private: friend class SpMat<eT>; friend class SpSubview_col<eT>; friend class SpSubview_row<eT>; friend class SpValProxy< SpSubview<eT> >; // allow SpValProxy to call insert_element() and delete_element() inline arma_warn_unused eT& insert_element(const uword in_row, const uword in_col, const eT in_val = eT(0)); inline void delete_element(const uword in_row, const uword in_col); inline void invalidate_cache() const; }; template<typename eT> class SpSubview_col : public SpSubview<eT> { public: typedef eT elem_type; typedef typename get_pod_type<elem_type>::result pod_type; static constexpr bool is_row = false; static constexpr bool is_col = true; static constexpr bool is_xvec = false; inline void operator= (const SpSubview<eT>& x); inline void operator= (const SpSubview_col& x); template<typename T1> inline void operator= (const SpBase<eT,T1>& x); template<typename T1> inline void operator= (const Base<eT,T1>& x); inline arma_warn_unused const SpOp<SpSubview_col<eT>,spop_htrans> t() const; inline arma_warn_unused const SpOp<SpSubview_col<eT>,spop_htrans> ht() const; inline arma_warn_unused const SpOp<SpSubview_col<eT>,spop_strans> st() const; protected: inline SpSubview_col(const SpMat<eT>& in_m, const uword in_col); inline SpSubview_col(const SpMat<eT>& in_m, const uword in_col, const uword in_row1, const uword in_n_rows); inline SpSubview_col() = delete; private: friend class SpMat<eT>; friend class SpSubview<eT>; }; template<typename eT> class SpSubview_row : public SpSubview<eT> { public: typedef eT elem_type; typedef typename get_pod_type<elem_type>::result pod_type; static constexpr bool is_row = true; static constexpr bool is_col = false; static constexpr bool is_xvec = false; inline void operator= (const SpSubview<eT>& x); inline void operator= (const SpSubview_row& x); template<typename T1> inline void operator= (const SpBase<eT,T1>& x); template<typename T1> inline void operator= (const Base<eT,T1>& x); inline arma_warn_unused const SpOp<SpSubview_row<eT>,spop_htrans> t() const; inline arma_warn_unused const SpOp<SpSubview_row<eT>,spop_htrans> ht() const; inline arma_warn_unused const SpOp<SpSubview_row<eT>,spop_strans> st() const; protected: inline SpSubview_row(const SpMat<eT>& in_m, const uword in_row); inline SpSubview_row(const SpMat<eT>& in_m, const uword in_row, const uword in_col1, const uword in_n_cols); inline SpSubview_row() = delete; private: friend class SpMat<eT>; friend class SpSubview<eT>; }; //! @}
7cfc45021a724317da657abe8afd3a8b7e10861f
63053b31a0293533907420e9a198e709596c0c7b
/Source/Unix/PlatformProcess.h
c1028be4002f86309beff0cefa18b7d37ce7377c
[ "MIT" ]
permissive
Alprog/GitTern
44e48646a640fd36cbd8b319d09840af5622d569
498c81de9081fe409d6c983b1fa961cddcaa3b7f
refs/heads/master
2021-04-29T22:59:37.905478
2019-02-17T19:59:47
2019-02-17T19:59:47
121,545,935
5
0
null
null
null
null
UTF-8
C++
false
false
342
h
PlatformProcess.h
#pragma once #include "Process.h" #include <unistd.h> class UnixProcess : public Process { public: UnixProcess(); ~UnixProcess(); virtual void Run(std::string path, std::string commandLine, std::string directory); virtual void Stop(); virtual bool IsRunning(); pid_t pid; }; using PlatformProcess = UnixProcess;
763fbfaf455d14307141fca5ae17685040ea6b0d
914c61d58282b9e00e8d2426c367eba67512f169
/Projects/Project2/partB/human.h
81563c7b91e18cfe07707331fe75f8a62d62687a
[]
no_license
Zachary-Rust/Zachary-Rust-CSCI-21
ab8d6c7b39cf74f826b70055d91408823051a1b9
23ea9cf0165f2b3d64656526b861575ac37a1fec
refs/heads/master
2021-05-09T20:43:40.145431
2018-05-20T04:27:35
2018-05-20T04:27:35
118,703,609
0
0
null
null
null
null
UTF-8
C++
false
false
448
h
human.h
//Zachary Rust //3/8/18 //Description: This class handles all operations relating to the human player (Sub-Class) #ifndef HUMAN #define HUMAN #include "player.h" #include "gameboard.h" class human: public player { public: human(); human(gameboard b); void MarkBoard(char row, int col, char c); char TakeTurn(char row, int col); bool CheckWin(); void PrintTurn(char r, int c); ~human() {} }; #endif
e61ab1d0b326f96f02e518a31b3272e499828983
64f9af56eec1ba3b09e4dae3cd583b1bb9fef4bb
/Spatial_Filtering/Filter2D.cpp
5302f81e25a9648590ace4ff3fe865350f8026a9
[]
no_license
allisonh32/IPCV
42ea83960d2d69508fc634f6b38462590236e8d9
edc9314959cdab69c77571d71a4face026325815
refs/heads/master
2020-12-21T19:20:53.920913
2020-01-27T16:47:35
2020-01-27T16:47:35
236,533,521
0
0
null
null
null
null
UTF-8
C++
false
false
3,209
cpp
Filter2D.cpp
/** Implementation file for image filtering * * \file ipcv/spatial_filtering/Filter2D.cpp * \author <Allison Hazebouck> (<amh7966>) * \date 10 21 2019 */ #include "Filter2D.h" #include <iostream> using namespace std; namespace ipcv { /** Correlates an image with the provided kernel * * \param[in] src source cv::Mat of CV_8UC3 * \param[out] dst destination cv::Mat of ddepth type * \param[in] ddepth desired depth of the destination image * \param[in] kernel convolution kernel (or rather a correlation * kernel), a single-channel floating point matrix * \param[in] anchor anchor of the kernel that indicates the relative * position of a filtered point within the kernel; * the anchor should lie within the kernel; default * value (-1,-1) means that the anchor is at the * kernel center * \param[in] delta optional value added to the filtered pixels * before storing them in dst * \param[in] border_mode pixel extrapolation method * \param[in] border_value value to use for constant border mode */ bool Filter2D(const cv::Mat& src, cv::Mat& dst, const int ddepth, const cv::Mat& kernel, const cv::Point anchor, const int delta, const BorderMode border_mode, const uint8_t border_value) { // create destination matrix dst.create(src.rows, src.cols, CV_8UC3); // initialize variables int kernel_sum_r, kernel_sum_g, kernel_sum_b; int offset = kernel.rows / 2; int rows, cols, kr, kc, src_rows, src_cols; //loop through rows and cols of source and kernel for (rows = offset; rows < src.rows-offset; rows++) { for (cols = offset; cols < src.cols-offset; cols++) { kernel_sum_r = 0; kernel_sum_g = 0; kernel_sum_b = 0; for (kr = 0; kr < kernel.rows; kr++) { for (kc = 0; kc < kernel.cols; kc++) { //sum multiplications at all points of kernel src_rows = rows + kr - offset; src_cols = cols + kc - offset; kernel_sum_r += kernel.at<float>(kr, kc) * src.at<cv::Vec3b>(src_rows, src_cols)[0]; kernel_sum_g += kernel.at<float>(kr, kc) * src.at<cv::Vec3b>(src_rows, src_cols)[1]; kernel_sum_b += kernel.at<float>(kr, kc) * src.at<cv::Vec3b>(src_rows, src_cols)[2]; } } //clip and crush as needed if (kernel_sum_r < 0) { kernel_sum_r = 0; } else if (kernel_sum_r > 255) { kernel_sum_r = 255; } if (kernel_sum_g < 0) { kernel_sum_g = 0; } else if (kernel_sum_g > 255) { kernel_sum_g = 255; } if (kernel_sum_b < 0) { kernel_sum_b = 0; } else if (kernel_sum_b > 255) { kernel_sum_b = 255; } //put summed values into destination mat dst.at<cv::Vec3b>(rows, cols)[0] = kernel_sum_r + delta; dst.at<cv::Vec3b>(rows, cols)[1] = kernel_sum_g + delta; dst.at<cv::Vec3b>(rows, cols)[2] = kernel_sum_b + delta; } } return true; } }
55c8acc1166fe51bb3782820f781c7b4bbd9d87c
a871415fe39f81e55851346d5ef7ad4823ac7d28
/include/hamls/TSeparatorTree.hh
43d400f815538757fcd9191d2cd09bbe35bd222f
[ "MIT" ]
permissive
PeterGerds/HAMLS
18892e5bc30a75a28ff37d3ad439a65d691f236c
6531765a364b44c02e3763b5d3283fdde980b2f2
refs/heads/master
2020-08-03T06:46:10.460169
2019-11-14T07:40:59
2019-11-14T07:40:59
211,658,319
0
0
null
null
null
null
UTF-8
C++
false
false
5,908
hh
TSeparatorTree.hh
#ifndef __HAMLS_TSEPARATORTREE_HH #define __HAMLS_TSEPARATORTREE_HH //---------------------------------------------------------------------------------------------- // This file is part of the HAMLS software. // // MIT License // // Copyright (c) 2019 Peter Gerds // // 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. //---------------------------------------------------------------------------------------------- // Project : HAMLS // File : TSeparatorTree.hh // Description : This class represents the so called 'separator tree' which is used in the // implementation of the AMLS algorithm by [Gao et al.]. Each node in this tree // represents a subproblem of the AMLS algorithm which is here identified by an // index. The descendant and ancestor relations between the nodes in the separator // tree are modelling the dependencies between the subproblems in the AMLS algorithm. // Author : Peter Gerds // Copyright : Peter Gerds, 2019. All Rights Reserved. #include <vector> #include <map> #include "cluster/TCluster.hh" #include "cluster/TNodeSet.hh" #include "cluster/TClusterTree.hh" namespace HAMLS { using namespace HLIB; //! //! \ingroup HAMLS_Module //! \class TSeparatorTree //! \brief class modelling the 'Separator Tree' //! class TSeparatorTree { public: // This datatype describes the associated ancestor set associated to a cluster typedef std::pair< const TCluster *, TIndexSet > cluster_idxset_t; // This datatype allows an efficient access to a the ancestor set of an given cluster typedef std::map< TIndexSet, cluster_idxset_t, TIndexSet::map_cmp_t > cluster_idxset_map_t; private: //! auxiliary array containing all the information which are necessary to //! derive the ancestor and descendant relation between the subproblems std::vector< cluster_idxset_t > _data; //! array containing the ancestor sets of each subproblem std::vector< TNodeSet > _ancestor_set; //! array containing the descendant sets of each subproblem std::vector< TNodeSet > _descendant_set; //! array containing information if the eigensolution associated to the subproblem is exact std::vector< bool > _exact; public: /////////////////////////////////////////////// // // constructor and destructor // //! construct empty TSeparatorTree TSeparatorTree () {} //! construct TSeparatorTree from the cluster \a root_amls_ct representing //! the domain substructuring applied in AMLS //! Note: Existence of the separator tree depends on existence of \a root_amls_ct, //! i.e., do not delete \a root_amls_ct before deleting the separator tree TSeparatorTree ( const TCluster * root_amls_ct ); //! dtor virtual ~TSeparatorTree () {} //////////////////////////////////////////////////////// // // misc. methods // //! Return the number of subproblems in the AMLS algorithm size_t n_subproblems () const { return _data.size(); } //! Return the number of domain subproblems in the AMLS algorithm size_t n_domain_subproblems () const; //! Return the number of interface subproblems in the AMLS algorithm size_t n_interface_subproblems () const; //! Return the depth of the Separator Tree size_t depth () const; //! Return the 'degrees of freedom' belonging to the subproblem \a i TIndexSet get_dof_is ( const idx_t i ) const; //! Return true if the subproblem \a i is an descendant of the subproblem \a j bool is_descendant ( const idx_t i, const idx_t j ) const; //! Return true if the subproblem \a i represents a 'domain' problem bool is_domain ( const idx_t i ) const; //! Return true if the indexset \a is represents a subdomain or an interface problem bool is_subproblem ( const TIndexSet is ) const; //! Return true if the matrix block associated to the indices \a i and \a j is zero bool matrix_block_is_zero ( const idx_t i, const idx_t j ) const; //! Return true if the eigensolution associated to the subproblem with index \a i is exact bool has_exact_eigensolution ( const idx_t i ) const { return _exact[i]; } //! Set true if the eigensolution associated to the subproblem //! with index \a i is exact otherwise set false void set_exact_eigensolution ( const idx_t i, const bool is_exact) { _exact[i] = is_exact; } //! Get the index of the subproblem which is associated with the index set \a is idx_t get_index ( const TIndexSet is ) const; }; }// namespace HAMLS #endif // __HAMLS_TSEPARATORTREE_HH
200163b93b2afd16ea758fcd77cc93a43909b616
83e80c6e94013f93e8bd116570f66d4c8b7d5582
/src/src/io/read_multilayer_network.cpp
183599931ebdef84c03aa334590b51bff7cf3bd7
[]
no_license
cran/multinet
3c049047487484ff988ae0457ef8c1b8681ac02f
8693584b3359e335df0199137203b578c7ecf86c
refs/heads/master
2023-02-26T05:49:52.698760
2023-02-14T09:20:03
2023-02-14T09:20:03
79,171,174
5
5
null
null
null
null
UTF-8
C++
false
false
9,692
cpp
read_multilayer_network.cpp
#include "core/exceptions/DuplicateElementException.hpp" #include "core/exceptions/WrongFormatException.hpp" #include "core/exceptions/assert_not_null.hpp" #include "io/read_multilayer_network.hpp" #include "io/read_network.hpp" #include <sstream> namespace uu { namespace net { std::unique_ptr<MultilayerNetwork> read_multilayer_network( const std::string& infile, const std::string& name, char separator, bool align ) { // Read metadata MultilayerMetadata meta = read_multilayer_metadata(infile, ','); //EdgeDir dir = meta.features.is_directed?EdgeDir::DIRECTED:EdgeDir::UNDIRECTED; // Check metadata consistency (@todo) & create graph & add attributes auto net = std::make_unique<MultilayerNetwork>(name); for (auto l: meta.layers) { std::string layer_name = l.first; auto layer_type = l.second; //std::cout << "creating layer " << l.first << " " << layer_type.is_directed << std::endl; auto dir = layer_type.is_directed ? EdgeDir::DIRECTED : EdgeDir::UNDIRECTED; auto loops = layer_type.allows_loops ? LoopMode::ALLOWED : LoopMode::DISALLOWED; net->layers()->add(layer_name, dir, loops); } for (auto inter: meta.interlayer_dir) { std::string layer_name1 = inter.first.first; std::string layer_name2 = inter.first.second; auto layer1 = net->layers()->get(layer_name1); if (!layer1) { throw core::WrongFormatException("unknown layer name (" + layer_name1 + ")"); } auto layer2 = net->layers()->get(layer_name2); if (!layer2) { throw core::WrongFormatException("unknown layer name (" + layer_name2 + ")"); } auto dir = inter.second ? EdgeDir::DIRECTED : EdgeDir::UNDIRECTED; net->interlayer_edges()->init(layer1, layer2, dir); } for (auto&& attr: meta.vertex_attributes) { net->actors()->attr()->add(attr.name, attr.type); } for (auto layer_attr: meta.intralayer_vertex_attributes) { std::string layer_name = layer_attr.first; for (auto&& attr: layer_attr.second) { net->layers()->get(layer_name)->vertices()->attr()->add(attr.name, attr.type); } } for (auto layer_attr: meta.intralayer_edge_attributes) { std::string layer_name = layer_attr.first; for (auto&& attr: layer_attr.second) { bool res = net->layers()->get(layer_name)->edges()->attr()->add(attr.name, attr.type); if (!res) { throw core::DuplicateElementException("edge attribute " + attr.name); } } } for (auto&& attr: meta.interlayer_edge_attributes) { for (auto l1: *net->layers()) { for (auto l2: *net->layers()) { auto iedges = net->interlayer_edges()->get(l1,l2); if (!iedges) continue; bool res = iedges->attr()->add(attr.name, attr.type); if (!res) { throw core::DuplicateElementException("edge attribute " + attr.name); } } } } // Read data (vertices, edges, attribute value(s)) read_multilayer_data(net.get(), meta, infile, separator); read_actor_attributes(net.get(), meta, infile, separator); // Align if (align) { for (auto layer: *net->layers()) { for (auto a: *net->actors()) { layer->vertices()->add(a); } } } return net; } template <> Network* read_layer( MultilayerNetwork* ml, const std::vector<std::string>& fields, size_t from_idx, size_t line_number ) { (void)line_number; // param not used std::string layer_name = fields.at(from_idx); auto layer = ml->layers()->get(layer_name); if (!layer) { layer = ml->layers()->add(layer_name, uu::net::EdgeDir::UNDIRECTED); } return layer; } template <> void read_actor( MultilayerNetwork* ml, const std::vector<std::string>& fields, const MultilayerMetadata& meta, size_t line_number ) { core::assert_not_null(ml, "read_vertex", "ml"); size_t num_attrs = meta.vertex_attributes.size(); if (fields.size() != 1 + num_attrs) { std::stringstream ss; ss << "[line " << line_number << "] actor name and " << num_attrs << " attribute value(s) expected"; throw core::WrongFormatException(ss.str()); } std::string actor_name = fields.at(0); auto actor = ml->actors()->get(actor_name); if (!actor) { throw core::ElementNotFoundException("actor " + actor_name + " must exist in at least one layer"); } read_attr_values(ml->actors()->attr(), actor, meta.vertex_attributes, fields, 1, line_number); } template <> void read_intralayer_vertex( MultilayerNetwork* ml, const std::vector<std::string>& fields, const MultilayerMetadata& meta, size_t line_number ) { core::assert_not_null(ml, "read_intralayer_vertex", "ml"); if (fields.size() < 2) { std::stringstream ss; ss << "[line " << line_number << "] actor name and layer name expected"; throw core::WrongFormatException(ss.str()); } auto l = read_layer<MultilayerNetwork, Network>(ml, fields, 1, line_number); auto v = read_actor(ml, l, fields, 0, line_number); auto v_attr = meta.intralayer_vertex_attributes.find(l->name); if (v_attr != meta.intralayer_vertex_attributes.end()) { size_t num_attrs = v_attr->second.size(); if (fields.size() != 2 + num_attrs) { std::stringstream ss; ss << "[line " << line_number << "] actor name, layer name and " << num_attrs << " attribute value(s) expected"; throw core::WrongFormatException(ss.str()); } read_attr_values(l->vertices()->attr(), v, v_attr->second, fields, 2, line_number); } } template <> void read_intralayer_edge( MultilayerNetwork* ml, const std::vector<std::string>& fields, const MultilayerMetadata& meta, size_t line_number ) { core::assert_not_null(ml, "read_intralayer_edge", "ml"); if (fields.size() < 3) { std::stringstream ss; ss << "[line " << line_number << "] actor1 name, actor2 name and layer name expected"; throw core::WrongFormatException(ss.str()); } auto l = read_layer<MultilayerNetwork, Network>(ml, fields, 2, line_number); auto v1 = read_actor(ml, l, fields, 0, line_number); auto v2 = read_actor(ml, l, fields, 1, line_number); /*if (!meta.layers.at(l.name).allows_loops) if (v1 == v2) { return; } */ auto e = l->edges()->add(v1,v2); auto e_attr = meta.intralayer_edge_attributes.find(l->name); if (e_attr != meta.intralayer_edge_attributes.end()) { size_t num_attrs = e_attr->second.size(); if (fields.size() != 3 + num_attrs) { std::stringstream ss; ss << "[line " << line_number << "] actor1 name, actor2 name, layer name and " << num_attrs << " attribute value(s) expected"; throw core::WrongFormatException(ss.str()); } read_attr_values(l->edges()->attr(), e, e_attr->second, fields, 3, line_number); } } template <> void read_interlayer_edge( MultilayerNetwork* ml, const std::vector<std::string>& fields, const MultilayerMetadata& meta, size_t line_number ) { (void)meta; // param not used core::assert_not_null(ml, "read_interlayer_edge", "ml"); if (fields.size() < 4) { std::stringstream ss; ss << "[line " << line_number << "] actor1 name, layer1 name, actor2 name and layer2 name expected"; throw core::WrongFormatException(ss.str()); } auto l1 = read_layer<MultilayerNetwork, Network>(ml, fields, 1, line_number); auto v1 = read_actor(ml, l1, fields, 0, line_number); auto l2 = read_layer<MultilayerNetwork, Network>(ml, fields, 3, line_number); auto v2 = read_actor(ml, l2, fields, 2, line_number); if (l1==l2) { auto e = l1->edges()->add(v1,v2); auto e_attr = meta.intralayer_edge_attributes.find(l1->name); size_t num_attrs = e_attr->second.size(); if (fields.size() != 4 + num_attrs) { std::stringstream ss; ss << "[line " << line_number << "] actor1 name, layer1 name, actor2 name, layer2 name and " << num_attrs << " attribute value(s) expected"; throw core::WrongFormatException(ss.str()); } if (e_attr != meta.intralayer_edge_attributes.end()) { read_attr_values(l1->edges()->attr(), e, e_attr->second, fields, 4, line_number); } } else { auto e = ml->interlayer_edges()->add(v1,l1,v2,l2); size_t num_attrs = meta.interlayer_edge_attributes.size(); if (fields.size() != 4 + num_attrs) { std::stringstream ss; ss << "[line " << line_number << "] actor1 name, layer1 name, actor2 name, layer2 name and " << num_attrs << " attribute value(s) expected"; throw core::WrongFormatException(ss.str()); } read_attr_values(ml->interlayer_edges()->get(l1,l2)->attr(), e, meta.interlayer_edge_attributes, fields, 4, line_number); } } } }
e70f662fef278e070716cc222b45b358ee6bb41d
9fdb16f3d1cdb24f75024088383d3cb0d8744f3d
/ChaseTagAI/Source/Astar/AstarNode.h
e4825fe20f9eb7f4e70d7af82eb606be4b5c044c
[]
no_license
whitephenix13/ChaseTagAI
1b096c5ba3b274746f2e8d5b20998f35a6fafedc
f809762c008559061c1c31f9ea4f03de13220474
refs/heads/master
2023-02-15T21:27:00.630067
2021-01-16T18:11:36
2021-01-16T18:11:36
285,898,945
0
0
null
null
null
null
UTF-8
C++
false
false
431
h
AstarNode.h
#pragma once #include <utility> class AstarNode { public: std::pair<int, int> cellIndex; float totalCost; AstarNode(); AstarNode(const AstarNode& copy); AstarNode(std::pair<int,int> cellIndex); // the top of the priority queue is the greatest element by default, // but we want the smallest, so flip the sign bool operator < (const AstarNode&); ~AstarNode(); };
e61bde32bbd1bcc2c4c8ae407ddf7aefb69fbc29
30549c5d42f41d3423178d802f6791fb28875fbd
/src/utils/shared_structs.hpp
d3f6f529a9a0d896cbab723295e000504dc614b2
[ "MIT" ]
permissive
new2f7/RayTracing
7d4cdf96616aacacab1e63262c861e8e62b0e421
609b230c68f2129f53fd3c85b479b947dce39949
refs/heads/master
2021-07-09T09:41:16.075302
2021-03-20T11:13:44
2021-03-20T11:13:44
235,313,525
1
0
null
2020-02-10T13:23:14
2020-01-21T10:15:16
C++
UTF-8
C++
false
false
2,255
hpp
shared_structs.hpp
#ifndef TRIANGLE_HPP #define TRIANGLE_HPP #ifdef __cplusplus #include "mathlib/mathlib.hpp" #include <CL/cl.h> #include <algorithm> #endif #define MATERIAL_BLINN 1 #define MATERIAL_METAL 2 #define MATERIAL_ORENNAYAR 4 #define MATERIAL_PHONG 5 #ifndef __cplusplus typedef struct { float3 pos[2]; } Bounds3; #endif typedef struct Material { #ifdef __cplusplus Material() {} #endif float3 diffuse; float3 specular; float3 emission; unsigned int type; float roughness; float ior; int padding; } Material; typedef struct Vertex { #ifdef __cplusplus Vertex() {} Vertex(const float3& position, const float2& texcoord, const float3& normal) : position(position), texcoord(texcoord.x, texcoord.y, 0), normal(normal) {} #endif float3 position; float3 texcoord; float3 normal; float3 tangent_s; } Vertex; typedef struct Triangle { #ifdef __cplusplus Triangle(Vertex v1, Vertex v2, Vertex v3, unsigned int mtlIndex) : v1(v1), v2(v2), v3(v3), mtlIndex(mtlIndex) {} void Project(float3 axis, float &min, float &max) const { min = std::numeric_limits<float>::max(); max = std::numeric_limits<float>::lowest(); float3 points[3] = { v1.position, v2.position, v3.position }; for (size_t i = 0; i < 3; ++i) { float val = Dot(points[i], axis); min = std::min(min, val); max = std::max(max, val); } } Bounds3 GetBounds() const { return Union(Bounds3(v1.position, v2.position), v3.position); } #endif Vertex v1, v2, v3; unsigned int mtlIndex; unsigned int padding[3]; } Triangle; typedef struct CellData { unsigned int start_index; unsigned int count; } CellData; typedef struct LinearBVHNode { #ifdef __cplusplus LinearBVHNode() {} #endif // 32 bytes Bounds3 bounds; // 4 bytes unsigned int offset; // primitives (leaf) or second child (interior) offset // 2 bytes unsigned short nPrimitives; // 0 -> interior node // 1 byte unsigned char axis; // interior node: xyz unsigned char pad[9]; // ensure 48 byte total size } LinearBVHNode; #endif // TRIANGLE_HPP
93f1338c1a20678583b4b189b7214703a30e2012
8751901f535ca551df4299022e964f71ac3848d2
/c++/LeetCode/LeetCode/CountBinarySubstrings.cpp
f8e2baaff4ed4ab2eae82d2707062234cef70613
[]
no_license
iorinie/LeetCode
af97154229e085156459107090982118d438a37b
666e59e92385a4b78d5f864885407196ecd6126a
refs/heads/master
2023-01-13T18:18:02.535492
2020-11-20T09:45:29
2020-11-20T09:45:29
263,205,449
1
0
null
null
null
null
UTF-8
C++
false
false
2,651
cpp
CountBinarySubstrings.cpp
#include "CountBinarySubstrings.h" /* 题目描述: 给定一个字符串 s,计算具有相同数量0和1的非空(连续)子字符串的数量,并且这些子字符串中的所有0和所有1都是组合在一起的。 重复出现的子串要计算它们出现的次数。 示例1: 输入: "00110011" 输出: 6 解释: 有6个子串具有相同数量的连续1和0:“0011”,“01”,“1100”,“10”,“0011” 和 “01”。 请注意,一些重复出现的子串要计算它们出现的次数。 另外,“00110011”不是有效的子串,因为所有的0(和1)没有组合在一起。 示例2: 输入: "10101" 输出: 4 解释: 有4个子串:“10”,“01”,“10”,“01”,它们具有相同数量的连续1和0。 注意: 1. s.length 在1到50,000之间。 2. s 只包含“0”或“1”字符。 */ /* 解法2:记录所有相同数的长度,依次比较取较小值累加 缺点: 知识点: 1. */ int countBinarySubstrings(string s) { int rslt = 0; if (s.size() <= 1) { return rslt; } int last = 0, cur = 1; //不论当前数字是啥,当前相同的数量都为1 for (int i = 1; i < s.size(); i++) { if (s[i] == s[i - 1]) { cur++; } else { if (last != 0) { rslt += cur < last ? cur : last; } last = cur; cur = 1; } } rslt += cur < last ? cur : last; return rslt; } /* 解法1:双指针,左指针指向相同数的起始位置,右指针指向结尾位置,从右指针往后,找不同数的个数 缺点:有大量的重复操作,时间复杂度太高 知识点: 1. */ //int countBinarySubstrings(string s) { // int rslt = 0; // if (s.size() <= 1) { // return rslt; // } // // int left = 0, right = 1; // while (right < s.size()) { // if (s[left] == s[right] && right + 1 < s.size()) { // right++; // } // else { // if (s[left] == s[right]) { //相等说明right过界了 // break; // } // else { // int offset = 0; // while (right + offset < s.size() && offset < right - left && s[right + offset] != s[left]) { // rslt++; // offset++; // } // left = right; // right++; // } // } // } // // return rslt; //}
f7f8c45afd2eb1fab20a80e266285151a66aa3de
5027897d89efd1d698b2287283fb0fc8288c1ef4
/Leetcode/LinkedList/707.DesignLinkedList/solution.h
4d89e0516391edf43f4bef81c6a626e2aec74c8f
[]
no_license
meteora211/SelfLearning
99adea31682370b07f69f407bcd019dea3d5a489
f6cf3753c5aa7e9a187575385eff315582cfdcaf
refs/heads/master
2023-06-24T15:21:09.984079
2023-06-16T15:15:39
2023-06-16T15:15:39
138,721,097
1
0
null
null
null
null
UTF-8
C++
false
false
3,149
h
solution.h
class MyLinkedList { private: struct ListNode{ int val; ListNode* prev; ListNode* next; ListNode(){}; ListNode(int e, ListNode* p, ListNode* s):val(e),prev(p),next(s){}; }; ListNode* header = new ListNode(); ListNode* tailer = new ListNode(); int _size; public: /** Initialize your data structure here. */ MyLinkedList() { _size = 0; header -> next = tailer; tailer -> prev = header; header -> prev = NULL; tailer -> next = NULL; } /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */ int get(int index) { ListNode* p = header; while(index-- >= 0) { if(tailer == (p = p -> next)) return -1; } return p->val; } /** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */ void addAtHead(int val) { ListNode* p = new ListNode(); p -> val = val; p -> next = header -> next; p -> prev = header; header -> next -> prev = p; header -> next = p; _size ++; } /** Append a node of value val to the last element of the linked list. */ void addAtTail(int val) { ListNode* p = new ListNode(); p -> val = val; p -> prev = tailer -> prev; p -> next = tailer; tailer -> prev -> next = p; tailer -> prev = p; _size ++; } /** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */ void addAtIndex(int index, int val) { if(index < 0 || index > _size) return; ListNode* p = new ListNode(); ListNode* cur = header; while(tailer != cur && index >= 0) { cur = cur -> next; index --; } if(index >= 0) { return; } else { p -> val = val; p-> next = cur; p -> prev = cur -> prev; cur -> prev -> next = p; cur -> prev = p; } _size ++; } /** Delete the index-th node in the linked list, if the index is valid. */ void deleteAtIndex(int index) { if(index < 0 || index > _size) return; ListNode* cur = header; while(tailer != cur && index>= 0) { cur = cur -> next; index --; } if(index >= 0 || cur == tailer) { return; } else { cur -> next -> prev = cur -> prev; cur -> prev -> next = cur -> next; delete cur; } _size --; } }; /** * Your MyLinkedList object will be instantiated and called as such: * MyLinkedList obj = new MyLinkedList(); * int param_1 = obj.get(index); * obj.addAtHead(val); * obj.addAtTail(val); * obj.addAtIndex(index,val); * obj.deleteAtIndex(index); */
1ce1e5dbc5786c5412dbf7160d59ae391bd0311d
751ea79faabf3d0ba4679ccfb4758aa6e88ef54c
/oop12/main.cpp
d76413b1d7412d5efae7dcf9e18c1e9588b39e86
[]
no_license
aabriti58/oop
66dd35c6cb8c740fa53fccd3feb6539f0531b2a1
bfdcde58ab49b415079cf8b1444225ae1a3dd295
refs/heads/main
2023-03-15T03:22:48.879754
2021-03-14T11:31:16
2021-03-14T11:31:16
347,614,415
0
0
null
null
null
null
UTF-8
C++
false
false
2,189
cpp
main.cpp
/*Binary operator #include <iostream> #include<math.h> using namespace std; class A{ public: float a; float b; float c; }ft,inch,total; int main() { int i; int d; cout<<"enter ft1:"<<endl; cin>>ft.a; cout<<"enter ft2:"<<endl; cin>>ft.b; cout<<"enter inch1:"<<endl; cin>>inch.a; cout<<"enter inch2:"<<endl; cin>>inch.b; ft.c= ft.a+ ft.b; inch.c= inch.a+ inch.b; d=floor(inch.c/12); for(i=0;i>d;i++) { inch.c=d; ft.c=ft.c+d; } cout<<"total distance: "<<ft.c<<"ft"<<inch.c<<"inch"<<endl; }*/ /*//same as above but different method #include<iostream> using namespace std; class Distance{ private: int feet; float inches; public: Distance():feet(0),inches(0.0){} Distance(int ft,float in):feet(ft),inches(in){} void getdist(){ cout<<"\nEnter feet: "; cin>>feet; cout<<"\nEnter inches: "; cin>>inches; } void showdist() const{ cout<<feet<<"\'"<<inches<<"\'"; } Distance operator + (Distance d2) const{ int f = feet + d2.feet; float i = inches + d2.inches; if(i>=12.0){ i -= 12.0; f++; } return Distance(f,i); } }; int main(){ Distance dist1,dist3; dist1.getdist(); Distance dist2; dist2.getdist(); Distance dist4; dist3 = dist1 + dist2; dist4 = dist1 + dist2 + dist3; cout<<"Dist1="; dist1.showdist(); cout<<endl; cout<<"Dist2="; dist2.showdist(); cout<<endl; cout<<"Dist3="; dist3.showdist(); cout<<endl; cout<<"Dist4="; dist4.showdist(); cout<<endl; return 0; }*/ #include <iostream> using namespace std; class concat{ private: string s; public: concat():s("s"){} concat(string n):s(n){} void getdata(){ cout<<"enter s1: "; cin>>s; } void showdata() const{ cout<<s<<" "; } concat operator + (concat c) const{ string s1 = s + " " + c.s; return concat(s1); } }; int main(){ concat a,b,c; a.getdata(); b.getdata(); c = a+b; cout<<"a="; a.showdata(); cout<<endl; cout<<"b="; b.showdata(); cout<<endl; cout<<"c="; c.showdata(); cout<<endl; }
72b8931f916b25624597ac1cc1a23f04acdf29d2
065b619484cf0b32d6bf6c35d48a0a09505c1406
/分类题目/算法竞赛入门经典/Ch4--函数和递归/Uva1339/Uva1339-pro.cpp
80ce4a08d4913a7ad9f705b096473d07ee4ff9c3
[]
no_license
shanPic/CodeOfAcm
8683caf552dbaebae19bb9c6d0816db8356eef43
67ea5ba1695035669f15dbccc88d36ddd1abca54
refs/heads/master
2021-07-10T09:14:02.500346
2017-10-11T15:55:18
2017-10-11T15:55:18
106,294,149
0
0
null
null
null
null
UTF-8
C++
false
false
655
cpp
Uva1339-pro.cpp
#include<bits/stdc++.h> using namespace std; int main() { int set1[30],set2[30]; char str1[110],str2[110]; bool flag; while(scanf("%s%s",str1,str2)==2){ memset(set1,0,sizeof(set1)); memset(set2,0,sizeof(set2)); for(int i=0;i<strlen(str1);i++){ set1[str1[i]-'A']++; set2[str2[i]-'A']++; } sort(set1,set1+26); sort(set2,set2+26); flag=1; for(int i=0;i<26;i++){ if(set1[i]!=set2[i]){ flag=0; break; } } if(flag) cout<<"YES"<<endl; else cout<<"NO"<<endl; } }
17613143be44b45fe29289703a26bc666a04bfde
8178161f4eabf12eae1b0e099eac9e8bc4df1bbe
/simulation client/SimulationLoop/TCP_sender.h
afe26883c1aa79ac7ac8c13e9c6ec2d24150f594
[]
no_license
AlexKLM/Physics-sim-and-concurrency
367f1820e6d0049f07f9b733d72685fea9d77256
16218695242a879f8d064e77d2a35184298464e1
refs/heads/master
2020-05-17T17:32:11.166574
2013-07-24T10:33:48
2013-07-24T10:33:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
735
h
TCP_sender.h
#pragma once #include <iostream> #include <winsock2.h> #include <process.h> #include<Windows.h> #include <string> #include <vector> #include <sstream> #include "shared_memory.h" #include "shared_struct.h" class TCP_sender { private: HANDLE thread; SOCKET send_socket; sockaddr_in server_addr; bool ready; int run(); public: bool isready();//ready to send; void setready(bool input); void start(); bool send(string msg); bool setup(sockaddr_in address); void close(); void set_address(sockaddr_in address); TCP_sender(sockaddr_in address); TCP_sender(void); ~TCP_sender(void); static unsigned __stdcall threadFunc(void *param) { if (param) return ((TCP_sender*)param)->run(); return 1; // Return error } };
05e642e2eb46ea1034155e34ec9a6fff6fa26472
7d010c8ac4751fcfc6b3b6d638a69dcdad14d87b
/Codeforces_ChoosingTeams.cpp
9c0c2fb64b73a01a4c987caf362486bd0a93c48f
[]
no_license
JoyCmollik/CodeforcesSolvedProblems
23e925c2a3d88f9b17e5ad6a5d96c9498a16282b
43a7ddfe0fc5c8e236c3e288ab74a4327c1ddb33
refs/heads/master
2023-05-30T16:42:19.759150
2021-06-09T06:31:11
2021-06-09T06:31:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
263
cpp
Codeforces_ChoosingTeams.cpp
#include <bits/stdc++.h> using namespace std; typedef unsigned long long int ulli; int main() { int n, k; cin >> n >> k; int members = 0; while (n--) { int y; cin >> y; if (5 - y >= k) members++; } cout << members / 3 << endl; return 0; }
4ad6cab23ac219879c7c453599140d82b88fc1ff
e76ea38dbe5774fccaf14e1a0090d9275cdaee08
/src/chrome/browser/bookmarks/bookmark_tag_model.h
b30e565cc37d53aef5ab38cac7eecc113a9d8087
[ "BSD-3-Clause" ]
permissive
eurogiciel-oss/Tizen_Crosswalk
efc424807a5434df1d5c9e8ed51364974643707d
a68aed6e29bd157c95564e7af2e3a26191813e51
refs/heads/master
2021-01-18T19:19:04.527505
2014-02-06T13:43:21
2014-02-06T13:43:21
16,070,101
1
3
null
null
null
null
UTF-8
C++
false
false
9,504
h
bookmark_tag_model.h
// 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. #ifndef CHROME_BROWSER_BOOKMARKS_BOOKMARK_TAG_MODEL_H_ #define CHROME_BROWSER_BOOKMARKS_BOOKMARK_TAG_MODEL_H_ #include "chrome/browser/bookmarks/bookmark_model.h" #include "chrome/browser/bookmarks/bookmark_model_observer.h" class BookmarkTagModelObserver; typedef string16 BookmarkTag; // BookmarTagModel provides a way to access and manipulate bookmarks in a // non-hierarchical way. BookmarkTagModel view the bookmarks as a flat list, // and each one can be marked with a collection of tags (tags are simply // strings). // // BookmarkTagModel converts on demand the data from an existing BookmarkModel // to its view of the world by considering all the titles of all the ancestors // as tags. This view is frozen on an individual bookmarks when the // BookmarkTagModel performs a change on the tags of this bookmarks. // // The Bookmark's meta info is used for storage. // // An observer may be attached to a BookmarkTagModel to observe relevant events. // // TODO(noyau): The meta info data is not preserved by copy/paste or drag and // drop, this means that bookmarks will loose their tag information if // manipulated that way. // class BookmarkTagModel : public BookmarkModelObserver { public: explicit BookmarkTagModel(BookmarkModel* bookmark_model); virtual ~BookmarkTagModel(); // Returns true if the model finished loading. bool loaded() const { return loaded_; } // Add and remove observers on this object. void AddObserver(BookmarkTagModelObserver* observer); void RemoveObserver(BookmarkTagModelObserver* observer); // Brackets an extensive set of changes, such as during import or sync, so // observers can delay any expensive UI updates until it's finished. class ExtensiveChanges { public: friend class BookmarkTagModel; explicit ExtensiveChanges(BookmarkTagModel* model) : model_(model) { model_->BeginExtensiveChanges(); } private: ~ExtensiveChanges() { model_->EndExtensiveChanges(); } BookmarkTagModel* model_; }; // Returns true if this bookmark model is currently in a mode where extensive // changes might happen, such as for import and sync. This is helpful for // observers that are created after the mode has started, and want to check // state during their own initializer. bool IsDoingExtensiveChanges() const; // Removes the given |BookmarkNode|. Observers are notified immediately. void Remove(const BookmarkNode* bookmark); // Removes all the bookmark nodes. Observers are only notified when all nodes // have been removed. There is no notification for individual node removals. void RemoveAll(); // Returns the favicon for |node|. If the favicon has not yet been // loaded it is loaded and the observer of the model notified when done. const gfx::Image& GetFavicon(const BookmarkNode* bookmark); // Sets the title of |node|. void SetTitle(const BookmarkNode* bookmark, const string16& title); // Sets the URL of |node|. void SetURL(const BookmarkNode* bookmark, const GURL& url); // Sets the date added time of |node|. void SetDateAdded(const BookmarkNode* bookmark, base::Time date_added); // Returns the most recently added bookmark for the |url|. Returns NULL if // |url| is not bookmarked. const BookmarkNode* GetMostRecentlyAddedBookmarkForURL(const GURL& url); // Creates a new bookmark. const BookmarkNode* AddURL(const string16& title, const GURL& url, const std::set<BookmarkTag>& tags); // Adds the |tags| to the tag list of the |bookmark|. void AddTagsToBookmark(const std::set<BookmarkTag>& tags, const BookmarkNode* bookmark); // Same but to a whole collection of |bookmarks|. void AddTagsToBookmarks(const std::set<BookmarkTag>& tags, const std::set<const BookmarkNode*>& bookmarks); // Remove the |tags| from the tag list of the |bookmark|. If the bookmark // is not tagged with one or more of the tags, these are ignored. void RemoveTagsFromBookmark(const std::set<BookmarkTag>& tags, const BookmarkNode* bookmark); // Same but to a whole collection of |bookmarks|. void RemoveTagsFromBookmarks(const std::set<BookmarkTag>& tags, const std::set<const BookmarkNode*>& bookmarks); // Returns all the tags set on a specific |bookmark|. std::set<BookmarkTag> GetTagsForBookmark(const BookmarkNode* bookmark); // Returns the bookmarks marked with all the given |tags|. std::set<const BookmarkNode*> BookmarksForTags( const std::set<BookmarkTag>& tags); // Returns the bookmarks marked with the given |tag|. std::set<const BookmarkNode*> BookmarksForTag(const BookmarkTag& tag); // Returns all tags related to the parent |tag|. If |tag| is null this method // will returns and sort all tags in the system. A related tag is a tag used // on one or more of the bookmarks tagged with |tag|. The returned tags are // ordered from the most common to the rarest one. std::vector<BookmarkTag> TagsRelatedToTag(const BookmarkTag& tag); // All the BookmarkModelObserver methods. See there for details. virtual void Loaded(BookmarkModel* model, bool ids_reassigned) OVERRIDE; virtual void BookmarkModelBeingDeleted(BookmarkModel* model) OVERRIDE; virtual void BookmarkNodeMoved(BookmarkModel* model, const BookmarkNode* old_parent, int old_index, const BookmarkNode* new_parent, int new_index) OVERRIDE; virtual void BookmarkNodeAdded(BookmarkModel* model, const BookmarkNode* parent, int index) OVERRIDE; virtual void OnWillRemoveBookmarks(BookmarkModel* model, const BookmarkNode* parent, int old_index, const BookmarkNode* node) OVERRIDE; virtual void BookmarkNodeRemoved(BookmarkModel* model, const BookmarkNode* parent, int old_index, const BookmarkNode* node) OVERRIDE; virtual void OnWillChangeBookmarkNode(BookmarkModel* model, const BookmarkNode* node) OVERRIDE; virtual void BookmarkNodeChanged(BookmarkModel* model, const BookmarkNode* node) OVERRIDE; virtual void OnWillChangeBookmarkMetaInfo(BookmarkModel* model, const BookmarkNode* node) OVERRIDE; virtual void BookmarkMetaInfoChanged(BookmarkModel* model, const BookmarkNode* node) OVERRIDE; virtual void BookmarkNodeFaviconChanged(BookmarkModel* model, const BookmarkNode* node) OVERRIDE; virtual void OnWillReorderBookmarkNode(BookmarkModel* model, const BookmarkNode* node) OVERRIDE; virtual void BookmarkNodeChildrenReordered(BookmarkModel* model, const BookmarkNode* node) OVERRIDE; virtual void ExtensiveBookmarkChangesBeginning(BookmarkModel* model) OVERRIDE; virtual void ExtensiveBookmarkChangesEnded(BookmarkModel* model) OVERRIDE; virtual void OnWillRemoveAllBookmarks(BookmarkModel* model) OVERRIDE; virtual void BookmarkAllNodesRemoved(BookmarkModel* model) OVERRIDE; private: // Notifies the observers that an extensive set of changes is about to happen, // such as during import or sync, so they can delay any expensive UI updates // until it's finished. void BeginExtensiveChanges(); void EndExtensiveChanges(); // Encode the tags in a format suitable for the BookmarkNode's metaInfo and // set or replace the value. void SetTagsOnBookmark(const std::set<BookmarkTag>& tags, const BookmarkNode* bookmark); // Build the caches of tag to bookmarks and bookmarks to tag for faster // access to the data. Load() is called from the constructor if possible, or // as soon as possible after that. void Load(); // Discard tag information for all descendants of a given folder node and // rebuild the cache for them. void ReloadDescendants(const BookmarkNode* folder); // Clear the local cache of all mentions of |bookmark|. void RemoveBookmark(const BookmarkNode* bookmark); // Extract the tags from |bookmark| and insert it in the local cache. void LoadBookmark(const BookmarkNode* bookmark); // The model from where the data is permanently stored. BookmarkModel* bookmark_model_; // True if the model is fully loaded. bool loaded_; // The observers. ObserverList<BookmarkTagModelObserver> observers_; // Local cache for quick access. std::map<const BookmarkTag, std::set<const BookmarkNode*> > tag_to_bookmarks_; std::map<const BookmarkNode*, std::set<BookmarkTag> > bookmark_to_tags_; // Set to true during the creation of a new bookmark in order to send only the // proper notification. bool inhibit_change_notifications_; DISALLOW_COPY_AND_ASSIGN(BookmarkTagModel); }; #endif // CHROME_BROWSER_BOOKMARKS_BOOKMARK_TAG_MODEL_H_
36d9061bb70affddc37428edac3ebc8b0a165ada
bb313333858dba1cc34d656f6b667ca21b491378
/src/widgets/windows/HistoryWindow.cpp
d39cee730b56c33ca7749db5df2033a1dbf85a77
[]
no_license
KittyIM/Client
8ac66957173788ab3f1d3898b031fe78b9584d72
4b436b5ac08d671109c936e4cbc0f64515497228
refs/heads/master
2016-09-06T17:49:14.332802
2012-03-18T20:06:06
2012-03-18T20:06:06
1,348,825
0
0
null
null
null
null
UTF-8
C++
false
false
18,989
cpp
HistoryWindow.cpp
#include "HistoryWindow.h" #include "ui_HistoryWindow.h" #include "ProtocolManager.h" #include "AccountManager.h" #include "SettingsWindow.h" #include "ContactManager.h" #include "IconManager.h" #include "Profile.h" #include "Core.h" #include <SDKConstants.h> #include <IContact.h> #include <QtGui/QStandardItemModel> #include <QtGui/QTreeWidgetItem> #include <QtGui/QStandardItem> #include <QtGui/QKeyEvent> #include <QtCore/QFileInfo> #include <QtCore/QDebug> #include <QtCore/QDir> #include <QtSql/QSqlDatabase> #include <QtSql/QSqlError> #include <QtSql/QSqlQuery> #include <QtWebKit/QWebFrame> #define qDebug() qDebug() << "[HistoryWindow]" #define qWarning() qWarning() << "[HistoryWindow]" namespace Kitty { ContactProxy::ContactProxy(QObject *parent): QSortFilterProxyModel(parent) { setDynamicSortFilter(true); setFilterCaseSensitivity(Qt::CaseInsensitive); setSourceModel(new QStandardItemModel()); } bool ContactProxy::filterAcceptsRow(int row, const QModelIndex &parent) const { QModelIndex index = sourceModel()->index(row, 0, parent); //root is always visible if(!parent.isValid()) { return true; } //accounts are only visible if atleast one contact is visible if(sourceModel()->hasChildren(index)) { for(int i = 0; i < sourceModel()->rowCount(index); ++i) { if(QSortFilterProxyModel::filterAcceptsRow(i, index)) { return true; } } return false; } //contact are accepted the usual way return QSortFilterProxyModel::filterAcceptsRow(row, parent); } HistoryWindow::HistoryWindow(Core *core, QWidget *parent): QWidget(parent), m_ui(new Ui::HistoryWindow), m_core(core) { m_ui->setupUi(this); //qDebug() << "Creating"; m_proxy = new ContactProxy(this); m_ui->contactTree->setModel(m_proxy); connect(m_core->iconManager(), SIGNAL(iconsUpdated()), SLOT(updateIcons())); connect(m_core, SIGNAL(settingsApplied()), SLOT(applySettings())); connect(m_ui->contactTree->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), SLOT(loadChats(QItemSelection,QItemSelection))); connect(m_ui->contactSearchEdit, SIGNAL(textChanged(QString)), SLOT(filterContacts(QString))); connect(m_ui->filtersButton, SIGNAL(toggled(bool)), SLOT(toggleFilters(bool))); connect(m_ui->refreshButton, SIGNAL(clicked()), SLOT(refreshChats())); restoreGeometry(m_core->setting(KittySDK::Settings::S_HISTORYWINDOW_GEOMETRY).toByteArray()); m_ui->splitter->restoreState(m_core->setting(KittySDK::Settings::S_HISTORYWINDOW_SPLITTER).toByteArray()); m_ui->chatWebView->setAutoScroll(false); m_ui->dateToEdit->setDate(QDate::currentDate()); m_ui->chatTree->header()->restoreState(m_core->setting(KittySDK::Settings::S_HISTORYWINDOW_COLUMNS, m_ui->chatTree->header()->saveState()).toByteArray()); m_ui->filtersButton->setChecked(m_core->setting(KittySDK::Settings::S_HISTORYWINDOW_FILTERS, false).toBool()); applySettings(); updateIcons(); QTimer::singleShot(0, this, SLOT(loadData())); } HistoryWindow::~HistoryWindow() { m_core->setSetting(KittySDK::Settings::S_HISTORYWINDOW_GEOMETRY, saveGeometry()); m_core->setSetting(KittySDK::Settings::S_HISTORYWINDOW_SPLITTER, m_ui->splitter->saveState()); m_core->setSetting(KittySDK::Settings::S_HISTORYWINDOW_COLUMNS, m_ui->chatTree->header()->saveState()); m_core->setSetting(KittySDK::Settings::S_HISTORYWINDOW_FILTERS, m_ui->filtersButton->isChecked()); delete m_ui; } void HistoryWindow::applySettings() { } void HistoryWindow::updateIcons() { m_ui->refreshButton->setIcon(m_core->icon(KittySDK::Icons::I_REFRESH)); m_ui->exportButton->setIcon(m_core->icon(KittySDK::Icons::I_FILE)); m_ui->importButton->setIcon(m_core->icon(KittySDK::Icons::I_FOLDER)); m_ui->printButton->setIcon(m_core->icon(KittySDK::Icons::I_PRINTER)); m_ui->filtersButton->setIcon(m_core->icon(KittySDK::Icons::I_FILTER)); m_ui->searchButton->setIcon(m_core->icon(KittySDK::Icons::I_SEARCH)); } void HistoryWindow::showContact(KittySDK::IContact *contact) { if(contact) { show(); activateWindow(); m_ui->contactSearchEdit->clear(); QModelIndex index = findContact(contact); if(index.isValid()) { m_ui->contactTree->setCurrentIndex(index); } } } void HistoryWindow::loadData() { m_ui->searchEdit->clear(); m_ui->contactSearchEdit->clear(); static_cast<QStandardItemModel*>(m_proxy->sourceModel())->clear(); m_ui->chatTree->clear(); m_ui->chatWebView->clear(); if(QStandardItem *root = static_cast<QStandardItemModel*>(m_proxy->sourceModel())->invisibleRootItem()) { QStandardItem *conversations = new QStandardItem(); conversations->setText(tr("Conversations")); conversations->setIcon(m_core->icon(KittySDK::Icons::I_FOLDER)); conversations->setData(HistoryWindow::ItemFolder, HistoryWindow::TypeRole); QDir historyDir(m_core->currentProfileDir() + "history/"); if(historyDir.exists()) { foreach(const QString &protoDir, historyDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot)) { KittySDK::IProtocol *proto = m_core->protocolManager()->protocolByName(protoDir); historyDir.cd(protoDir); foreach(const QString &accountDir, historyDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot)) { KittySDK::IAccount *acc = 0; QStandardItem *accountItem = new QStandardItem(); accountItem->setText(accountDir); accountItem->setData(HistoryWindow::ItemAccount, HistoryWindow::TypeRole); accountItem->setData(accountDir, HistoryWindow::PathNameRole); accountItem->setData(protoDir, HistoryWindow::ProtocolRole); if(proto) { accountItem->setIcon(m_core->icon(proto->protoInfo()->protoIcon())); acc = m_core->accountManager()->account(proto, accountDir); } else { accountItem->setIcon(m_core->icon(KittySDK::Icons::I_BULLET)); } historyDir.cd(accountDir); foreach(const QFileInfo &contactFile, historyDir.entryInfoList(QStringList("*.db"), QDir::Files)) { KittySDK::IContact *contact = 0; QStandardItem *contactItem = new QStandardItem(); contactItem->setData(HistoryWindow::ItemContact, HistoryWindow::TypeRole); contactItem->setData(protoDir, HistoryWindow::ProtocolRole); contactItem->setData(accountDir, HistoryWindow::AccountRole); contactItem->setData(contactFile.fileName(), HistoryWindow::PathNameRole); if(acc) { contact = acc->contacts().value(contactFile.completeBaseName()); } if(contact) { contactItem->setText(contact->display()); } else { contactItem->setText(contactFile.completeBaseName()); } if(proto) { contactItem->setIcon(m_core->icon(proto->protoInfo()->protoIcon())); } else { contactItem->setIcon(m_core->icon(KittySDK::Icons::I_BULLET)); } accountItem->appendRow(contactItem); } historyDir.cdUp(); if(accountItem->rowCount() > 0) { conversations->appendRow(accountItem); } else { delete accountItem; } } historyDir.cdUp(); } } root->appendRow(conversations); m_ui->contactTree->expandAll(); } } void HistoryWindow::changeEvent(QEvent *event) { if(event->type() == QEvent::LanguageChange) { m_ui->retranslateUi(this); } QWidget::changeEvent(event); } void HistoryWindow::filterContacts(const QString &filter) { m_proxy->setFilterWildcard(filter); m_ui->contactTree->expandAll(); } void HistoryWindow::on_chatTree_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous) { m_ui->chatWebView->clear(); if(current) { QModelIndex index = m_ui->contactTree->currentIndex(); int type = index.data(HistoryWindow::TypeRole).toInt(); switch(type) { case HistoryWindow::ItemAccount: { } break; case HistoryWindow::ItemContact: { QString filePath = m_core->currentProfileDir() + QString("history/%1/%2/%3").arg(index.data(HistoryWindow::ProtocolRole).toString()).arg(index.data(HistoryWindow::AccountRole).toString()).arg(index.data(HistoryWindow::PathNameRole).toString()); KittySDK::IAccount *acc = m_core->accountManager()->account(index.data(HistoryWindow::ProtocolRole).toString(), index.data(HistoryWindow::AccountRole).toString()); KittySDK::IContact *contact = 0; if(acc) { contact = acc->contacts().value(QFileInfo(index.data(HistoryWindow::PathNameRole).toString()).completeBaseName()); } if(QFile(filePath).exists()) { QSqlDatabase db = QSqlDatabase::database(); if(!db.isValid()) { db = QSqlDatabase::addDatabase("QSQLITE"); } db.setDatabaseName(filePath); if(!db.open()) { qDebug() << "Failed to open db" << db.databaseName() << db.lastError().text(); return; } QSqlQuery query; QString where; switch(m_ui->directionComboBox->currentIndex()) { case 1: where = QString("AND dir = %1 ").arg(KittySDK::IMessage::Incoming); break; case 2: where = QString("AND dir = %1 ").arg(KittySDK::IMessage::Outgoing); break; default: break; } if(m_ui->dateFromEdit->date() != QDate(1970, 1, 1)) { where.append(QString("AND timeStamp >= %1 ").arg(QDateTime(m_ui->dateFromEdit->date()).toTime_t())); } if(m_ui->dateToEdit->date() != QDate::currentDate()) { where.append(QString("AND timeStamp <= %1 ").arg(QDateTime(m_ui->dateToEdit->date()).toTime_t())); } if(!m_ui->searchEdit->text().isEmpty()) { where.append("AND body LIKE :search"); } query.prepare(QString("SELECT * FROM messages WHERE chatId=:chatId %1 ORDER BY timeStamp ASC;").arg(where)); query.bindValue("chatId", current->text(3)); if(!m_ui->searchEdit->text().isEmpty()) { query.bindValue("search", "%" + m_ui->searchEdit->text() + "%"); } if(query.exec()) { while(query.next()) { KittySDK::IMessage::Direction dir = (KittySDK::IMessage::Direction)query.value(3).toInt(); QString uid = QFileInfo(index.data(HistoryWindow::PathNameRole).toString()).completeBaseName(); KittySDK::IContact cnt(uid, 0); cnt.setDisplay(uid); KittySDK::IContact me(acc->uid(), acc); me.setDisplay(m_core->profileName()); KittySDK::IMessage *msg = 0; if(dir == KittySDK::IMessage::Incoming || dir == KittySDK::IMessage::System) { if(contact) { msg = new KittySDK::IMessage(contact, &me); } else { msg = new KittySDK::IMessage(&cnt, &me); } } else if(dir == KittySDK::IMessage::Outgoing) { if(contact) { msg = new KittySDK::IMessage(&me, contact); } else { msg = new KittySDK::IMessage(&me, &cnt); } } if(msg) { msg->setBody(query.value(4).toString()); msg->setDirection(dir); msg->setTimeStamp(QDateTime::fromTime_t(query.value(2).toInt())); m_ui->chatWebView->appendMessage(*msg); } delete msg; } m_ui->chatWebView->page()->mainFrame()->setScrollPosition(QPoint()); } else { qDebug() << "Error executing query" << query.lastQuery() << query.lastError().text(); } query.clear(); db.close(); } } break; } } } QModelIndex HistoryWindow::findContact(KittySDK::IContact *contact, const QModelIndex &parent) { for(int i = 0; i < m_proxy->rowCount(parent); ++i) { QModelIndex index = m_proxy->index(i, 0, parent); if(index.data(HistoryWindow::TypeRole).toInt() == HistoryWindow::ItemContact) { if(index.data(HistoryWindow::ProtocolRole).toString() == contact->protocol()->protoInfo()->protoName()) { if(index.data(HistoryWindow::AccountRole).toString() == contact->account()->uid()) { if(QFileInfo(index.data(HistoryWindow::PathNameRole).toString()).completeBaseName() == contact->uid()) { return index; } } } } if(m_proxy->rowCount(index) > 0) { QModelIndex result = findContact(contact, index); if(result.isValid()) { return result; } } } return QModelIndex(); } void HistoryWindow::loadChats(const QItemSelection &selected, const QItemSelection &deselected) { if(selected.indexes().count() > 0) { QModelIndex current = m_ui->contactTree->currentIndex(); m_ui->chatTree->clear(); int type = current.data(HistoryWindow::TypeRole).toInt(); switch(type) { case HistoryWindow::ItemFolder: { m_ui->chatTree->setColumnHidden(1, true); m_ui->chatTree->headerItem()->setText(0, tr("Account")); } break; case HistoryWindow::ItemAccount: { m_ui->chatTree->headerItem()->setText(0, tr("Contact")); m_ui->chatTree->setColumnHidden(1, true); QSqlDatabase db = QSqlDatabase::database(); if(!db.isValid()) { db = QSqlDatabase::addDatabase("QSQLITE"); } KittySDK::IAccount *acc = m_core->accountManager()->account(current.data(HistoryWindow::ProtocolRole).toString(), current.data().toString()); QDir accountPath = m_core->currentProfileDir() + QString("history/%1/%2/").arg(current.data(HistoryWindow::ProtocolRole).toString()).arg(current.data(HistoryWindow::PathNameRole).toString()); if(accountPath.exists()) { foreach(const QFileInfo &contactFile, accountPath.entryInfoList(QStringList("*.db"), QDir::Files)) { QTreeWidgetItem *item = new QTreeWidgetItem(); KittySDK::IContact *contact = 0; if(acc) { contact = acc->contacts().value(contactFile.completeBaseName()); item->setIcon(0, m_core->icon(acc->protocol()->protoInfo()->protoIcon())); } else { item->setIcon(0, m_core->icon(KittySDK::Icons::I_BULLET)); } if(contact) { item->setText(0, contact->display()); } else { item->setText(0, contactFile.completeBaseName()); } if(!m_ui->contactSearchEdit->text().isEmpty()) { if(!item->text(0).contains(m_ui->contactSearchEdit->text(), Qt::CaseInsensitive)) { delete item; continue; } } QString filePath = contactFile.absoluteFilePath(); if(QFile(filePath).exists()) { db.setDatabaseName(filePath); if(!db.open()) { qDebug() << "Failed to open db" << db.databaseName() << db.lastError().text(); delete item; return; } QSqlQuery query(" SELECT" " COUNT(DISTINCT chatId) as chats," " msg.count as messages " " FROM" " messages" " JOIN (SELECT COUNT(*) as count FROM messages) msg;"); query.next(); int chats = query.value(0).toInt(); int messages = query.value(1).toInt(); item->setText(2, tr("%n chat(s)", "", chats) + ", " + tr("%n message(s)", "", messages)); query.clear(); db.close(); m_ui->chatTree->addTopLevelItem(item); } } } } break; case HistoryWindow::ItemContact: { QString filePath = m_core->currentProfileDir() + QString("history/%1/%2/%3").arg(current.data(HistoryWindow::ProtocolRole).toString()).arg(current.data(HistoryWindow::AccountRole).toString()).arg(current.data(HistoryWindow::PathNameRole).toString()); m_ui->chatTree->headerItem()->setText(0, tr("Message")); m_ui->chatTree->setColumnHidden(1, false); KittySDK::IAccount *acc = m_core->accountManager()->account(current.data(HistoryWindow::ProtocolRole).toString(), current.data(HistoryWindow::AccountRole).toString()); if(QFile(filePath).exists()) { QSqlDatabase db = QSqlDatabase::database(); if(!db.isValid()) { db = QSqlDatabase::addDatabase("QSQLITE"); } db.setDatabaseName(filePath); if(!db.open()) { qDebug() << "Failed to open db" << db.databaseName() << db.lastError().text(); return; } QSqlQuery query(" SELECT" " *," " COUNT(*) as 'count'" " FROM (" " SELECT" " m.*," " lt.lastTimeStamp" " FROM" " messages m" " JOIN (SELECT MAX(timeStamp) as lastTimeStamp, chatId FROM messages GROUP BY chatId) lt" " ON" " lt.chatId = m.chatId" " ORDER BY" " timeStamp DESC," " dir DESC" " )" " GROUP BY chatId" " ORDER BY timeStamp DESC;"); while(query.next()) { QTreeWidgetItem *item = new QTreeWidgetItem(m_ui->chatTree); QString text = query.value(4).toString().remove(QRegExp("<[^>]*>")).remove("\n"); if(text.length() > 60) { text = text.left(60).append("..."); } if(acc && acc->protocol()) { item->setIcon(0, m_core->icon(acc->protocol()->protoInfo()->protoIcon())); } else { item->setIcon(0, m_core->icon(KittySDK::Icons::I_BULLET)); } QDateTime startTime = QDateTime::fromTime_t(query.value(2).toInt()); QDateTime endTime = QDateTime::fromTime_t(query.value(5).toInt()); QString duration = startTime.toString("h:mm"); if(startTime.date() != endTime.date()) { duration += startTime.toString(" d.MM.yyyy"); } duration += " - " + endTime.toString("h:mm d.MM.yyyy"); item->setText(0, text); item->setText(1, duration); item->setText(2, query.value(6).toString()); item->setText(3, query.value(1).toString()); } query.clear(); db.close(); } } break; } if(!m_ui->contactSearchEdit->hasFocus()) { m_ui->chatTree->setFocus(); } if(m_ui->chatTree->topLevelItemCount() > 0) { m_ui->chatTree->setCurrentItem(m_ui->chatTree->topLevelItem(0)); } } } void HistoryWindow::updateCurrentChat() { on_chatTree_currentItemChanged(m_ui->chatTree->currentItem(), 0); } void HistoryWindow::toggleFilters(bool checked) { if(!checked) { m_ui->directionComboBox->setCurrentIndex(0); m_ui->dateFromEdit->setDate(QDate(1970, 1, 1)); m_ui->dateToEdit->setDate(QDate::currentDate()); } } void HistoryWindow::on_chatTree_doubleClicked(const QModelIndex &current) { if(current.isValid()) { QModelIndex parent = m_ui->contactTree->currentIndex(); if(parent.data(HistoryWindow::TypeRole).toInt() == HistoryWindow::ItemAccount) { for(int i = 0; i < m_proxy->rowCount(parent); ++i) { QModelIndex index = m_proxy->index(i, 0, parent); if(index.data() == current.data()) { m_ui->contactTree->setCurrentIndex(index); } } } } } } void Kitty::HistoryWindow::refreshChats() { loadChats(m_ui->contactTree->selectionModel()->selection(), QItemSelection()); }
d8ca3ec531eeb224f4a4ef84f6fcc366ac0039a5
aeb4711e7738ead627d170c4c61c103d277cb96c
/moneybot_extern/backtracking.h
6ac6833cc14a8233f949ebafe627c7b4f1e210db
[]
no_license
navewindre/moneybot-external
a535b80a942192b5ce89efc76da0207832ddc26d
5328bab6151cf76858543189e804565693bd862b
refs/heads/main
2023-03-21T23:03:03.766271
2021-03-05T17:18:25
2021-03-05T17:18:25
344,880,019
0
1
null
null
null
null
UTF-8
C++
false
false
1,842
h
backtracking.h
#pragma once #include <array> #include "entity.h" #include "client.h" #include "sdk.h" constexpr const size_t BACKTRACKING_BACKUP = 64; namespace lagcomp { class c_backtracking { public: c_backtracking( ) { }; ~c_backtracking( ) { }; void update( ) { for ( int i{ }; i < 64; ++i ) { auto ent = g_instance.m_entlist.get_entity< c_base_player >( i ); if ( !ent.is_valid( ) ) continue; auto& record = m_records[ i ]; record.store( i ); } } vec3_t backtrack_entity( int i, int tick ) { return m_records[ i ].restore( tick ); } protected: struct lag_record { void store( int ent_number ) { //store entity's simulation time to backtrack to later //cache it by your own tickbase, we cant access usercmd reliably // fucking nerd m_index = ent_number; auto ent = g_instance.m_entlist.get_entity< c_base_player >( m_index ); m_simtime[ g_instance.m_local.m_nTickBase( ) % BACKTRACKING_BACKUP ] = ent.m_flSimulationTime( ); m_headpos[ g_instance.m_local.m_nTickBase( ) % BACKTRACKING_BACKUP ] = ent.get_bone_pos( 8 ); } vec3_t restore( int tick ) { //simply set the simtime back and the tickcount int bt_tick; int tick_delta; auto ent = g_instance.m_entlist.get_entity( m_index ); bt_tick = TIME_TO_TICKS( m_simtime[ tick % BACKTRACKING_BACKUP ] + util::get_lerp( ) ); tick_delta = g_instance.m_engine.set_tickcount( bt_tick ); ent.m_flSimulationTime( m_simtime[ tick + tick_delta ] ); return m_headpos[ ( tick + tick_delta ) % BACKTRACKING_BACKUP ]; } int m_index{ }; std::array< float, BACKTRACKING_BACKUP > m_simtime; std::array< vec3_t, BACKTRACKING_BACKUP > m_headpos; matrix3x4 m_bonedata[ 128 ]; }; std::array< lag_record, 64 > m_records; }; } extern lagcomp::c_backtracking g_backtracking;
2a3a706270fb741a06cb54827d6c420c1388becb
11e97f87deb25babb4a32c80941e7ff4e476c92a
/SMA/Rotor/SEQUnit.h
c4d2f0351026a5b7d69c947b552cc87a9a31ad8a
[]
no_license
xhyangxianjun/Builder6-program
b9d03d98658db5a5a8cf1586210a373bc391dc48
a12d811d7a5fa3dba6d3e8c05989a41cb89783de
refs/heads/master
2022-04-03T00:25:47.274355
2019-09-19T08:26:56
2019-09-19T08:26:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,337
h
SEQUnit.h
//--------------------------------------------------------------------------- #ifndef SEQUnitH #define SEQUnitH #include <Classes.hpp> #include <Grids.hpp> //--------------------------------------------------------------------------- //void Msg(AnsiString _sMsg) typedef void (__closure *SeqMsgFunc)(AnsiString); class CSEQ : public TThread { public: __fastcall CSEQ(void); __fastcall ~CSEQ(void); bool CheckCode(TStrings * _slSourse); void StartSeq () {m_bSeqInit = false ; Resume();} void DisplayFunc ( TStringGrid * _slValue) ; AnsiString GetErrName(); void SetMsgFunc(SeqMsgFunc Func) { m_pMsgFunc = Func ; } bool IsRun (void) { return !Suspended; } bool ReqStop() {m_bReqStop = true ;} private: enum EN_FUNC { fcCHECKFINISH = 0 , fcMOVE0RPM , fcMOVEHOME , fcMOVEABS , fcMOVEINC , fcLASER , fcDELAY , fcCOMMENT , fcEMPTY , fcCAMERA , fcSERVO0 , fcSHAKE0 , fcOR_SETSPEED0 , fcOR_SETTIME0 , fcOR_SETSTART , MAX_FUNC }; struct TFuncInfo { EN_FUNC iFunc ; double dPara1 ; double dPara2 ; double dPara3 ; double dPara4 ; double dPara5 ; double dPara6 ; double dPara7 ; double dPara8 ; double dPara9 ; double dPara10 ; }; int m_dORSpeed[100] ; int m_dORTime[100] ; int m_iMaxVal ; int m_iMaxTime ; TStringList * m_slSeq ; TFuncInfo * m_FuncInfo ; AnsiString m_sErrName ; int m_iMaxLines ; bool GetFuncName(AnsiString &_sLine , EN_FUNC &_fcName ) ; bool GetPara (AnsiString &_sLine , double &_dPara) ; SeqMsgFunc m_pMsgFunc ; bool m_bReqStop ; bool m_bSeqInit ; void __fastcall Execute(); AnsiString GetFuncNameString(EN_FUNC iFunc) ; }; extern CSEQ *pSeq; #endif
af74495f87a2ad96c2e8e59d323cc9a2ac73ffc9
0517284f941161b5f7d7663d3bc1ab735a5efb9b
/ch10/ex10_12.cc
2b1af2fbfd66edded630b29f9d86d95d39c4f517
[]
no_license
LuckyGrx/CppPrimer
874d56efa56aa23278afebb278752ff473835479
6818a2e80d6d343a86fe59bca104652948063abb
refs/heads/master
2021-09-21T17:04:13.800399
2018-08-29T12:49:40
2018-08-29T12:49:40
94,493,037
10
2
null
null
null
null
UTF-8
C++
false
false
690
cc
ex10_12.cc
/// /// @file ex10_12.cc /// @author zack(18357154046@163.com) /// @date 2017-08-25 14:04:56 /// #include "../ex07/ex7_26.h" #include <iostream> #include <string> #include <vector> #include <algorithm> using std::vector; using std::endl; using std::string; using std::sort; using std::cout; inline bool compareIsbn(const Sales_data &lhs,const Sales_data &rhs){ return lhs.isbn()<rhs.isbn(); } int main(){ Sales_data d1("a"),d2("aa"),d3("aaa"),d4("b"),d5("bb"),d6("z"); vector<Sales_data> vec{d1,d3,d2,d5,d4,d6}; sort(vec.begin(),vec.end(),compareIsbn); for_each(vec.begin(),vec.end(), [](const Sales_data &hs) { cout<<hs.isbn()<<" ";}); cout<<endl; return 0; }