hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
7183a7bcc789f718336e25d0388a553c39091d42
3,417
cpp
C++
src/simple-2d-polydar.cpp
mdsumner/polydar
44009e76fdbf36cb71d97253427e8b4000f53ec5
[ "MIT" ]
2
2020-05-05T07:07:27.000Z
2020-05-05T07:19:17.000Z
src/simple-2d-polydar.cpp
mdsumner/polydar
44009e76fdbf36cb71d97253427e8b4000f53ec5
[ "MIT" ]
null
null
null
src/simple-2d-polydar.cpp
mdsumner/polydar
44009e76fdbf36cb71d97253427e8b4000f53ec5
[ "MIT" ]
null
null
null
/** simple.cpp Purpose: Example of using polylidar in C++ @author Jeremy Castagno @version 05/20/19 */ #include <Rcpp.h> using namespace Rcpp; #include <iostream> #include <sstream> // std::istringstream #include <vector> #include <string> #include <fstream> #include <iomanip> #include "include/polylidar/polylidar.hpp" // Print arrays template <typename TElem> std::ostream& operator<<(std::ostream& os, const std::vector<TElem>& vec) { auto iter_begin = vec.begin(); auto iter_end = vec.end(); os << "["; for (auto iter = iter_begin; iter != iter_end; ++iter) { std::cout << ((iter != iter_begin) ? "," : "") << *iter; } os << "]"; return os; } // [[Rcpp::export]] Rcpp::List rcpp_polydar(NumericVector x, IntegerVector dim, NumericVector xyThresh, NumericVector alpha, NumericVector lmax, IntegerVector minTriangles, IntegerVector MAX_ITER) { //int argc; //char *argv[]; // std::cout << "Simple C++ Example of Polylidar" << std::endl; std::vector<double> points = as<std::vector<double> >(x); // std::vector<double> points = { // 0.0, 0.0, // 0.0, 1.0, // 1.0, 1.0, // 1.0, 0.0, // 5.0, 0.1, // }; // 5 X 2 matrix as one contigious array // Convert to multidimensional array std::vector<std::size_t> shape = { points.size() / 2, 2 }; polylidar::Matrix<double> points_(points.data(), shape[0], shape[1]); // Set configuration parameters polylidar::Config config; config.dim = dim[0]; config.xyThresh = xyThresh[0]; config.alpha = alpha[0]; config.lmax = lmax[0]; config.minTriangles = minTriangles[0]; // Extract polygon std::vector<float> timings; auto before = std::chrono::high_resolution_clock::now(); auto polygons = polylidar::ExtractPolygonsAndTimings(points_, config, timings); for (int i = 0; i < MAX_ITER[0]; i++) { polygons = polylidar::ExtractPolygonsAndTimings(points_, config, timings); } // FIXME: I have no idea how to get this stuff out // c++ fu is -- // for(auto const& polygon: polygons) { // polygon.shell; // what do we do? see std::cout below // } auto after = std::chrono::high_resolution_clock::now(); auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(after - before); // std::cout << "Polylidar took " << elapsed.count() << " milliseconds processing a " << shape[0] << " point cloud" << std::endl; // std::cout << "Point indices of Polygon Shell: "; Rcpp::List out(polygons.capacity()); int jj = 0; for(auto const& polygon: polygons) { // std::cout << polygon.shell << std::endl; IntegerVector idx(polygon.shell.capacity()); for (int ii = 0; ii < idx.length(); ii ++) { idx[ii] = (int)polygon.shell[ii]; } out[jj] = Rcpp::wrap(idx); jj = jj + 1; } // std::cout << polygons.capacity() << std::endl; // out[0] = Rcpp::wrap(idx); // std::cout << std::endl; // std::cout << "Detailed timings in milliseconds:" << std::endl; // std::cout << std::fixed << std::setprecision(2) << "Delaunay Triangulation: " << timings[0] << "; Mesh Extraction: " << timings[1] << "; Polygon Extraction: " << timings[2] <<std::endl; return out; }
30.508929
190
0.580334
mdsumner
71845503f276eb0333c946c1edf10ba8fc60df38
1,016
cpp
C++
src/NGFX/Private/Vulkan/vk_pipeline.cpp
PixPh/kaleido3d
8a8356586f33a1746ebbb0cfe46b7889d0ae94e9
[ "MIT" ]
38
2019-01-10T03:10:12.000Z
2021-01-27T03:14:47.000Z
src/NGFX/Private/Vulkan/vk_pipeline.cpp
fuqifacai/kaleido3d
ec77753b516949bed74e959738ef55a0bd670064
[ "MIT" ]
null
null
null
src/NGFX/Private/Vulkan/vk_pipeline.cpp
fuqifacai/kaleido3d
ec77753b516949bed74e959738ef55a0bd670064
[ "MIT" ]
8
2019-04-16T07:56:27.000Z
2020-11-19T02:38:37.000Z
#include "vk_common.h" namespace vulkan { GpuRenderPipeline::GpuRenderPipeline(GpuDevice* device, ngfx::RenderPipelineDesc const& desc) : GpuPipelineBase(device) { create_info_.stageCount; create_info_.pStages; create_info_.pVertexInputState; create_info_.pInputAssemblyState; create_info_.pTessellationState; create_info_.pViewportState; create_info_.pRasterizationState; create_info_.pMultisampleState; create_info_.pDepthStencilState; create_info_.pColorBlendState; create_info_.pDynamicState; create_info_.layout; create_info_.renderPass; create_info_.subpass; create_info_.basePipelineHandle; create_info_.basePipelineIndex; } GpuRenderPipeline::~GpuRenderPipeline() { } GpuComputePipeline::GpuComputePipeline(GpuDevice* device, ngfx::ComputePipelineDesc const& desc) : GpuPipelineBase(device) { create_info_.stage; create_info_.layout; create_info_.basePipelineIndex; create_info_.basePipelineHandle; } GpuComputePipeline::~GpuComputePipeline() { } }
24.190476
97
0.806102
PixPh
71898089850d4aaee8c18f2f9f3e84cddecb0816
460
cpp
C++
HandAugementedReality/HandAugementedReality/Finger.cpp
nemcek/hand-augmented-reality
6f4c1f23e1d18d35b3cc65bcc109ca06a8023ea6
[ "MIT" ]
null
null
null
HandAugementedReality/HandAugementedReality/Finger.cpp
nemcek/hand-augmented-reality
6f4c1f23e1d18d35b3cc65bcc109ca06a8023ea6
[ "MIT" ]
null
null
null
HandAugementedReality/HandAugementedReality/Finger.cpp
nemcek/hand-augmented-reality
6f4c1f23e1d18d35b3cc65bcc109ca06a8023ea6
[ "MIT" ]
1
2021-12-16T03:26:28.000Z
2021-12-16T03:26:28.000Z
#include "Finger.h" Finger::Finger() { } Finger::Finger(const Point& finger_tip_point, FingerType type) { this->location = Location(finger_tip_point); this->roi = Rect(Point(location.get().x - width / 2, location.get().y - height / 4), Size(width, height)); this->type = type; } /// Extracts finger from image by defined finger's region of interest void Finger::extract(const Mat & frame) { this->roi_data = frame(this->roi); } Finger::~Finger() { }
18.4
107
0.684783
nemcek
718aad9333fdba92b3c5e4fc7de25fdc1906a5cd
8,951
hpp
C++
hwlib/doxyfiles/texts/hwlib-doxygen-#0070-graphics.hpp
TheBlindMick/MPU6050
66880369fa7a73755846e60568137dfc07da1b5c
[ "BSL-1.0" ]
46
2017-02-15T14:24:14.000Z
2021-10-01T14:25:57.000Z
hwlib/doxyfiles/texts/hwlib-doxygen-#0070-graphics.hpp
TheBlindMick/MPU6050
66880369fa7a73755846e60568137dfc07da1b5c
[ "BSL-1.0" ]
27
2017-02-15T15:13:42.000Z
2021-08-28T15:29:01.000Z
hwlib/doxyfiles/texts/hwlib-doxygen-#0070-graphics.hpp
TheBlindMick/MPU6050
66880369fa7a73755846e60568137dfc07da1b5c
[ "BSL-1.0" ]
39
2017-05-18T11:51:03.000Z
2021-09-14T09:07:01.000Z
// ========================================================================== // // File : hwlib-doxygen-char-io.hpp // Part of : C++ hwlib library for close-to-the-hardware OO programming // Copyright : wouter@voti.nl 2017-2019 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // ========================================================================== // this file contains Doxygen lines (of course, that is its only purpose) /// @file /// \page graphics Graphics /// /// The (abstract) types /// \ref hwlib::istream istream and \ref hwlib::ostream ostream /// are used to read and write characters. /// /// <BR> /// /// ========================================================================= /// /// \section xy xy /// /// An \ref hwlib::xy "xy" is a value type that stores two int__fst16_t /// values x and y. xy values can be added and subtracted, and can be /// multiplied and divided by an integer value. /// An xy can also be printed /// to an \ref hwlib::ostream "ostream" using operator<<. /// /// attributes and operations | meaning or effect /// -------------------------------- | ------------------------------------------ /// \ref hwlib::xy::x "x" | x value /// \ref hwlib::xy::y "y" | y value /// \ref hwlib::xy::operator+ "+" | adds two xy values /// \ref hwlib::xy::operator+ "-" | subtracts to xy values /// \ref hwlib::xy::operator+ "*" | multiplies the x and y value by an integer /// \ref hwlib::xy::operator/ "/" | divides the x and y values by an integer /// \ref hwlib::xy::operator<< "<<" | prints an xy to an \ref hwlib::ostream "ostream" /// /// The overloaded all() function can be used to iterate over all (x,y) values /// within the (0 .. x-1, 0 .. y-1) range (in some unspecified order). /// /// <BR> /// /// ========================================================================= /// /// \section color color /// /// A \ref hwlib::color "color" is a value type that stores a color as /// three 8-bit red, green and blue values, plus a 'is_transparent' flag. /// When the transparent flag is not set, the color values determine the /// color. When it is set, the color values have no meaning. /// An color can also be printed /// to an \ref hwlib::ostream "ostream" using operator<<. /// /// Colors can be constructed, negated, /// and compared for equality or inequality. /// /// attributes and operations | meaning or effect /// --------------------------------------------------- | ------------------------------------------ /// \ref hwlib::color::is_transparent "is_transparent" | transparency flag /// \ref hwlib::color::red "rad" | red intensity /// \ref hwlib::color::green "green" | green intensity /// \ref hwlib::color::blue "blue" | blue intensity /// \ref hwlib::color::color(uint_fast32_t red,uint_fast32_t green,uint_fast32_t blue,bool transparent) "color(r,g,b)" | construct a color from its components /// \ref hwlib::color::color(uint_fast32_t) "color(v)" | construct a color from its 24-bit RGB value /// \ref hwlib::color::operator- "-" | yields the inverse of a color /// \ref hwlib::color::operator== "==" | tests for equality /// \ref hwlib::color::operator!= "!=" | tests for inequality /// \ref hwlib::color::operator<< "<<" | prints an xy to an \ref hwlib::ostream "ostream" /// /// The following color constants are available: /// - \ref hwlib::black "black" /// - \ref hwlib::white "white" /// - \ref hwlib::red "red" /// - \ref hwlib::green "green" /// - \ref hwlib::blue "blue" /// - \ref hwlib::gray "gray" /// - \ref hwlib::yellow "yellow" /// - \ref hwlib::cyan "cyan" /// - \ref hwlib::magenta "magenta" /// - \ref hwlib::transparent "transparent" /// - \ref hwlib::violet "violet" /// - \ref hwlib::sienna "sienna" /// - \ref hwlib::purple "purple" /// - \ref hwlib::pink "pink" /// - \ref hwlib::silver "silver" /// - \ref hwlib::brown "brown" /// - \ref hwlib::salmon "salmon" /// /// <BR> /// /// ========================================================================= /// /// \section image image /// /// An \ref hwlib::image image is an abstract class that defines /// an interface to a picture, that is: a rectangle of read-only pixels. /// An image is used to embed a picture in the application. /// /// attributes and operations | meaning or effect /// ------------------------------------------ | ------------------------------------------ /// \ref hwlib::image::size "size" | size in pixels in x and y direction /// \ref hwlib::image::operator[] operator [] | the color of the pixel at location loc /// /// <BR> /// /// ========================================================================= /// /// \section font font /// /// An \ref hwlib::font font is an abstract class that defines /// an interface to a set of pictures that show characters as a graphic /// images. /// A font is used to implement a character /// \ref hwlib::terminal "terminal" on a graphic /// \ref hwlib::window window. /// /// attributes and operations | meaning or effect /// ----------------------------------------------- | ------------------------------------------ /// \ref hwlib::image::operator[] "operator[ c ]" | returns the image for char c /// /// Two concrete built-in font classes are available: /// - \ref hwlib::font_default_8x8 font_default_8x8 /// - \ref hwlib::font_default_16x16 font_default_16x16 /// /// The font_default_16x16 is not available on AVR8 targets because /// the AVR compiler can't handle it. /// /// <BR> /// /// ========================================================================= /// /// \section window window /// /// An \ref hwlib::window window is an abstract class that defines /// an interface to a graphics display. The display can be cleared, /// and a pixel can be set to a color. /// /// Window operations are (potentially) buffered: a subsequent /// \ref hwlib::window::flush "flush()" call is required in order /// for the previous operations to take effect. /// /// attributes and operations | meaning or effect /// ----------------------------------------------- | ------------------------------------------ /// \ref hwlib::window::size "size" | size of the display, in pixels in a x any direction /// \ref hwlib::window::background "background" | the background color /// \ref hwlib::window::foreground "foreground" | the foreground color /// \ref hwlib::window::clear "clear()" | write the background color to all pixels /// \ref hwlib::window::clear "clear(col)" | write color col to tall pixels /// \ref hwlib::window::write "write(loc, col)" | write color col to the pixel at loc /// \ref hwlib::window::write "write(loc, img)" | write image img to the location loc /// \ref hwlib::window::flush "flush()" | flush all pending changes to the window /// /// The \ref hwlib::window_part "window_part" decorator creates a /// window in a rectangular part of another window. /// /// The \ref hwlib::window_invert "window_invert" decorator creates a /// window that writes inverted (the color of each pixel negated) to the /// underlying window. /// /// <BR> /// /// ========================================================================= /// /// \section drawables drawables /// /// A \ref hwlib::drawable drawable is an abstract class that defines /// an interface for something that cab be drawn /// on a \ref hwlib::window window. /// /// attributes and operations | meaning or effect /// ----------------------------------------------- | ------------------------------------------ /// \ref hwlib::drawable::start "start" | origin (top left corner) of where the drawable is to be drawn /// \ref hwlib::drawable::draw "draw(w)" | draw the drawable on window w /// /// A \ref hwlib::line "line" is a drawable. /// It is created by specifying its origin and its endpoint. /// A color can be specified. /// If none is, the foreground color of the window is used. /// /// A \ref hwlib::circle "circle" is a drawable. /// It is created by specifying its midpoint and its radius /// A color can be specified. /// If none is, the foreground color of the window is used. /// /// <BR> /// /// ========================================================================= /// /// \section terminal_from terminal_from /// /// A \ref hwlib::terminal_from "terminal_from" creates a /// character \ref hwlib::terminal "terminal" from a window and /// a character \ref hwlib::font "font". /// /// /// <BR> ///
43.451456
163
0.537594
TheBlindMick
718affb17c3349b1fbdd5e5ef593df60654db8a3
1,755
cpp
C++
901-1000/928. Minimize Malware Spread II.cpp
erichuang1994/leetcode-solution
d5b3bb3ce2a428a3108f7369715a3700e2ba699d
[ "MIT" ]
null
null
null
901-1000/928. Minimize Malware Spread II.cpp
erichuang1994/leetcode-solution
d5b3bb3ce2a428a3108f7369715a3700e2ba699d
[ "MIT" ]
null
null
null
901-1000/928. Minimize Malware Spread II.cpp
erichuang1994/leetcode-solution
d5b3bb3ce2a428a3108f7369715a3700e2ba699d
[ "MIT" ]
null
null
null
class Solution { public: int minMalwareSpread(vector<vector<int>> &graph, vector<int> &initial) { int N = graph.size(); vector<bool> flag(N, false); vector<vector<int>> connected(N, vector<int>()); vector<vector<int>> edges(N, vector<int>()); for (int i = 0; i < N; ++i) { for (int j = i + 1; j < N; ++j) { if (graph[i][j]) { edges[i].push_back(j); edges[j].push_back(i); } } } for (auto &i : initial) { flag[i] = true; } for (auto &n : initial) { unordered_set<int> s; queue<int> q; q.push(n); while (!q.empty()) { auto cur = q.front(); q.pop(); for (auto i : edges[cur]) { if (!flag[i] && s.find(i) == s.end()) { s.insert(i); q.push(i); } } } for (auto &idx : s) { connected[idx].push_back(n); } } vector<int> counter(N, 0); for (int i = 0; i < N; ++i) { if (!flag[i] && connected[i].size() == 1) { counter[connected[i][0]]++; } } int idx = -1, best = INT_MIN; for (auto &n : initial) { if (counter[n] > best || (counter[n] == best && n < idx)) { idx = n; best = counter[n]; } } return idx; } };
26.19403
74
0.325356
erichuang1994
718c201296b2b15165e073a60cdff475dc75aad9
7,348
cpp
C++
mwidgets/src/mediawidget/downloaddialog.cpp
quntax/qpcol
290e2f0639eaee12fe6190070b3e2c38a8fd1ea7
[ "BSD-3-Clause" ]
null
null
null
mwidgets/src/mediawidget/downloaddialog.cpp
quntax/qpcol
290e2f0639eaee12fe6190070b3e2c38a8fd1ea7
[ "BSD-3-Clause" ]
null
null
null
mwidgets/src/mediawidget/downloaddialog.cpp
quntax/qpcol
290e2f0639eaee12fe6190070b3e2c38a8fd1ea7
[ "BSD-3-Clause" ]
null
null
null
#include "downloaddialog.h" DownloadDialog::DownloadDialog(QWidget * parent) : QDialog(parent) { dialogText = QString("Downloading file:\n%1\n\nTarget directory:\n%2\n"); pixmap = QIcon::fromTheme("download").pixmap(QSize(48, 48)); } DownloadDialog::~DownloadDialog() { destroy(); } // TODO prompt for directory if not known.... give a chance to change if known void DownloadDialog::download(const QString &url, const QString &directory) { if (checkTargetExists(url, directory)) { close(); return; } imageLabel = new QLabel; imageLabel->setPixmap(pixmap); QFileInfo urlInfo(url); textLabel = new QLabel(dialogText.arg(urlInfo.fileName()).arg(directory)); buttonAbort = new QPushButton(QIcon::fromTheme("dialog-cancel"), tr("Abort")); connect(buttonAbort, SIGNAL(clicked()), this, SLOT(cancel())); buttonBox = new QDialogButtonBox(Qt::Horizontal); buttonBox->addButton(buttonAbort, QDialogButtonBox::RejectRole); progressBar = new QProgressBar; progressBar->setValue(0); progressBar->setFormat("%v / %m KB (%p%)"); QHBoxLayout * iconAndTextLayout = new QHBoxLayout; iconAndTextLayout->setSpacing(22); iconAndTextLayout->setContentsMargins(11, 11, 11, 11); iconAndTextLayout->addWidget(imageLabel); iconAndTextLayout->addWidget(textLabel); QHBoxLayout * abortButtonLayout = new QHBoxLayout; abortButtonLayout->addStretch(); abortButtonLayout->addWidget(buttonBox); QVBoxLayout * completeLayout = new QVBoxLayout; completeLayout->addLayout(iconAndTextLayout); completeLayout->addWidget(progressBar); completeLayout->addLayout(abortButtonLayout); QGridLayout * mainLayout = new QGridLayout; mainLayout->addLayout(completeLayout, 0, 0); setLayout(mainLayout); setMaximumSize(width(), height()); setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); setWindowTitle(QString(tr("%1 - downloading")).arg(file)); show(); targetFile.open(QFile::WriteOnly); downloader = new QHttpDownload; connect(downloader, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(updateProgressBar(qint64,qint64))); connect(downloader, SIGNAL(chunk(QByteArray)), this, SLOT(saveChunk(QByteArray))); connect(downloader, SIGNAL(clear()), this, SLOT(reset())); connect(downloader, SIGNAL(complete(QByteArray)), this, SLOT(complete())); sourceUrl = url; downloader->download(url); } void DownloadDialog::downloadToFile(const QString &remoteFile, const QString &localFile) { sourceUrl = remoteFile; targetFile.setFileName(localFile); dir = QFileInfo(targetFile).dir().canonicalPath(); file = QFileInfo(targetFile).fileName(); imageLabel = new QLabel; imageLabel->setPixmap(pixmap); QFileInfo urlInfo(remoteFile); textLabel = new QLabel(dialogText.arg(urlInfo.fileName()).arg(targetFile.fileName())); buttonAbort = new QPushButton(QIcon::fromTheme("dialog-cancel"), tr("Abort")); connect(buttonAbort, SIGNAL(clicked()), this, SLOT(cancel())); buttonBox = new QDialogButtonBox(Qt::Horizontal); buttonBox->addButton(buttonAbort, QDialogButtonBox::RejectRole); progressBar = new QProgressBar; progressBar->setValue(0); progressBar->setFormat("%v / %m KB (%p%)"); QHBoxLayout * iconAndTextLayout = new QHBoxLayout; iconAndTextLayout->setSpacing(22); iconAndTextLayout->setContentsMargins(11, 11, 11, 11); iconAndTextLayout->addWidget(imageLabel); iconAndTextLayout->addWidget(textLabel); QHBoxLayout * abortButtonLayout = new QHBoxLayout; abortButtonLayout->addStretch(); abortButtonLayout->addWidget(buttonBox); QVBoxLayout * completeLayout = new QVBoxLayout; completeLayout->addLayout(iconAndTextLayout); completeLayout->addWidget(progressBar); completeLayout->addLayout(abortButtonLayout); QGridLayout * mainLayout = new QGridLayout; mainLayout->addLayout(completeLayout, 0, 0); setLayout(mainLayout); setMaximumSize(width(), height()); setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); setWindowTitle(QString(tr("%1 - downloading")).arg(file)); show(); bool ioResult = targetFile.open(QFile::WriteOnly); if (! ioResult) { qDebug() << "Could not open target file"; cleanup(); return; } downloader = new QHttpDownload; connect(downloader, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(updateProgressBar(qint64,qint64))); connect(downloader, SIGNAL(chunk(QByteArray)), this, SLOT(saveChunk(QByteArray))); connect(downloader, SIGNAL(clear()), this, SLOT(reset())); connect(downloader, SIGNAL(complete(QByteArray)), this, SLOT(complete())); downloader->download(remoteFile); } void DownloadDialog::cancel() { downloader->blockSignals(true); downloader->disconnect(); targetFile.remove(); cleanup(); } void DownloadDialog::updateProgressBar(qint64 val, qint64 max) { progressBar->setValue(qRound((qreal)val/1024)); progressBar->setMaximum(qRound((qreal)max/1024)); } void DownloadDialog::complete() { targetFile.flush(); targetFile.close(); emit downloadCompleted(sourceUrl); emit downloadCompleted(this); emit downloadCompleted(this, sourceUrl); } void DownloadDialog::saveChunk(QByteArray chunk) { targetFile.write(chunk); } QString DownloadDialog::getSourceUrl() const { return sourceUrl; } QString DownloadDialog::getTargetFile() const { return QFile::decodeName(targetFile.fileName().toLocal8Bit()); } void DownloadDialog::reset() { targetFile.flush(); targetFile.resize(0); } void DownloadDialog::cleanup() { downloader->deleteLater(); downloader = 0; close(); } bool DownloadDialog::checkTargetExists(const QString &url, const QString &directory) { QFileInfo info(url); file = info.fileName(); if (file.isEmpty()) { file = QString("download_%1").arg(QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss")); } dir = directory; QString filename = QString("%1/%2").arg(dir).arg(file); QString message = QString(tr("File with name %1 already exists in directory %2\n" "You can click \"Yes\" to continue download, overwriting it,\n" "\"No\" to abort or \"Ignore\" to download file\n" "with randomly picked new name.\n\n" "Do you wish to proceed?")).arg(file).arg(dir); if (QFile::exists(filename)) { int result = QMessageBox::question( this, tr("File exists"), message, QMessageBox::Yes | QMessageBox::No | QMessageBox::Ignore, QMessageBox::No); if (result == QMessageBox::No) { return true; } if (result == QMessageBox::Ignore) { file.prepend(QCryptographicHash::hash(QDateTime::currentDateTime().toString().toLocal8Bit(), QCryptographicHash::Md5).toHex()); filename = QString("%1/%2").arg(dir).arg(file); } } targetFile.setFileName(filename); return false; }
30.238683
104
0.662221
quntax
718f148237aa142c37818bef9b5a428a39a9e747
4,292
cpp
C++
Editor/src/ImGuiWidgets/Viewport.cpp
FelipeCalin/Hildur
13e60a357e6f84ac1de842d9a9bd980155968cbc
[ "Apache-2.0" ]
null
null
null
Editor/src/ImGuiWidgets/Viewport.cpp
FelipeCalin/Hildur
13e60a357e6f84ac1de842d9a9bd980155968cbc
[ "Apache-2.0" ]
null
null
null
Editor/src/ImGuiWidgets/Viewport.cpp
FelipeCalin/Hildur
13e60a357e6f84ac1de842d9a9bd980155968cbc
[ "Apache-2.0" ]
null
null
null
#include "Viewport.h" #include <Hildur.h> #include <ImGui/imgui.h> #define BIND_EVENT_FN(x) std::bind(&Viewport::x, this, std::placeholders::_1) namespace Editor { Viewport::Viewport() { } Viewport::~Viewport() { } void Viewport::Init(uint32_t width, uint32_t height) { m_ObjectIDFrameBuffer = Hildur::FrameBuffer::Create(width, height); m_ObjectIDFrameBuffer->AddTextureAttachment("ID"); m_ObjectIDFrameBuffer->AddDepthBufferAttachment(); m_ObjectIDFrameBuffer->Ready(); } void Viewport::Render(Hildur::Ref<Hildur::FrameBuffer> framebuffer, const Hildur::Window& window) { ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, { 0.0f, 0.0f }); ImGui::Begin("Viewport"); if (m_ViewportWidth != ImGui::GetWindowContentRegionMax().x || m_ViewportHeight != ImGui::GetWindowContentRegionMax().y) { m_ViewportWidth = ImGui::GetWindowContentRegionMax().x; m_ViewportHeight = ImGui::GetWindowContentRegionMax().y; m_Rezised = true; } m_ViewportPosX = ImGui::GetWindowContentRegionMin().x + ImGui::GetWindowPos().x; m_ViewportPosY = ImGui::GetWindowContentRegionMin().y + ImGui::GetWindowPos().y; m_IsInViewport = ImGui::IsWindowHovered(); if (m_Rezised) { m_ObjectIDFrameBuffer->Resize(m_ViewportWidth, m_ViewportHeight); framebuffer->Resize(m_ViewportWidth, m_ViewportHeight); if (Hildur::Camera::GetMainCamera() != nullptr) Hildur::Camera::GetMainCamera()->UpdateAspect((float)m_ViewportWidth / (float)m_ViewportHeight); m_Rezised = false; } if (m_IsInViewport) { m_MouseViewportPosX = (float)((float)(Hildur::Input::GetMouseX() + window.GetPositionX() - m_ViewportPosX) / (float)m_ViewportWidth) - 0.5f; m_MouseViewportPosY = (float)((float)(Hildur::Input::GetMouseY() + window.GetPositionY() - m_ViewportPosY) / (float)m_ViewportHeight) - 0.5f; } ImGui::GetWindowDrawList()->AddImage( (void*)(intptr_t)framebuffer->GetAttachment("color")->rendererID, ImVec2(ImGui::GetCursorScreenPos()), ImVec2(ImGui::GetCursorScreenPos().x + m_ViewportWidth, ImGui::GetCursorScreenPos().y + m_ViewportHeight)); Hildur::Renderer::OnWindowResize(m_ViewportWidth, m_ViewportHeight); ImGui::End(); ImGui::PopStyleVar(); //Test ImGui::Begin("ID Buffer"); uint32_t imageWidth = ImGui::GetWindowContentRegionMax().x; uint32_t imageHeight = ImGui::GetWindowContentRegionMax().y; ImGui::GetWindowDrawList()->AddImage( (void*)(intptr_t)m_ObjectIDFrameBuffer->GetAttachment("ID")->rendererID, ImVec2(ImGui::GetCursorScreenPos()), ImVec2(ImGui::GetCursorScreenPos().x + imageWidth, ImGui::GetCursorScreenPos().y + imageHeight)); ImGui::End(); } void Viewport::OnEvent(Hildur::Event& e) { Hildur::EventDispatcher distpatcher(e); distpatcher.Dispatch<Hildur::WindowResizeEvent>(BIND_EVENT_FN(OnWindowResize)); distpatcher.Dispatch<Hildur::WindowMoveEvent>(BIND_EVENT_FN(OnWindowMove)); distpatcher.Dispatch<Hildur::WindowCloseEvent>(BIND_EVENT_FN(OnWindowClose)); distpatcher.Dispatch<Hildur::MouseButtonPressedEvent>(BIND_EVENT_FN(OnMouseClick)); distpatcher.Dispatch<Hildur::MouseScrolledEvent>(BIND_EVENT_FN(OnMouseScrolled)); } bool Viewport::OnWindowResize(Hildur::WindowResizeEvent& e) { m_Rezised = true; return false; } bool Viewport::OnWindowMove(Hildur::WindowMoveEvent& e) { return false; } bool Viewport::OnWindowClose(Hildur::WindowCloseEvent& e) { return false; } bool Viewport::OnMouseClick(Hildur::MouseButtonPressedEvent& e) { if (IsMouseInViewport() && e.GetMouseButton() == 0) { glm::vec3 objectID = ReadPixel(GetMouseViewportPos().x, GetMouseViewportPos().y); m_SelectedEntity = Hildur::Renderer::GetEntityFromID((uint32_t)(objectID.x * 255)); std::string name = m_SelectedEntity != nullptr ? m_SelectedEntity->m_Name : "The void!"; HR_CORE_WARN("Click in viewport! (this is supposed to happen), coords: ({0}, {1}), Object ID: {2}, Object name: {3}", GetMouseViewportPosNorm().x, GetMouseViewportPosNorm().y, objectID.x, name.c_str()); } return false; } bool Viewport::OnMouseScrolled(Hildur::MouseScrolledEvent& e) { return false; } void Viewport::UpdateSize() { } glm::vec3 Viewport::ReadPixel(uint32_t x, uint32_t y) { return m_ObjectIDFrameBuffer->ReadPixel("ID", x, y); } }
30.657143
206
0.731827
FelipeCalin
7190cdfec8b8840ab8a822b73e34a51a587241eb
5,883
cpp
C++
samples/flocking.cpp
jdduke/fpcpp
d9dba8aed135c85383a733fba3537d6afca5ddd7
[ "MIT" ]
16
2015-08-05T09:31:55.000Z
2021-04-18T02:23:46.000Z
samples/flocking.cpp
jdduke/fpcpp
d9dba8aed135c85383a733fba3537d6afca5ddd7
[ "MIT" ]
null
null
null
samples/flocking.cpp
jdduke/fpcpp
d9dba8aed135c85383a733fba3537d6afca5ddd7
[ "MIT" ]
null
null
null
///////////////////////////////////////////////////////////////////////////// // Copyright (c) 2012, Jared Duke. // This code is released under the MIT License. // www.opensource.org/licenses/mit-license.php ///////////////////////////////////////////////////////////////////////////// #include <fpcpp.h> #include <iostream> #include <time.h> #define _USE_MATH_DEFINES #include <math.h> #include <array> #if WIN32 #include <Windows.h> inline void idle(DWORD milliseconds) { Sleep(milliseconds); } #else #include <unistd.h> inline void idle(size_t microseconds) { usleep(microseconds*1000); } #endif /////////////////////////////////////////////////////////////////////////// enum { BOIDS = 25, X = 80, Y = 30, NEIGHBORHOOD = 15, AVOIDANCE = 5, }; /////////////////////////////////////////////////////////////////////////// using fp::fst; using fp::snd; using fp::index; using fp::types; typedef types<float,float>::pair P; typedef types<float,float>::pair D; typedef types<P, D>::pair Boid; typedef types<Boid>::list Boids; P pos(const Boid& b) { return fst(b); } D dir(const Boid& b) { return snd(b); } namespace std { template< typename T > std::pair<T,T> operator+(const std::pair<T,T>& a, const std::pair<T,T>& b) { return std::make_pair( fst(a) + fst(b), snd(b) + snd(b) ); } template< typename T > std::pair<T,T> operator-(const std::pair<T,T>& a, const std::pair<T,T>& b) { return std::make_pair( fst(a) - fst(b), snd(b) - snd(b) ); } template< typename T > std::pair<T,T> operator*(const std::pair<T,T>& a, T b) { return std::make_pair( fst(a) * b, snd(a) * b ); } template< typename T > std::pair<T,T> operator/(const std::pair<T,T>& a, T b) { return std::make_pair( fst(a) / b, snd(a) / b ); } } using namespace std; template <typename T> inline float length( const T& t ) { const let x = fst(t); const let y = snd(t); return sqrtf( (float)x*x + (float)y*y ); } template <typename T> inline T normalize( const T& t ) { const let tLength = length( t ); return tLength > 0.f ? t / tLength : t; } template <typename T> inline float dist( const T& a, const T& b) { return length( a - b ); } template <typename T, typename U, typename V> inline T clamp(const T& value, const U& low, const V& high) { return value < low ? low : (value > high ? high : value); } template <typename T> inline T fmod_(T t, T modulus) { return t >= (T)0 ? fmod(t, modulus) : modulus - fmod(-t, modulus); } template <typename T, typename U> inline T pmod( const T& t, U fstMod, U sndMod ) { return T( fmod_( fst(t), fstMod ), fmod_( snd(t), sndMod ) ); } /////////////////////////////////////////////////////////////////////////// D avoidance( const Boid& boid, const Boids& neighbors ) { return fp::sum( fp::map( [&](const Boid& otherBoid) -> D { const let avoidanceWeight = 1.f - (dist( pos(boid), pos(otherBoid) ) / NEIGHBORHOOD); return normalize( pos(boid) - pos(otherBoid) ) * avoidanceWeight + dir( boid ) * (1.f - avoidanceWeight); }, neighbors) ) / (float)neighbors.size(); } D alignment( const Boid& boid, const Boids& neighbors ) { const let avgDir = fp::sum( fp::map( &dir, neighbors )) / (float)neighbors.size(); return (avgDir + dir( boid )) *.5f; } D cohesion( const Boid& boid, const Boids& neighbors ) { const let avgPos = fp::sum( fp::map( &pos, neighbors) ) / (float)neighbors.size(); return (normalize( avgPos - pos( boid ) ) + dir( boid )) *.5f; } Boid evolve( const Boid& boid, const Boids& neighbors ) { let newDir = dir( boid ); if ( fp::length(neighbors) != 0) { std::array<float, 3> weights = { .5f, .2f, .3f }; newDir = normalize( avoidance( boid, neighbors ) * weights[0] + alignment( boid, neighbors ) * weights[1] + cohesion( boid, neighbors ) * weights[2] ); } let newPos = pmod( pos( boid ) + newDir, (float)X, (float)Y); return Boid( newPos, newDir ); } /////////////////////////////////////////////////////////////////////////// Boids evolve( const Boids& boids, size_t x, size_t y ) { return fp::map( [=,&boids]( const Boid& boid ) -> Boid { let neighbors = fp::filter( [=,&boid]( const Boid& otherBoid ) { return ( boid != otherBoid ) && ( dist( pos(boid), pos(otherBoid) ) < NEIGHBORHOOD ); }, boids ); return evolve( boid, neighbors ); }, boids); } #ifndef M_PI #define M_PI 3.14159265358979323846 #endif int main(int argc, char **argv) { srand((unsigned)time((time_t*)NULL)); std::array<char, 8> cardinalToChar = { '-', '/', '|', '\\', '-', '/', '|', '\\' }; let showCell = [&]( const D& v ) -> char { if (length(v) < .25) return ' '; let theta = atan2f( snd(v), fst(v) ); theta = theta < 0.f ? theta + 2.f*(float)M_PI : theta; let const index = (int)(theta * (4.f/M_PI)) % cardinalToChar.size(); return cardinalToChar[index]; }; let boids = fp::zip(fp::zip(fp::uniformN(BOIDS, 0.f, (float)X), fp::uniformN(BOIDS, 0.f, (float)Y)), fp::zip(fp::uniformN(BOIDS, -1.f,1.f), fp::uniformN(BOIDS, -1.f,1.f))); typedef std::array< D, X > Row; typedef std::array< Row, Y > Grid; while (true) { boids = evolve(boids, X, Y); Grid grid; for (size_t i = 0; i < fp::length(boids); ++i) { let x = (int)fst( pos(index(i,boids)) ) % X; let y = (int)snd( pos(index(i,boids)) ) % Y; grid[y][x] = grid[y][x] + dir( index(i,boids) ); } let showRow = [=](const Row& r) -> std::string { return fp::show(fp::map( showCell, r) ); }; std::cout << std::endl << fp::foldl1( [](const std::string& a, const std::string& b) { return a + "\n" + b; }, fp::map( showRow, grid )) << std::endl << std::endl; } return 0; }
29.712121
97
0.536291
jdduke
7193bd769bf53d713ca1f480c94054ab7e371e06
683
cpp
C++
tools/ifaceed/ifaceed/scripting/querytable.cpp
mamontov-cpp/saddy
f20a0030e18af9e0714fe56c19407fbeacc529a7
[ "BSD-2-Clause" ]
58
2015-08-09T14:56:35.000Z
2022-01-15T22:06:58.000Z
tools/ifaceed/ifaceed/scripting/querytable.cpp
mamontov-cpp/saddy-graphics-engine-2d
e25a6637fcc49cb26614bf03b70e5d03a3a436c7
[ "BSD-2-Clause" ]
245
2015-08-08T08:44:22.000Z
2022-01-04T09:18:08.000Z
tools/ifaceed/ifaceed/scripting/querytable.cpp
mamontov-cpp/saddy
f20a0030e18af9e0714fe56c19407fbeacc529a7
[ "BSD-2-Clause" ]
23
2015-12-06T03:57:49.000Z
2020-10-12T14:15:50.000Z
#include "querytable.h" #include <QVector> #include <renderer.h> #include <db/dbdatabase.h> #include <db/dbtable.h> QVector<unsigned long long> scripting::query_table( const sad::String& table, const sad::String& type_of_objects ) { sad::db::Database* db = sad::Renderer::ref()->database(""); sad::Vector<sad::db::Object*> objects; db->table(table)->objects(objects); QVector<unsigned long long> result; for(size_t i = 0; i < objects.size(); i++) { if (objects[i]->Active && objects[i]->isInstanceOf(type_of_objects)) { result << objects[i]->MajorId; } } return result; }
22.766667
77
0.590044
mamontov-cpp
7195d91b67b3890eda661e549e9f0936879e9562
1,105
cpp
C++
thread/example3.cpp
TedLyngmo/lyn_threads
576230ded5d5f8f0b17aabec870a7201f4f9108e
[ "Unlicense" ]
null
null
null
thread/example3.cpp
TedLyngmo/lyn_threads
576230ded5d5f8f0b17aabec870a7201f4f9108e
[ "Unlicense" ]
null
null
null
thread/example3.cpp
TedLyngmo/lyn_threads
576230ded5d5f8f0b17aabec870a7201f4f9108e
[ "Unlicense" ]
null
null
null
#include "lyn/thread.hpp" #include <chrono> #include <iostream> #include <thread> // event example lyn::thread::event<true> ev; // true = auto reset int state = 0; void a_thread() { // waits for ev to be signaled // runs the lambda // sets ev to non-signaled bool executed = ev.wait_for(std::chrono::milliseconds(5), []{ ++state; std::cout << "second TRUE\n"; }); if(not executed) { ev.wait([]{ std::cout << "second FALSE\n"; }); } ev.wait([]{ std::cout << "fourth: " << ++state << '\n'; }); // unguarded work } int main() { for(int i=0; i < 1000; ++i) { auto th = std::thread(a_thread); // runs the lambda // sets ev to signaled std::this_thread::sleep_for(std::chrono::milliseconds(5)); ev.set([]{ std::cout << "first " << ++state << '\n'; }); ev.wait_for_reset([]{ std::cout << "reset\n"; }); ev.set([]{ std::cout << "third " << ++state << '\n'; }); th.join(); } }
19.385965
66
0.472398
TedLyngmo
71969823bed10163f644eff544d814836e58e2da
52,395
cc
C++
Modules/Registration/src/irtkRegisteredImage.cc
kevin-keraudren/IRTK
ce329b7f58270b6c34665dcfe9a6e941649f3b94
[ "Apache-2.0" ]
3
2018-10-04T19:32:36.000Z
2021-09-02T07:37:30.000Z
Modules/Registration/src/irtkRegisteredImage.cc
kevin-keraudren/IRTK
ce329b7f58270b6c34665dcfe9a6e941649f3b94
[ "Apache-2.0" ]
null
null
null
Modules/Registration/src/irtkRegisteredImage.cc
kevin-keraudren/IRTK
ce329b7f58270b6c34665dcfe9a6e941649f3b94
[ "Apache-2.0" ]
4
2016-03-17T02:55:00.000Z
2018-02-03T05:40:05.000Z
/* The Image Registration Toolkit (IRTK) * * Copyright 2008-2015 Imperial College London * * 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 <irtkRegisteredImage.h> #include <irtkGaussianBlurring.h> #include <irtkGradientImageFilter.h> #include <irtkHessianImageFilter.h> #include <irtkVoxelFunction.h> #include <irtkImageGradientFunction.h> #include <irtkLinearInterpolateImageFunction.hxx> // incl. inline definitions #include <irtkFastLinearImageGradientFunction.hxx> // incl. inline definitions // ----------------------------------------------------------------------------- irtkRegisteredImage::irtkRegisteredImage() : _InputImage (NULL), _InputGradient (NULL), _InputHessian (NULL), _Transformation (NULL), _InterpolationMode (Interpolation_FastLinear), _ExtrapolationMode (Extrapolation_Default), _WorldCoordinates (NULL), _ImageToWorld (NULL), _ExternalDisplacement (NULL), _FixedDisplacement (NULL), _Displacement (NULL), _CacheWorldCoordinates (true), // FIXME: MUST be true to also cache anything else... _CacheFixedDisplacement(false), // by default, only if required by transformation _CacheDisplacement (false), // (c.f. irtkTransformation::RequiresCachingOfDisplacements) _SelfUpdate (true), _MinIntensity (numeric_limits<double>::quiet_NaN()), _MaxIntensity (numeric_limits<double>::quiet_NaN()), _GradientSigma (.0), _HessianSigma (.0), _PrecomputeDerivatives (false), _NumberOfActiveLevels (0), _NumberOfPassiveLevels (0) { for (int i = 0; i < 13; ++i) _Offset[i] = -1; } // ----------------------------------------------------------------------------- irtkRegisteredImage::irtkRegisteredImage(const irtkRegisteredImage &other) : irtkGenericImage<double>(other), _InputImage (other._InputImage), _InputGradient (other._InputGradient ? new GradientImageType(*other._InputGradient) : NULL), _InputHessian (other._InputHessian ? new GradientImageType(*other._InputHessian) : NULL), _Transformation (other._Transformation), _InterpolationMode (other._InterpolationMode), _ExtrapolationMode (other._ExtrapolationMode), _WorldCoordinates (other._WorldCoordinates), _ImageToWorld (other._ImageToWorld ? new irtkWorldCoordsImage (*other._ImageToWorld) : NULL), _ExternalDisplacement (other._ExternalDisplacement), _FixedDisplacement (other._FixedDisplacement ? new DisplacementImageType(*other._FixedDisplacement) : NULL), _Displacement (other._Displacement ? new DisplacementImageType(*other._Displacement) : NULL), _CacheWorldCoordinates (other._CacheWorldCoordinates), _CacheFixedDisplacement(other._CacheFixedDisplacement), _CacheDisplacement (other._CacheDisplacement), _SelfUpdate (other._SelfUpdate), _MinIntensity (other._MinIntensity), _MaxIntensity (other._MaxIntensity), _GradientSigma (other._GradientSigma), _HessianSigma (other._HessianSigma), _PrecomputeDerivatives (other._PrecomputeDerivatives), _NumberOfActiveLevels (other._NumberOfActiveLevels), _NumberOfPassiveLevels (other._NumberOfPassiveLevels) { memcpy(_Offset, other._Offset, 13 * sizeof(int)); } // ----------------------------------------------------------------------------- irtkRegisteredImage &irtkRegisteredImage::operator =(const irtkRegisteredImage &other) { irtkGenericImage<double>::operator =(other); _InputImage = other._InputImage; _InputGradient = other._InputGradient ? new GradientImageType(*other._InputGradient) : NULL; _InputHessian = other._InputHessian ? new GradientImageType(*other._InputHessian) : NULL; _Transformation = other._Transformation; _InterpolationMode = other._InterpolationMode; _ExtrapolationMode = other._ExtrapolationMode; _WorldCoordinates = other._WorldCoordinates; _ImageToWorld = other._ImageToWorld ? new irtkWorldCoordsImage (*other._ImageToWorld) : NULL; _ExternalDisplacement = other._ExternalDisplacement; _FixedDisplacement = other._FixedDisplacement ? new DisplacementImageType(*other._FixedDisplacement) : NULL; _Displacement = other._Displacement ? new DisplacementImageType(*other._Displacement) : NULL; _CacheWorldCoordinates = other._CacheWorldCoordinates; _CacheFixedDisplacement = other._CacheFixedDisplacement; _CacheDisplacement = other._CacheDisplacement; _SelfUpdate = other._SelfUpdate; _MinIntensity = other._MinIntensity; _MaxIntensity = other._MaxIntensity; _GradientSigma = other._GradientSigma; _HessianSigma = other._HessianSigma; _PrecomputeDerivatives = other._PrecomputeDerivatives; _NumberOfActiveLevels = other._NumberOfActiveLevels; _NumberOfPassiveLevels = other._NumberOfPassiveLevels; memcpy(_Offset, other._Offset, 13 * sizeof(int)); return *this; } // ----------------------------------------------------------------------------- irtkRegisteredImage::~irtkRegisteredImage() { if (_ImageToWorld != _WorldCoordinates) delete _ImageToWorld; delete _FixedDisplacement; delete _Displacement; if (_InputGradient != _InputImage) delete _InputGradient; delete _InputHessian; } // ----------------------------------------------------------------------------- void irtkRegisteredImage::Initialize(const irtkImageAttributes &attr, int t) { IRTK_START_TIMING(); // Clear possibly previously allocated displacement cache if (!_Transformation) Delete(_Displacement); // Check if input image is set if (!_InputImage) { cerr << "irtkRegisteredImage::Initialize: Missing input image" << endl; exit(1); } // Initialize base class if (attr._t > 1) { cerr << "irtkRegisteredImage::Initialize: Split multi-channel image/temporal sequence up into separate 2D/3D images" << endl; exit(1); } if (t == 0) t = 1; if (t != 1 && t != 4 && t != 10 && t != 13) { cerr << "irtkRegisteredImage::Initialize: Number of registered image channels must be either 1, 4, 10 or 13" << endl; exit(1); } irtkGenericImage<double>::Initialize(attr, t); // Set background value/foreground mask if (_InputImage->HasBackgroundValue()) { this->PutBackgroundValueAsDouble(_InputImage->GetBackgroundValueAsDouble()); } else { this->PutBackgroundValueAsDouble(MIN_GREY); } // Pre-compute world coordinates if (_WorldCoordinates) { if (_ImageToWorld != _WorldCoordinates) { delete _ImageToWorld; _ImageToWorld = _WorldCoordinates; } } else if (_CacheWorldCoordinates) { if (!_ImageToWorld) _ImageToWorld = new irtkWorldCoordsImage(); this->ImageToWorld(*_ImageToWorld, true /* i.e., always 3D vectors */); } else { Delete(_ImageToWorld); } // Determine number of active (changing) and passive (fixed) levels bool cache_fixed = !_ExternalDisplacement && _CacheFixedDisplacement; const irtkMultiLevelTransformation *mffd = NULL; if ((mffd = dynamic_cast<const irtkMultiLevelTransformation *>(_Transformation))) { _NumberOfPassiveLevels = 0; for (int l = 0; l < mffd->NumberOfLevels(); ++l) { if (mffd->LocalTransformationIsActive(l)) break; if (mffd->GetLocalTransformation(l)->RequiresCachingOfDisplacements()) cache_fixed = true; ++_NumberOfPassiveLevels; } _NumberOfActiveLevels = mffd->NumberOfLevels() - _NumberOfPassiveLevels; if (_NumberOfPassiveLevels == 0 && mffd->GetGlobalTransformation()->IsIdentity()) { _NumberOfPassiveLevels = -1; } } else if (_Transformation) { _NumberOfActiveLevels = 1; _NumberOfPassiveLevels = -1; } else { _NumberOfActiveLevels = 0; _NumberOfPassiveLevels = -1; } // Pre-compute fixed displacements if (cache_fixed && _NumberOfPassiveLevels >= 0) { if (!_FixedDisplacement) _FixedDisplacement = new DisplacementImageType(); _FixedDisplacement->Initialize(attr, 3); mffd->Displacement(-1, _NumberOfPassiveLevels, *_FixedDisplacement, _InputImage->GetTOrigin(), _ImageToWorld); } else { Delete(_FixedDisplacement); } // Pre-compute input derivatives if (t > 1) ComputeInputGradient(_GradientSigma); if (t > 4) ComputeInputHessian (_HessianSigma ); // Initialize offsets of registered image channels _Offset[0] = 0; _Offset[1] = this->NumberOfVoxels(); for (int c = 2; c < 13; ++c) _Offset[c] = _Offset[c-1] + _Offset[1]; // Attention: Initialization of actual image content must be forced upon first // Update call. This is initiated by the irtkImageSimilarity::Update // function which in turn is called before the first energy gradient // evaluation (see irtkGradientDescent::Gradient). IRTK_DEBUG_TIMING(4, "initialization of " << (_Transformation ? "moving" : "fixed") << " image"); } // ----------------------------------------------------------------------------- void irtkRegisteredImage::ComputeInputGradient(double sigma) { IRTK_START_TIMING(); // Smooth input image InputImageType *blurred_image = _InputImage; if (sigma > .0) { blurred_image = new InputImageType; if (this->HasBackgroundValue()) { blurred_image->PutBackgroundValueAsDouble(this->GetBackgroundValueAsDouble()); irtkGaussianBlurringWithPadding<double> blurring(sigma * _InputImage->GetXSize(), sigma * _InputImage->GetYSize(), sigma * _InputImage->GetZSize(), this->GetBackgroundValueAsDouble()); blurring.SetInput (_InputImage); blurring.SetOutput(blurred_image); blurring.Run(); } else { irtkGaussianBlurring<double> blurring(sigma * _InputImage->GetXSize(), sigma * _InputImage->GetYSize(), sigma * _InputImage->GetZSize()); blurring.SetInput (_InputImage); blurring.SetOutput(blurred_image); blurring.Run(); } } if (_PrecomputeDerivatives) { // Compute image gradient using finite differences typedef irtkGradientImageFilter<GradientImageType::VoxelType> FilterType; FilterType filter(FilterType::GRADIENT_VECTOR); filter.SetInput (blurred_image); filter.SetOutput(_InputGradient ? _InputGradient : new GradientImageType); // Note that even though the original nreg2 implementation did divide // the image gradient initially by the voxel size, the similarity gradient // was reoriented then by irtkImageRegistration2::EvaluateGradient using the // upper 3x3 image to world matrix. This effectively multiplied by the voxel // size again which is equivalent to only reorienting the image gradient // computed w.r.t. the voxel coordinates, i.e., leaving the magnitude of the // gradient in voxel units rather than world units (i.e., mm's). filter.UseVoxelSize (version.Major() >= 3); filter.UseOrientation(true); if (this->HasBackgroundValue()) { filter.SetPadding(this->GetBackgroundValueAsDouble()); } filter.Run(); _InputGradient = filter.GetOutput(); _InputGradient->PutTSize(.0); _InputGradient->PutBackgroundValueAsDouble(.0); if (blurred_image != _InputImage) delete blurred_image; IRTK_DEBUG_TIMING(5, "computation of 1st order image derivatives"); } else { delete _InputGradient; _InputGradient = blurred_image; IRTK_DEBUG_TIMING(5, "low-pass filtering of image for 1st order derivatives"); } } // ----------------------------------------------------------------------------- void irtkRegisteredImage::ComputeInputHessian(double sigma) { IRTK_START_TIMING(); // Smooth input image InputImageType *blurred_image = _InputImage; if (sigma > .0) { blurred_image = new InputImageType; if (this->HasBackgroundValue()) { blurred_image->PutBackgroundValueAsDouble(this->GetBackgroundValueAsDouble()); irtkGaussianBlurringWithPadding<double> blurring(sigma * _InputImage->GetXSize(), sigma * _InputImage->GetYSize(), sigma * _InputImage->GetZSize(), this->GetBackgroundValueAsDouble()); blurring.SetInput (_InputImage); blurring.SetOutput(blurred_image); blurring.Run(); } else { irtkGaussianBlurring<double> blurring(sigma * _InputImage->GetXSize(), sigma * _InputImage->GetYSize(), sigma * _InputImage->GetZSize()); blurring.SetInput (_InputImage); blurring.SetOutput(blurred_image); blurring.Run(); } } // Compute 2nd order image derivatives using finite differences typedef irtkHessianImageFilter<HessianImageType::VoxelType> FilterType; FilterType filter(FilterType::HESSIAN_MATRIX); filter.SetInput (blurred_image); filter.SetOutput (_InputHessian ? _InputHessian : new HessianImageType); filter.UseVoxelSize (true); filter.UseOrientation(true); if (this->HasBackgroundValue()) { filter.SetPadding(this->GetBackgroundValueAsDouble()); } filter.Run(); _InputHessian = filter.GetOutput(); _InputHessian->PutTSize(.0); _InputHessian->PutBackgroundValueAsDouble(.0); if (blurred_image != _InputImage) delete blurred_image; IRTK_DEBUG_TIMING(5, "computation of 2nd order image derivatives"); } // ============================================================================= // Update // ============================================================================= // ----------------------------------------------------------------------------- // Base class of voxel transformation functors struct Transformer { typedef irtkWorldCoordsImage::VoxelType CoordType; /// Constructor Transformer() : _Input (NULL), _Transformation(NULL), _Output (NULL), _y(0), _z(0) {} /// Initialize data members void Initialize(irtkRegisteredImage *o, const irtkBaseImage *i, const irtkTransformation *t) { _Input = i; _t = i->GetTOrigin(); _t0 = o->GetTOrigin(); _Transformation = t; _Output = o; _y = o->GetX() * o->GetY() * o->GetZ(); _z = 2 * _y; } /// Transform output voxel void operator ()(double &x, double &y, double &z) { _Output->ImageToWorld(x, y, z); _Transformation->Transform(x, y, z, _t, _t0); _Input->WorldToImage(x, y, z); } /// Transform output voxel using pre-computed world coordinates void operator ()(double &x, double &y, double &z, const CoordType *wc) { x = wc[_x], y = wc[_y], z = wc[_z]; _Transformation->Transform(x, y, z, _t, _t0); _Input->WorldToImage(x, y, z); } /// Transform output voxel using pre-computed world coordinates and displacements void operator ()(double &x, double &y, double &z, const CoordType *wc, const double *dx) { x = wc[_x] + dx[_x]; y = wc[_y] + dx[_y]; z = wc[_z] + dx[_z]; _Input->WorldToImage(x, y, z); } protected: const irtkBaseImage *_Input; const irtkTransformation *_Transformation; irtkRegisteredImage *_Output; static const int _x = 0; ///< Offset of x component int _y; ///< Offset of y component int _z; ///< Offset of z component double _t; ///< Time point double _t0; ///< Time point of target }; // ----------------------------------------------------------------------------- // Transformer used when no fixed transformation is cached struct DefaultTransformer : public Transformer { using Transformer::operator(); /// As this transformer is only used when no fixed transformation is cached, /// this overloaded operator should never be invoked void operator ()(double &, double &, double &, const CoordType *, const double *, const double *) { cerr << "irtkRegisteredImage::DefaultTransformer used even though _FixedDisplacement assumed to be NULL ?!?" << endl; exit(1); } }; // ----------------------------------------------------------------------------- // Transform output voxel using additive composition of displacements struct AdditiveTransformer : public Transformer { using Transformer::operator(); /// Transform output voxel using pre-computed world coordinates and displacements void operator ()(double &x, double &y, double &z, const CoordType *wc, const double *d1, const double *d2) { x = wc[_x] + d1[_x] + d2[_x]; y = wc[_y] + d1[_y] + d2[_y]; z = wc[_z] + d1[_z] + d2[_z]; _Input->WorldToImage(x, y, z); } }; // ----------------------------------------------------------------------------- // Transform output voxel using fluid composition of displacements struct FluidTransformer : public Transformer { using Transformer::operator(); /// Transform output voxel using pre-computed world coordinates and displacements /// /// Because fluid composition of displacement fields would require interpolation, /// let irtkTransformation::Displacement handle the fluid composition already when /// computing the second displacement field. void operator ()(double &x, double &y, double &z, const CoordType *wc, const double *, const double *dx) { x = wc[_x] + dx[_x]; y = wc[_y] + dx[_y]; z = wc[_z] + dx[_z]; _Input->WorldToImage(x, y, z); } }; // ----------------------------------------------------------------------------- // Transformer used when no transformation is set or custom displacement field given struct FixedTransformer : public Transformer { // Visual Studio 2013 has troubles resolving // void operator()(double&, double&, double&) // if a using Transformer::operator() statement is used because it is also // defined by this subclass. Instead, just re-implement the only other // overloaded version as well. /// Transform output voxel void operator ()(double &x, double &y, double &z) { _Output->ImageToWorld(x, y, z); _Input ->WorldToImage(x, y, z); } /// Transform output voxel using pre-computed world coordinates void operator ()(double &x, double &y, double &z, const CoordType *wc) { x = wc[_x], y = wc[_y], z = wc[_z]; _Input->WorldToImage(x, y, z); } /// Transform output voxel using pre-computed world coordinates and displacements void operator ()(double &x, double &y, double &z, const CoordType *wc, const double *dx) { Transformer::operator()(x, y, z, wc, dx); } /// As this transformer is only used when no transformation is set, /// this overloaded operator should never be invoked void operator ()(double &, double &, double &, const CoordType *, const double *, const double *) { cerr << "irtkRegisteredImage::FixedTransformer(..., d1, d2) used even though _Transformation assumed to be NULL ?!?" << endl; exit(1); } }; // ----------------------------------------------------------------------------- // Auxiliary function to allocate and initialize image interpolate function template <class ImageFunction> void New( ImageFunction *&f, const irtkBaseImage *image, #ifndef NDEBUG irtkInterpolationMode interp, #else irtkInterpolationMode, #endif irtkExtrapolationMode extrap, double padding, double default_value) { if (image) { f = new ImageFunction(); #ifndef NDEBUG interp = InterpolationWithoutPadding(interp); if (interp == Interpolation_FastLinear) interp = Interpolation_Linear; irtkInterpolationMode mode = f->InterpolationMode(); if (mode == Interpolation_FastLinear) mode = Interpolation_Linear; if (mode != interp) { cout << endl; cerr << __FILE__ << ":" << __LINE__ << ": Mismatch of interpolation mode: expected \"" << ToString(interp) << "\", but got \"" << ToString(mode) << "\"" << endl; exit(1); } #endif irtkImageGradientFunction *g = dynamic_cast<irtkImageGradientFunction *>(f); if (g) g->WrtWorld(true); f->Input(const_cast<irtkBaseImage *>(image)); if (extrap != Extrapolation_Default) { f->Extrapolator(f->New(extrap, image), true); } f->DefaultValue(default_value); f->Initialize(); if (f->Extrapolator()) f->Extrapolator()->DefaultValue(padding); } } template <> void New(irtkInterpolateImageFunction *&f, const irtkBaseImage *image, irtkInterpolationMode interp, irtkExtrapolationMode extrap, double padding, double default_value) { if (image) { f = irtkInterpolateImageFunction::New(interp, const_cast<irtkBaseImage *>(image)); f->Input(const_cast<irtkBaseImage *>(image)); if (extrap != Extrapolation_Default) { f->Extrapolator(f->New(extrap, image), true); } f->DefaultValue(default_value); f->Initialize(); if (f->Extrapolator()) f->Extrapolator()->DefaultValue(padding); } } template <> void New(irtkImageGradientFunction *&f, const irtkBaseImage *image, irtkInterpolationMode interp, irtkExtrapolationMode extrap, double padding, double default_value) { if (image) { f = irtkImageGradientFunction::New(interp, const_cast<irtkBaseImage *>(image)); f->WrtWorld(true); f->Input(const_cast<irtkBaseImage *>(image)); if (extrap != Extrapolation_Default) { f->Extrapolator(f->New(extrap, image), true); } f->DefaultValue(default_value); f->Initialize(); if (f->Extrapolator()) f->Extrapolator()->DefaultValue(padding); } } // TODO: Add template specialization for irtkImageHessianFunction // ----------------------------------------------------------------------------- // Base class of voxel interpolation functions template <class IntensityFunction, class GradientFunction, class HessianFunction> class Interpolator { protected: IntensityFunction *_IntensityFunction; GradientFunction *_GradientFunction; HessianFunction *_HessianFunction; bool _InterpolateWithPadding; double _PaddingValue; double _MinIntensity; double _MaxIntensity; double _RescaleSlope; double _RescaleIntercept; int _NumberOfVoxels; int _NumberOfChannels; irtkVector3D<int> _InputSize; public: /// Constructor Interpolator() : _IntensityFunction (NULL), _GradientFunction (NULL), _HessianFunction (NULL), _InterpolateWithPadding(false), _PaddingValue (-1), _MinIntensity (numeric_limits<double>::quiet_NaN()), _MaxIntensity (numeric_limits<double>::quiet_NaN()), _RescaleSlope (1.0), _RescaleIntercept (.0), _NumberOfVoxels (0), _NumberOfChannels (0) {} /// Copy constructor Interpolator(const Interpolator &other) : _IntensityFunction (NULL), _GradientFunction (NULL), _HessianFunction (NULL), _InterpolateWithPadding(other._InterpolateWithPadding), _PaddingValue (other._PaddingValue), _MinIntensity (other._MinIntensity), _MaxIntensity (other._MaxIntensity), _RescaleSlope (other._RescaleSlope), _RescaleIntercept (other._RescaleIntercept), _NumberOfVoxels (other._NumberOfVoxels), _NumberOfChannels (other._NumberOfChannels), _InputSize (other._InputSize) { if (other._IntensityFunction) { const irtkBaseImage *f = other._IntensityFunction->Input(); const double f_bg = (f->HasBackgroundValue() ? f->GetBackgroundValueAsDouble() : MIN_GREY); New<IntensityFunction>(_IntensityFunction, f, other._IntensityFunction->InterpolationMode(), other._IntensityFunction->ExtrapolationMode(), f_bg, f_bg); } if (other._GradientFunction) { const irtkBaseImage *g = other._GradientFunction->Input(); const double g_bg = (g->HasBackgroundValue() ? g->GetBackgroundValueAsDouble() : .0); New<GradientFunction>(_GradientFunction, g, other._GradientFunction->InterpolationMode(), other._GradientFunction->ExtrapolationMode(), g_bg, .0); } if (other._HessianFunction) { const irtkBaseImage *h = other._HessianFunction->Input(); const double h_bg = (h->HasBackgroundValue() ? h->GetBackgroundValueAsDouble() : .0); New<HessianFunction>(_HessianFunction, h, other._HessianFunction->InterpolationMode(), other._HessianFunction->ExtrapolationMode(), h_bg, .0); } } /// Destructor ~Interpolator() { Delete(_IntensityFunction); Delete(_GradientFunction); Delete(_HessianFunction); } /// Initialize data members void Initialize(irtkRegisteredImage *o, const irtkBaseImage *f, const irtkBaseImage *g, const irtkBaseImage *h, double omin = numeric_limits<double>::quiet_NaN(), double omax = numeric_limits<double>::quiet_NaN()) { _InterpolateWithPadding = (ToString(o->InterpolationMode()).find("with padding") != string::npos); if (o->HasBackgroundValue()) _PaddingValue = o->GetBackgroundValueAsDouble(); _NumberOfVoxels = o->GetX() * o->GetY() * o->GetZ(); _NumberOfChannels = o->GetT(); const double f_bg = (f->HasBackgroundValue() ? f->GetBackgroundValueAsDouble() : MIN_GREY); const double g_bg = (g && g->HasBackgroundValue() ? g->GetBackgroundValueAsDouble() : .0); const double h_bg = (h && h->HasBackgroundValue() ? h->GetBackgroundValueAsDouble() : .0); New<IntensityFunction>(_IntensityFunction, f, o->InterpolationMode(), o->ExtrapolationMode(), f_bg, f_bg); New<GradientFunction >(_GradientFunction, g, o->InterpolationMode(), Extrapolation_Default, g_bg, .0); New<HessianFunction >(_HessianFunction, h, o->InterpolationMode(), Extrapolation_Default, h_bg, .0); _MinIntensity = omin; _MaxIntensity = omax; if (!IsNaN(omin) || !IsNaN(omax)) { double imin, imax; f->GetMinMaxAsDouble(imin, imax); if (IsNaN(omin)) omin = imin; if (IsNaN(omax)) omax = imax; _RescaleSlope = (omax - omin) / (imax - imin); _RescaleIntercept = omin - _RescaleSlope * imin; } else { _RescaleSlope = 1.0; _RescaleIntercept = 0.0; } _InputSize = irtkVector3D<int>(f->X(), f->Y(), f->Z()); } /// Determine interpolation mode at given location /// /// \retval 1 Output channels should be interpolated without boundary checks. /// \retval 0 Output channels should be interpolated at boundary. /// \retval -1 Output channels should be padded. /// /// \note The return value 0 was used in a previous implementation but is /// currently unused. The mode is either 1 (inside) or -1 (outside). int InterpolationMode(double x, double y, double z, bool check_value = true) const { // Use bounds suitable also for _GradientFunction and _HessianFunction. // The linear image gradient function requires more strict bounds than // the linear image intensity interpolation function. bool inside = (.5 < x && x < _InputSize._x - 1.5 && .5 < y && y < _InputSize._y - 1.5); if (inside) { if (_InputSize._z == 1) inside = fequal(z, .0, 1e-3); else inside = (.5 < z && z < _InputSize._z - 1.5); if (inside && check_value) { if (_InterpolateWithPadding) { double value = _IntensityFunction->EvaluateWithPadding(x, y, z); if (value == _IntensityFunction->DefaultValue()) return -1; } } return inside ? 1 : -1; } return -1; } /// Interpolate input intensity function /// /// \return The interpolation mode, i.e., result of inside/outside domain check. int InterpolateIntensity(double x, double y, double z, double *o) { // Check if location is inside image domain int mode = InterpolationMode(x, y, z, false); if (mode == 1) { // Either interpolate using the input padding value to exclude background if (_InterpolateWithPadding) { *o = _IntensityFunction->EvaluateWithPaddingInside(x, y, z); // or simply ignore the input background value as done by nreg2 } else { *o = _IntensityFunction->EvaluateInside(x, y, z); } // Set background to output padding value if (*o == _IntensityFunction->DefaultValue()) { *o = _PaddingValue; if (_InterpolateWithPadding) return -1; // Rescale foreground to desired [min, max] range } else if (_RescaleSlope != 1.0 || _RescaleIntercept != .0) { *o = (*o) * _RescaleSlope + _RescaleIntercept; if (*o < _MinIntensity) *o = _MinIntensity; else if (*o > _MaxIntensity) *o = _MaxIntensity; } // Otherwise, set output intensity to outside value } else { *o = _PaddingValue; } // Pass inside/outside check result on to derivative interpolation // functions such that these boundary checks are only done once. // This requires the same interpolation mode for all channels. return mode; } /// Interpolate 1st order derivatives of input intensity function void InterpolateGradient(double x, double y, double z, double *o, int mode = 0) { o += _NumberOfVoxels; switch (mode) { // Inside case 1: if (_InterpolateWithPadding) { _GradientFunction->EvaluateWithPaddingInside(o, x, y, z, _NumberOfVoxels); } else { _GradientFunction->EvaluateInside(o, x, y, z, _NumberOfVoxels); } break; // Outside/Boundary default: for (int c = 1; c <= 3; ++c, o += _NumberOfVoxels) *o = .0; } } /// Interpolate 2nd order derivatives of input intensity function void InterpolateHessian(double x, double y, double z, double *o, int mode = 0) { o += 4 * _NumberOfVoxels; switch (mode) { // Inside case 1: if (_InterpolateWithPadding) { _HessianFunction->EvaluateWithPaddingInside(o, x, y, z, _NumberOfVoxels); } else { _HessianFunction->EvaluateInside(o, x, y, z, _NumberOfVoxels); } break; // Outside/Boundary default: for (int c = 4; c < _NumberOfChannels; ++c, o += _NumberOfVoxels) *o = .0; } } }; // ----------------------------------------------------------------------------- // Interpolates intensity template <class IntensityFunction, class GradientFunction, class HessianFunction> struct IntensityInterpolator : public Interpolator<IntensityFunction, GradientFunction, HessianFunction> { void operator()(double x, double y, double z, double *o) { this->InterpolateIntensity(x, y, z, o); } }; // ----------------------------------------------------------------------------- // Interpolates 1st order derivatives template <class IntensityFunction, class GradientFunction, class HessianFunction> struct GradientInterpolator : public Interpolator<IntensityFunction, GradientFunction, HessianFunction> { void operator()(double x, double y, double z, double *o) { int mode = this->InterpolationMode (x, y, z); this ->InterpolateGradient(x, y, z, o, mode); } }; // ----------------------------------------------------------------------------- // Interpolates 2nd order derivatives template <class IntensityFunction, class GradientFunction, class HessianFunction> struct HessianInterpolator : public Interpolator<IntensityFunction, GradientFunction, HessianFunction> { void operator()(double x, double y, double z, double *o) { int mode = this->InterpolationMode (x, y, z); this ->InterpolateHessian(x, y, z, o, mode); } }; // ----------------------------------------------------------------------------- // Interpolates intensity and 1st order derivatives template <class IntensityFunction, class GradientFunction, class HessianFunction> struct IntensityAndGradientInterpolator : public Interpolator<IntensityFunction, GradientFunction, HessianFunction> { void operator()(double x, double y, double z, double *o) { int mode = this->InterpolateIntensity(x, y, z, o); this ->InterpolateGradient (x, y, z, o, mode); } }; // ----------------------------------------------------------------------------- // Interpolates intensity and 2nd order derivatives template <class IntensityFunction, class GradientFunction, class HessianFunction> struct IntensityAndHessianInterpolator : public Interpolator<IntensityFunction, GradientFunction, HessianFunction> { void operator()(double x, double y, double z, double *o) { int mode = this->InterpolateIntensity(x, y, z, o); this ->InterpolateHessian (x, y, z, o, mode); } }; // ----------------------------------------------------------------------------- // Interpolates 1st and 2nd order derivatives template <class IntensityFunction, class GradientFunction, class HessianFunction> struct GradientAndHessianInterpolator : public Interpolator<IntensityFunction, GradientFunction, HessianFunction> { void operator()(double x, double y, double z, double *o) { int mode = this->InterpolationMode (x, y, z); this ->InterpolateGradient(x, y, z, o, mode); this ->InterpolateHessian (x, y, z, o, mode); } }; // ----------------------------------------------------------------------------- // Interpolates intensity, 1st and 2nd order derivatives template <class IntensityFunction, class GradientFunction, class HessianFunction> struct IntensityAndGradientAndHessianInterpolator : public Interpolator<IntensityFunction, GradientFunction, HessianFunction> { void operator()(double x, double y, double z, double *o) { int mode = this->InterpolateIntensity(x, y, z, o); this ->InterpolateGradient (x, y, z, o, mode); this ->InterpolateHessian (x, y, z, o, mode); } }; // ----------------------------------------------------------------------------- // Voxel update function template <class Transformer, class Interpolator> struct UpdateFunction : public irtkVoxelFunction { private: typedef typename Transformer::CoordType CoordType; Transformer _Transform; Interpolator _Interpolate; public: /// Constructor UpdateFunction(const irtkBaseImage *f, const irtkBaseImage *g, const irtkBaseImage *h, const irtkTransformation *t, irtkRegisteredImage *o, double omin = numeric_limits<double>::quiet_NaN(), double omax = numeric_limits<double>::quiet_NaN()) { _Transform .Initialize(o, f, t); _Interpolate.Initialize(o, f, g, h, omin, omax); } /// Resample input without pre-computed maps void operator ()(int i, int j, int k, int, double *o) { double x = i, y = j, z = k; _Transform (x, y, z); _Interpolate(x, y, z, o); } /// Resample input using pre-computed world coordinates void operator ()(int i, int j, int k, int, const CoordType *wc, double *o) { double x = i, y = j, z = k; _Transform (x, y, z, wc); _Interpolate(x, y, z, o); } /// Resample input using pre-computed world coordinates and displacements void operator ()(int i, int j, int k, int, const CoordType *wc, const double *dx, double *o) { double x = i, y = j, z = k; _Transform (x, y, z, wc, dx); _Interpolate(x, y, z, o); } /// Resample input using pre-computed world coordinates and additive displacements void operator ()(int i, int j, int k, int, const CoordType *wc, const double *d1, const double *d2, double *o) { double x = i, y = j, z = k; _Transform (x, y, z, wc, d1, d2); _Interpolate(x, y, z, o); } }; // ----------------------------------------------------------------------------- template <class Transformer, class Interpolator> void irtkRegisteredImage::Update3(const blocked_range3d<int> &region, bool intensity, bool gradient, bool hessian) { typedef UpdateFunction<Transformer, Interpolator> Function; Function f(intensity ? _InputImage : NULL, gradient ? _InputGradient : NULL, hessian ? _InputHessian : NULL, _Transformation, this, _MinIntensity, _MaxIntensity); if (_ImageToWorld) { if (_ExternalDisplacement) { ParallelForEachVoxel(region, _ImageToWorld, _ExternalDisplacement, this, f); } else if (_Displacement) { if (_FixedDisplacement) { ParallelForEachVoxel(region, _ImageToWorld, _FixedDisplacement, _Displacement, this, f); } else { ParallelForEachVoxel(region, _ImageToWorld, _Displacement, this, f); } } else { ParallelForEachVoxel(region, _ImageToWorld, this, f); } } else { ParallelForEachVoxel(region, this, f); } } // ----------------------------------------------------------------------------- template <class Transformer, class IntensityFunction, class GradientFunction, class HessianFunction> void irtkRegisteredImage::Update2(const blocked_range3d<int> &region, bool intensity, bool gradient, bool hessian) { // Auxiliary macro -- undefined again at the end of this body #define _update_using(Interpolator) \ Update3< \ Transformer, \ Interpolator<IntensityFunction, GradientFunction, HessianFunction> \ >(region, intensity, gradient, hessian) if (intensity) { if (gradient) { if (hessian) { _update_using(IntensityAndGradientAndHessianInterpolator); } else { _update_using(IntensityAndGradientInterpolator); } } else { if (hessian) { _update_using(IntensityAndHessianInterpolator); } else { _update_using(IntensityInterpolator); } } } else { if (gradient) { if (hessian) { _update_using(GradientAndHessianInterpolator); } else { _update_using(GradientInterpolator); } } else { if (hessian) { _update_using(HessianInterpolator); } else { cerr << "irtkRegisteredImage::Update: At least one output channel should be updated" << endl; exit(1); } } } #undef _update_using } // ----------------------------------------------------------------------------- template <class Transformer> void irtkRegisteredImage::Update1(const blocked_range3d<int> &region, bool intensity, bool gradient, bool hessian) { irtkInterpolationMode interpolation = InterpolationWithoutPadding(_InterpolationMode); if (_PrecomputeDerivatives) { // Instantiate image functions for commonly used interpolation methods // to allow the compiler to generate optimized code for these if (interpolation == Interpolation_Linear || interpolation == Interpolation_FastLinear) { // Auxiliary macro -- undefined again at the end of this body #define _update_using(InterpolatorType) \ Update2<Transformer, InterpolatorType<InputImageType>, \ InterpolatorType<GradientImageType>, \ InterpolatorType<HessianImageType> > \ (region, intensity, gradient, hessian) if (this->GetZ() == 1) { _update_using(irtkGenericLinearInterpolateImageFunction2D); } else { _update_using(irtkGenericLinearInterpolateImageFunction3D); } #undef _update_using // Otherwise use generic interpolate image function interface } else { Update2<Transformer, irtkInterpolateImageFunction, irtkInterpolateImageFunction, irtkInterpolateImageFunction> (region, intensity, gradient, hessian); } } else { // Auxiliary macro -- undefined again at the end of this body // TODO: Use also some HessianInterpolatorType #define _update_using(InterpolatorType, GradientInterpolatorType) \ Update2<Transformer, InterpolatorType<InputImageType>, \ GradientInterpolatorType<InputImageType>, \ InterpolatorType<HessianImageType> > \ (region, intensity, gradient, hessian) // Instantiate image functions for commonly used interpolation methods // to allow the compiler to generate optimized code for these if (interpolation == Interpolation_Linear) { if (this->GetZ() == 1) { _update_using(irtkGenericLinearInterpolateImageFunction2D, irtkGenericLinearImageGradientFunction2D); } else { _update_using(irtkGenericLinearInterpolateImageFunction3D, irtkGenericLinearImageGradientFunction3D); } } else if (interpolation == Interpolation_FastLinear) { if (this->GetZ() == 1) { _update_using(irtkGenericLinearInterpolateImageFunction2D, irtkGenericFastLinearImageGradientFunction2D); } else { _update_using(irtkGenericLinearInterpolateImageFunction3D, irtkGenericFastLinearImageGradientFunction3D); } // Otherwise use generic interpolate image function interface // TODO: Implement and use irtkImageHessianFunction } else { Update2<Transformer, irtkInterpolateImageFunction, irtkImageGradientFunction, irtkInterpolateImageFunction> (region, intensity, gradient, hessian); } #undef _update_using } } // ----------------------------------------------------------------------------- template <class TOut, class TIn> inline void CopyChannels(irtkGenericImage<TOut> *tgt, int l, const irtkGenericImage<TIn> *src) { assert(tgt->GetX() == src->GetX()); assert(tgt->GetY() == src->GetY()); assert(tgt->GetZ() == src->GetZ()); assert(tgt->GetT() >= l + src->GetT()); TOut *out = tgt->GetPointerToVoxels(0, 0, 0, l); const TIn *in = src->GetPointerToVoxels(); const int nvox = src->GetNumberOfVoxels(); for (int idx = 0; idx < nvox; ++idx) { (*out++) = static_cast<TOut>(*in++); } } // ----------------------------------------------------------------------------- template <> inline void CopyChannels(irtkGenericImage<irtkRegisteredImage::VoxelType> *tgt, int l, const irtkGenericImage<irtkRegisteredImage::VoxelType> *src) { assert(tgt->GetX() == src->GetX()); assert(tgt->GetY() == src->GetY()); assert(tgt->GetZ() == src->GetZ()); assert(tgt->GetT() >= l + src->GetT()); memcpy(tgt->GetPointerToVoxels(0, 0, 0, l), src->GetPointerToVoxels(), src->GetNumberOfVoxels() * sizeof(irtkRegisteredImage::VoxelType)); } // ----------------------------------------------------------------------------- void irtkRegisteredImage::Update(const blocked_range3d<int> &region, bool intensity, bool gradient, bool hessian, bool force) { // Update only channels that were initialized even if requested gradient = gradient && this->T() >= 4; hessian = hessian && this->T() >= 10; // Do nothing if no output should be updated if (!intensity && !gradient && !hessian) return; // Do nothing if no transformation is set or self-update is disabled // (i.e., external process is responsible for update of registered image) if (!force && (!_Transformation || !_SelfUpdate)) return; IRTK_START_TIMING(); if (_ExternalDisplacement && region.cols ().begin() == 0 && region.cols ().end() == _ExternalDisplacement->X() && region.rows ().begin() == 0 && region.rows ().end() == _ExternalDisplacement->Y() && region.pages().begin() == 0 && region.pages().end() == _ExternalDisplacement->Z()) { // Always use provided externally updated displacement field if given Update1<DefaultTransformer>(region, intensity, gradient, hessian); } else { // End time point of deformation and initial time for velocity-based // transformations, i.e., time point of initial condition of ODE const double t = _InputImage->GetTOrigin(); const double t0 = this ->GetTOrigin(); // ------------------------------------------------------------------------- // Update moving image (i.e., constantly changing transformation is set) if (_Transformation && _NumberOfActiveLevels > 0) { // For some transformations, it is faster to compute the displacements // all at once such as those which are represented by velocity fields. const bool cache = _CacheDisplacement || _Transformation->RequiresCachingOfDisplacements(); if (cache && !_Displacement) _Displacement = new DisplacementImageType(); // If we pre-computed the fixed displacement of the passive MFFD levels const irtkMultiLevelTransformation *mffd; if (_FixedDisplacement && (mffd = dynamic_cast<const irtkMultiLevelTransformation *>(_Transformation))) { if (dynamic_cast<const irtkFluidFreeFormTransformation *>(mffd)) { if (_Displacement) { *_Displacement = *_FixedDisplacement; mffd->Displacement(_NumberOfPassiveLevels, -1, *_Displacement, t, t0, _ImageToWorld); } Update1<FluidTransformer>(region, intensity, gradient, hessian); } else { if (_Displacement) { _Displacement->Initialize(_attr, 3); mffd->Displacement(_NumberOfPassiveLevels, -1, *_Displacement, t, t0, _ImageToWorld); } Update1<AdditiveTransformer>(region, intensity, gradient, hessian); } // Otherwise, simply let the (non-)MFFD compute the total transformation } else { if (_Displacement) { _Displacement->Initialize(_attr, 3); _Transformation->Displacement(*_Displacement, t, t0, _ImageToWorld); } Update1<DefaultTransformer>(region, intensity, gradient, hessian); } // ------------------------------------------------------------------------- // Update fixed image } else { // Copy input images if no transformation is set and the image attributes // of the input images are identical to those of the output images if (!_Transformation && this->HasSpatialAttributesOf(_InputImage)) { // Copy intensities if (intensity) { // Rescale foreground intensities to [_MinIntensity, _MaxIntensity] if (!IsNaN(_MinIntensity) || !IsNaN(_MaxIntensity)) { const int nvox = NumberOfVoxels(); if (nvox > 0) { InputImageType::VoxelType *iptr = _InputImage->Data(); InputImageType::VoxelType imin; InputImageType::VoxelType imax; imin = voxel_limits<InputImageType::VoxelType>::max(); imax = voxel_limits<InputImageType::VoxelType>::min(); for (int idx = 0; idx < nvox; ++idx, ++iptr) { if (_InputImage->IsForeground(idx)) { if (*iptr < imin) imin = *iptr; if (*iptr > imax) imax = *iptr; } } if (imin <= imax) { double omin = _MinIntensity; double omax = _MaxIntensity; if (IsNaN(omin)) omin = imin; if (IsNaN(omax)) omax = imax; const double slope = (omax - omin) / static_cast<double>(imax - imin); const double inter = omin - slope * static_cast<double>(imin); iptr = _InputImage->Data(); VoxelType *optr = this->Data(); const VoxelType bg = voxel_cast<VoxelType>(this->_bg); for (int idx = 0; idx < nvox; ++idx, ++iptr, ++optr) { if (_InputImage->IsForeground(idx)) { *optr = voxel_cast<VoxelType>(inter + slope * static_cast<double>(*iptr)); if (*optr < _MinIntensity) *optr = _MinIntensity; else if (*optr > _MaxIntensity) *optr = _MaxIntensity; } else { *optr = bg; } } } } } else { CopyChannels(this, 0, _InputImage); } } // Copy derivatives if (gradient) CopyChannels(this, 1, _InputGradient); if (hessian) CopyChannels(this, 4, _InputHessian); // Copy background mask (if set) this->PutMask(_InputImage->GetMask()); // Resample input images on (transformed) output image grid otherwise } else { Delete(_Displacement); _Displacement = _FixedDisplacement; _FixedDisplacement = NULL; if (_Transformation) { const bool cache = _CacheDisplacement || _Transformation->RequiresCachingOfDisplacements(); if (cache && !_Displacement) { _Displacement = new DisplacementImageType(); _Transformation->Displacement(*_Displacement, t, t0, _ImageToWorld); } } Update1<FixedTransformer>(region, intensity, gradient, hessian); Delete(_Displacement); // image usually only transformed once } } } IRTK_DEBUG_TIMING(4, "update of " << (_Transformation ? "moving" : "fixed") << " image" << " (intensity=" << (intensity ? "yes" : "no") << ", gradient=" << (gradient ? "yes" : "no") << ", hessian=" << (hessian ? "yes" : "no") << ")"); } // ----------------------------------------------------------------------------- void irtkRegisteredImage::Update(bool intensity, bool gradient, bool hessian, bool force) { blocked_range3d<int> region(0, Z(), 0, Y(), 0, X()); this->Update(region, intensity, gradient, hessian, force); } // ----------------------------------------------------------------------------- void irtkRegisteredImage::Update(const blocked_range3d<int> &region, const DisplacementImageType *disp, bool intensity, bool gradient, bool hessian) { // Update only channels that were initialized even if requested gradient = gradient && this->T() >= 4; hessian = hessian && this->T() >= 10; // Do nothing if no output should be updated if (!intensity && !gradient && !hessian) return; // Image to world map required by Update3 if (!_ImageToWorld) { _ImageToWorld = new irtkWorldCoordsImage(); this->ImageToWorld(*_ImageToWorld, true /* i.e., always 3D vectors */); } // Keep pointers to own displacement fields DisplacementImageType * const _disp = _Displacement; DisplacementImageType * const _fixed = _FixedDisplacement; // Replace displacement fields by user arguments _Displacement = const_cast<DisplacementImageType *>(disp); _FixedDisplacement = NULL; // Interpolate within specified region using fixed transfomer Update1<FixedTransformer>(region, intensity, gradient, hessian); // Reset pointers to own displacement fields _Displacement = _disp; _FixedDisplacement = _fixed; }
40.334873
129
0.616776
kevin-keraudren
719808bb3bebe7d1d308ff050376afa792945677
448
cc
C++
phastaIO/phiotimer_empty/phiotimer_empty.cc
polmes/phasta
38a361e8033072fa0b5376e424dddd3efa5a65d5
[ "BSD-3-Clause" ]
49
2015-04-16T13:45:34.000Z
2022-02-07T01:02:49.000Z
phastaIO/phiotimer_empty/phiotimer_empty.cc
polmes/phasta
38a361e8033072fa0b5376e424dddd3efa5a65d5
[ "BSD-3-Clause" ]
21
2015-10-06T19:50:43.000Z
2017-12-17T03:47:51.000Z
phastaIO/phiotimer_empty/phiotimer_empty.cc
polmes/phasta
38a361e8033072fa0b5376e424dddd3efa5a65d5
[ "BSD-3-Clause" ]
38
2015-04-21T12:13:40.000Z
2021-11-12T19:38:00.000Z
#include <phiotimer.h> void phastaio_time(phastaioTime*) {} size_t phastaio_time_diff(phastaioTime*, phastaioTime*) { return 1; } void phastaio_addReadBytes(size_t) {} void phastaio_addWriteBytes(size_t) {} void phastaio_addReadTime(size_t) {} void phastaio_addWriteTime(size_t) {} void phastaio_setfile(int) {} void phastaio_addOpenTime(size_t) {} void phastaio_addCloseTime(size_t) {} void phastaio_printStats() {} void phastaio_initStats() {}
29.866667
57
0.790179
polmes
719f1d89691cb01d7d1a0d34a117416f876f2bd1
920
cpp
C++
Examples/source/AddImage.cpp
kashifiqb/Aspose.Page-for-C
ac121edcf382d2543261f797d1dac108936ca69f
[ "MIT" ]
3
2020-06-19T20:30:11.000Z
2021-01-15T09:07:42.000Z
Examples/source/AddImage.cpp
kashifiqb/Aspose.Page-for-C
ac121edcf382d2543261f797d1dac108936ca69f
[ "MIT" ]
null
null
null
Examples/source/AddImage.cpp
kashifiqb/Aspose.Page-for-C
ac121edcf382d2543261f797d1dac108936ca69f
[ "MIT" ]
1
2019-12-26T12:53:01.000Z
2019-12-26T12:53:01.000Z
#include "stdafx.h" //#include "ExampleDirectories.h" #include "..\RunExamples.h" using namespace Aspose::Page::Xps; using namespace Aspose::Page::Xps::XpsModel; void AddImage() { //ExStart: AddImage // Create new XPS Document System::SharedPtr<XpsDocument> doc = System::MakeObject<XpsDocument>(); // Add Image System::SharedPtr<XpsPath> path = doc->AddPath(doc->CreatePathGeometry(u"M 30,20 l 258.24,0 0,56.64 -258.24,0 Z")); //Creating a matrix is optional, it can be used for proper positioning path->set_RenderTransform(doc->CreateMatrix(0.7f, 0.f, 0.f, 0.7f, 0.f, 20.f)); //Create Image Brush path->set_Fill(doc->CreateImageBrush(RunExamples::dataDir() + u"QL_logo_color.tif", System::Drawing::RectangleF(0.f, 0.f, 258.24f, 56.64f), System::Drawing::RectangleF(50.f, 20.f, 193.68f, 42.48f))); // Save resultant XPS document doc->Save(RunExamples::outDir() + u"AddImage_out.xps"); // ExEnd: AddImage }
41.818182
200
0.717391
kashifiqb
71a4545a18af8f66eda7bfb88777af13752a4729
16,127
cpp
C++
tests/tst_seasidefilteredmodel/seasidecache.cpp
LaakkonenJussi/nemo-qml-plugin-contacts
e94e468786000d4c4d403fea1bec8e49e37a471e
[ "BSD-3-Clause" ]
null
null
null
tests/tst_seasidefilteredmodel/seasidecache.cpp
LaakkonenJussi/nemo-qml-plugin-contacts
e94e468786000d4c4d403fea1bec8e49e37a471e
[ "BSD-3-Clause" ]
3
2021-09-29T07:13:48.000Z
2022-03-31T11:03:07.000Z
tests/tst_seasidefilteredmodel/seasidecache.cpp
LaakkonenJussi/nemo-qml-plugin-contacts
e94e468786000d4c4d403fea1bec8e49e37a471e
[ "BSD-3-Clause" ]
1
2022-03-25T15:33:41.000Z
2022-03-25T15:33:41.000Z
/* * Copyright (C) 2013 Jolla Mobile <andrew.den.exter@jollamobile.com> * * You may use this file under the terms of the BSD license as follows: * * "Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Nemo Mobile nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." */ #include "seasidecache.h" #include <qcontactstatusflags_impl.h> #include <QContactName> #include <QContactAvatar> #include <QContactEmailAddress> #include <QContactPhoneNumber> #include <QtDebug> struct Contact { const char *firstName; const char *middleName; const char *lastName; const bool isFavorite; const bool isOnline; const char *email; const char *phoneNumber; const char *avatar; }; static const Contact contactsData[] = { /*1*/ { "Aaron", u8"Elvis", "Aaronson", false, false, "aaronaa-testing@example.org", "1234567", 0 }, /*2*/ { "Aaron", u8"elvis", "Arthur", false, true, "aaronar-testing@example.org", 0, 0 }, /*3*/ { "Aaron", u8"\u00CBlvis", "Johns", true, false, "johns-testing@example.org", 0, 0 }, // 'Ëlvis' /*4*/ { "Arthur", u8"Elvi\u00DF", "Johns", false, true, "arthur1.johnz-tested@example.org", "2345678", 0 }, // 'Elviß' /*5*/ { "Jason", u8"\u00C6lvis", "Aaronson", false, false, "jay-tester@example.org", "3456789", 0 }, // 'Ælvis' /*6*/ { "Joe", u8"\u00D8lvis", "Johns", true, true, "jj-tester@example.org", 0, "file:///cache/joe.jpg" }, // 'Ølvis' /*7*/ { "Robin", u8"\u00D8lvi\u00DF", "Burchell", true, false, 0, "9876543", 0 } // 'Ølviß' }; static QStringList getAllContactDisplayLabelGroups() { QStringList groups; for (char c = 'A'; c <= 'Z'; ++c) { groups.append(QString(QChar::fromLatin1(c))); } groups.append(QString::fromLatin1("#")); return groups; } static QString determineDisplayLabelGroup(const SeasideCache::CacheItem *cacheItem, const QString &preferredProperty) { if (!cacheItem) return QString(); const QContactName nameDetail = cacheItem->contact.detail<QContactName>(); QString group = cacheItem->contact.detail<QContactDisplayLabel>().value(QContactDisplayLabel__FieldLabelGroup).toString(); const QString sort(preferredProperty == QString::fromLatin1("firstName") ? nameDetail.firstName() : nameDetail.lastName()); if (group.isEmpty() && !sort.isEmpty()) { group = QString(sort[0].toUpper()); } else if (group.isEmpty() && !cacheItem->displayLabel.isEmpty()) { group = QString(cacheItem->displayLabel[0].toUpper()); } if (group.isNull() || !SeasideCache::allContactDisplayLabelGroups.contains(group)) { group = QString::fromLatin1("#"); // 'other' group } return group; } QStringList SeasideCache::allContactDisplayLabelGroups = getAllContactDisplayLabelGroups(); SeasideCache *SeasideCache::instancePtr = 0; SeasideCache *SeasideCache::instance() { return instancePtr; } QContactManager *SeasideCache::manager() { static QContactManager *mgr = new QContactManager; return mgr; } QContactId SeasideCache::apiId(const QContact &contact) { return contact.id(); } QContactId SeasideCache::apiId(quint32 iid) { return QtContactsSqliteExtensions::apiContactId(iid, manager()->managerUri()); } bool SeasideCache::validId(const QContactId &id) { return !id.isNull(); } quint32 SeasideCache::internalId(const QContact &contact) { return internalId(contact.id()); } quint32 SeasideCache::internalId(const QContactId &id) { return QtContactsSqliteExtensions::internalContactId(id); } SeasideCache::SeasideCache() { instancePtr = this; for (int i = 0; i < FilterTypesCount; ++i) { m_models[i] = 0; m_populated[i] = false; } } void SeasideCache::reset() { for (int i = 0; i < FilterTypesCount; ++i) { m_contacts[i].clear(); m_populated[i] = false; m_models[i] = 0; } m_cache.clear(); m_cacheIndices.clear(); for (uint i = 0; i < sizeof(contactsData) / sizeof(Contact); ++i) { QContact contact; // This is specific to the qtcontacts-sqlite backend: contact.setId(apiId(i + 1)); QContactName name; name.setFirstName(QString::fromLatin1(contactsData[i].firstName)); name.setMiddleName(QString::fromUtf8(contactsData[i].middleName)); name.setLastName(QString::fromLatin1(contactsData[i].lastName)); contact.saveDetail(&name); if (contactsData[i].avatar) { QContactAvatar avatar; avatar.setImageUrl(QUrl(QLatin1String(contactsData[i].avatar))); contact.saveDetail(&avatar); } QContactStatusFlags statusFlags; if (contactsData[i].email) { QContactEmailAddress email; email.setEmailAddress(QLatin1String(contactsData[i].email)); contact.saveDetail(&email); statusFlags.setFlag(QContactStatusFlags::HasEmailAddress, true); } if (contactsData[i].phoneNumber) { QContactPhoneNumber phoneNumber; phoneNumber.setNumber(QLatin1String(contactsData[i].phoneNumber)); contact.saveDetail(&phoneNumber); statusFlags.setFlag(QContactStatusFlags::HasPhoneNumber, true); } contact.saveDetail(&statusFlags); m_cacheIndices.insert(internalId(contact), m_cache.count()); m_cache.append(CacheItem(contact)); QString fullName = name.firstName() + QChar::fromLatin1(' ') + name.lastName(); CacheItem &cacheItem = m_cache.last(); cacheItem.displayLabelGroup = determineDisplayLabelGroup(&cacheItem, sortProperty()); cacheItem.displayLabel = fullName; } insert(FilterAll, 0, getContactsForFilterType(FilterAll)); insert(FilterFavorites, 0, getContactsForFilterType(FilterFavorites)); } QList<quint32> SeasideCache::getContactsForFilterType(FilterType filterType) { QList<quint32> ids; for (uint i = 0; i < sizeof(contactsData) / sizeof(Contact); ++i) { if ((filterType == FilterAll) || (filterType == FilterFavorites && contactsData[i].isFavorite)) { ids.append(internalId(instancePtr->m_cache[i].contact.id())); } } return ids; } SeasideCache::~SeasideCache() { instancePtr = 0; } void SeasideCache::registerModel(ListModel *model, FilterType type, FetchDataType, FetchDataType) { for (int i = 0; i < FilterTypesCount; ++i) instancePtr->m_models[i] = 0; instancePtr->m_models[type] = model; } void SeasideCache::unregisterModel(ListModel *) { for (int i = 0; i < FilterTypesCount; ++i) instancePtr->m_models[i] = 0; } void SeasideCache::registerUser(QObject *) { } void SeasideCache::unregisterUser(QObject *) { } void SeasideCache::registerChangeListener(ChangeListener *) { } void SeasideCache::unregisterChangeListener(ChangeListener *) { } void SeasideCache::unregisterResolveListener(ResolveListener *) { } int SeasideCache::contactId(const QContact &contact) { quint32 internal = internalId(contact); return static_cast<int>(internal); } SeasideCache::CacheItem *SeasideCache::existingItem(const QContactId &id) { quint32 iid(internalId(id)); if (instancePtr->m_cacheIndices.contains(iid)) { return &instancePtr->m_cache[instancePtr->m_cacheIndices[iid]]; } return 0; } SeasideCache::CacheItem *SeasideCache::existingItem(quint32 iid) { if (instancePtr->m_cacheIndices.contains(iid)) { return &instancePtr->m_cache[instancePtr->m_cacheIndices[iid]]; } return 0; } SeasideCache::CacheItem *SeasideCache::itemById(const QContactId &id, bool) { quint32 iid(internalId(id)); if (instancePtr->m_cacheIndices.contains(iid)) { return &instancePtr->m_cache[instancePtr->m_cacheIndices[iid]]; } return 0; } SeasideCache::CacheItem *SeasideCache::itemById(int id, bool) { if (id == 0) return 0; // Construct a valid id from this value QContactId contactId = apiId(id); if (contactId.isNull()) { qWarning() << "Unable to formulate valid ID from:" << id; return 0; } return itemById(contactId); } QContact SeasideCache::contactById(const QContactId &id) { quint32 iid(internalId(id)); return instancePtr->m_cache[instancePtr->m_cacheIndices[iid]].contact; } QString SeasideCache::displayLabelGroup(const CacheItem *cacheItem) { if (!cacheItem) return QString(); return cacheItem->displayLabelGroup; } QStringList SeasideCache::allDisplayLabelGroups() { return allContactDisplayLabelGroups; } void SeasideCache::ensureCompletion(CacheItem *) { } void SeasideCache::refreshContact(CacheItem *) { } SeasideCache::CacheItem *SeasideCache::itemByPhoneNumber(const QString &, bool) { return 0; } SeasideCache::CacheItem *SeasideCache::itemByEmailAddress(const QString &, bool) { return 0; } SeasideCache::CacheItem *SeasideCache::itemByOnlineAccount(const QString &, const QString &, bool) { return 0; } SeasideCache::CacheItem *SeasideCache::resolvePhoneNumber(ResolveListener *, const QString &, bool) { // TODO: implement and test these functions return 0; } SeasideCache::CacheItem *SeasideCache::resolveEmailAddress(ResolveListener *, const QString &, bool) { return 0; } SeasideCache::CacheItem *SeasideCache::resolveOnlineAccount(ResolveListener *, const QString &, const QString &, bool) { return 0; } QContactId SeasideCache::selfContactId() { return QContactId(); } bool SeasideCache::saveContact(const QContact &) { return false; } bool SeasideCache::saveContacts(const QList<QContact> &) { return false; } void SeasideCache::removeContact(const QContact &) { } void SeasideCache::removeContacts(const QList<QContact> &) { } void SeasideCache::aggregateContacts(const QContact &, const QContact &) { } void SeasideCache::disaggregateContacts(const QContact &, const QContact &) { } void SeasideCache::fetchConstituents(const QContact &contact) { if (SeasideCache::CacheItem *item = itemById(SeasideCache::apiId(contact))) { if (item->itemData) { item->itemData->constituentsFetched(QList<int>()); } } } void SeasideCache::fetchMergeCandidates(const QContact &contact) { if (SeasideCache::CacheItem *item = itemById(SeasideCache::apiId(contact))) { if (item->itemData) { item->itemData->mergeCandidatesFetched(QList<int>()); } } } const QList<quint32> *SeasideCache::contacts(FilterType filterType) { return &instancePtr->m_contacts[filterType]; } bool SeasideCache::isPopulated(FilterType filterType) { return instancePtr->m_populated[filterType]; } QString SeasideCache::getPrimaryName(const QContact &) { return QString(); } QString SeasideCache::getSecondaryName(const QContact &) { return QString(); } QString SeasideCache::primaryName(const QString &, const QString &) { return QString(); } QString SeasideCache::secondaryName(const QString &, const QString &) { return QString(); } QString SeasideCache::placeholderDisplayLabel() { return QString(); } void SeasideCache::decomposeDisplayLabel(const QString &, QContactName *) { } QString SeasideCache::generateDisplayLabel(const QContact &, DisplayLabelOrder) { return QString(); } QString SeasideCache::generateDisplayLabelFromNonNameDetails(const QContact &) { return QString(); } QUrl SeasideCache::filteredAvatarUrl(const QContact &contact, const QStringList &) { foreach (const QContactAvatar &av, contact.details<QContactAvatar>()) { return av.imageUrl(); } return QUrl(); } bool SeasideCache::removeLocalAvatarFile(const QContact &, const QContactAvatar &) { return false; } QString SeasideCache::normalizePhoneNumber(const QString &input, bool) { return input; } QString SeasideCache::minimizePhoneNumber(const QString &input, bool) { return input; } QContactCollectionId SeasideCache::aggregateCollectionId() { return QContactCollectionId(); } QContactCollectionId SeasideCache::localCollectionId() { return QContactCollectionId(); } SeasideCache::DisplayLabelOrder SeasideCache::displayLabelOrder() { return FirstNameFirst; } QString SeasideCache::sortProperty() { return QString::fromLatin1("firstName"); } QString SeasideCache::groupProperty() { return QString::fromLatin1("firstName"); } void SeasideCache::populate(FilterType filterType) { m_populated[filterType] = true; if (m_models[filterType]) m_models[filterType]->makePopulated(); } void SeasideCache::insert(FilterType filterType, int index, const QList<quint32> &ids) { if (m_models[filterType]) m_models[filterType]->sourceAboutToInsertItems(index, index + ids.count() - 1); for (int i = 0; i < ids.count(); ++i) m_contacts[filterType].insert(index + i, ids.at(i)); if (m_models[filterType]) { m_models[filterType]->sourceItemsInserted(index, index + ids.count() - 1); m_models[filterType]->sourceItemsChanged(); } } void SeasideCache::remove(FilterType filterType, int index, int count) { if (m_models[filterType]) m_models[filterType]->sourceAboutToRemoveItems(index, index + count - 1); QList<quint32>::iterator it = m_contacts[filterType].begin() + index; m_contacts[filterType].erase(it, it + count); if (m_models[filterType]) { m_models[filterType]->sourceItemsRemoved(); m_models[filterType]->sourceItemsChanged(); } } int SeasideCache::importContacts(const QString &) { return 0; } QString SeasideCache::exportContacts() { return QString(); } void SeasideCache::setFirstName(FilterType filterType, int index, const QString &firstName) { CacheItem &cacheItem = m_cache[m_cacheIndices[m_contacts[filterType].at(index)]]; QContactName name = cacheItem.contact.detail<QContactName>(); name.setFirstName(firstName); cacheItem.contact.saveDetail(&name); QString fullName = name.firstName() + QChar::fromLatin1(' ') + name.lastName(); cacheItem.displayLabelGroup = determineDisplayLabelGroup(&cacheItem, sortProperty()); cacheItem.displayLabel = fullName; ItemListener *listener(cacheItem.listeners); while (listener) { listener->itemUpdated(&cacheItem); listener = listener->next; } if (m_models[filterType]) m_models[filterType]->sourceDataChanged(index, index); } quint32 SeasideCache::idAt(int index) const { return internalId(m_cache[index].contact.id()); }
27.805172
151
0.688163
LaakkonenJussi
71a49600f84ea0f01d7ad4760c17e8c79fbcb7cc
8,928
cpp
C++
src/monitormanager.cpp
dnnr/herbstluftwm
3bed77ed53c11d0f07d591feb0ef29bb4e741b51
[ "BSD-2-Clause-FreeBSD" ]
1
2018-12-02T16:51:04.000Z
2018-12-02T16:51:04.000Z
src/monitormanager.cpp
dnnr/herbstluftwm
3bed77ed53c11d0f07d591feb0ef29bb4e741b51
[ "BSD-2-Clause-FreeBSD" ]
8
2019-03-03T21:12:40.000Z
2019-05-05T13:30:19.000Z
src/monitormanager.cpp
dnnr/herbstluftwm
3bed77ed53c11d0f07d591feb0ef29bb4e741b51
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
#include "monitormanager.h" #include <X11/Xlib.h> #include <cassert> #include <memory> #include "ewmh.h" #include "floating.h" #include "frametree.h" #include "globals.h" #include "ipc-protocol.h" #include "layout.h" #include "monitor.h" #include "settings.h" #include "stack.h" #include "tag.h" #include "tagmanager.h" #include "utils.h" using std::function; using std::make_pair; using std::string; MonitorManager* g_monitors; MonitorManager::MonitorManager() : IndexingObject<Monitor>() , focus(*this, "focus") , by_name_(*this) { cur_monitor = 0; monitor_stack = new Stack(); } MonitorManager::~MonitorManager() { clearChildren(); delete monitor_stack; } void MonitorManager::injectDependencies(Settings* s, TagManager* t) { settings_ = s; tags_ = t; } void MonitorManager::clearChildren() { IndexingObject<Monitor>::clearChildren(); focus = {}; tags_ = {}; } void MonitorManager::ensure_monitors_are_available() { if (size() > 0) { // nothing to do return; } // add monitor if necessary Rectangle rect = { 0, 0, DisplayWidth(g_display, DefaultScreen(g_display)), DisplayHeight(g_display, DefaultScreen(g_display))}; HSTag* tag = tags_->ensure_tags_are_available(); // add monitor with first tag Monitor* m = addMonitor(rect, tag); m->tag->frame->root_->setVisibleRecursive(true); cur_monitor = 0; monitor_update_focus_objects(); } int MonitorManager::indexInDirection(Monitor* m, Direction dir) { RectangleIdxVec rects; int relidx = -1; FOR (i,0,size()) { rects.push_back(make_pair(i, byIdx(i)->rect)); if (byIdx(i) == m) relidx = i; } HSAssert(relidx >= 0); int result = find_rectangle_in_direction(rects, relidx, dir); return result; } int MonitorManager::string_to_monitor_index(string str) { if (str[0] == '\0') { return cur_monitor; } else if (str[0] == '-' || str[0] == '+') { if (isdigit(str[1])) { // relative monitor index int idx = cur_monitor + atoi(str.c_str()); idx %= size(); idx += size(); idx %= size(); return idx; } else if (str[0] == '-') { try { auto dir = Converter<Direction>::parse(str.substr(1)); return indexInDirection(focus(), dir); } catch (...) { return -1; } } else { return -1; } } else if (isdigit(str[0])) { // absolute monitor index int idx = atoi(str.c_str()); if (idx < 0 || idx >= (int)size()) { return -1; } return idx; } else { // monitor string for (unsigned i = 0; i < size(); i++) { if (byIdx(i)->name == str) { return (int)i; } } return -1; } } int MonitorManager::list_monitors(Output output) { string monitor_name = ""; int i = 0; for (auto monitor : *this) { if (monitor->name != "" ) { monitor_name = ", named \"" + monitor->name() + "\""; } else { monitor_name = ""; } output << i << ": " << monitor->rect << " with tag \"" << (monitor->tag ? monitor->tag->name->c_str() : "???") << "\"" << monitor_name << (((unsigned int) cur_monitor == i) ? " [FOCUS]" : "") << (monitor->lock_tag ? " [LOCKED]" : "") << "\n"; i++; } return 0; } Monitor* MonitorManager::byString(string str) { int idx = string_to_monitor_index(str); return ((idx >= 0) && idx < size()) ? byIdx(idx) : nullptr; } function<int(Input, Output)> MonitorManager::byFirstArg(MonitorCommand cmd) { return [this,cmd](Input input, Output output) -> int { Monitor *monitor; string monitor_name; if (!(input >> monitor_name)) { monitor = get_current_monitor(); } else { monitor = byString(monitor_name); if (!monitor) { output << input.command() << ": Monitor \"" << input.front() << "\" not found!\n"; return HERBST_INVALID_ARGUMENT; } } return cmd(*monitor, Input(input.command(), input.toVector()), output); }; } void MonitorManager::relayoutTag(HSTag *tag) { for (Monitor* m : *this) { if (m->tag == tag) { m->applyLayout(); break; } } } int MonitorManager::removeMonitor(Input input, Output output) { string monitorIdxString; if (!(input >> monitorIdxString)) { return HERBST_NEED_MORE_ARGS; } auto monitor = byString(monitorIdxString); if (monitor == nullptr) { output << input.command() << ": Monitor \"" << monitorIdxString << "\" not found!\n"; return HERBST_INVALID_ARGUMENT; } if (size() <= 1) { output << input.command() << ": Can't remove the last monitor\n"; return HERBST_FORBIDDEN; } removeMonitor(monitor); return HERBST_EXIT_SUCCESS; } void MonitorManager::removeMonitor(Monitor* monitor) { auto monitorIdx = index_of(monitor); if (cur_monitor > index_of(monitor)) { // Take into account that the current monitor will have a new // index after removal: cur_monitor--; } // Hide all clients visible in monitor assert(monitor->tag != nullptr); assert(monitor->tag->frame->root_ != nullptr); monitor->tag->frame->root_->setVisibleRecursive(false); g_monitors->removeIndexed(monitorIdx); if (cur_monitor >= g_monitors->size()) { cur_monitor--; // if selection has changed, then relayout focused monitor get_current_monitor()->applyLayout(); monitor_update_focus_objects(); // also announce the new selection ewmh_update_current_desktop(); emit_tag_changed(get_current_monitor()->tag, cur_monitor); } monitor_update_focus_objects(); } int MonitorManager::addMonitor(Input input, Output output) { // usage: add_monitor RECTANGLE [TAG [NAME]] string rectString, tagName, monitorName; input >> rectString; if (!input) { return HERBST_NEED_MORE_ARGS; } HSTag* tag = nullptr; if (input >> tagName) { tag = find_tag(tagName.c_str()); if (!tag) { output << input.command() << ": Tag \"" << tagName << "\" does not exist\n"; return HERBST_INVALID_ARGUMENT; } if (find_monitor_with_tag(tag)) { output << input.command() << ": Tag \"" << tagName << "\" is already being viewed on a monitor\n"; return HERBST_TAG_IN_USE; } } else { // if no tag is supplied tag = find_unused_tag(); if (!tag) { output << input.command() << ": There are not enough free tags\n"; return HERBST_TAG_IN_USE; } } // TODO: error message on invalid rectString auto rect = Rectangle::fromStr(rectString); if (input >> monitorName) { auto error = isValidMonitorName(monitorName); if (error != "") { output << input.command() << ": " << error; return HERBST_INVALID_ARGUMENT; } } auto monitor = addMonitor(rect, tag); if (!monitorName.empty()) { monitor->name = monitorName; } monitor->applyLayout(); tag->frame->root_->setVisibleRecursive(true); emit_tag_changed(tag, g_monitors->size() - 1); drop_enternotify_events(); return HERBST_EXIT_SUCCESS; } string MonitorManager::isValidMonitorName(string name) { if (isdigit(name[0])) { return "Invalid name \"" + name + "\": The monitor name may not start with a number\n"; } if (name.empty()) { return "An empty monitor name is not permitted\n"; } if (find_monitor_by_name(name.c_str())) { return "A monitor with the name \"" + name + "\" already exists\n"; } return ""; } Monitor* MonitorManager::addMonitor(Rectangle rect, HSTag* tag) { Monitor* m = new Monitor(settings_, this, rect, tag); addIndexed(m); return m; } void MonitorManager::lock() { settings_->monitors_locked = settings_->monitors_locked() + 1; lock_number_changed(); } void MonitorManager::unlock() { settings_->monitors_locked = std::max(0, settings_->monitors_locked() - 1); lock_number_changed(); } string MonitorManager::lock_number_changed() { if (settings_->monitors_locked() < 0) { return "must be non-negative"; } if (!settings_->monitors_locked()) { // if not locked anymore, then repaint all the dirty monitors for (auto m : *this) { if (m->dirty) { m->applyLayout(); } } } return {}; }
27.640867
95
0.567092
dnnr
71a5684041c3b8c47eb09591a384c59fd46ce891
3,297
cpp
C++
Src/Legacy/Math/matrix4.cpp
visualizersdotnl/tpb-06-final
7bd0b0e3fb954381466b2eb89d5edebef9f39ea7
[ "MIT" ]
4
2015-12-15T23:04:27.000Z
2018-01-17T23:09:10.000Z
Src/Legacy/Math/matrix4.cpp
visualizersdotnl/tpb-06-final
7bd0b0e3fb954381466b2eb89d5edebef9f39ea7
[ "MIT" ]
null
null
null
Src/Legacy/Math/matrix4.cpp
visualizersdotnl/tpb-06-final
7bd0b0e3fb954381466b2eb89d5edebef9f39ea7
[ "MIT" ]
null
null
null
#include <Shared/assert.h> #include "matrix4.h" #include "vector4.h" #include "misc.h" Matrix4 Matrix4::IDENTITY; void Matrix4::Init() { IDENTITY.SetIdentity(); } void Matrix4::SetIdentity() { _11 = 1.0f; _12 = 0.0f; _13 = 0.0f; _14 = 0.0f; _21 = 0.0f; _22 = 1.0f; _23 = 0.0f; _24 = 0.0f; _31 = 0.0f; _32 = 0.0f; _33 = 1.0f; _34 = 0.0f; _41 = 0.0f; _42 = 0.0f; _43 = 0.0f; _44 = 1.0f; } // Inspired by Wine's implementation of D3DXMatrixInverse // http://source.winehq.org/source/dlls/d3dx9_36/math.c#L227 Matrix4 Matrix4::Inversed() const { Matrix4 result; Vector4 vec[3]; float det = Determinant(); ASSERT( !FloatsEqual(det, 0.0f, 0.0000001f) ); static const float factor[4] = { 1, -1, 1, -1 }; for (int i=0; i<4; i++) { for (int j=0; j<4; j++) { if (j != i) { int a = j; if (j > i) a -= 1; vec[a].x = m[j][0]; vec[a].y = m[j][1]; vec[a].z = m[j][2]; vec[a].w = m[j][3]; } } Vector4 v = vec[0].Cross(vec[1], vec[2]); result.m[0][i] = factor[i] * v.x / det; result.m[1][i] = factor[i] * v.y / det; result.m[2][i] = factor[i] * v.z / det; result.m[3][i] = factor[i] * v.w / det; } return result; } // Inspired by Wine's implementation of D3DXMatrixDeterminant // http://source.winehq.org/source/dlls/d3dx9_36/math.c#L214 float Matrix4::Determinant() const { Vector4 v1, v2, v3; v1.x = m[0][0]; v1.y = m[1][0]; v1.z = m[2][0]; v1.w = m[3][0]; v2.x = m[0][1]; v2.y = m[1][1]; v2.z = m[2][1]; v2.w = m[3][1]; v3.x = m[0][2]; v3.y = m[1][2]; v3.z = m[2][2]; v3.w = m[3][2]; Vector4 minor = v1.Cross(v2, v3); return - (m[0][3] * minor.x + m[1][3] * minor.y + m[2][3] * minor.z + m[3][3] * minor.w); } //// Polar decomposition, based on: //// http://callumhay.blogspot.nl/2010/10/decomposing-affine-transforms.html //void Matrix4::PolarDecompose(Vector3* outTranslation, Matrix4* outRotation, Vector3* outScale) //{ // *outTranslation = Vector3(m[3][0], m[3][1], m[3][2]); // // Matrix4 m = *this; // m.m[3][0] = 0; // m.m[3][1] = 0; // m.m[3][2] = 0; // // // Extract the rotation component - this is done using polar decompostion, where // // we successively average the matrix with its inverse transpose until there is // // no/a very small difference between successive averages // float norm; // int count = 0; // Matrix4 rotation = m; // // do // { // Matrix4 nextRotation; // Matrix4 currInvTranspose = rotation.Transposed().Inversed(); // // // Go through every component in the matrices and find the next matrix // for (int i = 0; i < 4; i++) // for (int j = 0; j < 4; j++) // nextRotation.m[i][j] = 0.5f * (rotation.m[i][j] + currInvTranspose.m[i][j]); // // norm = 0.0f; // for (int i = 0; i < 3; i++) // { // float n = // fabs(rotation.m[i][0] - nextRotation.m[i][0]) + // fabs(rotation.m[i][1] - nextRotation.m[i][1]) + // fabs(rotation.m[i][2] - nextRotation.m[i][2]); // norm = max(norm, n); // } // rotation = nextRotation; // } // while (count++ < 100 && norm > 0.000001f); // // *outRotation = rotation; // // // The scale is simply the removal of the rotation from the non-translated matrix // Matrix4 scaleMatrix = rotation.Inversed() * m; // // *outScale = Vector3(scaleMatrix.m[0][0], scaleMatrix.m[1][1], scaleMatrix.m[2][2]); //}
22.737931
96
0.575978
visualizersdotnl
71a929242d9c405f7e8288708bff8c01d1359c35
1,863
hpp
C++
FinalExam/PNGio.hpp
MetalheadKen/NTUST-Parallel-Course
4a4e726a5220eaf7403375b61cf6ce8a7cd9cbb9
[ "MIT" ]
null
null
null
FinalExam/PNGio.hpp
MetalheadKen/NTUST-Parallel-Course
4a4e726a5220eaf7403375b61cf6ce8a7cd9cbb9
[ "MIT" ]
null
null
null
FinalExam/PNGio.hpp
MetalheadKen/NTUST-Parallel-Course
4a4e726a5220eaf7403375b61cf6ce8a7cd9cbb9
[ "MIT" ]
null
null
null
#pragma once #include <png.h> #include <cstdint> #include <list> #include <array> using std::list; using std::array; // struct for PNG image struct inputImage { int width, height; // width & height of the image png_byte depth; // color depth of the image png_byte color_type; // type of the color data (e.g. PNG_COLOR_TYPE_GRAY, PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLOR_TYPE_PALETTE, PNG_COLOR_TYPE_RGB_ALPHA ...) png_uint_32 stride; // bytes per row png_bytep *row_pointers; }; // struct for output gray-scale images struct outputImage { png_uint_32 width, height; png_byte *pixels; // width * height }; // struct for storing circles identified by HCT struct circles { list<array<uint32_t, 4>> data; // a list of arrays of size 4, each array contains center-x, center-y, radius, and # of votes }; // This function reads a PNG image file specified by the filename and stores the image data into data int pngRead(const char *filename, inputImage &data); // This function de-allocates memory allocated by pngRead or inputImage struct void pngFree(inputImage &data); // This function saves gray-scale image data into PNG file specified by the filename. int pngWrite(const char *filename, outputImage& data); // This function de-allocates memory for output image struct void pngFree(outputImage &data); // This function allocates memory for grya-scale images stored in outputImage struct with specified width and height. This function also blanks the canvas, i.e. fills the canvas with black color. void blank(outputImage &canvas, png_uint_32 width, png_uint_32 height); // This function draws circles based on the data recorded in the circleData struct void drawCircles(outputImage& canvas, circles& circleData, const png_byte v=0xff);
38.8125
197
0.721417
MetalheadKen
71a93b3de4fd9a828bfa604b1475bb1cf42e1368
2,350
hxx
C++
private/inet/xml/debug/include/headers.hxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
11
2017-09-02T11:27:08.000Z
2022-01-02T15:25:24.000Z
private/inet/xml/debug/include/headers.hxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
null
null
null
private/inet/xml/debug/include/headers.hxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
14
2019-01-16T01:01:23.000Z
2022-02-20T15:54:27.000Z
//+--------------------------------------------------------------------------- // // Microsoft Windows // Copyright (c) 1992 - 1999 Microsoft Corporation. All rights reserved.*/// // File: headers.hxx // // Contents: include files for Forms Debug DLL // //---------------------------------------------------------------------------- #ifndef FORMDBG_HEADERS_HXX #define FORMDBG_HEADERS_HXX #ifdef UNIX #define ENDTRY _endexcept #else #define ENDTRY #endif #if DBG==0 #define RETAILBUILD #endif #undef DBG #define DBG 1 #ifndef INCMSG #define INCMSG(x) //#define INCMSG(x) message(x) #endif #define _OLEAUT32_ #define INC_OLE2 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #define OEMRESOURCE // Windows includes //#include <w4warn.h> #ifndef X_WINDOWS_H_ #define X_WINDOWS_H_ // #pragma INCMSG("--- Beg <windows.h>") #include <windows.h> // #pragma INCMSG("--- End <windows.h>") #endif //#include <w4warn.h> // windows.h reenables some pragmas #ifndef X_WINDOWSX_H_ #define X_WINDOWSX_H_ // #pragma INCMSG("--- Beg <windowsx.h>") #include <windowsx.h> // #pragma INCMSG("--- End <windowsx.h>") #endif #ifndef X_PLATFORM_H_ #define X_PLATFORM_H_ // #pragma INCMSG("--- Beg <platform.h>") #include <platform.h> // #pragma INCMSG("--- End <platform.h>") #endif // C runtime includes #ifndef X_LIMITS_H_ #define X_LIMITS_H_ // #pragma INCMSG("--- Beg <limits.h>") #include <limits.h> // #pragma INCMSG("--- End <limits.h>") #endif #ifndef X_STDDEF_H_ #define X_STDDEF_H_ // #pragma INCMSG("--- Beg <stddef.h>") #include <stddef.h> // #pragma INCMSG("--- End <stddef.h>") #endif #ifndef X_SEARCH_H_ #define X_SEARCH_H_ // #pragma INCMSG("--- Beg <search.h>") #include <search.h> // #pragma INCMSG("--- End <search.h>") #endif #ifndef X_STRING_H_ #define X_STRING_H_ // #pragma INCMSG("--- Beg <string.h>") #include <string.h> // #pragma INCMSG("--- End <string.h>") #endif #ifndef X_TCHAR_H_ #define X_TCHAR_H_ // #pragma INCMSG("--- Beg <tchar.h>") #include <tchar.h> // #pragma INCMSG("--- End <tchar.h>") #endif // Core includes #ifndef X_F3DEBUG_H_ #define X_F3DEBUG_H_ #include "f3debug.h" #endif #ifndef X__F3DEBUG_H_ #define X__F3DEBUG_H_ #include "_f3debug.h" #endif #endif
19.747899
79
0.611489
King0987654
71a9fd975cf1f7c322f09d4adc40cf2502d74143
687
cpp
C++
03-Arrays/subarraysum2.cpp
ShreyashRoyzada/C-plus-plus-Algorithms
9db89faf0a9b9e636aece3e7289f21ab6a1e3748
[ "MIT" ]
21
2020-10-03T03:57:19.000Z
2022-03-25T22:41:05.000Z
03-Arrays/subarraysum2.cpp
ShreyashRoyzada/C-plus-plus-Algorithms
9db89faf0a9b9e636aece3e7289f21ab6a1e3748
[ "MIT" ]
40
2020-10-02T07:02:34.000Z
2021-10-30T16:00:07.000Z
03-Arrays/subarraysum2.cpp
ShreyashRoyzada/C-plus-plus-Algorithms
9db89faf0a9b9e636aece3e7289f21ab6a1e3748
[ "MIT" ]
90
2020-10-02T07:06:22.000Z
2022-03-25T22:41:17.000Z
#include<iostream> using namespace std; int main() { int n;cin>>n; int a[1000]; int currentsum=0; int maxsum=0; int left=-1; int right=-1; for(int i=0;i<n;i++) { cin>>a[i]; } for(int i=0;i<n;i++) { for(int j=i;j<n;j++) { currentsum=0; for(int k=i;k<=j;k++) { currentsum+= a[k]; } if(currentsum>maxsum){ maxsum= currentsum; left=i; right=j; } } cout<<endl; } cout<<"Maximum Sum is "<<maxsum<<endl; for(int k=left;k<=right;k++) { cout<<a[k]<<","; } return 0; }
17.615385
38
0.404658
ShreyashRoyzada
71add08d7d3fac9fb11e2cd01e74016a21164d1a
1,019
cpp
C++
PAT/A1155.cpp
iphelf/Programming-Practice
2a95bb7153957b035427046b250bf7ffc6b00906
[ "WTFPL" ]
null
null
null
PAT/A1155.cpp
iphelf/Programming-Practice
2a95bb7153957b035427046b250bf7ffc6b00906
[ "WTFPL" ]
null
null
null
PAT/A1155.cpp
iphelf/Programming-Practice
2a95bb7153957b035427046b250bf7ffc6b00906
[ "WTFPL" ]
null
null
null
#include<cstdio> #include<algorithm> #include<functional> using namespace std; const int MAXN=1e3; int N,heap[MAXN],path[MAXN],cnt; void dfs(int o) { path[cnt++]=heap[o]; int lc=o*2+1,rc=o*2+2; if(lc>=N && rc>=N) for(int i=0; i<cnt; i++) printf("%d%c",path[i],i==cnt-1?'\n':' '); else { if(rc<N) dfs(rc); if(lc<N) dfs(lc); } cnt--; } int main(void) { // freopen("in.txt","r",stdin); while(~scanf("%d",&N)) { for(int i=0; i<N; i++) scanf("%d",&heap[i]); cnt=0; dfs(0); if(is_heap(heap,heap+N,less<int>())) puts("Max Heap"); else if(is_heap(heap,heap+N,greater<int>())) puts("Min Heap"); else puts("Not Heap"); } return 0; } /* 8 98 72 86 60 65 12 23 50 8 8 38 25 58 52 82 70 60 8 10 28 15 12 34 9 8 56 98 86 23 98 86 12 98 72 65 98 72 60 50 Max Heap 8 25 70 8 25 82 8 38 52 8 38 58 60 Min Heap 10 15 8 10 15 9 10 28 34 10 28 12 56 Not Heap */
16.983333
75
0.50736
iphelf
71af7319bc7f7b6ab90ddfa8471be6bdba17c46a
1,248
cpp
C++
genomes/scripts/bounds.cpp
whelena/ginkgo
892b2e9f851f71a491cade6297f74f09f17acf4c
[ "BSD-2-Clause" ]
40
2015-06-15T14:17:15.000Z
2022-02-24T10:53:41.000Z
genomes/scripts/bounds.cpp
whelena/ginkgo
892b2e9f851f71a491cade6297f74f09f17acf4c
[ "BSD-2-Clause" ]
36
2016-04-10T07:35:39.000Z
2022-02-23T17:09:43.000Z
genomes/scripts/bounds.cpp
whelena/ginkgo
892b2e9f851f71a491cade6297f74f09f17acf4c
[ "BSD-2-Clause" ]
28
2015-07-02T21:14:38.000Z
2022-03-09T12:35:26.000Z
#include <iostream> #include <fstream> #include <string> #include <string.h> #include <stdlib.h> #include <vector> using namespace std; int main(int argc, char *argv[]){ ifstream bin_file(argv[1], ios::out); ofstream outfile(argv[2], ios::out); if(argc < 3) { cout << "Provide input and output files" << endl; return 1; } if(!bin_file.good()) { cout << "Unable to open input file: " << argv[1] << endl; return 1; } cout << "[Creating: " << argv[2] << "]" << endl; vector<pair<string, int> > bounds; pair<string, int> p; bool flag = true; string prev_chr; string new_chr; string dump; string chr; int cnt = 0; int loc; bin_file >> dump >> dump; //Ignore bin_file header while (!bin_file.eof()) { cnt++; bin_file >> new_chr >> loc; if (new_chr != prev_chr && flag == false) { p.first = prev_chr; p.second = cnt; bounds.push_back(p); prev_chr = new_chr; } if (new_chr != prev_chr && flag == true) { flag=false; prev_chr=new_chr; } } vector<pair<string, int> >::iterator it; for (it = bounds.begin(); it != bounds.end(); ++it) outfile << it->first << "\t" << it->second << endl; return 0; }
18.086957
61
0.564103
whelena
71afbf4202919189fedbc136b0c88992de25bc30
10,770
cpp
C++
csl/cslbase/tltime.cpp
arthurcnorman/general
5e8fef0cc7999fa8ab75d8fdf79ad5488047282b
[ "BSD-2-Clause" ]
null
null
null
csl/cslbase/tltime.cpp
arthurcnorman/general
5e8fef0cc7999fa8ab75d8fdf79ad5488047282b
[ "BSD-2-Clause" ]
null
null
null
csl/cslbase/tltime.cpp
arthurcnorman/general
5e8fef0cc7999fa8ab75d8fdf79ad5488047282b
[ "BSD-2-Clause" ]
null
null
null
// tltime.c Copyright A C Norman 2019 // Released under the modified BSD license - you can find the terms // of that easily enough! // $Id: tltime.cpp 5331 2020-04-25 13:47:28Z arthurcnorman $ // Cygwin and mingw32 both seem to use "emutls" to support the C++11 // keyword "thread_local". This can have performance consequences. // // The first thing is that this code illustrates is that in a worst case // scenario where a small and heavily-used function accesses a thread_local // variable the emutls scheme on x86_64 imposes a penalty that is a factor // of up to 20. The use-case I had in mind was a function like: // void *allocate(size_t n) // { void *r = (void *)fringe; // if ((fringe += n) < limit) return r; // ... // } // where making the variables fringe and limit thread_local can really hurt // overall system-wide performance. // // The resolution proposed here starts by giving up on the flexibility that // C++11 thread_local provides as regards declaring thread_local variables // anywhere and sometimes initializing them at the side of their definition. // It places all values that need to be thread_local (or at least all those // where access will be performance critical) in a structure, and using a // low level scheme to get a thread-specific pointer to that structure. // Allocating and initializing the thread-local structure is not an issue // addressed here! I use the Windows TlsAlloc, TlsSetValue and TlsGetValue // functions. I have two versions of this, one using the official Windows // entrypoints and the other re-implementing TlsGetValue (but omitting // validity checks!) such that it can be expanded in-line in my code. // // To use this one needs to collect all (or most) thread local variables // and replace them with structure members as in // typedef struct thread_locals_ // { uintptr_t fringe; // uintptr_t limit; // ... // } thread_locals; // thread_local thread_locals my_thread_locals; // Then at the startup of your code you need to allocate my_slot as shown // in the main() function here, and in EVERY thread you start you must go // TlsSetValue(my_slot, (void *)&my_thread_locals); // With that done, what used to be a simple reference to a variable, fringe // say, must be rewritten as ((thread_locals *)TlsGetValue(my_slot))->fringe. // or ((thread_locals *)tls_load())->fringe. These long and messy-looking // fragments might perhaps best be concealed via a header file containing // inline uintptr_t &TLfringe() // { return ((thread_locals *)tls_load())->fringe; // } // so that the main source code merely writes TLfringe() where it used to // write just fringe. Furthemore by wrapping the access through a function // like that it will be easy to conditionalize the code so that if C++11 // native thread_local is good enough it can be used: // inline uintptr_t &TLfringe() // { return my_thread_locals->fringe; // } // // // Timings as reported here are sensitive to minor issues such (perhaps) as // the alignment that various code fragments end up relative to where // cache lines fall. However the main message is that at least sometimes // on my Windows 10 host and Cygwin64 I see // simple non-thread-local case 1 // inline code working via GS 1.5 // use of TlsGetValue() 3 // use of C++11 thread_local 30 Cygwin, 15 Mingw // You are in fact entitles to use several different slots if your whole // project is split into several components - but you will then need to adapt // the code here so that each component uses its own "my_slot". #include <time.h> #include <iostream> #include <iomanip> #include <thread> #include <mutex> // The task I will perform will be just incrementing an integer. By // making it an integer in the middle of an array I illustrate that // I could be handling lots of thread-local data not just a single // word. This was set up as a simpler illustration that the use of // a struct as in the explanation above! thread_local int tl_vars[10]; int simple_vars[10]; #if defined __CYGWIN__ || defined __MINGW32__ #define ON_WINDOWS 1 #if __SIZEOF_POINTER__ == 4 #define ON_WINDOWS_32 1 #endif #endif // __CYGWIN__ || __MINGW32__ #ifdef ON_WINDOWS #include <intrin.h> // Provides code to read relative to FS or GS #include <windows.h> // This class exists so that its constructor and destructor can manage // allocation of a slot in the Windows vector of thread local values. class TLS_slot_container { public: int mine; TLS_slot_container() { mine = TlsAlloc(); } ~TLS_slot_container() { TlsFree(mine); } }; // On or before the first call of this the constructor for the // TLS_slot_container will be activated and that will allocate a slot. // These days I expect the C compiler to turn the implementation of this // into little more that a load from a static location in memory. It may // also have a test to see if the call is a first one so it can in that // case do the initialization. // Just one slot-number is needed for my entire program - the same value is // used by every thread. inline int get_my_TEB_slot() { static TLS_slot_container w; return w.mine; } #ifdef CAUTIOUS // The CAUTIOUS option uses the Microsoft API to access thread-local slots, // and so should be robust against potential changes in Windows. inline void *tls_load() { return reinterpret_cast<void *>(TlsGetValue(get_my_TEB_slot())); } std::uintptr_t tls_store(void *v) { return TlsSetValue(get_my_TEB_slot(), v); } #else // CAUTIOUS // The version is intended and expected to behave exactly like the version // that calls the Microsoft-provided functions, except (1) it does not // do even basic sanity checks on the slot-number saved via get_my_TAB_slot() // and (b) it can expand into inline code that then runs faster that the // official version even if it does just the same thing. #ifdef ON_WINDOWS_32 // I abstract away 32 vs 64-bit Windows issues here. The offsets used are from // www.geoffchappell.com/studies/windows/win32/ntdll/structs/teb/index.htm // which has repeated comments about the long term stability of the memory // layout involved. #define read_via_segment_register __readfsdword #define write_via_segment_register __writefsdword #define basic_TLS_offset 0xe10 #define extended_TLS_offset 0xf94 #else #define read_via_segment_register __readgsqword #define write_via_segment_register __writegsqword #define basic_TLS_offset 0x1480 #define extended_TLS_offset 0x1780 #endif // Windows 32 vs 64 bit inline void *extended_tls_load() { void **a = (void **)read_via_segment_register( extended_TLS_offset); return a[get_my_TEB_slot() - 64]; } inline void extended_tls_store(void *v) { void **a = (void **)read_via_segment_register( extended_TLS_offset); a[get_my_TEB_slot() - 64] = v; } inline void *tls_load() { if (get_my_TEB_slot() >= 64) return extended_tls_load(); else return reinterpret_cast<void *>(read_via_segment_register( basic_TLS_offset + sizeof(void *)*get_my_TEB_slot())); } inline void tls_store(void *v) { if (get_my_TEB_slot() >= 64) return extended_tls_store(v); else write_via_segment_register( basic_TLS_offset + sizeof(void *)*get_my_TEB_slot(), reinterpret_cast<std::intptr_t>(v)); } #endif // CAUTIOUS #endif // ON_WINDOWS // Now the four versions that I will compare. I force each to avoid getting // inlines because gcc is so clever that if it can inline them it does not // do anthting at all like the work I intend! Of course in a "real" use-case // the individual functions using data that might want to be thread_local // will be such that optimisation is not so easy, and inlining may be // prevented by complicated code or separate compilation. [[gnu::noinline]] void simple_inc() { simple_vars[5]++; } [[gnu::noinline]] void tl_inc() { tl_vars[5]++; } #ifdef ON_WINDOWS // These two tests are only relevant on Windows-based systems. [[gnu::noinline]] void windows_inc() { (reinterpret_cast<int *>(TlsGetValue(get_my_TEB_slot())))[5]++; } [[gnu::noinline]] void gs_inc() { (reinterpret_cast<int *>(tls_load()))[5]++; } #endif // ON_WINDOWS // This function times a function by calling it 0x40000000 times. It // sets the location to be incremented to zero first and displays the // value it has at the end as a rather crude verification that something // has happened. void timeit(const char *name, void (*fn)(), int *var) { std::cout << "Address of my workspace is " << var << std::endl; std::clock_t c0 = std::clock(); var[5] = 0; for (unsigned int i=0; i<0x40000000; i++) (*fn)(); std::clock_t c1 = std::clock(); std::cout << "incremented value = " << var[5] << " "; std::cout << std::setw(25) << name << " " << std::fixed << std::setprecision(2) << ((c1-c0)/static_cast<double>(CLOCKS_PER_SEC)) << std::flush << std::endl; } std::mutex mm; // Here I run all the three test cases that I have. I use a lock_guard so // that only one instance of this runs at any time, and in particular so // that the output that is generated ends up tidy. void runtests(const char *msg) { std::lock_guard<std::mutex> gg(mm); std::cout << "Running " << msg << std::endl; timeit("simple variable", simple_inc, simple_vars); #if defined ON_WINDOWS // Each thread must set the slot that is relative to ITS version of the GS // segment register to point at the data that it will use. TlsSetValue(get_my_TEB_slot(), reinterpret_cast<void *>()&tl_vars); #ifdef ON_WINDOWS_32 timeit("thread local via FS", gs_inc, tl_vars); #else timeit("thread local via GS", gs_inc, tl_vars); #endif TlsSetValue(get_my_TEB_slot(), reinterpret_cast<void *>()&tl_vars); timeit("Using Windows Tls API", windows_inc, tl_vars); #endif // ON_WINDOWS // The final test uses direct C++11 "thread_local" storage qualification. // It is the "obvious" way to use thread local data. timeit("C++11 thread_local", tl_inc, tl_vars); } int main(int argc, char *argv[]) { #if defined ON_WINDOWS // I deliberately allocate (and waste) over 64 slots to start with so that // the one I end up with will be an "extension slot", which will lead // to the more expensive path through my access code. for (int i=0; i<70; i++) TlsAlloc(); #endif // ON_WINDOWS // Run all tests in the main program... runtests("direct"); // ...then create a thread and run them in it. std::thread t1(runtests, "in a thread"); t1.join(); return 0; } // end of tltime.cpp
36.883562
78
0.705478
arthurcnorman
71afde0f14be22a48d284bdc4de2c93b2696594a
3,396
cpp
C++
src/software/gui/robot_diagnostics/threaded_robot_diagnostics_gui.cpp
jonl112/Software
61a028a98d5c0dd5e79bf055b231633290ddbf9f
[ "MIT" ]
null
null
null
src/software/gui/robot_diagnostics/threaded_robot_diagnostics_gui.cpp
jonl112/Software
61a028a98d5c0dd5e79bf055b231633290ddbf9f
[ "MIT" ]
null
null
null
src/software/gui/robot_diagnostics/threaded_robot_diagnostics_gui.cpp
jonl112/Software
61a028a98d5c0dd5e79bf055b231633290ddbf9f
[ "MIT" ]
null
null
null
#include "software/gui/robot_diagnostics/threaded_robot_diagnostics_gui.h" #include <QtCore/QTimer> #include <QtWidgets/QApplication> ThreadedRobotDiagnosticsGUI::ThreadedRobotDiagnosticsGUI(int argc, char** argv) : FirstInFirstOutThreadedObserver<SensorProto>(), termination_promise_ptr(std::make_shared<std::promise<void>>()), sensor_msg_buffer( std::make_shared<ThreadSafeBuffer<SensorProto>>(sensor_msg_buffer_size)), primitive_buffer(std::make_shared<ThreadSafeBuffer<TbotsProto::PrimitiveSet>>( primitive_buffer_size)), application_shutting_down(false) { run_robot_diagnostics_thread = std::thread( &ThreadedRobotDiagnosticsGUI::createAndRunRobotDiagnosticsGUI, this, argc, argv); run_send_primitives_thread = std::thread([this]() { while (true) { auto primitive = primitive_buffer->popLeastRecentlyAddedValue(); if (primitive) { this->sendValueToObservers(std::move(primitive.value())); } std::this_thread::sleep_for( std::chrono::milliseconds(send_primitive_interval_ms)); } }); } ThreadedRobotDiagnosticsGUI::~ThreadedRobotDiagnosticsGUI() { QCoreApplication* application_ptr = QApplication::instance(); if (!application_shutting_down.load() && application_ptr != nullptr) { // Call the Application in a threadsafe manner. // https://stackoverflow.com/questions/10868946/am-i-forced-to-use-pthread-cond-broadcast-over-pthread-cond-signal-in-order-to/10882705#10882705 QMetaObject::invokeMethod(application_ptr, "quit", Qt::ConnectionType::QueuedConnection); } run_robot_diagnostics_thread.join(); run_send_primitives_thread.join(); } void ThreadedRobotDiagnosticsGUI::createAndRunRobotDiagnosticsGUI(int argc, char** argv) { // We use raw pointers to have explicit control over the order of destruction. // For some reason, putting the QApplication and RobotDiagnosticsGUI on the stack does // not work, despite theoretically having the same order of destruction QApplication* application = new QApplication(argc, argv); QApplication::connect(application, &QApplication::aboutToQuit, [&]() { application_shutting_down = true; }); RobotDiagnosticsGUI* robot_diagnostics = new RobotDiagnosticsGUI(sensor_msg_buffer, primitive_buffer); robot_diagnostics->show(); // Run the QApplication and all windows / widgets. This function will block // until "quit" is called on the QApplication, either by closing all the // application windows or calling the destructor of this class application->exec(); // NOTE: The robot_diagnostics MUST be deleted before the QApplication. The // QApplication manages all the windows, widgets, and event loop so must be destroyed // last delete robot_diagnostics; delete application; // Let the system know the robot_diagnostics has shut down once the application has // stopped running termination_promise_ptr->set_value(); } void ThreadedRobotDiagnosticsGUI::onValueReceived(SensorProto sensor_msg) { sensor_msg_buffer->push(sensor_msg); } std::shared_ptr<std::promise<void>> ThreadedRobotDiagnosticsGUI::getTerminationPromise() { return termination_promise_ptr; }
40.428571
152
0.717314
jonl112
71b04db4d2e38dcdb2eacb58b34b5fefb1f20b26
1,715
cpp
C++
gen/src/model/Port.cpp
cpp-openapi/dockerctl
44da21c32509fb7e44c93551a41ceb14c42c18b1
[ "Apache-2.0" ]
null
null
null
gen/src/model/Port.cpp
cpp-openapi/dockerctl
44da21c32509fb7e44c93551a41ceb14c42c18b1
[ "Apache-2.0" ]
null
null
null
gen/src/model/Port.cpp
cpp-openapi/dockerctl
44da21c32509fb7e44c93551a41ceb14c42c18b1
[ "Apache-2.0" ]
null
null
null
/* * Port.cpp * * An open port on a container */ #include "Port.h" using namespace openapi; // macro should do the same job. Not really // OPENAP_JSON_CONVERT_FUNCS(Port, IP, PrivatePort, PublicPort, Type) void Port::ToJSON(Json & j) const { // OPENAPI_FOR_EACH(OPENAPI_TO_JSON_MEMBER, __VA_ARGS__) j.AddMember<decltype(this->ip)>(openapi::StringT(OPENAPI_LITERAL(IP)), this->ip); j.AddMember<decltype(this->private_port)>(openapi::StringT(OPENAPI_LITERAL(PrivatePort)), this->private_port); j.AddMember<decltype(this->public_port)>(openapi::StringT(OPENAPI_LITERAL(PublicPort)), this->public_port); j.AddMember<decltype(this->type)>(openapi::StringT(OPENAPI_LITERAL(Type)), this->type); } void Port::FromJSON(const Json & j) { // OPENAPI_FOR_EACH(OPENAPI_FROM_JSON_MEMBER, __VA_ARGS__) if(j.HasKey(openapi::StringT(OPENAPI_LITERAL(IP)))) { using V = remove_optional<decltype(this->ip)>::type; this->ip = j.GetMember<V>(openapi::StringT(OPENAPI_LITERAL(IP))); } if(j.HasKey(openapi::StringT(OPENAPI_LITERAL(PrivatePort)))) { using V = remove_optional<decltype(this->private_port)>::type; this->private_port = j.GetMember<V>(openapi::StringT(OPENAPI_LITERAL(PrivatePort))); } if(j.HasKey(openapi::StringT(OPENAPI_LITERAL(PublicPort)))) { using V = remove_optional<decltype(this->public_port)>::type; this->public_port = j.GetMember<V>(openapi::StringT(OPENAPI_LITERAL(PublicPort))); } if(j.HasKey(openapi::StringT(OPENAPI_LITERAL(Type)))) { using V = remove_optional<decltype(this->type)>::type; this->type = j.GetMember<V>(openapi::StringT(OPENAPI_LITERAL(Type))); } }
35.729167
114
0.695627
cpp-openapi
71b0f782717d87abd9736880fcde2d5e0bfe6ab8
640
cpp
C++
src/context/StringType.cpp
pougetat/decacompiler
3181c87fce7c28d742f372300daabeb9f9f8d3c6
[ "MIT" ]
null
null
null
src/context/StringType.cpp
pougetat/decacompiler
3181c87fce7c28d742f372300daabeb9f9f8d3c6
[ "MIT" ]
null
null
null
src/context/StringType.cpp
pougetat/decacompiler
3181c87fce7c28d742f372300daabeb9f9f8d3c6
[ "MIT" ]
null
null
null
#include "StringType.h" bool StringType::IsBooleanType() { return false; } bool StringType::IsFloatType() { return false; } bool StringType::IsIntType() { return false; } bool StringType::IsStringType() { return true; } bool StringType::IsVoidType() { return false; } bool StringType::IsClassType() { return false; } bool StringType::IsNullType() { return false; } bool StringType::IsSameType(AbstractType * other_type) { return other_type->IsStringType(); } string StringType::Symbol() { return string("string"); } string StringType::JasminSymbol() { return string("Ljava/lang/String;"); }
12.54902
54
0.682813
pougetat
71b183e0cbec056814a6fde953c91c890475351d
15,257
cpp
C++
data/112.cpp
TianyiChen/rdcpp-data
75c6868c876511e3ce143fdc3c08ddd74c7aa4ea
[ "MIT" ]
null
null
null
data/112.cpp
TianyiChen/rdcpp-data
75c6868c876511e3ce143fdc3c08ddd74c7aa4ea
[ "MIT" ]
null
null
null
data/112.cpp
TianyiChen/rdcpp-data
75c6868c876511e3ce143fdc3c08ddd74c7aa4ea
[ "MIT" ]
null
null
null
int Rgpz , u7, nT//a ,M4ElL /*d*/,DhV , xKKv7, Aev7f ,puj, E,hI, TGe,oN /*G6Iat*/ , //k aA, //U6 zWZLO ,//DEw MTL ,rq , a9 //Xt ,vu5 ,eHB,v8Y , osHw/*jo*/, h ,M,IT,//fpe dq5 ,PEwG, xq, dOu , AzCI, Z3sCV , sOO , LJ , WbN5,z ,pzg8 , duU4, QztyO , oDdEz/*UQ*/, Fndz , GdVz, OkxM,r,Vzf, xi// ,DiZ ,l ,pR ,/*B3O*/ Zjo , G,TFB, /*AJ*/x4 , Qrj , byD, lkDzm , otr, // il,ILc1, E2 , zfJVQ ,/*iCb*/ TG8, rKN,Xaw ,Rh4 ;void f_f0 (){{/**/ volatile int u6Pym, t2, iS5,TPF, R ; { return ; { /*f*/for (int i=1; i<1 ;++i ){ { ; } } }for (int i=1// ;i<2 //SLpVr ;++i){ return ; } { {} {{int cvw;volatile int Fp ;cvw = Fp ;for(int /*b*/i=1;i< 3 ;++i ) { } }/*3a*/if/*faJ*/(true)return ;else { { }} }{ {{ int Ci; /*D08*/volatile int nf8m ; if ( true){ } else Ci=nf8m ; } }} //Hqm {}}} Rh4= R + u6Pym +t2+ iS5 +/**/ TPF ;for (int i=1;i<4 ;++i) { int//3 jIB7QI; volatile int nwae,x , qpA, Q6,s0 ,j ,L, RP ;Rgpz=RP /*c*/+ nwae+x ;jIB7QI= qpA +Q6+s0 +j + L ; }return ; }{ volatile int utJ, X, jgs ,gNV3 ; { int m /*h*/;volatile int gjLk,V2O//OLmIW ,KVH , //d cy0R; m =cy0R + gjLk+ V2O + KVH ; ; return ; { volatile int UEo , traz, s9; return ;for (int i=1 ; i<5/*cR*/;++i ) /*SD*/ { /*H*/if(true) {}else { return ; } }{} if ( true ) return ; else u7 = //bEy s9 + UEo +/*E2iV*/traz; } } {{ { { { }}{} } if( true ){ for(int i=1; i<6 ;++i//G //qPa )for(int i=1; i< 7;++i){} } else{/*y2*/int fG; volatile int kC , tgG,//f i1fUe ;fG =i1fUe + kC+ tgG; } }{for//G (int i=1 ;i<8 ;++i ) if (true) ;//s else ;/*zN*/} return ;{ {} { //artB7 ;{ } } }} nT = gNV3+ utJ + X +jgs ;if( true ){ volatile int kY, D//PRE ,m0v ,Fp4D, y ,v,//rI X7, CYb2J ,MSW; ;for//0pg (int i=1 ; i< 9 //t ;++i )/*P*/; if/*7AW*/ (true) M4ElL =/*G7t*/MSW+ kY + D //fpu + m0v + Fp4D; //xwmY else//SS9 if ( true) if(true){ volatile int T , dDGX , QLP , GPmY , jt ; for (int i=1 ;i<10 ;++i)//5Q DhV = jt+T /*THJt*/+ dDGX +QLP+GPmY; }else //z { ;//6Y5 }/*5Z*/ else xKKv7=/*q*/ y+v + X7+ CYb2J ;} else { volatile int GGui ,HJ0 , UE6F8 , m8 ;{int LHG72 ;volatile int u0I ,xuQ, zbs ;LHG72 //kUlC =zbs +u0I+ xuQ ;for(int i=1; i< 11;++i) if(true ) for (int i=1; i<//su7 12 ;++i )if ( true ) { { } }else{for (int i=1 ; i< 13;++i) {} for (int i=1; i< 14;++i ){}}/*g3*/else { int IZ;volatile int A ,zY ;IZ= zY + A ;} {{ return ; ;}}{ }} Aev7f= m8 +GGui +HJ0 +UE6F8 ; } return ;{//M7 int QzK ;volatile int //D XW9,YI , SBu , i ,Gmo1 , PlIr , BN1j,Yph ,vNQv2QrY ,XhSY,//HV dM ;puj = dM +XW9 +YI+ SBu ;E=/*Sr*/i//SwrMw +/*TCN*/Gmo1 +PlIr+ BN1j ;;{ return ;return ;{ {}} } QzK = Yph +//S vNQv2QrY+XhSY ; } }if (true) {{/*vBrFF*/volatile int G8,AoceGT//6r ,/*N*/Jw//v ; {int F ; volatile int TmL , I1eY,aol ,bE , SbmW,cAwA , /*kc*/wJF ,hfAr ; hI=/*H*/ hfAr + TmL +I1eY; F = aol + bE+ SbmW+ /*7udH*/cAwA +//OHM wJF ; { {} }} TGe = Jw//0Q + G8+AoceGT;for (int i=1 ; i<15;++i ) {{{ } }/*ZJW*/}} /*Fgu*/{ //wVtP /*NV*/ int mf; volatile int Ilv9yon, IoY3 ,Lgys ,J83 ,n7c ,Doz,tq3r /*j*/;return ;/*DJ5*/ if //afE ( true ) return ;else mf =tq3r // +Ilv9yon + IoY3 ; for(int i=1 ; i< 16 ;++i )/*A*/{{ {}}/*ah*/ { ; { {}if (true ) if(true){ } else { } else for (int i=1;i<17 ;++i )/*6*/{ } } }} oN= Lgys+J83 +n7c + Doz /*1*/; }for (int i=1 ;i< 18;++i) return ; {int MHo ;volatile int /*x53S*/ uU4D, IEXNzF , //s caEv ,iOd , UIU ;{return ;/*0*/{ volatile int w8,bi/*vC6b*/;{} aA = //SYjo bi/*w7O*/ + w8; for/*P*/(int i=1/*e*/; i<19 ;++i ) for/*JL*/ (int i=1 ; //H7 i<20;++i//mxs ) return ; }} for (int i=1 ;/*2Tb*/i< 21;++i) MHo =UIU +/*7*/uU4D + IEXNzF //t5 + caEv + iOd ; //PScR } } else//4MB0 return ;;{ volatile int We1m , uuLv6 , h6y3,g ; zWZLO = g + We1m + uuLv6 +h6y3; {{for (int i=1;i<22;++i ) return ; { for /*Smh*/(int i=1 ; i< 23 ;++i )//vdJr if(true ) { }else for (int //Zd8v i=1//4R ;i<24//cZ //PDd ;++i){ }return ; }}//LX8Z { {/*Snw*/ {for(int i=1; i<25;++i ) { } } return ;} { if ( true ){ } else { } } } for (int i=1 ;i<26 ;++i ) { { }{} } ; }{{ for (int i=1 ; i< 27 ;++i ) { volatile int GY9O , px; if ( true );else for(int i=1 ; i<28 ;++i)/*Nflon*/{ }MTL = px//2V + GY9O; } { } } { { } }}{ { { for(int i=1 ;i< 29 ;++i); }//mjqo {}/**/} if (true ){{{}}} else if (true )return// ; else { ;}} }; return ; }void f_f1 () { { volatile int deI//TF1 , Hj ,fE7d , BH,tD ; rq=tD +// deI+ Hj +fE7d +BH ;{ {volatile int kktuj ,Ymz, wIYV ; {{ } }a9 = wIYV + kktuj+Ymz ; } { volatile int /*7E*/ Co ,aj, wsy ; vu5=wsy + Co + aj ; { if/*Z*/( true) { } else ; }}} { if ( //y true)if(true) {{}{ { }}{ volatile int o9A,CI;eHB= CI + o9A ; { }{ } }//inRj }else{ { /*BE0*/for (int i=1;i<30 ;++i/*i1*/){}; } }else { {} }{ volatile int FO9X,kAo1 ,SCn ,F25;{ {} }v8Y=F25 + //ISw FO9X + kAo1 +SCn; { return ; } } if(true );/**/else ;//dZ }{volatile int Y4 ,Nu ,gh2,Jom8E ; { volatile int //f pKhF , CL ,/*Rt*/ FD ; ;if ( true ) osHw = FD +//E pKhF + CL; else { { { } }{ }} if ( true )return ;else ;} if ( true ) //i8 for (int i=1 ; i< 31 ;++i) if( true ) h//FXtgrfC = Jom8E//s44 +Y4+ Nu+ gh2;else ;else //Rbf for (int i=1// ; i< 32;++i ) if ( true){ return ; {volatile int MaB ;M= MaB ;// }} else return ; { int QWMO9x ;//RS volatile int Bn ,FCU ;QWMO9x =FCU + Bn ; ; }} }{//m { if ( true )return ;else{ return ; {} ;} { {return ; } }}{volatile int JHwd//x ,c , P4 /*yu*/ , Ob3;{ {//9 }}//Dlv IT = Ob3//C6 +JHwd + c + P4; if// (true){ {} } else { {{ for//7 (int i=1 ; i< 33 ;++i ) {/*Pn*/ } for (int i=1//Tmw1 ;//Imxo i<34 ;++i )//vX if ( true) /**/{ } else{} } }//4b52 {} { } }} { {for (int i=1 /**/ ; i<35;++i ) {int m4;volatile int//r ZG; m4 =ZG; { } } {{ //U } ;} }for//8IZ (int i=1 ; i< 36;++i) { {; } { } } }return ; if (true ) {int f ; volatile int o6Rq,Eyc , Of , BB;{{ if (true ) {} else ; if ( true ){ {}{ }for (int i=1//DX ;/*zWq*/i<37 ;++i ) { } } else { }} if (true) if (true )return ;else {}else { { }//IR20 { }} {} } for(int i=1; i< 38 ;++i) { {volatile int U; dq5 =U ;return ;}for(int //B i=1 ; i< 39 ;++i ){} /**/ } { int daB ; volatile int PG ,t2ks7 ,qRS03w ,/*eUd*/Y5W ;//wHqM daB =Y5W +PG ;PEwG= /*b*/t2ks7 +qRS03w ;{ } } return ; f = BB +o6Rq + Eyc +/*T*/Of ; { {for (int i=1 ;//lgy i<40;++i) {} }}// } else {{for (int i=1; i<41 ;++i) if ( true /*F*/ ){ { }} else{ { } { }}/*dy*/{ { for (int i=1 ;/*sh*/ i< 42;++i )if( true ) { }else{} } {} } }{ volatile int ugTP ,//t5I1 ZS4 , goAL ; // if ( true ) xq = goAL+ ugTP//7 + ZS4 ;else { { } for (int i=1 ; i<43 ;++i)if(true) /*7*/; else { }}{ {; }} { if ( true) {//H } else { }//WOA for (int i=1 ;i< 44 ;++i /**/) {}/*W*/} {{} } }} }for(int i=1 ; i<45;++i )return ;;{volatile int sSN, mL ,U5 ,OO,CtZu ,T4 , THxD//1xzGJR ;{int/*Z0*/ XI ; volatile int Em0a, //WjLD SPSIg, oB8 ,// fD5v ,/*pWd*/MpC;{{/*ja4*/volatile int KwrlH9N,cKTN ; {}for (int i=1 ;i< 46 ;++i) dOu =cKTN +KwrlH9N ;} {/*zQ*/ { }} ;//tZ } XI = MpC+ Em0a+ SPSIg + oB8+fD5v ; {for(int i=1 ; i< 47;++i ) { { } } { } }//xG6y } AzCI =THxD + sSN + mL/*Gi*/ + U5 +OO +//CWa CtZu+T4 ;for(int i=1 ;i< 48 ;++i) {{ int zlK ;volatile int yXmL , PvSjB //m330 , k7 ; if( true ) zlK= k7 +yXmL+ PvSjB ;else/*f*/ if ( true)/*o27SXKO*/{} else return ; { //9M { }} } {if ( true ) ; else {}} } }{ return ; { //I int JMlhx ; volatile int IxA ,iYB7G//Siz , VwH, al/*5J*/; { for(int i=1 ; i<49;++i) {{ { } } } return ;{} if ( true ){ } else return ; }{{/*4j*/ //QtC int gApP; volatile int NoiaA , b ; if ( true )gApP=/**/ b + NoiaA ; else if ( true ) {/**/ }else { } if( true )/*pI8B*/ { } else{ } }{ }if( true) { return ;} else return ; }if ( true ) for (int i=1 ;//Uf9 i<50// ;++i ) JMlhx=al +IxA+ iYB7G +VwH; //vqva else ; };;{ { {for (int i=1; i< 51;++i ){} // }} { volatile int KR3, fH, gMV ; if (/*Ba*/true /**/){ if(true/*5*/) return ;else{{ } } } else return/*GnU*/ ; {} Z3sCV= gMV +/**/KR3 +fH ;{ { } { } } }{ for (int i=1 ; i<52 ;++i) {{if(true//oQW ) {}else//J61b if/*k*/ ( true)return ; else ; } };} //s71 }}//BEA return ; }void f_f2() /*ZK*/ {{//v0r7 { { { {{ } } }}{volatile int w , kXeL;{ volatile int xXX,RLK;sOO =RLK + xXX;} {;{}}LJ=//R9 kXeL+ w; } return ;{volatile int wqV,rhgIY4 ; ;WbN5=rhgIY4+/*mgUi*/wqV; //Id } }{ volatile int s4x ,/**/ Gc , jTEnyP ; if( true )return ; else //X70fM {//vu2 int /*g*/ zwdA0M ;volatile int cuDd3,ZRs;zwdA0M = ZRs /*y0*/ +cuDd3 ; return ; ;} z = jTEnyP + s4x + Gc ; } { ;{ ; } {for (int i=1;/*5h5*/i</*9c*/53;++i ) /*U0U8*/{{ { } } }for(int i=1 ;i<54 ;++i ) for (int i=1 ; i< 55;++i )//0yfrp return ;} if (/*Uf7O*/ true ) for(int i=1; i<56 ;++i)/*KGy1e4*/if( true ) {/*M*/{ { }{}//t /*s*/} ; { int Fs//Qrp70 ;volatile int cQ , aQ ,pf;if ( true) Fs= //bXif pf +//2C cQ ; else {} pzg8=aQ ;{ } }} else if(true ) {volatile int IWG , IUb, u9iw ;duU4 =u9iw + IWG //Cnr + IUb; {{ }} /**/}else { volatile int trk , ik, v1T,O8oW ; QztyO= O8oW + trk + ik+ v1T ; {volatile int WDTu; //n oDdEz = WDTu ; };/*j3YK*/ /*x*/}else{ ; { return ; } }/*1*/ }{ { { } {} }if ( true) {return ;{ volatile int umyWr, kFbw; { //iL } Fndz=kFbw+ umyWr ;} { { }}} else { volatile int Ke ,Hj3, W, acA3// ;GdVz = acA3 + /**/ Ke//K2Gls +Hj3+W; return ;} if (true) {/*o8k*/{volatile int /*5*/ R6fi7; for(int i=1 ; i<57;++i )OkxM= /*Ia*/ R6fi7 ; } ;} else//2u { volatile int Q,//0sO Y , cEJ8; {}r =cEJ8+ Q +Y; { {} { }}{ {} } /*uPH*/} } } { /*D*/volatile int C ,R0m ,WMze, uqC,/**/xjD; { //Pl if ( true) ;else ; { return ; } if( true){int//rS b5Ta ;volatile int UU ,lutW ,b8FH , htjY/*Y*//*M*/;for(int i=1 ;i<58 ;++i );b5Ta =htjY+UU+ //M6z lutW/*QW*/+ b8FH;//6nYu {/*CoE*/ }{; }/**/ } else { {}} } return ;{ return ;//Y { volatile int Nxq, gb; Vzf //VR =gb + /*QkTi8*/Nxq ; { { }}} }/*Pe9Q*/{volatile int//Xa vp, V, oNt ; xi=oNt +vp + V ; {{}//RRr for (int i=1; i<59 ;++i ) /*AKY*/{ }}{/**/ {} for (int i=1 ; i<60 ;++i ){ } /*ekL*/if( true/*fLD*/) if ( true)if( true )//r { volatile int Exvso , ieUAh ,Om ;DiZ =Om+Exvso+ ieUAh ; { } } else { }//A else ; else return ;}/**/}//4uIQ88 l=xjD + C+R0m + WMze+//yw uqC; }{ { if (true ){volatile int bs,nf;pR= nf /*rV*/ + bs ; { } }else /*0f*/ for (int i=1; i<61 ;++i )/*t*/ ; {int UDsS ; volatile int r4KZ , BT ;{ if //L ( true ) { } else//k { } } UDsS = BT + r4KZ ;{ } { { } }}/*p5*/return ; } {for(int i=1;i<62 ;++i ) if( true){{ } if (true){ { volatile int/*a*/ FgJmJV6 ; Zjo = FgJmJV6; } } else{ { }{ }} //ISG } else{return ;return ; { return ; }for (int i=1; i< 63 ;++i )return ;} { volatile int U90, kENn,bCW ;{ return ; for (int i=1 //tXk ; i< 64 ;++i ) for (int i=1 ; i<//WO 65 ;++i)if //A (true) { }else { }return /*Gx*/ ;} if ( true ) if (true ) for(int i=1; i<66;++i ) ; else{ }else{ } G =bCW+//ql U90+ kENn ; }{ for(int i=1; i<67;++i ) { volatile int q,yfMrQP ,//wm R0; TFB=R0 +q+yfMrQP;/*YXe*/}} ;} {//uz ;return ; {volatile int ekj5, KJLT , amsJ, //y CGW; x4= //RfQ CGW+ekj5 +KJLT + amsJ; {} }{int a2M ; volatile int X8b ,WfE, yR3k9 ; if ( true )// a2M=yR3k9 + X8b+ WfE; else ; {volatile int Q0poj , nA ; Qrj=//R nA+ Q0poj ;return ; } } }} {{ {; for (int i=1/*mig*/ ; i< 68 ;++i) ;}{for(int i=1 ; i<69 ;++i) ;} }return ; if (true){{ {{ }}/**/return /*YUK0*/ ; for (int i=1 ; i< 70;++i ) {//ggR12 /*ln*/}} if( true ) for (int /*F*/ i=1; i<71 ;++i )//n {return ;/*Z2yB*/ {return ; }{ ;} }//qzbMZ else//Tk {{ } {}} if (true ) ; else if ( true ) if (true ) { { {}for(int i=1 ; i< 72 ;++i ) //sw { {} } }return/*r6*/ ; }else {{}}else return ;{ {{{}} } for(int i=1;i<73;++i ) { } ;/**/ } { if ( true ) { if(true) for(int i=1//fP ; i</*s6*/74 ;++i){ } else{}/*eO3n*/{ } /*Bzh*/}else {volatile int ow; byD = ow;}} }else {{int/*2*/ S ; volatile int i0j , dKQ;S/*G*/=dKQ+ i0j ; {volatile int w1 ;/*HH6*/lkDzm = w1;} } ;/*pjRi*/if(true) /*i2*/ { volatile int obB ,Ve9 , je ; otr = je+ obB+Ve9 ;} else ;} } /*Zhn*/return ; } int main () { {/*prxM8*/int N ;volatile int f2zl, mOuB, j2UT , H2Ub, Z3Z6 ; {// volatile int f3WeH ,FcFh , oNEo,IMrF ; /*HU*/{ for(int /*K*/i=1 ;i<75 ;++i) ; } {for (int // i=1; i< /*T*/76 ;++i ) if//c (true ) return 17147934 ; else ; { { } { } }return 2010087196;{} }il =IMrF//bEP +f3WeH +FcFh+ oNEo;}return 1451764732; ;N = Z3Z6 +/*hpEW*/f2zl+ mOuB+j2UT + H2Ub; } { { { int Cmhq ; volatile int//N /*sj*//**/ jpXy9 ,o0, K8HP5,kD,/*MQ*/ZYAb /*k*/,iL3;for(int i=1; //Bij i< 77/*y78*/;++i ) if (true) for (int i=1; i<78//V7 ;++i) { } else Cmhq = iL3 +jpXy9//r52 +o0;/*66Vm*/ILc1 =K8HP5 + /*68ZL*/kD +ZYAb ; } ;; for(int i=1 ; i</*KH*/79 ;++i ) {/**/ /*Ne*/ { } }} ; ;} { { int v9VRI ,//fKo lIC;volatile int IbQi //7s , Jl,kal , Q34 , P9Jx,qx , bZJEP ,qoi, T8M0S,/*uBG*/RCr,BmLC , XeAf ;{ {;/*1*//*V5G*/ {} } }lIC =XeAf+IbQi +Jl+kal; E2=Q34 + P9Jx +qx +bZJEP ;{ if (true ) for (int i=1; i< 80 ;++i// ) { { } ;}else for (int i=1 ;//TJ i< 81//lwJ ;++i) ;{ if ( true) ; else { } }/*B*/ }v9VRI = qoi +T8M0S + RCr + BmLC; }{return 274366465 ; {{ { } return 1919818101 ; {{ }} }} } {for(int i=1 /**/; i<82 ;++i ){ return 1891735511 ;{ { }} }//Abd return 424810962 ; {{for(int i=1// //gRK ; i<83;++i // ){} }if ( true)return 1547636099 ;else return 1011285425; };}{ /*A*/return 1978825989; // return 826721;} //usS } { volatile int /*9yF*/ PJk3//hOr ,Vy, JatV , XSB , ySQa ; //89 zfJVQ= ySQa+ PJk3 + Vy /**/+ JatV+XSB//s ; if ( true) //wn for (int i=1;i< 84;++i );else{{{ int FUxE; volatile int//eBQ pA //W , U6ds; FUxE= U6ds + pA; } } { if// (true ){ ; {} {} } else for (int i=1//R ;i<85;++i ) { {}}{ }{ { }return 697538712 ;}; }} if (true //rw )//1aJ return 420913475;else { int ovB ;volatile int UbQ ,/*o5Pl*/IEdf , eBe, Bs,Iob ,/*6f*/ Ql//R ;/*dlYCo*/ovB =Ql+UbQ//m + IEdf/*Or*/;TG8 =eBe/*jXbOuy*/+ Bs + Iob; return 1980489708 ;/*5p2*/;} { /*5*/; if ( true){ {{int v5Te ; volatile int KVO ,//jT9pk iE ;v5Te= iE+KVO ; } }for (int i=1 ; i<86 ;++i ) if(//BeR true ){volatile int X9ats , GP//ZZ ;{{ /*5*/}}rKN = GP+ X9ats ;return 994250986 ;} else{ { {}/*xCm*/ } } } else return 2061753923; for (int i=1 ; i< 87 ;++i){ volatile int BS1L , KvF9c, NQ ;for(int i=1 ; i< 88 ;++i )/*5*/return 535255701 ; Xaw = NQ + BS1L + KvF9c/*9Z0uf*/ ;}} } //sx ;//Piej ;}/*TDF9*/
10.400136
81
0.457364
TianyiChen
71b186d6347bb2f3f565617bd1181323eddfeef8
703
cpp
C++
kattis/problems/pet.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
1
2020-07-16T01:46:38.000Z
2020-07-16T01:46:38.000Z
kattis/problems/pet.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
null
null
null
kattis/problems/pet.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
1
2020-05-27T14:30:43.000Z
2020-05-27T14:30:43.000Z
#include <iostream> using namespace std; inline void use_io_optimizations() { ios_base::sync_with_stdio(false); cin.tie(nullptr); } int main() { use_io_optimizations(); unsigned int winner_number {0}; unsigned int winner_points {0}; for (unsigned int i {0}; i < 5; ++i) { unsigned int points {0}; for (unsigned int j {0}; j < 4; ++j) { unsigned int grade; cin >> grade; points += grade; } if (winner_points < points) { winner_number = i + 1; winner_points = points; } } cout << winner_number << ' ' << winner_points << '\n'; return 0; }
16.738095
58
0.517781
Rkhoiwal
71b40079abf37683b1db939e36f6493b8ea0ddbf
3,794
cpp
C++
dev/Gems/CryLegacy/Code/Source/CryAnimation/SkeletonAnim_Params.cpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Gems/CryLegacy/Code/Source/CryAnimation/SkeletonAnim_Params.cpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Gems/CryLegacy/Code/Source/CryAnimation/SkeletonAnim_Params.cpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #include "CryLegacy_precompiled.h" #include <IRenderAuxGeom.h> #include "CharacterInstance.h" #include <float.h> void CSkeletonAnim::SetDesiredMotionParam(EMotionParamID nParameterID, float fParameter, float deltaTime222) { if (nParameterID >= eMotionParamID_COUNT) { return; //not a valid parameter } //we store the parameters in the run-time structure of the ParametricSampler for (int layer = 0; layer < ISkeletonAnim::LayerCount; ++layer) { const int animCount = GetNumAnimsInFIFO(layer); for (int i = 0; i < animCount; i++) { CAnimation& anim = GetAnimFromFIFO(layer, i); if (anim.GetParametricSampler() == 0) { continue; } const uint32 blendingOut = (i < animCount - 1); //It's a Parametric Animation SParametricSampler& lmg = *anim.GetParametricSampler(); for (uint32 d = 0; d < lmg.m_numDimensions; d++) { if (lmg.m_MotionParameterID[d] == nParameterID) { const uint32 locked = (lmg.m_MotionParameterFlags[d] & CA_Dim_LockedParameter); const uint32 init = lmg.m_MotionParameterFlags[d] & CA_Dim_Initialized; if (init == 0 || (locked == 0 && blendingOut == 0)) //if already initialized and locked or blending out, then we can't change the parameter any more { lmg.m_MotionParameter[d] = fParameter; lmg.m_MotionParameterFlags[d] |= CA_Dim_Initialized; } } } } } } bool CSkeletonAnim::GetDesiredMotionParam(EMotionParamID id, float& value) const { for (int layer = 0; layer < ISkeletonAnim::LayerCount; ++layer) { uint samplerCount = GetNumAnimsInFIFO(layer); uint samplerMax = MAX_EXEC_QUEUE; if (samplerMax > samplerCount) { samplerMax = samplerCount; } if (samplerCount > samplerMax) { samplerCount = samplerMax; } uint samplerActiveCount = 0; for (uint i = 0; i < samplerCount; ++i) { const CAnimation& animation = GetAnimFromFIFO(layer, i); samplerActiveCount += animation.IsActivated() ? 1 : 0; } if (samplerActiveCount > samplerMax) { samplerActiveCount = samplerMax; } samplerMax = samplerActiveCount; for (int i = samplerMax - 1; i >= 0; --i) { const CAnimation& animation = GetAnimFromFIFO(layer, i); const SParametricSampler* pParametric = animation.GetParametricSampler(); if (!pParametric) { continue; } for (int motionParam = 0; motionParam < MAX_LMG_DIMENSIONS; ++motionParam) { if (pParametric->m_MotionParameterID[motionParam] == id) { value = pParametric->m_MotionParameter[motionParam]; return true; } } } } return false; }
35.12963
168
0.584344
jeikabu
71b6ff277b32eb4d95b5d037136b872971c94da6
270
cpp
C++
2. Search & Sort/07. Alternative Sorting (Easy).cpp
thekalyan001/DMB1-CP
7ccf41bac7269bff432260c6078cebdb4e0f1483
[ "Apache-2.0" ]
null
null
null
2. Search & Sort/07. Alternative Sorting (Easy).cpp
thekalyan001/DMB1-CP
7ccf41bac7269bff432260c6078cebdb4e0f1483
[ "Apache-2.0" ]
null
null
null
2. Search & Sort/07. Alternative Sorting (Easy).cpp
thekalyan001/DMB1-CP
7ccf41bac7269bff432260c6078cebdb4e0f1483
[ "Apache-2.0" ]
null
null
null
//https://practice.geeksforgeeks.org/problems/alternative-sorting1311/1/# vector<int> alternateSort(int arr[], int n) { sort(arr,arr+n);int p=0; vector<int>v(n); for(int i=0;i<=n/2;i++) { v[p++]=arr[n-i-1]; p+1<n?v[p++]=arr[i]:0; } return v; }
18
74
0.577778
thekalyan001
71bc9557cb256fe65b08a9dc3f39b0f98c39252d
1,638
cc
C++
project1/src/main_ref.cc
jiunbae/ITE4065
3b9fcf9317e93ca7c829f1438b85f0f5ea2885db
[ "MIT" ]
11
2017-10-28T08:41:08.000Z
2021-06-24T07:24:21.000Z
project1/src/main_ref.cc
jiunbae/ITE4065
3b9fcf9317e93ca7c829f1438b85f0f5ea2885db
[ "MIT" ]
null
null
null
project1/src/main_ref.cc
jiunbae/ITE4065
3b9fcf9317e93ca7c829f1438b85f0f5ea2885db
[ "MIT" ]
4
2017-09-07T09:33:26.000Z
2021-02-19T07:45:08.000Z
#include <iostream> #include <string> #include <set> #include <map> using namespace std; int main() { int N; set<string> word_list; char cmd; string buf; std::ios::sync_with_stdio(false); cin >> N; for (int i = 0; i < N; i++){ cin >> buf; word_list.insert(buf); } cout << "R" << std::endl; while(cin >> cmd){ cin.get(); getline(cin, buf); switch(cmd){ case 'Q': { multimap<size_t, string> result; for (set<string>::iterator it = word_list.begin(); it != word_list.end(); it++){ size_t pos = buf.find(*it); if (pos != string::npos){ result.insert(make_pair(pos, *it)); } } multimap<size_t, string>::iterator it = result.begin(); int cnt = result.size(); if (cnt) { for (; cnt != 0; cnt--, it++){ cout << it->second; if (cnt != 1){ cout << "|"; } } } else { cout << -1; } cout << std::endl; } break; case 'A': word_list.insert(buf); break; case 'D': word_list.erase(buf); break; } } return 0; }
26.419355
75
0.336386
jiunbae
71c1dc3f28f132d37fe2134d13e3edb3bcc2207c
340
cpp
C++
Homeworks/2_ImageWarping/project/src/App/Warp.cpp
Qinxin-Yan/USTC_CG-1
80dc240bea879f000196986b98efcd0bbf8dec34
[ "MIT" ]
null
null
null
Homeworks/2_ImageWarping/project/src/App/Warp.cpp
Qinxin-Yan/USTC_CG-1
80dc240bea879f000196986b98efcd0bbf8dec34
[ "MIT" ]
null
null
null
Homeworks/2_ImageWarping/project/src/App/Warp.cpp
Qinxin-Yan/USTC_CG-1
80dc240bea879f000196986b98efcd0bbf8dec34
[ "MIT" ]
null
null
null
#include "Warp.h" Warp::Warp() { } Warp::~Warp() { } /*void Warp::add_static_point(QPoint P) { static_point_list.push_back(P); }*/ void Warp::add_map_point(map_pair Pair) { map_pair_list.push_back(Pair); } int Warp::map_pair_length() { return map_pair_list.size(); } map_pair Warp::get_map_pair(int i) { return map_pair_list[i]; }
11.724138
39
0.7
Qinxin-Yan
71c399be913f9582063460f586691cee134df776
830
cpp
C++
Graph(BFS, DFS)/p1890.cpp
vocovoco/Algorithm-Study
ba9d47ae5c28eb5b7810ddef371859b0b101a695
[ "MIT" ]
1
2017-12-20T12:21:01.000Z
2017-12-20T12:21:01.000Z
Graph(BFS, DFS)/p1890.cpp
vocovoco/Algorithm-Study
ba9d47ae5c28eb5b7810ddef371859b0b101a695
[ "MIT" ]
null
null
null
Graph(BFS, DFS)/p1890.cpp
vocovoco/Algorithm-Study
ba9d47ae5c28eb5b7810ddef371859b0b101a695
[ "MIT" ]
null
null
null
#if 1 #include <stdio.h> int main() { int map[101][101] = { 0, }; long long dp[101][101] = { 0, }; int width; scanf("%d", &width); for (int i = 1; i <= width; i++) { for (int j = 1; j <= width; j++) { scanf("%d", &map[i][j]); } } for (int i = (width * 2 - 1); i > 1; i--) { int a, b; if (i > width) { a = width; b = i - width; } else { b = 1; a = i - b; } while (a > 0 && b < width + 1) { if (a + map[a][b] <= width) { if (a + map[a][b] == width && b == width) { dp[a][b]++; } else { dp[a][b] += dp[a + map[a][b]][b]; } } if (b + map[a][b] <= width) { if (b + map[a][b] == width && a == width) { dp[a][b]++; } else { dp[a][b] += dp[a][b + map[a][b]]; } } a--; b++; } } printf("%lld", dp[1][1]); return 0; } #endif
16.27451
47
0.375904
vocovoco
71c5c6e75d4d283387e8978cf8bd6449541fb6ac
6,267
cpp
C++
source/services/service_manager/service_manager.cpp
aejsmith/kiwi
756d5b85d7dff631ad54c942a9da137ea298794e
[ "0BSD" ]
15
2015-08-02T18:20:40.000Z
2022-03-22T13:36:44.000Z
source/services/service_manager/service_manager.cpp
aejsmith/kiwi
756d5b85d7dff631ad54c942a9da137ea298794e
[ "0BSD" ]
null
null
null
source/services/service_manager/service_manager.cpp
aejsmith/kiwi
756d5b85d7dff631ad54c942a9da137ea298794e
[ "0BSD" ]
3
2016-03-04T06:15:34.000Z
2020-12-12T03:01:42.000Z
/* * Copyright (C) 2009-2021 Alex Smith * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /** * @file * @brief Service manager. */ #include "client.h" #include "service_manager.h" #include "service.h" #include <core/log.h> #include <core/utility.h> #include <kernel/ipc.h> #include <kernel/process.h> #include <kernel/status.h> #include <assert.h> #include <inttypes.h> #include <stdlib.h> extern const char *const *environ; ServiceManager g_serviceManager; ServiceManager::ServiceManager() : m_port (INVALID_HANDLE) {} ServiceManager::~ServiceManager() { if (m_port != INVALID_HANDLE) kern_handle_close(m_port); } int ServiceManager::run() { status_t ret; /* Set default environment variables. TODO: Not appropriate for a per- * session service manager instance. */ setenv("PATH", "/system/bin", 1); setenv("HOME", "/users/admin", 1); core_log(CORE_LOG_NOTICE, "service manager started"); ret = kern_port_create(&m_port); if (ret != STATUS_SUCCESS) { core_log(CORE_LOG_ERROR, "failed to create port: %d", ret); return EXIT_FAILURE; } addEvent(m_port, PORT_EVENT_CONNECTION, this); /* TODO: Service configuration. */ addService("org.kiwi.test", "/system/services/test", Service::kIpc | Service::kOnDemand); addService("org.kiwi.terminal", "/system/services/terminal_service", Service::kIpc | Service::kOnDemand); spawnProcess("/system/bin/terminal"); while (true) { ret = kern_object_wait(m_events.data(), m_events.size(), 0, -1); if (ret != STATUS_SUCCESS) { core_log(CORE_LOG_WARN, "failed to wait for events: %d", ret); continue; } size_t numEvents = m_events.size(); for (size_t i = 0; i < numEvents; ) { object_event_t &event = m_events[i]; uint32_t flags = event.flags; event.flags &= ~(OBJECT_EVENT_SIGNALLED | OBJECT_EVENT_ERROR); if (flags & OBJECT_EVENT_ERROR) { core_log(CORE_LOG_WARN, "error flagged on event %u for handle %u", event.event, event.handle); } else if (flags & OBJECT_EVENT_SIGNALLED) { auto handler = reinterpret_cast<EventHandler *>(event.udata); handler->handleEvent(event); } /* Calling the handler may change the event array, so we have to * handle this - start from the beginning. */ if (numEvents != m_events.size()) { numEvents = m_events.size(); i = 0; } else { i++; } } } } void ServiceManager::addService(std::string name, std::string path, uint32_t flags) { auto service = std::make_unique<Service>(std::move(name), std::move(path), flags); if (!(flags & Service::kOnDemand)) service->start(); m_services.emplace(service->name(), std::move(service)); } Service* ServiceManager::findService(const std::string &name) { auto ret = m_services.find(name); if (ret != m_services.end()) { return ret->second.get(); } else { return nullptr; } } status_t ServiceManager::spawnProcess(const char *path, handle_t *_handle) const { process_attrib_t attrib; handle_t map[][2] = { { 0, 0 }, { 1, 1 }, { 2, 2 } }; attrib.token = INVALID_HANDLE; attrib.root_port = m_port; attrib.map = map; attrib.map_count = core_array_size(map); const char *args[] = { path, nullptr }; status_t ret = kern_process_create(path, args, environ, 0, &attrib, _handle); if (ret != STATUS_SUCCESS) { core_log(CORE_LOG_ERROR, "failed to create process '%s': %d", path, ret); return ret; } return ret; } void ServiceManager::handleEvent(const object_event_t &event) { status_t ret; assert(event.handle == m_port); assert(event.event == PORT_EVENT_CONNECTION); handle_t handle; ipc_client_t ipcClient; ret = kern_port_listen(m_port, &ipcClient, 0, &handle); if (ret != STATUS_SUCCESS) { /* This may be harmless - client's connection attempt could be cancelled * between us receiving the event and calling listen, for instance. */ core_log(CORE_LOG_WARN, "failed to listen on port after connection event: %d", ret); return; } core_connection_t *connection = core_connection_create(handle, CORE_CONNECTION_RECEIVE_REQUESTS); if (!connection) { core_log(CORE_LOG_WARN, "failed to create connection"); kern_handle_close(handle); return; } Client* client = new Client(connection, ipcClient.pid); /* See if this client matches one of our services. */ for (const auto &it : m_services) { Service *service = it.second.get(); if (service->processId() == ipcClient.pid) { service->setClient(client); client->setService(service); } } } void ServiceManager::addEvent(handle_t handle, unsigned id, EventHandler *handler) { object_event_t &event = m_events.emplace_back(); event.handle = handle; event.event = id; event.flags = 0; event.data = 0; event.udata = handler; } void ServiceManager::removeEvents(EventHandler *handler) { for (auto it = m_events.begin(); it != m_events.end(); ) { if (reinterpret_cast<EventHandler *>(it->udata) == handler) { it = m_events.erase(it); } else { ++it; } } } int main(int argc, char **argv) { return g_serviceManager.run(); }
30.871921
110
0.636828
aejsmith
71c67bb0c2829175fbe254522b45edc62e333f8b
1,289
cpp
C++
src/learn/test_libevent.cpp
wohaaitinciu/zpublic
0e4896b16e774d2f87e1fa80f1b9c5650b85c57e
[ "Unlicense" ]
50
2015-01-07T01:54:54.000Z
2021-01-15T00:41:48.000Z
src/learn/test_libevent.cpp
sinmx/ZPublic
0e4896b16e774d2f87e1fa80f1b9c5650b85c57e
[ "Unlicense" ]
1
2015-05-26T07:40:19.000Z
2015-05-26T07:40:19.000Z
src/learn/test_libevent.cpp
sinmx/ZPublic
0e4896b16e774d2f87e1fa80f1b9c5650b85c57e
[ "Unlicense" ]
39
2015-01-07T02:03:15.000Z
2021-01-15T00:41:50.000Z
#include "stdafx.h" #include "test_libevent.h" struct timeval lasttime; int times = 0; static void timeout_cb(evutil_socket_t fd, short e, void *arg) { struct timeval newtime, difference; struct event *timeout = (event *)arg; double elapsed; evutil_gettimeofday(&newtime, NULL); evutil_timersub(&newtime, &lasttime, &difference); elapsed = difference.tv_sec + (difference.tv_usec / 1.0e6); printf("timeout_cb called at %d: %.3f seconds elapsed.\n", (int)newtime.tv_sec, elapsed); lasttime = newtime; if (++times < 5) { struct timeval tv; evutil_timerclear(&tv); tv.tv_sec = 2; event_add(timeout, &tv); } } void test_libevent() { struct event timeout; struct timeval tv; struct event_base *base; WORD wVersionRequested; WSADATA wsaData; wVersionRequested = MAKEWORD(2, 2); (void)WSAStartup(wVersionRequested, &wsaData); /* Initalize the event library */ base = event_base_new(); /* Initalize one event */ event_assign((event *)&timeout, base, -1, 0, timeout_cb, (void*) &timeout); evutil_timerclear(&tv); tv.tv_sec = 2; event_add((event *)&timeout, &tv); evutil_gettimeofday(&lasttime, NULL); event_base_dispatch(base); }
23.017857
79
0.645462
wohaaitinciu
71c84e229d9425e488c02b0cfba33e7b477ceb70
311
cpp
C++
P1134.cpp
AndrewWayne/OI_Learning
0fe8580066704c8d120a131f6186fd7985924dd4
[ "MIT" ]
null
null
null
P1134.cpp
AndrewWayne/OI_Learning
0fe8580066704c8d120a131f6186fd7985924dd4
[ "MIT" ]
null
null
null
P1134.cpp
AndrewWayne/OI_Learning
0fe8580066704c8d120a131f6186fd7985924dd4
[ "MIT" ]
null
null
null
#include <cstdio> using namespace std; int n, ans = 1; int num[4] = {6, 8, 4, 2}; int main() { scanf("%d",&n); for(int p = n; p > 0; p /= 5, ans = ans * num[p%4] %10) for (int i = 1; i <= p%10; i++) if(i != 5) ans = ans * i %10; printf("%d",ans); return 0; }
22.214286
59
0.421222
AndrewWayne
71ca4743af830dbe7955834b0a2b1a9455f39066
474
cpp
C++
src/DS/queue_demo.cpp
rrkarim/Algorithms-data-structues
3e8f9bb06a0298bf19b76684d7e5e0b539cf56cd
[ "MIT" ]
1
2021-09-08T08:15:40.000Z
2021-09-08T08:15:40.000Z
src/DS/queue_demo.cpp
rrkarim/Algorithms-data-structues
3e8f9bb06a0298bf19b76684d7e5e0b539cf56cd
[ "MIT" ]
null
null
null
src/DS/queue_demo.cpp
rrkarim/Algorithms-data-structues
3e8f9bb06a0298bf19b76684d7e5e0b539cf56cd
[ "MIT" ]
null
null
null
/** Queue implementation Iterator pattern Rasul Kerimov (CoderINusE) */ #include <inc_libs.h> #include "queue.h" #include <time.h> using namespace alg; using namespace std; const int MAX_ELEMENTS = 10005; int main() { srand (time(NULL)); //init random Queue<int> q0, q1; for(int i = 0; i < 10; ++i) q0.pushBack(rand() % 30); // generate 10 random elements for(Queue<int>::Iterator it = q0.begin(); it != q0.end(); ++it) { cout << *it << endl; } return 0; }
18.230769
85
0.64135
rrkarim
71d49d9f87d112f4351228c743214ec2e77b8f6e
91
cpp
C++
src/params.cpp
DanielLenz/rFBP
fc8ae71a8ff58858f6800eeb3a3f25a56c143d18
[ "MIT" ]
7
2019-12-03T17:45:31.000Z
2021-04-21T15:46:41.000Z
src/params.cpp
DanielLenz/rFBP
fc8ae71a8ff58858f6800eeb3a3f25a56c143d18
[ "MIT" ]
6
2020-09-28T06:57:23.000Z
2020-10-22T05:41:12.000Z
src/params.cpp
DanielLenz/rFBP
fc8ae71a8ff58858f6800eeb3a3f25a56c143d18
[ "MIT" ]
1
2020-10-11T08:59:41.000Z
2020-10-11T08:59:41.000Z
#include <params.hpp> template class Params < MagP64 >; template class Params < MagT64 >;
18.2
33
0.725275
DanielLenz
71d568094ded48d09db22efc6ad39d1f040c6eeb
382
cpp
C++
test/Day1.cpp
schoradt/adventofcode-c
09b9b5fc22cadc938190f5d83a895b601896d663
[ "MIT" ]
null
null
null
test/Day1.cpp
schoradt/adventofcode-c
09b9b5fc22cadc938190f5d83a895b601896d663
[ "MIT" ]
null
null
null
test/Day1.cpp
schoradt/adventofcode-c
09b9b5fc22cadc938190f5d83a895b601896d663
[ "MIT" ]
null
null
null
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include "doctest.h" #include "Day1.h" TEST_CASE("Testing Day 1") { Day1 day1; vector<int> input = day1.parseIntegerLines(day1.loadLinesString("199\n200\n208\n210\n200\n207\n240\n269\n260\n263")); CHECK_MESSAGE(7 == day1.process1(input), "test process 1"); CHECK_MESSAGE(5 == day1.process2(input), "test process 2"); }
25.466667
121
0.717277
schoradt
71d6dd0a5a0bb3b6cb3fcc9f8f02e1d2a78fb94d
9,391
cpp
C++
src/shogun/mathematics/Random.cpp
cloner1984/shogun
901c04b2c6550918acf0594ef8afeb5dcd840a7d
[ "BSD-3-Clause" ]
2
2015-01-13T15:18:27.000Z
2015-05-01T13:28:48.000Z
src/shogun/mathematics/Random.cpp
cloner1984/shogun
901c04b2c6550918acf0594ef8afeb5dcd840a7d
[ "BSD-3-Clause" ]
null
null
null
src/shogun/mathematics/Random.cpp
cloner1984/shogun
901c04b2c6550918acf0594ef8afeb5dcd840a7d
[ "BSD-3-Clause" ]
null
null
null
/* * This software is distributed under BSD 3-clause license (see LICENSE file). * * Authors: Viktor Gal, Bjoern Esser, Thoralf Klein, Heiko Strathmann, * Soeren Sonnenburg */ #ifdef _WIN32 #define _CRT_RAND_S #include <stdlib.h> #endif #include <shogun/mathematics/Random.h> #include <shogun/base/Parameter.h> #include <shogun/lib/external/SFMT/SFMT.h> #include <shogun/lib/external/dSFMT/dSFMT.h> #include <shogun/lib/Time.h> #include <shogun/lib/Lock.h> #ifdef DEV_RANDOM #include <fcntl.h> #endif using namespace shogun; CRandom::CRandom() : m_sfmt_32(NULL), m_sfmt_64(NULL), m_dsfmt(NULL) { m_seed = CRandom::generate_seed(); init(); } CRandom::CRandom(uint32_t seed) : m_seed(seed), m_sfmt_32(NULL), m_sfmt_64(NULL), m_dsfmt(NULL) { init(); } CRandom::~CRandom() { SG_FREE(m_x); SG_FREE(m_y); SG_FREE(m_xComp); SG_FREE(m_sfmt_32); SG_FREE(m_sfmt_64); SG_FREE(m_dsfmt); } void CRandom::set_seed(uint32_t seed) { reinit(seed); } uint32_t CRandom::get_seed() const { return m_seed; } void CRandom::init() { /** init ziggurat variables */ m_blockCount = 128; m_R = 3.442619855899; m_A = 9.91256303526217e-3; m_uint32ToU = 1.0 / (float64_t)std::numeric_limits<uint32_t>::max(); m_x = SG_MALLOC(float64_t, m_blockCount + 1); m_y = SG_MALLOC(float64_t, m_blockCount); m_xComp = SG_MALLOC(uint32_t, m_blockCount); // Initialise rectangle position data. // m_x[i] and m_y[i] describe the top-right position ox Box i. // Determine top right position of the base rectangle/box (the rectangle with the Gaussian tale attached). // We call this Box 0 or B0 for short. // Note. x[0] also describes the right-hand edge of B1. (See diagram). m_x[0] = m_R; m_y[0] = GaussianPdfDenorm(m_R); // The next box (B1) has a right hand X edge the same as B0. // Note. B1's height is the box area divided by its width, hence B1 has a smaller height than B0 because // B0's total area includes the attached distribution tail. m_x[1] = m_R; m_y[1] = m_y[0] + (m_A / m_x[1]); // Calc positions of all remaining rectangles. for(int i=2; i < m_blockCount; i++) { m_x[i] = GaussianPdfDenormInv(m_y[i-1]); m_y[i] = m_y[i-1] + (m_A / m_x[i]); } // For completeness we define the right-hand edge of a notional box 6 as being zero (a box with no area). m_x[m_blockCount] = 0.0; // Useful precomputed values. m_A_div_y0 = m_A / m_y[0]; // Special case for base box. m_xComp[0] stores the area of B0 as a proportion of R // (recalling that all segments have area A, but that the base segment is the combination of B0 and the distribution tail). // Thus -m_xComp[0] is the probability that a sample point is within the box part of the segment. m_xComp[0] = (uint32_t)(((m_R * m_y[0]) / m_A) * (float64_t)std::numeric_limits<uint32_t>::max()); for(int32_t i=1; i < m_blockCount-1; i++) { m_xComp[i] = (uint32_t)((m_x[i+1] / m_x[i]) * (float64_t)std::numeric_limits<uint32_t>::max()); } m_xComp[m_blockCount-1] = 0; // Shown for completeness. // Sanity check. Test that the top edge of the topmost rectangle is at y=1.0. // Note. We expect there to be a tiny drift away from 1.0 due to the inexactness of floating // point arithmetic. ASSERT(CMath::abs(1.0 - m_y[m_blockCount-1]) < 1e-10); /** init SFMT and dSFMT */ m_sfmt_32 = SG_MALLOC(sfmt_t, 1); m_sfmt_64 = SG_MALLOC(sfmt_t, 1); m_dsfmt = SG_MALLOC(dsfmt_t, 1); reinit(m_seed); } uint32_t CRandom::random_32() const { m_state_lock.lock(); uint32_t v = sfmt_genrand_uint32(m_sfmt_32); m_state_lock.unlock(); return v; } uint64_t CRandom::random_64() const { m_state_lock.lock(); uint64_t v = sfmt_genrand_uint64(m_sfmt_64); m_state_lock.unlock(); return v; } void CRandom::fill_array(uint32_t* array, int32_t size) const { #if defined(USE_ALIGNED_MEMORY) || defined(DARWIN) if ((size >= sfmt_get_min_array_size32(m_sfmt_32)) && (size % 4) == 0) { m_state_lock.lock(); sfmt_fill_array32(m_sfmt_32, array, size); m_state_lock.unlock(); return; } #endif for (int32_t i=0; i < size; i++) array[i] = random_32(); } void CRandom::fill_array(uint64_t* array, int32_t size) const { #if defined(USE_ALIGNED_MEMORY) || defined(DARWIN) if ((size >= sfmt_get_min_array_size64(m_sfmt_64)) && (size % 2) == 0) { m_state_lock.lock(); sfmt_fill_array64(m_sfmt_64, array, size); m_state_lock.unlock(); return; } #endif for (int32_t i=0; i < size; i++) array[i] = random_64(); } void CRandom::fill_array_oc(float64_t* array, int32_t size) const { m_state_lock.lock(); #if defined(USE_ALIGNED_MEMORY) || defined(DARWIN) if ((size >= dsfmt_get_min_array_size()) && (size % 2) == 0) { dsfmt_fill_array_open_close(m_dsfmt, array, size); m_state_lock.unlock(); return; } #endif for (int32_t i=0; i < size; i++) array[i] = dsfmt_genrand_open_close(m_dsfmt); m_state_lock.unlock(); } void CRandom::fill_array_co(float64_t* array, int32_t size) const { m_state_lock.lock(); #if defined(USE_ALIGNED_MEMORY) || defined(DARWIN) if ((size >= dsfmt_get_min_array_size()) && (size % 2) == 0) { dsfmt_fill_array_close_open(m_dsfmt, array, size); m_state_lock.unlock(); return; } #endif for (int32_t i=0; i < size; i++) array[i] = dsfmt_genrand_close_open(m_dsfmt); m_state_lock.unlock(); } void CRandom::fill_array_oo(float64_t* array, int32_t size) const { m_state_lock.lock(); #if defined(USE_ALIGNED_MEMORY) || defined(DARWIN) if ((size >= dsfmt_get_min_array_size()) && (size % 2) == 0) { dsfmt_fill_array_open_open(m_dsfmt, array, size); m_state_lock.unlock(); return; } #endif for (int32_t i=0; i < size; i++) array[i] = dsfmt_genrand_open_open(m_dsfmt); m_state_lock.unlock(); } void CRandom::fill_array_c1o2(float64_t* array, int32_t size) const { m_state_lock.lock(); #if defined(USE_ALIGNED_MEMORY) || defined(DARWIN) if ((size >= dsfmt_get_min_array_size()) && (size % 2) == 0) { dsfmt_fill_array_close1_open2(m_dsfmt, array, size); m_state_lock.unlock(); return; } #endif for (int32_t i=0; i < size; i++) array[i] = dsfmt_genrand_close1_open2(m_dsfmt); m_state_lock.unlock(); } float64_t CRandom::random_close() const { m_state_lock.lock(); float64_t v = sfmt_genrand_real1(m_sfmt_32); m_state_lock.unlock(); return v; } float64_t CRandom::random_open() const { m_state_lock.lock(); float64_t v = dsfmt_genrand_open_open(m_dsfmt); m_state_lock.unlock(); return v; } float64_t CRandom::random_half_open() const { m_state_lock.lock(); float64_t v = dsfmt_genrand_close_open(m_dsfmt); m_state_lock.unlock(); return v; } float64_t CRandom::normal_distrib(float64_t mu, float64_t sigma) const { return mu + (std_normal_distrib() * sigma); } float64_t CRandom::std_normal_distrib() const { for (;;) { // Select box at random. uint8_t u = random_32(); int32_t i = (int32_t)(u & 0x7F); float64_t sign = ((u & 0x80) == 0) ? -1.0 : 1.0; // Generate uniform random value with range [0,0xffffffff]. uint32_t u2 = random_32(); // Special case for the base segment. if(0 == i) { if(u2 < m_xComp[0]) { // Generated x is within R0. return u2 * m_uint32ToU * m_A_div_y0 * sign; } // Generated x is in the tail of the distribution. return sample_tail() * sign; } // All other segments. if(u2 < m_xComp[i]) { // Generated x is within the rectangle. return u2 * m_uint32ToU * m_x[i] * sign; } // Generated x is outside of the rectangle. // Generate a random y coordinate and test if our (x,y) is within the distribution curve. // This execution path is relatively slow/expensive (makes a call to Math.Exp()) but relatively rarely executed, // although more often than the 'tail' path (above). float64_t x = u2 * m_uint32ToU * m_x[i]; if(m_y[i-1] + ((m_y[i] - m_y[i-1]) * random_half_open()) < GaussianPdfDenorm(x) ) { return x * sign; } } } float64_t CRandom::sample_tail() const { float64_t x, y; float64_t m_R_reciprocal = 1.0 / m_R; do { x = -std::log(random_half_open()) * m_R_reciprocal; y = -std::log(random_half_open()); } while(y+y < x*x); return m_R + x; } float64_t CRandom::GaussianPdfDenorm(float64_t x) const { return std::exp(-(x * x * 0.5)); } float64_t CRandom::GaussianPdfDenormInv(float64_t y) const { // Operates over the y range (0,1], which happens to be the y range of the pdf, // with the exception that it does not include y=0, but we would never call with // y=0 so it doesn't matter. Remember that a Gaussian effectively has a tail going // off into x == infinity, hence asking what is x when y=0 is an invalid question // in the context of this class. return std::sqrt(-2.0 * std::log(y)); } void CRandom::reinit(uint32_t seed) { m_state_lock.lock(); m_seed = seed; sfmt_init_gen_rand(m_sfmt_32, m_seed); sfmt_init_gen_rand(m_sfmt_64, m_seed); dsfmt_init_gen_rand(m_dsfmt, m_seed); m_state_lock.unlock(); } uint32_t CRandom::generate_seed() { uint32_t seed; #if defined(_WIN32) rand_s(&seed); #elif defined(HAVE_ARC4RANDOM) seed = arc4random(); #elif defined(DEV_RANDOM) int fd = open(DEV_RANDOM, O_RDONLY); ASSERT(fd >= 0); ssize_t actual_read = read(fd, reinterpret_cast<char*>(&seed), sizeof(seed)); close(fd); ASSERT(actual_read == sizeof(seed)); #else SG_SWARNING("Not safe seed for the PRNG\n"); struct timeval tv; gettimeofday(&tv, NULL); seed=(uint32_t) (4223517*getpid()*tv.tv_sec*tv.tv_usec); #endif return seed; }
25.728767
124
0.695134
cloner1984
71d7b3bb107ddf1c9f98fcdb0f91391e945d30b0
8,659
cpp
C++
DlgVolumeCalc.cpp
RDamman/SpeakerWorkshop
87a38d04197a07a9a7878b3f60d5e0706782163c
[ "OML" ]
12
2019-06-07T10:06:41.000Z
2021-03-22T22:13:59.000Z
DlgVolumeCalc.cpp
RDamman/SpeakerWorkshop
87a38d04197a07a9a7878b3f60d5e0706782163c
[ "OML" ]
1
2019-05-09T07:38:12.000Z
2019-07-10T04:20:55.000Z
DlgVolumeCalc.cpp
RDamman/SpeakerWorkshop
87a38d04197a07a9a7878b3f60d5e0706782163c
[ "OML" ]
3
2020-09-08T08:27:33.000Z
2021-05-13T09:25:43.000Z
// DlgVolumeCalc.cpp : implementation file // #include "stdafx.h" #include "audtest.h" #include "DlgVolumeCalc.h" #include "Utils.h" #include "Math.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- typedef struct tagCALCVOLUME { float fVolume; float fDepth; float fHeight; float fWidth; float fRatio; } VOLUMECALC; // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- bool CDlgVolumeCalc::m_bIsShowing = false; // is it showing???? static WINDOWPLACEMENT g_wpWindowPlace = {0,0}; ///////////////////////////////////////////////////////////////////////////// // CDlgVolumeCalc dialog ///////////////////////////////////////////////////////////////////////////// // ------------------------------------------------------------------------- // CDlgVolumeCalc // ------------------------------------------------------------------------- CDlgVolumeCalc::CDlgVolumeCalc(CWnd* pParent /*=NULL*/) : CDialog(CDlgVolumeCalc::IDD, pParent), m_cfEdits() { //{{AFX_DATA_INIT(CDlgVolumeCalc) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT m_bIsShowing = true; // we have it now } // ------------------------------------------------------------------------- // DoDataExchange // ------------------------------------------------------------------------- void CDlgVolumeCalc::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); m_cfEdits.DDX_All( pDX); //{{AFX_DATA_MAP(CDlgVolumeCalc) DDX_Control(pDX, IDC_STDWIDTH, m_czStdWidth); DDX_Control(pDX, IDC_STDVOLUME, m_czStdVolume); DDX_Control(pDX, IDC_STDHEIGHT, m_czStdHeight); DDX_Control(pDX, IDC_STDDEPTH, m_czStdDepth); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CDlgVolumeCalc, CDialog) //{{AFX_MSG_MAP(CDlgVolumeCalc) ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN1, OnDeltaposSpin) ON_EN_CHANGE(IDC_WIDTH, OnChangeWidth) ON_EN_CHANGE(IDC_VOLUME, OnChangeVolume) ON_EN_CHANGE(IDC_DEPTH, OnChangeDepth) ON_EN_CHANGE(IDC_HEIGHT, OnChangeHeight) ON_WM_CLOSE() ON_WM_LBUTTONUP() ON_WM_RBUTTONUP() ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN2, OnDeltaposSpin) ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN3, OnDeltaposSpin) ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN4, OnDeltaposSpin) ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN5, OnDeltaposSpin) ON_BN_CLICKED(IDC_USERATIO, OnUseratio) //}}AFX_MSG_MAP END_MESSAGE_MAP() // ------------------------------------------------------------------------- // recalc_Values // ------------------------------------------------------------------------- void CDlgVolumeCalc::recalc_Values(bool bCalcVolume) { if ( m_fVolume < .000001f) m_fVolume = .000001f; if ( bCalcVolume) { m_fVolume = .000001f * m_fDepth * m_fHeight * m_fWidth; } else { float fold = .000001f * m_fDepth * m_fHeight * m_fWidth; float fratio = m_fVolume / fold; fratio = (float )exp( log( fratio) / 3); m_fHeight *= fratio; m_fWidth *=fratio; m_fDepth = m_fVolume / ( .000001f * m_fHeight * m_fWidth); // to be exact } UpdateData( FALSE); } ///////////////////////////////////////////////////////////////////////////// // CDlgVolumeCalc message handlers ///////////////////////////////////////////////////////////////////////////// // ------------------------------------------------------------------------- // OnInitDialog // ------------------------------------------------------------------------- BOOL CDlgVolumeCalc::OnInitDialog() { { // initialize the spinner format group FormatGroup cfdata[6] = { {IDC_VOLUME, IDC_SPIN4, 0.0f, 19900000.0f, &m_fVolume}, {IDC_HEIGHT, IDC_SPIN1, 0.0f, 19900000.0f, &m_fHeight}, {IDC_WIDTH, IDC_SPIN2, 0.0f, 19900000.0f, &m_fWidth}, {IDC_DEPTH, IDC_SPIN3, 0.0f, 19900000.0f, &m_fDepth}, {IDC_RATIO, IDC_SPIN5, 0.0f, 19900000.0f, &m_fRatio}, {0,0,0.0f,0.0f,NULL} }; m_cfEdits.AttachGroup( this, cfdata); GroupMetric cfgrp[5] = { { IDC_VOLUME, IDC_STDVOLUME, mtCuMeter }, { IDC_HEIGHT, IDC_STDHEIGHT, mtCm }, { IDC_WIDTH, IDC_STDWIDTH, mtCm }, { IDC_DEPTH, IDC_STDDEPTH, mtCm }, { 0, 0, mtNone } }; m_cfEdits.AttachMetrics( cfgrp); } CDialog::OnInitDialog(); { VOLUMECALC clc; CAudtestApp *capp = (CAudtestApp *)AfxGetApp(); if ( ! capp->ReadRegistry( IDS_VOLCALCINFO, &clc, sizeof(clc))) { m_fVolume = clc.fVolume; m_fHeight = clc.fHeight; m_fWidth = clc.fWidth; m_fDepth = clc.fDepth; m_fRatio = clc.fRatio; } else { m_fVolume = 1.0f; m_fHeight = 1.0f; m_fWidth = 1.0f; m_fDepth = 1.0f; m_fRatio = 1.0f; } } recalc_Values( true); UpdateData( FALSE); if ( g_wpWindowPlace.length == sizeof( g_wpWindowPlace)) // it's not empty, set back there SetWindowPlacement( &g_wpWindowPlace); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } // ------------------------------------------------------------------------- // OnDeltaposSpin // ------------------------------------------------------------------------- void CDlgVolumeCalc::OnDeltaposSpin(NMHDR* pNMHDR, LRESULT* pResult) { m_cfEdits.ProcessAllDelta( pNMHDR); *pResult = 0; } // ----------------------------------------------------------------------------------------- // OnChangeVolume,... // ----------------------------------------------------------------------------------------- void CDlgVolumeCalc::OnChangeVolume() { if ( GetDlgItem( IDC_VOLUME) == GetFocus()) { if ( VerboseUpdateData( TRUE)) recalc_Values( false); } } void CDlgVolumeCalc::OnChangeWidth() { if ( GetDlgItem( IDC_WIDTH) == GetFocus()) { if ( VerboseUpdateData( TRUE)) recalc_Values( true); } } void CDlgVolumeCalc::OnChangeDepth() { if ( GetDlgItem( IDC_DEPTH) == GetFocus()) { if ( VerboseUpdateData( TRUE)) recalc_Values( true); } } void CDlgVolumeCalc::OnChangeHeight() { if ( GetDlgItem( IDC_HEIGHT) == GetFocus()) { if ( VerboseUpdateData( TRUE)) recalc_Values( true); } } // ----------------------------------------------------------------------------------------- // OnClose // ----------------------------------------------------------------------------------------- void CDlgVolumeCalc::OnClose() { if (! VerboseUpdateData( TRUE)) return; { VOLUMECALC clc; CAudtestApp *capp = (CAudtestApp *)AfxGetApp(); clc.fVolume = m_fVolume; clc.fHeight = m_fHeight; clc.fWidth = m_fWidth; clc.fDepth = m_fDepth; clc.fRatio = m_fRatio; capp->WriteRegistry( IDS_VOLCALCINFO, &clc, sizeof(clc)); } g_wpWindowPlace.length = sizeof( g_wpWindowPlace); GetWindowPlacement( & g_wpWindowPlace); CDialog::OnClose(); DestroyWindow(); } // ----------------------------------------------------------------------------------------- // PostNcDestroy // ----------------------------------------------------------------------------------------- void CDlgVolumeCalc::PostNcDestroy() { CDialog::PostNcDestroy(); m_bIsShowing = false; delete this; // per microsoft, kill us here } // ----------------------------------------------------------------------------------------- // OnLButtonUp // ----------------------------------------------------------------------------------------- void CDlgVolumeCalc::OnLButtonUp(UINT nFlags, CPoint point) { if ( ! m_cfEdits.ProcessLeftClick( nFlags, point)) CDialog::OnLButtonUp(nFlags, point); } // ----------------------------------------------------------------------------------------- // OnRButtonUp // ----------------------------------------------------------------------------------------- void CDlgVolumeCalc::OnRButtonUp(UINT nFlags, CPoint point) { if ( ! m_cfEdits.ProcessRightClick( nFlags, point)) CDialog::OnRButtonUp(nFlags, point); } // ----------------------------------------------------------------------------------------- // OnUseRatio // ----------------------------------------------------------------------------------------- void CDlgVolumeCalc::OnUseratio() { float ftotal, fratio; if ( VerboseUpdateData( TRUE)) { m_fHeight = 1.0f; m_fWidth = m_fRatio; m_fDepth = m_fRatio * m_fRatio; ftotal = .000001f * m_fDepth * m_fHeight * m_fWidth; fratio = m_fVolume / ftotal; fratio = (float )exp( log( fratio) / 3); // cube root it m_fHeight *= fratio; m_fWidth *= fratio; m_fDepth *= fratio; recalc_Values( true); } }
26.975078
92
0.494861
RDamman
71d84de8bc7087a21e5a617b0828c7683b10eb62
2,649
cpp
C++
Visualizer/Visualizer.cpp
VendorSniper/reg
825dd4c638ca9be58abd6fcf62989a9c1899b61a
[ "MIT" ]
null
null
null
Visualizer/Visualizer.cpp
VendorSniper/reg
825dd4c638ca9be58abd6fcf62989a9c1899b61a
[ "MIT" ]
null
null
null
Visualizer/Visualizer.cpp
VendorSniper/reg
825dd4c638ca9be58abd6fcf62989a9c1899b61a
[ "MIT" ]
null
null
null
#include "Visualizer.h" reg::Visualizer::Visualizer(vtkImageData *image) { Initialize(image); Execute(image); } void reg::Visualizer::Execute(vtkImageData *image) { Wrapper<vtkRenderWindow>::Get()->AddRenderer(Wrapper<vtkRenderer>::Get()); Wrapper<vtkRenderWindowInteractor>::Get()->SetRenderWindow( Wrapper<vtkRenderWindow>::Get()); Wrapper<vtkRenderWindow>::Get()->Render(); Wrapper<vtkImageShiftScale>::Get()->SetInputData( Wrapper<vtkImageData>::Get()); Wrapper<vtkImageShiftScale>::Get()->SetScale( 5); ///< increase brightness by a factor of 5 Wrapper<vtkImageShiftScale>::Get()->Update(); Wrapper<vtkImageThreshold>::Get()->SetInputData( Wrapper<vtkImageShiftScale>::Get()->GetOutput()); Wrapper<vtkImageThreshold>::Get()->ThresholdBetween( 110, std::numeric_limits<double>::max()); ///< inclusive range of grey values Wrapper<vtkImageThreshold>::Get() ->ReplaceOutOn(); ///< specify replace values not in inclusive range Wrapper<vtkImageThreshold>::Get()->SetOutValue( 0); ///< set non-included values to 0 Wrapper<vtkImageThreshold>::Get()->Update(); Wrapper<vtkSmartVolumeMapper>::Get()->SetBlendModeToComposite(); // Wrapper<vtkSmartVolumeMapper>::Get()->SetInputData(Wrapper<vtkImageThreshold>::Get()->GetOutput()); Wrapper<vtkSmartVolumeMapper>::Get()->SetInputData( Wrapper<vtkImageData>::Get()); Wrapper<vtkVolumeProperty>::Get()->SetScalarOpacity( CompositeOpacity::Get()); ///< explicitly specify no opacity std::cout << *Wrapper<vtkVolumeProperty>::Get()->GetScalarOpacity() << std::endl; Wrapper<vtkVolumeProperty>::Get()->ShadeOff(); Wrapper<vtkVolumeProperty>::Get()->SetInterpolationType( VTK_LINEAR_INTERPOLATION); Wrapper<vtkVolume>::Get()->SetMapper(Wrapper<vtkSmartVolumeMapper>::Get()); Wrapper<vtkVolume>::Get()->SetProperty(Wrapper<vtkVolumeProperty>::Get()); Wrapper<vtkRenderer>::Get()->AddViewProp(Wrapper<vtkVolume>::Get()); Wrapper<vtkRenderer>::Get()->ResetCamera(); Wrapper<vtkRenderWindow>::Get()->Render(); Wrapper<vtkRenderWindowInteractor>::Get()->Start(); } void reg::Visualizer::Initialize(vtkImageData *image) { Wrapper<vtkImageData>::Set(image); Wrapper<vtkRenderer>::Allocate(); Wrapper<vtkRenderWindow>::Allocate(); Wrapper<vtkRenderWindowInteractor>::Allocate(); Wrapper<vtkSmartVolumeMapper>::Allocate(); Wrapper<vtkVolume>::Allocate(); Wrapper<vtkVolumeProperty>::Allocate(); CompositeOpacity::Allocate(); Wrapper<vtkImageShiftScale>::Allocate(); Wrapper<vtkImageThreshold>::Allocate(); }
44.898305
105
0.702529
VendorSniper
71d885eb80a49039d76e763b48f31c8a840120a0
40,544
cpp
C++
sbg/src/libpdb/Atomo.cpp
chaconlab/korpm
5a73b5ab385150b580b2fd3f1b2ad26fa3d55cf3
[ "MIT" ]
1
2022-01-02T01:48:05.000Z
2022-01-02T01:48:05.000Z
sbg/src/libpdb/Atomo.cpp
chaconlab/korpm
5a73b5ab385150b580b2fd3f1b2ad26fa3d55cf3
[ "MIT" ]
1
2021-11-10T10:50:08.000Z
2021-11-10T10:50:08.000Z
sbg/src/libpdb/Atomo.cpp
chaconlab/korpm
5a73b5ab385150b580b2fd3f1b2ad26fa3d55cf3
[ "MIT" ]
1
2021-12-03T03:29:39.000Z
2021-12-03T03:29:39.000Z
/*Implementation of the different methods of the Atom Class*/ #include <stdio.h> #include "Atomo.h" using namespace std; /*Table with the principal elements*/ Element Table_Elements::table_Elements[NUM_ELEMENTS]= { // Symbol Symbol group period number weight atomic cov vdw en Element((char*)"Carbon", C , "C ", 14, 2, 6.0, 12.011, 0.77, 0.77, 1.85, 2.55), // 0 Element((char*)"Hydrogen", H, "H ", 1, 1, 1.0, 1.00797, 0.78, 0.3, 1.2, 2.2), // 1 Element((char*)"Nitrogen", N, "N ", 15, 2, 7.0, 14.00674, 0.71, 0.7, 1.54, 3.04), // 2 Element((char*)"Oxygen", O, "O ", 16, 2, 8.0, 15.9994, 0.6, 0.66, 1.4, 3.44), // 3 Element((char*)"Phosphorus",P, "P ", 15, 3, 15.0, 30.973762, 1.15, 1.10, 1.9, 2.19), // 4 Element((char*)"Sulphur", S, "S ", 16, 3, 16.0, 32.066, 1.04, 1.04, 1.85, 2.58), // 5 Element((char*)"Calcium", CA, "CA", 2, 4, 20.0, 40.078, 1.97, 1.74, 1.367, 1.0), // 6 Mon: vdw radius taken from Rosetta Element((char*)"Iron", FE, "FE", 8, 4, 26.0, 55.845, 1.24, 1.16, 0.650, 1.83),// 7 Mon: vdw radius taken from Rosetta Element((char*)"Magnesium", MG, "MG", 2, 3, 12.0, 24.30506, 1.6, 1.36, 1.185, 1.31), // 8 Mon: vdw radius taken from Rosetta Element((char*)"Manganese", MN, "MN", 7, 4, 25.0, 54.93805, 1.24, 1.77, 1.0, 1.55), // 9 Mon: vdw radius manually set to 100pm Element((char*)"Sodium", NA, "NA", 1, 3, 11.0, 22.989768, 1.54, 0.0, 1.364, 0.93), // 10 Mon: 2.31A is a huge vdw radius for an ion... Element((char*)"Zinc", ZN, "ZN", 12, 4, 30.0, 65.39, 1.33, 1.25, 1.090, 1.65),// 11 Mon: vdw radius taken from Rosetta Element((char*)"Nickel", NI, "NI", 10, 4, 28.0, 58.6934, 1.25, 1.15, 0.0, 1.91), // 12 Element((char*)"Copper", CU, "CU", 11, 4, 29.0, 63.546, 1.28, 1.17, 0.70, 1.9), // 13 Mon: vdw radius manually set to 70pm Element((char*)"Potassium", K, "K ", 1, 4, 19.0, 39.0983, 2.27, 2.03, 1.764, 0.82), // 14 Mon: 2.31A is a huge vdw radius for an ion... Element((char*)"Cobalt", CO, "CO", 9, 4, 27.0, 58.9332, 1.25, 1.16, 0.8 , 1.88), // 15 Mon: vdw radius manually set to 80pm Element((char*)"Aluminum", AL, "AL", 13, 3, 13.0, 26.981539, 1.43, 1.25, 2.05, 1.61), // 16 Element((char*)"Bromine", BR, "BR", 17, 4, 35.0, 79.904, 0.0, 1.14, 1.95, 2.96), // 17 Element((char*)"Chlorine", CL, "CL", 17, 3, 17.0, 35.4527, 0.0, 0.99, 1.81, 3.16), // 18 Element((char*)"Chromium", CR, "CR", 6, 4, 24.0, 51.9961, 1.25, 0.0, 0.0, 1.66), // 19 Element((char*)"Silicon", SI, "SI", 14, 3, 14.0, 28.0855, 1.17, 1.17, 2.0, 1.9), // 20 Element((char*)"Cadmium", CD, "CD", 12, 5, 48.0, 112.411, 1.49, 1.41, 0.0, 1.69), // 21 Element((char*)"Gold", AU, "AU", 11, 6, 79.0, 196.96654, 1.44, 1.34, 0.0, 2.0), // 22 Element((char*)"Silver", AG, "AG", 11, 5, 47.0, 107.8682, 1.44, 1.34, 0.0, 1.93), // 23 Element((char*)"Platinum", PT, "PT", 10, 6, 78.0, 195.08, 1.38, 1.29, 0.0, 2.54), // 24 Element((char*)"Mercury", HG, "HG", 12, 6, 80.0, 200.59, 1.60, 1.44, 0.0, 1.8), // 25 Element((char*)"Iodine", I, "I ", 17, 5, 53.0, 126.904, 1.40, 1.39, 1.98, 2.96), // 26 Element((char*)"Fluorine", F, "F ", 17, 2, 9.0, 18.998, 0.42, 0.71, 1.47, 3.98), // 27 Element((char*)"Deuterium", D, "D ", 1, 1, 1.0, 2.01410, 0.78, 0.3, 1.2, 2.2) // 28 }; // PyRosetta's metallic ions with available .parms file: (must have vdw radius, otherwise they do not generate a density map, e.g. in rcd) // PyRosetta.namespace.ubuntu.release-72/database/chemical/residue_type_sets/fa_standard/residue_types/metal_ions //residue_types/metal_ions/CA.params //residue_types/metal_ions/CO.params //residue_types/metal_ions/CU.params //residue_types/metal_ions/FE.params //residue_types/metal_ions/FE2.params //residue_types/metal_ions/K.params //residue_types/metal_ions/MG.params //residue_types/metal_ions/MN.params //residue_types/metal_ions/NA.params //residue_types/metal_ions/ZN.params Atom_type *atom_types; int num_atom_type; Atom_type atom_types_Rosseta[54]= { // at name hybridation polar chrge vdw soft deep acept donor Avol Asolpar {0 , "CNH2", SP2_HYBRID, APOLAR, 0.550, 2.0000, 2.0000, 0.1200, false, false, 0.01918, -0.0010}, // 1 CNH2 // carbonyl C in Asn and Gln and guanidyl C in Arg {0 , "COO ", SP2_HYBRID, APOLAR, 0.620, 2.0000, 2.0000, 0.1200, false, false, 0.01918, -0.0010}, // 2 COO // carboxyl C in Asp and Glu {0 , "CH1 ", SP3_HYBRID, APOLAR, -0.090, 2.0000, 2.1400, 0.0486, false, false, 0.01918, -0.0010}, // 3 CH1 // aliphatic C with one H (Val, Ile, Thr) {0 , "CH2 ", SP3_HYBRID, APOLAR, -0.180, 2.0000, 2.1400, 0.1142, false, false, 0.01918, -0.0010}, // 4 CH2 // aliphatic C with two H (other residues) {0 , "CH3 ", SP3_HYBRID, APOLAR, -0.270, 2.0000, 2.1400, 0.1811, false, false, 0.01918, -0.0010}, // 5 CH3 // aliphatic C with three H (Ala) {0 , "aroC", SP2_HYBRID, APOLAR, -0.115, 2.0000, 2.1400, 0.1200, false, false, 0.1108, -0.0005}, // 6 aroC // aromatic ring C (His, Phe, Tyr, Trp) {2 , "Ntrp", SP2_HYBRID, POLAR, -0.610, 1.7500, 1.7500, 0.2384, false, true, -0.03910, -0.0016}, // 7 Ntrp // N in Trp side-chain {2 , "Nhis", RING_HYBRID,POLAR, -0.530, 1.7500, 1.7500, 0.2384, true, false, -0.03910, -0.0016}, // 8 Nhis // N in His side-chain {2 , "NH2O", SP2_HYBRID, POLAR, -0.470, 1.7500, 1.7500, 0.2384, false, true, -0.03910, -0.0016}, // 9 NH2O // N in Asn and Gln side-chain {2 , "Nlys", SP3_HYBRID, POLAR, -0.620, 1.7500, 1.7500, 0.2384, false, true, -0.12604, -0.0016}, // 10 NLYS // N in Lys side-chain, N-terminus? {2 , "Narg", SP2_HYBRID, POLAR, -0.750, 1.7500, 1.7500, 0.2384, false, true, -0.06256, -0.0016}, // 11 Narg // N in Arg side-chain **** -7.0, 07/08/01 ... too many buried Arg {2 , "Npro", SP2_HYBRID, APOLAR, -0.370, 1.7500, 1.8725, 0.2384, false, true, -0.03910, -0.0016}, // 12 Npro // N in Pro backbone {3 , "OH ", SP3_HYBRID, POLAR, -0.660, 1.5500, 1.6585, 0.1591, true, true, -0.04255, -0.0025}, // 13 OH // hydroxyl O in Ser, Thr and Tyr {3 , "ONH2", SP2_HYBRID, POLAR, -0.550, 1.5500, 1.5500, 0.1591, true, false, -0.03128, -0.0025}, // 14 ONH2 // carbonyl O in Asn and Gln **** -5.85, 07/08/01 ... too many buried Asn,Arg {3 , "OOC ", SP2_HYBRID, POLAR, -0.760, 1.5500, 1.5500, 0.2100, true, false, -0.06877, -0.0025}, // 15 OOC // carboyxl O in Asp and Glu {5 , "S ", SP3_HYBRID, POLAR, -0.160, 1.9000, 2.0330, 0.1600, false, false, 0.02576, -0.0021}, // 16 S // sulfur in Cys and Met {2 , "Nbb ", SP2_HYBRID, POLAR, -0.470, 1.7500, 1.8725, 0.2384, false, true, -0.03910, -0.0016}, // 17 Nbb // backbone N' {0 , "CAbb", SP3_HYBRID, APOLAR, 0.070, 2.0000, 2.1400, 0.0486, false, false, 0.01918, -0.0010}, // 18 CAbb // backbone CA {0 , "CObb", SP2_HYBRID, APOLAR, 0.510, 2.0000, 2.1400, 0.1400, false, false, 0.01918, -0.0010}, // 19 CObb // backbone C' {0 , "OCbb", SP2_HYBRID, POLAR, -0.510, 1.5500, 1.6585, 0.1591, true, false, -0.03128, -0.0025}, // 20 OCbb // backbone O' {4 , "Phos", SP3_HYBRID, APOLAR, -0.160, 1.9000, 2.0330, 0.3182, false, false, 0.000, -0.0011}, // 21 Phos // nucleic acid P (from S) {1 , "Hpol", H_HYBRID, APOLAR, 0.430, 1.0000, 1.0700, 0.0500, false, false, 0.000, 0.0005}, // 22 Hpol // polar H {1 , "Hapo", H_HYBRID, APOLAR, 0.095, 1.2000, 1.2840, 0.0500, false, false, 0.000, 0.0005}, // 23 Hapo // nonpolar H {1 , "Haro", H_HYBRID, APOLAR, 0.115, 1.2000, 1.2840, 0.0500, false, false, 0.000, 0.0005}, // 24 Haro // aromatic H {1 , "HNbb", H_HYBRID, APOLAR, 0.310, 1.0000, 1.0700, 0.0500, false, false, 0.000, 0.0005}, // 25 HNbb // backbone HN {3 , "HOH ", SP3_HYBRID, POLAR, 0.000, 1.4000, 1.4000, 0.0500, true, true, 0.000, 0.0005}, // 26 H2O // H2O {99, "F ", SP3_HYBRID, APOLAR, -0.250, 1.7100, 1.7100, 0.0750, false, false, 0.000, -0.0011}, // 27 F // F wild guess {18, "Cl ", SP3_HYBRID, APOLAR, -0.130, 2.0700, 2.0700, 0.2400, false, false, 0.000, -0.0011}, // 28 Cl // Cl wild guess {17, "Br ", SP3_HYBRID, APOLAR, -0.100, 2.2200, 2.2200, 0.3200, false, false, 0.000, -0.0011}, // 29 Br // Br wild guess {99, "I ", SP3_HYBRID, APOLAR, -0.090, 2.3600, 2.3600, 0.4240, false, false, 0.000, -0.0011}, // 30 I // I wild guess {11, "Zn2p", SP3_HYBRID, POLAR, 2.000, 1.0900, 1.0900, 0.2500, false, false, 0.000, -0.0011}, // 31 Zn2p // Zn2p wild guess {7 , "Fe2p", SP3_HYBRID, POLAR, 2.000, 0.7800, 0.7800, 0.0000, false, false, 0.000, -0.0011}, // 32 Fe2p // Fe2p wild guess {7 , "Fe3p", SP3_HYBRID, POLAR, 3.000, 0.6500, 0.6500, 0.0000, false, false, 0.000, -0.0011}, // 33 Fe3p // Fe3p wild guess {8 , "Mg2p", SP3_HYBRID, POLAR, 2.000, 1.1850, 1.1850, 0.0150, false, false, 0.000, -0.0011}, // 34 Mg2p // Mg2p wild guess {6 , "Ca2p", SP3_HYBRID, POLAR, 2.000, 1.3670, 1.3670, 0.1200, false, false, 0.000, -0.0011}, // 35 Ca2p // Ca2p wild guess {10, "Na1p", SP3_HYBRID, POLAR, 1.000, 1.3638, 1.3638, 0.0469, false, false, 0.000, 0.000}, // 36 Na1p // Na1p wild guess {14, "K1p ", SP3_HYBRID, POLAR, 1.000, 1.7638, 1.7638, 0.0870, false, false, 0.000, 0.000}, // 37 K1p // K1p wild guess {99, "VOOC", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 38 1 ASP/GLU // V01 {99, "VCOO", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 39 2 ASP/GLU // V02 {99, "VOCN", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 40 3 ASN/GLN or BB // V03 {99, "VNOC", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 41 4 ASN/GLN or BB // V04 {99, "VCON", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 42 5 ASN/GLN or BB // V05 {99, "VSOG", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 43 6 SER OG // V06 {99, "VSCB", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 44 7 SER CB // V07 {99, "VCSG", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 45 8 CYS SG // V08 {99, "VCCB", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 46 9 CYS CB // V09 {99, "VRNH", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 47 10 ARG NH // V10 {99, "VRNE", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 48 11 ARG NE // V11 {99, "VKNZ", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 49 12 LYS NZ // V12 {99, "VKCE", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 50 13 LYS CE // V13 {99, "VHND", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 51 14 HIS ND // V14 {99, "VHNE", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 52 15 HIS NE // V15 {99, "VHCB", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 53 16 HIS CB // V16 {99, "VHPO", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000} // 54 17 HPOL // V17 }; //NUEVOS RADIOS DE VDW Atom_type atom_types_ICM[54]= { // at name hybridation polar chrge vdw soft deep acept donor Avol Asolpar {0 , "CNH2", SP2_HYBRID, APOLAR, 0.550, 1.8100, 2.0000, 0.1200, false, false, 0.01918, -0.0010}, // 1 CNH2 // carbonyl C in Asn and Gln and guanidyl C in Arg {0 , "COO ", SP2_HYBRID, APOLAR, 0.620, 1.7600, 2.0000, 0.1200, false, false, 0.01918, -0.0010}, // 2 COO // carboxyl C in Asp and Glu {0 , "CH1 ", SP3_HYBRID, APOLAR, -0.090, 2.0100, 2.1400, 0.0486, false, false, 0.01918, -0.0010}, // 3 CH1 // aliphatic C with one H (Val, Ile, Thr) {0 , "CH2 ", SP3_HYBRID, APOLAR, -0.180, 1.9200, 2.1400, 0.1142, false, false, 0.01918, -0.0010}, // 4 CH2 // aliphatic C with two H (other residues) {0 , "CH3 ", SP3_HYBRID, APOLAR, -0.270, 1.9200, 2.1400, 0.1811, false, false, 0.01918, -0.0010}, // 5 CH3 // aliphatic C with three H (Ala) {0 , "aroC", SP2_HYBRID, APOLAR, -0.115, 1.7400, 2.1400, 0.1200, false, false, 0.1108, -0.0005}, // 6 aroC // aromatic ring C (His, Phe, Tyr, Trp) {2 , "Ntrp", SP2_HYBRID, POLAR, -0.610, 1.6600, 1.7500, 0.2384, false, true, -0.03910, -0.0016}, // 7 Ntrp // N in Trp side-chain {2 , "Nhis", RING_HYBRID,POLAR, -0.530, 1.6500, 1.7500, 0.2384, true, false, -0.03910, -0.0016}, // 8 Nhis // N in His side-chain {2 , "NH2O", SP2_HYBRID, POLAR, -0.470, 1.6200, 1.7500, 0.2384, false, true, -0.03910, -0.0016}, // 9 NH2O // N in Asn and Gln side-chain {2 , "Nlys", SP3_HYBRID, POLAR, -0.620, 1.6700, 1.7500, 0.2384, false, true, -0.12604, -0.0016}, // 10 NLYS // N in Lys side-chain, N-terminus? {2 , "Narg", SP2_HYBRID, POLAR, -0.750, 1.6700, 1.7500, 0.2384, false, true, -0.06256, -0.0016}, // 11 Narg // N in Arg side-chain **** -7.0, 07/08/01 ... too many buried Arg {2 , "Npro", SP2_HYBRID, APOLAR, -0.370, 1.6700, 1.8725, 0.2384, false, true, -0.03910, -0.0016}, // 12 Npro // N in Pro backbone {3 , "OH ", SP3_HYBRID, POLAR, -0.660, 1.5400, 1.6585, 0.1591, true, true, -0.04255, -0.0025}, // 13 OH // hydroxyl O in Ser, Thr and Tyr {3 , "ONH2", SP2_HYBRID, POLAR, -0.550, 1.5200, 1.5500, 0.1591, true, false, -0.03128, -0.0025}, // 14 ONH2 // carbonyl O in Asn and Gln **** -5.85, 07/08/01 ... too many buried Asn,Arg {3 , "OOC ", SP2_HYBRID, POLAR, -0.760, 1.4900, 1.5500, 0.2100, true, false, -0.06877, -0.0025}, // 15 OOC // carboyxl O in Asp and Glu {4 , "S ", SP3_HYBRID, POLAR, -0.160, 1.9400, 2.0330, 0.1600, false, false, 0.02576, -0.0021}, // 16 S // sulfur in Cys and Met {2 , "Nbb ", SP2_HYBRID, POLAR, -0.470, 1.7000, 1.8725, 0.2384, false, true, -0.03910, -0.0016}, // 17 Nbb // backbone N' {0 , "CAbb", SP3_HYBRID, APOLAR, 0.070, 1.9000, 2.1400, 0.0486, false, false, 0.01918, -0.0010}, // 18 CAbb // backbone CA {0 , "CObb", SP2_HYBRID, APOLAR, 0.510, 1.7500, 2.1400, 0.1400, false, false, 0.01918, -0.0010}, // 19 CObb // backbone C' {0 , "OCbb", SP2_HYBRID, POLAR, -0.510, 1.4900, 1.6585, 0.1591, true, false, -0.03128, -0.0025}, // 20 OCbb // backbone O' {4 , "Phos", SP3_HYBRID, APOLAR, -0.160, 1.9000, 2.0330, 0.3182, false, false, 0.000, -0.0011}, // 21 Phos // nucleic acid P (from S) {1 , "Hpol", H_HYBRID, APOLAR, 0.430, 1.0000, 1.0700, 0.0500, false, false, 0.000, 0.0005}, // 22 Hpol // polar H {1 , "Hapo", H_HYBRID, APOLAR, 0.095, 1.2000, 1.2840, 0.0500, false, false, 0.000, 0.0005}, // 23 Hapo // nonpolar H {1 , "Haro", H_HYBRID, APOLAR, 0.115, 1.2000, 1.2840, 0.0500, false, false, 0.000, 0.0005}, // 24 Haro // aromatic H {1 , "HNbb", H_HYBRID, APOLAR, 0.310, 1.0000, 1.0700, 0.0500, false, false, 0.000, 0.0005}, // 25 HNbb // backbone HN {3 , "HOH ", SP3_HYBRID, POLAR, 0.000, 1.4000, 1.4000, 0.0500, true, true, 0.000, 0.0005}, // 26 H2O // H2O {27, "F ", SP3_HYBRID, APOLAR, -0.250, 1.7100, 1.7100, 0.0750, false, false, 0.000, -0.0011}, // 27 F // F wild guess {18, "Cl ", SP3_HYBRID, APOLAR, -0.130, 2.0700, 2.0700, 0.2400, false, false, 0.000, -0.0011}, // 28 Cl // Cl wild guess {17, "Br ", SP3_HYBRID, APOLAR, -0.100, 2.2200, 2.2200, 0.3200, false, false, 0.000, -0.0011}, // 29 Br // Br wild guess {26, "I ", SP3_HYBRID, APOLAR, -0.090, 2.3600, 2.3600, 0.4240, false, false, 0.000, -0.0011}, // 30 I // I wild guess {11, "Zn2p", SP3_HYBRID, POLAR, 2.000, 1.0900, 1.0900, 0.2500, false, false, 0.000, -0.0011}, // 31 Zn2p // Zn2p wild guess {7 , "Fe2p", SP3_HYBRID, POLAR, 2.000, 0.7800, 0.7800, 0.0000, false, false, 0.000, -0.0011}, // 32 Fe2p // Fe2p wild guess {7 , "Fe3p", SP3_HYBRID, POLAR, 3.000, 0.6500, 0.6500, 0.0000, false, false, 0.000, -0.0011}, // 33 Fe3p // Fe3p wild guess {8 , "Mg2p", SP3_HYBRID, POLAR, 2.000, 1.1850, 1.1850, 0.0150, false, false, 0.000, -0.0011}, // 34 Mg2p // Mg2p wild guess {6 , "Ca2p", SP3_HYBRID, POLAR, 2.000, 1.3670, 1.3670, 0.1200, false, false, 0.000, -0.0011}, // 35 Ca2p // Ca2p wild guess {10, "Na1p", SP3_HYBRID, POLAR, 1.000, 1.3638, 1.3638, 0.0469, false, false, 0.000, 0.000}, // 36 Na1p // Na1p wild guess {14, "K1p ", SP3_HYBRID, POLAR, 1.000, 1.7638, 1.7638, 0.0870, false, false, 0.000, 0.000}, // 37 K1p // K1p wild guess {99, "VOOC", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 38 1 ASP/GLU // V01 {99, "VCOO", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 39 2 ASP/GLU // V02 {99, "VOCN", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 40 3 ASN/GLN or BB // V03 {99, "VNOC", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 41 4 ASN/GLN or BB // V04 {99, "VCON", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 42 5 ASN/GLN or BB // V05 {99, "VSOG", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 43 6 SER OG // V06 {99, "VSCB", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 44 7 SER CB // V07 {99, "VCSG", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 45 8 CYS SG // V08 {99, "VCCB", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 46 9 CYS CB // V09 {99, "VRNH", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 47 10 ARG NH // V10 {99, "VRNE", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 48 11 ARG NE // V11 {99, "VKNZ", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 49 12 LYS NZ // V12 {99, "VKCE", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 50 13 LYS CE // V13 {99, "VHND", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 51 14 HIS ND // V14 {99, "VHNE", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 52 15 HIS NE // V15 {99, "VHCB", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 53 16 HIS CB // V16 {99, "VHPO", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000} // 54 17 HPOL // V17 }; Atom_type atom_types_EEF1[31]= { // Solo he rellenado con EEF1 at, vdw, soft, deep // at name hybridation polar chrge vdw soft deep acept donor // Rmin/2 Rmin/2 emin {1 , "H", SP2_HYBRID, APOLAR, 0.550, 0.8000, 0.8000, 0.04980, false, false}, // 1 {1 , "HC", SP2_HYBRID, APOLAR, 0.620, 0.6000, 0.6000, 0.04980, false, false}, // 2 {1 , "HA", SP3_HYBRID, APOLAR, -0.090, 1.4680, 1.4680, 0.04500, false, false}, // 3 {0 , "CT", SP3_HYBRID, APOLAR, -0.180, 2.4900, 2.4900, 0.02620, false, false}, // 4 {0 , "C", SP3_HYBRID, APOLAR, -0.270, 2.1000, 2.1000, 0.12000, false, false}, // 5 {0 , "CH1E", SP2_HYBRID, APOLAR, -0.115, 2.3650, 2.3650, 0.04860, false, false}, // 6 {0 , "CH2E", SP2_HYBRID, POLAR, -0.610, 2.2350, 2.2350, 0.11420, false, true}, // 7 {0 , "CH3E", RING_HYBRID,POLAR, -0.530, 2.1650, 2.1650, 0.18110, true, false}, // 8 {0 , "CR1E", SP2_HYBRID, POLAR, -0.470, 2.1000, 2.1000, 0.12000, false, true}, // 9 {2 , "N", SP3_HYBRID, POLAR, -0.620, 1.6000, 1.6000, 0.23840, false, true}, // 10 {2 , "NR", SP2_HYBRID, POLAR, -0.750, 1.6000, 1.6000, 0.23840, false, true}, // 11 {2 , "NP", SP2_HYBRID, APOLAR, -0.370, 1.6000, 1.6000, 0.23840, false, true}, // 12 {2 , "NH1", SP3_HYBRID, POLAR, -0.660, 1.6000, 1.6000, 0.23840, true, true}, // 13 {2 , "NH2", SP2_HYBRID, POLAR, -0.550, 1.6000, 1.6000, 0.23840, true, false}, // 14 {2 , "NH3", SP2_HYBRID, POLAR, -0.760, 1.6000, 1.6000, 0.23840, true, false}, // 15 {2 , "NC2", SP3_HYBRID, POLAR, -0.160, 1.6000, 1.6000, 0.23840, false, false}, // 16 {3 , "O", SP2_HYBRID, POLAR, -0.470, 1.6000, 1.6000, 0.15910, false, true}, // 17 {3 , "OC", SP3_HYBRID, APOLAR, 0.070, 1.6000, 1.6000, 0.64690, false, false}, // 18 {3 , "OH1", SP2_HYBRID, APOLAR, 0.510, 1.6000, 1.6000, 0.15910, false, false}, // 19 {3 , "OH2", SP2_HYBRID, POLAR, -0.510, 1.7398, 1.7398, 0.07580, true, false}, // 20 {5 , "S", SP3_HYBRID, APOLAR, -0.160, 1.8900, 1.8900, 0.04300, false, false}, // 21 {5 , "SH1E",H_HYBRID, APOLAR, 0.430, 1.8900, 1.8900, 0.04300, false, false}, // 22 {7 , "FE", H_HYBRID, APOLAR, 0.095, 0.6500, 0.6500, 0.00000, false, false}, // 23 {99 , "OS", H_HYBRID, APOLAR, 0.115, 1.6000, 1.6000, 0.15910, false, false}, // 24 {99 , "CR", H_HYBRID, APOLAR, 0.310, 2.1000, 2.1000, 0.12000, false, false}, // 25 {99 , "CM", SP3_HYBRID, POLAR, 0.000, 2.4900, 2.4900, 0.02620, true, true}, // 26 {99, "OM", SP3_HYBRID, APOLAR, -0.250, 1.6000, 1.6000, 0.15910, false, false}, // 27 {99, "LP", SP3_HYBRID, APOLAR, -0.130, 0.2245, 0.2245, 0.04598, false, false}, // 28 {99, "HT", SP3_HYBRID, APOLAR, -0.100, 0.8000, 0.8000, 0.04980, false, false}, // 29 {99, "OT", SP3_HYBRID, APOLAR, -0.090, 1.6000, 1.6000, 0.15910, false, false}, // 30 {99, "CAL", SP3_HYBRID, POLAR, 2.000, 1.7100, 1.7100, 0.12000, false, false} // 31 }; Atom_type atom_types_Sybil[45]= { // at name hybridation polar chrge vdw soft deep acept donor Avol Asolpar {0 , "C2 ", SP2_HYBRID, APOLAR, 0.510, 2.0000, 2.1400, 0.1400, false, false, 0.01918, -0.0010}, // 1 {0 , "C3 ", SP3_HYBRID, APOLAR,-0.270, 2.0000, 2.1400, 0.1811, false, false, 0.01918, -0.0010}, // 2 {0 , "Car ", SP2_HYBRID, APOLAR,-0.115, 2.0000, 2.1400, 0.1200, false, false, 0.1108, -0.0005}, // 3 {0 , "Ccat", SP2_HYBRID, APOLAR,-0.115, 2.0000, 2.1400, 0.1200, false, false, 0.1108, -0.0005}, // 4 {2 , "N3 ", SP3_HYBRID, POLAR, -0.620, 1.7500, 1.7500, 0.2384, true, true, -0.12604, -0.0016}, // 5 {2 , "Nam ", SP2_HYBRID, POLAR, -0.470, 1.7500, 1.8725, 0.2384, false, true,-0.03910, -0.0016}, // 6 {2 , "Npl3", SP2_HYBRID, POLAR, -0.370, 1.7500, 1.8725, 0.2384, false, true,-0.03910, -0.0016}, // 7 {3 , "O2 ", SP2_HYBRID, POLAR, -0.510, 1.5500, 1.6585, 0.1591, true, false,-0.03128, -0.0025}, // 8 {3 , "O3 ", SP3_HYBRID, POLAR, -0.660, 1.5500, 1.6585, 0.1591, true, true,-0.04255, -0.0025}, // 9 {3 , "Oco2", SP2_HYBRID, POLAR, -0.760, 1.5500, 1.5500, 0.2100, true, false,-0.06877, -0.0025}, //10 {5 , "S3 ", SP3_HYBRID, POLAR, -0.160, 1.9000, 2.0330, 0.1600, false, false, 0.02576, -0.0021}, //11 //from here it is the same as Rosseta {4 , "Phos", SP3_HYBRID, APOLAR, -0.160, 1.9000, 2.0330, 0.3182, false, false, 0.000, -0.0011}, // 12 {1 , "Hpol", H_HYBRID, APOLAR, 0.430, 1.0000, 1.0700, 0.0500, false, false, 0.000, 0.0005}, // 13 {1 , "Hapo", H_HYBRID, APOLAR, 0.095, 1.2000, 1.2840, 0.0500, false, false, 0.000, 0.0005}, // 14 {1 , "Haro", H_HYBRID, APOLAR, 0.115, 1.2000, 1.2840, 0.0500, false, false, 0.000, 0.0005}, // 15 {1 , "HNbb", H_HYBRID, APOLAR, 0.310, 1.0000, 1.0700, 0.0500, false, false, 0.000, 0.0005}, // 16 {3 , "HOH ", SP3_HYBRID, POLAR, 0.000, 1.4000, 1.4000, 0.0500, true, true, 0.000, 0.0005}, // 17 {27, "F ", SP3_HYBRID, APOLAR, -0.250, 1.7100, 1.7100, 0.0750, false, false, 0.000, -0.0011}, // 18 {18, "Cl ", SP3_HYBRID, APOLAR, -0.130, 2.0700, 2.0700, 0.2400, false, false, 0.000, -0.0011}, // 19 {17, "Br ", SP3_HYBRID, APOLAR, -0.100, 2.2200, 2.2200, 0.3200, false, false, 0.000, -0.0011}, // 20 {26, "I ", SP3_HYBRID, APOLAR, -0.090, 2.3600, 2.3600, 0.4240, false, false, 0.000, -0.0011}, // 21 {11, "Zn2p", SP3_HYBRID, POLAR, 2.000, 1.0900, 1.0900, 0.2500, false, false, 0.000, -0.0011}, // 22 {7 , "Fe2p", SP3_HYBRID, POLAR, 2.000, 0.7800, 0.7800, 0.0000, false, false, 0.000, -0.0011}, // 23 {7 , "Fe3p", SP3_HYBRID, POLAR, 3.000, 0.6500, 0.6500, 0.0000, false, false, 0.000, -0.0011}, // 24 {8 , "Mg2p", SP3_HYBRID, POLAR, 2.000, 1.1850, 1.1850, 0.0150, false, false, 0.000, -0.0011}, // 25 {6 , "Ca2p", SP3_HYBRID, POLAR, 2.000, 1.3670, 1.3670, 0.1200, false, false, 0.000, -0.0011}, // 26 {10, "Na1p", SP3_HYBRID, POLAR, 1.000, 1.3638, 1.3638, 0.0469, false, false, 0.000, 0.000}, // 27 {14, "K1p ", SP3_HYBRID, POLAR, 1.000, 1.7638, 1.7638, 0.0870, false, false, 0.000, 0.000}, // 28 {99, "VOOC", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 29 {99, "VCOO", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 30 {99, "VOCN", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 31 {99, "VNOC", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 32 {99, "VCON", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 33 {99, "VSOG", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 34 {99, "VSCB", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 35 {99, "VCSG", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 36 {99, "VCCB", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 37 {99, "VRNH", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 38 {99, "VRNE", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 39 {99, "VKNZ", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 40 {99, "VKCE", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 41 {99, "VHND", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 42 {99, "VHNE", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 43 {99, "VHCB", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000}, // 44 {99, "VHPO", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false, 0.000, 0.000} // 45 }; /* //NUEVOS RADIOS DE VDW a partir de tablas de Julio Kovacs Atom_type atom_types[54]= { // at name hybridation polar chrge vdw soft deep acept donor {0 , "CNH2", SP2_HYBRID, APOLAR, 0.550, 1.7000, 2.0000, 0.1200, false, false}, // 1 CNH2 // carbonyl C in Asn and Gln and guanidyl C in Arg {0 , "COO ", SP2_HYBRID, APOLAR, 0.620, 1.7000, 2.0000, 0.1200, false, false}, // 2 COO // carboxyl C in Asp and Glu {0 , "CH1 ", SP3_HYBRID, APOLAR, -0.090, 1.7000, 2.1400, 0.0486, false, false}, // 3 CH1 // aliphatic C with one H (Val, Ile, Thr) {0 , "CH2 ", SP3_HYBRID, APOLAR, -0.180, 1.7000, 2.1400, 0.1142, false, false}, // 4 CH2 // aliphatic C with two H (other residues) {0 , "CH3 ", SP3_HYBRID, APOLAR, -0.270, 1.7000, 2.1400, 0.1811, false, false}, // 5 CH3 // aliphatic C with three H (Ala) {0 , "aroC", SP2_HYBRID, APOLAR, -0.115, 1.7400, 2.1400, 0.1200, false, false}, // 6 aroC // aromatic ring C (His, Phe, Tyr, Trp) {1 , "Ntrp", SP2_HYBRID, POLAR, -0.610, 1.5000, 1.7500, 0.2384, false, true}, // 7 Ntrp // N in Trp side-chain {1 , "Nhis", RING_HYBRID,POLAR, -0.530, 1.5000, 1.7500, 0.2384, true, false}, // 8 Nhis // N in His side-chain {1 , "NH2O", SP2_HYBRID, POLAR, -0.470, 1.5000, 1.7500, 0.2384, false, true}, // 9 NH2O // N in Asn and Gln side-chain {1 , "Nlys", SP3_HYBRID, POLAR, -0.620, 1.5000, 1.7500, 0.2384, false, true}, // 10 NLYS // N in Lys side-chain, N-terminus? {1 , "Narg", SP2_HYBRID, POLAR, -0.750, 1.5000, 1.7500, 0.2384, false, true}, // 11 Narg // N in Arg side-chain **** -7.0, 07/08/01 ... too many buried Arg {1 , "Npro", SP2_HYBRID, APOLAR, -0.370, 1.5000, 1.8725, 0.2384, false, true}, // 12 Npro // N in Pro backbone {2 , "OH ", SP3_HYBRID, POLAR, -0.660, 1.4000, 1.6585, 0.1591, true, true}, // 13 OH // hydroxyl O in Ser, Thr and Tyr {2 , "ONH2", SP2_HYBRID, POLAR, -0.550, 1.4000, 1.5500, 0.1591, true, false}, // 14 ONH2 // carbonyl O in Asn and Gln **** -5.85, 07/08/01 ... too many buried Asn,Arg {2 , "OOC ", SP2_HYBRID, POLAR, -0.760, 1.4000, 1.5500, 0.2100, true, false}, // 15 OOC // carboyxl O in Asp and Glu {3 , "S ", SP3_HYBRID, POLAR, -0.160, 1.8500, 2.0330, 0.1600, false, false}, // 16 S // sulfur in Cys and Met {2 , "Nbb ", SP2_HYBRID, POLAR, -0.470, 1.5000, 1.8725, 0.2384, false, true}, // 17 Nbb // backbone N' {0 , "CAbb", SP3_HYBRID, APOLAR, 0.070, 1.7000, 2.1400, 0.0486, false, false}, // 18 CAbb // backbone CA {0 , "CObb", SP2_HYBRID, APOLAR, 0.510, 1.7000, 2.1400, 0.1400, false, false}, // 19 CObb // backbone C' {0 , "OCbb", SP2_HYBRID, POLAR, -0.510, 1.5000, 1.6585, 0.1591, true, false}, // 20 OCbb // backbone O' {4 , "Phos", SP3_HYBRID, APOLAR, -0.160, 1.9000, 2.0330, 0.3182, false, false}, // 21 Phos // nucleic acid P (from S) {1 , "Hpol", H_HYBRID, APOLAR, 0.430, 1.0000, 1.0700, 0.0500, false, false}, // 22 Hpol // polar H {1 , "Hapo", H_HYBRID, APOLAR, 0.095, 1.0000, 1.2840, 0.0500, false, false}, // 23 Hapo // nonpolar H {1 , "Haro", H_HYBRID, APOLAR, 0.115, 1.0000, 1.2840, 0.0500, false, false}, // 24 Haro // aromatic H {1 , "HNbb", H_HYBRID, APOLAR, 0.310, 1.0000, 1.0700, 0.0500, false, false}, // 25 HNbb // backbone HN {3 , "HOH ", SP3_HYBRID, POLAR, 0.000, 1.0000, 1.4000, 0.0500, true, true}, // 26 H2O // H2O {99, "F ", SP3_HYBRID, APOLAR, -0.250, 1.7100, 1.7100, 0.0750, false, false}, // 27 F // F wild guess {18, "Cl ", SP3_HYBRID, APOLAR, -0.130, 2.0700, 2.0700, 0.2400, false, false}, // 28 Cl // Cl wild guess {17, "Br ", SP3_HYBRID, APOLAR, -0.100, 2.2200, 2.2200, 0.3200, false, false}, // 29 Br // Br wild guess {99, "I ", SP3_HYBRID, APOLAR, -0.090, 2.3600, 2.3600, 0.4240, false, false}, // 30 I // I wild guess {11, "Zn2p", SP3_HYBRID, POLAR, 2.000, 1.0900, 1.0900, 0.2500, false, false}, // 31 Zn2p // Zn2p wild guess {7 , "Fe2p", SP3_HYBRID, POLAR, 2.000, 0.7800, 0.7800, 0.0000, false, false}, // 32 Fe2p // Fe2p wild guess {7 , "Fe3p", SP3_HYBRID, POLAR, 3.000, 0.6500, 0.6500, 0.0000, false, false}, // 33 Fe3p // Fe3p wild guess {8 , "Mg2p", SP3_HYBRID, POLAR, 2.000, 1.1850, 1.1850, 0.0150, false, false}, // 34 Mg2p // Mg2p wild guess {6 , "Ca2p", SP3_HYBRID, POLAR, 2.000, 1.3670, 1.3670, 0.1200, false, false}, // 35 Ca2p // Ca2p wild guess {10, "Na1p", SP3_HYBRID, POLAR, 1.000, 1.3638, 1.3638, 0.0469, false, false}, // 36 Na1p // Na1p wild guess {14, "K1p ", SP3_HYBRID, POLAR, 1.000, 1.7638, 1.7638, 0.0870, false, false}, // 37 K1p // K1p wild guess {99, "VOOC", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false}, // 38 1 ASP/GLU // V01 {99, "VCOO", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false}, // 39 2 ASP/GLU // V02 {99, "VOCN", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false}, // 40 3 ASN/GLN or BB // V03 {99, "VNOC", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false}, // 41 4 ASN/GLN or BB // V04 {99, "VCON", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false}, // 42 5 ASN/GLN or BB // V05 {99, "VSOG", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false}, // 43 6 SER OG // V06 {99, "VSCB", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false}, // 44 7 SER CB // V07 {99, "VCSG", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false}, // 45 8 CYS SG // V08 {99, "VCCB", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false}, // 46 9 CYS CB // V09 {99, "VRNH", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false}, // 47 10 ARG NH // V10 {99, "VRNE", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false}, // 48 11 ARG NE // V11 {99, "VKNZ", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false}, // 49 12 LYS NZ // V12 {99, "VKCE", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false}, // 50 13 LYS CE // V13 {99, "VHND", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false}, // 51 14 HIS ND // V14 {99, "VHNE", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false}, // 52 15 HIS NE // V15 {99, "VHCB", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false}, // 53 16 HIS CB // V16 {99, "VHPO", H_HYBRID, APOLAR, 0.000, 0.0000, 0.0000, 0.0000, false, false} // 54 17 HPOL // V17 }; */ /*Default constructor*/ Atom::Atom() { /*The atom is created with the firts element of the table*/ element= Table_Elements::getElement(0); pdbSerialNumber=0; strcpy(pdbName," C "); pdbocc=0.0; pdbfact=0.0; position[0]=0.0; position[1]=0.0; position[2]=0.0; charge=0; father=NULL; bonds=NULL; num_bonds=0; } /*Constructor. e: Element Object of the atom. The Object element is copied in another object, not assignated p: three-dimension position of the atom ch: charge of the atom*/ Atom::Atom(Element *e, Tcoor p,float ch,char name[5],int serial, float occ, float fact) { element=e; strcpy(pdbName,name); position[0]=p[0]; position[1]=p[1]; position[2]=p[2]; charge=ch; pdbSerialNumber=serial; pdbocc=occ; pdbfact=fact; father=NULL; bonds=NULL; num_bonds=0; } /*Constructor from template */ Atom::Atom(Atom_type atom_type, char name[5], float *p, int serial) { element= Table_Elements::getElement(atom_type.at); strcpy(pdbName,name); position[0]=p[0]; position[1]=p[1]; position[2]=p[2]; //printf("%s %f %f %f\n",name, position[0],position[1],position[2]); charge=atom_type.chrge; pdbSerialNumber=serial; pdbocc=1.0; pdbfact=1.0; father=NULL; bonds=NULL; num_bonds=0; } /*Constructor. Copy of another atom. The only difference between both atoms is the name n: name of the new atom. a: atom to copy */ Atom::Atom(Atom *a) { element=a->getElement(); strcpy(pdbName,a->getPdbName()); Tcoor pos; a->getPosition(pos); position[0]=pos[0]; position[1]=pos[1]; position[2]=pos[2]; charge=a->getCharge(); pdbSerialNumber=a->getPdbSerial(); pdbocc=a->getPdbocc(); pdbfact=a->getPdbfact(); father=NULL; bonds=NULL; num_bonds=0; } /*Destructor*/ Atom::~Atom() { //std::cout<<"Atomo eliminado"<<std::endl; if(num_bonds>0) free(bonds); } /*Get the position of the atom*/ void Atom::getPosition(Tcoor coor) { coor[0]=position[0]; coor[1]=position[1]; coor[2]=position[2]; } /*Get the charge of the atom*/ float Atom::getCharge() { return charge; } /*Get the object Element of the atom*/ Element* Atom::getElement() { return element; } int Atom::getPdbSerial() { return pdbSerialNumber; } char* Atom::getPdbName() { return pdbName; } float Atom::getPdbocc() { return pdbocc; } float Atom::getPdbfact() { return pdbfact; } /*Set new position for the atom*/ void Atom::setPosition(Tcoor pos) { position[0]=pos[0]; position[1]=pos[1]; position[2]=pos[2]; } /*Set new Charge for the atom*/ void Atom::setCharge(float ch) { charge=ch; } void Atom::setPdbSerial(int serial) { pdbSerialNumber=serial; } void Atom::setPdbName(char n[5]) { strcpy(pdbName,n); } void Atom::setPdbocc(float occ) { pdbocc=occ; } void Atom::setPdbfact(float fact) { pdbfact=fact; } /*move an offset the position of the atom */ bool Atom::move(Tcoor offset) { position[0]+=offset[0]; position[1]+=offset[1]; position[2]+=offset[2]; return true; } /*move an offset the position of the atom */ bool Atom::moven(Tcoor offset) { position[0]-=offset[0]; position[1]-=offset[1]; position[2]-=offset[2]; return true; } char *Atom::getName() { return pdbName; } bool Atom::initAll() { return true; } bool Atom::moveAll(Tcoor offset) { return move(offset); } bool Atom::moveAlln(Tcoor offset) { return moven(offset); } TElement Atom::getClass() { return pdb_atom; } TMOL Atom::getMolType() { PDB_Container *f; f=(PDB_Container*)getFather(); if(f!=NULL) return f->getMolType(); else return tmol_null; } int Atom::get_numBonds() { return num_bonds; } Bond* Atom::getBond(int i) { if( i>num_bonds ) return NULL; else { return bonds[i]; } } void Atom::insertBond(Bond *b) { num_bonds++; bonds=(Bond**)realloc(bonds,sizeof(Bond*)*num_bonds); bonds[num_bonds-1]=b; } bool Atom::removeBond(Bond *b) { int i,j; for(i=0;i<num_bonds;i++) { if(b==bonds[i]) { for(j=i+1;j<num_bonds;j++) bonds[j-1]=bonds[j]; num_bonds--; bonds=(Bond**)realloc(bonds,sizeof(Bond*)*num_bonds); return true; } } return false; } Bond::Bond(Atom* i, Atom *f, int l) { final=f; init=i; link=l; } Bond::~Bond() { } int Bond::getLink() { return link; } Atom * Bond::getInit() { return init; } Atom *Bond::getFinal() { return final; }
64.355556
212
0.540475
chaconlab
71db72db15b02f52511cca6db4053c8727b4ca70
1,898
cpp
C++
gadgets/mri_core/ImageSortGadget.cpp
roopchansinghv/gadgetron
fb6c56b643911152c27834a754a7b6ee2dd912da
[ "MIT" ]
1
2022-02-22T21:06:36.000Z
2022-02-22T21:06:36.000Z
gadgets/mri_core/ImageSortGadget.cpp
apd47/gadgetron
073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2
[ "MIT" ]
null
null
null
gadgets/mri_core/ImageSortGadget.cpp
apd47/gadgetron
073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2
[ "MIT" ]
null
null
null
#include "ImageSortGadget.h" namespace Gadgetron{ int ImageSortGadget::index(GadgetContainerMessage<ISMRMRD::ImageHeader>* m1) { std::string sorting_dimension_local = sorting_dimension.value(); if (sorting_dimension_local.size() == 0) { return -1; } else if (sorting_dimension_local.compare("average") == 0) { return m1->getObjectPtr()->average; } else if (sorting_dimension_local.compare("slice") == 0) { return m1->getObjectPtr()->slice; } else if (sorting_dimension_local.compare("contrast") == 0) { return m1->getObjectPtr()->contrast; } else if (sorting_dimension_local.compare("phase") == 0) { return m1->getObjectPtr()->phase; } else if (sorting_dimension_local.compare("repetition") == 0) { return m1->getObjectPtr()->repetition; } else if (sorting_dimension_local.compare("set") == 0) { return m1->getObjectPtr()->set; } else { return -1; } return -1; } int ImageSortGadget::close(unsigned long flags) { GDEBUG("++++++ close call with %d images\n", images_.size()); if (images_.size()) { std::sort(images_.begin(),images_.end(), image_entry_compare); for (auto it = images_.begin(); it != images_.end(); it++) { if (this->next()->putq(it->mb_) == -1) { it->mb_->release(); GERROR("Error passing data on to next gadget\n"); return GADGET_FAIL; } } images_.clear(); } return GADGET_OK; } int ImageSortGadget::process(GadgetContainerMessage<ISMRMRD::ImageHeader>* m1) { if (index(m1) < 0) { if (this->next()->putq(m1) == -1) { m1->release(); GERROR("Error passing data on to next gadget\n"); return GADGET_FAIL; } } ImageEntry i; i.index_ = index(m1); i.mb_ = m1; images_.push_back(i); return GADGET_OK; } GADGET_FACTORY_DECLARE(ImageSortGadget); }
26.732394
80
0.620126
roopchansinghv
71dd3136da2779784f38d3e7e48498a500421044
899
cpp
C++
ojcpp/hht/015_kth_from_tail_list.cpp
softarts/oj
2f51f360a7a6c49e865461755aec2f3a7e721b9e
[ "Apache-2.0" ]
3
2019-05-04T03:26:02.000Z
2019-08-29T01:20:44.000Z
ojcpp/hht/015_kth_from_tail_list.cpp
softarts/oj
2f51f360a7a6c49e865461755aec2f3a7e721b9e
[ "Apache-2.0" ]
null
null
null
ojcpp/hht/015_kth_from_tail_list.cpp
softarts/oj
2f51f360a7a6c49e865461755aec2f3a7e721b9e
[ "Apache-2.0" ]
null
null
null
// // Created by rui.zhou on 5/6/2019. // #include <codech/codech_def.h> using namespace std; using namespace CODECH; namespace { class Solution { public: ListNode* findKth(ListNode *head,int k) { ListNode *p1 = head; ListNode *p2 = head; if (k==0) return nullptr; while (p2 && k>0) { p2=p2->next;k--; } if (k>0) { return nullptr; } while (p2) { p2=p2->next;p1=p1->next; } return p1; } }; } DEFINE_CODE_TEST(015_kth_tail_list) { Solution obj; { ListNode *h=CREATE_LIST({1,2,3,4,5,6,7,8,9}); VERIFY_CASE(obj.findKth(h,1)->val,9); VERIFY_CASE(obj.findKth(h,9)->val,1); VERIFY_CASE(obj.findKth(h,19),nullptr); VERIFY_CASE(obj.findKth(h,0),nullptr); } }
23.051282
53
0.49277
softarts
71df9f81a9278723166d38b05e9e38d5014ee554
475
cpp
C++
leetcode-cpp/XOROperationinanArray_1486.cpp
emacslisp/cpp
8230f81117d6f64adaa1696b0943cdb47505335a
[ "Apache-2.0" ]
null
null
null
leetcode-cpp/XOROperationinanArray_1486.cpp
emacslisp/cpp
8230f81117d6f64adaa1696b0943cdb47505335a
[ "Apache-2.0" ]
null
null
null
leetcode-cpp/XOROperationinanArray_1486.cpp
emacslisp/cpp
8230f81117d6f64adaa1696b0943cdb47505335a
[ "Apache-2.0" ]
null
null
null
#include<vector> #include<iostream> using namespace std; class Solution { public: int xorOperation(int n, int start) { vector<int> a(n); for(int i=0;i<n;i++) { a[i] = start + 2*i; } int x = a[0]; for(int i=1;i<n;i++) { x ^= a[i]; } return x; } }; int main() { Solution s; int n = 5; int start = 0; int result = s.xorOperation(n, start); cout<< result << endl; }
15.833333
42
0.465263
emacslisp
71dfb1c1d2b370433717364ae6a70d837f947e5e
9,630
cpp
C++
uppsrc/HexView/HexView.cpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
2
2016-04-07T07:54:26.000Z
2020-04-14T12:37:34.000Z
uppsrc/HexView/HexView.cpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
null
null
null
uppsrc/HexView/HexView.cpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
null
null
null
#include "HexView.h" NAMESPACE_UPP #ifdef PLATFORM_WIN32 inline int FormatHexDigit(int c) { return c < 10 ? c + '0' : c - 10 + 'a'; } void FormatHex(char *buffer, int64 number, int n) { buffer[n] = '\0'; while(n) { buffer[--n] = FormatHexDigit((byte)number & 0x0f); number >>= 4; } } void HexViewInfo::PrintValue(Draw& w, int x, int y, int bytes, bool be) { dword d = 0; Size fsz = GetTextSize("X", font); for(int i = 0; i < bytes; i++) { int b = data[be ? i : bytes - i - 1]; if(b < 0) { w.DrawText(x, y, String('?', 2 * bytes), font, SColorHighlight); x += 2 * bytes * fsz.cx; w.DrawText(x, y, "=", font); x += fsz.cx; w.DrawText(x, y, "?", font, Red); return; } d = (d << 8) | (byte) b; } w.DrawText(x, y, FormatIntHex(d, 2 * bytes), font, SColorHighlight); x += 2 * bytes * fsz.cx; w.DrawText(x, y, "=", font); x += fsz.cx; String txt = FormatUnsigned(d); w.DrawText(x, y, txt, font, Red); x += GetTextSize(txt, font).cx; w.DrawText(x, y, "=", font); x += fsz.cx; int q = d; if(bytes == 1) q = (int8) d; else if(bytes == 2) q = (int16) d; w.DrawText(x, y, FormatInt(q), font, Magenta); } void HexViewInfo::Paint(Draw& w) { Size sz = GetSize(); w.DrawRect(sz, SColorLtFace); if(mode < 1) return; Size fsz = GetTextSize("X", font); char h[17]; FormatHex(h, pos, longmode ? 16 : 8); int xx = 0; w.DrawText(xx, 0, h, font, SColorHighlight); xx += (longmode ? 16 : 8) * fsz.cx; w.DrawText(xx, 0, "=", font); xx += fsz.cx; w.DrawText(xx, 0, Format64(pos), font, Red); xx += (longmode ? 22 : 12) * fsz.cx; int y = 0; int x; for(int q = 0; q < mode; q++) { x = xx; if(q < 1) PrintValue(w, x, y, 1, q); x += 12 * fsz.cx; PrintValue(w, x, y, 2, q); x += 18 * fsz.cx; PrintValue(w, x, y, 4, q); x += 32 * fsz.cx; y += fsz.cy; } wchar wh[40]; memset(wh, 0, sizeof(wh)); int i = 0; for(i = 0; i < 40; i++) { if(data[2 * i] < 0 || data[2 * i + 1] < 0) break; wh[i] = MAKEWORD(data[2 * i], data[2 * i + 1]); } w.DrawText(x, 0, wh, font, Cyan, i); if(mode < 2) return; char sh[80]; memset(sh, 0, sizeof(sh)); for(i = 0; i < 80; i++) { if(data[i] < 0) break; sh[i] = data[i]; } WString ws = FromUtf8(sh, i); w.DrawText(x, fsz.cy, ws, font, Cyan, i); String txt; String ftxt; i = 0; for(;;) { if(data[i] < 0) { if((unsigned)i < sizeof(float)) ftxt = "?"; txt = "?"; break; } if((unsigned)i >= sizeof(double)) { double h; memcpy(&h, sh, sizeof(double)); txt = Sprintf("%.8g", h); break; } if(i == sizeof(float)) { float h; memcpy(&h, sh, sizeof(float)); ftxt = Sprintf("%.6g", h); } sh[i] = data[i]; i++; } w.DrawText(0, fsz.cy, txt, font, Red); w.DrawText(18 * fsz.cx, fsz.cy, ftxt, font, Red); } void HexViewInfo::SetMode(int _mode) { mode = _mode; Height(mode * GetTextSize("X", Courier(12)).cy + 3); Show(mode); } HexViewInfo::HexViewInfo() { SetMode(0); AddFrame(TopSeparatorFrame()); AddFrame(RightSeparatorFrame()); font = Courier(12); } int HexView::Byte(int64 adr) { return IsBadReadPtr((byte *)(uintptr_t)adr, 1) ? -1 : *(byte *)(unsigned)adr; } void HexView::Paint(Draw& w) { Size sz = GetSize(); w.DrawRect(sz, SColorPaper); int y = 0; int64 adr = sc; while(y < sz.cy) { char h[17]; FormatHex(h, adr, IsLongMode() ? 16 : 8); w.DrawText(0, y, h, font); int x = (IsLongMode() ? 17 : 9) * fsz.cx; int tx = x + columns * fcx3; for(int q = columns; q--;) { if(adr >= total) return; if(adr == cursor) { w.DrawRect(x, y, fsz.cx * 2, fsz.cy, LtCyan); w.DrawRect(tx, y, fsz.cx, fsz.cy, LtCyan); } int b = Byte(adr++); if(b < 0) { w.DrawText(x, y, "??", font, Brown); w.DrawText(tx, y, "?", font, Brown); } else { h[0] = FormatHexDigit((b & 0xf0) >> 4); h[1] = FormatHexDigit(b & 0x0f); h[2] = '\0'; w.DrawText(x, y, h, font, SColorText); Color color = SColorMark; switch(b) { case '\a': *h = 'a'; break; case '\b': *h = 'b'; break; case '\t': *h = 't'; break; case '\f': *h = 'f'; break; case '\r': *h = 'r'; break; case '\n': *h = 'n'; break; case '\v': *h = 'v'; break; case '\0': *h = '0'; break; default: if(b >= 32) { *h = b; color = SColorText; } else { *h = '.'; color = SColorDisabled; } } h[1] = '\0'; w.DrawText(tx, y, h, charset, font, color); } tx += fsz.cx; x += fcx3; } y += fsz.cy; } } void HexView::MouseWheel(Point, int zdelta, dword) { sb.Wheel(zdelta); } void HexView::SetSb() { sbm = 0; while((total >> sbm) > (1 << 30)) sbm++; sb.SetTotal(int(total >> sbm) / columns + 1); sb.SetPage(int(rows >> sbm)); sb.Set(int(sc >> sbm) / columns + 1); } void HexView::Layout() { Size sz = GetSize(); columns = fixed ? fixed : max(4, (sz.cx - (IsLongMode() ? 18 : 10) * fsz.cx) / (4 * fsz.cx)); rows = max(1, sz.cy / fsz.cy); bytes = columns * rows; SetSb(); } void HexView::SetTotal(int64 _total) { total = _total; Layout(); SetSb(); } void HexView::SetSc(int64 address) { sc = minmax(address, (int64)0, total); SetSb(); Refresh(); } void HexView::Scroll() { int64 q = (int)sb << sbm; if(q == 0) sc = 0; else sc = (q - 1) * columns + sc % columns; Refresh(); } void HexView::SetCursor(int64 _cursor) { cursor = _cursor; if(cursor > total) cursor = total - 1; if(cursor < 0) cursor = 0; int q = int(sc % columns); if(cursor >= sc + bytes) sc = cursor - bytes + columns; if(cursor < sc) { sc = cursor; } if(sc > q) sc = (sc - q) / columns * columns + q; if(sc >= total) sc = total - 1; if(sc < 0) sc = 0; SetSb(); Refresh(); info.SetPos(cursor, IsLongMode()); for(int i = 0; i < 80; i++) info.Set(i, Byte(cursor + i)); } void HexView::LeftDown(Point p, dword) { int rowi = p.y / fsz.cy; int x = (IsLongMode() ? 17 : 9) * fsz.cx; int tx = x + columns * fcx3; if(p.x >= x && p.x < tx) { x = p.x - x; int q = x / fcx3; if(x - q * fcx3 < 2 * fsz.cx && q < columns) { int64 c = sc + rowi * columns + q; if(c < total) SetCursor(c); } } else if(p.x >= tx) { int q = (p.x - tx) / fsz.cx; if(q >= 0 && q < columns) { int64 c = sc + rowi * columns + q; if(c < total) SetCursor(c); } } SetFocus(); } bool HexView::Key(dword key, int) { int pg = max(columns, bytes - columns); int q = int(sc % columns); switch(key) { case K_LEFT: SetCursor(cursor - 1); return true; case K_RIGHT: SetCursor(cursor + 1); return true; case K_UP: SetCursor(cursor - columns); return true; case K_DOWN: SetCursor(cursor + columns); return true; case K_PAGEUP: SetSc(sc - pg); SetCursor(cursor - pg); return true; case K_PAGEDOWN: SetSc(sc + pg); SetCursor(cursor + pg); return true; case K_CTRL_LEFT: SetSc(sc - 1); break; case K_CTRL_RIGHT: SetSc(sc + 1); break; case K_CTRL_UP: SetSc(sc - columns); break; case K_CTRL_DOWN: SetSc(sc + columns); break; case K_HOME: SetCursor((cursor - q) / columns * columns + q); break; case K_END: SetCursor((cursor - q) / columns * columns + q + columns - 1); break; case K_CTRL_HOME: case K_CTRL_PAGEUP: SetCursor(0); break; case K_CTRL_END: case K_CTRL_PAGEDOWN: SetCursor(total - 1); break; } return MenuBar::Scan(WhenBar, key); } void HexView::SetColumns(int x) { FixedColumns(x); } void HexView::SetCharset(int chr) { Charset(chr); } void HexView::StdGoto(const String& s) { CParser p(s); int n = 10; if(p.Char2('0', 'x') || p.Char('$') || p.Char('#')) n = 16; if(p.IsNumber(n)) { int64 a = p.ReadNumber(n); if(a >= 0 && a < total) { SetCursor(a); SetSc(a); return; } } Exclamation("Invalid position!"); } void HexView::Goto() { if(go.Execute() == IDOK) WhenGoto((String)~go.text); } void HexView::ColumnsMenu(Bar& bar) { bar.Add("Auto", THISBACK1(SetColumns, 0)) .Radio(fixed == 0); bar.Add("8", THISBACK1(SetColumns, 8)) .Radio(fixed == 8); bar.Add("16", THISBACK1(SetColumns, 16)) .Radio(fixed == 16); bar.Add("32", THISBACK1(SetColumns, 32)) .Radio(fixed == 32); } void HexView::SetInfo(int m) { info.SetMode(m); } void HexView::InfoMenu(Bar& bar) { bar.Add("None", THISBACK1(SetInfo, 0)) .Check(info.GetMode() == 0); bar.Add("Standard", THISBACK1(SetInfo, 1)) .Check(info.GetMode() == 1); bar.Add("Extended", THISBACK1(SetInfo, 2)) .Check(info.GetMode() == 2); } void HexView::CharsetMenu(Bar& bar) { for(int i = 1; i < CharsetCount(); i++) bar.Add(CharsetName(i), THISBACK1(SetCharset, i)) .Radio(charset == i); } void HexView::StdMenu(Bar& bar) { bar.Add("Go to..", THISBACK(Goto)) .Key(K_CTRL_G); bar.Add("Columns", THISBACK(ColumnsMenu)); bar.Add("Charset", THISBACK(CharsetMenu)); bar.Add("Position info", THISBACK(InfoMenu)); } void HexView::RightDown(Point p, dword w) { LeftDown(p, w); MenuBar::Execute(WhenBar); } HexView& HexView::SetFont(Font fnt) { font = fnt; fsz = GetTextSize("X", font); fcx3 = 3 * fsz.cx; Layout(); Refresh(); SetSb(); return *this; } void HexView::SerializeSettings(Stream& s) { int version = 0; s / version; s / fixed; s % charset; int mode = info.GetMode(); s / mode; info.SetMode(mode); go.text.SerializeList(s); } HexView::HexView() { SetFont(Courier(12)); BackPaint(); charset = CHARSET_WIN1252; sb <<= THISBACK(Scroll); SetFrame(InsetFrame()); AddFrame(sb); cursor = sc = 0; total = 0; fixed = 0; SetSc(0); SetCursor(0); AddFrame(info); info.SetMode(1); WhenBar = THISBACK(StdMenu); CtrlLayoutOKCancel(go, "Go to"); WhenGoto = THISBACK(StdGoto); } #endif END_UPP_NAMESPACE
19.573171
94
0.569886
dreamsxin
71e06d25cb6c4cb43a9080e1acfb2b9511e0034e
1,806
cpp
C++
2018-2019_Term2/CSC3002-Programming_Paradigms/Course_Material/Week 3/04 Programs/PowersOfTwo/PowersOfTwo.cpp
Vito-Swift/CourseMaterials
f2799f004f4353b5f35226158c8fd9f71818810e
[ "MIT" ]
null
null
null
2018-2019_Term2/CSC3002-Programming_Paradigms/Course_Material/Week 3/04 Programs/PowersOfTwo/PowersOfTwo.cpp
Vito-Swift/CourseMaterials
f2799f004f4353b5f35226158c8fd9f71818810e
[ "MIT" ]
null
null
null
2018-2019_Term2/CSC3002-Programming_Paradigms/Course_Material/Week 3/04 Programs/PowersOfTwo/PowersOfTwo.cpp
Vito-Swift/CourseMaterials
f2799f004f4353b5f35226158c8fd9f71818810e
[ "MIT" ]
2
2019-09-25T02:36:37.000Z
2020-06-05T08:47:01.000Z
/* * File: PowersOfTwo.cpp * --------------------- * This program generates a list of the powers of * two up to an exponent limit entered by the user. */ #include <iostream> #include <sstream> #include <string> #include <iomanip> using namespace std; /* Function prototypes */ int getInteger(string prompt); int raiseToPower(int n, int k); /* Main program */ int main() { cout << "This program lists powers of two." << endl; int limit = getInteger("Enter exponent limit: "); for (int i = 0; i <= limit; i++) { cout << setw(2) << i << setw(8) << raiseToPower(2, i) << endl; } return 0; } /* * Function: getInteger * Usage: int n = getInteger(prompt); * ---------------------------------- * Requests an integer value from the user. The function begins by * printing the prompt string on the console and then waits for the * user to enter a line of input data. If that line contains a * single integer, the function returns the corresponding integer * value. If the input is not a legal integer or if extraneous * characters (other than whitespace) appear on the input line, * the implementation gives the user a chance to reenter the value. */ int getInteger(string prompt) { int value; string line; while (true) { cout << prompt; getline(cin, line); istringstream stream(line); stream >> value >> ws; if (!stream.fail() && stream.eof()) break; cout << "Illegal integer format. Try again." << endl; } return value; } /* * Function: raiseToPower * Usage: p = raiseToPower(n, k); * ------------------------------ * Returns the integer n raised to the kth power. */ int raiseToPower(int n, int k) { int result = 1; for (int i = 0; i < k; i++) { result *= n; } return result; }
25.083333
67
0.608527
Vito-Swift
71e21a7d71ed77cc239111a19086c2570d797e32
3,728
cpp
C++
hal/src/driver/qt/epimage_qt.cpp
Euclideon/udshell
795e2d832429c8e5e47196742afc4b452aa23ec3
[ "MIT" ]
null
null
null
hal/src/driver/qt/epimage_qt.cpp
Euclideon/udshell
795e2d832429c8e5e47196742afc4b452aa23ec3
[ "MIT" ]
null
null
null
hal/src/driver/qt/epimage_qt.cpp
Euclideon/udshell
795e2d832429c8e5e47196742afc4b452aa23ec3
[ "MIT" ]
null
null
null
#include "driver.h" #if EPIMAGE_DRIVER == EPDRIVER_QT #include "hal/image.h" #include <QImage> #include <QImageReader> #include <QBuffer> void epImage_InitInternal() { } void epImage_DeinitInternal() { } epImageFormat ConvertQTImageFormatToEP(QImage::Format imageFormat) { switch (imageFormat) { case QImage::Format_RGB32: case QImage::Format_ARGB32: return epIF_BGRA8; case QImage::Format_RGBX8888: case QImage::Format_RGBA8888: return epIF_RGBA8; case QImage::Format_RGB888: return epIF_RGB8; case QImage::Format_Invalid: return epIF_Unknown; // TODO: add support for more formats case QImage::Format_ARGB32_Premultiplied: case QImage::Format_RGB16: case QImage::Format_ARGB8565_Premultiplied: case QImage::Format_RGB666: case QImage::Format_ARGB6666_Premultiplied: case QImage::Format_RGB555: case QImage::Format_ARGB8555_Premultiplied: case QImage::Format_RGB444: case QImage::Format_ARGB4444_Premultiplied: case QImage::Format_Mono: case QImage::Format_MonoLSB: case QImage::Format_Indexed8: case QImage::Format_RGBA8888_Premultiplied: case QImage::Format_BGR30: case QImage::Format_A2BGR30_Premultiplied: case QImage::Format_RGB30: case QImage::Format_A2RGB30_Premultiplied: case QImage::NImageFormats: case QImage::Format_Alpha8: case QImage::Format_Grayscale8: default: return epIF_Unknown; } } epImage* epImage_LoadImage(void *pBuffer, size_t bufferLen, const char *) { QByteArray a = QByteArray::fromRawData((const char *)(pBuffer), (int)bufferLen); QBuffer b; b.setData(a); b.open(QIODevice::ReadOnly); QImageReader qImageReader(&b); QImage qImage(qImageReader.read()); if (qImage.isNull()) { epDebugPrintf("Error loading image -- %s\n", qImageReader.errorString().toUtf8().data()); return nullptr; } epImage *pOutput = (epImage*)epAlloc(sizeof(epImage) + sizeof(epImageSurface)); if (!pOutput) { epDebugPrintf("Error allocating epImage\n"); return nullptr; } pOutput->pSurfaces = (epImageSurface*)&pOutput[1]; pOutput->elements = 1; pOutput->mips = 1; pOutput->numMetadataEntries = 0; pOutput->pMetadata = nullptr; epImageFormat format = ConvertQTImageFormatToEP(qImage.format()); QImage convertedImage; QImage &resultImage = format == epIF_Unknown ? convertedImage : qImage; if (format == epIF_Unknown) { // TODO: ** Instead of converting we should load the image in it's raw format // HACK: we convert to ARGB32 for now convertedImage = qImage.convertToFormat(QImage::Format_ARGB32, Qt::ThresholdDither); // No dithering if (convertedImage.isNull()) { epFree(pOutput); epDebugPrintf("Error converting image to BGRA32 format\n"); return nullptr; } format = epIF_BGRA8; } epImageSurface &surface = pOutput->pSurfaces[0]; surface.width = resultImage.width(); surface.height = resultImage.height(); surface.depth = 0; surface.format = format; surface.pImage = epAlloc(surface.width * surface.height * 4); if (!surface.pImage) { epFree(pOutput); epDebugPrintf("Error allocating epImage surface\n"); return nullptr; } const uchar *qImageBuffer = resultImage.bits(); memcpy(surface.pImage, qImageBuffer, surface.width * surface.height * 4); return pOutput; } void epImage_DestroyImage(epImage **ppImage) { if (ppImage && *ppImage) { for (size_t i = 0; i < (*ppImage)->elements; ++i) epFree((*ppImage)->pSurfaces[i].pImage); epFree(*ppImage); *ppImage = nullptr; } } void* epImage_WriteImage(epImage epUnusedParam(*pImage), const char epUnusedParam(*pFileExt), size_t epUnusedParam(*pOutputSize)) { return nullptr; } #else EPEMPTYFILE #endif
24.688742
129
0.720225
Euclideon
71e29fe3e2fab124ea2d209703403d9144b07590
18,789
cpp
C++
Src/media/NiceConnection.cpp
MrsZ/licode-windows
578a779ddd200a7dbf5e84e0b5b0376c0c39827a
[ "MIT" ]
60
2018-10-23T02:41:46.000Z
2022-03-16T07:40:52.000Z
Src/media/NiceConnection.cpp
gupar/licode-windows
578a779ddd200a7dbf5e84e0b5b0376c0c39827a
[ "MIT" ]
3
2018-10-25T11:10:06.000Z
2020-11-29T09:47:05.000Z
Src/media/NiceConnection.cpp
gupar/licode-windows
578a779ddd200a7dbf5e84e0b5b0376c0c39827a
[ "MIT" ]
46
2018-10-29T06:56:03.000Z
2022-02-18T07:07:17.000Z
/* * NiceConnection.cpp */ #include <nice/nice.h> #include <cstdio> #include <string> #include <cstring> #include <vector> #include "NiceConnection.h" #include "SdpInfo.h" using std::memcpy; // If true (and configured properly below) erizo will generate relay candidates for itself // MOSTLY USEFUL WHEN ERIZO ITSELF IS BEHIND A NAT #define SERVER_SIDE_TURN 0 namespace erizo { DEFINE_LOGGER(NiceConnection, "NiceConnection") void cb_nice_recv(NiceAgent* agent, guint stream_id, guint component_id, guint len, gchar* buf, gpointer user_data) { if (user_data == NULL || len == 0) { return; } NiceConnection* nicecon = reinterpret_cast<NiceConnection*>(user_data); nicecon->queueData(component_id, reinterpret_cast<char*> (buf), static_cast<unsigned int> (len)); } void cb_new_candidate(NiceAgent *agent, guint stream_id, guint component_id, gchar *foundation, gpointer user_data) { NiceConnection *conn = reinterpret_cast<NiceConnection*>(user_data); std::string found(foundation); conn->getCandidate(stream_id, component_id, found); } void cb_candidate_gathering_done(NiceAgent *agent, guint stream_id, gpointer user_data) { NiceConnection *conn = reinterpret_cast<NiceConnection*>(user_data); conn->gatheringDone(stream_id); } void cb_component_state_changed(NiceAgent *agent, guint stream_id, guint component_id, guint state, gpointer user_data) { if (state == NICE_COMPONENT_STATE_CONNECTED) { } else if (state == NICE_COMPONENT_STATE_FAILED) { NiceConnection *conn = reinterpret_cast<NiceConnection*>(user_data); conn->updateComponentState(component_id, NICE_FAILED); } } void cb_new_selected_pair(NiceAgent *agent, guint stream_id, guint component_id, gchar *lfoundation, gchar *rfoundation, gpointer user_data) { NiceConnection *conn = reinterpret_cast<NiceConnection*>(user_data); conn->updateComponentState(component_id, NICE_READY); } NiceConnection::NiceConnection(MediaType med, const std::string &transport_name, const std::string& connection_id, NiceConnectionListener* listener, unsigned int iceComponents, const IceConfig& iceConfig, std::string username, std::string password) : mediaType(med), connection_id_(connection_id), agent_(NULL), loop_(NULL), listener_(listener), candsDelivered_(0), iceState_(NICE_INITIAL), iceComponents_(iceComponents), username_(username), password_(password), iceConfig_(iceConfig), receivedLastCandidate_(false) { localCandidates.reset(new std::vector<CandidateInfo>()); transportName.reset(new std::string(transport_name)); for (unsigned int i = 1; i <= iceComponents_; i++) { comp_state_list_[i] = NICE_INITIAL; } g_type_init(); } NiceConnection::~NiceConnection() { ELOG_DEBUG("%s, message: destroying", toLog()); this->close(); ELOG_DEBUG("%s, message: destroyed", toLog()); } packetPtr NiceConnection::getPacket() { cCSLock Lock(queueMutex_); while (niceQueue_.empty()) { cCSUnlock Unlock(Lock); cond_.Wait(); if (this->checkIceState() >= NICE_FINISHED) { ELOG_DEBUG("%s, message: finished in getPacket thread", toLog()); packetPtr p(new dataPacket()); p->length = -1; return p; } } packetPtr p(niceQueue_.front()); niceQueue_.pop(); Lock.Unlock(); return p; } void NiceConnection::close() { cCSLock Lock(closeMutex_); if (this->checkIceState() == NICE_FINISHED) { return; } ELOG_DEBUG("%s, message:closing", toLog()); this->updateIceState(NICE_FINISHED); if (loop_ != NULL) { g_main_loop_quit(loop_); } if (loop_ != NULL) { ELOG_DEBUG("%s, message:Unrefing loop", toLog()); g_main_loop_unref(loop_); loop_ = NULL; } cond_.Set(); listener_ = NULL; m_Thread_.join(); if (agent_ != NULL) { ELOG_DEBUG("%s, message: unrefing agent", toLog()); g_object_unref(agent_); agent_ = NULL; } if (context_ != NULL) { ELOG_DEBUG("%s, message: Unrefing context", toLog()); g_main_context_unref(context_); context_ = NULL; } ELOG_DEBUG("%s, message: closed, this: %p", toLog(), this); } void NiceConnection::queueData(unsigned int component_id, char* buf, int len) { if (this->checkIceState() == NICE_READY) { cCSLock Lock(queueMutex_); if (niceQueue_.size() < 1000) { packetPtr p_(new dataPacket()); memcpy(p_->data, buf, len); p_->comp = component_id; p_->length = len; niceQueue_.push(p_); cond_.Set(); } } } int NiceConnection::sendData(unsigned int compId, const void* buf, int len) { int val = -1; if (this->checkIceState() == NICE_READY) { val = nice_agent_send(agent_, 1, compId, len, reinterpret_cast<const gchar*>(buf)); } if (val != len) { ELOG_DEBUG("%s, message: Sending less data than expected, sent: %d, to_send: %d", toLog(), val, len); } return val; } void NiceConnection::start() { cCSLock Lock(closeMutex_); if (this->checkIceState() != NICE_INITIAL) { return; } context_ = g_main_context_new(); ELOG_DEBUG("%s, message: creating Nice Agent", toLog()); //nice_debug_enable(FALSE); nice_debug_disable(true); // Create a nice agent agent_ = nice_agent_new(context_, NICE_COMPATIBILITY_RFC5245); loop_ = g_main_loop_new(context_, FALSE); m_Thread_ = std::thread(&NiceConnection::mainLoop, this); GValue controllingMode = { 0 }; g_value_init(&controllingMode, G_TYPE_BOOLEAN); g_value_set_boolean(&controllingMode, false); g_object_set_property(G_OBJECT(agent_), "controlling-mode", &controllingMode); GValue checks = { 0 }; g_value_init(&checks, G_TYPE_UINT); g_value_set_uint(&checks, 100); g_object_set_property(G_OBJECT(agent_), "max-connectivity-checks", &checks); if (iceConfig_.stunServer.compare("") != 0 && iceConfig_.stunPort != 0) { GValue val = { 0 }, val2 = { 0 }; g_value_init(&val, G_TYPE_STRING); g_value_set_string(&val, iceConfig_.stunServer.c_str()); g_object_set_property(G_OBJECT(agent_), "stun-server", &val); g_value_init(&val2, G_TYPE_UINT); g_value_set_uint(&val2, iceConfig_.stunPort); g_object_set_property(G_OBJECT(agent_), "stun-server-port", &val2); ELOG_DEBUG("%s, message:setting stun, stunServer: %s, stunPort: %d", toLog(), iceConfig_.stunServer.c_str(), iceConfig_.stunPort); } // Connect the signals g_signal_connect(G_OBJECT(agent_), "candidate-gathering-done", G_CALLBACK(cb_candidate_gathering_done), this); g_signal_connect(G_OBJECT(agent_), "component-state-changed", G_CALLBACK(cb_component_state_changed), this); g_signal_connect(G_OBJECT(agent_), "new-selected-pair", G_CALLBACK(cb_new_selected_pair), this); g_signal_connect(G_OBJECT(agent_), "new-candidate", G_CALLBACK(cb_new_candidate), this); // Create a new stream and start gathering candidates ELOG_DEBUG("%s, message: adding stream, iceComponents: %d", toLog(), iceComponents_); nice_agent_add_stream(agent_, iceComponents_); gchar *ufrag = NULL, *upass = NULL; nice_agent_get_local_credentials(agent_, 1, &ufrag, &upass); ufrag_ = std::string(ufrag); g_free(ufrag); upass_ = std::string(upass); g_free(upass); // Set our remote credentials. This must be done *after* we add a stream. if (username_.compare("") != 0 && password_.compare("") != 0) { ELOG_DEBUG("%s, message: setting remote credentials in constructor, ufrag:%s, pass:%s", toLog(), username_.c_str(), password_.c_str()); this->setRemoteCredentials(username_, password_); } // Set Port Range: If this doesn't work when linking the file libnice.sym has to be modified to include this call if (iceConfig_.minPort != 0 && iceConfig_.maxPort != 0) { ELOG_DEBUG("%s, message: setting port range, minPort: %d, maxPort: %d", toLog(), iceConfig_.minPort, iceConfig_.maxPort); nice_agent_set_port_range(agent_, (guint)1, (guint)1, (guint)iceConfig_.minPort, (guint)iceConfig_.maxPort); } if (iceConfig_.turnServer.compare("") != 0 && iceConfig_.turnPort != 0) { ELOG_DEBUG("%s, message: configuring TURN, turnServer: %s , turnPort: %d, turnUsername: %s, turnPass: %s", toLog(), iceConfig_.turnServer.c_str(), iceConfig_.turnPort, iceConfig_.turnUsername.c_str(), iceConfig_.turnPass.c_str()); for (unsigned int i = 1; i <= iceComponents_ ; i++) { nice_agent_set_relay_info(agent_, 1, i, iceConfig_.turnServer.c_str(), // TURN Server IP iceConfig_.turnPort, // TURN Server PORT iceConfig_.turnUsername.c_str(), // Username iceConfig_.turnPass.c_str(), // Pass NICE_RELAY_TYPE_TURN_UDP); } } if (agent_) { for (unsigned int i = 1; i <= iceComponents_; i++) { nice_agent_attach_recv(agent_, 1, i, context_, cb_nice_recv, this); } } ELOG_DEBUG("%s, message: gathering, this: %p", toLog(), this); nice_agent_gather_candidates(agent_, 1); } void NiceConnection::mainLoop() { // Start gathering candidates and fire event loop ELOG_DEBUG("%s, message: starting g_main_loop, this: %p", toLog(), this); if (agent_ == NULL) { return; } g_main_loop_run(loop_); ELOG_DEBUG("%s, message: finished g_main_loop, this: %p", toLog(), this); } bool NiceConnection::setRemoteCandidates(const std::vector<CandidateInfo> &candidates, bool isBundle) { if (agent_ == NULL) { this->close(); return false; } GSList* candList = NULL; ELOG_DEBUG("%s, message: setting remote candidates, candidateSize: %lu, mediaType: %d", toLog(), candidates.size(), this->mediaType); for (unsigned int it = 0; it < candidates.size(); it++) { NiceCandidateType nice_cand_type; CandidateInfo cinfo = candidates[it]; // If bundle we will add the candidates regardless the mediaType if (cinfo.componentId != 1 || (!isBundle && cinfo.mediaType != this->mediaType )) continue; switch (cinfo.hostType) { case HOST: nice_cand_type = NICE_CANDIDATE_TYPE_HOST; break; case SRFLX: nice_cand_type = NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE; break; case PRFLX: nice_cand_type = NICE_CANDIDATE_TYPE_PEER_REFLEXIVE; break; case RELAY: nice_cand_type = NICE_CANDIDATE_TYPE_RELAYED; break; default: nice_cand_type = NICE_CANDIDATE_TYPE_HOST; break; } if (cinfo.hostPort == 0) { continue; } NiceCandidate* thecandidate = nice_candidate_new(nice_cand_type); thecandidate->username = strdup(cinfo.username.c_str()); thecandidate->password = strdup(cinfo.password.c_str()); thecandidate->stream_id = (guint) 1; thecandidate->component_id = cinfo.componentId; thecandidate->priority = cinfo.priority; thecandidate->transport = NICE_CANDIDATE_TRANSPORT_UDP; nice_address_set_from_string(&thecandidate->addr, cinfo.hostAddress.c_str()); nice_address_set_port(&thecandidate->addr, cinfo.hostPort); std::ostringstream host_info; host_info << "hostType: " << cinfo.hostType << ", hostAddress: " << cinfo.hostAddress << ", hostPort: " << cinfo.hostPort; if (cinfo.hostType == RELAY || cinfo.hostType == SRFLX) { nice_address_set_from_string(&thecandidate->base_addr, cinfo.rAddress.c_str()); nice_address_set_port(&thecandidate->base_addr, cinfo.rPort); ELOG_DEBUG("%s, message: adding relay or srflx remote candidate, %s, rAddress: %s, rPort: %d", toLog(), host_info.str().c_str(), cinfo.rAddress.c_str(), cinfo.rPort); } else { ELOG_DEBUG("%s, message: adding remote candidate, %s, priority: %d, componentId: %d, ufrag: %s, pass: %s", toLog(), host_info.str().c_str(), cinfo.priority, cinfo.componentId, cinfo.username.c_str(), cinfo.password.c_str()); } candList = g_slist_prepend(candList, thecandidate); } // TODO(pedro): Set Component Id properly, now fixed at 1 nice_agent_set_remote_candidates(agent_, (guint) 1, 1, candList); #ifndef _DEBUG g_slist_free_full(candList, (GDestroyNotify)&nice_candidate_free); #endif // _DEBUG return true; } void NiceConnection::gatheringDone(uint stream_id) { ELOG_DEBUG("%s, message: gathering done, stream_id: %u", toLog(), stream_id); this->updateIceState(NICE_CANDIDATES_RECEIVED); } void NiceConnection::getCandidate(uint stream_id, uint component_id, const std::string &foundation) { GSList* lcands = nice_agent_get_local_candidates(agent_, stream_id, component_id); // We only want to get the new candidates if (candsDelivered_ <= g_slist_length(lcands)) { lcands = g_slist_nth(lcands, (candsDelivered_)); } for (GSList* iterator = lcands; iterator; iterator = iterator->next) { char address[NICE_ADDRESS_STRING_LEN], baseAddress[NICE_ADDRESS_STRING_LEN]; NiceCandidate *cand = reinterpret_cast<NiceCandidate*>(iterator->data); nice_address_to_string(&cand->addr, address); nice_address_to_string(&cand->base_addr, baseAddress); candsDelivered_++; if (strstr(address, ":") != NULL) { // We ignore IPv6 candidates at this point continue; } CandidateInfo cand_info; cand_info.componentId = cand->component_id; cand_info.foundation = cand->foundation; cand_info.priority = cand->priority; cand_info.hostAddress = std::string(address); cand_info.hostPort = nice_address_get_port(&cand->addr); cand_info.mediaType = mediaType; /* * NICE_CANDIDATE_TYPE_HOST, * NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE, * NICE_CANDIDATE_TYPE_PEER_REFLEXIVE, * NICE_CANDIDATE_TYPE_RELAYED, */ switch (cand->type) { case NICE_CANDIDATE_TYPE_HOST: cand_info.hostType = HOST; break; case NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE: cand_info.hostType = SRFLX; cand_info.rAddress = std::string(baseAddress); cand_info.rPort = nice_address_get_port(&cand->base_addr); break; case NICE_CANDIDATE_TYPE_PEER_REFLEXIVE: cand_info.hostType = PRFLX; break; case NICE_CANDIDATE_TYPE_RELAYED: char turnAddres[NICE_ADDRESS_STRING_LEN]; nice_address_to_string(&cand->turn->server, turnAddres); cand_info.hostType = RELAY; cand_info.rAddress = std::string(baseAddress); cand_info.rPort = nice_address_get_port(&cand->base_addr); break; default: break; } cand_info.netProtocol = "udp"; cand_info.transProtocol = std::string(*transportName.get()); cand_info.username = ufrag_; cand_info.password = upass_; // localCandidates->push_back(cand_info); if (this->getNiceListener() != NULL) this->getNiceListener()->onCandidate(cand_info, this); } // for nice_agent_get_local_candidates, the caller owns the returned GSList as well as the candidates // contained within it. // let's free everything in the list, as well as the list. g_slist_free_full(lcands, (GDestroyNotify)&nice_candidate_free); } void NiceConnection::setRemoteCredentials(const std::string& username, const std::string& password) { ELOG_DEBUG("%s, message: setting remote credentials, ufrag: %s, pass: %s", toLog(), username.c_str(), password.c_str()); nice_agent_set_remote_credentials(agent_, (guint) 1, username.c_str(), password.c_str()); } void NiceConnection::setNiceListener(NiceConnectionListener *listener) { this->listener_ = listener; } NiceConnectionListener* NiceConnection::getNiceListener() { return this->listener_; } void NiceConnection::updateComponentState(unsigned int compId, IceState state) { ELOG_DEBUG("%s, message: new ice component state, newState: %u, transportName: %s, componentId %u, iceComponents: %u", toLog(), state, transportName->c_str(), compId, iceComponents_); comp_state_list_[compId] = state; if (state == NICE_READY) { for (unsigned int i = 1; i <= iceComponents_; i++) { if (comp_state_list_[i] != NICE_READY) { return; } } } else if (state == NICE_FAILED) { if (receivedLastCandidate_) { ELOG_WARN("%s, message: component failed, transportName: %s, componentId: %u", toLog(), transportName->c_str(), compId); for (unsigned int i = 1; i <= iceComponents_; i++) { if (comp_state_list_[i] != NICE_FAILED) { return; } } } else { ELOG_WARN("%s, message: failed and not received all candidates, newComponentState:%u", toLog(), state); return; } } this->updateIceState(state); } IceState NiceConnection::checkIceState() { return iceState_; } void NiceConnection::updateIceState(IceState state) { if (state <= iceState_) { if (state != NICE_READY) ELOG_WARN("%s, message: unexpected ice state transition, iceState:%u, newIceState: %u", toLog(), iceState_, state); return; } ELOG_INFO("%s, message: iceState transition, transportName: %s, iceState: %u, newIceState: %u, this: %p", toLog(), transportName->c_str(), this->iceState_, state, this); this->iceState_ = state; switch (iceState_) { case NICE_FINISHED: return; case NICE_FAILED: ELOG_WARN("%s, message: Ice Failed", toLog()); break; case NICE_READY: case NICE_CANDIDATES_RECEIVED: break; default: break; } // Important: send this outside our state lock. Otherwise, serious risk of deadlock. if (this->listener_ != NULL) this->listener_->updateIceState(state, this); } CandidatePair NiceConnection::getSelectedPair() { char ipaddr[NICE_ADDRESS_STRING_LEN]; CandidatePair selectedPair; NiceCandidate* local, *remote; nice_agent_get_selected_pair(agent_, 1, 1, &local, &remote); nice_address_to_string(&local->addr, ipaddr); selectedPair.erizoCandidateIp = std::string(ipaddr); selectedPair.erizoCandidatePort = nice_address_get_port(&local->addr); ELOG_DEBUG("%s, message: selected pair, local_addr: %s, local_port: %d", toLog(), ipaddr, nice_address_get_port(&local->addr)); nice_address_to_string(&remote->addr, ipaddr); selectedPair.clientCandidateIp = std::string(ipaddr); selectedPair.clientCandidatePort = nice_address_get_port(&remote->addr); ELOG_INFO("%s, message: selected pair, remote_addr: %s, remote_port: %d", toLog(), ipaddr, nice_address_get_port(&remote->addr)); return selectedPair; } void NiceConnection::setReceivedLastCandidate(bool hasReceived) { ELOG_DEBUG("%s, message: setting hasReceivedLastCandidate, hasReceived: %u", toLog(), hasReceived); this->receivedLastCandidate_ = hasReceived; } } /* namespace erizo */
35.788571
120
0.685295
MrsZ
71e57b19baa1edddba9318d621d4734802662534
126
cpp
C++
src/file/file_system.cpp
clems4ever/myos
de1e05813ccc004e57ccc1727f41d65e844e7778
[ "MIT" ]
null
null
null
src/file/file_system.cpp
clems4ever/myos
de1e05813ccc004e57ccc1727f41d65e844e7778
[ "MIT" ]
null
null
null
src/file/file_system.cpp
clems4ever/myos
de1e05813ccc004e57ccc1727f41d65e844e7778
[ "MIT" ]
1
2020-02-25T17:04:12.000Z
2020-02-25T17:04:12.000Z
#include "file_system.h" void FileSystem::openFile(int id) { return; } void FileSystem::closeFile(int id) { return; }
7.875
34
0.68254
clems4ever
71e970b0385ff64f7666f9465940bafa94fa4c05
3,391
cpp
C++
questions/ui-process-update-31012449/main.cpp
SammyEnigma/stackoverflown
0f70f2534918b2e65cec1046699573091d9a40b5
[ "Unlicense" ]
54
2015-09-13T07:29:52.000Z
2022-03-16T07:43:50.000Z
questions/ui-process-update-31012449/main.cpp
SammyEnigma/stackoverflown
0f70f2534918b2e65cec1046699573091d9a40b5
[ "Unlicense" ]
null
null
null
questions/ui-process-update-31012449/main.cpp
SammyEnigma/stackoverflown
0f70f2534918b2e65cec1046699573091d9a40b5
[ "Unlicense" ]
31
2016-08-26T13:35:01.000Z
2022-03-13T16:43:12.000Z
#if 1 #include <QApplication> #include <QGridLayout> #include <QProcess> #include <QLabel> #include <QTimer> #include <QTextStream> #include <QRegExp> #include <cstdio> // QT 5, C++11 int main(int argc, char *argv[]) { if (argc > 1) { QCoreApplication app(argc, argv); // output 3 random values per line at ~20Hz QTextStream out(stdout); QTimer timer; timer.start(50); QObject::connect(&timer, &QTimer::timeout, [&out]{ out << qrand() << " " << qrand() << " " << qrand() << endl; }); return app.exec(); } QApplication app(argc, argv); QWidget w; QGridLayout layout(&w); QLabel l1, l2, l3; layout.addWidget(&l1, 0, 0); layout.addWidget(&l2, 0, 1); layout.addWidget(&l3, 0, 2); QProcess process; process.start(QCoreApplication::applicationFilePath(), QStringList("foo")); QObject::connect(&process, &QProcess::readyRead, [&]{ static QRegExp sep("\\W+"); while (process.canReadLine()) { QStringList data = QString::fromLocal8Bit(process.readLine()).split(sep, QString::SkipEmptyParts); if (data.length() != 3) continue; l1.setText(data.at(0)); l2.setText(data.at(1)); l3.setText(data.at(2)); } }); app.setQuitOnLastWindowClosed(false); process.connect(&app, SIGNAL(lastWindowClosed()), SLOT(terminate())); app.connect(&process, SIGNAL(finished(int)), SLOT(quit())); w.show(); return app.exec(); } #endif #if 0 #include <QApplication> #include <QGridLayout> #include <QProcess> #include <QLabel> #include <QTimer> #include <QTextStream> #include <QRegExp> #include <QPointer> #include <cstdio> // QT 4, C++98 class Emulator : public QObject { Q_OBJECT QTextStream m_out; QTimer m_timer; Q_SLOT void on_timeout() { m_out << qrand() << " " << qrand() << " " << qrand() << endl; } public: Emulator() : m_out(stdout) { m_timer.start(50); connect(&m_timer, SIGNAL(timeout()), SLOT(on_timeout())); } }; class Widget : public QWidget { Q_OBJECT QGridLayout m_layout; QLabel m_l1, m_l2, m_l3; QPointer<QProcess> m_process; Q_SLOT void on_readyRead() { static QRegExp sep("\\W+"); while (m_process->canReadLine()) { QStringList data = QString::fromLocal8Bit(m_process->readLine()).split(sep, QString::SkipEmptyParts); if (data.length() != 3) continue; m_l1.setText(data.at(0)); m_l2.setText(data.at(1)); m_l3.setText(data.at(2)); } } public: Widget(QProcess * process) : m_layout(this), m_process(process) { m_layout.addWidget(&m_l1, 0, 0); m_layout.addWidget(&m_l2, 0, 1); m_layout.addWidget(&m_l3, 0, 2); connect(m_process, SIGNAL(readyRead()), SLOT(on_readyRead())); } }; int main(int argc, char *argv[]) { if (argc > 1) { // output 3 random values per line at ~20Hz QCoreApplication app(argc, argv); Emulator emulator; return app.exec(); } QApplication app(argc, argv); QProcess process; Widget w(&process); process.start(QCoreApplication::applicationFilePath(), QStringList("foo")); app.setQuitOnLastWindowClosed(false); process.connect(&app, SIGNAL(lastWindowClosed()), SLOT(terminate())); app.connect(&process, SIGNAL(finished(int)), SLOT(quit())); w.show(); return app.exec(); } #include "main.moc" #endif
26.912698
110
0.624005
SammyEnigma
71efeb962cdec0a3b8a8e5b183162b74971fbcea
558
cpp
C++
qir/qat/Rules/Patterns/AnyPattern.cpp
troelsfr/qat
55ba460b6be307fc2ac7e8143bf14d7e117da161
[ "MIT" ]
null
null
null
qir/qat/Rules/Patterns/AnyPattern.cpp
troelsfr/qat
55ba460b6be307fc2ac7e8143bf14d7e117da161
[ "MIT" ]
null
null
null
qir/qat/Rules/Patterns/AnyPattern.cpp
troelsfr/qat
55ba460b6be307fc2ac7e8143bf14d7e117da161
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "Rules/IOperandPrototype.hpp" #include "Rules/Patterns/AnyPattern.hpp" namespace microsoft { namespace quantum { AnyPattern::AnyPattern() = default; AnyPattern::~AnyPattern() = default; bool AnyPattern::match(Value* instr, Captures& captures) const { return success(instr, captures); } AnyPattern::Child AnyPattern::copy() const { return std::make_shared<AnyPattern>(); } } // namespace quantum } // namespace microsoft
21.461538
66
0.68638
troelsfr
71f0a2f96e955c70479d6ea2c73fe6650449df67
3,076
cpp
C++
Code/System/Core/FileSystem/Platform/FileSystem_Win32.cpp
JuanluMorales/KRG
f3a11de469586a4ef0db835af4bc4589e6b70779
[ "MIT" ]
419
2022-01-27T19:37:43.000Z
2022-03-31T06:14:22.000Z
Code/System/Core/FileSystem/Platform/FileSystem_Win32.cpp
jagt/KRG
ba20cd8798997b0450491b0cc04dc817c4a4bc76
[ "MIT" ]
2
2022-01-28T20:35:33.000Z
2022-03-13T17:42:52.000Z
Code/System/Core/FileSystem/Platform/FileSystem_Win32.cpp
jagt/KRG
ba20cd8798997b0450491b0cc04dc817c4a4bc76
[ "MIT" ]
20
2022-01-27T20:41:02.000Z
2022-03-26T16:16:57.000Z
#ifdef _WIN32 #include "../FileSystem.h" #include "System/Core/Platform/PlatformHelpers_Win32.h" #include "System/Core/Algorithm/Hash.h" #include "System/Core/Math/Math.h" #include <windows.h> #include <shlwapi.h> #include <shlobj.h> #include <shellapi.h> #include <fstream> #include "../Time/Timers.h" #include "../Logging/Log.h" //------------------------------------------------------------------------- namespace KRG::FileSystem { char const Path::s_pathDelimiter = '\\'; //------------------------------------------------------------------------- String Path::GetFullPathString( char const* pPath ) { char fullpath[256] = { 0 }; if ( pPath != nullptr && pPath[0] != 0 ) { // Warning: this function is slow, so use sparingly DWORD length = GetFullPathNameA( pPath, 256, fullpath, nullptr ); KRG_ASSERT( length != 0 && length != 255 ); // Ensure directory paths have the final slash appended DWORD const result = GetFileAttributesA( fullpath ); if ( result != INVALID_FILE_ATTRIBUTES && ( result & FILE_ATTRIBUTE_DIRECTORY ) && fullpath[length - 1] != Path::s_pathDelimiter ) { fullpath[length] = Path::s_pathDelimiter; fullpath[length + 1] = 0; } } return String( fullpath ); } //------------------------------------------------------------------------- Path GetCurrentProcessPath() { return Path( Platform::Win32::GetCurrentModulePath() ).GetParentDirectory(); } //------------------------------------------------------------------------- bool LoadFile( Path const& path, TVector<Byte>& fileData ) { KRG_ASSERT( path.IsFile() ); // Open file handle HANDLE hFile = CreateFile( path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr ); if ( hFile == INVALID_HANDLE_VALUE ) { return false; } // Get file size LARGE_INTEGER fileSizeLI; if ( !GetFileSizeEx( hFile, &fileSizeLI ) ) { CloseHandle( hFile ); return false; } // Allocate destination memory size_t const fileSize = (size_t) ( fileSizeLI.QuadPart ); fileData.resize( fileSize ); // Read file static constexpr DWORD const defaultReadBufferSize = 65536; DWORD bytesRead = 0; DWORD remainingBytesToRead = (DWORD) fileSize; Byte* pBuffer = fileData.data(); while ( remainingBytesToRead != 0 ) { DWORD const numBytesToRead = Math::Min( defaultReadBufferSize, remainingBytesToRead ); ReadFile( hFile, pBuffer, numBytesToRead, &bytesRead, nullptr ); pBuffer += bytesRead; remainingBytesToRead -= bytesRead; } CloseHandle( hFile ); return true; } } #endif
31.71134
143
0.516255
JuanluMorales
71f37e064e4f31b9d0fed5724c98725d1715ef6f
2,894
hpp
C++
include/nexus/quic/detail/connection_impl.hpp
cbodley/nexus
6e5b19b6c6c74007a0643c55eb0775eb86e38f9b
[ "BSL-1.0" ]
6
2021-10-31T10:33:30.000Z
2022-03-25T20:54:58.000Z
include/nexus/quic/detail/connection_impl.hpp
cbodley/nexus
6e5b19b6c6c74007a0643c55eb0775eb86e38f9b
[ "BSL-1.0" ]
null
null
null
include/nexus/quic/detail/connection_impl.hpp
cbodley/nexus
6e5b19b6c6c74007a0643c55eb0775eb86e38f9b
[ "BSL-1.0" ]
null
null
null
#pragma once #include <boost/intrusive/list.hpp> #include <nexus/quic/detail/connection_state.hpp> #include <nexus/quic/detail/service.hpp> #include <nexus/quic/detail/stream_impl.hpp> #include <nexus/udp.hpp> struct lsquic_conn; struct lsquic_stream; namespace nexus::quic::detail { struct accept_operation; struct socket_impl; struct connection_impl : public connection_context, public boost::intrusive::list_base_hook<>, public service_list_base_hook { service<connection_impl>& svc; socket_impl& socket; connection_state::variant state; explicit connection_impl(socket_impl& socket); ~connection_impl(); void service_shutdown(); using executor_type = boost::asio::any_io_executor; executor_type get_executor() const; connection_id id(error_code& ec) const; udp::endpoint remote_endpoint(error_code& ec) const; void connect(stream_connect_operation& op); stream_impl* on_connect(lsquic_stream* stream); template <typename Stream, typename CompletionToken> decltype(auto) async_connect(Stream& stream, CompletionToken&& token) { auto& s = stream.impl; return boost::asio::async_initiate<CompletionToken, void(error_code)>( [this, &s] (auto h) { using Handler = std::decay_t<decltype(h)>; using op_type = stream_connect_async<Handler, executor_type>; auto p = handler_allocate<op_type>(h, std::move(h), get_executor(), s); auto op = handler_ptr<op_type, Handler>{p, &p->handler}; connect(*op); op.release(); // release ownership }, token); } void accept(stream_accept_operation& op); stream_impl* on_accept(lsquic_stream* stream); template <typename Stream, typename CompletionToken> decltype(auto) async_accept(Stream& stream, CompletionToken&& token) { auto& s = stream.impl; return boost::asio::async_initiate<CompletionToken, void(error_code)>( [this, &s] (auto h) { using Handler = std::decay_t<decltype(h)>; using op_type = stream_accept_async<Handler, executor_type>; auto p = handler_allocate<op_type>(h, std::move(h), get_executor(), s); auto op = handler_ptr<op_type, Handler>{p, &p->handler}; accept(*op); op.release(); // release ownership }, token); } bool is_open() const; void go_away(error_code& ec); void close(error_code& ec); void on_close(); void on_handshake(int status); void on_remote_goaway(); void on_remote_close(int app_error, uint64_t code); void on_incoming_stream_closed(stream_impl& s); void on_accepting_stream_closed(stream_impl& s); void on_connecting_stream_closed(stream_impl& s); void on_open_stream_closing(stream_impl& s); void on_open_stream_closed(stream_impl& s); void on_closing_stream_closed(stream_impl& s); }; } // namespace nexus::quic::detail
32.886364
81
0.701451
cbodley
71f582486aa97c49a2f0ffeb52f72f4fbc02860d
1,099
cpp
C++
oi/homework/2015-9-26/4-7/main.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
3
2018-08-30T09:43:20.000Z
2019-12-03T04:53:43.000Z
oi/homework/2015-9-26/4-7/main.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
null
null
null
oi/homework/2015-9-26/4-7/main.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
null
null
null
#include <iostream> #include <algorithm> #include <cmath> using namespace std; #define MAGIC_NUMBER 6174 void ReadDigits(int n,int digits[]){ for (int i=0; i<4; i++) { digits[i]=n%10; n/=10; } // for } int MakeMaxNumber(int digits[],int n){ int tmp=0; for (int i=n-1; i>=0; i--) { tmp*=10; if (digits[i]!=0) { tmp+=digits[i]; } } // for return tmp; } int MakeMinNumber(int digits[],int n){ int tmp=0; for (int i=0; i<n; i++) { tmp*=10; tmp+=digits[i]; } // for return tmp; } int main(int argc, char const *argv[]) { int n; cin>>n; if (int(log10(n))!=3 || n%1111==0) { cout<<"Input error"<<endl; return 0; } int cnt=0; int digits[4]; while (n!=MAGIC_NUMBER&&cnt<10) { ReadDigits(n,digits); std::sort(std::begin(digits),std::end(digits)); int maxN=MakeMaxNumber(digits,4); int minN=MakeMinNumber(digits,4); n=maxN-minN; cnt++; cout<<maxN<<" - "<<minN<<" = "<<n<<endl; } // while cout<<cnt<<endl; return 0; }
15.263889
50
0.517743
Riteme
71f65b43654fd22565096dbb1c2584d29ee356b3
104
hpp
C++
redvoid/src/Logger.hpp
fictionalist/RED-VOID
01bacd893f095748d784e494c80a6a9c96481acc
[ "MIT" ]
1
2021-01-04T01:31:34.000Z
2021-01-04T01:31:34.000Z
redvoid/src/Logger.hpp
fictionalist/RED-VOID
01bacd893f095748d784e494c80a6a9c96481acc
[ "MIT" ]
null
null
null
redvoid/src/Logger.hpp
fictionalist/RED-VOID
01bacd893f095748d784e494c80a6a9c96481acc
[ "MIT" ]
1
2021-01-05T00:55:47.000Z
2021-01-05T00:55:47.000Z
#pragma once #include <string> namespace Logger { bool init(); void log(std::string pattern, ...); }
13
36
0.663462
fictionalist
71fa3188959942010b1f365a7c1f2e06b69a368c
1,148
hpp
C++
graphExplorer/graphExplorer/lubySequence.hpp
fq00/lubySequenceEAs
6a107de687b3c2e159c8486ccc7eb02385c351c6
[ "MIT" ]
null
null
null
graphExplorer/graphExplorer/lubySequence.hpp
fq00/lubySequenceEAs
6a107de687b3c2e159c8486ccc7eb02385c351c6
[ "MIT" ]
null
null
null
graphExplorer/graphExplorer/lubySequence.hpp
fq00/lubySequenceEAs
6a107de687b3c2e159c8486ccc7eb02385c351c6
[ "MIT" ]
null
null
null
// // lubySequence.hpp // graphExplorer // // Created by Francesco Quinzan on 06.09.17. // Copyright © 2017 Francesco Quinzan. All rights reserved. // #ifndef lubySequence_hpp #define lubySequence_hpp #include <vector> #include <limits> #include <thread> #include "EA.hpp" using namespace std; /* overloaded vector to compute the sum */ class vec : public std::vector<unsigned long>{ public : unsigned long sum(){ unsigned long sum = 0; if(std::vector<unsigned long>::size() != 0){ for(unsigned long i = 0; i < std::vector<unsigned long>::size(); i++) sum = sum + std::vector<unsigned long>::at(i); } return sum; } }; class ls{ //public : /* variables for Luby sequence */ class EA * alg; unsigned long maxStep; class vec sequence; /* make actual Luby Sequence */ void makeSequence(); public: ls(class EA * EA, unsigned long maxStep){ ls::alg = EA; ls::maxStep = maxStep; ls::makeSequence(); } void run(std::vector<unsigned long> *); }; #endif /* lubySequence_hpp */
18.819672
81
0.587979
fq00
9f95c942849cae822a980f8e016e7fb0726c9233
2,903
cpp
C++
tests/world/test_terrain.cpp
Bycob/world
c6d943f9029c1bb227891507e5c6fe2b94cecfeb
[ "MIT" ]
16
2021-03-14T16:30:32.000Z
2022-03-18T13:41:53.000Z
tests/world/test_terrain.cpp
Tzian/world
3ebb33305acd2a751cf44099b07c1e5d47578194
[ "MIT" ]
1
2020-04-21T12:59:37.000Z
2020-04-23T17:49:03.000Z
tests/world/test_terrain.cpp
Tzian/world
3ebb33305acd2a751cf44099b07c1e5d47578194
[ "MIT" ]
4
2020-03-08T14:04:50.000Z
2020-12-03T08:51:04.000Z
#include <catch/catch.hpp> #include <world/core.h> #include <world/terrain.h> using namespace world; TEST_CASE("Terrain - getExactHeightAt", "[terrain]") { Terrain terrain(2); terrain(0, 0) = 1; terrain(0, 1) = 0; terrain(1, 0) = 0; terrain(1, 1) = 1; SECTION("getExactHeightAt trivial coordinates") { REQUIRE(terrain.getExactHeightAt(0, 0) == Approx(1)); REQUIRE(terrain.getExactHeightAt(0, 1) == Approx(0)); REQUIRE(terrain.getExactHeightAt(1, 0) == Approx(0)); REQUIRE(terrain.getExactHeightAt(1, 1) == Approx(1)); } SECTION("getExactHeightAt non trivial coordinates") { REQUIRE(terrain.getExactHeightAt(0.5, 0) == Approx(0.5)); REQUIRE(terrain.getExactHeightAt(0, 0.5) == Approx(0.5)); REQUIRE(terrain.getExactHeightAt(0.5, 1) == Approx(0.5)); REQUIRE(terrain.getExactHeightAt(1, 0.5) == Approx(0.5)); } terrain(0, 0) = 0.1; terrain(0, 1) = 0.4; terrain(1, 0) = 0.5; terrain(1, 1) = 0.7; SECTION("getExactHeightAt trivial coordinates, non trivial heights") { REQUIRE(terrain.getExactHeightAt(0, 0) == Approx(0.1)); REQUIRE(terrain.getExactHeightAt(0, 1) == Approx(0.4)); REQUIRE(terrain.getExactHeightAt(1, 0) == Approx(0.5)); REQUIRE(terrain.getExactHeightAt(1, 1) == Approx(0.7)); } SECTION("getExactHeightAt non trivial coordinates, non trivial heights") { std::stringstream str; for (double y = 1; y >= -0.02; y -= 0.05) { for (double x = 0; x <= 1.01; x += 0.05) { str << terrain.getExactHeightAt(x, y) << " "; } str << std::endl; } INFO(str.str()); REQUIRE(terrain.getExactHeightAt(0.5, 0) == Approx(0.3)); REQUIRE(terrain.getExactHeightAt(0, 0.5) == Approx(0.25)); REQUIRE(terrain.getExactHeightAt(0.5, 1) == Approx(0.55)); REQUIRE(terrain.getExactHeightAt(1, 0.5) == Approx(0.6)); } SECTION("Slope") { Terrain terrain2(3); terrain2.setBounds(0, 0, 0, 1, 1, 1); SECTION("X slope") { for (int x = 0; x < 3; ++x) { for (int y = 0; y < 3; ++y) { terrain2(x, y) = x / 2.; } } CHECK(terrain2.getSlope(1, 1) == Approx(1)); CHECK(terrain2.getSlope(0, 0) == Approx(1)); } SECTION("X Y slope") { for (int x = 0; x < 3; ++x) { for (int y = 0; y < 3; ++y) { terrain2(x, y) = (x + y) / 4.; } } CHECK(terrain2.getSlope(1, 1) == Approx(sqrt(2.) / 2.)); } } } TEST_CASE("Terrain - Mesh generation benchmark", "[terrain][!benchmark]") { Terrain terrain(129); BENCHMARK("Create a mesh") { Mesh *mesh = terrain.createMesh(); delete mesh; } }
31.554348
78
0.529452
Bycob
9f961d3d37347d99a083232bf2ce7b47d1265203
13,941
hpp
C++
tests/functional/coherence/util/ObservableMapTest.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-01T21:38:30.000Z
2021-11-03T01:35:11.000Z
tests/functional/coherence/util/ObservableMapTest.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
1
2020-07-24T17:29:22.000Z
2020-07-24T18:29:04.000Z
tests/functional/coherence/util/ObservableMapTest.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-10T18:40:58.000Z
2022-02-18T01:23:40.000Z
/* * Copyright (c) 2000, 2020, Oracle and/or its affiliates. * * Licensed under the Universal Permissive License v 1.0 as shown at * http://oss.oracle.com/licenses/upl. */ #include "cxxtest/TestSuite.h" #include "common/TestUtils.hpp" #include "mock/CommonMocks.hpp" #include "coherence/lang.ns" #include "coherence/net/NamedCache.hpp" #include "coherence/util/ArrayList.hpp" #include "coherence/util/Filter.hpp" #include "coherence/util/MapEvent.hpp" #include "coherence/util/MapListener.hpp" #include "coherence/util/filter/AlwaysFilter.hpp" #include "coherence/util/filter/NeverFilter.hpp" #include "coherence/util/ObservableMap.hpp" using coherence::net::NamedCache; using coherence::util::ArrayList; using coherence::util::Filter; using coherence::util::MapEvent; using coherence::util::MapListener; using coherence::util::ObservableMap; using coherence::util::filter::AlwaysFilter; using coherence::util::filter::NeverFilter; using namespace mock; using namespace std; namespace { bool matchListenerEvent(ArrayList::View vExpected, ArrayList::View vActual) { MapEvent::View vExpectedEvent = cast<MapEvent::View>(vExpected->get(0)); MapEvent::View vActualEvent = cast<MapEvent::View>(vActual->get(0)); // cout << "\n\n\n************************************************************\n\n\n"; // cout << vExpectedEvent->getKey() << " : " << vActualEvent->getKey() << endl; // cout << vExpectedEvent->getId() << " : " << vActualEvent->getId() << endl; // cout << vExpectedEvent->getOldValue() << " : " << vActualEvent->getOldValue() << endl; // cout << vExpectedEvent->getNewValue() << " : " << vActualEvent->getNewValue() << endl; // cout << vExpectedEvent->getMap() << " : " << vActualEvent->getMap() << endl; return Object::equals(vExpectedEvent->getKey(), vActualEvent->getKey()) && vExpectedEvent->getId() == vActualEvent->getId() && Object::equals(vExpectedEvent->getOldValue(), vActualEvent->getOldValue()) && Object::equals(vExpectedEvent->getNewValue(), vActualEvent->getNewValue()) && vExpectedEvent->getMap() == vActualEvent->getMap(); } } class ObservableMapTest : public CxxTest::TestSuite { public: void testKeyListener() { NamedCache::Handle hCache = ensureCleanCache("dist-observable-map"); // the mock which receives the events MockMapListener::Handle hMockListener = MockMapListener::create(); // the mock used in verifying the MapEvent which is passed to the listener MockMapEvent::Handle hMockMapEvent = MockMapEvent::create(); // map key Object::View vKey = String::create("key"); // values String::View vsInsertedVal = String::create("inserted-val"); String::View vsUpdatedVal = String::create("updated-val"); // set mock listener expectations hMockListener->setStrict(true); hMockListener->entryInserted(hMockMapEvent); // use an argument matcher to assert MapEvent state hMockListener->setMatcher(&matchListenerEvent); hMockListener->entryUpdated(hMockMapEvent); hMockListener->setMatcher(&matchListenerEvent); hMockListener->entryDeleted(hMockMapEvent); hMockListener->setMatcher(&matchListenerEvent); hMockListener->replay(); // setup mock for pattern matcher. hMockMapEvent->setStrict(true); // insert hMockMapEvent->getKey(); hMockMapEvent->setObjectReturn(vKey); hMockMapEvent->getId(); hMockMapEvent->setInt32Return(MapEvent::entry_inserted); hMockMapEvent->getOldValue(); hMockMapEvent->setObjectReturn(NULL); hMockMapEvent->getNewValue(); hMockMapEvent->setObjectReturn(vsInsertedVal); hMockMapEvent->getMap(); hMockMapEvent->setObjectReturn(hCache); // update hMockMapEvent->getKey(); hMockMapEvent->setObjectReturn(vKey); hMockMapEvent->getId(); hMockMapEvent->setInt32Return(MapEvent::entry_updated); hMockMapEvent->getOldValue(); hMockMapEvent->setObjectReturn(vsInsertedVal); hMockMapEvent->getNewValue(); hMockMapEvent->setObjectReturn(vsUpdatedVal); hMockMapEvent->getMap(); hMockMapEvent->setObjectReturn(hCache); //delete hMockMapEvent->getKey(); hMockMapEvent->setObjectReturn(vKey); hMockMapEvent->getId(); hMockMapEvent->setInt32Return(MapEvent::entry_deleted); hMockMapEvent->getOldValue(); hMockMapEvent->setObjectReturn(vsUpdatedVal); hMockMapEvent->getNewValue(); hMockMapEvent->setObjectReturn(NULL); hMockMapEvent->getMap(); hMockMapEvent->setObjectReturn(hCache); hMockMapEvent->replay(); hCache->addKeyListener(hMockListener, vKey, false); hCache->put(vKey, vsInsertedVal); hCache->put(vKey, vsUpdatedVal); hCache->remove(vKey); int64_t nInitialTime = System::currentTimeMillis(); bool fResult = false; while (!fResult && System::currentTimeMillis() - nInitialTime < 10000) { fResult = hMockListener->verifyAndReturnResult(); Thread::sleep(5); } // remove the listener and ensure that further events aren't received hCache->removeKeyListener(hMockListener, vKey); hCache->put(vKey, vsInsertedVal); hCache->put(vKey, vsUpdatedVal); hCache->remove(vKey); hMockListener->verify(); } void testFilterListenerNullFilter() { NamedCache::Handle hCache = ensureCleanCache("dist-observable-map"); // the mock which receives the events MockMapListener::Handle hMockListener = MockMapListener::create(); // the mock used in verifying the MapEvent which is passed to the listener MockMapEvent::Handle hMockMapEvent = MockMapEvent::create(); // map key Object::View vKey = String::create("key"); // values String::View vsInsertedVal = String::create("inserted-val"); String::View vsUpdatedVal = String::create("updated-val"); // set mock listener expectations hMockListener->setStrict(true); hMockListener->entryInserted(hMockMapEvent); // use an argument matcher to assert MapEvent state hMockListener->setMatcher(&matchListenerEvent); hMockListener->entryUpdated(hMockMapEvent); hMockListener->setMatcher(&matchListenerEvent); hMockListener->entryDeleted(hMockMapEvent); hMockListener->setMatcher(&matchListenerEvent); hMockListener->replay(); // setup mock for pattern matcher. hMockMapEvent->setStrict(true); // insert hMockMapEvent->getKey(); hMockMapEvent->setObjectReturn(vKey); hMockMapEvent->getId(); hMockMapEvent->setInt32Return(MapEvent::entry_inserted); hMockMapEvent->getOldValue(); hMockMapEvent->setObjectReturn(NULL); hMockMapEvent->getNewValue(); hMockMapEvent->setObjectReturn(vsInsertedVal); hMockMapEvent->getMap(); hMockMapEvent->setObjectReturn(hCache); // update hMockMapEvent->getKey(); hMockMapEvent->setObjectReturn(vKey); hMockMapEvent->getId(); hMockMapEvent->setInt32Return(MapEvent::entry_updated); hMockMapEvent->getOldValue(); hMockMapEvent->setObjectReturn(vsInsertedVal); hMockMapEvent->getNewValue(); hMockMapEvent->setObjectReturn(vsUpdatedVal); hMockMapEvent->getMap(); hMockMapEvent->setObjectReturn(hCache); //delete hMockMapEvent->getKey(); hMockMapEvent->setObjectReturn(vKey); hMockMapEvent->getId(); hMockMapEvent->setInt32Return(MapEvent::entry_deleted); hMockMapEvent->getOldValue(); hMockMapEvent->setObjectReturn(vsUpdatedVal); hMockMapEvent->getNewValue(); hMockMapEvent->setObjectReturn(NULL); hMockMapEvent->getMap(); hMockMapEvent->setObjectReturn(hCache); hMockMapEvent->replay(); hCache->addFilterListener(hMockListener); hCache->put(vKey, vsInsertedVal); hCache->put(vKey, vsUpdatedVal); hCache->remove(vKey); int64_t nInitialTime = System::currentTimeMillis(); bool fResult = false; while (!fResult && System::currentTimeMillis() - nInitialTime < 10000) { fResult = hMockListener->verifyAndReturnResult(); Thread::sleep(5); } // remove the listener and ensure that further events aren't received hCache->removeFilterListener(hMockListener); hCache->put(vKey, vsInsertedVal); hCache->put(vKey, vsUpdatedVal); hCache->remove(vKey); hMockListener->verify(); } void testFilterListener() { NamedCache::Handle hCache = ensureCleanCache("dist-observable-map"); // the mock which receives the events MockMapListener::Handle hMockListener = MockMapListener::create(); // the mock which shouldn't receive any events due to NeverFilter MockMapListener::Handle hMockNeverListener = MockMapListener::create(); // the mock used in verifying the MapEvent which is passed to the listener MockMapEvent::Handle hMockMapEvent = MockMapEvent::create(); // filter always evaluates to true Filter::View vAlwaysFilter = AlwaysFilter::create(); // filter always evaluates to false Filter::View vNeverFilter = NeverFilter::create(); // map key Object::View vKey = String::create("key"); // values String::View vsInsertedVal = String::create("inserted-val"); String::View vsUpdatedVal = String::create("updated-val"); // set mock listener expectations hMockListener->setStrict(true); hMockListener->entryInserted(hMockMapEvent); // use an argument matcher to assert MapEvent state hMockListener->setMatcher(&matchListenerEvent); hMockListener->entryUpdated(hMockMapEvent); hMockListener->setMatcher(&matchListenerEvent); hMockListener->entryDeleted(hMockMapEvent); hMockListener->setMatcher(&matchListenerEvent); hMockListener->replay(); // mock listener with NeverFilter hMockNeverListener->setStrict(true); hMockNeverListener->replay(); // setup mock for pattern matcher. hMockMapEvent->setStrict(true); // insert hMockMapEvent->getKey(); hMockMapEvent->setObjectReturn(vKey); hMockMapEvent->getId(); hMockMapEvent->setInt32Return(MapEvent::entry_inserted); hMockMapEvent->getOldValue(); hMockMapEvent->setObjectReturn(NULL); hMockMapEvent->getNewValue(); hMockMapEvent->setObjectReturn(vsInsertedVal); hMockMapEvent->getMap(); hMockMapEvent->setObjectReturn(hCache); // update hMockMapEvent->getKey(); hMockMapEvent->setObjectReturn(vKey); hMockMapEvent->getId(); hMockMapEvent->setInt32Return(MapEvent::entry_updated); hMockMapEvent->getOldValue(); hMockMapEvent->setObjectReturn(vsInsertedVal); hMockMapEvent->getNewValue(); hMockMapEvent->setObjectReturn(vsUpdatedVal); hMockMapEvent->getMap(); hMockMapEvent->setObjectReturn(hCache); //delete hMockMapEvent->getKey(); hMockMapEvent->setObjectReturn(vKey); hMockMapEvent->getId(); hMockMapEvent->setInt32Return(MapEvent::entry_deleted); hMockMapEvent->getOldValue(); hMockMapEvent->setObjectReturn(vsUpdatedVal); hMockMapEvent->getNewValue(); hMockMapEvent->setObjectReturn(NULL); hMockMapEvent->getMap(); hMockMapEvent->setObjectReturn(hCache); hMockMapEvent->replay(); hCache->addFilterListener(hMockListener, vAlwaysFilter); hCache->addFilterListener(hMockNeverListener, vNeverFilter); hCache->put(vKey, vsInsertedVal); hCache->put(vKey, vsUpdatedVal); hCache->remove(vKey); int64_t nInitialTime = System::currentTimeMillis(); bool fResult = false; while (!fResult && System::currentTimeMillis() - nInitialTime < 10000) { fResult = hMockListener->verifyAndReturnResult(); Thread::sleep(5); } // remove the listener and ensure that further events aren't received hCache->removeFilterListener(hMockListener, vAlwaysFilter); hCache->put(vKey, vsInsertedVal); hCache->put(vKey, vsUpdatedVal); hCache->remove(vKey); hMockListener->verify(); } };
42.895385
94
0.604476
chpatel3
9f9d603d223a3b2ba4227fcc361817e9598ffb05
3,001
hpp
C++
Support/Modules/Brep/NurbsFace.hpp
graphisoft-python/TextEngine
20c2ff53877b20fdfe2cd51ce7abdab1ff676a70
[ "Apache-2.0" ]
3
2019-07-15T10:54:54.000Z
2020-01-25T08:24:51.000Z
Support/Modules/Brep/NurbsFace.hpp
graphisoft-python/GSRoot
008fac2c6bf601ca96e7096705e25b10ba4d3e75
[ "Apache-2.0" ]
null
null
null
Support/Modules/Brep/NurbsFace.hpp
graphisoft-python/GSRoot
008fac2c6bf601ca96e7096705e25b10ba4d3e75
[ "Apache-2.0" ]
1
2020-09-26T03:17:22.000Z
2020-09-26T03:17:22.000Z
// ********************************************************************************************************************* // Data structure that represents one face of a NurbsBRep object. // // Note. All indices refer to containing NurbsBRep, starting from 0. // ********************************************************************************************************************* #if !defined(NURBSFACE_HPP) #define NURBSFACE_HPP #pragma once #include "BrepExport.hpp" // from GSRoot #include "Array.hpp" #include "ClassInfo.hpp" // from Brep #include "NurbsElementWithTolerance.hpp" namespace GS { class XMLIChannel; class XMLOChannel; } namespace Brep { class BREP_DLL_EXPORT NurbsFace : public NurbsElementWithToleranceTransform { // A face is a connected, finite part of a surface bounded by // * one outer loop and // * zero or more inner loops (separating the face from holes). // A face has an orientation, the surface normals of its surface point to the front side of the face // Neighbouring faces may have inconsistent orientation, their loop may refer to the common edge in the same direction. // In this case containing shell may refer these faces with different reversed flags. // Loop orientation is always determined on the face: // looking in the direction of the loop with face front side upwards the face inside is on the left private: static GS::ClassInfo classInfo; GS::Array<UInt32> loopIndices; // not empty, first is the outer loop Int32 shellIndex; // may be negative temporarily (uninitialized) or permanently (for lamina face) UInt32 surfaceIndex; // geometry of face is part of this surface // tolerance is not used in geometry checks void ReadVersion1 (GS::IChannel &ic); void WriteVersion1 (GS::OChannel &oc) const; public: NurbsFace (); NurbsFace (const GS::Array<UInt32>& loops, UInt32 surface, double tol); NurbsFace (const GS::Array<UInt32>& loops, Int32 shellIndex, UInt32 surface, double tol); NurbsFace (GS::XMLIChannel& inXML, const char* tagName) { ReadXML (inXML, tagName); } bool Equals (const NurbsFace& other) const; void AttachNurbsShell (UInt32 shellIndex); void DetachNurbsShell (); void Transform (const TRANMAT& tran); UInt32 GetSurfaceIndex () const { return surfaceIndex; } UInt32 GetLoopCount () const { return loopIndices.GetSize (); } UInt32 GetLoopIndex (UInt32 index) const { return loopIndices[index]; } const GS::Array<UInt32>& GetLoopIndices () const { return loopIndices; } Int32 GetShellIndex () const { return shellIndex; } ULong GetUsedBytes () const; ULong GetHeapUsedBytes () const; void Read (GS::IChannel& ic); void Write (GS::OChannel& oc) const; void WriteXML (GS::XMLOChannel& outXML, const char* tagName) const; void ReadXML (GS::XMLIChannel& inXML, const char* tagName); }; } // namespace Brep #endif // NURBSFACE_HPP
35.305882
120
0.64945
graphisoft-python
9f9f756378eafc8bf3696f73173f696477861477
11,741
cc
C++
common/src/LockOrderChecker.cc
liuxiang88/core-alljoyn
549c966482d9b89da84aa528117584e7049916cb
[ "Apache-2.0" ]
33
2018-01-12T00:37:43.000Z
2022-03-24T02:31:36.000Z
common/src/LockOrderChecker.cc
liuxiang88/core-alljoyn
549c966482d9b89da84aa528117584e7049916cb
[ "Apache-2.0" ]
1
2020-01-05T05:51:27.000Z
2020-01-05T05:51:27.000Z
common/src/LockOrderChecker.cc
liuxiang88/core-alljoyn
549c966482d9b89da84aa528117584e7049916cb
[ "Apache-2.0" ]
30
2017-12-13T23:24:00.000Z
2022-01-25T02:11:19.000Z
/** * @file * * Class implementing sanity checks for Mutex objects. */ /****************************************************************************** * Copyright (c) Open Connectivity Foundation (OCF), AllJoyn Open Source * Project (AJOSP) Contributors and others. * * SPDX-License-Identifier: Apache-2.0 * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution, and is available at * http://www.apache.org/licenses/LICENSE-2.0 * * Copyright (c) Open Connectivity Foundation and Contributors to AllSeen * Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for * any purpose with or without fee is hereby granted, provided that the * above copyright notice and this permission notice appear in all * copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. ******************************************************************************/ /* Lock verification is enabled just on Debug builds */ #ifndef NDEBUG #include <qcc/Debug.h> #include <qcc/MutexInternal.h> #include <qcc/LockLevel.h> #include <qcc/LockOrderChecker.h> #define QCC_MODULE "MUTEX" namespace qcc { /* * Default number of LockTrace objects allocated for each thread. Additional LockTrace * objects get allocated automatically if a thread acquires even more locks. */ const uint32_t LockOrderChecker::defaultMaximumStackDepth = 4; /* * LOCKORDERCHECKER_OPTION_MISSING_LEVEL_ASSERT is disabled by default because * specifying lock level values from apps is not supported, but some of these * apps acquire their own locks during listener callbacks. Listener callbacks * commonly get called while owning one or more SCL locks. * * Another example of problematic MISSING_LEVEL_ASSERT behavior is: timer * callbacks get called with the reentrancy lock held, and they can go off * and execute app code. * * If you need to detect locks that don't have a proper level value: * - Add the MISSING_LEVEL_ASSERT bit into LockOrderChecker::enabledOptions * - Run your tests and look for failing assertions: * - If an assertion points to a lock you care about, add a level * value to that lock. * - If an assertion points to a lock you want to ignore, mark that * lock as LOCK_LEVEL_CHECKING_DISABLED. * - Then re-run the tests, and repeat the above steps. */ int LockOrderChecker::enabledOptions = LOCKORDERCHECKER_OPTION_LOCK_ORDERING_ASSERT; /** * Lock/Unlock file name is unknown on Release builds, and on Debug builds * if the caller didn't specify the MUTEX_CONTEXT parameter. */ const char* LockOrderChecker::s_unknownFile = nullptr; /** * Lock/Unlock line number is unknown on Release builds, and on Debug builds * if the caller didn't specify the MUTEX_CONTEXT parameter. */ const uint32_t LockOrderChecker::s_unknownLineNumber = static_cast<uint32_t>(-1); class LockOrderChecker::LockTrace { public: /* Default constructor */ LockTrace() : m_lock(nullptr), m_level(LOCK_LEVEL_NOT_SPECIFIED), m_recursionCount(0) { } /* Copy constructor */ LockTrace(const LockTrace& other) { *this = other; } /* Assignment operator */ LockTrace& operator =(const LockTrace& other) { m_lock = other.m_lock; m_level = other.m_level; m_recursionCount = other.m_recursionCount; return *this; } /* Address of a lock acquired by current thread */ const Mutex* m_lock; /* * Keep a copy of the lock's level here just in case someone decides to destroy * the lock while owning it, and therefore reaching inside the lock to get the * level would become incorrect. */ LockLevel m_level; /* Number of times current thread acquired this lock, recursively */ uint32_t m_recursionCount; }; LockOrderChecker::LockOrderChecker() : m_currentDepth(0), m_maximumDepth(defaultMaximumStackDepth) { m_lockStack = new LockTrace[m_maximumDepth]; } LockOrderChecker::~LockOrderChecker() { delete[] m_lockStack; } /* * Called when a thread is about to acquire a lock. * * @param lock Lock being acquired by current thread. */ void LockOrderChecker::AcquiringLock(const Mutex* lock, const char* file, uint32_t line) { /* Find the most-recently acquired lock that is being verified */ bool foundRecentEntry = false; uint32_t recentEntry = m_currentDepth - 1; for (uint32_t stackEntry = 0; stackEntry < m_currentDepth; stackEntry++) { LockLevel previousLevel = m_lockStack[recentEntry].m_level; QCC_ASSERT(previousLevel != LOCK_LEVEL_CHECKING_DISABLED); if (previousLevel != LOCK_LEVEL_NOT_SPECIFIED) { foundRecentEntry = true; break; } recentEntry--; } /* * Nothing to check before this lock has been acquired if current thread doesn't * already own any other verified locks. */ if (!foundRecentEntry) { return; } if (file == s_unknownFile) { /* Caller's location is unknown, so try to at least point to the previous owner of this lock */ file = MutexInternal::GetLatestOwnerFileName(*lock); } if (line == s_unknownLineNumber) { /* Caller's location is unknown, so try to at least point to the previous owner of this lock */ line = MutexInternal::GetLatestOwnerLineNumber(*lock); } LockLevel previousLevel = m_lockStack[recentEntry].m_level; LockLevel lockLevel = MutexInternal::GetLevel(*lock); QCC_ASSERT(lockLevel != LOCK_LEVEL_CHECKING_DISABLED); if (lockLevel == LOCK_LEVEL_NOT_SPECIFIED) { if (enabledOptions & LOCKORDERCHECKER_OPTION_MISSING_LEVEL_ASSERT) { LockTrace& previousTrace = m_lockStack[recentEntry]; fprintf(stderr, "Acquiring lock %p with unspecified level (%s:%d). Current thread already owns lock %p level %d (%s:%d).\n", lock, (file != nullptr) ? file : "unknown file", line, previousTrace.m_lock, previousTrace.m_level, MutexInternal::GetLatestOwnerFileName(*previousTrace.m_lock) ? MutexInternal::GetLatestOwnerFileName(*previousTrace.m_lock) : "unknown file", MutexInternal::GetLatestOwnerLineNumber(*previousTrace.m_lock)); fflush(stderr); QCC_ASSERT(false && "Please add a valid level to the lock being acquired"); } return; } if (lockLevel >= previousLevel) { /* The order of acquiring this lock is correct */ return; } /* * Check if current thread already owns this lock. */ bool previouslyLocked = false; for (uint32_t stackEntry = 0; stackEntry < recentEntry; stackEntry++) { QCC_ASSERT(m_lockStack[stackEntry].m_level != LOCK_LEVEL_CHECKING_DISABLED); if (m_lockStack[stackEntry].m_lock == lock) { previouslyLocked = true; break; } } if (!previouslyLocked && (enabledOptions & LOCKORDERCHECKER_OPTION_LOCK_ORDERING_ASSERT)) { LockTrace& previousTrace = m_lockStack[recentEntry]; fprintf(stderr, "Acquiring lock %p level %d (%s:%d). Current thread already owns lock %p level %d (%s:%d).\n", lock, lockLevel, (file != nullptr) ? file : "unknown file", line, previousTrace.m_lock, previousTrace.m_level, MutexInternal::GetLatestOwnerFileName(*previousTrace.m_lock) ? MutexInternal::GetLatestOwnerFileName(*previousTrace.m_lock) : "unknown file", MutexInternal::GetLatestOwnerLineNumber(*previousTrace.m_lock)); fflush(stderr); QCC_ASSERT(false && "Detected out-of-order lock acquire"); } } /* * Called when a thread has just acquired a lock. * * @param lock Lock that has just been acquired by current thread. */ void LockOrderChecker::LockAcquired(const Mutex* lock) { LockLevel lockLevel = MutexInternal::GetLevel(*lock); QCC_ASSERT(lockLevel != LOCK_LEVEL_CHECKING_DISABLED); /* Check if current thread already owns this lock */ bool previouslyLocked = false; for (uint32_t stackEntry = 0; stackEntry < m_currentDepth; stackEntry++) { QCC_ASSERT(m_lockStack[stackEntry].m_level != LOCK_LEVEL_CHECKING_DISABLED); if (m_lockStack[stackEntry].m_lock == lock) { QCC_ASSERT(m_lockStack[stackEntry].m_level == lockLevel); QCC_ASSERT(m_lockStack[stackEntry].m_recursionCount > 0); m_lockStack[stackEntry].m_recursionCount++; previouslyLocked = true; break; } } if (previouslyLocked) { /* Lock is already present on the stack */ return; } /* Add this lock to the stack */ QCC_ASSERT(m_currentDepth <= m_maximumDepth); if (m_currentDepth == m_maximumDepth) { /* Grow the stack */ uint32_t newDepth = m_maximumDepth + 1; LockTrace* newStack = new LockTrace[newDepth]; QCC_ASSERT(newStack != nullptr); for (uint32_t stackEntry = 0; stackEntry < m_maximumDepth; stackEntry++) { newStack[stackEntry] = m_lockStack[stackEntry]; } delete[] m_lockStack; m_lockStack = newStack; m_maximumDepth = newDepth; } m_lockStack[m_currentDepth].m_lock = lock; m_lockStack[m_currentDepth].m_level = lockLevel; m_lockStack[m_currentDepth].m_recursionCount = 1; m_currentDepth++; } /* * Called when a thread is about to release a lock. * * @param lock Lock being released by current thread. */ void LockOrderChecker::ReleasingLock(const Mutex* lock) { LockLevel lockLevel = MutexInternal::GetLevel(*lock); QCC_ASSERT(lockLevel != LOCK_LEVEL_CHECKING_DISABLED); /* Check if current thread owns this lock */ bool previouslyLocked = false; for (uint32_t stackEntry1 = 0; stackEntry1 < m_currentDepth; stackEntry1++) { QCC_ASSERT(m_lockStack[stackEntry1].m_level != LOCK_LEVEL_CHECKING_DISABLED); if (m_lockStack[stackEntry1].m_lock == lock) { QCC_ASSERT(m_lockStack[stackEntry1].m_recursionCount > 0); m_lockStack[stackEntry1].m_recursionCount--; if (m_lockStack[stackEntry1].m_recursionCount == 0) { /* Current thread will no longer own this lock, so remove it from the stack */ for (uint32_t stackEntry2 = stackEntry1; stackEntry2 < (m_currentDepth - 1); stackEntry2++) { m_lockStack[stackEntry2] = m_lockStack[stackEntry2 + 1]; } m_currentDepth--; } previouslyLocked = true; break; } } if (!previouslyLocked) { fprintf(stderr, "Current thread doesn't own lock %p level %d.\n", lock, lockLevel); fflush(stderr); QCC_ASSERT(false && "Current thread doesn't own the lock it is trying to release"); } } } /* namespace */ #endif /* #ifndef NDEBUG */
36.015337
161
0.659399
liuxiang88
9fa0c153fc675b4efb68ca66ef5bc763a8c62a69
582
cpp
C++
engine/src/awesome/editor/menu_items/save_scene_as_menu_item.cpp
vitodtagliente/AwesomeEngine
eff06dbad1c4a168437f69800629a7e20619051c
[ "MIT" ]
3
2019-08-15T18:57:20.000Z
2020-01-09T22:19:26.000Z
engine/src/awesome/editor/menu_items/save_scene_as_menu_item.cpp
vitodtagliente/AwesomeEngine
eff06dbad1c4a168437f69800629a7e20619051c
[ "MIT" ]
null
null
null
engine/src/awesome/editor/menu_items/save_scene_as_menu_item.cpp
vitodtagliente/AwesomeEngine
eff06dbad1c4a168437f69800629a7e20619051c
[ "MIT" ]
null
null
null
#include "save_scene_as_menu_item.h" #include <awesome/data/archive.h> #include <awesome/asset/asset.h> #include <awesome/encoding/json.h> #include <awesome/entity/world.h> namespace editor { void SaveSceneAsMenuItem::render() { m_saveFileDialog.render(); } void SaveSceneAsMenuItem::execute() { m_saveFileDialog.open("Save Scene as...", Asset::getExtensionByType(Asset::Type::Scene), [](const std::filesystem::path& path) -> void { if (!path.string().empty()) { World::instance().save(path); } } ); } REFLECT_MENU_ITEM(SaveSceneAsMenuItem) }
20.785714
136
0.69244
vitodtagliente
9fa2031d57d6c5f85b382ff0dc8dda2ef87ab0b6
62,842
cpp
C++
java/jcl/src/native/harmony/org_apache_harmony_luni_platform_OSNetworkSystem.cpp
webos21/xi
496d636232183c4cc4ec25ab45f6ee25d5eeaf43
[ "Apache-2.0" ]
1
2018-09-25T10:56:25.000Z
2018-09-25T10:56:25.000Z
java/jcl/src/native/harmony/org_apache_harmony_luni_platform_OSNetworkSystem.cpp
webos21/xi
496d636232183c4cc4ec25ab45f6ee25d5eeaf43
[ "Apache-2.0" ]
2
2021-04-07T00:18:48.000Z
2021-04-07T00:20:08.000Z
java/jcl/src/native/harmony/org_apache_harmony_luni_platform_OSNetworkSystem.cpp
webos21/xi
496d636232183c4cc4ec25ab45f6ee25d5eeaf43
[ "Apache-2.0" ]
1
2017-10-26T23:20:32.000Z
2017-10-26T23:20:32.000Z
/* * Copyright (C) 2007 The Android Open Source Project * * 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 "org_apache_harmony_luni_platform_OSNetworkSystem.h" #include "AsynchronousSocketCloseMonitor.h" #include "JNIHelp.h" #include "JniConstants.h" #include "JniException.h" #include "LocalArray.h" #include "NetFd.h" #include "NetworkUtilities.h" #include "ScopedPrimitiveArray.h" #include "valueOf.h" #include "xi/xi_log.h" #include "xi/xi_mem.h" #include "xi/xi_string.h" #include "xi/xi_socket.h" #include "xi/xi_select.h" #include "xi/xi_poll.h" #if 0 // by cmjo #include <assert.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <unistd.h> #include <arpa/inet.h> #include <netdb.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <sys/un.h> #endif // 0 // Temporary hack to build on systems that don't have up-to-date libc headers. #ifndef IPV6_TCLASS #ifdef __linux__ #define IPV6_TCLASS 67 // Linux #else #define IPV6_TCLASS -1 // BSD(-like); TODO: Something better than this! #endif #endif #define EBADF 9 /* Bad file number */ #define EACCES 13 /* Permission denied */ #define EFAULT 14 /* Bad address */ #define EINVAL 22 /* Invalid argument */ #define EADDRINUSE 98 /* Address already in use */ #define EADDRNOTAVAIL 99 /* Cannot assign requested address */ #define ENETDOWN 100 /* Network is down */ #define ENETUNREACH 101 /* Network is unreachable */ #define ENETRESET 102 /* Network dropped connection because of reset */ #define ECONNABORTED 103 /* Software caused connection abort */ #define ECONNRESET 104 /* Connection reset by peer */ #define ENOBUFS 105 /* No buffer space available */ #define EISCONN 106 /* Transport endpoint is already connected */ #define ENOTCONN 107 /* Transport endpoint is not connected */ #define ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */ #define ETOOMANYREFS 109 /* Too many references: cannot splice */ #define ETIMEDOUT 110 /* Connection timed out */ #define ECONNREFUSED 111 /* Connection refused */ #define EHOSTDOWN 112 /* Host is down */ #define EHOSTUNREACH 113 /* No route to host */ #define EALREADY 114 /* Operation already in progress */ #define EINPROGRESS 115 /* Operation now in progress */ /* * TODO: The multicast code is highly platform-dependent, and for now * we just punt on anything but Linux. */ #if 1 //def __linux__ #define ENABLE_MULTICAST #endif #define JAVASOCKOPT_IP_MULTICAST_IF 16 #define JAVASOCKOPT_IP_MULTICAST_IF2 31 #define JAVASOCKOPT_IP_MULTICAST_LOOP 18 #define JAVASOCKOPT_IP_TOS 3 #define JAVASOCKOPT_MCAST_JOIN_GROUP 19 #define JAVASOCKOPT_MCAST_LEAVE_GROUP 20 #define JAVASOCKOPT_MULTICAST_TTL 17 #define JAVASOCKOPT_SO_BROADCAST 32 #define JAVASOCKOPT_SO_KEEPALIVE 8 #define JAVASOCKOPT_SO_LINGER 128 #define JAVASOCKOPT_SO_OOBINLINE 4099 #define JAVASOCKOPT_SO_RCVBUF 4098 #define JAVASOCKOPT_SO_TIMEOUT 4102 #define JAVASOCKOPT_SO_REUSEADDR 4 #define JAVASOCKOPT_SO_SNDBUF 4097 #define JAVASOCKOPT_TCP_NODELAY 1 /* constants for OSNetworkSystem_selectImpl */ #define SOCKET_OP_NONE 0 #define SOCKET_OP_READ 1 #define SOCKET_OP_WRITE 2 /* static struct CachedFields { jfieldID iaddr_ipaddress; jfieldID integer_class_value; jfieldID boolean_class_value; jfieldID socketimpl_address; jfieldID socketimpl_port; jfieldID socketimpl_localport; jfieldID dpack_address; jfieldID dpack_port; jfieldID dpack_length; } gCachedFields; */ /** * Returns the port number in a sockaddr_storage structure. * * @param address the sockaddr_storage structure to get the port from * * @return the port number, or -1 if the address family is unknown. */ static int getSocketAddressPort(xi_sock_addr_t* ss) { return ss->port; } /** * Obtain the socket address family from an existing socket. * * @param socket the file descriptor of the socket to examine * @return an integer, the address family of the socket */ static int getSocketAddressFamily(int socket) { int ret = 0; xi_sock_addr_t addr; ret = xi_socket_get_local(socket, &addr); if (ret < 0) { // Windows getsockname is different from linux // It does fail on the FD (not operated by connect/accept) // So, we need assume, if it failed AF_INET return XI_SOCK_FAMILY_INET; } else { return addr.family; } } // Handles translating between IPv4 and IPv6 addresses so -- where possible -- // we can use either class of address with either an IPv4 or IPv6 socket. class CompatibleSocketAddress { public: // Constructs an address corresponding to 'ss' that's compatible with 'fd'. CompatibleSocketAddress(int fd, const xi_sock_addr_t& ss, bool mapUnspecified) { mCompatibleAddress = reinterpret_cast<const xi_sock_addr_t*> (&ss); UNUSED(fd); UNUSED(mapUnspecified); } // Returns a pointer to an address compatible with the socket. const xi_sock_addr_t* get() const { return mCompatibleAddress; } private: const xi_sock_addr_t* mCompatibleAddress; }; /** * Converts an InetAddress object and port number to a native address structure. */ static bool inetAddressToSocketAddress(JNIEnv* env, jobject inetAddress, int port, xi_sock_addr_t* ss) { // Get the byte array that stores the IP address bytes in the InetAddress. if (inetAddress == NULL) { jniThrowNullPointerException(env, NULL); return false; } jclass inetAddressClass = env->FindClass("java/net/InetAddress"); jfieldID iaddr_ipaddress = env->GetFieldID(inetAddressClass, "ipaddress", "[B"); jbyteArray addressBytes = reinterpret_cast<jbyteArray> (env->GetObjectField(inetAddress, iaddr_ipaddress)); return byteArrayToSocketAddress(env, NULL, addressBytes, port, ss); } /* // Converts a number of milliseconds to a timeval. static timeval toTimeval(long ms) { timeval tv; tv.tv_sec = ms / 1000; tv.tv_usec = (ms - tv.tv_sec * 1000) * 1000; return tv; } // Converts a timeval to a number of milliseconds. static long toMs(const timeval& tv) { return tv.tv_sec * 1000 + tv.tv_usec / 1000; } */ /** * Query OS for timestamp. * Retrieve the current value of system clock and convert to milliseconds. * * @param[in] portLibrary The port library. * * @return 0 on failure, time value in milliseconds on success. * @deprecated Use @ref time_hires_clock and @ref time_hires_delta * * technically, this should return uint64_t since both timeval.tv_sec and * timeval.tv_usec are long */ /* static int time_msec_clock() { timeval tp; struct timezone tzp; gettimeofday(&tp, &tzp); return toMs(tp); } */ /** * Establish a connection to a peer with a timeout. The member functions are called * repeatedly in order to carry out the connect and to allow other tasks to * proceed on certain platforms. The caller must first call ConnectHelper::start. * if the result is -EINPROGRESS it will then * call ConnectHelper::isConnected until either another error or 0 is returned to * indicate the connect is complete. Each time the function should sleep for no * more than 'timeout' milliseconds. If the connect succeeds or an error occurs, * the caller must always end the process by calling ConnectHelper::done. * * Member functions return 0 if no errors occur, otherwise -errno. TODO: use +errno. */ class ConnectHelper { public: ConnectHelper(JNIEnv* env) : mEnv(env) { } int start(NetFd& fd, jobject inetAddr, jint port) { int ret = XI_SOCK_RV_ERR_ARGS; xi_sock_addr_t ss; if (!inetAddressToSocketAddress(mEnv, inetAddr, port, &ss)) { return -EINVAL; // Bogus, but clearly a failure, and we've already thrown. } log_trace(XDLOG, "!!!!!!!!! conn start !!!!!! fd=%d / ss.host=%s\n", fd.get(), ss.host); // Set the socket to non-blocking and initiate a connection attempt... //const CompatibleSocketAddress compatibleAddress(fd.get(), ss, true); setBlocking(fd.get(), false); if ((ret = xi_socket_connect(fd.get(), ss)) < 0) { // if (xi_socket_connect(fd.get(), ss) < 0) { if (fd.isClosed()) { log_error(XDLOG, "!!!!!!!!! conn closed !!!!! fd=%d / ss.host=%s\n", fd.get(), ss.host); return -EINVAL; // Bogus, but clearly a failure, and we've already thrown. } if (ret == XI_SOCK_RV_ERR_TRYLATER) { log_trace(XDLOG, "!!!!!!!!! conn progress !!!!!! fd=%d / ss.host=%s\n", fd.get(), ss.host); return -EINPROGRESS; } else { log_error(XDLOG, "!!!!!!!!! conn error !!!!!! fd=%d / ss.host=%s\n", fd.get(), ss.host); didFail(fd.get(), -ENETUNREACH); return -EINVAL; } // if (errno != EINPROGRESS) { // didFail(fd.get(), -errno); // } } // We connected straight away! didConnect(fd.get()); return 0; } // Returns 0 if we're connected; -EINPROGRESS if we're still hopeful, -errno if we've failed. // 'timeout' the timeout in milliseconds. If timeout is negative, perform a blocking operation. #if 1 int isConnected(int fd, int timeout) { // Initialize the fd sets for the select. xi_fdset_t *readSet = xi_sel_fdcreate(); xi_fdset_t *writeSet = xi_sel_fdcreate(); xi_sel_fdzero(readSet); xi_sel_fdzero(writeSet); xi_sel_fdset(fd, readSet); xi_sel_fdset(fd, writeSet); int nfds = fd + 1; int rc = xi_sel_select(nfds, readSet, writeSet, NULL, timeout); if (rc < 0) { xi_sel_fddestroy(readSet); xi_sel_fddestroy(writeSet); return rc; } else if (rc == 0) { xi_sel_fddestroy(readSet); xi_sel_fddestroy(writeSet); return -EINPROGRESS; } // If the fd is just in the write set, we're connected. if (xi_sel_fdisset(fd, writeSet) && !xi_sel_fdisset(fd, readSet)) { xi_sel_fddestroy(readSet); xi_sel_fddestroy(writeSet); return 0; } // If the fd is in both the read and write set, there was an error. if (xi_sel_fdisset(fd, readSet) || xi_sel_fdisset(fd, writeSet)) { // Get the pending error. // int error = 0; // socklen_t errorLen = sizeof(error); // if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &errorLen) == -1) { // return -errno; // Couldn't get the real error, so report why not. // } xi_sel_fddestroy(readSet); xi_sel_fddestroy(writeSet); return 3; } xi_sel_fddestroy(readSet); xi_sel_fddestroy(writeSet); return -EINPROGRESS; } # else // Use SELECT int isConnected(int fd, int timeout) { struct timeval passedTimeout; passedTimeout.tv_sec = timeout / 1000; passedTimeout.tv_usec = (timeout % 1000) * 1000; // Initialize the fd sets for the select. fd_set readSet; fd_set writeSet; FD_ZERO(&readSet); FD_ZERO(&writeSet); FD_SET(fd, &readSet); FD_SET(fd, &writeSet); int nfds = fd + 1; timeval* tp = timeout >= 0 ? &passedTimeout : NULL; int rc = select(nfds, &readSet, &writeSet, NULL, tp); if (rc == -1) { if (errno == EINTR) { // We can't trivially retry a select with TEMP_FAILURE_RETRY, so punt and ask the // caller to try again. return -EINPROGRESS; } return -errno; } // If the fd is just in the write set, we're connected. if (FD_ISSET(fd, &writeSet) && !FD_ISSET(fd, &readSet)) { return 0; } // If the fd is in both the read and write set, there was an error. if (FD_ISSET(fd, &readSet) || FD_ISSET(fd, &writeSet)) { // Get the pending error. // int error = 0; // socklen_t errorLen = sizeof(error); // if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &errorLen) == -1) { // return -errno; // Couldn't get the real error, so report why not. // } return -errno; } // Timeout expired. return -EINPROGRESS; } #endif void didConnect(int fd) { if (fd != -1) { setBlocking(fd, true); } } void didFail(int fd, int result) { if (fd != -1) { setBlocking(fd, true); } // if (result == XI_SOCK_RV_ERR_ADDR || result == XI_SOCK_RV_ERR_REFUSED // || result == XI_SOCK_RV_ERR_INUSE) { // jniThrowSocketExceptionMsg(mEnv, "java/net/ConnectException", // "connect failed!!", result); // //jniThrowConnectException(mEnv, -result); // } else if (result == XI_SOCK_RV_ERR_PERM) { // jniThrowSocketExceptionMsg(mEnv, "java/lang/SecurityException", // "security error!!", result); // //jniThrowSecurityException(mEnv, -result); // } else if (result == XI_SOCK_RV_ERR_TIMEOUT) { // jniThrowSocketExceptionMsg(mEnv, "java/net/SocketTimeoutException", // "time-out occurred!!", result); // //jniThrowSocketTimeoutException(mEnv, -result); // } else { // jniThrowSocketExceptionMsg(mEnv, "java/net/SocketException", // "generic socket error!!", result); // //jniThrowSocketException(mEnv, -result); // } if (result == -ECONNRESET || result == -ECONNREFUSED || result == -EADDRNOTAVAIL || result == -EADDRINUSE || result == -ENETUNREACH) { log_error(XDLOG, "ConnectionException!!!!"); jniThrowSocketExceptionMsg(mEnv, "java/net/ConnectException", "connect failed!!", result); //jniThrowConnectException(mEnv, -result); } else if (result == -EACCES) { log_error(XDLOG, "SecurityException!!!!"); jniThrowSocketExceptionMsg(mEnv, "java/lang/SecurityException", "security error!!", result); //jniThrowSecurityException(mEnv, -result); } else if (result == -ETIMEDOUT) { log_error(XDLOG, "SocketTimeoutException!!!!"); jniThrowSocketExceptionMsg(mEnv, "java/net/SocketTimeoutException", "time-out occurred!!", result); //jniThrowSocketTimeoutException(mEnv, -result); } else { log_error(XDLOG, "SocketException!!!!"); jniThrowSocketExceptionMsg(mEnv, "java/net/SocketException", "generic socket error!!", result); //jniThrowSocketException(mEnv, -result); } } private: JNIEnv* mEnv; }; #ifdef ENABLE_MULTICAST static void mcastJoinLeaveGroup(JNIEnv* env, int fd, jobject javaGroupRequest, bool join) { // group_req groupRequest; // // // Get the IPv4 or IPv6 multicast address to join or leave. // jclass multicastGroupRequestClass = env->FindClass("java/net/MulticastGroupRequest"); // jfieldID fid = env->GetFieldID(multicastGroupRequestClass, // "gr_group", "Ljava/net/InetAddress;"); // jobject group = env->GetObjectField(javaGroupRequest, fid); // if (!inetAddressToSocketAddress(env, group, 0, &groupRequest.gr_group)) { // return; // } // // // Get the interface index to use (or 0 for "whatever"). // fid = env->GetFieldID(multicastGroupRequestClass, "gr_interface", "I"); // groupRequest.gr_interface = env->GetIntField(javaGroupRequest, fid); // // int level = groupRequest.gr_group.ss_family == AF_INET ? IPPROTO_IP : IPPROTO_IPV6; // int option = join ? MCAST_JOIN_GROUP : MCAST_LEAVE_GROUP; // int rc = setsockopt(fd, level, option, &groupRequest, sizeof(groupRequest)); // if (rc == -1) { // jniThrowSocketException(env, errno); // return; // } xi_sock_addr_t grpaddr; xi_sock_addr_t ifaddr; // Get the IPv4 or IPv6 multicast address to join or leave. jclass multicastGroupRequestClass = env->FindClass( "java/net/MulticastGroupRequest"); jfieldID fid = env->GetFieldID(multicastGroupRequestClass, "gr_group", "Ljava/net/InetAddress;"); jobject group = env->GetObjectField(javaGroupRequest, fid); if (!inetAddressToSocketAddress(env, group, 0, &grpaddr)) { return; } grpaddr.type = XI_SOCK_TYPE_DATAGRAM; xi_mem_copy(&ifaddr, &grpaddr, sizeof(xi_sock_addr_t)); if (grpaddr.family == XI_SOCK_FAMILY_INET) { xi_strcpy(ifaddr.host, "0.0.0.0"); } else { xi_strcpy(ifaddr.host, "::0.0.0.0"); } int rc; if (join) { rc = xi_mcast_join(fd, ifaddr, grpaddr, NULL); } else { rc = xi_mcast_leave(fd, ifaddr, grpaddr, NULL); } if (rc != 0) { jniThrowSocketExceptionMsg(env, "java/net/SocketException", "Cannot join or leave multicast!!", rc); return; } } #endif // def ENABLE_MULTICAST /* static bool initCachedFields(JNIEnv* env) { memset(&gCachedFields, 0, sizeof(gCachedFields)); struct CachedFields* c = &gCachedFields; struct fieldInfo { jfieldID* field; jclass clazz; const char* name; const char* type; } fields[] = { {&c->iaddr_ipaddress, JniConstants::inetAddressClass, "ipaddress", "[B"}, {&c->integer_class_value, JniConstants::integerClass, "value", "I"}, {&c->boolean_class_value, JniConstants::booleanClass, "value", "Z"}, {&c->socketimpl_port, JniConstants::socketImplClass, "port", "I"}, {&c->socketimpl_localport, JniConstants::socketImplClass, "localport", "I"}, {&c->socketimpl_address, JniConstants::socketImplClass, "address", "Ljava/net/InetAddress;"}, {&c->dpack_address, JniConstants::datagramPacketClass, "address", "Ljava/net/InetAddress;"}, {&c->dpack_port, JniConstants::datagramPacketClass, "port", "I"}, {&c->dpack_length, JniConstants::datagramPacketClass, "length", "I"} }; for (unsigned i = 0; i < sizeof(fields) / sizeof(fields[0]); i++) { fieldInfo f = fields[i]; *f.field = env->GetFieldID(f.clazz, f.name, f.type); if (*f.field == NULL) return false; } return true; } */ //static void OSNetworkSystem_socket(JNIEnv* env, jobject, jobject fileDescriptor, jboolean stream) { JNIEXPORT void JNICALL Java_org_apache_harmony_luni_platform_OSNetworkSystem_socket(JNIEnv* env, jobject, jobject fileDescriptor, jboolean stream) { if (fileDescriptor == NULL) { jniThrowNullPointerException(env, NULL); //errno = EBADF; return; } // Try IPv6 but fall back to IPv4... xi_sock_type_e type = stream ? XI_SOCK_TYPE_STREAM : XI_SOCK_TYPE_DATAGRAM; //int fd = xi_socket_open(XI_SOCK_FAMILY_INET6, type, XI_SOCK_PROTO_IP); //if (fd < 0) { int fd = xi_socket_open(XI_SOCK_FAMILY_INET, type, XI_SOCK_PROTO_IP); //} if (fd < 0) { jniThrowSocketExceptionMsg(env, "java/net/SocketException", "cannot open socket", fd); return; } else { jniSetFileDescriptorOfFD(env, fileDescriptor, fd); } } /* static jint OSNetworkSystem_writeDirect(JNIEnv* env, jobject, jobject fileDescriptor, jint address, jint offset, jint count) { */ JNIEXPORT jint JNICALL Java_org_apache_harmony_luni_platform_OSNetworkSystem_writeDirect(JNIEnv* env, jobject, jobject fileDescriptor, jint address, jint offset, jint count) { if (count <= 0) { return 0; } NetFd fd(env, fileDescriptor); if (fd.isClosed()) { return 0; } jbyte* src = reinterpret_cast<jbyte*> (static_cast<xuint32> (address + offset)); xint32 bytesSent; { int intFd = fd.get(); AsynchronousSocketCloseMonitor monitor(intFd); //log_trace(XDLOG, "Send Message(fd=%d / bytes=%d)\n", intFd, xi_strlen((const xchar*)src)); bytesSent = xi_file_write(intFd, src, count); //bytesSent = NET_FAILURE_RETRY(fd, xi_file_write(intFd, src, count)); } if (env->ExceptionOccurred()) { return -1; } if (bytesSent < 0) { // if (errno == EAGAIN || errno == EWOULDBLOCK) { // // We were asked to write to a non-blocking socket, but were told // // it would block, so report "no bytes written". // return 0; // } else { log_error(XDLOG, "Send Message Error!!! (fd=%d / msg=%s)\n", fd.get(), src); jniThrowSocketExceptionMsg(env, "java/net/SocketException", "writeDirect error!!", bytesSent); return 0; // } } return bytesSent; } /* static jint OSNetworkSystem_write(JNIEnv* env, jobject, jobject fileDescriptor, jbyteArray byteArray, jint offset, jint count) { */ JNIEXPORT jint JNICALL Java_org_apache_harmony_luni_platform_OSNetworkSystem_write(JNIEnv* env, jobject, jobject fileDescriptor, jbyteArray byteArray, jint offset, jint count) { ScopedByteArrayRW bytes(env, byteArray); if (bytes.get() == NULL) { return -1; } jint address = static_cast<jint> (reinterpret_cast<xlong> (bytes.get())); // by jshwang // int result = OSNetworkSystem_writeDirect(env, NULL, fileDescriptor, address, offset, count); int result = Java_org_apache_harmony_luni_platform_OSNetworkSystem_writeDirect( env, NULL, fileDescriptor, address, offset, count); return result; } //static jboolean OSNetworkSystem_connectNonBlocking(JNIEnv* env, jobject, jobject fileDescriptor, jobject inetAddr, jint port) { JNIEXPORT jboolean JNICALL Java_org_apache_harmony_luni_platform_OSNetworkSystem_connectNonBlocking( JNIEnv* env, jobject, jobject fileDescriptor, jobject inetAddr, jint port) { NetFd fd(env, fileDescriptor); if (fd.isClosed()) { return JNI_FALSE; } //log_trace(XDLOG, "!!!!!!!!! fd=%d / port=%d\n", fd.get(), port); ConnectHelper context(env); return context.start(fd, inetAddr, port) == 0; } //static jboolean OSNetworkSystem_isConnected(JNIEnv* env, jobject, jobject fileDescriptor, jint timeout) { JNIEXPORT jboolean JNICALL Java_org_apache_harmony_luni_platform_OSNetworkSystem_isConnected(JNIEnv* env, jobject, jobject fileDescriptor, jint timeout) { NetFd fd(env, fileDescriptor); if (fd.isClosed()) { return JNI_FALSE; } ConnectHelper context(env); int result = context.isConnected(fd.get(), timeout); if (result == 0) { context.didConnect(fd.get()); return JNI_TRUE; } else if (result == -EINPROGRESS) { // Not yet connected, but not yet denied either... Try again later. return JNI_FALSE; } else { context.didFail(fd.get(), result); return JNI_FALSE; } } // TODO: move this into Java, using connectNonBlocking and isConnected! /* static void OSNetworkSystem_connect(JNIEnv* env, jobject, jobject fileDescriptor, jobject inetAddr, jint port, jint timeout) { */ JNIEXPORT void JNICALL Java_org_apache_harmony_luni_platform_OSNetworkSystem_connect(JNIEnv* env, jobject, jobject fileDescriptor, jobject inetAddr, jint port, jint timeout) { /* if a timeout was specified calculate the finish time value */ bool hasTimeout = timeout > 0; xint64 finishTime = xi_clock_msec(); if (hasTimeout) { log_trace(XDLOG, "current = %lld / timeout=%d / finish=%lld\n", finishTime, timeout, (finishTime + timeout)); finishTime += timeout; } NetFd fd(env, fileDescriptor); if (fd.isClosed()) { return; } //log_trace(XDLOG, "!!!!!!!!! fd=%d / port=%d\n", fd.get(), port); // ConnectHelper context(env); // xint32 ret = context.start(fd, inetAddr, port); // if (ret < 0) { // log_error(XDLOG, "!!!!!!!!! connection failed!!! fd=%d / port=%d\n", fd.get(), port); // } ConnectHelper context(env); int result = context.start(fd, inetAddr, port); int remainingTimeout = timeout; while (result == -EINPROGRESS) { log_trace(XDLOG, "!!!!!!!!! connection check!!! fd=%d / port=%d / ret=%d\n", fd.get(), port, result); /* * ok now try and connect. Depending on the platform this may sleep * for up to passedTimeout milliseconds */ result = context.isConnected(fd.get(), remainingTimeout); // FIXME : avoid VM addRefL Error!! // if (fd.isClosed()) { // log_error(XDLOG, "Socket is closed!!!\n"); // return; // } if (result == 0) { log_trace(XDLOG, "connection is done!!! fd=%d / port=%d / ret=%d\n", fd.get(), port, result); context.didConnect(fd.get()); return; } else if (result != -EINPROGRESS) { log_error(XDLOG, "connection is failed!!! fd=%d / port=%d / ret=%d\n", fd.get(), port, result); context.didFail(fd.get(), result); return; } /* check if the timeout has expired */ if (hasTimeout) { remainingTimeout = finishTime - xi_clock_msec(); if (remainingTimeout <= 0) { log_error(XDLOG, "connection is timeout!!! fd=%d / port=%d / ret=%d\n", fd.get(), port, result); context.didFail(fd.get(), -ETIMEDOUT); return; } log_trace(XDLOG, "connection retry!!! fd=%d / port=%d / remain=%lld\n", fd.get(), port, remainingTimeout); } else { remainingTimeout = 100; log_trace(XDLOG, "connection retry!!! fd=%d / port=%d / remain=%lld\n", fd.get(), port, remainingTimeout); } } } /* static void OSNetworkSystem_bind(JNIEnv* env, jobject, jobject fileDescriptor, jobject inetAddress, jint port) { */ JNIEXPORT void JNICALL Java_org_apache_harmony_luni_platform_OSNetworkSystem_bind(JNIEnv* env, jobject, jobject fileDescriptor, jobject inetAddress, jint port) { xi_sock_addr_t socketAddress; xi_mem_set(&socketAddress, 0, sizeof(socketAddress)); if (!inetAddressToSocketAddress(env, inetAddress, port, &socketAddress)) { return; } //log_trace(XDLOG, "!!!!!!!!! bind to %s\n", socketAddress.host); NetFd fd(env, fileDescriptor); if (fd.isClosed()) { return; } const CompatibleSocketAddress compatibleAddress(fd.get(), socketAddress, false); // int // rc = // TEMP_FAILURE_RETRY(bind(fd.get(), compatibleAddress.get(), sizeof(sockaddr_storage))); int rc = xi_socket_bind(fd.get(), socketAddress); if (rc < 0) { jniThrowSocketExceptionMsg(env, "java/net/BindException", "bind error!!", rc); //jniThrowBindException(env, errno); } } //static void OSNetworkSystem_listen(JNIEnv* env, jobject, jobject fileDescriptor, jint backlog) { JNIEXPORT void JNICALL Java_org_apache_harmony_luni_platform_OSNetworkSystem_listen(JNIEnv* env, jobject, jobject fileDescriptor, jint backlog) { NetFd fd(env, fileDescriptor); if (fd.isClosed()) { return; } int rc = xi_socket_listen(fd.get(), backlog); if (rc < 0) { jniThrowSocketExceptionMsg(env, "java/net/SocketException", "listen error!!", rc); //jniThrowSocketException(env, errno); } } /* static void OSNetworkSystem_accept(JNIEnv* env, jobject, jobject serverFileDescriptor, jobject newSocket, jobject clientFileDescriptor) { */ JNIEXPORT void JNICALL Java_org_apache_harmony_luni_platform_OSNetworkSystem_accept(JNIEnv* env, jobject, jobject serverFileDescriptor, jobject newSocket, jobject clientFileDescriptor) { if (newSocket == NULL) { jniThrowNullPointerException(env, NULL); return; } NetFd serverFd(env, serverFileDescriptor); if (serverFd.isClosed()) { return; } //sockaddr_storage ss; xi_sock_addr_t ss; int clientFd; { int intFd = serverFd.get(); AsynchronousSocketCloseMonitor monitor(intFd); clientFd = xi_socket_accept(intFd, &ss); } if (env->ExceptionOccurred()) { return; } if (clientFd < 0) { jniThrowSocketExceptionMsg(env, "java/net/SocketException", "accept error!!", clientFd); // if (errno == EAGAIN || errno == EWOULDBLOCK) { // jniThrowSocketTimeoutException(env, errno); // } else { // jniThrowSocketException(env, errno); // } return; } // Reset the inherited read timeout to the Java-specified default of 0. // timeval timeout(toTimeval(0)); // int rc = setsockopt(clientFd, SOL_SOCKET, SO_RCVTIMEO, &timeout, // sizeof(timeout)); // if (rc == -1) { // log_print(XDLOG, "couldn't reset SO_RCVTIMEO on accepted socket fd %i: %s", clientFd, strerror(errno)); // jniThrowSocketException(env, errno); // } /* * For network sockets, put the peer address and port in instance variables. * We don't bother to do this for UNIX domain sockets, since most peers are * anonymous anyway. */ if (ss.family == XI_SOCK_FAMILY_INET || ss.family == XI_SOCK_FAMILY_INET6) { // Remote address and port. jobject remoteAddress = socketAddressToInetAddress(env, &ss); if (remoteAddress == NULL) { xi_socket_close(clientFd); return; } int remotePort = getSocketAddressPort(&ss); jclass socketImplClass = env->FindClass("java/net/SocketImpl"); jfieldID socketimpl_address = env->GetFieldID(socketImplClass, "address", "Ljava/net/InetAddress;"); jfieldID socketimpl_port = env->GetFieldID(socketImplClass, "port", "I"); env->SetObjectField(newSocket, socketimpl_address, remoteAddress); env->SetIntField(newSocket, socketimpl_port, remotePort); // Local port. xi_mem_set(&ss, 0, sizeof(xi_sock_addr_t)); int rc = xi_socket_get_local(clientFd, &ss); if (rc < 0) { xi_socket_close(clientFd); jniThrowSocketExceptionMsg(env, "java/net/SocketException", "get local port error!!", rc); //jniThrowSocketException(env, errno); return; } int localPort = getSocketAddressPort(&ss); jfieldID socketimpl_localport = env->GetFieldID(socketImplClass, "localport", "I"); env->SetIntField(newSocket, socketimpl_localport, localPort); } jniSetFileDescriptorOfFD(env, clientFileDescriptor, clientFd); } /* static void OSNetworkSystem_sendUrgentData(JNIEnv* env, jobject, jobject fileDescriptor, jbyte value) { */ JNIEXPORT void JNICALL Java_org_apache_harmony_luni_platform_OSNetworkSystem_sendUrgentData( JNIEnv* env, jobject, jobject fileDescriptor, jbyte value) { NetFd fd(env, fileDescriptor); if (fd.isClosed()) { return; } int rc = xi_socket_send(fd.get(), &value, 1); if (rc < 0) { jniThrowSocketExceptionMsg(env, "java/net/SocketException", "send urgent data error!!", rc); //jniThrowSocketException(env, errno); } } //static void OSNetworkSystem_disconnectDatagram(JNIEnv* env, jobject, jobject fileDescriptor) { JNIEXPORT void JNICALL Java_org_apache_harmony_luni_platform_OSNetworkSystem_disconnectDatagram( JNIEnv* env, jobject, jobject fileDescriptor) { NetFd fd(env, fileDescriptor); if (fd.isClosed()) { return; } // To disconnect a datagram socket, we connect to a bogus address with // the family AF_UNSPEC. xi_sock_addr_t ss; xi_mem_set(&ss, 0, sizeof(ss)); ss.family = XI_SOCK_FAMILY_UNSPEC; int rc = xi_socket_connect(fd.get(), ss); if (rc < 0) { jniThrowSocketExceptionMsg(env, "java/net/SocketException", "datagram disconnect error!!", rc); //jniThrowSocketException(env, errno); } } /* Java_org_apache_harmony_luni_platform_OSNetworkSystem_setInetAddress(JNIEnv* env, jobject, jobject sender, jbyteArray address) { */ JNIEXPORT void JNICALL Java_org_apache_harmony_luni_platform_OSNetworkSystem_setInetAddress( JNIEnv* env, jobject, jobject sender, jbyteArray address) { jclass inetAddressClass = env->FindClass("java/net/InetAddress"); jfieldID iaddr_ipaddress = env->GetFieldID(inetAddressClass, "ipaddress", "[B"); env->SetObjectField(sender, iaddr_ipaddress, address); } // TODO: can we merge this with recvDirect? /* static jint OSNetworkSystem_readDirect(JNIEnv* env, jobject, jobject fileDescriptor, jint address, jint count) { */ JNIEXPORT jint JNICALL Java_org_apache_harmony_luni_platform_OSNetworkSystem_readDirect(JNIEnv* env, jobject, jobject fileDescriptor, jint address, jint count) { NetFd fd(env, fileDescriptor); if (fd.isClosed()) { return 0; } jbyte* dst = reinterpret_cast<jbyte*> (static_cast<xuint32> (address)); xint32 bytesReceived; { int intFd = fd.get(); AsynchronousSocketCloseMonitor monitor(intFd); bytesReceived = xi_file_read(intFd, dst, count); } if (env->ExceptionOccurred()) { return -1; } if (bytesReceived == 0) { return -1; } else if (bytesReceived < 0) { jniThrowSocketExceptionMsg(env, "java/net/SocketException", "readDirect error!!", bytesReceived); return 0; // if (errno == EAGAIN || errno == EWOULDBLOCK) { // // We were asked to read a non-blocking socket with no data // // available, so report "no bytes read". // return 0; // } else { // jniThrowSocketException(env, errno); // return 0; // } } else { return bytesReceived; } } /* static jint OSNetworkSystem_read(JNIEnv* env, jobject, jobject fileDescriptor, jbyteArray byteArray, jint offset, jint count) { */ JNIEXPORT jint JNICALL Java_org_apache_harmony_luni_platform_OSNetworkSystem_read(JNIEnv* env, jobject, jobject fileDescriptor, jbyteArray byteArray, jint offset, jint count) { ScopedByteArrayRW bytes(env, byteArray); if (bytes.get() == NULL) { return -1; } jint address = static_cast<jint> (reinterpret_cast<xlong> (bytes.get() + offset)); // by jshwang // return OSNetworkSystem_readDirect(env, NULL, fileDescriptor, address, count); return Java_org_apache_harmony_luni_platform_OSNetworkSystem_readDirect( env, NULL, fileDescriptor, address, count); } // TODO: can we merge this with readDirect? /* static jint OSNetworkSystem_recvDirect(JNIEnv* env, jobject, jobject fileDescriptor, jobject packet, jint address, jint offset, jint length, jboolean peek, jboolean connected) { */ JNIEXPORT jint JNICALL Java_org_apache_harmony_luni_platform_OSNetworkSystem_recvDirect(JNIEnv* env, jobject, jobject fileDescriptor, jobject packet, jint address, jint offset, jint length, jboolean peek, jboolean connected) { NetFd fd(env, fileDescriptor); if (fd.isClosed()) { return 0; } char* buf = reinterpret_cast<char*> (static_cast<xuint32> (address + offset)); //const int flags = peek ? MSG_PEEK : 0; xi_sock_addr_t ss; xi_mem_set(&ss, 0, sizeof(ss)); xint32 bytesReceived; { int intFd = fd.get(); AsynchronousSocketCloseMonitor monitor(intFd); bytesReceived = xi_socket_recvfrom(intFd, buf, length, &ss); } if (env->ExceptionOccurred()) { return -1; } if (bytesReceived < 0) { jniThrowSocketExceptionMsg(env, "java/net/SocketException", "recvfrom error!!", bytesReceived); // if (connected && errno == ECONNREFUSED) { // jniThrowException(env, "java/net/PortUnreachableException", ""); // } else if (errno == EAGAIN || errno == EWOULDBLOCK) { // jniThrowSocketTimeoutException(env, errno); // } else { // jniThrowSocketException(env, errno); // } return 0; } if (packet != NULL) { jclass datagramPacketClass = env->FindClass("java/net/DatagramPacket"); jfieldID dpack_length = env->GetFieldID(datagramPacketClass, "length", "I"); env->SetIntField(packet, dpack_length, bytesReceived); if (!connected) { jbyteArray addr = socketAddressToByteArray(env, &ss); if (addr == NULL) { return 0; } int port = getSocketAddressPort(&ss); jobject sender = byteArrayToInetAddress(env, addr); if (sender == NULL) { return 0; } jfieldID dpack_address = env->GetFieldID(datagramPacketClass, "address", "Ljava/net/InetAddress;"); jfieldID dpack_port = env->GetFieldID(datagramPacketClass, "port", "I"); env->SetObjectField(packet, dpack_address, sender); env->SetIntField(packet, dpack_port, port); } } UNUSED(peek); return bytesReceived; } /* static jint OSNetworkSystem_recv(JNIEnv* env, jobject, jobject fd, jobject packet, jbyteArray javaBytes, jint offset, jint length, jboolean peek, jboolean connected) { */ JNIEXPORT jint JNICALL Java_org_apache_harmony_luni_platform_OSNetworkSystem_recv(JNIEnv* env, jobject, jobject fd, jobject packet, jbyteArray javaBytes, jint offset, jint length, jboolean peek, jboolean connected) { ScopedByteArrayRW bytes(env, javaBytes); if (bytes.get() == NULL) { return -1; } jint address = reinterpret_cast<xlong> (bytes.get()); // by jshwang // return OSNetworkSystem_recvDirect(env, NULL, fd, packet, address, offset, length, peek, connected); return Java_org_apache_harmony_luni_platform_OSNetworkSystem_recvDirect( env, NULL, fd, packet, address, offset, length, peek, connected); } //static jint OSNetworkSystem_sendDirect(JNIEnv* env, jobject, jobject fileDescriptor, jint address, jint offset, jint length, jint port, jobject inetAddress) { JNIEXPORT jint JNICALL Java_org_apache_harmony_luni_platform_OSNetworkSystem_sendDirect(JNIEnv* env, jobject, jobject fileDescriptor, jint address, jint offset, jint length, jint port, jobject inetAddress) { NetFd fd(env, fileDescriptor); if (fd.isClosed()) { return -1; } xi_sock_addr_t receiver; if (inetAddress != NULL && !inetAddressToSocketAddress(env, inetAddress, port, &receiver)) { return -1; } char* buf = reinterpret_cast<char*> (static_cast<xuint32> (address + offset)); // sockaddr* to = inetAddress ? reinterpret_cast<sockaddr*> (&receiver) : NULL; // socklen_t toLength = inetAddress ? sizeof(receiver) : 0; xint32 bytesSent; { int intFd = fd.get(); AsynchronousSocketCloseMonitor monitor(intFd); bytesSent = xi_socket_sendto(intFd, buf, length, receiver); } if (env->ExceptionOccurred()) { return -1; } if (bytesSent < 0) { jniThrowSocketExceptionMsg(env, "java/net/SocketException", "sendDirect error!!", bytesSent); // if (errno == ECONNRESET || errno == ECONNREFUSED) { // return 0; // } else { // jniThrowSocketException(env, errno); // } } return bytesSent; } /* static jint OSNetworkSystem_send(JNIEnv* env, jobject, jobject fd, jbyteArray data, jint offset, jint length, jint port, jobject inetAddress) { */ JNIEXPORT jint JNICALL Java_org_apache_harmony_luni_platform_OSNetworkSystem_send(JNIEnv* env, jobject, jobject fd, jbyteArray data, jint offset, jint length, jint port, jobject inetAddress) { ScopedByteArrayRO bytes(env, data); if (bytes.get() == NULL) { return -1; } /* by jshwang return OSNetworkSystem_sendDirect(env, NULL, fd, reinterpret_cast<uintptr_t>(bytes.get()), offset, length, port, inetAddress); */ return Java_org_apache_harmony_luni_platform_OSNetworkSystem_sendDirect( env, NULL, fd, reinterpret_cast<xlong> (bytes.get()), offset, length, port, inetAddress); } // //static bool isValidFd(int fd) { // return fd >= 0 && fd < 64; //} // //static bool initFdSet(JNIEnv* env, jobjectArray fdArray, jint count, // fd_set* fdSet, int* maxFd) { // for (int i = 0; i < count; ++i) { // jobject fileDescriptor = env->GetObjectArrayElement(fdArray, i); // if (fileDescriptor == NULL) { // return false; // } // // const int fd = jniGetFDFromFileDescriptor(env, fileDescriptor); // if (!isValidFd(fd)) { // log_print(XDLOG, "selectImpl: ignoring invalid fd %i", fd); // continue; // } // // FD_SET(fd, fdSet); // // if (fd > *maxFd) { // *maxFd = fd; // } // } // return true; //} // ///* // * Note: fdSet has to be non-const because although on Linux FD_ISSET() is sane // * and takes a const fd_set*, it takes fd_set* on Mac OS. POSIX is not on our // * side here: // * http://www.opengroup.org/onlinepubs/000095399/functions/select.html // */ //static bool translateFdSet(JNIEnv* env, jobjectArray fdArray, jint count, // fd_set& fdSet, jint* flagArray, size_t offset, jint op) { // for (int i = 0; i < count; ++i) { // jobject fileDescriptor = env->GetObjectArrayElement(fdArray, i); // if (fileDescriptor == NULL) { // return false; // } // // const int fd = jniGetFDFromFileDescriptor(env, fileDescriptor); // if (isValidFd(fd) && FD_ISSET(fd, &fdSet)) { // flagArray[i + offset] = op; // } else { // flagArray[i + offset] = SOCKET_OP_NONE; // } // } // return true; //} /* static jboolean OSNetworkSystem_selectImpl(JNIEnv* env, jclass, jobjectArray readFDArray, jobjectArray writeFDArray, jint countReadC, jint countWriteC, jintArray outFlags, jlong timeoutMs) { */ JNIEXPORT jboolean JNICALL Java_org_apache_harmony_luni_platform_OSNetworkSystem_selectImpl(JNIEnv* env, jclass, jobjectArray readFDArray, jobjectArray writeFDArray, jint countReadC, jint countWriteC, jintArray outFlags, jlong timeoutMs) { xint32 i; xi_pollset_t *pset = xi_pollset_create(64, XI_POLLSET_OPT_EPOLL); // Read PollSet for (i = 0; i < countReadC; ++i) { jobject fileDescriptor = env->GetObjectArrayElement(readFDArray, i); if (fileDescriptor == NULL) { xi_pollset_destroy(pset); return -1; } const int fd = jniGetFDFromFileDescriptor(env, fileDescriptor); if (fd >= 0 && fd < 64) { log_error(XDLOG, "selectImpl: ignoring invalid fd %i", fd); continue; } xi_pollfd_t pfd; pfd.desc = fd; pfd.evts = XI_POLL_EVENT_IN; pfd.context = NULL; xi_pollset_add(pset, pfd); } // Write PollSet for (i = 0; i < countWriteC; ++i) { jobject fileDescriptor = env->GetObjectArrayElement(writeFDArray, i); if (fileDescriptor == NULL) { xi_pollset_destroy(pset); return -1; } const int fd = jniGetFDFromFileDescriptor(env, fileDescriptor); if (fd >= 0 && fd < 64) { log_warn(XDLOG, "selectImpl: ignoring invalid fd %i", fd); continue; } xi_pollfd_t pfd; pfd.desc = fd; pfd.evts = XI_POLL_EVENT_OUT; pfd.context = NULL; xi_pollset_add(pset, pfd); } // Perform the poll. xi_pollfd_t rfds[64]; int result = xi_pollset_poll(pset, &rfds[0], 64, timeoutMs); if (result == 0) { // Timeout. return JNI_FALSE; } else if (result < 0) { jniThrowSocketExceptionMsg(env, "java/net/SocketException", "poll error!!", result); return JNI_FALSE; // // Error. // if (errno == EINTR) { // return JNI_FALSE; // } else { // jniThrowSocketException(env, errno); // return JNI_FALSE; // } } // Translate the result into the int[] we're supposed to fill in. ScopedIntArrayRW flagArray(env, outFlags); if (flagArray.get() == NULL) { return JNI_FALSE; } jint *flags = flagArray.get(); for (i = 0; i < result; i++) { if ((rfds[i].evts & XI_POLL_EVENT_IN) == XI_POLL_EVENT_IN) { for (int j = 0; j < countReadC; j++) { jobject tofd = env->GetObjectArrayElement(readFDArray, j); const int tfd = jniGetFDFromFileDescriptor(env, tofd); if (tfd == rfds[i].desc) { flags[j] = SOCKET_OP_READ; } else { flags[j] = SOCKET_OP_NONE; } } } if ((rfds[i].evts & XI_POLL_EVENT_OUT) == XI_POLL_EVENT_OUT) { for (int j = 0; j < countWriteC; j++) { jobject tofd = env->GetObjectArrayElement(writeFDArray, j); const int tfd = jniGetFDFromFileDescriptor(env, tofd); if (tfd == rfds[i].desc) { flags[j + countReadC] = SOCKET_OP_WRITE; } else { flags[j + countReadC] = SOCKET_OP_NONE; } } } } // return translateFdSet(env, readFDArray, countReadC, readFds, // flagArray.get(), 0, SOCKET_OP_READ) && translateFdSet(env, // writeFDArray, countWriteC, writeFds, flagArray.get(), countReadC, // SOCKET_OP_WRITE); return JNI_TRUE; } /* static jobject OSNetworkSystem_getSocketLocalAddress(JNIEnv* env, jobject, jobject fileDescriptor) { */ JNIEXPORT jobject JNICALL Java_org_apache_harmony_luni_platform_OSNetworkSystem_getSocketLocalAddress( JNIEnv* env, jobject, jobject fileDescriptor) { NetFd fd(env, fileDescriptor); if (fd.isClosed()) { return NULL; } xi_sock_addr_t ss; int rc = xi_socket_get_local(fd.get(), &ss); if (rc < 0) { // TODO: the public API doesn't allow failure, so this whole method // represents a broken design. In practice, though, getsockname can't // fail unless we give it invalid arguments. log_error(XDLOG, "getsockname failed: get local address (errno=%i)", rc); return NULL; } return socketAddressToInetAddress(env, &ss); } /* static jint OSNetworkSystem_getSocketLocalPort(JNIEnv* env, jobject, jobject fileDescriptor) { */ JNIEXPORT jint JNICALL Java_org_apache_harmony_luni_platform_OSNetworkSystem_getSocketLocalPort( JNIEnv* env, jobject, jobject fileDescriptor) { NetFd fd(env, fileDescriptor); if (fd.isClosed()) { return 0; } xi_sock_addr_t ss; int rc = xi_socket_get_local(fd.get(), &ss); if (rc < 0) { // TODO: the public API doesn't allow failure, so this whole method // represents a broken design. In practice, though, getsockname can't // fail unless we give it invalid arguments. log_error(XDLOG, "getsockname failed: get local address (errno=%i)", rc); return 0; } return getSocketAddressPort(&ss); } /* template<typename T> static bool getSocketOption(JNIEnv* env, const NetFd& fd, int level, int option, T* value) { socklen_t size = sizeof(*value); int rc = getsockopt(fd.get(), level, option, value, &size); if (rc < 0) { log_print(XDLOG, "getSocketOption(fd=%i, level=%i, option=%i) failed: (errno=%i)", fd.get(), level, option, rc); jniThrowSocketExceptionMsg(env, "java/net/SocketException", "get socket option error!!", rc); //jniThrowSocketException(env, errno); return false; } return true; } static jobject getSocketOption_Boolean(JNIEnv* env, const NetFd& fd, int level, int option) { int value; return getSocketOption(env, fd, level, option, &value) ? booleanValueOf( env, value) : NULL; } static jobject getSocketOption_Integer(JNIEnv* env, const NetFd& fd, int level, int option) { int value; return getSocketOption(env, fd, level, option, &value) ? integerValueOf( env, value) : NULL; } */ //static jobject OSNetworkSystem_getSocketOption(JNIEnv* env, jobject, jobject fileDescriptor, jint option) { JNIEXPORT jobject JNICALL Java_org_apache_harmony_luni_platform_OSNetworkSystem_getSocketOption( JNIEnv* env, jobject, jobject fileDescriptor, jint option) { NetFd fd(env, fileDescriptor); if (fd.isClosed()) { return NULL; } int family = getSocketAddressFamily(fd.get()); if (family != XI_SOCK_FAMILY_INET && family != XI_SOCK_FAMILY_INET6) { jniThrowSocketExceptionMsg(env, "java/net/SocketException", "get socket option not support!!", 0); //jniThrowSocketException(env, EAFNOSUPPORT); return NULL; } xint32 val; switch (option) { case JAVASOCKOPT_TCP_NODELAY: // return getSocketOption_Boolean(env, fd, IPPROTO_TCP, TCP_NODELAY); //log_trace(XDLOG, "!!!!!!!!!!!!!!!!!!!!!!!!!! JAVASOCKOPT_TCP_NODELAY\n"); return booleanValueOf(env, JNI_FALSE); case JAVASOCKOPT_SO_SNDBUF: xi_socket_opt_get(fd.get(), XI_SOCK_OPT_SENDBUF, &val); //log_trace(XDLOG, "!!!!!!!!!!!!!!!!!!!!!!!!!! JAVASOCKOPT_SO_SNDBUF\n"); return integerValueOf(env, val); //return getSocketOption_Integer(env, fd, SOL_SOCKET, SO_SNDBUF); case JAVASOCKOPT_SO_RCVBUF: xi_socket_opt_get(fd.get(), XI_SOCK_OPT_RECVBUF, &val); //log_trace(XDLOG, "!!!!!!!!!!!!!!!!!!!!!!!!!! JAVASOCKOPT_SO_RCVBUF\n"); return integerValueOf(env, val); //return getSocketOption_Integer(env, fd, SOL_SOCKET, SO_RCVBUF); case JAVASOCKOPT_SO_BROADCAST: // return getSocketOption_Boolean(env, fd, SOL_SOCKET, SO_BROADCAST); //log_trace(XDLOG, "!!!!!!!!!!!!!!!!!!!!!!!!!! JAVASOCKOPT_SO_BROADCAST\n"); return booleanValueOf(env, JNI_FALSE); case JAVASOCKOPT_SO_REUSEADDR: xi_socket_opt_get(fd.get(), XI_SOCK_OPT_REUSEADDR, &val); //log_trace(XDLOG, "!!!!!!!!!!!!!!!!!!!!!!!!!! JAVASOCKOPT_SO_REUSEADDR\n"); return booleanValueOf(env, val); //return getSocketOption_Boolean(env, fd, SOL_SOCKET, SO_REUSEADDR); case JAVASOCKOPT_SO_KEEPALIVE: xi_socket_opt_get(fd.get(), XI_SOCK_OPT_KEEPALIVE, &val); //log_trace(XDLOG, "!!!!!!!!!!!!!!!!!!!!!!!!!! JAVASOCKOPT_SO_KEEPALIVE\n"); return booleanValueOf(env, val); //return getSocketOption_Boolean(env, fd, SOL_SOCKET, SO_KEEPALIVE); case JAVASOCKOPT_SO_OOBINLINE: // return getSocketOption_Boolean(env, fd, SOL_SOCKET, SO_OOBINLINE); //log_trace(XDLOG, "!!!!!!!!!!!!!!!!!!!!!!!!!! JAVASOCKOPT_SO_OOBINLINE\n"); return booleanValueOf(env, JNI_FALSE); case JAVASOCKOPT_IP_TOS: // if (family == AF_INET) { // return getSocketOption_Integer(env, fd, IPPROTO_IP, IP_TOS); // } else { // return getSocketOption_Integer(env, fd, IPPROTO_IPV6, IPV6_TCLASS); // } //log_trace(XDLOG, "!!!!!!!!!!!!!!!!!!!!!!!!!! JAVASOCKOPT_IP_TOS\n"); return 0; case JAVASOCKOPT_SO_LINGER: xi_socket_opt_get(fd.get(), XI_SOCK_OPT_LINGER, &val); //log_trace(XDLOG, "!!!!!!!!!!!!!!!!!!!!!!!!!! JAVASOCKOPT_SO_LINGER\n"); return integerValueOf(env, val); // { // linger lingr; // bool ok = getSocketOption(env, fd, SOL_SOCKET, SO_LINGER, &lingr); // if (!ok) { // return NULL; // We already threw. // } else if (!lingr.l_onoff) { // return booleanValueOf(env, false); // } else { // return integerValueOf(env, lingr.l_linger); // } // } case JAVASOCKOPT_SO_TIMEOUT: { // timeval timeout; // bool ok = getSocketOption(env, fd, SOL_SOCKET, SO_RCVTIMEO, &timeout); // return ok ? integerValueOf(env, toMs(timeout)) : NULL; //log_trace(XDLOG, "!!!!!!!!!!!!!!!!!!!!!!!!!! JAVASOCKOPT_SO_TIMEOUT\n"); return integerValueOf(env, 0); } #ifdef ENABLE_MULTICAST case JAVASOCKOPT_IP_MULTICAST_IF: { // Although setsockopt(2) can take an ip_mreqn for IP_MULTICAST_IF, getsockopt(2) // always returns an in_addr. // sockaddr_storage ss; // memset(&ss, 0, sizeof(ss)); // ss.ss_family = AF_INET; // This call is IPv4-only. // sockaddr_in* sa = reinterpret_cast<sockaddr_in*> (&ss); // if (!getSocketOption(env, fd, IPPROTO_IP, IP_MULTICAST_IF, // &sa->sin_addr)) { // return NULL; // } xi_sock_addr_t ss; ss.family = XI_SOCK_FAMILY_INET; xi_strcpy(ss.host, "0.0.0.0"); return socketAddressToInetAddress(env, &ss); } case JAVASOCKOPT_IP_MULTICAST_IF2: if (family == XI_SOCK_FAMILY_INET) { // The caller's asking for an interface index, but that's not how IPv4 works. // Our Java should never get here, because we'll try IP_MULTICAST_IF first and // that will satisfy us. jniThrowSocketExceptionMsg(env, "java/net/SocketException", "Not Supported!!!", -1); //jniThrowSocketException(env, EAFNOSUPPORT); } else { // return getSocketOption_Integer(env, fd, IPPROTO_IPV6, // IPV6_MULTICAST_IF); return integerValueOf(env, 0); } case JAVASOCKOPT_IP_MULTICAST_LOOP: if (family == XI_SOCK_FAMILY_INET) { // Although IPv6 was cleaned up to use int, IPv4 multicast loopback uses a byte. // u_char loopback; // bool ok = getSocketOption(env, fd, IPPROTO_IP, IP_MULTICAST_LOOP, // &loopback); // return ok ? booleanValueOf(env, loopback) : NULL; return booleanValueOf(env, JNI_FALSE); } else { // return getSocketOption_Boolean(env, fd, IPPROTO_IPV6, // IPV6_MULTICAST_LOOP); return booleanValueOf(env, JNI_FALSE); } case JAVASOCKOPT_MULTICAST_TTL: if (family == XI_SOCK_FAMILY_INET) { // Although IPv6 was cleaned up to use int, and IPv4 non-multicast TTL uses int, // IPv4 multicast TTL uses a byte. // u_char ttl; // bool ok = getSocketOption(env, fd, IPPROTO_IP, IP_MULTICAST_TTL, // &ttl); // return ok ? integerValueOf(env, ttl) : NULL; return integerValueOf(env, 64); } else { // return getSocketOption_Integer(env, fd, IPPROTO_IPV6, // IPV6_MULTICAST_HOPS); return integerValueOf(env, 64); } #else case JAVASOCKOPT_MULTICAST_TTL: case JAVASOCKOPT_IP_MULTICAST_IF: case JAVASOCKOPT_IP_MULTICAST_IF2: case JAVASOCKOPT_IP_MULTICAST_LOOP: jniThrowException(env, "java/lang/UnsupportedOperationException", NULL); return NULL; #endif // def ENABLE_MULTICAST default: jniThrowSocketExceptionMsg(env, "java/net/SocketException", "get socket option!!", 0); //jniThrowSocketException(env, ENOPROTOOPT); return NULL; } } /* template<typename T> static void setSocketOption(JNIEnv* env, const NetFd& fd, int level, int option, T* value) { int rc = setsockopt(fd.get(), level, option, value, sizeof(*value)); if (rc < 0) { log_print(XDLOG, "setSocketOption(fd=%i, level=%i, option=%i) failed: (errno=%i)", fd.get(), level, option, rc); jniThrowSocketExceptionMsg(env, "java/net/SocketException", "get socket option error!!", rc); //jniThrowSocketException(env, errno); } } */ //static void OSNetworkSystem_setSocketOption(JNIEnv* env, jobject, jobject fileDescriptor, jint option, jobject optVal) { JNIEXPORT void JNICALL Java_org_apache_harmony_luni_platform_OSNetworkSystem_setSocketOption( JNIEnv* env, jobject, jobject fileDescriptor, jint option, jobject optVal) { NetFd fd(env, fileDescriptor); if (fd.isClosed()) { return; } int intVal = 0; bool wasBoolean = false; UNUSED(wasBoolean); jclass integerClass = env->FindClass("java/lang/Integer"); jclass booleanClass = env->FindClass("java/lang/Boolean"); jclass inetAddressClass = env->FindClass("java/net/InetAddress"); jclass multicastGroupRequestClass = env->FindClass( "java/net/MulticastGroupRequest"); if (env->IsInstanceOf(optVal, integerClass)) { jfieldID integer_class_value = env->GetFieldID(integerClass, "value", "I"); intVal = (int) env->GetIntField(optVal, integer_class_value); } else if (env->IsInstanceOf(optVal, booleanClass)) { jfieldID boolean_class_value = env->GetFieldID(booleanClass, "value", "Z"); intVal = (int) env->GetBooleanField(optVal, boolean_class_value); wasBoolean = true; } else if (env->IsInstanceOf(optVal, inetAddressClass)) { // We use optVal directly as an InetAddress for IP_MULTICAST_IF. } else if (env->IsInstanceOf(optVal, multicastGroupRequestClass)) { // We use optVal directly as a MulticastGroupRequest for MCAST_JOIN_GROUP/MCAST_LEAVE_GROUP. } else { jniThrowSocketExceptionMsg(env, "java/net/SocketException", "cannot get the java member field!!", 0); return; } int family = getSocketAddressFamily(fd.get()); if (family != XI_SOCK_FAMILY_INET && family != XI_SOCK_FAMILY_INET6) { jniThrowSocketExceptionMsg(env, "java/net/SocketException", "set socket option not support!!", 0); //jniThrowSocketException(env, EAFNOSUPPORT); return; } // Since we expect to have a AF_INET6 socket even if we're communicating via IPv4, we always // set the IPPROTO_IP options. As long as we fall back to creating IPv4 sockets if creating // an IPv6 socket fails, we need to make setting the IPPROTO_IPV6 options conditional. switch (option) { case JAVASOCKOPT_IP_TOS: // setSocketOption(env, fd, IPPROTO_IP, IP_TOS, &intVal); // if (family == AF_INET6) { // setSocketOption(env, fd, IPPROTO_IPV6, IPV6_TCLASS, &intVal); // } //log_trace(XDLOG, "!!!!!!!!!!!!!!!!!!!!!!!!!! JAVASOCKOPT_IP_TOS\n"); return; case JAVASOCKOPT_SO_BROADCAST: //setSocketOption(env, fd, SOL_SOCKET, SO_BROADCAST, &intVal); //log_trace(XDLOG, "!!!!!!!!!!!!!!!!!!!!!!!!!! JAVASOCKOPT_SO_BROADCAST\n"); return; case JAVASOCKOPT_SO_KEEPALIVE: xi_socket_opt_set(fd.get(), XI_SOCK_OPT_KEEPALIVE, intVal); //setSocketOption(env, fd, SOL_SOCKET, SO_KEEPALIVE, &intVal); //log_trace(XDLOG, "!!!!!!!!!!!!!!!!!!!!!!!!!! JAVASOCKOPT_SO_KEEPALIVE\n"); return; case JAVASOCKOPT_SO_LINGER: xi_socket_opt_set(fd.get(), XI_SOCK_OPT_LINGER, intVal); //log_trace(XDLOG, "!!!!!!!!!!!!!!!!!!!!!!!!!! JAVASOCKOPT_SO_LINGER\n"); return; // { // linger l; // l.l_onoff = !wasBoolean; // l.l_linger = intVal <= 65535 ? intVal : 65535; // setSocketOption(env, fd, SOL_SOCKET, SO_LINGER, &l); // return; // } case JAVASOCKOPT_SO_OOBINLINE: // setSocketOption(env, fd, SOL_SOCKET, SO_OOBINLINE, &intVal); //log_trace(XDLOG, "!!!!!!!!!!!!!!!!!!!!!!!!!! JAVASOCKOPT_SO_OOBINLINE\n"); return; case JAVASOCKOPT_SO_RCVBUF: xi_socket_opt_set(fd.get(), XI_SOCK_OPT_RECVBUF, intVal); //setSocketOption(env, fd, SOL_SOCKET, SO_RCVBUF, &intVal); //log_trace(XDLOG, "!!!!!!!!!!!!!!!!!!!!!!!!!! JAVASOCKOPT_SO_RCVBUF\n"); return; case JAVASOCKOPT_SO_REUSEADDR: xi_socket_opt_set(fd.get(), XI_SOCK_OPT_REUSEADDR, intVal); //setSocketOption(env, fd, SOL_SOCKET, SO_REUSEADDR, &intVal); //log_trace(XDLOG, "!!!!!!!!!!!!!!!!!!!!!!!!!! JAVASOCKOPT_SO_REUSEADDR\n"); return; case JAVASOCKOPT_SO_SNDBUF: xi_socket_opt_set(fd.get(), XI_SOCK_OPT_SENDBUF, intVal); //setSocketOption(env, fd, SOL_SOCKET, SO_SNDBUF, &intVal); //log_trace(XDLOG, "!!!!!!!!!!!!!!!!!!!!!!!!!! JAVASOCKOPT_SO_SNDBUF\n"); return; case JAVASOCKOPT_SO_TIMEOUT: { xi_socket_opt_set(fd.get(), XI_SOCK_OPT_SNDTIMEO, intVal); xi_socket_opt_set(fd.get(), XI_SOCK_OPT_RCVTIMEO, intVal); // timeval timeout(toTimeval(intVal)); // setSocketOption(env, fd, SOL_SOCKET, SO_RCVTIMEO, &timeout); //log_trace(XDLOG, "!!!!!!!!!!!!!!!!!!!!!!!!!! JAVASOCKOPT_SO_TIMEOUT\n"); return; } case JAVASOCKOPT_TCP_NODELAY: // setSocketOption(env, fd, IPPROTO_TCP, TCP_NODELAY, &intVal); //log_trace(XDLOG, "!!!!!!!!!!!!!!!!!!!!!!!!!! JAVASOCKOPT_TCP_NODELAY\n"); return; #ifdef ENABLE_MULTICAST case JAVASOCKOPT_MCAST_JOIN_GROUP: mcastJoinLeaveGroup(env, fd.get(), optVal, true); return; case JAVASOCKOPT_MCAST_LEAVE_GROUP: mcastJoinLeaveGroup(env, fd.get(), optVal, false); return; case JAVASOCKOPT_IP_MULTICAST_IF: { xi_sock_addr_t sockVal; jclass inetAddressClass = env->FindClass("java/net/InetAddress"); if (!env->IsInstanceOf(optVal, inetAddressClass) || !inetAddressToSocketAddress(env, optVal, 0, &sockVal)) { return; } // This call is IPv4 only. The socket may be IPv6, but the address // that identifies the interface to join must be an IPv4 address. if (sockVal.family != XI_SOCK_FAMILY_INET) { jniThrowSocketExceptionMsg(env, "java/net/SocketException", "Not Supported!!", 0); //jniThrowSocketException(env, EAFNOSUPPORT); return; } // ip_mreqn mcast_req; // memset(&mcast_req, 0, sizeof(mcast_req)); // mcast_req.imr_address // = reinterpret_cast<sockaddr_in*> (&sockVal)->sin_addr; // setSocketOption(env, fd, IPPROTO_IP, IP_MULTICAST_IF, &mcast_req); return; } case JAVASOCKOPT_IP_MULTICAST_IF2: // TODO: is this right? should we unconditionally set the IPPROTO_IP state in case // we have an IPv6 socket communicating via IPv4? if (family == XI_SOCK_FAMILY_INET) { // IP_MULTICAST_IF expects a pointer to an ip_mreqn struct. // ip_mreqn multicastRequest; // memset(&multicastRequest, 0, sizeof(multicastRequest)); // multicastRequest.imr_ifindex = intVal; // setSocketOption(env, fd, IPPROTO_IP, IP_MULTICAST_IF, // &multicastRequest); } else { // IPV6_MULTICAST_IF expects a pointer to an integer. // setSocketOption(env, fd, IPPROTO_IPV6, IPV6_MULTICAST_IF, &intVal); } return; case JAVASOCKOPT_MULTICAST_TTL: { // Although IPv6 was cleaned up to use int, and IPv4 non-multicast TTL uses int, // IPv4 multicast TTL uses a byte. // u_char ttl = intVal; // setSocketOption(env, fd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl); // if (family == AF_INET6) { // setSocketOption(env, fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &intVal); // } return; } case JAVASOCKOPT_IP_MULTICAST_LOOP: { // Although IPv6 was cleaned up to use int, IPv4 multicast loopback uses a byte. // u_char loopback = intVal; // setSocketOption(env, fd, IPPROTO_IP, IP_MULTICAST_LOOP, &loopback); // if (family == AF_INET6) { // setSocketOption(env, fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &intVal); // } return; } #else case JAVASOCKOPT_MULTICAST_TTL: case JAVASOCKOPT_MCAST_JOIN_GROUP: case JAVASOCKOPT_MCAST_LEAVE_GROUP: case JAVASOCKOPT_IP_MULTICAST_IF: case JAVASOCKOPT_IP_MULTICAST_IF2: case JAVASOCKOPT_IP_MULTICAST_LOOP: jniThrowException(env, "java/lang/UnsupportedOperationException", NULL); return; #endif // def ENABLE_MULTICAST default: jniThrowSocketExceptionMsg(env, "java/net/SocketException", "set socket option!!", 0); } } static void doShutdown(JNIEnv* env, jobject fileDescriptor, xi_sock_shutdown_e how) { NetFd fd(env, fileDescriptor); if (fd.isClosed()) { return; } int rc = xi_socket_shutdown(fd.get(), how); if (rc < 0) { jniThrowSocketExceptionMsg(env, "java/net/SocketException", "shutdown error!!", rc); //jniThrowSocketException(env, errno); } } //static void OSNetworkSystem_shutdownInput(JNIEnv* env, jobject, jobject fd) { JNIEXPORT void JNICALL Java_org_apache_harmony_luni_platform_OSNetworkSystem_shutdownInput( JNIEnv* env, jobject, jobject fd) { doShutdown(env, fd, XI_SOCK_SHUTDOWN_RD); } //static void OSNetworkSystem_shutdownOutput(JNIEnv* env, jobject, jobject fd) { JNIEXPORT void JNICALL Java_org_apache_harmony_luni_platform_OSNetworkSystem_shutdownOutput( JNIEnv* env, jobject, jobject fd) { doShutdown(env, fd, XI_SOCK_SHUTDOWN_WR); } //static void OSNetworkSystem_close(JNIEnv* env, jobject, jobject fileDescriptor) { JNIEXPORT void JNICALL Java_org_apache_harmony_luni_platform_OSNetworkSystem_close(JNIEnv* env, jobject, jobject fileDescriptor) { NetFd fd(env, fileDescriptor); if (fd.isClosed()) { return; } int oldFd = fd.get(); jniSetFileDescriptorOfFD(env, fileDescriptor, -1); AsynchronousSocketCloseMonitor::signalBlockedThreads(oldFd); xi_socket_close(oldFd); } /* by jshwang static JNINativeMethod gMethods[] = { NATIVE_METHOD(OSNetworkSystem, accept, "(Ljava/io/FileDescriptor;Ljava/net/SocketImpl;Ljava/io/FileDescriptor;)V"), NATIVE_METHOD(OSNetworkSystem, bind, "(Ljava/io/FileDescriptor;Ljava/net/InetAddress;I)V"), NATIVE_METHOD(OSNetworkSystem, close, "(Ljava/io/FileDescriptor;)V"), NATIVE_METHOD(OSNetworkSystem, connectNonBlocking, "(Ljava/io/FileDescriptor;Ljava/net/InetAddress;I)Z"), NATIVE_METHOD(OSNetworkSystem, connect, "(Ljava/io/FileDescriptor;Ljava/net/InetAddress;II)V"), NATIVE_METHOD(OSNetworkSystem, disconnectDatagram, "(Ljava/io/FileDescriptor;)V"), NATIVE_METHOD(OSNetworkSystem, getSocketLocalAddress, "(Ljava/io/FileDescriptor;)Ljava/net/InetAddress;"), NATIVE_METHOD(OSNetworkSystem, getSocketLocalPort, "(Ljava/io/FileDescriptor;)I"), NATIVE_METHOD(OSNetworkSystem, getSocketOption, "(Ljava/io/FileDescriptor;I)Ljava/lang/Object;"), NATIVE_METHOD(OSNetworkSystem, isConnected, "(Ljava/io/FileDescriptor;I)Z"), NATIVE_METHOD(OSNetworkSystem, listen, "(Ljava/io/FileDescriptor;I)V"), NATIVE_METHOD(OSNetworkSystem, read, "(Ljava/io/FileDescriptor;[BII)I"), NATIVE_METHOD(OSNetworkSystem, readDirect, "(Ljava/io/FileDescriptor;II)I"), NATIVE_METHOD(OSNetworkSystem, recv, "(Ljava/io/FileDescriptor;Ljava/net/DatagramPacket;[BIIZZ)I"), NATIVE_METHOD(OSNetworkSystem, recvDirect, "(Ljava/io/FileDescriptor;Ljava/net/DatagramPacket;IIIZZ)I"), NATIVE_METHOD(OSNetworkSystem, selectImpl, "([Ljava/io/FileDescriptor;[Ljava/io/FileDescriptor;II[IJ)Z"), NATIVE_METHOD(OSNetworkSystem, send, "(Ljava/io/FileDescriptor;[BIIILjava/net/InetAddress;)I"), NATIVE_METHOD(OSNetworkSystem, sendDirect, "(Ljava/io/FileDescriptor;IIIILjava/net/InetAddress;)I"), NATIVE_METHOD(OSNetworkSystem, sendUrgentData, "(Ljava/io/FileDescriptor;B)V"), NATIVE_METHOD(OSNetworkSystem, setInetAddress, "(Ljava/net/InetAddress;[B)V"), NATIVE_METHOD(OSNetworkSystem, setSocketOption, "(Ljava/io/FileDescriptor;ILjava/lang/Object;)V"), NATIVE_METHOD(OSNetworkSystem, shutdownInput, "(Ljava/io/FileDescriptor;)V"), NATIVE_METHOD(OSNetworkSystem, shutdownOutput, "(Ljava/io/FileDescriptor;)V"), NATIVE_METHOD(OSNetworkSystem, socket, "(Ljava/io/FileDescriptor;Z)V"), NATIVE_METHOD(OSNetworkSystem, write, "(Ljava/io/FileDescriptor;[BII)I"), NATIVE_METHOD(OSNetworkSystem, writeDirect, "(Ljava/io/FileDescriptor;III)I"), }; int register_org_apache_harmony_luni_platform_OSNetworkSystem(JNIEnv* env) { AsynchronousSocketCloseMonitor::init(); return initCachedFields(env) && jniRegisterNativeMethods(env, "org/apache/harmony/luni/platform/OSNetworkSystem", gMethods, NELEM(gMethods)); } */ int register_org_apache_harmony_luni_platform_OSNetworkSystem(JNIEnv*) { AsynchronousSocketCloseMonitor::init(); return JNI_OK; // return initCachedFields(env); }
33.895361
160
0.708173
webos21
9fa23845bd9ae69dfeeb888d6b0af48eb27c2ade
2,329
cpp
C++
training/POJ/2923.cpp
voleking/ICPC
fc2cf408fa2607ad29b01eb00a1a212e6d0860a5
[ "MIT" ]
68
2017-10-08T04:44:23.000Z
2019-08-06T20:15:02.000Z
training/POJ/2923.cpp
voleking/ICPC
fc2cf408fa2607ad29b01eb00a1a212e6d0860a5
[ "MIT" ]
null
null
null
training/POJ/2923.cpp
voleking/ICPC
fc2cf408fa2607ad29b01eb00a1a212e6d0860a5
[ "MIT" ]
18
2017-05-31T02:52:23.000Z
2019-07-05T09:18:34.000Z
#include <cctype> #include <cfloat> #include <climits> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <string> #include <sstream> #include <algorithm> #include <complex> #include <deque> #include <list> #include <map> #include <queue> #include <set> #include <stack> #include <vector> #include <utility> #include <bitset> #define IOS std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); // #define __DEBUG__ #ifdef __DEBUG__ #define DEBUG(...) printf(__VA_ARGS__) #else #define DEBUG(...) #endif #define filename "" #define setfile() freopen(filename".in", "r", stdin); freopen(filename".out", "w", stdout); using namespace std; typedef long l; typedef long long ll; typedef unsigned long long ull; typedef unsigned long ul; typedef long double ld; typedef pair<int, int > Pii; const double pi = acos(-1.0); const int INF = INT_MAX; const int MAX_N = 10; const int MAX_W = 100 + 10; template <typename T> inline T sqr(T a) { return a * a;}; int N, C1, C2, W[MAX_N], dp[(1 << MAX_N) + 5], cases = 0; bool check(int S) { bool flag[MAX_W]; int sum = 0; memset(flag, 0, sizeof flag); flag[0] = 1; for (int i = 0; i < N; ++i) if (S >> i & 1) { sum += W[i]; for (int j = C1; j >= W[i]; --j) flag[j] |= flag[j - W[i]]; } for (int i = C1; i >= 0; --i) if (flag[i] && sum - i <= C2) return 1; return 0; } int main(int argc, char const *argv[]) { int t; scanf("%d", &t); while (t--) { scanf("%d%d%d", &N, &C1, &C2); if (C1 > C2) swap(C1, C2); for (int i = 0; i < N; ++i) scanf("%d", W + i); vector<int> v; for (int i = 1; i < 1 << N; ++i) if (check(i)) v.push_back(i); // for (auto x : v) // cout << x << endl; for (int i = 1; i < 1 << N; ++i) dp[i] = INF; dp[0] = 0; for (int i = 0; i < v.size(); ++i) for (int j = (1 << N) - 1 - v[i]; j >= 0; j--) if (!(j & v[i]) && dp[j] != INF) dp[j | v[i]] = min(dp[j] + 1, dp[j | v[i]]); printf("Scenario #%d:\n%d\n\n", ++cases, dp[(1 << N) - 1]); } return 0; }
24.010309
92
0.502362
voleking
9fa77f7f0f4bb47b995986a46df2dc868c12fe62
16,389
cpp
C++
Source/Lutefisk3D/Graphics/Technique.cpp
Lutefisk3D/lutefisk3d
d2132b82003427511df0167f613905191b006eb5
[ "Apache-2.0" ]
2
2018-04-14T19:05:23.000Z
2020-05-10T22:42:12.000Z
Source/Lutefisk3D/Graphics/Technique.cpp
Lutefisk3D/lutefisk3d
d2132b82003427511df0167f613905191b006eb5
[ "Apache-2.0" ]
4
2015-06-19T22:32:07.000Z
2017-04-05T06:01:50.000Z
Source/Lutefisk3D/Graphics/Technique.cpp
nemerle/lutefisk3d
d2132b82003427511df0167f613905191b006eb5
[ "Apache-2.0" ]
1
2015-12-27T15:36:10.000Z
2015-12-27T15:36:10.000Z
// // Copyright (c) 2008-2017 the Urho3D project. // // 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 "Technique.h" #include "Material.h" #include "Lutefisk3D/Core/Context.h" #include "Graphics.h" #include "GraphicsDefs.h" #include "Lutefisk3D/IO/Log.h" #include "Lutefisk3D/Core/ProcessUtils.h" #include "Lutefisk3D/Core/StringUtils.h" #include "Lutefisk3D/Core/Profiler.h" #include "Lutefisk3D/Resource/ResourceCache.h" #include "ShaderVariation.h" #include "Lutefisk3D/Resource/XMLFile.h" namespace Urho3D { const char* blendModeNames[MAX_BLENDMODES+1] = { "replace", "add", "multiply", "alpha", "addalpha", "premulalpha", "invdestalpha", "subtract", "subtractalpha", "zeroinvsrc", nullptr }; static const char* compareModeNames[MAX_COMPAREMODES+1] = { "always", "equal", "notequal", "less", "lessequal", "greater", "greaterequal", nullptr }; static const char* lightingModeNames[] = { "unlit", "pervertex", "perpixel", nullptr }; Pass::Pass(const QString& name) : blendMode_(BLEND_REPLACE), cullMode_(MAX_CULLMODES), depthTestMode_(CMP_LESSEQUAL), lightingMode_(LIGHTING_UNLIT), shadersLoadedFrameNumber_(0), alphaToCoverage_(false), depthWrite_(true) { name_ = name.toLower(); index_ = Technique::GetPassIndex(name_); // Guess default lighting mode from pass name if (index_ == Technique::basePassIndex || index_ == Technique::alphaPassIndex || index_ == Technique::materialPassIndex || index_ == Technique::deferredPassIndex) lightingMode_ = LIGHTING_PERVERTEX; else if (index_ == Technique::lightPassIndex || index_ == Technique::litBasePassIndex || index_ == Technique::litAlphaPassIndex) lightingMode_ = LIGHTING_PERPIXEL; } Pass::~Pass() { } /// Set blend mode. void Pass::SetBlendMode(BlendMode mode) { blendMode_ = mode; } /// Set culling mode override. By default culling mode is read from the material instead. Set the illegal culling mode MAX_CULLMODES to disable override again. void Pass::SetCullMode(CullMode mode) { cullMode_ = mode; } /// Set depth compare mode. void Pass::SetDepthTestMode(CompareMode mode) { depthTestMode_ = mode; } /// Set pass lighting mode, affects what shader variations will be attempted to be loaded. void Pass::SetLightingMode(PassLightingMode mode) { lightingMode_ = mode; } /// Set depth write on/off. void Pass::SetDepthWrite(bool enable) { depthWrite_ = enable; } /// Set alpha-to-coverage on/off. void Pass::SetAlphaToCoverage(bool enable) { alphaToCoverage_ = enable; } /// Set vertex shader name. void Pass::SetVertexShader(const QString& name) { vertexShaderName_ = name; ReleaseShaders(); } /// Set pixel shader name. void Pass::SetPixelShader(const QString& name) { pixelShaderName_ = name; ReleaseShaders(); } /// Set vertex shader defines. Separate multiple defines with spaces. void Pass::SetVertexShaderDefines(const QString& defines) { vertexShaderDefines_ = defines; ReleaseShaders(); } /// Set pixel shader defines. Separate multiple defines with spaces. void Pass::SetPixelShaderDefines(const QString& defines) { pixelShaderDefines_ = defines; ReleaseShaders(); } /// Set vertex shader define excludes. Use to mark defines that the shader code will not recognize, to prevent compiling redundant shader variations. void Pass::SetVertexShaderDefineExcludes(const QString& excludes) { vertexShaderDefineExcludes_ = excludes; ReleaseShaders(); } /// Set pixel shader define excludes. Use to mark defines that the shader code will not recognize, to prevent compiling redundant shader variations. void Pass::SetPixelShaderDefineExcludes(const QString& excludes) { pixelShaderDefineExcludes_ = excludes; ReleaseShaders(); } /// Reset shader pointers. void Pass::ReleaseShaders() { vertexShaders_.clear(); pixelShaders_.clear(); extraVertexShaders_.clear(); extraPixelShaders_.clear(); } /// Mark shaders loaded this frame. void Pass::MarkShadersLoaded(unsigned frameNumber) { shadersLoadedFrameNumber_ = frameNumber; } QString Pass::GetEffectiveVertexShaderDefines() const { // Prefer to return just the original defines if possible if (vertexShaderDefineExcludes_.isEmpty()) return vertexShaderDefines_; QStringList vsDefines = vertexShaderDefines_.split(' '); QStringList vsExcludes = vertexShaderDefineExcludes_.split(' '); for (unsigned i = 0; i < vsExcludes.size(); ++i) vsDefines.removeAll(vsExcludes[i]); return vsDefines.join(" "); } QString Pass::GetEffectivePixelShaderDefines() const { // Prefer to return just the original defines if possible if (pixelShaderDefineExcludes_.isEmpty()) return pixelShaderDefines_; QStringList psDefines = pixelShaderDefines_.split(' '); QStringList psExcludes = pixelShaderDefineExcludes_.split(' '); for (unsigned i = 0; i < psExcludes.size(); ++i) psDefines.removeAll(psExcludes[i]); return psDefines.join(" "); } std::vector<SharedPtr<ShaderVariation> >& Pass::GetVertexShaders(const StringHash& extraDefinesHash) { // If empty hash, return the base shaders if (!extraDefinesHash.Value()) return vertexShaders_; return extraVertexShaders_[extraDefinesHash]; } std::vector<SharedPtr<ShaderVariation> >& Pass::GetPixelShaders(const StringHash& extraDefinesHash) { if (!extraDefinesHash.Value()) return pixelShaders_; return extraPixelShaders_[extraDefinesHash]; } unsigned Technique::basePassIndex = 0; unsigned Technique::alphaPassIndex = 0; unsigned Technique::materialPassIndex = 0; unsigned Technique::deferredPassIndex = 0; unsigned Technique::lightPassIndex = 0; unsigned Technique::litBasePassIndex = 0; unsigned Technique::litAlphaPassIndex = 0; unsigned Technique::shadowPassIndex = 0; HashMap<QString, unsigned> Technique::passIndices; Technique::Technique(Context* context) : Resource(context) { } Technique::~Technique() { } void Technique::RegisterObject(Context* context) { context->RegisterFactory<Technique>(); } bool Technique::BeginLoad(Deserializer& source) { passes_.clear(); cloneTechniques_.clear(); SetMemoryUse(sizeof(Technique)); SharedPtr<XMLFile> xml(new XMLFile(context_)); if (!xml->Load(source)) return false; XMLElement rootElem = xml->GetRoot(); QString globalVS = rootElem.GetAttribute("vs"); QString globalPS = rootElem.GetAttribute("ps"); QString globalVSDefines = rootElem.GetAttribute("vsdefines"); QString globalPSDefines = rootElem.GetAttribute("psdefines"); // End with space so that the pass-specific defines can be appended if (!globalVSDefines.isEmpty()) globalVSDefines += ' '; if (!globalPSDefines.isEmpty()) globalPSDefines += ' '; XMLElement passElem = rootElem.GetChild("pass"); for (;passElem; passElem = passElem.GetNext("pass")) { if (!passElem.HasAttribute("name")) { URHO3D_LOGERROR("Missing pass name"); continue; } Pass* newPass = CreatePass(passElem.GetAttribute("name")); // Append global defines only when pass does not redefine the shader if (passElem.HasAttribute("vs")) { newPass->SetVertexShader(passElem.GetAttribute("vs")); newPass->SetVertexShaderDefines(passElem.GetAttribute("vsdefines")); } else { newPass->SetVertexShader(globalVS); newPass->SetVertexShaderDefines(globalVSDefines + passElem.GetAttribute("vsdefines")); } if (passElem.HasAttribute("ps")) { newPass->SetPixelShader(passElem.GetAttribute("ps")); newPass->SetPixelShaderDefines(passElem.GetAttribute("psdefines")); } else { newPass->SetPixelShader(globalPS); newPass->SetPixelShaderDefines(globalPSDefines + passElem.GetAttribute("psdefines")); } newPass->SetVertexShaderDefineExcludes(passElem.GetAttribute("vsexcludes")); newPass->SetPixelShaderDefineExcludes(passElem.GetAttribute("psexcludes")); if (passElem.HasAttribute("lighting")) { QString lighting = passElem.GetAttributeLower("lighting"); newPass->SetLightingMode((PassLightingMode)GetStringListIndex(lighting, lightingModeNames, LIGHTING_UNLIT)); } if (passElem.HasAttribute("blend")) { QString blend = passElem.GetAttributeLower("blend"); newPass->SetBlendMode((BlendMode)GetStringListIndex(blend, blendModeNames, BLEND_REPLACE)); } if (passElem.HasAttribute("cull")) { QString cull = passElem.GetAttributeLower("cull"); newPass->SetCullMode((CullMode)GetStringListIndex(cull, cullModeNames, MAX_CULLMODES)); } if (passElem.HasAttribute("depthtest")) { QString depthTest = passElem.GetAttributeLower("depthtest"); if (depthTest == "false") newPass->SetDepthTestMode(CMP_ALWAYS); else newPass->SetDepthTestMode((CompareMode)GetStringListIndex(depthTest, compareModeNames, CMP_LESS)); } if (passElem.HasAttribute("depthwrite")) newPass->SetDepthWrite(passElem.GetBool("depthwrite")); if (passElem.HasAttribute("alphatocoverage")) newPass->SetAlphaToCoverage(passElem.GetBool("alphatocoverage")); } return true; } void Technique::ReleaseShaders() { for (SharedPtr<Pass> & pass : passes_) { if(pass) pass->ReleaseShaders(); } } SharedPtr<Technique> Technique::Clone(const QString& cloneName) const { SharedPtr<Technique> ret(new Technique(context_)); ret->SetName(cloneName); // Deep copy passes for (const auto &i : passes_) { Pass* srcPass = i.Get(); if (!srcPass) continue; Pass* newPass = ret->CreatePass(srcPass->GetName()); newPass->SetBlendMode(srcPass->GetBlendMode()); newPass->SetDepthTestMode(srcPass->GetDepthTestMode()); newPass->SetLightingMode(srcPass->GetLightingMode()); newPass->SetDepthWrite(srcPass->GetDepthWrite()); newPass->SetAlphaToCoverage(srcPass->GetAlphaToCoverage()); newPass->SetVertexShader(srcPass->GetVertexShader()); newPass->SetPixelShader(srcPass->GetPixelShader()); newPass->SetVertexShaderDefines(srcPass->GetVertexShaderDefines()); newPass->SetPixelShaderDefines(srcPass->GetPixelShaderDefines()); newPass->SetVertexShaderDefineExcludes(srcPass->GetVertexShaderDefineExcludes()); newPass->SetPixelShaderDefineExcludes(srcPass->GetPixelShaderDefineExcludes()); } return ret; } Pass* Technique::CreatePass(const QString& name) { Pass* oldPass = GetPass(name); if (oldPass) return oldPass; SharedPtr<Pass> newPass(new Pass(name)); unsigned passIndex = newPass->GetIndex(); //TODO: passes_ is essentialy an pass_id => Pass dictionary, mark it as one if (passIndex >= passes_.size()) passes_.resize(passIndex + 1); passes_[passIndex] = newPass; // Calculate memory use now SetMemoryUse(unsigned(sizeof(Technique) + GetNumPasses() * sizeof(Pass))); return newPass; } void Technique::RemovePass(const QString& name) { HashMap<QString, unsigned>::const_iterator i = passIndices.find(name.toLower()); if (i == passIndices.end()) return; if (MAP_VALUE(i) < passes_.size() && passes_[MAP_VALUE(i)].Get()) { passes_[MAP_VALUE(i)].Reset(); SetMemoryUse((unsigned)(sizeof(Technique) + GetNumPasses() * sizeof(Pass))); } } bool Technique::HasPass(const QString& name) const { HashMap<QString, unsigned>::const_iterator i = passIndices.find(name.toLower()); return i != passIndices.end() ? HasPass(MAP_VALUE(i)) : false; } Pass* Technique::GetPass(const QString& name) const { HashMap<QString, unsigned>::const_iterator i = passIndices.find(name.toLower()); return i != passIndices.end() ? GetPass(MAP_VALUE(i)) : nullptr; } Pass* Technique::GetSupportedPass(const QString& name) const { HashMap<QString, unsigned>::const_iterator i = passIndices.find(name.toLower()); return i != passIndices.end() ? GetSupportedPass(MAP_VALUE(i)) : nullptr; } unsigned Technique::GetNumPasses() const { unsigned ret = 0; for (std::vector<SharedPtr<Pass> >::const_iterator i = passes_.begin(); i != passes_.end(); ++i) { if (i->Get()) ++ret; } return ret; } std::vector<QString> Technique::GetPassNames() const { std::vector<QString> ret; ret.reserve(passes_.size()); for (const SharedPtr<Pass> &pass : passes_) { if (pass) ret.push_back(pass->GetName()); } return ret; } std::vector<Pass*> Technique::GetPasses() const { std::vector<Pass*> ret; ret.reserve(passes_.size()); for (const SharedPtr<Pass> &pass : passes_) { if (pass) ret.push_back(pass); } return ret; } SharedPtr<Technique> Technique::CloneWithDefines(const QString& vsDefines, const QString& psDefines) { // Return self if no actual defines if (vsDefines.isEmpty() && psDefines.isEmpty()) return SharedPtr<Technique>(this); std::pair<StringHash, StringHash> key = std::make_pair(StringHash(vsDefines), StringHash(psDefines)); // Return existing if possible auto iter = cloneTechniques_.find(key); if (iter != cloneTechniques_.end()) return MAP_VALUE(iter); // Set same name as the original for the clones to ensure proper serialization of the material. This should not be a problem // since the clones are never stored to the resource cache iter = cloneTechniques_.insert(std::make_pair(key, Clone(GetName()))).first; for (Pass *pass : MAP_VALUE(iter)->passes_) { if (!pass) continue; if (!vsDefines.isEmpty()) pass->SetVertexShaderDefines(pass->GetVertexShaderDefines() + " " + vsDefines); if (!psDefines.isEmpty()) pass->SetPixelShaderDefines(pass->GetPixelShaderDefines() + " " + psDefines); } return MAP_VALUE(iter); } unsigned Technique::GetPassIndex(const QString& passName) { // Initialize built-in pass indices on first call if (passIndices.empty()) { basePassIndex = passIndices["base"] = 0; alphaPassIndex = passIndices["alpha"] = 1; materialPassIndex = passIndices["material"] = 2; deferredPassIndex = passIndices["deferred"] = 3; lightPassIndex = passIndices["light"] = 4; litBasePassIndex = passIndices["litbase"] = 5; litAlphaPassIndex = passIndices["litalpha"] = 6; shadowPassIndex = passIndices["shadow"] = 7; } QString nameLower = passName.toLower(); HashMap<QString, unsigned>::iterator i = passIndices.find(nameLower); if (i != passIndices.end()) return MAP_VALUE(i); unsigned newPassIndex = passIndices.size(); passIndices[nameLower] = newPassIndex; return newPassIndex; } }
30.981096
159
0.680273
Lutefisk3D
9fa93990b20b2cb38fe1fcc5b1e486af5ec33b49
906
cpp
C++
src/engine/ui/src/ui/widgets/ui_gamepad_image.cpp
code-disaster/halley
5c85c889b76c69c6bdef6f4801c6aba282b7af80
[ "Apache-2.0" ]
3,262
2016-04-10T15:24:10.000Z
2022-03-31T17:47:08.000Z
src/engine/ui/src/ui/widgets/ui_gamepad_image.cpp
code-disaster/halley
5c85c889b76c69c6bdef6f4801c6aba282b7af80
[ "Apache-2.0" ]
53
2016-10-09T16:25:04.000Z
2022-01-10T13:52:37.000Z
src/engine/ui/src/ui/widgets/ui_gamepad_image.cpp
code-disaster/halley
5c85c889b76c69c6bdef6f4801c6aba282b7af80
[ "Apache-2.0" ]
193
2017-10-23T06:08:41.000Z
2022-03-22T12:59:58.000Z
#include "halley/ui/widgets/ui_gamepad_image.h" using namespace Halley; UIGamepadImage::UIGamepadImage(UIStyle style, JoystickButtonPosition button, std::function<Sprite(JoystickButtonPosition, JoystickType)> iconRetriever, Colour4f col) : UIImage(Sprite()) , style(style) , button(button) , iconRetriever(std::move(iconRetriever)) , colour(col) { setOnlyEnabledWithInputs({ UIInputType::Gamepad }); } void UIGamepadImage::update(Time t, bool moved) { UIImage::update(t, moved); } void UIGamepadImage::setJoystickType(JoystickType type) { if (type != curType) { curType = type; setSprite(iconRetriever(button, type).setColour(colour)); } } void UIGamepadImage::onGamepadInput(const UIInputResults& input, Time time) { if (input.isButtonPressed(UIGamepadInput::Button::Accept)) { sendEvent(UIEvent(UIEventType::ButtonClicked, getId())); playSound(style.getString("downSound")); } }
25.166667
165
0.758278
code-disaster
9fab6047b372e0878f52e5aaa59da9c9b6b8641e
1,777
cpp
C++
cpp/A0153/main.cpp
Modnars/LeetCode
1c91fe9598418e6ed72233260f9cd8d5737fe216
[ "Apache-2.0" ]
2
2021-11-26T14:06:13.000Z
2021-11-26T14:34:34.000Z
cpp/A0153/main.cpp
Modnars/LeetCode
1c91fe9598418e6ed72233260f9cd8d5737fe216
[ "Apache-2.0" ]
2
2021-11-26T14:06:49.000Z
2021-11-28T11:28:49.000Z
cpp/A0153/main.cpp
Modnars/LeetCode
1c91fe9598418e6ed72233260f9cd8d5737fe216
[ "Apache-2.0" ]
null
null
null
// URL : https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array/ // Author : Modnar // Date : 2020/03/14 // Thanks : armeria(@leetcode.cn) #include <bits/stdc++.h> /* ************************* */ /** * 暴力搜索 * 直接遍历,获取最小元素即可。 * 本题存在一个简单优化,当发现某两个值之间发生“递减”,则可直接返回最小值。 */ // Complexity: Time: O(n) Space: O(1) // Time: 8ms(44.19%) Memory: 11.5MB(5.04%) class Solution { public: int findMin(std::vector<int> &nums) { // 本题不存在nums为空的情况,故此处可免去判断以加速 int min_val = nums[0]; for (int i = 0; i != nums.size(); ++i) if (nums[i] < min_val) return nums[i]; return min_val; } }; /* ************************* */ /** * 二分搜索 * 充分利用题中所提到的数组元素不重复,这样,对于任意两个元素均可进行“偏序比较”。 * 首先需要明确以下几点:二分过程中,左右端点值为l、r,中间值为mid。如果nums[mid] > * nums[r],说明最小值一定在右半部分(相对mid来说);否则(nums[mid] < nums[r]),就说明 * 最小值一定在左半部分(相对mid来说)。 * 细分来说,思考以下方面: * 1. 循环条件l < r,且l <= mid,mid更贴近l,而mid < r; * 2. 在while循环内,nums[mid]要么小于nums[r],要么大于,而不会等于,这也就是循环 * 内直接使用else判断的原因。 */ namespace AnsOne { // Thanks: armeria(@leetcode.cn) // Solution: https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array/solution/er-fen-cha-zhao-wei-shi-yao-zuo-you-bu-dui-cheng-z/ // Time: 0ms(100.00%) Memory: 11.7MB(5.04%) class Solution { public: int findMin(std::vector<int> &nums) { int l = 0, r = nums.size() - 1; while (l < r) { int mid = l + ((r - l) >> 1); if (nums[mid] > nums[r]) { l = mid + 1; } else { r = mid; } } return nums[l]; } }; } int main(int argc, const char *argv[]) { return EXIT_SUCCESS; }
26.924242
147
0.517727
Modnars
9facdcebcc915c60cb029d28b96f99e5c8339ebd
10,445
cpp
C++
simplemd/molecule-mappings/VelocityStoermerVerletMapping.cpp
HSU-HPC/MaMiCo
d6f8597bd41ac3a5d3929c5eb4f7ecbc1b80e2ee
[ "BSD-4-Clause" ]
6
2021-02-06T17:21:10.000Z
2022-01-27T21:36:55.000Z
simplemd/molecule-mappings/VelocityStoermerVerletMapping.cpp
HSU-HPC/MaMiCo
d6f8597bd41ac3a5d3929c5eb4f7ecbc1b80e2ee
[ "BSD-4-Clause" ]
1
2021-06-24T15:17:46.000Z
2021-06-25T11:54:52.000Z
simplemd/molecule-mappings/VelocityStoermerVerletMapping.cpp
HSU-HPC/MaMiCo
d6f8597bd41ac3a5d3929c5eb4f7ecbc1b80e2ee
[ "BSD-4-Clause" ]
6
2021-12-16T11:39:24.000Z
2022-03-28T07:00:30.000Z
// Copyright (C) 2015 Technische Universitaet Muenchen // This file is part of the Mamico project. For conditions of distribution // and use, please see the copyright notice in Mamico's main folder, or at // www5.in.tum.de/mamico #include "simplemd/molecule-mappings/VelocityStoermerVerletMapping.h" simplemd::moleculemappings::VelocityStoermerVerletMapping::VelocityStoermerVerletMapping( const double& kB,const double& dt,const double& mass, const tarch::la::Vector<MD_LINKED_CELL_NEIGHBOURS,simplemd::BoundaryType>& boundary, const tarch::la::Vector<MD_DIM,double> &domainOffset, const tarch::la::Vector<MD_DIM,double> &domainSize ): _dt(dt), _a(_dt/(2.0*mass)),_zero(0.0), _boundary(initReflectingBoundary(boundary)), _domainOffset(domainOffset), _domainSize(domainSize) {} simplemd::moleculemappings::VelocityStoermerVerletMapping::~VelocityStoermerVerletMapping(){} void simplemd::moleculemappings::VelocityStoermerVerletMapping::beginMoleculeIteration(){} void simplemd::moleculemappings::VelocityStoermerVerletMapping::endMoleculeIteration(){} void simplemd::moleculemappings::VelocityStoermerVerletMapping::handleMolecule(Molecule &molecule){ // if the molecule is fixed in space, return immediately: if(molecule.isFixed()) return; // do time integration update (position and velocity) ------------------------------ tarch::la::Vector<MD_DIM,double> &position = molecule.getPosition(); const tarch::la::Vector<MD_DIM,double> oldPosition(molecule.getConstPosition()); #if (MD_ERROR==MD_YES) const tarch::la::Vector<MD_DIM,double> oldVelocity(molecule.getConstVelocity()); #endif tarch::la::Vector<MD_DIM,double> &velocity = molecule.getVelocity(); // v_n = v_(n-1) + a*(f_n + f_(n-1)) velocity += _a*(molecule.getConstForce() + molecule.getConstForceOld()); // x_(n+1) = x_n + dt*(v_n + a*f_n) position += _dt*( molecule.getConstVelocity() + _a*molecule.getConstForce() ); #if (MD_ERROR == MD_YES) for (unsigned int d = 0; d < MD_DIM; d++){ if ( std::isnan(position[d]) || std::isinf(position[d]) ){ std::cout << "ERROR simplemd::moleculemappings::VelocityStoermerVerletMapping::handleMolecule: Position "; std::cout << d << " is out of range" << std::endl; std::cout << "Position: " << position << ", molecule: " << molecule.getID() << std::endl; std::cout << "Velocity: " << velocity << ", molecule: " << molecule.getID() << std::endl; std::cout << "OldVelocity: " << oldVelocity << ", molecule: " << molecule.getID() << std::endl; std::cout << "Force: " << molecule.getConstForce() << ", old: " << molecule.getConstForceOld() << std::endl; std::cout << "Old position: " << oldPosition << std::endl; exit(EXIT_FAILURE); } if (std::isnan(velocity[d]) || std::isinf(velocity[d])){ std::cout << "ERROR simplemd::moleculemappings::VelocityStoermerVerletMapping::handleMolecule: Velocity "; std::cout << d << " is NaN or Inf" << std::endl; std::cout << velocity << std::endl; std::cout << molecule.getConstForce() << ", " << molecule.getConstForceOld() << std::endl; exit(EXIT_FAILURE); } } #endif // apply reflection for (unsigned int d = 0; d < MD_DIM; d++){ // left/front/bottom reflecting boundary if (_boundary[2*d] && (position[d]<_domainOffset[d]) ){ //std::cout << "Reflect particle " << position << " d=" << d << ", " << 2*d << std::endl; position[d] = position[d] + 2.0*(_domainOffset[d]-position[d]); velocity[d] = -velocity[d]; } // right/back/top reflecting boundary if (_boundary[2*d+1] && (position[d]>_domainOffset[d]+_domainSize[d]) ){ //std::cout << "Reflect particle " << position << " d=" << d << ", " << 2*d+1 << std::endl; position[d] = position[d] + 2.0*(_domainOffset[d]+_domainSize[d]-position[d]); velocity[d] = -velocity[d]; } } // store force in force_old molecule.setForceOld(molecule.getConstForce()); // reset force molecule.setForce(_zero); } tarch::la::Vector<2*MD_DIM,bool> simplemd::moleculemappings::VelocityStoermerVerletMapping:: initReflectingBoundary(const tarch::la::Vector<MD_LINKED_CELL_NEIGHBOURS,simplemd::BoundaryType>& boundary) const{ tarch::la::Vector<2*MD_DIM,bool> reflect; for (unsigned int d = 0; d < 2*MD_DIM; d++){reflect[d] = false;} // check 6 sides for reflecting boundaries #if (MD_DIM==1) if (boundary[0] == simplemd::REFLECTING_BOUNDARY){ reflect[0] = true; } if (boundary[1] == simplemd::REFLECTING_BOUNDARY){ reflect[1] = true; } #elif (MD_DIM==2) // bottom if (boundary[1] == simplemd::REFLECTING_BOUNDARY){ reflect[2] = true; if ( (boundary[0] != simplemd::REFLECTING_BOUNDARY) || (boundary[2] != simplemd::REFLECTING_BOUNDARY) ){ std::cout << "ERROR simplemd::moleculemappings::VelocityStoermerVerletMapping::initReflectingBoundary: Boundaries 0,2 are not reflecting!" << std::endl; exit(EXIT_FAILURE); } } // left if (boundary[3] == simplemd::REFLECTING_BOUNDARY){ reflect[0] = true; if ( (boundary[0] != simplemd::REFLECTING_BOUNDARY) || (boundary[5] != simplemd::REFLECTING_BOUNDARY) ){ std::cout << "ERROR simplemd::moleculemappings::VelocityStoermerVerletMapping::initReflectingBoundary: Boundaries 0,5 are not reflecting!" << std::endl; exit(EXIT_FAILURE); } } // right if (boundary[4] == simplemd::REFLECTING_BOUNDARY){ reflect[1] = true; if ( (boundary[2] != simplemd::REFLECTING_BOUNDARY) || (boundary[7] != simplemd::REFLECTING_BOUNDARY) ){ std::cout << "ERROR simplemd::moleculemappings::VelocityStoermerVerletMapping::initReflectingBoundary: Boundaries 2,7 are not reflecting!" << std::endl; exit(EXIT_FAILURE); } } // top if (boundary[6] == simplemd::REFLECTING_BOUNDARY){ reflect[3] = true; if ( (boundary[5] != simplemd::REFLECTING_BOUNDARY) || (boundary[7] != simplemd::REFLECTING_BOUNDARY) ){ std::cout << "ERROR simplemd::moleculemappings::VelocityStoermerVerletMapping::initReflectingBoundary: Boundaries 5,7 are not reflecting!" << std::endl; exit(EXIT_FAILURE); } } #elif (MD_DIM==3) // bottom if (boundary[4] == simplemd::REFLECTING_BOUNDARY){ reflect[4] = true; if ( (boundary[0] != simplemd::REFLECTING_BOUNDARY) || (boundary[1] != simplemd::REFLECTING_BOUNDARY) || (boundary[2] != simplemd::REFLECTING_BOUNDARY) ||(boundary[3] != simplemd::REFLECTING_BOUNDARY) || (boundary[5] != simplemd::REFLECTING_BOUNDARY) || (boundary[6] != simplemd::REFLECTING_BOUNDARY) ||(boundary[7] != simplemd::REFLECTING_BOUNDARY) || (boundary[8] != simplemd::REFLECTING_BOUNDARY) ){ std::cout << "ERROR simplemd::moleculemappings::VelocityStoermerVerletMapping::initReflectingBoundary: Boundaries 0,1,2,3,5,6,7,8 are not reflecting!" << std::endl; exit(EXIT_FAILURE); } } // front if (boundary[10] == simplemd::REFLECTING_BOUNDARY){ reflect[2] = true; if ( (boundary[0] != simplemd::REFLECTING_BOUNDARY) || (boundary[1] != simplemd::REFLECTING_BOUNDARY) || (boundary[2] != simplemd::REFLECTING_BOUNDARY) ||(boundary[9] != simplemd::REFLECTING_BOUNDARY) || (boundary[11] != simplemd::REFLECTING_BOUNDARY) || (boundary[17] != simplemd::REFLECTING_BOUNDARY) ||(boundary[18] != simplemd::REFLECTING_BOUNDARY) || (boundary[19] != simplemd::REFLECTING_BOUNDARY) ){ std::cout << "ERROR simplemd::moleculemappings::VelocityStoermerVerletMapping::initReflectingBoundary: Boundaries 0,1,2,9,11,17,18,19 are not reflecting!" << std::endl; exit(EXIT_FAILURE); } } // left if (boundary[12] == simplemd::REFLECTING_BOUNDARY){ reflect[0] = true; if ( (boundary[0] != simplemd::REFLECTING_BOUNDARY) || (boundary[3] != simplemd::REFLECTING_BOUNDARY) || (boundary[6] != simplemd::REFLECTING_BOUNDARY) ||(boundary[9] != simplemd::REFLECTING_BOUNDARY) || (boundary[14] != simplemd::REFLECTING_BOUNDARY) || (boundary[17] != simplemd::REFLECTING_BOUNDARY) ||(boundary[20] != simplemd::REFLECTING_BOUNDARY) || (boundary[23] != simplemd::REFLECTING_BOUNDARY) ){ std::cout << "ERROR simplemd::moleculemappings::VelocityStoermerVerletMapping::initReflectingBoundary: Boundaries 0,3,6,9,14,17,20,23 are not reflecting!" << std::endl; exit(EXIT_FAILURE); } } // right if (boundary[13] == simplemd::REFLECTING_BOUNDARY){ reflect[1] = true; if ( (boundary[2] != simplemd::REFLECTING_BOUNDARY) || (boundary[5] != simplemd::REFLECTING_BOUNDARY) || (boundary[8] != simplemd::REFLECTING_BOUNDARY) ||(boundary[11] != simplemd::REFLECTING_BOUNDARY) || (boundary[16] != simplemd::REFLECTING_BOUNDARY) || (boundary[19] != simplemd::REFLECTING_BOUNDARY) ||(boundary[22] != simplemd::REFLECTING_BOUNDARY) || (boundary[25] != simplemd::REFLECTING_BOUNDARY) ){ std::cout << "ERROR simplemd::moleculemappings::VelocityStoermerVerletMapping::initReflectingBoundary: Boundaries 2,5,8,11,16,19,22,25 are not reflecting!" << std::endl; exit(EXIT_FAILURE); } } // back if (boundary[15] == simplemd::REFLECTING_BOUNDARY){ reflect[3] = true; if ( (boundary[6] != simplemd::REFLECTING_BOUNDARY) || (boundary[7] != simplemd::REFLECTING_BOUNDARY) || (boundary[8] != simplemd::REFLECTING_BOUNDARY) ||(boundary[14] != simplemd::REFLECTING_BOUNDARY) || (boundary[16] != simplemd::REFLECTING_BOUNDARY) || (boundary[23] != simplemd::REFLECTING_BOUNDARY) ||(boundary[24] != simplemd::REFLECTING_BOUNDARY) || (boundary[25] != simplemd::REFLECTING_BOUNDARY) ){ std::cout << "ERROR simplemd::moleculemappings::VelocityStoermerVerletMapping::initReflectingBoundary: Boundaries 6,7,8,14,16,23,24,25 are not reflecting!" << std::endl; exit(EXIT_FAILURE); } } // top if (boundary[21] == simplemd::REFLECTING_BOUNDARY){ reflect[5] = true; if ( (boundary[17] != simplemd::REFLECTING_BOUNDARY) || (boundary[18] != simplemd::REFLECTING_BOUNDARY) || (boundary[19] != simplemd::REFLECTING_BOUNDARY) ||(boundary[20] != simplemd::REFLECTING_BOUNDARY) || (boundary[22] != simplemd::REFLECTING_BOUNDARY) || (boundary[23] != simplemd::REFLECTING_BOUNDARY) ||(boundary[24] != simplemd::REFLECTING_BOUNDARY) || (boundary[25] != simplemd::REFLECTING_BOUNDARY) ){ std::cout << "ERROR simplemd::moleculemappings::VelocityStoermerVerletMapping::initReflectingBoundary: Boundaries 17,18,19,20,22,23,24,25 are not reflecting!" << std::endl; exit(EXIT_FAILURE); } } #endif return reflect; }
55.558511
198
0.684442
HSU-HPC
9fb0b2bd4169c0347f4c5c58708b5fc551f12dbe
12,100
cc
C++
test/common/t__xdrbuf.cc
codesloop/codesloop
d66e51c2d898a72624306f611a90364c76deed06
[ "BSD-2-Clause" ]
3
2016-05-09T15:29:29.000Z
2017-11-22T06:16:18.000Z
test/common/t__xdrbuf.cc
codesloop/codesloop
d66e51c2d898a72624306f611a90364c76deed06
[ "BSD-2-Clause" ]
null
null
null
test/common/t__xdrbuf.cc
codesloop/codesloop
d66e51c2d898a72624306f611a90364c76deed06
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (c) 2008,2009,2010, CodeSLoop Team Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** @file t__xdrbuf.cc @brief Tests to verify xdr utilities */ #ifndef DEBUG #define DEBUG #endif /* DEBUG */ #include "codesloop/common/xdrbuf.hh" #include "codesloop/common/pbuf.hh" #include "codesloop/common/zfile.hh" #include "codesloop/common/mpool.hh" #include "codesloop/common/common.h" #include "codesloop/common/test_timer.h" #include "codesloop/common/str.hh" #include "codesloop/common/ustr.hh" #include "codesloop/common/exc.hh" #include <assert.h> using namespace csl::common; /** @brief contains tests related to xdr buffer */ namespace test_xdrbuf { /** @test baseline for performance comparison */ void baseline() { pbuf pb; xdrbuf xb(pb); assert( xb.position() == 0 ); } /** @test copy constructor */ void test_copy() { pbuf pb; xdrbuf xb(pb); xdrbuf xc(xb); assert( xb == xc ); } /** @test integer de/serialization */ void test_longlong() { pbuf pb; xdrbuf xb(pb); uint64_t a = 0xdeadbabedeadbabeLL; uint64_t b; xb << a; xb.rewind(); xb >> b; assert( a == b ); assert( xb.position() == sizeof(int64_t) ); bool caught = false; try { unsigned int c; /* read more than available */ xb >> c; } catch( csl::common::exc e ) { caught = true; assert( e.reason_ == csl::common::exc::rs_xdr_eof ); assert( e.component_ == L"csl::common::xdrbuf" ); } assert( caught == true ); } /** @test integer de/serialization */ void test_int() { pbuf pb; xdrbuf xb(pb); unsigned int a = 0xbaddad; unsigned int b; xb << a; xb.rewind(); xb >> b; assert( a == b ); assert( xb.position() == sizeof(int32_t) ); bool caught = false; try { unsigned int c; /* read more than available */ xb >> c; } catch( csl::common::exc e ) { caught = true; assert( e.reason_ == csl::common::exc::rs_xdr_eof ); assert( e.component_ == L"csl::common::xdrbuf" ); } assert( caught == true ); } /** @test string de/serialization */ void test_string() { pbuf pb; xdrbuf xb(pb); xb << L"Hello World"; str hw; xb.rewind(); assert( pb.size() == sizeof(wchar_t)*11+sizeof(int64_t) ); xb >> hw; assert( hw.size() == 11 ); assert( hw == "Hello World" ); assert( xb.position() > 10 ); /* save position */ xdrbuf xx(xb); bool caught = false; try { unsigned int c; /* read more than available */ xb >> c; } catch( csl::common::exc e ) { caught = true; assert( e.reason_ == csl::common::exc::rs_xdr_eof ); assert( e.component_ == L"csl::common::xdrbuf" ); } assert( caught == true ); caught = false; try { /* add invalid pointer */ xx << reinterpret_cast<const char *>(0); str zz; xx >> zz; } catch( csl::common::exc e ) { str es; e.to_string(es); FPRINTF(stderr,L"Exception caught: %ls\n",es.c_str()); caught = true; } /* this should not throw an exception, will add as zero length string */ assert( caught == false ); } /** @test string de/serialization */ void test_ustring() { pbuf pb; xdrbuf xb(pb); xb << "Hello World"; ustr hw; xb.rewind(); assert( pb.size() == 20 ); xb >> hw; assert( hw.size() == 11 ); assert( hw == "Hello World" ); assert( xb.position() > 10 ); /* save position */ xdrbuf xx(xb); bool caught = false; try { unsigned int c; /* read more than available */ xb >> c; } catch( csl::common::exc e ) { caught = true; assert( e.reason_ == csl::common::exc::rs_xdr_eof ); assert( e.component_ == L"csl::common::xdrbuf" ); } assert( caught == true ); caught = false; try { /* add invalid pointer */ xx << reinterpret_cast<const char *>(0); str zz; xx >> zz; } catch( csl::common::exc e ) { str es; e.to_string(es); FPRINTF(stderr,L"Exception caught: %ls\n",es.c_str()); caught = true; } /* this should not throw an exception, will add as zero length string */ assert( caught == false ); } /** @test xdrbuf::bindata_t de/serialization */ void test_bin() { zfile zf; assert( zf.read_file("random.204800") == true ); assert( zf.get_size() == 204800 ); mpool<> mp; unsigned char * ptr = reinterpret_cast<unsigned char *>(mp.allocate(zf.get_size())); assert( ptr != 0 ); assert( zf.get_data(ptr) == true ); pbuf pb; xdrbuf xb(pb); xb << xdrbuf::bindata_t(ptr,zf.get_size()); unsigned char * ptr2 = reinterpret_cast<unsigned char *>(mp.allocate(zf.get_size())); assert( ptr2 != 0 ); xb.rewind(); uint64_t sz; assert( xb.get_data(ptr2,sz,204808) == true ); assert( xb.position() == 204808 ); assert( sz == zf.get_size() ); assert( sz == 204800 ); assert( ::memcmp( ptr, ptr2, static_cast<size_t>(sz) ) == 0 ); } /** @test pbuf de/serialization */ void test_pbuf() { zfile zf; assert( zf.read_file("random.2048") == true ); assert( zf.get_size() == 2048 ); pbuf ptr; assert( zf.get_data(ptr) == true ); assert( ptr.size() == 2048 ); pbuf pb; xdrbuf xb(pb); xb << ptr; assert( pb.size() == 2056 ); xb.rewind(); pbuf ptr2; xb >> ptr2; assert( ptr2.size() == 2048 ); assert( ptr == ptr2 ); } /** @test reading 2048 bytes of garbage integer */ void garbage_int_small() { zfile zf; assert( zf.read_file("random.2048") == true ); pbuf ptr; assert( zf.get_data(ptr) == true ); assert( ptr.size() == 2048 ); xdrbuf xb(ptr); int exc_caught = -2; try { xb.rewind(); while( true ) { unsigned int i; xb >> i; }; } catch( csl::common::exc e ) { exc_caught = e.reason_; } /* integer garbage cannot be validated, thus eof condition is checked */ assert( exc_caught == csl::common::exc::rs_xdr_eof ); } /** @test reading 204800 bytes of garbage integer */ void garbage_int_large() { zfile zf; assert( zf.read_file("random.204800") == true ); pbuf ptr; assert( zf.get_data(ptr) == true ); assert( ptr.size() == 204800 ); xdrbuf xb(ptr); int exc_caught = -2; try { xb.rewind(); unsigned long j = 0; while( true ) { unsigned int i; xb >> i; j += sizeof(int32_t); assert( xb.position() == j ); }; } catch( csl::common::exc e ) { exc_caught = e.reason_; } /* integer garbage cannot be validated, thus eof condition is checked */ assert( exc_caught == csl::common::exc::rs_xdr_eof ); } /** @test reading 2048 bytes of garbage string */ void garbage_string_small() { zfile zf; assert( zf.read_file("random.2048") == true ); pbuf ptr; assert( zf.get_data(ptr) == true ); assert( ptr.size() == 2048 ); xdrbuf xb(ptr); int exc_caught = -2; try { xb.rewind(); while( true ) { str i; xb >> i; }; } catch( csl::common::exc e ) { exc_caught = e.reason_; } /* garbage string does not match the expected size */ assert( exc_caught == csl::common::exc::rs_xdr_invalid ); } /** @test reading 204800 bytes of garbage string */ void garbage_string_large() { zfile zf; assert( zf.read_file("random.204800") == true ); pbuf ptr; assert( zf.get_data(ptr) == true ); assert( ptr.size() == 204800 ); xdrbuf xb(ptr); int exc_caught = -2; try { xb.rewind(); while( true ) { str i; xb >> i; }; } catch( csl::common::exc e ) { exc_caught = e.reason_; } /* garbage string does not match the expected size */ assert( exc_caught == csl::common::exc::rs_xdr_invalid ); } /** @test reading 2048 bytes of garbage binary data to pbuf */ void garbage_pbuf_small() { zfile zf; assert( zf.read_file("random.2048") == true ); pbuf ptr; assert( zf.get_data(ptr) == true ); assert( ptr.size() == 2048 ); xdrbuf xb(ptr); int exc_caught = -2; try { xb.rewind(); while( true ) { pbuf i; xb >> i; }; } catch( csl::common::exc e ) { exc_caught = e.reason_; } /* garbage binary data does not match the expected size */ assert( exc_caught == csl::common::exc::rs_xdr_invalid ); } /** @test reading 204800 bytes of garbage binary data to pbuf */ void garbage_pbuf_large() { zfile zf; assert( zf.read_file("random.204800") == true ); pbuf ptr; assert( zf.get_data(ptr) == true ); assert( ptr.size() == 204800 ); xdrbuf xb(ptr); int exc_caught = -2; try { xb.rewind(); while( true ) { pbuf i; xb >> i; assert( i.size() == xb.position() ); }; } catch( csl::common::exc e ) { exc_caught = e.reason_; } /* garbage binary data does not match the expected size */ assert( exc_caught == csl::common::exc::rs_xdr_invalid ); } } // end of test_xdrbuf using namespace test_xdrbuf; int main() { csl_common_print_results( "baseline ", csl_common_test_timer_v0(baseline),"" ); csl_common_print_results( "test_copy ", csl_common_test_timer_v0(test_copy),"" ); csl_common_print_results( "test_int ", csl_common_test_timer_v0(test_int),"" ); csl_common_print_results( "test_longlong ", csl_common_test_timer_v0(test_longlong),"" ); csl_common_print_results( "test_string ", csl_common_test_timer_v0(test_string),"" ); csl_common_print_results( "test_ustring ", csl_common_test_timer_v0(test_ustring),"" ); csl_common_print_results( "test_bin ", csl_common_test_timer_v0(test_bin),"" ); csl_common_print_results( "test_pbuf ", csl_common_test_timer_v0(test_pbuf),"" ); csl_common_print_results( "garbage_int_small ", csl_common_test_timer_v0(garbage_int_small),"" ); csl_common_print_results( "garbage_int_large ", csl_common_test_timer_v0(garbage_int_large),"" ); csl_common_print_results( "garbage_string_small ", csl_common_test_timer_v0(garbage_string_small),"" ); csl_common_print_results( "garbage_string_large ", csl_common_test_timer_v0(garbage_string_large),"" ); csl_common_print_results( "garbage_pbuf_small ", csl_common_test_timer_v0(garbage_pbuf_small),"" ); csl_common_print_results( "garbage_pbuf_large ", csl_common_test_timer_v0(garbage_pbuf_large),"" ); return 0; } /* EOF */
23.495146
105
0.594215
codesloop
9fb10a609bba3beeed23f82451423f8c42959681
1,227
cpp
C++
_includes/leet310/leet310_1.cpp
mingdaz/leetcode
64f2e5ad0f0446d307e23e33a480bad5c9e51517
[ "MIT" ]
null
null
null
_includes/leet310/leet310_1.cpp
mingdaz/leetcode
64f2e5ad0f0446d307e23e33a480bad5c9e51517
[ "MIT" ]
8
2019-12-19T04:46:05.000Z
2022-02-26T03:45:22.000Z
_includes/leet310/leet310_1.cpp
mingdaz/leetcode
64f2e5ad0f0446d307e23e33a480bad5c9e51517
[ "MIT" ]
null
null
null
class Solution { public: vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) { vector<int> vec[n+1]; int degree[n+1]; for(int i=0;i<=n;i++) degree[i]=0; for(int i=0;i<n-1;i++){ int a=edges[i].first; int b=edges[i].second; vec[a].push_back(b); vec[b].push_back(a); degree[a]++; degree[b]++; } queue<int >qq; for(int i=0;i<n;i++) if(degree[i]==1) qq.push(i); while(n>2){ int sz=qq.size(); for(int i=0;i<sz;i++){ int temp=qq.front();//cout<<temp<<" "; qq.pop(); n--; for(auto j=vec[temp].begin();j!=vec[temp].end();j++){ degree[*j]--; if(degree[*j]==1) qq.push(*j); } } } vector<int> rs; if(qq.empty()){rs.push_back(0);return rs;} while(!qq.empty()){ rs.push_back(qq.front()); qq.pop(); } return rs; } };
24.54
74
0.354523
mingdaz
9fb38af70a117431bbc2af22d78c136261cc0063
1,656
cpp
C++
src/http/http_request.cpp
Mojiajun/tinyreactor
94adab8941b1d4cf46297adec9f14d7ce26c44d8
[ "MIT" ]
1
2020-10-19T07:57:32.000Z
2020-10-19T07:57:32.000Z
src/http/http_request.cpp
Mojiajun/tinyreactor
94adab8941b1d4cf46297adec9f14d7ce26c44d8
[ "MIT" ]
null
null
null
src/http/http_request.cpp
Mojiajun/tinyreactor
94adab8941b1d4cf46297adec9f14d7ce26c44d8
[ "MIT" ]
null
null
null
// // Created by mojiajun on 2020/3/6. // #include "http_request.h" using namespace tinyreactor; bool HttpRequest::setMethod(const char *start, const char *end) { assert(method_ == kInvalid); std::string m(start, end); if (m == "GET") { method_ = kGet; } else if (m == "POST") { method_ = kPost; } else if (m == "HEAD") { method_ = kHead; } else if (m == "PUT") { method_ = kPut; } else if (m == "DELETE") { method_ = kDelete; } else { method_ = kInvalid; } return method_ != kInvalid; } const char *HttpRequest::methodString() const { const char *result = "UNKNOWN"; switch (method_) { case kGet:result = "GET"; break; case kPost:result = "POST"; break; case kHead:result = "HEAD"; break; case kPut:result = "PUT"; break; case kDelete:result = "DELETE"; break; default:break; } return result; } void HttpRequest::addHeader(const char *start, const char *colon, const char *end) { std::string field(start, colon); ++colon; while (colon < end && isspace(*colon)) { ++colon; } std::string value(colon, end); while (!value.empty() && isspace(value[value.size() - 1])) { value.resize(value.size() - 1); } headers_[field] = value; } std::string HttpRequest::getHeader(const std::string &field) const { std::string result; std::map<std::string, std::string>::const_iterator it = headers_.find(field); if (it != headers_.end()) { result = it->second; } return result; }
25.090909
84
0.551329
Mojiajun
9fb3953228e99b21cb2bf39dc0a6ec9819a8d14a
7,885
hpp
C++
include/veriblock/blockchain/pop/vbk_block_tree.hpp
Dmytro-Kyparenko/alt-integration-cpp
df18abdd4bfeec757c2df47efcaf4020d78880bb
[ "MIT" ]
null
null
null
include/veriblock/blockchain/pop/vbk_block_tree.hpp
Dmytro-Kyparenko/alt-integration-cpp
df18abdd4bfeec757c2df47efcaf4020d78880bb
[ "MIT" ]
null
null
null
include/veriblock/blockchain/pop/vbk_block_tree.hpp
Dmytro-Kyparenko/alt-integration-cpp
df18abdd4bfeec757c2df47efcaf4020d78880bb
[ "MIT" ]
null
null
null
// Copyright (c) 2019-2020 Xenios SEZC // https://www.veriblock.org // Distributed under the MIT software license, see the accompanying // file LICENSE or http://www.opensource.org/licenses/mit-license.php. #ifndef ALT_INTEGRATION_INCLUDE_VERIBLOCK_BLOCKCHAIN_VBK_BLOCK_TREE_HPP_ #define ALT_INTEGRATION_INCLUDE_VERIBLOCK_BLOCKCHAIN_VBK_BLOCK_TREE_HPP_ #include <utility> #include <veriblock/blockchain/blocktree.hpp> #include <veriblock/blockchain/pop/fork_resolution.hpp> #include <veriblock/blockchain/pop/pop_state_machine.hpp> #include <veriblock/blockchain/vbk_block_addon.hpp> #include <veriblock/blockchain/vbk_chain_params.hpp> #include <veriblock/entities/btcblock.hpp> #include <veriblock/finalizer.hpp> #include <veriblock/storage/payloads_index.hpp> namespace altintegration { // defined in vbk_block_tree.cpp extern template struct BlockIndex<BtcBlock>; extern template struct BlockTree<BtcBlock, BtcChainParams>; extern template struct BaseBlockTree<BtcBlock>; extern template struct BlockIndex<VbkBlock>; extern template struct BlockTree<VbkBlock, VbkChainParams>; extern template struct BaseBlockTree<VbkBlock>; /** * @class VbkBlockTree * * Veriblock block tree. * * @invariant stores only valid payloads. */ struct VbkBlockTree : public BlockTree<VbkBlock, VbkChainParams> { using VbkTree = BlockTree<VbkBlock, VbkChainParams>; using BtcTree = BlockTree<BtcBlock, BtcChainParams>; using index_t = VbkTree::index_t; using payloads_t = typename index_t::payloads_t; using pid_t = typename payloads_t::id_t; using endorsement_t = typename index_t::endorsement_t; using PopForkComparator = PopAwareForkResolutionComparator<VbkBlock, VbkChainParams, BtcTree, VbkBlockTree>; ~VbkBlockTree() override = default; VbkBlockTree(const VbkChainParams& vbkp, const BtcChainParams& btcp, PayloadsProvider& storagePayloads, PayloadsIndex& payloadsIndex); //! efficiently connect `index` to current tree, loaded from disk //! - recovers all pointers (pprev, pnext, endorsedBy) //! - recalculates chainWork //! - does validation of endorsements //! - recovers tips array //! @invariant NOT atomic. bool loadBlock(const index_t& index, ValidationState& state) override; BtcTree& btc() { return cmp_.getProtectingBlockTree(); } const BtcTree& btc() const { return cmp_.getProtectingBlockTree(); } PopForkComparator& getComparator() { return cmp_; } const PopForkComparator& getComparator() const { return cmp_; } PayloadsIndex& getPayloadsIndex() { return payloadsIndex_; } bool loadTip(const hash_t& hash, ValidationState& state) override; /** * @invariant atomic: adds either all or none of the payloads */ bool addPayloads(const VbkBlock::hash_t& hash, const std::vector<payloads_t>& payloads, ValidationState& state); void removePayloads(const hash_t& hash, const std::vector<pid_t>& pids); void removePayloads(const block_t& block, const std::vector<pid_t>& pids); void removePayloads(index_t& index, const std::vector<pid_t>& pids); /** * If we add payloads to the VBK tree in the following order: A1, B2, A3. * * Ending up with the tree looking like this: * A(1,3)-o-o-o-B(2) * * It is only safe to use this function to remove them in the opposite order: * A3, B2, A1; or A3, B2. * * It is unsafe to use this function to remove them in any other order eg: * B2, A3, A1; or just B2. */ void unsafelyRemovePayload(const Blob<24>& hash, const pid_t& pid); void unsafelyRemovePayload(const block_t& block, const pid_t& pid); void unsafelyRemovePayload(index_t& index, const pid_t& pid, bool shouldDetermineBestChain = true); std::string toPrettyString(size_t level = 0) const; using base::setState; bool setState(index_t& to, ValidationState& state) override; void overrideTip(index_t& to) override; void removeSubtree(index_t& toRemove) override; private: bool validateBTCContext(const payloads_t& vtb, ValidationState& state); /** * Add, apply and validate a payload to a block that's currently applied * * Will add duplicates. * The containing block must be applied * @invariant atomic: leaves the state unchanged on failure * @return: true/false on success/failure */ bool addPayloadToAppliedBlock(index_t& index, const payloads_t& payload, ValidationState& state); void determineBestChain(index_t& candidate, ValidationState& state) override; PopForkComparator cmp_; PayloadsProvider& payloadsProvider_; PayloadsIndex& payloadsIndex_; }; template <> void assertBlockCanBeRemoved(const BlockIndex<BtcBlock>& index); template <> void assertBlockCanBeRemoved(const BlockIndex<VbkBlock>& index); template <> std::vector<CommandGroup> payloadsToCommandGroups( VbkBlockTree& tree, const std::vector<VTB>& pop, const std::vector<uint8_t>& containinghash); template <> void payloadToCommands(VbkBlockTree& tree, const VTB& pop, const std::vector<uint8_t>& containingHash, std::vector<CommandPtr>& cmds); template <typename JsonValue> JsonValue ToJSON(const BlockIndex<VbkBlock>& i) { auto obj = json::makeEmptyObject<JsonValue>(); json::putStringKV(obj, "chainWork", i.chainWork.toHex()); std::vector<uint256> endorsements; for (const auto& e : i.getContainingEndorsements()) { endorsements.push_back(e.first); } json::putArrayKV(obj, "containingEndorsements", endorsements); std::vector<uint256> endorsedBy; for (const auto* e : i.endorsedBy) { endorsedBy.push_back(e->id); } json::putArrayKV(obj, "endorsedBy", endorsedBy); json::putIntKV(obj, "height", i.getHeight()); json::putKV(obj, "header", ToJSON<JsonValue>(i.getHeader())); json::putIntKV(obj, "status", i.getStatus()); json::putIntKV(obj, "ref", i.refCount()); auto stored = json::makeEmptyObject<JsonValue>(); json::putArrayKV(stored, "vtbids", i.getPayloadIds<VTB>()); json::putKV(obj, "stored", stored); return obj; } template <typename JsonValue> JsonValue ToJSON(const BlockIndex<BtcBlock>& i) { auto obj = json::makeEmptyObject<JsonValue>(); json::putStringKV(obj, "chainWork", i.chainWork.toHex()); json::putIntKV(obj, "height", i.getHeight()); json::putKV(obj, "header", ToJSON<JsonValue>(i.getHeader())); json::putIntKV(obj, "status", i.getStatus()); json::putIntKV(obj, "ref", i.refCount()); return obj; } // HACK: getBlockIndex accepts either hash_t or prev_block_hash_t // then, depending on what it received, it should do trim LE on full hash to // receive short hash, which is stored inside a map. In this weird case, when // Block=VbkBlock, we may call `getBlockIndex(block->previousBlock)`, it is a // call `getBlockIndex(Blob<12>). But when `getBlockIndex` accepts it, it does // an implicit cast to full hash (hash_t), adding zeroes in the end. Then, // .trimLE returns 12 zeroes. // // This hack allows us to inject explicit conversion hash_t (Blob<24>) -> // prev_block_hash_t (Blob<12>). template <> template <> inline BaseBlockTree<VbkBlock>::prev_block_hash_t BaseBlockTree<VbkBlock>::makePrevHash<BaseBlockTree<VbkBlock>::hash_t>( const hash_t& h) const { // do an explicit cast from hash_t -> prev_block_hash_t return h.template trimLE<prev_block_hash_t::size()>(); } inline void PrintTo(const VbkBlockTree& tree, std::ostream* os) { *os << tree.toPrettyString(); } } // namespace altintegration #endif // ALT_INTEGRATION_INCLUDE_VERIBLOCK_BLOCKCHAIN_VBK_BLOCK_TREE_HPP_
36.674419
79
0.703361
Dmytro-Kyparenko
9fb731856a125135c016f17bbb1a3b5b94706faa
1,226
cpp
C++
src/Selections/QCDNonIsolatedElectronSelection.cpp
jjacob/AnalysisSoftware
670513bcde9c3df46077f906246e912627ee251a
[ "Apache-2.0" ]
null
null
null
src/Selections/QCDNonIsolatedElectronSelection.cpp
jjacob/AnalysisSoftware
670513bcde9c3df46077f906246e912627ee251a
[ "Apache-2.0" ]
null
null
null
src/Selections/QCDNonIsolatedElectronSelection.cpp
jjacob/AnalysisSoftware
670513bcde9c3df46077f906246e912627ee251a
[ "Apache-2.0" ]
null
null
null
/* * QCDNonIsolatedElectronSelection.cpp * * Created on: 12 Apr 2012 * Author: kreczko */ #include "../../interface/Selections/QCDNonIsolatedElectronSelection.h" namespace BAT { QCDNonIsolatedElectronSelection::QCDNonIsolatedElectronSelection(unsigned int numberOfSelectionSteps) : QCDPFRelIsoEPlusJetsSelection(numberOfSelectionSteps) { } QCDNonIsolatedElectronSelection::~QCDNonIsolatedElectronSelection() { } bool QCDNonIsolatedElectronSelection::hasExactlyOneIsolatedLepton(const EventPtr event) const { const ElectronCollection allElectrons(event->Electrons()); // unsigned int nGoodElectrons(0), nGoodNonIsolatedElectrons(0), nGoodIsolatedElectrons(0); for (unsigned int index = 0; index < allElectrons.size(); ++index) { const ElectronPointer electron(allElectrons.at(index)); if (isGoodElectron(electron)) { ++nGoodElectrons; if (electron->pfRelativeIsolationRhoCorrected() < 0.2) ++nGoodIsolatedElectrons; if (electron->pfRelativeIsolationRhoCorrected() > 0.2) ++nGoodNonIsolatedElectrons; } } //no electrons below 0.2 in PFRelIso and at least one electron with PFIso > 0.2 return nGoodNonIsolatedElectrons > 0 && nGoodIsolatedElectrons == 0; } } /* namespace BAT */
30.65
103
0.769168
jjacob
9fba761eaa4b2b6b753a3ee83261dc2a82e8e602
11,030
cc
C++
pycpp/compression/gzip.cc
Alexhuszagh/funxx
9f6c1fae92d96a84282fc62be272f4dc1e1dba9b
[ "MIT", "BSD-3-Clause" ]
1
2017-07-21T22:58:38.000Z
2017-07-21T22:58:38.000Z
pycpp/compression/gzip.cc
Alexhuszagh/funxx
9f6c1fae92d96a84282fc62be272f4dc1e1dba9b
[ "MIT", "BSD-3-Clause" ]
null
null
null
pycpp/compression/gzip.cc
Alexhuszagh/funxx
9f6c1fae92d96a84282fc62be272f4dc1e1dba9b
[ "MIT", "BSD-3-Clause" ]
null
null
null
// :copyright: (c) 2017 Alex Huszagh. // :license: MIT, see licenses/mit.md for more details. #if defined(HAVE_ZLIB) // This module is basically identical to zlib, // so just include the private error handling. #include <pycpp/compression/zlib.cc> #include <pycpp/compression/gzip.h> #include <pycpp/preprocessor/byteorder.h> #include <string.h> #include <time.h> PYCPP_BEGIN_NAMESPACE // MACROS // ------ #define WINDOW_BITS 15 // HELPERS // ------- static size_t gzip_compress_bound(size_t size) { // need an extra 10 bytes for the header return zlib_compress_bound(size) + 10; } /** * Create the GZIP header. Use a default filetime, filename, * and comment by default, since these features aren't useful, * and just mess up reproducibility of the produced bytes * for testing purposes. */ static string gzip_header(int level, time_t mtime = 0, const string& filename = "", const string& comment = "") { string header; bool has_filename = !filename.empty(); bool has_comment = !comment.empty(); size_t length = 10; if (has_filename) { length += filename.size() + 1; } if (has_comment) { length += comment.size() + 1; } header.reserve(length); header += (char) 0x1f; /* magic number */ header += (char) 0x8b; /* magic number */ header += (char) 0x08; /* deflate */ // flags int flags = 0; if (has_filename) { flags += 8; } if (has_comment) { flags += 16; } header += (char) flags; // mtime uint32_t mtime_le = htole32(static_cast<uint32_t>(mtime)); header.append((char*) &mtime_le, sizeof(uint32_t)); // write remaining header if (level == Z_BEST_COMPRESSION) { header += (char) 0x02; /* extra flags */ } else if (level == Z_BEST_SPEED) { header += (char) 0x04; /* extra flags */ } else { header += (char) 0x00; /* extra flags */ } header += (char) 0xff; /* OS unknown */ // write filename and comments if (has_filename) { header += filename; header += (char) 0x00; } if (has_comment) { header += comment; header += (char) 0x00; } return header; } // OBJECTS // ------- /** * \brief Implied base class for the GZIP compressor. */ struct gzip_compressor_impl: filter_impl<z_stream> { using base = filter_impl<z_stream>; string header; uLong crc = 0; size_t size = 0; gzip_compressor_impl(int level = 9); ~gzip_compressor_impl() noexcept; void write_header(); void write_footer(void*& dst); virtual void call(); bool flush(void*& dst, size_t dstlen); compression_status operator()(const void*& src, size_t srclen, void*& dst, size_t dstlen); }; gzip_compressor_impl::gzip_compressor_impl(int level) { header = gzip_header(level); status = Z_OK; stream.zalloc = Z_NULL; stream.zfree = Z_NULL; stream.opaque = Z_NULL; PYCPP_CHECK(deflateInit2(&stream, level, Z_DEFLATED, -WINDOW_BITS, 8, Z_DEFAULT_STRATEGY)); } gzip_compressor_impl::~gzip_compressor_impl() noexcept { deflateEnd(&stream); } void gzip_compressor_impl::write_header() { // write header on first pass if (!header.empty() && header.size() < stream.avail_out) { memcpy(stream.next_out, header.data(), header.size()); stream.next_out += header.size(); stream.avail_out -= static_cast<uInt>(header.size()); header.clear(); } } void gzip_compressor_impl::write_footer(void*& dst) { if (status == Z_STREAM_END && stream.avail_out >= 8) { // write CRC32 uint32_t crc_le = htole32(crc); memcpy(stream.next_out, &crc_le, sizeof(uint32_t)); stream.next_out += sizeof(uint32_t); // write size uint32_t size_le = htole32(size & 0xffffffff); memcpy(stream.next_out, &size_le, sizeof(uint32_t)); stream.next_out += sizeof(uint32_t); after(dst); } } void gzip_compressor_impl::call() { // try to write header, and if cannot, return early write_header(); if (!header.empty()) { return; } size += stream.avail_in; crc = crc32(crc, stream.next_in, stream.avail_in); while (stream.avail_in && stream.avail_out && status != Z_STREAM_END) { status = deflate(&stream, Z_NO_FLUSH); check_zstatus(status); } } bool gzip_compressor_impl::flush(void*& dst, size_t dstlen) { // try to write header, and if cannot, return early write_header(); if (!header.empty()) { return false; } bool code = base::flush(dst, dstlen, [&]() { if (dstlen) { status = deflate(&stream, Z_FINISH); return status == Z_STREAM_END || status == Z_OK; } else { status = deflate(&stream, Z_FULL_FLUSH); return status == Z_STREAM_END || status == Z_OK; } }); if (code) { write_footer(dst); } return code; } compression_status gzip_compressor_impl::operator()(const void*& src, size_t srclen, void*& dst, size_t dstlen) { return base::operator()(src, srclen, dst, dstlen, Z_STREAM_END); } /** * \brief Implied base class for the GZIP decompressor. */ struct gzip_decompressor_impl: filter_impl<z_stream> { using base = filter_impl<z_stream>; bool header_done = false; uLong crc = 0; size_t size = 0; gzip_decompressor_impl(); ~gzip_decompressor_impl() noexcept; void read_header(); void read_footer(); virtual void call(); bool flush(void*& dst, size_t dstlen); compression_status operator()(const void*& src, size_t srclen, void*& dst, size_t dstlen); }; gzip_decompressor_impl::gzip_decompressor_impl() { status = Z_OK; stream.zalloc = Z_NULL; stream.zfree = Z_NULL; stream.opaque = Z_NULL; PYCPP_CHECK(inflateInit2(&stream, -WINDOW_BITS)); } gzip_decompressor_impl::~gzip_decompressor_impl() noexcept { inflateEnd(&stream); } static void read_string(z_stream& stream) { // no filename nor comment void* tmp = memchr(stream.next_in, 0, stream.avail_in); stream.avail_in -= static_cast<uInt>(distance(stream.next_in, (Bytef*) tmp)); if (!stream.avail_in) { throw runtime_error("Unable to read header."); } --stream.avail_in; ++stream.next_in; } void gzip_decompressor_impl::read_header() { if (!header_done && stream.avail_in >= 10) { // read our header char flags = stream.next_in[3]; stream.next_in += 10; stream.avail_in -= 10; if (flags == 8 || flags == 16) { // has flag or comment but not both read_string(stream); } else if (flags == 24) { // has both filename and comment read_string(stream); read_string(stream); } header_done = true; } } void gzip_decompressor_impl::read_footer() { if (status == Z_STREAM_END && stream.avail_in >= 8) { uint32_t* buf = (uint32_t*) stream.next_in; uint32_t crc_ = le32toh(*buf++); uint32_t size_ = le32toh(*buf++); if (crc_ != crc) { throw runtime_error("CRC mismatch in GZIP decompression."); } if (size_ != (size & 0xffffffff)) { throw runtime_error("Size mismatch in GZIP decompression."); } } } void gzip_decompressor_impl::call() { read_header(); if (!header_done) { return; } while (stream.avail_in && stream.avail_out && status != Z_STREAM_END) { Bytef* dst = stream.next_out; status = inflate(&stream, Z_NO_FLUSH); check_zstatus(status); // store out CRC and length information size_t length = distance(dst, stream.next_out); size += length; crc = static_cast<uLong>(crc32(crc, dst, static_cast<uInt>(length))); } read_footer(); } bool gzip_decompressor_impl::flush(void*& dst, size_t dstlen) { // null-op, always flushed return true; } compression_status gzip_decompressor_impl::operator()(const void*& src, size_t srclen, void*& dst, size_t dstlen) { return base::operator()(src, srclen, dst, dstlen, Z_STREAM_END); } gzip_compressor::gzip_compressor(int level): ptr_(make_unique<gzip_compressor_impl>(level)) {} gzip_compressor::gzip_compressor(gzip_compressor&& rhs) noexcept: ptr_(move(rhs.ptr_)) {} gzip_compressor & gzip_compressor::operator=(gzip_compressor&& rhs) noexcept { swap(rhs); return *this; } gzip_compressor::~gzip_compressor() noexcept {} compression_status gzip_compressor::compress(const void*& src, size_t srclen, void*& dst, size_t dstlen) { return (*ptr_)(src, srclen, dst, dstlen); } bool gzip_compressor::flush(void*& dst, size_t dstlen) { return ptr_->flush(dst, dstlen); } void gzip_compressor::close() noexcept { ptr_.reset(); } void gzip_compressor::swap(gzip_compressor& rhs) noexcept { using PYCPP_NAMESPACE::swap; swap(ptr_, rhs.ptr_); } gzip_decompressor::gzip_decompressor(): ptr_(make_unique<gzip_decompressor_impl>()) {} gzip_decompressor::gzip_decompressor(gzip_decompressor&& rhs) noexcept: ptr_(move(rhs.ptr_)) {} gzip_decompressor & gzip_decompressor::operator=(gzip_decompressor&& rhs) noexcept { swap(rhs); return *this; } gzip_decompressor::~gzip_decompressor() noexcept {} compression_status gzip_decompressor::decompress(const void*& src, size_t srclen, void*& dst, size_t dstlen) { return (*ptr_)(src, srclen, dst, dstlen); } bool gzip_decompressor::flush(void*& dst, size_t dstlen) { return ptr_->flush(dst, dstlen); } void gzip_decompressor::close() noexcept { ptr_.reset(); } void gzip_decompressor::swap(gzip_decompressor& rhs) noexcept { using PYCPP_NAMESPACE::swap; swap(ptr_, rhs.ptr_); } // FUNCTIONS // --------- void gzip_compress(const void*& src, size_t srclen, void*& dst, size_t dstlen) { gzip_compressor ctx; ctx.compress(src, srclen, dst, dstlen); ctx.flush(dst, dstlen); } string gzip_compress(const string_wrapper& str) { size_t dstlen = gzip_compress_bound(str.size()); return compress_bound(str, dstlen, [](const void*& src, size_t srclen, void*& dst, size_t dstlen) { gzip_compress(src, srclen, dst, dstlen); }); } string gzip_decompress(const string_wrapper& str) { return ctx_decompress<gzip_decompressor>(str); } void gzip_decompress(const void*& src, size_t srclen, void*& dst, size_t dstlen, size_t bound) { gzip_decompressor ctx; ctx.decompress(src, srclen, dst, dstlen); } string gzip_decompress(const string_wrapper& str, size_t bound) { return decompress_bound(str, bound, [](const void*& src, size_t srclen, void*& dst, size_t dstlen, size_t bound) { gzip_decompress(src, srclen, dst, dstlen, bound); }); } PYCPP_END_NAMESPACE #endif // HAVE_ZLIB
23.221053
118
0.63427
Alexhuszagh
9fc070a77f05979a683d6d8f19821838d8eaadd8
402
hpp
C++
day10/los.hpp
bcafuk/AoC-2019
5ff9b86f8483cd7a6e229d572ae9e34b894eb574
[ "Zlib" ]
null
null
null
day10/los.hpp
bcafuk/AoC-2019
5ff9b86f8483cd7a6e229d572ae9e34b894eb574
[ "Zlib" ]
null
null
null
day10/los.hpp
bcafuk/AoC-2019
5ff9b86f8483cd7a6e229d572ae9e34b894eb574
[ "Zlib" ]
2
2020-11-02T09:24:35.000Z
2020-12-02T09:46:27.000Z
#ifndef AOC_2019_DAY10_LOS_HPP #define AOC_2019_DAY10_LOS_HPP #include <cstddef> #include <set> #include "Location.hpp" std::set<Location> getVisible(const std::set<Location> &asteroids, const Location &origin, coordinate size); inline size_t countVisible(const std::set<Location> &asteroids, const Location &origin, coordinate size) { return getVisible(asteroids, origin, size).size(); } #endif
25.125
108
0.776119
bcafuk
9fc096f1b782929bb005ffc810f315613fd61a44
2,236
cpp
C++
src/ImageDataWebP.cpp
jhasse/jngl
1aab1bb5b9712eca50786418d44e9559373441a8
[ "Zlib" ]
61
2015-09-30T14:42:38.000Z
2022-03-30T13:56:54.000Z
src/ImageDataWebP.cpp
jhasse/jngl
1aab1bb5b9712eca50786418d44e9559373441a8
[ "Zlib" ]
57
2016-08-10T19:28:36.000Z
2022-03-15T07:18:00.000Z
src/ImageDataWebP.cpp
jhasse/jngl
1aab1bb5b9712eca50786418d44e9559373441a8
[ "Zlib" ]
3
2021-12-14T18:08:56.000Z
2022-02-23T08:29:19.000Z
// Copyright 2021 Jan Niklas Hasse <jhasse@bixense.com> // For conditions of distribution and use, see copyright notice in LICENSE.txt #ifndef NOWEBP #include "ImageDataWebP.hpp" #include <boost/math/special_functions/round.hpp> #include <future> #include <thread> #include <vector> namespace jngl { ImageDataWebP::ImageDataWebP(std::string filename, FILE* file, double scaleFactor) : filename(std::move(filename)) { fseek(file, 0, SEEK_END); auto filesize = ftell(file); fseek(file, 0, SEEK_SET); std::vector<uint8_t> buf(filesize); if (!fread(&buf[0], filesize, 1, file)) { throw std::runtime_error(std::string("Couldn't open WebP file. (" + this->filename + ")")); } if (!WebPGetInfo(&buf[0], filesize, &imgWidth, &imgHeight)) { throw std::runtime_error(std::string("Invalid WebP file. (" + this->filename + ")")); } WebPInitDecoderConfig(&config); config.options.use_threads = 1; scaledWidth = imgWidth; scaledHeight = imgHeight; if (scaleFactor + 1e-9 < 1) { config.options.use_scaling = 1; config.options.scaled_width = scaledWidth = std::max(1, boost::math::iround(imgWidth * scaleFactor)); config.options.scaled_height = scaledHeight = std::max(1, boost::math::iround(imgHeight * scaleFactor)); } config.output.colorspace = MODE_RGBA; #ifndef __EMSCRIPTEN__ thread = std::make_unique<std::thread>([this, buf{ std::move(buf) }, filesize]() mutable { #endif result = WebPDecode(&buf[0], filesize, &config); #ifndef __EMSCRIPTEN__ }); #endif } ImageDataWebP::~ImageDataWebP() { #ifndef __EMSCRIPTEN__ if (thread && thread->joinable()) { thread->join(); } #endif WebPFreeDecBuffer(&config.output); } const uint8_t* ImageDataWebP::pixels() const { #ifndef __EMSCRIPTEN__ if (thread->joinable()) { thread->join(); } #endif if (result != VP8_STATUS_OK) { throw std::runtime_error(std::string("Can't decode WebP file. (" + filename + ")")); } return config.output.u.RGBA.rgba; // NOLINT } int ImageDataWebP::getImageWidth() const { return imgWidth; } int ImageDataWebP::getImageHeight() const { return imgHeight; } int ImageDataWebP::getWidth() const { return scaledWidth; } int ImageDataWebP::getHeight() const { return scaledHeight; } } // namespace jngl #endif
25.409091
93
0.706172
jhasse
9fc0ab3bd2d8693cef845cc80c3064733410334d
445
cpp
C++
SKYLINE.cpp
Akki5/spoj-solutions
9169830415eb4f888ba0300eb47a423166b8d938
[ "MIT" ]
1
2019-05-23T20:03:40.000Z
2019-05-23T20:03:40.000Z
SKYLINE.cpp
Akki5/spoj-solutions
9169830415eb4f888ba0300eb47a423166b8d938
[ "MIT" ]
null
null
null
SKYLINE.cpp
Akki5/spoj-solutions
9169830415eb4f888ba0300eb47a423166b8d938
[ "MIT" ]
1
2021-08-28T16:48:42.000Z
2021-08-28T16:48:42.000Z
#include<stdio.h> int arr[1005][1005]={{0}}; void catalan() { int i,j; for(i=0;i<1005;i++) { for(j=0;j<=i;j++) { if(j==0) arr[i][j]=1; else arr[i][j]=(arr[i][j-1]+arr[i-1][j])%1000000; } } } int main() { catalan(); int t; scanf("%d",&t); while(t) { printf("%d\n",arr[t][t]); scanf("%d",&t); } return 0; }
15.344828
60
0.357303
Akki5
9fc1608f0ef16a533eeb38a1a847e6cc9fe70607
1,473
cpp
C++
890. Find and Replace Pattern.cpp
rajeev-ranjan-au6/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
3
2020-12-30T00:29:59.000Z
2021-01-24T22:43:04.000Z
890. Find and Replace Pattern.cpp
rajeevranjancom/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
null
null
null
890. Find and Replace Pattern.cpp
rajeevranjancom/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
null
null
null
class Solution { public: vector<string> findAndReplacePattern(vector<string>& words, string pattern) { vector<string>res; for (auto& s: words) { if (isValid(s, pattern)) { res.push_back(s); } } return res; } bool isValid(string& a, string& b) { unordered_map<char, char>m, t; int n = a.size(), l = b.size(); if (n != l) { return false; } for (int i = 0; i < n; ++i) { if (m.count(a[i]) || t.count(b[i])) { if (m[a[i]] == b[i] && t[b[i]] == a[i]) { continue; } else { return false; } } m[a[i]] = b[i]; t[b[i]] = a[i]; } return true; } }; class Solution { public: vector<string> findAndReplacePattern(vector<string>& words, string pattern) { vector<string>res; for (auto& s: words) { if (normalize(s) == normalize(pattern)) { res.push_back(s); } } return res; } string normalize(string& s) { unordered_map<char, char>m; string res; char c = 'a'; for (auto& x: s) { if (!m.count(x)) { m[x] = c++; } } for (auto& x: s) { res.push_back(m[x]); } return res; } };
23.758065
81
0.395791
rajeev-ranjan-au6
9fc1d4d7fa89f2790b17bd8b59789645edc8221b
41,199
cpp
C++
src/vehicle_status.cpp
PX4/micrortps_agent
f7fee30b4a88d0627b2f92ca141277ace1a13597
[ "BSD-3-Clause" ]
3
2020-11-14T08:35:19.000Z
2022-01-25T05:21:14.000Z
src/vehicle_status.cpp
PX4/micrortps_agent
f7fee30b4a88d0627b2f92ca141277ace1a13597
[ "BSD-3-Clause" ]
1
2021-06-10T11:41:17.000Z
2021-06-10T11:41:17.000Z
src/vehicle_status.cpp
PX4/micrortps_agent
f7fee30b4a88d0627b2f92ca141277ace1a13597
[ "BSD-3-Clause" ]
2
2020-10-13T08:16:05.000Z
2021-06-03T05:57:31.000Z
// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // 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. /*! * @file vehicle_status.cpp * This source file contains the definition of the described types in the IDL file. * * This file was generated by the tool gen. */ #ifdef _WIN32 // Remove linker warning LNK4221 on Visual Studio namespace { char dummy; } #endif #include "vehicle_status.h" #include <fastcdr/Cdr.h> #include <fastcdr/exceptions/BadParamException.h> using namespace eprosima::fastcdr::exception; #include <utility> vehicle_status::vehicle_status() { // m_timestamp_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@358c99f5 m_timestamp_ = 0; // m_nav_state_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@3ee0fea4 m_nav_state_ = 0; // m_nav_state_timestamp_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@48524010 m_nav_state_timestamp_ = 0; // m_arming_state_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@4b168fa9 m_arming_state_ = 0; // m_hil_state_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@1a84f40f m_hil_state_ = 0; // m_failsafe_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@23282c25 m_failsafe_ = false; // m_failsafe_timestamp_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@7920ba90 m_failsafe_timestamp_ = 0; // m_system_type_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@6b419da m_system_type_ = 0; // m_system_id_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@3b2da18f m_system_id_ = 0; // m_component_id_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@5906ebcb m_component_id_ = 0; // m_vehicle_type_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@258e2e41 m_vehicle_type_ = 0; // m_is_vtol_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@3d299e3 m_is_vtol_ = false; // m_is_vtol_tailsitter_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@55a561cf m_is_vtol_tailsitter_ = false; // m_vtol_fw_permanent_stab_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@3b938003 m_vtol_fw_permanent_stab_ = false; // m_in_transition_mode_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@6f3b5d16 m_in_transition_mode_ = false; // m_in_transition_to_fw_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@78b1cc93 m_in_transition_to_fw_ = false; // m_rc_signal_lost_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@6646153 m_rc_signal_lost_ = false; // m_data_link_lost_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@21507a04 m_data_link_lost_ = false; // m_data_link_lost_counter_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@143640d5 m_data_link_lost_counter_ = 0; // m_high_latency_data_link_lost_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@6295d394 m_high_latency_data_link_lost_ = false; // m_engine_failure_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@475e586c m_engine_failure_ = false; // m_mission_failure_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@657c8ad9 m_mission_failure_ = false; // m_geofence_violated_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@436a4e4b m_geofence_violated_ = false; // m_failure_detector_status_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@f2f2cc1 m_failure_detector_status_ = 0; // m_onboard_control_sensors_present_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@3a079870 m_onboard_control_sensors_present_ = 0; // m_onboard_control_sensors_enabled_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@3b2cf7ab m_onboard_control_sensors_enabled_ = 0; // m_onboard_control_sensors_health_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@2aa5fe93 m_onboard_control_sensors_health_ = 0; // m_latest_arming_reason_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@5c1a8622 m_latest_arming_reason_ = 0; // m_latest_disarming_reason_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@5ad851c9 m_latest_disarming_reason_ = 0; // m_armed_time_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@6156496 m_armed_time_ = 0; // m_takeoff_time_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@3c153a1 m_takeoff_time_ = 0; } vehicle_status::~vehicle_status() { } vehicle_status::vehicle_status(const vehicle_status &x) { m_timestamp_ = x.m_timestamp_; m_nav_state_ = x.m_nav_state_; m_nav_state_timestamp_ = x.m_nav_state_timestamp_; m_arming_state_ = x.m_arming_state_; m_hil_state_ = x.m_hil_state_; m_failsafe_ = x.m_failsafe_; m_failsafe_timestamp_ = x.m_failsafe_timestamp_; m_system_type_ = x.m_system_type_; m_system_id_ = x.m_system_id_; m_component_id_ = x.m_component_id_; m_vehicle_type_ = x.m_vehicle_type_; m_is_vtol_ = x.m_is_vtol_; m_is_vtol_tailsitter_ = x.m_is_vtol_tailsitter_; m_vtol_fw_permanent_stab_ = x.m_vtol_fw_permanent_stab_; m_in_transition_mode_ = x.m_in_transition_mode_; m_in_transition_to_fw_ = x.m_in_transition_to_fw_; m_rc_signal_lost_ = x.m_rc_signal_lost_; m_data_link_lost_ = x.m_data_link_lost_; m_data_link_lost_counter_ = x.m_data_link_lost_counter_; m_high_latency_data_link_lost_ = x.m_high_latency_data_link_lost_; m_engine_failure_ = x.m_engine_failure_; m_mission_failure_ = x.m_mission_failure_; m_geofence_violated_ = x.m_geofence_violated_; m_failure_detector_status_ = x.m_failure_detector_status_; m_onboard_control_sensors_present_ = x.m_onboard_control_sensors_present_; m_onboard_control_sensors_enabled_ = x.m_onboard_control_sensors_enabled_; m_onboard_control_sensors_health_ = x.m_onboard_control_sensors_health_; m_latest_arming_reason_ = x.m_latest_arming_reason_; m_latest_disarming_reason_ = x.m_latest_disarming_reason_; m_armed_time_ = x.m_armed_time_; m_takeoff_time_ = x.m_takeoff_time_; } vehicle_status::vehicle_status(vehicle_status &&x) { m_timestamp_ = x.m_timestamp_; m_nav_state_ = x.m_nav_state_; m_nav_state_timestamp_ = x.m_nav_state_timestamp_; m_arming_state_ = x.m_arming_state_; m_hil_state_ = x.m_hil_state_; m_failsafe_ = x.m_failsafe_; m_failsafe_timestamp_ = x.m_failsafe_timestamp_; m_system_type_ = x.m_system_type_; m_system_id_ = x.m_system_id_; m_component_id_ = x.m_component_id_; m_vehicle_type_ = x.m_vehicle_type_; m_is_vtol_ = x.m_is_vtol_; m_is_vtol_tailsitter_ = x.m_is_vtol_tailsitter_; m_vtol_fw_permanent_stab_ = x.m_vtol_fw_permanent_stab_; m_in_transition_mode_ = x.m_in_transition_mode_; m_in_transition_to_fw_ = x.m_in_transition_to_fw_; m_rc_signal_lost_ = x.m_rc_signal_lost_; m_data_link_lost_ = x.m_data_link_lost_; m_data_link_lost_counter_ = x.m_data_link_lost_counter_; m_high_latency_data_link_lost_ = x.m_high_latency_data_link_lost_; m_engine_failure_ = x.m_engine_failure_; m_mission_failure_ = x.m_mission_failure_; m_geofence_violated_ = x.m_geofence_violated_; m_failure_detector_status_ = x.m_failure_detector_status_; m_onboard_control_sensors_present_ = x.m_onboard_control_sensors_present_; m_onboard_control_sensors_enabled_ = x.m_onboard_control_sensors_enabled_; m_onboard_control_sensors_health_ = x.m_onboard_control_sensors_health_; m_latest_arming_reason_ = x.m_latest_arming_reason_; m_latest_disarming_reason_ = x.m_latest_disarming_reason_; m_armed_time_ = x.m_armed_time_; m_takeoff_time_ = x.m_takeoff_time_; } vehicle_status& vehicle_status::operator=(const vehicle_status &x) { m_timestamp_ = x.m_timestamp_; m_nav_state_ = x.m_nav_state_; m_nav_state_timestamp_ = x.m_nav_state_timestamp_; m_arming_state_ = x.m_arming_state_; m_hil_state_ = x.m_hil_state_; m_failsafe_ = x.m_failsafe_; m_failsafe_timestamp_ = x.m_failsafe_timestamp_; m_system_type_ = x.m_system_type_; m_system_id_ = x.m_system_id_; m_component_id_ = x.m_component_id_; m_vehicle_type_ = x.m_vehicle_type_; m_is_vtol_ = x.m_is_vtol_; m_is_vtol_tailsitter_ = x.m_is_vtol_tailsitter_; m_vtol_fw_permanent_stab_ = x.m_vtol_fw_permanent_stab_; m_in_transition_mode_ = x.m_in_transition_mode_; m_in_transition_to_fw_ = x.m_in_transition_to_fw_; m_rc_signal_lost_ = x.m_rc_signal_lost_; m_data_link_lost_ = x.m_data_link_lost_; m_data_link_lost_counter_ = x.m_data_link_lost_counter_; m_high_latency_data_link_lost_ = x.m_high_latency_data_link_lost_; m_engine_failure_ = x.m_engine_failure_; m_mission_failure_ = x.m_mission_failure_; m_geofence_violated_ = x.m_geofence_violated_; m_failure_detector_status_ = x.m_failure_detector_status_; m_onboard_control_sensors_present_ = x.m_onboard_control_sensors_present_; m_onboard_control_sensors_enabled_ = x.m_onboard_control_sensors_enabled_; m_onboard_control_sensors_health_ = x.m_onboard_control_sensors_health_; m_latest_arming_reason_ = x.m_latest_arming_reason_; m_latest_disarming_reason_ = x.m_latest_disarming_reason_; m_armed_time_ = x.m_armed_time_; m_takeoff_time_ = x.m_takeoff_time_; return *this; } vehicle_status& vehicle_status::operator=(vehicle_status &&x) { m_timestamp_ = x.m_timestamp_; m_nav_state_ = x.m_nav_state_; m_nav_state_timestamp_ = x.m_nav_state_timestamp_; m_arming_state_ = x.m_arming_state_; m_hil_state_ = x.m_hil_state_; m_failsafe_ = x.m_failsafe_; m_failsafe_timestamp_ = x.m_failsafe_timestamp_; m_system_type_ = x.m_system_type_; m_system_id_ = x.m_system_id_; m_component_id_ = x.m_component_id_; m_vehicle_type_ = x.m_vehicle_type_; m_is_vtol_ = x.m_is_vtol_; m_is_vtol_tailsitter_ = x.m_is_vtol_tailsitter_; m_vtol_fw_permanent_stab_ = x.m_vtol_fw_permanent_stab_; m_in_transition_mode_ = x.m_in_transition_mode_; m_in_transition_to_fw_ = x.m_in_transition_to_fw_; m_rc_signal_lost_ = x.m_rc_signal_lost_; m_data_link_lost_ = x.m_data_link_lost_; m_data_link_lost_counter_ = x.m_data_link_lost_counter_; m_high_latency_data_link_lost_ = x.m_high_latency_data_link_lost_; m_engine_failure_ = x.m_engine_failure_; m_mission_failure_ = x.m_mission_failure_; m_geofence_violated_ = x.m_geofence_violated_; m_failure_detector_status_ = x.m_failure_detector_status_; m_onboard_control_sensors_present_ = x.m_onboard_control_sensors_present_; m_onboard_control_sensors_enabled_ = x.m_onboard_control_sensors_enabled_; m_onboard_control_sensors_health_ = x.m_onboard_control_sensors_health_; m_latest_arming_reason_ = x.m_latest_arming_reason_; m_latest_disarming_reason_ = x.m_latest_disarming_reason_; m_armed_time_ = x.m_armed_time_; m_takeoff_time_ = x.m_takeoff_time_; return *this; } size_t vehicle_status::getMaxCdrSerializedSize(size_t current_alignment) { size_t initial_alignment = current_alignment; current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8); current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8); current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8); current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8); return current_alignment - initial_alignment; } size_t vehicle_status::getCdrSerializedSize(const vehicle_status& data, size_t current_alignment) { (void)data; size_t initial_alignment = current_alignment; current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8); current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8); current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1); current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8); current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8); return current_alignment - initial_alignment; } void vehicle_status::serialize(eprosima::fastcdr::Cdr &scdr) const { scdr << m_timestamp_; scdr << m_nav_state_; scdr << m_nav_state_timestamp_; scdr << m_arming_state_; scdr << m_hil_state_; scdr << m_failsafe_; scdr << m_failsafe_timestamp_; scdr << m_system_type_; scdr << m_system_id_; scdr << m_component_id_; scdr << m_vehicle_type_; scdr << m_is_vtol_; scdr << m_is_vtol_tailsitter_; scdr << m_vtol_fw_permanent_stab_; scdr << m_in_transition_mode_; scdr << m_in_transition_to_fw_; scdr << m_rc_signal_lost_; scdr << m_data_link_lost_; scdr << m_data_link_lost_counter_; scdr << m_high_latency_data_link_lost_; scdr << m_engine_failure_; scdr << m_mission_failure_; scdr << m_geofence_violated_; scdr << m_failure_detector_status_; scdr << m_onboard_control_sensors_present_; scdr << m_onboard_control_sensors_enabled_; scdr << m_onboard_control_sensors_health_; scdr << m_latest_arming_reason_; scdr << m_latest_disarming_reason_; scdr << m_armed_time_; scdr << m_takeoff_time_; } void vehicle_status::deserialize(eprosima::fastcdr::Cdr &dcdr) { dcdr >> m_timestamp_; dcdr >> m_nav_state_; dcdr >> m_nav_state_timestamp_; dcdr >> m_arming_state_; dcdr >> m_hil_state_; dcdr >> m_failsafe_; dcdr >> m_failsafe_timestamp_; dcdr >> m_system_type_; dcdr >> m_system_id_; dcdr >> m_component_id_; dcdr >> m_vehicle_type_; dcdr >> m_is_vtol_; dcdr >> m_is_vtol_tailsitter_; dcdr >> m_vtol_fw_permanent_stab_; dcdr >> m_in_transition_mode_; dcdr >> m_in_transition_to_fw_; dcdr >> m_rc_signal_lost_; dcdr >> m_data_link_lost_; dcdr >> m_data_link_lost_counter_; dcdr >> m_high_latency_data_link_lost_; dcdr >> m_engine_failure_; dcdr >> m_mission_failure_; dcdr >> m_geofence_violated_; dcdr >> m_failure_detector_status_; dcdr >> m_onboard_control_sensors_present_; dcdr >> m_onboard_control_sensors_enabled_; dcdr >> m_onboard_control_sensors_health_; dcdr >> m_latest_arming_reason_; dcdr >> m_latest_disarming_reason_; dcdr >> m_armed_time_; dcdr >> m_takeoff_time_; } /*! * @brief This function sets a value in member timestamp_ * @param _timestamp_ New value for member timestamp_ */ void vehicle_status::timestamp_(uint64_t _timestamp_) { m_timestamp_ = _timestamp_; } /*! * @brief This function returns the value of member timestamp_ * @return Value of member timestamp_ */ uint64_t vehicle_status::timestamp_() const { return m_timestamp_; } /*! * @brief This function returns a reference to member timestamp_ * @return Reference to member timestamp_ */ uint64_t& vehicle_status::timestamp_() { return m_timestamp_; } /*! * @brief This function sets a value in member nav_state_ * @param _nav_state_ New value for member nav_state_ */ void vehicle_status::nav_state_(uint8_t _nav_state_) { m_nav_state_ = _nav_state_; } /*! * @brief This function returns the value of member nav_state_ * @return Value of member nav_state_ */ uint8_t vehicle_status::nav_state_() const { return m_nav_state_; } /*! * @brief This function returns a reference to member nav_state_ * @return Reference to member nav_state_ */ uint8_t& vehicle_status::nav_state_() { return m_nav_state_; } /*! * @brief This function sets a value in member nav_state_timestamp_ * @param _nav_state_timestamp_ New value for member nav_state_timestamp_ */ void vehicle_status::nav_state_timestamp_(uint64_t _nav_state_timestamp_) { m_nav_state_timestamp_ = _nav_state_timestamp_; } /*! * @brief This function returns the value of member nav_state_timestamp_ * @return Value of member nav_state_timestamp_ */ uint64_t vehicle_status::nav_state_timestamp_() const { return m_nav_state_timestamp_; } /*! * @brief This function returns a reference to member nav_state_timestamp_ * @return Reference to member nav_state_timestamp_ */ uint64_t& vehicle_status::nav_state_timestamp_() { return m_nav_state_timestamp_; } /*! * @brief This function sets a value in member arming_state_ * @param _arming_state_ New value for member arming_state_ */ void vehicle_status::arming_state_(uint8_t _arming_state_) { m_arming_state_ = _arming_state_; } /*! * @brief This function returns the value of member arming_state_ * @return Value of member arming_state_ */ uint8_t vehicle_status::arming_state_() const { return m_arming_state_; } /*! * @brief This function returns a reference to member arming_state_ * @return Reference to member arming_state_ */ uint8_t& vehicle_status::arming_state_() { return m_arming_state_; } /*! * @brief This function sets a value in member hil_state_ * @param _hil_state_ New value for member hil_state_ */ void vehicle_status::hil_state_(uint8_t _hil_state_) { m_hil_state_ = _hil_state_; } /*! * @brief This function returns the value of member hil_state_ * @return Value of member hil_state_ */ uint8_t vehicle_status::hil_state_() const { return m_hil_state_; } /*! * @brief This function returns a reference to member hil_state_ * @return Reference to member hil_state_ */ uint8_t& vehicle_status::hil_state_() { return m_hil_state_; } /*! * @brief This function sets a value in member failsafe_ * @param _failsafe_ New value for member failsafe_ */ void vehicle_status::failsafe_(bool _failsafe_) { m_failsafe_ = _failsafe_; } /*! * @brief This function returns the value of member failsafe_ * @return Value of member failsafe_ */ bool vehicle_status::failsafe_() const { return m_failsafe_; } /*! * @brief This function returns a reference to member failsafe_ * @return Reference to member failsafe_ */ bool& vehicle_status::failsafe_() { return m_failsafe_; } /*! * @brief This function sets a value in member failsafe_timestamp_ * @param _failsafe_timestamp_ New value for member failsafe_timestamp_ */ void vehicle_status::failsafe_timestamp_(uint64_t _failsafe_timestamp_) { m_failsafe_timestamp_ = _failsafe_timestamp_; } /*! * @brief This function returns the value of member failsafe_timestamp_ * @return Value of member failsafe_timestamp_ */ uint64_t vehicle_status::failsafe_timestamp_() const { return m_failsafe_timestamp_; } /*! * @brief This function returns a reference to member failsafe_timestamp_ * @return Reference to member failsafe_timestamp_ */ uint64_t& vehicle_status::failsafe_timestamp_() { return m_failsafe_timestamp_; } /*! * @brief This function sets a value in member system_type_ * @param _system_type_ New value for member system_type_ */ void vehicle_status::system_type_(uint8_t _system_type_) { m_system_type_ = _system_type_; } /*! * @brief This function returns the value of member system_type_ * @return Value of member system_type_ */ uint8_t vehicle_status::system_type_() const { return m_system_type_; } /*! * @brief This function returns a reference to member system_type_ * @return Reference to member system_type_ */ uint8_t& vehicle_status::system_type_() { return m_system_type_; } /*! * @brief This function sets a value in member system_id_ * @param _system_id_ New value for member system_id_ */ void vehicle_status::system_id_(uint8_t _system_id_) { m_system_id_ = _system_id_; } /*! * @brief This function returns the value of member system_id_ * @return Value of member system_id_ */ uint8_t vehicle_status::system_id_() const { return m_system_id_; } /*! * @brief This function returns a reference to member system_id_ * @return Reference to member system_id_ */ uint8_t& vehicle_status::system_id_() { return m_system_id_; } /*! * @brief This function sets a value in member component_id_ * @param _component_id_ New value for member component_id_ */ void vehicle_status::component_id_(uint8_t _component_id_) { m_component_id_ = _component_id_; } /*! * @brief This function returns the value of member component_id_ * @return Value of member component_id_ */ uint8_t vehicle_status::component_id_() const { return m_component_id_; } /*! * @brief This function returns a reference to member component_id_ * @return Reference to member component_id_ */ uint8_t& vehicle_status::component_id_() { return m_component_id_; } /*! * @brief This function sets a value in member vehicle_type_ * @param _vehicle_type_ New value for member vehicle_type_ */ void vehicle_status::vehicle_type_(uint8_t _vehicle_type_) { m_vehicle_type_ = _vehicle_type_; } /*! * @brief This function returns the value of member vehicle_type_ * @return Value of member vehicle_type_ */ uint8_t vehicle_status::vehicle_type_() const { return m_vehicle_type_; } /*! * @brief This function returns a reference to member vehicle_type_ * @return Reference to member vehicle_type_ */ uint8_t& vehicle_status::vehicle_type_() { return m_vehicle_type_; } /*! * @brief This function sets a value in member is_vtol_ * @param _is_vtol_ New value for member is_vtol_ */ void vehicle_status::is_vtol_(bool _is_vtol_) { m_is_vtol_ = _is_vtol_; } /*! * @brief This function returns the value of member is_vtol_ * @return Value of member is_vtol_ */ bool vehicle_status::is_vtol_() const { return m_is_vtol_; } /*! * @brief This function returns a reference to member is_vtol_ * @return Reference to member is_vtol_ */ bool& vehicle_status::is_vtol_() { return m_is_vtol_; } /*! * @brief This function sets a value in member is_vtol_tailsitter_ * @param _is_vtol_tailsitter_ New value for member is_vtol_tailsitter_ */ void vehicle_status::is_vtol_tailsitter_(bool _is_vtol_tailsitter_) { m_is_vtol_tailsitter_ = _is_vtol_tailsitter_; } /*! * @brief This function returns the value of member is_vtol_tailsitter_ * @return Value of member is_vtol_tailsitter_ */ bool vehicle_status::is_vtol_tailsitter_() const { return m_is_vtol_tailsitter_; } /*! * @brief This function returns a reference to member is_vtol_tailsitter_ * @return Reference to member is_vtol_tailsitter_ */ bool& vehicle_status::is_vtol_tailsitter_() { return m_is_vtol_tailsitter_; } /*! * @brief This function sets a value in member vtol_fw_permanent_stab_ * @param _vtol_fw_permanent_stab_ New value for member vtol_fw_permanent_stab_ */ void vehicle_status::vtol_fw_permanent_stab_(bool _vtol_fw_permanent_stab_) { m_vtol_fw_permanent_stab_ = _vtol_fw_permanent_stab_; } /*! * @brief This function returns the value of member vtol_fw_permanent_stab_ * @return Value of member vtol_fw_permanent_stab_ */ bool vehicle_status::vtol_fw_permanent_stab_() const { return m_vtol_fw_permanent_stab_; } /*! * @brief This function returns a reference to member vtol_fw_permanent_stab_ * @return Reference to member vtol_fw_permanent_stab_ */ bool& vehicle_status::vtol_fw_permanent_stab_() { return m_vtol_fw_permanent_stab_; } /*! * @brief This function sets a value in member in_transition_mode_ * @param _in_transition_mode_ New value for member in_transition_mode_ */ void vehicle_status::in_transition_mode_(bool _in_transition_mode_) { m_in_transition_mode_ = _in_transition_mode_; } /*! * @brief This function returns the value of member in_transition_mode_ * @return Value of member in_transition_mode_ */ bool vehicle_status::in_transition_mode_() const { return m_in_transition_mode_; } /*! * @brief This function returns a reference to member in_transition_mode_ * @return Reference to member in_transition_mode_ */ bool& vehicle_status::in_transition_mode_() { return m_in_transition_mode_; } /*! * @brief This function sets a value in member in_transition_to_fw_ * @param _in_transition_to_fw_ New value for member in_transition_to_fw_ */ void vehicle_status::in_transition_to_fw_(bool _in_transition_to_fw_) { m_in_transition_to_fw_ = _in_transition_to_fw_; } /*! * @brief This function returns the value of member in_transition_to_fw_ * @return Value of member in_transition_to_fw_ */ bool vehicle_status::in_transition_to_fw_() const { return m_in_transition_to_fw_; } /*! * @brief This function returns a reference to member in_transition_to_fw_ * @return Reference to member in_transition_to_fw_ */ bool& vehicle_status::in_transition_to_fw_() { return m_in_transition_to_fw_; } /*! * @brief This function sets a value in member rc_signal_lost_ * @param _rc_signal_lost_ New value for member rc_signal_lost_ */ void vehicle_status::rc_signal_lost_(bool _rc_signal_lost_) { m_rc_signal_lost_ = _rc_signal_lost_; } /*! * @brief This function returns the value of member rc_signal_lost_ * @return Value of member rc_signal_lost_ */ bool vehicle_status::rc_signal_lost_() const { return m_rc_signal_lost_; } /*! * @brief This function returns a reference to member rc_signal_lost_ * @return Reference to member rc_signal_lost_ */ bool& vehicle_status::rc_signal_lost_() { return m_rc_signal_lost_; } /*! * @brief This function sets a value in member data_link_lost_ * @param _data_link_lost_ New value for member data_link_lost_ */ void vehicle_status::data_link_lost_(bool _data_link_lost_) { m_data_link_lost_ = _data_link_lost_; } /*! * @brief This function returns the value of member data_link_lost_ * @return Value of member data_link_lost_ */ bool vehicle_status::data_link_lost_() const { return m_data_link_lost_; } /*! * @brief This function returns a reference to member data_link_lost_ * @return Reference to member data_link_lost_ */ bool& vehicle_status::data_link_lost_() { return m_data_link_lost_; } /*! * @brief This function sets a value in member data_link_lost_counter_ * @param _data_link_lost_counter_ New value for member data_link_lost_counter_ */ void vehicle_status::data_link_lost_counter_(uint8_t _data_link_lost_counter_) { m_data_link_lost_counter_ = _data_link_lost_counter_; } /*! * @brief This function returns the value of member data_link_lost_counter_ * @return Value of member data_link_lost_counter_ */ uint8_t vehicle_status::data_link_lost_counter_() const { return m_data_link_lost_counter_; } /*! * @brief This function returns a reference to member data_link_lost_counter_ * @return Reference to member data_link_lost_counter_ */ uint8_t& vehicle_status::data_link_lost_counter_() { return m_data_link_lost_counter_; } /*! * @brief This function sets a value in member high_latency_data_link_lost_ * @param _high_latency_data_link_lost_ New value for member high_latency_data_link_lost_ */ void vehicle_status::high_latency_data_link_lost_(bool _high_latency_data_link_lost_) { m_high_latency_data_link_lost_ = _high_latency_data_link_lost_; } /*! * @brief This function returns the value of member high_latency_data_link_lost_ * @return Value of member high_latency_data_link_lost_ */ bool vehicle_status::high_latency_data_link_lost_() const { return m_high_latency_data_link_lost_; } /*! * @brief This function returns a reference to member high_latency_data_link_lost_ * @return Reference to member high_latency_data_link_lost_ */ bool& vehicle_status::high_latency_data_link_lost_() { return m_high_latency_data_link_lost_; } /*! * @brief This function sets a value in member engine_failure_ * @param _engine_failure_ New value for member engine_failure_ */ void vehicle_status::engine_failure_(bool _engine_failure_) { m_engine_failure_ = _engine_failure_; } /*! * @brief This function returns the value of member engine_failure_ * @return Value of member engine_failure_ */ bool vehicle_status::engine_failure_() const { return m_engine_failure_; } /*! * @brief This function returns a reference to member engine_failure_ * @return Reference to member engine_failure_ */ bool& vehicle_status::engine_failure_() { return m_engine_failure_; } /*! * @brief This function sets a value in member mission_failure_ * @param _mission_failure_ New value for member mission_failure_ */ void vehicle_status::mission_failure_(bool _mission_failure_) { m_mission_failure_ = _mission_failure_; } /*! * @brief This function returns the value of member mission_failure_ * @return Value of member mission_failure_ */ bool vehicle_status::mission_failure_() const { return m_mission_failure_; } /*! * @brief This function returns a reference to member mission_failure_ * @return Reference to member mission_failure_ */ bool& vehicle_status::mission_failure_() { return m_mission_failure_; } /*! * @brief This function sets a value in member geofence_violated_ * @param _geofence_violated_ New value for member geofence_violated_ */ void vehicle_status::geofence_violated_(bool _geofence_violated_) { m_geofence_violated_ = _geofence_violated_; } /*! * @brief This function returns the value of member geofence_violated_ * @return Value of member geofence_violated_ */ bool vehicle_status::geofence_violated_() const { return m_geofence_violated_; } /*! * @brief This function returns a reference to member geofence_violated_ * @return Reference to member geofence_violated_ */ bool& vehicle_status::geofence_violated_() { return m_geofence_violated_; } /*! * @brief This function sets a value in member failure_detector_status_ * @param _failure_detector_status_ New value for member failure_detector_status_ */ void vehicle_status::failure_detector_status_(uint8_t _failure_detector_status_) { m_failure_detector_status_ = _failure_detector_status_; } /*! * @brief This function returns the value of member failure_detector_status_ * @return Value of member failure_detector_status_ */ uint8_t vehicle_status::failure_detector_status_() const { return m_failure_detector_status_; } /*! * @brief This function returns a reference to member failure_detector_status_ * @return Reference to member failure_detector_status_ */ uint8_t& vehicle_status::failure_detector_status_() { return m_failure_detector_status_; } /*! * @brief This function sets a value in member onboard_control_sensors_present_ * @param _onboard_control_sensors_present_ New value for member onboard_control_sensors_present_ */ void vehicle_status::onboard_control_sensors_present_(uint64_t _onboard_control_sensors_present_) { m_onboard_control_sensors_present_ = _onboard_control_sensors_present_; } /*! * @brief This function returns the value of member onboard_control_sensors_present_ * @return Value of member onboard_control_sensors_present_ */ uint64_t vehicle_status::onboard_control_sensors_present_() const { return m_onboard_control_sensors_present_; } /*! * @brief This function returns a reference to member onboard_control_sensors_present_ * @return Reference to member onboard_control_sensors_present_ */ uint64_t& vehicle_status::onboard_control_sensors_present_() { return m_onboard_control_sensors_present_; } /*! * @brief This function sets a value in member onboard_control_sensors_enabled_ * @param _onboard_control_sensors_enabled_ New value for member onboard_control_sensors_enabled_ */ void vehicle_status::onboard_control_sensors_enabled_(uint64_t _onboard_control_sensors_enabled_) { m_onboard_control_sensors_enabled_ = _onboard_control_sensors_enabled_; } /*! * @brief This function returns the value of member onboard_control_sensors_enabled_ * @return Value of member onboard_control_sensors_enabled_ */ uint64_t vehicle_status::onboard_control_sensors_enabled_() const { return m_onboard_control_sensors_enabled_; } /*! * @brief This function returns a reference to member onboard_control_sensors_enabled_ * @return Reference to member onboard_control_sensors_enabled_ */ uint64_t& vehicle_status::onboard_control_sensors_enabled_() { return m_onboard_control_sensors_enabled_; } /*! * @brief This function sets a value in member onboard_control_sensors_health_ * @param _onboard_control_sensors_health_ New value for member onboard_control_sensors_health_ */ void vehicle_status::onboard_control_sensors_health_(uint64_t _onboard_control_sensors_health_) { m_onboard_control_sensors_health_ = _onboard_control_sensors_health_; } /*! * @brief This function returns the value of member onboard_control_sensors_health_ * @return Value of member onboard_control_sensors_health_ */ uint64_t vehicle_status::onboard_control_sensors_health_() const { return m_onboard_control_sensors_health_; } /*! * @brief This function returns a reference to member onboard_control_sensors_health_ * @return Reference to member onboard_control_sensors_health_ */ uint64_t& vehicle_status::onboard_control_sensors_health_() { return m_onboard_control_sensors_health_; } /*! * @brief This function sets a value in member latest_arming_reason_ * @param _latest_arming_reason_ New value for member latest_arming_reason_ */ void vehicle_status::latest_arming_reason_(uint8_t _latest_arming_reason_) { m_latest_arming_reason_ = _latest_arming_reason_; } /*! * @brief This function returns the value of member latest_arming_reason_ * @return Value of member latest_arming_reason_ */ uint8_t vehicle_status::latest_arming_reason_() const { return m_latest_arming_reason_; } /*! * @brief This function returns a reference to member latest_arming_reason_ * @return Reference to member latest_arming_reason_ */ uint8_t& vehicle_status::latest_arming_reason_() { return m_latest_arming_reason_; } /*! * @brief This function sets a value in member latest_disarming_reason_ * @param _latest_disarming_reason_ New value for member latest_disarming_reason_ */ void vehicle_status::latest_disarming_reason_(uint8_t _latest_disarming_reason_) { m_latest_disarming_reason_ = _latest_disarming_reason_; } /*! * @brief This function returns the value of member latest_disarming_reason_ * @return Value of member latest_disarming_reason_ */ uint8_t vehicle_status::latest_disarming_reason_() const { return m_latest_disarming_reason_; } /*! * @brief This function returns a reference to member latest_disarming_reason_ * @return Reference to member latest_disarming_reason_ */ uint8_t& vehicle_status::latest_disarming_reason_() { return m_latest_disarming_reason_; } /*! * @brief This function sets a value in member armed_time_ * @param _armed_time_ New value for member armed_time_ */ void vehicle_status::armed_time_(uint64_t _armed_time_) { m_armed_time_ = _armed_time_; } /*! * @brief This function returns the value of member armed_time_ * @return Value of member armed_time_ */ uint64_t vehicle_status::armed_time_() const { return m_armed_time_; } /*! * @brief This function returns a reference to member armed_time_ * @return Reference to member armed_time_ */ uint64_t& vehicle_status::armed_time_() { return m_armed_time_; } /*! * @brief This function sets a value in member takeoff_time_ * @param _takeoff_time_ New value for member takeoff_time_ */ void vehicle_status::takeoff_time_(uint64_t _takeoff_time_) { m_takeoff_time_ = _takeoff_time_; } /*! * @brief This function returns the value of member takeoff_time_ * @return Value of member takeoff_time_ */ uint64_t vehicle_status::takeoff_time_() const { return m_takeoff_time_; } /*! * @brief This function returns a reference to member takeoff_time_ * @return Reference to member takeoff_time_ */ uint64_t& vehicle_status::takeoff_time_() { return m_takeoff_time_; } size_t vehicle_status::getKeyMaxCdrSerializedSize(size_t current_alignment) { size_t current_align = current_alignment; return current_align; } bool vehicle_status::isKeyDefined() { return false; } void vehicle_status::serializeKey(eprosima::fastcdr::Cdr &scdr) const { (void) scdr; }
26.822266
101
0.767446
PX4
9fc2c2a7f7a214ab9d6c5787343529ed720c8d07
36
cpp
C++
Software/CPU/myscrypt/build/cmake-3.12.3/Tests/CompileFeatures/cxx_alignas.cpp
duonglvtnaist/Multi-ROMix-Scrypt-Accelerator
9cb9d96c72c3e912fb7cfd5a786e50e4844a1ee8
[ "MIT" ]
107
2021-08-28T20:08:42.000Z
2022-03-22T08:02:16.000Z
Software/CPU/myscrypt/build/cmake-3.12.3/Tests/CompileFeatures/cxx_alignas.cpp
duonglvtnaist/Multi-ROMix-Scrypt-Accelerator
9cb9d96c72c3e912fb7cfd5a786e50e4844a1ee8
[ "MIT" ]
3
2021-09-08T02:18:00.000Z
2022-03-12T00:39:44.000Z
Software/CPU/myscrypt/build/cmake-3.12.3/Tests/CompileFeatures/cxx_alignas.cpp
duonglvtnaist/Multi-ROMix-Scrypt-Accelerator
9cb9d96c72c3e912fb7cfd5a786e50e4844a1ee8
[ "MIT" ]
16
2021-08-30T06:57:36.000Z
2022-03-22T08:05:52.000Z
struct S1 { alignas(8) int n; };
6
19
0.555556
duonglvtnaist
9fc323305aff865969d7b9c2ee63bd7009a1c554
4,413
cpp
C++
src/wire/wire2lua/lua_source_stream.cpp
zmij/wire
9981eb9ea182fc49ef7243eed26b9d37be70a395
[ "Artistic-2.0" ]
5
2016-04-07T19:49:39.000Z
2021-08-03T05:24:11.000Z
src/wire/wire2lua/lua_source_stream.cpp
zmij/wire
9981eb9ea182fc49ef7243eed26b9d37be70a395
[ "Artistic-2.0" ]
null
null
null
src/wire/wire2lua/lua_source_stream.cpp
zmij/wire
9981eb9ea182fc49ef7243eed26b9d37be70a395
[ "Artistic-2.0" ]
1
2020-12-27T11:47:31.000Z
2020-12-27T11:47:31.000Z
/* * lua_source_stream.cpp * * Created on: Nov 23, 2017 * Author: zmij */ #include <wire/idl/generator.hpp> #include <wire/idl/syntax_error.hpp> #include <wire/wire2lua/lua_source_stream.hpp> #include <iomanip> namespace wire { namespace idl { namespace lua { namespace { ::std::string const autogenerated = R"~(------------------------------------------------------------------------------ -- THIS FILE IS AUTOGENERATED BY wire2lua PROGRAM -- Any manual modifications can be lost ------------------------------------------------------------------------------ )~"; void write_offset(::std::ostream& os, int space_number) { if (space_number > 0) os << ::std::setw( space_number ) << ::std::setfill(' ') << " "; } } source_stream::source_stream(::std::string const& filename) : stream_{filename}, current_offset_{0}, tab_width_{4} { if (!stream_) { throw ::std::runtime_error("Failed to open output file " + filename); } stream_ << autogenerated; } void source_stream::write_offset(int temp) { stream_ << "\n"; lua::write_offset(stream_, (current_offset_ + temp) * tab_width_); } void source_stream::modify_offset(int delta) { current_offset_ += delta; if (current_offset_ < 0) current_offset_ = 0; } void source_stream::set_offset(int offset) { current_offset_ = offset; if (current_offset_ < 0) current_offset_ = 0; } source_stream& operator << (source_stream& os, mapped_type const& mt) { if (auto pt = ast::dynamic_entity_cast< ast::parametrized_type >(mt.type)) { os << "wire.types." << pt->name(); if (pt->name() == ast::VARIANT) { os << "({ "; for (auto const& p : pt->params()) { switch (p.which()) { case ast::template_param_type::type: os << mapped_type{ ::boost::get< ast::type_ptr >(p) } << ", "; break; default: throw grammar_error(mt.type->decl_position(), "Unexpected variant parameter"); } } os << "})"; } else if (pt->name() == ast::DICTONARY) { // Expect exactly two type params os << "("; for (auto p = pt->params().begin(); p != pt->params().end(); ++p) { if (p != pt->params().begin()) os << ", "; switch (p->which()) { case ast::template_param_type::type: os << mapped_type{ ::boost::get< ast::type_ptr >(*p) }; break; default: throw grammar_error(mt.type->decl_position(), "Unexpected dictionary parameter"); } } os << ")"; } else if (pt->name() == ast::ARRAY) { // Expect exactly two params: type and int os << "("; for (auto p = pt->params().begin(); p != pt->params().end(); ++p) { if (p != pt->params().begin()) os << ", "; switch (p->which()) { case ast::template_param_type::type: os << mapped_type{ ::boost::get< ast::type_ptr >(*p) }; break; case ast::template_param_type::integral: os << ::boost::get< ::std::string >(*p); break; default: throw grammar_error(mt.type->decl_position(), "Unexpected array parameter"); } } os << ")"; } else { os << "("; auto const& p = pt->params().front(); switch (p.which()) { case ast::template_param_type::type: os << mapped_type{ ::boost::get< ast::type_ptr >(p) }; break; default: throw grammar_error(mt.type->decl_position(), "Unexpected " + pt->name() + " parameter"); } os << ")"; } } else if (auto ref = ast::dynamic_entity_cast< ast::reference >(mt.type)) { os << "wire.types.type('proxy')"; } else { os << "wire.types.type('" << mt.type->get_qualified_name() << "')"; } return os; } } /* namespace lua */ } /* namespace idl */ } /* namespace wire */
30.434483
109
0.469748
zmij
9fc4485039011f4bd14e9b94b527b57e8878848e
3,077
cpp
C++
src/GBuffer.cpp
NotCamelCase/JBIC
6304678696b65f66c560ecea91a52b5a1f528a7c
[ "MIT" ]
5
2015-07-24T14:32:09.000Z
2021-06-13T18:02:52.000Z
src/GBuffer.cpp
NotCamelCase/JBIC
6304678696b65f66c560ecea91a52b5a1f528a7c
[ "MIT" ]
null
null
null
src/GBuffer.cpp
NotCamelCase/JBIC
6304678696b65f66c560ecea91a52b5a1f528a7c
[ "MIT" ]
1
2020-09-03T23:30:41.000Z
2020-09-03T23:30:41.000Z
#include <GBuffer.h> #include <Scene.h> GBuffer::GBuffer(Scene* scene, GLuint texUnit) : m_texUnitStart(texUnit), m_fbo(0), m_scene(scene) { assert(fillGBuffer() && "Error creating GBuffer content!"); } GBuffer::~GBuffer() { glDeleteFramebuffers(1, &m_fbo); } bool GBuffer::fillGBuffer() { glGenFramebuffers(1, &m_fbo); glBindFramebuffer(GL_FRAMEBUFFER, m_fbo); GLuint renderTex, posTex, normalTex, matKA, matKD, matKS; glGenRenderbuffers(1, &renderTex); glBindRenderbuffer(GL_RENDERBUFFER, renderTex); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_scene->getRenderParams().width, m_scene->getRenderParams().height); posTex = createGBufferTexture(GBufferTexType::VERTEX_ATTRIB_POS); normalTex = createGBufferTexture(GBufferTexType::VERTEX_ATTRIB_NORMAL); matKA = createGBufferTexture(GBufferTexType::MAT_ATTRIB_KA); matKD = createGBufferTexture(GBufferTexType::MAT_ATTRIB_KD); matKS = createGBufferTexture(GBufferTexType::MAT_ATTRIB_KS); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, renderTex); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, posTex, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, normalTex, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, matKA, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3, GL_TEXTURE_2D, matKD, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT4, GL_TEXTURE_2D, matKS, 0); // Depth - POS - NORMAL - MAT_KA - MAT_KD - MAT_KS GLenum db[] = { GL_NONE, GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3, GL_COLOR_ATTACHMENT4 }; const uint numDrawBuffers = 6; #ifdef DEBUG GLint maxDrawBuffers; glGetIntegerv(GL_MAX_DRAW_BUFFERS, &maxDrawBuffers); if (numDrawBuffers > maxDrawBuffers) LOG_ME("Frame buffer attachments exceeding max available draw buffers!!!"); #endif glDrawBuffers(numDrawBuffers, db); glBindFramebuffer(GL_FRAMEBUFFER, 0); return glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE; } GLuint GBuffer::createGBufferTexture(GBufferTexType texType) { GLuint tex; glGenTextures(1, &tex); glActiveTexture(m_texUnitStart++); glBindTexture(GL_TEXTURE_2D, tex); glTexStorage2D(GL_TEXTURE_2D, 1, getTextureFormat(texType), m_scene->getRenderParams().width, m_scene->getRenderParams().height); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); return tex; } uint GBuffer::getTextureFormat(GBufferTexType type) { switch (type) { case GBufferTexType::VERTEX_ATTRIB_POS: case GBufferTexType::VERTEX_ATTRIB_NORMAL: return GL_RGB32F; case GBufferTexType::VERTEX_ATTRIB_UV: return GL_RGB32F; case GBufferTexType::MAT_ATTRIB_KA: case GBufferTexType::MAT_ATTRIB_KD: case GBufferTexType::MAT_ATTRIB_KS: return GL_RGB8; } }
35.367816
130
0.809555
NotCamelCase
9fc644cb8aa87a0f9107502f02bc0d85ec21aa35
1,299
cpp
C++
Heap/K_Sorted_Array.cpp
susantabiswas/placementPrep
22a7574206ddc63eba89517f7b68a3d2f4d467f5
[ "MIT" ]
19
2018-12-02T05:59:44.000Z
2021-07-24T14:11:54.000Z
Heap/K_Sorted_Array.cpp
susantabiswas/placementPrep
22a7574206ddc63eba89517f7b68a3d2f4d467f5
[ "MIT" ]
null
null
null
Heap/K_Sorted_Array.cpp
susantabiswas/placementPrep
22a7574206ddc63eba89517f7b68a3d2f4d467f5
[ "MIT" ]
13
2019-04-25T16:20:00.000Z
2021-09-06T19:50:04.000Z
//given an array which is k sorted that means all the elements are atmost 'k' //distance far from where they should be if they would have been sorted //sort the array /* using heap: take first 'k' elements and then heapify it now for i = k to n-1 : pop min from heap and insert arr[i] into heap do this for the rest of the elements This works beacause an element is atmost 'k' distance far from its correct pos so if we take 'k' elements then we are sure to get its correct by having the nearby 'k' elements */ #include<iostream> #include<queue> #include<vector> using namespace std; //comparator for priority queue struct comp{ bool operator()(const int&a ,const int&b){ return a>b; } }; //sorts the array void kSortArray(vector<int> &arr, int k = 3){ int i = 0, j = 0; int n = arr.size(); //create a min priority queue priority_queue<int, vector<int>, comp> pq; //insert the first k elements for(; i<k; i++) pq.push(arr[i]); //now for the rest of the elements for(j = 0; i<n && j<n; i++,j++){ arr[j] = pq.top(); pq.pop(); pq.push(arr[i]); } while(!pq.empty()){ arr[j++] = pq.top(); pq.pop(); } } int main(){ vector<int> arr = {2, 6, 3, 12, 56, 8}; kSortArray(arr,3); for (int i = 0; i < arr.size(); ++i) { cout<<arr[i]<<" "; } cout<<endl; }
21.65
84
0.639723
susantabiswas
9fcf670e1f4b22da78554e8d65612f76447fca22
8,609
cc
C++
src/GRPCClient.cc
mkaguilera/mvtx
9e5e099a11131351b79aadea77ee5920100c352a
[ "BSD-2-Clause" ]
null
null
null
src/GRPCClient.cc
mkaguilera/mvtx
9e5e099a11131351b79aadea77ee5920100c352a
[ "BSD-2-Clause" ]
null
null
null
src/GRPCClient.cc
mkaguilera/mvtx
9e5e099a11131351b79aadea77ee5920100c352a
[ "BSD-2-Clause" ]
null
null
null
/* * GRPCClient.cc * * Created on: Jun 7, 2016 * Author: theo */ #include <cassert> #include <unistd.h> #include "GRPCClient.h" GRPCClient::RequestHandler::RequestHandler(GRPCClient *grpc_client, const std::string &addr) : _grpc_client(grpc_client), _addr(addr) {} GRPCClient::RequestHandler::~RequestHandler() { _cq.Shutdown(); } Status GRPCClient::RequestHandler::getStatus() { return (_status); } GRPCClient::ReadRequestHandler::ReadRequestHandler(GRPCClient *grpc_client, const std::string &addr, rpc_read_args_t *rpc_read_args) : GRPCClient::RequestHandler::RequestHandler(grpc_client, addr), _rpc_read_args(rpc_read_args), _reply_reader(_grpc_client->getStub(addr)-> AsyncRead(&_ctx, GRPCClient::makeReadRequest(_rpc_read_args->read_args), &_cq)) { _reply_reader->Finish(&_reply, &_status, (void *) this); } GRPCClient::ReadRequestHandler::~ReadRequestHandler() {} void GRPCClient::ReadRequestHandler::proceed() { void *tag; bool ok; _cq.Next(&tag, &ok); assert(tag == (void *) this); if (ok) { _rpc_read_args->status = _reply.status(); if (_rpc_read_args->status) _rpc_read_args->value = new std::string(_reply.value()); } } GRPCClient::WriteRequestHandler::WriteRequestHandler(GRPCClient *grpc_client, const std::string &addr, rpc_write_args_t *rpc_write_args) : GRPCClient::RequestHandler::RequestHandler(grpc_client, addr), _rpc_write_args(rpc_write_args), _reply_reader(_grpc_client->getStub(_addr)-> AsyncWrite(&_ctx, GRPCClient::makeWriteRequest(_rpc_write_args->write_args), &_cq)) { _reply_reader->Finish(&_reply, &_status, (void *) this); } GRPCClient::WriteRequestHandler::~WriteRequestHandler() {} void GRPCClient::WriteRequestHandler::proceed() { void *tag; bool ok; _cq.Next(&tag, &ok); assert(tag == (void *) this); if (ok) _rpc_write_args->status = _reply.status(); } GRPCClient::PhaseOneCommitRequestHandler::PhaseOneCommitRequestHandler(GRPCClient *grpc_client, const std::string &addr, rpc_p1c_args_t *rpc_p1c_args) : GRPCClient::RequestHandler::RequestHandler(grpc_client, addr), _rpc_p1c_args(rpc_p1c_args), _reply_reader(_grpc_client->getStub(_addr)-> AsyncP1C(&_ctx, GRPCClient::makePhaseOneCommitRequest(_rpc_p1c_args->p1c_args), &_cq)) { _reply_reader->Finish(&_reply, &_status, (void *) this); } GRPCClient::PhaseOneCommitRequestHandler::~PhaseOneCommitRequestHandler() {} void GRPCClient::PhaseOneCommitRequestHandler::proceed() { void *tag; bool ok; _cq.Next(&tag, &ok); assert(tag == (void *) this); if (ok) { for (int i = 0; i < _reply.node_size(); i++) _rpc_p1c_args->nodes->insert(_reply.node(i)); _rpc_p1c_args->vote = _reply.vote(); } } GRPCClient::PhaseTwoCommitRequestHandler::PhaseTwoCommitRequestHandler(GRPCClient *grpc_client, const std::string &addr, rpc_p2c_args_t *rpc_p2c_args) : GRPCClient::RequestHandler::RequestHandler(grpc_client, addr), _rpc_p2c_args(rpc_p2c_args), _reply_reader(_grpc_client->getStub(_addr)-> AsyncP2C(&_ctx, GRPCClient::makePhaseTwoCommitRequest(_rpc_p2c_args->p2c_args), &_cq)) { _reply_reader->Finish(&_reply, &_status, (void *) this); } GRPCClient::PhaseTwoCommitRequestHandler::~PhaseTwoCommitRequestHandler() {} void GRPCClient::PhaseTwoCommitRequestHandler::proceed() { void *tag; bool ok; _cq.Next(&tag, &ok); assert(tag == (void *) this); if (ok) for (int i = 0; i < _reply.node_size(); i++) _rpc_p2c_args->nodes->insert(_reply.node(i)); } GRPCClient::~GRPCClient () { _address_to_stub.clear(); _tag_to_handler.clear(); } void GRPCClient::makeStub(const std::string &addr) { std::unique_lock<std::mutex> lock(_mutex1); if (_address_to_stub.find(addr) == _address_to_stub.end()) _address_to_stub[addr] = Mvtkvs::NewStub(grpc::CreateChannel(addr, grpc::InsecureChannelCredentials())); } Mvtkvs::Stub *GRPCClient::getStub(std::string addr) { std::unique_lock<std::mutex> lock(_mutex1); return (_address_to_stub[addr].get()); } ReadRequest GRPCClient::makeReadRequest(const read_args_t *read_args) { ReadRequest res; res.set_tid(read_args->tid); res.set_start_ts(read_args->start_ts); res.set_key(read_args->key); return (res); } WriteRequest GRPCClient::makeWriteRequest(const write_args_t *write_args) { WriteRequest res; res.set_tid(write_args->tid); res.set_key(write_args->key); res.set_value(*(write_args->value)); return (res); } PhaseOneCommitRequest GRPCClient::makePhaseOneCommitRequest(const p1c_args_t *p1c_args) { PhaseOneCommitRequest res; res.set_tid(p1c_args->tid); res.set_start_ts(p1c_args->start_ts); res.set_commit_ts(p1c_args->commit_ts); for (std::set<uint64_t>::iterator it = p1c_args->read_nodes->begin(); it != p1c_args->read_nodes->end(); ++it) res.add_read_node(*it); for (std::set<uint64_t>::iterator it = p1c_args->write_nodes->begin(); it != p1c_args->write_nodes->end(); ++it) res.add_write_node(*it); return (res); } PhaseTwoCommitRequest GRPCClient::makePhaseTwoCommitRequest(const p2c_args_t *p2c_args) { PhaseTwoCommitRequest res; res.set_tid(p2c_args->tid); res.set_vote(p2c_args->vote); return (res); } bool GRPCClient::syncRPC(const std::string &addr, request_t request, void *args) { ClientContext ctx; Status status; makeStub(addr); switch (request) { case (TREAD): { rpc_read_args_t *rpc_read_args = (rpc_read_args_t *) args; ReadRequest request = GRPCClient::makeReadRequest(rpc_read_args->read_args); ReadReply reply; _mutex1.lock(); status = _address_to_stub[addr]->Read(&ctx, request, &reply); _mutex1.unlock(); rpc_read_args->status = status.ok() && reply.status(); if (rpc_read_args->status) rpc_read_args->value->assign(reply.value()); break; } case (TWRITE): { rpc_write_args_t *rpc_write_args = (rpc_write_args_t *) args; WriteRequest request = GRPCClient::makeWriteRequest(rpc_write_args->write_args); WriteReply reply; _mutex1.lock(); status = _address_to_stub[addr]->Write(&ctx, request, &reply); _mutex1.unlock(); rpc_write_args->status = status.ok() && reply.status(); break; } case (TP1C): { rpc_p1c_args_t *rpc_p1c_args = (rpc_p1c_args_t *) args; PhaseOneCommitRequest request = GRPCClient::makePhaseOneCommitRequest(rpc_p1c_args->p1c_args); PhaseOneCommitReply reply; _mutex1.lock(); status = _address_to_stub[addr]->P1C(&ctx, request, &reply); _mutex1.unlock(); if (status.ok()) { for (int i = 0; i < reply.node_size(); i++) rpc_p1c_args->nodes->insert(reply.node(i)); rpc_p1c_args->vote = reply.vote(); } break; } case (TP2C): { rpc_p2c_args_t *rpc_p2c_args = (rpc_p2c_args_t *) args; PhaseTwoCommitRequest request = GRPCClient::makePhaseTwoCommitRequest(rpc_p2c_args->p2c_args); PhaseTwoCommitReply reply; _mutex1.lock(); status = _address_to_stub[addr]->P2C(&ctx, request, &reply); _mutex1.unlock(); if (status.ok()) { for (int i = 0; i < reply.node_size(); i++) rpc_p2c_args->nodes->insert(reply.node(i)); } break; } } return (status.ok()); } void GRPCClient::asyncRPC(const std::string &addr, uint64_t tag, request_t request, void *args) { GRPCClient::RequestHandler *handler = NULL; makeStub(addr); switch(request) { case (TREAD): { handler = new ReadRequestHandler(this, addr, (rpc_read_args_t *) args); break; } case (TWRITE): { handler = new WriteRequestHandler(this, addr, (rpc_write_args_t *) args); break; } case (TP1C): { handler = new PhaseOneCommitRequestHandler(this, addr, (rpc_p1c_args_t *) args); break; } case (TP2C): { handler = new PhaseTwoCommitRequestHandler(this, addr, (rpc_p2c_args_t *) args); break; } } _mutex2.lock(); _tag_to_handler[tag] = handler; _mutex2.unlock(); } bool GRPCClient::waitAsyncReply(uint64_t tag) { bool res; std::unique_lock<std::mutex> lock(_mutex2); _tag_to_handler[tag]->proceed(); res = _tag_to_handler[tag]->getStatus().ok(); if (res) { _tag_to_handler.erase(tag); delete _tag_to_handler[tag]; } return (res); }
30.856631
120
0.66988
mkaguilera
9fd9ac4012c5ab9d5add284d0b4e1f424c723443
10,195
cc
C++
src/test/admin_socket.cc
rpratap-bot/ceph
9834961a66927ae856935591f2fd51082e2ee484
[ "MIT" ]
4
2020-04-08T03:42:02.000Z
2020-10-01T20:34:48.000Z
src/test/admin_socket.cc
rpratap-bot/ceph
9834961a66927ae856935591f2fd51082e2ee484
[ "MIT" ]
93
2020-03-26T14:29:14.000Z
2020-11-12T05:54:55.000Z
src/test/admin_socket.cc
rpratap-bot/ceph
9834961a66927ae856935591f2fd51082e2ee484
[ "MIT" ]
23
2020-03-24T10:28:44.000Z
2020-09-24T09:42:19.000Z
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2011 New Dream Network * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include "common/Mutex.h" #include "common/Cond.h" #include "common/admin_socket.h" #include "common/admin_socket_client.h" #include "common/ceph_argparse.h" #include "gtest/gtest.h" #include <stdint.h> #include <string.h> #include <string> #include <sys/un.h> class AdminSocketTest { public: explicit AdminSocketTest(AdminSocket *asokc) : m_asokc(asokc) { } bool init(const std::string &uri) { return m_asokc->init(uri); } string bind_and_listen(const std::string &sock_path, int *fd) { return m_asokc->bind_and_listen(sock_path, fd); } bool shutdown() { m_asokc->shutdown(); return true; } AdminSocket *m_asokc; }; TEST(AdminSocket, Teardown) { std::unique_ptr<AdminSocket> asokc = std::make_unique<AdminSocket>(g_ceph_context); AdminSocketTest asoct(asokc.get()); ASSERT_EQ(true, asoct.shutdown()); } TEST(AdminSocket, TeardownSetup) { std::unique_ptr<AdminSocket> asokc = std::make_unique<AdminSocket>(g_ceph_context); AdminSocketTest asoct(asokc.get()); ASSERT_EQ(true, asoct.shutdown()); ASSERT_EQ(true, asoct.init(get_rand_socket_path())); ASSERT_EQ(true, asoct.shutdown()); } TEST(AdminSocket, SendHelp) { std::unique_ptr<AdminSocket> asokc = std::make_unique<AdminSocket>(g_ceph_context); AdminSocketTest asoct(asokc.get()); ASSERT_EQ(true, asoct.shutdown()); ASSERT_EQ(true, asoct.init(get_rand_socket_path())); AdminSocketClient client(get_rand_socket_path()); { string help; ASSERT_EQ("", client.do_request("{\"prefix\":\"help\"}", &help)); ASSERT_NE(string::npos, help.find("\"list available commands\"")); } { string help; ASSERT_EQ("", client.do_request("{" " \"prefix\":\"help\"," " \"format\":\"xml\"," "}", &help)); ASSERT_NE(string::npos, help.find(">list available commands<")); } { string help; ASSERT_EQ("", client.do_request("{" " \"prefix\":\"help\"," " \"format\":\"UNSUPPORTED\"," "}", &help)); ASSERT_NE(string::npos, help.find("\"list available commands\"")); } ASSERT_EQ(true, asoct.shutdown()); } TEST(AdminSocket, SendNoOp) { std::unique_ptr<AdminSocket> asokc = std::make_unique<AdminSocket>(g_ceph_context); AdminSocketTest asoct(asokc.get()); ASSERT_EQ(true, asoct.shutdown()); ASSERT_EQ(true, asoct.init(get_rand_socket_path())); AdminSocketClient client(get_rand_socket_path()); string version; ASSERT_EQ("", client.do_request("{\"prefix\":\"0\"}", &version)); ASSERT_EQ(CEPH_ADMIN_SOCK_VERSION, version); ASSERT_EQ(true, asoct.shutdown()); } TEST(AdminSocket, SendTooLongRequest) { std::unique_ptr<AdminSocket> asokc = std::make_unique<AdminSocket>(g_ceph_context); AdminSocketTest asoct(asokc.get()); ASSERT_EQ(true, asoct.shutdown()); ASSERT_EQ(true, asoct.init(get_rand_socket_path())); AdminSocketClient client(get_rand_socket_path()); string version; string request(16384, 'a'); //if admin_socket cannot handle it, segfault will happened. ASSERT_NE("", client.do_request(request, &version)); ASSERT_EQ(true, asoct.shutdown()); } class MyTest : public AdminSocketHook { bool call(std::string_view command, const cmdmap_t& cmdmap, std::string_view format, bufferlist& result) override { std::vector<std::string> args; cmd_getval(g_ceph_context, cmdmap, "args", args); result.append(command); result.append("|"); string resultstr; for (std::vector<std::string>::iterator it = args.begin(); it != args.end(); ++it) { if (it != args.begin()) resultstr += ' '; resultstr += *it; } result.append(resultstr); return true; } }; TEST(AdminSocket, RegisterCommand) { std::unique_ptr<AdminSocket> asokc = std::make_unique<AdminSocket>(g_ceph_context); std::unique_ptr<AdminSocketHook> my_test_asok = std::make_unique<MyTest>(); AdminSocketTest asoct(asokc.get()); ASSERT_EQ(true, asoct.shutdown()); ASSERT_EQ(true, asoct.init(get_rand_socket_path())); AdminSocketClient client(get_rand_socket_path()); ASSERT_EQ(0, asoct.m_asokc->register_command("test", "test", my_test_asok.get(), "")); string result; ASSERT_EQ("", client.do_request("{\"prefix\":\"test\"}", &result)); ASSERT_EQ("test|", result); ASSERT_EQ(true, asoct.shutdown()); } class MyTest2 : public AdminSocketHook { bool call(std::string_view command, const cmdmap_t& cmdmap, std::string_view format, bufferlist& result) override { std::vector<std::string> args; cmd_getval(g_ceph_context, cmdmap, "args", args); result.append(command); result.append("|"); string resultstr; for (std::vector<std::string>::iterator it = args.begin(); it != args.end(); ++it) { if (it != args.begin()) resultstr += ' '; resultstr += *it; } result.append(resultstr); return true; } }; TEST(AdminSocket, RegisterCommandPrefixes) { std::unique_ptr<AdminSocket> asokc = std::make_unique<AdminSocket>(g_ceph_context); std::unique_ptr<AdminSocketHook> my_test_asok = std::make_unique<MyTest>(); std::unique_ptr<AdminSocketHook> my_test2_asok = std::make_unique<MyTest2>(); AdminSocketTest asoct(asokc.get()); ASSERT_EQ(true, asoct.shutdown()); ASSERT_EQ(true, asoct.init(get_rand_socket_path())); AdminSocketClient client(get_rand_socket_path()); ASSERT_EQ(0, asoct.m_asokc->register_command("test", "test name=args,type=CephString,n=N", my_test_asok.get(), "")); ASSERT_EQ(0, asoct.m_asokc->register_command("test command", "test command name=args,type=CephString,n=N", my_test2_asok.get(), "")); string result; ASSERT_EQ("", client.do_request("{\"prefix\":\"test\"}", &result)); ASSERT_EQ("test|", result); ASSERT_EQ("", client.do_request("{\"prefix\":\"test command\"}", &result)); ASSERT_EQ("test command|", result); ASSERT_EQ("", client.do_request("{\"prefix\":\"test command\",\"args\":[\"post\"]}", &result)); ASSERT_EQ("test command|post", result); ASSERT_EQ("", client.do_request("{\"prefix\":\"test command\",\"args\":[\" post\"]}", &result)); ASSERT_EQ("test command| post", result); ASSERT_EQ("", client.do_request("{\"prefix\":\"test\",\"args\":[\"this thing\"]}", &result)); ASSERT_EQ("test|this thing", result); ASSERT_EQ("", client.do_request("{\"prefix\":\"test\",\"args\":[\" command post\"]}", &result)); ASSERT_EQ("test| command post", result); ASSERT_EQ("", client.do_request("{\"prefix\":\"test\",\"args\":[\" this thing\"]}", &result)); ASSERT_EQ("test| this thing", result); ASSERT_EQ(true, asoct.shutdown()); } class BlockingHook : public AdminSocketHook { public: Mutex _lock; Cond _cond; BlockingHook() : _lock("BlockingHook::_lock") {} bool call(std::string_view command, const cmdmap_t& cmdmap, std::string_view format, bufferlist& result) override { Mutex::Locker l(_lock); _cond.Wait(_lock); return true; } }; TEST(AdminSocketClient, Ping) { string path = get_rand_socket_path(); std::unique_ptr<AdminSocket> asokc = std::make_unique<AdminSocket>(g_ceph_context); AdminSocketClient client(path); // no socket { bool ok; std::string result = client.ping(&ok); EXPECT_NE(std::string::npos, result.find("No such file or directory")); ASSERT_FALSE(ok); } // file exists but does not allow connections (no process, wrong type...) ASSERT_TRUE(::creat(path.c_str(), 0777)); { bool ok; std::string result = client.ping(&ok); #if defined(__APPLE__) || defined(__FreeBSD__) const char* errmsg = "Socket operation on non-socket"; #else const char* errmsg = "Connection refused"; #endif EXPECT_NE(std::string::npos, result.find(errmsg)); ASSERT_FALSE(ok); } // a daemon is connected to the socket { AdminSocketTest asoct(asokc.get()); ASSERT_TRUE(asoct.init(path)); bool ok; std::string result = client.ping(&ok); EXPECT_EQ("", result); ASSERT_TRUE(ok); ASSERT_TRUE(asoct.shutdown()); } // hardcoded five seconds timeout prevents infinite blockage { AdminSocketTest asoct(asokc.get()); BlockingHook *blocking = new BlockingHook(); ASSERT_EQ(0, asoct.m_asokc->register_command("0", "0", blocking, "")); ASSERT_TRUE(asoct.init(path)); bool ok; std::string result = client.ping(&ok); EXPECT_NE(std::string::npos, result.find("Resource temporarily unavailable")); ASSERT_FALSE(ok); { Mutex::Locker l(blocking->_lock); blocking->_cond.Signal(); } ASSERT_TRUE(asoct.shutdown()); delete blocking; } } TEST(AdminSocket, bind_and_listen) { string path = get_rand_socket_path(); std::unique_ptr<AdminSocket> asokc = std::make_unique<AdminSocket>(g_ceph_context); AdminSocketTest asoct(asokc.get()); // successfull bind { int fd = 0; string message; message = asoct.bind_and_listen(path, &fd); ASSERT_NE(0, fd); ASSERT_EQ("", message); ASSERT_EQ(0, ::close(fd)); ASSERT_EQ(0, ::unlink(path.c_str())); } // silently discard an existing file { int fd = 0; string message; ASSERT_TRUE(::creat(path.c_str(), 0777)); message = asoct.bind_and_listen(path, &fd); ASSERT_NE(0, fd); ASSERT_EQ("", message); ASSERT_EQ(0, ::close(fd)); ASSERT_EQ(0, ::unlink(path.c_str())); } // do not take over a live socket { ASSERT_TRUE(asoct.init(path)); int fd = 0; string message; message = asoct.bind_and_listen(path, &fd); std::cout << "message: " << message << std::endl; EXPECT_NE(std::string::npos, message.find("File exists")); ASSERT_TRUE(asoct.shutdown()); } } /* * Local Variables: * compile-command: "cd .. ; * make unittest_admin_socket && * valgrind \ * --max-stackframe=20000000 --tool=memcheck \ * ./unittest_admin_socket --debug-asok 20 # --gtest_filter=AdminSocket*.* * " * End: */
32.365079
135
0.670917
rpratap-bot
9fda21634fe05289b2f757b3c3960e17085a5c27
453
cc
C++
src/kafka/kafka_handle.cc
Lanceolata/log2hdfs
1ea1b572567dbe1e65f4134849b1970f21baf741
[ "MIT" ]
null
null
null
src/kafka/kafka_handle.cc
Lanceolata/log2hdfs
1ea1b572567dbe1e65f4134849b1970f21baf741
[ "MIT" ]
null
null
null
src/kafka/kafka_handle.cc
Lanceolata/log2hdfs
1ea1b572567dbe1e65f4134849b1970f21baf741
[ "MIT" ]
null
null
null
// Copyright (c) 2017 Lanceolata #include "kafka/kafka_handle.h" namespace log2hdfs { std::shared_ptr<KafkaHandle> KafkaHandle::Init(rd_kafka_t* rk) { if (!rk) return nullptr; return std::make_shared<KafkaHandle>(rk); } const std::string KafkaHandle::MemberId() const { char* str = rd_kafka_memberid(rk_); std::string memberid = str ? str : ""; if (str) rd_kafka_mem_free(rk_, str); return memberid; } } // namespace log2hdfs
20.590909
64
0.693157
Lanceolata
9fdb04ad6e1367b30414caaaf5a1d4ffbcdc5487
4,076
cpp
C++
mozilla/gfx/layers/basic/TextureClientX11.cpp
naver/webgraphics
4f9b9aa6a13428b5872dd020eaf34ec77b33f240
[ "MS-PL" ]
5
2016-12-20T15:48:05.000Z
2020-05-01T20:12:09.000Z
mozilla/gfx/layers/basic/TextureClientX11.cpp
naver/webgraphics
4f9b9aa6a13428b5872dd020eaf34ec77b33f240
[ "MS-PL" ]
null
null
null
mozilla/gfx/layers/basic/TextureClientX11.cpp
naver/webgraphics
4f9b9aa6a13428b5872dd020eaf34ec77b33f240
[ "MS-PL" ]
2
2016-12-20T15:48:13.000Z
2019-12-10T15:15:05.000Z
/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*- // * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "mozilla/layers/TextureClientX11.h" #include "mozilla/layers/CompositableClient.h" #include "mozilla/layers/CompositableForwarder.h" #include "mozilla/layers/ISurfaceAllocator.h" #include "mozilla/layers/ShadowLayerUtilsX11.h" #include "mozilla/gfx/2D.h" #include "mozilla/gfx/Logging.h" #include "gfxXlibSurface.h" #include "gfx2DGlue.h" #include "mozilla/X11Util.h" #include <X11/Xlib.h> using namespace mozilla; using namespace mozilla::gfx; namespace mozilla { namespace layers { X11TextureData::X11TextureData(gfx::IntSize aSize, gfx::SurfaceFormat aFormat, bool aClientDeallocation, bool aIsCrossProcess, gfxXlibSurface* aSurface) : mSize(aSize) , mFormat(aFormat) , mSurface(aSurface) , mClientDeallocation(aClientDeallocation) , mIsCrossProcess(aIsCrossProcess) { MOZ_ASSERT(mSurface); } bool X11TextureData::Lock(OpenMode aMode, FenceHandle*) { return true; } void X11TextureData::Unlock() { if (mSurface && mIsCrossProcess) { FinishX(DefaultXDisplay()); } } bool X11TextureData::Serialize(SurfaceDescriptor& aOutDescriptor) { MOZ_ASSERT(mSurface); if (!mSurface) { return false; } if (!mClientDeallocation) { // Pass to the host the responsibility of freeing the pixmap. ReleasePixmap means // the underlying pixmap will not be deallocated in mSurface's destructor. // ToSurfaceDescriptor is at most called once per TextureClient. mSurface->ReleasePixmap(); } aOutDescriptor = SurfaceDescriptorX11(mSurface); return true; } already_AddRefed<gfx::DrawTarget> X11TextureData::BorrowDrawTarget() { MOZ_ASSERT(mSurface); if (!mSurface) { return nullptr; } IntSize size = mSurface->GetSize(); RefPtr<gfx::DrawTarget> dt = Factory::CreateDrawTargetForCairoSurface(mSurface->CairoSurface(), size); return dt.forget(); } bool X11TextureData::UpdateFromSurface(gfx::SourceSurface* aSurface) { RefPtr<DrawTarget> dt = BorrowDrawTarget(); if (!dt) { return false; } dt->CopySurface(aSurface, IntRect(IntPoint(), aSurface->GetSize()), IntPoint()); return true; } void X11TextureData::Deallocate(ISurfaceAllocator*) { mSurface = nullptr; } TextureData* X11TextureData::CreateSimilar(ISurfaceAllocator* aAllocator, TextureFlags aFlags, TextureAllocationFlags aAllocFlags) const { return X11TextureData::Create(mSize, mFormat, aFlags, aAllocator); } X11TextureData* X11TextureData::Create(gfx::IntSize aSize, gfx::SurfaceFormat aFormat, TextureFlags aFlags, ISurfaceAllocator* aAllocator) { MOZ_ASSERT(aSize.width >= 0 && aSize.height >= 0); if (aSize.width <= 0 || aSize.height <= 0 || aSize.width > XLIB_IMAGE_SIDE_SIZE_LIMIT || aSize.height > XLIB_IMAGE_SIDE_SIZE_LIMIT) { gfxDebug() << "Asking for X11 surface of invalid size " << aSize.width << "x" << aSize.height; return nullptr; } gfxImageFormat imageFormat = SurfaceFormatToImageFormat(aFormat); RefPtr<gfxASurface> surface = gfxPlatform::GetPlatform()->CreateOffscreenSurface(aSize, imageFormat); if (!surface || surface->GetType() != gfxSurfaceType::Xlib) { NS_ERROR("creating Xlib surface failed!"); return nullptr; } gfxXlibSurface* xlibSurface = static_cast<gfxXlibSurface*>(surface.get()); bool crossProcess = !aAllocator->IsSameProcess(); X11TextureData* texture = new X11TextureData(aSize, aFormat, !!(aFlags & TextureFlags::DEALLOCATE_CLIENT), crossProcess, xlibSurface); if (crossProcess) { FinishX(DefaultXDisplay()); } return texture; } } // namespace } // namespace
27.917808
104
0.686212
naver
9fdb09273c63226f542a55c84cc12ba9588c67ce
2,924
hpp
C++
Includes/Rosetta/PlayMode/Managers/CostManager.hpp
Hearthstonepp/Hearthstonepp
ee17ae6de1ee0078dab29d75c0fbe727a14e850e
[ "MIT" ]
62
2017-08-21T14:11:00.000Z
2018-04-23T16:09:02.000Z
Includes/Rosetta/PlayMode/Managers/CostManager.hpp
Hearthstonepp/Hearthstonepp
ee17ae6de1ee0078dab29d75c0fbe727a14e850e
[ "MIT" ]
37
2017-08-21T11:13:07.000Z
2018-04-30T08:58:41.000Z
Includes/Rosetta/PlayMode/Managers/CostManager.hpp
Hearthstonepp/Hearthstonepp
ee17ae6de1ee0078dab29d75c0fbe727a14e850e
[ "MIT" ]
10
2017-08-21T03:44:12.000Z
2018-01-10T22:29:10.000Z
// This code is based on Sabberstone project. // Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva // RosettaStone is hearthstone simulator using C++ with reinforcement learning. // Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon #ifndef ROSETTASTONE_PLAYMODE_COST_MANAGER_HPP #define ROSETTASTONE_PLAYMODE_COST_MANAGER_HPP #include <Rosetta/PlayMode/Auras/AdaptiveCostEffect.hpp> #include <optional> namespace RosettaStone::PlayMode { //! //! \brief CostManager class. //! //! This class manages the cost of the card. It is affected by cost aura, //! adaptive effect and enchantment. //! class CostManager { public: //! Default constructor. CostManager() = default; //! Calculates the value of the cost by considering the factors //! such as cost aura, adaptive effect and enchantment. //! \return cost The original value of the cost. //! \return The final value of the cost. int GetCost(int cost); //! Queues the update. void QueueUpdate(); //! Applies older entity's cost enchantments to the new one. //! \param newCardCost The cost of new card. //! \return The applied value of the cost. int EntityChanged(int newCardCost); //! Adds the aura that affects the cost. //! \param effectOp The effect operator to affect the cost value. //! \param value The value to affect the cost value. void AddCostAura(EffectOperator effectOp, int value); //! Removes the aura that affects the cost. //! \param effectOp The effect operator to affect the cost value. //! \param value The value to affect the cost value. void RemoveCostAura(EffectOperator effectOp, int value); //! Activates the adaptive effect that affects the cost. //! \param effect The adaptive cost effect to change the cost value. void ActivateAdaptiveEffect(AdaptiveCostEffect* effect); //! Updates the adaptive effect that affects the cost. //! \param value The value that affects the cost value to update. void UpdateAdaptiveEffect(int value = -1); //! Deactivates the adaptive effect that affects the cost. void DeactivateAdaptiveEffect(); //! Adds the enchantment that affects the cost. //! \param effectOp The effect operator to affect the cost value. //! \param value The value to affect the cost value. void AddCostEnchantment(EffectOperator effectOp, int value); private: //! Internal method of GetCost(). //! \return cost The original value of the cost. //! \return The final value of the cost. int GetCostInternal(int cost); std::vector<std::pair<EffectOperator, int>> m_costEffects; std::vector<std::pair<EffectOperator, int>> m_costEnchantments; int m_cachedValue = 0; bool m_toBeUpdated = true; AdaptiveCostEffect* m_adaptiveCostEffect = nullptr; }; } // namespace RosettaStone::PlayMode #endif // ROSETTASTONE_PLAYMODE_COST_MANAGER_HPP
35.228916
79
0.718194
Hearthstonepp
9fe4b95874e619cc13b8b9eac6346a531f84b57b
4,209
cxx
C++
src/AcdCalib.cxx
fermi-lat/AcdUtil
0fc8537ebc7c90dec9cb4a72e1ee274b78dd1b09
[ "BSD-3-Clause" ]
null
null
null
src/AcdCalib.cxx
fermi-lat/AcdUtil
0fc8537ebc7c90dec9cb4a72e1ee274b78dd1b09
[ "BSD-3-Clause" ]
null
null
null
src/AcdCalib.cxx
fermi-lat/AcdUtil
0fc8537ebc7c90dec9cb4a72e1ee274b78dd1b09
[ "BSD-3-Clause" ]
null
null
null
#include "../AcdUtil/AcdCalib.h" #include "CalibData/Acd/AcdPed.h" #include "CalibData/Acd/AcdGain.h" #include "CalibData/Acd/AcdVeto.h" #include "CalibData/Acd/AcdCno.h" #include "CalibData/Acd/AcdRange.h" #include "CalibData/Acd/AcdHighRange.h" #include "CalibData/Acd/AcdCoherentNoise.h" #include "CalibData/Acd/AcdRibbon.h" #include <iostream> namespace { // The following define the standard calib. values CalibData::AcdCalibObj::STATUS ok( CalibData::AcdCalibObj::OK ); CalibData::AcdPed idealPed( CalibData::AcdPed(0.,0.,ok) ); // all pedestals are null CalibData::AcdGain ribbonGain( CalibData::AcdGain(56.875,25.4,ok) ); // ribbons CalibData::AcdGain tileGain ( CalibData::AcdGain(204.75,50.,ok) ); // most tiles CalibData::AcdGain tile_12mmGain( CalibData::AcdGain(245.7,50.,ok) ); // 12mm thick tiles CalibData::AcdGain naGain ( CalibData::AcdGain(-1.,0.,ok) ); // NA channels CalibData::AcdVeto idealVeto ( CalibData::AcdVeto(-1.,0.,ok) );// veto fires at 50 counts PHA CalibData::AcdCno idealCno ( CalibData::AcdCno(50.,0.,ok) ); // cno pedestals are ideal CalibData::AcdRange idealRange ( CalibData::AcdRange(4000.,40.,ok));; // Switch occurs at 4000 in low range = 0 in High Range CalibData::AcdHighRange idealHighRange (CalibData::AcdHighRange(0.,2.04,4000.,ok));// Pedestal = 0, slope = 2.4 PHA/mip, saturates at 4000 PHA CalibData::AcdCoherentNoise idealCoherentNoise (CalibData::AcdCoherentNoise(0.,0.,0.,0.,ok));// Amplitude is 0, no oscillation // for testing (30 PHA counts, time constant of 500 ticks, oscillation of 500 ticks, phase -1. CalibData::AcdCoherentNoise realCoherentNoise(CalibData::AcdCoherentNoise(30.,800.,0.0054,-1.,ok)); // PMT is on + side of detector CalibData::AcdRibbon idealRibbon_Plus( CalibData::AcdRibbon(0.4,0.6,0.8,1.4,2.2,3.0,200.,ok)); // PMT is on - side of detector CalibData::AcdRibbon idealRibbon_Minus( CalibData::AcdRibbon(3.0,2.2,1.4,0.8,0.6,0.4,200.,ok)); } CalibData::AcdCalibObj* AcdCalib::getIdeal(AcdCalibData::CALTYPE cType, idents::AcdId id, unsigned pmt) { switch ( cType ) { case AcdCalibData::PEDESTAL: return &idealPed; case AcdCalibData::GAIN: case AcdCalibData::RIBBON: break; case AcdCalibData::VETO: return &idealVeto ; case AcdCalibData::CNO: return &idealCno; case AcdCalibData::RANGE: return &idealRange; case AcdCalibData::HIGH_RANGE: return &idealHighRange ; // switch to test //case AcdCalibData::COHERENT_NOISE: return &realCoherentNoise ; case AcdCalibData::COHERENT_NOISE: return &idealCoherentNoise ; default: return 0; } if ( cType == AcdCalibData::GAIN ) { if ( id.ribbon() ) { return &ribbonGain; } else if ( id.tile() ) { if ( id.face() == 0 && id.row() == 2 ) { return &tile_12mmGain; } else { return &tileGain; } } return &naGain; } else if ( cType == AcdCalibData::RIBBON ) { switch ( id.id() ) { case 500: case 501: case 601: case 603: return pmt == 0 ? &idealRibbon_Plus : &idealRibbon_Minus; case 502: case 503: case 600: case 602: return pmt == 0 ? &idealRibbon_Minus : &idealRibbon_Plus; default: return 0; } } return 0; } ICalibPathSvc::CalibItem AcdCalib::calibItem(AcdCalibData::CALTYPE cType) { switch ( cType ) { case AcdCalibData::PEDESTAL: return ICalibPathSvc::Calib_ACD_Ped ; case AcdCalibData::GAIN: return ICalibPathSvc::Calib_ACD_ElecGain ; case AcdCalibData::VETO: return ICalibPathSvc::Calib_ACD_ThreshVeto ; case AcdCalibData::CNO: return ICalibPathSvc::Calib_ACD_ThreshHigh ; case AcdCalibData::RANGE: return ICalibPathSvc::Calib_ACD_Range ; case AcdCalibData::HIGH_RANGE: return ICalibPathSvc::Calib_ACD_HighRange ; case AcdCalibData::COHERENT_NOISE: return ICalibPathSvc::Calib_ACD_CoherentNoise ; case AcdCalibData::RIBBON: return ICalibPathSvc::Calib_ACD_Ribbon ; default: ; } return ICalibPathSvc::Calib_COUNT; }
40.471154
146
0.665954
fermi-lat
9fe9571953e4d4146a418a8b4c8819d9753e8af5
2,374
hpp
C++
Aha/Aha/Math/Color.hpp
templateguy/aha
8965f3dfa318a8ee02e38fa082bbc5c8c6afa100
[ "MIT" ]
null
null
null
Aha/Aha/Math/Color.hpp
templateguy/aha
8965f3dfa318a8ee02e38fa082bbc5c8c6afa100
[ "MIT" ]
null
null
null
Aha/Aha/Math/Color.hpp
templateguy/aha
8965f3dfa318a8ee02e38fa082bbc5c8c6afa100
[ "MIT" ]
1
2018-04-27T05:48:41.000Z
2018-04-27T05:48:41.000Z
// // Color.hpp // Aha // // Created by Priyanshi Thakur on 01/05/18. // Copyright © 2018 Saurabh Sinha. All rights reserved. // #pragma once #include "../Math/Vec3.hpp" #include "../Math/Vec4.hpp" namespace aha { class Color : public Vec4f { public: Color() : Vec4f() { ; } Color(const Color& color) : Vec4f(color) { ; } Color(const Vec3f& color, float alpha) : Color(color.r, color.g, color.b, alpha) { ; } Color(const Vec3i& color, int alpha) : Color(color.r / 255.f, color.g / 255.f, color.b / 255.f, alpha / 255.f) { ; } Color(const Vec3f& color) : Color(color, 1.0f) { ; } Color(const Vec3i& color) : Color(color, 255) { ; } Color(const Vec4f& color) : Vec4f(color.r, color.g, color.b, color.a) { ; } Color(const Vec4i& color) : Vec4f(color.r / 255.f, color.g / 255.f, color.b / 255.f, color.a / 255.f) { ; } Color(float intensity, float alpha) : Color(Vec3f(intensity, intensity, alpha)) { ; } Color(int intensity, int alpha) : Color(Vec3i(intensity, intensity, alpha)) { ; } Color(float r, float g, float b, float a) : Vec4f(r, g, b, a) { ; } Color(int r, int g, int b, int a) : Color(Vec4i(r, g, b, a)) { ; } const Color& operator =(const Color& rhs) { r = rhs.r; g = rhs.g; b = rhs.g; a = rhs.a; return *this; } Color contrastingColor() const { float luminance = 0.299f + 0.587f + 0.144f + 0.f; return Color(luminance < 0.5f ? 1.f : 0.f, 1.f); } /// Allows for conversion between this Color and NanoVG's representation. inline operator NVGcolor () const { NVGcolor color; color.r = r; color.g = g; color.b = b; color.a = a; return color; } }; }
21.981481
118
0.420388
templateguy
9feb4218ede377ed9357259d7f8705e59a7bd910
4,349
cpp
C++
tiamoPCI/source/pci.agpintrf.cpp
godspeed1989/WDUtils
69057e92a5759487ef6bd62a85db24644759b42c
[ "BSD-2-Clause" ]
13
2015-05-29T14:18:53.000Z
2020-08-12T14:26:33.000Z
tiamoPCI/source/pci.agpintrf.cpp
godspeed1989/WDUtils
69057e92a5759487ef6bd62a85db24644759b42c
[ "BSD-2-Clause" ]
null
null
null
tiamoPCI/source/pci.agpintrf.cpp
godspeed1989/WDUtils
69057e92a5759487ef6bd62a85db24644759b42c
[ "BSD-2-Clause" ]
11
2015-06-10T19:27:28.000Z
2020-03-05T10:14:41.000Z
//******************************************************************** // created: 27:7:2008 0:07 // file: pci.agpintrf.cpp // author: tiamo // purpose: agp interface //******************************************************************** #include "stdafx.h" #pragma alloc_text("PAGE",agpintrf_Constructor) #pragma alloc_text("PAGE",agpintrf_Initializer) #pragma alloc_text("PAGE",agpintrf_Reference) #pragma alloc_text("PAGE",agpintrf_Dereference) #pragma alloc_text("PAGE",PciPnpTranslateBusAddress) #pragma alloc_text("PAGE",PciPnpWriteConfig) // // constructor [checked] // NTSTATUS agpintrf_Constructor(__in PPCI_COMMON_EXTENSION CommonExt,__in PPCI_INTERFACE PciInterface, __in PVOID Data,__in USHORT Version,__in USHORT Size,__in PINTERFACE Interface) { PAGED_CODE(); PPCI_PDO_EXTENSION PdoExt = reinterpret_cast<PPCI_PDO_EXTENSION>(CommonExt); if(PdoExt->BaseClass != PCI_CLASS_BRIDGE_DEV || PdoExt->SubClass != PCI_SUBCLASS_BR_PCI_TO_PCI) return STATUS_NOT_SUPPORTED; if(PdoExt->TargetAgpCapabilityId != PCI_CAPABILITY_ID_AGP_TARGET) { PPCI_FDO_EXTENSION ParentFdoExt = PdoExt->ParentFdoExtension; if(ParentFdoExt != ParentFdoExt->BusRootFdoExtension) return STATUS_NOT_SUPPORTED; NTSTATUS Status = STATUS_SUCCESS; PdoExt = 0; __try { KeEnterCriticalRegion(); KeWaitForSingleObject(&ParentFdoExt->ChildListLock,Executive,KernelMode,FALSE,0); PPCI_PDO_EXTENSION ChildPdoExt = CONTAINING_RECORD(ParentFdoExt->ChildPdoList.Next,PCI_PDO_EXTENSION,Common.ListEntry); while(ChildPdoExt) { if(ChildPdoExt->BaseClass == PCI_CLASS_BRIDGE_DEV && ChildPdoExt->SubClass == PCI_SUBCLASS_BR_HOST && ChildPdoExt->TargetAgpCapabilityId) { if(PdoExt) try_leave(Status = STATUS_NOT_SUPPORTED) else PdoExt = ChildPdoExt; } ChildPdoExt = CONTAINING_RECORD(ChildPdoExt->Common.ListEntry.Next,PCI_PDO_EXTENSION,Common.ListEntry); } } __finally { KeSetEvent(&ParentFdoExt->ChildListLock,IO_NO_INCREMENT,FALSE); KeLeaveCriticalRegion(); } if(!NT_SUCCESS(Status)) return Status; } if(PdoExt) { Interface->Version = 1; Interface->Context = PdoExt; Interface->Size = sizeof(AGP_TARGET_BUS_INTERFACE_STANDARD); Interface->InterfaceDereference = reinterpret_cast<PINTERFACE_DEREFERENCE>(&agpintrf_Dereference); Interface->InterfaceReference = reinterpret_cast<PINTERFACE_REFERENCE>(&agpintrf_Reference); PAGP_TARGET_BUS_INTERFACE_STANDARD AgpInterface = reinterpret_cast<PAGP_TARGET_BUS_INTERFACE_STANDARD>(Interface); AgpInterface->SetBusData = reinterpret_cast<PGET_SET_DEVICE_DATA>(&PciWriteAgpConfig); AgpInterface->GetBusData = reinterpret_cast<PGET_SET_DEVICE_DATA>(&PciReadAgpConfig); AgpInterface->CapabilityID = PdoExt->TargetAgpCapabilityId; return STATUS_SUCCESS; } return STATUS_NO_SUCH_DEVICE; } // // initializer [checked] // NTSTATUS agpintrf_Initializer(__in PPCI_ARBITER_INSTANCE Instance) { PAGED_CODE(); ASSERTMSG("PCI agpintrf_Initializer, unexpected call.",FALSE); return STATUS_UNSUCCESSFUL; } // // reference [checked] // VOID agpintrf_Reference(__in PPCI_PDO_EXTENSION PdoExt) { PAGED_CODE(); ASSERT(PdoExt->Common.ExtensionType == PciPdoExtensionType); if(InterlockedIncrement(&PdoExt->BusInterfaceReferenceCount) == 1) ObReferenceObject(PdoExt->PhysicalDeviceObject); } // // dereference [checked] // VOID agpintrf_Dereference(__in PPCI_PDO_EXTENSION PdoExt) { PAGED_CODE(); ASSERT(PdoExt->Common.ExtensionType == PciPdoExtensionType); if(InterlockedDecrement(&PdoExt->BusInterfaceReferenceCount) == 0) ObDereferenceObject(PdoExt->PhysicalDeviceObject); } // // write config [checked] // ULONG PciWriteAgpConfig(__in PPCI_PDO_EXTENSION PdoExt,__in ULONG DataType,__in PVOID Buffer,__in ULONG Offset,__in ULONG Length) { ASSERT(PdoExt->Common.ExtensionType == PciPdoExtensionType); PciWriteDeviceSpace(PdoExt,DataType,Buffer,Offset,Length,&Length); return Length; } // // read config [checked] // ULONG PciReadAgpConfig(__in PPCI_PDO_EXTENSION PdoExt,__in ULONG DataType,__in PVOID Buffer,__in ULONG Offset,__in ULONG Length) { ASSERT(PdoExt->Common.ExtensionType == PciPdoExtensionType); PciReadDeviceSpace(PdoExt,DataType,Buffer,Offset,Length,&Length); return Length; }
29.585034
141
0.74201
godspeed1989
9ff346f51e74e53433c92387bf26cfed6598535d
990
cpp
C++
Dynamic Programming/Filling_bookcase_shelves.cpp
Razdeep/LeetCode-Solutions
934cadbf42f5c5da2c16778c9d2353df203dbd85
[ "MIT" ]
1
2019-02-14T14:20:28.000Z
2019-02-14T14:20:28.000Z
Dynamic Programming/Filling_bookcase_shelves.cpp
Razdeep/LeetCode-Solutions
934cadbf42f5c5da2c16778c9d2353df203dbd85
[ "MIT" ]
null
null
null
Dynamic Programming/Filling_bookcase_shelves.cpp
Razdeep/LeetCode-Solutions
934cadbf42f5c5da2c16778c9d2353df203dbd85
[ "MIT" ]
null
null
null
class Solution { #define trace(x) cout << #x << ": " << x << endl; public: int minHeightShelves(vector<vector<int>>& books, int shelfWidth) { int oo = int(1e9); int n = int(books.size()); vector<int> dp(n, 0); int current_width = 0; const int WIDTH = 0; const int HEIGHT = 1; dp[0] = books[0][HEIGHT]; for (int i = 1; i < n; ++i) { dp[i] = dp[i - 1] + books[i][HEIGHT]; current_width = books[i][WIDTH]; int max_height_in_bottom_shelf = books[i][HEIGHT]; for (int j = i - 1; j >= 0 && (books[j][WIDTH] + current_width <= shelfWidth); --j) { max_height_in_bottom_shelf = max(max_height_in_bottom_shelf, books[j][HEIGHT]); dp[i] = min(dp[i], (j - 1 >= 0 ? dp[j - 1] : 0) + max_height_in_bottom_shelf); current_width += books[j][WIDTH]; } } return dp[n - 1]; } };
36.666667
97
0.483838
Razdeep
9ff59d3cac54cd8209ed57751e49f24f08645d63
1,263
cpp
C++
Evaluate Reverse Polish Notation.cpp
durgirajesh/Leetcode
18b11cd90e8a5ce33f4029d5b7edf9502273bc76
[ "MIT" ]
2
2020-06-25T12:46:13.000Z
2021-07-06T06:34:33.000Z
Evaluate Reverse Polish Notation.cpp
durgirajesh/Leetcode
18b11cd90e8a5ce33f4029d5b7edf9502273bc76
[ "MIT" ]
null
null
null
Evaluate Reverse Polish Notation.cpp
durgirajesh/Leetcode
18b11cd90e8a5ce33f4029d5b7edf9502273bc76
[ "MIT" ]
null
null
null
class Solution { public: int evalRPN(vector<string>& tokens) { stack<long> st; int n=tokens.size(); for(string str : tokens){ if(str=="+" || str=="-" || str=="*" || str=="/"){ int num1, num2; if(!st.empty()){ num1 = st.top(); st.pop(); } if(!st.empty()){ num2 = st.top(); st.pop(); } long result = 0; char ch = str[0]; switch(ch){ case '+' : result = num2 + num1; break; case '-' : result = num2 - num1; break; case '/' : result = num2 / num1; break; case '*' : result = num2*num1; break; } st.push(result); } else{ int n=atoi(str.c_str()); st.push(n); } } return st.top(); } };
28.704545
62
0.262866
durgirajesh
9ffd23b0bc01c42e4f6bb23fabef45a1af9031f9
65
cpp
C++
Profiles/prog.cpp
hemishv111/Hacktoberfest2k19
ead7c6c7cdd569e730a48257c7ca1ba2f76dfbae
[ "MIT" ]
22
2019-10-10T12:16:58.000Z
2020-10-28T09:09:52.000Z
Profiles/prog.cpp
hemishv111/Hacktoberfest2k19
ead7c6c7cdd569e730a48257c7ca1ba2f76dfbae
[ "MIT" ]
49
2019-10-09T11:23:06.000Z
2020-10-01T07:26:14.000Z
Profiles/prog.cpp
hemishv111/Hacktoberfest2k19
ead7c6c7cdd569e730a48257c7ca1ba2f76dfbae
[ "MIT" ]
80
2019-10-06T16:40:06.000Z
2020-10-22T16:34:58.000Z
include<iostream.h> int main() { cout<<"1"; cout<<"Hello"; }
9.285714
19
0.569231
hemishv111
b003e2a6c476dbee85b20b2d39d445b8d735481f
781
cpp
C++
splus.tech/Source.cpp
sehe/splus.tech
c476305ef23253bb268d977aaf5b7f6ac60d9b3f
[ "MIT" ]
2
2020-06-30T16:36:06.000Z
2021-08-05T11:52:25.000Z
splus.tech/Source.cpp
sehe/splus.tech
c476305ef23253bb268d977aaf5b7f6ac60d9b3f
[ "MIT" ]
null
null
null
splus.tech/Source.cpp
sehe/splus.tech
c476305ef23253bb268d977aaf5b7f6ac60d9b3f
[ "MIT" ]
1
2020-07-07T01:26:34.000Z
2020-07-07T01:26:34.000Z
#include <string> #include <iostream> #include <vector> #include "WebS.h" #include <algorithm> #include "menu.h" using namespace std; int main(int argc, char* argv[]) { if (argc > 1 && argv[1][0] == '/') { if (argv[1][1] == 's') { string IP = argv[2]; int port = stoi(argv[3]); WebS siteserv(IP.c_str(), port); if (siteserv.init() != 0) { return 0; } cout << "Server started" << endl; siteserv.run(); system("pause"); } if (argv[1][1] == '?') { help_menu_view(); } if (argv[1][1] == 'm') { man_menu_view(); } } else { string IP = "0.0.0.0"; int port = 80; WebS siteserv(IP.c_str(), port); if (siteserv.init() != 0) { return 0; } cout << "Server started" << endl; siteserv.run(); system("pause"); } return 0; }
18.595238
37
0.541613
sehe
b004e46b025814211cde93694094cc7a960cc93c
39,694
cpp
C++
Source/HeliumRain/UI/Menus/FlareSkirmishSetupMenu.cpp
zhyinty/HeliumRain
0096b9c9e9d0c0949d18624ea74b4991fdd175a2
[ "BSD-3-Clause" ]
646
2016-07-18T19:16:35.000Z
2022-03-27T17:16:57.000Z
Source/HeliumRain/UI/Menus/FlareSkirmishSetupMenu.cpp
zhyinty/HeliumRain
0096b9c9e9d0c0949d18624ea74b4991fdd175a2
[ "BSD-3-Clause" ]
2
2020-06-22T07:23:11.000Z
2020-06-29T07:01:32.000Z
Source/HeliumRain/UI/Menus/FlareSkirmishSetupMenu.cpp
zhyinty/HeliumRain
0096b9c9e9d0c0949d18624ea74b4991fdd175a2
[ "BSD-3-Clause" ]
114
2016-07-19T00:52:44.000Z
2022-01-27T06:09:42.000Z
#include "HeliumRain/UI/Menus/FlareSkirmishSetupMenu.h" #include "../../Flare.h" #include "../../Data/FlareCompanyCatalog.h" #include "../../Data/FlareSpacecraftCatalog.h" #include "../../Data/FlareSpacecraftComponentsCatalog.h" #include "../../Data/FlareCustomizationCatalog.h" #include "../../Data/FlareOrbitalMap.h" #include "../../Game/FlareGame.h" #include "../../Game/FlareSaveGame.h" #include "../../Game/FlareSkirmishManager.h" #include "../../Game/FlareGameUserSettings.h" #include "../../Player/FlareMenuPawn.h" #include "../../Player/FlareMenuManager.h" #include "../../Player/FlarePlayerController.h" #define LOCTEXT_NAMESPACE "FlareSkirmishSetupMenu" #define MAX_ASTEROIDS 50 #define MAX_DEBRIS_PERCENTAGE 25 /*---------------------------------------------------- Construct ----------------------------------------------------*/ void SFlareSkirmishSetupMenu::Construct(const FArguments& InArgs) { // Data MenuManager = InArgs._MenuManager; const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); int32 SideWidth = 0.65 * Theme.ContentWidth; int32 Width = 1 * Theme.ContentWidth; int32 LabelWidth = 0.225 * Theme.ContentWidth; int32 ListHeight = 880; // Build structure ChildSlot .HAlign(HAlign_Fill) .VAlign(VAlign_Fill) [ SNew(SOverlay) // Main + SOverlay::Slot() [ SNew(SVerticalBox) // Title + SVerticalBox::Slot() .AutoHeight() .HAlign(HAlign_Center) .Padding(Theme.ContentPadding) [ SNew(STextBlock) .Text(LOCTEXT("SkirmishSetupTitle", "New skirmish")) .TextStyle(&Theme.SpecialTitleFont) ] // Content + SVerticalBox::Slot() .AutoHeight() [ SNew(SHorizontalBox) // Sector settings + SHorizontalBox::Slot() .HAlign(HAlign_Left) .AutoWidth() [ SNew(SBox) .WidthOverride(SideWidth) [ SNew(SVerticalBox) // Title + SVerticalBox::Slot() .AutoHeight() .HAlign(HAlign_Left) .Padding(Theme.TitlePadding) [ SNew(STextBlock) .Text(LOCTEXT("SkirmishSectorSettingssTitle", "Settings")) .TextStyle(&Theme.SubTitleFont) ] // Opponent selector + SVerticalBox::Slot() .HAlign(HAlign_Left) .AutoHeight() .Padding(Theme.ContentPadding) [ SNew(SHorizontalBox) // Text + SHorizontalBox::Slot() .AutoWidth() [ SNew(SBox) .WidthOverride(LabelWidth) .Padding(FMargin(0, 20, 0, 0)) [ SNew(STextBlock) .Text(LOCTEXT("EnemyLabel", "Enemy company")) .TextStyle(&Theme.TextFont) ] ] // List + SHorizontalBox::Slot() .AutoWidth() .Padding(Theme.ContentPadding) [ SAssignNew(CompanySelector, SFlareDropList<FFlareCompanyDescription>) .OptionsSource(&MenuManager->GetPC()->GetGame()->GetCompanyCatalog()->Companies) .OnGenerateWidget(this, &SFlareSkirmishSetupMenu::OnGenerateCompanyComboLine) .HeaderWidth(6) .ItemWidth(6) [ SNew(SBox) .Padding(Theme.ListContentPadding) [ SNew(STextBlock) .Text(this, &SFlareSkirmishSetupMenu::OnGetCurrentCompanyComboLine) .TextStyle(&Theme.TextFont) ] ] ] ] // Planet selector + SVerticalBox::Slot() .HAlign(HAlign_Left) .AutoHeight() .Padding(Theme.ContentPadding) [ SNew(SHorizontalBox) // Text + SHorizontalBox::Slot() .AutoWidth() [ SNew(SBox) .WidthOverride(LabelWidth) .Padding(FMargin(0, 20, 0, 0)) [ SNew(STextBlock) .Text(LOCTEXT("PlanetLabel", "Planetary body")) .TextStyle(&Theme.TextFont) ] ] // List + SHorizontalBox::Slot() .AutoWidth() .Padding(Theme.ContentPadding) [ SAssignNew(PlanetSelector, SFlareDropList<FFlareSectorCelestialBodyDescription>) .OptionsSource(&MenuManager->GetPC()->GetGame()->GetOrbitalBodies()->OrbitalBodies) .OnGenerateWidget(this, &SFlareSkirmishSetupMenu::OnGeneratePlanetComboLine) .HeaderWidth(6) .ItemWidth(6) [ SNew(SBox) .Padding(Theme.ListContentPadding) [ SNew(STextBlock) .Text(this, &SFlareSkirmishSetupMenu::OnGetCurrentPlanetComboLine) .TextStyle(&Theme.TextFont) ] ] ] ] // Altitude + SVerticalBox::Slot() .HAlign(HAlign_Left) .AutoHeight() [ SNew(SBox) .WidthOverride(Theme.ContentWidth) [ SNew(SHorizontalBox) // Text + SHorizontalBox::Slot() .AutoWidth() .Padding(Theme.ContentPadding) [ SNew(SBox) .WidthOverride(LabelWidth) [ SNew(STextBlock) .Text(LOCTEXT("AltitudeLabel", "Altitude")) .TextStyle(&Theme.TextFont) ] ] // Slider + SHorizontalBox::Slot() .VAlign(VAlign_Center) .Padding(Theme.ContentPadding) [ SAssignNew(AltitudeSlider, SSlider) .Value(0) .Style(&Theme.SliderStyle) ] // Label + SHorizontalBox::Slot() .AutoWidth() .Padding(Theme.ContentPadding) [ SNew(SBox) .WidthOverride(LabelWidth / 2) [ SNew(STextBlock) .TextStyle(&Theme.TextFont) .Text(this, &SFlareSkirmishSetupMenu::GetAltitudeValue) ] ] ] ] // Asteroids + SVerticalBox::Slot() .HAlign(HAlign_Left) .AutoHeight() [ SNew(SBox) .WidthOverride(Theme.ContentWidth) [ SNew(SHorizontalBox) // Text + SHorizontalBox::Slot() .AutoWidth() .Padding(Theme.ContentPadding) [ SNew(SBox) .WidthOverride(LabelWidth) [ SNew(STextBlock) .Text(LOCTEXT("AsteroidLabel", "Asteroids")) .TextStyle(&Theme.TextFont) ] ] // Slider + SHorizontalBox::Slot() .VAlign(VAlign_Center) .Padding(Theme.ContentPadding) [ SAssignNew(AsteroidSlider, SSlider) .Value(0) .Style(&Theme.SliderStyle) .OnValueChanged(this, &SFlareSkirmishSetupMenu::OnAsteroidSliderChanged, true) ] // Label + SHorizontalBox::Slot() .AutoWidth() .Padding(Theme.ContentPadding) [ SNew(SBox) .WidthOverride(LabelWidth / 2) [ SNew(STextBlock) .TextStyle(&Theme.TextFont) .Text(this, &SFlareSkirmishSetupMenu::GetAsteroidValue) ] ] ] ] // Debris + SVerticalBox::Slot() .HAlign(HAlign_Left) .AutoHeight() [ SNew(SBox) .WidthOverride(Theme.ContentWidth) [ SNew(SHorizontalBox) // Text + SHorizontalBox::Slot() .AutoWidth() .Padding(Theme.ContentPadding) [ SNew(SBox) .WidthOverride(LabelWidth) [ SNew(STextBlock) .Text(LOCTEXT("DebrisLabel", "Debris density")) .TextStyle(&Theme.TextFont) ] ] // Slider + SHorizontalBox::Slot() .VAlign(VAlign_Center) .Padding(Theme.ContentPadding) [ SAssignNew(DebrisSlider, SSlider) .Value(0) .Style(&Theme.SliderStyle) .OnValueChanged(this, &SFlareSkirmishSetupMenu::OnDebrisSliderChanged, true) ] // Label + SHorizontalBox::Slot() .AutoWidth() .Padding(Theme.ContentPadding) [ SNew(SBox) .WidthOverride(LabelWidth / 2) [ SNew(STextBlock) .TextStyle(&Theme.TextFont) .Text(this, &SFlareSkirmishSetupMenu::GetDebrisValue) ] ] ] ] // Icy + SVerticalBox::Slot() .HAlign(HAlign_Left) .AutoHeight() .Padding(Theme.ContentPadding) [ SNew(SHorizontalBox) // Icy + SHorizontalBox::Slot() .AutoWidth() .Padding(Theme.SmallContentPadding) [ SAssignNew(IcyButton, SFlareButton) .Text(LOCTEXT("Icy", "Icy sector")) .HelpText(LOCTEXT("IcyInfo", "This sector will encompass an icy cloud of water particles")) .Toggle(true) ] // Debris + SHorizontalBox::Slot() .AutoWidth() .Padding(Theme.SmallContentPadding) [ SAssignNew(MetalDebrisButton, SFlareButton) .Text(LOCTEXT("MetallicDebris", "Battle debris")) .HelpText(LOCTEXT("MetallicDebrisInfo", "This sector will feature remains of a battle, instead of asteroid fragments")) .Toggle(true) ] ] ] ] // Player fleet + SHorizontalBox::Slot() .HAlign(HAlign_Fill) [ SNew(SBox) .WidthOverride(Width) [ SNew(SVerticalBox) // Title + SVerticalBox::Slot() .AutoHeight() .HAlign(HAlign_Left) .Padding(Theme.TitlePadding) [ SNew(STextBlock) .Text(this, &SFlareSkirmishSetupMenu::GetPlayerFleetTitle) .TextStyle(&Theme.SubTitleFont) ] // Add ship + SVerticalBox::Slot() .HAlign(HAlign_Left) .AutoHeight() [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() [ SNew(SFlareButton) .Transparent(true) .Width(4) .Text(LOCTEXT("AddPlayerShip", "Add ship")) .HelpText(this, &SFlareSkirmishSetupMenu::GetAddToPlayerFleetText) .IsDisabled(this, &SFlareSkirmishSetupMenu::IsAddToPlayerFleetDisabled) .OnClicked(this, &SFlareSkirmishSetupMenu::OnOrderShip, true) ] + SHorizontalBox::Slot() .AutoWidth() [ SNew(SFlareButton) .Transparent(true) .Width(4) .Text(LOCTEXT("ClearPlayerFleet", "Clear fleet")) .OnClicked(this, &SFlareSkirmishSetupMenu::OnClearFleet, true) ] + SHorizontalBox::Slot() .AutoWidth() [ SNew(SFlareButton) .Transparent(true) .Width(4) .Text(LOCTEXT("SortFleet", "Sort fleet")) .OnClicked(this, &SFlareSkirmishSetupMenu::OnSortPlayerFleet) ] ] + SVerticalBox::Slot() [ SNew(SBox) .HeightOverride(ListHeight) [ SNew(SScrollBox) .Style(&Theme.ScrollBoxStyle) .ScrollBarStyle(&Theme.ScrollBarStyle) + SScrollBox::Slot() .Padding(Theme.ContentPadding) [ SAssignNew(PlayerSpacecraftList, SListView<TSharedPtr<FFlareSkirmishSpacecraftOrder>>) .ListItemsSource(&PlayerSpacecraftListData) .SelectionMode(ESelectionMode::None) .OnGenerateRow(this, &SFlareSkirmishSetupMenu::OnGenerateSpacecraftLine) ] ] ] ] ] // Enemy fleet + SHorizontalBox::Slot() .HAlign(HAlign_Right) .AutoWidth() [ SNew(SBox) .WidthOverride(Width) [ SNew(SVerticalBox) // Title + SVerticalBox::Slot() .AutoHeight() .HAlign(HAlign_Left) .Padding(Theme.TitlePadding) [ SNew(STextBlock) .Text(this, &SFlareSkirmishSetupMenu::GetEnemyFleetTitle) .TextStyle(&Theme.SubTitleFont) ] // Add ship + SVerticalBox::Slot() .HAlign(HAlign_Left) .AutoHeight() [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() [ SNew(SFlareButton) .Transparent(true) .Width(4) .Text(LOCTEXT("AddEnemyShip", "Add ship")) .HelpText(this, &SFlareSkirmishSetupMenu::GetAddToEnemyFleetText) .IsDisabled(this, &SFlareSkirmishSetupMenu::IsAddToEnemyFleetDisabled) .OnClicked(this, &SFlareSkirmishSetupMenu::OnOrderShip, false) ] + SHorizontalBox::Slot() .AutoWidth() [ SNew(SFlareButton) .Transparent(true) .Width(4) .Text(LOCTEXT("ClearEnemyFleet", "Clear fleet")) .OnClicked(this, &SFlareSkirmishSetupMenu::OnClearFleet, false) ] + SHorizontalBox::Slot() .AutoWidth() [ SNew(SFlareButton) .Transparent(true) .Width(4) .Text(LOCTEXT("AutomaticFleet", "Automatic fleet")) .OnClicked(this, &SFlareSkirmishSetupMenu::OnAutoCreateEnemyFleet) ] ] + SVerticalBox::Slot() [ SNew(SBox) .HeightOverride(ListHeight) [ SNew(SScrollBox) .Style(&Theme.ScrollBoxStyle) .ScrollBarStyle(&Theme.ScrollBarStyle) + SScrollBox::Slot() .Padding(Theme.ContentPadding) [ SAssignNew(EnemySpacecraftList, SListView<TSharedPtr<FFlareSkirmishSpacecraftOrder>>) .ListItemsSource(&EnemySpacecraftListData) .SelectionMode(ESelectionMode::None) .OnGenerateRow(this, &SFlareSkirmishSetupMenu::OnGenerateSpacecraftLine) ] ] ] ] ] ] // Start + SVerticalBox::Slot() .HAlign(HAlign_Left) .VAlign(VAlign_Bottom) .Padding(Theme.ContentPadding) [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() [ SNew(SFlareButton) .Transparent(true) .Width(4) .Text(LOCTEXT("Back", "Back")) .OnClicked(this, &SFlareSkirmishSetupMenu::OnMainMenu) ] + SHorizontalBox::Slot() .AutoWidth() [ SNew(SFlareButton) .Transparent(true) .Width(4) .Icon(FFlareStyleSet::GetIcon("Load")) .Text(LOCTEXT("Start", "Start skirmish")) .HelpText(this, &SFlareSkirmishSetupMenu::GetStartHelpText) .IsDisabled(this, &SFlareSkirmishSetupMenu::IsStartDisabled) .OnClicked(this, &SFlareSkirmishSetupMenu::OnStartSkirmish) ] ] ] // Customization overlay + SOverlay::Slot() .HAlign(HAlign_Center) .VAlign(VAlign_Center) [ SAssignNew(UpgradeBox, SBackgroundBlur) .BlurRadius(Theme.BlurRadius) .BlurStrength(Theme.BlurStrength) .HAlign(HAlign_Left) .VAlign(VAlign_Top) .Visibility(EVisibility::Collapsed) [ SNew(SBorder) .BorderImage(&Theme.BackgroundBrush) [ SNew(SVerticalBox) // Top line + SVerticalBox::Slot() .AutoHeight() .Padding(Theme.TitlePadding) [ SNew(SHorizontalBox) // Icon + SHorizontalBox::Slot() .AutoWidth() [ SNew(SImage) .Image(FFlareStyleSet::GetIcon("ShipUpgradeMedium")) ] // Title + SHorizontalBox::Slot() .HAlign(HAlign_Fill) .VAlign(VAlign_Center) [ SNew(STextBlock) .Text(LOCTEXT("ShipUpgradeTitle", "Upgrade spacecraft")) .TextStyle(&Theme.TitleFont) ] // Close button + SHorizontalBox::Slot() .HAlign(HAlign_Right) .AutoWidth() [ SNew(SFlareButton) .Text(FText()) .Icon(FFlareStyleSet::GetIcon("Delete")) .OnClicked(this, &SFlareSkirmishSetupMenu::OnCloseUpgradePanel) .Width(1) ] ] // Upgrades + SVerticalBox::Slot() .AutoHeight() .Padding(Theme.TitlePadding) [ SNew(SHorizontalBox) // Engine + SHorizontalBox::Slot() .AutoWidth() [ SNew(SBox) .WidthOverride(0.25 * Theme.ContentWidth) [ SNew(SVerticalBox) + SVerticalBox::Slot() .AutoHeight() .Padding(Theme.TitlePadding) [ SNew(STextBlock) .Text(LOCTEXT("EngineUpgradeTitle", "Orbital engines")) .TextStyle(&Theme.SubTitleFont) ] + SVerticalBox::Slot() .VAlign(VAlign_Top) [ SAssignNew(OrbitalEngineBox, SVerticalBox) ] ] ] // RCS + SHorizontalBox::Slot() .AutoWidth() [ SNew(SBox) .WidthOverride(0.25 * Theme.ContentWidth) [ SNew(SVerticalBox) + SVerticalBox::Slot() .AutoHeight() .Padding(Theme.TitlePadding) [ SNew(STextBlock) .Text(LOCTEXT("RCSUpgradeTitle", "RCS")) .TextStyle(&Theme.SubTitleFont) ] + SVerticalBox::Slot() .VAlign(VAlign_Top) [ SAssignNew(RCSBox, SVerticalBox) ] ] ] // Weapons + SHorizontalBox::Slot() .AutoWidth() [ SNew(SVerticalBox) + SVerticalBox::Slot() .AutoHeight() .Padding(Theme.TitlePadding) [ SNew(STextBlock) .Text(LOCTEXT("WeaponUpgradeTitle", "Weapons")) .TextStyle(&Theme.SubTitleFont) ] + SVerticalBox::Slot() .VAlign(VAlign_Top) [ SNew(SBox) .HeightOverride(900) [ SNew(SScrollBox) .Style(&Theme.ScrollBoxStyle) .ScrollBarStyle(&Theme.ScrollBarStyle) + SScrollBox::Slot() [ SAssignNew(WeaponBox, SHorizontalBox) ] ] ] ] ] ] ] ] ]; } /*---------------------------------------------------- Interaction ----------------------------------------------------*/ void SFlareSkirmishSetupMenu::Setup() { SetEnabled(false); SetVisibility(EVisibility::Collapsed); } void SFlareSkirmishSetupMenu::Enter() { FLOG("SFlareSkirmishSetupMenu::Enter"); SetEnabled(true); SetVisibility(EVisibility::Visible); FCHECK(PlayerSpacecraftListData.Num() == 0); FCHECK(EnemySpacecraftListData.Num() == 0); // Setup lists CompanySelector->RefreshOptions(); PlanetSelector->RefreshOptions(); CompanySelector->SetSelectedIndex(0); PlanetSelector->SetSelectedIndex(0); // Start doing the setup MenuManager->GetGame()->GetSkirmishManager()->StartSetup(); // Empty lists PlayerSpacecraftListData.Empty(); EnemySpacecraftListData.Empty(); PlayerSpacecraftList->RequestListRefresh(); EnemySpacecraftList->RequestListRefresh(); } void SFlareSkirmishSetupMenu::Exit() { SetEnabled(false); SetVisibility(EVisibility::Collapsed); UFlareGameUserSettings* MyGameSettings = Cast<UFlareGameUserSettings>(GEngine->GetGameUserSettings()); FCHECK(PlayerSpacecraftListData.Num() <= MyGameSettings->MaxShipsInSector); FCHECK(EnemySpacecraftListData.Num() <= MyGameSettings->MaxShipsInSector); // Empty lists WeaponBox->ClearChildren(); PlayerSpacecraftListData.Empty(); EnemySpacecraftListData.Empty(); PlayerSpacecraftList->RequestListRefresh(); EnemySpacecraftList->RequestListRefresh(); } /*---------------------------------------------------- Content callbacks ----------------------------------------------------*/ FText SFlareSkirmishSetupMenu::GetAltitudeValue() const { return FText::AsNumber(FMath::RoundToInt(100.0f * AltitudeSlider->GetValue())); } FText SFlareSkirmishSetupMenu::GetAsteroidValue() const { return FText::AsNumber(FMath::RoundToInt(MAX_ASTEROIDS * AsteroidSlider->GetValue())); } FText SFlareSkirmishSetupMenu::GetDebrisValue() const { return FText::AsNumber(FMath::RoundToInt(100.0f * DebrisSlider->GetValue())); } FText SFlareSkirmishSetupMenu::GetPlayerFleetTitle() const { UFlareSpacecraftComponentsCatalog* Catalog = MenuManager->GetGame()->GetShipPartsCatalog(); int32 CombatValue = 0; for (auto Order : PlayerSpacecraftListData) { CombatValue += Order->Description->CombatPoints; for (auto Weapon : Order->WeaponTypes) { CombatValue += Catalog->Get(Weapon)->CombatPoints; } } return FText::Format(LOCTEXT("PlayerFleetTitleFormat", "Player fleet ({0})"), CombatValue); } FText SFlareSkirmishSetupMenu::GetEnemyFleetTitle() const { UFlareSpacecraftComponentsCatalog* Catalog = MenuManager->GetGame()->GetShipPartsCatalog(); int32 CombatValue = 0; for (auto Order : EnemySpacecraftListData) { CombatValue += Order->Description->CombatPoints; for (auto Weapon : Order->WeaponTypes) { CombatValue += Catalog->Get(Weapon)->CombatPoints; } } return FText::Format(LOCTEXT("EnemyFleetTitleFormat", "Enemy fleet ({0})"), CombatValue); } TSharedRef<ITableRow> SFlareSkirmishSetupMenu::OnGenerateSpacecraftLine(TSharedPtr<FFlareSkirmishSpacecraftOrder> Item, const TSharedRef<STableViewBase>& OwnerTable) { const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); const FFlareSpacecraftDescription* Desc = Item->Description; // Structure return SNew(SFlareListItem, OwnerTable) .Width(16) .Height(2) .Content() [ SNew(SHorizontalBox) // Picture + SHorizontalBox::Slot() .AutoWidth() .Padding(Theme.ContentPadding) .VAlign(VAlign_Top) [ SNew(SImage) .Image(&Desc->MeshPreviewBrush) ] // Main infos + SHorizontalBox::Slot() .Padding(Theme.ContentPadding) [ SNew(SVerticalBox) + SVerticalBox::Slot() .AutoHeight() .Padding(Theme.SmallContentPadding) [ SNew(STextBlock) .Text(Desc->Name) .TextStyle(&Theme.NameFont) ] + SVerticalBox::Slot() .AutoHeight() .Padding(Theme.SmallContentPadding) [ SNew(SBox) .WidthOverride(Theme.ContentWidth) [ SNew(STextBlock) .Text(Desc->Description) .TextStyle(&Theme.TextFont) .WrapTextAt(0.7 * Theme.ContentWidth) ] ] ] // Action buttons + SHorizontalBox::Slot() .AutoWidth() .Padding(Theme.ContentPadding) [ SNew(SVerticalBox) + SVerticalBox::Slot() .AutoHeight() [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() [ SNew(SFlareButton) .Text(FText()) .HelpText(LOCTEXT("UpgradeSpacecraftInfo", "Upgrade this spacecraft")) .Icon(FFlareStyleSet::GetIcon("ShipUpgradeSmall")) .OnClicked(this, &SFlareSkirmishSetupMenu::OnUpgradeSpacecraft, Item) .Width(1) ] + SHorizontalBox::Slot() .AutoWidth() [ SNew(SFlareButton) .Text(FText()) .HelpText(LOCTEXT("RemoveSpacecraftInfo", "Remove this spacecraft")) .Icon(FFlareStyleSet::GetIcon("Delete")) .OnClicked(this, &SFlareSkirmishSetupMenu::OnRemoveSpacecraft, Item) .Width(1) ] ] + SVerticalBox::Slot() .AutoHeight() [ SNew(SFlareButton) .Text(LOCTEXT("DuplicateSpacecraft", "Copy")) .HelpText(LOCTEXT("DuplicateSpacecraftInfo", "Add a copy of this spacecraft and upgrades")) .OnClicked(this, &SFlareSkirmishSetupMenu::OnDuplicateSpacecraft, Item) .Width(2) ] ] ]; } TSharedRef<SWidget> SFlareSkirmishSetupMenu::OnGenerateCompanyComboLine(FFlareCompanyDescription Item) { const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); return SNew(SBox) .Padding(Theme.ListContentPadding) [ SNew(STextBlock) .Text(Item.Name) .TextStyle(&Theme.TextFont) ]; } FText SFlareSkirmishSetupMenu::OnGetCurrentCompanyComboLine() const { const FFlareCompanyDescription Item = CompanySelector->GetSelectedItem(); return Item.Name; } FText Capitalize(const FText& Text) { FString Lowercase = Text.ToString().ToLower(); FString FirstChar = Lowercase.Left(1).ToUpper(); FString Remainder = Lowercase.Right(Lowercase.Len() - 1); return FText::FromString(FirstChar + Remainder); } TSharedRef<SWidget> SFlareSkirmishSetupMenu::OnGeneratePlanetComboLine(FFlareSectorCelestialBodyDescription Item) { const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); return SNew(SBox) .Padding(Theme.ListContentPadding) [ SNew(STextBlock) .Text(Capitalize(Item.CelestialBodyName)) .TextStyle(&Theme.TextFont) ]; } FText SFlareSkirmishSetupMenu::OnGetCurrentPlanetComboLine() const { const FFlareSectorCelestialBodyDescription Item = PlanetSelector->GetSelectedItem(); return Capitalize(Item.CelestialBodyName); } bool SFlareSkirmishSetupMenu::IsStartDisabled() const { UFlareSkirmishManager* SkirmishManager = MenuManager->GetGame()->GetSkirmishManager(); FText Unused; if (!CanStartPlaying(Unused)) { return true; } return false; } FText SFlareSkirmishSetupMenu::GetAddToPlayerFleetText() const { UFlareGameUserSettings* MyGameSettings = Cast<UFlareGameUserSettings>(GEngine->GetGameUserSettings()); if (PlayerSpacecraftListData.Num() >= MyGameSettings->MaxShipsInSector) { return LOCTEXT("TooManyPlayerShips", "You can't add more ships than the limit defined in settings"); } else { return LOCTEXT("OKPlayerShips", "Add a new ship to the player fleet"); } } FText SFlareSkirmishSetupMenu::GetAddToEnemyFleetText() const { UFlareGameUserSettings* MyGameSettings = Cast<UFlareGameUserSettings>(GEngine->GetGameUserSettings()); if (EnemySpacecraftListData.Num() >= MyGameSettings->MaxShipsInSector) { return LOCTEXT("TooManyEnemyShips", "You can't add more ships than the limit defined in settings"); } else { return LOCTEXT("OKEnemyShips", "Add a new ship to the enemy fleet"); } } bool SFlareSkirmishSetupMenu::IsAddToPlayerFleetDisabled() const { UFlareGameUserSettings* MyGameSettings = Cast<UFlareGameUserSettings>(GEngine->GetGameUserSettings()); return (PlayerSpacecraftListData.Num() >= MyGameSettings->MaxShipsInSector); } bool SFlareSkirmishSetupMenu::IsAddToEnemyFleetDisabled() const { UFlareGameUserSettings* MyGameSettings = Cast<UFlareGameUserSettings>(GEngine->GetGameUserSettings()); return (EnemySpacecraftListData.Num() >= MyGameSettings->MaxShipsInSector); } FText SFlareSkirmishSetupMenu::GetStartHelpText() const { UFlareSkirmishManager* SkirmishManager = MenuManager->GetGame()->GetSkirmishManager(); FText Reason; if (!CanStartPlaying(Reason)) { return Reason; } return LOCTEXT("StartHelpText", "Start the skirmish now"); } /*---------------------------------------------------- Callbacks ----------------------------------------------------*/ void SFlareSkirmishSetupMenu::OnAsteroidSliderChanged(float Value, bool ForPlayer) { } void SFlareSkirmishSetupMenu::OnDebrisSliderChanged(float Value, bool ForPlayer) { } void SFlareSkirmishSetupMenu::OnClearFleet(bool ForPlayer) { if (ForPlayer) { PlayerSpacecraftListData.Empty(); PlayerSpacecraftList->RequestListRefresh(); } else { EnemySpacecraftListData.Empty(); EnemySpacecraftList->RequestListRefresh(); } } static bool SortByCombatValue(const TSharedPtr<FFlareSkirmishSpacecraftOrder>& Ship1, const TSharedPtr<FFlareSkirmishSpacecraftOrder>& Ship2) { FCHECK(Ship1->Description); FCHECK(Ship2->Description); if (Ship1->Description->CombatPoints > Ship2->Description->CombatPoints) { return true; } else { return false; } } void SFlareSkirmishSetupMenu::OnSortPlayerFleet() { PlayerSpacecraftListData.Sort(SortByCombatValue); PlayerSpacecraftList->RequestListRefresh(); } void SFlareSkirmishSetupMenu::OnAutoCreateEnemyFleet() { // Settings float NerfRatio = 0.9f; float ShipRatio = 0.9f; float DiversityRatio = 0.6f; // Data UFlareSpacecraftCatalog* SpacecraftCatalog = MenuManager->GetGame()->GetSpacecraftCatalog(); UFlareSpacecraftComponentsCatalog* PartsCatalog = MenuManager->GetGame()->GetShipPartsCatalog(); // Get player value int32 PlayerLargeShips = 0; int32 PlayerCombatValue = 0; for (auto Order : PlayerSpacecraftListData) { PlayerCombatValue += Order->Description->CombatPoints; for (auto Weapon : Order->WeaponTypes) { PlayerCombatValue += PartsCatalog->Get(Weapon)->CombatPoints; } if (Order->Description->Size == EFlarePartSize::L) { PlayerLargeShips++; } } // Define objectives bool IsHighValueFleet = (PlayerCombatValue > 25); int32 TargetCombatValue = IsHighValueFleet ? NerfRatio * PlayerCombatValue : PlayerCombatValue; int32 TargetShipCombatValue = IsHighValueFleet ? ShipRatio * TargetCombatValue : TargetCombatValue; int32 CurrentCombatValue = 0; // Add ships, starting with the most powerful EnemySpacecraftListData.Empty(); for (int32 Index = SpacecraftCatalog->ShipCatalog.Num() - 1; Index >= 0; Index--) { for (const UFlareSpacecraftCatalogEntry* Spacecraft : SpacecraftCatalog->ShipCatalog) { int32 RemainingCombatValue = TargetShipCombatValue - CurrentCombatValue; if (Spacecraft->Data.CombatPoints > 0 && Spacecraft->Data.CombatPoints < RemainingCombatValue) { // Define how much of this ship we want float RawShipCount = (DiversityRatio * RemainingCombatValue) / (float)Spacecraft->Data.CombatPoints; int32 ShipCount = IsHighValueFleet ? FMath::FloorToInt(RawShipCount) : FMath::CeilToInt(RawShipCount); // Order all copies for (int OrderIndex = 0; OrderIndex < ShipCount; OrderIndex++) { TSharedPtr<FFlareSkirmishSpacecraftOrder> Order = FFlareSkirmishSpacecraftOrder::New(&Spacecraft->Data); Order->ForPlayer = false; SetOrderDefaults(Order); EnemySpacecraftListData.Add(Order); CurrentCombatValue += Spacecraft->Data.CombatPoints; } } } // Value exceeded, break off if (CurrentCombatValue >= TargetShipCombatValue) { break; } } // Upgrade ships, starting with the least powerful for (int32 Index = EnemySpacecraftListData.Num() - 1; Index >= 0; Index--) { // Value exceeded, break off int32 RemainingCombatValue = TargetCombatValue - CurrentCombatValue; if (RemainingCombatValue <= 0) { break; } // Get data TSharedPtr<FFlareSkirmishSpacecraftOrder> Order = EnemySpacecraftListData[Index]; FFlareSpacecraftComponentDescription* BestAntiLargeWeapon = NULL; FFlareSpacecraftComponentDescription* BestAntiSmallWeapon = NULL; float BestAntiLarge = 0; float BestAntiSmall = 0; // Find best weapons against specific archetypes TArray<FFlareSpacecraftComponentDescription*> WeaponList; PartsCatalog->GetWeaponList(WeaponList, Order->Description->Size); for (FFlareSpacecraftComponentDescription* Weapon : WeaponList) { int32 UpgradeCombatValue = Order->WeaponTypes.Num() * Weapon->CombatPoints; if (UpgradeCombatValue > RemainingCombatValue) { continue; } // TODO : this algorithm always ends up using missiles if it upgrades at all, make it more diverse float AntiLarge = Weapon->WeaponCharacteristics.AntiLargeShipValue; if (AntiLarge > BestAntiLarge) { BestAntiLarge = AntiLarge; BestAntiLargeWeapon = Weapon; } float AntiSmall = Weapon->WeaponCharacteristics.AntiSmallShipValue; if (AntiSmall > BestAntiSmall) { BestAntiSmall = AntiSmall; BestAntiSmallWeapon = Weapon; } } // Assign one anti-L weapon to each L ship, else use anti small FFlareSpacecraftComponentDescription* UpgradeWeapon = NULL; if (PlayerLargeShips && BestAntiLargeWeapon) { UpgradeWeapon = BestAntiLargeWeapon; PlayerLargeShips--; } else if (BestAntiSmallWeapon) { UpgradeWeapon = BestAntiSmallWeapon; } // Upgrade if (UpgradeWeapon) { for (int32 WeaponIndex = 0; WeaponIndex < Order->WeaponTypes.Num(); WeaponIndex++) { Order->WeaponTypes[WeaponIndex] = UpgradeWeapon->Identifier; CurrentCombatValue += UpgradeWeapon->CombatPoints; } } } EnemySpacecraftList->RequestListRefresh(); } void SFlareSkirmishSetupMenu::OnOrderShip(bool ForPlayer) { IsOrderingForPlayer = ForPlayer; FFlareMenuParameterData Data; Data.OrderForPlayer = ForPlayer; Data.Skirmish = MenuManager->GetGame()->GetSkirmishManager(); MenuManager->OpenSpacecraftOrder(Data, FOrderDelegate::CreateSP(this, &SFlareSkirmishSetupMenu::OnOrderShipConfirmed)); } void SFlareSkirmishSetupMenu::OnOrderShipConfirmed(FFlareSpacecraftDescription* Spacecraft) { auto Order = FFlareSkirmishSpacecraftOrder::New(Spacecraft); Order->ForPlayer = IsOrderingForPlayer; SetOrderDefaults(Order); // Add ship if (IsOrderingForPlayer) { PlayerSpacecraftListData.AddUnique(Order); PlayerSpacecraftList->RequestListRefresh(); } else { EnemySpacecraftListData.AddUnique(Order); EnemySpacecraftList->RequestListRefresh(); } } void SFlareSkirmishSetupMenu::OnUpgradeSpacecraft(TSharedPtr<FFlareSkirmishSpacecraftOrder> Order) { const FFlareSpacecraftDescription* Desc = Order->Description; UFlareSpacecraftComponentsCatalog* Catalog = MenuManager->GetGame()->GetShipPartsCatalog(); TArray<FFlareSpacecraftComponentDescription*> PartList; const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); // Prepare data FText Text = LOCTEXT("PickComponentFormat", "{0}\n({1} value)"); FText HelpText = LOCTEXT("PickComponentHelp", "Upgrade with this component"); // Reset lists OrbitalEngineBox->ClearChildren(); RCSBox->ClearChildren(); WeaponBox->ClearChildren(); UpgradeBox->SetVisibility(EVisibility::Visible); // Engines Catalog->GetEngineList(PartList, Desc->Size); for (auto Engine : PartList) { FLinearColor Color = (Order->EngineType == Engine->Identifier) ? Theme.FriendlyColor : Theme.NeutralColor; OrbitalEngineBox->InsertSlot(0) .Padding(FMargin(0, 10)) [ SNew(SFlareRoundButton) .Icon(&Engine->MeshPreviewBrush) .Text(Engine->Name) .HelpText(HelpText) .InvertedBackground(true) .HighlightColor(Color) .OnClicked(this, &SFlareSkirmishSetupMenu::OnUpgradeEngine, Order, Engine->Identifier) ]; } // RCS PartList.Empty(); Catalog->GetRCSList(PartList, Desc->Size); for (auto RCS : PartList) { FLinearColor Color = (Order->RCSType == RCS->Identifier) ? Theme.FriendlyColor : Theme.NeutralColor; RCSBox->InsertSlot(0) .Padding(FMargin(0, 10)) [ SNew(SFlareRoundButton) .Icon(&RCS->MeshPreviewBrush) .Text(RCS->Name) .HelpText(HelpText) .InvertedBackground(true) .HighlightColor(Color) .OnClicked(this, &SFlareSkirmishSetupMenu::OnUpgradeRCS, Order, RCS->Identifier) ]; } // Weapons PartList.Empty(); Catalog->GetWeaponList(PartList, Desc->Size); for (int32 Index = 0; Index < Order->Description->WeaponGroups.Num(); Index++) { // Create vertical structure const FFlareSpacecraftSlotGroupDescription& Slot = Order->Description->WeaponGroups[Index]; TSharedPtr<SVerticalBox> WeaponSlot; WeaponBox->AddSlot() [ SNew(SBox) .WidthOverride(0.25 * Theme.ContentWidth) [ SAssignNew(WeaponSlot, SVerticalBox) ] ]; for (auto Weapon : PartList) { FText NameText = FText::Format(Text, Weapon->Name, FText::AsNumber(Weapon->CombatPoints)); FLinearColor Color = (Order->WeaponTypes[Index] == Weapon->Identifier) ? Theme.FriendlyColor : Theme.NeutralColor; WeaponSlot->AddSlot() .Padding(FMargin(0, 10)) [ SNew(SFlareRoundButton) .Icon(&Weapon->MeshPreviewBrush) .Text(NameText) .HelpText(HelpText) .InvertedBackground(true) .HighlightColor(Color) .OnClicked(this, &SFlareSkirmishSetupMenu::OnUpgradeWeapon, Order, Index, Weapon->Identifier) ]; } } SlatePrepass(FSlateApplicationBase::Get().GetApplicationScale()); } void SFlareSkirmishSetupMenu::OnRemoveSpacecraft(TSharedPtr<FFlareSkirmishSpacecraftOrder> Order) { if (Order->ForPlayer) { PlayerSpacecraftListData.Remove(Order); PlayerSpacecraftList->RequestListRefresh(); } else { EnemySpacecraftListData.Remove(Order); EnemySpacecraftList->RequestListRefresh(); } } void SFlareSkirmishSetupMenu::OnDuplicateSpacecraft(TSharedPtr<FFlareSkirmishSpacecraftOrder> Order) { // Copy order TSharedPtr<FFlareSkirmishSpacecraftOrder> NewOrder = FFlareSkirmishSpacecraftOrder::New(Order->Description); NewOrder->EngineType = Order->EngineType; NewOrder->RCSType = Order->RCSType; NewOrder->WeaponTypes = Order->WeaponTypes; NewOrder->ForPlayer = Order->ForPlayer; // Add order if (Order->ForPlayer) { PlayerSpacecraftListData.Add(NewOrder); PlayerSpacecraftList->RequestListRefresh(); } else { EnemySpacecraftListData.Add(NewOrder); EnemySpacecraftList->RequestListRefresh(); } } void SFlareSkirmishSetupMenu::OnUpgradeEngine(TSharedPtr<FFlareSkirmishSpacecraftOrder> Order, FName Upgrade) { Order->EngineType = Upgrade; OnUpgradeSpacecraft(Order); } void SFlareSkirmishSetupMenu::OnUpgradeRCS(TSharedPtr<FFlareSkirmishSpacecraftOrder> Order, FName Upgrade) { Order->RCSType = Upgrade; OnUpgradeSpacecraft(Order); } void SFlareSkirmishSetupMenu::OnUpgradeWeapon(TSharedPtr<FFlareSkirmishSpacecraftOrder> Order, int32 GroupIndex, FName Upgrade) { const FFlareSpacecraftDescription* Desc = Order->Description; for (int32 Index = 0; Index < Order->Description->WeaponGroups.Num(); Index++) { if (Index == GroupIndex) { Order->WeaponTypes[Index] = Upgrade; } } OnUpgradeSpacecraft(Order); } void SFlareSkirmishSetupMenu::OnCloseUpgradePanel() { UpgradeBox->SetVisibility(EVisibility::Collapsed); } void SFlareSkirmishSetupMenu::OnStartSkirmish() { UFlareSkirmishManager* Skirmish = MenuManager->GetGame()->GetSkirmishManager(); // Add ships for (auto Order : PlayerSpacecraftListData) { Skirmish->AddShip(true, *Order.Get()); } PlayerSpacecraftListData.Empty(); for (auto Order : EnemySpacecraftListData) { Skirmish->AddShip(false, *Order.Get()); } EnemySpacecraftListData.Empty(); // Set sector settings Skirmish->GetData().SectorAltitude = AltitudeSlider->GetValue(); Skirmish->GetData().AsteroidCount = MAX_ASTEROIDS * AsteroidSlider->GetValue(); Skirmish->GetData().MetallicDebris = MetalDebrisButton->IsActive(); Skirmish->GetData().SectorDescription.CelestialBodyIdentifier = PlanetSelector->GetSelectedItem().CelestialBodyIdentifier; Skirmish->GetData().SectorDescription.IsIcy = IcyButton->IsActive(); Skirmish->GetData().SectorDescription.DebrisFieldInfo.DebrisFieldDensity = MAX_DEBRIS_PERCENTAGE * DebrisSlider->GetValue(); // Override company color with current settings FFlareCompanyDescription& PlayerCompanyData = Skirmish->GetData().PlayerCompanyData; const FFlareCompanyDescription* CurrentCompanyData = MenuManager->GetPC()->GetCompanyDescription(); PlayerCompanyData.CustomizationBasePaintColor = CurrentCompanyData->CustomizationBasePaintColor; PlayerCompanyData.CustomizationPaintColor = CurrentCompanyData->CustomizationPaintColor; PlayerCompanyData.CustomizationOverlayColor = CurrentCompanyData->CustomizationOverlayColor; PlayerCompanyData.CustomizationLightColor = CurrentCompanyData->CustomizationLightColor; PlayerCompanyData.CustomizationPatternIndex = CurrentCompanyData->CustomizationPatternIndex; // Set enemy name Skirmish->GetData().EnemyCompanyName = CompanySelector->GetSelectedItem().ShortName; // Create the game Skirmish->StartPlay(); } void SFlareSkirmishSetupMenu::OnMainMenu() { MenuManager->GetGame()->GetSkirmishManager()->EndSkirmish(); MenuManager->OpenMenu(EFlareMenu::MENU_Main); } /*---------------------------------------------------- Helpers ----------------------------------------------------*/ bool SFlareSkirmishSetupMenu::CanStartPlaying(FText& Reason) const { Reason = FText(); if (PlayerSpacecraftListData.Num() == 0) { Reason = LOCTEXT("SkirmishCantStartNoPlayer", "You don't have enough ships to start playing"); return false; } else if (EnemySpacecraftListData.Num() == 0) { Reason = LOCTEXT("SkirmishCantStartNoEnemy", "Your enemy doesn't have enough ships to start playing"); return false; } return true; } void SFlareSkirmishSetupMenu::SetOrderDefaults(TSharedPtr<FFlareSkirmishSpacecraftOrder> Order) { if (Order->Description->Size == EFlarePartSize::S) { Order->EngineType = FName("engine-thresher"); Order->RCSType = FName("rcs-coral"); for (auto& Slot : Order->Description->WeaponGroups) { Order->WeaponTypes.Add(FName("weapon-eradicator")); } } else { Order->EngineType = FName("pod-thera"); Order->RCSType = FName("rcs-rift"); for (auto& Slot : Order->Description->WeaponGroups) { Order->WeaponTypes.Add(FName("weapon-artemis")); } } } #undef LOCTEXT_NAMESPACE
26.114474
165
0.665617
zhyinty
b00d9f9b676e091eefc6eb42a6c888adf5b4a752
574
cpp
C++
ReceiveSms/ReceiveSms.cpp
ozekisms/cpp-send-sms-http-rest-ozeki
b4c9b2f675fb324bad1b0a55ae6504a5ea4b4dc3
[ "MIT" ]
null
null
null
ReceiveSms/ReceiveSms.cpp
ozekisms/cpp-send-sms-http-rest-ozeki
b4c9b2f675fb324bad1b0a55ae6504a5ea4b4dc3
[ "MIT" ]
null
null
null
ReceiveSms/ReceiveSms.cpp
ozekisms/cpp-send-sms-http-rest-ozeki
b4c9b2f675fb324bad1b0a55ae6504a5ea4b4dc3
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include "Ozeki.Libs.Rest.h" using namespace std; int main() { //Function to create unique identifier for each messages srand((unsigned)time(0)); Configuration configuration; configuration.Username = "http_user"; configuration.Password = "qwe123"; configuration.ApiUrl = "http://127.0.0.1:9509/api"; MessageApi api(configuration); auto result = api.DownloadIncoming(); cout << result << endl; for (Message message : result.Messages) { cout << message << endl; } return 0; }
21.259259
60
0.660279
ozekisms
b00fbb2b5fdd0175dcfcb55263d3d40ca7e11b07
326
cpp
C++
cpp/4353.cpp
jinhan814/BOJ
47d2a89a2602144eb08459cabac04d036c758577
[ "MIT" ]
9
2021-01-15T13:36:39.000Z
2022-02-23T03:44:46.000Z
cpp/4353.cpp
jinhan814/BOJ
47d2a89a2602144eb08459cabac04d036c758577
[ "MIT" ]
1
2021-07-31T17:11:26.000Z
2021-08-02T01:01:03.000Z
cpp/4353.cpp
jinhan814/BOJ
47d2a89a2602144eb08459cabac04d036c758577
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define fastio cin.tie(0)->sync_with_stdio(0) using namespace std; #define double long double const double PI = acos(-1); int main() { fastio; cout << fixed << setprecision(3); for (double D, V; cin >> D >> V && D;) { const double val = D * D * D - V * 6 / PI; cout << cbrt(val) << '\n'; } }
21.733333
45
0.592025
jinhan814
b0134943ddeb234b4e3a57a75b3d09037c4e9db3
9,060
cpp
C++
src/items/value_item_map.cpp
kitsudaiki/libKitsunemimiSakuraParser
5cc3c2de7717b01b02912c9a2e0dc578877e963d
[ "Apache-2.0" ]
null
null
null
src/items/value_item_map.cpp
kitsudaiki/libKitsunemimiSakuraParser
5cc3c2de7717b01b02912c9a2e0dc578877e963d
[ "Apache-2.0" ]
54
2020-08-27T21:40:28.000Z
2021-12-30T20:56:13.000Z
src/items/value_item_map.cpp
kitsudaiki/libKitsunemimiSakuraParser
5cc3c2de7717b01b02912c9a2e0dc578877e963d
[ "Apache-2.0" ]
null
null
null
/** * @file value_item_map.h * * @author Tobias Anker <tobias.anker@kitsunemimi.moe> * * @copyright Apache License Version 2.0 * * Copyright 2019 Tobias Anker * * 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 <items/value_item_map.h> #include <libKitsunemimiCommon/common_items/table_item.h> #include <libKitsunemimiCommon/common_items/data_items.h> namespace Kitsunemimi { namespace Sakura { /** * @brief constructor */ ValueItemMap::ValueItemMap() {} /** * @brief destructor */ ValueItemMap::~ValueItemMap() { clearChildMap(); } /** * @brief copy-constructor */ ValueItemMap::ValueItemMap(const ValueItemMap &other) { // copy items std::map<std::string, ValueItem>::const_iterator it; for(it = other.m_valueMap.begin(); it != other.m_valueMap.end(); it++) { ValueItem value = it->second; m_valueMap.insert(std::make_pair(it->first, value)); } // copy child-maps std::map<std::string, ValueItemMap*>::const_iterator itChilds; for(itChilds = other.m_childMaps.begin(); itChilds != other.m_childMaps.end(); itChilds++) { ValueItemMap* newValue = new ValueItemMap(*itChilds->second); m_childMaps.insert(std::make_pair(itChilds->first, newValue)); } } /** * @brief assignmet-operator */ ValueItemMap& ValueItemMap::operator=(const ValueItemMap &other) { if(this != &other) { // delet old items this->m_valueMap.clear(); // copy items std::map<std::string, ValueItem>::const_iterator it; for(it = other.m_valueMap.begin(); it != other.m_valueMap.end(); it++) { ValueItem value = it->second; this->m_valueMap.insert(std::make_pair(it->first, value)); } clearChildMap(); // copy child-maps std::map<std::string, ValueItemMap*>::const_iterator itChilds; for(itChilds = other.m_childMaps.begin(); itChilds != other.m_childMaps.end(); itChilds++) { ValueItemMap* newValue = new ValueItemMap(*itChilds->second); this->m_childMaps.insert(std::make_pair(itChilds->first, newValue)); } } return *this; } /** * @brief add a new key-value-pair to the map * * @param key key of the new entry * @param value data-item of the new entry * @param force true, to override, if key already exist. * * @return true, if new pair was inserted, false, if already exist and force-flag was false */ bool ValueItemMap::insert(const std::string &key, DataItem* value, bool force) { ValueItem valueItem; valueItem.item = value->copy(); return insert(key, valueItem, force); } /** * @brief add a new key-value-pair to the map * * @param key key of the new entry * @param value value-item of the new entry * @param force true, to override, if key already exist. * * @return true, if new pair was inserted, false, if already exist and force-flag was false */ bool ValueItemMap::insert(const std::string &key, ValueItem &value, bool force) { std::map<std::string, ValueItem>::iterator it; it = m_valueMap.find(key); if(it != m_valueMap.end() && force == false) { return false; } if(it != m_valueMap.end()) { it->second = value; } else { m_valueMap.insert(std::make_pair(key, value)); } return true; } /** * @brief add a new key-value-pair to the map * * @param key key of the new entry * @param value new child-map * @param force true, to override, if key already exist. * * @return true, if new pair was inserted, false, if already exist and force-flag was false */ bool ValueItemMap::insert(const std::string &key, ValueItemMap* value, bool force) { std::map<std::string, ValueItemMap*>::iterator it; it = m_childMaps.find(key); if(it != m_childMaps.end() && force == false) { return false; } if(it != m_childMaps.end()) { it->second = value; } else { m_childMaps.insert(std::make_pair(key, value)); } return true; } /** * @brief check if the map contains a specific key * * @param key key to identify the entry * * @return true, if key exist inside the map, else false */ bool ValueItemMap::contains(const std::string &key) { std::map<std::string, ValueItem>::const_iterator it; it = m_valueMap.find(key); if(it != m_valueMap.end()) { return true; } std::map<std::string, ValueItemMap*>::const_iterator childIt; childIt = m_childMaps.find(key); if(childIt != m_childMaps.end()) { return true; } return false; } /** * @brief remove a value-item from the map * * @param key key to identify the entry * * @return true, if item was found and removed, else false */ bool ValueItemMap::remove(const std::string &key) { std::map<std::string, ValueItem>::const_iterator it; it = m_valueMap.find(key); if(it != m_valueMap.end()) { m_valueMap.erase(it); return true; } std::map<std::string, ValueItemMap*>::const_iterator childIt; childIt = m_childMaps.find(key); if(childIt != m_childMaps.end()) { m_childMaps.erase(childIt); return true; } return false; } /** * @brief get data-item inside a value-item of the map as string * * @param key key to identify the value * * @return item as string, if found, else empty string */ std::string ValueItemMap::getValueAsString(const std::string &key) { std::map<std::string, ValueItem>::const_iterator it; it = m_valueMap.find(key); if(it != m_valueMap.end()) { return it->second.item->toString(); } return ""; } /** * @brief get data-item inside a value-item of the map * * @param key key to identify the value * * @return pointer to the data-item, if found, else a nullptr */ DataItem* ValueItemMap::get(const std::string &key) { std::map<std::string, ValueItem>::const_iterator it; it = m_valueMap.find(key); if(it != m_valueMap.end()) { return it->second.item; } return nullptr; } /** * @brief get a value-item from the map * * @param key key to identify the value * * @return requested value-item, if found, else an empty uninitialized value-item */ ValueItem ValueItemMap::getValueItem(const std::string &key) { std::map<std::string, ValueItem>::const_iterator it; it = m_valueMap.find(key); if(it != m_valueMap.end()) { return it->second; } return ValueItem(); } /** * @brief size get number of object in the map * * @return number of object inside the map */ uint64_t ValueItemMap::size() { return m_valueMap.size(); } /** * @brief ValueItemMap::toString * * @return */ const std::string ValueItemMap::toString() { // init table output TableItem table; table.addColumn("key"); table.addColumn("value"); // fill table std::map<std::string, ValueItem>::const_iterator it; for(it = m_valueMap.begin(); it != m_valueMap.end(); it++) { table.addRow(std::vector<std::string>{it->first, it->second.item->toString()}); } return table.toString(); } /** * @brief ValueItemMap::getValidationMap * @param validationMap */ void ValueItemMap::getValidationMap(std::map<std::string, FieldDef> &validationMap) const { std::map<std::string, ValueItem>::const_iterator it; for(it = m_valueMap.begin(); it != m_valueMap.end(); it++) { ValueItem value = it->second; FieldDef::IO_ValueType ioType = FieldDef::INPUT_TYPE; if(value.type == ValueItem::OUTPUT_PAIR_TYPE) { ioType = FieldDef::OUTPUT_TYPE; } const bool isReq = value.item->getString() == "?"; validationMap.emplace(it->first, FieldDef(ioType, value.fieldType, isReq, value.comment)); } } /** * @brief ValueItemMap::clearChildMap */ void ValueItemMap::clearChildMap() { // clear old child map std::map<std::string, ValueItemMap*>::const_iterator itChilds; for(itChilds = m_childMaps.begin(); itChilds != m_childMaps.end(); itChilds++) { ValueItemMap* oldMap = itChilds->second; delete oldMap; } m_childMaps.clear(); } } // namespace Sakura } // namespace Kitsunemimi
23.410853
98
0.620751
kitsudaiki
b013c68f4340f9acf3d51682dbb95f6f987b293a
1,502
cpp
C++
mdaio/usagetracking.cpp
magland/ap2d
26aba9a6c90c19decdc4a2c729062c7de746439f
[ "MIT" ]
null
null
null
mdaio/usagetracking.cpp
magland/ap2d
26aba9a6c90c19decdc4a2c729062c7de746439f
[ "MIT" ]
null
null
null
mdaio/usagetracking.cpp
magland/ap2d
26aba9a6c90c19decdc4a2c729062c7de746439f
[ "MIT" ]
null
null
null
#include "usagetracking.h" #include <QDebug> static int num_files_open=0; static int64_t num_bytes_allocated=0; static int malloc_count=0; static int num_bytes_read=0; static int num_bytes_written=0; FILE *jfopen(const char *path,const char *mode) { //printf("jfopen.\n"); FILE *F=fopen(path,mode); if (!F) return 0; num_files_open++; return F; } void jfclose(FILE *F) { //printf("jfclose.\n"); if (!F) return; fclose(F); num_files_open--; } int jfread(void *data,size_t sz,int num,FILE *F) { int ret=fread(data,sz,num,F); num_bytes_read+=ret; return ret; } int jfwrite(void *data,size_t sz,int num,FILE *F) { int ret=fwrite(data,sz,num,F); num_bytes_written+=ret; return ret; } int jnumfilesopen() { return num_files_open; } void *jmalloc(size_t num_bytes) { //printf("jmalloc %d.\n",(int)num_bytes); if (!num_bytes) return 0; void *ret=malloc(num_bytes+8); //add some space to track the number of bytes int32_t *tmp=(int32_t *)ret; tmp[0]=num_bytes; num_bytes_allocated+=num_bytes; malloc_count++; return (void *)(((unsigned char *)ret)+8); } void jfree(void *ptr) { //printf("jfree.\n"); if (!ptr) return; int64_t *tmp=(int64_t *)((unsigned char *)ptr-8); int64_t num_bytes=tmp[0]; free((void *)tmp); num_bytes_allocated-=num_bytes; malloc_count--; } int jmalloccount() { return malloc_count; } int64_t jbytesallocated() { return num_bytes_allocated; } int jnumbytesread() { return num_bytes_read; } int jnumbyteswritten() { return num_bytes_written; }
19.763158
77
0.704394
magland