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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
58afa5107ee38f491750a776226f9ccdf8dfb61d | 200 | cpp | C++ | Luogu/P1425.cpp | Rose2073/RoseCppSource | bdaf5de04049b07bbe0e1ef976d1fbe72520fa03 | [
"Apache-2.0"
] | 1 | 2021-04-05T16:26:00.000Z | 2021-04-05T16:26:00.000Z | Luogu/P1425.cpp | Rose2073/RoseCppSource | bdaf5de04049b07bbe0e1ef976d1fbe72520fa03 | [
"Apache-2.0"
] | null | null | null | Luogu/P1425.cpp | Rose2073/RoseCppSource | bdaf5de04049b07bbe0e1ef976d1fbe72520fa03 | [
"Apache-2.0"
] | null | null | null | #include<cstdio>
int main(){
int h1,m1,h2,m2;
scanf("%d %d %d %d",&h1,&m1,&h2,&m2);
int h3,m3;
m3 = m2 - m1;
if(m3 < 0){
h2--;
m3 += 60;
}
h3 = h2- h1;
printf("%d %d",h3,m3);
return 0;
}
| 13.333333 | 38 | 0.485 | Rose2073 |
58afa75cfb284311ac751d82a05cf59537ddbac7 | 26 | cpp | C++ | lang/Array2D.cpp | gizmomogwai/cpplib | a09bf4d3f2a312774d3d85a5c65468099a1797b0 | [
"MIT"
] | null | null | null | lang/Array2D.cpp | gizmomogwai/cpplib | a09bf4d3f2a312774d3d85a5c65468099a1797b0 | [
"MIT"
] | null | null | null | lang/Array2D.cpp | gizmomogwai/cpplib | a09bf4d3f2a312774d3d85a5c65468099a1797b0 | [
"MIT"
] | null | null | null | #include <lang/Array2D.h>
| 13 | 25 | 0.730769 | gizmomogwai |
58b065df3705499534e6437de4e626a7bab2cd13 | 5,231 | cpp | C++ | c++/extract_phone.cpp | isopleth/kinetics | b2954fecbe6b571fed53034cc88dc68e6455703a | [
"BSD-2-Clause"
] | null | null | null | c++/extract_phone.cpp | isopleth/kinetics | b2954fecbe6b571fed53034cc88dc68e6455703a | [
"BSD-2-Clause"
] | null | null | null | c++/extract_phone.cpp | isopleth/kinetics | b2954fecbe6b571fed53034cc88dc68e6455703a | [
"BSD-2-Clause"
] | null | null | null | // BSD 2-Clause License
//
// Copyright (c) 2019, Jason Leake
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Convert data collected by the phone to similar data format used by
// AX3 CSV output.
//
// The AX3 format accelerometer data lines of the form:
// 2020-10-22 18:00:04.780,-1.043625,0.020250,-0.020250
// and we use this format for phone gyro and accelerometer data
//
/**
* Jason Leake October 2019
*/
#include "PhoneDataConverter.h"
#include "util.h"
#include <cmath>
#include <filesystem>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <signal.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
using namespace std;
static constexpr auto programName = "extract_phone";
auto usage() {
util::justify(cerr, programName,
"This program extract particular field types from"
" phone data files.");
cerr << "Usage: " << programName << " [-s] <infile> <outfile> <type>" << endl;
cerr << "-l, --lazy does not generate files if they already exist" << endl;
cerr << "-s, --short stops processing after 100 lines have been output, for testing" << endl;
}
/**
* Entry point
*/
auto main(int argc, char** argv) -> int {
if (argc < 4) {
usage();
return EXIT_FAILURE;
}
auto typeString = string{};
auto inputFilename = string{};
auto outputFilename = string{};
auto force = true;
auto shortRun = false;
auto index = 1;
while (index < argc) {
if (argv[index][0] == '-') {
auto option = string{argv[index]};
if (option == "-l" || option == "--lazy") {
force = false;
}
else if (option == "-s" || option == "--short") {
shortRun = true;
cout << "Short run, terminating program when 100 lines written (-s present)" << endl;
}
else {
cerr << "Unrecognised option: " << argv[index] << endl;
usage();
return EXIT_FAILURE;
}
}
else if (inputFilename.empty()) {
inputFilename = argv[index];
}
else if (outputFilename.empty()) {
outputFilename = argv[index];
}
else if (typeString.empty()) {
typeString = argv[index];
cout << typeString << endl;
}
else {
cerr << "Extra parameter provided" << endl;
return EXIT_FAILURE;
}
index++;
}
if (force || !util::exists(outputFilename)) {
// Create output directories if they do not exist
auto outpath = filesystem::path{outputFilename};
if (!outpath.parent_path().empty() &&
!filesystem::exists(outpath.parent_path())) {
cout << "Creating output directory " << outpath.parent_path() << endl;
filesystem::create_directories(outpath.parent_path());
}
auto outfile = ofstream{outputFilename};
if (!outfile.is_open()) {
cerr << "Unable to open output file " << outputFilename << endl;
return EXIT_FAILURE;
}
// Check output directory exists
if (!util::exists(inputFilename)) {
return EXIT_FAILURE;
}
auto input = ifstream{inputFilename};
auto line = string{};
// Read the file and copy the records
auto inCount = 0;
auto outCount = 0;
// Accelerations have the phone's m/s^2 converted to g to match the
// way that we configure the AX3 configured. Could put in an
// auto-sense
auto converter = PhoneDataConverter(typeString);
while (getline(input, line)) {
if (converter.match(line)) {
auto newLine = converter.convert(line, inCount);
if (newLine.size() > 0) {
outfile << newLine << "\n";
outCount++;
}
}
if (inCount % 100000 == 0) {
cout << inCount << " lines processed.\r";
cout.flush();
}
inCount++;
if (shortRun) {
if (outCount >= 100) {
break;
}
}
}
cout << "\n" << inCount << " lines scanned, " << outCount << " written\n\n";
input.close();
outfile.close();
}
else {
cout << outputFilename << " exists, so skipping it" << endl;
}
util::exitSuccess(programName);
}
| 28.900552 | 95 | 0.652074 | isopleth |
58b1747958284c0ece6133fb6f452e5db3a30652 | 750 | cpp | C++ | sydney-2017-03-29/motivation1c.cpp | cjdb/cpp-conferences | bafe69cf11ca38451367553460e956cb52df3dd2 | [
"Apache-2.0"
] | 3 | 2017-09-15T00:10:25.000Z | 2018-09-22T12:50:18.000Z | sydney-2017-03-29/motivation1c.cpp | cjdb/cppcon | bafe69cf11ca38451367553460e956cb52df3dd2 | [
"Apache-2.0"
] | 1 | 2017-12-04T22:12:16.000Z | 2017-12-04T22:12:16.000Z | sydney-2017-03-29/motivation1c.cpp | cjdb/cppcon | bafe69cf11ca38451367553460e956cb52df3dd2 | [
"Apache-2.0"
] | 1 | 2017-12-04T10:50:54.000Z | 2017-12-04T10:50:54.000Z | #include <algorithm>
#include <iterator>
#include <iostream>
#include <type_traits>
#include <vector>
template <typename InputIterator, std::enable_if_t<
std::is_same<typename InputIterator::iterator_tag_t,
typename InputIterator::iterator_tag_t>::value,
int> = 0>
std::vector<double> make_vector(InputIterator first, InputIterator last)
{
auto v = std::vector<double>{};
while (first != last)
v.push_back(*first++);
return v;
}
std::vector<double> make_vector(std::size_t size, double magnitude)
{
return std::vector<double>(size, magnitude);
}
int main()
{
auto v = make_vector(10, 1);
copy(v.begin(), v.end(), std::ostream_iterator<decltype(v)::value_type>{std::cout, " "});
std::cout << '\n';
}
| 25 | 92 | 0.676 | cjdb |
58b1c412f971463564e3254bbb42efd0dd5684a5 | 1,491 | hh | C++ | Config.hh | cndolo/smart_pointers | 3586e06e609ddbea6faf3208e09ad40d7f554183 | [
"MIT"
] | null | null | null | Config.hh | cndolo/smart_pointers | 3586e06e609ddbea6faf3208e09ad40d7f554183 | [
"MIT"
] | null | null | null | Config.hh | cndolo/smart_pointers | 3586e06e609ddbea6faf3208e09ad40d7f554183 | [
"MIT"
] | null | null | null | #pragma once
#include <cstddef>
#include <cstdint>
struct ImageConfig{
static uint64_t PHYS_BASE;
static size_t SIZE;
static uint64_t VIRT_BASE;
static uint64_t KERN_END;
static uint64_t physBase() { return ImageConfig::PHYS_BASE; }
static size_t size() { return ImageConfig::SIZE; }
static uint64_t virtBase() { return ImageConfig::VIRT_BASE; }
static void setPhysBase(uint64_t phys) { ImageConfig::PHYS_BASE = phys; }
static void setSize(size_t size) { ImageConfig::SIZE = size; }
static void setVirtBase(uint64_t virt) { ImageConfig::VIRT_BASE = virt; }
};
struct MMIOConfig{
static uint64_t PHYS_BASE;
static size_t SIZE;
static uint64_t VIRT_BASE;
static uint64_t physBase() { return MMIOConfig::PHYS_BASE; }
static size_t size() { return MMIOConfig::SIZE; }
static uint64_t virtBase() { return MMIOConfig::VIRT_BASE; }
static void setPhysBase(uint64_t phys) { PHYS_BASE = phys; }
static void setSize(size_t size) { SIZE = size; }
static void setVirtBase(uint64_t virt) { VIRT_BASE = virt; }
};
struct KernelConfig{
static uint64_t PHYS_BASE;
static size_t SIZE;
static uint64_t VIRT_BASE;
static uint64_t physBase() { return KernelConfig::PHYS_BASE; }
static size_t size() { return KernelConfig::SIZE; }
static uint64_t virtBase() { return KernelConfig::VIRT_BASE; }
static void setPhysBase(uint64_t phys) { PHYS_BASE = phys; }
static void setSize(size_t size) { SIZE = size; }
static void setVirtBase(uint64_t virt) { VIRT_BASE = virt ;}
};
| 31.723404 | 74 | 0.744467 | cndolo |
58b5a1499ead2cc7ce06ce342361ef373820b9dc | 494 | cpp | C++ | nowcoder/80C.cpp | swwind/code | 25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0 | [
"WTFPL"
] | 3 | 2017-09-17T09:12:50.000Z | 2018-04-06T01:18:17.000Z | nowcoder/80C.cpp | swwind/code | 25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0 | [
"WTFPL"
] | null | null | null | nowcoder/80C.cpp | swwind/code | 25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0 | [
"WTFPL"
] | null | null | null | #include <bits/stdc++.h>
#define N 100020
#define mod 998244353
#define ll long long
using namespace std;
inline int read(){
int x=0,f=1;char ch=getchar();
while(ch>'9'||ch<'0')ch=='-'&&(f=0)||(ch=getchar());
while(ch<='9'&&ch>='0')x=(x<<3)+(x<<1)+ch-'0',ch=getchar();
return f?x:-x;
}
int main(int argc, char const *argv[]) {
int p = read();
ll res = 1;
for (int i = 1; i <= p; i++)
res = res * i % mod;
res = res * res % mod * 2 % mod;
cout << res << endl;
return 0;
} | 24.7 | 61 | 0.546559 | swwind |
58b5da290227a4419b775b445b190b4e906c0a5e | 2,267 | cpp | C++ | main.cpp | MattLigocki/DNNAssist | 97801013ac948c6fdd84fa622888c519eed3bc85 | [
"MIT"
] | null | null | null | main.cpp | MattLigocki/DNNAssist | 97801013ac948c6fdd84fa622888c519eed3bc85 | [
"MIT"
] | null | null | null | main.cpp | MattLigocki/DNNAssist | 97801013ac948c6fdd84fa622888c519eed3bc85 | [
"MIT"
] | null | null | null | #include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickStyle>
#include <QQmlContext>
#include <QQuickWindow>
#include <memory>
#include <QTimer>
#include "models/modelObjects/Classifier.h"
#include "computerVision/QCvDetectFilter.h"
#include "controllers/DataSetsScreenController.h"
#include "controllers/MediaScreenController.h"
#include "managers/ComputerVisionManager/AiManager.h"
#include "managers/HttpManager/HttpManager.h"
#include "utils/FileSystemHandler.h"
#include "utils/Common.h"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
app.setApplicationName("DNNAssist");
QQuickStyle::setStyle("Material");
//Register QML types
qmlRegisterType<QCvDetectFilter>("com.dnnassist.classes", 1, 0, "CvDetectFilter");
qmlRegisterType<ObjectListModel>("com.dnnassist.classes", 1, 0, "ObjectListModel");
qmlRegisterType<FileSystemHandler>("com.dnnassist.classes", 1, 0, "FileSystemHandler");
QQmlApplicationEngine engine;
//Register managers
engine.rootContext()->setContextProperty("aiManager", &AiManager::getInstance());
//Register controllers
engine.rootContext()->setContextProperty("dataSetsScreenController", &DataSetsScreenController::getInstance());
engine.rootContext()->setContextProperty("mediaScreenController", &MediaScreenController::getInstance());
//Register processed video output
engine.rootContext()->engine()->addImageProvider(QLatin1String("NwImageProvider"), MediaScreenController::getInstance().getImageProvider());
engine.rootContext()->setContextProperty("NwImageProvider", MediaScreenController::getInstance().getImageProvider());
engine.rootContext()->setContextProperty("httpManager", new HttpManager());
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
if (engine.rootObjects().isEmpty()) {
qDebug("Empty rootObjects");
return -1;
}
return app.exec();
}
| 34.876923 | 144 | 0.731804 | MattLigocki |
58b973b832611e5b257ea3d7531bc83bff23fe63 | 7,071 | cpp | C++ | src_pybind/core/py_ls.cpp | stnoh/pydelfem2 | 40224736dda9576a39d2b5a753a1ca1e4f906299 | [
"MIT"
] | 8 | 2020-11-23T01:51:20.000Z | 2022-01-28T04:28:18.000Z | src_pybind/core/py_ls.cpp | stnoh/pydelfem2 | 40224736dda9576a39d2b5a753a1ca1e4f906299 | [
"MIT"
] | null | null | null | src_pybind/core/py_ls.cpp | stnoh/pydelfem2 | 40224736dda9576a39d2b5a753a1ca1e4f906299 | [
"MIT"
] | 2 | 2021-07-13T06:30:37.000Z | 2021-10-19T00:44:49.000Z | /*
* Copyright (c) 2019 Nobuyuki Umetani
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include "../py_funcs.h"
#include "delfem2/lsmats.h"
#include "delfem2/lsitrsol.h"
#include "delfem2/lsvecx.h"
#include "delfem2/vecxitrsol.h"
#include "delfem2/lsilu_mats.h"
#include "delfem2/mshuni.h"
#include "delfem2/mshmisc.h"
namespace py = pybind11;
namespace dfm2 = delfem2;
// ----------------------------
void MatrixSquareSparse_SetPattern(
dfm2::CMatrixSparse<double>& mss,
const py::array_t<unsigned int>& psup_ind,
const py::array_t<unsigned int>& psup)
{
assert( mss.nrowblk == mss.ncolblk );
assert( mss.nrowdim == mss.ncoldim );
assert( psup_ind.ndim() == 1 );
assert( psup.ndim() == 1 );
assert( psup_ind.shape()[0] == mss.nrowblk+1 );
mss.SetPattern(psup_ind.data(), psup_ind.shape()[0],
psup.data(), psup.shape()[0]);
}
void MatrixSquareSparse_SetFixBC(
dfm2::CMatrixSparse<double>& mss,
const py::array_t<int>& flagbc)
{
assert( mss.nrowblk == mss.ncolblk );
assert( mss.nrowdim == mss.ncoldim );
assert( flagbc.ndim() == 2 );
assert( flagbc.shape()[0] == mss.nrowblk );
assert( flagbc.shape()[1] == mss.nrowdim );
mss.SetFixedBC(flagbc.data());
}
void PyMatSparse_ScaleBlk_LeftRight(
dfm2::CMatrixSparse<double>& mss,
const py::array_t<double>& scale)
{
assert( mss.nrowblk == mss.ncolblk );
assert( mss.nrowdim == mss.ncoldim );
assert( scale.ndim() == 1 );
assert( scale.shape()[0] == mss.nrowblk );
MatSparse_ScaleBlk_LeftRight(
mss,
scale.data());
}
void PyMatSparse_ScaleBlkLen_LeftRight(
dfm2::CMatrixSparse<double>& mss,
const py::array_t<double>& scale)
{
assert( mss.nrowblk == mss.ncolblk );
assert( mss.nrowdim == mss.ncoldim );
assert( scale.ndim() == 2 );
assert( scale.shape()[0] == mss.nrowblk );
assert( scale.shape()[1] == mss.nrowdim );
MatSparse_ScaleBlkLen_LeftRight(mss,
scale.data());
}
void PyMatrixSparse_ScaleBlkLen_LeftRight(
dfm2::CMatrixSparse<double>& mss,
const py::array_t<double>& scale,
bool is_sumndimval)
{
assert( mss.nrowblk == mss.ncolblk );
assert( mss.nrowdim == mss.ncoldim );
assert( scale.ndim() == 2 );
assert( scale.shape()[0] == mss.nrowblk );
assert( scale.shape()[1] == mss.nrowdim );
MatSparse_ScaleBlkLen_LeftRight(mss,
scale.data());
}
void LinearSystem_SetMasterSlave(
dfm2::CMatrixSparse<double>& mss,
py::array_t<double>& np_b,
const py::array_t<unsigned int>& np_ms)
{
assert( mss.nrowblk == mss.ncolblk );
assert( mss.nrowdim == mss.ncoldim );
assert( dfm2::CheckNumpyArray2D(np_b, mss.nrowblk, mss.nrowdim) );
assert( dfm2::CheckNumpyArray2D(np_ms, np_b.shape()[0], np_b.shape()[1]) );
SetMasterSlave(
mss,
np_ms.data());
dfm2::setRHS_MasterSlave(np_b.mutable_data(),
np_b.shape()[0]*np_b.shape()[1], np_ms.data());
}
std::vector<double> PySolve_PCG(
py::array_t<double>& vec_b,
py::array_t<double>& vec_x,
double conv_ratio, unsigned int iteration,
const dfm2::CMatrixSparse<double>& mat_A,
const dfm2::CPreconditionerILU<double>& ilu_A)
{
// std::cout << "solve pcg" << std::endl;
assert( vec_x.size() == vec_b.size() );
assert( vec_x.size() == mat_A.nrowblk*mat_A.nrowdim );
const unsigned int N = vec_b.size();
auto buff_vecb = vec_b.request();
auto buff_vecx = vec_x.request();
std::vector<double> tmp0(N);
std::vector<double> tmp1(N);
return dfm2::Solve_PCG(
dfm2::CVecXd((double*)buff_vecb.ptr,N),
dfm2::CVecXd((double*)buff_vecx.ptr,N),
dfm2::CVecXd(tmp0.data(),N),
dfm2::CVecXd(tmp1.data(),N),
conv_ratio,iteration,
mat_A,ilu_A);
}
std::vector<double> PySolve_PBiCGStab(
py::array_t<double>& vec_b,
py::array_t<double>& vec_x,
double conv_ratio, unsigned int iteration,
const dfm2::CMatrixSparse<double>& mat_A,
const dfm2::CPreconditionerILU<double>& ilu_A)
{
// std::cout << "solve pcg" << std::endl;
auto buff_vecb = vec_b.request();
auto buff_vecx = vec_x.request();
return Solve_PBiCGStab((double*)buff_vecb.ptr,
(double*)buff_vecx.ptr,
conv_ratio,iteration,
mat_A,ilu_A);
}
void PyPrecILU_SetPattern_ILUk(
dfm2::CPreconditionerILU<double>& mat_ilu,
const dfm2::CMatrixSparse<double>& mss,
int nlev_fill)
{
// mat_ilu.Initialize_ILU0(mss);
mat_ilu.Initialize_ILUk(mss,
nlev_fill);
}
std::tuple<py::array_t<unsigned int>,py::array_t<unsigned int>>
PyAddMasterSlavePattern(
const py::array_t<unsigned int>& ms_flag,
const py::array_t<unsigned int>& np_psup_ind0,
const py::array_t<unsigned int>& np_psup0)
{
assert(ms_flag.shape()[0] == np_psup_ind0.shape()[0]-1);
assert(ms_flag.ndim() == 2 );
std::vector<unsigned int> psup_ind, psup;
dfm2::JArray_AddMasterSlavePattern(
psup_ind, psup,
ms_flag.data(), ms_flag.shape()[1],
np_psup_ind0.data(), np_psup_ind0.shape()[0], np_psup0.data());
py::array_t<unsigned int> np_psup_ind((int)psup_ind.size(),psup_ind.data());
py::array_t<unsigned int> np_psup((int)psup.size(),psup.data());
return std::make_tuple(np_psup_ind,np_psup);
}
void PyMasterSlave_DistributeValue(
py::array_t<double>& val,
const py::array_t<int>& ms_flag)
{
double* pVal = (double*)(val.request().ptr);
const int nDoF = ms_flag.size();
for(int idof=0;idof<nDoF;++idof){
int jdof = ms_flag.data()[idof];
if( jdof == -1 ) continue;
assert( jdof >= 0 && jdof < nDoF );
pVal[ idof] = pVal[ jdof];
}
}
void init_ls(py::module &m){
py::class_<dfm2::CMatrixSparse<double>>(m,"CppMatrixSparse")
.def(py::init<>())
.def("initialize", &dfm2::CMatrixSparse<double>::Initialize)
.def("set_zero", &dfm2::CMatrixSparse<double>::setZero)
.def("add_dia", &dfm2::CMatrixSparse<double>::AddDia);
m.def("matrixSquareSparse_setPattern", &MatrixSquareSparse_SetPattern);
m.def("matrixSquareSparse_setFixBC", &MatrixSquareSparse_SetFixBC);
m.def("cppMatSparse_ScaleBlk_LeftRight", &PyMatSparse_ScaleBlk_LeftRight);
m.def("cppMatSparse_ScaleBlkLen_LeftRight", &PyMatSparse_ScaleBlkLen_LeftRight);
m.def("masterSlave_distributeValue", &PyMasterSlave_DistributeValue);
m.def("cppAddMasterSlavePattern", &PyAddMasterSlavePattern);
py::class_<dfm2::CPreconditionerILU<double>>(m,"PreconditionerILU")
.def(py::init<>())
.def("ilu_decomp", &dfm2::CPreconditionerILU<double>::DoILUDecomp)
.def("set_value", &dfm2::CPreconditionerILU<double>::SetValueILU);
m.def("cppPrecILU_SetPattern_ILUk", &PyPrecILU_SetPattern_ILUk);
m.def("linearSystem_setMasterSlave", &LinearSystem_SetMasterSlave);
m.def("linsys_solve_pcg", &PySolve_PCG);
m.def("linsys_solve_bicgstab", &PySolve_PBiCGStab);
}
| 32.43578 | 82 | 0.662848 | stnoh |
58badef2512e161d9056729ea2914b56fb6f230f | 6,757 | cc | C++ | content/browser/media/media_devices_util.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | content/browser/media/media_devices_util.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | content/browser/media/media_devices_util.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/media/media_devices_util.h"
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/command_line.h"
#include "base/strings/string_split.h"
#include "base/strings/string_tokenizer.h"
#include "content/browser/frame_host/render_frame_host_delegate.h"
#include "content/browser/frame_host/render_frame_host_impl.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/media_device_id.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/media_stream_request.h"
#include "media/base/media_switches.h"
namespace content {
namespace {
std::string GetDefaultMediaDeviceIDOnUIThread(MediaDeviceType device_type,
int render_process_id,
int render_frame_id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
RenderFrameHostImpl* frame_host =
RenderFrameHostImpl::FromID(render_process_id, render_frame_id);
if (!frame_host)
return std::string();
RenderFrameHostDelegate* delegate = frame_host->delegate();
if (!delegate)
return std::string();
MediaStreamType media_stream_type;
switch (device_type) {
case MEDIA_DEVICE_TYPE_AUDIO_INPUT:
media_stream_type = MEDIA_DEVICE_AUDIO_CAPTURE;
break;
case MEDIA_DEVICE_TYPE_VIDEO_INPUT:
media_stream_type = MEDIA_DEVICE_VIDEO_CAPTURE;
break;
default:
return std::string();
}
return delegate->GetDefaultMediaDeviceID(media_stream_type);
}
// This function is intended for testing purposes. It returns an empty string
// if no default device is supplied via the command line.
std::string GetDefaultMediaDeviceIDFromCommandLine(
MediaDeviceType device_type) {
DCHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kUseFakeDeviceForMediaStream));
const std::string option =
base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kUseFakeDeviceForMediaStream);
// Optional comma delimited parameters to the command line can specify values
// for the default device IDs.
// Examples: "video-input-default-id=mycam, audio-input-default-id=mymic"
base::StringTokenizer option_tokenizer(option, ", ");
option_tokenizer.set_quote_chars("\"");
while (option_tokenizer.GetNext()) {
std::vector<std::string> param =
base::SplitString(option_tokenizer.token(), "=", base::TRIM_WHITESPACE,
base::SPLIT_WANT_NONEMPTY);
if (param.size() != 2u) {
DLOG(WARNING) << "Forgot a value '" << option << "'? Use name=value for "
<< switches::kUseFakeDeviceForMediaStream << ".";
return std::string();
}
if (device_type == MEDIA_DEVICE_TYPE_AUDIO_INPUT &&
param.front() == "audio-input-default-id") {
return param.back();
} else if (device_type == MEDIA_DEVICE_TYPE_VIDEO_INPUT &&
param.front() == "video-input-default-id") {
return param.back();
}
}
return std::string();
}
} // namespace
MediaDeviceSaltAndOrigin::MediaDeviceSaltAndOrigin() = default;
MediaDeviceSaltAndOrigin::MediaDeviceSaltAndOrigin(std::string device_id_salt,
std::string group_id_salt,
url::Origin origin)
: device_id_salt(std::move(device_id_salt)),
group_id_salt(std::move(group_id_salt)),
origin(std::move(origin)) {}
void GetDefaultMediaDeviceID(
MediaDeviceType device_type,
int render_process_id,
int render_frame_id,
const base::Callback<void(const std::string&)>& callback) {
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kUseFakeDeviceForMediaStream)) {
std::string command_line_default_device_id =
GetDefaultMediaDeviceIDFromCommandLine(device_type);
if (!command_line_default_device_id.empty()) {
callback.Run(command_line_default_device_id);
return;
}
}
BrowserThread::PostTaskAndReplyWithResult(
BrowserThread::UI, FROM_HERE,
base::Bind(&GetDefaultMediaDeviceIDOnUIThread, device_type,
render_process_id, render_frame_id),
callback);
}
MediaDeviceSaltAndOrigin GetMediaDeviceSaltAndOrigin(int render_process_id,
int render_frame_id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
RenderFrameHost* frame_host =
RenderFrameHost::FromID(render_process_id, render_frame_id);
RenderProcessHost* process_host =
RenderProcessHost::FromID(render_process_id);
WebContentsImpl* web_contents = static_cast<WebContentsImpl*>(
WebContents::FromRenderFrameHost(frame_host));
std::string device_id_salt =
process_host ? process_host->GetBrowserContext()->GetMediaDeviceIDSalt()
: std::string();
std::string group_id_salt =
device_id_salt + (web_contents
? web_contents->GetMediaDeviceGroupIDSaltBase()
: std::string());
url::Origin origin =
frame_host ? frame_host->GetLastCommittedOrigin() : url::Origin();
return {std::move(device_id_salt), std::move(group_id_salt),
std::move(origin)};
}
MediaDeviceInfo TranslateMediaDeviceInfo(
bool has_permission,
const MediaDeviceSaltAndOrigin& salt_and_origin,
const MediaDeviceInfo& device_info) {
return MediaDeviceInfo(
GetHMACForMediaDeviceID(salt_and_origin.device_id_salt,
salt_and_origin.origin, device_info.device_id),
has_permission ? device_info.label : std::string(),
device_info.group_id.empty()
? std::string()
: GetHMACForMediaDeviceID(salt_and_origin.group_id_salt,
salt_and_origin.origin,
device_info.group_id),
has_permission ? device_info.video_facing
: media::MEDIA_VIDEO_FACING_NONE);
}
MediaDeviceInfoArray TranslateMediaDeviceInfoArray(
bool has_permission,
const MediaDeviceSaltAndOrigin& salt_and_origin,
const MediaDeviceInfoArray& device_infos) {
MediaDeviceInfoArray result;
for (const auto& device_info : device_infos) {
result.push_back(
TranslateMediaDeviceInfo(has_permission, salt_and_origin, device_info));
}
return result;
}
} // namespace content
| 37.331492 | 80 | 0.692023 | zipated |
58c2136e2f59f31a6cb737bc67deee08ed2d3bad | 12,074 | cpp | C++ | Gems/Atom/RHI/Code/Source/RHI/CommandListValidator.cpp | xw901103/o3de | 76e09a36d900e871d170ce1ff6530c85e047093c | [
"Apache-2.0",
"MIT"
] | 1 | 2021-11-13T11:56:22.000Z | 2021-11-13T11:56:22.000Z | Gems/Atom/RHI/Code/Source/RHI/CommandListValidator.cpp | xw901103/o3de | 76e09a36d900e871d170ce1ff6530c85e047093c | [
"Apache-2.0",
"MIT"
] | 2 | 2021-09-08T03:30:28.000Z | 2022-03-12T00:59:27.000Z | Gems/Atom/RHI/Code/Source/RHI/CommandListValidator.cpp | xw901103/o3de | 76e09a36d900e871d170ce1ff6530c85e047093c | [
"Apache-2.0",
"MIT"
] | 1 | 2021-07-09T06:02:14.000Z | 2021-07-09T06:02:14.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <Atom/RHI/CommandListValidator.h>
#include <Atom/RHI/Scope.h>
#include <Atom/RHI/ShaderResourceGroup.h>
#include <Atom/RHI/ShaderResourceGroupPool.h>
#include <Atom/RHI/ResourcePool.h>
#include <Atom/RHI/BufferPoolBase.h>
#include <Atom/RHI/ImagePoolBase.h>
#include <Atom/RHI/ImageView.h>
#include <Atom/RHI/ResourceView.h>
#include <Atom/RHI/Resource.h>
#include <Atom/RHI/FrameGraph.h>
#include <Atom/RHI/ScopeAttachment.h>
#include <Atom/RHI/FrameAttachment.h>
#include <Atom/RHI.Reflect/PipelineLayoutDescriptor.h>
namespace AZ
{
namespace RHI
{
void CommandListValidator::BeginScope(const Scope& scope)
{
if (!Validation::IsEnabled())
{
return;
}
AZ_PROFILE_FUNCTION(RHI);
AZ_Assert(m_scope == nullptr, "BeginScope called twice.");
m_scope = &scope;
for (const ScopeAttachment* scopeAttachment : scope.GetAttachments())
{
const ResourceView* resourceView = scopeAttachment->GetResourceView();
m_attachments[&resourceView->GetResource()].push_back(scopeAttachment);
}
}
void CommandListValidator::EndScope()
{
if (!Validation::IsEnabled())
{
return;
}
m_scope = nullptr;
m_attachments.clear();
}
bool CommandListValidator::ValidateShaderResourceGroup(const ShaderResourceGroup& shaderResourceGroup, const ShaderResourceGroupBindingInfo& bindingInfo) const
{
if (!Validation::IsEnabled())
{
return true;
}
AZ_PROFILE_FUNCTION(RHI);
ValidateViewContext context;
context.m_scopeName = m_scope->GetId().GetCStr();
context.m_srgName = shaderResourceGroup.GetName().GetCStr();
if (shaderResourceGroup.IsQueuedForCompile())
{
AZ_Warning("CommandListValidator", false,
"[Scope '%s']: SRG '%s' is queued for compilation. This means the parent pool '%s' was not "
"imported into the frame scheduler. This will result in SRG contents not being uploaded to "
"the GPU.",
context.m_scopeName,
context.m_srgName,
shaderResourceGroup.GetPool()->GetName().GetCStr());
return false;
}
bool isSuccess = true;
const ShaderResourceGroupData& groupData = shaderResourceGroup.GetData();
const ShaderResourceGroupLayout& groupLayout = *groupData.GetLayout();
// Validate buffers
const auto& bufferInputs = groupLayout.GetShaderInputListForBuffers();
for (uint32_t shaderInputIndex = 0; shaderInputIndex < bufferInputs.size(); ++shaderInputIndex)
{
const RHI::ShaderInputBufferDescriptor& shaderInputBuffer = bufferInputs[shaderInputIndex];
// First check if the buffer is being used.
auto findIt = bindingInfo.m_resourcesRegisterMap.find(shaderInputBuffer.m_name);
if (findIt == bindingInfo.m_resourcesRegisterMap.end() || findIt->second.m_shaderStageMask == RHI::ShaderStageMask::None)
{
continue;
}
context.m_shaderInputTypeName = GetShaderInputAccessName(shaderInputBuffer.m_access);
context.m_scopeAttachmentAccess = GetAttachmentAccess(shaderInputBuffer.m_access);
const RHI::ShaderInputBufferIndex bufferInputIndex(shaderInputIndex);
auto bufferViews = groupData.GetBufferViewArray(bufferInputIndex);
for (auto& bufferView : bufferViews)
{
if (bufferView)
{
context.m_resourceView = bufferView.get();
isSuccess &= ValidateView(context, bufferView->IgnoreFrameAttachmentValidation());
}
}
}
// Validate images
const auto& imageInputs = groupLayout.GetShaderInputListForImages();
for (uint32_t shaderInputIndex = 0; shaderInputIndex < imageInputs.size(); ++shaderInputIndex)
{
const RHI::ShaderInputImageDescriptor& shaderInputImage = imageInputs[shaderInputIndex];
// First check if the image is being used.
auto findIt = bindingInfo.m_resourcesRegisterMap.find(shaderInputImage.m_name);
if (findIt == bindingInfo.m_resourcesRegisterMap.end() || findIt->second.m_shaderStageMask == RHI::ShaderStageMask::None)
{
continue;
}
context.m_shaderInputTypeName = GetShaderInputAccessName(shaderInputImage.m_access);
context.m_scopeAttachmentAccess = GetAttachmentAccess(shaderInputImage.m_access);
const RHI::ShaderInputImageIndex imageInputIndex(shaderInputIndex);
auto imageViews = groupData.GetImageViewArray(imageInputIndex);
for (auto& imageView : imageViews)
{
if (imageView)
{
context.m_resourceView = imageView.get();
isSuccess &= ValidateView(context, false);
}
}
++shaderInputIndex;
}
return isSuccess;
}
bool CommandListValidator::ValidateAttachment(
const ValidateViewContext& context,
const FrameAttachment* frameAttachment) const
{
AZ_Assert(frameAttachment, "Frame attachment is null.");
[[maybe_unused]] const char* attachmentName = frameAttachment->GetId().GetCStr();
const AZStd::vector<const ScopeAttachment*>* scopeAttachments = nullptr;
auto findIt = m_attachments.find(frameAttachment->GetResource());
if (findIt != m_attachments.end())
{
scopeAttachments = &findIt->second;
}
if (scopeAttachments && scopeAttachments->size() > 0)
{
bool isValidUsage = false;
bool isValidAccess = false;
for (const ScopeAttachment* scopeAttachment : *scopeAttachments)
{
isValidUsage = (scopeAttachment->HasUsage(ScopeAttachmentUsage::Shader) || scopeAttachment->HasUsage(ScopeAttachmentUsage::SubpassInput));
isValidAccess = (scopeAttachment->HasAccessAndUsage(ScopeAttachmentUsage::Shader, context.m_scopeAttachmentAccess) || scopeAttachment->HasAccessAndUsage(ScopeAttachmentUsage::SubpassInput, context.m_scopeAttachmentAccess));
if (isValidUsage && isValidAccess)
{
return true;
}
}
// We couldn't find a scope attachment that matches the usage, output warning
AZ_Warning("CommandListValidator", false,
"[Scope '%s', SRG '%s']: Failed to find a matching usage for attachment '%s'. Mismatches are as follows:",
context.m_scopeName,
context.m_srgName,
attachmentName);
// Output mismatch for each of the scope attachments in the list
for (const ScopeAttachment* scopeAttachment : *scopeAttachments)
{
isValidUsage = (scopeAttachment->HasUsage(ScopeAttachmentUsage::Shader) || scopeAttachment->HasUsage(ScopeAttachmentUsage::SubpassInput));
isValidAccess = (scopeAttachment->HasAccessAndUsage(ScopeAttachmentUsage::Shader, context.m_scopeAttachmentAccess) || scopeAttachment->HasAccessAndUsage(ScopeAttachmentUsage::SubpassInput, context.m_scopeAttachmentAccess));
AZ_Warning("CommandListValidator", isValidUsage,
"[Scope '%s', SRG '%s']: Attachment '%s' is used as ['%s'], but usage needs to be 'Shader'",
context.m_scopeName,
context.m_srgName,
attachmentName,
scopeAttachment->GetUsageTypes().c_str());
AZ_Warning("CommandListValidator", isValidAccess,
"[Scope '%s', SRG '%s']: Attachment '%s' is marked for '%s' access, but the scope declared ['%s'] access.",
context.m_scopeName,
context.m_srgName,
attachmentName,
ToString(context.m_scopeAttachmentAccess),
scopeAttachment->GetAccessTypes().c_str());
}
return false;
}
AZ_Warning(
"CommandListValidator", false,
"[Scope '%s', SRG '%s']: Attachment '%s' not declared for usage in this scope. Actual usage: '%s'",
context.m_scopeName,
context.m_srgName,
attachmentName,
context.m_shaderInputTypeName);
return false;
}
ScopeAttachmentAccess CommandListValidator::GetAttachmentAccess(ShaderInputBufferAccess access)
{
return
(access == ShaderInputBufferAccess::ReadWrite)
? ScopeAttachmentAccess::ReadWrite
: ScopeAttachmentAccess::Read;
}
ScopeAttachmentAccess CommandListValidator::GetAttachmentAccess(ShaderInputImageAccess access)
{
return
(access == ShaderInputImageAccess::ReadWrite)
? ScopeAttachmentAccess::ReadWrite
: ScopeAttachmentAccess::Read;
}
bool CommandListValidator::ValidateView(const ValidateViewContext& context, bool ignoreAttachmentValidation) const
{
const ResourceView& resourceView = *context.m_resourceView;
const Resource& resource = resourceView.GetResource();
[[maybe_unused]] const char* resourceViewName = resourceView.GetName().GetCStr();
[[maybe_unused]] const char* resourceName = resource.GetName().GetCStr();
if (resourceView.IsStale())
{
AZ_Warning(
"CommandListValidator", false,
"[Scope '%s', SRG '%s']: ResourceView '%s' of Resource '%s' is stale! This indicates that the SRG was not properly "
"compiled, or was invalidated after compilation during the command list recording phase.",
context.m_scopeName,
context.m_srgName,
resourceViewName,
resourceName);
return false;
}
if (resource.IsAttachment())
{
return ValidateAttachment(context, resource.GetFrameAttachment());
}
// Resource is not an attachment. It must be in a read-only state.
if (!ignoreAttachmentValidation && context.m_scopeAttachmentAccess != ScopeAttachmentAccess::Read)
{
AZ_Warning(
"CommandListValidator", false,
"[Scope '%s', SRG '%s']: ResourceView '%s' of Resource '%s' is declared as '%s', but this type "
"requires that the resource be an attachment.",
context.m_scopeName,
context.m_srgName,
resourceViewName,
resourceName,
context.m_shaderInputTypeName);
return false;
}
return true;
}
}
}
| 43.431655 | 243 | 0.576942 | xw901103 |
58c4667a5921634e5f6e03fab9411c06efbe2d71 | 5,927 | cpp | C++ | Plugins/DlgSystem/Source/DlgSystem/Private/Nodes/DlgNode.cpp | denfrost/DlgSystem | e8e65b8e77ebaad9071dafed3c6dccc55c9aaa23 | [
"MIT"
] | null | null | null | Plugins/DlgSystem/Source/DlgSystem/Private/Nodes/DlgNode.cpp | denfrost/DlgSystem | e8e65b8e77ebaad9071dafed3c6dccc55c9aaa23 | [
"MIT"
] | null | null | null | Plugins/DlgSystem/Source/DlgSystem/Private/Nodes/DlgNode.cpp | denfrost/DlgSystem | e8e65b8e77ebaad9071dafed3c6dccc55c9aaa23 | [
"MIT"
] | null | null | null | // Copyright 2017-2018 Csaba Molnar, Daniel Butum
#include "DlgNode.h"
#include "DlgSystemPrivatePCH.h"
#include "DlgContextInternal.h"
#include "EngineUtils.h"
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Begin UObject interface
void UDlgNode::Serialize(FArchive& Ar)
{
Super::Serialize(Ar);
if (Ar.UE4Ver() >= VER_UE4_COOKED_ASSETS_IN_EDITOR_SUPPORT)
{
FStripDataFlags StripFlags(Ar);
#if WITH_EDITOR
if (!StripFlags.IsEditorDataStripped())
{
Ar << GraphNode;
}
#endif
}
#if WITH_EDITOR
else
{
Ar << GraphNode;
}
#endif
}
#if WITH_EDITOR
void UDlgNode::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent)
{
Super::PostEditChangeProperty(PropertyChangedEvent);
// Signal to the listeners
OnDialogueNodePropertyChanged.Broadcast(PropertyChangedEvent, BroadcastPropertyEdgeIndexChanged);
BroadcastPropertyEdgeIndexChanged = INDEX_NONE;
}
void UDlgNode::PostEditChangeChainProperty(struct FPropertyChangedChainEvent& PropertyChangedEvent)
{
// The Super::PostEditChangeChainProperty will construct a new FPropertyChangedEvent that will only have the Property and the
// MemberProperty name and it will call the PostEditChangeProperty, so we must get the array index of the Nodes modified from here.
// If you want to preserve all the change history of the tree you must broadcast the event from here to the children, but be warned
// that Property and MemberProperty are not set properly.
BroadcastPropertyEdgeIndexChanged = PropertyChangedEvent.GetArrayIndex(GET_MEMBER_NAME_STRING_CHECKED(UDlgNode, Children));
Super::PostEditChangeChainProperty(PropertyChangedEvent);
}
void UDlgNode::AddReferencedObjects(UObject* InThis, FReferenceCollector& Collector)
{
// Add the GraphNode to the referenced objects
UDlgNode* This = CastChecked<UDlgNode>(InThis);
Collector.AddReferencedObject(This->GraphNode, This);
Super::AddReferencedObjects(InThis, Collector);
}
#endif //WITH_EDITOR
// End UObject interface
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Begin own function
bool UDlgNode::HandleNodeEnter(UDlgContextInternal* DlgContext, TSet<const UDlgNode*> NodesEnteredWithThisStep)
{
check(DlgContext != nullptr);
// Fire all the node enter events
FireNodeEnterEvents(DlgContext);
for (FDlgEdge& Edge : Children)
{
Edge.ConstructTextFromArguments(DlgContext, OwnerName);
}
return ReevaluateChildren(DlgContext, {});
}
void UDlgNode::FireNodeEnterEvents(UDlgContextInternal* DlgContext)
{
for (const FDlgEvent& Event : EnterEvents)
{
UObject* Particpant = DlgContext->GetParticipant(Event.ParticipantName);
if (!IsValid(Particpant))
{
Particpant = DlgContext->GetParticipant(OwnerName);
}
Event.Call(Particpant);
}
}
bool UDlgNode::ReevaluateChildren(UDlgContextInternal* DlgContext, TSet<const UDlgNode*> AlreadyEvaluated)
{
check(DlgContext != nullptr);
TArray<const FDlgEdge*>& AvailableChildren = DlgContext->GetOptionArray();
TArray<FDlgEdgeData>& AllChildren = DlgContext->GetAllOptionsArray();
AvailableChildren.Empty();
AllChildren.Empty();
for (const FDlgEdge& Edge : Children)
{
const bool bSatisfied = Edge.Evaluate(DlgContext, { this });
if (bSatisfied || Edge.bIncludeInAllOptionListIfUnsatisfied)
{
AllChildren.Add(FDlgEdgeData{ bSatisfied, &Edge });
}
if (bSatisfied)
{
AvailableChildren.Add(&Edge);
}
}
// no child, but no end node?
if (AvailableChildren.Num() == 0)
{
UE_LOG(LogDlgSystem, Warning, TEXT("Dialogue stucked: no valid child for a node!"));
return false;
}
return true;
}
bool UDlgNode::CheckNodeEnterConditions(const UDlgContextInternal* DlgContext, TSet<const UDlgNode*> AlreadyVisitedNodes) const
{
if (AlreadyVisitedNodes.Contains(this))
{
return true;
}
AlreadyVisitedNodes.Add(this);
if (!FDlgCondition::EvaluateArray(EnterConditions, DlgContext, OwnerName))
{
return false;
}
if (!bCheckChildrenOnEvaluation)
{
return true;
}
// Has a valid child?
return HasAnySatisfiedChild(DlgContext, AlreadyVisitedNodes);
}
bool UDlgNode::HasAnySatisfiedChild(const UDlgContextInternal* DlgContext, TSet<const UDlgNode*> AlreadyVisitedNodes) const
{
for (const FDlgEdge& Edge : Children)
{
if (Edge.Evaluate(DlgContext, AlreadyVisitedNodes))
{
return true;
}
}
return false;
}
bool UDlgNode::OptionSelected(int32 OptionIndex, UDlgContextInternal* DlgContext)
{
TArray<const FDlgEdge*>& AvailableChildren = DlgContext->GetOptionArray();
if (AvailableChildren.IsValidIndex(OptionIndex))
{
check(AvailableChildren[OptionIndex] != nullptr);
return DlgContext->EnterNode(AvailableChildren[OptionIndex]->TargetIndex, {});
}
UE_LOG(LogDlgSystem,
Error,
TEXT("Failed to choose option index = %d - it only has %d valid options!"),
OptionIndex,
AvailableChildren.Num());
return false;
}
const TArray<int32> UDlgNode::GetNodeOpenChildren_DEPRECATED() const
{
TArray<int32> OutArray;
const int32 EdgesNum = Children.Num();
for (int32 EdgeIndex = 0; EdgeIndex < EdgesNum; EdgeIndex++)
{
if (!Children[EdgeIndex].IsValid())
{
OutArray.Add(EdgeIndex);
}
}
return OutArray;
}
FDlgEdge* UDlgNode::GetMutableNodeChildForTargetIndex(int32 TargetIndex)
{
for (FDlgEdge& Edge : Children)
{
if (Edge.TargetIndex == TargetIndex)
{
return &Edge;
}
}
return nullptr;
}
void UDlgNode::GetAssociatedParticipants(TArray<FName>& OutArray) const
{
if (OwnerName != NAME_None)
{
OutArray.AddUnique(OwnerName);
}
}
UDlgDialogue* UDlgNode::GetDialogue() const
{
return CastChecked<UDlgDialogue>(GetOuter());
}
// End own functions
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
| 26.698198 | 132 | 0.702042 | denfrost |
58c4e5ac7ba38b36e29a6975398fa189684f2f13 | 479 | cpp | C++ | Source/Editor/Private/Customizations/SEComponentClassFilterCustomization.cpp | foobit/SaveExtension | 390033bc757f2b694c497e22c324dcac539bcd15 | [
"Apache-2.0"
] | 110 | 2018-10-20T21:47:54.000Z | 2022-03-14T03:47:58.000Z | Source/Editor/Private/Customizations/SEComponentClassFilterCustomization.cpp | foobit/SaveExtension | 390033bc757f2b694c497e22c324dcac539bcd15 | [
"Apache-2.0"
] | 68 | 2018-12-19T09:08:56.000Z | 2022-03-09T06:43:38.000Z | Source/Editor/Private/Customizations/SEComponentClassFilterCustomization.cpp | foobit/SaveExtension | 390033bc757f2b694c497e22c324dcac539bcd15 | [
"Apache-2.0"
] | 45 | 2018-12-03T14:35:47.000Z | 2022-03-05T01:35:24.000Z | // Copyright 2015-2020 Piperift. All Rights Reserved.
#include "Customizations/SEComponentClassFilterCustomization.h"
#include "PropertyHandle.h"
#define LOCTEXT_NAMESPACE "FSEComponentClassFilterCustomization"
TSharedPtr<IPropertyHandle> FSEComponentClassFilterCustomization::GetFilterHandle(TSharedRef<IPropertyHandle> StructPropertyHandle)
{
return StructHandle->GetChildHandle(GET_MEMBER_NAME_CHECKED(FSEComponentClassFilter, ClassFilter));;
}
#undef LOCTEXT_NAMESPACE
| 31.933333 | 131 | 0.860125 | foobit |
58c6e8c64c29739e6951e1ff66d67fa5ea003393 | 2,338 | cpp | C++ | src/imaging/ossimJpegMemDest.cpp | martidi/ossim | 44268fa9d7fc5a3038642e702e85ccd339a4ff9f | [
"MIT"
] | null | null | null | src/imaging/ossimJpegMemDest.cpp | martidi/ossim | 44268fa9d7fc5a3038642e702e85ccd339a4ff9f | [
"MIT"
] | null | null | null | src/imaging/ossimJpegMemDest.cpp | martidi/ossim | 44268fa9d7fc5a3038642e702e85ccd339a4ff9f | [
"MIT"
] | 1 | 2018-10-11T11:36:16.000Z | 2018-10-11T11:36:16.000Z | //----------------------------------------------------------------------------
//
// License: See top level LICENSE.txt file
//
// Most of code and comments below are from jpeg-6b "example.c" file. See
// http://www4.cs.fau.de/Services/Doc/graphics/doc/jpeg/libjpeg.html
//
// Author: Oscar Kramer (From example by Thomas Lane)
//----------------------------------------------------------------------------
// $Id$
#include <ossim/imaging/ossimJpegMemDest.h>
#include <cstdlib> /* free, malloc */
/* *** Custom destination manager for JPEG writer *** */
typedef struct
{
struct jpeg_destination_mgr pub; /* public fields */
std::ostream* stream; /* target stream */
JOCTET* buffer; /* start of buffer */
} cpp_dest_mgr;
#define OUTPUT_BUF_SIZE 4096 /* choose an efficiently fwrite'able size */
void init_destination (j_compress_ptr cinfo)
{
cpp_dest_mgr* dest = (cpp_dest_mgr*) cinfo->dest;
/* Allocate the output buffer --- it will be released when done with image */
dest->buffer = (JOCTET *)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, OUTPUT_BUF_SIZE * sizeof(JOCTET));
dest->pub.next_output_byte = dest->buffer;
dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
}
boolean empty_output_buffer (j_compress_ptr cinfo)
{
cpp_dest_mgr* dest = (cpp_dest_mgr*) cinfo->dest;
dest->stream->write ((char*)dest->buffer, OUTPUT_BUF_SIZE);
dest->pub.next_output_byte = dest->buffer;
dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
return TRUE;
}
void term_destination (j_compress_ptr cinfo)
{
cpp_dest_mgr* dest = (cpp_dest_mgr*) cinfo->dest;
size_t datacount = OUTPUT_BUF_SIZE - dest->pub.free_in_buffer;
/* Write any data remaining in the buffer */
if (datacount > 0)
dest->stream->write ((char*)dest->buffer, datacount);
dest->stream->flush();
free (cinfo->dest);
}
void jpeg_cpp_stream_dest (j_compress_ptr cinfo, std::ostream& stream)
{
cpp_dest_mgr* dest;
/* first time for this JPEG object? */
if (cinfo->dest == NULL)
cinfo->dest = (struct jpeg_destination_mgr *) malloc (sizeof(cpp_dest_mgr));
dest = (cpp_dest_mgr*) cinfo->dest;
dest->pub.init_destination = init_destination;
dest->pub.empty_output_buffer = empty_output_buffer;
dest->pub.term_destination = term_destination;
dest->stream = &stream;
}
| 30.363636 | 103 | 0.652695 | martidi |
58ca4902c0172be2c805c0ddf926e800f67b4417 | 789 | hpp | C++ | mycenter/center/BaseCenter.hpp | nightli110/mycenter | 3d96bf6fa6e3442646f9a416c6fd80c9807590c8 | [
"MIT"
] | null | null | null | mycenter/center/BaseCenter.hpp | nightli110/mycenter | 3d96bf6fa6e3442646f9a416c6fd80c9807590c8 | [
"MIT"
] | null | null | null | mycenter/center/BaseCenter.hpp | nightli110/mycenter | 3d96bf6fa6e3442646f9a416c6fd80c9807590c8 | [
"MIT"
] | null | null | null | /***
* @Author: nightli
* @Date: 2020-10-13 17:15:52
* @LastEditors: nightli
* @LastEditTime: 2020-10-14 10:22:11
* @FilePath: /mycenter/MyCenter.hpp
* @Emile: 1658484908@qq.com
*/
#include <iostream>
#include "../App/InferenceAPP.hpp"
#include "../datatype/MyData.hpp"
using namespace std;
class BaseCenter
{
public:
BaseCenter();
BaseCenter(const BaseCenter&);
bool ProcessData(Json::Value DataInfoJson);
bool PostData(Json::Value request_json);
bool CallInferenceOnline(string Inferencename);
void InitCenter(InferenceAPPMap* MyAppMap);
void UpdateAppdata();
void RunCenter();
private:
InferenceAPPMap *CenterAppMap;
map<string, DataInfo> DataMsgs;
map<string, bool> AppStatus;
boost::shared_mutex read_write_mutex;
}; | 19.243902 | 51 | 0.698352 | nightli110 |
58cacab165c4632ea27caa957d773f0741d5828d | 18,087 | cc | C++ | test/helpers/vector_element.cc | GeorgeWeb/SYCL-DNN | 50fe1357f5302d188d85512c58de1ae7ed8a0912 | [
"Apache-2.0"
] | null | null | null | test/helpers/vector_element.cc | GeorgeWeb/SYCL-DNN | 50fe1357f5302d188d85512c58de1ae7ed8a0912 | [
"Apache-2.0"
] | null | null | null | test/helpers/vector_element.cc | GeorgeWeb/SYCL-DNN | 50fe1357f5302d188d85512c58de1ae7ed8a0912 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2018 Codeplay Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include "src/helpers/vector_element.h"
#include <CL/sycl.hpp>
template <typename T>
struct VectorElementTest : public ::testing::Test {};
using NumericTypes = ::testing::Types<float, double>;
TYPED_TEST_CASE(VectorElementTest, NumericTypes);
TYPED_TEST(VectorElementTest, NonVectorTypes) {
TypeParam a = 0;
TypeParam val = sycldnn::helpers::vector_element::get(a, 0);
EXPECT_EQ(a, val);
TypeParam const b = 10;
sycldnn::helpers::vector_element::set(a, 0, b);
EXPECT_EQ(b, a);
}
TYPED_TEST(VectorElementTest, Vector1DType) {
using Vec = cl::sycl::vec<TypeParam, 1>;
TypeParam a = 0;
Vec vec{a};
TypeParam val = sycldnn::helpers::vector_element::get(vec, 0);
EXPECT_EQ(a, val);
TypeParam const b = 10;
sycldnn::helpers::vector_element::set(vec, 0, b);
EXPECT_EQ(b, vec.s0());
}
TYPED_TEST(VectorElementTest, Vector2DType) {
using Vec = cl::sycl::vec<TypeParam, 2>;
TypeParam a0 = 0;
TypeParam a1 = 1;
Vec vec{a0, a1};
TypeParam val_0 = sycldnn::helpers::vector_element::get(vec, 0);
EXPECT_EQ(a0, val_0);
TypeParam val_1 = sycldnn::helpers::vector_element::get(vec, 1);
EXPECT_EQ(a1, val_1);
TypeParam const b0 = 10;
sycldnn::helpers::vector_element::set(vec, 0, b0);
EXPECT_EQ(b0, vec.s0());
EXPECT_EQ(a1, vec.s1());
TypeParam const b1 = 15;
sycldnn::helpers::vector_element::set(vec, 1, b1);
EXPECT_EQ(b0, vec.s0());
EXPECT_EQ(b1, vec.s1());
}
TYPED_TEST(VectorElementTest, Vector3DType) {
using Vec = cl::sycl::vec<TypeParam, 3>;
TypeParam a0 = 0;
TypeParam a1 = 1;
TypeParam a2 = 2;
Vec vec{a0, a1, a2};
TypeParam val_0 = sycldnn::helpers::vector_element::get(vec, 0);
EXPECT_EQ(a0, val_0);
TypeParam val_1 = sycldnn::helpers::vector_element::get(vec, 1);
EXPECT_EQ(a1, val_1);
TypeParam val_2 = sycldnn::helpers::vector_element::get(vec, 2);
EXPECT_EQ(a2, val_2);
TypeParam const b0 = 10;
sycldnn::helpers::vector_element::set(vec, 0, b0);
EXPECT_EQ(b0, vec.s0());
EXPECT_EQ(a1, vec.s1());
EXPECT_EQ(a2, vec.s2());
TypeParam const b1 = 15;
sycldnn::helpers::vector_element::set(vec, 1, b1);
EXPECT_EQ(b0, vec.s0());
EXPECT_EQ(b1, vec.s1());
EXPECT_EQ(a2, vec.s2());
TypeParam const b2 = 20;
sycldnn::helpers::vector_element::set(vec, 2, b2);
EXPECT_EQ(b0, vec.s0());
EXPECT_EQ(b1, vec.s1());
EXPECT_EQ(b2, vec.s2());
}
TYPED_TEST(VectorElementTest, Vector4DType) {
using Vec = cl::sycl::vec<TypeParam, 4>;
TypeParam a0 = 0;
TypeParam a1 = 1;
TypeParam a2 = 2;
TypeParam a3 = 3;
Vec vec{a0, a1, a2, a3};
TypeParam val_0 = sycldnn::helpers::vector_element::get(vec, 0);
EXPECT_EQ(a0, val_0);
TypeParam val_1 = sycldnn::helpers::vector_element::get(vec, 1);
EXPECT_EQ(a1, val_1);
TypeParam val_2 = sycldnn::helpers::vector_element::get(vec, 2);
EXPECT_EQ(a2, val_2);
TypeParam val_3 = sycldnn::helpers::vector_element::get(vec, 3);
EXPECT_EQ(a3, val_3);
TypeParam const b0 = 10;
sycldnn::helpers::vector_element::set(vec, 0, b0);
EXPECT_EQ(b0, vec.s0());
EXPECT_EQ(a1, vec.s1());
EXPECT_EQ(a2, vec.s2());
EXPECT_EQ(a3, vec.s3());
TypeParam const b1 = 15;
sycldnn::helpers::vector_element::set(vec, 1, b1);
EXPECT_EQ(b0, vec.s0());
EXPECT_EQ(b1, vec.s1());
EXPECT_EQ(a2, vec.s2());
EXPECT_EQ(a3, vec.s3());
TypeParam const b2 = 20;
sycldnn::helpers::vector_element::set(vec, 2, b2);
EXPECT_EQ(b0, vec.s0());
EXPECT_EQ(b1, vec.s1());
EXPECT_EQ(b2, vec.s2());
EXPECT_EQ(a3, vec.s3());
TypeParam const b3 = 30;
sycldnn::helpers::vector_element::set(vec, 3, b3);
EXPECT_EQ(b0, vec.s0());
EXPECT_EQ(b1, vec.s1());
EXPECT_EQ(b2, vec.s2());
EXPECT_EQ(b3, vec.s3());
}
TYPED_TEST(VectorElementTest, Vector8DType) {
using Vec = cl::sycl::vec<TypeParam, 8>;
TypeParam a0 = 0;
TypeParam a1 = 1;
TypeParam a2 = 2;
TypeParam a3 = 3;
TypeParam a4 = 4;
TypeParam a5 = 5;
TypeParam a6 = 6;
TypeParam a7 = 7;
Vec vec{a0, a1, a2, a3, a4, a5, a6, a7};
TypeParam val_0 = sycldnn::helpers::vector_element::get(vec, 0);
EXPECT_EQ(a0, val_0);
TypeParam val_1 = sycldnn::helpers::vector_element::get(vec, 1);
EXPECT_EQ(a1, val_1);
TypeParam val_2 = sycldnn::helpers::vector_element::get(vec, 2);
EXPECT_EQ(a2, val_2);
TypeParam val_3 = sycldnn::helpers::vector_element::get(vec, 3);
EXPECT_EQ(a3, val_3);
TypeParam val_4 = sycldnn::helpers::vector_element::get(vec, 4);
EXPECT_EQ(a4, val_4);
TypeParam val_5 = sycldnn::helpers::vector_element::get(vec, 5);
EXPECT_EQ(a5, val_5);
TypeParam val_6 = sycldnn::helpers::vector_element::get(vec, 6);
EXPECT_EQ(a6, val_6);
TypeParam val_7 = sycldnn::helpers::vector_element::get(vec, 7);
EXPECT_EQ(a7, val_7);
TypeParam const b0 = 10;
sycldnn::helpers::vector_element::set(vec, 0, b0);
EXPECT_EQ(b0, vec.s0());
EXPECT_EQ(a1, vec.s1());
EXPECT_EQ(a2, vec.s2());
EXPECT_EQ(a3, vec.s3());
EXPECT_EQ(a4, vec.s4());
EXPECT_EQ(a5, vec.s5());
EXPECT_EQ(a6, vec.s6());
EXPECT_EQ(a7, vec.s7());
TypeParam const b1 = 15;
sycldnn::helpers::vector_element::set(vec, 1, b1);
EXPECT_EQ(b0, vec.s0());
EXPECT_EQ(b1, vec.s1());
EXPECT_EQ(a2, vec.s2());
EXPECT_EQ(a3, vec.s3());
EXPECT_EQ(a4, vec.s4());
EXPECT_EQ(a5, vec.s5());
EXPECT_EQ(a6, vec.s6());
EXPECT_EQ(a7, vec.s7());
TypeParam const b2 = 20;
sycldnn::helpers::vector_element::set(vec, 2, b2);
EXPECT_EQ(b0, vec.s0());
EXPECT_EQ(b1, vec.s1());
EXPECT_EQ(b2, vec.s2());
EXPECT_EQ(a3, vec.s3());
EXPECT_EQ(a4, vec.s4());
EXPECT_EQ(a5, vec.s5());
EXPECT_EQ(a6, vec.s6());
EXPECT_EQ(a7, vec.s7());
TypeParam const b3 = 30;
sycldnn::helpers::vector_element::set(vec, 3, b3);
EXPECT_EQ(b0, vec.s0());
EXPECT_EQ(b1, vec.s1());
EXPECT_EQ(b2, vec.s2());
EXPECT_EQ(b3, vec.s3());
EXPECT_EQ(a4, vec.s4());
EXPECT_EQ(a5, vec.s5());
EXPECT_EQ(a6, vec.s6());
EXPECT_EQ(a7, vec.s7());
TypeParam const b4 = 40;
sycldnn::helpers::vector_element::set(vec, 4, b4);
EXPECT_EQ(b0, vec.s0());
EXPECT_EQ(b1, vec.s1());
EXPECT_EQ(b2, vec.s2());
EXPECT_EQ(b3, vec.s3());
EXPECT_EQ(b4, vec.s4());
EXPECT_EQ(a5, vec.s5());
EXPECT_EQ(a6, vec.s6());
EXPECT_EQ(a7, vec.s7());
TypeParam const b5 = 50;
sycldnn::helpers::vector_element::set(vec, 5, b5);
EXPECT_EQ(b0, vec.s0());
EXPECT_EQ(b1, vec.s1());
EXPECT_EQ(b2, vec.s2());
EXPECT_EQ(b3, vec.s3());
EXPECT_EQ(b4, vec.s4());
EXPECT_EQ(b5, vec.s5());
EXPECT_EQ(a6, vec.s6());
EXPECT_EQ(a7, vec.s7());
TypeParam const b6 = 60;
sycldnn::helpers::vector_element::set(vec, 6, b6);
EXPECT_EQ(b0, vec.s0());
EXPECT_EQ(b1, vec.s1());
EXPECT_EQ(b2, vec.s2());
EXPECT_EQ(b3, vec.s3());
EXPECT_EQ(b4, vec.s4());
EXPECT_EQ(b5, vec.s5());
EXPECT_EQ(b6, vec.s6());
EXPECT_EQ(a7, vec.s7());
TypeParam const b7 = 70;
sycldnn::helpers::vector_element::set(vec, 7, b7);
EXPECT_EQ(b0, vec.s0());
EXPECT_EQ(b1, vec.s1());
EXPECT_EQ(b2, vec.s2());
EXPECT_EQ(b3, vec.s3());
EXPECT_EQ(b4, vec.s4());
EXPECT_EQ(b5, vec.s5());
EXPECT_EQ(b6, vec.s6());
EXPECT_EQ(b7, vec.s7());
}
// NOLINTNEXTLINE(google-readability-function-size)
TYPED_TEST(VectorElementTest, Vector16DType) {
using Vec = cl::sycl::vec<TypeParam, 16>;
TypeParam a0 = 0;
TypeParam a1 = 1;
TypeParam a2 = 2;
TypeParam a3 = 3;
TypeParam a4 = 4;
TypeParam a5 = 5;
TypeParam a6 = 6;
TypeParam a7 = 7;
TypeParam a8 = 8;
TypeParam a9 = 9;
TypeParam a10 = 10;
TypeParam a11 = 11;
TypeParam a12 = 12;
TypeParam a13 = 13;
TypeParam a14 = 14;
TypeParam a15 = 15;
Vec vec{a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15};
TypeParam val_0 = sycldnn::helpers::vector_element::get(vec, 0);
EXPECT_EQ(a0, val_0);
TypeParam val_1 = sycldnn::helpers::vector_element::get(vec, 1);
EXPECT_EQ(a1, val_1);
TypeParam val_2 = sycldnn::helpers::vector_element::get(vec, 2);
EXPECT_EQ(a2, val_2);
TypeParam val_3 = sycldnn::helpers::vector_element::get(vec, 3);
EXPECT_EQ(a3, val_3);
TypeParam val_4 = sycldnn::helpers::vector_element::get(vec, 4);
EXPECT_EQ(a4, val_4);
TypeParam val_5 = sycldnn::helpers::vector_element::get(vec, 5);
EXPECT_EQ(a5, val_5);
TypeParam val_6 = sycldnn::helpers::vector_element::get(vec, 6);
EXPECT_EQ(a6, val_6);
TypeParam val_7 = sycldnn::helpers::vector_element::get(vec, 7);
EXPECT_EQ(a7, val_7);
TypeParam val_8 = sycldnn::helpers::vector_element::get(vec, 8);
EXPECT_EQ(a8, val_8);
TypeParam val_9 = sycldnn::helpers::vector_element::get(vec, 9);
EXPECT_EQ(a9, val_9);
TypeParam val_10 = sycldnn::helpers::vector_element::get(vec, 10);
EXPECT_EQ(a10, val_10);
TypeParam val_11 = sycldnn::helpers::vector_element::get(vec, 11);
EXPECT_EQ(a11, val_11);
TypeParam val_12 = sycldnn::helpers::vector_element::get(vec, 12);
EXPECT_EQ(a12, val_12);
TypeParam val_13 = sycldnn::helpers::vector_element::get(vec, 13);
EXPECT_EQ(a13, val_13);
TypeParam val_14 = sycldnn::helpers::vector_element::get(vec, 14);
EXPECT_EQ(a14, val_14);
TypeParam val_15 = sycldnn::helpers::vector_element::get(vec, 15);
EXPECT_EQ(a15, val_15);
TypeParam const b0 = 10;
sycldnn::helpers::vector_element::set(vec, 0, b0);
EXPECT_EQ(b0, vec.s0());
EXPECT_EQ(a1, vec.s1());
EXPECT_EQ(a2, vec.s2());
EXPECT_EQ(a3, vec.s3());
EXPECT_EQ(a4, vec.s4());
EXPECT_EQ(a5, vec.s5());
EXPECT_EQ(a6, vec.s6());
EXPECT_EQ(a7, vec.s7());
EXPECT_EQ(a8, vec.s8());
EXPECT_EQ(a9, vec.s9());
EXPECT_EQ(a10, vec.sA());
EXPECT_EQ(a11, vec.sB());
EXPECT_EQ(a12, vec.sC());
EXPECT_EQ(a13, vec.sD());
EXPECT_EQ(a14, vec.sE());
EXPECT_EQ(a15, vec.sF());
TypeParam const b1 = 15;
sycldnn::helpers::vector_element::set(vec, 1, b1);
EXPECT_EQ(b0, vec.s0());
EXPECT_EQ(b1, vec.s1());
EXPECT_EQ(a2, vec.s2());
EXPECT_EQ(a3, vec.s3());
EXPECT_EQ(a4, vec.s4());
EXPECT_EQ(a5, vec.s5());
EXPECT_EQ(a6, vec.s6());
EXPECT_EQ(a7, vec.s7());
EXPECT_EQ(a8, vec.s8());
EXPECT_EQ(a9, vec.s9());
EXPECT_EQ(a10, vec.sA());
EXPECT_EQ(a11, vec.sB());
EXPECT_EQ(a12, vec.sC());
EXPECT_EQ(a13, vec.sD());
EXPECT_EQ(a14, vec.sE());
EXPECT_EQ(a15, vec.sF());
TypeParam const b2 = 20;
sycldnn::helpers::vector_element::set(vec, 2, b2);
EXPECT_EQ(b0, vec.s0());
EXPECT_EQ(b1, vec.s1());
EXPECT_EQ(b2, vec.s2());
EXPECT_EQ(a3, vec.s3());
EXPECT_EQ(a4, vec.s4());
EXPECT_EQ(a5, vec.s5());
EXPECT_EQ(a6, vec.s6());
EXPECT_EQ(a7, vec.s7());
EXPECT_EQ(a8, vec.s8());
EXPECT_EQ(a9, vec.s9());
EXPECT_EQ(a10, vec.sA());
EXPECT_EQ(a11, vec.sB());
EXPECT_EQ(a12, vec.sC());
EXPECT_EQ(a13, vec.sD());
EXPECT_EQ(a14, vec.sE());
EXPECT_EQ(a15, vec.sF());
TypeParam const b3 = 30;
sycldnn::helpers::vector_element::set(vec, 3, b3);
EXPECT_EQ(b0, vec.s0());
EXPECT_EQ(b1, vec.s1());
EXPECT_EQ(b2, vec.s2());
EXPECT_EQ(b3, vec.s3());
EXPECT_EQ(a4, vec.s4());
EXPECT_EQ(a5, vec.s5());
EXPECT_EQ(a6, vec.s6());
EXPECT_EQ(a7, vec.s7());
EXPECT_EQ(a8, vec.s8());
EXPECT_EQ(a9, vec.s9());
EXPECT_EQ(a10, vec.sA());
EXPECT_EQ(a11, vec.sB());
EXPECT_EQ(a12, vec.sC());
EXPECT_EQ(a13, vec.sD());
EXPECT_EQ(a14, vec.sE());
EXPECT_EQ(a15, vec.sF());
TypeParam const b4 = 40;
sycldnn::helpers::vector_element::set(vec, 4, b4);
EXPECT_EQ(b0, vec.s0());
EXPECT_EQ(b1, vec.s1());
EXPECT_EQ(b2, vec.s2());
EXPECT_EQ(b3, vec.s3());
EXPECT_EQ(b4, vec.s4());
EXPECT_EQ(a5, vec.s5());
EXPECT_EQ(a6, vec.s6());
EXPECT_EQ(a7, vec.s7());
EXPECT_EQ(a8, vec.s8());
EXPECT_EQ(a9, vec.s9());
EXPECT_EQ(a10, vec.sA());
EXPECT_EQ(a11, vec.sB());
EXPECT_EQ(a12, vec.sC());
EXPECT_EQ(a13, vec.sD());
EXPECT_EQ(a14, vec.sE());
EXPECT_EQ(a15, vec.sF());
TypeParam const b5 = 50;
sycldnn::helpers::vector_element::set(vec, 5, b5);
EXPECT_EQ(b0, vec.s0());
EXPECT_EQ(b1, vec.s1());
EXPECT_EQ(b2, vec.s2());
EXPECT_EQ(b3, vec.s3());
EXPECT_EQ(b4, vec.s4());
EXPECT_EQ(b5, vec.s5());
EXPECT_EQ(a6, vec.s6());
EXPECT_EQ(a7, vec.s7());
EXPECT_EQ(a8, vec.s8());
EXPECT_EQ(a9, vec.s9());
EXPECT_EQ(a10, vec.sA());
EXPECT_EQ(a11, vec.sB());
EXPECT_EQ(a12, vec.sC());
EXPECT_EQ(a13, vec.sD());
EXPECT_EQ(a14, vec.sE());
EXPECT_EQ(a15, vec.sF());
TypeParam const b6 = 60;
sycldnn::helpers::vector_element::set(vec, 6, b6);
EXPECT_EQ(b0, vec.s0());
EXPECT_EQ(b1, vec.s1());
EXPECT_EQ(b2, vec.s2());
EXPECT_EQ(b3, vec.s3());
EXPECT_EQ(b4, vec.s4());
EXPECT_EQ(b5, vec.s5());
EXPECT_EQ(b6, vec.s6());
EXPECT_EQ(a7, vec.s7());
EXPECT_EQ(a8, vec.s8());
EXPECT_EQ(a9, vec.s9());
EXPECT_EQ(a10, vec.sA());
EXPECT_EQ(a11, vec.sB());
EXPECT_EQ(a12, vec.sC());
EXPECT_EQ(a13, vec.sD());
EXPECT_EQ(a14, vec.sE());
EXPECT_EQ(a15, vec.sF());
TypeParam const b7 = 70;
sycldnn::helpers::vector_element::set(vec, 7, b7);
EXPECT_EQ(b0, vec.s0());
EXPECT_EQ(b1, vec.s1());
EXPECT_EQ(b2, vec.s2());
EXPECT_EQ(b3, vec.s3());
EXPECT_EQ(b4, vec.s4());
EXPECT_EQ(b5, vec.s5());
EXPECT_EQ(b6, vec.s6());
EXPECT_EQ(b7, vec.s7());
EXPECT_EQ(a8, vec.s8());
EXPECT_EQ(a9, vec.s9());
EXPECT_EQ(a10, vec.sA());
EXPECT_EQ(a11, vec.sB());
EXPECT_EQ(a12, vec.sC());
EXPECT_EQ(a13, vec.sD());
EXPECT_EQ(a14, vec.sE());
EXPECT_EQ(a15, vec.sF());
TypeParam const b8 = 80;
sycldnn::helpers::vector_element::set(vec, 8, b8);
EXPECT_EQ(b0, vec.s0());
EXPECT_EQ(b1, vec.s1());
EXPECT_EQ(b2, vec.s2());
EXPECT_EQ(b3, vec.s3());
EXPECT_EQ(b4, vec.s4());
EXPECT_EQ(b5, vec.s5());
EXPECT_EQ(b6, vec.s6());
EXPECT_EQ(b7, vec.s7());
EXPECT_EQ(b8, vec.s8());
EXPECT_EQ(a9, vec.s9());
EXPECT_EQ(a10, vec.sA());
EXPECT_EQ(a11, vec.sB());
EXPECT_EQ(a12, vec.sC());
EXPECT_EQ(a13, vec.sD());
EXPECT_EQ(a14, vec.sE());
EXPECT_EQ(a15, vec.sF());
TypeParam const b9 = 90;
sycldnn::helpers::vector_element::set(vec, 9, b9);
EXPECT_EQ(b0, vec.s0());
EXPECT_EQ(b1, vec.s1());
EXPECT_EQ(b2, vec.s2());
EXPECT_EQ(b3, vec.s3());
EXPECT_EQ(b4, vec.s4());
EXPECT_EQ(b5, vec.s5());
EXPECT_EQ(b6, vec.s6());
EXPECT_EQ(b7, vec.s7());
EXPECT_EQ(b8, vec.s8());
EXPECT_EQ(b9, vec.s9());
EXPECT_EQ(a10, vec.sA());
EXPECT_EQ(a11, vec.sB());
EXPECT_EQ(a12, vec.sC());
EXPECT_EQ(a13, vec.sD());
EXPECT_EQ(a14, vec.sE());
EXPECT_EQ(a15, vec.sF());
TypeParam const b10 = 100;
sycldnn::helpers::vector_element::set(vec, 10, b10);
EXPECT_EQ(b0, vec.s0());
EXPECT_EQ(b1, vec.s1());
EXPECT_EQ(b2, vec.s2());
EXPECT_EQ(b3, vec.s3());
EXPECT_EQ(b4, vec.s4());
EXPECT_EQ(b5, vec.s5());
EXPECT_EQ(b6, vec.s6());
EXPECT_EQ(b7, vec.s7());
EXPECT_EQ(b8, vec.s8());
EXPECT_EQ(b9, vec.s9());
EXPECT_EQ(b10, vec.sA());
EXPECT_EQ(a11, vec.sB());
EXPECT_EQ(a12, vec.sC());
EXPECT_EQ(a13, vec.sD());
EXPECT_EQ(a14, vec.sE());
EXPECT_EQ(a15, vec.sF());
TypeParam const b11 = 110;
sycldnn::helpers::vector_element::set(vec, 11, b11);
EXPECT_EQ(b0, vec.s0());
EXPECT_EQ(b1, vec.s1());
EXPECT_EQ(b2, vec.s2());
EXPECT_EQ(b3, vec.s3());
EXPECT_EQ(b4, vec.s4());
EXPECT_EQ(b5, vec.s5());
EXPECT_EQ(b6, vec.s6());
EXPECT_EQ(b7, vec.s7());
EXPECT_EQ(b8, vec.s8());
EXPECT_EQ(b9, vec.s9());
EXPECT_EQ(b10, vec.sA());
EXPECT_EQ(b11, vec.sB());
EXPECT_EQ(a12, vec.sC());
EXPECT_EQ(a13, vec.sD());
EXPECT_EQ(a14, vec.sE());
EXPECT_EQ(a15, vec.sF());
TypeParam const b12 = 120;
sycldnn::helpers::vector_element::set(vec, 12, b12);
EXPECT_EQ(b0, vec.s0());
EXPECT_EQ(b1, vec.s1());
EXPECT_EQ(b2, vec.s2());
EXPECT_EQ(b3, vec.s3());
EXPECT_EQ(b4, vec.s4());
EXPECT_EQ(b5, vec.s5());
EXPECT_EQ(b6, vec.s6());
EXPECT_EQ(b7, vec.s7());
EXPECT_EQ(b8, vec.s8());
EXPECT_EQ(b9, vec.s9());
EXPECT_EQ(b10, vec.sA());
EXPECT_EQ(b11, vec.sB());
EXPECT_EQ(b12, vec.sC());
EXPECT_EQ(a13, vec.sD());
EXPECT_EQ(a14, vec.sE());
EXPECT_EQ(a15, vec.sF());
TypeParam const b13 = 130;
sycldnn::helpers::vector_element::set(vec, 13, b13);
EXPECT_EQ(b0, vec.s0());
EXPECT_EQ(b1, vec.s1());
EXPECT_EQ(b2, vec.s2());
EXPECT_EQ(b3, vec.s3());
EXPECT_EQ(b4, vec.s4());
EXPECT_EQ(b5, vec.s5());
EXPECT_EQ(b6, vec.s6());
EXPECT_EQ(b7, vec.s7());
EXPECT_EQ(b8, vec.s8());
EXPECT_EQ(b9, vec.s9());
EXPECT_EQ(b10, vec.sA());
EXPECT_EQ(b11, vec.sB());
EXPECT_EQ(b12, vec.sC());
EXPECT_EQ(b13, vec.sD());
EXPECT_EQ(a14, vec.sE());
EXPECT_EQ(a15, vec.sF());
TypeParam const b14 = 140;
sycldnn::helpers::vector_element::set(vec, 14, b14);
EXPECT_EQ(b0, vec.s0());
EXPECT_EQ(b1, vec.s1());
EXPECT_EQ(b2, vec.s2());
EXPECT_EQ(b3, vec.s3());
EXPECT_EQ(b4, vec.s4());
EXPECT_EQ(b5, vec.s5());
EXPECT_EQ(b6, vec.s6());
EXPECT_EQ(b7, vec.s7());
EXPECT_EQ(b8, vec.s8());
EXPECT_EQ(b9, vec.s9());
EXPECT_EQ(b10, vec.sA());
EXPECT_EQ(b11, vec.sB());
EXPECT_EQ(b12, vec.sC());
EXPECT_EQ(b13, vec.sD());
EXPECT_EQ(b14, vec.sE());
EXPECT_EQ(a15, vec.sF());
TypeParam const b15 = 150;
sycldnn::helpers::vector_element::set(vec, 15, b15);
EXPECT_EQ(b0, vec.s0());
EXPECT_EQ(b1, vec.s1());
EXPECT_EQ(b2, vec.s2());
EXPECT_EQ(b3, vec.s3());
EXPECT_EQ(b4, vec.s4());
EXPECT_EQ(b5, vec.s5());
EXPECT_EQ(b6, vec.s6());
EXPECT_EQ(b7, vec.s7());
EXPECT_EQ(b8, vec.s8());
EXPECT_EQ(b9, vec.s9());
EXPECT_EQ(b10, vec.sA());
EXPECT_EQ(b11, vec.sB());
EXPECT_EQ(b12, vec.sC());
EXPECT_EQ(b13, vec.sD());
EXPECT_EQ(b14, vec.sE());
EXPECT_EQ(b15, vec.sF());
}
| 28.085404 | 80 | 0.642008 | GeorgeWeb |
58cf2bd16dc965f1c4210914a4957cf70c23b1bd | 4,432 | cpp | C++ | libraries/CRC/test/unit_test_crc32.cpp | jantje/Arduino | cd40e51b4eb9f8947aa58f278f61c9121d711fb0 | [
"MIT"
] | 1,253 | 2015-01-03T17:07:53.000Z | 2022-03-22T11:46:42.000Z | libraries/CRC/test/unit_test_crc32.cpp | henriquerochamattos/Arduino | 3ace3a4e7b2b51d52d4c2ea363d23ebaacd9cc68 | [
"MIT"
] | 134 | 2015-01-21T20:33:13.000Z | 2022-01-05T08:59:33.000Z | libraries/CRC/test/unit_test_crc32.cpp | henriquerochamattos/Arduino | 3ace3a4e7b2b51d52d4c2ea363d23ebaacd9cc68 | [
"MIT"
] | 3,705 | 2015-01-02T17:03:16.000Z | 2022-03-31T13:20:30.000Z | //
// FILE: unit_test_crc32.cpp
// AUTHOR: Rob Tillaart
// DATE: 2021-03-31
// PURPOSE: unit tests for the CRC library
// https://github.com/RobTillaart/CRC
// https://github.com/Arduino-CI/arduino_ci/blob/master/REFERENCE.md
//
// supported assertions
// ----------------------------
// assertEqual(expected, actual); // a == b
// assertNotEqual(unwanted, actual); // a != b
// assertComparativeEquivalent(expected, actual); // abs(a - b) == 0 or (!(a > b) && !(a < b))
// assertComparativeNotEquivalent(unwanted, actual); // abs(a - b) > 0 or ((a > b) || (a < b))
// assertLess(upperBound, actual); // a < b
// assertMore(lowerBound, actual); // a > b
// assertLessOrEqual(upperBound, actual); // a <= b
// assertMoreOrEqual(lowerBound, actual); // a >= b
// assertTrue(actual);
// assertFalse(actual);
// assertNull(actual);
// // special cases for floats
// assertEqualFloat(expected, actual, epsilon); // fabs(a - b) <= epsilon
// assertNotEqualFloat(unwanted, actual, epsilon); // fabs(a - b) >= epsilon
// assertInfinity(actual); // isinf(a)
// assertNotInfinity(actual); // !isinf(a)
// assertNAN(arg); // isnan(a)
// assertNotNAN(arg); // !isnan(a)
#include <ArduinoUnitTests.h>
#include "Arduino.h"
#include "CRC32.h"
char str[24] = "123456789";
uint8_t * data = (uint8_t *) str;
unittest_setup()
{
}
unittest_teardown()
{
}
unittest(test_crc32)
{
fprintf(stderr, "TEST CRC32\n");
CRC32 crc;
crc.setPolynome(0x04C11DB7);
crc.setStartXOR(0xFFFFFFFF);
crc.setEndXOR(0xFFFFFFFF);
crc.setReverseIn(true);
crc.setReverseOut(true);
crc.add(data, 9);
assertEqual(0xCBF43926, crc.getCRC());
crc.reset();
crc.setPolynome(0x04C11DB7);
crc.setStartXOR(0xFFFFFFFF);
crc.setEndXOR(0xFFFFFFFF);
crc.add(data, 9);
assertEqual(0xFC891918, crc.getCRC());
crc.reset();
crc.setPolynome(0x1EDC6F41);
crc.setStartXOR(0xFFFFFFFF);
crc.setEndXOR(0xFFFFFFFF);
crc.setReverseIn(true);
crc.setReverseOut(true);
crc.add(data, 9);
assertEqual(0xE3069283, crc.getCRC());
crc.reset();
crc.setPolynome(0xA833982B);
crc.setStartXOR(0xFFFFFFFF);
crc.setEndXOR(0xFFFFFFFF);
crc.setReverseIn(true);
crc.setReverseOut(true);
crc.add(data, 9);
assertEqual(0x87315576, crc.getCRC());
crc.reset();
crc.setPolynome(0x04C11DB7);
crc.setStartXOR(0xFFFFFFFF);
crc.setEndXOR(0x00000000);
crc.setReverseIn(false);
crc.setReverseOut(false);
crc.add(data, 9);
assertEqual(0x0376E6E7, crc.getCRC());
crc.reset();
crc.setPolynome(0x04C11DB7);
crc.setStartXOR(0x00000000);
crc.setEndXOR(0xFFFFFFFF);
crc.setReverseIn(false);
crc.setReverseOut(false);
crc.add(data, 9);
assertEqual(0x765E7680, crc.getCRC());
crc.reset();
crc.setPolynome(0x814141AB);
crc.setStartXOR(0x00000000);
crc.setEndXOR(0x00000000);
crc.setReverseIn(false);
crc.setReverseOut(false);
crc.add(data, 9);
assertEqual(0x3010BF7F, crc.getCRC());
crc.reset();
crc.setPolynome(0x04C11DB7);
crc.setStartXOR(0xFFFFFFFF);
crc.setEndXOR(0x00000000);
crc.setReverseIn(true);
crc.setReverseOut(true);
crc.add(data, 9);
assertEqual(0x340BC6D9, crc.getCRC());
crc.reset();
crc.setPolynome(0x000000AF);
crc.setStartXOR(0x00000000);
crc.setEndXOR(0x00000000);
crc.setReverseIn(false);
crc.setReverseOut(false);
crc.add(data, 9);
assertEqual(0xBD0BE338, crc.getCRC());
/*
// DONE
assertEqual(0xCBF43926, crc32(data, 9, 0x04C11DB7, 0xFFFFFFFF, 0xFFFFFFFF, true, true));
assertEqual(0xFC891918, crc32(data, 9, 0x04C11DB7, 0xFFFFFFFF, 0xFFFFFFFF, false, false));
assertEqual(0xE3069283, crc32(data, 9, 0x1EDC6F41, 0xFFFFFFFF, 0xFFFFFFFF, true, true));
assertEqual(0x87315576, crc32(data, 9, 0xA833982B, 0xFFFFFFFF, 0xFFFFFFFF, true, true));
assertEqual(0x0376E6E7, crc32(data, 9, 0x04C11DB7, 0xFFFFFFFF, 0x00000000, false, false));
assertEqual(0x765E7680, crc32(data, 9, 0x04C11DB7, 0x00000000, 0xFFFFFFFF, false, false));
assertEqual(0x3010BF7F, crc32(data, 9, 0x814141AB, 0x00000000, 0x00000000, false, false));
assertEqual(0x340BC6D9, crc32(data, 9, 0x04C11DB7, 0xFFFFFFFF, 0x00000000, true, true));
assertEqual(0xBD0BE338, crc32(data, 9, 0x000000AF, 0x00000000, 0x00000000, false, false));
*/
}
unittest_main()
// --------
| 28.779221 | 97 | 0.664486 | jantje |
58d33bf3fdb8ba76a35b1ccdd46e058876393bec | 248 | hpp | C++ | test/test_mpi.hpp | mirandaconrado/object-archive | e3f43ac8aac86293f642b1a85a6892904ea3714b | [
"MIT"
] | 1 | 2019-12-10T11:38:49.000Z | 2019-12-10T11:38:49.000Z | test/test_mpi.hpp | mirandaconrado/object-archive | e3f43ac8aac86293f642b1a85a6892904ea3714b | [
"MIT"
] | null | null | null | test/test_mpi.hpp | mirandaconrado/object-archive | e3f43ac8aac86293f642b1a85a6892904ea3714b | [
"MIT"
] | null | null | null | #ifndef __TASK_DISTRIBUTION__TEST_MPI_HPP__
#define __TASK_DISTRIBUTION__TEST_MPI_HPP__
#include <boost/mpi/environment.hpp>
#include <boost/mpi/communicator.hpp>
extern boost::mpi::environment env;
extern boost::mpi::communicator world;
#endif
| 22.545455 | 43 | 0.826613 | mirandaconrado |
58d4885be4e47bbfc155f2e61d97b3c1a306fce9 | 573 | cpp | C++ | 156.cpp | R-penguins/UVa-Online-Judge-Solutions | 4bb24ab26c207903ff5b6fea6cfe122ae6578d62 | [
"MIT"
] | null | null | null | 156.cpp | R-penguins/UVa-Online-Judge-Solutions | 4bb24ab26c207903ff5b6fea6cfe122ae6578d62 | [
"MIT"
] | null | null | null | 156.cpp | R-penguins/UVa-Online-Judge-Solutions | 4bb24ab26c207903ff5b6fea6cfe122ae6578d62 | [
"MIT"
] | null | null | null | /**
* AOAPC II Example 5-4 Ananagrams
*/
#include <bits/stdc++.h>
using namespace std;
int main() {
map<string, string> trans;
string s;
while ((cin >> s) && s[0] != '#') {
string t = s;
for (char &c : t)
c = tolower(c);
sort(t.begin(), t.end());
if (trans.find(t) == trans.end())
trans[t] = s;
else
trans[t] = "";
}
set<string> ans;
for (auto p : trans)
if (p.second != "")
ans.insert(p.second);
for (string s : ans)
cout << s << "\n";
}
| 22.038462 | 41 | 0.4363 | R-penguins |
58d6497acc5d7e39331f6a73703c5a2565e01b8e | 66,002 | cxx | C++ | Modules/CLI/ModelMaker/ModelMaker.cxx | forfullstack/slicersources-src | 91bcecf037a27f3fad4c0ab57e8286fc258bb0f5 | [
"Apache-2.0"
] | null | null | null | Modules/CLI/ModelMaker/ModelMaker.cxx | forfullstack/slicersources-src | 91bcecf037a27f3fad4c0ab57e8286fc258bb0f5 | [
"Apache-2.0"
] | null | null | null | Modules/CLI/ModelMaker/ModelMaker.cxx | forfullstack/slicersources-src | 91bcecf037a27f3fad4c0ab57e8286fc258bb0f5 | [
"Apache-2.0"
] | null | null | null | /*=auto=========================================================================
Portions (c) Copyright 2006 Brigham and Women's Hospital (BWH) All Rights Reserved.
See COPYRIGHT.txt
or http://www.slicer.org/copyright/copyright.txt for details.
Program: 3D Slicer
Module: $RCSfile$
Date: $Date$
Version: $Revision$
=========================================================================auto=*/
#include "ModelMakerCLP.h"
// Slicer includes
#include <vtkPluginFilterWatcher.h>
// MRML includes
#include "vtkMRMLColorTableNode.h"
#include "vtkMRMLColorTableStorageNode.h"
#include "vtkMRMLModelDisplayNode.h"
#include "vtkMRMLModelHierarchyNode.h"
#include "vtkMRMLModelNode.h"
#include "vtkMRMLModelStorageNode.h"
#include "vtkMRMLScene.h"
// vtkITK includes
#include "vtkITKArchetypeImageSeriesScalarReader.h"
// VTK includes
#include <vtkVersion.h> // must precede reference to VTK_MAJOR_VERSION
#include <vtkDebugLeaks.h>
#include <vtkDecimatePro.h>
#if VTK_MAJOR_VERSION >= 9 || (VTK_MAJOR_VERSION >= 8 && VTK_MINOR_VERSION >= 2)
#include <vtkDiscreteFlyingEdges3D.h>
#include <vtkFlyingEdges3D.h>
#else
#include <vtkDiscreteMarchingCubes.h>
#include <vtkMarchingCubes.h>
#endif
#include <vtkGeometryFilter.h>
#include <vtkImageAccumulate.h>
#include <vtkImageChangeInformation.h>
#include <vtkImageConstantPad.h>
#include <vtkImageData.h>
#include <vtkImageThreshold.h>
#include <vtkImageToStructuredPoints.h>
#include <vtkInformation.h>
#include <vtkLookupTable.h>
#include <vtkNew.h>
#include <vtkPointData.h>
#include <vtkPolyDataNormals.h>
#include <vtkPolyDataWriter.h>
#include <vtkReverseSense.h>
#include <vtkSmartPointer.h>
#include <vtkSmoothPolyDataFilter.h>
#include <vtkStreamingDemandDrivenPipeline.h>
#include <vtkStripper.h>
#include <vtkThreshold.h>
#include <vtkTransform.h>
#include <vtkTransformPolyDataFilter.h>
#include <vtkUnstructuredGrid.h>
#include <vtkWindowedSincPolyDataFilter.h>
// VTKsys includes
#include <vtksys/SystemTools.hxx>
int main(int argc, char * argv[])
{
PARSE_ARGS;
vtkDebugLeaks::SetExitError(true);
if (debug)
{
std::cout << "The input volume is: " << InputVolume << std::endl;
std::cout << "The labels are: " << std::endl;
for(::size_t l = 0; l < Labels.size(); l++)
{
std::cout << "\tList element " << l << " = " << Labels[l] << std::endl;
}
std::cout << "The starting label is: " << StartLabel << std::endl;
std::cout << "The ending label is: " << EndLabel << std::endl;
std::cout << "The model name is: " << Name << std::endl;
std::cout << "Do joint smoothing flag is: " << JointSmoothing << std::endl;
std::cout << "Generate all flag is: " << GenerateAll << std::endl;
std::cout << "Number of smoothing iterations: " << Smooth << std::endl;
std::cout << "Number of decimate iterations: " << Decimate << std::endl;
std::cout << "Split normals? " << SplitNormals << std::endl;
std::cout << "Calculate point normals? " << PointNormals << std::endl;
std::cout << "Pad? " << Pad << std::endl;
std::cout << "Filter type: " << FilterType << std::endl;
std::cout << "Input color hierarchy scene file: "
<< (ModelHierarchyFile.size() > 0 ? ModelHierarchyFile.c_str() : "None") << std::endl;
std::cout << "Output model scene file: "
<< (ModelSceneFile.size() > 0 ? ModelSceneFile[0].c_str() : "None") << std::endl;
std::cout << "Color table file : " << ColorTable.c_str() << std::endl;
std::cout << "Save intermediate models: " << SaveIntermediateModels << std::endl;
std::cout << "Debug: " << debug << std::endl;
std::cout << "\nStarting..." << std::endl;
}
// get the model hierarchy id from the scene file
std::string::size_type loc;
std::string sceneFilename;
std::string modelHierarchyID;
if (InputVolume.size() == 0)
{
std::cerr << "ERROR: no input volume defined!" << endl;
return EXIT_FAILURE;
}
if (ModelSceneFile.size() == 0)
{
// make one up from the input volume's name
sceneFilename = vtksys::SystemTools::GetFilenameWithoutExtension(InputVolume) + std::string(".mrml");
std::cerr << "********\nERROR: no model scene defined! Using " << sceneFilename << endl;
std::cerr
<<
"WARNING: If you started Model Maker from the Slicer3 GUI, the models will NOT be loaded automatically.\nYou must use File->Import Scene "
<< sceneFilename << " to see your models (don't use Load or it will close your current scene).\n*****" << std::endl;
}
else
{
loc = ModelSceneFile[0].find_last_of("#");
if (loc != std::string::npos)
{
sceneFilename = std::string(ModelSceneFile[0].begin(),
ModelSceneFile[0].begin() + loc);
loc++;
modelHierarchyID = std::string(ModelSceneFile[0].begin() + loc, ModelSceneFile[0].end());
}
else
{
// the passed in file is missing a model hierarchy node, work around it
sceneFilename = ModelSceneFile[0];
}
}
if (debug)
{
std::cout << "Models file: " << sceneFilename << std::endl;
std::cout << "Model Hierarchy ID: " << modelHierarchyID << std::endl;
}
// check for the model mrml file
if (sceneFilename == "")
{
std::cout << "No file to store models!" << std::endl;
return EXIT_FAILURE;
}
// get the directory of the scene file
std::string rootDir
= vtksys::SystemTools::GetParentDirectory(sceneFilename.c_str());
vtkNew<vtkMRMLScene> modelScene;
// load the scene that Slicer will re-read
modelScene->SetURL(sceneFilename.c_str());
// only try importing if the scene file exists
if (vtksys::SystemTools::FileExists(sceneFilename.c_str()))
{
modelScene->Import();
if (debug)
{
std::cout << "Imported model scene file " << sceneFilename.c_str() << std::endl;
}
}
else
{
std::cerr << "Model scene file doesn't exist yet: " << sceneFilename.c_str() << std::endl;
}
// make sure we have a model hierarchy node
vtkMRMLNode * rnd = modelScene->GetNodeByID(modelHierarchyID);
vtkSmartPointer<vtkMRMLModelHierarchyNode> rtnd;
if (!rnd)
{
std::cerr << "Error: no model hierarchy node at ID \""
<< modelHierarchyID << "\", creating one" << std::endl;
// return EXIT_FAILURE;
rtnd = vtkSmartPointer<vtkMRMLModelHierarchyNode>::New();
rtnd->SetHideFromEditors(0);
modelScene->AddNode(rtnd);
// now get it again as a mrml node so can add things under it
rnd = modelScene->GetNodeByID(rtnd->GetID());
}
else
{
if (debug)
{
std::cout << "Got model hierarchy node " << rnd->GetID() << std::endl;
}
rtnd = vtkMRMLModelHierarchyNode::SafeDownCast(rnd);
}
// if there's a color based model hierarchy file, import it into the model scene
vtkMRMLModelHierarchyNode *topColorHierarchyNode = nullptr;
if (ModelHierarchyFile.length() > 0)
{
// only try importing if the scene file exists
if (vtksys::SystemTools::FileExists(ModelHierarchyFile.c_str()))
{
modelScene->SetURL(ModelHierarchyFile.c_str());
modelScene->Import();
// reset to the default file name
modelScene->SetURL(sceneFilename.c_str());
// and root directory
modelScene->SetRootDirectory(rootDir.c_str());
if (debug)
{
std::cout << "Imported model hierarchy scene file " << ModelHierarchyFile.c_str() << std::endl;
}
}
else
{
std::cerr << "Model hierarchy scene file doesn't exist, using a flat hieararchy" << std::endl;
}
// make sure we have a new model hierarchy node
vtkMRMLNode * mnode = modelScene->GetNthNodeByClass(1,"vtkMRMLModelHierarchyNode");
if (mnode != nullptr)
{
topColorHierarchyNode = vtkMRMLModelHierarchyNode::SafeDownCast(mnode);
}
if (!topColorHierarchyNode)
{
std::cerr << "Model hierarchy scene file failed to import a model hierarchy node" << std::endl;
}
else
{
if (debug)
{
std::cout << "Loaded a color based model hierarchy scene with top level node = " << topColorHierarchyNode->GetName() << ", id = " << topColorHierarchyNode->GetID() << std::endl;
}
}
}
// if have a color hierarchy node, make it a child of the passed in model hierarchy
if (topColorHierarchyNode != nullptr)
{
topColorHierarchyNode->SetParentNodeID(rtnd->GetID());
// there's also a chance that the parent node refs weren't reset when the top color hierarchy node was re-id'd
// go through all the hierarchy nodes that are right under the rtnd and reset them to be under the topColorHierarchyNode
std::vector< vtkMRMLHierarchyNode* > children = rtnd->GetChildrenNodes();
for (unsigned int i = 0; i < children.size(); i++)
{
// don't touch the top color hierarchy node since you don't want to reset it's parent to itself
if (strcmp(topColorHierarchyNode->GetID(), children[i]->GetID()) != 0)
{
children[i]->SetParentNodeID(topColorHierarchyNode->GetID());
if (debug)
{
std::cout << "Reset child " << i << " " << children[i]->GetName() << " so parent is now " << children[i]->GetParentNodeID() << std::endl;
}
}
}
}
vtkSmartPointer<vtkMRMLColorTableNode> colorNode;
vtkSmartPointer<vtkMRMLColorTableStorageNode> colorStorageNode;
int useColorNode = 0;
if (ColorTable != "")
{
useColorNode = 1;
}
// vtk and helper variables
vtkSmartPointer<vtkITKArchetypeImageSeriesReader> reader;
vtkImageData * image;
#if VTK_MAJOR_VERSION >= 9 || (VTK_MAJOR_VERSION >= 8 && VTK_MINOR_VERSION >= 2)
vtkSmartPointer<vtkDiscreteFlyingEdges3D> cubes;
#else
vtkSmartPointer<vtkDiscreteMarchingCubes> cubes;
#endif
vtkSmartPointer<vtkWindowedSincPolyDataFilter> smoother;
bool makeMultiple = false;
bool useStartEnd = false;
vtkSmartPointer<vtkImageAccumulate> hist;
std::vector<int> skippedModels;
std::vector<int> madeModels;
vtkSmartPointer<vtkWindowedSincPolyDataFilter> smootherSinc;
vtkSmartPointer<vtkSmoothPolyDataFilter> smootherPoly;
vtkSmartPointer<vtkImageConstantPad> padder;
vtkSmartPointer<vtkDecimatePro> decimator;
#if VTK_MAJOR_VERSION >= 9 || (VTK_MAJOR_VERSION >= 8 && VTK_MINOR_VERSION >= 2)
vtkSmartPointer<vtkFlyingEdges3D> mcubes;
#else
vtkSmartPointer<vtkMarchingCubes> mcubes;
#endif
vtkSmartPointer<vtkImageThreshold> imageThreshold;
vtkSmartPointer<vtkThreshold> threshold;
vtkSmartPointer<vtkImageToStructuredPoints> imageToStructuredPoints;
vtkSmartPointer<vtkGeometryFilter> geometryFilter;
vtkSmartPointer<vtkTransform> transformIJKtoLPS;
vtkSmartPointer<vtkReverseSense> reverser;
vtkSmartPointer<vtkTransformPolyDataFilter> transformer;
vtkSmartPointer<vtkPolyDataNormals> normals;
vtkSmartPointer<vtkStripper> stripper;
vtkSmartPointer<vtkPolyDataWriter> writer;
const char modelFileHeader[] = "3D Slicer output. SPACE=LPS"; // models are saved in LPS coordinate system
// keep track of number of models that will be generated, for filter
// watcher reporting
float numModelsToGenerate = 1.0;
float numSingletonFilterSteps;
float numRepeatedFilterSteps;
float numFilterSteps;
// increment after each filter is run
float currentFilterOffset = 0.0;
// if using the labels vector, get out the min/max
int labelsMin = 0, labelsMax = 0;
// figure out if we're making multiple models
if (GenerateAll)
{
makeMultiple = true;
if (debug)
{
std::cout << "GenerateAll! set make mult to true" << std::endl;
}
}
else if (Labels.size() > 0)
{
if (Labels.size() == 1)
{
// special case, only making one
labelsMin = Labels[0];
labelsMax = Labels[0];
}
else
{
makeMultiple = true;
// sort the vector
std::sort(Labels.begin(), Labels.end());
labelsMin = Labels[0];
labelsMax = Labels[Labels.size() - 1];
if (debug)
{
cout << "Set labels min to " << labelsMin << ", labels max = " << labelsMax << ", labels vector size = "
<< Labels.size() << endl;
}
}
}
else if (EndLabel >= StartLabel && (EndLabel != -1 && StartLabel != -1))
{
// only say we're making multiple if they're not the same
if (EndLabel > StartLabel)
{
makeMultiple = true;
}
useStartEnd = true;
}
if (makeMultiple)
{
numSingletonFilterSteps = 4;
if (JointSmoothing)
{
numRepeatedFilterSteps = 7;
}
else
{
numRepeatedFilterSteps = 9;
}
if (useStartEnd)
{
numModelsToGenerate = EndLabel - StartLabel + 1;
}
else
{
if (GenerateAll)
{
// this will be calculated later from the histogram output
}
else
{
numModelsToGenerate = Labels.size();
}
}
}
else
{
numSingletonFilterSteps = 1;
numRepeatedFilterSteps = 9;
}
numFilterSteps = numSingletonFilterSteps + (numRepeatedFilterSteps * numModelsToGenerate);
if (SaveIntermediateModels)
{
if (JointSmoothing)
{
numFilterSteps += numModelsToGenerate;
}
else
{
numFilterSteps += 3 * numModelsToGenerate;
}
}
if (debug)
{
std::cout << "useStartEnd = " << useStartEnd << ", numModelsToGenerate = " << numModelsToGenerate
<< ", numFilterSteps " << numFilterSteps << endl;
}
// check for the input file
// - strings that start with slicer: are shared memory references, so they won't exist.
// The memory address starts with 0x in linux but not on Windows
if (InputVolume.find(std::string("slicer:")) != 0)
{
FILE * infile;
infile = fopen(InputVolume.c_str(), "r");
if (infile == nullptr)
{
std::cerr << "ERROR: cannot open input volume file " << InputVolume << endl;
return EXIT_FAILURE;
}
fclose(infile);
}
// Read the file
reader = vtkSmartPointer<vtkITKArchetypeImageSeriesScalarReader>::New();
std::string comment = "Read Volume";
vtkPluginFilterWatcher watchReader(reader,
comment.c_str(),
CLPProcessInformation,
1.0 / numFilterSteps, currentFilterOffset / numFilterSteps);
if (debug)
{
watchReader.QuietOn();
}
currentFilterOffset++;
reader->SetArchetype(InputVolume.c_str());
reader->SetOutputScalarTypeToNative();
reader->SetDesiredCoordinateOrientationToNative();
reader->SetUseNativeOriginOn();
reader->Update();
vtkNew<vtkImageChangeInformation> ici;
ici->SetInputConnection(reader->GetOutputPort());
ici->SetOutputSpacing(1, 1, 1);
ici->SetOutputOrigin(0, 0, 0);
ici->Update();
image = ici->GetOutput();
ici->Update();
// add padding if flag is set
if (Pad)
{
std::cout << "Adding 1 pixel padding around the image, shifting origin." << std::endl;
if (padder)
{
padder->SetInputData(nullptr);
padder = nullptr;
}
padder = vtkSmartPointer<vtkImageConstantPad>::New();
vtkNew<vtkImageChangeInformation> translator;
translator->SetInputData(image);
// translate the extent by 1 pixel
translator->SetExtentTranslation(1, 1, 1);
// args are: -padx*xspacing, -pady*yspacing, -padz*zspacing
// but padding and spacing are both 1
translator->SetOriginTranslation(-1.0, -1.0, -1.0);
padder->SetInputConnection(translator->GetOutputPort());
padder->SetConstant(0);
translator->Update();
int extent[6];
ici->GetOutputInformation(0)->Get(
vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), extent);
// now set the output extent to the new size, padded by 2 on the
// positive side
padder->SetOutputWholeExtent(extent[0], extent[1] + 2,
extent[2], extent[3] + 2,
extent[4], extent[5] + 2);
}
if (useColorNode)
{
colorNode = vtkSmartPointer<vtkMRMLColorTableNode>::New();
modelScene->AddNode(colorNode);
// read the colour file
if (debug)
{
std::cout << "Colour table file name = " << ColorTable.c_str() << std::endl;
}
colorStorageNode = vtkSmartPointer<vtkMRMLColorTableStorageNode>::New();
colorStorageNode->SetFileName(ColorTable.c_str());
modelScene->AddNode(colorStorageNode);
if (debug)
{
std::cout << "Setting the colour node's storage node id to " << colorStorageNode->GetID()
<< ", it's file name = " << colorStorageNode->GetFileName() << std::endl;
}
colorNode->SetAndObserveStorageNodeID(colorStorageNode->GetID());
if (!colorStorageNode->ReadData(colorNode))
{
std::cerr << "Error reading colour file " << colorStorageNode->GetFileName() << endl;
return EXIT_FAILURE;
}
else
{
if (debug)
{
std::cout << "Read colour file " << colorStorageNode->GetFileName() << endl;
}
}
colorStorageNode = nullptr;
}
// each hierarchy node needs a display node
vtkNew<vtkMRMLModelDisplayNode> dnd;
dnd->SetVisibility(1);
modelScene->AddNode(dnd.GetPointer());
rtnd->SetAndObserveDisplayNodeID(dnd->GetID());
// If making multiple models, figure out which labels have voxels
if (makeMultiple)
{
hist = vtkSmartPointer<vtkImageAccumulate>::New();
hist->SetInputData(image);
// need to figure out how many bins
int extentMax = 0;
if (useColorNode)
{
// get the max integer that the colour node can map
extentMax = colorNode->GetNumberOfColors() - 1;
if (debug)
{
std::cout << "Using color node to get max label" << endl;
}
}
else
{
// use the full range of the scalar type
double dImageScalarMax = image->GetScalarTypeMax();
if (debug)
{
std::cout << "Image scalar max as double = " << dImageScalarMax << endl;
}
extentMax = (int)(floor(dImageScalarMax - 1.0));
int biggestBin = 1000000; // VTK_INT_MAX - 1;
if (extentMax < 0 || extentMax > biggestBin)
{
std::cout << "\nWARNING: due to lack of color label information and an image with a scalar maximum of "
<< dImageScalarMax << ", using " << biggestBin << " as the histogram number of bins" << endl;
extentMax = biggestBin;
}
else
{
std::cout
<<
"\nWARNING: due to lack of color label information, using the full scalar range of the input image when calculating the histogram over the image: "
<< extentMax << endl;
}
}
if (debug)
{
std::cout << "Setting histogram extentMax = " << extentMax << endl;
}
// hist->SetComponentExtent(0, 1023, 0, 0, 0, 0);
hist->SetComponentExtent(0, extentMax, 0, 0, 0, 0);
hist->SetComponentOrigin(0, 0, 0);
hist->SetComponentSpacing(1, 1, 1);
// try and update and get the min/max here, as need them for the
// marching cubes
comment = "Histogram All Models";
vtkPluginFilterWatcher watchImageAccumulate(hist,
comment.c_str(),
CLPProcessInformation,
1.0 / numFilterSteps,
currentFilterOffset / numFilterSteps);
currentFilterOffset += 1.0;
if (debug)
{
watchImageAccumulate.QuietOn();
}
hist->Update();
double *max = hist->GetMax();
double *min = hist->GetMin();
if (min[0] == 0)
{
if (debug)
{
std::cout << "Skipping 0" << endl;
}
min[0]++;
}
if (min[0] < 0)
{
if (debug)
{
std::cout << "Histogram min was less than zero: " << min[0] << ", resetting to 1\n";
}
min[0] = 1;
}
if (debug)
{
std::cout << "Hist: Min = " << min[0] << " and max = " << max[0] << " (image scalar type = "
<< image->GetScalarType() << ", max = " << image->GetScalarTypeMax() << ")" << endl;
}
if (GenerateAll)
{
if (debug)
{
std::cout << "GenerateAll flag is true, resetting the start and end labels from: " << StartLabel << " and "
<< EndLabel << " to " << min[0] << " and " << max[0] << endl;
}
StartLabel = (int)floor(min[0]);
EndLabel = (int)floor(max[0]);
useStartEnd = true;
// recalculate the number of filter steps, discount the labels with no
// voxels
numModelsToGenerate = 0;
for(int i = StartLabel; i <= EndLabel; i++)
{
if ((int)floor((((hist->GetOutput())->GetPointData())->GetScalars())->GetTuple1(i)) > 0)
{
if (debug && i < 0 && i > -100)
{
std::cout << i << " ";
}
numModelsToGenerate++;
}
}
if (debug)
{
std::cout << endl << "GenerateAll: there are " << numModelsToGenerate << " models to be generated." << endl;
}
numFilterSteps = numSingletonFilterSteps + (numRepeatedFilterSteps * numModelsToGenerate);
if (SaveIntermediateModels)
{
if (JointSmoothing)
{
// save after decimation
numFilterSteps += 1 * numModelsToGenerate;
}
else
{
// if not doing joint smoothing, save after marching cubes and
// smoothing as well as decimation
numFilterSteps += 3 * numModelsToGenerate;
}
}
if (debug)
{
std::cout << "Reset numFilterSteps to " << numFilterSteps << endl;
}
}
if (cubes)
{
cubes->SetInputData(nullptr);
cubes = nullptr;
}
#if VTK_MAJOR_VERSION >= 9 || (VTK_MAJOR_VERSION >= 8 && VTK_MINOR_VERSION >= 2)
cubes = vtkSmartPointer<vtkDiscreteFlyingEdges3D>::New();
#else
cubes = vtkSmartPointer<vtkDiscreteMarchingCubes>::New();
#endif
std::string comment1 = "Discrete Marching Cubes";
vtkPluginFilterWatcher watchDMCubes(cubes,
comment1.c_str(),
CLPProcessInformation,
1.0 / numFilterSteps,
currentFilterOffset / numFilterSteps);
if (debug)
{
watchDMCubes.QuietOn();
}
currentFilterOffset += 1.0;
// add padding if flag is set
if (Pad)
{
cubes->SetInputConnection(padder->GetOutputPort());
}
else
{
cubes->SetInputData(image);
}
if (useStartEnd)
{
if (debug)
{
std::cout << "Marching cubes: Using end label = " << EndLabel << ", start label = " << StartLabel << endl;
}
cubes->GenerateValues((EndLabel - StartLabel + 1), StartLabel, EndLabel);
}
else
{
if (debug)
{
std::cout << "Marching cubes: Using max = " << labelsMax << ", min = " << labelsMin << endl;
}
cubes->GenerateValues((labelsMax - labelsMin + 1), labelsMin, labelsMax);
}
try
{
cubes->Update();
}
catch(...)
{
std::cerr << "ERROR while updating marching cubes filter." << std::endl;
return EXIT_FAILURE;
}
if (JointSmoothing)
{
float passBand = 0.001;
if (smoother)
{
smoother->SetInputData(nullptr);
smoother = nullptr;
}
smoother = vtkSmartPointer<vtkWindowedSincPolyDataFilter>::New();
std::stringstream stream;
stream << "Joint Smooth All Models (";
stream << numModelsToGenerate;
stream << " to process)";
std::string comment2 = stream.str();
vtkPluginFilterWatcher watchSmoother(smoother,
comment2.c_str(),
CLPProcessInformation,
1.0 / numFilterSteps,
currentFilterOffset / numFilterSteps);
currentFilterOffset += 1.0;
if (debug)
{
watchSmoother.QuietOn();
}
cubes->ReleaseDataFlagOn();
smoother->SetInputConnection(cubes->GetOutputPort());
smoother->SetNumberOfIterations(Smooth);
smoother->BoundarySmoothingOff();
smoother->FeatureEdgeSmoothingOff();
smoother->SetFeatureAngle(120.0l);
smoother->SetPassBand(passBand);
smoother->NonManifoldSmoothingOn();
smoother->NormalizeCoordinatesOn();
try
{
smoother->Update();
}
catch(...)
{
std::cerr << "ERROR while updating smoothing filter." << std::endl;
return EXIT_FAILURE;
}
// smoother->ReleaseDataFlagOn();
}
/*
vtkPluginFilterWatcher watchImageAccumulate(hist,
"Histogram All Models",
CLPProcessInformation,
1.0/numFilterSteps,
currentFilterOffset/numFilterSteps);
currentFilterOffset += 1.0;
if (debug)
{
watchImageAccumulate.QuietOn();
}
hist->Update();
double *max = hist->GetMax();
double *min = hist->GetMin();
if (min[0] == 0)
{
if (debug)
{
std::cout << "Skipping 0" << endl;
}
min[0]++;
}
if (debug)
{
std::cout << "Min = " << min[0] << " and max = " << max[0] << endl;
}
if (GenerateAll)
{
if (debug)
{
std::cout << "GenerateAll flag is true, resetting the start and end labels from: " << StartLabel << " and " << EndLabel << " to " << min[0] << " and " << max[0] << endl;
}
StartLabel = (int)floor(min[0]);
EndLabel = (int)floor(max[0]);
// recalculate the number of filter steps, discount the labels with no
// voxels
numModelsToGenerate = 0;
for (int i = StartLabel; i <= EndLabel; i++)
{
if((int)floor((((hist->GetOutput())->GetPointData())->GetScalars())->GetTuple1(i)) > 0)
{
if (debug && i < 0 && i > -100) { std::cout << i << " "; }
numModelsToGenerate++;
}
}
if (debug)
{
std::cout << endl << "GenerateAll: there are " << numModelsToGenerate << " models to be generated." << endl;
}
numFilterSteps = numSingletonFilterSteps + (numRepeatedFilterSteps * numModelsToGenerate);
}
*/
if (useColorNode)
{
// but if we didn't get a named color node, try to guess
if (colorNode == nullptr)
{
std::cerr << "ERROR: must have a color node! Should be associated with the input label map volume.\n";
return EXIT_FAILURE;
}
}
} // end of make multiple
else
{
if (useStartEnd)
{
EndLabel = StartLabel;
}
}
// ModelMakerMarch
double labelFrequency = 0.0;;
std::string labelName;
// get the dimensions, marching cubes only works on 3d
int extents[6];
image->GetExtent(extents);
if (debug)
{
std::cout << "Image data extents: " << extents[0] << " " << extents[1] << " " << extents[2] << " " << extents[3]
<< " " << extents[4] << " " << extents[5] << endl;
}
if (extents[0] == extents[1] ||
extents[2] == extents[3] ||
extents[4] == extents[5])
{
std::cerr << "The volume is not 3D." << endl;
std::cerr << "\tImage data extents: " << extents[0] << " " << extents[1] << " " << extents[2] << " "
<< extents[3] << " " << extents[4] << " " << extents[5] << endl;
return EXIT_FAILURE;
}
// Get the RAS to IJK matrix and invert it and flip the first to axis directions to get the IJK to LPS which will need
// to be applied to the model as it will be built in pixel space
if (transformIJKtoLPS)
{
transformIJKtoLPS->SetInput(nullptr);
transformIJKtoLPS = nullptr;
}
transformIJKtoLPS = vtkSmartPointer<vtkTransform>::New();
vtkNew<vtkMatrix4x4> ijkToRasMatrix;
vtkMatrix4x4::Invert(reader->GetRasToIjkMatrix(), ijkToRasMatrix);
transformIJKtoLPS->Scale(-1.0, -1.0, 1.0); // RAS to LPS
transformIJKtoLPS->Concatenate(ijkToRasMatrix);
//
// Loop through all the labels
//
std::vector<int> loopLabels;
if (useStartEnd || GenerateAll)
{
// set up the loop list with all the labels between start and end
for(int i = StartLabel; i <= EndLabel; i++)
{
loopLabels.push_back(i);
}
}
else
{
// just copy the list of labels into the new var
for(::size_t i = 0; i < Labels.size(); i++)
{
loopLabels.push_back(Labels[i]);
}
}
for(::size_t l = 0; l < loopLabels.size(); l++)
{
// get the label out of the vector
int i = loopLabels[l];
if (makeMultiple)
{
labelFrequency = (((hist->GetOutput())->GetPointData())->GetScalars())->GetTuple1(i);
if (debug)
{
if (labelFrequency > 0.0)
{
std::cout << "Label " << i << " has " << labelFrequency << " voxels." << endl;
}
}
if (labelFrequency == 0.0)
{
skippedModels.push_back(i);
continue;
}
else
{
madeModels.push_back(i);
}
// name this model
// TODO: get the label name from the colour look up table
std::stringstream stream;
stream << i;
std::string stringI = stream.str();
if (colorNode != nullptr)
{
std::string colorName = std::string(colorNode->GetColorNameAsFileName(i));
if (colorName.c_str() != nullptr)
{
if (!SkipUnNamed ||
(SkipUnNamed && (colorName.compare("invalid") != 0 && colorName.compare("(none)") != 0)))
{
labelName = Name + std::string("_") + stringI + std::string("_") + colorName;
if (debug)
{
std::cout << "Got color name, set label name = " << labelName.c_str() << " (color name w/o spaces = "
<< colorName.c_str() << ")" << endl;
}
}
else
{
if (debug)
{
std::cout << "Invalid colour name for " << stringI.c_str() << " = " << colorName.c_str()
<< ", skipping.\n";
}
skippedModels.push_back(i);
madeModels.pop_back();
continue;
}
}
else
{
if (SkipUnNamed)
{
if (debug)
{
std::cout << "Null color name for " << i << endl;
}
skippedModels.push_back(i);
madeModels.pop_back();
continue;
}
else
{
// colour is out of range
labelName = Name + std::string("_") + stringI;
}
}
}
else
{
if (!SkipUnNamed)
{
labelName = Name + std::string("_") + stringI;
}
else
{
continue;
}
}
} // end of making multiples
else
{
// just make one
labelName = Name;
/*
if (colorNode != nullptr)
{
if (colorNode->GetColorNameAsFileName(i).c_str() != nullptr)
{
std::stringstream stream;
stream << i;
std::string stringI = stream.str();
labelName = Name + std::string("_") + stringI + std::string("_") + std::string(colorNode->GetColorNameAsFileName(i));
}
}
else
{
labelName = Name;
}
*/
}
// threshold
if (JointSmoothing == 0)
{
if (imageThreshold)
{
imageThreshold->SetInputData(nullptr);
imageThreshold->RemoveAllInputs();
imageThreshold = nullptr;
}
imageThreshold = vtkSmartPointer<vtkImageThreshold>::New();
std::string comment3 = "Threshold " + labelName;
vtkPluginFilterWatcher watchImageThreshold(imageThreshold,
comment3.c_str(),
CLPProcessInformation,
1.0 / numFilterSteps,
currentFilterOffset / numFilterSteps);
currentFilterOffset += 1.0;
if (debug)
{
watchImageThreshold.QuietOn();
}
if (Pad)
{
imageThreshold->SetInputConnection(padder->GetOutputPort());
}
else
{
imageThreshold->SetInputData(image);
}
imageThreshold->SetReplaceIn(1);
imageThreshold->SetReplaceOut(1);
imageThreshold->SetInValue(200);
imageThreshold->SetOutValue(0);
imageThreshold->ThresholdBetween(i, i);
imageThreshold->ReleaseDataFlagOn();
if (imageToStructuredPoints)
{
imageToStructuredPoints->SetInputData(nullptr);
imageToStructuredPoints = nullptr;
}
imageToStructuredPoints = vtkSmartPointer<vtkImageToStructuredPoints>::New();
imageToStructuredPoints->SetInputConnection(imageThreshold->GetOutputPort());
try
{
imageToStructuredPoints->Update();
}
catch(...)
{
std::cerr << "ERROR while updating image to structured points for label " << i << std::endl;
return EXIT_FAILURE;
}
imageToStructuredPoints->ReleaseDataFlagOn();
}
else
{
// use the output of the smoother
if (threshold)
{
threshold->SetInputData(nullptr);
threshold = nullptr;
}
threshold = vtkSmartPointer<vtkThreshold>::New();
std::string comment4 = "Threshold " + labelName;
vtkPluginFilterWatcher watchThreshold(threshold,
comment4.c_str(),
CLPProcessInformation,
1.0 / numFilterSteps,
currentFilterOffset / numFilterSteps);
currentFilterOffset += 1.0;
if (debug)
{
watchThreshold.QuietOn();
}
if (smoother == nullptr)
{
std::cerr << "\nERROR smoothing filter is null for joint smoothing!" << std::endl;
return EXIT_FAILURE;
}
threshold->SetInputConnection(smoother->GetOutputPort());
// In VTK 5.0, this is deprecated - the default behaviour seems to
// be okay
// threshold->SetAttributeModeToUseCellData();
threshold->ThresholdBetween(i, i);
threshold->ReleaseDataFlagOn();
if (geometryFilter)
{
geometryFilter->SetInputData(nullptr);
geometryFilter = nullptr;
}
geometryFilter = vtkSmartPointer<vtkGeometryFilter>::New();
geometryFilter->SetInputConnection(threshold->GetOutputPort());
geometryFilter->ReleaseDataFlagOn();
}
// if not joint smoothing, may need to skip this label
int skipLabel = 0;
if (JointSmoothing == 0)
{
if (mcubes)
{
mcubes->SetInputData(nullptr);
mcubes = nullptr;
}
#if VTK_MAJOR_VERSION >= 9 || (VTK_MAJOR_VERSION >= 8 && VTK_MINOR_VERSION >= 2)
mcubes = vtkSmartPointer<vtkFlyingEdges3D>::New();
#else
mcubes = vtkSmartPointer<vtkMarchingCubes>::New();
#endif
std::string comment5 = "Marching Cubes " + labelName;
vtkPluginFilterWatcher watchThreshold(mcubes,
comment5.c_str(),
CLPProcessInformation,
1.0 / numFilterSteps,
currentFilterOffset / numFilterSteps);
currentFilterOffset += 1.0;
if (debug)
{
watchThreshold.QuietOn();
}
mcubes->SetInputConnection(imageToStructuredPoints->GetOutputPort());
mcubes->SetValue(0, 100.5);
mcubes->ComputeScalarsOff();
mcubes->ComputeGradientsOff();
mcubes->ComputeNormalsOff();
mcubes->ReleaseDataFlagOn();
try
{
mcubes->Update();
}
catch(...)
{
std::cerr << "ERROR while running marching cubes, for label " << i << std::endl;
return EXIT_FAILURE;
}
if (debug)
{
std::cout << "\nNumber of polygons = " << (mcubes->GetOutput())->GetNumberOfPolys() << endl;
}
if ((mcubes->GetOutput())->GetNumberOfPolys() == 0)
{
std::cout << "Cannot create a model from label " << i
<< "\nNo polygons can be created,\nthere may be no voxels with this label in the volume." << endl;
if (transformIJKtoLPS)
{
transformIJKtoLPS = nullptr;
}
if (imageThreshold)
{
if (debug)
{
std::cout << "Setting image threshold input to null" << endl;
}
imageThreshold->SetInputData(nullptr);
imageThreshold->RemoveAllInputs();
imageThreshold = nullptr;
}
if (imageToStructuredPoints)
{
imageToStructuredPoints->SetInputData(nullptr);
imageToStructuredPoints = nullptr;
}
if (mcubes)
{
mcubes->SetInputData(nullptr);
mcubes = nullptr;
}
skipLabel = 1;
std::cout << "...continuing" << endl;
continue;
}
if (SaveIntermediateModels)
{
writer = vtkSmartPointer<vtkPolyDataWriter>::New();
std::string commentSaveCubes = "Writing intermediate model after marching cubes " + labelName;
vtkPluginFilterWatcher watchWriter(writer,
commentSaveCubes.c_str(),
CLPProcessInformation,
1.0 / numFilterSteps,
currentFilterOffset / numFilterSteps);
currentFilterOffset += 1.0;
writer->SetInputConnection(cubes->GetOutputPort());
writer->SetHeader(modelFileHeader);
writer->SetFileType(2);
std::string fileName;
if (rootDir != "")
{
fileName = rootDir + std::string("/") + labelName + std::string("-MarchingCubes.vtk");
}
else
{
fileName = labelName + std::string("-MarchingCubes.vtk");
}
if (debug)
{
watchWriter.QuietOn();
std::cout << "Writing intermediate file " << fileName.c_str() << std::endl;
}
writer->SetFileName(fileName.c_str());
if (!writer->Write())
{
std::cerr << "ERROR: Failed to write intermediate file " << fileName.c_str() << std::endl;
}
writer->SetInputData(nullptr);
writer = nullptr;
}
}
else
{
std::cout << "Skipping marching cubes..." << endl;
}
if (!skipLabel)
{
// In switch from vtk 4 to vtk 5, vtkDecimate was deprecated from the Patented dir, use vtkDecimatePro
// TODO: look at vtkQuadraticDecimation
if (decimator != nullptr)
{
decimator->SetInputData(nullptr);
decimator = nullptr;
}
decimator = vtkSmartPointer<vtkDecimatePro>::New();
std::string comment6 = "Decimate " + labelName;
vtkPluginFilterWatcher watchImageThreshold(decimator,
comment6.c_str(),
CLPProcessInformation,
1.0 / numFilterSteps,
currentFilterOffset / numFilterSteps);
currentFilterOffset += 1.0;
if (debug)
{
watchImageThreshold.QuietOn();
}
if (JointSmoothing == 0)
{
decimator->SetInputConnection(mcubes->GetOutputPort());
}
else
{
decimator->SetInputConnection(geometryFilter->GetOutputPort());
}
decimator->SetFeatureAngle(60);
// decimator->SetMaximumIterations(Decimate);
// decimator->SetMaximumSubIterations(0);
// decimator->PreserveEdgesOn();
decimator->SplittingOff();
decimator->PreserveTopologyOn();
decimator->SetMaximumError(1);
decimator->SetTargetReduction(Decimate);
// decimator->SetInitialError(0.0002);
// decimator->SetErrorIncrement(0.002);
decimator->ReleaseDataFlagOff();
try
{
decimator->Update();
}
catch(...)
{
std::cerr << "ERROR decimating model " << i << std::endl;
return EXIT_FAILURE;
}
if (debug)
{
std::cout << "After decimation, number of polygons = " << (decimator->GetOutput())->GetNumberOfPolys() << endl;
}
if (SaveIntermediateModels)
{
writer = vtkSmartPointer<vtkPolyDataWriter>::New();
std::string commentSaveDecimation = "Writing intermediate model after decimation " + labelName;
vtkPluginFilterWatcher watchWriter(writer,
commentSaveDecimation.c_str(),
CLPProcessInformation,
1.0 / numFilterSteps,
currentFilterOffset / numFilterSteps);
currentFilterOffset += 1.0;
writer->SetInputConnection(decimator->GetOutputPort());
writer->SetHeader(modelFileHeader);
writer->SetFileType(2);
std::string fileName;
if (rootDir != "")
{
fileName = rootDir + std::string("/") + labelName + std::string("-Decimated.vtk");
}
else
{
fileName = labelName + std::string("-MarchingCubes.vtk");
}
if (debug)
{
watchWriter.QuietOn();
std::cout << "Writing intermediate file " << fileName.c_str() << std::endl;
}
writer->SetFileName(fileName.c_str());
if (!writer->Write())
{
std::cerr << "ERROR: Failed to write intermediate file " << fileName.c_str() << std::endl;
}
writer->SetInputData(nullptr);
writer = nullptr;
}
if (transformIJKtoLPS == nullptr ||
transformIJKtoLPS->GetMatrix() == nullptr)
{
std::cout << "transformIJKtoLPS is "
<< (transformIJKtoLPS ==
nullptr ? "null" : "okay") << ", it's matrix is "
<< (transformIJKtoLPS->GetMatrix() == nullptr ? "null" : "okay") << endl;
}
else if ((transformIJKtoLPS->GetMatrix())->Determinant() < 0)
{
if (debug)
{
std::cout << "Determinant " << (transformIJKtoLPS->GetMatrix())->Determinant()
<< " is less than zero, reversing..." << endl;
}
if (reverser)
{
reverser->SetInputData(nullptr);
reverser = nullptr;
}
reverser = vtkSmartPointer<vtkReverseSense>::New();
std::string comment7 = "Reverse " + labelName;
vtkPluginFilterWatcher watchReverser(reverser,
comment7.c_str(),
CLPProcessInformation,
1.0 / numFilterSteps,
currentFilterOffset / numFilterSteps);
currentFilterOffset += 1.0;
if (debug)
{
watchReverser.QuietOn();
}
reverser->SetInputConnection(decimator->GetOutputPort());
reverser->ReverseNormalsOn();
reverser->ReleaseDataFlagOn();
}
if (JointSmoothing == 0)
{
if (strcmp(FilterType.c_str(), "Sinc") == 0)
{
if (smootherSinc)
{
smootherSinc->SetInputData(nullptr);
smootherSinc = nullptr;
}
smootherSinc = vtkSmartPointer<vtkWindowedSincPolyDataFilter>::New();
std::string comment8 = "Smooth " + labelName;
vtkPluginFilterWatcher watchSmoother(smootherSinc,
comment8.c_str(),
CLPProcessInformation,
1.0 / numFilterSteps,
currentFilterOffset / numFilterSteps);
currentFilterOffset += 1.0;
if (debug)
{
watchSmoother.QuietOn();
}
smootherSinc->SetPassBand(0.1);
if (Smooth == 1)
{
std::cerr << "Warning: Smoothing iterations of 1 not allowed for Sinc filter, using 2" << endl;
Smooth = 2;
}
if ((transformIJKtoLPS->GetMatrix())->Determinant() < 0)
{
smootherSinc->SetInputConnection(reverser->GetOutputPort());
}
else
{
smootherSinc->SetInputConnection(decimator->GetOutputPort());
}
smootherSinc->SetNumberOfIterations(Smooth);
smootherSinc->FeatureEdgeSmoothingOff();
smootherSinc->BoundarySmoothingOff();
smootherSinc->ReleaseDataFlagOn();
try
{
smootherSinc->Update();
}
catch(...)
{
std::cerr << "ERROR updating Sinc smoother for model " << i << std::endl;
return EXIT_FAILURE;
}
}
else
{
if (smootherPoly)
{
smootherPoly->SetInputData(nullptr);
smootherPoly = nullptr;
}
smootherPoly = vtkSmartPointer<vtkSmoothPolyDataFilter>::New();
std::string comment9 = "Smooth " + labelName;
vtkPluginFilterWatcher watchSmoother(smootherPoly,
comment9.c_str(),
CLPProcessInformation,
1.0 / numFilterSteps,
currentFilterOffset / numFilterSteps);
currentFilterOffset += 1.0;
if (debug)
{
watchSmoother.QuietOn();
}
// this next line massively rounds corners
smootherPoly->SetRelaxationFactor(0.33);
smootherPoly->SetFeatureAngle(60);
smootherPoly->SetConvergence(0);
if ((transformIJKtoLPS->GetMatrix())->Determinant() < 0)
{
smootherPoly->SetInputConnection(reverser->GetOutputPort());
}
else
{
smootherPoly->SetInputConnection(decimator->GetOutputPort());
}
smootherPoly->SetNumberOfIterations(Smooth);
smootherPoly->FeatureEdgeSmoothingOff();
smootherPoly->BoundarySmoothingOff();
smootherPoly->ReleaseDataFlagOn();
try
{
smootherPoly->Update();
}
catch(...)
{
std::cerr << "ERROR updating Poly smoother for model " << i << std::endl;
return EXIT_FAILURE;
}
}
if (SaveIntermediateModels)
{
writer = vtkSmartPointer<vtkPolyDataWriter>::New();
std::string commentSaveSmoothed = "Writing intermediate model after smoothing " + labelName;
vtkPluginFilterWatcher watchWriter(writer,
commentSaveSmoothed.c_str(),
CLPProcessInformation,
1.0 / numFilterSteps,
currentFilterOffset / numFilterSteps);
currentFilterOffset += 1.0;
if (strcmp(FilterType.c_str(), "Sinc") == 0)
{
writer->SetInputConnection(smootherSinc->GetOutputPort());
}
else
{
writer->SetInputConnection(smootherPoly->GetOutputPort());
}
writer->SetHeader(modelFileHeader);
writer->SetFileType(2);
std::string fileName;
if (rootDir != "")
{
fileName = rootDir + std::string("/") + labelName + std::string("-Smoothed.vtk");
}
else
{
fileName = labelName + std::string("-Smoothed.vtk");
}
if (debug)
{
watchWriter.QuietOn();
std::cout << "Writing intermediate file " << fileName.c_str() << std::endl;
}
writer->SetFileName(fileName.c_str());
if (!writer->Write())
{
std::cerr << "ERROR: Failed to write intermediate file " << fileName.c_str() << std::endl;
}
writer->SetInputData(nullptr);
writer = nullptr;
}
}
if (transformer)
{
transformer->SetInputData(nullptr);
transformer = nullptr;
}
transformer = vtkSmartPointer<vtkTransformPolyDataFilter>::New();
std::string comment1 = "Transform " + labelName;
vtkPluginFilterWatcher watchTransformer(transformer,
comment1.c_str(),
CLPProcessInformation,
1.0 / numFilterSteps,
currentFilterOffset / numFilterSteps);
currentFilterOffset += 1.0;
if (debug)
{
watchTransformer.QuietOn();
}
if (JointSmoothing == 0)
{
if (strcmp(FilterType.c_str(), "Sinc") == 0)
{
transformer->SetInputConnection(smootherSinc->GetOutputPort());
}
else
{
transformer->SetInputConnection(smootherPoly->GetOutputPort());
}
}
else
{
if ((transformIJKtoLPS->GetMatrix())->Determinant() < 0)
{
transformer->SetInputConnection(reverser->GetOutputPort());
}
else
{
transformer->SetInputConnection(decimator->GetOutputPort());
}
}
transformer->SetTransform(transformIJKtoLPS);
if (debug)
{
// transformIJKtoLPS->GetMatrix()->Print(std::cout);
}
transformer->ReleaseDataFlagOn();
if (normals)
{
normals->SetInputData(nullptr);
normals = nullptr;
}
normals = vtkSmartPointer<vtkPolyDataNormals>::New();
std::string comment2 = "Normals " + labelName;
vtkPluginFilterWatcher watchNormals(normals,
comment2.c_str(),
CLPProcessInformation,
1.0 / numFilterSteps,
currentFilterOffset / numFilterSteps);
currentFilterOffset += 1.0;
if (debug)
{
watchNormals.QuietOn();
}
if (PointNormals)
{
normals->ComputePointNormalsOn();
}
else
{
normals->ComputePointNormalsOff();
}
normals->SetInputConnection(transformer->GetOutputPort());
normals->SetFeatureAngle(60);
normals->SetSplitting(SplitNormals);
normals->ReleaseDataFlagOn();
if (stripper)
{
stripper->SetInputData(nullptr);
stripper = nullptr;
}
stripper = vtkSmartPointer<vtkStripper>::New();
std::string comment3 = "Strip " + labelName;
vtkPluginFilterWatcher watchStripper(stripper,
comment3.c_str(),
CLPProcessInformation,
1.0 / numFilterSteps,
currentFilterOffset / numFilterSteps);
currentFilterOffset += 1.0;
if (debug)
{
watchStripper.QuietOn();
}
stripper->SetInputConnection(normals->GetOutputPort());
stripper->ReleaseDataFlagOff();
// the poly data output from the stripper can be set as an input to a
// model's polydata
try
{
stripper->Update();
}
catch(...)
{
std::cerr << "ERROR updating stripper for model " << i << std::endl;
return EXIT_FAILURE;
}
// but for now we're just going to write it out
writer = vtkSmartPointer<vtkPolyDataWriter>::New();
std::string comment4 = "Write " + labelName;
vtkPluginFilterWatcher watchWriter(writer,
comment4.c_str(),
CLPProcessInformation,
1.0 / numFilterSteps,
currentFilterOffset / numFilterSteps);
currentFilterOffset += 1.0;
if (debug)
{
watchWriter.QuietOn();
}
writer->SetInputConnection(stripper->GetOutputPort());
writer->SetHeader(modelFileHeader);
writer->SetFileType(2);
std::string fileName;
if (rootDir != "")
{
fileName = rootDir + std::string("/") + labelName + std::string(".vtk");
}
else
{
std::cout << "WARNING: output directory is an empty string..." << endl;
fileName = labelName + std::string(".vtk");
}
writer->SetFileName(fileName.c_str());
if (debug)
{
std::cout << "Writing model " << " " << labelName << " to file " << writer->GetFileName() << endl;
}
if (!writer->Write())
{
std::cerr << "ERROR: Failed to write model file " << fileName.c_str() << std::endl;
}
writer->SetInputData(nullptr);
writer = nullptr;
if (modelScene.GetPointer() != nullptr)
{
if (debug)
{
std::cout << "Adding model " << labelName << " to the output scene, with filename " << fileName.c_str()
<< endl;
}
// each model needs a mrml node, a storage node and a display node
vtkNew<vtkMRMLModelNode> mnode;
mnode->SetScene(modelScene.GetPointer());
mnode->SetName(labelName.c_str());
vtkNew<vtkMRMLModelStorageNode> snode;
snode->SetFileName(fileName.c_str());
if (modelScene->AddNode(snode.GetPointer()) == nullptr)
{
std::cerr << "ERROR: unable to add the storage node to the model scene" << endl;
}
vtkNew<vtkMRMLModelDisplayNode> dnode;
dnode->SetColor(0.5, 0.5, 0.5);
double *rgba;
if (colorNode != nullptr)
{
rgba = colorNode->GetLookupTable()->GetTableValue(i);
if (rgba != nullptr)
{
if (debug)
{
std::cout << "Got colour: " << rgba[0] << " " << rgba[1] << " " << rgba[2] << " " << rgba[3] << endl;
}
dnode->SetColor(rgba[0], rgba[1], rgba[2]);
}
else
{
std::cerr << "Couldn't get look up table value for " << i << ", display node colour is not set (grey)"
<< endl;
}
}
dnode->SetVisibility(1);
modelScene->AddNode(dnode.GetPointer());
if (debug)
{
std::cout << "Added display node: id = " << (dnode->GetID() == nullptr ? "(null)" : dnode->GetID()) << endl;
std::cout << "Setting model's storage node: id = "
<< (snode->GetID() == nullptr ? "(null)" : snode->GetID()) << endl;
}
mnode->SetAndObserveStorageNodeID(snode->GetID());
mnode->SetAndObserveDisplayNodeID(dnode->GetID());
modelScene->AddNode(mnode.GetPointer());
// put it in the hierarchy, either the flat one by default or
// try to find the matching color hierarchy node to make this an
// associated node
std::string colorName;
if (colorNode != nullptr)
{
colorName = std::string(colorNode->GetColorNameAsFileName(i));
}
else
{
// might be in a testing case where the hierarchy nodes are
// numbered (made from the generic colors)
std::stringstream ss;
ss << i;
colorName = ss.str();
if (debug)
{
std::cout << "No color node, guessing at color name being same as label number " << colorName.c_str() << std::endl;
}
}
vtkMRMLNode *mrmlNode = nullptr;
if (colorName.compare("") != 0)
{
mrmlNode = modelScene->GetFirstNodeByName(colorName.c_str());
}
// if there's no color hierarchy, or no color name or the mrml node
// named for the color isn't a model hierarchy node, use a flat hierarchy
if (topColorHierarchyNode == nullptr ||
colorName.compare("") == 0 ||
mrmlNode == nullptr ||
strcmp(mrmlNode->GetClassName(),"vtkMRMLModelHierarchyNode") != 0)
{
vtkNew<vtkMRMLModelHierarchyNode> mhnd;
mhnd->SetHideFromEditors(1);
modelScene->AddNode(mhnd.GetPointer());
mhnd->SetParentNodeID(rnd->GetID());
mhnd->SetModelNodeID(mnode->GetID());
}
else
{
// use the template color hierarchy
vtkMRMLModelHierarchyNode *colorHierarchyNode = vtkMRMLModelHierarchyNode::SafeDownCast(mrmlNode);
if (colorHierarchyNode)
{
colorHierarchyNode->SetAssociatedNodeID(mnode->GetID());
// and hide it so that it doesn't clutter up the tree
colorHierarchyNode->SetHideFromEditors(1);
if (debug)
{
std::cout << "Found a color hierarchy node with name " << colorHierarchyNode->GetName() << ", set it's associated node to this model id: " << mnode->GetID() << std::endl;
}
}
}
if (debug)
{
std::cout << "...done adding model to output scene" << endl;
}
}
} // end of skipping an empty label
} // end of loop over labels
if (debug)
{
std::cout << "End of looping over labels" << endl;
}
// Report what was done
if (madeModels.size() > 0)
{
std::cout << "Made models from labels:";
for(::size_t i = 0; i < madeModels.size(); i++)
{
std::cout << " " << madeModels[i];
}
std::cout << endl;
}
if (skippedModels.size() > 0)
{
std::cout << "Skipped making models from labels:";
for(::size_t i = 0; i < skippedModels.size(); i++)
{
std::cout << " " << skippedModels[i];
}
std::cout << endl;
}
if (sceneFilename != "")
{
if (debug)
{
std::cout << "Writing to model scene output file: " << sceneFilename.c_str();
std::cout << ", to url: " << modelScene->GetURL() << std::endl;
}
// take out the colour nodes first
if (colorStorageNode != nullptr)
{
modelScene->RemoveNode(colorStorageNode);
}
if (colorNode != nullptr)
{
modelScene->RemoveNode(colorNode);
}
// take out any extra hierarchy nodes and display nodes
if (topColorHierarchyNode != nullptr)
{
// get all the hierarchies under it, recursively
std::vector< vtkMRMLHierarchyNode* > allChildren;
topColorHierarchyNode->GetAllChildrenNodes(allChildren);
for (unsigned int i = 0; i < allChildren.size(); i++)
{
if (allChildren[i]->GetAssociatedNodeID() == nullptr &&
allChildren[i]->GetNumberOfChildrenNodes() == 0)
{
// if this child doesn't have an associated node, nor does it have children nodes (keep the structure of the hierarchy), remove it and it's display node
if (debug)
{
std::cout << "Removing extraneous hierarchy node " << allChildren[i]->GetName() << std::endl;
}
if (vtkMRMLDisplayableHierarchyNode::SafeDownCast(allChildren[i]) != nullptr)
{
vtkMRMLDisplayNode *hierarchyDisplayNode = vtkMRMLDisplayableHierarchyNode::SafeDownCast(allChildren[i])->GetDisplayNode();
if (hierarchyDisplayNode)
{
if (debug)
{
std::cout << "\tand disp node " << hierarchyDisplayNode->GetID() << std::endl;
}
modelScene->RemoveNode(hierarchyDisplayNode);
}
}
modelScene->RemoveNode(allChildren[i]);
}
}
}
// write to disk
modelScene->Commit();
std::cout << "Models saved to scene file " << sceneFilename.c_str() << "\n";
if (ModelSceneFile.size() == 0)
{
std::cout << "\nIf you ran this from Slicer3's GUI, use File->Import Scene... " << sceneFilename.c_str()
<< " to load your models.\n";
}
}
// Clean up
if (debug)
{
std::cout << "Cleaning up" << endl;
}
if (cubes)
{
if (debug)
{
std::cout << "Deleting cubes" << endl;
}
cubes->SetInputData(nullptr);
cubes = nullptr;
}
if (colorNode)
{
colorNode = nullptr;
}
if (smoother)
{
if (debug)
{
std::cout << "Deleting smoother" << endl;
}
smoother->SetInputData(nullptr);
smoother = nullptr;
}
if (hist)
{
if (debug)
{
std::cout << "Deleting hist" << endl;
}
hist->SetInputData(nullptr);
hist = nullptr;
}
if (smootherSinc)
{
if (debug)
{
std::cout << "Deleting smootherSinc" << endl;
}
smootherSinc->SetInputData(nullptr);
smootherSinc = nullptr;
}
if (smootherPoly)
{
if (debug)
{
std::cout << "Deleting smoother poly" << endl;
}
smootherPoly->SetInputData(nullptr);
smootherPoly = nullptr;
}
if (decimator)
{
if (debug)
{
std::cout << "Deleting decimator" << endl;
}
decimator->SetInputData(nullptr);
decimator = nullptr;
}
if (mcubes)
{
if (debug)
{
std::cout << "Deleting mcubes" << endl;
}
mcubes->SetInputData(nullptr);
mcubes = nullptr;
}
if (imageThreshold)
{
if (debug)
{
std::cout << "Deleting image threshold" << endl;
}
imageThreshold->SetInputData(nullptr);
imageThreshold->RemoveAllInputs();
imageThreshold = nullptr;
if (debug)
{
std::cout << "... done deleting image threshold" << endl;
}
}
if (threshold)
{
if (debug)
{
cout << "Deleting threshold" << endl;
}
threshold->SetInputData(nullptr);
threshold = nullptr;
}
if (imageToStructuredPoints)
{
if (debug)
{
std::cout << "Deleting image to structured points" << endl;
}
imageToStructuredPoints->SetInputData(nullptr);
imageToStructuredPoints = nullptr;
}
if (geometryFilter)
{
if (debug)
{
cout << "Deleting geometry filter" << endl;
}
geometryFilter->SetInputData(nullptr);
geometryFilter = nullptr;
}
if (transformIJKtoLPS)
{
if (debug)
{
std::cout << "Deleting transform ijk to lps" << endl;
}
transformIJKtoLPS->SetInput(nullptr);
transformIJKtoLPS = nullptr;
}
if (reverser)
{
if (debug)
{
std::cout << "Deleting reverser" << endl;
}
reverser->SetInputData(nullptr);
reverser = nullptr;
}
if (transformer)
{
if (debug)
{
std::cout << "Deleting transformer" << endl;
}
transformer->SetInputData(nullptr);
transformer = nullptr;
}
if (normals)
{
if (debug)
{
std::cout << "Deleting normals" << endl;
}
normals->SetInputData(nullptr);
normals = nullptr;
}
if (stripper)
{
if (debug)
{
std::cout << "Deleting stripper" << endl;
}
stripper->SetInputData(nullptr);
stripper = nullptr;
}
if (ici.GetPointer())
{
if (debug)
{
std::cout << "Deleting ici, no set input null" << endl;
}
ici->SetInputData(nullptr);
}
if (debug)
{
std::cout << "Deleting reader" << endl;
}
reader = nullptr;
if (modelScene.GetPointer())
{
if (debug)
{
std::cout << "Deleting model scene" << endl;
}
modelScene->Clear(1);
}
return EXIT_SUCCESS;
}
| 32.820487 | 185 | 0.540484 | forfullstack |
58db275567c4749ea7dfab63efc0ac8e488b385e | 1,362 | cpp | C++ | code/exploration_50-TEMPLATE_SPECIALIZATION/01-example_of_specializing/main.cpp | ordinary-developer/exploring_cpp_11_2_ed_r_lischner | 468de9c64ae54db45c4de748436947d5849c4582 | [
"MIT"
] | 1 | 2017-05-04T08:23:46.000Z | 2017-05-04T08:23:46.000Z | code/exploration_50-TEMPLATE_SPECIALIZATION/01-example_of_specializing/main.cpp | ordinary-developer/exploring_cpp_11_2_ed_r_lischner | 468de9c64ae54db45c4de748436947d5849c4582 | [
"MIT"
] | null | null | null | code/exploration_50-TEMPLATE_SPECIALIZATION/01-example_of_specializing/main.cpp | ordinary-developer/exploring_cpp_11_2_ed_r_lischner | 468de9c64ae54db45c4de748436947d5849c4582 | [
"MIT"
] | null | null | null | #include <iostream>
#include <typeinfo>
template<class T>
class point {
public:
typedef T value_type;
point(T const& x, T const& y) : x_{ x }, y_{ y } { }
point() : point{ T{}, T{}} {
std::cout << "point<" << typeid(T).name() << ">()\n";
}
T const& x() const { return x_; }
T const& y() const { return y_; }
void move_absolute(T const& x, T const& y) {
x_ = x;
y_ = y;
}
void move_relative(T const& dx, T const& dy) {
x_ += dx;
y_ += dy;
}
private:
T x_;
T y_;
};
template<>
class point<double> {
public:
typedef double value_type;
point(double x, double y) : x_{ x }, y_{ y } { }
point() : point{ 0.0, 0.0 } {
std::cout << "point<double> specialization\n";
}
double x() const { return x_; }
double y() const { return y_; }
void move_absolute(double x, double y) {
x_ = x;
y_ = y;
}
void move_relative(double dx, double dy) {
x_ += dx;
y_ += dy;
}
private:
double x_;
double y_;
};
int main() {
point<short> s{};
point<double> d{};
s.move_absolute(10, 20);
d.move_absolute(1.23, 4.56);
return 0;
}
| 20.029412 | 65 | 0.448605 | ordinary-developer |
58df2ccf59b7cecfc0b1a6b87f7af664137aab83 | 910 | cpp | C++ | 2-1-Cpp Programming I/EX1/1-2.cpp | Awdrtgg/Coursework-Projects | d48124b71e477f71b6370f5c3317c6800f8fdb06 | [
"MIT"
] | 3 | 2018-12-02T13:52:55.000Z | 2019-02-26T13:19:50.000Z | 2-1-Cpp Programming I/EX1/1-2.cpp | Awdrtgg/Coursework-Projects | d48124b71e477f71b6370f5c3317c6800f8fdb06 | [
"MIT"
] | null | null | null | 2-1-Cpp Programming I/EX1/1-2.cpp | Awdrtgg/Coursework-Projects | d48124b71e477f71b6370f5c3317c6800f8fdb06 | [
"MIT"
] | null | null | null | /* --------------------------------------------------------------------------------------
Exercsie 1: Simple C++ Programming
Test 2: Prime Number
Programmer: Xiao Yunming
********************************************************************************
----------------------------------------------------------------------------------------*/
#include <iostream>
#include <math.h>
#include <fstream>
using namespace std;
int main()
{
int i = 2, upper;
cout << "Please input the upper number N:" << endl;
cin >> upper;
fstream tar;
tar.open("Record.txt",ios::app|ios::in);
tar << "The prime numbers below " << upper << " are: " << i;
while( i <= upper)
{
int circ = 2, sig = 0;
while( circ <= (int)sqrt(i))
{
if ( i % circ == 0)
{
sig = 0;
break;
}
else
sig = 1;
++circ;
}
if (sig == 1)
tar << ", " << i;
else;
++i;
}
tar << "." << endl;
}
| 20.222222 | 90 | 0.374725 | Awdrtgg |
58dfe46daef79e53952eb24f548cd30fcd185cb5 | 5,266 | cc | C++ | mindspore/ccsrc/runtime/graph_scheduler/actor/rpc/recv_actor.cc | zhz44/mindspore | 6044d34074c8505dd4b02c0a05419cbc32a43f86 | [
"Apache-2.0"
] | null | null | null | mindspore/ccsrc/runtime/graph_scheduler/actor/rpc/recv_actor.cc | zhz44/mindspore | 6044d34074c8505dd4b02c0a05419cbc32a43f86 | [
"Apache-2.0"
] | null | null | null | mindspore/ccsrc/runtime/graph_scheduler/actor/rpc/recv_actor.cc | zhz44/mindspore | 6044d34074c8505dd4b02c0a05419cbc32a43f86 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2022 Huawei Technologies Co., Ltd
*
* 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 "runtime/graph_scheduler/actor/rpc/recv_actor.h"
#include <memory>
#include <utility>
#include <functional>
#include <condition_variable>
#include "plugin/device/cpu/kernel/rpc/rpc_recv_kernel.h"
namespace mindspore {
namespace runtime {
void RecvActor::SetOpcontext(OpContext<DeviceTensor> *const op_context) {
std::unique_lock<std::mutex> lock(context_mtx_);
op_context_ = op_context;
is_context_valid_ = true;
context_cv_.notify_all();
}
void RecvActor::ResetOpcontext() {
std::unique_lock<std::mutex> lock(context_mtx_);
is_context_valid_ = false;
}
void RecvActor::SetRouteInfo(uint32_t, const std::string &, const std::string &recv_src_node_name,
const std::string &recv_dst_node_name) {
rpc_input_node_name_.emplace_back(recv_src_node_name);
input_inter_process_num_++;
}
bool RecvActor::StartServer() {
// Step 1: Create a tcp server and start listening.
server_ = std::make_unique<TCPServer>();
MS_EXCEPTION_IF_NULL(server_);
if (!server_->Initialize()) {
MS_LOG(EXCEPTION) << "Failed to initialize tcp server for recv actor";
}
ip_ = server_->GetIP();
port_ = server_->GetPort();
std::string server_url = ip_ + ":" + std::to_string(port_);
MS_LOG(INFO) << "Start server for recv actor. Server address: " << server_url;
// Step 2: Set the message handler of the server.
server_->SetMessageHandler(std::bind(&RecvActor::HandleMessage, this, std::placeholders::_1));
// Step 2: Register the server address to route table. The server should not be connected before this step is done.
ActorAddress recv_actor_addresss;
recv_actor_addresss.set_actor_id(inter_process_edge_name_);
recv_actor_addresss.set_ip(ip_);
recv_actor_addresss.set_port(port_);
MS_EXCEPTION_IF_NULL(actor_route_table_proxy_);
if (!actor_route_table_proxy_->RegisterRoute(inter_process_edge_name_, recv_actor_addresss)) {
MS_LOG(EXCEPTION) << "Failed to register route for " << inter_process_edge_name_ << " " << server_url
<< " when starting server.";
}
return true;
}
void RecvActor::RunOpInterProcessData(const std::shared_ptr<MessageBase> &msg, OpContext<DeviceTensor> *const context) {
MS_ERROR_IF_NULL_WO_RET_VAL(msg);
MS_ERROR_IF_NULL_WO_RET_VAL(op_context_);
auto &sequential_num = context->sequential_num_;
(void)input_op_inter_process_[sequential_num].emplace_back(msg->From().Name());
auto is_run = CheckRunningCondition(context);
MS_LOG(INFO) << "Actor(" << GetAID().Name() << ") receive the input op inter-process. Edge is "
<< inter_process_edge_name_ << ". Check running condition:" << is_run;
// Parse the message from remote peer and set to rpc recv kernel.
auto recv_kernel_mod = dynamic_cast<kernel::RpcKernelMod *>(kernel_info_->MutableKernelMod());
MS_ERROR_IF_NULL_WO_RET_VAL(recv_kernel_mod);
// We set remote data by the interface of the rpc kernel, because currently there's no remote input for a kernel mod.
recv_kernel_mod->SetRemoteInput(msg);
if (is_run) {
Run(context);
}
return;
}
bool RecvActor::CheckRunningCondition(const OpContext<DeviceTensor> *context) const {
MS_EXCEPTION_IF_NULL(context);
// Step 1: Judge data and control inputs are satisfied.
bool is_data_and_control_arrow_satisfied = AbstractActor::CheckRunningCondition(context);
if (!is_data_and_control_arrow_satisfied) {
return false;
}
if (input_inter_process_num_ != 0) {
// Step 2: Judge inter-process inputs are satisfied.
const auto &inter_process_iter = input_op_inter_process_.find(context->sequential_num_);
if (inter_process_iter == input_op_inter_process_.end()) {
return false;
}
const auto ¤t_inter_process_inputs = inter_process_iter->second;
if (current_inter_process_inputs.size() < input_inter_process_num_) {
return false;
} else if (current_inter_process_inputs.size() > input_inter_process_num_) {
MS_LOG(ERROR) << "Invalid inter process input num:" << current_inter_process_inputs.size()
<< " need:" << input_inter_process_num_ << " for actor:" << GetAID();
return false;
}
}
return true;
}
void RecvActor::HandleMessage(const std::shared_ptr<MessageBase> &msg) {
// Block the message handler if the context is invalid.
std::unique_lock<std::mutex> lock(context_mtx_);
context_cv_.wait(lock, [this] { return is_context_valid_; });
lock.unlock();
MS_ERROR_IF_NULL_WO_RET_VAL(msg);
MS_ERROR_IF_NULL_WO_RET_VAL(op_context_);
ActorDispatcher::Send(GetAID(), &RecvActor::RunOpInterProcessData, msg, op_context_);
}
} // namespace runtime
} // namespace mindspore
| 39.298507 | 120 | 0.735663 | zhz44 |
58e17d61020b6ce97efbaef0711fc44a699dedf2 | 2,606 | cpp | C++ | main.cpp | 0xADE1A1DE/CacheFX | 2b0127af579919e9196d35b9fdd325fa8229b51d | [
"Apache-2.0"
] | 3 | 2022-01-30T14:54:58.000Z | 2022-03-17T00:58:18.000Z | main.cpp | 0xADE1A1DE/CacheFX | 2b0127af579919e9196d35b9fdd325fa8229b51d | [
"Apache-2.0"
] | null | null | null | main.cpp | 0xADE1A1DE/CacheFX | 2b0127af579919e9196d35b9fdd325fa8229b51d | [
"Apache-2.0"
] | 4 | 2022-01-30T09:22:57.000Z | 2022-03-17T00:58:26.000Z | /*
* Copyright 2022 The University of Adelaide
*
* This file is part of CacheFX.
*
* 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 <getopt.h>
#include <iostream>
#include <map>
#include <string>
#include <unistd.h>
using namespace std;
#include <AttackEfficiencyController.h>
#include <CLArgs.h>
#include <CacheFactory/CacheFactory.h>
#include <Controller.h>
#include <EntropyLoss.h>
#include <ProfilingEvaluation.h>
#include <Victim/Victim.h>
#include <types.h>
int main(int argc, char** argv)
{
CLArgs args;
MeasurementType measurements = MT_INVALID;
args.parse(argc, argv);
// Configure cache
CacheFactory::Instance()->setCfgFilePath(args.get_cfgFilePath());
// Perform experiments
switch (args.get_measurements())
{
case MT_ENTROPY: {
EntropyLoss infoLoss;
infoLoss.evaluate();
if (args.get_fileOutput())
{
infoLoss.printStatistics(args.get_outputFile());
}
else
{
infoLoss.printStatistics();
}
break;
}
case MT_PROFILING: {
ProfilingEvaluation eval;
eval.evaluate(1);
if (args.get_fileOutput())
{
eval.printStatistics(args.get_outputFile());
}
else
{
eval.printStatistics();
}
break;
}
case MT_ATTACKER: {
if (args.get_victim() == VT_INVALID)
{
fprintf(stderr, "No victim specified\n");
exit(1);
}
for (int32_t i = 0; i < args.get_repeats(); i++)
{
unique_ptr<Controller> c = make_unique<Controller>(args);
c->run(i + 1);
}
break;
}
case MT_EFFICIENCY: {
if (args.get_victim() == VT_INVALID)
{
fprintf(stderr, "No victim specified\n");
exit(1);
}
unique_ptr<AttackEfficiencyController> c =
make_unique<AttackEfficiencyController>(args);
c->run(0);
break;
}
case MT_INVALID:
default: {
std::cout << "Invalid or no profiling type was specified for measurements!"
<< std::endl;
std::cout << "Profiling type can be any of the following: " << std::endl;
std::cout << "entropy, profiling, attacker" << std::endl;
}
}
}
| 23.690909 | 79 | 0.657713 | 0xADE1A1DE |
58e8b0f612d52ad89d385c9c65acd7fe2995970b | 400 | cc | C++ | extras/readnewmagres.cc | dch0ph/pNMRsim | 2420e618c7bff9b38b43e7c2ac684c5c28b61787 | [
"MIT"
] | null | null | null | extras/readnewmagres.cc | dch0ph/pNMRsim | 2420e618c7bff9b38b43e7c2ac684c5c28b61787 | [
"MIT"
] | null | null | null | extras/readnewmagres.cc | dch0ph/pNMRsim | 2420e618c7bff9b38b43e7c2ac684c5c28b61787 | [
"MIT"
] | null | null | null | #include "magres.h"
using namespace MagRes;
int main(int argc, const char **argv) {
try {
MagresFile magres;
magres.parse_from_file(argv[1]);
std::cout << magres;
}
catch (exception_t& exc) {
std::cerr << "Parsing failed: " << exc << '\n';
return 1;
}
catch (notmagres_exception_t&) {
std::cerr << "Not a new format magres file\n";
return 2;
}
return 0;
}
| 19.047619 | 51 | 0.6 | dch0ph |
58e999a3c5fd31dcf3b51b5996d50a3880d74664 | 530 | cpp | C++ | CodeChef June Contest 2020/Chef-and-String-Problem.cpp | Shiv-sharma-111/CodeChef-Contest | 93594692ba0818cb30ac3dd15addd67246e987ff | [
"MIT"
] | null | null | null | CodeChef June Contest 2020/Chef-and-String-Problem.cpp | Shiv-sharma-111/CodeChef-Contest | 93594692ba0818cb30ac3dd15addd67246e987ff | [
"MIT"
] | null | null | null | CodeChef June Contest 2020/Chef-and-String-Problem.cpp | Shiv-sharma-111/CodeChef-Contest | 93594692ba0818cb30ac3dd15addd67246e987ff | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
int T;
cin>>T;
while(T--)
{
string S;
//getline(cin,S);
cin>>S;
int n = S.length();
int count=0;
if(n==1)
{
cout<<"0"<<"\n";
}
else
{
for(int i=0;i<n;i++)
{
if((S[i]=='x' && S[i+1]=='y') || (S[i]=='y' && S[i+1]=='x'))
{
count++;
i++;
}
}
cout<<count<<"\n";
}
}
return 0;
}
| 15.142857 | 68 | 0.39434 | Shiv-sharma-111 |
58eb71bbe291896006a7ff8e7e255045e4e2abf4 | 8,781 | cpp | C++ | ntUPSd/CommandProcessor.cpp | 6XGate/ntUPSd | 7a3d7301a78db632c93c8eb9665c9d039137d835 | [
"MIT"
] | 20 | 2016-04-11T12:22:59.000Z | 2021-12-07T19:38:26.000Z | ntUPSd/CommandProcessor.cpp | 6XGate/ntUPSd | 7a3d7301a78db632c93c8eb9665c9d039137d835 | [
"MIT"
] | 1 | 2016-04-11T12:45:54.000Z | 2016-04-13T11:44:45.000Z | ntUPSd/CommandProcessor.cpp | 6XGate/ntUPSd | 7a3d7301a78db632c93c8eb9665c9d039137d835 | [
"MIT"
] | 8 | 2017-11-03T00:57:13.000Z | 2021-11-10T14:20:23.000Z | /*
Copyright 2016 Matthew Holder
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 "stdafx.h"
#include "CommandProcessor.h"
namespace
{
class CSimpleResult : public CReplResult
{
public:
explicit CSimpleResult(LPCSTR pszStaticResult) : m_pszStaticResult(pszStaticResult) { }
STDMETHOD(RenderResult)(CStringA &strResult) noexcept
{
_ATLTRY
{
strResult = m_pszStaticResult;
return S_OK;
}
_ATLCATCH(ex)
{
return ex.m_hr;
}
_ATLCATCHALL()
{
return E_FAIL;
}
}
private:
LPCSTR m_pszStaticResult;
};
}
HRESULT CCommandProcessor::Initialize() noexcept
{
_ATLTRY
{
if (!m_pszLastError.Allocate(LAST_ERROR_BUFFER_LENGTH))
{
return E_OUTOFMEMORY;
}
m_pBatteries = _ATL_NEW CBatteryCollection;
if (m_pBatteries == nullptr)
{
return E_OUTOFMEMORY;
}
HRESULT hr = m_pBatteries->LoadBatteries();
if (FAILED(hr))
{
return hr;
}
m_rgErrors.SetAt(S_OK, "OK");
m_rgPrimeHandlers.SetAt("STARTTLS", &CCommandProcessor::OnStartTls);
m_rgPrimeHandlers.SetAt("USERNAME", &CCommandProcessor::OnUserName);
m_rgPrimeHandlers.SetAt("PASSWORD", &CCommandProcessor::OnPassWord);
m_rgPrimeHandlers.SetAt("GET", &CCommandProcessor::OnGet);
m_rgPrimeHandlers.SetAt("LIST", &CCommandProcessor::OnList);
m_rgPrimeHandlers.SetAt("LOGIN", &CCommandProcessor::OnLogin);
m_rgPrimeHandlers.SetAt("LOGOUT", &CCommandProcessor::OnLogout);
m_rgGetHandlers.SetAt("VAR", &CCommandProcessor::OnGetVar);
m_rgListHandlers.SetAt("UPS", &CCommandProcessor::OnListUps);
return S_OK;
}
_ATLCATCH(ex)
{
return ex.m_hr;
}
_ATLCATCHALL()
{
return E_FAIL;
}
}
HRESULT CCommandProcessor::Eval(_In_z_ LPCSTR pszCommandLine, CComPtr<IReplResult> &rpResult) noexcept
{
CStringA strCommandLine = pszCommandLine;
LPSTR pszParameters = strCommandLine.GetBuffer();
LPCSTR pszCommand = GetPart(pszParameters);
HRESULT hr = S_FALSE;
if (pszCommand != nullptr)
{
auto pos = m_rgPrimeHandlers.Lookup(pszCommand);
if (pos != nullptr)
{
auto pfnHandler = m_rgPrimeHandlers.GetValueAt(pos);
hr = (this->*pfnHandler)(pszParameters, rpResult);
}
else
{
hr = NUT_E_UNKNOWNCMD;
}
}
else
{
hr = S_OK;
}
strCommandLine.ReleaseBuffer();
return hr;
}
LPCSTR CCommandProcessor::ReportError(HRESULT hr, LPCSTR) noexcept
{
if (!(hr & 0x20000000) || HRESULT_FACILITY(hr) != FACILITY_NUT)
{
hr = NUT_E_UNREPORTABLE;
}
if (!::FormatMessageA(
FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr, hr, 0x0000, m_pszLastError, LAST_ERROR_BUFFER_LENGTH, nullptr))
{
StringCchCopyA(m_pszLastError, LAST_ERROR_BUFFER_LENGTH, "UNKNOWN-ERROR");
}
return m_pszLastError;
}
HRESULT CCommandProcessor::DefaultResult(CStringA &strResult) noexcept
{
_ATLTRY
{
strResult = "OK";
return S_OK;
}
_ATLCATCH(ex)
{
return ex.m_hr;
}
_ATLCATCHALL()
{
return E_FAIL;
}
}
LPCSTR CCommandProcessor::GetPart(_Inout_z_ LPSTR &pszLine) noexcept
{
// A character position alias for pszLine.
LPCH &pchPos = pszLine;
// This all assumes the lines have been trimmed.
if (*pchPos == 0)
{
return nullptr;
}
LPCSTR pszResult = nullptr;
if (*pchPos == '"')
{
pszResult = ++pchPos;
LPCH pchTo = pchPos;
// Quoted part.
bool fContinue = true;
while (fContinue && *pchPos != '"' && *pchPos != 0)
{
if (*pchPos == '\\')
{
// Possible escaped character
++pchPos;
switch (*pchPos)
{
case 0:
// Unexpected end-of-line, just leave the back-slash.
--pchPos;
fContinue = false;
break;
case '"':
case '\\':
break;
default:
// Push the position back, the next character cannot be escaped.
--pchPos;
break;
}
}
*pchTo++ = *pchPos++;
}
// Zero out everything between pchTo and pchPos.
while (pchTo != pchPos)
{
*pchTo++ = 0;
}
// Remove the ending quote.
if (*pchPos == '"')
{
*pchPos++ = 0;
}
}
else
{
// Find the first non-white-space character. The part start at the beginning.
pszResult = pchPos;
while (*pchPos != 0)
{
if (isspace(*pchPos))
{
*pchPos++ = 0;
break;
}
++pchPos;
}
}
// Move past any other white-space characters.
while (*pchPos != 0)
{
if (!isspace(*pchPos))
{
break;
}
++pchPos;
}
return pszResult;
}
HRESULT CCommandProcessor::OnStartTls(_In_z_ LPSTR pszParameters, CComPtr<IReplResult>& rpResult) noexcept
{
UNREFERENCED_PARAMETER(pszParameters);
UNREFERENCED_PARAMETER(rpResult);
// TLS is currently not supported.
return NUT_E_NOTSUPPORTED;
}
HRESULT CCommandProcessor::OnUserName(_In_z_ LPSTR pszParameters, CComPtr<IReplResult> &rpResult) noexcept
{
UNREFERENCED_PARAMETER(rpResult);
_ATLTRY
{
LPCSTR pszUserName = GetPart(pszParameters);
if (pszUserName == nullptr || strlen(pszUserName) == 0)
{
return NUT_E_INVALIDARG;
}
if (!m_strUserName.IsEmpty())
{
return NUT_E_USERNAME_SET;
}
m_strUserName = pszUserName;
return S_OK;
}
_ATLCATCH(ex)
{
return ex.m_hr;
}
_ATLCATCHALL()
{
return E_FAIL;
}
}
HRESULT CCommandProcessor::OnPassWord(_In_z_ LPSTR pszParameters, CComPtr<IReplResult> &rpResult) noexcept
{
UNREFERENCED_PARAMETER(rpResult);
_ATLTRY
{
LPCSTR pszPassWord = GetPart(pszParameters);
if (pszPassWord == nullptr || strlen(pszPassWord) == 0)
{
return NUT_E_INVALIDARG;
}
if (!m_strPassWord.IsEmpty())
{
return NUT_E_PASSWORD_SET;
}
m_strPassWord = pszPassWord;
return S_OK;
}
_ATLCATCH(ex)
{
return ex.m_hr;
}
_ATLCATCHALL()
{
return E_FAIL;
}
}
HRESULT CCommandProcessor::OnGet(_In_z_ LPSTR pszParameters, CComPtr<IReplResult>& rpResult) noexcept
{
HRESULT hr = S_OK;
LPCSTR pszCommand = GetPart(pszParameters);
if (pszCommand != nullptr)
{
auto pos = m_rgGetHandlers.Lookup(pszCommand);
if (pos != nullptr)
{
auto pfnHandler = m_rgGetHandlers.GetValueAt(pos);
hr = (this->*pfnHandler)(pszParameters, rpResult);
}
else
{
hr = NUT_E_INVALIDARG;
}
}
else
{
hr = NUT_E_INVALIDARG;
}
return hr;
}
HRESULT CCommandProcessor::OnList(_In_z_ LPSTR pszParameters, CComPtr<IReplResult> &rpResult) noexcept
{
HRESULT hr = S_OK;
LPCSTR pszCommand = GetPart(pszParameters);
if (pszCommand != nullptr)
{
auto pos = m_rgListHandlers.Lookup(pszCommand);
if (pos != nullptr)
{
auto pfnHandler = m_rgListHandlers.GetValueAt(pos);
hr = (this->*pfnHandler)(pszParameters, rpResult);
}
else
{
hr = NUT_E_INVALIDARG;
}
}
else
{
hr = NUT_E_INVALIDARG;
}
return hr;
}
HRESULT CCommandProcessor::OnLogin(_In_z_ LPSTR pszParameters, CComPtr<IReplResult> &rpResult) noexcept
{
UNREFERENCED_PARAMETER(pszParameters);
UNREFERENCED_PARAMETER(rpResult);
return S_OK;
}
HRESULT CCommandProcessor::OnLogout(_In_z_ LPSTR pszParameters, CComPtr<IReplResult>& rpResult) noexcept
{
UNREFERENCED_PARAMETER(pszParameters);
rpResult = _ATL_NEW CSimpleResult("OK Goodbye");
if (rpResult == nullptr)
{
return E_OUTOFMEMORY;
}
return S_OK;
}
HRESULT CCommandProcessor::OnGetVar(_In_z_ LPSTR pszParameters, CComPtr<IReplResult>& rpResult) noexcept
{
HRESULT hr = S_OK;
LPCSTR pszUps = GetPart(pszParameters);
if (pszUps != nullptr)
{
LPCSTR pszName = GetPart(pszParameters);
if (pszName != nullptr)
{
POSITION pos = m_pBatteries->FindBattery(pszUps);
if (pos != NULL)
{
auto &battery = m_pBatteries->GetAt(pos);
hr = battery.GetVariable(pszName, rpResult);
}
else
{
hr = NUT_E_UNKNOWN_UPS;
}
}
else
{
hr = NUT_E_INVALIDARG;
}
}
else
{
hr = NUT_E_INVALIDARG;
}
return hr;
}
HRESULT CCommandProcessor::OnListUps(_In_z_ LPSTR pszParameters, CComPtr<IReplResult> &rpResult) noexcept
{
UNREFERENCED_PARAMETER(pszParameters);
rpResult = m_pBatteries;
return S_OK;
}
| 20.468531 | 106 | 0.705045 | 6XGate |
58ec0ca4937becbc75d48e9ea9339b82a75200f2 | 130 | cpp | C++ | Shader.cpp | jtilander/unittestcg | d56910eb75c6c3d4673a3bf465ab8e21169aaec5 | [
"MIT"
] | null | null | null | Shader.cpp | jtilander/unittestcg | d56910eb75c6c3d4673a3bf465ab8e21169aaec5 | [
"MIT"
] | null | null | null | Shader.cpp | jtilander/unittestcg | d56910eb75c6c3d4673a3bf465ab8e21169aaec5 | [
"MIT"
] | null | null | null | #include "Precompiled.h"
#include "Shader.h"
namespace aurora {
Shader::Shader()
{
}
Shader::~Shader()
{
}
}
| 8.125 | 25 | 0.553846 | jtilander |
58ed29b8d1b6e1d1e9ac7db84772577222747702 | 39,407 | cpp | C++ | component_library/src/physics.cpp | diederickh/corgi | e7c48adc51113d7b1b5d9571cde8c949025b85b6 | [
"Apache-2.0"
] | 272 | 2015-11-19T04:18:38.000Z | 2022-03-30T02:37:22.000Z | component_library/src/physics.cpp | diederickh/corgi | e7c48adc51113d7b1b5d9571cde8c949025b85b6 | [
"Apache-2.0"
] | 1 | 2015-11-19T19:21:50.000Z | 2017-02-16T17:43:01.000Z | component_library/src/physics.cpp | diederickh/corgi | e7c48adc51113d7b1b5d9571cde8c949025b85b6 | [
"Apache-2.0"
] | 44 | 2015-11-19T04:41:54.000Z | 2021-09-05T08:52:23.000Z | // Copyright 2015 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <cfloat>
#include <cmath>
#include "breadboard/event.h"
#include "breadboard/graph_state.h"
#include "corgi_component_library/bullet_physics.h"
#include "corgi_component_library/common_services.h"
#include "corgi_component_library/component_utils.h"
#include "corgi_component_library/graph.h"
#include "corgi_component_library/physics.h"
#include "corgi_component_library/rendermesh.h"
#include "corgi_component_library/transform.h"
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/reflection.h"
#include "fplbase/flatbuffer_utils.h"
#include "fplbase/mesh.h"
#include "mathfu/glsl_mappings.h"
#include "mathfu/vector.h"
using mathfu::vec3;
using mathfu::quat;
using fplbase::AssetManager;
using corgi::BulletBoxDef;
using corgi::BulletBoxDefBuilder;
using corgi::BulletCapsuleDef;
using corgi::BulletCapsuleDefBuilder;
using corgi::BulletConeDef;
using corgi::BulletConeDefBuilder;
using corgi::BulletCylinderDef;
using corgi::BulletCylinderDefBuilder;
using corgi::BulletNoShapeDef;
using corgi::BulletNoShapeDefBuilder;
using corgi::BulletShapeUnion;
using corgi::BulletShapeDef;
using corgi::BulletShapeDefBuilder;
using corgi::BulletSphereDef;
using corgi::BulletSphereDefBuilder;
using corgi::BulletStaticPlaneDef;
using corgi::BulletStaticPlaneDefBuilder;
using corgi::PhysicsDef;
using corgi::PhysicsDefBuilder;
using fplbase::Renderer;
using fplbase::Shader;
using fplbase::Vec3;
using mathfu::vec4;
CORGI_DEFINE_COMPONENT(corgi::component_library::PhysicsComponent,
corgi::component_library::PhysicsData)
BREADBOARD_DEFINE_EVENT(corgi::component_library::kCollisionEventId)
namespace corgi {
namespace component_library {
// The function that is called from Bullet while calling World's stepSimulation.
// Note that it can be called multiple times per entity update, as Bullet can
// potentially update the world several times with that call.
static void BulletTickCallback(btDynamicsWorld* world, btScalar time_step);
static const char* kPhysicsShader = "shaders/color";
static inline btVector3 ToBtVector3(const mathfu::vec3& v) {
return btVector3(v.x, v.y, v.z);
}
static inline btVector3 ToBtVector3(const fplbase::Vec3& v) {
return btVector3(v.x(), v.y(), v.z());
}
static inline fplbase::Vec3 BtToFlatVec3(const btVector3& v) {
return fplbase::Vec3(v.x(), v.y(), v.z());
}
static inline mathfu::vec3 BtToMathfuVec3(const btVector3& v) {
return mathfu::vec3(v.x(), v.y(), v.z());
}
static inline btQuaternion ToBtQuaternion(const mathfu::quat& q) {
// Bullet assumes a right handed system, while mathfu is left, so the axes
// need to be negated.
return btQuaternion(-q.vector().x, -q.vector().y, -q.vector().z,
q.scalar());
}
static inline mathfu::quat BtToMathfuQuat(const btQuaternion& q) {
// As above, the axes need to be negated.
return mathfu::quat(q.getW(), -q.getX(), -q.getY(), -q.getZ());
}
// These functions require bullet_physics.h, so define here.
RigidBodyData::RigidBodyData() {}
RigidBodyData::~RigidBodyData() {}
RigidBodyData& RigidBodyData::operator=(RigidBodyData&& src) {
offset = std::move(src.offset);
collision_type = std::move(src.collision_type);
collides_with = std::move(src.collides_with);
user_tag = std::move(src.user_tag);
shape = std::move(src.shape);
motion_state = std::move(src.motion_state);
rigid_body = std::move(src.rigid_body);
should_export = std::move(src.should_export);
return *this;
}
// These functions require bullet_physics.h, so define here.
PhysicsData::PhysicsData()
: body_count_(0), enabled_(false), gravity_multiplier_(1.0f) {}
PhysicsData::~PhysicsData() {}
PhysicsData::PhysicsData(PhysicsData&& src) { *this = std::move(src); }
PhysicsData& PhysicsData::operator=(PhysicsData&& src) {
body_count_ = std::move(src.body_count_);
enabled_ = std::move(src.enabled_);
triangle_mesh_ = std::move(src.triangle_mesh_);
for (size_t i = 0; i < kMaxPhysicsBodies; i++) {
rigid_bodies_[i] = std::move(src.rigid_bodies_[i]);
}
return *this;
}
mathfu::vec3 PhysicsData::Velocity() const {
// Only the first body can be non-kinematic, and thus use velocity.
return BtToMathfuVec3(rigid_bodies_[0].rigid_body->getLinearVelocity());
}
void PhysicsData::SetVelocity(const mathfu::vec3& velocity) {
rigid_bodies_[0].rigid_body->setLinearVelocity(ToBtVector3(velocity));
}
mathfu::vec3 PhysicsData::AngularVelocity() const {
return BtToMathfuVec3(rigid_bodies_[0].rigid_body->getAngularVelocity());
}
void PhysicsData::SetAngularVelocity(const mathfu::vec3& velocity) {
rigid_bodies_[0].rigid_body->setAngularVelocity(ToBtVector3(velocity));
}
int PhysicsData::RigidBodyIndex(const std::string& user_tag) const {
for (int i = 0; i < body_count_; ++i) {
if (user_tag == rigid_bodies_[i].user_tag) return i;
}
return -1;
}
void PhysicsData::GetAabb(int rigid_body_idx, mathfu::vec3* min,
mathfu::vec3* max) const {
btVector3 bt_min;
btVector3 bt_max;
rigid_bodies_[rigid_body_idx].rigid_body->getAabb(bt_min, bt_max);
*min = BtToMathfuVec3(bt_min);
*max = BtToMathfuVec3(bt_max);
}
// Used by Bullet to render the physics scene as a wireframe.
class PhysicsDebugDrawer : public btIDebugDraw {
public:
virtual ~PhysicsDebugDrawer() {}
virtual void drawLine(const btVector3& from, const btVector3& to,
const btVector3& color);
virtual int getDebugMode() const { return DBG_DrawWireframe; }
virtual void drawContactPoint(const btVector3& /*pointOnB*/,
const btVector3& /*normalOnB*/,
btScalar /*distance*/, int /*lifeTime*/,
const btVector3& /*color*/) {}
virtual void reportErrorWarning(const char* /*warningString*/) {}
virtual void draw3dText(const btVector3& /*location*/,
const char* /*textString*/) {}
virtual void setDebugMode(int /*debugMode*/) {}
Shader* shader() { return shader_; }
void set_shader(Shader* shader) { shader_ = shader; }
Renderer* renderer() { return renderer_; }
void set_renderer(Renderer* renderer) { renderer_ = renderer; }
private:
Shader* shader_;
Renderer* renderer_;
};
void PhysicsComponent::Init() {
AssetManager* asset_manager =
entity_manager_->GetComponent<CommonServicesComponent>()->asset_manager();
broadphase_.reset(new btDbvtBroadphase());
debug_drawer_.reset(new PhysicsDebugDrawer());
collision_configuration_.reset(new btDefaultCollisionConfiguration());
collision_dispatcher_.reset(
new btCollisionDispatcher(collision_configuration_.get()));
constraint_solver_.reset(new btSequentialImpulseConstraintSolver());
bullet_world_.reset(new btDiscreteDynamicsWorld(
collision_dispatcher_.get(), broadphase_.get(), constraint_solver_.get(),
collision_configuration_.get()));
bullet_world_->setGravity(btVector3(0.0f, 0.0f, gravity()));
bullet_world_->setDebugDrawer(debug_drawer_.get());
bullet_world_->setInternalTickCallback(BulletTickCallback,
static_cast<void*>(this));
debug_drawer_->set_shader(asset_manager->LoadShader(kPhysicsShader));
}
PhysicsComponent::PhysicsComponent()
: collision_callback_(nullptr),
collision_user_data_(nullptr),
gravity_(kDefaultPhysicsGravity),
max_steps_(kDefaultPhysicsMaxSteps) {}
PhysicsComponent::~PhysicsComponent() { ClearComponentData(); }
void PhysicsComponent::AddFromRawData(corgi::EntityRef& entity,
const void* raw_data) {
auto physics_def = static_cast<const PhysicsDef*>(raw_data);
PhysicsData* physics_data = AddEntity(entity);
TransformData* transform_data = Data<TransformData>(entity);
const vec3& scale = transform_data->scale;
// Make sure the physics data has been cleared from any previous loading,
// as the shapes need to be removed from the bullet world.
ClearPhysicsData(entity);
if (physics_def->shapes() && physics_def->shapes()->Length() > 0) {
int shape_count = physics_def->shapes()->Length() > kMaxPhysicsBodies
? kMaxPhysicsBodies
: physics_def->shapes()->Length();
physics_data->body_count_ = shape_count;
for (int index = 0; index < shape_count; ++index) {
auto shape_def = physics_def->shapes()->Get(index);
auto rb_data = &physics_data->rigid_bodies_[index];
switch (shape_def->data_type()) {
case BulletShapeUnion_BulletSphereDef: {
auto sphere_data =
static_cast<const BulletSphereDef*>(shape_def->data());
rb_data->shape.reset(new btSphereShape(sphere_data->radius()));
break;
}
case BulletShapeUnion_BulletBoxDef: {
auto box_data = static_cast<const BulletBoxDef*>(shape_def->data());
btVector3 half_extents = ToBtVector3(*box_data->half_extents());
rb_data->shape.reset(new btBoxShape(half_extents));
break;
}
case BulletShapeUnion_BulletCylinderDef: {
auto cylinder_data =
static_cast<const BulletCylinderDef*>(shape_def->data());
btVector3 half_extents = ToBtVector3(*cylinder_data->half_extents());
rb_data->shape.reset(new btCylinderShape(half_extents));
break;
}
case BulletShapeUnion_BulletCapsuleDef: {
auto capsule_data =
static_cast<const BulletCapsuleDef*>(shape_def->data());
rb_data->shape.reset(new btCapsuleShape(capsule_data->radius(),
capsule_data->height()));
break;
}
case BulletShapeUnion_BulletConeDef: {
auto cone_data = static_cast<const BulletConeDef*>(shape_def->data());
rb_data->shape.reset(
new btConeShape(cone_data->radius(), cone_data->height()));
break;
}
case BulletShapeUnion_BulletStaticPlaneDef: {
auto plane_data =
static_cast<const BulletStaticPlaneDef*>(shape_def->data());
btVector3 normal = ToBtVector3(*plane_data->normal());
rb_data->shape.reset(
new btStaticPlaneShape(normal, plane_data->constant()));
break;
}
case BulletShapeUnion_BulletNoShapeDef:
default: {
rb_data->shape.reset(new btEmptyShape());
break;
}
}
rb_data->shape->setLocalScaling(
btVector3(fabs(scale.x), fabs(scale.y), fabs(scale.z)));
rb_data->motion_state.reset(new btDefaultMotionState());
btScalar mass = shape_def->mass();
btVector3 inertia(0.0f, 0.0f, 0.0f);
if (rb_data->shape->getShapeType() != EMPTY_SHAPE_PROXYTYPE) {
rb_data->shape->calculateLocalInertia(mass, inertia);
}
btRigidBody::btRigidBodyConstructionInfo rigid_body_builder(
mass, rb_data->motion_state.get(), rb_data->shape.get(), inertia);
rigid_body_builder.m_restitution = shape_def->restitution();
rb_data->rigid_body.reset(new btRigidBody(rigid_body_builder));
rb_data->rigid_body->setUserIndex(static_cast<int>(entity.index()));
rb_data->rigid_body->setUserPointer(entity.container());
// Only the first shape can be non-kinematic.
if (index > 0 || physics_def->kinematic()) {
rb_data->rigid_body->setCollisionFlags(
rb_data->rigid_body->getCollisionFlags() |
btCollisionObject::CF_KINEMATIC_OBJECT);
}
if (shape_def->offset()) {
rb_data->offset = LoadVec3(shape_def->offset());
} else {
rb_data->offset = mathfu::kZeros3f;
}
rb_data->collision_type = static_cast<short>(shape_def->collision_type());
rb_data->collides_with = 0;
if (shape_def->collides_with()) {
for (auto collides = shape_def->collides_with()->begin();
collides != shape_def->collides_with()->end(); ++collides) {
rb_data->collides_with |= static_cast<short>(*collides);
}
}
if (shape_def->user_tag()) {
rb_data->user_tag = shape_def->user_tag()->str();
}
rb_data->should_export = true;
bullet_world_->addRigidBody(rb_data->rigid_body.get(),
rb_data->collision_type,
rb_data->collides_with);
// Give any custom gravity, after adding it to the world.
if (physics_def->gravity_multiplier() != 1.0f) {
rb_data->rigid_body->setGravity(bullet_world_->getGravity() *
physics_def->gravity_multiplier());
}
}
}
physics_data->enabled_ = true;
physics_data->gravity_multiplier_ = physics_def->gravity_multiplier();
UpdatePhysicsFromTransform(entity);
}
corgi::ComponentInterface::RawDataUniquePtr PhysicsComponent::ExportRawData(
const corgi::EntityRef& entity) const {
const PhysicsData* data = GetComponentData(entity);
if (data == nullptr) return nullptr;
flatbuffers::FlatBufferBuilder fbb;
bool defaults = entity_manager_->GetComponent<CommonServicesComponent>()
->export_force_defaults();
fbb.ForceDefaults(defaults);
std::vector<flatbuffers::Offset<BulletShapeDef>> shape_vector;
bool kinematic = true;
if (data->body_count_ > 0) {
kinematic = data->rigid_bodies_[0].rigid_body->isKinematicObject();
for (int index = 0; index < data->body_count_; ++index) {
const RigidBodyData& body = data->rigid_bodies_[index];
// Skip shapes that are set not to export.
if (!body.should_export) {
continue;
}
// The local scale of the shape adjusts the size of the shapes, but we
// want to save out the original size. So temporarily remove the scale,
// and add it back after saving out the original size.
btVector3 scale = body.shape->getLocalScaling();
body.shape->setLocalScaling(btVector3(1.0f, 1.0f, 1.0f));
BulletShapeUnion shape_type = BulletShapeUnion_BulletNoShapeDef;
flatbuffers::Offset<void> shape_data;
switch (body.shape->getShapeType()) {
case SPHERE_SHAPE_PROXYTYPE: {
auto sphere = static_cast<const btSphereShape*>(body.shape.get());
BulletSphereDefBuilder sphere_builder(fbb);
sphere_builder.add_radius(sphere->getRadius());
shape_type = BulletShapeUnion_BulletSphereDef;
shape_data = sphere_builder.Finish().Union();
break;
}
case BOX_SHAPE_PROXYTYPE: {
auto box = static_cast<const btBoxShape*>(body.shape.get());
BulletBoxDefBuilder box_builder(fbb);
Vec3 half_extents = BtToFlatVec3(box->getHalfExtentsWithMargin());
box_builder.add_half_extents(&half_extents);
shape_type = BulletShapeUnion_BulletBoxDef;
shape_data = box_builder.Finish().Union();
break;
}
case CYLINDER_SHAPE_PROXYTYPE: {
auto cylinder = static_cast<const btCylinderShape*>(body.shape.get());
BulletCylinderDefBuilder cylinder_builder(fbb);
Vec3 half_extents =
BtToFlatVec3(cylinder->getHalfExtentsWithMargin());
cylinder_builder.add_half_extents(&half_extents);
shape_type = BulletShapeUnion_BulletCylinderDef;
shape_data = cylinder_builder.Finish().Union();
break;
}
case CAPSULE_SHAPE_PROXYTYPE: {
auto capsule = static_cast<const btCapsuleShape*>(body.shape.get());
BulletCapsuleDefBuilder capsule_builder(fbb);
capsule_builder.add_radius(capsule->getRadius());
capsule_builder.add_height(2.0f * capsule->getHalfHeight());
shape_type = BulletShapeUnion_BulletCapsuleDef;
shape_data = capsule_builder.Finish().Union();
break;
}
case CONE_SHAPE_PROXYTYPE: {
auto cone = static_cast<const btConeShape*>(body.shape.get());
BulletConeDefBuilder cone_builder(fbb);
cone_builder.add_radius(cone->getRadius());
cone_builder.add_height(cone->getHeight());
shape_type = BulletShapeUnion_BulletConeDef;
shape_data = cone_builder.Finish().Union();
break;
}
case STATIC_PLANE_PROXYTYPE: {
auto plane = static_cast<const btStaticPlaneShape*>(body.shape.get());
BulletStaticPlaneDefBuilder plane_builder(fbb);
Vec3 normal = BtToFlatVec3(plane->getPlaneNormal());
plane_builder.add_normal(&normal);
plane_builder.add_constant(plane->getPlaneConstant());
shape_type = BulletShapeUnion_BulletStaticPlaneDef;
shape_data = plane_builder.Finish().Union();
break;
}
case EMPTY_SHAPE_PROXYTYPE: {
BulletNoShapeDefBuilder empty_builder(fbb);
shape_type = BulletShapeUnion_BulletNoShapeDef;
shape_data = empty_builder.Finish().Union();
break;
}
default: { assert(0); }
}
// Set the local scaling back in place.
body.shape->setLocalScaling(scale);
std::vector<signed short> collides_with;
for (signed short layer = 1;
layer < static_cast<signed short>(BulletCollisionType_End);
layer = layer << 1) {
if (body.collides_with & layer) {
collides_with.push_back(layer);
}
}
auto collides = fbb.CreateVector(collides_with);
auto user_tag = fbb.CreateString(body.user_tag);
BulletShapeDefBuilder shape_builder(fbb);
shape_builder.add_data_type(shape_type);
shape_builder.add_data(shape_data);
float invMass = body.rigid_body->getInvMass();
shape_builder.add_mass(invMass ? 1.0f / invMass : 0.0f);
shape_builder.add_restitution(body.rigid_body->getRestitution());
fplbase::Vec3 offset(body.offset.x, body.offset.y, body.offset.z);
shape_builder.add_offset(&offset);
shape_builder.add_collision_type(
static_cast<BulletCollisionType>(body.collision_type));
shape_builder.add_collides_with(collides);
shape_builder.add_user_tag(user_tag);
shape_vector.push_back(shape_builder.Finish());
}
}
// If no shapes were exported, there is nothing to be saved, as the
// additional flags all reflect information about the saved shapes.
if (!shape_vector.size()) {
return nullptr;
}
auto shapes = fbb.CreateVector(shape_vector);
PhysicsDefBuilder builder(fbb);
builder.add_kinematic(kinematic);
builder.add_shapes(shapes);
if (data->gravity_multiplier_ != 1.0f) {
builder.add_gravity_multiplier(data->gravity_multiplier_);
}
fbb.Finish(builder.Finish());
return fbb.ReleaseBufferPointer();
}
void PhysicsComponent::UpdateAllEntities(corgi::WorldTime delta_time) {
// Step the world.
bullet_world_->stepSimulation(delta_time / 1000.f, max_steps());
// Copy position information to Transforms.
for (auto iter = component_data_.begin(); iter != component_data_.end();
++iter) {
PhysicsData* physics_data = Data<PhysicsData>(iter->entity);
TransformData* transform_data = Data<TransformData>(iter->entity);
if (physics_data->body_count_ == 0 || !physics_data->enabled_) {
continue;
}
if (!physics_data->rigid_bodies_[0].rigid_body->isKinematicObject()) {
auto trans =
physics_data->rigid_bodies_[0].rigid_body->getWorldTransform();
// The quaternion needs to be normalized, as the provided one is not.
transform_data->orientation = BtToMathfuQuat(trans.getRotation());
transform_data->orientation.Normalize();
vec3 local_offset = vec3::HadamardProduct(
transform_data->scale, physics_data->rigid_bodies_[0].offset);
vec3 offset = transform_data->orientation.Inverse() * local_offset;
transform_data->position = BtToMathfuVec3(trans.getOrigin()) - offset;
}
// Update any kinematic objects with the current transform.
UpdatePhysicsObjectsTransform(iter->entity, true);
}
}
static void BulletTickCallback(btDynamicsWorld* world,
btScalar /* time_step */) {
PhysicsComponent* pc =
static_cast<PhysicsComponent*>(world->getWorldUserInfo());
pc->ProcessBulletTickCallback();
}
static void ExecuteGraphs(
CollisionData* collision_data, GraphData* this_graph_data,
corgi::EntityRef this_entity, const mathfu::vec3& this_position,
const std::string& this_tag, corgi::EntityRef other_entity,
const mathfu::vec3& other_position, const std::string& other_tag) {
collision_data->this_entity = this_entity;
collision_data->this_position = this_position;
collision_data->this_tag = this_tag;
collision_data->other_entity = other_entity;
collision_data->other_position = other_position;
collision_data->other_tag = other_tag;
if (this_graph_data) {
this_graph_data->broadcaster.BroadcastEvent(kCollisionEventId);
}
}
void PhysicsComponent::ProcessBulletTickCallback() {
// Check for collisions. Note that the number of manifolds and contacts might
// change when resolving collisions, so the result should not be cached.
for (int manifold_index = 0;
manifold_index < collision_dispatcher_->getNumManifolds();
manifold_index++) {
btPersistentManifold* contact_manifold =
collision_dispatcher_->getManifoldByIndexInternal(manifold_index);
for (int contact_index = 0;
contact_index < contact_manifold->getNumContacts(); contact_index++) {
btManifoldPoint& pt = contact_manifold->getContactPoint(contact_index);
if (pt.getDistance() < 0.0f) {
auto body_a = contact_manifold->getBody0();
auto body_b = contact_manifold->getBody1();
auto container_a =
static_cast<VectorPool<corgi::Entity>*>(body_a->getUserPointer());
auto container_b =
static_cast<VectorPool<corgi::Entity>*>(body_b->getUserPointer());
// Only generate events if both containers were defined
if (container_a == nullptr || container_b == nullptr) {
continue;
}
corgi::EntityRef entity_a(container_a, body_a->getUserIndex());
corgi::EntityRef entity_b(container_b, body_b->getUserIndex());
vec3 position_a = BtToMathfuVec3(pt.getPositionWorldOnA());
vec3 position_b = BtToMathfuVec3(pt.getPositionWorldOnB());
std::string tag_a;
std::string tag_b;
auto physics_a = Data<PhysicsData>(entity_a);
for (int i = 0; i < physics_a->body_count_; i++) {
if (physics_a->rigid_bodies_[i].rigid_body.get() == body_a) {
tag_a = physics_a->rigid_bodies_[i].user_tag;
break;
}
}
auto physics_b = Data<PhysicsData>(entity_b);
for (int i = 0; i < physics_b->body_count_; i++) {
if (physics_b->rigid_bodies_[i].rigid_body.get() == body_b) {
tag_b = physics_b->rigid_bodies_[i].user_tag;
break;
}
}
// Check if GraphComponent exists before trying to read its data.
if (GraphComponent::GetComponentId() != kInvalidComponent) {
auto graph_a = Data<GraphData>(entity_a);
auto graph_b = Data<GraphData>(entity_b);
// Broadcast that a collision event has occured, and then execute all
// collision graphs on both entities involved in the collision.
ExecuteGraphs(&collision_data_, graph_a, entity_a, position_a, tag_a,
entity_b, position_b, tag_b);
ExecuteGraphs(&collision_data_, graph_b, entity_b, position_b, tag_b,
entity_a, position_a, tag_a);
}
// If a collision callback has been registered, call that as well.
if (collision_callback_) {
collision_callback_(&collision_data_, collision_user_data_);
}
}
}
}
}
// Physics component requires that you have a transform component:
void PhysicsComponent::InitEntity(corgi::EntityRef& entity) {
entity_manager_->AddEntityToComponent<TransformComponent>(entity);
}
void PhysicsComponent::CleanupEntity(corgi::EntityRef& entity) {
DisablePhysics(entity);
}
void PhysicsComponent::EnablePhysics(const corgi::EntityRef& entity) {
PhysicsData* physics_data = Data<PhysicsData>(entity);
if (physics_data != nullptr && !physics_data->enabled_) {
physics_data->enabled_ = true;
for (int i = 0; i < physics_data->body_count_; i++) {
auto rb_data = &physics_data->rigid_bodies_[i];
bullet_world_->addRigidBody(rb_data->rigid_body.get(),
rb_data->collision_type,
rb_data->collides_with);
}
}
}
void PhysicsComponent::DisablePhysics(const corgi::EntityRef& entity) {
PhysicsData* physics_data = Data<PhysicsData>(entity);
if (physics_data != nullptr && physics_data->enabled_) {
physics_data->enabled_ = false;
for (int i = 0; i < physics_data->body_count_; i++) {
auto rb_data = &physics_data->rigid_bodies_[i];
bullet_world_->removeRigidBody(rb_data->rigid_body.get());
}
}
}
void PhysicsComponent::ClearPhysicsData(const corgi::EntityRef& entity) {
PhysicsData* physics_data = Data<PhysicsData>(entity);
if (physics_data != nullptr) {
DisablePhysics(entity);
for (int i = 0; i < physics_data->body_count_; ++i) {
auto rb_data = &physics_data->rigid_bodies_[i];
rb_data->motion_state.reset();
rb_data->shape.reset();
rb_data->rigid_body.reset();
}
physics_data->body_count_ = 0;
}
}
void PhysicsComponent::UpdatePhysicsFromTransform(
const corgi::EntityRef& entity) {
// Update all objects on the entity, not just kinematic ones. Also needs to
// check for updates on the scale.
UpdatePhysicsObjectsTransform(entity, false);
UpdatePhysicsScale(entity);
}
void PhysicsComponent::UpdatePhysicsObjectsTransform(
const corgi::EntityRef& entity, bool kinematic_only) {
if (Data<PhysicsData>(entity) == nullptr) return;
PhysicsData* physics_data = Data<PhysicsData>(entity);
TransformData* transform_data = Data<TransformData>(entity);
TransformComponent* transform_component = GetComponent<TransformComponent>();
mathfu::vec3 world_position = transform_component->WorldPosition(entity);
mathfu::quat world_orientation =
transform_component->WorldOrientation(entity);
btQuaternion orientation = ToBtQuaternion(world_orientation);
for (int i = 0; i < physics_data->body_count_; i++) {
auto rb_data = &physics_data->rigid_bodies_[i];
if (kinematic_only && !rb_data->rigid_body->isKinematicObject()) {
continue;
}
vec3 local_offset =
vec3::HadamardProduct(rb_data->offset, transform_data->scale);
vec3 offset = world_orientation.Inverse() * local_offset;
btVector3 position = ToBtVector3(world_position + offset);
btTransform transform(orientation, position);
rb_data->rigid_body->setWorldTransform(transform);
rb_data->motion_state->setWorldTransform(transform);
}
}
void PhysicsComponent::UpdatePhysicsScale(const corgi::EntityRef& entity) {
if (Data<PhysicsData>(entity) == nullptr) return;
PhysicsData* physics_data = Data<PhysicsData>(entity);
TransformData* transform_data = Data<TransformData>(entity);
for (int i = 0; i < physics_data->body_count_; i++) {
auto rb_data = &physics_data->rigid_bodies_[i];
const btVector3& localScale = rb_data->shape->getLocalScaling();
// Bullet doesn't handle a negative scale, so prevent any from being set.
const btVector3 newScale(fabs(transform_data->scale.x),
fabs(transform_data->scale.y),
fabs(transform_data->scale.z));
if ((localScale - newScale).length2() > FLT_EPSILON) {
// If the scale has changed, the rigid body needs to be removed from the
// world, updated accordingly, and added back in.
bullet_world_->removeRigidBody(rb_data->rigid_body.get());
rb_data->shape->setLocalScaling(newScale);
if (rb_data->shape->getShapeType() != EMPTY_SHAPE_PROXYTYPE &&
!rb_data->rigid_body->isStaticObject()) {
btVector3 localInertia;
float invMass = rb_data->rigid_body->getInvMass();
float mass = invMass ? 1.0f / invMass : 0.0f;
rb_data->shape->calculateLocalInertia(mass, localInertia);
rb_data->rigid_body->setMassProps(mass, localInertia);
}
bullet_world_->addRigidBody(rb_data->rigid_body.get(),
rb_data->collision_type,
rb_data->collides_with);
}
}
}
void PhysicsComponent::AwakenEntity(const corgi::EntityRef& entity) {
PhysicsData* physics_data = Data<PhysicsData>(entity);
if (physics_data != nullptr && physics_data->enabled_) {
for (int i = 0; i < physics_data->body_count_; i++) {
auto rb_data = &physics_data->rigid_bodies_[i];
if (!rb_data->rigid_body->isKinematicObject()) {
rb_data->rigid_body->activate();
}
}
}
}
void PhysicsComponent::AwakenAllEntities() {
for (auto iter = component_data_.begin(); iter != component_data_.end();
++iter) {
AwakenEntity(iter->entity);
}
}
void PhysicsComponent::InitStaticMesh(corgi::EntityRef& entity) {
PhysicsData* data = AddEntity(entity);
// Instantiate a holder for the triangle data. Note that the reset clears any
// previous data that might have been created.
data->triangle_mesh_.reset(new btTriangleMesh());
}
void PhysicsComponent::AddStaticMeshTriangle(const corgi::EntityRef& entity,
const vec3& pt0, const vec3& pt1,
const vec3& pt2) {
PhysicsData* data = GetComponentData(entity);
assert(data != nullptr && data->triangle_mesh_.get() != nullptr);
data->triangle_mesh_->addTriangle(ToBtVector3(pt0), ToBtVector3(pt1),
ToBtVector3(pt2));
}
void PhysicsComponent::FinalizeStaticMesh(const corgi::EntityRef& entity,
short collision_type,
short collides_with, float mass,
float restitution,
const std::string& user_tag) {
PhysicsData* data = GetComponentData(entity);
assert(data != nullptr && data->triangle_mesh_.get() != nullptr);
// If there are no triangles, there is nothing to add.
if (data->triangle_mesh_->getNumTriangles() == 0) {
return;
}
// If a static mesh was already defined, replace it.
// Otherwise a new shape needs to be added for it.
RigidBodyData* rb_data = nullptr;
for (int i = 0; i < data->body_count_; i++) {
if (data->rigid_bodies_[i].shape.get() != nullptr &&
data->rigid_bodies_[i].shape->getShapeType() ==
TRIANGLE_MESH_SHAPE_PROXYTYPE) {
rb_data = &data->rigid_bodies_[i];
bullet_world_->removeRigidBody(rb_data->rigid_body.get());
break;
}
}
if (rb_data == nullptr) {
assert(data->body_count_ < kMaxPhysicsBodies);
rb_data = &data->rigid_bodies_[data->body_count_++];
}
rb_data->shape.reset(
new btBvhTriangleMeshShape(data->triangle_mesh_.get(), false));
rb_data->collision_type = collision_type;
rb_data->collides_with = collides_with;
rb_data->should_export = false;
rb_data->offset = mathfu::kZeros3f;
rb_data->motion_state.reset(new btDefaultMotionState());
btVector3 inertia(0.0f, 0.0f, 0.0f);
btRigidBody::btRigidBodyConstructionInfo rigid_body_builder(
mass, rb_data->motion_state.get(), rb_data->shape.get(), inertia);
rigid_body_builder.m_restitution = restitution;
rb_data->rigid_body.reset(new btRigidBody(rigid_body_builder));
rb_data->rigid_body->setUserIndex(static_cast<int>(entity.index()));
rb_data->rigid_body->setUserPointer(entity.container());
rb_data->rigid_body->setCollisionFlags(
rb_data->rigid_body->getCollisionFlags() |
btCollisionObject::CF_KINEMATIC_OBJECT);
rb_data->user_tag = user_tag;
bullet_world_->addRigidBody(rb_data->rigid_body.get(),
rb_data->collision_type, rb_data->collides_with);
data->enabled_ = true;
}
corgi::EntityRef PhysicsComponent::RaycastSingle(mathfu::vec3& start,
mathfu::vec3& end) {
return RaycastSingle(start, end, BulletCollisionType_Raycast, nullptr);
}
corgi::EntityRef PhysicsComponent::RaycastSingle(mathfu::vec3& start,
mathfu::vec3& end,
short layer_mask) {
return RaycastSingle(start, end, layer_mask, nullptr);
}
corgi::EntityRef PhysicsComponent::RaycastSingle(mathfu::vec3& start,
mathfu::vec3& end,
mathfu::vec3* hit_point) {
return RaycastSingle(start, end, BulletCollisionType_Raycast, hit_point);
}
corgi::EntityRef PhysicsComponent::RaycastSingle(mathfu::vec3& start,
mathfu::vec3& end,
short layer_mask,
mathfu::vec3* hit_point) {
btVector3 bt_start = ToBtVector3(start);
btVector3 bt_end = ToBtVector3(end);
btCollisionWorld::ClosestRayResultCallback ray_results(bt_start, bt_end);
ray_results.m_collisionFilterGroup = layer_mask;
bullet_world_->rayTest(bt_start, bt_end, ray_results);
if (ray_results.hasHit()) {
auto container = static_cast<VectorPool<corgi::Entity>*>(
ray_results.m_collisionObject->getUserPointer());
if (container != nullptr) {
if (hit_point != nullptr)
*hit_point = BtToMathfuVec3(ray_results.m_hitPointWorld);
return corgi::EntityRef(container,
ray_results.m_collisionObject->getUserIndex());
}
}
return corgi::EntityRef();
}
void PhysicsComponent::GenerateRaycastShape(corgi::EntityRef& entity,
bool result_exportable) {
PhysicsData* data = GetComponentData(entity);
if (data == nullptr || data->body_count_ == kMaxPhysicsBodies) {
return;
}
// If the entity is already raycastable, there isn't a need to do anything
for (int index = 0; index < data->body_count_; ++index) {
auto shape = &data->rigid_bodies_[index];
if (shape->collides_with & BulletCollisionType_Raycast) {
return;
}
}
auto transform_data = Data<TransformData>(entity);
// Add an AABB about the entity for raycasting purposes
vec3 max(-FLT_MAX);
vec3 min(FLT_MAX);
if (!GetMaxMinPositionsForEntity(entity, *entity_manager_, &max, &min)) {
max = min = mathfu::kZeros3f;
} else {
// Bullet physics handles the scale itself, so it needs to be removed here.
max /= transform_data->scale;
min /= transform_data->scale;
}
auto rb_data = &data->rigid_bodies_[data->body_count_++];
// Make sure it is at least one unit in each direction
vec3 extents = vec3::Max(max - min, mathfu::kOnes3f);
btVector3 bt_extents = ToBtVector3(extents);
rb_data->offset = (max + min) / 2.0f;
rb_data->shape.reset(new btBoxShape(bt_extents / 2.0f));
rb_data->shape->setLocalScaling(btVector3(fabs(transform_data->scale.x),
fabs(transform_data->scale.y),
fabs(transform_data->scale.z)));
vec3 local_offset =
vec3::HadamardProduct(rb_data->offset, transform_data->scale);
vec3 transformed_offset =
transform_data->orientation.Inverse() * local_offset;
btVector3 position =
ToBtVector3(transform_data->position + transformed_offset);
btQuaternion orientation = ToBtQuaternion(transform_data->orientation);
rb_data->motion_state.reset(
new btDefaultMotionState(btTransform(orientation, position)));
btRigidBody::btRigidBodyConstructionInfo rigid_body_builder(
0, rb_data->motion_state.get(), rb_data->shape.get(), btVector3());
rb_data->rigid_body.reset(new btRigidBody(rigid_body_builder));
rb_data->rigid_body->setUserIndex(static_cast<int>(entity.index()));
rb_data->rigid_body->setUserPointer(entity.container());
rb_data->rigid_body->setCollisionFlags(
rb_data->rigid_body->getCollisionFlags() |
btCollisionObject::CF_KINEMATIC_OBJECT);
rb_data->collision_type = BulletCollisionType_Raycast;
rb_data->collides_with = BulletCollisionType_Raycast;
rb_data->should_export = result_exportable;
bullet_world_->addRigidBody(rb_data->rigid_body.get(),
rb_data->collision_type, rb_data->collides_with);
data->enabled_ = true;
}
float PhysicsComponent::GravityForEntity(const corgi::EntityRef& entity) const {
auto physics_data = Data<PhysicsData>(entity);
assert(physics_data);
return physics_data->gravity_multiplier_ * gravity();
}
void PhysicsComponent::DebugDrawWorld(Renderer* renderer,
const mathfu::mat4& camera_transform) {
renderer->set_model_view_projection(camera_transform);
debug_drawer_->set_renderer(renderer);
bullet_world_->debugDrawWorld();
}
void PhysicsComponent::DebugDrawObject(Renderer* renderer,
const mathfu::mat4& camera_transform,
const corgi::EntityRef& entity,
const mathfu::vec3& color) {
auto physics_data = Data<PhysicsData>(entity);
if (physics_data == nullptr) {
return;
}
renderer->set_model_view_projection(camera_transform);
debug_drawer_->set_renderer(renderer);
for (int i = 0; i < physics_data->body_count_; i++) {
auto rb_data = &physics_data->rigid_bodies_[i];
bullet_world_->debugDrawObject(rb_data->rigid_body->getWorldTransform(),
rb_data->shape.get(), ToBtVector3(color));
}
}
void PhysicsDebugDrawer::drawLine(const btVector3& from, const btVector3& to,
const btVector3& color) {
if (renderer_ != nullptr) {
renderer_->set_color(vec4(color.x(), color.y(), color.z(), 1.0f));
if (shader_ != nullptr) {
shader_->Set(*renderer_);
}
}
static const fplbase::Attribute attributes[] = {fplbase::kPosition3f,
fplbase::kEND};
static const unsigned short indices[] = {0, 1};
const btVector3 vertices[] = {from, to};
fplbase::Mesh::RenderArray(fplbase::Mesh::kLines, 2, attributes,
sizeof(btVector3),
reinterpret_cast<const char*>(vertices), indices);
}
} // component_library
} // corgi
| 41.350472 | 80 | 0.672216 | diederickh |
58ee6601c0d4e952ea5a78e4afd65c19923ad53d | 27,194 | cpp | C++ | Plugins/Renderer/gl_hud.cpp | fengjixuchui/MetaHookSv | a07d0629338100342dc4f8f1bb2b830455d214b0 | [
"MIT"
] | 1 | 2021-03-10T06:22:11.000Z | 2021-03-10T06:22:11.000Z | Plugins/Renderer/gl_hud.cpp | fengjixuchui/MetaHookSv | a07d0629338100342dc4f8f1bb2b830455d214b0 | [
"MIT"
] | null | null | null | Plugins/Renderer/gl_hud.cpp | fengjixuchui/MetaHookSv | a07d0629338100342dc4f8f1bb2b830455d214b0 | [
"MIT"
] | 1 | 2021-02-28T16:05:22.000Z | 2021-02-28T16:05:22.000Z | #include "gl_local.h"
#include <sstream>
//HDR
int last_luminance = 0;
#define MAX_GAUSSIAN_SAMPLES 16
#define LUMPASS_DOWN 0
#define LUMPASS_LOG 1
#define LUMPASS_EXP 2
//HBAO
#define AO_RANDOMTEX_SIZE 4
static const int NUM_MRT = 8;
static const int HBAO_RANDOM_SIZE = AO_RANDOMTEX_SIZE;
static const int HBAO_RANDOM_ELEMENTS = HBAO_RANDOM_SIZE * HBAO_RANDOM_SIZE;
static const int MAX_SAMPLES = 16;
GLuint hbao_random = 0;
GLuint hbao_randomview[MAX_SAMPLES] = { 0 };
vec4_t m_hbaoRandom[HBAO_RANDOM_ELEMENTS * MAX_SAMPLES] = { 0 };
//FXAA
SHADER_DEFINE(pp_fxaa);
//HDR
SHADER_DEFINE(pp_downsample);
SHADER_DEFINE(pp_downsample2x2);
SHADER_DEFINE(pp_lumindown);
SHADER_DEFINE(pp_luminlog);
SHADER_DEFINE(pp_luminexp);
SHADER_DEFINE(pp_luminadapt);
SHADER_DEFINE(pp_brightpass);
SHADER_DEFINE(pp_gaussianblurv);
SHADER_DEFINE(pp_gaussianblurh);
SHADER_DEFINE(pp_tonemap);
//HBAO
SHADER_DEFINE(depth_linearize);
SHADER_DEFINE(hbao_calc_blur);
SHADER_DEFINE(hbao_calc_blur_fog);
SHADER_DEFINE(hbao_blur);
SHADER_DEFINE(hbao_blur2);
SHADER_DEFINE(depth_clear);
SHADER_DEFINE(oitbuffer_clear);
SHADER_DEFINE(blit_oitblend);
SHADER_DEFINE(gamma_correction);
cvar_t *r_hdr = NULL;
cvar_t *r_hdr_debug = NULL;
MapConVar *r_hdr_blurwidth = NULL;
MapConVar *r_hdr_exposure = NULL;
MapConVar *r_hdr_darkness = NULL;
MapConVar *r_hdr_adaptation = NULL;
cvar_t *r_fxaa = NULL;
cvar_t *r_ssao = NULL;
cvar_t *r_ssao_debug = NULL;
MapConVar *r_ssao_radius = NULL;
MapConVar *r_ssao_intensity = NULL;
MapConVar *r_ssao_bias = NULL;
MapConVar *r_ssao_blur_sharpness = NULL;
std::unordered_map<int, hud_debug_program_t> g_HudDebugProgramTable;
void R_UseHudDebugProgram(int state, hud_debug_program_t *progOutput)
{
hud_debug_program_t prog = { 0 };
auto itor = g_HudDebugProgramTable.find(state);
if (itor == g_HudDebugProgramTable.end())
{
std::stringstream defs;
if (state & HUD_DEBUG_TEXARRAY)
defs << "#define TEXARRAY_ENABLED\n";
auto def = defs.str();
prog.program = R_CompileShaderFileEx("renderer\\shader\\hud_debug.vsh", "renderer\\shader\\hud_debug.fsh", def.c_str(), def.c_str(), NULL);
if (prog.program)
{
SHADER_UNIFORM(prog, basetex, "basetex");
SHADER_UNIFORM(prog, layer , "layer");
}
g_HudDebugProgramTable[state] = prog;
}
else
{
prog = itor->second;
}
if (prog.program)
{
GL_UseProgram(prog.program);
if (prog.basetex != -1)
glUniform1i(prog.basetex, 0);
if (progOutput)
*progOutput = prog;
}
else
{
Sys_ErrorEx("R_UseHudDebugProgram: Failed to load program!");
}
}
void R_InitPostProcess(void)
{
float numDir = 8; // keep in sync to glsl
signed short hbaoRandomShort[HBAO_RANDOM_ELEMENTS * MAX_SAMPLES * 4];
for (int i = 0; i < HBAO_RANDOM_ELEMENTS * MAX_SAMPLES; i++)
{
float Rand1 = gEngfuncs.pfnRandomFloat(0, 1);
float Rand2 = gEngfuncs.pfnRandomFloat(0, 1);
// Use random rotation angles in [0,2PI/NUM_DIRECTIONS)
float Angle = 2.f * M_PI * Rand1 / numDir;
m_hbaoRandom[i][0] = cosf(Angle);
m_hbaoRandom[i][1] = sinf(Angle);
m_hbaoRandom[i][2] = Rand2;
m_hbaoRandom[i][3] = 0;
#define SCALE ((1<<15))
hbaoRandomShort[i * 4 + 0] = (signed short)(SCALE*m_hbaoRandom[i][0]);
hbaoRandomShort[i * 4 + 1] = (signed short)(SCALE*m_hbaoRandom[i][1]);
hbaoRandomShort[i * 4 + 2] = (signed short)(SCALE*m_hbaoRandom[i][2]);
hbaoRandomShort[i * 4 + 3] = (signed short)(SCALE*m_hbaoRandom[i][3]);
#undef SCALE
}
hbao_random = GL_GenTexture();
glBindTexture(GL_TEXTURE_2D_ARRAY, hbao_random);
glTexStorage3D(GL_TEXTURE_2D_ARRAY, 1, GL_RGBA16_SNORM, HBAO_RANDOM_SIZE, HBAO_RANDOM_SIZE, MAX_SAMPLES);
glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, 0, HBAO_RANDOM_SIZE, HBAO_RANDOM_SIZE, MAX_SAMPLES, GL_RGBA, GL_SHORT, hbaoRandomShort);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBindTexture(GL_TEXTURE_2D_ARRAY, 0);
for (int i = 0; i < MAX_SAMPLES; i++)
{
hbao_randomview[i] = GL_GenTexture();
glTextureView(hbao_randomview[i], GL_TEXTURE_2D, hbao_random, GL_RGBA16_SNORM, 0, 1, i, 1);
glBindTexture(GL_TEXTURE_2D, hbao_randomview[i]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBindTexture(GL_TEXTURE_2D, 0);
}
//FXAA Pass
pp_fxaa.program = R_CompileShaderFile("renderer\\shader\\pp_fxaa.vsh", "renderer\\shader\\pp_fxaa.fsh", NULL);
SHADER_UNIFORM(pp_fxaa, tex0, "tex0");
SHADER_UNIFORM(pp_fxaa, rt_w, "rt_w");
SHADER_UNIFORM(pp_fxaa, rt_h, "rt_h");
//DownSample Pass
pp_downsample.program = R_CompileShaderFile("renderer\\shader\\fullscreentriangle.vert.glsl", "renderer\\shader\\down_sample.frag.glsl", NULL);
//2x2 Downsample Pass
pp_downsample2x2.program = R_CompileShaderFileEx("renderer\\shader\\fullscreentriangle.vert.glsl", "renderer\\shader\\down_sample.frag.glsl", "", "#define DOWNSAMPLE_2X2\n", NULL);
SHADER_UNIFORM(pp_downsample2x2, texelsize, "texelsize");
//Luminance Downsample Pass
pp_lumindown.program = R_CompileShaderFileEx("renderer\\shader\\fullscreentriangle.vert.glsl", "renderer\\shader\\hdr_lumpass.frag.glsl", "", "", NULL);
SHADER_UNIFORM(pp_lumindown, texelsize, "texelsize");
//Log Luminance Downsample Pass
pp_luminlog.program = R_CompileShaderFileEx("renderer\\shader\\fullscreentriangle.vert.glsl", "renderer\\shader\\hdr_lumpass.frag.glsl", "", "#define LUMPASS_LOG\n", NULL);
SHADER_UNIFORM(pp_luminlog, texelsize, "texelsize");
//Exp Luminance Downsample Pass
pp_luminexp.program = R_CompileShaderFileEx("renderer\\shader\\fullscreentriangle.vert.glsl", "renderer\\shader\\hdr_lumpass.frag.glsl", "", "#define LUMPASS_EXP\n", NULL);
SHADER_UNIFORM(pp_luminexp, texelsize, "texelsize");
//Luminance Adaptation Downsample Pass
pp_luminadapt.program = R_CompileShaderFileEx("renderer\\shader\\fullscreentriangle.vert.glsl", "renderer\\shader\\hdr_adaption.frag.glsl", "", "", NULL);
SHADER_UNIFORM(pp_luminadapt, frametime, "frametime");
//Bright Pass
pp_brightpass.program = R_CompileShaderFileEx("renderer\\shader\\fullscreentriangle.vert.glsl", "renderer\\shader\\hdr_brightpass.frag.glsl", "#define LUMTEX_ENABLED\n", "", NULL);
SHADER_UNIFORM(pp_brightpass, baseTex, "baseTex");
SHADER_UNIFORM(pp_brightpass, lumTex, "lumTex");
//Tone mapping
pp_tonemap.program = R_CompileShaderFileEx("renderer\\shader\\fullscreentriangle.vert.glsl", "renderer\\shader\\hdr_tonemap.frag.glsl", "#define LUMTEX_ENABLED\n#define TONEMAP_ENABLED\n", "", NULL);
SHADER_UNIFORM(pp_tonemap, baseTex, "baseTex");
SHADER_UNIFORM(pp_tonemap, blurTex, "blurTex");
SHADER_UNIFORM(pp_tonemap, lumTex, "lumTex");
SHADER_UNIFORM(pp_tonemap, blurfactor, "blurfactor");
SHADER_UNIFORM(pp_tonemap, exposure, "exposure");
SHADER_UNIFORM(pp_tonemap, darkness, "darkness");
//SSAO
depth_linearize.program = R_CompileShaderFile("renderer\\shader\\fullscreentriangle.vert.glsl", "renderer\\shader\\depthlinearize.frag.glsl", NULL);
hbao_calc_blur.program = R_CompileShaderFile("renderer\\shader\\fullscreentriangle.vert.glsl", "renderer\\shader\\hbao.frag.glsl", NULL);
depth_clear.program = R_CompileShaderFile("renderer\\shader\\fullscreentriangle.vert.glsl", "renderer\\shader\\depthclear.frag.glsl", NULL);
if (bUseOITBlend)
{
oitbuffer_clear.program = R_CompileShaderFile("renderer\\shader\\fullscreentriangle.vert.glsl", "renderer\\shader\\oitbuffer_clear.frag.glsl", NULL);
blit_oitblend.program = R_CompileShaderFile("renderer\\shader\\fullscreentriangle.vert.glsl", "renderer\\shader\\blit_oitblend.frag.glsl", NULL);
}
gamma_correction.program = R_CompileShaderFile("renderer\\shader\\fullscreentriangle.vert.glsl", "renderer\\shader\\gamma_correction.frag.glsl", NULL);
SHADER_UNIFORM(hbao_calc_blur, texLinearDepth, "texLinearDepth");
SHADER_UNIFORM(hbao_calc_blur, texRandom, "texRandom");
SHADER_UNIFORM(hbao_calc_blur, control_RadiusToScreen, "control_RadiusToScreen");
SHADER_UNIFORM(hbao_calc_blur, control_projOrtho, "control_projOrtho");
SHADER_UNIFORM(hbao_calc_blur, control_projInfo, "control_projInfo");
SHADER_UNIFORM(hbao_calc_blur, control_PowExponent, "control_PowExponent");
SHADER_UNIFORM(hbao_calc_blur, control_InvQuarterResolution, "control_InvQuarterResolution");
SHADER_UNIFORM(hbao_calc_blur, control_AOMultiplier, "control_AOMultiplier");
SHADER_UNIFORM(hbao_calc_blur, control_InvFullResolution, "control_InvFullResolution");
SHADER_UNIFORM(hbao_calc_blur, control_NDotVBias, "control_NDotVBias");
SHADER_UNIFORM(hbao_calc_blur, control_NegInvR2, "control_NegInvR2");
hbao_calc_blur_fog.program = R_CompileShaderFileEx("renderer\\shader\\fullscreentriangle.vert.glsl", "renderer\\shader\\hbao.frag.glsl",
"#define LINEAR_FOG_ENABLED\n", "#define LINEAR_FOG_ENABLED\n", NULL);
SHADER_UNIFORM(hbao_calc_blur_fog, texLinearDepth, "texLinearDepth");
SHADER_UNIFORM(hbao_calc_blur_fog, texRandom, "texRandom");
SHADER_UNIFORM(hbao_calc_blur_fog, control_RadiusToScreen, "control_RadiusToScreen");
SHADER_UNIFORM(hbao_calc_blur_fog, control_projOrtho, "control_projOrtho");
SHADER_UNIFORM(hbao_calc_blur_fog, control_projInfo, "control_projInfo");
SHADER_UNIFORM(hbao_calc_blur_fog, control_PowExponent, "control_PowExponent");
SHADER_UNIFORM(hbao_calc_blur_fog, control_InvQuarterResolution, "control_InvQuarterResolution");
SHADER_UNIFORM(hbao_calc_blur_fog, control_AOMultiplier, "control_AOMultiplier");
SHADER_UNIFORM(hbao_calc_blur_fog, control_InvFullResolution, "control_InvFullResolution");
SHADER_UNIFORM(hbao_calc_blur_fog, control_NDotVBias, "control_NDotVBias");
SHADER_UNIFORM(hbao_calc_blur_fog, control_NegInvR2, "control_NegInvR2");
SHADER_UNIFORM(hbao_calc_blur_fog, control_Fog, "control_Fog");
hbao_blur.program = R_CompileShaderFile("renderer\\shader\\fullscreentriangle.vert.glsl", "renderer\\shader\\hbao_blur.frag.glsl", NULL);
hbao_blur2.program = R_CompileShaderFileEx("renderer\\shader\\fullscreentriangle.vert.glsl", "renderer\\shader\\hbao_blur.frag.glsl",
"#define AO_BLUR_PRESENT\n", "#define AO_BLUR_PRESENT\n", NULL);
pp_gaussianblurh.program = R_CompileShaderFileEx("renderer\\shader\\fullscreentriangle.vert.glsl", "renderer\\shader\\gaussian_blur_16x.frag.glsl", "", "#define BLUR_HORIZONAL\n", NULL);
pp_gaussianblurv.program = R_CompileShaderFileEx("renderer\\shader\\fullscreentriangle.vert.glsl", "renderer\\shader\\gaussian_blur_16x.frag.glsl", "", "#define BLUR_VERTICAL\n", NULL);
r_hdr = gEngfuncs.pfnRegisterVariable("r_hdr", "1", FCVAR_ARCHIVE | FCVAR_CLIENTDLL);
r_hdr_debug = gEngfuncs.pfnRegisterVariable("r_hdr_debug", "0", FCVAR_CLIENTDLL);
r_hdr_blurwidth = R_RegisterMapCvar("r_hdr_blurwidth", "0.075", FCVAR_ARCHIVE | FCVAR_CLIENTDLL);
r_hdr_exposure = R_RegisterMapCvar("r_hdr_exposure", "0.8", FCVAR_ARCHIVE | FCVAR_CLIENTDLL);
r_hdr_darkness = R_RegisterMapCvar("r_hdr_darkness", "1.4", FCVAR_ARCHIVE | FCVAR_CLIENTDLL);
r_hdr_adaptation = R_RegisterMapCvar("r_hdr_adaptation", "50", FCVAR_ARCHIVE | FCVAR_CLIENTDLL);
r_fxaa = gEngfuncs.pfnRegisterVariable("r_fxaa", "1", FCVAR_ARCHIVE | FCVAR_CLIENTDLL);
r_ssao = gEngfuncs.pfnRegisterVariable("r_ssao", "1", FCVAR_ARCHIVE | FCVAR_CLIENTDLL);
r_ssao_debug = gEngfuncs.pfnRegisterVariable("r_ssao_debug", "0", FCVAR_CLIENTDLL);
r_ssao_radius = R_RegisterMapCvar("r_ssao_radius", "30.0", FCVAR_ARCHIVE | FCVAR_CLIENTDLL);
r_ssao_intensity = R_RegisterMapCvar("r_ssao_intensity", "3.0", FCVAR_ARCHIVE | FCVAR_CLIENTDLL);
r_ssao_bias = R_RegisterMapCvar("r_ssao_bias", "0.2", FCVAR_ARCHIVE | FCVAR_CLIENTDLL);
r_ssao_blur_sharpness = R_RegisterMapCvar("r_ssao_blur_sharpness", "1.0", FCVAR_ARCHIVE | FCVAR_CLIENTDLL);
last_luminance = 0;
}
void R_ShutdownPostProcess(void)
{
}
void R_DrawHUDQuad(int w, int h)
{
glBegin(GL_QUADS);
glTexCoord2f(0, 0);
glVertex3f(0, h, -1);
glTexCoord2f(0, 1);
glVertex3f(0, 0, -1);
glTexCoord2f(1, 1);
glVertex3f(w, 0, -1);
glTexCoord2f(1, 0);
glVertex3f(w, h, -1);
glEnd();
}
void R_DrawHUDQuad_Texture(int tex, int w, int h)
{
GL_Bind(tex);
R_DrawHUDQuad(w, h);
}
void GL_BlitFrameFufferToScreen(FBO_Container_t *src)
{
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glBindFramebuffer(GL_READ_FRAMEBUFFER, src->s_hBackBufferFBO);
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
glBlitFramebuffer(0, 0, src->iWidth, src->iHeight, 0, 0, glwidth, glheight, GL_COLOR_BUFFER_BIT, GL_LINEAR);
}
void GL_BlitFrameBufferToFrameBufferColorOnly(FBO_Container_t *src, FBO_Container_t *dst)
{
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, dst->s_hBackBufferFBO);
glBindFramebuffer(GL_READ_FRAMEBUFFER, src->s_hBackBufferFBO);
glBlitFramebuffer(0, 0, src->iWidth, src->iHeight, 0, 0, dst->iWidth, dst->iHeight, GL_COLOR_BUFFER_BIT, GL_LINEAR);
}
void GL_BlitFrameBufferToFrameBufferColorDepth(FBO_Container_t *src, FBO_Container_t *dst)
{
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, dst->s_hBackBufferFBO);
glBindFramebuffer(GL_READ_FRAMEBUFFER, src->s_hBackBufferFBO);
glBlitFramebuffer(0, 0, src->iWidth, src->iHeight, 0, 0, dst->iWidth, dst->iHeight, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST);
}
void R_DownSample(FBO_Container_t *src, FBO_Container_t *dst, qboolean filter2x2)
{
glBindFramebuffer(GL_FRAMEBUFFER, dst->s_hBackBufferFBO);
glClearColor(0, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);
if(filter2x2)
{
GL_UseProgram(pp_downsample2x2.program);
glUniform2f(pp_downsample2x2.texelsize, 2.0f / src->iWidth, 2.0f / src->iHeight);
}
else
{
GL_UseProgram(pp_downsample.program);
}
glViewport(glx, gly, dst->iWidth, dst->iHeight);
GL_Bind(src->s_hBackBufferTex);
glDrawArrays(GL_TRIANGLES, 0, 3);
}
void R_LuminPass(FBO_Container_t *src, FBO_Container_t *dst, int type)
{
glBindFramebuffer(GL_FRAMEBUFFER, dst->s_hBackBufferFBO);
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
if(type == LUMPASS_LOG)
{
GL_UseProgram(pp_luminlog.program);
glUniform2f(pp_luminlog.texelsize, 2.0f / src->iWidth, 2.0f / src->iHeight);
}
else if(type == LUMPASS_EXP)
{
GL_UseProgram(pp_luminexp.program);
glUniform2f(pp_luminexp.texelsize, 2.0f / src->iWidth, 2.0f / src->iHeight);
}
else
{
GL_UseProgram(pp_lumindown.program);
glUniform2f(pp_lumindown.texelsize, 2.0f / src->iWidth, 2.0f / src->iHeight);
}
glViewport(glx, gly, dst->iWidth, dst->iHeight);
GL_Bind(src->s_hBackBufferTex);
glDrawArrays(GL_TRIANGLES, 0, 3);
}
void R_LuminAdaptation(FBO_Container_t *src, FBO_Container_t *dst, FBO_Container_t *ada, double frametime)
{
glBindFramebuffer(GL_FRAMEBUFFER, dst->s_hBackBufferFBO);
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
GL_UseProgram(pp_luminadapt.program);
glUniform1f(pp_luminadapt.frametime, frametime * clamp(r_hdr_adaptation->GetValue(), 0.1, 100));
glViewport(glx, gly, dst->iWidth, dst->iHeight);
GL_SelectTexture(GL_TEXTURE0);
GL_Bind(src->s_hBackBufferTex);
GL_EnableMultitexture();
GL_Bind(ada->s_hBackBufferTex);
glDrawArrays(GL_TRIANGLES, 0, 3);
GL_DisableMultitexture();
}
void R_BrightPass(FBO_Container_t *src, FBO_Container_t *dst, FBO_Container_t *lum)
{
glBindFramebuffer(GL_FRAMEBUFFER, dst->s_hBackBufferFBO);
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
GL_UseProgram(pp_brightpass.program);
glUniform1i(pp_brightpass.baseTex, 0);
glUniform1i(pp_brightpass.lumTex, 1);
glViewport(glx, gly, dst->iWidth, dst->iHeight);
GL_SelectTexture(GL_TEXTURE0);
GL_Bind(src->s_hBackBufferTex);
GL_EnableMultitexture();
GL_Bind(lum->s_hBackBufferTex);
glDrawArrays(GL_TRIANGLES, 0, 3);
GL_DisableMultitexture();
}
void R_BlurPass(FBO_Container_t *src, FBO_Container_t *dst, qboolean vertical)
{
glBindFramebuffer(GL_FRAMEBUFFER, dst->s_hBackBufferFBO);
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
if(vertical)
{
GL_UseProgram(pp_gaussianblurv.program);
glUniform1f(0, 1.0f / src->iHeight);
}
else
{
GL_UseProgram(pp_gaussianblurh.program);
glUniform1f(0, 1.0f / src->iWidth);
}
glViewport(glx, gly, dst->iWidth, dst->iHeight);
GL_Bind(src->s_hBackBufferTex);
glDrawArrays(GL_TRIANGLES, 0, 3);
}
void R_BrightAccum(FBO_Container_t *blur1, FBO_Container_t *blur2, FBO_Container_t *blur3, FBO_Container_t *dst)
{
glBindFramebuffer(GL_FRAMEBUFFER, dst->s_hBackBufferFBO);
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE);
GL_UseProgram(pp_downsample.program);
glViewport(glx, gly, dst->iWidth, dst->iHeight);
GL_Bind(blur1->s_hBackBufferTex);
glDrawArrays(GL_TRIANGLES, 0, 3);
GL_Bind(blur2->s_hBackBufferTex);
glDrawArrays(GL_TRIANGLES, 0, 3);
GL_Bind(blur3->s_hBackBufferTex);
glDrawArrays(GL_TRIANGLES, 0, 3);
glDisable(GL_BLEND);
}
void R_ToneMapping(FBO_Container_t *src, FBO_Container_t *dst, FBO_Container_t *blur, FBO_Container_t *lum)
{
glBindFramebuffer(GL_FRAMEBUFFER, dst->s_hBackBufferFBO);
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
GL_UseProgram(pp_tonemap.program);
glUniform1i(pp_tonemap.baseTex, 0);
glUniform1i(pp_tonemap.blurTex, 1);
glUniform1i(pp_tonemap.lumTex, 2);
glUniform1f(pp_tonemap.blurfactor, clamp(r_hdr_blurwidth->GetValue(), 0, 1));
glUniform1f(pp_tonemap.exposure, clamp(r_hdr_exposure->GetValue(), 0.001, 10));
glUniform1f(pp_tonemap.darkness, clamp(r_hdr_darkness->GetValue(), 0.001, 10));
GL_Bind(src->s_hBackBufferTex);
GL_EnableMultitexture();
GL_Bind(blur->s_hBackBufferTex);
glActiveTexture(GL_TEXTURE2);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, lum->s_hBackBufferTex);
glViewport(glx, gly, dst->iWidth, dst->iHeight);
glDrawArrays(GL_TRIANGLES, 0, 3);
glActiveTexture(GL_TEXTURE2);
glDisable(GL_TEXTURE_2D);
glActiveTexture(GL_TEXTURE1);
GL_DisableMultitexture();
}
void R_HDR(void)
{
static glprofile_t profile_DoHDR;
GL_BeginProfile(&profile_DoHDR, "R_HDR");
GL_BeginFullScreenQuad(false);
GL_DisableMultitexture();
glEnable(GL_TEXTURE_2D);
glDisable(GL_BLEND);
glColor4f(1, 1, 1, 1);
//Downsample backbuffer
R_DownSample(&s_BackBufferFBO, &s_DownSampleFBO[0], false);//(1->1/4)
R_DownSample(&s_DownSampleFBO[0], &s_DownSampleFBO[1], false);//(1/4)->(1/16)
//Log Luminance DownSample from .. (RGB16F to R32F)
R_LuminPass(&s_DownSampleFBO[1], &s_LuminFBO[0], LUMPASS_LOG);//(1/16)->64x64
//Luminance DownSample from..
R_LuminPass(&s_LuminFBO[0], &s_LuminFBO[1], LUMPASS_DOWN);//64x64->16x16
R_LuminPass(&s_LuminFBO[1], &s_LuminFBO[2], LUMPASS_DOWN);//16x16->4x4
//exp Luminance DownSample from..
R_LuminPass(&s_LuminFBO[2], &s_Lumin1x1FBO[2], LUMPASS_EXP);//4x4->1x1
//Luminance Adaptation
R_LuminAdaptation(&s_Lumin1x1FBO[2], &s_Lumin1x1FBO[!last_luminance], &s_Lumin1x1FBO[last_luminance], *cl_time - *cl_oldtime);
last_luminance = !last_luminance;
//Bright Pass (with 1/16)
R_BrightPass(&s_DownSampleFBO[1], &s_BrightPassFBO, &s_Lumin1x1FBO[last_luminance]);
//Gaussian Blur Pass (with bright pass)
R_BlurPass(&s_BrightPassFBO, &s_BlurPassFBO[0][0], false);
R_BlurPass(&s_BlurPassFBO[0][0], &s_BlurPassFBO[0][1], true);
//Blur again and downsample from 1/16 to 1/32
R_BlurPass(&s_BlurPassFBO[0][1], &s_BlurPassFBO[1][0], false);
R_BlurPass(&s_BlurPassFBO[1][0], &s_BlurPassFBO[1][1], true);
//Blur again and downsample from 1/32 to 1/64
R_BlurPass(&s_BlurPassFBO[1][1], &s_BlurPassFBO[2][0], false);
R_BlurPass(&s_BlurPassFBO[2][0], &s_BlurPassFBO[2][1], true);
//Accumulate all blurred textures
R_BrightAccum(&s_BlurPassFBO[0][1], &s_BlurPassFBO[1][1], &s_BlurPassFBO[2][1], &s_BrightAccumFBO);
//Tone mapping
R_ToneMapping(&s_BackBufferFBO, &s_ToneMapFBO, &s_BrightAccumFBO, &s_Lumin1x1FBO[last_luminance]);
GL_UseProgram(0);
GL_EndFullScreenQuad();
GL_BlitFrameBufferToFrameBufferColorOnly(&s_ToneMapFBO, &s_BackBufferFBO);
GL_EndProfile(&profile_DoHDR);
}
void R_BeginFXAA(int w, int h)
{
GL_UseProgram(pp_fxaa.program);
glUniform1i(pp_fxaa.tex0, 0);
glUniform1f(pp_fxaa.rt_w, w);
glUniform1f(pp_fxaa.rt_h, h);
}
void R_DoFXAA(void)
{
if (!r_fxaa->value)
return;
if (!pp_fxaa.program)
return;
if (r_draw_pass)
return;
if (g_SvEngine_DrawPortalView)
return;
static glprofile_t profile_DoFXAA;
GL_BeginProfile(&profile_DoFXAA, "R_DoFXAA");
GL_PushDrawState();
GL_PushMatrix();
GL_BlitFrameBufferToFrameBufferColorOnly(&s_BackBufferFBO, &s_BackBufferFBO2);
glBindFramebuffer(GL_FRAMEBUFFER, s_BackBufferFBO.s_hBackBufferFBO);
R_BeginFXAA(glwidth, glheight);
GL_Begin2D();
GL_DisableMultitexture();
glEnable(GL_TEXTURE_2D);
glDisable(GL_BLEND);
R_DrawHUDQuad_Texture(s_BackBufferFBO2.s_hBackBufferTex, glwidth, glheight);
GL_UseProgram(0);
GL_PopMatrix();
GL_PopDrawState();
GL_EndProfile(&profile_DoFXAA);
}
void R_GammaCorrection(void)
{
static glprofile_t profile_GammaCorrection;
GL_BeginProfile(&profile_GammaCorrection, "R_GammaCorrection");
GL_BlitFrameBufferToFrameBufferColorOnly(&s_BackBufferFBO, &s_BackBufferFBO2);
glBindFramebuffer(GL_FRAMEBUFFER, s_BackBufferFBO.s_hBackBufferFBO);
GL_BeginFullScreenQuad(false);
glDisable(GL_BLEND);
GL_UseProgram(gamma_correction.program);
GL_Bind(s_BackBufferFBO2.s_hBackBufferTex);
glDrawArrays(GL_TRIANGLES, 0, 3);
GL_UseProgram(0);
GL_EndFullScreenQuad();
GL_EndProfile(&profile_GammaCorrection);
}
void R_ClearOITBuffer(void)
{
GL_BeginFullScreenQuad(false);
GL_UseProgram(oitbuffer_clear.program);
glDrawArrays(GL_TRIANGLES, 0, 3);
GL_UseProgram(0);
GL_EndFullScreenQuad();
GLuint val = 0;
glClearNamedBufferData(r_wsurf.hOITAtomicSSBO, GL_R32UI, GL_RED_INTEGER, GL_UNSIGNED_INT, (const void*)&val);
}
void R_BlendOITBuffer(void)
{
GL_BlitFrameBufferToFrameBufferColorOnly(&s_BackBufferFBO, &s_BackBufferFBO2);
glBindFramebuffer(GL_FRAMEBUFFER, s_BackBufferFBO.s_hBackBufferFBO);
GL_BeginFullScreenQuad(false);
glDisable(GL_BLEND);
GL_UseProgram(blit_oitblend.program);
GL_Bind(s_BackBufferFBO2.s_hBackBufferTex);
glDrawArrays(GL_TRIANGLES, 0, 3);
GL_UseProgram(0);
GL_EndFullScreenQuad();
}
void R_LinearizeDepth(FBO_Container_t *fbo)
{
glBindFramebuffer(GL_FRAMEBUFFER, s_DepthLinearFBO.s_hBackBufferFBO);
glDrawBuffer(GL_COLOR_ATTACHMENT0);
glDisable(GL_BLEND);
GL_UseProgram(depth_linearize.program);
glUniform4f(0, r_znear * r_zfar, r_znear - r_zfar, r_zfar, r_ortho ? 0 : 1);
GL_Bind(fbo->s_hBackBufferDepthTex);
glDrawArrays(GL_TRIANGLES, 0, 3);
}
bool R_IsSSAOEnabled(void)
{
if (!r_ssao->value)
return false;
if ((*r_refdef.onlyClientDraws) || r_draw_pass || g_SvEngine_DrawPortalView)
return false;
if ((*r_xfov) < 75)
return false;
if (CL_IsDevOverviewMode())
return false;
return true;
}
void R_AmbientOcclusion(void)
{
//Prepare parameters
static glprofile_t profile_AmbientOcclusion;
GL_BeginProfile(&profile_AmbientOcclusion, "R_AmbientOcclusion");
const float *ProjMatrix = r_projection_matrix;
float projInfoPerspective[] = {
2.0f / (ProjMatrix[4 * 0 + 0]), // (x) * (R - L)/N
2.0f / (ProjMatrix[4 * 1 + 1]), // (y) * (T - B)/N
-(1.0f - ProjMatrix[4 * 2 + 0]) / ProjMatrix[4 * 0 + 0], // L/N
-(1.0f + ProjMatrix[4 * 2 + 1]) / ProjMatrix[4 * 1 + 1], // B/N
};
float projScale = float(glheight) / (tanf(r_yfov * 0.5f) * 2.0f);
// radius
float meters2viewspace = 1.0f;
float R = r_ssao_radius->GetValue() * meters2viewspace;
auto R2 = R * R;
auto NegInvR2 = -1.0f / R2;
auto RadiusToScreen = R * 0.5f * projScale;
// ao
auto PowExponent = max(r_ssao_intensity->GetValue(), 0.0f);
auto NDotVBias = min(max(0.0f, r_ssao_bias->GetValue()), 1.0f);
auto AOMultiplier = 1.0f / (1.0f - NDotVBias);
// resolution
int quarterWidth = ((glwidth + 3) / 4);
int quarterHeight = ((glheight + 3) / 4);
vec2_t InvQuarterResolution;
InvQuarterResolution[0] = 1.0f / float(quarterWidth);
InvQuarterResolution[1] = 1.0f / float(quarterHeight);
vec2_t InvFullResolution;
InvFullResolution[0] = 1.0f / float(glwidth);
InvFullResolution[1] = 1.0f / float(glheight);
glBindFramebuffer(GL_FRAMEBUFFER, s_HBAOCalcFBO.s_hBackBufferFBO);
glDrawBuffer(GL_COLOR_ATTACHMENT0);
glDisable(GL_BLEND);
//setup args for hbao_calc
if (r_fog_mode == GL_LINEAR)
{
GL_UseProgram(hbao_calc_blur_fog.program);
glUniform4fv(hbao_calc_blur_fog.control_projInfo, 1, projInfoPerspective);
glUniform2fv(hbao_calc_blur_fog.control_InvFullResolution, 1, InvFullResolution);
glUniform2fv(hbao_calc_blur_fog.control_InvQuarterResolution, 1, InvQuarterResolution);
glUniform1i(hbao_calc_blur_fog.control_projOrtho, 0);
glUniform1f(hbao_calc_blur_fog.control_RadiusToScreen, RadiusToScreen);
glUniform1f(hbao_calc_blur_fog.control_AOMultiplier, AOMultiplier);
glUniform1f(hbao_calc_blur_fog.control_NDotVBias, NDotVBias);
glUniform1f(hbao_calc_blur_fog.control_NegInvR2, NegInvR2);
glUniform1f(hbao_calc_blur_fog.control_PowExponent, PowExponent);
glUniform2f(hbao_calc_blur_fog.control_Fog, r_fog_control[0], r_fog_control[1]);
}
else
{
GL_UseProgram(hbao_calc_blur.program);
glUniform4fv(hbao_calc_blur.control_projInfo, 1, projInfoPerspective);
glUniform2fv(hbao_calc_blur.control_InvFullResolution, 1, InvFullResolution);
glUniform2fv(hbao_calc_blur.control_InvQuarterResolution, 1, InvQuarterResolution);
glUniform1i(hbao_calc_blur.control_projOrtho, 0);
glUniform1f(hbao_calc_blur.control_RadiusToScreen, RadiusToScreen);
glUniform1f(hbao_calc_blur.control_AOMultiplier, AOMultiplier);
glUniform1f(hbao_calc_blur.control_NDotVBias, NDotVBias);
glUniform1f(hbao_calc_blur.control_NegInvR2, NegInvR2);
glUniform1f(hbao_calc_blur.control_PowExponent, PowExponent);
}
//Texture unit 0 = linearized depth
GL_Bind(s_DepthLinearFBO.s_hBackBufferTex);
//Texture unit 1 = random texture
GL_EnableMultitexture();
GL_Bind(hbao_randomview[0]);
glDrawArrays(GL_TRIANGLES, 0, 3);
//Disable texture unit 1
GL_DisableMultitexture();
//SSAO blur stage
//Write to HBAO texture2
glDrawBuffer(GL_COLOR_ATTACHMENT1);
GL_UseProgram(hbao_blur.program);
glUniform1f(0, r_ssao_blur_sharpness->GetValue() / meters2viewspace);
glUniform2f(1, 1.0f / float(glwidth), 0);
//Texture unit 0 = calc
GL_Bind(s_HBAOCalcFBO.s_hBackBufferTex);
glDrawArrays(GL_TRIANGLES, 0, 3);
//Write to main framebuffer or GBuffer lightmap channel
if (drawgbuffer)
{
glBindFramebuffer(GL_FRAMEBUFFER, s_GBufferFBO.s_hBackBufferFBO);
glDrawBuffer(GL_COLOR_ATTACHMENT1);
}
else
{
glBindFramebuffer(GL_FRAMEBUFFER, s_BackBufferFBO.s_hBackBufferFBO);
//Should we reset drawbuffer?
glDrawBuffer(GL_COLOR_ATTACHMENT0);
}
//Merged with rgb channel
glEnable(GL_BLEND);
glBlendFunc(GL_ZERO, GL_SRC_COLOR);
glColor4f(1, 1, 1, 1);
//Only draw on brush surfaces
glEnable(GL_STENCIL_TEST);
glStencilMask(0xFF);
glStencilFunc(GL_EQUAL, 0, 0xFF);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
GL_UseProgram(hbao_blur2.program);
glUniform1f(0, r_ssao_blur_sharpness->GetValue() / meters2viewspace);
glUniform2f(1, 0, 1.0f / float(glheight));
//Texture unit 0 = calc2
GL_Bind(s_HBAOCalcFBO.s_hBackBufferTex2);
glDrawArrays(GL_TRIANGLES, 0, 3);
GL_UseProgram(0);
glDisable(GL_STENCIL_TEST);
glDisable(GL_BLEND);
GL_EndProfile(&profile_AmbientOcclusion);
}
| 31.62093 | 200 | 0.770979 | fengjixuchui |
58efd1a49fb6e315db96db351495422257c34870 | 6,801 | cc | C++ | components/nacl/renderer/plugin/srpc_client.cc | hefen1/chromium | 52f0b6830e000ca7c5e9aa19488af85be792cc88 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/nacl/renderer/plugin/srpc_client.cc | hefen1/chromium | 52f0b6830e000ca7c5e9aa19488af85be792cc88 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/nacl/renderer/plugin/srpc_client.cc | hefen1/chromium | 52f0b6830e000ca7c5e9aa19488af85be792cc88 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2020-04-04T13:34:56.000Z | 2020-11-04T07:17:52.000Z | /*
* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "components/nacl/renderer/plugin/srpc_client.h"
#include <string.h>
#include "components/nacl/renderer/plugin/plugin.h"
#include "components/nacl/renderer/plugin/srpc_params.h"
#include "components/nacl/renderer/plugin/utility.h"
#include "native_client/src/shared/platform/nacl_log.h"
namespace plugin {
typedef bool (*RpcFunction)(void* obj, SrpcParams* params);
// MethodInfo records the method names and type signatures of an SRPC server.
class MethodInfo {
public:
// statically defined method - called through a pointer
MethodInfo(const RpcFunction function_ptr,
const char* name,
const char* ins,
const char* outs,
// index is set to UINT_MAX for methods implemented by the plugin,
// All methods implemented by nacl modules have indexes
// that are lower than UINT_MAX.
const uint32_t index = UINT_MAX) :
function_ptr_(function_ptr),
name_(STRDUP(name)),
ins_(STRDUP(ins)),
outs_(STRDUP(outs)),
index_(index) { }
~MethodInfo() {
free(reinterpret_cast<void*>(name_));
free(reinterpret_cast<void*>(ins_));
free(reinterpret_cast<void*>(outs_));
}
RpcFunction function_ptr() const { return function_ptr_; }
char* name() const { return name_; }
char* ins() const { return ins_; }
char* outs() const { return outs_; }
uint32_t index() const { return index_; }
private:
NACL_DISALLOW_COPY_AND_ASSIGN(MethodInfo);
RpcFunction function_ptr_;
char* name_;
char* ins_;
char* outs_;
uint32_t index_;
};
SrpcClient::SrpcClient()
: srpc_channel_initialised_(false) {
PLUGIN_PRINTF(("SrpcClient::SrpcClient (this=%p)\n",
static_cast<void*>(this)));
NaClSrpcChannelInitialize(&srpc_channel_);
}
SrpcClient* SrpcClient::New(nacl::DescWrapper* wrapper) {
nacl::scoped_ptr<SrpcClient> srpc_client(new SrpcClient());
if (!srpc_client->Init(wrapper)) {
PLUGIN_PRINTF(("SrpcClient::New (SrpcClient::Init failed)\n"));
return NULL;
}
return srpc_client.release();
}
bool SrpcClient::Init(nacl::DescWrapper* wrapper) {
PLUGIN_PRINTF(("SrpcClient::Init (this=%p, wrapper=%p)\n",
static_cast<void*>(this),
static_cast<void*>(wrapper)));
// Open the channel to pass RPC information back and forth
if (!NaClSrpcClientCtor(&srpc_channel_, wrapper->desc())) {
return false;
}
srpc_channel_initialised_ = true;
PLUGIN_PRINTF(("SrpcClient::Init (Ctor worked)\n"));
// Record the method names in a convenient way for later dispatches.
GetMethods();
PLUGIN_PRINTF(("SrpcClient::Init (GetMethods worked)\n"));
return true;
}
SrpcClient::~SrpcClient() {
PLUGIN_PRINTF(("SrpcClient::~SrpcClient (this=%p, has_srpc_channel=%d)\n",
static_cast<void*>(this), srpc_channel_initialised_));
// And delete the connection.
if (srpc_channel_initialised_) {
PLUGIN_PRINTF(("SrpcClient::~SrpcClient (destroying srpc_channel)\n"));
NaClSrpcDtor(&srpc_channel_);
}
for (Methods::iterator iter = methods_.begin();
iter != methods_.end();
++iter) {
delete iter->second;
}
PLUGIN_PRINTF(("SrpcClient::~SrpcClient (return)\n"));
}
void SrpcClient::GetMethods() {
PLUGIN_PRINTF(("SrpcClient::GetMethods (this=%p)\n",
static_cast<void*>(this)));
if (NULL == srpc_channel_.client) {
return;
}
uint32_t method_count = NaClSrpcServiceMethodCount(srpc_channel_.client);
// Intern the methods into a mapping from identifiers to MethodInfo.
for (uint32_t i = 0; i < method_count; ++i) {
int retval;
const char* method_name;
const char* input_types;
const char* output_types;
retval = NaClSrpcServiceMethodNameAndTypes(srpc_channel_.client,
i,
&method_name,
&input_types,
&output_types);
if (!retval) {
return;
}
if (!IsValidIdentifierString(method_name, NULL)) {
// If name is not an ECMAScript identifier, do not enter it into the
// methods_ table.
continue;
}
MethodInfo* method_info =
new MethodInfo(NULL, method_name, input_types, output_types, i);
if (NULL == method_info) {
return;
}
// Install in the map only if successfully read.
methods_[method_name] = method_info;
}
}
bool SrpcClient::HasMethod(const std::string& method_name) {
bool has_method = (NULL != methods_[method_name]);
PLUGIN_PRINTF((
"SrpcClient::HasMethod (this=%p, method_name='%s', return %d)\n",
static_cast<void*>(this), method_name.c_str(), has_method));
return has_method;
}
bool SrpcClient::InitParams(const std::string& method_name,
SrpcParams* params) {
MethodInfo* method_info = methods_[method_name];
if (method_info) {
return params->Init(method_info->ins(), method_info->outs());
}
return false;
}
bool SrpcClient::Invoke(const std::string& method_name, SrpcParams* params) {
// It would be better if we could set the exception on each detailed failure
// case. However, there are calls to Invoke from within the plugin itself,
// and these could leave residual exceptions pending. This seems to be
// happening specifically with hard_shutdowns.
PLUGIN_PRINTF(("SrpcClient::Invoke (this=%p, method_name='%s', params=%p)\n",
static_cast<void*>(this),
method_name.c_str(),
static_cast<void*>(params)));
// Ensure Invoke was called with a method name that has a binding.
if (NULL == methods_[method_name]) {
PLUGIN_PRINTF(("SrpcClient::Invoke (ident not in methods_)\n"));
return false;
}
PLUGIN_PRINTF(("SrpcClient::Invoke (sending the rpc)\n"));
// Call the method
last_error_ = NaClSrpcInvokeV(&srpc_channel_,
methods_[method_name]->index(),
params->ins(),
params->outs());
PLUGIN_PRINTF(("SrpcClient::Invoke (response=%d)\n", last_error_));
if (NACL_SRPC_RESULT_OK != last_error_) {
PLUGIN_PRINTF(("SrpcClient::Invoke (err='%s', return 0)\n",
NaClSrpcErrorString(last_error_)));
return false;
}
PLUGIN_PRINTF(("SrpcClient::Invoke (return 1)\n"));
return true;
}
void SrpcClient::AttachService(NaClSrpcService* service, void* instance_data) {
srpc_channel_.server = service;
srpc_channel_.server_instance_data = instance_data;
}
} // namespace plugin
| 34.005 | 79 | 0.651228 | hefen1 |
58f07777fde724228ad81e8451d775f50a07359f | 484 | cc | C++ | src/test/ndpc/test_fact.cc | abu-bakar-nu/nautilus | 9c5046d714e2ff2a00f757ba42dc887024365be6 | [
"MIT"
] | 28 | 2018-10-12T17:44:54.000Z | 2022-01-27T19:30:56.000Z | src/test/ndpc/test_fact.cc | abu-bakar-nu/nautilus | 9c5046d714e2ff2a00f757ba42dc887024365be6 | [
"MIT"
] | 31 | 2018-12-08T19:39:32.000Z | 2021-01-19T18:37:57.000Z | src/test/ndpc/test_fact.cc | abu-bakar-nu/nautilus | 9c5046d714e2ff2a00f757ba42dc887024365be6 | [
"MIT"
] | 26 | 2018-08-04T03:58:13.000Z | 2022-03-02T18:53:09.000Z | #define NDPC_NAUTILUS_KERNEL
#include "ndpc_glue.h"
#include "fact.hh"
//
//using namespace std;
NDPC_TEST(fact)
{
int input=5;
int output;
NDPC_PRINTF("Testing factorial example\n");
ndpc_init_preempt_threads();
if (fact(output,input)) {
NDPC_PRINTF("function call failed\n");
} else {
NDPC_PRINTF("fact(%d) = %d\n",input,output);
}
ndpc_deinit_preempt_threads();
NDPC_PRINTF("Done testing factorial example\n");
return 0;
}
| 15.125 | 52 | 0.654959 | abu-bakar-nu |
58f18b905a1a9b445fc9c6c15fa0a95e33282e91 | 3,016 | cpp | C++ | Control/MV/buttoncolumndelegate.cpp | martinkro/tutorial-qt | 8685434520c6ab61691722aa06ca075f8ddbeacf | [
"MIT"
] | 2 | 2018-06-24T10:19:30.000Z | 2018-12-13T14:31:49.000Z | Control/MV/buttoncolumndelegate.cpp | martinkro/tutorial-qt | 8685434520c6ab61691722aa06ca075f8ddbeacf | [
"MIT"
] | null | null | null | Control/MV/buttoncolumndelegate.cpp | martinkro/tutorial-qt | 8685434520c6ab61691722aa06ca075f8ddbeacf | [
"MIT"
] | null | null | null | #include "buttoncolumndelegate.h"
#include <QPainter>
ButtonColumnDelegate::ButtonColumnDelegate(QObject *parent) :
QStyledItemDelegate(parent)
{
if (QTableView *tableView = qobject_cast<QTableView *>(parent))
{
myWidget = tableView;
btn = new QPushButton("...", myWidget);
btn->hide();
myWidget->setMouseTracking(true);
connect(myWidget, SIGNAL(entered(QModelIndex)),
this, SLOT(cellEntered(QModelIndex)));
isOneCellInEditMode = false;
}
}
ButtonColumnDelegate::~ButtonColumnDelegate()
{
}
//createEditor
QWidget * ButtonColumnDelegate::createEditor(QWidget *parent,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
if (index.model()->headerData(index.column(), Qt::Horizontal, Qt::UserRole).toInt() == 1) {
QPushButton * btn = new QPushButton(parent);
btn->setText(index.data().toString());
return btn;
}
else {
return QStyledItemDelegate::createEditor(parent, option, index);
}
}
//setEditorData
void ButtonColumnDelegate::setEditorData(QWidget *editor,
const QModelIndex &index) const
{
if (index.model()->headerData(index.column(), Qt::Horizontal, Qt::UserRole).toInt() == 1) {
QPushButton * btn = qobject_cast<QPushButton *>(editor);
btn->setProperty("data_value", index.data());
}
else {
QStyledItemDelegate::setEditorData(editor, index);
}
}
//setModelData
void ButtonColumnDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const
{
if (index.model()->headerData(index.column(), Qt::Horizontal, Qt::UserRole).toInt() == 1) {
QPushButton *btn = qobject_cast<QPushButton *>(editor);
model->setData(index, btn->property("data_value"));
}
else {
QStyledItemDelegate::setModelData(editor, model, index);
}
}
//paint
void ButtonColumnDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
if (index.model()->headerData(index.column(), Qt::Horizontal, Qt::UserRole).toInt() == 1)
{
btn->setGeometry(option.rect);
btn->setText(index.data().toString());
if (option.state == QStyle::State_Selected)
painter->fillRect(option.rect, option.palette.highlight());
QPixmap map = QPixmap::grabWidget(btn);
painter->drawPixmap(option.rect.x(), option.rect.y(), map);
}
else {
QStyledItemDelegate::paint(painter, option, index);
}
}
//updateGeometry
void ButtonColumnDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
editor->setGeometry(option.rect);
}
//cellEntered
void ButtonColumnDelegate::cellEntered(const QModelIndex &index)
{
if (index.model()->headerData(index.column(), Qt::Horizontal, Qt::UserRole) == 1)
{
if (isOneCellInEditMode)
{
myWidget->closePersistentEditor(currentEditedCellIndex);
}
myWidget->openPersistentEditor(index);
isOneCellInEditMode = true;
currentEditedCellIndex = index;
}
else {
if (isOneCellInEditMode)
{
isOneCellInEditMode = false;
myWidget->closePersistentEditor(currentEditedCellIndex);
}
}
}
| 28.186916 | 132 | 0.734416 | martinkro |
58f24871922634cdd3c0013179c13807f95ee6ee | 648 | hpp | C++ | src/agl/opengl/function/texture/parameter.hpp | the-last-willy/abstractgl | d685bef25ac18773d3eea48ca52806c3a3485ddb | [
"MIT"
] | null | null | null | src/agl/opengl/function/texture/parameter.hpp | the-last-willy/abstractgl | d685bef25ac18773d3eea48ca52806c3a3485ddb | [
"MIT"
] | null | null | null | src/agl/opengl/function/texture/parameter.hpp | the-last-willy/abstractgl | d685bef25ac18773d3eea48ca52806c3a3485ddb | [
"MIT"
] | null | null | null | #pragma once
#include "agl/opengl/enum/texture_parameter.hpp"
#include "agl/opengl/name/all.hpp"
namespace agl {
inline
void parameter(Texture t, TextureParameter tp, GLfloat param) {
glTextureParameterf(
t,
static_cast<GLenum>(tp),
param);
}
inline
void parameter(Texture t, TextureParameter tp, GLint param) {
glTextureParameteri(
t,
static_cast<GLenum>(tp),
param);
}
inline
void mag_filter(Texture t, GLint param) {
parameter(t, TextureParameter::mag_filter, param);
}
inline
void min_filter(Texture t, GLint param) {
parameter(t, TextureParameter::min_filter, param);
}
}
| 18.514286 | 63 | 0.688272 | the-last-willy |
58f2dc1f040c2104e1140c2053409ed1dadc78d4 | 4,741 | cc | C++ | CommonTools/Utils/src/ExpressionEvaluator.cc | eric-moreno/cmssw | 3dc2c26f276632ac8357ac7b52675f04649e3903 | [
"Apache-2.0"
] | null | null | null | CommonTools/Utils/src/ExpressionEvaluator.cc | eric-moreno/cmssw | 3dc2c26f276632ac8357ac7b52675f04649e3903 | [
"Apache-2.0"
] | 7 | 2016-07-17T02:34:54.000Z | 2019-08-13T07:58:37.000Z | CommonTools/Utils/src/ExpressionEvaluator.cc | eric-moreno/cmssw | 3dc2c26f276632ac8357ac7b52675f04649e3903 | [
"Apache-2.0"
] | 2 | 2019-09-27T08:33:22.000Z | 2019-11-14T10:52:30.000Z | #include "CommonTools/Utils/interface/ExpressionEvaluator.h"
#include "FWCore/Version/interface/GetReleaseVersion.h"
#include "FWCore/Utilities/interface/GetEnvironmentVariable.h"
#include "FWCore/Utilities/interface/Exception.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "popenCPP.h"
#include <fstream>
#include <regex>
#include <dlfcn.h>
// #define VI_DEBUG
#ifdef VI_DEBUG
#include <iostream>
#define COUT std::cout
#else
#define COUT LogDebug("ExpressionEvaluator")
#endif
using namespace reco::exprEvalDetails;
namespace {
std::string generateName() {
auto n1 = execSysCommand("uuidgen | sed 's/-//g'");
n1.pop_back();
return n1;
}
void remove(std::string const& name) {
std::string sfile = "/tmp/" + name + ".cc";
std::string ofile = "/tmp/" + name + ".so";
std::string rm = "rm -f ";
rm += sfile + ' ' + ofile;
system(rm.c_str());
}
std::string patchArea() {
auto n1 = execSysCommand("pushd $CMSSW_BASE > /dev/null;scram tool tag cmssw CMSSW_BASE; popd > /dev/null");
n1.pop_back();
COUT << "base area " << n1 << std::endl;
return n1[0] == '/' ? n1 : std::string();
}
} // namespace
namespace reco {
ExpressionEvaluator::ExpressionEvaluator(const char* pkg, const char* iname, std::string const& iexpr)
: m_name("VI_" + generateName()) {
std::string pch = pkg;
pch += "/src/precompile.h";
std::string quote("\"");
std::string sfile = "/tmp/" + m_name + ".cc";
std::string ofile = "/tmp/" + m_name + ".so";
auto arch = edm::getEnvironmentVariable("SCRAM_ARCH");
auto baseDir = edm::getEnvironmentVariable("CMSSW_BASE");
auto relDir = edm::getEnvironmentVariable("CMSSW_RELEASE_BASE");
std::string incDir = "/include/" + arch + "/";
std::string cxxf;
{
// look in local dir
std::string file = baseDir + incDir + pch + ".cxxflags";
std::ifstream ss(file.c_str());
COUT << "local file: " << file << std::endl;
if (ss) {
std::getline(ss, cxxf);
incDir = baseDir + incDir;
} else {
// look in release area
std::string file = relDir + incDir + pch + ".cxxflags";
COUT << "file in release area: " << file << std::endl;
std::ifstream ss(file.c_str());
if (ss) {
std::getline(ss, cxxf);
incDir = relDir + incDir;
} else {
// look in release is a patch area
auto paDir = patchArea();
if (paDir.empty())
throw cms::Exception("ExpressionEvaluator", "error in opening patch area for " + baseDir);
std::string file = paDir + incDir + pch + ".cxxflags";
COUT << "file in base release area: " << file << std::endl;
std::ifstream ss(file.c_str());
if (!ss)
throw cms::Exception(
"ExpressionEvaluator",
pch + " file not found neither in " + baseDir + " nor in " + relDir + " nor in " + paDir);
std::getline(ss, cxxf);
incDir = paDir + incDir;
}
}
{
std::regex rq("-I[^ ]+");
cxxf = std::regex_replace(cxxf, rq, std::string(""));
}
{
std::regex rq("=\"");
cxxf = std::regex_replace(cxxf, rq, std::string("='\""));
}
{
std::regex rq("\" ");
cxxf = std::regex_replace(cxxf, rq, std::string("\"' "));
}
COUT << '|' << cxxf << "|\n" << std::endl;
}
std::string cpp = "c++ -H -Wall -shared -Winvalid-pch ";
cpp += cxxf;
cpp += " -I" + incDir;
cpp += " -o " + ofile + ' ' + sfile + " 2>&1\n";
COUT << cpp << std::endl;
// prepare the file to compile
std::string factory = "factory" + m_name;
std::string source = std::string("#include ") + quote + pch + quote + "\n";
source += "struct " + m_name + " final : public " + iname + "{\n";
source += iexpr;
source += "\n};\n";
source += "extern " + quote + 'C' + quote + ' ' + std::string(iname) + "* " + factory + "() {\n";
source += "static " + m_name + " local;\n";
source += "return &local;\n}\n";
COUT << source << std::endl;
{
std::ofstream tmp(sfile.c_str());
tmp << source << std::endl;
}
// compile
auto ss = execSysCommand(cpp);
COUT << ss << std::endl;
void* dl = dlopen(ofile.c_str(), RTLD_LAZY);
if (!dl) {
remove(m_name);
throw cms::Exception("ExpressionEvaluator",
std::string("compilation/linking failed\n") + cpp + ss + "dlerror " + dlerror());
return;
}
m_expr = dlsym(dl, factory.c_str());
remove(m_name);
}
ExpressionEvaluator::~ExpressionEvaluator() { remove(m_name); }
} // namespace reco
| 29.63125 | 112 | 0.554313 | eric-moreno |
58f34c122d02d04fb94eb84d5d64a621e9add997 | 974 | cpp | C++ | Week16/1235.cpp | bobsingh149/LeetCode | 293ed4931960bf5b9a3d5c4331ba4dfddccfcd55 | [
"MIT"
] | 101 | 2021-02-26T14:32:37.000Z | 2022-03-16T18:46:37.000Z | Week16/1235.cpp | bobsingh149/LeetCode | 293ed4931960bf5b9a3d5c4331ba4dfddccfcd55 | [
"MIT"
] | null | null | null | Week16/1235.cpp | bobsingh149/LeetCode | 293ed4931960bf5b9a3d5c4331ba4dfddccfcd55 | [
"MIT"
] | 30 | 2021-03-09T05:16:48.000Z | 2022-03-16T21:16:33.000Z | bool sortFunc(const vector<int>& p1, const vector<int>& p2) {
return p1[0] < p2[0];
}
class Solution {
public:
int jobScheduling(vector<int>& startTime, vector<int>& endTime, vector<int>& profit) {
vector<vector<int>> contain;
int max_end=0;
for(int i=0; i<startTime.size(); i++){
contain.push_back({endTime[i], startTime[i], profit[i]});
max_end=max(max_end, endTime[i]);
}
sort(contain.begin(), contain.end(), sortFunc);
int last=0;
vector<int> dp(max_end+1, 0);
for(int i=0; i<contain.size(); i++){
for(int j=last+1; j<=contain[i][0]; j++){
dp[j]=max(dp[j-1], dp[j]);
}
dp[contain[i][0]]=max(dp[contain[i][1]]+contain[i][2], dp[contain[i][0]]);
last=contain[i][0];
}
int maxx=0;
for(int i=0; i<=max_end; i++){
maxx=max(maxx, dp[i]);
}
return maxx;
}
};
| 32.466667 | 90 | 0.501027 | bobsingh149 |
58f507e211a425fdce51de03e2388d46b27b8c6a | 26,140 | cpp | C++ | Modules/Core/src/DataManagement/mitkPropertyRelationRuleBase.cpp | zhaomengxiao/MITK | a09fd849a4328276806008bfa92487f83a9e2437 | [
"BSD-3-Clause"
] | 1 | 2022-03-03T12:03:32.000Z | 2022-03-03T12:03:32.000Z | Modules/Core/src/DataManagement/mitkPropertyRelationRuleBase.cpp | zhaomengxiao/MITK | a09fd849a4328276806008bfa92487f83a9e2437 | [
"BSD-3-Clause"
] | 1 | 2021-12-22T10:19:02.000Z | 2021-12-22T10:19:02.000Z | Modules/Core/src/DataManagement/mitkPropertyRelationRuleBase.cpp | zhaomengxiao/MITK_lancet | a09fd849a4328276806008bfa92487f83a9e2437 | [
"BSD-3-Clause"
] | 1 | 2020-11-27T09:41:18.000Z | 2020-11-27T09:41:18.000Z | /*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "mitkPropertyRelationRuleBase.h"
#include <mitkDataNode.h>
#include <mitkExceptionMacro.h>
#include <mitkNodePredicateBase.h>
#include <mitkStringProperty.h>
#include <mitkUIDGenerator.h>
#include <mutex>
#include <regex>
#include <algorithm>
bool mitk::PropertyRelationRuleBase::IsAbstract() const
{
return true;
}
bool mitk::PropertyRelationRuleBase::IsSourceCandidate(const IPropertyProvider *owner) const
{
return owner != nullptr;
}
bool mitk::PropertyRelationRuleBase::IsDestinationCandidate(const IPropertyProvider *owner) const
{
return owner != nullptr;
}
mitk::PropertyKeyPath mitk::PropertyRelationRuleBase::GetRootKeyPath()
{
return PropertyKeyPath().AddElement("MITK").AddElement("Relations");
}
bool mitk::PropertyRelationRuleBase::IsSupportedRuleID(const RuleIDType& ruleID) const
{
return ruleID == this->GetRuleID();
}
mitk::PropertyKeyPath mitk::PropertyRelationRuleBase::GetRIIPropertyKeyPath(const std::string propName, const InstanceIDType& instanceID)
{
auto path = GetRootKeyPath();
if (instanceID.empty())
{
path.AddAnyElement();
}
else
{
path.AddElement(instanceID);
}
if (!propName.empty())
{
path.AddElement(propName);
}
return path;
}
std::string mitk::PropertyRelationRuleBase::GetRIIPropertyRegEx(const std::string propName, const InstanceIDType &instanceID) const
{
return PropertyKeyPathToPropertyRegEx(GetRIIPropertyKeyPath(propName, instanceID));
}
mitk::PropertyKeyPath mitk::PropertyRelationRuleBase::GetRIIRelationUIDPropertyKeyPath(const InstanceIDType& instanceID)
{
return GetRIIPropertyKeyPath("relationUID", instanceID);
}
mitk::PropertyKeyPath mitk::PropertyRelationRuleBase::GetRIIRuleIDPropertyKeyPath(const InstanceIDType& instanceID)
{
return GetRIIPropertyKeyPath("ruleID", instanceID);
}
mitk::PropertyKeyPath mitk::PropertyRelationRuleBase::GetRIIDestinationUIDPropertyKeyPath(const InstanceIDType& instanceID)
{
return GetRIIPropertyKeyPath("destinationUID", instanceID);
}
//workaround until T24729 is done. Please remove if T24728 is done
//then could directly use owner->GetPropertyKeys() again.
std::vector<std::string> mitk::PropertyRelationRuleBase::GetPropertyKeys(const mitk::IPropertyProvider *owner)
{
std::vector<std::string> keys;
auto sourceCasted = dynamic_cast<const mitk::DataNode*>(owner);
if (sourceCasted) {
auto sourceData = sourceCasted->GetData();
if (sourceData) {
keys = sourceData->GetPropertyKeys();
}
else {
keys = sourceCasted->GetPropertyKeys();
}
}
else {
keys = owner->GetPropertyKeys();
}
return keys;
}
//end workaround for T24729
bool mitk::PropertyRelationRuleBase::IsSource(const IPropertyProvider *owner) const
{
return !this->GetExistingRelations(owner).empty();
}
bool mitk::PropertyRelationRuleBase::HasRelation(
const IPropertyProvider* source, const IPropertyProvider* destination, RelationType requiredRelation) const
{
auto relTypes = this->GetRelationTypes(source, destination);
if (requiredRelation == RelationType::None)
{
return !relTypes.empty();
}
RelationVectorType allowedTypes = { RelationType::Complete };
if (requiredRelation == RelationType::Data)
{
allowedTypes.emplace_back(RelationType::Data);
}
else if (requiredRelation == RelationType::ID)
{
allowedTypes.emplace_back(RelationType::ID);
}
return relTypes.end() != std::find_first_of(relTypes.begin(), relTypes.end(), allowedTypes.begin(), allowedTypes.end());
}
mitk::PropertyRelationRuleBase::RelationVectorType mitk::PropertyRelationRuleBase::GetRelationTypes(
const IPropertyProvider* source, const IPropertyProvider* destination) const
{
if (!source)
{
mitkThrow() << "Error. Passed source pointer is NULL";
}
if (!destination)
{
mitkThrow() << "Error. Passed owner pointer is NULL";
}
auto instanceIDs_IDLayer = this->GetInstanceID_IDLayer(source, destination);
auto relIDs_dataLayer = this->GetRelationUIDs_DataLayer(source, destination, {});
if (relIDs_dataLayer.size() > 1)
{
MITK_WARN << "Property relation on data level is ambiguous. First relation is used. Relation UID: "
<< relIDs_dataLayer.front().first;
}
bool hasComplete = instanceIDs_IDLayer.end() != std::find_if(instanceIDs_IDLayer.begin(), instanceIDs_IDLayer.end(), [&](const InstanceIDVectorType::value_type& instanceID)
{
auto relID_IDlayer = this->GetRelationUIDByInstanceID(source, instanceID);
auto ruleID_IDlayer = this->GetRuleIDByInstanceID(source, instanceID);
return relIDs_dataLayer.end() != std::find_if(relIDs_dataLayer.begin(), relIDs_dataLayer.end(), [&](const DataRelationUIDVectorType::value_type& relID)
{
return relID.first == relID_IDlayer && relID.second == ruleID_IDlayer;
});
});
bool hasID = instanceIDs_IDLayer.end() != std::find_if(instanceIDs_IDLayer.begin(), instanceIDs_IDLayer.end(), [&](const InstanceIDVectorType::value_type& instanceID)
{
auto relID_IDlayer = this->GetRelationUIDByInstanceID(source, instanceID);
auto ruleID_IDlayer = this->GetRuleIDByInstanceID(source, instanceID);
return relIDs_dataLayer.end() == std::find_if(relIDs_dataLayer.begin(), relIDs_dataLayer.end(), [&](const DataRelationUIDVectorType::value_type& relID)
{
return relID.first == relID_IDlayer && relID.second == ruleID_IDlayer;
});
});
bool hasData = relIDs_dataLayer.end() != std::find_if(relIDs_dataLayer.begin(), relIDs_dataLayer.end(), [&](const DataRelationUIDVectorType::value_type& relID)
{
return instanceIDs_IDLayer.end() == std::find_if(instanceIDs_IDLayer.begin(), instanceIDs_IDLayer.end(), [&](const InstanceIDVectorType::value_type& instanceID)
{
auto relID_IDlayer = this->GetRelationUIDByInstanceID(source, instanceID);
auto ruleID_IDlayer = this->GetRuleIDByInstanceID(source, instanceID);
return relID.first == relID_IDlayer && relID.second == ruleID_IDlayer;
});
});
RelationVectorType result;
if (hasData)
{
result.emplace_back(RelationType::Data);
}
if (hasID)
{
result.emplace_back(RelationType::ID);
}
if (hasComplete)
{
result.emplace_back(RelationType::Complete);
}
return result;
}
mitk::PropertyRelationRuleBase::RelationUIDVectorType mitk::PropertyRelationRuleBase::GetExistingRelations(
const IPropertyProvider *source, RelationType layer) const
{
if (!source)
{
mitkThrow() << "Error. Passed source pointer is NULL";
}
RelationUIDVectorType relationUIDs;
InstanceIDVectorType instanceIDs;
if (layer != RelationType::Data)
{
auto ruleIDRegExStr = this->GetRIIPropertyRegEx("ruleID");
auto regEx = std::regex(ruleIDRegExStr);
//workaround until T24729 is done. You can use directly source->GetPropertyKeys again, when fixed.
const auto keys = GetPropertyKeys(source);
//end workaround for T24729
for (const auto& key : keys)
{
if (std::regex_match(key, regEx))
{
auto idProp = source->GetConstProperty(key);
auto ruleID = idProp->GetValueAsString();
if (this->IsSupportedRuleID(ruleID))
{
auto instanceID = this->GetInstanceIDByPropertyName(key);
instanceIDs.emplace_back(instanceID);
relationUIDs.push_back(this->GetRelationUIDByInstanceID(source, instanceID));
}
}
}
}
if (layer == RelationType::ID)
{
return relationUIDs;
}
DataRelationUIDVectorType relationUIDandRuleID_Data;
if (layer != RelationType::ID)
{
relationUIDandRuleID_Data = this->GetRelationUIDs_DataLayer(source, nullptr, instanceIDs);
}
RelationUIDVectorType relationUIDs_Data;
std::transform(relationUIDandRuleID_Data.begin(), relationUIDandRuleID_Data.end(), std::back_inserter(relationUIDs_Data),
[](const DataRelationUIDVectorType::value_type& v) { return v.first; });
if (layer == RelationType::Data)
{
return relationUIDs_Data;
}
std::sort(relationUIDs.begin(), relationUIDs.end());
std::sort(relationUIDs_Data.begin(), relationUIDs_Data.end());
RelationUIDVectorType result;
if (layer == RelationType::Complete)
{
std::set_intersection(relationUIDs.begin(), relationUIDs.end(), relationUIDs_Data.begin(), relationUIDs_Data.end(), std::back_inserter(result));
}
else
{
std::set_union(relationUIDs.begin(), relationUIDs.end(), relationUIDs_Data.begin(), relationUIDs_Data.end(), std::back_inserter(result));
}
return result;
}
mitk::PropertyRelationRuleBase::RelationUIDVectorType mitk::PropertyRelationRuleBase::GetRelationUIDs(
const IPropertyProvider *source, const IPropertyProvider *destination) const
{
if (!source)
{
mitkThrow() << "Error. Passed source pointer is NULL";
}
if (!destination)
{
mitkThrow() << "Error. Passed destination pointer is NULL";
}
RelationUIDVectorType relUIDs_id;
auto instanceIDs = this->GetInstanceID_IDLayer(source, destination);
for (const auto& instanceID : instanceIDs)
{
relUIDs_id.push_back(this->GetRelationUIDByInstanceID(source, instanceID));
}
DataRelationUIDVectorType relationUIDandRuleID_Data = this->GetRelationUIDs_DataLayer(source,destination,instanceIDs);
RelationUIDVectorType relUIDs_Data;
std::transform(relationUIDandRuleID_Data.begin(), relationUIDandRuleID_Data.end(), std::back_inserter(relUIDs_Data),
[](const DataRelationUIDVectorType::value_type& v) { return v.first; });
std::sort(relUIDs_id.begin(), relUIDs_id.end());
std::sort(relUIDs_Data.begin(), relUIDs_Data.end());
RelationUIDVectorType result;
std::set_union(relUIDs_id.begin(), relUIDs_id.end(), relUIDs_Data.begin(), relUIDs_Data.end(), std::back_inserter(result));
return result;
}
mitk::PropertyRelationRuleBase::RelationUIDType
mitk::PropertyRelationRuleBase::GetRelationUID(const IPropertyProvider *source, const IPropertyProvider *destination) const
{
auto result = this->GetRelationUIDs(source, destination);
if (result.empty())
{
mitkThrowException(NoPropertyRelationException);
}
else if(result.size()>1)
{
mitkThrow() << "Cannot return one(!) relation UID. Multiple relations exists for given rule, source and destination.";
}
return result[0];
}
mitk::PropertyRelationRuleBase::InstanceIDType mitk::PropertyRelationRuleBase::NULL_INSTANCE_ID()
{
return std::string();
};
mitk::PropertyRelationRuleBase::RelationUIDType mitk::PropertyRelationRuleBase::GetRelationUIDByInstanceID(
const IPropertyProvider *source, const InstanceIDType &instanceID) const
{
RelationUIDType result;
if (instanceID != NULL_INSTANCE_ID())
{
auto idProp = source->GetConstProperty(
PropertyKeyPathToPropertyName(GetRIIRelationUIDPropertyKeyPath(instanceID)));
if (idProp.IsNotNull())
{
result = idProp->GetValueAsString();
}
}
if (result.empty())
{
mitkThrowException(NoPropertyRelationException);
}
return result;
}
mitk::PropertyRelationRuleBase::InstanceIDType mitk::PropertyRelationRuleBase::GetInstanceIDByRelationUID(
const IPropertyProvider *source, const RelationUIDType &relationUID) const
{
if (!source)
{
mitkThrow() << "Error. Passed source pointer is NULL";
}
InstanceIDType result = NULL_INSTANCE_ID();
auto destRegExStr =
PropertyKeyPathToPropertyRegEx(GetRIIRelationUIDPropertyKeyPath());
auto regEx = std::regex(destRegExStr);
std::smatch instance_matches;
//workaround until T24729 is done. You can use directly source->GetPropertyKeys again, when fixed.
const auto keys = GetPropertyKeys(source);
//end workaround for T24729
for (const auto &key : keys)
{
if (std::regex_search(key, instance_matches, regEx))
{
auto idProp = source->GetConstProperty(key);
if (idProp->GetValueAsString() == relationUID)
{
if (instance_matches.size()>1)
{
result = instance_matches[1];
break;
}
}
}
}
return result;
}
mitk::PropertyRelationRuleBase::InstanceIDVectorType mitk::PropertyRelationRuleBase::GetInstanceID_IDLayer(
const IPropertyProvider *source, const IPropertyProvider *destination) const
{
if (!source)
{
mitkThrow() << "Error. Passed source pointer is NULL";
}
if (!destination)
{
mitkThrow() << "Error. Passed destination pointer is NULL";
}
auto identifiable = CastProviderAsIdentifiable(destination);
InstanceIDVectorType result;
if (identifiable)
{ // check for relations of type Connected_ID;
auto destRegExStr = this->GetRIIPropertyRegEx("destinationUID");
auto regEx = std::regex(destRegExStr);
std::smatch instance_matches;
auto destUID = identifiable->GetUID();
//workaround until T24729 is done. You can use directly source->GetPropertyKeys again, when fixed.
const auto keys = GetPropertyKeys(source);
//end workaround for T24729
for (const auto &key : keys)
{
if (std::regex_search(key, instance_matches, regEx))
{
auto idProp = source->GetConstProperty(key);
if (idProp->GetValueAsString() == destUID)
{
if (instance_matches.size()>1)
{
auto instanceID = instance_matches[1];
if (this->IsSupportedRuleID(GetRuleIDByInstanceID(source, instanceID)))
{
result.push_back(instanceID);
}
}
}
}
}
}
return result;
}
const mitk::Identifiable* mitk::PropertyRelationRuleBase::CastProviderAsIdentifiable(const mitk::IPropertyProvider* destination) const
{
auto identifiable = dynamic_cast<const Identifiable*>(destination);
if (!identifiable)
{ //This check and pass through to data is needed due to solve T25711. See Task for more information.
//This could be removed at the point we can get rid of DataNodes or they get realy transparent.
auto node = dynamic_cast<const DataNode*>(destination);
if (node && node->GetData())
{
identifiable = dynamic_cast<const Identifiable*>(node->GetData());
}
}
return identifiable;
}
mitk::PropertyRelationRuleBase::RelationUIDType mitk::PropertyRelationRuleBase::Connect(IPropertyOwner *source, const IPropertyProvider *destination) const
{
if (!source)
{
mitkThrow() << "Error. Passed source pointer is NULL";
}
if (!destination)
{
mitkThrow() << "Error. Passed destination pointer is NULL";
}
if (this->IsAbstract())
{
mitkThrow() << "Error. This is an abstract property relation rule. Abstract rule must not make a connection. Please use a concrete rule.";
}
auto instanceIDs = this->GetInstanceID_IDLayer(source, destination);
bool hasIDlayer = !instanceIDs.empty();
auto relUIDs_data = this->GetRelationUIDs_DataLayer(source, destination, {});
if (relUIDs_data.size() > 1)
{
MITK_WARN << "Property relation on data level is ambiguous. First relation is used. RelationUID ID: "
<< relUIDs_data.front().first;
}
bool hasDatalayer = !relUIDs_data.empty();
RelationUIDType relationUID = this->CreateRelationUID();
InstanceIDType instanceID = NULL_INSTANCE_ID();
if (hasIDlayer)
{
instanceID = instanceIDs.front();
}
else if (hasDatalayer)
{
try
{
instanceID = this->GetInstanceIDByRelationUID(source, relUIDs_data.front().first);
}
catch(...)
{ }
}
if(instanceID == NULL_INSTANCE_ID())
{
instanceID = this->CreateNewRelationInstance(source, relationUID);
}
auto relUIDKey =
PropertyKeyPathToPropertyName(GetRIIRelationUIDPropertyKeyPath(instanceID));
source->SetProperty(relUIDKey, mitk::StringProperty::New(relationUID));
auto ruleIDKey =
PropertyKeyPathToPropertyName(GetRIIRuleIDPropertyKeyPath(instanceID));
source->SetProperty(ruleIDKey, mitk::StringProperty::New(this->GetRuleID()));
if (!hasIDlayer)
{
auto identifiable = this->CastProviderAsIdentifiable(destination);
if (identifiable)
{
auto destUIDKey =
PropertyKeyPathToPropertyName(GetRIIDestinationUIDPropertyKeyPath(instanceID));
source->SetProperty(destUIDKey, mitk::StringProperty::New(identifiable->GetUID()));
}
}
this->Connect_datalayer(source, destination, instanceID);
return relationUID;
}
void mitk::PropertyRelationRuleBase::Disconnect(IPropertyOwner *source, const IPropertyProvider *destination, RelationType layer) const
{
if (source == nullptr)
{
mitkThrow() << "Error. Source is invalid. Cannot disconnect.";
}
if (destination == nullptr)
{
mitkThrow() << "Error. Destination is invalid. Cannot disconnect.";
}
try
{
const auto relationUIDs = this->GetRelationUIDs(source, destination);
for (const auto& relUID: relationUIDs)
{
this->Disconnect(source, relUID, layer);
}
}
catch (const NoPropertyRelationException &)
{
// nothing to do and no real error in context of disconnect.
}
}
void mitk::PropertyRelationRuleBase::Disconnect(IPropertyOwner *source, RelationUIDType relationUID, RelationType layer) const
{
if (source == nullptr)
{
mitkThrow() << "Error. Source is invalid. Cannot disconnect.";
}
if (layer == RelationType::Data || layer == RelationType::Complete)
{
this->Disconnect_datalayer(source, relationUID);
}
auto instanceID = this->GetInstanceIDByRelationUID(source, relationUID);
if ((layer == RelationType::ID || layer == RelationType::Complete) && instanceID != NULL_INSTANCE_ID())
{
auto instancePrefix = PropertyKeyPathToPropertyName(GetRootKeyPath().AddElement(instanceID));
//workaround until T24729 is done. You can use directly source->GetPropertyKeys again, when fixed.
const auto keys = GetPropertyKeys(source);
//end workaround for T24729
for (const auto &key : keys)
{
if (key.find(instancePrefix) == 0)
{
source->RemoveProperty(key);
}
}
}
}
mitk::PropertyRelationRuleBase::RelationUIDType mitk::PropertyRelationRuleBase::CreateRelationUID()
{
UIDGenerator generator;
return generator.GetUID();
}
/**This mutex is used to guard mitk::PropertyRelationRuleBase::CreateNewRelationInstance by a class wide mutex to avoid
racing conditions in a scenario where rules are used concurrently. It is not in the class interface itself, because it
is an implementation detail.
*/
std::mutex relationCreationLock;
mitk::PropertyRelationRuleBase::InstanceIDType mitk::PropertyRelationRuleBase::CreateNewRelationInstance(
IPropertyOwner *source, const RelationUIDType &relationUID) const
{
std::lock_guard<std::mutex> guard(relationCreationLock);
//////////////////////////////////////
// Get all existing instanc IDs
std::vector<int> instanceIDs;
InstanceIDType newID = "1";
auto destRegExStr =
PropertyKeyPathToPropertyRegEx(GetRIIRelationUIDPropertyKeyPath());
auto regEx = std::regex(destRegExStr);
std::smatch instance_matches;
//workaround until T24729 is done. You can use directly source->GetPropertyKeys again, when fixed.
const auto keys = GetPropertyKeys(source);
//end workaround for T24729
for (const auto &key : keys)
{
if (std::regex_search(key, instance_matches, regEx))
{
if (instance_matches.size()>1)
{
instanceIDs.push_back(std::stoi(instance_matches[1]));
}
}
}
//////////////////////////////////////
// Get new ID
std::sort(instanceIDs.begin(), instanceIDs.end());
if (!instanceIDs.empty())
{
newID = std::to_string(instanceIDs.back() + 1);
}
//////////////////////////////////////
// reserve new ID
auto relUIDKey =
PropertyKeyPathToPropertyName(GetRIIRelationUIDPropertyKeyPath(newID));
source->SetProperty(relUIDKey, mitk::StringProperty::New(relationUID));
return newID;
}
itk::LightObject::Pointer mitk::PropertyRelationRuleBase::InternalClone() const
{
return Superclass::InternalClone();
}
mitk::PropertyRelationRuleBase::InstanceIDType mitk::PropertyRelationRuleBase::GetInstanceIDByPropertyName(const std::string propName)
{
auto proppath = PropertyNameToPropertyKeyPath(propName);
auto ref = GetRootKeyPath();
if (proppath.GetSize() < 3 || !(proppath.GetFirstNode() == ref.GetFirstNode()) || !(proppath.GetNode(1) == ref.GetNode(1)))
{
mitkThrow() << "Property name is not for a RII property or containes no instance ID. Wrong name: " << propName;
}
return proppath.GetNode(2).name;
}
mitk::PropertyRelationRuleBase::RuleIDType mitk::PropertyRelationRuleBase::GetRuleIDByInstanceID(const IPropertyProvider *source,
const InstanceIDType &instanceID) const
{
if (!source)
{
mitkThrow() << "Error. Source is invalid. Cannot deduce rule ID";
}
auto path = GetRIIRuleIDPropertyKeyPath(instanceID);
auto name = PropertyKeyPathToPropertyName(path);
const auto prop = source->GetConstProperty(name);
std::string result;
if (prop.IsNotNull())
{
result = prop->GetValueAsString();
}
if (result.empty())
{
mitkThrowException(NoPropertyRelationException) << "Error. Source has no property relation with the passed instance ID. Instance ID: " << instanceID;
}
return result;
}
std::string mitk::PropertyRelationRuleBase::GetDestinationUIDByInstanceID(const IPropertyProvider* source,
const InstanceIDType& instanceID) const
{
if (!source)
{
mitkThrow() << "Error. Source is invalid. Cannot deduce rule ID";
}
auto path = GetRIIDestinationUIDPropertyKeyPath(instanceID);
auto name = PropertyKeyPathToPropertyName(path);
const auto prop = source->GetConstProperty(name);
std::string result;
if (prop.IsNotNull())
{
result = prop->GetValueAsString();
}
return result;
}
namespace mitk
{
/**
* \brief Predicate used to wrap rule checks.
*
* \ingroup DataStorage
*/
class NodePredicateRuleFunction : public NodePredicateBase
{
public:
using FunctionType = std::function<bool(const mitk::IPropertyProvider *, const mitk::PropertyRelationRuleBase *)>;
mitkClassMacro(NodePredicateRuleFunction, NodePredicateBase)
mitkNewMacro2Param(NodePredicateRuleFunction, const FunctionType &, PropertyRelationRuleBase::ConstPointer)
~NodePredicateRuleFunction() override = default;
bool CheckNode(const mitk::DataNode *node) const override
{
if (!node)
{
return false;
}
return m_Function(node, m_Rule);
};
protected:
explicit NodePredicateRuleFunction(const FunctionType &function, PropertyRelationRuleBase::ConstPointer rule) : m_Function(function), m_Rule(rule)
{
};
FunctionType m_Function;
PropertyRelationRuleBase::ConstPointer m_Rule;
};
} // namespace mitk
mitk::NodePredicateBase::ConstPointer mitk::PropertyRelationRuleBase::GetSourceCandidateIndicator() const
{
auto check = [](const mitk::IPropertyProvider *node, const mitk::PropertyRelationRuleBase *rule) {
return rule->IsSourceCandidate(node);
};
return NodePredicateRuleFunction::New(check, this).GetPointer();
}
mitk::NodePredicateBase::ConstPointer mitk::PropertyRelationRuleBase::GetDestinationCandidateIndicator() const
{
auto check = [](const mitk::IPropertyProvider *node, const mitk::PropertyRelationRuleBase *rule) {
return rule->IsDestinationCandidate(node);
};
return NodePredicateRuleFunction::New(check, this).GetPointer();
}
mitk::NodePredicateBase::ConstPointer mitk::PropertyRelationRuleBase::GetConnectedSourcesDetector() const
{
auto check = [](const mitk::IPropertyProvider *node, const mitk::PropertyRelationRuleBase *rule)
{
return rule->IsSource(node);
};
return NodePredicateRuleFunction::New(check, this).GetPointer();
}
mitk::NodePredicateBase::ConstPointer mitk::PropertyRelationRuleBase::GetSourcesDetector(
const IPropertyProvider *destination, RelationType exclusiveRelation) const
{
if (!destination)
{
mitkThrow() << "Error. Passed destination pointer is NULL";
}
auto check = [destination, exclusiveRelation](const mitk::IPropertyProvider *node,
const mitk::PropertyRelationRuleBase *rule) {
return rule->HasRelation(node, destination, exclusiveRelation);
};
return NodePredicateRuleFunction::New(check, this).GetPointer();
}
mitk::NodePredicateBase::ConstPointer mitk::PropertyRelationRuleBase::GetDestinationsDetector(
const IPropertyProvider *source, RelationType exclusiveRelation) const
{
if (!source)
{
mitkThrow() << "Error. Passed source pointer is NULL";
}
auto check = [source, exclusiveRelation](const mitk::IPropertyProvider *node,
const mitk::PropertyRelationRuleBase *rule) {
return rule->HasRelation(source, node, exclusiveRelation);
};
return NodePredicateRuleFunction::New(check, this).GetPointer();
}
mitk::NodePredicateBase::ConstPointer mitk::PropertyRelationRuleBase::GetDestinationDetector(
const IPropertyProvider *source, RelationUIDType relationUID) const
{
if (!source)
{
mitkThrow() << "Error. Passed source pointer is NULL";
}
auto relUIDs = this->GetExistingRelations(source);
if (std::find(relUIDs.begin(), relUIDs.end(), relationUID) == relUIDs.end())
{
mitkThrow()
<< "Error. Passed relationUID does not identify a relation instance of the passed source for this rule instance.";
};
auto check = [source, relationUID](const mitk::IPropertyProvider *node, const mitk::PropertyRelationRuleBase *rule) {
try
{
auto relevantUIDs = rule->GetRelationUIDs(source, node);
for (const auto& aUID : relevantUIDs)
{
if (aUID == relationUID)
{
return true;
}
}
}
catch(const NoPropertyRelationException &)
{
return false;
}
return false;
};
return NodePredicateRuleFunction::New(check, this).GetPointer();
}
| 29.977064 | 174 | 0.714575 | zhaomengxiao |
58f61a8cce9d5594b07bcc61457d49ed308d10a8 | 1,182 | hpp | C++ | cpp/src/datacentric/dc/types/record/root_key.hpp | datacentricorg/datacentric | b9e2dedfac35759ea09bb5653095daba5861512e | [
"Apache-2.0"
] | 1 | 2019-08-08T01:27:47.000Z | 2019-08-08T01:27:47.000Z | cpp/src/datacentric/dc/types/record/root_key.hpp | datacentricorg/datacentric | b9e2dedfac35759ea09bb5653095daba5861512e | [
"Apache-2.0"
] | null | null | null | cpp/src/datacentric/dc/types/record/root_key.hpp | datacentricorg/datacentric | b9e2dedfac35759ea09bb5653095daba5861512e | [
"Apache-2.0"
] | null | null | null | /*
Copyright (C) 2013-present The DataCentric Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma once
#include <dc/declare.hpp>
#include <dc/types/record/key.hpp>
namespace dc
{
template <typename TKey, typename TRecord> class root_key_impl;
template <typename TKey, typename TRecord> using root_key = dot::ptr<root_key_impl<TKey, TRecord>>;
template <typename TKey, typename TRecord> class key_impl;
template <typename TKey, typename TRecord> using key = dot::ptr<key_impl<TKey, TRecord>>;
/// Root record is recorded without a dataset.
template <typename TKey, typename TRecord>
class root_key_impl : public virtual key_impl<TKey, TRecord>
{
};
} | 33.771429 | 103 | 0.753807 | datacentricorg |
58f8610cdf0420bd3597b10a1403e8b2ad46cf17 | 7,256 | cpp | C++ | src/stores/GOG/gog_library.cpp | ColonelGerdauf/SKIF | ae0b300c0ededbc5437bd26c37be4f0b8fb8cfaa | [
"MIT"
] | null | null | null | src/stores/GOG/gog_library.cpp | ColonelGerdauf/SKIF | ae0b300c0ededbc5437bd26c37be4f0b8fb8cfaa | [
"MIT"
] | null | null | null | src/stores/GOG/gog_library.cpp | ColonelGerdauf/SKIF | ae0b300c0ededbc5437bd26c37be4f0b8fb8cfaa | [
"MIT"
] | null | null | null |
#include <stores/gog/gog_library.h>
#include <wtypes.h>
#include <filesystem>
/*
GOG Galaxy / Offline Installers shared registry struture
Root Key: HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\GOG.com\Games\
Each game is stored in a separate key beneath, named after the Game ID/Product ID of the game.
Each key have a bunch of values with some basic data of the game, its location, and launch options.
Registry values and the data they contain:
exe -- Full path to game executable
exeFile -- Filename of game executable
gameID -- App ID of the game
gameName -- Title of the game
launchCommand -- Default launch full path and parameter of the game
launchParam -- Default launch parameter of the game
path -- Path to the game folder
productID -- Same as App ID of the game ?
uninstallCommand -- Full path to the uninstaller of the game
workingDir -- Working directory of the game
There are more values, but they aren't listed here.
GOG Galaxy Custom Default Launch Option:
To launch a game using the Galaxy user's customized launch option,
it's enough to launch the game through Galaxy like the start menu shortcuts does, like this:
"D:\Games\GOG Galaxy\GalaxyClient.exe" /command=runGame /gameId=1895572517 /path="D:\Games\GOG Games\AI War 2"
*/
void
SKIF_GOG_GetInstalledAppIDs (std::vector <std::pair < std::string, app_record_s > > *apps)
{
HKEY hKey;
DWORD dwIndex = 0, dwResult, dwSize;
WCHAR szSubKey[MAX_PATH];
WCHAR szData[MAX_PATH];
/* Load GOG titles from registry */
if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, LR"(SOFTWARE\GOG.com\Games\)", 0, KEY_READ | KEY_WOW64_32KEY, &hKey) == ERROR_SUCCESS)
{
if (RegQueryInfoKeyW(hKey, NULL, NULL, NULL, &dwResult, NULL, NULL, NULL, NULL, NULL, NULL, NULL) == ERROR_SUCCESS)
{
do
{
dwSize = sizeof(szSubKey) / sizeof(WCHAR);
dwResult = RegEnumKeyExW(hKey, dwIndex, szSubKey, &dwSize, NULL, NULL, NULL, NULL);
if (dwResult == ERROR_NO_MORE_ITEMS)
break;
if (dwResult == ERROR_SUCCESS)
{
dwSize = sizeof(szData) / sizeof(WCHAR);
if (RegGetValueW(hKey, szSubKey, L"dependsOn", RRF_RT_REG_SZ, NULL, &szData, &dwSize) == ERROR_SUCCESS &&
wcslen(szData) == 0) // Only handles items without a dependency (skips DLCs)
{
dwSize = sizeof(szData) / sizeof(WCHAR);
if (RegGetValueW(hKey, szSubKey, L"GameID", RRF_RT_REG_SZ, NULL, &szData, &dwSize) == ERROR_SUCCESS)
{
int appid = _wtoi(szData);
app_record_s record(appid);
record.store = "GOG";
record.type = "Game";
//GOG_record.extended_config.vac.enabled = false;
record._status.installed = true;
dwSize = sizeof(szData) / sizeof(WCHAR);
if (RegGetValueW(hKey, szSubKey, L"GameName", RRF_RT_REG_SZ, NULL, &szData, &dwSize) == ERROR_SUCCESS)
record.names.normal = SK_WideCharToUTF8(szData);
// Strip null terminators // moved to later -- performed for all installed games as part of manage_games.cpp
//GOG_record.names.normal.erase(std::find(GOG_record.names.normal.begin(), GOG_record.names.normal.end(), '\0'), GOG_record.names.normal.end());
// Add (GOG) at the end of the name
//GOG_record.names.normal = GOG_record.names.normal + " (GOG)";
record.names.all_upper = record.names.normal;
std::for_each(record.names.all_upper.begin(), record.names.all_upper.end(), ::toupper);
dwSize = sizeof(szData) / sizeof(WCHAR);
if (RegGetValueW(hKey, szSubKey, L"path", RRF_RT_REG_SZ, NULL, &szData, &dwSize) == ERROR_SUCCESS)
record.install_dir = szData;
dwSize = sizeof(szData) / sizeof(WCHAR);
if (RegGetValueW(hKey, szSubKey, L"exeFile", RRF_RT_REG_SZ, NULL, &szData, &dwSize) == ERROR_SUCCESS)
{
app_record_s::launch_config_s lc;
lc.id = 0;
lc.store = L"GOG";
lc.executable = szData;
// lc.working_dir = record.install_dir;
dwSize = sizeof(szData) / sizeof(WCHAR);
if (RegGetValueW(hKey, szSubKey, L"exe", RRF_RT_REG_SZ, NULL, &szData, &dwSize) == ERROR_SUCCESS)
lc.executable_path = szData;
dwSize = sizeof(szData) / sizeof(WCHAR);
if (RegGetValueW(hKey, szSubKey, L"workingDir", RRF_RT_REG_SZ, NULL, &szData, &dwSize) == ERROR_SUCCESS)
lc.working_dir = szData;
dwSize = sizeof(szData) / sizeof(WCHAR);
if (RegGetValueW(hKey, szSubKey, L"launchParam", RRF_RT_REG_SZ, NULL, &szData, &dwSize) == ERROR_SUCCESS)
lc.launch_options = szData;
record.launch_configs[0] = lc;
/*
dwSize = sizeof(szData) / sizeof(WCHAR);
if (RegGetValueW(hKey, szSubKey, L"exeFile", RRF_RT_REG_SZ, NULL, &szData, &dwSize) == ERROR_SUCCESS)
record.specialk.profile_dir = szData;
*/
record.specialk.profile_dir = lc.executable;
record.specialk.injection.injection.type = sk_install_state_s::Injection::Type::Global;
std::pair <std::string, app_record_s>
GOG(record.names.normal, record);
apps->emplace_back(GOG);
}
}
}
}
dwIndex++;
} while (1);
}
RegCloseKey(hKey);
// If an item was read, see if we can detect GOG Galaxy as well
if (dwIndex > 0)
{
if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, LR"(SOFTWARE\GOG.com\GalaxyClient\)", 0, KEY_READ | KEY_WOW64_32KEY, &hKey) == ERROR_SUCCESS)
{
dwSize = sizeof(szData) / sizeof(WCHAR);
if (RegGetValueW(hKey, NULL, L"clientExecutable", RRF_RT_REG_SZ, NULL, szData, &dwSize) == ERROR_SUCCESS)
{
extern std::wstring GOGGalaxy_Path;
extern std::wstring GOGGalaxy_Folder;
extern bool GOGGalaxy_Installed;
GOGGalaxy_Folder = szData;
dwSize = sizeof(szData) / sizeof(WCHAR);
if (RegGetValueW(hKey, L"paths", L"client", RRF_RT_REG_SZ, NULL, szData, &dwSize) == ERROR_SUCCESS)
{
GOGGalaxy_Path = SK_FormatStringW(LR"(%ws\%ws)", szData, GOGGalaxy_Folder.c_str());
if (PathFileExistsW(GOGGalaxy_Path.c_str()))
GOGGalaxy_Installed = true;
}
}
RegCloseKey(hKey);
// Galaxy User ID
extern std::wstring GOGGalaxy_UserID;
dwSize = sizeof(szData) / sizeof(WCHAR);
if (RegOpenKeyExW(HKEY_CURRENT_USER, LR"(SOFTWARE\GOG.com\Galaxy\settings\)", 0, KEY_READ, &hKey) == ERROR_SUCCESS)
{
if (RegGetValueW(hKey, NULL, L"userId", RRF_RT_REG_SZ, NULL, &szData, &dwSize) == ERROR_SUCCESS)
GOGGalaxy_UserID = szData;
RegCloseKey(hKey);
}
}
}
}
}
| 38.595745 | 158 | 0.598953 | ColonelGerdauf |
58f8e45d5382e7466711e24f039dabb5293fbd25 | 374 | hpp | C++ | .experimentals/include/amtrs/io/functions.hpp | isaponsoft/libamtrs | 5adf821ee15592fc3280985658ca8a4b175ffcaa | [
"BSD-2-Clause-FreeBSD"
] | 1 | 2019-12-10T02:12:49.000Z | 2019-12-10T02:12:49.000Z | .experimentals/include/amtrs/io/functions.hpp | isaponsoft/libamtrs | 5adf821ee15592fc3280985658ca8a4b175ffcaa | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | .experimentals/include/amtrs/io/functions.hpp | isaponsoft/libamtrs | 5adf821ee15592fc3280985658ca8a4b175ffcaa | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | /* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *
* Use of this source code is governed by a BSD-style license that *
* can be found in the LICENSE file. */
#ifndef __libamtrs__io__functions__hpp
#define __libamtrs__io__functions__hpp
#include "def.hpp"
#include AMTRS_PLATFORM_INCLUDE(io-functions.hpp)
#endif
| 34 | 72 | 0.700535 | isaponsoft |
58f8e7b49afbd778b849e3052f126235103b460c | 816 | cpp | C++ | luogu/CF977F.cpp | delphi122/knowledge_planet | e86cb8f9aa47ef8918cde0e814984a6535023c21 | [
"Apache-2.0"
] | 1 | 2020-07-24T03:07:08.000Z | 2020-07-24T03:07:08.000Z | luogu/CF977F.cpp | delphi122/knowledge_planet | e86cb8f9aa47ef8918cde0e814984a6535023c21 | [
"Apache-2.0"
] | null | null | null | luogu/CF977F.cpp | delphi122/knowledge_planet | e86cb8f9aa47ef8918cde0e814984a6535023c21 | [
"Apache-2.0"
] | null | null | null | //
// Created by yangtao on 20-11-8.
//
//
// Created by yangtao on 2020/11/1.
//
#include<iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <map>
using namespace std;
const int N = 2e5 + 5;
int n, ans , v;
int a[N];
map<int, int> mm;
int main() {
cin >> n;
for(int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
mm[a[i]] = max(mm[a[i]], mm[a[i]-1] + 1);
if( mm[a[i]] > ans ) ans = mm[a[i]], v = a[i];
}
//// map<int,int>::iterator it = mm.begin();
// auto it = mm.begin();
// for(; it != mm.end(); it++) {
// cout << it->first << " " << it->second<< endl;
// }
cout << ans << endl;
for(int i = 1; i <= n; i++) {
if( a[i] == v - ans + 1) {
cout << i << " ";
ans--;
}
}
return 0;
}
| 20.4 | 56 | 0.436275 | delphi122 |
58fd0ccae0bff05ff70dbb867da0b748f9610784 | 647 | cpp | C++ | contest/1523/a/a.cpp | GoatGirl98/cf | 4077ca8e0fe29dc2bbb7b60166989857cc062e17 | [
"MIT"
] | null | null | null | contest/1523/a/a.cpp | GoatGirl98/cf | 4077ca8e0fe29dc2bbb7b60166989857cc062e17 | [
"MIT"
] | null | null | null | contest/1523/a/a.cpp | GoatGirl98/cf | 4077ca8e0fe29dc2bbb7b60166989857cc062e17 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define clog(x) std::clog << (#x) << " is " << (x) << '\n';
using LL = long long;
int main() {
//freopen("in", "r", stdin);
std::cin.tie(nullptr)->sync_with_stdio(false);
int cas = 1;
std::cin >> cas;
while (cas--) {
int n, m;
std::string a;
std::cin >> n >> m >> a;
a = std::string("0") + a + std::string("0");
m = std::min(n, m);
while (m--) {
std::string s = a;
for (int i = 1; i <= n; ++i) if (a[i] == '0') {
if ((a[i - 1] == '1') ^ a[i + 1] == '1') {
s[i] = '1';
}
}
std::swap(s, a);
}
for (int i = 1; i <= n; ++i) std::cout << a[i];
std::cout << '\n';
}
return 0;
} | 22.310345 | 59 | 0.434312 | GoatGirl98 |
58fef46ff52b59a4abbdafc630afa4314be7880a | 1,111 | cpp | C++ | lib/save_obj.cpp | CraGL/SubdivisionSkinning | c593a7a4e38a49716e9d3981824871a7b6c29324 | [
"Apache-2.0"
] | 19 | 2017-03-29T00:14:00.000Z | 2021-11-27T15:44:44.000Z | lib/save_obj.cpp | Myzhencai/SubdivisionSkinning | c593a7a4e38a49716e9d3981824871a7b6c29324 | [
"Apache-2.0"
] | 1 | 2019-05-08T21:48:11.000Z | 2019-05-08T21:48:11.000Z | lib/save_obj.cpp | Myzhencai/SubdivisionSkinning | c593a7a4e38a49716e9d3981824871a7b6c29324 | [
"Apache-2.0"
] | 5 | 2017-04-23T17:52:44.000Z | 2020-06-28T18:00:26.000Z | #include "save_obj.h"
#include <iostream>
#include <fstream>
namespace save_obj
{
void save_mesh( const std::string& out_path, const std::vector< std::vector< int > >& faces, const std::vector< std::vector< real_t > >& vertices, const std::string& header_message )
{
std::ofstream out( out_path );
save_mesh( out, faces, vertices, header_message );
std::cout << "Saved a mesh to: " << out_path << '\n';
}
void save_mesh( std::ostream& out, const std::vector< std::vector< int > >& faces, const std::vector< std::vector< real_t > >& vertices, const std::string& header_message )
{
// Save an optional header message.
out << header_message;
// Save vertices.
for( const auto& vert: vertices )
{
out << "v";
for( const auto& coord: vert )
{
out << ' ' << coord;
}
out << '\n';
}
out << '\n';
for( const auto& f: faces )
{
out << 'f';
for( const auto& vi : f )
{
// Vertices are 1-indexed.
out << ' ' << (vi+1);
}
out << '\n';
}
}
}
| 25.25 | 182 | 0.531953 | CraGL |
4500146138fdc658e2e90b3d655f9689fe73331b | 11,131 | cpp | C++ | src/tpcc/DBtxnNewOrder.cpp | bailuding/centiman | 213eab0bd391822cbc9a01644979f8409440c376 | [
"Apache-2.0"
] | 4 | 2016-07-14T18:11:39.000Z | 2021-04-14T01:27:38.000Z | src/tpcc/DBtxnNewOrder.cpp | bailuding/centiman | 213eab0bd391822cbc9a01644979f8409440c376 | [
"Apache-2.0"
] | null | null | null | src/tpcc/DBtxnNewOrder.cpp | bailuding/centiman | 213eab0bd391822cbc9a01644979f8409440c376 | [
"Apache-2.0"
] | 1 | 2015-11-23T17:23:43.000Z | 2015-11-23T17:23:43.000Z | //
// DBtxnNewOrder.cpp
// centiman TPCC
//
// Created by Alan Demers on 11/1/12.
// Copyright (c) 2012 ademers. All rights reserved.
//
//#include <unordered_set>
#include <set>
#include <tpcc/Tables.h>
#include <tpcc/DB.h>
#include <util/const.h>
namespace TPCC {
/*
* New Order Transaction ...
*/
int DB::txnNewOrder() {
int ans;
uint16_t theW_ID = terminal_w_id;
uint16_t theT_ID = terminal_id;
time_t now = time(0);
/*
* generate the input data ...
*/
uint16_t theD_ID = dg.uniformInt(0, numDISTRICTs_per_WAREHOUSE);
uint32_t theC_ID = dg.NURand(dg.A_for_C_ID, 1, numCUSTOMERs_per_DISTRICT, dg.C_for_C_ID) - 1; // in [0..numCUSTOMERs_per_DISTRICT)
uint16_t theOL_CNT = dg.uniformInt(5, 16);
/* choose items, quantities and supplying warehouses ... */
uint32_t i_ids[15];
uint16_t supply_w_ids[15];
uint16_t ol_quantities[15];
uint16_t all_local = 1;
{ /* do not order the same item twice ... */
// std::unordered_set<uint32_t> i_id_set;
std::set<uint32_t> i_id_set;
int ol = 0;
while( ol < theOL_CNT ) {
uint32_t tmp_i_id = dg.NURand(dg.A_for_OL_I_ID, 1, numITEMs, dg.C_for_OL_I_ID) - 1; // in [0..numITEMs)
if (i_id_set.find(tmp_i_id) != i_id_set.end()) continue;
// if( i_id_set.count(tmp_i_id) > 0 ) continue;
i_id_set.insert(tmp_i_id); i_ids[ol] = tmp_i_id;
supply_w_ids[ol] = theW_ID;
if( (numWAREHOUSEs > 1) && dg.flip(0.01) ) /* nonlocal warehouse */ {
all_local = 0;
do { supply_w_ids[ol] = dg.uniformInt(0, numWAREHOUSEs); } while( supply_w_ids[ol] == theW_ID );
}
ol_quantities[ol] = dg.uniformInt(1, 11);
ol++;
}
}
/* TODO: force rollback 1% of time ... */
// if( dg.flip(0.01) ) { i_ids[theOL_CNT-1] = (uint32_t)(-1); }
/*
* issue reads ...
*/
/* WAREHOUSE table ... */
TblWAREHOUSE::Key * pkW = new TblWAREHOUSE::Key(theW_ID);
ans = conn.requestRead(pkW);
/* DISTRICT table ... */
/* TblDISTRICT::Key * pkD = new TblDISTRICT::Key(theW_ID, theD_ID);
ans = conn.requestRead(pkD); pkD = 0;*/
/* DISTRICT_NEXT_O_ID table ... */
TblDISTRICT_NEXT_O_ID::Key * pkD_NEXT_O_ID = new TblDISTRICT_NEXT_O_ID::Key(theW_ID, theD_ID, theT_ID);
ans = conn.requestRead(pkD_NEXT_O_ID); delete pkD_NEXT_O_ID;
/* CUSTOMER table ... */
TblCUSTOMER::Key * pkC = new TblCUSTOMER::Key(theW_ID, theD_ID, theC_ID);
ans = conn.requestRead(pkC); delete pkC;
/* ITEM and STOCK tables ... */
for( int ol = 0; ol < theOL_CNT; ol++ ) {
TblITEM::Key * pkI = new TblITEM::Key(i_ids[ol]);
ans = conn.requestRead(pkI); delete pkI;
TblSTOCK::Key * pkS = new TblSTOCK::Key(supply_w_ids[ol], i_ids[ol]);
ans = conn.requestRead(pkS); delete pkS;
}
/*
* Get and process read results in the order they were issued ...
*/
uint32_t o_id;
double d_tax;
double c_discount;
char * c_last = 0;
char c_credit[2]; // 'BC' or 'GC'
double c_credit_lim;
/* WAREHOUSE table ... */
TblWAREHOUSE::Row * prW = 0;
Seqnum * pSeqnum = NULL;
ans = conn.getReadResult( ((::Value **)(&prW)), &pSeqnum );
if (*pSeqnum == Const::SEQNUM_NULL) {
pkW->print();
}
assert( !(prW->isNULL() || *pSeqnum == Const::SEQNUM_NULL) );
assert( !prW->isNULL(TblWAREHOUSE::Row::W_TAX) );
double w_tax = prW->getCol_double(TblWAREHOUSE::Row::W_TAX);
/* DISTRICT table ... */
/* TblDISTRICT::Row * prD = 0;
ans = conn.getReadResult( ((::Value **)(&prD)), &pSeqnum );
assert( !(prD->isNULL() || *pSeqnum == Const::SEQNUM_NULL) );
assert( !prD->isNULL(TblDISTRICT::Row::D_TAX) );
d_tax = prD->getCol_double(TblDISTRICT::Row::D_TAX);
assert( !prD->isNULL(TblDISTRICT::Row::D_NEXT_O_ID) );*/
/* DISTRICT_NEXT_O_ID table ... */
TblDISTRICT::Row * prD_NEXT_O_ID = 0;
ans = conn.getReadResult( ((::Value **)(&prD_NEXT_O_ID)), &pSeqnum );
o_id = prD_NEXT_O_ID->getCol_uint32(TblDISTRICT_NEXT_O_ID::Row::D_NEXT_O_ID);
prD_NEXT_O_ID->putCol_uint32(TblDISTRICT_NEXT_O_ID::Row::D_NEXT_O_ID, o_id+1);
pkD_NEXT_O_ID = new TblDISTRICT_NEXT_O_ID::Key(theW_ID, theD_ID, theT_ID);
ans = conn.requestWrite(pkD_NEXT_O_ID, prD_NEXT_O_ID); delete pkD_NEXT_O_ID;
/* CUSTOMER table ... */
TblCUSTOMER::Row * prC = 0;
ans = conn.getReadResult( ((::Value **)(&prC)), &pSeqnum );
assert( !(prC->isNULL() || *pSeqnum == Const::SEQNUM_NULL));
assert( !prC->isNULL(TblCUSTOMER::Row::C_DISCOUNT) );
c_discount = prC->getCol_double(TblCUSTOMER::Row::C_DISCOUNT);
assert( !prC->isNULL(TblCUSTOMER::Row::C_LAST) );
c_last = prC->getCol_cString(TblCUSTOMER::Row::C_LAST);
assert( !prC->isNULL(TblCUSTOMER::Row::C_CREDIT) );
ans = prC->getCol(TblCUSTOMER::Row::C_CREDIT, ((uint8_t *)(&c_credit[0])), (sizeof c_credit));
assert( ans == 2 );
assert( !prC->isNULL(TblCUSTOMER::Row::C_CREDIT_LIM) );
c_credit_lim = prC->getCol_double(TblCUSTOMER::Row::C_CREDIT_LIM);
/* create and write new rows for ORDER, ORDER_INDEX, NEW_ORDER ... */
TblORDER::Key * pkO = new TblORDER::Key( theW_ID, theD_ID, o_id, theT_ID );
TblORDER::Row * prO = new TblORDER::Row; prO->reset();
prO->putCol_time(TblORDER::Row::O_ENTRY_D, now);
prO->putCol_uint16(TblORDER::Row::O_OL_CNT, theOL_CNT);
prO->putCol_uint16(TblORDER::Row::O_ALL_LOCAL, all_local);
ans = conn.requestWrite(pkO, prO); delete pkO; delete prO;
TblORDER_INDEX::Key * pkOX = new TblORDER_INDEX::Key( theW_ID, theD_ID, theC_ID, theT_ID );
TblORDER_INDEX::Row * prOX = new TblORDER_INDEX::Row; prOX->reset();
prOX->putCol_uint32(TblORDER_INDEX::Row::OX_O_ID, o_id);
ans = conn.requestWrite(pkOX, prOX); delete pkOX; delete prOX;
TblNEW_ORDER::Key * pkNO = new TblNEW_ORDER::Key( theW_ID, theD_ID, o_id, theT_ID );
TblNEW_ORDER::Row * prNO = new TblNEW_ORDER::Row; prNO->reset();
ans = conn.requestWrite(pkNO, prNO); delete pkNO; delete prNO;
/* process ordered items, writing ORDER_LINE rows and updating STOCK table as needed ... */
double total_amount = 0.0;
for( int ol = 0; ol < theOL_CNT; ol++ ) {
/* retrieve ITEM and STOCK read results ... */
TblITEM::Row * prI = 0;
ans = conn.getReadResult( ((::Value **)(&prI)), &pSeqnum );
if( (prI->isNULL() || *pSeqnum == Const::SEQNUM_NULL)) /* request for unused item */ {
ans = (-1); goto Out;
}
assert( !(prI->isNULL(TblITEM::Row::I_PRICE)) );
double i_price = prI->getCol_double(TblITEM::Row::I_PRICE);
assert( !(prI->isNULL(TblITEM::Row::I_NAME)) );
char * i_name = prI->getCol_cString(TblITEM::Row::I_NAME);
assert( !(prI->isNULL(TblITEM::Row::I_DATA)) );
char * i_data = prI->getCol_cString(TblITEM::Row::I_DATA);
TblSTOCK::Row * prS = 0;
ans = conn.getReadResult( ((::Value **)(&prS)), &pSeqnum);
assert( !(prS->isNULL() || *pSeqnum == Const::SEQNUM_NULL) );
assert( !(prS->isNULL(TblSTOCK::Row::S_DIST_01+supply_w_ids[ol])) );
char * s_dist_xx = prS->getCol_cString(TblSTOCK::Row::S_DIST_01+supply_w_ids[ol]);
assert( !(prS->isNULL(TblSTOCK::Row::S_DATA)) );
char * s_data = prS->getCol_cString(TblSTOCK::Row::S_DATA);
assert( !(prS->isNULL(TblSTOCK::Row::S_QUANTITY)) );
uint16_t s_quantity = prS->getCol_uint16(NULL, TblSTOCK::Row::S_QUANTITY);
assert( !(prS->isNULL(TblSTOCK::Row::S_YTD)) );
uint32_t s_ytd = prS->getCol_uint32(TblSTOCK::Row::S_YTD);
assert( !(prS->isNULL(TblSTOCK::Row::S_ORDER_CNT)) );
uint16_t s_order_cnt = prS->getCol_uint16(NULL, TblSTOCK::Row::S_ORDER_CNT);
assert( !(prS->isNULL(TblSTOCK::Row::S_REMOTE_CNT)) );
uint16_t s_remote_cnt = prS->getCol_uint16(NULL, TblSTOCK::Row::S_REMOTE_CNT);
/* update the STOCK row ... */
if( s_quantity >= (ol_quantities[ol] + 10) ) {
prS->putCol_uint16( TblSTOCK::Row::S_QUANTITY, s_quantity - ol_quantities[ol] );
} else {
prS->putCol_uint16( TblSTOCK::Row::S_QUANTITY, s_quantity + 91 - ol_quantities[ol] );
}
prS->putCol_uint32(TblSTOCK::Row::S_YTD, s_ytd + ol_quantities[ol]);
prS->putCol_uint16(TblSTOCK::Row::S_ORDER_CNT, s_order_cnt+1);
if( supply_w_ids[ol] != theW_ID ) {
prS->putCol_uint16( TblSTOCK::Row::S_REMOTE_CNT, s_remote_cnt+1 );
}
TblSTOCK::Key * pkS = new TblSTOCK::Key(supply_w_ids[ol], i_ids[ol]);
ans = conn.requestWrite(pkS, prS); delete pkS;
/* insert an ORDER_LINE row ... */
TblORDER_LINE::Key * pkOL = new TblORDER_LINE::Key(theW_ID, theD_ID, o_id, ol, theT_ID);
TblORDER_LINE::Row * prOL = new TblORDER_LINE::Row; prOL->reset();
double ol_amount = ol_quantities[ol] * i_price;
prOL->putCol_uint32(TblORDER_LINE::Row::OL_I_ID, i_ids[ol]);
prOL->putCol_uint16(TblORDER_LINE::Row::OL_SUPPLY_W_ID, supply_w_ids[ol]);
// OL_DELIVERY_D is NULL
prOL->putCol_uint16(TblORDER_LINE::Row::OL_QUANTITY, ol_quantities[ol]);
prOL->putCol_double(TblORDER_LINE::Row::OL_AMOUNT, ol_amount);
prOL->putCol(TblORDER_LINE::Row::OL_DIST_INFO, (uint8_t *)(s_dist_xx), strlen(s_dist_xx));
ans = conn.requestWrite(pkOL, prOL); delete pkOL; delete prOL;
/* accumulate total_amount ... */
total_amount += ol_amount * (1.0 - c_discount) * (1.0 + w_tax + d_tax);
/* the funky "brand-generic" test ... */
char brand_generic = 'B';
if( (strstr(i_data, "ORIGINAL") == 0) || (strstr(i_data, "ORIGINAL") == 0) ) {
brand_generic = 'G';
}
/* clean up */
delete [] i_name; delete [] i_data;
delete [] s_dist_xx; delete [] s_data;
}
ans = 0;
Out: ;
/* clean up */
delete [] c_last;
/* clean keys */
delete pkW;
return ans;
}
};
| 45.247967 | 138 | 0.55844 | bailuding |
4500cd1403bcaa17d8b422096cc0f59b9b4c1f93 | 964 | cpp | C++ | mycobot/src/detect.cpp | tylerjw/mycobot | fa37de7b38e02973f61b92529b3ba2cebad2e71b | [
"BSD-3-Clause"
] | 4 | 2022-03-03T22:20:45.000Z | 2022-03-09T23:06:19.000Z | mycobot/src/detect.cpp | tylerjw/mycobot | fa37de7b38e02973f61b92529b3ba2cebad2e71b | [
"BSD-3-Clause"
] | null | null | null | mycobot/src/detect.cpp | tylerjw/mycobot | fa37de7b38e02973f61b92529b3ba2cebad2e71b | [
"BSD-3-Clause"
] | 2 | 2022-03-01T22:26:31.000Z | 2022-03-09T16:41:18.000Z | #include "mycobot/detect.hpp"
#include <serial/serial.h>
#include <fp/all.hpp>
#include <optional>
#include <string>
#include <vector>
namespace mycobot {
std::vector<std::string> get_ports() {
return []() {
std::vector<std::string> ret;
for (auto const& port_info : serial::list_ports())
ret.push_back(port_info.port);
return ret;
}();
}
std::optional<std::string> get_port_of_robot() {
auto const ports = []() {
std::vector<std::string> ret;
for (auto const& port_info : serial::list_ports()) {
// fmt::print("PortInfo: {}, {}, {}\n",
// port_info.port, port_info.description, port_info.hardware_id);
if (port_info.hardware_id == "USB VID:PID=1a86:55d4 SNR=52D2052903") {
// if (port_info.hardware_id == "0xEA60") {
ret.push_back(port_info.port);
}
}
return ret;
}();
if (ports.size() > 0) {
return ports.at(0);
}
return std::nullopt;
}
} // namespace mycobot
| 22.952381 | 76 | 0.613071 | tylerjw |
450274617d74b42f9fcb3455ee3c4477f8799f15 | 4,291 | cpp | C++ | src/tests/libs/alm/FriendLayout.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 1,338 | 2015-01-03T20:06:56.000Z | 2022-03-26T13:49:54.000Z | src/tests/libs/alm/FriendLayout.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 15 | 2015-01-17T22:19:32.000Z | 2021-12-20T12:35:00.000Z | src/tests/libs/alm/FriendLayout.cpp | Kirishikesan/haiku | 835565c55830f2dab01e6e332cc7e2d9c015b51e | [
"MIT"
] | 350 | 2015-01-08T14:15:27.000Z | 2022-03-21T18:14:35.000Z | /*
* Copyright 2007-2008, Christof Lutteroth, lutteroth@cs.auckland.ac.nz
* Copyright 2007-2008, James Kim, jkim202@ec.auckland.ac.nz
* Copyright 2010, Clemens Zeidler <haiku@clemens-zeidler.de>
* Copyright 2012, Haiku, Inc.
* Distributed under the terms of the MIT License.
*/
#include <Application.h>
#include <Button.h>
#include <LayoutBuilder.h>
#include <List.h>
#include <Message.h>
#include <StringView.h>
#include <Window.h>
// include this for ALM
#include "ALMLayout.h"
#include "ALMLayoutBuilder.h"
#include "LinearProgrammingTypes.h"
class FriendWindow : public BWindow {
public:
FriendWindow(BRect frame)
:
BWindow(frame, "ALM Friend Test", B_TITLED_WINDOW,
B_QUIT_ON_WINDOW_CLOSE | B_AUTO_UPDATE_SIZE_LIMITS),
fLayout2(NULL),
fBoom(NULL),
fLeft(NULL),
fTop(NULL),
fRight(NULL),
fBottom(NULL)
{
BButton* button1 = _MakeButton("friends!");
BButton* button2 = _MakeButton("friends!");
BButton* button3 = _MakeButton("friends!");
BButton* button4 = _MakeButton("friends!");
BButton* button5 = _MakeButton("friends!");
BButton* button6 = _MakeButton("friends!");
BALMLayout* layout1 = new BALMLayout(10, 10);
BView* almView1 = _MakeALMView(layout1);
BReference<XTab> xTabs[2];
layout1->AddXTabs(xTabs, 2);
BALM::BALMLayoutBuilder(layout1)
.Add(button1, layout1->Left(), layout1->Top(),
xTabs[0], layout1->Bottom())
.StartingAt(button1)
.AddToRight(button2, xTabs[1])
.AddToRight(button3, layout1->Right());
fLayout2 = new BALMLayout(10, 10, layout1);
BView* almView2 = _MakeALMView(fLayout2);
BALM::BALMLayoutBuilder(fLayout2)
.Add(button4, fLayout2->Left(), fLayout2->Top(), xTabs[0])
.StartingAt(button4)
.AddBelow(button5, NULL, xTabs[1], fLayout2->Right())
.AddBelow(button6, fLayout2->Bottom(), xTabs[0]);
fLeft = fLayout2->Left();
fBottom = fLayout2->BottomOf(button5);
fTop = fLayout2->BottomOf(button4);
fRight = xTabs[1];
layout1->AreaFor(button2)->SetContentAspectRatio(1.0f);
fLayout2->Solver()->AddConstraint(-1.0f, layout1->Left(), 1.0f, xTabs[0],
LinearProgramming::kLE, 90.0f);
BButton* archiveButton = new BButton("clone", new BMessage('arcv'));
archiveButton->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED,
B_SIZE_UNSET));
BLayoutBuilder::Group<>(this, B_VERTICAL)
.Add(almView1->GetLayout())
.Add(almView2->GetLayout())
.Add(archiveButton);
}
void MessageReceived(BMessage* message)
{
switch (message->what) {
case 'BOOM':
if (!fBoom) {
fBoom = _MakeButton("BOOM");
fLayout2->AddView(fBoom, fLeft, fTop,
fRight, fBottom);
} else {
if (fBoom->IsHidden(fBoom))
fBoom->Show();
else
fBoom->Hide();
}
break;
case 'arcv': {
BView* view = GetLayout()->View();
BMessage archive;
status_t err = view->Archive(&archive, true);
BWindow* window = new BWindow(BRect(30, 30, 400, 400),
"ALM Friend Test Clone", B_TITLED_WINDOW,
B_QUIT_ON_WINDOW_CLOSE | B_AUTO_UPDATE_SIZE_LIMITS);
window->SetLayout(new BGroupLayout(B_VERTICAL));
BView* clone;
if (err == B_OK)
err = BUnarchiver::InstantiateObject(&archive, clone);
if (err != B_OK)
window->AddChild(new BStringView("", "An error occurred!"));
else {
window->AddChild(clone);
}
window->Show();
break;
}
default:
BWindow::MessageReceived(message);
}
}
private:
BButton* _MakeButton(const char* label)
{
BButton* button = new BButton(label, new BMessage('BOOM'));
button->SetExplicitMinSize(BSize(10, 50));
button->SetExplicitMaxSize(BSize(500, 500));
button->SetExplicitAlignment(BAlignment(B_ALIGN_USE_FULL_WIDTH,
B_ALIGN_USE_FULL_HEIGHT));
return button;
}
BView* _MakeALMView(BALMLayout* layout)
{
BView* view = new BView(NULL, 0, layout);
view->SetViewUIColor(B_PANEL_BACKGROUND_COLOR);
return view;
}
BALMLayout* fLayout2;
BButton* fBoom;
XTab* fLeft;
YTab* fTop;
XTab* fRight;
YTab* fBottom;
};
class Friend : public BApplication {
public:
Friend()
:
BApplication("application/x-vnd.haiku.Friend")
{
BRect frameRect;
frameRect.Set(100, 100, 300, 300);
FriendWindow* window = new FriendWindow(frameRect);
window->Show();
}
};
int
main()
{
Friend app;
app.Run();
return 0;
}
| 24.66092 | 75 | 0.680028 | Kirishikesan |
4504f9adfd0c992fe47af0cbffea8e9a38dc2442 | 573 | cpp | C++ | week1/fileIO.cpp | shaili-regmi/cpp-examples | 66c8813b6ef301604c5003b103c1f11d5ee7519b | [
"MIT"
] | null | null | null | week1/fileIO.cpp | shaili-regmi/cpp-examples | 66c8813b6ef301604c5003b103c1f11d5ee7519b | [
"MIT"
] | null | null | null | week1/fileIO.cpp | shaili-regmi/cpp-examples | 66c8813b6ef301604c5003b103c1f11d5ee7519b | [
"MIT"
] | 4 | 2021-02-18T18:34:47.000Z | 2021-03-03T18:05:26.000Z | // Bryn Mawr College, 2021
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;
int main(int argc, char** argv)
{
string filename = "../files/grades.txt";
ifstream file(filename);
if (!file) // true if the file is valid
{
cout << "Cannot load file: " << filename << endl;
return 1;
}
int num = 0;
float sum = 0;
while (file)
{
int grade;
file >> grade;
sum += grade;
num++;
}
cout << "The average is " << sum/num << endl;
file.close();
return 0;
}
| 16.371429 | 55 | 0.558464 | shaili-regmi |
4505c2df666176b029ee7d913f366e9ea6e34bdd | 303 | hpp | C++ | States.hpp | nvg-ict/StateMachineTemplate | abae3222535d20bea2aa82ba4aca83ebab1081dc | [
"Apache-2.0"
] | null | null | null | States.hpp | nvg-ict/StateMachineTemplate | abae3222535d20bea2aa82ba4aca83ebab1081dc | [
"Apache-2.0"
] | null | null | null | States.hpp | nvg-ict/StateMachineTemplate | abae3222535d20bea2aa82ba4aca83ebab1081dc | [
"Apache-2.0"
] | null | null | null | /*
* States.hpp
*
* Created on: Mar 4, 2017
* Author: nico
*/
#ifndef STATES_HPP_
#define STATES_HPP_
/**
* @brief States for the statemachine
*/
namespace States
{
enum Events
{
evInitReady,
evTask,
evTaskDone,
evSTOP,
evSTOPdisable
};
}
#endif /* STATES_HPP_ */
| 10.448276 | 37 | 0.613861 | nvg-ict |
45085131ecd6b21788f40dda8cae150352d2802d | 982 | hpp | C++ | Haar.hpp | jdstmporter/Reason-Wavelet | 691e6e3a31911082751c58f5f91cfd4e7495cee6 | [
"BSD-3-Clause"
] | null | null | null | Haar.hpp | jdstmporter/Reason-Wavelet | 691e6e3a31911082751c58f5f91cfd4e7495cee6 | [
"BSD-3-Clause"
] | null | null | null | Haar.hpp | jdstmporter/Reason-Wavelet | 691e6e3a31911082751c58f5f91cfd4e7495cee6 | [
"BSD-3-Clause"
] | null | null | null | /*
* Haar.hpp
*
* Created on: 6 Jul 2020
* Author: julianporter
*/
#ifndef SRC_HAAR_HPP_
#define SRC_HAAR_HPP_
#include <algorithm>
#include <vector>
#include <cmath>
#include <map>
#include <memory>
#include "base.hpp"
namespace meromorph { namespace haar {
class Haar {
private:
uint32 N;
std::vector<float32> thresholds;
uint32 block;
float32 * row;
float32 * tmp;
float32 * details;
uint32 length(const uint32 n) const;
float32 * begin(const uint32 n);
float32 * end(const uint32 n);
public:
Haar(const uint32 N_);
Haar(const Haar &) = default;
virtual ~Haar();
uint32 size() const { return block; }
void reset();
void analyse(float32 *);
void threshold(const float32 scale=1.0);
void scale();
void synthesise(float32 *out);
float32 absMaximum() const;
void setThreshold(const uint32 index,const float32 value);
};
}}
#endif /* SRC_HAAR_HPP_ */
| 15.587302 | 62 | 0.630346 | jdstmporter |
450bfb405f75a9351e7c5860d6e97269891d2bc6 | 235 | cpp | C++ | src/0189.cpp | shuihan0555/LeetCode-Solutions-in-Cpp17 | 8bb69fc546486c5e73839431204927626601dd18 | [
"MIT"
] | null | null | null | src/0189.cpp | shuihan0555/LeetCode-Solutions-in-Cpp17 | 8bb69fc546486c5e73839431204927626601dd18 | [
"MIT"
] | null | null | null | src/0189.cpp | shuihan0555/LeetCode-Solutions-in-Cpp17 | 8bb69fc546486c5e73839431204927626601dd18 | [
"MIT"
] | null | null | null | class Solution {
public:
void rotate(vector<int>& nums, int k) {
k %= size(nums);
reverse(begin(nums), end(nums));
reverse(begin(nums), begin(nums) + k);
reverse(begin(nums) + k, end(nums));
}
}; | 26.111111 | 46 | 0.544681 | shuihan0555 |
450dd6b373337e29c554aa464975f95e7324aa6f | 4,501 | cpp | C++ | of_v0.8.0_vs_release/apps/myApps/GRT_Predict/src/fullBodyTracker.cpp | MatthiasHinz/Gesture_Recognizer_for_Web_GIS | 0ced6d72684d0f2d84b89c6afda2f7dcee0dc6b9 | [
"MIT"
] | null | null | null | of_v0.8.0_vs_release/apps/myApps/GRT_Predict/src/fullBodyTracker.cpp | MatthiasHinz/Gesture_Recognizer_for_Web_GIS | 0ced6d72684d0f2d84b89c6afda2f7dcee0dc6b9 | [
"MIT"
] | null | null | null | of_v0.8.0_vs_release/apps/myApps/GRT_Predict/src/fullBodyTracker.cpp | MatthiasHinz/Gesture_Recognizer_for_Web_GIS | 0ced6d72684d0f2d84b89c6afda2f7dcee0dc6b9 | [
"MIT"
] | 1 | 2018-07-05T12:41:34.000Z | 2018-07-05T12:41:34.000Z | #include "fullBodyTracker.h"
int outOfSync = 0;
const int maxOutOFSync = 500;
FullBodyTracker::FullBodyTracker(void)
{
}
FullBodyTracker::~FullBodyTracker(void)
{
}
void FullBodyTracker::initTracker(void)
{
niteRc = userTracker.create();
userTracker.setSkeletonSmoothingFactor(0.8);
isTracking = false;
}
void FullBodyTracker::update(void)
{
nite::UserTrackerFrameRef userTrackerFrame;
niteRc = userTracker.readFrame(&userTrackerFrame);
//Do other perframe processing stuff
const nite::Array<nite::UserData>& users = userTrackerFrame.getUsers();
outOfSync++; //in case the user does not appear in the frame
for (int i = 0; i < users.getSize(); ++i)
{
const nite::UserData& user = users[i];
if(!isTracking && user.isVisible() && !user.isLost()){
userTracker.startSkeletonTracking(user.getId());
userTracker.startPoseDetection(user.getId(), nite::POSE_CROSSED_HANDS);
userTracker.startPoseDetection(user.getId(), nite::POSE_PSI);
isTracking = true;
printf("Found User!\n");
}
if (user.getSkeleton().getState() == nite::SKELETON_TRACKED){
if(user.isLost() || !user.isVisible()){
isTracking = false;
userTracker.stopSkeletonTracking(user.getId());
userTracker.stopPoseDetection(user.getId(), nite::POSE_CROSSED_HANDS);
userTracker.stopPoseDetection(user.getId(), nite::POSE_PSI);
printf("Lost User!\n");
continue;
}
outOfSync=0;//user appears --> user in sync
const nite::SkeletonJoint& head = user.getSkeleton().getJoint(nite::JOINT_HEAD);
const nite::SkeletonJoint& leftHand = user.getSkeleton().getJoint(nite::JOINT_LEFT_HAND);
const nite::SkeletonJoint& rightHand = user.getSkeleton().getJoint(nite::JOINT_RIGHT_HAND);
if(head.getPositionConfidence() > 0.1){ //rejecting very uncertain values
headCoordinates.x = head.getPosition().x;
headCoordinates.y = head.getPosition().y;
headCoordinates.z = head.getPosition().z;
}
if(leftHand.getPositionConfidence() > 0.1){
leftHandCoordinates.x = leftHand.getPosition().x;
leftHandCoordinates.y = leftHand.getPosition().y;
leftHandCoordinates.z = leftHand.getPosition().z;
leftHandPositionConfidence = leftHand.getPositionConfidence();
/* printf("%d. (%5.2f, %5.2f, %5.2f)) \n", user.getId(),
leftHandCoordinates.x,
leftHandCoordinates.y,
leftHandCoordinates.z);*/
}else leftHandPositionConfidence = 0;
if(rightHand.getPositionConfidence() > 0.1){
rightHandCoordinates.x = rightHand.getPosition().x;
rightHandCoordinates.y = rightHand.getPosition().y;
rightHandCoordinates.z = rightHand.getPosition().z;
rightHandPositionConfidence = rightHand.getPositionConfidence();
/*printf("%d. (%5.2f, %5.2f, %5.2f)) \n", user.getId(),
rightHandCoordinates.x,
rightHandCoordinates.y,
rightHandCoordinates.z);*/
}else rightHandPositionConfidence = 0;
//detect pose
/*nite::PoseData pose = user.getPose(nite::POSE_PSI);
if(pose.isHeld()){
printf("User holds PSI Pose\n");
}*/
nite::PoseData pose = user.getPose(nite::POSE_CROSSED_HANDS);
if(pose.isEntered()){
printf("User enters crossed hands pose (ESCAPE)\n");
BYTE keys[1] = {VK_ESCAPE};
GUIConnector::sendKeyboardInput(keys,1);
}
}
if(outOfSync == maxOutOFSync && isTracking){
isTracking = false;
userTracker.stopSkeletonTracking(user.getId());
printf("Lost User! (user out of sync)\n");
}
/*const nite::Array<nite::GestureData>& gestures = userTrackerFrame.getUserById(trackedUser).;
for (int i = 0; i < gestures.getSize(); ++i)
{
if (gestures[i].isComplete()){
nite::HandId newId;
handTracker.startHandTracking(gestures[i].getCurrentPosition(), &newId);
}
}*/
}
}
Point3f FullBodyTracker::getLeftHandCoordinates(void)
{
return leftHandCoordinates;
}
Point3f FullBodyTracker::getRightHandCoordinates(void)
{
return rightHandCoordinates;
}
Point3f FullBodyTracker::getTransformedLeftHandCoordinates(void)
{
Point3f out;
out.x=leftHandCoordinates.x - headCoordinates.x;
out.y=leftHandCoordinates.y - headCoordinates.y;
out.z=leftHandCoordinates.z - headCoordinates.z;
return out;
}
Point3f FullBodyTracker::getTransformedRightHandCoordinates(void)
{
Point3f out;
out.x=rightHandCoordinates.x - headCoordinates.x;
out.y=rightHandCoordinates.y - headCoordinates.y;
out.z=rightHandCoordinates.z - headCoordinates.z;
return out;
}
nite::UserTracker FullBodyTracker::getUserTracker(){
return userTracker;
} | 28.308176 | 96 | 0.714286 | MatthiasHinz |
450e2111cdbc102af7b01657673639af2fa38c9c | 505 | hh | C++ | CppPool/cpp_d09/ex04/Priest.hh | 667MARTIN/Epitech | 81095d8e7d54e9abd95541ee3dfcc3bc85d5cf0e | [
"MIT"
] | 40 | 2018-01-28T14:23:27.000Z | 2022-03-05T15:57:47.000Z | CppPool/cpp_d09/ex04/Priest.hh | 667MARTIN/Epitech | 81095d8e7d54e9abd95541ee3dfcc3bc85d5cf0e | [
"MIT"
] | 1 | 2021-10-05T09:03:51.000Z | 2021-10-05T09:03:51.000Z | CppPool/cpp_d09/ex04/Priest.hh | 667MARTIN/Epitech | 81095d8e7d54e9abd95541ee3dfcc3bc85d5cf0e | [
"MIT"
] | 73 | 2019-01-07T18:47:00.000Z | 2022-03-31T08:48:38.000Z | //
// Priest.hh for Priest in /home/gwendoline/Epitech/Tek2/Piscine_cpp/piscine_cpp_d09/ex02
//
// Made by Gwendoline Rodriguez
// Login <gwendoline@epitech.net>
//
// Started on Thu Jan 14 16:50:20 2016 Gwendoline Rodriguez
// Last update Thu Jan 14 18:54:34 2016 Gwendoline Rodriguez
//
#ifndef _PRIEST_HH
#define _PRIEST_HH
#include "Mage.hh"
class Priest : public Mage
{
public:
explicit Priest(const std::string&, int);
~Priest();
int CloseAttack();
void Heal();
};
#endif
| 18.035714 | 89 | 0.69901 | 667MARTIN |
451157df0d6dc6e5135e7f9ce2b8f510befffa7c | 2,765 | cpp | C++ | Code/Modules/mutalisk/dx9/dx9Helpers.cpp | mrneo240/suicide-barbie | c8b01f9c04755e7f6d1d261fc4a1600cd6705b96 | [
"MIT"
] | 57 | 2021-01-02T00:18:22.000Z | 2022-03-27T14:40:25.000Z | Code/Modules/mutalisk/dx9/dx9Helpers.cpp | mrneo240/suicide-barbie | c8b01f9c04755e7f6d1d261fc4a1600cd6705b96 | [
"MIT"
] | 1 | 2021-01-05T20:43:02.000Z | 2021-01-11T23:04:41.000Z | Code/Modules/mutalisk/dx9/dx9Helpers.cpp | mrneo240/suicide-barbie | c8b01f9c04755e7f6d1d261fc4a1600cd6705b96 | [
"MIT"
] | 8 | 2021-01-01T22:34:43.000Z | 2022-03-22T01:21:26.000Z | #include "dx9Helpers.h"
#include <string>
#include <stdlib.h>
#include "../errors.h"
using namespace dx;
unsigned calcTextureSize(IDirect3DTexture9 const& texture)
{
IDirect3DTexture9& tex = const_cast<IDirect3DTexture9&>(texture);
const int mipMapLevels = tex.GetLevelCount();
//
// Size calculated by this equation:
// 1. in case of uncompressed textures - width*height*bytesPerPixel.
// 2. in case of compressed textures - max(1, width/4)*max(1, height/4)*(DXTver == 1 ? 8 : 16).
// To treat both compressed and uncompressed textures uniformly lets use -
// bytes = max(1,width/divisor)*max(1,height/divisor)*multiplier, and in case of
// uncompressed textures use 1 for divisor and bytesPerPixel in place of multiplier.
//
int multiplier = 0;
int divisor = 1;
// Get first mip map level description:
D3DSURFACE_DESC sd;
tex.GetLevelDesc( 0, &sd );
// Initialize multiplier and divisor to match actual format:
switch (sd.Format) {
// 64 bpp???
case D3DFMT_A16B16G16R16:
multiplier = 8;
break;
// 32 bpp:
case D3DFMT_A2W10V10U10:
case D3DFMT_V16U16:
case D3DFMT_X8L8V8U8:
case D3DFMT_Q8W8V8U8:
case D3DFMT_A8R8G8B8:
case D3DFMT_X8R8G8B8:
case D3DFMT_A2B10G10R10:
case D3DFMT_A8B8G8R8:
case D3DFMT_X8B8G8R8:
case D3DFMT_G16R16:
case D3DFMT_A2R10G10B10:
multiplier = 4;
break;
// 24 bpp:
case D3DFMT_R8G8B8:
multiplier = 3;
break;
// 16 bpp:
case D3DFMT_V8U8:
case D3DFMT_L6V5U5:
case D3DFMT_A8P8:
case D3DFMT_A8L8:
case D3DFMT_R5G6B5:
case D3DFMT_X1R5G5B5:
case D3DFMT_A1R5G5B5:
case D3DFMT_A4R4G4B4:
case D3DFMT_A8R3G3B2:
case D3DFMT_X4R4G4B4:
multiplier = 2;
break;
// 8 bpp:
case D3DFMT_A4L4:
case D3DFMT_P8:
case D3DFMT_L8:
case D3DFMT_R3G3B2:
case D3DFMT_A8:
multiplier = 1;
break;
// Compressed:
case D3DFMT_DXT1:
divisor = 4;
multiplier = 8;
break;
case D3DFMT_DXT2:
case D3DFMT_DXT3:
case D3DFMT_DXT4:
case D3DFMT_DXT5:
divisor = 4;
multiplier = 16;
break;
// UNKNOWN FORMAT!
default:
return 0;
};
unsigned bytes = 0;
// Calculate size:
for ( int i = 0; i < mipMapLevels; ++i ) {
tex.GetLevelDesc( i, &sd );
bytes +=
max( 1, sd.Width / divisor ) *
max( 1, sd.Height / divisor ) * multiplier;
}
return bytes;
}
ResultCheck::ResultCheck( char const* errorMessage_, char const* messagePrefix_, char const* messagePostfix_ )
: errorMessage( errorMessage_ ),
messagePrefix( messagePrefix_ ),
messagePostfix( messagePostfix_ )
{
}
ResultCheck& ResultCheck ::operator= ( HRESULT result )
{
if( FAILED(result) )
{
THROW_DXERROR( result,
std::string( messagePrefix ) +
std::string( errorMessage ) +
std::string( messagePostfix ) );
}
return *this;
} | 21.10687 | 110 | 0.692586 | mrneo240 |
4511e68cd54adac8baea46b169c0a8a6b659ed9d | 904 | cpp | C++ | Algorithmic-Toolbox/Extra_Poly_Mul.cpp | saddhu1005/Coursera-DataStructuresAlgorithms | 847508c1e93246900700a63b981033ec84d85031 | [
"MIT"
] | 1 | 2019-04-01T20:05:25.000Z | 2019-04-01T20:05:25.000Z | Algorithmic-Toolbox/Extra_Poly_Mul.cpp | saddhu1005/Coursera-DataStructuresAlgorithms | 847508c1e93246900700a63b981033ec84d85031 | [
"MIT"
] | null | null | null | Algorithmic-Toolbox/Extra_Poly_Mul.cpp | saddhu1005/Coursera-DataStructuresAlgorithms | 847508c1e93246900700a63b981033ec84d85031 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll * multp(ll a[],ll b[],ll n,ll l, ll r)
{
ll *rs=new ll[n*2-1];
for(ll i=0;i<n*2-1;++i)
rs[i]=0;
if(n==1)
{
rs[0]=a[l]*b[l];
return rs;
}
rs=multp(a,b,n/2,l,r);
rs=multp(a,b,n/2,l+n/2,r+n/2);
ll *d0e=new ll[n/2];
for(ll i=0;i<n/2;++i)
d0e[i]=0;
d0e=multp(a,b,n/2,l,r+n/2);
ll *d1e=new ll[n/2];
for(ll i=0;i<n/2;++i)
d1e[i]=0;
d1e=multp(a,b,n/2,l+n/2,r);
for(ll i=n/2;i<n+n/2;++i)
{
rs[i]+=d1e[i-n/2]+d0e[i-n/2];
}
return rs;
}
int main()
{
ll n;
cin>>n;
ll a[n+1],b[n+1];
ll i;
for(i=0;i<n;++i)
{
cin>>a[i];
}
for(i=0;i<n;++i)
{
cin>>b[i];
}
ll *r=new ll[2*n-1];
r=multp(a,b,4,0,0);
for(i=2*n-2;i>=0;--i)
{
cout<<r[i]<<" ";
}
cout<<endl;
} | 17.72549 | 41 | 0.409292 | saddhu1005 |
4512708dfee92a546339acc57fc16ac517ba07c0 | 554 | hpp | C++ | libs/zswagcl/include/zswagcl/openapi-parser.hpp | Klebert-Engineering/zswag | 39c63bd4d2c4be5e95ddcc6f4573022dac9924e5 | [
"BSD-3-Clause"
] | 8 | 2021-03-17T01:41:58.000Z | 2022-02-22T13:26:13.000Z | libs/zswagcl/include/zswagcl/openapi-parser.hpp | Klebert-Engineering/zswag | 39c63bd4d2c4be5e95ddcc6f4573022dac9924e5 | [
"BSD-3-Clause"
] | 38 | 2020-05-04T08:57:40.000Z | 2022-02-21T11:22:57.000Z | libs/zswagcl/include/zswagcl/openapi-parser.hpp | Klebert-Engineering/zswag | 39c63bd4d2c4be5e95ddcc6f4573022dac9924e5 | [
"BSD-3-Clause"
] | 4 | 2020-06-03T15:07:44.000Z | 2021-10-04T07:55:39.000Z | #pragma once
#include <istream>
#include "zswagcl/openapi-config.hpp"
#include "httpcl/http-client.hpp"
#include "httpcl/http-settings.hpp"
namespace zswagcl
{
/**
* Download and parse OpenAPI config from URL.
*
* Throws on error.
*/
OpenAPIConfig fetchOpenAPIConfig(const std::string& url,
httpcl::IHttpClient& client,
httpcl::Config httpConfig = {});
/**
* Parse OpenAPI config from input-stream.
*
* Throws on error.
*/
OpenAPIConfig parseOpenAPIConfig(std::istream&);
}
| 19.103448 | 65 | 0.637184 | Klebert-Engineering |
45159869f3605b62595dd52d902b9c1c8b35a7ef | 2,804 | hpp | C++ | include/pmath/Matrix2.hpp | M4T1A5/ProbablyMath | fbf907ebfcb5a4d59c89fa240c20a1bb876b74be | [
"MIT"
] | null | null | null | include/pmath/Matrix2.hpp | M4T1A5/ProbablyMath | fbf907ebfcb5a4d59c89fa240c20a1bb876b74be | [
"MIT"
] | null | null | null | include/pmath/Matrix2.hpp | M4T1A5/ProbablyMath | fbf907ebfcb5a4d59c89fa240c20a1bb876b74be | [
"MIT"
] | null | null | null | #pragma once
#ifndef MATRIX2_PMATH_H
#define MATRIX2_PMATH_H
#include "Vector2.hpp"
#include <iostream>
#include <string>
namespace pmath
{
template<typename T>
class Matrix2
{
public:
Matrix2();
Matrix2(const T& a11, const T& a12,
const T& a21, const T& a22);
Matrix2(const Vector2<T>& row1, const Vector2<T>& row2);
Matrix2(const Matrix2& matrix);
template<typename T2>
Matrix2(const Matrix2<T2>& matrix);
~Matrix2();
static const Matrix2 identity;
bool isIdentity() const;
T determinant() const;
Matrix2 transpose() const;
static Matrix2 transpose(const Matrix2& matrix);
Matrix2 cofactor() const;
static Matrix2 cofactor(const Matrix2& matrix);
Matrix2 inverse() const;
static Matrix2 inverse(const Matrix2& matrix);
const T* ptr() const;
static Matrix2 createRotation(const T& angle);
static Matrix2 createScaling(const T& x, const T& y);
static Matrix2 createScaling(const Vector2<T>& scale);
std::string toString() const;
#pragma region Operators
// Comparison
bool operator ==(const Matrix2& right) const;
bool operator !=(const Matrix2& right) const;
// Assignment
Matrix2& operator =(const Matrix2& right);
Matrix2& operator +=(const Matrix2& right);
Matrix2& operator -=(const Matrix2& right);
Matrix2& operator *=(const T& right);
Matrix2& operator *=(const Matrix2& right);
Matrix2& operator /=(const T& right);
// Arithmetic
Matrix2 operator +(const Matrix2& right) const;
Matrix2 operator -(const Matrix2& right) const;
Matrix2 operator *(const Matrix2& right) const;
Matrix2 operator *(const T& right) const;
Vector2<T> operator *(const Vector2<T>& right) const;
Matrix2 operator /(const T& right) const;
// Member access
Vector2<T>& operator [](const unsigned int index);
const Vector2<T>& operator [](const unsigned int index) const;
#pragma endregion
static const unsigned int COLUMNS = 2;
static const unsigned int ROWS = 2;
private:
Vector2<T> r1, r2;
};
template<typename T>
Matrix2<T> operator *(const T& left, const Matrix2<T>& right);
template<typename T>
Vector2<T>& operator *=(Vector2<T>& left, const Matrix2<T>& right);
template<typename T>
std::ostream& operator<<(std::ostream& out, const Matrix2<T>& right);
typedef Matrix2<float> Mat2;
typedef Matrix2<double> Mat2d;
typedef Matrix2<int> Mat2i;
typedef Matrix2<unsigned int> Mat2u;
}
#include "inl/Matrix2.inl"
#endif | 28.323232 | 73 | 0.614836 | M4T1A5 |
4516b87899f4583240c9c086372d0fa0537d24c4 | 241 | cc | C++ | build/ARM/python/m5/internal/param_ThermalResistor.i_init.cc | Jakgn/gem5_test | 0ba7cc5213cf513cf205af7fc995cf679ebc1a3f | [
"BSD-3-Clause"
] | null | null | null | build/ARM/python/m5/internal/param_ThermalResistor.i_init.cc | Jakgn/gem5_test | 0ba7cc5213cf513cf205af7fc995cf679ebc1a3f | [
"BSD-3-Clause"
] | null | null | null | build/ARM/python/m5/internal/param_ThermalResistor.i_init.cc | Jakgn/gem5_test | 0ba7cc5213cf513cf205af7fc995cf679ebc1a3f | [
"BSD-3-Clause"
] | null | null | null | #include "sim/init.hh"
extern "C" {
void init_param_ThermalResistor();
}
EmbeddedSwig embed_swig_param_ThermalResistor(init_param_ThermalResistor, "m5.internal._param_ThermalResistor");
| 26.777778 | 120 | 0.643154 | Jakgn |
931f7a28603651a2203a309bde1bea50b5fcfdca | 2,002 | cpp | C++ | source/log/Layout.cpp | intive/StudyBox_CV | 5ea9b643177667ebdc9809f28db6705b308409f4 | [
"Apache-2.0"
] | 3 | 2016-03-07T09:40:49.000Z | 2018-05-29T16:13:10.000Z | source/log/Layout.cpp | intive/StudyBox_CV | 5ea9b643177667ebdc9809f28db6705b308409f4 | [
"Apache-2.0"
] | 38 | 2016-03-06T20:44:46.000Z | 2016-05-18T19:16:40.000Z | source/log/Layout.cpp | blstream/StudyBox_CV | 5ea9b643177667ebdc9809f28db6705b308409f4 | [
"Apache-2.0"
] | 10 | 2016-03-10T21:30:18.000Z | 2016-04-20T07:01:12.000Z | #define _CRT_SECURE_NO_WARNINGS
#include "Layout.h"
#include <iomanip>
#include <sstream>
LoggerInfo::LoggerInfo(std::size_t id, std::string name) : loggerId(id), loggerName(name)
{
}
std::size_t LoggerInfo::id() const
{
return loggerId;
}
const std::string& LoggerInfo::name() const
{
return loggerName;
}
ThreadInfo::ThreadInfo(std::thread::id id, std::size_t number) : threadId(id), threadNumber(number)
{
}
std::thread::id ThreadInfo::id() const
{
return threadId;
}
std::size_t ThreadInfo::number() const
{
return threadNumber;
}
EventLogLevel::EventLogLevel(LogConfig::LogLevel level) : level(level)
{
}
const std::string& EventLogLevel::name() const
{
return LogConfig::LogLevelStrings[LogConfig::GetIndexForLevel(level)];
}
LogConfig::LogLevel EventLogLevel::value() const
{
return level;
}
Time::Time(std::tm* time) : time(time)
{
}
int Time::hour() const
{
return time->tm_hour;
}
int Time::minute() const
{
return time->tm_min;
}
int Time::second() const
{
return time->tm_sec;
}
int Time::millisecond() const
{
return 0; // TODO
}
Date::Date(std::time_t timeTicks) : tmtime(std::localtime(&timeTicks)), time(tmtime)
{
}
int Date::year() const
{
return 1900 + tmtime->tm_year;
}
int Date::month() const
{
return tmtime->tm_mon;
}
int Date::day() const
{
return tmtime->tm_wday;
}
std::string Date::toString(const std::string& format, const std::locale& locale) const
{
std::ostringstream ss;
ss.imbue(locale);
ss << std::put_time(tmtime, format.c_str());
return ss.str();
}
std::string Date::toIso8601() const
{
return toString("%FT%TZ");
}
Timestamp::Timestamp(std::time_t timeTicks) : timeTicks(timeTicks), date(timeTicks)
{
}
std::time_t Timestamp::ticks() const
{
return timeTicks;
}
Message::Message(std::size_t id, std::string message) : messageId(id), message(message)
{
}
std::size_t Message::id() const
{
return messageId;
}
std::string Message::what() const
{
return message;
}
| 16.683333 | 99 | 0.681818 | intive |
9326fea7cfefb0a2788b7d56c1eb06e083e1505c | 499 | cpp | C++ | src/TEMA VACANTA 2/#11/main.cpp | andrew-miroiu/Cpp-projects | d0917a7f78aef929c25dc9b019e910951c2050ac | [
"MIT"
] | 2 | 2021-11-27T18:29:32.000Z | 2021-11-28T14:35:47.000Z | src/TEMA VACANTA 2/#11/main.cpp | andrew-miroiu/Cpp-projects | d0917a7f78aef929c25dc9b019e910951c2050ac | [
"MIT"
] | null | null | null | src/TEMA VACANTA 2/#11/main.cpp | andrew-miroiu/Cpp-projects | d0917a7f78aef929c25dc9b019e910951c2050ac | [
"MIT"
] | null | null | null | #include <iostream>
/*11) Se dă un şir cu n numere naturale. Să se afişeze suma primilor n termeni din şir, apoi suma
primilor n-1 termeni din şir, şi aşa mai departe.*/
using namespace std;
int main()
{
int i, n, v[100], s=0;
cout<<"Scrie nr de elem: ";
cin>>n;
cout<<"Scrie elem vect.: ";
for(i=0; i<n; i++)
{
cin>>v[i];
s=s+v[i];
}
cout<<s<<endl;
for(i=n-1; i>0; i--)
{
cout<<s-v[i]<<endl;
s=s-v[i];
}
return 0;
}
| 19.192308 | 97 | 0.513026 | andrew-miroiu |
9333c21b1adced91325809aac79ac9d81c887635 | 123 | cpp | C++ | examples/op_new_arr_reinterpret_cast.cpp | typegrind/clang-typegrind | 6aa58997883d7973e14644563dc59ff9c34e8ffb | [
"MIT"
] | 2 | 2016-04-12T20:41:15.000Z | 2019-08-26T12:51:51.000Z | examples/op_new_arr_reinterpret_cast.cpp | typegrind/clang-typegrind | 6aa58997883d7973e14644563dc59ff9c34e8ffb | [
"MIT"
] | null | null | null | examples/op_new_arr_reinterpret_cast.cpp | typegrind/clang-typegrind | 6aa58997883d7973e14644563dc59ff9c34e8ffb | [
"MIT"
] | null | null | null | int main(void) {
int* pT = reinterpret_cast<int*>(::operator new[](100));
::operator delete[](pT);
return 0;
}
| 20.5 | 60 | 0.585366 | typegrind |
9335e297ab7455c1f85517ef1b2d632f562ed884 | 3,367 | cpp | C++ | src/wcl/geometry/LineSegment.cpp | WearableComputerLab/LibWCL | e1687a8fd2f96bfec3a84221044cfb8b7126a79c | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | src/wcl/geometry/LineSegment.cpp | WearableComputerLab/LibWCL | e1687a8fd2f96bfec3a84221044cfb8b7126a79c | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | src/wcl/geometry/LineSegment.cpp | WearableComputerLab/LibWCL | e1687a8fd2f96bfec3a84221044cfb8b7126a79c | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | /*-
* Copyright (c) 2008 Michael Marner <michael@20papercups.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 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 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 AUTHOR 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 <sstream>
#include <iostream>
#include <cstdlib>
#include <config.h>
#include <wcl/geometry/LineSegment.h>
#include <wcl/geometry/Intersection.h>
namespace wcl
{
LineSegment::LineSegment(const wcl::Vector& start, const wcl::Vector& end) :
Line(start, end - start), startPos(start), endPos(end)
{
}
wcl::Intersection LineSegment::intersect(const LineSegment& s)
{
wcl::Intersection ip = Line::intersect((wcl::Line)s);
if ( ip.intersects == wcl::Intersection::YES ) {
// Check whether or not the intersection point is on the segment.
if (!(this->isOnSegment(ip.point) && s.isOnSegment(ip.point))) {
ip.intersects = wcl::Intersection::NO;
}
}
return ip;
}
bool LineSegment::isOnSegment(const wcl::Vector& point) const {
wcl::Vector ba = endPos - startPos;
wcl::Vector ca = point - startPos;
wcl::Vector cross = ba.crossProduct(ca);
if ( abs(cross.length()) < TOL ) {
return false;
}
double dot = ba.dot(ca);
if ( dot < 0 ) return false;
if ( dot > ( endPos.distance(startPos) * endPos.distance(startPos) ) ) return false;
return true;
}
std::string LineSegment::toString()
{
std::stringstream ss;
ss << "LineSegment. Start: (" << startPos[0] << ", " << startPos[1] << ", " << startPos[2];
ss << ") End: (" << endPos[0] << ", " << endPos[1] << ", " << endPos[2] << ")" << std::endl;
return ss.str();
}
// Taken from Mathematics for Games and Interactive Applications
wcl::Vector LineSegment::closestPoint(const wcl::Vector& point) const
{
Vector w = point - startPos;
wcl::Vector direction = (endPos - startPos);
double proj = w.dot(direction);
if (proj <=0)
{
return startPos;
}
else
{
double vsq = direction.dot(direction);
if (proj >= vsq)
return startPos + direction;
else
return startPos + (proj/vsq)*direction;
}
}
}
| 32.68932 | 94 | 0.665281 | WearableComputerLab |
933e19a7867d100239d2d38a8ee1850f1c9e0db5 | 8,128 | cpp | C++ | src/ui-yml/StyleParser.cpp | raptoravis/two | 4366fcf8b3072d0233eb8e1e91ac1105194f60f5 | [
"Zlib"
] | null | null | null | src/ui-yml/StyleParser.cpp | raptoravis/two | 4366fcf8b3072d0233eb8e1e91ac1105194f60f5 | [
"Zlib"
] | null | null | null | src/ui-yml/StyleParser.cpp | raptoravis/two | 4366fcf8b3072d0233eb8e1e91ac1105194f60f5 | [
"Zlib"
] | null | null | null | // Copyright (c) 2019 Hugo Amiard hugo.amiard@laposte.net
// This software is provided 'as-is' under the zlib License, see the LICENSE.txt file.
// This notice and the license may not be removed or altered from any source distribution.
#include <infra/Cpp20.h>
#ifdef TWO_MODULES
module two.ui;
#else
#include <tree/Node.inl.h>
#include <refl/Class.h>
#include <srlz/Serial.h>
#include <infra/String.h>
#include <math/VecJson.h>
#include <ui/Types.h>
#include <ui/Style/StyleParser.h>
#include <ui/Style/Style.h>
#include <ui/Style/Skin.h>
#include <ui/Style/Styler.h>
#include <ui/Style/Styles.h>
#include <ui/Structs/RootSheet.h>
#include <ui/UiWindow.h>
#include <meta/ui/Convert.h>
#endif
#include <json11.hpp>
namespace two
{
export_ class TWO_UI_EXPORT Options
{
public:
vector<Var> m_fields;
void set(size_t index, const Var& value);
void merge(const Options& other);
void apply(Ref object);
};
using StyleMap = map<string, Options>;
export_ class refl_ TWO_UI_EXPORT Styler
{
public:
Styler(UiWindow& ui_window);
UiWindow& m_ui_window;
StyleMap m_layouts;
StyleMap m_skins;
void init();
void clear();
void setup();
void load(Style& style, StyleMap& layout_defs, StyleMap& skin_defs);
void define(Style& style, StyleMap& layout_defs, StyleMap& skin_defs);
static map<string, Style*> s_styles;
};
void load_style(Styler& styler, const string& name, const json& json_style);
void decline_images(Styler& styler, const string& style, Options& skin_def, const string& state)
{
for(size_t i = 0; i < skin_def.m_fields.size(); ++i)
if(!skin_def.m_fields[i].none() && (type(skin_def.m_fields[i]).is<Image>()
|| type(skin_def.m_fields[i]).is<ImageSkin>()))
{
Member& member = cls<InkStyle>().m_members[i];
Var value = skin_def.m_fields[member.m_index];
Options& declined_skin_def = styler.m_skins[style + ":" + state];
if(type(value).is<Image>())
{
string image_name = string(val<Image>(value).d_name) + "_" + replace_all(state, "|", "_");
Image& declined_image = *styler.m_ui_window.find_image(image_name.c_str());
declined_skin_def.set(member.m_index, Ref(&declined_image));
}
else if(type(value).is<ImageSkin>())
{
string image_name = string(val<ImageSkin>(value).d_image->d_name) + "_" + replace_all(state, "|", "_");
Image& declined_image = *styler.m_ui_window.find_image(image_name.c_str());
declined_skin_def.set(member.m_index, var(ImageSkin(declined_image, val<ImageSkin>(value))));
}
}
}
void decline(Styler& styler, const string& style, Options& skin_def, const json& json_states)
{
for(const json& state : json_states.array_items())
decline_images(styler, style, skin_def, state.string_value());
}
FromJson style_unpacker(UiWindow& ui_window)
{
FromJson unpacker;
unpacker.function<Image>([&](Ref, Ref& result, const json& json)
{
result = json == "null" ? Ref((Image*) nullptr)
: Ref(ui_window.find_image(json.string_value().c_str()));
});
return unpacker;
}
void load_member(Styler& styler, Options& definition, Member& member, const json& json_value)
{
static FromJson unpacker = style_unpacker(styler.m_ui_window);
Var value = member.m_default_value;
unpack(unpacker, value, json_value);
definition.set(member.m_index, value);
}
void load_style_attr(Styler& styler, const string& style, Options& layout_def, Options& skin_def, string key, const json& json_value)
{
string skin_key = replace_all(key, "skin_", "");
if(key == "selector" || key == "reset_skin")
;
else if(key == "copy_skin")
skin_def.merge(styler.m_skins[json_value.string_value()]);
else if(key == "decline")
decline(styler, style, skin_def, json_value);
else if(cls<Layout>().has_member(key.c_str()))
load_member(styler, layout_def, cls<Layout>().member(key.c_str()), json_value);
else if(cls<InkStyle>().has_member(skin_key.c_str()))
load_member(styler, skin_def, cls<InkStyle>().member(skin_key.c_str()), json_value);
else if(key.find("comment") != string::npos)
;
else // if(vector_has(meta<WidgetState>().m_enumIds, to_upper(key)))
{
vector<string> states = split_string(replace_all(key, " ", ""), ",");
for(const string& state : states)
load_style(styler, style + ":" + state, json_value);
}
}
void load_style(Styler& styler, const string& selector, const json& json_style)
{
vector<string> names = split_string(replace_all(selector, " ", ""), ",");
for(const string& name : names)
{
Options& layout_def = styler.m_layouts[name];
Options& skin_def = styler.m_skins[name];
for(auto& key_value : json_style.object_items())
load_style_attr(styler, name, layout_def, skin_def, key_value.first, key_value.second);
}
}
void replace_colours(const map<string, Colour>& colours, json& json_value)
{
visit_json(json_value, [&](json& json_value)
{
if(json_value.is_string() && colours.find(json_value.string_value()) != colours.end())
to_json(colours.at(json_value.string_value()), json_value);
});
}
void load_colours(map<string, Colour>& colours, const json& json_colours)
{
for(auto& key_value : json_colours.object_items())
from_json(key_value.second, colours[key_value.first]);
}
void load_style_sheet(Styler& styler, cstring path)
{
json style_sheet;
parse_json_file(path, style_sheet);
const json& includes = style_sheet["includes"];
for(size_t i = 0; i < includes.array_items().size(); ++i)
{
load_style_sheet(styler, (string(styler.m_ui_window.m_resource_path) + "interface/styles/" + includes[i].string_value()).c_str());
}
map<string, Colour> colours;
load_colours(colours, style_sheet["colours"]);
replace_colours(colours, const_cast<json&>(style_sheet["styles"]));
const json& styles = style_sheet["styles"];
for(size_t i = 0; i < styles.array_items().size(); ++i)
load_style(styler, styles[i]["selector"].string_value(), styles[i]);
}
void set_style_sheet(UiWindow& ui_window, cstring path)
{
Styler styler = { ui_window };
styler.clear();
load_style_sheet(styler, path);
styler.setup();
}
void set_default_style_sheet(UiWindow& ui_window)
{
Styler styler = { ui_window };
styler.clear();
styler.setup();
}
void Options::set(size_t index, const Var& value)
{
if(index >= m_fields.size())
m_fields.resize(index + 1);
m_fields[index] = value;
}
void Options::merge(const Options& other)
{
for(size_t i = 0; i < other.m_fields.size(); ++i)
if(!other.m_fields[i].none())
set(i, other.m_fields[i]);
}
void Options::apply(Ref object)
{
for(size_t i = 0; i < m_fields.size(); ++i)
if(!m_fields[i].none())
cls(object).m_members[i].set(object, m_fields[i]);
}
Styler::Styler()
{
// @kludge until reflection properly supports Enum default parameters
cls<ImageSkin>().m_constructors[0].m_arguments.back() = var(DIM_NONE);
}
void Styler::clear()
{
m_layouts = {};
m_skins = {};
this->init();
styles().setup(m_ui_window);
}
void Styler::setup()
{
for(auto& kv : s_styles)
this->load(*kv.second, m_layouts, m_skins);
visit_node<Widget>(*m_ui_window.m_root_sheet, [](Widget& widget, bool&) {
widget.m_frame.update_style(true);
});
}
void Styler::load(Style& style, StyleMap& layout_defs, StyleMap& skin_defs)
{
if(style.m_defined) return;
if(style.m_base)
this->load(*style.m_base, layout_defs, skin_defs);
this->define(style, layout_defs, skin_defs);
style.prepare();
style.m_defined = true;
}
void Styler::define(Style& style, StyleMap& layout_defs, StyleMap& skin_defs)
{
//if(style.m_base)
// this->load(*style.m_base, layout_defs, skin_defs);
layout_defs[style.name()].apply(Ref(&style.layout()));
skin_defs[style.name()].apply(Ref(&style.skin()));
for(auto& kv : skin_defs)
if(kv.first.find(string(style.name()) + ":") == 0)
{
WidgetState states = flags_from_string<WidgetState>(split_string(kv.first, ":")[1]);
InkStyle& skin = style.decline_skin(states);
skin_defs[style.name()].apply(Ref(&skin));
skin_defs[kv.first].apply(Ref(&skin));
}
}
}
| 28.519298 | 134 | 0.687008 | raptoravis |
93420c8cdc83e0718039a9b1fe1d15a10bced00f | 1,484 | hpp | C++ | include/math/constants.hpp | tomreddell/Hamilton | eec6e423f829a559237583803d11fbe06489a9b9 | [
"MIT"
] | 1 | 2020-09-19T14:48:32.000Z | 2020-09-19T14:48:32.000Z | include/math/constants.hpp | tomreddell/Hamilton | eec6e423f829a559237583803d11fbe06489a9b9 | [
"MIT"
] | null | null | null | include/math/constants.hpp | tomreddell/Hamilton | eec6e423f829a559237583803d11fbe06489a9b9 | [
"MIT"
] | 1 | 2021-01-01T02:23:55.000Z | 2021-01-01T02:23:55.000Z | #pragma once
#include "math/core_math.hpp"
/**
* @file constants.hpp
*/
/// Speed of light in vacuum (m/s)
constexpr double SPEED_LIGHT = 299792458.0;
namespace Earth
{
/// Earth mass (kg)
constexpr double MASS = 5.9722E24;
/// Earth gravitational constant (m3/s2)
constexpr double GRAVITATIONAL_CONSTANT = 3.986004418E14;
/// Length of earth stellar day (s) as defined by the International
/// Celestial Reference Frame
constexpr double IERS_DAY_SECONDS = 86164.098903691;
/// Earth equatorial rotational rate (rad/s)
constexpr double ROTATIONAL_RATE = 7.2921150E-5;
/// Earth standard gravity (m/s2)
constexpr double EQUATORIAL_GRAVITY = 9.7803253359;
namespace WGS84
{
/// Earth WGS84 Equatorial Radius (m)
constexpr double SEMI_MAJOR_AXIS = 6378137.0;
/// Earth WGS84 Polar Radius (m)
constexpr double SEMI_MINOR_AXIS = 6356752.314245;
/// Earth flattening (-)
constexpr double FLATTENING = 1.0 / 298.2572235630;
/// Earth eccentricity (-)
constexpr double ECCENTRICITY = 0.08181919084261345;
/// Earth Eccentricity Squared (-)
constexpr double ECCSQ = 1.0 - (SEMI_MINOR_AXIS / SEMI_MAJOR_AXIS)
* (SEMI_MINOR_AXIS / SEMI_MAJOR_AXIS);
}
} | 30.916667 | 76 | 0.582884 | tomreddell |
9343a5d6ea3bdc05162932d0111c8febf06d086d | 4,414 | cc | C++ | src/kudu/tserver/tablet_server_options.cc | luqun/kuduraft | a0746471a6a85e9d8ccb947a866eaf1a60159f8f | [
"Apache-2.0"
] | null | null | null | src/kudu/tserver/tablet_server_options.cc | luqun/kuduraft | a0746471a6a85e9d8ccb947a866eaf1a60159f8f | [
"Apache-2.0"
] | null | null | null | src/kudu/tserver/tablet_server_options.cc | luqun/kuduraft | a0746471a6a85e9d8ccb947a866eaf1a60159f8f | [
"Apache-2.0"
] | null | null | null | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 "kudu/tserver/tablet_server_options.h"
#include <ostream>
#include <string>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include "kudu/consensus/raft_consensus.h"
#include "kudu/gutil/macros.h"
#ifdef FB_DO_NOT_REMOVE
#include "kudu/master/master.h"
#endif
#include "kudu/server/rpc_server.h"
#include "kudu/tserver/tablet_server.h"
#include "kudu/util/flag_tags.h"
#include "kudu/util/status.h"
#include <boost/algorithm/string.hpp>
// TODO - iRitwik ( please refine these mechanisms to a standard way of
// passing all the properties of an instance )
DEFINE_string(tserver_addresses, "",
"Comma-separated list of the RPC addresses belonging to all "
"instances in this cluster. "
"NOTE: if not specified, configures a non-replicated Master.");
TAG_FLAG(tserver_addresses, stable);
DEFINE_string(tserver_regions, "",
"Comma-separated list of regions which is parallel to tserver_addresses.");
TAG_FLAG(tserver_regions, stable);
DEFINE_string(tserver_bbd, "",
"Comma-separated list of bool strings to specify Backed by "
"Database(non-witness). Runs parallel to tserver_addresses.");
TAG_FLAG(tserver_bbd, stable);
namespace kudu {
namespace tserver {
TabletServerOptions::TabletServerOptions() {
rpc_opts.default_port = TabletServer::kDefaultPort;
if (!FLAGS_tserver_addresses.empty()) {
Status s = HostPort::ParseStrings(FLAGS_tserver_addresses, TabletServer::kDefaultPort,
&tserver_addresses);
if (!s.ok()) {
LOG(FATAL) << "Couldn't parse the tserver_addresses flag('" << FLAGS_tserver_addresses << "'): "
<< s.ToString();
}
#ifdef FB_DO_NOT_REMOVE
// to simplify in FB, we allow rings with single instances.
if (tserver_addresses.size() < 2) {
LOG(FATAL) << "At least 2 tservers are required for a distributed config, but "
"tserver_addresses flag ('" << FLAGS_tserver_addresses << "') only specifies "
<< tserver_addresses.size() << " tservers.";
}
#endif
// TODO(wdberkeley): Un-actionable warning. Link to docs, once they exist.
if (tserver_addresses.size() <= 2) {
LOG(WARNING) << "Only 2 tservers are specified by tserver_addresses_flag ('" <<
FLAGS_tserver_addresses << "'), but minimum of 3 are required to tolerate failures"
" of any one tserver. It is recommended to use at least 3 tservers.";
}
}
if (!FLAGS_tserver_regions.empty()) {
boost::split(tserver_regions, FLAGS_tserver_regions, boost::is_any_of(","));
if (tserver_regions.size() != tserver_addresses.size()) {
LOG(FATAL) << "The number of tserver regions has to be same as tservers: "
<< FLAGS_tserver_regions << " " << FLAGS_tserver_addresses;
}
}
if (!FLAGS_tserver_bbd.empty()) {
std::vector<std::string> bbds;
boost::split(bbds, FLAGS_tserver_bbd, boost::is_any_of(","));
if (bbds.size() != tserver_addresses.size()) {
LOG(FATAL) << "The number of tserver bbd tags has to be same as tservers: "
<< FLAGS_tserver_bbd << " " << FLAGS_tserver_addresses;
}
for (auto tsbbd: bbds) {
if (tsbbd == "true") {
tserver_bbd.push_back(true);
} else if (tsbbd == "false") {
tserver_bbd.push_back(false);
} else {
LOG(FATAL) << "tserver bbd tags has to be bool true|false : "
<< FLAGS_tserver_bbd;
}
}
}
}
bool TabletServerOptions::IsDistributed() const {
return !tserver_addresses.empty();
}
} // namespace tserver
} // namespace kudu
| 37.40678 | 102 | 0.678749 | luqun |
9348d26c132c0f094f2739746278bbe6311ecb15 | 523 | cpp | C++ | C++/camera.cpp | Galaco/BTLRN_XTRM | c55405d5a36a44a8b1e3def555de9ec10027625b | [
"Unlicense"
] | null | null | null | C++/camera.cpp | Galaco/BTLRN_XTRM | c55405d5a36a44a8b1e3def555de9ec10027625b | [
"Unlicense"
] | null | null | null | C++/camera.cpp | Galaco/BTLRN_XTRM | c55405d5a36a44a8b1e3def555de9ec10027625b | [
"Unlicense"
] | null | null | null | #include "camera.h"
float zCamPos = -250.0;
Camera::Camera(){
posX = 0;
posY = 0;
}
void Camera::zoom( int d ){
zCamPos += d;
if ( ( zCamPos > CAMERAMINZOOM ) || ( zCamPos < CAMERAMAXZOOM ) ) // Check bounds for min and max camera distance
{
zCamPos -= d;
}
}
void Camera::update( float x , float y ){
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glTranslatef( - x , - y - YOFFSET , zCamPos ); // Translate the camera in the X and Y direction.
}
Camera::~Camera(){
} | 19.37037 | 117 | 0.58891 | Galaco |
934924abe6cb1e79d292b4d63694dadc739b48f3 | 1,106 | cpp | C++ | src/engine/graphics/vulkan/validationlayers.cpp | dmfedorin/ubiquitility | f3a1062d2489ffd48889bff5fc8062c05706a946 | [
"MIT"
] | null | null | null | src/engine/graphics/vulkan/validationlayers.cpp | dmfedorin/ubiquitility | f3a1062d2489ffd48889bff5fc8062c05706a946 | [
"MIT"
] | null | null | null | src/engine/graphics/vulkan/validationlayers.cpp | dmfedorin/ubiquitility | f3a1062d2489ffd48889bff5fc8062c05706a946 | [
"MIT"
] | null | null | null | #include "validationlayers.hpp"
ValidationLayers::ValidationLayers(bool enabled)
:
enabled(enabled)
{
}
auto ValidationLayers::is_enabled(void) const noexcept -> bool
{
return enabled;
}
auto ValidationLayers::check_layer_support(void) const -> void
{
uint32_t avl_layer_cnt;
vkEnumerateInstanceLayerProperties(&avl_layer_cnt, nullptr);
std::vector<VkLayerProperties> avl_layers{ avl_layer_cnt };
vkEnumerateInstanceLayerProperties(&avl_layer_cnt, avl_layers.data());
uint32_t req_layer_cnt = required_layers.size();
for (const auto &req_layer : required_layers) {
for (const auto &avl_layer : avl_layers) {
if (strcmp(req_layer, avl_layer.layerName) == 0)
req_layer_cnt--;
}
}
if (req_layer_cnt > 0) {
throw std::runtime_error{ "validation layers not supported" };
}
}
auto ValidationLayers::get_required_layers(
void) const noexcept -> const std::vector<const char *> &
{
return required_layers;
} | 28.358974 | 78 | 0.637432 | dmfedorin |
934edb92dbeebeb47901d3440274a97adc4fb6c8 | 462 | cpp | C++ | solutions/beecrowd/1253/1253.cpp | deniscostadsc/playground | 11fa8e2b708571940451f005e1f55af0b6e5764a | [
"MIT"
] | 18 | 2015-01-22T04:08:51.000Z | 2022-01-08T22:36:47.000Z | solutions/beecrowd/1253/1253.cpp | deniscostadsc/playground | 11fa8e2b708571940451f005e1f55af0b6e5764a | [
"MIT"
] | 4 | 2016-04-25T12:32:46.000Z | 2021-06-15T18:01:30.000Z | solutions/beecrowd/1253/1253.cpp | deniscostadsc/playground | 11fa8e2b708571940451f005e1f55af0b6e5764a | [
"MIT"
] | 25 | 2015-03-02T06:21:51.000Z | 2021-09-12T20:49:21.000Z | #include <cstdint>
#include <iostream>
#include <string>
int main() {
uint16_t i;
int16_t n, c;
std::string a = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::string s;
std::cin >> n;
while (n--) {
std::cin >> s;
std::cin >> c;
for (i = 0; i <= s.length() - 1; i++) {
s.at(i) = a.at(a.find_last_of(s.at(i)) - c);
}
std::cout << s << std::endl;
}
return 0;
}
| 17.769231 | 75 | 0.493506 | deniscostadsc |
9352b47a643cade9cfedd9552c153be445a4b29f | 11,258 | hpp | C++ | examples/segway_dynamics.hpp | yamaha-bps/cbr_control | c2faf79673d46c950dd7590f1072fc7decafad06 | [
"MIT"
] | null | null | null | examples/segway_dynamics.hpp | yamaha-bps/cbr_control | c2faf79673d46c950dd7590f1072fc7decafad06 | [
"MIT"
] | null | null | null | examples/segway_dynamics.hpp | yamaha-bps/cbr_control | c2faf79673d46c950dd7590f1072fc7decafad06 | [
"MIT"
] | null | null | null | // Copyright Yamaha 2021
// MIT License
// https://github.com/yamaha-bps/cbr_control/blob/master/LICENSE
#ifndef SEGWAY_DYNAMICS_HPP_
#define SEGWAY_DYNAMICS_HPP_
#include <Eigen/Dense>
// template here over some type
template<typename T1, typename T2>
auto segway_dynamics(const Eigen::MatrixBase<T1> & x, const Eigen::MatrixBase<T2> & u)
{
// Define nx, nu
constexpr auto nx = T1::RowsAtCompileTime;
constexpr auto nu = T2::RowsAtCompileTime;
// Initialize Parameters
constexpr double mb = 44.798;
constexpr double mw = 2.485;
constexpr double Jw = 0.055936595310797;
constexpr double a2 = -0.02322718759275;
constexpr double c2 = 0.166845864363019;
constexpr double A2 = 3.604960049044268;
constexpr double B2 = 3.836289730154863;
constexpr double C2 = 1.069672194414735;
constexpr double K = 1.261650363363571;
constexpr double r = 0.195;
constexpr double L = 0.5;
constexpr double gGravity = 9.81;
constexpr double FricCoeffViscous = 0.;
constexpr double velEps = 1.0e-3;
constexpr double FricCoeff = 1.225479467549329;
using T = typename decltype(x * u.transpose())::EvalReturnType::Scalar;
// xDot = f(x) + g(x)*u
Eigen::Matrix<T, nx, 1> xDot;
Eigen::Matrix<typename T1::Scalar, nx, 1> f;
Eigen::Matrix<typename T1::Scalar, nx, nu> g;
Eigen::Map<Eigen::Matrix<typename T1::Scalar, nx, 1>> g1(g.data());
Eigen::Map<Eigen::Matrix<typename T1::Scalar, nx, 1>> g2(g.data() + nx);
// Extract States
const auto & theta = x[2];
const auto & v = x[3];
const auto & thetaDot = x[4];
const auto & psi = x[5];
const auto & psiDot = x[6];
const auto Fric = FricCoeff * tanh((v - psiDot * r) / velEps) + FricCoeffViscous *
(v - psiDot * r);
f[0] = v * cos(theta);
f[1] = v * sin(theta);
f[2] = thetaDot;
f[3] = (1 / 2) * r *
(1 /
(4 * B2 * Jw + 4 *
pow(
a2,
2) * Jw * mb + 4 *
pow(
c2,
2) * Jw * mb + 2 * B2 * mb *
pow(
r,
2) +
pow(
a2,
2) *
pow(
mb,
2) *
pow(
r,
2) +
pow(
c2,
2) * pow(mb, 2) * pow(r, 2) + 4 * B2 * mw * pow(r, 2) + 4 * pow(a2, 2) * mb * mw * pow(r, 2) +
4 *
pow(
c2,
2) * mb * mw *
pow(
r,
2) +
(pow(
a2,
2) + (-1) *
pow(
c2,
2)) *
pow(
mb,
2) *
pow(
r,
2) * cos(2 * psi) + 2 * a2 * c2 *
pow(mb, 2) * pow(r, 2) * sin(2 * psi))) * ((-8) * B2 * Fric + (-8) * pow(a2, 2) * Fric * mb +
(-8) *
pow(
c2,
2) * Fric * mb + mb * r *
((-8) * c2 * Fric + a2 * ((-1) * A2 + C2) *
pow(thetaDot, 2) + 4 * a2 * B2 * (pow(psiDot, 2) + pow(thetaDot, 2)) +
pow(
a2,
3) * mb *
(4 *
pow(
psiDot,
2) + 3 *
pow(
thetaDot,
2)) + a2 *
pow(
c2,
2) * mb *
(4 *
pow(
psiDot,
2) + 3 *
pow(
thetaDot,
2))) * cos(psi) + (-4) * a2 * c2 * gGravity *
pow(mb, 2) * r * cos(2 * psi) + a2 * A2 * mb * r * pow(thetaDot, 2) * cos(3 * psi) +
(-1) * a2 * C2 * mb * r *
pow(
thetaDot,
2) * cos(3 * psi) +
pow(
a2,
3) *
pow(
mb,
2) * r *
pow(
thetaDot,
2) * cos(3 * psi) + (-3) * a2 *
pow(c2, 2) * pow(mb, 2) * r * pow(thetaDot, 2) * cos(3 * psi) + 8 * a2 * Fric * mb * r * sin(
psi) + 4 * B2 * c2 * mb * pow(psiDot, 2) * r * sin(psi) +
4 *
pow(
a2,
2) * c2 *
pow(
mb,
2) *
pow(
psiDot,
2) * r * sin(psi) + 4 *
pow(
c2,
3) *
pow(
mb,
2) *
pow(
psiDot,
2) * r * sin(psi) + A2 * c2 * mb * r *
pow(
thetaDot,
2) * sin(psi) + 4 * B2 * c2 * mb * r *
pow(thetaDot, 2) * sin(psi) + (-1) * c2 * C2 * mb * r * pow(thetaDot, 2) * sin(psi) +
3 *
pow(
a2,
2) * c2 *
pow(mb, 2) * r * pow(thetaDot, 2) * sin(psi) + 3 * pow(c2, 3) * pow(mb, 2) * r * pow(
thetaDot,
2) *
sin(psi) + 2 *
pow(a2, 2) * gGravity * pow(mb, 2) * r * sin(2 * psi) + (-2) * pow(c2, 2) * gGravity * pow(
mb,
2) *
r * sin(2 * psi) + A2 * c2 * mb * r * pow(thetaDot, 2) * sin(3 * psi) +
(-1) * c2 * C2 * mb * r *
pow(
thetaDot,
2) * sin(3 * psi) + 3 *
pow(
a2,
2) * c2 *
pow(
mb,
2) * r *
pow(
thetaDot,
2) * sin(3 * psi) + (-1) * pow(c2, 3) * pow(mb, 2) * r * pow(thetaDot, 2) * sin(3 * psi));
f[4] =
pow(
r,
2) * thetaDot *
((-2) * a2 * mb * v * cos(psi) + (-4) * a2 * c2 * mb * psiDot * cos(2 * psi) + (-2) *
(c2 * mb * v +
(A2 + (-1) * C2 + (-2) *
pow(
a2,
2) * mb + 2 *
pow(
c2,
2) * mb) * psiDot * cos(psi)) * sin(psi)) *
(1 / (Jw * pow(L, 2) + pow(L, 2) * mw * pow(r, 2) +
2 *
(C2 +
pow(
a2,
2) * mb) *
pow(
r,
2) *
pow(
cos(psi),
2) + 2 *
(A2 +
pow(c2, 2) * mb) * pow(r, 2) * pow(sin(psi), 2) + 2 * a2 * c2 * mb * pow(r, 2) * sin(2 * psi)));
f[5] = psiDot;
f[6] =
(1 /
(4 * B2 * Jw + 4 *
pow(
a2,
2) * Jw * mb + 4 *
pow(
c2,
2) * Jw * mb + 2 * B2 * mb *
pow(
r,
2) +
pow(
a2,
2) *
pow(
mb,
2) *
pow(
r,
2) +
pow(
c2,
2) *
pow(
mb,
2) *
pow(
r,
2) + 4 * B2 * mw *
pow(
r,
2) + 4 *
pow(
a2,
2) * mb * mw *
pow(
r,
2) + 4 *
pow(
c2,
2) * mb * mw *
pow(r, 2) + (pow(a2, 2) + (-1) * pow(c2, 2)) * pow(mb, 2) * pow(r, 2) * cos(2 * psi) +
2 * a2 * c2 *
pow(
mb,
2) *
pow(
r,
2) * sin(2 * psi))) *
(8 * Fric * Jw + 4 * Fric * mb *
pow(
r,
2) + 8 * Fric * mw *
pow(
r,
2) + 2 * mb *
(2 * c2 * Fric * r + a2 * gGravity *
(2 * Jw + (mb + 2 * mw) *
pow(r, 2))) * cos(psi) + (-2) * a2 * c2 * mb * (mb * pow(psiDot, 2) * pow(r, 2) +
(-2) *
(Jw + mw * pow(r, 2)) * pow(thetaDot, 2)) * cos(2 * psi) + 4 * c2 * gGravity * Jw * mb * sin(
psi) + (-4) * a2 * Fric * mb * r * sin(psi) + 2 * c2 * gGravity *
pow(mb, 2) * pow(r, 2) * sin(psi) + 4 * c2 * gGravity * mb * mw * pow(r, 2) * sin(psi) +
pow(
a2,
2) *
pow(
mb,
2) *
pow(
psiDot,
2) *
pow(
r,
2) * sin(2 * psi) + (-1) *
pow(
c2,
2) *
pow(
mb,
2) * pow(psiDot, 2) * pow(r, 2) * sin(2 * psi) + (-2) * A2 * Jw * pow(thetaDot, 2) * sin(
2 * psi) + 2 * C2 * Jw *
pow(
thetaDot,
2) * sin(2 * psi) + (-2) * pow(a2, 2) * Jw * mb * pow(thetaDot, 2) * sin(2 * psi) +
2 *
pow(
c2,
2) * Jw * mb *
pow(
thetaDot,
2) * sin(2 * psi) + (-1) * A2 * mb *
pow(
r,
2) *
pow(
thetaDot,
2) * sin(2 * psi) + C2 * mb *
pow(
r,
2) *
pow(
thetaDot,
2) * sin(2 * psi) + (-2) * A2 * mw *
pow(
r,
2) *
pow(thetaDot, 2) * sin(2 * psi) + 2 * C2 * mw * pow(r, 2) * pow(thetaDot, 2) * sin(2 * psi) +
(-2) *
pow(
a2,
2) * mb * mw * pow(r, 2) * pow(thetaDot, 2) * sin(2 * psi) + 2 * pow(c2, 2) * mb * mw * pow(
r,
2) *
pow(thetaDot, 2) * sin(2 * psi));
g1[0] = 0;
g2[0] = 0;
g1[1] = 0;
g2[1] = 0;
g1[2] = 0;
g2[2] = 0;
g1[3] = K * r *
(B2 +
pow(
a2,
2) * mb +
pow(
c2,
2) * mb + c2 * mb * r * cos(psi) + (-1) * a2 * mb * r * sin(psi)) *
(1 / (2 * B2 * Jw + 2 * pow(a2, 2) * Jw * mb + 2 * pow(c2, 2) * Jw * mb + B2 * mb * pow(r, 2) +
pow(
a2,
2) *
pow(
mb,
2) *
pow(
r,
2) +
pow(
c2,
2) *
pow(
mb,
2) *
pow(
r,
2) + 2 * B2 * mw *
pow(r, 2) + 2 * pow(a2, 2) * mb * mw * pow(r, 2) + 2 * pow(c2, 2) * mb * mw * pow(r, 2) +
(-1) *
pow(
c2,
2) *
pow(
mb,
2) *
pow(
r,
2) *
pow(
cos(psi),
2) + (-1) *
pow(
a2,
2) *
pow(mb, 2) * pow(r, 2) * pow(sin(psi), 2) + a2 * c2 * pow(mb, 2) * pow(r, 2) * sin(2 * psi)));
g2[3] = K * r *
(B2 +
pow(
a2,
2) * mb +
pow(
c2,
2) * mb + c2 * mb * r * cos(psi) + (-1) * a2 * mb * r * sin(psi)) *
(1 / (2 * B2 * Jw + 2 * pow(a2, 2) * Jw * mb + 2 * pow(c2, 2) * Jw * mb + B2 * mb * pow(r, 2) +
pow(
a2,
2) *
pow(
mb,
2) *
pow(
r,
2) +
pow(
c2,
2) *
pow(
mb,
2) *
pow(
r,
2) + 2 * B2 * mw *
pow(r, 2) + 2 * pow(a2, 2) * mb * mw * pow(r, 2) + 2 * pow(c2, 2) * mb * mw * pow(r, 2) +
(-1) *
pow(
c2,
2) *
pow(
mb,
2) *
pow(
r,
2) *
pow(
cos(psi),
2) + (-1) *
pow(
a2,
2) *
pow(mb, 2) * pow(r, 2) * pow(sin(psi), 2) + a2 * c2 * pow(mb, 2) * pow(r, 2) * sin(2 * psi)));
g1[4] = (-1) * K * L *
(1 /
(Jw *
pow(
L,
2) * 1 / r +
pow(
L,
2) * mw * r + 2 *
(C2 +
pow(
a2,
2) * mb) * r *
pow(
cos(psi),
2) + 2 *
(A2 + pow(c2, 2) * mb) * r * pow(sin(psi), 2) + 2 * a2 * c2 * mb * r * sin(2 * psi)));
g2[4] = K * L *
(1 /
(Jw *
pow(
L,
2) * 1 / r +
pow(
L,
2) * mw * r + 2 *
(C2 +
pow(
a2,
2) * mb) * r *
pow(
cos(psi),
2) + 2 *
(A2 + pow(c2, 2) * mb) * r * pow(sin(psi), 2) + 2 * a2 * c2 * mb * r * sin(2 * psi)));
g1[5] = 0;
g2[5] = 0;
g1[6] = (-2) * K *
(2 * Jw + mb *
pow(
r,
2) + 2 * mw *
pow(
r,
2) + c2 * mb * r * cos(psi) + (-1) * a2 * mb * r * sin(psi)) *
(1 /
(4 * B2 * Jw + 4 * pow(a2, 2) * Jw * mb + 4 * pow(c2, 2) * Jw * mb + 2 * B2 * mb * pow(r, 2) +
pow(
a2,
2) *
pow(
mb,
2) *
pow(
r,
2) +
pow(
c2,
2) * pow(mb, 2) * pow(r, 2) + 4 * B2 * mw * pow(r, 2) + 4 * pow(a2, 2) * mb * mw * pow(r, 2) +
4 *
pow(
c2,
2) * mb * mw *
pow(
r,
2) +
(pow(
a2,
2) + (-1) *
pow(
c2,
2)) *
pow(mb, 2) * pow(r, 2) * cos(2 * psi) + 2 * a2 * c2 * pow(mb, 2) * pow(r, 2) * sin(2 * psi)));
g2[6] = (-2) * K *
(2 * Jw + mb *
pow(
r,
2) + 2 * mw *
pow(
r,
2) + c2 * mb * r * cos(psi) + (-1) * a2 * mb * r * sin(psi)) *
(1 /
(4 * B2 * Jw + 4 * pow(a2, 2) * Jw * mb + 4 * pow(c2, 2) * Jw * mb + 2 * B2 * mb * pow(r, 2) +
pow(
a2,
2) *
pow(
mb,
2) *
pow(
r,
2) +
pow(
c2,
2) *
pow(
mb,
2) *
pow(
r,
2) + 4 * B2 * mw *
pow(r, 2) + 4 * pow(a2, 2) * mb * mw * pow(r, 2) + 4 * pow(c2, 2) * mb * mw * pow(r, 2) +
(pow(
a2,
2) + (-1) *
pow(
c2,
2)) *
pow(mb, 2) * pow(r, 2) * cos(2 * psi) + 2 * a2 * c2 * pow(mb, 2) * pow(r, 2) * sin(2 * psi)));
xDot = f + g * u;
return xDot;
}
#endif // SEGWAY_DYNAMICS_HPP_
| 20.211849 | 100 | 0.373601 | yamaha-bps |
9354b445599df8416c9c0a56d46a23ac4e56edfc | 600 | cpp | C++ | tutoriat-04-virtual-rtti/Subiecte examen/rezolvate/2.cpp | Tutoring-OOP-RM/Tutoring-OOP | f8709acbbe4a0fc0f869d95e3666c15f0332ddb8 | [
"MIT"
] | 4 | 2021-03-11T09:34:07.000Z | 2021-03-11T16:11:34.000Z | tutoriat-04-virtual-rtti/Subiecte examen/rezolvate/2.cpp | Tutoring-OOP-RM/Tutoring-OOP | f8709acbbe4a0fc0f869d95e3666c15f0332ddb8 | [
"MIT"
] | null | null | null | tutoriat-04-virtual-rtti/Subiecte examen/rezolvate/2.cpp | Tutoring-OOP-RM/Tutoring-OOP | f8709acbbe4a0fc0f869d95e3666c15f0332ddb8 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
class B {
public:
int x;
B(int i = 16) { x = i; }
B f(B ob) { return x + ob.x; }
};
class D : public B {
public:
D(int i = 25) { x = i; }
D f(D ob) { return x + ob.x + 1; }
void afisare() { cout << x; }
};
int main()
{
D *p1 = new D;
// LA p2 SE INCEARCA UN DOWNCAST GRESIT!
// D *p2 = new B; // a value of type "B *" cannot be used to initialize an entity of type "D *"!!
// error: invalid conversion from ‘B*’ to ‘D*’
D *p2 = new D;
D *p3 = new D(p1->f(*p2)); // 51 daca pt p2 pun D in D
cout << p3->x;
return 0;
}
| 20.689655 | 102 | 0.525 | Tutoring-OOP-RM |
935ae248a1bcee611fae546b2d549b2905f20536 | 9,797 | cc | C++ | aku/vtln.cc | phsmit/AaltoASR | 33cb58b288cc01bcdff0d6709a296d0dfcc7f74a | [
"BSD-3-Clause"
] | null | null | null | aku/vtln.cc | phsmit/AaltoASR | 33cb58b288cc01bcdff0d6709a296d0dfcc7f74a | [
"BSD-3-Clause"
] | null | null | null | aku/vtln.cc | phsmit/AaltoASR | 33cb58b288cc01bcdff0d6709a296d0dfcc7f74a | [
"BSD-3-Clause"
] | null | null | null | #include <math.h>
#include <string>
#include "io.hh"
#include "str.hh"
#include "conf.hh"
#include "HmmSet.hh"
#include "FeatureGenerator.hh"
#include "PhnReader.hh"
#include "Recipe.hh"
#include "SpeakerConfig.hh"
using namespace aku;
#define TINY 1e-10
std::string save_summary_file;
int info;
float grid_start;
float grid_step;
int grid_size;
bool relative_grid;
conf::Config config;
Recipe recipe;
HmmSet model;
FeatureGenerator fea_gen;
SpeakerConfig speaker_conf(fea_gen, &model);
VtlnModule *vtln_module;
std::string cur_speaker;
int cur_warp_index;
typedef struct
{
float center; // Center warp value
std::vector<float> warp_factors;
std::vector<double> log_likelihoods;
} SpeakerStats;
typedef std::map<std::string, SpeakerStats> SpeakerStatsMap;
SpeakerStatsMap speaker_stats;
void set_speaker(std::string speaker, std::string utterance, int grid_iter)
{
float new_warp;
int i;
cur_speaker = speaker;
assert(cur_speaker.size() > 0);
speaker_conf.set_speaker(speaker);
if (utterance.size() > 0)
speaker_conf.set_utterance(utterance);
SpeakerStatsMap::iterator it = speaker_stats.find(speaker);
if (it == speaker_stats.end()) {
// New speaker encountered
SpeakerStats new_speaker;
if (relative_grid)
new_speaker.center = vtln_module->get_warp_factor();
else
new_speaker.center = 1;
speaker_stats[cur_speaker] = new_speaker;
}
new_warp = speaker_stats[cur_speaker].center + grid_start + grid_iter
* grid_step;
vtln_module->set_warp_factor(new_warp);
for (i = 0; i < (int) speaker_stats[cur_speaker].warp_factors.size(); i++) {
if (fabs(new_warp - speaker_stats[cur_speaker].warp_factors[i]) < TINY)
break;
}
if (i == (int) speaker_stats[cur_speaker].warp_factors.size()) {
// New warp factor
speaker_stats[cur_speaker].warp_factors.push_back(new_warp);
speaker_stats[cur_speaker].log_likelihoods.push_back(0);
}
cur_warp_index = i;
}
void compute_vtln_log_likelihoods(Segmentator *seg, std::string &speaker,
std::string &utterance)
{
int grid_iter;
for (grid_iter = 0; grid_iter < grid_size; grid_iter++)
{
set_speaker(speaker, utterance, grid_iter);
seg->reset();
seg->init_utterance_segmentation();
while (seg->next_frame())
{
const Segmentator::IndexProbMap &pdfs = seg->pdf_probs();
FeatureVec fea_vec = fea_gen.generate(seg->current_frame());
if (fea_gen.eof())
break; // EOF in FeatureGenerator
for (Segmentator::IndexProbMap::const_iterator it = pdfs.begin();
it != pdfs.end(); ++it)
{
// Get probabilities
speaker_stats[cur_speaker].log_likelihoods[cur_warp_index] +=
util::safe_log((*it).second*model.pdf_likelihood((*it).first,
fea_vec));
}
}
}
}
void save_vtln_stats(FILE *fp)
{
for (SpeakerStatsMap::iterator it = speaker_stats.begin(); it
!= speaker_stats.end(); it++) {
fprintf(fp, "[%s]\n", (*it).first.c_str());
for (int i = 0; i < (int) (*it).second.warp_factors.size(); i++) {
fprintf(fp, "%.3f: %.3f\n", (*it).second.warp_factors[i],
(*it).second.log_likelihoods[i]);
}
fprintf(fp, "\n");
}
}
void find_best_warp_factors(void)
{
for (SpeakerStatsMap::iterator it = speaker_stats.begin(); it
!= speaker_stats.end(); it++) {
assert(
(*it).second.warp_factors.size() > 0
&& (*it).second.warp_factors.size()
== (*it).second.log_likelihoods.size());
float best_wf = (*it).second.warp_factors[0];
double best_ll = (*it).second.log_likelihoods[0];
for (int i = 1; i < (int) (*it).second.warp_factors.size(); i++) {
if ((*it).second.log_likelihoods[i] > best_ll) {
best_ll = (*it).second.log_likelihoods[i];
best_wf = (*it).second.warp_factors[i];
}
}
speaker_conf.set_speaker((*it).first);
vtln_module->set_warp_factor(best_wf);
}
}
int main(int argc, char *argv[])
{
PhnReader *phn_reader;
try {
config("usage: vtln [OPTION...]\n")
('h', "help", "", "", "display help")
('b', "base=BASENAME", "arg", "", "base filename for model files")
('g', "gk=FILE", "arg", "", "Gaussian kernels")
('m', "mc=FILE", "arg", "", "kernel indices for states")
('p', "ph=FILE", "arg", "", "HMM definitions")
('c', "config=FILE", "arg must", "", "feature configuration")
('r', "recipe=FILE", "arg must", "", "recipe file")
('O', "ophn", "", "", "use output phns for VTLN")
('v', "vtln=MODULE", "arg must", "", "VTLN module name")
('S', "speakers=FILE", "arg must", "", "speaker configuration input file")
('o', "out=FILE", "arg", "", "output speaker configuration file")
('s', "savesum=FILE", "arg", "", "save summary information (loglikelihoods)")
('\0', "snl", "", "", "phn-files with state number labels")
('\0', "rsamp", "", "", "phn sample numbers are relative to start time")
('\0', "grid-size=INT", "arg", "21", "warping grid size (default: 21/5)")
('\0', "grid-rad=FLOAT", "arg", "0.1", "radius of warping grid (default: 0.1/0.03)")
('\0', "relative", "", "", "relative warping grid (and smaller grid defaults)")
('B', "batch=INT", "arg", "0", "number of batch processes with the same recipe")
('I', "bindex=INT", "arg", "0", "batch process index")
('i', "info=INT", "arg", "0", "info level");
config.default_parse(argc, argv);
info = config["info"].get_int();
fea_gen.load_configuration(io::Stream(config["config"].get_str()));
if (config["base"].specified) {
model.read_all(config["base"].get_str());
}
else if (config["gk"].specified && config["mc"].specified
&& config["ph"].specified) {
model.read_gk(config["gk"].get_str());
model.read_mc(config["mc"].get_str());
model.read_ph(config["ph"].get_str());
}
else {
throw std::string(
"Must give either --base or all --gk, --mc and --ph");
}
if (config["savesum"].specified)
save_summary_file = config["savesum"].get_str();
if (config["batch"].specified ^ config["bindex"].specified)
throw std::string("Must give both --batch and --bindex");
// Read recipe file
recipe.read(io::Stream(config["recipe"].get_str()),
config["batch"].get_int(), config["bindex"].get_int(), true);
vtln_module = dynamic_cast<VtlnModule*> (fea_gen.module(
config["vtln"].get_str()));
if (vtln_module == NULL)
throw std::string("Module ") + config["vtln"].get_str()
+ std::string(" is not a VTLN module");
grid_start = config["grid-rad"].get_float();
grid_size = std::max(config["grid-size"].get_int(), 1);
grid_step = 2 * grid_start / std::max(grid_size - 1, 1);
relative_grid = config["relative"].specified;
if (relative_grid) {
if (!config["grid-rad"].specified)
grid_start = 0.03;
if (!config["grid-size"].specified)
grid_size = 5;
grid_step = 2 * grid_start / std::max(grid_size - 1, 1);
}
grid_start = -grid_start;
// Check the dimension
if (model.dim() != fea_gen.dim()) {
throw str::fmt(128,
"gaussian dimension is %d but feature dimension is %d",
model.dim(), fea_gen.dim());
}
speaker_conf.read_speaker_file(io::Stream(config["speakers"].get_str()));
for (int f = 0; f < (int) recipe.infos.size(); f++) {
if (info > 0) {
fprintf(stderr, "Processing file: %s",
recipe.infos[f].audio_path.c_str());
if (recipe.infos[f].start_time || recipe.infos[f].end_time)
fprintf(stderr, " (%.2f-%.2f)", recipe.infos[f].start_time,
recipe.infos[f].end_time);
fprintf(stderr, "\n");
}
// Open the audio and phn files from the given list.
phn_reader = recipe.infos[f].init_phn_files(&model,
config["rsamp"].specified, config["snl"].specified,
config["ophn"].specified, &fea_gen, NULL);
if (recipe.infos[f].speaker_id.size() == 0)
throw std::string("Speaker ID is missing");
compute_vtln_log_likelihoods(phn_reader,
recipe.infos[f].speaker_id, recipe.infos[f].utterance_id);
fea_gen.close();
phn_reader->close();
delete phn_reader;
}
// Find the best warp factors from statistics
find_best_warp_factors();
if (config["savesum"].specified) {
// Save the statistics
save_vtln_stats(io::Stream(save_summary_file, "w"));
}
// Write new speaker configuration
if (config["out"].specified) {
std::set<std::string> *speaker_set = NULL, *utterance_set = NULL;
std::set<std::string> speakers, empty_ut;
if (config["batch"].get_int() > 1) {
if (config["bindex"].get_int() == 1)
speakers.insert(std::string("default"));
for (SpeakerStatsMap::iterator it = speaker_stats.begin(); it
!= speaker_stats.end(); it++)
speakers.insert((*it).first);
speaker_set = &speakers;
utterance_set = &empty_ut;
}
speaker_conf.write_speaker_file(
io::Stream(config["out"].get_str(), "w"), speaker_set,
utterance_set);
}
}
catch (HmmSet::UnknownHmm &e) {
fprintf(stderr, "Unknown HMM in transcription\n");
abort();
}
catch (std::exception &e) {
fprintf(stderr, "exception: %s\n", e.what());
abort();
}
catch (std::string &str) {
fprintf(stderr, "exception: %s\n", str.c_str());
abort();
}
}
| 32.656667 | 101 | 0.597224 | phsmit |
935c5f36446a5daa029cb16ae2915b9374a805ea | 4,983 | cpp | C++ | zircon/system/utest/fuzz-utils/string-list.cpp | yanyushr/fuchsia | 98e70672a81a206d235503e398f37b7b65581f79 | [
"BSD-3-Clause"
] | null | null | null | zircon/system/utest/fuzz-utils/string-list.cpp | yanyushr/fuchsia | 98e70672a81a206d235503e398f37b7b65581f79 | [
"BSD-3-Clause"
] | null | null | null | zircon/system/utest/fuzz-utils/string-list.cpp | yanyushr/fuchsia | 98e70672a81a206d235503e398f37b7b65581f79 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <fuzz-utils/string-list.h>
#include <unittest/unittest.h>
namespace fuzzing {
namespace testing {
namespace {
#define arraysize(x) sizeof(x) / sizeof(x[0])
// Helper function to find expected strings in a list
bool Match(StringList* list, const char** expected, size_t off, size_t len) {
BEGIN_HELPER;
EXPECT_EQ(list->length(), len);
const char* elem = list->first();
for (size_t i = 0; i < len; ++i) {
ASSERT_NONNULL(elem);
EXPECT_STR_EQ(elem, expected[off + i]);
elem = list->next();
}
EXPECT_NULL(elem);
END_HELPER;
}
bool TestEmpty() {
BEGIN_TEST;
StringList list;
EXPECT_TRUE(list.is_empty());
EXPECT_NULL(list.first());
EXPECT_NULL(list.next());
END_TEST;
}
bool TestPushFrontAndBack() {
BEGIN_TEST;
StringList list;
const char* expected[] = {"", "foo", "bar", "baz", ""};
// Strings can be pushed from either end
list.push_front("bar");
list.push_back("baz");
list.push_front("foo");
EXPECT_TRUE(Match(&list, expected, 1, 3));
// Empty strings are fine
list.push_front("");
list.push_back("");
EXPECT_TRUE(Match(&list, expected, 0, 5));
// Null strings are ignored
list.push_front(nullptr);
list.push_back(nullptr);
EXPECT_TRUE(Match(&list, expected, 0, 5));
// Test the new constructor
StringList list2(expected, arraysize(expected));
EXPECT_TRUE(Match(&list, expected, 0, 5));
END_TEST;
}
bool TestKeepIf() {
BEGIN_TEST;
StringList list;
const char* original[] = {"", "foo", "bar", "baz", "qux",
"quux", "corge", "grault", "garply", "waldo",
"fred", "plugh", "xyzzy", "thud", ""};
const char* expected1[] = {"bar", "corge", "grault", "garply", "plugh"};
const char* expected2[] = {"corge", "grault", "garply", "plugh"};
const char* expected3[] = {"garply"};
for (size_t i = 0; i < arraysize(original); ++i) {
list.push_back(original[i]);
}
// Null string has no effect
list.keep_if(nullptr);
EXPECT_TRUE(Match(&list, original, 0, arraysize(original)));
// Empty string matches everything
list.keep_if("");
EXPECT_TRUE(Match(&list, original, 0, arraysize(original)));
// Match a string
list.keep_if("g");
EXPECT_TRUE(Match(&list, expected2, 0, arraysize(expected2)));
// Match a string that would have matched elements in the original list
list.keep_if("ar");
EXPECT_TRUE(Match(&list, expected3, 0, arraysize(expected3)));
// Use a string that doesn't match anything
list.keep_if("zzz");
EXPECT_TRUE(list.is_empty());
// Reset and apply both matches at once with logical-or
StringList substrs;
substrs.push_back("g");
substrs.push_back("ar");
list.clear();
for (size_t i = 0; i < arraysize(original); ++i) {
list.push_back(original[i]);
}
list.keep_if_any(&substrs);
EXPECT_TRUE(Match(&list, expected1, 0, arraysize(expected1)));
// Reset and apply both matches at once with logical-and
list.clear();
for (size_t i = 0; i < arraysize(original); ++i) {
list.push_back(original[i]);
}
list.keep_if_all(&substrs);
EXPECT_TRUE(Match(&list, expected3, 0, arraysize(expected3)));
END_TEST;
}
bool TestEraseIf() {
BEGIN_TEST;
StringList list;
const char* original[] = {"", "foo", "bar", "baz", ""};
const char* expected1[] = {"", "foo", "baz", ""};
const char* expected2[] = {"foo", "baz"};
for (size_t i = 0; i < sizeof(original) / sizeof(original[0]); ++i) {
list.push_back(original[i]);
}
// Null and empty strings have no effect
list.erase_if(nullptr);
EXPECT_TRUE(Match(&list, original, 0, arraysize(original)));
// Use a string that doesn't match anything
list.erase_if("zzz");
EXPECT_TRUE(Match(&list, original, 0, arraysize(original)));
// Match a string
list.erase_if("bar");
EXPECT_TRUE(Match(&list, expected1, 0, arraysize(expected1)));
// Idempotent
list.erase_if("bar");
EXPECT_TRUE(Match(&list, expected1, 0, arraysize(expected1)));
// Able to erase empty strings
list.erase_if("");
EXPECT_TRUE(Match(&list, expected2, 0, arraysize(expected2)));
END_TEST;
}
bool TestClear() {
BEGIN_TEST;
StringList list;
list.push_front("bar");
EXPECT_NONNULL(list.first());
list.clear();
EXPECT_NULL(list.next());
EXPECT_NULL(list.first());
EXPECT_EQ(list.length(), 0);
END_TEST;
}
BEGIN_TEST_CASE(StringListTest)
RUN_TEST(TestEmpty)
RUN_TEST(TestPushFrontAndBack)
RUN_TEST(TestKeepIf)
RUN_TEST(TestEraseIf)
RUN_TEST(TestClear)
END_TEST_CASE(StringListTest)
} // namespace
} // namespace testing
} // namespace fuzzing
| 26.365079 | 77 | 0.627333 | yanyushr |
935c99d810297c48a0b863ea0ae967f368f9a7a7 | 330 | cpp | C++ | HDU/20/hdu2030.cpp | bilibiliShen/CodeBank | 49a69b2b2c3603bf105140a9d924946ed3193457 | [
"MIT"
] | 1 | 2017-08-19T16:02:15.000Z | 2017-08-19T16:02:15.000Z | HDU/20/hdu2030.cpp | bilibiliShen/CodeBank | 49a69b2b2c3603bf105140a9d924946ed3193457 | [
"MIT"
] | null | null | null | HDU/20/hdu2030.cpp | bilibiliShen/CodeBank | 49a69b2b2c3603bf105140a9d924946ed3193457 | [
"MIT"
] | 1 | 2018-01-05T23:37:23.000Z | 2018-01-05T23:37:23.000Z | #include <stdio.h>
#include <string.h>
int main(void)
{
int n;
int count;
char c;
scanf("%d%*c", &n);
while (n--)
{
count = 0;
while ((c = getchar()) != '\n')
{
if (c < 0)
count++;
}
printf("%d\n", count / 2);
}
return 0;
}
| 12.222222 | 39 | 0.360606 | bilibiliShen |
93625ea160c92b5193dbc25e890a27fb6f2d3c33 | 1,658 | cpp | C++ | src/ui/components/frontiers_renderer.cpp | anuranbaka/Vulcan | 56339f77f6cf64b5fda876445a33e72cd15ce028 | [
"MIT"
] | 3 | 2020-03-05T23:56:14.000Z | 2021-02-17T19:06:50.000Z | src/ui/components/frontiers_renderer.cpp | anuranbaka/Vulcan | 56339f77f6cf64b5fda876445a33e72cd15ce028 | [
"MIT"
] | 1 | 2021-03-07T01:23:47.000Z | 2021-03-07T01:23:47.000Z | src/ui/components/frontiers_renderer.cpp | anuranbaka/Vulcan | 56339f77f6cf64b5fda876445a33e72cd15ce028 | [
"MIT"
] | 1 | 2021-03-03T07:54:16.000Z | 2021-03-03T07:54:16.000Z | /* Copyright (C) 2010-2019, The Regents of The University of Michigan.
All rights reserved.
This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab
under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an
MIT-style License that can be found at "https://github.com/h2ssh/Vulcan".
*/
/**
* \file frontiers_renderer.cpp
* \author Collin Johnson
*
* Definition of FrontiersRenderer.
*/
#include "ui/components/frontiers_renderer.h"
#include "hssh/local_topological/frontier.h"
#include "ui/common/gl_shapes.h"
#include <GL/gl.h>
#include <algorithm>
namespace vulcan
{
namespace ui
{
void draw_frontier(const hssh::Frontier& frontier);
void FrontiersRenderer::setRenderColor(const GLColor& frontierColor)
{
this->frontierColor = frontierColor;
}
void FrontiersRenderer::render(const std::vector<hssh::Frontier>& frontiers)
{
// Set the color here so it doesn't need to be passed into the draw_frontier function, as all colors are the same
// right now
frontierColor.set();
std::for_each(frontiers.begin(), frontiers.end(), [](const hssh::Frontier& frontier) {
draw_frontier(frontier);
});
}
void draw_frontier(const hssh::Frontier& frontier)
{
const float LINE_WIDTH = 2.0f;
glLineWidth(LINE_WIDTH);
glBegin(GL_LINES);
glVertex2f(frontier.boundary.a.x, frontier.boundary.a.y);
glVertex2f(frontier.boundary.b.x, frontier.boundary.b.y);
glEnd();
gl_draw_small_arrow(frontier.exitPoint, length(frontier.boundary) * 0.75, frontier.direction, LINE_WIDTH);
}
} // namespace ui
} // namespace vulcan
| 26.741935 | 117 | 0.728589 | anuranbaka |
9364ef2b32068883c5690a74afafab760d044879 | 636 | cpp | C++ | 7/char*replace.cpp | tangxiangru/NOIP | 6c756df37e5cb6105f5d5eb0fd9b03a4ef8407e4 | [
"MIT"
] | 1 | 2020-10-12T12:00:08.000Z | 2020-10-12T12:00:08.000Z | 7/char*replace.cpp | tangxiangru/NOIP | 6c756df37e5cb6105f5d5eb0fd9b03a4ef8407e4 | [
"MIT"
] | null | null | null | 7/char*replace.cpp | tangxiangru/NOIP | 6c756df37e5cb6105f5d5eb0fd9b03a4ef8407e4 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <string.h>
char *Replace(char *str, char *substr, char *newstr);
void main()
{
char a[80], b[80], c[80], *d;
gets(a);
gets(b);
gets(c);
d = Replace(a, b, c);
printf("%s", a);
}
char *Replace(char *str, char *substr, char *newstr)
{
int a, b, i, j, k, flag = 1;
a = strlen (str);
b = strlen (substr);
for (i = 0; i < a; i++)
{
if(str[i] == substr[0])
flag = 0;
for (j = i+1, k = 1; k < b; j++,k++)
if (str[j] != substr[k])
flag = 1;
if (flag == 0)
for (j = 0; j < b; j++)
{
str[i] = newstr[j];
i += 1;
}
}
return str;
} | 17.666667 | 54 | 0.45283 | tangxiangru |
9367af30344007cbbc912c8e26fd2890948e8f27 | 1,900 | cpp | C++ | W2D5/f2.cpp | MartrixG/2019-summer-OI | 4765533f4a373f6f277c1309c534050e52d631d8 | [
"MIT"
] | null | null | null | W2D5/f2.cpp | MartrixG/2019-summer-OI | 4765533f4a373f6f277c1309c534050e52d631d8 | [
"MIT"
] | null | null | null | W2D5/f2.cpp | MartrixG/2019-summer-OI | 4765533f4a373f6f277c1309c534050e52d631d8 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cstring>
#include <string>
#include <iostream>
using namespace std;
struct node
{
int max;
int l, r;
node *lc;
node *rc;
};
int max(int a, int b) { return a > b ? a : b; }
void build(node *root, int l, int r)
{
root->l = l;
root->r = r;
if (l == r)
{
root->lc = NULL;
root->rc = NULL;
scanf("%d",&root->max);
}
else
{
int mid = (l + r) >> 1;
root->lc = new node;
root->rc = new node;
build(root->lc, l, mid);
build(root->rc, mid + 1, r);
root->max = max(root->lc->max, root->rc->max);
}
}
int query_max(node *root, int l, int r)
{
if (root->r < l || root->l > r)
return -1;
if (root->l >= l && root->r <= r)
{
return root->max;
}
return max(query_max(root->lc, l, r), query_max(root->rc, l, r));
}
void modify(node *root, int l, int r, int k)
{
if (root->r < l || root->l > r)
return;
if (root->l >= l && root->r <= r)
{
root->max = k;
return;
}
if (root->l == root->r)
return;
modify(root->lc, l, r, k);
modify(root->rc, l, r, k);
root->max = max(root->lc->max, root->rc->max);
}
void clear(node *root)
{
if (root->lc != NULL)
clear(root->lc);
if (root->rc != NULL)
clear(root->rc);
root->lc=NULL;
root->rc=NULL;
delete (root);
}
int n, m;
int main()
{
while (scanf("%d%d", &n, &m) != EOF)
{
node* ROOT=new node;
build(ROOT, 1, n);
for (int i = 1; i <= m; i++)
{
char op;
int x, y;
cin >> op >> x >> y;
if (op == 'Q')
{
printf("%d\n", query_max(ROOT, x, y));
}
else
{
modify(ROOT, x, x, y);
}
}
clear(ROOT);
}
} | 19.791667 | 69 | 0.423684 | MartrixG |
9369374d15e2f717b63c5f7961f1fa454a2199d8 | 5,412 | hpp | C++ | src/utils/utils.hpp | TiWinDeTea/NinjaClown | fdd48e62466f11036fa0360fad2bcb182d6d3352 | [
"MIT"
] | 2 | 2020-04-10T14:39:00.000Z | 2021-02-11T15:52:16.000Z | src/utils/utils.hpp | TiWinDeTea/NinjaClown | fdd48e62466f11036fa0360fad2bcb182d6d3352 | [
"MIT"
] | 2 | 2019-12-17T08:50:20.000Z | 2020-02-03T09:37:56.000Z | src/utils/utils.hpp | TiWinDeTea/NinjaClown | fdd48e62466f11036fa0360fad2bcb182d6d3352 | [
"MIT"
] | 1 | 2020-08-19T03:06:52.000Z | 2020-08-19T03:06:52.000Z | #ifndef NINJACLOWN_UTILS_UTILS_HPP
#define NINJACLOWN_UTILS_UTILS_HPP
#include <algorithm>
#include <charconv>
#include <functional>
#include <optional>
#include <string_view>
#include <type_traits>
#include <cstddef>
namespace utils {
using ssize_t = std::make_signed_t<std::size_t>;
inline bool starts_with(std::string_view str, std::string_view prefix) {
return std::mismatch(str.begin(), str.end(), prefix.begin(), prefix.end()).second == prefix.end();
}
template <typename T>
struct add_const_s {
using type = T const;
};
template <typename T>
struct add_const_s<T &> {
using type = T const &;
};
template <typename T>
using add_const = typename add_const_s<T>::type;
template <typename T>
struct remove_const_s {
using type = std::remove_const_t<T>;
};
template <typename T>
struct remove_const_s<T &> {
using type = std::remove_const_t<T> &;
};
template <typename T>
using remove_const = typename remove_const_s<T>::type;
template <typename T>
std::optional<T> from_chars(std::string_view str) {
T value;
auto result = std::from_chars(str.data(), str.data() + str.size(), value);
if (result.ptr != str.data() + str.size() || result.ec != std::errc{}) {
return {};
}
return value;
}
// std::invoke is not constexpr in c++17
namespace detail {
template <class T>
struct is_reference_wrapper: std::false_type {};
template <typename U>
struct is_reference_wrapper<std::reference_wrapper<U>>: std::true_type {};
template <typename T>
constexpr bool is_reference_wrapper_v = is_reference_wrapper<T>::value;
template <typename T, typename Type, typename T1, typename... Args>
constexpr decltype(auto) do_invoke(Type T::*f, T1 &&t1, Args &&... args) {
if constexpr (std::is_member_function_pointer_v<decltype(f)>) {
if constexpr (std::is_base_of_v<T, std::decay_t<T1>>)
return (std::forward<T1>(t1).*f)(std::forward<Args>(args)...);
else if constexpr (is_reference_wrapper_v<std::decay_t<T1>>)
return (t1.get().*f)(std::forward<Args>(args)...);
else
return ((*std::forward<T1>(t1)).*f)(std::forward<Args>(args)...);
}
else {
static_assert(std::is_member_object_pointer_v<decltype(f)>);
static_assert(sizeof...(args) == 0);
if constexpr (std::is_base_of_v<T, std::decay_t<T1>>)
return std::forward<T1>(t1).*f;
else if constexpr (is_reference_wrapper_v<std::decay_t<T1>>)
return t1.get().*f;
else
return (*std::forward<T1>(t1)).*f;
}
}
template <class F, class... Args>
constexpr decltype(auto) do_invoke(F &&f, Args &&... args) {
return std::forward<F>(f)(std::forward<Args>(args)...);
}
} // namespace detail
template <class F, class... Args>
constexpr std::invoke_result_t<F, Args...> invoke(F &&f, Args &&... args) noexcept(std::is_nothrow_invocable_v<F, Args...>) {
return detail::do_invoke(std::forward<F>(f), std::forward<Args>(args)...);
}
// std::not_fn is not constexpr in c++17
namespace details {
template <typename Func>
struct not_fn_t {
template <typename... Args>
constexpr auto operator()(Args &&... args) & -> decltype(!std::declval<std::invoke_result_t<std::decay_t<Func> &, Args...>>()) {
return !utils::invoke(f, std::forward<Args>(args)...);
}
template <class... Args>
constexpr auto
operator()(Args &&... args) const & -> decltype(!std::declval<std::invoke_result_t<std::decay_t<Func> const &, Args...>>()) {
return !utils::invoke(f, std::forward<Args>(args)...);
}
template <class... Args>
constexpr auto operator()(Args &&... args) &&
-> decltype(!std::declval<std::invoke_result_t<std::decay_t<Func>, Args...>>()) {
return !utils::invoke(std::move(f), std::forward<Args>(args)...);
}
template <class... Args>
constexpr auto
operator()(Args &&... args) const && -> decltype(!std::declval<std::invoke_result_t<std::decay_t<Func> const, Args...>>()) {
return !utils::invoke(std::move(f), std::forward<Args>(args)...);
}
Func f;
};
} // namespace details
template <typename Func>
constexpr auto not_fn(Func &&f) noexcept {
return details::not_fn_t<Func>{std::forward<Func>(f)};
}
// std::is_sorted is not constexpr in c++17
template <typename ForwardIt, typename Compare>
constexpr bool is_sorted(ForwardIt begin, ForwardIt end, Compare comp) {
if (begin == end) {
return true;
}
auto current = std::next(begin);
auto previous = begin;
while (current != end) {
if (!comp(*previous++, *current++)) {
return false;
}
}
return true;
}
template <typename ForwardIt>
constexpr bool is_sorted(ForwardIt begin, ForwardIt end) {
return utils::is_sorted(begin, end, std::less<void>{});
}
// std::unique is not constexpr in c++17
template <typename ForwardIt, typename Predicate>
constexpr bool unique(ForwardIt begin, ForwardIt end, Predicate pred) {
return utils::is_sorted(begin, end, utils::not_fn(pred));
}
// std::unique is not constexpr in c++17
template <typename ForwardIt>
constexpr bool unique(ForwardIt begin, ForwardIt end) {
return utils::is_sorted(begin, end, utils::not_fn(std::equal_to<void>{}));
}
// checks that a collection contains all number sorted from 0 to max, exactly once
template <typename T>
constexpr bool has_all_sorted(const T &values, typename T::value_type max) {
return values.size() == max + 1 && values.back() == max && utils::is_sorted(values.begin(), values.end())
&& utils::unique(values.begin(), values.end());
}
} // namespace utils
#endif //NINJACLOWN_UTILS_UTILS_HPP
| 30.234637 | 130 | 0.68422 | TiWinDeTea |
936bc1c905f2db19d372803b59d6f7029abea133 | 4,186 | cc | C++ | third_party/blink/renderer/core/paint/compositing/paint_layer_compositor_test.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | third_party/blink/renderer/core/paint/compositing/paint_layer_compositor_test.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | third_party/blink/renderer/core/paint/compositing/paint_layer_compositor_test.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/paint/compositing/paint_layer_compositor.h"
#include "third_party/blink/renderer/core/animation/animation.h"
#include "third_party/blink/renderer/core/animation/element_animation.h"
#include "third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/testing/core_unit_test_helper.h"
namespace blink {
namespace {
class PaintLayerCompositorTest : public RenderingTest {
public:
PaintLayerCompositorTest()
: RenderingTest(SingleChildLocalFrameClient::Create()) {}
private:
void SetUp() override {
RenderingTest::SetUp();
EnableCompositing();
}
};
} // namespace
TEST_F(PaintLayerCompositorTest, AdvancingToCompositingInputsClean) {
SetBodyInnerHTML("<div id='box' style='position: relative'></div>");
PaintLayer* box_layer =
ToLayoutBox(GetLayoutObjectByElementId("box"))->Layer();
ASSERT_TRUE(box_layer);
EXPECT_FALSE(box_layer->NeedsCompositingInputsUpdate());
box_layer->SetNeedsCompositingInputsUpdate();
GetDocument().View()->UpdateLifecycleToCompositingInputsClean();
EXPECT_EQ(DocumentLifecycle::kCompositingInputsClean,
GetDocument().Lifecycle().GetState());
EXPECT_FALSE(box_layer->NeedsCompositingInputsUpdate());
GetDocument().View()->SetNeedsLayout();
EXPECT_TRUE(GetDocument().View()->NeedsLayout());
}
TEST_F(PaintLayerCompositorTest,
CompositingInputsCleanDoesNotTriggerAnimations) {
SetBodyInnerHTML(R"HTML(
<style>@keyframes fadeOut { from { opacity: 1; } to { opacity: 0; } }
.animate { animation: fadeOut 2s; }</style>
<div id='box'></div>
<div id='otherBox'></div>
)HTML");
Element* box = GetDocument().getElementById("box");
Element* otherBox = GetDocument().getElementById("otherBox");
ASSERT_TRUE(box);
ASSERT_TRUE(otherBox);
box->setAttribute("class", "animate", ASSERT_NO_EXCEPTION);
// Update the lifecycle to CompositingInputsClean. This should not start the
// animation lifecycle.
GetDocument().View()->UpdateLifecycleToCompositingInputsClean();
EXPECT_EQ(DocumentLifecycle::kCompositingInputsClean,
GetDocument().Lifecycle().GetState());
otherBox->setAttribute("class", "animate", ASSERT_NO_EXCEPTION);
// Now run the rest of the lifecycle. Because both 'box' and 'otherBox' were
// given animations separated only by a lifecycle update to
// CompositingInputsClean, they should both be started in the same lifecycle
// and as such grouped together.
GetDocument().View()->UpdateAllLifecyclePhases();
EXPECT_EQ(DocumentLifecycle::kPaintClean,
GetDocument().Lifecycle().GetState());
HeapVector<Member<Animation>> boxAnimations =
ElementAnimation::getAnimations(*box);
HeapVector<Member<Animation>> otherBoxAnimations =
ElementAnimation::getAnimations(*box);
EXPECT_EQ(1ul, boxAnimations.size());
EXPECT_EQ(1ul, otherBoxAnimations.size());
EXPECT_EQ(boxAnimations.front()->CompositorGroup(),
otherBoxAnimations.front()->CompositorGroup());
}
TEST_F(PaintLayerCompositorTest, UpdateDoesNotOrphanMainGraphicsLayer) {
SetHtmlInnerHTML(R"HTML(
<style> * { margin: 0 } </style>
<div id='box'></div>
)HTML");
auto* main_graphics_layer = GetDocument()
.GetLayoutView()
->Layer()
->GetCompositedLayerMapping()
->MainGraphicsLayer();
auto* main_graphics_layer_parent = main_graphics_layer->Parent();
EXPECT_NE(nullptr, main_graphics_layer_parent);
// Force CompositedLayerMapping to update the internal layer hierarchy.
auto* box = GetDocument().getElementById("box");
box->setAttribute(HTMLNames::styleAttr, "height: 1000px;");
GetDocument().View()->UpdateAllLifecyclePhases();
EXPECT_EQ(main_graphics_layer_parent, main_graphics_layer->Parent());
}
} // namespace blink
| 36.719298 | 87 | 0.723125 | zipated |
936dc75b3cfc04cdf53f38c65ad4f277d5e998a9 | 1,513 | cc | C++ | skiko/src/commonMain/cpp/generated/PathSegmentIterator.cc | sellmair/skiko | 9ccc6234799558386ccfa00630600e02c8eb62f9 | [
"Apache-2.0"
] | 842 | 2020-07-27T11:38:31.000Z | 2022-03-30T17:37:21.000Z | skiko/src/commonMain/cpp/generated/PathSegmentIterator.cc | sellmair/skiko | 9ccc6234799558386ccfa00630600e02c8eb62f9 | [
"Apache-2.0"
] | 127 | 2020-09-17T08:12:40.000Z | 2022-03-31T08:56:56.000Z | skiko/src/commonMain/cpp/generated/PathSegmentIterator.cc | sellmair/skiko | 9ccc6234799558386ccfa00630600e02c8eb62f9 | [
"Apache-2.0"
] | 49 | 2020-07-27T16:48:56.000Z | 2022-03-24T14:15:33.000Z | #include "SkPath.h"
#include "common.h"
SKIKO_EXPORT KNativePointer org_jetbrains_skia_PathSegmentIterator__1nMake
(KNativePointer pathPtr, KBoolean forceClose) {
SkPath* path = reinterpret_cast<SkPath*>(pathPtr);
SkPath::Iter* iter = new SkPath::Iter(*path, forceClose);
return reinterpret_cast<KNativePointer>(iter);
}
static void deletePathSegmentIterator(SkPath::Iter* iter) {
// std::cout << "Deleting [SkPathSegmentIterator " << path << "]" << std::endl;
delete iter;
}
SKIKO_EXPORT KNativePointer org_jetbrains_skia_PathSegmentIterator__1nGetFinalizer() {
return reinterpret_cast<KNativePointer>((&deletePathSegmentIterator));
}
SKIKO_EXPORT void org_jetbrains_skia_PathSegmentIterator__1nNext(KNativePointer ptr, KInt* data) {
SkPath::Iter* instance = reinterpret_cast<SkPath::Iter*>(ptr);
SkPoint pts[4];
SkPath::Verb verb = instance->next(pts);
data[0] = rawBits(pts[0].fX);
data[1] = rawBits(pts[0].fY);
data[2] = rawBits(pts[1].fX);
data[3] = rawBits(pts[1].fY);
data[4] = rawBits(pts[2].fX);
data[5] = rawBits(pts[2].fY);
data[6] = rawBits(pts[3].fX);
data[7] = rawBits(pts[3].fY);
// Otherwise it's null.
if (verb == SkPath::Verb::kConic_Verb)
data[8] = rawBits(instance->conicWeight());
int context = verb;
if (instance -> isClosedContour()) {
context = context | (1 << 7);
}
if (instance -> isCloseLine()) {
context = context | (1 << 6);
}
data[9] = context;
} | 30.26 | 98 | 0.66226 | sellmair |
936f32f4905b9a290905efd784be3b3828368b0d | 178,176 | cc | C++ | libcpp/Include/Proto/Qot_StockFilter.pb.cc | stephenlyu/gofutuapi | 1a60310dd142ac7049c9ef9cf22c7d78d0f880ef | [
"MIT"
] | 2 | 2020-11-27T04:53:13.000Z | 2021-11-15T02:15:27.000Z | libcpp/Include/Proto/Qot_StockFilter.pb.cc | stephenlyu/gofutuapi | 1a60310dd142ac7049c9ef9cf22c7d78d0f880ef | [
"MIT"
] | null | null | null | libcpp/Include/Proto/Qot_StockFilter.pb.cc | stephenlyu/gofutuapi | 1a60310dd142ac7049c9ef9cf22c7d78d0f880ef | [
"MIT"
] | null | null | null | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: Qot_StockFilter.proto
#include "Qot_StockFilter.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// This is a temporary google only hack
#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
#include "third_party/protobuf/version.h"
#endif
// @@protoc_insertion_point(includes)
namespace Qot_StockFilter {
class BaseFilterDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<BaseFilter>
_instance;
} _BaseFilter_default_instance_;
class AccumulateFilterDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<AccumulateFilter>
_instance;
} _AccumulateFilter_default_instance_;
class FinancialFilterDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<FinancialFilter>
_instance;
} _FinancialFilter_default_instance_;
class BaseDataDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<BaseData>
_instance;
} _BaseData_default_instance_;
class AccumulateDataDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<AccumulateData>
_instance;
} _AccumulateData_default_instance_;
class FinancialDataDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<FinancialData>
_instance;
} _FinancialData_default_instance_;
class StockDataDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<StockData>
_instance;
} _StockData_default_instance_;
class C2SDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<C2S>
_instance;
} _C2S_default_instance_;
class S2CDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<S2C>
_instance;
} _S2C_default_instance_;
class RequestDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<Request>
_instance;
} _Request_default_instance_;
class ResponseDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<Response>
_instance;
} _Response_default_instance_;
} // namespace Qot_StockFilter
namespace protobuf_Qot_5fStockFilter_2eproto {
void InitDefaultsBaseFilterImpl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
::google::protobuf::internal::InitProtobufDefaultsForceUnique();
#else
::google::protobuf::internal::InitProtobufDefaults();
#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::Qot_StockFilter::_BaseFilter_default_instance_;
new (ptr) ::Qot_StockFilter::BaseFilter();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::Qot_StockFilter::BaseFilter::InitAsDefaultInstance();
}
void InitDefaultsBaseFilter() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &InitDefaultsBaseFilterImpl);
}
void InitDefaultsAccumulateFilterImpl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
::google::protobuf::internal::InitProtobufDefaultsForceUnique();
#else
::google::protobuf::internal::InitProtobufDefaults();
#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::Qot_StockFilter::_AccumulateFilter_default_instance_;
new (ptr) ::Qot_StockFilter::AccumulateFilter();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::Qot_StockFilter::AccumulateFilter::InitAsDefaultInstance();
}
void InitDefaultsAccumulateFilter() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &InitDefaultsAccumulateFilterImpl);
}
void InitDefaultsFinancialFilterImpl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
::google::protobuf::internal::InitProtobufDefaultsForceUnique();
#else
::google::protobuf::internal::InitProtobufDefaults();
#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::Qot_StockFilter::_FinancialFilter_default_instance_;
new (ptr) ::Qot_StockFilter::FinancialFilter();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::Qot_StockFilter::FinancialFilter::InitAsDefaultInstance();
}
void InitDefaultsFinancialFilter() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFinancialFilterImpl);
}
void InitDefaultsBaseDataImpl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
::google::protobuf::internal::InitProtobufDefaultsForceUnique();
#else
::google::protobuf::internal::InitProtobufDefaults();
#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::Qot_StockFilter::_BaseData_default_instance_;
new (ptr) ::Qot_StockFilter::BaseData();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::Qot_StockFilter::BaseData::InitAsDefaultInstance();
}
void InitDefaultsBaseData() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &InitDefaultsBaseDataImpl);
}
void InitDefaultsAccumulateDataImpl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
::google::protobuf::internal::InitProtobufDefaultsForceUnique();
#else
::google::protobuf::internal::InitProtobufDefaults();
#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::Qot_StockFilter::_AccumulateData_default_instance_;
new (ptr) ::Qot_StockFilter::AccumulateData();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::Qot_StockFilter::AccumulateData::InitAsDefaultInstance();
}
void InitDefaultsAccumulateData() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &InitDefaultsAccumulateDataImpl);
}
void InitDefaultsFinancialDataImpl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
::google::protobuf::internal::InitProtobufDefaultsForceUnique();
#else
::google::protobuf::internal::InitProtobufDefaults();
#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::Qot_StockFilter::_FinancialData_default_instance_;
new (ptr) ::Qot_StockFilter::FinancialData();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::Qot_StockFilter::FinancialData::InitAsDefaultInstance();
}
void InitDefaultsFinancialData() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &InitDefaultsFinancialDataImpl);
}
void InitDefaultsStockDataImpl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
::google::protobuf::internal::InitProtobufDefaultsForceUnique();
#else
::google::protobuf::internal::InitProtobufDefaults();
#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
protobuf_Qot_5fCommon_2eproto::InitDefaultsSecurity();
protobuf_Qot_5fStockFilter_2eproto::InitDefaultsBaseData();
protobuf_Qot_5fStockFilter_2eproto::InitDefaultsAccumulateData();
protobuf_Qot_5fStockFilter_2eproto::InitDefaultsFinancialData();
{
void* ptr = &::Qot_StockFilter::_StockData_default_instance_;
new (ptr) ::Qot_StockFilter::StockData();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::Qot_StockFilter::StockData::InitAsDefaultInstance();
}
void InitDefaultsStockData() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &InitDefaultsStockDataImpl);
}
void InitDefaultsC2SImpl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
::google::protobuf::internal::InitProtobufDefaultsForceUnique();
#else
::google::protobuf::internal::InitProtobufDefaults();
#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
protobuf_Qot_5fCommon_2eproto::InitDefaultsSecurity();
protobuf_Qot_5fStockFilter_2eproto::InitDefaultsBaseFilter();
protobuf_Qot_5fStockFilter_2eproto::InitDefaultsAccumulateFilter();
protobuf_Qot_5fStockFilter_2eproto::InitDefaultsFinancialFilter();
{
void* ptr = &::Qot_StockFilter::_C2S_default_instance_;
new (ptr) ::Qot_StockFilter::C2S();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::Qot_StockFilter::C2S::InitAsDefaultInstance();
}
void InitDefaultsC2S() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &InitDefaultsC2SImpl);
}
void InitDefaultsS2CImpl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
::google::protobuf::internal::InitProtobufDefaultsForceUnique();
#else
::google::protobuf::internal::InitProtobufDefaults();
#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
protobuf_Qot_5fStockFilter_2eproto::InitDefaultsStockData();
{
void* ptr = &::Qot_StockFilter::_S2C_default_instance_;
new (ptr) ::Qot_StockFilter::S2C();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::Qot_StockFilter::S2C::InitAsDefaultInstance();
}
void InitDefaultsS2C() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &InitDefaultsS2CImpl);
}
void InitDefaultsRequestImpl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
::google::protobuf::internal::InitProtobufDefaultsForceUnique();
#else
::google::protobuf::internal::InitProtobufDefaults();
#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
protobuf_Qot_5fStockFilter_2eproto::InitDefaultsC2S();
{
void* ptr = &::Qot_StockFilter::_Request_default_instance_;
new (ptr) ::Qot_StockFilter::Request();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::Qot_StockFilter::Request::InitAsDefaultInstance();
}
void InitDefaultsRequest() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &InitDefaultsRequestImpl);
}
void InitDefaultsResponseImpl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
::google::protobuf::internal::InitProtobufDefaultsForceUnique();
#else
::google::protobuf::internal::InitProtobufDefaults();
#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
protobuf_Qot_5fStockFilter_2eproto::InitDefaultsS2C();
{
void* ptr = &::Qot_StockFilter::_Response_default_instance_;
new (ptr) ::Qot_StockFilter::Response();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::Qot_StockFilter::Response::InitAsDefaultInstance();
}
void InitDefaultsResponse() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &InitDefaultsResponseImpl);
}
::google::protobuf::Metadata file_level_metadata[11];
const ::google::protobuf::EnumDescriptor* file_level_enum_descriptors[5];
const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::BaseFilter, _has_bits_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::BaseFilter, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::BaseFilter, field_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::BaseFilter, filtermin_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::BaseFilter, filtermax_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::BaseFilter, isnofilter_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::BaseFilter, sortdir_),
1,
0,
3,
2,
4,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::AccumulateFilter, _has_bits_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::AccumulateFilter, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::AccumulateFilter, field_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::AccumulateFilter, filtermin_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::AccumulateFilter, filtermax_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::AccumulateFilter, isnofilter_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::AccumulateFilter, sortdir_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::AccumulateFilter, days_),
1,
0,
3,
2,
4,
5,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::FinancialFilter, _has_bits_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::FinancialFilter, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::FinancialFilter, field_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::FinancialFilter, filtermin_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::FinancialFilter, filtermax_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::FinancialFilter, isnofilter_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::FinancialFilter, sortdir_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::FinancialFilter, quarter_),
1,
0,
3,
2,
4,
5,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::BaseData, _has_bits_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::BaseData, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::BaseData, field_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::BaseData, value_),
1,
0,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::AccumulateData, _has_bits_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::AccumulateData, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::AccumulateData, field_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::AccumulateData, value_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::AccumulateData, days_),
1,
0,
2,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::FinancialData, _has_bits_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::FinancialData, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::FinancialData, field_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::FinancialData, value_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::FinancialData, quarter_),
1,
0,
2,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::StockData, _has_bits_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::StockData, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::StockData, security_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::StockData, name_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::StockData, basedatalist_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::StockData, accumulatedatalist_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::StockData, financialdatalist_),
1,
0,
~0u,
~0u,
~0u,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::C2S, _has_bits_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::C2S, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::C2S, begin_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::C2S, num_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::C2S, market_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::C2S, plate_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::C2S, basefilterlist_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::C2S, accumulatefilterlist_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::C2S, financialfilterlist_),
1,
2,
3,
0,
~0u,
~0u,
~0u,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::S2C, _has_bits_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::S2C, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::S2C, lastpage_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::S2C, allcount_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::S2C, datalist_),
0,
1,
~0u,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::Request, _has_bits_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::Request, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::Request, c2s_),
0,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::Response, _has_bits_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::Response, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::Response, rettype_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::Response, retmsg_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::Response, errcode_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::Qot_StockFilter::Response, s2c_),
3,
0,
2,
1,
};
static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
{ 0, 10, sizeof(::Qot_StockFilter::BaseFilter)},
{ 15, 26, sizeof(::Qot_StockFilter::AccumulateFilter)},
{ 32, 43, sizeof(::Qot_StockFilter::FinancialFilter)},
{ 49, 56, sizeof(::Qot_StockFilter::BaseData)},
{ 58, 66, sizeof(::Qot_StockFilter::AccumulateData)},
{ 69, 77, sizeof(::Qot_StockFilter::FinancialData)},
{ 80, 90, sizeof(::Qot_StockFilter::StockData)},
{ 95, 107, sizeof(::Qot_StockFilter::C2S)},
{ 114, 122, sizeof(::Qot_StockFilter::S2C)},
{ 125, 131, sizeof(::Qot_StockFilter::Request)},
{ 132, 141, sizeof(::Qot_StockFilter::Response)},
};
static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&::Qot_StockFilter::_BaseFilter_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::Qot_StockFilter::_AccumulateFilter_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::Qot_StockFilter::_FinancialFilter_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::Qot_StockFilter::_BaseData_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::Qot_StockFilter::_AccumulateData_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::Qot_StockFilter::_FinancialData_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::Qot_StockFilter::_StockData_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::Qot_StockFilter::_C2S_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::Qot_StockFilter::_S2C_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::Qot_StockFilter::_Request_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::Qot_StockFilter::_Response_default_instance_),
};
void protobuf_AssignDescriptors() {
AddDescriptors();
::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
"Qot_StockFilter.proto", schemas, file_default_instances, TableStruct::offsets, factory,
file_level_metadata, file_level_enum_descriptors, NULL);
}
void protobuf_AssignDescriptorsOnce() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 11);
}
void AddDescriptorsImpl() {
InitDefaults();
static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n\025Qot_StockFilter.proto\022\017Qot_StockFilter"
"\032\014Common.proto\032\020Qot_Common.proto\"f\n\nBase"
"Filter\022\r\n\005field\030\001 \002(\005\022\021\n\tfilterMin\030\002 \001(\001"
"\022\021\n\tfilterMax\030\003 \001(\001\022\022\n\nisNoFilter\030\004 \001(\010\022"
"\017\n\007sortDir\030\005 \001(\005\"z\n\020AccumulateFilter\022\r\n\005"
"field\030\001 \002(\005\022\021\n\tfilterMin\030\002 \001(\001\022\021\n\tfilter"
"Max\030\003 \001(\001\022\022\n\nisNoFilter\030\004 \001(\010\022\017\n\007sortDir"
"\030\005 \001(\005\022\014\n\004days\030\006 \002(\005\"|\n\017FinancialFilter\022"
"\r\n\005field\030\001 \002(\005\022\021\n\tfilterMin\030\002 \001(\001\022\021\n\tfil"
"terMax\030\003 \001(\001\022\022\n\nisNoFilter\030\004 \001(\010\022\017\n\007sort"
"Dir\030\005 \001(\005\022\017\n\007quarter\030\006 \002(\005\"(\n\010BaseData\022\r"
"\n\005field\030\001 \002(\005\022\r\n\005value\030\002 \002(\001\"<\n\016Accumula"
"teData\022\r\n\005field\030\001 \002(\005\022\r\n\005value\030\002 \002(\001\022\014\n\004"
"days\030\003 \002(\005\">\n\rFinancialData\022\r\n\005field\030\001 \002"
"(\005\022\r\n\005value\030\002 \002(\001\022\017\n\007quarter\030\003 \002(\005\"\352\001\n\tS"
"tockData\022&\n\010security\030\001 \002(\0132\024.Qot_Common."
"Security\022\014\n\004name\030\002 \002(\t\022/\n\014baseDataList\030\003"
" \003(\0132\031.Qot_StockFilter.BaseData\022;\n\022accum"
"ulateDataList\030\004 \003(\0132\037.Qot_StockFilter.Ac"
"cumulateData\0229\n\021financialDataList\030\005 \003(\0132"
"\036.Qot_StockFilter.FinancialData\"\213\002\n\003C2S\022"
"\r\n\005begin\030\001 \002(\005\022\013\n\003num\030\002 \002(\005\022\016\n\006market\030\003 "
"\002(\005\022#\n\005plate\030\004 \001(\0132\024.Qot_Common.Security"
"\0223\n\016baseFilterList\030\005 \003(\0132\033.Qot_StockFilt"
"er.BaseFilter\022\?\n\024accumulateFilterList\030\006 "
"\003(\0132!.Qot_StockFilter.AccumulateFilter\022="
"\n\023financialFilterList\030\007 \003(\0132 .Qot_StockF"
"ilter.FinancialFilter\"W\n\003S2C\022\020\n\010lastPage"
"\030\001 \002(\010\022\020\n\010allCount\030\002 \002(\005\022,\n\010dataList\030\003 \003"
"(\0132\032.Qot_StockFilter.StockData\",\n\007Reques"
"t\022!\n\003c2s\030\001 \002(\0132\024.Qot_StockFilter.C2S\"e\n\010"
"Response\022\025\n\007retType\030\001 \002(\005:\004-400\022\016\n\006retMs"
"g\030\002 \001(\t\022\017\n\007errCode\030\003 \001(\005\022!\n\003s2c\030\004 \001(\0132\024."
"Qot_StockFilter.S2C*\234\004\n\nStockField\022\026\n\022St"
"ockField_Unknown\020\000\022\030\n\024StockField_StockCo"
"de\020\001\022\030\n\024StockField_StockName\020\002\022\027\n\023StockF"
"ield_CurPrice\020\003\022,\n(StockField_CurPriceTo"
"Highest52WeeksRatio\020\004\022+\n\'StockField_CurP"
"riceToLowest52WeeksRatio\020\005\022-\n)StockField"
"_HighPriceToHighest52WeeksRatio\020\006\022+\n\'Sto"
"ckField_LowPriceToLowest52WeeksRatio\020\007\022\032"
"\n\026StockField_VolumeRatio\020\010\022\032\n\026StockField"
"_BidAskRatio\020\t\022\027\n\023StockField_LotPrice\020\n\022"
"\030\n\024StockField_MarketVal\020\013\022\027\n\023StockField_"
"PeAnnual\020\014\022\024\n\020StockField_PeTTM\020\r\022\025\n\021Stoc"
"kField_PbRate\020\016\022\035\n\031StockField_ChangeRate"
"5min\020\017\022\"\n\036StockField_ChangeRateBeginYear"
"\020\020*\311\001\n\017AccumulateField\022\033\n\027AccumulateFiel"
"d_Unknown\020\000\022\036\n\032AccumulateField_ChangeRat"
"e\020\001\022\035\n\031AccumulateField_Amplitude\020\002\022\032\n\026Ac"
"cumulateField_Volume\020\003\022\034\n\030AccumulateFiel"
"d_Turnover\020\004\022 \n\034AccumulateField_Turnover"
"Rate\020\005*\307\002\n\016FinancialField\022\032\n\026FinancialFi"
"eld_Unknown\020\000\022\034\n\030FinancialField_NetProfi"
"t\020\001\022\"\n\036FinancialField_NetProfitGrowth\020\002\022"
" \n\034FinancialField_SumOfBusiness\020\003\022&\n\"Fin"
"ancialField_SumOfBusinessGrowth\020\004\022 \n\034Fin"
"ancialField_NetProfitRate\020\005\022\"\n\036Financial"
"Field_GrossProfitRate\020\006\022 \n\034FinancialFiel"
"d_DebtAssetRate\020\007\022%\n!FinancialField_Retu"
"rnOnEquityRate\020\010*\331\001\n\020FinancialQuarter\022\034\n"
"\030FinancialQuarter_Unknown\020\000\022\033\n\027Financial"
"Quarter_Annual\020\001\022!\n\035FinancialQuarter_Fir"
"stQuarter\020\002\022\034\n\030FinancialQuarter_Interim\020"
"\003\022!\n\035FinancialQuarter_ThirdQuarter\020\004\022&\n\""
"FinancialQuarter_MostRecentQuarter\020\005*B\n\007"
"SortDir\022\016\n\nSortDir_No\020\000\022\022\n\016SortDir_Ascen"
"d\020\001\022\023\n\017SortDir_Descend\020\002B\025\n\023com.futu.ope"
"napi.pb"
};
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
descriptor, 2727);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"Qot_StockFilter.proto", &protobuf_RegisterTypes);
::protobuf_Common_2eproto::AddDescriptors();
::protobuf_Qot_5fCommon_2eproto::AddDescriptors();
}
void AddDescriptors() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
}
// Force AddDescriptors() to be called at dynamic initialization time.
struct StaticDescriptorInitializer {
StaticDescriptorInitializer() {
AddDescriptors();
}
} static_descriptor_initializer;
} // namespace protobuf_Qot_5fStockFilter_2eproto
namespace Qot_StockFilter {
const ::google::protobuf::EnumDescriptor* StockField_descriptor() {
protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_Qot_5fStockFilter_2eproto::file_level_enum_descriptors[0];
}
bool StockField_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
return true;
default:
return false;
}
}
const ::google::protobuf::EnumDescriptor* AccumulateField_descriptor() {
protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_Qot_5fStockFilter_2eproto::file_level_enum_descriptors[1];
}
bool AccumulateField_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
return true;
default:
return false;
}
}
const ::google::protobuf::EnumDescriptor* FinancialField_descriptor() {
protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_Qot_5fStockFilter_2eproto::file_level_enum_descriptors[2];
}
bool FinancialField_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
return true;
default:
return false;
}
}
const ::google::protobuf::EnumDescriptor* FinancialQuarter_descriptor() {
protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_Qot_5fStockFilter_2eproto::file_level_enum_descriptors[3];
}
bool FinancialQuarter_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
return true;
default:
return false;
}
}
const ::google::protobuf::EnumDescriptor* SortDir_descriptor() {
protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_Qot_5fStockFilter_2eproto::file_level_enum_descriptors[4];
}
bool SortDir_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 2:
return true;
default:
return false;
}
}
// ===================================================================
void BaseFilter::InitAsDefaultInstance() {
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int BaseFilter::kFieldFieldNumber;
const int BaseFilter::kFilterMinFieldNumber;
const int BaseFilter::kFilterMaxFieldNumber;
const int BaseFilter::kIsNoFilterFieldNumber;
const int BaseFilter::kSortDirFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
BaseFilter::BaseFilter()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsBaseFilter();
}
SharedCtor();
// @@protoc_insertion_point(constructor:Qot_StockFilter.BaseFilter)
}
BaseFilter::BaseFilter(const BaseFilter& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
::memcpy(&filtermin_, &from.filtermin_,
static_cast<size_t>(reinterpret_cast<char*>(&sortdir_) -
reinterpret_cast<char*>(&filtermin_)) + sizeof(sortdir_));
// @@protoc_insertion_point(copy_constructor:Qot_StockFilter.BaseFilter)
}
void BaseFilter::SharedCtor() {
_cached_size_ = 0;
::memset(&filtermin_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&sortdir_) -
reinterpret_cast<char*>(&filtermin_)) + sizeof(sortdir_));
}
BaseFilter::~BaseFilter() {
// @@protoc_insertion_point(destructor:Qot_StockFilter.BaseFilter)
SharedDtor();
}
void BaseFilter::SharedDtor() {
}
void BaseFilter::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* BaseFilter::descriptor() {
::protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const BaseFilter& BaseFilter::default_instance() {
::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsBaseFilter();
return *internal_default_instance();
}
BaseFilter* BaseFilter::New(::google::protobuf::Arena* arena) const {
BaseFilter* n = new BaseFilter;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void BaseFilter::Clear() {
// @@protoc_insertion_point(message_clear_start:Qot_StockFilter.BaseFilter)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 31u) {
::memset(&filtermin_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&sortdir_) -
reinterpret_cast<char*>(&filtermin_)) + sizeof(sortdir_));
}
_has_bits_.Clear();
_internal_metadata_.Clear();
}
bool BaseFilter::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:Qot_StockFilter.BaseFilter)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// required int32 field = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
set_has_field();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &field_)));
} else {
goto handle_unusual;
}
break;
}
// optional double filterMin = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(17u /* 17 & 0xFF */)) {
set_has_filtermin();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &filtermin_)));
} else {
goto handle_unusual;
}
break;
}
// optional double filterMax = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(25u /* 25 & 0xFF */)) {
set_has_filtermax();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &filtermax_)));
} else {
goto handle_unusual;
}
break;
}
// optional bool isNoFilter = 4;
case 4: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(32u /* 32 & 0xFF */)) {
set_has_isnofilter();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &isnofilter_)));
} else {
goto handle_unusual;
}
break;
}
// optional int32 sortDir = 5;
case 5: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) {
set_has_sortdir();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &sortdir_)));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:Qot_StockFilter.BaseFilter)
return true;
failure:
// @@protoc_insertion_point(parse_failure:Qot_StockFilter.BaseFilter)
return false;
#undef DO_
}
void BaseFilter::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:Qot_StockFilter.BaseFilter)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// required int32 field = 1;
if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->field(), output);
}
// optional double filterMin = 2;
if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->filtermin(), output);
}
// optional double filterMax = 3;
if (cached_has_bits & 0x00000008u) {
::google::protobuf::internal::WireFormatLite::WriteDouble(3, this->filtermax(), output);
}
// optional bool isNoFilter = 4;
if (cached_has_bits & 0x00000004u) {
::google::protobuf::internal::WireFormatLite::WriteBool(4, this->isnofilter(), output);
}
// optional int32 sortDir = 5;
if (cached_has_bits & 0x00000010u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(5, this->sortdir(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:Qot_StockFilter.BaseFilter)
}
::google::protobuf::uint8* BaseFilter::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:Qot_StockFilter.BaseFilter)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// required int32 field = 1;
if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->field(), target);
}
// optional double filterMin = 2;
if (cached_has_bits & 0x00000001u) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->filtermin(), target);
}
// optional double filterMax = 3;
if (cached_has_bits & 0x00000008u) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(3, this->filtermax(), target);
}
// optional bool isNoFilter = 4;
if (cached_has_bits & 0x00000004u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(4, this->isnofilter(), target);
}
// optional int32 sortDir = 5;
if (cached_has_bits & 0x00000010u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(5, this->sortdir(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:Qot_StockFilter.BaseFilter)
return target;
}
size_t BaseFilter::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:Qot_StockFilter.BaseFilter)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
// required int32 field = 1;
if (has_field()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->field());
}
// optional double filterMin = 2;
if (has_filtermin()) {
total_size += 1 + 8;
}
if (_has_bits_[0 / 32] & 28u) {
// optional bool isNoFilter = 4;
if (has_isnofilter()) {
total_size += 1 + 1;
}
// optional double filterMax = 3;
if (has_filtermax()) {
total_size += 1 + 8;
}
// optional int32 sortDir = 5;
if (has_sortdir()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->sortdir());
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void BaseFilter::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:Qot_StockFilter.BaseFilter)
GOOGLE_DCHECK_NE(&from, this);
const BaseFilter* source =
::google::protobuf::internal::DynamicCastToGenerated<const BaseFilter>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:Qot_StockFilter.BaseFilter)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:Qot_StockFilter.BaseFilter)
MergeFrom(*source);
}
}
void BaseFilter::MergeFrom(const BaseFilter& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:Qot_StockFilter.BaseFilter)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = from._has_bits_[0];
if (cached_has_bits & 31u) {
if (cached_has_bits & 0x00000001u) {
filtermin_ = from.filtermin_;
}
if (cached_has_bits & 0x00000002u) {
field_ = from.field_;
}
if (cached_has_bits & 0x00000004u) {
isnofilter_ = from.isnofilter_;
}
if (cached_has_bits & 0x00000008u) {
filtermax_ = from.filtermax_;
}
if (cached_has_bits & 0x00000010u) {
sortdir_ = from.sortdir_;
}
_has_bits_[0] |= cached_has_bits;
}
}
void BaseFilter::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:Qot_StockFilter.BaseFilter)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void BaseFilter::CopyFrom(const BaseFilter& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:Qot_StockFilter.BaseFilter)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool BaseFilter::IsInitialized() const {
if ((_has_bits_[0] & 0x00000002) != 0x00000002) return false;
return true;
}
void BaseFilter::Swap(BaseFilter* other) {
if (other == this) return;
InternalSwap(other);
}
void BaseFilter::InternalSwap(BaseFilter* other) {
using std::swap;
swap(filtermin_, other->filtermin_);
swap(field_, other->field_);
swap(isnofilter_, other->isnofilter_);
swap(filtermax_, other->filtermax_);
swap(sortdir_, other->sortdir_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata BaseFilter::GetMetadata() const {
protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages];
}
// ===================================================================
void AccumulateFilter::InitAsDefaultInstance() {
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int AccumulateFilter::kFieldFieldNumber;
const int AccumulateFilter::kFilterMinFieldNumber;
const int AccumulateFilter::kFilterMaxFieldNumber;
const int AccumulateFilter::kIsNoFilterFieldNumber;
const int AccumulateFilter::kSortDirFieldNumber;
const int AccumulateFilter::kDaysFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
AccumulateFilter::AccumulateFilter()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsAccumulateFilter();
}
SharedCtor();
// @@protoc_insertion_point(constructor:Qot_StockFilter.AccumulateFilter)
}
AccumulateFilter::AccumulateFilter(const AccumulateFilter& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
::memcpy(&filtermin_, &from.filtermin_,
static_cast<size_t>(reinterpret_cast<char*>(&days_) -
reinterpret_cast<char*>(&filtermin_)) + sizeof(days_));
// @@protoc_insertion_point(copy_constructor:Qot_StockFilter.AccumulateFilter)
}
void AccumulateFilter::SharedCtor() {
_cached_size_ = 0;
::memset(&filtermin_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&days_) -
reinterpret_cast<char*>(&filtermin_)) + sizeof(days_));
}
AccumulateFilter::~AccumulateFilter() {
// @@protoc_insertion_point(destructor:Qot_StockFilter.AccumulateFilter)
SharedDtor();
}
void AccumulateFilter::SharedDtor() {
}
void AccumulateFilter::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* AccumulateFilter::descriptor() {
::protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const AccumulateFilter& AccumulateFilter::default_instance() {
::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsAccumulateFilter();
return *internal_default_instance();
}
AccumulateFilter* AccumulateFilter::New(::google::protobuf::Arena* arena) const {
AccumulateFilter* n = new AccumulateFilter;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void AccumulateFilter::Clear() {
// @@protoc_insertion_point(message_clear_start:Qot_StockFilter.AccumulateFilter)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 63u) {
::memset(&filtermin_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&days_) -
reinterpret_cast<char*>(&filtermin_)) + sizeof(days_));
}
_has_bits_.Clear();
_internal_metadata_.Clear();
}
bool AccumulateFilter::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:Qot_StockFilter.AccumulateFilter)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// required int32 field = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
set_has_field();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &field_)));
} else {
goto handle_unusual;
}
break;
}
// optional double filterMin = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(17u /* 17 & 0xFF */)) {
set_has_filtermin();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &filtermin_)));
} else {
goto handle_unusual;
}
break;
}
// optional double filterMax = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(25u /* 25 & 0xFF */)) {
set_has_filtermax();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &filtermax_)));
} else {
goto handle_unusual;
}
break;
}
// optional bool isNoFilter = 4;
case 4: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(32u /* 32 & 0xFF */)) {
set_has_isnofilter();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &isnofilter_)));
} else {
goto handle_unusual;
}
break;
}
// optional int32 sortDir = 5;
case 5: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) {
set_has_sortdir();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &sortdir_)));
} else {
goto handle_unusual;
}
break;
}
// required int32 days = 6;
case 6: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(48u /* 48 & 0xFF */)) {
set_has_days();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &days_)));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:Qot_StockFilter.AccumulateFilter)
return true;
failure:
// @@protoc_insertion_point(parse_failure:Qot_StockFilter.AccumulateFilter)
return false;
#undef DO_
}
void AccumulateFilter::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:Qot_StockFilter.AccumulateFilter)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// required int32 field = 1;
if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->field(), output);
}
// optional double filterMin = 2;
if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->filtermin(), output);
}
// optional double filterMax = 3;
if (cached_has_bits & 0x00000008u) {
::google::protobuf::internal::WireFormatLite::WriteDouble(3, this->filtermax(), output);
}
// optional bool isNoFilter = 4;
if (cached_has_bits & 0x00000004u) {
::google::protobuf::internal::WireFormatLite::WriteBool(4, this->isnofilter(), output);
}
// optional int32 sortDir = 5;
if (cached_has_bits & 0x00000010u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(5, this->sortdir(), output);
}
// required int32 days = 6;
if (cached_has_bits & 0x00000020u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(6, this->days(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:Qot_StockFilter.AccumulateFilter)
}
::google::protobuf::uint8* AccumulateFilter::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:Qot_StockFilter.AccumulateFilter)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// required int32 field = 1;
if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->field(), target);
}
// optional double filterMin = 2;
if (cached_has_bits & 0x00000001u) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->filtermin(), target);
}
// optional double filterMax = 3;
if (cached_has_bits & 0x00000008u) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(3, this->filtermax(), target);
}
// optional bool isNoFilter = 4;
if (cached_has_bits & 0x00000004u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(4, this->isnofilter(), target);
}
// optional int32 sortDir = 5;
if (cached_has_bits & 0x00000010u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(5, this->sortdir(), target);
}
// required int32 days = 6;
if (cached_has_bits & 0x00000020u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(6, this->days(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:Qot_StockFilter.AccumulateFilter)
return target;
}
size_t AccumulateFilter::RequiredFieldsByteSizeFallback() const {
// @@protoc_insertion_point(required_fields_byte_size_fallback_start:Qot_StockFilter.AccumulateFilter)
size_t total_size = 0;
if (has_field()) {
// required int32 field = 1;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->field());
}
if (has_days()) {
// required int32 days = 6;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->days());
}
return total_size;
}
size_t AccumulateFilter::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:Qot_StockFilter.AccumulateFilter)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
if (((_has_bits_[0] & 0x00000022) ^ 0x00000022) == 0) { // All required fields are present.
// required int32 field = 1;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->field());
// required int32 days = 6;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->days());
} else {
total_size += RequiredFieldsByteSizeFallback();
}
// optional double filterMin = 2;
if (has_filtermin()) {
total_size += 1 + 8;
}
if (_has_bits_[0 / 32] & 28u) {
// optional bool isNoFilter = 4;
if (has_isnofilter()) {
total_size += 1 + 1;
}
// optional double filterMax = 3;
if (has_filtermax()) {
total_size += 1 + 8;
}
// optional int32 sortDir = 5;
if (has_sortdir()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->sortdir());
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void AccumulateFilter::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:Qot_StockFilter.AccumulateFilter)
GOOGLE_DCHECK_NE(&from, this);
const AccumulateFilter* source =
::google::protobuf::internal::DynamicCastToGenerated<const AccumulateFilter>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:Qot_StockFilter.AccumulateFilter)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:Qot_StockFilter.AccumulateFilter)
MergeFrom(*source);
}
}
void AccumulateFilter::MergeFrom(const AccumulateFilter& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:Qot_StockFilter.AccumulateFilter)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = from._has_bits_[0];
if (cached_has_bits & 63u) {
if (cached_has_bits & 0x00000001u) {
filtermin_ = from.filtermin_;
}
if (cached_has_bits & 0x00000002u) {
field_ = from.field_;
}
if (cached_has_bits & 0x00000004u) {
isnofilter_ = from.isnofilter_;
}
if (cached_has_bits & 0x00000008u) {
filtermax_ = from.filtermax_;
}
if (cached_has_bits & 0x00000010u) {
sortdir_ = from.sortdir_;
}
if (cached_has_bits & 0x00000020u) {
days_ = from.days_;
}
_has_bits_[0] |= cached_has_bits;
}
}
void AccumulateFilter::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:Qot_StockFilter.AccumulateFilter)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void AccumulateFilter::CopyFrom(const AccumulateFilter& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:Qot_StockFilter.AccumulateFilter)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool AccumulateFilter::IsInitialized() const {
if ((_has_bits_[0] & 0x00000022) != 0x00000022) return false;
return true;
}
void AccumulateFilter::Swap(AccumulateFilter* other) {
if (other == this) return;
InternalSwap(other);
}
void AccumulateFilter::InternalSwap(AccumulateFilter* other) {
using std::swap;
swap(filtermin_, other->filtermin_);
swap(field_, other->field_);
swap(isnofilter_, other->isnofilter_);
swap(filtermax_, other->filtermax_);
swap(sortdir_, other->sortdir_);
swap(days_, other->days_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata AccumulateFilter::GetMetadata() const {
protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages];
}
// ===================================================================
void FinancialFilter::InitAsDefaultInstance() {
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int FinancialFilter::kFieldFieldNumber;
const int FinancialFilter::kFilterMinFieldNumber;
const int FinancialFilter::kFilterMaxFieldNumber;
const int FinancialFilter::kIsNoFilterFieldNumber;
const int FinancialFilter::kSortDirFieldNumber;
const int FinancialFilter::kQuarterFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
FinancialFilter::FinancialFilter()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsFinancialFilter();
}
SharedCtor();
// @@protoc_insertion_point(constructor:Qot_StockFilter.FinancialFilter)
}
FinancialFilter::FinancialFilter(const FinancialFilter& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
::memcpy(&filtermin_, &from.filtermin_,
static_cast<size_t>(reinterpret_cast<char*>(&quarter_) -
reinterpret_cast<char*>(&filtermin_)) + sizeof(quarter_));
// @@protoc_insertion_point(copy_constructor:Qot_StockFilter.FinancialFilter)
}
void FinancialFilter::SharedCtor() {
_cached_size_ = 0;
::memset(&filtermin_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&quarter_) -
reinterpret_cast<char*>(&filtermin_)) + sizeof(quarter_));
}
FinancialFilter::~FinancialFilter() {
// @@protoc_insertion_point(destructor:Qot_StockFilter.FinancialFilter)
SharedDtor();
}
void FinancialFilter::SharedDtor() {
}
void FinancialFilter::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* FinancialFilter::descriptor() {
::protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const FinancialFilter& FinancialFilter::default_instance() {
::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsFinancialFilter();
return *internal_default_instance();
}
FinancialFilter* FinancialFilter::New(::google::protobuf::Arena* arena) const {
FinancialFilter* n = new FinancialFilter;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void FinancialFilter::Clear() {
// @@protoc_insertion_point(message_clear_start:Qot_StockFilter.FinancialFilter)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 63u) {
::memset(&filtermin_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&quarter_) -
reinterpret_cast<char*>(&filtermin_)) + sizeof(quarter_));
}
_has_bits_.Clear();
_internal_metadata_.Clear();
}
bool FinancialFilter::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:Qot_StockFilter.FinancialFilter)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// required int32 field = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
set_has_field();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &field_)));
} else {
goto handle_unusual;
}
break;
}
// optional double filterMin = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(17u /* 17 & 0xFF */)) {
set_has_filtermin();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &filtermin_)));
} else {
goto handle_unusual;
}
break;
}
// optional double filterMax = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(25u /* 25 & 0xFF */)) {
set_has_filtermax();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &filtermax_)));
} else {
goto handle_unusual;
}
break;
}
// optional bool isNoFilter = 4;
case 4: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(32u /* 32 & 0xFF */)) {
set_has_isnofilter();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &isnofilter_)));
} else {
goto handle_unusual;
}
break;
}
// optional int32 sortDir = 5;
case 5: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) {
set_has_sortdir();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &sortdir_)));
} else {
goto handle_unusual;
}
break;
}
// required int32 quarter = 6;
case 6: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(48u /* 48 & 0xFF */)) {
set_has_quarter();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &quarter_)));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:Qot_StockFilter.FinancialFilter)
return true;
failure:
// @@protoc_insertion_point(parse_failure:Qot_StockFilter.FinancialFilter)
return false;
#undef DO_
}
void FinancialFilter::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:Qot_StockFilter.FinancialFilter)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// required int32 field = 1;
if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->field(), output);
}
// optional double filterMin = 2;
if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->filtermin(), output);
}
// optional double filterMax = 3;
if (cached_has_bits & 0x00000008u) {
::google::protobuf::internal::WireFormatLite::WriteDouble(3, this->filtermax(), output);
}
// optional bool isNoFilter = 4;
if (cached_has_bits & 0x00000004u) {
::google::protobuf::internal::WireFormatLite::WriteBool(4, this->isnofilter(), output);
}
// optional int32 sortDir = 5;
if (cached_has_bits & 0x00000010u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(5, this->sortdir(), output);
}
// required int32 quarter = 6;
if (cached_has_bits & 0x00000020u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(6, this->quarter(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:Qot_StockFilter.FinancialFilter)
}
::google::protobuf::uint8* FinancialFilter::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:Qot_StockFilter.FinancialFilter)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// required int32 field = 1;
if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->field(), target);
}
// optional double filterMin = 2;
if (cached_has_bits & 0x00000001u) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->filtermin(), target);
}
// optional double filterMax = 3;
if (cached_has_bits & 0x00000008u) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(3, this->filtermax(), target);
}
// optional bool isNoFilter = 4;
if (cached_has_bits & 0x00000004u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(4, this->isnofilter(), target);
}
// optional int32 sortDir = 5;
if (cached_has_bits & 0x00000010u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(5, this->sortdir(), target);
}
// required int32 quarter = 6;
if (cached_has_bits & 0x00000020u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(6, this->quarter(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:Qot_StockFilter.FinancialFilter)
return target;
}
size_t FinancialFilter::RequiredFieldsByteSizeFallback() const {
// @@protoc_insertion_point(required_fields_byte_size_fallback_start:Qot_StockFilter.FinancialFilter)
size_t total_size = 0;
if (has_field()) {
// required int32 field = 1;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->field());
}
if (has_quarter()) {
// required int32 quarter = 6;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->quarter());
}
return total_size;
}
size_t FinancialFilter::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:Qot_StockFilter.FinancialFilter)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
if (((_has_bits_[0] & 0x00000022) ^ 0x00000022) == 0) { // All required fields are present.
// required int32 field = 1;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->field());
// required int32 quarter = 6;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->quarter());
} else {
total_size += RequiredFieldsByteSizeFallback();
}
// optional double filterMin = 2;
if (has_filtermin()) {
total_size += 1 + 8;
}
if (_has_bits_[0 / 32] & 28u) {
// optional bool isNoFilter = 4;
if (has_isnofilter()) {
total_size += 1 + 1;
}
// optional double filterMax = 3;
if (has_filtermax()) {
total_size += 1 + 8;
}
// optional int32 sortDir = 5;
if (has_sortdir()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->sortdir());
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void FinancialFilter::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:Qot_StockFilter.FinancialFilter)
GOOGLE_DCHECK_NE(&from, this);
const FinancialFilter* source =
::google::protobuf::internal::DynamicCastToGenerated<const FinancialFilter>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:Qot_StockFilter.FinancialFilter)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:Qot_StockFilter.FinancialFilter)
MergeFrom(*source);
}
}
void FinancialFilter::MergeFrom(const FinancialFilter& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:Qot_StockFilter.FinancialFilter)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = from._has_bits_[0];
if (cached_has_bits & 63u) {
if (cached_has_bits & 0x00000001u) {
filtermin_ = from.filtermin_;
}
if (cached_has_bits & 0x00000002u) {
field_ = from.field_;
}
if (cached_has_bits & 0x00000004u) {
isnofilter_ = from.isnofilter_;
}
if (cached_has_bits & 0x00000008u) {
filtermax_ = from.filtermax_;
}
if (cached_has_bits & 0x00000010u) {
sortdir_ = from.sortdir_;
}
if (cached_has_bits & 0x00000020u) {
quarter_ = from.quarter_;
}
_has_bits_[0] |= cached_has_bits;
}
}
void FinancialFilter::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:Qot_StockFilter.FinancialFilter)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void FinancialFilter::CopyFrom(const FinancialFilter& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:Qot_StockFilter.FinancialFilter)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool FinancialFilter::IsInitialized() const {
if ((_has_bits_[0] & 0x00000022) != 0x00000022) return false;
return true;
}
void FinancialFilter::Swap(FinancialFilter* other) {
if (other == this) return;
InternalSwap(other);
}
void FinancialFilter::InternalSwap(FinancialFilter* other) {
using std::swap;
swap(filtermin_, other->filtermin_);
swap(field_, other->field_);
swap(isnofilter_, other->isnofilter_);
swap(filtermax_, other->filtermax_);
swap(sortdir_, other->sortdir_);
swap(quarter_, other->quarter_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata FinancialFilter::GetMetadata() const {
protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages];
}
// ===================================================================
void BaseData::InitAsDefaultInstance() {
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int BaseData::kFieldFieldNumber;
const int BaseData::kValueFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
BaseData::BaseData()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsBaseData();
}
SharedCtor();
// @@protoc_insertion_point(constructor:Qot_StockFilter.BaseData)
}
BaseData::BaseData(const BaseData& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
::memcpy(&value_, &from.value_,
static_cast<size_t>(reinterpret_cast<char*>(&field_) -
reinterpret_cast<char*>(&value_)) + sizeof(field_));
// @@protoc_insertion_point(copy_constructor:Qot_StockFilter.BaseData)
}
void BaseData::SharedCtor() {
_cached_size_ = 0;
::memset(&value_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&field_) -
reinterpret_cast<char*>(&value_)) + sizeof(field_));
}
BaseData::~BaseData() {
// @@protoc_insertion_point(destructor:Qot_StockFilter.BaseData)
SharedDtor();
}
void BaseData::SharedDtor() {
}
void BaseData::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* BaseData::descriptor() {
::protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const BaseData& BaseData::default_instance() {
::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsBaseData();
return *internal_default_instance();
}
BaseData* BaseData::New(::google::protobuf::Arena* arena) const {
BaseData* n = new BaseData;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void BaseData::Clear() {
// @@protoc_insertion_point(message_clear_start:Qot_StockFilter.BaseData)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 3u) {
::memset(&value_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&field_) -
reinterpret_cast<char*>(&value_)) + sizeof(field_));
}
_has_bits_.Clear();
_internal_metadata_.Clear();
}
bool BaseData::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:Qot_StockFilter.BaseData)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// required int32 field = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
set_has_field();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &field_)));
} else {
goto handle_unusual;
}
break;
}
// required double value = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(17u /* 17 & 0xFF */)) {
set_has_value();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &value_)));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:Qot_StockFilter.BaseData)
return true;
failure:
// @@protoc_insertion_point(parse_failure:Qot_StockFilter.BaseData)
return false;
#undef DO_
}
void BaseData::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:Qot_StockFilter.BaseData)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// required int32 field = 1;
if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->field(), output);
}
// required double value = 2;
if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->value(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:Qot_StockFilter.BaseData)
}
::google::protobuf::uint8* BaseData::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:Qot_StockFilter.BaseData)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// required int32 field = 1;
if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->field(), target);
}
// required double value = 2;
if (cached_has_bits & 0x00000001u) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->value(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:Qot_StockFilter.BaseData)
return target;
}
size_t BaseData::RequiredFieldsByteSizeFallback() const {
// @@protoc_insertion_point(required_fields_byte_size_fallback_start:Qot_StockFilter.BaseData)
size_t total_size = 0;
if (has_value()) {
// required double value = 2;
total_size += 1 + 8;
}
if (has_field()) {
// required int32 field = 1;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->field());
}
return total_size;
}
size_t BaseData::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:Qot_StockFilter.BaseData)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
if (((_has_bits_[0] & 0x00000003) ^ 0x00000003) == 0) { // All required fields are present.
// required double value = 2;
total_size += 1 + 8;
// required int32 field = 1;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->field());
} else {
total_size += RequiredFieldsByteSizeFallback();
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void BaseData::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:Qot_StockFilter.BaseData)
GOOGLE_DCHECK_NE(&from, this);
const BaseData* source =
::google::protobuf::internal::DynamicCastToGenerated<const BaseData>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:Qot_StockFilter.BaseData)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:Qot_StockFilter.BaseData)
MergeFrom(*source);
}
}
void BaseData::MergeFrom(const BaseData& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:Qot_StockFilter.BaseData)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = from._has_bits_[0];
if (cached_has_bits & 3u) {
if (cached_has_bits & 0x00000001u) {
value_ = from.value_;
}
if (cached_has_bits & 0x00000002u) {
field_ = from.field_;
}
_has_bits_[0] |= cached_has_bits;
}
}
void BaseData::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:Qot_StockFilter.BaseData)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void BaseData::CopyFrom(const BaseData& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:Qot_StockFilter.BaseData)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool BaseData::IsInitialized() const {
if ((_has_bits_[0] & 0x00000003) != 0x00000003) return false;
return true;
}
void BaseData::Swap(BaseData* other) {
if (other == this) return;
InternalSwap(other);
}
void BaseData::InternalSwap(BaseData* other) {
using std::swap;
swap(value_, other->value_);
swap(field_, other->field_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata BaseData::GetMetadata() const {
protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages];
}
// ===================================================================
void AccumulateData::InitAsDefaultInstance() {
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int AccumulateData::kFieldFieldNumber;
const int AccumulateData::kValueFieldNumber;
const int AccumulateData::kDaysFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
AccumulateData::AccumulateData()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsAccumulateData();
}
SharedCtor();
// @@protoc_insertion_point(constructor:Qot_StockFilter.AccumulateData)
}
AccumulateData::AccumulateData(const AccumulateData& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
::memcpy(&value_, &from.value_,
static_cast<size_t>(reinterpret_cast<char*>(&days_) -
reinterpret_cast<char*>(&value_)) + sizeof(days_));
// @@protoc_insertion_point(copy_constructor:Qot_StockFilter.AccumulateData)
}
void AccumulateData::SharedCtor() {
_cached_size_ = 0;
::memset(&value_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&days_) -
reinterpret_cast<char*>(&value_)) + sizeof(days_));
}
AccumulateData::~AccumulateData() {
// @@protoc_insertion_point(destructor:Qot_StockFilter.AccumulateData)
SharedDtor();
}
void AccumulateData::SharedDtor() {
}
void AccumulateData::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* AccumulateData::descriptor() {
::protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const AccumulateData& AccumulateData::default_instance() {
::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsAccumulateData();
return *internal_default_instance();
}
AccumulateData* AccumulateData::New(::google::protobuf::Arena* arena) const {
AccumulateData* n = new AccumulateData;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void AccumulateData::Clear() {
// @@protoc_insertion_point(message_clear_start:Qot_StockFilter.AccumulateData)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 7u) {
::memset(&value_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&days_) -
reinterpret_cast<char*>(&value_)) + sizeof(days_));
}
_has_bits_.Clear();
_internal_metadata_.Clear();
}
bool AccumulateData::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:Qot_StockFilter.AccumulateData)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// required int32 field = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
set_has_field();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &field_)));
} else {
goto handle_unusual;
}
break;
}
// required double value = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(17u /* 17 & 0xFF */)) {
set_has_value();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &value_)));
} else {
goto handle_unusual;
}
break;
}
// required int32 days = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) {
set_has_days();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &days_)));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:Qot_StockFilter.AccumulateData)
return true;
failure:
// @@protoc_insertion_point(parse_failure:Qot_StockFilter.AccumulateData)
return false;
#undef DO_
}
void AccumulateData::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:Qot_StockFilter.AccumulateData)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// required int32 field = 1;
if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->field(), output);
}
// required double value = 2;
if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->value(), output);
}
// required int32 days = 3;
if (cached_has_bits & 0x00000004u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(3, this->days(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:Qot_StockFilter.AccumulateData)
}
::google::protobuf::uint8* AccumulateData::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:Qot_StockFilter.AccumulateData)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// required int32 field = 1;
if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->field(), target);
}
// required double value = 2;
if (cached_has_bits & 0x00000001u) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->value(), target);
}
// required int32 days = 3;
if (cached_has_bits & 0x00000004u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(3, this->days(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:Qot_StockFilter.AccumulateData)
return target;
}
size_t AccumulateData::RequiredFieldsByteSizeFallback() const {
// @@protoc_insertion_point(required_fields_byte_size_fallback_start:Qot_StockFilter.AccumulateData)
size_t total_size = 0;
if (has_value()) {
// required double value = 2;
total_size += 1 + 8;
}
if (has_field()) {
// required int32 field = 1;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->field());
}
if (has_days()) {
// required int32 days = 3;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->days());
}
return total_size;
}
size_t AccumulateData::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:Qot_StockFilter.AccumulateData)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
if (((_has_bits_[0] & 0x00000007) ^ 0x00000007) == 0) { // All required fields are present.
// required double value = 2;
total_size += 1 + 8;
// required int32 field = 1;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->field());
// required int32 days = 3;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->days());
} else {
total_size += RequiredFieldsByteSizeFallback();
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void AccumulateData::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:Qot_StockFilter.AccumulateData)
GOOGLE_DCHECK_NE(&from, this);
const AccumulateData* source =
::google::protobuf::internal::DynamicCastToGenerated<const AccumulateData>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:Qot_StockFilter.AccumulateData)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:Qot_StockFilter.AccumulateData)
MergeFrom(*source);
}
}
void AccumulateData::MergeFrom(const AccumulateData& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:Qot_StockFilter.AccumulateData)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = from._has_bits_[0];
if (cached_has_bits & 7u) {
if (cached_has_bits & 0x00000001u) {
value_ = from.value_;
}
if (cached_has_bits & 0x00000002u) {
field_ = from.field_;
}
if (cached_has_bits & 0x00000004u) {
days_ = from.days_;
}
_has_bits_[0] |= cached_has_bits;
}
}
void AccumulateData::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:Qot_StockFilter.AccumulateData)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void AccumulateData::CopyFrom(const AccumulateData& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:Qot_StockFilter.AccumulateData)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool AccumulateData::IsInitialized() const {
if ((_has_bits_[0] & 0x00000007) != 0x00000007) return false;
return true;
}
void AccumulateData::Swap(AccumulateData* other) {
if (other == this) return;
InternalSwap(other);
}
void AccumulateData::InternalSwap(AccumulateData* other) {
using std::swap;
swap(value_, other->value_);
swap(field_, other->field_);
swap(days_, other->days_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata AccumulateData::GetMetadata() const {
protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages];
}
// ===================================================================
void FinancialData::InitAsDefaultInstance() {
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int FinancialData::kFieldFieldNumber;
const int FinancialData::kValueFieldNumber;
const int FinancialData::kQuarterFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
FinancialData::FinancialData()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsFinancialData();
}
SharedCtor();
// @@protoc_insertion_point(constructor:Qot_StockFilter.FinancialData)
}
FinancialData::FinancialData(const FinancialData& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
::memcpy(&value_, &from.value_,
static_cast<size_t>(reinterpret_cast<char*>(&quarter_) -
reinterpret_cast<char*>(&value_)) + sizeof(quarter_));
// @@protoc_insertion_point(copy_constructor:Qot_StockFilter.FinancialData)
}
void FinancialData::SharedCtor() {
_cached_size_ = 0;
::memset(&value_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&quarter_) -
reinterpret_cast<char*>(&value_)) + sizeof(quarter_));
}
FinancialData::~FinancialData() {
// @@protoc_insertion_point(destructor:Qot_StockFilter.FinancialData)
SharedDtor();
}
void FinancialData::SharedDtor() {
}
void FinancialData::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* FinancialData::descriptor() {
::protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const FinancialData& FinancialData::default_instance() {
::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsFinancialData();
return *internal_default_instance();
}
FinancialData* FinancialData::New(::google::protobuf::Arena* arena) const {
FinancialData* n = new FinancialData;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void FinancialData::Clear() {
// @@protoc_insertion_point(message_clear_start:Qot_StockFilter.FinancialData)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 7u) {
::memset(&value_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&quarter_) -
reinterpret_cast<char*>(&value_)) + sizeof(quarter_));
}
_has_bits_.Clear();
_internal_metadata_.Clear();
}
bool FinancialData::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:Qot_StockFilter.FinancialData)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// required int32 field = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
set_has_field();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &field_)));
} else {
goto handle_unusual;
}
break;
}
// required double value = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(17u /* 17 & 0xFF */)) {
set_has_value();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &value_)));
} else {
goto handle_unusual;
}
break;
}
// required int32 quarter = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) {
set_has_quarter();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &quarter_)));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:Qot_StockFilter.FinancialData)
return true;
failure:
// @@protoc_insertion_point(parse_failure:Qot_StockFilter.FinancialData)
return false;
#undef DO_
}
void FinancialData::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:Qot_StockFilter.FinancialData)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// required int32 field = 1;
if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->field(), output);
}
// required double value = 2;
if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->value(), output);
}
// required int32 quarter = 3;
if (cached_has_bits & 0x00000004u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(3, this->quarter(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:Qot_StockFilter.FinancialData)
}
::google::protobuf::uint8* FinancialData::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:Qot_StockFilter.FinancialData)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// required int32 field = 1;
if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->field(), target);
}
// required double value = 2;
if (cached_has_bits & 0x00000001u) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->value(), target);
}
// required int32 quarter = 3;
if (cached_has_bits & 0x00000004u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(3, this->quarter(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:Qot_StockFilter.FinancialData)
return target;
}
size_t FinancialData::RequiredFieldsByteSizeFallback() const {
// @@protoc_insertion_point(required_fields_byte_size_fallback_start:Qot_StockFilter.FinancialData)
size_t total_size = 0;
if (has_value()) {
// required double value = 2;
total_size += 1 + 8;
}
if (has_field()) {
// required int32 field = 1;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->field());
}
if (has_quarter()) {
// required int32 quarter = 3;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->quarter());
}
return total_size;
}
size_t FinancialData::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:Qot_StockFilter.FinancialData)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
if (((_has_bits_[0] & 0x00000007) ^ 0x00000007) == 0) { // All required fields are present.
// required double value = 2;
total_size += 1 + 8;
// required int32 field = 1;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->field());
// required int32 quarter = 3;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->quarter());
} else {
total_size += RequiredFieldsByteSizeFallback();
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void FinancialData::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:Qot_StockFilter.FinancialData)
GOOGLE_DCHECK_NE(&from, this);
const FinancialData* source =
::google::protobuf::internal::DynamicCastToGenerated<const FinancialData>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:Qot_StockFilter.FinancialData)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:Qot_StockFilter.FinancialData)
MergeFrom(*source);
}
}
void FinancialData::MergeFrom(const FinancialData& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:Qot_StockFilter.FinancialData)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = from._has_bits_[0];
if (cached_has_bits & 7u) {
if (cached_has_bits & 0x00000001u) {
value_ = from.value_;
}
if (cached_has_bits & 0x00000002u) {
field_ = from.field_;
}
if (cached_has_bits & 0x00000004u) {
quarter_ = from.quarter_;
}
_has_bits_[0] |= cached_has_bits;
}
}
void FinancialData::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:Qot_StockFilter.FinancialData)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void FinancialData::CopyFrom(const FinancialData& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:Qot_StockFilter.FinancialData)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool FinancialData::IsInitialized() const {
if ((_has_bits_[0] & 0x00000007) != 0x00000007) return false;
return true;
}
void FinancialData::Swap(FinancialData* other) {
if (other == this) return;
InternalSwap(other);
}
void FinancialData::InternalSwap(FinancialData* other) {
using std::swap;
swap(value_, other->value_);
swap(field_, other->field_);
swap(quarter_, other->quarter_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata FinancialData::GetMetadata() const {
protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages];
}
// ===================================================================
void StockData::InitAsDefaultInstance() {
::Qot_StockFilter::_StockData_default_instance_._instance.get_mutable()->security_ = const_cast< ::Qot_Common::Security*>(
::Qot_Common::Security::internal_default_instance());
}
void StockData::clear_security() {
if (security_ != NULL) security_->Clear();
clear_has_security();
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int StockData::kSecurityFieldNumber;
const int StockData::kNameFieldNumber;
const int StockData::kBaseDataListFieldNumber;
const int StockData::kAccumulateDataListFieldNumber;
const int StockData::kFinancialDataListFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
StockData::StockData()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsStockData();
}
SharedCtor();
// @@protoc_insertion_point(constructor:Qot_StockFilter.StockData)
}
StockData::StockData(const StockData& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
_cached_size_(0),
basedatalist_(from.basedatalist_),
accumulatedatalist_(from.accumulatedatalist_),
financialdatalist_(from.financialdatalist_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_name()) {
name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
}
if (from.has_security()) {
security_ = new ::Qot_Common::Security(*from.security_);
} else {
security_ = NULL;
}
// @@protoc_insertion_point(copy_constructor:Qot_StockFilter.StockData)
}
void StockData::SharedCtor() {
_cached_size_ = 0;
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
security_ = NULL;
}
StockData::~StockData() {
// @@protoc_insertion_point(destructor:Qot_StockFilter.StockData)
SharedDtor();
}
void StockData::SharedDtor() {
name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (this != internal_default_instance()) delete security_;
}
void StockData::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* StockData::descriptor() {
::protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const StockData& StockData::default_instance() {
::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsStockData();
return *internal_default_instance();
}
StockData* StockData::New(::google::protobuf::Arena* arena) const {
StockData* n = new StockData;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void StockData::Clear() {
// @@protoc_insertion_point(message_clear_start:Qot_StockFilter.StockData)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
basedatalist_.Clear();
accumulatedatalist_.Clear();
financialdatalist_.Clear();
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 3u) {
if (cached_has_bits & 0x00000001u) {
GOOGLE_DCHECK(!name_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
(*name_.UnsafeRawStringPointer())->clear();
}
if (cached_has_bits & 0x00000002u) {
GOOGLE_DCHECK(security_ != NULL);
security_->Clear();
}
}
_has_bits_.Clear();
_internal_metadata_.Clear();
}
bool StockData::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:Qot_StockFilter.StockData)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// required .Qot_Common.Security security = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_security()));
} else {
goto handle_unusual;
}
break;
}
// required string name = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormat::PARSE,
"Qot_StockFilter.StockData.name");
} else {
goto handle_unusual;
}
break;
}
// repeated .Qot_StockFilter.BaseData baseDataList = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_basedatalist()));
} else {
goto handle_unusual;
}
break;
}
// repeated .Qot_StockFilter.AccumulateData accumulateDataList = 4;
case 4: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_accumulatedatalist()));
} else {
goto handle_unusual;
}
break;
}
// repeated .Qot_StockFilter.FinancialData financialDataList = 5;
case 5: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(42u /* 42 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_financialdatalist()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:Qot_StockFilter.StockData)
return true;
failure:
// @@protoc_insertion_point(parse_failure:Qot_StockFilter.StockData)
return false;
#undef DO_
}
void StockData::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:Qot_StockFilter.StockData)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// required .Qot_Common.Security security = 1;
if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *this->security_, output);
}
// required string name = 2;
if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"Qot_StockFilter.StockData.name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
2, this->name(), output);
}
// repeated .Qot_StockFilter.BaseData baseDataList = 3;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->basedatalist_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
3, this->basedatalist(static_cast<int>(i)), output);
}
// repeated .Qot_StockFilter.AccumulateData accumulateDataList = 4;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->accumulatedatalist_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
4, this->accumulatedatalist(static_cast<int>(i)), output);
}
// repeated .Qot_StockFilter.FinancialData financialDataList = 5;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->financialdatalist_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
5, this->financialdatalist(static_cast<int>(i)), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:Qot_StockFilter.StockData)
}
::google::protobuf::uint8* StockData::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:Qot_StockFilter.StockData)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// required .Qot_Common.Security security = 1;
if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
1, *this->security_, deterministic, target);
}
// required string name = 2;
if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->name().data(), static_cast<int>(this->name().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"Qot_StockFilter.StockData.name");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
2, this->name(), target);
}
// repeated .Qot_StockFilter.BaseData baseDataList = 3;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->basedatalist_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
3, this->basedatalist(static_cast<int>(i)), deterministic, target);
}
// repeated .Qot_StockFilter.AccumulateData accumulateDataList = 4;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->accumulatedatalist_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
4, this->accumulatedatalist(static_cast<int>(i)), deterministic, target);
}
// repeated .Qot_StockFilter.FinancialData financialDataList = 5;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->financialdatalist_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
5, this->financialdatalist(static_cast<int>(i)), deterministic, target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:Qot_StockFilter.StockData)
return target;
}
size_t StockData::RequiredFieldsByteSizeFallback() const {
// @@protoc_insertion_point(required_fields_byte_size_fallback_start:Qot_StockFilter.StockData)
size_t total_size = 0;
if (has_name()) {
// required string name = 2;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->name());
}
if (has_security()) {
// required .Qot_Common.Security security = 1;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*this->security_);
}
return total_size;
}
size_t StockData::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:Qot_StockFilter.StockData)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
if (((_has_bits_[0] & 0x00000003) ^ 0x00000003) == 0) { // All required fields are present.
// required string name = 2;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->name());
// required .Qot_Common.Security security = 1;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*this->security_);
} else {
total_size += RequiredFieldsByteSizeFallback();
}
// repeated .Qot_StockFilter.BaseData baseDataList = 3;
{
unsigned int count = static_cast<unsigned int>(this->basedatalist_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSize(
this->basedatalist(static_cast<int>(i)));
}
}
// repeated .Qot_StockFilter.AccumulateData accumulateDataList = 4;
{
unsigned int count = static_cast<unsigned int>(this->accumulatedatalist_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSize(
this->accumulatedatalist(static_cast<int>(i)));
}
}
// repeated .Qot_StockFilter.FinancialData financialDataList = 5;
{
unsigned int count = static_cast<unsigned int>(this->financialdatalist_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSize(
this->financialdatalist(static_cast<int>(i)));
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void StockData::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:Qot_StockFilter.StockData)
GOOGLE_DCHECK_NE(&from, this);
const StockData* source =
::google::protobuf::internal::DynamicCastToGenerated<const StockData>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:Qot_StockFilter.StockData)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:Qot_StockFilter.StockData)
MergeFrom(*source);
}
}
void StockData::MergeFrom(const StockData& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:Qot_StockFilter.StockData)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
basedatalist_.MergeFrom(from.basedatalist_);
accumulatedatalist_.MergeFrom(from.accumulatedatalist_);
financialdatalist_.MergeFrom(from.financialdatalist_);
cached_has_bits = from._has_bits_[0];
if (cached_has_bits & 3u) {
if (cached_has_bits & 0x00000001u) {
set_has_name();
name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
}
if (cached_has_bits & 0x00000002u) {
mutable_security()->::Qot_Common::Security::MergeFrom(from.security());
}
}
}
void StockData::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:Qot_StockFilter.StockData)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void StockData::CopyFrom(const StockData& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:Qot_StockFilter.StockData)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool StockData::IsInitialized() const {
if ((_has_bits_[0] & 0x00000003) != 0x00000003) return false;
if (!::google::protobuf::internal::AllAreInitialized(this->basedatalist())) return false;
if (!::google::protobuf::internal::AllAreInitialized(this->accumulatedatalist())) return false;
if (!::google::protobuf::internal::AllAreInitialized(this->financialdatalist())) return false;
if (has_security()) {
if (!this->security_->IsInitialized()) return false;
}
return true;
}
void StockData::Swap(StockData* other) {
if (other == this) return;
InternalSwap(other);
}
void StockData::InternalSwap(StockData* other) {
using std::swap;
basedatalist_.InternalSwap(&other->basedatalist_);
accumulatedatalist_.InternalSwap(&other->accumulatedatalist_);
financialdatalist_.InternalSwap(&other->financialdatalist_);
name_.Swap(&other->name_);
swap(security_, other->security_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata StockData::GetMetadata() const {
protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages];
}
// ===================================================================
void C2S::InitAsDefaultInstance() {
::Qot_StockFilter::_C2S_default_instance_._instance.get_mutable()->plate_ = const_cast< ::Qot_Common::Security*>(
::Qot_Common::Security::internal_default_instance());
}
void C2S::clear_plate() {
if (plate_ != NULL) plate_->Clear();
clear_has_plate();
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int C2S::kBeginFieldNumber;
const int C2S::kNumFieldNumber;
const int C2S::kMarketFieldNumber;
const int C2S::kPlateFieldNumber;
const int C2S::kBaseFilterListFieldNumber;
const int C2S::kAccumulateFilterListFieldNumber;
const int C2S::kFinancialFilterListFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
C2S::C2S()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsC2S();
}
SharedCtor();
// @@protoc_insertion_point(constructor:Qot_StockFilter.C2S)
}
C2S::C2S(const C2S& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
_cached_size_(0),
basefilterlist_(from.basefilterlist_),
accumulatefilterlist_(from.accumulatefilterlist_),
financialfilterlist_(from.financialfilterlist_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
if (from.has_plate()) {
plate_ = new ::Qot_Common::Security(*from.plate_);
} else {
plate_ = NULL;
}
::memcpy(&begin_, &from.begin_,
static_cast<size_t>(reinterpret_cast<char*>(&market_) -
reinterpret_cast<char*>(&begin_)) + sizeof(market_));
// @@protoc_insertion_point(copy_constructor:Qot_StockFilter.C2S)
}
void C2S::SharedCtor() {
_cached_size_ = 0;
::memset(&plate_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&market_) -
reinterpret_cast<char*>(&plate_)) + sizeof(market_));
}
C2S::~C2S() {
// @@protoc_insertion_point(destructor:Qot_StockFilter.C2S)
SharedDtor();
}
void C2S::SharedDtor() {
if (this != internal_default_instance()) delete plate_;
}
void C2S::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* C2S::descriptor() {
::protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const C2S& C2S::default_instance() {
::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsC2S();
return *internal_default_instance();
}
C2S* C2S::New(::google::protobuf::Arena* arena) const {
C2S* n = new C2S;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void C2S::Clear() {
// @@protoc_insertion_point(message_clear_start:Qot_StockFilter.C2S)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
basefilterlist_.Clear();
accumulatefilterlist_.Clear();
financialfilterlist_.Clear();
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 0x00000001u) {
GOOGLE_DCHECK(plate_ != NULL);
plate_->Clear();
}
if (cached_has_bits & 14u) {
::memset(&begin_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&market_) -
reinterpret_cast<char*>(&begin_)) + sizeof(market_));
}
_has_bits_.Clear();
_internal_metadata_.Clear();
}
bool C2S::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:Qot_StockFilter.C2S)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// required int32 begin = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
set_has_begin();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &begin_)));
} else {
goto handle_unusual;
}
break;
}
// required int32 num = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
set_has_num();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &num_)));
} else {
goto handle_unusual;
}
break;
}
// required int32 market = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) {
set_has_market();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &market_)));
} else {
goto handle_unusual;
}
break;
}
// optional .Qot_Common.Security plate = 4;
case 4: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_plate()));
} else {
goto handle_unusual;
}
break;
}
// repeated .Qot_StockFilter.BaseFilter baseFilterList = 5;
case 5: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(42u /* 42 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_basefilterlist()));
} else {
goto handle_unusual;
}
break;
}
// repeated .Qot_StockFilter.AccumulateFilter accumulateFilterList = 6;
case 6: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(50u /* 50 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_accumulatefilterlist()));
} else {
goto handle_unusual;
}
break;
}
// repeated .Qot_StockFilter.FinancialFilter financialFilterList = 7;
case 7: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(58u /* 58 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_financialfilterlist()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:Qot_StockFilter.C2S)
return true;
failure:
// @@protoc_insertion_point(parse_failure:Qot_StockFilter.C2S)
return false;
#undef DO_
}
void C2S::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:Qot_StockFilter.C2S)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// required int32 begin = 1;
if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->begin(), output);
}
// required int32 num = 2;
if (cached_has_bits & 0x00000004u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->num(), output);
}
// required int32 market = 3;
if (cached_has_bits & 0x00000008u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(3, this->market(), output);
}
// optional .Qot_Common.Security plate = 4;
if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
4, *this->plate_, output);
}
// repeated .Qot_StockFilter.BaseFilter baseFilterList = 5;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->basefilterlist_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
5, this->basefilterlist(static_cast<int>(i)), output);
}
// repeated .Qot_StockFilter.AccumulateFilter accumulateFilterList = 6;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->accumulatefilterlist_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
6, this->accumulatefilterlist(static_cast<int>(i)), output);
}
// repeated .Qot_StockFilter.FinancialFilter financialFilterList = 7;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->financialfilterlist_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
7, this->financialfilterlist(static_cast<int>(i)), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:Qot_StockFilter.C2S)
}
::google::protobuf::uint8* C2S::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:Qot_StockFilter.C2S)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// required int32 begin = 1;
if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->begin(), target);
}
// required int32 num = 2;
if (cached_has_bits & 0x00000004u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->num(), target);
}
// required int32 market = 3;
if (cached_has_bits & 0x00000008u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(3, this->market(), target);
}
// optional .Qot_Common.Security plate = 4;
if (cached_has_bits & 0x00000001u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
4, *this->plate_, deterministic, target);
}
// repeated .Qot_StockFilter.BaseFilter baseFilterList = 5;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->basefilterlist_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
5, this->basefilterlist(static_cast<int>(i)), deterministic, target);
}
// repeated .Qot_StockFilter.AccumulateFilter accumulateFilterList = 6;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->accumulatefilterlist_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
6, this->accumulatefilterlist(static_cast<int>(i)), deterministic, target);
}
// repeated .Qot_StockFilter.FinancialFilter financialFilterList = 7;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->financialfilterlist_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
7, this->financialfilterlist(static_cast<int>(i)), deterministic, target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:Qot_StockFilter.C2S)
return target;
}
size_t C2S::RequiredFieldsByteSizeFallback() const {
// @@protoc_insertion_point(required_fields_byte_size_fallback_start:Qot_StockFilter.C2S)
size_t total_size = 0;
if (has_begin()) {
// required int32 begin = 1;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->begin());
}
if (has_num()) {
// required int32 num = 2;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->num());
}
if (has_market()) {
// required int32 market = 3;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->market());
}
return total_size;
}
size_t C2S::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:Qot_StockFilter.C2S)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
if (((_has_bits_[0] & 0x0000000e) ^ 0x0000000e) == 0) { // All required fields are present.
// required int32 begin = 1;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->begin());
// required int32 num = 2;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->num());
// required int32 market = 3;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->market());
} else {
total_size += RequiredFieldsByteSizeFallback();
}
// repeated .Qot_StockFilter.BaseFilter baseFilterList = 5;
{
unsigned int count = static_cast<unsigned int>(this->basefilterlist_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSize(
this->basefilterlist(static_cast<int>(i)));
}
}
// repeated .Qot_StockFilter.AccumulateFilter accumulateFilterList = 6;
{
unsigned int count = static_cast<unsigned int>(this->accumulatefilterlist_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSize(
this->accumulatefilterlist(static_cast<int>(i)));
}
}
// repeated .Qot_StockFilter.FinancialFilter financialFilterList = 7;
{
unsigned int count = static_cast<unsigned int>(this->financialfilterlist_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSize(
this->financialfilterlist(static_cast<int>(i)));
}
}
// optional .Qot_Common.Security plate = 4;
if (has_plate()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*this->plate_);
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void C2S::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:Qot_StockFilter.C2S)
GOOGLE_DCHECK_NE(&from, this);
const C2S* source =
::google::protobuf::internal::DynamicCastToGenerated<const C2S>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:Qot_StockFilter.C2S)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:Qot_StockFilter.C2S)
MergeFrom(*source);
}
}
void C2S::MergeFrom(const C2S& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:Qot_StockFilter.C2S)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
basefilterlist_.MergeFrom(from.basefilterlist_);
accumulatefilterlist_.MergeFrom(from.accumulatefilterlist_);
financialfilterlist_.MergeFrom(from.financialfilterlist_);
cached_has_bits = from._has_bits_[0];
if (cached_has_bits & 15u) {
if (cached_has_bits & 0x00000001u) {
mutable_plate()->::Qot_Common::Security::MergeFrom(from.plate());
}
if (cached_has_bits & 0x00000002u) {
begin_ = from.begin_;
}
if (cached_has_bits & 0x00000004u) {
num_ = from.num_;
}
if (cached_has_bits & 0x00000008u) {
market_ = from.market_;
}
_has_bits_[0] |= cached_has_bits;
}
}
void C2S::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:Qot_StockFilter.C2S)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void C2S::CopyFrom(const C2S& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:Qot_StockFilter.C2S)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool C2S::IsInitialized() const {
if ((_has_bits_[0] & 0x0000000e) != 0x0000000e) return false;
if (!::google::protobuf::internal::AllAreInitialized(this->basefilterlist())) return false;
if (!::google::protobuf::internal::AllAreInitialized(this->accumulatefilterlist())) return false;
if (!::google::protobuf::internal::AllAreInitialized(this->financialfilterlist())) return false;
if (has_plate()) {
if (!this->plate_->IsInitialized()) return false;
}
return true;
}
void C2S::Swap(C2S* other) {
if (other == this) return;
InternalSwap(other);
}
void C2S::InternalSwap(C2S* other) {
using std::swap;
basefilterlist_.InternalSwap(&other->basefilterlist_);
accumulatefilterlist_.InternalSwap(&other->accumulatefilterlist_);
financialfilterlist_.InternalSwap(&other->financialfilterlist_);
swap(plate_, other->plate_);
swap(begin_, other->begin_);
swap(num_, other->num_);
swap(market_, other->market_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata C2S::GetMetadata() const {
protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages];
}
// ===================================================================
void S2C::InitAsDefaultInstance() {
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int S2C::kLastPageFieldNumber;
const int S2C::kAllCountFieldNumber;
const int S2C::kDataListFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
S2C::S2C()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsS2C();
}
SharedCtor();
// @@protoc_insertion_point(constructor:Qot_StockFilter.S2C)
}
S2C::S2C(const S2C& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
_cached_size_(0),
datalist_(from.datalist_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
::memcpy(&lastpage_, &from.lastpage_,
static_cast<size_t>(reinterpret_cast<char*>(&allcount_) -
reinterpret_cast<char*>(&lastpage_)) + sizeof(allcount_));
// @@protoc_insertion_point(copy_constructor:Qot_StockFilter.S2C)
}
void S2C::SharedCtor() {
_cached_size_ = 0;
::memset(&lastpage_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&allcount_) -
reinterpret_cast<char*>(&lastpage_)) + sizeof(allcount_));
}
S2C::~S2C() {
// @@protoc_insertion_point(destructor:Qot_StockFilter.S2C)
SharedDtor();
}
void S2C::SharedDtor() {
}
void S2C::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* S2C::descriptor() {
::protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const S2C& S2C::default_instance() {
::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsS2C();
return *internal_default_instance();
}
S2C* S2C::New(::google::protobuf::Arena* arena) const {
S2C* n = new S2C;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void S2C::Clear() {
// @@protoc_insertion_point(message_clear_start:Qot_StockFilter.S2C)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
datalist_.Clear();
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 3u) {
::memset(&lastpage_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&allcount_) -
reinterpret_cast<char*>(&lastpage_)) + sizeof(allcount_));
}
_has_bits_.Clear();
_internal_metadata_.Clear();
}
bool S2C::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:Qot_StockFilter.S2C)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// required bool lastPage = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
set_has_lastpage();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &lastpage_)));
} else {
goto handle_unusual;
}
break;
}
// required int32 allCount = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) {
set_has_allcount();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &allcount_)));
} else {
goto handle_unusual;
}
break;
}
// repeated .Qot_StockFilter.StockData dataList = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(input, add_datalist()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:Qot_StockFilter.S2C)
return true;
failure:
// @@protoc_insertion_point(parse_failure:Qot_StockFilter.S2C)
return false;
#undef DO_
}
void S2C::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:Qot_StockFilter.S2C)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// required bool lastPage = 1;
if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormatLite::WriteBool(1, this->lastpage(), output);
}
// required int32 allCount = 2;
if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->allcount(), output);
}
// repeated .Qot_StockFilter.StockData dataList = 3;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->datalist_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
3, this->datalist(static_cast<int>(i)), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:Qot_StockFilter.S2C)
}
::google::protobuf::uint8* S2C::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:Qot_StockFilter.S2C)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// required bool lastPage = 1;
if (cached_has_bits & 0x00000001u) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(1, this->lastpage(), target);
}
// required int32 allCount = 2;
if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->allcount(), target);
}
// repeated .Qot_StockFilter.StockData dataList = 3;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->datalist_size()); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
3, this->datalist(static_cast<int>(i)), deterministic, target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:Qot_StockFilter.S2C)
return target;
}
size_t S2C::RequiredFieldsByteSizeFallback() const {
// @@protoc_insertion_point(required_fields_byte_size_fallback_start:Qot_StockFilter.S2C)
size_t total_size = 0;
if (has_lastpage()) {
// required bool lastPage = 1;
total_size += 1 + 1;
}
if (has_allcount()) {
// required int32 allCount = 2;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->allcount());
}
return total_size;
}
size_t S2C::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:Qot_StockFilter.S2C)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
if (((_has_bits_[0] & 0x00000003) ^ 0x00000003) == 0) { // All required fields are present.
// required bool lastPage = 1;
total_size += 1 + 1;
// required int32 allCount = 2;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->allcount());
} else {
total_size += RequiredFieldsByteSizeFallback();
}
// repeated .Qot_StockFilter.StockData dataList = 3;
{
unsigned int count = static_cast<unsigned int>(this->datalist_size());
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSize(
this->datalist(static_cast<int>(i)));
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void S2C::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:Qot_StockFilter.S2C)
GOOGLE_DCHECK_NE(&from, this);
const S2C* source =
::google::protobuf::internal::DynamicCastToGenerated<const S2C>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:Qot_StockFilter.S2C)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:Qot_StockFilter.S2C)
MergeFrom(*source);
}
}
void S2C::MergeFrom(const S2C& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:Qot_StockFilter.S2C)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
datalist_.MergeFrom(from.datalist_);
cached_has_bits = from._has_bits_[0];
if (cached_has_bits & 3u) {
if (cached_has_bits & 0x00000001u) {
lastpage_ = from.lastpage_;
}
if (cached_has_bits & 0x00000002u) {
allcount_ = from.allcount_;
}
_has_bits_[0] |= cached_has_bits;
}
}
void S2C::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:Qot_StockFilter.S2C)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void S2C::CopyFrom(const S2C& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:Qot_StockFilter.S2C)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool S2C::IsInitialized() const {
if ((_has_bits_[0] & 0x00000003) != 0x00000003) return false;
if (!::google::protobuf::internal::AllAreInitialized(this->datalist())) return false;
return true;
}
void S2C::Swap(S2C* other) {
if (other == this) return;
InternalSwap(other);
}
void S2C::InternalSwap(S2C* other) {
using std::swap;
datalist_.InternalSwap(&other->datalist_);
swap(lastpage_, other->lastpage_);
swap(allcount_, other->allcount_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata S2C::GetMetadata() const {
protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages];
}
// ===================================================================
void Request::InitAsDefaultInstance() {
::Qot_StockFilter::_Request_default_instance_._instance.get_mutable()->c2s_ = const_cast< ::Qot_StockFilter::C2S*>(
::Qot_StockFilter::C2S::internal_default_instance());
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Request::kC2SFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
Request::Request()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsRequest();
}
SharedCtor();
// @@protoc_insertion_point(constructor:Qot_StockFilter.Request)
}
Request::Request(const Request& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
if (from.has_c2s()) {
c2s_ = new ::Qot_StockFilter::C2S(*from.c2s_);
} else {
c2s_ = NULL;
}
// @@protoc_insertion_point(copy_constructor:Qot_StockFilter.Request)
}
void Request::SharedCtor() {
_cached_size_ = 0;
c2s_ = NULL;
}
Request::~Request() {
// @@protoc_insertion_point(destructor:Qot_StockFilter.Request)
SharedDtor();
}
void Request::SharedDtor() {
if (this != internal_default_instance()) delete c2s_;
}
void Request::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* Request::descriptor() {
::protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const Request& Request::default_instance() {
::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsRequest();
return *internal_default_instance();
}
Request* Request::New(::google::protobuf::Arena* arena) const {
Request* n = new Request;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void Request::Clear() {
// @@protoc_insertion_point(message_clear_start:Qot_StockFilter.Request)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 0x00000001u) {
GOOGLE_DCHECK(c2s_ != NULL);
c2s_->Clear();
}
_has_bits_.Clear();
_internal_metadata_.Clear();
}
bool Request::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:Qot_StockFilter.Request)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// required .Qot_StockFilter.C2S c2s = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_c2s()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:Qot_StockFilter.Request)
return true;
failure:
// @@protoc_insertion_point(parse_failure:Qot_StockFilter.Request)
return false;
#undef DO_
}
void Request::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:Qot_StockFilter.Request)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// required .Qot_StockFilter.C2S c2s = 1;
if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *this->c2s_, output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:Qot_StockFilter.Request)
}
::google::protobuf::uint8* Request::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:Qot_StockFilter.Request)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// required .Qot_StockFilter.C2S c2s = 1;
if (cached_has_bits & 0x00000001u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
1, *this->c2s_, deterministic, target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:Qot_StockFilter.Request)
return target;
}
size_t Request::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:Qot_StockFilter.Request)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
// required .Qot_StockFilter.C2S c2s = 1;
if (has_c2s()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*this->c2s_);
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void Request::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:Qot_StockFilter.Request)
GOOGLE_DCHECK_NE(&from, this);
const Request* source =
::google::protobuf::internal::DynamicCastToGenerated<const Request>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:Qot_StockFilter.Request)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:Qot_StockFilter.Request)
MergeFrom(*source);
}
}
void Request::MergeFrom(const Request& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:Qot_StockFilter.Request)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
if (from.has_c2s()) {
mutable_c2s()->::Qot_StockFilter::C2S::MergeFrom(from.c2s());
}
}
void Request::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:Qot_StockFilter.Request)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void Request::CopyFrom(const Request& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:Qot_StockFilter.Request)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool Request::IsInitialized() const {
if ((_has_bits_[0] & 0x00000001) != 0x00000001) return false;
if (has_c2s()) {
if (!this->c2s_->IsInitialized()) return false;
}
return true;
}
void Request::Swap(Request* other) {
if (other == this) return;
InternalSwap(other);
}
void Request::InternalSwap(Request* other) {
using std::swap;
swap(c2s_, other->c2s_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Request::GetMetadata() const {
protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages];
}
// ===================================================================
void Response::InitAsDefaultInstance() {
::Qot_StockFilter::_Response_default_instance_._instance.get_mutable()->s2c_ = const_cast< ::Qot_StockFilter::S2C*>(
::Qot_StockFilter::S2C::internal_default_instance());
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Response::kRetTypeFieldNumber;
const int Response::kRetMsgFieldNumber;
const int Response::kErrCodeFieldNumber;
const int Response::kS2CFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
Response::Response()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsResponse();
}
SharedCtor();
// @@protoc_insertion_point(constructor:Qot_StockFilter.Response)
}
Response::Response(const Response& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_has_bits_(from._has_bits_),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
retmsg_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.has_retmsg()) {
retmsg_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.retmsg_);
}
if (from.has_s2c()) {
s2c_ = new ::Qot_StockFilter::S2C(*from.s2c_);
} else {
s2c_ = NULL;
}
::memcpy(&errcode_, &from.errcode_,
static_cast<size_t>(reinterpret_cast<char*>(&rettype_) -
reinterpret_cast<char*>(&errcode_)) + sizeof(rettype_));
// @@protoc_insertion_point(copy_constructor:Qot_StockFilter.Response)
}
void Response::SharedCtor() {
_cached_size_ = 0;
retmsg_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
::memset(&s2c_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&errcode_) -
reinterpret_cast<char*>(&s2c_)) + sizeof(errcode_));
rettype_ = -400;
}
Response::~Response() {
// @@protoc_insertion_point(destructor:Qot_StockFilter.Response)
SharedDtor();
}
void Response::SharedDtor() {
retmsg_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (this != internal_default_instance()) delete s2c_;
}
void Response::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* Response::descriptor() {
::protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const Response& Response::default_instance() {
::protobuf_Qot_5fStockFilter_2eproto::InitDefaultsResponse();
return *internal_default_instance();
}
Response* Response::New(::google::protobuf::Arena* arena) const {
Response* n = new Response;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void Response::Clear() {
// @@protoc_insertion_point(message_clear_start:Qot_StockFilter.Response)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
if (cached_has_bits & 3u) {
if (cached_has_bits & 0x00000001u) {
GOOGLE_DCHECK(!retmsg_.IsDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()));
(*retmsg_.UnsafeRawStringPointer())->clear();
}
if (cached_has_bits & 0x00000002u) {
GOOGLE_DCHECK(s2c_ != NULL);
s2c_->Clear();
}
}
if (cached_has_bits & 12u) {
errcode_ = 0;
rettype_ = -400;
}
_has_bits_.Clear();
_internal_metadata_.Clear();
}
bool Response::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:Qot_StockFilter.Response)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// required int32 retType = 1 [default = -400];
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) {
set_has_rettype();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &rettype_)));
} else {
goto handle_unusual;
}
break;
}
// optional string retMsg = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_retmsg()));
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->retmsg().data(), static_cast<int>(this->retmsg().length()),
::google::protobuf::internal::WireFormat::PARSE,
"Qot_StockFilter.Response.retMsg");
} else {
goto handle_unusual;
}
break;
}
// optional int32 errCode = 3;
case 3: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) {
set_has_errcode();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &errcode_)));
} else {
goto handle_unusual;
}
break;
}
// optional .Qot_StockFilter.S2C s2c = 4;
case 4: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, mutable_s2c()));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:Qot_StockFilter.Response)
return true;
failure:
// @@protoc_insertion_point(parse_failure:Qot_StockFilter.Response)
return false;
#undef DO_
}
void Response::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:Qot_StockFilter.Response)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// required int32 retType = 1 [default = -400];
if (cached_has_bits & 0x00000008u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->rettype(), output);
}
// optional string retMsg = 2;
if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->retmsg().data(), static_cast<int>(this->retmsg().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"Qot_StockFilter.Response.retMsg");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
2, this->retmsg(), output);
}
// optional int32 errCode = 3;
if (cached_has_bits & 0x00000004u) {
::google::protobuf::internal::WireFormatLite::WriteInt32(3, this->errcode(), output);
}
// optional .Qot_StockFilter.S2C s2c = 4;
if (cached_has_bits & 0x00000002u) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
4, *this->s2c_, output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
_internal_metadata_.unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:Qot_StockFilter.Response)
}
::google::protobuf::uint8* Response::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:Qot_StockFilter.Response)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = _has_bits_[0];
// required int32 retType = 1 [default = -400];
if (cached_has_bits & 0x00000008u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->rettype(), target);
}
// optional string retMsg = 2;
if (cached_has_bits & 0x00000001u) {
::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
this->retmsg().data(), static_cast<int>(this->retmsg().length()),
::google::protobuf::internal::WireFormat::SERIALIZE,
"Qot_StockFilter.Response.retMsg");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
2, this->retmsg(), target);
}
// optional int32 errCode = 3;
if (cached_has_bits & 0x00000004u) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(3, this->errcode(), target);
}
// optional .Qot_StockFilter.S2C s2c = 4;
if (cached_has_bits & 0x00000002u) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
4, *this->s2c_, deterministic, target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
_internal_metadata_.unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:Qot_StockFilter.Response)
return target;
}
size_t Response::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:Qot_StockFilter.Response)
size_t total_size = 0;
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
_internal_metadata_.unknown_fields());
}
// required int32 retType = 1 [default = -400];
if (has_rettype()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->rettype());
}
if (_has_bits_[0 / 32] & 7u) {
// optional string retMsg = 2;
if (has_retmsg()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->retmsg());
}
// optional .Qot_StockFilter.S2C s2c = 4;
if (has_s2c()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*this->s2c_);
}
// optional int32 errCode = 3;
if (has_errcode()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->errcode());
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void Response::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:Qot_StockFilter.Response)
GOOGLE_DCHECK_NE(&from, this);
const Response* source =
::google::protobuf::internal::DynamicCastToGenerated<const Response>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:Qot_StockFilter.Response)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:Qot_StockFilter.Response)
MergeFrom(*source);
}
}
void Response::MergeFrom(const Response& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:Qot_StockFilter.Response)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
cached_has_bits = from._has_bits_[0];
if (cached_has_bits & 15u) {
if (cached_has_bits & 0x00000001u) {
set_has_retmsg();
retmsg_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.retmsg_);
}
if (cached_has_bits & 0x00000002u) {
mutable_s2c()->::Qot_StockFilter::S2C::MergeFrom(from.s2c());
}
if (cached_has_bits & 0x00000004u) {
errcode_ = from.errcode_;
}
if (cached_has_bits & 0x00000008u) {
rettype_ = from.rettype_;
}
_has_bits_[0] |= cached_has_bits;
}
}
void Response::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:Qot_StockFilter.Response)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void Response::CopyFrom(const Response& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:Qot_StockFilter.Response)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool Response::IsInitialized() const {
if ((_has_bits_[0] & 0x00000008) != 0x00000008) return false;
if (has_s2c()) {
if (!this->s2c_->IsInitialized()) return false;
}
return true;
}
void Response::Swap(Response* other) {
if (other == this) return;
InternalSwap(other);
}
void Response::InternalSwap(Response* other) {
using std::swap;
retmsg_.Swap(&other->retmsg_);
swap(s2c_, other->s2c_);
swap(errcode_, other->errcode_);
swap(rettype_, other->rettype_);
swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Response::GetMetadata() const {
protobuf_Qot_5fStockFilter_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_Qot_5fStockFilter_2eproto::file_level_metadata[kIndexInFileMessages];
}
// @@protoc_insertion_point(namespace_scope)
} // namespace Qot_StockFilter
// @@protoc_insertion_point(global_scope)
| 35.191784 | 131 | 0.700336 | stephenlyu |
93725088b78cf054fd20e520c993f4e21abdadfb | 636 | cpp | C++ | TC/TCHS-53-250.cpp | aajjbb/contest-files | b8842681b96017063a7baeac52ae1318bf59d74d | [
"Apache-2.0"
] | 1 | 2018-08-28T19:58:40.000Z | 2018-08-28T19:58:40.000Z | TC/TCHS-53-250.cpp | aajjbb/contest-files | b8842681b96017063a7baeac52ae1318bf59d74d | [
"Apache-2.0"
] | 2 | 2017-04-16T00:48:05.000Z | 2017-08-03T20:12:26.000Z | TC/TCHS-53-250.cpp | aajjbb/contest-files | b8842681b96017063a7baeac52ae1318bf59d74d | [
"Apache-2.0"
] | 4 | 2016-03-04T19:42:00.000Z | 2018-01-08T11:42:00.000Z | #include <iostream>
#include <string>
#include <vector>
#include <cmath>
#define REP(i, j) for(i = 0; i < j; i++)
using namespace std;
class DNAConstruction {
public:
int maxLength(string n) {
int ans = 0, i, numA = 0, numT = 0, numC = 0, numG = 0;
REP(i, n.size()) {
if(n[i] == 'A') {
numA++;
}if(n[i] == 'T') {
numT++;
}if(n[i] == 'C') {
numC++;
}if(n[i] == 'G') {
numG++;
}
}
int pairOneMin = min(numA, numT);
REP(i, pairOneMin) {
ans++;
}
int pairTwoMin = min(numC, numG);
REP(i, pairTwoMin) {
ans++;
}
return ans;
}
};
<%:testing-code%>
// Powered by FileEdit
| 14.454545 | 57 | 0.512579 | aajjbb |
937976edbd5c1b989c74bf779298157b387a6984 | 9,346 | cpp | C++ | src/codegen.cpp | steakhal/wcomp | b52c1b77edc8f5242fd08338a9c72e5a9a709a46 | [
"MIT"
] | null | null | null | src/codegen.cpp | steakhal/wcomp | b52c1b77edc8f5242fd08338a9c72e5a9a709a46 | [
"MIT"
] | null | null | null | src/codegen.cpp | steakhal/wcomp | b52c1b77edc8f5242fd08338a9c72e5a9a709a46 | [
"MIT"
] | null | null | null | #include "cfg.h"
#include "expressions.h"
#include "statements.h"
#include "typecheck.h"
#include "utility.h"
#include <algorithm>
#include <cassert>
#include <iostream>
#include <optional>
#include <random>
#include <set>
#include <sstream>
#include <string_view>
namespace {
class symbols_to_asm {
std::ostream &ss;
public:
explicit symbols_to_asm(std::ostream &ss) : ss{ss} {}
void operator()(const symbols &syms) const {
for (const auto &pair : syms) {
const auto &name = pair.first;
const symbol &sym = pair.second;
const int width = sym.symbol_type == boolean ? 1 : 4;
ss << "var_" << sym.name << ": resb " << width << '\n';
}
}
};
std::string_view get_register(type ty) { return ty == boolean ? "al" : "eax"; }
void emit_eq_code(std::ostream &ss, type ty) {
ss << (ty == natural ? "cmp eax,ecx\n" : "cmp al,cl\n");
ss << "mov al,0\n";
ss << "mov cx,1\n";
ss << "cmove ax,cx\n";
}
void emit_operator_code(std::ostream &ss, std::string_view op) {
if (op == "+") {
ss << "add eax,ecx\n";
} else if (op == "-") {
ss << "sub eax,ecx\n";
} else if (op == "*") {
ss << "xor edx,edx\n";
ss << "mul ecx\n";
} else if (op == "/") {
ss << "xor edx,edx\n";
ss << "div ecx\n";
} else if (op == "%") {
ss << "xor edx,edx\n";
ss << "div ecx\n";
ss << "mov eax,edx\n";
} else if (op == "<") {
ss << "cmp eax,ecx\n";
ss << "mov al,0\n";
ss << "mov cx,1\n";
ss << "cmovb ax,cx\n";
} else if (op == "<=") {
ss << "cmp eax,ecx\n";
ss << "mov al,0\n";
ss << "mov cx,1\n";
ss << "cmovbe ax,cx\n";
} else if (op == ">") {
ss << "cmp eax,ecx\n";
ss << "mov al,0\n";
ss << "mov cx,1\n";
ss << "cmova ax,cx\n";
} else if (op == ">=") {
ss << "cmp eax,ecx\n";
ss << "mov al,0\n";
ss << "mov cx,1\n";
ss << "cmovae ax,cx\n";
} else if (op == "and") {
ss << "cmp al,1\n";
ss << "cmove ax,cx\n";
} else if (op == "or") {
ss << "cmp al,0\n";
ss << "cmove ax,cx\n";
} else {
error(-1,
std::string("Bug: Unsupported binary operator: ") + std::string(op));
}
}
std::string_view get_type_name(type ty) {
return ty == boolean ? "boolean" : "natural";
}
class expr_to_asm {
protected:
const symbols &syms;
std::ostream &ss;
const basicblock ¤t_block;
const bool encode_constants;
public:
expr_to_asm(const symbols &syms, std::ostream &ss, bool encode_constants,
const basicblock ¤t_block)
: syms{syms}, ss{ss}, current_block{current_block},
encode_constants{encode_constants} {}
void operator()(const number_expression &x) const {
if (encode_constants) {
const auto half_id = current_block.id / 2;
const bb_idx encoded = current_block.id ^ (x.value + half_id);
ss << "mov eax, " << encoded << '\n';
ss << "mov ebx, " << current_block.id << '\n';
ss << "xor eax, ebx\n";
ss << "sub eax, " << half_id << "; encoded " << x.value << "\n";
} else {
ss << "mov eax," << x.value << '\n';
}
}
void operator()(const boolean_expression &x) const {
if (encode_constants) {
const auto half_id = current_block.id / 2;
const bb_idx encoded = current_block.id ^ (x.value + half_id);
ss << "mov eax, " << encoded << '\n';
ss << "mov ebx, " << current_block.id << '\n';
ss << "xor eax, ebx\n";
ss << "sub eax, " << half_id << "; encoded " << x.value << "\n";
} else {
ss << "mov eax," << x.value << '\n';
}
}
void operator()(const id_expression &x) const {
const auto it = syms.find(x.name);
assert(it != syms.end());
ss << "mov eax,[var_" << it->second.name + "]\n";
}
void operator()(const binop_expression &x) const {
std::visit(*this, *x.left);
ss << "push eax\n";
std::visit(*this, *x.right);
ss << "mov ecx,eax\n";
ss << "pop eax\n";
if (x.op == "=")
emit_eq_code(ss, infer_expression_type(syms, *x.left));
else
emit_operator_code(ss, x.op);
}
void operator()(const not_expression &x) const {
std::visit(*this, *x.operand);
ss << "xor al,1\n";
}
};
class ir_to_asm : private expr_to_asm {
public:
ir_to_asm(const symbols &syms, std::ostream &ss, bool encode_constants,
const basicblock ¤t_block)
: expr_to_asm{syms, ss, encode_constants, current_block} {}
using expr_to_asm::operator();
// Basic ir instructions.
void operator()(const assign_statement &x) const {
std::visit(*this, *x.right);
const auto it = syms.find(x.left);
assert(it != syms.end());
ss << "mov [var_" + it->second.name + "],"
<< get_register(it->second.symbol_type) << '\n';
}
void operator()(const read_statement &x) const {
const auto it = syms.find(x.id);
assert(it != syms.end());
const type ty = it->second.symbol_type;
ss << "call read_" << get_type_name(ty) << '\n';
ss << "mov [var_" << it->second.name << "]," << get_register(ty) << '\n';
}
void operator()(const write_statement &x) const {
const type ty = infer_expression_type(syms, *x.value);
std::visit(*this, *x.value);
if (ty == boolean) {
ss << "and eax,1\n";
}
ss << "push eax\n";
ss << "call write_" << get_type_name(ty) << '\n';
ss << "add esp,4\n";
}
void operator()(const cassign &x) const {
std::visit(*this, *x.condition);
ss << "cmp al,1\n";
ss << "mov eax," << x.false_value << '\n';
ss << "mov ebx, " << x.true_value << '\n';
ss << "cmove eax, ebx\n";
ss << "mov [var_" << x.var.name << "], eax\n";
}
// Control-flow:
void operator()(const selector &x) const {
std::visit(*this, *x.condition);
ss << "cmp al,1\n";
ss << "je bb_" << x.true_branch.id << '\n';
ss << "jmp bb_" << x.false_branch.id << '\n';
}
void operator()(const jump &x) const {
ss << "jmp bb_" << x.target.id << '\n';
}
void operator()(const switcher &x) const {
// Load var to eax.
operator()(x.var);
assert(!x.branches.empty());
for (const basicblock *target : x.branches) {
ss << "mov ecx, " << target->id << '\n';
ss << "cmp eax,ecx\n";
ss << "je bb_" << target->id << '\n';
}
}
};
void emit_basicblock(std::ostream &ss, const cfg &cfg, const symbols &syms,
const basicblock &bb, bool encode_constants) {
ir_to_asm emitter{syms, ss, encode_constants, bb};
if (&bb == cfg.entry)
ss << "; entry\nmain:\n";
else if (&bb == cfg.exit)
ss << "; exit\n";
ss << "bb_" << bb.id << ":\n";
for (const ir_instruction &inst : bb.instructions)
std::visit(emitter, inst);
if (&bb == cfg.exit) {
ss << "xor eax,eax\n";
ss << "ret\n";
}
}
void recursively_emit_basicblock(std::vector<std::string> &out, const cfg &cfg,
const symbols &syms, const basicblock &bb,
std::set<bb_idx> &processed,
bool encode_constants) {
auto [_, succeeded] = processed.insert(bb.id);
if (!succeeded)
return;
std::stringstream ss;
emit_basicblock(ss, cfg, syms, bb, encode_constants);
out.push_back(std::move(ss).str());
if (bb.instructions.empty())
return;
std::visit(
overloaded{[&](const auto &x) {},
[&](const selector &x) {
recursively_emit_basicblock(out, cfg, syms, x.true_branch,
processed, encode_constants);
recursively_emit_basicblock(out, cfg, syms, x.false_branch,
processed, encode_constants);
},
[&](const jump &x) {
recursively_emit_basicblock(out, cfg, syms, x.target,
processed, encode_constants);
},
[&](const switcher &x) {
for (const basicblock *target : x.branches)
recursively_emit_basicblock(out, cfg, syms, *target,
processed, encode_constants);
}},
bb.instructions.back());
}
} // namespace
std::string codegen(const cfg &cfg, const symbols &syms,
std::optional<std::size_t> serialization_seed,
bool encode_constants) {
std::stringstream ss;
ss << "global main\n"
"extern write_natural\n"
"extern read_natural\n"
"extern write_boolean\n"
"extern read_boolean\n\n"
"section .bss\n";
symbols_to_asm{ss}(syms);
ss << "\nsection .text\n";
std::set<bb_idx> processed;
std::vector<std::string> code_of_basicblocks;
recursively_emit_basicblock(code_of_basicblocks, cfg, syms, *cfg.entry,
processed, encode_constants);
if (serialization_seed.has_value()) {
if (serialization_seed.value() == -1) {
std::random_device rd;
std::mt19937 gen(rd());
std::shuffle(code_of_basicblocks.begin(), code_of_basicblocks.end(), gen);
} else {
std::mt19937 gen(serialization_seed.value());
std::shuffle(code_of_basicblocks.begin(), code_of_basicblocks.end(), gen);
}
}
for (std::string &code : code_of_basicblocks)
ss << std::move(code);
return ss.str();
}
| 30.344156 | 80 | 0.543976 | steakhal |
937cd31d317ac36ff42be4b7c6dcb90929f9f525 | 3,836 | cpp | C++ | leetcode/last-stone-weight.cpp | jcpince/algorithms | c43dd8e98a0f0df691ead5f25c2c17a9241db908 | [
"MIT"
] | null | null | null | leetcode/last-stone-weight.cpp | jcpince/algorithms | c43dd8e98a0f0df691ead5f25c2c17a9241db908 | [
"MIT"
] | null | null | null | leetcode/last-stone-weight.cpp | jcpince/algorithms | c43dd8e98a0f0df691ead5f25c2c17a9241db908 | [
"MIT"
] | null | null | null | /*
Last Stone Weight
We have a collection of stones, each stone has a positive integer weight.
Each turn, we choose the two heaviest stones and smash them together. Suppose the stones have weights x and y with x <= y. The result of this smash is:
If x == y, both stones are totally destroyed;
If x != y, the stone of weight x is totally destroyed, and the stone of weight y has new weight y-x.
At the end, there is at most 1 stone left. Return the weight of this stone (or 0 if there are no stones left.)
Example 1:
Input: [2,7,4,1,8,1]
Output: 1
Explanation:
We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,
we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,
we combine 2 and 1 to get 1 so the array converts to [1,1,1] then,
we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of last stone.
Note:
1 <= stones.length <= 30
1 <= stones[i] <= 1000
*/
#include <bits/stdc++.h>
//#define DEBUG 1
#undef DEBUG
#include <ListNode.h>
#include <UnitTests.h>
#include <TestsHelper.h>
using namespace std;
const bool continue_on_failure = false;
class Solution {
public:
int lastStoneWeight(vector<int>& stones) {
if (stones.size() < 2) return stones[0];
sort(stones.begin(), stones.end());
int nb_stones = stones.size();
ListNode _l[nb_stones], *l, *heaviest = &_l[nb_stones-1];
int idx = nb_stones-1;
for ( ; idx >= 0 ; idx-- ) {
l = &_l[idx];
int stone = stones[idx];
l->val = stone;
l->next = idx > 0 ? &_l[idx-1] : NULL;
}
while (heaviest && heaviest->next) {
ListNode *second = heaviest->next;
if (second->val == heaviest->val) {
heaviest = second->next;
} else {
ListNode *new_stone = heaviest, *new_head = second->next, *prev = NULL;
new_stone->val = heaviest->val - second->val;
if (!new_head) return new_stone->val;
if (new_head->val <= new_stone->val) {
heaviest->next = new_head;
continue;
}
/* insert the new stone at its place in the list */
heaviest = new_head;
while(new_head && new_head->val > new_stone->val) {
prev = new_head;
new_head = new_head->next;
}
new_stone->next = prev->next;
prev->next = new_stone;
}
}
return heaviest ? heaviest->val : 0;
}
};
int run_test_case(void *_s, TestCase *tc) {
UNUSED(_s);
vector<int> stones = tc->test_case[JSON_TEST_CASE_IN_FIELDNAME];
int expected = tc->test_case[JSON_TEST_CASE_EXPECTED_FIELDNAME];
Solution s;
bool result = s.lastStoneWeight(stones);
if (result == expected) return 0;
printf("lastStoneWeight(%s) returned %d but expected %d\n",
array2str(stones).c_str(), result, expected);
assert(continue_on_failure);
return 1;
}
int main(int argc, char **argv) {
int tests_ran = 0;
const char *tc_id = NULL;
if (argc < 2 || argc > 3)
{
cerr << "Usage: " << argv[0] << " <json test file> [test case index or name]" << endl;
cerr << "Where: [test case index or name] specifies which test to run (all by default)" <<
endl;
return -1;
}
UnitTests uts(NULL, &run_test_case, argv[1]);
if (argc == 3) tc_id = argv[2];
int errors_count = uts.run_test_cases(tc_id, tests_ran);
if (errors_count == 0)
cout << "All " << tests_ran << " test(s) succeeded!!!" << endl;
else
cout << errors_count << " test(s) failed over a total of " << tests_ran << endl;
return errors_count;
}
| 29.507692 | 153 | 0.576903 | jcpince |
937d9e50dcd2cb71731073d945c9f0d633dd3a4c | 42,009 | cpp | C++ | libraries/VAL/src/TimSupport.cpp | tmigimatsu/VAL | 473c90067fceb136abd8bb11660d50fa1d38a040 | [
"BSD-3-Clause"
] | null | null | null | libraries/VAL/src/TimSupport.cpp | tmigimatsu/VAL | 473c90067fceb136abd8bb11660d50fa1d38a040 | [
"BSD-3-Clause"
] | null | null | null | libraries/VAL/src/TimSupport.cpp | tmigimatsu/VAL | 473c90067fceb136abd8bb11660d50fa1d38a040 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2019 - University of Strathclyde, King's College London and Schlumberger Ltd
// This source code is licensed under the BSD license found in the LICENSE file in the root directory of this source tree.
#include "TimSupport.h"
#include "FastEnvironment.h"
#include "Partitions.h"
#include "ptree.h"
#include <numeric>
#include <set>
using std::copy;
using std::greater;
using std::inserter;
using std::max_element;
using std::min_element;
using std::set;
#include <assert.h>
namespace TIM {
using namespace VAL;
ostream &operator<<(ostream &o, const Property &p) {
p.write(o);
return o;
};
int getId(parameter_symbol *s) {
const IDsymbol< var_symbol > *i =
dynamic_cast< const IDsymbol< var_symbol > * >(s);
if (!i) return -1;
return i->getId();
};
template < class T >
TIMpredSymbol *findPred(T *g);
template <>
TIMpredSymbol *findPred(simple_effect *g) {
return static_cast< TIMpredSymbol * >(
const_cast< pred_symbol * >(g->prop->head));
};
template <>
TIMpredSymbol *findPred(derivation_rule *g) {
return static_cast< TIMpredSymbol * >(
const_cast< pred_symbol * >(g->get_head()->head));
};
bool PropertySpace::contains(TIMobjectSymbol *t) const {
return binary_search(objects.begin(), objects.end(), t);
};
struct recordObjectIn {
PropertySpace *ps;
bool added;
recordObjectIn(PropertySpace *p) : ps(p), added(false){};
void operator()(TIMobjectSymbol *o) {
if (!ps->contains(o)) {
o->addIn(ps);
ps->add(o);
added = true;
};
};
operator bool() { return added; };
};
var_symbol *getAt(var_symbol_list *ps, int v) {
var_symbol_list::iterator i = ps->begin();
for (; v > 0; --v, ++i)
;
return *i;
};
parameter_symbol *getAt(parameter_symbol_list *ps, int v) {
parameter_symbol_list::iterator i = ps->begin();
for (; v > 0; --v, ++i)
;
return *i;
};
TransitionRule::TransitionRule(TIMAnalyser *t, operator_ *o, int v,
PropertyState *e, PropertyState *l,
PropertyState *r, opType ty)
: tan(t),
op(o),
drv(0),
opt(ty),
var(v),
enablers(e),
lhs(l),
rhs(r),
objects(var >= 0 ? tan->getTC().range(getAt(op->parameters, var))
: vector< const_symbol * >()){};
TransitionRule::TransitionRule(TIMAnalyser *t, derivation_rule *o, int v,
PropertyState *e, PropertyState *l,
PropertyState *r, opType ty)
: tan(t),
op(0),
drv(o),
opt(ty),
var(v),
enablers(e),
lhs(l),
rhs(r),
objects(var >= 0 ? tan->getTC().range(getAt(drv->get_head()->args, var))
: vector< const_symbol * >()){};
bool TransitionRule::applicableIn(const PropertyState *ps) const {
return std::includes(ps->begin(), ps->end(), lhs->begin(), lhs->end());
};
struct checkNotApplicable {
TIMobjectSymbol *tos;
checkNotApplicable(const_symbol *c)
: tos(static_cast< TIMobjectSymbol * >(c)){};
bool operator()(Property *p) {
return find_if(p->begin(), p->end(),
not1(bind2nd(mem_fun(&PropertySpace::contains), tos))) !=
p->end();
};
};
class RuleObjectIterator {
private:
TransitionRule *trule;
vector< const_symbol * >::iterator obit;
void findValid() {
while (obit != trule->objects.end()) {
if (find_if(trule->enablers->begin(), trule->enablers->end(),
checkNotApplicable(*obit)) == trule->enablers->end())
break;
++obit;
};
};
public:
RuleObjectIterator(TransitionRule *tr)
: trule(tr), obit(trule->objects.begin()) {
findValid();
};
void toEnd() { obit = trule->objects.end(); };
RuleObjectIterator &operator++() {
++obit;
findValid();
return *this;
};
TIMobjectSymbol *operator*() {
return static_cast< TIMobjectSymbol * >(*obit);
};
bool operator==(const RuleObjectIterator &roi) const {
return trule == roi.trule && obit == roi.obit;
};
bool operator!=(const RuleObjectIterator &roi) const {
return trule != roi.trule || obit != roi.obit;
};
};
RuleObjectIterator TransitionRule::endEnabledObjects() {
RuleObjectIterator i(this);
i.toEnd();
return i;
};
RuleObjectIterator TransitionRule::beginEnabledObjects() {
return RuleObjectIterator(this);
};
struct extendWithIncrRule {
PropertySpace *ps;
bool extended;
extendWithIncrRule(PropertySpace *p) : ps(p), extended(false){};
void operator()(TransitionRule *tr) {
if (tr->isIncreasing()) {
extended = for_each(tr->beginEnabledObjects(), tr->endEnabledObjects(),
recordObjectIn(ps));
};
};
operator bool() { return extended; };
};
template < class T >
T isSuper(const PropertyState *p, T b, T e) {
while (b != e) {
if (std::includes(p->begin(), p->end(), (*b)->begin(), (*b)->end()))
return b;
++b;
};
return b;
};
struct extendWithStateRule {
set< PropertyState * > &got;
list< PropertyState * > &toExtend;
PropertyState *prop;
extendWithStateRule(set< PropertyState * > &s, list< PropertyState * > &l)
: got(s),
toExtend(l),
prop(toExtend.empty() ? 0 : *(toExtend.begin())){};
void operator()(TransitionRule *tr) {
if (!prop) return;
PropertyState *p = tr->tryRule(prop);
if (p && got.find(p) == got.end()) {
set< PropertyState * >::const_iterator i =
isSuper(p, got.begin(), got.end());
if (i != got.end()) {
OUTPUT cout << *p
<< " is a superset of a state we already have: " << **i
<< "\n";
} else {
got.insert(p);
toExtend.push_back(p);
};
};
};
void next() {
toExtend.pop_front();
prop = toExtend.empty() ? 0 : *(toExtend.begin());
};
operator bool() { return !toExtend.empty(); };
};
bool PropertySpace::extend() {
if (!isStateValued) {
// cout << "\nExtending attribute space...\n";
// write(cout);
// We add to this space every object that is currently in all of the
// spaces for enabling properties of any increasing rule in this space.
bool b = for_each(rules.begin(), rules.end(), extendWithIncrRule(this));
if (b) sort(objects.begin(), objects.end());
return b;
} else {
// cout << "\nExtending state space...\n";
// For each state in the space we need to apply each rule (if it can be
// applied) and add the corresponding new state to the space. We really
// should confirm that we only use states for enabled objects, but maybe
// that's a refinement we can save until later.
//
// Basic pattern: for each state and rule pair, if rule applies then
// produce new state. Key issue: avoid retesting states with rules. One
// way to do this would be to take each state in turn and extend it with
// all rules, adding new states to a list as they are generated. As they
// are added to the list they can also be added to the internal set of
// states, so that membership can be checked fast.
list< PropertyState * > toExtend;
copy(states.begin(), states.end(), inserter(toExtend, toExtend.begin()));
extendWithStateRule ewsr(this->states, toExtend);
while (for_each(rules.begin(), rules.end(), ewsr)) ewsr.next();
// write(cout);
return false;
};
};
template <>
TIMpredSymbol *findPred(simple_goal *g) {
return static_cast< TIMpredSymbol * >(
const_cast< pred_symbol * >(g->getProp()->head));
};
struct process_argument {
TIMAnalyser *ta;
TIMpredSymbol *timps;
int arg;
proposition *prp;
virtual ~process_argument(){};
template < class T >
process_argument(TIMAnalyser *t, T *g, proposition *p)
: ta(t), timps(findPred< T >(g)), arg(0), prp(p){};
template < class T >
process_argument(TIMAnalyser *t, T *g)
: ta(t), timps(findPred< T >(g)), arg(0), prp(0){};
virtual void operator()(parameter_symbol *p) = 0;
};
struct process_argument_in_goal : public process_argument {
process_argument_in_goal(TIMAnalyser *t, simple_goal *g)
: process_argument(t, g){};
virtual ~process_argument_in_goal(){};
virtual void operator()(parameter_symbol *p) {
Property *prop = timps->property(arg);
++arg;
ta->insertPre(getId(p), prop);
};
};
struct process_argument_in_effect : public process_argument {
process_argument_in_effect(TIMAnalyser *t, simple_effect *g)
: process_argument(t, g){};
virtual ~process_argument_in_effect(){};
virtual void operator()(parameter_symbol *p) {
Property *prop = timps->property(arg);
++arg;
ta->insertEff(getId(p), prop);
};
};
struct process_argument_in_derivation_effect : public process_argument {
process_argument_in_derivation_effect(TIMAnalyser *t, derivation_rule *g)
: process_argument(t, g){};
virtual ~process_argument_in_derivation_effect(){};
virtual void operator()(parameter_symbol *p) {
Property *prop = timps->property(arg);
++arg;
ta->insertEff(getId(p), prop);
};
};
struct process_constant_in_goal : public process_argument {
process_constant_in_goal(TIMAnalyser *t, simple_goal *g)
: process_argument(t, g){};
virtual ~process_constant_in_goal(){};
virtual void operator()(parameter_symbol *p) {
Property *prop = timps->property(arg);
++arg;
ta->insertGoal(p, prop);
};
};
struct process_constant_in_initial : public process_argument {
process_constant_in_initial(TIMAnalyser *t, simple_effect *g)
: process_argument(t, g, g->prop){};
virtual ~process_constant_in_initial(){};
virtual void operator()(parameter_symbol *p) {
Property *prop = timps->property(arg);
++arg;
ta->insertInitial(p, prop, prp);
};
};
void TIMAnalyser::visit_simple_goal(simple_goal *p) {
if (finally) {
for_each(p->getProp()->args->begin(), p->getProp()->args->end(),
process_constant_in_goal(this, p));
} else {
for_each(p->getProp()->args->begin(), p->getProp()->args->end(),
process_argument_in_goal(this, p));
};
};
struct notIn {
PropertySpace *ps;
notIn(PropertySpace *p) : ps(p){};
bool operator()(Property *p) {
return (p->begin() == p->end()) || *(p->begin()) != ps;
};
};
bool Property::matches(const extended_pred_symbol *eps, pddl_type *pt) {
if (EPS(predicate)->getParent() != eps->getParent()) return false;
// cout << "A: " << *pt << "\n";
// cout << "B: " << *eps << "\n";
Types::const_iterator tcItr = eps->tcBegin() + posn;
if (tcItr == eps->tcEnd()) {
std::cerr
<< "A problem has been encountered with your domain/problem file.\n";
std::cerr
<< "-------------------------------------------------------------\n";
std::cerr
<< "Unfortunately, a bug has been encountered in your domain and "
"problem file,\n";
std::cerr << "and the planner has to terminate. The predicate:\n\n";
std::cerr << "\t" << eps->getName() << "\n\n";
int realArgs = 0;
{
Types::const_iterator tcsItr = eps->tcBegin();
Types::const_iterator tcsEnd = eps->tcEnd();
for (; tcsItr != tcsEnd; ++tcsItr) ++realArgs;
}
std::cerr << "...takes " << realArgs << " argument";
if (realArgs != 1) std::cerr << "s";
std::cerr << ", but has been given at least " << posn + 1 << ".\n";
exit(0);
}
if (*tcItr) {
// cout << "C: " << **(eps->tcBegin()+posn) << "\n";
} else {
// cout << "C: ***\n";
return false;
};
return (pt == (*tcItr)->type);
};
bool Property::equivalent(const Property *p) const {
if (this == p) return true;
if (posn != p->posn ||
EPS(predicate)->getParent() != EPS(p->predicate)->getParent())
return false;
return true;
};
struct notMatchFor {
pddl_type *pt;
Property *prop;
notMatchFor(pddl_type *p, Property *pr) : pt(p), prop(pr){};
bool operator()(extended_pred_symbol *eps) {
return !(prop->matches(eps, pt));
};
};
struct toProp {
int arg;
toProp(int a) : arg(a){};
Property *operator()(extended_pred_symbol *eps) {
return static_cast< TIMpredSymbol * >(eps)->property(arg);
};
};
void TIMAnalyser::close(set< Property * > &seed, const pddl_type *pt) {
bool adding = true;
while (adding) {
adding = false;
PropertyState *ps =
PropertyState::getPS(this, pt, seed.begin(), seed.end());
for (TRules::const_iterator r = trules.begin(); r != trules.end(); ++r) {
if ((*r)->applicableIn(ps)) {
copy((*r)->getRHS()->begin(), (*r)->getRHS()->end(),
inserter(seed, seed.begin()));
adding |= (seed.size() > ps->size());
};
};
};
};
vector< Property * > Property::matchers() {
vector< extended_pred_symbol * > v;
holding_pred_symbol *h = EPS(predicate)->getParent();
std::remove_copy_if(
h->pBegin(), h->pEnd(), inserter(v, v.begin()),
notMatchFor((*((EPS(predicate)->tBegin()) + posn))->type, this));
vector< Property * > ps;
transform(v.begin(), v.end(), inserter(ps, ps.begin()), toProp(posn));
return ps;
};
struct setMatchers {
vector< Property * > &ps;
setMatchers(vector< Property * > &p) : ps(p){};
void operator()(Property *p) {
vector< Property * > props = p->matchers();
copy(props.begin(), props.end(), inserter(ps, ps.end()));
};
};
void TIMobjectSymbol::distributeStates(TIMAnalyser *tan) {
vector< Property * >::iterator s, e, m;
vector< Property * > matchers;
for_each(initial.begin(), initial.end(), setMatchers(matchers));
s = matchers.begin();
e = matchers.end();
while (s != e) {
if ((*s)->begin() == (*s)->end()) {
// State belonging to no property space.
// This should not happen...but, see notes.
++s;
continue;
};
PropertySpace *p =
*((*s)->begin()); // Assumes only one space at this stage
p->add(this);
m = std::partition(s, e, notIn(p));
std::sort(m, e);
PropertyState *ps = PropertyState::getPS(tan, type, m, e);
p->add(ps);
e = m;
};
};
Property *Property::getBaseProperty(const pddl_type *pt) const {
if (!EPS(predicate)->getParent()) return const_cast< Property * >(this);
TIMpredSymbol *tps =
static_cast< TIMpredSymbol * >(EPS(predicate)->getParent()->find(
predicate, makeTT(EPS(predicate)->tBegin(), posn, pt),
makeTT(EPS(predicate)->tEnd(), 0, 0)));
return tps->property(posn);
};
ostream &operator<<(ostream &o, const TIMobjectSymbol &t) {
t.write(o);
return o;
};
void TIMAnalyser::visit_simple_effect(simple_effect *p) {
if (initially) {
for_each(p->prop->args->begin(), p->prop->args->end(),
process_constant_in_initial(this, p));
} else {
for_each(p->prop->args->begin(), p->prop->args->end(),
process_argument_in_effect(this, p));
};
};
void TIMAnalyser::visit_simple_derivation_effect(derivation_rule *p) {
for_each(p->get_head()->args->begin(), p->get_head()->args->end(),
process_argument_in_derivation_effect(this, p));
};
void TIMAnalyser::insertPre(int v, Property *p) {
if (v < 0) {
OUTPUT cout << "Property for a constant\n";
return;
};
if (overall) {
MEX(op)->addInvariant(p, v);
return;
} else {
if (op)
MEX(op)->addCondition(p, v,
isDurative ? (atStart ? START : END) : INSTANT);
};
if (!rules[v]) {
if (op)
rules[v] = new ProtoRule(
this, op, v, isDurative ? (atStart ? START : END) : INSTANT);
if (drv)
rules[v] = new ProtoRule(
this, drv, v, isDurative ? (atStart ? START : END) : INSTANT);
}
rules[v]->insertPre(p);
};
void TIMAnalyser::insertEff(int v, Property *p) {
if (v < 0) {
OUTPUT cout << "Property for a constant\n";
return;
};
if (!rules[v]) {
if (op)
rules[v] = new ProtoRule(
this, op, v, isDurative ? (atStart ? START : END) : INSTANT);
if (drv)
rules[v] = new ProtoRule(
this, drv, v, isDurative ? (atStart ? START : END) : INSTANT);
}
if (adding) {
rules[v]->insertAdd(p);
} else {
rules[v]->insertDel(p);
};
};
void TIMAnalyser::insertGoal(parameter_symbol *c, Property *p) {
TIMobjectSymbol *cc = dynamic_cast< TIMobjectSymbol * >(c);
cc->addFinal(p);
};
void TIMAnalyser::insertInitial(parameter_symbol *c, Property *p,
proposition *prp) {
TIMobjectSymbol *cc = dynamic_cast< TIMobjectSymbol * >(c);
cc->addInitial(p, prp);
};
ostream &operator<<(ostream &o, const PropertyState &p) {
p.write(o);
return o;
};
ostream &operator<<(ostream &o, const TransitionRule &tr) {
tr.write(o);
return o;
};
void ProtoRule::addRules(TRules &trules) {
sort(enablers.begin(), enablers.end());
sort(adds.begin(), adds.end());
sort(dels.begin(), dels.end());
vector< Property * > es;
set_difference(enablers.begin(), enablers.end(), dels.begin(), dels.end(),
inserter(es, es.begin()));
vector< Property * > is;
set_intersection(dels.begin(), dels.end(), adds.begin(), adds.end(),
inserter(is, is.begin()));
// Problem here: if we have a constant we still need to know what it is...
parameter_symbol *v = (var >= 0 ? (op ? getAt(op->parameters, var)
: getAt(drv->get_head()->args, var))
: 0);
vector< const pddl_type * > types(tan->getTC().leaves(v->type));
if (types.empty()) types.push_back(v->type);
if (is.size() > 1 ||
((is.size() == 1) && (dels.size() > 1 || adds.size() > 1))) {
assert(op);
// don't worry, cannot ever be true for derivation rules: have no delete
// effects, so is empty, dels empty....
for (vector< Property * >::iterator i = is.begin(); i != is.end(); ++i) {
Property *p = *i;
if (find(enablers.begin(), enablers.end(), p) != enablers.end()) {
enablers.erase(find(enablers.begin(), enablers.end(), p));
};
// Else we are deleting a non-precondition - which could be OK if we
// are looking at an action end point.
for (vector< const pddl_type * >::const_iterator pt = types.begin();
pt != types.end(); ++pt) {
PropertyState *x = PropertyState::getPS(tan, *pt, i, i + 1);
PropertyState *en =
PropertyState::getPS(tan, *pt, enablers.begin(), enablers.end());
trules.push_back(new TransitionRule(tan, op, var, en, x, x, opt));
};
enablers.insert(find_if(enablers.begin(), enablers.end(),
bind2nd(greater< Property * >(), p)),
p);
};
if (adds.size() > is.size() || dels.size() > is.size()) {
vector< Property * > nadds, ndels;
set_difference(adds.begin(), adds.end(), is.begin(), is.end(),
inserter(nadds, nadds.begin()));
set_difference(dels.begin(), dels.end(), is.begin(), is.end(),
inserter(ndels, ndels.begin()));
enablers.clear();
merge(es.begin(), es.end(), is.begin(), is.end(),
inserter(enablers, enablers.begin()));
es.swap(enablers);
} else {
// No other rule to construct (all in split forms).
return;
};
};
for (vector< const pddl_type * >::const_iterator pt = types.begin();
pt != types.end(); ++pt) {
PropertyState *e = PropertyState::getPS(tan, *pt, es.begin(), es.end());
PropertyState *l =
PropertyState::getPS(tan, *pt, dels.begin(), dels.end());
PropertyState *r =
PropertyState::getPS(tan, *pt, adds.begin(), adds.end());
if (op) {
trules.push_back(new TransitionRule(tan, op, var, e, l, r, opt));
} else {
trules.push_back(new TransitionRule(tan, drv, var, e, l, r, opt));
}
};
};
PropertyState::PMap PropertyState::pmap;
PropertySpace *PSCombiner(PropertySpace *p1, PropertySpace *p2) {
p1->merge(p2);
return p1;
};
typedef PropertySpace *(*PSC)(PropertySpace *, PropertySpace *);
typedef Partitioner< Property *, PropertySpace *, PSC > PM;
struct unifyWith {
PM ±
Property *pr;
TransitionRule *trl;
unifyWith(PM &p, Property *pp, TransitionRule *tr)
: pm(p), pr(pp), trl(tr){};
void operator()(Property *p) {
if (!pm.contains(p)) {
pm.add(p, new PropertySpace(p, trl));
} else {
// cout << "Adding rule " << *trl << " to " << *(pm.getData(p)) << "\n";
pm.getData(p)->add(trl);
};
pm.connect(pr, p);
};
};
struct makeSpace {
PM ±
makeSpace(PM &p) : pm(p){};
void operator()(Property *p) {
if (!pm.contains(p)) {
pm.add(p, new PropertySpace(p));
};
};
};
struct rulePartitioner {
PM ±
rulePartitioner(PM &p) : pm(p){};
void operator()(TransitionRule *tr) {
if (tr->isTrivial()) {
tr->distributeEnablers();
return;
};
Property *p =
tr->isIncreasing() ? *(tr->rhs->begin()) : *(tr->lhs->begin());
for_each(tr->lhs->begin(), tr->lhs->end(), unifyWith(pm, p, tr));
for_each(tr->rhs->begin(), tr->rhs->end(), unifyWith(pm, p, tr));
for_each(tr->enablers->begin(), tr->enablers->end(), makeSpace(pm));
};
};
void TransitionRule::distributeEnablers() {
if (op) {
MutexStore *m = MEX(op);
// The enabler mRecs in an op record the enabling property, the variable
// affected by the rule that is enabled and the part of the operator the
// rule comes from: START, MIDDLE or END
m->add(enablers->begin(), enablers->end(), var, opt);
}
};
PropertySpace::PropertySpace(Property *p, TransitionRule *t)
: properties(1, p), isStateValued(!t->isAttribute()), LSchecked(false) {
rules.insert(t);
};
void PropertySpace::add(TransitionRule *t) {
rules.insert(t);
isStateValued &= !t->isAttribute();
};
void PropertySpace::write(ostream &o) const {
o << "\nState space states:\n";
for_each(states.begin(), states.end(), ptrwriter< PropertyState >(o, "\n"));
o << "\nSpace properties: ";
for_each(properties.begin(), properties.end(),
ptrwriter< Property >(o, " "));
o << "\nSpace objects: ";
for_each(objects.begin(), objects.end(), ptrwriter< const_symbol >(o, " "));
o << "\nSpace rules:\n";
for_each(rules.begin(), rules.end(), ptrwriter< TransitionRule >(o, "\n"));
o << "Space is: " << (isStateValued ? "state valued" : "attribute valued");
};
ostream &operator<<(ostream &o, const PropertySpace &p) {
p.write(o);
return o;
};
PropertySpace *spaceSet(PM::DataSource &p) {
return PM::grabData(p)->finalise();
};
bool PropertySpace::isLockingSpace() {
if (LSchecked) return isLS;
LSchecked = true;
cout << "Complete check on locking spaces\n";
return false;
};
void TIMAnalyser::setUpSpaces() {
PM pts(&PSCombiner);
for_each(trules.begin(), trules.end(), rulePartitioner(pts));
transform(pts.begin(), pts.end(), inserter(propspaces, propspaces.begin()),
spaceSet);
// for_each(propspaces.begin(),propspaces.end(),ptrwriter<PropertySpace>(cout,"\n"));
};
// Need this because assembleMutexes is not const.
struct aMxs {
PropertySpace *p;
aMxs(PropertySpace *ps) : p(ps){};
void operator()(TransitionRule *tr) { p->assembleMutexes(tr); };
void operator()(Property *ps) { p->assembleMutexes(ps); };
};
struct aMxs1 {
TransitionRule *tr;
aMxs1(TransitionRule *t) : tr(t){};
void operator()(TransitionRule *t) { t->assembleMutex(tr); };
};
struct aMxs2 {
PropertySpace *ps;
Property *p;
aMxs2(PropertySpace *tps, Property *tp) : ps(tps), p(tp){};
void operator()(Property *tp) {
if (p <= tp) ps->assembleMutexes(p, tp);
};
};
/*
struct aMxs3 {
TransitionRule * tr;
aMxs3(TransitionRule * t) : tr(t) {};
void operator()(Property * p)
{
for(Property::SpaceIt i = p->begin();i != p->end();++i)
{
if((*i)->isState())
{
cout << *p << " is candidate enabler for
action " << tr->byWhat()->name->getName() << "\n";
(*i)->assembleMutexes(tr,p);
};
};
};
};
// tr is enabled by property p which appears in this PropertySpace
void PropertySpace::assembleMutexes(TransitionRule * tr,Property * p)
{
for_each(rules.begin(),rules.end(),aMxs1(tr));
};
*/
// This machinery might need to be reviewed to ensure it handles subtypes
// properly.
void PropertySpace::assembleMutexes(Property *p1, Property *p2) {
if (p1 == p2) {
if (p1->root()->arity() == 1) return;
// Same property - special case
SIterator s = begin();
for (; s != end(); ++s) {
if ((*s)->count(p1) > 1) {
break;
};
};
if (s == end()) {
// Got one...
OUTPUT cout << "Mutex between " << *p1 << " and " << *p2 << "\n";
cTPS(p1->root())->setMutex(p1->aPosn(), cTPS(p2->root()), p2->aPosn());
};
} else {
// Different properties
// If they only ever appear in different states then they are mutex...
SIterator s = begin();
for (; s != end(); ++s) {
if ((*s)->contains(p1) && (*s)->contains(p2)) {
break;
};
};
if (s == end()) {
// Got a mutex...
OUTPUT cout << "Mutex between " << *p1 << " and " << *p2 << "\n";
cTPS(p1->root())->setMutex(p1->aPosn(), cTPS(p2->root()), p2->aPosn());
cTPS(p2->root())->setMutex(p2->aPosn(), cTPS(p1->root()), p1->aPosn());
};
};
};
// This handles the mutexes that arise because an object cannot simultaneously
// make two different state transitions.
void TransitionRule::assembleMutex(TransitionRule *tr) {
if (op) {
OUTPUT cout << "Mutex caused by rules: " << *this << " ("
<< this->byWhat()->name->getName() << ") and " << *tr << " ("
<< tr->byWhat()->name->getName() << ")\n";
mutex::constructMutex(op, var, tr->op, tr->var, opt, tr->opt);
mutex::constructMutex(tr->op, tr->var, op, var, tr->opt, opt);
}
};
ostream &operator<<(ostream &o, opType opt) {
switch (opt) {
case INSTANT:
break;
case START:
o << "[start]";
break;
case END:
o << "[end]";
break;
case MIDDLE:
o << "[middle]";
break;
default:
break;
};
return o;
};
void mutex::write(ostream &o) const {
for (set< mutRec >::const_iterator i = argPairs.begin();
i != argPairs.end(); ++i) {
if (op1 == op2) {
o << "Cannot perform two concurrent '" << op1->name->getName()
<< "'s for same ";
if (getAt(op1->parameters, i->first)->type) {
o << getAt(op1->parameters, i->first)->type->getName();
} else {
o << i->first << "th argument";
};
o << " " << i->one << "-" << i->other << "\n";
} else {
o << "Mutex for '" << op1->name->getName() << "' and '"
<< op2->name->getName() << " args: " << i->first << " " << i->second
<< "\n";
o << "Mutex for '" << op1->name->getName() << "' and '"
<< op2->name->getName() << "' when using same ";
if (getAt(op1->parameters, i->first)->type) {
o << getAt(op1->parameters, i->first)->type->getName();
} else {
o << i->first << "th argument";
};
o << " " << i->one << "-" << i->other << "\n";
};
};
};
mutex *MutexStore::getMutex(operator_ *o) {
MutexRecord::iterator m = mutexes.find(o);
if (m == mutexes.end()) {
mutex *mx = new mutex(dynamic_cast< operator_ * >(this), o);
mutexes[o] = mx;
MEX(o)->mutexes[dynamic_cast< operator_ * >(this)] = mx;
return mx;
} else {
return m->second;
};
};
void MutexStore::showMutexes() {
operator_ *o = dynamic_cast< operator_ * >(this);
for (MutexRecord::iterator i = mutexes.begin(); i != mutexes.end(); ++i) {
if (i->first >= o) {
cout << *(i->second);
};
};
};
void showMutex(operator_ *op) {
TIM::MutexStore *tm = MEX(op);
if (tm) {
tm->showMutexes();
} else {
cout << "Not an action\n";
};
};
void completeMutexes(operator_ *op) {
TIM::MutexStore *tm = MEX(op);
if (tm) tm->additionalMutexes();
};
void PropertySpace::assembleMutexes(Property *p) {
for_each(properties.begin(), properties.end(), aMxs2(this, p));
};
// This is going to consider every rule against every rule in a space.
void PropertySpace::assembleMutexes(TransitionRule *tr) {
for_each(rules.begin(), rules.end(), aMxs1(tr));
// This was introduced as a way to handle the additional mutexes, but it is
// unnecessary.
// for_each(tr->getEnablers()->begin(),tr->getEnablers()->end(),
// aMxs3(tr));
};
void PropertySpace::assembleMutexes() {
for_each(rules.begin(), rules.end(), aMxs(this));
for_each(properties.begin(), properties.end(), aMxs(this));
};
void TIMAnalyser::assembleMutexes(PropertySpace *p) { p->assembleMutexes(); };
void TIMAnalyser::recordRulesInActions(PropertySpace *p) {
p->recordRulesInActions();
};
void TransitionRule::recordInAction(PropertySpace *p) {
TAS(op->name)->addStateChanger(p, this);
};
bool TIMactionSymbol::hasRuleFor(int prm) const {
for (RCiterator i = begin(); i != end(); ++i) {
if ((*i)->paramNum() == prm) return true;
};
return false;
};
struct recRiA {
PropertySpace *ps;
recRiA(PropertySpace *p) : ps(p){};
void operator()(TransitionRule *tr) { tr->recordInAction(ps); };
};
void PropertySpace::recordRulesInActions() {
for_each(rules.begin(), rules.end(), recRiA(this));
};
struct addMx1 {
operator_ *op;
const mRec ≺
addMx1(operator_ *o, const mRec &p) : op(o), pr(p){};
void operator()(PropertySpace *ps) {
// cout << "Property space: " << *ps << "\n";
// if(pr.opt == MIDDLE && !ps->isState()) return;
if (!ps->isState()) return;
ps->assembleMutexes(op, pr);
};
void operator()(TransitionRule *tr) { tr->assembleMutex(op, pr); };
};
struct addMx {
operator_ *mx;
addMx(operator_ *m) : mx(m){};
void operator()(const mRec &p) {
// cout << "For enabler " << *(p.first) << "\n";
// Work through all the PropertySpaces that p.first belongs to. Recall
// p.first is an enabler for the operator mx.
vector< Property * > ps((p.first)->matchers());
for (vector< Property * >::iterator i = ps.begin(); i != ps.end(); ++i) {
for_each((*i)->begin(), (*i)->end(), addMx1(mx, p));
};
};
};
void TransitionRule::assembleMutex(operator_ *o, const mRec &p) {
mutex::constructMutex(op, var, o, p.second, opt, p.opt);
mutex::constructMutex(o, p.second, op, var, p.opt, opt);
};
void PropertySpace::assembleMutexes(operator_ *op, const mRec &p) {
// Work through all the rules in the space
for_each(rules.begin(), rules.end(), addMx1(op, p));
};
void MutexStore::additionalMutexes() {
// Work through all the enabler mRecs of this action
// cout << "Considering enablers for action: " <<
// dynamic_cast<operator_*>(this)->name->getName() << "\n";
for_each(conditions.begin(), conditions.end(),
addMx(dynamic_cast< operator_ * >(this)));
// Work through all the invariant mRecs of this action
for_each(invariants.begin(), invariants.end(),
addMx(dynamic_cast< operator_ * >(this)));
};
bool checkRule(bool x, TransitionRule *tr) {
return x && !tr->isIncreasing();
};
Property *TransitionRule::candidateSplit() {
if (isIncreasing()) {
return *(rhs->begin());
};
if (isDecreasing()) {
return *(lhs->begin());
};
return 0;
};
void recordSV::operator()(Property *p) {
vector< int > cnts(ps->countsFor(p));
int mx = cnts.empty() ? 0 : *max_element(cnts.begin(), cnts.end());
int mn = cnts.empty() ? 0 : *min_element(cnts.begin(), cnts.end());
p->setSV(mx == 1, mn > 0);
if (mx == 1) {
sv.push_back(p);
#ifdef VERBOSE
cout << *p << " is single valued ";
if (mn > 0) cout << "and required";
cout << "\n";
#endif
};
};
bool PropertySpace::examine(vector< PropertySpace * > &as) {
// Leave this on to remind us to fix it!
//#ifdef VERBOSE
if (std::accumulate(rules.begin(), rules.end(), true, checkRule)) {
OUTPUT cout << "\nPotential pseudo space...\n"
<< "This will cause problems in several uses of TIM - tell "
"Derek to get on with fixing it!\n"
<< *this << "\n";
};
//#endif
while (!isStateValued && properties.size() > 1) {
// cout << "\nMultiple properties...looking for a
// splitter...\n"; cout << "Space is: " << *this << "\n";
for (set< TransitionRule * >::iterator i = rules.begin();
i != rules.end(); ++i) {
Property *p = (*i)->candidateSplit();
if (p) {
// cout << "Splitter is " << *p << "\n";
PropertySpace *ps = slice(p);
// cout << "Split into: " << *ps << "\nand:
//"
//<< *this << "\n";
while (ps->extend())
;
as.push_back(ps);
break;
};
};
};
if (isStateValued) {
if (!isStatic()) {
while (extend())
;
assembleMutexes();
};
return true;
};
return false;
};
typedef set< PropertyState * > PStates;
void doExamine::operator()(PropertySpace *p) {
if (p->examine(newas)) {
tan->propspaces.push_back(p);
} else {
newas.push_back(p);
};
};
template < class TI >
struct getConditionally {
bool cond;
Property *prop;
TI pit;
TI terminus;
typedef typename TI::value_type value_type;
typedef std::ptrdiff_t difference_type;
typedef typename TI::pointer pointer;
typedef typename TI::reference reference;
typedef std::input_iterator_tag iterator_category;
getConditionally(bool c, Property *p, TI pt, TI term)
: cond(c), prop(p), pit(pt), terminus(term) {
while (pit != terminus && (c ? (*pit == prop) : (*pit != prop))) ++pit;
};
Property *operator*() { return *pit; };
getConditionally< TI > &operator++() {
++pit;
while (pit != terminus && (cond ? (*pit == prop) : (*pit != prop))) ++pit;
return *this;
};
bool operator==(const getConditionally< TI > &x) const {
return pit == x.pit;
};
bool operator!=(const getConditionally< TI > &x) const {
return pit != x.pit;
};
};
template < class TI >
getConditionally< TI > getIt(bool c, Property *p, TI x1, TI x2) {
return getConditionally< TI >(c, p, x1, x2);
};
pair< PropertyState *, PropertyState * > PropertyState::split(Property *p) {
PropertyState *p1 = retrieve(tan, getIt(false, p, begin(), end()),
getIt(false, p, end(), end()));
PropertyState *p2 = retrieve(tan, getIt(true, p, begin(), end()),
getIt(true, p, end(), end()));
return make_pair(p1, p2);
};
TransitionRule *TransitionRule::splitRule(Property *p) {
if (find(lhs->begin(), lhs->end(), p) == lhs->end() &&
find(rhs->begin(), rhs->end(), p) == rhs->end()) {
return 0;
};
// cout << "This rule splits: " << *this << "\n";
pair< PropertyState *, PropertyState * > lhss, rhss;
PropertyState *ens;
// Need to remove all instances of p from the lhs/rhs of rule. Note that
// since we split rules that had a property in both sides the only way p can
// appear in both lhs and rhs is if one or other side contains nothing
// except p (possibly several copies).
lhss = lhs->split(p);
// cout << "Left splits to " << *(lhss.first) << " and " << *(lhss.second)
//<< "\n";
ens = enablers;
enablers = enablers->add(lhss.first->begin(), lhss.first->end());
lhs = lhss.second;
ens = ens->add(lhss.second->begin(), lhss.second->end());
rhss = rhs->split(p);
rhs = rhss.second;
// cout << "Right splits to " << *(rhss.first) << " and " << *(rhss.second)
//<< "\n";
// cout << "Enablers are now: " << *ens << " and " << *enablers << "\n";
TransitionRule *trnew =
new TransitionRule(tan, op, var, ens, lhss.first, rhss.first, opt);
// cout << "Objects are: ";
// for_each(objects.begin(),objects.end(),ptrwriter<const_symbol>(cout,"
//")); cout << "\n";
return trnew;
};
TransitionRule::TransitionRule(TransitionRule *tr, PropertyState *e,
PropertyState *l, PropertyState *r)
: tan(tr->tan),
op(tr->op),
opt(tr->opt),
var(tr->var),
enablers(e),
lhs(l),
rhs(r),
objects(){};
struct ruleSplitOn {
set< TransitionRule * > &xrules;
set< TransitionRule * > rules;
Property *prop;
ruleSplitOn(Property *p, set< TransitionRule * > &rs)
: xrules(rs), prop(p){};
void operator()(TransitionRule *tr) {
TransitionRule *t = tr->splitRule(prop);
if (t) xrules.insert(t);
if (!tr->isTrivial()) {
rules.insert(tr);
};
};
operator set< TransitionRule * >() { return rules; };
};
void splitRules(set< TransitionRule * > &rules, Property *p,
set< TransitionRule * > &xrules) {
rules = for_each(rules.begin(), rules.end(), ruleSplitOn(p, xrules));
};
void splitObjects(vector< TIMobjectSymbol * > &tobs, Property *p,
vector< TIMobjectSymbol * > &xtobs){
// I think we should be checking whether the objects are really valid for
// both
// spaces - in particular if the new space is a state space we should be
// filtering it.
//
// cout << "SYMBOLS: ";
// for_each(tobs.begin(),tobs.end(),ptrwriter<const_symbol>(cout,"
//"));
// cout << "\n";
};
void splitStates(PStates &states, Property *p, PStates &xstates) {
PStates::iterator e = states.end();
PStates newStates;
for (PStates::iterator i = states.begin(); i != e; ++i) {
pair< PropertyState *, PropertyState * > pp = (*i)->split(p);
if (!pp.first->empty()) xstates.insert(pp.first);
if (!pp.second->empty()) newStates.insert(pp.second);
};
states.swap(newStates);
};
bool ruleCheck(bool t, TransitionRule *tr) {
return t && !tr->isAttribute();
};
void PropertySpace::checkStateValued() {
isStateValued = accumulate(rules.begin(), rules.end(), true, ruleCheck);
};
PropertySpace *PropertySpace::slice(Property *p) {
// Also need to remove split property from this space and correct the
// relevant references to membership of property spaces.
PropertySpace *ps = new PropertySpace(p);
ps->isStateValued = false;
splitStates(states, p, ps->states);
// cout << "About to split rules in " << *this << "\n";
splitRules(rules, p, ps->rules);
// cout << "OBJECTS: ";
// for_each(objects.begin(),objects.end(),ptrwriter<const_symbol>(cout,"
// ")); cout << "\n";
splitObjects(objects, p, ps->objects);
properties.erase(remove(properties.begin(), properties.end(), p),
properties.end());
checkStateValued();
return ps;
};
bool Property::applicableTo(TypeChecker &tc, const pddl_type *tp) const {
// Caution: won't work if predicate has an either type spec.
pddl_type *x = (*(EPS(predicate)->tcBegin() + posn))->type;
return tc.subType(tp, x);
};
bool PropertySpace::applicableTo(TypeChecker &tc, const pddl_type *tp) const {
for (vector< Property * >::const_iterator i = properties.begin();
i != properties.end(); ++i) {
if (!(*i)->applicableTo(tc, tp)) return false;
};
return true;
};
set< PropertySpace * > TIMAnalyser::relevant(pddl_type *tp) {
// Really only want to use this on leaf types. Other types are more of a
// problem at both this end and the caller's end. This is only a temporary
// management of the situation.
if (!tcheck.isLeafType(tp)) {
return set< PropertySpace * >();
};
set< PropertySpace * > st;
for (vector< PropertySpace * >::iterator i = propspaces.begin();
i != propspaces.end(); ++i) {
if ((*i)->applicableTo(tcheck, tp)) {
st.insert(*i);
};
};
return st;
};
}; // namespace TIM
| 30.798387 | 122 | 0.558214 | tmigimatsu |
937ef1f4b01111547029f076d6f0900bb2256e10 | 6,244 | hpp | C++ | utils/convsym/input/AS_Listing.hpp | vladikcomper/md-modules | 24f652a036dc63f295173369dddfffb3be89bdd7 | [
"MIT"
] | 9 | 2018-01-22T06:44:43.000Z | 2022-03-26T18:57:40.000Z | utils/convsym/input/AS_Listing.hpp | vladikcomper/md-modules | 24f652a036dc63f295173369dddfffb3be89bdd7 | [
"MIT"
] | null | null | null | utils/convsym/input/AS_Listing.hpp | vladikcomper/md-modules | 24f652a036dc63f295173369dddfffb3be89bdd7 | [
"MIT"
] | null | null | null |
/* ------------------------------------------------------------ *
* ConvSym utility version 2.7 *
* Input wrapper for the AS listing format *
* ------------------------------------------------------------ */
struct Input__AS_Listing : public InputWrapper {
Input__AS_Listing() : InputWrapper() { // Constructor
}
~Input__AS_Listing() { // Destructor
}
/**
* Interface for input file parsing
*
* @param path Input file path
* @param baseOffset Base offset for the parsed records (subtracted from the fetched offsets to produce internal offsets)
* @param offsetLeftBoundary Left boundary for the calculated offsets
* @param offsetRightBoundary Right boundary for the calculated offsets
* @param offsetMask Mask applied to offset after base offset subtraction
*
* @return Sorted associative array (map) of found offsets and their corresponding symbol names
*/
std::multimap<uint32_t, std::string>
parse( const char *fileName,
uint32_t baseOffset = 0x000000,
uint32_t offsetLeftBoundary = 0x000000,
uint32_t offsetRightBoundary = 0x3FFFFF,
uint32_t offsetMask = 0xFFFFFF,
const char * opts = "" ) {
const int sBufferSize = 1024;
// Variables
uint8_t sBuffer[ sBufferSize ];
std::multimap<uint32_t, std::string> SymbolMap;
IO::FileInput input = IO::FileInput( fileName, IO::text );
if ( !input.good() ) { throw "Couldn't open input file"; }
uint32_t lastSymbolOffset = -1; // tracks symbols offsets to ignore sections where PC is reset (mainly Z80 stuff)
// For every string in a listing file ...
while ( input.readLine( sBuffer, sBufferSize ) >= 0 ) {
// Known issues for the Sonic 2 disassembly:
// * Some macros somehow define labels that looks like global ones (notably, _MOVE and such)
// * Labels from injected Z80 code sometimes make it to the list ...
uint8_t* ptr = sBuffer; // WARNING: dereffed type should be UNSIGNED, as it's used for certain range-based optimizations
// Check if this line has file idention number (pattern: "(d)", where d is a decimal digit)
if ( *ptr == '(' ) {
bool foundDigits = false;
ptr++;
// Cycle through as long as found characters are digits
while ( (unsigned)(*ptr-'0')<10 ) { foundDigits=true; ptr++; }
// If digit pattern doesn't end with ")" as expected, or no digits were found at all, stop
if ( *ptr++ != ')' || !foundDigits ) continue;
}
// Ensure line has a proper number (pattern: "ddddd/", where d is any digit)
{
bool foundDigits = false;
while ( *ptr == ' ' ) { ptr++; } // skip spaces, if present
// Cycle through as long as found characters are digits
while ( (unsigned)(*ptr-'0')<10 ) { foundDigits=true; ptr++; }
// If digit pattern doesn't end with "/" as expected, or no digits were found at all, stop
if ( *ptr++ != '/' || !foundDigits ) continue;
}
// Ensure line has a proper offset (pattern: "hhhh :", where h is a hexidecimal character)
while ( *ptr == ' ' ) { ptr++; } // skip spaces, if present
uint8_t* const sOffset = ptr; // remember location, where offset should presumably start
{
bool foundHexDigits = false;
// Cycle though as longs as proper hexidecimal characters are fetched
while ( (unsigned)(*ptr-'0')<10 || (unsigned)(*ptr-'A')<6 ) {
foundHexDigits = true;
ptr++;
}
if ( *ptr == 0x00 ) continue; // break if end of line was reached
*ptr++ = 0x00; // separate string pointered by "offset" variable from the rest of the line
while ( *ptr == ' ' ) { ptr++; } // skip spaces ...
// If offset pattern doesn't end with ":" as expected, or no hex characters were found at all, stop
if ( *ptr++ != ':' || !foundHexDigits ) continue;
}
// Check if line matches a label definition ...
if ( *ptr == ' ' && *(ptr+1) == '(' ) continue;
while ( *ptr && (ptr-sBuffer < 40) ) { ptr++; } // align to column 40 (where line starts)
while ( *ptr==' ' || *ptr=='\t' ) { ptr++; } // skip spaces or tabs, if present
uint8_t* const label = ptr; // remember location, where label presumably starts...
// The first character should be a latin letter (A..Z or a..z)
if ( (unsigned)(*ptr-'A')<26 || (unsigned)(*ptr-'a')<26 ) {
// Other characters should be letters are digits or _ char
while (
(unsigned)(*ptr-'A')<26 || (unsigned)(*ptr-'a')<26 || (unsigned)(*ptr-'0')<10 || *ptr=='_'
) { ptr++; }
// If the word is the only on the line and it ends with ":", treat it as a label
if ( *ptr==':' ) {
*ptr++ = 0x00; // separate string pointered by "label" variable from the rest of the line
// Convert offset to uint32_t
uint32_t offset = 0;
for ( uint8_t* c = sOffset; *c; c++ ) {
offset = offset*0x10 + (((unsigned)(*c-'0')<10) ? (*c-'0') : (*c-('A'-10)));
}
// Add label to the symbols table, if:
// 1) Its absolute offset is higher than the previous offset successfully added
// 2) When base offset is subtracted and the mask is applied, the resulting offset is within allowed boundaries
if ( (lastSymbolOffset == (uint32_t)-1) || (offset >= lastSymbolOffset) ) {
// Check if this is a label after ds or rs macro ...
while ( *ptr==' ' || *ptr=='\t' ) { ptr++; } // skip spaces or tabs, if present
if ( *ptr == 'd' && *(ptr+1) == 's' && *(ptr+2)=='.' ) continue;
if ( *ptr == 'r' && *(ptr+1) == 's' && *(ptr+2)=='.' ) continue;
// Add label to the symbols table
uint32_t converted_offset = (offset - baseOffset) & offsetMask;
if ( converted_offset >= offsetLeftBoundary && converted_offset <= offsetRightBoundary ) { // if offset is within range, add it ...
// Add label to the symbols map
SymbolMap.insert({converted_offset, std::string((const char*)label)});
lastSymbolOffset = offset; // stores an absolute offset, not the converted one ...
}
}
else {
IO::Log( IO::debug, "Symbol %s at offset %X ignored: its offset is less than the previous symbol successfully fetched", label, offset );
}
}
}
}
return SymbolMap;
}
};
| 39.27044 | 142 | 0.603459 | vladikcomper |
937f520ec2e8b59618931f94b3c31d1372db1b4e | 97 | cpp | C++ | cpp-old/lib/html/uri_map.cpp | boryas/hcppd | 86e7418bb5b6852e448d1f1a60029d2798c0b838 | [
"MIT"
] | 1 | 2018-08-25T08:10:07.000Z | 2018-08-25T08:10:07.000Z | cpp-old/lib/html/uri_map.cpp | boryas/hcppd | 86e7418bb5b6852e448d1f1a60029d2798c0b838 | [
"MIT"
] | 22 | 2016-09-21T05:46:18.000Z | 2016-12-18T04:05:18.000Z | cpp-old/lib/html/uri_map.cpp | boryas/ssfs | 86e7418bb5b6852e448d1f1a60029d2798c0b838 | [
"MIT"
] | null | null | null | #include "uri_map.h"
namespace ssfs {
namespace html {
} // namespace html
} // namespace ssfs
| 12.125 | 20 | 0.690722 | boryas |
93836cdfcd44be54ec3a233732f609adb087e450 | 2,317 | cpp | C++ | Source/Scene/LightProbeNode.cpp | PolyAH/RealTimeGI | 372638568ff22a4dea9c1ff448cec42e3e25aaf2 | [
"MIT"
] | 6 | 2021-10-31T14:43:04.000Z | 2022-03-12T12:56:27.000Z | Source/Scene/LightProbeNode.cpp | PolyAH/RealTimeGI | 372638568ff22a4dea9c1ff448cec42e3e25aaf2 | [
"MIT"
] | null | null | null | Source/Scene/LightProbeNode.cpp | PolyAH/RealTimeGI | 372638568ff22a4dea9c1ff448cec42e3e25aaf2 | [
"MIT"
] | null | null | null | // Copyright (c) 2021 Ammar Herzallah
//
// 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 "LightProbeNode.h"
#include "Render/RenderData/RenderLight.h"
#include "Render/RenderData/RenderTypes.h"
LightProbeNode::LightProbeNode()
: mRadius(100.0f)
, mIsSelected(false)
{
mType = ENodeType::LightProbe;
}
LightProbeNode::~LightProbeNode()
{
if (mRenderLightProbe)
mRenderLightProbe->Destroy();
}
void LightProbeNode::SetRadius(float radius)
{
mRadius = radius;
if (mRenderLightProbe)
{
mRenderLightProbe->SetRadius(mRadius);
mRenderLightProbe->SetDirty(true);
}
}
glm::vec3 LightProbeNode::GetPosition() const
{
return GetTransform().GetTranslate();
}
void LightProbeNode::OnTransform()
{
if (mRenderLightProbe)
{
mRenderLightProbe->SetPosition(GetTransform().GetTranslate());
mRenderLightProbe->SetDirty(true);
}
}
void LightProbeNode::UpdateRenderLightProbe()
{
CHECK(!mRenderLightProbe);
mRenderLightProbe = UniquePtr<RenderLightProbe>(new RenderLightProbe());
mRenderLightProbe->Create();
mRenderLightProbe->SetDirty(INVALID_INDEX);
mRenderLightProbe->SetRadius(mRadius);
mRenderLightProbe->SetPosition(GetTransform().GetTranslate());
}
void LightProbeNode::SetDirty()
{
mRenderLightProbe->SetDirty(LIGHT_PROBES_BOUNCES);
}
| 23.40404 | 81 | 0.761761 | PolyAH |
9387d45fa3768e77f825af46d81ffcb76b10d07e | 16,669 | cc | C++ | content/renderer/media/media_stream_video_source_unittest.cc | anirudhSK/chromium | a8f23c87e656ab9ba49de9ccccbc53f614cdcb41 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/renderer/media/media_stream_video_source_unittest.cc | anirudhSK/chromium | a8f23c87e656ab9ba49de9ccccbc53f614cdcb41 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/renderer/media/media_stream_video_source_unittest.cc | anirudhSK/chromium | a8f23c87e656ab9ba49de9ccccbc53f614cdcb41 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2015-04-17T13:19:09.000Z | 2021-10-21T12:55:15.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include <vector>
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "content/renderer/media/media_stream_video_source.h"
#include "content/renderer/media/mock_media_constraint_factory.h"
#include "content/renderer/media/mock_media_stream_dependency_factory.h"
#include "content/renderer/media/mock_media_stream_video_source.h"
#include "media/base/video_frame.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace content {
class MediaStreamVideoSourceTest
: public ::testing::Test {
public:
MediaStreamVideoSourceTest()
: number_of_successful_constraints_applied_(0),
number_of_failed_constraints_applied_(0),
mock_source_(new MockMediaStreamVideoSource(&factory_, true)) {
media::VideoCaptureFormats formats;
formats.push_back(media::VideoCaptureFormat(
gfx::Size(1280, 720), 30, media::PIXEL_FORMAT_I420));
formats.push_back(media::VideoCaptureFormat(
gfx::Size(640, 480), 30, media::PIXEL_FORMAT_I420));
formats.push_back(media::VideoCaptureFormat(
gfx::Size(352, 288), 30, media::PIXEL_FORMAT_I420));
formats.push_back(media::VideoCaptureFormat(
gfx::Size(320, 240), 30, media::PIXEL_FORMAT_I420));
mock_source_->SetSupportedFormats(formats);
webkit_source_.initialize(base::UTF8ToUTF16("dummy_source_id"),
blink::WebMediaStreamSource::TypeVideo,
base::UTF8ToUTF16("dummy_source_name"));
webkit_source_.setExtraData(mock_source_);
}
protected:
// Create a track that's associated with |webkit_source_|.
blink::WebMediaStreamTrack CreateTrack(
const std::string& id,
const blink::WebMediaConstraints& constraints) {
blink::WebMediaStreamTrack track;
track.initialize(base::UTF8ToUTF16(id), webkit_source_);
MediaStreamVideoSource* source =
static_cast<MediaStreamVideoSource*>(track.source().extraData());
source->AddTrack(track,
constraints,
base::Bind(
&MediaStreamVideoSourceTest::OnConstraintsApplied,
base::Unretained(this)));
return track;
}
blink::WebMediaStreamTrack CreateTrackAndStartSource(
const blink::WebMediaConstraints& constraints,
int expected_width,
int expected_height,
int expected_frame_rate) {
blink::WebMediaStreamTrack track = CreateTrack("123", constraints);
mock_source_->CompleteGetSupportedFormats();
const media::VideoCaptureParams& format = mock_source()->start_params();
EXPECT_EQ(expected_width, format.requested_format.frame_size.width());
EXPECT_EQ(expected_height, format.requested_format.frame_size.height());
EXPECT_EQ(expected_frame_rate, format.requested_format.frame_rate);
MediaStreamVideoSource* source =
static_cast<MediaStreamVideoSource*>(track.source().extraData());
EXPECT_TRUE(source->GetAdapter() != NULL);
EXPECT_EQ(0, NumberOfSuccessConstraintsCallbacks());
mock_source_->StartMockedSource();
// Once the source has started successfully we expect that the
// ConstraintsCallback in MediaStreamSource::AddTrack completes.
EXPECT_EQ(1, NumberOfSuccessConstraintsCallbacks());
return track;
}
int NumberOfSuccessConstraintsCallbacks() const {
return number_of_successful_constraints_applied_;
}
int NumberOfFailedConstraintsCallbacks() const {
return number_of_failed_constraints_applied_;
}
MockMediaStreamVideoSource* mock_source() { return mock_source_; }
// Test that the source crops to the requested max width and
// height even though the camera delivers a larger frame.
// TODO(perkj): Frame resolution should be verified in MediaStreamVideoTrack
// and not in the adapter.
void TestSourceCropFrame(int capture_width,
int capture_height,
const blink::WebMediaConstraints& constraints,
int expected_height,
int expected_width) {
// Expect the source to start capture with the supported resolution.
CreateTrackAndStartSource(constraints, capture_width, capture_height , 30);
ASSERT_TRUE(mock_source()->GetAdapter());
MockVideoSource* adapter = static_cast<MockVideoSource*>(
mock_source()->GetAdapter());
EXPECT_EQ(0, adapter->GetFrameNum());
scoped_refptr<media::VideoFrame> frame =
media::VideoFrame::CreateBlackFrame(gfx::Size(capture_width,
capture_height));
mock_source()->DeliverVideoFrame(frame);
EXPECT_EQ(1, adapter->GetFrameNum());
// Expect the delivered frame to be cropped.
EXPECT_EQ(expected_height, adapter->GetLastFrameWidth());
EXPECT_EQ(expected_width, adapter->GetLastFrameHeight());
}
private:
void OnConstraintsApplied(MediaStreamSource* source, bool success) {
ASSERT_EQ(source, webkit_source_.extraData());
if (success)
++number_of_successful_constraints_applied_;
else
++number_of_failed_constraints_applied_;
}
int number_of_successful_constraints_applied_;
int number_of_failed_constraints_applied_;
MockMediaStreamDependencyFactory factory_;
blink::WebMediaStreamSource webkit_source_;
// |mock_source_| is owned by |webkit_source_|.
MockMediaStreamVideoSource* mock_source_;
};
TEST_F(MediaStreamVideoSourceTest, AddTrackAndStartSource) {
blink::WebMediaConstraints constraints;
constraints.initialize();
blink::WebMediaStreamTrack track = CreateTrack("123", constraints);
mock_source()->CompleteGetSupportedFormats();
mock_source()->StartMockedSource();
EXPECT_EQ(1, NumberOfSuccessConstraintsCallbacks());
}
TEST_F(MediaStreamVideoSourceTest, AddTwoTracksBeforeSourceStarts) {
blink::WebMediaConstraints constraints;
constraints.initialize();
blink::WebMediaStreamTrack track1 = CreateTrack("123", constraints);
mock_source()->CompleteGetSupportedFormats();
blink::WebMediaStreamTrack track2 = CreateTrack("123", constraints);
EXPECT_EQ(0, NumberOfSuccessConstraintsCallbacks());
mock_source()->StartMockedSource();
EXPECT_EQ(2, NumberOfSuccessConstraintsCallbacks());
}
TEST_F(MediaStreamVideoSourceTest, AddTrackAfterSourceStarts) {
blink::WebMediaConstraints constraints;
constraints.initialize();
blink::WebMediaStreamTrack track1 = CreateTrack("123", constraints);
mock_source()->CompleteGetSupportedFormats();
mock_source()->StartMockedSource();
EXPECT_EQ(1, NumberOfSuccessConstraintsCallbacks());
blink::WebMediaStreamTrack track2 = CreateTrack("123", constraints);
EXPECT_EQ(2, NumberOfSuccessConstraintsCallbacks());
}
TEST_F(MediaStreamVideoSourceTest, AddTrackAndFailToStartSource) {
blink::WebMediaConstraints constraints;
constraints.initialize();
blink::WebMediaStreamTrack track = CreateTrack("123", constraints);
mock_source()->CompleteGetSupportedFormats();
mock_source()->FailToStartMockedSource();
EXPECT_EQ(1, NumberOfFailedConstraintsCallbacks());
}
TEST_F(MediaStreamVideoSourceTest, AddTwoTracksBeforeGetSupportedFormats) {
blink::WebMediaConstraints constraints;
constraints.initialize();
blink::WebMediaStreamTrack track1 = CreateTrack("123", constraints);
blink::WebMediaStreamTrack track2 = CreateTrack("123", constraints);
mock_source()->CompleteGetSupportedFormats();
mock_source()->StartMockedSource();
EXPECT_EQ(2, NumberOfSuccessConstraintsCallbacks());
}
// Test that the capture output is CIF if we set max constraints to CIF.
// and the capture device support CIF.
TEST_F(MediaStreamVideoSourceTest, MandatoryConstraintCif5Fps) {
MockMediaConstraintFactory factory;
factory.AddMandatory(MediaStreamVideoSource::kMaxWidth, 352);
factory.AddMandatory(MediaStreamVideoSource::kMaxHeight, 288);
factory.AddMandatory(MediaStreamVideoSource::kMaxFrameRate, 5);
CreateTrackAndStartSource(factory.CreateWebMediaConstraints(), 352, 288, 5);
}
// Test that the capture output is 720P if the camera support it and the
// optional constraint is set to 720P.
TEST_F(MediaStreamVideoSourceTest, MandatoryMinVgaOptional720P) {
MockMediaConstraintFactory factory;
factory.AddMandatory(MediaStreamVideoSource::kMinWidth, 640);
factory.AddMandatory(MediaStreamVideoSource::kMinHeight, 480);
factory.AddOptional(MediaStreamVideoSource::kMinWidth, 1280);
factory.AddOptional(MediaStreamVideoSource::kMinAspectRatio,
1280.0 / 720);
CreateTrackAndStartSource(factory.CreateWebMediaConstraints(), 1280, 720, 30);
}
// Test that the capture output have aspect ratio 4:3 if a mandatory constraint
// require it even if an optional constraint request a higher resolution
// that don't have this aspect ratio.
TEST_F(MediaStreamVideoSourceTest, MandatoryAspectRatio4To3) {
MockMediaConstraintFactory factory;
factory.AddMandatory(MediaStreamVideoSource::kMinWidth, 640);
factory.AddMandatory(MediaStreamVideoSource::kMinHeight, 480);
factory.AddMandatory(MediaStreamVideoSource::kMaxAspectRatio,
640.0 / 480);
factory.AddOptional(MediaStreamVideoSource::kMinWidth, 1280);
CreateTrackAndStartSource(factory.CreateWebMediaConstraints(), 640, 480, 30);
}
// Test that ApplyConstraints fail if the mandatory aspect ratio
// is set higher than supported.
TEST_F(MediaStreamVideoSourceTest, MandatoryAspectRatioTooHigh) {
MockMediaConstraintFactory factory;
factory.AddMandatory(MediaStreamVideoSource::kMinAspectRatio, 2);
CreateTrack("123", factory.CreateWebMediaConstraints());
mock_source()->CompleteGetSupportedFormats();
EXPECT_EQ(1, NumberOfFailedConstraintsCallbacks());
}
// Test that the source ignores an optional aspect ratio that is higher than
// supported.
TEST_F(MediaStreamVideoSourceTest, OptionalAspectRatioTooHigh) {
MockMediaConstraintFactory factory;
factory.AddOptional(MediaStreamVideoSource::kMinAspectRatio, 2);
CreateTrack("123", factory.CreateWebMediaConstraints());
mock_source()->CompleteGetSupportedFormats();
const media::VideoCaptureParams& params = mock_source()->start_params();
double aspect_ratio =
static_cast<double>(params.requested_format.frame_size.width()) /
params.requested_format.frame_size.height();
EXPECT_LT(aspect_ratio, 2);
}
// Test that the source starts video with the default resolution if the
// that is the only supported.
TEST_F(MediaStreamVideoSourceTest, DefaultCapability) {
media::VideoCaptureFormats formats;
formats.push_back(media::VideoCaptureFormat(
gfx::Size(MediaStreamVideoSource::kDefaultWidth,
MediaStreamVideoSource::kDefaultHeight),
MediaStreamVideoSource::kDefaultFrameRate,
media::PIXEL_FORMAT_I420));
mock_source()->SetSupportedFormats(formats);
blink::WebMediaConstraints constraints;
constraints.initialize();
CreateTrackAndStartSource(constraints,
MediaStreamVideoSource::kDefaultWidth,
MediaStreamVideoSource::kDefaultHeight,
30);
}
TEST_F(MediaStreamVideoSourceTest, InvalidMandatoryConstraint) {
MockMediaConstraintFactory factory;
factory.AddMandatory("weird key", 640);
CreateTrack("123", factory.CreateWebMediaConstraints());
mock_source()->CompleteGetSupportedFormats();
EXPECT_EQ(1, NumberOfFailedConstraintsCallbacks());
}
// Test that the source ignores an unknown optional constraint.
TEST_F(MediaStreamVideoSourceTest, InvalidOptionalConstraint) {
MockMediaConstraintFactory factory;
factory.AddOptional("weird key", 640);
CreateTrackAndStartSource(factory.CreateWebMediaConstraints(),
MediaStreamVideoSource::kDefaultWidth,
MediaStreamVideoSource::kDefaultHeight,
30);
}
// Tests that the source starts video with the max width and height set by
// constraints for screencast.
TEST_F(MediaStreamVideoSourceTest, ScreencastResolutionWithConstraint) {
media::VideoCaptureFormats formats;
formats.push_back(media::VideoCaptureFormat(
gfx::Size(480, 270), 30, media::PIXEL_FORMAT_I420));
mock_source()->SetSupportedFormats(formats);
MockMediaConstraintFactory factory;
factory.AddMandatory(MediaStreamVideoSource::kMaxWidth, 480);
factory.AddMandatory(MediaStreamVideoSource::kMaxHeight, 270);
CreateTrackAndStartSource(factory.CreateWebMediaConstraints(), 480, 270, 30);
EXPECT_EQ(480, mock_source()->max_requested_height());
EXPECT_EQ(270, mock_source()->max_requested_width());
}
// Test that optional constraints are applied in order.
TEST_F(MediaStreamVideoSourceTest, OptionalConstraints) {
MockMediaConstraintFactory factory;
// Min width of 2056 pixels can not be fulfilled.
factory.AddOptional(MediaStreamVideoSource::kMinWidth, 2056);
factory.AddOptional(MediaStreamVideoSource::kMinWidth, 641);
// Since min width is set to 641 pixels, max width 640 can not be fulfilled.
factory.AddOptional(MediaStreamVideoSource::kMaxWidth, 640);
CreateTrackAndStartSource(factory.CreateWebMediaConstraints(), 1280, 720, 30);
}
// Test that the webrtc video adapter can be created and that it received
// video frames if the source deliver video frames.
TEST_F(MediaStreamVideoSourceTest, AdapterReceiveVideoFrame) {
MockMediaConstraintFactory factory;
CreateTrackAndStartSource(factory.CreateWebMediaConstraints(),
MediaStreamVideoSource::kDefaultWidth,
MediaStreamVideoSource::kDefaultHeight,
MediaStreamVideoSource::kDefaultFrameRate);
ASSERT_TRUE(mock_source()->GetAdapter());
MockVideoSource* adapter = static_cast<MockVideoSource*>(
mock_source()->GetAdapter());
EXPECT_EQ(0, adapter->GetFrameNum());
scoped_refptr<media::VideoFrame> frame =
media::VideoFrame::CreateBlackFrame(
gfx::Size(MediaStreamVideoSource::kDefaultWidth,
MediaStreamVideoSource::kDefaultHeight));
mock_source()->DeliverVideoFrame(frame);
EXPECT_EQ(1, adapter->GetFrameNum());
EXPECT_EQ(MediaStreamVideoSource::kDefaultWidth,
adapter->GetLastFrameWidth());
EXPECT_EQ(MediaStreamVideoSource::kDefaultHeight,
adapter->GetLastFrameHeight());
}
// Test that the source crops to the requested max width and
// height even though the camera delivers a larger frame.
TEST_F(MediaStreamVideoSourceTest, DeliverCroppedVideoFrameOptional640360) {
MockMediaConstraintFactory factory;
factory.AddOptional(MediaStreamVideoSource::kMaxWidth, 640);
factory.AddOptional(MediaStreamVideoSource::kMaxHeight, 360);
TestSourceCropFrame(640, 480, factory.CreateWebMediaConstraints(), 640, 360);
}
TEST_F(MediaStreamVideoSourceTest, DeliverCroppedVideoFrameMandatory640360) {
MockMediaConstraintFactory factory;
factory.AddMandatory(MediaStreamVideoSource::kMaxWidth, 640);
factory.AddMandatory(MediaStreamVideoSource::kMaxHeight, 360);
TestSourceCropFrame(640, 480, factory.CreateWebMediaConstraints(), 640, 360);
}
TEST_F(MediaStreamVideoSourceTest, DeliverCroppedVideoFrameMandatory732489) {
MockMediaConstraintFactory factory;
factory.AddMandatory(MediaStreamVideoSource::kMaxWidth, 732);
factory.AddMandatory(MediaStreamVideoSource::kMaxHeight, 489);
factory.AddMandatory(MediaStreamVideoSource::kMinWidth, 732);
factory.AddMandatory(MediaStreamVideoSource::kMinWidth, 489);
TestSourceCropFrame(1280, 720, factory.CreateWebMediaConstraints(), 732, 489);
}
// Test that the source crops to the requested max width and
// height even though the requested frame has odd size.
TEST_F(MediaStreamVideoSourceTest, DeliverCroppedVideoFrame637359) {
MockMediaConstraintFactory factory;
factory.AddOptional(MediaStreamVideoSource::kMaxWidth, 637);
factory.AddOptional(MediaStreamVideoSource::kMaxHeight, 359);
TestSourceCropFrame(640, 480, factory.CreateWebMediaConstraints(), 637, 359);
}
TEST_F(MediaStreamVideoSourceTest, DeliverSmallerSizeWhenTooLargeMax) {
MockMediaConstraintFactory factory;
factory.AddOptional(MediaStreamVideoSource::kMaxWidth, 1920);
factory.AddOptional(MediaStreamVideoSource::kMaxHeight, 1080);
factory.AddOptional(MediaStreamVideoSource::kMinWidth, 1280);
factory.AddOptional(MediaStreamVideoSource::kMinHeight, 720);
TestSourceCropFrame(1280, 720, factory.CreateWebMediaConstraints(),
1280, 720);
}
} // namespace content
| 42.741026 | 80 | 0.758534 | anirudhSK |
938b6958a01ceaf9e93de67c5cf8d79b78e5fdfb | 7,668 | cpp | C++ | test/oauth1_unittests.cpp | ColdOrange/http-cpp | dda4f41032485d23bc33200834e3cb2957212da3 | [
"MIT"
] | 3 | 2016-05-17T11:40:55.000Z | 2018-06-05T11:06:44.000Z | test/oauth1_unittests.cpp | ColdOrange/http-cpp | dda4f41032485d23bc33200834e3cb2957212da3 | [
"MIT"
] | 3 | 2015-01-06T09:36:27.000Z | 2018-09-03T20:10:37.000Z | test/oauth1_unittests.cpp | ColdOrange/http-cpp | dda4f41032485d23bc33200834e3cb2957212da3 | [
"MIT"
] | 9 | 2015-01-06T02:00:21.000Z | 2022-02-21T14:47:08.000Z | //
// The MIT License (MIT)
//
// Copyright (c) 2013 by Konstantin (Kosta) Baumann & Autodesk Inc.
//
// 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 <cute/cute.hpp>
#include <http-cpp/oauth1/client.hpp>
#include <http-cpp/oauth1/utils.hpp>
CUTE_TEST(
"Test http::oauth1::create_oauth_parameters() method work properly",
"[http],[oauth1],[create_oauth_parameters]"
) {
auto const consumer_key = "xvz1evFS4wEEPTGEFPHBog";
auto const token_key = "370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb";
auto const timestamp = "1318622958";
auto const nonce = "kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg";
auto const signature = "tnnArxj06cWHq44gCs1OSKk/jLY=";
auto const sig_method = "HMAC-SHA1";
auto const version = "1.0";
auto const header_key_expected = "Authorization";
auto const header_value_expected = ""
"OAuth "
"oauth_consumer_key=\"xvz1evFS4wEEPTGEFPHBog\", "
"oauth_nonce=\"kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg\", "
"oauth_signature=\"tnnArxj06cWHq44gCs1OSKk%2FjLY%3D\", "
"oauth_signature_method=\"HMAC-SHA1\", "
"oauth_timestamp=\"1318622958\", "
"oauth_token=\"370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb\", "
"oauth_version=\"1.0\"";
auto params = http::oauth1::create_oauth_parameters(
consumer_key, token_key, timestamp, nonce, signature
);
auto header = http::oauth1::create_oauth_header(params);
CUTE_ASSERT(params["oauth_consumer_key"] == consumer_key);
CUTE_ASSERT(params["oauth_token"] == token_key);
CUTE_ASSERT(params["oauth_timestamp"] == timestamp);
CUTE_ASSERT(params["oauth_nonce"] == nonce);
CUTE_ASSERT(params["oauth_signature"] == signature);
CUTE_ASSERT(params["oauth_signature_method"] == sig_method);
CUTE_ASSERT(params["oauth_version"] == version);
CUTE_ASSERT(header.first == header_key_expected);
CUTE_ASSERT(header.second == header_value_expected);
}
CUTE_TEST(
"Test http::oauth1::create_signature_base() method work properly",
"[http],[oauth1],[create_signature_base]"
) {
auto const http_method = http::OP_POST();
auto const base_url = "https://api.twitter.com/1/statuses/update.json";
auto const consumer_key = "xvz1evFS4wEEPTGEFPHBog";
auto const token_key = "370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb";
auto const timestamp = "1318622958";
auto const nonce = "kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg";
auto params = http::parameters();
params["include_entities"] = "true";
params["status"] = "Hello Ladies + Gentlemen, a signed OAuth request!";
auto const sig_base_expected = ""
"POST&"
"https%3A%2F%2Fapi.twitter.com%2F1%2Fstatuses%2Fupdate.json&"
"include_entities%3Dtrue%26"
"oauth_consumer_key%3Dxvz1evFS4wEEPTGEFPHBog%26"
"oauth_nonce%3DkYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg%26"
"oauth_signature_method%3DHMAC-SHA1%26"
"oauth_timestamp%3D1318622958%26"
"oauth_token%3D370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb%26"
"oauth_version%3D1.0%26"
"status%3DHello%2520Ladies%2520%252B%2520Gentlemen%252C%2520a%2520signed%2520OAuth%2520request%2521";
auto sig_base = http::oauth1::create_signature_base(
http_method, base_url, params, consumer_key, token_key, timestamp, nonce
);
CUTE_ASSERT(sig_base == sig_base_expected);
}
CUTE_TEST(
"Test http::oauth1::create_signature() method work properly",
"[http],[oauth1],[create_signature]"
) {
auto const consumer_secret = "kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw";
auto const token_secret = "LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE";
auto const sig_expected = "tnnArxj06cWHq44gCs1OSKk/jLY=";
auto const sig_base = ""
"POST&"
"https%3A%2F%2Fapi.twitter.com%2F1%2Fstatuses%2Fupdate.json&"
"include_entities%3Dtrue%26"
"oauth_consumer_key%3Dxvz1evFS4wEEPTGEFPHBog%26"
"oauth_nonce%3DkYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg%26"
"oauth_signature_method%3DHMAC-SHA1%26"
"oauth_timestamp%3D1318622958%26"
"oauth_token%3D370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb%26"
"oauth_version%3D1.0%26"
"status%3DHello%2520Ladies%2520%252B%2520Gentlemen%252C%2520a%2520signed%2520OAuth%2520request%2521";
auto sig = http::oauth1::create_signature(
sig_base, consumer_secret, token_secret
);
CUTE_ASSERT(sig == sig_expected);
}
CUTE_TEST(
"Test http::oauth1::create_oauth_header() method works properly for a fully configured client object and a POST request",
"[http],[oauth1],[create_oauth_header][POST]"
) {
auto client = http::oauth1::client();
client.consumer_key = "xvz1evFS4wEEPTGEFPHBog";
client.consumer_secret = "kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw";
client.token_key = "370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb";
client.token_secret = "LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE";
auto const timestamp = "1318622958";
auto const nonce = "kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg";
auto const http_method = http::OP_POST();
auto const url = ""
"https://api.twitter.com/1/statuses/update.json?"
"include_entities=true&"
"status=Hello%20Ladies%20%2B%20Gentlemen%2C%20a%20signed%20OAuth%20request%21";
auto const header_key_expected = "Authorization";
auto const header_value_expected = ""
"OAuth "
"oauth_consumer_key=\"xvz1evFS4wEEPTGEFPHBog\", "
"oauth_nonce=\"kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg\", "
"oauth_signature=\"tnnArxj06cWHq44gCs1OSKk%2FjLY%3D\", "
"oauth_signature_method=\"HMAC-SHA1\", "
"oauth_timestamp=\"1318622958\", "
"oauth_token=\"370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb\", "
"oauth_version=\"1.0\"";
auto const header = http::oauth1::create_oauth_header(
client, url, http_method, timestamp, nonce
);
CUTE_ASSERT(header.first == header_key_expected);
CUTE_ASSERT(header.second == header_value_expected);
}
CUTE_TEST(
"Test http::oauth1::create_nonce() method does not create the same value for two consecutive calls",
"[http],[oauth1],[create_nonce]"
) {
auto nonce1 = http::oauth1::create_nonce();
auto nonce2 = http::oauth1::create_nonce();
CUTE_ASSERT(nonce1 != nonce2);
}
| 44.323699 | 125 | 0.700052 | ColdOrange |
939325fe795f85146d7d143f1a4f39c67c941ad5 | 30,206 | cc | C++ | inet/src/inet/routing/ospfv3/neighbor/Ospfv3Neighbor.cc | ntanetani/quisp | 003f85746266d2eb62c66883e5b965b654672c70 | [
"BSD-3-Clause"
] | null | null | null | inet/src/inet/routing/ospfv3/neighbor/Ospfv3Neighbor.cc | ntanetani/quisp | 003f85746266d2eb62c66883e5b965b654672c70 | [
"BSD-3-Clause"
] | null | null | null | inet/src/inet/routing/ospfv3/neighbor/Ospfv3Neighbor.cc | ntanetani/quisp | 003f85746266d2eb62c66883e5b965b654672c70 | [
"BSD-3-Clause"
] | 1 | 2021-07-02T13:32:40.000Z | 2021-07-02T13:32:40.000Z |
#include "inet/routing/ospfv3/neighbor/Ospfv3Neighbor.h"
#include "inet/routing/ospfv3/neighbor/Ospfv3NeighborStateDown.h"
namespace inet {
namespace ospfv3 {
// FIXME!!! Should come from a global unique number generator module.
unsigned long Ospfv3Neighbor::ddSequenceNumberInitSeed = 0;
Ospfv3Neighbor::Ospfv3Neighbor(Ipv4Address newId, Ospfv3Interface* parent)
{
EV_DEBUG << "$$$$$$ New Ospfv3Neighbor has been created\n";
this->neighborId = newId;
this->state = new Ospfv3NeighborStateDown;
this->containingInterface = parent;
this->neighborsDesignatedRouter = NULL_IPV4ADDRESS;
this->neighborsBackupDesignatedRouter = NULL_IPV4ADDRESS;
this->neighborsRouterDeadInterval = DEFAULT_DEAD_INTERVAL;
//this is always only link local address
this->neighborIPAddress = Ipv6Address::UNSPECIFIED_ADDRESS;
if (this->getInterface()->getArea()->getInstance()->getAddressFamily() == IPV6INSTANCE) {
this->neighborsDesignatedIP = Ipv6Address::UNSPECIFIED_ADDRESS;
this->neighborsBackupIP = Ipv6Address::UNSPECIFIED_ADDRESS;
}
else {
this->neighborsDesignatedIP = Ipv4Address::UNSPECIFIED_ADDRESS;
this->neighborsBackupIP = Ipv4Address::UNSPECIFIED_ADDRESS;
}
inactivityTimer = new cMessage("Ospfv3Neighbor::NeighborInactivityTimer", NEIGHBOR_INACTIVITY_TIMER);
inactivityTimer->setContextPointer(this);
pollTimer = new cMessage("Ospfv3Neighbor::NeighborPollTimer", NEIGHBOR_POLL_TIMER);
pollTimer->setContextPointer(this);
ddRetransmissionTimer = new cMessage("Ospfv3Neighbor::NeighborDDRetransmissionTimer", NEIGHBOR_DD_RETRANSMISSION_TIMER);
ddRetransmissionTimer->setContextPointer(this);
updateRetransmissionTimer = new cMessage("Ospfv3Neighbor::Neighbor::NeighborUpdateRetransmissionTimer", NEIGHBOR_UPDATE_RETRANSMISSION_TIMER);
updateRetransmissionTimer->setContextPointer(this);
requestRetransmissionTimer = new cMessage("Ospfv3sNeighbor::NeighborRequestRetransmissionTimer", NEIGHBOR_REQUEST_RETRANSMISSION_TIMER);
requestRetransmissionTimer->setContextPointer(this);
}//constructor
Ospfv3Neighbor::~Ospfv3Neighbor()
{
reset();
Ospfv3Process *proc = this->getInterface()->getArea()->getInstance()->getProcess();
proc->clearTimer(inactivityTimer);
proc->clearTimer(pollTimer);
proc->clearTimer(ddRetransmissionTimer);
proc->clearTimer(updateRetransmissionTimer);
proc->clearTimer(requestRetransmissionTimer);
delete inactivityTimer;
delete pollTimer;
delete ddRetransmissionTimer;
delete updateRetransmissionTimer;
delete requestRetransmissionTimer;
if (previousState != nullptr) {
delete previousState;
}
delete state;
}//destructor
Ospfv3Neighbor::Ospfv3NeighborStateType Ospfv3Neighbor::getState() const
{
return state->getState();
}
void Ospfv3Neighbor::processEvent(Ospfv3Neighbor::Ospfv3NeighborEventType event)
{
EV_DEBUG << "Passing event number " << event << " to state\n";
this->state->processEvent(this, event);
}
void Ospfv3Neighbor::changeState(Ospfv3NeighborState *newState, Ospfv3NeighborState *currentState)
{
if (this->previousState != nullptr) {
EV_DEBUG << "Changing neighbor from state" << currentState->getNeighborStateString() << " to " << newState->getNeighborStateString() << "\n";
delete this->previousState;
}
this->state = newState;
this->previousState = currentState;
}
void Ospfv3Neighbor::reset()
{
EV_DEBUG << "Reseting the neighbor " << this->getNeighborID() << "\n";
for (auto retIt = linkStateRetransmissionList.begin();
retIt != linkStateRetransmissionList.end();
retIt++)
{
delete (*retIt);
}
linkStateRetransmissionList.clear();
for (auto it = databaseSummaryList.begin(); it != databaseSummaryList.end(); it++) {
delete (*it);
}
databaseSummaryList.clear();
for (auto it = linkStateRequestList.begin(); it != linkStateRequestList.end(); it++) {
delete (*it);
}
linkStateRequestList.clear();
this->getInterface()->getArea()->getInstance()->getProcess()->clearTimer(ddRetransmissionTimer);
clearUpdateRetransmissionTimer();
clearRequestRetransmissionTimer();
if (lastTransmittedDDPacket != nullptr) {
delete lastTransmittedDDPacket;
lastTransmittedDDPacket = nullptr;
}
}
bool Ospfv3Neighbor::needAdjacency()
{
Ospfv3Interface::Ospfv3InterfaceType interfaceType = this->getInterface()->getType();
Ipv4Address routerID = this->getInterface()->getArea()->getInstance()->getProcess()->getRouterID();
Ipv4Address dRouter = this->getInterface()->getDesignatedID();
Ipv4Address backupDRouter = this->getInterface()->getBackupID();
if ((interfaceType == Ospfv3Interface::POINTTOPOINT_TYPE) ||
(interfaceType == Ospfv3Interface::POINTTOMULTIPOINT_TYPE) ||
(interfaceType == Ospfv3Interface::VIRTUAL_TYPE) ||
(dRouter == routerID) ||
(backupDRouter == routerID) ||
(!designatedRoutersSetUp &&
neighborsDesignatedRouter == NULL_IPV4ADDRESS)||
(this->getNeighborID() == dRouter) ||
(this->getNeighborID() == backupDRouter))
{
EV_DEBUG << "I need an adjacency with router " << this->getNeighborID()<<"\n";
return true;
}
else {
return false;
}
}
void Ospfv3Neighbor::initFirstAdjacency()
{
ddSequenceNumber = getUniqueULong();
firstAdjacencyInited = true;
}
unsigned long Ospfv3Neighbor::getUniqueULong()
{
return ddSequenceNumberInitSeed++;
}
void Ospfv3Neighbor::startUpdateRetransmissionTimer()
{
this->getInterface()->getArea()->getInstance()->getProcess()->setTimer(this->getUpdateRetransmissionTimer(), this->getInterface()->getRetransmissionInterval());
this->updateRetransmissionTimerActive = true;
EV_DEBUG << "Starting UPDATE TIMER\n";
}
void Ospfv3Neighbor::clearUpdateRetransmissionTimer()
{
this->getInterface()->getArea()->getInstance()->getProcess()->clearTimer(this->getUpdateRetransmissionTimer());
this->updateRetransmissionTimerActive = false;
}
void Ospfv3Neighbor::startRequestRetransmissionTimer()
{
this->getInterface()->getArea()->getInstance()->getProcess()->setTimer(this->requestRetransmissionTimer, this->getInterface()->getRetransmissionInterval());
this->requestRetransmissionTimerActive = true;
}
void Ospfv3Neighbor::clearRequestRetransmissionTimer()
{
this->getInterface()->getArea()->getInstance()->getProcess()->clearTimer(this->getRequestRetransmissionTimer());
this->requestRetransmissionTimerActive = false;
}
void Ospfv3Neighbor::sendDDPacket(bool init)
{
EV_DEBUG << "Start of function send DD Packet\n";
const auto& ddPacket = makeShared<Ospfv3DatabaseDescriptionPacket>();
//common header first
ddPacket->setType(ospf::DATABASE_DESCRIPTION_PACKET);
ddPacket->setRouterID(this->getInterface()->getArea()->getInstance()->getProcess()->getRouterID());
ddPacket->setAreaID(this->getInterface()->getArea()->getAreaID());
ddPacket->setInstanceID(this->getInterface()->getArea()->getInstance()->getInstanceID());
//DD packet next
Ospfv3Options options;
memset(&options, 0, sizeof(Ospfv3Options));
options.eBit = this->getInterface()->getArea()->getExternalRoutingCapability();
ddPacket->setOptions(options);
ddPacket->setInterfaceMTU(this->getInterface()->getInterfaceMTU());
Ospfv3DdOptions ddOptions;
ddPacket->setSequenceNumber(this->ddSequenceNumber);
B packetSize = OSPFV3_HEADER_LENGTH + OSPFV3_DD_HEADER_LENGTH;
if (init || databaseSummaryList.empty()) {
ddPacket->setLsaHeadersArraySize(0);
}
else {
while (!this->databaseSummaryList.empty()) {/// && (packetSize <= (maxPacketSize - OSPF_LSA_HEADER_LENGTH))) {
unsigned long headerCount = ddPacket->getLsaHeadersArraySize();
Ospfv3LsaHeader *lsaHeader = *(databaseSummaryList.begin());
ddPacket->setLsaHeadersArraySize(headerCount + 1);
ddPacket->setLsaHeaders(headerCount, *lsaHeader);
delete lsaHeader;
databaseSummaryList.pop_front();
packetSize += OSPFV3_LSA_HEADER_LENGTH;
}
}
EV_DEBUG << "DatabaseSummatyListCount = " << this->getDatabaseSummaryListCount() << endl;
if (init) {
ddOptions.iBit = true;
ddOptions.mBit = true;
ddOptions.msBit = true;
}
else {
ddOptions.iBit = false;
ddOptions.mBit = (databaseSummaryList.empty()) ? false : true;
ddOptions.msBit = (databaseExchangeRelationship == Ospfv3Neighbor::MASTER) ? true : false;
}
ddPacket->setDdOptions(ddOptions);
ddPacket->setPacketLengthField(packetSize.get());
ddPacket->setChunkLength(packetSize);
Packet *pk = new Packet();
pk->insertAtBack(ddPacket);
//TODO - ddPacket does not include Virtual Links and HopLimit. Also Checksum is not calculated
if (this->getInterface()->getType() == Ospfv3Interface::POINTTOPOINT_TYPE) {
EV_DEBUG << "(P2P link ) Send DD Packet to OSPF MCAST\n";
this->getInterface()->getArea()->getInstance()->getProcess()->sendPacket(pk,Ipv6Address::ALL_OSPF_ROUTERS_MCAST, this->getInterface()->getIntName().c_str());
}
else {
EV_DEBUG << "Send DD Packet to " << this->getNeighborIP() << "\n";
this->getInterface()->getArea()->getInstance()->getProcess()->sendPacket(pk,this->getNeighborIP(), this->getInterface()->getIntName().c_str());
}
}
void Ospfv3Neighbor::sendLinkStateRequestPacket()
{
const auto& requestPacket = makeShared<Ospfv3LinkStateRequestPacket>();
requestPacket->setType(ospf::LINKSTATE_REQUEST_PACKET);
requestPacket->setRouterID(this->getInterface()->getArea()->getInstance()->getProcess()->getRouterID());
requestPacket->setAreaID(this->getInterface()->getArea()->getAreaID());
requestPacket->setInstanceID(this->getInterface()->getArea()->getInstance()->getInstanceID());
//long maxPacketSize = (((IP_MAX_HEADER_BYTES + OSPF_HEADER_LENGTH + OSPF_REQUEST_LENGTH) > parentInterface->getMTU()) ?
// IPV4_DATAGRAM_LENGTH :
// parentInterface->getMTU()) - IP_MAX_HEADER_BYTES;
B packetSize = OSPFV3_HEADER_LENGTH;
if (linkStateRequestList.empty()) {
requestPacket->setRequestsArraySize(0);
}
else {
auto it = linkStateRequestList.begin();
while (it != linkStateRequestList.end()) { //TODO - maxpacketsize
unsigned long requestCount = requestPacket->getRequestsArraySize();
Ospfv3LsaHeader *requestHeader = (*it);
Ospfv3LsRequest request;
request.lsaType = requestHeader->getLsaType();
request.lsaID = requestHeader->getLinkStateID();
request.advertisingRouter = requestHeader->getAdvertisingRouter();
requestPacket->setRequestsArraySize(requestCount + 1);
requestPacket->setRequests(requestCount, request);
packetSize += OSPFV3_LSR_LENGTH;
it++;
}
}
requestPacket->setChunkLength(packetSize);
//TODO - TTL and Checksum calculation for LS Request is not implemented yet
Packet *pk = new Packet();
pk->insertAtBack(requestPacket);
if (this->getInterface()->getType() == Ospfv3Interface::POINTTOPOINT_TYPE) {
this->getInterface()->getArea()->getInstance()->getProcess()->sendPacket(pk,Ipv6Address::ALL_OSPF_ROUTERS_MCAST, this->getInterface()->getIntName().c_str());
}
else {
this->getInterface()->getArea()->getInstance()->getProcess()->sendPacket(pk,this->getNeighborIP(), this->getInterface()->getIntName().c_str());
}
}
void Ospfv3Neighbor::createDatabaseSummary()
{
Ospfv3Area* area = this->getInterface()->getArea();
int routerLSACount = area->getRouterLSACount();
for (int i=0; i<routerLSACount; i++) {
Ospfv3LsaHeader* lsaHeader = new Ospfv3LsaHeader(area->getRouterLSA(i)->getHeader());
this->databaseSummaryList.push_back(lsaHeader);
}
int networkLSACount = area->getNetworkLSACount();
for (int i=0; i<networkLSACount; i++) {
Ospfv3LsaHeader* lsaHeader = new Ospfv3LsaHeader(area->getNetworkLSA(i)->getHeader());
this->databaseSummaryList.push_back(lsaHeader);
}
int interAreaPrefixCount = area->getInterAreaPrefixLSACount();
for (int i=0; i<interAreaPrefixCount; i++) {
Ospfv3LsaHeader* lsaHeader = new Ospfv3LsaHeader(area->getInterAreaPrefixLSA(i)->getHeader());
this->databaseSummaryList.push_back(lsaHeader);
}
int linkLsaCount = this->getInterface()->getLinkLSACount();
for (int i=0; i<linkLsaCount; i++) {
Ospfv3LsaHeader* lsaHeader = new Ospfv3LsaHeader(this->getInterface()->getLinkLSA(i)->getHeader());
this->databaseSummaryList.push_back(lsaHeader);
}
int intraAreaPrefixCnt = area->getIntraAreaPrefixLSACount();
for (int i=0; i<intraAreaPrefixCnt; i++) {
Ospfv3LsaHeader* lsaHeader = new Ospfv3LsaHeader(area->getIntraAreaPrefixLSA(i)->getHeader());
this->databaseSummaryList.push_back(lsaHeader);
}
}
void Ospfv3Neighbor::retransmitUpdatePacket()
{
EV_DEBUG << "Retransmitting update packet\n";
const auto& updatePacket = makeShared<Ospfv3LinkStateUpdatePacket>();
updatePacket->setType(ospf::LINKSTATE_UPDATE_PACKET);
updatePacket->setRouterID(this->getInterface()->getArea()->getInstance()->getProcess()->getRouterID());
updatePacket->setAreaID(this->getInterface()->getArea()->getAreaID());
updatePacket->setInstanceID(this->getInterface()->getArea()->getInstance()->getInstanceID());
bool packetFull = false;
unsigned short lsaCount = 0;
B packetLength = OSPFV3_HEADER_LENGTH + OSPFV3_LSA_HEADER_LENGTH;
auto it = linkStateRetransmissionList.begin();
while (!packetFull && (it != linkStateRetransmissionList.end())) {
uint16_t lsaType = (*it)->getHeader().getLsaType();
const Ospfv3RouterLsa *routerLSA = (lsaType == ROUTER_LSA) ? dynamic_cast<Ospfv3RouterLsa *>(*it) : nullptr;
const Ospfv3NetworkLsa *networkLSA = (lsaType == NETWORK_LSA) ? dynamic_cast<Ospfv3NetworkLsa *>(*it) : nullptr;
const Ospfv3LinkLsa *linkLSA = (lsaType == LINK_LSA) ? dynamic_cast<Ospfv3LinkLsa *>(*it) : nullptr;
const Ospfv3InterAreaPrefixLsa *interAreaPrefixLSA = (lsaType == INTER_AREA_PREFIX_LSA) ? dynamic_cast<Ospfv3InterAreaPrefixLsa *>(*it) : nullptr;
const Ospfv3IntraAreaPrefixLsa *intraAreaPrefixLSA = (lsaType == INTRA_AREA_PREFIX_LSA) ? dynamic_cast<Ospfv3IntraAreaPrefixLsa *>(*it) : nullptr;
// OSPFASExternalLSA *asExternalLSA = (lsaType == AS_EXTERNAL_LSA_TYPE) ? dynamic_cast<OSPFASExternalLSA *>(*it) : nullptr;
B lsaSize;
bool includeLSA = false;
switch (lsaType) {
case ROUTER_LSA:
if (routerLSA != nullptr) {
lsaSize = calculateLSASize(routerLSA);
}
break;
case NETWORK_LSA:
if (networkLSA != nullptr) {
lsaSize = calculateLSASize(networkLSA);
}
break;
case INTER_AREA_PREFIX_LSA:
if (interAreaPrefixLSA != nullptr) {
lsaSize = calculateLSASize(interAreaPrefixLSA);
}
break;
// case AS_EXTERNAL_LSA_TYPE:
// if (asExternalLSA != nullptr) {
// lsaSize = calculateLSASize(asExternalLSA);
// }
// break;
//
// default:
// break;
case LINK_LSA:
if (linkLSA != nullptr)
lsaSize = calculateLSASize(linkLSA);
break;
case INTRA_AREA_PREFIX_LSA:
if (intraAreaPrefixLSA != nullptr) {
lsaSize = calculateLSASize(intraAreaPrefixLSA);
}
break;
}
if (B(packetLength + lsaSize).get() < this->getInterface()->getInterfaceMTU()) {
includeLSA = true;
lsaCount++;
}
else {
if ((lsaCount == 0) && (packetLength + lsaSize < IPV6_DATAGRAM_LENGTH)) {
includeLSA = true;
lsaCount++;
packetFull = true;
}
}
if (includeLSA) {
packetLength += lsaSize;
switch (lsaType) {
case ROUTER_LSA:
if (routerLSA != nullptr) {
unsigned int routerLSACount = updatePacket->getRouterLSAsArraySize();
updatePacket->setRouterLSAsArraySize(routerLSACount + 1);
updatePacket->setRouterLSAs(routerLSACount, *routerLSA);
unsigned short lsAge = updatePacket->getRouterLSAs(routerLSACount).getHeader().getLsaAge();
if (lsAge < MAX_AGE - this->getInterface()->getTransDelayInterval()) {
updatePacket->getRouterLSAsForUpdate(routerLSACount).getHeaderForUpdate().setLsaAge(lsAge + this->getInterface()->getTransDelayInterval());
}
else {
updatePacket->getRouterLSAsForUpdate(routerLSACount).getHeaderForUpdate().setLsaAge(MAX_AGE);
}
}
break;
case NETWORK_LSA:
if (networkLSA != nullptr) {
unsigned int networkLSACount = updatePacket->getNetworkLSAsArraySize();
updatePacket->setNetworkLSAsArraySize(networkLSACount + 1);
updatePacket->setNetworkLSAs(networkLSACount, *networkLSA);
unsigned short lsAge = updatePacket->getNetworkLSAs(networkLSACount).getHeader().getLsaAge();
if (lsAge < MAX_AGE - this->getInterface()->getTransDelayInterval()) {
updatePacket->getNetworkLSAsForUpdate(networkLSACount).getHeaderForUpdate().setLsaAge(lsAge + this->getInterface()->getTransDelayInterval());
}
else {
updatePacket->getNetworkLSAsForUpdate(networkLSACount).getHeaderForUpdate().setLsaAge(MAX_AGE);
}
}
break;
case INTER_AREA_PREFIX_LSA:
if (interAreaPrefixLSA != nullptr) {
unsigned int interAreaPrefixLSACount = updatePacket->getInterAreaPrefixLSAsArraySize();
updatePacket->setInterAreaPrefixLSAsArraySize(interAreaPrefixLSACount + 1);
updatePacket->setInterAreaPrefixLSAs(interAreaPrefixLSACount, *interAreaPrefixLSA);
unsigned short lsAge = updatePacket->getInterAreaPrefixLSAs(interAreaPrefixLSACount).getHeader().getLsaAge();
if (lsAge < MAX_AGE - this->getInterface()->getTransDelayInterval()) {
updatePacket->getInterAreaPrefixLSAsForUpdate(interAreaPrefixLSACount).getHeaderForUpdate().setLsaAge(lsAge + this->getInterface()->getTransDelayInterval());
}
else {
updatePacket->getInterAreaPrefixLSAsForUpdate(interAreaPrefixLSACount).getHeaderForUpdate().setLsaAge(MAX_AGE);
}
}
break;
// case AS_EXTERNAL_LSA_TYPE:
// if (asExternalLSA != nullptr) {
// unsigned int asExternalLSACount = updatePacket->getAsExternalLSAsArraySize();
//
// updatePacket->setAsExternalLSAsArraySize(asExternalLSACount + 1);
// updatePacket->setAsExternalLSAs(asExternalLSACount, *asExternalLSA);
//
// unsigned short lsAge = updatePacket->getAsExternalLSAs(asExternalLSACount).getHeader().getLsAge();
// if (lsAge < MAX_AGE - parentInterface->getTransmissionDelay()) {
// updatePacket->getAsExternalLSAs(asExternalLSACount).getHeader().setLsAge(lsAge + parentInterface->getTransmissionDelay());
// }
// else {
// updatePacket->getAsExternalLSAs(asExternalLSACount).getHeader().setLsAge(MAX_AGE);
// }
// }
// break;
case LINK_LSA:
if (linkLSA != nullptr) {
unsigned int linkLSACount = updatePacket->getLinkLSAsArraySize();
updatePacket->setLinkLSAsArraySize(linkLSACount + 1);
updatePacket->setLinkLSAs(linkLSACount, *linkLSA);
unsigned short lsAge = updatePacket->getLinkLSAs(linkLSACount).getHeader().getLsaAge();
if (lsAge < MAX_AGE - this->getInterface()->getTransDelayInterval()) {
updatePacket->getLinkLSAsForUpdate(linkLSACount).getHeaderForUpdate().setLsaAge(lsAge + this->getInterface()->getTransDelayInterval());
}
else {
updatePacket->getLinkLSAsForUpdate(linkLSACount).getHeaderForUpdate().setLsaAge(MAX_AGE);
}
}
break;
case INTRA_AREA_PREFIX_LSA:
if (intraAreaPrefixLSA != nullptr) {
unsigned int intraAreaPrefixLSACount = updatePacket->getIntraAreaPrefixLSAsArraySize();
updatePacket->setIntraAreaPrefixLSAsArraySize(intraAreaPrefixLSACount + 1);
updatePacket->setIntraAreaPrefixLSAs(intraAreaPrefixLSACount, *intraAreaPrefixLSA);
unsigned short lsAge = updatePacket->getIntraAreaPrefixLSAs(intraAreaPrefixLSACount).getHeader().getLsaAge();
if (lsAge < MAX_AGE - this->getInterface()->getTransDelayInterval()) {
updatePacket->getIntraAreaPrefixLSAsForUpdate(intraAreaPrefixLSACount).getHeaderForUpdate().setLsaAge(lsAge + this->getInterface()->getTransDelayInterval());
}
else {
updatePacket->getIntraAreaPrefixLSAsForUpdate(intraAreaPrefixLSACount).getHeaderForUpdate().setLsaAge(MAX_AGE);
}
}
break;
default:
break;
}
}
it++;
}
EV_DEBUG << "Retransmit - packet length: "<<packetLength<<"\n";
updatePacket->setChunkLength(B(packetLength)); //IPV6 HEADER BYTES
Packet *pk = new Packet();
pk->insertAtBack(updatePacket);
this->getInterface()->getArea()->getInstance()->getProcess()->sendPacket(pk, this->getNeighborIP(), this->getInterface()->getIntName().c_str());
//TODO
// int ttl = (parentInterface->getType() == Interface::VIRTUAL) ? VIRTUAL_LINK_TTL : 1;
// messageHandler->sendPacket(updatePacket, neighborIPAddress, parentInterface->getIfIndex(), ttl);
}
void Ospfv3Neighbor::addToRetransmissionList(const Ospfv3Lsa *lsa)
{
auto it = linkStateRetransmissionList.begin();
for ( ; it != linkStateRetransmissionList.end(); it++) {
if (((*it)->getHeader().getLinkStateID() == lsa->getHeader().getLinkStateID()) &&
((*it)->getHeader().getAdvertisingRouter().getInt() == lsa->getHeader().getAdvertisingRouter().getInt()))
{
break;
}
}
Ospfv3Lsa *lsaCopy = lsa->dup();
// switch (lsaC->getHeader().getLsaType()) {
// case ROUTER_LSA:
// lsaCopy = new Ospfv3RouterLsa((const_cast<Ospfv3Lsa*>(lsaC))));
// break;
//
// case NETWORK_LSA:
// lsaCopy = new Ospfv3NetworkLsa(*(check_and_cast<Ospfv3NetworkLsa *>(const_cast<Ospfv3Lsa*>(lsaC))));
// break;
//
// case INTER_AREA_PREFIX_LSA:
// lsaCopy = new Ospfv3InterAreaPrefixLsa(*(check_and_cast<Ospfv3InterAreaPrefixLsa* >(const_cast<Ospfv3Lsa*>(lsaC))));
// break;
//// case AS_EXTERNAL_LSA_TYPE:
//// lsaCopy = new OSPFASExternalLSA(*(check_and_cast<OSPFASExternalLSA *>(lsa)));
//// break;
//
// case LINK_LSA:
// lsaCopy = new Ospfv3LinkLsa(*(check_and_cast<Ospfv3LinkLsa *>(const_cast<Ospfv3Lsa*>(lsaC))));
// break;
//
// case INTRA_AREA_PREFIX_LSA:
// lsaCopy = new Ospfv3IntraAreaPrefixLsa(*(check_and_cast<Ospfv3IntraAreaPrefixLsa *>(const_cast<Ospfv3Lsa*>(lsaC))));
// break;
//
// default:
// ASSERT(false); // error
// break;
// }
// if LSA is on retransmission list then replace it
if (it != linkStateRetransmissionList.end()) {
delete (*it);
*it = static_cast<Ospfv3Lsa *>(lsaCopy);
}
else {
//if not then add it
linkStateRetransmissionList.push_back(static_cast<Ospfv3Lsa *>(lsaCopy));
}
}
void Ospfv3Neighbor::removeFromRetransmissionList(LSAKeyType lsaKey)
{
auto it = linkStateRetransmissionList.begin();
int counter = 0;
while (it != linkStateRetransmissionList.end())
{
EV_DEBUG << counter++ << " - HEADER in retransmition list:\n" << (*it)->getHeader() << "\n";
if (((*it)->getHeader().getLinkStateID() == lsaKey.linkStateID) &&
((*it)->getHeader().getAdvertisingRouter() == lsaKey.advertisingRouter))
{
delete (*it);
it = linkStateRetransmissionList.erase(it);
}
else
{
it++;
}
}
}//removeFromRetransmissionList
bool Ospfv3Neighbor::isLinkStateRequestListEmpty(LSAKeyType lsaKey) const
{
for (auto lsa : linkStateRetransmissionList) {
if ((lsa->getHeader().getLinkStateID() == lsaKey.linkStateID) &&
(lsa->getHeader().getAdvertisingRouter() == lsaKey.advertisingRouter))
{
return true;
}
}
return false;
}
Ospfv3Lsa *Ospfv3Neighbor::findOnRetransmissionList(LSAKeyType lsaKey)
{
for (auto & elem : linkStateRetransmissionList) {
if (((elem)->getHeader().getLinkStateID() == lsaKey.linkStateID) &&
((elem)->getHeader().getAdvertisingRouter() == lsaKey.advertisingRouter))
{
return elem;
}
}
return nullptr;
}
bool Ospfv3Neighbor::retransmitDatabaseDescriptionPacket()
{
EV_DEBUG << "Retransmitting DD Packet\n";
if (lastTransmittedDDPacket != nullptr) {
Packet *ddPacket = new Packet(*lastTransmittedDDPacket);
this->getInterface()->getArea()->getInstance()->getProcess()->sendPacket(ddPacket, this->getNeighborIP(), this->getInterface()->getIntName().c_str());
return true;
}
else {
EV_DEBUG << "But no packet is in the line\n";
return false;
}
}
void Ospfv3Neighbor::addToRequestList(const Ospfv3LsaHeader *lsaHeader)
{
linkStateRequestList.push_back(new Ospfv3LsaHeader(*lsaHeader));
EV_DEBUG << "Currently on request list:\n";
for (auto it = linkStateRequestList.begin(); it != linkStateRequestList.end(); it++) {
EV_DEBUG << "\tType: "<<(*it)->getLsaType() << ", ID: " << (*it)->getLinkStateID() << ", Adv: " << (*it)->getAdvertisingRouter() << "\n";
}
}
bool Ospfv3Neighbor::isLSAOnRequestList(LSAKeyType lsaKey)
{
if (findOnRequestList(lsaKey)==nullptr)
return false;
return true;
}
Ospfv3LsaHeader* Ospfv3Neighbor::findOnRequestList(LSAKeyType lsaKey)
{
//linkStateRequestList - list of LSAs that need to be received from the neighbor
for (auto it = linkStateRequestList.begin(); it != linkStateRequestList.end(); it++) {
if (((*it)->getLinkStateID() == lsaKey.linkStateID) &&
((*it)->getAdvertisingRouter() == lsaKey.advertisingRouter))
{
return *it;
}
}
return nullptr;
}
void Ospfv3Neighbor::removeFromRequestList(LSAKeyType lsaKey)
{
auto it = linkStateRequestList.begin();
while (it != linkStateRequestList.end()) {
if (((*it)->getLinkStateID() == lsaKey.linkStateID) &&
((*it)->getAdvertisingRouter() == lsaKey.advertisingRouter))
{
delete (*it);
it = linkStateRequestList.erase(it);
}
else {
it++;
}
}
if ((getState() == Ospfv3Neighbor::LOADING_STATE) && (linkStateRequestList.empty())) {
clearRequestRetransmissionTimer();
processEvent(Ospfv3Neighbor::LOADING_DONE);
}
}//removeFromRequestList
void Ospfv3Neighbor::addToTransmittedLSAList(LSAKeyType lsaKey)
{
TransmittedLSA transmit;
transmit.lsaKey = lsaKey;
transmit.age = 0;
transmittedLSAs.push_back(transmit);
}//addToTransmittedLSAList
bool Ospfv3Neighbor::isOnTransmittedLSAList(LSAKeyType lsaKey) const
{
for (std::list<TransmittedLSA>::const_iterator it = transmittedLSAs.begin(); it != transmittedLSAs.end(); it++) {
if ((it->lsaKey.linkStateID == lsaKey.linkStateID) &&
(it->lsaKey.advertisingRouter == lsaKey.advertisingRouter))
{
return true;
}
}
return false;
}//isOnTransmittedLSAList
void Ospfv3Neighbor::ageTransmittedLSAList()
{
auto it = transmittedLSAs.begin();
while ((it != transmittedLSAs.end()) && (it->age == MIN_LS_ARRIVAL)) {
transmittedLSAs.pop_front();
it = transmittedLSAs.begin();
}
// for (long i = 0; i < transmittedLSAs.size(); i++)
// {
// transmittedLSAs[i].age++;
// }
for (it = transmittedLSAs.begin(); it != transmittedLSAs.end(); it++) {
it->age++;
}
}//ageTransmittedLSAList
void Ospfv3Neighbor::deleteLastSentDDPacket()
{
if (lastTransmittedDDPacket != nullptr) {
delete lastTransmittedDDPacket;
lastTransmittedDDPacket = nullptr;
}
}//deleteLastSentDDPacket
} // namespace ospfv3
} // namespace inet
| 41.378082 | 185 | 0.63782 | ntanetani |
939440a5a5e256ffb670a6e4fcd62514dfc8ae2a | 449 | cc | C++ | exercises/ALLOC_DINAMICA/prova.cc | mfranzil/Programmazione1UniTN | 0aee3ec51d424039afcabfa9de80046c1d5be7d9 | [
"MIT"
] | 3 | 2021-11-05T16:25:50.000Z | 2022-02-10T14:06:00.000Z | exercises/ALLOC_DINAMICA/prova.cc | mfranzil/Programmazione1UniTN | 0aee3ec51d424039afcabfa9de80046c1d5be7d9 | [
"MIT"
] | null | null | null | exercises/ALLOC_DINAMICA/prova.cc | mfranzil/Programmazione1UniTN | 0aee3ec51d424039afcabfa9de80046c1d5be7d9 | [
"MIT"
] | 2 | 2018-10-31T14:53:40.000Z | 2020-01-09T22:34:37.000Z | using namespace std;
#include <iostream>
int main ()
{
int * a;
int n,i;
cout << (long) &n << endl;
do {
cout << "quanti elementi? (0 per terminare): " ;
cin >> n;
a = new int[n];
for (i=0;i<n;i++){
cout << i+1 << ": ";
cin >> a[i];
}
for (i=0;i<n;i++){
cout << a[i] << " &a: " << (long) &a[i] << endl ;
}
delete [] a;
} while (n > 0);
cout << endl << a[1] << endl; // pericolosa!
}
| 17.96 | 55 | 0.418708 | mfranzil |
93993bb30f15993cbdc60848b885d9a9ed9d6433 | 29,949 | cpp | C++ | Sample/TexturedPlate/TexturedPlate.cpp | po2xel/vkpp | 04cf67cefa4e967fc234378da06366d66447c335 | [
"MIT"
] | 5 | 2017-04-05T13:29:40.000Z | 2018-04-10T21:04:51.000Z | Sample/TexturedPlate/TexturedPlate.cpp | po2xel/vkpp | 04cf67cefa4e967fc234378da06366d66447c335 | [
"MIT"
] | null | null | null | Sample/TexturedPlate/TexturedPlate.cpp | po2xel/vkpp | 04cf67cefa4e967fc234378da06366d66447c335 | [
"MIT"
] | null | null | null | #include "TexturedPlate.h"
namespace vkpp::sample
{
TexturedPlate::TexturedPlate(CWindow& aWindow, const char* apApplicationName, uint32_t aApplicationVersion, const char* apEngineName, uint32_t aEngineVersion)
: ExampleBase(aWindow, apApplicationName, aApplicationVersion, apEngineName, aEngineVersion),
CWindowEvent(aWindow),
CMouseWheelEvent(aWindow),
CMouseMotionEvent(aWindow),
mDepthResource(mLogicalDevice, mPhysicalDeviceMemoryProperties),
mTextureResource(mLogicalDevice, mPhysicalDeviceMemoryProperties),
mVertexBufferRes(mLogicalDevice, mPhysicalDeviceMemoryProperties),
mIndexBufferRes(mLogicalDevice, mPhysicalDeviceMemoryProperties),
mUniformBufferRes(mLogicalDevice, mPhysicalDeviceMemoryProperties)
{
theApp.RegisterUpdateEvent([this](void)
{
Update();
});
mMouseWheelFunc = [this](Sint32 /*aPosX*/, Sint32 aPosY)
{
mCurrentZoomLevel *= (1.0f + aPosY * MINIMUM_ZOOM_LEVEL);
UpdateUniformBuffer();
};
mMouseMotionFunc = [this](Uint32 aMouseState, Sint32 /*aPosX*/, Sint32 /*aPosY*/, Sint32 aRelativeX, Sint32 aRelativeY)
{
if (aMouseState & CMouseEvent::ButtonMask::eLMask)
{
mCurrentRotation.x += aRelativeY;
mCurrentRotation.y += aRelativeX;
UpdateUniformBuffer();
}
};
mResizedFunc = [this](Sint32 /*aWidth*/, Sint32 /*aHeight*/)
{
// Ensure all operations on the device have been finished before destroying resources.
mLogicalDevice.Wait();
// Re-create swapchain.
CreateSwapchain(mSwapchain);
mDepthResource.Reset();
CreateDepthResource();
// Re-create framebuffers.
for (auto& lFramebuffer : mFramebuffers)
mLogicalDevice.DestroyFramebuffer(lFramebuffer);
mFramebuffers.clear();
CreateFramebuffer();
// Command buffers need to be recreated as they reference to the destroyed framebuffer.
mLogicalDevice.FreeCommandBuffers(mCmdPool, mDrawCmdBuffers);
AllocateCmdBuffers();
BuildCommandBuffers();
};
CreateCmdPool();
AllocateCmdBuffers();
CreateRenderPass();
CreateDepthResource();
CreateFramebuffer();
CreateSetLayout();
CreatePipelineLayout();
CreateGraphicsPipeline();
CreateDescriptorPool();
AllocateDescriptorSet();
// TODO: Vulkan core support three different compressed texture formats.
// As the support differs among implementations, it is needed to check device features and select a proper format and file.
LoadTexture("Texture/metalplate01_bc2_unorm.ktx", vkpp::Format::eBC2_uNormBlock);
CreateSampler();
CreateUniformBuffer();
UpdateUniformBuffer();
UpdateDescriptorSet();
CreateVertexBuffer();
CreateIndexBuffer();
BuildCommandBuffers();
CreateSemaphores();
CreateFences();
}
TexturedPlate::~TexturedPlate(void)
{
mLogicalDevice.Wait();
for (auto& lFence : mWaitFences)
mLogicalDevice.DestroyFence(lFence);
mLogicalDevice.DestroySemaphore(mPresentCompleteSemaphore);
mLogicalDevice.DestroySemaphore(mRenderCompleteSemaphore);
mIndexBufferRes.Reset();
mVertexBufferRes.Reset();
mUniformBufferRes.Reset();
mLogicalDevice.DestroySampler(mTextureSampler);
mLogicalDevice.DestroyDescriptorPool(mDescriptorPool);
mLogicalDevice.DestroyPipeline(mGraphicsPipeline);
mLogicalDevice.DestroyPipelineLayout(mPipelineLayout);
mLogicalDevice.DestroyDescriptorSetLayout(mSetLayout);
for (auto& lFramebuffer : mFramebuffers)
mLogicalDevice.DestroyFramebuffer(lFramebuffer);
mDepthResource.Reset();
mLogicalDevice.DestroyRenderPass(mRenderPass);
mLogicalDevice.FreeCommandBuffers(mCmdPool, mDrawCmdBuffers);
mLogicalDevice.DestroyCommandPool(mCmdPool);
}
void TexturedPlate::CreateCmdPool(void)
{
const vkpp::CommandPoolCreateInfo lCmdPoolCreateInfo
{
mGraphicsQueue.familyIndex,
vkpp::CommandPoolCreateFlagBits::eResetCommandBuffer
};
mCmdPool = mLogicalDevice.CreateCommandPool(lCmdPoolCreateInfo);
}
void TexturedPlate::AllocateCmdBuffers(void)
{
const vkpp::CommandBufferAllocateInfo lCmdAllocateInfo
{
mCmdPool,
static_cast<uint32_t>(mSwapchain.buffers.size())
};
mDrawCmdBuffers = mLogicalDevice.AllocateCommandBuffers(lCmdAllocateInfo);
}
void TexturedPlate::CreateRenderPass(void)
{
const std::array<vkpp::AttachementDescription, 2> lAttachments
{ {
// Color attachment
{
mSwapchain.surfaceFormat.format,
vkpp::SampleCountFlagBits::e1,
vkpp::AttachmentLoadOp::eClear, vkpp::AttachmentStoreOp::eStore,
vkpp::ImageLayout::eUndefined, vkpp::ImageLayout::ePresentSrcKHR
},
// Depth attachment
{
vkpp::Format::eD32sFloat,
vkpp::SampleCountFlagBits::e1,
vkpp::AttachmentLoadOp::eClear, vkpp::AttachmentStoreOp::eDontCare,
vkpp::ImageLayout::eUndefined, vkpp::ImageLayout::eDepthStencilAttachmentOptimal
}
} };
constexpr vkpp::AttachmentReference lColorRef
{
0, vkpp::ImageLayout::eColorAttachmentOptimal
};
constexpr vkpp::AttachmentReference lDepthRef
{
1, vkpp::ImageLayout::eDepthStencilAttachmentOptimal
};
constexpr std::array<vkpp::SubpassDescription, 1> lSubpassDescriptions
{ {
{
vkpp::PipelineBindPoint::eGraphics,
0, nullptr,
1, lColorRef.AddressOf(),
nullptr,
lDepthRef.AddressOf()
}
} };
constexpr std::array<vkpp::SubpassDependency, 2> lSubpassDependencies
{ {
{
vkpp::subpass::External, 0,
vkpp::PipelineStageFlagBits::eBottomOfPipe, vkpp::PipelineStageFlagBits::eColorAttachmentOutput,
vkpp::AccessFlagBits::eMemoryRead, vkpp::AccessFlagBits::eColorAttachmentWrite,
vkpp::DependencyFlagBits::eByRegion
},
{
0, vkpp::subpass::External,
vkpp::PipelineStageFlagBits::eColorAttachmentOutput, vkpp::PipelineStageFlagBits::eBottomOfPipe,
vkpp::AccessFlagBits::eColorAttachmentWrite, vkpp::AccessFlagBits::eMemoryRead,
vkpp::DependencyFlagBits::eByRegion
}
} };
const vkpp::RenderPassCreateInfo lRenderPassCreateInfo
{
lAttachments, lSubpassDescriptions, lSubpassDependencies
};
mRenderPass = mLogicalDevice.CreateRenderPass(lRenderPassCreateInfo);
}
void TexturedPlate::CreateDepthResource(void)
{
const vkpp::ImageCreateInfo lImageCreateInfo
{
vkpp::ImageType::e2D,
vkpp::Format::eD32sFloat,
mSwapchain.extent,
vkpp::ImageUsageFlagBits::eDepthStencilAttachment
};
vkpp::ImageViewCreateInfo lImageViewCreateInfo
{
vkpp::ImageViewType::e2D,
vkpp::Format::eD32sFloat,
{
vkpp::ImageAspectFlagBits::eDepth,
0, 1,
0, 1
}
};
mDepthResource.Reset(lImageCreateInfo, lImageViewCreateInfo, vkpp::MemoryPropertyFlagBits::eDeviceLocal);
}
void TexturedPlate::CreateFramebuffer(void)
{
for (auto& lSwapchain : mSwapchain.buffers)
{
const std::array<vkpp::ImageView, 2> lAttachments
{
lSwapchain.view,
mDepthResource.view
};
const vkpp::FramebufferCreateInfo lFramebufferCreateInfo
{
mRenderPass,
lAttachments,
mSwapchain.extent
};
mFramebuffers.emplace_back(mLogicalDevice.CreateFramebuffer(lFramebufferCreateInfo));
}
}
void TexturedPlate::CreateSetLayout(void)
{
constexpr std::array<vkpp::DescriptorSetLayoutBinding, 2> lSetLayoutBindings
{ {
// Binding 0: Vertex shader uniform buffer. (MVP matrix)
{
0, // Binding
vkpp::DescriptorType::eUniformBuffer,
1, // Descriptor count
vkpp::ShaderStageFlagBits::eVertex
},
// Binding 1: Fragment shader image sampler.
{
1, // Binding
vkpp::DescriptorType::eCombinedImageSampler,
1, // Descriptor count
vkpp::ShaderStageFlagBits::eFragment
}
} };
const vkpp::DescriptorSetLayoutCreateInfo lSetLayoutCreateInfo{ lSetLayoutBindings };
mSetLayout = mLogicalDevice.CreateDescriptorSetLayout(lSetLayoutCreateInfo);
}
void TexturedPlate::CreatePipelineLayout(void)
{
const vkpp::PipelineLayoutCreateInfo lPipelineLayoutCreateInfo
{
1, mSetLayout.AddressOf()
};
mPipelineLayout = mLogicalDevice.CreatePipelineLayout(lPipelineLayoutCreateInfo);
}
void TexturedPlate::CreateGraphicsPipeline(void)
{
const auto& lVertexShader = CreateShaderModule("Shader/SPV/texture.vert.spv");
const auto& lFragmentShader = CreateShaderModule("Shader/SPV/texture.frag.spv");
const std::vector<vkpp::PipelineShaderStageCreateInfo> lShaderStageCreateInfos
{
{
vkpp::ShaderStageFlagBits::eVertex,
lVertexShader
},
{
vkpp::ShaderStageFlagBits::eFragment,
lFragmentShader
}
};
constexpr std::array<vkpp::VertexInputBindingDescription, 1> lVertexInputBindingDescriptions{ VertexData::GetBindingDescription() };
constexpr auto lVertexAtributeDescriptions = VertexData::GetAttributeDescriptions();
const vkpp::PipelineVertexInputStateCreateInfo lInputStateCreateInfo
{
lVertexInputBindingDescriptions,
lVertexAtributeDescriptions
};
constexpr vkpp::PipelineInputAssemblyStateCreateInfo lInputAssemblyState{ vkpp::PrimitiveTopology::eTriangleList };
constexpr vkpp::PipelineViewportStateCreateInfo lViewportCreateInfo{ 1, 1 };
constexpr vkpp::PipelineRasterizationStateCreateInfo lRasterizationStateCreateInfo
{
DepthClamp::Disable, RasterizerDiscard::Disable,
vkpp::PolygonMode::eFill,
vkpp::CullModeFlagBits::eNone,
vkpp::FrontFace::eCounterClockwise,
DepthBias::Disable,
0.0f, 0.0f, 1.0f,
1.0f
};
constexpr vkpp::PipelineMultisampleStateCreateInfo lMultisampleStateCreateInfo;
constexpr vkpp::PipelineDepthStencilStateCreateInfo lDepthStencilStateCreateInfo
{
DepthTest::Enable, DepthWrite::Enable,
vkpp::CompareOp::eLessOrEqual
};
constexpr vkpp::PipelineColorBlendAttachmentState lColorBlendAttachmentState;
const vkpp::PipelineColorBlendStateCreateInfo lColorBlendStateCreateInfo
{
1, lColorBlendAttachmentState.AddressOf()
};
constexpr std::array<vkpp::DynamicState, 2> lDynamicStates
{
vkpp::DynamicState::eViewport,
vkpp::DynamicState::eScissor
};
const vkpp::PipelineDynamicStateCreateInfo lDynamicStateCreateInfo{ lDynamicStates };
const vkpp::GraphicsPipelineCreateInfo lGraphicsPipelineCreateInfo
{
2, lShaderStageCreateInfos.data(),
lInputStateCreateInfo.AddressOf(),
lInputAssemblyState.AddressOf(),
nullptr,
lViewportCreateInfo.AddressOf(),
lRasterizationStateCreateInfo.AddressOf(),
lMultisampleStateCreateInfo.AddressOf(),
lDepthStencilStateCreateInfo.AddressOf(),
lColorBlendStateCreateInfo.AddressOf(),
lDynamicStateCreateInfo.AddressOf(),
mPipelineLayout,
mRenderPass,
0
};
mGraphicsPipeline = mLogicalDevice.CreateGraphicsPipeline(lGraphicsPipelineCreateInfo);
mLogicalDevice.DestroyShaderModule(lFragmentShader);
mLogicalDevice.DestroyShaderModule(lVertexShader);
}
void TexturedPlate::CreateDescriptorPool(void)
{
constexpr std::array<vkpp::DescriptorPoolSize, 2> lPoolSizes
{ {
{ vkpp::DescriptorType::eUniformBuffer, 1},
{ vkpp::DescriptorType::eCombinedImageSampler, 1}
} };
const vkpp::DescriptorPoolCreateInfo lPoolCreateInfo
{
lPoolSizes, 2
};
mDescriptorPool = mLogicalDevice.CreateDescriptorPool(lPoolCreateInfo);
}
void TexturedPlate::AllocateDescriptorSet(void)
{
const vkpp::DescriptorSetAllocateInfo lSetAllocateInfo
{
mDescriptorPool,
1, mSetLayout.AddressOf()
};
mDescriptorSet = mLogicalDevice.AllocateDescriptorSet(lSetAllocateInfo);
}
void TexturedPlate::LoadTexture(const std::string& aFilename, vkpp::Format aTexFormat)
{
const gli::texture2d lTex2D{ gli::load(aFilename) };
assert(!lTex2D.empty());
mTexture.width = static_cast<uint32_t>(lTex2D[0].extent().x);
mTexture.height = static_cast<uint32_t>(lTex2D[0].extent().y);
mTexture.mipLevels = static_cast<uint32_t>(lTex2D.levels());
// Get device properties for the requested texture format.
// const auto& lFormatProperties = mPhysicalDevice.GetFormatProperties(mTexFormat);
// Create a host-visible staging buffer that contains the raw image data.
const vkpp::BufferCreateInfo lStagingBufferCreateInfo
{
lTex2D.size(),
vkpp::BufferUsageFlagBits::eTransferSrc // This buffer is used as a transfer source for the buffer copy.
};
BufferResource lStagingBufferRes{ mLogicalDevice, mPhysicalDeviceMemoryProperties };
lStagingBufferRes.Reset(lStagingBufferCreateInfo, vkpp::MemoryPropertyFlagBits::eHostVisible | vkpp::MemoryPropertyFlagBits::eHostCoherent);
auto lMappedMem = mLogicalDevice.MapMemory(lStagingBufferRes.memory, 0, lTex2D.size());
std::memcpy(lMappedMem, lTex2D.data(), lTex2D.size());
mLogicalDevice.UnmapMemory(lStagingBufferRes.memory);
// Setup buffer copy regions for each mip-level.
std::vector<vkpp::BufferImageCopy> lBufferCopyRegions;
uint32_t lOffset{ 0 };
for (uint32_t lIndex = 0; lIndex < mTexture.mipLevels; ++lIndex)
{
const vkpp::BufferImageCopy lBufferCopyRegion
{
lOffset,
{
vkpp::ImageAspectFlagBits::eColor,
lIndex,
},
{0, 0, 0},
{
static_cast<uint32_t>(lTex2D[lIndex].extent().x),
static_cast<uint32_t>(lTex2D[lIndex].extent().y),
1
}
};
lBufferCopyRegions.emplace_back(lBufferCopyRegion);
lOffset += static_cast<uint32_t>(lTex2D[lIndex].size());
}
// Create optimal tiled target image.
// Only use linear tiling if requested (and supported by the device).
// Support for linear tiling is mostly limited, so prefer to use optimal tiling instead.
// On most implementations, linear tiling will only support a very limited amount of formats and features (mip-maps, cube-maps, arrays, etc.).
const vkpp::ImageCreateInfo lImageCreateInfo
{
vkpp::ImageType::e2D,
aTexFormat,
{ mTexture.width, mTexture.height, 1 },
vkpp::ImageUsageFlagBits::eSampled | vkpp::ImageUsageFlagBits::eTransferDst,
vkpp::ImageLayout::eUndefined,
vkpp::ImageTiling::eOptimal,
vkpp::SampleCountFlagBits::e1,
mTexture.mipLevels
};
vkpp::ImageViewCreateInfo lImageViewCreateInfo
{
vkpp::ImageViewType::e2D,
aTexFormat,
// The subresource range describes the set of mip-levels (and array layers) that can be accessed through this image view.
// It is possible to create multiple image views for a single image referring to different (and/or overlapping) ranges of the image.
{
vkpp::ImageAspectFlagBits::eColor,
0, mTexture.mipLevels,
0, 1
}
};
mTextureResource.Reset(lImageCreateInfo, lImageViewCreateInfo, vkpp::MemoryPropertyFlagBits::eDeviceLocal);
const auto& lCopyCmd = BeginOneTimeCmdBuffer();
// Image barrier for optimal image.
// The sub-resource range describes the regions of the image which will be transitioned.
const vkpp::ImageSubresourceRange lImageSubRange
{
vkpp::ImageAspectFlagBits::eColor, // aspectMask: Only contains color data.
0, // baseMipLevel: Start at first mip-level.
mTexture.mipLevels, // levelCount: Transition on all mip-levels.
0, // baseArrayLayer: Start at first element in the array. (only one element in this example.)
1 // layerCount: The 2D texture only has one layer.
};
// Optimal image will be used as the destination for the copy, so it must be transfered from the initial undefined image layout to the transfer destination layout.
TransitionImageLayout<vkpp::ImageLayout::eUndefined, vkpp::ImageLayout::eTransferDstOptimal>
(
lCopyCmd, mTextureResource.image,
lImageSubRange,
vkpp::DefaultFlags, // srcAccessMask = 0: Only valid as initial layout, memory contents are not preserved.
// Can be accessed directly, no source dependency required.
vkpp::AccessFlagBits::eTransferWrite // dstAccessMask: Transfer destination (copy, blit).
// Make sure any write operation to the image has been finished.
);
// Copy all mip-levels from staging buffer.
lCopyCmd.Copy(mTextureResource.image, vkpp::ImageLayout::eTransferDstOptimal, lStagingBufferRes.buffer, lBufferCopyRegions);
// Transfer texture image layout to shader read after all mip-levels have been copied.
TransitionImageLayout<vkpp::ImageLayout::eTransferDstOptimal, vkpp::ImageLayout::eShaderReadOnlyOptimal>
(
lCopyCmd, mTextureResource.image,
lImageSubRange,
vkpp::AccessFlagBits::eTransferWrite, // srcAccessMask: Old layout is transfer destination.
// Make sure any write operation to the destination image has been finished.
vkpp::AccessFlagBits::eShaderRead // dstAccessMask: Shader read, like sampler, input attachment.
);
EndOneTimeCmdBuffer(lCopyCmd);
lStagingBufferRes.Reset();
}
// In Vulkan, textures are accessed by samplers. This separates all the sampling information from the texture data.
// This means it is possible to have multiple sampler objects for the same texture with different settings.
void TexturedPlate::CreateSampler(void)
{
const vkpp::SamplerCreateInfo lSamplerCreateInfo
{
vkpp::Filter::eLinear, // magFilter
vkpp::Filter::eLinear, // minFilter
vkpp::SamplerMipmapMode::eLinear, // mipmapMode
vkpp::SamplerAddressMode::eRepeat, // addressModeU
vkpp::SamplerAddressMode::eRepeat, // addressModeV
vkpp::SamplerAddressMode::eRepeat, // addressModeW
0.0f, // mipLodBias
Anisotropy::Enable, // anisotropyEnable
mPhysicalDeviceProperties.limits.maxSamplerAnisotropy, // maxAnisotropy
Compare::Enable, // compareEnable,
vkpp::CompareOp::eNever, // compareOp
0.0f, // minLoad
static_cast<float>(mTexture.mipLevels), // maxLoad: Set max level-of-detail to mip-level count of the texture.
vkpp::BorderColor::eFloatOpaqueWhite // borderColor
};
mTextureSampler = mLogicalDevice.CreateSampler(lSamplerCreateInfo);
}
void TexturedPlate::UpdateDescriptorSet(void)
{
// Setup a descriptor image info for the current texture to be used as a combined image sampler.
const vkpp::DescriptorImageInfo lTextureDescriptor
{
mTextureSampler, // Tells the pipeline how to sample the texture, including repeat, border, etc.
mTextureResource.view, // Images are never directly accessed by the shader, but rather through views defining the sub-resources.
mTexture.layout // The current layout of the image. Note: It should always fit the actual use, e.g. shader read.
};
const vkpp::DescriptorBufferInfo lDescriptorBufferInfo
{
mUniformBufferRes.buffer,
0,
sizeof(UniformBufferObject)
};
const std::array<vkpp::WriteDescriptorSetInfo, 2> lWriteDescriptorSets
{ {
// Binding 0: Vertex shader uniform buffer.
{
mDescriptorSet,
0, // dstBindig
vkpp::DescriptorType::eUniformBuffer,
lDescriptorBufferInfo
},
// Binding 1: Fragment shader texture sampler.
// Fragment shader: layout(binding = 1) uniform sampler2D samplerColor;
{
mDescriptorSet,
1, // binding
vkpp::DescriptorType::eCombinedImageSampler, // The descriptor set will use a combined image sampler (sampler and image could be split).
lTextureDescriptor
}
} };
mLogicalDevice.UpdateDescriptorSets(lWriteDescriptorSets);
}
void TexturedPlate::CreateVertexBuffer(void)
{
// Setup vertices for a single uv-mapped quad made from two triangles.
std::array<VertexData, 4> lVertices
{ {
{{1.0f, 1.0f, 0.0f}, {2.0f, 2.0f}, {0.0f, 0.0f, 1.0f}},
{{-1.0f, 1.0f, 0.0f}, {0.0f, 2.0f}, {0.0f, 0.0f, 1.0f}},
{{-1.0f, -1.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f, 1.0f}},
{{1.0f, -1.0f, 0.0f}, {2.0f, 0.0f}, {0.0f, 0.0f, 1.0f}}
} };
const auto lVertexDataSize = sizeof(lVertices);
const vkpp::BufferCreateInfo lBufferCreateInfo
{
lVertexDataSize,
vkpp::BufferUsageFlagBits::eVertexBuffer
};
mVertexBufferRes.Reset(lBufferCreateInfo, vkpp::MemoryPropertyFlagBits::eHostVisible | vkpp::MemoryPropertyFlagBits::eHostCoherent);
auto lMappedMem = mLogicalDevice.MapMemory(mVertexBufferRes.memory, 0, lVertexDataSize);
std::memcpy(lMappedMem, lVertices.data(), lVertexDataSize);
mLogicalDevice.UnmapMemory(mVertexBufferRes.memory);
}
void TexturedPlate::CreateIndexBuffer(void)
{
// Setup indices.
constexpr std::array<uint32_t, 6> lIndices
{
0, 3, 2,
0, 2, 1
};
constexpr auto lIndexDataSize = sizeof(lIndices);
const vkpp::BufferCreateInfo lIndexCreateInfo
{
lIndexDataSize,
vkpp::BufferUsageFlagBits::eIndexBuffer
};
mIndexBufferRes.Reset(lIndexCreateInfo, vkpp::MemoryPropertyFlagBits::eHostVisible | vkpp::MemoryPropertyFlagBits::eHostCoherent);
auto lMappedMem = mLogicalDevice.MapMemory(mIndexBufferRes.memory, 0, lIndexDataSize);
std::memcpy(lMappedMem, lIndices.data(), lIndexDataSize);
mLogicalDevice.UnmapMemory(mIndexBufferRes.memory);
}
void TexturedPlate::CreateUniformBuffer(void)
{
constexpr vkpp::BufferCreateInfo lBufferCreateInfo
{
sizeof(UniformBufferObject),
vkpp::BufferUsageFlagBits::eUniformBuffer
};
mUniformBufferRes.Reset(lBufferCreateInfo, vkpp::MemoryPropertyFlagBits::eHostVisible | vkpp::MemoryPropertyFlagBits::eHostCoherent);
}
void TexturedPlate::UpdateUniformBuffer(void)
{
const auto lWidth = static_cast<float>(mSwapchain.extent.width);
const auto lHeight = static_cast<float>(mSwapchain.extent.height);
const glm::vec3 lCameraPos;
mMVPMatrix.projection = glm::perspective(glm::radians(60.f), lWidth / lHeight, 0.001f, 256.0f);
const auto& lViewMatrix = glm::translate(glm::mat4(), glm::vec3(0.0f, 0.0f, mCurrentZoomLevel));
mMVPMatrix.model = lViewMatrix * glm::translate(glm::mat4(), lCameraPos);
mMVPMatrix.model = glm::rotate(mMVPMatrix.model, glm::radians(mCurrentRotation.x), glm::vec3(1.0f, 0.0f, 0.0f));
mMVPMatrix.model = glm::rotate(mMVPMatrix.model, glm::radians(mCurrentRotation.y), glm::vec3(0.0f, 1.0f, 0.0f));
mMVPMatrix.model = glm::rotate(mMVPMatrix.model, glm::radians(mCurrentRotation.z), glm::vec3(0.0f, 0.0f, 1.0f));
mMVPMatrix.viewPos = glm::vec4(0.0f, 0.0f, -mCurrentZoomLevel, 0.0f);
auto lMappedMem = mLogicalDevice.MapMemory(mUniformBufferRes.memory, 0, sizeof(UniformBufferObject));
std::memcpy(lMappedMem, &mMVPMatrix, sizeof(UniformBufferObject));
mLogicalDevice.UnmapMemory(mUniformBufferRes.memory);
}
vkpp::CommandBuffer TexturedPlate::BeginOneTimeCmdBuffer(void) const
{
const vkpp::CommandBufferAllocateInfo lCmdAllocateInfo
{
mCmdPool, 1
};
auto lCmdBuffer = mLogicalDevice.AllocateCommandBuffer(lCmdAllocateInfo);
constexpr vkpp::CommandBufferBeginInfo lCmdBufferBeginInfo{ vkpp::CommandBufferUsageFlagBits::eOneTimeSubmit };
lCmdBuffer.Begin(lCmdBufferBeginInfo);
return lCmdBuffer;
}
void TexturedPlate::EndOneTimeCmdBuffer(const vkpp::CommandBuffer& aCmdBuffer) const
{
aCmdBuffer.End();
constexpr vkpp::FenceCreateInfo lFenceCreateInfo;
const auto& lFence = mLogicalDevice.CreateFence(lFenceCreateInfo);
const vkpp::SubmitInfo lSubmitInfo{ aCmdBuffer };
mGraphicsQueue.handle.Submit(lSubmitInfo, lFence);
mLogicalDevice.WaitForFence(lFence);
mLogicalDevice.DestroyFence(lFence);
mLogicalDevice.FreeCommandBuffer(mCmdPool, aCmdBuffer);
}
// Create an image barrier for changing the layout of an image and put it into an active command buffer.
template <vkpp::ImageLayout OldLayout, vkpp::ImageLayout NewLayout>
void TexturedPlate::TransitionImageLayout(const vkpp::CommandBuffer& aCmdBuffer, const vkpp::Image& aImage, const vkpp::ImageSubresourceRange& aImageSubRange,
const vkpp::AccessFlags& aSrcAccessMask, const vkpp::AccessFlags& aDstAccessMask)
{
// Create an image barrier object.
const vkpp::ImageMemoryBarrier lImageBarrier
{
aSrcAccessMask, aDstAccessMask,
OldLayout, NewLayout,
aImage,
aImageSubRange
};
// Put barrier inside setup command buffer.
// Put barrier on top of pipeline.
aCmdBuffer.PipelineBarrier(vkpp::PipelineStageFlagBits::eTopOfPipe, vkpp::PipelineStageFlagBits::eTopOfPipe, vkpp::DependencyFlagBits::eByRegion, { lImageBarrier });
}
void TexturedPlate::CreateSemaphores(void)
{
constexpr vkpp::SemaphoreCreateInfo lSemaphoreCreateInfo;
mPresentCompleteSemaphore = mLogicalDevice.CreateSemaphore(lSemaphoreCreateInfo);
mRenderCompleteSemaphore = mLogicalDevice.CreateSemaphore(lSemaphoreCreateInfo);
}
void TexturedPlate::CreateFences(void)
{
constexpr vkpp::FenceCreateInfo lFenceCreateInfo{ vkpp::FenceCreateFlagBits::eSignaled };
for (std::size_t lIndex = 0; lIndex < mDrawCmdBuffers.size(); ++lIndex)
mWaitFences.emplace_back(mLogicalDevice.CreateFence(lFenceCreateInfo));
}
void TexturedPlate::BuildCommandBuffers(void)
{
constexpr vkpp::CommandBufferBeginInfo lCmdBufferBeginInfo;
constexpr std::array<vkpp::ClearValue, 2> lClearValues
{ {
{ 0.129411f, 0.156862f, 0.188235f, 1.0f },
{ 1.0f, 0.0f }
} };
for (std::size_t lIndex = 0; lIndex < mDrawCmdBuffers.size(); ++lIndex)
{
const vkpp::RenderPassBeginInfo lRenderPassBeginInfo
{
mRenderPass,
mFramebuffers[lIndex],
{
{0, 0},
mSwapchain.extent
},
lClearValues
};
const auto& lDrawCmdBuffer = mDrawCmdBuffers[lIndex];
lDrawCmdBuffer.Begin(lCmdBufferBeginInfo);
lDrawCmdBuffer.BeginRenderPass(lRenderPassBeginInfo);
lDrawCmdBuffer.BindVertexBuffer(mVertexBufferRes.buffer, 0);
lDrawCmdBuffer.BindIndexBuffer(mIndexBufferRes.buffer, 0, vkpp::IndexType::eUInt32);
const vkpp::Viewport lViewport
{
0.0f, 0.0f,
static_cast<float>(mSwapchain.extent.width), static_cast<float>(mSwapchain.extent.height)
};
lDrawCmdBuffer.SetViewport(lViewport);
const vkpp::Rect2D lScissor
{
{0, 0},
mSwapchain.extent
};
lDrawCmdBuffer.SetScissor(lScissor);
lDrawCmdBuffer.BindGraphicsPipeline(mGraphicsPipeline);
lDrawCmdBuffer.BindGraphicsDescriptorSet(mPipelineLayout, 0, mDescriptorSet);
lDrawCmdBuffer.DrawIndexed(6);
lDrawCmdBuffer.EndRenderPass();
lDrawCmdBuffer.End();
}
}
void TexturedPlate::Update(void)
{
auto lIndex = mLogicalDevice.AcquireNextImage(mSwapchain.handle, mPresentCompleteSemaphore);
mLogicalDevice.WaitForFence(mWaitFences[lIndex]);
mLogicalDevice.ResetFence(mWaitFences[lIndex]);
constexpr vkpp::PipelineStageFlags lWaitDstStageMask{ vkpp::PipelineStageFlagBits::eColorAttachmentOutput };
const vkpp::SubmitInfo lSubmitInfo
{
1, mPresentCompleteSemaphore.AddressOf(),
&lWaitDstStageMask,
1, mDrawCmdBuffers[lIndex].AddressOf(),
1, mRenderCompleteSemaphore.AddressOf()
};
mPresentQueue.handle.Submit(lSubmitInfo, mWaitFences[lIndex]);
const vkpp::khr::PresentInfo lPresentInfo
{
1, mRenderCompleteSemaphore.AddressOf(),
1, mSwapchain.handle.AddressOf(),
&lIndex
};
mPresentQueue.handle.Present(lPresentInfo);
}
} // End of namespace vkpp::sample.
| 34.424138 | 169 | 0.666934 | po2xel |
9399c81a999864698b991e622d333e5335e5ca59 | 906 | cpp | C++ | Duno/Duno-Core/Graphics/renderEngine/GLEntityReflectiveRenderer.cpp | DunoGameEngine/Duno | f6c0fd5371a73ccb5ea1ba78540854b831b75b7f | [
"Apache-2.0"
] | null | null | null | Duno/Duno-Core/Graphics/renderEngine/GLEntityReflectiveRenderer.cpp | DunoGameEngine/Duno | f6c0fd5371a73ccb5ea1ba78540854b831b75b7f | [
"Apache-2.0"
] | null | null | null | Duno/Duno-Core/Graphics/renderEngine/GLEntityReflectiveRenderer.cpp | DunoGameEngine/Duno | f6c0fd5371a73ccb5ea1ba78540854b831b75b7f | [
"Apache-2.0"
] | null | null | null | #include "GLEntityReflectiveRenderer.h"
#include "GLTextureLoader.h"
#include <iostream>
using namespace std;
/* Define all uniform location handles */
#define CUBE_MAP 6
#define CAMERA_POSITION 7
GLEntityReflectiveRenderer::GLEntityReflectiveRenderer(GLTexture* cubeMap):
GLEntityRenderer("entity/reflective", 2),
m_cube_map(cubeMap)
{
/* Map all uniforms */
getShader()->setLocation(CUBE_MAP, "cubeMap");
getShader()->setLocation(CAMERA_POSITION, "cameraPosition");
/* Load the cube map to texture unit 2 */
getShader()->bind();
getShader()->loadInt(2, CUBE_MAP);
getShader()->unbind();
}
/* Extends Render Model Function */
void GLEntityReflectiveRenderer::addRenderModel(DunoGameObject* model, DunoCamera* cam)
{
/* Bind the cube map texture */
GLTextureLoader::bindTextureCube(m_cube_map, 2);
getShader()->loadVector(cam->getPosition(), CAMERA_POSITION);
} | 30.2 | 88 | 0.735099 | DunoGameEngine |
939a77b5b4183acd140baecb92329ef7294c17f6 | 31,105 | cpp | C++ | emulator/src/mame/drivers/lindbergh.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | 1 | 2022-01-15T21:38:38.000Z | 2022-01-15T21:38:38.000Z | emulator/src/mame/drivers/lindbergh.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | emulator/src/mame/drivers/lindbergh.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | // license:BSD-3-Clause
// copyright-holders:Olivier Galibert
/***************************************************************************
Sega Lindbergh skeleton driver
TODO:
- tests area 0xd0000 - 0xd000f, wants an undumped ROM in there?
- Apparently there's no way to avoid a dead lock at 0xfd085, perhaps
tied to the aforementioned?
***************************************************************************
Lindbergh
Sega 2005-2009
This is a "PC-based" arcade system. Different configurations have different colored boxes.
The version documented here is the red box. The PC part of it is mostly just the CPU,
Intel North/South-bridge chipset and AGP/PCI card slots etc. The main board is still
a typically custom-made Sega arcade PCB using a custom nVIDIA GeForce video card.
The main board also has a slot for a compact flash card. Primary storage media is HDD.
Games are installed from a DVD. Both the CF and HDD are locked and unreadable on a regular PC.
The familiar PIC is still present on the back of the system and likely decrypts the HDD and/or DVD.
On this red box the CPU is a Celeron D at 2.8GHz. RAM is 512M DDR PC3200
The box has Sega number 845-0001D-02
Security
--------
The security seems to work in multiple steps. The information here
is a combination of our research and things found on the internet.
- At boot, the bios unlocks the CF card through an IDE command. There
is also a hardware heartbeat signal on the IDE bus to avoid
hotswapping, and making it hard to dump the card outside of a Lindberg
motherboard.
- The system boots on the CF which holds a customized Montavista linux.
- The CF system can either install the game (from the DVD) or start it
(on the HD) through the "/usr/sbin/segaboot" executable in the second
partition.
- The DVD includes an ISO-9660 filesystem at a (game-dependant)
offset. It has a handful of files, all encrypted. Of specific
interest and the su[0-3].dat files which are system updates, and the
frontend file which handles the setup of all the other files for the
game.
- The PIC includes an AES-CBC engine and has as data an IV, a key,
some game-specific identification information, and two pre and
post-whitening values. Everything but the key is dumpable through
commands, but the key seems well-protected. It's not realistic to
decrypt very large amounts of data through it though, the bandwidth
would be way too low.
- The CF decrypts the dvd/hd files with a custom crypto system which
is keyed by the result of decrypting 16 times 0x00, 16 times 0x01,
..., 16 times 0x0b through the PIC, giving a 176 bytes secondary key.
segaboot (in the second partition) and lxdecrypt_hard (in the first
partition's initrd) take care of that.
- The HD is unlocked by the CF with lxunlock.hdb in the first
partition's initrd. The method varies depending on the HD model.
That code is also capable of unlocking the CF (but don't forget
the hardware hearbeat there).
Lindbergh Game List
-------------------
Security Sega Part#
Game Dongle Sticker printed on PIC DVD Code
------------------------------------------------------------------------------------------
2 Spicy 253-5508-0491 317-0491-COM ^DVP-0027A
After Burner Climax (EXPORT) 253-5508-0440A ^317-0440-COM DVP-0009
After Burner Climax CE ? ? DVP-0031A
After Burner Climax SDX (rev A) ? ? DVP-0018A
Ami-Gyo (rev C) ? ? DVP-0007C
Ami-Gyo ? ? DVP-0028
Answer X Answer 253-5508-0618J 317-0618-JPN DVP-0025H ???
Answer X Answer 1.1 ? ? ?
Answer X Answer DX ? ? ?
Answer X Answer Premium ? ? ?
Answer X Answer 2 ? ? DVP-0067
Atractive Deck Poker (rev C) ? ? DVP-0033C
Cloud Nine (rev E) ? ? DVP-0034E
Club Majesty Extend ? ? ?
Club Majesty Formal ? ? ?
Cosmic Challenge ? ? DVP-0032
Cosmic Challenge (rev C) ? ? DVP-0032C
Derby Owners Club 2008: Feel the Rush ? ? DVP-0047A
Derby Owners Club 2008: Feel the Rush ? ? DVP-5006C
Derby Owners Club 2008: Feel the Rush V2.0 ? ? ?
Derby Owners Club 2009: Ride For the Life ? ? DVP-5014
Ghost Squad Evolution ? ? ^DVP-0029A
Harley Davidson: King of the Road ? ? ?
Hummer ? ? DVP-0057B
Hummer Extreme 253-5508-???? ^317-????-COM DVP-0079 ???
Initial D Arcade Stage 4 253-5508-0486J 317-0486-JPN DVP-0019
Initial D Arcade Stage 4 (rev A) 253-5508-0486J 317-0486-JPN DVP-0019A
Initial D Arcade Stage 4 (rev B) 253-5508-0486J 317-0486-JPN DVP-0019B
Initial D Arcade Stage 4 (rev C) 253-5508-0486J 317-0486-JPN ^DVP-0019C
Initial D Arcade Stage 4 (rev D) 253-5508-0486J 317-0486-JPN DVP-0019D
Initial D Arcade Stage 4 (rev G) 253-5508-0486J 317-0486-JPN DVP-0019G
Initial D4 253-5508-0486E 317-0486-EXP DVP-0030
Initial D4 (rev B) 253-5508-0486E 317-0486-EXP DVP-0030B
Initial D4 (rev C) 253-5508-0486E 317-0486-EXP ^DVP-0030C
Initial D4 (rev D) 253-5508-0486E 317-0486-EXP ^DVP-0030D
Initial D Arcade Stage 5 (rev A) ? ? DVP-0070A
Initial D Arcade Stage 5 EXP 2.0 ? ? DVP-0075
INFO STATION 2 (rev C) ? ? DVP-0050C
Let's Go Jungle (EXPORT) 253-5508-0442 317-0442-COM DVP-0011
Let's Go Jungle Special (rev A) ? ? DVP-0036A
MJ4 (rev F) ? ? DVP-0049F
MJ4 Evolution ? ? DVP-0081
OutRun 2 Special Tours (EXPORT) 253-5508-0452 317-0452-COM ?
OutRun 2 SP SDX ? ? DVP-0015A
Primeval Hunt 253-5508-0512 317-0512-COM ^DVP-0048A
R-Tuned: Ultimate Street Racing ? ? DVP-0060
Rambo (EXPORT) 253-5508-0540 ^317-0540-COM ^DVP-0069
SEGA Network Casino Club Ver. 2 ? ? DVP-0053
SEGA Network Casino Club Ver. 2 (rev B) ? ? DVP-0053B
SEGA Network Taisen Mahjong MJ4 (rev A) ? ? DVP-0049A
SEGA Network Taisen Mahjong MJ4 (rev F) ? ? DVP-0049F
SEGA Network Taisen Mahjong MJ4 (rev G) ? ? DVP-0049G
SEGA-Race TV (EXPORT) 253-5508-0504 ^317-0504-COM ^DVP-0044
StarHorse 2: New Generation (rev J) ? ? DVP-0001J
StarHorse 2: Second Fusion (rev E) ? ? DVP-0024E
StarHorse 2: Third Evolution (rev G) ? ? DVP-0046G
StarHorse 2: Third Evolution (rev D) ? ? DVP-0054D
StarHorse 2: Fifth Expansion (rev D) ? ? DVP-0082D
StarHorse 2: Fifth Expansion (rev E) ? ? DVP-0082E
The House Of The Dead 4 (EXPORT) (rev A) 253-5508-0427 ^317-0427-COM ^DVP-0003A
The House Of The Dead 4 (EXPORT) (rev B) ? ? DVP-0003B
The House Of The Dead EX (JAPAN) 253-5508-0550 ^317-0550-JPN DVP-0063
The House Of the Dead 4 Special (rev B) ? ? DVP-0010B
Router Update [For VTF] ? ? DVP-0026
VBIOS Update ? ? ^DVP-0021B
VBIOS Update [For VTF] ? ? DVP-0023A
VBIOS Update [For VTF] ? ? DVP-0023C
Virtua Fighter 5 ? ? DVP-00043
Virtua Fighter 5 R (rev D) ? ? DVP-5004D
Virtua Fighter 5 (EXPORT) (rev A) 253-5508-0438 317-0438-COM DVP-0008A
Virtua Fighter 5 (EXPORT) (rev B) 253-5508-0438 317-0438-COM DVP-0008B
Virtua Fighter 5 (EXPORT) (rev E) 253-5508-0438 317-0438-COM DVP-0008E
Virtua Tennis 3 (Power Smash 3) ? ? DVP-0005
Virtua Tennis 3 (Power Smash 3) (EXPORT) 253-5508-0434 ^317-0434-COM DVP-0005A
Virtua Tennis 3 (JAPAN) 253-5508-0506 317-0506-JPN ^DVP-0005C
WCC Football Intercontinental Clubs 2006-2007 ? ? ?
WCC Football Intercontinental Clubs 2007-2008 ? ? ?
WCC Football Intercontinental Clubs 2008-2009 ? ? DVP-5012
WCC Football Intercontinental Clubs 2009-2010 ? ? ?
Wheel Maniacs (rev D) ? ? DVP-0035D
^ denotes these parts are archived.
This list is not necessarily correct or complete.
Corrections and additions to the above are welcome.
Mainboard
---------
838-14487
Sticker: 838-14673
|----| |-----|
|USB ||---||1/8 | |-------|
|USB ||USB||AUDIO| |SERIAL1| SECURITY
-------------------|RJ45||USB||JACKS|-|SERIAL2|--CONNECTOR---|
|OSC(D245L6I) |
| VIA OSC(D250L6I) |
| VT1616 |-------| |
| |82541PI| 12V_POWER |
| |INTEL | |
| P P P P |-------| |-----------| |
| C C C C ISL6556B | | |
| I I I I A |-------| | | |
| 4 3 2 1 G |JG82875| | | |
| P |SL8DB | | CPU | |
| | | | | |
| |INTEL | | | |
| 14.31818MHz |-------| | | |
|JP |-----------| |
|12 |
|34 |-------| 932S208DG SIMM1 |
|56 |6300ESB| |
|78 |SL7XJ | SIMM2(not used) |
|910 | | |
|1112|INTEL | SIMM3(not used) |
| |-------| |
|32.768kHz |---------| SIMM4(not used) |
| 3V_BATT |COMPACT | |
| MB_BIOS.3J7 |FLASH | IDE40 |
| |SLOT | IDE40 ATX_POWER |
|------------------|---------|-------------------------------|
Notes:
CPU - Lindbergh RED: Intel Celeron D 335 SL8HM 2.8GHz 256k L2 cache, 533MHz FSB.
Lindbergh YELLOW: Intel Pentium 4 3.00GHz/1M/800 SL8JZ
SIMM1 - Lindbergh RED: 512M DDR PC3200
Lindbergh YELLOW: 1GB DDR PC3200
82541PI - Intel Gigabit Ethernet Controller
6300ESB - Intel Southbridge IC
JG82875 - Intel Northbridge IC
ISL6556B - Intersil ISL6556B Optimized Multiphase PWM Controller with 6-Bit
DAC and Programmable Internal Temperature Compensation
932S208DG- IDT 932S208DG Programmable PLL Clock synthesizer
VT1616 - VIA VT1616 6-channel AC97 codec sound IC
JP - Jumpers....
1-3 Normal (SET ON)
1-2 CMOS
3-4 PASSWORD
5-6 PCBL
7-8 BIOS
9-10 CF SLAVE
11-12 CF MASTER (SET ON)
IDE40 - ATA133 IDE connector(s)
A 40GB HDD is plugged in via an 80-pin flat cable
This game is 'Too Spicy'. The hard drive is a Hitachi Deskstar
model HDS728040PLAT20. Capacity is 41GB. C/H/S 16383/16/63
LBA 80,418,240 sectors. In the model number 8040 means 80GB full
capacity but only 40GB is actually available
P/N: 0A30209 BA17730E6B
Serial: EETNGM0G
CF SLOT - Accepts a compact flash card. The card is required to boot the system.
Revision C and E have been seen. StarHorse 2 has it's own special card.
There may be other revisions out there.
Sticker: LINDBERGH
MDA-C0004A
REV. C
Rear Board incorporating Security Board (plugged into main board security connector)
---------------------------------------
This board has the power input connectors on it and holes for access to the mainboard
I/O conections (LAN/COM/USB/speakers etc). Lower left is where the security board is plugged in.
837-14520R
171-8322C
839-1275
Sticker 839-1275R
|----------------------------------|
| |
| |
| POWER POWER |
| CN5 |
| |
| LED LED |
| |
| DSW(8) |
| |
| |
| SW2 SW1 |
| C/W |
| |
| CN2 |
|-------------|COM1 SPK_REAR LAN |
| | USB4|
| DIP18.IC1 | USB3|
| |COM2 SPK_FR USB2|
|SECURITY_CONN| USB1|
|-------------|--------------------|
DSW(8) - OFF,OFF,OFF,ON,ON,OFF,OFF,ON
DIP18.IC1 - DIP18 socket for protection PIC16F648A
Video Card (plugged into AGP slot)
----------
nVIDIA 180-10508-0000-A00
Sticker: BIOS VERSION 5.73.22.55.08
Sticker: 900-10508-2304-000 D 032 Made In China
Sticker: 600-10508-0004-000 J
Sticker: GeForce 7600 GS 0325206031558
|----------------------------------------|
| VRAM *VRAM VRAM *VRAM |-|
| | |POWER_CONN
| *VRAM VRAM |---------| *VRAM VRAM | |
|-V |NVIDIA | |-|
| G |U611B269 | |
|-A |0646B1S | |
| 27MHz |NA6105.00P |
| |G73-N-B1 | |
| |---------| |
| |
|-D *RT9173C |-------| 25MHz |
| V |NVIDIA | |
| I *VID_BIOS.U504 |HSI-N-A4 |
|- |4MJHT07B30 0607|
| |-------| |
| |----------| AGP |----------|
|----| |-------------|
Notes:
* - These parts on the other side of the PCB
VRAM - QIMONDA HYB18T256161AFL25 WVV10017 256Mbit x16 DDR2 SDRAM (P-TFBGA-84)
VID_BIOS - SST 25VF512 512Kbit serial flash ROM (video BIOS) at location U504 (SOIC8)
JVS I/O Card (plugged into PCI slot #4)
------------
Sega 2004
171-8300C
837-14472R
Sticker: 837-14472R91
|-----------------------------------------|
| 3V_BATT|
| FLASH.IC6 DS14185 |
| D442012 |
| |
|LED |
| DS485 |
|USB 0.1F |
| 5.5v |
| EDS1232 |--------| SUPERCAP
| RTL8201 |FREESCALE |
| |MPC8248 | |
|RJ45 25MHz | |48MHz |
| | |58.9824MHz |
| ISP1106 |--------| |
|mUSB PQ070XZ1H|
| |--------| PCI |-------------|
|--| |---------------|
Notes:
FLASH.IC6 - Spansion S29AL032D70 32Mbit flash ROM labelled 'FPR-24370B' (TSOP48)
DS14185 - National Semiconductor DS14185 EIA/TIA-232 3 Driver x 5 Receiver (SOIC10)
DS485 - National Semiconductor DS485 Low Power RS-485/RS-422 Multipoint Transceiver (SOIC8)
MPC8248 - Freescale MPC8248 PowerQUICC II Family Multi-Channel Controller (PBGA516)
EDS1232 - Elpida EDS1232AATA-75-E 128Mbit SDRAM (4M word x 32bit)
D442012 - NEC D442012AGY-BB70 2Mbit CMOS Static RAM (128k-word x 16bit)
ISP1106 - NXP Semiconductor ISP1106 Advanced Universal Serial Bus transceiver (SSOIC16)
RTL8201 - Realtek RTL8201 Single Chip Single Port 10/100M Fast Ethernet IC (QFP48)
mUSB - Mini USB connector
JVS I/O Board (connects arcade machine controls etc to PC)
-------------
Sega 2005
837-14572
171-8357B
|------------------------|
| USB_B USB_A CN6 CN7 CN8|
| GH6-2F |
| DS485 14.745MHz |
| UPC393 |
| 315-6414 CN9|
| |
|CN1 CN2 CN3 |
|------------------------|
*/
#include "emu.h"
#include "cpu/i386/i386.h"
#include "machine/pci.h"
#include "machine/i82875p.h"
#include "machine/i6300esb.h"
#include "machine/pci-usb.h"
#include "machine/pci-apic.h"
#include "machine/pci-sata.h"
#include "machine/pci-smbus.h"
#include "machine/i82541.h"
#include "machine/segabb.h"
#include "sound/pci-ac97.h"
#include "sound/sb0400.h"
#include "video/gf7600gs.h"
class lindbergh_state : public driver_device
{
public:
lindbergh_state(const machine_config &mconfig, device_type type, const char *tag);
virtual void machine_start() override;
virtual void machine_reset() override;
void lindbergh(machine_config &config);
};
lindbergh_state::lindbergh_state(const machine_config &mconfig, device_type type, const char *tag) : driver_device(mconfig, type, tag)
{
}
void lindbergh_state::machine_start()
{
}
void lindbergh_state::machine_reset()
{
}
MACHINE_CONFIG_START(lindbergh_state::lindbergh)
MCFG_CPU_ADD("maincpu", PENTIUM4, 28000000U*5) /* Actually Celeron D at 2,8 GHz */
MCFG_PCI_ROOT_ADD( ":pci")
MCFG_I82875P_HOST_ADD( ":pci:00.0", 0x103382c0, ":maincpu", 512*1024*1024)
MCFG_I82875P_AGP_ADD( ":pci:01.0")
MCFG_GEFORCE_7600GS_ADD( ":pci:01.0:00.0", 0x10de02e1)
MCFG_I82875P_OVERFLOW_ADD( ":pci:06.0", 0x103382c0)
MCFG_PCI_BRIDGE_ADD( ":pci:1c.0", 0x808625ae, 0x02)
MCFG_I82541PI_ADD( ":pci:1c.0:00.0", 0x103382c0)
MCFG_USB_UHCI_ADD( ":pci:1d.0", 0x808625a9, 0x02, 0x103382c0)
MCFG_USB_UHCI_ADD( ":pci:1d.1", 0x808625aa, 0x02, 0x103382c0)
MCFG_I6300ESB_WATCHDOG_ADD( ":pci:1d.4", 0x103382c0)
MCFG_APIC_ADD( ":pci:1d.5", 0x808625ac, 0x02, 0x103382c0)
MCFG_USB_EHCI_ADD( ":pci:1d.7", 0x808625ad, 0x02, 0x103382c0)
MCFG_PCI_BRIDGE_ADD( ":pci:1e.0", 0x8086244e, 0x0a)
MCFG_SB0400_ADD( ":pci:1e.0:02.0", 0x11021101)
MCFG_SEGA_LINDBERGH_BASEBOARD_ADD(":pci:1e.0:03.0")
MCFG_I6300ESB_LPC_ADD( ":pci:1f.0")
MCFG_LPC_ACPI_ADD( ":pci:1f.0:acpi")
MCFG_LPC_RTC_ADD( ":pci:1f.0:rtc")
MCFG_LPC_PIT_ADD( ":pci:1f.0:pit")
MCFG_SATA_ADD( ":pci:1f.2", 0x808625a3, 0x02, 0x103382c0)
MCFG_SMBUS_ADD( ":pci:1f.3", 0x808625a4, 0x02, 0x103382c0)
MCFG_AC97_ADD( ":pci:1f.5", 0x808625a6, 0x02, 0x103382c0)
MACHINE_CONFIG_END
#define LINDBERGH_BIOS \
ROM_REGION32_LE(0x100000, ":pci:1f.0", 0) /* PC bios, location 3j7 */ \
ROM_SYSTEM_BIOS(0, "bios0", "6.0.0010 alternate version") \
ROMX_LOAD("6.0.0010a.bin", 0x00000, 0x100000, CRC(10dd9b76) SHA1(1fdf1f921bc395846a7c3180fbdbc4ca287a9670), ROM_BIOS(1) ) \
ROM_SYSTEM_BIOS(1, "bios1", "6.0.0009") \
ROMX_LOAD("6.0.0009.bin", 0x00000, 0x100000, CRC(5ffdfbf8) SHA1(605bc4967b749b4e6d13fc2ebb845ba956a259a7), ROM_BIOS(2) ) \
ROM_SYSTEM_BIOS(2, "bios2", "6.0.0010") \
ROMX_LOAD("6.0.0010.bin", 0x00000, 0x100000, CRC(ea2bf888) SHA1(c9c5b6f0d4f4f36620939b15dd2f128a74347e37), ROM_BIOS(3) ) \
\
ROM_REGION(0x400000, ":pci:1e.0:03.0", 0) /* Baseboard MPC firmware */ \
ROM_LOAD("fpr-24370b.ic6", 0x000000, 0x400000, CRC(c3b021a4) SHA1(1b6938a50fe0e4ae813864649eb103838c399ac0)) \
\
ROM_REGION32_LE(0x10000, ":pci:01.0:00.0", 0) /* Geforce bios extension (custom for the card) */ \
ROM_LOAD("vid_bios.u504", 0x00000, 0x10000, CRC(f78d14d7) SHA1(f129787e487984edd23bf344f2e9500c85052275)) \
DISK_REGION("cf") \
DISK_IMAGE_READONLY("mda-c0004a_revb_lindyellow_v2.4.20_mvl31a_boot_2.01", 0, SHA1(e13da5f827df852e742b594729ee3f933b387410))
ROM_START(lindbios)
LINDBERGH_BIOS
ROM_END
ROM_START(hotd4)
LINDBERGH_BIOS
ROM_REGION(0x2000, ":pic", 0)
ROM_LOAD("317-0427-com.bin", 0, 0x2000, CRC(ef4a120c) SHA1(fcc0386fa708af9e010e40e1d259a6bd95e8b9e2)) // PIC was added from Rev A
DISK_REGION("dvd")
DISK_IMAGE_READONLY("dvp-0003b", 0, SHA1(67f2565338f1e8df4c6cfc83447f490f75541b16))
ROM_END
ROM_START(hotd4a)
LINDBERGH_BIOS
ROM_REGION(0x2000, ":pic", 0) // PIC security 253-5508-0427 / 317-0427-COM
ROM_LOAD("317-0427-com.bin", 0, 0x2000, CRC(ef4a120c) SHA1(fcc0386fa708af9e010e40e1d259a6bd95e8b9e2))
DISK_REGION("dvd")
DISK_IMAGE_READONLY("dvp-0003a", 0, SHA1(46544e28735f55418dd78bd19446093874438264))
ROM_END
ROM_START(vf5)
LINDBERGH_BIOS
ROM_REGION(0x2000, ":pic", 0) // PIC security 253-5508-0438 / 317-0438-COM
ROM_LOAD("317-0438-com.bin", 0, 0x2000, CRC(9aeb15d3) SHA1(405ddc44b2b40b72cfe2a081a0d5e43ceb9a380e))
DISK_REGION("dvd")
DISK_IMAGE_READONLY("dvp-0008e", 0, NO_DUMP)
ROM_END
ROM_START(abclimax)
LINDBERGH_BIOS
ROM_REGION(0x2000, ":pic", 0) // PIC security 253-5508-0440 / 317-0440-COM
ROM_LOAD("317-0440-com.bin", 0, 0x2000, CRC(8d09e717) SHA1(6b25982f7042541874115d33ea5d0c028140a962))
DISK_REGION("dvd")
DISK_IMAGE_READONLY("dvp-0009", 0, NO_DUMP)
ROM_END
ROM_START(letsgoju)
LINDBERGH_BIOS
ROM_REGION(0x2000, ":pic", 0) // PIC security 253-5508-0442 / 317-0442-COM
ROM_LOAD("317-0442-com.bin", 0, 0x2000, CRC(b706efbb) SHA1(97c2b65e521113c5201f0b588fcb37a39148a637))
DISK_REGION("dvd")
DISK_IMAGE_READONLY("dvp-0011", 0, NO_DUMP)
ROM_END
ROM_START(outr2sdx)
LINDBERGH_BIOS
ROM_REGION(0x2000, ":pic", 0) // PIC security 253-5508-0452 / 317-0452-COM (to verify, may be the one for OutRun 2 Special Tours)
ROM_LOAD("317-0452-com.bin", 0, 0x2000, CRC(f5b7bb3f) SHA1(6b179b255b3d29e5ce61902eeae4da07177a2943))
DISK_REGION("dvd")
DISK_IMAGE_READONLY("dvp-0015a", 0, NO_DUMP)
ROM_END
ROM_START(psmash3)
LINDBERGH_BIOS
ROM_REGION(0x2000, ":pic", 0) // PIC security 253-5508-0434 / 317-0434-COM
ROM_LOAD("317-0434-com.bin", 0, 0x2000, CRC(70e3b202) SHA1(4925a288f937d54529abe6ef467c9c23674e47f0))
DISK_REGION("dvd")
DISK_IMAGE_READONLY("dvp-0005a", 0, NO_DUMP)
ROM_END
ROM_START(vtennis3)
LINDBERGH_BIOS
ROM_REGION(0x2000, ":pic", 0) // PIC security 253-5508-0506 / 317-0506-JPN
ROM_LOAD("317-0506-jpn.bin", 0, 0x2000, NO_DUMP)
DISK_REGION("dvd")
DISK_IMAGE_READONLY("dvp-0005c", 0, SHA1(1fd689753c4b70dff0286cb7f623ee7fd439db62))
ROM_END
ROM_START(2spicy)
LINDBERGH_BIOS
ROM_REGION(0x2000, ":pic", 0) // PIC security 253-5508-0491 / 317-0491-COM
ROM_LOAD("317-0491-com.bin", 0, 0x2000, NO_DUMP)
DISK_REGION("dvd")
DISK_IMAGE_READONLY("dvp-0027a", 0, SHA1(da1aacee9e32e813844f4d434981e69cc5c80682))
ROM_END
ROM_START(ghostsev)
LINDBERGH_BIOS
DISK_REGION("dvd")
DISK_IMAGE_READONLY("dvp-0029a", 0, SHA1(256d9e8a6d61e1bcf65b17b8ed70fbc58796f7b1))
ROM_END
ROM_START(initiad4)
LINDBERGH_BIOS
ROM_REGION(0x2000, ":pic", 0) // PIC security 253-5508-0486E / 317-0486-COM
ROM_LOAD("317-0486-com.bin", 0, 0x2000, NO_DUMP)
DISK_REGION("dvd")
DISK_IMAGE_READONLY("dvp-0030d", 0, SHA1(e43e6d22fab4eceb81db8309e4634e049d9c41e6))
ROM_END
ROM_START(initiad4c)
LINDBERGH_BIOS
ROM_REGION(0x2000, ":pic", 0) // PIC security 253-5508-0486E / 317-0486-COM
ROM_LOAD("317-0486-com.bin", 0, 0x2000, NO_DUMP)
DISK_REGION("dvd")
DISK_IMAGE_READONLY("dvp-0030c", 0, SHA1(b1919f28539afec4c4bc52357e5210a090b5ae32))
ROM_END
ROM_START(segartv)
LINDBERGH_BIOS
ROM_REGION(0x2000, ":pic", 0) // PIC security 253-5508-0504 / 317-0504-COM
ROM_LOAD("317-0504-com.bin", 0, 0x2000, CRC(ae7eaea8) SHA1(187e417e0b5543d95245364b547925426aa9f80e))
DISK_REGION("dvd")
DISK_IMAGE_READONLY("dvp-0044", 0, SHA1(914aa23ece8aaf0f1942f77272b3a87d10f7a7db))
ROM_END
ROM_START(hotdex)
LINDBERGH_BIOS
ROM_REGION(0x2000, ":pic", 0) // PIC security 253-5508-0550 / 317-0550-JPN
ROM_LOAD("317-0550-jpn.bin", 0, 0x2000, CRC(7e247f13) SHA1(d416b0e7742b32eb31443967e84ef93fc9e56dfb))
DISK_REGION("dvd")
DISK_IMAGE_READONLY("hotdex", 0, NO_DUMP)
ROM_END
ROM_START(primevah)
LINDBERGH_BIOS
ROM_REGION(0x2000, ":pic", 0) // PIC security 253-5508-0512 / 317-0512-COM
ROM_LOAD("317-0512-com.bin", 0, 0x2000, NO_DUMP)
DISK_REGION("dvd")
DISK_IMAGE_READONLY("dvp-0048a", 0, SHA1(0c3b87b7309cf67ece54fc5cd5bbcfc7dc04083f))
ROM_END
ROM_START(rambo)
LINDBERGH_BIOS
ROM_REGION(0x2000, ":pic", 0) // PIC security 253-5508-0540 / 317-0540-COM
ROM_LOAD("317-0540-com.bin", 0, 0x2000, CRC(fd9a7bc0) SHA1(140b05573e25a41c1237c7a96c8e099efbfd75b8))
DISK_REGION("dvd")
DISK_IMAGE_READONLY("dvp-0069", 0, SHA1(1f3401b652c45db2b843360aff9cda862c2832c0))
ROM_END
ROM_START(hummerxt)
LINDBERGH_BIOS
ROM_REGION(0x2000, ":pic", 0) // PIC security id unknown
ROM_LOAD("hummerextreme.bin", 0, 0x2000, CRC(524bc69a) SHA1(c79b6bd384196c169e40e623f4c80c8b9eb11f81))
ROM_END
ROM_START(lbvbiosu)
LINDBERGH_BIOS
DISK_REGION("dvd")
DISK_IMAGE_READONLY("dvp-0021b", 0, SHA1(362ac028ba19ba4762678953a033034a5ee8ad53))
ROM_END
GAME(1999, lindbios, 0, lindbergh, 0, lindbergh_state, 0, ROT0, "Sega", "Sega Lindbergh Bios", MACHINE_IS_BIOS_ROOT)
GAME(2005, hotd4, lindbios, lindbergh, 0, lindbergh_state, 0, ROT0, "Sega", "The House of the Dead 4 (Export) (Rev B)", MACHINE_NOT_WORKING|MACHINE_UNEMULATED_PROTECTION|MACHINE_NO_SOUND)
GAME(2005, hotd4a, hotd4, lindbergh, 0, lindbergh_state, 0, ROT0, "Sega", "The House of the Dead 4 (Export) (Rev A)", MACHINE_NOT_WORKING|MACHINE_UNEMULATED_PROTECTION|MACHINE_NO_SOUND)
GAME(2005, vf5, lindbios, lindbergh, 0, lindbergh_state, 0, ROT0, "Sega", "Virtua Fighter 5 (Export)", MACHINE_NOT_WORKING|MACHINE_UNEMULATED_PROTECTION|MACHINE_NO_SOUND)
GAME(2006, abclimax, lindbios, lindbergh, 0, lindbergh_state, 0, ROT0, "Sega", "After Burner Climax (Export)", MACHINE_NOT_WORKING|MACHINE_UNEMULATED_PROTECTION|MACHINE_NO_SOUND)
GAME(2006, letsgoju, lindbios, lindbergh, 0, lindbergh_state, 0, ROT0, "Sega", "Let's Go Jungle (Export)", MACHINE_NOT_WORKING|MACHINE_UNEMULATED_PROTECTION|MACHINE_NO_SOUND)
GAME(2006, outr2sdx, lindbios, lindbergh, 0, lindbergh_state, 0, ROT0, "Sega", "OutRun 2 SP SDX", MACHINE_NOT_WORKING|MACHINE_UNEMULATED_PROTECTION|MACHINE_NO_SOUND)
GAME(2006, psmash3, lindbios, lindbergh, 0, lindbergh_state, 0, ROT0, "Sega", "Power Smash 3 / Virtua Tennis 3 (Export)", MACHINE_NOT_WORKING|MACHINE_UNEMULATED_PROTECTION|MACHINE_NO_SOUND)
GAME(2006, vtennis3, lindbios, lindbergh, 0, lindbergh_state, 0, ROT0, "Sega", "Virtua Tennis 3 (Japan)", MACHINE_NOT_WORKING|MACHINE_UNEMULATED_PROTECTION|MACHINE_NO_SOUND)
GAME(2007, 2spicy, lindbios, lindbergh, 0, lindbergh_state, 0, ROT0, "Sega", "2 Spicy", MACHINE_NOT_WORKING|MACHINE_UNEMULATED_PROTECTION|MACHINE_NO_SOUND)
GAME(2007, ghostsev, lindbios, lindbergh, 0, lindbergh_state, 0, ROT0, "Sega", "Ghost Squad Evolution", MACHINE_NOT_WORKING|MACHINE_UNEMULATED_PROTECTION|MACHINE_NO_SOUND)
GAME(2007, initiad4, lindbios, lindbergh, 0, lindbergh_state, 0, ROT0, "Sega", "Initial D4 (Rev D)", MACHINE_NOT_WORKING|MACHINE_UNEMULATED_PROTECTION|MACHINE_NO_SOUND)
GAME(2007, initiad4c, initiad4, lindbergh, 0, lindbergh_state, 0, ROT0, "Sega", "Initial D4 (Rev C)", MACHINE_NOT_WORKING|MACHINE_UNEMULATED_PROTECTION|MACHINE_NO_SOUND)
GAME(2007, segartv, lindbios, lindbergh, 0, lindbergh_state, 0, ROT0, "Sega", "Sega Race-TV (Export)", MACHINE_NOT_WORKING|MACHINE_UNEMULATED_PROTECTION|MACHINE_NO_SOUND)
GAME(2008, hotdex, lindbios, lindbergh, 0, lindbergh_state, 0, ROT0, "Sega", "The House of the Dead EX (Japan)", MACHINE_NOT_WORKING|MACHINE_UNEMULATED_PROTECTION|MACHINE_NO_SOUND)
GAME(2008, primevah, lindbios, lindbergh, 0, lindbergh_state, 0, ROT0, "Sega", "Primeval Hunt", MACHINE_NOT_WORKING|MACHINE_UNEMULATED_PROTECTION|MACHINE_NO_SOUND)
GAME(2008, rambo, lindbios, lindbergh, 0, lindbergh_state, 0, ROT0, "Sega", "Rambo (Export)", MACHINE_NOT_WORKING|MACHINE_UNEMULATED_PROTECTION|MACHINE_NO_SOUND)
GAME(2009, hummerxt, lindbios, lindbergh, 0, lindbergh_state, 0, ROT0, "Sega", "Hummer Extreme", MACHINE_NOT_WORKING|MACHINE_UNEMULATED_PROTECTION|MACHINE_NO_SOUND)
GAME(200?, lbvbiosu, lindbios, lindbergh, 0, lindbergh_state, 0, ROT0, "Sega", "VBios updater", MACHINE_NOT_WORKING|MACHINE_UNEMULATED_PROTECTION|MACHINE_NO_SOUND)
| 49.216772 | 191 | 0.553191 | rjw57 |
939c55a2b6c312de1bdc90ecd3bb4d66bd403efe | 98 | cpp | C++ | Arrays/test.cpp | sans712/SDE-Interview-Questions | 44f5bda60b9ed301b93a944e1c333d833c9b054b | [
"MIT"
] | null | null | null | Arrays/test.cpp | sans712/SDE-Interview-Questions | 44f5bda60b9ed301b93a944e1c333d833c9b054b | [
"MIT"
] | null | null | null | Arrays/test.cpp | sans712/SDE-Interview-Questions | 44f5bda60b9ed301b93a944e1c333d833c9b054b | [
"MIT"
] | null | null | null | #include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int main() {
} | 8.166667 | 20 | 0.704082 | sans712 |
4d36b3887a70c499e0c5783f4c75ed2fe0b3bd5b | 226 | cpp | C++ | sumofdigits.cpp | deepanshu1422/450Questions | 614a6bcb66f3202a62c375c0c0a63365e1021110 | [
"Apache-2.0"
] | null | null | null | sumofdigits.cpp | deepanshu1422/450Questions | 614a6bcb66f3202a62c375c0c0a63365e1021110 | [
"Apache-2.0"
] | null | null | null | sumofdigits.cpp | deepanshu1422/450Questions | 614a6bcb66f3202a62c375c0c0a63365e1021110 | [
"Apache-2.0"
] | null | null | null | #include<iostream>
using namespace std;
int sumofdigits(int a)
{
if(a/10==0)
{
return a;
}
int sum=a%10+sumofdigits(a/10);
return sum;
}
int main()
{
int b =sumofdigits(123);
cout<<b;
} | 10.761905 | 35 | 0.553097 | deepanshu1422 |
4d36bae1fed44345c75187bc870290e0a6a85b3e | 1,486 | cpp | C++ | Sid's Levels/Level - 2/Matrix/MedianInRowSortedMatrix.cpp | Tiger-Team-01/DSA-A-Z-Practice | e08284ffdb1409c08158dd4e90dc75dc3a3c5b18 | [
"MIT"
] | 14 | 2021-08-22T18:21:14.000Z | 2022-03-08T12:04:23.000Z | Sid's Levels/Level - 2/Matrix/MedianInRowSortedMatrix.cpp | Tiger-Team-01/DSA-A-Z-Practice | e08284ffdb1409c08158dd4e90dc75dc3a3c5b18 | [
"MIT"
] | 1 | 2021-10-17T18:47:17.000Z | 2021-10-17T18:47:17.000Z | Sid's Levels/Level - 2/Matrix/MedianInRowSortedMatrix.cpp | Tiger-Team-01/DSA-A-Z-Practice | e08284ffdb1409c08158dd4e90dc75dc3a3c5b18 | [
"MIT"
] | 5 | 2021-09-01T08:21:12.000Z | 2022-03-09T12:13:39.000Z | // { Driver Code Starts
//Initial template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function template for C++
class Solution{
public:
//OM GAN GANAPATHAYE NAMO NAMAH
//JAI SHRI RAM
//JAI BAJRANGBALI
//AMME NARAYANA, DEVI NARAYANA, LAKSHMI NARAYANA, BHADRE NARAYANA
int median(vector<vector<int>> &a, int r, int c){
//we need to find the min and max element
int min = INT_MAX;
int max = INT_MIN;
for(int i = 0; i < r; i++)
{
if(a[i][0] < min)
min = a[i][0];
if(a[i][c-1] > max)
max = a[i][c-1];
}
int desired = (r*c + 1)/2;
while(min < max)
{
int place = 0;
int mid = (min + max)/2;
for(int i = 0; i < r; i++)
{
place += upper_bound(a[i].begin(), a[i].end(), mid) - a[i].begin();
}
if(place < desired)
min = mid + 1;
else
max = mid;
}
return min;
}
};
// { Driver Code Starts.
int main()
{
int t;
cin>>t;
while(t--)
{
int r, c;
cin>>r>>c;
vector<vector<int>> matrix(r, vector<int>(c));
for(int i=0;i<r;++i)
for(int j=0;j<c;++j)
cin>>matrix[i][j];
Solution obj;
cout<<obj.median(matrix, r, c)<<endl;
}
return 0;
} // } Driver Code Ends
| 21.536232 | 83 | 0.446164 | Tiger-Team-01 |
4d37043ea5d0e06ef78be33c6c267f27286a6ca8 | 6,383 | cpp | C++ | src/obproxy/prometheus/ob_prometheus_convert.cpp | stutiredboy/obproxy | b5f98a6e1c45e6a878376df49b9c10b4249d3626 | [
"Apache-2.0"
] | 74 | 2021-05-31T15:23:49.000Z | 2022-03-12T04:46:39.000Z | src/obproxy/prometheus/ob_prometheus_convert.cpp | stutiredboy/obproxy | b5f98a6e1c45e6a878376df49b9c10b4249d3626 | [
"Apache-2.0"
] | 16 | 2021-05-31T15:26:38.000Z | 2022-03-30T06:02:43.000Z | src/obproxy/prometheus/ob_prometheus_convert.cpp | stutiredboy/obproxy | b5f98a6e1c45e6a878376df49b9c10b4249d3626 | [
"Apache-2.0"
] | 64 | 2021-05-31T15:25:36.000Z | 2022-02-23T08:43:58.000Z | /**
* Copyright (c) 2021 OceanBase
* OceanBase Database Proxy(ODP) is licensed under Mulan PubL v2.
* You can use this software according to the terms and conditions of the Mulan PubL v2.
* You may obtain a copy of Mulan PubL v2 at:
* http://license.coscl.org.cn/MulanPubL-2.0
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PubL v2 for more details.
*/
#define USING_LOG_PREFIX PROXY
#include "prometheus/ob_prometheus_convert.h"
#include "prometheus/ob_prometheus_exporter.h"
using namespace prometheus;
using namespace oceanbase::common;
namespace oceanbase
{
namespace obproxy
{
namespace prometheus
{
void ObProxyPrometheusConvert::build_label_map(std::map<std::string, std::string>& label_map,
const ObVector<ObPrometheusLabel> &label_array)
{
for (int i = 0; i< label_array.size(); i++) {
ObPrometheusLabel &label = label_array[i];
std::string key(label.get_key().ptr(), label.get_key().length());
std::string value(label.get_value().ptr(), label.get_value().length());
label_map.insert(std::pair<std::string, std::string>(key, value));
}
}
int ObProxyPrometheusConvert::get_or_create_exporter_family(const ObString &name, const ObString &help,
const ObVector<ObPrometheusLabel> &constant_label_array,
const ObPrometheusMetricType metric_type, void *&family)
{
int ret = OB_SUCCESS;
std::string name_str(name.ptr(), name.length());
std::string help_str(help.ptr(), help.length());
std::map<std::string, std::string> constant_label_map;
build_label_map(constant_label_map, constant_label_array);
switch (metric_type) {
case PROMETHEUS_TYPE_COUNTER:
ret = get_obproxy_prometheus_exporter().get_or_create_counter_family(name_str, help_str, constant_label_map, family);
break;
case PROMETHEUS_TYPE_GAUGE:
ret = get_obproxy_prometheus_exporter().get_or_create_gauge_family(name_str, help_str, constant_label_map, family);
break;
case PROMETHEUS_TYPE_HISTOGRAM:
ret = get_obproxy_prometheus_exporter().get_or_create_histogram_family(name_str, help_str, constant_label_map, family);
break;
default:
break;
}
if (OB_FAIL(ret)) {
LOG_WARN("fail to get or create faimyl", K(name), K(metric_type), K(ret));
}
return ret;
}
int ObProxyPrometheusConvert::create_counter_metric(void *family,
const ObVector<ObPrometheusLabel> &label_array,
void *&metric)
{
int ret = OB_SUCCESS;
std::map<std::string, std::string> label_map;
build_label_map(label_map, label_array);
if (OB_FAIL(get_obproxy_prometheus_exporter().create_metric<Counter>(family, label_map, metric))) {
LOG_WARN("fail to create metric", KP(family), K(label_array), K(ret));
}
return ret;
}
int ObProxyPrometheusConvert::create_gauge_metric(void *family,
const ObVector<ObPrometheusLabel> &label_array,
void *&metric)
{
int ret = OB_SUCCESS;
std::map<std::string, std::string> label_map;
build_label_map(label_map, label_array);
if (OB_FAIL(get_obproxy_prometheus_exporter().create_metric<Gauge>(family, label_map, metric))) {
LOG_WARN("fail to create metric", KP(family), K(label_array), K(ret));
}
return ret;
}
int ObProxyPrometheusConvert::create_histogram_metric(void *family,
const ObVector<ObPrometheusLabel> &label_array,
const ObSortedVector<int64_t> &ob_bucket_boundaries,
void *&metric)
{
int ret = OB_SUCCESS;
std::map<std::string, std::string> label_map;
build_label_map(label_map, label_array);
std::vector<double> bucket_boundaries;
for (int i = 0; i< ob_bucket_boundaries.size(); i++) {
bucket_boundaries.push_back(static_cast<double>(ob_bucket_boundaries[i]));
}
if (OB_FAIL(get_obproxy_prometheus_exporter().create_metric<Histogram>(family, label_map, metric, bucket_boundaries))) {
LOG_WARN("fail to create metric", KP(family), K(label_array), K(ret));
}
return ret;
}
int ObProxyPrometheusConvert::remove_metric(void* family, void* metric,
const ObPrometheusMetricType metric_type)
{
int ret = OB_SUCCESS;
switch (metric_type) {
case PROMETHEUS_TYPE_COUNTER:
ret = get_obproxy_prometheus_exporter().remove_metric<Counter>(family, metric);
break;
case PROMETHEUS_TYPE_GAUGE:
ret = get_obproxy_prometheus_exporter().remove_metric<Gauge>(family, metric);
break;
case PROMETHEUS_TYPE_HISTOGRAM:
ret = get_obproxy_prometheus_exporter().remove_metric<Histogram>(family, metric);
break;
default:
break;
}
if (OB_FAIL(ret)) {
LOG_WARN("fail to remove metric", KP(family), KP(metric), K(metric_type), K(ret));
}
return ret;
}
int ObProxyPrometheusConvert::handle_counter(void *metric, const int64_t value)
{
return get_obproxy_prometheus_exporter().handle_counter(metric, static_cast<double>(value));
}
int ObProxyPrometheusConvert::handle_gauge(void *metric, const double value)
{
return get_obproxy_prometheus_exporter().handle_gauge(metric, value);
}
int ObProxyPrometheusConvert::handle_gauge(void *metric, const int64_t value)
{
return get_obproxy_prometheus_exporter().handle_gauge(metric, static_cast<double>(value));
}
int ObProxyPrometheusConvert::handle_histogram(void *metric, const int64_t sum,
const ObVector<int64_t> &ob_bucket_counts)
{
std::vector<double> bucket_counts;
for (int i = 0; i< ob_bucket_counts.size(); i++) {
bucket_counts.push_back(static_cast<double>(ob_bucket_counts[i]));
}
return get_obproxy_prometheus_exporter().handle_histogram(metric, static_cast<double>(sum), bucket_counts);
}
} // end of namespace prometheus
} // end of namespace obproxy
} // end of namespace oceanbase
| 35.265193 | 125 | 0.674448 | stutiredboy |
4d385212911a25588c981d9a91d6b2406b043228 | 2,757 | hpp | C++ | gloom/src/scene_graph/util.hpp | Stektpotet/gloom | fcb6e031d573be029dd829d8e4fc0a97feb22687 | [
"MIT"
] | null | null | null | gloom/src/scene_graph/util.hpp | Stektpotet/gloom | fcb6e031d573be029dd829d8e4fc0a97feb22687 | [
"MIT"
] | null | null | null | gloom/src/scene_graph/util.hpp | Stektpotet/gloom | fcb6e031d573be029dd829d8e4fc0a97feb22687 | [
"MIT"
] | null | null | null | #pragma once
#include "../mesh.hpp"
#include "SceneNode.hpp"
// Creates an empty SceneNode instance.
template<typename TNode, typename... Args>
TNode* createSceneNode(Args... ctorArgs) {
return new TNode(std::forward<Args>(ctorArgs)...);
}
// Transfer the mesh to the GPU
template<typename TNode>
void TransferMesh(Mesh& mesh, TNode* node)
{
node->vertexArray.bind();
GLuint
positionsByteSize = static_cast<GLuint>(mesh.vertices.size() * sizeof(float)),
normalsByteSize = static_cast<GLuint>(mesh.normals.size() * sizeof(float)),
colorsByteSize = static_cast<GLuint>(mesh.colours.size() * sizeof(float));
VertexBuffer vbo = { //create a vbo with enough space for all the attributes
static_cast<GLsizeiptr>(positionsByteSize + normalsByteSize + colorsByteSize)
};
vbo.update( //upload the positional data
0, positionsByteSize, mesh.vertices.data()
);
vbo.update( //upload the normal data
positionsByteSize, normalsByteSize, mesh.normals.data()
);
vbo.update( //upload the color data
positionsByteSize + normalsByteSize, colorsByteSize, mesh.colours.data()
);
IndexBuffer<unsigned int> ibo = {
static_cast<GLsizeiptr>(mesh.indices.size()), mesh.indices.data()
};
ContinuousVertexLayout{ //Attribute layout descriptor
// name, size, components, internal type, normalized
{"position", positionsByteSize, 3, GL_FLOAT, GL_FALSE},
{"normal", normalsByteSize, 3, GL_FLOAT, GL_TRUE},
{"color", colorsByteSize, 4, GL_FLOAT, GL_TRUE},
}.applyToBuffer(vbo); //Activate the given attributes
node->VAOIndexCount = mesh.indices.size();
}
void updateTransforms(SceneNode* node, glm::mat4 transformationThusFar = glm::mat4(1))
{
// Do transformation computations here
glm::mat4 model = glm::translate(glm::mat4(1),node->referencePoint); //move to reference point
model = glm::rotate(model, node->rotation.x, { 1, 0, 0 }); //Rotate relative to referencePoint
model = glm::rotate(model, node->rotation.y, { 0, 1, 0 });
model = glm::rotate(model, node->rotation.z, { 0, 0, 1 });
model = glm::translate(model, -(node->referencePoint)); //move back into model space
model = glm::translate(node->position) * model;
node->matTRS = transformationThusFar * model;
//model = glm::translate(model, node->position); //Translate relative to referencePoint
// Store matrix in the node's currentTransformationMatrix here
//node->matTRS = transformationThusFar * model;
for (const auto& child : node->children)
updateTransforms(child, node->matTRS);
}
| 39.385714 | 109 | 0.657236 | Stektpotet |
4d3a2e90b6bae0a4adfb57f1a0910c6bfaf45ac2 | 3,229 | cpp | C++ | code/engine.vc2008/xrGame/MosquitoBald.cpp | ipl-adm/xray-oxygen | 3ae4d4911f5b000e93bdf108eb68db25315b2fc6 | [
"Apache-2.0"
] | 1 | 2021-06-15T13:04:36.000Z | 2021-06-15T13:04:36.000Z | code/engine.vc2008/xrGame/MosquitoBald.cpp | ipl-adm/xray-oxygen | 3ae4d4911f5b000e93bdf108eb68db25315b2fc6 | [
"Apache-2.0"
] | null | null | null | code/engine.vc2008/xrGame/MosquitoBald.cpp | ipl-adm/xray-oxygen | 3ae4d4911f5b000e93bdf108eb68db25315b2fc6 | [
"Apache-2.0"
] | null | null | null | #include "stdafx.h"
#include "mosquitobald.h"
#include "../xrParticles/psystem.h"
#include "../xrParticles/ParticlesObject.h"
#include "level.h"
#include "physicsshellholder.h"
#include "../xrengine/xr_collide_form.h"
CMosquitoBald::CMosquitoBald(void)
{
m_fHitImpulseScale = 1.f;
m_bLastBlowoutUpdate = false;
}
CMosquitoBald::~CMosquitoBald(void)
{
}
void CMosquitoBald::Load(LPCSTR section)
{
inherited::Load(section);
}
bool CMosquitoBald::BlowoutState()
{
bool result = inherited::BlowoutState();
if(!result)
{
m_bLastBlowoutUpdate = false;
UpdateBlowout();
}
else if(!m_bLastBlowoutUpdate)
{
m_bLastBlowoutUpdate = true;
UpdateBlowout();
}
return result;
}
void CMosquitoBald::Affect(SZoneObjectInfo* O)
{
CPhysicsShellHolder *pGameObject = smart_cast<CPhysicsShellHolder*>(O->object);
if(!pGameObject) return;
if(O->zone_ignore) return;
Fvector P;
XFORM().transform_tiny(P,CFORM()->getSphere().P);
Fvector hit_dir;
hit_dir.set( ::Random.randF(-.5f,.5f),
::Random.randF(.0f,1.f),
::Random.randF(-.5f,.5f));
hit_dir.normalize();
Fvector position_in_bone_space;
VERIFY(!pGameObject->getDestroy());
float dist = pGameObject->Position().distance_to(P) - pGameObject->Radius();
float power = Power(dist>0.f?dist:0.f, Radius());
float impulse = m_fHitImpulseScale*power*pGameObject->GetMass();
if(power > 0.01f)
{
position_in_bone_space.set(0.f,0.f,0.f);
CreateHit(pGameObject->ID(),ID(),hit_dir,power,0,position_in_bone_space,impulse,m_eHitTypeBlowout);
PlayHitParticles(pGameObject);
}
}
void CMosquitoBald::UpdateSecondaryHit()
{
if(m_dwAffectFrameNum == Device.dwFrame)
return;
m_dwAffectFrameNum = Device.dwFrame;
if(Device.dwPrecacheFrame)
return;
for(auto it: m_ObjectInfoMap)
{
if(!it.object->getDestroy())
{
CPhysicsShellHolder *pGameObject = smart_cast<CPhysicsShellHolder*>((&it)->object);
if(!pGameObject) return;
if((&it)->zone_ignore) return;
Fvector P;
XFORM().transform_tiny(P,CFORM()->getSphere().P);
Fvector hit_dir;
hit_dir.set(::Random.randF(-.5f,.5f), ::Random.randF(.0f,1.f), ::Random.randF(-.5f,.5f));
hit_dir.normalize();
Fvector position_in_bone_space;
VERIFY(!pGameObject->getDestroy());
float dist = pGameObject->Position().distance_to(P) - pGameObject->Radius();
float power = m_fSecondaryHitPower * RelativePower(dist>0.f?dist:0.f, Radius());
if(power<0.0f)
return;
float impulse = m_fHitImpulseScale*power*pGameObject->GetMass();
position_in_bone_space.set(0.f,0.f,0.f);
CreateHit(pGameObject->ID(),ID(),hit_dir,power,0,position_in_bone_space,impulse,m_eHitTypeBlowout);
}
}
}
#include "ZoneCampfire.h"
#include "TorridZone.h"
using namespace luabind;
#pragma optimize("s",on)
void CMosquitoBald::script_register (lua_State *L)
{
module(L)
[
class_<CTorridZone,CGameObject>("CTorridZone")
.def(constructor<>()),
class_<CMosquitoBald,CGameObject>("CMosquitoBald")
.def(constructor<>()),
class_<CZoneCampfire,CGameObject>("CZoneCampfire")
.def(constructor<>())
.def("turn_on", &CZoneCampfire::turn_on_script)
.def("turn_off", &CZoneCampfire::turn_off_script)
.def("is_on", &CZoneCampfire::is_on)
];
}
| 24.097015 | 102 | 0.709508 | ipl-adm |
4d4076d8d6f4bf2200eaeb83026467c1a9a295ed | 2,518 | cpp | C++ | MSP2007/MSP2007Ppg.cpp | jluzardo1971/ActiveGanttVC | 4748cb4d942551dc64c9017f279c90969cdcc634 | [
"MIT"
] | null | null | null | MSP2007/MSP2007Ppg.cpp | jluzardo1971/ActiveGanttVC | 4748cb4d942551dc64c9017f279c90969cdcc634 | [
"MIT"
] | null | null | null | MSP2007/MSP2007Ppg.cpp | jluzardo1971/ActiveGanttVC | 4748cb4d942551dc64c9017f279c90969cdcc634 | [
"MIT"
] | null | null | null | // ----------------------------------------------------------------------------------------
// COPYRIGHT NOTICE
// ----------------------------------------------------------------------------------------
//
// The Source Code Store LLC
// ACTIVEGANTT SCHEDULER COMPONENT FOR C++ - ActiveGanttVC
// ActiveX Control
// Copyright (c) 2002-2017 The Source Code Store LLC
//
// All Rights Reserved. No parts of this file may be reproduced, modified or transmitted
// in any form or by any means without the written permission of the author.
//
// ----------------------------------------------------------------------------------------
#include "stdafx.h"
#include "MSP2007.h"
#include "MSP2007Ppg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
IMPLEMENT_DYNCREATE(CMSP2007PropPage, COlePropertyPage)
/////////////////////////////////////////////////////////////////////////////
// Message map
BEGIN_MESSAGE_MAP(CMSP2007PropPage, COlePropertyPage)
//{{AFX_MSG_MAP(CMSP2007PropPage)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// Initialize class factory and guid
IMPLEMENT_OLECREATE_EX(CMSP2007PropPage, "MSP2007.MSP2007PropPage.1",
0xb00f005e, 0x637c, 0x4bed, 0x8f, 0x10, 0x99, 0x64, 0x71, 0xd2, 0xd9, 0x37)
/////////////////////////////////////////////////////////////////////////////
// CMSP2007PropPage::CMSP2007PropPageFactory::UpdateRegistry -
// Adds or removes system registry entries for CMSP2007PropPage
BOOL CMSP2007PropPage::CMSP2007PropPageFactory::UpdateRegistry(BOOL bRegister)
{
if (bRegister)
return AfxOleRegisterPropertyPageClass(AfxGetInstanceHandle(),
m_clsid, IDS_MSP2007_PPG);
else
return AfxOleUnregisterClass(m_clsid, NULL);
}
/////////////////////////////////////////////////////////////////////////////
// CMSP2007PropPage::CMSP2007PropPage - Constructor
CMSP2007PropPage::CMSP2007PropPage() :
COlePropertyPage(IDD, IDS_MSP2007_PPG_CAPTION)
{
//{{AFX_DATA_INIT(CMSP2007PropPage)
//}}AFX_DATA_INIT
}
/////////////////////////////////////////////////////////////////////////////
// CMSP2007PropPage::DoDataExchange - Moves data between page and properties
void CMSP2007PropPage::DoDataExchange(CDataExchange* pDX)
{
//{{AFX_DATA_MAP(CMSP2007PropPage)
//}}AFX_DATA_MAP
DDP_PostProcessing(pDX);
}
/////////////////////////////////////////////////////////////////////////////
// CMSP2007PropPage message handlers | 31.08642 | 92 | 0.542097 | jluzardo1971 |
4d4145b043ef5da2e8c43bed3e9b748aefd458ec | 3,324 | cc | C++ | hackt_docker/hackt/src/Object/ref/reference_set.cc | broken-wheel/hacktist | 36e832ae7dd38b27bca9be7d0889d06054dc2806 | [
"MIT"
] | null | null | null | hackt_docker/hackt/src/Object/ref/reference_set.cc | broken-wheel/hacktist | 36e832ae7dd38b27bca9be7d0889d06054dc2806 | [
"MIT"
] | null | null | null | hackt_docker/hackt/src/Object/ref/reference_set.cc | broken-wheel/hacktist | 36e832ae7dd38b27bca9be7d0889d06054dc2806 | [
"MIT"
] | null | null | null | /**
\file "Object/ref/reference_set.cc"
$Id: reference_set.cc,v 1.4 2010/04/02 22:18:46 fang Exp $
*/
#include "Object/ref/reference_set.hh"
#include <iostream>
#include <functional>
#include <algorithm>
#include "Object/entry_collection.hh"
#include "Object/traits/instance_traits.hh"
#include "util/iterator_more.hh"
namespace HAC {
namespace entity {
using std::for_each;
using std::mem_fun_ref;
using util::set_inserter;
#include "util/using_ostream.hh"
//=============================================================================
/**
Clears all member sets.
*/
void
global_references_set::clear(void) {
for_each(&ref_bin[0], &ref_bin[MAX], mem_fun_ref(&ref_bin_type::clear));
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/**
\return true if all sub-sets are empty
*/
bool
global_references_set::empty(void) const {
size_t i = 0;
do {
if (!ref_bin[i].empty()) {
return false;
}
++i;
} while (i<MAX);
return true;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/**
Clobbers this set of sets, by taking all sets from the
entry collection parameter.
*/
void
global_references_set::import_entry_collection(const entry_collection& c) {
#define GRAB_SET(Tag) \
ref_bin[class_traits<Tag>::type_tag_enum_value] = \
c.get_index_set<Tag>();
GRAB_SET(bool_tag)
GRAB_SET(int_tag)
GRAB_SET(enum_tag)
GRAB_SET(channel_tag)
GRAB_SET(process_tag)
#undef GRAB_SET
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/**
Insert the set differences into the destination set.
Difference: this set - src set
*/
void
global_references_set::set_difference(const global_references_set& src,
global_references_set& dst) const {
size_t i = 0;
do {
// linear time complexity
std::set_difference(ref_bin[i].begin(), ref_bin[i].end(),
src.ref_bin[i].begin(), src.ref_bin[i].end(),
set_inserter(dst.ref_bin[i]));
++i;
} while (i<MAX);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/**
Insert the set intersections into the destination set.
*/
void
global_references_set::set_intersection(const global_references_set& src,
global_references_set& dst) const {
size_t i = 0;
do {
// linear time complexity
std::set_intersection(ref_bin[i].begin(), ref_bin[i].end(),
src.ref_bin[i].begin(), src.ref_bin[i].end(),
set_inserter(dst.ref_bin[i]));
++i;
} while (i<MAX);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ostream&
global_references_set::dump(ostream& o) const {
typedef ref_bin_type::const_iterator const_iterator;
#define CASE_PRINT_TYPE_TAG_NAME(Tag) \
{ \
const ref_bin_type& \
ub(ref_bin[class_traits<Tag>::type_tag_enum_value]); \
const_iterator i(ub.begin()), e(ub.end()); \
for ( ; i!=e; ++i) { \
o << class_traits<Tag>::tag_name << '[' << *i << "], "; \
} \
}
CASE_PRINT_TYPE_TAG_NAME(bool_tag)
CASE_PRINT_TYPE_TAG_NAME(int_tag)
CASE_PRINT_TYPE_TAG_NAME(enum_tag)
CASE_PRINT_TYPE_TAG_NAME(channel_tag)
CASE_PRINT_TYPE_TAG_NAME(process_tag)
#undef CASE_PRINT_TYPE_TAG_NAME
return o;
}
//=============================================================================
} // end namespace entity
} // end namespace HAC
| 26.592 | 79 | 0.586342 | broken-wheel |